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
Making a string the name of an instance/object
1,479,490
<p>I've been struggling for a couple of days now with the following... </p> <p>I'm trying to find a way to instantiate a number of objects which I can name via a raw_input call, and then, when I need to, look at its attributes via the 'print VARIABLE NAME' command in conjunction with the <strong>str</strong>() method.</p> <p>So, to give an example. Let's say I want to create a zoo of 10 animals...</p> <pre><code> class Zoo(object): def __init__(self, species, legs, stomachs): self.species = species self.legs = legs self.stomachs = stomachs for i in range(9): species = raw_input("Enter species name: ") legs = input("How many legs does this species have? ") stomachs = input("...and how many stomachs? ") species = Zoo(species, legs, stomachs) </code></pre> <p>The idea is that the 'species' variable (first line of the for loop) e.g species = Bear becomes the object 'Bear' (last line of loop), which in conjunction with a <strong>str</strong>() method and the 'print Bear' command would give me the bears attributes. </p> <p>Like I say, I've struggled for a while with this but despite looking at other posts on similar themes still can't figure out a way. Some say use dictionaries, others say use setattr() but I can't see how this would work in my example.</p>
0
2009-09-25T20:45:18Z
1,479,552
<p>If you just want to introduce new named variables in a module namespace, then <code>setattr</code> may well be the easiest way to go:</p> <pre><code>import sys class Species: def __init__(self, name, legs, stomachs): self.name = name self.legs = legs self.stomachs = stomachs def create_species(): name = raw_input('Enter species name: ') legs = input('How many legs? ') stomachs = input('How many stomachs? ') species = Species(name, legs, stomachs) setattr(sys.modules[Species.__module__], name, species) if __name__ == '__main__': for i in range(5): create_species() </code></pre> <p>If you save this code to a file named <code>zoo.py</code>, and then import it from another module, you could use it as follows:</p> <pre><code>import zoo zoo.create_species() # =&gt; enter "Bear" as species name when prompted animal = zoo.Bear # &lt;= this object will be an instance of the Species class </code></pre> <p>Generally, though, using a dictionary is a more "Pythonic" way to maintain a collection of named values. Dynamically binding new variables has a number of issues, including the fact that most people will expect module variables to remain fairly steady between runs of a program. Also, the rules for naming of Python variables are much stricter than the possible set of animal names -- you can't include spaces in a variable name, for example, so while <code>setattr</code> will happily store the value, you'd have to use <code>getattr</code> to retrieve it.</p>
6
2009-09-25T20:59:25Z
[ "python", "string", "variables", "object" ]
Making a string the name of an instance/object
1,479,490
<p>I've been struggling for a couple of days now with the following... </p> <p>I'm trying to find a way to instantiate a number of objects which I can name via a raw_input call, and then, when I need to, look at its attributes via the 'print VARIABLE NAME' command in conjunction with the <strong>str</strong>() method.</p> <p>So, to give an example. Let's say I want to create a zoo of 10 animals...</p> <pre><code> class Zoo(object): def __init__(self, species, legs, stomachs): self.species = species self.legs = legs self.stomachs = stomachs for i in range(9): species = raw_input("Enter species name: ") legs = input("How many legs does this species have? ") stomachs = input("...and how many stomachs? ") species = Zoo(species, legs, stomachs) </code></pre> <p>The idea is that the 'species' variable (first line of the for loop) e.g species = Bear becomes the object 'Bear' (last line of loop), which in conjunction with a <strong>str</strong>() method and the 'print Bear' command would give me the bears attributes. </p> <p>Like I say, I've struggled for a while with this but despite looking at other posts on similar themes still can't figure out a way. Some say use dictionaries, others say use setattr() but I can't see how this would work in my example.</p>
0
2009-09-25T20:45:18Z
1,479,656
<pre><code>class Zoo(object): def __init__(self, name): self.name = name self.animals = [] def __str__(self): return ("The %s Zoo houses:\n" % self.name) + "\n".join(str(an) for an in self.animals) class Animal( object ): species = None def __init__(self, legs, stomach): self.legs = legs self.stomach = stomach def __str__(self): return "A %s with %d legs and %d stomachs" % ( self.species, self.legs, self.stomach ) class Bear( Animal ): species = "Bear" class Karp( Animal ): species = "Karp" ## this is the point ... you can look up Classes by their names here ## if you wonder show to automate the generation of this dict ... don't. ## ( or learn a lot Python, then add a metaclass to Animal ;-p ) species = dict( bear = Bear, karp = Karp ) zoo = Zoo( "Strange" ) while len(zoo.animals) &lt; 9: name = raw_input("Enter species name: ").lower() if name in species: legs = input("How many legs does this species have? ") stomachs = input("...and how many stomachs? ") zoo.animals.append( species[name]( legs, stomachs ) ) else: print "I have no idea what a", name, "is." print "Try again" print zoo </code></pre>
0
2009-09-25T21:23:36Z
[ "python", "string", "variables", "object" ]
Making a string the name of an instance/object
1,479,490
<p>I've been struggling for a couple of days now with the following... </p> <p>I'm trying to find a way to instantiate a number of objects which I can name via a raw_input call, and then, when I need to, look at its attributes via the 'print VARIABLE NAME' command in conjunction with the <strong>str</strong>() method.</p> <p>So, to give an example. Let's say I want to create a zoo of 10 animals...</p> <pre><code> class Zoo(object): def __init__(self, species, legs, stomachs): self.species = species self.legs = legs self.stomachs = stomachs for i in range(9): species = raw_input("Enter species name: ") legs = input("How many legs does this species have? ") stomachs = input("...and how many stomachs? ") species = Zoo(species, legs, stomachs) </code></pre> <p>The idea is that the 'species' variable (first line of the for loop) e.g species = Bear becomes the object 'Bear' (last line of loop), which in conjunction with a <strong>str</strong>() method and the 'print Bear' command would give me the bears attributes. </p> <p>Like I say, I've struggled for a while with this but despite looking at other posts on similar themes still can't figure out a way. Some say use dictionaries, others say use setattr() but I can't see how this would work in my example.</p>
0
2009-09-25T20:45:18Z
1,480,247
<p>It's really, truly, SERIOUSLY a bad idea to create barenamed variables on the fly -- I <strong>earnestly</strong> implore you to give up the requirement to be able to just <code>print FOOBAR</code> for a FOOBAR barename that never existed in the code, much as I'd implore a fellow human being who's keen to commit suicide to give up their crazy desires and give life a chance. Use dictionaries, use a function that takes <code>'FOOBAR'</code> as the argument and looks it up, etc.</p> <p>But if my fellow human being is adamant about wanting to put an end to their days, I might switch to suggestions about how to do that with the least collateral damage to themselves and others. The equivalent here would be...:</p> <pre><code>class Zoo(object): def __init__(self, species, legs, stomachs): self.species = species self.legs = legs self.stomachs = stomachs import __builtin__ setattr(__builtin__, species, self) </code></pre> <p>By explicitly using the <code>__builtin__</code> module, you ensure you can "print thespeciesname" from ANY module -- not just the one defining <code>Zoo</code>, nor just the one instantiating it.</p> <p>It's STILL a terrible idea, but this is the least-horror way to implement it.</p>
1
2009-09-26T02:16:01Z
[ "python", "string", "variables", "object" ]
Making a string the name of an instance/object
1,479,490
<p>I've been struggling for a couple of days now with the following... </p> <p>I'm trying to find a way to instantiate a number of objects which I can name via a raw_input call, and then, when I need to, look at its attributes via the 'print VARIABLE NAME' command in conjunction with the <strong>str</strong>() method.</p> <p>So, to give an example. Let's say I want to create a zoo of 10 animals...</p> <pre><code> class Zoo(object): def __init__(self, species, legs, stomachs): self.species = species self.legs = legs self.stomachs = stomachs for i in range(9): species = raw_input("Enter species name: ") legs = input("How many legs does this species have? ") stomachs = input("...and how many stomachs? ") species = Zoo(species, legs, stomachs) </code></pre> <p>The idea is that the 'species' variable (first line of the for loop) e.g species = Bear becomes the object 'Bear' (last line of loop), which in conjunction with a <strong>str</strong>() method and the 'print Bear' command would give me the bears attributes. </p> <p>Like I say, I've struggled for a while with this but despite looking at other posts on similar themes still can't figure out a way. Some say use dictionaries, others say use setattr() but I can't see how this would work in my example.</p>
0
2009-09-25T20:45:18Z
1,481,690
<pre><code>&gt;&gt;&gt; class Bear(): ... pass ... &gt;&gt;&gt; class Dog(): ... pass ... &gt;&gt;&gt; &gt;&gt;&gt; types = {'bear': Bear, 'dog': Dog} &gt;&gt;&gt; &gt;&gt;&gt; types['dog']() &lt;__main__.Dog instance at 0x75c10&gt; </code></pre>
0
2009-09-26T17:25:36Z
[ "python", "string", "variables", "object" ]
What is Python's Fabric equivalent in other languages?
1,479,632
<p>Can someone tell me what's the equivalent of Python's <a href="http://docs.fabfile.org/0.9/">Fabric</a> in Python itself, other languages or third party tools? I am still a bit fuzzy on what it is trying to accomplish and it's usage.</p>
5
2009-09-25T21:17:16Z
1,479,645
<p>It helps you to run commands on a lot of remote machines via SSH from your box. So you don't have to login on each one and copypaste the output of some machine back to your desktop.</p>
1
2009-09-25T21:21:13Z
[ "python" ]
What is Python's Fabric equivalent in other languages?
1,479,632
<p>Can someone tell me what's the equivalent of Python's <a href="http://docs.fabfile.org/0.9/">Fabric</a> in Python itself, other languages or third party tools? I am still a bit fuzzy on what it is trying to accomplish and it's usage.</p>
5
2009-09-25T21:17:16Z
1,479,653
<p>The Ruby community uses a tool called <a href="http://capistranorb.com" rel="nofollow">Capistrano</a> for the same purpose.</p>
1
2009-09-25T21:22:46Z
[ "python" ]
What is Python's Fabric equivalent in other languages?
1,479,632
<p>Can someone tell me what's the equivalent of Python's <a href="http://docs.fabfile.org/0.9/">Fabric</a> in Python itself, other languages or third party tools? I am still a bit fuzzy on what it is trying to accomplish and it's usage.</p>
5
2009-09-25T21:17:16Z
1,479,654
<p>These tools are for performing common remote administration tasks usually as part of automated builds - a Ruby equivalent might be Capistrano, JSch in Java.</p>
5
2009-09-25T21:22:48Z
[ "python" ]
What is Python's Fabric equivalent in other languages?
1,479,632
<p>Can someone tell me what's the equivalent of Python's <a href="http://docs.fabfile.org/0.9/">Fabric</a> in Python itself, other languages or third party tools? I am still a bit fuzzy on what it is trying to accomplish and it's usage.</p>
5
2009-09-25T21:17:16Z
1,480,519
<p>Looking at the fabric example the first thing I thought about was mpiexec. Given right coding, I believe fabric can be used to run bot-nets or parallel processing clusters depending on your inclination.</p>
0
2009-09-26T05:44:47Z
[ "python" ]
Readably print out a python dict() sorted by key
1,479,649
<p>I would like to print a python dictionary to a file using PrettyPrinter (for human readability) but have the dictionary be sorted by key in the output file to further improve readability. So:</p> <pre><code>mydict = {'a':1, 'b':2, 'c':3} pprint(mydict) </code></pre> <p>currently prints to</p> <pre><code>{'b':2, 'c':3, 'a':1} </code></pre> <p>I would like to PrettyPrint the dictionary but have it printed out sorted by key eg.</p> <pre><code>{'a':1, 'b':2, 'c':3} </code></pre> <p>What is the best way to do this?</p>
46
2009-09-25T21:22:11Z
1,479,676
<p>You could transform this dict a little to ensure that (as dicts aren't kept sorted internally), e.g.</p> <pre><code>pprint([(key, mydict[key]) for key in sorted(mydict.keys())]) </code></pre>
3
2009-09-25T21:28:23Z
[ "python" ]
Readably print out a python dict() sorted by key
1,479,649
<p>I would like to print a python dictionary to a file using PrettyPrinter (for human readability) but have the dictionary be sorted by key in the output file to further improve readability. So:</p> <pre><code>mydict = {'a':1, 'b':2, 'c':3} pprint(mydict) </code></pre> <p>currently prints to</p> <pre><code>{'b':2, 'c':3, 'a':1} </code></pre> <p>I would like to PrettyPrint the dictionary but have it printed out sorted by key eg.</p> <pre><code>{'a':1, 'b':2, 'c':3} </code></pre> <p>What is the best way to do this?</p>
46
2009-09-25T21:22:11Z
1,479,691
<p>The Python <code>pprint</code> module actually <em>already</em> sorts dictionaries by key. In versions prior to Python 2.5, the sorting was only triggered on dictionaries whose pretty-printed representation spanned multiple lines, but in 2.5.X and 2.6.X, <em>all</em> dictionaries are sorted.</p> <p>Generally, though, if you're writing data structures to a file and want them human-readable and writable, you might want to consider using an alternate format like YAML or JSON. Unless your users are themselves programmers, having them maintain configuration or application state dumped via <code>pprint</code> and loaded via <code>eval</code> can be a frustrating and error-prone task.</p>
12
2009-09-25T21:31:31Z
[ "python" ]
Readably print out a python dict() sorted by key
1,479,649
<p>I would like to print a python dictionary to a file using PrettyPrinter (for human readability) but have the dictionary be sorted by key in the output file to further improve readability. So:</p> <pre><code>mydict = {'a':1, 'b':2, 'c':3} pprint(mydict) </code></pre> <p>currently prints to</p> <pre><code>{'b':2, 'c':3, 'a':1} </code></pre> <p>I would like to PrettyPrint the dictionary but have it printed out sorted by key eg.</p> <pre><code>{'a':1, 'b':2, 'c':3} </code></pre> <p>What is the best way to do this?</p>
46
2009-09-25T21:22:11Z
1,479,748
<p>Actually pprint seems to sort the keys for you under python2.5</p> <pre><code>&gt;&gt;&gt; from pprint import pprint &gt;&gt;&gt; mydict = {'a':1, 'b':2, 'c':3} &gt;&gt;&gt; pprint(mydict) {'a': 1, 'b': 2, 'c': 3} &gt;&gt;&gt; mydict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5} &gt;&gt;&gt; pprint(mydict) {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} &gt;&gt;&gt; d = dict(zip("kjihgfedcba",range(11))) &gt;&gt;&gt; pprint(d) {'a': 10, 'b': 9, 'c': 8, 'd': 7, 'e': 6, 'f': 5, 'g': 4, 'h': 3, 'i': 2, 'j': 1, 'k': 0} </code></pre> <p>But not always under python 2.4</p> <pre><code>&gt;&gt;&gt; from pprint import pprint &gt;&gt;&gt; mydict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5} &gt;&gt;&gt; pprint(mydict) {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4} &gt;&gt;&gt; d = dict(zip("kjihgfedcba",range(11))) &gt;&gt;&gt; pprint(d) {'a': 10, 'b': 9, 'c': 8, 'd': 7, 'e': 6, 'f': 5, 'g': 4, 'h': 3, 'i': 2, 'j': 1, 'k': 0} &gt;&gt;&gt; </code></pre> <p>Reading the source code of pprint.py (2.5) it does sort the dictionary using</p> <pre><code>items = object.items() items.sort() </code></pre> <p>for multiline or this for single line</p> <pre><code>for k, v in sorted(object.items()): </code></pre> <p>before it attempts to print anything, so if your dictionary sorts properly like that then it should pprint properly. In 2.4 the second sorted() is missing (didn't exist then) so objects printed on a single line won't be sorted.</p> <p>So the answer appears to be use python2.5, though this doesn't quite explain your output in the question.</p>
53
2009-09-25T21:55:27Z
[ "python" ]
Readably print out a python dict() sorted by key
1,479,649
<p>I would like to print a python dictionary to a file using PrettyPrinter (for human readability) but have the dictionary be sorted by key in the output file to further improve readability. So:</p> <pre><code>mydict = {'a':1, 'b':2, 'c':3} pprint(mydict) </code></pre> <p>currently prints to</p> <pre><code>{'b':2, 'c':3, 'a':1} </code></pre> <p>I would like to PrettyPrint the dictionary but have it printed out sorted by key eg.</p> <pre><code>{'a':1, 'b':2, 'c':3} </code></pre> <p>What is the best way to do this?</p>
46
2009-09-25T21:22:11Z
11,789,032
<p>I wrote the following function to print dicts, lists, and tuples in a more readable format:</p> <pre><code>def printplus(obj): """ Pretty-prints the object passed in. """ # Dict if isinstance(obj, dict): for k, v in sorted(obj.items()): print u'{0}: {1}'.format(k, v) # List or tuple elif isinstance(obj, list) or isinstance(obj, tuple): for x in obj: print x # Other else: print obj </code></pre> <p>Example usage in iPython:</p> <pre><code>&gt;&gt;&gt; dict_example = {'c': 1, 'b': 2, 'a': 3} &gt;&gt;&gt; printplus(dict_example) a: 3 b: 2 c: 1 &gt;&gt;&gt; tuple_example = ((1, 2), (3, 4), (5, 6), (7, 8)) &gt;&gt;&gt; printplus(tuple_example) (1, 2) (3, 4) (5, 6) (7, 8) </code></pre>
11
2012-08-03T03:51:19Z
[ "python" ]
Readably print out a python dict() sorted by key
1,479,649
<p>I would like to print a python dictionary to a file using PrettyPrinter (for human readability) but have the dictionary be sorted by key in the output file to further improve readability. So:</p> <pre><code>mydict = {'a':1, 'b':2, 'c':3} pprint(mydict) </code></pre> <p>currently prints to</p> <pre><code>{'b':2, 'c':3, 'a':1} </code></pre> <p>I would like to PrettyPrint the dictionary but have it printed out sorted by key eg.</p> <pre><code>{'a':1, 'b':2, 'c':3} </code></pre> <p>What is the best way to do this?</p>
46
2009-09-25T21:22:11Z
15,060,724
<p>I had the same problem you had. I used a for loop with the sorted function passing in the dictionary like so:</p> <pre><code>for item in sorted(mydict): print(item) </code></pre>
3
2013-02-25T05:31:03Z
[ "python" ]
Readably print out a python dict() sorted by key
1,479,649
<p>I would like to print a python dictionary to a file using PrettyPrinter (for human readability) but have the dictionary be sorted by key in the output file to further improve readability. So:</p> <pre><code>mydict = {'a':1, 'b':2, 'c':3} pprint(mydict) </code></pre> <p>currently prints to</p> <pre><code>{'b':2, 'c':3, 'a':1} </code></pre> <p>I would like to PrettyPrint the dictionary but have it printed out sorted by key eg.</p> <pre><code>{'a':1, 'b':2, 'c':3} </code></pre> <p>What is the best way to do this?</p>
46
2009-09-25T21:22:11Z
18,219,242
<p>An easy way to print the sorted contents of the dictionary, in Python 3:</p> <pre><code>&gt;&gt;&gt; dict_example = {'c': 1, 'b': 2, 'a': 3} &gt;&gt;&gt; for key, value in sorted(dict_example.items()): ... print("{} : {}".format(key, value)) ... a : 3 b : 2 c : 1 </code></pre> <p>The expression <code>dict_example.items()</code> returns tuples, which can then be sorted by <code>sorted()</code>:</p> <pre><code>&gt;&gt;&gt; dict_example.items() dict_items([('c', 1), ('b', 2), ('a', 3)]) &gt;&gt;&gt; sorted(dict_example.items()) [('a', 3), ('b', 2), ('c', 1)] </code></pre>
8
2013-08-13T21:07:44Z
[ "python" ]
Readably print out a python dict() sorted by key
1,479,649
<p>I would like to print a python dictionary to a file using PrettyPrinter (for human readability) but have the dictionary be sorted by key in the output file to further improve readability. So:</p> <pre><code>mydict = {'a':1, 'b':2, 'c':3} pprint(mydict) </code></pre> <p>currently prints to</p> <pre><code>{'b':2, 'c':3, 'a':1} </code></pre> <p>I would like to PrettyPrint the dictionary but have it printed out sorted by key eg.</p> <pre><code>{'a':1, 'b':2, 'c':3} </code></pre> <p>What is the best way to do this?</p>
46
2009-09-25T21:22:11Z
36,336,386
<p>Another alternative :</p> <pre><code>&gt;&gt;&gt; mydict = {'a':1, 'b':2, 'c':3} &gt;&gt;&gt; import json &gt;&gt;&gt; print json.dumps(mydict, indent=4, sort_keys=True) { "a": 1, "b": 2, "c": 3 } </code></pre>
0
2016-03-31T14:32:36Z
[ "python" ]
How to bind a TextField to an IBOutlet()?
1,479,709
<p>I'm trying to figure out how to update an NSTextField programatically.</p> <p>I've figured out how to get the current value of the Text Field from Python:</p> <pre><code>myVar = objc.IBOutlet() .... self.myVar.stringValue() </code></pre> <p>How do I set the value of myVar from the Python side and have the GUI update? I'd like some sort of two way binding (like {myVAR} in Flex).</p> <p>Thanks!</p>
1
2009-09-25T21:38:01Z
1,479,843
<blockquote> <p>How do I set the value of myVar from the Python side and have the GUI update?</p> </blockquote> <p>Why would you want to? The nib loader set it to a control; if you set the variable, you would lose the control.</p> <p>To set the value of the control, send it a <code>setStringValue_</code> (or similar) message.</p>
1
2009-09-25T22:32:25Z
[ "python", "cocoa", "binding", "pyobjc" ]
"Too many values to unpack" Exception
1,479,776
<p>I'm working on a project in Django and I've just started trying to extend the User model in order to make user profiles. </p> <p>Unfortunately, I've run into a problem: Every time I try to get the user's profile inside of a template (<code>user.get_template.lastIP</code>, for example), I get the following error:</p> <pre> Environment: Request Method: GET Request URL: http://localhost:8000/ Django Version: 1.1 Python Version: 2.6.1 Template error: In template /path/to/base.tpl, error at line 19 Caught an exception while rendering: too many values to unpack 19 : Hello, {{user.username}} ({{ user.get_profile.rep}}). How's it goin? Logout Exception Type: TemplateSyntaxError at / Exception Value: Caught an exception while rendering: too many values to unpack </pre> <p>Any ideas as to what's going on or what I'm doing wrong?</p>
52
2009-09-25T22:04:27Z
1,479,795
<p>Most likely there is an error somewhere in the get_profile() call. In your view, before you return the request object, put this line:</p> <pre><code>request.user.get_profile() </code></pre> <p>It should raise the error, and give you a more detailed traceback, which you can then use to further debug.</p>
0
2009-09-25T22:12:03Z
[ "python", "django" ]
"Too many values to unpack" Exception
1,479,776
<p>I'm working on a project in Django and I've just started trying to extend the User model in order to make user profiles. </p> <p>Unfortunately, I've run into a problem: Every time I try to get the user's profile inside of a template (<code>user.get_template.lastIP</code>, for example), I get the following error:</p> <pre> Environment: Request Method: GET Request URL: http://localhost:8000/ Django Version: 1.1 Python Version: 2.6.1 Template error: In template /path/to/base.tpl, error at line 19 Caught an exception while rendering: too many values to unpack 19 : Hello, {{user.username}} ({{ user.get_profile.rep}}). How's it goin? Logout Exception Type: TemplateSyntaxError at / Exception Value: Caught an exception while rendering: too many values to unpack </pre> <p>Any ideas as to what's going on or what I'm doing wrong?</p>
52
2009-09-25T22:04:27Z
1,479,796
<p>That exception means that you are trying to unpack a tuple, but the tuple has too many values with respect to the number of target variables. For example: this work, and prints 1, then 2, then 3</p> <pre><code>def returnATupleWithThreeValues(): return (1,2,3) a,b,c = returnATupleWithThreeValues() print a print b print c </code></pre> <p>But this raises your error</p> <pre><code>def returnATupleWithThreeValues(): return (1,2,3) a,b = returnATupleWithThreeValues() print a print b </code></pre> <p>raises</p> <pre><code>Traceback (most recent call last): File "c.py", line 3, in ? a,b = returnATupleWithThreeValues() ValueError: too many values to unpack </code></pre> <p>Now, the reason why this happens in your case, I don't know, but maybe this answer will point you in the right direction.</p>
116
2009-09-25T22:13:22Z
[ "python", "django" ]
"Too many values to unpack" Exception
1,479,776
<p>I'm working on a project in Django and I've just started trying to extend the User model in order to make user profiles. </p> <p>Unfortunately, I've run into a problem: Every time I try to get the user's profile inside of a template (<code>user.get_template.lastIP</code>, for example), I get the following error:</p> <pre> Environment: Request Method: GET Request URL: http://localhost:8000/ Django Version: 1.1 Python Version: 2.6.1 Template error: In template /path/to/base.tpl, error at line 19 Caught an exception while rendering: too many values to unpack 19 : Hello, {{user.username}} ({{ user.get_profile.rep}}). How's it goin? Logout Exception Type: TemplateSyntaxError at / Exception Value: Caught an exception while rendering: too many values to unpack </pre> <p>Any ideas as to what's going on or what I'm doing wrong?</p>
52
2009-09-25T22:04:27Z
1,479,907
<p>This happens to me when I'm using Jinja2 for templates. The problem can be solved by running the development server using the <a href="http://code.google.com/p/django-command-extensions/wiki/RunServerPlus" rel="nofollow"><code>runserver_plus</code></a> command from <a href="http://code.google.com/p/django-command-extensions/" rel="nofollow">django_extensions</a>. </p> <p>It uses the <a href="http://werkzeug.pocoo.org/" rel="nofollow">werkzeug</a> debugger which also happens to be a lot better and has a very nice interactive debugging console. It does some ajax magic to launch a python shell at <em>any</em> frame (in the call stack) so you can debug.</p>
0
2009-09-25T23:03:52Z
[ "python", "django" ]
"Too many values to unpack" Exception
1,479,776
<p>I'm working on a project in Django and I've just started trying to extend the User model in order to make user profiles. </p> <p>Unfortunately, I've run into a problem: Every time I try to get the user's profile inside of a template (<code>user.get_template.lastIP</code>, for example), I get the following error:</p> <pre> Environment: Request Method: GET Request URL: http://localhost:8000/ Django Version: 1.1 Python Version: 2.6.1 Template error: In template /path/to/base.tpl, error at line 19 Caught an exception while rendering: too many values to unpack 19 : Hello, {{user.username}} ({{ user.get_profile.rep}}). How's it goin? Logout Exception Type: TemplateSyntaxError at / Exception Value: Caught an exception while rendering: too many values to unpack </pre> <p>Any ideas as to what's going on or what I'm doing wrong?</p>
52
2009-09-25T22:04:27Z
1,481,134
<p>This problem looked familiar so I thought I'd see if I could replicate from the limited amount of information.</p> <p>A quick search turned up an entry in James Bennett's blog <a href="http://www.b-list.org/weblog/2006/jun/06/django-tips-extending-user-model/">here</a> which mentions that when working with the UserProfile to extend the User model a common mistake in settings.py can cause Django to throw this error. </p> <p>To quote the blog entry:</p> <blockquote> <p>The value of the setting is not "appname.models.modelname", it's just "appname.modelname". The reason is that Django is not using this to do a direct import; instead, it's using an internal model-loading function which only wants the name of the app and the name of the model. Trying to do things like "appname.models.modelname" or "projectname.appname.models.modelname" in the AUTH_PROFILE_MODULE setting will cause Django to blow up with the dreaded "too many values to unpack" error, so make sure you've put "appname.modelname", and nothing else, in the value of AUTH_PROFILE_MODULE.</p> </blockquote> <p>If the OP had copied more of the traceback I would expect to see something like the one below which I was able to duplicate by adding "models" to my AUTH_PROFILE_MODULE setting.</p> <pre><code>TemplateSyntaxError at / Caught an exception while rendering: too many values to unpack Original Traceback (most recent call last): File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/debug.py", line 71, in render_node result = node.render(context) File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/debug.py", line 87, in render output = force_unicode(self.filter_expression.resolve(context)) File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/__init__.py", line 535, in resolve obj = self.var.resolve(context) File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/__init__.py", line 676, in resolve value = self._resolve_lookup(context) File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/__init__.py", line 711, in _resolve_lookup current = current() File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/contrib/auth/models.py", line 291, in get_profile app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.') ValueError: too many values to unpack </code></pre> <p>This I think is one of the few cases where Django still has a bit of import magic that tends to cause confusion when a small error doesn't throw the expected exception.</p> <p>You can see at the end of the traceback that I posted how using anything other than the form "appname.modelname" for the AUTH_PROFILE_MODULE would cause the line "app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')" to throw the "too many values to unpack" error.</p> <p>I'm 99% sure that this was the original problem encountered here.</p>
8
2009-09-26T12:43:50Z
[ "python", "django" ]
"Too many values to unpack" Exception
1,479,776
<p>I'm working on a project in Django and I've just started trying to extend the User model in order to make user profiles. </p> <p>Unfortunately, I've run into a problem: Every time I try to get the user's profile inside of a template (<code>user.get_template.lastIP</code>, for example), I get the following error:</p> <pre> Environment: Request Method: GET Request URL: http://localhost:8000/ Django Version: 1.1 Python Version: 2.6.1 Template error: In template /path/to/base.tpl, error at line 19 Caught an exception while rendering: too many values to unpack 19 : Hello, {{user.username}} ({{ user.get_profile.rep}}). How's it goin? Logout Exception Type: TemplateSyntaxError at / Exception Value: Caught an exception while rendering: too many values to unpack </pre> <p>Any ideas as to what's going on or what I'm doing wrong?</p>
52
2009-09-25T22:04:27Z
1,899,737
<p>try unpacking in one variable,</p> <p>python will handle it as a list,</p> <p>then unpack from the list</p>
11
2009-12-14T08:51:12Z
[ "python", "django" ]
Case-insensitive comparison of sets in Python
1,479,979
<p>I have two sets (although I can do lists, or whatever):</p> <pre><code>a = frozenset(('Today','I','am','fine')) b = frozenset(('hello','how','are','you','today')) </code></pre> <p>I want to get:</p> <pre><code>frozenset(['Today']) </code></pre> <p>or at least:</p> <pre><code>frozenset(['today']) </code></pre> <p>The second option is doable if I lowercase everything I presume, but I'm looking for a more elegant way. Is it possible to do </p> <pre><code>a.intersection(b) </code></pre> <p>in a case-insensitive manner?</p> <p>Shortcuts in Django are also fine since I'm using that framework.</p> <p>Example from intersection method below (I couldn't figure out how to get this formatted in a comment):</p> <pre><code>print intersection('Today I am fine tomorrow'.split(), 'Hello How a re you TODAY and today and Today and Tomorrow'.split(), key=str.lower) [(['tomorrow'], ['Tomorrow']), (['Today'], ['TODAY', 'today', 'Today'])] </code></pre>
4
2009-09-25T23:35:12Z
1,480,000
<p>First, don't you mean <code>a.intersection(b)</code>? The intersection (if case insensitive) would be <code>set(['today'])</code>. The difference would be <code>set(['i', 'am', 'fine'])</code></p> <p>Here are two ideas:</p> <p>1.) Write a function to convert the elements of both sets to lowercase and then do the intersection. Here's one way you could do it:</p> <pre><code>&gt;&gt;&gt; intersect_with_key = lambda s1, s2, key=lambda i: i: set(map(key, s1)).intersection(map(key, s2)) &gt;&gt;&gt; fs1 = frozenset('Today I am fine'.split()) &gt;&gt;&gt; fs2 = frozenset('Hello how are you TODAY'.split()) &gt;&gt;&gt; intersect_with_key(fs1, fs2) set([]) &gt;&gt;&gt; intersect_with_key(fs1, fs2, key=str.lower) set(['today']) &gt;&gt;&gt; </code></pre> <p>This is not very efficient though because the conversion and new sets would have to be created on each call.</p> <p>2.) Extend the <code>frozenset</code> class to keep a case insensitive copy of the elements. Override the <code>intersection</code> method to use the case insensitive copy of the elements. This would be more efficient.</p>
3
2009-09-25T23:44:36Z
[ "python", "django", "compare" ]
Case-insensitive comparison of sets in Python
1,479,979
<p>I have two sets (although I can do lists, or whatever):</p> <pre><code>a = frozenset(('Today','I','am','fine')) b = frozenset(('hello','how','are','you','today')) </code></pre> <p>I want to get:</p> <pre><code>frozenset(['Today']) </code></pre> <p>or at least:</p> <pre><code>frozenset(['today']) </code></pre> <p>The second option is doable if I lowercase everything I presume, but I'm looking for a more elegant way. Is it possible to do </p> <pre><code>a.intersection(b) </code></pre> <p>in a case-insensitive manner?</p> <p>Shortcuts in Django are also fine since I'm using that framework.</p> <p>Example from intersection method below (I couldn't figure out how to get this formatted in a comment):</p> <pre><code>print intersection('Today I am fine tomorrow'.split(), 'Hello How a re you TODAY and today and Today and Tomorrow'.split(), key=str.lower) [(['tomorrow'], ['Tomorrow']), (['Today'], ['TODAY', 'today', 'Today'])] </code></pre>
4
2009-09-25T23:35:12Z
1,480,230
<p>Unfortunately, even if you COULD "change on the fly" the comparison-related special methods of the sets' items (<code>__lt__</code> and friends -- actually, only <code>__eq__</code> needed the way sets are currently implemented, but that's an implementatio detail) -- and you can't, because they belong to a built-in type, <code>str</code> -- that wouldn't suffice, because <code>__hash__</code> is <strong>also</strong> crucial <strong>and</strong> by the time you want to do your intersection it's already been applied, putting the sets' items in different hash buckets from where they'd need to end up to make intersection work the way you want (i.e., no guarantee that 'Today' and 'today' are in the same bucket).</p> <p>So, for your purposes, you inevitably need to build new data structures -- if you consider it "inelegant" to have to do that at all, you're plain out of luck: built-in sets just don't carry around the HUGE baggage and overhead that would be needed to allow people to change comparison and hashing functions, which would bloat things by 10 times (or more) for the sae of a need felt in (maybe) one use case in a million.</p> <p>If you have frequent needs connected with case-insensitive comparison, you should consider subclassing or wrapping <code>str</code> (overriding comparison and hashing) to provide a "case insensitive str" type <code>cistr</code> -- and then, of course, make sure than only instances of <code>cistr</code> are (e.g.) added to your sets (&amp;c) of interest (either by subclassing <code>set</code> &amp;c, or simply by paying care). To give an oversimplified example...:</p> <pre><code>class ci(str): def __hash__(self): return hash(self.lower()) def __eq__(self, other): return self.lower() == other.lower() class cifrozenset(frozenset): def __new__(cls, seq=()): return frozenset((ci(x) for x in seq)) a = cifrozenset(('Today','I','am','fine')) b = cifrozenset(('hello','how','are','you','today')) print a.intersection(b) </code></pre> <p>this does emit <code>frozenset(['Today'])</code>, as per your expressed desire. Of course, in real life you'd probably want to do MUCH more overriding (for example...: the way I have things here, any operation on a <code>cifrozenset</code> returns a plain <code>frozenset</code>, losing the precious case independence special feature -- you'd probably want to ensure that a <code>cifrozenset</code> is returned each time instead, and, while quite feasible, that's NOT trivial).</p>
6
2009-09-26T02:03:24Z
[ "python", "django", "compare" ]
Case-insensitive comparison of sets in Python
1,479,979
<p>I have two sets (although I can do lists, or whatever):</p> <pre><code>a = frozenset(('Today','I','am','fine')) b = frozenset(('hello','how','are','you','today')) </code></pre> <p>I want to get:</p> <pre><code>frozenset(['Today']) </code></pre> <p>or at least:</p> <pre><code>frozenset(['today']) </code></pre> <p>The second option is doable if I lowercase everything I presume, but I'm looking for a more elegant way. Is it possible to do </p> <pre><code>a.intersection(b) </code></pre> <p>in a case-insensitive manner?</p> <p>Shortcuts in Django are also fine since I'm using that framework.</p> <p>Example from intersection method below (I couldn't figure out how to get this formatted in a comment):</p> <pre><code>print intersection('Today I am fine tomorrow'.split(), 'Hello How a re you TODAY and today and Today and Tomorrow'.split(), key=str.lower) [(['tomorrow'], ['Tomorrow']), (['Today'], ['TODAY', 'today', 'Today'])] </code></pre>
4
2009-09-25T23:35:12Z
1,480,291
<p>Here's version that works for any pair of iterables:</p> <pre><code>def intersection(iterableA, iterableB, key=lambda x: x): """Return the intersection of two iterables with respect to `key` function. """ def unify(iterable): d = {} for item in iterable: d.setdefault(key(item), []).append(item) return d A, B = unify(iterableA), unify(iterableB) return [(A[k], B[k]) for k in A if k in B] </code></pre> <p>Example:</p> <pre><code>print intersection('Today I am fine'.split(), 'Hello How a re you TODAY'.split(), key=str.lower) # -&gt; [(['Today'], ['TODAY'])] </code></pre>
8
2009-09-26T02:46:07Z
[ "python", "django", "compare" ]
Case-insensitive comparison of sets in Python
1,479,979
<p>I have two sets (although I can do lists, or whatever):</p> <pre><code>a = frozenset(('Today','I','am','fine')) b = frozenset(('hello','how','are','you','today')) </code></pre> <p>I want to get:</p> <pre><code>frozenset(['Today']) </code></pre> <p>or at least:</p> <pre><code>frozenset(['today']) </code></pre> <p>The second option is doable if I lowercase everything I presume, but I'm looking for a more elegant way. Is it possible to do </p> <pre><code>a.intersection(b) </code></pre> <p>in a case-insensitive manner?</p> <p>Shortcuts in Django are also fine since I'm using that framework.</p> <p>Example from intersection method below (I couldn't figure out how to get this formatted in a comment):</p> <pre><code>print intersection('Today I am fine tomorrow'.split(), 'Hello How a re you TODAY and today and Today and Tomorrow'.split(), key=str.lower) [(['tomorrow'], ['Tomorrow']), (['Today'], ['TODAY', 'today', 'Today'])] </code></pre>
4
2009-09-25T23:35:12Z
1,487,698
<pre><code>&gt;&gt;&gt; a_, b_ = map(set, [map(str.lower, a), map(str.lower, b)]) &gt;&gt;&gt; a_ &amp; b_ set(['today']) </code></pre> <p>Or... with less maps,</p> <pre><code>&gt;&gt;&gt; a_ = set(map(str.lower, a)) &gt;&gt;&gt; b_ = set(map(str.lower, b)) &gt;&gt;&gt; a_ &amp; b_ set(['today']) </code></pre>
1
2009-09-28T15:27:51Z
[ "python", "django", "compare" ]
How to get _sqlite3.so file?
1,480,024
<p>I have installed Python 2.6.2.. I did it "locally" since I do not have root permissions. With this version of Python I wanted to use module called "sqlite3" (it is called "pysqlite" in earlier versions). In theory I had to be able to use this module without any problems since it is supposed to be included by default in the considered version of Python. However, I have some troubles. When I type:</p> <pre><code>from sqlite3 import * </code></pre> <p>I get:</p> <pre><code>Traceback (most recent call last): File "", line 1, in File "/home/verrtex/opt/lib/python2.6/sqlite3/init.py", line 24, in from dbapi2 import * File "/home/verrtex/opt/lib/python2.6/sqlite3/dbapi2.py", line 27, in from _sqlite3 import * ImportError: No module named _sqlite3 </code></pre> <p>As I have already told to, the possible reason of this problem is that the module in tries to import _sqlite3 and fails, so it's not finding _sqlite3.so. This explanations is supported by the fact that I do not have _sqlite3.so file in my "/home/verrtex/opt/lib/python2.6/lib-dynload" directory. So, this is the problem I have to solve (I have to get this file to this directory).</p> <p>I found out that to solve this problem I have to "install sqlite3 and recompile Python". I also found out that the problem can be solved by "building from source and moving the library to /usr/lib/python2.5/lib-dynload/". </p> <p>However, it is not clear to me what exactly should I do. Should I install python module called "sqlite3" or I should install sqlite-database? By the way, I have already sqlite-database installed globally by the administrator. Can I use it or I still have to install my own database? By the way, I do not have root permissions. Can it be a problem? Or I need to install a python module? Is absence of root permissions a problem, in this case?</p> <p>I also has been told to, to take source files from SQLite Download Page, extract archive, move to expanded directory and execute:</p> <pre><code>./configure make make install </code></pre> <p>Then I have to copy newly compiled files to my Python directory. Should I copy all newly compiled files? And to which exactly directory should I copy (my Python directory have some subdirectories)?</p> <p>Would very appreciate any help, because I stack with this problem for a wile.</p> <p>P.S. My OS is CentOS release 5.3 (Final).</p>
3
2009-09-25T23:55:45Z
1,480,027
<p>Your <code>sys.path</code> is likely not pointing to your locally installed copy, or you're not running the Python 2.6.2 you think you are.</p> <p>If none of that is the case, you need the SQLite development headers (sqlite-dev or whatever), and then recompile Python. You need to pay attention at the end of the compile, because it complains about what it didn't build due to missing dependencies.</p> <p>EDIT: Reread question.</p> <p>EDIT 2: Also, <strong>please</strong> don't do this:</p> <pre><code>from module import * </code></pre> <p>Do this:</p> <pre><code>from module import what_i_need import module2 </code></pre>
1
2009-09-25T23:58:45Z
[ "python", "sqlite", "sqlite3", "pysqlite" ]
How to get _sqlite3.so file?
1,480,024
<p>I have installed Python 2.6.2.. I did it "locally" since I do not have root permissions. With this version of Python I wanted to use module called "sqlite3" (it is called "pysqlite" in earlier versions). In theory I had to be able to use this module without any problems since it is supposed to be included by default in the considered version of Python. However, I have some troubles. When I type:</p> <pre><code>from sqlite3 import * </code></pre> <p>I get:</p> <pre><code>Traceback (most recent call last): File "", line 1, in File "/home/verrtex/opt/lib/python2.6/sqlite3/init.py", line 24, in from dbapi2 import * File "/home/verrtex/opt/lib/python2.6/sqlite3/dbapi2.py", line 27, in from _sqlite3 import * ImportError: No module named _sqlite3 </code></pre> <p>As I have already told to, the possible reason of this problem is that the module in tries to import _sqlite3 and fails, so it's not finding _sqlite3.so. This explanations is supported by the fact that I do not have _sqlite3.so file in my "/home/verrtex/opt/lib/python2.6/lib-dynload" directory. So, this is the problem I have to solve (I have to get this file to this directory).</p> <p>I found out that to solve this problem I have to "install sqlite3 and recompile Python". I also found out that the problem can be solved by "building from source and moving the library to /usr/lib/python2.5/lib-dynload/". </p> <p>However, it is not clear to me what exactly should I do. Should I install python module called "sqlite3" or I should install sqlite-database? By the way, I have already sqlite-database installed globally by the administrator. Can I use it or I still have to install my own database? By the way, I do not have root permissions. Can it be a problem? Or I need to install a python module? Is absence of root permissions a problem, in this case?</p> <p>I also has been told to, to take source files from SQLite Download Page, extract archive, move to expanded directory and execute:</p> <pre><code>./configure make make install </code></pre> <p>Then I have to copy newly compiled files to my Python directory. Should I copy all newly compiled files? And to which exactly directory should I copy (my Python directory have some subdirectories)?</p> <p>Would very appreciate any help, because I stack with this problem for a wile.</p> <p>P.S. My OS is CentOS release 5.3 (Final).</p>
3
2009-09-25T23:55:45Z
14,545,666
<p>Although you might have found your solution, I just wrote mine down for someone who are stuck in the same problem. </p> <p>My OS is <strong>CentOS 6.3(Final) with python2.6</strong>.</p> <p>I install python2.7.3 in my system, but the problem's still there. (_sqlite3.so should be in <code>/path/to/python2.7.3/lib/python2.7/lib-dynload</code> after python2.7.3 has been installed. Because before python2.7 was installed, <a href="http://www.sqlite.org/sqlite-autoconf-3071502.tar.gz" rel="nofollow">sqlite-autoconf-3071502.tar.gz</a> was installed.)</p> <p>I then copy the <code>/path/to/python2.6/lib/python2.6/lib-dynload/_sqlite3.so</code> to the python2.7's path. And type in the python-shell:</p> <blockquote> <p><code>&gt;&gt;&gt; import sqlite3</code></p> </blockquote> <p>or </p> <blockquote> <p><code>&gt;&gt;&gt; import _sqlite3</code></p> </blockquote> <p>No error reports.</p> <p>Unfortunately, the damn error appeared as before when I run my python script. I install sqlite-devel(<code>sudo yum install sqlite-devel</code> or download <a href="http://pkgs.org/download/sqlite-devel" rel="nofollow">here</a>), and then reinstall python2.7.3 again. Run my python script again. Thank goodness! The damn error finally solved.</p>
0
2013-01-27T08:23:07Z
[ "python", "sqlite", "sqlite3", "pysqlite" ]
Is there anyway to use TestCase.assertEqual() outside of a TestCase?
1,480,144
<p>I have a utility class that stores methods that are useful for some unit test cases. I want these helper methods to be able to do asserts/fails/etc., but it seems I can't use those methods because they expect TestCase as their first argument...</p> <p>I want to be able to store the common methods outside of the testcase code and continue to use asserts in them, is that possible at all? They are ultimately used in testcase code.</p> <p>I have something like:</p> <p><strong>unittest_foo.py:</strong></p> <pre><code>import unittest from common_methods import * class TestPayments(unittest.TestCase): def test_0(self): common_method1("foo") </code></pre> <p><strong>common_methods.py:</strong> </p> <pre><code>from unittest import TestCase def common_method1(): blah=stuff TestCase.failUnless(len(blah) &gt; 5) ... ... </code></pre> <p>When the suite is run:</p> <p><code>TypeError: unbound method failUnless() must be called with TestCase instance as first argument (got bool instance instead)</code></p>
2
2009-09-26T01:05:08Z
1,480,150
<p>Sounds like you want this, from the error at least ...</p> <h3>unittest_foo.py:</h3> <pre><code>import unittest from common_methods import * class TestPayments(unittest.TestCase): def test_0(self): common_method1(self, "foo") </code></pre> <h3>common_methods.py:</h3> <pre><code>def common_method1( self, stuff ): blah=stuff self.failUnless(len(blah) &gt; 5) </code></pre>
1
2009-09-26T01:08:51Z
[ "python", "unit-testing" ]
Is there anyway to use TestCase.assertEqual() outside of a TestCase?
1,480,144
<p>I have a utility class that stores methods that are useful for some unit test cases. I want these helper methods to be able to do asserts/fails/etc., but it seems I can't use those methods because they expect TestCase as their first argument...</p> <p>I want to be able to store the common methods outside of the testcase code and continue to use asserts in them, is that possible at all? They are ultimately used in testcase code.</p> <p>I have something like:</p> <p><strong>unittest_foo.py:</strong></p> <pre><code>import unittest from common_methods import * class TestPayments(unittest.TestCase): def test_0(self): common_method1("foo") </code></pre> <p><strong>common_methods.py:</strong> </p> <pre><code>from unittest import TestCase def common_method1(): blah=stuff TestCase.failUnless(len(blah) &gt; 5) ... ... </code></pre> <p>When the suite is run:</p> <p><code>TypeError: unbound method failUnless() must be called with TestCase instance as first argument (got bool instance instead)</code></p>
2
2009-09-26T01:05:08Z
1,480,296
<p>This is often accomplished with multiple inheritance:</p> <p><strong>common_methods.py:</strong> </p> <pre><code>class CommonMethods: def common_method1(self, stuff): blah=stuff self.failUnless(len(blah) &gt; 5) ... ... </code></pre> <p><strong>unittest_foo.py:</strong></p> <pre><code>import unittest from common_methods import CommonMethods class TestPayments(unittest.TestCase, CommonMethods): def test_0(self): self.common_method1("foo") </code></pre>
3
2009-09-26T02:48:11Z
[ "python", "unit-testing" ]
Python: Grab the A record of any URI?
1,480,183
<p>I basically want to implement something where you can type in any URI ( I probably will only deal with http ) and I want to return the A record of the domain in the URI, I want the server's IP address. </p> <p>I know there's the ping command which most people use to look an ip address up, but I also know there's 'host' and 'dig' which are more specific. </p> <p>Are there any native functions I can use that will do this for me? And if so, how lenient is that function in terms of what URI string it accepts and the structure it's in? I want to throw it:</p> <ul> <li><a href="http://foo.com" rel="nofollow">http://foo.com</a></li> <li>www.foo.com</li> <li><a href="http://foo.com/baz.ext" rel="nofollow">http://foo.com/baz.ext</a></li> </ul> <p>And have basically anything return an IP address. If need be I can take care of the URI parsing ( so it's a consistent format when looked up ) myself, that's an extra plus though.</p>
0
2009-09-26T01:25:55Z
1,480,191
<pre><code>py&gt; import urlparse,socket py&gt; p = urlparse.urlparse("http://stackoverflow.com/questions/1480183") py&gt; p ('http', 'stackoverflow.com', '/questions/1480183', '', '', '') py&gt; host=p[1] py&gt; ai=socket.gethostbyname(host) py&gt; socket.gethostbyname(host) '69.59.196.211' </code></pre>
5
2009-09-26T01:31:43Z
[ "python", "url", "dns", "ip", "host" ]
how to submit query to .aspx page in python
1,480,356
<p>I need to scrape query results from an .aspx web page. </p> <p><a href="http://legistar.council.nyc.gov/Legislation.aspx">http://legistar.council.nyc.gov/Legislation.aspx</a></p> <p>The url is static, so how do I submit a query to this page and get the results? Assume we need to select "all years" and "all types" from the respective dropdown menus. </p> <p>Somebody out there must know how to do this.</p>
16
2009-09-26T03:27:22Z
1,480,367
<p>"Assume we need to select "all years" and "all types" from the respective dropdown menus."</p> <p>What do these options do to the URL that is ultimately submitted.</p> <p>After all, it amounts to an HTTP request sent via <code>urllib2</code>. </p> <p>Do know how to do '"all years" and "all types" from the respective dropdown menus' you do the following.</p> <ol> <li><p>Select '"all years" and "all types" from the respective dropdown menus'</p></li> <li><p>Note the URL which is actually submitted.</p></li> <li><p>Use this URL in <code>urllib2</code>.</p></li> </ol>
0
2009-09-26T03:33:17Z
[ "asp.net", "python", "asp.net-ajax" ]
how to submit query to .aspx page in python
1,480,356
<p>I need to scrape query results from an .aspx web page. </p> <p><a href="http://legistar.council.nyc.gov/Legislation.aspx">http://legistar.council.nyc.gov/Legislation.aspx</a></p> <p>The url is static, so how do I submit a query to this page and get the results? Assume we need to select "all years" and "all types" from the respective dropdown menus. </p> <p>Somebody out there must know how to do this.</p>
16
2009-09-26T03:27:22Z
1,480,376
<p>Most ASP.NET sites (the one you referenced included) will actually post their queries back to themselves using the HTTP POST verb, not the GET verb. That is why the URL is not changing as you noted.</p> <p>What you will need to do is look at the generated HTML and capture all their form values. Be sure to capture all the form values, as some of them are used to page validation and without them your POST request will be denied.</p> <p>Other than the validation, an ASPX page in regards to scraping and posting is no different than other web technologies.</p>
3
2009-09-26T03:39:38Z
[ "asp.net", "python", "asp.net-ajax" ]
how to submit query to .aspx page in python
1,480,356
<p>I need to scrape query results from an .aspx web page. </p> <p><a href="http://legistar.council.nyc.gov/Legislation.aspx">http://legistar.council.nyc.gov/Legislation.aspx</a></p> <p>The url is static, so how do I submit a query to this page and get the results? Assume we need to select "all years" and "all types" from the respective dropdown menus. </p> <p>Somebody out there must know how to do this.</p>
16
2009-09-26T03:27:22Z
1,480,696
<p>As an overview, you will need to perform four main tasks:</p> <ul> <li>to submit request(s) to the web site, </li> <li>to retrieve the response(s) from the site </li> <li>to parse these responses</li> <li>to have some logic to iterate in the tasks above, with parameters associated with the navigation (to "next" pages in the results list)</li> </ul> <p>The http request and response handling is done with methods and classes from Python's standard library's <a href="http://docs.python.org/library/urllib.html">urllib</a> and <a href="http://docs.python.org/library/urllib2.html">urllib2</a>. The parsing of the html pages can be done with Python's standard library's <a href="http://docs.python.org/library/htmlparser.html">HTMLParser</a> or with other modules such as <a href="http://www.crummy.com/software/BeautifulSoup/">Beautiful Soup</a></p> <p>The following snippet demonstrates the requesting and receiving of a search at the site indicated in the question. This site is ASP-driven and as a result we need to ensure that we send several form fields, some of them with 'horrible' values as these are used by the ASP logic to maintain state and to authenticate the request to some extent. Indeed submitting. The requests have to be sent with the <strong>http POST method</strong> as this is what is expected from this ASP application. The main difficulty is with identifying the form field and associated values which ASP expects (getting pages with Python is the easy part).</p> <p>This code is functional, or more precisely, <em>was</em> functional, until I removed most of the VSTATE value, and possibly introduced a typo or two by adding comments.</p> <pre><code>import urllib import urllib2 uri = 'http://legistar.council.nyc.gov/Legislation.aspx' #the http headers are useful to simulate a particular browser (some sites deny #access to non-browsers (bots, etc.) #also needed to pass the content type. headers = { 'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.13) Gecko/2009073022 Firefox/3.0.13', 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml; q=0.9,*/*; q=0.8', 'Content-Type': 'application/x-www-form-urlencoded' } # we group the form fields and their values in a list (any # iterable, actually) of name-value tuples. This helps # with clarity and also makes it easy to later encoding of them. formFields = ( # the viewstate is actualy 800+ characters in length! I truncated it # for this sample code. It can be lifted from the first page # obtained from the site. It may be ok to hardcode this value, or # it may have to be refreshed each time / each day, by essentially # running an extra page request and parse, for this specific value. (r'__VSTATE', r'7TzretNIlrZiKb7EOB3AQE ... ...2qd6g5xD8CGXm5EftXtNPt+H8B'), # following are more of these ASP form fields (r'__VIEWSTATE', r''), (r'__EVENTVALIDATION', r'/wEWDwL+raDpAgKnpt8nAs3q+pQOAs3q/pQOAs3qgpUOAs3qhpUOAoPE36ANAve684YCAoOs79EIAoOs89EIAoOs99EIAoOs39EIAoOs49EIAoOs09EIAoSs99EI6IQ74SEV9n4XbtWm1rEbB6Ic3/M='), (r'ctl00_RadScriptManager1_HiddenField', ''), (r'ctl00_tabTop_ClientState', ''), (r'ctl00_ContentPlaceHolder1_menuMain_ClientState', ''), (r'ctl00_ContentPlaceHolder1_gridMain_ClientState', ''), #but then we come to fields of interest: the search #criteria the collections to search from etc. # Check boxes (r'ctl00$ContentPlaceHolder1$chkOptions$0', 'on'), # file number (r'ctl00$ContentPlaceHolder1$chkOptions$1', 'on'), # Legislative text (r'ctl00$ContentPlaceHolder1$chkOptions$2', 'on'), # attachement # etc. (not all listed) (r'ctl00$ContentPlaceHolder1$txtSearch', 'york'), # Search text (r'ctl00$ContentPlaceHolder1$lstYears', 'All Years'), # Years to include (r'ctl00$ContentPlaceHolder1$lstTypeBasic', 'All Types'), #types to include (r'ctl00$ContentPlaceHolder1$btnSearch', 'Search Legislation') # Search button itself ) # these have to be encoded encodedFields = urllib.urlencode(formFields) req = urllib2.Request(uri, encodedFields, headers) f= urllib2.urlopen(req) #that's the actual call to the http site. # *** here would normally be the in-memory parsing of f # contents, but instead I store this to file # this is useful during design, allowing to have a # sample of what is to be parsed in a text editor, for analysis. try: fout = open('tmp.htm', 'w') except: print('Could not open output file\n') fout.writelines(f.readlines()) fout.close() </code></pre> <p>That's about it for the getting of the initial page. As said above, then one would need to parse the page, i.e. find the parts of interest and gather them as appropriate, and store them to file/database/whereever. This job can be done in very many ways: using html parsers, or XSLT type of technogies (indeed after parsing the html to xml), or even for crude jobs, simple regular-expression. Also, one of the items one typically extracts is the "next info", i.e. a link of sorts, that can be used in a new request to the server to get subsequent pages.</p> <p>This should give you a rough flavor of what "long hand" html scraping is about. There are many other approaches to this, such as dedicated utilties, scripts in Mozilla's (FireFox) GreaseMonkey plug-in, XSLT...</p>
19
2009-09-26T07:37:23Z
[ "asp.net", "python", "asp.net-ajax" ]
how to submit query to .aspx page in python
1,480,356
<p>I need to scrape query results from an .aspx web page. </p> <p><a href="http://legistar.council.nyc.gov/Legislation.aspx">http://legistar.council.nyc.gov/Legislation.aspx</a></p> <p>The url is static, so how do I submit a query to this page and get the results? Assume we need to select "all years" and "all types" from the respective dropdown menus. </p> <p>Somebody out there must know how to do this.</p>
16
2009-09-26T03:27:22Z
6,311,712
<p><a href="http://seleniumhq.org/" rel="nofollow">Selenium</a> is a great tool to use for this kind of task. You can specify the form values that you want to enter and retrieve the html of the response page as a string in a couple of lines of python code. Using Selenium you might not have to do the manual work of simulating a valid post request and all of its hidden variables, as I found out after much trial and error.</p>
4
2011-06-10T20:26:41Z
[ "asp.net", "python", "asp.net-ajax" ]
how to submit query to .aspx page in python
1,480,356
<p>I need to scrape query results from an .aspx web page. </p> <p><a href="http://legistar.council.nyc.gov/Legislation.aspx">http://legistar.council.nyc.gov/Legislation.aspx</a></p> <p>The url is static, so how do I submit a query to this page and get the results? Assume we need to select "all years" and "all types" from the respective dropdown menus. </p> <p>Somebody out there must know how to do this.</p>
16
2009-09-26T03:27:22Z
8,864,259
<p>The code in the other answers was useful; I never would have been able to write my crawler without it.</p> <p>One problem I did come across was cookies. The site I was crawling was using cookies to log session id/security stuff, so I had to add code to get my crawler to work:</p> <p>Add this import:</p> <pre><code> import cookielib </code></pre> <p>Init the cookie stuff:</p> <pre><code> COOKIEFILE = 'cookies.lwp' # the path and filename that you want to use to save your cookies in cj = cookielib.LWPCookieJar() # This is a subclass of FileCookieJar that has useful load and save methods </code></pre> <p>Install <code>CookieJar</code> so that it is used as the default <code>CookieProcessor</code> in the default opener handler:</p> <pre><code> cj.load(COOKIEFILE) opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) </code></pre> <p>To see what cookies the site is using:</p> <pre><code> print 'These are the cookies we have received so far :' for index, cookie in enumerate(cj): print index, ' : ', cookie </code></pre> <p>This saves the cookies:</p> <pre><code> cj.save(COOKIEFILE) # save the cookies </code></pre>
3
2012-01-14T18:12:44Z
[ "asp.net", "python", "asp.net-ajax" ]
Efficient method to determine location on a grid(array)
1,480,406
<p>I am representing a grid with a 2D list in python. I would like to pick a point (x,y) in the list and determine it's location...right edge, top left corner, somewhere in the middle...</p> <p>Currently I am checking like so:</p> <pre><code> # left column, not a corner if x == 0 and y != 0 and y != self.dim_y - 1: pass # right column, not a corner elif x == self.dim_x - 1 and y != 0 and y != self.dim_y - 1: pass # top row, not a corner elif y == 0 and x != 0 and x != self.dim_x - 1: pass # bottom row, not a corner elif y == self.dim_y - 1 and x != 0 and x != self.dim_x - 1: pass # top left corner elif x == 0 and y == 0: pass # top right corner elif x == self.dim_x - 1 and y == 0: pass # bottom left corner elif x == 0 and y == self.dim_y - 1: pass # bottom right corner elif x == self.dim_x - 1 and y == self.dim_y - 1: pass # somewhere in middle; not an edge else: pass </code></pre> <p>Where I have some function do something after the location is determined</p> <p>dim_x and dim_y are the dimensions of the list. </p> <p>Is there a better way of doing this without so many if-else statements? Something efficient would be good since this part of the logic is being called a couple million times...it's for simulated annealing. </p> <p>Thanks in advance. Also, what would be a better way of wording the title?</p>
2
2009-09-26T03:58:50Z
1,480,422
<pre><code># initially: method_list = [ bottom_left, bottom, bottom_right, left, middle, right, top_left, top, top_right, ] # each time: keyx = 0 if not x else (2 if x == self.dim_x - 1 else 1) keyy = 0 if not y else (2 if y == self.dim_y - 1 else 1) key = keyy * 3 + keyx method_list[key](self, x, y, other_args) </code></pre> <p>Untested ... but the general idea should shine through.</p> <p><strong>Update</strong> after the goal posts were drastically relocated by "Something efficient would be good since this part of the logic is being called a couple million times...it's for simulated annealing":</p> <p>Originally you didn't like the chain of tests, and said you were calling a function to handle each of the 8 cases. If you want fast (in Python): retain the chain of tests, and do the handling of each case inline instead of calling a function.</p> <p>Can you use psyco? Also, consider using Cython.</p>
3
2009-09-26T04:16:57Z
[ "python", "arrays", "list", "performance" ]
Efficient method to determine location on a grid(array)
1,480,406
<p>I am representing a grid with a 2D list in python. I would like to pick a point (x,y) in the list and determine it's location...right edge, top left corner, somewhere in the middle...</p> <p>Currently I am checking like so:</p> <pre><code> # left column, not a corner if x == 0 and y != 0 and y != self.dim_y - 1: pass # right column, not a corner elif x == self.dim_x - 1 and y != 0 and y != self.dim_y - 1: pass # top row, not a corner elif y == 0 and x != 0 and x != self.dim_x - 1: pass # bottom row, not a corner elif y == self.dim_y - 1 and x != 0 and x != self.dim_x - 1: pass # top left corner elif x == 0 and y == 0: pass # top right corner elif x == self.dim_x - 1 and y == 0: pass # bottom left corner elif x == 0 and y == self.dim_y - 1: pass # bottom right corner elif x == self.dim_x - 1 and y == self.dim_y - 1: pass # somewhere in middle; not an edge else: pass </code></pre> <p>Where I have some function do something after the location is determined</p> <p>dim_x and dim_y are the dimensions of the list. </p> <p>Is there a better way of doing this without so many if-else statements? Something efficient would be good since this part of the logic is being called a couple million times...it's for simulated annealing. </p> <p>Thanks in advance. Also, what would be a better way of wording the title?</p>
2
2009-09-26T03:58:50Z
1,480,437
<p>If I understand correctly, you have a collection of coordinates (x,y) living in a grid, and you would like to know, given any coordinate, whether it is inside the grid or on an edge.</p> <p>The approach I would take is to normalize the grid before making the comparison, so that its origin is (0,0) and its top right corner is (1,1), then I would only have to know the value of the coordinate to determine its location. Let me explain.</p> <p>0) Let _max represent the maximum value and _min, for instance, x_min is the minimum value of the coordinate x; let _new represent the normalized value.</p> <pre><code>1) Given (x,y), compute: x_new = (x_max-x)/(x_max-x_min) and y_new=(y_max-y)/(y_max-y_min). 2) [this is pseudo code] switch y_new: case y_new==0: pos_y='bottom' case y_new==1: pos_y='top' otherwise: pos_y='%2.2f \% on y', 100*y_new switch x_new: case x_new==0: pos_x='left' case x_new==1: pos_x='right' otherwise: pos_x='%2.2f \% on x', 100*x_new print pos_y, pos_x It would print stuff like "bottom left" or "top right" or "32.58% on y 15.43% on x" Hope that helps. </code></pre>
1
2009-09-26T04:31:11Z
[ "python", "arrays", "list", "performance" ]
Efficient method to determine location on a grid(array)
1,480,406
<p>I am representing a grid with a 2D list in python. I would like to pick a point (x,y) in the list and determine it's location...right edge, top left corner, somewhere in the middle...</p> <p>Currently I am checking like so:</p> <pre><code> # left column, not a corner if x == 0 and y != 0 and y != self.dim_y - 1: pass # right column, not a corner elif x == self.dim_x - 1 and y != 0 and y != self.dim_y - 1: pass # top row, not a corner elif y == 0 and x != 0 and x != self.dim_x - 1: pass # bottom row, not a corner elif y == self.dim_y - 1 and x != 0 and x != self.dim_x - 1: pass # top left corner elif x == 0 and y == 0: pass # top right corner elif x == self.dim_x - 1 and y == 0: pass # bottom left corner elif x == 0 and y == self.dim_y - 1: pass # bottom right corner elif x == self.dim_x - 1 and y == self.dim_y - 1: pass # somewhere in middle; not an edge else: pass </code></pre> <p>Where I have some function do something after the location is determined</p> <p>dim_x and dim_y are the dimensions of the list. </p> <p>Is there a better way of doing this without so many if-else statements? Something efficient would be good since this part of the logic is being called a couple million times...it's for simulated annealing. </p> <p>Thanks in advance. Also, what would be a better way of wording the title?</p>
2
2009-09-26T03:58:50Z
1,480,473
<pre><code>def location(x,y,dim_x,dim_y): index = 1*(y==0) + 2*(y==dim_y-1) + 3*(x==0) + 6*(x==dim_x-1) return ["interior","top","bottom","left","top-left", "bottom-left","right","top-right","bottom-right"][index] </code></pre>
7
2009-09-26T05:11:18Z
[ "python", "arrays", "list", "performance" ]
Efficient method to determine location on a grid(array)
1,480,406
<p>I am representing a grid with a 2D list in python. I would like to pick a point (x,y) in the list and determine it's location...right edge, top left corner, somewhere in the middle...</p> <p>Currently I am checking like so:</p> <pre><code> # left column, not a corner if x == 0 and y != 0 and y != self.dim_y - 1: pass # right column, not a corner elif x == self.dim_x - 1 and y != 0 and y != self.dim_y - 1: pass # top row, not a corner elif y == 0 and x != 0 and x != self.dim_x - 1: pass # bottom row, not a corner elif y == self.dim_y - 1 and x != 0 and x != self.dim_x - 1: pass # top left corner elif x == 0 and y == 0: pass # top right corner elif x == self.dim_x - 1 and y == 0: pass # bottom left corner elif x == 0 and y == self.dim_y - 1: pass # bottom right corner elif x == self.dim_x - 1 and y == self.dim_y - 1: pass # somewhere in middle; not an edge else: pass </code></pre> <p>Where I have some function do something after the location is determined</p> <p>dim_x and dim_y are the dimensions of the list. </p> <p>Is there a better way of doing this without so many if-else statements? Something efficient would be good since this part of the logic is being called a couple million times...it's for simulated annealing. </p> <p>Thanks in advance. Also, what would be a better way of wording the title?</p>
2
2009-09-26T03:58:50Z
1,480,746
<p>I guess if you really want to treat all these cases completely differently, your solution is okay, as it is very explicit. A compact solution might look more elegant, but will probably be harder to maintain. It really depends on what happens inside the if-blocks.</p> <p>As soon as there is a common handling of, say, the corners, one might prefer to catch those cases with one clever if-statement.</p>
0
2009-09-26T08:11:39Z
[ "python", "arrays", "list", "performance" ]
Efficient method to determine location on a grid(array)
1,480,406
<p>I am representing a grid with a 2D list in python. I would like to pick a point (x,y) in the list and determine it's location...right edge, top left corner, somewhere in the middle...</p> <p>Currently I am checking like so:</p> <pre><code> # left column, not a corner if x == 0 and y != 0 and y != self.dim_y - 1: pass # right column, not a corner elif x == self.dim_x - 1 and y != 0 and y != self.dim_y - 1: pass # top row, not a corner elif y == 0 and x != 0 and x != self.dim_x - 1: pass # bottom row, not a corner elif y == self.dim_y - 1 and x != 0 and x != self.dim_x - 1: pass # top left corner elif x == 0 and y == 0: pass # top right corner elif x == self.dim_x - 1 and y == 0: pass # bottom left corner elif x == 0 and y == self.dim_y - 1: pass # bottom right corner elif x == self.dim_x - 1 and y == self.dim_y - 1: pass # somewhere in middle; not an edge else: pass </code></pre> <p>Where I have some function do something after the location is determined</p> <p>dim_x and dim_y are the dimensions of the list. </p> <p>Is there a better way of doing this without so many if-else statements? Something efficient would be good since this part of the logic is being called a couple million times...it's for simulated annealing. </p> <p>Thanks in advance. Also, what would be a better way of wording the title?</p>
2
2009-09-26T03:58:50Z
1,480,880
<p>Something like this might be more readable / maintainable. It will probably be a lot faster than your nested if statements since it only tests each condition once and dispatches through a dictionary which is nice and fast.</p> <pre><code>class LocationThing: def __init__(self, x, y): self.dim_x = x self.dim_y = y def interior(self): print "interior" def left(self): print "left" def right(self): print "right" def top(self): print "top" def bottom(self): print "bottom" def top_left(self): print "top_left" def top_right(self): print "top_right" def bottom_left(self): print "bottom_left" def bottom_right(self): print "bottom_right" location_map = { # (left, right, top, bottom) ( False, False, False, False ) : interior, ( True, False, False, False ) : left, ( False, True, False, False ) : right, ( False, False, True, False ) : top, ( False, False, False, True ) : bottom, ( True, False, True, False ) : top_left, ( False, True, True, False ) : top_right, ( True, False, False, True ) : bottom_left, ( False, True, False, True ) : bottom_right, } def location(self, x,y): method = self.location_map[(x==0, x==self.dim_x-1, y==0, y==self.dim_y-1)] return method(self) l = LocationThing(10,10) l.location(0,0) l.location(0,1) l.location(1,1) l.location(9,9) l.location(9,1) l.location(1,9) l.location(0,9) l.location(9,0) </code></pre> <p>When you run the above it prints</p> <pre><code>top_left left interior bottom_right right bottom bottom_left top_right </code></pre>
0
2009-09-26T09:50:47Z
[ "python", "arrays", "list", "performance" ]
Efficient method to determine location on a grid(array)
1,480,406
<p>I am representing a grid with a 2D list in python. I would like to pick a point (x,y) in the list and determine it's location...right edge, top left corner, somewhere in the middle...</p> <p>Currently I am checking like so:</p> <pre><code> # left column, not a corner if x == 0 and y != 0 and y != self.dim_y - 1: pass # right column, not a corner elif x == self.dim_x - 1 and y != 0 and y != self.dim_y - 1: pass # top row, not a corner elif y == 0 and x != 0 and x != self.dim_x - 1: pass # bottom row, not a corner elif y == self.dim_y - 1 and x != 0 and x != self.dim_x - 1: pass # top left corner elif x == 0 and y == 0: pass # top right corner elif x == self.dim_x - 1 and y == 0: pass # bottom left corner elif x == 0 and y == self.dim_y - 1: pass # bottom right corner elif x == self.dim_x - 1 and y == self.dim_y - 1: pass # somewhere in middle; not an edge else: pass </code></pre> <p>Where I have some function do something after the location is determined</p> <p>dim_x and dim_y are the dimensions of the list. </p> <p>Is there a better way of doing this without so many if-else statements? Something efficient would be good since this part of the logic is being called a couple million times...it's for simulated annealing. </p> <p>Thanks in advance. Also, what would be a better way of wording the title?</p>
2
2009-09-26T03:58:50Z
1,481,572
<p>For a fast inner-loop function, you can just bite the bullet and do the ugly: nested if else statements with repeated terms, so that each comparison is only done once, and it runs about <strong>twice as fast</strong> as an example cleaner answer (by mobrule):</p> <pre><code>import timeit def f0(x, y, x_dim, y_dim): if x!=0: if x!=x_dim: # in the x interior if y!=0: if y!=y_dim: # y interior return "interior" else: # y==y_dim edge 'top' return "interior-top" else: return "interior-bottom" else: # x = x_dim, "right" if y!=0: if y!=y_dim: # return "right-interior" else: # y==y_dim edge 'top' return "right-top" else: return "right-bottom" else: # x=0 'left' if y!=0: if y!=y_dim: # y interior return "left-interior" else: # y==y_dim edge 'top' return "left-top" else: return "left-bottom" r_list = ["interior","top","bottom","left","top-left", "bottom-left","right","top-right","bottom-right"] def f1(x,y,dim_x,dim_y): index = 1*(y==0) + 2*(y==dim_y-1) + 3*(x==0) + 6*(x==dim_x-1) return r_list[index] for x, y, x_dim, y_dim in [(4, 4, 5, 6), (0, 0, 5, 6)]: t = timeit.Timer("f0(x, y, x_dim, y_dim)", "from __main__ import f0, f1, x, y, x_dim, y_dim, r_list") print "f0", t.timeit(number=1000000) t = timeit.Timer("f1(x, y, x_dim, y_dim)", "from __main__ import f0, f1, x, y, x_dim, y_dim, r_list") print "f1", t.timeit(number=1000000) </code></pre> <p>Which gives:</p> <pre><code>f0 0.729887008667 # nested if-else for interior point (no "else"s) f1 1.4765329361 f0 0.622623920441 # nested if-else for left-bottom (all "else"s) f1 1.49259114265 </code></pre> <p>So it's a bit better than twice as fast as mobrule's answer, which was the fastest looking code that I knew would work when I posted this. (Also, I moved mobrule's string list out of the function as that sped up the result by 50%.) Speed over beauty?</p> <p>If instead you want a concise and easy to read solution, I suggest:</p> <pre><code>def f1(x, y, x_dim, y_dim): d_x = {0:"left", x_dim:"right"} d_y = {0:"bottom", y_dim:"top"} return d_x.get(x, "interior")+"-"+d_y.get(y, "interior") </code></pre> <p>which is as fast as the others by my timing.</p>
0
2009-09-26T16:23:39Z
[ "python", "arrays", "list", "performance" ]
Most used Python module for video processing?
1,480,431
<p>I need to:</p> <ol> <li>Open a video file</li> <li>Iterate over the frames of the file as images</li> <li>Do some analysis in this image frame of the video</li> <li>Draw in this image of the video</li> <li>Create a new video with these changes</li> </ol> <p>OpenCV isn't working for my webcam, but python-gst is working. Is this possible using python-gst?</p> <p>Thank you!</p>
12
2009-09-26T04:23:53Z
1,480,450
<p>Do you mean opencv can't connect to your webcam or can't read video files recorded by it?</p> <p>Have you tried saving the video in an other format?</p> <p>OpenCV is probably the best supported python image processing tool </p>
5
2009-09-26T04:47:50Z
[ "python", "image-processing", "video-processing" ]
Most used Python module for video processing?
1,480,431
<p>I need to:</p> <ol> <li>Open a video file</li> <li>Iterate over the frames of the file as images</li> <li>Do some analysis in this image frame of the video</li> <li>Draw in this image of the video</li> <li>Create a new video with these changes</li> </ol> <p>OpenCV isn't working for my webcam, but python-gst is working. Is this possible using python-gst?</p> <p>Thank you!</p>
12
2009-09-26T04:23:53Z
1,497,418
<p>Just build a C/C++ wrapper for your webcam and then use SWIG or SIP to access these functions from Python. Then use OpenCV in Python that's the best open sourced computer vision library in the wild.</p> <p>If you worry for performance and you work under Linux, you could download free versions of Intel Performance Primitives (IPP) that could be loaded at runtime with zero effort from OpenCV. For certain algorithms you could get a 200% boost of performances, plus automatic multicore support for most of time consuming functions.</p>
0
2009-09-30T11:00:07Z
[ "python", "image-processing", "video-processing" ]
Most used Python module for video processing?
1,480,431
<p>I need to:</p> <ol> <li>Open a video file</li> <li>Iterate over the frames of the file as images</li> <li>Do some analysis in this image frame of the video</li> <li>Draw in this image of the video</li> <li>Create a new video with these changes</li> </ol> <p>OpenCV isn't working for my webcam, but python-gst is working. Is this possible using python-gst?</p> <p>Thank you!</p>
12
2009-09-26T04:23:53Z
1,929,649
<p>I'm going through this myself. It's only a couple of lines in MATLAB using mmreader, but I've already blown two work days trying to figure out how to pull frames from a video file into numpy. If you have enough disk space, and it doesn't have to be real time, you can use:</p> <pre><code>mplayer -noconsolecontrols -vo png blah.mov </code></pre> <p>and then pull the .png files into numpy using:</p> <pre><code>pylab.imread('blah0000001.png') </code></pre> <p>I know this is incomplete, but it may still help you. Good luck!</p>
3
2009-12-18T17:36:04Z
[ "python", "image-processing", "video-processing" ]
Most used Python module for video processing?
1,480,431
<p>I need to:</p> <ol> <li>Open a video file</li> <li>Iterate over the frames of the file as images</li> <li>Do some analysis in this image frame of the video</li> <li>Draw in this image of the video</li> <li>Create a new video with these changes</li> </ol> <p>OpenCV isn't working for my webcam, but python-gst is working. Is this possible using python-gst?</p> <p>Thank you!</p>
12
2009-09-26T04:23:53Z
1,939,327
<p>I used this script to convert a movie to a numpy array + binary store:</p> <pre><code>""" Takes a MPEG movie and produces a numpy record file with a numpy array. """ import os filename = 'walking' if not(os.path.isfile(filename + '.npy')): # do nothing if files exists N_frame = 42 # number of frames we want to store os.system('ffmpeg -i WALK.MOV.qt -f image2 foo-%03d.png') # convert them to numpy from numpy import zeros, save, mean from pylab import imread n_x, n_y, n_rgb = imread('foo-001.png').shape mov = zeros((n_y, n_x, N_frame)) for i_frame in range(N_frame): name = 'foo-%03d.png' % (i_frame +1) mov[:n_y,:n_x,i_frame] = flipud(mean(imread(name), axis=2)).T os.system('rm -f foo-*.png') save(filename + '.npy', mov) </code></pre> <p>note that depending on your conventions you may not want to flip the image. you may then load it using :</p> <pre><code>load('walking.npy') </code></pre>
3
2009-12-21T10:25:19Z
[ "python", "image-processing", "video-processing" ]
phpMyAdmin equivalent in python?
1,480,453
<p>Is there a python equivalent of phpMyAdmin?</p> <p>Here's why I'm looking for a python version of phpmyadmin: While I agree that phpmyadmin really rocks, I don't want to run php on my server. I'd like to move from apache2-prefork to apache2-mpm-worker. Worker blows the doors off of prefork for performance, but php5 doesn't work with worker. (Technically it does, but it's far more complicated.) The extra memory and performance penalty for having php on this server is large to me.</p>
27
2009-09-26T04:51:49Z
1,480,549
<p>You can use phpMyAdmin for python project, because phpMyAdmin is meant for MySQL databases. If you are using MySQL, then regardless of whether you are using PHP or python, you can use phpMyAdmin.</p>
9
2009-09-26T06:08:12Z
[ "python", "phpmyadmin" ]
phpMyAdmin equivalent in python?
1,480,453
<p>Is there a python equivalent of phpMyAdmin?</p> <p>Here's why I'm looking for a python version of phpmyadmin: While I agree that phpmyadmin really rocks, I don't want to run php on my server. I'd like to move from apache2-prefork to apache2-mpm-worker. Worker blows the doors off of prefork for performance, but php5 doesn't work with worker. (Technically it does, but it's far more complicated.) The extra memory and performance penalty for having php on this server is large to me.</p>
27
2009-09-26T04:51:49Z
13,483,043
<p>I'm basing my answer off the last sentence of your question, "[the] extra memory and performance penalty for having php on this server", because it sounds like you don't want php on that server, even though "phpmyadmin rocks". From that, I would suggest using phpMyAdmin to manage the MySQL database remotely, which you can find an example of <a href="http://archive09.linux.com/feature/130016" rel="nofollow">here</a>.</p>
1
2012-11-20T22:08:14Z
[ "python", "phpmyadmin" ]
phpMyAdmin equivalent in python?
1,480,453
<p>Is there a python equivalent of phpMyAdmin?</p> <p>Here's why I'm looking for a python version of phpmyadmin: While I agree that phpmyadmin really rocks, I don't want to run php on my server. I'd like to move from apache2-prefork to apache2-mpm-worker. Worker blows the doors off of prefork for performance, but php5 doesn't work with worker. (Technically it does, but it's far more complicated.) The extra memory and performance penalty for having php on this server is large to me.</p>
27
2009-09-26T04:51:49Z
22,571,406
<p>I don't think there is an alternative to phpMyAdmin. <a href="https://github.com/ChipaKraken/pythonMyAdmin" rel="nofollow">pythonMyAdmin</a> doesn't seems mature.</p> <p>The philosophy in python is to create the databease with the ORM and after to manage it through the web framework admin page (like the one in Django).</p> <p>A lightweight alternative is using <a href="http://flask.pocoo.org/" rel="nofollow">Flask</a> and <a href="https://flask-admin.readthedocs.org/en/latest/" rel="nofollow">Flask-Admin</a> with a SQLAlchemy model.</p>
2
2014-03-21T23:39:10Z
[ "python", "phpmyadmin" ]
Python interpreter as a c++ class
1,480,490
<p>I am working on embedding python in to c++. In some peculiar case I require two separate instances of the interpreter in same thread.</p> <p>Can I wrap Python interpreter in to a c++ class and get services from two or more class instances?</p>
7
2009-09-26T05:28:18Z
1,480,578
<p>You can, but I'd recommend you not to re-implement a Python interpreter when there is a standard implementation. Use <strong>boost::python</strong> to interface with Python.</p>
3
2009-09-26T06:28:08Z
[ "c++", "python", "multithreading", "python-c-api", "python-embedding" ]
Python interpreter as a c++ class
1,480,490
<p>I am working on embedding python in to c++. In some peculiar case I require two separate instances of the interpreter in same thread.</p> <p>Can I wrap Python interpreter in to a c++ class and get services from two or more class instances?</p>
7
2009-09-26T05:28:18Z
1,480,900
<p>Callin <code>Py_Initialize()</code> twice won't work well, however <a href="http://docs.python.org/c-api/init.html#Py%5FNewInterpreter"><code>Py_NewInterpreter</code></a> can work, depending on what you're trying to do. Read the docs carefully, you have to hold the GIL when calling this.</p>
6
2009-09-26T10:01:10Z
[ "c++", "python", "multithreading", "python-c-api", "python-embedding" ]
Python interpreter as a c++ class
1,480,490
<p>I am working on embedding python in to c++. In some peculiar case I require two separate instances of the interpreter in same thread.</p> <p>Can I wrap Python interpreter in to a c++ class and get services from two or more class instances?</p>
7
2009-09-26T05:28:18Z
1,515,293
<p>I don't think you are the first person to want to do this, unfortunately I believe it is not possible. Are you able to run the python interperters as separate processes and use RPC?</p>
1
2009-10-04T01:00:56Z
[ "c++", "python", "multithreading", "python-c-api", "python-embedding" ]
Python interpreter as a c++ class
1,480,490
<p>I am working on embedding python in to c++. In some peculiar case I require two separate instances of the interpreter in same thread.</p> <p>Can I wrap Python interpreter in to a c++ class and get services from two or more class instances?</p>
7
2009-09-26T05:28:18Z
1,518,878
<ul> <li>You can let the python interpreter live outside of your application memory space. Just embed the interpreter in a DLL.</li> <li>You can set up &amp; save python contexts to simulate two different interpreters.</li> </ul>
0
2009-10-05T08:45:55Z
[ "c++", "python", "multithreading", "python-c-api", "python-embedding" ]
Python interpreter as a c++ class
1,480,490
<p>I am working on embedding python in to c++. In some peculiar case I require two separate instances of the interpreter in same thread.</p> <p>Can I wrap Python interpreter in to a c++ class and get services from two or more class instances?</p>
7
2009-09-26T05:28:18Z
8,849,082
<p>I have used Py_NewInterpreter for different interpreters in different threads, but this should also work for several interpreters within one thread:</p> <p>In the main thread:</p> <pre><code>Py_Initialize(); PyEval_InitThreads(); mainThreadState = PyEval_SaveThread(); </code></pre> <p>For each interpreter instance (in any thread):</p> <pre><code>// initialize interpreter PyEval_AcquireLock(); // get the GIL myThreadState = Py_NewInterpreter(); ... // call python code PyEval_ReleaseThread(myThreadState); // swap out thread state + release the GIL ... // any other code // continue with interpreter PyEval_AcquireThread(myThreadState); // get GIL + swap in thread state ... // call python code PyEval_ReleaseThread(myThreadState); ... // any other code // finish with interpreter PyEval_AcquireThread(myThreadState); ... // call python code Py_EndInterpreter(myThreadState); PyEval_ReleaseLock(); // release the GIL </code></pre> <p>Note that you need a variable myThreadState for each interpreter instance!</p> <p>Finally the finish in the main thread:</p> <pre><code>PyEval_RestoreThread(mainThreadState); Py_Finalize(); </code></pre> <p>There are some restrictions with using several interpreter instances (they seem not to be totally independent), but in most cases this does not seem to cause problems.</p>
12
2012-01-13T10:28:54Z
[ "c++", "python", "multithreading", "python-c-api", "python-embedding" ]
Python interpreter as a c++ class
1,480,490
<p>I am working on embedding python in to c++. In some peculiar case I require two separate instances of the interpreter in same thread.</p> <p>Can I wrap Python interpreter in to a c++ class and get services from two or more class instances?</p>
7
2009-09-26T05:28:18Z
29,132,983
<p>mosaik's answer did not work in my situation where my module is a plugin to a host application that already initializes python. I was able to get it to work with the following code.</p> <pre><code>// initialize interpreter ::PyEval_InitThreads(); ::PyThreadState *mainThread = ::PyThreadState_Get(); myState = ::Py_NewInterpreter(); ... // call python code ::PyThreadState_Swap(mainThread); ... // any other code mainThread = ::PyThreadState_Swap(myState) ... // call python code ::PyThreadState_Swap(mainThread) ... // any other code // finished with interpreter mainThread = ::PyThreadState_Swap(myState) ::Py_EndInterpreter(myState); ::PyThreadState_Swap(mainThread) </code></pre> <p>When I called <code>PyEval_AcquireLock()</code> the program blocked and the function did not return. Further, calling <code>PyEval_ReleaseThread(myState)</code> seemed to invalidate the interpreter also.</p>
0
2015-03-18T21:24:31Z
[ "c++", "python", "multithreading", "python-c-api", "python-embedding" ]
How can I, on some global keystroke, paste some text to current active application in linux with Python or C++
1,480,655
<p>I want to write app, which will work like a daemon and on some global keystroke paste some text to current active application (text editor, browser, jabber client) I think i will need to use some low level xserver api. How i can do this with Python or C++ ?</p>
1
2009-09-26T07:18:01Z
1,480,730
<h3>Probably you want to hack <a href="http://sourceforge.net/projects/xmon/" rel="nofollow">xmon</a>...</h3> <p><hr /></p> <p>AFAIK there is no easy way to hook the X protocol. You will need to do "deep packet inspection", which would be fairly easy in the application event loop but not so easy, as you want, "like a daemon", or on "global keystroke[s]".</p> <p>So, I know this is really brute force and ignorance, but I think you will have to wrap the X server by starting it on a non-standard port or publishing an environment variable, just like you were using something like an SSH tunnel to forward an X server connection.</p> <p>There is an X protocol monitor called Xmon for which source is available. It might be a good starting point.</p>
1
2009-09-26T08:03:14Z
[ "c++", "python", "linux", "xserver" ]
How can I, on some global keystroke, paste some text to current active application in linux with Python or C++
1,480,655
<p>I want to write app, which will work like a daemon and on some global keystroke paste some text to current active application (text editor, browser, jabber client) I think i will need to use some low level xserver api. How i can do this with Python or C++ ?</p>
1
2009-09-26T07:18:01Z
1,480,829
<p>You can use the <a href="http://xmacro.sourceforge.net/" rel="nofollow">xmacroplay utility from xmacro</a> to do this under X windows I think. Either use it directly - send it commands to standard input using the subprocess module, or read the source code and find out how it does it! I don't think there are python bindings for it.</p> <p>From the xmacroplay website</p> <pre><code>xmacroplay: Reads lines from the standard input. It can understand the following lines: Delay [sec] - delays the program with [sec] secundums ButtonPress [n] - sends a ButtonPress event with button [n] this emulates the pressing of the mouse button [n] ButtonRelease [n] - sends a ButtonRelease event with button [n] this emulates the releasing of the mouse button [n] ... snip lots more ... </code></pre> <p>This is probably the command you are interested in</p> <pre><code>String [max. 1024 long string] - Sends the string as single characters converted to KeyPress and KeyRelease events based on a character table in chartbl.h (currently only Latin1 is used...) </code></pre> <p>There is also <a href="http://www.gnu.org/software/xnee/" rel="nofollow">Xnee</a> which does a similar thing.</p>
0
2009-09-26T09:16:02Z
[ "c++", "python", "linux", "xserver" ]
Socket program Python vs C++ (Winsock)
1,481,103
<p>I have python program which works perfectly for internet chatting. But program built on similar sockets in C++ do not work over internet.<br /> Python program</p> <pre><code>import thread import socket class p2p: def __init__(self): socket.setdefaulttimeout(50) self.port = 3000 #Destination IP HERE self.peerId = '59.95.18.156' #declaring sender socket self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM ) self.socket.bind(('', self.port)) self.socket.settimeout(50) #starting thread for reception thread.start_new_thread(self.receiveData, ()) while 1: data=raw_input('&gt;') #print 'sending...'+data self.sendData(data) def receiveData(self): while 1: data,address=self.socket.recvfrom(1024) print data def sendData(self,data): self.socket.sendto(data, (self.peerId,self.port)) if __name__=='__main__': print 'Started......' p2p() </code></pre> <p>I want to built similar functionality in c++. I took server and client programs from MSDN. But they are working only on localhost not over internet .. they are as follows...</p> <p>Sender</p> <pre><code>#include &lt;stdio.h&gt; #include "winsock2.h" void main() { WSADATA wsaData; SOCKET SendSocket; sockaddr_in RecvAddr; int Port = 3000; char SendBuf[3]={'a','2','\0'}; int BufLen = 3; //--------------------------------------------- // Initialize Winsock WSAStartup(MAKEWORD(2,2), &amp;wsaData); //--------------------------------------------- // Create a socket for sending data SendSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); //--------------------------------------------- // Set up the RecvAddr structure with the IP address of // the receiver (in this example case "123.456.789.1") // and the specified port number. RecvAddr.sin_family = AF_INET; RecvAddr.sin_port = htons(Port); RecvAddr.sin_addr.s_addr = inet_addr("59.95.18.156"); //--------------------------------------------- // Send a datagram to the receiver printf("Sending a datagram to the receiver...\n"); sendto(SendSocket, SendBuf, BufLen, 0, (SOCKADDR *) &amp;RecvAddr, sizeof(RecvAddr)); //--------------------------------------------- // When the application is finished sending, close the socket. printf("Finished sending. Closing socket.\n"); closesocket(SendSocket); //--------------------------------------------- // Clean up and quit. printf("Exiting.\n"); WSACleanup(); return; } </code></pre> <p>Receiver</p> <pre><code>#include &lt;stdio.h&gt; #include "winsock2.h" #include&lt;iostream&gt; using namespace std; void main() { WSADATA wsaData; SOCKET RecvSocket; sockaddr_in RecvAddr; int Port = 3000; char RecvBuf[3]; int BufLen = 3; sockaddr_in SenderAddr; int SenderAddrSize = sizeof(SenderAddr); //----------------------------------------------- // Initialize Winsock WSAStartup(MAKEWORD(2,2), &amp;wsaData); //----------------------------------------------- // Create a receiver socket to receive datagrams RecvSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); //----------------------------------------------- // Bind the socket to any address and the specified port. RecvAddr.sin_family = AF_INET; RecvAddr.sin_port = htons(Port); RecvAddr.sin_addr.s_addr = htonl(INADDR_ANY); bind(RecvSocket, (SOCKADDR *) &amp;RecvAddr, sizeof(RecvAddr)); //----------------------------------------------- // Call the recvfrom function to receive datagrams // on the bound socket. printf("Receiving datagrams...\n"); while(true){ recvfrom(RecvSocket, RecvBuf, BufLen, 0, (SOCKADDR *)&amp;SenderAddr, &amp;SenderAddrSize); cout&lt;&lt;RecvBuf; } //----------------------------------------------- // Close the socket when finished receiving datagrams printf("Finished receiving. Closing socket.\n"); closesocket(RecvSocket); //----------------------------------------------- // Clean up and exit. printf("Exiting.\n"); WSACleanup(); return; } </code></pre> <p>Thank you very much for any help .. </p> <p>Sorry for too much code in the question.</p>
0
2009-09-26T12:17:37Z
1,481,797
<p>Per <a href="http://msdn.microsoft.com/en-us/library/ms740148%28VS.85%29.aspx" rel="nofollow">the docs</a>, <code>sendto</code> returns a number that's >0 (number of bytes sent) for success, &lt;0 for failure, and in the latter case you use <a href="http://msdn.microsoft.com/en-us/library/ms741580%28VS.85%29.aspx" rel="nofollow">WSAGetLastError</a> for more information. So try saving the <code>sendto</code> result, printing it (as well as the size of the data you're trying to send), and in case of error print the last-error code too. What do you see then?</p>
1
2009-09-26T18:13:42Z
[ "c++", "python", "sockets", "winsock" ]
pythonic format for indices
1,481,192
<p>I am after a string format to efficiently represent a set of indices. For example "1-3,6,8-10,16" would produce [1,2,3,6,8,9,10,16]</p> <p>Ideally I would also be able to represent infinite sequences. </p> <p>Is there an existing standard way of doing this? Or a good library? Or can you propose your own format? </p> <p>thanks!</p> <p>Edit: Wow! - thanks for all the well considered responses. I agree I should use ':' instead. Any ideas about infinite lists? I was thinking of using "1.." to represent all positive numbers.</p> <p>The use case is for a shopping cart. For some products I need to restrict product sales to multiples of X, for others any positive number. So I am after a string format to represent this in the database.</p>
6
2009-09-26T13:21:53Z
1,481,262
<p>If you're into something Pythonic, I think <code>1:3,6,8:10,16</code> would be a better choice, as <code>x:y</code> is a standard notation for index range and the syntax allows you to use this notation on objects. Note that the call</p> <pre><code>z[1:3,6,8:10,16] </code></pre> <p>gets translated into</p> <pre><code>z.__getitem__((slice(1, 3, None), 6, slice(8, 10, None), 16)) </code></pre> <p>Even though this is a <code>TypeError</code> if <code>z</code> is a built-in container, you're free to create the class that will return something reasonable, e.g. as NumPy's arrays.</p> <p>You might also say that by convention <code>5:</code> and <code>:5</code> represent infinite index ranges (this is a bit stretched as Python has no built-in types with negative or infinitely large positive indexes).</p> <p>And here's the parser (a beautiful one-liner that suffers from <code>slice(16, None, None)</code> glitch described below):</p> <pre><code>def parse(s): return [slice(*map(int, x.split(':'))) for x in s.split(',')] </code></pre> <p>There's one pitfall, however: <code>8:10</code> by definition includes only indices 8 and 9 -- without upper bound. If that's unacceptable for your purposes, you certainly need a different format and <code>1-3,6,8-10,16</code> looks good to me. The parser then would be </p> <pre><code>def myslice(start, stop=None, step=None): return slice(start, (stop if stop is not None else start) + 1, step) def parse(s): return [myslice(*map(int, x.split('-'))) for x in s.split(',')] </code></pre> <p><hr /></p> <p><strong>Update:</strong> here's the full parser for a combined format:</p> <pre><code>from sys import maxsize as INF def indices(s: 'string with indices list') -&gt; 'indices generator': for x in s.split(','): splitter = ':' if (':' in x) or (x[0] == '-') else '-' ix = x.split(splitter) start = int(ix[0]) if ix[0] is not '' else -INF if len(ix) == 1: stop = start + 1 else: stop = int(ix[1]) if ix[1] is not '' else INF step = int(ix[2]) if len(ix) &gt; 2 else 1 for y in range(start, stop + (splitter == '-'), step): yield y </code></pre> <p>This handles negative numbers as well, so</p> <pre><code> print(list(indices('-5, 1:3, 6, 8:15:2, 20-25, 18'))) </code></pre> <p>prints</p> <pre><code>[-5, 1, 2, 6, 7, 8, 10, 12, 14, 20, 21, 22, 23, 24, 25, 18, 19] </code></pre> <p><hr /></p> <p>Yet another alternative is to use <code>...</code> (which Python recognizes as the built-in constant Ellipsis so you can call <code>z[...]</code> if you want) but I think <code>1,...,3,6, 8,...,10,16</code> is less readable.</p>
3
2009-09-26T13:48:36Z
[ "python", "indexing", "set", "sequence" ]
pythonic format for indices
1,481,192
<p>I am after a string format to efficiently represent a set of indices. For example "1-3,6,8-10,16" would produce [1,2,3,6,8,9,10,16]</p> <p>Ideally I would also be able to represent infinite sequences. </p> <p>Is there an existing standard way of doing this? Or a good library? Or can you propose your own format? </p> <p>thanks!</p> <p>Edit: Wow! - thanks for all the well considered responses. I agree I should use ':' instead. Any ideas about infinite lists? I was thinking of using "1.." to represent all positive numbers.</p> <p>The use case is for a shopping cart. For some products I need to restrict product sales to multiples of X, for others any positive number. So I am after a string format to represent this in the database.</p>
6
2009-09-26T13:21:53Z
1,481,263
<p>This is probably about as lazily as it can be done, meaning it will be okay for even very large lists:</p> <pre><code>def makerange(s): for nums in s.split(","): # whole list comma-delimited range_ = nums.split("-") # number might have a dash - if not, no big deal start = int(range_[0]) for i in xrange(start, start + 1 if len(range_) == 1 else int(range_[1]) + 1): yield i s = "1-3,6,8-10,16" print list(makerange(s)) </code></pre> <p>output:</p> <pre><code>[1, 2, 3, 6, 8, 9, 10, 16] </code></pre>
2
2009-09-26T13:48:38Z
[ "python", "indexing", "set", "sequence" ]
pythonic format for indices
1,481,192
<p>I am after a string format to efficiently represent a set of indices. For example "1-3,6,8-10,16" would produce [1,2,3,6,8,9,10,16]</p> <p>Ideally I would also be able to represent infinite sequences. </p> <p>Is there an existing standard way of doing this? Or a good library? Or can you propose your own format? </p> <p>thanks!</p> <p>Edit: Wow! - thanks for all the well considered responses. I agree I should use ':' instead. Any ideas about infinite lists? I was thinking of using "1.." to represent all positive numbers.</p> <p>The use case is for a shopping cart. For some products I need to restrict product sales to multiples of X, for others any positive number. So I am after a string format to represent this in the database.</p>
6
2009-09-26T13:21:53Z
1,481,267
<p>This looked like a fun puzzle to go with my coffee this morning. If you settle on your given syntax (which looks okay to me, with some notes at the end), here is a pyparsing converter that will take your input string and return a list of integers:</p> <pre><code>from pyparsing import * integer = Word(nums).setParseAction(lambda t : int(t[0])) intrange = integer("start") + '-' + integer("end") def validateRange(tokens): if tokens.from_ &gt; tokens.to: raise Exception("invalid range, start must be &lt;= end") intrange.setParseAction(validateRange) intrange.addParseAction(lambda t: list(range(t.start, t.end+1))) indices = delimitedList(intrange | integer) def mergeRanges(tokens): ret = set() for item in tokens: if isinstance(item,int): ret.add(item) else: ret += set(item) return sorted(ret) indices.setParseAction(mergeRanges) test = "1-3,6,8-10,16" print indices.parseString(test) </code></pre> <p>This also takes care of any overlapping or duplicate entries, such "3-8,4,6,3,4", and returns a list of just the unique integers.</p> <p>The parser takes care of validating that ranges like "10-3" are not allowed. If you really wanted to allow this, and have something like "1,5-3,7" return 1,5,4,3,7, then you could tweak the intrange and mergeRanges parse actions to get this simpler result (and discard the validateRange parse action altogether).</p> <p>You are very likely to get whitespace in your expressions, I assume that this is not significant. "1, 2, 3-6" would be handled the same as "1,2,3-6". Pyparsing does this by default, so you don't see any special whitespace handling in the code above (but it's there...)</p> <p>This parser does not handle negative indices, but if that were needed too, just change the definition of integer to:</p> <pre><code>integer = Combine(Optional('-') + Word(nums)).setParseAction(lambda t : int(t[0])) </code></pre> <p>Your example didn't list any negatives, so I left it out for now.</p> <p>Python uses ':' for a ranging delimiter, so your original string could have looked like "1:3,6,8:10,16", and Pascal used '..' for array ranges, giving "1..3,6,8..10,16" - meh, dashes are just as good as far as I'm concerned.</p>
1
2009-09-26T13:50:38Z
[ "python", "indexing", "set", "sequence" ]
pythonic format for indices
1,481,192
<p>I am after a string format to efficiently represent a set of indices. For example "1-3,6,8-10,16" would produce [1,2,3,6,8,9,10,16]</p> <p>Ideally I would also be able to represent infinite sequences. </p> <p>Is there an existing standard way of doing this? Or a good library? Or can you propose your own format? </p> <p>thanks!</p> <p>Edit: Wow! - thanks for all the well considered responses. I agree I should use ':' instead. Any ideas about infinite lists? I was thinking of using "1.." to represent all positive numbers.</p> <p>The use case is for a shopping cart. For some products I need to restrict product sales to multiples of X, for others any positive number. So I am after a string format to represent this in the database.</p>
6
2009-09-26T13:21:53Z
1,481,281
<p>You don't need a string for that, This is as simple as it can get:</p> <pre><code>from types import SliceType class sequence(object): def __getitem__(self, item): for a in item: if isinstance(a, SliceType): i = a.start step = a.step if a.step else 1 while True: if a.stop and i &gt; a.stop: break yield i i += step else: yield a print list(sequence()[1:3,6,8:10,16]) </code></pre> <p>Output:</p> <pre><code>[1, 2, 3, 6, 8, 9, 10, 16] </code></pre> <p>I'm using Python slice type power to express the sequence ranges. I'm also using generators to be memory efficient.</p> <p>Please note that I'm adding 1 to the slice stop, otherwise the ranges will be different because the stop in slices is not included.</p> <p>It supports steps:</p> <pre><code>&gt;&gt;&gt; list(sequence()[1:3,6,8:20:2]) [1, 2, 3, 6, 8, 10, 12, 14, 16, 18, 20] </code></pre> <p>And infinite sequences:</p> <pre><code>sequence()[1:3,6,8:] 1, 2, 3, 6, 8, 9, 10, ... </code></pre> <p><hr /></p> <p>If you have to give it a string then you can combine @ilya n. parser with this solution. I'll extend @ilya n. parser to support indexes as well as ranges:</p> <pre><code>def parser(input): ranges = [a.split('-') for a in input.split(',')] return [slice(*map(int, a)) if len(a) &gt; 1 else int(a[0]) for a in ranges] </code></pre> <p>Now you can use it like this:</p> <pre><code>&gt;&gt;&gt; print list(sequence()[parser('1-3,6,8-10,16')]) [1, 2, 3, 6, 8, 9, 10, 16] </code></pre>
7
2009-09-26T14:00:28Z
[ "python", "indexing", "set", "sequence" ]
pythonic format for indices
1,481,192
<p>I am after a string format to efficiently represent a set of indices. For example "1-3,6,8-10,16" would produce [1,2,3,6,8,9,10,16]</p> <p>Ideally I would also be able to represent infinite sequences. </p> <p>Is there an existing standard way of doing this? Or a good library? Or can you propose your own format? </p> <p>thanks!</p> <p>Edit: Wow! - thanks for all the well considered responses. I agree I should use ':' instead. Any ideas about infinite lists? I was thinking of using "1.." to represent all positive numbers.</p> <p>The use case is for a shopping cart. For some products I need to restrict product sales to multiples of X, for others any positive number. So I am after a string format to represent this in the database.</p>
6
2009-09-26T13:21:53Z
1,481,985
<pre><code>import sys class Sequencer(object): def __getitem__(self, items): if not isinstance(items, (tuple, list)): items = [items] for item in items: if isinstance(item, slice): for i in xrange(*item.indices(sys.maxint)): yield i else: yield item &gt;&gt;&gt; s = Sequencer() &gt;&gt;&gt; print list(s[1:3,6,8:10,16]) [1, 2, 6, 8, 9, 16] </code></pre> <p>Note that I am using the <code>xrange</code> builtin to generate the sequence. That seems awkward at first because it doesn't include the upper number of sequences by default, however it proves to be very convenient. You can do things like:</p> <pre><code>&gt;&gt;&gt; print list(s[1:10:3,5,5,16,13:5:-1]) [1, 4, 7, 5, 5, 16, 13, 12, 11, 10, 9, 8, 7, 6] </code></pre> <p>Which means you can use the <em><code>step</code></em> part of <code>xrange</code>.</p>
1
2009-09-26T19:28:50Z
[ "python", "indexing", "set", "sequence" ]
How can I make Python see sqlite?
1,481,237
<p>I cannot use sqlite3 (build python package), for the reason that <code>_sqlite3.so</code> file is missing. I found that people had the same problem and they resolved it <a href="http://www.linuxquestions.org/questions/slackware-14/no-sqlite3.so-in-usrlibpython2.5lib-dynload-599027/" rel="nofollow">here</a>. To solve my problem I have to "install <code>sqlite3</code> and recompile Python". I also found out that the problem can be solved by "building from source and moving the library to <code>/usr/lib/python2.5/lib-dynload/</code>".</p> <p>As I have been told to here, I have to install sqlite from the source and copy newly compiled files to my Python directory (nothing was said about "recompile Python"). Well, I have installed sqlite and now I have to copy something to my <code>/lib-dynload/</code> directory.</p> <p>I am not sure what exactly I should copy. In my <code>/lib-dynload/</code> directory I have only .so files. And in my <code>sqlite-3.6.18</code> I do not have any <code>*.so</code> files (it makes me suspicious). I had this problem since I did not have <code>_sqlite3.so</code> file in <code>/lib-dynload/</code>. By compilation of sqlite I got some new files (for example <code>sqlite3.o</code> and <code>sqlite3.lo</code>) but <code>not _sqlite3.so</code>.</p> <p>P.S. Some details: <br>1. I use Python 2.6.2 (which I installed locally). <br>2. I do not have root permissions. <br>3. I had already sqlite installed globally on the machine by root. <br>4. I just installed sqlite locally. <br>5. My OS is CentOS release 5.3 (Final). <br>6. When I type in Python command line <code>import sqlite3</code> I get:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/loctopu/opt/lib/python2.6/sqlite3/__init__.py", line 24, in &lt;module&gt; from dbapi2 import * File "/home/loctopu/opt/lib/python2.6/sqlite3/dbapi2.py", line 27, in &lt;module&gt; from _sqlite3 import * ImportError: No module named _sqlite3 </code></pre>
1
2009-09-26T13:39:23Z
2,046,217
<p>I don't have exact answer, but few hints here</p> <ul> <li><p>To install python from source, you don't need to be root, you can always install at <code>/home/USERNAME/usr</code>, for example when you do configure, do like <code>./configure --prefix=/home/USERNAME/usr</code></p></li> <li><p>Installing sqlite binaries does not mean its included python extension (instead, sqlite dev files are needed when you compile python)</p></li> <li><p>proper import usage of sqlite3 is <code>import sqlite3</code></p></li> </ul>
0
2010-01-12T02:02:39Z
[ "python", "sqlite", "pysqlite" ]
Python - Same line of code only works the second time it called?
1,481,264
<p>Sorry I couldn't really describe my problem much better in the title.</p> <p>I am trying to learn Python, and came across this strange behavior and was hoping someone could explain this to me.</p> <p>I am running Ubuntu 8.10 and python 2.5.2</p> <p>First I import xml.dom<br /> Then I create an instance of a minidom (using its fully qaulified name xml.dom.minidom)<br /> This fails, but then if I run that same line again, it works! See below:</p> <pre><code>$&gt; python Python 2.5.2 (r252:60911, Oct 5 2008, 19:29:17) [GCC 4.3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import xml.dom &gt;&gt;&gt; xml.dom.minidom.parseString("&lt;xml&gt;&lt;item/&gt;&lt;/xml&gt;") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'module' object has no attribute 'minidom' &gt;&gt;&gt; xml.dom.minidom.parseString("&lt;xml&gt;&lt;item/&gt;&lt;/xml&gt;") &lt;xml.dom.minidom.Document instance at 0x7fd914e42fc8&gt; </code></pre> <p>I tried on another machine, and if consistently fails.</p>
3
2009-09-26T13:49:42Z
1,481,273
<p>minidom is a module so you should need</p> <pre><code>import xml.dom.minidom xml.dom.minidom.parseString("&lt;xml&gt;&lt;item/&gt;&lt;/xml&gt;") </code></pre> <p>I don't know how you got the second parseString to work it fails on my python as in your other machine</p>
4
2009-09-26T13:54:35Z
[ "python" ]
Python - Same line of code only works the second time it called?
1,481,264
<p>Sorry I couldn't really describe my problem much better in the title.</p> <p>I am trying to learn Python, and came across this strange behavior and was hoping someone could explain this to me.</p> <p>I am running Ubuntu 8.10 and python 2.5.2</p> <p>First I import xml.dom<br /> Then I create an instance of a minidom (using its fully qaulified name xml.dom.minidom)<br /> This fails, but then if I run that same line again, it works! See below:</p> <pre><code>$&gt; python Python 2.5.2 (r252:60911, Oct 5 2008, 19:29:17) [GCC 4.3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import xml.dom &gt;&gt;&gt; xml.dom.minidom.parseString("&lt;xml&gt;&lt;item/&gt;&lt;/xml&gt;") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'module' object has no attribute 'minidom' &gt;&gt;&gt; xml.dom.minidom.parseString("&lt;xml&gt;&lt;item/&gt;&lt;/xml&gt;") &lt;xml.dom.minidom.Document instance at 0x7fd914e42fc8&gt; </code></pre> <p>I tried on another machine, and if consistently fails.</p>
3
2009-09-26T13:49:42Z
1,481,280
<p>I couldn't get your code to work even on the second try (using Python 2.6.1 on Snow Leopard). :-) However, here's one version that does work for me:</p> <pre><code>&gt;&gt;&gt; from xml.dom.minidom import parseString &gt;&gt;&gt; parseString("&lt;xml&gt;&lt;item/&gt;&lt;/xml&gt;") &lt;xml.dom.minidom.Document instance at 0x100539830&gt; </code></pre> <p>Personally, I prefer this style of import. It tends to make for much less verbose code.</p>
0
2009-09-26T13:59:38Z
[ "python" ]
Python - Same line of code only works the second time it called?
1,481,264
<p>Sorry I couldn't really describe my problem much better in the title.</p> <p>I am trying to learn Python, and came across this strange behavior and was hoping someone could explain this to me.</p> <p>I am running Ubuntu 8.10 and python 2.5.2</p> <p>First I import xml.dom<br /> Then I create an instance of a minidom (using its fully qaulified name xml.dom.minidom)<br /> This fails, but then if I run that same line again, it works! See below:</p> <pre><code>$&gt; python Python 2.5.2 (r252:60911, Oct 5 2008, 19:29:17) [GCC 4.3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import xml.dom &gt;&gt;&gt; xml.dom.minidom.parseString("&lt;xml&gt;&lt;item/&gt;&lt;/xml&gt;") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'module' object has no attribute 'minidom' &gt;&gt;&gt; xml.dom.minidom.parseString("&lt;xml&gt;&lt;item/&gt;&lt;/xml&gt;") &lt;xml.dom.minidom.Document instance at 0x7fd914e42fc8&gt; </code></pre> <p>I tried on another machine, and if consistently fails.</p>
3
2009-09-26T13:49:42Z
1,481,322
<p>I can replicate your behaviour on Ubuntu 9.04 (python 2.6.2). If you do <code>python -v</code> you can see the first error causes lots of extra imports. Since it doesn't happen for everybody, I can only assume the Ubuntu/Debian have added something to python to auto load modules.</p> <p>Still the recommended action is to <code>import xml.dom.minidom</code>.</p>
0
2009-09-26T14:28:58Z
[ "python" ]
Python - Same line of code only works the second time it called?
1,481,264
<p>Sorry I couldn't really describe my problem much better in the title.</p> <p>I am trying to learn Python, and came across this strange behavior and was hoping someone could explain this to me.</p> <p>I am running Ubuntu 8.10 and python 2.5.2</p> <p>First I import xml.dom<br /> Then I create an instance of a minidom (using its fully qaulified name xml.dom.minidom)<br /> This fails, but then if I run that same line again, it works! See below:</p> <pre><code>$&gt; python Python 2.5.2 (r252:60911, Oct 5 2008, 19:29:17) [GCC 4.3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import xml.dom &gt;&gt;&gt; xml.dom.minidom.parseString("&lt;xml&gt;&lt;item/&gt;&lt;/xml&gt;") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'module' object has no attribute 'minidom' &gt;&gt;&gt; xml.dom.minidom.parseString("&lt;xml&gt;&lt;item/&gt;&lt;/xml&gt;") &lt;xml.dom.minidom.Document instance at 0x7fd914e42fc8&gt; </code></pre> <p>I tried on another machine, and if consistently fails.</p>
3
2009-09-26T13:49:42Z
1,481,378
<p>The problem is in <code>apport_python_hook.apport_excepthook()</code> as a side effect it imports <code>xml.dom.minidom</code>.</p> <p>Without <code>apport_except_hook</code>:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; sys.excepthook = sys.__excepthook__ &gt;&gt;&gt; import xml.dom &gt;&gt;&gt; xml.dom.minidom Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'module' object has no attribute 'minidom' &gt;&gt;&gt; xml.dom.minidom Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'module' object has no attribute 'minidom' &gt;&gt;&gt; </code></pre> <p>With <code>apport_except_hook</code>:</p> <pre><code>&gt;&gt;&gt; import apport_python_hook &gt;&gt;&gt; apport_python_hook.install() &gt;&gt;&gt; xml.dom.minidom Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'module' object has no attribute 'minidom' &gt;&gt;&gt; xml.dom.minidom &lt;module 'xml.dom.minidom' from '../lib/python2.6/xml/dom/minidom.pyc'&gt; </code></pre>
7
2009-09-26T14:56:27Z
[ "python" ]
how to configure apache on XP for python 2.6.2 and what do you prefer, python with framework/without?
1,481,309
<p>I am starting python today. It will be my pleasure to have your help.</p>
2
2009-09-26T14:17:10Z
1,481,329
<p>If you are starting Python today, why tackle web development immediately? I'd start off with "hello world" in the console.</p>
0
2009-09-26T14:31:42Z
[ "python", "apache", "windows-xp" ]
how to configure apache on XP for python 2.6.2 and what do you prefer, python with framework/without?
1,481,309
<p>I am starting python today. It will be my pleasure to have your help.</p>
2
2009-09-26T14:17:10Z
1,481,362
<p>About a framework - choose the one you'll like. You can find most of them on <a href="http://wiki.python.org/moin/WebFrameworks" rel="nofollow">Python wiki</a>.</p> <p>About Apache - if you choose a framework, it'll probably have some kind of development web server built-in, with better debugging capabilities than Apache installation. If you really want Apache, then you could <a href="http://code.google.com/p/modwsgi/wiki/InstallationOnWindows" rel="nofollow">install</a> and <a href="http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide" rel="nofollow">configure</a> <a href="http://code.google.com/p/modwsgi/" rel="nofollow">mod_wsgi</a>.</p>
1
2009-09-26T14:48:07Z
[ "python", "apache", "windows-xp" ]
How to add header while making soap request using soappy
1,481,313
<p>I have WSDL file, using that i wanted to make soap request which will look exactly like this --</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"&gt; &lt;soap:Header&gt; &lt;AuthSoapHd xmlns="http://foobar.org/"&gt; &lt;strUserName&gt;string&lt;/strUserName&gt; &lt;strPassword&gt;string&lt;/strPassword&gt; &lt;/AuthSoapHd&gt; &lt;/soap:Header&gt; &lt;soap:Body&gt; &lt;SearchQuotes xmlns="http://foobar.org/"&gt; &lt;searchtxt&gt;string&lt;/searchtxt&gt; &lt;/SearchQuotes&gt; &lt;/soap:Body&gt; &lt;/soap:Envelope&gt; </code></pre> <p>To sovle this, i did this</p> <pre><code>&gt;&gt; from SOAPpy import WSDL &gt;&gt; WSDLFILE = '/path/foo.wsdl' &gt;&gt; server = WSDL.Proxy(WSDLFILE) &gt;&gt; server.SearchQuotes('rel') </code></pre> <p>I get this error </p> <pre><code>faultType: &lt;Fault soap:Server: System.Web.Services.Protocols.SoapException: Server was unable to process request. ---&gt; System.NullReferenceException: Object reference not set to an instance of an object. </code></pre> <p>The i debugged it and got this </p> <pre><code>*** Outgoing SOAP ****************************************************** &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/1999/XMLSchema" &gt; &lt;SOAP-ENV:Body&gt; &lt;SearchQuotes SOAP-ENC:root="1"&gt; &lt;v1 xsi:type="xsd:string"&gt;rel&lt;/v1&gt; &lt;/SearchQuotes&gt; &lt;/SOAP-ENV:Body&gt; &lt;/SOAP-ENV:Envelope&gt; </code></pre> <p>We can see it doesn't contain any header. I think that WSDL file has some bug. Now, can anyone suggest me how to add header to this outgoing soap request.</p> <p>Any sort of help will be appreciated. Thanks in advance</p>
0
2009-09-26T14:22:13Z
1,481,829
<p>Not tested, but I believe you can use the method <a href="https://svn.origo.ethz.ch/playmobil/trunk/contrib/pywebsvcs/SOAPpy/docs/UsingHeaders.txt" rel="nofollow">the docs</a> suggest to add soap headers, i.e., make and prep a <code>SOAPpy.Header</code> instance, then use <code>server = server._hd (hd)</code> to get a proxy equipped with it (though in your case that does seem to be a workaround attempt to broken WSDL, as you say -- might it be better to fix the WSDL instead?).</p>
0
2009-09-26T18:23:32Z
[ "python", "soap", "soappy" ]
set URL when enter site - pylons
1,481,363
<p>My problem is that when a user enter my website like: www.mywebsite.com</p> <p>I use <a href="http://pylonshq.com" rel="nofollow">pylonshq</a> </p> <p>I want the URL to be change to /#home if its possible via. map.connect. I have no idéa how to fix it via. python, so therefore a guide or maybe some samples would be a help.</p> <p>Right now it looks like this: </p> <pre><code>map.connect('/', controller='home',action='index') </code></pre>
1
2009-09-26T14:48:15Z
1,481,557
<p>Simplest solution is to add js, something like this: location.url += '#home'.</p> <p>Or issue redirect with anchor included (but this won't work in IE).</p>
1
2009-09-26T16:14:28Z
[ "python", "pylons" ]
Python urllib2 HTTPS and proxy NTLM authentication
1,481,398
<p>urllib2 doesn't seem to support HTTPS with proxy authentication in general, even less with NTLM authentication. Anyone knows if there is a patch somewhere for HTTPS on proxy with NTLM authentication.</p> <p>Regards,</p> <p>Laurent</p>
5
2009-09-26T15:03:41Z
1,481,487
<p><a href="http://code.google.com/p/python-ntlm/" rel="nofollow">http://code.google.com/p/python-ntlm/</a></p> <p>I never tried with HTTPS but I think it should work.</p> <p>EDIT: If you are using SSL Tunneling, proxy authentication is a bad idea.</p> <p>Proxy using Basic Auth over HTTPS is not secure when the SSL is tunneled. Your password will be sent in clear (Base64-encoded) to proxy. Lots of people assumes the password will be encrypted inside SSL. It's not true in this case. </p> <p>It's almost impossible to support other encrypted or hashed mechanisms like Digest/NTLM because they all require negotiation (multiple exchanges) and that's not defined in CONNECT protocol. This negotiation happens out of the band of the HTTP connection. It's very hard to implement in proxy/browser also.</p> <p>If this is an enterprise proxy, IP ACL is the only secure solution.</p>
2
2009-09-26T15:49:47Z
[ "python", "authentication", "proxy", "https", "ntlm" ]
Python urllib2 HTTPS and proxy NTLM authentication
1,481,398
<p>urllib2 doesn't seem to support HTTPS with proxy authentication in general, even less with NTLM authentication. Anyone knows if there is a patch somewhere for HTTPS on proxy with NTLM authentication.</p> <p>Regards,</p> <p>Laurent</p>
5
2009-09-26T15:03:41Z
1,481,719
<p>Good recipe (for HTTPS w/proxy) and discussion <a href="http://code.activestate.com/recipes/456195/" rel="nofollow">here</a>, it should be possible to meld that with the python-nltm code @ZZ has already suggested.</p>
1
2009-09-26T17:42:37Z
[ "python", "authentication", "proxy", "https", "ntlm" ]
Python urllib2 HTTPS and proxy NTLM authentication
1,481,398
<p>urllib2 doesn't seem to support HTTPS with proxy authentication in general, even less with NTLM authentication. Anyone knows if there is a patch somewhere for HTTPS on proxy with NTLM authentication.</p> <p>Regards,</p> <p>Laurent</p>
5
2009-09-26T15:03:41Z
1,793,206
<p>Late reply. Urllib2 does not support NTLM proxying but <a href="http://pycurl.sourceforge.net/" rel="nofollow">pycurl</a> does. Excerpt:</p> <pre><code>self._connection = pycurl.Curl() self._connection.setopt(pycurl.PROXY, PROXY_HOST) self._connection.setopt(pycurl.PROXYPORT, PROXY_PORT) self._connection.setopt(pycurl.PROXYUSERPWD, "%s:%s" % (PROXY_USER, PROXY_PASS)) ... </code></pre>
6
2009-11-24T21:56:57Z
[ "python", "authentication", "proxy", "https", "ntlm" ]
What is the __del__ method, How to call it?
1,481,488
<p>I am reading a code. There is a class in which <code>__del__</code> method is defined. I figured out that this method is used to destroy an instance of the class. However, I cannot find a place where this method is used. The main reason for that is that I do not know how this method is used, probably not like that: <code>obj1.del()</code>. So, my questions is how to call the <code>__del__</code> method? Thank you for any help.</p>
29
2009-09-26T15:49:52Z
1,481,512
<p><code>__del__</code> is a <strong>destructor</strong>. It is called when an object is <strong>garbage collected</strong> which happens after all references to the object have been deleted. </p> <p>In a <strong>simple case</strong> this could be right after you say <code>del x</code> or, if <code>x</code> is a local variable, after the function ends. In particular, unless there are circular references, CPython (the standard Python implementation) will garbage collect immediately. </p> <p>However, this is the <strong>implementation detail</strong> of CPython. The only <strong>required</strong> property of Python garbage collection is that it happens <em>after</em> all references have been deleted, so this might not necessary happen <em>right after</em> and <strong>might not happen at all</strong>. </p> <p>Even more, variables can live for a long time for <strong>many reasons</strong>, e.g. a propagating exception or module introspection can keep variable reference count greater than 0. Also, variable can be a part of <strong>cycle of references</strong> — CPython with garbage collection turned on breaks most, but not all, such cycles, and even then only periodically.</p> <p>Since you have no guarantee it's executed, one should <strong>never</strong> put the code that you need to be run into <code>__del__()</code> — instead, this code belongs to <code>finally</code> clause of the <code>try</code> block or to a context manager in a <code>with</code> statement. However, there are <strong>valid use cases</strong> for <code>__del__</code>: e.g. if an object <code>X</code> references <code>Y</code> and also keeps a copy of <code>Y</code> reference in a global <code>cache</code> (<code>cache['X -&gt; Y'] = Y</code>) then it would be polite for <code>X.__del__</code> to also delete the cache entry.</p> <p><strong>If you know</strong> that the destructor provides (in violation of the above guideline) a required cleanup, you might want to <strong>call it directly</strong>, since there is nothing special about it as a method: <code>x.__del__()</code>. Obviously, you should you do so only if you know that it doesn't mind to be called twice. Or, as a last resort, you can redefine this method using</p> <pre><code>type(x).__del__ = my_safe_cleanup_method </code></pre>
64
2009-09-26T15:58:53Z
[ "python", "oop" ]
What is the __del__ method, How to call it?
1,481,488
<p>I am reading a code. There is a class in which <code>__del__</code> method is defined. I figured out that this method is used to destroy an instance of the class. However, I cannot find a place where this method is used. The main reason for that is that I do not know how this method is used, probably not like that: <code>obj1.del()</code>. So, my questions is how to call the <code>__del__</code> method? Thank you for any help.</p>
29
2009-09-26T15:49:52Z
1,481,523
<p>The <code>__del__</code> method (note spelling!) is called when your object is finally destroyed. Technically speaking (in cPython) that is when there are no more references to your object, ie when it goes out of scope.</p> <p>If you want to delete your object and thus call the <code>__del__</code> method use</p> <pre><code>del obj1 </code></pre> <p>which will delete the object (provided there weren't any other references to it).</p> <p>I suggest you write a small class like this</p> <pre><code>class T: def __del__(self): print "deleted" </code></pre> <p>And investigate in the python interpreter, eg</p> <pre><code>&gt;&gt;&gt; a = T() &gt;&gt;&gt; del a deleted &gt;&gt;&gt; a = T() &gt;&gt;&gt; b = a &gt;&gt;&gt; del b &gt;&gt;&gt; del a deleted &gt;&gt;&gt; def fn(): ... a = T() ... print "exiting fn" ... &gt;&gt;&gt; fn() exiting fn deleted &gt;&gt;&gt; </code></pre> <p>Note that jython and ironpython have different rules as to exactly when the object is deleted and <code>__del__</code> is called. It isn't considered good practice to use <code>__del__</code> though because of this and the fact that the object and its environment may be in an unknown state when it is called. It isn't absolutely guaranteed <code>__del__</code> will be called either - the interpreter can exit in various ways without deleteting all objects.</p>
5
2009-09-26T16:00:51Z
[ "python", "oop" ]
What is the __del__ method, How to call it?
1,481,488
<p>I am reading a code. There is a class in which <code>__del__</code> method is defined. I figured out that this method is used to destroy an instance of the class. However, I cannot find a place where this method is used. The main reason for that is that I do not know how this method is used, probably not like that: <code>obj1.del()</code>. So, my questions is how to call the <code>__del__</code> method? Thank you for any help.</p>
29
2009-09-26T15:49:52Z
1,481,527
<p>The <code>__del__</code> method, it will be called when the object is garbage collected. Note that it isn't necessarily guaranteed to be called though. The following code by itself won't necessarily do it:</p> <pre><code>del obj </code></pre> <p>The reason being that <code>del</code> just decrements the reference count by one. If something else has a reference to the object, <code>__del__</code> won't get called.</p> <p>There are a few caveats to using <code>__del__</code> though. Generally, they usually just aren't very useful. It sounds to me more like you want to use a close method or maybe a <a href="http://effbot.org/zone/python-with-statement.htm" rel="nofollow">with statement</a>.</p> <p>See the <a href="http://docs.python.org/reference/datamodel.html#object.%5F%5Fdel%5F%5F" rel="nofollow">python documentation on <code>__del__</code> methods</a>.</p> <p>One other thing to note: <code>__del__</code> methods can inhibit garbage collection if overused. In particular, a circular reference that has more than one object with a <code>__del__</code> method won't get garbage collected. This is because the garbage collector doesn't know which one to call first. See the documentation on the <a href="http://docs.python.org/library/gc.html#gc.garbage" rel="nofollow">gc module</a> for more info.</p>
3
2009-09-26T16:02:03Z
[ "python", "oop" ]
What is the __del__ method, How to call it?
1,481,488
<p>I am reading a code. There is a class in which <code>__del__</code> method is defined. I figured out that this method is used to destroy an instance of the class. However, I cannot find a place where this method is used. The main reason for that is that I do not know how this method is used, probably not like that: <code>obj1.del()</code>. So, my questions is how to call the <code>__del__</code> method? Thank you for any help.</p>
29
2009-09-26T15:49:52Z
2,452,895
<p>I wrote up the answer for another question, though this is a more accurate question for it. </p> <p><a href="http://stackoverflow.com/questions/2433130/can-someone-here-explain-constructors-and-destructors-in-python-simple-explanat/2433847#2433847">Can someone here explain constructors and destructors in python - simple explanation required - new to programming</a></p> <p>Here is a slightly opinionated answer.</p> <p>Don't use <code>__del__</code>. This is not C++ or a language built for destructors. The <code>__del__</code> method really should be gone in Python 3.x, though I'm sure someone will find a use case that makes sense. If you need to use <code>__del__</code>, be aware of the basic limitations per <a href="http://docs.python.org/reference/datamodel.html" rel="nofollow">http://docs.python.org/reference/datamodel.html</a>:</p> <ul> <li><code>__del__</code> is called when the garbage collector happens to be collecting the objects, not when you lose the last reference to an object and not when you execute <code>del object</code>.</li> <li><code>__del__</code> is responsible for calling any <code>__del__</code> in a superclass, though it is not clear if this is in method resolution order (MRO) or just calling each superclass.</li> <li>Having a <code>__del__</code> means that the garbage collector gives up on detecting and cleaning any cyclic links, such as losing the last reference to a linked list. You can get a list of the objects ignored from gc.garbage. You can sometimes use weak references to avoid the cycle altogether. This gets debated now and then: see <a href="http://mail.python.org/pipermail/python-ideas/2009-October/006194.html" rel="nofollow">http://mail.python.org/pipermail/python-ideas/2009-October/006194.html</a>.</li> <li>The <code>__del__</code> function can cheat, saving a reference to an object, and stopping the garbage collection.</li> <li>Exceptions explicitly raised in <code>__del__</code> are ignored.</li> <li><code>__del__</code> complements <code>__new__</code> far more than <code>__init__</code>. This gets confusing. See <a href="http://www.algorithm.co.il/blogs/index.php/programming/python/python-gotchas-1-del-is-not-the-opposite-of-init/" rel="nofollow">http://www.algorithm.co.il/blogs/index.php/programming/python/python-gotchas-1-del-is-not-the-opposite-of-init/</a> for an explanation and gotchas.</li> <li><code>__del__</code> is not a "well-loved" child in Python. You will notice that sys.exit() documentation does not specify if garbage is collected before exiting, and there are lots of odd issues. Calling the <code>__del__</code> on globals causes odd ordering issues, e.g., <a href="http://bugs.python.org/issue5099" rel="nofollow">http://bugs.python.org/issue5099</a>. Should <code>__del__</code> called even if the <code>__init__</code> fails? See <a href="http://mail.python.org/pipermail/python-dev/2000-March/thread.html#2423" rel="nofollow">http://mail.python.org/pipermail/python-dev/2000-March/thread.html#2423</a> for a long thread.</li> </ul> <p>But, on the other hand:</p> <ul> <li><code>__del__</code> means you do not forget to call a close statement. See <a href="http://eli.thegreenplace.net/2009/06/12/safely-using-destructors-in-python/" rel="nofollow">http://eli.thegreenplace.net/2009/06/12/safely-using-destructors-in-python/</a> for a pro <code>__del__</code> viewpoint. This is usually about freeing ctypes or some other special resource.</li> </ul> <p>And my pesonal reason for not liking the <code>__del__</code> function.</p> <ul> <li>Everytime someone brings up <code>__del__</code> it devolves into thirty messages of confusion.</li> <li>It breaks these items in the Zen of Python: <ul> <li>Simple is better than complicated.</li> <li>Special cases aren't special enough to break the rules.</li> <li>Errors should never pass silently.</li> <li>In the face of ambiguity, refuse the temptation to guess.</li> <li>There should be one-- and preferably only one --obvious way to do it.</li> <li>If the implementation is hard to explain, it's a bad idea.</li> </ul></li> </ul> <p>So, find a reason not to use <code>__del__</code>.</p>
25
2010-03-16T08:21:02Z
[ "python", "oop" ]
Python: This should be impossible, shouldn't it?
1,481,545
<p>This is part of my Django application which is saving a user's profile in a special way.</p> <pre><code>class SomeUser: def __init__(self, request): self.logged_in = True self.profile = request.user.get_profile() self.favorites = self.profile.favorites.all().values_list('pk', flat=True) def save(self, resp): print "1: " + str(self.favorites) self.profile.favorites = self.favorites print "2: " + str(self.favorites) self.profile.save() return resp </code></pre> <p>Output:</p> <pre><code>1: [68, 56] 2: [] </code></pre> <p>How is this even possible? I'm not fiddling with <code>self.favorites</code> at all! How can its value change?</p> <p>EDIT: Updated the question with more info.</p>
1
2009-09-26T16:10:06Z
1,481,566
<p>With <em>just</em> this snippet of code, it can't happen (assuming self.favorites and self.hello aren't properties). My guess would be that something somewhere else is mutating the value of self.favorites or self.hello. Is there another thread that could be doing this somewhere? Or could this perhaps be happening in a different request?</p>
0
2009-09-26T16:21:18Z
[ "python", "django" ]
Python: This should be impossible, shouldn't it?
1,481,545
<p>This is part of my Django application which is saving a user's profile in a special way.</p> <pre><code>class SomeUser: def __init__(self, request): self.logged_in = True self.profile = request.user.get_profile() self.favorites = self.profile.favorites.all().values_list('pk', flat=True) def save(self, resp): print "1: " + str(self.favorites) self.profile.favorites = self.favorites print "2: " + str(self.favorites) self.profile.save() return resp </code></pre> <p>Output:</p> <pre><code>1: [68, 56] 2: [] </code></pre> <p>How is this even possible? I'm not fiddling with <code>self.favorites</code> at all! How can its value change?</p> <p>EDIT: Updated the question with more info.</p>
1
2009-09-26T16:10:06Z
1,481,574
<p>I'm guessing self.favorites is some kind of iterator, maybe a django QuerySet.</p> <p>The first str() runs the iterator and empties it out</p> <p>The second str() runs the iterator again and it is empty</p>
4
2009-09-26T16:24:27Z
[ "python", "django" ]
What is a difference between "sqlite" and "pysqlite2/sqlite3" modules?
1,481,682
<p>I gave up to make "sqlite3" working but I just found out (with help("modules")) that I have "sqlite" module. I tested it (create table, insert some values and so on) and it works fine. But before I start to use this module I would like to know if it has some significant limitations in comparison with sqlite3 module? Can anybody, pleas, give me advise?</p> <p>Thank you in advance.</p>
3
2009-09-26T17:22:53Z
1,481,725
<p>As per <a href="http://trac.edgewall.org/wiki/PySqlite">this wiki</a>, you can ask your module exactly what version it is, e.g.:</p> <pre><code>&gt;&gt;&gt; import sqlite &gt;&gt;&gt; sqlite.version '1.0.1' &gt;&gt;&gt; sqlite._sqlite.sqlite_version() '2.8.16' </code></pre> <p>So what versions numbers do you see when you try this?</p> <p>A list of release note links from pysqlite version 2.3.4 to 2.5.5 (about 2 years' worth of releases) is available <a href="http://oss.itsystementwicklung.de/trac/pysqlite/">here</a> -- so if you were using the 2.3.2 embedded in the sqlite3 that comes with Python 2.5 or the 2.4.1 that comes with Python 2.6 you could trace exactly what features, optimizations and bug fixes you might be missing (a long list). But 1.0.1 is SO far back that I don't know where to find a further list of changes from there to 2.3.2! Looks like a job for an archeologist...;-).</p> <p>I've seen a pysqlite tutorial <a href="http://baijum81.livejournal.com/14159.html">here</a>; full docs (LaTex sources) <a href="http://oss.itsystementwicklung.de/trac/pysqlite/wiki/OldLatexDocs">here</a>; good luck! </p>
6
2009-09-26T17:45:12Z
[ "python", "sqlite", "sqlite3", "pysqlite" ]
Django instance start under Google App Engine
1,481,942
<p>After thinking quite a while about how to make a fast and scalable web application, I am almost decided to go for a combination of Google App Engine, Python+Django, and app-engine-patch. But I came across a comment in the <a href="http://code.google.com/p/app-engine-patch/wiki/FAQ" rel="nofollow">app-engine-patch FAQ</a> that made me think that perhaps the combination is not quite as mature as I thought: it may take seconds (1-4, according to the FAQ) to boot an instance of Django. That may not be a problem if there is some persistance from request to request, but it seems that when there is no sustained traffic then the Django instance is shut down in a few seconds. If the system is not called every other second or so, any incoming request will take seconds(!) to be granted. This is unacceptable. As a quick fix (ugly, I know), I was thinking about having an external machine making a dummy request to the framework every second just to keep it alive. </p> <p>Do you agree with this? Do you have any other approach?</p> <p>Another doubt that I have is what will happen if there is enough traffic to jump from one n servers to n+1, will that request take seconds to be granted because a new Django instance has to be initiated? or Google's infrastructure doesn't work this way? I confess my ignorance on this. issue.</p> <p>Help!</p>
2
2009-09-26T19:15:30Z
1,482,005
<p>I respect what you are trying to do, but this sounds a little like pre-mature optimization to me. The py+django patch you are discussing is recommended by Google until they upgrade to "real" django so I can't imagine it's all that bad. It's also not that hard to test the performance of what you are talking about, so I suggest you do that and run a few metrics on it first before making your final decision. That way you'll have some math to back it up when someone else starts complaining ;)</p>
1
2009-09-26T19:38:33Z
[ "python", "django", "google-app-engine", "app-engine-patch", "google-app-engine-patch" ]
Django instance start under Google App Engine
1,481,942
<p>After thinking quite a while about how to make a fast and scalable web application, I am almost decided to go for a combination of Google App Engine, Python+Django, and app-engine-patch. But I came across a comment in the <a href="http://code.google.com/p/app-engine-patch/wiki/FAQ" rel="nofollow">app-engine-patch FAQ</a> that made me think that perhaps the combination is not quite as mature as I thought: it may take seconds (1-4, according to the FAQ) to boot an instance of Django. That may not be a problem if there is some persistance from request to request, but it seems that when there is no sustained traffic then the Django instance is shut down in a few seconds. If the system is not called every other second or so, any incoming request will take seconds(!) to be granted. This is unacceptable. As a quick fix (ugly, I know), I was thinking about having an external machine making a dummy request to the framework every second just to keep it alive. </p> <p>Do you agree with this? Do you have any other approach?</p> <p>Another doubt that I have is what will happen if there is enough traffic to jump from one n servers to n+1, will that request take seconds to be granted because a new Django instance has to be initiated? or Google's infrastructure doesn't work this way? I confess my ignorance on this. issue.</p> <p>Help!</p>
2
2009-09-26T19:15:30Z
1,482,184
<p>Yes, long startup times are a caveat of using a framework with a lot of code. There's no way around them, currently, other than using a framework that is lighter-weight (such as the built in webapp framework).</p> <p>Polling your app isn't recommended: It'll use up quota, and doesn't actually guarantee that the real user requests hit the same instance your polling requests did, since apps run on multiple instances.</p> <p>Fortunately, there's a simple solution: Get popular! The more popular your app is, the less frequently instances need restarting, and the smaller a proportion of users it affects.</p>
3
2009-09-26T21:06:48Z
[ "python", "django", "google-app-engine", "app-engine-patch", "google-app-engine-patch" ]
Django instance start under Google App Engine
1,481,942
<p>After thinking quite a while about how to make a fast and scalable web application, I am almost decided to go for a combination of Google App Engine, Python+Django, and app-engine-patch. But I came across a comment in the <a href="http://code.google.com/p/app-engine-patch/wiki/FAQ" rel="nofollow">app-engine-patch FAQ</a> that made me think that perhaps the combination is not quite as mature as I thought: it may take seconds (1-4, according to the FAQ) to boot an instance of Django. That may not be a problem if there is some persistance from request to request, but it seems that when there is no sustained traffic then the Django instance is shut down in a few seconds. If the system is not called every other second or so, any incoming request will take seconds(!) to be granted. This is unacceptable. As a quick fix (ugly, I know), I was thinking about having an external machine making a dummy request to the framework every second just to keep it alive. </p> <p>Do you agree with this? Do you have any other approach?</p> <p>Another doubt that I have is what will happen if there is enough traffic to jump from one n servers to n+1, will that request take seconds to be granted because a new Django instance has to be initiated? or Google's infrastructure doesn't work this way? I confess my ignorance on this. issue.</p> <p>Help!</p>
2
2009-09-26T19:15:30Z
1,483,439
<p>Also, it seems to me (but Nick can correct me here if I'm wrong) that if you use the built in Django (.97 or 1.0) the loading is less of a problem. Logically, I'd say they keep the built-in libs in memory for everyone, or share that cached code between instances. But I don't know for sure.</p>
0
2009-09-27T11:53:19Z
[ "python", "django", "google-app-engine", "app-engine-patch", "google-app-engine-patch" ]
Django instance start under Google App Engine
1,481,942
<p>After thinking quite a while about how to make a fast and scalable web application, I am almost decided to go for a combination of Google App Engine, Python+Django, and app-engine-patch. But I came across a comment in the <a href="http://code.google.com/p/app-engine-patch/wiki/FAQ" rel="nofollow">app-engine-patch FAQ</a> that made me think that perhaps the combination is not quite as mature as I thought: it may take seconds (1-4, according to the FAQ) to boot an instance of Django. That may not be a problem if there is some persistance from request to request, but it seems that when there is no sustained traffic then the Django instance is shut down in a few seconds. If the system is not called every other second or so, any incoming request will take seconds(!) to be granted. This is unacceptable. As a quick fix (ugly, I know), I was thinking about having an external machine making a dummy request to the framework every second just to keep it alive. </p> <p>Do you agree with this? Do you have any other approach?</p> <p>Another doubt that I have is what will happen if there is enough traffic to jump from one n servers to n+1, will that request take seconds to be granted because a new Django instance has to be initiated? or Google's infrastructure doesn't work this way? I confess my ignorance on this. issue.</p> <p>Help!</p>
2
2009-09-26T19:15:30Z
1,985,669
<p>See <a href="http://takashi-matsuo.blogspot.com/2009/10/minimum-cost-of-various-frameworks-cold.html" rel="nofollow">Takashi Matsuo's comparisons</a>. Basically, for simplest app-engine-patch that does almost nothing, he claims about ~1s versus ~350ms for webapp+Django templates.</p> <p>It feels like longer than 1s for our app, but Takashi just tried the very simplest app he could think of.</p>
0
2009-12-31T14:40:06Z
[ "python", "django", "google-app-engine", "app-engine-patch", "google-app-engine-patch" ]
Django instance start under Google App Engine
1,481,942
<p>After thinking quite a while about how to make a fast and scalable web application, I am almost decided to go for a combination of Google App Engine, Python+Django, and app-engine-patch. But I came across a comment in the <a href="http://code.google.com/p/app-engine-patch/wiki/FAQ" rel="nofollow">app-engine-patch FAQ</a> that made me think that perhaps the combination is not quite as mature as I thought: it may take seconds (1-4, according to the FAQ) to boot an instance of Django. That may not be a problem if there is some persistance from request to request, but it seems that when there is no sustained traffic then the Django instance is shut down in a few seconds. If the system is not called every other second or so, any incoming request will take seconds(!) to be granted. This is unacceptable. As a quick fix (ugly, I know), I was thinking about having an external machine making a dummy request to the framework every second just to keep it alive. </p> <p>Do you agree with this? Do you have any other approach?</p> <p>Another doubt that I have is what will happen if there is enough traffic to jump from one n servers to n+1, will that request take seconds to be granted because a new Django instance has to be initiated? or Google's infrastructure doesn't work this way? I confess my ignorance on this. issue.</p> <p>Help!</p>
2
2009-09-26T19:15:30Z
2,039,666
<p>They also mention in the FAQ that using a zipped version of Django will help the load time, although I'm guessing it might still be long. As for your original question, I'd agree with others that polling your app is probably not a good idea because it likely won't solve your problem because Google may distribute your requests across many machines, etc, etc.</p>
1
2010-01-11T02:54:04Z
[ "python", "django", "google-app-engine", "app-engine-patch", "google-app-engine-patch" ]
Export QT Menu to text
1,481,999
<p>I was wondering if there is a way to convert my QT (version 4.50) menu and all its submenus into a text document in something similar to the following format:</p> <ul> <li>Menu 1 <ul> <li>Sub Menu 2</li> </ul></li> <li>Menu 2 <ul> <li>sub menu 3</li> <li>sub menu 4 <ul> <li>sub menu 1</li> </ul></li> </ul></li> </ul>
0
2009-09-26T19:35:51Z
1,483,655
<p>You might want to look at <a href="http://doc.trolltech.com/4.5/qobject.html#findChildren" rel="nofollow">QObject::findChildren</a>, and use it like this:</p> <pre><code>submenus = mainwindow.menuBar().findChildren(QAction) </code></pre> <p>Depending on how you construct your menus you might have to use QMenu as a parameter aswell. Also depending on your usage some sub menus could have no parent (depending on how you constructed them or added them to the parent menu) and then findChildren won't find them. </p>
1
2009-09-27T14:14:18Z
[ "python", "qt", "pyqt" ]
Why I get urllib2.HTTPError with urllib2 and no errors with urllib?
1,482,028
<p>I have the following simple code:</p> <pre><code>import urllib2 import sys sys.path.append('../BeautifulSoup/BeautifulSoup-3.1.0.1') from BeautifulSoup import * page='http://en.wikipedia.org/wiki/Main_Page' c=urllib2.urlopen(page) </code></pre> <p>This code generates the following error messages:</p> <pre><code> c=urllib2.urlopen(page) File "/usr/lib64/python2.4/urllib2.py", line 130, in urlopen return _opener.open(url, data) File "/usr/lib64/python2.4/urllib2.py", line 364, in open response = meth(req, response) File "/usr/lib64/python2.4/urllib2.py", line 471, in http_response response = self.parent.error( File "/usr/lib64/python2.4/urllib2.py", line 402, in error return self._call_chain(*args) File "/usr/lib64/python2.4/urllib2.py", line 337, in _call_chain result = func(*args) File "/usr/lib64/python2.4/urllib2.py", line 480, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 403: Forbidden </code></pre> <p>But if I replace urllib2 by urllib, I get no error messages. Can anybody explain this behavior?</p>
6
2009-09-26T19:46:36Z
1,482,042
<p>Wikipedia seems to be filtering out urllib2's default User-Agent. Just change it.</p>
4
2009-09-26T19:52:40Z
[ "python", "urllib2", "urllib" ]
Why I get urllib2.HTTPError with urllib2 and no errors with urllib?
1,482,028
<p>I have the following simple code:</p> <pre><code>import urllib2 import sys sys.path.append('../BeautifulSoup/BeautifulSoup-3.1.0.1') from BeautifulSoup import * page='http://en.wikipedia.org/wiki/Main_Page' c=urllib2.urlopen(page) </code></pre> <p>This code generates the following error messages:</p> <pre><code> c=urllib2.urlopen(page) File "/usr/lib64/python2.4/urllib2.py", line 130, in urlopen return _opener.open(url, data) File "/usr/lib64/python2.4/urllib2.py", line 364, in open response = meth(req, response) File "/usr/lib64/python2.4/urllib2.py", line 471, in http_response response = self.parent.error( File "/usr/lib64/python2.4/urllib2.py", line 402, in error return self._call_chain(*args) File "/usr/lib64/python2.4/urllib2.py", line 337, in _call_chain result = func(*args) File "/usr/lib64/python2.4/urllib2.py", line 480, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 403: Forbidden </code></pre> <p>But if I replace urllib2 by urllib, I get no error messages. Can anybody explain this behavior?</p>
6
2009-09-26T19:46:36Z
1,482,046
<p>The original <code>urllib</code> simply does not raise an exception on a 403 code. If you add <code>print c.getcode()</code> to the last line of your program, <code>urllib</code> will reach it and still print out 403.</p> <p>Then if you do <code>print c.read()</code> at the end, you will see that you did indeed get an error page from Wikipedia. It's just a matter of <code>urllib2</code> deciding to treat an error 403 as a runtime exception, versus <code>urllib</code> allowing you to still get an error 403 and then do something with the page.</p>
9
2009-09-26T19:55:21Z
[ "python", "urllib2", "urllib" ]
Why I get urllib2.HTTPError with urllib2 and no errors with urllib?
1,482,028
<p>I have the following simple code:</p> <pre><code>import urllib2 import sys sys.path.append('../BeautifulSoup/BeautifulSoup-3.1.0.1') from BeautifulSoup import * page='http://en.wikipedia.org/wiki/Main_Page' c=urllib2.urlopen(page) </code></pre> <p>This code generates the following error messages:</p> <pre><code> c=urllib2.urlopen(page) File "/usr/lib64/python2.4/urllib2.py", line 130, in urlopen return _opener.open(url, data) File "/usr/lib64/python2.4/urllib2.py", line 364, in open response = meth(req, response) File "/usr/lib64/python2.4/urllib2.py", line 471, in http_response response = self.parent.error( File "/usr/lib64/python2.4/urllib2.py", line 402, in error return self._call_chain(*args) File "/usr/lib64/python2.4/urllib2.py", line 337, in _call_chain result = func(*args) File "/usr/lib64/python2.4/urllib2.py", line 480, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 403: Forbidden </code></pre> <p>But if I replace urllib2 by urllib, I get no error messages. Can anybody explain this behavior?</p>
6
2009-09-26T19:46:36Z
5,125,803
<p><a href="http://stackoverflow.com/questions/2233687/overriding-urllib2-httperror-and-reading-response-html-anyway">Overriding urllib2 HTTPError and reading response HTML anyway</a> this post shows some nice way to obtain detailed error message from server</p>
0
2011-02-26T08:08:56Z
[ "python", "urllib2", "urllib" ]
Is there any way to programmatically generate Python bytecode?
1,482,055
<p>I want to hack around with the Python interpreter and try creating a small DSL . Is there any module where I can do something like this theoretical code (similar to LINQ expression trees)? </p> <pre><code>expression_tree = Function( Print( String('Hello world!') ) ) compile_to_bytecode(expression_tree) </code></pre> <p>Or would it just be easier to just generate Python source code? Could this be made easier by using C or SWIG or Cython?</p>
9
2009-09-26T20:01:18Z
1,482,059
<p>Check out the disassembler module found here:</p> <p><a href="http://docs.python.org/library/dis.html" rel="nofollow">http://docs.python.org/library/dis.html</a></p>
0
2009-09-26T20:02:45Z
[ "python", "expression-trees", "abstract-syntax-tree", "dsl", "bytecode" ]
Is there any way to programmatically generate Python bytecode?
1,482,055
<p>I want to hack around with the Python interpreter and try creating a small DSL . Is there any module where I can do something like this theoretical code (similar to LINQ expression trees)? </p> <pre><code>expression_tree = Function( Print( String('Hello world!') ) ) compile_to_bytecode(expression_tree) </code></pre> <p>Or would it just be easier to just generate Python source code? Could this be made easier by using C or SWIG or Cython?</p>
9
2009-09-26T20:01:18Z
1,482,069
<p>In Python 2.X, you would typically approach this with the <a href="http://docs.python.org/library/compiler.html" rel="nofollow"><code>compiler</code> module</a> and its <code>ast</code> sub-module. In Python 3.X, you would use just <a href="http://docs.python.org/3.1/library/ast.html" rel="nofollow"><code>ast</code></a>.</p> <p>Both offer a <code>compile()</code> function that will go from source/AST to "a code object that can be executed by the <code>exec</code> statement or <code>eval()</code>."</p>
5
2009-09-26T20:07:24Z
[ "python", "expression-trees", "abstract-syntax-tree", "dsl", "bytecode" ]
Is there any way to programmatically generate Python bytecode?
1,482,055
<p>I want to hack around with the Python interpreter and try creating a small DSL . Is there any module where I can do something like this theoretical code (similar to LINQ expression trees)? </p> <pre><code>expression_tree = Function( Print( String('Hello world!') ) ) compile_to_bytecode(expression_tree) </code></pre> <p>Or would it just be easier to just generate Python source code? Could this be made easier by using C or SWIG or Cython?</p>
9
2009-09-26T20:01:18Z
1,482,101
<p><a href="http://blog.fmeyer.org/entry/writing%5Fa%5Fdomain%5Fspecific%5Flanguage%5Fdsl%5Fwith%5Fpython" rel="nofollow">Fernando Meyer recently wrote a blog post</a> explaining how to use the <code># coding</code> directive to specify your own extensions to Python. Example (the actual format definition is in <a href="http://github.com/fmeyer/pydsl/blob/master/pyspec.py" rel="nofollow">pyspec.py</a> and <a href="http://github.com/fmeyer/pydsl/blob/master/tokenizer.py" rel="nofollow">tokenizer.py</a>):</p> <pre><code># coding: pyspec class Bow: def shot(self): print "got shot" def score(self): return 5 describe Bowling: it "should score 0 for gutter game": bowling = Bow() bowling.shot() assert that bowling.score.should_be(5) </code></pre>
1
2009-09-26T20:25:00Z
[ "python", "expression-trees", "abstract-syntax-tree", "dsl", "bytecode" ]
Is there any way to programmatically generate Python bytecode?
1,482,055
<p>I want to hack around with the Python interpreter and try creating a small DSL . Is there any module where I can do something like this theoretical code (similar to LINQ expression trees)? </p> <pre><code>expression_tree = Function( Print( String('Hello world!') ) ) compile_to_bytecode(expression_tree) </code></pre> <p>Or would it just be easier to just generate Python source code? Could this be made easier by using C or SWIG or Cython?</p>
9
2009-09-26T20:01:18Z
1,482,194
<p>It's easier to generate Python code and run it. If you do that you can also debug it more easily since there is actual source for the debugger to display. See also Malte Borchs article in the July issue of Python magazine, where he talks about this amongst other things.</p>
2
2009-09-26T21:11:44Z
[ "python", "expression-trees", "abstract-syntax-tree", "dsl", "bytecode" ]
Is there any way to programmatically generate Python bytecode?
1,482,055
<p>I want to hack around with the Python interpreter and try creating a small DSL . Is there any module where I can do something like this theoretical code (similar to LINQ expression trees)? </p> <pre><code>expression_tree = Function( Print( String('Hello world!') ) ) compile_to_bytecode(expression_tree) </code></pre> <p>Or would it just be easier to just generate Python source code? Could this be made easier by using C or SWIG or Cython?</p>
9
2009-09-26T20:01:18Z
1,482,491
<p>Working via <code>ast</code> and compiling the tree into bytecode, as another answer suggests, is probably simplest; generating sources and compiling those, almost as good.</p> <p>However, to explore lower-level approaches, check out the links from <a href="http://news.ycombinator.com/item?id=781461">this page</a>; I've found <a href="http://code.google.com/p/byteplay/">byteplay</a> especially useful (currently doesn't work on 2.6 nor 3.*, only 2.4 or 2.5, but I think fixing it for 2.6 should be easy, as currently discussed in its tracker). I have not used Phil Eby's similarly-featured <a href="http://pypi.python.org/pypi/BytecodeAssembler">BytecodeAssembler</a>, but given the author's reputation I'm sure it's worth checking it out!</p>
9
2009-09-27T00:35:35Z
[ "python", "expression-trees", "abstract-syntax-tree", "dsl", "bytecode" ]
Is there any way to programmatically generate Python bytecode?
1,482,055
<p>I want to hack around with the Python interpreter and try creating a small DSL . Is there any module where I can do something like this theoretical code (similar to LINQ expression trees)? </p> <pre><code>expression_tree = Function( Print( String('Hello world!') ) ) compile_to_bytecode(expression_tree) </code></pre> <p>Or would it just be easier to just generate Python source code? Could this be made easier by using C or SWIG or Cython?</p>
9
2009-09-26T20:01:18Z
38,509,519
<p>Updating for Python3 - there's also very interesting assembler <a href="https://github.com/zachariahreed/byteasm" rel="nofollow"><code>zachariahreed/byteasm</code></a>.</p> <p>Actually the only one working for me in Py3. It has very nice &amp; clean API:</p> <pre><code>&gt;&gt;&gt; import byteasm, dis &gt;&gt;&gt; b = byteasm.FunctionBuilder() &gt;&gt;&gt; b.add_positional_arg('x') &gt;&gt;&gt; b.emit_load_const('Hello!') &gt;&gt;&gt; b.emit_load_fast('x') &gt;&gt;&gt; b.emit_build_tuple(2) &gt;&gt;&gt; b.emit_return_value() &gt;&gt;&gt; f = b.make('f') &gt;&gt;&gt; f &lt;function f at 0xb7012a4c&gt; &gt;&gt;&gt; dis.dis(f) 1 0 LOAD_CONST 0 ('Hello!') 3 LOAD_FAST 0 (x) 6 BUILD_TUPLE 2 9 RETURN_VALUE &gt;&gt;&gt; f(108) ('Hello!', 108) </code></pre>
0
2016-07-21T16:23:55Z
[ "python", "expression-trees", "abstract-syntax-tree", "dsl", "bytecode" ]
What does it mean "weakly-referenced object no longer exists"?
1,482,141
<p>I am running a Python code and I get the following error message:</p> <pre><code>Exception exceptions.ReferenceError: 'weakly-referenced object no longer exists' in &lt;bound method crawler.__del__ of &lt;searchengine.crawler instance at 0x2b8c1f99ef80&gt;&gt; ignored </code></pre> <p>Does anybody know what can it means?</p> <p>P.S. This is the code which produce the error:</p> <pre><code>import sqlite class crawler: def __init__(self,dbname): tmp = sqlite.connect(dbname) self.con = tmp.cursor() def __del__(self): self.con.close() crawler = crawler('searchindex.db') </code></pre>
5
2009-09-26T20:42:08Z
1,482,147
<p>Weak references are a form of reference that does not prevent the garbage collector from disposing the referenced object. If you want to guarantee that the object will continue to exist, you should use a strong (normal) reference.</p> <p>Otherwise, there is no guarantee that the object will or will not exist after all the normal references have gone out of scope.</p>
1
2009-09-26T20:44:27Z
[ "python" ]
What does it mean "weakly-referenced object no longer exists"?
1,482,141
<p>I am running a Python code and I get the following error message:</p> <pre><code>Exception exceptions.ReferenceError: 'weakly-referenced object no longer exists' in &lt;bound method crawler.__del__ of &lt;searchengine.crawler instance at 0x2b8c1f99ef80&gt;&gt; ignored </code></pre> <p>Does anybody know what can it means?</p> <p>P.S. This is the code which produce the error:</p> <pre><code>import sqlite class crawler: def __init__(self,dbname): tmp = sqlite.connect(dbname) self.con = tmp.cursor() def __del__(self): self.con.close() crawler = crawler('searchindex.db') </code></pre>
5
2009-09-26T20:42:08Z
1,482,155
<p>The code is referring to an instance which has already been garbage collected. To avoid circular references you can use a weak reference which isn't enough to prevent garbage collection. In this case there is a weakref.proxy (<a href="http://docs.python.org/library/weakref.html#weakref.proxy" rel="nofollow">http://docs.python.org/library/weakref.html#weakref.proxy</a>) to a searchengine.crawler object.</p>
1
2009-09-26T20:49:57Z
[ "python" ]
What does it mean "weakly-referenced object no longer exists"?
1,482,141
<p>I am running a Python code and I get the following error message:</p> <pre><code>Exception exceptions.ReferenceError: 'weakly-referenced object no longer exists' in &lt;bound method crawler.__del__ of &lt;searchengine.crawler instance at 0x2b8c1f99ef80&gt;&gt; ignored </code></pre> <p>Does anybody know what can it means?</p> <p>P.S. This is the code which produce the error:</p> <pre><code>import sqlite class crawler: def __init__(self,dbname): tmp = sqlite.connect(dbname) self.con = tmp.cursor() def __del__(self): self.con.close() crawler = crawler('searchindex.db') </code></pre>
5
2009-09-26T20:42:08Z
1,482,477
<p>A normal AKA strong reference is one that keeps the referred-to object alive: in CPython, each object keeps the number of (normal) references to it that exists (known as its "reference count" or RC) and goes away as soon as the RC reaches zero (occasional generational mark and sweep passes also garbage-collect "reference loops" once in a while).</p> <p>When you don't want an object to stay alive just because another one refers to it, then you use a "weak reference", a special variety of reference that doesn't increment the RC; see <a href="http://docs.python.org/library/weakref.html?highlight=weakref#module-weakref">the docs</a> for details. Of course, since the referred-to object CAN go away if not otherwise referred to (the whole purpose of the weak ref rather than a normal one!-), the referring-to object needs to be warned if it tries to use an object that's gone away -- and that alert is given exactly by the exception you're seeing.</p> <p>In your code...:</p> <pre><code> def __init__(self,dbname): tmp = sqlite.connect(dbname) self.con = tmp.cursor() def __del__(self): self.con.close() </code></pre> <p><code>tmp</code> is a normal reference to the connection... but it's a local variable, so it goes away at the end of <code>__init__</code>. The (peculiarly named;-) cursor <code>self.con</code> stays, BUT it's internally implemented to only hold a WEAK ref to the connection, so the connection goes away when <code>tmp</code> does. So in <code>__del__</code> the call to <code>.close</code> fails (since the cursor needs to use the connection in order to close itself).</p> <p>Simplest solution is the following tiny change:</p> <pre><code> def __init__(self,dbname): self.con = sqlite.connect(dbname) self.cur = self.con.cursor() def __del__(self): self.cur.close() self.con.close() </code></pre> <p>I've also taken the opportunity to use con for connection and cur for cursor, but Python won't mind if you're keen to swap those (you'll just leave readers perplexed;-).</p>
14
2009-09-27T00:27:08Z
[ "python" ]
Why I cannot build a chain of methods? (method1.method2.method3)
1,482,270
<p>If I have the following code:</p> <pre><code>import sqlite sqlite.connect('tmp.db').cursor().close() </code></pre> <p>I get the following error message:</p> <pre><code>Traceback (most recent call last): File "searchengine2.py", line 13, in ? sqlite.connect('tmp.db').cursor().close() File "/usr/lib64/python2.4/site-packages/sqlite/main.py", line 280, in close if self.con and self.con.closed: ReferenceError: weakly-referenced object no longer exists </code></pre> <p>However, if I modify the code in the following way:</p> <pre><code>import sqlite x1 = sqlite.connect('tmp.db') x2 = x1.cursor() x3 = x2.close() </code></pre> <p>everything is fine. Why? </p>
0
2009-09-26T21:46:49Z
1,482,290
<p>Apparently the <code>cursor</code> keeps a weak reference to the connection (<code>self.con</code>). Because you chain the functions, the connection you've instantiated is out of scope as soon as you instantiate the cursor -- nothing holds a <em>strong</em> reference to the connection anymore, and the connection is eligible for garbage collection.</p> <p>Therefore, by the time you try to <code>close</code> the cursor (which in turn tries to <code>close</code> the connection), the connection is already out of scope and may have been garbage collected -- if it was, then the connection is already closed.</p> <p>There's no way to get around this without modifying the cursor's source to make it hold a strong reference to the connection, and there's no easy way to tell how many problems that might introduce if you do it that way. (Good) designers don't arbitrarily make weak references without a good reason.</p> <p>(Hopefully you understand weak references from <a href="http://stackoverflow.com/questions/1482141/what-does-it-mean-weakly-referenced-object-no-longer-exists">your last question</a>.)</p>
3
2009-09-26T22:00:22Z
[ "python", "sqlite", "methods" ]