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
module' object has no attribute 'drawMatches' opencv python
20,259,025
34
2013-11-28T06:17:47Z
20,260,048
16
2013-11-28T07:23:16Z
[ "python", "opencv", "image-processing", "computer-vision" ]
I am just doing a example of feature detection in OpenCV, I have just taken a example as given below. It is giving me a error like **module' object has no attribute 'drawMatches'** I have checked the OpenCV Docs. Why do i get this error ? ``` import numpy as np import cv2 import matplotlib.pyplot as plt img1 = cv2.im...
The `drawMatches` Function is not part of the Python interface. As you can see in the [docs](http://docs.opencv.org/modules/features2d/doc/drawing_function_of_keypoints_and_matches.html#drawmatches), it is only defined for `C++` at the moment. Excerpt from the docs: ``` C++: void drawMatches(const Mat& img1, const...
module' object has no attribute 'drawMatches' opencv python
20,259,025
34
2013-11-28T06:17:47Z
21,989,251
13
2014-02-24T13:29:52Z
[ "python", "opencv", "image-processing", "computer-vision" ]
I am just doing a example of feature detection in OpenCV, I have just taken a example as given below. It is giving me a error like **module' object has no attribute 'drawMatches'** I have checked the OpenCV Docs. Why do i get this error ? ``` import numpy as np import cv2 import matplotlib.pyplot as plt img1 = cv2.im...
I know this question has an accepted answer that is correct, but if you are using OpenCV 2.4.8 and not 3.0(-dev), a workaround could be to use some functions from the included samples found in `opencv\sources\samples\python2\find_obj` ``` import cv2 from find_obj import filter_matches,explore_match img1 = cv2.imread(...
module' object has no attribute 'drawMatches' opencv python
20,259,025
34
2013-11-28T06:17:47Z
26,227,854
57
2014-10-07T02:51:13Z
[ "python", "opencv", "image-processing", "computer-vision" ]
I am just doing a example of feature detection in OpenCV, I have just taken a example as given below. It is giving me a error like **module' object has no attribute 'drawMatches'** I have checked the OpenCV Docs. Why do i get this error ? ``` import numpy as np import cv2 import matplotlib.pyplot as plt img1 = cv2.im...
I am late to the party as well, but I installed OpenCV 2.4.9 for Mac OS X, and the `drawMatches` function doesn't exist in my distribution. I've also tried the second approach with `find_obj` and that didn't work for me either. With that, I decided to write my own implementation of it that mimics `drawMatches` to the b...
Is there a way in Python to check whether an entry to os.environ is a variable or a shell function?
20,259,568
6
2013-11-28T06:55:11Z
20,259,837
7
2013-11-28T07:10:58Z
[ "python", "bash", "shell", "environment-variables" ]
With the `os` module in Python we can easily access environment variables through the dict `os.environ`. However, I found out that `os.environ` does not just hold variables, but also globally defined shell functions (e.g. from the `module` software package). Is it possible from within Python to find out whether a give...
This feature is bash-specific, so a test for an exported shell function needs to do what Bash does. Experimentation and [source code](http://git.savannah.gnu.org/cgit/bash.git/tree/variables.c#n341) show that Bash recognizes an environment variable as a shell function at startup by the presence of a `() {` prefix in it...
Is the SSE unaligned load intrinsic any slower than the aligned load intrinsic on x64_64 Intel CPUs?
20,259,694
10
2013-11-28T07:02:52Z
20,265,193
9
2013-11-28T11:38:02Z
[ "python", "c", "performance", "sse" ]
I'm considering changing some code high performance code that currently requires 16 byte aligned arrays and uses `_mm_load_ps` to relax the alignment constraint and use `_mm_loadu_ps`. There are a lot of myths about the performance implications of memory alignment for SSE instructions, so I made a small test case of wh...
You have a lot of noise in your results. I re-ran this on a Xeon E3-1230 V2 @ 3.30GHz running Debian 7, doing 12 runs (discarding the first to account for virtual memory noise) over a 200000000 array, with 10 iterations for the `i` within the benchmark functions, explicit `noinline` for the functions you provided, and ...
Inheritance of private and protected methods in Python
20,261,517
16
2013-11-28T08:54:36Z
20,261,595
23
2013-11-28T08:59:00Z
[ "python", "inheritance", "methods", "private", "protected" ]
I know, there are no 'real' private/protected methods in Python. This approach isn't meaned to hide anything, I just want to understand what Python does. ``` class Parent(object): def _protected(self): pass def __private(self): pass class Child(Parent): def foo(self): self._protec...
Names starting with a double underscore are *mangled* to protect them from clashes when inherited. Subclasses can define their own `__private()` method and these will not interfere with the same name on the parent class. Such names are considered *class private*. Mangling is done by prepending any such name with an ex...
python convert a string to arguments list
20,263,839
6
2013-11-28T10:41:26Z
20,264,077
7
2013-11-28T10:51:32Z
[ "python", "eval" ]
Can I convert a string to arguments list in python? ``` def func(**args): for a in args: print a, args[a] func(a=2, b=3) # I want the following work like above code s='a=2, b=3' func(s) ``` I know: list can, just use \*list, but list can't have an element like: a=2 and eval can only evaluate expressio...
You want a *dictionary*, not an 'argument list'. You also would be better off using [`ast.literal_eval()`](http://docs.python.org/2/library/ast.html#ast.literal_eval) to evaluate *just* Python literals: ``` from ast import literal_eval params = "{'a': 2, 'b': 3}" func(**literal_eval(params)) ``` Before you go this r...
python convert a string to arguments list
20,263,839
6
2013-11-28T10:41:26Z
20,264,114
7
2013-11-28T10:53:10Z
[ "python", "eval" ]
Can I convert a string to arguments list in python? ``` def func(**args): for a in args: print a, args[a] func(a=2, b=3) # I want the following work like above code s='a=2, b=3' func(s) ``` I know: list can, just use \*list, but list can't have an element like: a=2 and eval can only evaluate expressio...
You could massage the input string into a dictionary and then call your function with that, e.g. ``` >>> x='a=2, b=3' >>> args = dict(e.split('=') for e in x.split(', ')) >>> f(**args) a 2 b 3 ```
Rearrange columns of numpy 2D array
20,265,229
14
2013-11-28T11:39:44Z
20,265,477
25
2013-11-28T11:51:52Z
[ "python", "arrays", "numpy", "edit-in-place" ]
Is there a way to change the order of the columns in a numpy 2D array to a new and arbitrary order? For example, I have an array ``` array([[10, 20, 30, 40, 50], [ 6, 7, 8, 9, 10]]) ``` and I want to change it into, say ``` array([[10, 30, 50, 40, 20], [ 6, 8, 10, 9, 7]]) ``` by applying the per...
This is possible using fancy indexing: ``` >>> import numpy as np >>> a = np.array([[10, 20, 30, 40, 50], ... [ 6, 7, 8, 9, 10]]) >>> your_permutation = [0,4,1,3,2] >>> i = np.argsort(your_permutation) >>> i array([0, 2, 4, 3, 1]) >>> a[:,i] array([[10, 30, 50, 40, 20], [ 6, 8, 10, 9, 7]]) `...
Cython: cimport and import numpy as (both) np
20,268,228
12
2013-11-28T14:07:09Z
20,268,478
12
2013-11-28T14:21:09Z
[ "python", "numpy", "cython", "python-import" ]
In the [tutorial](http://docs.cython.org/src/tutorial/numpy.html#adding-types) of the Cython documentation, there are cimport and import statements of numpy module: ``` import numpy as np cimport numpy as np ``` I found this convention is quite popular among numpy/cython users. This looks strange for me because they...
`cimport my_module` gives access to **C** functions or attributes or even sub-modules under `my_module` `import my_module` gives access to **Python** functions or attributes or sub-modules under `my_module`. In your case: ``` cimport numpy as np ``` gives you access to Numpy C API, where you can declare array buffe...
Fastest way to compare ordered lists and count common elements *including* duplicates
20,268,415
3
2013-11-28T14:17:13Z
20,268,481
8
2013-11-28T14:21:12Z
[ "python" ]
I need to compare two lists of numbers and count how many elements of first list are there in second list. For example, ``` a = [2, 3, 3, 4, 4, 5] b1 = [0, 2, 2, 3, 3, 4, 6, 8] ``` here I should get result of 4: I should count '2' 1 time (as it happens only once in first list), '3' - 2 times, '4' - 1 time (as it hap...
You can use the intersection feature of `collections.Counter` to solve the problem in an easy and readable way: ``` >>> from collections import Counter >>> intersection = Counter( [2,3,3,4,4,5] ) & Counter( [0, 2, 2, 3, 3, 4, 6, 8] ) >>> intersection Counter({3: 2, 2: 1, 4: 1}) ``` As @Bakuriu says in the comments, t...
How do I do a "starts with" query using SQL alchemy?
20,269,260
3
2013-11-28T15:01:21Z
20,269,298
7
2013-11-28T15:03:14Z
[ "python", "sqlalchemy" ]
I am learning to use SQL alchemy to connect to a mysql database. I want to pull records from the DB that start with a given string. I know that for simple equality all I need to do is this ``` queryRes = ses.query(Table).filter(Tablee.fullFilePath == filePath).all() result = [] ``` How do I do something like this? `...
This is the pure SQL: ``` SELECT * FROM table WHERE field LIKE "string%" ``` The SQL alchemy is: ``` q = ses.query(Table).filter(Table.fullFilePath.like('path%')).all() ```
Consistently getting ImportError: Could not import settings 'myapp.settings' error
20,270,297
10
2013-11-28T15:54:08Z
20,270,490
9
2013-11-28T16:05:16Z
[ "python", "django" ]
There appears to be a number of potential solutions to this problem but nothing seems to work for me. Running `python manage.py runserver` is fine but I get the error when trying to run `django-admin.py` - with any option. I am actually trying to do a `django-admin.py dumpdata myapp`. ``` Traceback (most recent call ...
Try: ``` export PYTHONPATH=/path/to/folder/with/manage.py:$PYTHONPATH ``` It seems like it is a path problem. the path from where you call `manage.py` is usually added to PYTHONPATH, if you call django-admin.py it is not. Your application therefore does not find the `ram` module. You need to add the **folder** where ...
Using scipy's kmeans2 function in python
20,271,520
5
2013-11-28T17:06:41Z
20,277,731
9
2013-11-29T03:04:34Z
[ "python", "scipy", "k-means" ]
I found [this](http://hackmap.blogspot.in/2007/09/k-means-clustering-in-scipy.html) example for using kmeans2 algorithm in python. I can't get the following part ``` # make some z vlues z = numpy.sin(xy[:,1]-0.2*xy[:,1]) # whiten them z = whiten(z) # let scipy do its magic (k==3 groups) res, idx = kmeans2(numpy.arra...
First: ``` # make some z vlues z = numpy.sin(xy[:,1]-0.2*xy[:,1]) ``` The weirdest thing about this is that it's equivalent to: ``` z = numpy.sin(0.8*xy[:, 1]) ``` So I don't know why it's written that way. maybe there's a typo? Next, ``` # whiten them z = whiten(z) ``` *whitening* is simply normalizing the vari...
How to use pytest to check that Error is NOT raised
20,274,987
3
2013-11-28T21:29:54Z
20,275,035
10
2013-11-28T21:34:15Z
[ "python", "py.test", "raise" ]
Let's assume we have smth like that : ``` import py, pytest ERROR1 = ' --- Error : value < 5! ---' ERROR2 = ' --- Error : value > 10! ---' class MyError(Exception): def __init__(self, m): self.m = m def __str__(self): return self.m def foo(i): if i < 5: raise MyError(ERROR1) ...
A test will fail if it raises any kind of unexpected Exception. You can just invoke foo(7) and you will have tested that no MyError is raised. So, following will suffice: ``` def test_foo3(): foo(7) ``` If you really want to write an assert statement for this, you can try: ``` def test_foo3(): try: f...
working with .bmp files in python 3
20,276,458
4
2013-11-29T00:01:03Z
20,276,563
10
2013-11-29T00:17:25Z
[ "python", "image", "python-3.x", "bmp" ]
I have a bmp file. It is just a red square. I have to write a program with functions to make it have white stripes. Things I would need to do: * load the bmp file. * read and assess the bmp file. * code certain areas coordinates of the file to be colored white. * close the file * display the end product file as output...
The easy way to do this is with a third-party image-processing library like [PIL/Pillow](http://pillow.readthedocs.org/en/latest/). The code is simple enough that you could figure it out in a few minutes from the examples on the [`Image`](http://pillow.readthedocs.org/en/latest/reference/Image.html) module docs… But...
py.test does not find tests under a class
20,277,058
7
2013-11-29T01:27:19Z
20,277,099
13
2013-11-29T01:35:05Z
[ "python", "unit-testing", "pycharm", "py.test" ]
I am trying to create test classes that aren't unittest based. This method under this class ``` class ClassUnderTestTests: def test_something(self): ``` cannot be detected and run when you call py.test from the command line or when you run this test in PyCharm (it's on its own module). This ``` def test_somet...
By convention it searches for > Test prefixed test classes (without an **init** method) eg. ``` # content of test_class.py class TestClass: def test_one(self): x = "this" assert 'h' in x def test_two(self): x = "hello" assert hasattr(x, 'check') ``` See the docs [here](http:...
Fastest pairwise distance metric in python
20,277,982
7
2013-11-29T03:40:13Z
20,319,282
13
2013-12-02T00:59:10Z
[ "python", "arrays", "numpy", "scipy", "scikit-learn" ]
I have an 1D array of numbers, and want to calculate all pairwise euclidean distances. I have a method (thanks to SO) of doing this with broadcasting, but it's inefficient because it calculates each distance twice. And it doesn't scale well. Here's an example that gives me what I want with an array of 1000 numbers. `...
Neither of the other answers quite answered the question - 1 was in Cython, one was slower. But both provided very useful hints. Following up on them suggests that `scipy.spatial.distance.pdist` is the way to go. Here's some code: ``` import numpy as np import random import sklearn.metrics.pairwise import scipy.spati...
Python, Kivy and Android Game
20,280,526
10
2013-11-29T07:31:25Z
20,285,035
15
2013-11-29T11:45:14Z
[ "android", "python", "pygame", "kivy" ]
I want to create a game for Android and want to try something new. I really love python and want to use it for developing an Android game. Game is not simple, it would be 3D RPG game. I found [Kivy Crossplatform Framework](http://kivy.org/) and [PyGame](http://www.pygame.org/). I really liked both but I'm not sure if...
I don't think there is a python solution with strong 3d support at the moment, and certainly not with strong ready-rolled tools to make a complex 3d game easy. Basic pygame doesn't really have 3d support - you can see [this previous question](http://stackoverflow.com/questions/4865636/does-pygame-do-3d) for some speci...
django.request logger not propagated to root?
20,282,521
23
2013-11-29T09:37:22Z
22,336,174
46
2014-03-11T20:40:51Z
[ "python", "django", "logging" ]
Using Django 1.5.1: ``` DEBUG = False LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(message)s' }, }, 'handlers': { 'console': { 'level': 'DEBUG', ...
The solution is to prevent Django from configuring logging and handle it ourselves. Fortunately this is easy. In `settings.py`: ``` LOGGING_CONFIG = None LOGGING = {...} # whatever you want, as you already have import logging.config logging.config.dictConfig(LOGGING) ``` **UPDATE ~March 2015**: Django has [clarifie...
Loading modules in IronPython
20,284,551
4
2013-11-29T11:19:36Z
20,284,552
7
2013-11-29T11:19:36Z
[ "python", "ironpython" ]
I am confused about the two ways to import modules in IronPython. On the one hand, the tutorial documentation that comes with IronPython 2.7.4 states that you can do it using the regular `import` syntax: ``` import System from System import Xml ``` This works as I would expect. On the other hand, many resources on ...
While I was researching this question I stumbled across what I believe to be the answer (this is from trial and error alone so if I'm wrong I'd be happy to be corrected!) The `import` statement in Python is more analogous to a `using <namespace>` statement in C#. you still need to load the relevant .dll assembly. C# d...
Using multiple exceptions in python
20,287,886
3
2013-11-29T14:23:47Z
20,287,925
8
2013-11-29T14:25:54Z
[ "python", "exception", "python-3.x", "exception-handling" ]
Is there a way to use multiple exceptions in python? Like code below: ``` try: #mycode except AttributeError TypeError ValueError: #my exception ``` What I mean is how to use `AttributeError` `TypeError` `ValueError` with each other?
Use a tuple: ``` try: # mycode except (AttributeError, TypeError, ValueError): # catches any of the three exception types above ``` Quoting the [reference `try` statement documentation](http://docs.python.org/3/reference/compound_stmts.html#the-try-statement): > When an exception occurs in the `try` suite, a s...
How to use Bulk API to store the keywords in ES by using Python
20,288,770
15
2013-11-29T15:14:35Z
21,114,192
35
2014-01-14T12:58:58Z
[ "python", "elasticsearch", "elasticsearch-bulk-api" ]
I have to store some message in ElasticSearch integrate with my python program. Now what I try to store the message is: ``` d={"message":"this is message"} for index_nr in range(1,5): ElasticSearchAPI.addToIndex(index_nr, d) print d ``` That means if I have 10 message then I have to repeat my code...
``` from datetime import datetime from elasticsearch import Elasticsearch from elasticsearch import helpers es = Elasticsearch() actions = [] for j in range(0, 10): action = { "_index": "tickets-index", "_type": "tickets", "_id": j, "_source": { "any":"data" + str(j),...
How to use Bulk API to store the keywords in ES by using Python
20,288,770
15
2013-11-29T15:14:35Z
23,118,497
26
2014-04-16T19:30:16Z
[ "python", "elasticsearch", "elasticsearch-bulk-api" ]
I have to store some message in ElasticSearch integrate with my python program. Now what I try to store the message is: ``` d={"message":"this is message"} for index_nr in range(1,5): ElasticSearchAPI.addToIndex(index_nr, d) print d ``` That means if I have 10 message then I have to repeat my code...
Although @justinachen 's code helped me start with py-elasticseearch, after looking in the source code let me do a simple improvement: ``` es = Elasticsearch() j = 0 actions = [] while (j <= 10): action = { "_index": "tickets-index", "_type": "tickets", "_id": j, "_source": { ...
matplotlib iterate subplot axis array through single list
20,288,842
4
2013-11-29T15:18:13Z
20,289,530
12
2013-11-29T16:00:46Z
[ "python", "matplotlib" ]
Is there a simple/clean way to iterate an array of axis returned by subplots like ``` nrow = ncol = 2 a = [] fig, axs = plt.subplots(nrows=nrow, ncols=ncol) for i, row in enumerate(axs): for j, ax in enumerate(row): a.append(ax) for i, ax in enumerate(a): ax.set_ylabel(str(i)) ``` which even w...
The `ax` return value is a numpy array, which can be reshaped, I believe, without any copying of the data. If you use the following, you'll get a linear array that you can iterate over cleanly. ``` nrow = 1; ncol = 2; fig, axs = plt.subplots(nrows=nrow, ncols=nrow) for ax in axs.reshape(-1): ax.set_ylabel(str(i)) `...
python matplotlib filled boxplots
20,289,091
6
2013-11-29T15:33:48Z
20,291,461
22
2013-11-29T18:17:12Z
[ "python", "matplotlib", "visualization", "boxplot" ]
Does anyone know if we can plot filled boxplots in python matplotlib? I've checked <http://matplotlib.org/api/pyplot_api.html> but I couldn't find useful information about that.
The example that @Fenikso shows an example of doing this, but it actually does it in a sub-optimal way. Basically, you want to pass `patch_artist=True` to `boxplot`. As a quick example: ``` import matplotlib.pyplot as plt import numpy as np data = [np.random.normal(0, std, 1000) for std in range(1, 6)] plt.boxplot(...
python selenium import my regular firefox profile ( add-ons)
20,289,598
3
2013-11-29T16:05:12Z
20,290,667
8
2013-11-29T17:15:50Z
[ "python", "firefox", "selenium" ]
I've been trying to get my add-ons to work with my driver(driver as in webdriver.Firefox(profile)). I have no idea how to import (or if its optional at all) my regular Firefox profile. The one, i assume, contains all my add-ons. Help is needed indeed. Beside a solution (if available) an explanation to why my add-ons ...
If you do this, and set `path_to_my_profile` to where your usual profile resided, then Selenium should use your profile: ``` from selenium import webdriver from selenium.webdriver.firefox.webdriver import FirefoxProfile profile = FirefoxProfile(path_to_my_profile) driver = webdriver.Firefox(profile) ``` I've not don...
python sockets stop recv from hanging?
20,289,981
6
2013-11-29T16:27:42Z
20,290,016
10
2013-11-29T16:30:18Z
[ "python", "sockets", "pygame" ]
I am trying to create a two player game in pygame using sockets, the thing is, when I try to receive data on on this line: ``` message = self.conn.recv(1024) ``` python hangs until it gets some data. The problem with this is that is pauses the game loop when the client is not sending anything through the socket and c...
Use nonblocking mode. (See [`socket.setblocking`](http://docs.python.org/2/library/socket.html#socket.socket.setblocking).) Or check if there is data available before call `recv`. For example, using [`select.select`](http://docs.python.org/2/library/select.html#select.select): ``` r, _, _ = select.select([self.conn],...
Python: Associate for loop with a list
20,290,089
3
2013-11-29T16:34:58Z
20,290,134
8
2013-11-29T16:37:24Z
[ "python", "list", "loops", "for-loop" ]
I couldn't find any workaround for this. In my real example this will serve to associate color masks with objects. I think the best way to explain is give an example: ``` objects = ['pencil','pen','keyboard','table','phone'] colors = ['red','green','blue'] for n, i in enumerate(objects): print n,i #0 pencil ...
Use `%`: ``` for n, obj in enumerate(objects): print n, obj, colors[n % len(colors)] ``` or [`zip()`](http://docs.python.org/2/library/functions.html#zip) and [`itertools.cycle()`](http://docs.python.org/2/library/itertools.html#itertools.cycle): ``` from itertools import cycle for n, (obj, color) in enumerate(...
SQLAlchemy query, join on relationship and order by count
20,290,462
7
2013-11-29T17:00:29Z
20,291,995
7
2013-11-29T19:05:18Z
[ "python", "sqlalchemy", "flask", "flask-sqlalchemy" ]
I have two SQLAlchemy models set up as follows: ``` ############## # Post Model # ############## class Post(db.Model): id = db.Column(db.Integer, primary_key = True) title = db.Column(db.String(250)) content = db.Column(db.String(5000)) timestamp = db.Column(db.Integer) author_id = db.Column(db.Int...
The translation from raw query to Flask-SQLAlchemy is pretty much mechanical: ``` db.session.query(Post, db.func.count(Like.id)).outerjoin(Like).group_by(Post.id) ```
Find key of object with maximum property value
20,291,392
5
2013-11-29T18:11:07Z
20,291,432
7
2013-11-29T18:14:57Z
[ "python", "dictionary" ]
I have dictionary of dictionaries like this. ``` d = { 'a' : {'c' : 1, 'h' : 2}, 'b' : {'c' : 3, 'h' : 5}, 'c' : {'c' : 2, 'h' : 1}, 'd' : {'c' : 4, 'h' : 1} } ``` I need to get key of the item that has highest value of `c + h`. I know you can get key of item with highest value in case like this: ``...
``` >>> max(d, key = lambda x: d[x]['c'] + d[x]['h']) 'b' >>> d {'a': {'h': 2, 'c': 1}, 'c': {'h': 1, 'c': 2}, 'b': {'h': 5, 'c': 3}, 'd': {'h': 1, 'c': 4}} ```
Find key of object with maximum property value
20,291,392
5
2013-11-29T18:11:07Z
20,291,436
8
2013-11-29T18:15:02Z
[ "python", "dictionary" ]
I have dictionary of dictionaries like this. ``` d = { 'a' : {'c' : 1, 'h' : 2}, 'b' : {'c' : 3, 'h' : 5}, 'c' : {'c' : 2, 'h' : 1}, 'd' : {'c' : 4, 'h' : 1} } ``` I need to get key of the item that has highest value of `c + h`. I know you can get key of item with highest value in case like this: ``...
You can specify your own function for `key` which can do fancy stuff like getting the value for both `c` and `h` and add those up. For example using an inline-lambda: ``` >>> max(d, key=lambda x: d[x]['c'] + d[x]['h']) 'b' ```
Can't execute shell script from python subprocess: permission denied
20,291,543
8
2013-11-29T18:26:02Z
20,291,574
11
2013-11-29T18:28:52Z
[ "python", "shell" ]
Tried googling but couldn't find something that relates to my particular problem. I'm trying to run a shell script from python but the shell script wouldn't run because of a permission denied error. The python code I'm running is: ``` process = subprocess.Popen('run.sh', shell=True, stdout=subprocess.PIPE) process.wai...
Check your run.sh mode, if no executable flag, set it with command ``` chmod +x run.sh ```
Making py.test, coverage and tox work together: __init__.py in tests folder?
20,292,950
11
2013-11-29T20:30:08Z
22,256,532
16
2014-03-07T17:18:22Z
[ "python", "code-coverage", "py.test", "coverage.py", "tox" ]
I'm having a weird problem with `tox`, `py.test`, `coverage` and `pytest-cov`: when `py.test` with the `--cov` option is launched from `tox`, it seems to require an `__init__.py` file in the `tests` folder which is not immediately obvious. While writing this post, I have kind of solved the initial problem by adding th...
Use `--cov {envsitepackagesdir}/<your-package-name>` in tox.ini.
Python ASCII plots in terminal
20,295,646
10
2013-11-30T01:56:22Z
20,411,508
13
2013-12-05T21:49:38Z
[ "python", "matplotlib" ]
With Octave I am able to plot arrays to the terminal, for example, plotting an array with values for the function `x^2` gives this output in my terminal: ``` 10000 ++---------+-----------+----------+-----------+---------++ ++ + + + + ++ |+ : ...
As @Benjamin Barenblat pointed out, there is currently no way using matplotlib. If you really want to use a pure python library, you may check [ASCII Plotter](http://www.algorithm.co.il/blogs/ascii-plotter/). However, as I commented above, I would use [gnuplot](http://www.gnuplot.info/) as suggested e.g. in [this](http...
Printing within list comprehension in Python
20,296,311
3
2013-11-30T03:53:50Z
20,296,329
11
2013-11-30T03:58:08Z
[ "python", "list", "function", "printing", "list-comprehension" ]
I am getting a syntax error when executing the following code. I want to print within a list comprehension. As you see, I tried a different approach (commented out line) by using print(). But I think this syntax is supported in Python 3 as earlier versions of Python treat print as a statement. ``` 1 import sys 2 i...
**No** statements can appear in Python expressions. `print` is one kind of statement in Python 2, and list comprehensions are one kind of expression. Impossible. Neither can you, for example, put a `global` statement in an index expression. Note that in Python 2, you can put ``` from __future__ import print_function ...
Printing within list comprehension in Python
20,296,311
3
2013-11-30T03:53:50Z
20,296,330
8
2013-11-30T03:58:10Z
[ "python", "list", "function", "printing", "list-comprehension" ]
I am getting a syntax error when executing the following code. I want to print within a list comprehension. As you see, I tried a different approach (commented out line) by using print(). But I think this syntax is supported in Python 3 as earlier versions of Python treat print as a statement. ``` 1 import sys 2 i...
It's not a print statement in Python 3, it's a function. ``` >>> sys.version '3.4.0a4+ (default:8af2dc11464f, Nov 12 2013, 22:38:21) \n[GCC 4.7.3]' >>> [print(i) for i in range(4)] 0 1 2 3 ``` and returns: ``` [None, None, None, None] ``` And as Tim Peters said, no statements can be in comprehensions or generator e...
python: create iterator through subsets of a set for a loop
20,297,154
4
2013-11-30T06:03:41Z
20,297,167
7
2013-11-30T06:05:28Z
[ "python" ]
I have a sequence of consecutive integers, for example `[1, 2, 3]`. I'd like to create an iterator that goes through all the subsets of the set. In this case `[], [1],...,[1,2,3]`. How could I do this?
The [`itertools` documentation](http://docs.python.org/2.7/library/itertools.html#recipes) contains a recipe for this construction under the name `powerset`, if that's what you need. ``` from itertools import chain, combinations def powerset(iterable): "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1...
Merging list of dictionary in python
20,297,175
8
2013-11-30T06:07:15Z
20,297,213
13
2013-11-30T06:12:33Z
[ "python", "dictionary" ]
I have a list of dictionaries in python. Now how do i merge these dictionaries into single entity in python. Example dictionary is ``` input_dictionary = [{"name":"kishore", "playing":["cricket","basket ball"]}, {"name":"kishore", "playing":["volley ball","cricket"]}, {"name":"k...
Using [`itertools.groupby`](http://docs.python.org/2/library/itertools.html#itertools.groupby): ``` input_dictionary = [{"name":"kishore", "playing":["cricket","basket ball"]}, {"name":"kishore", "playing":["volley ball","cricket"]}, {"name":"kishore", "playing":["cricket","hock...
When are bisect_left and bisect_right not equal?
20,297,249
9
2013-11-30T06:18:04Z
20,297,253
10
2013-11-30T06:18:49Z
[ "python", "python-2.7" ]
In my understanding, bisect\_left and bisect\_right are two different ways of doing the same thing: bisection, one coming from the left and the other coming from the right. Thus, it follows that they have the same result. Under what circumstances are these two not equal, i.e. when will they return different results, as...
When the target to locate is in the list, `bisect_left`, `bisect_right` return different result. For example: ``` >>> import bisect >>> bisect.bisect_left([1,2,3], 2) 1 >>> bisect.bisect_right([1,2,3], 2) 2 ```
When are bisect_left and bisect_right not equal?
20,297,249
9
2013-11-30T06:18:04Z
20,297,273
10
2013-11-30T06:21:10Z
[ "python", "python-2.7" ]
In my understanding, bisect\_left and bisect\_right are two different ways of doing the same thing: bisection, one coming from the left and the other coming from the right. Thus, it follows that they have the same result. Under what circumstances are these two not equal, i.e. when will they return different results, as...
`bisect.bisect_left` returns the leftmost place in the sorted list to insert the given element. `bisect.bisect_right` returns the rightmost place in the sorted list to insert the given element. An alternative question is when are they equivalent? By answering this, the answer to your question becomes clear. They are ...
python dataframe pandas drop column using int
20,297,317
23
2013-11-30T06:27:11Z
20,301,769
23
2013-11-30T15:06:58Z
[ "python", "pandas", "dataframe" ]
I understand that to drop a column you use df.drop('column name', axis=1). Is there a way to drop a column using a numerical index instead of the column name?
You can delete column on `i` index like this: ``` df.drop(df.columns[i], axis=1) ``` It could work strange, if you have duplicate names in columns, so to do this you can rename column you want to delete column by new name. Or you can reassign DataFrame like this: ``` df = df.iloc[:, [j for j, c in enumerate(df.colum...
How to remove Add button in Django admin, for specific Model?
20,297,321
9
2013-11-30T06:27:27Z
21,454,467
10
2014-01-30T10:56:21Z
[ "python", "django", "django-models", "django-admin" ]
I have Django model "AmountOfBooks" that is used just as balance for Book model. If this is not good pattern for database modeling just say so. Anyway AmountOfBooks have two fields: ``` class AmountOfBooks(models.Model): book = models.ForeignKey(Book, editable=False) amount = models.PositiveIntegerFie...
It is easy, just overload has\_add\_permission method in your Admin class like so: ``` class MyAdmin(admin.ModelAdmin): def has_add_permission(self, request): return False ```
Python pandas dataframe: retrieve number of columns
20,297,332
34
2013-11-30T06:28:21Z
20,297,639
47
2013-11-30T07:11:45Z
[ "python", "pandas", "dataframe" ]
How do you programmatically retrieve the number of columns in a pandas dataframe? I was hoping for something like: ``` df.num_columns ```
Like so: ``` import pandas as pd df = pd.DataFrame({"pear": [1,2,3], "apple": [2,3,4], "orange": [3,4,5]}) len(df.columns) 3 ```
Python pandas dataframe: retrieve number of columns
20,297,332
34
2013-11-30T06:28:21Z
20,304,311
19
2013-11-30T18:56:56Z
[ "python", "pandas", "dataframe" ]
How do you programmatically retrieve the number of columns in a pandas dataframe? I was hoping for something like: ``` df.num_columns ```
Alternative: ``` df.shape[1] ``` (`df.shape[0]` is the number of rows)
pip installing data files to the wrong place
20,298,729
4
2013-11-30T09:41:07Z
20,370,738
7
2013-12-04T08:46:37Z
[ "python", "pip", "packaging", "easy-install", "package-managers" ]
The source for the package is [here](https://github.com/captn3m0/hackertray/) I'm installing the package from the index via: ``` easy_install hackertray pip install hackertray ``` `easy_install` installs `images/hacker-tray.png` to the following folder: ``` /usr/local/lib/python2.7/dist-packages/hackertray-1.8-py2....
Don't use `data_files` with relative paths. Actually, don't use `data_files` at all, unless you make sure the target paths are absolute ones properly generated in a cross-platform way insted of hard coded values. Use `package_data` instead: ``` setup( # (...) package_data={ "hackertray.data": [ ...
django_openid_auth TypeError openid.yadis.manager.YadisServiceManager object is not JSON serializable
20,301,338
6
2013-11-30T14:22:16Z
20,412,655
11
2013-12-05T23:05:33Z
[ "python", "django", "django-openid-auth" ]
I used `django_openid_auth` on my project and it worked quite alright for some time. But today, I tested the application and came across this exception: ``` Environment: Request Method: GET Request URL: http://localhost:7777/google/login/ Django Version: 1.6 Python Version: 2.7.3 Installed Applications: ('django.co...
This seems to be a known bug: <https://bugs.launchpad.net/django-openid-auth/+bug/1252826> However, as of now, there doesn't seem to be a fix. The workaround, as per [this comment](https://bugs.launchpad.net/django-openid-auth/+bug/1252826/comments/2), is [to reset the serializer](http://bazaar.launchpad.net/~strycor...
What's the difference between 'coding=utf8' and '-*- coding: utf-8 -*-'?
20,301,920
11
2013-11-30T15:24:00Z
20,302,074
15
2013-11-30T15:39:28Z
[ "python", "python-2.7", "utf-8", "character-encoding" ]
Is there any difference between using ``` #coding=utf8 ``` and ``` # -*- coding: utf-8 -*- ``` What about ``` # encoding: utf-8 ```
There is no difference; Python recognizes all 3. It looks for the pattern: ``` coding[:=]\s*([-\w.]+) ``` on the first two lines of the file (which also must start with a `#`). That's the literal text 'coding', followed by either a colon or an equals sign, followed by optional whitespace. Any word, dash or dot chara...
Why Python function len is faster than __len__ method?
20,302,558
8
2013-11-30T16:21:05Z
20,302,670
23
2013-11-30T16:31:23Z
[ "python" ]
In Python, `len` is a function to get the length of a collection by calling an object's `__len__` method: ``` def len(x): return x.__len__() ``` So I would expect direct call of `__len__()` to be at least that fast as `len()`. ``` import timeit setup = ''' ''' print (timeit.Timer('a="12345"; x=a.__len__()', se...
The builtin `len()` function does not look up the `.__len__` attribute. It looks up the [`tp_as_sequence` pointer](http://docs.python.org/2/c-api/typeobj.html#tp_as_sequence), which in turn has a [`sq_length` attribute](http://docs.python.org/2/c-api/typeobj.html#PySequenceMethods.sq_length). The `.__len__` attribute ...
TypeError: Type str doesn't support the buffer API # find method?
20,302,756
8
2013-11-30T16:39:23Z
20,302,895
14
2013-11-30T16:50:06Z
[ "python", "python-3.x" ]
Here is my input: ``` <!DOCTYPE html> .......... <div class="content"> <div class="stream-item-header"> <a class="account-group js-account-group js-action-profile js-user-profile-link js-nav" href="https://twitter.com/jimcramer" data-user-id="14216123"> <img class="avatar js-action-profile-avatar" ...
You can't use `bytes.find()` to find a `str` object inside a `bytes` object(since they're different types, a `str` can't be inside `bytes`). You can, however, look for a bytes object inside it. This should work: ``` start_link = input.find(b' <p class="js-tweet-text tweet-text" ') ``` Btw, you should be using an ht...
Django Rest Framework ImageField
20,303,252
18
2013-11-30T17:20:17Z
20,304,647
14
2013-11-30T19:25:45Z
[ "python", "django", "django-rest-framework" ]
I can not save the image in this ImageField. **when sending data back:** ``` { "image": ["No file was submitted. Check the encoding type on the form."] } ``` **model.py** ``` class MyPhoto(models.Model): owner = models.ForeignKey('auth.User', related_name='image') image = models.ImageField(upload_to='ph...
You seem to be missing the `request.FILES` argument to the serializer constructor in the your `post` and `put` handlers. ``` serializer = PhotoSerializer(data=request.DATA, files=request.FILES) ```
Django Rest Framework ImageField
20,303,252
18
2013-11-30T17:20:17Z
28,136,161
19
2015-01-25T12:04:15Z
[ "python", "django", "django-rest-framework" ]
I can not save the image in this ImageField. **when sending data back:** ``` { "image": ["No file was submitted. Check the encoding type on the form."] } ``` **model.py** ``` class MyPhoto(models.Model): owner = models.ForeignKey('auth.User', related_name='image') image = models.ImageField(upload_to='ph...
I think you can use `request.data` instead after `django rest framework 3.0`. The usage of `request.DATA` and `request.FILES` is now pending deprecation in favor of a single `request.data` attribute that contains all the parsed data. You can check it from [here](http://www.django-rest-framework.org/topics/3.0-announce...
how can I use the python imaging library to create a bitmap
20,304,438
4
2013-11-30T19:08:25Z
20,304,716
7
2013-11-30T19:32:25Z
[ "python", "bitmap", "python-imaging-library" ]
I have a 2d list in python, and I want to make a graphical pic of the data. Maybe a n by m column grid where each square is a different color of grey depending on the value in my 2d list. However, I can't seem to figure out how to create images using PIL. This is some of the stuff I've been messing with: ``` def crea...
this is from <http://en.wikibooks.org/wiki/Python_Imaging_Library/Editing_Pixels> ``` import Image img = Image.new( 'RGB', (255,255), "black") # create a new black image pixels = img.load() # create the pixel map for i in range(img.size[0]): # for every pixel: for j in range(img.size[1]): pixels[i,j] ...
loading cookies from selenium to mechanize with cookielib
20,306,110
6
2013-11-30T21:55:23Z
20,313,832
7
2013-12-01T15:32:48Z
[ "python", "cookies", "selenium", "mechanize", "cookielib" ]
I am trying to login to a website with selenium, then transfer the cookie to mechanize. I have successfully logged in with selenium and saved its session cookie to a variable. The problem comes when trying to load the cookie with cookielib. Relevant coding: ``` . . #loging in to website with selenium . cookie = brows...
if you print the cookies collected by Selenium and compare it to a cookie collected by mechanize/cookielib you will notice they use different formats. To overcome this you can try something like this (you may need to modify it a bit, to fit your needs. but you get the general idea): ``` cj = cookielib.LWPCookieJar() ...
How do I integrate Ajax with Django applications?
20,306,981
153
2013-11-30T23:41:00Z
20,307,569
389
2013-12-01T01:02:55Z
[ "python", "ajax", "django" ]
I am new to Django and pretty new to Ajax. I am working on a project where I need to integrate the two. I believe that I understand the principles behind them both, but have not found a good explanation of the two together. Could someone give me a quick explanation of how the codebase must change with the two of them ...
Even though this isn't entirely in the SO spirit, I love this question, because I had the same trouble when I started so I'll give you a quick guide. Obviously you don't understand the principles behind them (don't take it as an offense, but if you did you wouldn't be asking). Django is server-side. It means, say a cl...
How do I integrate Ajax with Django applications?
20,306,981
153
2013-11-30T23:41:00Z
28,341,345
10
2015-02-05T10:17:57Z
[ "python", "ajax", "django" ]
I am new to Django and pretty new to Ajax. I am working on a project where I need to integrate the two. I believe that I understand the principles behind them both, but have not found a good explanation of the two together. Could someone give me a quick explanation of how the codebase must change with the two of them ...
Further from yuvi's excellent answer, I would like to add a small specific example on how to deal with this within Django (beyond any js that will be used). The example uses `AjaxableResponseMixin` and assumes an Author model. ``` import json from django.http import HttpResponse from django.views.generic.edit import ...
Django: built-in password reset views
20,307,473
7
2013-12-01T00:49:52Z
20,307,530
9
2013-12-01T00:57:37Z
[ "python", "django", "authentication", "passwords", "reset" ]
I am following the documentation and I am getting a NoReverseMatch error when I click on the page to restart my password. NoReverseMatch at /resetpassword/ Reverse for 'password\_reset\_done' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] **urls.py:** ``` (r'^resetpassword/passwords...
Add the url name to the entry in your `urls.py` for `password_reset_done`: ``` (r'^resetpassword/passwordsent/$', 'django.contrib.auth.views.password_reset_done', name='password_reset_done'), ``` Internally, the `password_reset` view uses `reverse('password_reset_done')` to look up where to send the user after resett...
Python: is "Except keyerror" faster than "if key in dict"?
20,308,567
6
2013-12-01T03:57:20Z
20,308,657
16
2013-12-01T04:12:57Z
[ "python", "exception", "dictionary", "keyerror" ]
Edit 2: It was suggested that this is a copy of a similar question. I'd disagree since my question focuses on speed, while the other question asks what is more "readable" or "better" (without defining better). While the questions are similar, there is a big difference in the discussion/answers given. > EDIT: > I reali...
Your claim is absolutely false depends on the input. If you have a diverse set of keys, and hits the `except` block often, the performance is not good. If the `try` block is dominant the `try/except` idiom can be performant on smaller lists. Here is a benchmark showing several ways to do the same thing: ``` from __f...
How to pad a string to a fixed length with spaces in Python?
20,309,255
8
2013-12-01T06:05:35Z
20,309,306
20
2013-12-01T06:13:30Z
[ "python", "string", "format" ]
I'm sure this is covered in plenty of places, but I don't know the exact name of the action I'm trying to do so I can't really look it up. I've been reading an official Python book for 30 minutes trying to find out how to do this. Problem: I need to put a string in a certain length "field". For example, if the name f...
You can use the [`ljust` method on strings](http://docs.python.org/2/library/stdtypes.html#str.ljust). ``` >>> name = 'John' >>> name.ljust(15) 'John ' ``` Note that if the name is longer than 15 characters, `ljust` won't truncate it. If you want to end up with exactly 15 characters, you can slice the resul...
How to pad a string to a fixed length with spaces in Python?
20,309,255
8
2013-12-01T06:05:35Z
20,309,356
21
2013-12-01T06:20:52Z
[ "python", "string", "format" ]
I'm sure this is covered in plenty of places, but I don't know the exact name of the action I'm trying to do so I can't really look it up. I've been reading an official Python book for 30 minutes trying to find out how to do this. Problem: I need to put a string in a certain length "field". For example, if the name f...
This is super simple with `format`: ``` >>> a = "John" >>> "{:<15}".format(a) 'John ' ```
How to call a function from another file in Python?
20,309,456
89
2013-12-01T06:34:10Z
20,309,470
109
2013-12-01T06:36:16Z
[ "python", "file", "function", "import" ]
I've seen this topic here covered numerous times, but none of the answers I've seen seem to work for me, so I'll try to be as specific to my problem as possible. Set\_up: I have a .py file for each function I need to use in a program. In this program, I need to call the function from the external files. I've tried: ...
No need to add `file.py` while importing. Just write `from file import function`, and then call the function using `function(a, b)`. The reason why this may not work, is because `file` is one of Python's core modules, so I suggest you change the name of your file. Note, that if you're trying to import functions from `...
How to call a function from another file in Python?
20,309,456
89
2013-12-01T06:34:10Z
20,309,473
26
2013-12-01T06:37:14Z
[ "python", "file", "function", "import" ]
I've seen this topic here covered numerous times, but none of the answers I've seen seem to work for me, so I'll try to be as specific to my problem as possible. Set\_up: I have a .py file for each function I need to use in a program. In this program, I need to call the function from the external files. I've tried: ...
First of all you do not need a `.py` if you have a file `a.py` and inside you have some functions: ``` def b(): # something return 1 def c(): # something return 2 ``` And you want to import them in `z.py` you have to write ``` from a import b, c ```
How to split string with limit by the end in Python
20,312,851
6
2013-12-01T13:52:50Z
20,312,856
10
2013-12-01T13:53:26Z
[ "python", "string", "split" ]
I have the following string: `"hello.world.foo.bar"` and I want to split (with the `"."` as delimiter, and only want to get two elemets starting by the end) this in the following: `["hello.world.foo", "bar"]` How can I accomplish this? exist the limit by the end?
Use [`str.rsplit`](http://docs.python.org/2/library/stdtypes#str.rsplit) specifying maxsplit (the second argument) as `1`: ``` >>> "hello.world.foo.bar".rsplit('.', 1) # <-- 1: maxsplit ['hello.world.foo', 'bar'] ```
Given this same piece of code, why is the python version 100x+ slower than C?
20,314,049
2
2013-12-01T15:55:49Z
20,314,143
19
2013-12-01T16:05:04Z
[ "python", "c", "performance", "code-translation" ]
I'm doing project euler Q14. > Which starting number, under one million, produces the longest collatz chain? I was very surprised to see someone who could get a result in 0.7sec. More surprised when I see it is merely a naive brute force solution. I was skeptical as I spent so much time to optimize my python version...
**In short** - it's not slower, it's just stuck. The while loop in your python version is an infinite loop - your indentation doesn't include changing `j` so you'll never exit it. The fact that your program didn't just "take longer" but actually got completely stuck should have been a hint (don't feel bad though, I on...
Find Arc/Circle equation given three points in space (3D)
20,314,306
5
2013-12-01T16:20:26Z
20,315,063
7
2013-12-01T17:30:32Z
[ "python", "numpy", "geometry" ]
Given 3 points in space (3D): A = (x1, y1, z1), B = (x2, y2, z2) C = (x3, y3, z3); then how to find the center and radius of the circle (arc) that passes through these three points, i.e. find circle equation? Using Python and Numpy here is my initial code ``` import numpy as np A = np.array([x1, y1, z1]) B = np.array(...
There are two issues with your code. The first is in the naming convention. For all the formulas you are using to hold, the side of length `a` has to be the one opposite the point `A`, and similarly for `b` and `B` and `c` and `C`. You can solve that by computing them as: ``` a = np.linalg.norm(C - B) b = np.linalg.n...
How to properly and securely handle cookies and sessions in Python's Flask?
20,314,921
8
2013-12-01T17:18:18Z
20,314,952
13
2013-12-01T17:21:19Z
[ "python", "security", "session", "cookies", "flask" ]
In application I am writing at the moment I've been saving in users browser a cookie that had session ID stored inside, and that ID was used as a reference to a session stored in the database containing user's information including the fact if the user is logged in properly. I wanted to review the security of my solut...
# The background ## Method #1 An easy and safe way to handle sessions is to do the following: * Use a session cookie that contains a session ID (a random number). * Sign that session cookie using a secret key (to prevent tempering — this is what [itsdangerous](http://pythonhosted.org/itsdangerous/) does). * Store ...
Multiplying a string by zero
20,317,255
5
2013-12-01T21:05:05Z
20,317,267
15
2013-12-01T21:07:00Z
[ "python", "string", "computer-science" ]
In terms of computer science, and specifically in Python, how to explain that multiplying a string by zero (which is an int) produces an empty string? ``` >>> 'hello' * 0 >>> '' ```
Follow the sequence: ``` 'hello' * 3 == 'hellohellohello' 'hello' * 2 == 'hellohello' 'hello' * 1 == 'hello' 'hello' * 0 == ? ``` An empty string is the only thing that continues the sequence, so it's either that or undefined. It makes sense as "zero repetitions of the string `'hello'`". This sequence is a way of lo...
run python script directly from command line
20,318,158
5
2013-12-01T22:36:59Z
20,318,301
11
2013-12-01T22:53:33Z
[ "python", "bash", "shell", "shebang", "env" ]
``` #!/usr/bin/env python ``` I put that at the top of a script. I've seen that should make the script runnable from the command line without the need for `python programname.py`. Unless I'm misunderstanding I should be able to use `programname.py` as long as I have the above line at the top of the script. Is this cor...
# Universal running of Python scripts You can pretty much universally run without the shebang (`#!`) with ``` python myscript.py ``` Or nearly equivalently (it places the current directory on your path and executes the module named `myscript`) **(preferably do this!)**: ``` python -m myscript ``` from the command ...
Why in numpy `nan == nan` is False while nan in [nan] is True?
20,320,022
15
2013-12-02T02:43:52Z
20,320,060
16
2013-12-02T02:47:57Z
[ "python", "numpy", null ]
While the first part of the question (which is in the title) has been answered a few times before (i.e., [Why is NaN not equal to NaN?](http://stackoverflow.com/questions/10034149/why-is-nan-not-equal-to-nan)), I don't see why the second piece works the way it does (inspired by this question [How to Check list containi...
`nan` not being equal to `nan` is part of the definition of `nan`, so that part's easy. As for `nan in [nan]` being True, that's because identity is tested before equality for containment in lists. You're comparing the same two objects. If you tried the same thing with two *different* `nan`s, you'd get False: ``` >>...
Debugging Apache/Django/WSGI Bad Request (400) Error
20,321,673
48
2013-12-02T05:49:30Z
20,618,753
89
2013-12-16T19:03:03Z
[ "python", "django", "apache", "mod-wsgi", "django-wsgi" ]
My simple Django app worked fine in debug mode (`manage.py runserver`), and works under WSGI+Apache on my dev box, but when I pushed to EC2 I began receiving intermittent (10-80% of the time) errors of `Bad Request (400)` for any URLs I try to view (whether in my app or in the Django admin. Where can I find debug info...
Add the ALLOWED\_HOSTS setting to your settings.py like so... ``` ALLOWED_HOSTS = [ '.example.com', # Allow domain and subdomains '.example.com.', # Also allow FQDN and subdomains ] ``` I had this same problem and found the answer [here in the docs](https://docs.djangoproject.com/en/1.7/ref/settings/#allowed-...
Downsample a 1D numpy array
20,322,079
13
2013-12-02T06:24:58Z
20,322,495
15
2013-12-02T06:57:50Z
[ "python", "numpy", "scipy", "signal-processing", "resampling" ]
I have a 1-d numpy array which I would like to downsample. Any of the following methods are acceptable if the downsampling raster doesn't perfectly fit the data: * overlap downsample intervals * convert whatever number of values remains at the end to a separate downsampled value * interpolate to fit raster basically ...
In the simple case where your array's size is divisible by the downsampling factor (`R`), you can `reshape` your array, and take the mean along the new axis: ``` import numpy as np a = np.array([1.,2,6,2,1,7]) R = 3 a.reshape(-1, R) => array([[ 1., 2., 6.], [ 2., 1., 7.]]) a.reshape(-1, R).mean(axis=1) =...
Any Functional Programming method of traversing a nested dictionary?
20,324,830
9
2013-12-02T09:29:06Z
20,324,938
19
2013-12-02T09:35:04Z
[ "python", "dictionary", "functional-programming" ]
I am trying to find a better way to implement this: ``` d = {"a": {"b": {"c": 4}}} l = ["a", "b", "c"] for x in l: d = d[x] print (d) # 4 ``` I am learning functional programming so I am just trying random example that come to my head :)
Use [`reduce()`](http://docs.python.org/2/library/functions.html#reduce): ``` reduce(dict.__getitem__, l, d) ``` or better still, using [`operator.getitem()`](http://docs.python.org/2/library/operator.html#operator.getitem): ``` from operator import getitem reduce(getitem, l, d) ``` Demo: ``` >>> d = {"a": {"b": ...
Can I arrange 3 equally sized subplots in a triangular shape?
20,324,864
6
2013-12-02T09:31:03Z
20,325,013
14
2013-12-02T09:39:23Z
[ "python", "matlab", "matplotlib" ]
To make this clear, I will use an 4x4 grid to show where and how large I want my subplots. The counting goes like this: ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ``` I want the top plot to be placed over 2, 3, 6, and 7. The two bottom plots are then 9, 10, 13, 14 and 11, 12, 15, 16, respectively. In Matlab, y...
Use `subplot` with range: ``` img = imread('cameraman.tif'); figure; subplot(4,4,[2 3 6 7]);imshow(img); subplot(4,4,[9 10 13 14]);imshow(img); subplot(4,4,[11 12 15 16]);imshow(img); ``` And the result is: ![ ](http://i.stack.imgur.com/N63mx.jpg) --- A `matplotlib` solution based on [`subplot2grid`](http://matplo...
Error installing Python Image Library using pip on Mac OS X 10.9
20,325,473
78
2013-12-02T10:01:29Z
20,334,915
28
2013-12-02T18:07:48Z
[ "python", "osx", "pip" ]
I want to install PIL on Mavericks using pip but get this error. ``` _imagingft.c:73:10: fatal error: 'freetype/fterrors.h' file not found #include <freetype/fterrors.h> ^ 1 error generated. error: command 'cc' failed with exit status 1 ``` My Command Line Tools are installed and up to date and every hint I ...
I've solved this problem with this symlink: ``` ln -s /usr/local/Cellar/freetype/2.5.1/include/freetype2 /usr/local/include/freetype ``` I have freetype already installed via homebrew too.
Error installing Python Image Library using pip on Mac OS X 10.9
20,325,473
78
2013-12-02T10:01:29Z
20,387,016
30
2013-12-04T22:03:37Z
[ "python", "osx", "pip" ]
I want to install PIL on Mavericks using pip but get this error. ``` _imagingft.c:73:10: fatal error: 'freetype/fterrors.h' file not found #include <freetype/fterrors.h> ^ 1 error generated. error: command 'cc' failed with exit status 1 ``` My Command Line Tools are installed and up to date and every hint I ...
With macports, the solution that worked for me: ``` sudo port install freetype sudo ln -s /opt/local/include/freetype2 /opt/local/include/freetype ``` And then re-run the PIL build process.
Error installing Python Image Library using pip on Mac OS X 10.9
20,325,473
78
2013-12-02T10:01:29Z
20,481,633
208
2013-12-09T21:55:28Z
[ "python", "osx", "pip" ]
I want to install PIL on Mavericks using pip but get this error. ``` _imagingft.c:73:10: fatal error: 'freetype/fterrors.h' file not found #include <freetype/fterrors.h> ^ 1 error generated. error: command 'cc' failed with exit status 1 ``` My Command Line Tools are installed and up to date and every hint I ...
Instead of symlinking to a specific version of freetype2, do this: ``` ln -s /usr/local/include/freetype2 /usr/local/include/freetype ``` This saves you the trouble of recreating the symlink whenever you upgrade freetype2.
calling ipython from a virtualenv
20,327,621
23
2013-12-02T11:51:15Z
26,482,258
23
2014-10-21T08:34:49Z
[ "python", "virtualenv", "ipython" ]
I understand that ipython is not [virtualenv-aware](http://rodesia.org/2012/09/04/making-ipython-virtualenv-aware/) and that the most logical solution to this is to install ipython in each virtualenv seperately using ``` pip install ipython ``` So far so good. One thing I noticed is that if the system-wide copy of ip...
`alias ipy="python -c 'import IPython; IPython.terminal.ipapp.launch_new_instance()'"` This is a great way of always being sure that the ipython instance always belongs to the virtualenv's python version. This works only on ipython >2.0. [Source](https://coderwall.com/p/xdox9a)
ValueError: unconverted data remains: 02:05
20,327,937
6
2013-12-02T12:07:31Z
20,328,136
7
2013-12-02T12:17:14Z
[ "python", "date", "datetime", "python-2.7" ]
I have some dates in a json files, and I am searching for those who corresponds to today's date : ``` import os import time from datetime import datetime from pytz import timezone input_file = file(FILE, "r") j = json.loads(input_file.read().decode("utf-8-sig")) os.environ['TZ'] = 'CET' for item in j: lt = ti...
The value of `st` at `st = datetime.strptime(st, '%A %d %B')` line something like `01 01 2013 02:05` and the `strptime` can't parse this. Indeed, you get an hour in addition of the date... You need to add `%H:%M` at your strptime.
Count number of values in python
20,328,610
3
2013-12-02T12:40:43Z
20,328,673
10
2013-12-02T12:43:32Z
[ "python", "list", "count" ]
I have a list look like this: ``` Lux = ([ 0 0 0 0 0 120 120 120 120 120 240 240 240 240 240 0 0 0 0 0 120 120 120 120 120]) ``` I want to count how many zeros I have, but only from the 14 place, and let say until 16 place The answer will be in this case 2. I know that count function count all the appearance. How can...
Use `list.count` and `slicing`: ``` >>> lis = [0, 0, 0, 0, 0, 120, 120, 120, 120, 120, 240, 240, 240, 240, 240, 0, 0, 0, 0, 0, 120, 120, 120, 120, 120] >>> lis[14:].count(0) 5 >>> lis[14:17].count(0) 2 ``` Another option is to use `sum` and a generator expression, but this is going to be very slow compared to `list.c...
Argparse argument generated help, 'metavar' with choices
20,328,931
4
2013-12-02T12:57:22Z
20,335,589
8
2013-12-02T18:48:33Z
[ "python", "argparse" ]
When using an argument (optional and positional both have this *problem*) with the keyword `choices`, the generated help output shows those choices. If that same argument also includes a `metavar` keyword, the list of choices is omitted from the generated output. What I had in mind, was to show the `metavar` in the `...
You can add the choices to the help text. ``` parser=argparse.ArgumentParser() parser.add_argument('-f',metavar="TEST",choices=('a','b','c'), help='choices, {%(choices)s}') print parser.format_help() ``` produces: ``` usage: stack20328931.py [-h] [-f TEST] optional arguments: -h, --help show this help messag...
Having trouble clearing tinymce textarea with selenium
20,329,216
4
2013-12-02T13:13:17Z
20,334,755
7
2013-12-02T17:57:34Z
[ "python", "selenium" ]
In selenium I want to enter some text into the tinymce text area, but I'm having trouble clearing the textarea before putting in my text. The clear function that usually work well to remove preexisting texts in a "normal" input area dosn't seem to work for a tinymce textarea
If you show your current attempts it would be possible to fix them. Have you inspected the page's source code to make sure you're in the right frame and selecting the right element? Generally speaking you can clear a textbox/textarea/whatnot by seleniums clear() function, like this: ``` 1. driver.find_element_by_id("...
How to calculate mean in python?
20,329,746
5
2013-12-02T13:40:54Z
20,329,778
9
2013-12-02T13:42:49Z
[ "python", "list", "average", "mean" ]
I have a list that I want to calculate the average(mean?) of the values for her. When I do this: ``` import numpy as np #in the beginning of the code goodPix = ['96.7958', '97.4333', '96.7938', '96.2792', '97.2292'] PixAvg = np.mean(goodPix) ``` I'm getting this error code: ``` ret = um.add.reduce(arr, axis=axis, d...
Convert you list from strings to np.float: ``` >>> gp = np.array(goodPix, np.float) >>> np.mean(gp) 96.906260000000003 ```
Cannot find the file specified when using subprocess.call('dir', shell=True) in Python
20,330,385
12
2013-12-02T14:14:57Z
20,335,954
10
2013-12-02T19:10:29Z
[ "python", "shell", "python-2.7", "path", "subprocess" ]
In a 64-bit system with 32 bit python 2.7 installed I am trying to do the following: ``` import subprocess p = subprocess.call('dir', shell=True) print p ``` But this gives me: ``` Traceback (most recent call last): File "test.py", line 2, in <module> p = subprocess.call('dir', shell=True) File "C:\Python27\...
I think you may have a problem with your `COMSPEC` environment variable: ``` >>> import os >>> os.environ['COMSPEC'] 'C:\\Windows\\system32\\cmd.exe' >>> import subprocess >>> subprocess.call('dir', shell=True) (normal output here) >>> os.environ['COMSPEC'] = 'C:\\nonexistent.exe' >>> subprocess.call('dir', shel...
How to write a custom estimator in sklearn and use cross-validation on it?
20,330,445
7
2013-12-02T14:17:53Z
20,352,065
7
2013-12-03T13:07:01Z
[ "python", "scikit-learn" ]
I would like to check the prediction error of a new method trough cross-validation. I would like to know if I can pass my method to the cross-validation function of sklearn and in case how. I would like something like sklearn.cross\_validation(cv=10).mymethod. I need also to know how to define mymethod should it be a...
The answer also lies in sklearn's [documentation](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.cross_val_score.html#sklearn.model_selection.cross_val_score). You need to define two things: * an estimator that implements the `fit(X, y)` function, `X` being the matrix with inputs and `y` bei...
Python Joint Distribution of N Variables
20,332,750
3
2013-12-02T16:15:20Z
20,338,214
7
2013-12-02T21:28:17Z
[ "python", "numpy", "distribution", "probability-density" ]
So I need to calculate the joint probability distribution for N variables. I have code for two variables, but I am having trouble generalizing it to higher dimensions. I imagine there is some sort of pythonic vectorization that could be helpful, but, right now my code is very C like (and yes I know that is not the righ...
Check out the function `numpy.histogramdd`. This function can compute histograms in arbitrary numbers of dimensions. If you set the parameter `normed=True`, it returns the bin count divided by the bin hypervolume. If you'd prefer something more like a probability mass function (where everything sums to 1), just normali...
cimport gives fatal error: 'numpy/arrayobject.h' file not found
20,333,128
2
2013-12-02T16:33:07Z
20,348,414
8
2013-12-03T10:21:45Z
[ "python", "numpy", "cython" ]
I'm trying to teach myself Cython but having problems accessing numpy. The problems seem to be when I use 'cimport'. For example when importing the following function: ``` cimport numpy def cy_sum(x): cdef numpy.ndarray[int, ndim=1] arr = x cdef int i, s = 0 for i in range(arr.shape[0]): s += ...
Ok, as has been pointed out above, similar questions have been asked before. Eg: [Make distutils look for numpy header files in the correct place](http://stackoverflow.com/questions/2379898/make-distutils-look-for-numpy-header-files-in-the-correct-place). I got my code to work by using a setup file with the line ``` i...
pandas dataframe TypeError
20,333,435
8
2013-12-02T16:47:03Z
20,333,894
33
2013-12-02T17:08:57Z
[ "python", "pandas", "typeerror", "dataframe" ]
I have the following structure to my dataFrame: ``` Index: 1008 entries, Trial1.0 to Trial3.84 Data columns (total 5 columns): CHUNK_NAME 1008 non-null values LAMBDA 1008 non-null values BETA 1008 non-null values HIT_RATE 1008 ...
`&` has higher precedence than `==`. Write: ``` my_df.ix[(my_df.CHUNK_NAME==chunks[0])&(my_df.LAMBDA==lam_beta[0][0])] ^ ^ ^ ^ ```
pycallgraph with pycharm does not work
20,333,530
8
2013-12-02T16:51:33Z
23,987,195
10
2014-06-02T04:05:01Z
[ "python", "pycharm" ]
I'm using mac os x and trying to setup pycallgraph. Ive installed pycallgraph with pip and graphviz with homebrew. Everything works from shell. But not from pycharm. ``` from pycallgraph import PyCallGraph from pycallgraph import Config from pycallgraph import GlobbingFilter from pycallgraph.output import Graphviz...
It worked for me in MacOS by installing **graphviz** using `brew install graphviz` and then testing **dot** by using **dot -v**. You can also download pkg from here: <http://www.graphviz.org/Download_macos.php>
PyCharm logging output colours
20,333,674
9
2013-12-02T16:58:45Z
21,880,915
8
2014-02-19T12:46:40Z
[ "python", "google-app-engine", "logging", "pycharm" ]
I'm using PyCharm to develop a GAE app in Mac OS X. Is there any way to display colours in the run console of PyCharm? I've set a [handler](http://xsnippet.org/359377/) to output colours in ansi format. Then, I've added the handler: ``` LOG = logging.getLogger() LOG.setLevel(logging.DEBUG) for handler in LOG.handlers...
Pycharm doesn't support that feature natively, however you can download Grep console plugin: <http://plugins.jetbrains.com/plugin/7125?pr=pycharm> and set the colors as you like here's a screenshot: <http://plugins.jetbrains.com/files/7125/screenshot_14104.png> I hope it helps somewhat :) although it doesn't provide ...
django app: Cannot assign "''": "ImageText.link" must be a "Link" instance
20,334,029
2
2013-12-02T17:15:15Z
20,346,355
7
2013-12-03T08:40:03Z
[ "python", "django", "django-models", "django-cms", "django-1.5" ]
I'm building an app for my Django 1.5.1 and Django-cms installation. The app meant to permit to upload an image linked to an URL. My code : **cms\_plugins.py** ``` from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from cms.plugins.text.widgets.wymeditor_widget import WYMEditor from dja...
The problem here has not much to do with your schema specifically but with how django handles `OneToOne` relationships. When you subclass `CMSPlugin`, django creates an implicit `OneToOne` relationship from your model to the `CMSPlugin` and vice versa. This being the case, imagine the following scenario: I have a pl...
Should I define __all__ even if I prefix hidden functions and variables with underscores in modules?
20,334,880
2
2013-12-02T18:05:32Z
20,334,936
7
2013-12-02T18:08:37Z
[ "python" ]
From the perspective of an external user of the module, are both necessary? From my understanding, by correctly prefix hidden functions with an underscore it essentially does the same thing as explicitly define `__all__`, but I keep seeing developers doing both in their code. Why is that?
When importing from a module with `from modulename import *` names starting with underscores are indeed skipped. However, a module rarely contains *only* public API objects. Usually you've made imports to support the code as well, and *those* names are global in the module as well. Without `__all__`, those names would...
Python: How to keep repeating a program until a specific input is obtained?
20,337,489
6
2013-12-02T20:45:37Z
20,337,522
13
2013-12-02T20:47:35Z
[ "python", "loops", "for-loop", "while-loop" ]
I have a function that evaluates input, and I need to keep asking for their input and evaluating it until they enter a blank line. How can I set that up? ``` while input != '': evaluate input ``` I thought of using something like that, but it didn't exactly work. Any help?
There are two ways to do this. First is like this: ``` while True: # Loop continuously inp = raw_input() # Get the input if inp == "": # If it is a blank line... break # ...break the loop ``` The second is like this: ``` inp = raw_input() # Get the input while inp ...
Cleanest way to hide every nth tick label in matplotlib colorbar?
20,337,664
12
2013-12-02T20:57:03Z
20,341,184
15
2013-12-03T01:31:51Z
[ "python", "matplotlib" ]
The labels on my horizontal colorbar are too close together and I don't want to reduce text size further: ``` cbar = plt.colorbar(shrink=0.8, orientation='horizontal', extend='both', pad=0.02) cbar.ax.tick_params(labelsize=8) ``` ![horizontal colorbar with bad labels](http://i.stack.imgur.com/t52fd.png) I'd like to ...
For loop the ticklabels, and call `set_visible()`: ``` for label in cbar.ax.xaxis.get_ticklabels()[::2]: label.set_visible(False) ```
In Python how can one tell if a module comes from a C extension?
20,339,053
4
2013-12-02T22:18:03Z
20,339,418
8
2013-12-02T22:45:17Z
[ "python", "python-c-extension", "extension-modules" ]
What is the correct or most robust way to tell from Python if an imported module comes from a [C extension](http://docs.python.org/2/extending/extending.html) as opposed to a pure Python module? This is useful, for example, if a Python package has a module with both a pure Python implementation and a C implementation, ...
First, I don't think this is at all useful. It's very common for modules to be pure-Python wrappers around a C extension module—or, in some cases, pure-Python wrappers around a C extension module if it's available, or a pure Python implementation if not. For some popular third-party examples: `numpy` is pure Python,...
Python and lmfit: How to fit multiple datasets with shared parameters?
20,339,234
6
2013-12-02T22:33:42Z
20,341,726
9
2013-12-03T02:28:05Z
[ "python", "parameters", "curve-fitting", "lmfit" ]
I would like to use the [lmfit](http://lmfit.github.io/lmfit-py/ "lmfit") module to fit a function to a variable number of data-sets, with some shared and some individual parameters. Here is an example generating Gaussian data, and fitting to each data-set individually: ``` import numpy as np import matplotlib.pyplot...
I think you're most of the way there. You need to put the data sets into an array or structure that can be used in a single, global objective function that you give to minimize() and fits all data sets with a single set of Parameters for all the data sets. You can share this set among data sets as you like. Expanding o...
pandas create named columns in dataframe from dict
20,340,844
11
2013-12-03T00:56:01Z
20,341,058
10
2013-12-03T01:19:14Z
[ "python", "pandas", "typeerror", "dataframe" ]
I have a dictionary object of the form: ``` my_dict = {id1: val1, id2: val2, id3: val3, ...} ``` I want to create this into a dataframe where I want to name the 2 columns 'business\_id' and 'business\_code'. I tried: ``` business_df = DataFrame.from_dict(my_dict,orient='index',columns=['business_id','business_code...
You can iterate through the items: ``` In [11]: pd.DataFrame(list(my_dict.iteritems()), columns=['business_id','business_code']) Out[11]: business_id business_code 0 id2 val2 1 id3 val3 2 id1 val1 ```
Where is "The Zen of Python" located in the CPython source code?
20,341,264
5
2013-12-03T01:39:40Z
20,341,303
7
2013-12-03T01:43:38Z
[ "python" ]
You of course know what happens when you `import this`, but **where is the Zen located in the interpreter source code**? I'd searched the string *"Readability counts"* with both `ag` and `grep -r` in a local clone but haven't found anything relevant. Searching `"zen of python" site:hg.python.org` in Google gives me n...
There's a file called [`this.py`](http://hg.python.org/cpython/file/c3896275c0f6/Lib/this.py) in the Lib directory. The string is encoded using [ROT-13](http://en.wikipedia.org/wiki/ROT-13) so it's not searchable. The code to decode it is in the file.
Which is a better practice - global import or local import
20,346,189
5
2013-12-03T08:31:13Z
20,346,290
11
2013-12-03T08:36:34Z
[ "python", "django", "import" ]
I am developing an app in django and I had a doubt if importing a library at the global level has any impact over the memory or performance than importing at the local ( per-function) level. If it is imported per function or view, the modules that are needed alone are imported saving space right? Or are there any negat...
You surely must have noticed that almost all Python code does the imports at the top of the file. There's a reason for that: the overhead of importing is minimal, and the likelihood is that you will be importing the code at some point during the process lifetime anyway, so you may as well get it out of the way. The on...
How to generate a random graph given the number of nodes and edges?
20,347,020
3
2013-12-03T09:13:58Z
20,352,801
8
2013-12-03T13:43:37Z
[ "python", "random", "igraph" ]
I am using python with igraph library: ``` from igraph import * g = Graph() g.add_vertices(4) g.add_edges([(0,2),(1,2),(3,2)]) print g.betweenness() ``` I would like to generate a random graph with 10000 nodes and 100000 edges. The edges can be random. Please suggest a way to have random edges (using numpy.random.ran...
Do you have to use `numpy.random.rand`? If not, just use [`Graph.Erdos_Renyi`](http://igraph.sourceforge.net/doc/python/igraph.GraphBase-class.html#Erdos_Renyi), which lets you specify the number of nodes and edges directly: ``` g = Graph.Erdos_Renyi(n=10000, m=100000) ```
Can't install numpy 1.8 with python 2.7 under windows 7
20,347,252
2
2013-12-03T09:25:28Z
27,174,374
8
2014-11-27T15:45:04Z
[ "python", "numpy" ]
I have donwloaded numpy 1.8 zip version and I have python 2.7 and windows 7. When I do ``` python setup.py install ``` I get: ``` Q:\Users\user\Desktop\numpy-1.8.0>python setup.py install Running from numpy source directory. non-existing path in 'numpy\\distutils': 'site.cfg' F2PY Version 2 blas_opt_info: blas_mkl_i...
Had the same problem, solved by installing MS Visual C++ Compiler for Python 2.7: [From here](http://www.microsoft.com/en-us/download/details.aspx?id=44266)