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
job queue implementation for python
1,336,489
<p>Do you know/use any distributed job queue for python? Can you share links or tools</p>
13
2009-08-26T18:01:08Z
1,336,518
<p>In addition to multiprocessing there's also the <a href="http://pypi.python.org/pypi/celery/0.6.0" rel="nofollow">Celery</a> project, if you're using Django.</p>
3
2009-08-26T18:06:35Z
[ "python", "job-queue" ]
job queue implementation for python
1,336,489
<p>Do you know/use any distributed job queue for python? Can you share links or tools</p>
13
2009-08-26T18:01:08Z
1,336,532
<p>There's also "bucker" by Sylvain Hellegouarch which you can find here:</p> <ul> <li><a href="http://trac.defuze.org/wiki/bucker" rel="nofollow">http://trac.defuze.org/wiki/bucker</a></li> </ul> <p>It describes itself like this:</p> <ul> <li>bucker is a queue system that supports multiple storage for the queue (memcached, Amazon SQS for now) and is driven by XML messages sent over a TCP connections between a client and the queue server.</li> </ul>
3
2009-08-26T18:10:01Z
[ "python", "job-queue" ]
job queue implementation for python
1,336,489
<p>Do you know/use any distributed job queue for python? Can you share links or tools</p>
13
2009-08-26T18:01:08Z
1,336,588
<p>Look at <a href="http://xph.us/software/beanstalkd/" rel="nofollow">beanstalkd</a></p>
2
2009-08-26T18:18:36Z
[ "python", "job-queue" ]
job queue implementation for python
1,336,489
<p>Do you know/use any distributed job queue for python? Can you share links or tools</p>
13
2009-08-26T18:01:08Z
2,025,357
<p>redqueue? It's implemented in python+tornado framework, speaks memcached protocol and is optionally persistent into log files. Currently it is also able to behave like beanstalkd, the reserve/delete way in memcache protocol as well.</p> <p><a href="http://github.com/superisaac/redqueue" rel="nofollow" title="redqueue">REDQUEUE</a></p>
2
2010-01-08T03:44:20Z
[ "python", "job-queue" ]
job queue implementation for python
1,336,489
<p>Do you know/use any distributed job queue for python? Can you share links or tools</p>
13
2009-08-26T18:01:08Z
3,303,344
<p>It's a year late or whatever, but this is something I've hacked together to make a queue of Processes executing them only X number at a time. <a href="http://github.com/goosemo/job_queue" rel="nofollow">http://github.com/goosemo/job_queue</a></p>
1
2010-07-21T20:04:24Z
[ "python", "job-queue" ]
job queue implementation for python
1,336,489
<p>Do you know/use any distributed job queue for python? Can you share links or tools</p>
13
2009-08-26T18:01:08Z
3,303,367
<p>Pyres is a resque clone built in python. Resque is used by Github as their message queue. Both use Redis as the queue backend and provide a web-based monitoring application.</p> <p><a href="http://binarydud.github.com/pyres/intro.html">http://binarydud.github.com/pyres/intro.html</a></p>
12
2010-07-21T20:08:00Z
[ "python", "job-queue" ]
job queue implementation for python
1,336,489
<p>Do you know/use any distributed job queue for python? Can you share links or tools</p>
13
2009-08-26T18:01:08Z
3,758,551
<p>Also there is Unix 'at'</p> <p>For more info: man at</p>
-2
2010-09-21T08:34:41Z
[ "python", "job-queue" ]
job queue implementation for python
1,336,489
<p>Do you know/use any distributed job queue for python? Can you share links or tools</p>
13
2009-08-26T18:01:08Z
9,342,317
<p>If you think that Celery is too heavy for your needs then you might want to look at the simple distributed task queue:</p> <ul> <li><a href="https://github.com/rojkov/taskqueue" rel="nofollow">https://github.com/rojkov/taskqueue</a></li> <li><a href="http://simpletaskqueue.readthedocs.org/" rel="nofollow">http://simpletaskqueue.readthedocs.org/</a></li> </ul>
2
2012-02-18T15:05:48Z
[ "python", "job-queue" ]
What's the fastest way to fixup line-endings for SMTP sending?
1,336,524
<p>I'm coding a email application that produces messages for sending via SMTP. That means I need to change all lone \n and \r characters into the canonical \r\n sequence we all know and love. Here's the code I've got now:</p> <pre><code>CRLF = '\r\n' msg = re.sub(r'(?&lt;!\r)\n', CRLF, msg) msg = re.sub(r'\r(?!\n)', CRLF, msg) </code></pre> <p>The problem is it's not very fast. On large messages (around 80k) it takes up nearly 30% of the time to send a message!</p> <p>Can you do better? I eagerly await your Python gymnastics.</p>
2
2009-08-26T18:08:15Z
1,336,574
<p>You could start by pre-compiling the regexes, e.g.</p> <pre><code>FIXCR = re.compile(r'\r(?!\n)') FIXLN = re.compile(r'(?&lt;!\r)\n') </code></pre> <p>Then use FIXCR.sub and FIXLN.sub. Next, you could try to combine the regexes into one, with a | thingy, which should also help.</p>
0
2009-08-26T18:15:51Z
[ "python", "smtp", "performance" ]
What's the fastest way to fixup line-endings for SMTP sending?
1,336,524
<p>I'm coding a email application that produces messages for sending via SMTP. That means I need to change all lone \n and \r characters into the canonical \r\n sequence we all know and love. Here's the code I've got now:</p> <pre><code>CRLF = '\r\n' msg = re.sub(r'(?&lt;!\r)\n', CRLF, msg) msg = re.sub(r'\r(?!\n)', CRLF, msg) </code></pre> <p>The problem is it's not very fast. On large messages (around 80k) it takes up nearly 30% of the time to send a message!</p> <p>Can you do better? I eagerly await your Python gymnastics.</p>
2
2009-08-26T18:08:15Z
1,336,577
<p>Maybe it is the fact that inserting an extra character in the middle of the string is killing it.</p> <p>When you are substituting the text "hello \r world" it has to actually increase the size of the entire string by one character to "hello \r\n world" .</p> <p>I would suggest looping over the string and looking at characters one by one. If it is not a \r or \n then just append it to the new string. If it is a \r or \n append the new string with the correct values</p> <p>Code in C# (converting to python should be trivial)</p> <pre><code> string FixLineEndings(string input) { if (string.IsNullOrEmpty(input)) return string.Empty; StringBuilder rv = new StringBuilder(input.Length); for(int i = 0; i &lt; input.Length; i++) { char c = input[i]; if (c != '\r' &amp;&amp; c != '\n') { rv.Append(c); } else if (c == '\n') { rv.Append("\r\n"); } else if (c == '\r') { if (i == input.Length - 1) { rv.Append("\r\n"); //a \r at the end of the string } else if (input[i + 1] != '\n') { rv.Append("\r\n"); } } } return rv.ToString(); } </code></pre> <p>This was interesting enough to go write up a sample program to test. I used the regex given in the other answer and the code for using the regex was:</p> <p>static readonly Regex _r1 = new Regex(@"(? <p>I tried with a bunch of test cases. The outputs are:</p> <pre> ------------------------ Size: 1000 characters All\r String: 00:00:00.0038237 Regex : 00:00:00.0047669 All\r\n String: 00:00:00.0001745 Regex : 00:00:00.0009238 All\n String: 00:00:00.0024014 Regex : 00:00:00.0029281 No \r or \n String: 00:00:00.0000904 Regex : 00:00:00.0000628 \r at every 100th position and \n at every 102th position String: 00:00:00.0002232 Regex : 00:00:00.0001937 ------------------------ Size: 10000 characters All\r String: 00:00:00.0010271 Regex : 00:00:00.0096480 All\r\n String: 00:00:00.0006441 Regex : 00:00:00.0038943 All\n String: 00:00:00.0010618 Regex : 00:00:00.0136604 No \r or \n String: 00:00:00.0006781 Regex : 00:00:00.0001943 \r at every 100th position and \n at every 102th position String: 00:00:00.0006537 Regex : 00:00:00.0005838 </pre> <p>which show the string replacing function doing better in cases where the number of \r and \n's are high. For regular use though the original regex approach is much faster (see the last set of test cases - the ones w/o \r\n and with few \r's and \n's)</p> <p>This was of course coded in C# and not python but i'm guessing there would be similarities in the run times across languages</p>
1
2009-08-26T18:16:39Z
[ "python", "smtp", "performance" ]
What's the fastest way to fixup line-endings for SMTP sending?
1,336,524
<p>I'm coding a email application that produces messages for sending via SMTP. That means I need to change all lone \n and \r characters into the canonical \r\n sequence we all know and love. Here's the code I've got now:</p> <pre><code>CRLF = '\r\n' msg = re.sub(r'(?&lt;!\r)\n', CRLF, msg) msg = re.sub(r'\r(?!\n)', CRLF, msg) </code></pre> <p>The problem is it's not very fast. On large messages (around 80k) it takes up nearly 30% of the time to send a message!</p> <p>Can you do better? I eagerly await your Python gymnastics.</p>
2
2009-08-26T18:08:15Z
1,336,648
<p>Something like this? Compile your regex.</p> <pre><code>CRLF = '\r\n' cr_or_lf_regex = re.compile(r'(?:(?&lt;!\r)\n)|(?:\r(?!\n))') </code></pre> <p>Then, when you want to replace stuff use this:</p> <pre><code>cr_or_lf_regex.sub(CRLF, msg) </code></pre> <p><strong>EDIT:</strong> Since the above is actually slower, let me take another stab at it.</p> <pre><code>last_chr = '' def fix_crlf(input_chr): global last_chr if input_chr != '\r' and input_chr != '\n' and last_chr != '\r': result = input_chr else: if last_chr == '\r' and input_chr == '\n': result = '\r\n' elif last_chr != '\r' and input_chr == '\n': result = '\r\n' elif last_chr == '\r' and input_chr != '\n': result = '\r\n%s' % input_chr else: result = '' last_chr = input_chr return result fixed_msg = ''.join([fix_crlf(c) for c in msg]) </code></pre>
-1
2009-08-26T18:30:58Z
[ "python", "smtp", "performance" ]
What's the fastest way to fixup line-endings for SMTP sending?
1,336,524
<p>I'm coding a email application that produces messages for sending via SMTP. That means I need to change all lone \n and \r characters into the canonical \r\n sequence we all know and love. Here's the code I've got now:</p> <pre><code>CRLF = '\r\n' msg = re.sub(r'(?&lt;!\r)\n', CRLF, msg) msg = re.sub(r'\r(?!\n)', CRLF, msg) </code></pre> <p>The problem is it's not very fast. On large messages (around 80k) it takes up nearly 30% of the time to send a message!</p> <p>Can you do better? I eagerly await your Python gymnastics.</p>
2
2009-08-26T18:08:15Z
1,337,185
<p>This regex helped:</p> <p><code>re.sub(r'\r\n|\r|\n', '\r\n', msg)</code></p> <p>But this code ended up winning:</p> <p><code>msg.replace('\r\n','\n').replace('\r','\n').replace('\n','\r\n')</code></p> <p>The original regexes took .6s to convert /usr/share/dict/words from \n to \r\n, the new regex took .3s, and the replace()s took .08s. </p>
2
2009-08-26T20:13:02Z
[ "python", "smtp", "performance" ]
What's the fastest way to fixup line-endings for SMTP sending?
1,336,524
<p>I'm coding a email application that produces messages for sending via SMTP. That means I need to change all lone \n and \r characters into the canonical \r\n sequence we all know and love. Here's the code I've got now:</p> <pre><code>CRLF = '\r\n' msg = re.sub(r'(?&lt;!\r)\n', CRLF, msg) msg = re.sub(r'\r(?!\n)', CRLF, msg) </code></pre> <p>The problem is it's not very fast. On large messages (around 80k) it takes up nearly 30% of the time to send a message!</p> <p>Can you do better? I eagerly await your Python gymnastics.</p>
2
2009-08-26T18:08:15Z
1,337,572
<p>Replace them on the fly as you're writing the string to wherever it's going. If you use a regex or anything else you'll be making two passes: one to replace the characters and then one to write it. Deriving a new Stream class and wrapping it around whatever you're writing to is pretty effective; that's the way we do it with System.Net.Mail and that means I can use the same stream encoder for writing to both files and network streams. I'd have to see some of your code in order to give you a really good way to do this though. Also, keep in mind that the actual replacement won't really be any faster, however the total execution time would be reduced since you're only making one pass instead of two (assuming you actually are writing the output of the email somewhere).</p>
1
2009-08-26T21:23:14Z
[ "python", "smtp", "performance" ]
BDB Python Interface Error when Reading BDB
1,336,617
<p>bsddb.db.DBInvalidArgError: (22, 'Invalid argument -- /dbs/supermodels.db: unexpected file type or format')</p> <p>Is this error a result of incompatible BDB versions (1.85 or 3+)? If so, how do I check the versions, trouble-shoot and solve this error?</p>
0
2009-08-26T18:24:43Z
1,338,491
<p>Yes, this certainly could be due to older versions of the db file, but it would help if you posted the code that generated this exception and the full traceback.</p> <p>In the absence of this, are you sure that the database file that you're opening is of the correct type? For example, attempting to open a btree file as if it is a hash raises the exception that you are seeing:</p> <pre><code>&gt;&gt;&gt; import bsddb &gt;&gt;&gt; bt = bsddb.btopen('bt') &gt;&gt;&gt; bt.close() &gt;&gt;&gt; bsddb.hashopen('bt') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? File "/usr/lib/python2.4/bsddb/__init__.py", line 298, in hashopen d.open(file, db.DB_HASH, flags, mode) bsddb.db.DBInvalidArgError: (22, 'Invalid argument -- ./bt: unexpected file type or format') </code></pre> <p>In *nix you can usually determine the type of db by using the <code>file</code> command, e.g.</p> <pre><code>$ file /etc/aliases.db cert8.db /etc/aliases.db: Berkeley DB (Hash, version 8, native byte-order) cert8.db: Berkeley DB 1.85 (Hash, version 2, native byte-order) </code></pre> <p>Opening a 1.85 version file fails with the same exception:</p> <pre><code>&gt;&gt;&gt; db = bsddb.hashopen('/etc/aliases.db') # works, but... &gt;&gt;&gt; db = bsddb.hashopen('cert8.db') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? File "/usr/lib/python2.4/bsddb/__init__.py", line 298, in hashopen d.open(file, db.DB_HASH, flags, mode) bsddb.db.DBInvalidArgError: (22, 'Invalid argument -- ./cert8.db: unexpected file type or format') </code></pre> <p>If you need to migrate the database files, you should look at the <code>db_dump</code>, <code>db_dump185</code> and <code>db_load</code> utilities that come with the bdb distribuition.</p>
0
2009-08-27T02:00:50Z
[ "python", "berkeley-db" ]
Specifying constraints for fmin_cobyla in scipy
1,336,777
<p>I use Python 2.5.</p> <p>I am passing bounds to the cobyla optimisation:</p> <pre><code>import numpy from numpy import asarray Initial = numpy.asarray [2, 4, 5, 3] # Initial values to start with #bounding limits (lower,upper) - for visualizing #bounds = [(1, 5000), (1, 6000), (2, 100000), (1, 50000)] # actual passed bounds b1 = lambda x: 5000 - x[0] # lambda x: bounds[0][1] - Initial[0] b2 = lambda x: x[0] - 2.0 # lambda x: Initial[0] - bounds[0][0] b3 = lambda x: 6000 - x[1] # same as above b4 = lambda x: x[1] - 4.0 b5 = lambda x: 100000 - x[2] b6 = lambda x: x[2] - 5.0 b7 = lambda x: 50000 - x[3] b8 = lambda x: x[3] - 3.0 b9 = lambda x: x[2] &gt; x[3] # very important condition for my problem! opt= optimize.fmin_cobyla(func,Initial,cons=[b1,b2,b3,b4,b5,b6,b7,b8,b9,b10],maxfun=1500000) </code></pre> <p>Based on the initial values <code>Initial</code> and as per/within the bounds <code>b1</code> to <code>b10</code> the values are passed to <code>opt()</code>. But the values are deviating, especially with <code>b9</code>. This is a very important bounding condition for my problem!</p> <p>"The value of <code>x[2]</code> passed to my function <code>opt()</code> at every iteration must be always greater than <code>x[3]</code>" -- How is it possible to achieve this?</p> <p>Is there anything wrong in my bounds (<code>b1</code> to <code>b9</code>) definition ?</p> <p>Or is there a better way of defining of my bounds?</p> <p>Please help me.</p>
1
2009-08-26T18:53:37Z
1,336,891
<p><code>fmin_cobyla()</code> is not an interior point method. That is, it will pass points that are outside of the bounds ("infeasible points") to the function during the course of the optmization run.</p> <p>On thing that you will need to fix is that <code>b9</code> and <code>b10</code> are not in the form that <code>fmin_cobyla()</code> expects. The bound functions need to return a positive number if they are within the bound, 0.0 if they are exactly on the bound, and a negative number if they are out of bounds. Ideally, these functions should be smooth. <code>fmin_cobyla()</code> will try to take numerical derivatives of these functions in order to let it know how to get back to the feasible region.</p> <pre><code>b9 = lambda x: x[2] - x[3] </code></pre> <p>I'm not sure how to implement <code>b10</code> in a way that <code>fmin_cobyla()</code> will be able to use, though.</p>
3
2009-08-26T19:17:25Z
[ "python", "function", "lambda", "scipy", "specifications" ]
Specifying constraints for fmin_cobyla in scipy
1,336,777
<p>I use Python 2.5.</p> <p>I am passing bounds to the cobyla optimisation:</p> <pre><code>import numpy from numpy import asarray Initial = numpy.asarray [2, 4, 5, 3] # Initial values to start with #bounding limits (lower,upper) - for visualizing #bounds = [(1, 5000), (1, 6000), (2, 100000), (1, 50000)] # actual passed bounds b1 = lambda x: 5000 - x[0] # lambda x: bounds[0][1] - Initial[0] b2 = lambda x: x[0] - 2.0 # lambda x: Initial[0] - bounds[0][0] b3 = lambda x: 6000 - x[1] # same as above b4 = lambda x: x[1] - 4.0 b5 = lambda x: 100000 - x[2] b6 = lambda x: x[2] - 5.0 b7 = lambda x: 50000 - x[3] b8 = lambda x: x[3] - 3.0 b9 = lambda x: x[2] &gt; x[3] # very important condition for my problem! opt= optimize.fmin_cobyla(func,Initial,cons=[b1,b2,b3,b4,b5,b6,b7,b8,b9,b10],maxfun=1500000) </code></pre> <p>Based on the initial values <code>Initial</code> and as per/within the bounds <code>b1</code> to <code>b10</code> the values are passed to <code>opt()</code>. But the values are deviating, especially with <code>b9</code>. This is a very important bounding condition for my problem!</p> <p>"The value of <code>x[2]</code> passed to my function <code>opt()</code> at every iteration must be always greater than <code>x[3]</code>" -- How is it possible to achieve this?</p> <p>Is there anything wrong in my bounds (<code>b1</code> to <code>b9</code>) definition ?</p> <p>Or is there a better way of defining of my bounds?</p> <p>Please help me.</p>
1
2009-08-26T18:53:37Z
1,342,801
<p>for b10, a possible option could be:</p> <pre><code>b10 = lambda x: min(abs(i-j)-d for i,j in itertools.combinations(x,2)) </code></pre> <p>where <em>d</em> is a delta greater than the minimum difference you want between your variables (e.g 0.001)</p>
2
2009-08-27T18:05:36Z
[ "python", "function", "lambda", "scipy", "specifications" ]
Example of subclassing string.Template in Python?
1,336,786
<p>I haven't been able to find a good example of subclassing string.Template in Python, even though I've seen multiple references to doing so in documentation.</p> <p>Are there any examples of this on the web?</p> <p>I want to change the $ to be a different character and maybe change the regex for identifiers.</p>
13
2009-08-26T18:54:53Z
1,336,851
<p>From python <a href="http://docs.python.org/library/string.html">docs</a>:</p> <blockquote> <p>Advanced usage: you can derive subclasses of Template to customize the placeholder syntax, delimiter character, or the entire regular expression used to parse template strings. To do this, you can override these class attributes:</p> <p>delimiter – This is the literal string describing a placeholder introducing delimiter. The default value $. Note that this should not be a regular expression, as the implementation will call re.escape() on this string as needed.</p> <p>idpattern – This is the regular expression describing the pattern for non-braced placeholders (the braces will be added automatically as appropriate). The default value is the regular expression [_a-z][<em>a-z0-9]</em>.</p> </blockquote> <p>Example:</p> <pre><code>from string import Template class MyTemplate(Template): delimiter = '#' idpattern = r'[a-z][_a-z0-9]*' &gt;&gt;&gt; s = MyTemplate('#who likes $what') &gt;&gt;&gt; s.substitute(who='tim', what='kung pao') 'tim likes $what' </code></pre>
19
2009-08-26T19:07:40Z
[ "python", "stringtemplate" ]
Dictionary vs Object - which is more efficient and why?
1,336,791
<p>What is more efficient in Python in terms of memory usage and CPU consumption - Dictionary or Object?</p> <p><strong>Background:</strong> I have to load huge amount of data into Python. I created an object that is just a field container. Creating 4M instances and putting them into a dictionary took about 10 minutes and ~6GB of memory. After dictionary is ready, accessing it is a blink of an eye.</p> <p><strong>Example:</strong> To check the performance I wrote two simple programs that do the same - one is using objects, other dictionary:</p> <p>Object (execution time ~18sec):</p> <pre><code>class Obj(object): def __init__(self, i): self.i = i self.l = [] all = {} for i in range(1000000): all[i] = Obj(i) </code></pre> <p>Dictionary (execution time ~12sec):</p> <pre><code>all = {} for i in range(1000000): o = {} o['i'] = i o['l'] = [] all[i] = o </code></pre> <p><strong>Question:</strong> Am I doing something wrong or dictionary is just faster than object? If indeed dictionary performs better, can somebody explain why?</p>
76
2009-08-26T18:55:45Z
1,336,829
<p>Attribute access in an object uses dictionary access behind the scenes - so by using attribute access you are adding extra overhead. Plus in the object case, you are incurring additional overhead because of e.g. additional memory allocations and code execution (e.g. of the <code>__init__</code> method).</p> <p>In your code, if <code>o</code> is an <code>Obj</code> instance, <code>o.attr</code> is equivalent to <code>o.__dict__['attr']</code> with a small amount of extra overhead.</p>
10
2009-08-26T19:03:57Z
[ "python", "performance", "dictionary", "object" ]
Dictionary vs Object - which is more efficient and why?
1,336,791
<p>What is more efficient in Python in terms of memory usage and CPU consumption - Dictionary or Object?</p> <p><strong>Background:</strong> I have to load huge amount of data into Python. I created an object that is just a field container. Creating 4M instances and putting them into a dictionary took about 10 minutes and ~6GB of memory. After dictionary is ready, accessing it is a blink of an eye.</p> <p><strong>Example:</strong> To check the performance I wrote two simple programs that do the same - one is using objects, other dictionary:</p> <p>Object (execution time ~18sec):</p> <pre><code>class Obj(object): def __init__(self, i): self.i = i self.l = [] all = {} for i in range(1000000): all[i] = Obj(i) </code></pre> <p>Dictionary (execution time ~12sec):</p> <pre><code>all = {} for i in range(1000000): o = {} o['i'] = i o['l'] = [] all[i] = o </code></pre> <p><strong>Question:</strong> Am I doing something wrong or dictionary is just faster than object? If indeed dictionary performs better, can somebody explain why?</p>
76
2009-08-26T18:55:45Z
1,336,890
<p>Have you tried using <code>__slots__</code>?</p> <p>From the documentation <a href="http://docs.python.org/reference/datamodel.html#slots">http://docs.python.org/reference/datamodel.html#slots</a>:</p> <p>"By default, instances of both old and new-style classes have a dictionary for attribute storage. This wastes space for objects having very few instance variables. The space consumption can become acute when creating large numbers of instances.</p> <p>The default can be overridden by defining <code>__slots__</code> in a new-style class definition. The <code>__slots__</code> declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because <code>__dict__</code> is not created for each instance."</p> <p>So does this save time as well as memory?</p> <p>Comparing the three approaches on my computer:</p> <p>test_slots.py:</p> <pre><code>class Obj(object): __slots__ = ('i', 'l') def __init__(self, i): self.i = i self.l = [] all = {} for i in range(1000000): all[i] = Obj(i) </code></pre> <p>test_obj.py:</p> <pre><code>class Obj(object): def __init__(self, i): self.i = i self.l = [] all = {} for i in range(1000000): all[i] = Obj(i) </code></pre> <p>test_dict.py:</p> <pre><code>all = {} for i in range(1000000): o = {} o['i'] = i o['l'] = [] all[i] = o </code></pre> <p>test_namedtuple.py (supported in 2.6):</p> <pre><code>import collections Obj = collections.namedtuple('Obj', 'i l') all = {} for i in range(1000000): all[i] = Obj(i, []) </code></pre> <p>Run benchmark (using CPython 2.5):</p> <pre><code>$ lshw | grep product | head -n 1 product: Intel(R) Pentium(R) M processor 1.60GHz $ python --version Python 2.5 $ time python test_obj.py &amp;&amp; time python test_dict.py &amp;&amp; time python test_slots.py real 0m27.398s (using 'normal' object) real 0m16.747s (using __dict__) real 0m11.777s (using __slots__) </code></pre> <p>Using CPython 2.6.2, including the named tuple test:</p> <pre><code>$ python --version Python 2.6.2 $ time python test_obj.py &amp;&amp; time python test_dict.py &amp;&amp; time python test_slots.py &amp;&amp; time python test_namedtuple.py real 0m27.197s (using 'normal' object) real 0m17.657s (using __dict__) real 0m12.249s (using __slots__) real 0m12.262s (using namedtuple) </code></pre> <p>So yes (not really a surprise), using <code>__slots__</code> is a performance optimization. Using a named tuple has similar performance to <code>__slots__</code>.</p>
107
2009-08-26T19:17:25Z
[ "python", "performance", "dictionary", "object" ]
Dictionary vs Object - which is more efficient and why?
1,336,791
<p>What is more efficient in Python in terms of memory usage and CPU consumption - Dictionary or Object?</p> <p><strong>Background:</strong> I have to load huge amount of data into Python. I created an object that is just a field container. Creating 4M instances and putting them into a dictionary took about 10 minutes and ~6GB of memory. After dictionary is ready, accessing it is a blink of an eye.</p> <p><strong>Example:</strong> To check the performance I wrote two simple programs that do the same - one is using objects, other dictionary:</p> <p>Object (execution time ~18sec):</p> <pre><code>class Obj(object): def __init__(self, i): self.i = i self.l = [] all = {} for i in range(1000000): all[i] = Obj(i) </code></pre> <p>Dictionary (execution time ~12sec):</p> <pre><code>all = {} for i in range(1000000): o = {} o['i'] = i o['l'] = [] all[i] = o </code></pre> <p><strong>Question:</strong> Am I doing something wrong or dictionary is just faster than object? If indeed dictionary performs better, can somebody explain why?</p>
76
2009-08-26T18:55:45Z
1,336,906
<pre><code>from datetime import datetime ITER_COUNT = 1000 * 1000 def timeit(method): def timed(*args, **kw): s = datetime.now() result = method(*args, **kw) e = datetime.now() print method.__name__, '(%r, %r)' % (args, kw), e - s return result return timed class Obj(object): def __init__(self, i): self.i = i self.l = [] class SlotObj(object): __slots__ = ('i', 'l') def __init__(self, i): self.i = i self.l = [] @timeit def profile_dict_of_dict(): return dict((i, {'i': i, 'l': []}) for i in xrange(ITER_COUNT)) @timeit def profile_list_of_dict(): return [{'i': i, 'l': []} for i in xrange(ITER_COUNT)] @timeit def profile_dict_of_obj(): return dict((i, Obj(i)) for i in xrange(ITER_COUNT)) @timeit def profile_list_of_obj(): return [Obj(i) for i in xrange(ITER_COUNT)] @timeit def profile_dict_of_slotobj(): return dict((i, SlotObj(i)) for i in xrange(ITER_COUNT)) @timeit def profile_list_of_slotobj(): return [SlotObj(i) for i in xrange(ITER_COUNT)] if __name__ == '__main__': profile_dict_of_dict() profile_list_of_dict() profile_dict_of_obj() profile_list_of_obj() profile_dict_of_slotobj() profile_list_of_slotobj() </code></pre> <p>Results:</p> <pre><code>hbrown@hbrown-lpt:~$ python ~/Dropbox/src/StackOverflow/1336791.py profile_dict_of_dict ((), {}) 0:00:08.228094 profile_list_of_dict ((), {}) 0:00:06.040870 profile_dict_of_obj ((), {}) 0:00:11.481681 profile_list_of_obj ((), {}) 0:00:10.893125 profile_dict_of_slotobj ((), {}) 0:00:06.381897 profile_list_of_slotobj ((), {}) 0:00:05.860749 </code></pre>
3
2009-08-26T19:19:29Z
[ "python", "performance", "dictionary", "object" ]
Dictionary vs Object - which is more efficient and why?
1,336,791
<p>What is more efficient in Python in terms of memory usage and CPU consumption - Dictionary or Object?</p> <p><strong>Background:</strong> I have to load huge amount of data into Python. I created an object that is just a field container. Creating 4M instances and putting them into a dictionary took about 10 minutes and ~6GB of memory. After dictionary is ready, accessing it is a blink of an eye.</p> <p><strong>Example:</strong> To check the performance I wrote two simple programs that do the same - one is using objects, other dictionary:</p> <p>Object (execution time ~18sec):</p> <pre><code>class Obj(object): def __init__(self, i): self.i = i self.l = [] all = {} for i in range(1000000): all[i] = Obj(i) </code></pre> <p>Dictionary (execution time ~12sec):</p> <pre><code>all = {} for i in range(1000000): o = {} o['i'] = i o['l'] = [] all[i] = o </code></pre> <p><strong>Question:</strong> Am I doing something wrong or dictionary is just faster than object? If indeed dictionary performs better, can somebody explain why?</p>
76
2009-08-26T18:55:45Z
1,336,952
<p><strong>There is no question.</strong><br /> You have data, with no other attributes (no methods, nothing). Hence you have a data container (in this case, a dictionary).</p> <p>I usually prefer to think in terms of <strong>data modeling</strong>. If there is some huge performance issue, then I can give up something in the abstraction, but only with very good reasons.<br /> Programming is all about managing complexity, and the maintaining the <strong>correct abstraction</strong> is very often one of the most useful way to achieve such result.</p> <p>About the <em>reasons</em> an object is slower, I think your measurement is not correct.<br /> You are performing too little assignments inside the for loop, and therefore what you see there is the different time necessary to instantiate a dict (intrinsic object) and a "custom" object. Although from the language perspective they are the same, they have quite a different implementation.<br /> After that, the assignment time should be almost the same for both, as in the end members are maintained inside a dictionary.</p>
3
2009-08-26T19:28:12Z
[ "python", "performance", "dictionary", "object" ]
Dictionary vs Object - which is more efficient and why?
1,336,791
<p>What is more efficient in Python in terms of memory usage and CPU consumption - Dictionary or Object?</p> <p><strong>Background:</strong> I have to load huge amount of data into Python. I created an object that is just a field container. Creating 4M instances and putting them into a dictionary took about 10 minutes and ~6GB of memory. After dictionary is ready, accessing it is a blink of an eye.</p> <p><strong>Example:</strong> To check the performance I wrote two simple programs that do the same - one is using objects, other dictionary:</p> <p>Object (execution time ~18sec):</p> <pre><code>class Obj(object): def __init__(self, i): self.i = i self.l = [] all = {} for i in range(1000000): all[i] = Obj(i) </code></pre> <p>Dictionary (execution time ~12sec):</p> <pre><code>all = {} for i in range(1000000): o = {} o['i'] = i o['l'] = [] all[i] = o </code></pre> <p><strong>Question:</strong> Am I doing something wrong or dictionary is just faster than object? If indeed dictionary performs better, can somebody explain why?</p>
76
2009-08-26T18:55:45Z
1,338,150
<p>Have you considered using a <a href="http://docs.python.org/library/collections.html" rel="nofollow">namedtuple</a>? (<a href="http://code.activestate.com/recipes/500261/" rel="nofollow">link for python 2.4/2.5</a>)</p> <p>It's the new standard way of representing structured data that gives you the performance of a tuple and the convenience of a class.</p> <p>It's only downside compared with dictionaries is that (like tuples) it doesn't give you the ability to change attributes after creation.</p>
7
2009-08-26T23:39:22Z
[ "python", "performance", "dictionary", "object" ]
Python dateutil.rrule is incredibly slow
1,336,824
<p>I'm using the python dateutil module for a calendaring application which supports repeating events. I really like the ability to parse ical rrules using the rrulestr() function. Also, using rrule.between() to get dates within a given interval is very fast.</p> <p>However, as soon as I try doing any other operations (ie: list slices, before(), after(),...) everything begins to crawl. It seems like dateutil tries to calculate every date even if all I want is to get the last date with rrule.before(datetime.max).</p> <p>Is there any way of avoiding these unnecessary calculations?</p>
2
2009-08-26T19:03:10Z
1,337,063
<p>My guess is probably not. The last date before datetime.max means you have to calculate all the recurrences up until datetime.max, and that will reasonably be a LOT of recurrences. It might be possible to add shortcuts for some of the simpler recurrences. If it is every year on the same date for example, you don't really need to compute the recurrences inbetween, for example. But if you have every third something you must, for example, and also if you have a maximum recurrences, etc. But I guess dateutil doesn't have these shortcuts. It would probably be quite complex to implement reliably.</p> <p>May I ask why you need to find the last recurrence before datetime.max? It is, after all, almost eight thousand years into the future... :-)</p>
4
2009-08-26T19:52:08Z
[ "python", "calendar", "icalendar", "python-dateutil" ]
How do I switch this Proxy to use Proxy-Authentication?
1,336,882
<p>I'm trying to modify my simple Twisted web proxy to use "Proxy-Authentication" (username/password) instead of the current IP based authentication. Problem is, I'm new to Twisted and don't even know where to start. </p> <p>Here is my Factory Class.</p> <pre><code>class ProxyFactory(http.HTTPFactory): def __init__(self, ip, internal_ips): http.HTTPFactory.__init__(self) self.ip = ip self.protocol = proxy.Proxy self.INTERNAL_IPS = internal_ips def buildProtocol(self, addr): print addr # IP based authentication -- need to switch this to use standard Proxy password authentication if addr.host not in self.INTERNAL_IPS: return None #p = protocol.ServerFactory.buildProtocol(self, addr) p = self.protocol() p.factory = self # timeOut needs to be on the Protocol instance cause # TimeoutMixin expects it there p.timeOut = self.timeOut return p </code></pre> <p>Any idea what I need to do to make this work? Thanks for your help!</p>
1
2009-08-26T19:15:15Z
1,462,680
<p>A similar question came up on the Twisted mailing list a while ago:</p> <p><a href="http://www.mail-archive.com/twisted-python@twistedmatrix.com/msg01080.html" rel="nofollow">http://www.mail-archive.com/twisted-python@twistedmatrix.com/msg01080.html</a></p> <p>As I mentioned there, you probably need to subclass some of the twisted.proxy classes so that they understand the Proxy-Authenticate and Proxy-Authorization headers.</p>
1
2009-09-22T21:20:05Z
[ "python", "authentication", "proxy", "twisted" ]
Python: Alternatives to pickling a module
1,336,908
<p>I am working on my program, <a href="http://garlicsim.com" rel="nofollow">GarlicSim</a>, in which a user creates a simulation, then he is able to manipulate it as he desires, and then he can save it to file.</p> <p>I recently tried implementing the saving feature. The natural thing that occured to me is to pickle the <code>Project</code> object, which contains the entire simulation.</p> <p>Problem is, the <code>Project</code> object also includes a module-- That is the "simulation package", which is a package/module that contains several critical objects, mostly functions, that define the simulation. I need to save them together with the simulation, but it seems that it is impossible to pickle a module, as I witnessed when I tried to pickle the <code>Project</code> object and an exception was raised.</p> <p>What would be a good way to work around that limitation?</p> <p>(I should also note that the simulation package gets imported dynamically in the program.)</p>
2
2009-08-26T19:19:50Z
1,336,943
<p>If you have the original code for the simulation package modules, which I presume are dynamically generated, then I would suggest serializing that and reconstructing the modules when loaded. You would do this in the <code>Project.__getstate__()</code> and <code>Project.__setstate__()</code> methods.</p>
1
2009-08-26T19:26:28Z
[ "python", "module", "pickle" ]
Python: Alternatives to pickling a module
1,336,908
<p>I am working on my program, <a href="http://garlicsim.com" rel="nofollow">GarlicSim</a>, in which a user creates a simulation, then he is able to manipulate it as he desires, and then he can save it to file.</p> <p>I recently tried implementing the saving feature. The natural thing that occured to me is to pickle the <code>Project</code> object, which contains the entire simulation.</p> <p>Problem is, the <code>Project</code> object also includes a module-- That is the "simulation package", which is a package/module that contains several critical objects, mostly functions, that define the simulation. I need to save them together with the simulation, but it seems that it is impossible to pickle a module, as I witnessed when I tried to pickle the <code>Project</code> object and an exception was raised.</p> <p>What would be a good way to work around that limitation?</p> <p>(I should also note that the simulation package gets imported dynamically in the program.)</p>
2
2009-08-26T19:19:50Z
1,337,012
<p>If the project somehow has a reference to a module with stuff you need, it sounds like you might want to refactor the use of that module into a class within the module. This is often better anyway, because the use of a module for stuff smells of a big fat global. In my experience, such an application structure will only lead to trouble.</p> <p>(Of course the quick way out is to save the module's <strong>dict</strong> instead of the module itself.)</p>
2
2009-08-26T19:39:48Z
[ "python", "module", "pickle" ]
Running doctests through iPython and pseudo-consoles
1,336,980
<p>I've got a fairly basic doctestable file:</p> <pre><code>class Foo(): """ &gt;&gt;&gt; 3+2 5 """ if __name__ in ("__main__", "__console__"): import doctest doctest.testmod(verbose=True) </code></pre> <p>which works as expected when run directly through python.</p> <p>However, in iPython, I get</p> <pre><code>1 items had no tests: __main__ 0 tests in 1 items. 0 passed and 0 failed. Test passed. </code></pre> <p>Since this is part of a Django project and will need access to all of the appropriate variables and such that manage.py sets up, I can also run it through a modified command, which uses code.InteractiveConsole, one result of which is <code>__name__</code> gets set to '<code>__console__</code>'.</p> <p>With the code above, I get the same result as with iPython. I tried changing the last line to this:</p> <pre><code> this = __import__(__name__) doctest.testmod(this, verbose=True) </code></pre> <p>and I get an ImportError on <code>__console__</code>, which makes sense, I guess. This has no effect on either python or ipython.</p> <p>So, I'd like to be able to run doctests successfully through all three of these methods, especially the InteractiveConsole one, since I expect to be needing Django pony magic fairly soon.</p> <p>Just for clarification, this is what I'm expecting:</p> <pre><code>Trying: 3+2 Expecting: 5 ok 1 items had no tests: __main__ 1 items passed all tests: 1 tests in __main__.Foo 1 tests in 2 items. 1 passed and 0 failed. Test passed. </code></pre>
1
2009-08-26T19:33:33Z
1,337,175
<p>The following works:</p> <pre><code>$ ipython ... In [1]: %run file.py Trying: 3+2 Expecting: 5 ok 1 items had no tests: __main__ 1 items passed all tests: 1 tests in __main__.Foo 1 tests in 2 items. 1 passed and 0 failed. Test passed. In [2]: </code></pre> <p>I have no idea why <code>ipython file.py</code> does not work. But the above is at least a workaround.</p> <p><strong>EDIT:</strong></p> <p>I found the reason why it does not work. It is quite simple:</p> <ul> <li>If you do not specify the module to test in <code>doctest.testmod()</code>, it assumes that you want to test the <code>__main__</code> module.</li> <li>When IPython executes the file passed to it on the command line, the <code>__main__</code> module is IPython's <code>__main__</code>, not your module. So doctest tries to execute doctests in IPython's entry script.</li> </ul> <p>The following works, but feels a bit weird:</p> <pre><code>if __name__ == '__main__': import doctest import the_current_module doctest.testmod(the_current_module) </code></pre> <p>So basically the module imports itself (that's the "feels a bit weird" part). But it works. Something I do not like abt. this approach is that every module needs to include its own name in the source.</p> <p><strong>EDIT 2:</strong></p> <p>The following script, <code>ipython_doctest</code>, makes ipython behave the way you want:</p> <pre><code>#! /usr/bin/env bash echo "__IP.magic_run(\"$1\")" &gt; __ipython_run.py ipython __ipython_run.py </code></pre> <p>The script creates a python script that will execute <code>%run argname</code> in IPython.</p> <p>Example:</p> <pre><code>$ ./ipython_doctest file.py Trying: 3+2 Expecting: 5 ok 1 items had no tests: __main__ 1 items passed all tests: 1 tests in __main__.Foo 1 tests in 2 items. 1 passed and 0 failed. Test passed. Python 2.5 (r25:51908, Mar 7 2008, 03:27:42) Type "copyright", "credits" or "license" for more information. IPython 0.9.1 -- An enhanced Interactive Python. ? -&gt; Introduction and overview of IPython's features. %quickref -&gt; Quick reference. help -&gt; Python's own help system. object? -&gt; Details about 'object'. ?object also works, ?? prints more. In [1]: </code></pre>
1
2009-08-26T20:10:54Z
[ "python", "django", "ipython" ]
Running doctests through iPython and pseudo-consoles
1,336,980
<p>I've got a fairly basic doctestable file:</p> <pre><code>class Foo(): """ &gt;&gt;&gt; 3+2 5 """ if __name__ in ("__main__", "__console__"): import doctest doctest.testmod(verbose=True) </code></pre> <p>which works as expected when run directly through python.</p> <p>However, in iPython, I get</p> <pre><code>1 items had no tests: __main__ 0 tests in 1 items. 0 passed and 0 failed. Test passed. </code></pre> <p>Since this is part of a Django project and will need access to all of the appropriate variables and such that manage.py sets up, I can also run it through a modified command, which uses code.InteractiveConsole, one result of which is <code>__name__</code> gets set to '<code>__console__</code>'.</p> <p>With the code above, I get the same result as with iPython. I tried changing the last line to this:</p> <pre><code> this = __import__(__name__) doctest.testmod(this, verbose=True) </code></pre> <p>and I get an ImportError on <code>__console__</code>, which makes sense, I guess. This has no effect on either python or ipython.</p> <p>So, I'd like to be able to run doctests successfully through all three of these methods, especially the InteractiveConsole one, since I expect to be needing Django pony magic fairly soon.</p> <p>Just for clarification, this is what I'm expecting:</p> <pre><code>Trying: 3+2 Expecting: 5 ok 1 items had no tests: __main__ 1 items passed all tests: 1 tests in __main__.Foo 1 tests in 2 items. 1 passed and 0 failed. Test passed. </code></pre>
1
2009-08-26T19:33:33Z
1,351,905
<p>The root problem is that <code>ipython</code> plays weird tricks with <code>__main__</code> (through its own <code>FakeModule</code> module) so that, by the time <code>doctest</code> is introspecting that "alleged module" through its <code>__dict__</code>, <code>Foo</code> is <em>NOT</em> there -- so doctest doesn't recurse into it.</p> <p>Here's one solution:</p> <pre><code>class Foo(): """ &gt;&gt;&gt; 3+2 5 """ if __name__ in ("__main__", "__console__"): import doctest, inspect, sys m = sys.modules['__main__'] m.__test__ = dict((n,v) for (n,v) in globals().items() if inspect.isclass(v)) doctest.testmod(verbose=True) </code></pre> <p>This DOES produce, as requested:</p> <pre><code>$ ipython dot.py Trying: 3+2 Expecting: 5 ok 1 items had no tests: __main__ 1 items passed all tests: 1 tests in __main__.__test__.Foo 1 tests in 2 items. 1 passed and 0 failed. Test passed. Python 2.5.1 (r251:54863, Feb 6 2009, 19:02:12) [[ snip snip ]] In [1]: </code></pre> <p>Just setting global <code>__test__</code> doesn't work, again because setting it as a global of what you're thinking of as <code>__main__</code> does NOT actually place it in the <code>__dict__</code> of the actual object that gets recovered by <code>m = sys.modules['__main__']</code>, and the latter is exactly the expression <code>doctest</code> is using internally (actually it uses <code>sys.modules.get</code>, but the extra precaution is not necessary here since we do know that <code>__main__</code> exists in <code>sys.modules</code>... it's just NOT the object you expect it to be!-).</p> <p>Also, just setting <code>m.__test__ = globals()</code> directly does not work either, for a different reason: <code>doctest</code> checks that the values in <code>__test__</code> are strings, functions, classes, or modules, and without some selection you cannot guarantee that <code>globals()</code> will satisfy that condition (in fact it won't). Here I'm selecting just classes, if you also want functions or whatnot you can use an <code>or</code> in the <code>if</code> clause in the genexp within the <code>dict</code> call.</p> <p>I don't know exactly how you're running a Django shell that's able to execute your script (as I believe <code>python manage.py shell</code> doesn't accept arguments, you must be doing something else, and I can't guess exactly what!-), but a similar approach should help (whether your Django shell is using ipython, the default when available, or plain Python): appropriately setting <code>__test__</code> in the object you obtain as <code>sys.modules['__main__']</code> (or <code>__console__</code>, if that's what you're then passing on to doctest.testmod, I guess) should work, as it mimics what doctest will then be doing internally to locate your test strings.</p> <p>And, to conclude, a philosophical reflection on design, architecture, simplicity, transparency, and "black magic"...:</p> <p>All of this effort is basically what's needed to defeat the "black magic" that ipython (and maybe Django, though it may be simply delegating that part to ipython) is doing on your behalf for your "convenience"... any time at which two frameworks (or more;-) are independently doing each its own brand of black magic, interoperability may suddenly require substantial effort and become anything BUT convenient;-).</p> <p>I'm not saying that the same convenience could have been provided (by any one or more of ipython, django and/or doctests) <em>without</em> black magic, introspection, fake modules, and so on; the designers and maintainers of each of those frameworks are superb engineers, and I expect they've done their homework thoroughly, and are performing only the minimum amount of black magic that's indispensable to deliver the amount of user convenience they decided they needed. Nevertheless, even in such a situation, "black magic" suddenly turns from a dream of convenience to a nightmare of debugging as soon as you want to do something even marginally outside what the framework's author had conceived.</p> <p>OK, maybe in this case not quite a nightmare, but I do notice that this question has been open a while and even with the lure of the bounty it didn't get many answers yet -- though you now do have two answers to pick from, mine using the <code>__test__</code> special feature of doctest, @codeape's using the peculiar <code>__IP.magic_run</code> feature of ironpython. I prefer mine because it does not rely on anything internal or undocumented -- <code>__test__</code> IS a documented feature of doctest, while <code>__IP</code>, with those two looming leading underscores, scream "deep internals, don't touch" to me;-)... if it breaks at the next point release I wouldn't be at all surprised. Still, matter of taste -- that answer may arguably be considered more "convenient".</p> <p>But, this is exactly my point: convenience may come at an enormous price in terms of giving up simplicity, transparency, and/or avoidance of internal/undocumented/unstable features; so, as a lesson for all of us, the least black magic &amp;c we can get away with (even at the price of giving up an epsilon of convenience here and there), the happier we'll all be in the long run (and the happier we'll make other developers that need to leverage our current efforts in the future).</p>
8
2009-08-29T17:05:02Z
[ "python", "django", "ipython" ]
SQLAlchemy Inheritance
1,337,095
<p>I'm a bit confused about inheritance under sqlalchemy, to the point where I'm not even sure what type of inheritance (single table, joined table, concrete) I should be using here. I've got a base class with some information that's shared amongst the subclasses, and some data that are completely separate. Sometimes, I'll want data from all the classes, and sometimes only from the subclasses. Here's an example:</p> <pre><code>class Building: def __init__(self, x, y): self.x = x self.y = y class Commercial(Building): def __init__(self, x, y, business): Building.__init__(self, x, y) self.business = business class Residential(Building): def __init__(self, x, y, numResidents): Building.__init__(self, x, y, layer) self.numResidents = numResidents </code></pre> <p>How would I convert this to SQLAlchemy using declarative? How, then, would I query which buildings are within <code>x&gt;5</code> and <code>y&gt;3</code>? Or which Residential buildings have only 1 resident?</p>
38
2009-08-26T19:57:53Z
1,337,871
<p>Choosing how to represent the inheritance is mostly a database design issue. For performance single table inheritance is usually best. From a good database design point of view, joined table inheritance is better. Joined table inheritance enables you to have foreign keys to subclasses enforced by the database, it's a lot simpler to have non-null constraints for subclass fields. Concrete table inheritance is kind of worst of both worlds.</p> <p>Single table inheritance setup with declarative looks like this:</p> <pre><code>class Building(Base): __tablename__ = 'building' id = Column(Integer, primary_key=True) building_type = Column(String(32), nullable=False) x = Column(Float, nullable=False) y = Column(Float, nullable=False) __mapper_args__ = {'polymorphic_on': building_type} class Commercial(Building): __mapper_args__ = {'polymorphic_identity': 'commercial'} business = Column(String(50)) class Residential(Building): __mapper_args__ = {'polymorphic_identity': 'residential'} num_residents = Column(Integer) </code></pre> <p>To make it joined table inheritance, you'll need to add</p> <pre><code>__tablename__ = 'commercial' id = Column(None, ForeignKey('building.id'), primary_key=True) </code></pre> <p>to the subclasses.</p> <p>Querying is mostly the same with both approaches:</p> <pre><code># buildings that are within x&gt;5 and y&gt;3 session.query(Building).filter((Building.x &gt; 5) &amp; (Building.y &gt; 3)) # Residential buildings that have only 1 resident session.query(Residential).filter(Residential.num_residents == 1) </code></pre> <p>To control which fields are loaded you can use the <code>query.with_polymorphic()</code> method.</p> <p>The most important thing to think about using inheritance for the datamapping, is whether you actually need inheritance or can do with aggregation. Inheritance will be a pain if you will ever need to change the type of an building, or your buildings can have both commercial and residential aspects. In those cases it's usually better to have the commercial and residential aspects as related objects.</p>
57
2009-08-26T22:25:10Z
[ "python", "inheritance", "sqlalchemy" ]
SQLAlchemy Inheritance
1,337,095
<p>I'm a bit confused about inheritance under sqlalchemy, to the point where I'm not even sure what type of inheritance (single table, joined table, concrete) I should be using here. I've got a base class with some information that's shared amongst the subclasses, and some data that are completely separate. Sometimes, I'll want data from all the classes, and sometimes only from the subclasses. Here's an example:</p> <pre><code>class Building: def __init__(self, x, y): self.x = x self.y = y class Commercial(Building): def __init__(self, x, y, business): Building.__init__(self, x, y) self.business = business class Residential(Building): def __init__(self, x, y, numResidents): Building.__init__(self, x, y, layer) self.numResidents = numResidents </code></pre> <p>How would I convert this to SQLAlchemy using declarative? How, then, would I query which buildings are within <code>x&gt;5</code> and <code>y&gt;3</code>? Or which Residential buildings have only 1 resident?</p>
38
2009-08-26T19:57:53Z
1,337,957
<p>Ants Aasma's solution is much more elegant, but if you are keeping your Class definitions separate from your table definitions intentionally, you need to map your classes to your tables with the mapper function. After you have defined your classes, you need to define your tables:</p> <pre><code>building = Table('building', metadata, Column('id', Integer, primary_key=True), Column('x', Integer), Column('y', Integer), ) commercial = Table('commercial', metadata, Column('building_id', Integer, ForeignKey('building.id'), primary_key=True), Column('business', String(50)), ) residential = Table('residential', metadata, Column('building_id', Integer, ForeignKey('building.id'), primary_key=True), Column('numResidents', Integer), )</code></pre> <p>Then you can map the tables to the classes:</p> <pre><code>mapper(Building, building) mapper(Commercial, commercial, inherits=Building, polymorphic_identity='commercial') mapper(Residential, residential, inherits=Building, polymorphic_identity='residential')</code></pre> <p>Then interact with the classes the exact same way Ants Aasma described.</p>
8
2009-08-26T22:42:50Z
[ "python", "inheritance", "sqlalchemy" ]
Is there a Python module for converting RTF to plain text?
1,337,446
<p>Ideally, I'd like a module or library that doesn't require superuser access to install; I have limited privileges in my working environment.</p>
20
2009-08-26T20:56:59Z
1,337,465
<p>There is good library <a href="http://code.google.com/p/pyrtf-ng/" rel="nofollow">pyrtf-ng</a> for all-purpose RTF handling.</p>
1
2009-08-26T21:01:33Z
[ "python", "text", "rtf" ]
Is there a Python module for converting RTF to plain text?
1,337,446
<p>Ideally, I'd like a module or library that doesn't require superuser access to install; I have limited privileges in my working environment.</p>
20
2009-08-26T20:56:59Z
1,337,467
<p>Have you checked out <a href="http://code.google.com/p/pyrtf-ng/" rel="nofollow">pyrtf-ng</a>?</p> <p><strong>Update:</strong> The parsing functionality is available if you do a Subversion checkout, but I'm not sure how full-featured it is. (Look in the <code>rtfng.parser.base</code> module.)</p>
3
2009-08-26T21:01:36Z
[ "python", "text", "rtf" ]
Is there a Python module for converting RTF to plain text?
1,337,446
<p>Ideally, I'd like a module or library that doesn't require superuser access to install; I have limited privileges in my working environment.</p>
20
2009-08-26T20:56:59Z
1,337,815
<p>OpenOffice has a RTF reader. You can use python to script OpenOffice, <a href="http://wiki.services.openoffice.org/wiki/Python" rel="nofollow">see here for more info</a>.</p> <p>You could probably try using the magic com-object on Windows to read anything that smells ms-binary. I wouldn't recommend that though.</p> <p>Actually parsing the raw data probably won't be very hard, <a href="http://www.infionline.net/~wtnewton/batch/rtf2txt.htm" rel="nofollow">see this example</a> written in .bat/QBasic.</p> <p><em><a href="http://www.docfrac.net/" rel="nofollow">DocFrac</a> is a free open source converter betweeen RTF, HTML and text. Windows, Linux, ActiveX and DLL platforms available.</em> It will probably be pretty easy to wrap it up in python.</p> <p><em><a href="http://rpm.pbone.net/index.php3/stat/45/idpl/1146922/numer/3/nazwa/RTF::TEXT::Converter" rel="nofollow">RTF::TEXT::Converter</a> - Perl extension for converting RTF into text</em>. (in case You have problems withg DocFrac).</p> <p>Official Rich Text Format (RTF) <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=e5b8ebc2-6ad6-49f0-8c90-e4f763e3f04f&amp;DisplayLang=en" rel="nofollow">Specifications</a>, version 1.7, by Microsoft.</p> <p>Good luck (with the limited privileges in Your working environment).</p>
7
2009-08-26T22:10:09Z
[ "python", "text", "rtf" ]
Is there a Python module for converting RTF to plain text?
1,337,446
<p>Ideally, I'd like a module or library that doesn't require superuser access to install; I have limited privileges in my working environment.</p>
20
2009-08-26T20:56:59Z
1,573,854
<p>I ran into the same thing ans I was trying to code it myself. It's not that easy but here is what I had when I decided to go for a commandline app. Its ruby but you can adapt to python very easily. There is some header garbage to clean up, but you can see more or less the idea.</p> <pre><code>f = File.open('r.rtf','r') b=0 p=false str = '' begin while (char = f.readchar) if char.chr=='{' b+=1 next end if char.chr=='}' b-=1 next end if char.chr=='\\' p=true next end if p==true &amp;&amp; (char.chr==' ' or char.chr=='\n' or char.chr=='\t' or char.chr=='\r') p=false next end if p==true &amp;&amp; (char.chr=='\'') #this is the source of my headaches. you need to read the code page from the header and encode this. p=false str &lt;&lt; '#' next end next if b&gt;2 next if p str &lt;&lt; char.chr end rescue EOFError end f.close </code></pre>
0
2009-10-15T17:22:44Z
[ "python", "text", "rtf" ]
Is there a Python module for converting RTF to plain text?
1,337,446
<p>Ideally, I'd like a module or library that doesn't require superuser access to install; I have limited privileges in my working environment.</p>
20
2009-08-26T20:56:59Z
1,821,405
<p>I've been working on a library called Pyth, which can do this:</p> <p><a href="http://pypi.python.org/pypi/pyth/">http://pypi.python.org/pypi/pyth/</a></p> <p>Converting an RTF file to plaintext looks something like this:</p> <pre><code>from pyth.plugins.rtf15.reader import Rtf15Reader from pyth.plugins.plaintext.writer import PlaintextWriter doc = Rtf15Reader.read(open('sample.rtf')) print PlaintextWriter.write(doc).getvalue() </code></pre> <p>Pyth can also generate RTF files, read and write XHTML, generate documents from Python markup a la Nevow's stan, and has limited experimental support for latex and pdf output. Its RTF support is <a href="http://github.com/brendonh/pyth/blob/master/pyth/plugins/rtf15/reader.py">pretty robust</a> -- we use it in production to read RTF files generated by various versions of Word, OpenOffice, Mac TextEdit, EIOffice, and others.</p>
36
2009-11-30T18:07:06Z
[ "python", "text", "rtf" ]
Is there a Python module for converting RTF to plain text?
1,337,446
<p>Ideally, I'd like a module or library that doesn't require superuser access to install; I have limited privileges in my working environment.</p>
20
2009-08-26T20:56:59Z
6,353,632
<p>Conversely, if you want to write RTFs easily from Python, you can use the third-party module <a href="https://github.com/viking-sudo-rm/rtflib/blob/master/rtflib.py" rel="nofollow">rtflib</a>. It's a fairly new and incomplete module but still very powerful and useful. Below is an example that writes "hello world" in rich text to an RTF called helloworld.rtf. This is a very primitive example, and the module can also be used to add colors, italics, tables, and many other aspects of rich text to RTF files.</p> <pre><code>from rtflib import * file = RTF("helloworld.rtf") file.startfile() file.addstrict() file.addtext("hello world") file.writeout() </code></pre>
0
2011-06-15T05:55:50Z
[ "python", "text", "rtf" ]
Is there a Python module for converting RTF to plain text?
1,337,446
<p>Ideally, I'd like a module or library that doesn't require superuser access to install; I have limited privileges in my working environment.</p>
20
2009-08-26T20:56:59Z
11,966,087
<p><a href="http://code.google.com/p/pyrtf-ng/" rel="nofollow">PyRTF-ng</a> 0.9.1 has not parsed any of my RTF documents, both with the ParsingException. First document was generated with OpenOffice 3.4, the second one with Mac TextEdit.</p> <p><a href="https://pypi.python.org/pypi/pyth/" rel="nofollow">Pyth</a> 0.5.6 parsed without problems both documents, but has not processed cyrillic symbols properly.</p> <p>But each editor opens other's editor document correctly and without trouble, so all libraries seems to have a weak rtf support.</p> <p>So I'm writing my own parser with with blackjack and hookers.</p> <p>(I've uploaded both files, so you can check RTF libraries by yourself: <a href="http://yadi.sk/d/RMHawVdSD8O9" rel="nofollow">http://yadi.sk/d/RMHawVdSD8O9</a> <a href="http://yadi.sk/d/RmUaSe5tD8OD" rel="nofollow">http://yadi.sk/d/RmUaSe5tD8OD</a>)</p>
1
2012-08-15T08:22:55Z
[ "python", "text", "rtf" ]
Is there a Python module for converting RTF to plain text?
1,337,446
<p>Ideally, I'd like a module or library that doesn't require superuser access to install; I have limited privileges in my working environment.</p>
20
2009-08-26T20:56:59Z
29,842,287
<p>I just came across <a href="http://sourceforge.net/projects/pyrtflib/" rel="nofollow">pyrtflib</a> - there's not much (any) documentation on it, it's kinda a case of installing it and then using the inbuilt help() function to find out what's available and what everything does.</p> <p>Having said that in my little trial run of its rtf.Rtf2Html.getHtml() function it went well enough. I haven't tried the Rtf2Txt function but given the simpler nature of converting rtf to plaintext it should do fine I'd expect.</p>
1
2015-04-24T08:24:15Z
[ "python", "text", "rtf" ]
Is there a Python module for converting RTF to plain text?
1,337,446
<p>Ideally, I'd like a module or library that doesn't require superuser access to install; I have limited privileges in my working environment.</p>
20
2009-08-26T20:56:59Z
38,086,182
<p>Here's a link to a script that converts rtf to text using regex: <a href="http://stackoverflow.com/questions/188545/regular-expression-for-extracting-text-from-an-rtf-string">Regular Expression for extracting text from an RTF string</a></p> <p>Also, and updated link on github: <a href="https://gist.github.com/gilsondev/7c1d2d753ddb522e7bc22511cfb08676" rel="nofollow">Github link</a></p>
1
2016-06-28T20:57:54Z
[ "python", "text", "rtf" ]
Python object @property
1,337,935
<p>I'm trying to create a point class which defines a property called "coordinate". However, it's not behaving like I'd expect and I can't figure out why. </p> <pre><code>class Point: def __init__(self, coord=None): self.x = coord[0] self.y = coord[1] @property def coordinate(self): return (self.x, self.y) @coordinate.setter def coordinate(self, value): self.x = value[0] self.y = value[1] p = Point((0,0)) p.coordinate = (1,2) &gt;&gt;&gt; p.x 0 &gt;&gt;&gt; p.y 0 &gt;&gt;&gt; p.coordinate (1, 2) </code></pre> <p>It seems that p.x and p.y are not getting set for some reason, even though the setter "should" set those values. Anybody know why this is? </p>
6
2009-08-26T22:39:35Z
1,337,976
<p>The <code>property</code> method (and by extension, the <code>@property</code> decorator) <a href="http://docs.python.org/library/functions.html#property">requires a new-style class</a> i.e. a class that subclasses <code>object</code>.</p> <p>For instance,</p> <pre><code>class Point: </code></pre> <p>should be</p> <pre><code>class Point(object): </code></pre> <p>Also, the <code>setter</code> attribute (along with the others) was added in Python 2.6.</p>
9
2009-08-26T22:47:45Z
[ "python", "new-style-class" ]
Python object @property
1,337,935
<p>I'm trying to create a point class which defines a property called "coordinate". However, it's not behaving like I'd expect and I can't figure out why. </p> <pre><code>class Point: def __init__(self, coord=None): self.x = coord[0] self.y = coord[1] @property def coordinate(self): return (self.x, self.y) @coordinate.setter def coordinate(self, value): self.x = value[0] self.y = value[1] p = Point((0,0)) p.coordinate = (1,2) &gt;&gt;&gt; p.x 0 &gt;&gt;&gt; p.y 0 &gt;&gt;&gt; p.coordinate (1, 2) </code></pre> <p>It seems that p.x and p.y are not getting set for some reason, even though the setter "should" set those values. Anybody know why this is? </p>
6
2009-08-26T22:39:35Z
1,337,977
<p>It will work if you derive Point from object:</p> <pre><code>class Point(object): # ... </code></pre>
4
2009-08-26T22:47:46Z
[ "python", "new-style-class" ]
Can I write Python applications using PyObjC that target NON-jailbroken iPhones?
1,338,095
<p>Is it currently possible to compile Python and PyObjC for the iPhone such that AppStore applications can written in Python?</p> <p>If not, is this a purely technical issue or a deliberate policy decision by Apple?</p>
3
2009-08-26T23:18:00Z
1,338,097
<p>no, apple strictly forbids running any kind of interpreter on iphone, and it is completely policy issue.</p>
0
2009-08-26T23:18:54Z
[ "iphone", "python", "pyobjc" ]
Can I write Python applications using PyObjC that target NON-jailbroken iPhones?
1,338,095
<p>Is it currently possible to compile Python and PyObjC for the iPhone such that AppStore applications can written in Python?</p> <p>If not, is this a purely technical issue or a deliberate policy decision by Apple?</p>
3
2009-08-26T23:18:00Z
1,338,105
<p>No: it's Apple's deliberate policy decision (no doubt with some technical underpinnings) to not support interpreters/runtimes on iPhone for most languages -- ObjC (and Javascript within Safari) is what Apple wants you to use, not Python, Java, Ruby, and so forth.</p>
1
2009-08-26T23:20:56Z
[ "iphone", "python", "pyobjc" ]
Configure Django project in a subdirectory using mod_python. Admin not working
1,338,101
<p>HI guys. I was trying to configure my django project in a subdirectory of the root, but didn't get things working.(LOcally it works perfect). I followed the django official django documentarion to deploy a project with mod_python. The real problem is that I am getting "Page not found" errors, whenever I try to go to the admin or any view of my apps. </p> <p>Here is my python.conf file located in /etc/httpd/conf.d/ in Fedora 7</p> <p>LoadModule python_module modules/mod_python.so</p> <p></p> <pre><code>SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE mysite.settings PythonOption django.root /mysite PythonDebug On PythonPath "['/var/www/vhosts/mysite.com/httpdocs','/var/www/vhosts/mysite.com/httpdocs/mysite'] + sys.path" </code></pre> <p></p> <p>I know /var/www/ is not the best place to put my django project, but I just want to send a demo of my work in progress to my customer, later I will change the location.</p> <p>For example. If I go to www.domain.com/mysite/ I get the index view I configured in mysite.urls. But I cannot access to my app.urls (www.domain.com/mysite/app/) and any of the admin.urls.(www.domain.com/mysite/admin/) </p> <p>Here is mysite.urls: </p> <p>urlpatterns = patterns('',</p> <pre><code>url(r'^admin/password_reset/$', 'django.contrib.auth.views.password_reset', name='password_reset'), (r'^password_reset/done/$', 'django.contrib.auth.views.password_reset_done'), (r'^reset/(?P&lt;uidb36&gt;[0-9A-Za-z]+)-(?P&lt;token&gt;.+)/$', 'django.contrib.auth.views.password_reset_confirm'), (r'^reset/done/$', 'django.contrib.auth.views.password_reset_complete'), (r'^$', 'app.views.index'), (r'^admin/', include(admin.site.urls)), (r'^app/', include('mysite.app.urls')), (r'^photologue/', include('photologue.urls')), </code></pre> <p>)</p> <p>I also tried changing admin.site.urls with ''django.contrib.admin.urls' , but it didn't worked. I googled a lot to solve this problem and read how other developers configure their django project, but didn't find too much information to deploy django in a subdirectory. I have the admin enabled in INSTALLED_APPS and the settings.py is ok. </p> <p>Please if you have any guide or telling me what I am doing wrong it will be much appreciated.</p> <p>THanks.</p>
1
2009-08-26T23:19:57Z
1,338,186
<p>I'm using mod_wsgi, so I'm not sure if it's all the same. But in my urls.py, I have:</p> <pre><code>(r'^admin/(.*)', admin.site.root), </code></pre> <p>In my Apache config, I have this:</p> <pre><code>Alias /admin/media/ /usr/lib/python2.5/site-packages/django/contrib/admin/media </code></pre> <p>Your path may vary.</p>
0
2009-08-26T23:53:27Z
[ "python", "django", "deployment", "mod-python" ]
Configure Django project in a subdirectory using mod_python. Admin not working
1,338,101
<p>HI guys. I was trying to configure my django project in a subdirectory of the root, but didn't get things working.(LOcally it works perfect). I followed the django official django documentarion to deploy a project with mod_python. The real problem is that I am getting "Page not found" errors, whenever I try to go to the admin or any view of my apps. </p> <p>Here is my python.conf file located in /etc/httpd/conf.d/ in Fedora 7</p> <p>LoadModule python_module modules/mod_python.so</p> <p></p> <pre><code>SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE mysite.settings PythonOption django.root /mysite PythonDebug On PythonPath "['/var/www/vhosts/mysite.com/httpdocs','/var/www/vhosts/mysite.com/httpdocs/mysite'] + sys.path" </code></pre> <p></p> <p>I know /var/www/ is not the best place to put my django project, but I just want to send a demo of my work in progress to my customer, later I will change the location.</p> <p>For example. If I go to www.domain.com/mysite/ I get the index view I configured in mysite.urls. But I cannot access to my app.urls (www.domain.com/mysite/app/) and any of the admin.urls.(www.domain.com/mysite/admin/) </p> <p>Here is mysite.urls: </p> <p>urlpatterns = patterns('',</p> <pre><code>url(r'^admin/password_reset/$', 'django.contrib.auth.views.password_reset', name='password_reset'), (r'^password_reset/done/$', 'django.contrib.auth.views.password_reset_done'), (r'^reset/(?P&lt;uidb36&gt;[0-9A-Za-z]+)-(?P&lt;token&gt;.+)/$', 'django.contrib.auth.views.password_reset_confirm'), (r'^reset/done/$', 'django.contrib.auth.views.password_reset_complete'), (r'^$', 'app.views.index'), (r'^admin/', include(admin.site.urls)), (r'^app/', include('mysite.app.urls')), (r'^photologue/', include('photologue.urls')), </code></pre> <p>)</p> <p>I also tried changing admin.site.urls with ''django.contrib.admin.urls' , but it didn't worked. I googled a lot to solve this problem and read how other developers configure their django project, but didn't find too much information to deploy django in a subdirectory. I have the admin enabled in INSTALLED_APPS and the settings.py is ok. </p> <p>Please if you have any guide or telling me what I am doing wrong it will be much appreciated.</p> <p>THanks.</p>
1
2009-08-26T23:19:57Z
1,338,190
<p>If your settings.py is correct and has your correct INSTALLED_APPS and it works in the development server, then I'd say it's you Apache configuration file.</p> <p>Try running my python app to create Apache configuration files for mod_python + Django. The source is <a href="http://github.com/hughdbrown/Apache-conf/tree/master" rel="nofollow">here</a> at github.com. Once you have a working configuration file, you can modify it.</p> <p>Run like this:</p> <pre><code>C:\Users\hughdbrown\Documents\django\Apache-conf&gt;python http_conf_gen.py --flavor=mod_python --source_dir=. --server_name=foo.com --project_name=foo Writing 'foo.vhost.python.conf' </code></pre> <p>Result looks like this:</p> <pre><code># apache_template.txt NameVirtualHost *:80 &lt;VirtualHost *:80&gt; ServerAdmin webmaster@foo.com ServerName foo.com DocumentRoot "./foo/" &lt;Location "/"&gt; # without this, you'll get 403 permission errors # Apache - "Client denied by server configuration" allow from all SetHandler python-program PythonHandler django.core.handlers.modpython PythonOption django.root /foo PythonDebug On PythonPath "[os.path.normpath(s) for s in (r'.', r'C:\Python26\lib\site-packages\django') ] + sys.path" SetEnv DJANGO_SETTINGS_MODULE foo.settings PythonAutoReload Off &lt;/Location&gt; &lt;Location "/media" &gt; SetHandler None allow from all &lt;/Location&gt; &lt;Location "/site-media" &gt; SetHandler None allow from all &lt;/Location&gt; &lt;LocationMatch "\.(jpg|gif|png)$"&gt; SetHandler None allow from all &lt;/LocationMatch&gt; &lt;/VirtualHost&gt; </code></pre>
0
2009-08-26T23:54:53Z
[ "python", "django", "deployment", "mod-python" ]
One-liner Python code for setting string to 0 string if empty
1,338,518
<p>What is a one-liner code for setting a string in python to the string, 0 if the string is empty?</p> <pre><code># line_parts[0] can be empty # if so, set a to the string, 0 # one-liner solution should be part of the following line of code if possible a = line_parts[0] ... </code></pre>
10
2009-08-27T02:12:49Z
1,338,529
<pre><code>a = '0' if not line_parts[0] else line_parts[0] </code></pre>
11
2009-08-27T02:15:50Z
[ "python", "string" ]
One-liner Python code for setting string to 0 string if empty
1,338,518
<p>What is a one-liner code for setting a string in python to the string, 0 if the string is empty?</p> <pre><code># line_parts[0] can be empty # if so, set a to the string, 0 # one-liner solution should be part of the following line of code if possible a = line_parts[0] ... </code></pre>
10
2009-08-27T02:12:49Z
1,338,532
<pre><code>a = line_parts[0] or "0" </code></pre> <p>This is one of the nicest Python idioms, making it easy to provide default values. It's often used like this for default values of functions:</p> <pre><code>def fn(arg1, arg2=None): arg2 = arg2 or ["weird default value"] </code></pre>
45
2009-08-27T02:16:41Z
[ "python", "string" ]
java to python conversion: x509 / dsa / sha1withdsa crypto howto?
1,338,546
<p>I've got the following Java code that I'm trying to convert to python, and I'm not really sure how to do this:</p> <pre><code>import java.security.spec.X509EncodedKeySpec; import java.security.KeyFactory; import java.security.PublicKey; import java.security.Signature; byte[] key = KeyReader.read(filestream) //KeyReader.read(inputstream) just reads in the bytes 1 at a time from the filestream X509EncodedKeySpec pubKey = new X509EncodedKeySpec(key); KeyFactory keyFactory = KeyFactory.getInstance("DSA"); PublicKey pub = keyFactory.generatePublic(pubKey); Signature signature = Signature.getInstance("SHA1withDSA"); signature.initVerify(pub) signature.update(a_byte_string) //doesn't matter </code></pre> <p>I'm kinda lost as to how to do this in python. Specifically, the SHA1withDSA part. I just don't know enough about the python crypto libs (m2crypto to be exact) to map the functions (nor could I find any decent writeups on how to do this).</p>
2
2009-08-27T02:22:43Z
1,441,873
<p>I don't exactly understand the Java code, but is this what you are trying to do?</p> <pre><code>from M2Crypto import X509 x509 = X509.load_cert(filename) assert x509.verify() == 1 </code></pre>
1
2009-09-17T23:33:45Z
[ "java", "python", "cryptography", "sha1", "m2crypto" ]
python variable scope
1,338,590
<p>I have started to learn about python and is currently reading through a script written by someone else. I noticed that globals are scattered throughout the script (and I don't like it).. Besides that, I also noticed that when I have code like this</p> <pre><code>def some_function(): foo.some_method() # some other code if __name__ == '__main__' : foo = Some_Object() some_function() </code></pre> <p>even though I don't pass in foo into some_function(), but some_function is still able to manipulate foo (??!). I don't quite like this although it is somewhat similar to Javascript closure (?). I would like to know whether it is possible to stop some_function() from accessing foo if foo is not passed in as a function argument? Or this is the preferred way in python??! (I'm using python 2.5 under ubuntu hardy at the moment)</p>
2
2009-08-27T02:41:30Z
1,338,621
<p>As far as I know, the only way to stop <code>some_function</code> from accessing <code>foo</code> is to eliminate the <code>foo</code> variable from <code>some_function</code>'s scope, possibly like:</p> <pre><code>tmp = foo del foo some_function() foo = tmp </code></pre> <p>Of course, this will crash your (current) code since <code>foo</code> doesn't exist in the scope of <code>some_function</code> anymore.</p> <p>In Python, variables are searched locally, then up in scope until globally, and finally built-ins are searched.</p> <p>Another option <em>could</em> be:</p> <pre><code>with some_object as foo: some_function() </code></pre> <p>But then, you'll have to at least declare <code>some_object.__exit__</code>, maybe <code>some_object.__enter__</code> as well. The end result is that you control which <code>foo</code> is in the scope of <code>some_function</code>. </p> <p>More explanation on the "with" statement <a href="http://effbot.org/zone/python-with-statement.htm" rel="nofollow">here</a>.</p>
2
2009-08-27T02:53:18Z
[ "python" ]
python variable scope
1,338,590
<p>I have started to learn about python and is currently reading through a script written by someone else. I noticed that globals are scattered throughout the script (and I don't like it).. Besides that, I also noticed that when I have code like this</p> <pre><code>def some_function(): foo.some_method() # some other code if __name__ == '__main__' : foo = Some_Object() some_function() </code></pre> <p>even though I don't pass in foo into some_function(), but some_function is still able to manipulate foo (??!). I don't quite like this although it is somewhat similar to Javascript closure (?). I would like to know whether it is possible to stop some_function() from accessing foo if foo is not passed in as a function argument? Or this is the preferred way in python??! (I'm using python 2.5 under ubuntu hardy at the moment)</p>
2
2009-08-27T02:41:30Z
1,338,667
<p>That script has really serious issues with style and organization -- for example, if somebody imports it they have to somehow divine the fact that they have to set <code>thescript.foo</code> to an instance of <code>Some_Object</code> before calling <code>some_function</code>... yeurgh!-)</p> <p>It's unfortunate that you're having to learn Python from a badly written script, but I'm not sure I understand your question. Variable scope in Python is locals (including arguments), nonlocals (i.e., locals of surrounding functions, for nested functions), globals, builtins.</p> <p>Is what you want to stop access to globals? <code>some_function.func_globals</code> is read-only, but you could make a new function with empty globals:</p> <pre><code>import new f=new.function(some_function.func_code, {}) </code></pre> <p>now calling <code>f()</code> will given an exception <code>NameError: global name 'foo' is not defined</code>. You could set this back in the module with the name <code>some_function</code>, or even do it systematically via a decorator, e.g.:</p> <pre><code>def noglobal(f): return new.function(f.func_code, {}) ... @noglobal def some_function(): ... </code></pre> <p>this will guarantee the exception happens whenever <code>some_function</code> is called. I'm not clear on what benefit you expect to derive from that, though. Maybe you can clarify...?</p>
4
2009-08-27T03:11:48Z
[ "python" ]
python variable scope
1,338,590
<p>I have started to learn about python and is currently reading through a script written by someone else. I noticed that globals are scattered throughout the script (and I don't like it).. Besides that, I also noticed that when I have code like this</p> <pre><code>def some_function(): foo.some_method() # some other code if __name__ == '__main__' : foo = Some_Object() some_function() </code></pre> <p>even though I don't pass in foo into some_function(), but some_function is still able to manipulate foo (??!). I don't quite like this although it is somewhat similar to Javascript closure (?). I would like to know whether it is possible to stop some_function() from accessing foo if foo is not passed in as a function argument? Or this is the preferred way in python??! (I'm using python 2.5 under ubuntu hardy at the moment)</p>
2
2009-08-27T02:41:30Z
1,338,805
<p>In python, something like <code>foo</code> is not a value, it's a <em>name</em>. When you try to access it, python tries to find the value associated with it (like dereferencing a pointer). It does this by first looking in the local scope (the function), then working its way outwards until it reaches the module scope (i.e. global), and finally builtins, until it finds something matching the name.</p> <p>That makes something like this work:</p> <pre><code>def foo(): bar() def bar(): pass </code></pre> <p>Despite the fact that <code>bar</code> doesn't exist when you defined <code>foo</code>, the function will work because you later defined <code>bar</code> in a scope that encloses <code>foo</code>.</p> <p>Exactly the same thing is going on in the code you post, it's just that <code>foo</code> is the output of <code>Some_Object()</code>, not a function definition.</p> <p>As Alex said, the fact that you <em>can</em> write code like that does not mean that you <em>should</em>.</p>
1
2009-08-27T04:06:41Z
[ "python" ]
Good way of handling NoneType objects when printing in Python
1,338,690
<p>How do I go about printin a NoneType object in Python?</p> <pre><code># score can be a NonType object logging.info("NEW_SCORE : "+score) </code></pre> <p>Also why is that sometime I see a comma instead of the + above?</p>
4
2009-08-27T03:22:55Z
1,338,693
<pre><code>logging.info("NEW_SCORE : " + str(score)) </code></pre> <p>Proof by Python interpreter:</p> <pre><code>&gt;&gt;&gt; x = None &gt;&gt;&gt; "x: " + x Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: cannot concatenate 'str' and 'NoneType' objects &gt;&gt;&gt; "x: " + str(x) 'x: None' </code></pre> <p>QED</p>
4
2009-08-27T03:24:24Z
[ "python", "string" ]
Good way of handling NoneType objects when printing in Python
1,338,690
<p>How do I go about printin a NoneType object in Python?</p> <pre><code># score can be a NonType object logging.info("NEW_SCORE : "+score) </code></pre> <p>Also why is that sometime I see a comma instead of the + above?</p>
4
2009-08-27T03:22:55Z
1,338,726
<p>The best approach is:</p> <pre><code>logging.info("NEW_SCORE: %s", score) </code></pre> <p>In most contexts, you'd have to use a <code>%</code> operator between the format string on the left and the value(s) on the right (in a tuple, if more than one). But the <code>logging</code> functions are special: you pass the format string as the first argument, then, one after the other, just as many arguments as needed to match the number of <code>%s</code> &amp;c formatting markers in the format, and the <code>logging</code> functions will use the formatting operator <code>%s</code> as appropriate <em>if and only if</em> necessary -- so you don't incur any runtime overhead if your current logging level is such that, e.g., <code>logging.info</code> is not actually going to be shown.</p> <p>Forget <code>str</code> calls and <code>+</code>-based string concatenation anyway -- even without <code>logging</code>'s specials, <code>%</code>-formatting is really the way to go (in Python 2.6 or earlier; in 2.6 or later, you should also consider strings' <code>format</code> method, allowing clearer and more readable expression of what amounts to the same functionality).</p>
8
2009-08-27T03:39:36Z
[ "python", "string" ]
Good way of handling NoneType objects when printing in Python
1,338,690
<p>How do I go about printin a NoneType object in Python?</p> <pre><code># score can be a NonType object logging.info("NEW_SCORE : "+score) </code></pre> <p>Also why is that sometime I see a comma instead of the + above?</p>
4
2009-08-27T03:22:55Z
1,338,755
<p>For print purpose,you need to str first. A comma is to print with a single space between it..For example:</p> <p>print "hi guys","how are you today"</p> <p><em>this syntax will output:</em></p> <p>hi guys how are you today</p> <p>but it will be different if your syntax like this:</p> <p>print "hi guys"+"how are you today"</p> <p><em>this syntax will output:</em></p> <p>hi guyshow are you today</p>
0
2009-08-27T03:49:19Z
[ "python", "string" ]
Good way of handling NoneType objects when printing in Python
1,338,690
<p>How do I go about printin a NoneType object in Python?</p> <pre><code># score can be a NonType object logging.info("NEW_SCORE : "+score) </code></pre> <p>Also why is that sometime I see a comma instead of the + above?</p>
4
2009-08-27T03:22:55Z
14,646,844
<p>if not score==None: logging.info("NEW_SCORE : "+score)</p> <p>or</p> <p>logging.info("NEW_SCORE: %s" % str(score) )</p>
0
2013-02-01T12:58:02Z
[ "python", "string" ]
Parameter binding using GQL in Google App Engine
1,338,704
<p>Okay so I have this mode:</p> <pre><code>class Posts(db.Model): rand1 = db.FloatProperty() #other models here </code></pre> <p>and this controller:</p> <pre><code>class Random(webapp.RequestHandler): def get(self): rand2 = random.random() posts_query = db.GqlQuery("SELECT * FROM Posts WHERE rand1 &gt; :rand2 ORDER BY rand LIMIT 1") #Assigning values for Django templating template_values = { 'posts_query': posts_query, #test purposes 'rand2': rand2, } path = os.path.join(os.path.dirname(__file__), 'templates/random.html') self.response.out.write(template.render(path, template_values)) </code></pre> <p>So when an entity is added a random float is generated (0-1) and then when I need to grab a random entity I want to be able to just use a simple SELECT query. It errors with: </p> <pre><code>BadArgumentError('Missing named arguments for bind, requires argument rand2',) </code></pre> <p>Now this works if I go:</p> <pre><code>posts_query = db.GqlQuery("SELECT * FROM Posts WHERE rand1 &gt; 1 ORDER BY rand LIMIT 1") </code></pre> <p>So clearly my query is wrong; how does one use a variable in a where statement :S</p>
2
2009-08-27T03:28:56Z
1,338,732
<p>Substitute:</p> <pre><code> "...WHERE rand1 &gt; :rand2 ORDER BY rand LIMIT 1") </code></pre> <p>with:</p> <pre><code> "...WHERE rand1 &gt; :rand2 ORDER BY rand LIMIT 1", rand2=rand2) </code></pre> <p>Or</p> <pre><code> "...WHERE rand1 &gt; :1 ORDER BY rand LIMIT 1", rand2) </code></pre> <p>See for more information: "<a href="http://code.google.com/appengine/docs/python/datastore/gqlqueryclass.html" rel="nofollow">The Gql query class</a>"</p> <p><sub> The funny thing is that I have just learned this about 2 hrs ago :P </sub></p>
3
2009-08-27T03:40:41Z
[ "python", "django", "google-app-engine", "binding", "gql" ]
Accesing dictionary with class attribute
1,338,714
<p>now i am working with python. So one question about dict .... suppose i have a dict that </p> <pre><code>config = {'account_receivable': '4', 'account_payable': '5', 'account_cogs': '8', 'accoun t_retained_earning': '9', 'account_income': '6', 'account_expense': '31', 'durat ion': 2, 'financial_year_month': 9, 'financial_year_day': 15, 'account_cash': '3 ', 'account_inventory': '2', 'account_accumulated_depriciation': '34', 'account_ depriciation_expense': '35', 'account_salary_expense': '30', 'account_payroll_pa yable': '68', 'account_discount': '36', 'financial_year_close': '2008-08-08'} </code></pre> <p>if print --> config['account_receivable'] it will return its corresponding value that 4</p> <p>but i want to access it by that way--> config.account_receivable and then it will return it corresponding value</p> <p>how i can implement this??? if any one can please help me</p> <p>BR// nazmul</p>
4
2009-08-27T03:34:08Z
1,338,719
<p>Well, you could do it with a bunch of objects.</p> <pre><code>class Config(object): pass config = Config() config.account_receivable = 4 print config.account_receivable </code></pre> <p>Obviously you can extend this class to do more for you. e.g. define <code>__init__</code> so you can create it with arguments, and perhaps defaults.</p> <p>You could possibly also use a <a href="http://docs.python.org/library/collections.html" rel="nofollow">namedtuple</a> (<a href="http://code.activestate.com/recipes/500261/" rel="nofollow">python 2.4/2.5 link</a>). This is a data structure specifically designed to hold structured records.</p> <pre><code>from collections import namedtuple Config = namedtuple('Config', 'account_receivable account_payable') # etc -- list all the fields c = Config(account_receivable='4', account_payable='5') print c.account_receivable </code></pre> <p>With namedtuples, you cannot change values once they have been set.</p>
0
2009-08-27T03:36:29Z
[ "python", "dictionary" ]
Accesing dictionary with class attribute
1,338,714
<p>now i am working with python. So one question about dict .... suppose i have a dict that </p> <pre><code>config = {'account_receivable': '4', 'account_payable': '5', 'account_cogs': '8', 'accoun t_retained_earning': '9', 'account_income': '6', 'account_expense': '31', 'durat ion': 2, 'financial_year_month': 9, 'financial_year_day': 15, 'account_cash': '3 ', 'account_inventory': '2', 'account_accumulated_depriciation': '34', 'account_ depriciation_expense': '35', 'account_salary_expense': '30', 'account_payroll_pa yable': '68', 'account_discount': '36', 'financial_year_close': '2008-08-08'} </code></pre> <p>if print --> config['account_receivable'] it will return its corresponding value that 4</p> <p>but i want to access it by that way--> config.account_receivable and then it will return it corresponding value</p> <p>how i can implement this??? if any one can please help me</p> <p>BR// nazmul</p>
4
2009-08-27T03:34:08Z
1,338,720
<p>Have a look at <a href="http://stackoverflow.com/questions/1305532/convert-python-dict-to-object">http://stackoverflow.com/questions/1305532/convert-python-dict-to-object</a>.</p>
3
2009-08-27T03:37:15Z
[ "python", "dictionary" ]
Accesing dictionary with class attribute
1,338,714
<p>now i am working with python. So one question about dict .... suppose i have a dict that </p> <pre><code>config = {'account_receivable': '4', 'account_payable': '5', 'account_cogs': '8', 'accoun t_retained_earning': '9', 'account_income': '6', 'account_expense': '31', 'durat ion': 2, 'financial_year_month': 9, 'financial_year_day': 15, 'account_cash': '3 ', 'account_inventory': '2', 'account_accumulated_depriciation': '34', 'account_ depriciation_expense': '35', 'account_salary_expense': '30', 'account_payroll_pa yable': '68', 'account_discount': '36', 'financial_year_close': '2008-08-08'} </code></pre> <p>if print --> config['account_receivable'] it will return its corresponding value that 4</p> <p>but i want to access it by that way--> config.account_receivable and then it will return it corresponding value</p> <p>how i can implement this??? if any one can please help me</p> <p>BR// nazmul</p>
4
2009-08-27T03:34:08Z
1,338,730
<p><strong>You need to use one of Python's <a href="http://docs.python.org/reference/datamodel.html#customizing-attribute-access" rel="nofollow">special methods</a>.</strong></p> <pre><code>class config(object): def __init__(self, data): self.data = data def __getattr__(self, name): return self.data[name] c = config(data_dict) print c.account_discount -&gt; 36 </code></pre>
2
2009-08-27T03:40:01Z
[ "python", "dictionary" ]
Accesing dictionary with class attribute
1,338,714
<p>now i am working with python. So one question about dict .... suppose i have a dict that </p> <pre><code>config = {'account_receivable': '4', 'account_payable': '5', 'account_cogs': '8', 'accoun t_retained_earning': '9', 'account_income': '6', 'account_expense': '31', 'durat ion': 2, 'financial_year_month': 9, 'financial_year_day': 15, 'account_cash': '3 ', 'account_inventory': '2', 'account_accumulated_depriciation': '34', 'account_ depriciation_expense': '35', 'account_salary_expense': '30', 'account_payroll_pa yable': '68', 'account_discount': '36', 'financial_year_close': '2008-08-08'} </code></pre> <p>if print --> config['account_receivable'] it will return its corresponding value that 4</p> <p>but i want to access it by that way--> config.account_receivable and then it will return it corresponding value</p> <p>how i can implement this??? if any one can please help me</p> <p>BR// nazmul</p>
4
2009-08-27T03:34:08Z
1,338,737
<p>You can do this with collections.namedtuple:</p> <pre><code>from collections import namedtuple config_object = namedtuple('ConfigClass', config.keys())(*config.values()) print config_object.account_receivable </code></pre> <p>You can learn more about namedtuple here:</p> <p><a href="http://docs.python.org/dev/library/collections.html">http://docs.python.org/dev/library/collections.html</a></p>
7
2009-08-27T03:42:05Z
[ "python", "dictionary" ]
Accesing dictionary with class attribute
1,338,714
<p>now i am working with python. So one question about dict .... suppose i have a dict that </p> <pre><code>config = {'account_receivable': '4', 'account_payable': '5', 'account_cogs': '8', 'accoun t_retained_earning': '9', 'account_income': '6', 'account_expense': '31', 'durat ion': 2, 'financial_year_month': 9, 'financial_year_day': 15, 'account_cash': '3 ', 'account_inventory': '2', 'account_accumulated_depriciation': '34', 'account_ depriciation_expense': '35', 'account_salary_expense': '30', 'account_payroll_pa yable': '68', 'account_discount': '36', 'financial_year_close': '2008-08-08'} </code></pre> <p>if print --> config['account_receivable'] it will return its corresponding value that 4</p> <p>but i want to access it by that way--> config.account_receivable and then it will return it corresponding value</p> <p>how i can implement this??? if any one can please help me</p> <p>BR// nazmul</p>
4
2009-08-27T03:34:08Z
1,338,739
<p>For that purpose, lo that many years ago, I invented the simple <code>Bunch</code> idiom; one simple way to implement <code>Bunch</code> is:</p> <pre><code>class Bunch(object): def __init__(self, adict): self.__dict__.update(adict) </code></pre> <p>If <code>config</code> is a dict, you can't use <code>config.account_receivable</code> -- that's absolutely impossible, because a dict doesn't <strong>have</strong> that attribute, period. However, you <em>can</em> wrap <code>config</code> into a <code>Bunch</code>:</p> <pre><code>cb = Bunch(config) </code></pre> <p>and then access <code>cb.config_account</code> to your heart's content!</p> <p><strong>Edit</strong>: if you want <em>attribute assignment</em> on the <code>Bunch</code> to also affect the original <code>dict</code> (<code>config</code> in this case), so that e.g. <code>cb.foo = 23</code> will do <code>config['foo'] = 23</code>, you need a slighly different implementation of <code>Bunch</code>:</p> <pre><code>class RwBunch(object): def __init__(self, adict): self.__dict__ = adict </code></pre> <p>Normally, the plain <code>Bunch</code> is preferred, exactly <em>because</em>, after instantiation, the <code>Bunch</code> instance and the <code>dict</code> it was "primed" from are entirely decoupled -- changes to either of them do not affect the other; and such decoupling, most often, is what's desired.</p> <p>When you <strong>do</strong> want "coupling" effects, then <code>RwBunch</code> is the way to get them: with it, every attribute setting or deletion on the instance will intrinsically set or delete the item from the <code>dict</code>, and, vice versa, setting or deleting items from the <code>dict</code> will intrinsically set or delete attributes from the instance.</p>
12
2009-08-27T03:42:59Z
[ "python", "dictionary" ]
Accesing dictionary with class attribute
1,338,714
<p>now i am working with python. So one question about dict .... suppose i have a dict that </p> <pre><code>config = {'account_receivable': '4', 'account_payable': '5', 'account_cogs': '8', 'accoun t_retained_earning': '9', 'account_income': '6', 'account_expense': '31', 'durat ion': 2, 'financial_year_month': 9, 'financial_year_day': 15, 'account_cash': '3 ', 'account_inventory': '2', 'account_accumulated_depriciation': '34', 'account_ depriciation_expense': '35', 'account_salary_expense': '30', 'account_payroll_pa yable': '68', 'account_discount': '36', 'financial_year_close': '2008-08-08'} </code></pre> <p>if print --> config['account_receivable'] it will return its corresponding value that 4</p> <p>but i want to access it by that way--> config.account_receivable and then it will return it corresponding value</p> <p>how i can implement this??? if any one can please help me</p> <p>BR// nazmul</p>
4
2009-08-27T03:34:08Z
1,339,772
<p>You can subclass dict to return items from itself for undefined attributes:</p> <pre><code>class AttrAccessibleDict(dict): def __getattr__(self, key): try: return self[key] except KeyError: return AttributeError(key) config = AttrAccessibleDict(config) print(config.account_receivable) </code></pre> <p>You might also want to override some other methods as well, such as <code>__setattr__</code>, <code>__delattr__</code>, <code>__str__</code>, <code>__repr__</code> and <code>copy</code>.</p>
0
2009-08-27T08:51:58Z
[ "python", "dictionary" ]
Is it crazy to not rely on a caching system like memcached nowadays ( for dynamic sites )?
1,338,777
<p>I was just reviewing one of my client's applications which uses some old outdated php framework that doesn't rely on caching at all and is pretty much completely database dependent.</p> <p>I figure I'll just rewrite it from scratch because it's <em>really</em> outdated and in this rewrite I want to implement a caching system. It'd be nice if I could get a few pointers if anyone has done this prior.</p> <ul> <li>Rewrite will be done in either PHP or Python</li> <li>Would be nice if I could profile before and after this implementation</li> <li>I have my own server so I'm not restricted by shared hosting</li> </ul>
2
2009-08-27T03:57:36Z
1,338,804
<p>Since Python is one of your choices, I would go with Django. Built-in caching mechanism, and I've been using <a href="http://github.com/dcramer/django-debug-toolbar/tree/master" rel="nofollow">this debug_toolbar</a> to help me while developing/profiling.</p> <p>By the way, memcached does <strong>not</strong> work the way you've described. It maps unique keys to values in memory, it has nothing to do with .csh files or database queries. What you store in a value is what's going to be cached.</p> <p>Oh, and caching is only worth if there are (or will be) performance problems. There's nothing wrong with "not relying" with caches if you don't need it. Premature optimization is 99% evil!</p>
3
2009-08-27T04:06:25Z
[ "php", "python", "memcached", "scalability" ]
Is it crazy to not rely on a caching system like memcached nowadays ( for dynamic sites )?
1,338,777
<p>I was just reviewing one of my client's applications which uses some old outdated php framework that doesn't rely on caching at all and is pretty much completely database dependent.</p> <p>I figure I'll just rewrite it from scratch because it's <em>really</em> outdated and in this rewrite I want to implement a caching system. It'd be nice if I could get a few pointers if anyone has done this prior.</p> <ul> <li>Rewrite will be done in either PHP or Python</li> <li>Would be nice if I could profile before and after this implementation</li> <li>I have my own server so I'm not restricted by shared hosting</li> </ul>
2
2009-08-27T03:57:36Z
1,338,810
<p>If your site performance is fine then there's no reason to add caching. Lots of sites can get by without any cache at all, or by moving to a file-system based cache. It's only the super high traffic sites that need memcached.</p> <p>What's "crazy" is code architecture (or a lack of architecture) that makes adding caching in latter difficult. </p>
6
2009-08-27T04:08:29Z
[ "php", "python", "memcached", "scalability" ]
Is it crazy to not rely on a caching system like memcached nowadays ( for dynamic sites )?
1,338,777
<p>I was just reviewing one of my client's applications which uses some old outdated php framework that doesn't rely on caching at all and is pretty much completely database dependent.</p> <p>I figure I'll just rewrite it from scratch because it's <em>really</em> outdated and in this rewrite I want to implement a caching system. It'd be nice if I could get a few pointers if anyone has done this prior.</p> <ul> <li>Rewrite will be done in either PHP or Python</li> <li>Would be nice if I could profile before and after this implementation</li> <li>I have my own server so I'm not restricted by shared hosting</li> </ul>
2
2009-08-27T03:57:36Z
1,338,828
<p>Caching, when it works right (==high hit rate), is one of the few general-purpose techniques that can really help with <em>latency</em> -- the harder part of problems generically describes as "performance". You can enhance <em>QPS</em> (queries per second) measures of performance just by throwing more hardware at the problem -- but latency doesn't work that way (i.e., it doesn't take just one month to make a babies if you set nine mothers to work on it;-).</p> <p>However, the main resource used by caching is typically <em>memory</em> (RAM or disk as it may be). As you mention in a comment that the only performance problem you observe is memory usage, caching wouldn't help: it would just earmark some portion of memory to use for caching purposes, leaving even less available as a "general fund". As a resident of California I'm witnessing first-hand what happens when too many resources are earmarked, and I couldn't recommend such a course of action with a clear conscience!-)</p>
9
2009-08-27T04:18:05Z
[ "php", "python", "memcached", "scalability" ]
Is it crazy to not rely on a caching system like memcached nowadays ( for dynamic sites )?
1,338,777
<p>I was just reviewing one of my client's applications which uses some old outdated php framework that doesn't rely on caching at all and is pretty much completely database dependent.</p> <p>I figure I'll just rewrite it from scratch because it's <em>really</em> outdated and in this rewrite I want to implement a caching system. It'd be nice if I could get a few pointers if anyone has done this prior.</p> <ul> <li>Rewrite will be done in either PHP or Python</li> <li>Would be nice if I could profile before and after this implementation</li> <li>I have my own server so I'm not restricted by shared hosting</li> </ul>
2
2009-08-27T03:57:36Z
1,338,864
<p>Depending on the specific nature of the codebase and traffic patterns, you might not even need to re-write the whole site. Horribly inefficient code is not such a big deal if it can be bypassed via cache for 99.9% of page requests.</p> <p>When choosing PHP or Python, make sure you figure out where you're going to host the site (or if you even get to make that call). Many of my clients are already set up on a webserver and Python is not an option. You should also make sure any databases/external programs you want to interface with are well-supported in PHP or Python.</p>
0
2009-08-27T04:34:43Z
[ "php", "python", "memcached", "scalability" ]
Attribute Error in Python
1,338,847
<p>I'm trying to add a unittest attribute to an object in Python</p> <pre><code>class Boy: def run(self, args): print("Hello") class BoyTest(unittest.TestCase) def test(self) self.assertEqual('2' , '2') def self_test(): suite = unittest.TestSuite() loader = unittest.TestLoader() suite.addTest(loader.loadTestsFromTestCase(Boy.BoyTest)) return suite </code></pre> <p>However, I keep getting <code>"AttributeError: class Boy has no attribute 'BoyTest'"</code> whenever I call <code>self_test()</code>. Why?</p>
0
2009-08-27T04:28:57Z
1,338,860
<p>As the argument of <code>loadTestsFromTestCase</code>, you're trying to access <code>Boy.BoyTest</code>, i.e., the <code>BoyTest</code> attribute of class object <code>Boy</code>, which just doesn't exist, as the error msg is telling you. Why don't you just use <code>BoyTest</code> there instead?</p>
3
2009-08-27T04:33:25Z
[ "python", "attributeerror" ]
Attribute Error in Python
1,338,847
<p>I'm trying to add a unittest attribute to an object in Python</p> <pre><code>class Boy: def run(self, args): print("Hello") class BoyTest(unittest.TestCase) def test(self) self.assertEqual('2' , '2') def self_test(): suite = unittest.TestSuite() loader = unittest.TestLoader() suite.addTest(loader.loadTestsFromTestCase(Boy.BoyTest)) return suite </code></pre> <p>However, I keep getting <code>"AttributeError: class Boy has no attribute 'BoyTest'"</code> whenever I call <code>self_test()</code>. Why?</p>
0
2009-08-27T04:28:57Z
1,340,156
<p>As Alex has stated you are trying to use BoyTest as an attibute of Boy:</p> <pre><code>class Boy: def run(self, args): print("Hello") class BoyTest(unittest.TestCase) def test(self) self.assertEqual('2' , '2') def self_test(): suite = unittest.TestSuite() loader = unittest.TestLoader() suite.addTest(loader.loadTestsFromTestCase(BoyTest)) return suite </code></pre> <p>Note the change:</p> <pre><code>suite.addTest(loader.loadTestsFromTestCase(Boy.BoyTest)) </code></pre> <p>to:</p> <pre><code>suite.addTest(loader.loadTestsFromTestCase(BoyTest)) </code></pre> <p>Does this solve your problem?</p>
-1
2009-08-27T10:23:31Z
[ "python", "attributeerror" ]
accessing base class primitive type in python
1,338,858
<p>I am trying to derive a class from a python primitive, the float, for the purpose of printing a different repr string when it's printed out.</p> <p>How do I access the underlying data from the derived class when I do this?</p> <p>Here's a simplified example of what I am trying to do:</p> <pre><code>class efloat(float): def __repr__(self): return "here's my number: %s" % str(WHAT CAN I PUT HERE???) </code></pre> <p>Ok, thanks folks! I think I get it now. Here's the finished class for anyone who's curious:</p> <pre><code>import math class efloat(float): """efloat(x) -&gt; floating point number with engineering representation when printed Convert a string or a number to a floating point number, if possible. When asked to render itself for printing (via str() or print) it is normalized to engineering style notation at powers of 10 in multiples of 3 (for micro, milli, kilo, mega, giga, etc.) """ def _exponent(self): if self == 0.0: ret = 0 else: ret = math.floor(math.log10(abs(self))) return ret def _mantissa(self): return self/math.pow(10, self._exponent()) def _asEng(self): shift = self._exponent() % 3 retval = "%3.12ge%+d" % (self._mantissa()*math.pow(10, shift), self._exponent() - shift) return retval def __str__(self): return self._asEng() def __repr__(self): return str(self) def __add__(self, x): return efloat(float.__add__(self, float(x))) def __radd__(self, x): return efloat(float.__add__(self, float(x))) def __mul__(self, x): return efloat(float.__mul__(self, float(x))) def __rmul__(self, x): return efloat(float.__mul__(self, float(x))) def __sub__(self, x): return efloat(float.__sub__(self, float(x))) def __rsub__(self, x): return efloat(float.__rsub__(self, float(x))) def __div__(self, x): return efloat(float.__div__(self, float(x))) def __rdiv__(self, x): return efloat(float.__rdiv__(self, float(x))) def __truediv__(self, x): return efloat(float.__truediv__(self, float(x))) def __rtruediv__(self, x): return efloat(float.__rtruediv__(self, float(x))) def __pow__(self, x): return efloat(float.__pow__(self, float(x))) def __rpow__(self, x): return efloat(float.__rpow__(self, float(x))) def __divmod__(self, x): return efloat(float.__divmod__(self, float(x))) def __neg__(self): return efloat(float.__neg__(self)) def __floordiv__(self, x): return efloat(float.__floordiv__(self, float(x))) </code></pre>
2
2009-08-27T04:32:57Z
1,338,866
<p>If you don't override <code>__str__</code>, that will still access the underlying method, so:</p> <pre><code>class efloat(float): def __repr__(self): return "here's my number: %s" % self </code></pre> <p>will work. More generally, you could use <code>self+0</code>, <code>self*1</code>, or any other identity manipulation that you did not explicitly override; if you overrode them all, worst case, <code>float.__add__(self, 0)</code> or the like.</p>
4
2009-08-27T04:35:38Z
[ "python", "class", "floating-point" ]
accessing base class primitive type in python
1,338,858
<p>I am trying to derive a class from a python primitive, the float, for the purpose of printing a different repr string when it's printed out.</p> <p>How do I access the underlying data from the derived class when I do this?</p> <p>Here's a simplified example of what I am trying to do:</p> <pre><code>class efloat(float): def __repr__(self): return "here's my number: %s" % str(WHAT CAN I PUT HERE???) </code></pre> <p>Ok, thanks folks! I think I get it now. Here's the finished class for anyone who's curious:</p> <pre><code>import math class efloat(float): """efloat(x) -&gt; floating point number with engineering representation when printed Convert a string or a number to a floating point number, if possible. When asked to render itself for printing (via str() or print) it is normalized to engineering style notation at powers of 10 in multiples of 3 (for micro, milli, kilo, mega, giga, etc.) """ def _exponent(self): if self == 0.0: ret = 0 else: ret = math.floor(math.log10(abs(self))) return ret def _mantissa(self): return self/math.pow(10, self._exponent()) def _asEng(self): shift = self._exponent() % 3 retval = "%3.12ge%+d" % (self._mantissa()*math.pow(10, shift), self._exponent() - shift) return retval def __str__(self): return self._asEng() def __repr__(self): return str(self) def __add__(self, x): return efloat(float.__add__(self, float(x))) def __radd__(self, x): return efloat(float.__add__(self, float(x))) def __mul__(self, x): return efloat(float.__mul__(self, float(x))) def __rmul__(self, x): return efloat(float.__mul__(self, float(x))) def __sub__(self, x): return efloat(float.__sub__(self, float(x))) def __rsub__(self, x): return efloat(float.__rsub__(self, float(x))) def __div__(self, x): return efloat(float.__div__(self, float(x))) def __rdiv__(self, x): return efloat(float.__rdiv__(self, float(x))) def __truediv__(self, x): return efloat(float.__truediv__(self, float(x))) def __rtruediv__(self, x): return efloat(float.__rtruediv__(self, float(x))) def __pow__(self, x): return efloat(float.__pow__(self, float(x))) def __rpow__(self, x): return efloat(float.__rpow__(self, float(x))) def __divmod__(self, x): return efloat(float.__divmod__(self, float(x))) def __neg__(self): return efloat(float.__neg__(self)) def __floordiv__(self, x): return efloat(float.__floordiv__(self, float(x))) </code></pre>
2
2009-08-27T04:32:57Z
1,339,725
<p>You can call the base class methods, by accessing them off the base class to get an unbound method and call them with self:</p> <pre><code>class myfloat(float): def __str__(self): return "My float is " + float.__str__(self) print(myfloat(4.5)) </code></pre>
2
2009-08-27T08:42:25Z
[ "python", "class", "floating-point" ]
What wrong when SimpleXMLRPC and DBusGMainLoop working in the same time
1,339,003
<p>In python I try create a service that maintain calling event between SflPhone(dbus service) and external app, when I start SimpleXMLRPCServer my service no longer response for any calling event, such as on_call_state_changed function was not called. </p> <p>When I comment out <strong><code>thread.start_new_thread(start_server(s,))</code></strong> everything is work well. I don't know how to make this two thing work together. Does one can help? Thank.</p> <pre><code>import dbus from dbus.mainloop.glib import DBusGMainLoop import gobject from gobject import GObject from SimpleXMLRPCServer import SimpleXMLRPCServer import thread from os import path class SlfPhoneConnector : def __init__(self) : self.activeCalls = {} account = { "username" : "1111", "Account.type" : "SIP", "hostname" : "192.168.1.109", "Account.alias" : "1111", "password":"1111", "Account.enable" : "TRUE" } session = dbus.SessionBus() conf_obj = session.get_object("org.sflphone.SFLphone", "/org/sflphone/SFLphone/ConfigurationManager") self.conf_mgr = dbus.Interface(conf_obj ,"org.sflphone.SFLphone.ConfigurationManager") call_obj = session.get_object("org.sflphone.SFLphone", "/org/sflphone/SFLphone/CallManager") self.call_mgr = dbus.Interface(call_obj ,"org.sflphone.SFLphone.CallManager") self.call_mgr.connect_to_signal('incomingCall', self.on_incoming_call) self.call_mgr.connect_to_signal('callStateChanged', self.on_call_state_changed) self.account_id = self.conf_mgr.addAccount(account) self.conf_mgr.sendRegister(self.account_id, 1) #self.call_mgr.placeCall(self.account_id, self.account_id, "2222" ) def on_incoming_call(self, account, callid, to): print "Incoming call: " + account + ", " + callid + ", " + to self.activeCalls[callid] = {'Account': account, 'To': to, 'State': '' } self.call_mgr.accept(callid) # On call state changed event, set the values for new calls, # or delete the call from the list of active calls def on_call_state_changed(self, callid, state): print "Call state changed: " + callid + ", " + state if state == "HUNGUP": try: del self.activeCalls[callid] except KeyError: print "Call " + callid + " didn't exist. Cannot delete." elif state in [ "RINGING", "CURRENT", "INCOMING", "HOLD" ]: try: self.activeCalls[callid]['State'] = state except KeyError, e: print "This call didn't exist!: " + callid + ". Adding it to the list." callDetails = self.getCallDetails(callid) self.activeCalls[callid] = {'Account': callDetails['ACCOUNTID'], 'To': callDetails['PEER_NUMBER'], 'State': state } elif state in [ "BUSY", "FAILURE" ]: try: del self.activeCalls[callid] except KeyError, e: print "This call didn't exist!: " + callid def getCallDetails(self, callid): """Return informations on this call if exists""" return self.call_mgr.getCallDetails(callid) def place_call(self, callid): self.call_mgr.placeCall(self.account_id, self.account_id, callid) def hangup(self) : call0 = self.activeCalls.keys()[0] self.call_mgr.hangUp(call0) def start_server(obj): server = SimpleXMLRPCServer( ("localhost", 9988), allow_none= True) server.register_instance(obj) print "server start @localhost 9988 forever ..." server.serve_forever() if __name__ == "__main__" : DBusGMainLoop(set_as_default=True) s = SlfPhoneConnector() thread.start_new_thread(start_server(s,)) ... {{ another code here }} #loop = gobject.MainLoop() #loop.run() </code></pre>
1
2009-08-27T05:20:50Z
1,339,203
<p>Try adding after ifmain trick:</p> <pre><code>gobject.threads_init() dbus.glib.init_threads() </code></pre>
0
2009-08-27T06:30:36Z
[ "python", "voip", "xml-rpc", "sip", "dbus" ]
How to make this method non-recursive?
1,339,215
<p>Hey. This example is pretty specific but I think it could apply to a broad range of functions. It's taken from some online programming contest.</p> <p>There is a game with a simple winning condition. Draw is not possible. Game cannot go on forever because every move takes you closer to the terminating condition. The function should, given a state, determine if the player who is to move now has a winning strategy. In the example, the state is an integer. A player chooses a non-zero digit and subtracts it from the number: the new state is the new integer. The winner is the player who reaches zero.</p> <p>I coded this:</p> <pre><code>from Memoize import Memoize @Memoize def Game(x): if x == 0: return True for digit in str(x): if digit != '0' and not Game(x-int(digit)): return True return False </code></pre> <p>I think it's clear how it works. I also realize that for this specific game there's probably a much smarter solution but my question is general. However this makes python go crazy even for relatively small inputs. Is there any way to make this code work with a loop?</p> <p>Thanks</p> <p>This is what I mean by translating into a loop:</p> <pre><code>def fac(x): if x &lt;= 1: return x else: return x*fac(x-1) def fac_loop(x): result = 1 for i in xrange(1,x+1): result *= i return result ## dont try: fac(10000) print fac_loop(10000) % 100 ## works </code></pre>
2
2009-08-27T06:33:42Z
1,339,285
<p>By "go crazy" I assume you mean:</p> <pre><code>&gt;&gt;&gt; Game(10000) # stuff skipped RuntimeError: maximum recursion depth exceeded in cmp </code></pre> <p>You could start at the bottom instead -- a crude change would be:</p> <pre><code># after defining Game() for i in range(10000): Game(i) # Now this will work: print Game(10000) </code></pre> <p>This is because, if you start with a high number, you have to recurse a long way before you reach the bottom (0), so your memoization decorator doesn't help the way it should.</p> <p>By starting from the bottom, you ensure that every recursive call hits the dictionary of results immediately. You probably use extra space, but you don't recurse far.</p> <p>You can turn any recursive function into an iterative function by using a loop and a stack -- essentially running the call stack by hand. See <a href="http://stackoverflow.com/questions/531668/which-recursive-functions-cannot-be-rewritten-using-loops">this question</a> or <a href="http://stackoverflow.com/questions/159590/way-to-go-from-recursion-to-iteration">this quesstion</a>, for example, for some discussion. There may be a more elegant loop-based solution here, but it doesn't leap out to me.</p>
3
2009-08-27T06:53:05Z
[ "python", "recursion", "refactoring" ]
How to make this method non-recursive?
1,339,215
<p>Hey. This example is pretty specific but I think it could apply to a broad range of functions. It's taken from some online programming contest.</p> <p>There is a game with a simple winning condition. Draw is not possible. Game cannot go on forever because every move takes you closer to the terminating condition. The function should, given a state, determine if the player who is to move now has a winning strategy. In the example, the state is an integer. A player chooses a non-zero digit and subtracts it from the number: the new state is the new integer. The winner is the player who reaches zero.</p> <p>I coded this:</p> <pre><code>from Memoize import Memoize @Memoize def Game(x): if x == 0: return True for digit in str(x): if digit != '0' and not Game(x-int(digit)): return True return False </code></pre> <p>I think it's clear how it works. I also realize that for this specific game there's probably a much smarter solution but my question is general. However this makes python go crazy even for relatively small inputs. Is there any way to make this code work with a loop?</p> <p>Thanks</p> <p>This is what I mean by translating into a loop:</p> <pre><code>def fac(x): if x &lt;= 1: return x else: return x*fac(x-1) def fac_loop(x): result = 1 for i in xrange(1,x+1): result *= i return result ## dont try: fac(10000) print fac_loop(10000) % 100 ## works </code></pre>
2
2009-08-27T06:33:42Z
1,339,473
<p>In general, it is only possible to convert recursive functions into loops when they are <a href="http://en.wikipedia.org/wiki/Primitive%5Frecursive%5Ffunction" rel="nofollow">primitive-recursive</a>; this basically means that they call themselves only once in the body. Your function calls itself multiple times. Such a function really needs a stack. It is possible to make the stack explicit, e.g. with lists. One reformulation of your algorithm using an explicit stack is</p> <pre><code>def Game(x): # x, str(x), position stack = [(x,str(x),0)] # return value res = None while stack: if res is not None: # we have a return value if not res: stack.pop() res = True continue # res is True, continue to search res = None x, s, pos = stack.pop() if x == 0: res = True continue if pos == len(s): # end of loop, return False res = False continue stack.append((x,s,pos+1)) digit = s[pos] if digit == '0': continue x -= int(digit) # recurse, starting with position 0 stack.append((x,str(x),0)) return res </code></pre> <p>Basically, you need to make each local variable an element of a stack frame; the local variables here are x, str(x), and the iteration counter of the loop. Doing return values is a bit tricky - I chose to set res to not-None if a function has just returned.</p>
4
2009-08-27T07:45:39Z
[ "python", "recursion", "refactoring" ]
How to make this method non-recursive?
1,339,215
<p>Hey. This example is pretty specific but I think it could apply to a broad range of functions. It's taken from some online programming contest.</p> <p>There is a game with a simple winning condition. Draw is not possible. Game cannot go on forever because every move takes you closer to the terminating condition. The function should, given a state, determine if the player who is to move now has a winning strategy. In the example, the state is an integer. A player chooses a non-zero digit and subtracts it from the number: the new state is the new integer. The winner is the player who reaches zero.</p> <p>I coded this:</p> <pre><code>from Memoize import Memoize @Memoize def Game(x): if x == 0: return True for digit in str(x): if digit != '0' and not Game(x-int(digit)): return True return False </code></pre> <p>I think it's clear how it works. I also realize that for this specific game there's probably a much smarter solution but my question is general. However this makes python go crazy even for relatively small inputs. Is there any way to make this code work with a loop?</p> <p>Thanks</p> <p>This is what I mean by translating into a loop:</p> <pre><code>def fac(x): if x &lt;= 1: return x else: return x*fac(x-1) def fac_loop(x): result = 1 for i in xrange(1,x+1): result *= i return result ## dont try: fac(10000) print fac_loop(10000) % 100 ## works </code></pre>
2
2009-08-27T06:33:42Z
1,339,530
<p>Well, recursion mostly is about being able to execute some code without losing previous contexts and their order. In particular, function frames put and saved onto call stack during recursion, therefore giving constraint on recursion depth because stack size is limited. You can 'increase' your recursion depth by manually managing/saving required information on each recursive call by creating a state stack on the heap memory. Usually, amount of available heap memory is larger than stack's one. Think: good quick sort implementations eliminate recursion to the larger side by creating an outer loop with ever-changing state variables (lower/upper array boundaries and pivot in QS example). </p> <p>While I was typing this, Martin v. Löwis posted good answer about converting recursive functions into loops.</p>
0
2009-08-27T07:58:09Z
[ "python", "recursion", "refactoring" ]
How to make this method non-recursive?
1,339,215
<p>Hey. This example is pretty specific but I think it could apply to a broad range of functions. It's taken from some online programming contest.</p> <p>There is a game with a simple winning condition. Draw is not possible. Game cannot go on forever because every move takes you closer to the terminating condition. The function should, given a state, determine if the player who is to move now has a winning strategy. In the example, the state is an integer. A player chooses a non-zero digit and subtracts it from the number: the new state is the new integer. The winner is the player who reaches zero.</p> <p>I coded this:</p> <pre><code>from Memoize import Memoize @Memoize def Game(x): if x == 0: return True for digit in str(x): if digit != '0' and not Game(x-int(digit)): return True return False </code></pre> <p>I think it's clear how it works. I also realize that for this specific game there's probably a much smarter solution but my question is general. However this makes python go crazy even for relatively small inputs. Is there any way to make this code work with a loop?</p> <p>Thanks</p> <p>This is what I mean by translating into a loop:</p> <pre><code>def fac(x): if x &lt;= 1: return x else: return x*fac(x-1) def fac_loop(x): result = 1 for i in xrange(1,x+1): result *= i return result ## dont try: fac(10000) print fac_loop(10000) % 100 ## works </code></pre>
2
2009-08-27T06:33:42Z
1,343,492
<p>You could modify your recursive version a bit:</p> <pre><code>def Game(x): if x == 0: return True s = set(digit for digit in str(x) if digit != '0') return any(not Game(x-int(digit)) for digit in s) </code></pre> <p>This way, you don't examine digits multiple times. For example, if you are doing 111, you don't have to look at 110 three times.</p> <p>I'm not sure if this counts as an iterative version of the original algorithm you presented, but here is a memoized iterative version:</p> <pre><code>import Queue def Game2(x): memo = {} memo[0] = True calc_dep = {} must_calc = Queue.Queue() must_calc.put(x) while not must_calc.empty(): n = must_calc.get() if n and n not in calc_dep: s = set(int(c) for c in str(n) if c != '0') elems = [n - digit for digit in s] calc_dep[n] = elems for new_elem in elems: if new_elem not in calc_dep: must_calc.put(new_elem) for k in sorted(calc_dep.keys()): v = calc_dep[k] #print k, v memo[k] = any(not memo[i] for i in v) return memo[x] </code></pre> <p>It first calculates the set of numbers that x, the input, depends on. Then it calculates those numbers, starting at the bottom and going towards x. </p> <p>The code is so fast because of the test for calc_dep. It avoids calculating multiple dependencies. As a result, it can do Game(10000) in under 400 milliseconds whereas the original takes -- I don't know how long. A long time.</p> <p>Here are performance measurements:</p> <pre><code>Elapsed: 1000 0:00:00.029000 Elapsed: 2000 0:00:00.044000 Elapsed: 4000 0:00:00.086000 Elapsed: 8000 0:00:00.197000 Elapsed: 16000 0:00:00.461000 Elapsed: 32000 0:00:00.969000 Elapsed: 64000 0:00:01.774000 Elapsed: 128000 0:00:03.708000 Elapsed: 256000 0:00:07.951000 Elapsed: 512000 0:00:19.148000 Elapsed: 1024000 0:00:34.960000 Elapsed: 2048000 0:01:17.960000 Elapsed: 4096000 0:02:55.013000 </code></pre> <p>It's reasonably zippy.</p>
0
2009-08-27T20:06:27Z
[ "python", "recursion", "refactoring" ]
Python: Memory leak debugging
1,339,293
<p>I have a small multithreaded script running in django and over time its starts using more and more memory. Leaving it for a full day eats about 6GB of RAM and I start to swap.</p> <p>Following <a href="http://www.lshift.net/blog/2008/11/14/tracing-python-memory-leaks">http://www.lshift.net/blog/2008/11/14/tracing-python-memory-leaks</a> I see this as the most common types (with only 800M of memory used):</p> <pre><code>(Pdb) objgraph.show_most_common_types(limit=20) dict 43065 tuple 28274 function 7335 list 6157 NavigableString 3479 instance 2454 cell 1256 weakref 974 wrapper_descriptor 836 builtin_function_or_method 766 type 742 getset_descriptor 562 module 423 method_descriptor 373 classobj 256 instancemethod 255 member_descriptor 218 property 185 Comment 183 __proxy__ 155 </code></pre> <p>which doesn't show anything weird. What should I do now to help debug the memory problems?</p> <p><em>Update:</em> Trying some things people are recommending. I ran the program overnight, and when I work up, 50% * 8G == 4G of RAM used. </p> <pre><code>(Pdb) from pympler import muppy (Pdb) muppy.print_summary() types | # objects | total size ========================================== | =========== | ============ unicode | 210997 | 97.64 MB list | 1547 | 88.29 MB dict | 41630 | 13.21 MB set | 50 | 8.02 MB str | 109360 | 7.11 MB tuple | 27898 | 2.29 MB code | 6907 | 1.16 MB type | 760 | 653.12 KB weakref | 1014 | 87.14 KB int | 3552 | 83.25 KB function (__wrapper__) | 702 | 82.27 KB wrapper_descriptor | 998 | 77.97 KB cell | 1357 | 74.21 KB &lt;class 'pympler.asizeof.asizeof._Claskey | 1113 | 69.56 KB function (__init__) | 574 | 67.27 KB </code></pre> <p>That doesn't sum to 4G, nor really give me any big data structured to go fix. The unicode is from a set() of "done" nodes, and the list's look like just random <code>weakref</code>s. </p> <p>I didn't use guppy since it required a C extension and I didn't have root so it was going to be a pain to build.</p> <p>None of the objectI was using have a <code>__del__</code> method, and looking through the libraries, it doesn't look like django nor the python-mysqldb do either. Any other ideas?</p>
24
2009-08-27T06:55:41Z
1,339,333
<p>Try <a href="http://guppy-pe.sourceforge.net/" rel="nofollow">Guppy</a>.</p> <p>Basicly, you need more information or be able to extract some. Guppy even provides graphical representation of data.</p>
0
2009-08-27T07:04:24Z
[ "python", "django", "debugging", "memory-leaks" ]
Python: Memory leak debugging
1,339,293
<p>I have a small multithreaded script running in django and over time its starts using more and more memory. Leaving it for a full day eats about 6GB of RAM and I start to swap.</p> <p>Following <a href="http://www.lshift.net/blog/2008/11/14/tracing-python-memory-leaks">http://www.lshift.net/blog/2008/11/14/tracing-python-memory-leaks</a> I see this as the most common types (with only 800M of memory used):</p> <pre><code>(Pdb) objgraph.show_most_common_types(limit=20) dict 43065 tuple 28274 function 7335 list 6157 NavigableString 3479 instance 2454 cell 1256 weakref 974 wrapper_descriptor 836 builtin_function_or_method 766 type 742 getset_descriptor 562 module 423 method_descriptor 373 classobj 256 instancemethod 255 member_descriptor 218 property 185 Comment 183 __proxy__ 155 </code></pre> <p>which doesn't show anything weird. What should I do now to help debug the memory problems?</p> <p><em>Update:</em> Trying some things people are recommending. I ran the program overnight, and when I work up, 50% * 8G == 4G of RAM used. </p> <pre><code>(Pdb) from pympler import muppy (Pdb) muppy.print_summary() types | # objects | total size ========================================== | =========== | ============ unicode | 210997 | 97.64 MB list | 1547 | 88.29 MB dict | 41630 | 13.21 MB set | 50 | 8.02 MB str | 109360 | 7.11 MB tuple | 27898 | 2.29 MB code | 6907 | 1.16 MB type | 760 | 653.12 KB weakref | 1014 | 87.14 KB int | 3552 | 83.25 KB function (__wrapper__) | 702 | 82.27 KB wrapper_descriptor | 998 | 77.97 KB cell | 1357 | 74.21 KB &lt;class 'pympler.asizeof.asizeof._Claskey | 1113 | 69.56 KB function (__init__) | 574 | 67.27 KB </code></pre> <p>That doesn't sum to 4G, nor really give me any big data structured to go fix. The unicode is from a set() of "done" nodes, and the list's look like just random <code>weakref</code>s. </p> <p>I didn't use guppy since it required a C extension and I didn't have root so it was going to be a pain to build.</p> <p>None of the objectI was using have a <code>__del__</code> method, and looking through the libraries, it doesn't look like django nor the python-mysqldb do either. Any other ideas?</p>
24
2009-08-27T06:55:41Z
1,339,344
<p>I think you should use different tools. Apparently, the statistics you got is only about GC objects (i.e. objects which may participate in cycles); most notably, it lacks strings.</p> <p>I recommend to use <a href="http://code.google.com/p/pympler/" rel="nofollow">Pympler</a>; this should provide you with more detailed statistics.</p>
1
2009-08-27T07:07:27Z
[ "python", "django", "debugging", "memory-leaks" ]
Python: Memory leak debugging
1,339,293
<p>I have a small multithreaded script running in django and over time its starts using more and more memory. Leaving it for a full day eats about 6GB of RAM and I start to swap.</p> <p>Following <a href="http://www.lshift.net/blog/2008/11/14/tracing-python-memory-leaks">http://www.lshift.net/blog/2008/11/14/tracing-python-memory-leaks</a> I see this as the most common types (with only 800M of memory used):</p> <pre><code>(Pdb) objgraph.show_most_common_types(limit=20) dict 43065 tuple 28274 function 7335 list 6157 NavigableString 3479 instance 2454 cell 1256 weakref 974 wrapper_descriptor 836 builtin_function_or_method 766 type 742 getset_descriptor 562 module 423 method_descriptor 373 classobj 256 instancemethod 255 member_descriptor 218 property 185 Comment 183 __proxy__ 155 </code></pre> <p>which doesn't show anything weird. What should I do now to help debug the memory problems?</p> <p><em>Update:</em> Trying some things people are recommending. I ran the program overnight, and when I work up, 50% * 8G == 4G of RAM used. </p> <pre><code>(Pdb) from pympler import muppy (Pdb) muppy.print_summary() types | # objects | total size ========================================== | =========== | ============ unicode | 210997 | 97.64 MB list | 1547 | 88.29 MB dict | 41630 | 13.21 MB set | 50 | 8.02 MB str | 109360 | 7.11 MB tuple | 27898 | 2.29 MB code | 6907 | 1.16 MB type | 760 | 653.12 KB weakref | 1014 | 87.14 KB int | 3552 | 83.25 KB function (__wrapper__) | 702 | 82.27 KB wrapper_descriptor | 998 | 77.97 KB cell | 1357 | 74.21 KB &lt;class 'pympler.asizeof.asizeof._Claskey | 1113 | 69.56 KB function (__init__) | 574 | 67.27 KB </code></pre> <p>That doesn't sum to 4G, nor really give me any big data structured to go fix. The unicode is from a set() of "done" nodes, and the list's look like just random <code>weakref</code>s. </p> <p>I didn't use guppy since it required a C extension and I didn't have root so it was going to be a pain to build.</p> <p>None of the objectI was using have a <code>__del__</code> method, and looking through the libraries, it doesn't look like django nor the python-mysqldb do either. Any other ideas?</p>
24
2009-08-27T06:55:41Z
1,339,400
<p>Have you tried <a href="http://docs.python.org/library/gc.html#gc.set%5Fdebug">gc.set_debug()</a> ?</p> <p>You need to ask yourself simple questions:</p> <ul> <li>Am I using objects with <code>__del__</code> methods? Do I absolutely, unequivocally, need them?</li> <li>Can I get reference cycles in my code? Can't we break these circles before getting rid of the objects?</li> </ul> <p>See, the main issue would be a cycle of objects containing <code>__del__</code> methods:</p> <pre><code>import gc class A(object): def __del__(self): print 'a deleted' if hasattr(self, 'b'): delattr(self, 'b') class B(object): def __init__(self, a): self.a = a def __del__(self): print 'b deleted' del self.a def createcycle(): a = A() b = B(a) a.b = b return a, b gc.set_debug(gc.DEBUG_LEAK) a, b = createcycle() # remove references del a, b # prints: ## gc: uncollectable &lt;A 0x...&gt; ## gc: uncollectable &lt;B 0x...&gt; ## gc: uncollectable &lt;dict 0x...&gt; ## gc: uncollectable &lt;dict 0x...&gt; gc.collect() # to solve this we break explicitely the cycles: a, b = createcycle() del a.b del a, b # objects are removed correctly: ## a deleted ## b deleted gc.collect() </code></pre> <p>I would really encourage you to flag objects / concepts that are cycling in your application and focus on their lifetime: when you don't need them anymore, do we have anything referencing it?</p> <p>Even for cycles without <code>__del__</code> methods, we can have an issue:</p> <pre><code>import gc # class without destructor class A(object): pass def createcycle(): # a -&gt; b -&gt; c # ^ | # ^&lt;--&lt;--&lt;--| a = A() b = A() a.next = b c = A() b.next = c c.next = a return a, b, b gc.set_debug(gc.DEBUG_LEAK) a, b, c = createcycle() # since we have no __del__ methods, gc is able to collect the cycle: del a, b, c # no panic message, everything is collectable: ##gc: collectable &lt;A 0x...&gt; ##gc: collectable &lt;A 0x...&gt; ##gc: collectable &lt;dict 0x...&gt; ##gc: collectable &lt;A 0x...&gt; ##gc: collectable &lt;dict 0x...&gt; ##gc: collectable &lt;dict 0x...&gt; gc.collect() a, b, c = createcycle() # but as long as we keep an exterior ref to the cycle...: seen = dict() seen[a] = True # delete the cycle del a, b, c # nothing is collected gc.collect() </code></pre> <p>If you have to use "seen"-like dictionaries, or history, be careful that you keep only the actual data you need, and no external references to it.</p> <p>I'm a bit disappointed now by <code>set_debug</code>, I wish it could be configured to output data somewhere else than to stderr, but hopefully <a href="http://bugs.python.org/issue5851">that should change soon</a>.</p>
5
2009-08-27T07:26:36Z
[ "python", "django", "debugging", "memory-leaks" ]
Python: Memory leak debugging
1,339,293
<p>I have a small multithreaded script running in django and over time its starts using more and more memory. Leaving it for a full day eats about 6GB of RAM and I start to swap.</p> <p>Following <a href="http://www.lshift.net/blog/2008/11/14/tracing-python-memory-leaks">http://www.lshift.net/blog/2008/11/14/tracing-python-memory-leaks</a> I see this as the most common types (with only 800M of memory used):</p> <pre><code>(Pdb) objgraph.show_most_common_types(limit=20) dict 43065 tuple 28274 function 7335 list 6157 NavigableString 3479 instance 2454 cell 1256 weakref 974 wrapper_descriptor 836 builtin_function_or_method 766 type 742 getset_descriptor 562 module 423 method_descriptor 373 classobj 256 instancemethod 255 member_descriptor 218 property 185 Comment 183 __proxy__ 155 </code></pre> <p>which doesn't show anything weird. What should I do now to help debug the memory problems?</p> <p><em>Update:</em> Trying some things people are recommending. I ran the program overnight, and when I work up, 50% * 8G == 4G of RAM used. </p> <pre><code>(Pdb) from pympler import muppy (Pdb) muppy.print_summary() types | # objects | total size ========================================== | =========== | ============ unicode | 210997 | 97.64 MB list | 1547 | 88.29 MB dict | 41630 | 13.21 MB set | 50 | 8.02 MB str | 109360 | 7.11 MB tuple | 27898 | 2.29 MB code | 6907 | 1.16 MB type | 760 | 653.12 KB weakref | 1014 | 87.14 KB int | 3552 | 83.25 KB function (__wrapper__) | 702 | 82.27 KB wrapper_descriptor | 998 | 77.97 KB cell | 1357 | 74.21 KB &lt;class 'pympler.asizeof.asizeof._Claskey | 1113 | 69.56 KB function (__init__) | 574 | 67.27 KB </code></pre> <p>That doesn't sum to 4G, nor really give me any big data structured to go fix. The unicode is from a set() of "done" nodes, and the list's look like just random <code>weakref</code>s. </p> <p>I didn't use guppy since it required a C extension and I didn't have root so it was going to be a pain to build.</p> <p>None of the objectI was using have a <code>__del__</code> method, and looking through the libraries, it doesn't look like django nor the python-mysqldb do either. Any other ideas?</p>
24
2009-08-27T06:55:41Z
1,339,419
<p>Do you use any extension? They are a wonderful place for memory leaks, and will not be tracked by python tools.</p>
1
2009-08-27T07:34:49Z
[ "python", "django", "debugging", "memory-leaks" ]
Python: Memory leak debugging
1,339,293
<p>I have a small multithreaded script running in django and over time its starts using more and more memory. Leaving it for a full day eats about 6GB of RAM and I start to swap.</p> <p>Following <a href="http://www.lshift.net/blog/2008/11/14/tracing-python-memory-leaks">http://www.lshift.net/blog/2008/11/14/tracing-python-memory-leaks</a> I see this as the most common types (with only 800M of memory used):</p> <pre><code>(Pdb) objgraph.show_most_common_types(limit=20) dict 43065 tuple 28274 function 7335 list 6157 NavigableString 3479 instance 2454 cell 1256 weakref 974 wrapper_descriptor 836 builtin_function_or_method 766 type 742 getset_descriptor 562 module 423 method_descriptor 373 classobj 256 instancemethod 255 member_descriptor 218 property 185 Comment 183 __proxy__ 155 </code></pre> <p>which doesn't show anything weird. What should I do now to help debug the memory problems?</p> <p><em>Update:</em> Trying some things people are recommending. I ran the program overnight, and when I work up, 50% * 8G == 4G of RAM used. </p> <pre><code>(Pdb) from pympler import muppy (Pdb) muppy.print_summary() types | # objects | total size ========================================== | =========== | ============ unicode | 210997 | 97.64 MB list | 1547 | 88.29 MB dict | 41630 | 13.21 MB set | 50 | 8.02 MB str | 109360 | 7.11 MB tuple | 27898 | 2.29 MB code | 6907 | 1.16 MB type | 760 | 653.12 KB weakref | 1014 | 87.14 KB int | 3552 | 83.25 KB function (__wrapper__) | 702 | 82.27 KB wrapper_descriptor | 998 | 77.97 KB cell | 1357 | 74.21 KB &lt;class 'pympler.asizeof.asizeof._Claskey | 1113 | 69.56 KB function (__init__) | 574 | 67.27 KB </code></pre> <p>That doesn't sum to 4G, nor really give me any big data structured to go fix. The unicode is from a set() of "done" nodes, and the list's look like just random <code>weakref</code>s. </p> <p>I didn't use guppy since it required a C extension and I didn't have root so it was going to be a pain to build.</p> <p>None of the objectI was using have a <code>__del__</code> method, and looking through the libraries, it doesn't look like django nor the python-mysqldb do either. Any other ideas?</p>
24
2009-08-27T06:55:41Z
1,343,115
<p>Is DEBUG=False in settings.py?</p> <p>If not Django will happily store all the SQL queries you make which adds up.</p>
18
2009-08-27T18:52:29Z
[ "python", "django", "debugging", "memory-leaks" ]
Python: Memory leak debugging
1,339,293
<p>I have a small multithreaded script running in django and over time its starts using more and more memory. Leaving it for a full day eats about 6GB of RAM and I start to swap.</p> <p>Following <a href="http://www.lshift.net/blog/2008/11/14/tracing-python-memory-leaks">http://www.lshift.net/blog/2008/11/14/tracing-python-memory-leaks</a> I see this as the most common types (with only 800M of memory used):</p> <pre><code>(Pdb) objgraph.show_most_common_types(limit=20) dict 43065 tuple 28274 function 7335 list 6157 NavigableString 3479 instance 2454 cell 1256 weakref 974 wrapper_descriptor 836 builtin_function_or_method 766 type 742 getset_descriptor 562 module 423 method_descriptor 373 classobj 256 instancemethod 255 member_descriptor 218 property 185 Comment 183 __proxy__ 155 </code></pre> <p>which doesn't show anything weird. What should I do now to help debug the memory problems?</p> <p><em>Update:</em> Trying some things people are recommending. I ran the program overnight, and when I work up, 50% * 8G == 4G of RAM used. </p> <pre><code>(Pdb) from pympler import muppy (Pdb) muppy.print_summary() types | # objects | total size ========================================== | =========== | ============ unicode | 210997 | 97.64 MB list | 1547 | 88.29 MB dict | 41630 | 13.21 MB set | 50 | 8.02 MB str | 109360 | 7.11 MB tuple | 27898 | 2.29 MB code | 6907 | 1.16 MB type | 760 | 653.12 KB weakref | 1014 | 87.14 KB int | 3552 | 83.25 KB function (__wrapper__) | 702 | 82.27 KB wrapper_descriptor | 998 | 77.97 KB cell | 1357 | 74.21 KB &lt;class 'pympler.asizeof.asizeof._Claskey | 1113 | 69.56 KB function (__init__) | 574 | 67.27 KB </code></pre> <p>That doesn't sum to 4G, nor really give me any big data structured to go fix. The unicode is from a set() of "done" nodes, and the list's look like just random <code>weakref</code>s. </p> <p>I didn't use guppy since it required a C extension and I didn't have root so it was going to be a pain to build.</p> <p>None of the objectI was using have a <code>__del__</code> method, and looking through the libraries, it doesn't look like django nor the python-mysqldb do either. Any other ideas?</p>
24
2009-08-27T06:55:41Z
1,346,194
<p>See <a href="http://nedbatchelder.com/blog/200809/a%5Fserver%5Fmemory%5Fleak.html">this excellent blog post from Ned Batchelder</a> on how they traced down real memory leak in HP's Tabblo. A classic and worth reading.</p>
5
2009-08-28T10:35:55Z
[ "python", "django", "debugging", "memory-leaks" ]
Python: Memory leak debugging
1,339,293
<p>I have a small multithreaded script running in django and over time its starts using more and more memory. Leaving it for a full day eats about 6GB of RAM and I start to swap.</p> <p>Following <a href="http://www.lshift.net/blog/2008/11/14/tracing-python-memory-leaks">http://www.lshift.net/blog/2008/11/14/tracing-python-memory-leaks</a> I see this as the most common types (with only 800M of memory used):</p> <pre><code>(Pdb) objgraph.show_most_common_types(limit=20) dict 43065 tuple 28274 function 7335 list 6157 NavigableString 3479 instance 2454 cell 1256 weakref 974 wrapper_descriptor 836 builtin_function_or_method 766 type 742 getset_descriptor 562 module 423 method_descriptor 373 classobj 256 instancemethod 255 member_descriptor 218 property 185 Comment 183 __proxy__ 155 </code></pre> <p>which doesn't show anything weird. What should I do now to help debug the memory problems?</p> <p><em>Update:</em> Trying some things people are recommending. I ran the program overnight, and when I work up, 50% * 8G == 4G of RAM used. </p> <pre><code>(Pdb) from pympler import muppy (Pdb) muppy.print_summary() types | # objects | total size ========================================== | =========== | ============ unicode | 210997 | 97.64 MB list | 1547 | 88.29 MB dict | 41630 | 13.21 MB set | 50 | 8.02 MB str | 109360 | 7.11 MB tuple | 27898 | 2.29 MB code | 6907 | 1.16 MB type | 760 | 653.12 KB weakref | 1014 | 87.14 KB int | 3552 | 83.25 KB function (__wrapper__) | 702 | 82.27 KB wrapper_descriptor | 998 | 77.97 KB cell | 1357 | 74.21 KB &lt;class 'pympler.asizeof.asizeof._Claskey | 1113 | 69.56 KB function (__init__) | 574 | 67.27 KB </code></pre> <p>That doesn't sum to 4G, nor really give me any big data structured to go fix. The unicode is from a set() of "done" nodes, and the list's look like just random <code>weakref</code>s. </p> <p>I didn't use guppy since it required a C extension and I didn't have root so it was going to be a pain to build.</p> <p>None of the objectI was using have a <code>__del__</code> method, and looking through the libraries, it doesn't look like django nor the python-mysqldb do either. Any other ideas?</p>
24
2009-08-27T06:55:41Z
4,957,480
<p>See <a href="http://opensourcehacker.com/2008/03/07/debugging-django-memory-leak-with-trackrefs-and-guppy/">http://opensourcehacker.com/2008/03/07/debugging-django-memory-leak-with-trackrefs-and-guppy/</a> . Short answer: if you're running django but not in a web-request-based format, you need to manually run <code>db.reset_queries()</code> (and of course have DEBUG=False, as others have mentioned). Django automatically does <code>reset_queries()</code> after a web request, but in your format, that never happens.</p>
29
2011-02-10T13:10:05Z
[ "python", "django", "debugging", "memory-leaks" ]
How to fetch rows from below table using google app engine GQL query (python)?
1,339,346
<pre><code>List_name Email ========== ================== andrew adam@gmail.com adam adam@gmail.com smith adam@gmail.com john adam@gmail.com andrew andrew@gmail.com adam andrew@gmail.com smith andrew@gmail.com john andrew@gmail.com andrew john@gmail.com adam john@gmail.com smith john@gmail.com john john@gmail.com andrew smith@gmail.com adam smith@gmail.com smith smith@gmail.com john smith@gmail.com </code></pre> <p>In the above table email_ids are repeated, I want to display all emails in the above table with out repetition.</p> <p>Here there is only 4 emails, I want to retrieve only 4 rows from table is this possible using GQL query in goolge app engine.</p> <p>And one more thing i want to use paging to display emails (10 emails for a page), </p> <p>i.e., if there is 15 emails in table, need to display 10 emails in 1ST page and 5 emails in 2nd page. </p> <p>Paging is very important! </p>
1
2009-08-27T07:07:44Z
1,339,588
<p>If you're accustomed to working with a relational database, Google App Engine can seem unusual. The query syntax is <em>very</em> limited. Instead of putting everything into a simple table and writing complicated queries, you have to put everything into complicated data structures and then write simple queries.</p> <p>You should get used to creating several different Entities, usually one for each primary key for a possible query. In this case, you should have an Entity UniqueEmailAddress or something like that. Every time you add a record, get the UniqueEmailAddress with that name and update it, or create it if it doesn't exist. Then you can just query on UniqueEmailAddress directly.</p>
4
2009-08-27T08:14:41Z
[ "python", "google-app-engine" ]
How to fetch rows from below table using google app engine GQL query (python)?
1,339,346
<pre><code>List_name Email ========== ================== andrew adam@gmail.com adam adam@gmail.com smith adam@gmail.com john adam@gmail.com andrew andrew@gmail.com adam andrew@gmail.com smith andrew@gmail.com john andrew@gmail.com andrew john@gmail.com adam john@gmail.com smith john@gmail.com john john@gmail.com andrew smith@gmail.com adam smith@gmail.com smith smith@gmail.com john smith@gmail.com </code></pre> <p>In the above table email_ids are repeated, I want to display all emails in the above table with out repetition.</p> <p>Here there is only 4 emails, I want to retrieve only 4 rows from table is this possible using GQL query in goolge app engine.</p> <p>And one more thing i want to use paging to display emails (10 emails for a page), </p> <p>i.e., if there is 15 emails in table, need to display 10 emails in 1ST page and 5 emails in 2nd page. </p> <p>Paging is very important! </p>
1
2009-08-27T07:07:44Z
1,339,610
<p>You can use the <a href="http://docs.python.org/tutorial/datastructures.html" rel="nofollow">set</a> function in python you will be able to remove all the duplication. I don't think there is a way of doing it GQL.</p> <pre><code>&gt;&gt;&gt; basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] &gt;&gt;&gt; fruit = set(basket) # create a set without duplicates &gt;&gt;&gt; fruit set(['orange', 'pear', 'apple', 'banana']) </code></pre>
1
2009-08-27T08:18:26Z
[ "python", "google-app-engine" ]
How to add bi-directional manytomanyfields in django admin?
1,339,409
<p>In my models.py i have something like:</p> <pre><code>class LocationGroup(models.Model): name = models.CharField(max_length=200) class Report(models.Model): name = models.CharField(max_length=200) locationgroups = models.ManyToManyField(LocationGroup) </code></pre> <p>admin.py (standard):</p> <pre><code>admin.site.register(LocationGroup) admin.site.register(Report) </code></pre> <p>When I enter the admin page for Report, it shows a nice multiple choice field. How can I add the same multiple choice field in LocationGroup? I can access all Reports by calling LocationGroup.report_set.all()</p>
11
2009-08-27T07:31:08Z
1,340,600
<p>I think yon can combine this sample code (<a href="http://code.djangoproject.com/ticket/897" rel="nofollow">source</a>) wich breaks sync_db</p> <pre><code>class ItemType(meta.Model): name = meta.CharField(maxlength=100) description = meta.CharField(maxlength=250) properties = meta.ManyToManyField('PropertyType', db_table='app_propertytype_itemtypes') class PropertyType(meta.Model): name = meta.CharField(maxlength=100) itemtypes = meta.ManyToManyField(ItemType) </code></pre> <p>with <a href="http://www.djangosnippets.org/snippets/1295/" rel="nofollow">this snippet</a></p> <pre><code>class ManyToManyField_NoSyncdb(models.ManyToManyField): def __init__(self, *args, **kwargs): super(ManyToManyField_NoSyncdb, self).__init__(*args, **kwargs) self.creates_table = False </code></pre> <p>to obtain something like</p> <pre><code>class ItemType(meta.Model): name = meta.CharField(maxlength=100) description = meta.CharField(maxlength=250) properties = meta.ManyToManyField_NoSyncdb('PropertyType', db_table='app_propertytype_itemtypes') class PropertyType(meta.Model): name = meta.CharField(maxlength=100) itemtypes = meta.ManyToManyField(ItemType) </code></pre> <p><strong>Disclaimer</strong> : this is just a rough idea</p> <p>Edit: There is probably someting to do with <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#proxy-models" rel="nofollow">Django's 1.1 Proxy Models</a></p>
2
2009-08-27T11:55:09Z
[ "python", "django", "django-models" ]
How to add bi-directional manytomanyfields in django admin?
1,339,409
<p>In my models.py i have something like:</p> <pre><code>class LocationGroup(models.Model): name = models.CharField(max_length=200) class Report(models.Model): name = models.CharField(max_length=200) locationgroups = models.ManyToManyField(LocationGroup) </code></pre> <p>admin.py (standard):</p> <pre><code>admin.site.register(LocationGroup) admin.site.register(Report) </code></pre> <p>When I enter the admin page for Report, it shows a nice multiple choice field. How can I add the same multiple choice field in LocationGroup? I can access all Reports by calling LocationGroup.report_set.all()</p>
11
2009-08-27T07:31:08Z
1,370,357
<p>I think what are you are looking for is <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#inlinemodeladmin-objects" rel="nofollow">admin inlines</a>. In your admin.py you will want to add something like this:</p> <pre><code>class LocationGroupInline(admin.TabularInline): model = LocationGroup class ReportAdmin(admin.ModelAdmin): inlines = [ LocationGroupInline, ] admin.site.register(Report, ReportAdmin) admin.site.register(LocationGroup) </code></pre> <p>There are many options to include in LocationGroupInline if you want to further configure the inline display of the related model. Two of these options are <strong>form</strong> and <strong>formset</strong>, which will let you use custom Django Form and FormSet classes to further customize the look and feel of the inline model admin. Using this you can create a simple Form that displays just the multiple choice field you want (except for a M2M field it will not be possible to display as a single drop down, but a multiple select box). For example:</p> <pre><code>class MyLocationGroupForm(forms.Form): location = forms.MultipleModelChoiceField( queryset=LocationGroup.objects.all()) class LocationGroupInline(admin.TabularInline): model = LocationGroup form = MyLocationGroupForm </code></pre>
1
2009-09-02T21:56:07Z
[ "python", "django", "django-models" ]
How to add bi-directional manytomanyfields in django admin?
1,339,409
<p>In my models.py i have something like:</p> <pre><code>class LocationGroup(models.Model): name = models.CharField(max_length=200) class Report(models.Model): name = models.CharField(max_length=200) locationgroups = models.ManyToManyField(LocationGroup) </code></pre> <p>admin.py (standard):</p> <pre><code>admin.site.register(LocationGroup) admin.site.register(Report) </code></pre> <p>When I enter the admin page for Report, it shows a nice multiple choice field. How can I add the same multiple choice field in LocationGroup? I can access all Reports by calling LocationGroup.report_set.all()</p>
11
2009-08-27T07:31:08Z
1,452,189
<p>The workaround I found was to follow the instructions for <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#working-with-many-to-many-intermediary-models">ManyToManyFields with intermediary models</a>. Even though you're not using the 'through' model feature, just pretend as if you were and create a stub model with the necessary ForeignKey.</p> <pre><code># models: make sure the naming convention matches what ManyToManyField would create class Report_LocationGroups(models.Model): locationgroup = models.ForeignKey(LocationGroup) report = models.ForeignKey(Report) # admin class ReportInline(admin.TabularInline): model = models.Report_LocationGroups class LocationGroupAdmin(admin.ModelAdmin): inlines = ReportInline, </code></pre>
8
2009-09-20T22:29:06Z
[ "python", "django", "django-models" ]
Regexp to literally interpret \t as \t and not tab
1,340,162
<p>I'm trying to match a sequence of text with backslashed in it, like a windows path.</p> <p>Now, when I match with regexp in python, it gets the match, but the module interprets all backslashes followed by a valid escape char (i.e. <code>t</code>) as an escape sequence, which is not what I want.</p> <p>How do I get it not to do that?</p> <p>Thanks /m</p> <p>EDIT: well, i missed that the regexp that matches the text that contains the backslash is a (.*). I've tried the raw notation (examplefied in the awnsers), but it does not help in my situation. Or im doing it wrong. EDIT2: Did it wrong. Thanks guys/girls!</p>
1
2009-08-27T10:25:09Z
1,340,168
<p>Use double backslashes with r like this</p> <pre><code>&gt;&gt;&gt; re.match(r"\\t", r"\t") &lt;_sre.SRE_Match object at 0xb7ce5d78&gt; </code></pre> <p>From python <a href="http://docs.python.org/library/re.html#raw-string-notation">docs</a>:</p> <blockquote> <p>When one wants to match a literal backslash, it must be escaped in the regular expression. With raw string notation, this means r"\". Without raw string notation, one must use "\\", making the following lines of code functionally identical:</p> </blockquote> <pre><code>&gt;&gt;&gt; re.match(r"\\", r"\\") &lt;_sre.SRE_Match object at ...&gt; &gt;&gt;&gt; re.match("\\\\", r"\\") &lt;_sre.SRE_Match object at ...&gt; </code></pre>
9
2009-08-27T10:25:57Z
[ "python", "regex" ]
Regexp to literally interpret \t as \t and not tab
1,340,162
<p>I'm trying to match a sequence of text with backslashed in it, like a windows path.</p> <p>Now, when I match with regexp in python, it gets the match, but the module interprets all backslashes followed by a valid escape char (i.e. <code>t</code>) as an escape sequence, which is not what I want.</p> <p>How do I get it not to do that?</p> <p>Thanks /m</p> <p>EDIT: well, i missed that the regexp that matches the text that contains the backslash is a (.*). I've tried the raw notation (examplefied in the awnsers), but it does not help in my situation. Or im doing it wrong. EDIT2: Did it wrong. Thanks guys/girls!</p>
1
2009-08-27T10:25:09Z
1,340,172
<p>Always use the <code>r</code> prefix when defining your regex. This will tell Python to treat the string as raw, so it doesn't do any of the standard processing.</p> <pre><code> regex = r'\t' </code></pre>
-1
2009-08-27T10:26:54Z
[ "python", "regex" ]
back-to-back histograms in matplotlib
1,340,338
<p>There is a nice function that draws <a href="http://www.mathworks.co.uk/matlabcentral/fileexchange/23312" rel="nofollow">back to back histograms</a> in Matlab. I need to create a similar graph in matplotlib. Can anyone show a working code example?</p>
3
2009-08-27T11:02:25Z
1,340,368
<p>This <a href="http://www.mail-archive.com/matplotlib-users@lists.sourceforge.net/msg04828.html" rel="nofollow">matplotlib users mailing post</a> has some sample code for a <em>bihistogram</em> that goes up and down instead of left and right. <a href="http://www.itl.nist.gov/div898/handbook/eda/section3/bihistog.htm" rel="nofollow">Here's the example output</a> he linked to.</p> <p>If up-down absolutely won't work for you, it should only take a few minutes to swap the operations on the y-axis with the x-axis operations.</p> <p>Also, your link isn't a MATLAB function, it's an actual script that someone wrote in about 40 lines. You could actually look at the script source and try porting it, since MATLAB and matplotlib have fairly close syntax.</p>
2
2009-08-27T11:07:49Z
[ "python", "matplotlib", "histogram" ]
back-to-back histograms in matplotlib
1,340,338
<p>There is a nice function that draws <a href="http://www.mathworks.co.uk/matlabcentral/fileexchange/23312" rel="nofollow">back to back histograms</a> in Matlab. I need to create a similar graph in matplotlib. Can anyone show a working code example?</p>
3
2009-08-27T11:02:25Z
1,340,499
<p>Thanks to the link pointed by Mark Rushakoff, following is what I finally did</p> <pre><code>import numpy as np from matplotlib import pylab as pl dataOne = get_data_one() dataTwo = get_data_two() hN = pl.hist(dataTwo, orientation='horizontal', normed=0, rwidth=0.8, label='ONE') hS = pl.hist(dataOne, bins=hN[1], orientation='horizontal', normed=0, rwidth=0.8, label='TWO') for p in hS[2]: p.set_width( - p.get_width()) xmin = min([ min(w.get_width() for w in hS[2]), min([w.get_width() for w in hN[2]]) ]) xmin = np.floor(xmin) xmax = max([ max(w.get_width() for w in hS[2]), max([w.get_width() for w in hN[2]]) ]) xmax = np.ceil(xmax) range = xmax - xmin delta = 0.0 * range pl.xlim([xmin - delta, xmax + delta]) xt = pl.xticks() n = xt[0] s = ['%.1f'%abs(i) for i in n] pl.xticks(n, s) pl.legend(loc='best') pl.axvline(0.0) pl.show() </code></pre>
4
2009-08-27T11:32:36Z
[ "python", "matplotlib", "histogram" ]
Locally Hosted Google App Engine (WebApp Framework / BigTable)
1,340,887
<p>I have been playing with Google App engine a lot lately, from home on personal projects, and I have been really enjoying it. I've converted a few of my coworkers over and we are interested in using GAE for a few of our projects at work.</p> <p>Our work has to be hosted locally on our own servers. I've done some searching around and I really can't find any information on using the WebApp framework and BigTable locally.</p> <p>Any information you could provide on setting up a GAE-ish environment on a local Windows server would be much appreciated. I know GAE is much more than just the framework and BigTable - the scalability, propogation of your application/data across many servers are all features we <strong>don't</strong> need. We just want to get the webapp framework and BigTable up and running through mod_wsgi on Apache.</p>
1
2009-08-27T12:51:28Z
1,342,175
<p>Webapp is a fine choice for a simple web framework but there are plenty of other simple python web frameworks that have instructions for setting them up in your use case (cherrypy, web.py, etc). Since google developed webapp for gae I don't believe they published instructions for setting it up behind apache.</p> <p>BigTable is proprietary to Google so you will not be able to run it locally. If you are looking for something with similar performance characteristics I'd look into the schemaless 'document-oriented' databases.</p>
4
2009-08-27T16:19:59Z
[ "python", "google-app-engine", "mod-wsgi" ]
Should Python unittests be in a separate module?
1,340,892
<p>Is there a consensus about the best place to put Python unittests?</p> <p>Should the unittests be included within the same module as the functionality being tested (executed when the module is run on its own (<code>if __name__ == '__main__'</code>, etc.)), or is it better to include the unittests within different modules?</p> <p>Perhaps a combination of both approaches is best, including module level tests within each module and adding higher level tests which test functionality included in more than one module as separate modules (perhaps in a /test subdirectory?).</p> <p>I assume that test discovery is more straightforward if the tests are included in separate modules, but there's an additional burden on the developer if he/she has to remember to update the additional test module if the module under test is modified.</p> <p>I'd be interested to know peoples' thoughts on the best way of organizing unittests. </p>
14
2009-08-27T12:52:34Z
1,340,934
<p>Personally, I create a tests/ folder in my source directory and try to, more or less, mirror my main source code hierarchy with unit test equivalents (having 1 module = 1 unit test module as a rule of thumb).</p> <p>Note that I'm using <a href="http://code.google.com/p/python-nose/">nose</a> and its philosophy is a bit different than unittest's.</p>
9
2009-08-27T13:00:42Z
[ "python", "unit-testing", "testing" ]
Should Python unittests be in a separate module?
1,340,892
<p>Is there a consensus about the best place to put Python unittests?</p> <p>Should the unittests be included within the same module as the functionality being tested (executed when the module is run on its own (<code>if __name__ == '__main__'</code>, etc.)), or is it better to include the unittests within different modules?</p> <p>Perhaps a combination of both approaches is best, including module level tests within each module and adding higher level tests which test functionality included in more than one module as separate modules (perhaps in a /test subdirectory?).</p> <p>I assume that test discovery is more straightforward if the tests are included in separate modules, but there's an additional burden on the developer if he/she has to remember to update the additional test module if the module under test is modified.</p> <p>I'd be interested to know peoples' thoughts on the best way of organizing unittests. </p>
14
2009-08-27T12:52:34Z
1,340,964
<p>I generally keep test code in a separate module, and ship the module/package and tests in a single distribution. If the user installs using <code>setup.py</code> they can run the tests from the test directory to ensure that everything works in their environment, but only the module's code ends up under <code>Lib/site-packages</code>.</p>
4
2009-08-27T13:04:00Z
[ "python", "unit-testing", "testing" ]
Should Python unittests be in a separate module?
1,340,892
<p>Is there a consensus about the best place to put Python unittests?</p> <p>Should the unittests be included within the same module as the functionality being tested (executed when the module is run on its own (<code>if __name__ == '__main__'</code>, etc.)), or is it better to include the unittests within different modules?</p> <p>Perhaps a combination of both approaches is best, including module level tests within each module and adding higher level tests which test functionality included in more than one module as separate modules (perhaps in a /test subdirectory?).</p> <p>I assume that test discovery is more straightforward if the tests are included in separate modules, but there's an additional burden on the developer if he/she has to remember to update the additional test module if the module under test is modified.</p> <p>I'd be interested to know peoples' thoughts on the best way of organizing unittests. </p>
14
2009-08-27T12:52:34Z
1,341,011
<p><code>if __name__ == '__main__'</code>, etc. is great for small tests.</p>
0
2009-08-27T13:12:23Z
[ "python", "unit-testing", "testing" ]
Should Python unittests be in a separate module?
1,340,892
<p>Is there a consensus about the best place to put Python unittests?</p> <p>Should the unittests be included within the same module as the functionality being tested (executed when the module is run on its own (<code>if __name__ == '__main__'</code>, etc.)), or is it better to include the unittests within different modules?</p> <p>Perhaps a combination of both approaches is best, including module level tests within each module and adding higher level tests which test functionality included in more than one module as separate modules (perhaps in a /test subdirectory?).</p> <p>I assume that test discovery is more straightforward if the tests are included in separate modules, but there's an additional burden on the developer if he/she has to remember to update the additional test module if the module under test is modified.</p> <p>I'd be interested to know peoples' thoughts on the best way of organizing unittests. </p>
14
2009-08-27T12:52:34Z
1,341,048
<p>There might be reasons other than testing to use the <code>if __name__ == '__main__'</code> check. Keeping the tests in other modules leaves that option open to you. Also - if you refactor the implementation of a module and your tests are in another module that was not edited - you KNOW the tests have not been changed when you run them against the refactored code.</p>
2
2009-08-27T13:17:25Z
[ "python", "unit-testing", "testing" ]
Should Python unittests be in a separate module?
1,340,892
<p>Is there a consensus about the best place to put Python unittests?</p> <p>Should the unittests be included within the same module as the functionality being tested (executed when the module is run on its own (<code>if __name__ == '__main__'</code>, etc.)), or is it better to include the unittests within different modules?</p> <p>Perhaps a combination of both approaches is best, including module level tests within each module and adding higher level tests which test functionality included in more than one module as separate modules (perhaps in a /test subdirectory?).</p> <p>I assume that test discovery is more straightforward if the tests are included in separate modules, but there's an additional burden on the developer if he/she has to remember to update the additional test module if the module under test is modified.</p> <p>I'd be interested to know peoples' thoughts on the best way of organizing unittests. </p>
14
2009-08-27T12:52:34Z
1,341,053
<ol> <li>Where you have to if using a library specifying where unittests should live,</li> <li>in the modules themselves for small projects, or</li> <li>in a <code>tests/</code> subdirectory in your package for larger projects.</li> </ol> <p>It's a matter of what works best for the project you're creating.</p> <p>Sometimes the libraries you're using determine where tests should go, as is the case with Django (where you put your tests in <code>models.py</code>, <code>tests.py</code> or a <code>tests/</code> subdirectory in your apps).</p> <p>If there are no existing constraints, it's a matter of personal preference. For a small set of modules, it may be more convenient to put the unittests in the files you're creating.</p> <p>For anything more than a few modules I create the tests separately in a <code>tests/</code> directory in the package. Having testing code mixed with the implementation adds unnecessary noise for anyone reading the code.</p>
8
2009-08-27T13:18:00Z
[ "python", "unit-testing", "testing" ]
Should Python unittests be in a separate module?
1,340,892
<p>Is there a consensus about the best place to put Python unittests?</p> <p>Should the unittests be included within the same module as the functionality being tested (executed when the module is run on its own (<code>if __name__ == '__main__'</code>, etc.)), or is it better to include the unittests within different modules?</p> <p>Perhaps a combination of both approaches is best, including module level tests within each module and adding higher level tests which test functionality included in more than one module as separate modules (perhaps in a /test subdirectory?).</p> <p>I assume that test discovery is more straightforward if the tests are included in separate modules, but there's an additional burden on the developer if he/she has to remember to update the additional test module if the module under test is modified.</p> <p>I'd be interested to know peoples' thoughts on the best way of organizing unittests. </p>
14
2009-08-27T12:52:34Z
1,341,060
<p>I usually have them in a separate folder called most often <em>test/</em>. Personally I am not using the if __name__ == '__main__' check, because I use nosetests and it handles the test detection by itself.</p>
1
2009-08-27T13:20:32Z
[ "python", "unit-testing", "testing" ]
Should Python unittests be in a separate module?
1,340,892
<p>Is there a consensus about the best place to put Python unittests?</p> <p>Should the unittests be included within the same module as the functionality being tested (executed when the module is run on its own (<code>if __name__ == '__main__'</code>, etc.)), or is it better to include the unittests within different modules?</p> <p>Perhaps a combination of both approaches is best, including module level tests within each module and adding higher level tests which test functionality included in more than one module as separate modules (perhaps in a /test subdirectory?).</p> <p>I assume that test discovery is more straightforward if the tests are included in separate modules, but there's an additional burden on the developer if he/she has to remember to update the additional test module if the module under test is modified.</p> <p>I'd be interested to know peoples' thoughts on the best way of organizing unittests. </p>
14
2009-08-27T12:52:34Z
1,341,119
<h1>YES, do use a separate module.</h1> <p>It does not really make sense to use the <code>__main__</code> trick. Just assume that you have <strong>several files</strong> in your module, and it does not work anymore, because <strong>you don't want to run each source file</strong> separately when testing your module.</p> <p>Also, when installing a module, most of the time <strong>you don't want to install the tests</strong>. Your end-user does not care about tests, only the developers should care.</p> <p>No, really. Put your tests in <code>tests/</code>, your doc in <code>doc</code>, and have a Makefile ready around for a <code>make test</code>. Any other approaches are just intermediate solutions, only valid for specific tiny modules.</p>
9
2009-08-27T13:31:11Z
[ "python", "unit-testing", "testing" ]
Why saving of MSWord document can silently fail?
1,340,950
<p>I need to change some custom properties values in many files. Here is an example of code - how I do it for a single file:</p> <pre><code>import win32com.client MSWord = win32com.client.Dispatch("Word.Application") MSWord.Visible = False doc = MSWord.Documents.Open(file) doc.CustomDocumentProperties('Some Property').Value = 'Some New Value' doc.Save() doc.Close() MSWord.Quit() </code></pre> <p>Running the same code for <code>"Excel.Application"</code> (with minor changes - just to make it work) gives me excellent result. However when I'm using <code>doc.Save()</code> or <code>doc.SaveAs(same_file)</code> for MSWord it silently fails. I don't know why, but changes are not saved. </p> <p>Now my workaround is to use <code>SaveAs</code> to a different file, it also works good. But I want to understand why I have such strange behaviour for MSWord files and how it can be fixed?</p> <p><strong>Edit</strong>: I changed my code, not to misdirect people with silent fail cause of try/except. However, thanks to all of them for finding that defect in my code :)</p>
3
2009-08-27T13:02:27Z
1,341,027
<blockquote> <p>(a) Check to see if you have file write access</p> <p>(b) Make sure you code catches using the COMException</p> <p>(C) are you gracefully terminating excel/words when creating multiple documents </p> </blockquote> <p><strong>Darknight</strong></p>
0
2009-08-27T13:14:56Z
[ "python", "automation", "ms-word", "ole" ]