title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
counting combinations and permutations efficiently
2,096,573
<p>I have some code to count permutations and combinations, and I'm trying to make it work better for large numbers.</p> <p>I've found a better algorithm for permutations that avoids large intermediate results, but I still think I can do better for combinations.</p> <p>So far, I've put in a special case to reflect th...
22
2010-01-19T19:52:03Z
18,443,221
<p>There's a function for this in scipy which hasn't been mentioned yet: <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.comb.html" rel="nofollow">scipy.misc.comb</a>. It seems efficient based on some quick timing results for your doctest (~0.004 seconds for <code>comb(100000, 1000, 1) == comb(1...
3
2013-08-26T11:39:34Z
[ "python", "algorithm", "math", "combinations", "permutation" ]
How can I iterate over every character in a given encoding using Python?
2,097,136
<p>Is there a way to iterate over every character in a given encoding, and print it's code? Say, UTF8?</p>
0
2010-01-19T21:14:10Z
2,097,149
<p>dude, do you have any idea how many code points there are in unicode...</p> <p>btw, from the Python docs:</p> <p>unichr(i)</p> <p>Return the Unicode string of one character whose Unicode code is the integer i. For example, unichr(97) returns the string u'a'. This is the inverse of ord() for Unicode strings. The v...
3
2010-01-19T21:16:29Z
[ "python", "unicode", "encoding" ]
How can I iterate over every character in a given encoding using Python?
2,097,136
<p>Is there a way to iterate over every character in a given encoding, and print it's code? Say, UTF8?</p>
0
2010-01-19T21:14:10Z
2,097,197
<p>For single-byte encodings you can use:</p> <pre><code>''.join(chr(x) for x in range(256)).decode(encoding, 'ignore') </code></pre> <p>to get a string containing all the valid characters in the given encoding.</p> <p>For fixed-size multibyte encodings careful use of <code>struct.pack()</code> in place of <code>chr...
1
2010-01-19T21:23:44Z
[ "python", "unicode", "encoding" ]
How can I iterate over every character in a given encoding using Python?
2,097,136
<p>Is there a way to iterate over every character in a given encoding, and print it's code? Say, UTF8?</p>
0
2010-01-19T21:14:10Z
2,097,532
<p>All Unicode characters can be represented in <code>UTF-n</code> for all defined <code>n</code>. What are you trying to achieve?</p> <p>If you really want to do something like print all the valid characters in a particular encoding, without needing to know whether the encoding is "single byte" or "multi byte" or whe...
4
2010-01-19T22:09:47Z
[ "python", "unicode", "encoding" ]
Parsing name and address information with differing number of spaces
2,097,191
<p>I have a comma delimited text file. The 5th field on each line contains the name and address information. The name is separated from the street information by a '¬' character. The same character also separates the city|state|zip. A sample field would be:<br> "¬BOL¬MICKEY M MOUSE¬123 TOMORROW LANE¬ORLANDO FL 123...
0
2010-01-19T21:23:11Z
2,097,226
<p>In your examples it seems that you can in both cases solve the problem by getting the 'first fields', the 'last fields' and 'everything in between':</p> <pre><code>m = line.split("¬")[2].split() firstname = m[0] surname = m[-1] initials = m[1:-1] # Maybe just keep this as a list? </code></pre> <p>And:</p> <pre><...
3
2010-01-19T21:27:44Z
[ "python", "parsing", "street-address" ]
Parsing name and address information with differing number of spaces
2,097,191
<p>I have a comma delimited text file. The 5th field on each line contains the name and address information. The name is separated from the street information by a '¬' character. The same character also separates the city|state|zip. A sample field would be:<br> "¬BOL¬MICKEY M MOUSE¬123 TOMORROW LANE¬ORLANDO FL 123...
0
2010-01-19T21:23:11Z
2,097,234
<p>Basically what Anon suggests, you can implement it like this:</p> <pre><code>cityInfo = m[4].split() city, state, zipCode = ' '.join(cityInfo[:-2]), cityInfo[-2], cityInfo[-1]) </code></pre>
0
2010-01-19T21:29:09Z
[ "python", "parsing", "street-address" ]
Set parent in a ModelForm in Google App Engine
2,097,225
<p>I want to create an Entity Group relationship in an Entity that is being created through a ModelForm.</p> <p>How do I pass the parent instance and set the <code>parent=</code> attribute in the ModelForm?</p>
4
2010-01-19T21:27:35Z
2,097,376
<p>I'll be interested to see if you get any good solutions to this problem. My own solution, which is far from elegant, is to do this:</p> <pre><code>book = models.Book(title='Foo') chapter = models.Chapter(parent=book, title='dummy') form = forms.ChapterForm(request.POST, request.FILES, instance=chapter) </code></pr...
4
2010-01-19T21:49:51Z
[ "python", "django", "google-app-engine", "app-engine-patch" ]
Set parent in a ModelForm in Google App Engine
2,097,225
<p>I want to create an Entity Group relationship in an Entity that is being created through a ModelForm.</p> <p>How do I pass the parent instance and set the <code>parent=</code> attribute in the ModelForm?</p>
4
2010-01-19T21:27:35Z
5,096,982
<p>I subclassed djangoforms.ModelForm and added a create method*:</p> <pre><code>class ModelForm(djangoforms.ModelForm): """Django ModelForm class which uses our implementation of BoundField. """ def create(self, commit=True, key_name=None, parent=None): """Save this form's cleaned data into a new model ins...
0
2011-02-23T20:54:43Z
[ "python", "django", "google-app-engine", "app-engine-patch" ]
How do I get a µ character out of sqlite and onto a web-page?
2,097,256
<p>On a Python driven web app using a sqlite datastore I had this error:</p> <blockquote> <p>Could not decode to UTF-8 column 'name' with text '300µL-10-10'</p> </blockquote> <p>Reading <a href="http://docs.python.org/library/sqlite3.html#connection-objects" rel="nofollow">here</a> it looks like I need to switch...
4
2010-01-19T21:31:32Z
2,097,679
<p>Unfortunately, the data in your datastore is not encoded as UTF-8; instead, it's probably either latin-1 or cp1252. To decode it automatically, try setting Connection.text_factory to your own function:</p> <pre><code>def convert_string(s): try: u = s.decode("utf-8") except UnicodeDecodeError: ...
3
2010-01-19T22:31:28Z
[ "python", "sqlite", "unicode", "utf-8" ]
Creating a simple hierarchy structure in Maya using mel/python
2,097,306
<p>So I want to create a very simple structure out of group and locator nodes in Maya which will then be exported for use in my game level.</p> <p>e.g. </p> <pre><code>Group_Root group_parent - group1 - locator1 - group2 - locator2 - group3 </code></pre> <p>There is only one Group_Root in t...
1
2010-01-19T21:38:43Z
2,098,428
<p>Have you seen <a href="http://www.vfxoverflow.com/" rel="nofollow">VFX Overflow</a>? It's Q&amp;A for visual effects, so I'd expect a number of the watchers to be quite familiar with Maya/MEL and Python. That said, it is fairly new so the user base is still small...</p>
0
2010-01-20T01:17:53Z
[ "python", "maya", "autodesk", "mel" ]
Creating a simple hierarchy structure in Maya using mel/python
2,097,306
<p>So I want to create a very simple structure out of group and locator nodes in Maya which will then be exported for use in my game level.</p> <p>e.g. </p> <pre><code>Group_Root group_parent - group1 - locator1 - group2 - locator2 - group3 </code></pre> <p>There is only one Group_Root in t...
1
2010-01-19T21:38:43Z
5,411,511
<p>Names can be a bit annoying with MEL. In general, it's good practice to never trust a name to be what you're specifying. </p> <p>This is a good example of how *not to do things: </p> <pre><code>group -n myGroup1 circle1 sphere1; </code></pre> <p>..because that is in no way guaranteed to result in something named ...
0
2011-03-23T20:56:32Z
[ "python", "maya", "autodesk", "mel" ]
Creating a simple hierarchy structure in Maya using mel/python
2,097,306
<p>So I want to create a very simple structure out of group and locator nodes in Maya which will then be exported for use in my game level.</p> <p>e.g. </p> <pre><code>Group_Root group_parent - group1 - locator1 - group2 - locator2 - group3 </code></pre> <p>There is only one Group_Root in t...
1
2010-01-19T21:38:43Z
12,758,707
<p>I'm guessing that it being over two years, you've figured this one out by now.. but for posterity, there were two issues - firstly, you were spot on with the need for absolute paths, but there was also a slight bug in the way you were applying the maya.cmds.parent() call. I've just done some light rewriting to illus...
0
2012-10-06T09:54:34Z
[ "python", "maya", "autodesk", "mel" ]
how to safely generate a SQL LIKE statement using python db-api
2,097,475
<p>I am trying to assemble the following SQL statement using python's db-api:</p> <pre><code>SELECT x FROM myTable WHERE x LIKE 'BEGINNING_OF_STRING%'; </code></pre> <p>where BEGINNING_OF_STRING should be a python var to be safely filled in through the DB-API. I tried</p> <pre><code>beginningOfString = 'abc' cursor...
12
2010-01-19T22:02:03Z
2,097,511
<p><strong>EDIT:</strong></p> <p>As Brian and Thomas noted, the <strong>far</strong> better way to do this would be to use:</p> <pre><code>beginningOfString += '%' cursor.execute("SELECT x FROM myTable WHERE x LIKE ?", (beginningOfString,) ) </code></pre> <p>since the first method leaves you open to SQL injection at...
2
2010-01-19T22:06:48Z
[ "python", "sql", "sql-like", "python-db-api" ]
how to safely generate a SQL LIKE statement using python db-api
2,097,475
<p>I am trying to assemble the following SQL statement using python's db-api:</p> <pre><code>SELECT x FROM myTable WHERE x LIKE 'BEGINNING_OF_STRING%'; </code></pre> <p>where BEGINNING_OF_STRING should be a python var to be safely filled in through the DB-API. I tried</p> <pre><code>beginningOfString = 'abc' cursor...
12
2010-01-19T22:02:03Z
2,097,551
<p>It's best to separate the parameters from the sql if you can. Then you can let the db module take care of proper quoting of the parameters.</p> <pre><code>sql='SELECT x FROM myTable WHERE x LIKE %s' args=[beginningOfString+'%'] cursor.execute(sql,args) </code></pre>
14
2010-01-19T22:12:17Z
[ "python", "sql", "sql-like", "python-db-api" ]
how to safely generate a SQL LIKE statement using python db-api
2,097,475
<p>I am trying to assemble the following SQL statement using python's db-api:</p> <pre><code>SELECT x FROM myTable WHERE x LIKE 'BEGINNING_OF_STRING%'; </code></pre> <p>where BEGINNING_OF_STRING should be a python var to be safely filled in through the DB-API. I tried</p> <pre><code>beginningOfString = 'abc' cursor...
12
2010-01-19T22:02:03Z
2,097,582
<p>Take note of <a href="http://docs.python.org/library/sqlite3.html" rel="nofollow">Sqlite3</a> documentation: </p> <blockquote> <p>Usually your SQL operations will need to use values from Python variables. You shouldn’t assemble your query using Python’s string operations because doing so is insecure; ...
1
2010-01-19T22:18:01Z
[ "python", "sql", "sql-like", "python-db-api" ]
Pylons and multiple forms per page
2,097,556
<p>I've got a web page I'm generating with Pylons and the evoque templating tool. I'm trying to generate a page with multiple forms per page (one form is part of a base template that becomes part of every page). I'm having a problem as I seemingly can only get the form element values for one form; whenever I try to get...
1
2010-01-19T22:12:55Z
2,104,760
<p>You will only get the form values for the form that was posted in the request(ie: whichever submit button the user clicked), that's how html works. </p>
1
2010-01-20T20:37:22Z
[ "python", "html", "forms", "pylons" ]
Pylons and multiple forms per page
2,097,556
<p>I've got a web page I'm generating with Pylons and the evoque templating tool. I'm trying to generate a page with multiple forms per page (one form is part of a base template that becomes part of every page). I'm having a problem as I seemingly can only get the form element values for one form; whenever I try to get...
1
2010-01-19T22:12:55Z
2,500,262
<p>Yes (to iterate Tom's answer), HTML is designed to explicitly only allow a single form to be submitted at a time. Plus, forms may <strong>not</strong> be nested, so no confusion possible there. </p> <p>However, a single form <strong>may</strong> contain multiple submit buttons. So, you may if you really want to org...
0
2010-03-23T13:33:48Z
[ "python", "html", "forms", "pylons" ]
Easy way to get data between tags of xml or html files in python?
2,097,921
<p>I am using Python and need to find and retrieve all character data between tags:</p> <pre><code>&lt;tag&gt;I need this stuff&lt;/tag&gt; </code></pre> <p>I then want to output the found data to another file. I am just looking for a very easy and efficient way to do this. </p> <p>If you can post a quick code sni...
1
2010-01-19T23:07:57Z
2,097,940
<p><a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a> is a wonderful HTML/XML parser for Python:</p> <blockquote> <p>Beautiful Soup is a Python HTML/XML parser designed for quick turnaround projects like screen-scraping. Three features make it powerful:</p> <ol> <l...
2
2010-01-19T23:10:44Z
[ "python", "html", "xml" ]
Easy way to get data between tags of xml or html files in python?
2,097,921
<p>I am using Python and need to find and retrieve all character data between tags:</p> <pre><code>&lt;tag&gt;I need this stuff&lt;/tag&gt; </code></pre> <p>I then want to output the found data to another file. I am just looking for a very easy and efficient way to do this. </p> <p>If you can post a quick code sni...
1
2010-01-19T23:07:57Z
2,097,946
<p>I quite like parsing into <a href="http://docs.python.org/library/xml.etree.elementtree.html" rel="nofollow">element tree</a> and then using <code>element.text</code> and <code>element.tail</code>.</p> <p>It also has <strong>xpath</strong> like searching</p> <pre><code>&gt;&gt;&gt; from xml.etree.ElementTree impor...
0
2010-01-19T23:11:59Z
[ "python", "html", "xml" ]
Easy way to get data between tags of xml or html files in python?
2,097,921
<p>I am using Python and need to find and retrieve all character data between tags:</p> <pre><code>&lt;tag&gt;I need this stuff&lt;/tag&gt; </code></pre> <p>I then want to output the found data to another file. I am just looking for a very easy and efficient way to do this. </p> <p>If you can post a quick code sni...
1
2010-01-19T23:07:57Z
2,098,142
<p>without external modules, eg </p> <pre><code>&gt;&gt;&gt; myhtml = """ &lt;tag&gt;I need this stuff&lt;/tag&gt; ... blah blah ... &lt;tag&gt;I need this stuff too ... &lt;/tag&gt; ... blah blah """ &gt;&gt;&gt; for item in myhtml.split("&lt;/tag&gt;"): ... if "&lt;tag&gt;" in item: ... print item [ item.fin...
1
2010-01-20T00:00:54Z
[ "python", "html", "xml" ]
Easy way to get data between tags of xml or html files in python?
2,097,921
<p>I am using Python and need to find and retrieve all character data between tags:</p> <pre><code>&lt;tag&gt;I need this stuff&lt;/tag&gt; </code></pre> <p>I then want to output the found data to another file. I am just looking for a very easy and efficient way to do this. </p> <p>If you can post a quick code sni...
1
2010-01-19T23:07:57Z
2,099,400
<p>Use xpath and lxml;</p> <pre><code>from lxml import etree pageInMemory = open("pageToParse.html", "r") parsedPage = etree.HTML(pageInMemory) yourListOfText = parsedPage.xpath("//tag//text()") saveFile = open("savedFile", "w") saveFile.writelines(yourListOfText) pageInMemory.close() saveFile.close() </code></pr...
0
2010-01-20T06:15:05Z
[ "python", "html", "xml" ]
can SimpleXMLRPCServer listen on multiple addresses?
2,098,045
<p>I have two IPs mapping to the machine, and I was wondering how I can have one python xmlrpc server listening on both IPs (same port), like you could do with Apache.</p> <p>Thank you,</p>
1
2010-01-19T23:39:15Z
2,098,074
<p>Use "" as the host:</p> <pre><code>s = SimpleXMLRPCServer.SimpleXMLRPCServer(("", 8000)) </code></pre>
3
2010-01-19T23:46:18Z
[ "python", "simplexmlrpcserver" ]
Should I create each class in its own .py file?
2,098,088
<p>I'm quite new to Python in general.</p> <p>I'm aware that I can create multiple classes in the same .py file, but I'm wondering if I should create each class in its own .py file.</p> <p>In C# for instance, I would have a class that handles all Database interactions. Then another class that had the business rules.<...
23
2010-01-19T23:49:00Z
2,098,096
<p>No. Typical Python style is to put related classes in the same module. It may be that a class ends up in a module of its own (especially if it's a large class), but it should not be a goal in its own right. And when you do, please do not name the module after the class -- you'll just end up confusing yourself and ot...
21
2010-01-19T23:51:30Z
[ "python" ]
Should I create each class in its own .py file?
2,098,088
<p>I'm quite new to Python in general.</p> <p>I'm aware that I can create multiple classes in the same .py file, but I'm wondering if I should create each class in its own .py file.</p> <p>In C# for instance, I would have a class that handles all Database interactions. Then another class that had the business rules.<...
23
2010-01-19T23:49:00Z
2,098,097
<p>Each .py file represents a module, so you should keep logical groups of functions, constants and classes together in the same file.</p> <p>Each class in a .py file will just create epic bloat in your module table, since if you're only interested in one class you can still</p> <pre><code>from whatever import SomeCl...
6
2010-01-19T23:51:51Z
[ "python" ]
Should I create each class in its own .py file?
2,098,088
<p>I'm quite new to Python in general.</p> <p>I'm aware that I can create multiple classes in the same .py file, but I'm wondering if I should create each class in its own .py file.</p> <p>In C# for instance, I would have a class that handles all Database interactions. Then another class that had the business rules.<...
23
2010-01-19T23:49:00Z
2,098,099
<p>Probably not. Python files are "modules". Modules should contain just what code is independently reusable. If that comprises several classes, which is the norm, then that's perfectly ok.</p>
1
2010-01-19T23:51:47Z
[ "python" ]
Should I create each class in its own .py file?
2,098,088
<p>I'm quite new to Python in general.</p> <p>I'm aware that I can create multiple classes in the same .py file, but I'm wondering if I should create each class in its own .py file.</p> <p>In C# for instance, I would have a class that handles all Database interactions. Then another class that had the business rules.<...
23
2010-01-19T23:49:00Z
2,102,195
<p>Another point worth mentioning, is that if a file grows too large, you can always transform it into a package, making easy to reorganize without breaking the client's code.</p>
3
2010-01-20T14:52:10Z
[ "python" ]
Should I create each class in its own .py file?
2,098,088
<p>I'm quite new to Python in general.</p> <p>I'm aware that I can create multiple classes in the same .py file, but I'm wondering if I should create each class in its own .py file.</p> <p>In C# for instance, I would have a class that handles all Database interactions. Then another class that had the business rules.<...
23
2010-01-19T23:49:00Z
4,672,452
<p>I'll disagree with the others and say yes. For me, I have had better success putting each class in its own file (module). But there are exceptions so let me explain with an example.</p> <p>If you have a class Foo, then put it in a file called Foo.py, with the following sections:</p> <ol> <li>Imports <ul> <li>This ...
1
2011-01-12T18:25:31Z
[ "python" ]
Should I create each class in its own .py file?
2,098,088
<p>I'm quite new to Python in general.</p> <p>I'm aware that I can create multiple classes in the same .py file, but I'm wondering if I should create each class in its own .py file.</p> <p>In C# for instance, I would have a class that handles all Database interactions. Then another class that had the business rules.<...
23
2010-01-19T23:49:00Z
32,386,150
<p>Yes each class in its own file. Importing even a single class (or function) in a file with multiple classes causes python to execute the definition of all classes in the file. Try this:</p> <p>manyClass.py</p> <pre><code>class foo(): print 'a bunch of time consuming work' class tryme(): print 'try me' </cod...
0
2015-09-03T22:02:32Z
[ "python" ]
Using a function to create a function in Python
2,098,181
<p>I'm new to programming and I'm interested in if it's possible to use a function to create another function based in inputted information:</p> <pre><code>def get_new_toy(self): new_toy = gui.multenterbox( msg = 'Enter the data for the new toy:', title = 'New Toy', fields = ('Toy Name', 'F...
0
2010-01-20T00:12:54Z
2,098,216
<p>Here is an example python function that returns a new function based on the parameter passed in. I'm not sure what you are trying to do but this might help point you in the right direction.</p> <pre><code>def add_to(amount): def f(x): return x + amount return f if __name__ == "__main__": add_...
2
2010-01-20T00:18:46Z
[ "python", "function" ]
What is the purpose of pinax's groups?
2,098,190
<p>I viewed the DjangoCon 2009 talks about pinax by James Tauber and pydanny and heared about pinax's groups. But I don't get the actual usecases they describe, even after reading the <a href="http://pinaxproject.com/docs/dev/groups.html" rel="nofollow">documentation</a>.</p> <p>So what is the real purpose of groups a...
2
2010-01-20T00:14:26Z
2,106,532
<p>Say you have a wiki app or a todo app and you don't want your site just to have one wiki and one todo list. Say that you want your site to have teams where each team gets its own wiki and todo list.</p> <p>The groups app in Pinax provides the base for you to built your teams app on. It helps you create a new model ...
5
2010-01-21T02:34:23Z
[ "python", "django", "pinax" ]
Python optparse not seeing argument
2,098,211
<p>I am trying to pass '-f nameoffile' to the program when I call it from the command line. I got this from the python sites documentation but when I pass '-f filename' or '--file=filename' it throws the error that I didnt pass enough arguments. If i pass -h the programs responds how it should and gives me the help. ...
0
2010-01-20T00:17:40Z
2,098,235
<p>After parsing the options out of the argument list, you check that you were passed an argument. This is independent of the argument to -f. It sounds like you're just not passing this argument. Since you also don't actually <em>use</em> this argument, you should probably just remove the check on len(args).</p>
1
2010-01-20T00:21:52Z
[ "python", "optparse" ]
Python optparse not seeing argument
2,098,211
<p>I am trying to pass '-f nameoffile' to the program when I call it from the command line. I got this from the python sites documentation but when I pass '-f filename' or '--file=filename' it throws the error that I didnt pass enough arguments. If i pass -h the programs responds how it should and gives me the help. ...
0
2010-01-20T00:17:40Z
2,098,249
<p>Your problem is probably the <code>if len(args) != 1:</code>. That is looking for an <em>additional</em> argument (i.e. not an option). If you remove that check and look at your <code>options</code> dictionary you should see <code>{'filename': 'blah'}</code>.</p>
2
2010-01-20T00:24:56Z
[ "python", "optparse" ]
Python optparse not seeing argument
2,098,211
<p>I am trying to pass '-f nameoffile' to the program when I call it from the command line. I got this from the python sites documentation but when I pass '-f filename' or '--file=filename' it throws the error that I didnt pass enough arguments. If i pass -h the programs responds how it should and gives me the help. ...
0
2010-01-20T00:17:40Z
2,098,251
<p>Your input filename isn't an option to the program, it's an argument:</p> <pre><code>def main(): usage = "Usage: %prog [options] FILE" description = "Read data from FILE." parser = OptionParser(usage, description=description) (options, args) = parser.parse_args() if len(args) != 1: pars...
1
2010-01-20T00:25:27Z
[ "python", "optparse" ]
Python optparse not seeing argument
2,098,211
<p>I am trying to pass '-f nameoffile' to the program when I call it from the command line. I got this from the python sites documentation but when I pass '-f filename' or '--file=filename' it throws the error that I didnt pass enough arguments. If i pass -h the programs responds how it should and gives me the help. ...
0
2010-01-20T00:17:40Z
2,098,275
<p>You should set the 'action' attribute in the 'add_option()' method to 'store', this tells the optparse object to store the argument immediately following the option flag, though this is the default behavior. The value following the flag will then be stored in 'options.filename' and not in args. I also think that the...
0
2010-01-20T00:30:40Z
[ "python", "optparse" ]
Python Detect Keystrokes Sent to Another Application
2,098,388
<p>I have a Python program that sends keystrokes to another application using SendKeys. Some of the keystrokes, however, must be sent to the application after it does some processing (which takes an unknown amount of time). So far I have had to let the Python application know the processing was finished by Alt+Tabbing ...
0
2010-01-20T01:06:11Z
2,098,509
<p>Have a look at <a href="http://mindtrove.info/articles/monitoring-global-input-with-pyhook/" rel="nofollow">pyHook</a>.</p> <p>It allows Keyboard hooking:</p> <pre><code>import pythoncom, pyHook def OnKeyboardEvent(event): print 'MessageName:',event.MessageName print 'Message:',event.Message print 'Time:',...
0
2010-01-20T01:40:28Z
[ "python", "sendkeys" ]
GAE datastore eager loading in python api
2,098,417
<p>I have two models in relation one-to-many:</p> <blockquote> <p><strong>class Question(db.Model):</strong></p> <blockquote> <p><strong>questionText = db.StringProperty(multiline=False)</strong></p> </blockquote> <p><strong>class Answer(db.Model):</strong></p> <blockquote> <p><strong>answer...
1
2010-01-20T01:15:03Z
2,099,009
<p>By default PyAMF will not encode ReferenceProperty fields unless they have already been specifically loaded by the service method. This is on purpose so you don't end up encoding more than you have to.</p> <p>PyAMF looks for a special class attribute <code>__amf__</code> which it uses to customise the encoding and ...
1
2010-01-20T04:20:41Z
[ "python", "google-app-engine", "gae-datastore", "eager-loading", "pyamf" ]
Python Send Keystrokes to Non-Active Application
2,098,480
<p>I'm automating some common GUI tasks I have to do in an application, and I'm using a Python program and SendKeys to do it. So far I've had to activate the application I'm sending keys to (since SendKeys just sends the keystrokes to the active window), but I'd like to be able to send keystrokes to an application in t...
2
2010-01-20T01:32:36Z
2,099,376
<pre><code>SendKeys is a Python module for Windows that can send one or more keystrokes or keystroke combinations to the active window. </code></pre> <p>If you need to do some automated work in the background, make another user/session and do it in that.</p> <p>However if you must do something of this like on windows...
3
2010-01-20T06:08:05Z
[ "python", "sendkeys" ]
Python Send Keystrokes to Non-Active Application
2,098,480
<p>I'm automating some common GUI tasks I have to do in an application, and I'm using a Python program and SendKeys to do it. So far I've had to activate the application I'm sending keys to (since SendKeys just sends the keystrokes to the active window), but I'd like to be able to send keystrokes to an application in t...
2
2010-01-20T01:32:36Z
2,101,964
<p>This is a frequent question in the <a href="http://autohotkey.com" rel="nofollow">autohotkey</a>.com forums. Search under "sending commands to controls". Basically, if you have the control ID, then it doesn't need to be visible in order to operate on it. There're more details on the forums.</p> <p>good luck!</p>
2
2010-01-20T14:23:07Z
[ "python", "sendkeys" ]
Python Send Keystrokes to Non-Active Application
2,098,480
<p>I'm automating some common GUI tasks I have to do in an application, and I'm using a Python program and SendKeys to do it. So far I've had to activate the application I'm sending keys to (since SendKeys just sends the keystrokes to the active window), but I'd like to be able to send keystrokes to an application in t...
2
2010-01-20T01:32:36Z
2,102,340
<p><a href="http://pywinauto.openqa.org/" rel="nofollow">pywinauto</a> is another MS-only GUI automation tool, this one written in Python.</p>
3
2010-01-20T15:09:44Z
[ "python", "sendkeys" ]
wxPython - lines drawn with Device Context disappear when focus changes
2,098,482
<p>I've written this small app that draws lines between two points selected by the user and it works but how do I keep the lines I draw from disappearing whenever the window is minimized or gets covered by another open window?</p> <pre><code>class SimpleDraw(wx.Frame): def __init__(self, parent, id, title, size=(640...
1
2010-01-20T01:32:51Z
2,098,572
<p>You have to structure your program differently in a GUI environment. Typically, you maintain a data structure called your model. In your case, you already have a start of one, <code>self.points</code>. Then you only draw on the window in response to a paint event. The windowing system will send you paint events ...
0
2010-01-20T01:56:39Z
[ "python", "wxpython" ]
wxPython - lines drawn with Device Context disappear when focus changes
2,098,482
<p>I've written this small app that draws lines between two points selected by the user and it works but how do I keep the lines I draw from disappearing whenever the window is minimized or gets covered by another open window?</p> <pre><code>class SimpleDraw(wx.Frame): def __init__(self, parent, id, title, size=(640...
1
2010-01-20T01:32:51Z
2,102,387
<p>Your issue is that you are <em>only</em> drawing when the user clicks. The resize/erase (when another window covers yours) problems are because your window doesn't maintain a "buffer" which it can redraw.</p> <p>Here, I've modified your sample, it seems to be working okay.</p> <pre><code>import wx class SimpleDra...
0
2010-01-20T15:15:45Z
[ "python", "wxpython" ]
Parallel while Loops in Python
2,098,495
<p>I'm pretty new to Python, and programming in general and I'm creating a virtual pet style game for my little sister.</p> <p>Is it possible to run 2 <em>while</em> loops parallel to each other in python? eg:</p> <pre><code>while 1: input_event_1 = gui.buttonbox( msg = 'Hello, what would you like to do w...
3
2010-01-20T01:37:42Z
2,098,521
<p>i think they cannot be coupled in to one while loop. maybe you need to check the <strong>threading</strong> or <strong>multiprocessing</strong> library.</p>
0
2010-01-20T01:43:28Z
[ "python", "events", "loops", "parallel-processing", "while-loop" ]
Parallel while Loops in Python
2,098,495
<p>I'm pretty new to Python, and programming in general and I'm creating a virtual pet style game for my little sister.</p> <p>Is it possible to run 2 <em>while</em> loops parallel to each other in python? eg:</p> <pre><code>while 1: input_event_1 = gui.buttonbox( msg = 'Hello, what would you like to do w...
3
2010-01-20T01:37:42Z
2,098,542
<p>Have a look at <a href="http://docs.python.org/library/threading.html#timer-objects" rel="nofollow">Threading.Timer</a>. </p> <p>There is a <a href="http://code.activestate.com/recipes/496800/" rel="nofollow">code recipe here to schedule a function to run every 5 seconds</a>.</p> <pre><code>import thread import th...
0
2010-01-20T01:48:19Z
[ "python", "events", "loops", "parallel-processing", "while-loop" ]
Parallel while Loops in Python
2,098,495
<p>I'm pretty new to Python, and programming in general and I'm creating a virtual pet style game for my little sister.</p> <p>Is it possible to run 2 <em>while</em> loops parallel to each other in python? eg:</p> <pre><code>while 1: input_event_1 = gui.buttonbox( msg = 'Hello, what would you like to do w...
3
2010-01-20T01:37:42Z
2,098,543
<p>The only way to "have two while loops in parallel" would be to place them on different threads, but then you need to tackle the synchronization and coordination problems between them since they're reaching into the same object.</p> <p>I suggest you instead put a time check in the first (and single) loop and perform...
3
2010-01-20T01:48:17Z
[ "python", "events", "loops", "parallel-processing", "while-loop" ]
Parallel while Loops in Python
2,098,495
<p>I'm pretty new to Python, and programming in general and I'm creating a virtual pet style game for my little sister.</p> <p>Is it possible to run 2 <em>while</em> loops parallel to each other in python? eg:</p> <pre><code>while 1: input_event_1 = gui.buttonbox( msg = 'Hello, what would you like to do w...
3
2010-01-20T01:37:42Z
2,098,560
<p>Essentially to have processing to happen in parallel you have several solutions</p> <p>1- Separate processes (ie: programs) running independently that speak to one another through a specific protocol (eg: Sockets)</p> <p>2- Or you can have the one process spawn off multiple threads</p> <p>3- Build an event queue ...
1
2010-01-20T01:52:12Z
[ "python", "events", "loops", "parallel-processing", "while-loop" ]
Parallel while Loops in Python
2,098,495
<p>I'm pretty new to Python, and programming in general and I'm creating a virtual pet style game for my little sister.</p> <p>Is it possible to run 2 <em>while</em> loops parallel to each other in python? eg:</p> <pre><code>while 1: input_event_1 = gui.buttonbox( msg = 'Hello, what would you like to do w...
3
2010-01-20T01:37:42Z
2,098,574
<p>put one of them into a function, the threading.Thread class supports a target attribute:</p> <pre><code>import threading threading.Thread(target=yourFunc).start() </code></pre> <p>Will start yourFunc() running in the background.</p>
1
2010-01-20T01:57:24Z
[ "python", "events", "loops", "parallel-processing", "while-loop" ]
Parallel while Loops in Python
2,098,495
<p>I'm pretty new to Python, and programming in general and I'm creating a virtual pet style game for my little sister.</p> <p>Is it possible to run 2 <em>while</em> loops parallel to each other in python? eg:</p> <pre><code>while 1: input_event_1 = gui.buttonbox( msg = 'Hello, what would you like to do w...
3
2010-01-20T01:37:42Z
2,098,657
<p>There is also a package called <a href="http://simpy.sourceforge.net/" rel="nofollow">SimPy</a> that you could also look at. The <b>threading</b> and <b>multiprocessing</b> libraries may also help.</p>
0
2010-01-20T02:19:37Z
[ "python", "events", "loops", "parallel-processing", "while-loop" ]
Parallel while Loops in Python
2,098,495
<p>I'm pretty new to Python, and programming in general and I'm creating a virtual pet style game for my little sister.</p> <p>Is it possible to run 2 <em>while</em> loops parallel to each other in python? eg:</p> <pre><code>while 1: input_event_1 = gui.buttonbox( msg = 'Hello, what would you like to do w...
3
2010-01-20T01:37:42Z
2,099,391
<p>You should use State Machines for this (see the Apress pygame book - downloads here: <a href="http://apress.com/book/downloadfile/3765" rel="nofollow">http://apress.com/book/downloadfile/3765</a> ), see chapter 7.</p> <p>A simplified state machine:</p> <pre><code>def do_play(pet, time_passed): pet.happiness +=...
3
2010-01-20T06:11:25Z
[ "python", "events", "loops", "parallel-processing", "while-loop" ]
POSTing forms in Django's admin interface
2,098,527
<p>I'm writing a Django admin action to mass e-mail contacts. The action is defined as follows:</p> <pre><code>def email_selected(self,request,queryset): rep_list = [] for each in queryset: reps = CorporatePerson.objects.filter(company_id = Company.objects.get(name=each.name)) contact_reps =...
1
2010-01-20T01:45:08Z
2,098,671
<p>You can use django's inbuilt url tag to avoid hardcoding links. see... </p> <p><a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#url" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/templates/builtins/#url</a></p> <p>Chances are you'd be better off setting up a mass mailer to be trigger...
1
2010-01-20T02:24:12Z
[ "python", "django", "django-admin", "django-templates", "django-urls" ]
setting referral url in python urllib.urlretrieve
2,098,623
<p>I am using <code>urllib.urlretrieve</code> in Python to download websites. Though some websites seem to not want me to download them, unless they have a proper referrer from their own site. Does anybody know of a way I can set a referrer in one of Python's libraries or a external one to. </p>
5
2010-01-20T02:12:21Z
2,098,654
<p><code>urllib</code> makes it hard to send arbitrary headers with the request; you could use <a href="http://docs.python.org/library/urllib2.html" rel="nofollow">urllib2</a>, which lets you build and send a <a href="http://docs.python.org/library/urllib2.html#urllib2.Request" rel="nofollow">Request</a> object with ar...
2
2010-01-20T02:19:05Z
[ "python", "html" ]
setting referral url in python urllib.urlretrieve
2,098,623
<p>I am using <code>urllib.urlretrieve</code> in Python to download websites. Though some websites seem to not want me to download them, unless they have a proper referrer from their own site. Does anybody know of a way I can set a referrer in one of Python's libraries or a external one to. </p>
5
2010-01-20T02:12:21Z
2,098,655
<pre><code>import urllib2 req = urllib2.Request('http://www.example.com/') req.add_header('Referer', 'http://www.python.org/') r = urllib2.urlopen(req) </code></pre> <p>adopted from <a href="http://docs.python.org/library/urllib2.html">http://docs.python.org/library/urllib2.html</a></p>
9
2010-01-20T02:19:11Z
[ "python", "html" ]
setting referral url in python urllib.urlretrieve
2,098,623
<p>I am using <code>urllib.urlretrieve</code> in Python to download websites. Though some websites seem to not want me to download them, unless they have a proper referrer from their own site. Does anybody know of a way I can set a referrer in one of Python's libraries or a external one to. </p>
5
2010-01-20T02:12:21Z
12,096,956
<p>Also, using <code>urllib2</code> with <code>build_opener</code> you can do this:</p> <pre><code>import urllib2 opener = urllib2.build_opener() opener.addheaders = [('Referer', 'http://www.python.org/')] opener.open('http://www.example.com/') </code></pre>
1
2012-08-23T17:20:10Z
[ "python", "html" ]
Python List indexed by tuples
2,098,695
<p>I'm a Matlab user needing to use Python for some things, I would really appreciate it if someone can help me out with Python syntax:</p> <p>(1) Is it true that lists can be indexed by tuples in Python? If so, how do I do this? For example, I would like to use that to represent a matrix of data.</p> <p>(2) Assumi...
3
2010-01-20T02:32:25Z
2,098,702
<p>You should look into <a href="http://numpy.scipy.org/">numpy</a>, it's made for just this sort of thing.</p>
8
2010-01-20T02:34:32Z
[ "python", "list", "matlab", "list-comprehension" ]
Python List indexed by tuples
2,098,695
<p>I'm a Matlab user needing to use Python for some things, I would really appreciate it if someone can help me out with Python syntax:</p> <p>(1) Is it true that lists can be indexed by tuples in Python? If so, how do I do this? For example, I would like to use that to represent a matrix of data.</p> <p>(2) Assumi...
3
2010-01-20T02:32:25Z
2,098,703
<ol> <li>No, but dicts can.</li> <li>Sounds like you want a "2d array", matrix type, or something else. Have you looked at <a href="http://numpy.scipy.org/" rel="nofollow">numpy</a> yet?</li> <li>Depends on what you choose from #2, but Python does have <a href="http://docs.python.org/library/functions.html#sum" rel="n...
3
2010-01-20T02:34:48Z
[ "python", "list", "matlab", "list-comprehension" ]
Python List indexed by tuples
2,098,695
<p>I'm a Matlab user needing to use Python for some things, I would really appreciate it if someone can help me out with Python syntax:</p> <p>(1) Is it true that lists can be indexed by tuples in Python? If so, how do I do this? For example, I would like to use that to represent a matrix of data.</p> <p>(2) Assumi...
3
2010-01-20T02:32:25Z
2,098,720
<p>(1) I don't think you can use a tuple as an index of python list. You may use list of list ( e.g. a[i][j]) but it seems that it's not your point. You may use a dictionary whose key is tuple. </p> <pre><code>d = { (1,1):1, (2,1):2 ... } </code></pre> <p>(2) If you don't mind about the performance, </p> <pre><c...
0
2010-01-20T02:41:42Z
[ "python", "list", "matlab", "list-comprehension" ]
Python List indexed by tuples
2,098,695
<p>I'm a Matlab user needing to use Python for some things, I would really appreciate it if someone can help me out with Python syntax:</p> <p>(1) Is it true that lists can be indexed by tuples in Python? If so, how do I do this? For example, I would like to use that to represent a matrix of data.</p> <p>(2) Assumi...
3
2010-01-20T02:32:25Z
2,098,729
<p>No, it isn't the case that a list can be indexed by anything but an integer. A dictionary, however, is another case. A dictionary is a hash table consisting a key-value pairs. Keys must be unique and immutable. The value can be objects of any type, including integers, tuples, lists, or other dictionaries. For your e...
0
2010-01-20T02:46:19Z
[ "python", "list", "matlab", "list-comprehension" ]
Python List indexed by tuples
2,098,695
<p>I'm a Matlab user needing to use Python for some things, I would really appreciate it if someone can help me out with Python syntax:</p> <p>(1) Is it true that lists can be indexed by tuples in Python? If so, how do I do this? For example, I would like to use that to represent a matrix of data.</p> <p>(2) Assumi...
3
2010-01-20T02:32:25Z
2,098,768
<p>Here's an example of how to easily create an array (matrix) in numpy:</p> <pre><code>&gt;&gt;&gt; import numpy &gt;&gt;&gt; a = numpy.array([[1,2,3],[4,5,6],[7,8,9]]) </code></pre> <p>here is how it is displayed</p> <pre><code>&gt;&gt;&gt; a array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) </code></pre> <p...
2
2010-01-20T02:57:19Z
[ "python", "list", "matlab", "list-comprehension" ]
Python List indexed by tuples
2,098,695
<p>I'm a Matlab user needing to use Python for some things, I would really appreciate it if someone can help me out with Python syntax:</p> <p>(1) Is it true that lists can be indexed by tuples in Python? If so, how do I do this? For example, I would like to use that to represent a matrix of data.</p> <p>(2) Assumi...
3
2010-01-20T02:32:25Z
2,099,278
<p>I agree with everyone. Use Numpy/Scipy. But here are specific answers to your questions.</p> <ol> <li><p>Yes. And the index can either be a built-in list or a Numpy array. Suppose <code>x = scipy.array([10, 11, 12, 13])</code> and <code>y = scipy.array([0, 2])</code>. Then <code>x[[0, 2]]</code> and <code>x[y]</cod...
2
2010-01-20T05:41:58Z
[ "python", "list", "matlab", "list-comprehension" ]
Is a reason I can't add a ManyToManyField?
2,098,696
<p>So I'm building a Django application, and these are a few models I have:</p> <pre><code>class MagicType(models.Model): name = models.CharField(max_length=155) parent = models.ForeignKey('self', null=True, blank=True) class Spell(models.Model): name = models.CharField(max_length=250, db_index=True) ...
2
2010-01-20T02:32:28Z
2,098,709
<p>Is MagicType declared in the same models file (and before) Spell?</p> <p>Does <code>magic_types = models.ManyToManyField('MagicType')</code> work (with 'MagicType' quoted)? </p>
3
2010-01-20T02:36:15Z
[ "python", "django", "django-models" ]
Is a reason I can't add a ManyToManyField?
2,098,696
<p>So I'm building a Django application, and these are a few models I have:</p> <pre><code>class MagicType(models.Model): name = models.CharField(max_length=155) parent = models.ForeignKey('self', null=True, blank=True) class Spell(models.Model): name = models.CharField(max_length=250, db_index=True) ...
2
2010-01-20T02:32:28Z
2,106,858
<p>I suggest you use django-extensions , this will give you a commnad <code>sqldiiff</code> that works better than evolution, because there is a problem creating the intermediate table between MagicType and MagicType.</p> <p>I suggest you run the command <code>sqlall yourapp</code> and execute directly the sql code of...
3
2010-01-21T04:07:22Z
[ "python", "django", "django-models" ]
Merging all sub-arrays with mutual elements into one sub-array
2,098,948
<p>I need to find all sub-arrays which share any mutual element and merge them into one sub-array. (Implementing in Python but any algorithmic idea would be helpful)</p> <p>Multidimensional array structure:</p> <pre><code>categories = {'car':['automobile','auto'], 'bike':['vehicle','motorcycle','motorbi...
0
2010-01-20T03:59:35Z
2,098,996
<p>Note that there <strong>is</strong> no "first key" -- dicts don't keep order, so if you need some order preserved you'll need to start from some different, alternative data structure.</p> <p>Apart from order-related issues, I'd start with something like:</p> <pre><code>def merged(dictoflists): result = dict() ...
2
2010-01-20T04:15:03Z
[ "python", "performance", "algorithm", "arrays" ]
Merging all sub-arrays with mutual elements into one sub-array
2,098,948
<p>I need to find all sub-arrays which share any mutual element and merge them into one sub-array. (Implementing in Python but any algorithmic idea would be helpful)</p> <p>Multidimensional array structure:</p> <pre><code>categories = {'car':['automobile','auto'], 'bike':['vehicle','motorcycle','motorbi...
0
2010-01-20T03:59:35Z
2,099,084
<p>I can't imagine that a recursive solution would be speedy.<br> Is using <a href="http://docs.python.org/library/stdtypes.html#mutable-sequence-types" rel="nofollow">list.extend()</a> too slow?<br> You could do something like this: </p> <pre><code>categories['car'].extend(categories['bike']); categories['car'].exten...
0
2010-01-20T04:40:48Z
[ "python", "performance", "algorithm", "arrays" ]
Merging all sub-arrays with mutual elements into one sub-array
2,098,948
<p>I need to find all sub-arrays which share any mutual element and merge them into one sub-array. (Implementing in Python but any algorithmic idea would be helpful)</p> <p>Multidimensional array structure:</p> <pre><code>categories = {'car':['automobile','auto'], 'bike':['vehicle','motorcycle','motorbi...
0
2010-01-20T03:59:35Z
2,429,255
<pre><code>&gt;&gt;&gt; categories = {'car':['automobile','auto'], 'bike':['vehicle','motorcycle','motorbike','automobile'], 'software':['computer','macbook','apple','microsoft','mozilla'], 'firefox':['internet','mozilla','browser'], 'bicycle':['vehicle']} &gt;&gt;&gt...
0
2010-03-11T22:36:21Z
[ "python", "performance", "algorithm", "arrays" ]
Getting information about static files in Python App Engine; workarounds
2,099,008
<p>I'm working on an App Engine project that will have customizable themes. I'd like to be able to use jQuery UI themes. The problem is figuring out what the CSS file is going to be named. (Typically, "jquery-ui-1.7.2.custom.css". Version numbers will change, and people tend to rename things, but there should only ...
1
2010-01-20T04:20:32Z
2,109,820
<p>To accomplish what you are asking, I would use the datastore for serving the CSS files. Since this would allow easy listing, sorting and even modification and uploading.</p> <p>Other than that, your next best options would be to store the CSS data inside a script (a dictionary where the filename is the key name, an...
1
2010-01-21T14:17:33Z
[ "python", "google-app-engine", "jquery-ui", "themes" ]
Reverse ForeignKey lookup
2,099,037
<p>I'm new to Django and am still trying to break old PHP habits. Below are two models. To make things confusing they live in separate files, in different apps...</p> <pre><code>#article.models from someapp.author.models import Author class Article(model.Model): ... author = models.ForeignKey(Author) # auth...
2
2010-01-20T04:29:27Z
2,099,193
<p>I think this is what you're asking for...</p> <pre><code>class Article(model.Model): ... author = models.ForeignKey(Author, related_name='articles') </code></pre> <p>On a side note, by default without changing anything you've got, I think this would work for you...</p> <pre><code>article.author_set </code...
3
2010-01-20T05:13:46Z
[ "python", "django", "models" ]
Django template ifequal tag
2,099,064
<p>I'm using an ifequal tag in my django template inside a loop where atleast one of the items should equal the other at some point in the loop but for some reason it never displays what it should. I was wondering if there are any weird cases that i should know about.</p> <p>I have a list of int city ID's that should ...
4
2010-01-20T04:36:38Z
2,099,103
<p>The code you've posted would go into infinite loops if either pflags or mflags were non-empty.</p> <p>Consider e.g. this snippet from your code:</p> <pre><code> i = 0 while i &lt; len(pflags): pflags[i] = int(pflags[i]) </code></pre> <p>that's it -- end of loop -- <strong>no</strong> incrementing of <code>i...
1
2010-01-20T04:47:23Z
[ "python", "django", "django-templates" ]
Django template ifequal tag
2,099,064
<p>I'm using an ifequal tag in my django template inside a loop where atleast one of the items should equal the other at some point in the loop but for some reason it never displays what it should. I was wondering if there are any weird cases that i should know about.</p> <p>I have a list of int city ID's that should ...
4
2010-01-20T04:36:38Z
2,111,351
<pre><code>{% for id in pflags %}{% ifequal id city.id %} ... {% endfor %} </code></pre> <p>Could it be that <strong>id</strong> is a string and <strong>city.id</strong> is an integer?</p>
4
2010-01-21T17:26:02Z
[ "python", "django", "django-templates" ]
Django template ifequal tag
2,099,064
<p>I'm using an ifequal tag in my django template inside a loop where atleast one of the items should equal the other at some point in the loop but for some reason it never displays what it should. I was wondering if there are any weird cases that i should know about.</p> <p>I have a list of int city ID's that should ...
4
2010-01-20T04:36:38Z
5,065,479
<p>Notice: </p> <blockquote> <p>It is only possible to compare an argument to template variables or strings. You cannot check for equality with Python objects such as True or False. If you need to test if something is true or false, use the if tag instead.</p> </blockquote> <p>From <a href="http://docs.djangoprojec...
-1
2011-02-21T11:38:59Z
[ "python", "django", "django-templates" ]
using django and twisted together
2,099,189
<p>1)I want to devlop a website that has forums and chat.<strong>The chat and forums are linked in some way</strong>.Meaning for each thread the users can chat in the chat room for that thread or can post a reply to the forum. I was thinking of using django for forums and twisted for chat thing.Can i combine the two? ...
5
2010-01-20T05:12:28Z
2,099,238
<p>I would not combine the two per se; calls into Django would happen synchronously which means that Twisted's event loop would be blocked. Better to treat the Twisted process as a <a href="http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/">standalone app using Django</a> and to have a classic web ser...
10
2010-01-20T05:30:51Z
[ "python", "django", "chat", "twisted", "forums" ]
using django and twisted together
2,099,189
<p>1)I want to devlop a website that has forums and chat.<strong>The chat and forums are linked in some way</strong>.Meaning for each thread the users can chat in the chat room for that thread or can post a reply to the forum. I was thinking of using django for forums and twisted for chat thing.Can i combine the two? ...
5
2010-01-20T05:12:28Z
2,101,355
<p>If forum application needs to get something from chat application, it's simplier to make forum application communicate with chat application with plain HTTP requests and to make them run separately.</p>
0
2010-01-20T12:41:24Z
[ "python", "django", "chat", "twisted", "forums" ]
using django and twisted together
2,099,189
<p>1)I want to devlop a website that has forums and chat.<strong>The chat and forums are linked in some way</strong>.Meaning for each thread the users can chat in the chat room for that thread or can post a reply to the forum. I was thinking of using django for forums and twisted for chat thing.Can i combine the two? ...
5
2010-01-20T05:12:28Z
2,106,609
<p>I have a project going that might be just what you are looking for (at least to get started). It is called Hotdot: <a href="http://github.com/clemesha/hotdot">http://github.com/clemesha/hotdot</a> . </p> <p>Also, I wrote up more details about this topic here: <a href="http://clemesha.org/blog/2009/dec/17/realtime...
10
2010-01-21T02:58:12Z
[ "python", "django", "chat", "twisted", "forums" ]
why 1 is ok,but 2 is error,use django and jquery
2,099,345
<p>django view:</p> <pre><code>def json_view(request): import json tag=request.GET.get('tag') if tag=='userName': username=request.GET.get('userName') result='successName' if username: try: user=User.objects.get(username=username) result='...
1
2010-01-20T05:59:54Z
2,101,712
<p>Write a unit test that isolates the problem. Documentation: <a href="http://docs.djangoproject.com/en/dev/topics/testing/" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/testing/</a></p> <p>The body of the test should be something like:</p> <pre><code>from django.test.client import Client c = Client() ...
1
2010-01-20T13:42:56Z
[ "python", "django" ]
Does IronPython and Jython have the same GIL issues as CPython?
2,099,405
<p>I read about the problems with CPython and CPU bound threads and the GIL and some changes in Python 3.2.</p> <p>Do IronPython and Jython have this same problem?</p> <p>Thanks</p>
2
2010-01-20T06:17:30Z
2,099,421
<p>No, neither have a GIL at all.</p> <p>See <a href="http://stackoverflow.com/questions/1120354/does-jython-have-the-gil">previous answer about Jython</a> and I<a href="http://wiki.python.org/moin/IronPython" rel="nofollow">ronPython wiki page</a>.</p>
8
2010-01-20T06:21:32Z
[ "python", "ironpython", "jython" ]
tips on creating RSS/XML easily in python
2,099,666
<p>I have a list if these 3 items: title and link and a html based description and I am looking for a library or external tool which can be fed these 3 items and create a rss xml page. Does such a thing exist?</p>
4
2010-01-20T07:23:46Z
2,099,685
<p>How about <a href="http://docs.djangoproject.com/en/dev/ref/contrib/syndication/" rel="nofollow">django's RSS Framework</a>?</p>
2
2010-01-20T07:27:18Z
[ "python", "xml", "rss" ]
tips on creating RSS/XML easily in python
2,099,666
<p>I have a list if these 3 items: title and link and a html based description and I am looking for a library or external tool which can be fed these 3 items and create a rss xml page. Does such a thing exist?</p>
4
2010-01-20T07:23:46Z
2,099,746
<p>This might not be the answer you search for, but any RSS dialect is a fairly simple standard (holding for 0.9 and 2 especially, and with constraints for 1, too).</p> <p>You could consider writing it by hand, if you don't have any additional constraints (like, you already use Django, or it will get more complex in t...
1
2010-01-20T07:42:27Z
[ "python", "xml", "rss" ]
tips on creating RSS/XML easily in python
2,099,666
<p>I have a list if these 3 items: title and link and a html based description and I am looking for a library or external tool which can be fed these 3 items and create a rss xml page. Does such a thing exist?</p>
4
2010-01-20T07:23:46Z
2,101,186
<p>I suggest you use a template and feed the list of items to the template.</p> <p>Example <a href="http://jinja.pocoo.org/2/">Jinja2</a> template (Atom, not RSS, but you get the idea), assuming that the items are 3-tuples (title, link, html):</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;feed xmlns...
10
2010-01-20T12:12:00Z
[ "python", "xml", "rss" ]
TCP connection reset occurs when WSGI app responds before consuming environ['wsgi.input']
2,099,752
<p>For our webservice, I wrote some logic to prevent <code>multipart/form-data</code> POSTs larger than, say, 4mb.</p> <p>It boils down to the following (I've stripped away all WebOb usage and just reduced it to plain vanilla WSGI code):</p> <pre><code>import paste.httpserver form = """\ &lt;html> &lt;body> &lt;fo...
3
2010-01-20T07:44:05Z
2,099,848
<p>This is happening because you are discarding the input stream without reading it, and this is forcing it closed. The browser has queued up a good portion of the file to be sent already and then it gets a write error because the server closes the connection forcefully.</p> <p>There is no way around this that I know...
0
2010-01-20T08:11:07Z
[ "python", "http", "tcp", "paste", "wsgiref" ]
python wraps.who can give a example
2,099,788
<pre><code>from functools import wraps def a(): a='aa' def b(): b="bbb" c=wraps(a)(b) print c#what happen? </code></pre> <p>What is the wraps mean, example is the best.</p>
2
2010-01-20T07:53:04Z
2,099,793
<p>Quoted from <a href="http://docs.python.org/library/functools.html#functools.wraps" rel="nofollow">the documentation</a>:</p> <pre><code>functools.wraps(wrapped[, assigned][, updated]) </code></pre> <p>This is a convenience function for invoking <code>partial(update_wrapper, wrapped=wrapped, assigned=assigned, up...
7
2010-01-20T07:55:52Z
[ "python" ]
How to prevent JPEG compression when uploading image through Picasa API?
2,100,001
<p>I'm using the Python <a href="http://code.google.com/apis/picasaweb/docs/1.0/developers_guide_python.html" rel="nofollow">client library</a> for the Picasa Web Albums API to upload some JPEG images to an album. But the photos appear very compressed once uploaded. In Picasa 3.6 there is an option to upload images in ...
1
2010-01-20T08:40:47Z
2,124,172
<p>I managed to solve this problem myself, and it turned out to be a weird one :-)</p> <p>I asked around on the Google Group for the Picasa data API and people there were saying that the API does not do any compression when uploading new images. That led me to look at the other code, namely the <code>urlfetch</code>.<...
3
2010-01-23T18:24:07Z
[ "python", "jpeg", "gdata-api", "picasa" ]
Where is the function 'real_ugettext' in django?
2,100,032
<p>In <a href="http://code.djangoproject.com/browser/django/trunk/django/utils/translation/__init__.py?rev=6582" rel="nofollow"><code>django.utils.translations.__init__.py</code></a>:</p> <pre><code>def ugettext(message): return real_ugettext(message) </code></pre> <p>I can't find it.</p>
0
2010-01-20T08:45:31Z
2,100,053
<p>Django does some nasty global-munging magic in order to replace it with ugettext from either trans_real or trans_null found in the same package.</p>
0
2010-01-20T08:50:05Z
[ "python", "django" ]
Where is the function 'real_ugettext' in django?
2,100,032
<p>In <a href="http://code.djangoproject.com/browser/django/trunk/django/utils/translation/__init__.py?rev=6582" rel="nofollow"><code>django.utils.translations.__init__.py</code></a>:</p> <pre><code>def ugettext(message): return real_ugettext(message) </code></pre> <p>I can't find it.</p>
0
2010-01-20T08:45:31Z
2,100,070
<p>Read <a href="http://code.djangoproject.com/browser/django/trunk/django/utils/translation/__init__.py?rev=6582" rel="nofollow">that file</a> a little closer:</p> <pre><code>def delayed_loader(*args, **kwargs): """ Replace each real_* function with the corresponding function from either trans_real or tra...
4
2010-01-20T08:53:33Z
[ "python", "django" ]
How to find the source of increasing memory usage of a twisted server?
2,100,192
<p>I have an audio broadcasting server written in Python and based on Twisted. It works fine, but its memory usage is increasing when there are more users on server, but the memory usage never goes down when those users get off line. As you see in following figure: <img src="http://static.ez2learn.com/temp/mem_figure3...
17
2010-01-20T09:18:30Z
2,100,821
<p>Have you thought about using CentOS' alternative to dtrace - <a href="http://sourceware.org/systemtap/wiki" rel="nofollow">SystemTap</a> I think its called. </p> <p>This should give you a pretty low level trace of what's happening inside your *nix processes.......a stab in the dark, but might give you some more tr...
0
2010-01-20T11:03:44Z
[ "python", "memory-leaks", "memory-management", "twisted" ]
How to find the source of increasing memory usage of a twisted server?
2,100,192
<p>I have an audio broadcasting server written in Python and based on Twisted. It works fine, but its memory usage is increasing when there are more users on server, but the memory usage never goes down when those users get off line. As you see in following figure: <img src="http://static.ez2learn.com/temp/mem_figure3...
17
2010-01-20T09:18:30Z
2,100,894
<p>It does sound like a memory leak in a C module to me. <a href="http://valgrind.org/" rel="nofollow">Valgrind</a> is a good tool to track memory-allocation related problems. I don't know how good it works with run-time loaded modules though...</p>
2
2010-01-20T11:17:21Z
[ "python", "memory-leaks", "memory-management", "twisted" ]
How to find the source of increasing memory usage of a twisted server?
2,100,192
<p>I have an audio broadcasting server written in Python and based on Twisted. It works fine, but its memory usage is increasing when there are more users on server, but the memory usage never goes down when those users get off line. As you see in following figure: <img src="http://static.ez2learn.com/temp/mem_figure3...
17
2010-01-20T09:18:30Z
2,229,010
<p>As my guessing, it is due to memory fragmentation problem. The original design is to keep audio data chunks in a list, all of them are not in fixed size. Once the total size of the buffering list exceeds the limit of buffer, it pops some chunks from the top of list for limiting the size. It might looks like this:...
6
2010-02-09T12:39:59Z
[ "python", "memory-leaks", "memory-management", "twisted" ]
django error. about django.forms
2,100,198
<pre><code>from django import forms class a(forms.Form): name = forms.CharField(initial='Your name') url = forms.URLField(initial='Your Web site') comment = forms.CharField() data = {'name': 'hahaha', 'url': '', 'comment': 'Foo'} f = a(data,auto_id=False) #print f.is_valid() print f.errors </code></pre> ...
0
2010-01-20T09:20:06Z
2,100,210
<p>That error shows up because you're not running the script as part of a Django app. There are a <a href="http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/" rel="nofollow">number of measures</a> you can take to get it to work, but having a form separate from the app will probably not be terribly usef...
1
2010-01-20T09:23:12Z
[ "python", "django" ]
Python sockets, how to escape from infinite loop and handle exceptions
2,100,224
<p>I have a script that connects to a remote server. The code is below</p> <pre><code>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((remote_host,remote_port)) s.setblocking(False) while True: try: data = s.recv(1024) if not data: break pkt_type = ord(data[2]...
1
2010-01-20T09:26:40Z
2,100,259
<p><strong>EDIT:</strong> <strike>Looks like a FSM should be handy here.</strike></p> <p>Actually, I suggest you take a look at <a href="http://docs.huihoo.com/python/twisted/howto/clients.html" rel="nofollow">Twisted Reactor</a> - haven't used it myself (yet), but it does all the bulk work and nasty stuff that you wo...
0
2010-01-20T09:32:13Z
[ "python", "sockets", "communication-protocol" ]
Python sockets, how to escape from infinite loop and handle exceptions
2,100,224
<p>I have a script that connects to a remote server. The code is below</p> <pre><code>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((remote_host,remote_port)) s.setblocking(False) while True: try: data = s.recv(1024) if not data: break pkt_type = ord(data[2]...
1
2010-01-20T09:26:40Z
2,100,361
<p>A Finite State Machine (FSM) is pretty much the canonical way to do this sort of thing. A good reference for doing FSMs in Python is this: <a href="http://wiki.python.org/moin/FiniteStateMachine" rel="nofollow">http://wiki.python.org/moin/FiniteStateMachine</a></p>
1
2010-01-20T09:48:33Z
[ "python", "sockets", "communication-protocol" ]
Python sockets, how to escape from infinite loop and handle exceptions
2,100,224
<p>I have a script that connects to a remote server. The code is below</p> <pre><code>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((remote_host,remote_port)) s.setblocking(False) while True: try: data = s.recv(1024) if not data: break pkt_type = ord(data[2]...
1
2010-01-20T09:26:40Z
2,101,043
<p>In addition to the above tips, you need to buffer the data - when using a stream protocol you can't just assume that you will get all the data you want in one call to recv. Instead you must take what you read from recv and add it to a buffer, then examine the buffer to see if it contains all the data for a message y...
0
2010-01-20T11:45:13Z
[ "python", "sockets", "communication-protocol" ]
Python List not getting in rendered in javascript
2,100,233
<p>I have a javascript which takes two variables i.e two lists one is a list of numbers and the other list of strings from django/python</p> <pre><code>numbersvar = [0,1,2,3] stringsvar = ['a','b','c'] </code></pre> <p>The numbersvar is rendered perfectly but when I do {{stringsvar}} it does not render it.</p>
1
2010-01-20T09:27:46Z
2,100,611
<p>Maybe it will be better to use a <strong><a href="http://www.google.com/url?sa=t&amp;source=web&amp;ct=res&amp;cd=1&amp;ved=0CDkQFjAA&amp;url=http%3A%2F%2Fdocs.python.org%2Flibrary%2Fjson.html&amp;ei=b9pWS7mmO8eK_Abcppz-Aw&amp;usg=AFQjCNG7_WS8ga_dF7-eGjquJarNhC5Eew&amp;sig2=_SZrRNdbAGmbGuW9tVYgHw" rel="nofollow">jso...
3
2010-01-20T10:27:11Z
[ "javascript", "python" ]
Python List not getting in rendered in javascript
2,100,233
<p>I have a javascript which takes two variables i.e two lists one is a list of numbers and the other list of strings from django/python</p> <pre><code>numbersvar = [0,1,2,3] stringsvar = ['a','b','c'] </code></pre> <p>The numbersvar is rendered perfectly but when I do {{stringsvar}} it does not render it.</p>
1
2010-01-20T09:27:46Z
2,100,628
<p>What does stringsvar contain? The list, or the string representation of the list?</p> <p>I suggest you pass the correct javascript string representation of the list from the view method to the template to render. Python and javascript array literals have the same syntax, so you could do:</p> <pre><code>def my_view...
0
2010-01-20T10:29:18Z
[ "javascript", "python" ]
Django: Check on type of relation a form has
2,100,297
<p>I have a situation where I need to check if a form has m2m relation before saving it in views.py as I am using the same views.py for different models.</p> <p>Example:</p> <pre><code>#models.py class BaseClass(models.Model): # Some generic stuff. class SomeClass(BaseClass): # This class doesnt have any many2...
1
2010-01-20T09:37:52Z
2,100,599
<pre><code>if hasattr(form, 'save_m2m'): form.save_m2m() </code></pre> <p>You should bear in mind that <code>save_m2m</code> is only necessary (and only exists) when you call <code>form.save</code> with <code>commit=False</code> argument. If you save it with <code>commit=True</code> which is the default, there's n...
0
2010-01-20T10:24:26Z
[ "python", "django", "django-views" ]
Django: Check on type of relation a form has
2,100,297
<p>I have a situation where I need to check if a form has m2m relation before saving it in views.py as I am using the same views.py for different models.</p> <p>Example:</p> <pre><code>#models.py class BaseClass(models.Model): # Some generic stuff. class SomeClass(BaseClass): # This class doesnt have any many2...
1
2010-01-20T09:37:52Z
2,102,240
<p>I just figured out the probable solution for this.</p> <p>You could use something like this:</p> <pre><code>if len(form_instance._meta.many_to_many) &gt; 0: for i in form_instance._meta.many_to_many: if type(i) = ManyToManyField: form_instance.save_m2m() break </code></pre>
0
2010-01-20T14:58:20Z
[ "python", "django", "django-views" ]
Django: Check on type of relation a form has
2,100,297
<p>I have a situation where I need to check if a form has m2m relation before saving it in views.py as I am using the same views.py for different models.</p> <p>Example:</p> <pre><code>#models.py class BaseClass(models.Model): # Some generic stuff. class SomeClass(BaseClass): # This class doesnt have any many2...
1
2010-01-20T09:37:52Z
2,103,524
<p>Antony is right and it is even easier, I quote from the <a href="http://docs.djangoproject.com/en/1.1/topics/forms/modelforms/#the-save-method" rel="nofollow">documentation</a>:</p> <blockquote> <p>Another side effect of using <code>commit=False</code> is seen when your model has a many-to-many relation with anot...
0
2010-01-20T17:37:40Z
[ "python", "django", "django-views" ]
Django: Check on type of relation a form has
2,100,297
<p>I have a situation where I need to check if a form has m2m relation before saving it in views.py as I am using the same views.py for different models.</p> <p>Example:</p> <pre><code>#models.py class BaseClass(models.Model): # Some generic stuff. class SomeClass(BaseClass): # This class doesnt have any many2...
1
2010-01-20T09:37:52Z
2,103,895
<p>In fact, <code>save_m2m()</code> is always injected into <code>ModelForm</code> instance after <code>save(commit=False)</code>. Even if there're no <code>ManyToMany</code> fields in the model.</p> <p>Here's the source of <code>save_m2m</code> function:</p> <pre><code>def save_m2m(): opts = instance._meta c...
0
2010-01-20T18:29:03Z
[ "python", "django", "django-views" ]
sort csv by column
2,100,353
<p>I want to sort a CSV table by date. Started out being a simple task:</p> <pre><code>import sys import csv reader = csv.reader(open("files.csv"), delimiter=";") for id, path, title, date, author, platform, type, port in reader: print date </code></pre> <p>I used Python's CSV module to read in a file with that...
14
2010-01-20T09:47:32Z
2,100,384
<pre><code>import operator sortedlist = sorted(reader, key=operator.itemgetter(3), reverse=True) </code></pre> <p>or use lambda</p> <pre><code>sortedlist = sorted(reader, key=lambda row: row[3], reverse=True) </code></pre>
32
2010-01-20T09:51:50Z
[ "python", "csv", "sorting", "parsing" ]
sort csv by column
2,100,353
<p>I want to sort a CSV table by date. Started out being a simple task:</p> <pre><code>import sys import csv reader = csv.reader(open("files.csv"), delimiter=";") for id, path, title, date, author, platform, type, port in reader: print date </code></pre> <p>I used Python's CSV module to read in a file with that...
14
2010-01-20T09:47:32Z
2,100,963
<p>The reader acts like a generator. On a file with some fake data:</p> <pre><code>&gt;&gt;&gt; import sys, csv &gt;&gt;&gt; data = csv.reader(open('data.csv'),delimiter=';') &gt;&gt;&gt; data &lt;_csv.reader object at 0x1004a11a0&gt; &gt;&gt;&gt; data.next() ['a', ' b', ' c'] &gt;&gt;&gt; data.next() ['x', ' y', ' z...
7
2010-01-20T11:28:24Z
[ "python", "csv", "sorting", "parsing" ]
How to make os.mkfifo and subprocess.Popen work together?
2,100,581
<p>I'm trying to redirect a <strong>patch</strong> command output using a named pipe. I tried like this:</p> <pre><code>fifo = os.path.join(self.path, 'pipe') os.mkfifo(fifo) op = os.popen('cat '+ fifo) proc = Popen(['patch', current_keyframe, '--input='+fpath, '--output='+fifo], stdin=PIPE, stdout=PIPE) os.unlink(fif...
0
2010-01-20T10:22:44Z
2,100,620
<p>You aren't waiting for the patch command to finish before you read from the fifo. Replace the <code>subprocess.Popen()</code> call with <code>subprocess.call()</code>, and remove the stdin/stdout redirections you aren't using. Also, use <code>open(fifo)</code> to read from the fifo, not <code>os.popen('cat ' + fifo)...
1
2010-01-20T10:28:46Z
[ "python", "subprocess", "patch", "fifo" ]
Can I get the kerning value of two characters using PIL?
2,100,696
<p>Is it possible to get the kerning value of two characters in a font using PIL?</p>
0
2010-01-20T10:42:23Z
2,100,738
<p>No, PIL can only be used to render text, not get its metrics. You'll need to use either the appropriate Windows API functions, or the <a href="http://www.freetype.org/" rel="nofollow">FreeType</a> library (for which no stable Python bindings exist) in order to get kerning info.</p>
1
2010-01-20T10:50:30Z
[ "python", "fonts", "python-imaging-library" ]
Can I get the kerning value of two characters using PIL?
2,100,696
<p>Is it possible to get the kerning value of two characters in a font using PIL?</p>
0
2010-01-20T10:42:23Z
2,106,256
<p>The answer is, as Ignacio said, no.</p> <p>That was the serious part of this answer. And now, for something completely different:</p> <p>you can approximate <em>a</em> (not <em>the</em>, since you can't know by using PIL alone what is the design em size of the font) kerning value using something like:</p> <pre><c...
2
2010-01-21T01:11:42Z
[ "python", "fonts", "python-imaging-library" ]
Subtract dict A from dict B (deep del)?
2,100,697
<p>If I have a deeply nested dict is there a built-in way to subtract/remove list of "paths" (eg: keyA.keyB.key1, keyA.keyC.key2, etc) or a the keys of a second dict from the original dict? Or maybe there is a common module which has functionality like this?</p>
4
2010-01-20T10:42:32Z
2,100,809
<p>Here's a suggestion:</p> <pre><code>D = { "keyA": { "keyB" : { "keyC" : 42, "keyD": 13 }, "keyE" : 55 } } def remove_path(dictionary, path): for node in path[:-1]: dictionary = dictionary[node] del dictionary[path[-1]] remove_path(D,...
2
2010-01-20T11:02:04Z
[ "python", "dictionary" ]