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
Proper way to handle multiple forms on one page in Django
1,395,807
<p>I have a template page expecting two forms. If I just use one form, things are fine as in this typical example:</p> <pre><code>if request.method == 'POST': form = AuthorForm(request.POST,) if form.is_valid(): form.save() # do something. else: form = AuthorForm() </code></pre> <p>If I w...
123
2009-09-08T19:17:09Z
1,395,866
<p>You have a few options:</p> <ol> <li><p>Put different URLs in the action for the two forms. Then you'll have two different view functions to deal with the two different forms.</p></li> <li><p>Read the submit button values from the POST data. You can tell which submit button was clicked: <a href="http://stackoverf...
81
2009-09-08T19:29:10Z
[ "python", "django", "forms" ]
Proper way to handle multiple forms on one page in Django
1,395,807
<p>I have a template page expecting two forms. If I just use one form, things are fine as in this typical example:</p> <pre><code>if request.method == 'POST': form = AuthorForm(request.POST,) if form.is_valid(): form.save() # do something. else: form = AuthorForm() </code></pre> <p>If I w...
123
2009-09-08T19:17:09Z
1,395,970
<p>A method for future reference is something like this. bannedphraseform is the first form and expectedphraseform is the second. If the first one is hit, the second one is skipped (which is a reasonable assumption in this case):</p> <pre><code>if request.method == 'POST': bannedphraseform = BannedPhraseForm(req...
30
2009-09-08T19:50:05Z
[ "python", "django", "forms" ]
Proper way to handle multiple forms on one page in Django
1,395,807
<p>I have a template page expecting two forms. If I just use one form, things are fine as in this typical example:</p> <pre><code>if request.method == 'POST': form = AuthorForm(request.POST,) if form.is_valid(): form.save() # do something. else: form = AuthorForm() </code></pre> <p>If I w...
123
2009-09-08T19:17:09Z
17,303,425
<p>Django's class based views provide a generic FormView but for all intents and purposes it is designed to only handle one form. </p> <p>One way to handle multiple forms with same target action url using Django's generic views is to extend the 'TemplateView' as shown below; I use this approach often enough that I hav...
9
2013-06-25T17:09:50Z
[ "python", "django", "forms" ]
Proper way to handle multiple forms on one page in Django
1,395,807
<p>I have a template page expecting two forms. If I just use one form, things are fine as in this typical example:</p> <pre><code>if request.method == 'POST': form = AuthorForm(request.POST,) if form.is_valid(): form.save() # do something. else: form = AuthorForm() </code></pre> <p>If I w...
123
2009-09-08T19:17:09Z
26,551,263
<p>This is a bit late, but this is the best solution I found. You make a look-up dictionary for the form name and its class, you also have to add an attribute to identify the form, and in your views you have to add it as a hidden field, with the <code>form.formlabel</code>.</p> <pre><code># form holder form_holder = {...
1
2014-10-24T15:32:55Z
[ "python", "django", "forms" ]
Proper way to handle multiple forms on one page in Django
1,395,807
<p>I have a template page expecting two forms. If I just use one form, things are fine as in this typical example:</p> <pre><code>if request.method == 'POST': form = AuthorForm(request.POST,) if form.is_valid(): form.save() # do something. else: form = AuthorForm() </code></pre> <p>If I w...
123
2009-09-08T19:17:09Z
27,836,159
<p>Here is simple way to handle the above.</p> <p>In Html Template we put Post</p> <pre><code>&lt;form action="/useradd/addnewroute/" method="post" id="login-form"&gt;{% csrf_token %} &lt;!-- add details of form here--&gt; &lt;form&gt; &lt;form action="/useradd/addarea/" method="post" id="login-form"&gt;{% csrf_toke...
1
2015-01-08T08:54:06Z
[ "python", "django", "forms" ]
Proper way to handle multiple forms on one page in Django
1,395,807
<p>I have a template page expecting two forms. If I just use one form, things are fine as in this typical example:</p> <pre><code>if request.method == 'POST': form = AuthorForm(request.POST,) if form.is_valid(): form.save() # do something. else: form = AuthorForm() </code></pre> <p>If I w...
123
2009-09-08T19:17:09Z
33,028,994
<p>I needed multiple forms that are independently validated on the same page. The key concepts I was missing were 1) using the form prefix for the submit button name and 2) an unbounded form does not trigger validation. If it helps anyone else, here is my simplified example of two forms AForm and BForm using TemplateVi...
2
2015-10-09T02:36:25Z
[ "python", "django", "forms" ]
How to drop into REPL (Read, Eval, Print, Loop) from Python code
1,395,913
<p>Is there a way to programmatically force a Python script to drop into a REPL at an arbitrary point in its execution, even if the script was launched from the command line?</p> <p>I'm writing a quick and dirty plotting program, which I want to read data from stdin or a file, plot it, and then drop into the REPL to a...
66
2009-09-08T19:40:33Z
1,395,925
<p>You can launch the debugger:</p> <pre><code>import pdb;pdb.set_trace() </code></pre> <p>Not sure what you want the REPL for, but the debugger is very similar.</p>
14
2009-09-08T19:42:26Z
[ "python", "interactive" ]
How to drop into REPL (Read, Eval, Print, Loop) from Python code
1,395,913
<p>Is there a way to programmatically force a Python script to drop into a REPL at an arbitrary point in its execution, even if the script was launched from the command line?</p> <p>I'm writing a quick and dirty plotting program, which I want to read data from stdin or a file, plot it, and then drop into the REPL to a...
66
2009-09-08T19:40:33Z
1,396,190
<p>Here's how you should do it (IPython > v0.11):</p> <pre><code>import IPython IPython.embed() </code></pre> <p>For IPython &lt;= v0.11:</p> <pre><code>from IPython.Shell import IPShellEmbed ipshell = IPShellEmbed() ipshell() # this call anywhere in your program will start IPython </code></pre> <p>You should use...
27
2009-09-08T20:31:58Z
[ "python", "interactive" ]
How to drop into REPL (Read, Eval, Print, Loop) from Python code
1,395,913
<p>Is there a way to programmatically force a Python script to drop into a REPL at an arbitrary point in its execution, even if the script was launched from the command line?</p> <p>I'm writing a quick and dirty plotting program, which I want to read data from stdin or a file, plot it, and then drop into the REPL to a...
66
2009-09-08T19:40:33Z
1,396,199
<p>You could try using the interactive option for python:</p> <pre><code>python -i program.py </code></pre> <p>This will execute the code in program.py, then go to the REPL. Anything you define or import in the top level of program.py will be available.</p>
50
2009-09-08T20:34:12Z
[ "python", "interactive" ]
How to drop into REPL (Read, Eval, Print, Loop) from Python code
1,395,913
<p>Is there a way to programmatically force a Python script to drop into a REPL at an arbitrary point in its execution, even if the script was launched from the command line?</p> <p>I'm writing a quick and dirty plotting program, which I want to read data from stdin or a file, plot it, and then drop into the REPL to a...
66
2009-09-08T19:40:33Z
1,396,386
<p>I frequently use this:</p> <pre><code>def interact(): import code code.InteractiveConsole(locals=globals()).interact() </code></pre>
87
2009-09-08T21:18:44Z
[ "python", "interactive" ]
How to drop into REPL (Read, Eval, Print, Loop) from Python code
1,395,913
<p>Is there a way to programmatically force a Python script to drop into a REPL at an arbitrary point in its execution, even if the script was launched from the command line?</p> <p>I'm writing a quick and dirty plotting program, which I want to read data from stdin or a file, plot it, and then drop into the REPL to a...
66
2009-09-08T19:40:33Z
1,396,504
<p>To get use of iPython and functionality of debugger you should use <a href="http://pypi.python.org/pypi/ipdb/">ipdb</a>, </p> <p>You can use it in the same way as pdb, with the addition of :</p> <pre><code>import ipdb ipdb.set_trace() </code></pre>
13
2009-09-08T21:48:45Z
[ "python", "interactive" ]
How to drop into REPL (Read, Eval, Print, Loop) from Python code
1,395,913
<p>Is there a way to programmatically force a Python script to drop into a REPL at an arbitrary point in its execution, even if the script was launched from the command line?</p> <p>I'm writing a quick and dirty plotting program, which I want to read data from stdin or a file, plot it, and then drop into the REPL to a...
66
2009-09-08T19:40:33Z
22,339,942
<p>I just did this in one of my own scripts (it runs inside an automation framework that is a huge PITA to instrument):</p> <pre><code>x = 0 # exit loop counter while x == 0: user_input = raw_input("Please enter a command, or press q to quit: ") if user_input[0] == "q": x = 1 else: try: ...
0
2014-03-12T01:01:18Z
[ "python", "interactive" ]
Unexpected results feeding Django File upload object to Python CSV module
1,396,126
<p>I have no problems getting the file to upload and if I save it to disk, all formatting is intact.</p> <p>I wrote a function to read in the the file within Django using:</p> <pre><code>data = csv.reader(f.read()) </code></pre> <p>where f is the Django file object that I get from 'form.cleaned_data['file']' and yes...
0
2009-09-08T20:19:40Z
1,396,259
<p>What happens if you try reading in the whole file, logging its first few bytes, and then passing it into the parser? Perhaps the file isn't being uploaded as you expect? An http form-encoding issue, perhaps?</p>
0
2009-09-08T20:48:38Z
[ "python", "django", "csv", "iterator" ]
Unexpected results feeding Django File upload object to Python CSV module
1,396,126
<p>I have no problems getting the file to upload and if I save it to disk, all formatting is intact.</p> <p>I wrote a function to read in the the file within Django using:</p> <pre><code>data = csv.reader(f.read()) </code></pre> <p>where f is the Django file object that I get from 'form.cleaned_data['file']' and yes...
0
2009-09-08T20:19:40Z
1,396,735
<p>You're actually passing the wrong iterable to <code>csv.reader()</code>. Try changing that line to:</p> <pre><code>data = csv.reader(f) </code></pre> <p>What you're doing is passing the whole contents of the file to the <code>csv.reader()</code> function, which will cause it to iterate over every individual chara...
1
2009-09-08T22:44:59Z
[ "python", "django", "csv", "iterator" ]
Efficient Python Data Storage (Abstract Data Types?)
1,396,241
<p>Pardon the ambiguity in the title- I wasn't quite sure how to phrase my question.</p> <p>Given a string: </p> <pre><code>blah = "There are three cats in the hat" </code></pre> <p>and the (I'm not quite sure which data structure to use for this) "userInfo":</p> <pre><code>cats -&gt; ("tim", "1 infinite loop") thr...
-1
2009-09-08T20:42:32Z
1,396,268
<p>I'm not sure what exactly you're trying to do, but maybe you're looking for something like this:</p> <pre><code>userinfo = { "tim": "1 infinite loop", "sally": "123 fake st", "john": "123 fake st", "albert": "345 real road", "janet": None } conditions = { "cats": ["tim"], "three": ["sally", "tim"], ...
0
2009-09-08T20:50:47Z
[ "python", "data-structures" ]
Efficient Python Data Storage (Abstract Data Types?)
1,396,241
<p>Pardon the ambiguity in the title- I wasn't quite sure how to phrase my question.</p> <p>Given a string: </p> <pre><code>blah = "There are three cats in the hat" </code></pre> <p>and the (I'm not quite sure which data structure to use for this) "userInfo":</p> <pre><code>cats -&gt; ("tim", "1 infinite loop") thr...
-1
2009-09-08T20:42:32Z
1,396,276
<p>I haven't got the slightest clue of what you actually are trying to do, but if you have a lot of data, and you need to store it, and you need to search in it, some sort of database with indexing capabilities seems to be the way to go.</p> <p>ZODB, CouchBD or SQL is a matter of taste. I seriously doubt you need to c...
1
2009-09-08T20:52:18Z
[ "python", "data-structures" ]
Efficient Python Data Storage (Abstract Data Types?)
1,396,241
<p>Pardon the ambiguity in the title- I wasn't quite sure how to phrase my question.</p> <p>Given a string: </p> <pre><code>blah = "There are three cats in the hat" </code></pre> <p>and the (I'm not quite sure which data structure to use for this) "userInfo":</p> <pre><code>cats -&gt; ("tim", "1 infinite loop") thr...
-1
2009-09-08T20:42:32Z
1,396,305
<p>Something like this?</p> <pre><code>class Content( object ): def __init__( self, content, maps_to ): self.content= content.split() self.maps_to = maps_to def matches( self, words ): return all( c in words for c in self.content ) def __str__( self ): return "%s -&gt; %r" %...
6
2009-09-08T20:58:44Z
[ "python", "data-structures" ]
How to using widget PlainTextEdit or TextEdit for output and input text?
1,396,339
<p>How to using widget PlainTextEdit or TextEdit for output and input text? I'm interested PyQt4.</p>
-1
2009-09-08T21:08:19Z
1,396,360
<p><a href="http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qplaintextedit.html" rel="nofollow">PlainTextEdit</a></p> <p><a href="http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qtextedit.html" rel="nofollow">TextEdit</a></p>
3
2009-09-08T21:13:14Z
[ "python", "user-interface", "qt" ]
How to using widget PlainTextEdit or TextEdit for output and input text?
1,396,339
<p>How to using widget PlainTextEdit or TextEdit for output and input text? I'm interested PyQt4.</p>
-1
2009-09-08T21:08:19Z
1,401,466
<p>You need to be more specific, but anyways, the following code will create a dialog with a TextEdit that will show the input file: <code> from PyQt4 import QtCore, QtGui</p> <pre><code>def read_file(file): """ Returns all contents of file """ result = "" with open(file) as f: for line in ...
0
2009-09-09T19:04:07Z
[ "python", "user-interface", "qt" ]
ctypes pointer question
1,396,533
<p>I was reading the ctypes tutorial, and I came across this:</p> <pre><code>s = "Hello, World" c_s = c_char_p(s) print c_s c_s.value = "Hi, there" </code></pre> <p>But I had been using pointers like this:</p> <pre><code>s = "Hello, World!" c_s = c_char_p() c_s = s print c_s c_s.value Traceback (most recent call la...
1
2009-09-08T21:55:07Z
1,396,730
<p>In your second example, you've got the statements:</p> <pre><code>c_s = c_char_p() c_s = s </code></pre> <p>The <code>ctypes</code> module can't break the <a href="http://docs.python.org/reference/executionmodel.html" rel="nofollow">rules of Python assignments</a>, and in the above case the second assignment <em>r...
3
2009-09-08T22:44:10Z
[ "python", "object", "pointers", "declaration", "ctypes" ]
Customizing how Python's `copy` module treats my objects
1,396,547
<p>From the <a href="http://docs.python.org/library/copy.html" rel="nofollow"><code>copy</code> documentation</a>:</p> <blockquote> <p>Classes can use the same interfaces to control copying that they use to control pickling.</p> <p>[...]</p> <p>In order for a class to define its own copy implementation, it...
3
2009-09-08T21:58:48Z
1,396,683
<p><code>__setstate__()</code> and <code>__getstate__()</code>.</p> <p>Notice that the copy documentation says that they <em>can</em> use the same interface, but they don't necessarily have do so. </p> <p>See <a href="http://books.google.com/books?id=vpTAq4dnmuAC&amp;pg=PA283&amp;lpg=PA283&amp;dq=pickle+setstate&amp;...
1
2009-09-08T22:32:50Z
[ "python", "copy", "pickle" ]
Customizing how Python's `copy` module treats my objects
1,396,547
<p>From the <a href="http://docs.python.org/library/copy.html" rel="nofollow"><code>copy</code> documentation</a>:</p> <blockquote> <p>Classes can use the same interfaces to control copying that they use to control pickling.</p> <p>[...]</p> <p>In order for a class to define its own copy implementation, it...
3
2009-09-08T21:58:48Z
1,397,416
<p>It works as follows: if a class defines <code>__copy__</code>, that takes precedence for <code>copy.copy</code> purposes (and similarly <code>__deepcopy__</code> takes precedence for <code>copy.deepcopy</code> purposes). If these very specific special methods are not defined, then the same mechanisms as for pickling...
7
2009-09-09T03:33:51Z
[ "python", "copy", "pickle" ]
Why is subtraction faster than addition in Python?
1,396,564
<p>I was optimising some Python code, and tried the following experiment:</p> <pre><code>import time start = time.clock() x = 0 for i in range(10000000): x += 1 end = time.clock() print '+=',end-start start = time.clock() x = 0 for i in range(10000000): x -= -1 end = time.clock() print '-=',end-start </cod...
32
2009-09-08T22:01:59Z
1,396,597
<pre><code>$ python -m timeit -s "x=0" "x+=1" 10000000 loops, best of 3: 0.151 usec per loop $ python -m timeit -s "x=0" "x-=-1" 10000000 loops, best of 3: 0.154 usec per loop </code></pre> <p>Looks like you've some <a href="http://www-plan.cs.colorado.edu/diwan/asplos09.pdf">measurement bias</a></p>
13
2009-09-08T22:09:23Z
[ "python", "performance", "addition", "subtraction" ]
Why is subtraction faster than addition in Python?
1,396,564
<p>I was optimising some Python code, and tried the following experiment:</p> <pre><code>import time start = time.clock() x = 0 for i in range(10000000): x += 1 end = time.clock() print '+=',end-start start = time.clock() x = 0 for i in range(10000000): x -= -1 end = time.clock() print '-=',end-start </cod...
32
2009-09-08T22:01:59Z
1,396,614
<p>The running loop backwards is faster because the computer has an easier time comparing if a number is equal to 0.</p>
-1
2009-09-08T22:12:52Z
[ "python", "performance", "addition", "subtraction" ]
Why is subtraction faster than addition in Python?
1,396,564
<p>I was optimising some Python code, and tried the following experiment:</p> <pre><code>import time start = time.clock() x = 0 for i in range(10000000): x += 1 end = time.clock() print '+=',end-start start = time.clock() x = 0 for i in range(10000000): x -= -1 end = time.clock() print '-=',end-start </cod...
32
2009-09-08T22:01:59Z
1,396,671
<p>I think the "general programming lesson" is that it is <em>really</em> hard to predict, solely by looking at the source code, which sequence of statements will be the fastest. Programmers at all levels frequently get caught up by this sort of "intuitive" optimisation. What you think you know may not necessarily be t...
7
2009-09-08T22:27:52Z
[ "python", "performance", "addition", "subtraction" ]
Why is subtraction faster than addition in Python?
1,396,564
<p>I was optimising some Python code, and tried the following experiment:</p> <pre><code>import time start = time.clock() x = 0 for i in range(10000000): x += 1 end = time.clock() print '+=',end-start start = time.clock() x = 0 for i in range(10000000): x -= -1 end = time.clock() print '-=',end-start </cod...
32
2009-09-08T22:01:59Z
1,396,704
<p>With Python 2.5 the biggest problem here is using range, which will allocate a list that big to iterate over it. When using xrange, whichever is done second is a tiny bit faster for me. (Not sure if range has become a generator in Python 3.)</p>
0
2009-09-08T22:39:06Z
[ "python", "performance", "addition", "subtraction" ]
Why is subtraction faster than addition in Python?
1,396,564
<p>I was optimising some Python code, and tried the following experiment:</p> <pre><code>import time start = time.clock() x = 0 for i in range(10000000): x += 1 end = time.clock() print '+=',end-start start = time.clock() x = 0 for i in range(10000000): x -= -1 end = time.clock() print '-=',end-start </cod...
32
2009-09-08T22:01:59Z
1,396,740
<p>It's always a good idea when asking a question to say what platform and what version of Python you are using. Sometimes it does't matter. This is NOT one of those times:</p> <ol> <li><p><code>time.clock()</code> is appropriate only on Windows. Throw away your own measuring code and use <code>-m timeit</code> as dem...
4
2009-09-08T22:46:51Z
[ "python", "performance", "addition", "subtraction" ]
Why is subtraction faster than addition in Python?
1,396,564
<p>I was optimising some Python code, and tried the following experiment:</p> <pre><code>import time start = time.clock() x = 0 for i in range(10000000): x += 1 end = time.clock() print '+=',end-start start = time.clock() x = 0 for i in range(10000000): x -= -1 end = time.clock() print '-=',end-start </cod...
32
2009-09-08T22:01:59Z
1,396,744
<p>I can reproduce this on my Q6600 (Python 2.6.2); increasing the range to 100000000:</p> <pre><code>('+=', 11.370000000000001) ('-=', 10.769999999999998) </code></pre> <p>First, some observations:</p> <ul> <li>This is 5% for a trivial operation. That's significant.</li> <li>The speed of the native addition and su...
71
2009-09-08T22:47:51Z
[ "python", "performance", "addition", "subtraction" ]
Why is subtraction faster than addition in Python?
1,396,564
<p>I was optimising some Python code, and tried the following experiment:</p> <pre><code>import time start = time.clock() x = 0 for i in range(10000000): x += 1 end = time.clock() print '+=',end-start start = time.clock() x = 0 for i in range(10000000): x -= -1 end = time.clock() print '-=',end-start </cod...
32
2009-09-08T22:01:59Z
1,397,046
<p>Your experiment is faulty. The way this experiment should be designed is to write 2 different programs - 1 for addition, 1 for subtraction. They should be exactly the same and run under the same conditions with the data being put to file. Then you need to average the runs (at least several thousand), but you'd ne...
0
2009-09-09T00:37:51Z
[ "python", "performance", "addition", "subtraction" ]
Why is subtraction faster than addition in Python?
1,396,564
<p>I was optimising some Python code, and tried the following experiment:</p> <pre><code>import time start = time.clock() x = 0 for i in range(10000000): x += 1 end = time.clock() print '+=',end-start start = time.clock() x = 0 for i in range(10000000): x -= -1 end = time.clock() print '-=',end-start </cod...
32
2009-09-08T22:01:59Z
1,397,081
<blockquote> <p>"The second loop is reliably faster ..."</p> </blockquote> <p>That's your explanation right there. Re-order your script so the subtraction test is timed first, <em>then</em> the addition, and suddenly addition becomes the faster operation again:</p> <pre><code>-= 3.05 += 2.84 </code></pre> <p>Obvio...
5
2009-09-09T00:55:59Z
[ "python", "performance", "addition", "subtraction" ]
Why is subtraction faster than addition in Python?
1,396,564
<p>I was optimising some Python code, and tried the following experiment:</p> <pre><code>import time start = time.clock() x = 0 for i in range(10000000): x += 1 end = time.clock() print '+=',end-start start = time.clock() x = 0 for i in range(10000000): x -= -1 end = time.clock() print '-=',end-start </cod...
32
2009-09-08T22:01:59Z
1,399,677
<p>That would be remarkable, so I have thoroughly evaluated your code and also setup the expiriment as I would find it more <em>correct</em> (all declarations and function calls outside the loop). Both versions I have run five times.</p> <ul> <li>Running your code validated your claims: -= takes constantly less time; ...
0
2009-09-09T13:26:04Z
[ "python", "performance", "addition", "subtraction" ]
Why is subtraction faster than addition in Python?
1,396,564
<p>I was optimising some Python code, and tried the following experiment:</p> <pre><code>import time start = time.clock() x = 0 for i in range(10000000): x += 1 end = time.clock() print '+=',end-start start = time.clock() x = 0 for i in range(10000000): x -= -1 end = time.clock() print '-=',end-start </cod...
32
2009-09-08T22:01:59Z
4,078,287
<blockquote>Is there a more general programming lesson here?</blockquote> <p>The more general programming lesson here is that intuition is a poor guide when predicting run-time performance of computer code.</p> <p>One can reason about algorithmic complexity, hypothesise about compiler optimisations, estimate cache pe...
2
2010-11-02T13:46:31Z
[ "python", "performance", "addition", "subtraction" ]
python and mechanize.open()
1,396,646
<p>I have some code that is using mechanize and a password protected site. I can login just fine and get the results I expect. However, once I log in I don't want to "click" links I want to iterate through a list of URLs. Unfortunately each .open() call simply gets a re-direct to the login page, which is the behaviour ...
2
2009-09-08T22:20:09Z
1,396,706
<p>This isn't an answer, but it might lead you in the right direction. Try turning on Mechanize's extensive debugging facilities, using some combination of the statements below:</p> <pre><code>browser.set_debug_redirects(True) browser.set_debug_responses(True) browser.set_debug_http(True) </code></pre> <p>This will ...
1
2009-09-08T22:40:27Z
[ "python", "mechanize" ]
python and mechanize.open()
1,396,646
<p>I have some code that is using mechanize and a password protected site. I can login just fine and get the results I expect. However, once I log in I don't want to "click" links I want to iterate through a list of URLs. Unfortunately each .open() call simply gets a re-direct to the login page, which is the behaviour ...
2
2009-09-08T22:20:09Z
1,396,801
<p>Instead of using for each link:</p> <pre><code>browser.open('www.google.com') </code></pre> <p>Try using the following after doing the initial login:</p> <pre><code>browser.follow_link(text = 'a href text') </code></pre> <p>My guess is that calling open is what is resetting your cookies.</p>
2
2009-09-08T23:06:00Z
[ "python", "mechanize" ]
python and mechanize.open()
1,396,646
<p>I have some code that is using mechanize and a password protected site. I can login just fine and get the results I expect. However, once I log in I don't want to "click" links I want to iterate through a list of URLs. Unfortunately each .open() call simply gets a re-direct to the login page, which is the behaviour ...
2
2009-09-08T22:20:09Z
1,396,826
<p>Will,</p> <p>Your suggestion pointed me in exactly the right direction.</p> <p>Every web browser I have ever used responded to something like the following correct:</p> <pre><code>http://www.foo.com//bar/baz/trool.html </code></pre> <p>Since I hate getting things concatenated incorrectly my SITE variable was "ht...
2
2009-09-08T23:13:39Z
[ "python", "mechanize" ]
Python: Get object by id
1,396,668
<p>Let's say I have an id of a Python object, which I retrieved by doing <code>id(thing)</code>. How do I find <code>thing</code> again by the id number I was given?</p>
63
2009-09-08T22:26:56Z
1,396,690
<p>You can use the <a href="http://docs.python.org/library/gc.html">gc</a> module to get all the objects currently tracked by the Python garbage collector.</p> <pre><code>import gc def objects_by_id(id_): for obj in gc.get_objects(): if id(obj) == id_: return obj raise Exception("No found"...
29
2009-09-08T22:34:56Z
[ "python" ]
Python: Get object by id
1,396,668
<p>Let's say I have an id of a Python object, which I retrieved by doing <code>id(thing)</code>. How do I find <code>thing</code> again by the id number I was given?</p>
63
2009-09-08T22:26:56Z
1,396,696
<p>Short answer, you can't.</p> <p>Long answer, you can maintain a dict for mapping IDs to objects, or look the ID up by exhaustive search of <code>gc.get_objects()</code>, but this will create one of two problems: either the dict's reference will keep the object alive and prevent GC, or (if it's a WeakValue dict or y...
34
2009-09-08T22:37:30Z
[ "python" ]
Python: Get object by id
1,396,668
<p>Let's say I have an id of a Python object, which I retrieved by doing <code>id(thing)</code>. How do I find <code>thing</code> again by the id number I was given?</p>
63
2009-09-08T22:26:56Z
1,396,731
<p>eGenix mxTools library does provide such a function, although marked as "expert-only": <a href="http://www.egenix.com/products/python/mxBase/mxTools/doc/#%5FToc199521822" rel="nofollow"><code>mx.Tools.makeref(id)</code></a> </p>
2
2009-09-08T22:44:18Z
[ "python" ]
Python: Get object by id
1,396,668
<p>Let's say I have an id of a Python object, which I retrieved by doing <code>id(thing)</code>. How do I find <code>thing</code> again by the id number I was given?</p>
63
2009-09-08T22:26:56Z
1,396,739
<p>You'll probably want to consider implementing it another way. Are you aware of the weakref module?</p> <p>(Edited) The Python <a href="http://docs.python.org/library/weakref.html">weakref module</a> lets you keep references, dictionary references, and proxies to objects without having those references count in the ...
20
2009-09-08T22:46:31Z
[ "python" ]
Python: Get object by id
1,396,668
<p>Let's say I have an id of a Python object, which I retrieved by doing <code>id(thing)</code>. How do I find <code>thing</code> again by the id number I was given?</p>
63
2009-09-08T22:26:56Z
1,397,628
<p>Just mentioning this module for completeness. <a href="http://www.friday.com/bbum/2007/08/24/python-di/" rel="nofollow">This code by Bill Bumgarner</a> includes a C extension to do what you want without looping throughout every object in existence.</p> <p>The code for the function is quite straightforward. Every Py...
5
2009-09-09T05:01:52Z
[ "python" ]
Python: Get object by id
1,396,668
<p>Let's say I have an id of a Python object, which I retrieved by doing <code>id(thing)</code>. How do I find <code>thing</code> again by the id number I was given?</p>
63
2009-09-08T22:26:56Z
15,702,647
<p>This can be done easily by <code>ctypes</code>:</p> <pre><code>import ctypes a = "hello world" print ctypes.cast(id(a), ctypes.py_object).value </code></pre> <p>output:</p> <pre><code>hello world </code></pre>
72
2013-03-29T11:51:23Z
[ "python" ]
How to install 64-bit Python on Solaris?
1,396,678
<p>I am trying to install Python 2.6 on <a href="http://en.wikipedia.org/wiki/Solaris%5F%28operating%5Fsystem%29" rel="nofollow">Solaris</a> by building the source on Solaris machine. I installed one this way and it appears that it is 32-bit. I downloaded some source tar ball as Linux or Unix for this purpose. Everythi...
0
2009-09-08T22:30:50Z
1,396,693
<p>It's currently an <a href="http://bugs.python.org/issue1306248" rel="nofollow">acknowledged bug</a> that Solaris 64-bit support is suboptimal, but that bug report looks to contain some flags that you might want to use. See also <a href="http://code.activestate.com/lists/python-list/540079/" rel="nofollow">this maili...
2
2009-09-08T22:35:46Z
[ "python", "solaris" ]
How to install 64-bit Python on Solaris?
1,396,678
<p>I am trying to install Python 2.6 on <a href="http://en.wikipedia.org/wiki/Solaris%5F%28operating%5Fsystem%29" rel="nofollow">Solaris</a> by building the source on Solaris machine. I installed one this way and it appears that it is 32-bit. I downloaded some source tar ball as Linux or Unix for this purpose. Everythi...
0
2009-09-08T22:30:50Z
1,592,707
<p>I would strongly suggest seeing if you can get away with the 32 bit version of Python. If your new to compiling stuff on Solaris, this will save you <em>many</em> headaches. However, it is possible, and I do have a working 64 bit version of Python. I'm using <em>cc: Sun C 5.8 2005/10/13</em> to compile. Addition...
3
2009-10-20T05:54:29Z
[ "python", "solaris" ]
apt like column output - python library
1,396,820
<p>Debian's apt tool outputs results in uniform width columns. For instance, try running "aptitude search svn" .. and all names appear in the first column of the same width.</p> <p>Now if you resize the terminal, the column width is adjusted accordingly.</p> <p>Is there a Python library that enables one to do this? N...
2
2009-09-08T23:12:30Z
1,397,122
<p>Well, aptitude uses <a href="http://cwidget.alioth.debian.org/" rel="nofollow"><code>cwidget</code></a> to format the columns in the text-only display. You could call into <code>cwidget</code> writing a python extension for it, but I don't think it is worth the trouble... You can use your preferred method of getting...
2
2009-09-09T01:17:06Z
[ "python", "table", "formatting", "terminal", "apt" ]
apt like column output - python library
1,396,820
<p>Debian's apt tool outputs results in uniform width columns. For instance, try running "aptitude search svn" .. and all names appear in the first column of the same width.</p> <p>Now if you resize the terminal, the column width is adjusted accordingly.</p> <p>Is there a Python library that enables one to do this? N...
2
2009-09-08T23:12:30Z
1,397,365
<p>First, use <code>ioctl</code> to get the size of the TTY:</p> <pre><code>import termios, fcntl, struct, sys def get_tty_size(): s = struct.pack("HHHH", 0, 0, 0, 0) fd_stdout = sys.stdout.fileno() size = fcntl.ioctl(fd_stdout, termios.TIOCGWINSZ, s) return struct.unpack("HHHH", size)[:2] print get_...
2
2009-09-09T03:14:57Z
[ "python", "table", "formatting", "terminal", "apt" ]
apt like column output - python library
1,396,820
<p>Debian's apt tool outputs results in uniform width columns. For instance, try running "aptitude search svn" .. and all names appear in the first column of the same width.</p> <p>Now if you resize the terminal, the column width is adjusted accordingly.</p> <p>Is there a Python library that enables one to do this? N...
2
2009-09-08T23:12:30Z
1,397,382
<p>I don't think there's a general, cross-platform way to "get the width of the terminal" -- <strong>most definitely NOT</strong> "look at the COLUMNS environment variable" (see my comment on the question). On Linux and Mac OS X (and I expect all modern Unix versions),</p> <pre><code>curses.wrapper(lambda _: curses.t...
2
2009-09-09T03:19:43Z
[ "python", "table", "formatting", "terminal", "apt" ]
apt like column output - python library
1,396,820
<p>Debian's apt tool outputs results in uniform width columns. For instance, try running "aptitude search svn" .. and all names appear in the first column of the same width.</p> <p>Now if you resize the terminal, the column width is adjusted accordingly.</p> <p>Is there a Python library that enables one to do this? N...
2
2009-09-08T23:12:30Z
1,446,973
<p><strong>Update</strong>: The <code>colprint</code> routine is now available in the <a href="http://code.activestate.com/pypm/applib/" rel="nofollow">applib</a> Python library <a href="https://github.com/ActiveState/applib/blob/master/applib/textui.py#L213" rel="nofollow">hosted in GitHub</a>. </p> <p>Here's the com...
4
2009-09-18T21:45:44Z
[ "python", "table", "formatting", "terminal", "apt" ]
How Do I Select all Objects via a Relationship Model
1,396,985
<p>Given the Model:</p> <pre><code>class Profile(models.Model): user = models.ForeignKey(User, unique=True) class Thingie(models.Model): children = models.ManyToManyField('self', blank=True, symmetrical=False) class Relation(models.Model): profile = models.ForeignKey(Profile) thingie = models.Foreig...
1
2009-09-09T00:15:11Z
1,397,159
<p>Did you read the Django doc on <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/" rel="nofollow">Making queries</a>? It has a simple example of achieving what you want, more specifically <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships" rel="nofollow">L...
0
2009-09-09T01:33:48Z
[ "python", "django", "django-queryset" ]
How Do I Select all Objects via a Relationship Model
1,396,985
<p>Given the Model:</p> <pre><code>class Profile(models.Model): user = models.ForeignKey(User, unique=True) class Thingie(models.Model): children = models.ManyToManyField('self', blank=True, symmetrical=False) class Relation(models.Model): profile = models.ForeignKey(Profile) thingie = models.Foreig...
1
2009-09-09T00:15:11Z
1,397,299
<p>Without defining a direct relationship between Profile and Thingie, you can't.</p> <p>The best way would be to add a ManyToMany to Thingie that points to Profile and use the <code>through</code> argument (<a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ManyToManyField.through" rel=...
0
2009-09-09T02:41:36Z
[ "python", "django", "django-queryset" ]
How Do I Select all Objects via a Relationship Model
1,396,985
<p>Given the Model:</p> <pre><code>class Profile(models.Model): user = models.ForeignKey(User, unique=True) class Thingie(models.Model): children = models.ManyToManyField('self', blank=True, symmetrical=False) class Relation(models.Model): profile = models.ForeignKey(Profile) thingie = models.Foreig...
1
2009-09-09T00:15:11Z
1,397,323
<p>Do you definitely need it to be a queryset? If you only need it to be an iterable, a simple expression for your purposes is:</p> <pre><code>profiles = [r.profile for r in thingie.relation_set.all()] </code></pre> <p>I'm not sure if a list comprehension counts as irritating iterating, but to me this is a perfectly ...
2
2009-09-09T02:55:40Z
[ "python", "django", "django-queryset" ]
Polymorphism in Django
1,397,537
<p>I have the following models. How do I get access to the <strong>unicode</strong> of the inheriting tables (Team and Athete) from the Entity table? I'm trying to display a list of all the Entities that displays 'name' if Team and 'firstname' and 'lastname' if Athlete.</p> <pre><code>class Entity(models.Model): ent...
1
2009-09-09T04:34:18Z
1,397,598
<p>Loop over all the entities... if entity.<strong>class</strong> == 'Athlete' and entity.firstname and entity.lastname: blah</p> <p>Hope this helps.</p> <p>Edit: hmmm looks like I forgot about actually getting the combined list of both entities. Not sure I know of a slick way to do that.</p>
0
2009-09-09T04:54:44Z
[ "python", "django", "inheritance" ]
Polymorphism in Django
1,397,537
<p>I have the following models. How do I get access to the <strong>unicode</strong> of the inheriting tables (Team and Athete) from the Entity table? I'm trying to display a list of all the Entities that displays 'name' if Team and 'firstname' and 'lastname' if Athlete.</p> <pre><code>class Entity(models.Model): ent...
1
2009-09-09T04:34:18Z
1,397,610
<p>I answered a similar question a while ago. Have a look, I think one of the answers probably solves your problem as well.</p> <p><a href="http://stackoverflow.com/questions/929029/how-do-i-access-the-child-classes-of-an-object-in-django-without-knowing-the-name">http://stackoverflow.com/questions/929029/how-do-i-acc...
0
2009-09-09T04:57:51Z
[ "python", "django", "inheritance" ]
Polymorphism in Django
1,397,537
<p>I have the following models. How do I get access to the <strong>unicode</strong> of the inheriting tables (Team and Athete) from the Entity table? I'm trying to display a list of all the Entities that displays 'name' if Team and 'firstname' and 'lastname' if Athlete.</p> <pre><code>class Entity(models.Model): ent...
1
2009-09-09T04:34:18Z
1,397,616
<p>I am not very clear what you want to do, but in any case you can add a criteria in dervied class instead of checking <strong>unicode</strong> method of derived classes</p> <p>e.g. you can ask the class isTypeA ? or why don't you check the type?</p>
0
2009-09-09T04:58:52Z
[ "python", "django", "inheritance" ]
Polymorphism in Django
1,397,537
<p>I have the following models. How do I get access to the <strong>unicode</strong> of the inheriting tables (Team and Athete) from the Entity table? I'm trying to display a list of all the Entities that displays 'name' if Team and 'firstname' and 'lastname' if Athlete.</p> <pre><code>class Entity(models.Model): ent...
1
2009-09-09T04:34:18Z
1,398,317
<p>This is a little ugly, but I think it should work:</p> <pre><code>entities = Entity.objects.all() for entity in entities: try: print entity.team except: print entity.athlete </code></pre> <p>Check out <a href="http://docs.djangoproject.com/en/1.0/topics/db/models/#id7" rel="nofollow">http://doc...
0
2009-09-09T08:30:02Z
[ "python", "django", "inheritance" ]
Polymorphism in Django
1,397,537
<p>I have the following models. How do I get access to the <strong>unicode</strong> of the inheriting tables (Team and Athete) from the Entity table? I'm trying to display a list of all the Entities that displays 'name' if Team and 'firstname' and 'lastname' if Athlete.</p> <pre><code>class Entity(models.Model): ent...
1
2009-09-09T04:34:18Z
1,640,076
<p>From pure Python, you can use the <code>isinstance</code> function:</p> <pre><code>class Entity: def __init__(self): if isinstance(self, Team): print 'is team' elif isinstance(self, Athlete): print 'is athlete' class Team(Entity): def __unicode__(self): retur...
1
2009-10-28T20:57:39Z
[ "python", "django", "inheritance" ]
Polymorphism in Django
1,397,537
<p>I have the following models. How do I get access to the <strong>unicode</strong> of the inheriting tables (Team and Athete) from the Entity table? I'm trying to display a list of all the Entities that displays 'name' if Team and 'firstname' and 'lastname' if Athlete.</p> <pre><code>class Entity(models.Model): ent...
1
2009-09-09T04:34:18Z
1,966,064
<p>If I undestand correctly, you are simply asking how to call the <code>__unicode__</code> method of a given object. </p> <p>Use <code>unicode(instance)</code> and depending on the type of entity, the appropriate implementation will be called polymorphically.</p>
0
2009-12-27T14:27:33Z
[ "python", "django", "inheritance" ]
Polymorphism in Django
1,397,537
<p>I have the following models. How do I get access to the <strong>unicode</strong> of the inheriting tables (Team and Athete) from the Entity table? I'm trying to display a list of all the Entities that displays 'name' if Team and 'firstname' and 'lastname' if Athlete.</p> <pre><code>class Entity(models.Model): ent...
1
2009-09-09T04:34:18Z
1,978,733
<p>I don't believe you have to do anything. If <code>Entity</code> is never instantiated directly, you will never call the non-existent <code>Entity.__unicode__</code> method. However, if you'd like to play it save, you could add a stub method in your <code>Entity</code> class:</p> <pre><code>class Entity(models.Model...
0
2009-12-30T06:36:34Z
[ "python", "django", "inheritance" ]
Polymorphism in Django
1,397,537
<p>I have the following models. How do I get access to the <strong>unicode</strong> of the inheriting tables (Team and Athete) from the Entity table? I'm trying to display a list of all the Entities that displays 'name' if Team and 'firstname' and 'lastname' if Athlete.</p> <pre><code>class Entity(models.Model): ent...
1
2009-09-09T04:34:18Z
1,996,019
<p>This <a href="http://stackoverflow.com/questions/929029/how-do-i-access-the-child-classes-of-an-object-in-django-without-knowing-the-name/929982#929982">answer from Carl Meyer</a> to the question mentioned earlier by Paul McMillan might be what your looking for. A subtlety to this problem not captured in some of the...
5
2010-01-03T19:35:06Z
[ "python", "django", "inheritance" ]
embedding plot within Qt gui
1,397,553
<p>How do you embed a vpython plot (animated) within your Qt GUI? so that it has its own display area and would not need to created a new window anymore.</p>
2
2009-09-09T04:40:56Z
1,397,627
<p>vpython's <a href="http://vpython.org/contents/FAQ.html" rel="nofollow">FAQs</a> claim that vpython's architecture make any embedding a problem...:</p> <p><strong>Q: Is there a way to embed VPython in another environment?</strong></p> <blockquote> <p>This is difficult because VPython has two threads, your comp...
3
2009-09-09T05:01:18Z
[ "python", "user-interface", "qt" ]
embedding plot within Qt gui
1,397,553
<p>How do you embed a vpython plot (animated) within your Qt GUI? so that it has its own display area and would not need to created a new window anymore.</p>
2
2009-09-09T04:40:56Z
1,414,819
<p>I contacted maintainer of VPython and he confirmed, that he is not aware of any working solution where Visual is embedded into QT window.</p> <p>That turned me to try VTK and so far I'm pretty happy, no problem with using VTK within PyQT framework.</p>
1
2009-09-12T10:30:49Z
[ "python", "user-interface", "qt" ]
how to recover the binary stream(original form) from radix 64 encoding
1,397,799
<p>how to get the actual public key i.e its binary form i.e without radix 64 conversion .i need to extract the public key from radix64 encoding .the pgp server gives me the key in radix 64 format now i have to extract the public key from it.</p>
0
2009-09-09T06:08:13Z
1,397,814
<pre><code>import base64 decoded_bytes = base64.b64decode(ascii_chars) </code></pre>
2
2009-09-09T06:14:38Z
[ "python", "encoding" ]
how to recover the binary stream(original form) from radix 64 encoding
1,397,799
<p>how to get the actual public key i.e its binary form i.e without radix 64 conversion .i need to extract the public key from radix64 encoding .the pgp server gives me the key in radix 64 format now i have to extract the public key from it.</p>
0
2009-09-09T06:08:13Z
1,397,861
<p>base64_encoded_data.decode('base64')</p>
0
2009-09-09T06:32:06Z
[ "python", "encoding" ]
How to read formatted input in python?
1,397,827
<p>I want to read from stdin five numbers entered as follows:</p> <p>3, 4, 5, 1, 8</p> <p>into seperate variables a,b,c,d &amp; e.</p> <p>How do I do this in python?</p> <p>I tried this:</p> <pre><code>import string a=input() b=a.split(', ') </code></pre> <p>for two integers, but it does not work. I get:</p> <pr...
7
2009-09-09T06:19:59Z
1,397,838
<p><strong>Under Python 2.x only</strong> (*)</p> <p>after a = input()</p> <p>a is a tuple with the 5 values readily parsed! </p> <p>A quick way to assign these 5 values is</p> <pre><code>a, b, c, d, e = a </code></pre> <p>(*) with Python version 3.0? or for sure 3.1, input() works more like the raw_input() metho...
2
2009-09-09T06:23:38Z
[ "python", "input" ]
How to read formatted input in python?
1,397,827
<p>I want to read from stdin five numbers entered as follows:</p> <p>3, 4, 5, 1, 8</p> <p>into seperate variables a,b,c,d &amp; e.</p> <p>How do I do this in python?</p> <p>I tried this:</p> <pre><code>import string a=input() b=a.split(', ') </code></pre> <p>for two integers, but it does not work. I get:</p> <pr...
7
2009-09-09T06:19:59Z
1,397,841
<p>Use <a href="http://docs.python.org/library/functions.html#raw%5Finput"><code>raw_input()</code></a> instead of <code>input()</code>.</p> <pre><code># Python 2.5.4 &gt;&gt;&gt; a = raw_input() 3, 4, 5 &gt;&gt;&gt; a '3, 4, 5' &gt;&gt;&gt; b = a.split(', ') &gt;&gt;&gt; b ['3', '4', '5'] &gt;&gt;&gt; [s.strip() for ...
15
2009-09-09T06:24:52Z
[ "python", "input" ]
How to read formatted input in python?
1,397,827
<p>I want to read from stdin five numbers entered as follows:</p> <p>3, 4, 5, 1, 8</p> <p>into seperate variables a,b,c,d &amp; e.</p> <p>How do I do this in python?</p> <p>I tried this:</p> <pre><code>import string a=input() b=a.split(', ') </code></pre> <p>for two integers, but it does not work. I get:</p> <pr...
7
2009-09-09T06:19:59Z
1,397,847
<p>If you print out a (the variable containing your input) you will find out, that a already contains a tuple. You do not have to split the contents.</p> <blockquote> <p>&gt;&gt;&gt; a = input()<br /> 3, 4, 5, 1, 8<br /> &gt;&gt;&gt; print(a)<br /> (3, 4, 5, 1, 8)<br /> &gt;&gt;&gt; type(a)<br /> ...
0
2009-09-09T06:27:46Z
[ "python", "input" ]
How to read formatted input in python?
1,397,827
<p>I want to read from stdin five numbers entered as follows:</p> <p>3, 4, 5, 1, 8</p> <p>into seperate variables a,b,c,d &amp; e.</p> <p>How do I do this in python?</p> <p>I tried this:</p> <pre><code>import string a=input() b=a.split(', ') </code></pre> <p>for two integers, but it does not work. I get:</p> <pr...
7
2009-09-09T06:19:59Z
2,591,151
<pre><code>in = eval(input()) a, b, c, d, e = in </code></pre>
-2
2010-04-07T09:09:30Z
[ "python", "input" ]
What is the simplest way to implement a remote FIFO queue as a Python GAE application?
1,397,864
<p>What is the simplest way to implement a remote FIFO queue as a Python GAE application and then push/pull name-value pair dictionaries to and from it? </p> <p>For example, when an http get is made to the GAE application, the GAE app would return the oldest collection of name-value pairs that were posted to the app w...
1
2009-09-09T06:33:35Z
1,398,656
<p>The below assumes you're using the webapp framework. </p> <p>The simple answer is that you just use self.request.GET, which is a MultiDict (which you can treat as a dict in many cases) containing the form data sent to the request.</p> <p>Note that HTTP allows form data to contain the same key multiple times; if wh...
0
2009-09-09T09:53:16Z
[ "python", "google-app-engine" ]
What is the simplest way to implement a remote FIFO queue as a Python GAE application?
1,397,864
<p>What is the simplest way to implement a remote FIFO queue as a Python GAE application and then push/pull name-value pair dictionaries to and from it? </p> <p>For example, when an http get is made to the GAE application, the GAE app would return the oldest collection of name-value pairs that were posted to the app w...
1
2009-09-09T06:33:35Z
1,398,981
<p>Something along these lines:</p> <pre><code>from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.ext.webapp import run_wsgi_app class QueueItem(db.Model): created = db.DateTimeProperty(required=True, auto_now_add=True) data = db.BlobProperty(required=True) @stati...
3
2009-09-09T11:00:20Z
[ "python", "google-app-engine" ]
Are Python extensions produced by Cython/Pyrex threadsafe?
1,397,977
<p>If not, is there a way I can guarantee thread safety by programming a certain way?</p> <p>To clarify, when talking about "threadsafe,' I mean Python threads, not OS-level threads.</p>
4
2009-09-09T07:04:54Z
1,399,771
<p>Python's global interpreter lock means that only one thread can be active in the interpreter at any one time. However, once control is passed out to a C extension another thread can be active within the interpreter. Multiple threads can be created, and nothing prevents a thread from being interrupted within the mi...
2
2009-09-09T13:45:23Z
[ "python", "thread-safety", "cython", "pyrex" ]
Are Python extensions produced by Cython/Pyrex threadsafe?
1,397,977
<p>If not, is there a way I can guarantee thread safety by programming a certain way?</p> <p>To clarify, when talking about "threadsafe,' I mean Python threads, not OS-level threads.</p>
4
2009-09-09T07:04:54Z
1,400,401
<p>It all depends on the interaction between your Cython code and Python's GIL, as documented in detail <a href="http://docs.cython.org/src/userguide/external_C_code.html#acquiring-and-releasing-the-gil" rel="nofollow">here</a>. If you don't do anything special, Cython-generated code will respect the GIL (as will a C-...
5
2009-09-09T15:27:58Z
[ "python", "thread-safety", "cython", "pyrex" ]
looping over all member variables of a class in python
1,398,022
<p>How do you get a list of all variables in a class thats iteratable? Kind of like locals(), but for a class</p> <pre><code>class Example(object): bool143 = True bool2 = True blah = False foo = True foobar2000 = False def as_list(self) ret = [] for field in XXX: if ge...
40
2009-09-09T07:15:42Z
1,398,049
<pre><code>&gt;&gt;&gt; a = Example() &gt;&gt;&gt; dir(a) ['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'bool143', 'bool2', 'blah', 'foo', 'foobar2000', '...
5
2009-09-09T07:21:44Z
[ "python" ]
looping over all member variables of a class in python
1,398,022
<p>How do you get a list of all variables in a class thats iteratable? Kind of like locals(), but for a class</p> <pre><code>class Example(object): bool143 = True bool2 = True blah = False foo = True foobar2000 = False def as_list(self) ret = [] for field in XXX: if ge...
40
2009-09-09T07:15:42Z
1,398,059
<pre><code>dir(obj) </code></pre> <p>gives you all attributes of the object. You need to filter out the members from methods etc yourself:</p> <pre><code>class Example(object): bool143 = True bool2 = True blah = False foo = True foobar2000 = False members = [attr for attr in dir(Example()) if no...
52
2009-09-09T07:23:45Z
[ "python" ]
looping over all member variables of a class in python
1,398,022
<p>How do you get a list of all variables in a class thats iteratable? Kind of like locals(), but for a class</p> <pre><code>class Example(object): bool143 = True bool2 = True blah = False foo = True foobar2000 = False def as_list(self) ret = [] for field in XXX: if ge...
40
2009-09-09T07:15:42Z
1,398,673
<p>The easy way to do this is to save all instances of the class in a <code>list</code>.</p> <pre><code>a = Example() b = Example() all_examples = [ a, b ] </code></pre> <p>Objects don't spring into existence spontaneously. Some part of your program created them for a reason. The creation is done for a reason. Col...
0
2009-09-09T09:57:34Z
[ "python" ]
looping over all member variables of a class in python
1,398,022
<p>How do you get a list of all variables in a class thats iteratable? Kind of like locals(), but for a class</p> <pre><code>class Example(object): bool143 = True bool2 = True blah = False foo = True foobar2000 = False def as_list(self) ret = [] for field in XXX: if ge...
40
2009-09-09T07:15:42Z
1,939,279
<p>@truppo: your answer is almost correct, but callable will always return false since you're just passing in a string. You need something like the following:</p> <pre><code>[attr for attr in dir(obj()) if not callable(getattr(obj(),attr)) and not attr.startswith("__")] </code></pre> <p>which will filter out function...
18
2009-12-21T10:14:47Z
[ "python" ]
looping over all member variables of a class in python
1,398,022
<p>How do you get a list of all variables in a class thats iteratable? Kind of like locals(), but for a class</p> <pre><code>class Example(object): bool143 = True bool2 = True blah = False foo = True foobar2000 = False def as_list(self) ret = [] for field in XXX: if ge...
40
2009-09-09T07:15:42Z
13,286,863
<p>If you want only the variables (without functions) use:</p> <pre><code>vars(your_object) </code></pre>
41
2012-11-08T10:10:22Z
[ "python" ]
Initialize a string variable in Python: "" or None?
1,398,164
<p>Suppose I have a class with a <strong>string</strong> instance attribute. Should I initialize this attribute with <strong>""</strong> value or <strong>None</strong>? Is either okay?</p> <pre><code>def __init__(self, mystr="") self.mystr = mystr </code></pre> <p>or</p> <pre><code>def __init__(self, mystr=None) ...
30
2009-09-09T07:49:17Z
1,398,175
<p>Since both None and "" are false, you can do both. See <a href="http://docs.python.org/library/stdtypes.html#truth-value-testing" rel="nofollow">6.1. Truth Value Testing</a>.</p> <p><strong>Edit</strong></p> <p>To answer the question in your edit: No, you can assign a different type.</p> <pre><code>&gt;&gt;&gt; a...
1
2009-09-09T07:51:45Z
[ "python" ]
Initialize a string variable in Python: "" or None?
1,398,164
<p>Suppose I have a class with a <strong>string</strong> instance attribute. Should I initialize this attribute with <strong>""</strong> value or <strong>None</strong>? Is either okay?</p> <pre><code>def __init__(self, mystr="") self.mystr = mystr </code></pre> <p>or</p> <pre><code>def __init__(self, mystr=None) ...
30
2009-09-09T07:49:17Z
1,398,177
<p>It depends. If you want to distinguish between no parameter passed in at all, and an empty string passed in, you could use None.</p>
4
2009-09-09T07:52:13Z
[ "python" ]
Initialize a string variable in Python: "" or None?
1,398,164
<p>Suppose I have a class with a <strong>string</strong> instance attribute. Should I initialize this attribute with <strong>""</strong> value or <strong>None</strong>? Is either okay?</p> <pre><code>def __init__(self, mystr="") self.mystr = mystr </code></pre> <p>or</p> <pre><code>def __init__(self, mystr=None) ...
30
2009-09-09T07:49:17Z
1,398,178
<p>If not having a value has a meaning in your program (e.g. an optional value), you should use None. That's its purpose anyway. </p> <p>If the value must be provided by the caller of __init__, I would recommend not to initialize it.</p> <p>If "" makes sense as a default value, use it.</p> <p>In Python the type is d...
35
2009-09-09T07:52:45Z
[ "python" ]
Initialize a string variable in Python: "" or None?
1,398,164
<p>Suppose I have a class with a <strong>string</strong> instance attribute. Should I initialize this attribute with <strong>""</strong> value or <strong>None</strong>? Is either okay?</p> <pre><code>def __init__(self, mystr="") self.mystr = mystr </code></pre> <p>or</p> <pre><code>def __init__(self, mystr=None) ...
30
2009-09-09T07:49:17Z
1,398,180
<p>Either is fine, though <code>None</code> is more common as a convention - <code>None</code> indicates that no value was passed for the optional parameter.</p> <p>There <em>will</em> be times when "" is the correct default value to use - in my experience, those times occur less often.</p>
2
2009-09-09T07:53:28Z
[ "python" ]
Initialize a string variable in Python: "" or None?
1,398,164
<p>Suppose I have a class with a <strong>string</strong> instance attribute. Should I initialize this attribute with <strong>""</strong> value or <strong>None</strong>? Is either okay?</p> <pre><code>def __init__(self, mystr="") self.mystr = mystr </code></pre> <p>or</p> <pre><code>def __init__(self, mystr=None) ...
30
2009-09-09T07:49:17Z
1,398,418
<p>Either <em>might</em> be fine, but I don't think there is a definite answer.</p> <ul> <li>If you want to indicate that the value has not been set, comparing with <code>None</code> is better than comparing with <code>""</code>, since <code>""</code> might be a valid value,</li> <li>If you just want a default value, ...
4
2009-09-09T08:54:49Z
[ "python" ]
Initialize a string variable in Python: "" or None?
1,398,164
<p>Suppose I have a class with a <strong>string</strong> instance attribute. Should I initialize this attribute with <strong>""</strong> value or <strong>None</strong>? Is either okay?</p> <pre><code>def __init__(self, mystr="") self.mystr = mystr </code></pre> <p>or</p> <pre><code>def __init__(self, mystr=None) ...
30
2009-09-09T07:49:17Z
1,398,596
<p>For lists or dicts, the answer is more clear, according to <a href="http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#default-parameter-values" rel="nofollow">http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#default-parameter-values</a> use None as default parameter.</p> <p>...
1
2009-09-09T09:41:19Z
[ "python" ]
Initialize a string variable in Python: "" or None?
1,398,164
<p>Suppose I have a class with a <strong>string</strong> instance attribute. Should I initialize this attribute with <strong>""</strong> value or <strong>None</strong>? Is either okay?</p> <pre><code>def __init__(self, mystr="") self.mystr = mystr </code></pre> <p>or</p> <pre><code>def __init__(self, mystr=None) ...
30
2009-09-09T07:49:17Z
1,398,628
<p>None is used to indicate "not set", whereas any other value is used to indicate a "default" value.</p> <p>Hence, if your class copes with empty strings and you like it as a default value, use "". If your class needs to check if the variable was set at all, use None.</p> <p>Notice that it doesn't matter if your var...
5
2009-09-09T09:48:34Z
[ "python" ]
Initialize a string variable in Python: "" or None?
1,398,164
<p>Suppose I have a class with a <strong>string</strong> instance attribute. Should I initialize this attribute with <strong>""</strong> value or <strong>None</strong>? Is either okay?</p> <pre><code>def __init__(self, mystr="") self.mystr = mystr </code></pre> <p>or</p> <pre><code>def __init__(self, mystr=None) ...
30
2009-09-09T07:49:17Z
18,683,729
<p>Another way to initialize an empty string is by using the built-in <code>str()</code> function with no arguments.</p> <blockquote> <p>str(object='')</p> <p>Return a string containing a nicely printable representation of an object.</p> <p>...</p> <p>If no argument is given, returns the empty string,...
1
2013-09-08T12:34:55Z
[ "python" ]
Django: show list of many to many items in the admin interface
1,398,606
<p>This might be a simple question, but i can't seem to grasp it.</p> <p>I have two simple models in models.py: Service and Host. Host.services has a m2m relationship with Service. In other words, a host has several services and one service can reside on multiple hosts; a basic m2m.</p> <p>models.py</p> <pre><code>c...
8
2009-09-09T09:43:11Z
1,398,652
<p>You should change <code>get_services</code> to something like:</p> <pre><code>def get_services(self): return "\n".join([s.servicename for s in self.services.all()]) </code></pre> <p><strong>Update:</strong> Try using <code>\n</code> as the separator rather than <code>&lt;br/&gt;</code>, as the output of get_se...
19
2009-09-09T09:52:52Z
[ "python", "django" ]
Python: display the time in a different time zone
1,398,674
<p>Is there an elegant way to display the current time in another time zone?</p> <p>I would like to have something with the general spirit of:</p> <pre><code>cur=&lt;Get the current time, perhaps datetime.datetime.now()&gt; print "Local time ", cur print "Pacific time ", &lt;something like cur.tz('PST')&gt; print "...
16
2009-09-09T09:57:52Z
1,398,729
<p>You could use the <a href="http://pytz.sourceforge.net/">pytz</a> library:</p> <pre><code>&gt;&gt;&gt; from datetime import datetime, timedelta &gt;&gt;&gt; from pytz import timezone &gt;&gt;&gt; import pytz &gt;&gt;&gt; utc = pytz.utc &gt;&gt;&gt; utc.zone 'UTC' &gt;&gt;&gt; eastern = timezone('US/Eastern') &gt;&g...
24
2009-09-09T10:10:43Z
[ "python", "time", "timezone" ]
Python: display the time in a different time zone
1,398,674
<p>Is there an elegant way to display the current time in another time zone?</p> <p>I would like to have something with the general spirit of:</p> <pre><code>cur=&lt;Get the current time, perhaps datetime.datetime.now()&gt; print "Local time ", cur print "Pacific time ", &lt;something like cur.tz('PST')&gt; print "...
16
2009-09-09T09:57:52Z
1,398,732
<p>You can check <a href="http://stackoverflow.com/questions/1301493/python-timezones">this question</a>.</p> <p>Or try using <a href="http://pytz.sourceforge.net/" rel="nofollow">pytz</a>. Here you can find an installation guide with some usage examples.</p>
0
2009-09-09T10:11:27Z
[ "python", "time", "timezone" ]
Python: display the time in a different time zone
1,398,674
<p>Is there an elegant way to display the current time in another time zone?</p> <p>I would like to have something with the general spirit of:</p> <pre><code>cur=&lt;Get the current time, perhaps datetime.datetime.now()&gt; print "Local time ", cur print "Pacific time ", &lt;something like cur.tz('PST')&gt; print "...
16
2009-09-09T09:57:52Z
1,398,742
<p>One way, through the timezone setting of the C library, is</p> <pre><code>&gt;&gt;&gt; cur=time.time() &gt;&gt;&gt; os.environ["TZ"]="US/Pacific" &gt;&gt;&gt; time.tzset() &gt;&gt;&gt; time.strftime("%T %Z", time.localtime(cur)) '03:09:51 PDT' &gt;&gt;&gt; os.environ["TZ"]="GMT" &gt;&gt;&gt; time.strftime("%T %Z", ...
2
2009-09-09T10:12:15Z
[ "python", "time", "timezone" ]
Python: display the time in a different time zone
1,398,674
<p>Is there an elegant way to display the current time in another time zone?</p> <p>I would like to have something with the general spirit of:</p> <pre><code>cur=&lt;Get the current time, perhaps datetime.datetime.now()&gt; print "Local time ", cur print "Pacific time ", &lt;something like cur.tz('PST')&gt; print "...
16
2009-09-09T09:57:52Z
5,096,669
<p>A simpler method:</p> <pre><code>from datetime import datetime from pytz import timezone south_africa = timezone('Africa/Johannesburg') sa_time = datetime.now(south_africa) print sa_time.strftime('%Y-%m-%d_%H-%M-%S') </code></pre>
37
2011-02-23T20:26:12Z
[ "python", "time", "timezone" ]
Python: display the time in a different time zone
1,398,674
<p>Is there an elegant way to display the current time in another time zone?</p> <p>I would like to have something with the general spirit of:</p> <pre><code>cur=&lt;Get the current time, perhaps datetime.datetime.now()&gt; print "Local time ", cur print "Pacific time ", &lt;something like cur.tz('PST')&gt; print "...
16
2009-09-09T09:57:52Z
31,286,366
<p>This is my implementation:</p> <pre><code>from datetime import datetime from pytz import timezone def local_time(zone='Asia/Jerusalem'): other_zone = timezone(zone) other_zone_time = datetime.now(other_zone) return other_zone_time.strftime('%T') </code></pre>
0
2015-07-08T07:39:29Z
[ "python", "time", "timezone" ]
Python: display the time in a different time zone
1,398,674
<p>Is there an elegant way to display the current time in another time zone?</p> <p>I would like to have something with the general spirit of:</p> <pre><code>cur=&lt;Get the current time, perhaps datetime.datetime.now()&gt; print "Local time ", cur print "Pacific time ", &lt;something like cur.tz('PST')&gt; print "...
16
2009-09-09T09:57:52Z
35,274,555
<p>I need time info all time time, so I have this neat .py script on my server that lets me just select and deselect what time zones I want to display in order of east->west. </p> <p>It prints like this:</p> <pre><code>Australia/Sydney : 2016-02-09 03:52:29 AEDT+1100 Asia/Singapore : 2016-02-09 00:52:29 S...
0
2016-02-08T16:32:56Z
[ "python", "time", "timezone" ]
Problems with Snow Leopard, Django & PIL
1,398,701
<p>I am having some trouble getting Django &amp; PIL work properly since upgrading to Snow Leopard.</p> <p>I have installed freetype, libjpeg and then PIL, which tells me:</p> <pre><code>--- TKINTER support ok --- JPEG support ok --- ZLIB (PNG/ZIP) support ok --- FREETYPE2 support ok </code></pre> <p>but when I try...
5
2009-09-09T10:05:13Z
1,413,877
<p>Cato</p> <p>I had the same experience with Leopard 10.5.x Here is what I did to fix it, (may not work for you).</p> <ol> <li>Go to your PIL working folder (where you unzipped PIL) cd to your build folder cd to your lib.macosx-10.* folder (specific to your os) remove *.so cd back to your PIL build folder (I logged...
14
2009-09-12T00:43:05Z
[ "python", "django", "osx-snow-leopard", "python-imaging-library", "libjpeg" ]
Problems with Snow Leopard, Django & PIL
1,398,701
<p>I am having some trouble getting Django &amp; PIL work properly since upgrading to Snow Leopard.</p> <p>I have installed freetype, libjpeg and then PIL, which tells me:</p> <pre><code>--- TKINTER support ok --- JPEG support ok --- ZLIB (PNG/ZIP) support ok --- FREETYPE2 support ok </code></pre> <p>but when I try...
5
2009-09-09T10:05:13Z
2,661,327
<p>As a follow up to Ken's response, I had the same problem with Snow Leopard 10.6.x which was caused by installing PIL before libjpeg. After installing libjpeg, I reinstalled PIL by doing the following.</p> <ol> <li>cd to PIL working folder</li> <li>python setup.py clean</li> <li>python setup.py build_ext -i &lt;-...
5
2010-04-18T06:16:25Z
[ "python", "django", "osx-snow-leopard", "python-imaging-library", "libjpeg" ]
Problems with Snow Leopard, Django & PIL
1,398,701
<p>I am having some trouble getting Django &amp; PIL work properly since upgrading to Snow Leopard.</p> <p>I have installed freetype, libjpeg and then PIL, which tells me:</p> <pre><code>--- TKINTER support ok --- JPEG support ok --- ZLIB (PNG/ZIP) support ok --- FREETYPE2 support ok </code></pre> <p>but when I try...
5
2009-09-09T10:05:13Z
5,903,771
<p>I ran into a similar issue while on Ubuntu 8.04. I was able to get myself out of it by simply re-issuing my PIL install (via pip):</p> <pre><code>pip install PIL --upgrade </code></pre> <p>Not sure what the issue was but I suspect it's similar to what others here reported.</p>
3
2011-05-05T20:37:54Z
[ "python", "django", "osx-snow-leopard", "python-imaging-library", "libjpeg" ]
using cookies with twisted.web.client
1,398,740
<p>I'm trying to make a web client application using twisted but having some trouble with cookies. Does anyone have an example I can look at?</p>
3
2009-09-09T10:12:10Z
1,399,641
<p>Turns out there is no easy way afaict The headers are stored in twisted.web.client.HTTPClientFactory but not available from twisted.web.client.getPage() which is the function designed for pulling back a web page. I ended up rewriting the function: </p> <pre><code>from twisted.web import client def getPage(url, con...
2
2009-09-09T13:18:38Z
[ "python", "cookies", "twisted" ]
using cookies with twisted.web.client
1,398,740
<p>I'm trying to make a web client application using twisted but having some trouble with cookies. Does anyone have an example I can look at?</p>
3
2009-09-09T10:12:10Z
1,687,928
<p>While it's true that <code>getPage</code> doesn't easily allow direct access to the request or response headers (just one example of how <code>getPage</code> isn't a super awesome API), cookies are actually supported.</p> <pre><code>cookies = {cookies: tosend} d = getPage(url, cookies=cookies) def cbPage(result): ...
7
2009-11-06T14:23:05Z
[ "python", "cookies", "twisted" ]
using cookies with twisted.web.client
1,398,740
<p>I'm trying to make a web client application using twisted but having some trouble with cookies. Does anyone have an example I can look at?</p>
3
2009-09-09T10:12:10Z
6,163,306
<pre><code>from twisted.internet import reactor from twisted.web import client def getPage(url, contextFactory=None, *args, **kwargs): return client._makeGetterFactory( url, CustomHTTPClientFactory, contextFactory=contextFactory, *args, **kwargs).deferred class CustomHTTPClientFact...
1
2011-05-28T17:39:33Z
[ "python", "cookies", "twisted" ]
Downloading file using IE from python
1,398,780
<p>I'm trying to download file with Python using IE:</p> <pre><code>from win32com.client import DispatchWithEvents class EventHandler(object): def OnDownloadBegin(self): pass ie = DispatchWithEvents("InternetExplorer.Application", EventHandler) ie.Visible = 0 ie.Navigate('http://website/file.xml') </co...
7
2009-09-09T10:18:42Z
1,398,794
<p>You don't need to use IE. You could use something like</p> <pre><code>import urllib2 data = urllib2.urlopen("http://website/file.xml").read() </code></pre> <p><strong>Update:</strong> I see you've updated your question. If you need to use a browser, then clearly this answer isn't appropriate for you.</p> <p><stro...
1
2009-09-09T10:22:41Z
[ "python", "internet-explorer", "com" ]
Downloading file using IE from python
1,398,780
<p>I'm trying to download file with Python using IE:</p> <pre><code>from win32com.client import DispatchWithEvents class EventHandler(object): def OnDownloadBegin(self): pass ie = DispatchWithEvents("InternetExplorer.Application", EventHandler) ie.Visible = 0 ie.Navigate('http://website/file.xml') </co...
7
2009-09-09T10:18:42Z
1,398,819
<p>If you can't control Internet Explorer using its COM interface, I suggest using the <a href="http://www.autoitscript.com/autoit3/" rel="nofollow">AutoIt</a> COM to control its GUI from Python.</p>
1
2009-09-09T10:27:29Z
[ "python", "internet-explorer", "com" ]
Downloading file using IE from python
1,398,780
<p>I'm trying to download file with Python using IE:</p> <pre><code>from win32com.client import DispatchWithEvents class EventHandler(object): def OnDownloadBegin(self): pass ie = DispatchWithEvents("InternetExplorer.Application", EventHandler) ie.Visible = 0 ie.Navigate('http://website/file.xml') </co...
7
2009-09-09T10:18:42Z
4,565,493
<p>I don't know how to say this nicely, but this sounds like about the most foolhardy software idea in recent memory. Python is much more capable of performing AJAX calls than IE is.</p> <p>To access the data, yes, you <em>can</em> use <code>urllib</code> and <code>urllib2</code> . If there is JSON data in the respon...
3
2010-12-30T19:15:39Z
[ "python", "internet-explorer", "com" ]
Downloading file using IE from python
1,398,780
<p>I'm trying to download file with Python using IE:</p> <pre><code>from win32com.client import DispatchWithEvents class EventHandler(object): def OnDownloadBegin(self): pass ie = DispatchWithEvents("InternetExplorer.Application", EventHandler) ie.Visible = 0 ie.Navigate('http://website/file.xml') </co...
7
2009-09-09T10:18:42Z
4,566,022
<p>I have something like that (an awful 3rd part application with lots of weird dotnet 'ajax' controls), and I use iMacros plugin for Firefox to do some automation. But I'm doing batch inserts, not downloads.</p> <p>You can try record, edit and replay the inputs sent thru a VNC session. Look at something like <a href=...
0
2010-12-30T20:29:08Z
[ "python", "internet-explorer", "com" ]