content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Can I write a UDF for MySQL in Python? I would like to have the option to call Python via MySQL stored procs. For this reason I was wondering if I can use Python to write a UDF that I can call from MySQL. If that's not possible what alternative way could I use to make this happen. A: The MySQL 5.0 docs say tha...
Can I write a UDF for MySQL in Python?
I would like to have the option to call Python via MySQL stored procs. For this reason I was wondering if I can use Python to write a UDF that I can call from MySQL. If that's not possible what alternative way could I use to make this happen.
[ "The MySQL 5.0\ndocs say that a trigger can call a\nUDF, so that part seems possible. Reviewing the source code of some UDF extensions would give you a good idea of the complexity involved. You can find open source packages on the MySQL UDF\nrepository.\nI wish I had an easy answer to the \"create a MySQL UDF in ...
[ 7 ]
[]
[]
[ "mysql", "python", "user_defined_functions" ]
stackoverflow_0005772011_mysql_python_user_defined_functions.txt
Q: How to retrieve data from a datastore in Python on Google App Engine via an HTTP response I am sending data to the Google App Engine via the httpRequest get method. This goes perfectly well and gets stored in the datastore. But how to return the result from the Google App Engine via HTTP or is there any other meth...
How to retrieve data from a datastore in Python on Google App Engine via an HTTP response
I am sending data to the Google App Engine via the httpRequest get method. This goes perfectly well and gets stored in the datastore. But how to return the result from the Google App Engine via HTTP or is there any other method for doing the same? Any help will be useful.
[ "Personally, I prefer to using the model to define my Data\nfrom google.appengine.ext import db\n\nclass SomeData(db.model):\n attr1 = db.StringProperty(required=Ture)\n attr2 = db.StringProperty()\n ..........\n\nThen, I could retrieve the data with\ndata = SomeData.get_by_id(id)\n\nFor the routing\nroute...
[ 2, 0 ]
[]
[]
[ "google_app_engine", "http", "python" ]
stackoverflow_0005774448_google_app_engine_http_python.txt
Q: xargs, python, reading files from stdin In a directory with 30 CSV files, running: find . -name "*.csv" | (xargs python ~/script.py) How can I have python properly run on each file passed by xargs? I do print sys.stdin and it's just one file. I try for file in stdin loop, but there's nothing there. What am I mis...
xargs, python, reading files from stdin
In a directory with 30 CSV files, running: find . -name "*.csv" | (xargs python ~/script.py) How can I have python properly run on each file passed by xargs? I do print sys.stdin and it's just one file. I try for file in stdin loop, but there's nothing there. What am I missing?
[ "In fact xargs does not pass to stdin. It passes all its read from stdin as arguments to the command you give it in parameter.\nYou can debug your command invokation with an echo:\nfind . -name \"*.csv\" | (xargs echo python ./script.py)\n\nYou will see all your files outputed on one line.\nSo in fact to access you...
[ 3, 1 ]
[]
[]
[ "python", "xargs" ]
stackoverflow_0005774097_python_xargs.txt
Q: Is this technique acceptable for constructing ParseResults in pyparsing? I feel that ParseActions make my code a bit clunky when trying to construct the resulting parse tree (known as ParseResults in pyparsing). What I'm doing now is to have global variables that store groups of matched tokens that are returned by...
Is this technique acceptable for constructing ParseResults in pyparsing?
I feel that ParseActions make my code a bit clunky when trying to construct the resulting parse tree (known as ParseResults in pyparsing). What I'm doing now is to have global variables that store groups of matched tokens that are returned by the Group element. Then at the end, I will inject the results back into the t...
[ "Have you thought about using setResultsName with listAllMatches=True? Here's a demo:\nfrom pyparsing import *\n\naExpr = Word(\"A\", nums)\nbExpr = Word(\"B\", nums)\ncExpr = Word(\"C\", nums)\n\ngrammar = ZeroOrMore(aExpr.setResultsName(\"A\",listAllMatches=True) |\n bExpr.setResultsName(\"B\...
[ 2 ]
[]
[]
[ "pyparsing", "python" ]
stackoverflow_0005774837_pyparsing_python.txt
Q: How to set icon in gtk.AboutDialog on Windows? I have an about dialog in my Python application and I want to set a custom icon for the dialog. I looked at set_logo_icon_name(), but that doesn't accept an absolute path to an image. What can I do to insert my custom icon? A: Use set_logo() instead. set_logo_icon_n...
How to set icon in gtk.AboutDialog on Windows?
I have an about dialog in my Python application and I want to set a custom icon for the dialog. I looked at set_logo_icon_name(), but that doesn't accept an absolute path to an image. What can I do to insert my custom icon?
[ "Use set_logo() instead. set_logo_icon_name() is for named (i.e., themed) icons. set_logo() takes a gtk.gdk.Pixbuf which you can create from an absolute image path with gtk.gdk.pixbuf_new_from_file().\n" ]
[ 4 ]
[]
[]
[ "about_box", "graphical_logo", "pygtk", "python" ]
stackoverflow_0005774036_about_box_graphical_logo_pygtk_python.txt
Q: How to save and restore all cookies with Selenium RC? I'm running complex tests that create many cookies for different sections of my web site. Occasionally I have to restart the browser in the middle a long test and since the Selenium server doesn't modify the base Firefox profile, the cookies evaporate. Is there...
How to save and restore all cookies with Selenium RC?
I'm running complex tests that create many cookies for different sections of my web site. Occasionally I have to restart the browser in the middle a long test and since the Selenium server doesn't modify the base Firefox profile, the cookies evaporate. Is there any way I can save all of the cookies to a Python variable...
[ "Yes, sure. Look at getCookie, getCookieByName and createCookie methods.\n", "I think you should crate a browser profile and start server for that profile. So all your cookies get saved/modified during every execution. I've gievn these details as answer for another question . Please refer it.. It is given for jav...
[ 0, 0 ]
[]
[]
[ "cookies", "python", "selenium", "selenium_rc" ]
stackoverflow_0003265062_cookies_python_selenium_selenium_rc.txt
Q: What does pycuda.debug actually do? As part of a larger project, I've come across a strangely consistent bug that I can't get my head around, but is an archetypical 'black box' bug; when running with cuda-gdb python -m pycuda.debug prog.py -args, it runs fine, but slow. If i drop pycuda.debug, it breaks. Consisten...
What does pycuda.debug actually do?
As part of a larger project, I've come across a strangely consistent bug that I can't get my head around, but is an archetypical 'black box' bug; when running with cuda-gdb python -m pycuda.debug prog.py -args, it runs fine, but slow. If i drop pycuda.debug, it breaks. Consistently, at exactly the same point in multipl...
[ "Almost nothing. It mostly sets compiler flags in the pycuda.driver module so that CUDA code gets compiled with the necessary debugging symbols and assembled in the way CUDA-gdb requires. The rest is a tiny wrapper that nicely encapsulates the pycuda libraries so thar everything works. The whole thing is about 20 l...
[ 1 ]
[]
[]
[ "cuda", "debugging", "gpgpu", "pycuda", "python" ]
stackoverflow_0005775246_cuda_debugging_gpgpu_pycuda_python.txt
Q: Create a new images with smaller images using PIL I am writing a photomosaic python application. I want to know how to create the final image (.jpg) using multiple smaller images from a pool of images with Python/PIL. I have the order in which I want the various images to be in a 2-dimensional list. A: Documente...
Create a new images with smaller images using PIL
I am writing a photomosaic python application. I want to know how to create the final image (.jpg) using multiple smaller images from a pool of images with Python/PIL. I have the order in which I want the various images to be in a 2-dimensional list.
[ "Documented on the first PIL documenation page (paste() method):\nhttp://effbot.org/imagingbook/image.htm\nIn addition:\nhttp://www.daniweb.com/software-development/python/threads/128112\nhttp://bytes.com/topic/python/answers/22566-overlaying-transparent-images-pil\n" ]
[ 0 ]
[]
[]
[ "image_manipulation", "python", "python_imaging_library" ]
stackoverflow_0005775427_image_manipulation_python_python_imaging_library.txt
Q: lxml findall() problem Just trying to make a simple program to get wikipedia's recentchanges and parse that XML file. I stuck at the point where findall() not working. What I'm doing wrong? import urllib2 from lxml import etree as ET result = urllib2.urlopen('http://en.wikipedia.org/w/api.php?action=query&format=...
lxml findall() problem
Just trying to make a simple program to get wikipedia's recentchanges and parse that XML file. I stuck at the point where findall() not working. What I'm doing wrong? import urllib2 from lxml import etree as ET result = urllib2.urlopen('http://en.wikipedia.org/w/api.php?action=query&format=xml&list=recentchanges&rcpro...
[ "I suspect the root node is the topic node, so it's looking for a node named \"api\" inside of the root node. If so, both of the following will work:\nquery/recentchanges/rc\n\n/api/query/recentchanges/rc\n\n" ]
[ 3 ]
[]
[]
[ "lxml", "mediawiki", "python" ]
stackoverflow_0005775505_lxml_mediawiki_python.txt
Q: What are the arguments against using pystone to estimate overall relative system performance across multiple systems? I'm starting up a distributed computing project, somewhat like the various @home projects out there (though not doing simple scientific computing, but instead occasionally engaging the remote user ...
What are the arguments against using pystone to estimate overall relative system performance across multiple systems?
I'm starting up a distributed computing project, somewhat like the various @home projects out there (though not doing simple scientific computing, but instead occasionally engaging the remote user in tasks involving presentation of audio and visual stimuli) and I need to get a sense of the relative system performance a...
[ "The big problem with Pystone as a benchmark of anything (whether it be Python interpreter versions or the underlying hardware) is that it simply doesn't exercise enough different aspects of the computing environment.\nInteger arithmetic, floating point arithmetic, vector operations, dedicated media hardware, memor...
[ 4 ]
[]
[]
[ "benchmarking", "python" ]
stackoverflow_0005774685_benchmarking_python.txt
Q: Placing vertices of graphs + wxpython I have to draw graphs along with edges according to a file input by the user. I am using wxPython for the same. Once the positions are clear I can easily create circles and edges between the nodes but I have a problem that given a panel to draw on is there any way I can get to...
Placing vertices of graphs + wxpython
I have to draw graphs along with edges according to a file input by the user. I am using wxPython for the same. Once the positions are clear I can easily create circles and edges between the nodes but I have a problem that given a panel to draw on is there any way I can get to know optimum positions for the vertices to...
[ "You want a Graph Drawing algorithm. There is ongoing research in this area, but a simple force-directed algorithm can give good results for small graphs. Look at this wikipedia article for the algorithm. You can also get some open source libraries that handle this problem, like NodeBox and Graphvis.\n", "Also a...
[ 0, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0005760291_python_wxpython.txt
Q: Multiple parameters for the __contains__ function Is it possible to pass the "__ contains __" function in a list more than one parameter? I'd like to check if at least one of the items i have in a list exist in a different list. For example: [0,1,4,8,87,6,4,7,5,'a','f','er','fa','vz'] I'd like to check if the one ...
Multiple parameters for the __contains__ function
Is it possible to pass the "__ contains __" function in a list more than one parameter? I'd like to check if at least one of the items i have in a list exist in a different list. For example: [0,1,4,8,87,6,4,7,5,'a','f','er','fa','vz'] I'd like to check if the one of the items (8,5,'f') are on that list. How can I do i...
[ "AFAIK, __contains__ takes only one argument and it can't be changed. \nHowever you can do following to get the desired result :\n>>> a = [0,1,4,8,87,6,4,7,5,'a','f','er','fa','vz']\n>>> any(map(lambda x: x in a, (8,5,'f')))\nTrue\n\nor \n>>> from functools import partial\n>>> from operator import contains\n>>> f =...
[ 8, 3, 2 ]
[]
[]
[ "contains", "python" ]
stackoverflow_0005776548_contains_python.txt
Q: Dynamic change in Configuration to reflect in user defined Data structures In my program, I read a "configuration file" and from that I initialize many classes. I need a way so that Dynamic changes in the configuration file, can successfully update all the classes. What is the best way this can be achived in Pytho...
Dynamic change in Configuration to reflect in user defined Data structures
In my program, I read a "configuration file" and from that I initialize many classes. I need a way so that Dynamic changes in the configuration file, can successfully update all the classes. What is the best way this can be achived in Python ? As an example: The /etc/passwd file consists of Username:Password:User ID:...
[ "You can watch the changes to the file using e.g. pyinotify (Linux) or watchdog (cross-platform). Once the change is detected, you can update your data structures.\nUpdating username (or other \"derived\" information stored elsewhere) is better done by storing (and using) not it but some invariants that never chang...
[ 0 ]
[]
[]
[ "configuration", "initialization", "python" ]
stackoverflow_0005776969_configuration_initialization_python.txt
Q: Determine location of laptop based on WiFi Say, I want to determine the location of the local machine 192.168.1.2 connected on my network. I want to find the "relative"/"absolute" ( any would do, relative is better though) of the laptop. Is there a way to do it? WiFi based location searching (the most common answ...
Determine location of laptop based on WiFi
Say, I want to determine the location of the local machine 192.168.1.2 connected on my network. I want to find the "relative"/"absolute" ( any would do, relative is better though) of the laptop. Is there a way to do it? WiFi based location searching (the most common answer that popped up when I searched for this) is b...
[ "You need to use an external service, e.g. from Google.\nHave a look at http://samy.pl/androidmap/ - when feeding the MAC address / BSSID of a nearby wireless LAN access point, it is likely to give you a pretty exact location (for my home's wireless lan it even has the correct address + house number).\nHowever, fin...
[ 3 ]
[]
[]
[ "geolocation", "location", "network_programming", "networking", "python" ]
stackoverflow_0005777258_geolocation_location_network_programming_networking_python.txt
Q: What's wrong with this query? I'm trying to execute the following in my function but I'm getting an error You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '/ (SELECT COUNT(1) FROM users WHERE registered_at BETWEEN '1293861600' AND...
What's wrong with this query?
I'm trying to execute the following in my function but I'm getting an error You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '/ (SELECT COUNT(1) FROM users WHERE registered_at BETWEEN '1293861600' AND '1303' at line 1") I'm basically t...
[ "You probably need to prepend SELECT to your query.\n", "cursor.execute( \"SELECT COUNT(1) \"\n \" / ( SELECT COUNT(1) FROM users \" \n \" WHERE registered_at BETWEEN '1293861600' AND '1303729537') \" \n \" FROM users \"\n \" WHERE ( registered_at BE...
[ 2, 1, 1, 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0005777381_mysql_python.txt
Q: Vectorizing an indexing operation in numpy What is the best way to vectorize the following code in numpy? from numpy import * A = zeros(5, dtype='int') I = [1, 1, 1, 3] J = [2, 1, 1, 1] for i, j in zip(I, J): A[i] += j print A The result should be: [0 4 0 1 0] Here A is the original array, I stores the in...
Vectorizing an indexing operation in numpy
What is the best way to vectorize the following code in numpy? from numpy import * A = zeros(5, dtype='int') I = [1, 1, 1, 3] J = [2, 1, 1, 1] for i, j in zip(I, J): A[i] += j print A The result should be: [0 4 0 1 0] Here A is the original array, I stores the index at which we want to increment by the corresp...
[ "You can use numpy.bincount():\nA = numpy.zeros(5, dtype='int')\nI = [1, 1, 1, 3]\nJ = [2, 1, 1, 1]\nsums = numpy.bincount(I, J)\nA[:len(sums)] += sums\nprint(A)\n\nprints\n[0 4 0 1 0]\n\n", "In principle you can do it with numpy's bincount and unique, but I'd guess it'll only make the code much less readable wit...
[ 3, 2 ]
[]
[]
[ "indexing", "numpy", "python" ]
stackoverflow_0005776699_indexing_numpy_python.txt
Q: Mapping a 3-dimensional coordinate to a 1-dimensional index I have a 3-dimensional coordinate. I'd like to map it to a 1-dimensional index. As I understand, one can use a pairing function to handle this in the 2-dimensional case. However, I've come up with the following naive implementation for the 3D case: from n...
Mapping a 3-dimensional coordinate to a 1-dimensional index
I have a 3-dimensional coordinate. I'd like to map it to a 1-dimensional index. As I understand, one can use a pairing function to handle this in the 2-dimensional case. However, I've come up with the following naive implementation for the 3D case: from numpy import * # the size of the coordinate space xn = 100 yn = 1...
[ "You can implement a function ravel_index() for NumPy arrays of arbitrary dimension:\ndef ravel_index(x, dims):\n i = 0\n for dim, j in zip(dims, x):\n i *= dim\n i += j\n return i\n\nThis function is the inverse of the function numpy.unravel_index().\nFor your application, you can call this ...
[ 2, 2, 1 ]
[]
[]
[ "coordinates", "numpy", "python" ]
stackoverflow_0005777058_coordinates_numpy_python.txt
Q: PyQt QSpinBox update range depending on the value of other spinbox i am using pyqt4 to develop a GUI for the first time; I have a spinbox, and I would like the range of values allowed in it to be dependant on the value another spinbox. for example, the maximum value allowed in the first spinbox should be equal to...
PyQt QSpinBox update range depending on the value of other spinbox
i am using pyqt4 to develop a GUI for the first time; I have a spinbox, and I would like the range of values allowed in it to be dependant on the value another spinbox. for example, the maximum value allowed in the first spinbox should be equal to the value of the second spinbox. I thought this may be possible using ...
[ "You have not shown your code where you make the connection between the 'valueChanged' signal of spinbox2 with the function. Are you making that connection ?. Also the code you have given for function seems to be incomplete. \nYou can try something like this:\nspinbbox2.valueChanged.connect(handler)\n# Or this whic...
[ 4 ]
[]
[]
[ "pyqt", "pyqt4", "python" ]
stackoverflow_0005777885_pyqt_pyqt4_python.txt
Q: How to translate an unprintable string to a normal string in python? I have a string (that originally is taken from a search result of a search engine) that contains special characters such as '\xe9' and I just want to replace those characters to normal characters so that I could print them (it's a python program)...
How to translate an unprintable string to a normal string in python?
I have a string (that originally is taken from a search result of a search engine) that contains special characters such as '\xe9' and I just want to replace those characters to normal characters so that I could print them (it's a python program). So how do I do it? It keeps writing me this error: " File "D:\Python27\l...
[ "It appears that you are on a Windows machine, in a Hebrew locale, with the default encoding being cp1255 which uses the hi-bit-set characters to support the Hebrew script, not Western European characters like u'\\xe9' which is LATIN SMALL LETTER E WITH ACUTE.\nYou should be able to do \nprint u'\\xe9'\n\nin IDLE a...
[ 1, 1 ]
[]
[]
[ "character", "python" ]
stackoverflow_0005777502_character_python.txt
Q: Mac OS X pygame input goes to Terminal instead of Python I'm having trouble running a pygame based app on Mac OS X via Terminal. Input events such as keystrokes go to the Terminal instead of my Python app, and are detected by pygame. For example, I have the following test script: import pygame pygame.init() scre...
Mac OS X pygame input goes to Terminal instead of Python
I'm having trouble running a pygame based app on Mac OS X via Terminal. Input events such as keystrokes go to the Terminal instead of my Python app, and are detected by pygame. For example, I have the following test script: import pygame pygame.init() screen = pygame.display.set_mode((640, 480)) done = False while n...
[ "The default py-game on Mac Ports has the problem you describe. A work-around is to install the py-game2.6 target instead. This works for me with OS X 10.6.7.\n", "Can you check if the pygame.K_* constants actually correspond to the correct values for your keyboard? For the record I tried your code in Linux on a...
[ 2, 1 ]
[]
[]
[ "macos", "pygame", "python", "terminal" ]
stackoverflow_0002718897_macos_pygame_python_terminal.txt
Q: simple example aes256 crypt Why this example doesn't work ? from Crypto.Cipher import AES x = AES.new("sdsfdsafsadfdsafasdfdsarwe876539", AES.MODE_CBC, "2324234342342342") print x.decrypt(x.encrypt('abcdfghkbhgjrdfs')) A: Because x is an object with state. Using it to encrypt a string changes the state; using i...
simple example aes256 crypt
Why this example doesn't work ? from Crypto.Cipher import AES x = AES.new("sdsfdsafsadfdsafasdfdsarwe876539", AES.MODE_CBC, "2324234342342342") print x.decrypt(x.encrypt('abcdfghkbhgjrdfs'))
[ "Because x is an object with state. Using it to encrypt a string changes the state; using it again will generate different output.\nUse a new AES cipher with the same initial state as you had when encrypting:\n>>> from Crypto.Cipher import AES\n>>> key= \"sdsfdsafsadfdsafasdfdsarwe876539\"\n>>> prefix= '23242343423...
[ 7 ]
[]
[]
[ "encryption", "python" ]
stackoverflow_0005778304_encryption_python.txt
Q: sorted key= does not apply to sublists I'm writing a unit tests, one of them checks a method that returns a list containing sub lists [[],[],[]], the order of the sublists does not matter only the quantity of sublists and their values, the problem is that TestCase.assertItemsEqual() is deprecated and there is no T...
sorted key= does not apply to sublists
I'm writing a unit tests, one of them checks a method that returns a list containing sub lists [[],[],[]], the order of the sublists does not matter only the quantity of sublists and their values, the problem is that TestCase.assertItemsEqual() is deprecated and there is no TestCase.assertElementsEqual() method. To sol...
[ "In Python 3 heterogeneous comparisons no longer \"just work\". I think that the rationale for this change was that they return potentially unexpected results. Also: we can no longer specify a cmp function for customized sorting. So I think that you were on the right track trying to replace the None values.\nYou ca...
[ 0, 0 ]
[]
[]
[ "python", "python_3.x", "sorting" ]
stackoverflow_0005696206_python_python_3.x_sorting.txt
Q: python scraping by getting urls dynamic way I am new to the world of data scraping,previously used python for web and desktop app development. I am just wondering,if there is any way to get the urls from a page then look into it for specific information like,phone no,address etc. Currently I am using BeautifulSoup...
python scraping by getting urls dynamic way
I am new to the world of data scraping,previously used python for web and desktop app development. I am just wondering,if there is any way to get the urls from a page then look into it for specific information like,phone no,address etc. Currently I am using BeautifulSoup and built method where I am telling the urls as ...
[ "You can use Scrapy. It simplifies both crawling and parsing (it uses libxml2 for parsing by default).\n", "Use a more efficient HTML parser, like lxml. See here for performance comparisons of various Python parsers. \n" ]
[ 3, 0 ]
[]
[]
[ "python", "web_crawler", "web_scraping" ]
stackoverflow_0005754922_python_web_crawler_web_scraping.txt
Q: Defining a function that counts relative frequency of Amino Acids I'm trying to calculate codon frequency within a given sequence of DNA. For example: sequence = 'ATGAAGAAA' codons = ['ATG', 'AAG', 'AAA'] for XX in codons: frequency = codons.count(XX)/(codons.count(XX)+codons.count(XX2)+codons.count(XX3)) Note ...
Defining a function that counts relative frequency of Amino Acids
I'm trying to calculate codon frequency within a given sequence of DNA. For example: sequence = 'ATGAAGAAA' codons = ['ATG', 'AAG', 'AAA'] for XX in codons: frequency = codons.count(XX)/(codons.count(XX)+codons.count(XX2)+codons.count(XX3)) Note that XX2 and XX3 will not always be in the sequence. Some codons may or...
[ "use defaultdict\nfrom collections import defaultdict\n\nmydict = defaultdict(int)\n\nfor aa in mysecuence:\n mydict[aa] +=1\n\nThis works for aminoacids (proteins).\nFor codons, you should iterate on the sequence in 3 positions steps to get the keys of the defaultdict. For example:\n>>> mysec = \"GAUCACTUGCCA\"...
[ 6, 2, 1, 1, 0 ]
[]
[]
[ "bioinformatics", "python" ]
stackoverflow_0005774099_bioinformatics_python.txt
Q: How can I get all html following a searched item using BeautifulSoup in Python? I am trying to return all of the html after a search text string using BeautifulSoup in Python. Here is my code: html = '<html>table1<table><tr>text1<td>text2</td></tr></table>table2<table><tr>text3<td>text4</td></tr></table></html>' ...
How can I get all html following a searched item using BeautifulSoup in Python?
I am trying to return all of the html after a search text string using BeautifulSoup in Python. Here is my code: html = '<html>table1<table><tr>text1<td>text2</td></tr></table>table2<table><tr>text3<td>text4</td></tr></table></html>' soup = BeautifulSoup(''.join(html)) foundtext = soup.find(text='text1') soup2 = found...
[ "The following code will print out the nodes after the first occurence of text1\nfrom BeautifulSoup import BeautifulSoup, NavigableString\n\nhtml = '<html>table1<table><tr>text1<td>text2</td></tr></table>table2<table><tr>text3<td>text4</td></tr></table></html>'\nsoup = BeautifulSoup(html)\n\nfound = False\nfor node...
[ 2, 0 ]
[]
[]
[ "beautifulsoup", "html", "python" ]
stackoverflow_0005778694_beautifulsoup_html_python.txt
Q: python: can i access the index of the element when i use map()? In python we can use map(lambda word: someFunction(element), data) but can i access the index to tell which element is being accessed? map(lambda word: someFunction(word,indexOfcurrentelement), data) A: You can if you enumerate first. map(lambda (i...
python: can i access the index of the element when i use map()?
In python we can use map(lambda word: someFunction(element), data) but can i access the index to tell which element is being accessed? map(lambda word: someFunction(word,indexOfcurrentelement), data)
[ "You can if you enumerate first.\nmap(lambda (index, word): someFunction(word, index), enumerate(data))\n\n", "If you don't want to use \"lambda\" here is one way:\nx=[50,100,150]\n\nindex = []\n\nfor i in x:\n indexis=x.index(i)\n index = index+[indexis]\n\nfor a, b in zip(index, x):\n print (a,b)\n\n",...
[ 4, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005775144_python.txt
Q: Why is ordered choice in pyparsing failing for my use case? >>> g = MatchFirst( Literal("scoobydoo"), Literal("scooby") ) >>> g.parseString( "scooby" ) pyparsing.ParseException: Expected "scoobydoo" (at char 0), (line:1, col:1) Is the ParseException thrown because the scooby has already been consumed in the chara...
Why is ordered choice in pyparsing failing for my use case?
>>> g = MatchFirst( Literal("scoobydoo"), Literal("scooby") ) >>> g.parseString( "scooby" ) pyparsing.ParseException: Expected "scoobydoo" (at char 0), (line:1, col:1) Is the ParseException thrown because the scooby has already been consumed in the character stream & thus the parser cannot backtrack ? I'm looking for ...
[ "MatchFirst (or '|') does short-circuiting by design. To force all alternatives to be checked, use Or (or '^'). oneOf(\"scooby scoobydoo\") will also work, since oneOf will short-circuit, but only after rearranging alternative words that have leading overlaps.\n" ]
[ 2 ]
[]
[]
[ "pyparsing", "python" ]
stackoverflow_0005777727_pyparsing_python.txt
Q: Error from collections module in Python I am getting the following errror when a python program is run File "/home/user/Desktop/important/paper/ordereddict.py", line 1, in from collections import MutableMapping ImportError: cannot import name MutableMapping When I tried import collections it works f...
Error from collections module in Python
I am getting the following errror when a python program is run File "/home/user/Desktop/important/paper/ordereddict.py", line 1, in from collections import MutableMapping ImportError: cannot import name MutableMapping When I tried import collections it works fine. Please help. I am using version Python 2...
[ "collections.MutableMapping was introduced only in Python 2.6, so you need at least that version of Python to use your ordereddict module.\n", "You have to use Python 2.6 to use MutableMapping\n" ]
[ 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005778973_python.txt
Q: Using live_settings in python shell I have 2 settings file (settings.py for my localserver) and (live_settings.py for my live_server). Starting the shell using python manage.py shell in cmd When i start the shell in my command prompt it takes settings.py by default, how can i set it to live_settings.py and then st...
Using live_settings in python shell
I have 2 settings file (settings.py for my localserver) and (live_settings.py for my live_server). Starting the shell using python manage.py shell in cmd When i start the shell in my command prompt it takes settings.py by default, how can i set it to live_settings.py and then start the python shell.
[ "You could start a normal shell (i.e. just typing python in your projct directory rather than using the manage.py helper). and manually set it up with your Django config like so\nimport live_settings\nfrom django.core.management import setup_environ\nsetup_environ(live_settings)\n\nThis worked for me. I've not use...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005778812_django_python.txt
Q: While using two threads in Python when an error occurs the program does nothing, why? I'm making a simple server for my game in Python and I'm using two threads. One thread is looking for new users that wish to connect (for it shall be a MMORPG!) and the other is communicating with users. My problem is this: I ca...
While using two threads in Python when an error occurs the program does nothing, why?
I'm making a simple server for my game in Python and I'm using two threads. One thread is looking for new users that wish to connect (for it shall be a MMORPG!) and the other is communicating with users. My problem is this: I can't debug! Or at least, it's very hard because when an error occurs nothing happens! Lets s...
[ "I'm not sure about the reason of your problem, but I think you can solve with this:\nimport sys\n...\nprint >> sys.stderr, 'whatever you want to print'\n\nI use a function for this Debug information with coloured output (DEBUG is a global variable):\ndef debug(self, *txt):\n if DEBUG:\n print >> sys.stde...
[ 0 ]
[]
[]
[ "multithreading", "pygame", "python" ]
stackoverflow_0005778849_multithreading_pygame_python.txt
Q: delete everything from output which is behind ":" when python gives me an output in form like: randomfilename.txt:randomstringmniaonovinaio How can i make from it just randomfilename.txt in python/shell? A: >>> 'randomfilename.txt:randomstringmniaonovinaio'.split(':')[0] 'randomfilename.txt' A: >>> s = "rand...
delete everything from output which is behind ":"
when python gives me an output in form like: randomfilename.txt:randomstringmniaonovinaio How can i make from it just randomfilename.txt in python/shell?
[ ">>> 'randomfilename.txt:randomstringmniaonovinaio'.split(':')[0]\n'randomfilename.txt'\n\n", ">>> s = \"randomfilename.txt:dslfkjsdosdfu\"\n>>> print s.split(\":\")[0]\nrandomfilename.txt\n\n", "In the shell you can use cut:\npython yourscript.py | cut --delim=\":\" -f 1\n\nOnly the string before the first : w...
[ 2, 2, 1, 0, 0 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0005778573_linux_python.txt
Q: Reading and Writing to Kernel Space using inpout32 Below is code I am using with python. Note that inpout32.dll which can be found here is present in the same directory. import ctypes ctypes.windll.inpout32.Out32(0x300, 40) print ctypes.windll.inpout32.Inp32(0x300) The code should input 40 in the addr...
Reading and Writing to Kernel Space using inpout32
Below is code I am using with python. Note that inpout32.dll which can be found here is present in the same directory. import ctypes ctypes.windll.inpout32.Out32(0x300, 40) print ctypes.windll.inpout32.Inp32(0x300) The code should input 40 in the address of 300, however when I try to read the value at addr...
[ "What model are you using? http://www.opal-rt.com/kb-article/pc104-ios-do-not-work a quick google search shows that some cards reserve 0x300, and that this is a common source of such problems. Seems like you might be using the wrong base address.\n" ]
[ 0 ]
[]
[]
[ "hardware", "io", "kernel", "python" ]
stackoverflow_0005475685_hardware_io_kernel_python.txt
Q: Is there a way of drawing a caption box in matplotlib Is there a function for drawing a caption box underneath a figure/graph using matplotlib? I have searched google and haven't found any such function. something like what is shown in the image would be great. A: Use pyplot.text. Here is some sample code: fro...
Is there a way of drawing a caption box in matplotlib
Is there a function for drawing a caption box underneath a figure/graph using matplotlib? I have searched google and haven't found any such function. something like what is shown in the image would be great.
[ "Use pyplot.text. Here is some sample code:\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\nx = np.arange(0,3,.25)\ny = np.sin(x)\ntxt = '''\n Lorem ipsum dolor sit amet, consectetur adipisicing elit,\n sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\n Ut enim ad minim veni...
[ 36, 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0005777576_matplotlib_python.txt
Q: Sort on multiple NumPy arrays I am creating a 2 dimensional numpy array that contains stock returns. I want to sum the return every 2 days, and if the sum is in the top two, I will set every element in a similar shaped array to True. For example, returns below is the daily returns for four different stocks. ret...
Sort on multiple NumPy arrays
I am creating a 2 dimensional numpy array that contains stock returns. I want to sum the return every 2 days, and if the sum is in the top two, I will set every element in a similar shaped array to True. For example, returns below is the daily returns for four different stocks. returns=np.array([ [0, 0, 4, 8],...
[ "You can use numpy.lexsort() to get the indices that sort your arrays using prices as primary key and names as secondary key. Applying advanced indexing using these indices yields the sorted arrays:\ncol_indices = numpy.lexsort((names, prices))\nrow_indices = numpy.arange(len(names))[:, None]\nprint(prices[row_ind...
[ 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0005779754_numpy_python.txt
Q: Read/Write files in Python I need to make a file readable and writable in python. Currently the file is read-only. I am running on a Windows machine. I run the following code: os.chmod(projectPath, stat.S_IWRITE | stat.S_IREAD) on a file that needs to be read/write. But when I try to execute the file that needs ...
Read/Write files in Python
I need to make a file readable and writable in python. Currently the file is read-only. I am running on a Windows machine. I run the following code: os.chmod(projectPath, stat.S_IWRITE | stat.S_IREAD) on a file that needs to be read/write. But when I try to execute the file that needs to be read write, I get the fo...
[ "I think you only need the stat.S_IWRITE mode.\nI just ran a test with this code \ndef main():\n path = \"C:\\\\temp\\\\log.txt\"\n os.chmod(path, stat.S_IWRITE)\n\nAnd it set a file that was read only to not read only, where as when I ran it with S_IREAD instead, it set it back to read only\n", "Make sure ...
[ 6, 0 ]
[]
[]
[ "file", "file_io", "permissions", "python" ]
stackoverflow_0005779989_file_file_io_permissions_python.txt
Q: Module `operator` in python has no `rfloordiv`? Suppose I have s class, that has members op, left, right (this is related question to How to assign an operation like sum or substitute, etc., to a variable ). So, in op I store an operator, for example - operator.add, operator.radd, etc. But I want to store operator...
Module `operator` in python has no `rfloordiv`?
Suppose I have s class, that has members op, left, right (this is related question to How to assign an operation like sum or substitute, etc., to a variable ). So, in op I store an operator, for example - operator.add, operator.radd, etc. But I want to store operator.rfloordiv and there's no such member in this class? ...
[ "Most magic operator methods come in two flavours: the plain variant and the variant prefixed with r (example __add__() and __radd()__). If you try to add the objects a of type A and b of type B, Python first calls A.__add__(a, b). If this returns the special value NotImplemented, B.__radd__(b, a) is called.\nBot...
[ 4 ]
[]
[]
[ "operator_overloading", "python" ]
stackoverflow_0005780128_operator_overloading_python.txt
Q: Simple way to decrease values without making a new attribute? I'm making a program where you're firing a 'blaster', and I have 5 ammo. I'm blasting an alien who has 5 health. At the end I instantiate the player and make him blast 6 times to check that the program works correctly. But the way I've done it makes it ...
Simple way to decrease values without making a new attribute?
I'm making a program where you're firing a 'blaster', and I have 5 ammo. I'm blasting an alien who has 5 health. At the end I instantiate the player and make him blast 6 times to check that the program works correctly. But the way I've done it makes it so that the amount won't decrease. Is there an easy fix to this, or...
[ "Think about it: the amount of ammunition available is part of a player's state. An object's state is best represented as instance variables of that object. So you should not have ammo as an argument to blast -- it should be self.ammo in that method, initialized to 5 or whatever in the __init__ you forgot to code...
[ 6, 3, 1, 0, 0 ]
[]
[]
[ "attributes", "instantiation", "python" ]
stackoverflow_0002582863_attributes_instantiation_python.txt
Q: Where can I get a template website? I want to benchmark the performance of a template website on a modified kernel. I want to use a website template that has 2-3 tiers (frontend, database etc), logic to create users and some logic to store/modify data for each user. A quick search did not reveal any useful results...
Where can I get a template website?
I want to benchmark the performance of a template website on a modified kernel. I want to use a website template that has 2-3 tiers (frontend, database etc), logic to create users and some logic to store/modify data for each user. A quick search did not reveal any useful results as of yet. I've little experience in web...
[ "You could simply download and run one of the sample django applications like: \nhttp://code.google.com/p/django-voting/\nor \nhttps://github.com/scrum8/django-job-board/\nOr you could just create a clean django project and turn on the admin console. \n", "I would suggest taking a look at the Django framework: ...
[ 1, 1 ]
[]
[]
[ "python", "web" ]
stackoverflow_0005780231_python_web.txt
Q: marking up mutation positions in a sequence with html in python I was wondering if there are any methods in python or biopython that allows one to markup a sequence in html. I would like to mark positions on a sequence (ie colour bases differently) according to if that position is a known snp/indel etc Having a l...
marking up mutation positions in a sequence with html in python
I was wondering if there are any methods in python or biopython that allows one to markup a sequence in html. I would like to mark positions on a sequence (ie colour bases differently) according to if that position is a known snp/indel etc Having a list of mutation positions in an array (read from a database) eg mutat...
[ "If you wanted to make your mutations green and you had a list of mutations (0 indexed):\n>>> seq = \"ACGTACGT\"\n>>> muts = [0,1,5]\n>>> mark_up = \"<span style='color:green;'>%s</span>\"\n\n# use list comprehension to add mark up to muts\n>>> marked_up_seq = [ mark_up % seq[x] if x in muts else seq[x] for x in ra...
[ 2, 0 ]
[]
[]
[ "bioinformatics", "biopython", "python" ]
stackoverflow_0005390170_bioinformatics_biopython_python.txt
Q: Using Mako with Pyramid causes an error When trying to use Mako with the Pyramid framework, by going into the development.ini file, and adding the line mako.directories = TestProject:templates in: [app:TestProject] and then creating a simple html file called template.mako in the templates subdirectory I get an...
Using Mako with Pyramid causes an error
When trying to use Mako with the Pyramid framework, by going into the development.ini file, and adding the line mako.directories = TestProject:templates in: [app:TestProject] and then creating a simple html file called template.mako in the templates subdirectory I get an: ImportError: No module named TestProject B...
[ "As summary:\nEdit the file development.ini and add in the section [app:MyProject]:\n\nmako.directories = myproject:templates\n\nNow we can open the file /MyProject/myproject/__init__.py and add a line like:\n\nconfig.add_route('foo', '/foo', view='myproject.views.foo', view_renderer='foo.mako')\n\nThis will render...
[ 9, 3 ]
[]
[]
[ "mako", "pylons", "pyramid", "python" ]
stackoverflow_0005059820_mako_pylons_pyramid_python.txt
Q: Create new instance of class with metaclass in python I would like to create dynamically a new instance of a class with a specific metaclass in python. I've tried this : type('A', (object, metaclass=tmp, ), {}) but doesn't work :( Does anybody know how I could achieve this? A: A metaclass is typically a subcla...
Create new instance of class with metaclass in python
I would like to create dynamically a new instance of a class with a specific metaclass in python. I've tried this : type('A', (object, metaclass=tmp, ), {}) but doesn't work :( Does anybody know how I could achieve this?
[ "A metaclass is typically a subclass of type, (or perhaps rarely a function taking name, bases, clsdict as arguments), so you should be able to use it like type. If tmp is your metaclass, then try:\ntmp('A',(object,),{})\n\n" ]
[ 6 ]
[]
[]
[ "metaclass", "python" ]
stackoverflow_0005780876_metaclass_python.txt
Q: Simple Python concatenation question If I type the following into IDLE, it gives me the result of 'wordwordword': print("word" * 3) If I go through the following steps in IDLE, it gives me the same result: sentence = input() #I type "word" number = int(input()) #I type it to int because input() saves as a string,...
Simple Python concatenation question
If I type the following into IDLE, it gives me the result of 'wordwordword': print("word" * 3) If I go through the following steps in IDLE, it gives me the same result: sentence = input() #I type "word" number = int(input()) #I type it to int because input() saves as a string, I type "3" print(sentence * number) But ...
[ "You code works well in python 3.\nWith python 2, just replace input by raw_input() like that :\nsentence = raw_input()\nnumber = int(raw_input())\nprint(sentence * number)\n\nYou can read the PEP 3111 to understand the difference and the motivation between input and raw_input in python2 and python3.\n", "I'd try...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005780987_python.txt
Q: How do I override PySerial's "__del__" method in Python? I have a simple Python script set up to send Characters to a device on COM3. (This is running on Windows XP) The device receives the Characters fine, but when the script ends, or I call ser.close() #ser is an instance of the `serial` method `Serial` It...
How do I override PySerial's "__del__" method in Python?
I have a simple Python script set up to send Characters to a device on COM3. (This is running on Windows XP) The device receives the Characters fine, but when the script ends, or I call ser.close() #ser is an instance of the `serial` method `Serial` It sets the DTR Line on the serial port High, Resetting my Devic...
[ "Sure, go ahead and override it. You can either create a subclass of Serial and specify a do-nothing __del__() method and use the subclass instead of Serial, or delete that method from the actual Serial class (monkey-patching) using the del statement. The former method is preferred but the second may be necessary i...
[ 3, 2 ]
[]
[]
[ "overriding", "pyserial", "python", "serial_port" ]
stackoverflow_0005780830_overriding_pyserial_python_serial_port.txt
Q: Cucumber Regex: How do I match a repeating pattern of comma separated value pairs? I have the following strings: I submit the following values: username 'foo', password 'bar' I submit the following values: username 'foo', password 'bar','foo', profile 'bar', extra 'something' I am trying to match the value pairs ...
Cucumber Regex: How do I match a repeating pattern of comma separated value pairs?
I have the following strings: I submit the following values: username 'foo', password 'bar' I submit the following values: username 'foo', password 'bar','foo', profile 'bar', extra 'something' I am trying to match the value pairs but I am not sure how I can repeat a pattern. So the result I want is: username 'foo' ...
[ "If you need to be able to parse an arbitrary number of pairs, then I'd suggest using a table, e.g.:\nWhen I submit the following values:\n | username | foo |\n | password | bar |\n\nThere's a rows_hash method on Cucumber::Ast::Table that will give you what you need.\nHowever, I suspect that using a 'one-size-fit...
[ 2, 0, 0 ]
[]
[]
[ "bdd", "cucumber", "python", "regex" ]
stackoverflow_0005743569_bdd_cucumber_python_regex.txt
Q: How do I add a string of numbers in python For instance if I have the string entered 345. I want them to be added 3 + 4 + 5. I've seen this here before just can't seem to find it again. Thanks! A: Maybe it's my Scheme getting to me, but I'd use map here. map(int, s) says "take this sequence but with all its elem...
How do I add a string of numbers in python
For instance if I have the string entered 345. I want them to be added 3 + 4 + 5. I've seen this here before just can't seem to find it again. Thanks!
[ "Maybe it's my Scheme getting to me, but I'd use map here. map(int, s) says \"take this sequence but with all its elements as integers\". That is, it's the same as [int(x) for x in s], but faster to read/type.\n>>> x = \"345\"\n>>> sum(map(int, x))\n12\n\n", "s = raw_input()\nprint sum(int(c) for c in s.strip())\...
[ 12, 6, 6, 1 ]
[ "What unutbu said plus, if the number is an int, not a string:\nnum = 345 \nsum([int(x) for x in str(num)])\n\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0005781043_python.txt
Q: Django: reuse code for redirection on missing object I have a site whose URLs look like http://www.example.com/NY-2010/ http://www.example.com/NY-2010/location/ http://www.example.com/NY-2010/something-else/ http://www.example.com/Washington-2009/ http://www.example.com/Washington-2009/location/ http://www.exampl...
Django: reuse code for redirection on missing object
I have a site whose URLs look like http://www.example.com/NY-2010/ http://www.example.com/NY-2010/location/ http://www.example.com/NY-2010/something-else/ http://www.example.com/Washington-2009/ http://www.example.com/Washington-2009/location/ http://www.example.com/Washington-2009/something-else/ and so on. There ar...
[ "I think the simplest way to do this would be to create new utility function called get_object_or_redirect in the same vein as get_object_or_404. You could probably even copy the contents of get_object_or_404 from django.shortcuts as a starting point for your implementation, or just extract out what you have above...
[ 1, 1 ]
[]
[]
[ "django", "django_views", "python" ]
stackoverflow_0005780811_django_django_views_python.txt
Q: Charts in django Web Applications I want to Embed a chart in a Web Application developed using django. I have come across Google charts API, ReportLab, PyChart, MatPlotLib and ChartDirector I want to do it in the server side rather than send the AJAX request to Google chart APIs, as I also want to embed the chart ...
Charts in django Web Applications
I want to Embed a chart in a Web Application developed using django. I have come across Google charts API, ReportLab, PyChart, MatPlotLib and ChartDirector I want to do it in the server side rather than send the AJAX request to Google chart APIs, as I also want to embed the chart into the PDF. Which is the best option ...
[ "Another choice is CairoPlot.\nWe picked matplotlib over the others for some serious graphing inside one of our django apps, primarily because it was the only one that gave us exactly the kind of control we needed.\nPerformance generating PNG's was fine for us but... it was a highly specialized app with less than 1...
[ 8, 5, 3, 3, 1, 1, 0 ]
[]
[]
[ "charts", "django", "python" ]
stackoverflow_0000609944_charts_django_python.txt
Q: Problem uploading file using python and Urllib2 import os import sys import time import base64 import hmac import mimetypes import urllib2 from hashlib import sha1 from poster.streaminghttp import register_openers def read_data(file_object): while True: r = file_object.read(1 * 1024) print 'rr...
Problem uploading file using python and Urllib2
import os import sys import time import base64 import hmac import mimetypes import urllib2 from hashlib import sha1 from poster.streaminghttp import register_openers def read_data(file_object): while True: r = file_object.read(1 * 1024) print 'rrr',r if not r: print 'r' ...
[ "Use strace or a network sniffer like Wireshark for hunting the problem down.\n", "One showstopper may be your arguments populating the urllib2.Request \nrequest = urllib2.Request(bucket, data=data)\n\nThe first argument should be a valid URL. From your shared code it doesn't appeared bucket has been populated w...
[ 0, 0 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0005779465_python_urllib2.txt
Q: How does CreateProcess locate the executable? According to the docs, CreateProcess can be passed an executable name as first argument, or a command line as a second argument (from which the executable name will be extracted). If you pass an executable name, the docs say PATH won't be searched. if you pass a comman...
How does CreateProcess locate the executable?
According to the docs, CreateProcess can be passed an executable name as first argument, or a command line as a second argument (from which the executable name will be extracted). If you pass an executable name, the docs say PATH won't be searched. if you pass a command line instead, the first token is extracted to be ...
[ "You need to modify the environment of the current process if you want CreateProcess to see it. Currently, the subshell (whether included in the command line or requested via shell=True) is seeing your modified environment, but the direct invocation of CreateProcess is not.\n", "If I'm reading your question right...
[ 3, 0 ]
[ "Thought of checking MSDN? CreateProcess documentation.\nTo quote one part of it:\n\nThe directory from which the application loaded.\n The current directory for the parent process.\n The 32-bit Windows system directory. Use the GetSystemDirectory function to get the path of this directory.\n The 16-bit Windows ...
[ -1 ]
[ "python", "subprocess", "winapi" ]
stackoverflow_0005776789_python_subprocess_winapi.txt
Q: Matrix problem Python For example if I have matrix: x=[['1', '7', 'U1'], ['1.5', '8', 'U1'], ['2', '5.5', 'U2']] How can I take all data from x, except the last one. Then I need to sum this elements. This is what I need: sum=1+7+1.5+8+2+5.5= ?? Thanks EDIT2: I try: > x=[['1', '7', 'U1'], ['1.5', '8', > 'U1'], ...
Matrix problem Python
For example if I have matrix: x=[['1', '7', 'U1'], ['1.5', '8', 'U1'], ['2', '5.5', 'U2']] How can I take all data from x, except the last one. Then I need to sum this elements. This is what I need: sum=1+7+1.5+8+2+5.5= ?? Thanks EDIT2: I try: > x=[['1', '7', 'U1'], ['1.5', '8', > 'U1'], ['2', '5.5', 'U2']] > > s...
[ "You can take all elements apart from the last one indexing with [:-1].\nTo take that sum, try sum(sum(float(el) for el in els[:-1]) for els in x).\nIf you actually have strings in the list, you might need to cast the elements. Also, if there are always 3 elements, this could be a bit faster:\nsum(float(a) + float(...
[ 9 ]
[]
[]
[ "python", "sum" ]
stackoverflow_0005781294_python_sum.txt
Q: How to use database connection in threads? I want to use standard database connections in threads. Is it thread-safe? A: Depends on the particular database implementation you are using. If the module conforms to the Python Database API Specification v2.0, it should have the threadsafety global that will let you ...
How to use database connection in threads?
I want to use standard database connections in threads. Is it thread-safe?
[ "Depends on the particular database implementation you are using. If the module conforms to the Python Database API Specification v2.0, it should have the threadsafety global that will let you know what can be shared between processes and what not. I guess if it is not 0, you can multi-thread at least some of your ...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0005781290_python.txt
Q: Create Rank of tuples in python How do i do this? starting with this sample Id, Id2 CCC [ (A123 A120 '2011-03'), LL= (A133 A123 '2011-03'), ( D123 D120 '2011-04'), (D140 D123 '2011-04'),] I.m trying to get this, Adding rank to each tuple. [(A123, A120 ,'2011-0...
Create Rank of tuples in python
How do i do this? starting with this sample Id, Id2 CCC [ (A123 A120 '2011-03'), LL= (A133 A123 '2011-03'), ( D123 D120 '2011-04'), (D140 D123 '2011-04'),] I.m trying to get this, Adding rank to each tuple. [(A123, A120 ,'2011-03',1), LL= (A133, A123, '2011-...
[ "import pprint\nLL= [ ('A123', 'A120', '2011-03'),\n ('A133', 'A123', '2011-03'),\n ('D123', 'D120', '2011-04'),\n ('D140', 'D123', '2011-04'),]\nLL = [row+(i,) for i,row in enumerate(LL,1)]\npprint.pprint(LL)\n\nyields\n[('A123', 'A120', '2011-03', 1),\n ('A133', 'A123', '2011-03', 2),\n ('D123', 'D...
[ 3, 1, 0 ]
[]
[]
[ "python", "rank", "tuples" ]
stackoverflow_0005780983_python_rank_tuples.txt
Q: django sum for a queryset I need to do an aggregation on a django queryset for sets of data. I have a model that looks something like this: class Model1(models.Model): ... some fields here ... class Model2(models.Model): model1 = models.ForeignKey(Model1) number = models.IntegerField() active = m...
django sum for a queryset
I need to do an aggregation on a django queryset for sets of data. I have a model that looks something like this: class Model1(models.Model): ... some fields here ... class Model2(models.Model): model1 = models.ForeignKey(Model1) number = models.IntegerField() active = models.BooleanField() catego...
[ "I'm pretty sure you can do this with the annotate QuerySet method. I'll post an update if I can find a good example. \nUpdate: I think something like this.... if I understand your question correctly. Except you would use Count instead of Avg. \n\n\n\nAuthor.objects.values('name').annotate(average_rating=Avg('boo...
[ 3 ]
[]
[]
[ "django", "django_queryset", "python" ]
stackoverflow_0005781186_django_django_queryset_python.txt
Q: Serialize datetime to JSON How do I get DateTimeField from the Mysql database in Django in JSON format? I got an error when I executed the code Date.time cannot be serialized in json (data holds a lot of values): data = json.dumps(data) But this was fixed by adding ALL_data = serializers.serialize("json", data, e...
Serialize datetime to JSON
How do I get DateTimeField from the Mysql database in Django in JSON format? I got an error when I executed the code Date.time cannot be serialized in json (data holds a lot of values): data = json.dumps(data) But this was fixed by adding ALL_data = serializers.serialize("json", data, ensure_ascii=False) But now I ge...
[ "DjangoJSONEncoder solved my problem.\nimport json\nfrom django.core.serializers.json import DjangoJSONEncoder\ndata = json.dumps(data, cls=DjangoJSONEncoder)\n\n", "Django's serializers are only meant to be used on query sets; you will have to find a different way to solve your problem, such as converting the da...
[ 87, 5, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005583401_django_python.txt
Q: C# > XML-RPC.NET > Python MailMan I am attempting to use a .NET web application to manage an external MailMan server running in Python. I have the connection up and running, and all the basic functionality working completely. The last issue remaining is to find .NET's equivalent data type for a Python Key/Value ...
C# > XML-RPC.NET > Python MailMan
I am attempting to use a .NET web application to manage an external MailMan server running in Python. I have the connection up and running, and all the basic functionality working completely. The last issue remaining is to find .NET's equivalent data type for a Python Key/Value pair list. I have no access to the inne...
[ "You can view the XML-RPC specs here:\nhttp://www.xmlrpc.com/spec1\nThe spec details the different payloads for XML-RPC. One of them is \"struct,\" which may be what you are looking for. It can contain members, which in turn contain a name/value pair.\nIf you are using XML-RPC.NET, you can then look at the XML-RP...
[ 0 ]
[]
[]
[ "c#", "python", "xml_rpc" ]
stackoverflow_0005410605_c#_python_xml_rpc.txt
Q: Unable to create a basic video file using OpenCV I'm trying to create a basic video file using OpenCV (in Python). I have the following code, which runs without any errors, but I don't see the output file created. I was wondering if anyone had ideas as to what was going wrong. from cv import * im1 = LoadImage("/ho...
Unable to create a basic video file using OpenCV
I'm trying to create a basic video file using OpenCV (in Python). I have the following code, which runs without any errors, but I don't see the output file created. I was wondering if anyone had ideas as to what was going wrong. from cv import * im1 = LoadImage("/home/spoll/laptop1.jpg") im2 = LoadImage("/home/spoll/la...
[ "Why are you not checking errors? If CreateVideoWriter() is failing, you will never know.\nI think that CreateVideoWriter is returning NULL. Add the appropriate code to check the return and verify if this is true.\nIf it is, the problem is most probably CV_FOURCC() which is not finding the codec.\nThen, check this ...
[ 3 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0005781863_opencv_python.txt
Q: How do widgets update in Tkinter? Okay, so I'm just trying to get some clarification on why my code is not working like I thought it would. I am building a GUI, and I want to display text on a Label with a text variable. I have already made a function that updates the Label when the function is called, but of cour...
How do widgets update in Tkinter?
Okay, so I'm just trying to get some clarification on why my code is not working like I thought it would. I am building a GUI, and I want to display text on a Label with a text variable. I have already made a function that updates the Label when the function is called, but of course that is not my problem. My problem s...
[ "The UI will update every time the event loop is entered. This is because painting is done via events (also known as \"idle tasks\" because they are done when the UI is otherwise idle). \nYour problem is this: when you write a loop and do time.sleep, the event loop will not be entered while that loop is running, s...
[ 7 ]
[]
[]
[ "python", "tkinter", "user_interface", "widget" ]
stackoverflow_0005781286_python_tkinter_user_interface_widget.txt
Q: Is Python accessible from within Tortoise hg / Mercurial installation? I know that Tortoise HG (the windows explorer Mercurial plugin) uses Python internally, but does it expose Python so that I can use it for other purposes? If I try to use python from the command line It's not recognized (as far as I can tell) B...
Is Python accessible from within Tortoise hg / Mercurial installation?
I know that Tortoise HG (the windows explorer Mercurial plugin) uses Python internally, but does it expose Python so that I can use it for other purposes? If I try to use python from the command line It's not recognized (as far as I can tell) Bitbucket's getting started tutorial states (my emphasis): if you are on Win...
[ "The FAQ is saying that a program like py2exe was used to make it so that anyone could drop it on their computer without having to worry about having the right version of python installed. If you want to use the python API for mercurial check out their home page. If you want a portable copy of python go here http:/...
[ 2 ]
[]
[]
[ "python", "tortoisehg" ]
stackoverflow_0005782487_python_tortoisehg.txt
Q: Problem opening a text file in Python This seems like it should be very easy: f = open('C:\Users\john\Desktop\text.txt', 'r') But I am getting this error: Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> f = open('C:\Users\john\Desktop\text.txt', 'r') IOError: [Errno 22] invalid ...
Problem opening a text file in Python
This seems like it should be very easy: f = open('C:\Users\john\Desktop\text.txt', 'r') But I am getting this error: Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> f = open('C:\Users\john\Desktop\text.txt', 'r') IOError: [Errno 22] invalid mode ('r') or filename: 'C:\\Users\robejohn...
[ "Your file name has backslash characters in it. Backslash is the escape character in Python strings. Either replace them with '/' characters or use r'C:\\Users\\john\\Desktop\\text.txt'.\nYou might also find the functions in os.path useful.\n", "In Windows, paths use backslash. But if a string that must represent...
[ 11, 5 ]
[]
[]
[ "python" ]
stackoverflow_0005782321_python.txt
Q: How to run IN and NOT IN SPARQL statements in python rdflib to remove the intersection of two graphs I'm trying to use the IN and NOT IN statements (that were if I understand correctly, introduced in SPARQL 1.1) on the python implementation of SPARQL (now in rdfextras) but it seems that the syntax is not recognise...
How to run IN and NOT IN SPARQL statements in python rdflib to remove the intersection of two graphs
I'm trying to use the IN and NOT IN statements (that were if I understand correctly, introduced in SPARQL 1.1) on the python implementation of SPARQL (now in rdfextras) but it seems that the syntax is not recognised. Let's consider two sets (A and B). I want to output what is in Set A, removing what is in Set B. SELECT...
[ "I have tried a similar query and also got a parsing exception. I have gone through rdflib's SPARQL parser code and it doesn't seem to exist a rule to handle IN or NOT IN. I would assume that this functionality is not implemented.\nAnyway, I am not sure you are using it correctly. Having a look at the NOT IN defini...
[ 7, 4 ]
[]
[]
[ "python", "rdflib", "sparql" ]
stackoverflow_0005779971_python_rdflib_sparql.txt
Q: Pythonic way to find the name of global namespace imports I am trying to build some dynamic code that parses a text file with objects named from the imports at the top of the module... right now I iterate through all items in sys._getframe(0) to find f_globals. Is there a more pythonic way of finding f_globals? i...
Pythonic way to find the name of global namespace imports
I am trying to build some dynamic code that parses a text file with objects named from the imports at the top of the module... right now I iterate through all items in sys._getframe(0) to find f_globals. Is there a more pythonic way of finding f_globals? import re import sys import inspect ## Import all Object models ...
[ "Did you want globals()?\n", "Can't You just use\nglobals()\n\n?\nMoreover, is there a reason why not explicitly specify object to iterate over? That way, you are not prone to \"globals\" \"pollution\" by some correlated imports.\n" ]
[ 2, 1 ]
[]
[]
[ "introspection", "python" ]
stackoverflow_0005782651_introspection_python.txt
Q: Is it possible to install py26-mysql without installing mysql5 package? I am developing a database based django application and I have installed apache, python and django using macport on a snow leopard machine. I ran into issues installing MySQL with macport. But I was able to successfully install a standalone My...
Is it possible to install py26-mysql without installing mysql5 package?
I am developing a database based django application and I have installed apache, python and django using macport on a snow leopard machine. I ran into issues installing MySQL with macport. But I was able to successfully install a standalone MySQL server (from MySQL.com). Is it possible to remove the MysQL package insta...
[ "To use py26-mysql you don't need the entire server distribution for MySQL. You do need the client libs, at the very least. If you remove the server, you need to make sure you re-install the base libraries needed by the Python module to function.\n" ]
[ 2 ]
[]
[]
[ "macports", "mysql", "python" ]
stackoverflow_0005782875_macports_mysql_python.txt
Q: Submitting empty form and weird output Here's my form : <form action = "/search/" method = "get"> <input type = "text" name = "q"> <input type = "submit" value = "Search"> </form> And here's my view: def search(request): if 'q' in request.GET: message = 'You searched for: %r' % request.GET['q...
Submitting empty form and weird output
Here's my form : <form action = "/search/" method = "get"> <input type = "text" name = "q"> <input type = "submit" value = "Search"> </form> And here's my view: def search(request): if 'q' in request.GET: message = 'You searched for: %r' % request.GET['q'] else: message = 'You submitte...
[ "The \"weird u thing\" is a unicode string. You can read about it here: http://docs.python.org/tutorial/introduction.html#unicode-strings\nAnd I'm guessing since the user pressed submit, you get a request that has an empty q value (u'') since the user didn't enter anything. That makes sense, right? You should chang...
[ 3, 2, 1, 1 ]
[]
[]
[ "django", "forms", "python" ]
stackoverflow_0005779916_django_forms_python.txt
Q: Registering Global Hotkeys on a mac? I'm writing an app with Titanium Developer which lets me use Javascript, PHP, Ruby and Python. It provides an API with certain standard features one might want but one that's lacking is global events. Now I want to assign global hotkeys to my app and are pretty much left cluele...
Registering Global Hotkeys on a mac?
I'm writing an app with Titanium Developer which lets me use Javascript, PHP, Ruby and Python. It provides an API with certain standard features one might want but one that's lacking is global events. Now I want to assign global hotkeys to my app and are pretty much left clueless. Right now I'm only targeting MAC but a...
[ "You may be able to use Python to directly invoke PyObjC, which is a Python interface to Objective-C. A search for \"pyobjc hotkey\" turned up this document. (The one at the official PyObjC is broken for some reason.)\n" ]
[ 2 ]
[]
[]
[ "cocoa", "global_hotkey", "hotkeys", "python", "ruby" ]
stackoverflow_0005782776_cocoa_global_hotkey_hotkeys_python_ruby.txt
Q: Python Matrix length How can I get length of random Matrix(except last element in every row), for example: x=[['1', '7', 'U1'], ['1.5', '8', 'U1'], ['2', '5.5', 'U2']] I know that for length Python use "len(x)", but it's not correct Result must be in this case 6 (last element on every row not count) thanks A: s...
Python Matrix length
How can I get length of random Matrix(except last element in every row), for example: x=[['1', '7', 'U1'], ['1.5', '8', 'U1'], ['2', '5.5', 'U2']] I know that for length Python use "len(x)", but it's not correct Result must be in this case 6 (last element on every row not count) thanks
[ "sum(len(xx) - 1 for xx in x) should work.\n" ]
[ 2 ]
[]
[]
[ "matrix", "python" ]
stackoverflow_0005783235_matrix_python.txt
Q: python regex match and replace dates I need to match dates in form: January 10, 2012 And replace in form: 10 January 2012 Here is what I have so far: pattern = re.findall(r'(?:January|February|March|April|May|June|July|August|September|October|November|December)\s\d\d,\s\d{4}', text) print pattern ...
python regex match and replace dates
I need to match dates in form: January 10, 2012 And replace in form: 10 January 2012 Here is what I have so far: pattern = re.findall(r'(?:January|February|March|April|May|June|July|August|September|October|November|December)\s\d\d,\s\d{4}', text) print pattern How do i replace?
[ "Use strptime() to parse the date and strftime() to generate the new string. There is no reason to use a regex in this case.\nIn [1]: import time\nIn [2]: tm = time.strptime('January 10, 2012', '%B %d, %Y')\nIn [3]: time.strftime('%d %B %Y', tm)\nOut[4]: '10 January 2012'\n\n", "Just in general, something like th...
[ 5, 0 ]
[]
[]
[ "date", "datetime", "python", "regex" ]
stackoverflow_0005783186_date_datetime_python_regex.txt
Q: Use .Net (C#) dll in Python script I'm attempting to port a simple C# command-line utility to Python. The C# program uses a custom .Net dll called foobar.dll that interfaces with some lab equipment via I2C. The usage of the dll in the C# code is as follows: fooBar.fooProvider provider = new foobar.fooProvider() ...
Use .Net (C#) dll in Python script
I'm attempting to port a simple C# command-line utility to Python. The C# program uses a custom .Net dll called foobar.dll that interfaces with some lab equipment via I2C. The usage of the dll in the C# code is as follows: fooBar.fooProvider provider = new foobar.fooProvider() fooBar.fooBarLib fooLib = new foobar.foo...
[ "Python for .NET works really well, and you can execute .NET code from within Python. IronPython works well too, although the other way around. You can think of Python for .NET as an extension of CPython that can execute .NET code, while IronPython is an extension of the CLR allowing to execute Python code. Since y...
[ 7 ]
[]
[]
[ ".net", "c#", "dll", "python", "python.net" ]
stackoverflow_0005783387_.net_c#_dll_python_python.net.txt
Q: downloading Progress bar urllib2 python so i wanted to make a progress bar or percent using urllib2. i found this code on a different question on stack overflow: import urllib2, sys def chunk_report(bytes_so_far, chunk_size, total_size): percent = float(bytes_so_far) / total_size percent = round(percent*100...
downloading Progress bar urllib2 python
so i wanted to make a progress bar or percent using urllib2. i found this code on a different question on stack overflow: import urllib2, sys def chunk_report(bytes_so_far, chunk_size, total_size): percent = float(bytes_so_far) / total_size percent = round(percent*100, 2) sys.stdout.write("Downloaded %d of %d...
[ "Looks like the data is discarded. You can modify the chunk_read function to save it to a file.\nModified chunk_read will return the read data:\ndef chunk_read(response, chunk_size=8192, report_hook=None):\n total_size = response.info().getheader('Content-Length').strip()\n total_size = int(total_size)\n byte...
[ 2 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0005783517_python_urllib2.txt
Q: How to User Variable Names For Opening One or More Files In Python? Python newb and first-time poster... I'm building a mass disk copying program and have been pretty successful in working through issues until now. I am trying to open from 1 to n (up to 28) files (actually drives in Linux, e.g., /dev/sdc, /dev/sdd...
How to User Variable Names For Opening One or More Files In Python?
Python newb and first-time poster... I'm building a mass disk copying program and have been pretty successful in working through issues until now. I am trying to open from 1 to n (up to 28) files (actually drives in Linux, e.g., /dev/sdc, /dev/sdd, ...), depending on user checkbox selection. I'm using something like b...
[ "Don't use eval; keep a dictionary (Edit: or list) of file handles instead of individually named variables.\n#!/usr/bin/env python\n\ndef main():\n outfiles = [open(\"/tmp/tmp{0}\".format(i), 'wb') for i in (0,1,2,3)]\n\n with open('/dev/null', 'rb') as inf:\n # do reading/writing\n pass\n\n ...
[ 6, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005783516_python.txt
Q: If I start learning C on Ubuntu will it give me an edge when I start learning Objective-C later this summer? I know Ruby right now, however I want to learn a new language. I am running Ubuntu 10.04 right now but I am going to get a Mac later this summer. Anyways I want something more for GUI development. I was won...
If I start learning C on Ubuntu will it give me an edge when I start learning Objective-C later this summer?
I know Ruby right now, however I want to learn a new language. I am running Ubuntu 10.04 right now but I am going to get a Mac later this summer. Anyways I want something more for GUI development. I was wondering if I should learn C on Ubuntu right now, and then learn Objective-C when I get an iMac? Will learning C giv...
[ "It's frequently helpful to learn programming languages in the order they were created. The folks that wrote Objective-C clearly had C and its syntax, peculiarities, and features in mind when they defined the language. It can't hurt you to learn C now. You may have some insight into why Objective-C is structured...
[ 4, 1, 0, 0, 0 ]
[]
[]
[ "c", "linux", "macos", "objective_c", "python" ]
stackoverflow_0002840932_c_linux_macos_objective_c_python.txt
Q: Python multiprocessing issue / misunderstanding I'm having an issue with multiprocessing; I'm using python2.7 on linux 2.6.36. I know this would be much easier with a higher level module or library but I'm trying to use the lower level functions (os.fork() and os.exec*) to ensure I really understand- This is kind...
Python multiprocessing issue / misunderstanding
I'm having an issue with multiprocessing; I'm using python2.7 on linux 2.6.36. I know this would be much easier with a higher level module or library but I'm trying to use the lower level functions (os.fork() and os.exec*) to ensure I really understand- This is kind of a learning exercise. Below is my code, it's a mul...
[ "Perhaps you are being affected by a bug causing child processes to inherit pending signals. That would explain why the stack trace appears more than once. The child is trying to wait on its own non-existent child.\nAlso more than one queued signal of the same type may be handled at once, so I don't recommend usi...
[ 4, 1 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0005783183_multiprocessing_python.txt
Q: Python global variable is not working as expected I'm just starting out with Python and experimenting with different solutions. I was working with global variables and I ran into something but don't know why it's doing what it's doing. To start, I have two modules: test1 and test2. test1 is as follows: import test...
Python global variable is not working as expected
I'm just starting out with Python and experimenting with different solutions. I was working with global variables and I ran into something but don't know why it's doing what it's doing. To start, I have two modules: test1 and test2. test1 is as follows: import test2 num = 0 def start(): global num num = num + 5...
[ "The global declaration is not for modifying the name, it's for rebinding it. Since you are accessing the name via its module what you are doing is modifying the module.\n", "From test2's perspective, test1.num is a variable belonging to the module test1.\nThe global keyword only specifics that the scoping for th...
[ 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005783967_python.txt
Q: PyQT: can't drag/drop plain text into browser form element, but i can back into a text editor I've finally got a working example of both dragging AND dropping into & out of a listwidget, but sometimes the dragging into other contexts/applications doesn't work. Example: SUCCESS: select & drag text/plain from gedit...
PyQT: can't drag/drop plain text into browser form element, but i can back into a text editor
I've finally got a working example of both dragging AND dropping into & out of a listwidget, but sometimes the dragging into other contexts/applications doesn't work. Example: SUCCESS: select & drag text/plain from gedit into the listwidget and back to the text-editor FAILURE: but I can't then drag the plain-text list...
[ "It seems to work if you replace:\nresult = drag.exec_(QtCore.Qt.MoveAction)\n\nwith\nresult = drag.exec_(QtCore.Qt.CopyAction)\n\n" ]
[ 0 ]
[]
[]
[ "drag_and_drop", "forms", "pyqt", "python", "text" ]
stackoverflow_0005780256_drag_and_drop_forms_pyqt_python_text.txt
Q: ctypes: construct pointer from arbitrary integer For low-level purposes, I need to construct a ctypes pointer from an arbitrary address, given as an integer. For instance: INTP = ctypes.POINTER(ctypes.c_int) p = INTP(0x12345678) # i *know* this is the address But all such attempts result in TypeError: expected c...
ctypes: construct pointer from arbitrary integer
For low-level purposes, I need to construct a ctypes pointer from an arbitrary address, given as an integer. For instance: INTP = ctypes.POINTER(ctypes.c_int) p = INTP(0x12345678) # i *know* this is the address But all such attempts result in TypeError: expected c_long instead of int Is there anything I can do to ov...
[ "You can use ctypes.cast(addr, type). I'll extend your example to acquire an address via a known object, to demonstrate:\nINTP = ctypes.POINTER(ctypes.c_int)\nnum = ctypes.c_int(42)\naddr = ctypes.addressof(num)\nprint 'address:', addr, type(addr)\nptr = ctypes.cast(addr, INTP)\nprint 'pointer:', ptr\nprint 'value:...
[ 40 ]
[]
[]
[ "ctypes", "python", "pywin32" ]
stackoverflow_0005783761_ctypes_python_pywin32.txt
Q: TypeError: 'NoneType' object is not iterable I get the "TypeError: 'NoneType' object is not iterable" on the line "companyName, monthAverage, costPerTon, totalCost = displayCost(companyName, monthAverage, costPerTon, totalCost)" and I can't for the life of me figure out why. Sorry I can't seem to get it to format ...
TypeError: 'NoneType' object is not iterable
I get the "TypeError: 'NoneType' object is not iterable" on the line "companyName, monthAverage, costPerTon, totalCost = displayCost(companyName, monthAverage, costPerTon, totalCost)" and I can't for the life of me figure out why. Sorry I can't seem to get it to format correctly... 4-25-11 Final Project, Global Garbage...
[ "You try to unpack the return value of displayCost into 4 variables, but displayCost doesn't return anything. Because every function call returns something in Python (or throws an exception), None is returned. Then None can't be unpacked.\nYou probably want to change:\ncompanyName, monthAverage, costPerTon, total...
[ 6, 3 ]
[]
[]
[ "python" ]
stackoverflow_0005784582_python.txt
Q: python: geometric brownian motion simulation A basic simulation of GBM doesn't seem to work. What am I doing wrong? The following code always outputs values less than 1e-20, instead of something distributed randomly around 1.0: import math import random p = 1 dt = 1 mu = 0 sigma = 1 for k in range(100): p *= ...
python: geometric brownian motion simulation
A basic simulation of GBM doesn't seem to work. What am I doing wrong? The following code always outputs values less than 1e-20, instead of something distributed randomly around 1.0: import math import random p = 1 dt = 1 mu = 0 sigma = 1 for k in range(100): p *= math.exp((mu - sigma * sigma / 2) * dt + ...
[ "I found the answer. There is no problem with the code. It's just that the resulting lognormal distribution has enormous scale parameter = 1 * sqrt(100) = 10. With scale of 10, the skewness is insane.\nThus, even though the mean of the distribution is 1.0, it will take me billions of iterations (if not billions of...
[ 3, 0, 0, 0 ]
[]
[]
[ "python", "random", "simulation" ]
stackoverflow_0005774433_python_random_simulation.txt
Q: In Django, how do I make uniques on 3 fields? class ExternalFriends(models.Model): external_user = models.ForeignKey(User) name = models.CharField(max_length=20, null=False, blank=False, db_index=True) external_account_id = models.CharField(max_length=200, null=True, blank=True, db_index=T rue) So let...
In Django, how do I make uniques on 3 fields?
class ExternalFriends(models.Model): external_user = models.ForeignKey(User) name = models.CharField(max_length=20, null=False, blank=False, db_index=True) external_account_id = models.CharField(max_length=200, null=True, blank=True, db_index=T rue) So let's say I want all 3 fields to be "unique_together"....
[ "Use the Meta option unique_together. This takes a tuple (or tuples) describing sets of columns that should be considered unique together.\nThe model would look like this:\nclass ExternalFriends(models.Model):\n # columns\n\n class Meta:\n unique_together = ('external_user', 'name', 'external_account_...
[ 5 ]
[]
[]
[ "database", "django", "django_models", "mysql", "python" ]
stackoverflow_0005785053_database_django_django_models_mysql_python.txt
Q: Python: How to compare two lists of dictionaries Folks, Relative n00b to python, trying to find out the diff of two lists of dictionaries. If these were just regular lists, I could create sets and then do a '-'/intersect operation. However, set operation does not work on lists of dictionaries: >>> l = [] >>> pool...
Python: How to compare two lists of dictionaries
Folks, Relative n00b to python, trying to find out the diff of two lists of dictionaries. If these were just regular lists, I could create sets and then do a '-'/intersect operation. However, set operation does not work on lists of dictionaries: >>> l = [] >>> pool1 = {} >>> l.append(pool1) >>> s = set(l) Traceback (m...
[ "You need a \"hashable\" dictionary.\nThe items() attribute is a list of tuples. Make this a tuple() and you have a hashable version of a dictionary.\ntuple( sorted( some_dict.items() ) )\n\n", "You can define your own dict wrapper that defines __hash__ method:\nclass HashableDict(dict):\n def __hash__(self):...
[ 5, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005783745_python.txt
Q: Python lxml: Strange issue with reading repeated elements and storing in a list I'm running into a bizarre issue. I've had two very different versions of code to solve the same issue, and have run into the same problem. I have simplified the problem down to this: Here is the xml file: <Test> <Object name="Ob1"> ...
Python lxml: Strange issue with reading repeated elements and storing in a list
I'm running into a bizarre issue. I've had two very different versions of code to solve the same issue, and have run into the same problem. I have simplified the problem down to this: Here is the xml file: <Test> <Object name="Ob1"> <List/> </Object> <Object name="Ob2"> <List> <item>One</item> <item>Two</...
[ "The TestClass.list is a class-level attribute, so each object_list.append() is happening on the same list. \nFor example:\nclass Foo(object):\n lst = []\n\nf1 = Foo()\nf1.lst.append(1)\nf2 = Foo()\nf2.lst.append(2)\nprint f1.lst\nprint f2.lst\n\n[1, 2]\n[1, 2]\n\nYou should make it an instance-level attribute:\...
[ 2 ]
[]
[]
[ "list", "lxml", "parsing", "python", "xml" ]
stackoverflow_0005785039_list_lxml_parsing_python_xml.txt
Q: How do I use Django South when my app is inside another directory? So by default, Django creates apps inside the root project dir. But I moved it inside "apps". py manage.py schemamigration ./apps/chat --initial This doesn't work. Instead of "chat", I put "chat" Inside another directory. A: is apps python modu...
How do I use Django South when my app is inside another directory?
So by default, Django creates apps inside the root project dir. But I moved it inside "apps". py manage.py schemamigration ./apps/chat --initial This doesn't work. Instead of "chat", I put "chat" Inside another directory.
[ "is apps python module or just directory?\nif apps python modue, \nadd apps.chat to installed apps in settings.py\nand run \npy manage.py schemamigration chat --initial\n\nif apps is just directory, so you need to add this directory to your PYTHONPATH.\nadd these lines at near top of your manage.py\nimport os\nimp...
[ 1 ]
[]
[]
[ "django", "django_south", "migration", "mysql", "python" ]
stackoverflow_0005784803_django_django_south_migration_mysql_python.txt
Q: Need help making a Python script starup on mac using Launch Agent and send output to a window I've created a python script I wish to have run automatically when I log in on a mac, and need some help using a Launch Agent to do this. I used SO extensively getting things working up to this point, so I figured this wa...
Need help making a Python script starup on mac using Launch Agent and send output to a window
I've created a python script I wish to have run automatically when I log in on a mac, and need some help using a Launch Agent to do this. I used SO extensively getting things working up to this point, so I figured this was the place to ask, but I'm still fairly new to this, so I need some help. Here's what I've got so ...
[ "If you want the output to appear in a terminal, you can use Launch Agent to start an Apple Script which will open Terminal and then run your python script:\ntell application \"Terminal\"\n activate\n do script \"/usr/bin/python WVCS-0.1.py\"\nend tell\n\nor to display the text in the applescript / calling wi...
[ 4 ]
[]
[]
[ "launchd", "python", "startupscript" ]
stackoverflow_0005781575_launchd_python_startupscript.txt
Q: Django string index out of range Very confused. I have a variable that has 32 items in it, and I'm trying to do a for loop but it's saying "Caught IndexError while rendering: string index out of range" Any ideas? The variable definitely isn't empty. {% if photos %} <ul class="photo-grid"> {% for photo ...
Django string index out of range
Very confused. I have a variable that has 32 items in it, and I'm trying to do a for loop but it's saying "Caught IndexError while rendering: string index out of range" Any ideas? The variable definitely isn't empty. {% if photos %} <ul class="photo-grid"> {% for photo in photos %} <li> ...
[ "I believe the problem might be with the photo.images part of the value. Is images an array or collection in the photo object? If it is an array, the images.low_resolution is trying to access the image in the array at the index value of low_resolution which is probably not what you want (or maybe it is???). You...
[ 3 ]
[]
[]
[ "django", "python", "templates" ]
stackoverflow_0005785744_django_python_templates.txt
Q: Syntax error in python, need help for a project I'm trying to find a way to fix this syntax error. I can't seem to find it to make the program run correctly. This is my code below wrong = 0 test = raw_input("Please enter a 4 digit integer:") def start(test): if test.isdigit(): if wrong(test)==True: ...
Syntax error in python, need help for a project
I'm trying to find a way to fix this syntax error. I can't seem to find it to make the program run correctly. This is my code below wrong = 0 test = raw_input("Please enter a 4 digit integer:") def start(test): if test.isdigit(): if wrong(test)==True: print 'Invalid input. Four integers m...
[ "You've called a function named wrong() but defined a function named error(). Is that the problem you're seeing?\n", "Don't you mean if error(test)? 'wrong' is not a function.\n" ]
[ 2, 1 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0005785997_python_syntax.txt
Q: Why can't I install greenlet (just a basic python package)? I untarred it from: http://pypi.python.org/pypi/greenlet#downloads (I'm in my virtual env. I sourced it, too, thats why I didn't sudo) $ py setup.py install /usr/lib/python2.6/distutils/dist.py:266: UserWarning: Unknown distribution option: 'repository' ...
Why can't I install greenlet (just a basic python package)?
I untarred it from: http://pypi.python.org/pypi/greenlet#downloads (I'm in my virtual env. I sourced it, too, thats why I didn't sudo) $ py setup.py install /usr/lib/python2.6/distutils/dist.py:266: UserWarning: Unknown distribution option: 'repository' warnings.warn(msg) running install running bdist_egg running eg...
[ "On Ubuntu you'd need to install the python-dev package. This provides the Python.h header:\n% dpkg -S /usr/include/python2.6/Python.h\npython2.6-dev: /usr/include/python2.6/Python.h\n\n", "you don't have python-dev installed so there is no Python.h header.\n" ]
[ 6, 2 ]
[]
[]
[ "linux", "python", "unix" ]
stackoverflow_0005786017_linux_python_unix.txt
Q: Proxy pattern idiom I'm a web application developer and in using SQLAlchemy I find it clumsy to do this in many of my controllers when I'm wanting a specific row from (say) the users table: from model import dbsession # SQLAlchemy SessionMaker instance from model import User user = dbsession().query(User).filter_...
Proxy pattern idiom
I'm a web application developer and in using SQLAlchemy I find it clumsy to do this in many of my controllers when I'm wanting a specific row from (say) the users table: from model import dbsession # SQLAlchemy SessionMaker instance from model import User user = dbsession().query(User).filter_by(some_kw_args).first() ...
[ "You mention \"didn't like having to do 'all of that'\" where 'all of that' looks an awful lot like only 1 - 2 lines of code so I'm feeling that this isn't really necessary. Basically I don't really think that either statement you started with is all that verbose or confusing. \nHowever, If I had to come up with ...
[ 3 ]
[]
[]
[ "abstraction", "idioms", "python", "sqlalchemy" ]
stackoverflow_0005783544_abstraction_idioms_python_sqlalchemy.txt
Q: If I have a web server with 10 process and 10 threads, what does that mean? http://pypi.python.org/pypi/Spawning/ So I'm playing with Spawning... If I run it with 10 process and 10 threads, what does that mean? I'm building a chat room (long-polling using eventlet). Does that mean that only 10 people can be prese...
If I have a web server with 10 process and 10 threads, what does that mean?
http://pypi.python.org/pypi/Spawning/ So I'm playing with Spawning... If I run it with 10 process and 10 threads, what does that mean? I'm building a chat room (long-polling using eventlet). Does that mean that only 10 people can be present in the chat room?
[ "No. It all depends on the architecture of your application. Event-based apps can support large amounts of connections (users, sessions, whatever matters in your app) in a single thread.\nYou usually need multiple threads when you're performing blocking IO operations, and multiple processes when you need true compu...
[ 0, 0 ]
[]
[]
[ "ajax", "multithreading", "process", "python" ]
stackoverflow_0005786361_ajax_multithreading_process_python.txt
Q: Is there an equilivent to Linq.Expressions.Expression in python? I would like to be able to get the expression out of a lambda function much like C# does and parse it into something else? Example in C#: void Foo<T>(Expression<Func<T, bool>> expression { // ... } Foo<Baz>(someObj => someObj.HasBar); The lambda ...
Is there an equilivent to Linq.Expressions.Expression in python?
I would like to be able to get the expression out of a lambda function much like C# does and parse it into something else? Example in C#: void Foo<T>(Expression<Func<T, bool>> expression { // ... } Foo<Baz>(someObj => someObj.HasBar); The lambda operator will be traslated to an expression that could be inspected. W...
[ "Python provides full access to the compiled form of code.\n>>> f = lambda(x): 2*x\n>>> f.func_code.co_code\n'd\\x00\\x00|\\x00\\x00\\x14S'\n>>> \n\nYou can, in principle, reverse engineer this to figure out the expression, though it's no mean feat to do so. The dis module might give you a bit of a head-start:\n>>>...
[ 1 ]
[]
[]
[ "expression_trees", "lambda", "python" ]
stackoverflow_0005786593_expression_trees_lambda_python.txt
Q: Python CGI - Creating a hyperlink with a query string I was wondering how would I create a hyperlink to another page of my website with the query string being based off an item in a list returned from a database. So for example: for item in database generate hyperlink the hyperlink would be something like te...
Python CGI - Creating a hyperlink with a query string
I was wondering how would I create a hyperlink to another page of my website with the query string being based off an item in a list returned from a database. So for example: for item in database generate hyperlink the hyperlink would be something like test.py?message=24, where 24 is the item in the list returned...
[ "You can look for urlparse module documentation which provides urljoin method to construct a absolute url by joining one base url with a relative path.\n" ]
[ 0 ]
[]
[]
[ "cgi", "html", "python" ]
stackoverflow_0005786653_cgi_html_python.txt
Q: django error with admin page i'm new to django and im trying add a user using django admin page. but i end up with a 404 : Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/admin/auth/user/add/ user not found what is going on ? am i doing anything wrong ? here is my urls.py : from dj...
django error with admin page
i'm new to django and im trying add a user using django admin page. but i end up with a 404 : Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/admin/auth/user/add/ user not found what is going on ? am i doing anything wrong ? here is my urls.py : from django.conf.urls.defaults import * f...
[ "I think your admin urlpattern is incorrect. Try this:\nurlpatterns = patterns('', \n (r'^admin/(.*)', admin.site.root),\n)\n\nAnother possibility: You need to create the necessary tables for the administration application: \npython manage.py syncdb. \n\nDid you syncdb?\n", "i know it's bad to answer my own qu...
[ 1, 1 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0005782584_django_django_admin_python.txt
Q: amqp queue_delete catch errors in async way I've just got started using pika(v 0.9.4) with Tornado (through the use of pika.adapters.tornado_connection.TornadoConnection) and I was wondering what's the appropriate way of catching errors when using, say: queue_delete for when the queue you're trying to delete doesn...
amqp queue_delete catch errors in async way
I've just got started using pika(v 0.9.4) with Tornado (through the use of pika.adapters.tornado_connection.TornadoConnection) and I was wondering what's the appropriate way of catching errors when using, say: queue_delete for when the queue you're trying to delete doesn't exist. RabbitMQ raises AMQPError, but I am not...
[ "Disclaimer: I'm the author of stormed-amqp\nI would suggest trying with stormed-amqp\nimport logging\nlogging.basicConfig()\n\nfrom tornado.ioloop import IOLoop\nfrom stormed import Connection\n\ndef on_connect():\n ch = conn.channel()\n ch.queue_declare(queue='hello', durable=False)\n ch.queue_declare(qu...
[ 0, 0 ]
[]
[]
[ "amqp", "python", "rabbitmq", "tornado" ]
stackoverflow_0005302695_amqp_python_rabbitmq_tornado.txt
Q: Good Python library for AMQP Can you recommend what Python library to use for accessing AMQP (RabbitMQ)? From my research pika seems to be the preferred one. A: My own research led me to believe that the right library to use would be Kombu, as this is also what Celery (mentioned by @SteveMc) has transitioned to....
Good Python library for AMQP
Can you recommend what Python library to use for accessing AMQP (RabbitMQ)? From my research pika seems to be the preferred one.
[ "My own research led me to believe that the right library to use would be Kombu, as this is also what Celery (mentioned by @SteveMc) has transitioned to. I am also using RabbitMQ and have used Kombu with the default amqplib backend successfully.\nKombu also supports other transports behind the same API. Useful if...
[ 26, 21, 3, 2 ]
[]
[]
[ "amqp", "python", "rabbitmq" ]
stackoverflow_0005031606_amqp_python_rabbitmq.txt
Q: Django pre_save triggered twice I am using django signals for data denormalization. Here is my code: # vote was saved @receiver(pre_save, sender=Vote) def update_post_votes_on_save(sender, instance, **kwargs): """ Update post rating """ # is vote is being updated, then we must remove previous value first ...
Django pre_save triggered twice
I am using django signals for data denormalization. Here is my code: # vote was saved @receiver(pre_save, sender=Vote) def update_post_votes_on_save(sender, instance, **kwargs): """ Update post rating """ # is vote is being updated, then we must remove previous value first if instance.id: old_vote ...
[ "I'm sorry, for the confusement, but dispatch_uid solved the problem, after all. Just remember, that you might have to restart the development server to see the effect, before asking a question on SO :)\n" ]
[ 9 ]
[]
[]
[ "django", "django_signals", "python" ]
stackoverflow_0005718244_django_django_signals_python.txt
Q: how to get function's name from within the function (or kind of "self" reference to the function)? This answer shows that there is a built-in __name__ attribute of a function which can be used from outside the function, i.e. print f.__name__. However, how can I get this attribute from within the function itself? J...
how to get function's name from within the function (or kind of "self" reference to the function)?
This answer shows that there is a built-in __name__ attribute of a function which can be used from outside the function, i.e. print f.__name__. However, how can I get this attribute from within the function itself? Just using unqualified __name__ does not help: print __name__ prints __main__. Using print f.__name__ fro...
[ "if you don't want to \"inspect\" the stack, you could use a decorator on your method to store it in your dictionnary and avoid to launch it twice.\nfunction_list = []\ndef method_singleton(function):\n global function_list\n def decorated_method(*args, **kwargs):\n if function.__name__ not in function...
[ 4, 3 ]
[]
[]
[ "python" ]
stackoverflow_0005787299_python.txt
Q: replacing object by a dummy before any imports and/or other statements get executed I use USE_DUMMY which if it's set to True then a dummy is created for my module. The question is: how do I set this variable (from an external module) BEFORE the import and/or other statements get executed? a.py: USE_DUMMY = False...
replacing object by a dummy before any imports and/or other statements get executed
I use USE_DUMMY which if it's set to True then a dummy is created for my module. The question is: how do I set this variable (from an external module) BEFORE the import and/or other statements get executed? a.py: USE_DUMMY = False def unvailable(): print 'not available' if USE_DUMMY is True: def dummy(): ...
[ "In contrast to some other languages, Python's import is simply an executable statement. This means that if you want to take some actions before importing some modules, you can simply place code before the relevant import.\nIn other words, if you need to set a global variable before any imports etc, you could place...
[ 2, 0 ]
[]
[]
[ "import", "python", "testing" ]
stackoverflow_0005745647_import_python_testing.txt
Q: Displaying images in Django Try with a specific folder to display an image, but does not work, tell me what I was doing wrong and where, what can it not enough? All images are in the folder C:\dip\todo. Use runserver. settings.py MEDIA_ROOT = 'C:/dip/todo/' MEDIA_URL = 'http://127.0.0.1:8000/media/' ADMIN_MEDIA_P...
Displaying images in Django
Try with a specific folder to display an image, but does not work, tell me what I was doing wrong and where, what can it not enough? All images are in the folder C:\dip\todo. Use runserver. settings.py MEDIA_ROOT = 'C:/dip/todo/' MEDIA_URL = 'http://127.0.0.1:8000/media/' ADMIN_MEDIA_PREFIX = '/admin-media/' admin.py...
[ "Your media url says: \nMEDIA_URL = 'http://127.0.0.1:8000/media/'\n\nBut in urls you have: \n(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}), )\n\nTry changing site_media to media and it should work\n" ]
[ 2 ]
[]
[]
[ "django", "django_admin", "django_forms", "django_models", "python" ]
stackoverflow_0005787613_django_django_admin_django_forms_django_models_python.txt
Q: PyQt: change the alignment of checkboxes in a QTableView I have a QTableView with checkbox, but the checkbox is aligned left, and I need to align it center. I tried this, but I have a problem with the "check" function: def drawCheck(self, painter, option, rect, state): textMargin = QtGui.QApplication.style().p...
PyQt: change the alignment of checkboxes in a QTableView
I have a QTableView with checkbox, but the checkbox is aligned left, and I need to align it center. I tried this, but I have a problem with the "check" function: def drawCheck(self, painter, option, rect, state): textMargin = QtGui.QApplication.style().pixelMetric(QtGui.QStyle.PM_FocusFrameHMargin) + 1 checkRec...
[ "The example code you link to doesn't have a check function - could it be a typo that has been fixed? Or maybe it's a function defined in the code itself and isn't part of Qt?\n" ]
[ 0 ]
[]
[]
[ "alignment", "checkbox", "pyqt", "python", "qtreeview" ]
stackoverflow_0002965855_alignment_checkbox_pyqt_python_qtreeview.txt
Q: Creating a 3 column HTML table with dynamic data in Django I am trying to create a dynamic HTML table with 3 columns and 3 rows. Each column will have 3 records from the database so there will be 9 total records displayed (if they have 9 friends. otherwise just however many they have). I am doing this to mainly di...
Creating a 3 column HTML table with dynamic data in Django
I am trying to create a dynamic HTML table with 3 columns and 3 rows. Each column will have 3 records from the database so there will be 9 total records displayed (if they have 9 friends. otherwise just however many they have). I am doing this to mainly display small user profile pictures with their friends' usernames ...
[ "you can use the forloop.counter and do something like:\n<table>\n <tr>\n{% for person in people %}\n <td>{{ person }}</td>\n {% if not forloop.last and forloop.counter == 3 or forloop.counter == 6 %}\n </tr>\n <tr>\n {% endif %}\n{% endfor %}\n </tr>\n</table>\n\nor roll a custom template ...
[ 9, 1, 0 ]
[]
[]
[ "django", "html", "python", "xhtml" ]
stackoverflow_0005785348_django_html_python_xhtml.txt
Q: Pythonpath issue - Cocos2d I'm trying to use a game library called Cocos2d in python. However, I can't really import it. It's installed in one of python's lib directories, and when I import it, it's saying that it's not there. I know it has to do with pythonpath (provided in the IDE I'm using) but I'm not sure how...
Pythonpath issue - Cocos2d
I'm trying to use a game library called Cocos2d in python. However, I can't really import it. It's installed in one of python's lib directories, and when I import it, it's saying that it's not there. I know it has to do with pythonpath (provided in the IDE I'm using) but I'm not sure how to set it up. I've tried just a...
[ "Do you get an import error message ?\nI don't know how you installed it but here are the steps I just did and which are working here.\n\nDownload cocos2d-0.4.0.zip from the official website\nExtract it anywhere\nOpen a command-line in that folder\ntype python setup.py install\n\n\nIt even automatically installs py...
[ 1 ]
[]
[]
[ "cocos2d_python", "python", "pythonpath" ]
stackoverflow_0005774089_cocos2d_python_python_pythonpath.txt
Q: Standard Python libraries and Unicode I have been reading left right and centre about unicode and python. I think I understand what encoding/decoding is, yet as soon as I try to use a standard library method manipulating a file name, I get the infamous: UnicodeEncodeError: 'ascii' codec can't encode character u'\...
Standard Python libraries and Unicode
I have been reading left right and centre about unicode and python. I think I understand what encoding/decoding is, yet as soon as I try to use a standard library method manipulating a file name, I get the infamous: UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 19: ordinal not in range(...
[ "Filenames on *nix cannot be manipulated as unicode. The filename must be encoded to match the charset of the filesystem and then used.\n", "you should decode manually the filename with the correct encoding (latin1?) before os.path.join\nbtw: # -- coding: utf-8 -- refers to the string literals in your .py file\ne...
[ 2, 1, 1 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0005787736_python_unicode.txt
Q: Using a Python script to start and stop the Google App Engine dev_appserver during continuous integration testing I'm trying to write a Python script that will enable me to start the Google App Engine dev_appserver using coverage.py, fetch the /test url from the app that I launch, wait for the server to finish ret...
Using a Python script to start and stop the Google App Engine dev_appserver during continuous integration testing
I'm trying to write a Python script that will enable me to start the Google App Engine dev_appserver using coverage.py, fetch the /test url from the app that I launch, wait for the server to finish returning the page, then shutdown the dev_appserver, and then generate a report. My challenge is how to launch the dev_ap...
[ "You should go with subprocess Popen\nimport os\nimport signal\nimport subprocess\n\ncoverage_proc = subprocess.Popen(\n ['coverage','run', your_flag_list]\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT)\ntime.sleep(5) #Find the correct sleep value\nurllib.urlopen('http://localhost:...
[ 4, 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005786887_google_app_engine_python.txt