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
OSError: [Errno 13] Permission denied when updating setuptools
22,121,569
5
2014-03-01T23:02:43Z
24,375,494
8
2014-06-23T22:18:53Z
[ "python", "homebrew", "setuptools" ]
I'm trying to update setuptools using homebrew but I keep getting an error that says: ``` OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/setuptools-1.1.3-py2.7.egg' ``` How do I allow my computer to make changes to that file so I can update setuptools?
I figured out how to fix it! I looked up the name of that file `setuptools-0.6c11-py2.7.egg` and I found a python [page on it](https://pypi.python.org/pypi/setuptools/0.6c11) that says > NOTE: Regardless of what sort of Python you're using, if you've previously installed older versions of setuptools, please delete all...
How is HDF5 different from a folder with files?
22,125,778
20
2014-03-02T09:11:06Z
28,512,028
26
2015-02-14T03:14:25Z
[ "python", "persistence", "metadata", "hdf5" ]
I'm working on an [open source project](https://github.com/abstractfactory/openmetadata) dealing with adding metadata to folders. The provided (Python) API lets you browse and access metadata like it was just another folder. Because it is just another folder. ``` \folder\.meta\folder\somedata.json ``` Then I came acr...
As someone who developed a scientific project that went from using folders of files to HDF5, I think I can shed some light on the advantages of HDF5. When I began my project, I was operating on small test datasets, and producing small amounts of output, in the range of kilobytes. I began with the easiest data format, ...
numpy.polyfit with adapted parameters
22,126,229
4
2014-03-02T10:07:07Z
22,126,795
7
2014-03-02T11:09:43Z
[ "python", "numpy", "polynomial-math" ]
Regarding to this: [polynomial equation parameters](http://stackoverflow.com/questions/21973740/polynomial-equation-parameters) where I get 3 parameters for a squared function `y = a*x² + b*x + c` now I want only to get the **first** parameter for a squared function which describes my function `y = a*x²`. With other ...
This can be done by [numpy.linalg.lstsq](http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.lstsq.html). To explain how to use it, it is maybe easiest to show how you would do a standard 2nd order polyfit 'by hand'. Assuming you have your measurement vectors `x` and `y`, you first construct a so-called [d...
Are there more data structures available to Python (2.7) than the standard list, set, tuple dict in the standard library?
22,127,088
2
2014-03-02T11:41:42Z
22,127,108
10
2014-03-02T11:43:54Z
[ "python", "python-2.7", "data-structures" ]
I've been going through the coursera courses on algorithms, and it seems to me that Python doesn't have as rich of collection of data structures as the ones presented there. Java's collections seem much more diverse. For instance, if i'd like to have collections specialized in either insertion at the end / in the mid...
Python's standard and external libraries contain many additional data structures: * See the [collections](http://docs.python.org/2/library/collections.html) module for namedtuple, deque, Counters, OrderedDict and defaultdict. * See the [heapq](http://docs.python.org/2/library/heapq.html) module for heaps, which can be...
Opposite of melt in python pandas
22,127,569
19
2014-03-02T12:32:48Z
22,127,685
18
2014-03-02T12:44:16Z
[ "python", "pandas" ]
I cannot figure out how to do "reverse melt" using Pandas in python. This is my starting data ``` import pandas as pd from StringIO import StringIO origin = pd.read_table(StringIO('''label type value x a 1 x b 2 x c 3 y a 4 y b 5 y c 6 z a 7 z b 8 z c 9''')) origin Out[5]: ...
there are a few ways; using [`.pivot`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html#pandas.DataFrame.pivot): ``` >>> origin.pivot(index='label', columns='type')['value'] type a b c label x 1 2 3 y 4 5 6 z 7 8 9 [3 rows x 3 columns] ``` using [`...
Two different color colormaps in the same imshow matplotlib
22,128,166
7
2014-03-02T13:28:01Z
22,129,174
14
2014-03-02T14:56:55Z
[ "python", "matplotlib", "color-mapping", "imshow" ]
Let's suppose the example below ``` import matplotlib.pyplot as plt import numpy as np v1 = -1 + 2*np.random.rand(50,150) fig = plt.figure() ax = fig.add_subplot(111) p = ax.imshow(v1,interpolation='nearest') cb = plt.colorbar(p,shrink=0.5) plt.xlabel('Day') plt.ylabel('Depth') cb.set_label('RWU') plt.show() ``` I w...
First of all, is it possible that you just want to use a diverging colormap, 'neutral' at zero, and diverging to two distinct colours? This is an example: ``` import matplotlib.pyplot as plt import numpy as np v1 = -1+2*np.random.rand(50,150) fig,ax = plt.subplots() p = ax.imshow(v1,interpolation='nearest',cmap=plt.c...
How to find max value in a numpy array column?
22,129,225
11
2014-03-02T15:01:52Z
22,129,268
16
2014-03-02T15:06:20Z
[ "python", "arrays", "numpy" ]
I can find quite a few permutations of this question, but not this (rather simple) one: how do I find the maximum value of a specific column of a numpy array (in the most pythonic way)? ``` a = array([[10, 2], [3, 4], [5, 6]]) ``` What I want is the max value in the first column and second column (these are x,y coord...
Just unpack the list: ``` In [273]: xmax, ymax = a.max(axis=0) In [274]: print xmax, ymax #10 6 ```
How to calculate the sentence similarity using word2vec model of gensim with python
22,129,943
32
2014-03-02T16:04:53Z
22,130,100
32
2014-03-02T16:18:16Z
[ "python", "gensim", "word2vec" ]
According to the [Gensim Word2Vec](http://radimrehurek.com/gensim/models/word2vec.html), I can use the word2vec model in gensim package to calculate the similarity between 2 words. e.g. ``` trained_model.similarity('woman', 'man') 0.73723527 ``` However, the word2vec model fails to predict the sentence similarity. ...
This is actually a pretty challenging problem that you are asking. Computing sentence similarity requires building a grammatical model of the sentence, understanding equivalent structures (e.g. "he walked to the store yesterday" and "yesterday, he walked to the store"), finding similarity not just in the pronouns and v...
How to calculate the sentence similarity using word2vec model of gensim with python
22,129,943
32
2014-03-02T16:04:53Z
23,463,581
10
2014-05-05T01:35:35Z
[ "python", "gensim", "word2vec" ]
According to the [Gensim Word2Vec](http://radimrehurek.com/gensim/models/word2vec.html), I can use the word2vec model in gensim package to calculate the similarity between 2 words. e.g. ``` trained_model.similarity('woman', 'man') 0.73723527 ``` However, the word2vec model fails to predict the sentence similarity. ...
Once you compute the sum of the two sets of word vectors, you should take the cosine between the vectors, not the diff. The cosine can be computed by taking the dot product of the two vectors normalized. Thus, the word count is not a factor.
How to calculate the sentence similarity using word2vec model of gensim with python
22,129,943
32
2014-03-02T16:04:53Z
31,417,164
22
2015-07-14T20:54:53Z
[ "python", "gensim", "word2vec" ]
According to the [Gensim Word2Vec](http://radimrehurek.com/gensim/models/word2vec.html), I can use the word2vec model in gensim package to calculate the similarity between 2 words. e.g. ``` trained_model.similarity('woman', 'man') 0.73723527 ``` However, the word2vec model fails to predict the sentence similarity. ...
Since you're using gensim, you should probably use it's doc2vec implementation. doc2vec is an extension of word2vec to the phrase-, sentence-, and document-level. It's a pretty simple extension, described here <http://cs.stanford.edu/~quocle/paragraph_vector.pdf> Gensim is nice because it's intuitive, fast, and flexi...
Can't use chrome driver for selenium
22,130,109
7
2014-03-02T16:19:00Z
22,130,211
15
2014-03-02T16:28:45Z
[ "python", "google-chrome", "python-3.x", "selenium", "python-3.3" ]
I'm having trouble using the Chrome driver for selenium. I have the chromedriver downloaded and saved to C:\Chrome ``` driver = webdriver.Chrome(executable_path="C:/Chrome/") ``` Using that gives me the following error: ``` Traceback (most recent call last): File "C:\Python33\lib\subprocess.py", line 1105, in _exe...
You should specify the executable file path, not the directory path that contains the executable. ``` driver = webdriver.Chrome(executable_path=r"C:\Chrome\chromedriver.exe") ```
Can't use chrome driver for selenium
22,130,109
7
2014-03-02T16:19:00Z
25,664,873
10
2014-09-04T11:56:59Z
[ "python", "google-chrome", "python-3.x", "selenium", "python-3.3" ]
I'm having trouble using the Chrome driver for selenium. I have the chromedriver downloaded and saved to C:\Chrome ``` driver = webdriver.Chrome(executable_path="C:/Chrome/") ``` Using that gives me the following error: ``` Traceback (most recent call last): File "C:\Python33\lib\subprocess.py", line 1105, in _exe...
**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 <http://chromedriver.storage.googleapis.com/index.html> 4. Un...
Django's CachedStaticFilesStorage not hashing file urls
22,130,697
9
2014-03-02T17:14:44Z
24,193,636
9
2014-06-12T20:47:23Z
[ "python", "css", "django", "versioning" ]
I wanted to enabling versioning to some of my javascript and css files as I was getting caching problems when working on the site. I read about CachedStaticFilesStorage in Django 1.6 and it seemed perfect. I modified my settings.py to the following settings: ``` STATIC_ROOT = 'staticfiles' STATIC_URL = '' # Addition...
Very tricky... If you read the docs carefully, you will learn: > ... use the **`staticfiles`** `static` template tag to refer to your static files in your templates ... So instead of: ``` {% load static %} ``` Use ``` {% load staticfiles %} ```
AttributeError: 'module' object has no attribute '[x]'
22,131,139
3
2014-03-02T17:55:40Z
22,131,656
11
2014-03-02T18:36:21Z
[ "python" ]
I am trying to make a script that moves all the .txt files in your desktop to desktop/org, the code is as follows: ``` import os import shutil userhome = os.path.expanduser('~') src = userhome + '/Desktop/' dst = src+ 'org/' def main(): txtlist = os.listdir(src) for file in txtlist: sortFiles(file) ...
Wow, that’s some bad luck. You can understand what’s going on when you look at the traceback: ``` Traceback (most recent call last): File "C:\Python32\org.py", line 3, in <module> import shutil ``` So, the first line that is being executed is `import shutil`. That’s where everything starts going wrong—w...
Clever way to return nearest "floor" binary number in Python?
22,131,181
3
2014-03-02T17:58:23Z
22,131,305
17
2014-03-02T18:09:40Z
[ "python", "numpy", "binary" ]
Looking for something along the lines of: ``` t = 1 get_floor_bin(t) #1 t = 2 get_floor_bin(t) #2 t = 3 get_floor_bin(t) #2 t = 7 get_floor_bin(t) #4 t = 15 get_floor_bin(t) #8 t = 16 get_floor_bin(t) #16 ``` My current approach involves creating a list of binary numbers, and searching for each individual closes...
Is this what you need? Your explanation isn't terribly easy to understand. ``` for i in 1, 2, 3, 7, 15, 16: print 1 << (i.bit_length() - 1) ``` This gives: ``` 1 2 2 4 8 16 ```
Launch Pycharm from command line (terminal)
22,133,861
4
2014-03-02T21:38:48Z
27,163,648
21
2014-11-27T05:27:02Z
[ "python", "command-line", "environment-variables", "pycharm", "sage" ]
I want to try out PyCharm for sage mathematics development. Normally I run eclipse to do sage development, but now I want to try it with PyCharm. To launch eclipse with sage environment variables, in command line I normally do the following: ``` sage -sh cd /path/to/eclipse ./eclipse ``` The first line loads the sag...
1. Open Application Pycharm 2. Find tools in menu bar 3. Create Command-line Launcher May this what you need.
Django logging to console
22,134,895
13
2014-03-02T23:04:34Z
22,141,937
11
2014-03-03T08:30:54Z
[ "python", "django", "logging" ]
I'm trying to set up a logger that will log to the console (I want this because I'm using Heroku with Papertrails (Heroku's logging addon) and stuff written to the console will show up in Papertrails, making it filterable and all the nice Papertrail features.) In settings I was first trying the following: ``` LOGGING...
The following script: ``` import logging, logging.config import sys LOGGING = { 'version': 1, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'stream': sys.stdout, } }, 'root': { 'handlers': ['console'], 'level': 'INFO' } } logg...
Django logging to console
22,134,895
13
2014-03-02T23:04:34Z
22,144,791
14
2014-03-03T10:52:52Z
[ "python", "django", "logging" ]
I'm trying to set up a logger that will log to the console (I want this because I'm using Heroku with Papertrails (Heroku's logging addon) and stuff written to the console will show up in Papertrails, making it filterable and all the nice Papertrail features.) In settings I was first trying the following: ``` LOGGING...
I finally got it. Here's what was happening. When you define a logger using getLogger, you give a logger a name, in this case ``` logger = logging.getLogger(__name__) ``` and you then have to define how a logger with that name behaves in the LOGGING configuration. In this case, since that file is inside a module, th...
A plethora of Python OSC modules - which one to use?
22,135,511
11
2014-03-03T00:10:20Z
22,152,877
9
2014-03-03T17:10:08Z
[ "python", "python-module", "osc" ]
Open Sound Control (OSC) is a protocol for communication among computers, sound synthesizers, and other multimedia devices that is optimized for modern networking technology. It is particularly common to use OSC with MAX/MSP -- which in fact is what I am doing, using OSC with Python to talk to another subsystem in MAX....
I have used pyOSC with great success on OSX. The code isn't under much development but this is most likely due to it's stability and simplicity. I briefly tried [txosc](https://bitbucket.org/arjan/txosc/wiki/Home) and it may warrant further testing. My usage of pyosc is limited but it works well. eg. ``` import OSC c...
Unable to compile pyglpk on OSX 10.8 / Ubuntu 14.x
22,135,568
7
2014-03-03T00:17:29Z
22,159,942
7
2014-03-03T23:42:14Z
[ "python", "osx", "glpk" ]
I am struggling to compile PyGLPK on OSX 10.8. I have installed glpk and gmp through homebrew. I have verified that the following files are all present in /usr/local/include ``` gmp.h gmpxx.h glpk.h ``` Yet I still get the following error. ``` python setup.py build running build running build_ext building 'glpk' ext...
Not sure this is a general fix, but it solved my particular need for GLPK. I just reverted back to an older version and it worked. First uninstall the newest: ``` brew remove glpk ``` Then install an old one (4.39). ``` cd $(brew --prefix) git checkout a82e823 Library/Formula/glpk.rb brew install glpk ``` Then thi...
Django requirements.txt FIle in root
22,135,597
3
2014-03-03T00:21:53Z
22,135,671
7
2014-03-03T00:30:53Z
[ "python", "django" ]
I have set-up a requirements folder as such: ``` requirements/ local.txt development.txt/ production.txt/ ``` I am wondering what I put in my base requirements.txt file to redirect to the appropriate file? I don't want to have to use the `-r requirements/local.txt`. I want a solution based off my virtual enviro...
generally there is a some sort of `common.txt` requirments file which would hold the shared packages, like `django` and you could extend that in your `development.txt` with a line that says ``` -r requirements/common.txt pygraphviz django-nose ``` etc.. The above imitates a sort of inheritance, and is a common and e...
Pygame - Collision detection with two CIRCLES
22,135,712
2
2014-03-03T00:35:49Z
22,135,814
9
2014-03-03T00:45:47Z
[ "python", "pygame", "collision", "circle" ]
I'm making a collision detection program where my cursor is a circle with a radius of 20 and should change a value to TRUE when it hits another circle. For testing purposes, I have a stationary circle in the centre of my screen with a radius of 50. I'm able to test whether the cursor circle has hit the stationary circl...
Just check whether the distance between the two centers is less than the sum of the radiuses. Imagine the two circles just barely touching each other (see graphic below), then draw a line between the two centers. The length of that line will be sum of the two radiuses (or radii if you're Latin). So if the two circles i...
Convert number strings with commas in pandas DataFrame to float
22,137,723
11
2014-03-03T02:37:01Z
22,137,890
19
2014-03-03T02:54:41Z
[ "python", "pandas" ]
I have a DataFrame that contains numbers as strings with commas for the thousands marker. I need to convert them to floats. ``` a = [['1,200', '4,200'], ['7,000', '-0.03'], [ '5', '0']] df=pandas.DataFrame(a) ``` I am guessing I need to use locale.atof. Indeed ``` df[0].apply(locale.atof) ``` works as expected. I g...
You need to [set the locale](http://stackoverflow.com/a/2308488/1240268) first: ``` In [11]: locale.setlocale(locale.LC_NUMERIC, '') Out[11]: 'en_GB.UTF-8' In [12]: df.applymap(atof) Out[12]: 0 1 0 1200 4200.00 1 7000 -0.03 2 5 0.00 ``` If you're [reading in from csv](http://pandas.pydata....
Drawing rectangle or line using mouse events in open cv using python
22,140,880
4
2014-03-03T07:22:19Z
22,141,475
13
2014-03-03T08:00:04Z
[ "python", "opencv", "python-3.x" ]
I am trying to draw a straight line between two coordinates which would be obtained by clicking on the image or by mouse events. I am able to draw individual circles on clicking the mouse, but cannot figure out how to draw line between those points. When I am using this code, I can only print the start and end coordina...
You can refer below C++ code which I used to crop image ``` #include <iostream> #include "opencv2/opencv.hpp" #include <stdio.h> using namespace std; using namespace cv; Mat src,img,ROI; Rect cropRect(0,0,0,0); Point P1(0,0); Point P2(0,0); const char* winName="Crop Image"; bool clicked=false; int i=0; char imgN...
Open file for read/write, create if needed
22,142,243
6
2014-03-03T08:50:47Z
22,142,335
7
2014-03-03T08:56:26Z
[ "python", "file-io", "python-3.x", "io", "posix" ]
What is the most elegant way to open a file such that * the file gets created if it does not exist, * the file won't be truncated if it does exist and * it is possible to write any part of the file (after seeking), not just the end? As far as I can tell, [the `open` builtin](http://docs.python.org/3/library/functions...
You need to use [`os.open()`](http://docs.python.org/3/library/os.html#os.open) to open it at a lower level in the OS than `open()` allows. In particular, passing `os.RDWR | os.O_CREAT` as `flags` should do what you want. See the `open(2)` man page for details. You can then pass the returned FD to [`os.fdopen()`](http:...
making django server accessible in LAN
22,144,189
13
2014-03-03T10:25:31Z
22,144,305
26
2014-03-03T10:30:07Z
[ "python", "django" ]
I have installed django server and it can be accessible as below ``` http://localhost:8000/get-sms/ http://127.0.0.1:8000/get-sms/ ``` suppose My ip is x.x.x.x . From another PC under same network when i do `my-ip:8000/get-sms/` it is not working. i can easily ping my ip with that computer. Moreover on my port 81...
[Running the Django Development Server](https://docs.djangoproject.com/en/1.6/ref/django-admin/#runserver-port-or-address-port) This is what you're looking for. To help you further, here is what you should do : `python manage.py runserver 0.0.0.0:8000` By the way, this may be a duplicate of [that](http://stackover...
Test coverage tool for Behave test framework
22,144,504
5
2014-03-03T10:39:00Z
23,836,778
7
2014-05-23T19:07:34Z
[ "python", "automated-tests", "coverage.py", "python-behave" ]
We are using Behave BDD tool for automating API's. Is there any tool which give code coverage using our behave cases? We tried using coverage module, it didn't work with Behave.
You can run any module with coverage to see the code usage. In your case should be close to `coverage run --source='.' -m behave` Tracking code coverage for Aceptace/Integration/Behaviour test will give a high coverage number easily but can lead to the idea that the code are properly tested. Those are for see things ...
How to fix Meta.fields cannot be a string. Did you mean to type: ('name')
22,147,222
3
2014-03-03T12:47:11Z
22,147,442
11
2014-03-03T12:57:37Z
[ "python", "django" ]
Currently I have a script that allows a user to add new Hotel using a Form Here is the script. I get the following Error Exception AddHotelForm.Meta.fields cannot be a string. Did you mean to type: ('name',)? Request Method: GET Request URL: 8000/hotel/new Django Version: 1.6.2 Exception Type: TypeError Exception Val...
So the problem seems to be exactly what is stated in the error message. Your problem is that this: ``` ("name") ``` is not the same as this: ``` ("name",) ``` Try it: ``` >>> type(("name")) <type 'str'> >>> type(("name",)) <type 'tuple'> ``` So to fix it change your form definition: ``` class AddHotelForm(forms...
Iterators in Python 3
22,147,757
2
2014-03-03T13:13:10Z
22,147,847
8
2014-03-03T13:17:40Z
[ "python", "python-3.x", "dictionary", "iterable", "memory-efficient" ]
In Python 3 a lot of functions (now classes) that returned lists now return iterables, the most popular example being `range`. In this case range was made an iterable in Python 3 to improve performance, and memory efficiency (since you don't have to build a list anymore). Other "new" iterables are `map`, `enumerate`, ...
Several reasons: 1. The dictionary operations now return [dictionary view objects](http://docs.python.org/3/library/stdtypes.html#dictionary-view-objects); these act as sets as well, giving you a far richer object to work with in your code. In Python 2 you'd have to use the `dict.view*()` methods to do the same. 2. Th...
What does axis in pandas mean?
22,149,584
39
2014-03-03T14:41:04Z
22,149,930
68
2014-03-03T14:55:35Z
[ "python", "pandas" ]
Here is my code to generate a dataframe: ``` import pandas as pd dff = pd.DataFrame(np.random.randn(1,2),columns=list('AB')) ``` then I got the dataframe: ``` +------------+---------+--------+ | | A | B | +------------+---------+--------- | 0 | 0.626386| 1.52325| +------------+-------...
It specifies the axis **along which** the means are computed. By default `axis=0`. This is consistent with the `numpy.mean` usage when `axis` is specified *explicitly* (in `numpy.mean`, axis==None by default, which computes the mean value over the flattened array) , in which `axis=0` along the *rows* (namely, *index* i...
Http Redirection code 3XX in python requests
22,150,023
10
2014-03-03T14:59:37Z
22,150,088
20
2014-03-03T15:01:50Z
[ "python", "redirect", "python-requests", "http-status-codes" ]
I am trying to capture http status code 3XX/302 for a redirection url. But I cannot get it because it gives 200 status code. Here is the code: ``` import requests r = requests.get('http://goo.gl/NZek5') print r.status_code ``` I suppose this should issue either 301 or 302 because it redirects to another page. I had ...
`requests` handles redirects *for you*, see [redirection and history](http://docs.python-requests.org/en/latest/user/quickstart/#redirection-and-history). Set `allow_redirects=False` if you don't want `requests` to handle redirections, or you can inspect the redirection responses contained in the `r.history` list. De...
How can I break a for loop in jinja2?
22,150,273
11
2014-03-03T15:10:53Z
22,150,349
17
2014-03-03T15:13:44Z
[ "python", "jinja2" ]
How can I break out of a for loop in jinja2? my code is like this: ``` <a href="#"> {% for page in pages if page.tags['foo'] == bar %} {{page.title}} {% break %} {% endfor %} </a> ``` I have more than one page that has this condition and I want to end the loop, once the condition has been met.
You can't use `break`, you'd filter instead. From the Jinja2 [documentation on `{% for %}`](http://jinja.pocoo.org/docs/templates/#for): > Unlike in Python it’s not possible to break or continue in a loop. You can however filter the sequence during iteration which allows you to skip items. The following example skip...
Why doesn't join() automatically convert its arguments to strings? When would you ever not want them to be strings?
22,152,668
4
2014-03-03T16:59:38Z
22,152,693
8
2014-03-03T17:00:57Z
[ "python", "string-concatenation" ]
We have a list: ``` myList = [1, "two"] ``` And want to print it out, normally I would use something like: ``` "{0} and {1}".format(*myList) ``` But you could also do: ``` " and ".join(myList) ``` But unfortunately: ``` >>> " and ".join(myList) Traceback (most recent call last): File "<stdin>", line 1, in <mod...
From the [Zen of Python](http://www.python.org/dev/peps/pep-0020/): > Explicit is better than implicit. and > Errors should never pass silently. Converting to strings implicitly can easily hide bugs, and I'd really want to know if I suddenly have different types somewhere that were meant to be strings. If you want...
Flask blueprint static directory does not work?
22,152,840
14
2014-03-03T17:08:26Z
22,152,975
9
2014-03-03T17:14:44Z
[ "python", "flask" ]
[According to the Flask readme](http://flask.pocoo.org/docs/blueprints/#static-files), blueprint static files are accessible at `blueprintname/static`. But for some reason, it doesn't work. My blueprint is like this: * `app/frontend/views.py` : ``` frontend = Blueprint('frontend', __name__, template_folder='temp...
I include an argument to the static\_url\_path parameter to ensure that the Blueprint's static path doesn't conflict with the static path of the main app. e.g: ``` admin = Blueprint('admin', __name__, static_folder='static', static_url_path='/static/admin') ```
Flask blueprint static directory does not work?
22,152,840
14
2014-03-03T17:08:26Z
22,153,002
13
2014-03-03T17:15:53Z
[ "python", "flask" ]
[According to the Flask readme](http://flask.pocoo.org/docs/blueprints/#static-files), blueprint static files are accessible at `blueprintname/static`. But for some reason, it doesn't work. My blueprint is like this: * `app/frontend/views.py` : ``` frontend = Blueprint('frontend', __name__, template_folder='temp...
You probably registered your Blueprint to sit at the root of your site: ``` app.register_blueprint(core, url_prefix='') ``` but the `static` view in the Blueprint is no different from all your other Blueprint views; it uses that `url_prefix` value to make the URL unique. The *core* `static` view is *also* active, so...
How to remove whitespace from end of string in Python?
22,153,065
5
2014-03-03T17:18:58Z
22,153,092
11
2014-03-03T17:20:17Z
[ "python", "whitespace", "strip" ]
I want to remove the whitespace at the end of 'Joe' ``` name = 'Joe' print(name, ', you won!') >>>Joe , you won! ``` I tried the rstrip method, but it didn't work ``` name='Joe' name=name.rstrip() print(name, ', you won!') >>>Joe , you won! ``` My only solution was to concatenate the string ``` name='Joe' name=nam...
The [`print()` function](http://docs.python.org/3/library/functions.html#print) **adds** whitespace between the arguments, there is nothing to strip there. Use `sep=''` to stop the function from doing that: ``` print(name, ', you won!', sep='') ``` or you can use [string formatting](http://docs.python.org/3/library/...
Error using cv2.equalizeHist
22,153,271
5
2014-03-03T17:27:47Z
22,154,058
10
2014-03-03T18:08:01Z
[ "python", "image", "opencv", "image-processing", "histogram" ]
I am trying to equalize the histogram of a gray level image using the following code: ``` import cv2 im = cv2.imread("myimage.png") eq = cv2.equalizeHist(im) ``` The following exception is raised: ``` error: (-215) CV_ARE_SIZES_EQ(src, dst) && CV_ARE_TYPES_EQ(src, dst) && CV_MAT_TYPE(src->type) == CV_8UC1 in functio...
cv2.equalizeHist only works on grayscale ( 1 channel ) images. either: ``` im = cv2.imread("myimage.png", 0) # load as grayscale ``` or: ``` im = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) # or convert ```
Why doesn't python execute anything after 'unittest.main()' gets executed?
22,153,719
6
2014-03-03T17:50:13Z
22,153,802
9
2014-03-03T17:54:09Z
[ "python", "unit-testing", "testing", "python-unittest" ]
So let's say I have the following: ``` import unittest class MyTests(unittest.TestCase): def test001(self): print 'This is test001' def test002(self): print 'This is test002' if __name__ == '__main__': unittest.main() print 'Done' ``` And the output is: ``` >> This is test001 >> This is test002 >...
Pass `exit=False` to the `unittest.main()` call ([documentation](http://docs.python.org/2/library/unittest.html#unittest.main)): ``` unittest.main(exit=False) ``` Here's what I'm getting on the console: ``` $ python test.py This is test001 .This is test002 . ----------------------------------------------------------...
Why does invoking a module with -m option set sys.path[0] to empty string?
22,154,428
6
2014-03-03T18:28:32Z
22,155,151
7
2014-03-03T19:08:19Z
[ "python", "python-3.x" ]
I have a python script `foo.py` in my current directory `C:\test`. Here is the code. ``` import sys print('sys.path:', sys.path) print('sys.argv:', sys.argv) ``` When I execute it as a script, I see this output. ``` C:\test>python foo.py sys.path: ['C:\\test', 'C:\\Windows\\system32\\python34.zip', 'C:\\Python34\\D...
Look at what `man python` says about `-m`: > `-m module-name` > > > Searches `sys.path` for the named module and runs the corresponding .py file as a script. If you think about it, it makes no sense to add the directory containing the .py file to be run into `sys.path`, as it already has to be there to be found in th...
Whats the best way to round an odd number to an even one?
22,154,885
6
2014-03-03T18:54:09Z
22,154,913
19
2014-03-03T18:56:01Z
[ "python", "math", "integer", "rounding", "legacy" ]
I was in the middle of modernising some legacy code, when I stumbled into the following line: `rounded_val = (len(src_string) / 2) * 2` What it was doing it was taking advantage of [Python's weird integer division](http://stackoverflow.com/questions/22075837/2-3-returns-0-in-python-why), to round the length value of ...
Use `//` floor division instead if you don't like relying on the Python 2 `/` behaviour for integer operands: ``` rounded_val = (len(src_string) // 2) * 2 ```
Whats the best way to round an odd number to an even one?
22,154,885
6
2014-03-03T18:54:09Z
22,154,943
10
2014-03-03T18:57:29Z
[ "python", "math", "integer", "rounding", "legacy" ]
I was in the middle of modernising some legacy code, when I stumbled into the following line: `rounded_val = (len(src_string) / 2) * 2` What it was doing it was taking advantage of [Python's weird integer division](http://stackoverflow.com/questions/22075837/2-3-returns-0-in-python-why), to round the length value of ...
Maybe ``` rounded_val = len(src_string) & ~1 ``` This simply clears the 1s bit, which is exactly what you need. Only works for `int`s, but len should always be integer.
Pandas MultiIndex versus Panel
22,156,258
14
2014-03-03T20:04:29Z
25,162,895
8
2014-08-06T14:22:36Z
[ "python", "pandas" ]
Using Pandas, what are the reasons to use a Panel versus a MultiIndex DataFrame? I have personally found significant difference between the two in the ease of accessing different dimensions/levels, but that may just be my being more familiar with the interface for one versus the other. I assume there are more substant...
In my practice, the strongest, easiest-to-see difference is that a Panel needs to be homogeneous in every dimension. If you look at a Panel as a stack of Dataframes, you cannot create it by stacking Dataframes of different sizes or with different indexes/columns. You can indeed handle more non-homogeneous type of data ...
django-rest-framework: How Do I Serialize a Field That Already Contains JSON?
22,156,403
2
2014-03-03T20:12:35Z
22,294,986
8
2014-03-10T08:09:41Z
[ "python", "json", "django", "serialization", "django-rest-framework" ]
I am pretty new to the django-rest-framework, so could use some help. I have an object with a TextField that is a string containing JSON. I'm using django-rest-framework to serialize the whole object as JSON. However, this one string that is already JSON gets serialized as an encoded string containing the JSON rather...
I solved this another way: 1: use a JSON-Field for the JSON content (`django-jsonfield` or `django-json-field` should be fine). These then will to loads/dumps as needed 2: in my serializer, use the transform-method to prevent the data added as string to the response ``` class MyModelSerializer(serializers.ModelSeria...
Most efficient way to take sequential substrings python
22,156,839
3
2014-03-03T20:34:58Z
22,156,870
7
2014-03-03T20:36:36Z
[ "python" ]
Let's say I have `abcdefgh`. I want all the sequential substrings of length `k`. So for this string if `k = 4`, I would want `abcd` `bcde` `cdef` `defg` `efgh`. I would just loop through with the indices, but is there a more "pythonic" way?
How about: ``` In [13]: s = "abcdefgh" In [14]: [s[i:i+4] for i in xrange(len(s)-3)] Out[14]: ['abcd', 'bcde', 'cdef', 'defg', 'efgh'] ``` Still a loop, but wrapped in a list comprehension. Or, if you want to get fancy: ``` In [18]: map(''.join, zip(*(s[i:] for i in range(4)))) Out[18]: ['abcd', 'bcde', 'cdef', 'd...
Is there a way to sort a list in python until the first sorted k elements are found?
22,158,650
5
2014-03-03T22:15:16Z
22,158,771
9
2014-03-03T22:22:51Z
[ "python", "algorithm", "sorting", "quicksort", "mergesort" ]
I have a normal boring list of non sorted numbers. From that list I need to take the first k elements after sorting. The thing is that if the list is considerably long and k is considerably small sorting the entire list seems like a waste. I came up with an algorithmic solution for this, but requires me to write my own...
You can use the [`heapq`](http://docs.python.org/2/library/heapq.html) module, in particular its [`nlargest`](http://docs.python.org/2/library/heapq.html#heapq.nlargest) or [`nsmallest`](http://docs.python.org/2/library/heapq.html#heapq.nsmallest) functions. Alternatively just build the heap and call [`heappop()`](htt...
Tkinter set focus on Entry widget
22,161,794
2
2014-03-04T02:40:22Z
22,171,574
7
2014-03-04T12:09:39Z
[ "python", "widget", "tkinter", "entry", "setfocus" ]
Here is my code: ``` import tkinter as tk userData = tk.Tk() nbdays = tk.IntVar() mainframe = tk.Frame(userData, relief= 'raised', borderwidth=1) tk.Label(mainframe, text = 'Number of days', font = 10).place(x=2, y = 30) tk.Entry(mainframe, width= 8, textvariable = nbdays).place(x= 200, y= 30) ``` [....] How do I se...
Use the `focus_set` method which is common to all widgets: ``` entry = tk.Entry(...) entry.place(...) entry.focus_set() ```
gcc error when I'm trying to install readline-6.2
22,166,277
7
2014-03-04T08:11:12Z
23,134,706
31
2014-04-17T13:37:59Z
[ "python", "gcc", "centos" ]
Could anyone kindly help me out what's wrong with the gcc when I am trying to install readline module for my newly installed python2.7 in the CentOS server? ``` gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -DHAVE_RL_CALLBACK -DHAVE_RL_CATCH_SIGNAL -DHAVE_RL_COMPL...
readline is bundled with the Python module and it attempts to build it for you, but you'll see this error display if your system was unable to complete the build. In my case, `patch` was missing from the system. `yum install patch` solved it for me.
Weird pdfs from Generalised Extreme Value (GEV) Maximum Likelihood fitted data
22,167,975
4
2014-03-04T09:35:12Z
22,514,175
7
2014-03-19T17:52:50Z
[ "python", "statistics", "scipy" ]
I am doing some data analysis involving fitting datasets to a Generalised Extreme Value (GEV) distribution, but I'm getting some weird results. Here's what I'm doing: ``` from scipy.stats import genextreme as gev import numpy data = [1.47, 0.02, 0.3, 0.01, 0.01, 0.02, 0.02, 0.12, 0.38, 0.02, 0.15, 0.01, 0.3, 0.24, 0.0...
First, I think you may want to keep you location parameter fixed at `0`. Second, you got zeros in your data, the resulting fit may have `+inf` `pdf` at `x=0` e.g. for the GEV fit or for the Weibull fit. Therefore, the fit is actually correct, but when you plot the `pdf` (including `x=0`), the resulting plot is distort...
how to calculate percentage in python
22,169,081
5
2014-03-04T10:19:22Z
22,170,977
8
2014-03-04T11:42:50Z
[ "python", "python-2.7", "percentage" ]
this is my program ``` print" Welcome to NLC Boys Hr. Sec. School " a=input("\nEnter the Tamil marks :") b=input("\nEnter the English marks :") c=input("\nEnter the Maths marks :") d=input("\nEnter the Science marks :") e=input("\nEnter the Social science marks :") tota=a+b+c+d+e print"Total is: ", tota per=float(tota...
I guess you're learning how to Python. The other answers are right. But I am going to answer your main question: "how to calculate percentage in python" Although it works the way you did it, it doesn´t look very pythonic. Also, what happens if you need to add a new subject? You'll have to add another variable, use an...
Read Excel File in Python
22,169,325
13
2014-03-04T10:29:11Z
22,170,333
12
2014-03-04T11:10:10Z
[ "python", "excel" ]
I've an Excel File ``` Arm_id DSPName DSPCode HubCode PinCode PPTL 1 JaVAS 01 AGR 282001 1,2 2 JaVAS 01 AGR 282002 3,4 3 JaVAS 01 AGR 28200...
This is one approach: ``` from xlrd import open_workbook class Arm(object): def __init__(self, id, dsp_name, dsp_code, hub_code, pin_code, pptl): self.id = id self.dsp_name = dsp_name self.dsp_code = dsp_code self.hub_code = hub_code self.pin_code = pin_code self.pp...
What does enumerate mean?
22,171,558
66
2014-03-04T12:08:57Z
22,171,593
132
2014-03-04T12:10:15Z
[ "python", "enumerate" ]
I am using tkinter in Python and came across the following code: ``` for row_number, row in enumerate(cursor): ``` I was wondering whether anyone could explain what enumerate means in this context?
The [`enumerate()` function](http://docs.python.org/2/library/functions.html#enumerate) adds a counter to an iterable. So for each element in `cursor`, a tuple is produced with `(counter, element)`; the `for` loop binds that to `row_number` and `row`, respectively. Demo: ``` >>> elements = ('foo', 'bar', 'baz') >>> ...
What does enumerate mean?
22,171,558
66
2014-03-04T12:08:57Z
22,171,642
21
2014-03-04T12:12:05Z
[ "python", "enumerate" ]
I am using tkinter in Python and came across the following code: ``` for row_number, row in enumerate(cursor): ``` I was wondering whether anyone could explain what enumerate means in this context?
It's a builtin generator function, see <http://docs.python.org/2/library/functions.html#enumerate> . In short, it yields the elements of an iterator, as well as an index number: ``` for item in enumerate(["a", "b", "c"]): print item ``` prints ``` (0, "a") (1, "b") (2, "c") ``` It's helpful if you want to loop...
pytest: parameterized test with cartesian product of arguments
22,171,681
6
2014-03-04T12:13:53Z
22,390,931
8
2014-03-13T21:07:07Z
[ "python", "unit-testing", "py.test" ]
Just wondering, is there any (more) elegant way of parameterizing with the cartesian product? This is what I figured out so far: ``` numbers = [1,2,3,4,5] vowels = ['a','e','i','o','u'] consonants = ['x','y','z'] cartesian = [elem for elem in itertools.product(*[numbers,vowels,consonants])] @pytest.fixture(pa...
I can think of two ways to do this. One uses parametrized fixtures, and one parametrizes the test function. It's up to you which one you find more elegant. Here is the test function parametrized: ``` import itertools import pytest numbers = [1,2,3,4,5] vowels = ['a','e','i','o','u'] consonants = ['x','y','z'] @pyt...
pytest: parameterized test with cartesian product of arguments
22,171,681
6
2014-03-04T12:13:53Z
32,019,130
14
2015-08-14T21:47:21Z
[ "python", "unit-testing", "py.test" ]
Just wondering, is there any (more) elegant way of parameterizing with the cartesian product? This is what I figured out so far: ``` numbers = [1,2,3,4,5] vowels = ['a','e','i','o','u'] consonants = ['x','y','z'] cartesian = [elem for elem in itertools.product(*[numbers,vowels,consonants])] @pytest.fixture(pa...
You can apply multiple `parametrize` arguments, in which case they will generate a product of all parameters: ``` import pytest numbers = [1,2,3,4,5] vowels = ['a','e','i','o','u'] consonants = ['x','y','z'] @pytest.mark.parametrize('number', numbers) @pytest.mark.parametrize('vowel', vowels) @pytest.mark.parametri...
matplotlib: make plus sign thicker
22,172,565
21
2014-03-04T12:55:40Z
22,172,981
46
2014-03-04T13:14:50Z
[ "python", "matplotlib", "markers" ]
In Matplotlib, I would like to draw a **thick plus sign** (or a cross), but the one provided in the [marker set](http://www.loria.fr/~rougier/teaching/matplotlib/#markers) is too **thin**. Even as I increase its size, it doesn't get any thicker. For [example](http://statsmodels.sourceforge.net/devel/generated/statsmo...
You can use `markeredgewidth` (or `mew`). You'll want to combine it with `markersize`, otherwise you get thick but tiny markers. For example: ``` plt.plot([2,4,6,1,3,5], '+', mew=10, ms=20) ``` ![enter image description here](http://i.stack.imgur.com/DTnfV.png)
How to serve cloudstorage files using app engine SDK
22,174,903
5
2014-03-04T14:37:24Z
22,355,873
7
2014-03-12T15:15:51Z
[ "python", "google-app-engine", "sdk", "google-cloud-storage", "serving" ]
In app engine I can serve cloudstorage files like a pdf using the default bucket of my application: ``` http://storage.googleapis.com/<appid>.appspot.com/<file_name> ``` But how can I serve local cloudstorage files in the SDK, without making use of a blob\_key? I write to the default bucket like this: ``` gcs_file_...
**UPDATE I found this feature to serve cloudstorage files using the SDK:** [This feature has not been documented yet.](https://gist.github.com/voscausa/9541133) ``` http://localhost:8080/_ah/gcs/app_default_bucket/filename ``` This meands we do not need the img serving url to serve NON images as shown below !!! To ...
Python max() takes no keyword arguments
22,175,134
4
2014-03-04T14:47:18Z
22,175,320
7
2014-03-04T14:55:38Z
[ "python", "python-2.4" ]
I have a script that I wrote on a machine running Python 2.7.3 that utilizes the max function with a key along with glob to find the youngest file of a specific type in a directory. I tried to move this onto another machine only to discover that it's running Python 2.4.3 and the script doesn't work as a result. The pr...
I'm not certain what tools Python 2.4 has access to, but I'm pretty sure you still have list comprehensions, so you could tuple your list together with the key you want to use, compare, and then unpack. This works because tuples compare element-wise, so if you put the "key" at the front of your tuples, it'll act as the...
No lighting in VTK
22,175,821
3
2014-03-04T15:16:17Z
22,183,359
8
2014-03-04T21:23:40Z
[ "python", "vtk" ]
I'd like to just display the polygons in their specified colour with no shading, is this possible? I've tried setting each of ambient, specular, diffuse etc. to 1 and the others to 0 with no luck.
To disable shading you really have to set lightning off. To do so specify `actor.GetProperty().LightingOff()` on the respective vtkActor. See e.g. <http://www.vtk.org/doc/nightly/html/classvtkProperty.html> Based on the [vtk Pyramid](http://www.vtk.org/Wiki/VTK/Examples/Python/GeometricObjects/Display/Pyramid) the ef...
Generally speaking, how are (Python) projects structured?
22,177,976
10
2014-03-04T16:49:34Z
22,183,108
9
2014-03-04T21:10:23Z
[ "python", "qt", "pyqt", "structure" ]
I'm a bit lost when it comes to structuring my project(s). I try to structure things in ways that make sense, but always end up restructuring the whole thing at least twice per day. Granted, my projects aren't very big, but I would love to not have to restructure everything and just settle on something for once. I'll ...
Let's deal with your last question first, because it's the most important as far as structuring python projects is concerned. Once you've sorted out how to get the imports working correctly within your project, the rest becomes much easier to deal with. The key thing to understand is that the directory of the currentl...
Is it possible to store the alembic connect string outside of alembic.ini?
22,178,339
9
2014-03-04T17:06:22Z
27,256,675
13
2014-12-02T18:45:20Z
[ "python", "sqlalchemy", "alembic" ]
I'm using Alembic with SQL Alchemy. With SQL Alchemy, I tend to follow a pattern where I don't store the connect string with the versioned code. Instead I have file `secret.py` that contains any confidential information.. I throw this filename in my .gitignore so it doesn't endup on github. This pattern works fine, bu...
I had the very same problem yesterday and found a following solution to work. I do the following in `env.py`: ``` # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config # this will overwrite the ini-file sqlalchemy.url path # with the path given...
Mixing file.readline() and file.next()
22,179,974
12
2014-03-04T18:26:25Z
22,180,106
17
2014-03-04T18:32:53Z
[ "python" ]
I noticed some strange behavior today playing around with `next()` and `readline()`. It seems that both functions produce the same results (which is what I expect). However, when I mix them, I get a `ValueError`. Here's what I did: ``` >>> f = open("text.txt", 'r') >>> f.readline() 'line 0\n' >>> f.readline() 'line 1\...
According to [Python's doc](http://docs.python.org/2/library/stdtypes.html#file.next) (emphasis is mine) > A file object is its own iterator, for example iter(f) returns f (unless f is closed). When a file is used as an iterator, **typically in a for loop** (for example, for line in f: print line.strip()), **the next(...
Pandas Dataframe display on a webpage
22,180,993
17
2014-03-04T19:19:54Z
22,181,298
21
2014-03-04T19:37:04Z
[ "python", "pandas", "flask" ]
Ok, I am using Flask but this probably applies to a lot of similar products. I construct a pandas Dataframe, e.g. ``` @app.route('/analysis/<filename>') def analysis(filename): x = pd.DataFrame(np.random.randn(20, 5)) return render_template("analysis.html", name=filename, data=x) ``` The template analysis.ht...
The following should work: ``` @app.route('/analysis/<filename>') def analysis(filename): x = pd.DataFrame(np.random.randn(20, 5)) return render_template("analysis.html", name=filename, data=x.to_html()) # ^^^^^^^^^ ``` Check [the documentation](...
Pandas Dataframe display on a webpage
22,180,993
17
2014-03-04T19:19:54Z
22,233,851
11
2014-03-06T19:15:57Z
[ "python", "pandas", "flask" ]
Ok, I am using Flask but this probably applies to a lot of similar products. I construct a pandas Dataframe, e.g. ``` @app.route('/analysis/<filename>') def analysis(filename): x = pd.DataFrame(np.random.randn(20, 5)) return render_template("analysis.html", name=filename, data=x) ``` The template analysis.ht...
Ok, I have managed to get some very nice results by now combining the hints I got here. In the actual Python viewer I use ``` @app.route('/analysis/<filename>') def analysis(filename): x = pd.DataFrame(np.random.randn(20, 5)) return render_template("analysis.html", name=filename, data=x) ``` e.g. I send the c...
Javascript - No 'Access-Control-Allow-Origin' header is present on the requested resource
22,181,384
8
2014-03-04T19:41:15Z
22,182,389
13
2014-03-04T20:32:22Z
[ "javascript", "python", "ajax", "flask", "cors" ]
I need to send data throught XmlHttpRequest from javascript to python server. Because I'm using localhost I need to use CORS. I'm using Flask framework and his module flask\_cors. As javascript I have this: ``` var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xm...
I got Javascript working with Flask by using this [decorator](https://blog.skyred.fi/articles/better-crossdomain-snippet-for-flask.html), and adding "OPTIONS" to my list of acceptable methods. The decorator should be used beneath your route decorator, like this: ``` @app.route('/login', methods=['POST', 'OPTIONS']) @c...
Javascript - No 'Access-Control-Allow-Origin' header is present on the requested resource
22,181,384
8
2014-03-04T19:41:15Z
32,749,344
7
2015-09-23T20:58:00Z
[ "javascript", "python", "ajax", "flask", "cors" ]
I need to send data throught XmlHttpRequest from javascript to python server. Because I'm using localhost I need to use CORS. I'm using Flask framework and his module flask\_cors. As javascript I have this: ``` var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xm...
I have used the **flask-cors** extension. Install using `pip install flask-cors` Then it's simply ``` from flask.ext.cors import CORS app = Flask(__name__) CORS(app) ``` This will allow all domains
Using utf-8 characters in a Jinja2 template
22,181,944
18
2014-03-04T20:10:17Z
22,182,709
17
2014-03-04T20:47:48Z
[ "python", "python-2.7", "utf-8", "character-encoding", "jinja2" ]
I'm trying to use utf-8 characters when rendering a template with Jinja2. Here is how my template looks like: ``` <!DOCTYPE HTML> <html manifest="" lang="en-US"> <head> <meta charset="UTF-8"> <title>{{title}}</title> ... ``` The title variable is set something like this: ``` index_variables = {'title':''} in...
TL;DR: * [Pass Unicode](http://jinja.pocoo.org/docs/api/#unicode) to `template.render()` * Encode the rendered unicode result to a bytestring before writing it to a file This had me puzzled for a while. Because you do ``` index_file.write( template.render(index_variables) ) ``` in one statement, that's basicall...
How do I configure vim to set softtabs conditionally?
22,184,723
8
2014-03-04T22:41:27Z
22,184,932
8
2014-03-04T22:54:46Z
[ "python", "ruby", "vim" ]
I am now a Python/Ruby polyglot and have a need to switch out values in my .vimrc depending on the filetype I'm using. I need `tabstop=2`, `softtabstop=2` for Ruby and `tabstop=4`, `softtabstop=4` for Python. My Google-fu has failed as to how to do this. Any ideas on how to detect file extension?
Make sure you have this in your `~/.vimrc`: ``` filetype plugin on ``` Then create these two files in `~/.vim/ftplugin`: In `~/.vim/ftplugin/python.vim`: ``` setlocal tabstop=4 softtabstop=4 shiftwidth=4 expandtab ``` In `~/.vim/ftplugin/ruby.vim`: ``` setlocal tabstop=2 softtabstop=2 shiftwidth=2 expandtab ``` ...
Python's __loader__, what is it?
22,185,888
5
2014-03-05T00:07:59Z
22,187,290
7
2014-03-05T02:27:53Z
[ "python", "loader", "python-import" ]
I've seen the term `__loader__` floating around some Python files and I can't find any documentation on it aside from a few brief descriptions about it's purpose, but they still don't provide enough information for me to get a good understanding of it. All I know is that it has something to do with importing modules, o...
> What is `__loader__`? `__loader__` is an attribute that is set on an imported module by its loader. Accessing it should return the loader object itself. In Python versions before 3.3, `__loader__` was not set by the built-in import machinery. Instead, this attribute was only available on modules that were imported ...
How to delete all instances of a character in a string in python?
22,187,233
20
2014-03-05T02:22:40Z
22,187,309
37
2014-03-05T02:29:35Z
[ "python", "string", "python-2.7", "replace" ]
How do I delete all the instances of a character in this string? Here is my code: ``` def findreplace(char, string): place = string.index(char) string[place] = '' return string ``` However, if I run this, this is what happens: ``` >>> findreplace('i', 'it is icy') Traceback (most recent call last): Fil...
Strings are immutable in Python, which means once a string is created, you cannot alter the contents of the strings. If at all, you need to change it, a new instance of the string will be created with the alterations. Having that in mind, we have so many ways to solve this 1. Using [`str.replace`](http://docs.python....
Python circular importing?
22,187,279
26
2014-03-05T02:26:05Z
22,187,343
26
2014-03-05T02:34:32Z
[ "python", "import", "circular-dependency" ]
So i'm getting this error ``` Traceback (most recent call last): File "/Users/alex/dev/runswift/utils/sim2014/simulator.py", line 3, in <module> from world import World File "/Users/alex/dev/runswift/utils/sim2014/world.py", line 2, in <module> from entities.field import Field File "/Users/alex/dev/runsw...
When you import a module (or a member of it) for the first time, the code inside the module is executed sequentially like any other code; e.g., it is not treated any differently that the body of a function. An `import` is just a command like any other (assignment, a function call, `def`, `class`). Assuming your imports...
Python circular importing?
22,187,279
26
2014-03-05T02:26:05Z
22,210,807
43
2014-03-05T22:30:30Z
[ "python", "import", "circular-dependency" ]
So i'm getting this error ``` Traceback (most recent call last): File "/Users/alex/dev/runswift/utils/sim2014/simulator.py", line 3, in <module> from world import World File "/Users/alex/dev/runswift/utils/sim2014/world.py", line 2, in <module> from entities.field import Field File "/Users/alex/dev/runsw...
I think the currently accepted answer by jpmc26 comes down too heavily on circular imports. They can work just fine, if you set them up correctly. The easiest way to do so is to use `import my_module` syntax, rather than `from my_module import some_object`. The former will almost always work, even if `my_module` inclu...
difference between find and index
22,190,064
8
2014-03-05T06:17:05Z
22,190,078
11
2014-03-05T06:18:08Z
[ "python", "string", "python-2.7" ]
I am new to python and cannot quite understand the difference between find and index. ``` >>> line 'hi, this is ABC oh my god!!' >>> line.find("o") 16 >>> line.index("o") 16 ``` They always return the same result. Thanks!!
[`str.find`](http://docs.python.org/2/library/stdtypes.html#str.find) returns `-1` when it does not find the substring. ``` >>> line = 'hi, this is ABC oh my god!!' >>> line.find('?') -1 ``` While [`str.index`](http://docs.python.org/2/library/stdtypes.html#str.index) raises `ValueError`: ``` >>> line.index('?') Tra...
How could I use requests in asyncio?
22,190,403
37
2014-03-05T06:36:52Z
22,414,756
64
2014-03-14T20:06:16Z
[ "python", "python-requests", "python-3.4" ]
I want to do parallel http request tasks in `asyncio`, but I find that `python-requests` would block the event loop of `asyncio`. I've found [aiohttp](https://github.com/KeepSafe/aiohttp) but it couldn't provide the service of http request using a http proxy. So I want to know if there's a way to do asynchronous http ...
To use requests (or any other blocking libraries) with asyncio, you can use [BaseEventLoop.run\_in\_executor](http://docs.python.org/3.4/library/asyncio-eventloop.html#asyncio.BaseEventLoop.run_in_executor) to run a function in another thread and yield from it to get the result. For example: ``` import asyncio import ...
How could I use requests in asyncio?
22,190,403
37
2014-03-05T06:36:52Z
23,784,727
16
2014-05-21T13:30:47Z
[ "python", "python-requests", "python-3.4" ]
I want to do parallel http request tasks in `asyncio`, but I find that `python-requests` would block the event loop of `asyncio`. I've found [aiohttp](https://github.com/KeepSafe/aiohttp) but it couldn't provide the service of http request using a http proxy. So I want to know if there's a way to do asynchronous http ...
[aiohttp](http://aiohttp.readthedocs.org/) can be used with HTTP proxy already: ``` import asyncio import aiohttp @asyncio.coroutine def do_request(): proxy_url = 'http://localhost:8118' # your proxy address connector = aiohttp.ProxyConnector(proxy_url) response = yield from aiohttp.request( 'GE...
How could I use requests in asyncio?
22,190,403
37
2014-03-05T06:36:52Z
29,213,962
8
2015-03-23T15:21:14Z
[ "python", "python-requests", "python-3.4" ]
I want to do parallel http request tasks in `asyncio`, but I find that `python-requests` would block the event loop of `asyncio`. I've found [aiohttp](https://github.com/KeepSafe/aiohttp) but it couldn't provide the service of http request using a http proxy. So I want to know if there's a way to do asynchronous http ...
There is now an asyncio port of requests. <http://github.com/rdbhost/yieldfromRequests>
I get an error in python3 when importing mechanize
22,190,503
15
2014-03-05T06:42:45Z
24,001,585
12
2014-06-02T19:11:34Z
[ "python", "python-3.x", "mechanize" ]
I get an error in python3 when importing mechanize. I've just installed mechanize into my virtualenv where python3 is installed. ``` $ which python3 /Users/myname/.virtualenvs/python3/bin/python3 $ pip freeze mechanize==0.2.5 ``` But, when I try to import mechanize in my python code, I get this error. ``` import m...
Alas, mechanize doesn't support Python 3. <http://wwwsearch.sourceforge.net/mechanize/faq.html> > Python 2.4, 2.5, 2.6, or 2.7. Python 3 is not yet supported. You might like to comment on the issue at <https://github.com/jjlee/mechanize/issues/96> --- Update: I wrote my own automating library MechanicalSoup. It's P...
submit request (post) internally in python-eve
22,191,816
3
2014-03-05T07:58:16Z
22,206,090
7
2014-03-05T18:25:37Z
[ "python", "eve" ]
I have a resource in eve e.g. ABC, I want to manipulate another resource e.g. BCD when some condition meet while I am posting a new item to ABC, I know I can hook the event for post/pre\_POST\_ABC but is there a 'internal' way to do post on BCD without going through via the HTTP again?
In your callback function you could either: A) use the data driver to store data directly to the database Something like this: ``` def update_ABC(request, payload): accounts = app.data.driver.db['abc_collection'] account = accounts.insert(docs) app = Eve() app.on_post_POST_ABC += update_ABC app.run() ``...
Duplicate email using both python-social-auth and email registration in Django
22,198,724
5
2014-03-05T13:09:40Z
22,203,272
7
2014-03-05T16:20:20Z
[ "python", "django", "django-authentication", "python-social-auth" ]
I'm using both python-social-auth and email registration in my project. For the user model I use a subclass of AbstractBaseUser: ``` class User(AbstractBaseUser): USERNAME_FIELD = 'email' AUTH_USER_MODEL = 'userprofile.User' ``` But when a user that is registered with his email ([email protected]) and password trie...
Problem solved. The issue was about the order in pipeline that has to be the following: ``` DEFAULT_AUTH_PIPELINE = ( 'social.pipeline.social_auth.social_details', 'social.pipeline.social_auth.social_uid', 'social.pipeline.social_auth.auth_allowed', 'social.pipeline.social_auth.social_user', 'socia...
Use print inside lambda
22,198,754
2
2014-03-05T13:10:50Z
22,198,768
7
2014-03-05T13:11:30Z
[ "python", "python-2.7" ]
I am trying to use print inside lambda. Something like that: ``` lambda x: print x ``` I understand, that in Python 2.7 print is not a function. So, basically, my question is: Is there a pretty way to use print as function in Python 2.7?
You can import `print_function` from the `__future__` and use it as a function like this ``` from __future__ import print_function map(print, [1, 2, 3]) # 1 # 2 # 3 ```
accessing python dict with function values
22,199,417
3
2014-03-05T13:38:30Z
22,199,451
7
2014-03-05T13:40:00Z
[ "python", "function", "dictionary" ]
I am trying to make a menu of options in python where if the user selects a number a different function is executed: ``` def options(x): return { 1: f1(), 2: f2() }[x] def f1(): print "hi" def f2(): print "bye" ``` However, well I call ``` options(1) ``` I get: ``` hi bye ``` and...
You are invoking the functions instead of assiging them against the keys ``` def f1(): print "hi" def f2(): print "bye" functions = {1: f1, 2: f2} # dict of functions (Note: no parenthesis) def options(x): return functions[x]() # Get the function against the index and invoke it options(1) # hi options(...
Identifying the data type of an input
22,199,741
4
2014-03-05T13:52:37Z
22,199,927
7
2014-03-05T14:01:12Z
[ "python", "python-3.x", "types", "user-input", "python-3.2" ]
Hi I am trying to print the data type of a user input and produce a table like following: > ABCDEFGH = String, > 1.09 = float, 0 = int, true = bool , etc. I'm using python 3.2.3 and I know I could use type() to get the type of the data but in python all user inputs are taken as strings and I don't know how to determi...
``` from ast import literal_eval def get_type(input_data): try: return type(literal_eval(input_data)) except (ValueError, SyntaxError): # A string, so return str return str print(get_type("1")) # <class 'int'> print(get_type("1.2354")) # <class 'float'> print(get_type("True"))...
Patch over a function imported inside another function
22,201,583
4
2014-03-05T15:09:34Z
22,201,798
8
2014-03-05T15:19:22Z
[ "python", "unit-testing", "testing", "mocking", "python-unittest" ]
In order to avoid a circular import, I've been forced to define a function that looks like: ``` # do_something.py def do_it(): from .helpers import do_it_helper # do stuff ``` Now I'd like to be able to test this function, with `do_it_helper` patched over. If the import were a top level import, ``` class Te...
You should mock out `helpers.do_it_helper`: ``` class Test_do_it(unittest.TestCase): def test_do_it(self): with patch('helpers.do_it_helper') as helper_mock: helper_mock.return_value = 12 # test things ``` Here's an example using mock on `os.getcwd()`: ``` import unittest from moc...
How to mix bash with python
22,204,241
5
2014-03-05T16:59:19Z
22,204,316
8
2014-03-05T17:03:02Z
[ "python", "bash" ]
I enjoy using unix commands very much, but I came to the point, where I would find embedded python parts useful. This is my code: ``` #!/bin/bash - echo "hello!"; exec python <<END_OF_PYTHON #!/usr/bin/env python import sys print ("xyzzy") sys.exit(0) END_OF_PYTHON echo "goodbye!"; ``` However, only "hello" gets...
Don't use `exec`. That replaces the shell process with the program you're running, so the rest of the script doesn't execute. ``` #!/bin/bash - echo "hello!"; python <<END_OF_PYTHON #!/usr/bin/env python import sys print ("xyzzy") sys.exit(0) END_OF_PYTHON echo "goodbye!"; ```
How to mix bash with python
22,204,241
5
2014-03-05T16:59:19Z
22,204,560
7
2014-03-05T17:14:13Z
[ "python", "bash" ]
I enjoy using unix commands very much, but I came to the point, where I would find embedded python parts useful. This is my code: ``` #!/bin/bash - echo "hello!"; exec python <<END_OF_PYTHON #!/usr/bin/env python import sys print ("xyzzy") sys.exit(0) END_OF_PYTHON echo "goodbye!"; ``` However, only "hello" gets...
On the `exec python ...` line, you're `exec()`ing the Python interpreter on your `PATH`, so the `python` image will replace the `bash` image, and there is absolutely no hope of the `echo "goodbye!"` ever being executed. If that's what you want, that's fine, but otherwise, just omit the exec. The shebang (“#!”) lin...
Efficient way to create term density matrix from pandas DataFrame
22,205,845
5
2014-03-05T18:13:57Z
22,206,409
10
2014-03-05T18:40:21Z
[ "python", "pandas", "nltk" ]
I am trying to create a term density matrix from a pandas dataframe, so I can rate terms appearing in the dataframe. I also want to be able to keep the 'spatial' aspect of my data (see comment at the end of post for an example of what I mean). I am new to pandas and NLTK, so I expect my problem to be soluble with some...
You can use scikit-learn's [CountVectorizer](http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html): ``` In [14]: from sklearn.feature_extraction.text import CountVectorizer In [15]: countvec = CountVectorizer() In [16]: countvec.fit_transform(df.title) Out[16]: <4x8 ...
file read and for loop in python
22,207,125
3
2014-03-05T19:18:32Z
22,207,346
7
2014-03-05T19:29:32Z
[ "python", "list", "for-loop" ]
I have this file: ``` -0 1 16 9 -00 1 3 4 0 7 9 -000 ... ``` and I want to sort them and store them to a file. I read the file store them inside a list , sort the list and then save the list to a file. Problem is that It starts from the second -x . ``` for line in file: temp_buffer = line.split() f...
You can use `itertools.groupby` to "partition" the data into groups between lines starting with `-` instead. Where it starts with `-` write the line out, otherwise, write the sorted lines, eg: ``` from itertools import groupby with open('input') as fin, open('output', 'w') as fout: for k, g in groupby(fin, lambda L...
Example to understand scipy basin hopping optimization function
22,207,372
7
2014-03-05T19:30:56Z
22,208,797
21
2014-03-05T20:44:03Z
[ "python", "scipy", "mathematical-optimization" ]
I came across the [basin hopping algorithm](http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.basinhopping.html#scipy.optimize.basinhopping) in scipy and created a simple problem to understand how to use it but it doesnt seem to be working correctly for that problem. May be I'm doing something complete...
The function you are testing makes use of an approach called Metropolis-Hastings, which can be modified into a procedure called simulated annealing that can optimze functions in a stochastic way. The way this works is as follows. First you pick a point, like your point `x0`. From that point, you generate a random pert...
Python - how to find files and skip directories in os.listdir
22,207,936
17
2014-03-05T19:59:34Z
22,207,977
17
2014-03-05T20:01:33Z
[ "python", "file-manager" ]
I use `os.listdir` and it works fine, but I get sub-directories in the list also, which is not what I want: I need only files. What function do I need to use for that? I looked also at `os.walk` and it seems to be what I want, but I'm not sure of how it works.
You need to filter out directories; `os.listdir()` lists all *names* in a given path. You can use [`os.path.isdir()`](http://docs.python.org/2/library/os.path.html#os.path.isdir) for this: ``` basepath = '/path/to/directory' for fname in os.listdir(basepath): path = os.path.join(basepath, fname) if os.path.isd...
Python - how to find files and skip directories in os.listdir
22,207,936
17
2014-03-05T19:59:34Z
22,208,063
9
2014-03-05T20:06:00Z
[ "python", "file-manager" ]
I use `os.listdir` and it works fine, but I get sub-directories in the list also, which is not what I want: I need only files. What function do I need to use for that? I looked also at `os.walk` and it seems to be what I want, but I'm not sure of how it works.
Here is a nice little one-liner in the form of a list comprehension: ``` [f for f in os.listdir(your_directory) if os.path.isfile(os.path.join(your_directory, f))] ``` This will `return` a `list` of filenames within the specified `your_directory`.
What is more pythonic in python?
22,208,334
3
2014-03-05T20:20:41Z
22,208,360
8
2014-03-05T20:22:12Z
[ "python", "string", "python-2.7", "coding-style" ]
Which string implementation in python is more pythonic? ``` string += "<%s>%s</%s>%s" % (a, b, c, d) ``` or ``` string += '<' + a + '>' + b + '<'/' + c + '>' + d ```
String formatting is faster and more readable, always. Consider using named parameters, and the more recent [`str.format()` method](http://docs.python.org/2/library/stdtypes.html#str.format): ``` "<{tag}>{value}</{tag}>{tail}".format(tag='foo', value='bar', tail='spam') ```
Python - "map" a list of keys to a dictionary
22,210,071
3
2014-03-05T21:48:03Z
22,210,116
7
2014-03-05T21:50:42Z
[ "python", "list", "dictionary", "syntax" ]
I have a multidimensional dictionary in Python, and I have a list which has the keys that I want to access. What is the easiest way to get the value from the dictionary? Example: ``` main = { 'one': { 'two': { 'three': "Final word" } } } mylist = ['one', 'two', 'three'] # and I w...
Loop over `mylist`, storing an intermediate dict (I called it `submain`) until you run out of `mylist` elements: ``` submain = main for key in mylist: submain = submain[key] print submain ```
How do I download NLTK data?
22,211,525
7
2014-03-05T23:19:31Z
30,822,962
14
2015-06-13T19:58:24Z
[ "python", "nltk" ]
Updated answer:NLTK works for 2.7 well. I had 3.2. I uninstalled 3.2 and installed 2.7. Now it works!! I have installed NLTK and tried to download NLTK Data. What I did was to follow the instrution on this site: <http://www.nltk.org/data.html> I downloaded NLTK, installed it, and then tried to run the following code:...
To download all dataset and models: ``` $ python3 >>> import nltk >>> nltk.download('all') ```
Python, pandas: how to sort dataframe by index
22,211,737
16
2014-03-05T23:35:32Z
22,211,821
24
2014-03-05T23:41:50Z
[ "python", "pandas" ]
When there is an DataFrame like the following: ``` import pandas as pd df = pd.DataFrame([1, 1, 1, 1, 1], index=[100, 29, 234, 1, 150], columns=['A']) ``` How can I sort this dataframe by index with each combination of index and column value intact?
Dataframes have a `sort_index` method which returns a copy by default. Pass `inplace=True` to operate in place. ``` import pandas as pd df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A']) df.sort_index(inplace=True) print(df.to_string()) ``` Gives me: ``` A 1 4 29 2 100 1 150 ...
MultiIndex Group By in Pandas Data Frame
22,214,985
2
2014-03-06T04:30:45Z
22,217,558
11
2014-03-06T07:10:35Z
[ "python", "pandas", "dataset", "dataframe" ]
I have a data set that contains countries and statistics on economic indicators by year, organized like so: ``` Country Metric 2011 2012 2013 2014 USA GDP 7 4 0 2 USA Pop. 2 3 0 3 GB GDP 8 7 0 7 GB ...
In this case, you don't actually need a `groupby`. You also don't have a `MultiIndex`. You can make one like this: ``` import pandas from io import StringIO datastring = StringIO("""\ Country Metric 2011 2012 2013 2014 USA GDP 7 4 0 2 USA Pop. 2 3 ...
Social Security Number Check - Python
22,215,314
3
2014-03-06T04:54:23Z
22,215,387
8
2014-03-06T05:00:02Z
[ "python", "while-loop" ]
Writing a program that prompts the user to enter a social security number in the format `ddd-dd-dddd` where `d` is a digit. The program displays `"Valid SSN"` for a correct Social Security number or `"Invalid SSN"` if it's not correct. I nearly have it, just have one issue. I'm not sure how to check if it's in the rig...
You can use [`re`](http://docs.python.org/2/library/re.html) to match the pattern: ``` In [112]: import re In [113]: ptn=re.compile(r'^\d\d\d-\d\d-\d\d\d\d$') ``` Or `r'^\d{3}-\d{2}-\d{4}$'` to make the pattern much readable as @Blender mentioned. ``` In [114]: bool(re.match(ptn, '999-99-1234')) Out[114]: True In ...
grouping rows in list in pandas groupby
22,219,004
12
2014-03-06T08:31:09Z
22,221,675
21
2014-03-06T10:28:32Z
[ "python", "pandas" ]
I have a pandas data frame like: ``` A 1 A 2 B 5 B 5 B 4 C 6 ``` I want to group by the first column and get second column as lists in rows: ``` A [1,2] B [5,5,4] C [6] ``` Is it possible to do something like this using pandas groupby?
You can do this using `groupby` to group on the column of interest and then `apply` `list` to every group: ``` In [1]: # create the dataframe df = pd.DataFrame( {'a':['A','A','B','B','B','C'], 'b':[1,2,5,5,4,6]}) df Out[1]: a b 0 A 1 1 A 2 2 B 5 3 B 5 4 B 4 5 C 6 [6 rows x 2 columns] In [76]: df....
Shebang doesn't work with python3
22,222,473
4
2014-03-06T11:00:34Z
30,128,006
7
2015-05-08T15:52:37Z
[ "python", "python-3.x", "shebang" ]
I have the following program: ``` #!/usr/local/bin/python3 print("Hello") ``` Via terminal I do `test.py` and I get: ``` Traceback (most recent call last): File "/usr/lib/python3.3/site.py", line 629, in <module> main() File "/usr/lib/python3.3/site.py", line 614, in main known_paths = addusersitepackag...
Generally, take care of some pitfalls: 1. set the executable flag on the script: `chmod u+x test.py` 2. try to execute with a preceding dot "./", so call `./test.py` otherwise it might execute some other script from within your PATH 3. also make sure you don't have windows line endings, this seems to prevent the sheba...
Pre-allocating a list of None
22,225,666
5
2014-03-06T13:14:36Z
22,225,720
12
2014-03-06T13:16:14Z
[ "python", "performance", "list", "design-patterns", "python-3.x" ]
Suppose you want to write a function which yields a list of objects, and you know in advance the length `n` of such list. In python the list supports indexed access in O(1), so it is arguably a good idea to pre-allocate the list and access it with indexes instead of allocating an empty list and using the `append()` me...
When you append an item to a list, Python 'over-allocates', see the [source-code](http://svn.python.org/projects/python/trunk/Objects/listobject.c) of the list object. This means that for example when adding 1 item to a list of 8 items, it actually makes room for 8 new items, and uses only the first one of those. The n...
Pre-allocating a list of None
22,225,666
5
2014-03-06T13:14:36Z
22,225,721
10
2014-03-06T13:16:15Z
[ "python", "performance", "list", "design-patterns", "python-3.x" ]
Suppose you want to write a function which yields a list of objects, and you know in advance the length `n` of such list. In python the list supports indexed access in O(1), so it is arguably a good idea to pre-allocate the list and access it with indexes instead of allocating an empty list and using the `append()` me...
In between those two options the first one is clearly better as no Python for loop is involved. ``` >>> %timeit [None] * 100 1000000 loops, best of 3: 469 ns per loop >>> %timeit [None for x in range(100)] 100000 loops, best of 3: 4.8 us per loop ``` **Update:** And `list.append` has an [`O(1)` complexity](https://...
Histogram with stacked components
22,226,375
6
2014-03-06T13:44:32Z
22,228,078
7
2014-03-06T14:57:17Z
[ "python", "matplotlib", "pandas", "seaborn" ]
Let's say that I have a value that I've measured every day for the past 90 days. I would like to plot a histogram of the values, but I want to make it easy for the viewer to see where the measurements have accumulated over certain non-overlapping subsets of the past 90 days. I want to do this by "subdividing" each bar ...
Ok, here's one way to attack it, using features from the `matplotlib` `hist` function itself: ``` fig, ax = plt.subplots(1, 1, figsize=(9, 5)) ax.hist([data.ix[low:high, 'values'] for low, high in [(0, 70), (70, 85), (85, 90)]], bins=15, stacked=True, rwidth=1.0, label=['first70', '...