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 |
|---|---|---|---|---|---|---|---|---|---|
Why can't I pass a direct reference to a dictionary value to a function? | 855,514 | <p>Earlier today I asked a <a href="http://stackoverflow.com/questions/853483/can-i-pass-dictionary-values-entry-and-keys-to-function">question</a>
about passing dictionary values to a function. While I understand now how to accomplish what I was trying to accomplish the why question (which was not asked) was never an... | 1 | 2009-05-13T00:25:53Z | 855,589 | <p>You can only pass references to objects.</p>
<pre><code>a = { 'a' : 123, 'b' : [ 1, 2, 3 ] }
def f(dictionary_value):
dictionary_value.append(4)
f( a['b'] )
</code></pre>
<p>Does what you expect. Dictionary element <code>a['b']</code> is passed "by reference" to the function <code>f</code> which updates the... | 2 | 2009-05-13T01:01:11Z | [
"python",
"function",
"dictionary",
"parameters"
] |
How do I upload a files to google app engine app when field name is not known | 855,667 | <p>I have tried a few options, none of which seem to work (if I have a simple multipart form with a named field, it works well, but when I don't know the name I can't just grab all files in the request...). </p>
<p>I have looked at <a href="http://stackoverflow.com/questions/81451/upload-files-in-google-app-engine">ht... | 1 | 2009-05-13T01:28:16Z | 857,151 | <p>Check out the documentation on the <a href="http://pythonpaste.org/webob/reference.html#query-post-variables" rel="nofollow">Webob request object</a>. File uploads are treated the same as other form fields, except they're a file upload object, rather than a string - so you can iterate over the available fields the s... | 0 | 2009-05-13T10:15:41Z | [
"python",
"google-app-engine"
] |
Python try-else | 855,759 | <p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
| 308 | 2009-05-13T02:15:11Z | 855,764 | <p>The statements in the <code>else</code> block are executed if execution falls off the bottom of the <code>try</code> - if there was no exception. Honestly, I've never found a need.</p>
<p>However, <a href="http://docs.python.org/tutorial/errors.html#handling-exceptions">Handling Exceptions</a> notes:</p>
<blockquo... | 531 | 2009-05-13T02:18:22Z | [
"python",
"exception-handling"
] |
Python try-else | 855,759 | <p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
| 308 | 2009-05-13T02:15:11Z | 855,768 | <p>Looking at <a href="http://docs.python.org/reference/compound_stmts.html" rel="nofollow">Python reference</a> it seems that <code>else</code> is executed after <code>try</code> when there's no exception.
The optional else clause is executed if and when control flows off the end of the try clause. <a href="http://www... | 2 | 2009-05-13T02:20:32Z | [
"python",
"exception-handling"
] |
Python try-else | 855,759 | <p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
| 308 | 2009-05-13T02:15:11Z | 855,781 | <p>Even though you can't think of a use of it right now, you can bet there has to be a use for it. Here is an unimaginative sample:</p>
<p>With <code>else</code>:</p>
<pre><code>a = [1,2,3]
try:
something = a[2]
except:
print "out of bounds"
else:
print something
</code></pre>
<p>Without <code>else</code... | 7 | 2009-05-13T02:26:42Z | [
"python",
"exception-handling"
] |
Python try-else | 855,759 | <p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
| 308 | 2009-05-13T02:15:11Z | 855,783 | <p>The <code>else:</code> block is confusing and (nearly) useless. It's also part of the <code>for</code> and <code>while</code> statements.</p>
<p>Actually, even on an <code>if</code>-statement, the <code>else:</code> can be abused in truly terrible ways creating bugs that are very hard to find.</p>
<p>Consider thi... | -12 | 2009-05-13T02:28:03Z | [
"python",
"exception-handling"
] |
Python try-else | 855,759 | <p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
| 308 | 2009-05-13T02:15:11Z | 855,796 | <p>I find it really useful when you've got cleanup to do that has to be done even if there's an exception:</p>
<pre><code>try:
data = something_that_can_go_wrong()
except Exception as e: # yes, I know that's a bad way to do it...
handle_exception(e)
else:
do_stuff(data)
finally:
clean_up()
</code></pre... | 12 | 2009-05-13T02:34:26Z | [
"python",
"exception-handling"
] |
Python try-else | 855,759 | <p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
| 308 | 2009-05-13T02:15:11Z | 855,803 | <p>One use: test some code that should raise an exception.</p>
<pre><code>try:
this_should_raise_TypeError()
except TypeError:
pass
except:
assert False, "Raised the wrong exception type"
else:
assert False, "Didn't raise any exception"
</code></pre>
<p>(This code should be abstracted into a more gene... | 31 | 2009-05-13T02:36:39Z | [
"python",
"exception-handling"
] |
Python try-else | 855,759 | <p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
| 308 | 2009-05-13T02:15:11Z | 865,647 | <p>That's it. The 'else' block of a try-except clause exists for code that runs when (and only when) the tried operation succeeds. It can be used, and it can be abused.</p>
<pre><code>try:
fp= open("configuration_file", "rb")
except EnvironmentError:
confdata= '' # it's ok if the file can't be opened
else:
... | 1 | 2009-05-14T20:43:20Z | [
"python",
"exception-handling"
] |
Python try-else | 855,759 | <p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
| 308 | 2009-05-13T02:15:11Z | 865,770 | <p>An <code>else</code> block can often exist to complement functionality that occurs in every <code>except</code> block.</p>
<pre><code>try:
test_consistency(valuable_data)
except Except1:
inconsistency_type = 1
except Except2:
inconsistency_type = 2
except:
# Something else is wrong
raise
else:
... | 0 | 2009-05-14T21:07:30Z | [
"python",
"exception-handling"
] |
Python try-else | 855,759 | <p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
| 308 | 2009-05-13T02:15:11Z | 915,253 | <p>There's a nice example of <code>try-else</code> in <a href="http://www.python.org/dev/peps/pep-0380/#id9">PEP 380</a>. Basically, it comes down to doing different exception handling in different parts of the algorithm.</p>
<p>It's something like this:</p>
<pre><code>try:
do_init_stuff()
except:
handle_init... | 5 | 2009-05-27T11:39:02Z | [
"python",
"exception-handling"
] |
Python try-else | 855,759 | <p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
| 308 | 2009-05-13T02:15:11Z | 6,078,085 | <p>Perhaps a use might be:</p>
<pre><code>#debug = []
def debuglog(text, obj=None):
" Simple little logger. "
try:
debug # does global exist?
except NameError:
pass # if not, don't even bother displaying
except:
print('Unknown cause. Debug debuglog().')
else:
#... | 1 | 2011-05-20T22:12:04Z | [
"python",
"exception-handling"
] |
Python try-else | 855,759 | <p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
| 308 | 2009-05-13T02:15:11Z | 13,863,613 | <p>Here is another place where I like to use this pattern:</p>
<pre><code> while data in items:
try
data = json.loads(data)
except ValueError as e:
log error
else:
# work on the `data`
</code></pre>
| 0 | 2012-12-13T15:58:14Z | [
"python",
"exception-handling"
] |
Python try-else | 855,759 | <p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
| 308 | 2009-05-13T02:15:11Z | 14,590,478 | <p>There is one <strong>big</strong> reason to use <code>else</code> - style and readability. It's generally a good idea to keep code that can cause exceptions near the code that deals with them. For example, compare these:</p>
<pre><code>try:
from EasyDialogs import AskPassword
// 20 other lines
getpass... | 42 | 2013-01-29T19:13:57Z | [
"python",
"exception-handling"
] |
Python try-else | 855,759 | <p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
| 308 | 2009-05-13T02:15:11Z | 17,937,190 | <p>I have found <code>else</code> useful for dealing with a possibly incorrect config file:</p>
<pre><code>try:
value, unit = cfg['locks'].split()
except ValueError:
msg = 'lock must consist of two words separated by white space'
self.log('warn', msg)
else:
# get on with lock processing if config is o... | 0 | 2013-07-30T02:06:15Z | [
"python",
"exception-handling"
] |
Python try-else | 855,759 | <p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
| 308 | 2009-05-13T02:15:11Z | 18,357,464 | <p>From <a href="http://docs.python.org/2/tutorial/errors.html#handling-exceptions">Errors and Exceptions # Handling exceptions - docs.python.org</a></p>
<blockquote>
<p>The <code>try ... except</code> statement has an optional <code>else</code> clause, which,
when present, must follow all except clauses. It is us... | 7 | 2013-08-21T12:29:59Z | [
"python",
"exception-handling"
] |
Python try-else | 855,759 | <p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
| 308 | 2009-05-13T02:15:11Z | 20,127,761 | <p>I have found the <code>try: ... else:</code> construct useful in the situation where you are running database queries and logging the results of those queries to a separate database of the same flavour/type. Let's say I have lots of worker threads all handling database queries submitted to a queue </p>
<pre><code>#... | 0 | 2013-11-21T17:22:05Z | [
"python",
"exception-handling"
] |
Python try-else | 855,759 | <p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
| 308 | 2009-05-13T02:15:11Z | 22,580,418 | <p>Most answers seem to concentrate on why we can't just put the material in the else clause in the try clause itself. The question <a href="http://stackoverflow.com/questions/3996329/">else clause in try statement... what is it good for</a> specifically asks why the else clause code cannot go <em>after</em> the try bl... | 2 | 2014-03-22T16:39:05Z | [
"python",
"exception-handling"
] |
Python try-else | 855,759 | <p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
| 308 | 2009-05-13T02:15:11Z | 28,443,901 | <blockquote>
<h1>Python try-else</h1>
<p>What is the intended use of the optional <code>else</code> clause of the try statement?</p>
</blockquote>
<h2>Summary</h2>
<p>The <code>else</code> statement runs if there are <em>no</em> exceptions and if not interrupted by a <code>return</code>, <code>continue</code>,... | 9 | 2015-02-10T23:31:25Z | [
"python",
"exception-handling"
] |
Python try-else | 855,759 | <p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
| 308 | 2009-05-13T02:15:11Z | 29,400,828 | <p>Suppose your programming logic depends on whether a dictionary has an entry with a given key. You can test the result of <code>dict.get(key)</code> using <code>if... else...</code> construct, or you can do:</p>
<pre><code>try:
val = dic[key]
except KeyError:
do_some_stuff()
else:
do_some_stuff_with_val(... | 0 | 2015-04-01T21:05:41Z | [
"python",
"exception-handling"
] |
Python try-else | 855,759 | <p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
| 308 | 2009-05-13T02:15:11Z | 29,710,273 | <p>Try-except-else is great for combining <a href="https://docs.python.org/2/glossary.html#term-eafp" rel="nofollow">the EAFP pattern</a> with <a href="https://docs.python.org/2/glossary.html#term-duck-typing" rel="nofollow">duck-typing</a>:</p>
<pre><code>try:
cs = x.cleanupSet
except AttributeError:
pass
else:
... | 3 | 2015-04-17T22:11:22Z | [
"python",
"exception-handling"
] |
Please introduce a multi-processing library in Perl or Ruby | 855,805 | <p>In python we can use multiprocessing modules.
If there is a similar library in Perl and Ruby, would you teach it?
I would appreciate it if you can include a brief sample.</p>
| 5 | 2009-05-13T02:37:32Z | 855,820 | <p><strong>Ruby:</strong></p>
<ul>
<li><a href="http://stackoverflow.com/questions/710785/working-with-multiple-processes-in-ruby">Working with multiple processes in Ruby</a></li>
<li><a href="http://www.igvita.com/2008/11/13/concurrency-is-a-myth-in-ruby/" rel="nofollow">Concurrency is a Myth in Ruby</a></li>
</ul>
... | 12 | 2009-05-13T02:44:24Z | [
"python",
"ruby",
"perl"
] |
Please introduce a multi-processing library in Perl or Ruby | 855,805 | <p>In python we can use multiprocessing modules.
If there is a similar library in Perl and Ruby, would you teach it?
I would appreciate it if you can include a brief sample.</p>
| 5 | 2009-05-13T02:37:32Z | 856,035 | <p>With Perl, you have options. One option is to use processes as below. I need to look up how to write the analogous program using threads but <a href="http://perldoc.perl.org/perlthrtut.html" rel="nofollow">http://perldoc.perl.org/perlthrtut.html</a> should give you an idea.</p>
<pre><code>#!/usr/bin/perl
use stric... | 9 | 2009-05-13T04:14:55Z | [
"python",
"ruby",
"perl"
] |
Please introduce a multi-processing library in Perl or Ruby | 855,805 | <p>In python we can use multiprocessing modules.
If there is a similar library in Perl and Ruby, would you teach it?
I would appreciate it if you can include a brief sample.</p>
| 5 | 2009-05-13T02:37:32Z | 857,105 | <p>Check out <a href="http://search.cpan.org/dist/Coro/" rel="nofollow">Coro</a> which provide coroutines to Perl.</p>
<p>Here is an excerpt from the authors docs....</p>
<blockquote>
<p>This module collection manages continuations in general, most often in the form of cooperative threads (also called coros, or sim... | 3 | 2009-05-13T10:01:43Z | [
"python",
"ruby",
"perl"
] |
Please introduce a multi-processing library in Perl or Ruby | 855,805 | <p>In python we can use multiprocessing modules.
If there is a similar library in Perl and Ruby, would you teach it?
I would appreciate it if you can include a brief sample.</p>
| 5 | 2009-05-13T02:37:32Z | 4,857,344 | <p>Have a look at this nice summary page for Perl parallel processing libs <a href="http://www.openfusion.net/perl/parallel_processing_perl_modules" rel="nofollow">http://www.openfusion.net/perl/parallel_processing_perl_modules</a>. I like Parallel::Forker, its a modern and more powerful library than the older Parallel... | 1 | 2011-01-31T23:31:29Z | [
"python",
"ruby",
"perl"
] |
Please introduce a multi-processing library in Perl or Ruby | 855,805 | <p>In python we can use multiprocessing modules.
If there is a similar library in Perl and Ruby, would you teach it?
I would appreciate it if you can include a brief sample.</p>
| 5 | 2009-05-13T02:37:32Z | 9,201,759 | <p><a href="https://github.com/pmahoney/process_shared" rel="nofollow">https://github.com/pmahoney/process_shared</a> for ruby</p>
| 0 | 2012-02-08T21:31:12Z | [
"python",
"ruby",
"perl"
] |
Auto-populating created_by field with Django admin site | 855,816 | <p>I want to use the Django admin interface for a very simple web application but I can't get around a problem that should not be that hard to resolve ..</p>
<p>Consider the following:</p>
<pre><code>class Contact(models.Model):
name = models.CharField(max_length=250, blank=False)
created_by = models.ForeignK... | 18 | 2009-05-13T02:42:01Z | 855,837 | <p><a href="http://code.djangoproject.com/wiki/CookBookNewformsAdminAndUser">http://code.djangoproject.com/wiki/CookBookNewformsAdminAndUser</a></p>
<p>Involves implementing save methods on your ModelAdmin objects.</p>
| 22 | 2009-05-13T02:50:42Z | [
"python",
"django",
"django-models",
"django-admin"
] |
Auto-populating created_by field with Django admin site | 855,816 | <p>I want to use the Django admin interface for a very simple web application but I can't get around a problem that should not be that hard to resolve ..</p>
<p>Consider the following:</p>
<pre><code>class Contact(models.Model):
name = models.CharField(max_length=250, blank=False)
created_by = models.ForeignK... | 18 | 2009-05-13T02:42:01Z | 855,866 | <p>You need to specify a <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#default" rel="nofollow">default</a> for the field, in this case a method call that gets the current user (see the auth documentation to get the current user).</p>
| 3 | 2009-05-13T03:04:21Z | [
"python",
"django",
"django-models",
"django-admin"
] |
Auto-populating created_by field with Django admin site | 855,816 | <p>I want to use the Django admin interface for a very simple web application but I can't get around a problem that should not be that hard to resolve ..</p>
<p>Consider the following:</p>
<pre><code>class Contact(models.Model):
name = models.CharField(max_length=250, blank=False)
created_by = models.ForeignK... | 18 | 2009-05-13T02:42:01Z | 12,977,762 | <p>I really wanted a better solution than the ones I found elsewhere, so I wrote some middleware - implementation on the <a href="http://stackoverflow.com/a/12977709/795488">Populate user Id question</a>. My solution requires no changes to any form or view.</p>
| 1 | 2012-10-19T15:40:43Z | [
"python",
"django",
"django-models",
"django-admin"
] |
Subclassing ctypes - Python | 855,941 | <p>This is some code I found on the internet. I'm not sure how it is meant to be used. I simply filled <em>members</em> with the enum keys/values and it works, but I'm curious what this metaclass is all about. I am assuming it has something to do with ctypes, but I can't find much information on subclassing ctypes. I k... | 4 | 2009-05-13T03:36:33Z | 855,961 | <p>A metaclass is a class used to create classes. Think of it this way: all objects have a class, a class is also an object, therefore, it makes sense that a class can have a class.</p>
<p><a href="http://www.ibm.com/developerworks/linux/library/l-pymeta.html" rel="nofollow">http://www.ibm.com/developerworks/linux/lib... | 4 | 2009-05-13T03:41:27Z | [
"python",
"ctypes"
] |
Subclassing ctypes - Python | 855,941 | <p>This is some code I found on the internet. I'm not sure how it is meant to be used. I simply filled <em>members</em> with the enum keys/values and it works, but I'm curious what this metaclass is all about. I am assuming it has something to do with ctypes, but I can't find much information on subclassing ctypes. I k... | 4 | 2009-05-13T03:36:33Z | 856,614 | <p>That is indeed a weird class.</p>
<p>The way you are using it is correct, although another way would be:</p>
<pre><code>class TOKEN(Enumeration):
T_UNDEF = 0
T_NAME = 1
T_NUMBER = 2
T_STRING = 3
T_OPERATOR = 4
T_VARIABLE = 5
T_FUNCTION = 6
</code></pre>
<p>(That's what the f... | 3 | 2009-05-13T07:47:21Z | [
"python",
"ctypes"
] |
Changing LD_LIBRARY_PATH at runtime for ctypes | 856,116 | <p>How do you update this environment variable at runtime so that ctypes can load a library wherever? I've tried the following and neither seem to work.</p>
<pre><code>from ctypes import *
os.environ['LD_LIBRARY_PATH'] = "/home/starlon/Projects/pyCFA635/lib"
os.putenv('LD_LIBRARY_PATH', "/home/starlon/Projects/pyCFA... | 25 | 2009-05-13T04:52:49Z | 856,287 | <p>By the time a program such as Python is running, the dynamic loader (ld.so.1 or something similar) has already read LD_LIBRARY_PATH and won't notice any changes thereafter. So, unless the Python software itself evaluates LD_LIBRARY_PATH and uses it to build the possible path name of the library for <code>dlopen()</... | 30 | 2009-05-13T05:57:52Z | [
"python",
"ctypes"
] |
Changing LD_LIBRARY_PATH at runtime for ctypes | 856,116 | <p>How do you update this environment variable at runtime so that ctypes can load a library wherever? I've tried the following and neither seem to work.</p>
<pre><code>from ctypes import *
os.environ['LD_LIBRARY_PATH'] = "/home/starlon/Projects/pyCFA635/lib"
os.putenv('LD_LIBRARY_PATH', "/home/starlon/Projects/pyCFA... | 25 | 2009-05-13T04:52:49Z | 1,226,278 | <p>CDLL can be passed a fully qualified path name, so for example I am using the following in one of my scripts where the .so is in the same directory as the python script.</p>
<pre><code>import os
path = os.path.dirname(os.path.realpath(__file__))
dll = CDLL("%s/iface.so"%path)
</code></pre>
<p>In your case the foll... | 11 | 2009-08-04T08:20:48Z | [
"python",
"ctypes"
] |
Changing LD_LIBRARY_PATH at runtime for ctypes | 856,116 | <p>How do you update this environment variable at runtime so that ctypes can load a library wherever? I've tried the following and neither seem to work.</p>
<pre><code>from ctypes import *
os.environ['LD_LIBRARY_PATH'] = "/home/starlon/Projects/pyCFA635/lib"
os.putenv('LD_LIBRARY_PATH', "/home/starlon/Projects/pyCFA... | 25 | 2009-05-13T04:52:49Z | 4,326,241 | <p>Even if you give a fully qualified path to CDLL or cdll.LoadLibrary(), you may still need to set LD_LIBRARY_PATH before invoking Python. If the shared library you load explicitly refers to another shared library and no "rpath" is set in the .so for that library, then it won't be found, even if it has already been lo... | 18 | 2010-12-01T15:58:50Z | [
"python",
"ctypes"
] |
Changing LD_LIBRARY_PATH at runtime for ctypes | 856,116 | <p>How do you update this environment variable at runtime so that ctypes can load a library wherever? I've tried the following and neither seem to work.</p>
<pre><code>from ctypes import *
os.environ['LD_LIBRARY_PATH'] = "/home/starlon/Projects/pyCFA635/lib"
os.putenv('LD_LIBRARY_PATH', "/home/starlon/Projects/pyCFA... | 25 | 2009-05-13T04:52:49Z | 35,271,855 | <p>Compile your binary with a rpath relative to the current working directory like:</p>
<pre><code>gcc -shared -o yourbinary.so yoursource.c otherbinary.so \
-Wl,-rpath='.',-rpath='./another/relative/rpath' -fpic
</code></pre>
<p>Then, you are able to change the working directory in python at runtime with:</p>
... | 1 | 2016-02-08T14:19:27Z | [
"python",
"ctypes"
] |
launch a process off a mysql row insert | 856,173 | <p>I need to launch a server side process off a mysql row insert. I'd appreciate some feedback/suggestions. So far I can think of three options:</p>
<p>1st (least attractive): My preliminary understanding is that I can write a kind of "custom trigger" in C that could fire off a row insert. In addition to having to r... | 3 | 2009-05-13T05:15:21Z | 856,208 | <p>Write an insert trigger which duplicates inserted rows to a secondary table. Periodically poll the secondary table for rows with an external application/cronjob; if any rows are in the table, delete them and do your processing (or set a 'processing started' flag and only delete from the secondary table upon successf... | 4 | 2009-05-13T05:28:42Z | [
"python",
"mysql",
"linux",
"perl"
] |
launch a process off a mysql row insert | 856,173 | <p>I need to launch a server side process off a mysql row insert. I'd appreciate some feedback/suggestions. So far I can think of three options:</p>
<p>1st (least attractive): My preliminary understanding is that I can write a kind of "custom trigger" in C that could fire off a row insert. In addition to having to r... | 3 | 2009-05-13T05:15:21Z | 856,210 | <p>I had this issue about 2 years ago in .NET and I went with the 3rd approach. However, looking back at it, I'm wondering if looking into Triggers with PhpMyAdmin & MySQL isn't the approach to look into.</p>
| 0 | 2009-05-13T05:30:23Z | [
"python",
"mysql",
"linux",
"perl"
] |
what are the applications of the python reload function? | 856,174 | <p>I have been wondering about the reload() function in python, which seems like it can lead to problems if used without care. </p>
<p>Why would you want to reload a module, rather than just stop/start python again?</p>
<p>I imagine one application might be to test changes to a module interactively. </p>
| 1 | 2009-05-13T05:15:30Z | 856,181 | <blockquote>
<p>I imagine one application might be to test changes to a module interactively.</p>
</blockquote>
<p>That's really the only use for it. From the <a href="http://docs.python.org/library/functions.html#reload" rel="nofollow">Python documentation</a>:</p>
<blockquote>
<p>This is useful if you have edit... | 4 | 2009-05-13T05:18:02Z | [
"python"
] |
what are the applications of the python reload function? | 856,174 | <p>I have been wondering about the reload() function in python, which seems like it can lead to problems if used without care. </p>
<p>Why would you want to reload a module, rather than just stop/start python again?</p>
<p>I imagine one application might be to test changes to a module interactively. </p>
| 1 | 2009-05-13T05:15:30Z | 856,194 | <p>reload is useful for reloading code that may have changed in a Python module. Usually this means a plugin system.</p>
<p>Take a look at this link:</p>
<p><a href="http://www.codexon.com/posts/a-better-python-reload" rel="nofollow">http://www.codexon.com/posts/a-better-python-reload</a></p>
<p>It will tell you the... | 6 | 2009-05-13T05:21:54Z | [
"python"
] |
what are the applications of the python reload function? | 856,174 | <p>I have been wondering about the reload() function in python, which seems like it can lead to problems if used without care. </p>
<p>Why would you want to reload a module, rather than just stop/start python again?</p>
<p>I imagine one application might be to test changes to a module interactively. </p>
| 1 | 2009-05-13T05:15:30Z | 945,818 | <p>Adding a link to my new <a href="http://code.google.com/p/reimport/" rel="nofollow">reimport</a> module that was released yesterday. This provides a more thorough reimport than the reload() builtin. With this reimport you can be sure that class changes and function updates will get reflected in all instances and cal... | 1 | 2009-06-03T16:51:02Z | [
"python"
] |
How do I represent many to many relation in the form of Google App Engine? | 856,462 | <pre><code>class Entry(db.Model):
...
class Tag(db.Model):
...
class EntryTag(db.Model):
entry = db.ReferenceProperty(Entry, required=True, collection_name='tag_set')
tag = db.ReferenceProperty(Tag, required=True, collection_name='entry_set')
</code></pre>
<p>The template should be {{form.as_table}}<... | 1 | 2009-05-13T06:58:45Z | 942,398 | <p>You will need to create a formset for your <code>EntryTag</code> class. For more information, see <a href="http://docs.djangoproject.com/en/dev/topics/forms/formsets/#topics-forms-formsets" rel="nofollow">the Django formset docs</a>.</p>
<p>Otherwise, you may wish to create a custom form with a <a href="http://doc... | 1 | 2009-06-02T23:20:55Z | [
"python",
"google-app-engine"
] |
tokenize module | 856,769 | <p>Please help</p>
<p>There are many tokens in module tokenize like STRING,BACKQUOTE,AMPEREQUAL etc.</p>
<pre><code> >>> import cStringIO
>>> import tokenize
>>> source = "{'test':'123','hehe':['hooray',0x10]}"
>>> src = cStringIO.StringIO(source).readline
>>> src = tok... | 0 | 2009-05-13T08:31:23Z | 856,820 | <p>You will need to read python's code <a href="http://svn.python.org/view/python/trunk/Parser/tokenizer.c?revision=65543&view=markup" rel="nofollow">tokenizer.c</a> to understand the detail.
Just search the keyword you want to know. Should be not hard.</p>
| 3 | 2009-05-13T08:43:01Z | [
"python",
"tokenize"
] |
tokenize module | 856,769 | <p>Please help</p>
<p>There are many tokens in module tokenize like STRING,BACKQUOTE,AMPEREQUAL etc.</p>
<pre><code> >>> import cStringIO
>>> import tokenize
>>> source = "{'test':'123','hehe':['hooray',0x10]}"
>>> src = cStringIO.StringIO(source).readline
>>> src = tok... | 0 | 2009-05-13T08:31:23Z | 856,824 | <p>Python's lexical analysis (including tokens) is documented at <a href="http://docs.python.org/reference/lexical_analysis.html" rel="nofollow">http://docs.python.org/reference/lexical_analysis.html</a> . As <a href="http://docs.python.org/library/token.html#module-token" rel="nofollow">http://docs.python.org/library... | 2 | 2009-05-13T08:44:21Z | [
"python",
"tokenize"
] |
tokenize module | 856,769 | <p>Please help</p>
<p>There are many tokens in module tokenize like STRING,BACKQUOTE,AMPEREQUAL etc.</p>
<pre><code> >>> import cStringIO
>>> import tokenize
>>> source = "{'test':'123','hehe':['hooray',0x10]}"
>>> src = cStringIO.StringIO(source).readline
>>> src = tok... | 0 | 2009-05-13T08:31:23Z | 862,269 | <p>The various AMPER, BACKQUOTE etc values correspond to the token number of the appropriate symbol for python tokens / operators. ie AMPER = & (ampersand), AMPEREQUAL = "&=".</p>
<p>However, you don't actually have to care about these. They're used by the internal C tokeniser, but the python wrapper simplif... | 2 | 2009-05-14T08:52:08Z | [
"python",
"tokenize"
] |
PyAMF / Django - Flex class mapping errors | 856,846 | <p>I'm using PyAmf to communicate with a Flex app. But I keep getting errors.</p>
<p>My model:</p>
<pre><code>from django.contrib.auth.models import User
class Talent(User):
street = models.CharField(max_length=100)
street_nr = models.CharField(max_length=100)
postal_code = models.PositiveIntegerField()
... | 2 | 2009-05-13T08:51:47Z | 861,074 | <p>This is done using the IExternalizable interface.</p>
<ul>
<li><a href="http://dev.pyamf.org/wiki/IExternalizable" rel="nofollow">PyAMF Docs</a></li>
<li><a href="http://livedocs.adobe.com/flex/3/langref/flash/utils/IExternalizable.html" rel="nofollow">Adobe Docs</a></li>
</ul>
<p>It lets you explicitly write and ... | 3 | 2009-05-14T00:33:11Z | [
"python",
"django",
"flex",
"pyamf"
] |
PyAMF / Django - Flex class mapping errors | 856,846 | <p>I'm using PyAmf to communicate with a Flex app. But I keep getting errors.</p>
<p>My model:</p>
<pre><code>from django.contrib.auth.models import User
class Talent(User):
street = models.CharField(max_length=100)
street_nr = models.CharField(max_length=100)
postal_code = models.PositiveIntegerField()
... | 2 | 2009-05-13T08:51:47Z | 3,472,935 | <p>With the release of PyAMF 0.6b2 I can finally answer this question.</p>
<p>0.5.1 was pretty strict in how it handled inheritance when it came to encoding Django models. It ensured that all properties were guaranteed to be encoded on each object - and expected that all properties were available when decoding the req... | 1 | 2010-08-12T23:55:34Z | [
"python",
"django",
"flex",
"pyamf"
] |
2D arrays in Python | 856,948 | <p>What's the best way to create 2D arrays in Python?</p>
<p>What I want is want is to store values like this:</p>
<pre><code>X , Y , Z
</code></pre>
<p>so that I access data like <code>X[2],Y[2],Z[2]</code> or <code>X[n],Y[n],Z[n]</code> where <code>n</code> is variable.
I don't know in the beginning how big <code>... | 23 | 2009-05-13T09:22:51Z | 856,976 | <p>In Python one would usually use <a href="http://docs.python.org/tutorial/datastructures.html">lists</a> for this purpose. Lists can be nested arbitrarily, thus allowing the creation of a 2D array. Not every sublist needs to be the same size, so that solves your other problem. Have a look at the examples I linked to.... | 8 | 2009-05-13T09:28:51Z | [
"python",
"arrays",
"list",
"tuples",
"multidimensional-array"
] |
2D arrays in Python | 856,948 | <p>What's the best way to create 2D arrays in Python?</p>
<p>What I want is want is to store values like this:</p>
<pre><code>X , Y , Z
</code></pre>
<p>so that I access data like <code>X[2],Y[2],Z[2]</code> or <code>X[n],Y[n],Z[n]</code> where <code>n</code> is variable.
I don't know in the beginning how big <code>... | 23 | 2009-05-13T09:22:51Z | 856,978 | <pre><code>>>> a = []
>>> for i in xrange(3):
... a.append([])
... for j in xrange(3):
... a[i].append(i+j)
...
>>> a
[[0, 1, 2], [1, 2, 3], [2, 3, 4]]
>>>
</code></pre>
| 20 | 2009-05-13T09:29:01Z | [
"python",
"arrays",
"list",
"tuples",
"multidimensional-array"
] |
2D arrays in Python | 856,948 | <p>What's the best way to create 2D arrays in Python?</p>
<p>What I want is want is to store values like this:</p>
<pre><code>X , Y , Z
</code></pre>
<p>so that I access data like <code>X[2],Y[2],Z[2]</code> or <code>X[n],Y[n],Z[n]</code> where <code>n</code> is variable.
I don't know in the beginning how big <code>... | 23 | 2009-05-13T09:22:51Z | 857,034 | <p>If you want to do some serious work with arrays then you should use the <a href="http://numpy.scipy.org/">numpy library</a>. This will allow you for example to do vector addition and matrix multiplication, and for large arrays it is much faster than Python lists. </p>
<p>However, numpy requires that the size is pre... | 7 | 2009-05-13T09:42:42Z | [
"python",
"arrays",
"list",
"tuples",
"multidimensional-array"
] |
2D arrays in Python | 856,948 | <p>What's the best way to create 2D arrays in Python?</p>
<p>What I want is want is to store values like this:</p>
<pre><code>X , Y , Z
</code></pre>
<p>so that I access data like <code>X[2],Y[2],Z[2]</code> or <code>X[n],Y[n],Z[n]</code> where <code>n</code> is variable.
I don't know in the beginning how big <code>... | 23 | 2009-05-13T09:22:51Z | 857,169 | <p>Depending what you're doing, you may not really have a 2-D array.</p>
<p>80% of the time you have simple list of "row-like objects", which might be proper sequences.</p>
<pre><code>myArray = [ ('pi',3.14159,'r',2), ('e',2.71828,'theta',.5) ]
myArray[0][1] == 3.14159
myArray[1][1] == 2.71828
</code></pre>
<p>More... | 9 | 2009-05-13T10:21:14Z | [
"python",
"arrays",
"list",
"tuples",
"multidimensional-array"
] |
2D arrays in Python | 856,948 | <p>What's the best way to create 2D arrays in Python?</p>
<p>What I want is want is to store values like this:</p>
<pre><code>X , Y , Z
</code></pre>
<p>so that I access data like <code>X[2],Y[2],Z[2]</code> or <code>X[n],Y[n],Z[n]</code> where <code>n</code> is variable.
I don't know in the beginning how big <code>... | 23 | 2009-05-13T09:22:51Z | 857,255 | <p>I would suggest that you use a dictionary like so:</p>
<pre><code>arr = {}
arr[1] = (1, 2, 4)
arr[18] = (3, 4, 5)
print(arr[1])
>>> (1, 2, 4)
</code></pre>
<p>If you're not sure an entry is defined in the dictionary, you'll need a validation mechanism when calling "arr[x]", e.g. try-except.</p>
| 5 | 2009-05-13T10:47:14Z | [
"python",
"arrays",
"list",
"tuples",
"multidimensional-array"
] |
2D arrays in Python | 856,948 | <p>What's the best way to create 2D arrays in Python?</p>
<p>What I want is want is to store values like this:</p>
<pre><code>X , Y , Z
</code></pre>
<p>so that I access data like <code>X[2],Y[2],Z[2]</code> or <code>X[n],Y[n],Z[n]</code> where <code>n</code> is variable.
I don't know in the beginning how big <code>... | 23 | 2009-05-13T09:22:51Z | 857,698 | <p>If you are concerned about memory footprint, the Python standard library contains the <a href="http://docs.python.org/library/array.html" rel="nofollow">array module</a>; these arrays contain elements of the same type.</p>
| 3 | 2009-05-13T12:33:18Z | [
"python",
"arrays",
"list",
"tuples",
"multidimensional-array"
] |
2D arrays in Python | 856,948 | <p>What's the best way to create 2D arrays in Python?</p>
<p>What I want is want is to store values like this:</p>
<pre><code>X , Y , Z
</code></pre>
<p>so that I access data like <code>X[2],Y[2],Z[2]</code> or <code>X[n],Y[n],Z[n]</code> where <code>n</code> is variable.
I don't know in the beginning how big <code>... | 23 | 2009-05-13T09:22:51Z | 30,797,346 | <p>Please consider the follwing codes:</p>
<pre><code>from numpy import zeros
scores = zeros((len(chain1),len(chain2)), float)
</code></pre>
| 0 | 2015-06-12T07:13:45Z | [
"python",
"arrays",
"list",
"tuples",
"multidimensional-array"
] |
Does python have a call_user_func() like PHP? | 856,992 | <p>Does python have a function like <code>call_user_func()</code> in PHP?</p>
<p>PHP Version:</p>
<pre><code>call_user_func(array($object,$methodName),$parameters)
</code></pre>
<p>How do I achieve the above in Python?</p>
| 0 | 2009-05-13T09:33:23Z | 857,038 | <p>I don't see the problem, unless <code>methodName</code> is a string. In that case <a href="http://docs.python.org/library/functions.html#getattr" rel="nofollow">getattr</a> does the job:</p>
<pre><code>>>> class A:
... def func(self, a, b):
... return a + b
...
>>> a = A()
>>>... | 7 | 2009-05-13T09:42:54Z | [
"php",
"python"
] |
Does python have a call_user_func() like PHP? | 856,992 | <p>Does python have a function like <code>call_user_func()</code> in PHP?</p>
<p>PHP Version:</p>
<pre><code>call_user_func(array($object,$methodName),$parameters)
</code></pre>
<p>How do I achieve the above in Python?</p>
| 0 | 2009-05-13T09:33:23Z | 857,063 | <p>For a given object 'obj', a given method name 'meth', and a given set of arguments 'args':</p>
<pre><code> obj.__getattribute__(meth)(*args)
</code></pre>
<p>Should get you there.</p>
<p>Of course, it goes without saying - What the heck is it you want to do?</p>
| 0 | 2009-05-13T09:49:43Z | [
"php",
"python"
] |
Does python have a call_user_func() like PHP? | 856,992 | <p>Does python have a function like <code>call_user_func()</code> in PHP?</p>
<p>PHP Version:</p>
<pre><code>call_user_func(array($object,$methodName),$parameters)
</code></pre>
<p>How do I achieve the above in Python?</p>
| 0 | 2009-05-13T09:33:23Z | 857,099 | <p>You can call use getattr with locals() or globals() to do something similar</p>
<pre><code># foo.method() is called if it's available in global scope
getattr(globals()['foo'], 'method')(*args)
# Same thing, but for 'foo' in local scope
getattr(locals()['foo'], 'method')(*args)
</code></pre>
<p>See also: <strong>D... | 0 | 2009-05-13T10:00:35Z | [
"php",
"python"
] |
Does python have a call_user_func() like PHP? | 856,992 | <p>Does python have a function like <code>call_user_func()</code> in PHP?</p>
<p>PHP Version:</p>
<pre><code>call_user_func(array($object,$methodName),$parameters)
</code></pre>
<p>How do I achieve the above in Python?</p>
| 0 | 2009-05-13T09:33:23Z | 857,139 | <p>Picking which object to instantiate isn't that hard. A class is a first-class object and can be assigned to a variable or passed as an argument to a function.</p>
<pre><code>class A(object):
def __init__( self, arg1, arg2 ):
etc.
class B(object):
def __init__( self, arg1, arg2 ):
etc.
t... | 0 | 2009-05-13T10:12:52Z | [
"php",
"python"
] |
Does python have a call_user_func() like PHP? | 856,992 | <p>Does python have a function like <code>call_user_func()</code> in PHP?</p>
<p>PHP Version:</p>
<pre><code>call_user_func(array($object,$methodName),$parameters)
</code></pre>
<p>How do I achieve the above in Python?</p>
| 0 | 2009-05-13T09:33:23Z | 857,294 | <p>If you need to use classes from far-off places (and in fact, if you need any classes at all) then you're best off creating and using a dictionary for them:</p>
<pre><code>funcs = {'Eggs': foo.Eggs, 'Spam': bar.Spam}
def call_func(func_name, *args, **kwargs):
if not func_name in funcs:
raise ValueError(... | 4 | 2009-05-13T10:55:52Z | [
"php",
"python"
] |
Infinite recursion trying to check all elements of a TreeCtrl | 857,560 | <p>I have a TreeCtrl in which more than one Item can be assigned the same object as PyData. When the object is updated, I want to update all of the items in the tree which have that object as their PyData.</p>
<p>I thought the following code would solve the problem quite neatly, but for some reason the logical test (c... | 0 | 2009-05-13T12:01:18Z | 857,715 | <p>There is no way for <code>current != self.GetFirstVisibleItem()</code> to be false. See comments below</p>
<pre><code>def RefreshNodes(self, obj, current=None):
print "Entered refresh"
current = current or self.GetFirstVisibleItem()
if current.IsOk():
print self.GetPyData(current).name
... | 1 | 2009-05-13T12:37:57Z | [
"python",
"wxpython"
] |
Infinite recursion trying to check all elements of a TreeCtrl | 857,560 | <p>I have a TreeCtrl in which more than one Item can be assigned the same object as PyData. When the object is updated, I want to update all of the items in the tree which have that object as their PyData.</p>
<p>I thought the following code would solve the problem quite neatly, but for some reason the logical test (c... | 0 | 2009-05-13T12:01:18Z | 857,742 | <p>How is the "next" item ever going to be the first item? </p>
<p>This appears to be a tautology. The next is never the first.</p>
<pre><code> current = self.GetNextVisible(current)
current != self.GetFirstVisibleItem()
</code></pre>
<p>It doesn't appear that next wraps around to the beginning. It appear... | 3 | 2009-05-13T12:44:08Z | [
"python",
"wxpython"
] |
Infinite recursion trying to check all elements of a TreeCtrl | 857,560 | <p>I have a TreeCtrl in which more than one Item can be assigned the same object as PyData. When the object is updated, I want to update all of the items in the tree which have that object as their PyData.</p>
<p>I thought the following code would solve the problem quite neatly, but for some reason the logical test (c... | 0 | 2009-05-13T12:01:18Z | 857,849 | <p>Just realised the problem: if current is not a valid item, it's logical value is False.</p>
<p>Hence the line current = current or self.GetFirstVisibleItem() wraps back to the first item before current.IsOk() is called...</p>
| 0 | 2009-05-13T13:09:15Z | [
"python",
"wxpython"
] |
Setting the encoding for sax parser in Python | 857,597 | <p>When I feed a utf-8 encoded xml to an ExpatParser instance:</p>
<pre><code>def test(filename):
parser = xml.sax.make_parser()
with codecs.open(filename, 'r', encoding='utf-8') as f:
for line in f:
parser.feed(line)
</code></pre>
<p>...I get the following:</p>
<pre><code>Traceback (most... | 6 | 2009-05-13T12:09:11Z | 857,654 | <p>Your code fails in Python 2.6, but works in 3.0.</p>
<p>This does work in 2.6, presumably because it allows the parser itself to figure out the encoding (perhaps by reading the encoding optionally specified on the first line of the XML file, and otherwise defaulting to utf-8):</p>
<pre><code>def test(filename):
... | 5 | 2009-05-13T12:22:58Z | [
"python",
"unicode",
"sax"
] |
Setting the encoding for sax parser in Python | 857,597 | <p>When I feed a utf-8 encoded xml to an ExpatParser instance:</p>
<pre><code>def test(filename):
parser = xml.sax.make_parser()
with codecs.open(filename, 'r', encoding='utf-8') as f:
for line in f:
parser.feed(line)
</code></pre>
<p>...I get the following:</p>
<pre><code>Traceback (most... | 6 | 2009-05-13T12:09:11Z | 857,899 | <p>The SAX parser in Python 2.6 should be able to parse utf-8 without mangling it. Although you've left out the ContentHandler you're using with the parser, if that content handler attempts to print any non-ascii characters to your console, that will cause a crash.</p>
<p>For example, say I have this XML doc:</p>
<pr... | 5 | 2009-05-13T13:18:29Z | [
"python",
"unicode",
"sax"
] |
Setting the encoding for sax parser in Python | 857,597 | <p>When I feed a utf-8 encoded xml to an ExpatParser instance:</p>
<pre><code>def test(filename):
parser = xml.sax.make_parser()
with codecs.open(filename, 'r', encoding='utf-8') as f:
for line in f:
parser.feed(line)
</code></pre>
<p>...I get the following:</p>
<pre><code>Traceback (most... | 6 | 2009-05-13T12:09:11Z | 1,848,649 | <p>Jarret Hardie already explained the issue. But those of you who are coding for the command line, and don't seem to have the "sys.setdefaultencoding" visible, the quick work around this bug (or "feature") is:</p>
<pre><code>import sys
reload(sys)
sys.setdefaultencoding('utf-8')
</code></pre>
<p>Hopefully <code>relo... | 5 | 2009-12-04T18:03:11Z | [
"python",
"unicode",
"sax"
] |
Setting the encoding for sax parser in Python | 857,597 | <p>When I feed a utf-8 encoded xml to an ExpatParser instance:</p>
<pre><code>def test(filename):
parser = xml.sax.make_parser()
with codecs.open(filename, 'r', encoding='utf-8') as f:
for line in f:
parser.feed(line)
</code></pre>
<p>...I get the following:</p>
<pre><code>Traceback (most... | 6 | 2009-05-13T12:09:11Z | 12,046,099 | <p>Commenting on janpf's answer (sorry, I don't have enough reputation to put it there), note that Janpf's version will break IDLE which requires its own stdout etc. that is different from sys's default. So I'd suggest modifying the code to be something like:</p>
<pre><code>import sys
currentStdOut = sys.stdout
curr... | 0 | 2012-08-20T22:27:44Z | [
"python",
"unicode",
"sax"
] |
Setting the encoding for sax parser in Python | 857,597 | <p>When I feed a utf-8 encoded xml to an ExpatParser instance:</p>
<pre><code>def test(filename):
parser = xml.sax.make_parser()
with codecs.open(filename, 'r', encoding='utf-8') as f:
for line in f:
parser.feed(line)
</code></pre>
<p>...I get the following:</p>
<pre><code>Traceback (most... | 6 | 2009-05-13T12:09:11Z | 33,598,023 | <p>To set an arbitrary file encoding for a SAX parser, one can use <a href="https://docs.python.org/2/library/xml.sax.reader.html#xml.sax.xmlreader.InputSource" rel="nofollow">InputSource</a> as follows:</p>
<pre><code>def test(filename, encoding):
parser = xml.sax.make_parser()
with open(filename, "rb") as f:... | 2 | 2015-11-08T19:24:21Z | [
"python",
"unicode",
"sax"
] |
List Element without iteration | 858,109 | <p>I want to know how to find an element in list without iteration</p>
| -6 | 2009-05-13T13:58:28Z | 858,121 | <p>The <a href="http://docs.python.org/tutorial/datastructures.html#more-on-lists" rel="nofollow"><code>mylist.index("blah")</code> method</a> of a list will return the index of the first occurrence of the item "blah":</p>
<pre><code>>>> ["item 1", "blah", "item 3"].index("blah")
1
>>> ["item 1", "it... | 9 | 2009-05-13T13:59:42Z | [
"python",
"list",
"find",
"iteration"
] |
List Element without iteration | 858,109 | <p>I want to know how to find an element in list without iteration</p>
| -6 | 2009-05-13T13:58:28Z | 858,145 | <p>You can also use <code>in</code> syntax:</p>
<pre><code>>>> l = [1,2,3]
>>> 1 in l
True
</code></pre>
| 4 | 2009-05-13T14:03:45Z | [
"python",
"list",
"find",
"iteration"
] |
List Element without iteration | 858,109 | <p>I want to know how to find an element in list without iteration</p>
| -6 | 2009-05-13T13:58:28Z | 858,146 | <p>This is a somewhat strange question. Do you want a hotline with <code>$someDeity</code>, or do you want another function to do the iteration for you, or do you want a <em>more efficient</em> way to test membership?</p>
<p>In the first case I cannot help you. In the second case, have a look at the <a href="http://do... | 5 | 2009-05-13T14:03:49Z | [
"python",
"list",
"find",
"iteration"
] |
Dead-simple web authentication for a single user | 858,149 | <p>I wrote a small internal web app using (a subset of) <a href="http://pylonshq.com/" rel="nofollow">pylons</a>. As it turns out, I now need to allow a user to access it from the web. This is not an application that was written to be web facing, and it has a bunch of gaping security holes.</p>
<p>What is the simplest... | 0 | 2009-05-13T14:04:35Z | 858,173 | <p>if there's only a single user, <a href="http://impetus.us/~rjmooney/projects/misc/clientcertauth.html" rel="nofollow">using a certificate</a> would probably be easiest.</p>
| 8 | 2009-05-13T14:08:56Z | [
"python",
"security",
"authentication",
"web-applications"
] |
Dead-simple web authentication for a single user | 858,149 | <p>I wrote a small internal web app using (a subset of) <a href="http://pylonshq.com/" rel="nofollow">pylons</a>. As it turns out, I now need to allow a user to access it from the web. This is not an application that was written to be web facing, and it has a bunch of gaping security holes.</p>
<p>What is the simplest... | 0 | 2009-05-13T14:04:35Z | 858,184 | <p>Basic HTTP authentication can be bruteforced easily by tools like brutus. If his ip is static you can allow his ip and deny all others with htaccess. </p>
| 2 | 2009-05-13T14:09:47Z | [
"python",
"security",
"authentication",
"web-applications"
] |
Dead-simple web authentication for a single user | 858,149 | <p>I wrote a small internal web app using (a subset of) <a href="http://pylonshq.com/" rel="nofollow">pylons</a>. As it turns out, I now need to allow a user to access it from the web. This is not an application that was written to be web facing, and it has a bunch of gaping security holes.</p>
<p>What is the simplest... | 0 | 2009-05-13T14:04:35Z | 858,188 | <p>How about VPN? There should be plenty of user-friendly VPN clients. He might already be familiar with the technology since many corporations use them to grant workers access to internal network while on the road.</p>
| 4 | 2009-05-13T14:10:49Z | [
"python",
"security",
"authentication",
"web-applications"
] |
How to save django FileField to user folder? | 858,213 | <p>I've got a model like this</p>
<blockquote>
<pre>
<code>
def upload_location(instance, filename):
return 'validate/%s/builds/%s' % (get_current_user(), filename)
class MidletPair(models.Model):
jad_file = models.FileField(upload_to = upload_location)
jar_file = models.FileField(upload_to = upload_loca... | 3 | 2009-05-13T14:16:48Z | 858,259 | <p>First, don't search the net for Django help. Search here only: <a href="http://docs.djangoproject.com/en/dev/" rel="nofollow">http://docs.djangoproject.com/en/dev/</a></p>
<p>Second, the current user is part of Authentication.</p>
<p><a href="http://docs.djangoproject.com/en/dev/topics/auth/#topics-auth" rel="nof... | 4 | 2009-05-13T14:23:49Z | [
"python",
"django",
"django-models",
"upload"
] |
How to save django FileField to user folder? | 858,213 | <p>I've got a model like this</p>
<blockquote>
<pre>
<code>
def upload_location(instance, filename):
return 'validate/%s/builds/%s' % (get_current_user(), filename)
class MidletPair(models.Model):
jad_file = models.FileField(upload_to = upload_location)
jar_file = models.FileField(upload_to = upload_loca... | 3 | 2009-05-13T14:16:48Z | 858,576 | <p>The current user is stored in the request object, and you can't get that in a model method unless you pass it in from elsewhere - which you can't do in the upload_to function.</p>
<p>So you'll need to approach this in a different manner - I would suggest doing it at the form level. You can pass the request object i... | 8 | 2009-05-13T15:13:25Z | [
"python",
"django",
"django-models",
"upload"
] |
How to save django FileField to user folder? | 858,213 | <p>I've got a model like this</p>
<blockquote>
<pre>
<code>
def upload_location(instance, filename):
return 'validate/%s/builds/%s' % (get_current_user(), filename)
class MidletPair(models.Model):
jad_file = models.FileField(upload_to = upload_location)
jar_file = models.FileField(upload_to = upload_loca... | 3 | 2009-05-13T14:16:48Z | 2,424,900 | <p>If you added a user field to the model, and have that attribute set before you performed an upload, then you could get the user in to your upload_location function via the instance attribute.</p>
| 5 | 2010-03-11T12:38:04Z | [
"python",
"django",
"django-models",
"upload"
] |
Datetime issue in Django | 858,470 | <p>I am trying to add the datetime object of a person. Whenever the birth year is less than year 1942, I get a strange error <code>DataError: unable to parse time</code> when reading the data back from the DB.</p>
<pre><code>class Person(models.Model):
"""A simple class to hold the person info
"""
name = m... | 3 | 2009-05-13T14:54:17Z | 858,554 | <p>The only thing I could come up with here can be found in the <a href="http://www.postgresql.org/docs/6.3/static/c0804.htm">PostgreSQL docs</a>. My guess is that Django is storing your date in a "reltime" field, which can only go back 68 years. My calculator verifies that 2009-68 == 1941, which seems very close to wh... | 6 | 2009-05-13T15:08:32Z | [
"python",
"django",
"datetime",
"postgresql"
] |
How to recognize whether a script is running on a tty? | 858,623 | <p>I would like my script to act differently in an interactive shell session and when running with redirected stdout (for example when piped to some other command).</p>
<p>How do I recognize which of these two happen in a Python script?</p>
<p>Example of such behavior in existing program: grep --color=auto highlights... | 43 | 2009-05-13T15:24:06Z | 858,628 | <pre><code>import os, sys
os.isatty(sys.stdout.fileno())
</code></pre>
<p>or</p>
<pre><code>sys.stdout.isatty()
</code></pre>
| 46 | 2009-05-13T15:24:45Z | [
"python",
"shell"
] |
getopts Values class and Template.Substitute don't (immediately) work together | 858,784 | <p>I have python code something like:</p>
<pre><code>from string import Template
import optparse
def main():
usage = "usage: %prog options outputname"
p = optparse.OptionParser(usage)
p.add_option('--optiona', '-a', default="")
p.add_option('--optionb', '-b', default="")
options, arguments = p.parse_args()
... | 1 | 2009-05-13T15:55:57Z | 858,949 | <p>The following appears to work for me:</p>
<pre><code>from string import Template
import optparse
def main():
usage = "usage: %prog options outputname"
p = optparse.OptionParser(usage)
p.add_option('--optiona', '-a', default="")
p.add_option('--optionb', '-b', default="")
options, arguments = p.... | 4 | 2009-05-13T16:24:14Z | [
"python",
"templates",
"getopts"
] |
getopts Values class and Template.Substitute don't (immediately) work together | 858,784 | <p>I have python code something like:</p>
<pre><code>from string import Template
import optparse
def main():
usage = "usage: %prog options outputname"
p = optparse.OptionParser(usage)
p.add_option('--optiona', '-a', default="")
p.add_option('--optionb', '-b', default="")
options, arguments = p.parse_args()
... | 1 | 2009-05-13T15:55:57Z | 858,972 | <p><code>OptionParser.parse_args</code> returns an object with the option variable names as attributes, rather than as dictionary keys. The error you're getting means that <code>options</code> does not support subscripting, which it would normally do by implementing <code>__getitem__</code>.</p>
<p>So, in other words,... | 6 | 2009-05-13T16:29:29Z | [
"python",
"templates",
"getopts"
] |
How to redirect python warnings to a custom stream? | 858,916 | <p>Let's say I have a file-like object like StreamIO and want the python's warning module write all warning messages to it. How do I do that?</p>
| 4 | 2009-05-13T16:18:21Z | 858,928 | <p>Try reassigning <a href="http://docs.python.org/library/warnings.html#warnings.showwarning" rel="nofollow">warnings.showwarning</a> i.e.</p>
<pre><code>#!/sw/bin/python2.5
import warnings, sys
def customwarn(message, category, filename, lineno, file=None, line=None):
sys.stdout.write(warnings.formatwarning(me... | 7 | 2009-05-13T16:20:28Z | [
"python",
"warnings",
"io"
] |
How to redirect python warnings to a custom stream? | 858,916 | <p>Let's say I have a file-like object like StreamIO and want the python's warning module write all warning messages to it. How do I do that?</p>
| 4 | 2009-05-13T16:18:21Z | 859,138 | <p>I think something like this would work, although it's untested code and the interface looks like there is a cleaner way which eludes me at present:</p>
<pre><code>import warnings
# defaults to the 'myStringIO' file
def my_warning_wrapper(message, category, filename, lineno, file=myStringIO, line=None):
warning... | 0 | 2009-05-13T16:57:28Z | [
"python",
"warnings",
"io"
] |
How to redirect python warnings to a custom stream? | 858,916 | <p>Let's say I have a file-like object like StreamIO and want the python's warning module write all warning messages to it. How do I do that?</p>
| 4 | 2009-05-13T16:18:21Z | 859,351 | <pre><code>import sys
import StringIO
sys.stdout = StringIO.StringIO()
</code></pre>
| 0 | 2009-05-13T17:40:52Z | [
"python",
"warnings",
"io"
] |
About 20 models in 1 django app | 859,192 | <p>I have started work on a local app for myself that runs through the browser. Having recently gone through the django tutorial I'm thinking that it might be better to use django rather than just plain python.</p>
<p>There's one problem: I have at least 20 models and each will have many functions. Quite simply it's g... | 34 | 2009-05-13T17:06:36Z | 859,211 | <p>You can break up the models over multiple files. This goes for views as well. </p>
| 0 | 2009-05-13T17:09:20Z | [
"python",
"django",
"django-models"
] |
About 20 models in 1 django app | 859,192 | <p>I have started work on a local app for myself that runs through the browser. Having recently gone through the django tutorial I'm thinking that it might be better to use django rather than just plain python.</p>
<p>There's one problem: I have at least 20 models and each will have many functions. Quite simply it's g... | 34 | 2009-05-13T17:06:36Z | 859,217 | <p>You <em>can</em> split them into separate files and simply have imports at the top of your main models.py field. </p>
<p>Whether you'd really <em>want</em> to is another question.</p>
| 0 | 2009-05-13T17:10:15Z | [
"python",
"django",
"django-models"
] |
About 20 models in 1 django app | 859,192 | <p>I have started work on a local app for myself that runs through the browser. Having recently gone through the django tutorial I'm thinking that it might be better to use django rather than just plain python.</p>
<p>There's one problem: I have at least 20 models and each will have many functions. Quite simply it's g... | 34 | 2009-05-13T17:06:36Z | 859,222 | <p>This is a pretty common need... I can't imagine wading through a models.py file that's 10,000 lines long :-)</p>
<p>You can split up the <code>models.py</code> file (and views.py too) into a pacakge. In this case, your project tree will look like:</p>
<pre><code>/my_proj
/myapp
/models
__in... | 64 | 2009-05-13T17:10:40Z | [
"python",
"django",
"django-models"
] |
About 20 models in 1 django app | 859,192 | <p>I have started work on a local app for myself that runs through the browser. Having recently gone through the django tutorial I'm thinking that it might be better to use django rather than just plain python.</p>
<p>There's one problem: I have at least 20 models and each will have many functions. Quite simply it's g... | 34 | 2009-05-13T17:06:36Z | 859,436 | <blockquote>
<p>The models are all related so I cant's
simply make them into separate apps
can I?</p>
</blockquote>
<p>You <strong>can</strong> separate them into separate apps. To use a model in one app from another app you just import it in the same way you would import django.contrib apps.</p>
| 15 | 2009-05-13T17:58:37Z | [
"python",
"django",
"django-models"
] |
About 20 models in 1 django app | 859,192 | <p>I have started work on a local app for myself that runs through the browser. Having recently gone through the django tutorial I'm thinking that it might be better to use django rather than just plain python.</p>
<p>There's one problem: I have at least 20 models and each will have many functions. Quite simply it's g... | 34 | 2009-05-13T17:06:36Z | 859,442 | <p>"I have at least 20 models" -- this is probably more than one Django "app" and is more like a Django "project" with several small "apps"</p>
<p>I like to partition things around topics or subject areas that have a few (1 to 5) models. This becomes a Django "app" -- and is the useful unit of reusability.</p>
<p>Th... | 29 | 2009-05-13T18:00:12Z | [
"python",
"django",
"django-models"
] |
About 20 models in 1 django app | 859,192 | <p>I have started work on a local app for myself that runs through the browser. Having recently gone through the django tutorial I'm thinking that it might be better to use django rather than just plain python.</p>
<p>There's one problem: I have at least 20 models and each will have many functions. Quite simply it's g... | 34 | 2009-05-13T17:06:36Z | 2,061,853 | <p>Having 20 models in one app might be a sign that you should break it up in smaller ones.</p>
<p>The purpose of a Django app is to have a small single-purpose piece of code, that fits nicelly together.</p>
<p>So, if you had a e-commerce site, you might have a shopping_cart app, a billing app, and so on. </p>
<p>Ke... | 5 | 2010-01-14T02:47:14Z | [
"python",
"django",
"django-models"
] |
Getting pdb-style caller information in python | 859,280 | <p>Let's say I have the following method (in a class or a module, I don't think it matters):</p>
<pre><code>def someMethod():
pass
</code></pre>
<p>I'd like to access the caller's state at the time this method is called.</p>
<p><code>traceback.extract_stack</code> just gives me some strings about the call stack.... | 1 | 2009-05-13T17:25:11Z | 859,505 | <p>I figured it out:</p>
<pre><code>import inspect
def callMe():
tag = ''
frame = inspect.currentframe()
try:
tag = frame.f_back.f_locals['self']._tag
finally:
del frame
return tag
</code></pre>
| 1 | 2009-05-13T18:13:30Z | [
"python",
"stack",
"pdb"
] |
Getting the template name in django template | 859,319 | <p>For debugging purposes, I would like to have a variable in all my templates holding the path of the template being rendered. For example, if a view renders templates/account/logout.html I would like {{ template_name }} to contain the string templates/account/logout.html.</p>
<p>I don't want to go and change any vi... | 4 | 2009-05-13T17:34:35Z | 859,951 | <p>Templates are just strings not file names. Probably your best option is to monkey patch <code>render_to_response</code> and/or <code>direct_to_template</code> and copy the filename arg into the context.</p>
| 1 | 2009-05-13T19:32:32Z | [
"python",
"django"
] |
Getting the template name in django template | 859,319 | <p>For debugging purposes, I would like to have a variable in all my templates holding the path of the template being rendered. For example, if a view renders templates/account/logout.html I would like {{ template_name }} to contain the string templates/account/logout.html.</p>
<p>I don't want to go and change any vi... | 4 | 2009-05-13T17:34:35Z | 860,260 | <p><strong>The easy way:</strong></p>
<p>Download and use the <a href="http://github.com/robhudson/django-debug-toolbar/tree/master">django debug toolbar</a>. You'll get an approximation of what you're after and a bunch more.</p>
<p><strong>The less easy way:</strong></p>
<p>Replace <code>Template.render</code> wit... | 8 | 2009-05-13T20:34:22Z | [
"python",
"django"
] |
How do I GROUP BY on every given increment of a field value? | 859,489 | <p>I have a Python application. It has an SQLite database, full of data about things that happen, retrieved by a Web scraper from the Web. This data includes time-date groups, as Unix timestamps, in a column reserved for them. I want to retrieve the names of organisations that did things and count how often they did th... | 1 | 2009-05-13T18:10:20Z | 859,601 | <p>Create a table listing all weeks since the epoch, and <code>JOIN</code> it to your table of events.</p>
<pre><code>CREATE TABLE Weeks (
week INTEGER PRIMARY KEY
);
INSERT INTO Weeks (week) VALUES (200919); -- e.g. this week
SELECT w.week, e.org, COUNT(*)
FROM Events e JOIN Weeks w ON (w.week = strftime('%Y%W', ... | 1 | 2009-05-13T18:30:03Z | [
"python",
"sql",
"sqlite",
"iteration",
"increment"
] |
How do I GROUP BY on every given increment of a field value? | 859,489 | <p>I have a Python application. It has an SQLite database, full of data about things that happen, retrieved by a Web scraper from the Web. This data includes time-date groups, as Unix timestamps, in a column reserved for them. I want to retrieve the names of organisations that did things and count how often they did th... | 1 | 2009-05-13T18:10:20Z | 859,643 | <p>To do this in a set-based manner (which is what SQL is good at) you will need a set-based representation of your time increments. That can be a temporary table, a permanent table, or a derived table (i.e. subquery). I'm not too familiar with SQLite and it's been awhile since I've worked with UNIX. Timestamps in UNIX... | 1 | 2009-05-13T18:36:16Z | [
"python",
"sql",
"sqlite",
"iteration",
"increment"
] |
How do I GROUP BY on every given increment of a field value? | 859,489 | <p>I have a Python application. It has an SQLite database, full of data about things that happen, retrieved by a Web scraper from the Web. This data includes time-date groups, as Unix timestamps, in a column reserved for them. I want to retrieve the names of organisations that did things and count how often they did th... | 1 | 2009-05-13T18:10:20Z | 860,174 | <p>Not being familiar with SQLite I think this approach should work for most databases, as it finds the weeknumber and subtracts the offset </p>
<pre><code>SELECT org, ROUND(time/604800) - week_offset, COUNT(*)
FROM table
GROUP BY org, ROUND(time/604800) - week_offset
</code></pre>
<p>In Oracle I would use the follow... | 1 | 2009-05-13T20:14:00Z | [
"python",
"sql",
"sqlite",
"iteration",
"increment"
] |
Can't find my PYTHONPATH | 859,594 | <p>I'm trying to change my PYTHONPATH. I've tried to change it in "My Computer" etc, but it doesn't exist there. I searched in the registry in some places, and even ran a whole search for the word 'PYTHONPATH', but to no avail.</p>
<p>However, it Python I can easily see it exists. So where is it?</p>
| 9 | 2009-05-13T18:28:59Z | 859,611 | <p>Python does some stuff up front when it is started, probably also setting that path in windows. Just set it and see, if it is changed in <code>sys.path</code>. </p>
<p><a href="http://docs.python.org/using/windows.html#excursus-setting-environment-variables">Setting environment variables</a> in the Python docs say:... | 6 | 2009-05-13T18:32:29Z | [
"python",
"windows",
"path"
] |
Can't find my PYTHONPATH | 859,594 | <p>I'm trying to change my PYTHONPATH. I've tried to change it in "My Computer" etc, but it doesn't exist there. I searched in the registry in some places, and even ran a whole search for the word 'PYTHONPATH', but to no avail.</p>
<p>However, it Python I can easily see it exists. So where is it?</p>
| 9 | 2009-05-13T18:28:59Z | 859,613 | <p>At runtime, you can change it with:</p>
<pre><code>import sys
sys.path.append('...')
</code></pre>
<p>In My Computer, right-click Properties (or press Win-Break), System tab, Environment Variables, System. You can add it if it's not already there.</p>
<p>Finally, in the CMD prompt:</p>
<pre><code>set PYTHONPATH ... | 11 | 2009-05-13T18:32:31Z | [
"python",
"windows",
"path"
] |
Can't find my PYTHONPATH | 859,594 | <p>I'm trying to change my PYTHONPATH. I've tried to change it in "My Computer" etc, but it doesn't exist there. I searched in the registry in some places, and even ran a whole search for the word 'PYTHONPATH', but to no avail.</p>
<p>However, it Python I can easily see it exists. So where is it?</p>
| 9 | 2009-05-13T18:28:59Z | 859,614 | <p>You can add it under "My Computer" if it doesn't exist. PYTHONPATH just adds to the default sys.path.</p>
<p>On unix/linux/osx you can:</p>
<pre><code>$ export PYTHONPATH=/to/my/python/libs
</code></pre>
<p>You can also use .pth files to point to libraries:</p>
<p><a href="http://docs.python.org/library/site.ht... | 5 | 2009-05-13T18:32:41Z | [
"python",
"windows",
"path"
] |
Can't find my PYTHONPATH | 859,594 | <p>I'm trying to change my PYTHONPATH. I've tried to change it in "My Computer" etc, but it doesn't exist there. I searched in the registry in some places, and even ran a whole search for the word 'PYTHONPATH', but to no avail.</p>
<p>However, it Python I can easily see it exists. So where is it?</p>
| 9 | 2009-05-13T18:28:59Z | 859,615 | <p>What's it set to? Have you tried creating a PYTHONPATH environment variable?</p>
| 0 | 2009-05-13T18:32:45Z | [
"python",
"windows",
"path"
] |
Can't find my PYTHONPATH | 859,594 | <p>I'm trying to change my PYTHONPATH. I've tried to change it in "My Computer" etc, but it doesn't exist there. I searched in the registry in some places, and even ran a whole search for the word 'PYTHONPATH', but to no avail.</p>
<p>However, it Python I can easily see it exists. So where is it?</p>
| 9 | 2009-05-13T18:28:59Z | 859,618 | <p>You need modify your environment variables. How to do this depends on which version of Windows you have.</p>
<p>If the PYTHONPATH variable doesn't exist, you have to create it. It might not exist if you haven't already created it.</p>
| 0 | 2009-05-13T18:33:19Z | [
"python",
"windows",
"path"
] |
Can't find my PYTHONPATH | 859,594 | <p>I'm trying to change my PYTHONPATH. I've tried to change it in "My Computer" etc, but it doesn't exist there. I searched in the registry in some places, and even ran a whole search for the word 'PYTHONPATH', but to no avail.</p>
<p>However, it Python I can easily see it exists. So where is it?</p>
| 9 | 2009-05-13T18:28:59Z | 859,672 | <p>Here's how I solved it.</p>
<p>First, get the current path. There's a lot more there than I expected.</p>
<pre><code>import sys
print ';'.join(sys.path)
</code></pre>
<p>Copy that result to the clipboard. Go to My Computer and create the new environment variable PYTHONPATH, and for the value paste from the clipbo... | 2 | 2009-05-13T18:41:04Z | [
"python",
"windows",
"path"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.