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
get bins coordinates with hexbin in matplotlib
12,951,065
6
2012-10-18T09:11:16Z
13,754,416
13
2012-12-06T23:19:38Z
[ "python", "matplotlib", "histogram" ]
I use matplotlib's method `hexbin` to compute 2d histograms on my data. But I would like to get the coordinates of the centers of the hexagons in order to further process the results. I got the values using `get_array()` method on the result, but I cannot figure out how to get the bins coordinates. I tried to compute...
I think this works. ``` from __future__ import division import numpy as np import math import matplotlib.pyplot as plt def generate_data(n): """Make random, correlated x & y arrays""" points = np.random.multivariate_normal(mean=(0,0), cov=[[0.4,9],[9,10]],size=int(n)) return points if __name__ ==...
Writing Python bindings for C++ code that use OpenCV
12,957,492
11
2012-10-18T14:51:16Z
12,972,689
22
2012-10-19T10:50:55Z
[ "c++", "python", "boost", "opencv", "boost-python" ]
I'm trying to write a python wrapper for some C++ code that make use of OpenCV but I'm having difficulties returning the result, which is a OpenCV C++ Mat object, to the python interpreter. I've looked at OpenCV's source and found the file cv2.cpp which has conversions functions to perform conversions to and fro betwe...
I solved the problem so I thought I'll share it here with others who may have the same problem. Basically, to get rid of the segmentation fault, I need to call numpy's import\_array() function. The "high level" view for running C++ code from python is this: Suppose you have a function `foo(arg)` in python that is a ...
how to use hough circles in cv2 with python?
12,957,577
8
2012-10-18T14:54:52Z
12,957,885
16
2012-10-18T15:11:18Z
[ "python", "opencv", "circle", "hough-transform" ]
I have the following code and I want to detect the circle. ``` img = cv2.imread("act_circle.png") gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) circles = cv2.HoughCircles(gray,cv2.CV_HOUGH_GRADIENT) ``` it looks like it does not have the attribute and the error is the following ``` 'module' object has no attr...
`CV_HOUGH_GRADIENT` belongs to the `cv` module, so you'll need to import that: ``` import cv2.cv as cv ``` and change your function call to ``` circles = cv2.HoughCircles(gray,cv.CV_HOUGH_GRADIENT) ```
(matplotlib) Plot yerr/xerr as shaded region rather than error bars
12,957,582
31
2012-10-18T14:20:47Z
12,958,534
32
2012-10-18T15:44:22Z
[ "python", "matplotlib" ]
In matplotlib, how do I plot error as a shaded region rather than error bars? For example: ![](http://qhwiki.originlab.com/~originla/howto/images/c/cc/Error_Bars_with_Fill_Area_01.png) Rather than ![](http://www.dplot.com/examples/error-bars.gif)
Ignoring the smooth interpolation between points in your example graph (that would require doing some manual interpolation, or just have a higher resolution of your data), you can use `pylab.fill_between()`: ``` from matplotlib import pyplot as pl import numpy as np x = np.linspace(0, 30, 30) y = np.sin(x/6*np.pi) er...
(matplotlib) Plot yerr/xerr as shaded region rather than error bars
12,957,582
31
2012-10-18T14:20:47Z
13,157,955
42
2012-10-31T12:27:51Z
[ "python", "matplotlib" ]
In matplotlib, how do I plot error as a shaded region rather than error bars? For example: ![](http://qhwiki.originlab.com/~originla/howto/images/c/cc/Error_Bars_with_Fill_Area_01.png) Rather than ![](http://www.dplot.com/examples/error-bars.gif)
This is basically the [same answer provided by Evert](http://stackoverflow.com/a/12958534/17523), but extended to show-off some cool options of `fill_between` ![enter image description here](http://i.stack.imgur.com/pqbee.png) ``` from matplotlib import pyplot as pl import numpy as np pl.clf() pl.hold(1) x = np.lin...
Matplotlib placement of text e.g. suptitle inside the frame
12,957,801
12
2012-10-18T15:06:44Z
12,958,839
14
2012-10-18T16:01:09Z
[ "python", "matplotlib", "title" ]
So far i have placed my suptitles above the frame, like this: ![enter image description here](http://i.stack.imgur.com/j55xB.png) How can i get the suptitles from **above** the frame **into the frame?** So far i have a solution that just prints a text and sets it on the right position with computing xlim and ylim. H...
Your solution using `text` is also my go-to solution. However, you don't need to compute the position based on xlim and ylim. If you set `transform=ax.transAxes` the coordinates for positioning the text are taken as being relative to the axes bounding box (0,0 being the lower left corner). Like so: ``` data = range(1,...
Matplotlib placement of text e.g. suptitle inside the frame
12,957,801
12
2012-10-18T15:06:44Z
12,958,847
15
2012-10-18T16:01:31Z
[ "python", "matplotlib", "title" ]
So far i have placed my suptitles above the frame, like this: ![enter image description here](http://i.stack.imgur.com/j55xB.png) How can i get the suptitles from **above** the frame **into the frame?** So far i have a solution that just prints a text and sets it on the right position with computing xlim and ylim. H...
Have you considered `axes.title`? You can see the documentation for it [here](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.title). You can also pass x and y coordinates as keyword arguments `ax.title("my title", x=0.5, y=0.6)`. Hope this helps.
Tastypie: How can I fill the resource without database?
12,958,702
6
2012-10-18T15:54:21Z
12,959,375
9
2012-10-18T16:31:08Z
[ "python", "django", "foursquare", "tastypie" ]
I want to grab some information from Foursquare , add some fields and return it via django-tastypie. UPDATE: ``` def obj_get_list(self, request=None, **kwargs): near = '' if 'near' in request.GET and request.GET['near']: near = request.GET['near'] if 'q' in request.GET and request.GET['q']: ...
`ModelResource` is only suitable when you have ORM Model behind the resource. In other cases you should use `Resource`. This subject is discussed in `ModelResource` description, mentioning when it is suitable and when it is not: <http://django-tastypie.readthedocs.org/en/latest/resources.html#why-resource-vs-modelreso...
Remove all inline styles using BeautifulSoup
12,959,308
6
2012-10-18T16:27:10Z
12,959,554
19
2012-10-18T16:41:09Z
[ "python", "css", "beautifulsoup", "inline" ]
I'm doing some HTML cleaning with BeautifulSoup. Noob to both Python & BeautifulSoup. I've got tags being removed correctly as follows, based on an answer I found elsewhere on Stackoverflow: ``` [s.extract() for s in soup('script')] ``` But how to remove inline styles? For instance the following: ``` <p class="autho...
You don't need to parse any CSS if you just want to remove it all. BeautifulSoup provides a way to remove entire attributes like so: ``` for tag in soup(): for attribute in ["class", "id", "name", "style"]: del tag[attribute] ``` Also, if you just want to delete entire tags (and their contents), you don't...
What is "_csv" in Python?
12,959,968
13
2012-10-18T17:04:50Z
12,959,997
12
2012-10-18T17:06:46Z
[ "python", "csv", "symbols", "built-in" ]
In attempting to read the source code for the `csv.py` file (as a guide to implementing my own `writer` class in another context) I found that much of the functionality in that file is, in turn, imported from something called `_csv`: ``` from _csv import Error, __version__, writer, reader, register_dialect, \ ...
`_csv` is the C "backbone" of the `csv` module. Its source is in [`Modules/_csv.c`](http://hg.python.org/cpython/file/tip/Modules/_csv.c). You can find the compiled version of this module from the Python command prompt with: ``` >>> import _csv >>> _csv <module '_csv' from '/usr/lib/python2.6/lib-dynload/_csv.so'> ```...
What is "_csv" in Python?
12,959,968
13
2012-10-18T17:04:50Z
12,960,069
12
2012-10-18T17:10:49Z
[ "python", "csv", "symbols", "built-in" ]
In attempting to read the source code for the `csv.py` file (as a guide to implementing my own `writer` class in another context) I found that much of the functionality in that file is, in turn, imported from something called `_csv`: ``` from _csv import Error, __version__, writer, reader, register_dialect, \ ...
Not to disagree with larsmans answer. There is an official explanation of the module naming convention in [PEP8](http://www.python.org/dev/peps/pep-0008/): > When an extension module written in C or C++ has an accompanying Python module that provides a higher level (e.g. more object oriented) interface, the C/C++ mod...
python explicitly not passing optional parameter
12,960,012
3
2012-10-18T17:07:57Z
12,960,156
8
2012-10-18T17:16:01Z
[ "python", "optional-parameters" ]
imagine the following scenario: ``` class A: def __init__(self, arg1=3, arg2=5): pass def createA(arg1=None, arg2=None): if arg1 is None: if arg2 is None: a = A() else: a = A(arg2=arg2) else: if arg2 is None: a = A(arg1=arg1) else...
``` def create_A(arg1=None, arg2=None): kwargs = {} if arg1 is not None: kwargs['arg1'] = arg1 if arg1 is not None: kwargs['arg2'] = arg2 return A(**kwargs) ``` or maybe even ``` def create_A(**kwargs): return A(**kwargs) ```
how to get all the keys in a 2d dict python
12,960,019
4
2012-10-18T17:08:11Z
12,960,093
9
2012-10-18T17:12:21Z
[ "python", "dictionary" ]
I have a dictionary of form: ``` d = {123:{2:1,3:1}, 124:{3:1}, 125:{2:1},126:{1:1}} ``` So, lets look into 2nd degree keys.. ``` 123--> 2,3 124--> 3 125--> 2 126--> 1 ``` So total number of unique 2nd order keys are: ``` 1,2,3 ``` Now, i want to modify this dict as ``` d = {123:{1:0,2:1,3:1}, 124:{1:0,2:0,3:1}...
``` keyset = set() for k in d: keyset.update(d[k]) for k in d: for kk in keyset: d[k].setdefault(kk, 0) ```
How do I make Django admin URLs accessible to localhost only?
12,960,212
2
2012-10-18T17:19:27Z
12,960,354
10
2012-10-18T17:28:46Z
[ "python", "django", "apache", "wsgi", "django-wsgi" ]
What is the simplest way to make Django /admin/ urls accessible to localhost only? Options I have thought of: * Seperate the admin site out of the project (somehow) and run as a different virtual host (in Apache2) * Use a proxy in front of the hosting (Apache2) web server * Restrict the URL in Apache within WSGI some...
Id go for apache configuration: ``` <Location /admin> Order Deny, Allow Deny from all Allow from 127.0.0.1 </Location> ``` HTH.
pandas read_csv index_col=None not working
12,960,574
12
2012-10-18T17:44:44Z
12,961,158
14
2012-10-18T18:19:30Z
[ "python", "pandas" ]
I am going through the 'Python for Data Analysis' book and having trouble in the 'Example: 2012 Federal Election Commision Database' section reading the data to a DataFrame. The trouble is that one of the columns of data is always being set as the index column, even when the index\_col argument is set to None. Here is...
## Quick Answer Use **index\_col=False** instead of index\_col=None when you have delimiters at the end of each line to turn off index column inference and discard the last column. ## More Detail Juniper may be on to something but after looking at the data, there is a comma at the end of each line. And this quote: ...
Trouble in parsing date using dateutil
12,960,614
10
2012-10-18T17:47:25Z
12,988,841
14
2012-10-20T13:20:27Z
[ "python", "python-2.7", "python-dateutil" ]
I am using python-dateutil for parsing a date from a string: ``` import dateutil.parser print dateutil.parser.parse('some null string', fuzzy=True).date() 2012-10-18 print dateutil.parser.parse('some 31 Oct 2012 string', fuzzy=True).date() 2012-10-31 ``` What I am expecting is for `dateutil.parser.parse('some null st...
See the [dateutil docs](http://labix.org/python-dateutil#head-c0e81a473b647dfa787dc11e8c69557ec2c3ecd2), specifically the parse function (emphasizes mine): > Additionally, the following keyword arguments are available: > > **default** > If given, this must be a datetime instance. Any fields missing in the parsed date ...
How to stop Python unittest from printing test docstring?
12,962,772
9
2012-10-18T20:01:33Z
12,962,854
11
2012-10-18T20:06:23Z
[ "python", "unit-testing" ]
I've noticed that, when my Python unit tests contain documentation at the top of the function, sometimes the framework prints them in the test output. Normally, the test output contains one test per line: ``` <test name> ... ok ``` If the test has a docstring of the form ``` """ test that so and so happens """ ``` ...
The *first* line of the docstring is used; the responsible method is [`TestCase.shortDescription()`](http://docs.python.org/library/unittest.html#unittest.TestCase.shortDescription), which you can override in your testcases: ``` class MyTests(unittest.TestCase): # .... def shortDescription(self): retu...
Python subprocess Popen.communicate() equivalent to Popen.stdout.read()?
12,965,023
24
2012-10-18T22:59:05Z
12,965,273
33
2012-10-18T23:27:56Z
[ "python", "subprocess", "wait", "popen", "communicate" ]
Very specific question (I hope): **What are the differences between the following three codes?** (I expect it to be only that the first does not wait for the child process to be finished, while the second and third ones do. But I need to be sure this is the *only* difference...) I also welcome other remarks/suggestio...
If you look at the source for `subprocess.communicate()`, it shows a perfect example of the difference: ``` def communicate(self, input=None): ... # Optimization: If we are only using one pipe, or no pipe at # all, using select() or threads is unnecessary. if [self.stdin, self.stdout, self.stderr].coun...
matplotlib scatter plot colour as function of third variable
12,965,075
20
2012-10-18T23:05:31Z
12,965,761
23
2012-10-19T00:33:05Z
[ "python", "matplotlib", "scatter" ]
I would like to know how to make matplotlib's scatter function colour points by a third variable. Questions [gnuplot linecolor variable in matplotlib?](http://stackoverflow.com/questions/8945699/gnuplot-linecolor-variable-in-matplotlib) and [Matplotlib scatterplot; colour as a function of a third variable](http://stac...
This works for me, using matplotlib 1.1: ``` import numpy as np import matplotlib.pyplot as plt x = np.arange(10) y = np.sin(x) plt.scatter(x, y, marker='+', s=150, linewidths=4, c=y, cmap=plt.cm.coolwarm) plt.show() ``` Result: ![enter image description here](http://i.stack.imgur.com/Hb7on.png) Alternatively, fo...
How to get JSON from webpage into Python script
12,965,203
40
2012-10-18T23:20:37Z
12,965,253
35
2012-10-18T23:26:28Z
[ "python", "json" ]
Got the following code in one of my scripts: ``` # # url is defined above. # jsonurl = urlopen(url) # # While trying to debug, I put this in: # print jsonurl # # Was hoping text would contain the actual json crap from the URL, but seems not... # text = json.loads(jsonurl) print text ``` What I want to do is get the...
I'll take a guess that you actually want to get data from the URL: ``` jsonurl = urlopen(url) text = json.loads(jsonurl.read()) # <-- read from it ``` Or, check out [JSON decoder](http://docs.python-requests.org/en/latest/user/quickstart/#json-response-content) in the [requests](http://docs.python-requests.org/en/lat...
How to get JSON from webpage into Python script
12,965,203
40
2012-10-18T23:20:37Z
12,965,254
76
2012-10-18T23:26:29Z
[ "python", "json" ]
Got the following code in one of my scripts: ``` # # url is defined above. # jsonurl = urlopen(url) # # While trying to debug, I put this in: # print jsonurl # # Was hoping text would contain the actual json crap from the URL, but seems not... # text = json.loads(jsonurl) print text ``` What I want to do is get the...
Get data from the URL and then call `json.loads` e.g. ``` import urllib, json url = "http://maps.googleapis.com/maps/api/geocode/json?address=googleplex&sensor=false" response = urllib.urlopen(url) data = json.loads(response.read()) print data ``` The output would result in something like this: ``` { "results" : ...
How can I install Python modules programmatically / through a Python script?
12,966,147
13
2012-10-19T01:30:18Z
13,016,849
13
2012-10-22T17:46:47Z
[ "python", "pip", "distutils", "easy-install", "maya" ]
Can I download and install Python modules from PyPi strictly inside a script, without using a shell **at all**? I use a non-standard Python environment, Autodesk Maya's Python interpreter. This does not come with "easy\_install," and there is no "shell," only a python script interpreter invoked by the main Maya execut...
Installing easy\_install for Maya on windows. 1. Download [ez\_setup.py](http://peak.telecommunity.com/dist/ez_setup.py). 2. open windows cmd elevated (start, type *cmd*, *rmb* click on it ->run as administrator) 3. change the cmd directory to x:\maya install dir\bin * example: cd c:\Program Files\MayaXX\bin 4. exe...
make distutils in Python automatically find packages
12,966,216
30
2012-10-19T01:42:13Z
12,966,345
10
2012-10-19T02:00:31Z
[ "python", "distutils", "setup.py" ]
When describing a python package in `setup.py` in `distutils` in Python, is there a way to make it so automatically get every directory that has a `__init__.py` in it and include that as a subpackage? ie if the structure is: ``` mypackage/__init__.py mypackage/a/__init__.py mypackage/b/__init__.py ``` I want to avoi...
The easiest way (that I know of) is to use [`pkgutil.walk_packages`](http://docs.python.org/library/pkgutil.html#pkgutil.walk_packages) to yield the packages: ``` from distutils.core import setup from pkgutil import walk_packages import mypackage def find_packages(path=__path__, prefix=""): yield prefix pref...
make distutils in Python automatically find packages
12,966,216
30
2012-10-19T01:42:13Z
14,376,861
80
2013-01-17T10:22:49Z
[ "python", "distutils", "setup.py" ]
When describing a python package in `setup.py` in `distutils` in Python, is there a way to make it so automatically get every directory that has a `__init__.py` in it and include that as a subpackage? ie if the structure is: ``` mypackage/__init__.py mypackage/a/__init__.py mypackage/b/__init__.py ``` I want to avoi...
I would recommend using the find\_packages() function available with [setuptools](http://pypi.python.org/pypi/setuptools) such as: ``` from setuptools import setup, find_packages ``` and then do ``` packages=find_packages() ```
Decoding JSON with Python and storing nested object
12,966,308
2
2012-10-19T01:55:23Z
12,966,420
7
2012-10-19T02:11:00Z
[ "python", "json" ]
I am trying to decode the following JSON file with Python: ``` {"node":[ { "id":"12387", "ip":"172.20.0.1", "hid":"213", "coord":{"dist":"12","lat":"-9.8257","lon":"65.0880"}, "status":{"speed":"90","direction":"N"}, "ts":"12387"} ] } ``` By using: ``` json_data=open('sampleJSON') jdata ...
You can use a recursive function to print it all out. This could be improved, but here is the idea: ``` import json json_data = open('data.json') jdata = json.load(json_data) def printKeyVals(data, indent=0): if isinstance(data, list): print for item in data: printKeyVals(item, indent...
Preserving original doctype and declaration of an lxml.etree parsed xml
12,966,488
10
2012-10-19T02:21:17Z
12,966,853
8
2012-10-19T03:14:19Z
[ "python", "lxml", "doctype", "xml-declaration" ]
I'm using python's lxml and I'm trying to read an xml document, modify and write it back but the original doctype and xml declaration disappears. I'm wondering if there's an easy way of putting it back in whether through lxml or some other solution?
The following will include the DOCTYPE and the XML declaration: ``` from lxml import etree from StringIO import StringIO tree = etree.parse(StringIO('''<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE root SYSTEM "test" [ <!ENTITY tasty "eggs"> ]> <root> <a>&tasty;</a> </root> ''')) docinfo = tree.docinf...
Managing connection to redis from Python
12,967,107
23
2012-10-19T03:47:47Z
12,973,514
39
2012-10-19T11:41:17Z
[ "python", "connection", "redis" ]
I'm using `redis-py` in my python application to store simple variables or lists of variables in a Redis database, so I thought it would be better to create a connection to the redis server everytime I need to save or retrieve a variable as this is not done very often and don't want to have a permanent connection that ...
Python uses a reference counter mechanism to deal with objects, so at the end of the blocks, the my\_server object will be automatically destroyed and the connection closed. You do not need to close it explicitly. Now this is not how you are supposed to manage Redis connections. Connecting/disconnecting for each opera...
Serve up pdf as a download with Pyramid, ningx, X-Accel-Redirect Header
12,967,734
4
2012-10-19T05:09:30Z
12,967,877
7
2012-10-19T05:26:36Z
[ "python", "nginx", "pyramid" ]
I want a user to be able to click a link like this: `<a href="/download?file=123">download</a>` Have a Pyramid 1.2.7 app handle the view like this ``` @view_config(route_name='download') def download(request): file_id = request.GET['file'] filename = get_filename(file_id) headers = request.response.heade...
If you want to indicate that a web browser should download a resource rather than display it, try using the `Content-Disposition` header [as described in RFC 6266](http://tools.ietf.org/html/rfc6266). For example, the following response header will tell the browser to download the file: ``` Content-Disposition: attach...
Mongo ObjectID: "can't compare offset-naive and offset-aware datetimes" even with pytz
12,968,565
7
2012-10-19T06:29:53Z
13,455,055
18
2012-11-19T13:42:58Z
[ "python", "mongodb", "datetime", "timezone", "pymongo" ]
I'm trying to prettify ObjectIDs timestamp with [py-pretty](http://pypi.python.org/pypi/py-pretty) but it keeps giving me a TypeError: ``` TypeError: can't compare offset-naive and offset-aware datetimes ``` even after I attempt convert the timestamp to a timezone unaware UTC date with Pytz. This is the code I'm tryi...
I'm not a py-pretty expert, but your code doesn't convert timezone-aware date to timezone unaware date. It just takes the current date (using `now`) in the utc timezone (so timezone aware). You can naively convert tz-aware datetime to tz-unaware one by using: ``` your_datetime_var.replace(tzinfo=None) ``` in your c...
sys.exit() does not terminate my program
12,969,767
2
2012-10-19T07:54:10Z
12,969,853
10
2012-10-19T07:59:34Z
[ "python" ]
I want to exit a Python script if my try succeeds. My code just doesn't exit and continues to execute the rest of the script. If I run `python myscript.py --help`, I need the script to exit. If I run `python myscript.py` I need do execute the `except` part. ``` try: if sys.argv[1] == '--help' or sys.argv[1] == '-...
As the [docs say](http://docs.python.org/library/sys.html#sys.exit), `sys.exit` in fact does nothing but raising `SystemExit` and you're intercepting it in the end. You either call `sys.exit` outside of try-except or catch it explicitly and then re-raise.
Can you explain this recursive "n choose k" code to me?
12,970,897
2
2012-10-19T09:07:56Z
12,987,884
10
2012-10-20T11:19:21Z
[ "python", "recursion" ]
Here is the code to a subset problem with arguments n and k. n represents the total number of students and k represents the amount of the students I want to get out of n. The code attempts to give the number of possible combinations of pulling k number of students out of n number of students. ``` def subset(n, k): ...
The recursion is based on a simple observation, for which I will give a combinatorial argument, as to why it is true, rather than a mathematical proof through formulae. Whenever you choose `k` elements out of `n`, there are two cases: 1. You choose element `#n` 2. You don't choose element `#n` Since these events are...
Is python package virtualenv necessary when I use python 3.3?
12,971,443
25
2012-10-19T09:38:39Z
14,096,957
17
2012-12-31T03:00:41Z
[ "python", "virtualenv", "python-3.3" ]
I was looking in [Cristoph Gohlke's python packages](http://www.lfd.uci.edu/~gohlke/pythonlibs/) and I noticed that there is a package Virtualenv for Python 3.3. Since there is a package *venv* in the standard python library v3.3, I was wondering if there is an advantage to install this package separately. Edit: From...
Generally, the virtualenv package is not required when using python3.3 or later, since it was incorporated into the standard library via [PEP 405](http://www.python.org/dev/peps/pep-0405/). As you note in the question, there are some relatively small differences between the latest versions of virtualenv and the venv pa...
Sorting list by an attribute that can be None
12,971,631
10
2012-10-19T09:48:31Z
12,971,697
10
2012-10-19T09:52:48Z
[ "python", "python-3.x", "2to3" ]
I'm trying to sort a list of objects using `my_list.sort(key=operator.attrgetter(attr_name))` but if any of the list items has `attr = None` instead of `attr = 'whatever'`, then I get a `TypeError: unorderable types: NoneType() < str()` In Py2 it wasn't a problem. How do I handle this in Py3?
The ordering comparison operators are stricter about types in Python 3, as described [here](http://docs.python.org/release/3.0.1/whatsnew/3.0.html#ordering-comparisons): > The ordering comparison operators (<, <=, >=, >) raise a TypeError > exception when the operands don’t have a meaningful natural ordering. Pytho...
Sorting list by an attribute that can be None
12,971,631
10
2012-10-19T09:48:31Z
26,348,624
10
2014-10-13T20:47:43Z
[ "python", "python-3.x", "2to3" ]
I'm trying to sort a list of objects using `my_list.sort(key=operator.attrgetter(attr_name))` but if any of the list items has `attr = None` instead of `attr = 'whatever'`, then I get a `TypeError: unorderable types: NoneType() < str()` In Py2 it wasn't a problem. How do I handle this in Py3?
For a general solution, you can define an object that compares less than any other object: ``` from functools import total_ordering @total_ordering class MinType(object): def __le__(self, other): return True def __eq__(self, other): return (self is other) Min = MinType() ``` Then use a sort...
PorterStemmer doesn't seem to work
12,974,045
7
2012-10-19T12:10:59Z
12,974,301
9
2012-10-19T12:27:40Z
[ "python", "nltk", "porter-stemmer" ]
I am new to python and practising with examples from book. Can anyone explain why when I am trying to stem some example with this code nothing is changed? ``` >>> from nltk.stem import PorterStemmer >>> stemmer=PorterStemmer() >>> stemmer.stem('numpang wifi stop gadget shopping') 'numpang wifi stop gadget shopping' ...
try this: ``` res = ",".join([ stemmer.stem(kw) for kw in 'numpang wifi stop gadget shopping'.split(" ")]) ``` the problem is that, probably, that stemmer works on single words. your string has no "root" word, while the single word "shopping" has the root "shop". so you'll have to compute the stemming separately edi...
Python multiprocessing, passing an object reference containig a semaphore
12,974,414
5
2012-10-19T12:35:25Z
12,978,919
10
2012-10-19T16:55:39Z
[ "python", "multiprocessing" ]
I've a scenario like this: I've created an object of the class element containing a semaphore. ``` import multiprocessing as mpr class Element(object): def __init__(self): self.sem = mpr.Semaphore() self.xyz = 33 def fun( ch ): a = ch.recv() print( a[0] ) print( a[1].xyz ) a[1].xy...
I don't think you understood how the `multiprocessing` module works. When you send something through the pipe, it gets pickled and then unpickled in the subprocess. This means that the subprocess actually has a *copy* of the original object! That's why the change is "lost". Adding a semaphore wont change anything. If...
Accessing the Quick Panel in a Sublime Text 2 Plugin
12,976,008
6
2012-10-19T14:06:37Z
13,013,082
12
2012-10-22T14:01:08Z
[ "python", "sublimetext2" ]
I'm in the process of learning how to create Sublime Text 2 plugins. One of the things that I would like to do is take any highlighted text, check if a website will return a 200 at that address, and then place some information into the quick panel (and yes, I know that I should be doing the url lookup in a thread so th...
You don't need to create another instance of `WindowCommand` to accomplish this. Btw, you usually write commands but don't create their instances in your plugins. They are instantiated and invoked via key bindings or `run_command` method of View/Window/sublime. You can get the current active window inside your `check_...
How can I put and get a set of multiple items in a queue?
12,977,301
3
2012-10-19T15:14:47Z
12,977,342
7
2012-10-19T15:16:52Z
[ "python", "variables", "task-queue" ]
Worker: ``` def worker(): while True: fruit, colour = q.get() print 'A ' + fruit + ' is ' + colour q.task_done() ``` Putting items into queue: ``` fruit = 'banana' colour = 'yellow' q.put(fruit, colour) ``` Output: ``` >>> A banana is yellow ``` How would I be able to achieve this? I t...
Yes, use a tuple: ``` fruit = 'banana' colour = 'yellow' q.put((fruit, colour)) ``` It should be automatically unpacked (should, because I can't try it atm).
Python equivalent of D3.js
12,977,517
47
2012-10-19T15:26:16Z
14,177,775
35
2013-01-05T23:59:44Z
[ "python", "graph", "d3.js", "graph-tool" ]
Can anyone recommend a Python library that can do **interactive** graph visualization? I specifically want something like `d3.js` but for `python` and ideally it would be 3D as well. I have looked at: * `NetworkX` - it only does `Matplotlib` plots and those seem to be 2D. I didn't see any sort of interactiveness, li...
You could use [d3py](https://github.com/mikedewar/d3py) a python module that generate xml pages embedding d3.js script. For example : ``` import d3py import networkx as nx import logging logging.basicConfig(level=logging.DEBUG) G = nx.Graph() G.add_edge(1,2) G.add_edge(1,3) G.add_edge(3,2) G.add_edge(3,4) G.add_edge...
Python equivalent of D3.js
12,977,517
47
2012-10-19T15:26:16Z
15,456,131
11
2013-03-16T23:56:37Z
[ "python", "graph", "d3.js", "graph-tool" ]
Can anyone recommend a Python library that can do **interactive** graph visualization? I specifically want something like `d3.js` but for `python` and ideally it would be 3D as well. I have looked at: * `NetworkX` - it only does `Matplotlib` plots and those seem to be 2D. I didn't see any sort of interactiveness, li...
One recipe that I have used (described here: [Co-Director Network Data Files in GEXF and JSON from OpenCorporates Data via Scraperwiki and networkx](http://blog.ouseful.info/2013/02/25/co-director-network-data-files-in-gexf-and-json-from-opencorporates-data-via-scraperwiki/) ) runs as follows: * generate a network rep...
Python equivalent of D3.js
12,977,517
47
2012-10-19T15:26:16Z
19,304,576
14
2013-10-10T19:28:07Z
[ "python", "graph", "d3.js", "graph-tool" ]
Can anyone recommend a Python library that can do **interactive** graph visualization? I specifically want something like `d3.js` but for `python` and ideally it would be 3D as well. I have looked at: * `NetworkX` - it only does `Matplotlib` plots and those seem to be 2D. I didn't see any sort of interactiveness, li...
Have you looked at vincent? Vincent takes Python data objects and converts them to Vega visualization grammar. Vega is a higher-level visualization tool built on top of D3. As compared to D3py, the vincent repo has been updated more recently. Though the examples are all static D3. more info: * <https://github.com/wro...
Python equivalent of D3.js
12,977,517
47
2012-10-19T15:26:16Z
20,129,277
11
2013-11-21T18:37:53Z
[ "python", "graph", "d3.js", "graph-tool" ]
Can anyone recommend a Python library that can do **interactive** graph visualization? I specifically want something like `d3.js` but for `python` and ideally it would be 3D as well. I have looked at: * `NetworkX` - it only does `Matplotlib` plots and those seem to be 2D. I didn't see any sort of interactiveness, li...
Another option is [bokeh](http://bokeh.pydata.org/) which just went to version 0.3.
Localizing Epoch Time with pytz in Python
12,978,391
7
2012-10-19T16:19:12Z
13,260,035
9
2012-11-06T21:53:13Z
[ "python", "datetime", "timezone", "epoch", "pytz" ]
Im working on converting epoch timestamps to dates in different timezones with pytz. What I am trying to do is create a DateTime object that accepts an Olson database timezone and an epoch time and returns a localized datetime object. Eventually I need to answer questions like "What hour was it in New York at epoch tim...
`fromtimestamp()` returns localtime that shouldn't be used with arbitrary timezone.localize(); you need `utcfromtimestamp()` to get datetime in UTC and then convert it to a desired timezone: ``` from datetime import datetime import pytz # get time in UTC utc_dt = datetime.utcfromtimestamp(posix_timestamp).replace(tzi...
Ruby equivalent of Python str[3:]
12,978,768
5
2012-10-19T16:45:58Z
12,978,822
10
2012-10-19T16:49:36Z
[ "python", "ruby", "substring" ]
Is there a Ruby equivalent of Python's method for getting a substring that ends at the end of the string, like `str[3:]`? It's not convenient to have to put in the length of the string.
Pass a range with last element = -1 ``` str[3..-1] ```
Python Get Screen Pixel Value in OS X
12,978,846
10
2012-10-19T16:50:46Z
13,024,603
14
2012-10-23T06:24:39Z
[ "python", "osx", "automation", "ui-automation" ]
I'm in the process of building an automated game bot in Python on OS X 10.8.2 and in the process of researching Python GUI automation I discovered autopy. The mouse manipulation API is great, but it seems that the screen capture methods rely on deprecated OpenGL methods... Are there any efficient ways of getting the c...
A small improvement, but using the TIFF compression option for `screencapture` is a bit quicker: ``` $ time screencapture -t png /tmp/test.png real 0m0.235s user 0m0.191s sys 0m0.016s $ time screencapture -t tiff /tmp/test.tiff real 0m0.079s user 0m0.028s sys 0m0.026s ``` T...
Averaging scores in database (Django)
12,979,425
3
2012-10-19T17:31:56Z
12,979,440
7
2012-10-19T17:33:13Z
[ "python", "django" ]
I have a database `Result.objects.all()` of around 15 objects. Result has a field called score which ranges from 1-5. So if I preform `q = Result.objecets.get(id=1)`, `q.score` is 2. What's a method of finding the average of all scores for all 15 objects?
You can use django [aggregation](https://docs.djangoproject.com/en/dev/topics/db/aggregation/) functions to do this; ``` # Average price across all objects. >>> from django.db.models import Avg >>> Result.objects.all().aggregate(Avg('score')) {'score__avg': 34.35} ```
Python set().issubset() not working as expected
12,979,703
5
2012-10-19T17:48:59Z
12,979,845
9
2012-10-19T17:58:14Z
[ "python", "python-2.7", "set" ]
I'm trying to use `set().issubset()` for comparison of sequences. As you can imagine, it's not working as expected ;) In advance: sorry for the long code-blob. ``` class T(object): def __init__(self, value, attributes = None): self.value = value self.attributes = Attributes(attributes) def __eq__(self, ot...
Your objects are being hashed by their `id` (you didn't override `__hash__`). Of course they're not subsets since `xx` and `yy` contain unique objects. In order to do this, you need to come up with some sort of `__hash__` function. `__hash__` should always return the same value for an object which is why it's usually ...
Using Python's subprocess and Popen in one script to run another Python script which requires user interaction (by raw_input)
12,980,148
6
2012-10-19T18:19:32Z
12,982,539
7
2012-10-19T21:12:46Z
[ "python", "automation", "subprocess", "popen" ]
The problem I have is as follows, and I will use simple example to illustrate it. I have written a python script that requires user interaction, specifically it uses the raw\_input() function to get the user's input. The code below simply asks the user to type in two numbers in succession (hitting enter between each), ...
You can only call `communicate` once. Therefore you need to pass all the input at once, i.e. `child.communicate("1\n1\n")`. Alternatively you can write to stdin: ``` child = subprocess.Popen("./test.py", stdin=subprocess.PIPE) child.stdin.write("1\n") ch...
gi.repository Windows
12,981,137
11
2012-10-19T19:27:58Z
12,986,596
11
2012-10-20T08:13:36Z
[ "python", "windows", "gtk", "pygobject" ]
I'm developing an app which has to be 100% compatible on windows and on linux. On linux I have no problems, but on windows I came up with this message: from gi.repository import Gtk ImportError: No module named gi I installed pygobject, pygtkallinone, gtk.. what am I missing?
`gi.repository` module is called **PyGObject** and is for Gtk+3 and is not yet available for Windows (there has been experiments, but is not ready AFAIK). <https://live.gnome.org/PyGObject> `gtk` module is called **PyGtk** and is for Gtk+2 and is very mature on Windows platforms (in particular 2.24). <http://www.pygtk...
gi.repository Windows
12,981,137
11
2012-10-19T19:27:58Z
20,948,842
16
2014-01-06T11:15:45Z
[ "python", "windows", "gtk", "pygobject" ]
I'm developing an app which has to be 100% compatible on windows and on linux. On linux I have no problems, but on windows I came up with this message: from gi.repository import Gtk ImportError: No module named gi I installed pygobject, pygtkallinone, gtk.. what am I missing?
Most of Havok answer is correct, except that documentation has been improved a lot lately, with a Tutorial: * <http://python-gtk-3-tutorial.readthedocs.org/en/latest/> Including a PDF version for offline reading: * <http://media.readthedocs.org/pdf/python-gtk-3-tutorial/latest/python-gtk-3-tutorial.pdf> And a compl...
How to draw line inside a scatter plot
12,981,696
3
2012-10-19T20:05:53Z
12,983,510
7
2012-10-19T22:52:08Z
[ "python", "numpy", "matplotlib", "plot", "scipy" ]
I can't believe that this is so complicated but I tried and googled for a while now. I just want to analyse my scatter plot with a few graphical features. For starters, I want to add simply a line. So, I have a few (4) points and I want to add a line to it, like in this plot (source: <http://en.wikipedia.org/wiki/Fil...
`plot`takes either y values and uses x as index array `0..N-1` or x and y values as described in the [documentation](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot). So you could use ``` p5 = axScatter.plot((0, 1), "r--") ``` in your code to plot the line. However, you are asking for "good practice...
Flask ImportError with bson on OS X
12,983,472
4
2012-10-19T22:47:36Z
12,983,651
25
2012-10-19T23:13:03Z
[ "python", "mongodb", "pymongo", "bson" ]
I'm having trouble getting a simple Hello World app to work using Flask, MongoDB, and Python. The app is bombing when trying to import from the `bson` module. All modules were installed successfully via `pip` and I'm running in a `virtualenv`, so I'm not sure why I'm getting the error: `ImportError: cannot import name ...
Try uninstalling the `bson` and `pymongo` packages and then reinstalling the `pymongo` package. `pymongo` installs its own `bson` package and I think you've overwritten it with the other `bson` package installation and that is probably what is causing your import error.
How do I run a python script from a file? (UNIX)
12,984,206
2
2012-10-20T00:38:22Z
12,984,221
8
2012-10-20T00:41:03Z
[ "python", "unix" ]
Basically what I want to do is make a file called doPython and in this file I want to do the command: ``` python myFile.py data.txt ``` I've tried Googling and making a few scripts but I can't seem to get it to work. It says "No such file or directory when I try with ``` #!/usr/bin/env python python myFile.py data.t...
`#!/usr/bin/env python` says that your script is to be run with the Python interpreter. You just need to call `sh` or `bash`: ``` #!/bin/sh python myFile.py data.txt ```
Python PIL "IOError: image file truncated" with big images
12,984,426
6
2012-10-20T01:20:27Z
20,068,394
8
2013-11-19T10:00:21Z
[ "python", "image", "python-imaging-library", "zope" ]
I think this problem is not Zope-related. Nonetheless I'll explain what I'm trying to do: I'm using a PUT\_factory in Zope to upload images to the ZODB per FTP. The uploaded image is saved as a Zope Image inside a newly created container object. This works fine, but I want to resize the image if it exceeds a certain s...
Best thing is that you can: ``` if img and img.meta_type == 'Image': pilImg = PIL.Image.open( StringIO(str(img.data)) ) elif imgData: pilImg = PIL.Image.open( StringIO(imgData) ) try: pilImg.load() except IOError: pass # You can always log it to logger pilImg.thumbnail((width, height), PIL.Image.ANTI...
Python PIL "IOError: image file truncated" with big images
12,984,426
6
2012-10-20T01:20:27Z
23,575,424
25
2014-05-09T23:26:17Z
[ "python", "image", "python-imaging-library", "zope" ]
I think this problem is not Zope-related. Nonetheless I'll explain what I'm trying to do: I'm using a PUT\_factory in Zope to upload images to the ZODB per FTP. The uploaded image is saved as a Zope Image inside a newly created container object. This works fine, but I want to resize the image if it exceeds a certain s...
I'm a little late to reply here, but I ran into a similar problem and I wanted to share my solution. First, here's a pretty typical stack trace for this problem: ``` Traceback (most recent call last): ... File ..., line 2064, in ... im.thumbnail(DEFAULT_THUMBNAIL_SIZE, Image.ANTIALIAS) File "/Library/Python/...
Replace all non-alphanumeric characters in a string
12,985,456
32
2012-10-20T05:10:04Z
12,985,459
57
2012-10-20T05:11:02Z
[ "python" ]
I have a string with which i want to replace any character that isn't a standard character or number such as (a-z or 0-9) with an asterisk. For example, "h^&ell`.,|o w]{+orld" is replaced with "h\*ell\*o\*w\*orld". Note that multiple characters such as "^&" get replaced with one asterisk. How would I go about doing thi...
Regex to the rescue! ``` import re s = re.sub('[^0-9a-zA-Z]+', '*', s) ``` Example: ``` >>> re.sub('[^0-9a-zA-Z]+', '*', 'h^&ell`.,|o w]{+orld') 'h*ell*o*w*orld' ```
Replace all non-alphanumeric characters in a string
12,985,456
32
2012-10-20T05:10:04Z
22,096,493
14
2014-02-28T13:27:31Z
[ "python" ]
I have a string with which i want to replace any character that isn't a standard character or number such as (a-z or 0-9) with an asterisk. For example, "h^&ell`.,|o w]{+orld" is replaced with "h\*ell\*o\*w\*orld". Note that multiple characters such as "^&" get replaced with one asterisk. How would I go about doing thi...
The pythonic way. ``` print "".join([ c if c.isalnum() else "*" for c in s ]) ``` This doesn't deal with multiple non-matching characters, though.
How do I compute all possibilities for an array of numbers/bits (in python, or any language for that matter)
12,986,272
3
2012-10-20T07:21:28Z
12,991,706
8
2012-10-20T19:05:33Z
[ "python", "arrays", "combinations" ]
I have been wracking my brains out for 3 hours straight, but I still don't get it, so I am asking here. (I wrote Python in the title, but this could be for pretty much any language) Let's assume I have an array of bits (but it may also be integers in a defined range) of fixed length n, let's say 5. ``` array=[0,1,1,0...
In Python, use [itertools](http://docs.python.org/library/itertools.html#itertools.product) for stuff like this ``` from itertools import product for i in product([0,1], repeat=5): print i ``` Yields: ``` (0, 0, 0, 0, 0) (0, 0, 0, 0, 1) (0, 0, 0, 1, 0) (0, 0, 0, 1, 1) (0, 0, 1, 0, 0) etc... ```
Conditional for in Python
12,986,996
13
2012-10-20T09:16:28Z
12,987,032
29
2012-10-20T09:21:18Z
[ "python" ]
Does Python have something like below? ``` for item in items #where item>3: #..... ``` I mean Python 2.7 and Python 3.3 both together.
You can combine the loop with a [generator expression](http://docs.python.org/reference/expressions.html#grammar-token-generator_expression): ``` for x in (y for y in items if y > 10): .... ``` [itertools.ifilter](http://docs.python.org/library/itertools.html#itertools.ifilter) is another option - and even prefer...
Confusion between numpy, scipy, matplotlib and pylab
12,987,624
104
2012-10-20T10:44:33Z
12,987,916
106
2012-10-20T11:22:50Z
[ "python", "numpy", "matplotlib", "scipy" ]
Numpy, scipy, matplotlib, and pylab are common terms among they who use python for scientific computation. I just learn a bit about pylab, and I got a lot of confusion. Whenever I want to import numpy, I can always do: ``` import numpy as np ``` I just consider, that once I do ``` from pylab import * ``` The numpy...
1. No, `pylab` is part of `matplotlib` (in `matplotlib.pylab`) and tries to give you a MatLab like environment. `matplotlib` has a number of dependencies, among them `numpy` which it imports under the common alias `np`. `scipy` is not a dependency of `matplotlib`. 2. If you run `ipython --pylab` an automatic import wil...
ImportError: Could not import settings
12,987,648
28
2012-10-20T10:48:05Z
12,988,283
29
2012-10-20T12:10:24Z
[ "python", "django" ]
I am trying to develop an sample project in Django and getting errors when I run the syncdb command. This is how my project structure looks like: /Users/django\_demo/godjango/bookings: ``` manage.py registration/ forms.py views.py models.py urls.py bookings/ settings.p...
The error says `ImportError: Could not import settings 'bookings.settings' (Is it on sys.path?): No module named unipath` So, is your path `/Users/django_demo/godjango/bookings` within the python-sys.path? Check it in your shell with: ``` $ python Python 2.7.3 (v2.7.3:70274d53c1dd, Apr 9 2012, 20:52:43) [GCC 4.2.1...
ImportError: Could not import settings
12,987,648
28
2012-10-20T10:48:05Z
12,988,327
10
2012-10-20T12:15:58Z
[ "python", "django" ]
I am trying to develop an sample project in Django and getting errors when I run the syncdb command. This is how my project structure looks like: /Users/django\_demo/godjango/bookings: ``` manage.py registration/ forms.py views.py models.py urls.py bookings/ settings.p...
The significant part of the traceback here is right at the very end. It says "No module named unipath". You've referred to that somewhere in your code, but you don't seem to have it in your project - it's not part of the standard library, so you'll need to install it somewhere that Python can see it.
ImportError: Could not import settings
12,987,648
28
2012-10-20T10:48:05Z
14,876,533
12
2013-02-14T14:02:19Z
[ "python", "django" ]
I am trying to develop an sample project in Django and getting errors when I run the syncdb command. This is how my project structure looks like: /Users/django\_demo/godjango/bookings: ``` manage.py registration/ forms.py views.py models.py urls.py bookings/ settings.p...
Modify your wsgi.py file from ``` import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bookings.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() ``` to ``` import os, sys sys.path.append(' /Users/Sreek/django_demo/godjango/bookings') os.environ.setdefaul...
Split a dictionary into 2 dictionaries
12,988,351
15
2012-10-20T12:17:59Z
12,988,416
13
2012-10-20T12:27:10Z
[ "python" ]
What is the best way to split a dictionary in half? ``` d = {'key1': 1, 'key2': 2, 'key3': 3, 'key4': 4, 'key5': 5} ``` I'm looking to do this: ``` d1 = {'key1': 1, 'key2': 2, 'key3': 3} d2 = {'key4': 4, 'key5': 5} ``` It does not matter which keys/values go into each dictionary. I am simply looking for the simples...
This would work, although I didn't test edge-cases: ``` >>> d = {'key1': 1, 'key2': 2, 'key3': 3, 'key4': 4, 'key5': 5} >>> d1 = dict(d.items()[len(d)/2:]) >>> d2 = dict(d.items()[:len(d)/2]) >>> print d1 {'key1': 1, 'key5': 5, 'key4': 4} >>> print d2 {'key3': 3, 'key2': 2} ```
How can I remove the Unicode u from a JSON item?
12,988,612
2
2012-10-20T12:51:23Z
12,988,662
8
2012-10-20T12:56:38Z
[ "python", "json", "string", "unicode" ]
``` >>> stuff = '[["hiya"]]' >>> js = json.loads(stuff) >>> js[0] [u'hiya'] >>> str(js[0]) "[u'hiya']" ``` It doesn't seem to go away. How can I print `hiya` on its own (without manually stripping the special characters away)?
You have a list that's nested two levels deep. Try it like this to simply print 'hiya': ``` >>> import json >>> stuff = '[["hiya"]]' >>> js = json.loads(stuff) >>> str(js[0][0]) 'hiya' ```
Django CMS - not able to upload images through cmsplugin_filer_image
12,988,973
6
2012-10-20T13:36:25Z
13,059,037
9
2012-10-24T22:50:58Z
[ "python", "django", "django-admin", "django-cms", "django-file-upload" ]
i have a problem with a local installation on django cms 2.3.3: i've installed it trough pip, in a separated virtualenv. next i followed the tutorial for settings.py configuration, i started the server. Then in the admin i created an page (home), and i've tried to add an image in the placeholder through the cmsplugin\_...
This error because you installed PIL with out JPEG/PNG support. you will need to install the following packages ``` sudo apt-get install python-imaging python-dev libjpeg8 libjpeg8-dev libfreetype6 libfreetype6-dev ``` Then uninstall PIL `pip uninstall PIL` I suggest installing pillow instead of PIL using `pip inst...
Using SCSS with Flask
12,989,916
4
2012-10-20T15:31:10Z
13,102,908
7
2012-10-27T18:23:09Z
[ "python", "flask", "sass" ]
I'm trying to use scss with Flask and get it to auto-compile. I've tried using [Flask-Scss](http://packages.python.org/Flask-Scss/) — unfortunately, when I set it up, I get `Scanning acceleration disabled (_speedups not found)!` errors, and no CSS file. Anyone know how to fix this, or get it to generate CSS files?
The error results from an error in the installation process. If you install through `pip` on an Ubuntu system and you get this warning: ``` ========================================================================== WARNING: The C extension could not be compiled, speedups are not enabled. Plain-Python installation succ...
How to fetch process,thread name,levelname in customized python logger
12,990,199
2
2012-10-20T16:02:28Z
12,990,639
10
2012-10-20T16:54:20Z
[ "python", "python-3.x", "python-2.7", "wxpython", "ironpython" ]
I am developing customized logger program,as per the requirement i need to fetch the process,thread and name of object Inside the called function(In below example its obj needs to fetch inside the get\_configured\_logger function) and class name to which obj belongs. as shown with comments in below code, please give so...
To add current process/thread name to a log message you could specify in the format string: ``` %(processName)s %(threadName)s ``` To get them as strings: ``` process_name = multiprocessing.current_process().name thread_name = threading.current_thread().name ```
Stretching a list in Python
12,991,962
2
2012-10-20T19:37:36Z
12,992,032
8
2012-10-20T19:44:14Z
[ "python", "algorithm", "list" ]
An example: I have a list `[1,2,3,4,5,6,7,8]` and I need to "stretch" it to lenght 20, with existing values distributed as evenly as possible,"missing" values replaced with `None` and the resulting list has to start with 1 and end with 8. There are 8-1 spaces between the values in the original list and and 20-8 None v...
Basic idea: just linearly interpolate the new positions from the old positions. For simplicity, we use floor division, but you could get clever and use rounding division for a slightly more even distribution. ``` def stretch_to(l, n): out = [None] * n m = len(l) for i, x in enumerate(l): out[i*(n-1...
Python dictionary increment
12,992,165
9
2012-10-20T20:00:03Z
12,992,178
7
2012-10-20T20:01:43Z
[ "python", "dictionary", "increment" ]
In Python it's annoying to have to check whether a key is in the dictionary first before incrementing it: ``` if key in my_dict: my_dict[key] += num else: my_dict[key] = num ``` Is there a shorter substitute for the four lines above?
What you want is called a defaultdict See <http://docs.python.org/library/collections.html#collections.defaultdict>
Python dictionary increment
12,992,165
9
2012-10-20T20:00:03Z
12,992,182
11
2012-10-20T20:01:56Z
[ "python", "dictionary", "increment" ]
In Python it's annoying to have to check whether a key is in the dictionary first before incrementing it: ``` if key in my_dict: my_dict[key] += num else: my_dict[key] = num ``` Is there a shorter substitute for the four lines above?
You have quite a few options. I like using `Counter`: ``` >>> from collections import Counter >>> d = Counter() >>> d[12] += 3 >>> d Counter({12: 3}) ``` Or `defaultdict`: ``` >>> from collections import defaultdict >>> d = defaultdict(int) # int() == 0, so the default value for each key is 0 >>> d[12] += 3 >>> d d...
Python dictionary increment
12,992,165
9
2012-10-20T20:00:03Z
12,992,212
22
2012-10-20T20:06:31Z
[ "python", "dictionary", "increment" ]
In Python it's annoying to have to check whether a key is in the dictionary first before incrementing it: ``` if key in my_dict: my_dict[key] += num else: my_dict[key] = num ``` Is there a shorter substitute for the four lines above?
An alternative is: ``` my_dict[key] = my_dict.get(key, 0) + num ```
tkinter/py2app created application doesn't show window on initial launch
12,992,316
4
2012-10-20T20:18:23Z
12,993,157
12
2012-10-20T22:12:02Z
[ "python", "osx", "tkinter", "tk", "py2app" ]
I'm running into an issue where launching a python app created with Tkinter and packaged by py2app doesn't show the application window immediately. The only way I've gotten the window to show after launch is to click on the application icon in the dock. [This guy](http://stackoverflow.com/questions/10003707/sdl-based-...
After doing some extensive research, it would appear that this is a result of setting the 'argv\_emulation' option to True in the, py2app, setup.py file.
Errors while installing python autopy
12,993,126
7
2012-10-20T22:06:35Z
13,150,697
11
2012-10-31T03:04:59Z
[ "python", "autopy" ]
Hey I have looked at and old question here but it doesn't answer my question I have installed libpng, then try to install autopy and get complie errors. I am not great at python yet so I am not sure on how to fix them. ``` Ashley:~ ashleyhughes$ sudo easy_install autopy Searching for autopy Reading http://pypi.pytho...
I had the same problem, if you notice all 9 errors are coming from one file: src/screengrab.c This file has not been updated to the latest version of OpenGL and there are deprecated methods. On the autopy github repo there is a bug reported for this [here.](https://github.com/msanders/autopy/pull/27) The fix/hack sugge...
Errno 10061 : No connection could be made because the target machine actively refused it ( client - server )
12,993,276
13
2012-10-20T22:32:10Z
12,993,494
11
2012-10-20T23:10:20Z
[ "python", "sockets" ]
I have a problem with these client and server codes, I keep getting the **[Errno 10061] No connection could be made because the target machine actively refused it** I'm running the server on a virtual machine with Windows XP SP3 and the client on Windows 7 64bit, my python version is 2.7.3. What I want to know is how ...
10061 is WSAECONNREFUSED, 'connection refused', which means either a firewall (unlikely) or more probably nothing listening at the IP:port you tried to connect to.
Passing a custom python function into a tornado template
12,993,835
3
2012-10-21T00:19:41Z
13,003,440
13
2012-10-21T23:58:50Z
[ "python", "tornado" ]
I want to write a custom function and pass it unto my tornado template fine. Like `def trimString(data): return data[0:20]` then push this into my tornado file. This should allow me trim strings. Is this possible? Thanks.
It's not [especially clear in the documentation](http://www.tornadoweb.org/en/stable/guide/templates.html?highlight=ui_methods#template-syntax), but you can do this easily by defining this function in a module and passing the module to `tornado.web.Application` as the `ui_methods` argument. I. E.: in ui\_methods.py: ...
Appending data to a json file in Python
12,994,442
11
2012-10-21T02:35:37Z
12,994,527
16
2012-10-21T02:54:44Z
[ "python", "json" ]
I'm trying to create a function that would add entries to a json file. Eventually, I want a file that looks like ``` [{"name" = "name1", "url" = "url1"}, {"name" = "name2", "url" = "url2"}] ``` etc. This is what I have: ``` def add(args): with open(DATA_FILENAME, mode='r', encoding='utf-8') as feedsjson: ...
You probably want to use a JSON *list* instead of a dictionary as the toplevel element. So, initialize the file with an empty list: ``` with open(DATA_FILENAME, mode='w', encoding='utf-8') as f: json.dump([], f) ``` Then, you can *append* new entries to this list: ``` with open(DATA_FILENAME, mode='w', encoding...
Appending data to a json file in Python
12,994,442
11
2012-10-21T02:35:37Z
12,994,577
13
2012-10-21T03:08:43Z
[ "python", "json" ]
I'm trying to create a function that would add entries to a json file. Eventually, I want a file that looks like ``` [{"name" = "name1", "url" = "url1"}, {"name" = "name2", "url" = "url2"}] ``` etc. This is what I have: ``` def add(args): with open(DATA_FILENAME, mode='r', encoding='utf-8') as feedsjson: ...
json might not be the best choice for on-disk formats; The trouble it has with appending data is a good example of why this might be. Specifically, json objects have a syntax that means the whole object must be read and parsed in order to understand any part of it. Fortunately, there are lots of other options. A parti...
Representing and solving a maze given an image
12,995,434
189
2012-10-21T06:03:44Z
12,995,815
181
2012-10-21T07:20:56Z
[ "python", "algorithm", "matlab", "image-processing", "maze" ]
What is the best way to represent and solve a maze given an image? ![The cover image of The Scope Issue 134](http://i.stack.imgur.com/TqKCM.jpg) Given an JPEG image (as seen above), what's the best way to read it in, parse it into some data structure and solve the maze? My first instinct is to read the image in pixel...
Here is a solution. 1. Convert image to grayscale (not yet binary), adjusting weights for the colors so that final grayscale image is approximately uniform. You can do it simply by controlling sliders in Photoshop in Image -> Adjustments -> Black & White. 2. Convert image to binary by setting appropriate threshold in ...
Representing and solving a maze given an image
12,995,434
189
2012-10-21T06:03:44Z
13,042,259
18
2012-10-24T02:41:16Z
[ "python", "algorithm", "matlab", "image-processing", "maze" ]
What is the best way to represent and solve a maze given an image? ![The cover image of The Scope Issue 134](http://i.stack.imgur.com/TqKCM.jpg) Given an JPEG image (as seen above), what's the best way to read it in, parse it into some data structure and solve the maze? My first instinct is to read the image in pixel...
Uses a queue for a threshold continuous fill. Pushes the pixel left of the entrance onto the queue and then starts the loop. If a queued pixel is dark enough, it's colored light gray (above threshold), and all the neighbors are pushed onto the queue. ``` from PIL import Image img = Image.open("/tmp/in.jpg") (w,h) = im...
Representing and solving a maze given an image
12,995,434
189
2012-10-21T06:03:44Z
13,045,519
27
2012-10-24T08:33:15Z
[ "python", "algorithm", "matlab", "image-processing", "maze" ]
What is the best way to represent and solve a maze given an image? ![The cover image of The Scope Issue 134](http://i.stack.imgur.com/TqKCM.jpg) Given an JPEG image (as seen above), what's the best way to read it in, parse it into some data structure and solve the maze? My first instinct is to read the image in pixel...
Tree search is too much. The maze is inherently separable along the solution path(s). (Thanks to [rainman002](http://www.reddit.com/r/coding/comments/11yvxu/solving_a_maze_given_an_image_stack_overflow/c6qtnrr) from Reddit for pointing this out to me.) Because of this, you can quickly use [connected components](https...
Representing and solving a maze given an image
12,995,434
189
2012-10-21T06:03:44Z
13,174,351
116
2012-11-01T09:40:23Z
[ "python", "algorithm", "matlab", "image-processing", "maze" ]
What is the best way to represent and solve a maze given an image? ![The cover image of The Scope Issue 134](http://i.stack.imgur.com/TqKCM.jpg) Given an JPEG image (as seen above), what's the best way to read it in, parse it into some data structure and solve the maze? My first instinct is to read the image in pixel...
This solution is written in Python. Thanks Mikhail for the pointers on the image preparation. **An animated Breadth-First Search:** ![Animated version of BFS](http://i.stack.imgur.com/dM6Yc.gif) **The Completed Maze:** ![Completed Maze](http://i.stack.imgur.com/xyRo9.png) ``` #!/usr/bin/env python import sys fro...
Representing and solving a maze given an image
12,995,434
189
2012-10-21T06:03:44Z
16,656,993
56
2013-05-20T19:33:31Z
[ "python", "algorithm", "matlab", "image-processing", "maze" ]
What is the best way to represent and solve a maze given an image? ![The cover image of The Scope Issue 134](http://i.stack.imgur.com/TqKCM.jpg) Given an JPEG image (as seen above), what's the best way to read it in, parse it into some data structure and solve the maze? My first instinct is to read the image in pixel...
I tried myself implementing A-Star search for this problem. Followed closely the implementation by [Joseph Kern](http://stackoverflow.com/a/13174351/1025391) for the framework and the algorithm pseudocode given [here](http://en.wikipedia.org/wiki/A-star#Pseudocode): ``` import heapq def AStar(start, goal, neighbor_no...
Representing and solving a maze given an image
12,995,434
189
2012-10-21T06:03:44Z
20,487,166
16
2013-12-10T05:51:13Z
[ "python", "algorithm", "matlab", "image-processing", "maze" ]
What is the best way to represent and solve a maze given an image? ![The cover image of The Scope Issue 134](http://i.stack.imgur.com/TqKCM.jpg) Given an JPEG image (as seen above), what's the best way to read it in, parse it into some data structure and solve the maze? My first instinct is to read the image in pixel...
Here you go: [maze-solver-python](https://github.com/scharissis/maze-solver-python) (GitHub) ![enter image description here](http://i.stack.imgur.com/HZwwi.gif) I had fun playing around with this and extended on [Joseph Kern](http://stackoverflow.com/a/13174351/1505651)'s answer. Not to detract from it; I just made s...
Name '_' is not defined
12,995,888
3
2012-10-21T07:34:00Z
12,995,923
23
2012-10-21T07:40:39Z
[ "python", "django" ]
I'm getting the following error when I perform: ``` $ python manage.py schemamigration myapp --initial ``` It seems to complain about this line: ``` audio_file = models.FileField(_("Audio file"), upload_to=get_audio_upload_path) ``` I'm not sure what I'm doing wrong. Please help. ``` Traceback (most recent call la...
You miss this: ``` from django.utils.translation import gettext as _ ``` Read more info from [Django i18n docs](https://docs.djangoproject.com/en/dev/topics/i18n/translation/). It's an idiomatic method in `Django`/`python` projects.
Count all values in a matrix greater than a value
12,995,937
13
2012-10-21T07:43:02Z
12,996,094
17
2012-10-21T08:11:00Z
[ "python", "arrays", "coding-style", "numpy", "pixel" ]
I have to count all the values in a matrix (2-d array) that are greater than 200. The code I wrote down for this is: ``` za=0 p31 = numpy.asarray(o31) for i in range(o31.size[0]): for j in range(o32.size[1]): if p31[i,j]<200: za=za+1 print za ``` `o31` is an image and I am c...
The `numpy.where` function is your friend. Because it's implemented to take full advantage of the array datatype, for large images you should notice a speed improvement over the pure python solution you provide. Using numpy.where directly will yield a boolean mask indicating whether certain values match your condition...
Count all values in a matrix greater than a value
12,995,937
13
2012-10-21T07:43:02Z
12,996,105
9
2012-10-21T08:13:37Z
[ "python", "arrays", "coding-style", "numpy", "pixel" ]
I have to count all the values in a matrix (2-d array) that are greater than 200. The code I wrote down for this is: ``` za=0 p31 = numpy.asarray(o31) for i in range(o31.size[0]): for j in range(o32.size[1]): if p31[i,j]<200: za=za+1 print za ``` `o31` is an image and I am c...
There are many ways to achieve this, like flatten-and-filter or simply enumerate, but I think using [Boolean/mask array](http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays) is the easiest one (and iirc a much faster one): ``` >>> y = np.array([[123,24123,32432], [234,24,23]]) array(...
Count all values in a matrix greater than a value
12,995,937
13
2012-10-21T07:43:02Z
12,996,211
28
2012-10-21T08:32:56Z
[ "python", "arrays", "coding-style", "numpy", "pixel" ]
I have to count all the values in a matrix (2-d array) that are greater than 200. The code I wrote down for this is: ``` za=0 p31 = numpy.asarray(o31) for i in range(o31.size[0]): for j in range(o32.size[1]): if p31[i,j]<200: za=za+1 print za ``` `o31` is an image and I am c...
This is very straightforward with boolean arrays: ``` p31 = numpy.asarray(o31) za = (p31 < 200).sum() # p31<200 is a boolean array, so `sum` counts the number of True elements ```
How to setup and launch a Scrapy spider programmatically (urls and settings)
12,996,910
20
2012-10-21T10:10:19Z
17,120,002
7
2013-06-15T03:47:20Z
[ "python", "scrapy", "scrapyd" ]
I've written a working crawler using scrapy, now I want to control it through a Django webapp, that is to say: * Set 1 or several `start_urls` * Set 1 or several `allowed_domains` * Set `settings` values * Start the spider * Stop / pause / resume a spider * retrieve some stats while running * retrive some stats afte...
> At first I thought scrapyd was made for this, but after reading the doc, it seems that it's more a daemon able to manage 'packaged spiders', aka 'scrapy eggs'; and that all the settings (start\_urls , allowed\_domains, settings ) must still be hardcoded in the 'scrapy egg' itself ; so it doesn't look like a solution ...
Empty list boolean value
12,997,305
3
2012-10-21T11:17:53Z
12,997,334
15
2012-10-21T11:21:57Z
[ "python", "list", "boolean" ]
This may be simply idiotic, but for me it's a bit confusing: ``` In [697]: l=[] In [698]: bool(l) Out[698]: False In [699]: l == True Out[699]: False In [700]: l == False Out[700]: False In [701]: False == False Out[701]: True ``` Why does `l==False` return `False` while `False == False` returns `True`?
You are checking it against the literal value of the boolean `False`. The same as `'A' == False` will not be true. If you cast it, you'll see the difference: ``` >>> l = [] >>> l is True False >>> l is False False >>> l == True False >>> l == False False >>> bool(l) == False True ``` The reason `False == False` is t...
How do I change the color of my widget in Kivy at run time?
12,997,545
11
2012-10-21T11:49:16Z
13,008,269
9
2012-10-22T09:19:59Z
[ "python", "kivy" ]
I'm having trouble changing the color of a simple widget in Kivy. I can set the color when I create the widget, but I can't change it afterwards. Here is the simple layout definition file `circletest.kv`. It defines a circle where the color (actually just the r, from rgba), position and size are all linked to variable...
In your initial version, you were just missing the declaration of the property ``` from kivy.properties import NumericProperty ``` in the header and ``` r = NumericProperty(0) ``` just under `class CircleWidget(Widget):` also, you state that your kv file is named circletest.kv, but your app is named TestApp, so yo...
How do I change the color of my widget in Kivy at run time?
12,997,545
11
2012-10-21T11:49:16Z
13,010,008
12
2012-10-22T10:58:48Z
[ "python", "kivy" ]
I'm having trouble changing the color of a simple widget in Kivy. I can set the color when I create the widget, but I can't change it afterwards. Here is the simple layout definition file `circletest.kv`. It defines a circle where the color (actually just the r, from rgba), position and size are all linked to variable...
The answer by tshirtman is correct, here is the explanation of what's going on. In your kv file when you set ``` <CircleWidget>: canvas: Color: rgba: self.r, 1, 1, 1 Ellipse: pos: self.pos size: self.size ``` The line `rgba: self.r, 1, 1, 1` tries to update the...
Need to convert a list of strings to a list of normal numbers, strings are base 10
12,997,807
2
2012-10-21T12:28:15Z
12,997,819
7
2012-10-21T12:29:48Z
[ "python", "string", "list" ]
I have a list of integers looking like this: ``` ["1e-04", "1e-06", "1e-08", "1e-10", "1e-12"] ``` I need to convert this list of strings into a list of normal numbers, but the base 10 gets me stuck. Any suggestions? Thanks.
``` >>> import ast >>> L = ["1e-04", "1e-06", "1e-08", "1e-10", "1e-12"] >>> [ast.literal_eval(x) for x in L] [0.0001, 1e-06, 1e-08, 1e-10, 1e-12] ``` Or simply.. ``` >>> [float(x) for x in L] [0.0001, 1e-06, 1e-08, 1e-10, 1e-12] ```
Remove xticks in a matplot lib plot?
12,998,430
82
2012-10-21T13:53:56Z
12,998,531
146
2012-10-21T14:05:20Z
[ "python", "matplotlib", "plot" ]
I have a semilogx plot and I would like to remove the xticks. I tried : ``` plt.gca().set_xticks([]) plt.xticks([]) ax.set_xticks([]) ``` The grid disappear (ok), but small ticks (at the place of the main ticks) remain. How to remove them ?
The [`tick_params`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.tick_params) method is very useful for stuff like this. This code turns off major and minor ticks and removes the labels from the x-axis. ``` from matplotlib import pyplot as plt plt.plot(range(10)) plt.tick_params( axis='x', ...
Remove xticks in a matplot lib plot?
12,998,430
82
2012-10-21T13:53:56Z
12,999,832
25
2012-10-21T16:37:39Z
[ "python", "matplotlib", "plot" ]
I have a semilogx plot and I would like to remove the xticks. I tried : ``` plt.gca().set_xticks([]) plt.xticks([]) ax.set_xticks([]) ``` The grid disappear (ok), but small ticks (at the place of the main ticks) remain. How to remove them ?
There is a better, and simpler, solution than the one given by John Vinyard. Use `NullLocator`: ``` import matplotlib.pyplot as plt plt.plot(range(10)) plt.gca().xaxis.set_major_locator(plt.NullLocator()) plt.show() plt.savefig('plot') ``` Hope that helps.
Remove xticks in a matplot lib plot?
12,998,430
82
2012-10-21T13:53:56Z
19,916,006
13
2013-11-11T21:09:54Z
[ "python", "matplotlib", "plot" ]
I have a semilogx plot and I would like to remove the xticks. I tried : ``` plt.gca().set_xticks([]) plt.xticks([]) ax.set_xticks([]) ``` The grid disappear (ok), but small ticks (at the place of the main ticks) remain. How to remove them ?
Try this to remove the labels (but not the ticks): ``` import matplotlib.pyplot as plt plt.setp( ax.get_xticklabels(), visible=False) ``` [example](http://matplotlib.org/examples/pylab_examples/shared_axis_demo.html)
Remove xticks in a matplot lib plot?
12,998,430
82
2012-10-21T13:53:56Z
21,322,270
27
2014-01-24T00:38:53Z
[ "python", "matplotlib", "plot" ]
I have a semilogx plot and I would like to remove the xticks. I tried : ``` plt.gca().set_xticks([]) plt.xticks([]) ax.set_xticks([]) ``` The grid disappear (ok), but small ticks (at the place of the main ticks) remain. How to remove them ?
Not exactly what the OP was asking for, but a simple way to disable all axes lines, ticks and labels is to simply call: ``` plt.axis('off') ```
Remove xticks in a matplot lib plot?
12,998,430
82
2012-10-21T13:53:56Z
33,707,647
12
2015-11-14T10:56:26Z
[ "python", "matplotlib", "plot" ]
I have a semilogx plot and I would like to remove the xticks. I tried : ``` plt.gca().set_xticks([]) plt.xticks([]) ax.set_xticks([]) ``` The grid disappear (ok), but small ticks (at the place of the main ticks) remain. How to remove them ?
Here is an alternative solution that I found on the [matplotlib mailing list](http://matplotlib.1069221.n5.nabble.com/turning-off-tick-marks-tp27160p27162.html): ``` import matplotlib.pylab as plt x = range(1000) ax = plt.axes() ax.semilogx(x, x) ax.xaxis.set_ticks_position('none') ``` ![graph](http://i.imgur.com/Cz...
Is it possible to mock Python's built in print function?
12,998,908
17
2012-10-21T14:50:41Z
12,999,087
11
2012-10-21T15:13:04Z
[ "python", "unit-testing", "mocking", "python-2.x" ]
I've tried ``` from mock import Mock import __builtin__ __builtin__.print = Mock() ``` But that raises a syntax error. I've also tried patching it like so ``` @patch('__builtin__.print') def test_something_that_performs_lots_of_prints(self, mock_print): # assert stuff ``` Is there any way to do this?
`print` is a keyword in python 2.x, using it as attribute raises a SyntaxError. You can avoid that by using `from __future__ import print_function` in the beginning of the file. Note: you can't simply use `setattr`, because the print function you modified doesn't get invoked unless the `print` statement is disabled. ...
Is it possible to mock Python's built in print function?
12,998,908
17
2012-10-21T14:50:41Z
31,171,719
11
2015-07-01T21:08:36Z
[ "python", "unit-testing", "mocking", "python-2.x" ]
I've tried ``` from mock import Mock import __builtin__ __builtin__.print = Mock() ``` But that raises a syntax error. I've also tried patching it like so ``` @patch('__builtin__.print') def test_something_that_performs_lots_of_prints(self, mock_print): # assert stuff ``` Is there any way to do this?
I know that there is already an accepted answer but there is simpler solution for that problem - mocking the print in python 2.x. Answer is in the mock library tutorial: <http://www.voidspace.org.uk/python/mock/patch.html> and it is: ``` >>> from StringIO import StringIO >>> def foo(): ... print 'Something' ... >>...