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: Converting any encoding to utf8 in python? I'm crawling webpages from different websites and they have varied encodings. A sample of the encodings I get are - Big5 TIS-620 utf-16le shift_JIS EUC-JP MacCyrillic koi8-r apart from the more common encodings. I can get the unicode source of the web page by decoding...
Converting any encoding to utf8 in python?
I'm crawling webpages from different websites and they have varied encodings. A sample of the encodings I get are - Big5 TIS-620 utf-16le shift_JIS EUC-JP MacCyrillic koi8-r apart from the more common encodings. I can get the unicode source of the web page by decoding using the above encodings. My question is this:...
[ "Yes, UTF-8 is nothing more than a scheme for storing integers in bytes, in such a way that smaller integers take fewer bytes. The result is that values less than 128 are stored in one byte so that ASCII is still ASCII. UTF-8 can represent all Unicode codepoints.\n", "Short and sweet, ........ yes!\n" ]
[ 4, 1 ]
[]
[]
[ "character_encoding", "encoding", "python", "unicode", "utf_8" ]
stackoverflow_0006972466_character_encoding_encoding_python_unicode_utf_8.txt
Q: Make Python respond to Windows timezone changes When Python is running under Windows, time.localtime does not report the correct time if the timezone is changed during the life time of the Python instance. Under Linux, time.tzset can always been run to alleviate problems like this, but there appears to be no equiv...
Make Python respond to Windows timezone changes
When Python is running under Windows, time.localtime does not report the correct time if the timezone is changed during the life time of the Python instance. Under Linux, time.tzset can always been run to alleviate problems like this, but there appears to be no equivalent in Windows. Is there a way to fix this without ...
[ "A more rational solution is to use Kernel32's GetLocalTime with pywin32 or ctypes. Any time zone changes are reflected immediately.\nimport ctypes\nclass SYSTEMTIME(ctypes.Structure):\n _fields_ = [\n ('wYear', ctypes.c_int16),\n ('wMonth', ctypes.c_int16),\n ('wDayOfWeek', ctypes.c_int16),...
[ 8, 4, 4 ]
[]
[]
[ "localtime", "python", "time", "timezone", "windows" ]
stackoverflow_0004360981_localtime_python_time_timezone_windows.txt
Q: Code coverage with django debug server I am using coverage.py from http://nedbatchelder.com/code/coverage/ for getting coverage data for my django unittests but I can't seem to figure out how can I run the coverage on the django debug server. I would want to run the django server using: coverage -x manage.py runse...
Code coverage with django debug server
I am using coverage.py from http://nedbatchelder.com/code/coverage/ for getting coverage data for my django unittests but I can't seem to figure out how can I run the coverage on the django debug server. I would want to run the django server using: coverage -x manage.py runserver 0.0.0.0:8080 and when stopping this se...
[ "Hmm, not sure what to make of that. When I create a brand new Django project, I get some coverage measurement:\n$ django-admin.py startproject mysite\n$ cd mysite\n$ coverage run manage.py runserver\nValidating models...\n\n0 errors found\nDjango version 1.3, using settings 'mysite.settings'\nDevelopment server i...
[ 3 ]
[]
[]
[ "coverage.py", "django", "python" ]
stackoverflow_0006972046_coverage.py_django_python.txt
Q: Using heapy to track down memory leaks in Django app I've followed excellent post here how to setup heapy with Django: http://www.toofishes.net/blog/using-guppy-debug-django-memory-leaks/ I've commanded hp.setref() and now after awhile I get also data with hp.heap(): >>> hp.heap() Partition of a set of 12075 objec...
Using heapy to track down memory leaks in Django app
I've followed excellent post here how to setup heapy with Django: http://www.toofishes.net/blog/using-guppy-debug-django-memory-leaks/ I've commanded hp.setref() and now after awhile I get also data with hp.heap(): >>> hp.heap() Partition of a set of 12075 objects. Total size = 1515496 bytes. Index Count % Size...
[ "I don't have any experience with heapy, but in my experience, Django (and most other Python programs) don't leak memory, but they also don't clean up memory as pristinely as some would like.\nAlso, Django has settings that cause it to consume memory for diagnostic reasons. For example, setting DEBUG=True can caus...
[ 0 ]
[]
[]
[ "debugging", "django", "memory_leaks", "python" ]
stackoverflow_0006972653_debugging_django_memory_leaks_python.txt
Q: AssertRaises fails even though exception is raised I am running into the following rather strange problem: I am developing a django app and in my models class I am defining an exception that should be raised when a validation fails: class MissingValueException(Exception): """Raise when a required attribute is miss...
AssertRaises fails even though exception is raised
I am running into the following rather strange problem: I am developing a django app and in my models class I am defining an exception that should be raised when a validation fails: class MissingValueException(Exception): """Raise when a required attribute is missing.""" def __init__(self, message): super(MissingVa...
[ "This could happen if your tests and your product code are importing your exception class through two different paths, so asserRaises doesn't realize that the exception you got was the one you were looking for.\nLook at your imports, make sure that they are the same in both places. Having the same directories avai...
[ 6 ]
[]
[]
[ "django", "python", "unit_testing" ]
stackoverflow_0006972703_django_python_unit_testing.txt
Q: Cannot get entire web page after query I'm trying to scrape the historical NAVPS tables found on this page: http://www.philequity.net/pefi_historicalnavps.php All the code here are the contents of my minimal working script. So it starts with: import urllib import urllib2 from BeautifulSoup import BeautifulSoup op...
Cannot get entire web page after query
I'm trying to scrape the historical NAVPS tables found on this page: http://www.philequity.net/pefi_historicalnavps.php All the code here are the contents of my minimal working script. So it starts with: import urllib import urllib2 from BeautifulSoup import BeautifulSoup opener = urllib2.build_opener() urllib2.instal...
[ "When I look at the POST request in firebug, I see one more parameter that you aren't passing: \"type\" is \"Year\". I don't know if this will get the data for you, there's any number of other reasons it might not serve you the data.\n" ]
[ 1 ]
[]
[]
[ "javascript", "python", "screen_scraping", "urllib", "urllib2" ]
stackoverflow_0006972637_javascript_python_screen_scraping_urllib_urllib2.txt
Q: Invalid OpenID response: HTTP 599: SSL certificate problem, verify that the CA cert is OK. I'm trying to run authdemo.py (demos/auth/ folder) from Tornado 2 http://www.tornadoweb.org/ package to try out authentication mix-ins. However I get the following error: [I 110728 15:24:57 web:1235] 302 GET / (127.0.0.1) 1....
Invalid OpenID response: HTTP 599: SSL certificate problem, verify that the CA cert is OK.
I'm trying to run authdemo.py (demos/auth/ folder) from Tornado 2 http://www.tornadoweb.org/ package to try out authentication mix-ins. However I get the following error: [I 110728 15:24:57 web:1235] 302 GET / (127.0.0.1) 1.00ms [I 110728 15:24:57 web:1235] 302 GET /auth/login?next=%2F (127.0.0.1) 0.00ms [I 110728 15:2...
[ "Most likely a certificate bundle problem. It looks like a curl error, which is weird, as curl is no longer the default HTTPClient. Are you on Python 2.5, perhaps? Try updating pycurl and libcurl, or try Python 2.6.\n" ]
[ 1 ]
[]
[]
[ "google_openid", "oauth", "python", "ssl", "tornado" ]
stackoverflow_0006858948_google_openid_oauth_python_ssl_tornado.txt
Q: Python - Google App Engine - Get model ID in Dict In my Google App Engine - Python app, I've got a to_dict() to allow JSON serialization of my models. class BaseModel(db.Model): createdOn = db.DateTimeProperty(auto_now_add=True) createdBy = db.UserProperty(auto_current_user_add=True) modifiedOn = db.DateTime...
Python - Google App Engine - Get model ID in Dict
In my Google App Engine - Python app, I've got a to_dict() to allow JSON serialization of my models. class BaseModel(db.Model): createdOn = db.DateTimeProperty(auto_now_add=True) createdBy = db.UserProperty(auto_current_user_add=True) modifiedOn = db.DateTimeProperty(auto_now_add=True) modifiedBy = db.UserPrope...
[ "There's A handy to_dict method in ext.db, you could update your method to something like:\nclass MyModel(db.Model):\n def to_dict(self):\n return db.to_dict(self, {'id':self.key().id()})\n\nYou might want to check if your model is is_saved before trying to get the id though.\n" ]
[ 5 ]
[]
[]
[ "dictionary", "google_app_engine", "json", "python" ]
stackoverflow_0006972609_dictionary_google_app_engine_json_python.txt
Q: Write frames from camera to a single image in OpenCV I am trying to grab frames from camera and add them into a single image to get the effect as in this image: http://www.danheller.com/images/California/DeathValley/Nite/tent-star-trails.jpg But my image turns white after a couple of seconds. Here is the code: #!/...
Write frames from camera to a single image in OpenCV
I am trying to grab frames from camera and add them into a single image to get the effect as in this image: http://www.danheller.com/images/California/DeathValley/Nite/tent-star-trails.jpg But my image turns white after a couple of seconds. Here is the code: #!/usr/bin/python import cv stream = cv.CaptureFromCAM(0) cv....
[ "Yes, your image will turn white after a few frames because adding images pixel by pixel increases the brightness by quite a lot. You'll have to come up with a better algorithm to merge the images together.\nOne way you can do that is add the two images then normalize the resulting image before adding more images o...
[ 1 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0006972870_opencv_python.txt
Q: python look-and-say sequence improved I would like to introduce look-and-say sequence at first. It goes like a = {1, 11, 21, 1211, 111221 ... The system is it checks the previous digit and counts the numbers. 1 = one 1 (so = 11) 11 = two 1 (so = 21) 21 = one 2 one 1 (so = 1211) As a rule of the sequence, no numbe...
python look-and-say sequence improved
I would like to introduce look-and-say sequence at first. It goes like a = {1, 11, 21, 1211, 111221 ... The system is it checks the previous digit and counts the numbers. 1 = one 1 (so = 11) 11 = two 1 (so = 21) 21 = one 2 one 1 (so = 1211) As a rule of the sequence, no number can go beyond 3, so creating a translatio...
[ "You can use groupby, it's just what you want:\nfrom itertools import groupby\ndef lookandsay(n):\n return ''.join( str(len(list(g))) + k for k, g in groupby(n))\n\n>>> lookandsay('1')\n'11'\n>>> lookandsay('1A2b41')\n'111A121b1411'\n>>> lookandsay(lookandsay('1A2b41'))\n'311A1112111b111421'\n\ngroupby returns c...
[ 16, 4, 3 ]
[]
[]
[ "python", "sequences" ]
stackoverflow_0006972764_python_sequences.txt
Q: UnicodeDecodeError is raised when getting a cookie in Google App Engine I have a GAE project in Python where I am setting a cookie in one of my RequestHandlers with this code: self.response.headers['Set-Cookie'] = 'app=ABCD; expires=Fri, 31-Dec-2020 23:59:59 GMT' I checked in Chrome and I can see the cookie liste...
UnicodeDecodeError is raised when getting a cookie in Google App Engine
I have a GAE project in Python where I am setting a cookie in one of my RequestHandlers with this code: self.response.headers['Set-Cookie'] = 'app=ABCD; expires=Fri, 31-Dec-2020 23:59:59 GMT' I checked in Chrome and I can see the cookie listed, so it appears to be working. Then later in another RequestHandler, I get t...
[ "You're looking to use the decode function somewhat like this (cred @agf:):\nself.request.cookies['app'].decode('utf-8')\n\nFrom official python documentation (plus a couple added details):\nPython’s 8-bit strings have a .decode([encoding], [errors]) method that interprets the string using the given encoding. The f...
[ 0, 0 ]
[]
[]
[ "character_encoding", "cookies", "google_app_engine", "python", "unicode" ]
stackoverflow_0006839922_character_encoding_cookies_google_app_engine_python_unicode.txt
Q: If you subclass from dict, why is __dict__ always empty? I have a question regarding the subclassing behaviour in Python 2.7. If I subclass from the built-in dict type, it seems that __ dict __ is always empty. Where does Python save the key/value pairs? >>> class Foobar(dict): ... pass ... >>> foobar = Fooba...
If you subclass from dict, why is __dict__ always empty?
I have a question regarding the subclassing behaviour in Python 2.7. If I subclass from the built-in dict type, it seems that __ dict __ is always empty. Where does Python save the key/value pairs? >>> class Foobar(dict): ... pass ... >>> foobar = Foobar() >>> foobar.__dict__ {} >>> foobar['test'] = 1 >>> foobar._...
[ "__dict__ is where an object's attributes are stored. Dicts' items are not attributes, they are items. Most dicts have no data attributes.\nBTW: subclassing dict is difficult to do properly, depending what you are trying to achieve. For example, you can override its __setitem__ method, but then update won't use ...
[ 6, 5, 5, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006973747_python.txt
Q: Python regex to PHP? I'm trying to convert a Python script into PHP. The following 2 regular expressions work in Python: '/\*\*([\w\n\(\)\[\]\.\*\'\"\-#|,@{}_<>=:/ ]+?)\*/' '(?:\* ([\w\d\(\),\.\'\"\-\:#|/ ]+)|(?<= @)(\w+)(?: (.+))?)' ...however, if I try to run them in PHP I get: Warning: preg_match_all() [functi...
Python regex to PHP?
I'm trying to convert a Python script into PHP. The following 2 regular expressions work in Python: '/\*\*([\w\n\(\)\[\]\.\*\'\"\-#|,@{}_<>=:/ ]+?)\*/' '(?:\* ([\w\d\(\),\.\'\"\-\:#|/ ]+)|(?<= @)(\w+)(?: (.+))?)' ...however, if I try to run them in PHP I get: Warning: preg_match_all() [function.preg-match-all]: Unknow...
[ "PCRE (including preg_match_all) requires a pattern boundary. You need to wrap the entire pattern in /, @, #, %, or many other possible options. I suggest % as it doesn't look like you are using it in either pattern, that is:\n%(?:\\* ([\\w\\d\\(\\),\\.\\'\\\"\\-\\:#|/ ]+)|(?<= @)(\\w+)(?: (.+))?)%\n", "The rea...
[ 1, 1 ]
[]
[]
[ "php", "python", "regex" ]
stackoverflow_0006973847_php_python_regex.txt
Q: cant find ReleaseCapture in opencv while using python? I am trying to release a cam capture which has been acquired by the API call camera = cv.CaptureFromCAM(-1) How can I release it. There is a function named "ReleaseCapture" but it has no python binding. Can anybody suggest any alternative? Thanks a lot...
cant find ReleaseCapture in opencv while using python?
I am trying to release a cam capture which has been acquired by the API call camera = cv.CaptureFromCAM(-1) How can I release it. There is a function named "ReleaseCapture" but it has no python binding. Can anybody suggest any alternative? Thanks a lot
[ "I found a similar answered question here \ncapture = cv.CaptureFromCAM(0)\nframe = cv.QueryFrame(capture)\n\n#some code ...\n\ndel(capture)\n\nbe carefull of using frame or another image captured from cam after deleting capture\nregards\n" ]
[ 8 ]
[]
[]
[ "capture", "opencv", "python" ]
stackoverflow_0006691546_capture_opencv_python.txt
Q: Find the numbers that can be made with addition and subtraction, using all numbers given I've profiled my application, and it spends 90% of its time in plus_minus_variations. The function finds ways to make various numbers given a list of numbers using addition and subtraction. For example: Input 1, 2 Output 1+2=...
Find the numbers that can be made with addition and subtraction, using all numbers given
I've profiled my application, and it spends 90% of its time in plus_minus_variations. The function finds ways to make various numbers given a list of numbers using addition and subtraction. For example: Input 1, 2 Output 1+2=3 1-2=-1 -1+2=1 -1-2=-3 This is my current code. I think it could be improved a lot in terms ...
[ "If it is ok not to get trace of number producing there is no reasons to recalculate sum of number combination every time. You can store intermediate results:\ndef combine(l,r):\n res = set()\n for x in l:\n for y in r:\n res.add( x+y )\n res.add( x-y )\n res.add( -x+y ...
[ 6, 5, 4, 2, 0, 0 ]
[]
[]
[ "algorithm", "performance", "python" ]
stackoverflow_0006971819_algorithm_performance_python.txt
Q: How to do a django select sql or statement? I'm not asking on how to do a raw sql. I'm thinking more in terms of the django queryset api. If I want to execute a sql like select * from table where id="1" or id="2" or id="3"; how would I do it using django queryset api? I know that if you chain filters together y...
How to do a django select sql or statement?
I'm not asking on how to do a raw sql. I'm thinking more in terms of the django queryset api. If I want to execute a sql like select * from table where id="1" or id="2" or id="3"; how would I do it using django queryset api? I know that if you chain filters together you can get AND. But how would you do OR? BTW how...
[ "Your query is the same as select * from table where id in ('1', '2', '3'); which using Django queryset will be: YourModel.objects.filter(id__in=['1', '3', '4']).\n" ]
[ 2 ]
[]
[]
[ "django", "django_queryset", "python", "sql" ]
stackoverflow_0006974520_django_django_queryset_python_sql.txt
Q: Python vs Javascript floating point arithmetic giving very different answers. What am I doing wrong? Python version | Javascript version | Whitepaper So, I'm working on a website to calculate Glicko ratings for two player games. It involves a lot of floating point arithmetic (square roots, exponents, division, all...
Python vs Javascript floating point arithmetic giving very different answers. What am I doing wrong?
Python version | Javascript version | Whitepaper So, I'm working on a website to calculate Glicko ratings for two player games. It involves a lot of floating point arithmetic (square roots, exponents, division, all the nasty stuff) and I for some reason am getting a completely different answer from the Python implement...
[ "typically you get errors like this where you are subtracting two similar numbers - then the normally insignificant differences between values become amplified. for example, if you have two values that are 1.2345 and 1.2346 in python, but 1.2344 and 1.2347 in javascript, then the differences are 1e-4 and 3 e-4 res...
[ 7, 2 ]
[]
[]
[ "floating_point", "javascript", "python" ]
stackoverflow_0006974625_floating_point_javascript_python.txt
Q: iterate through unicode strings and compare with unicode in python dictionary I have two python dictionaries containing information about japanese words and characters: vocabDic : contains vocabulary, key: word, value: dictionary with information about it kanjiDic : contains kanji ( single japanese character ), ...
iterate through unicode strings and compare with unicode in python dictionary
I have two python dictionaries containing information about japanese words and characters: vocabDic : contains vocabulary, key: word, value: dictionary with information about it kanjiDic : contains kanji ( single japanese character ), key: kanji, value: dictionary with information about it Now I would like to iterat...
[ "From your description of the problem, it sounds like vocab is an encoded str object, not a unicode object.\nFor concreteness, suppose vocab equals u'債務の天井' encoded in utf-8:\nIn [42]: v=u'債務の天井'\nIn [43]: vocab=v.encode('utf-8') # val['text']\nOut[43]: '\\xe5\\x82\\xb5\\xe5\\x8b\\x99\\xe3\\x81\\xae\\xe5\\xa4\\xa...
[ 11 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0006974510_python_unicode.txt
Q: detect circular dependencies in python I don't understand why the _ResolveDependencies method in DepsTree class can detect circular dependencies. Seems it can detect the situation if a requires b and e and b requires e, but it's not a circular dependencies. class DepsTree(object): """Represents the set of depend...
detect circular dependencies in python
I don't understand why the _ResolveDependencies method in DepsTree class can detect circular dependencies. Seems it can detect the situation if a requires b and e and b requires e, but it's not a circular dependencies. class DepsTree(object): """Represents the set of dependencies between source files.""" def __ini...
[ "Short version: _ResolveDependencies performs a depth-first traversal of the dependency tree, recording the path. If it encounters a node that is already in the path, this means there's a cycle.\n_ResolveDependencies traverses the dependency forest embodied by Source.requires. The active calls to _ResolveDependenci...
[ 2 ]
[]
[]
[ "circular_dependency", "google_closure_library", "python" ]
stackoverflow_0006974708_circular_dependency_google_closure_library_python.txt
Q: Plot with non-numerical data on x axis (for ex., dates) I'd like to plot numerical data against non numerical data, say something like this: import matplotlib.pyplot as pl x=['a','b','c','d'] y=[1,2,3,4] pl.plot(x,y) However, with matplotlib plot packages you get a warning that the data is not float (ValueError: ...
Plot with non-numerical data on x axis (for ex., dates)
I'd like to plot numerical data against non numerical data, say something like this: import matplotlib.pyplot as pl x=['a','b','c','d'] y=[1,2,3,4] pl.plot(x,y) However, with matplotlib plot packages you get a warning that the data is not float (ValueError: invalid literal for float(): a). In their 'How-to', they sug...
[ "Use the xticks function.\nimport matplotlib.pyplot as pl\nxticks=['a','b','c','d']\nx=[1,2,3,4]\ny=[1,2,3,4]\npl.plot(x,y)\npl.xticks(x,xticks)\npl.show()\n\n", "import matplotlib.pyplot as plt\nx = ['a','b','c','d']\ny = [1,2,3,4]\nplt.plot(y)\nplt.xticks(range(len(x)), x)\nplt.show()\n\n\nOn a side note, dates...
[ 15, 13 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0006974847_matplotlib_python.txt
Q: I can't figure out the problem in this code about python, need help I'm going to create a game, user put in the name and bet number and my program is gonna show the bet number is greater than the sum of 5 random dice and show each picture of them. I know there is something wrong but I dont know where import cgi im...
I can't figure out the problem in this code about python, need help
I'm going to create a game, user put in the name and bet number and my program is gonna show the bet number is greater than the sum of 5 random dice and show each picture of them. I know there is something wrong but I dont know where import cgi import random formData = cgi.FieldStorage() playerName = formData["name"]....
[ "The line\ndie%i = random.randint(1,6)%index\n\nIs not valid python syntax. It's cousin a few lines below:\ntotal = die%i + die%i\n\nWill not give you the results you're expecting; the %'s will be treated as mod operators. That loop should be something more like:\nfor die in range(theLength):\n val = random.ran...
[ 2, 1, 0 ]
[]
[]
[ "python", "xhtml" ]
stackoverflow_0006975015_python_xhtml.txt
Q: What is this error mean in Python and XHTML? It keep showing this error Traceback (most recent call last): File "/home/zca22/public_html/Lab_Assn_5/Scripts/dice.py", line 7, in <module> playerGuess = int(formData["guess"].value) File "/usr/lib/python2.6/cgi.py", line 541, in __getitem__ raise KeyError,...
What is this error mean in Python and XHTML?
It keep showing this error Traceback (most recent call last): File "/home/zca22/public_html/Lab_Assn_5/Scripts/dice.py", line 7, in <module> playerGuess = int(formData["guess"].value) File "/usr/lib/python2.6/cgi.py", line 541, in __getitem__ raise KeyError, key KeyError: 'guess' I don't know what's wrong ...
[ "It looks like you're not POSTing it a guess value. You should have something like this in the page before:\n<form action=\"/cgi-bin/guess.py\" method=\"post\">\n <dl>\n <dt><label for=\"name_field\">Name:</label></dt>\n <dd><input type=\"text\" id=\"name_field\" name=\"name\" required=\"required\"...
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "python", "xhtml" ]
stackoverflow_0006975248_python_xhtml.txt
Q: How can I scramble a word with a factor? I would like to scramble a word with a factor. The bigger the factor is, the more scrambled the word will become. For example, the word "paragraphs" with factor of 1.00 would become "paaprahrgs", and it will become "paargarphs" with a factor of 0.50. The distance from the o...
How can I scramble a word with a factor?
I would like to scramble a word with a factor. The bigger the factor is, the more scrambled the word will become. For example, the word "paragraphs" with factor of 1.00 would become "paaprahrgs", and it will become "paargarphs" with a factor of 0.50. The distance from the original letter position and the number of scra...
[ "You could use the factor as a number of shuffling chars in the string around.\nAs the factor seem's to be between 0 and 1, you can multiply the factor with the string's length.\nfrom random import random\n\ndef shuffle(string, factor):\n string = list(string)\n length = len(string)\n if length < 2...
[ 3, 2, 1, 1 ]
[ "You could do a for-loop that counts down to 0. \nConvert the String into a Char-Array and use a RNG to choose 2 letters to swap.\n" ]
[ -1 ]
[ "python", "scramble" ]
stackoverflow_0006975437_python_scramble.txt
Q: Can I weak reference methods? Possible Duplicate: Why doesn't the weakref work on this bound method? A bit of context: I was trying to implement an Listener (or Observer, same thing) pattern: An EventManager keeps a list of all the Listeners handlers interested in an Event. For example, a Listener object would ...
Can I weak reference methods?
Possible Duplicate: Why doesn't the weakref work on this bound method? A bit of context: I was trying to implement an Listener (or Observer, same thing) pattern: An EventManager keeps a list of all the Listeners handlers interested in an Event. For example, a Listener object would have a onEndOfTheWorldEvent method...
[ "Let's say you want weakrefs on a method \"meth\".\nYou can get weakrefs on it like this\nweak_obj = weakref.ref(meth.im_self)\nweak_func = weakref.ref(meth.im_func)\n\nSo, you can deref it like that\nobj = weak_obj()\nfunc = weak_func()\n\nand get \"meth\" back with\nmeth = getattr(obj, func.__name__)\n\n", "lis...
[ 8, 2 ]
[]
[]
[ "python", "weak_references" ]
stackoverflow_0006975508_python_weak_references.txt
Q: Python operating on multiple data arrays in a rolling window consider the following code: class MyClass(object): def __init__(self): self.data_a = np.array(range(100)) self.data_b = np.array(range(100,200)) self.data_c = np.array(range(200,300)) def _method_i_do_not_have_access_t...
Python operating on multiple data arrays in a rolling window
consider the following code: class MyClass(object): def __init__(self): self.data_a = np.array(range(100)) self.data_b = np.array(range(100,200)) self.data_c = np.array(range(200,300)) def _method_i_do_not_have_access_to(self, data, window, func): output = np.empty(np.size(da...
[ "The question is how would _my_func know on which indizes to operate? If you know the indizes in advance when calling your function, the simplest approach would be just using a lambda: lambda val: self._my_func(self.a, self.b, index, val) with _my_func obviously changed to accommodate the additional parameters.\nSi...
[ 1, 1, 0, 0 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0006974034_arrays_numpy_python.txt
Q: Efficient iteration over 3D array? I am using Python and Numpy to do some data analysis. I have a large 3D matrix (NxNxN), where each cell is again a matrix, this time a 3x3 matrix. Calling the matrix data, it looks like this: data[N,N,N,3,3] I need to find the eigenvalues of all the 3x3 matrices, and for that ...
Efficient iteration over 3D array?
I am using Python and Numpy to do some data analysis. I have a large 3D matrix (NxNxN), where each cell is again a matrix, this time a 3x3 matrix. Calling the matrix data, it looks like this: data[N,N,N,3,3] I need to find the eigenvalues of all the 3x3 matrices, and for that I use Numpy's eigvals routine, but it ta...
[ "itertools.product is nicer than nested loops, aesthetically speaking. But I don't think it will make your code that much faster. My testing suggests that iteration is not your bottleneck. \n>>> bigdata = numpy.arange(256 * 256 * 256 * 3 * 3).reshape(256, 256, 256, 3, 3)\n>>> %timeit numpy.linalg.eigvals(bigdata[10...
[ 5, 4, 2 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0006973849_numpy_python.txt
Q: How can I create a list of sums of random numbers in Python? Can I write a for loop to get a series of sums of random numbers? I'm new with it. I have no clue. A: import random sum(random.random() for i in range(how_many_random_numbers_do_you_want)) A: oh for goodness sake. the other answers here are trying t...
How can I create a list of sums of random numbers in Python?
Can I write a for loop to get a series of sums of random numbers? I'm new with it. I have no clue.
[ "import random\nsum(random.random() for i in range(how_many_random_numbers_do_you_want))\n\n", "oh for goodness sake. the other answers here are trying too hard to be cool.\nif you are new to this:\nfrom random import random\ntotal = 0\nfor i in range(10):\n total = total + random()\nprint total\n\n[edit: cha...
[ 3, 3, 1, 0, 0 ]
[]
[]
[ "python", "random" ]
stackoverflow_0006974776_python_random.txt
Q: Finding Tags And Text In BeautifulSoup I'm having some trouble formulating a findAll query for BeautifulSoup that'll do what I want. Previously, I was using findAll to extract only the text from some html, essentially stripping away all the tags. For example, if I had: <b>Cows</b> are being abducted by aliens acco...
Finding Tags And Text In BeautifulSoup
I'm having some trouble formulating a findAll query for BeautifulSoup that'll do what I want. Previously, I was using findAll to extract only the text from some html, essentially stripping away all the tags. For example, if I had: <b>Cows</b> are being abducted by aliens according to the <a href="www.washingtonpost.com...
[ "Note: The BeautifulSoup.findAll is a search API. The first named argument of findAll which is name can be used to restrict the search to a given set of tags. With just a single findAll it is not possible to select all text between tags and at the same time select the text and tag for <a>. So I came up with the bel...
[ 4 ]
[]
[]
[ "beautifulsoup", "html", "python" ]
stackoverflow_0006975757_beautifulsoup_html_python.txt
Q: delegate from one view to another I am using Pyramid with different views. I am wondering if it is possible to "delegate" parts of a views job to another view (another route). For example: http://localhost:6543/sample_project/testruns/testrun001/report.html?action=edit => delegate to: http://localhost:6543/sample...
delegate from one view to another
I am using Pyramid with different views. I am wondering if it is possible to "delegate" parts of a views job to another view (another route). For example: http://localhost:6543/sample_project/testruns/testrun001/report.html?action=edit => delegate to: http://localhost:6543/sample_project/testruns/testrun001/report.jso...
[ "You can directly call views, they simply won't be going through the pyramid router mechanism which applies the permission and other such parameters to the view. Presumably if you are trying to call it, however, you already know these things.\nIn reality, you probably just want to refactor the common functionality ...
[ 1 ]
[]
[]
[ "pyramid", "python" ]
stackoverflow_0006972674_pyramid_python.txt
Q: Why does a list slice [:n] allow using a list with fewer than n elements in a loop? Possible Duplicate: good primer for python slice notation I have this Python code; items is a list of tuples: # Print the first 20 for item in items[:20]: print item[0], item[1] It prints the first twenty elements of the lis...
Why does a list slice [:n] allow using a list with fewer than n elements in a loop?
Possible Duplicate: good primer for python slice notation I have this Python code; items is a list of tuples: # Print the first 20 for item in items[:20]: print item[0], item[1] It prints the first twenty elements of the list. If the list has fewer than twenty elements, it still works, but I don't understand wh...
[ "If the passed value exceeds the number of list elements, slice is limited by the length of the list.\nl = range(1,2)\nl[:10] == l\n\n" ]
[ 4 ]
[]
[]
[ "list", "python", "slice" ]
stackoverflow_0006976076_list_python_slice.txt
Q: Subclassing and built-in methods in Python For convenience, I wanted to subclass socket to create an ICMP socket: class ICMPSocket(socket.socket): def __init__(self): socket.socket.__init__( self, socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("i...
Subclassing and built-in methods in Python
For convenience, I wanted to subclass socket to create an ICMP socket: class ICMPSocket(socket.socket): def __init__(self): socket.socket.__init__( self, socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp")) def sendto(self, data, host): ...
[ "I know this doesn't answer your question, but you could put the socket into an instance variable. This is what Nobody also suggested in the comments.\nclass ICMPSocket():\n def __init__(self):\n self.s = socket.socket(\n socket.AF_INET,\n socket.SOCK_RAW,\n socket.getprot...
[ 6, 3 ]
[]
[]
[ "python", "subclassing" ]
stackoverflow_0006976094_python_subclassing.txt
Q: Python Tkinter canvas.xview units How are the 'units' (what) from the Tkinter canvas scrolling methods xview(SCROLL, step, what) and yview(SCROLL, step, what) defined? Is it defined in pixels? Is it possible to change it (for a slower scrolling for example)? For a better context please see the code here. Thanks in...
Python Tkinter canvas.xview units
How are the 'units' (what) from the Tkinter canvas scrolling methods xview(SCROLL, step, what) and yview(SCROLL, step, what) defined? Is it defined in pixels? Is it possible to change it (for a slower scrolling for example)? For a better context please see the code here. Thanks in advance.
[ "for slower scrolling, you can play around with the xscrollincrement & yscrollincrement options of the Canvas:\nfrom Tkinter import *\n\nroot = Tk()\nc = Canvas(root, scrollregion=(0,0,500,500), height=200, width=200)\ns = Scrollbar(root, command=c.yview)\nc.pack(side=LEFT)\ns.pack(side=RIGHT, fill=Y)\nc.configure(...
[ 8, 3 ]
[]
[]
[ "python", "scroll", "tkinter" ]
stackoverflow_0006863921_python_scroll_tkinter.txt
Q: how do you style a form already inside django I'm using django-registration. I'd like to update the AuthenticationForm in 'django.contrib.auth.forms'. Specifically, I would like to pass the 'attrs' dict to add a few attributes. How do I update a form that comes with django? A: You can use the views that come wit...
how do you style a form already inside django
I'm using django-registration. I'd like to update the AuthenticationForm in 'django.contrib.auth.forms'. Specifically, I would like to pass the 'attrs' dict to add a few attributes. How do I update a form that comes with django?
[ "You can use the views that come with auth and override the form parameter with your own form:\ndjango.contrib.auth.views.login(request[, template_name, redirect_field_name, authentication_form])\n\nMore info here.\n", "The standard way is to subclass AuthenticationForm, change the attrs in constructor, pass the ...
[ 2, 1 ]
[]
[]
[ "django", "django_registration", "python" ]
stackoverflow_0006976205_django_django_registration_python.txt
Q: Assigning multiple variable values to a single variable in Python I have a number of variables which are set and later in my code I want to use these variables together as one single variable with a . separation. For example Release=1 Build=2 ServicePack=3 Hotfix=4 Directory=Release.Build.ServicePack.Hotfix I un...
Assigning multiple variable values to a single variable in Python
I have a number of variables which are set and later in my code I want to use these variables together as one single variable with a . separation. For example Release=1 Build=2 ServicePack=3 Hotfix=4 Directory=Release.Build.ServicePack.Hotfix I understand that the above line will not work but I'm not sure how to join...
[ "Directory = '.'.join(str(x) for x in (Release, Build, ServicePack, Hotfix))\n\nTurn each variable into a string. Join them together with a '.' in between. \nos.path.join(\"path/to/base\", Directory)\n\nwill work fine, resulting in\npath/to/base/Release.Build.ServicePack.Hotfix\n\nIf I were you, I'd either use all ...
[ 8 ]
[]
[]
[ "path", "python", "string" ]
stackoverflow_0006976393_path_python_string.txt
Q: Order results based on select options? Like 'best match', 'time ending soonest', etc. Using django 1.3 You know the select options like on ebay where they have 'best match', 'time ending soonest', etc. And when you choose an option the pages refreshes and returns the results in that order. How do you do that? So...
Order results based on select options? Like 'best match', 'time ending soonest', etc. Using django 1.3
You know the select options like on ebay where they have 'best match', 'time ending soonest', etc. And when you choose an option the pages refreshes and returns the results in that order. How do you do that? So far this is my idea, I was going to store a session variable for the user and base on what the session vari...
[ "You could just set the ordering via GET. The template would have something like\n<a href=\"?ordering=best\">Best match</a>\n<a href=\"?ordering=soonest\">Ending soonest</a>\n\nThe view would check request.GET and sort appropriately.\n" ]
[ 1 ]
[]
[]
[ "django", "jquery", "python", "select", "session" ]
stackoverflow_0006976395_django_jquery_python_select_session.txt
Q: Package in pypi not installable by pip Why can't I use $ sudo pip install facebook-python-sdk even with facebook-python-sdk package in pypi? log: http://dpaste.com/hold/589044/ A: Not sure what's going on there, but you can use pip to install from the github repo: pip install git+https://github.com/facebook/pyt...
Package in pypi not installable by pip
Why can't I use $ sudo pip install facebook-python-sdk even with facebook-python-sdk package in pypi? log: http://dpaste.com/hold/589044/
[ "Not sure what's going on there, but you can use pip to install from the github repo:\npip install git+https://github.com/facebook/python-sdk.git\\#egg=facebook-python-sdk\n\nI usually use pip install -e which makes pip symlink the package for you, so you can edit the repo, update it etc, and get the latest changes...
[ 3 ]
[]
[]
[ "facebook", "pip", "python" ]
stackoverflow_0006976548_facebook_pip_python.txt
Q: Python: Best Dictionary implementation I have few python scripts where I am storing 5-10 million string key value pairs in a dictionary and I query this dictionary around 5-10 million times. I noticed that python dict is not performing very well. Is there any other implementation best suited for string keys. Edit:...
Python: Best Dictionary implementation
I have few python scripts where I am storing 5-10 million string key value pairs in a dictionary and I query this dictionary around 5-10 million times. I noticed that python dict is not performing very well. Is there any other implementation best suited for string keys. Edit: I am having two large lists of person names...
[ "Wow. A hashmap (dictionary) might not be the structure you're looking for.\nInstead of using strings, try a representation that can give you good and fast hashing. Or are you really storing strings? If so, scracth the \"might\" in the previous sentence.\nCould you give us details about the problem you're tackling?...
[ 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "performance", "python" ]
stackoverflow_0005483121_performance_python.txt
Q: Overriding the logging class in WSGI does not work I have implemented my own custom Logger for my django site: class SpecialLogger(logging.Logger): def __init__(self, name, level=logging.DEBUG): logging.Logger.__init__(self, name, level) def special(self, msg, *args, **kwargs): self.log(se...
Overriding the logging class in WSGI does not work
I have implemented my own custom Logger for my django site: class SpecialLogger(logging.Logger): def __init__(self, name, level=logging.DEBUG): logging.Logger.__init__(self, name, level) def special(self, msg, *args, **kwargs): self.log(self.level, msg, *args, **kwargs) In my wsgi file, I have...
[ "The setLoggerClass function sets the class to be used for all loggers instantiated after the call returns, but any loggers created before the call will still be logging.Logger. You could append a line in your wsgi file to confirm that the correct class is being used, e.g.\nimport logging\nfrom testbed.utils import...
[ 0 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0006955980_logging_python.txt
Q: Most pythonic way of assigning keyword arguments using a variable as keyword? What is the most pythonic way to get around the following problem? From the interactive shell: >>> def f(a=False): ... if a: ... return 'a was True' ... return 'a was False' ... >>> f(a=True) 'a was True' >>> kw = 'a' >>...
Most pythonic way of assigning keyword arguments using a variable as keyword?
What is the most pythonic way to get around the following problem? From the interactive shell: >>> def f(a=False): ... if a: ... return 'a was True' ... return 'a was False' ... >>> f(a=True) 'a was True' >>> kw = 'a' >>> val = True >>> f(kw=val) Traceback (most recent call last): File "<stdin>", lin...
[ "Use keyword argument unpacking:\n>>> kw = {'a': True}\n\n>>> f(**kw)\n<<< 'a was True'\n\n", "In many circumstances you can just use\nf(kw)\n\nas keyword arguments don't have to be specified as keywords, if you specify all arguments before them.\nPython 3 has a syntax for keyword only arguments, but that's not w...
[ 43, 7 ]
[]
[]
[ "keyword_argument", "python" ]
stackoverflow_0006976658_keyword_argument_python.txt
Q: How do I customize the python side of my Django models? I have a Django application that defines a one-to-many model relationship. The models look like this: from django.db import models # Create your models here. class StreamNetwork(models.Model): name = models.CharField(max_length=50) def __unicode__(s...
How do I customize the python side of my Django models?
I have a Django application that defines a one-to-many model relationship. The models look like this: from django.db import models # Create your models here. class StreamNetwork(models.Model): name = models.CharField(max_length=50) def __unicode__(self): return self.name class Stream(models.Model): ...
[ "Keep in mind that a QuerySet is more than just a simple database query, so the \"expected result\" should be that it contains additional information. One simple way to do what you want (and I'd say it's a Django Way) is to define a model manager that returns only what you want. Something like:\nimport simplejson...
[ 1, 0, 0 ]
[]
[]
[ "django", "models", "mysql", "python" ]
stackoverflow_0006975952_django_models_mysql_python.txt
Q: Getting and trapping HTTP response using Mechanize in Python I am trying to get the response codes from Mechanize in python. While I am able to get a 200 status code anything else isn't returned (404 throws and exception and 30x is ignored). Is there a way to get the original status code? Thanks A: Errors will t...
Getting and trapping HTTP response using Mechanize in Python
I am trying to get the response codes from Mechanize in python. While I am able to get a 200 status code anything else isn't returned (404 throws and exception and 30x is ignored). Is there a way to get the original status code? Thanks
[ "Errors will throw an exception, so just use try:...except:... to handle them.\nYour Mechanize browser object has a method set_handle_redirect() that you can use to turn 30x redirection on or off. Turn it off and you get an error for redirects that you handle just like you handle any other error:\n>>> from mechaniz...
[ 13, 0 ]
[]
[]
[ "mechanize", "python" ]
stackoverflow_0002673022_mechanize_python.txt
Q: How to manage a python dictionary with three items and add the last one? I have a dictionary in python like this: x = {country:{city:population}:......} and I want to create a new dictionary like y = {country:cities_population}, where cities_population adds all the population in every city in every country and I r...
How to manage a python dictionary with three items and add the last one?
I have a dictionary in python like this: x = {country:{city:population}:......} and I want to create a new dictionary like y = {country:cities_population}, where cities_population adds all the population in every city in every country and I really don't know how to do it. I tried this: for country in x: for city, popu...
[ "Well, how about:\n y = { }\n for country, cities in x.iteritems():\n y[country] = sum(cities.values())\n\n", "I'm going to assume you want to sum up more than just the city populations for each country:\n>>> attributes = ['population', 'gdp', 'murders']\n>>> x = {'usa': {'chicago': dict(zip(attributes, [10,...
[ 2, 1, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0006976908_dictionary_python.txt
Q: AppEngine - When to use a parent relationship? I'm trying to understand when to use an entity "parent" on GAE. Is this only useful for querying (ie get all the Foo objects where the parent == someObj) or does the child have access to the parent entity much like a ReferenceProperty? When is it better to use the pa...
AppEngine - When to use a parent relationship?
I'm trying to understand when to use an entity "parent" on GAE. Is this only useful for querying (ie get all the Foo objects where the parent == someObj) or does the child have access to the parent entity much like a ReferenceProperty? When is it better to use the parent vs ReferenceProperty?
[ "The only time you should use entity groups (which is what all entities with a common parent form) is for transactional safety. If you need to update multiple records in a transaction, they all need to have the same root entity. The reason you wouldn't just put all your entities under a single parent is because upd...
[ 5, 1 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0006976443_google_app_engine_google_cloud_datastore_python.txt
Q: Coverting a recursive function to a tail recursive one in python As an exercise, i implemented the map function using recursion in python as follows: #map function that applies the function f on every element of list l and returns the new list def map(l,f): if l == []: return [] else: retu...
Coverting a recursive function to a tail recursive one in python
As an exercise, i implemented the map function using recursion in python as follows: #map function that applies the function f on every element of list l and returns the new list def map(l,f): if l == []: return [] else: return [f(l[0])] + map(l[1:],f) I am aware of the fact that python does n...
[ "Tail recursion means you must be directly returning the result of a recursive call, with no further manipulation.\nThe obvious recursion in map is to compute the function on one element of the list, then use a recursive call to process the rest of the list. However, you need to combine the result of processing one...
[ 7, 0, 0, 0 ]
[]
[]
[ "python", "recursion", "tail_recursion" ]
stackoverflow_0006976906_python_recursion_tail_recursion.txt
Q: Tkinter: How do you place a text field that you can update at whim? I want to be able to manipulate an integer that will be displayed in real-time in the Tk window. I tried: xp = StringVar() Label(master, textvariable=xp).pack() xp.set(0) and then later, I tried: xp.set(xp+1) But it failed badly on that line, wi...
Tkinter: How do you place a text field that you can update at whim?
I want to be able to manipulate an integer that will be displayed in real-time in the Tk window. I tried: xp = StringVar() Label(master, textvariable=xp).pack() xp.set(0) and then later, I tried: xp.set(xp+1) But it failed badly on that line, with the message: Exception in Tkinter callback File "/usr/lib/.../Tkinter....
[ "Looks to me like the scope of the xp variable in the first snippet does not include the second snippet. This means that they're really different variables (that happen to have a very similar name) and so the second snippet is being run without the handle to the StringVar accessible, which isn't going to work.\n" ]
[ 3 ]
[]
[]
[ "callback", "nameerror", "python", "tkinter" ]
stackoverflow_0006977123_callback_nameerror_python_tkinter.txt
Q: outputting data as dictionaries in a new python file I like to store my data after a longish python program as dictionaries in a new script. This then allows me to import the program (and hence data) easily for further manipulation. I write something like this (an old example): file = open(p['results']+'asa_contac...
outputting data as dictionaries in a new python file
I like to store my data after a longish python program as dictionaries in a new script. This then allows me to import the program (and hence data) easily for further manipulation. I write something like this (an old example): file = open(p['results']+'asa_contacts.py','w') print>>file, \ ''' \''' This file stores the c...
[ "Unless there's a specific reason that you need source code -- and I suspect there isn't, you just want to serialize and deserialize data from disk -- a better option would be Python's pickle module.\n", "I am not sure if this is what you are looking for but try the inbuilt function repr.\nrepr(a)\n\n", "Lossy'...
[ 2, 1, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0006975808_dictionary_python.txt
Q: PyQT4 QWebView not resizing correctly I have a QWebview in a grid layout, along with other widgets. When the user resizes the window, the QWebview doesn't resize, but the other widgets do. How can I make the QWebview resize correctly? A: Most likely you're not using correct sizePolicy. Take a look here http://do...
PyQT4 QWebView not resizing correctly
I have a QWebview in a grid layout, along with other widgets. When the user resizes the window, the QWebview doesn't resize, but the other widgets do. How can I make the QWebview resize correctly?
[ "Most likely you're not using correct sizePolicy. Take a look here http://doc.qt.nokia.com/4.6/layout.html\nDoes using other widget in place of QWebView change anything?\n", "in the dialog class's resizeEvent, one that extends QDialog, call webView->setGeometry, and this->resize, this->update.\nhint: check if siz...
[ 0, 0 ]
[]
[]
[ "grid", "pyqt4", "python", "qwebview", "resize" ]
stackoverflow_0002938874_grid_pyqt4_python_qwebview_resize.txt
Q: most easy, reliable, cheap way to deploy this python (workhorse) app with a PHP frontend? I am developing a small part of a PHP application with some python code. The python code runs like an equivalent of a servlet (listens and responds to HTTP on port 8765) on localhost. The PHP app calls it like: PHP'S_CURL("ht...
most easy, reliable, cheap way to deploy this python (workhorse) app with a PHP frontend?
I am developing a small part of a PHP application with some python code. The python code runs like an equivalent of a servlet (listens and responds to HTTP on port 8765) on localhost. The PHP app calls it like: PHP'S_CURL("http://localhost:8765/search?term=electrical+design") The pyth-let is written with the BaseHTTPS...
[ "You can use flup to serve your python app with fastcgi. I've also used gunicorn to deploy python webapps along with supervisor and found that to be a good approach - and even easier to setup.\n" ]
[ 3 ]
[]
[]
[ "hosting", "python" ]
stackoverflow_0006939561_hosting_python.txt
Q: Django Form Preview with google app engine I still didn't get django form preview with google app engine to work. I didn't see a working example and my attempts to use django form preview with google app engine failed since I couldn't translate the request handler usage from django to gae. I'm getting a form previ...
Django Form Preview with google app engine
I still didn't get django form preview with google app engine to work. I didn't see a working example and my attempts to use django form preview with google app engine failed since I couldn't translate the request handler usage from django to gae. I'm getting a form preview but it won't render: <html><body><for...
[ "The Django documentation for FormPreview can be found here. It makes it clear that FormPreview is intended to be subclassed and used as a handler, which you can't do in webapp - it's specific to the Django framework. You certainly can't just instantiate a FormPreview object with your form and expect the string rep...
[ 1 ]
[]
[]
[ "django_forms", "google_app_engine", "python" ]
stackoverflow_0006951732_django_forms_google_app_engine_python.txt
Q: tkinter: How do I fix my window so that the window doesn't resize when my content resizes? I have a feeling it is to do with my pack() function. The window always "packs" the content in to the smallest size it can possibly be, but because the content is always changing, the window size is always changing and this ...
tkinter: How do I fix my window so that the window doesn't resize when my content resizes?
I have a feeling it is to do with my pack() function. The window always "packs" the content in to the smallest size it can possibly be, but because the content is always changing, the window size is always changing and this moves the button, which is centred. I want the window to stay at a certain size the whole time, ...
[ "You can do:\nroot.geometry('200x200')\nroot.mainloop()\n\n" ]
[ 4 ]
[]
[]
[ "pack", "python", "resize", "tkinter" ]
stackoverflow_0006977866_pack_python_resize_tkinter.txt
Q: SQLAlchemy mapped_collection on table itself? I was wondering if it was possible to somehow fetch the objects from a table and get them returned indexed by an arbitrary value, similar to mapped_collection. I realize that this is easy to work around (And that I am already doing). But I was just wondering if this wa...
SQLAlchemy mapped_collection on table itself?
I was wondering if it was possible to somehow fetch the objects from a table and get them returned indexed by an arbitrary value, similar to mapped_collection. I realize that this is easy to work around (And that I am already doing). But I was just wondering if this was possible.
[ "what's wrong with :\nmy_mapping = dict(Session.query(MyClass.somekey, MyClass))\n\n?\nI do that all the time to make a quick cache of something.\n" ]
[ 1 ]
[]
[]
[ "collections", "python", "sqlalchemy" ]
stackoverflow_0006969092_collections_python_sqlalchemy.txt
Q: How to create a basic semantic search in python I want to write a basic semantic web crawler using Python, I know that semantic apps use RDF files, but what else? I have some Python RDF modules installed and I started learning how they work. Could you introduce me to the technologies and techniques used in a sema...
How to create a basic semantic search in python
I want to write a basic semantic web crawler using Python, I know that semantic apps use RDF files, but what else? I have some Python RDF modules installed and I started learning how they work. Could you introduce me to the technologies and techniques used in a semantic application?
[ "The next things you might want to learn are:\n\nembedding samantic data in HTML - RDFa, microformats, microdata. Some stats: microformats and RDFa deployment across the Web via DAM.co.uk:\n\nquerying RDF data - SPARQL\nmost popular ontologies currently in use\nlist of available SPARQL endpoints\n\nYou can find som...
[ 5 ]
[]
[]
[ "python", "rdf", "search_engine", "semantic_web", "semantics" ]
stackoverflow_0006974900_python_rdf_search_engine_semantic_web_semantics.txt
Q: How to map multiple foreign keys to the same parent in SQLAlchemy? Upon adding a second foreign key to the same table I get the following error: Please specify the 'onclause' of this join explicitly. How can I specify this relationship? class Parent(Base): First = Column(Integer, ForeignKey('Child.Ex1')) ...
How to map multiple foreign keys to the same parent in SQLAlchemy?
Upon adding a second foreign key to the same table I get the following error: Please specify the 'onclause' of this join explicitly. How can I specify this relationship? class Parent(Base): First = Column(Integer, ForeignKey('Child.Ex1')) Second = Column(Integer, ForeignKey('Child.Ex2')) class Child(Base): ...
[ "(ed. note: pep8 recommends naming class attributes starting with lowercase...just a convention)\nclass Parent(Base):\n __tablename__ = \"Parent\"\n id = Column(Integer, primary_key=True)\n first = Column(\"First\", Integer, ForeignKey('Child.Ex1'))\n second = Column(\"Second\", Integer, ForeignKey('Chi...
[ 1 ]
[]
[]
[ "clause", "foreign_keys", "python", "sqlalchemy" ]
stackoverflow_0006819824_clause_foreign_keys_python_sqlalchemy.txt
Q: Problem with macports picking up wrong python I previously installed Python in /opt/local/Library/Frameworks/Python.framework/Versions/2.6/bin/python2.6. then after the Lion update I installed it again in /System/Library/Frameworks/Python.framework/Versions/2.6/bin/python2.6. But when I install any Python package ...
Problem with macports picking up wrong python
I previously installed Python in /opt/local/Library/Frameworks/Python.framework/Versions/2.6/bin/python2.6. then after the Lion update I installed it again in /System/Library/Frameworks/Python.framework/Versions/2.6/bin/python2.6. But when I install any Python package using MacPorts, the installation fails with the fol...
[ "What do you mean by you installed Python 2.6 again in /System/Library/Frameworks/Python.framework/Versions/2.6/bin/python2.6? That's the location of the Apple-supplied Python 2.6 in Lion. There are also Apple-suppled Python 2.7 and 2.5 versions in that framework. Do not modify or delete anything in /System/Libr...
[ 2, 0 ]
[]
[]
[ "macos", "macports", "python" ]
stackoverflow_0006977836_macos_macports_python.txt
Q: How to install SSL for python 2.5 on Debian Linux? Question How do I install SSL for Python 2.5 on Debian? I have tried: sudo easy_install ssl But getting: $ python setup.py build looking for /usr/include/openssl/ssl.h looking for /usr/include/krb5.h running build running build_py running build_ext building 'ssl....
How to install SSL for python 2.5 on Debian Linux?
Question How do I install SSL for Python 2.5 on Debian? I have tried: sudo easy_install ssl But getting: $ python setup.py build looking for /usr/include/openssl/ssl.h looking for /usr/include/krb5.h running build running build_py running build_ext building 'ssl._ssl2' extension creating build/temp.linux-i686-2.5 crea...
[ "For reference, you must install libbluetooth-dev.\n", "In fact, you shouldn't compile your own version of python ssl module for several reasons:\n\nyou won't get automatic security updates of your python ssl module;\nyou won't get smooth upgrade path if you decide to upgrade Debian system on your server.\n\nThe ...
[ 8, 1 ]
[]
[]
[ "installation", "python", "ssl" ]
stackoverflow_0003241658_installation_python_ssl.txt
Q: simple instantiations of python classes Can you please explain why 'hello world' isn't returned below? What do I need to modify for it to be expressed properly when called? Thanks. >>> class MyClass: ... i=12345 ... def f(self): ... return 'hello world' ... >>> x=MyClass() >>> x.i 12345 >>> x....
simple instantiations of python classes
Can you please explain why 'hello world' isn't returned below? What do I need to modify for it to be expressed properly when called? Thanks. >>> class MyClass: ... i=12345 ... def f(self): ... return 'hello world' ... >>> x=MyClass() >>> x.i 12345 >>> x.f <bound method MyClass.f of <__main__.MyClas...
[ "f is a method, so you need to call it. i.e. x.f()\nIt's no different than if you define a function without the class:\ndef f():\n return 'something'\n\nIf you just refer to f, you'll get the function itself\nprint f\n\nyields <function f at 0xdcc2a8>, while\nprint f()\n\nyields \"something\".\n", "When inside...
[ 8, 5 ]
[]
[]
[ "python" ]
stackoverflow_0006978123_python.txt
Q: Using web.py on Appengine I am looking for a simple python web framework which runs both as standalone and on Appengine. I would like to write the app in such a way that i can switch between standalone and Appengine based on the deployment configuration. Standalone will be using RDBMS. When i checked web.py looked...
Using web.py on Appengine
I am looking for a simple python web framework which runs both as standalone and on Appengine. I would like to write the app in such a way that i can switch between standalone and Appengine based on the deployment configuration. Standalone will be using RDBMS. When i checked web.py looked simple and promising. I have t...
[ "\nDoes web.py work well on Appengine?\n\nYes it does work pretty well, it's compact and very easy to use.\n\nIs there any major known gotchas?\n\nWeb.py does not offer any Data Abstraction Layer compatible with GAE; that means that in order to switch from a RDBMS to a NoSQL database, you have to create by yourself...
[ 4, 3, 1, 0 ]
[]
[]
[ "deployment", "google_app_engine", "python", "web.py" ]
stackoverflow_0006943615_deployment_google_app_engine_python_web.py.txt
Q: 3D Rendering in Google App Engine Is it possible to render any kind of 3D images in Google App Engine (with Backends)? I'm looking for a Python solution, but I will learn Java if needed. A: App Engine doesn't currently support C modules on the Python runtime. As a result, any rendering code would have to be writ...
3D Rendering in Google App Engine
Is it possible to render any kind of 3D images in Google App Engine (with Backends)? I'm looking for a Python solution, but I will learn Java if needed.
[ "App Engine doesn't currently support C modules on the Python runtime. As a result, any rendering code would have to be written entirely in Python, and would be very, very slow. You couldn't take advantage of a GPU, either, since the runtime doesn't supply one.\nYour best option, if you care at all about efficiency...
[ 3 ]
[]
[]
[ "3d", "google_app_engine", "java", "python" ]
stackoverflow_0006941528_3d_google_app_engine_java_python.txt
Q: Python Server for multiple clients with or without XMLRPC I made a set of XMLRPC client-server programs in python and set up a little method for authenticating my clients. However, after coding pretty much the whole thing, I realized that once a client was authenticated, the flag I had set for it was global in my ...
Python Server for multiple clients with or without XMLRPC
I made a set of XMLRPC client-server programs in python and set up a little method for authenticating my clients. However, after coding pretty much the whole thing, I realized that once a client was authenticated, the flag I had set for it was global in my class i.e. as long as one client is authenticated, all clients ...
[ "Something like this would work:\nclass SomeClass(object):\n authenticated = {}\n def authenticate(self, username, password):\n #do something here\n if authenticate(username, password):\n # make unique token can probably be just a hash\n # of the millisecond time and the us...
[ 1, 0 ]
[]
[]
[ "multithreading", "python", "xml_rpc" ]
stackoverflow_0006978204_multithreading_python_xml_rpc.txt
Q: Python function argument of predicate type a=b Pardon my Python skill or the lack of it. I saw some methods calls of the form auth_req = urllib2.Request(auth_uri, data=authreq_data) If I put in just authreq_data I get an error. What is the correct technical definition for this type of method argument? Is it a boo...
Python function argument of predicate type a=b
Pardon my Python skill or the lack of it. I saw some methods calls of the form auth_req = urllib2.Request(auth_uri, data=authreq_data) If I put in just authreq_data I get an error. What is the correct technical definition for this type of method argument? Is it a boolean/predicate type?
[ "They're called keyword arguments.\nYou can use them without specifying the keyword, so long as you also pass all the arguments before them.\nThe signature of urrlib2.Request is\nurllib2.Request(url[, data][, headers][, origin_req_host][, unverifiable])\n\nSo as long as you specify the url, auth_uri in this case, y...
[ 7, 0 ]
[]
[]
[ "keyword_argument", "python" ]
stackoverflow_0006978903_keyword_argument_python.txt
Q: Where should I put Py_INCREF and Py_DECREF on this block in Python C Extension? Whenever I called my function, memory usage is increased around +10M per call, so I think there is some memory leak here. .... PyObject *pair = PyTuple_New(2), *item = PyList_New(0); PyTuple_SetItem(pair, 0, PyInt_FromLong(v[j])); if...
Where should I put Py_INCREF and Py_DECREF on this block in Python C Extension?
Whenever I called my function, memory usage is increased around +10M per call, so I think there is some memory leak here. .... PyObject *pair = PyTuple_New(2), *item = PyList_New(0); PyTuple_SetItem(pair, 0, PyInt_FromLong(v[j])); if(v[j] != DISTANCE_MAX && (p[j] || d[0][j])){ jp=j; while(jp!=istart) { PyList...
[ "The objects you create with PyInt_FromLong() and you add to the list should be kept in a local variable.\nThe reason are the ownership rules: PyInt_FromLong() generates a reference that you own. In the call to PyTuple_SetItem(), you lose this ownership again, because PyTuple_SetItem() \"steals\" it from you, so yo...
[ 11, 0 ]
[]
[]
[ "c", "python", "reference_counting" ]
stackoverflow_0006977161_c_python_reference_counting.txt
Q: Best method for reading newline delimited files and discarding the newlines? I am trying to determine the best way to handle getting rid of newlines when reading in newline delimited files in Python. What I've come up with is the following code, include throwaway code to test. import os def getfile(filename,resul...
Best method for reading newline delimited files and discarding the newlines?
I am trying to determine the best way to handle getting rid of newlines when reading in newline delimited files in Python. What I've come up with is the following code, include throwaway code to test. import os def getfile(filename,results): f = open(filename) filecontents = f.readlines() for line in filecont...
[ "lines = open(filename).read().splitlines()\n\n", "Here's a generator that does what you requested. In this case, using rstrip is sufficient and slightly faster than strip.\nlines = (line.rstrip('\\n') for line in open(filename))\n\nHowever, you'll most likely want to use this to get rid of trailing whitespaces t...
[ 201, 24, 11, 8, 4, 3, 2 ]
[]
[]
[ "file", "python", "readline" ]
stackoverflow_0000544921_file_python_readline.txt
Q: End-line characters from lines read from text file, using Python When reading lines from a text file using python, the end-line character often needs to be truncated before processing the text, as in the following example: f = open("myFile.txt", "r") for line in f: line = line[:-1] # do something with line...
End-line characters from lines read from text file, using Python
When reading lines from a text file using python, the end-line character often needs to be truncated before processing the text, as in the following example: f = open("myFile.txt", "r") for line in f: line = line[:-1] # do something with line Is there an elegant way or idiom for retrieving text lines without t...
[ "The idiomatic way to do this in Python is to use rstrip('\\n'):\nfor line in open('myfile.txt'): # opened in text-mode; all EOLs are converted to '\\n'\n line = line.rstrip('\\n')\n process(line)\n\nEach of the other alternatives has a gotcha:\n\nfile('...').read().splitlines() has to load the whole file in...
[ 53, 17, 6, 5, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0000339537_python.txt
Q: How can I use numpy without installing it? I console access to a computer where I do not have root nor sudo rights. Python version is 2.5.2 and numpy is not available. I cannot use python setup.py install --user nor there are any compilers available on the machine. Can I somehow use the compiled packages available...
How can I use numpy without installing it?
I console access to a computer where I do not have root nor sudo rights. Python version is 2.5.2 and numpy is not available. I cannot use python setup.py install --user nor there are any compilers available on the machine. Can I somehow use the compiled packages available https://edge.launchpad.net/~scipy/+archive/ppa/...
[ "If you can resolve all the dependencies, you might be able to install it in your $HOME using dpkg. dpkg doesn't resolve dependencies automatically, so you might have to figure out the right order to install the packages in. Download the .deb files that you're interested in and run the following command for each pa...
[ 5, 3, 1, 0 ]
[]
[]
[ "launchpad", "numpy", "python" ]
stackoverflow_0006976503_launchpad_numpy_python.txt
Q: Is there way to identify Class and object For example I have class Class Cls: var 1 var 2 def func(self): --- do some statement Now, I can simply import class and create object import Cls clsObj = Cls() Here, Cls is class and clsObj is instance of class. Is there any way that I distinguish betwe...
Is there way to identify Class and object
For example I have class Class Cls: var 1 var 2 def func(self): --- do some statement Now, I can simply import class and create object import Cls clsObj = Cls() Here, Cls is class and clsObj is instance of class. Is there any way that I distinguish between them. Thank you
[ "Yes, just use the builtin type() which gives the type of a particular object. type(clsObj) will give Instance as the answer. You can also check with isinstance\nisinstance(clsObj,Cls) will return True whereas isinstance(Cls,Cls) will return False\n", "I think this takes all cases into account:\ndef isclass(obj):...
[ 3, 3, 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006978331_django_python.txt
Q: wx.StaticBox size parameter not respected I'm trying to create a wx.StaticBox having a constant size, regardless to the size of the widget within. So I have a panel containing the following code: box = wx.StaticBox(self, -1, 'BoxTitle', size=(200, 200)) bsizer = wx.StaticBoxSizer(box, wx.VERTICAL) text = wx.Stati...
wx.StaticBox size parameter not respected
I'm trying to create a wx.StaticBox having a constant size, regardless to the size of the widget within. So I have a panel containing the following code: box = wx.StaticBox(self, -1, 'BoxTitle', size=(200, 200)) bsizer = wx.StaticBoxSizer(box, wx.VERTICAL) text = wx.StaticText(self, -1, 'Text') bsizer.Add(text) borde...
[ "If you add the following after creating your StaticBox it will force the size for you:\nbox.SetMaxSize((200,200))\n\nNote that a StaticText box does not wrap its text, so if your text is wider than the StaticBox it will extend beyond the edge of the box (as least on OS X it does this, may behave differently on Win...
[ 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0006977690_python_wxpython.txt
Q: Using Python, how can I obtain the running process and the exe name for that process? Suppose that I have an exe running and its name is myexe.exe. On Windows, I can see the process for myexe.exe in Process Explorer. Using Python, how can I obtain the process ID of myexe.exe and shut it down? A: You can do it vi...
Using Python, how can I obtain the running process and the exe name for that process?
Suppose that I have an exe running and its name is myexe.exe. On Windows, I can see the process for myexe.exe in Process Explorer. Using Python, how can I obtain the process ID of myexe.exe and shut it down?
[ "You can do it via wmi service, if you use the wmi (Windows Management Instrumentation module). Look here for the examples to get the process name and to terminate using the process id.\n", "The best way to do it on windows is to use PyWin32 ( http://sourceforge.net/projects/pywin32 )\nLook at the following code ...
[ 2, 0 ]
[]
[]
[ "process", "python", "windows" ]
stackoverflow_0006977371_process_python_windows.txt
Q: Disable option to move FeinCMS contenttypes within a region I'd like to disable the option to move FeinCMS contenttypes whithin a region. Does anyone have any suggestions how to accomplish this? A: No, that's not possible currently. What's the reasoning behind this feature request?
Disable option to move FeinCMS contenttypes within a region
I'd like to disable the option to move FeinCMS contenttypes whithin a region. Does anyone have any suggestions how to accomplish this?
[ "No, that's not possible currently. \nWhat's the reasoning behind this feature request?\n" ]
[ 2 ]
[]
[]
[ "content_management_system", "contenttype", "django", "feincms", "python" ]
stackoverflow_0006979529_content_management_system_contenttype_django_feincms_python.txt
Q: Create a 16 Bit TIFF image from a Python string I need to use scanner in 16 bit depth and color mode, so i modified python-imaging-sane (that doesn't support RGB tiff with 16 bit depth) to receive from a scanner (epson v500) an image in a Python string. this is the modified function that i use to send data from th...
Create a 16 Bit TIFF image from a Python string
I need to use scanner in 16 bit depth and color mode, so i modified python-imaging-sane (that doesn't support RGB tiff with 16 bit depth) to receive from a scanner (epson v500) an image in a Python string. this is the modified function that i use to send data from the scanner to a python string: #define READSIZE 32768 ...
[ "You probably have the byte order wrong. Try swapping the two bytes that make up the sixteen bit data and see what you get.\n" ]
[ 0 ]
[]
[]
[ "endianness", "image", "python", "sane", "tiff" ]
stackoverflow_0006974309_endianness_image_python_sane_tiff.txt
Q: Weird django import errors What I was trying to do was to override the save method of one of my models called Shastra class Shastra(models.Model): something = models.IntegerField() def save(self, *args, **kwargs): post_content(app='shastra', content=self) super(Shastra, self).save(*args, *...
Weird django import errors
What I was trying to do was to override the save method of one of my models called Shastra class Shastra(models.Model): something = models.IntegerField() def save(self, *args, **kwargs): post_content(app='shastra', content=self) super(Shastra, self).save(*args, **kwargs) # The function being ...
[ "Circular import. Either resolve it, or use string as FK argument (models.ForeignKey('app.Shastra')).\n", "It looks like you have a circular import. \nshastra\\models.py is doing from fb_api.api import *\nfb_api\\api.py is doing from fb_api.models import FbApiUser\nfb_api\\models.py is doing from shastra.models ...
[ 7, 3 ]
[]
[]
[ "django", "django_errors", "django_models", "python" ]
stackoverflow_0006979922_django_django_errors_django_models_python.txt
Q: App Engine CRUD with webapp - thoughts on structuring? Two approaches: # routes: (passed to WSGIApplication) [..snip..] ('/note/add', AddNoteHandler), ('/note/delete/(.+)', DeleteNoteHandler), ('/note/view/(.+)', ViewNoteHandler), ('/note', ListNotesHandler), [..snip..] .. versus .. ('/note/(.*)', NoteHandler) #...
App Engine CRUD with webapp - thoughts on structuring?
Two approaches: # routes: (passed to WSGIApplication) [..snip..] ('/note/add', AddNoteHandler), ('/note/delete/(.+)', DeleteNoteHandler), ('/note/view/(.+)', ViewNoteHandler), ('/note', ListNotesHandler), [..snip..] .. versus .. ('/note/(.*)', NoteHandler) # which moves all the code from many RequestHandlers to one.....
[ "Have all of the handlers which share code subclass a base handler (which subclasses webapp.RequestHander).\nThat way you both have the routes and handlers separated properly and can factor out common code.\n" ]
[ 2 ]
[]
[]
[ "crud", "google_app_engine", "python" ]
stackoverflow_0006979912_crud_google_app_engine_python.txt
Q: Find an efficient way to integrate different language libraries into one project using Python as the "glue" I am about to get involved in a NLP-related project and I need to use various libraries. Some are in java, others in C/C++ (for tasks that require more speed) and finally some are in Python. I was thinking o...
Find an efficient way to integrate different language libraries into one project using Python as the "glue"
I am about to get involved in a NLP-related project and I need to use various libraries. Some are in java, others in C/C++ (for tasks that require more speed) and finally some are in Python. I was thinking of using Python as the "glue" and create wrapper-classes for every task that I want to do that relies on a differe...
[ "I would simply advise not doing this.\nDon't implement stuff in C/C++ \"for speed\". The performance benefit is not likely to be as great as you expect; e.g. compared with implementing in Java using \"best practice\" design and performance techniques.\nDon't try and glue lots of languages together. You are setti...
[ 5, 1, 1, 0, 0 ]
[]
[]
[ "c++", "java", "nlp", "python", "wrapper" ]
stackoverflow_0006970359_c++_java_nlp_python_wrapper.txt
Q: Rendering HTML in web.py I am handling with a Wikipedia-like project. I can convert the text file to html code using the markdown. My problem is, I want to render this html code in a html file. Here is my code, class articles: def GET(self): form_name=web.input() article_name=form_name.page ...
Rendering HTML in web.py
I am handling with a Wikipedia-like project. I can convert the text file to html code using the markdown. My problem is, I want to render this html code in a html file. Here is my code, class articles: def GET(self): form_name=web.input() article_name=form_name.page article_file_path=os.path...
[ "HTML escaping is on by default in web.py templates. To turn it off, prepend the variable name with a colon:\n<form name=\"form\" method=\"GET\">\n $:content\n</form>\n\nMake sure there is no way for a potentially malicious user to feed arbitrary HTML into your unescaped templates.\n", "You need to specify the...
[ 13, 2 ]
[]
[]
[ "html", "python", "templates", "web.py" ]
stackoverflow_0006979819_html_python_templates_web.py.txt
Q: File operations in Python I have a piece of code which extracts a string that lies between two strings.However,this script performs this operation only on a line.I want to perform this operation on a complete file and get a list of all the words lying between those two words. Note:The two words are fixed.For ex:If...
File operations in Python
I have a piece of code which extracts a string that lies between two strings.However,this script performs this operation only on a line.I want to perform this operation on a complete file and get a list of all the words lying between those two words. Note:The two words are fixed.For ex:If my code is something like 'co...
[ "If the file fits comfortably into memory, you can get this with a single regex call:\nimport re\nregex = re.compile(\nr\"\"\"(?x)\n(?<= # Assert that the text before the current location is:\n \\b # word boundary\n int # \"int\"\n \\s # whitespace\n) # End of lookbehind\n[^=]* # Match any num...
[ 3, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006978770_python.txt
Q: How to grab streaming data from twitter using nltk - regular expression I am newbie in Python and given a task from my boss to do this : Grab streaming data from twitter in JSON Parsing using NLTK and Regular Expression Save it to file base or database file, ok Is there anyone know how to grab a streaming data ...
How to grab streaming data from twitter using nltk - regular expression
I am newbie in Python and given a task from my boss to do this : Grab streaming data from twitter in JSON Parsing using NLTK and Regular Expression Save it to file base or database file, ok Is there anyone know how to grab a streaming data from twitter using the step above ? Your help would be very grateful :)
[ "A quick Google search yields Tweepy, which is a python library for accessing the Twitter API. This should get you started. In terms of parsing the data, you'll need to be a little more specific as to what you want to parse. \n", "This should point you in the right direction\nimport urllib2, simplejson\n\njson = ...
[ 2, 1, 0 ]
[]
[]
[ "json", "nltk", "python", "stream", "twitter" ]
stackoverflow_0006853282_json_nltk_python_stream_twitter.txt
Q: Django, Signals and another process I've got my Django project running well, and a separate background process which will collect data from various sources and store that data in an index. I've got a model in a Django app called Sources which contains, essentially, a list of sources that data can come from! I've s...
Django, Signals and another process
I've got my Django project running well, and a separate background process which will collect data from various sources and store that data in an index. I've got a model in a Django app called Sources which contains, essentially, a list of sources that data can come from! I've successfully managed to create a signal th...
[ "It's unclear how are you running the background process you're talking about.\nAnyway, I'd suggest that in your background task you use the Sources model directly. There are convenient ways to run the task without leaving realm of Django (so as to have an access to your models. You can use Celery [1], for example,...
[ 7, 2 ]
[]
[]
[ "django", "multiprocessing", "python", "signals" ]
stackoverflow_0006980353_django_multiprocessing_python_signals.txt
Q: How to do a wget call via proxy with python? I tried to use this script pdfmeat to get data about papers from google scholar. This script works very well in my pc, but when I try to put this script in my server I don't have results. I saw that is very probably that my server is in the black list of google scholar,...
How to do a wget call via proxy with python?
I tried to use this script pdfmeat to get data about papers from google scholar. This script works very well in my pc, but when I try to put this script in my server I don't have results. I saw that is very probably that my server is in the black list of google scholar, give that I have an error (redirects to solve a c...
[ "Have you tried just setting the http_proxy env. var.?\nSo:\n$ export http_proxy=\"oneHttpProxy\"\n$ python pdfmeat.py .... \n" ]
[ 0 ]
[]
[]
[ "google_scholar", "python", "wget" ]
stackoverflow_0006980575_google_scholar_python_wget.txt
Q: django ForeignKey display UPDATED ANSWER TO QUESTION: How do I get a lookup value (from Atc) to display on a transaction table (Drugs) when displaying Drug? Solution, using Saverio's approach of embedding the relationship in the model itself: models.py class Atc(models.Model): id = models.CharField(max_length=...
django ForeignKey display
UPDATED ANSWER TO QUESTION: How do I get a lookup value (from Atc) to display on a transaction table (Drugs) when displaying Drug? Solution, using Saverio's approach of embedding the relationship in the model itself: models.py class Atc(models.Model): id = models.CharField(max_length=60, primary_key=True, db_column...
[ "how are you fetching that description? if you have any code post it so maybe we can help more!\nyou have to use your notesid to fetch the notesinline object and display it!\nfetched_note = NotesInline.objects.filter(id=notesid)\n\nwhere notesid is your DrugsAdmin's object variable :)\n", "Why not just\nclass Atc...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006980547_django_python.txt
Q: django - get field which name is dynamic What I need: I want to get object details from DB. I use get() function. The problem I have is, that I make in in a function, and one of the arguments is field name as string: def delete_file_if_changed(id, change, form, model, field_name='image'): if change: if...
django - get field which name is dynamic
What I need: I want to get object details from DB. I use get() function. The problem I have is, that I make in in a function, and one of the arguments is field name as string: def delete_file_if_changed(id, change, form, model, field_name='image'): if change: if field_name in form.changed_data: ...
[ "You know, I thought this was your answer at first -- it lets you search by a dynamic property: Could the ** operator work?\nkw = {field_name:change} # you're not explicit as to which is the field_name\n # value you would like to search for.\nold_image = model.objects.get(**kw)\n\nBut, if yo...
[ 28, 3, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006980877_django_python.txt
Q: Python web app - synchronized serial access I'm a java intermediate developer, python newbie and web-services uber newbie. As a learning experience, I'm trying to realize a RESTful web service in python to remotely control a simple on/off light via an RS232-over-USB relay board. I already figured out the basics of...
Python web app - synchronized serial access
I'm a java intermediate developer, python newbie and web-services uber newbie. As a learning experience, I'm trying to realize a RESTful web service in python to remotely control a simple on/off light via an RS232-over-USB relay board. I already figured out the basics of web.py & pyserial libraries. The board I am usin...
[ "Your solution seems OK if your web app is run under the same python instance (running integrated in web.py dev webserver).\nBut if you want to run it under multiple Python processes, then you have to put the lock on the file itself using fcntl module.\n" ]
[ 1 ]
[]
[]
[ "multithreading", "pyserial", "python", "web.py", "web_services" ]
stackoverflow_0006980724_multithreading_pyserial_python_web.py_web_services.txt
Q: Reference or Copy I just started with Python 3. In a Python book i read that the interpreter can be forced to make a copy of a instance instead creating a reference by useing the slicing-notation. This should create a reference to the existing instance of s1: s1 = "Test" s2 = s1 print(s1 == s2) print(s1 is s2) Th...
Reference or Copy
I just started with Python 3. In a Python book i read that the interpreter can be forced to make a copy of a instance instead creating a reference by useing the slicing-notation. This should create a reference to the existing instance of s1: s1 = "Test" s2 = s1 print(s1 == s2) print(s1 is s2) This should create a new ...
[ "This is true for mutable datatypes such as lists (i.e. works as you expect with s1 = [1,2,3]).\nHowever strings and also e.g. tuples in python are immutable (meaning they cant be changed, you can only create new instances). There is no reason for a python interpreter to create copies of such objects, as you can no...
[ 7, 2, 2, 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0006981453_python_python_3.x.txt
Q: URL Redirection with jQuery and Pyramid? I have a Pyramid app for a web page with a form. I was using window.location = XXX after the form's POST but I was told that this is not SEO friendly. Therefore, I am trying to do a redirect on the server side. What I did is add a view in my pyramid app at mydomain.com/re...
URL Redirection with jQuery and Pyramid?
I have a Pyramid app for a web page with a form. I was using window.location = XXX after the form's POST but I was told that this is not SEO friendly. Therefore, I am trying to do a redirect on the server side. What I did is add a view in my pyramid app at mydomain.com/redirect. Going to this address returns a 301 to...
[ "jQuery won't redirect the browser when it receives a 3xx response. It will only follow the redirection in the AJAX request. It's the standard behavior for XmlHttpRequest and I am pretty sure it can't be changed.\nWhat you want is either not submit your form with JavaScript and use a HTTP redirection, or use JavaSc...
[ 0 ]
[]
[]
[ "jquery", "pyramid", "python", "redirect" ]
stackoverflow_0006978531_jquery_pyramid_python_redirect.txt
Q: Python- how to convert Datetimefield from model into UTC time zone For python, how do i convert a DatetimeField (has my local server time) to a datetimefield in UTC zone? A: >>> import datetime >>> import pytz >>> datetime.datetime.now(pytz.timezone('Europe/Minsk')) datetime.datetime(2011, 8, 8, 15, 32, 7, 81689...
Python- how to convert Datetimefield from model into UTC time zone
For python, how do i convert a DatetimeField (has my local server time) to a datetimefield in UTC zone?
[ ">>> import datetime\n>>> import pytz\n>>> datetime.datetime.now(pytz.timezone('Europe/Minsk'))\ndatetime.datetime(2011, 8, 8, 15, 32, 7, 816893, tzinfo=<DstTzInfo 'Europe/Minsk' EEST+3:00:00 DST>)\n>>> x = datetime.datetime.now()\n>>> x\ndatetime.datetime(2011, 8, 8, 15, 32, 26, 960839)\n>>> x.replace(tzinfo=pytz....
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003756678_python.txt
Q: Python get recent files FTP I need to get the newest files/directory on my FTP server (updated today), I've discovered this solution: def callback(line): try: #only use this code if you'll be dealing with that FTP server alone #look into dateutil module which parses dates with more flexibility...
Python get recent files FTP
I need to get the newest files/directory on my FTP server (updated today), I've discovered this solution: def callback(line): try: #only use this code if you'll be dealing with that FTP server alone #look into dateutil module which parses dates with more flexibility when = datetime.strptime...
[ "Looking at the documentation for the Python ftplib, it looks like the output from retrlines() will be a line where the file name is the last \"column\". \n-rw-r--r-- 1 ftp-usr pdmaint 5305 Mar 20 09:48 INDEX\n\nSo a simple split and getting the last field should work. It will however only work if there are ...
[ 1, 1 ]
[]
[]
[ "ftplib", "python" ]
stackoverflow_0006981597_ftplib_python.txt
Q: wx.ListCtrl: how can I select a row on EVT_RIGHT_DOWN? I'm writing a simple database GUI with wxpython. In order to display my database entries, I'm using a wx.ListCtrl. Let's consider the following code snippet: class BookList(wx.ListCtrl): def __init__(self, parent, ID=wx.ID_ANY): wx.ListCtrl.__init__(self...
wx.ListCtrl: how can I select a row on EVT_RIGHT_DOWN?
I'm writing a simple database GUI with wxpython. In order to display my database entries, I'm using a wx.ListCtrl. Let's consider the following code snippet: class BookList(wx.ListCtrl): def __init__(self, parent, ID=wx.ID_ANY): wx.ListCtrl.__init__(self, parent, ID) self.InsertColumn(0, 'Title') self.In...
[ "I found a solution that involves both the possible solutions I guessed.\nI have keep track of the currently selected row. The snippet speaks itself:\nclass BookList(wx.ListCtrl):\n def __init__(self, parent, ID=wx.ID_ANY):\n wx.ListCtrl.__init__(self, parent, ID)\n\n self.InsertColumn(0, 'Title')\n self....
[ 0 ]
[]
[]
[ "python", "wxpython", "wxwidgets" ]
stackoverflow_0006981500_python_wxpython_wxwidgets.txt
Q: Safeguarding MySQL password when developing in Python? I'm writing a Python script which uses a MySQL database, which is locally hosted. The program will be delivered as source code. As a result, the MySQL password will be visible to bare eyes. Is there a good way to protect this? The idea is to prevent some naug...
Safeguarding MySQL password when developing in Python?
I'm writing a Python script which uses a MySQL database, which is locally hosted. The program will be delivered as source code. As a result, the MySQL password will be visible to bare eyes. Is there a good way to protect this? The idea is to prevent some naughty people from looking at the source code, gaining direct a...
[ "Short answer\nYou can't.\nIf the password is stored in the artifact that's shipped to the end-user you must consider it compromised! Even if the artifact is a compiled binary, there are always (more or less complicated) ways to get at the password.\nThe only way to protect your resources is by exposing only a limi...
[ 16, 7, 0 ]
[ "Either use simple passwor like root.Else Don't use password.\n" ]
[ -5 ]
[ "mysql", "python" ]
stackoverflow_0006981064_mysql_python.txt
Q: Django Application Layout: Internationalization What is the best way to store language constants in django project? For example, we know, that for translation we need to do: from django.utils.translation import gettext_lazy as _ class MyThing(models.Model): name = models.CharField(help_text=_('This is the he...
Django Application Layout: Internationalization
What is the best way to store language constants in django project? For example, we know, that for translation we need to do: from django.utils.translation import gettext_lazy as _ class MyThing(models.Model): name = models.CharField(help_text=_('This is the help text')) If we have a lot of variants, we can use ...
[ "I think it really depends. If you have a big public-facing site that you want to translate into N languages, then they aren't constant and will require updates from dedicated translators whenever the content changes. For a project like that, gettext is wholly unsuitable because gettext is to hard for non-technical...
[ 1, 0 ]
[]
[]
[ "django", "internationalization", "python" ]
stackoverflow_0006980850_django_internationalization_python.txt
Q: Cython won't compile on Windows 7 x64 I'm struggling with installing Cython on Windows 7 x64. I downloaded and installed the automated MinGW installer. The created a distutils.cfg to the distutils folder with the following content: [build] compiler = mingw32 After adding C:\MinGW\bin to the environment variables,...
Cython won't compile on Windows 7 x64
I'm struggling with installing Cython on Windows 7 x64. I downloaded and installed the automated MinGW installer. The created a distutils.cfg to the distutils folder with the following content: [build] compiler = mingw32 After adding C:\MinGW\bin to the environment variables, I called easy_install Cython but I get the...
[ "There are pre-compiled Cython packages on this site. I'd suggest you to switch to x86 Python, you gain no real advantage by using the x64 version. If you want to stick with x64, you can't use MingW and you have to use MS SDK C++ compiler (more on this).\n\nDo not use MinGW-w64. As you will notice, the MinGW import...
[ 11 ]
[]
[]
[ "64_bit", "cython", "mingw", "python", "windows_7" ]
stackoverflow_0006982009_64_bit_cython_mingw_python_windows_7.txt
Q: Wrap python list to unsigned char* Edit : Hi all !! I'm currently trying to access to C++ functions from Python and I'm facing to a problem when I try to pass Python list as argument to a function. here is the C++ function definition I'm trying to access (used to send command to PC/SC reader) : SRpdu *SendAPDU(u...
Wrap python list to unsigned char*
Edit : Hi all !! I'm currently trying to access to C++ functions from Python and I'm facing to a problem when I try to pass Python list as argument to a function. here is the C++ function definition I'm trying to access (used to send command to PC/SC reader) : SRpdu *SendAPDU(unsigned int uiAPDU, //Command ...
[ "You should look into module arrays.\nIn particular, you are looking to call fromlist. If you are using a list to pass instead of a string just because you think that's what you should do, there is a string function available, fromstring. Either way, you can simply initialize the array with format specifier 'B' (no...
[ 1 ]
[]
[]
[ "c++", "python", "swig", "unsigned_char" ]
stackoverflow_0006943442_c++_python_swig_unsigned_char.txt
Q: Download from FTP with Python - Pathname I'm using the ftplib to connect to my FTP-server. I want to download a file from my FTP-server to a specified directory on my computer. I have this simple code: def download(ftp,file): f = open(file,"wb") ftp.retrbinary("RETR " + file,f.write) f.close() What do...
Download from FTP with Python - Pathname
I'm using the ftplib to connect to my FTP-server. I want to download a file from my FTP-server to a specified directory on my computer. I have this simple code: def download(ftp,file): f = open(file,"wb") ftp.retrbinary("RETR " + file,f.write) f.close() What do I have to add to this code to download the fi...
[ "Update the call to open with the local path you want to write to. For example:\nimport os\ndef download(ftp,file, localdir):\n f = open(os.path.join(localdir, file),\"wb\")\n ftp.retrbinary(\"RETR \" + file,f.write)\n f.close()\n\n" ]
[ 1 ]
[]
[]
[ "ftp", "python" ]
stackoverflow_0006983633_ftp_python.txt
Q: Sql Alchemy Duplicated Commit I'm currently facing a problem in my Cherrypy application. Im my own custom session module, when performing session.add(), the exact same object gets updated twice. cherrypy.request.SessionManager.user_data = user try: db_session.add(cherrypy.request.SessionManager) db_sessi...
Sql Alchemy Duplicated Commit
I'm currently facing a problem in my Cherrypy application. Im my own custom session module, when performing session.add(), the exact same object gets updated twice. cherrypy.request.SessionManager.user_data = user try: db_session.add(cherrypy.request.SessionManager) db_session.commit() Will Return 2011-06-21...
[ "You might try adding the user_data to the session rather than adding the SessionManager object itself to the session. This would at least make debugging more straightforward.\nAs it is, I'm not sure whether you have a database session inside the cherrypy SessionManager-- which would seem undesirable, but maybe sq...
[ 1, 1 ]
[]
[]
[ "commit", "duplicate_data", "python", "sqlalchemy" ]
stackoverflow_0006422308_commit_duplicate_data_python_sqlalchemy.txt
Q: Question about Arrays in Python and Perl? How would the following be translated, its an array in perl, I thought that I could translate into python as a list. I am trying to create a program that takes the 2-dimensional shape and basic DNA origami info, and supplies the nodes, the cost, and the range of each DNA s...
Question about Arrays in Python and Perl?
How would the following be translated, its an array in perl, I thought that I could translate into python as a list. I am trying to create a program that takes the 2-dimensional shape and basic DNA origami info, and supplies the nodes, the cost, and the range of each DNA strand and also adding a bufferzone and the clea...
[ "Base Array:\n\nxCoords = []\nyCoords = []\nzCoords = []\n\n\nMultidimensional Array:\n\nxCoords = [[]];\nyCoords = [[]];\nzCoords = [[]];\n\nxCoords = []\nyCoords = []\nzCoords = []\nxCoords.append([])\nyCoords.append([])\nzCoords.append([])\n\nCredit here\nExample to declare and populate two dimensional array\nxC...
[ 2, 0 ]
[]
[]
[ "arrays", "perl", "python" ]
stackoverflow_0006983901_arrays_perl_python.txt
Q: Using Twisted to run command on remote system I'm trying to write a Client/Server using Twisted that will allow the client to issue remote commands on the server and receive response data in real time. i.e. If I run $> ssh server someProg.sh, I will see the results in 'real time', not all at once when the process ...
Using Twisted to run command on remote system
I'm trying to write a Client/Server using Twisted that will allow the client to issue remote commands on the server and receive response data in real time. i.e. If I run $> ssh server someProg.sh, I will see the results in 'real time', not all at once when the process finishes. Is this sort of thing possible in Twisted...
[ "Absolutely. As already noted in a comment, you can do this by connecting to the SSH server directly with Twisted's \"conch\" library. This is more scalable (you can open lots of connections without any extra processes) and more portable (it can work on Windows) but it won't take into account your OpenSSH configu...
[ 5 ]
[ "You could use paramiko lib http://www.lag.net/paramiko/\nimport paramiko\n\nclass XXX():\n\ndef ssh_processing(self, params):\n\n ssh = paramiko.SSHClient()\n ssh.set_missing_host_key_policy( paramiko.AutoAddPolicy() )\n\n ssh_connection = ssh.connect(ip, username=params['username'] , password...
[ -1 ]
[ "python", "twisted" ]
stackoverflow_0006963948_python_twisted.txt
Q: Python with CGI - handle ajax I'd like to: Send request from the browser to a python CGI script This request will start some very long operation The browser should check progress of that operation every 3 seconds How can I do that? A: You could do this - Use Javascript to check progress every 3 seconds. Your ...
Python with CGI - handle ajax
I'd like to: Send request from the browser to a python CGI script This request will start some very long operation The browser should check progress of that operation every 3 seconds How can I do that?
[ "You could do this -\n\nUse Javascript to check progress every 3 seconds.\nYour Python script hit at anytime should give the progress at that instance. It should essentially act as state-machine. You need a server here or maybe the progress is stored on some file. \n\nBut having a server is the way to go... \nMaybe...
[ 1, 1 ]
[]
[]
[ "ajax", "cgi", "python" ]
stackoverflow_0006983622_ajax_cgi_python.txt
Q: How can I find a process by name and kill using ctypes? On Windows, I want to find a process by the name of 'exename.exe', and then kill it. How can I do it by ctypes not any other 3rd-party module? A: Try this: import sys, os.path, ctypes, ctypes.wintypes Psapi = ctypes.WinDLL('Psapi.dll') EnumProcesses = Psap...
How can I find a process by name and kill using ctypes?
On Windows, I want to find a process by the name of 'exename.exe', and then kill it. How can I do it by ctypes not any other 3rd-party module?
[ "Try this:\nimport sys, os.path, ctypes, ctypes.wintypes\n\nPsapi = ctypes.WinDLL('Psapi.dll')\nEnumProcesses = Psapi.EnumProcesses\nEnumProcesses.restype = ctypes.wintypes.BOOL\nGetProcessImageFileName = Psapi.GetProcessImageFileNameA\nGetProcessImageFileName.restype = ctypes.wintypes.DWORD\n\nKernel32 = ctypes.Wi...
[ 9, 9 ]
[]
[]
[ "ctypes", "python", "windows" ]
stackoverflow_0006980246_ctypes_python_windows.txt
Q: Why is it useful to have a MetaData object which is not bind to an engine in SQLAlchemy? I am trying to understand the behavior of MySQL regarding the MetaData object and the engine object. This SO-Answer describes MetaData as a collection of table definitions and engine as the dialect and connection details of...
Why is it useful to have a MetaData object which is not bind to an engine in SQLAlchemy?
I am trying to understand the behavior of MySQL regarding the MetaData object and the engine object. This SO-Answer describes MetaData as a collection of table definitions and engine as the dialect and connection details of a specific database So far so good. But when is it useful to have these two separated? Aren'...
[ "SQLAlchemy 0.1 didn't have a \"metadata\" object - the Engine was bound directly to each Table. That idea got old very quick, partially because folks wanted to declare their Table object before they connected, and \"bound metadata\" came along. Then, a long period of mass confusion occurred. People were in th...
[ 10, 5 ]
[]
[]
[ "metadata", "python", "sqlalchemy" ]
stackoverflow_0006983515_metadata_python_sqlalchemy.txt
Q: A super strange bug of os.path.abspath On My Python 2.6 ( 64bit, win7, ActivePython ), when i call: os.path.abspath('D:/PROJECTS/SuiShouBei/www/ssb/static/voices/en/mp3/con.mp3') It returns: '\\\\.\\con' I have no problem with other paths so far. Anyone has the same issue? Can someone please tell me why? A: I ca...
A super strange bug of os.path.abspath
On My Python 2.6 ( 64bit, win7, ActivePython ), when i call: os.path.abspath('D:/PROJECTS/SuiShouBei/www/ssb/static/voices/en/mp3/con.mp3') It returns: '\\\\.\\con' I have no problem with other paths so far. Anyone has the same issue? Can someone please tell me why?
[ "I can reproduce this in Python 2.6, 2.7, 3.1 and 3.2.\nThe reason for this behavior is the fact that CON is an illegal filename in Windows (try os.path.abspath('D:/PROJECTS/SuiShouBei/www/ssb/static/voices/en/mp3/cont.mp3') and see that everything works fine).\nSo take care that your filenames don't contain\n< (le...
[ 45 ]
[]
[]
[ "filesystems", "python", "windows" ]
stackoverflow_0006984450_filesystems_python_windows.txt
Q: shutil.copy failure when the destination already exists and is read-only I am using shutil.copy to copy files from one location to another. If a file with the same name already exists in the destination location, it is normally ok and overwrites. However, if the destination is read-only, it throws a permission d...
shutil.copy failure when the destination already exists and is read-only
I am using shutil.copy to copy files from one location to another. If a file with the same name already exists in the destination location, it is normally ok and overwrites. However, if the destination is read-only, it throws a permission denied error. What is the most elegant way to deal with this? Is there another...
[ "smth like\nimport os\nimport shutil\n\ndef my_super_copy(what, where):\n try:\n shutil.copy(what, where)\n except IOError:\n os.chmod(where, 777) #?? still can raise exception\n shutil.copy(what, where)\n\n", "You don't have to check for permissions. Let the OS tell you there's a perm...
[ 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006984248_python.txt
Q: Google App Engine - Python and render from bigtable I there: I am experimenting with GAE and i wish to create a CMS using plain python (not Django or another framework). And my problem is that GAE does not allow to save files, so i can save a user-created template in a folder. When you want to render a file, you ...
Google App Engine - Python and render from bigtable
I there: I am experimenting with GAE and i wish to create a CMS using plain python (not Django or another framework). And my problem is that GAE does not allow to save files, so i can save a user-created template in a folder. When you want to render a file, you use the next command: tmpl = os.path.join(os.path.dir...
[ "For a start, if you're using template.render, you are using a framework: the minimal \"webapp\" framework included with GAE. And, of course, the template module itself is a thin wrapper around Django's template library. However, the wrapper - which takes care of a few incompatibilities between Django and webapp - ...
[ 4 ]
[]
[]
[ "google_app_engine", "python", "templates" ]
stackoverflow_0006984356_google_app_engine_python_templates.txt
Q: A method to plot power consumption graph with matplotlib? I'm currently doing a small bit of coding for my master's thesis, and decided to do it in python which I toyed around with during a project last year due to finding it quite pleasent to code in. I'm writing a small model simulating a cryptosystem leaking po...
A method to plot power consumption graph with matplotlib?
I'm currently doing a small bit of coding for my master's thesis, and decided to do it in python which I toyed around with during a project last year due to finding it quite pleasent to code in. I'm writing a small model simulating a cryptosystem leaking power usage side channel information during an XOR operation, giv...
[ "\nBased on the picture you provided, I think plot() satisfied your requirement. Following is a simple example:\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nx = np.arange(0, 2, 0.01)\ny = np.random.random_sample(len(x))\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.plot(x, y)\nax.set_xlabel('Power...
[ 2, 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0006983671_matplotlib_python.txt