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 |
|---|---|---|---|---|---|---|---|---|---|
Center Google Map Based on geocoded IP | 1,365,722 | <p>Basically whenever someones opens up my (Google) map I want it default to their approximate location.</p>
<p>Is there an easy way to do it with Google's API or do I have to write a custom code (this is python based app)?</p>
| 5 | 2009-09-02T03:38:31Z | 1,367,223 | <p>You can use Google API's built-in <a href="http://code.google.com/apis/ajax/documentation/#ClientLocation">ClientLocation</a> object:</p>
<pre><code>if (GBrowserIsCompatible())
{
var map = new google.maps.Map2(document.getElementById("mapdiv"));
if (google.loader.ClientLocation)
{
var center = new google.maps.LatLng(
google.loader.ClientLocation.latitude,
google.loader.ClientLocation.longitude
);
var zoom = 8;
map.setCenter(center, zoom);
}
}
</code></pre>
| 6 | 2009-09-02T11:46:53Z | [
"javascript",
"python",
"django",
"google-maps"
] |
Center Google Map Based on geocoded IP | 1,365,722 | <p>Basically whenever someones opens up my (Google) map I want it default to their approximate location.</p>
<p>Is there an easy way to do it with Google's API or do I have to write a custom code (this is python based app)?</p>
| 5 | 2009-09-02T03:38:31Z | 6,348,822 | <p>IP Address Geocoding API for Google Maps: <a href="http://web3o.blogspot.com/2011/06/ip-address-geocoding-api-for-google.html" rel="nofollow">http://web3o.blogspot.com/2011/06/ip-address-geocoding-api-for-google.html</a></p>
| 0 | 2011-06-14T19:17:47Z | [
"javascript",
"python",
"django",
"google-maps"
] |
Managing multiple Twisted client connections | 1,365,737 | <p>I'm trying to use Twisted in a sort of spidering program that manages multiple client connections. I'd like to maintain of a pool of about 5 clients working at one time. The functionality of each client is to connect to a specified IRC server that it gets from a list, enter a specific channel, and then save the list of the users in that channel to a database.</p>
<p>The problem I'm having is more architectural than anything. I'm fairly new to Twisted and I don't know what options are available for managing multiple clients. I'm assuming the easiest way is to simply have each ClientCreator instance die off once it's completed its work and have a central loop that can check to see if there's room to add a new client. I would think this isn't a particularly unusual problem so I'm hoping to glean some information from other peoples' experiences. </p>
| 6 | 2009-09-02T03:45:01Z | 1,365,747 | <p>Since each of your clients needs to update a database, instinctively I think I'd piggyback off the <code>connection pool</code> -- see <a href="http://www.rexx.com/~dkuhlman/twisted%5Fpatterns.html#connection-pooling" rel="nofollow">here</a> for more (the whole doc is recommended for some important design patterns that often emerge when using twisted).</p>
| 3 | 2009-09-02T03:49:39Z | [
"python",
"twisted"
] |
Managing multiple Twisted client connections | 1,365,737 | <p>I'm trying to use Twisted in a sort of spidering program that manages multiple client connections. I'd like to maintain of a pool of about 5 clients working at one time. The functionality of each client is to connect to a specified IRC server that it gets from a list, enter a specific channel, and then save the list of the users in that channel to a database.</p>
<p>The problem I'm having is more architectural than anything. I'm fairly new to Twisted and I don't know what options are available for managing multiple clients. I'm assuming the easiest way is to simply have each ClientCreator instance die off once it's completed its work and have a central loop that can check to see if there's room to add a new client. I would think this isn't a particularly unusual problem so I'm hoping to glean some information from other peoples' experiences. </p>
| 6 | 2009-09-02T03:45:01Z | 1,408,498 | <p>The best option is really just to do the obvious thing here. Don't have a loop, or a repeating timed call; just have handlers that do the right thing.</p>
<p>Keep a central connection-management object around, and make event-handling methods feed it the information it needs to keep going. When it starts, make 5 outgoing connections. Keep track of how many are in progress, maintain a list with them in it. When a connection succeeds (in <code>connectionMade</code>) update the list to remember the connection's new state. When a connection completes (in <code>connectionLost</code>) tell the connection manager; its response should be to remove that connection and make a new connection somewhere else. In the middle, it should be fairly obvious how to fire off a request for the names you need and stuff them into a database (waiting for the database insert to complete before dropping your IRC connection, most likely, by waiting for the <code>Deferred</code> to come back from <code>adbapi</code>).</p>
| 4 | 2009-09-11T00:52:04Z | [
"python",
"twisted"
] |
Managing multiple Twisted client connections | 1,365,737 | <p>I'm trying to use Twisted in a sort of spidering program that manages multiple client connections. I'd like to maintain of a pool of about 5 clients working at one time. The functionality of each client is to connect to a specified IRC server that it gets from a list, enter a specific channel, and then save the list of the users in that channel to a database.</p>
<p>The problem I'm having is more architectural than anything. I'm fairly new to Twisted and I don't know what options are available for managing multiple clients. I'm assuming the easiest way is to simply have each ClientCreator instance die off once it's completed its work and have a central loop that can check to see if there's room to add a new client. I would think this isn't a particularly unusual problem so I'm hoping to glean some information from other peoples' experiences. </p>
| 6 | 2009-09-02T03:45:01Z | 5,399,173 | <p>I don't know if you are forced to use Twisted, otherwise you might want to give <a href="http://www.gevent.org/" rel="nofollow">Gevent</a> a try.</p>
| -1 | 2011-03-22T23:34:54Z | [
"python",
"twisted"
] |
Python long filename support broken in Windows | 1,365,797 | <p>I write Python script to copy files; unfortunately it keeps failing because filename is too long(>256). Is there anyway to deal with that problem?</p>
<p>I'm using Python 2.5.4 and Windows XP.</p>
<p>Cheers,</p>
| 3 | 2009-09-02T04:15:52Z | 1,365,807 | <p>Use <a href="http://msdn.microsoft.com/en-us/library/aa365247%28VS.85%29.aspx#maximum%5Fpath%5Flength">paths beginning with the string <code>\\?\</code></a>.</p>
| 6 | 2009-09-02T04:19:51Z | [
"python"
] |
Python long filename support broken in Windows | 1,365,797 | <p>I write Python script to copy files; unfortunately it keeps failing because filename is too long(>256). Is there anyway to deal with that problem?</p>
<p>I'm using Python 2.5.4 and Windows XP.</p>
<p>Cheers,</p>
| 3 | 2009-09-02T04:15:52Z | 1,365,823 | <p>Have you tried the workarounds suggested in <a href="http://mail.python.org/pipermail/python-bugs-list/2007-March/037810.html" rel="nofollow">this</a> old thread, exp. the "magic prefix" trick? I don't know if the underyling issue (that we're not using the right one out of the many available Windows APIs for files) ever got fixed, but the workarounds should work...</p>
| 1 | 2009-09-02T04:23:01Z | [
"python"
] |
Python long filename support broken in Windows | 1,365,797 | <p>I write Python script to copy files; unfortunately it keeps failing because filename is too long(>256). Is there anyway to deal with that problem?</p>
<p>I'm using Python 2.5.4 and Windows XP.</p>
<p>Cheers,</p>
| 3 | 2009-09-02T04:15:52Z | 1,365,827 | <p>In order to use the <code>\\?\</code> prefix (as already proposed), you also need to make sure you use Unicode strings as filenames, not regular (byte) strings.</p>
| 5 | 2009-09-02T04:25:06Z | [
"python"
] |
.NET developer moving to ubuntu for development | 1,365,830 | <p>I've been developing in .NET now for about 3 years. I love the visual studio IDE and sadly I won't be able to use it anymore.</p>
<p>Could someone save me hours of searching the web and reading reviews, and suggest the 'standard' or most popular IDE/Text editor for linux that will get me up and running quickly?</p>
<p>My main goals here are web development backed with Python.</p>
| 3 | 2009-09-02T04:26:23Z | 1,365,838 | <p>First off, if you want to do web with Python, the <a href="http://www.djangoproject.com/" rel="nofollow">Django</a> framework seems like the best choice.</p>
<p>From some quick Googling, the best IDE for Django would be <a href="http://kubasik.net/blog/2009/03/12/finally-a-django-ide-with-real-code-completion-and-template-support/" rel="nofollow">NetBeans with a plugin</a>.</p>
<p>Good luck on learning 'nix development, then!</p>
| 1 | 2009-09-02T04:30:22Z | [
"python",
"ide",
"editor"
] |
.NET developer moving to ubuntu for development | 1,365,830 | <p>I've been developing in .NET now for about 3 years. I love the visual studio IDE and sadly I won't be able to use it anymore.</p>
<p>Could someone save me hours of searching the web and reading reviews, and suggest the 'standard' or most popular IDE/Text editor for linux that will get me up and running quickly?</p>
<p>My main goals here are web development backed with Python.</p>
| 3 | 2009-09-02T04:26:23Z | 1,365,847 | <p>See <a href="http://stackoverflow.com/questions/81584/what-ide-to-use-for-python">this</a> question about Python IDEs.</p>
<p>I use Eclipse + PyDev.</p>
| 2 | 2009-09-02T04:34:41Z | [
"python",
"ide",
"editor"
] |
.NET developer moving to ubuntu for development | 1,365,830 | <p>I've been developing in .NET now for about 3 years. I love the visual studio IDE and sadly I won't be able to use it anymore.</p>
<p>Could someone save me hours of searching the web and reading reviews, and suggest the 'standard' or most popular IDE/Text editor for linux that will get me up and running quickly?</p>
<p>My main goals here are web development backed with Python.</p>
| 3 | 2009-09-02T04:26:23Z | 1,365,849 | <p>I really like gedit and a terminal. You'll more than likely need to make a few <a href="http://grigio.org/textmate%5Fgedit%5Ffew%5Fsteps" rel="nofollow">tweaks</a> and maybe install a plugin or two. gedit also has a Python console window plugin if you like that kind of integration. (Edit -> Preferences -> Plugins, then enable the bottom pane with View -> Bottom Pane)</p>
<p>If you're new to Ubuntu I'd still recommend trying a few different tools before you get settled. The impression I get is that text editors are more commonplace than full blown IDEs on Linux. I tried a few IDEs on Ubuntu and it just didn't seem right - gedit is lightweight and I actually enjoy using it more than Textmate on OS X.</p>
| 0 | 2009-09-02T04:35:50Z | [
"python",
"ide",
"editor"
] |
.NET developer moving to ubuntu for development | 1,365,830 | <p>I've been developing in .NET now for about 3 years. I love the visual studio IDE and sadly I won't be able to use it anymore.</p>
<p>Could someone save me hours of searching the web and reading reviews, and suggest the 'standard' or most popular IDE/Text editor for linux that will get me up and running quickly?</p>
<p>My main goals here are web development backed with Python.</p>
| 3 | 2009-09-02T04:26:23Z | 1,365,852 | <p>If you are willing to pay Wing IDE (<a href="http://www.wingware.com/" rel="nofollow">http://www.wingware.com/</a>) is the best (IMO)
They have trial versions and a basic version free (<a href="https://wingware.com/wing101" rel="nofollow">https://wingware.com/wing101</a>)</p>
| 0 | 2009-09-02T04:36:30Z | [
"python",
"ide",
"editor"
] |
.NET developer moving to ubuntu for development | 1,365,830 | <p>I've been developing in .NET now for about 3 years. I love the visual studio IDE and sadly I won't be able to use it anymore.</p>
<p>Could someone save me hours of searching the web and reading reviews, and suggest the 'standard' or most popular IDE/Text editor for linux that will get me up and running quickly?</p>
<p>My main goals here are web development backed with Python.</p>
| 3 | 2009-09-02T04:26:23Z | 1,365,860 | <p>Consider <a href="http://www.wingware.com/doc/howtos/django" rel="nofollow">Wing IDE</a> -- IMHO the best commercial IDE for Python, it does support Django if that's what you want (as, apparently, do 80% of Python-based websites; personally, I prefer <a href="http://werkzeug.pocoo.org/" rel="nofollow">werkzeug</a> and the like, but maybe that's partly because my "web apps" tend to be more like "web services", with most all the UI/views parts done in HTML/CSS/Dojo;-).</p>
<p>Me, I use <a href="http://www.sontek.net/post/Python-with-a-modular-IDE-%28Vim%29.aspx" rel="nofollow">Vim</a> (usually in the gvim incarnation) as my "Python IDE" (and I've seen Emacs-using colleagues do at-least-equivalent wizardry, but I just can't get used to Emacs myself!-)... but I have to admit that a Wing IDE expect, particularly if faced with a thorny debug scenario, can do circles around me (and even around the Emacsers). ((So why haven't I made the effort to switch? Maybe because, thanks to fanatical testing, I now face thorny debug scenarios too rarely to make me an expert in any new tool!-)) ((Or maybe because my fingers, having learned vi 30+ years ago, would HATE me if I switched to ANYTHING else;-)).</p>
| 3 | 2009-09-02T04:41:42Z | [
"python",
"ide",
"editor"
] |
.NET developer moving to ubuntu for development | 1,365,830 | <p>I've been developing in .NET now for about 3 years. I love the visual studio IDE and sadly I won't be able to use it anymore.</p>
<p>Could someone save me hours of searching the web and reading reviews, and suggest the 'standard' or most popular IDE/Text editor for linux that will get me up and running quickly?</p>
<p>My main goals here are web development backed with Python.</p>
| 3 | 2009-09-02T04:26:23Z | 1,365,891 | <p><strong><a href="http://monodevelop.com/" rel="nofollow">Mono Develop</a></strong></p>
<p>If you've been using visual studio, then I'd guess that mono develop would be the closest thing. As far as I know, its the best attempt around to be a linux version of visual studio. A quick Google search gives several results for python plugins for mono develop.</p>
| 0 | 2009-09-02T04:56:09Z | [
"python",
"ide",
"editor"
] |
.NET developer moving to ubuntu for development | 1,365,830 | <p>I've been developing in .NET now for about 3 years. I love the visual studio IDE and sadly I won't be able to use it anymore.</p>
<p>Could someone save me hours of searching the web and reading reviews, and suggest the 'standard' or most popular IDE/Text editor for linux that will get me up and running quickly?</p>
<p>My main goals here are web development backed with Python.</p>
| 3 | 2009-09-02T04:26:23Z | 29,961,165 | <p>You can still develop .NET on linux.<br>
Microsoft's <a href="https://code.visualstudio.com" rel="nofollow">Visual Studio Code</a> is an Integrated Development Environment (IDE) with support for Mac, Linux and Windows.</p>
| 1 | 2015-04-30T07:06:26Z | [
"python",
"ide",
"editor"
] |
Diff django model objects with ManyToMany fields | 1,365,963 | <p>I have a situation where I need to notify some users when something in DB changes. My idea is to catch <code>pre_save</code> and <code>post_save</code> signal and make some kind of diff and mail that. Generally it works good, but I don't know how to get diff for m2m fields. </p>
<p>At the moment I have something like this:</p>
<pre><code>def pre_save(sender, **kwargs):
pk = kwargs['instance'].pk
instance = copy.deepcopy(sender.objects.get(pk=pk))
tracking[sender] = instance
def post_save(sender, **kwargs):
instance = copy.deepcopy(kwargs['instance'])
print diff(instance, (tracking[sender])) # TODO: don't print, save diff somewhere
</code></pre>
<p>Diff function should work for every model (at the mommet I have four model classes). With deepcopy I can save old model, but I don't know how to save m2m fields because they are in separate table (yes, I know I can get this data, but at the momment of execution I don't know what fields are m2m and I wouldn't like to create different slot for every model). What I would like is generic solution, so I can just add models later without thinking about notification part. </p>
<p>My plan is to call <code>get_data()</code> and <code>clear_data()</code> functions after <code>save()</code> in view to clean diff that slots have generated.</p>
<p>Is this good way of doing this? Is there a better way? Is there django application that can do this job for me?</p>
<p>Excuse my English, it's not my native language.</p>
| 1 | 2009-09-02T05:26:41Z | 1,367,520 | <p>First of all, you don't need to use deepcopy for this. Re-querying the sender from the database returns a "fresh" object.</p>
<pre><code>def pre_save(sender, **kwargs):
pk = kwargs['instance'].pk
instance = sender.objects.get(pk=pk)
tracking[sender] = instance
</code></pre>
<p>You can get a list of all the many-to-many fields for a class, and check the values related to the current instance:</p>
<pre><code>for field in sender._meta.local_many:
values = field.value_from_object(instance).objects.all()
# Now values is a list of related objects, which you can diff
</code></pre>
| 6 | 2009-09-02T12:51:15Z | [
"python",
"django",
"diff",
"models"
] |
random.choice not random | 1,366,047 | <p>I'm using Python 2.5 on Linux, in multiple parallel FCGI processes. I use</p>
<pre><code> chars = string.ascii_letters + string.digits
cookie = ''.join([random.choice(chars) for x in range(32)])
</code></pre>
<p>to generate distinct cookies. Assuming that the RNG is seeded from /dev/urandom, and that the sequence of random numbers comes from the Mersenne twister, I would expect that there is practically zero chance of collision.</p>
<p>However, I do see regular collisions, even though only a few (<100) users are logged in at any time.</p>
<p>Why are the random numbers not more random?</p>
| 13 | 2009-09-02T06:06:22Z | 1,366,192 | <p>To avoid the problem, you can use a sequence of cookies, that are guaranteed to be different (you can e.g. use a set). Each time you give a cookie to someone, you take it from the sequence and you add another to it. Another option is to generate a UUID and use that as a cookie.</p>
<p>Another way to avoid the problem could be to hold a private key, and use a (e.g. MD5) checksum of the private key, with a counter value joined to it. The probability for collisions will then be very low. To be safer, add a few more variables to the checksum, like the current time, the ip address of the user, ...</p>
<p>Libraries to generate cookies exist. Any WSGI implementation probably contains a cookie generator.</p>
<p>If you're only interested in how random your strings are, you could generate a file with, say, one million cookies and perform randomness checks on that file. This, however, is not what I would recommend.</p>
| -4 | 2009-09-02T06:59:59Z | [
"python",
"random"
] |
random.choice not random | 1,366,047 | <p>I'm using Python 2.5 on Linux, in multiple parallel FCGI processes. I use</p>
<pre><code> chars = string.ascii_letters + string.digits
cookie = ''.join([random.choice(chars) for x in range(32)])
</code></pre>
<p>to generate distinct cookies. Assuming that the RNG is seeded from /dev/urandom, and that the sequence of random numbers comes from the Mersenne twister, I would expect that there is practically zero chance of collision.</p>
<p>However, I do see regular collisions, even though only a few (<100) users are logged in at any time.</p>
<p>Why are the random numbers not more random?</p>
| 13 | 2009-09-02T06:06:22Z | 1,366,234 | <p>It shouldn't be generating duplicates.</p>
<pre><code>import random
chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
def gen():
return ''.join([random.choice(chars) for x in range(32)])
test = [gen() for i in range(100000)]
print len(test), len(set(test)) # 100000 100000
</code></pre>
<p>The chances of duplicates is significant with chars = "ab"; 126 duplicates in 1000000 iterations. It's nonexistant with 62.</p>
<p>That said, this isn't a good way to generate cookies, because session cookies need to be unpredictable, to avoid attacks involving stealing other people's session cookies. The Mersenne Twister is not designed for generating secure random numbers. This is what I do:</p>
<pre><code>import os, hashlib
def gen():
return hashlib.sha1(os.urandom(512)).hexdigest()
test = [gen() for i in range(100000)]
print len(test), len(set(test))
</code></pre>
<p>... which should be very secure (which is to say, difficult to take a string of session cookies and guess other existing session cookies from them).</p>
| 12 | 2009-09-02T07:11:52Z | [
"python",
"random"
] |
random.choice not random | 1,366,047 | <p>I'm using Python 2.5 on Linux, in multiple parallel FCGI processes. I use</p>
<pre><code> chars = string.ascii_letters + string.digits
cookie = ''.join([random.choice(chars) for x in range(32)])
</code></pre>
<p>to generate distinct cookies. Assuming that the RNG is seeded from /dev/urandom, and that the sequence of random numbers comes from the Mersenne twister, I would expect that there is practically zero chance of collision.</p>
<p>However, I do see regular collisions, even though only a few (<100) users are logged in at any time.</p>
<p>Why are the random numbers not more random?</p>
| 13 | 2009-09-02T06:06:22Z | 1,366,249 | <p>This is definitely not a normal collision scenario:</p>
<ul>
<li>32 characters with 62 options per character is equivalent to 190 bits (log2(62) * 32)</li>
<li>According to the birthday paradox, you should be receiving a collision naturally once every 2**95 cookies, which means never</li>
</ul>
<p>Could this be a concurrency issue?</p>
<ul>
<li>If so, use different <code>random.Random</code> instances for each thread</li>
<li>Can save these instances in thread-local storage (<code>threading.local()</code>)</li>
<li>On linux, Python should seed them using <code>os.urandom()</code> - not system time - so you should get different streams for each thread.</li>
</ul>
| 3 | 2009-09-02T07:17:25Z | [
"python",
"random"
] |
random.choice not random | 1,366,047 | <p>I'm using Python 2.5 on Linux, in multiple parallel FCGI processes. I use</p>
<pre><code> chars = string.ascii_letters + string.digits
cookie = ''.join([random.choice(chars) for x in range(32)])
</code></pre>
<p>to generate distinct cookies. Assuming that the RNG is seeded from /dev/urandom, and that the sequence of random numbers comes from the Mersenne twister, I would expect that there is practically zero chance of collision.</p>
<p>However, I do see regular collisions, even though only a few (<100) users are logged in at any time.</p>
<p>Why are the random numbers not more random?</p>
| 13 | 2009-09-02T06:06:22Z | 1,366,286 | <p>I had to erase my original answer, which suggested that generator is not seeded from <code>/dev/urandom</code>, since its <a href="http://svn.python.org/projects/python/branches/py3k/Lib/random.py" rel="nofollow">source</a> (for Python 3.x) clearly says that it is:</p>
<pre><code>def seed(self, a=None):
"""Initialize internal state from hashable object.
None or no argument seeds from current time or from an operating
system specific randomness source if available.
If a is not None or an int or long, hash(a) is used instead.
"""
if a is None:
try:
a = int(_hexlify(_urandom(16)), 16)
except NotImplementedError:
import time
a = int(time.time() * 256) # use fractional seconds
super().seed(a)
self.gauss_next = None
</code></pre>
<p>I therefore humbly accept that there are mysteries in the world that I may not be able to decipher.</p>
| 0 | 2009-09-02T07:30:57Z | [
"python",
"random"
] |
random.choice not random | 1,366,047 | <p>I'm using Python 2.5 on Linux, in multiple parallel FCGI processes. I use</p>
<pre><code> chars = string.ascii_letters + string.digits
cookie = ''.join([random.choice(chars) for x in range(32)])
</code></pre>
<p>to generate distinct cookies. Assuming that the RNG is seeded from /dev/urandom, and that the sequence of random numbers comes from the Mersenne twister, I would expect that there is practically zero chance of collision.</p>
<p>However, I do see regular collisions, even though only a few (<100) users are logged in at any time.</p>
<p>Why are the random numbers not more random?</p>
| 13 | 2009-09-02T06:06:22Z | 1,370,961 | <ol>
<li><p>I don't know how your FCGI processes are being spawned, but is it possible that it's using fork() after the Python interpreter has started (and the random module has been imported by something), hence effectively seeding two processes' <code>random._inst</code>s from the same source?</p></li>
<li><p>Maybe put some debugging in to check that it is correctly seeding from urandom, and not falling back to the less rigorous time-based seed?</p></li>
</ol>
<p>eta re comment: man! That's me stumped then; if the RNG always has different state at startup I can't see how you could possibly get collisions. Weird. Would have to put in a lot of state logging to investigate the particular cases which result in collisions, I guess, which sounds like a lot of work trawling through logs. Could it be (1a) the FCGI server usually doesn't fork, but occasionally does (maybe under load, or something)?</p>
<p>Or (3) some higher-level problem such as a broken HTTP proxy passing the same Set-Cookie to multiple clients?</p>
| 1 | 2009-09-03T01:05:05Z | [
"python",
"random"
] |
Django session expiry? | 1,366,146 | <p>From django's documentation, I became under the impression that calling:</p>
<pre><code>request.session.set_expiry(300)
</code></pre>
<p>from one view would cause the session to expire after five minutes <em>inactivity</em>; however, this is not the behavior that I'm experiencing in django trunk. If I call this method from one view, and browse around to other views that don't call the method, the session expires in five minutes. The behavior that I was expecting was a expire only after five minutes of inactivity and not simply failing to call set_expiry again before the expiry.</p>
<p>My question then is do I really need to call set_expiry in every view? If so, does there exist some decorator that may be of assistance? I can't imagine this isn't part of contrib. </p>
<p>Thanks,
Pete</p>
| 11 | 2009-09-02T06:42:14Z | 1,371,117 | <p>As the author of those methods, I can see that the documentation isn't very clear regarding this. Your observations are correct: only requests which cause the session to be altered is considered "activity".</p>
<p>You can use the <a href="http://docs.djangoproject.com/en/dev/topics/http/sessions/#session-save-every-request"><code>SESSION_SAVE_EVERY_REQUEST</code></a> setting to get the behavior you're after (at the obvious cost of the session having to being saved every request).</p>
| 25 | 2009-09-03T02:16:31Z | [
"python",
"django"
] |
Django session expiry? | 1,366,146 | <p>From django's documentation, I became under the impression that calling:</p>
<pre><code>request.session.set_expiry(300)
</code></pre>
<p>from one view would cause the session to expire after five minutes <em>inactivity</em>; however, this is not the behavior that I'm experiencing in django trunk. If I call this method from one view, and browse around to other views that don't call the method, the session expires in five minutes. The behavior that I was expecting was a expire only after five minutes of inactivity and not simply failing to call set_expiry again before the expiry.</p>
<p>My question then is do I really need to call set_expiry in every view? If so, does there exist some decorator that may be of assistance? I can't imagine this isn't part of contrib. </p>
<p>Thanks,
Pete</p>
| 11 | 2009-09-02T06:42:14Z | 13,105,909 | <p>A simple middleware would probably do better than setting this up in every view. This is what I used.</p>
<pre><code>class SessionExpiry(object):
""" Set the session expiry according to settings """
def process_request(self, request):
if getattr(settings, 'SESSION_EXPIRY', None):
request.session.set_expiry(settings.SESSION_EXPIRY)
return None
</code></pre>
<p>This depends on <code>SESSION_EXPIRY</code> being set in your config. It's format is the same as <code>request.session.set_expiry</code>.</p>
<p><code>MIDDLEWARE_CLASSES</code> should be defined with this order in mind:</p>
<pre><code>MIDDLEWARE_CLASSES = (
...
'django.contrib.sessions.middleware.SessionMiddleware',
'<yourproject>.<yourapp>.middleware.SessionExpiry',
...
}
</code></pre>
<p>It'd be nice if <code>django.contrib.sessions</code> took this setting into account by default.</p>
| 3 | 2012-10-28T02:32:23Z | [
"python",
"django"
] |
What would cause a zip file to not be recognized on Google App Engine's when it reads properly in my local GAE sdk | 1,366,274 | <p>My code executes successfully when I run it locally, but when I upload it to GAE and attempt to run it throws me a BadZipfile: File is not a zip file, or ends with a comment</p>
<pre><code>raw_file = urllib2.urlopen(url)
buffer = cStringIO.StringIO(raw_file.read())
z = zipfile.ZipFile(buffer)
</code></pre>
<p>zipped file size is 2.5 mb
unzipped size is 14 mb</p>
<p>What is the difference in the two environments that is causing this error?</p>
| 3 | 2009-09-02T07:25:49Z | 1,366,670 | <p>The maximum size you can fetch using urlfetch (App Engine's API for making HTTP requests to other sites) is 1MB, so your file is getting truncated. The dev_appserver doesn't enforce the 1MB limit.</p>
| 2 | 2009-09-02T09:27:46Z | [
"python",
"google-app-engine",
"zipfile"
] |
Anyone get python26 install in Snow Leopard via Macports? | 1,366,542 | <p>I got build error after run in Snow Leopard (MacPort v.1.8.0)</p>
<pre><code>sudo port install python26
</code></pre>
<p>any workaround please?</p>
<pre><code>Error: Target org.macports.build returned: shell command " cd "/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_ports_lang_python26/work/Python-2.6.2" && /usr/bin/make all MAKE="/usr/bin/make CC=/usr/bin/gcc-4.2" " returned error 2
Command output: if test ""; then \
/usr/bin/gcc-4.2 -o Python.framework/Versions/2.6/Python -dynamiclib \
-isysroot "" \
-all_load libpython2.6.a -Wl,-single_module \
-install_name /opt/local/Library/Frameworks/Python.framework/Versions/2.6/Python \
-compatibility_version 2.6 \
-current_version 2.6; \
else \
/usr/bin/libtool -o Python.framework/Versions/2.6/Python -dynamic libpython2.6.a \
-lSystem -lSystemStubs -arch_only i386 -install_name /opt/local/Library/Frameworks/Python.framework/Versions/2.6/Python -compatibility_version 2.6 -current_version 2.6 ;\
fi
/usr/bin/install -c -d -m 755 \
Python.framework/Versions/2.6/Resources/English.lproj
/usr/bin/install -c -m 644 Mac/Resources/framework/Info.plist \
Python.framework/Versions/2.6/Resources/Info.plist
ln -fsn 2.6 Python.framework/Versions/Current
ln -fsn Versions/Current/Python Python.framework/Python
ln -fsn Versions/Current/Headers Python.framework/Headers
ln -fsn Versions/Current/Resources Python.framework/Resources
/usr/bin/gcc-4.2 -L/opt/local/lib -u _PyMac_Error Python.framework/Versions/2.6/Python -o python.exe \
Modules/python.o \
-ldl
ld: warning: in Python.framework/Versions/2.6/Python, file is not of required architecture
Undefined symbols:
"_PyMac_Error", referenced from:
"_Py_Main", referenced from:
_main in python.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
make: *** [python.exe] Error 1
</code></pre>
| 3 | 2009-09-02T08:54:48Z | 1,366,613 | <p>There are apparently problems with Python via Macports on Snow Leopard, see <a href="http://www.reddit.com/r/Python/comments/9fm2w/snow%5Fleopard%5Fmacports%5Fwarning%5Fpython%5Fports%5Fbroken/" rel="nofollow">this thread</a>. From there, <a href="http://www.reddit.com/r/Python/comments/9fm2w/snow%5Fleopard%5Fmacports%5Fwarning%5Fpython%5Fports%5Fbroken/c0cl7dn" rel="nofollow">here</a>'s an entry suggesting a way to get it working.</p>
| 4 | 2009-09-02T09:13:22Z | [
"python",
"osx-snow-leopard",
"macports"
] |
How to convert tab separated, pipe separated to CSV file format in Python | 1,366,775 | <p>I have a text file (.txt) which could be in tab separated format or pipe separated format, and I need to convert it into CSV file format. I am using python 2.6. Can any one suggest me how to identify the delimiter in a text file, read the data and then convert that into comma separated file.</p>
<p>Thanks in advance</p>
| 4 | 2009-09-02T09:52:09Z | 1,366,827 | <p>Like this</p>
<pre><code>from __future__ import with_statement
import csv
import re
with open( input, "r" ) as source:
with open( output, "wb" ) as destination:
writer= csv.writer( destination )
for line in input:
writer.writerow( re.split( '[\t|]', line ) )
</code></pre>
| 0 | 2009-09-02T10:06:57Z | [
"python",
"csv"
] |
How to convert tab separated, pipe separated to CSV file format in Python | 1,366,775 | <p>I have a text file (.txt) which could be in tab separated format or pipe separated format, and I need to convert it into CSV file format. I am using python 2.6. Can any one suggest me how to identify the delimiter in a text file, read the data and then convert that into comma separated file.</p>
<p>Thanks in advance</p>
| 4 | 2009-09-02T09:52:09Z | 1,366,845 | <pre><code>for line in open("file"):
line=line.strip()
if "|" in line:
print ','.join(line.split("|"))
else:
print ','.join(line.split("\t"))
</code></pre>
| 0 | 2009-09-02T10:11:36Z | [
"python",
"csv"
] |
How to convert tab separated, pipe separated to CSV file format in Python | 1,366,775 | <p>I have a text file (.txt) which could be in tab separated format or pipe separated format, and I need to convert it into CSV file format. I am using python 2.6. Can any one suggest me how to identify the delimiter in a text file, read the data and then convert that into comma separated file.</p>
<p>Thanks in advance</p>
| 4 | 2009-09-02T09:52:09Z | 1,366,894 | <p>I fear that you can't identify the delimiter without knowing what it is. The problem with CSV is, that, <a href="http://catb.org/esr/writings/taoup/html/ch05s02.html#id2901882" rel="nofollow">quoting ESR</a>:</p>
<blockquote>
<p>the Microsoft version of CSV is a textbook example of how not to design a textual file format.</p>
</blockquote>
<p>The delimiter needs to be escaped in some way if it can appear in fields. Without knowing, how the escaping is done, automatically identifying it is difficult. Escaping could be done the UNIX way, using a backslash '\', or the Microsoft way, using quotes which then must be escaped, too. This is not a trivial task.</p>
<p>So my suggestion is to get full documentation from whoever generates the file you want to convert. Then you can use one of the approaches suggested in the other answers or some variant.</p>
<p>Edit:</p>
<p>Python provides <a href="http://docs.python.org/library/csv.html#csv.Sniffer" rel="nofollow">csv.Sniffer</a> that can help you deduce the format of your DSV. If your input looks like this (note the quoted delimiter in the first field of the second row):</p>
<pre><code>a|b|c
"a|b"|c|d
foo|"bar|baz"|qux
</code></pre>
<p>You can do this:</p>
<pre><code>import csv
csvfile = open("csvfile.csv")
dialect = csv.Sniffer().sniff(csvfile.read(1024))
csvfile.seek(0)
reader = csv.DictReader(csvfile, dialect=dialect)
for row in reader:
print row,
# => {'a': 'a|b', 'c': 'd', 'b': 'c'} {'a': 'foo', 'c': 'qux', 'b': 'bar|baz'}
# write records using other dialect
</code></pre>
| 6 | 2009-09-02T10:24:32Z | [
"python",
"csv"
] |
How to convert tab separated, pipe separated to CSV file format in Python | 1,366,775 | <p>I have a text file (.txt) which could be in tab separated format or pipe separated format, and I need to convert it into CSV file format. I am using python 2.6. Can any one suggest me how to identify the delimiter in a text file, read the data and then convert that into comma separated file.</p>
<p>Thanks in advance</p>
| 4 | 2009-09-02T09:52:09Z | 1,366,956 | <p>I would suggest taking some of the example code from the existing answers, or perhaps better use the <code>csv</code> module from python and change it to first assume tab separated, then pipe separated, and produce two output files which are comma separated. Then you visually examine both files to determine which one you want and pick that.</p>
<p>If you actually have lots of files, then you need to try to find a way to detect which file is which.<br />
One of the examples has this:</p>
<pre><code>if "|" in line:
</code></pre>
<p>This may be enough: if the first line of a file contains a pipe, then maybe the whole file is pipe separated, else assume a tab separated file.</p>
<p>Alternatively fix the file to contain a key field in the first line which is easily identified - or maybe the first line contains column headers which can be detected.</p>
| 0 | 2009-09-02T10:41:29Z | [
"python",
"csv"
] |
How to convert tab separated, pipe separated to CSV file format in Python | 1,366,775 | <p>I have a text file (.txt) which could be in tab separated format or pipe separated format, and I need to convert it into CSV file format. I am using python 2.6. Can any one suggest me how to identify the delimiter in a text file, read the data and then convert that into comma separated file.</p>
<p>Thanks in advance</p>
| 4 | 2009-09-02T09:52:09Z | 1,373,954 | <p>Your strategy could be the following:</p>
<ul>
<li>parse the file with BOTH a tab-separated csv reader and a pipe-separated csv reader</li>
<li>calculate some statistics on resulting rows to decide which resultset is the one you want to write. An idea could be counting the total number of fields in the two recordset (expecting that tab and pipe are not so common). Another one (if your data is strongly structured and you expect the same number of fields in each line) could be measuring the standard deviation of number of fields per line and take the record set with the smallest standard deviation.</li>
</ul>
<p>In the following example you find the simpler statistic (total number of fields)</p>
<pre><code>import csv
piperows= []
tabrows = []
#parsing | delimiter
f = open("file", "rb")
readerpipe = csv.reader(f, delimiter = "|")
for row in readerpipe:
piperows.append(row)
f.close()
#parsing TAB delimiter
f = open("file", "rb")
readertab = csv.reader(f, delimiter = "\t")
for row in readerpipe:
tabrows.append(row)
f.close()
#in this example, we use the total number of fields as indicator (but it's not guaranteed to work! it depends by the nature of your data)
#count total fields
totfieldspipe = reduce (lambda x,y: x+ y, [len(f) for f in piperows])
totfieldstab = reduce (lambda x,y: x+ y, [len(f) for f in tabrows])
if totfieldspipe > totfieldstab:
yourrows = piperows
else:
yourrows = tabrows
#the var yourrows contains the rows, now just write them in any format you like
</code></pre>
| 1 | 2009-09-03T14:59:56Z | [
"python",
"csv"
] |
Django: retrieve all galleries containing one public photo at least | 1,366,943 | <p>excuse me for my ugly english) !</p>
<p>Imagine these very simple models :</p>
<pre><code>class Photo(models.Model):
is_public = models.BooleanField('Public', default=False)
class Gallery(models.Model):
photos = models.ManyToManyField('Photos', related_name='galleries', null=True, blank=True)
</code></pre>
<p>I need to select all <code>Gallery</code> instances which contain <em>at least</em> one public photo (and if possible adding a <code>photos__count</code> attribute which contains the number of public photos).</p>
<p>I tried this query :</p>
<pre><code>Gallery.objects.all()\
.annotate(Count('photos'))\
.filter(photos__is_public=True)
</code></pre>
<p>It seems to be okay, but :
- the query is strange
- the added attribute <code>photos__count</code> on each gallery will contain the total number of photos on this gallery, instead of the number of public photos in this gallery.</p>
<p>I thin that the hard-coded sql query I need is that :</p>
<pre><code>SELECT `gallery`.* , COUNT(`gallery_photos`.`photo_id`)
FROM `gallery`
INNER JOIN `gallery_photos` ON (`gallery`.`id` = `gallery_photos`.`gallery_id`)
INNER JOIN `photo` ON (`gallery_photos`.`photo_id` = `photo`.`id`)
WHERE `photo`.`is_public` = True
GROUP BY gallery.id ;
</code></pre>
<p>Any idea to fix it ?</p>
<p>Thank you ! ;-)</p>
| 1 | 2009-09-02T10:38:01Z | 1,367,441 | <p>This should do it:</p>
<p><strong>Edit, updated to add count:</strong></p>
<pre><code>SELECT `gallery`.*, 'a'.'count'
FROM `gallery`
inner join (
select `gallery`.`id`, count(*) as count
from `gallery_photos`
INNER JOIN `photo` ON (`gallery_photos`.`photo_id` = `photo`.`id`)
where `photo`.`is_public` = True
group by `gallery`.`id`
) a on `gallery`.`id` = 'a'.'id'
WHERE `photo`.`is_public` = True
</code></pre>
| 0 | 2009-09-02T12:36:41Z | [
"python",
"sql",
"django",
"django-models",
"count"
] |
Django: retrieve all galleries containing one public photo at least | 1,366,943 | <p>excuse me for my ugly english) !</p>
<p>Imagine these very simple models :</p>
<pre><code>class Photo(models.Model):
is_public = models.BooleanField('Public', default=False)
class Gallery(models.Model):
photos = models.ManyToManyField('Photos', related_name='galleries', null=True, blank=True)
</code></pre>
<p>I need to select all <code>Gallery</code> instances which contain <em>at least</em> one public photo (and if possible adding a <code>photos__count</code> attribute which contains the number of public photos).</p>
<p>I tried this query :</p>
<pre><code>Gallery.objects.all()\
.annotate(Count('photos'))\
.filter(photos__is_public=True)
</code></pre>
<p>It seems to be okay, but :
- the query is strange
- the added attribute <code>photos__count</code> on each gallery will contain the total number of photos on this gallery, instead of the number of public photos in this gallery.</p>
<p>I thin that the hard-coded sql query I need is that :</p>
<pre><code>SELECT `gallery`.* , COUNT(`gallery_photos`.`photo_id`)
FROM `gallery`
INNER JOIN `gallery_photos` ON (`gallery`.`id` = `gallery_photos`.`gallery_id`)
INNER JOIN `photo` ON (`gallery_photos`.`photo_id` = `photo`.`id`)
WHERE `photo`.`is_public` = True
GROUP BY gallery.id ;
</code></pre>
<p>Any idea to fix it ?</p>
<p>Thank you ! ;-)</p>
| 1 | 2009-09-02T10:38:01Z | 1,367,445 | <p>I would try:</p>
<pre><code>Gallery.objects.filter(photos__is_public=True).annotate(Count('photos'))
</code></pre>
<p>I believe you just got your filter ordering wrong but I have not set up your models to test that assumption.</p>
<p>Try number two:</p>
<pre><code>Gallery.objects.exclude(photos__is_public=False).annotate(Count('photos'))
</code></pre>
<p>That should be exclude all galleries where none of the photos are public and return a count of what is and isn't public.</p>
| 0 | 2009-09-02T12:36:56Z | [
"python",
"sql",
"django",
"django-models",
"count"
] |
Django: retrieve all galleries containing one public photo at least | 1,366,943 | <p>excuse me for my ugly english) !</p>
<p>Imagine these very simple models :</p>
<pre><code>class Photo(models.Model):
is_public = models.BooleanField('Public', default=False)
class Gallery(models.Model):
photos = models.ManyToManyField('Photos', related_name='galleries', null=True, blank=True)
</code></pre>
<p>I need to select all <code>Gallery</code> instances which contain <em>at least</em> one public photo (and if possible adding a <code>photos__count</code> attribute which contains the number of public photos).</p>
<p>I tried this query :</p>
<pre><code>Gallery.objects.all()\
.annotate(Count('photos'))\
.filter(photos__is_public=True)
</code></pre>
<p>It seems to be okay, but :
- the query is strange
- the added attribute <code>photos__count</code> on each gallery will contain the total number of photos on this gallery, instead of the number of public photos in this gallery.</p>
<p>I thin that the hard-coded sql query I need is that :</p>
<pre><code>SELECT `gallery`.* , COUNT(`gallery_photos`.`photo_id`)
FROM `gallery`
INNER JOIN `gallery_photos` ON (`gallery`.`id` = `gallery_photos`.`gallery_id`)
INNER JOIN `photo` ON (`gallery_photos`.`photo_id` = `photo`.`id`)
WHERE `photo`.`is_public` = True
GROUP BY gallery.id ;
</code></pre>
<p>Any idea to fix it ?</p>
<p>Thank you ! ;-)</p>
| 1 | 2009-09-02T10:38:01Z | 1,369,274 | <p>This?</p>
<pre>
Gallery.objects.filter(photos__is_public=True)\
.annotate(Count('photos__is_public'))
</pre>
| 0 | 2009-09-02T18:09:02Z | [
"python",
"sql",
"django",
"django-models",
"count"
] |
Django: retrieve all galleries containing one public photo at least | 1,366,943 | <p>excuse me for my ugly english) !</p>
<p>Imagine these very simple models :</p>
<pre><code>class Photo(models.Model):
is_public = models.BooleanField('Public', default=False)
class Gallery(models.Model):
photos = models.ManyToManyField('Photos', related_name='galleries', null=True, blank=True)
</code></pre>
<p>I need to select all <code>Gallery</code> instances which contain <em>at least</em> one public photo (and if possible adding a <code>photos__count</code> attribute which contains the number of public photos).</p>
<p>I tried this query :</p>
<pre><code>Gallery.objects.all()\
.annotate(Count('photos'))\
.filter(photos__is_public=True)
</code></pre>
<p>It seems to be okay, but :
- the query is strange
- the added attribute <code>photos__count</code> on each gallery will contain the total number of photos on this gallery, instead of the number of public photos in this gallery.</p>
<p>I thin that the hard-coded sql query I need is that :</p>
<pre><code>SELECT `gallery`.* , COUNT(`gallery_photos`.`photo_id`)
FROM `gallery`
INNER JOIN `gallery_photos` ON (`gallery`.`id` = `gallery_photos`.`gallery_id`)
INNER JOIN `photo` ON (`gallery_photos`.`photo_id` = `photo`.`id`)
WHERE `photo`.`is_public` = True
GROUP BY gallery.id ;
</code></pre>
<p>Any idea to fix it ?</p>
<p>Thank you ! ;-)</p>
| 1 | 2009-09-02T10:38:01Z | 1,371,865 | <p>The django documentation is at </p>
<p><a href="http://docs.djangoproject.com/en/dev/topics/db/aggregation/#order-of-annotate-and-filter-clauses" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/db/aggregation/#order-of-annotate-and-filter-clauses</a></p>
<p>and my experience says that the following query:</p>
<pre><code>Gallery.objects.filter(photos__is_public=True).annotate(Count('photos'))
</code></pre>
<p>would give you galleries with at least one photo that is public and a count of only photos that are public. The only thing is that it will exclude galleries with zero public photos but it sounds like you don't care about that. Have you tested the above query?</p>
<p>If it still doesn't return the right data then annotate is probably changing the returned data by causing it to return only galleries where all are public. In that case you could use the "extra" method to get the count you want.</p>
<pre><code>Gallery.objects.filter(photos__is_public=True).extra(select={
"photo_count": """
SELECT COUNT(`gallery_photos.id`)
FROM `gallery_photos`
WHERE `gallery_photos.gallery_id` `gallery.id AND
`gallery_photos.is_public = True
"""})
</code></pre>
<p>Jason Christa's exclude method may also work.</p>
| 0 | 2009-09-03T07:18:39Z | [
"python",
"sql",
"django",
"django-models",
"count"
] |
Python (Imaging library): Resample string as argument | 1,367,029 | <p>Python beginner question. Code below should explain my problem:</p>
<pre><code>import Image
resolution = (200,500)
scaler = "Image.ANTIALIAS"
im = Image.open("/home/user/Photos/DSC00320.JPG")
im.resize(resolution , scaler)
</code></pre>
<p>RESULT:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/dist-packages/PIL/Image.py", line 1255, in resize
raise ValueError("unknown resampling filter")
ValueError: unknown resampling filter
</code></pre>
<p>This one works:</p>
<pre><code>im.resize(resolution , Image.ANTIALIAS)
</code></pre>
| 2 | 2009-09-02T11:03:37Z | 1,367,056 | <p>As you said, <code>im.resize(resolution , Image.ANTIALIAS)</code> is the solution</p>
<p>You have to take care than this is different than <code>im.resize(resolution , "Image.ANTIALIAS")</code>.</p>
<p>In your example, the variable <code>scaler</code> has the string <code>"Image.ANTIALIAS"</code> as a value, that is different than the value <code>Image.ANTIALIAS</code>.</p>
<p>A string representing <em>xxxx</em> <strong>is different</strong> than the value <em>xxxx</em>, exactly as the string <code>"12"</code> is completely different than the integer <code>12</code>.</p>
| 2 | 2009-09-02T11:10:16Z | [
"python",
"python-imaging-library"
] |
Python (Imaging library): Resample string as argument | 1,367,029 | <p>Python beginner question. Code below should explain my problem:</p>
<pre><code>import Image
resolution = (200,500)
scaler = "Image.ANTIALIAS"
im = Image.open("/home/user/Photos/DSC00320.JPG")
im.resize(resolution , scaler)
</code></pre>
<p>RESULT:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/dist-packages/PIL/Image.py", line 1255, in resize
raise ValueError("unknown resampling filter")
ValueError: unknown resampling filter
</code></pre>
<p>This one works:</p>
<pre><code>im.resize(resolution , Image.ANTIALIAS)
</code></pre>
| 2 | 2009-09-02T11:03:37Z | 1,367,066 | <p>Well, then Image.ANTIALIAS is not a string, so don't treat it as one:</p>
<pre><code>scaler = Image.ANTIALIAS
</code></pre>
| 7 | 2009-09-02T11:13:50Z | [
"python",
"python-imaging-library"
] |
Python (Imaging library): Resample string as argument | 1,367,029 | <p>Python beginner question. Code below should explain my problem:</p>
<pre><code>import Image
resolution = (200,500)
scaler = "Image.ANTIALIAS"
im = Image.open("/home/user/Photos/DSC00320.JPG")
im.resize(resolution , scaler)
</code></pre>
<p>RESULT:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/dist-packages/PIL/Image.py", line 1255, in resize
raise ValueError("unknown resampling filter")
ValueError: unknown resampling filter
</code></pre>
<p>This one works:</p>
<pre><code>im.resize(resolution , Image.ANTIALIAS)
</code></pre>
| 2 | 2009-09-02T11:03:37Z | 1,367,072 | <p>As @ThibThib said using "Image.ANTIALIAS" is not the same thing as Image.ANTIALIAS.
But if you always expect to get the resample value as a string you could do the following:</p>
<pre><code>scaler = 'ANTIALIAS'
resample = {
'ANTIALIAS': Image.ANTIALIAS,
'BILINEAR': Image.BILINEAR,
'BICUBIC': Image.BICUBIC
}
im.resize(resolution , resample[scaler])
</code></pre>
| 3 | 2009-09-02T11:14:34Z | [
"python",
"python-imaging-library"
] |
How to download a webpage in every five minutes? | 1,367,189 | <p>I want to download a list of web pages. I know wget can do this. However downloading every URL in every five minutes and save them to a folder seems beyond the capability of wget.
Does anyone knows some tools either in java or python or Perl which accomplishes the task?</p>
<p>Thanks in advance.</p>
| 1 | 2009-09-02T11:39:32Z | 1,367,209 | <p>Write a bash script that uses wget and put it in your crontab to run every 5 minutes. (*/5 * * * *)</p>
<p>If you need to keep a history of all these web pages, set a variable at the beginning of your script with the current unixtime and append it to the output filenames.</p>
| 5 | 2009-09-02T11:44:31Z | [
"python",
"download",
"webpage",
"wget",
"web-crawler"
] |
How to download a webpage in every five minutes? | 1,367,189 | <p>I want to download a list of web pages. I know wget can do this. However downloading every URL in every five minutes and save them to a folder seems beyond the capability of wget.
Does anyone knows some tools either in java or python or Perl which accomplishes the task?</p>
<p>Thanks in advance.</p>
| 1 | 2009-09-02T11:39:32Z | 1,367,219 | <p>Sounds like you'd want to <a href="http://www.scrounge.org/linux/cron.html" rel="nofollow">use cron with wget</a>
<hr/>
But if you're set on using python:</p>
<pre><code>import time
import os
wget_command_string = "wget ..."
while true:
os.system(wget_command_string)
time.sleep(5*60)
</code></pre>
| 7 | 2009-09-02T11:45:52Z | [
"python",
"download",
"webpage",
"wget",
"web-crawler"
] |
Python subprocess.Popen "OSError: [Errno 12] Cannot allocate memory" | 1,367,373 | <p><strong>Note:</strong> This question was originally asked <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory">here</a> but the bounty time expired even though an acceptable answer was not actually found. I am re-asking this question including all details provided in the original question.</p>
<p>A python script is running a set of class functions every 60 seconds using the <a href="http://docs.python.org/library/sched.html">sched</a> module:</p>
<pre><code># sc is a sched.scheduler instance
sc.enter(60, 1, self.doChecks, (sc, False))
</code></pre>
<p>The script is running as a daemonised process using the code <a href="http://www.jejik.com/articles/2007/02/a%5Fsimple%5Funix%5Flinux%5Fdaemon%5Fin%5Fpython/">here</a>.</p>
<p>A number of class methods that are called as part of doChecks use the <a href="http://docs.python.org/library/subprocess.html">subprocess</a> module to call system functions in order to get system statistics:</p>
<pre><code>ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]
</code></pre>
<p>This runs fine for a period of time before the entire script crashing with the following error:</p>
<pre><code>File "/home/admin/sd-agent/checks.py", line 436, in getProcesses
File "/usr/lib/python2.4/subprocess.py", line 533, in __init__
File "/usr/lib/python2.4/subprocess.py", line 835, in _get_handles
OSError: [Errno 12] Cannot allocate memory
</code></pre>
<p>The output of free -m on the server once the script has crashed is:</p>
<pre><code>$ free -m
total used free shared buffers cached
Mem: 894 345 549 0 0 0
-/+ buffers/cache: 345 549
Swap: 0 0 0
</code></pre>
<p>The server is running CentOS 5.3. I am unable to reproduce on my own CentOS boxes nor with any other user reporting the same problem.</p>
<p>I have tried a number of things to debug this as suggested in the original question:</p>
<ol>
<li><p>Logging the output of free -m before and after the Popen call. There is no significant change in memory usage i.e. memory is not gradually being used up as the script runs.</p></li>
<li><p>I added close_fds=True to the Popen call but this made no difference - the script still crashed with the same error. Suggested <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory/1297785#1297785">here</a> and <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory/1278961#1278961">here</a>.</p></li>
<li><p>I checked the rlimits which showed (-1, -1) on both RLIMIT_DATA and RLIMIT_AS as suggested <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory/1270442#1270442">here</a>.</p></li>
<li><p><a href="http://www.zenoss.com/community/wiki/common-error-messages-and-solutions/oserror-errno-12-cannot-allocate-memory-in-popen2.py/">An article</a> suggested the having no swap space might be the cause but swap is actually available on demand (according to the web host) and this was also suggested as a bogus cause <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory/1270171#1270171">here</a>.</p></li>
<li><p>The processes are being closed because that is the behaviour of using .communicate() as backed up by the Python source code and comments <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory/1216824#1216824">here</a>.</p></li>
</ol>
<p>The entire checks can be found at on <a href="http://github.com/dmytton/sd-agent/blob/82f5ff9203e54d2adeee8cfed704d09e3f00e8eb/checks.py">GitHub here</a> with the getProcesses function defined from line 442. This is called by doChecks() starting at line 520.</p>
<p>The script was run with strace with the following output before the crash:</p>
<pre><code>recv(4, "Total Accesses: 516662\nTotal kBy"..., 234, 0) = 234
gettimeofday({1250893252, 887805}, NULL) = 0
write(3, "2009-08-21 17:20:52,887 - checks"..., 91) = 91
gettimeofday({1250893252, 888362}, NULL) = 0
write(3, "2009-08-21 17:20:52,888 - checks"..., 74) = 74
gettimeofday({1250893252, 888897}, NULL) = 0
write(3, "2009-08-21 17:20:52,888 - checks"..., 67) = 67
gettimeofday({1250893252, 889184}, NULL) = 0
write(3, "2009-08-21 17:20:52,889 - checks"..., 81) = 81
close(4) = 0
gettimeofday({1250893252, 889591}, NULL) = 0
write(3, "2009-08-21 17:20:52,889 - checks"..., 63) = 63
pipe([4, 5]) = 0
pipe([6, 7]) = 0
fcntl64(7, F_GETFD) = 0
fcntl64(7, F_SETFD, FD_CLOEXEC) = 0
clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0xb7f12708) = -1 ENOMEM (Cannot allocate memory)
write(2, "Traceback (most recent call last"..., 35) = 35
open("/usr/bin/sd-agent/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/bin/sd-agent/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python24.zip/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/plat-linux2/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python2.4/lib-tk/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/lib-dynload/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/site-packages/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
write(2, " File \"/usr/bin/sd-agent/agent."..., 52) = 52
open("/home/admin/sd-agent/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/bin/sd-agent/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python24.zip/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/plat-linux2/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python2.4/lib-tk/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/lib-dynload/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/site-packages/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
write(2, " File \"/home/admin/sd-agent/dae"..., 60) = 60
open("/usr/bin/sd-agent/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/bin/sd-agent/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python24.zip/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/plat-linux2/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python2.4/lib-tk/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/lib-dynload/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/site-packages/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
write(2, " File \"/usr/bin/sd-agent/agent."..., 54) = 54
open("/usr/lib/python2.4/sched.py", O_RDONLY|O_LARGEFILE) = 8
write(2, " File \"/usr/lib/python2.4/sched"..., 55) = 55
fstat64(8, {st_mode=S_IFREG|0644, st_size=4054, ...}) = 0
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7d28000
read(8, "\"\"\"A generally useful event sche"..., 4096) = 4054
write(2, " ", 4) = 4
write(2, "void = action(*argument)\n", 25) = 25
close(8) = 0
munmap(0xb7d28000, 4096) = 0
open("/usr/bin/sd-agent/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/bin/sd-agent/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python24.zip/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/plat-linux2/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python2.4/lib-tk/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/lib-dynload/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/site-packages/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
write(2, " File \"/usr/bin/sd-agent/checks"..., 60) = 60
open("/usr/bin/sd-agent/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/bin/sd-agent/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python24.zip/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/plat-linux2/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python2.4/lib-tk/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/lib-dynload/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/site-packages/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
write(2, " File \"/usr/bin/sd-agent/checks"..., 64) = 64
open("/usr/lib/python2.4/subprocess.py", O_RDONLY|O_LARGEFILE) = 8
write(2, " File \"/usr/lib/python2.4/subpr"..., 65) = 65
fstat64(8, {st_mode=S_IFREG|0644, st_size=39931, ...}) = 0
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7d28000
read(8, "# subprocess - Subprocesses with"..., 4096) = 4096
read(8, "lso, the newlines attribute of t"..., 4096) = 4096
read(8, "code < 0:\n print >>sys.st"..., 4096) = 4096
read(8, "alse does not exist on 2.2.0\ntry"..., 4096) = 4096
read(8, " p2cread\n # c2pread <-"..., 4096) = 4096
write(2, " ", 4) = 4
write(2, "errread, errwrite)\n", 19) = 19
close(8) = 0
munmap(0xb7d28000, 4096) = 0
open("/usr/lib/python2.4/subprocess.py", O_RDONLY|O_LARGEFILE) = 8
write(2, " File \"/usr/lib/python2.4/subpr"..., 71) = 71
fstat64(8, {st_mode=S_IFREG|0644, st_size=39931, ...}) = 0
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7d28000
read(8, "# subprocess - Subprocesses with"..., 4096) = 4096
read(8, "lso, the newlines attribute of t"..., 4096) = 4096
read(8, "code < 0:\n print >>sys.st"..., 4096) = 4096
read(8, "alse does not exist on 2.2.0\ntry"..., 4096) = 4096
read(8, " p2cread\n # c2pread <-"..., 4096) = 4096
read(8, "table(self, handle):\n "..., 4096) = 4096
read(8, "rrno using _sys_errlist (or siml"..., 4096) = 4096
read(8, " p2cwrite = None, None\n "..., 4096) = 4096
write(2, " ", 4) = 4
write(2, "self.pid = os.fork()\n", 21) = 21
close(8) = 0
munmap(0xb7d28000, 4096) = 0
write(2, "OSError", 7) = 7
write(2, ": ", 2) = 2
write(2, "[Errno 12] Cannot allocate memor"..., 33) = 33
write(2, "\n", 1) = 1
unlink("/var/run/sd-agent.pid") = 0
close(3) = 0
munmap(0xb7e0d000, 4096) = 0
rt_sigaction(SIGINT, {SIG_DFL, [], SA_RESTORER, 0x589978}, {0xb89a60, [], SA_RESTORER, 0x589978}, 8) = 0
brk(0xa022000) = 0xa022000
exit_group(1) = ?
</code></pre>
| 62 | 2009-09-02T12:23:43Z | 1,371,363 | <p>swap may not be the red herring previously suggested. How big is the python process in question just before the <code>ENOMEM</code>?</p>
<p>Under kernel 2.6, <code>/proc/sys/vm/swappiness</code> controls how aggressively the kernel will turn to swap, and <code>overcommit*</code> files how much and how precisely the kernel may apportion memory with a wink and a nod. Like your facebook relationship status, <a href="http://www.kernel.org/doc/Documentation/sysctl/vm.txt">it's complicated</a>.</p>
<blockquote>
<p><em>...but swap is actually available on demand (according to the web host)...</em></p>
</blockquote>
<p>but not according to the output of your <code>free(1)</code> command, which shows no swap space recognized by your server instance. Now, your web host may certainly know much more than I about this topic, but virtual RHEL/CentOS systems I've used have reported swap available to the guest OS.</p>
<p>Adapting <a href="http://www.kernel.org/doc/Documentation/sysctl/vm.txt">Red Hat KB Article 15252</a>:</p>
<blockquote>
<p>A Red Hat Enterprise Linux 5 system
will run just fine with no swap space
at all as long as the sum of anonymous
memory and system V shared memory is
less than about 3/4 the amount of RAM.
.... Systems with 4GB of ram or less
<em>[are recommended to have]</em> a minimum of
2GB of swap space.</p>
</blockquote>
<p>Compare your <code>/proc/sys/vm</code> settings to a plain CentOS 5.3 installation. Add a swap file. Ratchet down <code>swappiness</code> and see if you live any longer.</p>
| 8 | 2009-09-03T03:55:58Z | [
"python",
"linux",
"memory"
] |
Python subprocess.Popen "OSError: [Errno 12] Cannot allocate memory" | 1,367,373 | <p><strong>Note:</strong> This question was originally asked <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory">here</a> but the bounty time expired even though an acceptable answer was not actually found. I am re-asking this question including all details provided in the original question.</p>
<p>A python script is running a set of class functions every 60 seconds using the <a href="http://docs.python.org/library/sched.html">sched</a> module:</p>
<pre><code># sc is a sched.scheduler instance
sc.enter(60, 1, self.doChecks, (sc, False))
</code></pre>
<p>The script is running as a daemonised process using the code <a href="http://www.jejik.com/articles/2007/02/a%5Fsimple%5Funix%5Flinux%5Fdaemon%5Fin%5Fpython/">here</a>.</p>
<p>A number of class methods that are called as part of doChecks use the <a href="http://docs.python.org/library/subprocess.html">subprocess</a> module to call system functions in order to get system statistics:</p>
<pre><code>ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]
</code></pre>
<p>This runs fine for a period of time before the entire script crashing with the following error:</p>
<pre><code>File "/home/admin/sd-agent/checks.py", line 436, in getProcesses
File "/usr/lib/python2.4/subprocess.py", line 533, in __init__
File "/usr/lib/python2.4/subprocess.py", line 835, in _get_handles
OSError: [Errno 12] Cannot allocate memory
</code></pre>
<p>The output of free -m on the server once the script has crashed is:</p>
<pre><code>$ free -m
total used free shared buffers cached
Mem: 894 345 549 0 0 0
-/+ buffers/cache: 345 549
Swap: 0 0 0
</code></pre>
<p>The server is running CentOS 5.3. I am unable to reproduce on my own CentOS boxes nor with any other user reporting the same problem.</p>
<p>I have tried a number of things to debug this as suggested in the original question:</p>
<ol>
<li><p>Logging the output of free -m before and after the Popen call. There is no significant change in memory usage i.e. memory is not gradually being used up as the script runs.</p></li>
<li><p>I added close_fds=True to the Popen call but this made no difference - the script still crashed with the same error. Suggested <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory/1297785#1297785">here</a> and <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory/1278961#1278961">here</a>.</p></li>
<li><p>I checked the rlimits which showed (-1, -1) on both RLIMIT_DATA and RLIMIT_AS as suggested <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory/1270442#1270442">here</a>.</p></li>
<li><p><a href="http://www.zenoss.com/community/wiki/common-error-messages-and-solutions/oserror-errno-12-cannot-allocate-memory-in-popen2.py/">An article</a> suggested the having no swap space might be the cause but swap is actually available on demand (according to the web host) and this was also suggested as a bogus cause <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory/1270171#1270171">here</a>.</p></li>
<li><p>The processes are being closed because that is the behaviour of using .communicate() as backed up by the Python source code and comments <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory/1216824#1216824">here</a>.</p></li>
</ol>
<p>The entire checks can be found at on <a href="http://github.com/dmytton/sd-agent/blob/82f5ff9203e54d2adeee8cfed704d09e3f00e8eb/checks.py">GitHub here</a> with the getProcesses function defined from line 442. This is called by doChecks() starting at line 520.</p>
<p>The script was run with strace with the following output before the crash:</p>
<pre><code>recv(4, "Total Accesses: 516662\nTotal kBy"..., 234, 0) = 234
gettimeofday({1250893252, 887805}, NULL) = 0
write(3, "2009-08-21 17:20:52,887 - checks"..., 91) = 91
gettimeofday({1250893252, 888362}, NULL) = 0
write(3, "2009-08-21 17:20:52,888 - checks"..., 74) = 74
gettimeofday({1250893252, 888897}, NULL) = 0
write(3, "2009-08-21 17:20:52,888 - checks"..., 67) = 67
gettimeofday({1250893252, 889184}, NULL) = 0
write(3, "2009-08-21 17:20:52,889 - checks"..., 81) = 81
close(4) = 0
gettimeofday({1250893252, 889591}, NULL) = 0
write(3, "2009-08-21 17:20:52,889 - checks"..., 63) = 63
pipe([4, 5]) = 0
pipe([6, 7]) = 0
fcntl64(7, F_GETFD) = 0
fcntl64(7, F_SETFD, FD_CLOEXEC) = 0
clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0xb7f12708) = -1 ENOMEM (Cannot allocate memory)
write(2, "Traceback (most recent call last"..., 35) = 35
open("/usr/bin/sd-agent/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/bin/sd-agent/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python24.zip/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/plat-linux2/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python2.4/lib-tk/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/lib-dynload/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/site-packages/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
write(2, " File \"/usr/bin/sd-agent/agent."..., 52) = 52
open("/home/admin/sd-agent/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/bin/sd-agent/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python24.zip/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/plat-linux2/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python2.4/lib-tk/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/lib-dynload/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/site-packages/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
write(2, " File \"/home/admin/sd-agent/dae"..., 60) = 60
open("/usr/bin/sd-agent/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/bin/sd-agent/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python24.zip/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/plat-linux2/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python2.4/lib-tk/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/lib-dynload/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/site-packages/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
write(2, " File \"/usr/bin/sd-agent/agent."..., 54) = 54
open("/usr/lib/python2.4/sched.py", O_RDONLY|O_LARGEFILE) = 8
write(2, " File \"/usr/lib/python2.4/sched"..., 55) = 55
fstat64(8, {st_mode=S_IFREG|0644, st_size=4054, ...}) = 0
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7d28000
read(8, "\"\"\"A generally useful event sche"..., 4096) = 4054
write(2, " ", 4) = 4
write(2, "void = action(*argument)\n", 25) = 25
close(8) = 0
munmap(0xb7d28000, 4096) = 0
open("/usr/bin/sd-agent/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/bin/sd-agent/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python24.zip/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/plat-linux2/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python2.4/lib-tk/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/lib-dynload/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/site-packages/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
write(2, " File \"/usr/bin/sd-agent/checks"..., 60) = 60
open("/usr/bin/sd-agent/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/bin/sd-agent/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python24.zip/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/plat-linux2/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python2.4/lib-tk/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/lib-dynload/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/site-packages/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
write(2, " File \"/usr/bin/sd-agent/checks"..., 64) = 64
open("/usr/lib/python2.4/subprocess.py", O_RDONLY|O_LARGEFILE) = 8
write(2, " File \"/usr/lib/python2.4/subpr"..., 65) = 65
fstat64(8, {st_mode=S_IFREG|0644, st_size=39931, ...}) = 0
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7d28000
read(8, "# subprocess - Subprocesses with"..., 4096) = 4096
read(8, "lso, the newlines attribute of t"..., 4096) = 4096
read(8, "code < 0:\n print >>sys.st"..., 4096) = 4096
read(8, "alse does not exist on 2.2.0\ntry"..., 4096) = 4096
read(8, " p2cread\n # c2pread <-"..., 4096) = 4096
write(2, " ", 4) = 4
write(2, "errread, errwrite)\n", 19) = 19
close(8) = 0
munmap(0xb7d28000, 4096) = 0
open("/usr/lib/python2.4/subprocess.py", O_RDONLY|O_LARGEFILE) = 8
write(2, " File \"/usr/lib/python2.4/subpr"..., 71) = 71
fstat64(8, {st_mode=S_IFREG|0644, st_size=39931, ...}) = 0
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7d28000
read(8, "# subprocess - Subprocesses with"..., 4096) = 4096
read(8, "lso, the newlines attribute of t"..., 4096) = 4096
read(8, "code < 0:\n print >>sys.st"..., 4096) = 4096
read(8, "alse does not exist on 2.2.0\ntry"..., 4096) = 4096
read(8, " p2cread\n # c2pread <-"..., 4096) = 4096
read(8, "table(self, handle):\n "..., 4096) = 4096
read(8, "rrno using _sys_errlist (or siml"..., 4096) = 4096
read(8, " p2cwrite = None, None\n "..., 4096) = 4096
write(2, " ", 4) = 4
write(2, "self.pid = os.fork()\n", 21) = 21
close(8) = 0
munmap(0xb7d28000, 4096) = 0
write(2, "OSError", 7) = 7
write(2, ": ", 2) = 2
write(2, "[Errno 12] Cannot allocate memor"..., 33) = 33
write(2, "\n", 1) = 1
unlink("/var/run/sd-agent.pid") = 0
close(3) = 0
munmap(0xb7e0d000, 4096) = 0
rt_sigaction(SIGINT, {SIG_DFL, [], SA_RESTORER, 0x589978}, {0xb89a60, [], SA_RESTORER, 0x589978}, 8) = 0
brk(0xa022000) = 0xa022000
exit_group(1) = ?
</code></pre>
| 62 | 2009-09-02T12:23:43Z | 1,376,124 | <blockquote>
<p>munmap(0xb7d28000, 4096) = 0<br />
write(2, "OSError", 7) = 7 </p>
</blockquote>
<p>I've seen sloppy code that looks like this:</p>
<pre><code>serrno = errno;
some_Syscall(...)
if (serrno != errno)
/* sound alarm: CATROSTOPHIC ERROR !!! */
</code></pre>
<p>You should check to see if this is what is happening in the
python code. Errno is only valid if the proceeding system call
failed.</p>
<p>Edited to add: </p>
<p>You don't say how long this process lives. Possible consumers of memory </p>
<ul>
<li>forked processes</li>
<li>unused data structures</li>
<li>shared libraries</li>
<li>memory mapped files</li>
</ul>
| 0 | 2009-09-03T21:43:09Z | [
"python",
"linux",
"memory"
] |
Python subprocess.Popen "OSError: [Errno 12] Cannot allocate memory" | 1,367,373 | <p><strong>Note:</strong> This question was originally asked <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory">here</a> but the bounty time expired even though an acceptable answer was not actually found. I am re-asking this question including all details provided in the original question.</p>
<p>A python script is running a set of class functions every 60 seconds using the <a href="http://docs.python.org/library/sched.html">sched</a> module:</p>
<pre><code># sc is a sched.scheduler instance
sc.enter(60, 1, self.doChecks, (sc, False))
</code></pre>
<p>The script is running as a daemonised process using the code <a href="http://www.jejik.com/articles/2007/02/a%5Fsimple%5Funix%5Flinux%5Fdaemon%5Fin%5Fpython/">here</a>.</p>
<p>A number of class methods that are called as part of doChecks use the <a href="http://docs.python.org/library/subprocess.html">subprocess</a> module to call system functions in order to get system statistics:</p>
<pre><code>ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]
</code></pre>
<p>This runs fine for a period of time before the entire script crashing with the following error:</p>
<pre><code>File "/home/admin/sd-agent/checks.py", line 436, in getProcesses
File "/usr/lib/python2.4/subprocess.py", line 533, in __init__
File "/usr/lib/python2.4/subprocess.py", line 835, in _get_handles
OSError: [Errno 12] Cannot allocate memory
</code></pre>
<p>The output of free -m on the server once the script has crashed is:</p>
<pre><code>$ free -m
total used free shared buffers cached
Mem: 894 345 549 0 0 0
-/+ buffers/cache: 345 549
Swap: 0 0 0
</code></pre>
<p>The server is running CentOS 5.3. I am unable to reproduce on my own CentOS boxes nor with any other user reporting the same problem.</p>
<p>I have tried a number of things to debug this as suggested in the original question:</p>
<ol>
<li><p>Logging the output of free -m before and after the Popen call. There is no significant change in memory usage i.e. memory is not gradually being used up as the script runs.</p></li>
<li><p>I added close_fds=True to the Popen call but this made no difference - the script still crashed with the same error. Suggested <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory/1297785#1297785">here</a> and <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory/1278961#1278961">here</a>.</p></li>
<li><p>I checked the rlimits which showed (-1, -1) on both RLIMIT_DATA and RLIMIT_AS as suggested <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory/1270442#1270442">here</a>.</p></li>
<li><p><a href="http://www.zenoss.com/community/wiki/common-error-messages-and-solutions/oserror-errno-12-cannot-allocate-memory-in-popen2.py/">An article</a> suggested the having no swap space might be the cause but swap is actually available on demand (according to the web host) and this was also suggested as a bogus cause <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory/1270171#1270171">here</a>.</p></li>
<li><p>The processes are being closed because that is the behaviour of using .communicate() as backed up by the Python source code and comments <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory/1216824#1216824">here</a>.</p></li>
</ol>
<p>The entire checks can be found at on <a href="http://github.com/dmytton/sd-agent/blob/82f5ff9203e54d2adeee8cfed704d09e3f00e8eb/checks.py">GitHub here</a> with the getProcesses function defined from line 442. This is called by doChecks() starting at line 520.</p>
<p>The script was run with strace with the following output before the crash:</p>
<pre><code>recv(4, "Total Accesses: 516662\nTotal kBy"..., 234, 0) = 234
gettimeofday({1250893252, 887805}, NULL) = 0
write(3, "2009-08-21 17:20:52,887 - checks"..., 91) = 91
gettimeofday({1250893252, 888362}, NULL) = 0
write(3, "2009-08-21 17:20:52,888 - checks"..., 74) = 74
gettimeofday({1250893252, 888897}, NULL) = 0
write(3, "2009-08-21 17:20:52,888 - checks"..., 67) = 67
gettimeofday({1250893252, 889184}, NULL) = 0
write(3, "2009-08-21 17:20:52,889 - checks"..., 81) = 81
close(4) = 0
gettimeofday({1250893252, 889591}, NULL) = 0
write(3, "2009-08-21 17:20:52,889 - checks"..., 63) = 63
pipe([4, 5]) = 0
pipe([6, 7]) = 0
fcntl64(7, F_GETFD) = 0
fcntl64(7, F_SETFD, FD_CLOEXEC) = 0
clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0xb7f12708) = -1 ENOMEM (Cannot allocate memory)
write(2, "Traceback (most recent call last"..., 35) = 35
open("/usr/bin/sd-agent/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/bin/sd-agent/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python24.zip/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/plat-linux2/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python2.4/lib-tk/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/lib-dynload/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/site-packages/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
write(2, " File \"/usr/bin/sd-agent/agent."..., 52) = 52
open("/home/admin/sd-agent/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/bin/sd-agent/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python24.zip/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/plat-linux2/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python2.4/lib-tk/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/lib-dynload/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/site-packages/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
write(2, " File \"/home/admin/sd-agent/dae"..., 60) = 60
open("/usr/bin/sd-agent/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/bin/sd-agent/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python24.zip/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/plat-linux2/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python2.4/lib-tk/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/lib-dynload/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/site-packages/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
write(2, " File \"/usr/bin/sd-agent/agent."..., 54) = 54
open("/usr/lib/python2.4/sched.py", O_RDONLY|O_LARGEFILE) = 8
write(2, " File \"/usr/lib/python2.4/sched"..., 55) = 55
fstat64(8, {st_mode=S_IFREG|0644, st_size=4054, ...}) = 0
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7d28000
read(8, "\"\"\"A generally useful event sche"..., 4096) = 4054
write(2, " ", 4) = 4
write(2, "void = action(*argument)\n", 25) = 25
close(8) = 0
munmap(0xb7d28000, 4096) = 0
open("/usr/bin/sd-agent/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/bin/sd-agent/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python24.zip/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/plat-linux2/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python2.4/lib-tk/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/lib-dynload/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/site-packages/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
write(2, " File \"/usr/bin/sd-agent/checks"..., 60) = 60
open("/usr/bin/sd-agent/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/bin/sd-agent/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python24.zip/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/plat-linux2/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python2.4/lib-tk/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/lib-dynload/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/site-packages/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
write(2, " File \"/usr/bin/sd-agent/checks"..., 64) = 64
open("/usr/lib/python2.4/subprocess.py", O_RDONLY|O_LARGEFILE) = 8
write(2, " File \"/usr/lib/python2.4/subpr"..., 65) = 65
fstat64(8, {st_mode=S_IFREG|0644, st_size=39931, ...}) = 0
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7d28000
read(8, "# subprocess - Subprocesses with"..., 4096) = 4096
read(8, "lso, the newlines attribute of t"..., 4096) = 4096
read(8, "code < 0:\n print >>sys.st"..., 4096) = 4096
read(8, "alse does not exist on 2.2.0\ntry"..., 4096) = 4096
read(8, " p2cread\n # c2pread <-"..., 4096) = 4096
write(2, " ", 4) = 4
write(2, "errread, errwrite)\n", 19) = 19
close(8) = 0
munmap(0xb7d28000, 4096) = 0
open("/usr/lib/python2.4/subprocess.py", O_RDONLY|O_LARGEFILE) = 8
write(2, " File \"/usr/lib/python2.4/subpr"..., 71) = 71
fstat64(8, {st_mode=S_IFREG|0644, st_size=39931, ...}) = 0
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7d28000
read(8, "# subprocess - Subprocesses with"..., 4096) = 4096
read(8, "lso, the newlines attribute of t"..., 4096) = 4096
read(8, "code < 0:\n print >>sys.st"..., 4096) = 4096
read(8, "alse does not exist on 2.2.0\ntry"..., 4096) = 4096
read(8, " p2cread\n # c2pread <-"..., 4096) = 4096
read(8, "table(self, handle):\n "..., 4096) = 4096
read(8, "rrno using _sys_errlist (or siml"..., 4096) = 4096
read(8, " p2cwrite = None, None\n "..., 4096) = 4096
write(2, " ", 4) = 4
write(2, "self.pid = os.fork()\n", 21) = 21
close(8) = 0
munmap(0xb7d28000, 4096) = 0
write(2, "OSError", 7) = 7
write(2, ": ", 2) = 2
write(2, "[Errno 12] Cannot allocate memor"..., 33) = 33
write(2, "\n", 1) = 1
unlink("/var/run/sd-agent.pid") = 0
close(3) = 0
munmap(0xb7e0d000, 4096) = 0
rt_sigaction(SIGINT, {SIG_DFL, [], SA_RESTORER, 0x589978}, {0xb89a60, [], SA_RESTORER, 0x589978}, 8) = 0
brk(0xa022000) = 0xa022000
exit_group(1) = ?
</code></pre>
| 62 | 2009-09-02T12:23:43Z | 1,377,174 | <p>I continue to suspect that your customer/user has some kernel module or driver loaded which
is interfering with the <code>clone()</code> system call (perhaps some obscure security enhancement,
something like LIDS but more obscure?) or is somehow filling up some of the kernel data
structures that are necessary for <code>fork()</code>/<code>clone()</code> to operate (process table, page
tables, file descriptor tables, etc).</p>
<p>Here's the relevant portion of the <code>fork(2)</code> man page:</p>
<pre>
ERRORS
EAGAIN fork() cannot allocate sufficient memory to copy the parent's page tables and allocate a task structure for the
child.
EAGAIN It was not possible to create a new process because the caller's RLIMIT_NPROC resource limit was encountered. To
exceed this limit, the process must have either the CAP_SYS_ADMIN or the CAP_SYS_RESOURCE capability.
ENOMEM fork() failed to allocate the necessary kernel structures because memory is tight.
</pre>
<p>I suggest having the user try this after booting into a stock, generic kernel and with only a minimal set of modules and drivers loaded (minimum necessary to run your application/script). From there, assuming it works in that configuration, they can perform a binary search between that and the configuration which exhibits the issue. This is standard sysadmin troubleshooting 101.</p>
<p>The relevant line in your <code>strace</code> is:</p>
<pre><code>clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0xb7f12708) = -1 ENOMEM (Cannot allocate memory)
</code></pre>
<p>... I know others have talked about swap and memory availability (and I would recommend that you set up at least a small swap partition, ironically even if it's on a RAM disk ... the code paths through the Linux kernel when it has even a tiny bit of swap available have been exercised far more extensively than those (exception handling paths) in which there is zero swap available.</p>
<p>However I suspect that this is still a red herring.</p>
<p>The fact that <code>free</code> is reporting 0 (ZERO) memory in use by the cache and buffers is very disturbing. I suspect that the <code>free</code> output ... and possibly your application issue here, are caused by some proprietary kernel module which is interfering with the memory allocation in some way.</p>
<p>According to the man pages for fork()/clone() the fork() system call should return EAGAIN if your call would cause a resource limit violation (RLIMIT_NPROC) ... however, it doesn't say if EAGAIN is to be returned by other RLIMIT* violations. In any event if your target/host has some sort of weird Vormetric or other security settings (or even if your process is running under some weird SELinux policy) then it might be causing this -ENOMEM failure.</p>
<p>It's pretty unlikely to be a normal run-of-the-mill Linux/UNIX issue. You've got something non-standard going on there.</p>
| 5 | 2009-09-04T04:02:46Z | [
"python",
"linux",
"memory"
] |
Python subprocess.Popen "OSError: [Errno 12] Cannot allocate memory" | 1,367,373 | <p><strong>Note:</strong> This question was originally asked <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory">here</a> but the bounty time expired even though an acceptable answer was not actually found. I am re-asking this question including all details provided in the original question.</p>
<p>A python script is running a set of class functions every 60 seconds using the <a href="http://docs.python.org/library/sched.html">sched</a> module:</p>
<pre><code># sc is a sched.scheduler instance
sc.enter(60, 1, self.doChecks, (sc, False))
</code></pre>
<p>The script is running as a daemonised process using the code <a href="http://www.jejik.com/articles/2007/02/a%5Fsimple%5Funix%5Flinux%5Fdaemon%5Fin%5Fpython/">here</a>.</p>
<p>A number of class methods that are called as part of doChecks use the <a href="http://docs.python.org/library/subprocess.html">subprocess</a> module to call system functions in order to get system statistics:</p>
<pre><code>ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]
</code></pre>
<p>This runs fine for a period of time before the entire script crashing with the following error:</p>
<pre><code>File "/home/admin/sd-agent/checks.py", line 436, in getProcesses
File "/usr/lib/python2.4/subprocess.py", line 533, in __init__
File "/usr/lib/python2.4/subprocess.py", line 835, in _get_handles
OSError: [Errno 12] Cannot allocate memory
</code></pre>
<p>The output of free -m on the server once the script has crashed is:</p>
<pre><code>$ free -m
total used free shared buffers cached
Mem: 894 345 549 0 0 0
-/+ buffers/cache: 345 549
Swap: 0 0 0
</code></pre>
<p>The server is running CentOS 5.3. I am unable to reproduce on my own CentOS boxes nor with any other user reporting the same problem.</p>
<p>I have tried a number of things to debug this as suggested in the original question:</p>
<ol>
<li><p>Logging the output of free -m before and after the Popen call. There is no significant change in memory usage i.e. memory is not gradually being used up as the script runs.</p></li>
<li><p>I added close_fds=True to the Popen call but this made no difference - the script still crashed with the same error. Suggested <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory/1297785#1297785">here</a> and <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory/1278961#1278961">here</a>.</p></li>
<li><p>I checked the rlimits which showed (-1, -1) on both RLIMIT_DATA and RLIMIT_AS as suggested <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory/1270442#1270442">here</a>.</p></li>
<li><p><a href="http://www.zenoss.com/community/wiki/common-error-messages-and-solutions/oserror-errno-12-cannot-allocate-memory-in-popen2.py/">An article</a> suggested the having no swap space might be the cause but swap is actually available on demand (according to the web host) and this was also suggested as a bogus cause <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory/1270171#1270171">here</a>.</p></li>
<li><p>The processes are being closed because that is the behaviour of using .communicate() as backed up by the Python source code and comments <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory/1216824#1216824">here</a>.</p></li>
</ol>
<p>The entire checks can be found at on <a href="http://github.com/dmytton/sd-agent/blob/82f5ff9203e54d2adeee8cfed704d09e3f00e8eb/checks.py">GitHub here</a> with the getProcesses function defined from line 442. This is called by doChecks() starting at line 520.</p>
<p>The script was run with strace with the following output before the crash:</p>
<pre><code>recv(4, "Total Accesses: 516662\nTotal kBy"..., 234, 0) = 234
gettimeofday({1250893252, 887805}, NULL) = 0
write(3, "2009-08-21 17:20:52,887 - checks"..., 91) = 91
gettimeofday({1250893252, 888362}, NULL) = 0
write(3, "2009-08-21 17:20:52,888 - checks"..., 74) = 74
gettimeofday({1250893252, 888897}, NULL) = 0
write(3, "2009-08-21 17:20:52,888 - checks"..., 67) = 67
gettimeofday({1250893252, 889184}, NULL) = 0
write(3, "2009-08-21 17:20:52,889 - checks"..., 81) = 81
close(4) = 0
gettimeofday({1250893252, 889591}, NULL) = 0
write(3, "2009-08-21 17:20:52,889 - checks"..., 63) = 63
pipe([4, 5]) = 0
pipe([6, 7]) = 0
fcntl64(7, F_GETFD) = 0
fcntl64(7, F_SETFD, FD_CLOEXEC) = 0
clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0xb7f12708) = -1 ENOMEM (Cannot allocate memory)
write(2, "Traceback (most recent call last"..., 35) = 35
open("/usr/bin/sd-agent/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/bin/sd-agent/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python24.zip/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/plat-linux2/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python2.4/lib-tk/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/lib-dynload/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/site-packages/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
write(2, " File \"/usr/bin/sd-agent/agent."..., 52) = 52
open("/home/admin/sd-agent/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/bin/sd-agent/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python24.zip/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/plat-linux2/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python2.4/lib-tk/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/lib-dynload/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/site-packages/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
write(2, " File \"/home/admin/sd-agent/dae"..., 60) = 60
open("/usr/bin/sd-agent/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/bin/sd-agent/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python24.zip/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/plat-linux2/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python2.4/lib-tk/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/lib-dynload/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/site-packages/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
write(2, " File \"/usr/bin/sd-agent/agent."..., 54) = 54
open("/usr/lib/python2.4/sched.py", O_RDONLY|O_LARGEFILE) = 8
write(2, " File \"/usr/lib/python2.4/sched"..., 55) = 55
fstat64(8, {st_mode=S_IFREG|0644, st_size=4054, ...}) = 0
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7d28000
read(8, "\"\"\"A generally useful event sche"..., 4096) = 4054
write(2, " ", 4) = 4
write(2, "void = action(*argument)\n", 25) = 25
close(8) = 0
munmap(0xb7d28000, 4096) = 0
open("/usr/bin/sd-agent/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/bin/sd-agent/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python24.zip/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/plat-linux2/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python2.4/lib-tk/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/lib-dynload/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/site-packages/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
write(2, " File \"/usr/bin/sd-agent/checks"..., 60) = 60
open("/usr/bin/sd-agent/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/bin/sd-agent/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python24.zip/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/plat-linux2/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python2.4/lib-tk/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/lib-dynload/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/site-packages/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
write(2, " File \"/usr/bin/sd-agent/checks"..., 64) = 64
open("/usr/lib/python2.4/subprocess.py", O_RDONLY|O_LARGEFILE) = 8
write(2, " File \"/usr/lib/python2.4/subpr"..., 65) = 65
fstat64(8, {st_mode=S_IFREG|0644, st_size=39931, ...}) = 0
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7d28000
read(8, "# subprocess - Subprocesses with"..., 4096) = 4096
read(8, "lso, the newlines attribute of t"..., 4096) = 4096
read(8, "code < 0:\n print >>sys.st"..., 4096) = 4096
read(8, "alse does not exist on 2.2.0\ntry"..., 4096) = 4096
read(8, " p2cread\n # c2pread <-"..., 4096) = 4096
write(2, " ", 4) = 4
write(2, "errread, errwrite)\n", 19) = 19
close(8) = 0
munmap(0xb7d28000, 4096) = 0
open("/usr/lib/python2.4/subprocess.py", O_RDONLY|O_LARGEFILE) = 8
write(2, " File \"/usr/lib/python2.4/subpr"..., 71) = 71
fstat64(8, {st_mode=S_IFREG|0644, st_size=39931, ...}) = 0
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7d28000
read(8, "# subprocess - Subprocesses with"..., 4096) = 4096
read(8, "lso, the newlines attribute of t"..., 4096) = 4096
read(8, "code < 0:\n print >>sys.st"..., 4096) = 4096
read(8, "alse does not exist on 2.2.0\ntry"..., 4096) = 4096
read(8, " p2cread\n # c2pread <-"..., 4096) = 4096
read(8, "table(self, handle):\n "..., 4096) = 4096
read(8, "rrno using _sys_errlist (or siml"..., 4096) = 4096
read(8, " p2cwrite = None, None\n "..., 4096) = 4096
write(2, " ", 4) = 4
write(2, "self.pid = os.fork()\n", 21) = 21
close(8) = 0
munmap(0xb7d28000, 4096) = 0
write(2, "OSError", 7) = 7
write(2, ": ", 2) = 2
write(2, "[Errno 12] Cannot allocate memor"..., 33) = 33
write(2, "\n", 1) = 1
unlink("/var/run/sd-agent.pid") = 0
close(3) = 0
munmap(0xb7e0d000, 4096) = 0
rt_sigaction(SIGINT, {SIG_DFL, [], SA_RESTORER, 0x589978}, {0xb89a60, [], SA_RESTORER, 0x589978}, 8) = 0
brk(0xa022000) = 0xa022000
exit_group(1) = ?
</code></pre>
| 62 | 2009-09-02T12:23:43Z | 7,263,866 | <p>Have you tried using:</p>
<pre><code>(status,output) = commands.getstatusoutput("ps aux")
</code></pre>
<p>I thought this had fixed the exact same problem for me.
But then my process ended up getting killed instead of failing to spawn, which is even worse..</p>
<p>After some testing I found that this only occurred on older versions of python: it happens with 2.6.5 but not with 2.7.2</p>
<p>My search had led me here <a href="http://bramp.net/blog/python-close_fds-issue" rel="nofollow">python-close_fds-issue</a>, but unsetting closed_fds had not solved the issue. It is still well worth a read.</p>
<p>I found that python was leaking file descriptors by just keeping an eye on it:</p>
<pre><code>watch "ls /proc/$PYTHONPID/fd | wc -l"
</code></pre>
<p>Like you, I do want to capture the command's output, and I do want to avoid OOM errors... but it looks like the only way is for people to use a less buggy version of Python. Not ideal...</p>
| 2 | 2011-08-31T21:47:43Z | [
"python",
"linux",
"memory"
] |
Python subprocess.Popen "OSError: [Errno 12] Cannot allocate memory" | 1,367,373 | <p><strong>Note:</strong> This question was originally asked <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory">here</a> but the bounty time expired even though an acceptable answer was not actually found. I am re-asking this question including all details provided in the original question.</p>
<p>A python script is running a set of class functions every 60 seconds using the <a href="http://docs.python.org/library/sched.html">sched</a> module:</p>
<pre><code># sc is a sched.scheduler instance
sc.enter(60, 1, self.doChecks, (sc, False))
</code></pre>
<p>The script is running as a daemonised process using the code <a href="http://www.jejik.com/articles/2007/02/a%5Fsimple%5Funix%5Flinux%5Fdaemon%5Fin%5Fpython/">here</a>.</p>
<p>A number of class methods that are called as part of doChecks use the <a href="http://docs.python.org/library/subprocess.html">subprocess</a> module to call system functions in order to get system statistics:</p>
<pre><code>ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]
</code></pre>
<p>This runs fine for a period of time before the entire script crashing with the following error:</p>
<pre><code>File "/home/admin/sd-agent/checks.py", line 436, in getProcesses
File "/usr/lib/python2.4/subprocess.py", line 533, in __init__
File "/usr/lib/python2.4/subprocess.py", line 835, in _get_handles
OSError: [Errno 12] Cannot allocate memory
</code></pre>
<p>The output of free -m on the server once the script has crashed is:</p>
<pre><code>$ free -m
total used free shared buffers cached
Mem: 894 345 549 0 0 0
-/+ buffers/cache: 345 549
Swap: 0 0 0
</code></pre>
<p>The server is running CentOS 5.3. I am unable to reproduce on my own CentOS boxes nor with any other user reporting the same problem.</p>
<p>I have tried a number of things to debug this as suggested in the original question:</p>
<ol>
<li><p>Logging the output of free -m before and after the Popen call. There is no significant change in memory usage i.e. memory is not gradually being used up as the script runs.</p></li>
<li><p>I added close_fds=True to the Popen call but this made no difference - the script still crashed with the same error. Suggested <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory/1297785#1297785">here</a> and <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory/1278961#1278961">here</a>.</p></li>
<li><p>I checked the rlimits which showed (-1, -1) on both RLIMIT_DATA and RLIMIT_AS as suggested <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory/1270442#1270442">here</a>.</p></li>
<li><p><a href="http://www.zenoss.com/community/wiki/common-error-messages-and-solutions/oserror-errno-12-cannot-allocate-memory-in-popen2.py/">An article</a> suggested the having no swap space might be the cause but swap is actually available on demand (according to the web host) and this was also suggested as a bogus cause <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory/1270171#1270171">here</a>.</p></li>
<li><p>The processes are being closed because that is the behaviour of using .communicate() as backed up by the Python source code and comments <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory/1216824#1216824">here</a>.</p></li>
</ol>
<p>The entire checks can be found at on <a href="http://github.com/dmytton/sd-agent/blob/82f5ff9203e54d2adeee8cfed704d09e3f00e8eb/checks.py">GitHub here</a> with the getProcesses function defined from line 442. This is called by doChecks() starting at line 520.</p>
<p>The script was run with strace with the following output before the crash:</p>
<pre><code>recv(4, "Total Accesses: 516662\nTotal kBy"..., 234, 0) = 234
gettimeofday({1250893252, 887805}, NULL) = 0
write(3, "2009-08-21 17:20:52,887 - checks"..., 91) = 91
gettimeofday({1250893252, 888362}, NULL) = 0
write(3, "2009-08-21 17:20:52,888 - checks"..., 74) = 74
gettimeofday({1250893252, 888897}, NULL) = 0
write(3, "2009-08-21 17:20:52,888 - checks"..., 67) = 67
gettimeofday({1250893252, 889184}, NULL) = 0
write(3, "2009-08-21 17:20:52,889 - checks"..., 81) = 81
close(4) = 0
gettimeofday({1250893252, 889591}, NULL) = 0
write(3, "2009-08-21 17:20:52,889 - checks"..., 63) = 63
pipe([4, 5]) = 0
pipe([6, 7]) = 0
fcntl64(7, F_GETFD) = 0
fcntl64(7, F_SETFD, FD_CLOEXEC) = 0
clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0xb7f12708) = -1 ENOMEM (Cannot allocate memory)
write(2, "Traceback (most recent call last"..., 35) = 35
open("/usr/bin/sd-agent/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/bin/sd-agent/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python24.zip/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/plat-linux2/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python2.4/lib-tk/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/lib-dynload/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/site-packages/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
write(2, " File \"/usr/bin/sd-agent/agent."..., 52) = 52
open("/home/admin/sd-agent/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/bin/sd-agent/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python24.zip/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/plat-linux2/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python2.4/lib-tk/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/lib-dynload/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/site-packages/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
write(2, " File \"/home/admin/sd-agent/dae"..., 60) = 60
open("/usr/bin/sd-agent/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/bin/sd-agent/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python24.zip/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/plat-linux2/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python2.4/lib-tk/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/lib-dynload/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/site-packages/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
write(2, " File \"/usr/bin/sd-agent/agent."..., 54) = 54
open("/usr/lib/python2.4/sched.py", O_RDONLY|O_LARGEFILE) = 8
write(2, " File \"/usr/lib/python2.4/sched"..., 55) = 55
fstat64(8, {st_mode=S_IFREG|0644, st_size=4054, ...}) = 0
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7d28000
read(8, "\"\"\"A generally useful event sche"..., 4096) = 4054
write(2, " ", 4) = 4
write(2, "void = action(*argument)\n", 25) = 25
close(8) = 0
munmap(0xb7d28000, 4096) = 0
open("/usr/bin/sd-agent/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/bin/sd-agent/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python24.zip/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/plat-linux2/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python2.4/lib-tk/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/lib-dynload/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/site-packages/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
write(2, " File \"/usr/bin/sd-agent/checks"..., 60) = 60
open("/usr/bin/sd-agent/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/bin/sd-agent/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python24.zip/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/plat-linux2/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python2.4/lib-tk/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/lib-dynload/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/site-packages/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
write(2, " File \"/usr/bin/sd-agent/checks"..., 64) = 64
open("/usr/lib/python2.4/subprocess.py", O_RDONLY|O_LARGEFILE) = 8
write(2, " File \"/usr/lib/python2.4/subpr"..., 65) = 65
fstat64(8, {st_mode=S_IFREG|0644, st_size=39931, ...}) = 0
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7d28000
read(8, "# subprocess - Subprocesses with"..., 4096) = 4096
read(8, "lso, the newlines attribute of t"..., 4096) = 4096
read(8, "code < 0:\n print >>sys.st"..., 4096) = 4096
read(8, "alse does not exist on 2.2.0\ntry"..., 4096) = 4096
read(8, " p2cread\n # c2pread <-"..., 4096) = 4096
write(2, " ", 4) = 4
write(2, "errread, errwrite)\n", 19) = 19
close(8) = 0
munmap(0xb7d28000, 4096) = 0
open("/usr/lib/python2.4/subprocess.py", O_RDONLY|O_LARGEFILE) = 8
write(2, " File \"/usr/lib/python2.4/subpr"..., 71) = 71
fstat64(8, {st_mode=S_IFREG|0644, st_size=39931, ...}) = 0
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7d28000
read(8, "# subprocess - Subprocesses with"..., 4096) = 4096
read(8, "lso, the newlines attribute of t"..., 4096) = 4096
read(8, "code < 0:\n print >>sys.st"..., 4096) = 4096
read(8, "alse does not exist on 2.2.0\ntry"..., 4096) = 4096
read(8, " p2cread\n # c2pread <-"..., 4096) = 4096
read(8, "table(self, handle):\n "..., 4096) = 4096
read(8, "rrno using _sys_errlist (or siml"..., 4096) = 4096
read(8, " p2cwrite = None, None\n "..., 4096) = 4096
write(2, " ", 4) = 4
write(2, "self.pid = os.fork()\n", 21) = 21
close(8) = 0
munmap(0xb7d28000, 4096) = 0
write(2, "OSError", 7) = 7
write(2, ": ", 2) = 2
write(2, "[Errno 12] Cannot allocate memor"..., 33) = 33
write(2, "\n", 1) = 1
unlink("/var/run/sd-agent.pid") = 0
close(3) = 0
munmap(0xb7e0d000, 4096) = 0
rt_sigaction(SIGINT, {SIG_DFL, [], SA_RESTORER, 0x589978}, {0xb89a60, [], SA_RESTORER, 0x589978}, 8) = 0
brk(0xa022000) = 0xa022000
exit_group(1) = ?
</code></pre>
| 62 | 2009-09-02T12:23:43Z | 13,329,386 | <p>As a general rule (i.e. in vanilla kernels), <code>fork</code>/<code>clone</code> failures with <code>ENOMEM</code> <a href="https://github.com/torvalds/linux/blob/master/kernel/fork.c"><strong>occur specifically</strong></a> because of either <strong>an honest to God out-of-memory condition</strong> (<code>dup_mm</code>, <code>dup_task_struct</code>, <code>alloc_pid</code>, <code>mpol_dup</code>, <code>mm_init</code> etc. croak), or because <code>security_vm_enough_memory_mm</code> failed you <strong>while <a href="https://github.com/torvalds/linux/blob/38a76013ad809beb0b52f60d365c960d035bd83c/mm/mmap.c#L91">enforcing</a> the <a href="https://github.com/torvalds/linux/blob/master/Documentation/vm/overcommit-accounting">overcommit policy</a>.</strong></p>
<p>Start by checking the vmsize of the process that failed to fork, at the time of the fork attempt, and then compare to the amount of free memory (physical and swap) as it relates to the overcommit policy (plug the numbers in.)</p>
<p>In your particular case, note that Virtuozzo has <a href="https://src.openvz.org/projects/OVZL/repos/linux-2.6.32-openvz/browse/kernel/sys.c#183">additional checks</a> in <a href="https://src.openvz.org/projects/OVZL/repos/linux-2.6.32-openvz/commits/5198e6ea6a7c9c1a7d890f4c639007fce9290b05#mm/mmap.c">overcommit enforcement</a>. Moreover, I'm not sure how much control you truly have, from <strong>within</strong> your container, over <a href="http://kb.odin.com/en/112740">swap and overcommit configuration</a> (in order to influence the outcome of the enforcement.)</p>
<p>Now, in order to actually move forward I'd say you're <strong>left with two options</strong>:</p>
<ul>
<li>switch to a larger instance, or</li>
<li>put some coding effort into <strong>more effectively controlling your script's memory</strong> footprint</li>
</ul>
<p><strong>NOTE</strong> that the coding effort may be all for naught if it turns out that it's not you, but some other guy collocated in a different instance on the same server as you running amock.</p>
<p>Memory-wise, we already know that <strong><code>subprocess.Popen</code> uses <code>fork</code>/<code>clone</code></strong> <a href="http://svn.python.org/projects/python/trunk/Lib/subprocess.py">under the hood</a>, meaning that every time you call it you're <strong>requesting once more as much memory as Python is already eating up</strong>, i.e. in the hundreds of additional MB, all in order to then <code>exec</code> a puny 10kB executable such as <code>free</code> or <code>ps</code>. In the case of an unfavourable overcommit policy, you'll soon see <code>ENOMEM</code>.</p>
<p>Alternatives to <code>fork</code> that do not have this parent page tables etc. copy problem are <a href="http://linux.die.net/man/2/vfork"><code>vfork</code></a> and <a href="http://linux.die.net/man/3/posix_spawn"><code>posix_spawn</code></a>. But if you do not feel like rewriting chunks of <code>subprocess.Popen</code> in terms of <code>vfork</code>/<code>posix_spawn</code>, consider using <code>suprocess.Popen</code> only once, at the beginning of your script (when Python's memory footprint is minimal), to <strong>spawn a shell script that then runs <code>free</code>/<code>ps</code>/<code>sleep</code> and whatever else in a loop</strong> parallel to your script; poll the script's output or read it synchronously, possibly from a separate thread if you have other stuff to take care of asynchronously -- do your data crunching in Python but leave the forking to the subordinate process.</p>
<p><strong>HOWEVER</strong>, in your particular case you can skip invoking <code>ps</code> and <code>free</code> altogether; that <strong>information is readily available to you in Python directly from <a href="http://www.kernel.org/doc/Documentation/filesystems/proc.txt"><code>procfs</code></a></strong>, whether you choose to access it yourself or via <a href="https://www.google.com/search?q=python%20procfs">existing libraries and/or packages</a>. If <code>ps</code> and <code>free</code> were the only utilities you were running, then you can <strong>do away with <code>subprocess.Popen</code> completely</strong>.</p>
<p>Finally, whatever you do as far as <code>subprocess.Popen</code> is concerned, if your script leaks memory you will still hit the wall eventually. Keep an eye on it, and <a href="https://www.google.com/search?q=python%20memory%20leaks">check for memory leaks</a>.</p>
| 50 | 2012-11-11T07:30:08Z | [
"python",
"linux",
"memory"
] |
Python subprocess.Popen "OSError: [Errno 12] Cannot allocate memory" | 1,367,373 | <p><strong>Note:</strong> This question was originally asked <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory">here</a> but the bounty time expired even though an acceptable answer was not actually found. I am re-asking this question including all details provided in the original question.</p>
<p>A python script is running a set of class functions every 60 seconds using the <a href="http://docs.python.org/library/sched.html">sched</a> module:</p>
<pre><code># sc is a sched.scheduler instance
sc.enter(60, 1, self.doChecks, (sc, False))
</code></pre>
<p>The script is running as a daemonised process using the code <a href="http://www.jejik.com/articles/2007/02/a%5Fsimple%5Funix%5Flinux%5Fdaemon%5Fin%5Fpython/">here</a>.</p>
<p>A number of class methods that are called as part of doChecks use the <a href="http://docs.python.org/library/subprocess.html">subprocess</a> module to call system functions in order to get system statistics:</p>
<pre><code>ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]
</code></pre>
<p>This runs fine for a period of time before the entire script crashing with the following error:</p>
<pre><code>File "/home/admin/sd-agent/checks.py", line 436, in getProcesses
File "/usr/lib/python2.4/subprocess.py", line 533, in __init__
File "/usr/lib/python2.4/subprocess.py", line 835, in _get_handles
OSError: [Errno 12] Cannot allocate memory
</code></pre>
<p>The output of free -m on the server once the script has crashed is:</p>
<pre><code>$ free -m
total used free shared buffers cached
Mem: 894 345 549 0 0 0
-/+ buffers/cache: 345 549
Swap: 0 0 0
</code></pre>
<p>The server is running CentOS 5.3. I am unable to reproduce on my own CentOS boxes nor with any other user reporting the same problem.</p>
<p>I have tried a number of things to debug this as suggested in the original question:</p>
<ol>
<li><p>Logging the output of free -m before and after the Popen call. There is no significant change in memory usage i.e. memory is not gradually being used up as the script runs.</p></li>
<li><p>I added close_fds=True to the Popen call but this made no difference - the script still crashed with the same error. Suggested <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory/1297785#1297785">here</a> and <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory/1278961#1278961">here</a>.</p></li>
<li><p>I checked the rlimits which showed (-1, -1) on both RLIMIT_DATA and RLIMIT_AS as suggested <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory/1270442#1270442">here</a>.</p></li>
<li><p><a href="http://www.zenoss.com/community/wiki/common-error-messages-and-solutions/oserror-errno-12-cannot-allocate-memory-in-popen2.py/">An article</a> suggested the having no swap space might be the cause but swap is actually available on demand (according to the web host) and this was also suggested as a bogus cause <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory/1270171#1270171">here</a>.</p></li>
<li><p>The processes are being closed because that is the behaviour of using .communicate() as backed up by the Python source code and comments <a href="http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory/1216824#1216824">here</a>.</p></li>
</ol>
<p>The entire checks can be found at on <a href="http://github.com/dmytton/sd-agent/blob/82f5ff9203e54d2adeee8cfed704d09e3f00e8eb/checks.py">GitHub here</a> with the getProcesses function defined from line 442. This is called by doChecks() starting at line 520.</p>
<p>The script was run with strace with the following output before the crash:</p>
<pre><code>recv(4, "Total Accesses: 516662\nTotal kBy"..., 234, 0) = 234
gettimeofday({1250893252, 887805}, NULL) = 0
write(3, "2009-08-21 17:20:52,887 - checks"..., 91) = 91
gettimeofday({1250893252, 888362}, NULL) = 0
write(3, "2009-08-21 17:20:52,888 - checks"..., 74) = 74
gettimeofday({1250893252, 888897}, NULL) = 0
write(3, "2009-08-21 17:20:52,888 - checks"..., 67) = 67
gettimeofday({1250893252, 889184}, NULL) = 0
write(3, "2009-08-21 17:20:52,889 - checks"..., 81) = 81
close(4) = 0
gettimeofday({1250893252, 889591}, NULL) = 0
write(3, "2009-08-21 17:20:52,889 - checks"..., 63) = 63
pipe([4, 5]) = 0
pipe([6, 7]) = 0
fcntl64(7, F_GETFD) = 0
fcntl64(7, F_SETFD, FD_CLOEXEC) = 0
clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0xb7f12708) = -1 ENOMEM (Cannot allocate memory)
write(2, "Traceback (most recent call last"..., 35) = 35
open("/usr/bin/sd-agent/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/bin/sd-agent/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python24.zip/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/plat-linux2/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python2.4/lib-tk/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/lib-dynload/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/site-packages/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
write(2, " File \"/usr/bin/sd-agent/agent."..., 52) = 52
open("/home/admin/sd-agent/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/bin/sd-agent/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python24.zip/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/plat-linux2/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python2.4/lib-tk/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/lib-dynload/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/site-packages/daemon.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
write(2, " File \"/home/admin/sd-agent/dae"..., 60) = 60
open("/usr/bin/sd-agent/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/bin/sd-agent/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python24.zip/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/plat-linux2/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python2.4/lib-tk/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/lib-dynload/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/site-packages/agent.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
write(2, " File \"/usr/bin/sd-agent/agent."..., 54) = 54
open("/usr/lib/python2.4/sched.py", O_RDONLY|O_LARGEFILE) = 8
write(2, " File \"/usr/lib/python2.4/sched"..., 55) = 55
fstat64(8, {st_mode=S_IFREG|0644, st_size=4054, ...}) = 0
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7d28000
read(8, "\"\"\"A generally useful event sche"..., 4096) = 4054
write(2, " ", 4) = 4
write(2, "void = action(*argument)\n", 25) = 25
close(8) = 0
munmap(0xb7d28000, 4096) = 0
open("/usr/bin/sd-agent/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/bin/sd-agent/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python24.zip/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/plat-linux2/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python2.4/lib-tk/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/lib-dynload/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/site-packages/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
write(2, " File \"/usr/bin/sd-agent/checks"..., 60) = 60
open("/usr/bin/sd-agent/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/bin/sd-agent/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python24.zip/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/plat-linux2/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOMEM (Cannot allocate memory)
open("/usr/lib/python2.4/lib-tk/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/lib-dynload/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
open("/usr/lib/python2.4/site-packages/checks.py", O_RDONLY|O_LARGEFILE) = -1 ENOENT (No such file or directory)
write(2, " File \"/usr/bin/sd-agent/checks"..., 64) = 64
open("/usr/lib/python2.4/subprocess.py", O_RDONLY|O_LARGEFILE) = 8
write(2, " File \"/usr/lib/python2.4/subpr"..., 65) = 65
fstat64(8, {st_mode=S_IFREG|0644, st_size=39931, ...}) = 0
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7d28000
read(8, "# subprocess - Subprocesses with"..., 4096) = 4096
read(8, "lso, the newlines attribute of t"..., 4096) = 4096
read(8, "code < 0:\n print >>sys.st"..., 4096) = 4096
read(8, "alse does not exist on 2.2.0\ntry"..., 4096) = 4096
read(8, " p2cread\n # c2pread <-"..., 4096) = 4096
write(2, " ", 4) = 4
write(2, "errread, errwrite)\n", 19) = 19
close(8) = 0
munmap(0xb7d28000, 4096) = 0
open("/usr/lib/python2.4/subprocess.py", O_RDONLY|O_LARGEFILE) = 8
write(2, " File \"/usr/lib/python2.4/subpr"..., 71) = 71
fstat64(8, {st_mode=S_IFREG|0644, st_size=39931, ...}) = 0
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7d28000
read(8, "# subprocess - Subprocesses with"..., 4096) = 4096
read(8, "lso, the newlines attribute of t"..., 4096) = 4096
read(8, "code < 0:\n print >>sys.st"..., 4096) = 4096
read(8, "alse does not exist on 2.2.0\ntry"..., 4096) = 4096
read(8, " p2cread\n # c2pread <-"..., 4096) = 4096
read(8, "table(self, handle):\n "..., 4096) = 4096
read(8, "rrno using _sys_errlist (or siml"..., 4096) = 4096
read(8, " p2cwrite = None, None\n "..., 4096) = 4096
write(2, " ", 4) = 4
write(2, "self.pid = os.fork()\n", 21) = 21
close(8) = 0
munmap(0xb7d28000, 4096) = 0
write(2, "OSError", 7) = 7
write(2, ": ", 2) = 2
write(2, "[Errno 12] Cannot allocate memor"..., 33) = 33
write(2, "\n", 1) = 1
unlink("/var/run/sd-agent.pid") = 0
close(3) = 0
munmap(0xb7e0d000, 4096) = 0
rt_sigaction(SIGINT, {SIG_DFL, [], SA_RESTORER, 0x589978}, {0xb89a60, [], SA_RESTORER, 0x589978}, 8) = 0
brk(0xa022000) = 0xa022000
exit_group(1) = ?
</code></pre>
| 62 | 2009-09-02T12:23:43Z | 26,416,752 | <p>Looking at the output of <code>free -m</code> it seems to me that you actually do not have swap memory available. I am not sure if in Linux the swap always will be available automatically on demand, but I was having the same problem and none of the answers here really helped me. Adding some swap memory however, fixed the problem in my case so since this might help other people facing the same problem, I post my answer on how to add a 1GB swap (on Ubuntu 12.04 but it should work similarly for other distributions.)</p>
<p>You can first check if there is any swap memory enabled.</p>
<pre><code>$sudo swapon -s
</code></pre>
<p>if it is empty, it means you don't have any swap enabled. To add a 1GB swap:</p>
<pre><code>$sudo dd if=/dev/zero of=/swapfile bs=1024 count=1024k
$sudo mkswap /swapfile
$sudo swapon /swapfile
</code></pre>
<p>Add the following line to the <code>fstab</code> to make the swap permanent.</p>
<pre><code>$sudo vim /etc/fstab
/swapfile none swap sw 0 0
</code></pre>
<p>Source and more information can be found <a href="https://www.digitalocean.com/community/tutorials/how-to-add-swap-on-ubuntu-12-04">here</a>.</p>
| 5 | 2014-10-17T01:58:12Z | [
"python",
"linux",
"memory"
] |
Reading a website with asyncore | 1,367,453 | <p>I would like to read a website asynchronously, which isnt possible with urllib as far as I know. Now I tried reading with with plain sockets, but HTTP is giving me hell.
I run into all kind of funky encodings, for example transfer-encoding: chunked, have to parse all that stuff manually, and I feel like coding C, not python at the moment. </p>
<p>Isnt there a nicer way like URLLib, asynchronously? I dont really feel like re-implementing the whole HTTP specification, when it's all been done before.</p>
<p>Twisted isnt an option currently.</p>
<p>Greetings, </p>
<p>Tom</p>
| 7 | 2009-09-02T12:39:25Z | 1,367,499 | <p>You can implement an asynchronous call yourself. For each call, start a new thread (or try to get one from a pool) and use a callback to process it.</p>
<p>You can do this very nicely with a decorator:</p>
<pre><code>def threaded(callback=lambda *args, **kwargs: None, daemonic=False):
"""Decorate a function to run in its own thread and report the result
by calling callback with it."""
def innerDecorator(func):
def inner(*args, **kwargs):
target = lambda: callback(func(*args, **kwargs))
t = threading.Thread(target=target)
t.setDaemon(daemonic)
t.start()
return inner
return innerDecorator
@threaded()
def get_webpage(url):
data = urllib.urlopen(url).read()
print data
</code></pre>
| 7 | 2009-09-02T12:47:16Z | [
"python",
"web-services",
"sockets"
] |
Reading a website with asyncore | 1,367,453 | <p>I would like to read a website asynchronously, which isnt possible with urllib as far as I know. Now I tried reading with with plain sockets, but HTTP is giving me hell.
I run into all kind of funky encodings, for example transfer-encoding: chunked, have to parse all that stuff manually, and I feel like coding C, not python at the moment. </p>
<p>Isnt there a nicer way like URLLib, asynchronously? I dont really feel like re-implementing the whole HTTP specification, when it's all been done before.</p>
<p>Twisted isnt an option currently.</p>
<p>Greetings, </p>
<p>Tom</p>
| 7 | 2009-09-02T12:39:25Z | 1,367,941 | <p>Have you looked at <a href="http://asynchttp.sourceforge.net/">http://asynchttp.sourceforge.net/</a>? </p>
<p>"Asynchronous HTTP Client for Python</p>
<p>The 'asynchttp'' module is a logical extension of the Python library 'asynchat' module which is built on the 'asyncore' and 'select' modules. Our goal is to provide the functionality of the excellent 'httplib' module without using blocking sockets."</p>
<p>The project's last commit was 2001-05-29, so it looks dead. But it might be of interest anyway.</p>
<p>Disclaimer: I have not used it myself.</p>
<p>Also, <a href="http://effbot.org/zone/effnews-1.htm">this blog post</a> has some information on async HTTP.</p>
| 5 | 2009-09-02T14:09:07Z | [
"python",
"web-services",
"sockets"
] |
Reading a website with asyncore | 1,367,453 | <p>I would like to read a website asynchronously, which isnt possible with urllib as far as I know. Now I tried reading with with plain sockets, but HTTP is giving me hell.
I run into all kind of funky encodings, for example transfer-encoding: chunked, have to parse all that stuff manually, and I feel like coding C, not python at the moment. </p>
<p>Isnt there a nicer way like URLLib, asynchronously? I dont really feel like re-implementing the whole HTTP specification, when it's all been done before.</p>
<p>Twisted isnt an option currently.</p>
<p>Greetings, </p>
<p>Tom</p>
| 7 | 2009-09-02T12:39:25Z | 1,372,289 | <p>The furthest I came was using modified asynchttp, that codeape suggested. I have tried to use both asyncore/asynchat and asynchttp, with lots of pain. It took me far too long to try to fix all the bugs in it (there's a method handle_read, nearly copied from asyncore, only badly indented and was giving me headaches with chunked encoding). Also, asyncore and asynchat are best not used according to some hints I got on google.</p>
<p>I have settled with twisted, but that's obviously out of the question for you.</p>
<p>It might also depend what are you trying to do with your application and why you want async requests, if threads are an option or not, if you're doing GUI programming or something else so if you could shed some more inforation, that's always good. If not, I'd vote for threaded version suggested above, it offers much more readability and maintainability.</p>
| 1 | 2009-09-03T09:03:20Z | [
"python",
"web-services",
"sockets"
] |
Reading a website with asyncore | 1,367,453 | <p>I would like to read a website asynchronously, which isnt possible with urllib as far as I know. Now I tried reading with with plain sockets, but HTTP is giving me hell.
I run into all kind of funky encodings, for example transfer-encoding: chunked, have to parse all that stuff manually, and I feel like coding C, not python at the moment. </p>
<p>Isnt there a nicer way like URLLib, asynchronously? I dont really feel like re-implementing the whole HTTP specification, when it's all been done before.</p>
<p>Twisted isnt an option currently.</p>
<p>Greetings, </p>
<p>Tom</p>
| 7 | 2009-09-02T12:39:25Z | 5,132,953 | <p>Asyncore simple HTTP client example is pretty straightforward :) </p>
<p><a href="http://docs.python.org/library/asyncore.html" rel="nofollow">http://docs.python.org/library/asyncore.html</a></p>
<pre><code>import asyncore, socket
class HTTPClient(asyncore.dispatcher):
def __init__(self, host, path):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.connect( (host, 80) )
self.buffer = 'GET %s HTTP/1.0\r\n\r\n' % path
def handle_connect(self):
pass
def handle_close(self):
self.close()
def handle_read(self):
print self.recv(8192)
def writable(self):
return (len(self.buffer) > 0)
def handle_write(self):
sent = self.send(self.buffer)
self.buffer = self.buffer[sent:]
client = HTTPClient('www.python.org', '/')
asyncore.loop()
</code></pre>
| 1 | 2011-02-27T11:31:30Z | [
"python",
"web-services",
"sockets"
] |
How to decorate a method inside a class? | 1,367,514 | <p>Am attempting to decorate a method inside a class but python is throwing an error on me.
My class looks like this:</p>
<pre><code>from pageutils import formatHeader
myPage(object):
def __init__(self):
self.PageName = ''
def createPage(self):
pageHeader = self.createHeader()
@formatHeader #<----- decorator
def createHeader(self):
return "Page Header ",self.PageName
if __name__=="__main__":
page = myPage()
page.PageName = 'My Page'
page.createPage()
#------- pageutils.py --------------------
def formatHeader(fn):
def wrapped():
return '<div class="page_header">'+fn()+'</div>'
return wrapped
</code></pre>
<p>Python throws the following error</p>
<p>self.createHeader()
TypeError: wrapped() takes no arguments (1 given)</p>
<p>Where am i goofing</p>
<p>Gath</p>
| 35 | 2009-09-02T12:50:19Z | 1,367,530 | <p>Python automatically passes the class instance as reference. (The <code>self</code> argument which is seen in all class methods).</p>
<p>You could do:</p>
<pre><code>def formatHeader(fn):
def wrapped(self=None):
return '<div class="page_header">'+fn(self)+'</div>'
return wrapped
</code></pre>
| 27 | 2009-09-02T12:52:30Z | [
"python",
"decorator"
] |
How to decorate a method inside a class? | 1,367,514 | <p>Am attempting to decorate a method inside a class but python is throwing an error on me.
My class looks like this:</p>
<pre><code>from pageutils import formatHeader
myPage(object):
def __init__(self):
self.PageName = ''
def createPage(self):
pageHeader = self.createHeader()
@formatHeader #<----- decorator
def createHeader(self):
return "Page Header ",self.PageName
if __name__=="__main__":
page = myPage()
page.PageName = 'My Page'
page.createPage()
#------- pageutils.py --------------------
def formatHeader(fn):
def wrapped():
return '<div class="page_header">'+fn()+'</div>'
return wrapped
</code></pre>
<p>Python throws the following error</p>
<p>self.createHeader()
TypeError: wrapped() takes no arguments (1 given)</p>
<p>Where am i goofing</p>
<p>Gath</p>
| 35 | 2009-09-02T12:50:19Z | 1,367,567 | <p>You are omitting the self parameter which is present in the undecorated function (createHeader in your case).</p>
<pre><code>def formatHeader(fn):
from functools import wraps
@wraps(fn)
def wrapper(self):
return '<div class="page_header">'+fn(self)+'</div>'
return wrapper
</code></pre>
<p>If you are unsure about the signature of the function you want to decorate, you can make it rather general as follows:</p>
<pre><code>def formatHeader(fn):
from functools import wraps
@wraps(fn)
def wrapper(*args, **kw):
return '<div class="page_header">'+fn(*args, **kw)+'</div>'
return wrapper
</code></pre>
| 42 | 2009-09-02T13:01:30Z | [
"python",
"decorator"
] |
How to count possibilities in python lists | 1,367,550 | <p>Given a list like this:</p>
<pre><code>num = [1, 2, 3, 4, 5]
</code></pre>
<p>There are 10 three-element combinations:</p>
<pre><code>[123, 124, 125, 134, 135, 145, 234, 235, 245, 345]
</code></pre>
<p>How can I generate this list?</p>
| 3 | 2009-09-02T12:57:47Z | 1,367,582 | <p>Use <a href="http://docs.python.org/library/itertools.html#itertools.combinations" rel="nofollow">itertools.combinations</a>:</p>
<pre><code>import itertools
num = [1, 2, 3, 4, 5]
combinations = []
for combination in itertools.combinations(num, 3):
combinations.append(int("".join(str(i) for i in combination)))
# => [123, 124, 125, 134, 135, 145, 234, 235, 245, 345]
print len(combinations)
# => 10
</code></pre>
<p><strong>Edit</strong></p>
<p>You can skip int(), join(), and str() if you are only interested in the number of combinations. itertools.combinations() gives you tuples that may be good enough.</p>
| 10 | 2009-09-02T13:04:29Z | [
"python"
] |
How to count possibilities in python lists | 1,367,550 | <p>Given a list like this:</p>
<pre><code>num = [1, 2, 3, 4, 5]
</code></pre>
<p>There are 10 three-element combinations:</p>
<pre><code>[123, 124, 125, 134, 135, 145, 234, 235, 245, 345]
</code></pre>
<p>How can I generate this list?</p>
| 3 | 2009-09-02T12:57:47Z | 1,367,592 | <p>I believe you are looking for the <a href="http://en.wikipedia.org/wiki/Binomial%5Fcoefficient" rel="nofollow">binomial coefficient</a>:</p>
| 2 | 2009-09-02T13:06:09Z | [
"python"
] |
How to count possibilities in python lists | 1,367,550 | <p>Given a list like this:</p>
<pre><code>num = [1, 2, 3, 4, 5]
</code></pre>
<p>There are 10 three-element combinations:</p>
<pre><code>[123, 124, 125, 134, 135, 145, 234, 235, 245, 345]
</code></pre>
<p>How can I generate this list?</p>
| 3 | 2009-09-02T12:57:47Z | 1,367,598 | <p>You are talking about <a href="http://en.wikipedia.org/wiki/Combination" rel="nofollow">combinations</a>. There are <em>n!/(k! * (n - k)!)</em> ways to take <em>k</em> elements from a list of <em>n</em> elements. So:</p>
<pre><code>>>> num = [1, 2, 3, 4, 5]
>>> fac = lambda n: 1 if n < 2 else n * fac(n - 1)
>>> combos = lambda n, k: fac(n) / fac(k) / fac(n - k)
>>> combos(len(num), 3)
10
</code></pre>
<p>Use <a href="http://docs.python.org/library/itertools.html#itertools.combinations" rel="nofollow">itertools.combinations</a> only if you actually want to generate all combinations. <em>Not</em> if you just want to know the <em>number</em> of different combinations.</p>
<p>Also, there are more efficient ways to calculate the number of combinations than using the code shown above. For example,</p>
<pre><code>>>> from operator import truediv, mul
>>> from itertools import starmap
>>> from functools import reduce
>>> combos = lambda n, k: reduce(mul, starmap(truediv, zip(range(n, n - k, -1), range(k, 0, -1))))
>>> combos(len(num), 3)
10.0
</code></pre>
<p>(Note that this code uses floating point division!)</p>
| 5 | 2009-09-02T13:07:27Z | [
"python"
] |
How to count possibilities in python lists | 1,367,550 | <p>Given a list like this:</p>
<pre><code>num = [1, 2, 3, 4, 5]
</code></pre>
<p>There are 10 three-element combinations:</p>
<pre><code>[123, 124, 125, 134, 135, 145, 234, 235, 245, 345]
</code></pre>
<p>How can I generate this list?</p>
| 3 | 2009-09-02T12:57:47Z | 1,367,601 | <p><a href="http://docs.python.org/library/itertools.html#itertools.combinations" rel="nofollow"><code>itertools.combinations()</code></a>:</p>
<blockquote>
<p>Return r length subsequences of elements from the input iterable.</p>
<p>Combinations are emitted in lexicographic sort order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.</p>
<p>Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeat values in each combination.</p>
</blockquote>
<pre><code>>>> num = [1, 2, 3, 4, 5]
>>> [i for i in itertools.combinations(num,3)]
[(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 4, 5), (2, 3, 4), (2, 3, 5),
(2, 4, 5), (3, 4, 5)]
>>>
</code></pre>
| 2 | 2009-09-02T13:08:05Z | [
"python"
] |
How to create objects dynamically in an elegant way in python? | 1,367,819 | <p>I have two classes that I would like to merge into a composite. These two classes will continue to be used standalone and I don't want to modify them.
For some reasons, I want to let my composite class creating the objects. I am thinking about something like the code below (it is just an example) but I think it is complex and I don't like it very much. I guess that it could be improved by some techniques and tricks that I ignore.</p>
<p>Please note that the composite is designed to manage a lot of different classes with different constructor signatures.</p>
<p>What would recommend in order to improve this code?</p>
<pre><code>class Parent:
def __init__(self, x):
self.x = x
class A(Parent):
def __init__(self, x, a="a", b="b", c="c"):
Parent.__init__(self, x)
self.a, self.b, self.c = a, b, c
def do(self):
print self.x, self.a, self.b, self.c
class D(Parent):
def __init__(self, x, d):
Parent.__init__(self, x)
self.d = d
def do(self):
print self.x, self.d
class Composite(Parent):
def __init__(self, x, list_of_classes, list_of_args):
Parent.__init__(self, x)
self._objs = []
for i in xrange(len(list_of_classes)):
self._objs.append(self._make_object(list_of_classes[i], list_of_args[i]))
def _make_object(self, the_class, the_args):
if the_class is A:
a = the_args[0] if len(the_args)>0 else "a"
b = the_args[1] if len(the_args)>1 else "b"
c = the_args[2] if len(the_args)>2 else "c"
return the_class(self.x, a, b, c)
if the_class is D:
return the_class(self.x, the_args[0])
def do(self):
for o in self._objs: o.do()
compo = Composite("x", [A, D, A], [(), ("hello",), ("A", "B", "C")])
compo.do()
</code></pre>
| 4 | 2009-09-02T13:50:01Z | 1,368,196 | <p>You could shorten it by removing type-checking <code>_make_object</code>, and letting class constructors take care of the default arguments, e.g.</p>
<pre><code>class Composite(Parent):
def __init__(self, x, list_of_classes, list_of_args):
Parent.__init__(self, x)
self._objs = [
the_class(self.x, *the_args)
for the_class, the_args
in zip(list_of_classes, list_of_args)
if isinstance(the_class, Parent.__class__)
]
def do(self):
for o in self._objs: o.do()
</code></pre>
<p>This would also allow you to use it with new classes without modifying its code.</p>
| 3 | 2009-09-02T14:52:47Z | [
"python"
] |
Python methods: default parameter values are evaluated ONCE | 1,367,883 | <p>I've found a strange issue with subclassing and dictionary updates in New-Style Classes:</p>
<pre><code>Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on
win32
>>> class a(object):
... def __init__(self, props={}):
... self.props = props
...
>>> class b(a):
... def __init__(self, val = None):
... super(b, self).__init__()
... self.props.update({'arg': val})
...
>>> class c(b):
... def __init__(self, val):
... super(c, self).__init__(val)
...
>>> b_inst = b(2)
>>> b_inst.props
{'arg': 2}
>>> c_inst = c(3)
>>> c_inst.props
{'arg': 3}
>>> b_inst.props
{'arg': 3}
>>>
</code></pre>
<p>In debug, in second call (<code>c(3)</code>) you can see that within <code>a</code> constructor <code>self.props</code> is already equal to <code>{'arg': 2}</code>, and when <code>b</code> constructor is called after that, it becomes <code>{'arg': 3}</code> for both objects!</p>
<p>also, the order of constructors calling is:</p>
<pre><code> a, b # for b(2)
c, a, b # for c(3)
</code></pre>
<p>If you'll change <code>self.props.update()</code> with <code>self.props = {'arg': val}</code> in <code>b</code> constructor, everything will be ok, and will act as expected</p>
<p>But I really need to <em>update</em> this property, not to replace</p>
| 3 | 2009-09-02T14:00:28Z | 1,367,927 | <p>Your problem is in this line:</p>
<pre><code>def __init__(self, props={}):
</code></pre>
<p>{} is an mutable type. And in python default argument values are only evaluated once. That means all your instances are sharing the same dictionary object!</p>
<p>To fix this change it to:</p>
<pre><code>class a(object):
def __init__(self, props=None):
if is None:
props = {}
self.props = props
</code></pre>
| 5 | 2009-09-02T14:06:30Z | [
"python",
"dictionary",
"super"
] |
Python methods: default parameter values are evaluated ONCE | 1,367,883 | <p>I've found a strange issue with subclassing and dictionary updates in New-Style Classes:</p>
<pre><code>Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on
win32
>>> class a(object):
... def __init__(self, props={}):
... self.props = props
...
>>> class b(a):
... def __init__(self, val = None):
... super(b, self).__init__()
... self.props.update({'arg': val})
...
>>> class c(b):
... def __init__(self, val):
... super(c, self).__init__(val)
...
>>> b_inst = b(2)
>>> b_inst.props
{'arg': 2}
>>> c_inst = c(3)
>>> c_inst.props
{'arg': 3}
>>> b_inst.props
{'arg': 3}
>>>
</code></pre>
<p>In debug, in second call (<code>c(3)</code>) you can see that within <code>a</code> constructor <code>self.props</code> is already equal to <code>{'arg': 2}</code>, and when <code>b</code> constructor is called after that, it becomes <code>{'arg': 3}</code> for both objects!</p>
<p>also, the order of constructors calling is:</p>
<pre><code> a, b # for b(2)
c, a, b # for c(3)
</code></pre>
<p>If you'll change <code>self.props.update()</code> with <code>self.props = {'arg': val}</code> in <code>b</code> constructor, everything will be ok, and will act as expected</p>
<p>But I really need to <em>update</em> this property, not to replace</p>
| 3 | 2009-09-02T14:00:28Z | 1,367,928 | <p><code>props</code> should not have a default value like that. Do this instead:</p>
<pre><code>class a(object):
def __init__(self, props=None):
if props is None:
props = {}
self.props = props
</code></pre>
<p>This is a common python <a href="http://www.ferg.org/projects/python%5Fgotchas.html#contents%5Fitem%5F6rops" rel="nofollow">"gotcha"</a>.</p>
| 7 | 2009-09-02T14:06:48Z | [
"python",
"dictionary",
"super"
] |
Python methods: default parameter values are evaluated ONCE | 1,367,883 | <p>I've found a strange issue with subclassing and dictionary updates in New-Style Classes:</p>
<pre><code>Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on
win32
>>> class a(object):
... def __init__(self, props={}):
... self.props = props
...
>>> class b(a):
... def __init__(self, val = None):
... super(b, self).__init__()
... self.props.update({'arg': val})
...
>>> class c(b):
... def __init__(self, val):
... super(c, self).__init__(val)
...
>>> b_inst = b(2)
>>> b_inst.props
{'arg': 2}
>>> c_inst = c(3)
>>> c_inst.props
{'arg': 3}
>>> b_inst.props
{'arg': 3}
>>>
</code></pre>
<p>In debug, in second call (<code>c(3)</code>) you can see that within <code>a</code> constructor <code>self.props</code> is already equal to <code>{'arg': 2}</code>, and when <code>b</code> constructor is called after that, it becomes <code>{'arg': 3}</code> for both objects!</p>
<p>also, the order of constructors calling is:</p>
<pre><code> a, b # for b(2)
c, a, b # for c(3)
</code></pre>
<p>If you'll change <code>self.props.update()</code> with <code>self.props = {'arg': val}</code> in <code>b</code> constructor, everything will be ok, and will act as expected</p>
<p>But I really need to <em>update</em> this property, not to replace</p>
| 3 | 2009-09-02T14:00:28Z | 1,367,938 | <p>The short version: Do this:</p>
<pre><code>class a(object):
def __init__(self, props=None):
self.props = props if props is not None else {}
class b(a):
def __init__(self, val = None):
super(b, self).__init__()
self.props.update({'arg': val})
class c(b):
def __init__(self, val):
super(c, self).__init__(val)
</code></pre>
<p>The long version: </p>
<p>The function definition is evaluated exactly once, so every time you call it the same default argument is used. For this to work like you expected, the default arguments would have to be evaluated every time a function is called. But instead Python generates a function object once and adds the defaults to the object ( as <code>func_obj.func_defaults</code> ) </p>
| 1 | 2009-09-02T14:08:43Z | [
"python",
"dictionary",
"super"
] |
simplifying data structures and condition statements in python code | 1,367,913 | <p>I was wondering if there are any ways to simplify the following piece of Code. As you can see, there are numerous dicts being used as well as condition statements to weed out bad input data. Note that the trip rate values are not all inputed yet, the dicts are just copied and pasted for now</p>
<p><strong>EDIT</strong></p>
<p>In any of the rates, (x,y):z . x and y are correct, the z values are not as they're just copy/pasted</p>
<p>this code works in case you want to copy, paste, and test it</p>
<pre><code>import math
# step 1.4 return trip rates
def trip_rates( population_stratification, analysis_type, low_income, medium_income, high_income ):
''' this function returns the proper trip rate tuple to be used based on input
data
ADPT = Average Daily Person Trips per Household
pph = person per household
veh_hh = vehicles per household
(param_1, param_2): ADPT
'''
li = low_income
mi = medium_income
hi = high_income
# table 5 -
if analysis_type == 1:
if population_stratification == 1:
rates = {( li, 1 ):3.6, ( li, 2 ):6.5, ( li, 3 ):9.1, ( li, 4 ):11.5, ( li, 5 ): 13.8,
( mi, 1 ):3.9, ( mi, 2 ):7.3, ( mi, 3 ):10.0, ( mi, 4 ):13.1, ( mi, 5 ): 15.9,
( hi, 1 ):4.5, ( mi, 2 ):9.2, ( mi, 3 ):12.2, ( mi, 4 ):14.8, ( mi, 5 ): 18.2}
return rates
if population_stratification == 2:
rates = {
( li, 1 ):3.1, ( li, 2 ):6.3, ( li, 3 ):9.4, ( li, 4 ):12.5, ( li, 5 ): 14.7,
( mi, 1 ):4.8, ( mi, 2 ):7.2, ( mi, 3 ):10.1, ( mi, 4 ):13.3, ( mi, 5 ): 15.5,
( hi, 1 ):4.9, ( mi, 2 ):7.7, ( mi, 3 ):12.5, ( mi, 4 ):13.8, ( mi, 5 ): 16.7
}
return rates
if population_stratification == 3: #TODO: input actual rate
rates = {
( li, 1 ):3.6, ( li, 2 ):6.5, ( li, 3 ):9.1, ( li, 4 ):11.5, ( li, 5 ): 13.8,
( mi, 1 ):3.9, ( mi, 2 ):7.3, ( mi, 3 ):10.0, ( mi, 4 ):13.1, ( mi, 5 ): 15.9,
( hi, 1 ):4.5, ( mi, 2 ):9.2, ( mi, 3 ):12.2, ( mi, 4 ):14.8, ( mi, 5 ): 18.2
}
return rates
if population_stratification == 4: #TODO: input actual rate
rates = {
( li, 1 ):3.1, ( li, 2 ):6.3, ( li, 3 ):9.4, ( li, 4 ):12.5, ( li, 5 ): 14.7,
( mi, 1 ):4.8, ( mi, 2 ):7.2, ( mi, 3 ):10.1, ( mi, 4 ):13.3, ( mi, 5 ): 15.5,
( hi, 1 ):4.9, ( mi, 2 ):7.7, ( mi, 3 ):12.5, ( mi, 4 ):13.8, ( mi, 5 ): 16.7
}
return rates
#table 6
elif analysis_type == 2:
if population_stratification == 1: #TODO: Change rates
rates = {
( 0, 1 ):3.6, ( 0, 2 ):6.5, ( 0, 3 ):9.1, ( 0, 4 ):11.5, ( 0, 5 ): 13.8,
( 1, 1 ):3.9, ( 1, 2 ):7.3, ( 1, 3 ):10.0, ( 1, 4 ):13.1, ( 1, 5 ): 15.9,
( 2, 1 ):4.5, ( 2, 2 ):9.2, ( 2, 3 ):12.2, ( 2, 4 ):14.8, ( 2, 5 ): 18.2,
( 3, 1 ):4.5, ( 3, 2 ):9.2, ( 3, 3 ):12.2, ( 3, 4 ):14.8, ( 3, 5 ): 18.2
}
return rates
if population_stratification == 2: #TODO: Change rates
rates = {
( 0, 1 ):3.6, ( 0, 2 ):6.5, ( 0, 3 ):9.1, ( 0, 4 ):11.5, ( 0, 5 ): 13.8,
( 1, 1 ):3.9, ( 1, 2 ):7.3, ( 1, 3 ):10.0, ( 1, 4 ):13.1, ( 1, 5 ): 15.9,
( 2, 1 ):4.5, ( 2, 2 ):9.2, ( 2, 3 ):12.2, ( 2, 4 ):14.8, ( 2, 5 ): 18.2,
( 3, 1 ):4.5, ( 3, 2 ):9.2, ( 3, 3 ):12.2, ( 3, 4 ):14.8, ( 3, 5 ): 18.2
}
return rates
if population_stratification == 3: #TODO: Change rates
rates = {
( 0, 1 ):3.6, ( 0, 2 ):6.5, ( 0, 3 ):9.1, ( 0, 4 ):11.5, ( 0, 5 ): 13.8,
( 1, 1 ):3.9, ( 1, 2 ):7.3, ( 1, 3 ):10.0, ( 1, 4 ):13.1, ( 1, 5 ): 15.9,
( 2, 1 ):4.5, ( 2, 2 ):9.2, ( 2, 3 ):12.2, ( 2, 4 ):14.8, ( 2, 5 ): 18.2,
( 3, 1 ):4.5, ( 3, 2 ):9.2, ( 3, 3 ):12.2, ( 3, 4 ):14.8, ( 3, 5 ): 18.2
}
return rates
if population_stratification == 4: #TODO: Change rates
rates = {
( 0, 1 ):3.6, ( 0, 2 ):6.5, ( 0, 3 ):9.1, ( 0, 4 ):11.5, ( 0, 5 ): 13.8,
( 1, 1 ):3.9, ( 1, 2 ):7.3, ( 1, 3 ):10.0, ( 1, 4 ):13.1, ( 1, 5 ): 15.9,
( 2, 1 ):4.5, ( 2, 2 ):9.2, ( 2, 3 ):12.2, ( 2, 4 ):14.8, ( 2, 5 ): 18.2,
( 3, 1 ):4.5, ( 3, 2 ):9.2, ( 3, 3 ):12.2, ( 3, 4 ):14.8, ( 3, 5 ): 18.2
}
return rates
# table 7
elif analysis_type == 3:
if population_stratification == 1: #TODO: input actual rate
rates = {
( li, 0 ):3.6, ( li, 1 ):6.5, ( li, 2 ):9.1, ( li, 3 ):11.5,
( mi, 0 ):3.9, ( mi, 1 ):7.3, ( mi, 2 ):10.0, ( mi, 3 ):13.1,
( hi, 0 ):4.5, ( mi, 1 ):9.2, ( mi, 2 ):12.2, ( mi, 3 ):14.8
}
return rates
if population_stratification == 2: #TODO: input actual rate
rates = {
( li, 0 ):3.6, ( li, 1 ):6.5, ( li, 2 ):9.1, ( li, 3 ):11.5,
( mi, 0 ):3.9, ( mi, 1 ):7.3, ( mi, 2 ):10.0, ( mi, 3 ):13.1,
( hi, 0 ):4.5, ( mi, 1 ):9.2, ( mi, 2 ):12.2, ( mi, 3 ):14.8
}
return rates
if population_stratification == 3: #TODO: input actual rate
rates = {
( li, 0 ):3.6, ( li, 1 ):6.5, ( li, 2 ):9.1, ( li, 3 ):11.5,
( mi, 0 ):3.9, ( mi, 1 ):7.3, ( mi, 2 ):10.0, ( mi, 3 ):13.1,
( hi, 0 ):4.5, ( mi, 1 ):9.2, ( mi, 2 ):12.2, ( mi, 3 ):14.8
}
return rates
if population_stratification == 4: #TODO: input actual rate
rates = {
( li, 0 ):3.6, ( li, 1 ):6.5, ( li, 2 ):9.1, ( li, 3 ):11.5,
( mi, 0 ):3.9, ( mi, 1 ):7.3, ( mi, 2 ):10.0, ( mi, 3 ):13.1,
( hi, 0 ):4.5, ( mi, 1 ):9.2, ( mi, 2 ):12.2, ( mi, 3 ):14.8
}
return rates
def interpolate( population_stratification, analysis_type, low_income, medium_income, high_income, x, y ):
#get rates dict
rates = trip_rates( population_stratification, analysis_type, low_income, medium_income, high_income )
# dealing with x parameters
#when using income levels, x_1 and x_2 are li, mi, or hi
if analysis_type == 1 or analysis_type == 2 or analsis_type == 4:
if x < high_income and x >= medium_income:
x_1 = medium_income
x_2 = high_income
elif x < medium_income:
x_1 = low_income
x_2 = medium_income
else:
x_1 = high_income
x_2 = high_income
if analysis_type == 3:
if x >= 3:
x_1 = 3
x_2 = 3
else:
x_1 = int( math.floor( x ) )
x_2 = int( math.ceil( x ) )
# dealing with y parametrs
#when using persons per household, max number y = 5
if analysis_type == 1 or analysis_type == 4:
if y >= 5:
y_1 = 5
y_2 = 5
else:
y_1 = int( math.floor( y ) )
y_2 = int( math.ceil( y ) )
elif analysis_type == 2 or analysis_type == 3:
if y >= 5:
y_1 = 5
y_2 = 5
else:
y_1 = int( math.floor( y ) )
y_2 = int( math.ceil( y ) )
# denominator
z = ( ( x_2 - x_1 ) * ( y_2 - y_1 ) )
result = ( ( ( rates[( x_1, y_1 )] ) * ( ( x_2 - x ) * ( y_2 - y ) ) / ( z ) ) +
( ( rates[( x_2, y_1 )] ) * ( ( x - x_1 ) * ( y_2 - y ) ) / ( z ) ) +
( ( rates[( x_1, y_2 )] ) * ( ( x_2 - x ) * ( y - y_1 ) ) / ( z ) ) +
( ( rates[( x_2, y_2 )] ) * ( ( x - x_1 ) * ( y - y_1 ) ) / ( z ) ) )
return result
#test
low_income = 20000 #this is calculated using exchange rates
medium_income = 40000 # this is calculated using exchange rates
high_income = 60000 # this is calculated using exchange rates
population_stratification = 1 #inputed by user
analysis_type = 1 #inputed by user
x = 35234.34 #test income
y = 3.5 # test pph
print interpolate( population_stratification, analysis_type, low_income, medium_income, high_income, x, y )
</code></pre>
| 2 | 2009-09-02T14:05:33Z | 1,368,036 | <p>Well, where to start? Here is just a first observation:</p>
<p>You have a lot of data there, and it seems code and data are mixed into each other.</p>
<p>Data and Code should be separate. Data is an external source, something you modify or read in. You could probably adapt your code to quickly parse Data from a good editable representation to a representation useful for your algorithms. I suspect your code will be shorter, clearer, and less error prone (did you notice all of the 'rates' dictionaries have multiple keys, and you miss a lot of 'hi' keys?).</p>
<p>If you need better abstractions such as matrices and arrays of data, look into <code>numpy</code></p>
<hr>
<p>Edit 1</p>
<p>Did you count your number of dimensions? You have a many-dimensional matrix here with X dimensions:
analysis_type, population_stratification, income_level, index</p>
<p>If I see right this is a 3x4x3x3 (= 108 entries) "matrix" or "lookup table". If this is the data your model builds on, fine. But can't you put those numbers in a file, or table that you read in? Your code would be next to trivial.</p>
<hr>
<p>Edit 2</p>
<p>Ok, I'll bite for some minor python style: Testing for values in a Set or a Range.</p>
<p>Instead of:</p>
<pre><code>if analysis_type == 1 or analysis_type == 2 or analsis_type == 4:
</code></pre>
<p>you can use</p>
<pre><code>if analysis_type in (1, 2, 4):
</code></pre>
<p>or even using readable names as (CUBIC, ..) as suggested.</p>
<p>Instead of:</p>
<pre><code>if x < high_income and x >= medium_income:
</code></pre>
<p>you can used chained conditions; Python is one of the few programming languages where conditions chain to make nautral if statements:</p>
<pre><code>if medium_income <= x < high_income:
</code></pre>
<hr>
<p>Edit 3</p>
<p>More important than small code figures is of course code design and refactoring. Edit 2 can only give you some polish.</p>
<p>You should learn to loathe duplicate code.</p>
<p>Also, you have quite a lot of branches in one function. That is a good sign you should break it up into multiple functions. It can also reduce duplication. For example, when one variable like <code>analysis_type</code> can totally change what the function does, why have two different behaviors in one function? You shouldn't have the whole program in one function. Perhaps analysis_type == 3 is better expressed in its own function (as an example)?</p>
<p>Do you understand that your function <code>trip_rates</code> basically does an array lookup, where the array lookup is hardcoded as if ..: return .. if : return .., and the array is written out in full in the function? What if <code>trip_rates</code> could be implemented like this? Would it be possible?</p>
<pre><code>data_model = compute_table(low_income, ...)
return data_model[analysis_type][population_stratification]
</code></pre>
| 5 | 2009-09-02T14:26:25Z | [
"python",
"data-structures",
"conditional"
] |
simplifying data structures and condition statements in python code | 1,367,913 | <p>I was wondering if there are any ways to simplify the following piece of Code. As you can see, there are numerous dicts being used as well as condition statements to weed out bad input data. Note that the trip rate values are not all inputed yet, the dicts are just copied and pasted for now</p>
<p><strong>EDIT</strong></p>
<p>In any of the rates, (x,y):z . x and y are correct, the z values are not as they're just copy/pasted</p>
<p>this code works in case you want to copy, paste, and test it</p>
<pre><code>import math
# step 1.4 return trip rates
def trip_rates( population_stratification, analysis_type, low_income, medium_income, high_income ):
''' this function returns the proper trip rate tuple to be used based on input
data
ADPT = Average Daily Person Trips per Household
pph = person per household
veh_hh = vehicles per household
(param_1, param_2): ADPT
'''
li = low_income
mi = medium_income
hi = high_income
# table 5 -
if analysis_type == 1:
if population_stratification == 1:
rates = {( li, 1 ):3.6, ( li, 2 ):6.5, ( li, 3 ):9.1, ( li, 4 ):11.5, ( li, 5 ): 13.8,
( mi, 1 ):3.9, ( mi, 2 ):7.3, ( mi, 3 ):10.0, ( mi, 4 ):13.1, ( mi, 5 ): 15.9,
( hi, 1 ):4.5, ( mi, 2 ):9.2, ( mi, 3 ):12.2, ( mi, 4 ):14.8, ( mi, 5 ): 18.2}
return rates
if population_stratification == 2:
rates = {
( li, 1 ):3.1, ( li, 2 ):6.3, ( li, 3 ):9.4, ( li, 4 ):12.5, ( li, 5 ): 14.7,
( mi, 1 ):4.8, ( mi, 2 ):7.2, ( mi, 3 ):10.1, ( mi, 4 ):13.3, ( mi, 5 ): 15.5,
( hi, 1 ):4.9, ( mi, 2 ):7.7, ( mi, 3 ):12.5, ( mi, 4 ):13.8, ( mi, 5 ): 16.7
}
return rates
if population_stratification == 3: #TODO: input actual rate
rates = {
( li, 1 ):3.6, ( li, 2 ):6.5, ( li, 3 ):9.1, ( li, 4 ):11.5, ( li, 5 ): 13.8,
( mi, 1 ):3.9, ( mi, 2 ):7.3, ( mi, 3 ):10.0, ( mi, 4 ):13.1, ( mi, 5 ): 15.9,
( hi, 1 ):4.5, ( mi, 2 ):9.2, ( mi, 3 ):12.2, ( mi, 4 ):14.8, ( mi, 5 ): 18.2
}
return rates
if population_stratification == 4: #TODO: input actual rate
rates = {
( li, 1 ):3.1, ( li, 2 ):6.3, ( li, 3 ):9.4, ( li, 4 ):12.5, ( li, 5 ): 14.7,
( mi, 1 ):4.8, ( mi, 2 ):7.2, ( mi, 3 ):10.1, ( mi, 4 ):13.3, ( mi, 5 ): 15.5,
( hi, 1 ):4.9, ( mi, 2 ):7.7, ( mi, 3 ):12.5, ( mi, 4 ):13.8, ( mi, 5 ): 16.7
}
return rates
#table 6
elif analysis_type == 2:
if population_stratification == 1: #TODO: Change rates
rates = {
( 0, 1 ):3.6, ( 0, 2 ):6.5, ( 0, 3 ):9.1, ( 0, 4 ):11.5, ( 0, 5 ): 13.8,
( 1, 1 ):3.9, ( 1, 2 ):7.3, ( 1, 3 ):10.0, ( 1, 4 ):13.1, ( 1, 5 ): 15.9,
( 2, 1 ):4.5, ( 2, 2 ):9.2, ( 2, 3 ):12.2, ( 2, 4 ):14.8, ( 2, 5 ): 18.2,
( 3, 1 ):4.5, ( 3, 2 ):9.2, ( 3, 3 ):12.2, ( 3, 4 ):14.8, ( 3, 5 ): 18.2
}
return rates
if population_stratification == 2: #TODO: Change rates
rates = {
( 0, 1 ):3.6, ( 0, 2 ):6.5, ( 0, 3 ):9.1, ( 0, 4 ):11.5, ( 0, 5 ): 13.8,
( 1, 1 ):3.9, ( 1, 2 ):7.3, ( 1, 3 ):10.0, ( 1, 4 ):13.1, ( 1, 5 ): 15.9,
( 2, 1 ):4.5, ( 2, 2 ):9.2, ( 2, 3 ):12.2, ( 2, 4 ):14.8, ( 2, 5 ): 18.2,
( 3, 1 ):4.5, ( 3, 2 ):9.2, ( 3, 3 ):12.2, ( 3, 4 ):14.8, ( 3, 5 ): 18.2
}
return rates
if population_stratification == 3: #TODO: Change rates
rates = {
( 0, 1 ):3.6, ( 0, 2 ):6.5, ( 0, 3 ):9.1, ( 0, 4 ):11.5, ( 0, 5 ): 13.8,
( 1, 1 ):3.9, ( 1, 2 ):7.3, ( 1, 3 ):10.0, ( 1, 4 ):13.1, ( 1, 5 ): 15.9,
( 2, 1 ):4.5, ( 2, 2 ):9.2, ( 2, 3 ):12.2, ( 2, 4 ):14.8, ( 2, 5 ): 18.2,
( 3, 1 ):4.5, ( 3, 2 ):9.2, ( 3, 3 ):12.2, ( 3, 4 ):14.8, ( 3, 5 ): 18.2
}
return rates
if population_stratification == 4: #TODO: Change rates
rates = {
( 0, 1 ):3.6, ( 0, 2 ):6.5, ( 0, 3 ):9.1, ( 0, 4 ):11.5, ( 0, 5 ): 13.8,
( 1, 1 ):3.9, ( 1, 2 ):7.3, ( 1, 3 ):10.0, ( 1, 4 ):13.1, ( 1, 5 ): 15.9,
( 2, 1 ):4.5, ( 2, 2 ):9.2, ( 2, 3 ):12.2, ( 2, 4 ):14.8, ( 2, 5 ): 18.2,
( 3, 1 ):4.5, ( 3, 2 ):9.2, ( 3, 3 ):12.2, ( 3, 4 ):14.8, ( 3, 5 ): 18.2
}
return rates
# table 7
elif analysis_type == 3:
if population_stratification == 1: #TODO: input actual rate
rates = {
( li, 0 ):3.6, ( li, 1 ):6.5, ( li, 2 ):9.1, ( li, 3 ):11.5,
( mi, 0 ):3.9, ( mi, 1 ):7.3, ( mi, 2 ):10.0, ( mi, 3 ):13.1,
( hi, 0 ):4.5, ( mi, 1 ):9.2, ( mi, 2 ):12.2, ( mi, 3 ):14.8
}
return rates
if population_stratification == 2: #TODO: input actual rate
rates = {
( li, 0 ):3.6, ( li, 1 ):6.5, ( li, 2 ):9.1, ( li, 3 ):11.5,
( mi, 0 ):3.9, ( mi, 1 ):7.3, ( mi, 2 ):10.0, ( mi, 3 ):13.1,
( hi, 0 ):4.5, ( mi, 1 ):9.2, ( mi, 2 ):12.2, ( mi, 3 ):14.8
}
return rates
if population_stratification == 3: #TODO: input actual rate
rates = {
( li, 0 ):3.6, ( li, 1 ):6.5, ( li, 2 ):9.1, ( li, 3 ):11.5,
( mi, 0 ):3.9, ( mi, 1 ):7.3, ( mi, 2 ):10.0, ( mi, 3 ):13.1,
( hi, 0 ):4.5, ( mi, 1 ):9.2, ( mi, 2 ):12.2, ( mi, 3 ):14.8
}
return rates
if population_stratification == 4: #TODO: input actual rate
rates = {
( li, 0 ):3.6, ( li, 1 ):6.5, ( li, 2 ):9.1, ( li, 3 ):11.5,
( mi, 0 ):3.9, ( mi, 1 ):7.3, ( mi, 2 ):10.0, ( mi, 3 ):13.1,
( hi, 0 ):4.5, ( mi, 1 ):9.2, ( mi, 2 ):12.2, ( mi, 3 ):14.8
}
return rates
def interpolate( population_stratification, analysis_type, low_income, medium_income, high_income, x, y ):
#get rates dict
rates = trip_rates( population_stratification, analysis_type, low_income, medium_income, high_income )
# dealing with x parameters
#when using income levels, x_1 and x_2 are li, mi, or hi
if analysis_type == 1 or analysis_type == 2 or analsis_type == 4:
if x < high_income and x >= medium_income:
x_1 = medium_income
x_2 = high_income
elif x < medium_income:
x_1 = low_income
x_2 = medium_income
else:
x_1 = high_income
x_2 = high_income
if analysis_type == 3:
if x >= 3:
x_1 = 3
x_2 = 3
else:
x_1 = int( math.floor( x ) )
x_2 = int( math.ceil( x ) )
# dealing with y parametrs
#when using persons per household, max number y = 5
if analysis_type == 1 or analysis_type == 4:
if y >= 5:
y_1 = 5
y_2 = 5
else:
y_1 = int( math.floor( y ) )
y_2 = int( math.ceil( y ) )
elif analysis_type == 2 or analysis_type == 3:
if y >= 5:
y_1 = 5
y_2 = 5
else:
y_1 = int( math.floor( y ) )
y_2 = int( math.ceil( y ) )
# denominator
z = ( ( x_2 - x_1 ) * ( y_2 - y_1 ) )
result = ( ( ( rates[( x_1, y_1 )] ) * ( ( x_2 - x ) * ( y_2 - y ) ) / ( z ) ) +
( ( rates[( x_2, y_1 )] ) * ( ( x - x_1 ) * ( y_2 - y ) ) / ( z ) ) +
( ( rates[( x_1, y_2 )] ) * ( ( x_2 - x ) * ( y - y_1 ) ) / ( z ) ) +
( ( rates[( x_2, y_2 )] ) * ( ( x - x_1 ) * ( y - y_1 ) ) / ( z ) ) )
return result
#test
low_income = 20000 #this is calculated using exchange rates
medium_income = 40000 # this is calculated using exchange rates
high_income = 60000 # this is calculated using exchange rates
population_stratification = 1 #inputed by user
analysis_type = 1 #inputed by user
x = 35234.34 #test income
y = 3.5 # test pph
print interpolate( population_stratification, analysis_type, low_income, medium_income, high_income, x, y )
</code></pre>
| 2 | 2009-09-02T14:05:33Z | 1,368,110 | <p>As well with kaizer's suggestion about data and code, here are some simple cleanups:</p>
<p>The code</p>
<pre><code>if y >= 5:
y_1 = 5
y_2 = 5
else:
y_1 = int( math.floor( y ) )
y_2 = int( math.ceil( y ) )
</code></pre>
<p>can be written as</p>
<pre><code>min(5, int(math.floor(y))
</code></pre>
<p>or</p>
<pre><code>int(math.floor(min(5, y))
</code></pre>
<p>or even made a function:</p>
<pre><code>def limitedInt(v, maxV):
return min(5, int(math.floor(y))
</code></pre>
<p>Also I would recommend that instead of saying <code>analysis_type == 1</code> you say something like
<code>analysis_type = CUBIC</code> (i.e., an name that describes the analysis type) and set the name to 1. This will not simplify so much as make the code easier to read.</p>
<p>You might find the book <a href="http://martinfowler.com/books.html#refactoring" rel="nofollow">Refactoring</a> by Martin Fowler or <a href="http://rads.stackoverflow.com/amzn/click/0321109295" rel="nofollow">Refactoring Workbook</a> by William Wake as a way to learn about cleaning up code (<a href="http://refactoring.com/" rel="nofollow">the website</a> is also available, but without knowing about "code smells" described in the books, it is not as helpful.</p>
| 2 | 2009-09-02T14:41:05Z | [
"python",
"data-structures",
"conditional"
] |
Java equivalent of a Python functionality -> set(string) | 1,368,181 | <p>I want to mimic a Python functionality in Java.
In Python if I want unique characters in a string I can do just,</p>
<pre><code>text = "i am a string"
print set(text) # o/p is set(['a', ' ', 'g', 'i', 'm', 'n', 's', 'r', 't'])
</code></pre>
<p>How can I do this in Java trivially or directly? </p>
| 2 | 2009-09-02T14:51:34Z | 1,368,214 | <pre><code>String str = "i am a string";
System.out.println(new HashSet<String>(Arrays.asList(str.split(""))));
</code></pre>
<p>EDIT: For those who object that they aren't exactly equivalent because str.split will include an empty string in the set, we can do it even more verbose:</p>
<pre><code>String str = "i am a string";
Set<String> set = new HashSet<String>(Arrays.asList(str.split("")));
set.remove("");
System.out.println(set);
</code></pre>
<p>But of course it depends on what you need to accomplish.</p>
| 7 | 2009-09-02T14:54:58Z | [
"java",
"python",
"set"
] |
How do I unit test Django Views? | 1,368,255 | <p>I want to begin integrating unit tests into my Django projects and I've discovered unit testing a view to be tricky because of the way Django implements views with functions. </p>
<p>For example, each function is a view/page in Django if the function has a URL.</p>
<p>How do I unit test Django views?</p>
| 8 | 2009-09-02T15:02:23Z | 1,368,389 | <p>I'm not sure how testing a view is tricky.</p>
<p>You just use the <a href="https://docs.djangoproject.com/en/dev/topics/testing/tools/#the-test-client" rel="nofollow">test client</a>.</p>
<p>Code coverage is easy. You reason how how a URL request maps to a code path and make the appropriate URL requests.</p>
<p>You can, if you want, call the view functions "manually" by creating a Request object and examining the Response object, but this is too much work.</p>
<p>If you have doubts about your code coverage, that's a good thing. It means you have code you can't easily map to a URL (which is all a user can ever see of a web application.) If you have code that doesn't map to a URL, you should probably either (a) delete the code or (b) refactor it into a separate module.</p>
<p>We have lots of modules outside our view functions. Our view functions import these modules. We test these "outside the view function" modules with ordinary unittest.</p>
<hr>
<p>Here's a typical structure.</p>
<pre><code>some_big_product/
|-- __init__.py
|-- settings.py
|-- urls.py
|-- logging.ini
|-- other_global_files.py
|-- an_app_1/
| |-- __init__.py
| |-- urls.py
| |-- models.py
| |-- views.py
| |-- tests.py <-- the generic Django testing
| |-- app_specific_module.py
| |-- app_specific_package/
| | |-- __init__.py
| |-- test_app_specific_module.py <-- unittest
| |-- test_app_specific_package.py
|-- generic_module.py
|-- generic_package/
| |-- __init__.py
|-- tests/
| |-- test_this.py
| |-- test_that.py
| |-- test_all.py <-- not always practical
|-- scripts/
|-- run_tests.sh
</code></pre>
| 9 | 2009-09-02T15:26:45Z | [
"python",
"django",
"unit-testing",
"views"
] |
How do I unit test Django Views? | 1,368,255 | <p>I want to begin integrating unit tests into my Django projects and I've discovered unit testing a view to be tricky because of the way Django implements views with functions. </p>
<p>For example, each function is a view/page in Django if the function has a URL.</p>
<p>How do I unit test Django views?</p>
| 8 | 2009-09-02T15:02:23Z | 1,368,848 | <p>django.test.client should have everything you need for basic unit testing of the view. I also really like <a href="http://twill.idyll.org/" rel="nofollow">twill</a> and <a href="http://seleniumhq.org/" rel="nofollow">selenium</a> for testing the full stack. </p>
| 2 | 2009-09-02T16:44:29Z | [
"python",
"django",
"unit-testing",
"views"
] |
How do I unit test Django Views? | 1,368,255 | <p>I want to begin integrating unit tests into my Django projects and I've discovered unit testing a view to be tricky because of the way Django implements views with functions. </p>
<p>For example, each function is a view/page in Django if the function has a URL.</p>
<p>How do I unit test Django views?</p>
| 8 | 2009-09-02T15:02:23Z | 1,368,999 | <p>You could try <a href="http://github.com/42/tddspry/tree/master" rel="nofollow">tddspry</a> - collection of helpers to test Django with nosetests and twill. Nose also have coverage plugin which generate pretty reports of the coverage. </p>
| 0 | 2009-09-02T17:09:36Z | [
"python",
"django",
"unit-testing",
"views"
] |
python file-like buffer object | 1,368,261 | <p>I've written a buffer class that provides a File-like interface with <code>read</code>, <code>write</code>, <code>seek</code>, <code>tell</code>, <code>flush</code> methods to a simple string in memory. Of course it is incomplete (e.g. I didn't write <code>readline</code>). It's purpose is to be filled by a background thread from some external data source, but let a user treat it like a file. I'd expect it to contain a relatively small amount of data (maybe 50K max)</p>
<p>Is there a better way to do this instead of writing it from scratch?</p>
| 12 | 2009-09-02T15:03:03Z | 1,368,272 | <p>You can use the standard Python modules <a href="http://docs.python.org/2/library/stringio.html" rel="nofollow"><code>StringIO</code></a> or <a href="http://docs.python.org/2/library/stringio.html#module-cStringIO" rel="nofollow"><code>cStringIO</code></a> to obtain an in-memory buffer which implements the <a href="http://docs.python.org/2/library/stdtypes.html#bltin-file-objects" rel="nofollow">file interface</a>.</p>
<p><code>cStringIO</code> is implemented in C, and will be faster, so you should use that version if possible.</p>
<p>If you're using Python 3 you should use the <a href="https://docs.python.org/3/library/io.html#io.StringIO" rel="nofollow"><code>io.StringIO</code></a> instead of <code>StringIO</code> and <a href="https://docs.python.org/3/library/io.html#io.BytesIO" rel="nofollow"><code>io.BytesIO</code></a> instead of <code>cStringIO</code>.</p>
| 18 | 2009-09-02T15:04:48Z | [
"python",
"io",
"buffer"
] |
python file-like buffer object | 1,368,261 | <p>I've written a buffer class that provides a File-like interface with <code>read</code>, <code>write</code>, <code>seek</code>, <code>tell</code>, <code>flush</code> methods to a simple string in memory. Of course it is incomplete (e.g. I didn't write <code>readline</code>). It's purpose is to be filled by a background thread from some external data source, but let a user treat it like a file. I'd expect it to contain a relatively small amount of data (maybe 50K max)</p>
<p>Is there a better way to do this instead of writing it from scratch?</p>
| 12 | 2009-09-02T15:03:03Z | 1,368,274 | <p>I think you might be looking for <code>StringIO</code>.</p>
| 6 | 2009-09-02T15:04:57Z | [
"python",
"io",
"buffer"
] |
pywikipedia login.py socket.error: (10060, 'Operation timed out') | 1,368,266 | <p>I'm totally new to python, so hopefully someone can help if I'm doing something obviously wrong. I'm trying to create and run a simple pywikipedia bot on vocabularies.referata.com, a semantic mediawiki site. I downloaded the pywikipedia distro and created a family file:</p>
<pre><code>import config, family, urllib # REQUIRED
class Family(family.Family): # REQUIRED
def __init__(self): # REQUIRED
family.Family.__init__(self) # REQUIRED
self.name = 'explicator' # REQUIRED; replace with actual name
self.langs = { # REQUIRED
'en': 'vocabularies.referata.com', # Include one line for each wiki in family
}
</code></pre>
<p>I've created a user, wikibot, and run:</p>
<pre><code>python generate_user_files.py
</code></pre>
<p>as per instructions on:</p>
<pre><code>http://meta.wikimedia.org/wiki/Using_the_python_wikipediabot
</code></pre>
<p>When I try to run:</p>
<pre><code>python login.py
</code></pre>
<p>I'm getting the following error:</p>
<pre><code>C:\pywikipedia>python login.py
Password for user wikibot on explicator:en:
Logging in to explicator:en as wikibot
Traceback (most recent call last):
File "login.py", line 376, in <module>
main()
File "login.py", line 372, in main
loginMan.login()
File "login.py", line 261, in login
cookiedata = self.getCookie(api)
File "login.py", line 178, in getCookie
response, data = self.site.postData(address, self.site.urlEncode(predata))
File "C:\pywikipedia\wikipedia.py", line 4915, in postData
conn.endheaders()
File "C:\Python25\lib\httplib.py", line 860, in endheaders
self._send_output()
File "C:\Python25\lib\httplib.py", line 732, in _send_output
self.send(msg)
File "C:\Python25\lib\httplib.py", line 699, in send
self.connect()
File "C:\Python25\lib\httplib.py", line 683, in connect
raise socket.error, msg
socket.error: (10060, 'Operation timed out')
</code></pre>
<p>Is their something stupid/apparent that I need to check or am doing wrong? I'm behind a firewall, would this be the problem? (and if so what steps do I need to take to fix it).</p>
<p>thanks for any help
Stuart</p>
| 0 | 2009-09-02T15:03:34Z | 1,369,062 | <p>I'm not familiar w/ pywikipedia =p, but the problem is at least about connection rather than python: the socket connection fails to be established at the beginning.</p>
<ul>
<li>Is the post url, <code>address</code> in the login.py L178 , correct? Any typo or misconfiguration? </li>
<li>Is the url accessible? You could try to directly visit the url in browser and see if there is any http response. If the server is reachable, you could check whether it's listening on certain port like 80, by <code>netstat -ant</code>, <code>netstat -anptcp</code> or similar. On windows, a firewall w/ default settings may block communication, you could see whether there is any warning dialog waiting for confirm, or check the fireware log. Also, you need to have Administrator privilege to use port 80.</li>
</ul>
| 0 | 2009-09-02T17:23:52Z | [
"python",
"mediawiki",
"pywikipedia"
] |
pywikipedia login.py socket.error: (10060, 'Operation timed out') | 1,368,266 | <p>I'm totally new to python, so hopefully someone can help if I'm doing something obviously wrong. I'm trying to create and run a simple pywikipedia bot on vocabularies.referata.com, a semantic mediawiki site. I downloaded the pywikipedia distro and created a family file:</p>
<pre><code>import config, family, urllib # REQUIRED
class Family(family.Family): # REQUIRED
def __init__(self): # REQUIRED
family.Family.__init__(self) # REQUIRED
self.name = 'explicator' # REQUIRED; replace with actual name
self.langs = { # REQUIRED
'en': 'vocabularies.referata.com', # Include one line for each wiki in family
}
</code></pre>
<p>I've created a user, wikibot, and run:</p>
<pre><code>python generate_user_files.py
</code></pre>
<p>as per instructions on:</p>
<pre><code>http://meta.wikimedia.org/wiki/Using_the_python_wikipediabot
</code></pre>
<p>When I try to run:</p>
<pre><code>python login.py
</code></pre>
<p>I'm getting the following error:</p>
<pre><code>C:\pywikipedia>python login.py
Password for user wikibot on explicator:en:
Logging in to explicator:en as wikibot
Traceback (most recent call last):
File "login.py", line 376, in <module>
main()
File "login.py", line 372, in main
loginMan.login()
File "login.py", line 261, in login
cookiedata = self.getCookie(api)
File "login.py", line 178, in getCookie
response, data = self.site.postData(address, self.site.urlEncode(predata))
File "C:\pywikipedia\wikipedia.py", line 4915, in postData
conn.endheaders()
File "C:\Python25\lib\httplib.py", line 860, in endheaders
self._send_output()
File "C:\Python25\lib\httplib.py", line 732, in _send_output
self.send(msg)
File "C:\Python25\lib\httplib.py", line 699, in send
self.connect()
File "C:\Python25\lib\httplib.py", line 683, in connect
raise socket.error, msg
socket.error: (10060, 'Operation timed out')
</code></pre>
<p>Is their something stupid/apparent that I need to check or am doing wrong? I'm behind a firewall, would this be the problem? (and if so what steps do I need to take to fix it).</p>
<p>thanks for any help
Stuart</p>
| 0 | 2009-09-02T15:03:34Z | 1,375,566 | <p>Works for me, sorry. I just created an account, and used your family file. It seems to be on your side.</p>
<pre><code>$ python login.py -v -v -family:explicator -lang:en
Pywikipediabot [http] trunk/pywikipedia (r6858, May 08 2009, 15:23:29)
Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3]
WARNING: Using -v -v on login.py might leak private data. When sharing, please double check your password is not readable and log out your bots session.
Password for user NicDumZ on explicator:en:
Logging in to explicator:en as NicDumZ
self.site.postData(/w/index.php?title=Special:Userlogin&useskin=monobook&action=submit, wpSkipCookieCheck=1&wpPassword=XXXXX&wpDomain=&wpRemember=1&wpLoginattempt=Aanmelden%20%26%20Inschrijven&wpName=NicDumZ)
302/Found
Date: Thu, 03 Sep 2009 19:46:47 GMT
Server: Apache
Cache-Control: private, must-revalidate, max-age=0
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Set-Cookie: referata_session=XXXXXXXXXXdab8c53151d27046d68473; path=/; HttpOnly
Set-Cookie: referataUserID=4; expires=Sat, 03-Oct-2009 19:46:48 GMT; path=/; httponly
Set-Cookie: referataUserName=NicDumZ; expires=Sat, 03-Oct-2009 19:46:48 GMT; path=/; httponly
Set-Cookie: referatasession=XXXXXXXXXX270504613b1d26dfef82e6; expires=Sat, 03-Oct-2009 19:46:48 GMT; path=/; httponly
Vary: Accept-Encoding,Cookie
X-Vary-Options: Accept-Encoding;list-contains=gzip,Cookie;string-contains=referataToken;string-contains=referataLoggedOut;string-contains=referata_session
Location: http://vocabularies.referata.com/wiki/Main_Page
Content-Encoding: gzip
Transfer-Encoding: chunked
Content-Type: text/html; charset=utf-8
Should be logged in now
</code></pre>
<p>Can you try the same, with -v -v options so that I can help you debug that issue? Please comment back so I can get your updates.</p>
| 0 | 2009-09-03T19:49:58Z | [
"python",
"mediawiki",
"pywikipedia"
] |
How does Django determine if an uploaded image is valid? | 1,368,724 | <p>I'm trying to add images to my models in my Django app.</p>
<p>models.py</p>
<pre><code>class ImageMain(models.Model):
"""This is the Main Image of the product"""
product = models.ForeignKey(Product)
photo = models.ImageField(upload_to='products')
</code></pre>
<p>In development mode, every time I try to upload the image via Django admin, I keep getting:</p>
<pre><code>Upload a valid image. The file you uploaded was either not an image or a corrupted image.
</code></pre>
<p>The jpg I'm trying to upload can be viewed with os X Preview so it would seem to be valid.</p>
<p>It seems the problem is Python Imaging Library doesn't recognize it as an image. Why would that be happening with a valid image?</p>
<p>PIL is installed, verified via the Django shell.</p>
| 3 | 2009-09-02T16:21:21Z | 1,368,786 | <p>According to Django's source code. Those three lines are responsible for verifying images:</p>
<pre><code>from PIL import Image
trial_image = Image.open(file)
trial_image.verify()
</code></pre>
<p>The image type could be unsupported by PIL. Check the list of supported formats <a href="http://www.pythonware.com/library/pil/handbook/index.htm">here</a></p>
| 11 | 2009-09-02T16:30:35Z | [
"python",
"django",
"python-imaging-library"
] |
How does Django determine if an uploaded image is valid? | 1,368,724 | <p>I'm trying to add images to my models in my Django app.</p>
<p>models.py</p>
<pre><code>class ImageMain(models.Model):
"""This is the Main Image of the product"""
product = models.ForeignKey(Product)
photo = models.ImageField(upload_to='products')
</code></pre>
<p>In development mode, every time I try to upload the image via Django admin, I keep getting:</p>
<pre><code>Upload a valid image. The file you uploaded was either not an image or a corrupted image.
</code></pre>
<p>The jpg I'm trying to upload can be viewed with os X Preview so it would seem to be valid.</p>
<p>It seems the problem is Python Imaging Library doesn't recognize it as an image. Why would that be happening with a valid image?</p>
<p>PIL is installed, verified via the Django shell.</p>
| 3 | 2009-09-02T16:21:21Z | 1,368,795 | <p>I looked into the Django source, in <code>django/forms/fields.py</code>, in the <code>ImageField</code> class. Django actually does use PIL to determine when an image is valid.</p>
| 0 | 2009-09-02T16:32:53Z | [
"python",
"django",
"python-imaging-library"
] |
How does Django determine if an uploaded image is valid? | 1,368,724 | <p>I'm trying to add images to my models in my Django app.</p>
<p>models.py</p>
<pre><code>class ImageMain(models.Model):
"""This is the Main Image of the product"""
product = models.ForeignKey(Product)
photo = models.ImageField(upload_to='products')
</code></pre>
<p>In development mode, every time I try to upload the image via Django admin, I keep getting:</p>
<pre><code>Upload a valid image. The file you uploaded was either not an image or a corrupted image.
</code></pre>
<p>The jpg I'm trying to upload can be viewed with os X Preview so it would seem to be valid.</p>
<p>It seems the problem is Python Imaging Library doesn't recognize it as an image. Why would that be happening with a valid image?</p>
<p>PIL is installed, verified via the Django shell.</p>
| 3 | 2009-09-02T16:21:21Z | 1,369,729 | <p>Did you try uploading image format like gif or png? It might be that your PIL was not built with the jpeg lib properly. I had a similar issue with Django on Ubuntu. If you have ever seen the error message <code>decoder jpeg not available</code>, check this <a href="http://effbot.org/zone/pil-decoder-jpeg-not-available.htm" rel="nofollow">link</a>. Relevant line from the link:</p>
<pre><code>$ cd libImaging
$ ./configure --with-jpeg=/somelib/lib --with-zlib=/somelib/lib
</code></pre>
| 2 | 2009-09-02T19:46:02Z | [
"python",
"django",
"python-imaging-library"
] |
Split a list of dates by another list of dates | 1,368,802 | <p>I have a number of nodes in a network. The nodes send status information every hour to indicate that they are alive. So i have a list of Nodes and the time when they were last alive. I want to graph the number of alive nodes over the time.</p>
<p>The list of nodes is sorted by the time they were last alive but i cant figure out a nice way to count how many are alive at a each date.</p>
<pre><code>from datetime import datetime, timedelta
seen = [ n.last_seen for n in c.nodes ] # a list of datetimes
seen.sort()
start = seen[0]
end = seen[-1]
diff = end - start
num_points = 100
step = diff / num_points
num = len( c.nodes )
dates = [ start + i * step for i in range( num_points ) ]
</code></pre>
<p>What i want is basically </p>
<pre><code>alive = [ len([ s for s in seen if s > date]) for date in dates ]
</code></pre>
<p>but thats not really efficient. The solution should use the fact that the <code>seen</code> list is sorted and not loop over the whole list for every date.</p>
| 1 | 2009-09-02T16:34:16Z | 1,368,905 | <p>The python <a href="http://docs.python.org/library/bisect.html" rel="nofollow">bisect module</a> will find the correct index for you, and you can deduct the number of items before and after.</p>
<p>If I'm understanding right, that would be O(dates) * O(log(seen))</p>
<p><hr /></p>
<p>Edit 1</p>
<p>It should be possible to do in one pass, just like SilentGhost demonstrates. However,itertools.groupby works fine with sorted data, it should be able to do something here, perhaps like this (this is more than O(n) but could be improved):</p>
<pre><code>import itertools
# numbers are easier to make up now
seen = [-1, 10, 12, 15, 20, 75]
dates = [5, 15, 25, 50, 100]
def finddate(s, dates):
"""Find the first date in @dates larger than s"""
for date in dates:
if s < date:
break
return date
for date, group in itertools.groupby(seen, key=lambda s: finddate(s, dates)):
print date, list(group)
</code></pre>
| 1 | 2009-09-02T16:53:04Z | [
"python",
"performance"
] |
Split a list of dates by another list of dates | 1,368,802 | <p>I have a number of nodes in a network. The nodes send status information every hour to indicate that they are alive. So i have a list of Nodes and the time when they were last alive. I want to graph the number of alive nodes over the time.</p>
<p>The list of nodes is sorted by the time they were last alive but i cant figure out a nice way to count how many are alive at a each date.</p>
<pre><code>from datetime import datetime, timedelta
seen = [ n.last_seen for n in c.nodes ] # a list of datetimes
seen.sort()
start = seen[0]
end = seen[-1]
diff = end - start
num_points = 100
step = diff / num_points
num = len( c.nodes )
dates = [ start + i * step for i in range( num_points ) ]
</code></pre>
<p>What i want is basically </p>
<pre><code>alive = [ len([ s for s in seen if s > date]) for date in dates ]
</code></pre>
<p>but thats not really efficient. The solution should use the fact that the <code>seen</code> list is sorted and not loop over the whole list for every date.</p>
| 1 | 2009-09-02T16:34:16Z | 1,368,951 | <p>this generator traverses the list only once:</p>
<pre><code>def get_alive(seen, dates):
c = len(seen)
for date in dates:
for s in seen[-c:]:
if s >= date: # replaced your > for >= as it seems to make more sense
yield c
break
else:
c -= 1
</code></pre>
| 2 | 2009-09-02T16:59:53Z | [
"python",
"performance"
] |
Split a list of dates by another list of dates | 1,368,802 | <p>I have a number of nodes in a network. The nodes send status information every hour to indicate that they are alive. So i have a list of Nodes and the time when they were last alive. I want to graph the number of alive nodes over the time.</p>
<p>The list of nodes is sorted by the time they were last alive but i cant figure out a nice way to count how many are alive at a each date.</p>
<pre><code>from datetime import datetime, timedelta
seen = [ n.last_seen for n in c.nodes ] # a list of datetimes
seen.sort()
start = seen[0]
end = seen[-1]
diff = end - start
num_points = 100
step = diff / num_points
num = len( c.nodes )
dates = [ start + i * step for i in range( num_points ) ]
</code></pre>
<p>What i want is basically </p>
<pre><code>alive = [ len([ s for s in seen if s > date]) for date in dates ]
</code></pre>
<p>but thats not really efficient. The solution should use the fact that the <code>seen</code> list is sorted and not loop over the whole list for every date.</p>
| 1 | 2009-09-02T16:34:16Z | 1,369,460 | <p>I took SilentGhosts generator solution a bit further using explicit iterators. This is the linear time solution i was thinking of. </p>
<pre><code>def splitter( items, breaks ):
""" assuming `items` and `breaks` are sorted """
c = len( items )
items = iter(items)
item = items.next()
breaks = iter(breaks)
breaker = breaks.next()
while True:
if breaker > item:
for it in items:
c -= 1
if it >= breaker:
item = it
yield c
break
else:# no item left that is > the current breaker
yield 0 # 0 items left for the current breaker
# and 0 items left for all other breaks, since they are > the current
for _ in breaks:
yield 0
break # and done
else:
yield c
for br in breaks:
if br > item:
breaker = br
break
yield c
else:
# there is no break > any item in the list
break
</code></pre>
| 1 | 2009-09-02T18:45:35Z | [
"python",
"performance"
] |
Rose diagrams in Google Chart | 1,368,822 | <p>I searched around for ways to make rose diagrams (circular histograms) in Google Chart. The API has only radar diagrams, so it seems not technically possible (am I correct?). This <a href="http://www.carloslabs.com/node/18" rel="nofollow">wind rose example</a> was the closest I came to a solution.</p>
<p>Because I needed them, I figured out a way to fake them quickly using the Radar plots, Python and the <a href="http://code.google.com/p/google-chartwrapper/" rel="nofollow">Google-Chartwrapper</a> library. There's a (non-technical) <a href="http://positivelyglorious.com/software-media/wow-fully-functional-rose-diagrams-with-google-chart/" rel="nofollow">write-up available</a> and the code is on <a href="http://github.com/Mettadore/PyGoogleRose" rel="nofollow">Github</a>.</p>
<p><strong>Before I take this further (i.e. clean code, abstract, waste more time, etc.), has anyone else seen examples of Rose diagrams in Google Chart that might be useful?</strong></p>
<p>(By the way, I know about matplotlib, etc. I'm using Python 3.x out of necessity and, as yet, the graphing libraries haven't caught up enough to use as I need them. See also SO question 418835))</p>
| 1 | 2009-09-02T16:39:08Z | 1,644,195 | <p>Well, it looks like no-one has any other examples. I DID decide to play around with this to see what else is possible and created a quick proof of concept for <a href="http://rose-clock.mettadore.com" rel="nofollow">time-based rose diagrams</a>. It's just a silly thing to show your relative Twitter posting amount by time of day, but shows how Google Chart can be used for rose diagrams. The problem here, and a problem in general that this has illustrated with Google Chart, is that you cannot have embedded data contained in the chart, with drill-down capabilities, popups, etc. (as you could with a Javascript/Flex/other solution).</p>
<p>It'd be nice if there were a Google Chart-style API that was javascript based to allow embedded data.</p>
| 1 | 2009-10-29T14:39:14Z | [
"python",
"google-visualization",
"histogram"
] |
Default encoding of exception messages | 1,369,089 | <p>The following code examines the behaviour of the <code>float()</code> method when fed a non-ascii symbol:</p>
<pre><code>import sys
try:
float(u'\xbd')
except ValueError as e:
print sys.getdefaultencoding() # in my system, this is 'ascii'
print e[0].decode('latin-1') # u'invalid literal for float(): ' followed by the 1/2 (one half) character
print unicode(e[0]) # raises "UnicodeDecodeError: 'ascii' codec can't decode byte 0xbd in position 29: ordinal not in range(128)"
</code></pre>
<p>My question: <strong>why is the error message <code>e[0]</code> encoded in Latin-1?</strong> The default encoding is Ascii, and this seems to be what <code>unicode()</code> expects.</p>
<p>Platform is Ubuntu 9.04, Python 2.6.2</p>
| 6 | 2009-09-02T17:27:16Z | 1,369,177 | <p>The ASCII encoding only includes the bytes with values <code><= 127</code>. The range of characters represented by these bytes is identical in most encodings; in other words, "A" is <code>chr(65)</code> in ASCII, in latin-1, in UTF-8, and so on.</p>
<p>The one half symbol, however, is not part of the ASCII character set, so when Python tries to encode this symbol into ASCII, it can do nothing but fail.</p>
<p><strong>Update:</strong> Here's what happens (I assume we're talking CPython):</p>
<p><code>float(u'\xbd')</code> leads to <code>PyFloat_FromString</code> in <a href="http://svn.python.org/view/python/branches/release26-maint/Objects/floatobject.c?revision=72566&view=markup" rel="nofollow">floatobject.c</a> being called. This function, giving a unicode object, in turn calls <code>PyUnicode_EncodeDecimal</code> in <a href="http://svn.python.org/view/python/branches/release26-maint/Objects/unicodeobject.c?revision=74576&view=markup" rel="nofollow">unicodeobject.c</a> being called. From skimming over the code, I get it that this function turns the unicode object into a string by replacing every character with a unicode codepoint <code><256</code> with the byte of that value, i.e. the one half character, having the codepoint 189, is turned into <code>chr(89)</code>.</p>
<p>Then, <code>PyFloat_FromString</code> does its work as usual. At this moment, it's working with a regular string, which happens to be containing a non-ASCII range byte. It doesn't care about this; it just finds a byte that's not a digit, a period or the like, so it raises the value error.</p>
<p>The argument to this exception is a string </p>
<pre><code>"invalid literal for float(): " + evil_string
</code></pre>
<p>That's fine; an exception message is, after all, a string. It's only when you try to decode this string, using the default encoding ASCII, that this turns into a problem.</p>
| 2 | 2009-09-02T17:49:23Z | [
"python",
"exception",
"encoding",
"python-2.x"
] |
Default encoding of exception messages | 1,369,089 | <p>The following code examines the behaviour of the <code>float()</code> method when fed a non-ascii symbol:</p>
<pre><code>import sys
try:
float(u'\xbd')
except ValueError as e:
print sys.getdefaultencoding() # in my system, this is 'ascii'
print e[0].decode('latin-1') # u'invalid literal for float(): ' followed by the 1/2 (one half) character
print unicode(e[0]) # raises "UnicodeDecodeError: 'ascii' codec can't decode byte 0xbd in position 29: ordinal not in range(128)"
</code></pre>
<p>My question: <strong>why is the error message <code>e[0]</code> encoded in Latin-1?</strong> The default encoding is Ascii, and this seems to be what <code>unicode()</code> expects.</p>
<p>Platform is Ubuntu 9.04, Python 2.6.2</p>
| 6 | 2009-09-02T17:27:16Z | 1,369,247 | <p>From experimenting with you code snippet, it would seem I have the same behavior on my platform (Py2.6 on OS X 10.5).</p>
<p>Since you established that e[0] is encoded with <code>latin-1</code>, the correct way to convert it <code>unicode</code> is to do <code>.decode('latin-1')</code>, and <em>not</em> <code>unicode(e[0])</code>.</p>
<p><strong>Update:</strong> So it sounds like e[0] does not have a valid encoding. Definetely not <code>latin-1</code>. Because of that, as mentioned elsewhere in the comments, you'll have to call <code>repr(e[0])</code> if you need to display this error message w/o causing a cascading exception.</p>
| 0 | 2009-09-02T18:04:17Z | [
"python",
"exception",
"encoding",
"python-2.x"
] |
Default encoding of exception messages | 1,369,089 | <p>The following code examines the behaviour of the <code>float()</code> method when fed a non-ascii symbol:</p>
<pre><code>import sys
try:
float(u'\xbd')
except ValueError as e:
print sys.getdefaultencoding() # in my system, this is 'ascii'
print e[0].decode('latin-1') # u'invalid literal for float(): ' followed by the 1/2 (one half) character
print unicode(e[0]) # raises "UnicodeDecodeError: 'ascii' codec can't decode byte 0xbd in position 29: ordinal not in range(128)"
</code></pre>
<p>My question: <strong>why is the error message <code>e[0]</code> encoded in Latin-1?</strong> The default encoding is Ascii, and this seems to be what <code>unicode()</code> expects.</p>
<p>Platform is Ubuntu 9.04, Python 2.6.2</p>
| 6 | 2009-09-02T17:27:16Z | 1,369,335 | <p>e[0] isn't encoded with latin-1; it just so happens that the byte \xbd, when decoded as latin-1, is the character U+00BD.</p>
<p>The conversion occurs in <code>Objects/floatobject.c</code>.</p>
<p>First, the unicode string must be converted to a byte string. This is performed using <code>PyUnicode_EncodeDecimal()</code>:</p>
<pre><code>if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
PyUnicode_GET_SIZE(v),
s_buffer,
NULL))
return NULL;
</code></pre>
<p>which is implemented in <code>unicodeobject.c</code>. It doesn't perform any sort of character set conversion, it just writes bytes with values equal to the unicode ordinals of the string. In this case, U+00BD -> 0xBD.</p>
<p>The statement formatting the error is:</p>
<pre><code>PyOS_snprintf(buffer, sizeof(buffer),
"invalid literal for float(): %.200s", s);
</code></pre>
<p>where <code>s</code> contains the byte string created earlier. <code>PyOS_snprintf()</code> writes a byte string, and <code>s</code> is a byte string, so it just includes it directly.</p>
| 8 | 2009-09-02T18:19:54Z | [
"python",
"exception",
"encoding",
"python-2.x"
] |
Default encoding of exception messages | 1,369,089 | <p>The following code examines the behaviour of the <code>float()</code> method when fed a non-ascii symbol:</p>
<pre><code>import sys
try:
float(u'\xbd')
except ValueError as e:
print sys.getdefaultencoding() # in my system, this is 'ascii'
print e[0].decode('latin-1') # u'invalid literal for float(): ' followed by the 1/2 (one half) character
print unicode(e[0]) # raises "UnicodeDecodeError: 'ascii' codec can't decode byte 0xbd in position 29: ordinal not in range(128)"
</code></pre>
<p>My question: <strong>why is the error message <code>e[0]</code> encoded in Latin-1?</strong> The default encoding is Ascii, and this seems to be what <code>unicode()</code> expects.</p>
<p>Platform is Ubuntu 9.04, Python 2.6.2</p>
| 6 | 2009-09-02T17:27:16Z | 1,369,357 | <p>Very good question!</p>
<p>I took the liberty to dig into Python's source code, which is a mere command away on properly set up linux distributions (<code>apt-get source python2.5</code>)</p>
<p><em>Damn</em>, John Millikin beat me to it. That's right, <code>PyUnicode_EncodeDecimal</code> is the answer it does this here:</p>
<pre><code>/* (Loop ch in the unicode string) */
if (Py_UNICODE_ISSPACE(ch)) {
*output++ = ' ';
++p;
continue;
}
decimal = Py_UNICODE_TODECIMAL(ch);
if (decimal >= 0) {
*output++ = '0' + decimal;
++p;
continue;
}
if (0 < ch && ch < 256) {
*output++ = (char)ch;
++p;
continue;
}
/* All other characters are considered unencodable */
collstart = p;
collend = p+1;
while (collend < end) {
if ((0 < *collend && *collend < 256) ||
!Py_UNICODE_ISSPACE(*collend) ||
Py_UNICODE_TODECIMAL(*collend))
break;
}
</code></pre>
<p>See, it leaves all unicode code points < 256 in place, which are the latin-1 characters, based on Unicode's backward compatibility.</p>
<p><hr /></p>
<p>Addendum</p>
<p>With this in place, you can verify by trying other non-latin-1 characters, it will throw a different exception:</p>
<pre><code>>>> float(u"ħ")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'decimal' codec can't encode character u'\u0127' in position 0: invalid decimal Unicode string
</code></pre>
| 5 | 2009-09-02T18:23:23Z | [
"python",
"exception",
"encoding",
"python-2.x"
] |
Managing Python Path When Moving Code from Development Computer to Target | 1,369,159 | <p>I have a python project with this directory structure and these files:</p>
<pre><code>/home/project_root
|---__init__.py
|---setup
|---__init__.py
|---configs.py
|---test_code
|---__init__.py
|---tester.py
</code></pre>
<p>The tester script imports from setup/configs.py with the reference "setup.configs". It runs fine on my development machine.</p>
<p>This works on the development (Linux) computer. When I move this to another (Linux) computer, I set the PYTHONPATH with </p>
<pre><code>PYTHONPATH = "/home/project_root"
</code></pre>
<p>But when I run tester.py, it can't find the configs module. And when I run the interactive Python interpreter, sys.path doesn't include the /home/project_root directory. But /home/project_root does appear when I echo $PYTHPATH.</p>
<p>What am I doing wrong here? </p>
<p>(I don't want to rely on the .bashrc file to set the PYTHONPATH for the target machine -- the code is for a Django application, and will eventually be run by www-data. And, I know that the apache configuration for Django includes a specification of the PYTHONPATH, but I don't want to use that here as I'm first trying to make sure the code passes its unit tests in the target machine environment.)</p>
<p><strong>CURIOUSER AND CURIOUSER</strong>
This seems to be a userid and permissions problem.
- When launched by a command from an ordinary user, the interpreter can import modules as expected.
- When launched by sudo (I'm running Ubuntu here), the interpreter cannot import modules as expected.
- I've been calling the test script with sudo, as the files are owned by www-data (b/c they'll be called by the user running apache as part of the Django application).
- After changing the files' ownership to that of an ordinary user, the test script <em>does</em> run without import errors (albeit, into all sorts of userid related walls).</p>
<p>Sorry to waste your time. <strong>This question should be closed.</strong></p>
| 3 | 2009-09-02T17:45:17Z | 1,369,185 | <p>Try explicitly setting your python path <em>in your scripts</em>. If you don't want to have to change it, you could always add something like "../" to the path in tester. That is to say:</p>
<pre><code>sys.path.append("../")
</code></pre>
| 0 | 2009-09-02T17:51:04Z | [
"python",
"path",
"pythonpath"
] |
Managing Python Path When Moving Code from Development Computer to Target | 1,369,159 | <p>I have a python project with this directory structure and these files:</p>
<pre><code>/home/project_root
|---__init__.py
|---setup
|---__init__.py
|---configs.py
|---test_code
|---__init__.py
|---tester.py
</code></pre>
<p>The tester script imports from setup/configs.py with the reference "setup.configs". It runs fine on my development machine.</p>
<p>This works on the development (Linux) computer. When I move this to another (Linux) computer, I set the PYTHONPATH with </p>
<pre><code>PYTHONPATH = "/home/project_root"
</code></pre>
<p>But when I run tester.py, it can't find the configs module. And when I run the interactive Python interpreter, sys.path doesn't include the /home/project_root directory. But /home/project_root does appear when I echo $PYTHPATH.</p>
<p>What am I doing wrong here? </p>
<p>(I don't want to rely on the .bashrc file to set the PYTHONPATH for the target machine -- the code is for a Django application, and will eventually be run by www-data. And, I know that the apache configuration for Django includes a specification of the PYTHONPATH, but I don't want to use that here as I'm first trying to make sure the code passes its unit tests in the target machine environment.)</p>
<p><strong>CURIOUSER AND CURIOUSER</strong>
This seems to be a userid and permissions problem.
- When launched by a command from an ordinary user, the interpreter can import modules as expected.
- When launched by sudo (I'm running Ubuntu here), the interpreter cannot import modules as expected.
- I've been calling the test script with sudo, as the files are owned by www-data (b/c they'll be called by the user running apache as part of the Django application).
- After changing the files' ownership to that of an ordinary user, the test script <em>does</em> run without import errors (albeit, into all sorts of userid related walls).</p>
<p>Sorry to waste your time. <strong>This question should be closed.</strong></p>
| 3 | 2009-09-02T17:45:17Z | 1,369,186 | <p>Stick this in the tester script right before the <code>import setup.configs</code></p>
<pre><code>import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.path.pardir))
</code></pre>
<p><code>sys.path</code> is a list of all the directories the python interpreter looks for when importing a python module.
This will add the parent directory which contains setup module to the beginning of that list which means that the local directory will be checked first. That is important if you have your module installed system wide. More info on that here: <a href="http://docs.python.org/library/sys.html#sys.path" rel="nofollow">sys doc</a>.</p>
<p><strong>EDIT:</strong> You could also put a .pth file in <code>/usr/local/lib/python2.X/site-packages/</code> A .pth file is simply a text file with a directory path on each line that the python interpreter will search in. So just add a file with this line in it:</p>
<pre>/home/project_root</pre>
| 4 | 2009-09-02T17:51:19Z | [
"python",
"path",
"pythonpath"
] |
Managing Python Path When Moving Code from Development Computer to Target | 1,369,159 | <p>I have a python project with this directory structure and these files:</p>
<pre><code>/home/project_root
|---__init__.py
|---setup
|---__init__.py
|---configs.py
|---test_code
|---__init__.py
|---tester.py
</code></pre>
<p>The tester script imports from setup/configs.py with the reference "setup.configs". It runs fine on my development machine.</p>
<p>This works on the development (Linux) computer. When I move this to another (Linux) computer, I set the PYTHONPATH with </p>
<pre><code>PYTHONPATH = "/home/project_root"
</code></pre>
<p>But when I run tester.py, it can't find the configs module. And when I run the interactive Python interpreter, sys.path doesn't include the /home/project_root directory. But /home/project_root does appear when I echo $PYTHPATH.</p>
<p>What am I doing wrong here? </p>
<p>(I don't want to rely on the .bashrc file to set the PYTHONPATH for the target machine -- the code is for a Django application, and will eventually be run by www-data. And, I know that the apache configuration for Django includes a specification of the PYTHONPATH, but I don't want to use that here as I'm first trying to make sure the code passes its unit tests in the target machine environment.)</p>
<p><strong>CURIOUSER AND CURIOUSER</strong>
This seems to be a userid and permissions problem.
- When launched by a command from an ordinary user, the interpreter can import modules as expected.
- When launched by sudo (I'm running Ubuntu here), the interpreter cannot import modules as expected.
- I've been calling the test script with sudo, as the files are owned by www-data (b/c they'll be called by the user running apache as part of the Django application).
- After changing the files' ownership to that of an ordinary user, the test script <em>does</em> run without import errors (albeit, into all sorts of userid related walls).</p>
<p>Sorry to waste your time. <strong>This question should be closed.</strong></p>
| 3 | 2009-09-02T17:45:17Z | 1,369,435 | <blockquote>
<p>(I don't want to rely on the .bashrc file to set the PYTHONPATH for the target machine -- the code is for a Django application, and will eventually be run by www-data. And, I know that the apache configuration for Django includes a specification of the PYTHONPATH, but I don't want to use that here as I'm first trying to make sure the code passes its unit tests in the target machine environment.)</p>
</blockquote>
<p>If the code is for a Django application, is there a reason you're not testing it in the context of a Django project? Testing it in the context of a Django project gives a couple benefits:</p>
<ol>
<li>Django's <code>manage.py</code> will set up your Python environment for you. It'll add the appropriate project paths to <code>sys.path</code>, and it'll set the environment variable <code>DJANGO_SETTINGS_MODULE</code> correctly.</li>
<li>Django's libraries include ample unit testing facilities, and you can easily extend that functionality to include your own testing facilities. Executing tests in a Django project is as easy as executing a single command via <code>manage.py</code>.</li>
</ol>
| 0 | 2009-09-02T18:39:59Z | [
"python",
"path",
"pythonpath"
] |
How do I extract a date range from a csv using perl/php/grep/etc? | 1,369,287 | <p>Is there a way to take text like below (if it was already in an array or a file) and have it strip the lines with a specified date range? </p>
<p>For instance if i wanted every line from 2009-09-04 until 2009-09-09 to be pulled out (maybe this can be done with grep?) how would I go about doing so? </p>
<pre><code>date,test,time,avail
2009-09-01,JS,0.119,99.90
2009-09-02,JS,0.154,99.89
2009-09-03,SWF,0.177,99.90
2009-09-04,SWF,0.177,99.90
2009-09-05,SWF,0.177,99.90
2009-09-06,SWF,0.177,99.90
2009-09-07,SWF,0.177,99.90
2009-09-08,SWF,0.177,99.90
2009-09-09,SWF,0.177,99.90
2009-09-10,SWF,0.177,99.90
</code></pre>
<p>Thanks!</p>
| 1 | 2009-09-02T18:10:42Z | 1,369,338 | <p><em>(This solution is in PHP -- but you can probably do that directly from the command-line, I suppose, with somekind of grep or anything)</em></p>
<p>Considering your dates are in the <code>YYYY-MM-DD</code> format, and that they are at the beginning of each line, you just have to compare the lines alphabetically to compare the dates.</p>
<p>One solution would be to :</p>
<ul>
<li>load the string</li>
<li>explode it by lines</li>
<li>remove the first line</li>
<li>iterate over the lines, keeping only those that interest you</li>
</ul>
<p>For the first parts :</p>
<pre><code>$str = <<<STR
date,test,time,avail
2009-09-01,JS,0.119,99.90
2009-09-02,JS,0.154,99.89
2009-09-03,SWF,0.177,99.90
2009-09-04,SWF,0.177,99.90
2009-09-05,SWF,0.177,99.90
2009-09-06,SWF,0.177,99.90
2009-09-07,SWF,0.177,99.90
2009-09-08,SWF,0.177,99.90
2009-09-09,SWF,0.177,99.90
2009-09-10,SWF,0.177,99.90
STR;
$lines = explode(PHP_EOL, $str);
unset($lines[0]); // first line is useless
</code></pre>
<p>And, to iterate over the lines, filtering in/out those you want / don't want, you could use a foreach loop... Or use the <a href="http://php.net/array%5Ffilter" rel="nofollow"><code>array_filter</code></a> function, which exists just for this ;-)</p>
<p>For instance, you could use something like this :</p>
<pre><code>$new_lines = array_filter($lines, 'my_filter');
var_dump($new_lines);
</code></pre>
<p>And your callback function would be :</p>
<pre><code>function my_filter($line) {
$min = '2009-09-04';
$max = '2009-09-09';
if ($line >= $min && $line <= $max) {
return true;
} else {
return false;
}
}
</code></pre>
<p>And, the result :</p>
<pre><code>array
4 => string '2009-09-04,SWF,0.177,99.90' (length=26)
5 => string '2009-09-05,SWF,0.177,99.90' (length=26)
6 => string '2009-09-06,SWF,0.177,99.90' (length=26)
7 => string '2009-09-07,SWF,0.177,99.90' (length=26)
8 => string '2009-09-08,SWF,0.177,99.90' (length=26)
</code></pre>
<p>Hope this helps ;-)</p>
<p><br>
If your dates where not in the <code>YYYY-MM-DD</code> format, or not at the beginning of each line, you'd have to <a href="http://php.net/explode" rel="nofollow"><code>explode</code></a> the lines, and use <a href="http://php.net/strtotime" rel="nofollow"><code>strtotime</code></a> <em>(or do some custom parsing, depending on the format)</em>, and, then, compare timestamps.</p>
<p>But, in your case... No need for all that ;-)</p>
| 2 | 2009-09-02T18:20:19Z | [
"php",
"python",
"ruby",
"perl",
"grep"
] |
How do I extract a date range from a csv using perl/php/grep/etc? | 1,369,287 | <p>Is there a way to take text like below (if it was already in an array or a file) and have it strip the lines with a specified date range? </p>
<p>For instance if i wanted every line from 2009-09-04 until 2009-09-09 to be pulled out (maybe this can be done with grep?) how would I go about doing so? </p>
<pre><code>date,test,time,avail
2009-09-01,JS,0.119,99.90
2009-09-02,JS,0.154,99.89
2009-09-03,SWF,0.177,99.90
2009-09-04,SWF,0.177,99.90
2009-09-05,SWF,0.177,99.90
2009-09-06,SWF,0.177,99.90
2009-09-07,SWF,0.177,99.90
2009-09-08,SWF,0.177,99.90
2009-09-09,SWF,0.177,99.90
2009-09-10,SWF,0.177,99.90
</code></pre>
<p>Thanks!</p>
| 1 | 2009-09-02T18:10:42Z | 1,369,393 | <p>Well, you could probably <em>somehow</em> make it work with grep, but sed is more suited for the task:</p>
<pre><code>sort < file.csv | sed -ne /^2009-09-04/,/^2009-09-09/p
</code></pre>
| 3 | 2009-09-02T18:28:58Z | [
"php",
"python",
"ruby",
"perl",
"grep"
] |
How do I extract a date range from a csv using perl/php/grep/etc? | 1,369,287 | <p>Is there a way to take text like below (if it was already in an array or a file) and have it strip the lines with a specified date range? </p>
<p>For instance if i wanted every line from 2009-09-04 until 2009-09-09 to be pulled out (maybe this can be done with grep?) how would I go about doing so? </p>
<pre><code>date,test,time,avail
2009-09-01,JS,0.119,99.90
2009-09-02,JS,0.154,99.89
2009-09-03,SWF,0.177,99.90
2009-09-04,SWF,0.177,99.90
2009-09-05,SWF,0.177,99.90
2009-09-06,SWF,0.177,99.90
2009-09-07,SWF,0.177,99.90
2009-09-08,SWF,0.177,99.90
2009-09-09,SWF,0.177,99.90
2009-09-10,SWF,0.177,99.90
</code></pre>
<p>Thanks!</p>
| 1 | 2009-09-02T18:10:42Z | 1,369,399 | <p>Python</p>
<pre><code>import csv
import datetime
start= datetime.datetime(2009,9,4)
end= datetime.datetime(2009,9,9)
source= csv.DictReader( open("someFile","rb") )
for row in source:
dt = datetime.datetime.strptime(row['date'],"%Y-%m-%d")
if start <= dt <= end:
print row # depends on what "pulled out" means
</code></pre>
| 4 | 2009-09-02T18:31:12Z | [
"php",
"python",
"ruby",
"perl",
"grep"
] |
How do I extract a date range from a csv using perl/php/grep/etc? | 1,369,287 | <p>Is there a way to take text like below (if it was already in an array or a file) and have it strip the lines with a specified date range? </p>
<p>For instance if i wanted every line from 2009-09-04 until 2009-09-09 to be pulled out (maybe this can be done with grep?) how would I go about doing so? </p>
<pre><code>date,test,time,avail
2009-09-01,JS,0.119,99.90
2009-09-02,JS,0.154,99.89
2009-09-03,SWF,0.177,99.90
2009-09-04,SWF,0.177,99.90
2009-09-05,SWF,0.177,99.90
2009-09-06,SWF,0.177,99.90
2009-09-07,SWF,0.177,99.90
2009-09-08,SWF,0.177,99.90
2009-09-09,SWF,0.177,99.90
2009-09-10,SWF,0.177,99.90
</code></pre>
<p>Thanks!</p>
| 1 | 2009-09-02T18:10:42Z | 1,369,576 | <p>awk solution is similar to sed:</p>
<pre><code>awk '/^2009-09-04/,/^2009-09-09/ {next} {print}' filename
</code></pre>
<p>Without hardcoding the dates:</p>
<pre><code>awk -v start='^2009-09-04' -v stop='^2009-09-09' '
$0 ~ start, $0 ~ stop {next}
{print}
' date.data
</code></pre>
| 1 | 2009-09-02T19:10:48Z | [
"php",
"python",
"ruby",
"perl",
"grep"
] |
How do I extract a date range from a csv using perl/php/grep/etc? | 1,369,287 | <p>Is there a way to take text like below (if it was already in an array or a file) and have it strip the lines with a specified date range? </p>
<p>For instance if i wanted every line from 2009-09-04 until 2009-09-09 to be pulled out (maybe this can be done with grep?) how would I go about doing so? </p>
<pre><code>date,test,time,avail
2009-09-01,JS,0.119,99.90
2009-09-02,JS,0.154,99.89
2009-09-03,SWF,0.177,99.90
2009-09-04,SWF,0.177,99.90
2009-09-05,SWF,0.177,99.90
2009-09-06,SWF,0.177,99.90
2009-09-07,SWF,0.177,99.90
2009-09-08,SWF,0.177,99.90
2009-09-09,SWF,0.177,99.90
2009-09-10,SWF,0.177,99.90
</code></pre>
<p>Thanks!</p>
| 1 | 2009-09-02T18:10:42Z | 1,371,548 | <p>Using <a href="http://www.r-project.org" rel="nofollow">R</a></p>
<pre><code>> d <- read.csv("http://dpaste.com/88980/plain/", sep=",", header=T)
> r1 <- rownames(d[d$date == "2009-09-04",])
> r2 <- rownames(d[d$date == "2009-09-09",])
> d[rownames(d) %in% r1:r2,]
date test time avail
4 2009-09-04 SWF 0.177 99.9
5 2009-09-05 SWF 0.177 99.9
6 2009-09-06 SWF 0.177 99.9
7 2009-09-07 SWF 0.177 99.9
8 2009-09-08 SWF 0.177 99.9
9 2009-09-09 SWF 0.177 99.9
>
</code></pre>
| 0 | 2009-09-03T05:24:32Z | [
"php",
"python",
"ruby",
"perl",
"grep"
] |
How do I extract a date range from a csv using perl/php/grep/etc? | 1,369,287 | <p>Is there a way to take text like below (if it was already in an array or a file) and have it strip the lines with a specified date range? </p>
<p>For instance if i wanted every line from 2009-09-04 until 2009-09-09 to be pulled out (maybe this can be done with grep?) how would I go about doing so? </p>
<pre><code>date,test,time,avail
2009-09-01,JS,0.119,99.90
2009-09-02,JS,0.154,99.89
2009-09-03,SWF,0.177,99.90
2009-09-04,SWF,0.177,99.90
2009-09-05,SWF,0.177,99.90
2009-09-06,SWF,0.177,99.90
2009-09-07,SWF,0.177,99.90
2009-09-08,SWF,0.177,99.90
2009-09-09,SWF,0.177,99.90
2009-09-10,SWF,0.177,99.90
</code></pre>
<p>Thanks!</p>
| 1 | 2009-09-02T18:10:42Z | 1,381,076 | <p>Perl:</p>
<blockquote>
<pre><code>perl -F/,/ -ane '
print if $F[0] ge "2009-09-04"
&& $F[0] le "2009-09-09"' filename
</code></pre>
</blockquote>
| 0 | 2009-09-04T19:20:32Z | [
"php",
"python",
"ruby",
"perl",
"grep"
] |
How do I extract a date range from a csv using perl/php/grep/etc? | 1,369,287 | <p>Is there a way to take text like below (if it was already in an array or a file) and have it strip the lines with a specified date range? </p>
<p>For instance if i wanted every line from 2009-09-04 until 2009-09-09 to be pulled out (maybe this can be done with grep?) how would I go about doing so? </p>
<pre><code>date,test,time,avail
2009-09-01,JS,0.119,99.90
2009-09-02,JS,0.154,99.89
2009-09-03,SWF,0.177,99.90
2009-09-04,SWF,0.177,99.90
2009-09-05,SWF,0.177,99.90
2009-09-06,SWF,0.177,99.90
2009-09-07,SWF,0.177,99.90
2009-09-08,SWF,0.177,99.90
2009-09-09,SWF,0.177,99.90
2009-09-10,SWF,0.177,99.90
</code></pre>
<p>Thanks!</p>
| 1 | 2009-09-02T18:10:42Z | 1,381,095 | <p>You can use <a href="http://www.perl.com/pub/a/2004/06/18/variables.html" rel="nofollow">perl's flip flop</a> to extract a line range.</p>
| 1 | 2009-09-04T19:24:31Z | [
"php",
"python",
"ruby",
"perl",
"grep"
] |
strategies for finding duplicate mailing addresses | 1,369,289 | <p>I'm trying to come up with a method of finding duplicate addresses, based on a similarity score. Consider these duplicate addresses:</p>
<pre><code>addr_1 = '# 3 FAIRMONT LINK SOUTH'
addr_2 = '3 FAIRMONT LINK S'
addr_3 = '5703 - 48TH AVE'
adrr_4 = '5703- 48 AVENUE'
</code></pre>
<p>I'm planning on applying some string transformation to make long words abbreviated, like NORTH -> N, remove all spaces, commas and dashes and pound symbols. Now, having this output, how can I compare addr_3 with the rest of addresses and detect similar? What percentage of similarity would be safe? Could you provide a simple python code for this?</p>
<pre><code>addr_1 = '3FAIRMONTLINKS'
addr_2 = '3FAIRMONTLINKS'
addr_3 = '570348THAV'
adrr_4 = '570348AV'
</code></pre>
<p>Thankful,</p>
<p>Eduardo</p>
| 4 | 2009-09-02T18:11:03Z | 1,369,409 | <p>Removing spaces, commas and dashes will be ambiguous . It will be better to replace them with a single space.</p>
<p>Take for example this address</p>
<pre><code>56 5th avenue
</code></pre>
<p>And this</p>
<pre><code>5, 65th avenue
</code></pre>
<p>with your method both of them will be:</p>
<pre><code>565THAV
</code></pre>
<p>What you can do is write a good address shortening algorithm and then use string comparison to detect duplicates. This should be enough to detect duplicates in the general case. A general similarity algorithm won't work. Because one number difference can mean a huge change in Addresses.</p>
<p>The algorithm can go like this:</p>
<ol>
<li>replace all commas dashes with spaces. Use he <a href="http://docs.python.org/library/string.html#string.translate" rel="nofollow">translate</a> method for that.</li>
<li>Build a dictionary with words and their abbreviated form</li>
<li>Remove the <code>TH</code> part if it was following a number.</li>
</ol>
| 2 | 2009-09-02T18:33:46Z | [
"python",
"duplicates",
"street-address",
"similarity",
"mailing"
] |
strategies for finding duplicate mailing addresses | 1,369,289 | <p>I'm trying to come up with a method of finding duplicate addresses, based on a similarity score. Consider these duplicate addresses:</p>
<pre><code>addr_1 = '# 3 FAIRMONT LINK SOUTH'
addr_2 = '3 FAIRMONT LINK S'
addr_3 = '5703 - 48TH AVE'
adrr_4 = '5703- 48 AVENUE'
</code></pre>
<p>I'm planning on applying some string transformation to make long words abbreviated, like NORTH -> N, remove all spaces, commas and dashes and pound symbols. Now, having this output, how can I compare addr_3 with the rest of addresses and detect similar? What percentage of similarity would be safe? Could you provide a simple python code for this?</p>
<pre><code>addr_1 = '3FAIRMONTLINKS'
addr_2 = '3FAIRMONTLINKS'
addr_3 = '570348THAV'
adrr_4 = '570348AV'
</code></pre>
<p>Thankful,</p>
<p>Eduardo</p>
| 4 | 2009-09-02T18:11:03Z | 1,369,651 | <p>This should be helpful in building your dictionary of abbreviations:</p>
<p><a href="http://www.usps.com/ncsc/lookups/usps%5Fabbreviations.html" rel="nofollow">http://www.usps.com/ncsc/lookups/usps%5Fabbreviations.html</a></p>
| 2 | 2009-09-02T19:27:55Z | [
"python",
"duplicates",
"street-address",
"similarity",
"mailing"
] |
strategies for finding duplicate mailing addresses | 1,369,289 | <p>I'm trying to come up with a method of finding duplicate addresses, based on a similarity score. Consider these duplicate addresses:</p>
<pre><code>addr_1 = '# 3 FAIRMONT LINK SOUTH'
addr_2 = '3 FAIRMONT LINK S'
addr_3 = '5703 - 48TH AVE'
adrr_4 = '5703- 48 AVENUE'
</code></pre>
<p>I'm planning on applying some string transformation to make long words abbreviated, like NORTH -> N, remove all spaces, commas and dashes and pound symbols. Now, having this output, how can I compare addr_3 with the rest of addresses and detect similar? What percentage of similarity would be safe? Could you provide a simple python code for this?</p>
<pre><code>addr_1 = '3FAIRMONTLINKS'
addr_2 = '3FAIRMONTLINKS'
addr_3 = '570348THAV'
adrr_4 = '570348AV'
</code></pre>
<p>Thankful,</p>
<p>Eduardo</p>
| 4 | 2009-09-02T18:11:03Z | 1,370,350 | <p>First, simplify the address string by collapsing all whitespace to a single space between each word, and forcing everything to lower case (or upper case if you prefer):</p>
<pre><code>adr = " ".join(adr.tolower().split())
</code></pre>
<p>Then, I would strip out things like "st" in "41st Street" or "nd" in "42nd Street":</p>
<pre><code>adr = re.sub("1st(\b|$)", r'1', adr)
adr = re.sub("([2-9])\s?nd(\b|$)", r'\1', adr)
</code></pre>
<p>Note that the second sub() will work with a space between the "2" and the "nd", but I didn't set the first one to do that; because I'm not sure how you can tell the difference between "41 St Ave" and "41 St" (that second one is "41 Street" abbreviated).</p>
<p>Be sure to read all the help for the re module; it's powerful but cryptic.</p>
<p>Then, I would split what you have left into a list of words, and apply the Soundex algorithm to list items that don't look like numbers:</p>
<p><a href="http://en.wikipedia.org/wiki/Soundex" rel="nofollow">http://en.wikipedia.org/wiki/Soundex</a></p>
<p><a href="http://wwwhomes.uni-bielefeld.de/gibbon/Forms/Python/SEARCH/soundex.html" rel="nofollow">http://wwwhomes.uni-bielefeld.de/gibbon/Forms/Python/SEARCH/soundex.html</a></p>
<pre><code>adrlist = [word if word.isdigit() else soundex(word) for word in adr.split()]
</code></pre>
<p>Then you can work with the list or join it back to a string as you think best.</p>
<p>The whole idea of the Soundex thing is to handle misspelled addresses. That may not be what you want, in which case just ignore this Soundex idea.</p>
<p>Good luck.</p>
| 1 | 2009-09-02T21:54:37Z | [
"python",
"duplicates",
"street-address",
"similarity",
"mailing"
] |
strategies for finding duplicate mailing addresses | 1,369,289 | <p>I'm trying to come up with a method of finding duplicate addresses, based on a similarity score. Consider these duplicate addresses:</p>
<pre><code>addr_1 = '# 3 FAIRMONT LINK SOUTH'
addr_2 = '3 FAIRMONT LINK S'
addr_3 = '5703 - 48TH AVE'
adrr_4 = '5703- 48 AVENUE'
</code></pre>
<p>I'm planning on applying some string transformation to make long words abbreviated, like NORTH -> N, remove all spaces, commas and dashes and pound symbols. Now, having this output, how can I compare addr_3 with the rest of addresses and detect similar? What percentage of similarity would be safe? Could you provide a simple python code for this?</p>
<pre><code>addr_1 = '3FAIRMONTLINKS'
addr_2 = '3FAIRMONTLINKS'
addr_3 = '570348THAV'
adrr_4 = '570348AV'
</code></pre>
<p>Thankful,</p>
<p>Eduardo</p>
| 4 | 2009-09-02T18:11:03Z | 1,372,808 | <p>I had to do this once. I converted everything to lowercase, computed each address's Levenshtein distance to every other address, and ordered the results. It worked very well, but it was quite time-consuming.</p>
<p>You'll want to use an implementation of Levenshtein in C rather than in Python if you have a large data set. Mine was a few tens of thousands and took the better part of a day to run, I think.</p>
| 0 | 2009-09-03T11:18:35Z | [
"python",
"duplicates",
"street-address",
"similarity",
"mailing"
] |
strategies for finding duplicate mailing addresses | 1,369,289 | <p>I'm trying to come up with a method of finding duplicate addresses, based on a similarity score. Consider these duplicate addresses:</p>
<pre><code>addr_1 = '# 3 FAIRMONT LINK SOUTH'
addr_2 = '3 FAIRMONT LINK S'
addr_3 = '5703 - 48TH AVE'
adrr_4 = '5703- 48 AVENUE'
</code></pre>
<p>I'm planning on applying some string transformation to make long words abbreviated, like NORTH -> N, remove all spaces, commas and dashes and pound symbols. Now, having this output, how can I compare addr_3 with the rest of addresses and detect similar? What percentage of similarity would be safe? Could you provide a simple python code for this?</p>
<pre><code>addr_1 = '3FAIRMONTLINKS'
addr_2 = '3FAIRMONTLINKS'
addr_3 = '570348THAV'
adrr_4 = '570348AV'
</code></pre>
<p>Thankful,</p>
<p>Eduardo</p>
| 4 | 2009-09-02T18:11:03Z | 1,377,318 | <p>I regularly inspect addresses for duplication where I work, and I have to say, I find Soundex highly unsuitable. It's both too slow and too eager to match things. I have similar issues with Levenshtein distance.</p>
<p>What has worked best for me is to sanitize and tokenize the addresses (get rid of punctuation, split things up into words) and then just see how many tokens match up. Because addresses typically have several tokens, you can develop a level of confidence in terms of a combination of (1) how many tokens were matched, (2) how many <em>numeric</em> tokens were matched, and (3) how many tokens are available. For example, if all tokens in the shorter address are in the longer address, the confidence of a match is pretty high. Likewise, if you match 5 tokens including at least one that's numeric, even if the addresses each have 8, that's still a high-confidence match.</p>
<p>It's definitely useful to do some tweaking, like substituting some common abbreviations. The USPS lists help, though I wouldn't go gung-ho trying to implement all of them, and some of the most valuable substitutions aren't on those lists. For example, 'JFK' should be a match for 'JOHN F KENNEDY', and there are a number of common ways to shorten 'MARTIN LUTHER KING JR'.</p>
<p>Maybe it goes without saying but I'll say it anyway, for completeness: Don't forget to just do a straight string comparison on the whole address before messing with more complicated things! This should be a very cheap test, and thus is probably a no-brainer first pass.</p>
<p>Obviously, the more time you're willing and able to spend (both on programming/testing and on run time), the better you'll be able to do. Fuzzy string matching techniques (faster and less generalized kinds than Levenshtein) can be useful, as a separate pass from the token approach (I wouldn't try to fuzzy match individual tokens against each other). I find that fuzzy string matching doesn't give me enough bang for my buck on addresses (though I will use it on names).</p>
| 0 | 2009-09-04T05:07:04Z | [
"python",
"duplicates",
"street-address",
"similarity",
"mailing"
] |
strategies for finding duplicate mailing addresses | 1,369,289 | <p>I'm trying to come up with a method of finding duplicate addresses, based on a similarity score. Consider these duplicate addresses:</p>
<pre><code>addr_1 = '# 3 FAIRMONT LINK SOUTH'
addr_2 = '3 FAIRMONT LINK S'
addr_3 = '5703 - 48TH AVE'
adrr_4 = '5703- 48 AVENUE'
</code></pre>
<p>I'm planning on applying some string transformation to make long words abbreviated, like NORTH -> N, remove all spaces, commas and dashes and pound symbols. Now, having this output, how can I compare addr_3 with the rest of addresses and detect similar? What percentage of similarity would be safe? Could you provide a simple python code for this?</p>
<pre><code>addr_1 = '3FAIRMONTLINKS'
addr_2 = '3FAIRMONTLINKS'
addr_3 = '570348THAV'
adrr_4 = '570348AV'
</code></pre>
<p>Thankful,</p>
<p>Eduardo</p>
| 4 | 2009-09-02T18:11:03Z | 1,927,502 | <p>In order to do this right, you need to standardize your addresses according to USPS standards (your address examples appear to be US based). There are many direct marketing service providers that offer <a href="http://en.wikipedia.org/wiki/CASS" rel="nofollow">CASS</a> (Coding Accuracy Support System) certification of postal addresses. The CASS process will standardize all of your addresses and append zip + 4 to them. Any undeliverable addresses will be flagged which will further reduce your postal mailing costs, if that is your intent. Once all of your addresses are standardized, eliminating duplicates will be trivial. </p>
| 1 | 2009-12-18T10:52:44Z | [
"python",
"duplicates",
"street-address",
"similarity",
"mailing"
] |
Aliasing a class in Python | 1,369,534 | <p>I am writing a class to implement an algorithm. This algorithm has three levels of complexity. It makes sense to me to implement the classes like this:</p>
<pre><code>class level0:
def calc_algorithm(self):
# level 0 algorithm
pass
# more level0 stuff
class level1(level0):
def calc_algorithm(self):
# level 1 algorithm
pass
# more level1 stuff
class level2(level1):
def calc_algorithm(self):
# level 2 algorithm
pass
# more level2 stuff
</code></pre>
<p>Where I expect that <code>calc_algorithm</code> will be overridden in each class. Depending on a certain commandline option I want to run either level 0, level 1 or level 2 on the data. This is how I call the algorithm:</p>
<pre><code>for offset in itertools.product(*map(xrange, (dim[0] - 1, dim[1] - 1, dim[2] - 1))):
algorithm(offset).calc_algorithm
</code></pre>
<p>Where <code>algorithm</code> is either <code>level0</code>, <code>level1</code> or <code>level2</code>.</p>
<p>The way I'd do it in other languages is:</p>
<pre><code>for offset in itertools.product(*map(xrange, (dim[0] - 1, dim[1] - 1, dim[2] - 1))):
if (level == 0):
level0(offset).calc_algorithm
else:
if (level == 1):
level1(offset).calc_algorithm
else:
level2(offset).calc_algorithm
</code></pre>
<p>Is there a Pythonic way to alias a class to refer to another class, so that I could do:</p>
<pre><code>algorithm = (level == 0) and level0 or (level == 1) and level1 or level2
</code></pre>
<p>and then call <code>algorithm</code> as above?</p>
<p><hr /></p>
<p>Just for comparison, in Specman, which is an Aspect Oriented language I could write the class like this:</p>
<pre><code>struct algorithm {
level: uint;
// common stuff for all levels
calc_algorithm() is empty;
when (level == 0) {
calc_algorithm() is only {
// level 0 algorithm
};
};
when (level == 1) {
calc_algorithm() is only {
// level 1 algorithm
};
};
when (level == 1) {
calc_algorithm() is only {
// level 1 algorithm
};
};
};
</code></pre>
<p>And then once I set the <code>level</code> struct member, I can use the rest of the class transparently.</p>
| 1 | 2009-09-02T18:59:52Z | 1,369,564 | <p>Are you looking for something along these lines?</p>
<pre><code>dispatch = {0: level0, 1: level1, 2:level2}
dispatch[offset].calc_algorithm
</code></pre>
<p>Keys (and <code>offset</code>), obviously, could come from command line.</p>
| 11 | 2009-09-02T19:06:50Z | [
"python",
"class"
] |
Aliasing a class in Python | 1,369,534 | <p>I am writing a class to implement an algorithm. This algorithm has three levels of complexity. It makes sense to me to implement the classes like this:</p>
<pre><code>class level0:
def calc_algorithm(self):
# level 0 algorithm
pass
# more level0 stuff
class level1(level0):
def calc_algorithm(self):
# level 1 algorithm
pass
# more level1 stuff
class level2(level1):
def calc_algorithm(self):
# level 2 algorithm
pass
# more level2 stuff
</code></pre>
<p>Where I expect that <code>calc_algorithm</code> will be overridden in each class. Depending on a certain commandline option I want to run either level 0, level 1 or level 2 on the data. This is how I call the algorithm:</p>
<pre><code>for offset in itertools.product(*map(xrange, (dim[0] - 1, dim[1] - 1, dim[2] - 1))):
algorithm(offset).calc_algorithm
</code></pre>
<p>Where <code>algorithm</code> is either <code>level0</code>, <code>level1</code> or <code>level2</code>.</p>
<p>The way I'd do it in other languages is:</p>
<pre><code>for offset in itertools.product(*map(xrange, (dim[0] - 1, dim[1] - 1, dim[2] - 1))):
if (level == 0):
level0(offset).calc_algorithm
else:
if (level == 1):
level1(offset).calc_algorithm
else:
level2(offset).calc_algorithm
</code></pre>
<p>Is there a Pythonic way to alias a class to refer to another class, so that I could do:</p>
<pre><code>algorithm = (level == 0) and level0 or (level == 1) and level1 or level2
</code></pre>
<p>and then call <code>algorithm</code> as above?</p>
<p><hr /></p>
<p>Just for comparison, in Specman, which is an Aspect Oriented language I could write the class like this:</p>
<pre><code>struct algorithm {
level: uint;
// common stuff for all levels
calc_algorithm() is empty;
when (level == 0) {
calc_algorithm() is only {
// level 0 algorithm
};
};
when (level == 1) {
calc_algorithm() is only {
// level 1 algorithm
};
};
when (level == 1) {
calc_algorithm() is only {
// level 1 algorithm
};
};
};
</code></pre>
<p>And then once I set the <code>level</code> struct member, I can use the rest of the class transparently.</p>
| 1 | 2009-09-02T18:59:52Z | 1,369,704 | <pre><code>dispatch = {0:level0, 1:level1, 2:level2}
algo = dispatch[offset]() # "calling" a class constructs an instance.
algo.calc_algorithm()
</code></pre>
<p>If you like introspection more:</p>
<pre><code>class_name = "level%d" % offset
klass = globals()[class_name]
algo = klass()
algo.calc_algorithm()
</code></pre>
| 4 | 2009-09-02T19:41:50Z | [
"python",
"class"
] |
Aliasing a class in Python | 1,369,534 | <p>I am writing a class to implement an algorithm. This algorithm has three levels of complexity. It makes sense to me to implement the classes like this:</p>
<pre><code>class level0:
def calc_algorithm(self):
# level 0 algorithm
pass
# more level0 stuff
class level1(level0):
def calc_algorithm(self):
# level 1 algorithm
pass
# more level1 stuff
class level2(level1):
def calc_algorithm(self):
# level 2 algorithm
pass
# more level2 stuff
</code></pre>
<p>Where I expect that <code>calc_algorithm</code> will be overridden in each class. Depending on a certain commandline option I want to run either level 0, level 1 or level 2 on the data. This is how I call the algorithm:</p>
<pre><code>for offset in itertools.product(*map(xrange, (dim[0] - 1, dim[1] - 1, dim[2] - 1))):
algorithm(offset).calc_algorithm
</code></pre>
<p>Where <code>algorithm</code> is either <code>level0</code>, <code>level1</code> or <code>level2</code>.</p>
<p>The way I'd do it in other languages is:</p>
<pre><code>for offset in itertools.product(*map(xrange, (dim[0] - 1, dim[1] - 1, dim[2] - 1))):
if (level == 0):
level0(offset).calc_algorithm
else:
if (level == 1):
level1(offset).calc_algorithm
else:
level2(offset).calc_algorithm
</code></pre>
<p>Is there a Pythonic way to alias a class to refer to another class, so that I could do:</p>
<pre><code>algorithm = (level == 0) and level0 or (level == 1) and level1 or level2
</code></pre>
<p>and then call <code>algorithm</code> as above?</p>
<p><hr /></p>
<p>Just for comparison, in Specman, which is an Aspect Oriented language I could write the class like this:</p>
<pre><code>struct algorithm {
level: uint;
// common stuff for all levels
calc_algorithm() is empty;
when (level == 0) {
calc_algorithm() is only {
// level 0 algorithm
};
};
when (level == 1) {
calc_algorithm() is only {
// level 1 algorithm
};
};
when (level == 1) {
calc_algorithm() is only {
// level 1 algorithm
};
};
};
</code></pre>
<p>And then once I set the <code>level</code> struct member, I can use the rest of the class transparently.</p>
| 1 | 2009-09-02T18:59:52Z | 1,370,918 | <p>The key is thatâââunlike in some other languages where classes are âspecialâ and you'd have to have some unusual means of âaliasingâ themâââin Python, classes are themselves first-class objects which are referenced by perfectly normal variables.</p>
<p>So âaâ can be aliased as âbâ as simply as saying âb=aâ.</p>
<blockquote>
<p>Is there a Pythonic way to alias a class to refer to another class, so that I could do:</p>
<p>algorithm = (level == 0) and level0 or (level == 1) and level1 or level2</p>
</blockquote>
<p>Well yes, that's exactly right and will already work just as you wrote it!</p>
<p>...although modern Python has the if/else expression so today you'd generally say:</p>
<pre><code>algorithm= level0 if level==0 else level1 if level==1 else level2
</code></pre>
<p>but then a sequence access would probably be simpler than two conditionals:</p>
<pre><code>algorithm= (level0, level1, level2)[level]
</code></pre>
| 3 | 2009-09-03T00:50:28Z | [
"python",
"class"
] |
Aliasing a class in Python | 1,369,534 | <p>I am writing a class to implement an algorithm. This algorithm has three levels of complexity. It makes sense to me to implement the classes like this:</p>
<pre><code>class level0:
def calc_algorithm(self):
# level 0 algorithm
pass
# more level0 stuff
class level1(level0):
def calc_algorithm(self):
# level 1 algorithm
pass
# more level1 stuff
class level2(level1):
def calc_algorithm(self):
# level 2 algorithm
pass
# more level2 stuff
</code></pre>
<p>Where I expect that <code>calc_algorithm</code> will be overridden in each class. Depending on a certain commandline option I want to run either level 0, level 1 or level 2 on the data. This is how I call the algorithm:</p>
<pre><code>for offset in itertools.product(*map(xrange, (dim[0] - 1, dim[1] - 1, dim[2] - 1))):
algorithm(offset).calc_algorithm
</code></pre>
<p>Where <code>algorithm</code> is either <code>level0</code>, <code>level1</code> or <code>level2</code>.</p>
<p>The way I'd do it in other languages is:</p>
<pre><code>for offset in itertools.product(*map(xrange, (dim[0] - 1, dim[1] - 1, dim[2] - 1))):
if (level == 0):
level0(offset).calc_algorithm
else:
if (level == 1):
level1(offset).calc_algorithm
else:
level2(offset).calc_algorithm
</code></pre>
<p>Is there a Pythonic way to alias a class to refer to another class, so that I could do:</p>
<pre><code>algorithm = (level == 0) and level0 or (level == 1) and level1 or level2
</code></pre>
<p>and then call <code>algorithm</code> as above?</p>
<p><hr /></p>
<p>Just for comparison, in Specman, which is an Aspect Oriented language I could write the class like this:</p>
<pre><code>struct algorithm {
level: uint;
// common stuff for all levels
calc_algorithm() is empty;
when (level == 0) {
calc_algorithm() is only {
// level 0 algorithm
};
};
when (level == 1) {
calc_algorithm() is only {
// level 1 algorithm
};
};
when (level == 1) {
calc_algorithm() is only {
// level 1 algorithm
};
};
};
</code></pre>
<p>And then once I set the <code>level</code> struct member, I can use the rest of the class transparently.</p>
| 1 | 2009-09-02T18:59:52Z | 1,372,684 | <p>Personally, I wouldn't create 3 classes, but one class with 3 different calculation methods, and dinamically change the official calculation method (the calculation interface) as needed.
For example:</p>
<pre><code>class algorithm:
def __init__(self, level = 0):
self.level = level
self.calcFunctions = {0: self.calcLevel0, 1: self.calcLevel1, 2:self.calcLevel2}
#initial value for calc function
self.setLevel(level)
def setLevel(self, newlevel):
self.level = newlevel
self.calc = self.calcFunctions[level]
def calcLevel0(self):
"""Level 0 calc algorithm"""
#...
pass
def calcLevel1(self):
"""Level 1 calc algorithm"""
#...
pass
def calcLevel2(self):
"""Level 2 calc algorithm"""
#...
pass
#class in use:
#level (taken from command line in your case)
level = 1
alg = algorithm()
alg.setLevel(level)
alg.calc()
</code></pre>
<p>If you don't need to change the calcFunction dinamically during execution, you could also pass level to class constructor</p>
| 2 | 2009-09-03T10:40:19Z | [
"python",
"class"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.