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
list
In Python, how to make data members visible to subclasses if not known when initializing an object?
2,566,840
<p>The title is a bit long, but it should be pretty straightforward for someone well-aware of python.</p> <p>I'm a python newbie. So, maybe i'm doing things in the wrong way.</p> <p>Suppose I have a class TreeNode</p> <pre><code>class TreeNode(Node): def __init__(self, name, id): Node.__init__(self, name...
1
2010-04-02T13:26:59Z
2,566,853
<p>You could just initialize it with a default value:</p> <pre><code>self.father = None </code></pre> <p>That way the attribute will at least be recognized. And this is valid since at this point there really is no <code>father</code>.</p>
2
2010-04-02T13:30:59Z
[ "python" ]
In Python, how to make data members visible to subclasses if not known when initializing an object?
2,566,840
<p>The title is a bit long, but it should be pretty straightforward for someone well-aware of python.</p> <p>I'm a python newbie. So, maybe i'm doing things in the wrong way.</p> <p>Suppose I have a class TreeNode</p> <pre><code>class TreeNode(Node): def __init__(self, name, id): Node.__init__(self, name...
1
2010-04-02T13:26:59Z
2,566,885
<p>In response to your statement on Justin's answer, try this:</p> <pre><code>print ' Name %s Father %s '%(str(self.name), str(self.father.name)) </code></pre> <p>The str() command will get a string representation of an object even if it's <code>None</code></p>
0
2010-04-02T13:36:42Z
[ "python" ]
Django logging features?
2,567,046
<p>I need to run a lot of Django management commands in the crontab and want to log the output of each run to a special timestamped file. Is there a Django or Python module to help me do this or do I just have to roll my own?</p>
1
2010-04-02T14:11:12Z
2,567,210
<p>You can use the Python logging package which is part of Python, see <a href="http://stackoverflow.com/questions/1598823/elegant-setup-of-python-logging-in-django/1598979#1598979">my answer</a> to another question about elegant setup of logging in Django. You can inspect <code>sys.argv</code> to determine how you wan...
3
2010-04-02T14:40:42Z
[ "python", "django" ]
Django logging features?
2,567,046
<p>I need to run a lot of Django management commands in the crontab and want to log the output of each run to a special timestamped file. Is there a Django or Python module to help me do this or do I just have to roll my own?</p>
1
2010-04-02T14:11:12Z
2,567,525
<p>Have a look at <a href="http://github.com/zain/jogging" rel="nofollow">django-jogging</a>. It's a breeze to set up all kinds of custom logging with it.</p>
2
2010-04-02T15:36:00Z
[ "python", "django" ]
Django logging features?
2,567,046
<p>I need to run a lot of Django management commands in the crontab and want to log the output of each run to a special timestamped file. Is there a Django or Python module to help me do this or do I just have to roll my own?</p>
1
2010-04-02T14:11:12Z
5,872,783
<p>as of django 1.3 a better logging configuration approach is available. please check my answer to.. the same question pointed at by Vinay :-)</p> <p><a href="http://stackoverflow.com/questions/1598823/elegant-setup-of-python-logging-in-django/5806903#5806903">Elegant setup of Python logging in Django</a></p>
1
2011-05-03T16:40:43Z
[ "python", "django" ]
Python class structure ... prep() method?
2,567,238
<p>We have a metaclass, a class, and a child class for an alert system:</p> <pre><code>class AlertMeta(type): """ Metaclass for all alerts Reads attrs and organizes AlertMessageType data """ def __new__(cls, base, name, attrs): new_class = super(AlertMeta, cls).__new__(cls, base, name, attrs) # do stuff to...
0
2010-04-02T14:44:10Z
2,568,239
<p>For our particular issue, we're making dequeue() a classmethod.</p>
0
2010-04-02T17:51:07Z
[ "python" ]
Calculating Nearest Match to Mean/Stddev Pair With LibSVM
2,567,483
<p>I'm new to SVMs, and I'm trying to use the Python interface to <a href="http://www.csie.ntu.edu.tw/~cjlin/libsvm/">libsvm</a> to classify a sample containing a mean and stddev. However, I'm getting nonsensical results.</p> <p>Is this task inappropriate for SVMs or is there an error in my use of libsvm? Below is the...
6
2010-04-02T15:29:25Z
2,569,372
<p>If you are interested in a different way of doing this, you could do the following. This way is theoretically more sound, however not as straightforward.</p> <p>By mentioning mean and std, it seems as if you refer to data that you assume to be distributed in some way. E.g., the data you observer is Gaussian distrib...
3
2010-04-02T21:44:19Z
[ "python", "artificial-intelligence", "machine-learning", "svm", "libsvm" ]
Calculating Nearest Match to Mean/Stddev Pair With LibSVM
2,567,483
<p>I'm new to SVMs, and I'm trying to use the Python interface to <a href="http://www.csie.ntu.edu.tw/~cjlin/libsvm/">libsvm</a> to classify a sample containing a mean and stddev. However, I'm getting nonsensical results.</p> <p>Is this task inappropriate for SVMs or is there an error in my use of libsvm? Below is the...
6
2010-04-02T15:29:25Z
2,570,217
<p>The problem seems to be coming from combining multiclass prediction with probability estimates.</p> <p><strong>If you configure your code not to make probability estimates, it actually works</strong>, e.g.:</p> <pre><code>&lt;snip&gt; # Test classifiers. kernels = [LINEAR, POLY, RBF] kname = ['linear','polynomial'...
5
2010-04-03T04:25:06Z
[ "python", "artificial-intelligence", "machine-learning", "svm", "libsvm" ]
Decorator for determining HTTP response from a view
2,567,570
<p>I want to create a decorator that will allow me to return a raw or "string" representation of a view if a GET parameter "raw" equals "1". The concept works, but I'm stuck on how to pass context to my renderer. Here's what I have so far:</p> <pre><code>from django.shortcuts import render_to_response from django.ht...
1
2010-04-02T15:45:42Z
2,567,633
<p>You just need to call <code>view</code> from within your decorator and use the context returned from that.</p> <pre><code>if request.method == "GET": context = view(*args, **kwargs) try: if request.GET['raw'] == "1": render = HttpResponse( render_to_string(templa...
0
2010-04-02T15:57:57Z
[ "python", "django", "decorator" ]
Decorator for determining HTTP response from a view
2,567,570
<p>I want to create a decorator that will allow me to return a raw or "string" representation of a view if a GET parameter "raw" equals "1". The concept works, but I'm stuck on how to pass context to my renderer. Here's what I have so far:</p> <pre><code>from django.shortcuts import render_to_response from django.ht...
1
2010-04-02T15:45:42Z
2,567,643
<p>Have your real view method return something sensible (a context <code>dict</code> in this case) and call it.</p> <pre><code>def raw_response(template): def wrap(view): def response(request, *args, **kwargs): context = view(request, *args, **kwargs) if request.method == 'GET' and ...
0
2010-04-02T15:59:48Z
[ "python", "django", "decorator" ]
Disco/MapReduce: Using chain_reader on split data
2,567,617
<p>My algorithm currently uses nr_reduces 1 because I need to ensure that the data for a given key is aggregated.</p> <p>To pass input to the next iteration, one should use "chain_reader". However, the results from a mapper are as a single result list, and it appears this means that the next map iteration takes place...
2
2010-04-02T15:54:04Z
16,132,367
<p>I could give a long answer but since this question is 3 years old: check out this page: <a href="http://discoproject.org/doc/disco/howto/dataflow.html#single-partition-map" rel="nofollow">http://discoproject.org/doc/disco/howto/dataflow.html#single-partition-map</a></p> <p>In short: When there is N input for the ma...
0
2013-04-21T14:48:00Z
[ "python", "mapreduce", "disco" ]
Using pam_python in a script running with mod_python
2,567,705
<p>I would like to develop a web interface to allow users of a Linux system to do certain tasks related to their account. I decided to write the backend of the site using Python and mod_python on Apache. To authenticate the users, I thought I could use <a href="http://packages.debian.org/squeeze/python-pam" rel="nofoll...
2
2010-04-02T16:10:19Z
2,569,376
<p>It seems like you have to enable Apache to use PAM authentication. Take a look at this site: <a href="http://www.debianhelp.co.uk/apachepam.htm" rel="nofollow">http://www.debianhelp.co.uk/apachepam.htm</a></p> <p>You might want to take a look at this site too : <a href="http://inming.net/?p=86" rel="nofollow">http:...
0
2010-04-02T21:46:34Z
[ "python", "linux", "mod-python", "pam" ]
Browser simulation - Python
2,567,738
<p>I need to access a few HTML pages through a Python script, problem is that I need COOKIE functionality, therefore a simple urllib HTTP request won't work.</p> <p>Any ideas?</p>
7
2010-04-02T16:16:12Z
2,567,803
<p>Here's something that does cookies, and as a bonus does authentication for a site that requires a username and password.</p> <pre><code>import urllib2 import cookielib import string def cook(): url="http://wherever" cj = cookielib.LWPCookieJar() authinfo = urllib2.HTTPBasicAuthHandler() realm="re...
2
2010-04-02T16:30:42Z
[ "python", "session", "browser", "cookies" ]
Browser simulation - Python
2,567,738
<p>I need to access a few HTML pages through a Python script, problem is that I need COOKIE functionality, therefore a simple urllib HTTP request won't work.</p> <p>Any ideas?</p>
7
2010-04-02T16:16:12Z
2,567,804
<p>The <a href="http://docs.python.org/library/cookielib.html#module-cookielib" rel="nofollow">cookielib module</a> provides cookie handling for HTTP clients.</p> <blockquote> <p>The <a href="http://docs.python.org/library/cookielib.html#module-cookielib" rel="nofollow">cookielib</a> module defines classes for auto...
3
2010-04-02T16:30:44Z
[ "python", "session", "browser", "cookies" ]
Browser simulation - Python
2,567,738
<p>I need to access a few HTML pages through a Python script, problem is that I need COOKIE functionality, therefore a simple urllib HTTP request won't work.</p> <p>Any ideas?</p>
7
2010-04-02T16:16:12Z
2,567,841
<p>check out <a href="http://wwwsearch.sourceforge.net/mechanize/">Mechanize</a>. "Stateful programmatic web browsing in Python".<br> It handles cookies automagically.</p> <pre><code>import mechanize br = mechanize.Browser() resp = br.open("http://www.mysitewithcookies.com/") print resp.info() # headers print resp...
12
2010-04-02T16:36:21Z
[ "python", "session", "browser", "cookies" ]
SECURITY Flaws in this design for User authentication
2,567,893
<p>SECURITY Flaws in this design for User authentication.</p> <p>From: <a href="http://wiki.pylonshq.com/display/pylonscookbook/Simple+Homegrown+Authentication" rel="nofollow">http://wiki.pylonshq.com/display/pylonscookbook/Simple+Homegrown+Authentication</a></p> <p>Note: a. Project follows the MVC pattern. ...
0
2010-04-02T16:48:12Z
2,570,817
<p>I prefer approach with decorating functions that require authentication because it does not require typing action name 2 times - in the function definition and in requires_auth list. In that case you can mistype action name and it would not be noticed by interpreter. Decorating actions does not have this problem:</p...
1
2010-04-03T09:44:13Z
[ "python", "authentication", "pylons" ]
Eclipse: PyDev installation difficulties
2,567,895
<p>I'm having difficulty getting PyDev to work.</p> <p>I had an installation of Eclipse for PHP developers (1.2.1.20090918-0703). A month ago, I installed PyDev, and everything worked great. I go to fire it up this morning, and PyDev is gone. There is no option to create a Python project, the Python language editor is...
0
2010-04-02T16:48:30Z
15,892,577
<p>there's an easy way to install plugin for eclipse, download the pydev package zip file (not install it via eclipse update), extract it, and put it into your eclipse/dropins/pydev folder.</p> <p>this is a hidden way to install plugin. </p>
0
2013-04-09T03:04:17Z
[ "python", "eclipse", "pydev" ]
Python HTTPSConnection.close() does not appear to close the connection?
2,567,974
<p>I'm not sure if this is a bug or if I'm just doing something wrong. If I were to do an HTTP connection like this:</p> <pre><code>import httplib http_connection = httplib.HTTPConnection("192.168.192.196") http_connection.request("GET", "/") http_connection.sock.settimeout(20) response = http_connection.getresponse...
1
2010-04-02T17:01:43Z
2,586,321
<p>Turns out that if you send the "Connection: close" HTTP header, this isn't an issue - although I still think that .close() should actually close the connection like it does for HTTPConnection.</p>
0
2010-04-06T16:04:31Z
[ "python", "https" ]
An extended Bezier Library or Algorithms of bezier operations
2,568,018
<p><br> Is there a library of data structures and operations for quadratic bezier curves? I need to implement:</p> <ul> <li>bezier to bitmap converting with arbitrary quality</li> <li>optimizing bezier curves</li> <li>common operations like subtraction, extraction, rendering etc.</li> </ul> <p>languages: c,c++,.net,p...
0
2010-04-02T17:09:49Z
2,568,820
<p>You might want to take a look at <a href="http://cairographics.org/" rel="nofollow">Cairo</a>. I am not exactly sure if it covers all your requirements but it should be able to handle rendering at least.</p>
1
2010-04-02T19:45:35Z
[ "python", "algorithm", "bezier", "curve" ]
An extended Bezier Library or Algorithms of bezier operations
2,568,018
<p><br> Is there a library of data structures and operations for quadratic bezier curves? I need to implement:</p> <ul> <li>bezier to bitmap converting with arbitrary quality</li> <li>optimizing bezier curves</li> <li>common operations like subtraction, extraction, rendering etc.</li> </ul> <p>languages: c,c++,.net,p...
0
2010-04-02T17:09:49Z
3,493,870
<p>A little bit of python lib is included in nodebox:</p> <p><a href="http://nodebox.net/code/index.php/Bezier" rel="nofollow">http://nodebox.net/code/index.php/Bezier</a></p> <p>There are plenty of algorithms inside inkscape, but I did not digg the code yet to find, how easy they could be used outside if inkscape.</...
4
2010-08-16T14:03:46Z
[ "python", "algorithm", "bezier", "curve" ]
Avoiding thumbnail name collisions with sorl-thumbnail
2,568,134
<p>Understanding that I should probably just dig into the source to come up with a solution, I'm wondering if anyone has come up with a tactic for dealing with this.</p> <p>In my project, I have <em>a lot</em> of images being generated outside of the application. I'm isolating them on the filesystem based on a model'...
1
2010-04-02T17:33:19Z
2,568,550
<p>Ah hah. Well it looks like the solution was staring me in the face the whole time. <a href="http://thumbnail.sorl.net/docs/#this-just-doesn-t-cover-my-cravings" rel="nofollow">http://thumbnail.sorl.net/docs/#this-just-doesn-t-cover-my-cravings</a></p> <p>Looks like I'm going to subclass sorl.thumbnail.main.DjangoTh...
1
2010-04-02T18:57:44Z
[ "python", "django", "sorl-thumbnail" ]
Can I use HTTP Post Requests for SOAP? - SOAP and Django
2,568,175
<p>I am wondering if I could use simply use HTTP POST Requests in order to implement a SOAP API.</p> <p>If so how should I format and treat the requests?</p>
4
2010-04-02T17:40:12Z
2,568,295
<p>Yes, see <a href="http://www.w3schools.com/SOAP/soap_httpbinding.asp" rel="nofollow">http://www.w3schools.com/SOAP/soap_httpbinding.asp</a></p> <blockquote> <p>A SOAP method is an HTTP request/response that complies with the SOAP encoding rules.</p> <p>HTTP + XML = SOAP</p> <p>A SOAP request could b...
3
2010-04-02T18:01:19Z
[ "python", "django", "http", "soap", "post" ]
Can I use HTTP Post Requests for SOAP? - SOAP and Django
2,568,175
<p>I am wondering if I could use simply use HTTP POST Requests in order to implement a SOAP API.</p> <p>If so how should I format and treat the requests?</p>
4
2010-04-02T17:40:12Z
2,568,347
<p>Yep, I have done this in certain cases where SOAPpy did not work with a given schema. This should get you started.</p> <pre><code>import httplib from xml.dom import minidom http.request("POST", "/path/to/my/webservice", body=xml, headers = { "Host": "myservername", "Content-Type": "text/xml; charset=UTF-8"...
8
2010-04-02T18:17:08Z
[ "python", "django", "http", "soap", "post" ]
Can I use HTTP Post Requests for SOAP? - SOAP and Django
2,568,175
<p>I am wondering if I could use simply use HTTP POST Requests in order to implement a SOAP API.</p> <p>If so how should I format and treat the requests?</p>
4
2010-04-02T17:40:12Z
31,014,065
<p>I found a great example of this in the <a href="https://pypi.python.org/pypi/simple-salesforce" rel="nofollow">simple-salesforce</a> package. The code is in <code>login.py</code> and pasted below</p> <pre><code>soap_url = 'https://{domain}.salesforce.com/services/Soap/u/{sf_version}' domain = 'test' if sandbox else...
0
2015-06-23T21:42:47Z
[ "python", "django", "http", "soap", "post" ]
Python -- what is NOT in 2.7 that IS in 3.1? So many things have been back-ported, what is NOT?
2,568,187
<p>I've been following the saga of Python 3.x and have watched the 3.x features gradually getting back-ported to the 2.x line. </p> <p>Most of the libraries I use haven't been ported and some (e.g. Twisted) seem covertly or overtly hostile to 3.x to varying degrees. At any rate, there has been very little movement t...
26
2010-04-02T17:42:16Z
2,569,034
<p>The most important thing is probably unicode throughout. So there is no need anymore to fiddle around with str/unicode. This sounds small but has huge (positive) implications when you think of OS interaction - for example everyone has to try hard to give you 'usable' strings instead of 'a binary thing that might be ...
6
2010-04-02T20:32:41Z
[ "python", "python-3.x", "python-2.7" ]
Python -- what is NOT in 2.7 that IS in 3.1? So many things have been back-ported, what is NOT?
2,568,187
<p>I've been following the saga of Python 3.x and have watched the 3.x features gradually getting back-ported to the 2.x line. </p> <p>Most of the libraries I use haven't been ported and some (e.g. Twisted) seem covertly or overtly hostile to 3.x to varying degrees. At any rate, there has been very little movement t...
26
2010-04-02T17:42:16Z
2,578,325
<p>Speed might be a feature worth mentioning.</p> <p>The speed imporovements of project "Unladen Swallow" have been approved to be merged into Python. But as far as I know only to Python 3. See <a href="http://www.python.org/dev/peps/pep-3146/" rel="nofollow">PEP 3146</a> for details.</p>
3
2010-04-05T12:24:50Z
[ "python", "python-3.x", "python-2.7" ]
Nested generator functions in python
2,568,396
<p>Consider a tuple <code>v = (a,b,c)</code> and a generator function <code>generate(x)</code> which receives an item from the tuple and generates several options for each item.</p> <p>What is the pythonic way of generating a set of all the possible combinations of the result of <code>generate(x)</code> on each item i...
2
2010-04-02T18:26:48Z
2,568,422
<p>Python 2.6 has the function <a href="http://docs.python.org/library/itertools.html#itertools.product" rel="nofollow"><code>itertools.product()</code></a> that does what you want:</p> <pre><code>import itertools v = (a, b, c) for d, e, f in itertools.product(*(generate(x) for x in v)): print d, e, f </code></pre> ...
8
2010-04-02T18:31:44Z
[ "python", "generator", "list-comprehension" ]
sorl-thumbnail and file renaming
2,568,653
<p>having a similar model:</p> <pre><code>class Foo(models.Model): slug = models.SlugField(unique=True) img = ImageWithThumbnailsField(upload_to='uploads/',thumbnail={'size': (56, 34)}) </code></pre> <p>It works fine but I want to add 2 more features to it:</p> <p>1- It should also generate a second thumbnai...
0
2010-04-02T19:15:31Z
2,568,703
<p><strong>First part:</strong></p> <p>Just pass it in like this: <code>sizes=( (56,34), (195,123), )</code></p> <p><strong>Second part:</strong></p> <p>You can specify a function for the <code>upload_to</code> which Django will call, passing it an instance of the model and the original filename. With that, you ca...
3
2010-04-02T19:22:42Z
[ "python", "django", "sorl-thumbnail" ]
sorl-thumbnail and file renaming
2,568,653
<p>having a similar model:</p> <pre><code>class Foo(models.Model): slug = models.SlugField(unique=True) img = ImageWithThumbnailsField(upload_to='uploads/',thumbnail={'size': (56, 34)}) </code></pre> <p>It works fine but I want to add 2 more features to it:</p> <p>1- It should also generate a second thumbnai...
0
2010-04-02T19:15:31Z
37,212,442
<p>All you have to do is to create a method in your models.py like this:</p> <pre><code>def rename_file(instance, filename): extension = filename.split(".")[1] rename = "rename_here" return rename + "." + extension </code></pre> <p>Then in the class that extends <code>models.Model</code></p> <pre><code>c...
0
2016-05-13T14:19:42Z
[ "python", "django", "sorl-thumbnail" ]
Inverse dictionary lookup - Python
2,568,673
<p>is there any straight forward way of finding a key by knowing the value within a dictionary?</p> <p>all I can think of is this:</p> <pre><code>key = [key for key, value in dict_obj.items() if value == 'value'][0] </code></pre> <hr> <p>Any ideas?</p>
45
2010-04-02T19:18:27Z
2,568,694
<p>There is none. Don't forget that the value may be found on any number of keys, including 0 or more than 1.</p>
28
2010-04-02T19:21:10Z
[ "python", "dictionary" ]
Inverse dictionary lookup - Python
2,568,673
<p>is there any straight forward way of finding a key by knowing the value within a dictionary?</p> <p>all I can think of is this:</p> <pre><code>key = [key for key, value in dict_obj.items() if value == 'value'][0] </code></pre> <hr> <p>Any ideas?</p>
45
2010-04-02T19:18:27Z
2,568,717
<p>There isn't one as far as I know of, one way however to do it is to create a dict for normal lookup by key and another dict for reverse lookup by value.</p> <p>There's an example of such an implementation here:</p> <p><a href="http://code.activestate.com/recipes/415903-two-dict-classes-which-can-lookup-keys-by-val...
2
2010-04-02T19:24:23Z
[ "python", "dictionary" ]
Inverse dictionary lookup - Python
2,568,673
<p>is there any straight forward way of finding a key by knowing the value within a dictionary?</p> <p>all I can think of is this:</p> <pre><code>key = [key for key, value in dict_obj.items() if value == 'value'][0] </code></pre> <hr> <p>Any ideas?</p>
45
2010-04-02T19:18:27Z
2,569,004
<p>Through values in dictionary can be object of any kind they can't be hashed or indexed other way. So finding key by the value is unnatural for this collection type. Any query like that can be executed in O(n) time only. So if this is frequent task you should take a look for some indexing of key like Jon sujjested or...
0
2010-04-02T20:26:32Z
[ "python", "dictionary" ]
Inverse dictionary lookup - Python
2,568,673
<p>is there any straight forward way of finding a key by knowing the value within a dictionary?</p> <p>all I can think of is this:</p> <pre><code>key = [key for key, value in dict_obj.items() if value == 'value'][0] </code></pre> <hr> <p>Any ideas?</p>
45
2010-04-02T19:18:27Z
2,569,074
<p>There are cases where a dictionary is a one:one mapping</p> <p>Eg,</p> <pre><code>d = {1: "one", 2: "two" ...} </code></pre> <p>Your approach is ok if you are only doing a single lookup. However if you need to do more than one lookup it will be more efficient to create an inverse dictionary</p> <pre><code>ivd =...
26
2010-04-02T20:40:25Z
[ "python", "dictionary" ]
Inverse dictionary lookup - Python
2,568,673
<p>is there any straight forward way of finding a key by knowing the value within a dictionary?</p> <p>all I can think of is this:</p> <pre><code>key = [key for key, value in dict_obj.items() if value == 'value'][0] </code></pre> <hr> <p>Any ideas?</p>
45
2010-04-02T19:18:27Z
2,569,076
<p>Your list comprehension goes through all the dict's items finding all the matches, then just returns the first key. This generator expression will only iterate as far as necessary to return the first value:</p> <pre><code>key = (key for key,value in dd.items() if value=='value').next() </code></pre> <p>where dd i...
35
2010-04-02T20:40:49Z
[ "python", "dictionary" ]
Inverse dictionary lookup - Python
2,568,673
<p>is there any straight forward way of finding a key by knowing the value within a dictionary?</p> <p>all I can think of is this:</p> <pre><code>key = [key for key, value in dict_obj.items() if value == 'value'][0] </code></pre> <hr> <p>Any ideas?</p>
45
2010-04-02T19:18:27Z
2,569,966
<p>I know this might be considered 'wasteful', but in this scenario I often store the key as an additional column in the value record:</p> <pre><code>d = {'key1' : ('key1', val, val...), 'key2' : ('key2', val, val...) } </code></pre> <p>it's a tradeoff and feels wrong, but it's simple and works and of course depends ...
0
2010-04-03T01:43:36Z
[ "python", "dictionary" ]
Inverse dictionary lookup - Python
2,568,673
<p>is there any straight forward way of finding a key by knowing the value within a dictionary?</p> <p>all I can think of is this:</p> <pre><code>key = [key for key, value in dict_obj.items() if value == 'value'][0] </code></pre> <hr> <p>Any ideas?</p>
45
2010-04-02T19:18:27Z
11,635,360
<p>Maybe a dictionary-like class such as <code>DoubleDict</code> down below is what you want? You can use any one of the provided metaclasses in conjuction with <code>DoubleDict</code> or may avoid using any metaclass at all.</p> <pre><code>import functools import threading ###########################################...
4
2012-07-24T16:33:38Z
[ "python", "dictionary" ]
Inverse dictionary lookup - Python
2,568,673
<p>is there any straight forward way of finding a key by knowing the value within a dictionary?</p> <p>all I can think of is this:</p> <pre><code>key = [key for key, value in dict_obj.items() if value == 'value'][0] </code></pre> <hr> <p>Any ideas?</p>
45
2010-04-02T19:18:27Z
11,658,633
<p>This version is 26% shorter than <a href="http://stackoverflow.com/q/2568673/623735">yours</a> but functions identically, even for redundant/ambiguous values (returns the first match, as yours does). However, it is probably twice as slow as yours, because it creates a list from the dict twice.</p> <pre><code>key = ...
19
2012-07-25T21:06:16Z
[ "python", "dictionary" ]
Inverse dictionary lookup - Python
2,568,673
<p>is there any straight forward way of finding a key by knowing the value within a dictionary?</p> <p>all I can think of is this:</p> <pre><code>key = [key for key, value in dict_obj.items() if value == 'value'][0] </code></pre> <hr> <p>Any ideas?</p>
45
2010-04-02T19:18:27Z
24,402,956
<pre><code>key in dict.values() </code></pre> <p>This is literally it</p>
-3
2014-06-25T07:44:47Z
[ "python", "dictionary" ]
Inverse dictionary lookup - Python
2,568,673
<p>is there any straight forward way of finding a key by knowing the value within a dictionary?</p> <p>all I can think of is this:</p> <pre><code>key = [key for key, value in dict_obj.items() if value == 'value'][0] </code></pre> <hr> <p>Any ideas?</p>
45
2010-04-02T19:18:27Z
27,052,594
<p>No, you can not do this efficiently without looking in all the keys and checking all their values. So you will need <code>O(n)</code> time to do this. If you need to do a lot of such lookups you will need to do this efficiently by constructing a reversed dictionary (can be done also in <code>O(n)</code>) and then ma...
1
2014-11-21T01:13:43Z
[ "python", "dictionary" ]
Inverse dictionary lookup - Python
2,568,673
<p>is there any straight forward way of finding a key by knowing the value within a dictionary?</p> <p>all I can think of is this:</p> <pre><code>key = [key for key, value in dict_obj.items() if value == 'value'][0] </code></pre> <hr> <p>Any ideas?</p>
45
2010-04-02T19:18:27Z
35,366,662
<p>Since this is still very relevant, the first Google hit and I just spend some time figuring this out, I'll post my (working in Python 3) solution:</p> <pre><code>testdict = {'one' : '1', 'two' : '2', 'three' : '3', 'four' : '4' } value = '2' [key for key in tes...
1
2016-02-12T15:46:31Z
[ "python", "dictionary" ]
Does Python/Scipy have a firls( ) replacement (i.e. a weighted, least squares, FIR filter design)?
2,568,707
<p>I am porting code from Matlab to Python and am having trouble finding a replacement for the firls( ) routine. It is used for, least-squares linear-phase Finite Impulse Response (FIR) filter design.</p> <p>I looked at scipy.signal and nothing there looked like it would do the trick. Of course I was able to replace...
2
2010-04-02T19:23:10Z
2,569,232
<p>It seems unlikely that you'll find exactly what you seek already written in Python, but perhaps the Matlab function's help page gives or references a description of the algorithm?</p>
0
2010-04-02T21:14:01Z
[ "python", "algorithm", "math", "matlab", "digital-filter" ]
Does Python/Scipy have a firls( ) replacement (i.e. a weighted, least squares, FIR filter design)?
2,568,707
<p>I am porting code from Matlab to Python and am having trouble finding a replacement for the firls( ) routine. It is used for, least-squares linear-phase Finite Impulse Response (FIR) filter design.</p> <p>I looked at scipy.signal and nothing there looked like it would do the trick. Of course I was able to replace...
2
2010-04-02T19:23:10Z
2,571,867
<p>This <a href="http://mpastell.com/2010/01/18/fir-with-scipy/" rel="nofollow">blog post</a> contains code detailing how to use <code>scipy.signal</code> to implement FIR filters. </p>
1
2010-04-03T16:32:37Z
[ "python", "algorithm", "math", "matlab", "digital-filter" ]
Does Python/Scipy have a firls( ) replacement (i.e. a weighted, least squares, FIR filter design)?
2,568,707
<p>I am porting code from Matlab to Python and am having trouble finding a replacement for the firls( ) routine. It is used for, least-squares linear-phase Finite Impulse Response (FIR) filter design.</p> <p>I looked at scipy.signal and nothing there looked like it would do the trick. Of course I was able to replace...
2
2010-04-02T19:23:10Z
11,627,514
<p>Obviously, this post is somewhat dated, but maybe it is still interesting for some:</p> <p>I think there are two near-equivalents to firls in Python:</p> <ul> <li>You can try the firwin function with window='boxcar'. This is similar to Matlab where fir1 with a boxcar window delivers the same (? or at least very si...
1
2012-07-24T09:02:39Z
[ "python", "algorithm", "math", "matlab", "digital-filter" ]
Does Python/Scipy have a firls( ) replacement (i.e. a weighted, least squares, FIR filter design)?
2,568,707
<p>I am porting code from Matlab to Python and am having trouble finding a replacement for the firls( ) routine. It is used for, least-squares linear-phase Finite Impulse Response (FIR) filter design.</p> <p>I looked at scipy.signal and nothing there looked like it would do the trick. Of course I was able to replace...
2
2010-04-02T19:23:10Z
21,020,023
<p>This post is really in response to </p> <blockquote> <p>You can try the firwin function with window='boxcar'...</p> </blockquote> <p>Do don't use boxcar it means no window at all (it is ideal but only works "ideally" with an infinite number of multipliers - sinc in time). The whole perpose of using a window is t...
0
2014-01-09T12:17:07Z
[ "python", "algorithm", "math", "matlab", "digital-filter" ]
Does Python/Scipy have a firls( ) replacement (i.e. a weighted, least squares, FIR filter design)?
2,568,707
<p>I am porting code from Matlab to Python and am having trouble finding a replacement for the firls( ) routine. It is used for, least-squares linear-phase Finite Impulse Response (FIR) filter design.</p> <p>I looked at scipy.signal and nothing there looked like it would do the trick. Of course I was able to replace...
2
2010-04-02T19:23:10Z
29,379,160
<p>I found a firls() implementation attached here in <a href="http://projects.scipy.org/scipy/attachment/ticket/648/designtools.py" rel="nofollow" title="here">SciPy ticket 648</a></p> <p>Minor changes to get it working:</p> <ol> <li><p>Swap the following two lines: <code> bands, desired, weight = array(bands), array...
1
2015-03-31T21:46:38Z
[ "python", "algorithm", "math", "matlab", "digital-filter" ]
Python: why does `random.randint(a, b)` return a range inclusive of `b`?
2,568,783
<p>It has always seemed strange to me that <code>random.randint(a, b)</code> would return an integer in the range <code>[a, b]</code>, instead of <code>[a, b-1]</code> like <code>range(...)</code>.</p> <p>Is there any reason for this apparent inconsistency?</p>
28
2010-04-02T19:38:00Z
2,568,804
<p>I don't think there's a reason for that. But at least it's documented.</p>
3
2010-04-02T19:42:04Z
[ "python", "random" ]
Python: why does `random.randint(a, b)` return a range inclusive of `b`?
2,568,783
<p>It has always seemed strange to me that <code>random.randint(a, b)</code> would return an integer in the range <code>[a, b]</code>, instead of <code>[a, b-1]</code> like <code>range(...)</code>.</p> <p>Is there any reason for this apparent inconsistency?</p>
28
2010-04-02T19:38:00Z
2,568,810
<p>I guess <code>random.randint</code> was just the first attempt at implementing this feature. It seems that the Python developers also felt that this was a problem, which is why in v1.5.2 they added another method <a href="http://docs.python.org/library/random.html#random.randrange">randrange</a> with more standard p...
10
2010-04-02T19:42:36Z
[ "python", "random" ]
Python: why does `random.randint(a, b)` return a range inclusive of `b`?
2,568,783
<p>It has always seemed strange to me that <code>random.randint(a, b)</code> would return an integer in the range <code>[a, b]</code>, instead of <code>[a, b-1]</code> like <code>range(...)</code>.</p> <p>Is there any reason for this apparent inconsistency?</p>
28
2010-04-02T19:38:00Z
2,568,917
<p>I tried to get to the bottom of this by examining some old sources. I <em>suspected</em> that <code>randint</code> was implemented before Python's long integer: meaning that if you wanted a random number that included <code>INT_MAX</code>, you would have needed to call <code>random.randrange(0, INT_MAX + 1)</code> ...
61
2010-04-02T20:08:31Z
[ "python", "random" ]
Python: why does `random.randint(a, b)` return a range inclusive of `b`?
2,568,783
<p>It has always seemed strange to me that <code>random.randint(a, b)</code> would return an integer in the range <code>[a, b]</code>, instead of <code>[a, b-1]</code> like <code>range(...)</code>.</p> <p>Is there any reason for this apparent inconsistency?</p>
28
2010-04-02T19:38:00Z
2,568,995
<p>This is speculation, but normal human usage of 'give me a random number from a to b' is inclusive. Implementing it that way sort of makes sense, given Python's general philosophy of being a more human-readable language.</p>
5
2010-04-02T20:25:14Z
[ "python", "random" ]
Searching text for geonames
2,568,963
<p>which part of huge package nltk I must study and use, if I need mark geonames in text?</p>
2
2010-04-02T20:19:50Z
2,570,311
<p>You'll want to use their named entity recognizer <a href="http://nltk.googlecode.com/svn/trunk/doc/book/ch07.html#named-entity-recognition" rel="nofollow">nltk.ne_chunk</a>. </p> <p>Once the text is tagged you'll want to look for phrases labeled LOC (location) and GPE (Geo-political Entity).</p>
2
2010-04-03T05:13:41Z
[ "python", "nlp", "nltk" ]
wxPython: Load font from file
2,569,085
<p>I'm making a wxPython app, and I want to use some non-standard font that I have on file. How do I do this?</p>
0
2010-04-02T20:42:10Z
2,569,377
<p>The Win32 API you need is called <a href="http://msdn.microsoft.com/en-us/library/dd183326%28VS.85%29.aspx" rel="nofollow">AddFontResource</a> (you'll also want to use RemoveFontResource when you're done with a font). I haven't been able to find a python wrapper for this function, so you'll need to use <a href="htt...
0
2010-04-02T21:46:41Z
[ "python", "fonts", "wxpython" ]
How to handle redirects while parsing HTML? - Python
2,569,089
<p>I'm trying to submit a few forms through a Python script, I'm using the mechanized library.</p> <p>This is so I can implement a temporary API.</p> <p>The problem is that before after submission a blank page is returned informing that the request is being processed, after a few seconds the page is redirected to the...
1
2010-04-02T20:42:24Z
2,569,561
<p>Traditionally When you get a redirect, the status code of the response is 302, and there's a location header that instructs the browser where to go next. Other techniques(that are lame) would be to put a <a href="http://webdesign.about.com/od/metataglibraries/a/aa080300a.htm" rel="nofollow">meta refresh tag</a> in t...
2
2010-04-02T22:37:53Z
[ "python", "html", "http", "forms", "screen-scraping" ]
How to handle redirects while parsing HTML? - Python
2,569,089
<p>I'm trying to submit a few forms through a Python script, I'm using the mechanized library.</p> <p>This is so I can implement a temporary API.</p> <p>The problem is that before after submission a blank page is returned informing that the request is being processed, after a few seconds the page is redirected to the...
1
2010-04-02T20:42:24Z
2,574,423
<p>If it uses meta tags then you need to parse the HTML manually. Otherwise mechanize will handle the redirect automatically. </p>
1
2010-04-04T12:55:02Z
[ "python", "html", "http", "forms", "screen-scraping" ]
urllib2 in Python 2.6.4: Any way to override windows hosts file?
2,569,155
<p>I am using the urllib2 module in Python 2.6.4, running in Windows XP, to access a URL. I am making a post request, that does not involve cookies or https or anything too complicated. The domain is redirected in my C:\WINDOWS\system32\drivers\etc\hosts file. However, I would like the request from urllib2 to go to the...
1
2010-04-02T20:55:38Z
2,569,174
<p>Connect to the IP address and pass the <code>Host</code> header manually.</p>
5
2010-04-02T20:58:27Z
[ "python", "windows", "ip", "urllib2", "hosts" ]
How to implement mib module in net-snmp with python?
2,569,222
<p>in the faq, i read this "..the agent can also support MIB modules implemented in perl or (from 5.4) python." I have built net-snmp with python support, but it's not clear yet how to actually implement my own MIB module with python now. The python scripts i see in the python directory are related to implementing an ...
4
2010-04-02T21:09:25Z
2,642,628
<p>Unfortunately, net-snmp does not yet include support for agent creation in python. If you look at the <code>README</code> in the python directory of the net-snmp source tree, it says,</p> <blockquote> <p>The 'netsnmp' module provides a full featured, tri-lingual SNMP (SNMPv3, SNMPv2c, SNMPv1) <strong>client</stro...
3
2010-04-15T03:54:59Z
[ "python", "snmp", "pysnmp" ]
How to implement mib module in net-snmp with python?
2,569,222
<p>in the faq, i read this "..the agent can also support MIB modules implemented in perl or (from 5.4) python." I have built net-snmp with python support, but it's not clear yet how to actually implement my own MIB module with python now. The python scripts i see in the python directory are related to implementing an ...
4
2010-04-02T21:09:25Z
18,631,045
<p>There is an AgentX <a href="https://pypi.python.org/pypi/agentx" rel="nofollow">library in pip</a> for writing Python SNMP sub-agents.</p>
0
2013-09-05T08:11:59Z
[ "python", "snmp", "pysnmp" ]
DEADLOCK_WRAP error when using Berkeley Db in python (bsddb)
2,569,227
<p>I am using a berkdb to store a huge list of key-value pairs but for some reason when i try to access some of the data later i get this error:</p> <pre><code>try: key = 'scrape011201-590652' contenttext = contentdict[key] except: print the error &lt;type 'exceptions.KeyError'&gt; 'scrape011201-590652' ...
0
2010-04-02T21:11:34Z
3,563,034
<p>I'm pretty certain the <code>DeadlockWrap</code> stuff is not relevant here. It's simply a way to <a href="http://epydoc.sourceforge.net/stdlib/bsddb.dbutils-module.html#DeadlockWrap" rel="nofollow">automagically provide retries with a back-off strategy</a>. In other words, if the database manipulation fails, it wai...
4
2010-08-25T05:18:29Z
[ "python", "berkeley-db", "bsddb" ]
DEADLOCK_WRAP error when using Berkeley Db in python (bsddb)
2,569,227
<p>I am using a berkdb to store a huge list of key-value pairs but for some reason when i try to access some of the data later i get this error:</p> <pre><code>try: key = 'scrape011201-590652' contenttext = contentdict[key] except: print the error &lt;type 'exceptions.KeyError'&gt; 'scrape011201-590652' ...
0
2010-04-02T21:11:34Z
3,586,961
<pre><code>contenttext = contentdict[key] if contentdict.has_key(key) else None </code></pre>
0
2010-08-27T18:07:31Z
[ "python", "berkeley-db", "bsddb" ]
sqlite3.OperationalError: database is locked - non-threaded application
2,569,233
<p>I have a Python application which throws the standard <code>sqlite3.OperationalError: database is locked</code> error. I have looked around the internet and could not find any solution which worked (please note that there is no multiprocesses/threading going on, and as you can see I have tried raising the timeout p...
4
2010-04-02T21:14:40Z
2,573,065
<p>Do you really need to continuously open and close the database file for every single UPDATE? If you do the same thing in every function that accesses the database, is it possible that you have called the <code>update_index</code> function from another function that already opened the database <em>using a different c...
1
2010-04-03T23:42:55Z
[ "python", "sql", "sqlite", "sqlite3" ]
sqlite3.OperationalError: database is locked - non-threaded application
2,569,233
<p>I have a Python application which throws the standard <code>sqlite3.OperationalError: database is locked</code> error. I have looked around the internet and could not find any solution which worked (please note that there is no multiprocesses/threading going on, and as you can see I have tried raising the timeout p...
4
2010-04-02T21:14:40Z
2,594,746
<p>You might particularly check for functions that keep a read-lock (unfinished cursor). That would block the commit from the update function. Note that there is a dedicated mailing list for Python-sqlite problems: <a href="http://groups.google.com/group/python-sqlite" rel="nofollow">http://groups.google.com/group/pyth...
2
2010-04-07T18:03:05Z
[ "python", "sql", "sqlite", "sqlite3" ]
Is it possible to use a back reference to specify the number of replications in a regular expression?
2,569,418
<p>Is it possible to use a back reference to specify the number of replications in a regular expression?</p> <p>foo= 'ADCKAL+2AG.+2AG.+2AG.+2AGGG+.G+3AGGa.'</p> <p>The substrings that start with '+[0-9]' followed by '[A-z]{<strong>n</strong>}.' need to be replaced with simply '+' where the variable <strong>n</strong>...
0
2010-04-02T21:57:36Z
2,569,467
<p>No, you cannot use back-references as quantifiers. A workaround is to construct a regular expression that can handle each of the cases in an alternation.</p> <pre><code>import re foo = 'ADCKAL+2AG.+2AG.+2AG.+2AGGG^+.+G+3AGGa4.' pattern = '|'.join('\+%s[ACGTNacgtn]{%s}.' % (i, i) for i in range(1, 10)) regex = re.c...
1
2010-04-02T22:12:58Z
[ "python", "regex" ]
Python and MySQL
2,569,427
<p>Is there an easy way (without downloading any plugins) to connect to a MySQL database in Python?</p> <p>Also, what would be the difference from calling a PHP script to retrieve the data from the database and hand it over to Python and importing one of these third-parties plugins that requires some additional softwa...
0
2010-04-02T22:00:14Z
2,569,448
<p>If you don't want to download the python libraries to connect to MySQL, the effective answer is no, not trivially. </p>
-1
2010-04-02T22:05:43Z
[ "php", "python", "mysql" ]
Python and MySQL
2,569,427
<p>Is there an easy way (without downloading any plugins) to connect to a MySQL database in Python?</p> <p>Also, what would be the difference from calling a PHP script to retrieve the data from the database and hand it over to Python and importing one of these third-parties plugins that requires some additional softwa...
0
2010-04-02T22:00:14Z
2,569,453
<p>You just need the <a href="http://sourceforge.net/projects/mysql-python/" rel="nofollow">MySQL for Python module</a> that is <a href="http://www.python.org/dev/peps/pep-0249/" rel="nofollow">Python DB API 2.0</a> compliant.</p> <p>I don't know why wouldn't you want to install it. If you are worried about it being t...
2
2010-04-02T22:06:47Z
[ "php", "python", "mysql" ]
Python and MySQL
2,569,427
<p>Is there an easy way (without downloading any plugins) to connect to a MySQL database in Python?</p> <p>Also, what would be the difference from calling a PHP script to retrieve the data from the database and hand it over to Python and importing one of these third-parties plugins that requires some additional softwa...
0
2010-04-02T22:00:14Z
2,569,567
<p>No, there is no way that I've ever heard of or can think of to connect to a MySQL database with vanilla python. Just install the MySqldb python package-</p> <p>You can typically do:</p> <pre> sudo easy_install MySqldb </pre>
-1
2010-04-02T22:40:23Z
[ "php", "python", "mysql" ]
How to generate a mixed-case hash in Python?
2,569,503
<p>I am having a hard time figuring out a reasonable way to generate a mixed-case hash in Python.</p> <p>I want to generate something like: aZeEe9E</p> <p>Right now I'm using MD5, which doesn't generate case-sensitive hashes.</p> <p>Do any of you know how to generate a hash value consisting of upper- and lower- case...
1
2010-04-02T22:21:14Z
2,569,508
<p>you can base64 encode the output of the hash. This has a couple of additional characters beyond those you mentioned.</p>
3
2010-04-02T22:22:44Z
[ "python", "hash", "mixed-case" ]
How to generate a mixed-case hash in Python?
2,569,503
<p>I am having a hard time figuring out a reasonable way to generate a mixed-case hash in Python.</p> <p>I want to generate something like: aZeEe9E</p> <p>Right now I'm using MD5, which doesn't generate case-sensitive hashes.</p> <p>Do any of you know how to generate a hash value consisting of upper- and lower- case...
1
2010-04-02T22:21:14Z
2,569,511
<p>Maybe you can use <a href="http://docs.python.org/library/base64.html" rel="nofollow">base64-encoded</a> hashes?</p>
3
2010-04-02T22:25:11Z
[ "python", "hash", "mixed-case" ]
How do I most efficienty check the unique elements in a list?
2,569,578
<p>let's say I have a list</p> <pre><code>li = [{'q':'apple','code':'2B'}, {'q':'orange','code':'2A'}, {'q':'plum','code':'2A'}] </code></pre> <p>What is the most efficient way to return the count of unique "codes" in this list? In this case, the unique codes is 2, because only <em>2B</em> and <em>2A</em>...
5
2010-04-02T22:43:29Z
2,569,584
<p>Probably the most efficient simple way is to create a set of the codes, which will filter out uniques, then get the number of elements in that set:</p> <pre><code>count = len(set(d["code"] for d in li)) </code></pre> <p>As always, I advise to not worry about this kind of efficiency unless you've measured your perf...
8
2010-04-02T22:45:10Z
[ "python", "list", "dictionary", "performance" ]
socket.accept error 24: To many open files
2,569,620
<p>I have a problem with open files under my Ubuntu 9.10 when running server in Python2.6 And main problem is that, that i don't know why it so.. </p> <p>I have set </p> <p>ulimit -n = 999999</p> <p>net.core.somaxconn = 999999</p> <p>fs.file-max = 999999</p> <p>and lsof gives me about 12000 open files when server ...
6
2010-04-02T22:56:37Z
4,578,356
<p>Params that configure max open connections.</p> <p>at /etc/sysctl.conf</p> <p>add:</p> <pre><code>net.core.somaxconn=131072 fs.file-max=131072 </code></pre> <p>and then: </p> <pre><code>sudo sysctl -p </code></pre> <p>at /usr/include/linux/limits.h </p> <p>change:</p> <pre><code>NR_OPEN = 65536 </code></pre>...
16
2011-01-02T12:26:38Z
[ "python", "exception", "file", "sockets" ]
socket.accept error 24: To many open files
2,569,620
<p>I have a problem with open files under my Ubuntu 9.10 when running server in Python2.6 And main problem is that, that i don't know why it so.. </p> <p>I have set </p> <p>ulimit -n = 999999</p> <p>net.core.somaxconn = 999999</p> <p>fs.file-max = 999999</p> <p>and lsof gives me about 12000 open files when server ...
6
2010-04-02T22:56:37Z
25,846,614
<p>You can also do this from your python code like below</p> <pre><code>import resource resource.setrlimit(resource.RLIMIT_NOFILE, (65536, 65536)) </code></pre> <p>The second argument is tuple <code>(soft_limit, hard_limit)</code>. The hard limit is the ceiling for the soft limit. The soft limit is what is actually e...
3
2014-09-15T11:03:53Z
[ "python", "exception", "file", "sockets" ]
I'm doing a lot of lists and dictionary sorting...and this is causing memory errors in Python website
2,569,677
<p>I retrieved data from the log table in my database. Then I started finding unique users, comparing/sorting lists, etc.</p> <p>In the end I got down to this.</p> <pre><code>stats = {'2010-03-19': {'date': '2010-03-19', 'unique_users': 312, 'queries': 1465}, '2010-03-18': {'date': '2010-03-18', 'unique_users': 329, ...
1
2010-04-02T23:15:25Z
2,569,685
<p>If you only want the values you could just do:</p> <pre><code>mylist = stats.values() </code></pre> <p>If you need the key - value pair you should iterate the dict's <strong>items</strong>:</p> <pre><code>mylist = [] for k,v in stats.iteritems(): mylist.append(v) </code></pre> <p>In the code in your question...
7
2010-04-02T23:19:09Z
[ "python", "optimization", "list", "dictionary", "performance" ]
I'm doing a lot of lists and dictionary sorting...and this is causing memory errors in Python website
2,569,677
<p>I retrieved data from the log table in my database. Then I started finding unique users, comparing/sorting lists, etc.</p> <p>In the end I got down to this.</p> <pre><code>stats = {'2010-03-19': {'date': '2010-03-19', 'unique_users': 312, 'queries': 1465}, '2010-03-18': {'date': '2010-03-18', 'unique_users': 329, ...
1
2010-04-02T23:15:25Z
2,569,716
<p>The problem is that when you iterate through a dictionary using a <code>for ... in ...</code> loop you only iterate through the keys. You can demonstrate this with:</p> <pre><code>&gt;&gt;&gt; for x in stats: print x ... 2010-03-19 2010-03-18 etc </code></pre> <p>so when you do <code>for k,v in stats:</code> it ...
5
2010-04-02T23:34:27Z
[ "python", "optimization", "list", "dictionary", "performance" ]
I'm doing a lot of lists and dictionary sorting...and this is causing memory errors in Python website
2,569,677
<p>I retrieved data from the log table in my database. Then I started finding unique users, comparing/sorting lists, etc.</p> <p>In the end I got down to this.</p> <pre><code>stats = {'2010-03-19': {'date': '2010-03-19', 'unique_users': 312, 'queries': 1465}, '2010-03-18': {'date': '2010-03-18', 'unique_users': 329, ...
1
2010-04-02T23:15:25Z
2,569,729
<p>The default behavior when iterating a dictionary is equivalent to calling its <code>keys()</code> method.</p> <p>So the following are equivalent:</p> <pre><code>&gt;&gt;&gt; for k in stats: print k &gt;&gt;&gt; for k in stats.keys(): print k </code></pre> <p>If you want to iterate over keys and values in a single...
1
2010-04-02T23:40:29Z
[ "python", "optimization", "list", "dictionary", "performance" ]
downloading archives response corrupts files
2,569,875
<pre><code> wrapper = FileWrapper(file("C:/pics.zip")) content_type = mimetypes.guess_type(result.files)[0] response = HttpResponse(wrapper, content_type=content_type) response['Content-Length'] = os.path.getsize("C:/pics.zip") response['Content-Disposition'] = "attachment; filena...
1
2010-04-03T00:40:49Z
2,569,879
<p>The problem is that you're not reading it as a binary file :) This should work:</p> <pre><code>wrapper = FileWrapper(file("C:/pics.zip", 'rb')) </code></pre>
2
2010-04-03T00:43:26Z
[ "python", "django" ]
How come I get a timed-out when I try to download something off my own domain?
2,569,886
<pre><code>def download(source_url): socket.setdefaulttimeout(10) agents = ['Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)','Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1)','Microsoft Internet Explorer/4.0b1 (Windows 95)','Opera/8.00 (Windows NT 5.1; U; en)'] ree = urllib2.Request(source_url) ...
0
2010-04-03T00:51:09Z
2,569,912
<p>When you say "your own domain", are you hitting it from inside a NAT firewall?</p> <p>Something like this?</p> <p>123.1.2.3 (public myIP) &lt;- NAT gateway -> 192.168.1.5 (private IP of server) &lt;--> 192.168.1.10 (you)</p> <p>Many firewalls don't allow an internal address to access an external interface withou...
0
2010-04-03T01:13:48Z
[ "python", "django" ]
How come I get a timed-out when I try to download something off my own domain?
2,569,886
<pre><code>def download(source_url): socket.setdefaulttimeout(10) agents = ['Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)','Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1)','Microsoft Internet Explorer/4.0b1 (Windows 95)','Opera/8.00 (Windows NT 5.1; U; en)'] ree = urllib2.Request(source_url) ...
0
2010-04-03T00:51:09Z
2,569,914
<p>This will fail if you're running the development server, since it's single-threaded and it's busy serving the original request. Use mod_wsgi or strap on something like <a href="http://lincolnloop.com/blog/2008/mar/25/serving-django-cherrypy/" rel="nofollow">CherryPy</a> if you want it to work.</p>
1
2010-04-03T01:15:34Z
[ "python", "django" ]
Getting HTTP GET variables using Tipfy
2,569,895
<p>I'm currently playing around with <a href="http://code.google.com/p/tipfy/" rel="nofollow">tipfy</a> on Google's Appengine and just recently ran into a problem: I can't for the life of me find any documentation on how to use GET variables in my application, I've tried sifting through both <a href="http://docs.tipfy....
2
2010-04-03T00:57:47Z
2,569,901
<p><code>request.args.get('variable')</code> should work for what I think you mean by "GET data".</p>
3
2010-04-03T01:07:28Z
[ "python", "google-app-engine", "mod-wsgi", "werkzeug", "tipfy" ]
Getting HTTP GET variables using Tipfy
2,569,895
<p>I'm currently playing around with <a href="http://code.google.com/p/tipfy/" rel="nofollow">tipfy</a> on Google's Appengine and just recently ran into a problem: I can't for the life of me find any documentation on how to use GET variables in my application, I've tried sifting through both <a href="http://docs.tipfy....
2
2010-04-03T00:57:47Z
3,250,062
<p>Source: <a href="http://www.tipfy.org/wiki/guide/request/" rel="nofollow">http://www.tipfy.org/wiki/guide/request/</a></p> <p>The <strong>Request</strong> object contains all the information transmitted by the client of the application. You will retrieve from it GET and POST values, uploaded files, cookies and head...
2
2010-07-14T20:11:21Z
[ "python", "google-app-engine", "mod-wsgi", "werkzeug", "tipfy" ]
Getting HTTP GET variables using Tipfy
2,569,895
<p>I'm currently playing around with <a href="http://code.google.com/p/tipfy/" rel="nofollow">tipfy</a> on Google's Appengine and just recently ran into a problem: I can't for the life of me find any documentation on how to use GET variables in my application, I've tried sifting through both <a href="http://docs.tipfy....
2
2010-04-03T00:57:47Z
3,465,136
<p>this works for me (tipfy 0.6):</p> <pre><code>from tipfy import RequestHandler, Response from tipfy.ext.session import SessionMiddleware, SessionMixin from tipfy.ext.jinja2 import render_response from tipfy import Tipfy class I18nHandler(RequestHandler, SessionMixin): middleware = [SessionMiddleware] de...
0
2010-08-12T06:12:21Z
[ "python", "google-app-engine", "mod-wsgi", "werkzeug", "tipfy" ]
Can I filter a django model with a python list?
2,569,982
<p>Say I have a model object 'Person' defined, which has a field called 'Name'. And I have a list of people:</p> <pre><code>l = ['Bob','Dave','Jane'] </code></pre> <p>I would like to return a list of all Person records where the first name is <em>not</em> in the list of names defined in l.</p> <p>What is the most py...
3
2010-04-03T01:51:24Z
2,570,013
<p>This should work:</p> <p><code>Person.objects.exclude(name__in=['Bob','Dave','Jane'])</code></p>
4
2010-04-03T02:14:50Z
[ "python", "django", "django-models" ]
Can I filter a django model with a python list?
2,569,982
<p>Say I have a model object 'Person' defined, which has a field called 'Name'. And I have a list of people:</p> <pre><code>l = ['Bob','Dave','Jane'] </code></pre> <p>I would like to return a list of all Person records where the first name is <em>not</em> in the list of names defined in l.</p> <p>What is the most py...
3
2010-04-03T01:51:24Z
2,570,020
<p>Renaming <code>l</code> for readability:</p> <pre><code>names = ['Bob','Dave','Jane'] Person.objects.[exclude][1](Name__[in][2]=names) </code></pre> <p>UPDATE 1: Answer to the second question (in your 'EDIT' paragraph):</p> <pre><code>present = Person.objects.values_list('Name', flat=True) absent = set(names) - ...
3
2010-04-03T02:18:04Z
[ "python", "django", "django-models" ]
Error in python - don't understand
2,570,023
<p>I'm creating a game, and am quite new to Python generally.</p> <p>I created a function 'descriptionGenerator()' which generates a description for characters and objects either randomly or using variables passed to it.</p> <p>It seemed to be working, but every now and then it wouldn't work correctly. So i placed it...
2
2010-04-03T02:23:59Z
2,570,030
<p>While you check to see if <code>height</code> is greater than or less than 1.5 or 1.8, you have nothing in place if it is <em>equal</em> to one of those values. Change the comparisons around those points to either <code>&gt;=</code> and <code>&lt;</code>, or to <code>&gt;</code> and <code>&lt;=</code>.</p>
2
2010-04-03T02:30:52Z
[ "python", "osx" ]
Error in python - don't understand
2,570,023
<p>I'm creating a game, and am quite new to Python generally.</p> <p>I created a function 'descriptionGenerator()' which generates a description for characters and objects either randomly or using variables passed to it.</p> <p>It seemed to be working, but every now and then it wouldn't work correctly. So i placed it...
2
2010-04-03T02:23:59Z
2,570,032
<p>You define height_string inside if/else statements:</p> <pre><code>if float(height) &gt; 1.8: height_string = 'tall' if float(height) &gt; 2: height_string = 'very tall' elif float(height) &lt; 1.8 and float(height) &gt; 1.5: height_string = 'average' elif float(height) &lt; 1.5: height_stri...
3
2010-04-03T02:33:48Z
[ "python", "osx" ]
How to convert tag-and-username-like text into proper links in a twitter message?
2,570,193
<p>I'm writing a twitter-like note-taking web app.</p> <p>In a page the latest 20 notes of the user will be listed, and when the user scroll to the bottom of the browser window more items will be loaded and rendered.</p> <p>The initial 20 notes are part of the generated html of my django template, but the other dyna...
0
2010-04-03T04:03:39Z
2,570,547
<p>I'm not sure exactly what you're asking, but what's wrong with something like <code>{{ user.get_absolute_url }}</code>? For the tag detail URLs, it really depends on what you're looking for, but you would have to construct the url and view for that yourself.</p>
0
2010-04-03T07:29:07Z
[ "python", "django", "twitter" ]
How to convert tag-and-username-like text into proper links in a twitter message?
2,570,193
<p>I'm writing a twitter-like note-taking web app.</p> <p>In a page the latest 20 notes of the user will be listed, and when the user scroll to the bottom of the browser window more items will be loaded and rendered.</p> <p>The initial 20 notes are part of the generated html of my django template, but the other dyna...
0
2010-04-03T04:03:39Z
2,570,796
<p>There's a couple of pieces to consider here. On the server side, you have to be able to maintain what "chunk" of the notes list the user is on. The easiest way to do this is probably the Django <a href="http://docs.djangoproject.com/en/dev/topics/pagination/" rel="nofollow">paginator</a>. It works basically by ta...
2
2010-04-03T09:38:52Z
[ "python", "django", "twitter" ]
How to convert tag-and-username-like text into proper links in a twitter message?
2,570,193
<p>I'm writing a twitter-like note-taking web app.</p> <p>In a page the latest 20 notes of the user will be listed, and when the user scroll to the bottom of the browser window more items will be loaded and rendered.</p> <p>The initial 20 notes are part of the generated html of my django template, but the other dyna...
0
2010-04-03T04:03:39Z
2,571,180
<p>The question isn't that clear... but for generating the HTML out of a Tweet take a look at twp(based on the official twitter-text-java lib):<br> <a href="http://github.com/BonsaiDen/twp" rel="nofollow">http://github.com/BonsaiDen/twp</a> </p>
1
2010-04-03T11:59:29Z
[ "python", "django", "twitter" ]
Output alternatives in Python
2,570,269
<p>Is there any alternatives to the print statement for output in Python.<br> Also, how can I format my output text to be color-coded?</p> <p>I'm a beginner programmer, pretty new to it.<br> Thanks</p>
2
2010-04-03T04:56:40Z
2,570,272
<pre><code>sys.stdout.write() </code></pre> <p>Is one alternative. You can also write to <code>sys.stderr</code>. Personally, I use <code>sys.stdout</code> when I need to pass a generic "stream" to some function that will write to it. And open file is a stream, and <code>sys.stdout</code> is a stream. This way my func...
7
2010-04-03T04:58:12Z
[ "python" ]
Output alternatives in Python
2,570,269
<p>Is there any alternatives to the print statement for output in Python.<br> Also, how can I format my output text to be color-coded?</p> <p>I'm a beginner programmer, pretty new to it.<br> Thanks</p>
2
2010-04-03T04:56:40Z
2,571,945
<p>You can use <a href="http://docs.python.org/library/pprint.html" rel="nofollow">PrettyPrint</a> for print data </p>
0
2010-04-03T16:57:51Z
[ "python" ]
Text-based game graphics in Python
2,570,377
<p>I'm pretty new to programming, and I'm creating a simple text-based game.></p> <p>I'm wondering if there is a simple way to create my own terminal-type window with which I can place coloured input etc.</p> <p>Is there a graphics module well suited to this? I'm using Mac, but I would like it to work on Windows as w...
0
2010-04-03T05:52:54Z
2,570,392
<p>You could use the <a href="http://pypi.python.org/pypi/termcolor" rel="nofollow">termcolor</a> library - it that what you're looking for?</p> <p>On Windows things are trickier. See this <a href="http://stackoverflow.com/questions/287871/print-in-terminal-with-colors-using-python/288556#288556">SO answer</a> - you s...
2
2010-04-03T05:57:20Z
[ "python", "graphics", "textbox", "terminal" ]
Text-based game graphics in Python
2,570,377
<p>I'm pretty new to programming, and I'm creating a simple text-based game.></p> <p>I'm wondering if there is a simple way to create my own terminal-type window with which I can place coloured input etc.</p> <p>Is there a graphics module well suited to this? I'm using Mac, but I would like it to work on Windows as w...
0
2010-04-03T05:52:54Z
2,570,399
<p>The <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/text.html" rel="nofollow">Tkinter Text Widget</a> will do what you ask. the <a href="http://docs.python.org/library/idle.html" rel="nofollow">IDLE</a> main window is implemented as one, if you want to play with an example.</p>
2
2010-04-03T06:02:00Z
[ "python", "graphics", "textbox", "terminal" ]
Text-based game graphics in Python
2,570,377
<p>I'm pretty new to programming, and I'm creating a simple text-based game.></p> <p>I'm wondering if there is a simple way to create my own terminal-type window with which I can place coloured input etc.</p> <p>Is there a graphics module well suited to this? I'm using Mac, but I would like it to work on Windows as w...
0
2010-04-03T05:52:54Z
2,571,060
<p>For game programming with Python, I would always recommend PyGame. It is not very complex and enables you to easily use input, graphics and sound. As a start:</p> <p><a href="http://www.penzilla.net/tutorials/python/pygame/" rel="nofollow">http://www.penzilla.net/tutorials/python/pygame/</a></p>
1
2010-04-03T11:08:51Z
[ "python", "graphics", "textbox", "terminal" ]
Multithreaded FTP upload. Is it possible?
2,570,621
<p>I need to upload multiple files from directory to the server via FTP and SFTP. I've solved this task for SFTP with python, paramiko and threading. But I have problem with doing it for FTP. I tried to use ftplib for python, but it seems that it doesn't support threading and I upload all files one by one, which is ver...
3
2010-04-03T08:07:09Z
2,570,739
<p>Another approach to concurrency besides through is asynchronous io. For Python the standard toolkit for asynchronous network is <a href="http://www.twistedmatrix.com" rel="nofollow">Twisted</a>.</p> <p>Take a look at this FTP client <a href="http://twistedmatrix.com/projects/core/documentation/examples/ftpclient.py...
1
2010-04-03T09:07:51Z
[ "php", "python", "ftp", "curl", "multithreading" ]
Multithreaded FTP upload. Is it possible?
2,570,621
<p>I need to upload multiple files from directory to the server via FTP and SFTP. I've solved this task for SFTP with python, paramiko and threading. But I have problem with doing it for FTP. I tried to use ftplib for python, but it seems that it doesn't support threading and I upload all files one by one, which is ver...
3
2010-04-03T08:07:09Z
2,570,829
<p>There is an effor of creating an <a href="http://effbot.org/zone/asyncore-ftp-client.htm" rel="nofollow">asynchronous FTP client</a> but basically the FTP protocol allows synchronous commands. To allow parallel downloads/uploads you need to open multiple FTP connections. This can be done by ftplib and threads.</p>
2
2010-04-03T09:48:44Z
[ "php", "python", "ftp", "curl", "multithreading" ]
Multithreaded FTP upload. Is it possible?
2,570,621
<p>I need to upload multiple files from directory to the server via FTP and SFTP. I've solved this task for SFTP with python, paramiko and threading. But I have problem with doing it for FTP. I tried to use ftplib for python, but it seems that it doesn't support threading and I upload all files one by one, which is ver...
3
2010-04-03T08:07:09Z
2,633,859
<p>It looks like something might be possible with the pycurl module.</p> <p>There are two examples that if you put them together would work.</p> <p>Go here: <a href="http://pycurl.cvs.sourceforge.net/pycurl/pycurl/examples/" rel="nofollow">http://pycurl.cvs.sourceforge.net/pycurl/pycurl/examples/</a></p> <p>and look...
0
2010-04-13T23:18:47Z
[ "php", "python", "ftp", "curl", "multithreading" ]
Multithreaded FTP upload. Is it possible?
2,570,621
<p>I need to upload multiple files from directory to the server via FTP and SFTP. I've solved this task for SFTP with python, paramiko and threading. But I have problem with doing it for FTP. I tried to use ftplib for python, but it seems that it doesn't support threading and I upload all files one by one, which is ver...
3
2010-04-03T08:07:09Z
6,735,686
<p>You can run the script in multiple command prompts / shells (just make sure each file is only handled once by all the different scripts). I am not sure if this quick and dirty trick will improve transfer speed though..</p>
0
2011-07-18T15:53:58Z
[ "php", "python", "ftp", "curl", "multithreading" ]
(Python) algorithm to randomly select a key based on proportionality/weight
2,570,690
<p>I'm a bit at a loss as to how to find a clean algorithm for doing the following:</p> <p>Suppose I have a dict k:</p> <pre><code>&gt;&gt;&gt; k = {'A': 68, 'B': 62, 'C': 47, 'D': 16, 'E': 81} </code></pre> <p>I now want to randomly select one of these keys, based on the 'weight' they have in the total (i.e. sum) a...
8
2010-04-03T08:41:26Z
2,570,707
<p>The algorithm would be this.. </p> <p>Select a number randomly between 1 and 274. To do that, call a rand() funciton (assume it returns a value between 0 and 1), multiply rand() by 274. The resulting value should now be in a range. If its between 1 and 68, select A, if its between 69 and 130 select B and so on. Thi...
2
2010-04-03T08:52:04Z
[ "python" ]
(Python) algorithm to randomly select a key based on proportionality/weight
2,570,690
<p>I'm a bit at a loss as to how to find a clean algorithm for doing the following:</p> <p>Suppose I have a dict k:</p> <pre><code>&gt;&gt;&gt; k = {'A': 68, 'B': 62, 'C': 47, 'D': 16, 'E': 81} </code></pre> <p>I now want to randomly select one of these keys, based on the 'weight' they have in the total (i.e. sum) a...
8
2010-04-03T08:41:26Z
2,570,709
<p>The simplest way of doing this when your weights are relatively small integers (such as in your example) is to build a long string containing all the characters in the appropriate weights and choose a character at random from it:</p> <pre><code>import random d = {'A': 68, 'B': 62, 'C': 47, 'D': 16, 'E': 81} s = ''....
2
2010-04-03T08:52:48Z
[ "python" ]
(Python) algorithm to randomly select a key based on proportionality/weight
2,570,690
<p>I'm a bit at a loss as to how to find a clean algorithm for doing the following:</p> <p>Suppose I have a dict k:</p> <pre><code>&gt;&gt;&gt; k = {'A': 68, 'B': 62, 'C': 47, 'D': 16, 'E': 81} </code></pre> <p>I now want to randomly select one of these keys, based on the 'weight' they have in the total (i.e. sum) a...
8
2010-04-03T08:41:26Z
2,570,801
<p>This should do the trick:</p> <pre><code>&gt;&gt;&gt; k = {'A': 68, 'B': 62, 'C': 47, 'D': 16, 'E': 81} &gt;&gt;&gt; import random &gt;&gt;&gt; def weighted_pick(dic): ... total = sum(dic.itervalues()) ... pick = random.randint(0, total-1) ... tmp = 0 ... for key, weight in dic.iteritems(): ... ...
9
2010-04-03T09:39:46Z
[ "python" ]
(Python) algorithm to randomly select a key based on proportionality/weight
2,570,690
<p>I'm a bit at a loss as to how to find a clean algorithm for doing the following:</p> <p>Suppose I have a dict k:</p> <pre><code>&gt;&gt;&gt; k = {'A': 68, 'B': 62, 'C': 47, 'D': 16, 'E': 81} </code></pre> <p>I now want to randomly select one of these keys, based on the 'weight' they have in the total (i.e. sum) a...
8
2010-04-03T08:41:26Z
2,570,802
<p>Here's a weighted choice function, with some code that exercises it.</p> <pre><code>import random def WeightedPick(d): r = random.uniform(0, sum(d.itervalues())) s = 0.0 for k, w in d.iteritems(): s += w if r &lt; s: return k return k def Test(): k = {'A': 68, 'B': 62, 'C': 47,...
9
2010-04-03T09:40:05Z
[ "python" ]
(Python) algorithm to randomly select a key based on proportionality/weight
2,570,690
<p>I'm a bit at a loss as to how to find a clean algorithm for doing the following:</p> <p>Suppose I have a dict k:</p> <pre><code>&gt;&gt;&gt; k = {'A': 68, 'B': 62, 'C': 47, 'D': 16, 'E': 81} </code></pre> <p>I now want to randomly select one of these keys, based on the 'weight' they have in the total (i.e. sum) a...
8
2010-04-03T08:41:26Z
2,571,112
<p>I've developed an algorithm a few years ago, with application in Perl and SQL, you can read about it <a href="http://use.perl.org/~bart/journal/33630" rel="nofollow">here</a>, complete with analysis and tests why it (most likely) is correct.</p> <p>The concept is simple: for each item, pick a random number, pull it...
-1
2010-04-03T11:28:34Z
[ "python" ]
(Python) algorithm to randomly select a key based on proportionality/weight
2,570,690
<p>I'm a bit at a loss as to how to find a clean algorithm for doing the following:</p> <p>Suppose I have a dict k:</p> <pre><code>&gt;&gt;&gt; k = {'A': 68, 'B': 62, 'C': 47, 'D': 16, 'E': 81} </code></pre> <p>I now want to randomly select one of these keys, based on the 'weight' they have in the total (i.e. sum) a...
8
2010-04-03T08:41:26Z
28,082,941
<p>one should also look at <a href="http://docs.scipy.org/doc/scipy/reference/generate/scipy.stats.rv_discrete.html" rel="nofollow">this link</a></p> <p>make two list for k, say <code>xk</code> and <code>yk</code></p> <pre><code>from scipy import stats custm = stats.rv_discrete(name='test', values=(xk, yk)) custm.rvs...
2
2015-01-22T06:58:58Z
[ "python" ]