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
How to join absolute and relative urls?
8,223,939
37
2011-11-22T08:32:59Z
8,223,955
71
2011-11-22T08:35:34Z
[ "python", "url" ]
I have urls: ``` url1 = "http://127.0.0.1/test1/test2/test3/test5.xml" url2 = "../../test4/test6.xml" ``` How to get a absolute url for url2 ?
You should use [urlparse.urljoin](https://docs.python.org/2/library/urlparse.html#urlparse.urljoin) : ``` >>> import urlparse >>> urlparse.urljoin(url1, url2) 'http://127.0.0.1/test1/test4/test6.xml' ``` With Python 3 [urlparse is renamed to urllib.parse](https://docs.python.org/2/library/urlparse.html#index-0): ```...
Exposing a C++ class instance to a python embedded interpreter
8,225,934
13
2011-11-22T11:19:51Z
8,226,377
13
2011-11-22T11:55:52Z
[ "c++", "python", "boost", "swig", "boost-python" ]
I am looking for a simple way to expose a C++ class instance to a python embedded interpreter. * I have a C++ library. This library is wrapped (using swig for the moment) and I am able to use it from the python interpreter * I have a C++ main program which instanciates a Foo class from my library and embeds a python i...
[Boost python](http://www.boost.org/doc/libs/release/libs/python/doc/) Allows you to expose c++ classes to python in a very tightly integrated way - you can even wrap them so that you can derive python classes from your c++ ones, and have virtual methods resolved to the python overrides. The [boost python tutorial](ht...
Python configuration file: Any file format recommendation? INI format still appropriate? Seems quite old school
8,225,954
53
2011-11-22T11:21:08Z
8,225,999
7
2011-11-22T11:24:49Z
[ "python" ]
I need to store configurations (key/value) for a Python application and I am searching for the best way to store these configurations in a file. I run into Python's [ConfigParser](http://docs.python.org/library/configparser.html) and I wondered if the INI file format is really still appropriate nowadays?! Does there e...
This entirely depends on your requirements. If (as you say) all you need is key/value pairs, ini files (or other "plain" config files) will perfectly suit you. No, they are not outdated, as they are still in use. XML/JSON is perfect if you have hierarchical structures and also want to use more sophisticated methods (e...
Python configuration file: Any file format recommendation? INI format still appropriate? Seems quite old school
8,225,954
53
2011-11-22T11:21:08Z
8,226,090
62
2011-11-22T11:31:37Z
[ "python" ]
I need to store configurations (key/value) for a Python application and I am searching for the best way to store these configurations in a file. I run into Python's [ConfigParser](http://docs.python.org/library/configparser.html) and I wondered if the INI file format is really still appropriate nowadays?! Does there e...
Consider using plain Python files as configuration files. An example (`example.conf`): ``` # use normal python comments value1 = 32 value2 = u"A unicode value" value3 = "A plain string value" value4 = ["lists", "are", "handy"] value5 = {"and": "so", "are": "dictionaries"} ``` In your program, load the config file ...
Python configuration file: Any file format recommendation? INI format still appropriate? Seems quite old school
8,225,954
53
2011-11-22T11:21:08Z
8,226,136
28
2011-11-22T11:35:24Z
[ "python" ]
I need to store configurations (key/value) for a Python application and I am searching for the best way to store these configurations in a file. I run into Python's [ConfigParser](http://docs.python.org/library/configparser.html) and I wondered if the INI file format is really still appropriate nowadays?! Does there e...
INI is till totally OK and as other said, the format of your config file really depends from how you are going to use it. Personally I am a fan of [YAML](http://yaml.org/): concise, readable, flexible. Google seems to share my enthusiasm, as they use it too in the Google App Engine. The python parser is [here](http:/...
Python configuration file: Any file format recommendation? INI format still appropriate? Seems quite old school
8,225,954
53
2011-11-22T11:21:08Z
8,226,291
8
2011-11-22T11:50:01Z
[ "python" ]
I need to store configurations (key/value) for a Python application and I am searching for the best way to store these configurations in a file. I run into Python's [ConfigParser](http://docs.python.org/library/configparser.html) and I wondered if the INI file format is really still appropriate nowadays?! Does there e...
[Dictionaries](http://docs.python.org/library/stdtypes.html#dict) are pretty popular as well. Basically a hash table. `{"one": 1, "two": 2}` is an example, kind of looks like json. Then you can call it up like `mydict["one"]`, which would return 1. Then you can use [shelve](http://docs.python.org/library/shelve.html...
python - Size limit of set data type
8,226,006
3
2011-11-22T11:25:16Z
8,226,050
10
2011-11-22T11:28:22Z
[ "python" ]
I have a list with 7,200,000 elements in it. When I try to convert it with set() it cuts out to 4,500,000 elements. What can I do to bypass this problem? I'm using Python 3.2.2 x86 on Windows.
I think your list has duplicate elements which are removed in set. Sets include unique elements only.
Ipython Emacs integration
8,226,493
7
2011-11-22T12:04:14Z
8,227,355
7
2011-11-22T13:10:47Z
[ "python", "emacs", "ipython" ]
Has anyone managed to get Emacs 23, python-mode.el and ipython.el working together recently? my .emacs looks like this: ``` (add-to-list 'load-path "~/.emacs.d/python-mode.el-6.0.3/") (require 'python-mode) (add-to-list 'auto-mode-alist '("\\.py\\'" . python-mode)) (require 'ipython) ``` the error I'm getting on `C-...
ipython.el is known to be out of date. None of the core IPython developers know emacs lisp. Someone is now [working to fix it](https://github.com/ipython/ipython/pull/1015) - if you have time, please test his branch and report whether it works.
Ipython Emacs integration
8,226,493
7
2011-11-22T12:04:14Z
9,222,783
9
2012-02-10T04:41:25Z
[ "python", "emacs", "ipython" ]
Has anyone managed to get Emacs 23, python-mode.el and ipython.el working together recently? my .emacs looks like this: ``` (add-to-list 'load-path "~/.emacs.d/python-mode.el-6.0.3/") (require 'python-mode) (add-to-list 'auto-mode-alist '("\\.py\\'" . python-mode)) (require 'ipython) ``` the error I'm getting on `C-...
Here's another reason someone may be getting this error: iPython 0.12 exits with an error if given a -color arg. What fixed it for me was replacing ``` (setq py-python-command-args '("-colors" "Linux")) ``` in my .emacs with ``` (setq py-python-command-args '("--colors=linux")) ``` That is, make sure that the arg...
sort list of floating-point numbers in groups
8,226,923
6
2011-11-22T12:35:56Z
8,226,951
13
2011-11-22T12:38:17Z
[ "python", "numpy" ]
I have an array of floating-point numbers, which is unordered. I know that the values always fall around a few points, which are not known. For illustration, this list ``` [10.01,5.001,4.89,5.1,9.9,10.1,5.05,4.99] ``` has values clustered around 5 and 10, so I would like [5,10] as answer. I would like to find those ...
Check [python-cluster](http://pypi.python.org/pypi/cluster/1.1.0b1) With this library you could do something like this: ``` from cluster import * data = [10.01,5.001,4.89,5.1,9.9,10.1,5.05,4.99] cl = HierarchicalClustering(data, lambda x,y: abs(x-y)) print [mean(cluster) for cluster in cl.getlevel(1.0)] ``` And you...
Strange "local" folder inside virtualenv folder
8,227,120
18
2011-11-22T12:51:14Z
8,228,132
18
2011-11-22T14:09:03Z
[ "python", "virtualenv" ]
After I create my virtualenv environment (VE), inside it there is a symbolic link named "local". It points to the VE folder, which means that if you open it you end up in the same folder that you started in. I wouldn't care about that, but it makes some autocompletion "wizards" in PyCharm unusable (they show the same ...
According to [the source](https://github.com/pypa/virtualenv/blob/112b6a22452b3ed813943f092f48031d3477d081/virtualenv.py#L1294) the `local` symlink was put in place as a fix for [a bug](https://bugs.launchpad.net/ubuntu/+source/python2.7/+bug/839588) that affected platforms using the ["posix\_local" install scheme](htt...
Alignment in a GridLayout in PyQt4
8,227,735
2
2011-11-22T13:38:21Z
8,228,215
11
2011-11-22T14:14:07Z
[ "python", "pyqt4", "qtgui" ]
I'm trying to create a QGridLayout in PyQt4, and I can't figure out for the life of me how to change the alignment of the contents of the cells. The docs say that any nonzero value for the 5th (6th counting self) argument means that the element being added doesn't fill the grid space, but so far I've not found any valu...
``` import PyQt4.QtCore.Qt ``` Won't work, since that last `Qt` isn't a module (it's most likely just a class providing namespacing). Do the following: ``` from PyQt4 import QtCore ``` Then for, say, right alignment: ``` QtCore.Qt.AlignRight ``` This is what you should pass to the *alignment* argument of `QGridLay...
Is nose an extension of unittest?
8,228,364
5
2011-11-22T14:25:12Z
8,228,865
7
2011-11-22T14:58:54Z
[ "python", "testing", "nose" ]
I'm about to use nose as a method for test discovery on my already implemented unittest classes in my rather large project. I was under the impression that nose is just used primarily for test discovery and test running (in parallel as well). But I see [this question](http://stackoverflow.com/questions/5696884/python-n...
Nose mimics behavior of py.test. That's what they say on their [website](http://code.google.com/p/python-nose/): > nose provides an alternate test discovery and running process for unittest, one that is intended to mimic the behavior of py.test as much as is reasonably possible without resorting to too much magic Nos...
Is nose an extension of unittest?
8,228,364
5
2011-11-22T14:25:12Z
8,228,874
8
2011-11-22T14:59:25Z
[ "python", "testing", "nose" ]
I'm about to use nose as a method for test discovery on my already implemented unittest classes in my rather large project. I was under the impression that nose is just used primarily for test discovery and test running (in parallel as well). But I see [this question](http://stackoverflow.com/questions/5696884/python-n...
The [docs](http://code.google.com/p/python-nose/) for nose say: > nose provides an **alternate** test discovery and running process for > unittest, one that is intended to mimic the behavior of py.test as > much as is reasonably possible without resorting to too much magic. If you [take a peek at the code](http://cod...
embedding python
8,229,597
5
2011-11-22T15:48:06Z
8,229,809
14
2011-11-22T16:01:57Z
[ "python", "c", "python-c-api", "python-embedding" ]
Im trying to call python functions from C code, and i followed a sample from [here](http://docs.python.org/release/2.3.2/ext/pure-embedding.html) I also have the correct include file directries, library directries, and linked the python32.lib (im using python 32) however the error was that python/C APIs such as PyStri...
The example code you used is for ancient Python version, 2.3.2. Python 3.x line introduced a number of incompatibilites not only in the language but in the C API as well. The functions you mention simply no longer exist in Python 3.2. `PyString_` functions were renamed to `PyBytes_`. `PyInt_` functions are gone, `Py...
Python sets are not json serializable
8,230,315
71
2011-11-22T16:38:01Z
8,230,373
70
2011-11-22T16:41:32Z
[ "python", "json", "serialization" ]
I have a python set that contains objects with `__hash__` and `__eq__` methods in order to make certain no duplicates are included in the collection. I need to json encode this result set, but passing even an empty set to the `json.dumps` method raises a TypeError ``` File "/usr/lib/python2.7/json/encoder.py", li...
[JSON](http://www.json.org/) notation has only a handful of native datatypes (objects, arrays, strings, numbers, booleans, and null), so anything serialized in JSON needs to be expressed as one of these types. As shown in the [json module docs](http://docs.python.org/library/json.html#), this conversion can be done au...
Python sets are not json serializable
8,230,315
71
2011-11-22T16:38:01Z
8,230,505
47
2011-11-22T16:49:28Z
[ "python", "json", "serialization" ]
I have a python set that contains objects with `__hash__` and `__eq__` methods in order to make certain no duplicates are included in the collection. I need to json encode this result set, but passing even an empty set to the `json.dumps` method raises a TypeError ``` File "/usr/lib/python2.7/json/encoder.py", li...
You can create a custom encoder that returns a `list` when it encounters a `set`. Here's an example: ``` >>> import json >>> class SetEncoder(json.JSONEncoder): ... def default(self, obj): ... if isinstance(obj, set): ... return list(obj) ... return json.JSONEncoder.default(self, obj) ... >>> ...
Parallel Coordinates plot in Matplotlib
8,230,638
28
2011-11-22T16:58:29Z
8,241,606
7
2011-11-23T11:43:32Z
[ "python", "matplotlib", "parallel-coordinates" ]
Two and three dimensional data can be viewed relatively straight-forwardly using traditional plot types. Even with four dimensional data, we can often find a way to display the data. Dimensions above four, though, become increasingly difficult to display. Fortunately, [parallel coordinates plots](http://en.wikipedia.or...
I'm sure there is a better way of doing it, but here's a quick-and-dirty one (a really dirty one): ``` #!/usr/bin/python import numpy as np import matplotlib.pyplot as plt import matplotlib.ticker as ticker #vectors to plot: 4D for this example y1=[1,2.3,8.0,2.5] y2=[1.5,1.7,2.2,2.9] x=[1,2,3,8] # spines fig,(ax,ax...
Parallel Coordinates plot in Matplotlib
8,230,638
28
2011-11-22T16:58:29Z
16,907,551
27
2013-06-03T23:39:36Z
[ "python", "matplotlib", "parallel-coordinates" ]
Two and three dimensional data can be viewed relatively straight-forwardly using traditional plot types. Even with four dimensional data, we can often find a way to display the data. Dimensions above four, though, become increasingly difficult to display. Fortunately, [parallel coordinates plots](http://en.wikipedia.or...
[pandas](http://pandas.pydata.org/pandas-docs/stable/visualization.html#parallel-coordinates) has a parallel coordinates wrapper: ``` import pandas import matplotlib.pyplot as plt from pandas.tools.plotting import parallel_coordinates data = pandas.read_csv(r'C:\Python27\Lib\site-packages\pandas\tests\data\iris.csv',...
Django Debug Toolbar: understanding the time panel
8,232,434
30
2011-11-22T19:13:47Z
8,233,206
34
2011-11-22T20:15:54Z
[ "python", "django", "django-debug-toolbar" ]
I'm running the Django Debug Toolbar to profile my site and try to figure out why certain views are taking so long. It's been immensely valuable with regards to seeing what queries I'm running and how much they're costing me, but I can't understand how to read the time panel. I've looked around everywhere for some doc...
**User CPU time**: The time your server-side code ran while processing the request **System CPU time**: The time operating system code called by your server-side code ran while processing the request **Total CPU time**: total time to fully respond once request was received (user+system) **Elapsed time**: Time since ...
change unicode string into list?
8,233,412
4
2011-11-22T20:31:30Z
8,233,460
8
2011-11-22T20:34:54Z
[ "python" ]
I get the data as type `<type 'unicode'>` ``` u'{0.128,0.128,0.133,0.137,0.141,0.146,0.15,0.155,0.159,0.164,0.169,0.174,0.179,0.185,0.19,0.196,0.202,0.208,0.214,0.22}' ``` I want to convert this to list like ``` [0.128,0.128,0.133,0.137,0.141,0.146,0.15,0.155,0.159,0.164,0.169,0.174,0.179,0.185,0.19,0.196,0.202,0.20...
Just like that: ``` >>> a = u'{0.128,0.128,0.133,0.137,0.141,0.146,0.15,0.155,0.159,0.164,0.169,0.174,0.179,0.185,0.19,0.196,0.202,0.208,0.214,0.22}' >>> [float(i) for i in a.strip('{}').split(',')] [0.128, 0.128, 0.133, 0.137, 0.141, 0.146, 0.15, 0.155, 0.159, 0.164, 0.169, 0.174, 0.179, 0.185, 0.19, 0.196, 0.202, 0....
Is it possible to have SimpleHTTPServer serve files from two different directories?
8,234,266
4
2011-11-22T21:47:00Z
8,675,236
7
2011-12-30T01:16:19Z
[ "python", "simplehttpserver" ]
If I do `python -m SimpleHTTPServer` it serves the files in the current directory. My directory structure looks like this: ``` /protected/public /protected/private /test ``` I want to start the server in my `/test` directory and I want it to serve files in the `/test` directory. But I want all requests to the server...
I think I have found the answer to this, basically it involves changing the current working directory, starting the server and then returning back to your original working directory. This is how I achieved it, I've commented out two sets of options for you, as the solution for me was just moving to a folder within my ...
Is it possible to have SimpleHTTPServer serve files from two different directories?
8,234,266
4
2011-11-22T21:47:00Z
20,409,103
8
2013-12-05T19:43:13Z
[ "python", "simplehttpserver" ]
If I do `python -m SimpleHTTPServer` it serves the files in the current directory. My directory structure looks like this: ``` /protected/public /protected/private /test ``` I want to start the server in my `/test` directory and I want it to serve files in the `/test` directory. But I want all requests to the server...
I think it is absolutely possible to do that. You can start the server inside `/test` directory and override `translate_path` method of `SimpleHTTPRequestHandler` as follows: ``` import BaseHTTPServer import SimpleHTTPServer server_address = ("", 8888) PUBLIC_RESOURCE_PREFIX = '/public' PUBLIC_DIRECTORY = '/path/to/pr...
Python: Format output string, right alignment
8,234,445
42
2011-11-22T22:03:03Z
8,234,511
80
2011-11-22T22:06:38Z
[ "python", "formatting", "alignment" ]
I am processing a text file containing coordinates x,y,z ``` 1 128 1298039 123388 0 2 ``` .... every line is delimited into 3 items using ``` words = line.split () ``` After processing data I need to write coordinates back in another txt file so as items in each column are aligned right (a...
Try this approach using the newer [`str.format`](http://docs.python.org/library/stdtypes.html#str.format) syntax: ``` line_new = '{:>12} {:>12} {:>12}'.format(word[0], word[1], word[2]) ``` And here's how to do it using the old `%` syntax (useful for older versions of Python that don't support `str.format`): ``` l...
Python: Format output string, right alignment
8,234,445
42
2011-11-22T22:03:03Z
8,234,515
11
2011-11-22T22:07:04Z
[ "python", "formatting", "alignment" ]
I am processing a text file containing coordinates x,y,z ``` 1 128 1298039 123388 0 2 ``` .... every line is delimited into 3 items using ``` words = line.split () ``` After processing data I need to write coordinates back in another txt file so as items in each column are aligned right (a...
It can be achieved by using `rjust`: ``` line_new = word[0].rjust(10) + word[1].rjust(10) + word[2].rjust(10) ```
Python: Format output string, right alignment
8,234,445
42
2011-11-22T22:03:03Z
8,234,565
15
2011-11-22T22:10:46Z
[ "python", "formatting", "alignment" ]
I am processing a text file containing coordinates x,y,z ``` 1 128 1298039 123388 0 2 ``` .... every line is delimited into 3 items using ``` words = line.split () ``` After processing data I need to write coordinates back in another txt file so as items in each column are aligned right (a...
You can align it like that: ``` print('{:>8} {:>8} {:>8}'.format(*words)) ``` where `>` means "**align to right**" and `8` is the **width** for specific value. And here is a proof: ``` >>> for line in [[1, 128, 1298039], [123388, 0, 2]]: print('{:>8} {:>8} {:>8}'.format(*line)) 1 128 1298039 12...
How do I find one number in a string in Python?
8,234,641
9
2011-11-22T22:17:23Z
8,234,662
17
2011-11-22T22:19:17Z
[ "python", "string" ]
I have a file called something like FILE-1.txt or FILE-340.txt. I want to be able to get the number from the file name. I've found that I can use ``` numbers = re.findall(r'\d+', '%s' %(filename)) ``` to get a list containing the number, and use numbers[0] to get the number itself as a string... But if I know it is j...
Use `search` instead of `findall`: ``` number = re.search(r'\d+', filename).group() ``` Alternatively: ``` number = filter(str.isdigit, filename) ```
How to use Python to ensure a string is only numbers and then convert it to an integer
8,234,791
3
2011-11-22T22:29:04Z
8,234,812
8
2011-11-22T22:29:55Z
[ "python" ]
If i have a string like this: `asdf5493` I need the last four digits and i get it by doing this: ``` strVar[-4:] ``` Is it possible to then see if they are all numbers?
``` strVar[-4:].isdigit() ``` tests if all four characters are digits. [Documentation](http://docs.python.org/library/stdtypes.html#str.isdigit) **EDIT:** If your actual goal is to convert this number to an integer, the usual idiom in Python is to just try to do this, and catch the exception in case it fails: ``` s ...
What is the general way to implement operators precedence in Python
8,235,666
2
2011-11-23T00:05:16Z
8,235,846
11
2011-11-23T00:28:33Z
[ "python", "algorithm", "parsing", "programming-languages" ]
Suppose I would like to write a fairly simple programming language, and I want to implement operators such like 2 + 3 \* 2 = 8 What is the general way to implement things like this?
I'm not sure how much detail you're interested in, but it sounds like you're looking to implement a parser. There's typically two steps: The **lexer** reads over the text and converts it to tokens. For example, it might read "2 + 3 \* 2" and convert it to `INTEGER` `PLUS` `INTEGER` `STAR` `INTEGER` The **parser** rea...
Why is semicolon allowed in this python snippet?
8,236,380
64
2011-11-23T01:48:29Z
8,236,402
92
2011-11-23T01:52:18Z
[ "python" ]
Python does not warrant the use of semicolons to end statements. So why is this (below) allowed? ``` import pdb; pdb.set_trace() ```
Python does not *require* semi-colons to terminate statements. Semi colons *can* be used to delimit statements if you wish to put multiple statements on the same line. Now, *why* is this allowed? It's a simple design decision. I don't think Python needs this semi-colon thing, but somebody thought it would be nice to h...
Why is semicolon allowed in this python snippet?
8,236,380
64
2011-11-23T01:48:29Z
8,236,407
38
2011-11-23T01:53:18Z
[ "python" ]
Python does not warrant the use of semicolons to end statements. So why is this (below) allowed? ``` import pdb; pdb.set_trace() ```
<http://docs.python.org/reference/compound_stmts.html> > Compound statements consist of one or more ‘clauses.’ A clause > consists of a header and a ‘suite.’ The clause headers of a particular > compound statement are all at the same indentation level. Each clause > header begins with a uniquely identifying ke...
Why is semicolon allowed in this python snippet?
8,236,380
64
2011-11-23T01:48:29Z
8,236,943
9
2011-11-23T03:24:01Z
[ "python" ]
Python does not warrant the use of semicolons to end statements. So why is this (below) allowed? ``` import pdb; pdb.set_trace() ```
As everyone else has noted, you *can* use semicolons to separate statements. You don't *have* to, and it's not the usual style. As for why this is useful, some people like to put two or more really trivial short statements on a single line (personally I think this turns several trivial easily skimmed lines into one co...
Why is semicolon allowed in this python snippet?
8,236,380
64
2011-11-23T01:48:29Z
8,245,614
24
2011-11-23T16:23:48Z
[ "python" ]
Python does not warrant the use of semicolons to end statements. So why is this (below) allowed? ``` import pdb; pdb.set_trace() ```
Python uses the `;` as a separator, not a terminator. You can also use them at the end of a line, which makes them *look* like a statement terminator, but this is legal only because blank statements are legal in Python -- a line that contains a semicolon at the end is two statements, the second one blank.
Why is semicolon allowed in this python snippet?
8,236,380
64
2011-11-23T01:48:29Z
29,094,034
9
2015-03-17T08:07:30Z
[ "python" ]
Python does not warrant the use of semicolons to end statements. So why is this (below) allowed? ``` import pdb; pdb.set_trace() ```
# Semicolon in the interpreter Having read the answers, I still miss one important aspect of using semicolons, possibly the only one where it really makes a difference... When you're working in an interpreter REPL (the Python interactive shell, IDLE, ipython) the value of the last expression is printed to the screen ...
Specifying default filenames with argparse, but not opening them on --help?
8,236,954
9
2011-11-23T03:26:03Z
8,239,911
8
2011-11-23T09:35:49Z
[ "python", "argparse" ]
Let's say I have a script that does some work on a file. It takes this file's name on the command line, but if it's not provided, it defaults to a known filename (`content.txt`, say). With python's `argparse`, I use the following: ``` parser = argparse.ArgumentParser(description='my illustrative example') parser.add_a...
Looking at the argparse code, I see: * `ArgumentParser.parse_args` calls `parse_known_args` and makes sure that there isn't any pending argument to be parsed. * `ArgumentParser.parse_known_args` sets default values and calls `ArgumentParser._parse_known_args` Hence, the workaround would be to use `ArgumentParser._par...
Specifying default filenames with argparse, but not opening them on --help?
8,236,954
9
2011-11-23T03:26:03Z
8,240,351
10
2011-11-23T10:08:48Z
[ "python", "argparse" ]
Let's say I have a script that does some work on a file. It takes this file's name on the command line, but if it's not provided, it defaults to a known filename (`content.txt`, say). With python's `argparse`, I use the following: ``` parser = argparse.ArgumentParser(description='my illustrative example') parser.add_a...
You could subclass `argparse.FileType`: ``` import argparse import warnings class ForgivingFileType(argparse.FileType): def __call__(self, string): try: super(ForgivingFileType,self).__call__(string) except IOError as err: warnings.warn(err) parser = argparse.ArgumentParse...
Python 3 - non-copying stream interface to bytearray?
8,237,122
6
2011-11-23T03:57:51Z
8,237,575
8
2011-11-23T05:06:01Z
[ "python", "stream", "python-3.x", "bytearray" ]
I read buffer of data from somewhere to `bytearray`. Now, I want to work with this data using stream-like interface (i.e. `read`, `seek` etc.) Can I just wrap my `bytearray` with `io.BytesIO`? ``` mybytearray = bytearray(...) stream = io.BytesIO(mybytearray) ``` My fear here is `BytesIO` copies data of `mybytearray`...
`BytesIO` manages its own memory and will copy a buffer used to initialize it. You could encapsulate your `bytearray` in a file-like class. Or you can go the other way, letting the `BytesIO` object handle memory allocation. Then you can get a view of the buffer that can be modified by index and slice, but you can't re-...
Clear variable in python
8,237,647
76
2011-11-23T05:17:26Z
8,237,659
76
2011-11-23T05:20:18Z
[ "python" ]
Is there a way to clear the value of a variable in python? For example if I was implementing a binary tree: ``` Class Node: self.left = somenode1 self.right = somenode2 ``` If I wanted to remove some node from the tree, I would need to set `self.left` to empty.
What's wrong with `self.left = None`? Am I misinterpreting your question, or are you just not familiar with the `None` keyword?
Clear variable in python
8,237,647
76
2011-11-23T05:17:26Z
8,237,663
148
2011-11-23T05:21:05Z
[ "python" ]
Is there a way to clear the value of a variable in python? For example if I was implementing a binary tree: ``` Class Node: self.left = somenode1 self.right = somenode2 ``` If I wanted to remove some node from the tree, I would need to set `self.left` to empty.
The `del` keyword would do. ``` >>> a=1 >>> a 1 >>> del a >>> a Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'a' is not defined ``` **EDITED:** But in this case I vote for `self.left = None`
Clear variable in python
8,237,647
76
2011-11-23T05:17:26Z
24,223,494
29
2014-06-14T19:27:18Z
[ "python" ]
Is there a way to clear the value of a variable in python? For example if I was implementing a binary tree: ``` Class Node: self.left = somenode1 self.right = somenode2 ``` If I wanted to remove some node from the tree, I would need to set `self.left` to empty.
`var = None` "clears the value", setting the value of the variable to "null" like value of "None", however the pointer to the variable remains. `del var` removes the definition for the variable totally. In case you want to use the variable later, e.g. set a new value for it, i.e. retain the variable, `None` would be ...
Clear variable in python
8,237,647
76
2011-11-23T05:17:26Z
32,417,911
21
2015-09-05T21:35:29Z
[ "python" ]
Is there a way to clear the value of a variable in python? For example if I was implementing a binary tree: ``` Class Node: self.left = somenode1 self.right = somenode2 ``` If I wanted to remove some node from the tree, I would need to set `self.left` to empty.
Actually, that does not delete the variable/property. All it will do is set its value to `None`, therefore the variable will still take up space in memory. If you want to completely wipe all existence of the variable from memory, you can just type: ``` del self.left ```
django.core.exceptions.ImproperlyConfigured: Error loading psycopg module: No module named psycopg
8,237,842
14
2011-11-23T05:49:52Z
22,423,419
12
2014-03-15T11:49:03Z
[ "python", "django", "module", "psycopg2", "django-manage.py" ]
Presently, I'm attempting to configure Django for use on a project, and am encountering a persistent error when I try to run `python manage.py syncdb`. ``` File "/x/x/x/x/x/x/base.py", line 23, in ? raise ImproperlyConfigured("Error loading psycopg module: %s" % e) django.core.exceptions.ImproperlyConfigured: Erro...
I had the error as well; although `psycopg2` was installed on my system using `apt-get`, my virtualenv couldn't find it: ``` >>> import psycopg2 Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named psycopg2 ``` It was fixed by doing a `pip install psycopg2` inside the ...
How to pass variables with spaces through URL in :Django
8,238,268
6
2011-11-23T06:48:09Z
8,238,340
7
2011-11-23T06:57:50Z
[ "python", "django", "django-urls" ]
I am having trouble in passing variables with spaces in them through the urls. Now Suppose I have an object ``` class Kiosks(models.Model): name = models.CharField(max_length = 200, unique = True) owner = models.ForeignKey(User) ``` Now the "name" entered for kiosk is say "Akash Deshpande" and saved. Now whil...
Allow spaces in your regex. ``` urlpatterns = patterns('kiosks.views', url(r'^([\w ]+)/$', 'dashboard'),) ``` And for the love of Pete, use `reverse()`. It will help you catch silly mistakes like this.
How to save traceback / sys.exc_info() values in a variable?
8,238,360
41
2011-11-23T07:00:30Z
8,238,552
56
2011-11-23T07:25:18Z
[ "python", "exception-handling" ]
I want to save name of the error and the traceback details into a variable.. ``` import sys try: try: print x except Exception, ex: raise NameError except Exception, er: print "0", sys.exc_info()[0] print "1", sys.exc_info()[1] print "2", sys.exc_info()[2] ``` Output Getting: ``` ...
This is how I do it: ``` >>> import traceback >>> try: ... int('k') ... except: ... var = traceback.format_exc() ... >>> print var Traceback (most recent call last): File "<stdin>", line 2, in <module> ValueError: invalid literal for int() with base 10: 'k' ``` You should however take a look at the [traceback ...
How to save traceback / sys.exc_info() values in a variable?
8,238,360
41
2011-11-23T07:00:30Z
25,212,045
7
2014-08-08T20:51:04Z
[ "python", "exception-handling" ]
I want to save name of the error and the traceback details into a variable.. ``` import sys try: try: print x except Exception, ex: raise NameError except Exception, er: print "0", sys.exc_info()[0] print "1", sys.exc_info()[1] print "2", sys.exc_info()[2] ``` Output Getting: ``` ...
Use `traceback.extract_stack()` if you want convenient access to module and function names and line numbers. Use `''.join(traceback.format_stack())` if you just want a string that looks like the `traceback.print_stack()` output. Notice that even with `''.join()` you will get a multi-line string, since the elements of...
fast data move from file to some StringIO
8,240,647
7
2011-11-23T10:30:08Z
8,242,372
7
2011-11-23T12:41:54Z
[ "python", "stream" ]
In Python I have a file stream, and I want to copy some part of it into a `StringIO`. I want this to be fastest as possible, with minimum copy. But if I do: ``` data = file.read(SIZE) stream = StringIO(data) ``` I think 2 copies was done, no? One copy into data from file, another copy inside `StringIO` into internal...
In short: you can't avoid 2 copies using StringIO. Some assumptions: * You're using cStringIO, otherwise it would be silly to optimize this much. * It's speed and not memory efficiency you're after. If not, see Jakob Bowyer's solution, or use a variant using `file.read(SOME_BYTE_COUNT)` if your file is binary. * You'...
Executing tasks in parallel in python
8,241,099
9
2011-11-23T11:05:05Z
8,242,359
17
2011-11-23T12:40:48Z
[ "python", "multithreading", "queue", "parallel-processing" ]
I am using python 2.7, I have some code that looks like this: ``` task1() task2() task3() dependent1() task4() task5() task6() dependent2() dependent3() ``` The only dependencies here are as follows: dependent1 needs to wait for tasks1-3, dependent2 needs to wait for tasks 4-6 and dependent3 needs to wait for depen...
The builtin [threading.Thread](http://docs.python.org/library/threading.html#threading.Thread) class offers all you need: [start](http://docs.python.org/library/threading.html#threading.Thread.start) to start a new thread and [join](http://docs.python.org/library/threading.html#threading.Thread.join) to wait for the en...
how to start django shell with ipython in qtconsole mode?
8,242,105
15
2011-11-23T12:21:00Z
8,242,555
7
2011-11-23T12:57:01Z
[ "python", "django", "shell", "ipython" ]
When i start django shell by typing `python manage.py shell` the [ipython](http://ipython.org/) shell is started. Is it possible to make Django start ipython in [qtconsole](http://ipython.org/ipython-doc/dev/interactive/qtconsole.html) mode? (i.e. make it run `ipython qtconsole`) Arek edit: so I'm trying what Andrew ...
The docs [here](https://docs.djangoproject.com/en/dev/intro/tutorial01/#playing-with-the-api) say: > If you'd rather not use manage.py, no problem. Just set the > DJANGO\_SETTINGS\_MODULE environment variable to mysite.settings and run > python from the same directory manage.py is in (or ensure that > directory is on ...
python all possible pairs of 2 list elements, and getting the index of that pair
8,242,832
9
2011-11-23T13:17:57Z
8,242,900
16
2011-11-23T13:22:56Z
[ "python", "list", "tuples", "cartesian-product" ]
let's say I have two lists: ``` a = list(1,2,3) b = list(4,5,6) ``` So I can have 9 pairs of these list members: ``` (1,4) (1,5) (1,6) (2,4) (2,5) (2,6) (3,4) (3,5) (3,6) ``` Now, given two list members like above, can I find out the pair's index? Like (1,4) from above would be the 1st pair.
And to complete the answer and stay in the example: ``` import itertools a = [1, 2, 3] b = [4, 5, 6] c = list(itertools.product(a, b)) idx = c.index((1,4)) ``` But this will be the zero-based list index, so 0 instead of 1.
python all possible pairs of 2 list elements, and getting the index of that pair
8,242,832
9
2011-11-23T13:17:57Z
8,242,995
8
2011-11-23T13:29:37Z
[ "python", "list", "tuples", "cartesian-product" ]
let's say I have two lists: ``` a = list(1,2,3) b = list(4,5,6) ``` So I can have 9 pairs of these list members: ``` (1,4) (1,5) (1,6) (2,4) (2,5) (2,6) (3,4) (3,5) (3,6) ``` Now, given two list members like above, can I find out the pair's index? Like (1,4) from above would be the 1st pair.
One way to do this: 1. Find the first element of the pair your are looking for in the first list: ``` p = (1, 4) i = a.index(p[0]) ``` 2. Find the second element of the pair your are looking for in the second list: ``` j = b.index(p[1]) ``` 3. Compute the index in the product list: ``` k ...
Is there anything like Python Itertools in Perl?
8,242,972
3
2011-11-23T13:28:02Z
8,243,088
7
2011-11-23T13:35:51Z
[ "python", "perl", "itertools" ]
Python has [great module for working with iterators called itertools](http://docs.python.org/library/itertools.html) Is there any analog in Perl? I know about [Object-Iterate](https://github.com/briandfoy/Object-Iterate) but it has only imap and igrep.
[List::Gen](https://metacpan.org/module/List%3a%3aGen) does a lot of that.
Inserting a string into a list without getting split into characters
8,243,188
45
2011-11-23T13:42:45Z
8,243,232
65
2011-11-23T13:45:32Z
[ "python" ]
I'm new to Python and can't find a way to insert a string into a list without it getting split into individual characters: ``` >>> list=['hello','world'] >>> list ['hello', 'world'] >>> list[:0]='foo' >>> list ['f', 'o', 'o', 'hello', 'world'] ``` What should I do to have: ``` ['foo', 'hello', 'world'] ``` Searched...
To add to the end of the list: ``` list.append('foo') ``` To insert at the beginning: ``` list.insert(0, 'foo') ```
Inserting a string into a list without getting split into characters
8,243,188
45
2011-11-23T13:42:45Z
8,243,246
9
2011-11-23T13:46:24Z
[ "python" ]
I'm new to Python and can't find a way to insert a string into a list without it getting split into individual characters: ``` >>> list=['hello','world'] >>> list ['hello', 'world'] >>> list[:0]='foo' >>> list ['f', 'o', 'o', 'hello', 'world'] ``` What should I do to have: ``` ['foo', 'hello', 'world'] ``` Searched...
Sticking to the method you are using to insert it, use ``` list[:0] = ['foo'] ``` <http://docs.python.org/release/2.6.6/library/stdtypes.html#mutable-sequence-types>
Why does the python datetime class have a 'fromtimestamp' method, but not a 'totimestamp' method?
8,243,556
8
2011-11-23T14:08:19Z
8,243,839
13
2011-11-23T14:29:24Z
[ "python", "datetime", "timestamp" ]
Python's `datetime` class has a `fromtimestamp` method to create a `datetime` object from a timestamp, but doesn't provide a `totimestamp` method for the other way round... I'm aware that with something like `time.mktime(x.timetuple())` you can convert the `datetime` object to a timestamp, but this looks unnecessary co...
I do remember a [discussion/bug report](http://bugs.python.org/issue2736) about this thing while I wondered about this some time back. Long story short: plenty of proposals have been made, but for some reason, none have been accepted. The point is I think best summed up in [this reply](http://bugs.python.org/issue2736...
How do you divide each element in a list by an int?
8,244,915
53
2011-11-23T15:37:13Z
8,244,949
85
2011-11-23T15:38:56Z
[ "python" ]
I just want to divide each element in a list by an int. ``` myList = [10,20,30,40,50,60,70,80,90] myInt = 10 newList = myList/myInt ``` This is the error: ``` TypeError: unsupported operand type(s) for /: 'list' and 'int' ``` I understand why I am receiving this error. But I am frustrated that I can't find a soluti...
The idiomatic way would be to use list comprehension: ``` myList = [10,20,30,40,50,60,70,80,90] myInt = 10 newList = [x / myInt for x in myList] ``` or, if you need to maintain the reference to the original list: ``` myList[:] = [x / myInt for x in myList] ```
How do you divide each element in a list by an int?
8,244,915
53
2011-11-23T15:37:13Z
8,244,971
14
2011-11-23T15:40:10Z
[ "python" ]
I just want to divide each element in a list by an int. ``` myList = [10,20,30,40,50,60,70,80,90] myInt = 10 newList = myList/myInt ``` This is the error: ``` TypeError: unsupported operand type(s) for /: 'list' and 'int' ``` I understand why I am receiving this error. But I am frustrated that I can't find a soluti...
``` >>> myList = [10,20,30,40,50,60,70,80,90] >>> myInt = 10 >>> newList = map(lambda x: x/myInt, myList) >>> newList [1, 2, 3, 4, 5, 6, 7, 8, 9] ```
How do you divide each element in a list by an int?
8,244,915
53
2011-11-23T15:37:13Z
8,247,234
29
2011-11-23T18:24:16Z
[ "python" ]
I just want to divide each element in a list by an int. ``` myList = [10,20,30,40,50,60,70,80,90] myInt = 10 newList = myList/myInt ``` This is the error: ``` TypeError: unsupported operand type(s) for /: 'list' and 'int' ``` I understand why I am receiving this error. But I am frustrated that I can't find a soluti...
The way you tried first is actually directly possible with [numpy](http://numpy.org): ``` import numpy myArray = numpy.array([10,20,30,40,50,60,70,80,90]) myInt = 10 newArray = myArray/myInt ``` If you do such operations with long lists and especially in any sort of scientific computing project, I would really advise...
How can I improve the efficiency of this numpy loop
8,245,817
8
2011-11-23T16:37:38Z
8,246,171
7
2011-11-23T17:04:19Z
[ "python", "optimization", "numpy" ]
I've got a numpy array containing labels. I'd like to get calculate a number for each label based on its size and bounding box. How can I write this more efficiently so that it's realistic to use on large arrays (~15000 labels)? ``` A = array([[ 1, 1, 0, 3, 3], [ 1, 1, 0, 0, 0], [ 1, 0, 0, 2, 2],...
I wasn't really able to implement this efficiently using some NumPy vectorised functions, so maybe a clever Python implementation will be faster. ``` def first_row(a, labels): d = {} d_setdefault = d.setdefault len_ = len num_labels = len_(labels) for i, row in enumerate(a): for label in ro...
python add dictionary to existing dictionary
8,245,892
2
2011-11-23T16:43:00Z
8,245,991
9
2011-11-23T16:50:48Z
[ "python" ]
What am I doing wrong here? The append inside the dictionary doesn't seem to be working ``` final = [] topid = { "ida" : "ida", "idb" : "idb", "idc" : "idc", "subid" : {} } for subid in subids: insubid = { "name" : subid.name, "sida" : "sida", "sidb" : "sidb", "s...
I'm not sure this is what you want, but by using `append`, your code is expecting `subid` to be a list. If that's what you are going for, you should be able to change this: ``` topid = { "ida" : "ida", "idb" : "idb", "idc" : "idc", "subid" : {} } ``` to this: ``` topid = { "ida" : "ida", "i...
Does Python's os.system() wait for an end of the process?
8,246,520
14
2011-11-23T17:24:09Z
8,246,551
10
2011-11-23T17:31:34Z
[ "python" ]
The [Python manual](http://docs.python.org/library/os.html#os.system) says nothing about whether `os.system("cmd")` waits or not for a process to end: To quote the manual: > Execute the command (a string) in a subshell. It looks like it does wait (same behaviour as Perl's `system`). Is this correct?
The manual doesn't explicitly say, but it does imply that it waits for the end of the process by saying that the return value is the return value of the program. So to answer your question, yes it does wait.
Does Python's os.system() wait for an end of the process?
8,246,520
14
2011-11-23T17:24:09Z
8,246,562
20
2011-11-23T17:32:07Z
[ "python" ]
The [Python manual](http://docs.python.org/library/os.html#os.system) says nothing about whether `os.system("cmd")` waits or not for a process to end: To quote the manual: > Execute the command (a string) in a subshell. It looks like it does wait (same behaviour as Perl's `system`). Is this correct?
Yes it does. The return value of the call is the exit code of the subprocess.
Configuring so that pip install can work from github
8,247,605
130
2011-11-23T18:56:54Z
8,256,424
182
2011-11-24T11:40:39Z
[ "python", "git", "pip" ]
We'd like to use pip with github to install private packages to our production servers. This question concerns what needs to be in the github repo in order for the install to be successful. Assuming the following command line (which authenticates just fine and tries to install): ``` pip install git+ssh://git@github.c...
You need the whole python package, with a `setup.py` file in it. A package named `foo` would be: ``` foo # the installable package ├── foo │   ├── __init__.py │   └── bar.py └── setup.py ``` And install from github like: ``` $ pip install git+git://github.com/myuser/foo.git@v123 or $...
Configuring so that pip install can work from github
8,247,605
130
2011-11-23T18:56:54Z
8,382,819
79
2011-12-05T08:48:58Z
[ "python", "git", "pip" ]
We'd like to use pip with github to install private packages to our production servers. This question concerns what needs to be in the github repo in order for the install to be successful. Assuming the following command line (which authenticates just fine and tries to install): ``` pip install git+ssh://git@github.c...
I had similar issue when I had to install from github repo, but did not want to install git , etc. The simple way to do it is using zip archive of the package. Add `/zipball/master` to the repo URL: ``` $ pip install https://github.com/hmarr/django-debug-toolbar-mongo/zipball/master Downloading/unpacking https://...
Python - How to cut a string in Python?
8,247,792
5
2011-11-23T19:12:46Z
8,247,835
16
2011-11-23T19:16:36Z
[ "python", "string" ]
Suppose that I have the following string: ``` http://www.domain.com/?s=some&two=20 ``` How can I take off what is after `&` including the `&` and have this string: ``` http://www.domain.com/?s=some ```
You need to split the string: ``` >>> s = 'http://www.domain.com/?s=some&two=20' >>> s.split('&') ['http://www.domain.com/?s=some', 'two=20'] ``` That will return a list as you can see so you can do: ``` >>> s2 = s.split('&')[0] >>> print s2 http://www.domain.com/?s=some ```
Python - How to cut a string in Python?
8,247,792
5
2011-11-23T19:12:46Z
8,247,863
29
2011-11-23T19:18:39Z
[ "python", "string" ]
Suppose that I have the following string: ``` http://www.domain.com/?s=some&two=20 ``` How can I take off what is after `&` including the `&` and have this string: ``` http://www.domain.com/?s=some ```
Well, to answer the immediate question: ``` >>> s = "http://www.domain.com/?s=some&two=20" ``` The `rfind` method returns the index of right-most substring: ``` >>> s.rfind("&") 29 ``` You can take all elements up to a given index with the slicing operator: ``` >>> "foobar"[:4] 'foob' ``` Putting the two together...
How do I specify an arrow-like linestyle in Matplotlib?
8,247,973
9
2011-11-23T19:28:44Z
8,253,729
7
2011-11-24T07:55:21Z
[ "python", "matplotlib" ]
I would like to display a set of xy-data in Matplotlib in such a way as to indicate a particular path. Ideally, the linestyle would be modified to use an arrow-like patch. I have created a mock-up, shown below (using Omnigraphsketcher). It seems like I should be able to override one of the common `linestyle` declaratio...
Here's a starting off point: 1. Walk along your line at fixed steps (`aspace` in my example below) . A. This involves taking steps along the line segments created by two sets of points (`x1`,`y1`) and (`x2`,`y2`). B. If your step is longer than the line segment, shift to the next set of points. 2. At that poin...
How to know/change current directory in Python shell?
8,248,397
84
2011-11-23T20:06:01Z
8,248,430
125
2011-11-23T20:08:54Z
[ "python", "windows", "python-3.x", "python-3.2" ]
I am using Python 3.2 on Windows 7. When I open the Python shell, how can I know what the current directory is and how can I change it to another directory where my modules are?
You can use the `os` module. ``` >>> import os >>> os.getcwd() '/home/user' >>> os.chdir("/tmp/") >>> os.getcwd() '/tmp' ``` But if it's about finding other modules: You can set an environment variable called `PYTHONPATH`, under Linux would be like ``` export PYTHONPATH=/path/to/my/library:$PYTHONPATH ``` Then, the...
How to know/change current directory in Python shell?
8,248,397
84
2011-11-23T20:06:01Z
8,248,433
10
2011-11-23T20:09:09Z
[ "python", "windows", "python-3.x", "python-3.2" ]
I am using Python 3.2 on Windows 7. When I open the Python shell, how can I know what the current directory is and how can I change it to another directory where my modules are?
you want ``` import os os.getcwd() os.chdir('..') ```
How to know/change current directory in Python shell?
8,248,397
84
2011-11-23T20:06:01Z
9,913,449
8
2012-03-28T18:23:04Z
[ "python", "windows", "python-3.x", "python-3.2" ]
I am using Python 3.2 on Windows 7. When I open the Python shell, how can I know what the current directory is and how can I change it to another directory where my modules are?
``` >>> import os >>> os.system('cd c:\mydir') ``` In fact, `os.system()` can execute any command that windows command prompt can execute, not just change dir.
Matplotlib tight_layout() doesn't take into account figure suptitle
8,248,467
41
2011-11-23T20:12:46Z
8,248,506
37
2011-11-23T20:16:56Z
[ "python", "matplotlib" ]
If I add a suptitle to my matplotlib figure it gets overlaid by the subplot's titles. Does anybody know how to easily take care of that? I tried the tight\_layout() function, but it only makes things worse. Example: ``` import numpy as np import matplotlib.pyplot as plt f = np.random.random(100) g = np.random.random...
You could manually adjust the spacing using `plt.subplots_adjust(top=0.85)`: ``` import numpy as np import matplotlib.pyplot as plt f = np.random.random(100) g = np.random.random(100) fig = plt.figure() fig.suptitle('Long Suptitle', fontsize=24) plt.subplot(121) plt.plot(f) plt.title('Very Long Title 1', fontsize=20)...
Matplotlib tight_layout() doesn't take into account figure suptitle
8,248,467
41
2011-11-23T20:12:46Z
19,627,237
26
2013-10-28T04:32:55Z
[ "python", "matplotlib" ]
If I add a suptitle to my matplotlib figure it gets overlaid by the subplot's titles. Does anybody know how to easily take care of that? I tried the tight\_layout() function, but it only makes things worse. Example: ``` import numpy as np import matplotlib.pyplot as plt f = np.random.random(100) g = np.random.random...
One thing you could change in your code very easily is the `fontsize` you are using for the titles. However, I am going to assume that you don't just want to do that! Some alternatives to using `fig.subplots_adjust(top=0.85)`: Usually `tight_layout()` does a pretty good job at positioning everything in good locations...
Matplotlib tight_layout() doesn't take into account figure suptitle
8,248,467
41
2011-11-23T20:12:46Z
28,414,755
8
2015-02-09T16:42:38Z
[ "python", "matplotlib" ]
If I add a suptitle to my matplotlib figure it gets overlaid by the subplot's titles. Does anybody know how to easily take care of that? I tried the tight\_layout() function, but it only makes things worse. Example: ``` import numpy as np import matplotlib.pyplot as plt f = np.random.random(100) g = np.random.random...
An alternative and simple to use solution is to adjust the coordinates of the suptitle text in the figure using the y argument in the call of suptitle (see the [docs](http://matplotlib.org/api/figure_api.html?highlight=suptitle#matplotlib.figure.Figure.suptitle)): ``` import numpy as np import matplotlib.pyplot as plt...
Uploading large files with Python/Django
8,249,042
12
2011-11-23T21:03:36Z
8,250,848
12
2011-11-24T00:13:50Z
[ "python", "django" ]
I am wondering if there are any ramifications in uploading files that are roughly 4GB in size through a web app using Django/Python? I remember in the past streaming uploads using Java was the preferred method but does this still today or is it perfectly safe to do so with Django/Python?
Django will by default, put uploaded file data into memory if it is less than 2.5MB. Anything larger will be written to the server's `/tmp` directory and then copied across when the transfer completes. Many of Django's file upload settings can be customised, details are available in [the documentation](https://docs.dja...
how to get all possible combination of items from 2-dimensional list in python?
8,249,836
5
2011-11-23T22:17:35Z
8,249,850
11
2011-11-23T22:18:48Z
[ "python", "list", "combinatorics" ]
I didn't find a better way to phrase this question in the title. If you can, please edit. I have a list of lists like this: ``` a = [['a','b'],[1,2]] ``` now, I'd like a function that spits out all possible combination like this: ``` [['a',1],['a',2],['b',1],['b',2]] ``` where nor the number of lists in a is known...
You need [`itertools.product()`](http://docs.python.org/library/itertools.html#itertools.product): ``` >>> list(itertools.product(*a)) [('a', 1), ('a', 2), ('b', 1), ('b', 2)] ```
Command not found: django-admin.py
8,250,086
14
2011-11-23T22:42:04Z
20,488,233
17
2013-12-10T07:09:08Z
[ "python", "django", "heroku" ]
I am a complete beginner to Python/Django, but I want to dive right in and start experimenting. Thus I was following this guide on installing Python/Django <http://devcenter.heroku.com/articles/django>. Everything is working fine until the step `django-admin.py startproject hellodjango` Where I get `command not fou...
Actually, if you use Ubuntu, it's just `django-admin` not `django-admin.py`. Resides in `/usr/bin` Probably the same thing on Mac. You're using a Windows tutorial. It may also tell you ``` python manage.py runserver ``` and that is actually ``` python ./manage.py runserver ```
Access memory address in python
8,250,625
14
2011-11-23T23:42:13Z
8,250,902
21
2011-11-24T00:22:44Z
[ "python", "memory", "memory-address" ]
My question is: How can I read the content of a memory address in python? example: ptr = id(7) I want to read the content of memory pointed by ptr. Thanks.
Have a look at [ctypes.string\_at](http://docs.python.org/library/ctypes.html#ctypes.string_at). Here's an example. It dumps the raw data structure of a Python 3 integer. Hopefully you're only doing this as an exercise. No reason to do this with pure Python. ``` from ctypes import string_at from sys import getsizeof f...
Read a zip an write it to an other file python
8,251,387
4
2011-11-24T01:53:34Z
8,251,407
8
2011-11-24T01:57:05Z
[ "python", "zip" ]
I want to read a file and write it back out. Here's my code: ``` file = open( zipname , 'r' ) content = file.read() file.close() alt = open('x.zip', 'w') alt.write(content ) alt.close() ``` This doesn't work, why????? Edit: The rewritten file is corrupt (python 2.7.1 on windows)
Read and write in the binary mode, 'rb' and 'wb': ``` f = open(zipname , 'rb') content = f.read() f.close() alt = open('x.zip', 'wb') alt.write(content ) alt.close() ``` The reason the text mode didn't work on Windows is that the newline translation from '\r\n' to '\r' mangled the binary data in the zip file.
Numpy: For every element in one array, find the index in another array
8,251,541
12
2011-11-24T02:22:04Z
8,251,668
9
2011-11-24T02:45:59Z
[ "python", "arrays", "search", "numpy", "indexing" ]
I have two 1D arrays, x & y, one smaller than the other. I'm trying to find the index of every element of y in x. I've found two naive ways to do this, the first is slow, and the second memory-intensive. # The slow way ``` indices= [] for iy in y: indices += np.where(x==iy)[0][0] ``` # The memory hog ``` xe = ...
How about this? It does assume that every element of y is in x, (and will return results even for elements that aren't!) but it is much faster. ``` import numpy as np # Generate some example data... x = np.arange(1000) np.random.shuffle(x) y = np.arange(100) # Actually preform the operation... xsorted = np.argsort(...
Numpy: For every element in one array, find the index in another array
8,251,541
12
2011-11-24T02:22:04Z
8,251,757
11
2011-11-24T03:02:13Z
[ "python", "arrays", "search", "numpy", "indexing" ]
I have two 1D arrays, x & y, one smaller than the other. I'm trying to find the index of every element of y in x. I've found two naive ways to do this, the first is slow, and the second memory-intensive. # The slow way ``` indices= [] for iy in y: indices += np.where(x==iy)[0][0] ``` # The memory hog ``` xe = ...
As Joe Kington said, [searchsorted()](http://docs.scipy.org/doc/numpy/reference/generated/numpy.searchsorted.html) can search element very quickly. To deal with elements that are not in x, you can check the searched result with original y, and create a masked array: ``` import numpy as np x = np.array([3,5,7,1,9,8,6,6...
Is there a way to perform a mouseover (hover over an element) using Selenium and Python bindings?
8,252,558
16
2011-11-24T05:23:07Z
8,261,754
35
2011-11-24T19:34:33Z
[ "python", "selenium", "selenium-webdriver", "python-bindings" ]
Reading [here](http://groups.google.com/group/selenium-developers/browse_thread/thread/eebb4269d53b4a01) ,there apparently used to be a RenderedWebElement class with a hover method.It,however,was exclusively for Java (Searched the python bindings documentation [here](http://selenium.googlecode.com/svn/trunk/docs/api/py...
To do a hover you need to use the `move_to_element` method. Here is an example ``` from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains firefox = webdriver.Firefox() firefox.get('http://foo.bar') element_to_hover_over = firefox.find_element_by_id("baz") hover = ActionChain...
SQLAlchemy, get object not bound to a Session
8,253,978
25
2011-11-24T08:21:41Z
8,254,472
27
2011-11-24T09:06:12Z
[ "python", "sqlalchemy" ]
For various reasons, I am trying to get an collections of objects out of a database and pass it to another process that is not connected to the database. My code looks like the one below but I keep getting ``` sqlalchemy.exc.UnboundExecutionError: Instance <MyClass at 0x8db7fec> is not bound to a Session; attribute re...
If you want a bunch of objects produced by querying a session to be usable outside the scope of the session, you need to [expunge](http://docs.sqlalchemy.org/en/latest/orm/session_state_management.html#expunging) them for the session. In your first function example, you will need to add a line: ``` session.expunge_al...
Looping for every character in a string in Python decoder ring
8,254,477
6
2011-11-24T09:06:36Z
8,254,662
8
2011-11-24T09:21:26Z
[ "python", "string", "decoder", "caesar-cipher" ]
I'm trying to make a simple decoder ring in Python. Example: ``` a=b, `b=c, c=d, etc. ``` I want the script to take an encoded message and output the decoded message. For instance, I would input `"ifmmp"` and it would output `"hello"`. I've been thinking I need to split all the characters up and loop through them...
How about: ``` s = 'ifmmp' new_s = '' for c in s: n = ord(c) n = n - 1 if n < ord('a'): # 'a' -> 'z' n = ord('z') new_s += chr(n) # print('new_s = %r' % new_s) -> new_s = 'hello' ``` Of course, this is only handling small letters, not capital.
print and format output
8,255,309
2
2011-11-24T10:10:38Z
8,255,406
7
2011-11-24T10:17:10Z
[ "python" ]
I have a simple script: ``` now = datetime.datetime.now() print "%d%d%d%d%d" % ( now.year, now.month, now.day, now.hour, now.minute ) ``` result: ``` 20111124149 ``` How to get result: ``` 201111241409 ``` ?
Method one: use `%02d` instead of `%d`. This pads up to width two with leading zeros. ``` print "%02d%02d%02d%02d%02d" % (now.year, now.month, now.day, now.hour, now.minute) ``` Method two, the correct way: use [`datetime.strftime`](http://docs.python.org/library/datetime.html#datetime.datetime.strftime). ``` print ...
Running webdriver chrome with Selenium
8,255,929
87
2011-11-24T10:57:00Z
8,259,152
84
2011-11-24T15:07:57Z
[ "python", "linux", "google-chrome", "selenium", "web-testing" ]
I ran into a problem while working with Selenium. For my project, I have to use Chrome. However, I can't connect to that browser after launching it with Selenium. For some reason, Selenium can't find Chrome by itself. This is what happens when I try to launch Chrome without including a path: ``` Traceback (most recen...
You need to make sure the standalone ChromeDriver binary (which is different than the Chrome browser binary) is either in your path or available in the webdriver.chrome.driver environment variable. see <http://code.google.com/p/selenium/wiki/ChromeDriver> for full information on how wire things up. Edit: Right, seem...
Running webdriver chrome with Selenium
8,255,929
87
2011-11-24T10:57:00Z
8,946,843
65
2012-01-20T19:30:37Z
[ "python", "linux", "google-chrome", "selenium", "web-testing" ]
I ran into a problem while working with Selenium. For my project, I have to use Chrome. However, I can't connect to that browser after launching it with Selenium. For some reason, Selenium can't find Chrome by itself. This is what happens when I try to launch Chrome without including a path: ``` Traceback (most recen...
**Mac OSX only** An easier way to get going (assuming you already have [homebrew](http://mxcl.github.com/homebrew/) installed, which you should, if not, go do that first and let homebrew make your life better) is to just run the following command: ``` brew install chromedriver ``` That should put the chromedriver in...
Running webdriver chrome with Selenium
8,255,929
87
2011-11-24T10:57:00Z
15,861,575
22
2013-04-07T10:54:56Z
[ "python", "linux", "google-chrome", "selenium", "web-testing" ]
I ran into a problem while working with Selenium. For my project, I have to use Chrome. However, I can't connect to that browser after launching it with Selenium. For some reason, Selenium can't find Chrome by itself. This is what happens when I try to launch Chrome without including a path: ``` Traceback (most recen...
For windows, please have the `chromedriver.exe` placed under `<Install Dir>/Python27/Scripts/`
Running webdriver chrome with Selenium
8,255,929
87
2011-11-24T10:57:00Z
24,364,290
49
2014-06-23T11:04:36Z
[ "python", "linux", "google-chrome", "selenium", "web-testing" ]
I ran into a problem while working with Selenium. For my project, I have to use Chrome. However, I can't connect to that browser after launching it with Selenium. For some reason, Selenium can't find Chrome by itself. This is what happens when I try to launch Chrome without including a path: ``` Traceback (most recen...
**For Linux** 1. Check you have installed latest version of chrome brwoser-> `chromium-browser -version` 2. If not, install latest version of chrome `sudo apt-get install chromium-browser` 3. get appropriate version of chrome driver from [here](http://chromedriver.storage.googleapis.com/index.html) 4. Unzip the chrome...
Running webdriver chrome with Selenium
8,255,929
87
2011-11-24T10:57:00Z
25,988,106
25
2014-09-23T06:16:02Z
[ "python", "linux", "google-chrome", "selenium", "web-testing" ]
I ran into a problem while working with Selenium. For my project, I have to use Chrome. However, I can't connect to that browser after launching it with Selenium. For some reason, Selenium can't find Chrome by itself. This is what happens when I try to launch Chrome without including a path: ``` Traceback (most recen...
For windows Download webdriver from: <http://chromedriver.storage.googleapis.com/2.9/chromedriver_win32.zip> or download the latest chromedriver from [here](https://sites.google.com/a/chromium.org/chromedriver/downloads) Paste the chromedriver.exe file in "C:\Python27\Scripts" Folder. This should work now. ``` f...
Simple validation with SQLAlchemy
8,256,715
2
2011-11-24T12:02:29Z
8,256,921
7
2011-11-24T12:16:59Z
[ "python", "sqlalchemy", "flask-sqlalchemy" ]
I'm new to sqlalchemy, and I'm trying to achieve simple validation of model's fields, as provided by Django ORM (min & max for Integer, email, ...). Can SQLAlchemy do this sort of field validations out of the box ? By the way, I'm using SQLAlchemy with Flask.
See [Simple Validators](http://docs.sqlalchemy.org/en/rel_1_0/orm/mapped_attributes.html#simple-validators) in the documentation. Sample code extract below: ``` class EmailAddress(Base): __tablename__ = 'address' id = Column(Integer, primary_key=True) email = Column(String) @validates('email') de...
python: what's the difference between pythonbrew and virtualenv?
8,256,723
38
2011-11-24T12:03:05Z
8,348,440
50
2011-12-01T21:18:47Z
[ "python", "ruby", "rvm", "virtualenv", "pythonbrew" ]
I am new to python and I am planning to learn django. I had a bit of experience with ruby (not rails) and I am familiar with **[RVM](http://beginrescueend.com/)** however I don't understand the difference between **[pythonbrew](https://github.com/utahta/pythonbrew)** and **[virtualenv](http://pypi.python.org/pypi/virtu...
Pythonbrew is akin to Ruby's *rvm*: It's a shell function that allows you to: * Build one or more complete self-contained versions of Python, each stored locally under your home directory. You can build multiple versions of Python this way. * Switch between the versions of Python easily. The Pythons you build are c...
Wrap text in PIL
8,257,147
8
2011-11-24T12:34:17Z
8,262,001
8
2011-11-24T20:05:25Z
[ "python", "python-imaging-library" ]
I'm using PIL to draw text on an image. How would I wrap a string of text. This is my code: ``` text = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea c...
You will need to first split the text into lines of the right length, and then draw each line individually. The second part is easy, but the first part may be quite tricky to do accurately if varible-width fonts are used. If fixed-width fonts are used, or if accuracy doesn't matter that much, then you can just use the...
Automatic detection of display availability with matplotlib
8,257,385
8
2011-11-24T12:52:31Z
8,258,144
8
2011-11-24T13:51:32Z
[ "python", "matplotlib" ]
I'm generating matplotlib figures in a script which I run alternatively with or without a graphical display. I'd like the script to adjust automatically: with display, it should show the figures interactively, while without a display, it should just save them into a file. From an answer to the question [Generating mat...
You can detect directly if you have a display with the OS module in python. in my case it's > > > os.environ["DISPLAY"] > > > ':0.0'
In Python: check if file modification time is older than a specific datetime
8,258,145
5
2011-11-24T13:51:40Z
8,258,198
13
2011-11-24T13:55:16Z
[ "python", "datetime" ]
I wrote this code in c# to check if a file is out of date: ``` DateTime? lastTimeModified = file.getLastTimeModified(); if (!lastTimeModified.HasValue) { //File does not exist, so it is out of date return true; } if (lastTimeModified.Value < DateTime.Now.AddMinu...
You want to use the [`os.path.getmtime`](http://docs.python.org/library/os.path.html#os.path.getmtime) function (in combination with the [`time.time`](http://docs.python.org/library/time.html#time.time) one). This should give you an idea: ``` >>> import os.path as path >>> path.getmtime('next_commit.txt') 1318340964.0...
How can I append a number to a string in Racket?
8,258,617
2
2011-11-24T14:27:54Z
8,260,779
7
2011-11-24T17:31:20Z
[ "python", "racket", "string-concatenation" ]
Python : `xx = "p" + "y" + str(3)` => `xx == "py3"` How can I get the same result using Racket? ``` (string-append "racket" (number->string 5) " ") ``` Is there another way in Racket, similar to the Python example above, to append a number to a string?
~~Python automatically coerces the number to a string, while Racket will *not* do so.~~ Neither Racket nor Python will coerce the number into a string. That is why you must use `number->string` explicitly in Racket, *and `str()` in Python* (`"p" + str(3)`). You may also find Racket's `format` function to behave similar...
Comparing PHP's __get() with __get__() and __getattr__() in Python
8,258,819
11
2011-11-24T14:44:36Z
11,901,500
7
2012-08-10T12:15:58Z
[ "php", "python" ]
What is the difference between `__get__()` and `__getattr__()` in Python? I come from a PHP background, where there is only `__get()`. When should I use which function? I've been trying to figure this out for a while. I see plenty of questions like [this one](http://stackoverflow.com/questions/3278077/difference-betwe...
First an foremost, PHP does **not** have an equivalent to Python's `__get__()` – not even close! What you are looking for is most definitely `__getattr__()`. > I come from a PHP background, where there is only `__get__` **PHP** has a [magic method](http://php.net/manual/en/language.oop5.magic.php) called [`__get()`](...
Python argparse command line flags without arguments
8,259,001
99
2011-11-24T14:57:15Z
8,259,080
137
2011-11-24T15:01:57Z
[ "python", "command-line-arguments", "argparse" ]
How do I add an optional flag to my command line args? eg. so I can write ``` python myprog.py ``` or ``` python myprog.py -w ``` I tried ``` parser.add_argument('-w') ``` But I just get an error message saying ``` Usage [-w W] error: argument -w: expected one argument ``` which I take it means that it wants a...
As you have it, the argument w is expecting a value after -w on the command line. If you are just looking to flip a switch by setting a variable `True` or `False`, have a look at <http://docs.python.org/dev/library/argparse.html#action> (specifically store\_true and store\_false) ``` parser.add_argument('-w', action='...
Count total search objects count in template using django-haystack
8,261,462
8
2011-11-24T18:54:29Z
8,313,346
27
2011-11-29T15:26:52Z
[ "python", "django", "django-haystack", "xapian" ]
I am using django haystack with xapian as the backend search engine. I am using `FacetedSearchView` and `FacetedSearchForm` for faceting over the search. I have passed `searchqueryset` to the `FacetSearchView` in my `urls.py` file. But the problem is I cannot access that `searchqueryset` in template. All I want to do ...
Haystack uses the standard django pagination: <https://docs.djangoproject.com/en/dev/topics/pagination/> Showing `{{ page.object_list|length }}` of `{{ page.paginator.count }}` Results on Page `{{ page.number }}` of `{{ page.paginator.num_pages }}`
How to fix pylint warning "Abstract class not referenced"?
8,261,526
15
2011-11-24T19:04:16Z
8,261,641
22
2011-11-24T19:21:12Z
[ "python", "warnings", "abstract-class", "pylint" ]
I have a Python class that raises "NotImplementedError" for a couple of methods and the class is inherited by a few other classes which are defined in their own files. When I run Pylint on the file that has the abstract class, it always complains "Abstract class not referenced". I was wondering is it just Pylint being...
If you have in your class a method raising a `NotImplementedError` it is enough to make pylint think this is an abstract class. As pylint check each file isolated from the rest of the project, if no one inherit from this class in the file it will raise this message. If you want to desactivate it you'll have to put th...
urllib2 try and except on 404
8,262,275
8
2011-11-24T20:40:18Z
8,262,330
24
2011-11-24T20:46:40Z
[ "python", "exception", "urllib2", "python-2.x" ]
I'm trying to go through a series of numbered data pages using urlib2. What I want to do is use a try statement, but I have little knowledge of it, Judging by reading up a bit, it seems to be based on specific 'names' that are exceptions, eg IOError etc. I don't know what the error code is I'm looking for, which is par...
You should catch `urllib2.HTTPError` if you want to detect a 404: ``` try: req = urllib2.Request(url, useragent) # create a request object handle = urllib2.urlopen(req) # and open it to return a handle on the url except urllib2.HTTPError, e: print 'We failed with error code - %s.' % e.code if...
Python - fixed exponent in scientific notation?
8,262,302
6
2011-11-24T20:43:28Z
8,262,434
12
2011-11-24T21:01:01Z
[ "python", "scientific-notation", "format-specifiers" ]
Consider the following Python snippet: ``` for ix in [0.02, 0.2, 2, 20, 200, 2000]: iss=str(ix) + "e9" isf=float(iss) print(iss + "\t=> " + ("%04.03e" % isf ) + " (" + str(isf) + ")") ``` It generates the following output: ``` 0.02e9 => 2.000e+07 (20000000.0) 0.2e9 => 2.000e+08 (200000000.0) 2e9 => 2.00...
Format it yourself (see [Format Specification Mini-Language](http://docs.python.org/library/string.html#format-specification-mini-language)): ``` for ix in [.02e9,.2e9,2e9,20e9,200e9,2000e9]: print('{:.3e} => {:0=8.3f}e9'.format(ix,ix/1e9)) ``` ### Output ``` 2.000e+07 => 0000.020e9 2.000e+08 => 0000.200e9 2.000...