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 |
|---|---|---|---|---|---|---|---|---|---|
Can I use CountVectorizer in scikit-learn to count frequency of documents that were not used to extract the tokens? | 22,920,801 | 11 | 2014-04-07T19:01:20Z | 22,920,964 | 21 | 2014-04-07T19:10:04Z | [
"python",
"machine-learning",
"scikit-learn",
"tf-idf"
] | I have been working with the `CountVectorizer` class in scikit-learn.
I understand that if used in the manner shown below, the final output will consist of an array containing counts of features, or tokens.
These tokens are extracted from a set of keywords, i.e.
```
tags = [
"python, tools",
"linux, tools, ubunt... | You're right that `vocabulary` is what you want. It works like this:
```
>>> cv = sklearn.feature_extraction.text.CountVectorizer(vocabulary=['hot', 'cold', 'old'])
>>> cv.fit_transform(['pease porridge hot', 'pease porridge cold', 'pease porridge in the pot', 'nine days old']).toarray()
array([[1, 0, 0],
[0, 1... |
Simple async example with tornado python | 22,920,877 | 4 | 2014-04-07T19:05:12Z | 22,947,746 | 12 | 2014-04-08T20:42:23Z | [
"python",
"asynchronous",
"tornado"
] | I want find simple async server example.
I have got some function with lot of wait, database transactions ... etc:
```
def blocking_task(n):
for i in xrange(n):
print i
sleep(1)
return i
```
I need run it function in separated process without blocking. Is it possible? | Tornado is designed to run all your operations in a single thread, but utilize asynchronous I/O to avoid blocking as much as possible. If the DB you're using has asychronous Python bindings (ideally ones geared for Tornado specifically, like [Motor](http://motor.readthedocs.org/en/stable/) for MongoDB or [momoko](https... |
Python raise with two parameters | 22,921,088 | 2 | 2014-04-07T19:16:14Z | 22,921,147 | 7 | 2014-04-07T19:18:44Z | [
"python",
"python-2.7",
"exception"
] | What does `raise A, B` do? And how is it different from what `raise A` does?
Some examples (running at the interpreter of python 2.7):
```
class E(Exception):
pass
e = E()
raise Exception, e
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
__main__.E
raise Exception(e)
Traceback (most ... | `raise` supports up to **three** arguments; the first two are the type and value, the third is a traceback object to use for the exception. The line:
```
raise Exception, value
```
is normally exactly equivalent to:
```
raise Exception(value)
```
so, creating an instance of `Exception()`, passing in the second valu... |
Python MySQL Connector executing second sql statement within cursor loop? | 22,921,181 | 5 | 2014-04-07T19:20:35Z | 22,930,485 | 8 | 2014-04-08T07:35:10Z | [
"python",
"mysql",
"mysql-python",
"mysql-connector"
] | The following logic works with the mysqldb module (see [python mysqldb multiple cursors for one connection](http://stackoverflow.com/questions/11927146/python-mysqldb-multiple-cursors-for-one-connection)), but I am getting the following error with mysql.connector on cursor2.execute(sql)
"Unread result found."
I reali... | MySQL Connector/Python is, by default, non-buffering. This means the data is not fetched automatically and you need to 'consume' **all** rows. (It works with MySQLdb because that driver is buffering by default.)
Using Connector/Python you have to use the buffered-argument set to True for cursor you use as iterator. In... |
elasticsearch-py scan and scroll to return all documents | 22,921,629 | 14 | 2014-04-07T19:45:44Z | 22,940,815 | 7 | 2014-04-08T14:59:45Z | [
"python",
"elasticsearch"
] | I am using elasticsearch-py to connect to my ES database which contains over 3 million documents. I want to return all the documents so I can abstract data and write it to a csv. I was able to accomplish this easily for 10 documents (the default return) using the following code.
```
es=Elasticsearch("glycerin")
query=... | The python scan method is generating a GET call to the rest api. It is trying to send over your scroll\_id over http. The most likely case here is that your scroll\_id is too large to be sent over http and so you are seeing this error because it returns no response.
Because the scroll\_id grows based on the number of ... |
if __name__ == '__main__' in IPython | 22,923,002 | 15 | 2014-04-07T21:00:01Z | 22,923,778 | 10 | 2014-04-07T21:49:33Z | [
"python",
"ipython"
] | I have Python scripts that use the `if __name__ == '__main__'` trick to have some code only run when the script is called as a script and not when it is loaded into the interactive interpreter. However, when I edit these scripts from IPython using the `%edit` command, IPython apparently sets `__name__` to `'__main__'` ... | It sounds like you might just need the `-x` switch:
```
In [1]: %edit
IPython will make a temporary file named: /tmp/ipython_edit_J8j9Wl.py
Editing... done. Executing edited code...
Name is main -- executing
Out[1]: "if __name__ == '__main__':\n print 'Name is main -- executing'\n"
In [2]: %edit -x /tmp/ipython_ed... |
if __name__ == '__main__' in IPython | 22,923,002 | 15 | 2014-04-07T21:00:01Z | 22,923,872 | 10 | 2014-04-07T21:56:50Z | [
"python",
"ipython"
] | I have Python scripts that use the `if __name__ == '__main__'` trick to have some code only run when the script is called as a script and not when it is loaded into the interactive interpreter. However, when I edit these scripts from IPython using the `%edit` command, IPython apparently sets `__name__` to `'__main__'` ... | When working from within Emacs (which I assume is close to what you get with `%edit`), I usually use this trick:
```
if __name__ == '__main__' and '__file__' in globals():
# do what you need
```
For obvious reasons, `__file__` is defined only for `import`'ed modules, and not for interactive shell. |
How to wrap a c++ function which takes in a function pointer in python using SWIG | 22,923,696 | 8 | 2014-04-07T21:43:27Z | 22,965,961 | 9 | 2014-04-09T14:38:56Z | [
"python",
"c++",
"swig"
] | Here is a simplified example of what I want to do. Suppose I have the following c++ code in test.h
```
double f(double x);
double myfun(double (*f)(double x));
```
It doesn't really matter for now what these functions do. The important thing is that myfun takes in a function pointer.
After including the test.h file ... | Note: this answer has a long section on workarounds. If you simply want to use this skip straight to solution 5.
## The problem
You've run into the fact that in Python everything is an object. Before we look at fixing things, first let's understand what's going on as is. I've created a complete example to work with, ... |
Calculate Pandas DataFrame Time Difference Between Two Columns in Hours and Minutes | 22,923,775 | 12 | 2014-04-07T21:49:30Z | 22,924,683 | 13 | 2014-04-07T23:01:08Z | [
"python",
"datetime",
"pandas"
] | I have two columns from and to date in a dataframe
when I try add new column diff with to find the difference between two date using
```
df['diff'] = df['todate'] - df['fromdate']
```
I get the diff column in days if more than 24 hours.
```
2014-01-24 13:03:12.050000,2014-01-26 23:41:21.870000,"2 days, 10:38:09.820... | Pandas timestamp differences returns a datetime.timedelta object. This can easily be converted into hours by using the \*as\_type\* method, like so
```
import pandas
df = pandas.DataFrame(columns=['to','fr','ans'])
df.to = [pandas.Timestamp('2014-01-24 13:03:12.050000'), pandas.Timestamp('2014-01-27 11:57:18.240000'),... |
Mouse Position Python Tkinter | 22,925,599 | 4 | 2014-04-08T00:39:50Z | 22,925,718 | 7 | 2014-04-08T00:53:36Z | [
"python",
"tkinter",
"mouse-pointer"
] | Is there a way to get the position of the mouse and set it as a var? | You could set up a callback to react to `<Motion>` events:
```
import Tkinter as tk
root = tk.Tk()
def motion(event):
x, y = event.x, event.y
print('{}, {}'.format(x, y))
root.bind('<Motion>', motion)
root.mainloop()
```
I'm not sure what kind of variable you want. Above, I set local variables `x` and `y` t... |
Mouse Position Python Tkinter | 22,925,599 | 4 | 2014-04-08T00:39:50Z | 22,943,296 | 9 | 2014-04-08T16:45:38Z | [
"python",
"tkinter",
"mouse-pointer"
] | Is there a way to get the position of the mouse and set it as a var? | At any point in time you can use the method `winfo_pointerx` and `winfo_pointery` to get the x,y coordinates relative to the root window. To convert that to absolute screen coordinates you can get the `winfo_pointerx` or `winfo_pointery`, and from that subtract the respective `winfo_rootx` or `winfo_rooty`
For example... |
Selecting specific rows and columns from NumPy array | 22,927,181 | 19 | 2014-04-08T03:52:52Z | 22,927,889 | 13 | 2014-04-08T04:59:26Z | [
"python",
"arrays",
"numpy",
"multidimensional-array"
] | I've been going crazy trying to figure out what stupid thing I'm doing wrong here.
I'm using NumPy, and I have specific row indices and specific column indices that I want to select from. Here's the gist of my problem:
```
import numpy as np
a = np.arange(20).reshape((5,4))
# array([[ 0, 1, 2, 3],
# [ 4, ... | Fancy indexing requires you to provide all indices for each dimension. You are providing 3 indices for the first one, and only 2 for the second one, hence the error. You want to do something like this:
```
>>> a[[[0, 0], [1, 1], [3, 3]], [[0,2], [0,2], [0, 2]]]
array([[ 0, 2],
[ 4, 6],
[12, 14]])
```
... |
Selecting specific rows and columns from NumPy array | 22,927,181 | 19 | 2014-04-08T03:52:52Z | 22,931,212 | 8 | 2014-04-08T08:10:36Z | [
"python",
"arrays",
"numpy",
"multidimensional-array"
] | I've been going crazy trying to figure out what stupid thing I'm doing wrong here.
I'm using NumPy, and I have specific row indices and specific column indices that I want to select from. Here's the gist of my problem:
```
import numpy as np
a = np.arange(20).reshape((5,4))
# array([[ 0, 1, 2, 3],
# [ 4, ... | As Toan suggests, a simple hack would be to just select the rows first, and then select the columns over *that*.
```
>>> a[[0,1,3], :] # Returns the rows you want
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[12, 13, 14, 15]])
>>> a[[0,1,3], :][:, [0,2]] # Selects the columns you want as well
a... |
Sorting a list of dates in Python | 22,931,470 | 2 | 2014-04-08T08:22:59Z | 22,931,508 | 7 | 2014-04-08T08:24:56Z | [
"python",
"sorting",
"date"
] | I have a list in python that is directories who's names are the date they were created;
```
import os
ConfigDir = "C:/Config-Archive/"
for root, dirs, files in os.walk(ConfigDir):
if len(dirs) == 0: # This directory has no subfolder
ConfigListDir = root + "/../" # Step back up one directory
ConfigL... | You'd parse the date in a sorting key:
```
from datetime import datetime
sorted(ConfigList, key=lambda d: datetime.strptime(d, '%d-%m-%Y'))
```
Demo:
```
>>> from datetime import datetime
>>> ConfigList = ['01-02-2014', '01-03-2014', '01-08-2013', '01-09-2013', '01-10-2013']
>>> sorted(ConfigList, key=lambda d: dat... |
How to use gdb python debugging extension inside virtualenv | 22,931,774 | 8 | 2014-04-08T08:37:34Z | 30,430,059 | 7 | 2015-05-25T01:13:57Z | [
"python",
"gdb",
"virtualenv"
] | I'm running ubuntu, and installed the python-dbg package. When trying to use the installed version directly everything works great:
```
$ gdb python2.7-dbg
GNU gdb (Ubuntu/Linaro 7.4-2012.04-0ubuntu2.1) 7.4-2012.04
---x snipped x---
Reading symbols from /usr/bin/python2.7-dbg...done.
(gdb) r
Starting program: /usr/bin... | @itai's answer only partially worked for me on Ubuntu Trusty (14.04). I found a couple of other things worked better:
`sudo apt-get install python2.7-dbg`
then, in the virtualenv:
```
. bin/activate
mkdir bin/.debug
ln -s /usr/lib/debug/usr/bin/python2.7-gdb.py bin/.debug/python-gdb.py
ln -s /usr/lib/debug/usr/bin/p... |
convert rgba color codes 255,255,255,255 to kivy color codes in 1,1,1,1 | 22,932,242 | 4 | 2014-04-08T08:58:30Z | 22,932,597 | 8 | 2014-04-08T09:13:41Z | [
"python",
"colors",
"kivy"
] | In order to specify any color value in kivy we need to specify values from 0 to 1 i.e.
color defaults to [1,1,1,1] and can contain values between 0 and 1 , however rgba codes which are readily available for other languages are always specified from 0 to 255 and i usually refer them from any web link as in
<http://www.r... | I think you can just divide it by 255:
```
float_color = color / 255.0
``` |
python split string every 3rd value but into a nested format | 22,932,552 | 5 | 2014-04-08T09:11:16Z | 22,932,717 | 12 | 2014-04-08T09:19:22Z | [
"python"
] | I have a list like so:
```
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
```
I want it to look like so
```
[['a', 'b', 'c'],['d', 'e', 'f'],['g', 'h', 'i']]
```
what's the most efficient way to do this?
edit:
what about going the other way?
```
[['a', 'b', 'c'],['d', 'e', 'f'],['g', 'h', 'i']]
```
-->
```
['a',... | You can do what you want with a simple list comprehension.
```
>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> [a[i:i+3] for i in range(0, len(a), 3)]
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
```
If you want the last sub-list to be padded you can do this before the list comprehension:
```
>>> padding = 0
>>> a += [paddin... |
pylibmc installation error using pip in python | 22,934,082 | 6 | 2014-04-08T10:19:37Z | 22,934,437 | 12 | 2014-04-08T10:35:58Z | [
"python",
"django",
"installation",
"pip"
] | I am trying to install pylibmc using pip inside my virtual env and getting the below error
```
pip install pylibmc
Downloading/unpacking pylibmc
Downloading pylibmc-1.3.0.tar.gz (49kB): 49kB downloaded
Running setup.py egg_info for package pylibmc
warning: no files found matching 'LICENSE'
warning: no fil... | Actually we need to install dev package like below
```
sudo apt-get install libmemcached-dev
``` |
How to clear variables in ipython? | 22,934,204 | 48 | 2014-04-08T10:24:34Z | 22,934,273 | 66 | 2014-04-08T10:27:42Z | [
"python",
"memory",
"ipython"
] | Sometimes I rerun a script within the same ipython session and I get bad surprises when variables haven't been cleared. How do I clear all variables?
And is it possible to force this somehow every time I invoke the magic command %run?
Thanks | `%reset` seems to clear defined variables. |
How to clear variables in ipython? | 22,934,204 | 48 | 2014-04-08T10:24:34Z | 26,905,790 | 25 | 2014-11-13T09:48:34Z | [
"python",
"memory",
"ipython"
] | Sometimes I rerun a script within the same ipython session and I get bad surprises when variables haven't been cleared. How do I clear all variables?
And is it possible to force this somehow every time I invoke the magic command %run?
Thanks | To erase a single variable:
```
reset_selective name_variable
```
can be useful!
For more information on specific behaviour type:
```
reset?
``` |
numpy: multiply arrays rowwise | 22,934,219 | 3 | 2014-04-08T10:25:06Z | 22,934,388 | 8 | 2014-04-08T10:33:20Z | [
"python",
"numpy"
] | I have those arrays:
```
a = np.array([
[1,2],
[3,4],
[5,6],
[7,8]])
b = np.array([1,2,3,4])
```
and I want them to multiply like so:
```
[[1*1, 2*1],
[3*2, 4*2],
[5*3, 6*3],
[7*4, 8*4]]
```
... basically `out[i] = a[i] * b[i]`, where `a[i].shape` is `(2,)` and `b[i]` then is a scalar.
What's ... | add an axis to b:
```
>>> np.multiply(a, b[:, np.newaxis])
array([[ 1, 2],
[ 6, 8],
[15, 18],
[28, 32]])
``` |
PyDrive: cannot write file to specific GDrive folder | 22,934,525 | 7 | 2014-04-08T10:39:56Z | 22,934,892 | 17 | 2014-04-08T10:57:08Z | [
"python",
"google-drive-sdk"
] | I'm trying to copy files from a local machine to a specific folder in GDrive using PyDrive. If the target folder does not yet exist, I want to create it. Here is the relevant section of my code:
```
gfile = drive.CreateFile({'title':'dummy.csv',
'mimeType':'text/csv',
'parent': tgt_folder_id})
gfile.S... | OK, looks like this is how you do it:
```
gfile = drive.CreateFile({'title':'dummy.csv', 'mimeType':'text/csv',
"parents": [{"kind": "drive#fileLink","id": tgt_folder_id}]})
```
The "parents" map is used in the Google Drive SDK, which PyDrive is supposed to wrap. But the very few examples I've seen with PyDri... |
Merging two strings | 22,937,302 | 2 | 2014-04-08T12:39:34Z | 22,937,432 | 8 | 2014-04-08T12:44:17Z | [
"python",
"string",
"python-3.x"
] | ```
a = '---e'
b = 'e---'
for i in a:
c=''
for k in b:
if i == k:
c += i
else:
c += '-'
print(c)
```
Result:
```
e---
```
I wanted to merge a and b so that the result would be 'e--e'. Can this be done using for loops? Can someone please fix my code or suggest a different approach. I'd ... | One possibility, taking the character from the first string, unless that one is `-`:
```
>>> a = '---e'
>>> b = 'e---'
>>> ''.join(x if x != '-' else y for x, y in zip(a, b))
'e--e'
```
This works by first zipping the two strings. That way, each character is paired with the character from the other string at the same... |
Pandas: Reading Excel with merged cells | 22,937,650 | 4 | 2014-04-08T12:51:38Z | 22,938,181 | 7 | 2014-04-08T13:13:43Z | [
"python",
"excel",
"pandas"
] | I have Excel files with multiple sheets, each of which looks a little like this (but much longer):
```
Sample CD4 CD8
Day 1 8311 17.3 6.44
8312 13.6 3.50
8321 19.8 5.88
8322 13.5 4.09
Day 2 8311 16.0 4.92
8312 5.67 2.28
8321 ... | You could use the [Series.fillna](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.fillna.html) method to forword-fill in the NaN values:
```
df.index = pd.Series(df.index).fillna(method='ffill')
```
---
For example,
```
In [42]: df
Out[42]:
Sample CD4 CD8
Day 1 8311 17.30 6.44
... |
Error trying to install Postgres for python (psycopg2) | 22,938,679 | 39 | 2014-04-08T13:33:49Z | 22,940,034 | 87 | 2014-04-08T14:26:45Z | [
"python",
"django",
"heroku",
"psycopg2"
] | I tried to install psycopg2 to my environment, but I get the following error:
```
(venv)avlahop@apostolos-laptop:~/development/django/rhombus-dental$ sudo pip install psycopg2
Downloading/unpacking psycopg2,
Downloading psycopg2-2.5.2.tar.gz (685kB): 685kB downloaded
Running setup.py egg_info for package psycopg2
Ins... | The `python-dev` package is required for compilation of Python extensions written in C or C++, like `psycopg2`. If you're running a Debian-based distribution (e.g. Ubuntu), you can install `python-dev` by running
```
apt-get install python-dev
```
or
```
apt-get install python3-dev
```
depending on your python vers... |
Error trying to install Postgres for python (psycopg2) | 22,938,679 | 39 | 2014-04-08T13:33:49Z | 29,525,507 | 16 | 2015-04-08T21:17:12Z | [
"python",
"django",
"heroku",
"psycopg2"
] | I tried to install psycopg2 to my environment, but I get the following error:
```
(venv)avlahop@apostolos-laptop:~/development/django/rhombus-dental$ sudo pip install psycopg2
Downloading/unpacking psycopg2,
Downloading psycopg2-2.5.2.tar.gz (685kB): 685kB downloaded
Running setup.py egg_info for package psycopg2
Ins... | For `Ubuntu 14.04`, from Docker image `python:3.4.3-slim` this combination worked for me:
```
sudo apt-get update
sudo apt-get install -y build-essential
sudo apt-get install -y python3.4-dev
sudo apt-get install -y libpq-dev
pip3 install psycopg2
```
Note `build-essential` package. It was crucial in my case. |
Why are explicit calls to magic methods slower than "sugared" syntax? | 22,940,769 | 10 | 2014-04-08T14:57:53Z | 22,941,041 | 12 | 2014-04-08T15:08:59Z | [
"python",
"performance",
"magic-methods",
"syntactic-sugar"
] | I was messing around with a small custom data object that needs to be hashable, comparable, and fast, when I ran into an odd-looking set of timing results. Some of the comparisons (and the hashing method) for this object simply delegate to an attribute, so I was using something like:
```
def __hash__(self):
return... | Two reasons:
* The API lookups look at the *type* only. They don't look at `self.foo.__hash__`, they look for `type(self.foo).__hash__`. That's one less dictionary to look in.
* The C slot lookup is faster than the pure-Python attribute lookup (which will use `__getattribute__`); instead looking up the method objects ... |
Fastest file format for read/write operations with Pandas and/or Numpy | 22,941,147 | 4 | 2014-04-08T15:13:45Z | 22,941,306 | 8 | 2014-04-08T15:21:45Z | [
"python",
"numpy",
"pandas"
] | I've been working for a while with very large DataFrames and I've been using the csv format to store input data and results. I've noticed that a lot of time goes into reading and writing these files which, for example, dramatically slows down batch processing of data. I was wondering if the file format itself is of rel... | Use HDF5. Beats writing flat files hands down. And you can query. Docs are [here](http://pandas.pydata.org/pandas-docs/stable/io.html#hdf5-pytables)
Here's a [perf comparison vs SQL](http://stackoverflow.com/questions/16628329/hdf5-and-sqlite-concurrency-compression-i-o-performance). Updated to show SQL/HDF\_fixed/HDF... |
Logging to Instagram using Python requests | 22,941,347 | 5 | 2014-04-08T15:23:32Z | 23,025,139 | 7 | 2014-04-12T01:49:18Z | [
"python",
"instagram"
] | I am trying to write a script in python, to log into `http://insta.friendorfollow.com/` and get the list of the people that are not following back. I want to use "requests module", so far I made numerous attempts with no luck. My code is as follow :
```
import requests, re
f = open('file', 'w')
r = requests.get('http... | All is fine now,
```
#!/usr/bin/env python
username = "username"
password = "password"
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import re
driver = webdriver.PhantomJS()
driver.get("http://insta.friendorfollow.com")
driver.find_elements_by_tag_name("a")[1].click()
print "Perime... |
Ordering a list of tuples in python | 22,943,785 | 3 | 2014-04-08T17:10:04Z | 22,943,901 | 7 | 2014-04-08T17:15:30Z | [
"python",
"list",
"sorting"
] | I have a list, my\_list:
```
[['28/02/2014, apples']
['09/07/2014, oranges']
['22/04/2014, bananas']
['14/03/2014, tomatoes']]
```
which I am trying to order by date. This is the code I am using:
```
def display(my_list):
for item in my_list:
x = ([item[0] + ": " + item[1]])
print x
```
I've tri... | You can use `sorted()` with applying a `key` function that takes the first item from every sublist, splits it by `:` and converts the part before the colon to `datetime` using `strptime()`:
```
>>> from datetime import datetime
>>> l = [['28/02/2014: apples'], ['09/07/2014: oranges'], ['22/04/2014: bananas'], ['14/03/... |
sum of absolute differences of a number in an array | 22,943,787 | 16 | 2014-04-08T17:10:05Z | 22,944,263 | 16 | 2014-04-08T17:33:49Z | [
"python",
"arrays",
"algorithm"
] | I want to calculate the sum of absolute differences of a number at index i with all integers up to index i-1 in o(n). But i am not able to think of any approach better than o(n^2) .
For E.g. :
```
[3,5,6,7,1]
```
array with absolute sum will be(for integer at index i sum will be at index i in another array):
```
[0... | I can offer an O(n log n) solution for a start: Let fi be the i-th number of the result. We have:

When walking through the array from left to right and maintain a binary search tree of the elements *a0* to *ai-1*, we can solve all parts of the formul... |
class labels in Pandas scattermatrix | 22,943,894 | 5 | 2014-04-08T17:15:11Z | 22,976,730 | 8 | 2014-04-10T00:57:15Z | [
"python",
"matplotlib",
"pandas",
"scatter-plot"
] | This question has been asked before, [Multiple data in scatter matrix](http://stackoverflow.com/q/21131707/1586229), but didn't receive an answer.
I'd like to make a scatter matrix, something like [in the pandas docs](http://pandas.pydata.org/pandas-docs/stable/visualization.html#scatter-plot-matrix), but with differe... | ### Update: This functionality is now in the latest version of Seaborn. [Here's an example](http://stanford.edu/~mwaskom/software/seaborn/examples/scatterplot_matrix.html).
The following was my stopgap measure:
```
def factor_scatter_matrix(df, factor, palette=None):
'''Create a scatter matrix of the variables in... |
Check if requirements are up to date | 22,944,861 | 20 | 2014-04-08T18:06:04Z | 22,947,854 | 16 | 2014-04-08T20:48:21Z | [
"python",
"package",
"pip",
"pypi",
"requirements.txt"
] | I'm using `pip` [requirements files](http://pip.readthedocs.org/en/latest/user_guide.html#requirements-files) for keeping my dependency list.
I also try to follow best practices for managing dependencies and provide precise package versions inside the requirements file. For example:
```
Django==1.5.1
lxml==3.0
```
*... | Just found a python package specifically for the task - [piprot](https://github.com/sesh/piprot), with the following slogan:
```
How rotten are your requirements?
```
It's very straightforward to work with:
```
$ piprot requirements.txt
Django (1.5.1) is 315 days out of date. Latest is 1.6.2
lxml (3.0) is 542 days ... |
Check if requirements are up to date | 22,944,861 | 20 | 2014-04-08T18:06:04Z | 23,102,728 | 40 | 2014-04-16T07:28:47Z | [
"python",
"package",
"pip",
"pypi",
"requirements.txt"
] | I'm using `pip` [requirements files](http://pip.readthedocs.org/en/latest/user_guide.html#requirements-files) for keeping my dependency list.
I also try to follow best practices for managing dependencies and provide precise package versions inside the requirements file. For example:
```
Django==1.5.1
lxml==3.0
```
*... | Pip has this functionality built-in. Assuming that you're inside your virtualenv type:
```
$ pip list --outdated
psycopg2 (Current: 2.5.1 Latest: 2.5.2)
requests (Current: 2.2.0 Latest: 2.2.1)
$ pip install -U psycopg2 requests
```
After that new versions of psycopg2 and requests will be downloaded and installed. Th... |
Check if a string contains at least one of the strings in a list | 22,945,032 | 7 | 2014-04-08T18:13:55Z | 22,945,071 | 8 | 2014-04-08T18:15:31Z | [
"python",
"list",
"match"
] | I'm trying to do a matching using python.
I have a list of string (len~3000), and a file, and I want to check if for each line in the file, it has at least one of the strings in the list.
The most straight forward way is to check one by one, but it takes time (not that long though).
Is there a way that I can search ... | You can use [`any`](https://docs.python.org/3/library/functions.html#any) and a [generator expression](http://legacy.python.org/dev/peps/pep-0289/):
```
# Please do not name a list "list" -- it overrides the built-in
lst = ["a", "b", "c"]
if any(s in line for s in lst):
# Do stuff
```
The above code will test if ... |
Flask-Admin ModelView custom validation? | 22,947,083 | 4 | 2014-04-08T20:05:25Z | 23,068,912 | 7 | 2014-04-14T19:44:49Z | [
"python",
"validation",
"flask-admin",
"flask-peewee"
] | I'm studying Flask-Admin combined with PeeWee Backend ModelView (but my question may be applied to SQLAlchemy backend too), and there are two things I could not find in the docs or examples:
(1). When I my model has an unique field and I test/try to duplicate it, I get a default Flask crash screen, with the message: "... | I guess I've found some things that help, but don't completelly answer my question.
I posted an example on PasteBin: <http://pastebin.com/siwiaJAw>
first, I could not find a 'before save' step, but I've found how to add field-level custom validation, which helps in the cases of creates and updates.
If you check the ... |
Don't argparse read unicode from commandline? | 22,947,181 | 7 | 2014-04-08T20:10:53Z | 22,947,334 | 8 | 2014-04-08T20:19:38Z | [
"python",
"unicode",
"argparse"
] | Running Python 2.7
When executing:
```
$ python client.py get_emails -a "åäö"
```
I get:
```
usage: client.py get_emails [-h] [-a AREA] [-t {rfc2822,plain}]
client.py get_emails: error: argument -a/--area: invalid unicode value: '\xc3\xa5\xc3\xa4\xc3\xb6'
```
This is my parser:
```
def _argparse():
desc = ... | You can try
```
type=lambda s: unicode(s, 'utf8')
```
instead of
```
type=unicode
```
Without encoding argument unicode() defaults to ascii. |
Don't argparse read unicode from commandline? | 22,947,181 | 7 | 2014-04-08T20:10:53Z | 23,085,282 | 9 | 2014-04-15T13:33:22Z | [
"python",
"unicode",
"argparse"
] | Running Python 2.7
When executing:
```
$ python client.py get_emails -a "åäö"
```
I get:
```
usage: client.py get_emails [-h] [-a AREA] [-t {rfc2822,plain}]
client.py get_emails: error: argument -a/--area: invalid unicode value: '\xc3\xa5\xc3\xa4\xc3\xb6'
```
This is my parser:
```
def _argparse():
desc = ... | The command-line arguments are encoded using `sys.getfilesystemencoding()`:
```
import sys
def commandline_arg(bytestring):
unicode_string = bytestring.decode(sys.getfilesystemencoding())
return unicode_string
# ...
parser_get_emails.add_argument('-a', '--area', type=commandline_arg)
```
Note: You don't nee... |
Flask example with POST | 22,947,905 | 4 | 2014-04-08T20:51:21Z | 22,949,613 | 9 | 2014-04-08T22:41:54Z | [
"python",
"rest",
"flask",
"lxml"
] | Suppose the following route which accesses an xml file to replace the text of a specific tag with a given xpath (?key=):
```
@app.route('/resource', methods = ['POST'])
def update_text():
# CODE
```
Then, I would use cURL like this:
```
curl -X POST http://ip:5000/resource?key=listOfUsers/user1 -d "John"
```
Th... | **Before actually answering your question:**
Parameters in a URL (e.g. `key=listOfUsers/user1`) are `GET` parameters and you shouldn't be using them for `POST` requests. A quick explanation of the difference between GET and POST can be found [here](http://stackoverflow.com/questions/3477333/what-is-the-difference-betw... |
"ImportError: No module named BeautifulSoup" error even after installation | 22,949,324 | 3 | 2014-04-08T22:20:18Z | 22,949,342 | 7 | 2014-04-08T22:21:58Z | [
"python",
"module",
"beautifulsoup",
"failed-installation"
] | I'm running into the following error:
```
Traceback (most recent call last):
File "C:\Python27\files\samplefileoutput.py", line 1, in <module>
import BeautifulSoup
ImportError: No module named BeautifulSoup
```
when I try to run the following file:
```
import BeautifulSoup
f = open('c:\output.txt', 'a')
f.writ... | Beautiful Soup 4's module is `bs4`.
```
from bs4 import BeautifulSoup
```
will work, or
```
import bs4
```
if you want to import the entire module. |
mysql_config not found when installing mysqldb python interface for mariadb 10 Ubuntu 13.10 | 22,949,654 | 9 | 2014-04-08T22:44:56Z | 22,949,839 | 12 | 2014-04-08T22:59:02Z | [
"python",
"mysql",
"sqlalchemy",
"mysql-python",
"mariadb"
] | After I installed Mariadb 10 the Mysql workbench and JPDB client both connect and work fine so next step was get programming with Python (using SQLAlchemy) which seems to require MySQL-python so I went to update that and got:
"mysql\_config not found" I looked in the "usual places" and did not see a file...
So I follo... | Found it! The case is that mariadb has a compatible package, if you have the ppa setup as in <http://downloads.mariadb.org/>. Just "sudo apt-get install libmariadbclient-dev". thanks to <http://data-matters.blogspot.com/2013/08/install-mysql-python-with-mariadb.html>
After this the mysql-python installs correctly |
mysql_config not found when installing mysqldb python interface for mariadb 10 Ubuntu 13.10 | 22,949,654 | 9 | 2014-04-08T22:44:56Z | 25,430,349 | 11 | 2014-08-21T15:34:27Z | [
"python",
"mysql",
"sqlalchemy",
"mysql-python",
"mariadb"
] | After I installed Mariadb 10 the Mysql workbench and JPDB client both connect and work fine so next step was get programming with Python (using SQLAlchemy) which seems to require MySQL-python so I went to update that and got:
"mysql\_config not found" I looked in the "usual places" and did not see a file...
So I follo... | For Centos 7.0 install the following:
```
yum install mariadb-devel
``` |
dot product of two 1D vectors in numpy | 22,949,966 | 3 | 2014-04-08T23:11:12Z | 22,950,012 | 8 | 2014-04-08T23:16:04Z | [
"python",
"numpy"
] | I'm working with `numpy` in `python` to calculate a vector multiplication.
I have a vector x of dimensions n x 1 and I want to calculate x\*x\_transpose.
This gives me problems because `x.T` or `x.transpose()` doesn't affect a 1 dimensional vector (`numpy` represents vertical and horizontal vectors the same way).
*But... | You are essentially computing an [Outer Product](http://en.wikipedia.org/wiki/Outer_product).
You can use `np.outer`.
```
In [15]: a=[1,2,3]
In [16]: np.outer(a,a)
Out[16]:
array([[1, 2, 3],
[2, 4, 6],
[3, 6, 9]])
``` |
Check requirements for python 3 support | 22,951,451 | 11 | 2014-04-09T01:57:41Z | 22,951,587 | 10 | 2014-04-09T02:14:13Z | [
"python",
"python-3.x",
"porting",
"2to3",
"requirements.txt"
] | I have several python projects with different set of dependencies listed in [pip requirements files](http://pip.readthedocs.org/en/latest/user_guide.html#requirements-files). I've started to think about porting the code to python 3, but I need to know if my dependencies are already there.
Is it possible to check what ... | With the help of @thefourtheye and [py3readiness.org](http://py3readiness.org/) sources, I've found exactly what I needed.
[`caniusepython3`](https://pypi.python.org/pypi/caniusepython3) module by Brett Cannon:
> Determine what projects are blocking you from porting to Python 3
>
> This script takes in a set of depen... |
PyCharm noinspection for whole file? | 22,951,489 | 4 | 2014-04-09T02:01:16Z | 22,959,267 | 10 | 2014-04-09T10:07:51Z | [
"python",
"pycharm",
"py.test"
] | Is it possible to disable an inspection for the whole file in PyCharm?
The reason this is needed is when dealing with [py.test](http://pytest.org/). It uses fixtures which appear to shadow function parameters, and at the same time cause unresolved references. e.g.:
```
from myfixtures import user # Unused import sta... | > Is it possible to disable an inspection for the whole file in PyCharm?
Yes. This answer is for this question only (and not about *"Maybe there's another way to fix these problems? Maybe I'm using py.test incorrectly?"*).
1. "Settings | Scopes"
2. Create new scope that would include such "unwanted" file(s)
3. "Setti... |
Python 2.X adding single quotes around a string | 22,952,543 | 6 | 2014-04-09T04:01:21Z | 22,952,645 | 7 | 2014-04-09T04:12:46Z | [
"python",
"python-2.7"
] | Currently to add single quotes around a string, the best solution I came up with was to make a small wrapper function.
```
def foo(s1):
return "'" + s1 + "'"
```
Is there an easier more pythonic way of doing this? | What about:
```
def foo(s1):
return "'%s'" % s1
``` |
How to extract all coefficients in sympy | 22,955,888 | 9 | 2014-04-09T07:39:55Z | 23,000,881 | 10 | 2014-04-10T23:24:41Z | [
"python",
"sympy"
] | You can get a coefficient of a specific term by using coeff();
```
x, a = symbols("x, a")
expr = 3 + x + x**2 + a*x*2
expr.coeff(x)
# 2*a + 1
```
Here I want to extract all the coefficients of x, x\*\*2 (and so on), like;
```
# for example
expr.coefficients(x)
# want {1: 3, x: (2*a + 1), x**2: 1}
```
There is a met... | The easiest way is to use `Poly`
```
>>> a = Poly(expr, x)
>>> a.coeffs()
[1, 2*a + 1, 3]
``` |
How to extract all coefficients in sympy | 22,955,888 | 9 | 2014-04-09T07:39:55Z | 24,127,329 | 15 | 2014-06-09T19:16:34Z | [
"python",
"sympy"
] | You can get a coefficient of a specific term by using coeff();
```
x, a = symbols("x, a")
expr = 3 + x + x**2 + a*x*2
expr.coeff(x)
# 2*a + 1
```
Here I want to extract all the coefficients of x, x\*\*2 (and so on), like;
```
# for example
expr.coefficients(x)
# want {1: 3, x: (2*a + 1), x**2: 1}
```
There is a met... | `all_coeffs()` can be sometime better than using `coeffs()` for a `Poly`.
The difference lies in output of these both. `coeffs()` returns a list containing all coefficients which has a value and ignores those whose coefficient is `0` whereas `all_coeffs()` returns all coefficients including those whose coefficient is z... |
Why does numpy.power return 0 for small exponents while math.pow returns the correct answer? | 22,956,139 | 49 | 2014-04-09T07:52:37Z | 22,956,234 | 34 | 2014-04-09T07:57:04Z | [
"python",
"numpy"
] | ```
In [25]: np.power(10,-100)
Out[25]: 0
In [26]: math.pow(10,-100)
Out[26]: 1e-100
```
I would expect both the commands to return 1e-100. This is not a precision issue either, since the issue persists even after increasing precision to 500. Is there some setting which I can change to get the correct answer? | numpy method assumes you want integer returned since you supplied an integer.
```
np.power(10.0,-100)
```
works as you would expect. |
Why does numpy.power return 0 for small exponents while math.pow returns the correct answer? | 22,956,139 | 49 | 2014-04-09T07:52:37Z | 22,956,238 | 68 | 2014-04-09T07:57:15Z | [
"python",
"numpy"
] | ```
In [25]: np.power(10,-100)
Out[25]: 0
In [26]: math.pow(10,-100)
Out[26]: 1e-100
```
I would expect both the commands to return 1e-100. This is not a precision issue either, since the issue persists even after increasing precision to 500. Is there some setting which I can change to get the correct answer? | Oh, it's much "worse" than that:
```
In [2]: numpy.power(10,-1)
Out[2]: 0
```
But this is a hint to what's going on: `10` is an integer, and `numpy.power` doesn't coerce the numbers to floats. But this works:
```
In [3]: numpy.power(10.,-1)
Out[3]: 0.10000000000000001
In [4]: numpy.power(10.,-100)
Out[4]: 1e-100... |
Remove tuple from list of tuples if certain condition is met | 22,957,606 | 2 | 2014-04-09T09:00:53Z | 22,957,628 | 7 | 2014-04-09T09:01:41Z | [
"python",
"list",
"python-2.7",
"tuples"
] | I have a list of tuples that look like this;
```
ListTuples = [(100, 'AAA'), (80, 'BBB'), (20, 'CCC'), (40, 'DDD')]
```
I want to remove the tuples when the first element of the tuple is less than 50. The OutputList will look like this;
```
OutputList = [(100, 'AAA'), (80, 'BBB')]
```
How can this be done in python... | You can easily do it as:
```
out_tup = [i for i in in_tup if i[0] >= 50]
[Out]: [(100, 'AAA'), (80, 'BBB')]
```
This simply creates a new list of tuples with only those tuples whose first element is greater than or equal to 50. Same result, however the approach is different. Instead of removing invalid tuples you ac... |
Counting the character recursively | 22,958,263 | 9 | 2014-04-09T09:29:08Z | 22,958,308 | 20 | 2014-04-09T09:30:59Z | [
"python",
"recursion"
] | ```
def count_m_recursive(sentence):
s = len(sentence)
if s == 0:
return 0
elif sentence[0] == 'm':
return 1
else:
return count_m_recursive(sentence[1:s-1]
```
This is my code. So if `count_m_recursive('my oh my')` I should get 2
What is wrong with the code ? | Two things are wrong:
1. You are cutting off the *last* character on each recursive call:
```
return count_m_recursive(sentence[1:s-1])
```
Don't limit the call to `s-1`, the end index is *not* included.
2. You don't want to ignore the rest of the text when you find an `m` at the start; your version retu... |
Counting the character recursively | 22,958,263 | 9 | 2014-04-09T09:29:08Z | 22,959,490 | 11 | 2014-04-09T10:17:00Z | [
"python",
"recursion"
] | ```
def count_m_recursive(sentence):
s = len(sentence)
if s == 0:
return 0
elif sentence[0] == 'm':
return 1
else:
return count_m_recursive(sentence[1:s-1]
```
This is my code. So if `count_m_recursive('my oh my')` I should get 2
What is wrong with the code ? | For the fun, you can write the entire thing as an anonymous lambda expression as follows:
```
def make_funny_func():
# wrapped the code with return clause to emphasize that it is
# anonymous ;)
return (
# Y combinator
(lambda f: (lambda x: x(x))(lambda y: f(lambda a: y(y)(a))))
# o... |
What happens when a Python yield statement has no expression? | 22,960,397 | 5 | 2014-04-09T10:56:35Z | 22,960,435 | 8 | 2014-04-09T10:58:06Z | [
"python",
"generator",
"yield"
] | I'm a C# programmer trying to understand some Python code. The code in question is a generator function, and looks like this:
```
def func():
oldValue = curValue
yield
curValue = oldValue
```
If I understand this correctly, this will generate a iterable sequence with one member. However, there is no expre... | It'll yield `None`; just like an empty `return` expression would:
```
>>> def func():
... yield
...
>>> f = func()
>>> next(f) is None
True
```
You'd use it to *pause code*. Everything before the `yield` is run when you first call `next()` on the generator, everything after the `yield` is only run when you call ... |
the reason: python string assignments accidentally change '\b' into '\x08' and '\a' into '\x07', why Python did this? | 22,961,145 | 7 | 2014-04-09T11:31:08Z | 22,961,200 | 9 | 2014-04-09T11:33:45Z | [
"python",
"string"
] | Had two answers and some comments, mentioned another question, but all had not provided REASON, why Python did this changes? such as '/b' is '/x08' is just the result, but why?
Cheers.
I try to add this path"F:\big data\Python\_coding\diveintopython-5.4\py"
into sys.path, therefore, the code under it could be imported... | Your strings are being escaped. Check out the docs on [string literals](https://docs.python.org/2.0/ref/strings.html):
> The backslash () character is used to escape characters that
> otherwise have a special meaning, such as newline, backslash itself,
> or the quote character. String literals may optionally be prefix... |
Min-Max difference in continuous part of certain length within a np.array | 22,962,240 | 3 | 2014-04-09T12:15:49Z | 22,962,528 | 7 | 2014-04-09T12:27:30Z | [
"python",
"numpy"
] | I have a numpy array of values like this:
```
a = np.array((1, 3, 4, 5, 10))
```
In this case the array has length 5. Now I want to know the difference between the lowest and highest value in the array, but only within a certain continuous part of the array, for example with length 3.
So in this case it would be the... | This is a bit tricky to get done in a vectorised way in Numpy. One option is to use `numpy.lib.stride_tricks.as_strided`, which requires care, because it allows to access arbitrary memory. Here's an example for a window size of `k = 3`:
```
>>> k = 3
>>> shape = (len(a) - k + 1, k)
>>> b = numpy.lib.stride_tricks.as_s... |
Creating a zero-filled pandas data frame | 22,963,263 | 13 | 2014-04-09T12:56:30Z | 22,964,673 | 19 | 2014-04-09T13:49:36Z | [
"python",
"pandas",
"dataframe"
] | What is the best way to create a zero-filled pandas data frame of a given size?
I have used:
```
zero_data = np.zeros(shape=(len(data),len(feature_list)))
d = pd.DataFrame(zero_data, columns=feature_list)
```
Is there a better way to do it? | You can try this:
```
d = pd.DataFrame(0, index=np.arange(len(data)), columns=feature_list)
``` |
python find the index of the last value in a list that is not a "None" | 22,964,733 | 2 | 2014-04-09T13:51:46Z | 22,964,840 | 7 | 2014-04-09T13:55:51Z | [
"python",
"list"
] | I have a list with values and a bunch of `None`. For example:
```
a = ['a', 'b', None, 4, 5, None, 5, 4, None, 7, None, None, None, None]
```
I'm looking for the quickest (shortest number of characters) way to find the index of, in this case `7`, the last non-`None` value.
`9` should be the output. | I think it's hard to beat something very obvious, like:
```
def get_last(a):
for i, e in enumerate(reversed(a)):
if e is not None:
return len(a) - i - 1
return -1
```
Note that [`reversed()`](https://docs.python.org/2/library/functions.html#reversed) simply creates a reversed iterator, it doesn't copy t... |
Pandas Series to json and back | 22,965,985 | 5 | 2014-04-09T14:39:47Z | 22,966,563 | 8 | 2014-04-09T15:01:51Z | [
"python",
"json",
"pandas"
] | I have some problems converting a simple Pandas Series into a json string and back. Here's my attempt
```
import pandas as pd
f = pd.Series(data=[1.0,2.0,3.0],index=[10,20,30])
x = f.to_json()
a = pd.read_json(x)
```
This results in ValueError: If using all scalar values, you must pass an Index.
The json String x lo... | You need to specify the type of object (default is `DataFrame`) and the format of the JSON string. More info [here](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.json.read_json.html).
This should work:
```
a = pd.read_json(x, typ='series', orient='records')
``` |
Output from <= in python is weird | 22,966,317 | 3 | 2014-04-09T14:52:34Z | 22,966,336 | 13 | 2014-04-09T14:53:15Z | [
"python",
"list",
"set"
] | ```
>>> [6,7,8,16,18] <= [6,8,11,13,17]
True
```
`<=` Should return `True` if every element in left set is in right set. But `7,16,18` are not in the right list. Even if I put the numbers in sets like so
```
>>> (6,7,8,16,18) <= (6,8,11,13,17)
True
```
<https://docs.python.org/2/library/sets.html> | You are using **lists and tuples**, not sets. Use [`{...}` for set literals](https://docs.python.org/3/reference/expressions.html#set-displays):
```
>>> {6, 7, 8, 16, 18} <= {6, 8, 11, 13, 17}
False
```
or use [`set([...])`](https://docs.python.org/3/library/functions.html#func-set) or [`frozenset([...])`](https://do... |
How to filter filter_horizontal in Django admin? | 22,968,631 | 3 | 2014-04-09T16:31:08Z | 23,140,826 | 12 | 2014-04-17T18:34:26Z | [
"python",
"django",
"django-admin"
] | I'm looking for a way to use filter\_horizontal on the base of a filtered queryset.
I've tried to use it with a custom manager:
**In models.py:**
```
class AvailEquipManager(models.Manager):
def get_query_set(self):
return super(AvailEquipManager, self).get_query_set().filter(id=3)
class Equipment(model... | I found a solution by adapting the answer to a different question which I found in [Google Groups](https://groups.google.com/forum/#!topic/django-users/-46GAa0FMlc)
It works with a custom ModelForm like so:
Create a new forms.py:
```
from django import forms
from models import Equipment
class EquipmentModelForm(for... |
How is irange() any different from range() or xrange()? | 22,971,078 | 10 | 2014-04-09T18:31:35Z | 22,971,204 | 14 | 2014-04-09T18:36:31Z | [
"python",
"range",
"generator",
"xrange"
] | I was going through Python Generators Wiki when I came across this [RangeGenerator](https://wiki.python.org/moin/RangeGenerator) page which talks about `irange()` -
> This will let us iterator over large spans of numbers without
> resorting to xrange, which is a lazy list as opposed to a generator.
I can't seem to un... | `irange()` returns a generator type, which *can only be iterated over*. Nothing else. Once you iterated over it, the generator is exhausted and can not be iterated over again.
The Python 2 [`xrange()` type](https://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange) a... |
Gunicorn (Python3.4 and 3.3) sends in response only headers without data | 22,974,024 | 3 | 2014-04-09T21:11:03Z | 24,021,700 | 8 | 2014-06-03T17:44:53Z | [
"python",
"python-3.x",
"wsgi",
"gunicorn"
] | I have vm in cloud, python 3.3 (also tried with 3.4 - same result) and Gunicorn 18.
I copy/paste 'hello world' app (app.py):
```
def app(environ, start_response):
data = "Hello, World!\n"
start_response("200 OK", [
("Content-Type", "text/plain"),
("Content-Length", str(len(data)))
])
re... | To add to Graham's explanation, replacing
```
return iter([data])
```
with
```
return [bytes(data, 'utf-8')]
```
works for me under Python 3. That solved the same problem when I had it too. |
pygame installation issue in mac os | 22,974,339 | 14 | 2014-04-09T21:31:30Z | 27,439,489 | 14 | 2014-12-12T08:19:25Z | [
"python",
"pygame"
] | I have following issue of installing pygame package.
```
In file included from src/_numericsurfarray.c:23:
src/pygame.h:106:10: fatal error: 'SDL.h' file not found
#include <SDL.h>
^
1 error generated.
error: Setup script exited with error: command 'gcc' failed with exit status 1
```
**System information**
... | Here (OSX Mavericks) I got able to install this way:
```
brew install sdl sdl_image sdl_mixer sdl_ttf portmidi
pip install https://bitbucket.org/pygame/pygame/get/default.tar.gz
```
("default" branch is on commit **e3ae850** right now)
Source: <https://bitbucket.org/pygame/pygame/issue/139/sdlh-not-found-even-though... |
Querystring Array Parameters in Python using Requests | 22,974,772 | 6 | 2014-04-09T21:58:29Z | 23,347,265 | 35 | 2014-04-28T17:17:59Z | [
"python",
"python-requests"
] | I have been trying to figure out how to use `python-requests` to send a request that the url looks like:
```
http://example.com/api/add.json?name='hello'&data[]='hello'&data[]='world'
```
Normally I can build a dictionary and do:
```
data = {'name': 'hello', 'data': 'world'}
response = requests.get('http://example.c... | All you need to do is putting it on a list and making the key as **list like string**:
```
data = {'name': 'hello', 'data[]': ['hello', 'world']}
response = requests.get('http://example.com/api/add.json', params=data)
``` |
Python semi-noob, can someone explain why this phonomena occurs in 'Lists' | 22,976,523 | 4 | 2014-04-10T00:36:34Z | 22,976,549 | 7 | 2014-04-10T00:38:54Z | [
"python"
] | I'm working on a small app that pulls data out of a list stored in a list, passes it through a class init, and then displays/allows user to work. Everything was going fine until i tried to format the original 'list' in the IDLE so it was easier to read (for me). so I'd change 9 to 09, 8 to 08. etc It was a simple forma... | It's nothing to do with lists or strings. When you prefix a number with `0`, it's interpreted as [octal](http://en.wikipedia.org/wiki/Octal). And 9 is not a valid octal digit!
```
Python 2.7.6
Type "help", "copyright", "credits" or "license" for more information.
>>> 09
File "<stdin>", line 1
09
^
SyntaxEr... |
Display multiple mpld3 exports on a single HTML page | 22,981,359 | 5 | 2014-04-10T07:25:35Z | 23,003,221 | 7 | 2014-04-11T03:59:44Z | [
"python",
"matplotlib",
"flask"
] | I've found the `mpld3` package to be brilliant for exporting a `matplolib` plot to HTML and displaying this via a `flask` app.
Each export comes with a lot of JS which seems unnecessary duplication if you want to display multiple plots within a single page. However I'm not well enough versed in JS to extract the relev... | You're half-way there with your answer. I think what you want to do is something like this, which will embed three figures on the page:
```
<script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
<script type="text/javascript" src="http://mpld3.github.io/js/mpld3.v0.1.js"></script>
<style>
</style>... |
Why `float` function is slower than multiplying by 1.0? | 22,983,625 | 19 | 2014-04-10T09:12:13Z | 22,983,997 | 26 | 2014-04-10T09:27:49Z | [
"python",
"optimization",
"python-internals"
] | I understand that this could be argued as a non-issue, but I write software for HPC environments, so this 3.5x speed increase actually makes a difference.
```
In [1]: %timeit 10 / float(98765)
1000000 loops, best of 3: 313 ns per loop
In [2]: %timeit 10 / (98765 * 1.0)
10000000 loops, best of 3: 80.6 ns p... | Because Peep hole optimizer optimizes it by precalculating the result of that multiplication
```
import dis
dis.dis(compile("10 / float(98765)", "<string>", "eval"))
1 0 LOAD_CONST 0 (10)
3 LOAD_NAME 0 (float)
6 LOAD_CONST 1 (98765)
... |
Why is it a syntax error to invoke a method on a numeric literal in Python? | 22,984,228 | 4 | 2014-04-10T09:38:40Z | 22,984,243 | 7 | 2014-04-10T09:39:46Z | [
"python",
"syntax"
] | I can invoke methods on numbers only when I bind them to a name:
```
>>> a = 5
>>> a.bit_length()
3
```
I can invoke methods on string literals:
```
>>> 'Hello World'.lower()
'hello world'
```
But I cannot invoke methods on numeric literals:
```
>>> 5.bit_length()
```
This raises a `SyntaxError`. Is there a pract... | The floating point numbers are parsed as per the following rules, [quoting from the docs](https://docs.python.org/3/reference/lexical_analysis.html#floating-point-literals),
```
floatnumber ::= pointfloat | exponentfloat
pointfloat ::= [intpart] fraction | intpart "."
exponentfloat ::= (intpart | pointfloat) e... |
Recovering features names of explained_variance_ratio_ in PCA with sklearn | 22,984,335 | 15 | 2014-04-10T09:43:18Z | 22,986,100 | 19 | 2014-04-10T10:58:59Z | [
"python",
"machine-learning",
"scikit-learn",
"pca"
] | I'm trying to recover from a PCA done with scikit-learn, **which** features are selected as *relevant*.
A classic example with IRIS dataset.
```
import pandas as pd
import pylab as pl
from sklearn import datasets
from sklearn.decomposition import PCA
# load dataset
iris = datasets.load_iris()
df = pd.DataFrame(iris.... | Each principal component is a linear combination of the original variables:

where `X_i`s are the original variables, and `Beta_i`s are the corresponding weights or so called coefficients.
To obtain the weights, you may simply pass identity matrix to the `transform` met... |
Get lambda function's name as string | 22,985,086 | 2 | 2014-04-10T10:14:54Z | 22,985,136 | 12 | 2014-04-10T10:16:58Z | [
"python",
"function",
"lambda"
] | How can I get a lambda function's name?
Using the `__name__` property returns `<lambda>`:
```
def myfunc():
pass
myfunc_l = lambda :None
print myfunc.__name__
print myfunc_l.__name__
>>myfunc
>><lambda>
```
I was expecting `myfunc_l` but I got `<lambda>` | Lambdas are anonymous, which *means* they do not **have** a name.
You can always assign a name to `__name__` if you feel they should have one anyway:
```
myfunc_l = lambda: None
myfunc_l.__name__ = 'foo'
```
Note that Python cannot know that you assigned the `lambda` function object to a specific name; the assignmen... |
Pass extra arguments to Serializer Class in Django Rest Framework | 22,988,878 | 23 | 2014-04-10T13:02:12Z | 28,750,126 | 23 | 2015-02-26T18:33:49Z | [
"python",
"django",
"rest",
"django-rest-framework"
] | I want to pass some arguments to DRF Serializer class from Viewset, so for I have tried this:
```
class OneZeroSerializer(rest_serializer.ModelSerializer):
def __init__(self, *args, **kwargs):
print args # show values that passed
location = rest_serializer.SerializerMethodField('get_alternate_name')
... | It's very easy with "context" arg for "ModelSerializer" constructor.
For example:
in view:
```
my_objects = MyModelSerializer(
input_collection,
many=True,
context={'user_id': request.user.id}
).data
```
in serializers:
```
class MyModelSerializer(serializers.ModelSerializer):
...
is_my_object =... |
Pass extra arguments to Serializer Class in Django Rest Framework | 22,988,878 | 23 | 2014-04-10T13:02:12Z | 34,084,329 | 10 | 2015-12-04T08:57:36Z | [
"python",
"django",
"rest",
"django-rest-framework"
] | I want to pass some arguments to DRF Serializer class from Viewset, so for I have tried this:
```
class OneZeroSerializer(rest_serializer.ModelSerializer):
def __init__(self, *args, **kwargs):
print args # show values that passed
location = rest_serializer.SerializerMethodField('get_alternate_name')
... | To fulfill the answer of redcyb - consider using in your view the `get_serializer_context` method from `GenericAPIView`, like this:
```
def get_serializer_context(self):
return {'user': self.request.user.email}
``` |
how to smooth a curve in python | 22,988,882 | 7 | 2014-04-10T13:02:21Z | 22,989,863 | 11 | 2014-04-10T13:44:58Z | [
"python",
"numpy",
"signal-processing",
"gaussian",
"smoothing"
] | I have an entropy curve (1d numpy array) but this curve has a lot of noise.
I would like to delete the noise with a smoothing.
This is the plot of my curve:

I have tried to solve this issue making a convolution product with a Kaiser-Bessel filter:
```
gaussian_c... | ok, I solved.
I have used another approach: [Savitzky-Golay filter](http://en.wikipedia.org/wiki/Savitzky%E2%80%93Golay_filter_for_smoothing_and_differentiation)
The code:
```
def savitzky_golay(y, window_size, order, deriv=0, rate=1):
import numpy as np
from math import factorial
try:
window_si... |
Why does this argparse code behave differently between Python 2 and 3? | 22,990,977 | 4 | 2014-04-10T14:27:35Z | 22,994,500 | 7 | 2014-04-10T17:04:24Z | [
"python",
"python-3.x",
"argparse",
"python-2.x"
] | The following code, using argparse's subparsers, fails on Python 3 but runs as expected in Python 2. After comparing the docs, I still can't tell why.
```
#!/usr/bin/env python
from __future__ import print_function
from argparse import ArgumentParser
def action(args):
print(args)
if __name__ == '__main__':
... | the latest `argparse` release changed how it tested for required arguments, and subparsers fell through the cracks. They are no longer 'required'. <http://bugs.python.org/issue9253#msg186387>
When you get `test.py: error: too few arguments`, it's objecting that you did not give it a 'subcommand' argument. In 3.3.5 it ... |
Sort a pandas datetime index | 22,993,603 | 4 | 2014-04-10T16:21:19Z | 22,993,988 | 7 | 2014-04-10T16:40:23Z | [
"python",
"datetime",
"pandas"
] | I have a pandas datetime index that I construct. It may be that through the construction process that the individual members are not in order. I want to sort the index. Is there an obvious way I should be doing this?
What I've done so far is this
```
import pandas as pd
tseries = pd.to_datetime(['2001-02-04', '2013-0... | try
```
tseries.order()
```
If you work with a DataFrame, the term is called sort again, i.e. .sort() and .sort\_index() |
How come the Python's logging module doesn't follow PEP8 conventions? | 22,993,667 | 13 | 2014-04-10T16:24:32Z | 22,993,896 | 14 | 2014-04-10T16:36:26Z | [
"python",
"logging",
"history",
"pep8"
] | This is is just a curiosity with historical purposes:
I was wondering if someone knows why the very widely used (and core module) [logging](https://docs.python.org/2/library/logging.html#logging.getLogger) doesn't follow the Python's [PEP-8 naming convention](http://www.python.org/dev/peps/pep-0008/#prescriptive-namin... | The `logging` module was developed by a [separate company](http://www.red-dove.com/python_logging.html) in 2001, and was heavily based on Log4j. As such it follows the naming conventions the original author picked, which mirror the Log4j choices; the latter has a [`getLogger()` method too](http://logging.apache.org/log... |
Difference between np.random.seed() and np.random.RandomState() | 22,994,423 | 10 | 2014-04-10T17:00:30Z | 22,994,890 | 17 | 2014-04-10T17:24:22Z | [
"python",
"numpy",
"random"
] | I know that to seed the randomness of numpy.random, and be able to reproduce it, I should us:
```
import numpy as np
np.random.seed(1234)
```
but what does
`np.random.RandomState()`
do? | If you want to set the seed that calls to `np.random...` will use, use `np.random.seed`:
```
np.random.seed(1234)
np.random.uniform(0, 10, 5)
#array([ 1.9151945 , 6.22108771, 4.37727739, 7.85358584, 7.79975808])
np.random.rand(2,3)
#array([[ 0.27259261, 0.27646426, 0.80187218],
# [ 0.95813935, 0.87593263,... |
Can matplotlib errorbars have a linestyle set? | 22,995,797 | 9 | 2014-04-10T18:11:40Z | 23,002,214 | 10 | 2014-04-11T01:59:31Z | [
"python",
"matplotlib",
"plot"
] | Is is possible to set the same linestyle to matplotlib errorbars than to the datapoints linestyle?
In the example below, two lines are plotted, one of them is dashed because of the ls='-.' parameter. However, the errorbar are solid lines. Is is possible to modify the style/look of the errorbars to match the results li... | It is trivial, changing the linestyle of the errorbars only require a simple `.set_linestyle` call:
```
eb1=plt.errorbar(x, y, yerr=yerr, lw=2, errorevery=2, ls='-.')
eb1[-1][0].set_linestyle('--') #eb1[-1][0] is the LineCollection objects of the errorbar lines
eb2=plt.errorbar(x, y2, yerr=yerr2, lw=2, errorevery=3)
e... |
How to check if lowercase letters exist? | 22,997,072 | 2 | 2014-04-10T19:17:08Z | 22,997,102 | 8 | 2014-04-10T19:18:51Z | [
"python",
"string"
] | I have been observing unusual behavior with the .`islower()` and `.isupper()` methods in Python. For example:
```
>>> test = '8765iouy9987OIUY'
>>> test.islower()
False
>>> test.isupper()
False
```
However, the following mixed string value seems to work:
```
>>> test2 = 'b1'
>>> test2.islower()
True
>>> test2.isuppe... | `islower()` and `isupper()` only return `True` if **all** letters in the string are lowercase or uppercase, respectively.
You'd have to test for individual characters; `any()` and a generator expression makes that relatively efficient:
```
>>> test = '8765iouy9987OIUY'
>>> any(c.islower() for c in test)
True
>>> any(... |
How to output RandomForest Classifier from python? | 23,000,693 | 7 | 2014-04-10T23:09:41Z | 23,013,518 | 13 | 2014-04-11T13:09:13Z | [
"python",
"scikit-learn",
"random-forest"
] | I have trained a RandomForestClassifier from Python Sckit Learn Module with very big dataset, but question is how can I possibly save this model and let other people apply it on their end.
Thank you! | The recommended method is to use `joblib`, this will result in a much smaller file than a pickle:
```
from sklearn.externals import joblib
joblib.dump(clf, 'filename.pkl')
#then your colleagues can load it
clf = joblib.load('filename.pk1')
```
See the [online docs](http://scikit-learn.org/stable/tutorial/basic/tut... |
How to get ordered dictionaries in pymongo? | 23,001,156 | 6 | 2014-04-10T23:54:59Z | 30,787,769 | 9 | 2015-06-11T17:41:25Z | [
"python",
"pymongo",
"order",
"bson"
] | I am trying get ordered dictionaries in Pymongo. I have read it can be done with bson.son.Son. The Docs are [Here](http://api.mongodb.org/python/current/api/bson/son.html)
However, I can't seem to make it work. There is not much on google about it. There are some discussions on configuring pymongo first to tell it to ... | This solution above is correct for older versions of MongoDB and the pymongo driver but it no longer works with pymongo3 and MongoDB3+ You now need to add `document_class=OrderedDict` to the MongoClient constructor. Modifying the above answer for pymongo3 compatibility.
```
from collections import OrderedDict
from pym... |
Python beautiful soup form input parsing | 23,001,678 | 5 | 2014-04-11T00:53:17Z | 23,001,729 | 11 | 2014-04-11T00:59:15Z | [
"python",
"html",
"parsing",
"beautifulsoup",
"html-parsing"
] | My goal is to grab a list of all input names and values. To pair them up and submit the form. The names and values are randomised.
```
from bs4 import BeautifulSoup # parsing
html = """
<html>
<head id="Head1"><title>Title Page</title></head>
<body>
<form id="formS" action="login.asp?dx=" method="post">
<inp... | You cannot submit a form with `BeautifulSoup`, but here's how you can get the list of name,value pairs:
```
print [(element['name'], element['value']) for element in html_proc.find_all('input')]
```
prints:
```
[('qw1NWJOJi/E8IyqHSHA==', 'gDcZHY+nV'),
('sfqwWJOJi/E8DFDHSHB==', 'kgDcZHY+n'),
('Jsfqw1NdddfDDSDKKSL... |
Pandas: SettingWithCopyWarning | 23,002,762 | 15 | 2014-04-11T03:04:49Z | 23,005,564 | 19 | 2014-04-11T06:56:40Z | [
"python",
"python-2.7",
"pandas"
] | I'd like to replace values in a `Pandas` `DataFrame` larger than an arbitrary number (100 in this case) with `NaN` (as values this large are indicative of a failed experiment). Previously I've used this to replace unwanted values:
```
sve2_all[sve2_all[' Hgtot ng/l'] > 100] = np.nan
```
However, I got the following e... | As suggested in the error message, you should use loc to do this:
```
sve2_all.loc[sve2_all['Hgtot ng/l'] > 100] = np.nan
```
*The warning is here to stop you modifying a copy (here `sve2_all[sve2_all[' Hgtot ng/l'] > 100]` is **potentially** a copy, and if it is then any modifications would not change the original f... |
PyQt - how to make getOpenFileName remember last opening path? | 23,002,801 | 5 | 2014-04-11T03:10:37Z | 23,003,370 | 8 | 2014-04-11T04:13:33Z | [
"python",
"pyqt",
"qfiledialog"
] | According to getOpenFileName instructions:
```
QString fileName = QFileDialog.getOpenFileName(this, tr("Open File"),
"/home",
tr("Images (*.png *.xpm *.jpg)"));
```
How can I make the dialog remember the path the last time when I clo... | If you omit the `dir` argument (or pass in an empty string), the dialog should remember the last directory:
```
filename = QtGui.QFileDialog.getOpenFileName(
parent, 'Open File', '', 'Images (*.png *.xpm *.jpg)')
```
The [tr](http://qt-project.org/doc/qt-4.8/qobject.html#tr) function is used fo... |
How to modify pandas plotting integration? | 23,009,509 | 4 | 2014-04-11T10:04:58Z | 23,010,837 | 7 | 2014-04-11T11:04:57Z | [
"python",
"matplotlib",
"pandas"
] | I'm trying to modify the [scatter\_matrix](http://pandas.pydata.org/pandas-docs/stable/visualization.html#scatter-plot-matrix) plot available on Pandas.
Simple usage would be
Obtained doing :
```
iris = datasets.load_iris()
df = pd.DataFrame(iris.data, co... | `pd.tools.plotting.scatter_matrix` returns an array of the axes it draws; The lower left boundary axes corresponds to indices `[:,0]` and `[-1,:]`. One can loop over these elements and apply any sort of modifications. For example:
```
axs = pd.tools.plotting.scatter_matrix(df, diagonal='kde')
def wrap(txt, width=8):
... |
Expanding width of column in QTreeWidget dynamically | 23,010,241 | 2 | 2014-04-11T10:37:15Z | 23,019,883 | 8 | 2014-04-11T18:18:13Z | [
"python",
"qt",
"user-interface",
"pyqt",
"pyside"
] | Using PySide, I am developing a small application. In my application, I am using QTreeWidget, to show form like data. This QTreeWidget has single column.My problem is that QTreeWidget not showing horizontal scroll bar when its element expands in horizontal direction. Has anybody have any idea about this issue?
After t... | You need to [resize to contents](http://qt-project.org/doc/qt-5/qheaderview.html#ResizeMode-enum) as well as switching off [stretch last section](http://qt-project.org/doc/qt-5/qheaderview.html#stretchLastSection-prop):
```
treewidget.header().setResizeMode(QtGui.QHeaderView.ResizeToContents)
treewidget.header... |
Max retries exceeded with URL | 23,013,220 | 20 | 2014-04-11T12:56:36Z | 24,899,222 | 30 | 2014-07-22T22:55:38Z | [
"python",
"python-requests"
] | I'm trying to get the content of this url "<https://itunes.apple.com/in/genre/ios-business/id6000?mt=8>" and its showing this error
```
Traceback (most recent call last):
File "/home/preetham/Desktop/eg.py", line 17, in <module>
page1 = requests.get(ap)
File "/usr/local/lib/python2.7/dist-packages/requests/api... | What happened here is that **itunes** server refuses your connection (you're sending too many requests from same ip address in short period of time)
> Max retries exceeded with url: /in/app/adobe-reader/id469337564?mt=8
error trace is misleading it should be something like **"No connection could be made because the t... |
shutting down computer (linux) using python | 23,013,274 | 6 | 2014-04-11T12:58:45Z | 23,013,969 | 8 | 2014-04-11T13:27:26Z | [
"python",
"linux",
"python-2.7",
"system-shutdown"
] | I am trying to write a script that will shut down the computer if a few requirements are filled with the command
```
os.system("poweroff")
```
also tried
```
os.system("shutdown now -h")
```
and a few others. but nothing happens when I run it, the computer goes through the code without crashing or producing... | Many of the linux distributions out there require super user privileges to execute `shutdown` or `halt`, but then, how come that if you're sitting on your computer you can power it off without being root? Well... the idea behind this is that if you have physical access to the computer, you could pretty much pull the po... |
Python openCV: kmeans example not working | 23,014,085 | 4 | 2014-04-11T13:31:55Z | 23,016,177 | 8 | 2014-04-11T15:02:56Z | [
"python",
"opencv",
"k-means"
] | I am working my way through the openCV examples and sometimes the examples won't run. In many cases I just have to make small changes and it works then. In this case I found no solution so far. If I run the following code I get an error on the kmeans line. I checked the data types and it seems everything is alright. An... | I was using the example from the 3.x openCV version while I am running on 2.4.8. The syntax is different in 2.x:
```
ret, labels, centers = cv2.kmeans(points, cluster_n, term_crit, 10, 0)
``` |
Does enumerate create a copy of its argument? | 23,015,133 | 2 | 2014-04-11T14:15:33Z | 23,015,166 | 8 | 2014-04-11T14:17:30Z | [
"python",
"enumerate"
] | If I use enumerate while iterating through a very large list of graph clusters, I want to make sure I'm not unnecessarily creating any copies of this list in memory.
I've been trying to confirm that it will not create any copies, but would like to know for sure.
```
for i, cluster in enumerate(c):
# code that doe... | No, it doesn't. It lazily iterates the iterable you pass in while the loop executes. |
Python grouping elements in a list in increasing size | 23,015,438 | 7 | 2014-04-11T14:28:41Z | 23,015,602 | 13 | 2014-04-11T14:36:14Z | [
"python",
"list",
"python-3.x"
] | ```
my_list = [my_list[int((i**2 + i)/2):int((i**2 + 3*i + 3)/2)] for i in range(int((-1 + (1 + 8*len(my_list))**0.5)/2))]
```
Is there a neater solution to grouping the elements of a list into subgroups of increasing size than this?
Examples:
```
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] --> [[1], [2, 3], [4, 5, 6], [7, ... | Using a generator expression:
```
from itertools import count
try:
_range = xrange
except NameError:
# Python 3
_range = range
def incremental_window(it):
"""Produce monotonically increasing windows on an iterable.
Only complete windows are yielded, if the last elements do not form
a comple... |
Why do ints require three times as much memory in Python? | 23,016,610 | 20 | 2014-04-11T15:22:27Z | 23,016,640 | 29 | 2014-04-11T15:23:51Z | [
"python",
"object",
"memory",
"int",
"python-internals"
] | On a 64-bit system an integer in Python takes 24 bytes. This is 3 times the memory that would be needed in e.g. C for a 64-bit integer. Now, I know this is because Python integers are objects. But what is the extra memory used for? I have my guesses, but it would be nice to know for sure. | Remember that the Python `int` type does not have a limited range like C `int` has; the only limit is the available memory.
Memory goes to storing the value, the current size of the integer storage (the storage size is variable to support arbitrary sizes), and the standard Python object bookkeeping (a reference to the... |
Fastest way to calculate the centroid of a set of coordinate tuples in python without numpy | 23,020,659 | 11 | 2014-04-11T19:03:31Z | 23,021,198 | 7 | 2014-04-11T19:35:30Z | [
"python",
"performance"
] | Good afternoon everyone!
I've been working on a project that is incredibly time sensitive (that unfortunately has to be in python) and one of the functions that is used extensively is a function that calculates the centroid of a list of (x, y) tuples. To illustrate:
```
def centroid(*points):
x_coords = [p[0] for... | ```
import numpy as np
data = np.random.randint(0, 10, size=(100000, 2))
```
this here is fast
```
def centeroidnp(arr):
length = arr.shape[0]
sum_x = np.sum(arr[:, 0])
sum_y = np.sum(arr[:, 1])
return sum_x/length, sum_y/length
%timeit centeroidnp(data)
10000 loops, best of 3: 181 µs per loop
```
... |
Convert SRE_Match object to string | 23,025,565 | 7 | 2014-04-12T02:59:59Z | 23,025,573 | 8 | 2014-04-12T03:01:35Z | [
"python"
] | The output of my `re.search` returns `<_sre.SRE_Match object at 0x10d6ed4e0>` I was wondering how could I convert this to a string? or a more readable form? | You should do it as:
```
result = re.search(your_stuff_here)
if result:
print result.group(0)
``` |
Generating and verifying password hashes with flask-bcrypt | 23,026,004 | 2 | 2014-04-12T04:11:02Z | 23,026,945 | 7 | 2014-04-12T06:26:33Z | [
"python",
"hash",
"flask",
"bcrypt"
] | So I've recently learned how to store passwords in a DB, that is by adding a salt to the plaintext password, hashing it, and then storing the hash.
I'm working on a really small Flask app to try all this out, but I'm having a problem with the password hashing and checking parts of the process. It seems that I"m ending... | Ok so it looks like I've solved my problem. Turns out I wasn't using bcrypt properly. Here's what I learned:
The hashes were different each time I called generate\_password\_hash because bcrypt automatically generates a salt for you and appends it to the hashed password, so no need to generate it with urandom or store... |
(python) open a file in memory | 23,028,071 | 5 | 2014-04-12T08:29:26Z | 23,028,118 | 8 | 2014-04-12T08:35:07Z | [
"python",
"file",
"python-3.x"
] | (I'm working on a Python 3.4 project.)
There's a way to open a (sqlite3) database in memory :
```
with sqlite3.connect(":memory:") as database:
```
Does such a trick exist for the open() function ? Something like :
```
with open(":file_in_memory:") as myfile:
```
The idea is to speed up some test functions ... | How about [StringIO](https://docs.python.org/2/library/stringio.html):
```
import StringIO
output = StringIO.StringIO()
output.write('First line.\n')
print >>output, 'Second line.'
# Retrieve file contents -- this will be
# 'First line.\nSecond line.\n'
contents = output.getvalue()
# Close object and discard memory... |
Bad disparity map using StereoBM in OpenCV | 23,030,775 | 8 | 2014-04-12T13:05:40Z | 23,045,810 | 11 | 2014-04-13T17:19:18Z | [
"python",
"opencv",
"computer-vision",
"stereo-3d"
] | I've put together a stereo cam rig and am having trouble using it to produce a good disparity map. Here's an example of two rectified images and the disparity map I produced with them:

As you can see, the results are pretty bad. Changing the S... | It turned out that the problem was the visualization and not the data itself. Somewhere I read that `cv2.reprojectImageTo3D` required a disparity map as floating point values, which is why I was requesting `cv2.CV_32F` from `block_matcher.compute`.
Reading the OpenCV documentation more carefully has led me to think th... |
How do I implement markdown in Django 1.6 app? | 23,031,406 | 7 | 2014-04-12T14:04:08Z | 23,032,368 | 12 | 2014-04-12T15:30:06Z | [
"python",
"django",
"django-models",
"django-admin",
"markdown"
] | I have a text field in `models.py` where I can input text content for a blog using the admin.
I want to be able to write the content for this text field in markdown format, but I'm using Django 1.6 and `django.contrib.markup` is not supported anymore.
I can't find anywhere that has a tutorial and runs through adding ... | Thank you for your answers and suggestions, but I've decided to use markdown-deux.
Here's how I did it:
`pip install django-markdown-deux`
Then I did `pip freeze > requirements.txt` to make sure that my requirements file was updated.
Then I added 'markdown\_deux' to the list of INSTALLED\_APPS:
```
INSTALLED_APPS ... |
Display notifications in Gnome Shell | 23,031,619 | 4 | 2014-04-12T14:23:37Z | 23,055,969 | 9 | 2014-04-14T08:58:39Z | [
"python",
"python-2.7",
"status",
"gnome",
"gnome-shell"
] | How can i send notifications in `GNOME` through a python program?
I have tried python bindings like `pynotify`,`python-notify2`, but the all give pop-up notifications which are temporary. Is there any python bindings to give notifications on the message tray in `GNOME`? | You must use [PyGObject](https://wiki.gnome.org/action/show/Projects/PyGObject), which gives you access to the GNOME platform through the use of GObject introspection. You can read an example in the [Arch documentation for Desktop notifications](https://wiki.archlinux.org/index.php/Desktop%5fnotifications#Python):
```... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.