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 |
|---|---|---|---|---|---|---|---|---|---|
How to get lxml working under IronPython? | 1,200,726 | <p>I need to port some code that relies heavily on lxml from a CPython application to IronPython.</p>
<p>lxml is very Pythonic and I would like to keep using it under IronPython, but it depends on libxslt and libxml2, which are C extensions.</p>
<p>Does anyone know of a workaround to allow lxml under IronPython or a version of lxml that doesn't have those C-extension dependencies?</p>
| 6 | 2009-07-29T14:36:12Z | 1,215,474 | <p>You might check out <a href="http://www.resolversystems.com/documentation/index.php/Ironclad.html" rel="nofollow">IronClad</a>, which is an open source project intended to make C Extensions for Python available in IronPython.</p>
| 2 | 2009-08-01T00:31:50Z | [
".net",
"xml",
"ironpython",
"python",
"lxml"
] |
pylint false positive for superclass __init__ | 1,201,094 | <p>If I derive a class from ctypes.BigEndianStructure, pylint warns if I don't call BigEndianStructure.<strong>init</strong> (). Great, but if I fix my code, pylint still warns:</p>
<pre><code>import ctypes
class Foo(ctypes.BigEndianStructure):
def __init__(self):
ctypes.BigEndianStructure.__init__(self)
$ pylint mymodule.py
C: 1: Missing docstring
C: 3:Foo: Missing docstring
W: 4:Foo.__init__: __init__ method from base class 'Structure' is not called
W: 4:Foo.__init__: __init__ method from base class 'BigEndianStructure' is not called
R: 3:Foo: Too few public methods (0/2)
</code></pre>
<p>At first I thought this was because Structure comes from a C module. I don't get the warning if I subclass from one of my classes or, say, SocketServer.BaseServer which is pure python. But I also don't get the warning if I subclass from smbus.SMBus, which is in a C module.</p>
<p>Anyone know of a workaround other than disabling W0231?</p>
| 0 | 2009-07-29T15:25:52Z | 1,201,213 | <p>Try using the new-style <code>super</code> calls:</p>
<pre><code>class Foo(ctypes.BigEndianStructure):
def __init__(self):
super(Foo, self).__init__()
</code></pre>
| 4 | 2009-07-29T15:44:55Z | [
"python",
"pylint"
] |
Importing files in Python from __init__.py | 1,201,115 | <p>Suppose I have the following structure:</p>
<pre><code>app/
__init__.py
foo/
a.py
b.py
c.py
__init__.py
</code></pre>
<p>a.py, b.py and c.py share some common imports (logging, os, re, etc). Is it possible to import these three or four common modules from the <code>__init__.py</code> file so I don't have to import them in every one of the files?</p>
<p>Edit: My goal is to avoid having to import 5-6 modules in each file and it's not related to performance reasons.</p>
| 11 | 2009-07-29T15:29:26Z | 1,201,151 | <p>No, they have to be put in each module's namespace, so you have to import them somehow (unless you pass <code>logging</code> around as a function argument, which would be a weird way to do things, to say the least).</p>
<p>But the modules are only imported once anyway (and then put into the <code>a</code>, <code>b</code>, and <code>c</code> namespaces), so don't worry about using too much memory or something like that.</p>
<p>You can of course put them into a separate module and import <em>that</em> into each <code>a</code>, <code>b</code>, and <code>c</code>, but this separate module would still have to be imported everytime.</p>
| 11 | 2009-07-29T15:33:20Z | [
"python",
"import",
"module"
] |
Importing files in Python from __init__.py | 1,201,115 | <p>Suppose I have the following structure:</p>
<pre><code>app/
__init__.py
foo/
a.py
b.py
c.py
__init__.py
</code></pre>
<p>a.py, b.py and c.py share some common imports (logging, os, re, etc). Is it possible to import these three or four common modules from the <code>__init__.py</code> file so I don't have to import them in every one of the files?</p>
<p>Edit: My goal is to avoid having to import 5-6 modules in each file and it's not related to performance reasons.</p>
| 11 | 2009-07-29T15:29:26Z | 1,201,177 | <p>You can do this using a common file such as <code>include.py</code>, but it goes against recommended practices because it involves a wildcard import. Consider the following files:</p>
<pre><code>app/
__init__.py
foo/
a.py
b.py
c.py
include.py <- put the includes here.
__init__.py
</code></pre>
<p>Now, in <code>a.py</code>, etc., do:</p>
<pre><code>from include import *
</code></pre>
<p>As stated above, it's not recommended because wildcard-imports are discouraged.</p>
| 13 | 2009-07-29T15:38:32Z | [
"python",
"import",
"module"
] |
Importing files in Python from __init__.py | 1,201,115 | <p>Suppose I have the following structure:</p>
<pre><code>app/
__init__.py
foo/
a.py
b.py
c.py
__init__.py
</code></pre>
<p>a.py, b.py and c.py share some common imports (logging, os, re, etc). Is it possible to import these three or four common modules from the <code>__init__.py</code> file so I don't have to import them in every one of the files?</p>
<p>Edit: My goal is to avoid having to import 5-6 modules in each file and it's not related to performance reasons.</p>
| 11 | 2009-07-29T15:29:26Z | 1,201,244 | <p>Yes, but <strong>don't do it</strong>. Seriously, don't. But if you still want to know how to do it, it'd look like this:</p>
<pre><code>import __init__
re = __init__.re
logging = __init__.logging
os = __init__.os
</code></pre>
<p>I say not to do it not only because it's messy and pointless, but also because your package isn't really supposed to use <code>__init__.py</code> like that. It's package initialization code.</p>
| 6 | 2009-07-29T15:51:04Z | [
"python",
"import",
"module"
] |
Check if an element exists | 1,201,381 | <p>I'm trying to find out if an Element in a Django model exists. I think that should be very easy to do, but couldn't find any elegant way in the <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/" rel="nofollow">Making queries</a> section of the Django documentation.</p>
<p>The problem I have is that I've thousands of screenshots in a directory and need to check if they are in the database that is supposed to store them. So I'm iterating over the filenames and want to see for each of them if a corresponding element exists. Having a model called Screenshot, the only way I could come up with is</p>
<pre><code>filenames = os.listdir(settings.SCREENSHOTS_ON_DISC)
for filename in filenames:
exists = Screenshot.objects.filter(filename=filename)
if exists:
...
</code></pre>
<p>Is there a nicer/ faster way to do this? Note that a screenshot can be in the database more than once (thus I didn't use .get).</p>
| 0 | 2009-07-29T16:12:10Z | 1,201,455 | <p>You could try:</p>
<pre><code>Screenshot.objects.filter(filename__in = filenames)
</code></pre>
<p>That will give you a list of all the screenshots you do have. You could compare the two lists and see what doesnt exist between the two. That should get you started, but you might want to tweak the query for performance/use.</p>
| 1 | 2009-07-29T16:25:09Z | [
"python",
"django",
"performance"
] |
Check if an element exists | 1,201,381 | <p>I'm trying to find out if an Element in a Django model exists. I think that should be very easy to do, but couldn't find any elegant way in the <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/" rel="nofollow">Making queries</a> section of the Django documentation.</p>
<p>The problem I have is that I've thousands of screenshots in a directory and need to check if they are in the database that is supposed to store them. So I'm iterating over the filenames and want to see for each of them if a corresponding element exists. Having a model called Screenshot, the only way I could come up with is</p>
<pre><code>filenames = os.listdir(settings.SCREENSHOTS_ON_DISC)
for filename in filenames:
exists = Screenshot.objects.filter(filename=filename)
if exists:
...
</code></pre>
<p>Is there a nicer/ faster way to do this? Note that a screenshot can be in the database more than once (thus I didn't use .get).</p>
| 0 | 2009-07-29T16:12:10Z | 1,201,456 | <p>If your <code>Screenshot</code> model has a lot of attributes, then the code you showed is doing unnecessary work for your specific need. For example, you can do something like this:</p>
<pre><code>files_in_db = Screenshot.objects.values_list('filename', flat=True).distinct()
</code></pre>
<p>which will give you a list of all filenames in the database, and generate SQL to only fetch the filenames. It won't try to create and populate Screenshot objects. If you have</p>
<pre><code>files_on_disc = os.listdir(settings.SCREENSHOTS_ON_DISC)
</code></pre>
<p>then you can iterate over one list looking for membership in the other, or make one or both lists into sets to find common members etc.</p>
| 2 | 2009-07-29T16:25:33Z | [
"python",
"django",
"performance"
] |
Check if an element exists | 1,201,381 | <p>I'm trying to find out if an Element in a Django model exists. I think that should be very easy to do, but couldn't find any elegant way in the <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/" rel="nofollow">Making queries</a> section of the Django documentation.</p>
<p>The problem I have is that I've thousands of screenshots in a directory and need to check if they are in the database that is supposed to store them. So I'm iterating over the filenames and want to see for each of them if a corresponding element exists. Having a model called Screenshot, the only way I could come up with is</p>
<pre><code>filenames = os.listdir(settings.SCREENSHOTS_ON_DISC)
for filename in filenames:
exists = Screenshot.objects.filter(filename=filename)
if exists:
...
</code></pre>
<p>Is there a nicer/ faster way to do this? Note that a screenshot can be in the database more than once (thus I didn't use .get).</p>
| 0 | 2009-07-29T16:12:10Z | 1,201,923 | <p>This query gets you all the files that are in your database and filesystem:</p>
<pre><code>discfiles = os.listdir(settings.SCREENSHOTS_ON_DISC)
filenames = (Screenshot.objects.filter(filename__in=discfiles)
.values_list('filename', flat=True)
.order_by('filename')
.distinct())
</code></pre>
<p>Note the <code>order_by</code>. If you have an ordering specified in your model definition, then using <code>distinct</code> may not return what you expect. This is documented here:</p>
<ul>
<li><a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#distinct" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/models/querysets/#distinct</a></li>
</ul>
<p>So make the ordering explicit, then execute the query.</p>
| 1 | 2009-07-29T17:46:35Z | [
"python",
"django",
"performance"
] |
Sending an exception on the SimpleXMLRPCServer | 1,201,507 | <p>I'm trying to raise an exception on the Server Side of an SimpleXMLRPCServer; however, all attempts get a "Fault 1" exception on the client side.</p>
<p>RPC_Server.AbortTest()
File "C:\Python25\lib\xmlrpclib.py", line 1147, in <strong>call</strong>
return self.<strong>send(self.__name, args)
File "C:\Python25\lib\xmlrpclib.py", line 1437, in __request
verbose=self.__verbose
File "C:\Python25\lib\xmlrpclib.py", line 1201, in request
return self._parse_response(h.getfile(), sock)
File "C:\Python25\lib\xmlrpclib.py", line 1340, in _parse_response
return u.close()
File "C:\Python25\lib\xmlrpclib.py", line 787, in close
raise Fault(</strong>self._stack[0])
xmlrpclib.Fault: :Test Aborted by a RPC
request"></p>
| 0 | 2009-07-29T16:34:21Z | 1,202,742 | <p>Yes, this is what happens when you raise an exception on the server side. Are you expecting the SimpleXMLRPCServer to return the exception to the client?</p>
<p>You can only use objects that can be marshalled through XML. This includes</p>
<ul>
<li>boolean : The True and False constants</li>
<li>integers : Pass in directly</li>
<li>floating-point numbers : Pass in directly</li>
<li>strings : Pass in directly</li>
<li>arrays : Any Python sequence type containing conformable elements. Arrays are returned as lists</li>
<li>structures : A Python dictionary. Keys must be strings, values may be any conformable type. Objects of user-defined classes can be passed in; only their <code>__dict__</code> attribute is transmitted.</li>
<li>dates : in seconds since the epoch (pass in an instance of the DateTime class) or a datetime.datetime instance.</li>
<li>binary data : pass in an instance of the Binary wrapper class</li>
</ul>
| 1 | 2009-07-29T20:11:06Z | [
"python",
"exception",
"simplexmlrpcserver"
] |
Sending an exception on the SimpleXMLRPCServer | 1,201,507 | <p>I'm trying to raise an exception on the Server Side of an SimpleXMLRPCServer; however, all attempts get a "Fault 1" exception on the client side.</p>
<p>RPC_Server.AbortTest()
File "C:\Python25\lib\xmlrpclib.py", line 1147, in <strong>call</strong>
return self.<strong>send(self.__name, args)
File "C:\Python25\lib\xmlrpclib.py", line 1437, in __request
verbose=self.__verbose
File "C:\Python25\lib\xmlrpclib.py", line 1201, in request
return self._parse_response(h.getfile(), sock)
File "C:\Python25\lib\xmlrpclib.py", line 1340, in _parse_response
return u.close()
File "C:\Python25\lib\xmlrpclib.py", line 787, in close
raise Fault(</strong>self._stack[0])
xmlrpclib.Fault: :Test Aborted by a RPC
request"></p>
| 0 | 2009-07-29T16:34:21Z | 19,157,397 | <p>If you raise an exception like this:</p>
<pre><code>raise Exception('Help!')
</code></pre>
<p>in the server the message member of the exception you get in the client will be the same as executing str() on the original exception prefixed with the string representation of the type.</p>
<p>The result I get for the message member is:</p>
<pre><code><type 'exceptions.Exception'>:Help!
</code></pre>
<p>You could certainly parse this to get the information you need.</p>
| 0 | 2013-10-03T10:57:22Z | [
"python",
"exception",
"simplexmlrpcserver"
] |
Cannot insert data into an sqlite3 database using Python | 1,201,522 | <p>I can successfully use Python to create a database and run the execute() method to create 2 new tables and specify the column names. However, I cannot insert data into the database. This is the code that I am trying to use to insert the data into the database:</p>
<pre><code>#! /usr/bin/env python
import sqlite3
companies = ('GOOG', 'AAPL', 'MSFT')
db = sqlite3.connect('data.db')
c = db.cursor()
for company in companies:
c.execute('INSERT INTO companies VALUES (?)', (company,))
</code></pre>
<p>Here is the code that I use to successfully create the database with:</p>
<pre><code>#! /usr/bin/env python
import sqlite3
db = sqlite3.connect('data.db')
db.execute('CREATE TABLE companies ' \
'( '\
'company varchar(255) '\
')')
db.execute('CREATE TABLE data ' \
'( '\
'timestamp int, '\
'company int, '\
'shares_held_by_all_insider int, '\
'shares_held_by_institutional int, '\
'float_held_by_institutional int, '\
'num_institutions int '\
')')
</code></pre>
| 4 | 2009-07-29T16:36:23Z | 1,201,577 | <p>To insert the data you don't need a cursor</p>
<p>just use the db</p>
<p>db.execute() instead of c.execute() and get rid of the c = db.cursor() line</p>
<p>Cursors aren't used to insert data, but usually to read data, or update data in place.</p>
| 3 | 2009-07-29T16:44:46Z | [
"python",
"sqlite",
"sqlite3"
] |
Cannot insert data into an sqlite3 database using Python | 1,201,522 | <p>I can successfully use Python to create a database and run the execute() method to create 2 new tables and specify the column names. However, I cannot insert data into the database. This is the code that I am trying to use to insert the data into the database:</p>
<pre><code>#! /usr/bin/env python
import sqlite3
companies = ('GOOG', 'AAPL', 'MSFT')
db = sqlite3.connect('data.db')
c = db.cursor()
for company in companies:
c.execute('INSERT INTO companies VALUES (?)', (company,))
</code></pre>
<p>Here is the code that I use to successfully create the database with:</p>
<pre><code>#! /usr/bin/env python
import sqlite3
db = sqlite3.connect('data.db')
db.execute('CREATE TABLE companies ' \
'( '\
'company varchar(255) '\
')')
db.execute('CREATE TABLE data ' \
'( '\
'timestamp int, '\
'company int, '\
'shares_held_by_all_insider int, '\
'shares_held_by_institutional int, '\
'float_held_by_institutional int, '\
'num_institutions int '\
')')
</code></pre>
| 4 | 2009-07-29T16:36:23Z | 1,201,594 | <p>Try to add</p>
<pre><code>db.commit()
</code></pre>
<p>after the inserting.</p>
| 19 | 2009-07-29T16:46:56Z | [
"python",
"sqlite",
"sqlite3"
] |
How do I link relative to a Pylons application root? | 1,201,555 | <p>In Pylons I have a mako template linking to <code>/static/resource.css</code>. How do I automatically link to <code>/pylons/static/resource.css</code> when I decide to map the application to a subdirectory on my web server?</p>
| 1 | 2009-07-29T16:41:49Z | 1,224,667 | <p>What you want are <a href="http://routes.groovie.org/manual.html#static-named-routes" rel="nofollow">static routes</a>:</p>
<pre><code>map.connect('resource', '/static/resource.css', _static=True)
</code></pre>
| 1 | 2009-08-03T21:11:21Z | [
"python",
"pylons",
"mako"
] |
How do I link relative to a Pylons application root? | 1,201,555 | <p>In Pylons I have a mako template linking to <code>/static/resource.css</code>. How do I automatically link to <code>/pylons/static/resource.css</code> when I decide to map the application to a subdirectory on my web server?</p>
| 1 | 2009-07-29T16:41:49Z | 1,331,147 | <p>If you want your static file links to be relative to your app root, wrap them like this in your templates (assuming Mako and Pylons 0.9.7):</p>
<pre><code>${url('/static/resource.css')}
</code></pre>
<p>The root path of your app will be prepended. No need to define specific routes for each file.</p>
| 2 | 2009-08-25T21:35:22Z | [
"python",
"pylons",
"mako"
] |
Java Wrapper to Perl/Python code | 1,201,628 | <p>I have to deploy some Web Services on a server that only supports the Java ones, but some of them will be done using perl or python. I want to know if is possible to develop a Java wrapper to call a specific code written in perl or python. So, I want to have all the Web Services in Java, but some of them will call some code using other languages.</p>
<p>Thanks in advance.
Regards,
Ukrania</p>
| 3 | 2009-07-29T16:53:47Z | 1,201,644 | <p>There's something I used a while back called Jython which allows you to execute Python code from Java. It was a little quirky, but I got it to do what I needed.</p>
<p><a href="http://www.jython.org" rel="nofollow">http://www.jython.org</a></p>
| 0 | 2009-07-29T16:56:53Z | [
"java",
"python",
"perl",
"web-services",
"wrapper"
] |
Java Wrapper to Perl/Python code | 1,201,628 | <p>I have to deploy some Web Services on a server that only supports the Java ones, but some of them will be done using perl or python. I want to know if is possible to develop a Java wrapper to call a specific code written in perl or python. So, I want to have all the Web Services in Java, but some of them will call some code using other languages.</p>
<p>Thanks in advance.
Regards,
Ukrania</p>
| 3 | 2009-07-29T16:53:47Z | 1,201,645 | <p>For the Python part of it you can use <a href="http://www.jython.org/" rel="nofollow">Jython</a> to run Python code right from your Java virtual machine. It'll integrate fully with your Java code as a bonus.</p>
| 3 | 2009-07-29T16:56:56Z | [
"java",
"python",
"perl",
"web-services",
"wrapper"
] |
Java Wrapper to Perl/Python code | 1,201,628 | <p>I have to deploy some Web Services on a server that only supports the Java ones, but some of them will be done using perl or python. I want to know if is possible to develop a Java wrapper to call a specific code written in perl or python. So, I want to have all the Web Services in Java, but some of them will call some code using other languages.</p>
<p>Thanks in advance.
Regards,
Ukrania</p>
| 3 | 2009-07-29T16:53:47Z | 1,201,710 | <p>For Python you can use the <a href="http://developers.sun.com/scripting/" rel="nofollow">Java Scripting API</a>.<br />
A Perl implementation is sadly still missing.</p>
| 1 | 2009-07-29T17:05:16Z | [
"java",
"python",
"perl",
"web-services",
"wrapper"
] |
Java Wrapper to Perl/Python code | 1,201,628 | <p>I have to deploy some Web Services on a server that only supports the Java ones, but some of them will be done using perl or python. I want to know if is possible to develop a Java wrapper to call a specific code written in perl or python. So, I want to have all the Web Services in Java, but some of them will call some code using other languages.</p>
<p>Thanks in advance.
Regards,
Ukrania</p>
| 3 | 2009-07-29T16:53:47Z | 1,201,722 | <p>This depends heavily upon your needs. If Jython is an option for the Python code (it isn't always 100% compatible), then it is probably the best option there. Otherwise, you will need to use Java's Process Builder to call the interpretters directly and return the results on their output stream. This will not be fast (but then again, Jython isn't that fast either, relative to regular Java code), but it is an extremely flexible solution.</p>
| 3 | 2009-07-29T17:06:23Z | [
"java",
"python",
"perl",
"web-services",
"wrapper"
] |
Java Wrapper to Perl/Python code | 1,201,628 | <p>I have to deploy some Web Services on a server that only supports the Java ones, but some of them will be done using perl or python. I want to know if is possible to develop a Java wrapper to call a specific code written in perl or python. So, I want to have all the Web Services in Java, but some of them will call some code using other languages.</p>
<p>Thanks in advance.
Regards,
Ukrania</p>
| 3 | 2009-07-29T16:53:47Z | 1,203,587 | <p>For Perl, use <a href="http://search.cpan.org/dist/Inline-Java/" rel="nofollow">Inline::Java</a>. There are several options for integrating the code; you can <a href="http://search.cpan.org/dist/Inline-Java/Java/Callback.pod" rel="nofollow">call a separate process</a> or you can use an <a href="http://search.cpan.org/dist/Inline-Java/Java/PerlInterpreter/PerlInterpreter.pod" rel="nofollow">embedded interpreter</a>.</p>
| 3 | 2009-07-29T23:09:23Z | [
"java",
"python",
"perl",
"web-services",
"wrapper"
] |
How to identify the currently available wireless networks with Python in Windows? | 1,201,749 | <p>Is there a way to get a list of wireless networks (SSID's) that are currently available? And seeing what is the current connected network? </p>
<p>Doesn't need to be exactly the SSID, I just need to identify the current wireless network.</p>
| 2 | 2009-07-29T17:10:46Z | 1,201,916 | <p>You can use the netsh command. I don't remember the exact syntax used to invoke cli commands from within python, but I'm sure it should be fairly easy to locate.</p>
<p>The article below has more information about how to use netsh itself:</p>
<p><a href="http://technet.microsoft.com/en-us/library/cc755301%28WS.10%29.aspx#bkmk_wlanShowNetworks" rel="nofollow">http://technet.microsoft.com/en-us/library/cc755301%28WS.10%29.aspx#bkmk_wlanShowNetworks</a></p>
| 2 | 2009-07-29T17:44:54Z | [
"python",
"windows",
"windows-xp",
"wireless",
"ssid"
] |
How to set proxy in Windows with Python? | 1,201,771 | <p>How can I get the current Windows' browser proxy setting, as well as set them to a value?</p>
<p>I know I can do this by looking in the registry at <code>Software\Microsoft\Windows\CurrentVersion\Internet Settings\ProxyServer</code>, but I'm looking, if it is possible, to do this without messing directly with the registry.</p>
| 1 | 2009-07-29T17:14:20Z | 1,201,789 | <p>If the code you are using uses <code>urlopen</code> under the hood you an set the <code>http_proxy</code> environment variable to have it picked up.</p>
<p>See the <a href="http://docs.python.org/library/urllib.html" rel="nofollow">documentation</a> here for more info.</p>
| 0 | 2009-07-29T17:18:37Z | [
"python",
"windows",
"proxy",
"registry"
] |
How to set proxy in Windows with Python? | 1,201,771 | <p>How can I get the current Windows' browser proxy setting, as well as set them to a value?</p>
<p>I know I can do this by looking in the registry at <code>Software\Microsoft\Windows\CurrentVersion\Internet Settings\ProxyServer</code>, but I'm looking, if it is possible, to do this without messing directly with the registry.</p>
| 1 | 2009-07-29T17:14:20Z | 1,205,881 | <p>urllib module automatically retrieves settings from registry when no proxies are specified as a parameter or in the environment variables</p>
<blockquote>
<p>In a Windows environment, if no proxy
environment variables are set, proxy
settings are obtained from the
registryâs Internet Settings section.</p>
</blockquote>
<p>See the documentation of urllib module referenced in the earlier post.</p>
<p>To set the proxy I assume you'll need to use the pywin32 module and modify the registry directly.</p>
| 3 | 2009-07-30T11:02:16Z | [
"python",
"windows",
"proxy",
"registry"
] |
How to set proxy in Windows with Python? | 1,201,771 | <p>How can I get the current Windows' browser proxy setting, as well as set them to a value?</p>
<p>I know I can do this by looking in the registry at <code>Software\Microsoft\Windows\CurrentVersion\Internet Settings\ProxyServer</code>, but I'm looking, if it is possible, to do this without messing directly with the registry.</p>
| 1 | 2009-07-29T17:14:20Z | 9,039,001 | <p>You can use WinHttpGetIEProxyConfigForCurrentUser as stated in <a href="http://stackoverflow.com/questions/202547/how-do-i-find-out-the-browsers-proxy-settings">this SO question</a></p>
<p>There's <a href="http://stackoverflow.com/questions/1025029/how-to-use-win32-apis-with-python">another SO question</a> with examples of <a href="http://sourceforge.net/projects/pywin32/" rel="nofollow">PyWin32</a>, the Python for Windows extensions.</p>
| 0 | 2012-01-27T19:34:46Z | [
"python",
"windows",
"proxy",
"registry"
] |
Django and File Permissions: Best Practices? | 1,201,785 | <p>I am integrating "legacy" code with Django, and have problems when the process executing Django must write to legacy code directories where it lacks write permissions. (The legacy code is a Python backend to a Tkinter GUI, which I'm repurposing to a browser-based UI.)</p>
<p>I could:</p>
<ul>
<li>Make the legacy directory writeable
to all, but this seems like bad
practice.</li>
<li>Find the userid of the Django
execution process, assign that to a
group and give that group write
permissions to the whole legacy
directory. (I suspect this is the
user running apache.) This too seems
bad -- if that user is
compromised,the whole directory is at
risk.</li>
<li>Isolate the "write" calls in the
code, ensure they all go somewhere in
a designated subdirectory tree, and
make that tree world (or Django user
group) writeable. This seems the
least risky, but also the most work.</li>
</ul>
<p>Any other ideas? Am I missing some obvious fix? I'm completely new to this.</p>
| 0 | 2009-07-29T17:17:18Z | 1,201,895 | <p>I'd go with option number 2. I don't think your django user is any more likely to get compromised than your Tkinter user. If there's something else under apache that you're worried about, run it under a separate apache with the right user.</p>
| 0 | 2009-07-29T17:39:53Z | [
"python",
"django"
] |
Adding a field to a structured numpy array | 1,201,817 | <p>What is the cleanest way to add a field to a structured numpy array? Can it be done destructively, or is it necessary to create a new array and copy over the existing fields? Are the contents of each field stored contiguously in memory so that such copying can be done efficiently?</p>
| 18 | 2009-07-29T17:24:12Z | 1,201,821 | <pre><code>import numpy
def add_field(a, descr):
"""Return a new array that is like "a", but has additional fields.
Arguments:
a -- a structured numpy array
descr -- a numpy type description of the new fields
The contents of "a" are copied over to the appropriate fields in
the new array, whereas the new fields are uninitialized. The
arguments are not modified.
>>> sa = numpy.array([(1, 'Foo'), (2, 'Bar')], \
dtype=[('id', int), ('name', 'S3')])
>>> sa.dtype.descr == numpy.dtype([('id', int), ('name', 'S3')])
True
>>> sb = add_field(sa, [('score', float)])
>>> sb.dtype.descr == numpy.dtype([('id', int), ('name', 'S3'), \
('score', float)])
True
>>> numpy.all(sa['id'] == sb['id'])
True
>>> numpy.all(sa['name'] == sb['name'])
True
"""
if a.dtype.fields is None:
raise ValueError, "`A' must be a structured numpy array"
b = numpy.empty(a.shape, dtype=a.dtype.descr + descr)
for name in a.dtype.names:
b[name] = a[name]
return b
</code></pre>
| 4 | 2009-07-29T17:25:29Z | [
"python",
"numpy"
] |
Adding a field to a structured numpy array | 1,201,817 | <p>What is the cleanest way to add a field to a structured numpy array? Can it be done destructively, or is it necessary to create a new array and copy over the existing fields? Are the contents of each field stored contiguously in memory so that such copying can be done efficiently?</p>
| 18 | 2009-07-29T17:24:12Z | 1,208,039 | <p>If you're using numpy 1.3, there's also numpy.lib.recfunctions.append_fields(). </p>
<p>For many installations, you'll need to <code>import numpy.lib.recfunctions</code> to access this. <code>import numpy</code> will not allow one to see the <code>numpy.lib.recfunctions</code></p>
| 16 | 2009-07-30T17:18:58Z | [
"python",
"numpy"
] |
wxPython: Handling events in a widget that is inside a notebook | 1,201,979 | <p>I have a wxPython notebook, in this case a <code>wx.aui.AuiNotebook</code>. (but this problem has happened with other kinds of notebooks as well.) In my notebook I have a widget, in this case a subclass of <code>ScrolledPanel</code>, for which I am trying to do some custom event handling (for <code>wx.EVT_KEY_DOWN</code>). However, the events are not being handled. I checked my code outside of the notebook, and the event handling works, but when I put my widget in the notebook, the event handler doesn't seem to get invoked when the event happens.</p>
<p>Does the notebook somehow block the event? How do I solve this?</p>
| 2 | 2009-07-29T17:58:41Z | 1,203,996 | <p>I tried reproducing your problem but it worked fine for me. The only thing I can think of is that there is one of your classes that also binds to <code>wx.EVT_KEY_DOWN</code> and doesn't call <a href="http://www.wxpython.org/docs/api/wx.Event-class.html#Skip" rel="nofollow">wx.Event.Skip()</a> in its callback. That would prevent further handling of the event. If your scrolled panel happens to be downstream of such an object in the sequence of event handlers it will never see the event.</p>
<p>For reference, here's an example that worked for me (on Windows). Is what you're doing much different than this?</p>
<pre><code>import wx
import wx.aui, wx.lib.scrolledpanel
class AppFrame(wx.Frame):
def __init__(self, *args, **kwds):
wx.Frame.__init__(self, *args, **kwds)
# The notebook
self.nb = wx.aui.AuiNotebook(self)
# Create a scrolled panel
panel = wx.lib.scrolledpanel.ScrolledPanel(self, -1)
panel.SetupScrolling()
self.add_panel(panel, 'Scrolled Panel')
# Create a normal panel
panel = wx.Panel(self, -1)
self.add_panel(panel, 'Simple Panel')
# Set the notebook on the frame
self.sizer = wx.BoxSizer()
self.sizer.Add(self.nb, 1, wx.EXPAND)
self.SetSizer(self.sizer)
# Status bar to display the key code of what was typed
self.sb = self.CreateStatusBar()
def add_panel(self, panel, name):
panel.Bind(wx.EVT_KEY_DOWN, self.on_key)
self.nb.AddPage(panel, name)
def on_key(self, event):
self.sb.SetStatusText("key: %d [%d]" % (event.GetKeyCode(), event.GetTimestamp()))
event.Skip()
class TestApp(wx.App):
def OnInit(self):
frame = AppFrame(None, -1, 'Click on a panel and hit a key')
frame.Show()
self.SetTopWindow(frame)
return 1
if __name__ == "__main__":
app = TestApp(0)
app.MainLoop()
</code></pre>
| 2 | 2009-07-30T01:21:58Z | [
"python",
"user-interface",
"event-handling",
"wxpython"
] |
OpenSocial Win32 compatibility | 1,202,086 | <p>I am planning to develop an application in Python on the Win32 platform. Does the <a href="http://en.wikipedia.org/wiki/OpenSocial" rel="nofollow">OpenSocial</a> API work upon the Win32 platform as well?</p>
<p>To make things more clear, I need to use information from the OpenSocial API to conduct certain things in the application.</p>
| 0 | 2009-07-29T18:16:52Z | 1,202,124 | <p>Yes the general idea of an API is it uses a standard language like XML or JSON or whatever. You can easily find libraries that read/write those formats in most languages, no matter the platform. If you're lucky someone will have written a library for the specific API you need.</p>
<p>Which in this case, they have :)
<a href="http://code.google.com/p/opensocial-python-client/" rel="nofollow">http://code.google.com/p/opensocial-python-client/</a></p>
<p>Hope that helps!</p>
| 1 | 2009-07-29T18:23:40Z | [
"python",
"opensocial"
] |
Sorting a list of dictionaries of objects by dictionary values | 1,202,088 | <p>This is related to the various other questions about sorting values of dictionaries that I have read here, but I have not found the answer. I'm a newbie and maybe I just didn't see the answer as it concerns my problem.</p>
<p>I have this function, which I'm using as a Django custom filter to sort results from a list of dictionaries. Actually, the main part of this function was answered in a related question on stackoverflow.</p>
<pre><code>def multikeysorting(dict_list, sortkeys):
from operator import itemgetter
def multikeysort(items, columns):
comparers = [ ((itemgetter(col[1:]), -1) if col.startswith('-') else (itemgetter(col), 1)) for col in columns]
def sign(a, b):
if a < b: return -1
elif a > b: return 1
else: return 0
def comparer(left,right):
for fn, mult in comparers:
result = sign(fn(left), fn(right))
if result:
return mult * result
else:
return 0
return sorted(items, cmp=comparer)
keys_list = sortkeys.split(",")
return multikeysort(dict_list, keys_list)
</code></pre>
<p>This filter is called as follows in Django:</p>
<pre><code>{% for item in stats|statleaders_has_stat:"TOT_PTS_Misc"|multikeysorting:"-TOT_PTS_Misc.value,TOT_PTS_Misc.player.last_name" %}
</code></pre>
<p>This means that there are two dictionary values passed to the function to sort the list of dictionaries. The sort works with the dictionary keys, but not the values.</p>
<p>How can I sort the and return the dictionary by sorting the list of dictionaries with more than one value? In the example above, first by the value, then by the last_name.</p>
<p>Here is an example of the data:
<pre>
[{u'TOT_PTS_Misc': < StatisticPlayerRollup: DeWitt, Ash Total Points : 6.0>, 'player': < Player: DeWitt, Ash>},
{u'TOT_PTS_Misc': < StatisticPlayerRollup: Ackerman, Luke Total Points : 18.0>, 'player': < Player: Ackerman, Luke>},
{u'TOT_PTS_Misc': < StatisticPlayerRollup: Wise, Dan Total Points : 19.0>, 'player': < Player: Wise, Dan>},
{u'TOT_PTS_Misc': < StatisticPlayerRollup: Allison, Mike Total Points : 18.0>, 'player': < Player: Allison, Mike>},
{u'TOT_PTS_Misc': < StatisticPlayerRollup: Wolford, Alex Total Points : 18.0>, 'player': < Player: Wolford, Alex>},
{u'TOT_PTS_Misc': < StatisticPlayerRollup: Okes, Joe Total Points : 18.0>, 'player': < Player: Okes, Joe>},
{u'TOT_PTS_Misc': < StatisticPlayerRollup: Grattan, Paul Total Points : 18.0>, 'player': < Player: Grattan, Paul>}]
</pre></p>
<p>The listing should be sorted as follows:</p>
<pre>
LastName Points
Wise 19.0
Ackerman 18.0
Allison 18.0
Grattan 18.0
Okes 18.0
Wolford 18.0
Hagg 6.0
DeWitt 6.0
</pre>
<p>The TOT_PTS_Misc is an object that contains the player name as well as the number of points. (I hope I am explaining this correct.)</p>
<p>But, there should be an arbitrary sort of values, either ascending or descending. Not always that same values and possibly more than two.</p>
<p><hr /></p>
<p>So I came up with this solution, but wanted to know if it makes sense and if there is anything that should be changed.</p>
<pre>
def multikeysorting(dict_list, sortkeys):
from operator import itemgetter, attrgetter
klist = sortkeys.split(",")
vlist = []
for i in klist:
vlist.append(tuple(i.split(".")))
def getkeyvalue(val_list):
result = []
for id,val in enumerate(val_list):
if val[0].startswith('-'):
if len(val) == 2:
result.append((itemgetter(val[0][1:]).attrgetter(val[1]), -1))
else:
att = val[1]
for j in val[2:]:
att = att + "." + j
result.append((itemgetter(val[0][1:]).attrgetter(att), -1))
else:
if len(val) == 2:
result.append((itemgetter(val[0]).attrgetter(val[1]), 1))
else:
att = val[1]
for j in val[2:]:
att = att + "." + j
result.append((itemgetter(val[0]).attrgetter(att), 1))
return result
return sorted(dict_list, key=getkeyvalue(vlist))
</pre>
| 2 | 2009-07-29T18:17:25Z | 1,202,438 | <p>As far as I can see, there are two things you need to do.</p>
<p>First, parse the call path out of the sort key, that is: turn <code>'TOT_PTS_Misc.value'</code> to <code>('TOT_PTS_Misc','value')</code>
Second, use attrgetter in a similar way to the use of itemgetter, for the callable part.</p>
<p>If i'm not mistaken, <code>itemgetter('TOT_PTS_Misc').attrgetter('value')</code> SHOULD be equal to <code>dict['TOT_PTS_Misc'].value</code></p>
| 0 | 2009-07-29T19:15:03Z | [
"python",
"django"
] |
Sorting a list of dictionaries of objects by dictionary values | 1,202,088 | <p>This is related to the various other questions about sorting values of dictionaries that I have read here, but I have not found the answer. I'm a newbie and maybe I just didn't see the answer as it concerns my problem.</p>
<p>I have this function, which I'm using as a Django custom filter to sort results from a list of dictionaries. Actually, the main part of this function was answered in a related question on stackoverflow.</p>
<pre><code>def multikeysorting(dict_list, sortkeys):
from operator import itemgetter
def multikeysort(items, columns):
comparers = [ ((itemgetter(col[1:]), -1) if col.startswith('-') else (itemgetter(col), 1)) for col in columns]
def sign(a, b):
if a < b: return -1
elif a > b: return 1
else: return 0
def comparer(left,right):
for fn, mult in comparers:
result = sign(fn(left), fn(right))
if result:
return mult * result
else:
return 0
return sorted(items, cmp=comparer)
keys_list = sortkeys.split(",")
return multikeysort(dict_list, keys_list)
</code></pre>
<p>This filter is called as follows in Django:</p>
<pre><code>{% for item in stats|statleaders_has_stat:"TOT_PTS_Misc"|multikeysorting:"-TOT_PTS_Misc.value,TOT_PTS_Misc.player.last_name" %}
</code></pre>
<p>This means that there are two dictionary values passed to the function to sort the list of dictionaries. The sort works with the dictionary keys, but not the values.</p>
<p>How can I sort the and return the dictionary by sorting the list of dictionaries with more than one value? In the example above, first by the value, then by the last_name.</p>
<p>Here is an example of the data:
<pre>
[{u'TOT_PTS_Misc': < StatisticPlayerRollup: DeWitt, Ash Total Points : 6.0>, 'player': < Player: DeWitt, Ash>},
{u'TOT_PTS_Misc': < StatisticPlayerRollup: Ackerman, Luke Total Points : 18.0>, 'player': < Player: Ackerman, Luke>},
{u'TOT_PTS_Misc': < StatisticPlayerRollup: Wise, Dan Total Points : 19.0>, 'player': < Player: Wise, Dan>},
{u'TOT_PTS_Misc': < StatisticPlayerRollup: Allison, Mike Total Points : 18.0>, 'player': < Player: Allison, Mike>},
{u'TOT_PTS_Misc': < StatisticPlayerRollup: Wolford, Alex Total Points : 18.0>, 'player': < Player: Wolford, Alex>},
{u'TOT_PTS_Misc': < StatisticPlayerRollup: Okes, Joe Total Points : 18.0>, 'player': < Player: Okes, Joe>},
{u'TOT_PTS_Misc': < StatisticPlayerRollup: Grattan, Paul Total Points : 18.0>, 'player': < Player: Grattan, Paul>}]
</pre></p>
<p>The listing should be sorted as follows:</p>
<pre>
LastName Points
Wise 19.0
Ackerman 18.0
Allison 18.0
Grattan 18.0
Okes 18.0
Wolford 18.0
Hagg 6.0
DeWitt 6.0
</pre>
<p>The TOT_PTS_Misc is an object that contains the player name as well as the number of points. (I hope I am explaining this correct.)</p>
<p>But, there should be an arbitrary sort of values, either ascending or descending. Not always that same values and possibly more than two.</p>
<p><hr /></p>
<p>So I came up with this solution, but wanted to know if it makes sense and if there is anything that should be changed.</p>
<pre>
def multikeysorting(dict_list, sortkeys):
from operator import itemgetter, attrgetter
klist = sortkeys.split(",")
vlist = []
for i in klist:
vlist.append(tuple(i.split(".")))
def getkeyvalue(val_list):
result = []
for id,val in enumerate(val_list):
if val[0].startswith('-'):
if len(val) == 2:
result.append((itemgetter(val[0][1:]).attrgetter(val[1]), -1))
else:
att = val[1]
for j in val[2:]:
att = att + "." + j
result.append((itemgetter(val[0][1:]).attrgetter(att), -1))
else:
if len(val) == 2:
result.append((itemgetter(val[0]).attrgetter(val[1]), 1))
else:
att = val[1]
for j in val[2:]:
att = att + "." + j
result.append((itemgetter(val[0]).attrgetter(att), 1))
return result
return sorted(dict_list, key=getkeyvalue(vlist))
</pre>
| 2 | 2009-07-29T18:17:25Z | 1,202,936 | <p>You gain access to the keys using <code>itemgetter</code> and to the value attributes using <code>attrgetter</code>.</p>
<p>So, once you've extracted the key, value names you're interested in, you can construct your key function:</p>
<pre><code>from operator import attrgetter, itemgetter
itmget = itemgetter('TOT_PTS_Misc')
attget_v = attrgetter('value')
attget_l = attrgetter('last_name')
def keyfunc(x):
itm = itmget(x)
return (-attget_v(itm), attget_n(itm))
sorted(dictlist, key=keyfunc)
</code></pre>
<p>This seems to work. Is it what you're asking? Or am I missing something?</p>
| 2 | 2009-07-29T20:46:41Z | [
"python",
"django"
] |
raw_input without leaving a history in readline | 1,202,127 | <p>Is there a way of using raw_input without leaving a sign in the readline history, so that it don't show when tab-completing?</p>
| 4 | 2009-07-29T18:24:10Z | 1,202,308 | <p>You could make a function something like</p>
<pre><code>import readline
def raw_input_no_history():
input = raw_input()
readline.remove_history_item(readline.get_current_history_length()-1)
return input
</code></pre>
<p>and call that function instead of raw_input. You may not need the minus 1 dependent on where you call it from.</p>
| 6 | 2009-07-29T18:53:08Z | [
"python",
"history",
"readline",
"tab-completion"
] |
random.sample return only characters instead of strings | 1,202,251 | <p>This is a kind of newbie question, but I couldn't find a solution. I read a list of strings from a file, and try to get a random, 5 element sample with random.sample, but the resultung list only contains characters. Why is that? How can I get a random sample list of strings?</p>
<p>This is what I do:</p>
<pre><code> names = random.sample( open('names.txt').read(), 5 )
print names
</code></pre>
<p>This gives a five element character list like:</p>
<pre><code>['\x91', 'h', 'l', 'n', 's']
</code></pre>
<p>If I omit the random.sample part, and print the list, it prints out every line of the file, which is the expected behaviour, and proves that the file is read OK.</p>
| 2 | 2009-07-29T18:44:26Z | 1,202,272 | <p>If the names are all on seperate lines, ry the following:</p>
<pre><code>names = random.sample(open('names.txt').readlines(), count)
print names
</code></pre>
<p>Essentially you are going wrong because you need to pass an interable to <code>random.sample()</code>. When you pass a string it treats it like a list. If you're names are all on one line, you need to use <code>split()</code> to pull them apart and pass that list to <code>random.sample()</code>.</p>
| 3 | 2009-07-29T18:47:14Z | [
"python",
"string",
"character",
"random-sample"
] |
Combinatorics Counting Puzzle: Roll 20, 8-sided dice, what is the probability of getting at least 5 dice of the same value | 1,202,343 | <p>Assume a game in which one rolls 20, 8-sided die, for a total number of 8^20 possible outcomes. To calculate the probability of a particular event occurring, we divide the number of ways that event can occur by 8^20. </p>
<p>One can calculate the number of ways to get exactly 5 dice of the value 3. (20 choose 5) gives us the number of orders of 3. 7^15 gives us the number of ways we can not get the value 3 for 15 rolls.</p>
<pre><code>number of ways to get exactly 5, 3's = (20 choose 5)*7^15.
</code></pre>
<p>The answer can also be viewed as how many ways can I rearrange the string 3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 (20 choose 5) times the total number of values we the zero's (assuming 7 legal values) 7^15 (is this correct).</p>
<ul>
<li><p>Question 1: How can I calculate the number of ways to get exactly 5 dice of the same value(That is, for all die values).
Note: if I just naively use my first answer above and multiply bt 8, I get an enormous amount of double counting?</p>
<p>I understand that I could solve for each of the cases (5 1's), (5, 2's), (5, 3's), ... (5's, 8) sum them (more simply 8*(5 1's) ). Then subtract the sum of number of overlaps (5 1's) and (5 2's), (5 1's) and (5 3's)... (5 1's) and (5, 2's) and ... and (5, 8's) but this seems exceedingly messy. I would a generalization of this in a way that scales up to large numbers of samples and large numbers of classes.</p></li>
<li><p>How can I calculate the number of ways to get <strong>at least</strong> 5 dice of the same value?</p>
<p>So 111110000000000000000 or 11110100000000000002 or 11111100000001110000 or 11011211222222223333, but not 00001111222233334444 or 000511512252363347744.</p></li>
</ul>
<p>I'm looking for answers which either explain the math or point to a library which supports this (esp python modules). Extra points for detail and examples.</p>
| 3 | 2009-07-29T18:58:43Z | 1,202,427 | <p>The exact probability distribution Fs,i of a sum of i s-sided dice can be calculated as the repeated convolution of the single-die probability distribution with itself.</p>
<p><img src="http://upload.wikimedia.org/math/b/1/4/b140f36d9f022772b54f1236c3744190.png" alt="alt text" /></p>
<p>where <img src="http://upload.wikimedia.org/math/8/1/d/81d3fe9d2b978ab1720716be72b67c4c.png" alt="alt text" /> for all <img src="http://upload.wikimedia.org/math/0/c/0/0c0c3f5f824c566d0700b0d18d0bbc72.png" alt="alt text" /> and 0 otherwise.</p>
<p><a href="http://en.wikipedia.org/wiki/Dice" rel="nofollow">http://en.wikipedia.org/wiki/Dice</a></p>
| 2 | 2009-07-29T19:12:59Z | [
"python",
"puzzle",
"combinatorics",
"discrete-mathematics",
"dice"
] |
Combinatorics Counting Puzzle: Roll 20, 8-sided dice, what is the probability of getting at least 5 dice of the same value | 1,202,343 | <p>Assume a game in which one rolls 20, 8-sided die, for a total number of 8^20 possible outcomes. To calculate the probability of a particular event occurring, we divide the number of ways that event can occur by 8^20. </p>
<p>One can calculate the number of ways to get exactly 5 dice of the value 3. (20 choose 5) gives us the number of orders of 3. 7^15 gives us the number of ways we can not get the value 3 for 15 rolls.</p>
<pre><code>number of ways to get exactly 5, 3's = (20 choose 5)*7^15.
</code></pre>
<p>The answer can also be viewed as how many ways can I rearrange the string 3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 (20 choose 5) times the total number of values we the zero's (assuming 7 legal values) 7^15 (is this correct).</p>
<ul>
<li><p>Question 1: How can I calculate the number of ways to get exactly 5 dice of the same value(That is, for all die values).
Note: if I just naively use my first answer above and multiply bt 8, I get an enormous amount of double counting?</p>
<p>I understand that I could solve for each of the cases (5 1's), (5, 2's), (5, 3's), ... (5's, 8) sum them (more simply 8*(5 1's) ). Then subtract the sum of number of overlaps (5 1's) and (5 2's), (5 1's) and (5 3's)... (5 1's) and (5, 2's) and ... and (5, 8's) but this seems exceedingly messy. I would a generalization of this in a way that scales up to large numbers of samples and large numbers of classes.</p></li>
<li><p>How can I calculate the number of ways to get <strong>at least</strong> 5 dice of the same value?</p>
<p>So 111110000000000000000 or 11110100000000000002 or 11111100000001110000 or 11011211222222223333, but not 00001111222233334444 or 000511512252363347744.</p></li>
</ul>
<p>I'm looking for answers which either explain the math or point to a library which supports this (esp python modules). Extra points for detail and examples.</p>
| 3 | 2009-07-29T18:58:43Z | 1,202,507 | <p>Recursive solution:</p>
<pre><code>Prob_same_value(n) = Prob_same_value(n-1) * (1 - Prob_noone_rolling_that_value(N-(n-1)))
</code></pre>
| 1 | 2009-07-29T19:29:02Z | [
"python",
"puzzle",
"combinatorics",
"discrete-mathematics",
"dice"
] |
Combinatorics Counting Puzzle: Roll 20, 8-sided dice, what is the probability of getting at least 5 dice of the same value | 1,202,343 | <p>Assume a game in which one rolls 20, 8-sided die, for a total number of 8^20 possible outcomes. To calculate the probability of a particular event occurring, we divide the number of ways that event can occur by 8^20. </p>
<p>One can calculate the number of ways to get exactly 5 dice of the value 3. (20 choose 5) gives us the number of orders of 3. 7^15 gives us the number of ways we can not get the value 3 for 15 rolls.</p>
<pre><code>number of ways to get exactly 5, 3's = (20 choose 5)*7^15.
</code></pre>
<p>The answer can also be viewed as how many ways can I rearrange the string 3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 (20 choose 5) times the total number of values we the zero's (assuming 7 legal values) 7^15 (is this correct).</p>
<ul>
<li><p>Question 1: How can I calculate the number of ways to get exactly 5 dice of the same value(That is, for all die values).
Note: if I just naively use my first answer above and multiply bt 8, I get an enormous amount of double counting?</p>
<p>I understand that I could solve for each of the cases (5 1's), (5, 2's), (5, 3's), ... (5's, 8) sum them (more simply 8*(5 1's) ). Then subtract the sum of number of overlaps (5 1's) and (5 2's), (5 1's) and (5 3's)... (5 1's) and (5, 2's) and ... and (5, 8's) but this seems exceedingly messy. I would a generalization of this in a way that scales up to large numbers of samples and large numbers of classes.</p></li>
<li><p>How can I calculate the number of ways to get <strong>at least</strong> 5 dice of the same value?</p>
<p>So 111110000000000000000 or 11110100000000000002 or 11111100000001110000 or 11011211222222223333, but not 00001111222233334444 or 000511512252363347744.</p></li>
</ul>
<p>I'm looking for answers which either explain the math or point to a library which supports this (esp python modules). Extra points for detail and examples.</p>
| 3 | 2009-07-29T18:58:43Z | 1,202,598 | <p>Here is what I am thinking...</p>
<p>If you just had 5 dice, you would only have eight ways to get what you want.</p>
<p>For each of those eight ways, all possible combinations of the other 15 dice work.</p>
<p>So - I think the answer is: (8 * 8**15) / 8**20</p>
<p>(The answer for at least 5 the same.)</p>
| 1 | 2009-07-29T19:44:56Z | [
"python",
"puzzle",
"combinatorics",
"discrete-mathematics",
"dice"
] |
Combinatorics Counting Puzzle: Roll 20, 8-sided dice, what is the probability of getting at least 5 dice of the same value | 1,202,343 | <p>Assume a game in which one rolls 20, 8-sided die, for a total number of 8^20 possible outcomes. To calculate the probability of a particular event occurring, we divide the number of ways that event can occur by 8^20. </p>
<p>One can calculate the number of ways to get exactly 5 dice of the value 3. (20 choose 5) gives us the number of orders of 3. 7^15 gives us the number of ways we can not get the value 3 for 15 rolls.</p>
<pre><code>number of ways to get exactly 5, 3's = (20 choose 5)*7^15.
</code></pre>
<p>The answer can also be viewed as how many ways can I rearrange the string 3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 (20 choose 5) times the total number of values we the zero's (assuming 7 legal values) 7^15 (is this correct).</p>
<ul>
<li><p>Question 1: How can I calculate the number of ways to get exactly 5 dice of the same value(That is, for all die values).
Note: if I just naively use my first answer above and multiply bt 8, I get an enormous amount of double counting?</p>
<p>I understand that I could solve for each of the cases (5 1's), (5, 2's), (5, 3's), ... (5's, 8) sum them (more simply 8*(5 1's) ). Then subtract the sum of number of overlaps (5 1's) and (5 2's), (5 1's) and (5 3's)... (5 1's) and (5, 2's) and ... and (5, 8's) but this seems exceedingly messy. I would a generalization of this in a way that scales up to large numbers of samples and large numbers of classes.</p></li>
<li><p>How can I calculate the number of ways to get <strong>at least</strong> 5 dice of the same value?</p>
<p>So 111110000000000000000 or 11110100000000000002 or 11111100000001110000 or 11011211222222223333, but not 00001111222233334444 or 000511512252363347744.</p></li>
</ul>
<p>I'm looking for answers which either explain the math or point to a library which supports this (esp python modules). Extra points for detail and examples.</p>
| 3 | 2009-07-29T18:58:43Z | 1,202,614 | <p>Double counting can be solved by use of the <a href="http://en.wikipedia.org/wiki/Inclusion-exclusion%5Fprinciple" rel="nofollow">Inclusion/Exclusion Principle</a></p>
<p>I suspect it comes out to: </p>
<pre><code>Choose(8,1)*P(one set of 5 Xs)
- Choose(8,2)*P(a set of 5 Xs and a set of 5 Ys)
+ Choose(8,3)*P(5 Xs, 5 Ys, 5 Zs)
- Choose(8,4)*P(5 Xs, 5 Ys, 5 Zs, 5 As)
P(set of 5 Xs) = 20 Choose 5 * 7^15 / 8^20
P(5 Xs, 5 Ys) = 20 Choose 5,5 * 6^10 / 8^20
</code></pre>
<p>And so on. This doesn't solve the problem directly of 'more then 5 of the same', as if you simply summed the results of this applied to 5,6,7..20; you would over count the cases where you have, say, 10 1's and 5 8's. </p>
<p>You could probably apply inclusion exclusion again to come up with that second answer; so, P(of at least 5)=P(one set of 20)+ ... + (P(one set of 15) - 7*P(set of 5 from 5 dice)) + ((P(one set of 14) - 7*P(one set of 5 from 6) - 7*P(one set of 6 from 6)). Coming up with the source code for that is proving itself more difficult.</p>
| 3 | 2009-07-29T19:48:39Z | [
"python",
"puzzle",
"combinatorics",
"discrete-mathematics",
"dice"
] |
Combinatorics Counting Puzzle: Roll 20, 8-sided dice, what is the probability of getting at least 5 dice of the same value | 1,202,343 | <p>Assume a game in which one rolls 20, 8-sided die, for a total number of 8^20 possible outcomes. To calculate the probability of a particular event occurring, we divide the number of ways that event can occur by 8^20. </p>
<p>One can calculate the number of ways to get exactly 5 dice of the value 3. (20 choose 5) gives us the number of orders of 3. 7^15 gives us the number of ways we can not get the value 3 for 15 rolls.</p>
<pre><code>number of ways to get exactly 5, 3's = (20 choose 5)*7^15.
</code></pre>
<p>The answer can also be viewed as how many ways can I rearrange the string 3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 (20 choose 5) times the total number of values we the zero's (assuming 7 legal values) 7^15 (is this correct).</p>
<ul>
<li><p>Question 1: How can I calculate the number of ways to get exactly 5 dice of the same value(That is, for all die values).
Note: if I just naively use my first answer above and multiply bt 8, I get an enormous amount of double counting?</p>
<p>I understand that I could solve for each of the cases (5 1's), (5, 2's), (5, 3's), ... (5's, 8) sum them (more simply 8*(5 1's) ). Then subtract the sum of number of overlaps (5 1's) and (5 2's), (5 1's) and (5 3's)... (5 1's) and (5, 2's) and ... and (5, 8's) but this seems exceedingly messy. I would a generalization of this in a way that scales up to large numbers of samples and large numbers of classes.</p></li>
<li><p>How can I calculate the number of ways to get <strong>at least</strong> 5 dice of the same value?</p>
<p>So 111110000000000000000 or 11110100000000000002 or 11111100000001110000 or 11011211222222223333, but not 00001111222233334444 or 000511512252363347744.</p></li>
</ul>
<p>I'm looking for answers which either explain the math or point to a library which supports this (esp python modules). Extra points for detail and examples.</p>
| 3 | 2009-07-29T18:58:43Z | 1,202,632 | <p>I believe you can use the formula of x occurrences in n events as:</p>
<p>P = probability^n * (n!/((n - x)!x!))</p>
<p>So the final result is going to be the sum of results from 0 to n.</p>
<p>I don't really see any easy way to combine it into one step that would be less messy. With this way you have the formula spelled out in the code as well. You may have to write your own factorial method though.</p>
<pre><code> float calculateProbability(int tosses, int atLeastNumber) {
float atLeastProbability = 0;
float eventProbability = Math.pow( 1.0/8.0, tosses);
int nFactorial = factorial(tosses);
for ( i = 1; i <= atLeastNumber; i++) {
atLeastProbability += eventProbability * (nFactorial / (factorial(tosses - i) * factorial(i) );
}
}
</code></pre>
| 1 | 2009-07-29T19:52:36Z | [
"python",
"puzzle",
"combinatorics",
"discrete-mathematics",
"dice"
] |
Combinatorics Counting Puzzle: Roll 20, 8-sided dice, what is the probability of getting at least 5 dice of the same value | 1,202,343 | <p>Assume a game in which one rolls 20, 8-sided die, for a total number of 8^20 possible outcomes. To calculate the probability of a particular event occurring, we divide the number of ways that event can occur by 8^20. </p>
<p>One can calculate the number of ways to get exactly 5 dice of the value 3. (20 choose 5) gives us the number of orders of 3. 7^15 gives us the number of ways we can not get the value 3 for 15 rolls.</p>
<pre><code>number of ways to get exactly 5, 3's = (20 choose 5)*7^15.
</code></pre>
<p>The answer can also be viewed as how many ways can I rearrange the string 3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 (20 choose 5) times the total number of values we the zero's (assuming 7 legal values) 7^15 (is this correct).</p>
<ul>
<li><p>Question 1: How can I calculate the number of ways to get exactly 5 dice of the same value(That is, for all die values).
Note: if I just naively use my first answer above and multiply bt 8, I get an enormous amount of double counting?</p>
<p>I understand that I could solve for each of the cases (5 1's), (5, 2's), (5, 3's), ... (5's, 8) sum them (more simply 8*(5 1's) ). Then subtract the sum of number of overlaps (5 1's) and (5 2's), (5 1's) and (5 3's)... (5 1's) and (5, 2's) and ... and (5, 8's) but this seems exceedingly messy. I would a generalization of this in a way that scales up to large numbers of samples and large numbers of classes.</p></li>
<li><p>How can I calculate the number of ways to get <strong>at least</strong> 5 dice of the same value?</p>
<p>So 111110000000000000000 or 11110100000000000002 or 11111100000001110000 or 11011211222222223333, but not 00001111222233334444 or 000511512252363347744.</p></li>
</ul>
<p>I'm looking for answers which either explain the math or point to a library which supports this (esp python modules). Extra points for detail and examples.</p>
| 3 | 2009-07-29T18:58:43Z | 1,202,634 | <p>I suggest that you spend a little bit of time writing up a Monte Carlo simulation and let it run while you work out the math by hand. Hopefully the Monte Carlo simulation will converge before you're finished with the math and you'll be able to check your solution.</p>
<p>A slightly faster option might involve creating a SO clone for math questions.</p>
| 4 | 2009-07-29T19:53:20Z | [
"python",
"puzzle",
"combinatorics",
"discrete-mathematics",
"dice"
] |
Combinatorics Counting Puzzle: Roll 20, 8-sided dice, what is the probability of getting at least 5 dice of the same value | 1,202,343 | <p>Assume a game in which one rolls 20, 8-sided die, for a total number of 8^20 possible outcomes. To calculate the probability of a particular event occurring, we divide the number of ways that event can occur by 8^20. </p>
<p>One can calculate the number of ways to get exactly 5 dice of the value 3. (20 choose 5) gives us the number of orders of 3. 7^15 gives us the number of ways we can not get the value 3 for 15 rolls.</p>
<pre><code>number of ways to get exactly 5, 3's = (20 choose 5)*7^15.
</code></pre>
<p>The answer can also be viewed as how many ways can I rearrange the string 3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 (20 choose 5) times the total number of values we the zero's (assuming 7 legal values) 7^15 (is this correct).</p>
<ul>
<li><p>Question 1: How can I calculate the number of ways to get exactly 5 dice of the same value(That is, for all die values).
Note: if I just naively use my first answer above and multiply bt 8, I get an enormous amount of double counting?</p>
<p>I understand that I could solve for each of the cases (5 1's), (5, 2's), (5, 3's), ... (5's, 8) sum them (more simply 8*(5 1's) ). Then subtract the sum of number of overlaps (5 1's) and (5 2's), (5 1's) and (5 3's)... (5 1's) and (5, 2's) and ... and (5, 8's) but this seems exceedingly messy. I would a generalization of this in a way that scales up to large numbers of samples and large numbers of classes.</p></li>
<li><p>How can I calculate the number of ways to get <strong>at least</strong> 5 dice of the same value?</p>
<p>So 111110000000000000000 or 11110100000000000002 or 11111100000001110000 or 11011211222222223333, but not 00001111222233334444 or 000511512252363347744.</p></li>
</ul>
<p>I'm looking for answers which either explain the math or point to a library which supports this (esp python modules). Extra points for detail and examples.</p>
| 3 | 2009-07-29T18:58:43Z | 1,203,223 | <p>This problem is really hard if you have to generalize it (get the exact formula).</p>
<p>But anyways, let me explain the algorithm.
If you want to know </p>
<blockquote>
<p>the number of ways to get exactly 5
dice of the same value</p>
</blockquote>
<p>you have to rephrase your previous problem, as</p>
<blockquote>
<p>calculate the number of ways to get
exactly 5 dice of the value 3 AND no
other value can be repeated exactly 5
times</p>
</blockquote>
<p>For simplicity's sake, let's call function F(20,8,5) (5 dice, all values) the first answer, and F(20,8,5,3) (5 dice, value 3) the second.
We have that F(20,8,5) = F(20,8,5,3) * 8 + <strong>(events when more than one value is repeated 5 times)</strong></p>
<p>So if we can get F(20,8,5,3) it should be pretty simple isn't it?
Well...not so much...</p>
<p>First, let us define some variables:
<strong>X1,X2,X3...,Xi , where Xi=number of times we get the dice i</strong></p>
<p>Then:</p>
<pre><code>F(20,8,5)/20^8 = P(X1=5 or X2=5 or ... or X8=5, with R=20(rolls) and N=8(dice number))
</code></pre>
<p>, P(statement) being the standard way to write a probability.</p>
<p>we continue:</p>
<pre><code>F(20,8,5,3)/20^8 = P(X3=5 and X1<>5 and ... and X8<>5, R=20, N=8)
F(20,8,5,3)/20^8 = 1 - P(X1=5 or X2=5 or X4=5 or X5=5 or X6=5 or X7=5 or X8=5, R=15, N=7)
F(20,8,5,3)/20^8 = 1 - F(15,7,5)/7^15
</code></pre>
<p>recursively:</p>
<pre><code>F(15,8,5) = F(15,7,5,1) * 7
P(X1=5 or X2=5 or X4=5 or X5=5 or X6=5 or X7=5 or X8=5, R=15, N=7) = P(X1=5 and X2<>5 and X4<>5 and .. and X8<>5. R=15, N=7) * 7
</code></pre>
<p><hr /></p>
<pre><code>F(15,7,5,1)/7^15 = 1 - F(10,6,5)/6^10 F(10,6,5) = F(10,6,5,2) * 6
</code></pre>
<p><hr /></p>
<pre><code>F(10,6,5,2)/6^10 = 1 - F(5,5,5)/5^5
F(5,5,5) = F(5,5,5,4) * 5
</code></pre>
<p>Well then... F(5,5,5,4) is the number of ways to get 5 dices of value 4 in 5 rolls, such as no other dice repeats 5 times. There is only 1 way, out of a total 5^5. The probability is then 1/5^5.</p>
<p>F(5,5,5) is the number of ways to get 5 dices of any value (out of 5 values) in 5 rolls. It's obviously 5. The probability is then 5/5^5 = 1/5^4.</p>
<p>F(10,6,5,2) is the number of ways to get 5 dices of value 2 in 10 rolls, such as no other dice repeats 5 times.
F(10,6,5,2) = (1-F(5,5,5)/5^5) * 6^10 = (1-1/5^4) * 6^10</p>
<p>Well... I think it may be incorrect at some part, but anyway, you get the idea. I hope I could make the algorithm understandable.</p>
<p><strong>edit:</strong>
I did some checks, and I realized you have to add some cases when you get more than one value repeated exactly 5 times. Don't have time to solve that part thou...</p>
| 2 | 2009-07-29T21:38:14Z | [
"python",
"puzzle",
"combinatorics",
"discrete-mathematics",
"dice"
] |
Templating+scripting reverse proxy? | 1,202,430 | <p>Thinking through an idea, wanted to get feedback/suggestions:</p>
<p>Having had great success with url rewriting and nginx, I'm now thinking of a more capable reverse proxy/router that would do the following:</p>
<ul>
<li>Map requests to handlers based on regex matching (ala Django)</li>
<li>Certain requests would simply be routed to backend servers - eg. static media, memcached, etc</li>
<li>Other requests would render templates that pull in data from several backend servers</li>
</ul>
<p>For example, a template could consist of:</p>
<pre><code><body>
<div>{% remote http://someserver/somepage %}</div>
<div>{% remote http://otherserver/otherpage %}</div>
</body>
</code></pre>
<p>The reverse proxy would make the http requests to someserver/somepage and otherserver/otherpage and pull the results into the template.</p>
<p>Questions:</p>
<ul>
<li>Does the idea make sense or is it a bad idea?</li>
<li>Is there an existing package that implements something like this?</li>
<li>How about an existing server+scripting for implementing this - eg. lighttpd+lua, nginx+??</li>
<li>How about nginx+SSI? Looks pretty capable, if you have experience / recommendations please comment.</li>
<li>How about something like a <a href="http://www.igvita.com/2009/04/20/ruby-proxies-for-scale-and-monitoring/" rel="nofollow">scripting language+eventlet</a> ?</li>
<li>Twisted?</li>
</ul>
<p>My preferences are python for scripting and jinja/django style templates, but I'm open to alternatives.</p>
| 2 | 2009-07-29T19:13:33Z | 1,204,970 | <p>So instead of doing something an AJAXy call into an iframe or something, you're doing it on the server side.</p>
<p>I think it's something I'd only do if the external site was totally under my control, purely for the security implications. It'd also hit your response times quite a bit.</p>
<p>Am I missing the point completely, or would this be quite simple to do with some functions & urllib?</p>
| 0 | 2009-07-30T07:26:54Z | [
"python",
"proxy",
"twisted",
"reverse-proxy"
] |
Templating+scripting reverse proxy? | 1,202,430 | <p>Thinking through an idea, wanted to get feedback/suggestions:</p>
<p>Having had great success with url rewriting and nginx, I'm now thinking of a more capable reverse proxy/router that would do the following:</p>
<ul>
<li>Map requests to handlers based on regex matching (ala Django)</li>
<li>Certain requests would simply be routed to backend servers - eg. static media, memcached, etc</li>
<li>Other requests would render templates that pull in data from several backend servers</li>
</ul>
<p>For example, a template could consist of:</p>
<pre><code><body>
<div>{% remote http://someserver/somepage %}</div>
<div>{% remote http://otherserver/otherpage %}</div>
</body>
</code></pre>
<p>The reverse proxy would make the http requests to someserver/somepage and otherserver/otherpage and pull the results into the template.</p>
<p>Questions:</p>
<ul>
<li>Does the idea make sense or is it a bad idea?</li>
<li>Is there an existing package that implements something like this?</li>
<li>How about an existing server+scripting for implementing this - eg. lighttpd+lua, nginx+??</li>
<li>How about nginx+SSI? Looks pretty capable, if you have experience / recommendations please comment.</li>
<li>How about something like a <a href="http://www.igvita.com/2009/04/20/ruby-proxies-for-scale-and-monitoring/" rel="nofollow">scripting language+eventlet</a> ?</li>
<li>Twisted?</li>
</ul>
<p>My preferences are python for scripting and jinja/django style templates, but I'm open to alternatives.</p>
| 2 | 2009-07-29T19:13:33Z | 1,328,662 | <p>This already exist an is called Deliverance: <a href="http://deliverance.openplans.org/" rel="nofollow">http://deliverance.openplans.org/</a></p>
| 1 | 2009-08-25T14:28:52Z | [
"python",
"proxy",
"twisted",
"reverse-proxy"
] |
Constructor specialization in python | 1,202,711 | <p>Class hierarchies and constructors are related. Parameters from a child class need to be passed to their parent. </p>
<p>So, in Python, we end up with something like this:</p>
<pre><code>class Parent(object):
def __init__(self, a, b, c, ka=None, kb=None, kc=None):
# do something with a, b, c, ka, kb, kc
class Child(Parent):
def __init__(self, a, b, c, d, e, f, ka=None, kb=None, kc=None, kd=None, ke=None, kf=None):
super(Child, self).__init__(a, b, c, ka=ka, kb=kb, kc=kc)
# do something with d, e, f, kd, ke, kf
</code></pre>
<p>Imagine this with a dozen child classes and lots of parameters. Adding new parameters becomes very tedious.</p>
<p>Of course one can dispense with named parameters completely and use *args and **kwargs, but that makes the method declarations ambiguous.</p>
<p>Is there a pattern for elegantly dealing with this in Python (2.6)?</p>
<p>By "elegantly" I mean I would like to reduce the number of times the parameters appear. a, b, c, ka, kb, kc all appear 3 times: in the Child constructor, in the super() call to Parent, and in the Parent constructor.</p>
<p>Ideally, I'd like to specify the parameters for Parent's <strong>init</strong> once, and in Child's <strong>init</strong> only specify the additional parameters.</p>
<p>I'd like to do something like this:</p>
<pre><code>class Parent(object):
def __init__(self, a, b, c, ka=None, kb=None, kc=None):
print 'Parent: ', a, b, c, ka, kb, kc
class Child(Parent):
def __init__(self, d, e, f, kd='d', ke='e', kf='f', *args, **kwargs):
super(Child, self).__init__(*args, **kwargs)
print 'Child: ', d, e, f, kd, ke, kf
x = Child(1, 2, 3, 4, 5, 6, ka='a', kb='b', kc='c', kd='d', ke='e', kf='f')
</code></pre>
<p>This unfortunately doesn't work, since 4, 5, 6 end up assigned to kd, ke, kf.</p>
<p>Is there some elegant python pattern for accomplishing the above?</p>
| 4 | 2009-07-29T20:06:15Z | 1,202,783 | <p>Well, the only solution I could see is using a mixture of listed variables as well as *args and **kwargs, as such:</p>
<pre><code>class Parent(object):
def __init__(self, a, b, c, ka=None, kb=None, kc=None):
pass
class Child(Parent):
def __init__(self, d, e, f, *args, kd=None, ke=None, kf=None, **kwargs):
Parent.__init__(self, *args, **kwargs)
pass
</code></pre>
<p>This way, you could see which parameters are required by each of the classes, but without having to re-type them.</p>
<p>One thing to note is that you lose your desired ordering (a, b, c, d, e, f) as it becomes (d, e, f, a, b, c). I'm not sure if there's a way to have the *args before the other non-named parameters.</p>
| 2 | 2009-07-29T20:18:33Z | [
"python",
"design-patterns",
"class",
"oop",
"anti-patterns"
] |
Constructor specialization in python | 1,202,711 | <p>Class hierarchies and constructors are related. Parameters from a child class need to be passed to their parent. </p>
<p>So, in Python, we end up with something like this:</p>
<pre><code>class Parent(object):
def __init__(self, a, b, c, ka=None, kb=None, kc=None):
# do something with a, b, c, ka, kb, kc
class Child(Parent):
def __init__(self, a, b, c, d, e, f, ka=None, kb=None, kc=None, kd=None, ke=None, kf=None):
super(Child, self).__init__(a, b, c, ka=ka, kb=kb, kc=kc)
# do something with d, e, f, kd, ke, kf
</code></pre>
<p>Imagine this with a dozen child classes and lots of parameters. Adding new parameters becomes very tedious.</p>
<p>Of course one can dispense with named parameters completely and use *args and **kwargs, but that makes the method declarations ambiguous.</p>
<p>Is there a pattern for elegantly dealing with this in Python (2.6)?</p>
<p>By "elegantly" I mean I would like to reduce the number of times the parameters appear. a, b, c, ka, kb, kc all appear 3 times: in the Child constructor, in the super() call to Parent, and in the Parent constructor.</p>
<p>Ideally, I'd like to specify the parameters for Parent's <strong>init</strong> once, and in Child's <strong>init</strong> only specify the additional parameters.</p>
<p>I'd like to do something like this:</p>
<pre><code>class Parent(object):
def __init__(self, a, b, c, ka=None, kb=None, kc=None):
print 'Parent: ', a, b, c, ka, kb, kc
class Child(Parent):
def __init__(self, d, e, f, kd='d', ke='e', kf='f', *args, **kwargs):
super(Child, self).__init__(*args, **kwargs)
print 'Child: ', d, e, f, kd, ke, kf
x = Child(1, 2, 3, 4, 5, 6, ka='a', kb='b', kc='c', kd='d', ke='e', kf='f')
</code></pre>
<p>This unfortunately doesn't work, since 4, 5, 6 end up assigned to kd, ke, kf.</p>
<p>Is there some elegant python pattern for accomplishing the above?</p>
| 4 | 2009-07-29T20:06:15Z | 1,202,787 | <p>"dozen child classes and lots of parameters" sounds like a problem irrespective of parameter naming.</p>
<p>I suspect that a little refactoring can peel out some <strong>Strategy</strong> objects that would simplify this hierarchy and make the super-complex constructors go away.</p>
| 6 | 2009-07-29T20:20:00Z | [
"python",
"design-patterns",
"class",
"oop",
"anti-patterns"
] |
Constructor specialization in python | 1,202,711 | <p>Class hierarchies and constructors are related. Parameters from a child class need to be passed to their parent. </p>
<p>So, in Python, we end up with something like this:</p>
<pre><code>class Parent(object):
def __init__(self, a, b, c, ka=None, kb=None, kc=None):
# do something with a, b, c, ka, kb, kc
class Child(Parent):
def __init__(self, a, b, c, d, e, f, ka=None, kb=None, kc=None, kd=None, ke=None, kf=None):
super(Child, self).__init__(a, b, c, ka=ka, kb=kb, kc=kc)
# do something with d, e, f, kd, ke, kf
</code></pre>
<p>Imagine this with a dozen child classes and lots of parameters. Adding new parameters becomes very tedious.</p>
<p>Of course one can dispense with named parameters completely and use *args and **kwargs, but that makes the method declarations ambiguous.</p>
<p>Is there a pattern for elegantly dealing with this in Python (2.6)?</p>
<p>By "elegantly" I mean I would like to reduce the number of times the parameters appear. a, b, c, ka, kb, kc all appear 3 times: in the Child constructor, in the super() call to Parent, and in the Parent constructor.</p>
<p>Ideally, I'd like to specify the parameters for Parent's <strong>init</strong> once, and in Child's <strong>init</strong> only specify the additional parameters.</p>
<p>I'd like to do something like this:</p>
<pre><code>class Parent(object):
def __init__(self, a, b, c, ka=None, kb=None, kc=None):
print 'Parent: ', a, b, c, ka, kb, kc
class Child(Parent):
def __init__(self, d, e, f, kd='d', ke='e', kf='f', *args, **kwargs):
super(Child, self).__init__(*args, **kwargs)
print 'Child: ', d, e, f, kd, ke, kf
x = Child(1, 2, 3, 4, 5, 6, ka='a', kb='b', kc='c', kd='d', ke='e', kf='f')
</code></pre>
<p>This unfortunately doesn't work, since 4, 5, 6 end up assigned to kd, ke, kf.</p>
<p>Is there some elegant python pattern for accomplishing the above?</p>
| 4 | 2009-07-29T20:06:15Z | 1,203,012 | <p>I try to group the parameters into their own objects, e.g, instead of passing
sourceDirectory, targetDirectory, temporaryDirectory, serverName, serverPort, I'd have a
DirectoryContext and ServerContext objects. </p>
<p>If the context objects start having more
behavior or logic it might lead to the strategy objects mentioned in <a href="http://stackoverflow.com/questions/1202711/constructor-specialization-in-python/1202787#1202787">here</a>.</p>
| 1 | 2009-07-29T21:01:05Z | [
"python",
"design-patterns",
"class",
"oop",
"anti-patterns"
] |
get request data in Django form | 1,202,839 | <p>Is it possible to get request.user data in a form class? I want to clean an email address to make sure that it's unique, but if it's the current users email address then it should pass.</p>
<p>This is what I currently have which works great for creating new users, but if I want to edit a user I run into the problem of their email not validating, because it comes up as being taken already. If I could check that it's their email using request.user.email then I would be able to solve my problem, but I'm not sure how to do that. </p>
<pre><code>class editUserForm(forms.Form):
email_address = forms.EmailField(widget=forms.TextInput(attrs={'class':'required'}))
def clean_email_address(self):
this_email = self.cleaned_data['email_address']
test = UserProfiles.objects.filter(email = this_email)
if len(test)>0:
raise ValidationError("A user with that email already exists.")
else:
return this_email
</code></pre>
| 34 | 2009-07-29T20:29:51Z | 1,202,963 | <p>Not that I'm aware of. One way to handle this is have your Form class's <code>__init__</code> take an optional email parameter, which it can store as an attribute. If supplied at form creation time, it can use that during validation for the comparison you're interested in. </p>
| 0 | 2009-07-29T20:51:48Z | [
"python",
"django"
] |
get request data in Django form | 1,202,839 | <p>Is it possible to get request.user data in a form class? I want to clean an email address to make sure that it's unique, but if it's the current users email address then it should pass.</p>
<p>This is what I currently have which works great for creating new users, but if I want to edit a user I run into the problem of their email not validating, because it comes up as being taken already. If I could check that it's their email using request.user.email then I would be able to solve my problem, but I'm not sure how to do that. </p>
<pre><code>class editUserForm(forms.Form):
email_address = forms.EmailField(widget=forms.TextInput(attrs={'class':'required'}))
def clean_email_address(self):
this_email = self.cleaned_data['email_address']
test = UserProfiles.objects.filter(email = this_email)
if len(test)>0:
raise ValidationError("A user with that email already exists.")
else:
return this_email
</code></pre>
| 34 | 2009-07-29T20:29:51Z | 1,204,136 | <p>As ars and Diarmuid have pointed out, you can pass <code>request.user</code> into your form, and use it in validating the email. Diarmuid's code, however, is wrong. The code should actually read:</p>
<pre><code>from django import forms
class UserForm(forms.Form):
email_address = forms.EmailField(widget = forms.TextInput(attrs = {'class':'required'}))
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user', None)
super(UserForm, self).__init__(*args, **kwargs)
def clean_email_address(self):
email = self.cleaned_data.get('email_address')
if self.user and self.user.email == email:
return email
if UserProfile.objects.filter(email=email).count():
raise forms.ValidationError(u'That email address already exists.')
return email
</code></pre>
<p>Then, in your view, you can use it like so:</p>
<pre><code>def someview(request):
if request.method == 'POST':
form = UserForm(request.POST, user=request.user)
if form.is_valid():
# Do something with the data
pass
else:
form = UserForm(user=request.user)
# Rest of your view follows
</code></pre>
<p><s>Note that you should pass request.POST as a keyword argument, since your constructor expects 'user' as the first positional argument.</s></p>
<p>Doing it this way, you need to pass <code>user</code> as a keyword argument. You can either pass <code>request.POST</code> as a positional argument, or a keyword argument (via <code>data=request.POST</code>).</p>
| 48 | 2009-07-30T02:24:04Z | [
"python",
"django"
] |
get request data in Django form | 1,202,839 | <p>Is it possible to get request.user data in a form class? I want to clean an email address to make sure that it's unique, but if it's the current users email address then it should pass.</p>
<p>This is what I currently have which works great for creating new users, but if I want to edit a user I run into the problem of their email not validating, because it comes up as being taken already. If I could check that it's their email using request.user.email then I would be able to solve my problem, but I'm not sure how to do that. </p>
<pre><code>class editUserForm(forms.Form):
email_address = forms.EmailField(widget=forms.TextInput(attrs={'class':'required'}))
def clean_email_address(self):
this_email = self.cleaned_data['email_address']
test = UserProfiles.objects.filter(email = this_email)
if len(test)>0:
raise ValidationError("A user with that email already exists.")
else:
return this_email
</code></pre>
| 34 | 2009-07-29T20:29:51Z | 14,201,789 | <p>Just so you know, with Django 1.4 and generic class based CreateView and UpdateView, a self.instance is populated on each model form, which allows you to compare the POSTed email vs the current user email.</p>
<p>Here is a code sample, using mixin</p>
<pre><code>class EmailUniqueMixin(object):
"""
Ensure each User's email is unique
on the form level
"""
def clean_email(self):
email = self.cleaned_data['email']
existing_email = User.objects.filter(email=email).exclude(pk=self.instance.id)
if existing_email:
raise forms.ValidationError('That email address already exists')
else:
return email
</code></pre>
| 3 | 2013-01-07T18:26:16Z | [
"python",
"django"
] |
get request data in Django form | 1,202,839 | <p>Is it possible to get request.user data in a form class? I want to clean an email address to make sure that it's unique, but if it's the current users email address then it should pass.</p>
<p>This is what I currently have which works great for creating new users, but if I want to edit a user I run into the problem of their email not validating, because it comes up as being taken already. If I could check that it's their email using request.user.email then I would be able to solve my problem, but I'm not sure how to do that. </p>
<pre><code>class editUserForm(forms.Form):
email_address = forms.EmailField(widget=forms.TextInput(attrs={'class':'required'}))
def clean_email_address(self):
this_email = self.cleaned_data['email_address']
test = UserProfiles.objects.filter(email = this_email)
if len(test)>0:
raise ValidationError("A user with that email already exists.")
else:
return this_email
</code></pre>
| 34 | 2009-07-29T20:29:51Z | 14,656,536 | <p>Here's the way to get the user in your form when using generic views:</p>
<p>In the view, pass the <code>request.user</code> to the form using <code>get_form_kwargs</code>:</p>
<pre><code>class SampleView( View ):
def get_form_kwargs( self ):
kwargs = super( SampleView, self ).get_form_kwargs()
kwargs['user'] = self.request.user
return kwargs
</code></pre>
<p>In the form you will receive the <code>user</code> with the <code>__init__</code> function:</p>
<pre><code>class SampleForm( Form ):
def __init__( self, user, *args, **kwargs ):
super( SampleForm, self ).__init__( *args, **kwargs )
self.user = user
</code></pre>
| 17 | 2013-02-01T23:01:56Z | [
"python",
"django"
] |
Python - tempfile.TemporaryFile cannot be read; why? | 1,202,848 | <p>The <a href="http://docs.python.org/library/tempfile.html#tempfile.TemporaryFile">official documentation for TemporaryFile</a> reads:</p>
<blockquote>
<p>The mode parameter defaults to 'w+b'
so that the file created <strong>can be read
and written without being closed</strong>.</p>
</blockquote>
<p>Yet, the below code does not work as expected:</p>
<pre><code>import tempfile
def play_with_fd():
with tempfile.TemporaryFile() as f:
f.write('test data\n')
f.write('most test data\n')
print 'READ:', f.read()
f.write('further data')
print 'READ:', f.read()
f.write('even more')
print 'READ:', f.read()
print 'READ:', f.read()
print 'READ:', f.read()
if __name__ == '__main__':
play_with_fd()
</code></pre>
<p>The output I get is:</p>
<pre><code>> python play.py
READ:
READ:
READ:
READ:
READ:
</code></pre>
<p>Can anyone explain this behavior? Is there a way to read from temporary files at all? (without having to use the low-level mkstemp that wouldn't automatically delete the files; and I don't care about named files)</p>
| 13 | 2009-07-29T20:31:34Z | 1,202,917 | <p><code>read()</code> does not return anything because you are at the end of the file. You need to call <a href="http://docs.python.org/library/stdtypes.html#file.seek" rel="nofollow"><code>seek()</code></a> first before <code>read()</code> will return anything. For example, put this line in front of the first <code>read()</code>:</p>
<pre><code>f.seek(-10, 1)
</code></pre>
<p>Of course, before writing again, be sure to <code>seek()</code> to the end (if that is where you want to continue writing to).</p>
| 7 | 2009-07-29T20:43:00Z | [
"python",
"file",
"io",
"temporary-files"
] |
Python - tempfile.TemporaryFile cannot be read; why? | 1,202,848 | <p>The <a href="http://docs.python.org/library/tempfile.html#tempfile.TemporaryFile">official documentation for TemporaryFile</a> reads:</p>
<blockquote>
<p>The mode parameter defaults to 'w+b'
so that the file created <strong>can be read
and written without being closed</strong>.</p>
</blockquote>
<p>Yet, the below code does not work as expected:</p>
<pre><code>import tempfile
def play_with_fd():
with tempfile.TemporaryFile() as f:
f.write('test data\n')
f.write('most test data\n')
print 'READ:', f.read()
f.write('further data')
print 'READ:', f.read()
f.write('even more')
print 'READ:', f.read()
print 'READ:', f.read()
print 'READ:', f.read()
if __name__ == '__main__':
play_with_fd()
</code></pre>
<p>The output I get is:</p>
<pre><code>> python play.py
READ:
READ:
READ:
READ:
READ:
</code></pre>
<p>Can anyone explain this behavior? Is there a way to read from temporary files at all? (without having to use the low-level mkstemp that wouldn't automatically delete the files; and I don't care about named files)</p>
| 13 | 2009-07-29T20:31:34Z | 1,202,998 | <p>You must put </p>
<pre><code>f.seek(0)
</code></pre>
<p>before trying to read the file (this will send you to the beginning of the file), and</p>
<pre><code>f.seek(0, 2)
</code></pre>
<p>to return to the end so you can assure you won't overwrite it.</p>
| 25 | 2009-07-29T20:58:55Z | [
"python",
"file",
"io",
"temporary-files"
] |
Python CSV DictReader/Writer issues | 1,202,855 | <p>I'm trying to extract a bunch of lines from a CSV file and write them into another, but I'm having some problems.</p>
<pre><code>import csv
f = open("my_csv_file.csv", "r")
r = csv.DictReader(f, delimiter=',')
fieldnames = r.fieldnames
target = open("united.csv", 'w')
w = csv.DictWriter(united, fieldnames=fieldnames)
while True:
try:
row = r.next()
if r.line_num <= 2: #first two rows don't matter
continue
else:
w.writerow(row)
except StopIteration:
break
f.close()
target.close()
</code></pre>
<p>Running this, I get the following error:</p>
<pre><code>Traceback (most recent call last):
File "unify.py", line 16, in <module>
w.writerow(row)
File "C:\Program Files\Python25\lib\csv.py", line 12
return self.writer.writerow(self._dict_to_list(row
File "C:\Program Files\Python25\lib\csv.py", line 12
if k not in self.fieldnames:
TypeError: argument of type 'NoneType' is not iterable
</code></pre>
<p>Not entirely sure what I'm dong wrong.</p>
| 2 | 2009-07-29T20:32:42Z | 1,202,875 | <p>I don't know either, but since all you're doing is copying lines from one file to another why are you bothering with the <code>csv</code> stuff at all? Why not something like:</p>
<pre><code>f = open("my_csv_file.csv", "r")
target = open("united.csv", 'w')
f.readline()
f.readline()
for line in f:
target.write(line)
</code></pre>
| 11 | 2009-07-29T20:35:26Z | [
"python",
"csv"
] |
Python CSV DictReader/Writer issues | 1,202,855 | <p>I'm trying to extract a bunch of lines from a CSV file and write them into another, but I'm having some problems.</p>
<pre><code>import csv
f = open("my_csv_file.csv", "r")
r = csv.DictReader(f, delimiter=',')
fieldnames = r.fieldnames
target = open("united.csv", 'w')
w = csv.DictWriter(united, fieldnames=fieldnames)
while True:
try:
row = r.next()
if r.line_num <= 2: #first two rows don't matter
continue
else:
w.writerow(row)
except StopIteration:
break
f.close()
target.close()
</code></pre>
<p>Running this, I get the following error:</p>
<pre><code>Traceback (most recent call last):
File "unify.py", line 16, in <module>
w.writerow(row)
File "C:\Program Files\Python25\lib\csv.py", line 12
return self.writer.writerow(self._dict_to_list(row
File "C:\Program Files\Python25\lib\csv.py", line 12
if k not in self.fieldnames:
TypeError: argument of type 'NoneType' is not iterable
</code></pre>
<p>Not entirely sure what I'm dong wrong.</p>
| 2 | 2009-07-29T20:32:42Z | 1,282,896 | <p>As for the exception, looks like this line:</p>
<pre><code>w = csv.DictWriter(united, fieldnames=fieldnames)
</code></pre>
<p>should be</p>
<pre><code>w = csv.DictWriter(target, fieldnames=fieldnames)
</code></pre>
| 1 | 2009-08-15T21:29:53Z | [
"python",
"csv"
] |
Python CSV DictReader/Writer issues | 1,202,855 | <p>I'm trying to extract a bunch of lines from a CSV file and write them into another, but I'm having some problems.</p>
<pre><code>import csv
f = open("my_csv_file.csv", "r")
r = csv.DictReader(f, delimiter=',')
fieldnames = r.fieldnames
target = open("united.csv", 'w')
w = csv.DictWriter(united, fieldnames=fieldnames)
while True:
try:
row = r.next()
if r.line_num <= 2: #first two rows don't matter
continue
else:
w.writerow(row)
except StopIteration:
break
f.close()
target.close()
</code></pre>
<p>Running this, I get the following error:</p>
<pre><code>Traceback (most recent call last):
File "unify.py", line 16, in <module>
w.writerow(row)
File "C:\Program Files\Python25\lib\csv.py", line 12
return self.writer.writerow(self._dict_to_list(row
File "C:\Program Files\Python25\lib\csv.py", line 12
if k not in self.fieldnames:
TypeError: argument of type 'NoneType' is not iterable
</code></pre>
<p>Not entirely sure what I'm dong wrong.</p>
| 2 | 2009-07-29T20:32:42Z | 2,413,953 | <p>The reason you're getting the error is most likely that your original CSV file (my_csv_file.csv) doesn't have a header row. Therefore, when you construct the reader object, its fieldnames field is set to <code>None</code>.</p>
<p>When you try to write a row using the writer, it first checks to make sure there are no keys in the dict that are not in its list of known fields. Since <code>fieldnames</code> is set to <code>None</code>, an attempt to dereference the key name throws an exception.</p>
| 1 | 2010-03-10T01:36:58Z | [
"python",
"csv"
] |
Python CSV DictReader/Writer issues | 1,202,855 | <p>I'm trying to extract a bunch of lines from a CSV file and write them into another, but I'm having some problems.</p>
<pre><code>import csv
f = open("my_csv_file.csv", "r")
r = csv.DictReader(f, delimiter=',')
fieldnames = r.fieldnames
target = open("united.csv", 'w')
w = csv.DictWriter(united, fieldnames=fieldnames)
while True:
try:
row = r.next()
if r.line_num <= 2: #first two rows don't matter
continue
else:
w.writerow(row)
except StopIteration:
break
f.close()
target.close()
</code></pre>
<p>Running this, I get the following error:</p>
<pre><code>Traceback (most recent call last):
File "unify.py", line 16, in <module>
w.writerow(row)
File "C:\Program Files\Python25\lib\csv.py", line 12
return self.writer.writerow(self._dict_to_list(row
File "C:\Program Files\Python25\lib\csv.py", line 12
if k not in self.fieldnames:
TypeError: argument of type 'NoneType' is not iterable
</code></pre>
<p>Not entirely sure what I'm dong wrong.</p>
| 2 | 2009-07-29T20:32:42Z | 3,595,110 | <p>To clear up the confusion about the error: you get it because <code>r.fieldnames</code> is only set once you read from the input file for the first time using <code>r</code>. Hence the way you wrote it, <code>fieldnames</code> will always be initialized to <code>None</code>.</p>
<p>You may initialize <code>w = csv.DictWriter(united, fieldnames=fieldnames)</code> with <code>r.fieldnames</code> only after you read the first line from <code>r</code>, which means you would have to restructure your code.</p>
<p>This behavior is documented in the <a href="http://docs.python.org/library/csv.html#csv.csvreader.fieldnames">Python Standard Library documentation</a></p>
<blockquote>
<p>DictReader objects have the following public attribute:</p>
<p>csvreader.fieldnames</p>
<p>If not passed as a parameter when creating the object, this attribute is initialized upon first access or when the first record is read from the file.</p>
</blockquote>
| 11 | 2010-08-29T14:27:34Z | [
"python",
"csv"
] |
How to use Python's Easygui module to pick files and insert filenames into code | 1,202,902 | <p>I'm trying to use Python's easygui module to select a file and then insert it's name into a program I wrote (see code below). So I want to insert filename 1 and 2 where it says <strong>insert filename1</strong>, etc.. Any help would be greatly appreciated. Thanks! </p>
<pre><code>import easygui
import csv
msg='none'
title='select a 90m distance csv file'
filetypes=['*.csv']
default='*'
filename1= easygui.fileopenbox()
filename2= easygui.fileopenbox()
dist90m_GIS_filename=(open('**insert filename1'**,'rb'))
datafile_filename=(open(**insert filename2'**,'rb'))
GIS_FH=csv.reader(dist90m_GIS_filename)
DF_FH=csv.reader(datafile_filename)
dist90m=[]
for line in GIS_FH:
dist90m.append(line[3])
data1=[]
data2=[]
for line in DF_FH:
data1.append(','.join(line[0:57]))
data2.append(','.join(line[58:63]))
outfile=(open('X:\\herring_schools\\python_tests\\excel_test_out.csv','w'))
i=0
for row in data1:
row=row+','+dist90m[i]+','+data2[i]+'\n'
outfile.write(row)
i=i+1
outfile.close()
</code></pre>
| 0 | 2009-07-29T20:40:22Z | 1,206,424 | <p>I'm going to assume you're new to programming. If I misunderstood your question, I apologize.</p>
<p>In your code, after the lines:</p>
<pre><code>filename1 = easygui.fileopenbox()
filename2 = easygui.fileopenbox()
</code></pre>
<p>The selected file names are stored in the variables <code>filename1</code> and <code>filename2</code>. You can use those variables to open file <em>handles</em> like this:</p>
<pre><code>dist90m_GIS_filename=(open(filename1,'rb'))
datafile_filename=(open(filename2,'rb'))
</code></pre>
<p>Notice how I simply wrote <code>filename1</code> where you wrote <code>**insert filename1**</code>. This is the whole point of variables. You use them where you need their value.</p>
| 2 | 2009-07-30T12:53:55Z | [
"python",
"file",
"easygui"
] |
Using Enthought | 1,202,967 | <p>I need to calculate the inverse of the complementary error function (erfc^(1)) for a problem.</p>
<p>I was looking into Python tools for it, and many threads said Enthought has most of the
math tools needed, so I downloaded and installed it in my local user account. But I am not
very sure about how to use it? </p>
<p>Any ideas?</p>
| 1 | 2009-07-29T20:52:12Z | 1,203,037 | <p><a href="http://scipy.org/" rel="nofollow">SciPy</a>, which is included in the <a href="http://en.wikipedia.org/wiki/Enthought" rel="nofollow">Enthought</a> Python distribution, contains that <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.special.erfcinv.html#scipy.special.erfcinv" rel="nofollow">special function</a>.</p>
<pre><code>In [1]: from scipy.special import erfcinv
In [2]: from numpy import linspace
In [3]: x = linspace(0, 1, 10)
In [4]: y = erfcinv(x)
In [5]: y
Out[5]:
array([ 1.27116101e+308, 1.12657583e+000, 8.63123068e-001,
6.84070350e-001, 5.40731396e-001, 4.16808192e-001,
3.04570194e-001, 1.99556951e-001, 9.87900997e-002,
0.00000000e+000])
</code></pre>
| 8 | 2009-07-29T21:05:17Z | [
"python",
"scipy"
] |
Using Enthought | 1,202,967 | <p>I need to calculate the inverse of the complementary error function (erfc^(1)) for a problem.</p>
<p>I was looking into Python tools for it, and many threads said Enthought has most of the
math tools needed, so I downloaded and installed it in my local user account. But I am not
very sure about how to use it? </p>
<p>Any ideas?</p>
| 1 | 2009-07-29T20:52:12Z | 1,203,097 | <p>Here's a quick example of calculations in the Enthought Python Distribution (EPD) with the inverse of the complementary error function (<code>erfcinv</code>), which is included in the <a href="http://www.scipy.org/" rel="nofollow">SciPy</a> package that comes with the EPD:</p>
<pre><code>C:\>c:\Python25\python
EPD Py25 (4.1.30101) -- http://www.enthought.com/epd
Python 2.5.2 |EPD Py25 4.1.30101| (r252:60911, Dec 19 2008, 13:49:12) [MSC v.131
0 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from scipy.special import erfcinv
>>> erfcinv(0.)
1.271161006153646e+308
>>> erfcinv(1.)
0.0
>>> erfcinv(2.)
-1.271161006153646e+308
>>> exit()
C:\>
</code></pre>
| 1 | 2009-07-29T21:16:12Z | [
"python",
"scipy"
] |
Formatting text into boxes in the Python Shell | 1,203,036 | <p>I've created a basic menu class that looks like this:</p>
<pre><code>class Menu:
def __init__(self, title, body):
self.title = title
self.body = body
def display(self):
#print the menu to the screen
</code></pre>
<p>What I want to do is format the title and the body so they fit inside premade boxes almost. Where no matter what I pass as the body, display will be able to fit it inside. The format would look something like this.</p>
<pre><code>********************************************************************************
* Here's the title *
********************************************************************************
* *
* The body will go in here. Say I put a line break here ---> \n *
* it will go to the next line. I also want to keep track\n *
* \t <----- of tabs so I can space things out on lines if i have to *
* *
********************************************************************************
</code></pre>
<p>The title I think will be easy but I'm getting lost on the body.</p>
| 1 | 2009-07-29T21:04:56Z | 1,203,113 | <pre><code>#!/usr/bin/env python
def format_box(title, body, width=80):
box_line = lambda text: "* " + text + (" " * (width - 6 - len(text))) + " *"
print "*" * width
print box_line(title)
print "*" * width
print box_line("")
for line in body.split("\n"):
print box_line(line.expandtabs())
print box_line("")
print "*" * width
format_box(
"Here's the title",
"The body will go in here. Say I put a line break here ---> \n"
"it will go to the next line. I also want to keep track\n"
"\t<----- of tabs so I can space things out on lines if i have to"
);
</code></pre>
| 4 | 2009-07-29T21:19:13Z | [
"python",
"shell",
"formatting"
] |
Formatting text into boxes in the Python Shell | 1,203,036 | <p>I've created a basic menu class that looks like this:</p>
<pre><code>class Menu:
def __init__(self, title, body):
self.title = title
self.body = body
def display(self):
#print the menu to the screen
</code></pre>
<p>What I want to do is format the title and the body so they fit inside premade boxes almost. Where no matter what I pass as the body, display will be able to fit it inside. The format would look something like this.</p>
<pre><code>********************************************************************************
* Here's the title *
********************************************************************************
* *
* The body will go in here. Say I put a line break here ---> \n *
* it will go to the next line. I also want to keep track\n *
* \t <----- of tabs so I can space things out on lines if i have to *
* *
********************************************************************************
</code></pre>
<p>The title I think will be easy but I'm getting lost on the body.</p>
| 1 | 2009-07-29T21:04:56Z | 1,210,175 | <p>You could also try the standard <a href="http://docs.python.org/library/textwrap.html" rel="nofollow">'textwrap'</a> module</p>
| 0 | 2009-07-31T00:54:32Z | [
"python",
"shell",
"formatting"
] |
Can you Make a Django form set validate the initial data? | 1,203,237 | <p>Here's an example:</p>
<pre><code>from django import forms
class ArticleForm(forms.Form):
title = forms.CharField()
pub_date = forms.DateField()
from django.forms.formsets import formset_factory
ArticleFormSet = formset_factory(ArticleForm)
formset = ArticleFormSet(initial=my_data)
</code></pre>
<p>So 'my_data' in the example is the data I want to form to show when it is first loaded before any user input. But I'd like to go ahead and run the form's validation on the data so the user can see if there are any existing errors before they edit the data.</p>
<p>I tried doing this:</p>
<pre><code>formset = ArticleFormSet(initial=my_data)
formset.is_valid()
</code></pre>
<p>But it didn't help.</p>
| 1 | 2009-07-29T21:40:45Z | 1,203,279 | <p>I can't see how there can be any validation errors if the data just came straight out of the DB. However, it's quite easy to do this - instead of passing the data in as <code>initial,</code> pass it as <code>data</code>, just as if it came from a POST.</p>
<pre><code>formset = ArticleFormSet(data=my_data)
</code></pre>
<p>This sets the form as bound, and triggers validation.</p>
| 1 | 2009-07-29T21:51:03Z | [
"python",
"django",
"forms",
"formset"
] |
Can you Make a Django form set validate the initial data? | 1,203,237 | <p>Here's an example:</p>
<pre><code>from django import forms
class ArticleForm(forms.Form):
title = forms.CharField()
pub_date = forms.DateField()
from django.forms.formsets import formset_factory
ArticleFormSet = formset_factory(ArticleForm)
formset = ArticleFormSet(initial=my_data)
</code></pre>
<p>So 'my_data' in the example is the data I want to form to show when it is first loaded before any user input. But I'd like to go ahead and run the form's validation on the data so the user can see if there are any existing errors before they edit the data.</p>
<p>I tried doing this:</p>
<pre><code>formset = ArticleFormSet(initial=my_data)
formset.is_valid()
</code></pre>
<p>But it didn't help.</p>
| 1 | 2009-07-29T21:40:45Z | 9,393,493 | <p>Use </p>
<p><code>formset = ArticleFormSet(data=my_data)</code></p>
<p>Very important, my_data should be a dict with this format</p>
<pre><code>data = {
'form-TOTAL_FORMS': u'2',
'form-INITIAL_FORMS': u'2',
'form-MAX_NUM_FORMS': u'',
'form-0-title': u'Test',
'form-0-pub_date': u'1904-06-16',
'form-1-title': u'Test',
}
</code></pre>
<p>form-TOTAL_FORMS and form-INITIAL_FORMS are mandatory!!!</p>
| 0 | 2012-02-22T10:59:05Z | [
"python",
"django",
"forms",
"formset"
] |
recursive lambda-expressions possible? | 1,203,292 | <p>I'm trying to write a lambda-expression that calls itself, but i can't seem to find any syntax for that, or even if it's possible.</p>
<p>Essentially what I wanted to transfer the following function into the following lambda expression: (I realize it's a silly application, it just adds, but I'm exploring what I can do with lambda-expressions in python)</p>
<pre><code>def add(a, b):
if a <= 0:
return b
else:
return 1 + add(a - 1, b)
add = lambda a, b: [1 + add(a-1, b), b][a <= 0]
</code></pre>
<p>but calling the lambda form of add results in a runtime error because the maximum recursion depth is reached. Is it even possible to do this in python? Or am I just making some stupid mistake? Oh, I'm using python3.0, but I don't think that should matter?</p>
| 17 | 2009-07-29T21:54:24Z | 1,203,297 | <p>Maybe you need a Y combinator?</p>
<p><strong>Edit</strong> - make that a Z combinator (I hadn't realized that Y combinators are more for call-by-name)</p>
<p>Using the definition of the Z combinator from <a href="http://en.wikipedia.org/wiki/Fixed%5Fpoint%5Fcombinator">Wikipedia</a></p>
<pre><code>>>> Z = lambda f: (lambda x: f(lambda *args: x(x)(*args)))(lambda x: f(lambda *args: x(x)(*args)))
</code></pre>
<p>Using this, you can then define add as a completely anonymous function (ie. no reference to its name in its definition)</p>
<pre><code>>>> add = Z(lambda f: lambda a, b: b if a <= 0 else 1 + f(a - 1, b))
>>> add(1, 1)
2
>>> add(1, 5)
6
</code></pre>
| 18 | 2009-07-29T21:55:53Z | [
"python",
"recursion",
"lambda"
] |
recursive lambda-expressions possible? | 1,203,292 | <p>I'm trying to write a lambda-expression that calls itself, but i can't seem to find any syntax for that, or even if it's possible.</p>
<p>Essentially what I wanted to transfer the following function into the following lambda expression: (I realize it's a silly application, it just adds, but I'm exploring what I can do with lambda-expressions in python)</p>
<pre><code>def add(a, b):
if a <= 0:
return b
else:
return 1 + add(a - 1, b)
add = lambda a, b: [1 + add(a-1, b), b][a <= 0]
</code></pre>
<p>but calling the lambda form of add results in a runtime error because the maximum recursion depth is reached. Is it even possible to do this in python? Or am I just making some stupid mistake? Oh, I'm using python3.0, but I don't think that should matter?</p>
| 17 | 2009-07-29T21:54:24Z | 1,203,337 | <p>First of all recursive lambda expressions are completely unnecessary. As you yourself point out, for the lambda expression to call itself, it needs to have a name. But lambda expressions is nothing else than anonymous functions. So if you give the lambda expression a name, it's no longer a lambda expression, but a function.</p>
<p>Hence, using a lambda expression is useless, and will only confuse people. So create it with a def instead.</p>
<p>But yes, as you yourself discovered, lambda expressions can be recursive. Your own example is. It's in fact so fantastically recursive that you exceed the maximum recursion depth. So it's recursive alright. Your problem is that you always call add in the expression, so the recursion never stops. Don't do that. Your expression can be expressed like this instead:</p>
<pre><code>add = lambda a, b: a > 0 and (1 + add(a-1, b)) or b
</code></pre>
<p>Which takes care of that problem. However, your first def is the correct way of doing it.</p>
| 7 | 2009-07-29T22:06:29Z | [
"python",
"recursion",
"lambda"
] |
recursive lambda-expressions possible? | 1,203,292 | <p>I'm trying to write a lambda-expression that calls itself, but i can't seem to find any syntax for that, or even if it's possible.</p>
<p>Essentially what I wanted to transfer the following function into the following lambda expression: (I realize it's a silly application, it just adds, but I'm exploring what I can do with lambda-expressions in python)</p>
<pre><code>def add(a, b):
if a <= 0:
return b
else:
return 1 + add(a - 1, b)
add = lambda a, b: [1 + add(a-1, b), b][a <= 0]
</code></pre>
<p>but calling the lambda form of add results in a runtime error because the maximum recursion depth is reached. Is it even possible to do this in python? Or am I just making some stupid mistake? Oh, I'm using python3.0, but I don't think that should matter?</p>
| 17 | 2009-07-29T21:54:24Z | 1,203,364 | <pre><code>add = lambda a, b: b if a <= 0 else 1 + add(a - 1, b)
</code></pre>
| 3 | 2009-07-29T22:13:32Z | [
"python",
"recursion",
"lambda"
] |
recursive lambda-expressions possible? | 1,203,292 | <p>I'm trying to write a lambda-expression that calls itself, but i can't seem to find any syntax for that, or even if it's possible.</p>
<p>Essentially what I wanted to transfer the following function into the following lambda expression: (I realize it's a silly application, it just adds, but I'm exploring what I can do with lambda-expressions in python)</p>
<pre><code>def add(a, b):
if a <= 0:
return b
else:
return 1 + add(a - 1, b)
add = lambda a, b: [1 + add(a-1, b), b][a <= 0]
</code></pre>
<p>but calling the lambda form of add results in a runtime error because the maximum recursion depth is reached. Is it even possible to do this in python? Or am I just making some stupid mistake? Oh, I'm using python3.0, but I don't think that should matter?</p>
| 17 | 2009-07-29T21:54:24Z | 1,203,499 | <p>Perhaps you should try the <a href="http://en.wikipedia.org/wiki/Fixed_point_combinator">Z combinator</a>, where this example is from:</p>
<pre><code>>>> Z = lambda f: (lambda x: f(lambda *args: x(x)(*args)))(lambda x: f(lambda *args: x(x)(*args)))
>>> fact = lambda f: lambda x: 1 if x == 0 else x * f(x-1)
>>> Z(fact)(5)
120
</code></pre>
| 7 | 2009-07-29T22:41:29Z | [
"python",
"recursion",
"lambda"
] |
recursive lambda-expressions possible? | 1,203,292 | <p>I'm trying to write a lambda-expression that calls itself, but i can't seem to find any syntax for that, or even if it's possible.</p>
<p>Essentially what I wanted to transfer the following function into the following lambda expression: (I realize it's a silly application, it just adds, but I'm exploring what I can do with lambda-expressions in python)</p>
<pre><code>def add(a, b):
if a <= 0:
return b
else:
return 1 + add(a - 1, b)
add = lambda a, b: [1 + add(a-1, b), b][a <= 0]
</code></pre>
<p>but calling the lambda form of add results in a runtime error because the maximum recursion depth is reached. Is it even possible to do this in python? Or am I just making some stupid mistake? Oh, I'm using python3.0, but I don't think that should matter?</p>
| 17 | 2009-07-29T21:54:24Z | 1,203,505 | <p>You want the Y combinator, or some other <a href="http://en.wikipedia.org/wiki/Fixed%5Fpoint%5Fcombinator" rel="nofollow">fixed point combinator</a>.</p>
<p>Here's an example implementation as a Python lambda expression:</p>
<pre><code>Y = lambda g: (lambda f: g(lambda arg: f(f)(arg))) (lambda f: g(lambda arg: f(f)(arg)))
</code></pre>
<p>Use it like so:</p>
<pre><code>factorial = Y(lambda f: (lambda num: num and num * f(num - 1) or 1))
</code></pre>
<p>That is, you pass into Y() a single-argument function (or lambda), which receives as its argument a recursive version of itself. So the function doesn't need to know its own name, since it gets a reference to itself instead.</p>
<p>Note that this does get tricky for your add() function because the Y combinator only supports passing a single argument. You can get more arguments by <a href="http://en.wikipedia.org/wiki/Currying" rel="nofollow">currying</a> -- but I'll leave that as an exercise for the reader. :-)</p>
| 0 | 2009-07-29T22:42:17Z | [
"python",
"recursion",
"lambda"
] |
recursive lambda-expressions possible? | 1,203,292 | <p>I'm trying to write a lambda-expression that calls itself, but i can't seem to find any syntax for that, or even if it's possible.</p>
<p>Essentially what I wanted to transfer the following function into the following lambda expression: (I realize it's a silly application, it just adds, but I'm exploring what I can do with lambda-expressions in python)</p>
<pre><code>def add(a, b):
if a <= 0:
return b
else:
return 1 + add(a - 1, b)
add = lambda a, b: [1 + add(a-1, b), b][a <= 0]
</code></pre>
<p>but calling the lambda form of add results in a runtime error because the maximum recursion depth is reached. Is it even possible to do this in python? Or am I just making some stupid mistake? Oh, I'm using python3.0, but I don't think that should matter?</p>
| 17 | 2009-07-29T21:54:24Z | 21,441,870 | <p>a little late ... but I just found this gem @ <a href="http://metapython.blogspot.com/2010/11/recursive-lambda-functions.html" rel="nofollow">http://metapython.blogspot.com/2010/11/recursive-lambda-functions.html</a></p>
<pre><code>def myself (*args, **kw):
caller_frame = currentframe(1)
code = caller_frame.f_code
return FunctionType(code, caller_frame.f_globals)(*args,**kw)
print "5! = "
print (lambda x:1 if n <= 1 else myself(n-1)*n)(5)
</code></pre>
| 0 | 2014-01-29T20:24:49Z | [
"python",
"recursion",
"lambda"
] |
can't see records inserted by django test case | 1,203,295 | <p>I'm trying to provide integration to my django application from subversion through the post commit hook.</p>
<p>I have a django test case (a subclass of unittest.TestCase) that (a) inserts a couple of records into a table, (b) spawns an svn commit, (c) svn commit runs a hook that uses my django model to look up info.</p>
<p>I'm using an sqlite3 db. The test is <em>not</em> using the :memory: db, it is using a real file. I have modified the django test code (for debugging this issue) to avoid deleting the test db when it is finished so I can inspect it.</p>
<p>The test code dumps model.MyModel.objects.all() and the records are there between (a) and (b).</p>
<p>When the hook fires at (c) it also dumps the model and there are no records. When I inspect the db manually after the test runs, there are no records.</p>
<p>Is there something going on in the django test framework that isn't commiting the records to the db file?</p>
<p><strong>To clarify</strong>: (d) end the test case. Thus the svn commit hook is run before the test case terminates, and before any django db cleanup code <em>should</em> be run.</p>
<p><strong>Extra info</strong>: I added a 15 second delay between (b) and (b) so that I could examine the db file manually in the middle of the test. The records aren't in the file.</p>
| 3 | 2009-07-29T21:55:29Z | 1,203,379 | <p>Are you using Django trunk? Recent changes (<a href="http://code.djangoproject.com/changeset/9756">Changeset 9756</a>) run tests in a transaction which is then rolled back. Here's the check-in comment:</p>
<blockquote>
<p>Fixed #8138 -- Changed
django.test.TestCase to rollback tests
(when the database supports it)
instead of flushing and reloading the
database. This can substantially
reduce the time it takes to run large
test suites.</p>
</blockquote>
| 5 | 2009-07-29T22:17:16Z | [
"python",
"django",
"testing",
"sqlite"
] |
can't see records inserted by django test case | 1,203,295 | <p>I'm trying to provide integration to my django application from subversion through the post commit hook.</p>
<p>I have a django test case (a subclass of unittest.TestCase) that (a) inserts a couple of records into a table, (b) spawns an svn commit, (c) svn commit runs a hook that uses my django model to look up info.</p>
<p>I'm using an sqlite3 db. The test is <em>not</em> using the :memory: db, it is using a real file. I have modified the django test code (for debugging this issue) to avoid deleting the test db when it is finished so I can inspect it.</p>
<p>The test code dumps model.MyModel.objects.all() and the records are there between (a) and (b).</p>
<p>When the hook fires at (c) it also dumps the model and there are no records. When I inspect the db manually after the test runs, there are no records.</p>
<p>Is there something going on in the django test framework that isn't commiting the records to the db file?</p>
<p><strong>To clarify</strong>: (d) end the test case. Thus the svn commit hook is run before the test case terminates, and before any django db cleanup code <em>should</em> be run.</p>
<p><strong>Extra info</strong>: I added a 15 second delay between (b) and (b) so that I could examine the db file manually in the middle of the test. The records aren't in the file.</p>
| 3 | 2009-07-29T21:55:29Z | 1,203,393 | <p>The test framework is not saving the data to the database, the data is cleaned once the tests have finished.</p>
| 1 | 2009-07-29T22:19:41Z | [
"python",
"django",
"testing",
"sqlite"
] |
Error in Django running on Apache/mod_wsgi | 1,203,448 | <p>Recently i asked a <a href="http://stackoverflow.com/questions/1195260/installing-django-with-modwsgi">question</a> regarding an error in apache/mod_wsgi recognizing the python script directory.
The community kindly answered the question resulting in a successful installation. Now I have a different error, the server daemon (well, technically is a windows service, I say tomato you say...) doesn't find any of the models, here's the full traceback:</p>
<p>Environment:</p>
<pre><code>Request Method: GET
Request URL: `http://localhost/polls/`
Django Version: 1.0.2 final
Python Version: 2.6.2
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'mysite.polls']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware')
</code></pre>
<p>Template error:
In template c:\users\marcos\documents\djangotemplates\polls\poll<code>_</code>list.html, error at line 1
Caught an exception while rendering: no such table: polls_poll </p>
<pre>
1 : {% if object_list %}
2 : <ul>
3 : {% for poll in object_list %}
4 : <li> <a href="{{poll.id}}/">{{ poll.question }} </a> </li>
5 : {% endfor %}
6 : </ul>
7 : {% else %}
8 : <p>No polls are available.</p>
9 : {% endif %}
10 :
</pre>
<p>Traceback: </p>
<pre> File "C:\Python26\lib\site-packages\django\core\handlers\base.py" in get_response
86. response = callback(request, *callback_args, **callback_kwargs)
File "C:\Python26\lib\site-packages\django\views\generic\list_detail.py" in object_list
101. return HttpResponse(t.render(c), mimetype=mimetype)
File "C:\Python26\lib\site-packages\django\template\__init__.py" in render
176. return self.nodelist.render(context)
File "C:\Python26\lib\site-packages\django\template\__init__.py" in render
768. bits.append(self.render_node(node, context))
File "C:\Python26\lib\site-packages\django\template\debug.py" in render_node
81. raise wrapped
</pre>
<pre><code>Exception Type: TemplateSyntaxError at /polls/
Exception Value: Caught an exception while rendering: no such table: polls_poll
</code></pre>
<p>somewhere someone advice me to use <strong>manage.py dbshell</strong> and the script responded:<br />
Error: You appear not to have the 'sqlite3' program installed or on your path.</p>
<p>But still the Django runserver runs the app perfectly. I don't see what changed in the environment to screw the web-app so hard. Please help!</p>
| 1 | 2009-07-29T22:31:34Z | 1,203,465 | <p>Try <strong>manage.py syncdb</strong> to make sure that django can connect to the database and that all the tables are created.</p>
| 0 | 2009-07-29T22:34:18Z | [
"python",
"django",
"apache",
"sqlite3",
"mod-wsgi"
] |
Error in Django running on Apache/mod_wsgi | 1,203,448 | <p>Recently i asked a <a href="http://stackoverflow.com/questions/1195260/installing-django-with-modwsgi">question</a> regarding an error in apache/mod_wsgi recognizing the python script directory.
The community kindly answered the question resulting in a successful installation. Now I have a different error, the server daemon (well, technically is a windows service, I say tomato you say...) doesn't find any of the models, here's the full traceback:</p>
<p>Environment:</p>
<pre><code>Request Method: GET
Request URL: `http://localhost/polls/`
Django Version: 1.0.2 final
Python Version: 2.6.2
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'mysite.polls']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware')
</code></pre>
<p>Template error:
In template c:\users\marcos\documents\djangotemplates\polls\poll<code>_</code>list.html, error at line 1
Caught an exception while rendering: no such table: polls_poll </p>
<pre>
1 : {% if object_list %}
2 : <ul>
3 : {% for poll in object_list %}
4 : <li> <a href="{{poll.id}}/">{{ poll.question }} </a> </li>
5 : {% endfor %}
6 : </ul>
7 : {% else %}
8 : <p>No polls are available.</p>
9 : {% endif %}
10 :
</pre>
<p>Traceback: </p>
<pre> File "C:\Python26\lib\site-packages\django\core\handlers\base.py" in get_response
86. response = callback(request, *callback_args, **callback_kwargs)
File "C:\Python26\lib\site-packages\django\views\generic\list_detail.py" in object_list
101. return HttpResponse(t.render(c), mimetype=mimetype)
File "C:\Python26\lib\site-packages\django\template\__init__.py" in render
176. return self.nodelist.render(context)
File "C:\Python26\lib\site-packages\django\template\__init__.py" in render
768. bits.append(self.render_node(node, context))
File "C:\Python26\lib\site-packages\django\template\debug.py" in render_node
81. raise wrapped
</pre>
<pre><code>Exception Type: TemplateSyntaxError at /polls/
Exception Value: Caught an exception while rendering: no such table: polls_poll
</code></pre>
<p>somewhere someone advice me to use <strong>manage.py dbshell</strong> and the script responded:<br />
Error: You appear not to have the 'sqlite3' program installed or on your path.</p>
<p>But still the Django runserver runs the app perfectly. I don't see what changed in the environment to screw the web-app so hard. Please help!</p>
| 1 | 2009-07-29T22:31:34Z | 1,203,792 | <p>You don't have a database. It's not clear why you don't have a sqlite3 driver. However, you don't have sqlite3 and you don't have a database.</p>
<ol>
<li><p>Run manage.py syncdb build the database. </p>
<ul>
<li><p>Be sure to use the same <code>settings.py</code> as your production instance. </p></li>
<li><p>Be sure your <code>settings.py</code> has the correct driver. You're using SQLite3, be sure that an absolute path name is used. </p></li>
<li><p>Be sure to use the same <code>PYTHONPATH</code> and working directory as production to be sure that all modules are actually found</p></li>
</ul></li>
<li><p>Run ordinary SQL to see that you actually built the database.</p></li>
<li><p>Run the Django <code>/admin</code> application to see what's in the database.</p></li>
</ol>
<p>SQLite3 is included with Python. For it to be missing, your Python installation must be damaged or incomplete. Reinstall from scratch.</p>
| 6 | 2009-07-30T00:19:08Z | [
"python",
"django",
"apache",
"sqlite3",
"mod-wsgi"
] |
Error in Django running on Apache/mod_wsgi | 1,203,448 | <p>Recently i asked a <a href="http://stackoverflow.com/questions/1195260/installing-django-with-modwsgi">question</a> regarding an error in apache/mod_wsgi recognizing the python script directory.
The community kindly answered the question resulting in a successful installation. Now I have a different error, the server daemon (well, technically is a windows service, I say tomato you say...) doesn't find any of the models, here's the full traceback:</p>
<p>Environment:</p>
<pre><code>Request Method: GET
Request URL: `http://localhost/polls/`
Django Version: 1.0.2 final
Python Version: 2.6.2
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'mysite.polls']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware')
</code></pre>
<p>Template error:
In template c:\users\marcos\documents\djangotemplates\polls\poll<code>_</code>list.html, error at line 1
Caught an exception while rendering: no such table: polls_poll </p>
<pre>
1 : {% if object_list %}
2 : <ul>
3 : {% for poll in object_list %}
4 : <li> <a href="{{poll.id}}/">{{ poll.question }} </a> </li>
5 : {% endfor %}
6 : </ul>
7 : {% else %}
8 : <p>No polls are available.</p>
9 : {% endif %}
10 :
</pre>
<p>Traceback: </p>
<pre> File "C:\Python26\lib\site-packages\django\core\handlers\base.py" in get_response
86. response = callback(request, *callback_args, **callback_kwargs)
File "C:\Python26\lib\site-packages\django\views\generic\list_detail.py" in object_list
101. return HttpResponse(t.render(c), mimetype=mimetype)
File "C:\Python26\lib\site-packages\django\template\__init__.py" in render
176. return self.nodelist.render(context)
File "C:\Python26\lib\site-packages\django\template\__init__.py" in render
768. bits.append(self.render_node(node, context))
File "C:\Python26\lib\site-packages\django\template\debug.py" in render_node
81. raise wrapped
</pre>
<pre><code>Exception Type: TemplateSyntaxError at /polls/
Exception Value: Caught an exception while rendering: no such table: polls_poll
</code></pre>
<p>somewhere someone advice me to use <strong>manage.py dbshell</strong> and the script responded:<br />
Error: You appear not to have the 'sqlite3' program installed or on your path.</p>
<p>But still the Django runserver runs the app perfectly. I don't see what changed in the environment to screw the web-app so hard. Please help!</p>
| 1 | 2009-07-29T22:31:34Z | 1,204,119 | <p>I solve the problem adding the sqlite3 binaries directory to the PYTHONPATH environment variable.</p>
| 1 | 2009-07-30T02:18:25Z | [
"python",
"django",
"apache",
"sqlite3",
"mod-wsgi"
] |
Error in Django running on Apache/mod_wsgi | 1,203,448 | <p>Recently i asked a <a href="http://stackoverflow.com/questions/1195260/installing-django-with-modwsgi">question</a> regarding an error in apache/mod_wsgi recognizing the python script directory.
The community kindly answered the question resulting in a successful installation. Now I have a different error, the server daemon (well, technically is a windows service, I say tomato you say...) doesn't find any of the models, here's the full traceback:</p>
<p>Environment:</p>
<pre><code>Request Method: GET
Request URL: `http://localhost/polls/`
Django Version: 1.0.2 final
Python Version: 2.6.2
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'mysite.polls']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware')
</code></pre>
<p>Template error:
In template c:\users\marcos\documents\djangotemplates\polls\poll<code>_</code>list.html, error at line 1
Caught an exception while rendering: no such table: polls_poll </p>
<pre>
1 : {% if object_list %}
2 : <ul>
3 : {% for poll in object_list %}
4 : <li> <a href="{{poll.id}}/">{{ poll.question }} </a> </li>
5 : {% endfor %}
6 : </ul>
7 : {% else %}
8 : <p>No polls are available.</p>
9 : {% endif %}
10 :
</pre>
<p>Traceback: </p>
<pre> File "C:\Python26\lib\site-packages\django\core\handlers\base.py" in get_response
86. response = callback(request, *callback_args, **callback_kwargs)
File "C:\Python26\lib\site-packages\django\views\generic\list_detail.py" in object_list
101. return HttpResponse(t.render(c), mimetype=mimetype)
File "C:\Python26\lib\site-packages\django\template\__init__.py" in render
176. return self.nodelist.render(context)
File "C:\Python26\lib\site-packages\django\template\__init__.py" in render
768. bits.append(self.render_node(node, context))
File "C:\Python26\lib\site-packages\django\template\debug.py" in render_node
81. raise wrapped
</pre>
<pre><code>Exception Type: TemplateSyntaxError at /polls/
Exception Value: Caught an exception while rendering: no such table: polls_poll
</code></pre>
<p>somewhere someone advice me to use <strong>manage.py dbshell</strong> and the script responded:<br />
Error: You appear not to have the 'sqlite3' program installed or on your path.</p>
<p>But still the Django runserver runs the app perfectly. I don't see what changed in the environment to screw the web-app so hard. Please help!</p>
| 1 | 2009-07-29T22:31:34Z | 1,512,070 | <p>Just fixed a problem similar. I think you have to add your app name to the INSTALLED_APPS list in settings.py.</p>
| 0 | 2009-10-02T22:19:33Z | [
"python",
"django",
"apache",
"sqlite3",
"mod-wsgi"
] |
Error in Django running on Apache/mod_wsgi | 1,203,448 | <p>Recently i asked a <a href="http://stackoverflow.com/questions/1195260/installing-django-with-modwsgi">question</a> regarding an error in apache/mod_wsgi recognizing the python script directory.
The community kindly answered the question resulting in a successful installation. Now I have a different error, the server daemon (well, technically is a windows service, I say tomato you say...) doesn't find any of the models, here's the full traceback:</p>
<p>Environment:</p>
<pre><code>Request Method: GET
Request URL: `http://localhost/polls/`
Django Version: 1.0.2 final
Python Version: 2.6.2
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'mysite.polls']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware')
</code></pre>
<p>Template error:
In template c:\users\marcos\documents\djangotemplates\polls\poll<code>_</code>list.html, error at line 1
Caught an exception while rendering: no such table: polls_poll </p>
<pre>
1 : {% if object_list %}
2 : <ul>
3 : {% for poll in object_list %}
4 : <li> <a href="{{poll.id}}/">{{ poll.question }} </a> </li>
5 : {% endfor %}
6 : </ul>
7 : {% else %}
8 : <p>No polls are available.</p>
9 : {% endif %}
10 :
</pre>
<p>Traceback: </p>
<pre> File "C:\Python26\lib\site-packages\django\core\handlers\base.py" in get_response
86. response = callback(request, *callback_args, **callback_kwargs)
File "C:\Python26\lib\site-packages\django\views\generic\list_detail.py" in object_list
101. return HttpResponse(t.render(c), mimetype=mimetype)
File "C:\Python26\lib\site-packages\django\template\__init__.py" in render
176. return self.nodelist.render(context)
File "C:\Python26\lib\site-packages\django\template\__init__.py" in render
768. bits.append(self.render_node(node, context))
File "C:\Python26\lib\site-packages\django\template\debug.py" in render_node
81. raise wrapped
</pre>
<pre><code>Exception Type: TemplateSyntaxError at /polls/
Exception Value: Caught an exception while rendering: no such table: polls_poll
</code></pre>
<p>somewhere someone advice me to use <strong>manage.py dbshell</strong> and the script responded:<br />
Error: You appear not to have the 'sqlite3' program installed or on your path.</p>
<p>But still the Django runserver runs the app perfectly. I don't see what changed in the environment to screw the web-app so hard. Please help!</p>
| 1 | 2009-07-29T22:31:34Z | 8,866,318 | <p>None of these were right for me when I was trying to run manage.py dbshell, but then it is 3 years later, and I'm on 10.7. I added my mysql path to my PATH variable like this:</p>
<p>PATH=$PATH:/usr/local/mysql-5.5.16-osx10.6-x86_64/bin</p>
<p>Actually, it's better to put this into your .profile file. With Mac OS 10.7 you'll probably have to create one of these if you haven't already. From a Terminal window, just enter cd, then hit return to get back to your home directory, then do vi .profile to make the new file, and insert:</p>
<p>export PATH=$PATH:/usr/local/mysql-5.5.16-osx10.6-x86_64/bin</p>
<p>I'm giving a lot of detail here for people who don't know all this off the top of their head, like me. The next time you log in your path will be set automatically. To set it now from the .profile file, just do:</p>
<p>. ./.profile</p>
<p>To verify your new PATH variable, do this:</p>
<p>echo $PATH</p>
| 0 | 2012-01-14T23:36:55Z | [
"python",
"django",
"apache",
"sqlite3",
"mod-wsgi"
] |
How to write an application for the system tray in Linux | 1,203,451 | <p>How do I write my application so it'll live in the system tray on Linux? In fact, just like <a href="http://checkgmail.sourceforge.net/">CheckGmail</a>.</p>
<p>As with CheckGmail, I'd also like some sort of popup box to appear when I hover the tray icon.</p>
<p>Is there an API, class or something for doing this? All I'm able to find seems to be for Windows.</p>
<p>If I have to be language specific, then preferably in C/C++ but a solution in Python will most likely also do.</p>
<p>Thanks.</p>
| 20 | 2009-07-29T22:31:39Z | 1,203,476 | <p>This might help:</p>
<p><a href="http://standards.freedesktop.org/systemtray-spec/systemtray-spec-latest.html">http://standards.freedesktop.org/systemtray-spec/systemtray-spec-latest.html</a></p>
| 11 | 2009-07-29T22:37:45Z | [
"c++",
"python",
"c",
"linux",
"system-tray"
] |
How to write an application for the system tray in Linux | 1,203,451 | <p>How do I write my application so it'll live in the system tray on Linux? In fact, just like <a href="http://checkgmail.sourceforge.net/">CheckGmail</a>.</p>
<p>As with CheckGmail, I'd also like some sort of popup box to appear when I hover the tray icon.</p>
<p>Is there an API, class or something for doing this? All I'm able to find seems to be for Windows.</p>
<p>If I have to be language specific, then preferably in C/C++ but a solution in Python will most likely also do.</p>
<p>Thanks.</p>
| 20 | 2009-07-29T22:31:39Z | 1,203,482 | <h1>python-eggtrayicon</h1>
<p>here's the example that comes with the debian package <code>python-eggtrayicon</code> in debian/testing...</p>
<pre><code>#!/usr/bin/python
import pygtk
pygtk.require("2.0")
import gtk
import egg.trayicon
t = egg.trayicon.TrayIcon("MyFirstTrayIcon")
t.add(gtk.Label("Hello"))
t.show_all()
gtk.main()
</code></pre>
<p>It just shows a label in the notification area . (Search on that, and you'll probably get <em>much</em> better hits...)</p>
| 8 | 2009-07-29T22:38:30Z | [
"c++",
"python",
"c",
"linux",
"system-tray"
] |
How to write an application for the system tray in Linux | 1,203,451 | <p>How do I write my application so it'll live in the system tray on Linux? In fact, just like <a href="http://checkgmail.sourceforge.net/">CheckGmail</a>.</p>
<p>As with CheckGmail, I'd also like some sort of popup box to appear when I hover the tray icon.</p>
<p>Is there an API, class or something for doing this? All I'm able to find seems to be for Windows.</p>
<p>If I have to be language specific, then preferably in C/C++ but a solution in Python will most likely also do.</p>
<p>Thanks.</p>
| 20 | 2009-07-29T22:31:39Z | 1,203,493 | <p><a href="http://qt.nokia.com/" rel="nofollow">Qt</a> is cross platform and has support for the system tray. Its <a href="http://www.riverbankcomputing.co.uk/software/pyqt/download" rel="nofollow">Python bindings</a> are pretty good as well. See the <a href="http://doc.qt.nokia.com/4.5/desktop-systray.html" rel="nofollow">example application</a> for further details.</p>
| 4 | 2009-07-29T22:41:09Z | [
"c++",
"python",
"c",
"linux",
"system-tray"
] |
How to write an application for the system tray in Linux | 1,203,451 | <p>How do I write my application so it'll live in the system tray on Linux? In fact, just like <a href="http://checkgmail.sourceforge.net/">CheckGmail</a>.</p>
<p>As with CheckGmail, I'd also like some sort of popup box to appear when I hover the tray icon.</p>
<p>Is there an API, class or something for doing this? All I'm able to find seems to be for Windows.</p>
<p>If I have to be language specific, then preferably in C/C++ but a solution in Python will most likely also do.</p>
<p>Thanks.</p>
| 20 | 2009-07-29T22:31:39Z | 1,203,504 | <p>The Qt framework contains a <a href="http://doc.qt.io/qt-5/qsystemtrayicon.html" rel="nofollow">QSystemTrayIcon</a> class. This means that you can write an application in C++ or Python (or any other <a href="http://www.qtsoftware.com/products/programming-language-support" rel="nofollow">language with Qt bindings</a>, including C#, Ada, Pascal, Perl, PHP and Ruby) and run your application on Windows, Linux, Mac or any other supported Qt operating system. I should add that Qt applications generally do a pretty good job of looking native on whatever operating system you are using without very much effort (even between Gnome/KDE on Linux). Qt also has excellent documentation, lots of sample code, a generous license and is well-maintained.</p>
| 24 | 2009-07-29T22:42:12Z | [
"c++",
"python",
"c",
"linux",
"system-tray"
] |
How to write an application for the system tray in Linux | 1,203,451 | <p>How do I write my application so it'll live in the system tray on Linux? In fact, just like <a href="http://checkgmail.sourceforge.net/">CheckGmail</a>.</p>
<p>As with CheckGmail, I'd also like some sort of popup box to appear when I hover the tray icon.</p>
<p>Is there an API, class or something for doing this? All I'm able to find seems to be for Windows.</p>
<p>If I have to be language specific, then preferably in C/C++ but a solution in Python will most likely also do.</p>
<p>Thanks.</p>
| 20 | 2009-07-29T22:31:39Z | 30,048,543 | <p>From a python prompt try this.</p>
<pre><code>import gtk
icon = gtk.StatusIcon()
icon.set_from_stock(gtk.STOCK_ABOUT)
gtk.main()
</code></pre>
<p>You should see an icon in the system tray.</p>
<p>See this <a href="http://eurion.net/python-snippets/snippet/Systray%20icon.html" rel="nofollow">snippet</a> for a bigger example.</p>
| 1 | 2015-05-05T09:03:14Z | [
"c++",
"python",
"c",
"linux",
"system-tray"
] |
Django equivalent of New Relic RPM for Rails? | 1,203,494 | <p>Does Django have anything equivalent to the New Relic RPM performance monitoring app for Rails (<a href="http://www.newrelic.com/">http://www.newrelic.com/</a>)?</p>
<p>Looking to do an app in Django, but would really like to be able to use something like New Relic for monitoring performance.</p>
| 7 | 2009-07-29T22:41:10Z | 1,203,543 | <p>None that I'm aware. django-debug-toolbar is a fairly popular app which can provide you with performance info for a particular page, but feature-wise it doesn't even come close to what the New Relic demo shows (I have no experience with NR/RoR myself).</p>
| 3 | 2009-07-29T22:53:15Z | [
"python",
"django"
] |
Django equivalent of New Relic RPM for Rails? | 1,203,494 | <p>Does Django have anything equivalent to the New Relic RPM performance monitoring app for Rails (<a href="http://www.newrelic.com/">http://www.newrelic.com/</a>)?</p>
<p>Looking to do an app in Django, but would really like to be able to use something like New Relic for monitoring performance.</p>
| 7 | 2009-07-29T22:41:10Z | 3,160,780 | <p>Sorry that New Relic doesn't support Python web apps (and therefore Django) at this time, but it is definitely something we are looking at for the long term roadmap. It may be too late for your current requirements, but stay tuned as we continue to build out our footprint. Good luck!</p>
<p>Lew Cirne
Founder and CEO
New Relic</p>
| 2 | 2010-07-01T18:50:25Z | [
"python",
"django"
] |
Django equivalent of New Relic RPM for Rails? | 1,203,494 | <p>Does Django have anything equivalent to the New Relic RPM performance monitoring app for Rails (<a href="http://www.newrelic.com/">http://www.newrelic.com/</a>)?</p>
<p>Looking to do an app in Django, but would really like to be able to use something like New Relic for monitoring performance.</p>
| 7 | 2009-07-29T22:41:10Z | 7,374,925 | <p>YES! We (New Relic) just announced our Python agent at DjangoCon this week. Sign up at newrelic.com and enjoy!</p>
| 7 | 2011-09-10T21:49:58Z | [
"python",
"django"
] |
How do I limit the border size on a matplotlib graph? | 1,203,639 | <p>I'm making some pretty big graphs, and the whitespace in the border is taking up a lot of pixels that would be better used by data. It seems that the border grows as the graph grows.</p>
<p>Here are the guts of my graphing code:</p>
<pre><code> import matplotlib
from pylab import figure
fig = figure()
ax = fig.add_subplot(111)
ax.plot_date((dates, dates), (highs, lows), '-', color='black')
ax.plot_date(dates, closes, '-', marker='_', color='black')
ax.set_title('Title')
ax.grid(True)
fig.set_figheight(96)
fig.set_figwidth(24)
</code></pre>
<p>Is there a way to reduce the size of the border? Maybe a setting somewhere that would allow me to keep the border at a constant 2 inches or so? </p>
| 7 | 2009-07-29T23:29:21Z | 1,204,848 | <p>Try the <a href="http://matplotlib.sourceforge.net/api/figure%5Fapi.html#matplotlib.figure.Figure.subplots%5Fadjust"><code>subplots_adjust</code></a> API:</p>
<blockquote>
<p>subplots_adjust(*args, **kwargs)</p>
<p>fig.subplots_adjust(left=None, bottom=None, right=None, wspace=None, hspace=None)</p>
<p>Update the SubplotParams with kwargs (defaulting to rc where None) and update the subplot locations</p>
</blockquote>
| 5 | 2009-07-30T06:45:10Z | [
"python",
"graph",
"matplotlib",
"plot"
] |
How do I limit the border size on a matplotlib graph? | 1,203,639 | <p>I'm making some pretty big graphs, and the whitespace in the border is taking up a lot of pixels that would be better used by data. It seems that the border grows as the graph grows.</p>
<p>Here are the guts of my graphing code:</p>
<pre><code> import matplotlib
from pylab import figure
fig = figure()
ax = fig.add_subplot(111)
ax.plot_date((dates, dates), (highs, lows), '-', color='black')
ax.plot_date(dates, closes, '-', marker='_', color='black')
ax.set_title('Title')
ax.grid(True)
fig.set_figheight(96)
fig.set_figwidth(24)
</code></pre>
<p>Is there a way to reduce the size of the border? Maybe a setting somewhere that would allow me to keep the border at a constant 2 inches or so? </p>
| 7 | 2009-07-29T23:29:21Z | 1,207,711 | <p>Since it looks like you're just using a single subplot, you may want to skip <code>add_subplot</code> and go straight to <a href="http://matplotlib.sourceforge.net/api/figure%5Fapi.html#matplotlib.figure.Figure.add%5Faxes"><code>add_axes</code></a>. This will allow you to give the size of the axes (in figure-relative coordinates), so you can make it as large as you want within the figure. In your case, this would mean your code would look something like</p>
<pre><code> import matplotlib.pyplot as plt
fig = plt.figure()
# add_axes takes [left, bottom, width, height]
border_width = 0.05
ax_size = [0+border_width, 0+border_width,
1-2*border_width, 1-2*border-width]
ax = fig.add_axes(ax_size)
ax.plot_date((dates, dates), (highs, lows), '-', color='black')
ax.plot_date(dates, closes, '-', marker='_', color='black')
ax.set_title('Title')
ax.grid(True)
fig.set_figheight(96)
fig.set_figwidth(24)
</code></pre>
<p>If you wanted, you could even put the parameters to <code>set_figheight</code>/<code>set_figwidth</code> directly in the <code>figure()</code> call.</p>
| 6 | 2009-07-30T16:23:51Z | [
"python",
"graph",
"matplotlib",
"plot"
] |
JTIP file format reader for python | 1,203,640 | <p>I have to work with some image files. They are named as .png and .jpg, but I tried 3 different image viewers, and none of them could open the files. I found out that the first 8 bytes of these files were CF10rUrm, and DROID told me it was a JTIP (JPEG Tiled Image Pyramid).</p>
<p>I need to use these from Python. Does anybody know of any way to either view these image files, convert them to another format, or, (a bit of a stretch), to read them directly from Python? (I've tried PIL already, and it doesn't recognize them.)</p>
<p>I know it's possible, since the program that uses these image files can view them. It's not open source, however.</p>
| 1 | 2009-07-29T23:29:31Z | 1,203,861 | <p>With a fast search I found a <a href="http://adrresources.coalliance.org/wiki/index.php/Tiler_Python_Code" rel="nofollow">Python script</a> that might do what you want.</p>
| -1 | 2009-07-30T00:42:48Z | [
"python",
"image",
"file",
"jpeg"
] |
Django and fcgi - logging question | 1,203,896 | <p>I have a site running in Django. Frontend is lighttpd and is using fcgi to host django.</p>
<p>I start my fcgi processes as follows:</p>
<pre><code>python2.6 /<snip>/manage.py runfcgi maxrequests=10 host=127.0.0.1 port=8000 pidfile=django.pid
</code></pre>
<p>For logging, I have a RotatingFileHandler defined as follows:</p>
<pre><code>file_handler = RotatingFileHandler(filename, maxBytes=10*1024*1024, backupCount=5,encoding='utf-8')
</code></pre>
<p>The logging is working. However, it looks like the files are rotating when they do not even get up to 10Kb, let alone 10Mb. My guess is that each fcgi instance is only handling 10 requests, and then re-spawning. Each respawn of fcgi creates a new file. I confirm that fcgi is starting up under new process id every so often (hard to tell time exactly, but under a minute).</p>
<p>Is there any way to get around this issues? I would like all fcgi instances logging to one file until it reaches the size limit, at which point a log file rotation would take place.</p>
| 5 | 2009-07-30T00:52:03Z | 1,204,141 | <p>In your shoes I'd switch to a <a href="http://docs.python.org/library/logging.handlers.html#timedrotatingfilehandler" rel="nofollow">TimedRotatingFileHandler</a> -- I'm surprised that the size-based rotating file handles is giving this problem (as it should be impervious to what processes are producing the log entries), but the timed version (though not controlled on exactly the parameter you prefer) should solve it. Or, write your own, more solid, rotating file handler (you can take a lot from the standard library sources) that <em>ensures</em> varying processes are not a problem (as they should never be).</p>
| 2 | 2009-07-30T02:25:32Z | [
"python",
"django",
"logging",
"fastcgi",
"lighttpd"
] |
Django and fcgi - logging question | 1,203,896 | <p>I have a site running in Django. Frontend is lighttpd and is using fcgi to host django.</p>
<p>I start my fcgi processes as follows:</p>
<pre><code>python2.6 /<snip>/manage.py runfcgi maxrequests=10 host=127.0.0.1 port=8000 pidfile=django.pid
</code></pre>
<p>For logging, I have a RotatingFileHandler defined as follows:</p>
<pre><code>file_handler = RotatingFileHandler(filename, maxBytes=10*1024*1024, backupCount=5,encoding='utf-8')
</code></pre>
<p>The logging is working. However, it looks like the files are rotating when they do not even get up to 10Kb, let alone 10Mb. My guess is that each fcgi instance is only handling 10 requests, and then re-spawning. Each respawn of fcgi creates a new file. I confirm that fcgi is starting up under new process id every so often (hard to tell time exactly, but under a minute).</p>
<p>Is there any way to get around this issues? I would like all fcgi instances logging to one file until it reaches the size limit, at which point a log file rotation would take place.</p>
| 5 | 2009-07-30T00:52:03Z | 1,206,060 | <p>As you appear to be using the default file opening mode of append ("a") rather than write ("w"), if a process re-spawns it should append to the existing file, then rollover when the size limit is reached. So I am not sure that what you are seeing is caused by re-spawning CGI processes. (This of course assumes that the filename remains the same when the process re-spawns).</p>
<p>Although the logging package is thread-safe, it does not handle concurrent access to the same file from multiple processes - because there is no standard way to do it in the stdlib. My normal advice is to set up a separate daemon process which implements a socket server and logs events received across it to file - the other processes then just implement a SocketHandler to communicate with the logging daemon. Then all events will get serialised to disk properly. The Python documentation contains a <a href="http://docs.python.org/library/logging.html#sending-and-receiving-logging-events-across-a-network" rel="nofollow">working socket server</a> which could serve as a basis for this need.</p>
| 0 | 2009-07-30T11:40:40Z | [
"python",
"django",
"logging",
"fastcgi",
"lighttpd"
] |
Django and fcgi - logging question | 1,203,896 | <p>I have a site running in Django. Frontend is lighttpd and is using fcgi to host django.</p>
<p>I start my fcgi processes as follows:</p>
<pre><code>python2.6 /<snip>/manage.py runfcgi maxrequests=10 host=127.0.0.1 port=8000 pidfile=django.pid
</code></pre>
<p>For logging, I have a RotatingFileHandler defined as follows:</p>
<pre><code>file_handler = RotatingFileHandler(filename, maxBytes=10*1024*1024, backupCount=5,encoding='utf-8')
</code></pre>
<p>The logging is working. However, it looks like the files are rotating when they do not even get up to 10Kb, let alone 10Mb. My guess is that each fcgi instance is only handling 10 requests, and then re-spawning. Each respawn of fcgi creates a new file. I confirm that fcgi is starting up under new process id every so often (hard to tell time exactly, but under a minute).</p>
<p>Is there any way to get around this issues? I would like all fcgi instances logging to one file until it reaches the size limit, at which point a log file rotation would take place.</p>
| 5 | 2009-07-30T00:52:03Z | 2,149,920 | <p>As Alex stated, logging is thread-safe, but the standard handlers cannot be safely used to log from multiple processes into a single file.</p>
<p><a href="http://pypi.python.org/pypi/ConcurrentLogHandler/0.8.2">ConcurrentLogHandler</a> uses file locking to allow for logging from within multiple processes.</p>
| 6 | 2010-01-27T20:12:10Z | [
"python",
"django",
"logging",
"fastcgi",
"lighttpd"
] |
NoReverseMatch Exception help in Django | 1,204,138 | <p>I'm fairly new to python and following along with part 4 of the tutorial for the Django framework <a href="http://docs.djangoproject.com/en/1.0/intro/tutorial04/#intro-tutorial04">here</a>. I'm trying to implement generic views for the polls app--my code seems correct (as far as I can tell), but when I try to vote, I get a NoReverseMatch Exception that states: </p>
<blockquote>
<p>Reverse for 'polls/poll_results' with arguments '(1L,)' and keyword arguments '{}' not found.</p>
</blockquote>
<p>My code was working perfectly before I attempted the generic views, but I can't seem pinpoint the problem now.</p>
<p>Here's the code for my urls.py in the poll directory:</p>
<pre><code>from django.conf.urls.defaults import *
from djtest.polls.models import Poll
info_dict = {
'queryset': Poll.objects.all(),
}
urlpatterns = patterns('',
(r'^$', 'django.views.generic.list_detail.object_list', info_dict),
(r'^(?P<object_id>\d+)/$', 'django.views.generic.list_detail.object_detail', info_dict),
url(r'^(?P<object_id>\d+)/results/$', 'django.views.generic.list_detail.object_detail', dict(info_dict, template_name='polls/results.html'), 'poll_results'),
(r'^(?P<poll_id>\d+)/vote/$', 'djtest.polls.views.vote'),
)
</code></pre>
<p>And here is the views.py:</p>
<pre><code>from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.core.urlresolvers import reverse
from djtest.polls.models import Poll, Choice
def vote(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
#redisplay form
return render_to_response('polls/poll_detail.html', {
'object': p,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('poll_results', args=(p.id,)))
</code></pre>
<p>I have a feeling that it is a syntactical error, but I can't find it. Thanks in advance for any help...</p>
| 10 | 2009-07-30T02:24:17Z | 1,204,314 | <p>Try using:</p>
<pre><code>return HttpResponseRedirect(reverse('poll_results', kwargs={'object_id': p.id}))
</code></pre>
| 5 | 2009-07-30T03:27:37Z | [
"python",
"django",
"exception",
"syntax",
"django-generic-views"
] |
NoReverseMatch Exception help in Django | 1,204,138 | <p>I'm fairly new to python and following along with part 4 of the tutorial for the Django framework <a href="http://docs.djangoproject.com/en/1.0/intro/tutorial04/#intro-tutorial04">here</a>. I'm trying to implement generic views for the polls app--my code seems correct (as far as I can tell), but when I try to vote, I get a NoReverseMatch Exception that states: </p>
<blockquote>
<p>Reverse for 'polls/poll_results' with arguments '(1L,)' and keyword arguments '{}' not found.</p>
</blockquote>
<p>My code was working perfectly before I attempted the generic views, but I can't seem pinpoint the problem now.</p>
<p>Here's the code for my urls.py in the poll directory:</p>
<pre><code>from django.conf.urls.defaults import *
from djtest.polls.models import Poll
info_dict = {
'queryset': Poll.objects.all(),
}
urlpatterns = patterns('',
(r'^$', 'django.views.generic.list_detail.object_list', info_dict),
(r'^(?P<object_id>\d+)/$', 'django.views.generic.list_detail.object_detail', info_dict),
url(r'^(?P<object_id>\d+)/results/$', 'django.views.generic.list_detail.object_detail', dict(info_dict, template_name='polls/results.html'), 'poll_results'),
(r'^(?P<poll_id>\d+)/vote/$', 'djtest.polls.views.vote'),
)
</code></pre>
<p>And here is the views.py:</p>
<pre><code>from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.core.urlresolvers import reverse
from djtest.polls.models import Poll, Choice
def vote(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
#redisplay form
return render_to_response('polls/poll_detail.html', {
'object': p,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('poll_results', args=(p.id,)))
</code></pre>
<p>I have a feeling that it is a syntactical error, but I can't find it. Thanks in advance for any help...</p>
| 10 | 2009-07-30T02:24:17Z | 1,204,537 | <p>Are you sure that's where your error really is? Based on the error message, it sounds like either in a view or in a template you are trying to reverse <code>'polls/poll_results'</code> (in a template, you may be doing something like <code>{% url polls/poll_results poll.pk %}</code>)</p>
| 1 | 2009-07-30T05:03:00Z | [
"python",
"django",
"exception",
"syntax",
"django-generic-views"
] |
NoReverseMatch Exception help in Django | 1,204,138 | <p>I'm fairly new to python and following along with part 4 of the tutorial for the Django framework <a href="http://docs.djangoproject.com/en/1.0/intro/tutorial04/#intro-tutorial04">here</a>. I'm trying to implement generic views for the polls app--my code seems correct (as far as I can tell), but when I try to vote, I get a NoReverseMatch Exception that states: </p>
<blockquote>
<p>Reverse for 'polls/poll_results' with arguments '(1L,)' and keyword arguments '{}' not found.</p>
</blockquote>
<p>My code was working perfectly before I attempted the generic views, but I can't seem pinpoint the problem now.</p>
<p>Here's the code for my urls.py in the poll directory:</p>
<pre><code>from django.conf.urls.defaults import *
from djtest.polls.models import Poll
info_dict = {
'queryset': Poll.objects.all(),
}
urlpatterns = patterns('',
(r'^$', 'django.views.generic.list_detail.object_list', info_dict),
(r'^(?P<object_id>\d+)/$', 'django.views.generic.list_detail.object_detail', info_dict),
url(r'^(?P<object_id>\d+)/results/$', 'django.views.generic.list_detail.object_detail', dict(info_dict, template_name='polls/results.html'), 'poll_results'),
(r'^(?P<poll_id>\d+)/vote/$', 'djtest.polls.views.vote'),
)
</code></pre>
<p>And here is the views.py:</p>
<pre><code>from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.core.urlresolvers import reverse
from djtest.polls.models import Poll, Choice
def vote(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
#redisplay form
return render_to_response('polls/poll_detail.html', {
'object': p,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('poll_results', args=(p.id,)))
</code></pre>
<p>I have a feeling that it is a syntactical error, but I can't find it. Thanks in advance for any help...</p>
| 10 | 2009-07-30T02:24:17Z | 8,859,723 | <p>I've tried the solution provided as answer and didn't worked for me. In my case i was getting the same error (following the same tutorial) and the problem was that the name of the view in the urls.py file was a bit different that in the views.py (because a typing error).</p>
| 0 | 2012-01-14T02:38:46Z | [
"python",
"django",
"exception",
"syntax",
"django-generic-views"
] |
NoReverseMatch Exception help in Django | 1,204,138 | <p>I'm fairly new to python and following along with part 4 of the tutorial for the Django framework <a href="http://docs.djangoproject.com/en/1.0/intro/tutorial04/#intro-tutorial04">here</a>. I'm trying to implement generic views for the polls app--my code seems correct (as far as I can tell), but when I try to vote, I get a NoReverseMatch Exception that states: </p>
<blockquote>
<p>Reverse for 'polls/poll_results' with arguments '(1L,)' and keyword arguments '{}' not found.</p>
</blockquote>
<p>My code was working perfectly before I attempted the generic views, but I can't seem pinpoint the problem now.</p>
<p>Here's the code for my urls.py in the poll directory:</p>
<pre><code>from django.conf.urls.defaults import *
from djtest.polls.models import Poll
info_dict = {
'queryset': Poll.objects.all(),
}
urlpatterns = patterns('',
(r'^$', 'django.views.generic.list_detail.object_list', info_dict),
(r'^(?P<object_id>\d+)/$', 'django.views.generic.list_detail.object_detail', info_dict),
url(r'^(?P<object_id>\d+)/results/$', 'django.views.generic.list_detail.object_detail', dict(info_dict, template_name='polls/results.html'), 'poll_results'),
(r'^(?P<poll_id>\d+)/vote/$', 'djtest.polls.views.vote'),
)
</code></pre>
<p>And here is the views.py:</p>
<pre><code>from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.core.urlresolvers import reverse
from djtest.polls.models import Poll, Choice
def vote(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
#redisplay form
return render_to_response('polls/poll_detail.html', {
'object': p,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('poll_results', args=(p.id,)))
</code></pre>
<p>I have a feeling that it is a syntactical error, but I can't find it. Thanks in advance for any help...</p>
| 10 | 2009-07-30T02:24:17Z | 11,946,236 | <p>I could not find any explanation that fixed the problem, until I ran across this person's abridged Django tutorial: <a href="http://tony.abou-assaleh.net/web-development/stripped-down-django-tutorial" rel="nofollow">http://tony.abou-assaleh.net/web-development/stripped-down-django-tutorial</a></p>
<p>It's basically a line in the details template, which should be:</p>
<pre><code><form action="/polls/{{ poll.id }}/vote/" method="post">
</code></pre>
<p>Instead of:</p>
<pre><code><form action="{% url 'polls.views.vote' poll.id %}" method="post">
</code></pre>
<p>I'm not sure why this fixed the issue, but it did for me. I'd love an explanation if anyone has one.</p>
| 1 | 2012-08-14T05:29:31Z | [
"python",
"django",
"exception",
"syntax",
"django-generic-views"
] |
Python: \number Backreference in re.sub | 1,204,223 | <p>I'm trying to use python's re.sub function to replace some text.</p>
<pre><code>>>> import re
>>> text = "<hi type=\"italic\"> the></hi>"
>>> pat_error = re.compile(">(\s*\w*)*>")
>>> pat_error.search(text)
<_sre.SRE_Match object at 0xb7a3fea0>
>>> re.sub(pat_error, ">\1", text)
'<hi type="italic">\x01</hi>'
</code></pre>
<p>Afterwards the value of text should be </p>
<pre><code>"<hi type="italic"> the</hi>"
</code></pre>
| 1 | 2009-07-30T03:01:34Z | 1,204,239 | <pre><code>>>> text.replace("><", "<")
'<hi type="italic"> the</hi>'
</code></pre>
| 0 | 2009-07-30T03:05:21Z | [
"python",
"regex",
"backreference"
] |
Python: \number Backreference in re.sub | 1,204,223 | <p>I'm trying to use python's re.sub function to replace some text.</p>
<pre><code>>>> import re
>>> text = "<hi type=\"italic\"> the></hi>"
>>> pat_error = re.compile(">(\s*\w*)*>")
>>> pat_error.search(text)
<_sre.SRE_Match object at 0xb7a3fea0>
>>> re.sub(pat_error, ">\1", text)
'<hi type="italic">\x01</hi>'
</code></pre>
<p>Afterwards the value of text should be </p>
<pre><code>"<hi type="italic"> the</hi>"
</code></pre>
| 1 | 2009-07-30T03:01:34Z | 1,204,270 | <p>Two bugs in your code. First, you're not matching (and specifically, capturing) what you think you're matching and capturing -- insert after your call to <code>.search</code>:</p>
<pre><code>>>> _.groups()
('',)
</code></pre>
<p>The unconstrained repetition of repetitions (star after a capturing group with nothing but stars) matches once too many -- with the empty string at the end of what you think you're matchin -- and that's what gets captured. Fix by changing at least one of the stars to a plus, e.g., by:</p>
<pre><code>>>> pat_error = re.compile(r">(\s*\w+)*>")
>>> pat_error.search(text)
<_sre.SRE_Match object at 0x83ba0>
>>> _.groups()
(' the',)
</code></pre>
<p>Now THIS matches and captures sensibly. Second, youre not using raw string literal syntax where you should, so you don't have a backslash where you think you have one -- you have an escape sequence <code>\1</code> which is the same as chr(1). Fix by using raw string literal syntax, i.e. after the above snippet</p>
<pre><code>>>> pat_error.sub(r">\1", text)
'<hi type="italic"> the</hi>'
</code></pre>
<p>Alternatively you could double up all of your backslashes, to avoid them being taken as the start of escape sequences -- but, raw string literal syntax is much more readable.</p>
| 9 | 2009-07-30T03:13:55Z | [
"python",
"regex",
"backreference"
] |
\r\n vs \n in python eval function | 1,204,376 | <p>Why eval function doesn't work with \r\n but with \n. for example
eval("for i in range(5):\r\n print 'hello'") doesn't work
eval("for i in range(5):\n print 'hello'") works</p>
<p>I know there is not a problem cause using replace("\r","") is corrected, but someone knows why happens?</p>
<p>--Edit--
Oh! sorry , exactly, I meant exec. Carriage returns appeared because I'm reading from a HTML textarea via POST (I'm on a Linux box). now It is clearer, thanks to everyone.</p>
| 4 | 2009-07-30T03:51:23Z | 1,204,403 | <p>Do you mean eval or exec? Please post exactly what you ran, plus the full traceback and error message.</p>
<p>The problem is probably because the Python grammar says that lines are terminated by newlines ('\n'), not the two-character sequence '\r\n'.</p>
<p>In general, it would be safer for you to use replace('\r\n', '\n') in case there's a meaningful '\r' in there somewhere. It would be better if you didn't have the '\r' there in the first place ... how are you obtaining the text -- binary read on a Windows box??</p>
<p>Talking about safety, you should be careful about using eval or exec on any old code obtained from a possible enemy.</p>
| 1 | 2009-07-30T04:03:51Z | [
"python",
"eval"
] |
\r\n vs \n in python eval function | 1,204,376 | <p>Why eval function doesn't work with \r\n but with \n. for example
eval("for i in range(5):\r\n print 'hello'") doesn't work
eval("for i in range(5):\n print 'hello'") works</p>
<p>I know there is not a problem cause using replace("\r","") is corrected, but someone knows why happens?</p>
<p>--Edit--
Oh! sorry , exactly, I meant exec. Carriage returns appeared because I'm reading from a HTML textarea via POST (I'm on a Linux box). now It is clearer, thanks to everyone.</p>
| 4 | 2009-07-30T03:51:23Z | 1,204,472 | <p>You have a strange definition of "work":</p>
<pre><code>>>> eval("for i in range(5):\n print 'hello'")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
for i in range(5):
^
SyntaxError: invalid syntax
>>>
</code></pre>
<p>I'm not sure why you're using <code>eval</code> -- I suspect you mean <code>exec</code>. Expressions and statements are drastically different entities in Python -- <code>eval</code> only deals with expressions (a bare expression <em>is</em> also a statement, so <code>exec</code> can deal with it as well as other statements).</p>
<p>Turning to <code>exec</code>, and pondering the situation as a Python core committer, I think it's a minor mis-design: just like (redundant and useless) spaces, tabs and form feeds just before a NEWLINE are accepted and ignored, so should (just as redundant and useless) carriage returns be. I apologize: I think we never ever considered that somebody might <em>want</em> to put carriage returns there -- but then, it doesn't make any more sense to have e.g. form feeds there, and we do accept <em>that</em>... so I see no rationale for rejecting carriage returns (or other Unicode non-ANSI whitespace, either, now that in Python 3 we accept arbitrary Unicode non-ANSI alphanumerics in identifiers).</p>
<p>If you care, please open an issue on Python's issue tracker, and (barring unforeseen opposition by other commiters) I think I can get it fixed by Python 3.2 (which should be out in 12 to 18 months -- that's an estimate [informed guess], not a promise;-).</p>
| 6 | 2009-07-30T04:37:45Z | [
"python",
"eval"
] |
Getting total/free RAM from within Python | 1,204,378 | <p>From within a Python application, how can I get the total amount of RAM of the system and how much of it is currently free, in a cross-platform way?</p>
<p>Ideally, the amount of free RAM should consider only physical memory that can actually be allocated to the Python process.</p>
| 9 | 2009-07-30T03:52:42Z | 1,204,394 | <p>You can't do this with just the standard Python library, although there might be some third party package that does it. Barring that, you can use the os package to determine which operating system you're on and use that information to acquire the info you want for that system (and encapsulate that into a single cross-platform function).</p>
| 3 | 2009-07-30T03:59:07Z | [
"python",
"wxpython"
] |
Getting total/free RAM from within Python | 1,204,378 | <p>From within a Python application, how can I get the total amount of RAM of the system and how much of it is currently free, in a cross-platform way?</p>
<p>Ideally, the amount of free RAM should consider only physical memory that can actually be allocated to the Python process.</p>
| 9 | 2009-07-30T03:52:42Z | 1,204,410 | <p>Have you tried <a href="http://support.hyperic.com/display/SIGAR/Home">SIGAR - System Information Gatherer And Reporter</a>?
After install</p>
<pre><code>import os, sigar
sg = sigar.open()
mem = sg.mem()
sg.close()
print mem.total() / 1024, mem.free() / 1024
</code></pre>
<p>Hope this helps</p>
| 12 | 2009-07-30T04:06:21Z | [
"python",
"wxpython"
] |
Getting total/free RAM from within Python | 1,204,378 | <p>From within a Python application, how can I get the total amount of RAM of the system and how much of it is currently free, in a cross-platform way?</p>
<p>Ideally, the amount of free RAM should consider only physical memory that can actually be allocated to the Python process.</p>
| 9 | 2009-07-30T03:52:42Z | 1,204,839 | <p>For the free memory part, there is a function in the wx library:</p>
<pre><code>wx.GetFreeMemory()
</code></pre>
<p>Unfortunately, this only works on Windows. Linux and Mac ports either return "-1" or raise a <code>NotImplementedError</code>.</p>
| 6 | 2009-07-30T06:43:20Z | [
"python",
"wxpython"
] |
Getting total/free RAM from within Python | 1,204,378 | <p>From within a Python application, how can I get the total amount of RAM of the system and how much of it is currently free, in a cross-platform way?</p>
<p>Ideally, the amount of free RAM should consider only physical memory that can actually be allocated to the Python process.</p>
| 9 | 2009-07-30T03:52:42Z | 14,371,887 | <p><a href="http://code.google.com/p/psutil/">psutil</a> would be another good choice. It also needs a library installed however.</p>
<pre><code>>>> import psutil
>>> psutil.virtual_memory()
vmem(total=8374149120L, available=2081050624L, percent=75.1,
used=8074080256L, free=300068864L, active=3294920704,
inactive=1361616896, buffers=529895424L, cached=1251086336)
</code></pre>
| 6 | 2013-01-17T03:41:47Z | [
"python",
"wxpython"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.