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
Installing h5py on an Ubuntu server
24,744,969
33
2014-07-14T20:03:45Z
26,366,310
14
2014-10-14T17:05:21Z
[ "python", "python-2.7", "installation", "installer", "h5py" ]
I was installing h5py on an Ubuntu server. However it seems to return an error that `h5py.h` is not found. It gives the same error message when I install it using `pip` or the `setup.py` file. What am I missing here? I have Numpy version 1.8.1, which higher than the required version of 1.6 or above. The complete outp...
You can use [python-h5py](http://packages.ubuntu.com/trusty/python-h5py). > sudo apt-get install python-h5py And then in your Python file try: > import h5py
Installing h5py on an Ubuntu server
24,744,969
33
2014-07-14T20:03:45Z
33,045,656
7
2015-10-09T19:19:34Z
[ "python", "python-2.7", "installation", "installer", "h5py" ]
I was installing h5py on an Ubuntu server. However it seems to return an error that `h5py.h` is not found. It gives the same error message when I install it using `pip` or the `setup.py` file. What am I missing here? I have Numpy version 1.8.1, which higher than the required version of 1.6 or above. The complete outp...
In my case (Ubuntu 15.04) installing `libhdf5-dev` was not enough. I had to run: `HDF5_DIR=/usr/lib/x86_64-linux-gnu/hdf5/serial/ pip install h5py` to make it work.
How to use setuptools to install in a custom directory?
24,745,852
4
2014-07-14T20:57:45Z
24,746,315
7
2014-07-14T21:31:07Z
[ "python", "setuptools" ]
I have a python package that I need to install in the /usr/lib/python2.7/dist-packages or any other specific directory for that matter. Whenever I run the setup.py script it gives the following output: ``` root@abc44:~/som_dir/plugins/abc$python setup.py install running install running bdist_egg running egg_info writ...
Since the `python setup.py install` command is just a shortcut to `easy_install`, try running it directly, it has the `--install-dir` option: ``` easy_install . --install-dir /usr/lib/python2.7/dist-packages ``` You can get other available options with `python setup.py install -h`, in case you need some more, but the...
Python / Pillow: How to scale an image
24,745,857
11
2014-07-14T20:57:56Z
24,745,969
23
2014-07-14T21:05:27Z
[ "python", "python-imaging-library", "image-scaling", "pillow" ]
Suppose I have an image which is 2322pxx4128px. How do I scale it so that both the width and height are both less than 1028px? I won't be able to use Image.resize (<http://pillow.readthedocs.org/en/latest/reference/Image.html#PIL.Image.size>) since that requires me to give both the new width and height. What I plan to...
Noo need to reinvent the wheel, there is the [`Image.thumbnail`](http://pillow.readthedocs.org/en/latest/reference/Image.html#PIL.Image.Image.thumbnail) method available for this: ``` maxsize = (1028, 1028) image.thumbnail(maxsize, PIL.Image.ANTIALIAS) ``` Ensures the resulting size is not bigger than the given bound...
Beautiful Soup Using Regex to Find Tags?
24,748,445
3
2014-07-15T01:05:54Z
24,748,491
10
2014-07-15T01:12:13Z
[ "python", "regex", "web-scraping" ]
I'd really like to be able to allow Beautiful Soup to match any list of tags, like so. I know attr accepts regex, but is there anything in beautiful soup that allows you to do so? ``` soup.findAll("(a|div)") ``` Output: ``` <a> ASDFS <div> asdfasdf <a> asdfsdf ``` My goal is to create a scraper that can grab tables...
[`find_all()`](http://www.crummy.com/software/BeautifulSoup/bs4/doc/) is the most favored method in the Beautiful Soup search API. You can pass a variation of filters. You can pass a [list](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#a-list) to find multiple tags: ``` >>> soup.find_all(['a', 'div']) ``` **...
Why do tuples in Python work with reversed but do not have __reversed__?
24,750,146
3
2014-07-15T05:02:01Z
24,750,225
9
2014-07-15T05:10:12Z
[ "python", "iterator", "tuples", "immutability", "reverse" ]
In discussion of [this answer](http://stackoverflow.com/questions/9449674/how-to-implement-a-persistent-python-list/9449852#9449852) we realized that tuples do not have a `__reversed__` method. My guess was that creating the iterator would require mutating the tuple. And yet tuples play fine with `reversed`. Why can't ...
According to the [*spec*](https://docs.python.org/2/library/functions.html#reversed): **reversed(seq)** > Return a reverse iterator. seq must be an object which has a > **reversed**() method **or supports the sequence protocol (the \_\_len\_\_() method and the \_\_getitem\_\_() method with integer arguments starting ...
Python "raise from" usage
24,752,395
27
2014-07-15T07:33:02Z
24,752,607
30
2014-07-15T07:44:52Z
[ "python", "python-3.x", "exception-handling" ]
What's the difference between `raise` and `raise from` in Python? ``` try: raise ValueError except Exception as e: raise IndexError ``` which yields ``` Traceback (most recent call last): File "tmp.py", line 2, in <module> raise ValueError ValueError During handling of the above exception, another exc...
The difference is that when you use `from`, the *`__cause__` attribute* is set and the message states that the exception was *directly caused by*. If you omit the `from` then no `__cause__` is set, but the *`__context__` attribute* may be set as well, and the traceback then shows the context as *during handling somethi...
Unsupervised pre-training for convolutional neural network in theano
24,752,655
30
2014-07-15T07:47:24Z
26,047,542
27
2014-09-25T20:29:26Z
[ "python", "neural-network", "theano", "deep-learning", "unsupervised-learning" ]
I would like to design a deep net with one (or more) convolutional layers (CNN) and one or more fully connected hidden layers on top. For deep network with fully connected layers there are methods in theano for unsupervised pre-training, e.g., using [denoising auto-encoders](http://www.deeplearning.net/tutorial/SdA.h...
[This paper](http://people.idsia.ch/~ciresan/data/icann2011.pdf) describes an approach for building a stacked convolutional autoencoder. Based on that paper and some Google searches I was able to implement the described network. Basically, everything you need is described in the Theano convolutional network and denoisi...
functools.partial wants to use a positional argument as a keyword argument
24,755,463
11
2014-07-15T10:10:25Z
24,755,491
18
2014-07-15T10:11:39Z
[ "python", "partialfunction" ]
So I am trying to understand `partials`: ``` import functools def f(x,y) : print x+y g0 = functools.partial( f, 3 ) g0(1) 4 # Works as expected ``` In: ``` g1 = functools.partial( f, y=3 ) g1(1) 4 # Works as expected ``` In: ``` g2 = functools.partial( f, x=3 ) g2(1) TypeError: f() got multiple values for...
This has nothing to do with `functools.partial`, really. You are essentially calling your function like this: ``` f(1, x=3) ``` Python first fulfils the positional arguments, and your first argument is `x`. Then the keyword arguments are applied, and you **again** supplied `x`. `functools.partial()` has no means to ...
Python "Error 'dict' object has no attribute 'load'"
24,757,879
2
2014-07-15T12:09:26Z
24,757,947
7
2014-07-15T12:12:57Z
[ "python", "json", "urllib2" ]
I am sort of new to Python and I've looked around for this, but basically what I'm making is an IRC bot. Now, the thing that's giving me an issue is a YouTube extract command I added. Here is the source: ``` if text.find(':'+prefix+'yt') != -1: idb = text.split(':'+prefix+'yt') videoid = idb[1].strip() if ...
You are storing the result of `json.load` in a variable named `json`, effectively overriding the module `json`. This is most likely not what you want to achieve. Try renaming that.
Django.rest_framework: How to serialize one to many to many?
24,760,455
6
2014-07-15T14:09:55Z
24,816,791
11
2014-07-18T03:30:41Z
[ "python", "django", "serialization", "django-queryset", "django-rest-framework" ]
I have some troubles serializing with django. I have three models, let's say a School, a Room and a Desk (dummy name for example). Each School have multiple Room, and each Room have multiple Desk. The classes and their relations look like this : ``` class School(models.Model): name = models.CharField() class Roo...
If I'm understanding you correctly, you want the `SchoolSerializer` to return a nested structure 2 levels deep, but skipping the intermediate model. To do this, I would create a method in your `School` model to retrieve the `Desk` instances: ``` class School(models.Model): ... def get_desks(self): roo...
Pandas: Check if row exists with certain values
24,761,133
5
2014-07-15T14:41:01Z
24,761,389
9
2014-07-15T14:51:19Z
[ "python", "pandas", "contains" ]
I have a two dimensional (or more) pandas DataFrame like this: ``` >>> import pandas as pd >>> df = pd.DataFrame([[0,1],[2,3],[4,5]], columns=['A', 'B']) >>> df A B 0 0 1 1 2 3 2 4 5 ``` Now suppose I have a numpy array like `np.array([2,3])` and want to check if there is any row in `df` that matches with t...
Turns out it is really easy, the following does the job here: ``` >>> ((df['A'] == 2) & (df['B'] == 3)).any() True >>> ((df['A'] == 1) & (df['B'] == 2)).any() False ``` Maybe somebody comes up with a better solution which allows directly passing in the array and the list of columns to match. Note that the parenthesi...
Pandas - Compute z-score for all columns
24,761,998
5
2014-07-15T15:18:59Z
24,762,240
21
2014-07-15T15:29:03Z
[ "python", "pandas", "indexing", "statistics" ]
I have a dataframe containing a single column of IDs and all other columns are numerical values for which I want to compute z-scores. Here's a subsection of it: ``` ID Age BMI Risk Factor PT 6 48 19.3 4 PT 8 43 20.9 NaN PT 2 39 18.1 3 PT 9 41 19.5 NaN ``` Some of my ...
Build a list from the columns and remove the column you don't want to calculate the Z score for: ``` In [66]: cols = list(df.columns) cols.remove('ID') df[cols] Out[66]: Age BMI Risk Factor 0 6 48 19.3 4 1 8 43 20.9 NaN 2 2 39 18.1 3 3 9 41 19.5 NaN In [68]: # now ite...
Inconsistent Execution Time in Python on all systems
24,762,030
2
2014-07-15T15:20:36Z
24,762,575
7
2014-07-15T15:45:10Z
[ "python", "performance" ]
Something that's been driving me crazy with python... I used to think it was [just Windows](http://stackoverflow.com/questions/24749808/), but I was wrong. I can have the same exact code and run it multiple times and it executes in wildly different amounts of time. Take the following test code, for example: ``` import...
You are measuring very short times, and then even a little bit of something happening somewhere has a big impact. I ran your test script on my machine (OS X, Core i7, Python 2.7) and made this plot of `results`: ![enter image description here](http://i.stack.imgur.com/844uk.png) You can see that most of the time the...
Get the value of a Cython pointer
24,764,048
4
2014-07-15T17:01:43Z
24,764,641
8
2014-07-15T17:37:58Z
[ "python", "c", "pointers", "cython" ]
I am writing a function that constructs a malloc'd `unsigned char *` array, and then retuns the pointer. In pure Cython or C, this is easy. All you have to do is set a return type on the function, and return the pointer to the array. Done. However, I have reached a point where I need to return a pointer to an array cre...
You can cast a pointer to the appropriate C type, which should then be translated into a Python integer by Cython. The correct C type is `uintptr_t` from `<stddef.h>` which in Cython would be available via `from libc.stdint cimport uintptr_t`. The cast is of course written `<uintptr_t>array_or_pointer`.
Upgrade python packages from requirements.txt using pip command
24,764,549
13
2014-07-15T17:32:03Z
24,764,628
9
2014-07-15T17:37:14Z
[ "python", "django" ]
How do I upgrade all my python packages from requirements.txt file using pip command? tried with below command ``` $ pip install --upgrade -r requirements.txt ``` Since, the python packages are suffixed with the version number (`Django==1.5.1`) they don't seem to upgrade. Is there any better approach than manually e...
No. Your requirements file has been [pinned](http://nvie.com/posts/pin-your-packages/) to specific versions. If your requirements are set to that version, you should not be trying to upgrade beyond those versions. If you **need** to upgrade, then you need to switch to unpinned versions in your requirements file. Examp...
What is the most pythonic way to conditionally return a function
24,766,075
4
2014-07-15T18:59:13Z
24,766,099
8
2014-07-15T19:00:38Z
[ "python", "function", "return", "conditional-statements" ]
Say I have 2 functions. I want func2 to return func1 UNLESS func1 returns None, in which case func2 returns something else. There are two ways that I could do this, but they both feel slightly wrong. I could say: ``` def func1(n): if (condition): return foo def func2(n): if func1(n) is not None: ...
Since `None` evaluates to `False`, you could do: ``` def func2(n): return func1(n) or something_else ``` It should be noted however that this will cause `func2` to return `something_else` if `func1(n)` returns anything falsey (`0`, `[]`, etc.) --- For many functions, you could use [`next`](https://docs.python.o...
How to install Python 3.3 (not 3.4) on OS X with Homebrew?
24,767,286
7
2014-07-15T20:10:28Z
26,522,217
8
2014-10-23T06:10:58Z
[ "python", "django", "osx", "python-3.x", "homebrew" ]
If you install python3 through Homebrew it installs the latest version by default, which I did. But I want 3.3 instead of 3.4. How can I replace it with 3.3 specifically using Homebrew? I want to try Django with Python 3 but I'm just learning Django so I want to use the latest stable version, currently 1.6, which is co...
Here are some elements that you can piece together from the [homebrew FAQ](https://github.com/Homebrew/homebrew/wiki/FAQ). 1. [Can I edit formulae myself?](https://github.com/Homebrew/homebrew/wiki/FAQ#can-i-edit-formulae-myself) - yes. ``` brew edit python3 ``` 2. look for the `url` and change it to the ftp...
Individual alpha values in scatter plot / Matplotlib
24,767,355
11
2014-07-15T20:15:12Z
24,773,975
9
2014-07-16T06:47:09Z
[ "python", "matplotlib", "alpha", "scatter-plot" ]
I'm wondering if it is possible to have individual alpha values for each point to be plotted using the **scatter** function of **Matplotlib**. I need to plot a set of points, each one with its alpha value. For example, I have this code to plot some points ``` def plot_singularities(points_x, p, alpha_point, file_path...
tcaswell's suggestion is correct, you can do it like this: ``` import numpy as np import matplotlib.pylab as plt x = np.arange(10) y = np.arange(10) alphas = np.linspace(0.1, 1, 10) rgba_colors = np.zeros((10,4)) # for red the first column needs to be one rgba_colors[:,0] = 1.0 # the fourth column needs to be your a...
BeautifulSoup responses with error
24,768,858
6
2014-07-15T21:54:17Z
24,768,904
9
2014-07-15T21:58:55Z
[ "python", "html", "beautifulsoup", "html-parsing" ]
I am trying to get my feet wet with BS. I tried to work my way through the documentation butat the very first step I encountered already a problem. This is my code: ``` from bs4 import BeautifulSoup soup = BeautifulSoup('https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=5....1b&per_page=250&ac...
You are passing URL as a string. Instead you need to get the page source via [`urllib2`](https://docs.python.org/2/library/urllib2.html) or [`requests`](http://docs.python-requests.org/en/latest/): ``` from urllib2 import urlopen # for Python 3: from urllib.request import urlopen from bs4 import BeautifulSoup URL = ...
How do I configure a Python interpreter in IntelliJ IDEA with the PyCharm plugin?
24,769,117
62
2014-07-15T22:18:30Z
24,769,264
97
2014-07-15T22:29:48Z
[ "python", "intellij-idea" ]
There is a tutorial in the IDEA docs on how to add a Python interpreter in PyCharm, which involves accessing the "Project Interpreter" page. Even after installing the Python plugin, I don't see that setting anywhere. Am I missing something obvious?
With the Python plugin installed, navigate to File > Project Structure. Under the Project menu for Project SDK, select "New" and select "Python SDK", then select "Local". Provided you have a Python SDK installed, the flow should be natural from there - navigate to the location your Python installation lives.
UnicodeDecodeError: 'ascii' codec can't decode byte 0x96 in position 0
24,769,756
3
2014-07-15T23:22:20Z
24,772,424
7
2014-07-16T04:50:21Z
[ "python", "django", "celery", "python-unicode" ]
I looked at a number of the answers to similar questions, but can't seem to see where the error is occurring in my code. The error occurs when I try to run celery: `celery –A runLogProject worker –loglevel=INFO`. I commented out all the code related to Celery and it gives the same error. I also tried reinstalling C...
That's tricky issue. The problem is in how you typed your command: Wrong: ``` celery –A runLogProject worker –loglevel=INFO ``` Correct: ``` celery -A runLogProject worker -loglevel=INFO ``` It's almost impossible to spot a difference. In first to pass parameters -A and -loglevel are used dashes (ascii code: 8...
How do I detect if Gevent's monkey-patching is active?
24,770,633
7
2014-07-16T01:10:55Z
24,770,674
11
2014-07-16T01:15:22Z
[ "python", "gevent" ]
I have a Python unittest that depends on `multiprocessing` and therefore must not run when Gevent's monkey-patching is active. Is there a Python statement that can tell me whether `gevent.monkey.patch_all` has run or not?
I'm not sure there is an idiomatic way, but one simple way would be to check the `socket.socket` class: ``` import gevent.monkey, gevent.socket gevent.monkey.patch_all() import socket if socket.socket is gevent.socket.socket: print "gevent monkey patch has occurred" ```
How do I detect if Gevent's monkey-patching is active?
24,770,633
7
2014-07-16T01:10:55Z
24,780,917
8
2014-07-16T12:34:42Z
[ "python", "gevent" ]
I have a Python unittest that depends on `multiprocessing` and therefore must not run when Gevent's monkey-patching is active. Is there a Python statement that can tell me whether `gevent.monkey.patch_all` has run or not?
afaik the `gevent.monkey.saved` dict is only updated when an item is patched, and the original is placed within the dict (and removed on unpatching), e.g. ``` >>> from gevent.monkey import saved >>> 'sys' in saved True ```
Who runs the callback when using apply_async method of a multiprocessing pool?
24,770,934
18
2014-07-16T01:44:32Z
24,771,322
17
2014-07-16T02:35:59Z
[ "python", "callback", "parallel-processing", "multiprocessing" ]
I'm trying to understand a little bit of what's going on behind the scenes when using the apply\_sync method of a multiprocessing pool. Who runs the callback method? Is it the main process that called apply\_async? Let's say I send out a whole bunch of apply\_async commands with callbacks and then continue with my pr...
There is indeed a hint in the docs: > callback should complete immediately since **otherwise the thread which > handles the results** will get blocked. The callbacks are handled in the main process, but *they're run in their own separate thread*. When you create a `Pool` it actually creates a few `Thread` objects int...
How to check if string is a pangram?
24,771,381
4
2014-07-16T02:42:36Z
24,771,688
9
2014-07-16T03:24:21Z
[ "python", "string", "python-2.7", "pangram" ]
I want to create a function which takes a string as input and check whether the string is pangram or not (pangram is a piece of text which contains every letter of the alphabet). I wrote the following code, which works, but I am looking for an alternative way to do it, hopefully a shorted way. ``` import string def ...
``` is_pangram = lambda s: not set('abcdefghijklmnopqrstuvwxyz') - set(s.lower()) >>> is_pangram('abc') False >>> is_pangram('the quick brown fox jumps over the lazy dog') True >>> is_pangram('Does the quick brown fox jump over the lazy dog?') True >>> is_pangram('Do big jackdaws love my sphinx of quartz?') True ``` ...
How to downgrade the installed version of 'pip' on windows?
24,773,109
5
2014-07-16T05:50:17Z
24,773,239
12
2014-07-16T05:59:22Z
[ "python", "windows" ]
On a windows 7 machine I have `pip` version 1.5.6 installed: ``` pip 1.5.6 from C:\Users\dietz\PNC\tas\ENV\lib\site-packages (python 2.7) ``` In order to find the reason for an error I want to install a different version of pip, which worked fine for me. So how can I uninstall `pip` and install version 1.2.1 instead?
`pip` itself is just a normal python package. Thus you can install pip with pip. Of cource, you don't want to affect the system's pip, install it inside a virtualenv. ``` pip install pip==1.2.1 ```
How to fix error “Expected version spec in …” using pip install on Windows?
24,773,883
11
2014-07-16T06:42:04Z
26,715,385
14
2014-11-03T13:29:35Z
[ "python", "windows" ]
On a Windows 7 machine I am using the following command to install a package from a local directory: ``` pip install addons/pnc_tests --upgrade --extra-index-url=http://some_server/simple ``` which results in the following error: ``` C:\Users\alex\PNC\tas\ENV\Scripts\pip-script.py run on 07/16/14 07:50:47 Exception...
I guess you are missing the parameter -r; It must be like this if you have a requirement file to install from; `pip install -r addons/pnc_tests --upgrade --extra-index-url=http://some_server/simple` As it is defined on; [Pip Documentation](http://pip.readthedocs.org/en/latest/reference/pip_install.html#requirements-...
Element-wise logical OR in Pandas
24,775,648
15
2014-07-16T08:19:48Z
24,775,756
22
2014-07-16T08:24:41Z
[ "python", "pandas", "boolean-logic", "logical-operators", "boolean-operations" ]
I would like the element-wise logical OR operator. I know "or" itself is not what I am looking for. For AND I want to use & as explained [here](http://stackoverflow.com/questions/21415661/logic-operator-for-boolean-indexing-in-pandas "here"). For NOT I want to use np.invert() as explained [here](http://stackoverflow.c...
The corresponding operator is `|`: ``` df[(df < 3) | (df == 5)] ``` would elementwise check if value is less than 3 or equal to 5.
Django Compressor does not minify files
24,779,433
5
2014-07-16T11:18:45Z
26,417,144
15
2014-10-17T02:52:07Z
[ "python", "django", "mezzanine", "django-compressor" ]
I am trying to let django-compressor working with mezzanine. For first attempt I simply installed django compressor (as should be done for Mezzanine) and changed DEBUG = False but nothing changed in HTML generated from Django. So I followed the docs of django compressor and I modified my settings.py: ``` STATICFILES_F...
Django compressor will not run on the django server even with Debug = False. It also by default only will merge all your css files into one. To do other things like minify you can apply a filter. Here is what I did in my settings.py ``` COMPRESS_ENABLED = True COMPRESS_CSS_FILTERS = ['compressor.filters.css_default.Cs...
Customizing unittest.mock.mock_open for iteration
24,779,893
4
2014-07-16T11:40:27Z
24,779,923
12
2014-07-16T11:42:09Z
[ "python", "unit-testing", "mocking", "python-mock" ]
How should I customize unittest.mock.mock\_open to handle this code? ``` file: impexpdemo.py def import_register(register_fn): with open(register_fn) as f: return [line for line in f] ``` My first attempt tried `read_data`. ``` class TestByteOrderMark1(unittest.TestCase): REGISTER_FN = 'test_dummy_pa...
The `mock_open()` object does indeed not implement iteration. If you are not using the file object as a context manager, you could use: ``` m = unittest.mock.MagicMock(name='open', spec=open) m.return_value = iter(self.TEST_TEXT) with unittest.mock.patch('builtins.open', m): ``` Now `open()` returns an iterator, so...
Split list on None and record index
24,783,105
5
2014-07-16T14:14:27Z
24,783,312
7
2014-07-16T14:22:56Z
[ "python", "itertools" ]
I have a list which can contain both `None`s and `datetime` objects. I need to split this in sublists of consecutive `datetime` objects and need to record the index of the first `datetime` object of this sublist in the original list. E.g., I need to be able to turn ``` original = [None, datetime(2013, 6, 4), datetime...
I'd use a generator to produce the elements, encapsulating the grouping: ``` from itertools import takewhile def indexed_date_groups(it): indexed = enumerate(it) for i, elem in indexed: if elem is not None: yield ( i, [elem] + [v for i, v in takewhile( lambda v...
How to compute residuals of a point process in python
24,785,518
2
2014-07-16T16:04:45Z
24,790,177
7
2014-07-16T20:34:48Z
[ "python", "statistics", "scipy", "stochastic-process" ]
I am trying to reproduce the work from <http://jheusser.github.io/2013/09/08/hawkes.html> in python except with different data. I have written code to simulate a Poisson process as well as the Hawkes process they describe. To do the Hawkes model MLE I define the log likelihood function as ``` def loglikelihood(params...
OK, so first thing that you may wish to do is to plot the data. To keep it simple I've reproduced [this figure](http://jheusser.github.io/images/fake_intensity.png) as it only has 8 events occurring so it's easy to see the behaviour of the system. The following code: ``` import numpy as np import math, matplotlib impo...
Dropping time from datetime <[M8] in Pandas
24,786,209
5
2014-07-16T16:40:36Z
24,792,087
12
2014-07-16T22:45:42Z
[ "python", "datetime", "pandas", "dataframe" ]
So I have a 'Date' column in my data frame where the dates have the format like this ``` 0 1998-08-26 04:00:00 ``` If I only want the Year month and day how do I drop the trivial hour?
The quickest way is to use DatetimeIndex's normalize (you first need to make the column a DatetimeIndex): ``` In [11]: df = pd.DataFrame({"t": pd.date_range('2014-01-01', periods=5, freq='H')}) In [12]: df Out[12]: t 0 2014-01-01 00:00:00 1 2014-01-01 01:00:00 2 2014-01-01 02:00:00 3 2014-01-01 03...
Calculate the Cumulative Distribution Function (CDF) in Python
24,788,200
5
2014-07-16T18:36:16Z
24,788,741
8
2014-07-16T19:08:10Z
[ "python", "numpy", "machine-learning", "statistics", "scipy" ]
How can I calculate in python the [Cumulative Distribution Function (CDF)](https://en.wikipedia.org/wiki/Cumulative_distribution_function)? I want to calculate it from an array of points I have (discrete distribution), not with the continuous distributions that, for example, scipy has.
(It is possible that my interpretation of the question is wrong. If the question is how to get from a discrete PDF into a discrete CDF, then `np.cumsum` divided by a suitable constant will do if the samples are equispaced. If the array is not equispaced, then `np.cumsum` of the array multiplied by the distances between...
Change the title of factor plot in seaborn
24,789,671
6
2014-07-16T20:05:49Z
24,791,192
10
2014-07-16T21:35:22Z
[ "python", "seaborn", "aesthetics" ]
Does anyone know how to change the legend and the title in seaborn? See the below. I kind of want to change the name "Gaussia" to "Guassian Naive Bayes" etc...![enter image description here](http://i.stack.imgur.com/n6dD2.png) ![enter image description here](http://i.stack.imgur.com/tDs0C.png)or the legend in the sec...
These values are just taken from the field in the input DataFrame that you use as the `col` or `hue` variable in the factorgrid plot. So the correct thing to do would be to set the values as you want them in the original DataFrame and then pass that to `seaborn.factorplot`. Alternatively, once you have plotted, the fu...
How to write a lambda function that is conditional on two variables (columns) in python
24,790,676
5
2014-07-16T21:01:36Z
24,790,920
8
2014-07-16T21:16:46Z
[ "python", "lambda", "pandas", "conditional", "multiple-columns" ]
I have a data set, df, with two variables, x and y. I want to write a function that does the following: > x if x>100 and y<50 else y I am used to doing data analysis in STATA so I'm relatively new to pandas for data analysis. If it helps, in stata it would look like: > replace x = cond(x>100 & y<50, x, y) In other ...
Use `where`: ``` df['dummyVar '] = df['x'].where((df['x'] > 100) & (df['y'] < 50), df['y']) ``` This will be much faster than performing an apply operation as it is vectorised.
Install pyyaml using pip/Add PyYaml as pip dependency
24,791,251
13
2014-07-16T21:39:12Z
24,791,419
15
2014-07-16T21:50:55Z
[ "python", "pip", "yaml" ]
I want to use PyYaml in my pip project, but am having trouble using it as a dependency. Mainly the problem is thet PyYaml in pip is not a cross platform install. How do I install pyyaml using pip so that it works. Note, on a current fresh Ubuntu install I get the following error when running `pip install pyyaml` ``` ...
You will need some extra packages to build it. First of all you need to uninstall `pyyaml`, or it will complain later that it is already installed ``` pip uninstall pyyaml ``` Then install the following packages: ``` sudo apt-get install libyaml-dev libpython2.7-dev ``` Finally install it again ``` pip install py...
Numpy pcolormesh: TypeError: Dimensions of C are incompatible with X and/or Y
24,791,614
5
2014-07-16T22:05:10Z
24,792,143
10
2014-07-16T22:51:35Z
[ "python", "numpy", "matplotlib" ]
This code: ``` xedges = np.arange(self.min_spread - 0.5, self.max_spread + 1.5) yedges = np.arange(self.min_span - 0.5, self.max_span + 1.5) h, xe, ye = np.histogram2d( self.spread_values , self.span_values , [xedges, yedges] ) fig = plt.figure(figsize=(7,3)) ax = fig.add_subplot(111) x, y = np.meshgrid(xe...
This may look very amazing, but the explanation is simple... The error message is printed in this way: ``` if not (numCols in (Nx, Nx - 1) and numRows in (Ny, Ny - 1)): raise TypeError('Dimensions of C %s are incompatible with' ' X (%d) and/or Y (%d); see help(%s)' % ( ...
Python JSON: NameError: name 'false' is not defined
24,791,854
2
2014-07-16T22:25:07Z
24,791,927
10
2014-07-16T22:30:55Z
[ "python", "json" ]
I was trying to json.load this dict from twitter: ``` {"created_at":"Thu Jul 10 20:02:00 +0000 2014","id":487325888950710272,"id_str":"487325888950710272","text":"\u5f81\u9678\u300c\u5de6\u8155\u306e\u7fa9\u624b\u306f\u30db\u30ed\u3060\u300d","source":"\u003ca href=\"http:\/\/twittbot.net\/\" rel=\"nofollow\"\u003etwi...
You are trying to paste the string straight into Python. Don't do that, it is a string sequence that *represents* objects. JSON only *looks* a lot like Python, but it is not actual Python code. Here I loaded this as a *raw Python string* to not interpret any escapes in it: ``` >>> import json >>> json_string = r'''{...
Django: AppRegistryNotReady()
24,793,351
22
2014-07-17T01:13:01Z
24,793,445
30
2014-07-17T01:24:12Z
[ "python", "django", "django-1.7" ]
Python: 2.7; Django: 1.7; Mac 10.9.4 I'm following the tutorial of [Tango with Django](http://www.tangowithdjango.com/book/chapters/models.html#creating-a-population-script) At Chapter 5, the tutorial teaches how to create a population script, which can automatically create some data for the database for the ease of ...
If you are using your django project applications in standalone scripts, in other words, without using `manage.py` - you need to manually call `django.setup()` first - it would configure the logging and, what is important - populate [apps registry](https://docs.djangoproject.com/en/dev/ref/applications/#application-reg...
Selenium Python get all children elements
24,795,198
18
2014-07-17T05:00:43Z
24,795,416
25
2014-07-17T05:19:14Z
[ "python", "selenium", "selenium-webdriver" ]
In Selenium with Python is it possible to get all the children of a WebElement as a list?
Yes, you can achieve it by `find_elements_by_css_selector("*")` or `find_elements_by_xpath(".//*")`. However, this doesn't sound like a valid use case to find **all children** of an element. It is an expensive operation to get all direct/indirect children. Please further explain what you are trying to do. There should...
Selenium Python get all children elements
24,795,198
18
2014-07-17T05:00:43Z
24,795,418
11
2014-07-17T05:19:31Z
[ "python", "selenium", "selenium-webdriver" ]
In Selenium with Python is it possible to get all the children of a WebElement as a list?
Yes, you can use `find_elements_by_` to retrieve children elements into a list. See the python bindings here: <http://selenium-python.readthedocs.org/en/latest/api.html> Example HTML: ``` <ul class="bar"> <li>one</li> <li>two</li> <li>three</li> </ul> ``` You can use the `find_elements_by_` like so: ```...
Starting the ipython notebook
24,795,239
14
2014-07-17T05:04:07Z
24,938,101
15
2014-07-24T15:35:46Z
[ "python" ]
In an ubuntu terminal window when the notebook is starting this error is raised. Could anybody explain this error ``` KeyError: 3 ERROR:root:Exception in I/O handler for fd 3 Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/zmq/eventloop/ioloop.py", line 330, in start self._handlers[fd](...
I had to upgrade pyzmq to get it working: ``` sudo pip install pyzmq --upgrade ``` If the problem still persists try upgrading the rest of the libraries which are: ``` sudo pip install jinja2 sudo pip install tornado ``` If you don't wanna be messing around with these libraries you could run a virtual environment a...
How to save unicode with SQLAlchemy?
24,795,444
5
2014-07-17T05:22:33Z
24,919,349
7
2014-07-23T19:33:02Z
[ "python", "unicode", "sqlalchemy" ]
I've encountered such error: ``` File "/vagrant/env/local/lib/python2.7/site-packages/sqlalchemy/engine/default.py", line 435, in do_execute cursor.execute(statement, parameters) exceptions.UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 8410: ordinal not in range(128...
Your problem is here: ``` $ sudo grep client_encoding /etc/postgresql/9.3/main/postgresql.conf client_encoding = sql_ascii ``` That causes psycopg2 to default to ASCII: ``` >>> import psycopg2 >>> psycopg2.connect('dbname=dev_db user=dev').encoding 'SQLASCII' ``` ... which effectively shuts off psycopg2'...
Python's implementation of Permutation Test with permutation number as input
24,795,535
4
2014-07-17T05:29:49Z
24,801,874
9
2014-07-17T11:05:39Z
[ "python", "testing", "statistics" ]
R well-known library for permutation test i.e. [perm](http://cran.r-project.org/web/packages/perm/). The example I'm interested in is this: ``` x <- c(12.6, 11.4, 13.2, 11.2, 9.4, 12.0) y <- c(16.4, 14.1, 13.4, 15.4, 14.0, 11.3) permTS(x,y, alternative="two.sided", method="exact.mc", control=permControl(nmc=30000))...
This is a possible implementation of permutation test using monte-carlo method: ``` def exact_mc_perm_test(xs, ys, nmc): n, k = len(xs), 0 diff = np.abs(np.mean(xs) - np.mean(ys)) zs = np.concatenate([xs, ys]) for j in range(nmc): np.random.shuffle(zs) k += diff < np.abs(np.mean(zs[:n])...
Install pip failed
24,795,955
2
2014-07-17T06:03:48Z
24,796,817
7
2014-07-17T06:58:21Z
[ "python", "linux", "python-2.7", "pip", "yum" ]
i am using redhat 5.3 I using following command to update python to 2.7. (it was python 2.4 before update) ``` # xz -d Python-2.7.6.tar.xz # tar xvf Python-2.7.6.tar # cd Python-2.7.6/ # ./configure # make && make install ``` And I Install the python-setuptools ``` # yum install python-setuptools ``` Then I insta...
You should be very careful when upgrading Python on RedHat (including Fedora/CentOS) because a large majority of the system applications rely on the bundled version of Python. This is especially true of `yum`, which relies on the version of Python that comes bundled with the operating system. In short - **if you upgra...
Is it possible to use Variable for collection name using pymongo?
24,799,988
2
2014-07-17T09:40:21Z
24,800,102
9
2014-07-17T09:44:56Z
[ "python", "mongodb", "pymongo" ]
Is it possible to use Variable for collection name using pymongo? for example: ``` col = 'my_collection' db.col.update() ```
You can use: ``` col = 'my_collection' db[col].update() ``` [reference](http://api.mongodb.org/python/current/tutorial.html#getting-a-database)
Unnamed Python objects have the same id
24,802,740
5
2014-07-17T11:50:31Z
24,802,850
12
2014-07-17T11:55:07Z
[ "python", "python-2.7" ]
Let's create two lists: ``` x = range(3) y = range(3) print id(x), id(y) ``` Out: ``` 4366592912 4366591040 ``` I created two independent lists, and the output shows two different memory addresses. This is not surprising. But now let's do the same thing without the assignment: ``` id(range(3)) ``` Out: ``` 43666...
[From the doc of `id(object)`](https://docs.python.org/3.4/library/functions.html#id): > Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. **Two objects with non-overlapping lifetimes may have the same id() value.** Since the ...
Fit a non-linear function to data/observations with pyMCMC/pyMC
24,804,298
14
2014-07-17T12:58:56Z
24,834,164
10
2014-07-18T21:37:25Z
[ "python", "regression", "pymc" ]
I am trying to fit some data with a Gaussian (and more complex) function(s). I have created a small example below. My first question is, *am I doing it right?* My second question is, *how do I add an error in the x-direction, i.e. in the x-position of the observations/data?* It is very hard to find nice guides on ho...
> My first question is, am I doing it right? Yes! You need to include a burn-in period, which you know. I like to throw out the first half of my samples. You don't need to do any thinning, but sometimes it will make your post-MCMC work faster to process and smaller to store. The only other thing I advise is to set a ...
How can I copy a Python string?
24,804,453
32
2014-07-17T13:06:07Z
24,804,471
72
2014-07-17T13:07:28Z
[ "python", "string", "python-2.7" ]
I do this: ``` a = 'hello' ``` And now I just want an independent copy of `a`: ``` import copy b = str(a) c = a[:] d = a + '' e = copy.copy(a) map( id, [ a,b,c,d,e ] ) ``` Out[3]: ``` [4365576160, 4365576160, 4365576160, 4365576160, 4365576160] ``` Why do they all have the same memory address and how can I get ...
You don't *need* to copy a Python string. They are immutable, and the `copy` module always returns the original in such cases, as do `str()`, the whole string slice, and concatenating with an empty string. Moreover, your `'hello'` string is *interned* ([certain strings are](http://stackoverflow.com/questions/24245324/...
Another one about pyCrypto and Paramiko
24,804,829
14
2014-07-17T13:24:27Z
24,822,876
33
2014-07-18T10:29:04Z
[ "python", "paramiko", "pycrypto" ]
I already spent 2 days trying to install pyCrypto for Paramiko module. So, first issue I had faced was this: ``` >>> import paramiko Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Program Files\Python\lib\site-packages\paramiko\__init__.py", line 31 , in <module> from paramiko...
Problem is solved by editing string in crypto\Random\OSRNG\nt.py: ``` import winrandom ``` to ``` from . import winrandom ```
How to use python-docx to replace text in a Word document and save
24,805,671
4
2014-07-17T14:00:44Z
24,813,382
8
2014-07-17T20:56:31Z
[ "python", "text", "replace", "ms-word", "python-docx" ]
The oodocx module mentioned in the same page refers the user to an /examples folder that does not seem to be there. I have read the documentation of python-docx 0.7.2, plus everything I could find in Stackoverflow on the subject, so please believe that I have done my “homework”. Python is the only language I kno...
The current version of python-docx does not have a `search()` function or a `replace()` function. These are requested fairly frequently, but an implementation for the general case is quite tricky and it hasn't risen to the top of the backlog yet. Several folks have had success though, getting done what they need, usin...
ImportError: No module named scipy
24,808,043
13
2014-07-17T15:44:24Z
28,016,843
19
2015-01-19T01:44:49Z
[ "python", "python-2.7", "scipy", "pybrain" ]
I am using Python 2.7 and trying to get PyBrain to work. But I get this error even though scipy is installed - ``` raceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.7/site-packages/PyBrain-0.3.1- py2.7.egg/pybrain/__init__.py", line 1, in <module> from pybrain....
Try to install it as a python package using pip. You said you already tried: ``` sudo apt-get install python-scipy ``` Now run: ``` pip install scipy ``` I ran both and it worked on my Debian-based box.
Sending a form array to Flask
24,808,660
13
2014-07-17T16:15:48Z
24,808,706
30
2014-07-17T16:18:20Z
[ "python", "html", "flask" ]
I have a html form with multiple inputs named like this: ``` <input name="hello[]" type="text" /> <input name="hello[]" type="text" /> <input name="hello[]" type="text" /> ``` In PHP you get this as an array but is it the same way in Python using Flask? I tried this: ``` hello = request.form['hello'] print hell...
You are following a [PHP convention of adding brackets to the field names](http://stackoverflow.com/questions/4543500/form-input-field-names-containing-square-brackets-like-fieldindex). It's not a web standard, but because PHP supports it out of the box it is popular; Ruby on Rails also uses it. If you do use that con...
Correct way to edit dictionary value python
24,810,660
6
2014-07-17T18:11:01Z
24,810,749
8
2014-07-17T18:16:34Z
[ "python", "pep8" ]
I have written the following code in two different ways. I am trying to find the "correct pythonic" way of doing it. I will explain the reasons for both. First way, EAFP. This one uses pythons EAFP priciple, but causes some code duplication. ``` try: my_dict['foo']['bar'] = some_var except KeyError: my_dict['...
I would say a seasoned Python developer would either use [dict.setdefault](https://docs.python.org/2/library/stdtypes.html#dict.setdefault) or [collections.defaultdict](https://docs.python.org/2/library/collections.html#collections.defaultdict) ``` my_dict.setdefault('foo', {})['bar'] = some_var ``` or ``` from col...
How to share sessions between modules on a Google App Engine Python application?
24,811,286
8
2014-07-17T18:49:27Z
24,818,688
7
2014-07-18T06:41:47Z
[ "python", "google-app-engine", "session", "module" ]
I'm trying to make a basic app on Google App Engine with two modules using Google App Engine Modules(<https://developers.google.com/appengine/docs/python/modules/>) and They share session information between the modules: Modules: * Module 1 - Login Page: a basic page with a login form where if is a valid user I creat...
By default webapp2\_extra.sessions uses cooki-based sessions. These will be tied to a specific domain. Your modules are probably at module1.yourapp.appspot.com and module2.yourapp.appspot.com (a guess). The second module won't be able to see the cookies set by the first module. In your config try setting the domain fo...
Why are complex numbers in Python denoted with 'j' instead of 'i'?
24,812,444
11
2014-07-17T19:59:34Z
24,812,607
9
2014-07-17T20:09:23Z
[ "python" ]
I know this is an electrical engineering convention, but I'm still wondering why it was chosen for Python. I don't know other programming languages with complex-number literals, so I don't have anything to compare against, but does anyone know any that do use i?
Python adopted the convention used by electrical engineers. In that field, `i` is used to represent current and use `j` as the square root of -1. There was a [bug](http://bugs.python.org/issue10562) logged to change it to `i` in Python 3.3. It was resolves as a "WONTFIX" with this reasoning by [Guido van Rossum](http:...
Why are complex numbers in Python denoted with 'j' instead of 'i'?
24,812,444
11
2014-07-17T19:59:34Z
24,812,657
11
2014-07-17T20:11:40Z
[ "python" ]
I know this is an electrical engineering convention, but I'm still wondering why it was chosen for Python. I don't know other programming languages with complex-number literals, so I don't have anything to compare against, but does anyone know any that do use i?
It appears to be, as you guessed, because Python follows the electrical engineering convention. Here's an exchange from the Python bug tracker [Issue10562](http://bugs.python.org/issue10562): > **Boštjan Mejak**: In Python, the letter 'j' denotes the imaginary unit. It would be great if we would follow mathematics in...
Python: default dict keys to avoid KeyError
24,814,024
9
2014-07-17T21:41:33Z
24,814,077
19
2014-07-17T21:44:40Z
[ "python", "json", "csv", "dictionary", "keyerror" ]
**Fairly new to python, novice developer, first time caller** I'm calling some JSON and parsing relevant data as csv. I cannot figure out how to fill in the intermediate json Dict file with default keys, as many are unpopulated. The result is a KeyError as I attempt to parse the content into a csv. Would love any advi...
You can use `your_dict.get(key, "default value")` instead of directly referencing a key.
ipython notebook clear cell output in code
24,816,237
17
2014-07-18T02:02:56Z
24,818,304
30
2014-07-18T06:12:07Z
[ "python", "ipython", "ipython-notebook" ]
In a iPython notebook, I have a while loop that listens to a Serial port and `print` the received data in real time. What I want to achieve to only show the latest received data (i.e only one line showing the most recent data. no scrolling in the cell output area) What I need(i think) is to clear the old cell output ...
You can use [`IPython.display.clear_output`](http://ipython.org/ipython-doc/dev/api/generated/IPython.display.html#IPython.display.clear_output) to clear the output of a cell. ``` from IPython.display import clear_output for i in range(10): clear_output() print("Hello World!") ``` At the end of this loop you...
django: return string from view
24,817,007
12
2014-07-18T03:59:16Z
24,817,024
27
2014-07-18T04:01:45Z
[ "python", "django", "django-views" ]
I know this is a simple question, sorry. I just want to return a simple string, no templates. I have my view: ``` def myview(request): return "return this string" ``` I don't remember the command. Thanks
According to the [documentation](https://docs.djangoproject.com/en/dev/topics/http/views/): > A view function, or view for short, is simply a Python function that > takes a Web request and returns a Web response. > > Each view function is responsible for returning an HttpResponse > object. In other words, your view s...
How do you have an attribute called "property" and use the @property decorator?
24,819,862
4
2014-07-18T07:52:39Z
24,819,901
7
2014-07-18T07:54:53Z
[ "python", "django", "properties", "built-in" ]
I have a bit of a problem, and I've tried googling, but it doesn't turn up anything helpful. I'm designing a django application and I want/need to have a field called "property". The reason for this is that *is* the technical title of the thing I'm trying to manage, and where possible I'd like to keep the business ter...
Maybe this helps: ``` # On the module-level, do a workaround reference # as property() is just a normal built-in function _property = property class Foobar: property = .... @_property def registryCascadeItems(self): .... ```
Summing over a multiindex level in a pandas series
24,826,368
10
2014-07-18T13:37:08Z
24,826,569
15
2014-07-18T13:46:44Z
[ "python", "pandas", "statistics", "multi-index" ]
Using the Pandas package in python, I would to sum (marginalize) over one level in a series with a 3-level multiindex to produce a series with a 2 level multiindex. For example, if I have the following: ``` ind = [tuple(x) for x in ['ABC', 'ABc', 'AbC', 'Abc', 'aBC', 'aBc', 'abC', 'abc']] mi = pd.MultiIndex.from_tuple...
If you know you always want to aggregate over the first two levels, then this is pretty easy: ``` In [27]: data.groupby(level=[0, 1]).sum() Out[27]: A B 277 b 37 a B 159 b 16 dtype: int64 ```
Do any of python's built in modules use threads?
24,830,449
3
2014-07-18T17:13:02Z
24,830,551
7
2014-07-18T17:20:37Z
[ "python", "multithreading", "standard-library" ]
Will importing/using any of python's built in libraries spawn threads without being explicitly asked?
The [`multiprocessing`](https://docs.python.org/2.7/library/multiprocessing.html) module and [`subprocess`](https://docs.python.org/2.7/library/subprocess.html) module both spawn `threading.Thead` objects internally to help handle I/O with the processes they spawn. Specifically, `multiprocessing.Pool` [spawns three th...
Are there any built-in functions which block on I/O that don't allow other threads to run?
24,831,458
10
2014-07-18T18:21:52Z
24,844,446
9
2014-07-19T20:00:59Z
[ "python", "multithreading", "python-multithreading" ]
I came across this interesting statement in "Caveats" section of the documentation for the [`thread`](https://docs.python.org/2/library/thread.html) module today: > Not all built-in functions that may block waiting for I/O allow other > threads to run. (The most popular ones (`time.sleep()`, `file.read()`, > `select.s...
Here's the [official word from Guido van Rossum](http://bugs.python.org/issue22006#msg223471) on this one: > Not in my wildest dreams could I have expected that that claim would > still be in the docs 20 years later. :-) Please get rid of it. So the answer to my question is "No".
TypeError: 'in <string>' requires string as left operand, not int
24,831,961
2
2014-07-18T18:57:22Z
24,831,982
11
2014-07-18T18:58:36Z
[ "python" ]
Why am I getting this error in the very basic Python script? What does the error mean? Error: ``` Traceback (most recent call last): File "cab.py", line 16, in <module> if cab in line: TypeError: 'in <string>' requires string as left operand, not int ``` Script: ``` import re import sys #loco = sys.argv[1] c...
You simply need to make `cab` a string: ``` cab = '6176' ``` As the error message states, you cannot do `<int> in <string>`: ``` >>> 1 in '123' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'in <string>' requires string as left operand, not int >>> ``` because [integers](https:...
unbound method must be called with instance as first argument - python
24,833,338
5
2014-07-18T20:32:17Z
24,833,469
8
2014-07-18T20:41:58Z
[ "python", "function", "class", "python-2.7", "typeerror" ]
I keep on receiving the error: TypeError: unbound method get\_num\_students() must be called with Student instance as first argument (got nothing instead) I need to have this project done by tonight... Any and all help is well appreciated. Here is the code: ``` class Student(object): num_students = 0 num_gra...
It seems like you wanted to define `grad_early`, `get_num_students` and `get_grad_2013` as class methods, but you declared them as instance methods instead. An instance method is a method that, well, belongs to an instance of the class. An example would be ``` class Student(object): # ... def print_name(sel...
.pyw and pythonw does not run under Windows 7
24,835,155
11
2014-07-18T23:23:30Z
30,310,192
10
2015-05-18T18:14:38Z
[ "python", "python-2.7", "windows-7", "pythonw" ]
Running a simple .py or .pyw python file causes `python.exe` to show up under Task Manager. ``` python myApp.py python myApp.pyw ``` However when we try to run it without using the console, the script does not appear to run, nor does `python.exe` or `pythonw.exe` appears under Task Manager ``` pythonw myApp.pyw pyth...
**tl;dr** * To **troubleshoot**, use **output redirection** on invocation: ``` pythonw myApp.py 1>stdout.txt 2>stderr.txt ``` This will capture stdout output, such as from `print()`, in file `stdout.txt`, and stderr output (such as from unhandled exceptions), in file `stderr.txt`; from PowerShell, use `cmd /...
Apache Spark: Job aborted due to stage failure: "TID x failed for unknown reasons"
24,836,401
9
2014-07-19T03:21:05Z
24,839,222
8
2014-07-19T10:14:42Z
[ "python", "apache-spark" ]
I'm dealing with some strange error messages that I *think* comes down to a memory issue, but I'm having a hard time pinning it down and could use some guidance from the experts. I have a 2-machine Spark (1.0.1) cluster. Both machines have 8 cores; one has 16GB memory, the other 32GB (which is the master). My applicat...
If I had a penny for every time I asked people "have you tried increasing the number of partitions to something quite large like at least 4 tasks per CPU - like even as high as 1000 partitions?" I'd be a rich man. So have you tried increasing the partitions? Anyway, other things I've found help with weird dissasociati...
Python - Matrix outer product
24,839,481
5
2014-07-19T10:43:16Z
24,842,096
7
2014-07-19T15:45:35Z
[ "python", "numpy", "matrix" ]
Given two matrices ``` A: m * r B: n * r ``` I want to generate another matrix `C: m * n`, with each entry `C_ij` being a matrix calculated by the outer product of `A_i` and `B_j`. For example, ``` A: [[1, 2], [3, 4]] B: [[3, 1], [1, 2]] ``` gives ``` C: [[[3, 1], [[1 ,2], [6, 2]], [2 ,4]], [...
The Einstein notation expresses this problem nicely ``` In [85]: np.einsum('ac,bd->abcd',A,B) Out[85]: array([[[[ 3, 1], [ 6, 2]], [[ 1, 2], [ 2, 4]]], [[[ 9, 3], [12, 4]], [[ 3, 6], [ 4, 8]]]]) ```
Download pdf using urllib?
24,844,729
9
2014-07-19T20:33:14Z
24,845,366
11
2014-07-19T21:57:49Z
[ "python", "pdf", "urllib" ]
I am trying to download a pdf file from a website using urllib. This is what i got so far: ``` import urllib def download_file(download_url): web_file = urllib.urlopen(download_url) local_file = open('some_file.pdf', 'w') local_file.write(web_file.read()) web_file.close() local_file.close() if __...
Here is an example that works: ``` import urllib2 def main(): download_file("http://mensenhandel.nl/files/pdftest2.pdf") def download_file(download_url): response = urllib2.urlopen(download_url) file = open("document.pdf", 'w') file.write(response.read()) file.close() print("Completed") if _...
python parse prints only first line from list
24,849,562
2
2014-07-20T10:27:04Z
24,849,595
7
2014-07-20T10:31:26Z
[ "python", "list" ]
I have a list 'a',where I need to print all the matching letters of the list with the line of a text file 'hello.txt'.But it only prints the first word from the list and line instead of all the list and lines ``` a=['comp','graphics','card','part'] with open('hello.txt', 'r') as f: for key in a: for line ...
The file-object `f` is an iterator. [Once you've iterated it, it's exhausted](http://stackoverflow.com/questions/5187457/what-does-it-mean-to-consume-in-python-in-an-iterator), thus your `for line in f:` loop will only work for the first key. Store the lines in a `list`, then it should work. ``` a=['comp','graphics','...
How to catch exception output from Python subprocess.check_output()?
24,849,998
14
2014-07-20T11:24:17Z
24,850,026
20
2014-07-20T11:28:23Z
[ "python", "bash", "subprocess" ]
I'm trying to do a Bitcoin payment from within Python. In bash I would normally do this: ``` bitcoin sendtoaddress <bitcoin address> <amount> ``` so for example: ``` bitcoin sendtoaddress 1HoCUcbK9RbVnuaGQwiyaJGGAG6xrTPC9y 1.4214 ``` if it is successfull I get a transaction id as output but if I try to transfer an ...
According to the [`subprocess.check_output()` docs](https://docs.python.org/2/library/subprocess.html#subprocess.check_output), the exception raised on error has an `output` attribute that you can use to access the error details: ``` try: subprocess.check_output(...) except subprocess.CalledProcessError as e: ...
tornado 403 GET warning when opening websocket
24,851,207
24
2014-07-20T13:58:08Z
25,071,488
62
2014-08-01T01:26:03Z
[ "python", "websocket", "tornado" ]
I found this python script which should allow me to open a WebSocket. However, I receive the warning `[W 1402720 14:44:35 web:1811] 403 GET / (192.168.0.102) 11.02 ms` in my Linux terminal when trying to open the actual WebSocket (using Old WebSocket Terminal Chrome plugin). The messages "connection opened", "connectio...
please add ``` def check_origin(self, origin): return True ``` in class MyHandler like this ``` class MyHandler(tornado.websocket.WebSocketHandler): def check_origin(self, origin): return True def open(self): print "connection opened" self.write_message("connection opened") ...
flask View function mapping is overwriting an existing endpoint function: type
24,851,241
4
2014-07-20T14:03:57Z
24,851,516
10
2014-07-20T14:36:20Z
[ "python", "flask" ]
I recently purchased [RealPython](http://www.realpython.com/) to learn about Python and web development. However, I have ran into a road block that I think is a Python configuration issue on my machine. Any help would be much obliged. So I have a Flask document called app.py similar to [RealPython's github app.py](htt...
So, you figured out the solution: It's a namespace issue. You have three functions that are conflicting against one another - `def type`. When you renamed them using different names, this fixed the issue. I am the author of [Real Python](http://realpython.com), by the way. Correcting now. Cheers!
HSV to RGB Color Conversion
24,852,345
6
2014-07-20T16:06:33Z
24,852,375
10
2014-07-20T16:09:31Z
[ "python", "colors", "pygame", "rgb", "hsv" ]
Is there a way to convert HSV color arguments to RGB type color arguments using pygame modules in python? I tried the following code, but it returns ridiculous values. ``` import colorsys test_color = colorsys.hsv_to_rgb(359, 100, 100) print(test_color) ``` and this code returns the following nonsense ``` (100, -990...
That function expects decimal for `s` (saturation) and `v` (value), not percent. Divide by 100. ``` >>> import colorsys # Using percent, incorrect >>> test_color = colorsys.hsv_to_rgb(359,100,100) >>> test_color (100, -9900.0, -9900.0) # Using decimal, correct >>> test_color = colorsys.hsv_to_rgb(359,1,1) >>> test_c...
Python 3 Annotations: Type hinting a list of a specified type (PyCharm)
24,853,923
9
2014-07-20T19:08:33Z
25,320,495
21
2014-08-15T02:37:15Z
[ "python", "python-3.x", "pycharm", "type-hinting" ]
Using Python 3's function annotations, it is possible to specify the type of items contained within a homogeneous list (or other collection) for the purpose of type hinting in PyCharm and other IDEs? A pseudo-python code example for a list of int: ``` def my_func(l:list<int>): pass ``` I know it's possible using...
Answering my own question; the TLDR answer is No **Yes**. **Original Answer** As of Aug 2014, I have confirmed that it is not possible to use Python 3 type annotations to specify types within collections (ex: a list of strings). The use of formatted docstrings such as reStructuredText or Sphinx are viable alternativ...
Lists are for homogeneous data and tuples are for heterogeneous data... why?
24,854,139
4
2014-07-20T19:32:55Z
24,854,173
8
2014-07-20T19:36:52Z
[ "python" ]
I feel like this must have been asked before (probably more than once), so potential apologies in advance, but I can't find it anywhere (here or through Google). Anyway, when explaining the difference between lists and tuples in Python, the second thing mentioned, after tuples being immutable, is that lists are best f...
First of all, that guideline is only sort of true. You're free to use tuples for homogenous data and lists for heterogenous data, and there may be cases where that's a fine thing to do. One important case is if you need the collection to the hashable so you can use it as a dictionary key; in this case you must use a tu...
How to detect with python if the string contains html code?
24,856,035
3
2014-07-20T23:54:56Z
24,856,208
7
2014-07-21T00:23:41Z
[ "python", "html", "parsing", "detect" ]
How to detect either the string contains an html (can be html4, html5, just partials of html within text)? I do not need a version of HTML, but rather if the string is just a text or it contains an html. Text is typically multiline with also empty lines # Update: example inputs: html: ``` <head><title>I'm title</ti...
You can use an HTML parser, like [`BeautifulSoup`](http://www.crummy.com/software/BeautifulSoup/bs4/doc/). Note that it really tries it best to parse an HTML, even broken HTML, it can be very and not very lenient depending on the [underlying parser](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-par...
Whats the difference between 'for x in list:' and 'for x in list[:]:'
24,856,824
4
2014-07-21T02:13:04Z
24,856,843
8
2014-07-21T02:14:15Z
[ "python", "list" ]
I'm following a pygame book and both of these notations appear: ``` for x in xs: # do something with x for x in xs[:]: # do something with x ``` Do they have the same meaning?
`xs[:]` copies the list. * `for x in xs` -- Iterate over the list `xs` as-is. * `for x in xs[:]` -- Iterate over the a copy of list `xs`. One of the reasons why you'd want to "iterate over a copy" is for in-place modification of the original list. The other common reason for "copying" is atomicity of the data you're ...
SyntaxError "no viable alternative at input 'self'"
24,857,676
4
2014-07-21T04:16:13Z
24,857,691
11
2014-07-21T04:17:32Z
[ "python", "jython" ]
I have a gui.py file containing the following code: ``` from javax.swing import JFrame, JPanel, Box, JComboBox, JSpinner, JButton, JLabel, SpinnerNumberModel, WindowConstants from java.awt import BoxLayout, GridLayout class SettingsWindow: def start( self ): selected = self.combobox.selectedIndex ...
You forgot to close the parens on the previous line of code.
Remove integer values from line in a file in python
24,860,800
2
2014-07-21T08:36:48Z
24,860,848
7
2014-07-21T08:40:10Z
[ "python" ]
How to remove integer values in lines of a file in python? This is my present output ``` നട തുറന്നപ്പോള്‍ കൃഷ്ണന്‍ പുഞ്ചിരിച്ചു കൊണ്ട് നില്‍ക്കുക ആയിരുന്നു 1. എന്തോ പറയുന്ന à´...
Use regular expression to replace digit characters, e.g. ``` import re re.sub(r'\d+', '', input_str) ```
How to check if a column exists in Pandas
24,870,306
37
2014-07-21T16:43:02Z
24,870,404
73
2014-07-21T16:48:49Z
[ "python", "pandas", "dataframe" ]
Is there a way to check if a column exists in a Pandas DataFrame? Suppose that I have the following DataFrame: ``` >>> import pandas as pd >>> from random import randint >>> df = pd.DataFrame({'A': [randint(1, 9) for x in xrange(10)], 'B': [randint(1, 9)*10 for x in xrange(10)], ...
This will work: ``` if 'A' in df: ``` But for clarity, I'd probably write it as: ``` if 'A' in df.columns: ```
Python pandas : pd.options.display.mpl_style = 'default' causes graph crash
24,870,647
5
2014-07-21T17:02:10Z
24,940,507
8
2014-07-24T17:43:03Z
[ "python", "matplotlib", "pandas" ]
Everything is in the title. My graph is displayed properly when I do not set this option at the beginning of my python script, otherwise it opens the window for the graph but closes it straightback and end the run. I am using pandas 0.14.0 and matplotlib 1.3.0. Anyone already saw this ? You can see my code below if n...
Use the following: `plt.show(block=True)`
Does iterrows have performance issues?
24,870,953
6
2014-07-21T17:19:17Z
24,871,316
25
2014-07-21T17:39:48Z
[ "python", "performance", "pandas", "iteration" ]
I have noticed very poor performance when using iterrows from pandas. Is this something that is experienced by others? Is it specific to iterrows and should this function be avoided for data of a certain size (I'm working with 2-3 million rows)? [This discussion](https://github.com/pydata/pandas/issues/7683) on GitHu...
Generally, `iterrows` should only be used in very very specific cases. This is the general order of precedence for performance of various operations: ``` 1) vectorization 2) using a custom cython routine 3) apply a) reductions that can be performed in cython b) iteration in python space 4) itertuples 5) iterro...
Redis in python, how do you close the connection?
24,875,806
7
2014-07-21T22:20:42Z
24,876,042
7
2014-07-21T22:41:04Z
[ "python", "redis" ]
<https://github.com/andymccurdy/redis-py> I know in ruby we use the quit() method. I can't find anything here for python python: ``` import redis r = redis.StrictRedis(host='localhost', port=6379, db=0) r.set('foo', 'bar') print r.get('foo') #r.close() doesn't work ``` ruby ``` require "redis" redis = Redis.new re...
StrictRedis doesn't implement connection semantics itself, instead it uses a connection pool, which is available as a property of a StrictRedis instance: `S.connection_pool`. The connection\_pool object has a `disconnect` method to force an immediate disconnect of all connections in the pool if necessary, however when ...
Redis in python, how do you close the connection?
24,875,806
7
2014-07-21T22:20:42Z
24,876,863
7
2014-07-22T00:09:06Z
[ "python", "redis" ]
<https://github.com/andymccurdy/redis-py> I know in ruby we use the quit() method. I can't find anything here for python python: ``` import redis r = redis.StrictRedis(host='localhost', port=6379, db=0) r.set('foo', 'bar') print r.get('foo') #r.close() doesn't work ``` ruby ``` require "redis" redis = Redis.new re...
Just use `redis.Redis`. It uses a connection pool under the hood, so you don't have to worry about managing at that level. If you absolutely have to use a low level connection, you need to do the response handling that is normally done for you by `redis.Redis`. Here's an example of executing a single command using th...
How to count digits, letters, spaces for a string in Python
24,878,174
6
2014-07-22T02:58:33Z
24,878,232
10
2014-07-22T03:06:55Z
[ "python" ]
I am trying to make a function to detect how many digits,letter,spaces, and others for a string. Do you know what's wrong with my code? and can I improve my code to be more simple and precise? thanks! (here is the revised code) ``` def count(x): length = len(x) digit = 0 letters = 0 space = 0 othe...
Here's another option: ``` s = 'some string' numbers = sum(c.isdigit() for c in s) words = sum(c.isalpha() for c in s) spaces = sum(c.isspace() for c in s) others = len(s) - numbers - words - spaces ```
Pythonic way to delete an item completely from a dictionary
24,885,932
4
2014-07-22T11:17:50Z
24,886,035
9
2014-07-22T11:22:15Z
[ "python", "dictionary" ]
I was wondering if there is a pythonic way to delete an item completely from a dictionary. To illustrate that, consider the dict given below: ``` mydict = {'A': ['B', 'O'], 'B': ['A'], 'C': ['D', 'E', 'F', 'O'], 'D': ['E', 'C', 'F'], 'E': ['C', 'D', 'F', 'O'], 'F': ['C...
No, there are no other options here than a full set of loops, as you need to remove any `'E'` strings from your *values*: ``` {k: [i for i in v if i != 'E'] for k, v in mydict.iteritems() if k != 'E'} ``` This rebuilds your dictionary, removing the `'E'` key while we are at it, leaving you with a new dictionary that ...
Reverse repr function in Python
24,886,123
6
2014-07-22T11:26:42Z
24,886,425
14
2014-07-22T11:40:48Z
[ "python", "repr" ]
if I have a string with characters ( 0x61 0x62 0xD ), the repr function of this string will return 'ab\r'. Is there way to do reverse operation: if I have string 'ab\r'(with characters 0x61 0x62 0x5C 0x72), I need obtain string 0x61 0x62 0xD.
I think what you're looking for is [`ast.literal_eval`](https://docs.python.org/2/library/ast.html#ast.literal_eval): ``` >>> s = repr("ab\r") >>> s "'ab\\r'" >>> from ast import literal_eval >>> literal_eval(s) 'ab\r' ```
Pycharm does not show plot
24,886,625
12
2014-07-22T11:50:32Z
28,154,000
11
2015-01-26T16:11:30Z
[ "python", "matplotlib", "pycharm" ]
Pycharm does not show plot from the following code: ``` import pandas as pd import numpy as np import matplotlib as plt ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000)) ts = ts.cumsum() ts.plot() ``` What happens is that a window appears for less than a second, and then disapp...
I had the same problem. Check wether `plt.isinteractive()` is True. Setting it to 'False' helped for me. ``` plt.interactive(False) ```
Pycharm does not show plot
24,886,625
12
2014-07-22T11:50:32Z
32,619,747
8
2015-09-16T22:22:13Z
[ "python", "matplotlib", "pycharm" ]
Pycharm does not show plot from the following code: ``` import pandas as pd import numpy as np import matplotlib as plt ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000)) ts = ts.cumsum() ts.plot() ``` What happens is that a window appears for less than a second, and then disapp...
I realize this is old but I figured I'd clear up a misconception for other travelers. Setting plt.pyplot.isinteractive() to 'False' means that the plot will on be drawn on specific commands to draw (i.e. plt.pyplot.show()). Setting plt.pyplot.isinteractive() to 'True' means that every pyplot (plt) command will trigger ...
How to get Google Analytics credentials without gflags - using run_flow() instead?
24,890,146
22
2014-07-22T14:29:32Z
27,037,233
10
2014-11-20T10:28:15Z
[ "python", "google-analytics", "google-analytics-api", "google-api-python-client", "oauth2client" ]
This may take a second to explain so please bear with me: I'm working on a project for work that requires me to pull in google analytics data. I originally did this following this [link](https://developers.google.com/analytics/solutions/articles/hello-analytics-api), so after installing the API client `pip install --u...
``` from oauth2client import tools flags = tools.argparser.parse_args(args=[]) credentials = tools.run_flow(flow, storage, flags) ``` Took a bit of mucking about but climbed my way out the two traps it dropped me into: 1. have to use the argparser provided in tools 2. I had to feed args an empty list to prevent it f...
error: cannot locate an Oracle software installation
24,891,091
4
2014-07-22T15:09:31Z
26,974,073
9
2014-11-17T13:45:17Z
[ "python", "oracle", "plone", "buildout", "cx-oracle" ]
I'm working on Plone. **PRELUDE** I've installed: oracle-instantclient12.1-basic-12.1.0.1.0-1.x86\_64.rpm oracle-instantclient12.1-devel-12.1.0.1.0-1.x86\_64.rpm oracle-instantclient12.1-sqlplus-12.1.0.1.0-1.x86\_64.rpm and also cx\_Oracle. I've tested the installations and it's all ok: db connection successfully. ...
Got the same problem, background is: ``` echo $ORACLE_HOME /usr/lib/oracle/12.1/client64 ``` But: sudo env | grep ORACLE\_HOME yields nothing. The solution: ``` sudo visudo ``` Then add the line : ``` Defaults env_keep += "ORACLE_HOME" ``` As found [here](http://www.toadworld.com/platforms/oracle/b/weblog/archi...
Python Flask how to get parameters from a URL?
24,892,035
53
2014-07-22T15:49:09Z
24,892,131
95
2014-07-22T15:53:46Z
[ "python", "web-services", "flask", "url-parameters" ]
In Flask, How do I extract parameters from a URL? How can I extract named parameters from a URL using flask and python? When the user accesses this URL running on my flask app, I want the web service to be able to handle the parameters specified after the question mark: ``` http://10.1.1.1:5000/login?username=alex&pa...
Use [`request.args`](http://flask.pocoo.org/docs/api/#flask.Request.args) to get parsed contents of query string: ``` from flask import request @app.route(...) def login(): username = request.args.get('username') password = request.args.get('password') ```
Python 3.4 and 2.7: Cannot install numpy package for python 3.4
24,892,810
17
2014-07-22T16:26:58Z
24,892,867
39
2014-07-22T16:29:09Z
[ "python", "ubuntu", "numpy", "pip" ]
I am using Ubuntu 12.04 and want to use python 3.4 side by side with python 2.7. The installation of python 3.4 worked properly. However, I cannot install the numpy package for python 3 (and as a consequence I can't install scipy, pandas etc.). Using ``` sudo pip3 install numpy ``` spits out the following error: ...
You have not installed the Python 3 *development package*. Install `python3.4-dev`: ``` apt-get install python3.4-dev ``` The main package never includes the development headers; Debian (and by extension Ubuntu) package policy is to put those into a separate `-dev` package. To install `numpy` however, you need these ...
No such file or directory with Flask
24,892,927
5
2014-07-22T16:32:29Z
24,892,960
12
2014-07-22T16:34:31Z
[ "python", "flask" ]
flask question: I have my `run.py` file in the following dir ``` /Users/`<username>`/Python_stuff/flask ``` but when I run it it says ``` (api_automation)MacBook-Pro:flask `<username>`$ ./run.py -bash: ./run.py: flask/bin/python: bad interpreter: No such file or directory ``` I'm confused as to why this is happeni...
Your file starts with a [shebang](http://en.wikipedia.org/wiki/Shebang_(Unix)) telling the shell what program to load to run the script. The shebang line is the first line starting with `#!`. In this case, the shebang tells the shell to run `flask/bin/python`, and that file does not exist in your current location. Th...
Is it possible to create grouping of input cells in IPython Notebook?
24,895,714
11
2014-07-22T19:07:18Z
29,077,267
8
2015-03-16T12:50:55Z
[ "python", "ipython", "ipython-notebook" ]
When I do data analysis on IPython Notebook, I often feel the need to move up or down several adjacent input cells, for better flow of the analysis story. I'd expected that once I'd create a heading, all cells under that heading would move together if I move the heading. But this is not the case. Any way I can do thi...
I use a little-known extension, which does exactly what you want (i.e. "once I'd create a heading, all cells under that heading would move together if I move the heading"). It is part of the [Calico suite](http://calicoproject.org), but can be installed separately. More specifically, you need to install a [Calico Note...
What's the difference between python's multiprocessing and concurrent.futures?
24,896,193
6
2014-07-22T19:32:10Z
24,896,362
14
2014-07-22T19:40:06Z
[ "python", "multiprocessing", "concurrent.futures" ]
A simple way of implementing multiprocessing in python is ``` from multiprocessing import Pool def calculate(number): return number if __name__ == '__main__': pool = Pool() result = pool.map(calculate, range(4)) ``` An alternative implementation based on futures is ``` from concurrent.futures import Pr...
You actually should use the `if __name__ == "__main__"` guard with `ProcessPoolExecutor`, too: It's using `multiprocessing.Process` to populate its `Pool` under the covers, just like `multiprocessing.Pool` does, so all the same caveats regarding picklability (especially on Windows), etc. apply. I believe that `Process...