title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
python, Json and string indices must be integers, not str
10,390,900
4
2012-04-30T21:35:11Z
10,390,969
7
2012-04-30T21:41:34Z
[ "python", "json", "url", "httplib2" ]
I am using Python, and I sent a request to a URL and received a reply using httplib2. The reply I got was in JSon, how do I access a specific parameter. What I have at the moment is: ``` resp, content = parser.request(access_token_uri, method = 'POST', body = params, headers = headers) raise Exception(content['acc...
Well if the response type is json and it comes in type str. If you are running 2.4 of Python use simplejson if 2.6 use json: ``` import json # Your code retdict = json.loads(content) ``` Then treat it like a dictionary. ``` accesstoken = retdict['access_token'] ```
bottle on cherrypy server + ssl
10,390,927
8
2012-04-30T21:36:50Z
10,391,047
8
2012-04-30T21:49:03Z
[ "python", "ssl", "cherrypy" ]
I am trying to run Bottle on top of Cherrypy's server. I want to get SSL Support. So far I have tried this: ``` from bottle import Bottle, route from cherrypy import wsgiserver app = Bottle() @app.route("/") def index(): return "Hello" server = wsgiserver.CherryPyWSGIServer( ('0.0.0.0', 443), app) ...
Try using the following: ``` import web from web.wsgiserver import CherryPyWSGIServer from web.wsgiserver.ssl_builtin import BuiltinSSLAdapter ssl_cert = "path/to/ssl_certificate" ssl_key = "path/to/ssl_private_key" CherryPyWSGIServer.ssl_adapter = BuiltinSSLAdapter(ssl_cert, ssl_key, None) ```
Python program that finds most frequent word in a .txt file, Must print word and its count
10,390,989
7
2012-04-30T21:42:53Z
10,391,032
15
2012-04-30T21:47:05Z
[ "python" ]
As of right now, I have a function to replace the countChars function, ``` def countWords(lines): wordDict = {} for line in lines: wordList = lines.split() for word in wordList: if word in wordDict: wordDict[word] += 1 else: wordDict[word] = 1 return wordDict ``` but when I run the program i...
This program is actually a 4-liner, if you use the powerful tools at your disposal: ``` with open(yourfile) as f: text = f.read() words = re.compile(r"a-zA-Z'").findall(text) counts = collections.Counter(words) ``` The regular expression will find all words, irregardless of the punctuation adjacent to them (but ...
Setting fabric hosts list from an external hosts file
10,391,377
2
2012-04-30T22:26:15Z
10,391,475
10
2012-04-30T22:38:26Z
[ "python", "fabric" ]
I need to get fabric to set its hosts list by opening and reading a file to get the hosts. Setting it this way allows me to have a huge list of hosts without needing to edit my fabfile for this data each time. I tried this: ``` def set_hosts(): env.hosts = [line.split(',') for line in open("host_file")] def unam...
The problem you're hitting here is that you're setting env.hosts to a function object, not a list or iterable. You need the parens after readlines, to actually call it: ``` def set_hosts(): env.hosts = open('hosts_file', 'r').readlines() ```
regex contains "times" but not "clock"
10,391,635
2
2012-04-30T22:59:10Z
10,391,690
7
2012-04-30T23:05:51Z
[ "python", "regex" ]
**Disclaimer:** I know "in" and "not in" can be used but due to technical contraints I need to use regex. I have: ``` a = "digital clock time fan. Segments featuring digital 24 hour oclock times. For 11+" b = "nine times ten is ninety" ``` and I would like to match based on contains "times" but not "oclock", so a an...
You can use a [negative lookahead](http://www.regular-expressions.info/lookaround.html) for this: ``` ^(?!.*\bo?clock\b).*\btimes\b ``` Explanation: ``` ^ # starting at the beginning of the string (?! # fail if .*\bo?clock\b # we can match 'clock' or 'oclock' anywhere in the strin...
Accepting PHP in a textarea may be too dangerous, trying to find another solution
10,391,655
3
2012-04-30T23:01:31Z
10,391,675
7
2012-04-30T23:03:50Z
[ "php", "python", "arrays", "input" ]
I'm having an issue with finding some way of accepting the data below, and being able to parse it as arrays, etc. in PHP or Python. ``` $data = array( 'full_name' => array('name'=>'Full Name', 'type'=>'textarea'), 'company' => array('name'=>'Organization', 'required'=>true), } ``` There are many more fields i...
What about using JSON as an input format? That could be parsed easily, and wouldn't be a security risk.
ValueError: need more than 1 value to unpack python
10,391,963
5
2012-04-30T23:48:17Z
10,391,990
11
2012-04-30T23:53:31Z
[ "python" ]
I have got an existing menu that gives you options `L` or `D`. `L` should load the contents of a file and `D` should display it. ``` if option == "l" or option == "L": with open("packages.txt") as infp: for line in infp: line = line.rstrip() name,adult,child= line.split(',') if option ==...
This means that there is a line in `packages.txt` that, when you strip whitespace and split on commas, doesn't give exactly three pieces. In fact, it seems that it gives only 1 piece ("need more than 1 value to unpack"), which suggests that there's a line with no commas at all. Perhaps there are blank or comment lines...
Splitting a string with multiple delimiters in Python
10,393,157
8
2012-05-01T03:20:19Z
10,393,166
25
2012-05-01T03:22:27Z
[ "python", "string", "split", "delimiter" ]
I'm using regular expressions to split a string using multiple delimiters. But if two of my delimiters occur next to each other in the string, it puts an empty string in the resulting list. For example: ``` re.split(',|;', "This,is;a,;string") ``` Results in ``` ['This', 'is', 'a', '', 'string'] ``` Is there any wa...
Try this: ``` import re re.split(r'[,;]+', 'This,is;a,;string') > ['This', 'is', 'a', 'string'] ```
How does work this pythonic trick: a[::-1]
10,393,453
3
2012-05-01T04:12:29Z
10,393,468
11
2012-05-01T04:14:13Z
[ "python" ]
``` >> a = range(10) >> print a[::-1] [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] ``` This slice gives reversed list. How does it work?
The third argument is a step modifier. In this case you are using a step of `-1`. You could also use a step of `2` to print every even index. ``` >>> a = range(10) >>> a[::2] [0, 2, 4, 6, 8] >>> a[::-2] [9, 7, 5, 3, 1] ```
Python time.sleep
10,393,886
6
2012-05-01T05:20:59Z
10,393,929
9
2012-05-01T05:27:50Z
[ "python", "time", "tkinter", "sleep", "elapsedtime" ]
I am trying to delete text inside a text box after waiting 5 seconds, but instead the program wont run and does sleep over everything else. Also is there a way for me to just make my textbox sleep so i can run other code while the text is frozen? ``` from time import time, sleep from Tkinter import * def empty_textbo...
You really should be using something like the Tkinter [after method](http://infohost.nmt.edu/tcc/help/pubs/tkinter/universal.html) rather than `time.sleep(...)`. There's an example of using the after method at this [other stackoverflow question](http://stackoverflow.com/questions/2400262/code-a-timer-in-a-python-gui-i...
How do I use vi keys in ipython under *nix?
10,394,302
24
2012-05-01T06:21:34Z
10,394,328
26
2012-05-01T06:24:54Z
[ "python", "bash", "vi", "ipython", "readline" ]
Currently in Bash I use `set -o vi` to enable vi mode in my bash prompt. How do I get this going in ipython? *Note:* If an answer applies to all \*nix, I'll remove the OS X from the title :)
Looks like a solution works for many other readline compatible apps: Set the following in your `~/.inputrc` file: ``` set editing-mode vi set keymap vi set convert-meta on ``` Source: <http://www.jukie.net/bart/blog/20040326082602>
How do I use vi keys in ipython under *nix?
10,394,302
24
2012-05-01T06:21:34Z
10,394,340
8
2012-05-01T06:26:24Z
[ "python", "bash", "vi", "ipython", "readline" ]
Currently in Bash I use `set -o vi` to enable vi mode in my bash prompt. How do I get this going in ipython? *Note:* If an answer applies to all \*nix, I'll remove the OS X from the title :)
`ipython` uses the readline library and this is configurable using the `~/.inputrc` file. You can add ``` set editing-mode vi ``` to that file to make all `readline` based applications use vi style keybindings instead of Emacs.
How do I use vi keys in ipython under *nix?
10,394,302
24
2012-05-01T06:21:34Z
17,361,281
10
2013-06-28T09:18:01Z
[ "python", "bash", "vi", "ipython", "readline" ]
Currently in Bash I use `set -o vi` to enable vi mode in my bash prompt. How do I get this going in ipython? *Note:* If an answer applies to all \*nix, I'll remove the OS X from the title :)
You can also interactively switch between Vi-mode and Emacs mode. According to the the [readline docs](https://www.gnu.org/software/bash/manual/html_node/Readline-vi-Mode.html) to switch between them you are supposed to be able to use the M-C-j key combination but that only seems to allow me to switch to vi-mode - on m...
How do I use vi keys in ipython under *nix?
10,394,302
24
2012-05-01T06:21:34Z
38,329,940
29
2016-07-12T13:12:35Z
[ "python", "bash", "vi", "ipython", "readline" ]
Currently in Bash I use `set -o vi` to enable vi mode in my bash prompt. How do I get this going in ipython? *Note:* If an answer applies to all \*nix, I'll remove the OS X from the title :)
In case someone's wandering in here recently, [IPython 5.0 switched from readline to prompt\_toolkit](http://ipython.readthedocs.io/en/stable/whatsnew/version5.html#new-terminal-interface), so an updated answer to this question is to pass an option: ``` $ ipython --TerminalInteractiveShell.editing_mode=vi ``` ... or ...
Setting sqlite temp store directory
10,394,517
7
2012-05-01T06:50:35Z
10,395,983
7
2012-05-01T09:41:47Z
[ "python", "sqlite", "sqlite3" ]
I have a Python binary which uses SQLite as its backend database. SQLite's documentation and the code suggests that setting any of the following 3 environment variables should work: ``` export TMP=/var/tmp/sqlite/ export TEMP=/var/tmp/sqlite/ export TEMPDIR=/var/tmp/sqlite/ ``` If I export the above variables in my b...
The environment variables you are referring to are indeed what sqlite looks for but in Windows, not UNIX. In Unix, the environment variable you need to set is `TMPDIR` as shown in the sources: ``` static const char *unixTempFileDir(void){ static const char *azDirs[] = { 0, 0, "/var/tmp", "/usr/t...
Maximum size of "TEXT" datatype in postgresql
10,395,975
28
2012-05-01T09:40:52Z
10,396,038
52
2012-05-01T09:48:07Z
[ "python", "postgresql" ]
I am working with python. I have a field with "text" datatype in postgres. Whenever I try to save a very large string, it throws internal error in python, but if I save the string with a smaller size, it saves it properly. I don't understand the problem. Is it that there is some maximum limit for entering the charact...
From the [manual](http://www.postgresql.org/docs/current/interactive/datatype-character.html): > In any case, the longest possible character string that can be stored > is about 1 GB.
Strange `UnicodeEncodeError` using `os.path.exists`
10,396,141
11
2012-05-01T09:58:09Z
10,396,375
15
2012-05-01T10:22:41Z
[ "python", "apache", "unicode", "flask" ]
In a web-application (using Flask), I get the following error: ``` Unable to retrieve the thumbnail for u'/var/data/uploads/2012/03/22/12 Gerd\xb4s Banjo Trio 1024.jpg' Traceback (most recent call last): File "/var/www/beta/env/lib/python2.7/site-packages/dblib-1.0dev3-py2.7.egg/dblib/orm/file.py", line 169, in get_t...
See Django docs for same issue. When using mod\_wsgi, should be same solution: <https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/modwsgi/#if-you-get-a-unicodeencodeerror> Excerpt from the above linked doc: > [...] you must ensure that the environment used to start Apache is > configured to accept non-ASCI...
How to host python cgi script with `python -m SimpleHTTPServer 8000` or `python -m CGIHTTPServer 8000`?
10,396,330
16
2012-05-01T10:18:53Z
10,396,381
25
2012-05-01T10:23:19Z
[ "python", "hosting", "cgi", "simplehttpserver" ]
When I run `python -m SimpleHTTPServer 8000` or `python -m CGIHTTPServer 8000` in my shell I am hosting the content of my current directory to the internet. I would like to make the following cgi\_script.py work correctly using the above command in the command line when I browse to `192.xxx.x.xx:8000/cgi_script.py` `...
Try with `python -m CGIHTTPServer 8000`. Note that you have to move the script to a `cgi-bin` or `htbin` directory in order to be runnable.
Best practice when defining instance variables
10,396,920
10
2012-05-01T11:15:31Z
10,397,243
9
2012-05-01T11:50:23Z
[ "python", "variables", "constructor" ]
I'm fairly new to Python and have a question regarding the following class: ``` class Configuration: def __init__(self): parser = SafeConfigParser() try: if parser.read(CONFIG_FILE) is None: raise IOError('Cannot open configuration file') except IOError, error: ...
I would definitely declare all instance variables in `__init__`. To not do so leads to increased complexity and potential unexpected side effects. To provide an alternate point of view from David Hall in terms of access, this is from the [Google Python style guide](http://google-styleguide.googlecode.com/svn/trunk/pyg...
Is there a performance difference in using a tuple over a frozenset as a key for a dictionary?
10,398,470
5
2012-05-01T13:37:43Z
10,398,548
9
2012-05-01T13:43:23Z
[ "python" ]
I have a script that makes many calls to a dictionary using a key consisting of two variables. I know that my program will encounter the two variables again in the reverse order which makes storing the key as a tuple feasible. (Creating a matrix with the same labels for rows and columns) Therefore, I was wondering if ...
In a quick test, apparently it makes a negligible difference. ``` python -m timeit -s "keys = list(zip(range(10000), range(10, 10000)))" -s "values = range(10000)" -s "a=dict(zip(keys, values))" "for i in keys:" " _ = a[i]" 1000 loops, best of 3: 855 usec per loop python -m timeit -s "keys = [frozenset(i) for i in z...
Is there a performance difference in using a tuple over a frozenset as a key for a dictionary?
10,398,470
5
2012-05-01T13:37:43Z
10,398,619
8
2012-05-01T13:49:01Z
[ "python" ]
I have a script that makes many calls to a dictionary using a key consisting of two variables. I know that my program will encounter the two variables again in the reverse order which makes storing the key as a tuple feasible. (Creating a matrix with the same labels for rows and columns) Therefore, I was wondering if ...
Without having done any tests, I have a few guesses. For `frozenset`s, cpython [stores the hash](http://hg.python.org/cpython/file/5fd1ac1c9474/Objects/setobject.c#l766) after it has been calculated; furthermore, iterating over a set of any kind incurs extra overhead because the data is stored sparsely. In a 2-item set...
Setting up cron job in google app engine python
10,399,313
3
2012-05-01T14:42:10Z
10,399,362
9
2012-05-01T14:46:29Z
[ "python", "google-app-engine", "cron" ]
I'm just getting started with Google App Engine so I'm still learning how to configure everything. I wrote a script called parsexml.py that I want to run every 10 minutes or so. This file is in my main directory, alongside main.py, app.yaml, etc. As I understand it, I need to create a new file, cron.yaml which looks li...
Brian, You'll need to update both your `app.yaml` and `cron.yaml` files. In each of these, you'll need to specify the path where the script will run. `app.yaml`: ``` handlers: - url: /path/to/cron script: parsexml.py ``` or if you have a catch all handler you won't need to change it. For example: ``` handlers: -...
Accessing value inside nested dictionaries
10,399,614
3
2012-05-01T15:03:20Z
10,399,796
12
2012-05-01T15:15:27Z
[ "python", "dictionary" ]
I am new to python and need help in solving an issue: I have a dictionary like `tmpDict = {'ONE':{'TWO':{'THREE':10}}}` Do we have any other way to access THREE's value other than doing `tmpDict['ONE']['TWO']['THREE']`?
As always in python, there are of course several ways to do it, but **there is one obvious way to do it.** `tmpdict["ONE"]["TWO"]["THREE"]` *is* the obvious way to do it. When that does not fit well with your algorithm, that may be a hint that your structure is not the best for the problem. If you just want to just ...
Check if string in strings
10,399,671
5
2012-05-01T15:07:41Z
10,399,903
9
2012-05-01T15:23:11Z
[ "python", "string", "list", "comparison" ]
I have a huge list containing many strings like: ``` ['xxxx','xx','xy','yy','x',......] ``` Now I am looking for an efficient way that removes all strings that are present within another string. For example 'xx' 'x' fit in 'xxxx'. As the dataset is huge, I was wondering if there is an efficient method for this besid...
`x in <string>` is fast, but checking each string against all other strings in the list will take O(n^2) time. Instead of shaving a few cycles by optimizing the comparison, you can achieve huge savings by using a different data structure so that you can check each string in just one lookup: For two thousand strings, th...
Django - Catch argument in Class based FormView
10,400,113
5
2012-05-01T15:39:17Z
10,400,188
15
2012-05-01T15:43:35Z
[ "python", "django", "django-generic-views" ]
On my page, i need to display the post detail and a comment form for viewer to post comment. I created 2 generic views: ``` # views.py class PostDetailView (DetailView): model = Post context_object_name = 'post' template_name = 'post.html' def get_context_data(self, **kwargs): context = super(PostDetailVi...
`self.kwargs['post_id']` or `self.args[0]` contains that value [Docs](https://docs.djangoproject.com/en/dev/topics/class-based-views/#dynamic-filtering)
How do I use ffmpeg with Python by passing File Objects (instead of locations to files on disk)
10,400,556
6
2012-05-01T16:08:14Z
10,401,698
7
2012-05-01T17:33:32Z
[ "python", "ffmpeg", "subprocess", "pyffmpeg" ]
I'm trying to use ffmpeg with Python's subprocess module to convert some audio files. I grab the audio files from a URL and would like to just be able to pass the Python File Objects to ffmpeg, instead of first saving them to disk. It would also be very nice if I could just get back a file stream instead of having ffmp...
with ffmpeg you can use `-` as input/output file name to indicate that it should read the data from stdin / write to stdout. Then you can use the `stdin`/`stdout` arguments of `Popen` to read/write your data. an example: ``` from subprocess import Popen, PIPE with open("test.avi", "rb") as infile: p=Popen(["ffm...
Python dictionary initilization
10,401,180
4
2012-05-01T16:52:32Z
10,401,209
10
2012-05-01T16:54:45Z
[ "python" ]
I am not sure if this is a bug or a feature. I have a dictionary to be initialized with empty lists. Lets say ``` keys =['one','two','three'] sets = dict.fromkeys(keys,[]) ``` What I observed is if you append any item to any of the lists all the lists are modified. ``` sets = dict.fromkeys(['one','two','three'],[])...
This is how things work in Python. When you use `fromkeys()` in this manner, you end with three references to the same list. When you change one list, all three appear to change. The same behaviour can also be seen here: ``` In [2]: l = [[]] * 3 In [3]: l Out[3]: [[], [], []] In [4]: l[0].append('one') In [5]: l ...
Reload in Python interpreter
10,401,424
7
2012-05-01T17:11:43Z
10,401,534
14
2012-05-01T17:21:18Z
[ "python", "interpreter", "reload" ]
``` $ python >>> import myapp >>> reload(myapp) <module 'myapp' from 'myapp.pyc'> >>> ``` `ctrl+D` ``` $ python >>> from myapp import * >>> reload(myapp) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'myapp' is not defined ``` Why this behaves differently? How can I reload ...
From <http://docs.python.org/library/functions.html#reload> : > If a module imports objects from another module using from ... import > ..., calling reload() for the other module does not redefine the > objects imported from it — one way around this is to re-execute the > from statement, another is to use import and...
MongoKit "ImportError: No module named objectid " error
10,401,499
7
2012-05-01T17:17:32Z
10,401,553
11
2012-05-01T17:22:51Z
[ "python", "python-2.7", "flask", "pymongo", "mongokit" ]
I get some very strange error using MongoKit: ``` >>> from mongokit import * Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.7/dist-packages/mongokit/__init__.py", line 35, in <module> from document import Document, ObjectId File "/usr/local/lib/python2.7/d...
It's an error in the dependencies. As of [PyMongo 1.11](http://api.mongodb.org/python/1.11/api/index.html) [`objectid` lives in the `bson` module, not `pymongo`](http://api.mongodb.org/python/current/api/index.html).
MongoKit "ImportError: No module named objectid " error
10,401,499
7
2012-05-01T17:17:32Z
10,456,425
10
2012-05-04T21:33:15Z
[ "python", "python-2.7", "flask", "pymongo", "mongokit" ]
I get some very strange error using MongoKit: ``` >>> from mongokit import * Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.7/dist-packages/mongokit/__init__.py", line 35, in <module> from document import Document, ObjectId File "/usr/local/lib/python2.7/d...
As Electro said, it's a Bug. I used the following dirty little hack to keep my site running until it is fixed: ``` import sys import pymongo import bson.objectid pymongo.objectid = bson.objectid sys.modules["pymongo.objectid"] = bson.objectid ```
MySQL and Python Select Statement Issues
10,401,873
5
2012-05-01T17:48:00Z
10,402,201
21
2012-05-01T18:18:14Z
[ "python", "mysql", "select", "encoding" ]
Thanks for taking the time to read this. It's going to be a long post to explain the problem. I haven't been able to find an answer in all the usual sources. Problem: I am having an issue with using the select statement with python to recall data from a table in a mysql database. System and versions: ``` Linux ubunt...
Your execute statement doesn't seem quite correct. My understanding is that it should follow the pattern `cursor.execute( <select statement string>, <tuple>)` and by putting only a single value in the tuple location it is actually just a string. To make the second argument the correct data type you need to put a comma ...
"Unpack requires a string argument of length 4" when unpacking floats?
10,402,457
3
2012-05-01T18:39:05Z
10,402,510
8
2012-05-01T18:43:53Z
[ "python", "hex", "css-float" ]
I am trying to convert hex value to float using (Python 2.7) the following method: ``` def hex2float(x): y = 0 z = x.decode('hex') try: y = struct.unpack('!f', z)[0] except: print sys.exc_info()[1] print 'z = ' + z print 'y = %s' % (y) print 'x = ' + x return def...
You need four bytes to unpack, so prepend null bytes if necessary: ``` z = x.decode('hex') z = '\0' * (4 - len(z)) + z ``` Normally `str.decode` only outputs as much bytes as necessary to represent the value, so that's why you only see it happen for small values. This works perfectly: ``` >>> z = '615885'.decode("...
Comparing the first couple characters in a string
10,403,466
2
2012-05-01T19:55:22Z
10,403,496
8
2012-05-01T19:57:58Z
[ "python", "string", "compare" ]
So I have a list of strings: ``` list1 = ["1thing", "2thing", "3thing", "1thing"] ``` and I want to find out how many times each one is in the list. The thing is, I only want to compare the first couple of characters because I know that if the first, say 3 characters are the same, then the whole string is the same. I...
Use a generator to extract the first couple of characters, and use the builtin `collections.Counter` class on that: ``` Counter(item[:2] for item in list1) ```
OpenCV dot target detection not finding all targets, and found circles are offset
10,404,062
8
2012-05-01T20:43:02Z
10,416,428
8
2012-05-02T15:04:23Z
[ "python", "c", "opencv", "image-processing", "computer-vision" ]
I'm trying to detect the center of black/white dot targets, like in this picture. I've tried to use the cv2.HoughCircles method but 1, am only able to detect 2 to 3 targets, and 2, when I plot the found circles back onto the image, they're always offset slightly. Am I using the wrong method? Should I be using the find...
Playing the code I wrote in [another post](http://stackoverflow.com/a/6416361/176769), I was able to achieve a slightly better result: ![](http://i.stack.imgur.com/HPGeo.jpg) **It's all about the parameters.** It always is. There are 3 important functions that are called in this program that you should experiment wi...
When to use explicit wait vs implicit wait in selenium webdriver?
10,404,160
18
2012-05-01T20:50:33Z
28,067,495
36
2015-01-21T12:40:27Z
[ "python", "selenium", "selenium-webdriver", "webdriver" ]
I am using: ``` driver.manage().timeouts().implicitlyWait(180, TimeUnit.SECONDS); ``` But it still fails continuously for the below element ``` driver.findElement(By.id("name")).clear(); driver.findElement(By.id("name")).sendKeys("Create_title_01"); ``` I have added wait code: ``` for (int second = 0;; sec...
TL;DR: Always use explicit wait. Forget that implicit wait exists. --- Here is a quick rundown on the differences between explicit and implicit wait: Explicit wait: * documented and defined behaviour. * runs in the local part of selenium (in the language of your code). * works on any condition you can think of. * r...
os.path.getsize Returns Incorrect Value?
10,404,534
5
2012-05-01T21:20:58Z
10,404,634
7
2012-05-01T21:28:52Z
[ "python", "file", "directory", "size" ]
``` def size_of_dir(dirname): print("Size of directory: ") print(os.path.getsize(dirname)) ``` is the code in question. dirname is a directory with **130** files of about **1kb** each. When I call this function, it returns **4624**, which is **NOT** the size of the directory...why is this?
This value (4624B) represents the size of the *file* that *describes* that directory. Directories are described as inodes (<http://en.wikipedia.org/wiki/Inode>) that hold information about the files and directories it contains. To get the number of files/subdirectories inside that path, use: ``` len(os.path.listdir(d...
matplotlib set yaxis label size
10,404,759
32
2012-05-01T21:39:26Z
10,404,895
48
2012-05-01T21:51:14Z
[ "python", "matplotlib", "label", "graphing" ]
How can I change the size of only the yaxis label? Right now, I change the size of all labels using ``` pylab.rc('font', family='serif', size=40) ``` but in my case, I would like to make the y-axis label larger than the x-axis. However, I'd like to leave the tick labels alone. I've tried, for example: ``` pylab.gca...
If you are using the 'pylab' for interactive plotting you can set the labelsize at creation time with `pylab.ylabel('Example', fontsize=40)`. If you use `pyplot` programmatically you can either set the fontsize on creation with `ax.set_ylabel('Example', fontsize=40)` or afterwards with `ax.yaxis.label.set_size(40)`.
How could a distributed queue-like-thing be implemented on top of a RBDMS or NOSQL datastore or other messaging system (e.g., rabbitmq)?
10,404,921
7
2012-05-01T21:53:47Z
10,441,515
7
2012-05-04T01:24:45Z
[ "java", "python", "nosql", "message-queue", "rabbitmq" ]
From the wouldn't-it-be-cool-if category of questions ... By "queue-like-thing" I mean supports the following operations: * append(entry:Entry) - add entry to tail of queue * take(): Entry - remove entry from head of queue and return it * promote(entry\_id) - move the entry one position closer to the head; the entry ...
Redis supports lists and ordered sets: <http://redis.io/topics/data-types#lists> It also supports transactions and publish/subscribe messaging. So, yes, I would say this can be easily done on redis. Update: In fact, about 80% of it has been done many times: <http://www.google.co.uk/search?q=python+redis+queue> Sever...
piping in shell via Python subprocess module
10,405,515
5
2012-05-01T22:53:29Z
10,405,562
8
2012-05-01T22:59:26Z
[ "python", "shell", "subprocess", "pipe" ]
So I'm trying to query for the top 3 CPU "intensive" processes on a given machine, and I found this shell command to do it: `ps -eo pcpu,pid,user,args | sort -k 1 -r | head -3` I want to use this data inside a Python script, so I need to be able to capture the output of the above command via the `subprocess` module. T...
You can pass the `shell=True` argument to execute the plain shell command: ``` import subprocess subprocess.check_output('ps -eo pcpu,pid,user,args | sort -k 1 -r | head -3', shell=True) ``` Alternatively, use the sorting options of ps and Python's built-in string functions like this: ``` raw...
Check if something is not in a list in Python
10,406,130
86
2012-05-02T00:16:19Z
10,406,143
152
2012-05-02T00:18:42Z
[ "python", "list", "conditional-statements" ]
I have a list of tuples in [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29), and I have a conditional where I want to take the branch ONLY if the tuple is not in the list (if it is in the list, then I don't want to take the if branch) ``` if curr_x -1 > 0 and (curr_x-1 , curr_y) not in myList: ...
The bug is probably somewhere else in your code, because it should work fine: ``` >>> 3 not in [2, 3, 4] False >>> 3 not in [4, 5, 6] True ``` Or with tuples: ``` >>> (2, 3) not in [(2, 3), (5, 6), (9, 1)] False >>> (2, 3) not in [(2, 7), (7, 3), "hi"] True ```
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd1 in position 2: ordinal not in range(128)
10,406,135
37
2012-05-02T00:17:08Z
10,406,161
88
2012-05-02T00:21:01Z
[ "python", "django", "utf-8" ]
I am attempting to work with a very large dataset that has some non-standard characters in it. I need to use unicode, as per the job specs, but I am baffled. (And quite possibly doing it all wrong.) I open the CSV using: ``` 15 ncesReader = csv.reader(open('geocoded_output.csv', 'rb'), delimiter='\t', quotechar=...
Unicode is not equal to UTF-8. The latter is just an *encoding* for the former. You are doing it the wrong way around. You are *reading* UTF-8-*encoded* data, so you have to *decode* the UTF-8-encoded String into a unicode string. So just replace `.encode` with `.decode`, and it should work (if your .csv is UTF-8-enc...
When using subprocess.Popen(), stderr and stdout have no output
10,406,257
6
2012-05-02T00:34:33Z
10,406,270
8
2012-05-02T00:37:28Z
[ "python", "svn", "subprocess" ]
I'm using Python to automate an SVN commit, and I want to write the SVN command's output to a log file. The code that I have can make SVN run, but the problem is that on a successful commit, the `subprocess` invocation does not return any output for my log. When I run SVN manually, by comparison, I get output that sho...
Don't use `wait()` when you are using PIPE. Use communicate() ``` process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) out, err = process.communicate() ``` From the [subprocess docs](http://docs.python.org/library/subprocess.html#subprocess.Po...
How to Change Default Virtualenvwrapper Prompt
10,406,926
16
2012-05-02T02:24:25Z
20,026,992
28
2013-11-17T03:53:09Z
[ "python", "bash", "virtualenv", "command-prompt", "virtualenvwrapper" ]
How do you change the default Virtualenvwrapper prompt? By default, working on a particular virtual environment with a command like "workon <\_name\_of\_env\_>" prepends the name of the virtualenv to your prompt. This may work poorly if you're not using a default command prompt.
If you are working on a custom PS1 (as I when found out this issue), I recommend you to disable prompt change, use `export VIRTUAL_ENV_DISABLE_PROMPT=1` (see [virtualenv docs](https://virtualenv.pypa.io/en/latest/reference.html#envvar-VIRTUAL_ENV_DISABLE_PROMPT)), and make your own virtualenv prompt in order to add to ...
How do I get my HTML button to delete the right list item from a SQLite database?
10,407,433
6
2012-05-02T03:45:55Z
10,409,174
8
2012-05-02T07:04:59Z
[ "python", "html", "forms", "flask", "jinja2" ]
I'm a beginner, so forgive any stupidity in advance. I'm using Flask (and by extension Jinja2) to create a simple web app -- one that basically lets you type a movie into a web form, which adds it to a SQLite database. I've gotten Flask to very nicely iterate through all the movies in the database and print them to the...
Just add a hidden input to every form with the element id/name that you want to delete as the value :) eg. ``` <form action="{{ url_for('delete_movie') }}" method=post class=delete-movie> <input type=hidden value="{{ movie.name }}"name=movie_to_delete"></input> <input type=submit></input> </form> ```
python django - no module psycopg2.extension even after installing compiled version psycopg2-2.4.5.win32-py2.7.‌exe
10,407,564
8
2012-05-02T04:06:06Z
10,966,500
14
2012-06-10T05:11:41Z
[ "python", "django", "heroku", "psycopg2" ]
I am using python django on windows,and trying to deploy to heroku . When i tried to install psycopg2 using pip, ``` pip install psycopg2 ``` i got error : unable to find vcvarsall.bat Then i found that i need to install visual studio 2008 (or) i can directly download and install compiled version , so downla...
Despite some claims on the Internet, psycopg2 DOES work in a VirtualEnv. Download the correct version of [win-psycopg2](http://www.stickpeople.com/projects/python/win-psycopg/). Typically I use 32-bit Python 2.7 so I got psycopg2-2.4.5.win32-py2.7-pg9.1.3-release.exe. You CANNOT install this file into a VirtualEnv, b...
Django: MEDIA_URL returns Page Not Found
10,408,022
5
2012-05-02T05:08:43Z
10,408,267
7
2012-05-02T05:38:48Z
[ "python", "django", "media-url" ]
**settings.py** ``` # -*- coding: utf-8 -*- # Django settings for basic pinax project. import os.path import posixpath PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) DEBUG = True TEMPLATE_DEBUG = DEBUG # tells Pinax to serve media through the staticfiles app. SERVE_MEDIA = DEBUG # django-compressor is ...
Add following line under `if settings.DEBUG` in urls.py ``` (r'^site-media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes':True}), ``` Or set `MEDIA_URL = "/media/"` `staticfiles` serves static files, for media file, you have to specify serving path explicitly. *up...
Generators to iterate over a dictionary uniformly in both Python 2 and 3
10,408,119
7
2012-05-02T05:22:29Z
10,408,235
9
2012-05-02T05:34:41Z
[ "python", "python-3.x" ]
Is there a way to efficiently iterate over the values/items in a dictionary that works in both Python 2 and Python 3? In Python 2, I can write ``` for x in mydict: for x in mydict.iterkeys(): for x in mydict.viewkeys(): for x in mydict.itervalues(): for x in mydict.viewvalues(): for x in mydict.iteritems(): for x in ...
values() version of Just another dunce's answer ``` for value in (mydict[key] for key in mydict): ``` or ``` def dict_values(d): return (mydict[key] for key in mydict) def dict_items(d): return ((key, mydict[key]) for key in mydict) for value in dict_values(mydict): ... for value in dict_items(mydict): ...
Python program to Website Application
10,408,208
2
2012-05-02T05:31:53Z
10,409,701
7
2012-05-02T07:49:07Z
[ "python", "django", "web", "cgi", "pyramid" ]
I'm working on a project which is converting a 50mb python Graduated interval recall rating system for pictures and text program to a website based application. (and then design a website around it) It needs to connect to a database to store user information frequently so it needs to be run server side correct? Assumin...
Well, it may be difficult to give you a good advice because the description of your project is quite vague - what in the world is "a 50mb python Graduated interval recall rating system for pictures and text program"??? :) - but I'll try to outline the difference between the options you're listing: **Django** is a sort...
Python inheritance - calling base class methods inside child class?
10,408,739
11
2012-05-02T06:27:12Z
10,408,847
10
2012-05-02T06:37:36Z
[ "python", "class", "inheritance", "base-class", "overwrite" ]
It baffles me how I can't find a clear explanation of this anywhere. Why and when do you need to call the method of the base class inside the same-name method of the child class? ``` class Child(Base): def __init__(self): Base.__init__(self) def somefunc(self): Base.somefunc(self) ``` I'm gue...
Usually, you do this when you want to extend the functionality by modifiying, but not completely replacing a base class method. `defaultdict` is a good example of this: ``` class DefaultDict(dict): def __init__(self, default): self.default = default dict.__init__(self) def __getitem__(self, ke...
Remove leading and trailing slash /
10,408,826
15
2012-05-02T06:35:28Z
10,408,845
52
2012-05-02T06:37:32Z
[ "python", "django", "path", "strip" ]
I am using `request.path` to return the current URL in Django, and it is returning `/get/category`. I need it as `get/category` (without leading and trailing slash). How can I do this?
``` >>> "/get/category".strip("/") 'get/category' ``` `strip()` is the proper way to do this.
How to get all sub-elements of an element tree with Python ElementTree?
10,408,927
4
2012-05-02T06:43:50Z
10,409,082
8
2012-05-02T06:56:49Z
[ "python", "xml", "elementtree" ]
I want to find a way to get all the sub-elements of an element tree like the way ElementTree.getchildren() does, since getchildren() is deprecated since Python version 2.7, I don't want to use it anymore, though I can still use it currently. Thanks.
All sub-elements (descendants) of `elem`: ``` all_descendants = list(elem.iter()) ``` A more complete example: ``` >>> import xml.etree.ElementTree as ET >>> a = ET.Element('a') >>> b = ET.SubElement(a, 'b') >>> c = ET.SubElement(a, 'c') >>> d = ET.SubElement(a, 'd') >>> e = ET.SubElement(b, 'e') >>> f = ET.SubEleme...
add blobs or trees to a created repository using pygit2 (libgit2)?
10,409,378
6
2012-05-02T07:22:20Z
10,415,537
7
2012-05-02T14:14:33Z
[ "python", "git", "libgit2" ]
I am trying to use pygit2 library. seems I got stuck on the first step. its documentation doesn't explain how to create a blob and add it to a tree. It is mostly around how to work with an existing git repository but I want to create one and add blobs, commits, ... to my repo. Is it possible to create a blob from a fi...
The python bindings don't let you create a blob from a file directly, so you'll have to read in the file to memory and use `Repository.write(pygit2.GIT_OBJ_BLOB, filecontents)` to create the blob. You can then create trees with the `TreeBuilder`, for example, like ``` import pygit2 as g repo = g.Repository('.') # gr...
IOError Input/Output Error When Printing
10,409,897
13
2012-05-02T08:05:16Z
20,997,655
7
2014-01-08T13:53:14Z
[ "python", "io", "stdout", "ioerror" ]
I have inherited some code which is periodically (randomly) failing due to an Input/Output error being raised during a call to print. I am trying to determine the cause of the exception being raised (or at least, better understand it) and how to handle it correctly. When executing the following line of Python (in a 2....
I think it has to do with the terminal the process is attached to. I got this error when I run a python process in the background and closed the terminal in which I started it: ``` $ myprogram.py Ctrl-Z $ bg $ exit ``` The problem was that I started a not daemonized process in a remote server and logged out (closing ...
Converting integer to binary in python
10,411,085
64
2012-05-02T09:31:41Z
10,411,108
146
2012-05-02T09:32:56Z
[ "python", "binary", "integer" ]
In order to convert an integer to a binary, i have used this code : ``` >>> bin(6) '0b110' ``` and when to erase the '0b', i use this : ``` >>> bin(6)[2:] '110' ``` What can i do if i want to show `6` as `00000110` instead of `110`?
``` >>> '{0:08b}'.format(6) 00000110 ``` Just to explain the parts of the formatting string: * `{}` places a variable into a string * `0` takes the variable at argument position 0 * `:` adds formatting options for this variable (otherwise it would represent decimal `6`) * `08` formats the number to eight digits zero-...
Converting integer to binary in python
10,411,085
64
2012-05-02T09:31:41Z
10,411,184
52
2012-05-02T09:37:09Z
[ "python", "binary", "integer" ]
In order to convert an integer to a binary, i have used this code : ``` >>> bin(6) '0b110' ``` and when to erase the '0b', i use this : ``` >>> bin(6)[2:] '110' ``` What can i do if i want to show `6` as `00000110` instead of `110`?
Just another idea: ``` >>> bin(6)[2:].zfill(8) '00000110' ```
Converting integer to binary in python
10,411,085
64
2012-05-02T09:31:41Z
10,411,628
8
2012-05-02T10:07:33Z
[ "python", "binary", "integer" ]
In order to convert an integer to a binary, i have used this code : ``` >>> bin(6) '0b110' ``` and when to erase the '0b', i use this : ``` >>> bin(6)[2:] '110' ``` What can i do if i want to show `6` as `00000110` instead of `110`?
A bit twiddling method... ``` >>> bin8 = lambda x : ''.join(reversed( [str((x >> i) & 1) for i in range(8)] ) ) >>> bin8(6) >>> '00000110' ```
WindowsError: [Error 126] when loading a DLL with ctypes
10,411,709
6
2012-05-02T10:13:51Z
10,412,956
11
2012-05-02T11:37:47Z
[ "python", "windows", "dll", "ctypes" ]
This works fine on Windows 7 with Python 2.7: ``` lib = ctypes.cdll.LoadLibrary('prov_means') provmeans = lib.provmeans ``` The library prov\_means.DLL is in my working directory. It exports a simple, stand-alone C function provmeans() with no dependencies. When I try the same thing on Windows XP and Python 2.7 I ge...
Error 126 is what you get when a dependent DLL can not be found. There are two obvious causes for this: 1. Your DLL is not being located. 2. Your DLL depends on other DLLs that cannot be found. I doubt that option 1 is the problem but in any case I think I would probably be using a full path to that DLL to be sure. ...
How to run nginx + python (without django)
10,412,063
7
2012-05-02T10:39:00Z
10,412,223
8
2012-05-02T10:48:55Z
[ "python", "nginx", "web", "fastcgi" ]
I want to have simple program in python that can process different requests (POST, GET, MULTIPART-FORMDATA). I don't want to use a complete framework. I basically need to be able to get GET and POST params - probably (but not necessarily) in a way similar to PHP. To get some other SERVER variables like REQUEST\_URI, Q...
Although you can make Python run a webserver by itself with [`wsgiref`](http://docs.python.org/library/wsgiref.html#examples), I would recommend using one of the [many Python webservers](http://nichol.as/benchmark-of-python-web-servers) around. In the case of Nginx I would look at Gunicorn or uWSGI.
processing of list of list
10,414,018
2
2012-05-02T12:43:26Z
10,414,046
11
2012-05-02T12:45:34Z
[ "python", "list" ]
I am working on lists of list input: ``` x = [['a','a','a'],['b','b','b'],['c','c','c'],['d','d','d']] ``` and am looking for an output: ``` s = ['a_b_c_d','a_b_c_d','a_b_c_d'] ``` Kindly let me know how can I do this using list comprehension.
``` In [6]: x = [['a','a','a'],['b','b','b'],['c','c','c'],['d','d','d']] In [7]: ['_'.join(s) for s in zip(*x)] Out[7]: ['a_b_c_d', 'a_b_c_d', 'a_b_c_d'] ``` As requested, this uses a list comprehension. See @eumiro's answer for a `map()`-based solution that I think is just as good.
processing of list of list
10,414,018
2
2012-05-02T12:43:26Z
10,414,049
12
2012-05-02T12:45:43Z
[ "python", "list" ]
I am working on lists of list input: ``` x = [['a','a','a'],['b','b','b'],['c','c','c'],['d','d','d']] ``` and am looking for an output: ``` s = ['a_b_c_d','a_b_c_d','a_b_c_d'] ``` Kindly let me know how can I do this using list comprehension.
``` >>> x = [['a','a','a'],['b','b','b'],['c','c','c'],['d','d','d']] >>> map('_'.join, zip(*x)) ['a_b_c_d', 'a_b_c_d', 'a_b_c_d'] ``` … although @aix's list comprehension is more list-comprehensible.
Python: Why should I use next() and not obj.next()?
10,414,210
22
2012-05-02T12:55:10Z
10,414,229
24
2012-05-02T12:56:59Z
[ "python", "next", "built-in" ]
Python 2.6 introduced a `next` function. Why was this necessary? One could always type `obj.next()` instead of `next(obj)`. Is the latter more `pythonic`?
> [`next(iterator[, default])`](http://docs.python.org/2/library/functions.html#next) > > Retrieve the next item from the *iterator* by calling its `next()``(__next__()` in python 3) method. If *default* is given, it is returned if the iterator is exhausted, otherwise `StopIteration` is raised. You get the `default` o...
Python: Why should I use next() and not obj.next()?
10,414,210
22
2012-05-02T12:55:10Z
10,414,254
10
2012-05-02T12:58:30Z
[ "python", "next", "built-in" ]
Python 2.6 introduced a `next` function. Why was this necessary? One could always type `obj.next()` instead of `next(obj)`. Is the latter more `pythonic`?
Apart from the obvious additional functionality, it also looks better when used together with generator expressions. Compare ``` (x for x in lst if x > 2).next() ``` to ``` next(x for x in lst if x > 2) ``` The latter is a lot more consistent with the rest of Python's style, IMHO.
Python: Why should I use next() and not obj.next()?
10,414,210
22
2012-05-02T12:55:10Z
10,414,364
34
2012-05-02T13:05:31Z
[ "python", "next", "built-in" ]
Python 2.6 introduced a `next` function. Why was this necessary? One could always type `obj.next()` instead of `next(obj)`. Is the latter more `pythonic`?
[PEP 3114](http://www.python.org/dev/peps/pep-3114/) describes this change. An excerpt about the motivation: > This PEP proposes that the `next` method be renamed to `__next__`, > consistent with all the other protocols in Python in which a method is > implicitly called as part of a language-level protocol, and that a...
Exhausting floating point precision in a (seemingly) infinite loop
10,414,992
4
2012-05-02T13:41:49Z
10,415,035
11
2012-05-02T13:44:51Z
[ "python", "floating-point", "floating-accuracy", "floating-point-precision" ]
I've got the following Python script: ``` x = 300000000.0 while (x < x + x): x = x + x print "exec: " + str(x) print "terminated" + str(x) ``` This seemingly infinite loop, terminates pretty quickly if x is a floating point number. But if i change x to 300000000 instead, it gets into an infinite loop (runs lo...
* When you initialize `x` to `300000000`, integer math is used throughout the program. * When you initialize `x` to `300000000.0`, floating-point math is used instead. In Python, integers can grow arbitrarily large. (More accurately, they're limited by the available memory.) This means that the integer version of your...
How can I recover the return value of a function passed to multiprocessing.Process?
10,415,028
34
2012-05-02T13:44:34Z
10,415,215
35
2012-05-02T13:55:08Z
[ "python", "multiprocessing" ]
In the example code below, I'd like to recover the return value of the function `worker`. How can I go about doing this? Where is this value stored? **Example Code:** ``` import multiprocessing def worker(procnum): '''worker function''' print str(procnum) + ' represent!' return procnum if __name__ == '...
Use [shared variable](http://docs.python.org/library/multiprocessing.html#sharing-state-between-processes) to communicate. For example like this: ``` def worker(procnum, return_dict): '''worker function''' print str(procnum) + ' represent!' return_dict[procnum] = procnum if __name__ == '__main__': ma...
How can I recover the return value of a function passed to multiprocessing.Process?
10,415,028
34
2012-05-02T13:44:34Z
28,799,109
14
2015-03-01T21:09:38Z
[ "python", "multiprocessing" ]
In the example code below, I'd like to recover the return value of the function `worker`. How can I go about doing this? Where is this value stored? **Example Code:** ``` import multiprocessing def worker(procnum): '''worker function''' print str(procnum) + ' represent!' return procnum if __name__ == '...
I think the approach suggested by @sega\_sai is the better one. But it really needs a code example, so here goes: ``` import multiprocessing from os import getpid def worker(procnum): print 'I am number %d in process %d' % (procnum, getpid()) return getpid() if __name__ == '__main__': pool = multiprocess...
How can I use the Django ORM in my Tornado application?
10,415,429
17
2012-05-02T14:06:59Z
10,415,532
12
2012-05-02T14:14:18Z
[ "python", "django", "tornado" ]
I have an existing Django application with a database and corresponding **models.py** file. I have a new Tornado application that provides a web service to other applications. It needs to read/write from that same database, and there is code in the models file I'd like to use. How can I best use the Django database a...
Add the path to the Django project to the Tornado application's PYTHONPATH env-var and set DJANGO\_SETTINGS\_MODULE appropriately. You should then be able to import your models and use then as normal with Django taking care of initial setup on the first import. You shouldn't require any symlinks.
How can I use the Django ORM in my Tornado application?
10,415,429
17
2012-05-02T14:06:59Z
10,415,717
17
2012-05-02T14:23:48Z
[ "python", "django", "tornado" ]
I have an existing Django application with a database and corresponding **models.py** file. I have a new Tornado application that provides a web service to other applications. It needs to read/write from that same database, and there is code in the models file I'd like to use. How can I best use the Django database a...
there is an example [here](https://bitbucket.org/yml/dj_tornado/src/c9a11ce11d4c/dj_tornado.py) about how to use django ORM and django form inside Tornado. and you can read [Using Django Inside the Tornado Web Server](http://lincolnloop.com/blog/2009/sep/15/using-django-inside-tornado-web-server/) for some information....
How to process a string into layer of sublists
10,415,752
8
2012-05-02T14:25:44Z
10,416,064
10
2012-05-02T14:42:09Z
[ "python", "list", "recursion", "sublist" ]
This is the example form, I'll try to explain it in words later. I have a list from breaking up a string... say ``` [a, a, a, b, a, a, b, a, c, a, b, a, a, c, a, c, a] ``` where b is criteria 1 and c is criteria 2 I want to break it into a list like this: ``` [a, a, a, [b, a, a, [b, a, c], a, [b, a, a, c], a, c], ...
here you go: ``` lst = "aaabaabacabaacaca" def go(it): for x in it: if x == 'b': yield [x] + list(go(it)) else: yield x if x == 'c': break print list(go(iter(lst))) ```
replacing layout on a QWidget with another layout
10,416,582
4
2012-05-02T15:13:02Z
10,439,207
14
2012-05-03T20:56:41Z
[ "python", "layout", "qt4", "pyqt4" ]
I have a widget which changes when an option is toggled. This invalidates all layouts and widgets. I keep list of all layouts, so I can delete them using something similar to [this answer](http://stackoverflow.com/a/9383780/761090): ``` class MyWidget(QFrame): # ... def reLayout(self): def deleteLayoutChil...
You can simply reparent the layout to a temporary widget: ``` def reLayout(self): QWidget().setLayout(self.layout()) layout = QGridLayout(self) ... ``` That will reparent all the child widgets to that temporary object, and that object is deleted immediately along with its new children because we don't kee...
What is different between all these OpenCV Python interfaces?
10,417,108
55
2012-05-02T15:42:01Z
10,425,504
103
2012-05-03T05:16:31Z
[ "python", "opencv" ]
There are * [`opencv`](http://opencv.willowgarage.com/documentation/python/introduction.html) (the library from the OpenCV guys), * [`cv`](http://opencv.willowgarage.com/documentation/python/cookbook.html) (the old library from the OpenCV guys) and * [`pyopencv`](https://code.google.com/p/pyopencv/) with its predecess...
Officially, OpenCV releases two types of Python interfaces, `cv` and `cv2`. **cv:** I started working on `cv`. In this, all OpenCV data types are preserved as such. For example, when loaded, images are of format `cvMat`, same as in C++. For array operations, there are several functions like `cvSet2D`, `cvGet2D`, etc...
Python multi-lists iteration
10,418,575
6
2012-05-02T17:16:57Z
10,418,613
13
2012-05-02T17:19:11Z
[ "python", "list", "iteration" ]
Is there a clever way to iterate over **two** lists in Python (without using *list comprehension*)? I mean, something like this: ``` # (a, b) is the cartesian product between the two lists' elements for a, b in list1, list2: foo(a, b) ``` instead of: ``` for a in list1: for b in list2: foo(a, b) ```
[`itertools.product()`](http://docs.python.org/library/itertools.html#itertools.product) does exactly this: ``` for a, b in itertools.product(list1, list2): foo(a, b) ``` It can handle an arbitrary number of iterables, and in that sense is more general than nested `for` loops.
How does pgBouncer help to speed up Django
10,419,665
12
2012-05-02T18:34:56Z
10,419,731
9
2012-05-02T18:39:19Z
[ "python", "django", "postgresql", "connection-pooling", "pgbouncer" ]
I have some management commands that are based on gevent. Since my management command makes thousands to requests, I can turn all socket calls into non-blocking calls using Gevent. This really speeds up my application as I can make requests simultaneously. Currently the bottleneck in my application seems to be Postgre...
PgBouncer reduces the latency in establishing connections by serving as a proxy which maintains a connection pool. This may help speed up your application if you're opening many short-lived connections to Postgres. If you only have a small number of connections, you won't see much of a win.
How does pgBouncer help to speed up Django
10,419,665
12
2012-05-02T18:34:56Z
10,420,469
55
2012-05-02T19:37:03Z
[ "python", "django", "postgresql", "connection-pooling", "pgbouncer" ]
I have some management commands that are based on gevent. Since my management command makes thousands to requests, I can turn all socket calls into non-blocking calls using Gevent. This really speeds up my application as I can make requests simultaneously. Currently the bottleneck in my application seems to be Postgre...
Besides saving the overhead of connect & disconnect where this is otherwise done on each request, a connection pooler can funnel a large number of client connections down to a small number of actual database connections. In PostgreSQL, the optimal number of active database connections is usually somewhere around ((2 \*...
Adding the number 1 to a set has no effect
10,419,918
9
2012-05-02T18:53:58Z
10,419,951
13
2012-05-02T18:56:32Z
[ "python", "python-3.x", "set" ]
I cannot add the integer number `1` to an existing set. In an interactive shell, this is what I am doing: ``` >>> st = {'a', True, 'Vanilla'} >>> st {'a', True, 'Vanilla'} >>> st.add(1) >>> st {'a', True, 'Vanilla'} # Here's the problem; there's no 1, but anything else works >>> st.add(2) >>> st {'a', True, 'Vanilla...
``` >>> 1 == True True ``` I believe your problem is that `1` and `True` are the same value, so 1 is "already in the set". ``` >>> st {'a', True, 'Vanilla'} >>> 1 in st True ``` In mathematical operations `True` is itself treated as `1`: ``` >>> 5 + True 6 >>> True * 2 2 >>> 3. / (True + True) 1.5 ``` Though True ...
Django - How to get admin url from model instance
10,420,271
17
2012-05-02T19:21:58Z
10,420,333
21
2012-05-02T19:26:03Z
[ "python", "django", "django-models", "django-admin" ]
First of all, thank you for reading my question. I'm trying to send an email to a user when a new model instance is saved and I want the email to include a link to the admin page for that model instance. Is there a way to get the correct URL? I figure Django must have that information stored somewhere.
This [Django snippet](http://djangosnippets.org/snippets/1916/) should do: ``` from django.core import urlresolvers from django.contrib.contenttypes.models import ContentType from django.db import models class MyModel(models.Model): def get_admin_url(self): content_type = ContentType.objects.get_for_mode...
Django - How to get admin url from model instance
10,420,271
17
2012-05-02T19:21:58Z
10,420,949
27
2012-05-02T20:13:12Z
[ "python", "django", "django-models", "django-admin" ]
First of all, thank you for reading my question. I'm trying to send an email to a user when a new model instance is saved and I want the email to include a link to the admin page for that model instance. Is there a way to get the correct URL? I figure Django must have that information stored somewhere.
Not trying to rip off @JosvicZammit, but using `ContentType` is the wrong approach here. It's just a wasted DB query. You can get the require info from the `_meta` attribute: ``` from django.core.urlresolvers import reverse info = (model_instance._meta.app_label, model_instance._meta.model_name) admin_url = reverse('...
group list of ints by continuous sequence
10,420,464
9
2012-05-02T19:36:46Z
10,420,670
11
2012-05-02T19:51:45Z
[ "python" ]
I have a list of integers... ``` [1,2,3,4,5,8,9,10,11,200,201,202] ``` I would like to group them into a list of lists where each sublist contains integers whose sequence has not been broken. Like this... ``` [[1,5],[8,11],[200,202]] ``` I have a rather clunky work around... ``` lSequenceOfNum = [1,2,3,4,5,8,9,10,...
Assuming the list will always be in ascending order: ``` from itertools import groupby, count numberlist = [1,2,3,4,5,8,9,10,11,200,201,202] def as_range(g): l = list(g) return l[0], l[-1] print [as_range(g) for _, g in groupby(numberlist, key=lambda n, c=count(): n-next(c))] ```
how to make jenkins run a python script that executes a build?
10,421,879
7
2012-05-02T21:18:14Z
10,422,128
8
2012-05-02T21:40:38Z
[ "python", "hudson", "jenkins" ]
Learning Jenkins, and trying to get it to build a project for which my build script is written in python. ``` ./build.py -i ``` I've tried using the 'Execute script' and 'Execute Python script'. The script first line is ``` #!/usr/bin/python ``` Jenkins doesn't complain about either attempt, it just seems to ignore...
You should be able to use an "Execute shell" build step and specify `/path/to/build.py -i` I'm guessing that the current directory when the build job runs isn't what you're expecting. Jenkins has a built-in environment variable WORKSPACE that is set to the root of the build's workspace, so assuming that the Python scr...
Relative paths in scripts executed by cron jobs
10,422,377
4
2012-05-02T22:06:50Z
10,422,444
8
2012-05-02T22:13:08Z
[ "python", "cron", "crontab" ]
I'm setting up my first cron job and it's not working. I think the problem may be a relative path issue. Given cron job: ``` */1 * * * * python2.7 /home/path/to/my/script/my_script.py ``` and my\_script.py: ``` import sqlite3 db = sqlite3.connect('my_db.db') cur = db.cursor() ... ``` How do I make sure that `my_sc...
``` import sqlite3 import os dir_path = os.path.dirname(os.path.abspath(__file__)) db = sqlite3.connect(os.path.join(dir_path, 'my_db.db')) cur = db.cursor() ... ``` Remember that Python's [os.path module](http://docs.python.org/library/os.path.html#module-os.path) is your best friend when manipulating paths.
line, = plot(x,sin(x)) what does comma stand for?
10,422,504
12
2012-05-02T22:18:32Z
10,422,547
15
2012-05-02T22:22:40Z
[ "python", "numpy", "matplotlib" ]
I'm trying to make an animated plot. Here is an example code: ``` from pylab import * import time ion() tstart = time.time() # for profiling x = arange(0,2*pi,0.01) # x-array line, = plot(x,sin(x)) for i in arange(1,200): line.set_ydata(sin(x+i/10.0)) # update the data draw() ...
The comma is Python syntax that denotes either a single-element tuple. E.g., ``` >>> tuple([1]) (1,) ``` In this case, it is used for argument unpacking: `plot` returns a single-element list, which is unpacked into `line`: ``` >>> x, y = [1, 2] >>> x 1 >>> y 2 >>> z, = [3] >>> z 3 ``` An alternative, perhaps more r...
PyMongo Cursor Iteration
10,424,078
2
2012-05-03T01:53:04Z
10,424,151
9
2012-05-03T02:06:04Z
[ "python", "mongodb", "pymongo" ]
I'm looking to create and handle a cursor in python the way cursors natively work in mongo. I know the intended way is to do 'result = collection.find()' and do a 'for record in result' but I'm looking to wrap iteration functionality in a class. I'd like to be able to create a new class object and call a function e.g. ...
I don't understand how what you are showing is any more convenient that just doing: ``` col = pymongo.Connection().db.collection cur = col.find({}) obj = next(cur, None) if obj: age = obj['age'] gender = obj['gender'] ``` Its not clear how this wrapper is helpful. Also, if what you are really after is an ORM...
What are the connection limits for Google Cloud SQL from App Engine, and how to best reuse DB connections?
10,424,442
6
2012-05-03T02:46:30Z
10,436,158
13
2012-05-03T17:09:17Z
[ "python", "mysql", "google-app-engine", "wsgi", "google-cloud-sql" ]
I have a Google App Engine app that uses a Google Cloud SQL instance for storing data. I need my instance to be able to serve hundreds of clients at a time, via restful calls, which each result in one or a handful of DB queries. I've wrapped the methods that need DB access and store the handle to the DB connection in o...
Short answer: Your queries are probably too slow and the mysql server doesn't have enough threads to process all of the requests you are trying to send it. Long Answer: As background, Cloud SQL has two limits that are relevant here: * Connections: These correspond to the 'conn' object in your code. There is a corres...
How do I remove all punctuation that follows a string?
10,424,738
4
2012-05-03T03:34:34Z
10,424,749
11
2012-05-03T03:35:38Z
[ "python", "regex", "string" ]
It's for a game in which the user can input a value like "Iced tea.." I would like to manipulate the string to return "Iced tea" without the trailing punctuation marks. Looking for most elegant / simplest python solution. Tried ``` def last_character(word): if word.endswith('.' or ','): word = word[:-1] re...
``` >>> 'words!?.,;:'.rstrip('?:!.,;') 'words' ```
Python inequalities: != vs not ==
10,424,983
5
2012-05-03T04:09:30Z
10,425,003
13
2012-05-03T04:12:24Z
[ "python", "operators" ]
I realized today while writing some Python that one could write the inequality operator as `a!=b` or `not a==b`. This got me curious: 1. Do both ways behave exactly the same, or are there some subtle differences? 2. Is there any reason to use one over the other? Is one more commonly used than the other?
1. `==` invokes `__eq__()`. `!=` invokes `__ne__()` if it exists, otherwise is equivalent to `not ==`. 2. Not unless the difference in 1 matters.
Python inequalities: != vs not ==
10,424,983
5
2012-05-03T04:09:30Z
10,425,040
7
2012-05-03T04:16:14Z
[ "python", "operators" ]
I realized today while writing some Python that one could write the inequality operator as `a!=b` or `not a==b`. This got me curious: 1. Do both ways behave exactly the same, or are there some subtle differences? 2. Is there any reason to use one over the other? Is one more commonly used than the other?
Be mindful of your parenthesis. ``` >>> not "test" == True True >>> not "test" and True False ``` `==` takes precedence over `not`. But `not` and `and` have the same precedence, so [Python Operators Precedence](http://www.tutorialspoint.com/python/python_basic_operators.htm "Python Operators Precedence")
Is shifting required to pop the front of a list in Python?
10,426,500
4
2012-05-03T06:52:14Z
10,426,549
8
2012-05-03T06:55:33Z
[ "python", "list" ]
The python data strcutures page <http://docs.python.org/tutorial/datastructures.html> says *It is also possible to use a list as a queue, where the first element added is the first element retrieved (“first-in, first-out”); however, lists are not efficient for this purpose. While appends and pops from the end of l...
> No shifting is required while doing a pop operation at the list -head right? Think of a list as an array of references, where the first element of the list is *always* at array position zero. When you pop the first element of the list, you have to shift all the reference to the left by one position. One could imagi...
Store multi-line input into a String (Python)
10,426,699
3
2012-05-03T07:08:32Z
10,426,764
11
2012-05-03T07:13:09Z
[ "python" ]
Input: ``` 359716482 867345912 413928675 398574126 546281739 172639548 984163257 621857394 735492861 ``` my code : ``` print("Enter the array:\n") userInput = input().splitlines() print(userInput) ``` my problem here is that, `userInput` only takes in the first line value but it doesn't seem to take in values af...
You can use `readlines()` method of file objects: ``` import sys userInput = sys.stdin.readlines() ```
Animate quadratic grid changes (matshow)
10,429,556
6
2012-05-03T10:30:42Z
10,431,216
10
2012-05-03T12:17:44Z
[ "python", "numpy", "matplotlib" ]
I have a NxN grid with some values, which change every time step. I have found a way to plot a single grid configuration of this with `matshow` function, but I don't know how do I update the status with every time step. Here is a simple example: ``` from pylab import * from matplotlib import pyplot a = arange(25) a =...
matplotlib 1.1 has an animation module (look at the [examples](http://matplotlib.sourceforge.net/examples/animation/index.html#animation-examples-index)). Using `animation.FuncAnimation` you can update your plot like so: ``` import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation ...
Django: Is separating views.py into its own module a good idea?
10,430,095
4
2012-05-03T11:06:14Z
10,430,277
7
2012-05-03T11:18:28Z
[ "python", "django", "django-views", "python-import" ]
### Dilemma My `views.py` gets pretty unwieldy, so I want to separate it into a separate `views` module inside of my app. However, I'm not sure this is a good idea, for two reasons: 1. If my views file is the same name as the app name, I cannot import the model without using `django.db.get_model`, therefore I am worr...
> I cannot import the model without using django.db.get\_model You can: `from project_name.app_name.models import MyModel` And it's preferable way, 'relative imports for intra-package imports are highly discouraged', - as [said in PEP-8](http://www.python.org/dev/peps/pep-0008/#imports). There shouldn't be any proble...
In python, is set.pop() deterministic?
10,432,022
7
2012-05-03T13:06:28Z
10,432,828
13
2012-05-03T13:51:58Z
[ "python", "set" ]
I understand that the elements of a python set are not ordered. Calling the pop method returns an arbitrary element; I'm fine with that. What I'm wondering is whether or not pop will ALWAYS return the same element when the set has the same history. Within one version of python of course, I don't mind if different vers...
The answer in general is **no.** The python source that @Christophe and @Marcin (un)helpfully point to shows that elements are popped in the order they appear in the hash table. So, pop order (and presumably iteration order) *is* deterministic, but only for *fixed* hash values. That's the case for numbers but *not* for...
Python Syntax for Chained Conditionals
10,433,142
5
2012-05-03T14:09:15Z
10,433,163
12
2012-05-03T14:10:40Z
[ "python", "conditional-operator" ]
I'm a beginner in Python currently self-learning via the book "How to Think like a Computer Scientist" From an exercise from the book on Chained Conditionals, Syntax taught was: ``` def function(x,y) if ..: print ".." elif..: print ".." else: print".." ``` However, when I tried this to fin...
Though your second example is working, it is *not* the same thing as the first example. In the second, every `if` condition will be evaluated, regardless of whether or not a previous one was true and executed. In the chained `if/elif` example, the whole thing is treated as a unit and only the first matched condition wi...
How to make python3.2 interpreter the default interpreter in debian
10,434,260
12
2012-05-03T15:12:33Z
10,434,370
20
2012-05-03T15:18:51Z
[ "python", "linux", "debian" ]
I got both python2 and python3 installed in my debian machine. But when i try to invoke the python interpreter by just typing 'python' in bash, python2 pops up and not python3. Since I am working with the latter at the moment, It would be easier to invoke python3 by just typing python. Please guide me through this.
the only somehow safe way would be to use an alias in your shell, by placing ``` alias python=python3 ``` into your `~/.profile` or `~/.bashrc`... this way the system scripts depending on python being python2 won't be affected.
How to make python3.2 interpreter the default interpreter in debian
10,434,260
12
2012-05-03T15:12:33Z
10,468,921
8
2012-05-06T07:28:09Z
[ "python", "linux", "debian" ]
I got both python2 and python3 installed in my debian machine. But when i try to invoke the python interpreter by just typing 'python' in bash, python2 pops up and not python3. Since I am working with the latter at the moment, It would be easier to invoke python3 by just typing python. Please guide me through this.
Well, you can simply create a `virtualenv` with the python3.x using this command: `virtualenv -p <path-to-python3.x> <virtualenvname>`
How can I get the whole request POST body in Python with Flask?
10,434,599
136
2012-05-03T15:31:26Z
10,434,709
122
2012-05-03T15:38:22Z
[ "python", "flask" ]
I want to be able to get the whole POST body of the request as a string or file handle that I can read but I'm unable to find a way (I'm new to Flask and Python for web at all). This is what I got: ``` from flask import Flask app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def parse_request(): # ob...
``` from flask import request request.data ```
How can I get the whole request POST body in Python with Flask?
10,434,599
136
2012-05-03T15:31:26Z
16,664,376
213
2013-05-21T07:25:07Z
[ "python", "flask" ]
I want to be able to get the whole POST body of the request as a string or file handle that I can read but I'm unable to find a way (I'm new to Flask and Python for web at all). This is what I got: ``` from flask import Flask app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def parse_request(): # ob...
The [docs](http://flask.pocoo.org/docs/api/#flask.Request) describe the attributes available on the request. In most common cases `request.data` will be empty because it's used as a fallback: > `request.data` Contains the incoming request data as string in case it came with a mimetype Flask does not handle. * `reques...
How can I get the whole request POST body in Python with Flask?
10,434,599
136
2012-05-03T15:31:26Z
25,268,170
39
2014-08-12T15:22:24Z
[ "python", "flask" ]
I want to be able to get the whole POST body of the request as a string or file handle that I can read but I'm unable to find a way (I'm new to Flask and Python for web at all). This is what I got: ``` from flask import Flask app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def parse_request(): # ob...
It is simply as follows For **URL Query parameter**, use **request.args** ``` search = request.args.get("search") page = request.args.get("page") ``` For **Form input**, use **request.form** ``` email = request.form.get('email') password = request.form.get('password') ``` For **data type application/json**, use **...
Replacing a substring of a string with Python
10,436,454
19
2012-05-03T17:30:00Z
10,436,472
8
2012-05-03T17:31:43Z
[ "python", "string", "substring", "string-interpolation" ]
I'd like to get a few opinions on the best way to replace a substring of a string with some other text. Here's an example: I have a string, a, which could be something like "Hello my name is $name". I also have another string, b, which I want to insert into string a in the place of its substring '$name'. I assume it ...
Actually this is already implemented in the module [`string.Template`](http://docs.python.org/library/string.html?highlight=string.template#string.Template).
Replacing a substring of a string with Python
10,436,454
19
2012-05-03T17:30:00Z
10,436,674
11
2012-05-03T17:45:33Z
[ "python", "string", "substring", "string-interpolation" ]
I'd like to get a few opinions on the best way to replace a substring of a string with some other text. Here's an example: I have a string, a, which could be something like "Hello my name is $name". I also have another string, b, which I want to insert into string a in the place of its substring '$name'. I assume it ...
There are a number of ways to do it, the more commonly used would be through the facilities already provided by strings. That means the use of the `%` operator, or better yet, the newer and recommended `str.format()`. Example: ``` a = "Hello my name is {name}" result = a.format(name=b) ``` Or more simply ``` result...
Replacing a substring of a string with Python
10,436,454
19
2012-05-03T17:30:00Z
10,436,832
55
2012-05-03T17:56:37Z
[ "python", "string", "substring", "string-interpolation" ]
I'd like to get a few opinions on the best way to replace a substring of a string with some other text. Here's an example: I have a string, a, which could be something like "Hello my name is $name". I also have another string, b, which I want to insert into string a in the place of its substring '$name'. I assume it ...
Here are the most common ways to do it: ``` >>> import string >>> t = string.Template("Hello my name is $name") >>> print t.substitute(name='Guido') Hello my name is Guido >>> t = "Hello my name is %(name)s" >>> print t % dict(name='Tim') Hello my name is Tim >>> t = "Hello my name is {name}" >>> print t.format(name...