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 |
|---|---|---|---|---|---|---|---|---|---|
What is the L in numpy.shape and 32 in numpy.type of an array? | 21,284,790 | 4 | 2014-01-22T13:52:06Z | 21,284,938 | 9 | 2014-01-22T13:57:59Z | [
"python",
"arrays",
"numpy"
] | I'm trying the functions of numpy arrays and below is the code:
```
import numpy as np
Z =np.array(
[[0,4,0,0,0,0],
[0,0,0,1,0,0],
[0,1,0,1,0,0],
[0,0,1,1,0,0],
[0,0,0,0,0,0],
[0,0,0,0,0,0]])
print Z
print Z.dtype
print Z.shape
```
Which gave:
```
[[0 4 0 0 0 0]
[0 0 0 1 0 0]
[0 1 0 ... | The 32 in the [array type](http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html) refers to 32-bit width of the underlying machine integer that stores the array. This means that an array with, say, 1 million elements, will take up at least 4 million bytes (32 million bits) of memory.
On the other hand, the suff... |
What does this mean in the docs for random.shuffle? | 21,284,853 | 5 | 2014-01-22T13:54:26Z | 21,284,969 | 8 | 2014-01-22T13:59:23Z | [
"python",
"random"
] | <http://docs.python.org/2/library/random.html#random.shuffle>
> `random.shuffle(x[, random])`
>
> Shuffle the sequence *x* in place. The optional argument *random* is a 0-argument function returning a random float in [0.0, 1.0); by
> default, this is the function `random()`.
>
> Note that for even rather small `len(x)... | It means that for longer lists, the random number generator will start repeating itself, so that the number of different possible 'shuffles' for a given list is not going to be the number of permutations of the list.
For a list of length *N*, there are *N!* (*N* factorial) possible ways to permute the list order, but ... |
How to read numbers in text file using python? | 21,285,684 | 3 | 2014-01-22T14:30:06Z | 21,285,855 | 11 | 2014-01-22T14:37:55Z | [
"python",
"file-io"
] | I am new to python programming and I am learning python by doing simple programs. Here is what I would like to do: if I have a text file containing numbers:
say this a f1.txt
```
f1.txt:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 15
fp = open('f1.txt')
a1=[]
a2=[]
a3=[]
a4=[]
lines = fp.readlines()
for ln in lines[0:len(... | You could do it like this:
```
a1 = []
a2 = []
a3 = []
a4 = []
with open('f1.txt') as f:
for line in f:
data = line.split()
a1.append(int(data[0]))
a2.append(int(data[1]))
a3.append(int(data[2]))
a4.append(int(data[3]))
```
So first of all, we use the `with` statement to o... |
Remove line through marker in matplotlib legend | 21,285,885 | 5 | 2014-01-22T14:39:10Z | 21,286,772 | 10 | 2014-01-22T15:16:22Z | [
"python",
"matplotlib",
"legend"
] | I have a `matplotlib` plot generated with the following code:
```
import matplotlib.pyplot as pyplot
Fig, ax = pyplot.subplots()
for i, (mark, color) in enumerate(zip(
['s', 'o', 'D', 'v'], ['r', 'g', 'b', 'purple'])):
ax.plot(i+1, i+1, color=color,
marker=mark,
markerfacecolor='None',... | You can specify `linestyle="None"` as a keyword argument in the plot command:
```
import matplotlib.pyplot as pyplot
Fig, ax = pyplot.subplots()
for i, (mark, color) in enumerate(zip(
['s', 'o', 'D', 'v'], ['r', 'g', 'b', 'purple'])):
ax.plot(i+1, i+1, color=color,
marker=mark,
markerf... |
Pandas: dataframe column type conversion | 21,287,624 | 22 | 2014-01-22T15:51:28Z | 21,290,084 | 20 | 2014-01-22T17:42:28Z | [
"python",
"pandas",
"na",
"gotchas"
] | I read data from a .csv file to a Pandas dataframe as below. For one of the columns, namely `id`, I want to specify the column type as `int`. The problem is the `id` series has missing/empty values.
When I try to cast the `id` column to integer while reading the .csv, I get:
```
df= pd.read_csv("data.csv", dtype={'id... | The lack of NaN rep in integer columns is a [pandas "gotcha"](http://pandas.pydata.org/pandas-docs/stable/gotchas.html#support-for-integer-na).
The usual workaround is to simply use floats (if you don't specify the dtype this is what will be used). |
Second y-axis label getting cut off | 21,288,062 | 12 | 2014-01-22T16:09:18Z | 21,288,063 | 29 | 2014-01-22T16:09:18Z | [
"python",
"graph",
"matplotlib"
] | I'm trying to plot two sets of data in a bar graph with matplotlib, so I'm using two axes with the `twinx()` method. However, the second y-axis label gets cut off. I've tried a few different methods with no success (`tight_layout()`, setting the `major_pad`s in `rcParams`, etc...). I feel like the solution is simple, b... | I just figured it out: the trick is to use `bbox_inches='tight'` in `savefig`.
E.G. `plt.savefig("test.png",bbox_inches='tight')`
 |
Loading .RData files into Python | 21,288,133 | 6 | 2014-01-22T16:12:13Z | 21,288,178 | 8 | 2014-01-22T16:14:12Z | [
"python",
"rdata"
] | I have a bunch of .RData time-series files and would like to load them directly into Python without first converting the files to some other extension (such as .csv). Any ideas on the best way to accomplish this?
Thanks. | People ask this sort of thing on the R-help and R-dev list and the usual answer is that the code is the documentation for the `.RData` file format. So any other implementation in any other language is **hard++**.
I think the only reasonable way is to install RPy2 and use R's `load` function from that, converting to ap... |
Link to class method in python docstring | 21,289,806 | 15 | 2014-01-22T17:29:18Z | 21,296,279 | 7 | 2014-01-22T23:27:19Z | [
"python",
"python-sphinx",
"spyder"
] | I want to add a link to a method in my class from within the docstring of another method of the same class. I want the link to work in sphinx and preferentially also in Spyder and other Python IDE's.
I tried several options and found only one that works, but it's cumbersome.
Suppose the following structure in `mymodu... | If you want to manually specify the text of the link you can use:
```
:func:`my text <mymodule.MyClass.foo>`
```
For more information, checkout [Cross-referencing Python objects](http://sphinx-doc.org/domains.html#cross-referencing-python-objects). |
Link to class method in python docstring | 21,289,806 | 15 | 2014-01-22T17:29:18Z | 21,297,186 | 15 | 2014-01-23T00:46:27Z | [
"python",
"python-sphinx",
"spyder"
] | I want to add a link to a method in my class from within the docstring of another method of the same class. I want the link to work in sphinx and preferentially also in Spyder and other Python IDE's.
I tried several options and found only one that works, but it's cumbersome.
Suppose the following structure in `mymodu... | The solution that works for Sphinx is to prefix the reference with `~`.
So the answer is:
```
def class MyClass():
def foo(self):
print 'foo'
def bar(self):
"""This method does the same as :func:`~mymodule.MyClass.foo`"""
print 'foo'
```
This results in an html looking like this : `Thi... |
Convert floats to ints in Pandas? | 21,291,259 | 20 | 2014-01-22T18:42:15Z | 21,291,383 | 23 | 2014-01-22T18:49:11Z | [
"python",
"pandas"
] | I've working with data imported from a CSV. Pandas changed some columns to float, so now the numbers in these columns get displayed as floating points! However, I need them to be displayed as integers, or, without comma. Is there a way to convert them to integers or not diplay the comma? | Use the .astype() function to manipulate column dtypes.
```
>>> df = pd.DataFrame(np.random.rand(3,4), columns=list("ABCD"))
>>> df
A B C D
0 0.542447 0.949988 0.669239 0.879887
1 0.068542 0.757775 0.891903 0.384542
2 0.021274 0.587504 0.180426 0.574300
>>> df[list("ABCD")... |
Convert floats to ints in Pandas? | 21,291,259 | 20 | 2014-01-22T18:42:15Z | 21,291,622 | 18 | 2014-01-22T19:01:18Z | [
"python",
"pandas"
] | I've working with data imported from a CSV. Pandas changed some columns to float, so now the numbers in these columns get displayed as floating points! However, I need them to be displayed as integers, or, without comma. Is there a way to convert them to integers or not diplay the comma? | To modify the float output do this:
```
df= pd.DataFrame(range(5), columns=['a'])
df.a = df.a.astype(float)
df
Out[33]:
a
0 0.0000000
1 1.0000000
2 2.0000000
3 3.0000000
4 4.0000000
pd.options.display.float_format = '{:,.0f}'.format
df
Out[35]:
a
0 0
1 1
2 2
3 3
4 4
``` |
How to properly use association_proxy and ordering_list together with SQLAlchemy | 21,292,726 | 8 | 2014-01-22T19:58:56Z | 21,297,237 | 13 | 2014-01-23T00:50:24Z | [
"python",
"sqlalchemy",
"flask"
] | Based on some posts on the SQLAlchemy Google Group:
<https://groups.google.com/forum/#!topic/sqlalchemy/S4_8PeRBNJw>
<https://groups.google.com/forum/#!topic/sqlalchemy/YRyI7ic1QkY>
I assumed I could successfully use the `assocation_proxy` and `ordering_list` extensions to create an ordered, many to many relationship... | *sooo close ;-)*
Please read [Creation of New Values](http://docs.sqlalchemy.org/en/rel_0_9/orm/extensions/associationproxy.html#creation-of-new-values) secion of `association_proxy` extension.
In order to make your code work, you can either
**Option-1**: add the following constructor to `UserImage` class:
```
def... |
Python `type(x)==` what? | 21,293,564 | 3 | 2014-01-22T20:43:44Z | 21,293,583 | 10 | 2014-01-22T20:44:46Z | [
"python",
"class",
"types"
] | In a code, I am trying to check the type of a class of a variable entered into a function. What I want is something like this:
```
def foo(x):
if type(x)=='int':
pass
```
But I can't find anything that I can put in place of `'int'` that will return `True` when I input an integer. I have made a temporary fi... | Use `int` and [`isinstance()`](http://docs.python.org/2/library/functions.html#isinstance):
```
if isinstance(x, int):
```
You *could* restrict yourself to *just* the type with:
```
if type(x) is int:
```
but that excludes subclasses of `int`.
However, ask yourself why you are testing for specific types; better to... |
Test if tuple contains only None values with Python | 21,294,383 | 3 | 2014-01-22T21:30:42Z | 21,294,401 | 14 | 2014-01-22T21:31:48Z | [
"python",
"python-2.7",
"tuples",
"nonetype"
] | I need to find if my tuple contains only None value.
I use this code but i not sure it's the good practice:
```
# coding=utf8
def isOnlyNoneValuesTuple(t):
"""
test if tuple contains only None values
"""
if not len(tuple(itertools.ifilter(None, t))):
return True
else:
return False... | ```
return all(item is None for item in t)
``` |
how to get access to error message from abort command when using custom error handler | 21,294,889 | 17 | 2014-01-22T21:59:36Z | 21,297,608 | 18 | 2014-01-23T01:30:53Z | [
"python",
"http",
"flask",
"http-error"
] | Using a python flask server, I want to be able to throw an http error response with the abort command and use a custom response string and a custom message in the body
```
@app.errorhandler(400)
def custom400(error):
response = jsonify({'message': error.message})
response.status_code = 404
response.status ... | People rely on `abort()` too much. The truth is that there are much better ways to handle errors.
For example, you can write this helper function:
```
def bad_request(message):
response = jsonify({'message': message})
response.status_code = 400
return response
```
Then from your view function you can ret... |
how to get access to error message from abort command when using custom error handler | 21,294,889 | 17 | 2014-01-22T21:59:36Z | 21,301,229 | 26 | 2014-01-23T06:46:47Z | [
"python",
"http",
"flask",
"http-error"
] | Using a python flask server, I want to be able to throw an http error response with the abort command and use a custom response string and a custom message in the body
```
@app.errorhandler(400)
def custom400(error):
response = jsonify({'message': error.message})
response.status_code = 404
response.status ... | If you look at [`flask/__init__.py`](https://github.com/mitsuhiko/flask/blob/d517f35d60a14fcea2e503f578e65b68eafa6577/flask/__init__.py#L17) you will see that `abort` is actually imported from [`werkzeug.exceptions`](https://github.com/mitsuhiko/werkzeug/blob/5eed9385b861a1ae53c03eaae5a8dea4480113d6/werkzeug/exceptions... |
pip connection failure: cannot fetch index base URL http://pypi.python.org/simple/ | 21,294,997 | 22 | 2014-01-22T22:05:18Z | 21,298,276 | 11 | 2014-01-23T02:38:24Z | [
"python",
"git",
"ubuntu",
"pip",
"git-review"
] | I run `sudo pip install git-review`, and get the following messages:
```
Downloading/unpacking git-review
Cannot fetch index base URL http://pypi.python.org/simple/
Could not find any downloads that satisfy the requirement git-review
No distributions at all found for git-review
Storing complete log in /home/sai/.p... | Check your proxy connection, I had a similar issue, then I changed my connection which wasn't proxied and boom, of it started downloading and setting up the library |
pip connection failure: cannot fetch index base URL http://pypi.python.org/simple/ | 21,294,997 | 22 | 2014-01-22T22:05:18Z | 22,446,201 | 23 | 2014-03-17T02:59:43Z | [
"python",
"git",
"ubuntu",
"pip",
"git-review"
] | I run `sudo pip install git-review`, and get the following messages:
```
Downloading/unpacking git-review
Cannot fetch index base URL http://pypi.python.org/simple/
Could not find any downloads that satisfy the requirement git-review
No distributions at all found for git-review
Storing complete log in /home/sai/.p... | **EDIT:**
The current version of `PIP` no longer has this issue. As of right now, version: `7.1.2` is the current version. Here is the `PIP` link:
<https://pypi.python.org/pypi/pip>
**ORIGINAL FIX:**
I got this issue when trying to use `pip==1.5.4`
This is an issue related to PIP and Python's PYPI trusting SSL cer... |
pip connection failure: cannot fetch index base URL http://pypi.python.org/simple/ | 21,294,997 | 22 | 2014-01-22T22:05:18Z | 25,881,272 | 10 | 2014-09-17T02:21:37Z | [
"python",
"git",
"ubuntu",
"pip",
"git-review"
] | I run `sudo pip install git-review`, and get the following messages:
```
Downloading/unpacking git-review
Cannot fetch index base URL http://pypi.python.org/simple/
Could not find any downloads that satisfy the requirement git-review
No distributions at all found for git-review
Storing complete log in /home/sai/.p... | I added --proxy command line option to point to the proxy and it's working (pip version is 1.5.4 and python 2.7). for some reason it was not taking the shell env variables HTTPS\_PROXY, HTTP\_PROXY, https\_proxy, http\_proxy.
```
sudo pip --proxy [user:passwd@]proxy.server:port install git-review
``` |
How can I create a relay server using tulip/asyncio in Python? | 21,295,068 | 2 | 2014-01-22T22:09:02Z | 21,297,354 | 7 | 2014-01-23T01:05:05Z | [
"python",
"asynchronous",
"python-asyncio"
] | I have the [example echo server](http://docs.python.org/3.4/library/asyncio-protocol.html#echo-server)
```
import asyncio
class EchoServer(asyncio.Protocol):
def connection_made(self, transport):
peername = transport.get_extra_info('peername')
print('connection from {}'.format(peername))
s... | Here is a simple proxy which allow you to `wget 127.0.0.1:8888` and get a html response from google:
```
import asyncio
class Client(asyncio.Protocol):
def connection_made(self, transport):
self.connected = True
# save the transport
self.transport = transport
def data_received(self, ... |
Find the length of the longest string in a Pandas DataFrame column | 21,295,334 | 9 | 2014-01-22T22:26:49Z | 21,295,630 | 15 | 2014-01-22T22:44:12Z | [
"python",
"pandas"
] | Is there a faster way to find the length of the longest string in a Pandas DataFrame than what's shown in the example below?
```
import numpy as np
import pandas as pd
x = ['ab', 'bcd', 'dfe', 'efghik']
x = np.repeat(x, 1e7)
df = pd.DataFrame(x, columns=['col1'])
print df.col1.map(lambda x: len(x)).max()
# result --... | DSM's suggestion seems to be about the best you're going to get without doing some manual microoptimization:
```
%timeit -n 100 df.col1.str.len().max()
100 loops, best of 3: 11.7 ms per loop
%timeit -n 100 df.col1.map(lambda x: len(x)).max()
100 loops, best of 3: 16.4 ms per loop
%timeit -n 100 df.col1.map(len).max(... |
How to count all positive and negative values in a pandas groupby? | 21,296,945 | 5 | 2014-01-23T00:22:28Z | 21,297,120 | 8 | 2014-01-23T00:39:46Z | [
"python",
"lambda",
"pandas"
] | Let's assume we have a table:
```
df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
'B' : ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'],
'C' : np.random.randn(8), 'D' : np.random.randn(8)})
```
Output:
```
A B ... | You could do this as a one line apply (the first column being negative, the second positive):
```
In [11]: df.groupby('A').C.apply(lambda x: pd.Series([(x < 0).sum(), (x >= 0).sum()])).unstack()
Out[111]:
0 1
A
bar 2 1
foo 2 3
[2 rows x 2 columns]
```
However, I think a neater way is to use a dumm... |
Use `__dict__` or `vars()`? | 21,297,203 | 9 | 2014-01-23T00:47:37Z | 21,300,095 | 15 | 2014-01-23T05:28:13Z | [
"python"
] | Builtin function `vars()` looks more Pythonic to me, but I see `__dict__` used more frequently.
The Python documentation indicates that they are equivalent.
One blogger [claims that `__dict__` is faster than `vars()`](http://pythondoeswhat.blogspot.com/2012/01/dict-and-vars.html).
Which shall I use? | Generally, you should consider dunder/magic methods to be the implementation and invoking functions/methods as the API, so it would be preferable to use `vars()` over `__dict__`, in the same way that you would do `len(a_list)` and not `a_list.__len__()`, or `a_dict["key"]` rather than `a_dict.__getitem__('key')` |
Performance issues in Burrows-Wheeler in python | 21,297,887 | 5 | 2014-01-23T01:58:33Z | 21,298,629 | 8 | 2014-01-23T03:12:36Z | [
"python",
"performance",
"algorithm"
] | I was trying to implement [Burrows-Wheeler](http://en.wikipedia.org/wiki/Burrows%E2%80%93Wheeler_transform) transform in python. (This is one of the assignments in online course, but I hope I have done some work to be qualified to ask for help).
The algorithm works as follows. Take a string which ends with a special c... | It takes a long time to make all those string slices with long strings. It's *at least* O(N^2) (since you create N strings of N length, and each one has to be copied into memory taking its source data from the original), which destroys the overall performance and makes the sorting irrelevant. Not to mention the memory ... |
check if numpy array is multidimensional or not | 21,299,798 | 5 | 2014-01-23T05:04:32Z | 21,299,842 | 10 | 2014-01-23T05:07:30Z | [
"python",
"numpy"
] | I want to check if a numpy array is multidimensional or not?
```
V = [[ -7.94627203e+01 -1.81562235e+02 -3.05418070e+02 -2.38451033e+02][ 9.43740653e+01 1.69312771e+02 1.68545575e+01 -1.44450299e+02][ 5.61599000e+00 8.76135909e+01 1.18959245e+02 -1.44049237e+02]]
```
How can I do that in numpy? | Use the [`.ndim`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.ndim.html) property of the ndarray:
```
>>> a = np.array([[ -7.94627203e+01, -1.81562235e+02, -3.05418070e+02, -2.38451033e+02],[ 9.43740653e+01, 1.69312771e+02, 1.68545575e+01, -1.44450299e+02],[ 5.61599000e+00, 8.76135909... |
Iterate over all pairs of consecutive items from a given list | 21,303,224 | 22 | 2014-01-23T08:42:21Z | 21,303,286 | 32 | 2014-01-23T08:45:47Z | [
"python",
"list",
"iterator"
] | Given a list
```
l = [1,7,3,5]
```
I want to iterate over all pairs of consecutive list items `(1,7),(7,3),(3,5)`, i.e.
```
for i in xrange(len(l)-1):
x=l[i]
y=l[i+1]
# do something
```
I would like to do this in a more compact way, like `for (x,y) in someiterator(l): ...`,
is there a way to do do this ... | Just use [zip](http://docs.python.org/2/library/functions.html#zip)
```
>>> l = [1, 7, 3, 5]
>>> for first, second in zip(l, l[1:]):
... print first, second
...
1 7
7 3
3 5
```
As suggested you might consider using the `izip` function in `itertools` for very long lists where you don't want to create a new list.
... |
Iterate over all pairs of consecutive items from a given list | 21,303,224 | 22 | 2014-01-23T08:42:21Z | 21,303,303 | 15 | 2014-01-23T08:46:30Z | [
"python",
"list",
"iterator"
] | Given a list
```
l = [1,7,3,5]
```
I want to iterate over all pairs of consecutive list items `(1,7),(7,3),(3,5)`, i.e.
```
for i in xrange(len(l)-1):
x=l[i]
y=l[i+1]
# do something
```
I would like to do this in a more compact way, like `for (x,y) in someiterator(l): ...`,
is there a way to do do this ... | Look at `pairwise` at itertools recipes: <http://docs.python.org/2/library/itertools.html#recipes>
Quoting from there:
```
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return izip(a, b)
```
---
**A General Version**
A general version, that yields... |
Iterating over multiple lists in python - flask - jinja2 templates | 21,306,134 | 2 | 2014-01-23T10:57:00Z | 21,306,466 | 8 | 2014-01-23T11:11:00Z | [
"python",
"flask",
"jinja2"
] | I am facing an issue in Iterating `for loop` over multiple lists in flask jinja2 template.
My code is something looks like below
```
Type = 'RS'
IDs = ['1001','1002']
msgs = ['Success','Success']
rcs = ['0','1']
return render_template('form_result.html',type=type,IDs=IDs,msgs=msgs,rcs=rcs)
```
I am not sure of comin... | you need `zip()` but it isn't defined in jinja2 templates.
one solution is zipping it **before** `render_template` function is called, like:
view function:
```
return render_template('form_result.html',type=type,reqIDs_msgs_rcs=zip(IDs,msgs,rcs))
```
template:
```
{% for reqID,msg,rc in reqIDs_msgs_rcs %}
<h1>ID -... |
Can I hack Packery.js to create circular bin packing? | 21,307,524 | 4 | 2014-01-23T11:59:10Z | 21,465,521 | 10 | 2014-01-30T19:16:43Z | [
"javascript",
"jquery",
"python",
"bin-packing",
"packery"
] | 
this is [implemented in python](http://fuseki.net/rect/) ([more tests](http://fuseki.net/rect/imgs/))
I'm interested in a result like in the image above (implemented in python) using the [Packery.js](http://packery.metafizzy.co/) jQ... | Yes! See <https://github.com/metafizzy/packery/issues/62>
> In the works.
>
> 
>
> Development is on the [center-out-corner branch](https://github.com/metafizzy/packery/tree/center-out-corner). It's in an experimental phase. While this is a neat visual demo, I'm uns... |
Avoid twitter api limitation with Tweepy | 21,308,762 | 11 | 2014-01-23T12:53:21Z | 22,314,672 | 10 | 2014-03-11T01:26:16Z | [
"python",
"python-2.7",
"twitter",
"tweepy"
] | I saw in some thread in stack exchange that the limitation can be in function of the number of requests per 15 minutes and depends also on the complexity of the alghorithm, except that this is not a complex one .
So I use this code :
```
import tweepy
import sqlite3
import time
db = sqlite3.connect('data/MyDB.db')
#... | The problem is that your `try: except:` block is in the wrong place. Inserting data into the database will never raise a `TweepError` - it's iterating over `Cursor.items()` that will. I would suggest refactoring your code to call the `next` method of `Cursor.items()` in an infinite loop. That call should be placed in t... |
Avoid twitter api limitation with Tweepy | 21,308,762 | 11 | 2014-01-23T12:53:21Z | 25,141,354 | 9 | 2014-08-05T14:29:46Z | [
"python",
"python-2.7",
"twitter",
"tweepy"
] | I saw in some thread in stack exchange that the limitation can be in function of the number of requests per 15 minutes and depends also on the complexity of the alghorithm, except that this is not a complex one .
So I use this code :
```
import tweepy
import sqlite3
import time
db = sqlite3.connect('data/MyDB.db')
#... | If you want to avoid errors and respect the rate limit you can use the following function which takes your `api` object as an argument. It retrieves the number of remaining requests **of the same type as the last request** and waits until the rate limit has been reset if desired.
```
def test_rate_limit(api, wait=True... |
Avoid twitter api limitation with Tweepy | 21,308,762 | 11 | 2014-01-23T12:53:21Z | 31,866,907 | 23 | 2015-08-06T22:36:04Z | [
"python",
"python-2.7",
"twitter",
"tweepy"
] | I saw in some thread in stack exchange that the limitation can be in function of the number of requests per 15 minutes and depends also on the complexity of the alghorithm, except that this is not a complex one .
So I use this code :
```
import tweepy
import sqlite3
import time
db = sqlite3.connect('data/MyDB.db')
#... | For anyone who stumbles upon this on Google, tweepy 3.2+ has additional parameters for the [tweepy.api](http://docs.tweepy.org/en/v3.2.0/api.html#API) class, in particular:
* `wait_on_rate_limit` â Whether or not to automatically wait for rate limits to replenish
* `wait_on_rate_limit_notify` â Whether or not to p... |
histogram graph line style in matplotlib | 21,309,735 | 2 | 2014-01-23T13:36:28Z | 21,310,232 | 8 | 2014-01-23T13:57:41Z | [
"python",
"matplotlib",
"plot",
"histogram"
] | I need to plot two histograms in the same figure and there is overlapping. I use command like
```
plt.hist(data1,bins=40,normed=True,histtype='step')
plt.hist(data2,bins=40,normed=True,histtype='step')
```
To distinguish these two different histograms (need to present them in black and white), I want to make one of t... | Do you have all the libraries you need imported? Also, sometimes not all linestyles are available to all plot types. There are linestyles that work for plots that do not work on vectors (even though they look like the should), for example. When the symbol name does not work '--' it is a good idea to try the named versi... |
List database tables with SQLAlchemy | 21,310,549 | 19 | 2014-01-23T14:09:51Z | 21,346,185 | 37 | 2014-01-25T03:20:06Z | [
"python",
"database",
"sqlalchemy"
] | I want to implement a function that gives information about all the tables (and their column names) that are present in a database (not only those created with SQLAlchemy). While reading the documentation it seems to me that this is done via reflection but I didn't manage to get something working. Any suggestions or ex... | start with an engine:
```
from sqlalchemy import create_engine
engine = create_engine("postgresql://u:p@host/database")
```
quick path to all table /column names, use an inspector:
```
from sqlalchemy import inspect
inspector = inspect(engine)
for table_name in inspector.get_table_names():
for column in inspecto... |
How to make a POST (ReST) API in Robot framework with | 21,311,532 | 5 | 2014-01-23T14:51:32Z | 22,474,072 | 9 | 2014-03-18T08:37:44Z | [
"python",
"http",
"robotframework"
] | I need to replicate the below API call in Robot Framework:
`curl -X POST "http://xyz/api/createApp" -H "Content-Type:application/json" -d @/tmp/testfile.json`
testfile.json has a json payload. I cannot send the content of Json file as body.
I have imported the HTTP libraries. But do not see any key-word to make an A... | Bulkan's robotframework-requests is nice. But if you can get by with less, you can do your own local lib/posthttp.py in a few lines like this:
```
import requests
import json
def do_requests_post( url=None, data=None, headers={"Content-Type":"application/json"}):
return requests.post( url, data=data, headers=json... |
Make a Pandas MultiIndex from a product of iterables? | 21,316,628 | 11 | 2014-01-23T18:37:54Z | 21,317,700 | 10 | 2014-01-23T19:34:35Z | [
"python",
"pandas"
] | I have a utility function for creating a Pandas MultiIndex when I have two or more iterables and I want an index key for each unique pairing of the values in those iterables. It looks like this
```
import pandas as pd
import itertools
def product_index(values, names=None):
"""Make a MultiIndex from the combinator... | This is a very similar construction (but using `cartesian_product` which for larger arrays is faster than `itertools.product`)
```
In [2]: from pandas.tools.util import cartesian_product
In [3]: MultiIndex.from_arrays(cartesian_product([range(3),list('ab')]))
Out[3]:
MultiIndex(levels=[[0, 1, 2], [u'a', u'b']],
... |
Pandas/Python: How to concatenate two dataframes without duplicates? | 21,317,384 | 7 | 2014-01-23T19:16:45Z | 21,317,570 | 11 | 2014-01-23T19:27:33Z | [
"python",
"pandas"
] | I'd like to concatenate two dataframes A, B to a new one without duplicate rows (if rows in B already exist in A, don't add):
Dataframe A: Dataframe B:
```
I II I II
0 1 2 5 6
1 3 1 3 1
```
New Dataframe:
```
I II
0 1 2
1 3 1
2 5 6
```
How can I do this? | The simplest way is to just do the concatenation, and then dedupe.
```
>>> df1
A B
0 1 2
1 3 1
>>> df2
A B
0 5 6
1 3 1
>>> pandas.concat([df1,df2]).drop_duplicates().reset_index(drop=True)
A B
0 1 2
1 3 1
2 5 6
```
The reset\_index(drop=True) is to fix up the index after the concat and dedup... |
How do I create a login API using Django Rest Framework? | 21,317,899 | 34 | 2014-01-23T19:46:33Z | 21,318,739 | 25 | 2014-01-23T20:34:01Z | [
"python",
"django",
"rest",
"django-rest-framework"
] | I want to create a login api (or use an existing one if it is already pre-bundled) using django rest framework. However, I'm completely at a loss. Whenever I send a post request to the django rest framework "login" url, it just sends back the browsable api template page...
**MY CONFIGURATION**
urls.py
```
url(r'^api... | Take a look at the api view from [django-rest-framework-jwt](https://github.com/GetBlimp/django-rest-framework-jwt). It's an implementation for creating auth tokens rather than cookie sessions, but your implementation will be similar. See [views.py](https://github.com/GetBlimp/django-rest-framework-jwt/blob/master/rest... |
How do I create a login API using Django Rest Framework? | 21,317,899 | 34 | 2014-01-23T19:46:33Z | 26,064,197 | 11 | 2014-09-26T16:31:50Z | [
"python",
"django",
"rest",
"django-rest-framework"
] | I want to create a login api (or use an existing one if it is already pre-bundled) using django rest framework. However, I'm completely at a loss. Whenever I send a post request to the django rest framework "login" url, it just sends back the browsable api template page...
**MY CONFIGURATION**
urls.py
```
url(r'^api... | If you want something like this I do the same thing however I use Token authentication.
Check out their token page [here](http://www.django-rest-framework.org/api-guide/authentication#tokenauthentication)
This may not be what you want but the way I do it is (since I'm using it as a rest api endpoints for mobile clien... |
python iterating over dictionaries | 21,319,774 | 10 | 2014-01-23T21:32:44Z | 21,319,852 | 12 | 2014-01-23T21:36:59Z | [
"python"
] | I have two dictionaries.I'm iterating over it one inside the other.
I want to select the next item each time it iterates inside the inner loop rather than from the beginning.
```
dict1={'a':1 , 'b':2 , 'c':3}
dict2={'x':10, 'y':20, 'z':30}
for key,value in dict1:
#do something
for k,v in dict2:
#do s... | First, `for key,value in dict1` doesn't do what you wantâit just iterates over the *keys*. If you want to iterate over key-value pair, you need `for key, value in dict1.items()`.
Meanwhile, it sounds like what you're asking for is lock-step iteration, not nested iteration? If so, you want the `zip` function:
```
fo... |
How to determine whether a Pandas Column contains a particular value | 21,319,929 | 15 | 2014-01-23T21:41:11Z | 21,320,011 | 21 | 2014-01-23T21:45:44Z | [
"python",
"pandas"
] | I am trying to determine whether there is an entry in a Pandas column that has a particular value. I tried to do this with `if x in df['id']`. I thought this was working, except when I fed it a value that I knew was not in the column `43 in df['id']` it still returned `True`. When I subset to a data frame only containi... | `in` of a Series checks whether the value is in the index:
```
In [11]: s = pd.Series(list('abc'))
In [12]: s
Out[12]:
0 a
1 b
2 c
dtype: object
In [13]: 1 in s
Out[13]: True
In [14]: 'a' in s
Out[14]: False
```
One option is to see if it's in [unique](http://pandas.pydata.org/pandas-docs/stable/generate... |
How to write a pandas Series to CSV as a row, not as a column? | 21,320,405 | 5 | 2014-01-23T22:11:36Z | 21,320,592 | 8 | 2014-01-23T22:24:38Z | [
"python",
"csv",
"pandas"
] | I need to write a `pandas.Series` object to a CSV file as a row, not as a column. Simply doing
```
the_series.to_csv( 'file.csv' )
```
gives me a file like this:
```
record_id,2013-02-07
column_a,7.0
column_b,5.0
column_c,6.0
```
What I need instead is this:
```
record_id,column_a,column_b,column_c
2013-02-07,7.0,... | You can just use the DataFrame constructor (rather than to\_frame):
```
In [11]: pd.DataFrame(s).T
Out[11]:
record_id column_a column_b column_c
2013-02-07 7 5 6
``` |
Is there any advantage to using DeMorgan Law in python? | 21,320,961 | 8 | 2014-01-23T22:49:22Z | 21,321,540 | 14 | 2014-01-23T23:32:23Z | [
"python",
"demorgans-law"
] | I use pycharm and a few times when using if statements I have seen the suggestion to change the statement to DeMorgan Law like the following if statement.
```
if new_odds > 10 and new_odds <= 30:
if not (not (new_odds > 10) or not (new_odds <= 20)):
```
For me it makes it less readable, so is there any adva... | First of all, its [**DeMorgan's Laws**](http://en.wikipedia.org/wiki/De_Morgan%27s_laws), not *DeMorgans Law*, which states that:
> "not (A and B)" is the same as "(not A) or (not B)"
>
> and also,
>
> "not (A or B)" is the same as "(not A) and (not B)"
Which are used to transform logic between alternate forms. So wh... |
How to change fonts in matplotlib (python)? | 21,321,670 | 10 | 2014-01-23T23:43:33Z | 21,323,217 | 17 | 2014-01-24T02:20:17Z | [
"python",
"fonts",
"matplotlib"
] | It sounds as an easy problem but I do not find any effective solution to change the font (not the font size) in a plot made with matplotlib in python.
I found a couple of tutorials to change the default font of matplotlib by modifying some files in the folders where matplotlib stores its default font - see [this blog ... | Say you want Comic Sans for the title and Helvetica for the x label.
```
csfont = {'fontname':'Comic Sans MS'}
hfont = {'fontname':'Helvetica'}
plt.title('title',**csfont)
plt.xlabel('xlabel', **hfont)
plt.show()
``` |
Using Selenium in Python to click/select a radio button | 21,322,116 | 5 | 2014-01-24T00:22:33Z | 21,322,160 | 19 | 2014-01-24T00:26:05Z | [
"python",
"selenium",
"selenium-webdriver"
] | I am trying to select from a list of 3 buttons, but can't find a way to select them. Below is the HTML I am working with.
```
<input name="pollQuestion" type="radio" value="SRF">
<font face="arial,sans-serif" size="-1">ChoiceOne</font><br />
<input name="pollQuestion" type="radio" value="COM">
<font face="ari... | Use CSS Selector or XPath to select by `value` attribute directly, then click it.
```
browser.find_elements_by_css("input[type='radio'][value='SRF']").click
# browser.find_element_by_xpath(".//input[@type='radio' and @value='SRF']").click
```
Corrections (but OP should learn how to look up in documentation)
* In Pyt... |
getting a dictionary of class variables and values | 21,322,244 | 4 | 2014-01-24T00:36:19Z | 21,322,297 | 9 | 2014-01-24T00:41:40Z | [
"python",
"class",
"dictionary",
"class-variables"
] | I am working on a method to return all the class variables as keys and values as values of a dictionary , for instance i have:
first.py
```
class A:
a = 3
b = 5
c = 6
```
Then in the second.py i should be able to call maybe a method or something that will return a dictionary like this
```
import first
... | You need to filter out functions and built-in class attributes.
```
>>> class A:
... a = 3
... b = 5
... c = 6
...
>>> {key:value for key, value in A.__dict__.items() if not key.startswith('__') and not callable(key)}
{'a': 3, 'c': 6, 'b': 5}
``` |
isinstance returning false when class is the same? | 21,323,908 | 3 | 2014-01-24T03:32:55Z | 21,323,951 | 7 | 2014-01-24T03:36:47Z | [
"python"
] | ```
def addError(self, e):
if not isinstance(e, Error):
raise ValueError('{0} is not type {0}'.format(e, Error))
self.__errors.append(e)
```
Message:
ValueError: `<class 'api.utils.Error'>` is not type `<class 'api.utils.Error'>` | You're passing the class *itself*, not an instance of the class. That explains your problem.
```
>>> class A:
pass
>>> isinstance(A, A)
False
```
What you probably want is to check an instance:
```
>>> isinstance(A(), A)
True
``` |
Numpy build fails with cannot import multiarray | 21,324,426 | 6 | 2014-01-24T04:23:23Z | 34,929,739 | 9 | 2016-01-21T16:56:56Z | [
"python",
"osx",
"python-2.7",
"numpy",
"homebrew"
] | I'm using homebrew python on Mavericks, trying to build numpy 1.8. Unfortunately, when I try to install numpy, I get the following error: <https://gist.github.com/ngoldbaum/8592039>
I'm able to build numpy 1.7.2 with `pip install numpy==1.7.2`, but numpy 1.8 always fails to build with the same traceback. | on Mac:
1.) remove these 2 folders manually:
```
rm -rf /usr/local/lib/python2.7/site-packages/numpy/
rm -rf /usr/local/lib/python2.7/site-packages/numpy-1.10.4.dist-info/
```
notice: `pip uninstall numpy` didn't work for me, I had to remove numpy manually.
2.) re-install numpy: `pip install numpy` |
What is the Difference between PySphere and PyVmomi? | 21,326,448 | 11 | 2014-01-24T07:02:57Z | 21,433,805 | 19 | 2014-01-29T14:21:43Z | [
"python",
"vmware"
] | I need to write python scripts to automate time configuration of Virtual Machines running on a ESX/ESXi host.
I don't know which api to use...
I am able to find to python bindings for VMWare apis viz. PySphere and PyVmomi.
Could anyone please explain what is the difference between them, which one should be used?
Thank... | I'm the (now former) VMware employee who helped get this out the door.
pyVmomi represents the official bindings of the vSphere API released by VMware. The functions and object names map directly to what's documented in the [vSphere Web Services SDK](https://www.vmware.com/support/developer/vc-sdk/). It takes a while t... |
Why isn't SQLAlchemy creating serial columns? | 21,328,599 | 3 | 2014-01-24T09:10:20Z | 21,346,262 | 8 | 2014-01-25T03:31:30Z | [
"python",
"sql",
"postgresql",
"sqlalchemy"
] | SQLAlchemy is generating, but not enabling, sequences for columns in postgresql. I suspect I may be doing something wrong in engine setup.
Using an example from the SQLAlchemy tutorial (<http://docs.sqlalchemy.org/en/rel_0_9/orm/tutorial.html>):
```
#!/usr/bin/env python
from sqlalchemy import create_engine, Column,... | this is because you provided it with an explicit `Sequence`. The `SERIAL` datatype in postgresql generates its *own* sequence, which SQLAlchemy knows how to locate - so if you omit the `Sequence`, SQLAlchemy will render `SERIAL`, assuming the intent is that the column is auto-incrementing (which is determined by the `a... |
shapely and matplotlib point-in-polygon not accurate with geolocation | 21,328,854 | 6 | 2014-01-24T09:23:26Z | 21,420,950 | 8 | 2014-01-29T02:31:20Z | [
"python",
"google-maps-api-3",
"matplotlib",
"point-in-polygon",
"shapely"
] | I am testing the point-in-polygon function with matplotlib and shapely.
Here is a [map](http://plnkr.co/edit/ACvSkWeMXDjBFZ0Ewfha) contains a Bermuda triangle polygon.
**Google maps**'s point-in-polygon functions clearly shows **testingPoint** and **testingPoint2** are inside of the polygon which is a correct result.... | Remember: *the world isn't flat!* If Google Maps' projection is the answer you want, you need to project the geographic coordinates onto [spherical Mercator](http://docs.openlayers.org/library/spherical_mercator.html) to get a different set of X and Y coordinates. [Pyproj](https://pypi.python.org/pypi/pyproj/) can help... |
Iterate two lists in python | 21,329,123 | 2 | 2014-01-24T09:36:21Z | 21,329,165 | 7 | 2014-01-24T09:38:53Z | [
"python",
"arrays",
"list",
"python-2.7"
] | I am having a list of file names created using `dirs = os.listdir(dir/path)`.
Also I am exporting a data set from a csv file. `stocks = csv.reader(open('config.csv', 'rb'))`
Sample stock data:
> fileName1,url1
>
> fileName2,url2
What I need to do is get the each url for each file in the `dirs` list in a python scri... | Pytho provides a built-in function for this, [`zip`](http://docs.python.org/2/library/functions.html#zip):
```
for dir, stock, in zip(dirs, stocks)
```
Demo:
```
>>> a = ["cat", "dogs"]
>>> b = ["http://cat-service.com", "http://dogs-care.com"]
>>> for animal, site in zip(a, b):
print(animal, site)
cat http://... |
Python: count until element in list is a tuple | 21,329,354 | 2 | 2014-01-24T09:47:44Z | 21,329,386 | 8 | 2014-01-24T09:49:26Z | [
"python",
"list",
"python-2.7",
"tuples"
] | I have a list like this:
```
MyList = [2,3,(1,2),5]
```
where the elements 0, 1 and 3 are integers while the element 2 is a tuple. I would like to create a counter which tells me how many elements there are in the list **before the tuple comes**.
In the example, I would like a counter which will take the value 2 (2 e... | Use [`isinstance()`](http://docs.python.org/2/library/functions.html#isinstance) to determine the type of an object:
```
>>> counter = 0
>>> while not isinstance(MyList[counter], tuple):
... counter += 1
...
>>> counter
2
``` |
Python: count until element in list is a tuple | 21,329,354 | 2 | 2014-01-24T09:47:44Z | 21,329,389 | 9 | 2014-01-24T09:49:28Z | [
"python",
"list",
"python-2.7",
"tuples"
] | I have a list like this:
```
MyList = [2,3,(1,2),5]
```
where the elements 0, 1 and 3 are integers while the element 2 is a tuple. I would like to create a counter which tells me how many elements there are in the list **before the tuple comes**.
In the example, I would like a counter which will take the value 2 (2 e... | You can use a `for` loop and `break` out:
```
counter = 0
for elem in MyList:
if isinstance(elem, tuple):
break
counter += 1
```
or, using `enumerate()`:
```
for counter, elem in enumerate(MyList):
if isinstance(elem, tuple):
break
# counter *could* be unbound if `MyList` is empty
```
o... |
Don't call function if None Value returned | 21,329,495 | 3 | 2014-01-24T09:53:37Z | 21,329,555 | 11 | 2014-01-24T09:56:19Z | [
"python",
"syntactic-sugar"
] | suppose you have a function that can return some object or None:
```
def foobar(arg):
if arg == 'foo':
return None
else:
return 'bar'
```
Now you call this method and you want to do something with the object, for this example i get a `str`, so i may want to call the `upper()` function.
There are n... | You can use:
```
(foobar('foo') or '').upper()
```
The expression inside the parenthesis returns a string, even if `foobar()` returns a falsy value.
This *does* result in `None` being replaced by the empty string. If your code relies on `None` being left in place, your best choice still is to use a separate `if` sta... |
Disqus SSO - Not working | 21,331,077 | 5 | 2014-01-24T11:07:02Z | 21,426,292 | 7 | 2014-01-29T08:57:04Z | [
"python",
"django",
"single-sign-on",
"disqus"
] | I am using Python and Django to log into Disqus. The admins have confirmed that the account has SSO enabled and their debug tools confirm that my login token is correct.. However my config seems to be ignore.. Login buttons are not getting replaced and so on..
Here is an example of the JS Disqus implementation..
```
... | We went through several code implementations on GitHub to integrate Disqus SSO in our Django website. Our requirement was a simple one and we used the following workflow for it:
In disqus.py:
```
import base64
import hashlib
import hmac
import json as simplejson
import time
DISQUS_SECRET_KEY = 'SECRET KEY FROM API'
... |
SKLearn - Principal Component Analysis leads to horrible results in knn predictions | 21,331,160 | 4 | 2014-01-24T11:11:32Z | 21,331,792 | 17 | 2014-01-24T11:42:38Z | [
"python",
"machine-learning",
"scikit-learn",
"pca",
"knn"
] | by adding PCA to the algorithm, I'm working to improve %96.5 SKlearn kNN prediction score for kaggle digit recognition tutorial, yet new kNN predictions based on PCA output are horrible like 23%.
below is the full code and i appreciate if you point out where i am mistaken.
```
import pandas as pd
import numpy as np
i... | When you are processing the test data, you used `fit_transform(X_test)` which actually recomputes another PCA transformation on the test data. You should be using `transform(X_test)`, so that the test data undergoes the same transformation as the training data.
The portion of code will look something like (thanks ogri... |
Plot number of occurrences from Pandas DataFrame | 21,331,722 | 4 | 2014-01-24T11:39:12Z | 21,333,244 | 9 | 2014-01-24T12:52:41Z | [
"python",
"matplotlib",
"pandas"
] | I have a DataFrame with two columns. One of them is containing timestamps and another one - id of some action. Something like that:
```
2000-12-29 00:10:00 action1
2000-12-29 00:20:00 action2
2000-12-29 00:30:00 action2
2000-12-29 00:40:00 action1
2000-12-29 00:50:00 action1
...
2000-12-31 00:10:00... | You can get the counts by using
```
df.groupby([df.index.date, 'action']).count()
```
or you can plot directly using this method
```
df.groupby([df.index.date, 'action']).count().plot(kind='bar')
```
You could also just store the results to `count` and then plot it separately. This is assuming that your index is al... |
python split string on whitespace | 21,332,084 | 4 | 2014-01-24T11:58:07Z | 21,332,302 | 7 | 2014-01-24T12:07:46Z | [
"python",
"string",
"split",
"whitespace"
] | I am trying to convert a copy/pasted text to a csv, wich I can split after.
The problem is that there are whitespace tabs in it that I cant seem to get rid of
Example Copy/Paste:
```
Amarr Hybrid Tech Decryptor 12 Decryptors - Hybrid 12 m3
Ancient Coordinates Database 23 Sleeper Components 2.30 ... | I see that you have several `\t` sometimes. I'd use the `re` module to split correctly:
```
for line in lines:
linedata = re.split(r'\t+', line)
print ",".join(linedata)
``` |
Why does mixing types in Python struct.pack uses more space than needed? | 21,332,956 | 6 | 2014-01-24T12:39:07Z | 21,333,154 | 8 | 2014-01-24T12:48:01Z | [
"python",
"pack"
] | I have just tried using struct.pack in Python for the first time, and I don't understand its behaviour when I am mixing types
When I am trying to pack a single char and nothing else, it works as expected, i.e.
```
struct.pack("b",1)
```
gives `'\x01'`. But as soon as I try to mix in data of a different type, the cha... | `struct.pack` is usually used to access memory structures, not files. In memory, accessing data which occupies several bytes at an odd/unaligned address can cause exceptions or performance loss.
That's why compilers align the data (usually on a 4 or 8 byte boundary) and [the `struct` module](http://www.python.org/doc/... |
Combine multiple separate lists into a list of lists | 21,334,073 | 5 | 2014-01-24T13:33:47Z | 21,334,099 | 7 | 2014-01-24T13:34:51Z | [
"python",
"list"
] | Below are three lists which I would like to combine into a single nested list:
```
List_1=[1,2,3]
List_2=[4,5,6]
List_3=[7,8,9]
```
My attempt:
```
List_x=[]
List_x.append(List_1)
List_x.append(List_2)
List_x.append(List_3)
print List_x
```
Result:
```
[[1,2,3],[4,5,6],[7,8,9]]
```
Desired result: Same as the res... | If you need a nested list (list of list), Concat them like this:
```
>>> l1 = [1,2,3]
>>> l2 = [4,5,6]
>>> l3 = [7,8,9]
>>> l123 = [l1,l2,l3]
>>> l123
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
```
If you want a flattened combined list, use [`itertools.chain`](http://docs.python.org/2/library/itertools.html#itertools.chain):
... |
show reverse dependencies with pip? | 21,336,323 | 11 | 2014-01-24T15:26:22Z | 21,336,698 | 7 | 2014-01-24T15:43:23Z | [
"python",
"dependencies",
"pip"
] | Is it possible to show the reverse dependencies with `pip`?
I want to know which package needs package `foo`. And which version of `foo` is needed by this package. | It is possible to do for already installed packages:
```
>>>import pip
>>>package_name = 'pymongo'
>>>rev_dep = [
... pkg.project_name for pkg in pip.get_installed_distributions() if package_name in
... [requirement.project_name for requirement in pkg.requires()]
...]
>>>rev_dep
['mongoengine', 'motor']
``` |
show reverse dependencies with pip? | 21,336,323 | 11 | 2014-01-24T15:26:22Z | 26,300,187 | 10 | 2014-10-10T13:06:32Z | [
"python",
"dependencies",
"pip"
] | Is it possible to show the reverse dependencies with `pip`?
I want to know which package needs package `foo`. And which version of `foo` is needed by this package. | I found Alexander's answer perfect, except it's hard to copy/paste. Here is the same, ready to paste:
```
import pip
def rdeps(package_name):
return [pkg.project_name
for pkg in pip.get_installed_distributions()
if package_name in [requirement.project_name
fo... |
How do I call one Flask view from another one? | 21,340,678 | 10 | 2014-01-24T19:17:12Z | 21,342,070 | 13 | 2014-01-24T20:38:50Z | [
"python",
"flask-login",
"flask"
] | I have a JSON API in one blueprint module, and a web frontend in another one.
I would like to shave off a few AJAX requests the client JS code would have to make by embedding some of the JSON it'll need in the frontend view template, before sending it to the client, [like in this gist I found](https://gist.github.com/... | You can use a [Flask test client](http://flask.pocoo.org/docs/api/#flask.Flask.test_client) for this:
```
client = app.test_client()
response = client.get('/your/url', headers=list(request.headers))
```
To keep the authentication with Flask-Login you need to pass your request's headers.
Thanks to [Chris McKinnel](ht... |
how to get endianess in Java or python? | 21,341,325 | 2 | 2014-01-24T19:54:07Z | 21,341,417 | 7 | 2014-01-24T19:59:08Z | [
"java",
"python",
"c",
"endianness"
] | In `C` I could the `Endianess` of the machine by the following method. how would I get using a `python` or `Java` program?. In Java, char is `2-bytes` unlike `C` where it is `1-byte`. I think it might not be possible with `python` since it is a `dynamic language`, but I could be wrong
```
bool isLittleEndian()
{
... | In Java, it's just
```
ByteOrder.nativeOrder();
```
...which returns either `BIG_ENDIAN` or `LITTLE_ENDIAN`.
<http://docs.oracle.com/javase/6/docs/api/java/nio/ByteOrder.html> |
Error importing Theano | 21,342,931 | 9 | 2014-01-24T21:36:38Z | 21,345,831 | 12 | 2014-01-25T02:25:28Z | [
"python",
"theano"
] | After installing python, numpy, scipy and theano to ~/.local, I tried to import theano but it threw an error:
```
>>> import theano
Problem occurred during compilation with the command line below:
g++ -shared -g -march=core2 -mcx16 -msahf --param l1-cache-size=32 --param l1-cache-line-size=64 --param l2-cache-size=409... | You didn't build correctly python. It wasn't compiled with the -fPIC parameter. Look at how to compile python with a shared library.
EDIT:
You need to compile python like this:
```
./configure --enable-shared
make
make install
``` |
Why does a Python Iterator need an iter method that simply returns self? | 21,343,327 | 3 | 2014-01-24T22:04:06Z | 21,343,400 | 7 | 2014-01-24T22:08:56Z | [
"python",
"iterator"
] | I understand that the standard says that it does but I am trying to find the underlying reason for this.
If it simply always returns `self` what is the need for it?
You clearly always have access to the object since you are calling `iter` on that object, so what's the need for having it? | Imagine you want to write code that iterates over any kind of iterable. Normally you'd just write a `for` statement or comprehension, but let's instead explicitly do what `for` does under the covers, to make things more obvious:
```
i = iter(iterable)
while True:
try:
val = next(i)
except StopIteration... |
ImportError: no module named win32api | 21,343,774 | 14 | 2014-01-24T22:39:12Z | 35,948,588 | 18 | 2016-03-11T19:43:19Z | [
"python",
"winapi"
] | I am using python 2.7 and i want to use pywin32-214 on windows 7. I installed pywin32-214 by using msi installer. But when i import win32api in my python script then it throws error "no module named win32api". what should i do? Can I use pywin32 api for windows 7? | This is resolve my case as found on
[Where to find the win32api module for Python?](http://stackoverflow.com/questions/3580855/where-to-find-the-win32api-module-for-python)
```
pip install pypiwin32
``` |
creating sets of tuples in python | 21,344,938 | 4 | 2014-01-25T00:28:57Z | 21,344,966 | 8 | 2014-01-25T00:31:11Z | [
"python",
"tuples"
] | How do i create a set of tuples with each tuple containing two elements? Each tuple will have an `x` and `y` value: `(x,y)`
I have the numbers 1 through 50, and want to assign `x` to all values 1 through 50 and `y` also 1 through 50.
```
S = {(1,1),(1,2),(1,3),(1,4)...(1,50),(2,1)......(50,50)}
```
I tried
```
posit... | ```
mySet = set(itertools.product(range(1,51), repeat=2))
```
OR
```
mySet = set((x,y) for x in range(1,51) for y in range(1,51))
``` |
python selenium click on button | 21,350,605 | 15 | 2014-01-25T12:36:12Z | 21,350,625 | 25 | 2014-01-25T12:39:13Z | [
"python",
"python-2.7",
"selenium",
"selenium-webdriver"
] | I am quite new to python selenium and I am trying to click on a button which has the following html structure:
```
<div class="b_div">
<div class="button c_button s_button" onclick="submitForm('mTF')">
<input class="very_small" type="button"></input>
<div class="s_image"></div>
<span>
... | Remove space between classes in css selector:
```
driver.find_element_by_css_selector('.button .c_button .s_button').click()
# ^ ^
```
=>
```
driver.find_element_by_css_selector('.button.c_button.s_button').click()
``` |
Split a string to even sized chunks | 21,351,275 | 5 | 2014-01-25T13:39:01Z | 21,351,295 | 10 | 2014-01-25T13:40:47Z | [
"python",
"string",
"tuples"
] | How would I be able to take a string like `'aaaaaaaaaaaaaaaaaaaaaaa'`
and split it into 4 length tuples like (`aaaa`,`aaaa`,`aaaa`) | Use [`textwrap.wrap`](http://docs.python.org/2/library/textwrap.html#textwrap.wrap):
```
>>> import textwrap
>>> s = 'aaaaaaaaaaaaaaaaaaaaaaa'
>>> textwrap.wrap(s, 4)
['aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaa']
``` |
Reading data from a CSV file online in Python 3 | 21,351,882 | 4 | 2014-01-25T14:37:15Z | 21,351,911 | 7 | 2014-01-25T14:40:31Z | [
"python",
"csv"
] | Just testing something out as practice. I have this huge CSV file online
<https://raw.github.com/datasets/gdp/master/data/gdp.csv>
And I want to read all the data and put it into a table so I can do analyse it and make tables.
The code I have so far was put together using other StackOverflow questions and other website... | You need to split the read CSV data by lines before passing it to the `csv.reader()`:
```
datareader = csv.reader(webpage.read().decode('utf-8').splitlines())
```
The `csv.reader()` then takes care of the rest for you.
You could also have [`io.TextIOWrapper()`](http://docs.python.org/3/library/io.html#io.TextIOWrapp... |
Matplotlib: Plotting numerous disconnected line segments with different colors | 21,352,580 | 12 | 2014-01-25T15:40:57Z | 21,357,666 | 30 | 2014-01-25T23:35:46Z | [
"python",
"matplotlib",
"plot",
"line"
] | I have a set of data records like this:
```
(s1, t1), (u1, v1), color1
(s2, t2), (u2, v2), color2
.
.
.
(sN, tN), (uN, vN), colorN
```
In any record, the first two values are the **end-points** of a line segment, the third value is the **color** of that line segment. More specifically, `(sn, tn)` are the x-y coordina... | use `LineCollection`:
```
import numpy as np
import pylab as pl
from matplotlib import collections as mc
lines = [[(0, 1), (1, 1)], [(2, 3), (3, 3)], [(1, 2), (1, 3)]]
c = np.array([(1, 0, 0, 1), (0, 1, 0, 1), (0, 0, 1, 1)])
lc = mc.LineCollection(lines, colors=c, linewidths=2)
fig, ax = pl.subplots()
ax.add_collec... |
How can I insert a new tag into a BeautifulSoup object? | 21,356,014 | 8 | 2014-01-25T20:44:25Z | 21,356,230 | 12 | 2014-01-25T21:04:02Z | [
"python",
"beautifulsoup"
] | Trying to get my head around html construction with BS.
I'm trying to insert a new tag:
```
self.new_soup.body.insert(3, """<div id="file_history"></div>""")
```
when I check the result, I get:
```
<div id="file_histor"y></div>
```
So I'm inserting a string that being sanitised for websafe html..
What... | See the documentation on [how to append a tag](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#navigablestring-and-new-tag):
```
soup = BeautifulSoup("<b></b>")
original_tag = soup.b
new_tag = soup.new_tag("a", href="http://www.example.com")
original_tag.append(new_tag)
original_tag
# <b><a href="http://www.ex... |
urrlib2.urlopen: "Name or service not known" persists when starting script without internet connection | 21,356,781 | 4 | 2014-01-25T21:58:49Z | 21,356,898 | 8 | 2014-01-25T22:09:47Z | [
"python",
"urllib2"
] | I have this simple minimal 'working' example below that opens a connection to google every two seconds. When I run this script when I have a working internet connection, I get the Success message, and when I then disconnect, I get the Fail message and when I reconnect again I get the Success again. So far, so good.
Ho... | This happens because the DNS name "www.google.com" cannot be resolved. If there is no internet connection the DNS server is probably not reachable to resolve this entry.
It seems I misread your question the first time. The behaviour you describe is, on Linux, a peculiarity of glibc. It only reads "/etc/resolv.conf" on... |
Using Numpy creates a tcl folder when using py2exe | 21,358,042 | 6 | 2014-01-26T00:20:52Z | 21,409,769 | 10 | 2014-01-28T15:28:27Z | [
"python",
"numpy",
"py2exe"
] | When using `py2exe` on my Python program I get an executable, but also a `tcl\` folder.
This is strange, because I don't use `tcl/tk` at all and nothing related to `tkinter` in my code.
**Why importing `numpy` is responsible for adding this `tcl\` folder ? How to prevent this to happen ?**
---
**test.py**
```
impo... | `Modulefinder` module which is used to determine dependencies gets "confused" and thinks you need `Tkinter`.
If you run following script...
```
from modulefinder import ModuleFinder
finder = ModuleFinder()
finder.run_script('test.py')
print finder.report()
```
...you will see found modules (shortened):
```
Name ... |
NumPy List Comprehension Syntax | 21,360,028 | 3 | 2014-01-26T05:18:18Z | 21,360,107 | 10 | 2014-01-26T05:31:24Z | [
"python",
"numpy"
] | I'd like to be able to use list comprehension syntax to work with NumPy arrays easily.
For instance, I would like something like the below obviously wrong code to just reproduce the same array.
```
>>> X = np.random.randn(8,4)
>>> [[X[i,j] for i in X] for j in X[i]]
Traceback (most recent call last):
File "<stdin>"... | First, you should not be using NumPy arrays as lists of lists.
Second, let's forget about NumPy; your listcomp doesn't make any sense in the first place, even for lists of lists.
In the inner comprehension, `for i in X` is going to iterate over the rows in X. Those rows aren't numbers, they're lists (or, in NumPy, 1D... |
Python's sqlite3 module exceptions --- where is the documentation? | 21,360,271 | 8 | 2014-01-26T05:54:32Z | 21,361,010 | 9 | 2014-01-26T07:44:56Z | [
"python",
"exception",
"exception-handling",
"sqlite3",
"documentation"
] | I'm using Python 2.6.9 with the sqlite3 module. When I do something like:
```
userdb = sqlite3.connect("UserDatabase")
```
I want to wrap it in a try/except so that if, say, the connection fails, I can make an attempt to connect to another version of the database and notify the user that they are utilizing an older v... | From [the module source code](https://github.com/ghaering/pysqlite/blob/master/src/connection.c), it appears that the only special kind of exception raised (discarding common Python exceptions raised by internal calls) comes from a call to `sqlite3_open()`, about which the [sqlite3 documentation](http://www.sqlite.org/... |
how to dynamically update a plot in a loop in ipython notebook (within one cell) | 21,360,361 | 32 | 2014-01-26T06:10:38Z | 21,361,994 | 39 | 2014-01-26T09:51:06Z | [
"python",
"matplotlib",
"pandas",
"ipython",
"ipython-notebook"
] | Environment: Python 2.7, matplotlib 1.3, IPython notebook 1.1, linux, chrome. The code is in one single input cell, using `--pylab=inline`
I want to use IPython notebook and pandas to consume a stream and dynamically update a plot every 5 seconds.
When I just use print statement to print the data in text format, it w... | use `IPython.display` module:
```
%matplotlib inline
import time
import pylab as pl
from IPython import display
for i in range(10):
pl.plot(pl.randn(100))
display.clear_output(wait=True)
display.display(pl.gcf())
time.sleep(1.0)
``` |
how to dynamically update a plot in a loop in ipython notebook (within one cell) | 21,360,361 | 32 | 2014-01-26T06:10:38Z | 24,804,512 | 15 | 2014-07-17T13:09:07Z | [
"python",
"matplotlib",
"pandas",
"ipython",
"ipython-notebook"
] | Environment: Python 2.7, matplotlib 1.3, IPython notebook 1.1, linux, chrome. The code is in one single input cell, using `--pylab=inline`
I want to use IPython notebook and pandas to consume a stream and dynamically update a plot every 5 seconds.
When I just use print statement to print the data in text format, it w... | You can further improve this by adding `wait=True` to `clear_output`:
```
display.clear_output(wait=True)
display.display(pl.gcf())
``` |
Specific sort a list of numbers separated by dots | 21,361,604 | 7 | 2014-01-26T09:03:34Z | 21,361,618 | 8 | 2014-01-26T09:04:50Z | [
"python",
"list",
"sorting"
] | I have a list:
```
L = ['1.1.1.', '1.1.10.', '1.1.11.', '1.1.12.', '1.1.13.', '1.1.2.', '1.1.3.', '1.1.4.']
```
I want to sort it in next order:
```
1.1.1.
1.1.2.
1.1.3.
1.1.4.
1.1.10.
1.1.11.
1.1.12.
1.1.13.
```
The following method does not produce a result:
```
L.sort(key=lambda s: int(re.search(r'.(\d+)',s).gr... | Just get the last part, convert that to an int and return it as the key for comparison
```
print(sorted(L, key=lambda x: int(x.split(".")[2])))
```
If you want **all the parts to be considered**, you can do like this
```
print(sorted(L, key=lambda x: [int(i) for i in x.rstrip(".").split(".")]))
```
It removes `.` a... |
Bad input shape error on SVM training using scikit | 21,362,489 | 3 | 2014-01-26T10:53:15Z | 21,362,978 | 8 | 2014-01-26T11:51:39Z | [
"python",
"machine-learning",
"svm",
"scikit-learn"
] | I m a little new to scikit and ML. I m trying to train an SVM classifier for one vs all classification. I m using the following code.
```
g=list()
for i in range(0,120):
g.append(1)
for i in range(120,240):
g.append(2)
u=set(g)
numclasses=len(u)
lin_clf = svm.LinearSVC()
lin_clf.fit(features,u)
```
Features... | Which line of the code is throwing the error? Is it `lin_clf.fit(features,u)`?
According to the [documentation](http://scikit-learn.org/stable/modules/generated/sklearn.svm.LinearSVC.html) of LinearSVC, the arguments for `fit(X,y)` are
> X : {array-like, sparse matrix}, shape = [n\_samples, n\_features]
>
> Training ... |
Using Flask-Mail asynchronously results in "RuntimeError: working outside of application context" | 21,362,700 | 4 | 2014-01-26T11:18:25Z | 21,369,001 | 13 | 2014-01-26T20:50:00Z | [
"python",
"flask",
"python-multithreading",
"flask-mail"
] | I am trying to send some mail asynchronously (based on the code in [The Flask Mega-Tutorial, Part XI: Email Support](http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xi-email-support)). However, I get the following error about working outside an application context. How do I fix this problem?
```
Trace... | The code should run in an app context. Add `with app.app_context()`:
```
@async
def send_async_email(msg):
with app.app_context():
mail.send(msg)
``` |
Interpret numpy.fft.fft2 output | 21,362,843 | 4 | 2014-01-26T11:33:55Z | 21,364,096 | 8 | 2014-01-26T13:39:33Z | [
"python",
"numpy",
"fft",
"frequency-distribution"
] | My goal is to obtain a plot with the spatial frequencies of an image - kind of like doing a fourier transformation on it. I don't care about the position on the image of features with the frequency f (for instance); I'd just like to have a graphic which tells me how much of every frequency I have (the amplitude for a f... | `freq` has a few very large values, and lots of small values. You can see that by plotting
```
plt.hist(freq.ravel(), bins=100)
```
(See below.) So, when you use
```
ax1.imshow(freq, interpolation="none")
```
Matplotlib uses `freq.min()` as the lowest value in the color range (which is by default colored blue), and... |
AssertionError - no exception supplied - django | 21,363,285 | 7 | 2014-01-26T12:25:18Z | 21,363,464 | 20 | 2014-01-26T12:42:29Z | [
"python",
"django",
"python-2.7"
] | I am really confused not knowing what it wants from me.
this is my simple function
```
def confirm_abo(request):
try:
abo = Abonnement.objects.get(id=int(request.GET.get('abocid')))
abo.status = 1
abo.save()
link = "http://127.0.0.1:8000/delete_link/?abocid=" + str(abo.id)
subject = "t... | Check the template `abc_confirm.html` whether it contains invalid tag usage like following:
```
{% if x == '0' %}
...
{% else if x == '1' %} {# used `else if` instead of `elif` %}
...
{% endif %}
```
could cause `AssertionError` ..:
```
>>> from django.template import Template, Context
>>>
>>> t = Template('''
...... |
Plot inside Ipython Notebook | 21,363,357 | 3 | 2014-01-26T12:32:10Z | 21,363,373 | 10 | 2014-01-26T12:33:53Z | [
"python",
"matplotlib",
"ipython",
"ipython-notebook"
] | I'm using IPython notebooks to share code and (hopefully) graphics with m collaborators. sadly, I cannot get matplotlib to plot inside the notebook, it always gives me a pop-up window, which I obviously cannot include in [notebook pastes](http://nbviewer.ipython.org/) or similar.
Here's two minimal examples of how I g... | You need to be using the [matplotlib inline backend](http://ipython.org/ipython-doc/dev/interactive/notebook.html#plotting).
```
%matplotlib inline
``` |
Celery worker and command line args | 21,365,101 | 7 | 2014-01-26T15:15:07Z | 21,432,683 | 8 | 2014-01-29T13:35:16Z | [
"python",
"celery"
] | I am refactoring my code to use celery worker.
Before I used to use argparse to pass command line args.
e.g.
```
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Node')
parser.add_argument('--environment', action="store", default='local', help="env e.g. production of development")
... | The Celery worker does not execute your `__main__`.
If you want to add additional command-line options you can use `app.user_options`,
but note that it uses the `optparse` module, not `argparse`.
See this section in the docs for more:
<http://docs.celeryproject.org/en/latest/userguide/extending.html#preload-options> |
'instancemethod' object has no attribute '__getitem__' with class variables | 21,365,521 | 4 | 2014-01-26T15:47:45Z | 21,365,593 | 7 | 2014-01-26T15:53:04Z | [
"python",
"raspberry-pi"
] | I'm trying to create a python class to control stepper motors using my Raspberry Pi. It mostly works, however I keep on getting an "'instancemethod' object has no attribute `'__getitem__'` error whenever I define a list as a class variable. The error message lists this piece of code as the culprit but I can't see anyth... | You didn't post the full traceback, but I can take a guess:
```
def clockwise(self,speed):
seq = stepper.clockwise
self.WaitTime = (1.0 / (self.stepNum * self.coilNum)) * speed
for pin in range(0, 4):
xpin = self.pinarray[pin]
if seq[self.StepCounter][pin]!=0:
```
You set `seq` equal to th... |
Searching for equivalent of FileNotFoundError in Python 2 | 21,367,320 | 18 | 2014-01-26T18:17:18Z | 21,368,457 | 11 | 2014-01-26T19:59:03Z | [
"python",
"json",
"file",
"python-2.7",
"python-3.x"
] | I created a class named Options. It works fine but not not with Python 2.
And I want it to work on both Python 2 and 3.
The problem is identified: FileNotFoundError doesn t exist in Python 2.
But if I use IOError it doesn t work in Python 3
Changed in version 3.3: EnvironmentError, IOError, WindowsError, VMSError, soc... | You can use the base class exception [EnvironmentError](http://docs.python.org/2/library/exceptions.html#exceptions.EnvironmentError) and use the 'errno' attribute to figure out which exception was raised:
```
from __future__ import print_function
import os
import errno
try:
open('no file of this name') # gene... |
Searching for equivalent of FileNotFoundError in Python 2 | 21,367,320 | 18 | 2014-01-26T18:17:18Z | 21,368,622 | 13 | 2014-01-26T20:14:27Z | [
"python",
"json",
"file",
"python-2.7",
"python-3.x"
] | I created a class named Options. It works fine but not not with Python 2.
And I want it to work on both Python 2 and 3.
The problem is identified: FileNotFoundError doesn t exist in Python 2.
But if I use IOError it doesn t work in Python 3
Changed in version 3.3: EnvironmentError, IOError, WindowsError, VMSError, soc... | If `FileNotFoundError` isn't there, define it:
```
try:
FileNotFoundError
except NameError:
FileNotFoundError = IOError
```
Now you can catch `FileNotFoundError` in Python 2 since it's really `IOError`.
Be careful though, `IOError` has other meanings. In particular, any message should probably say "file coul... |
How to calculate the distance between two points using return methods in python? | 21,369,449 | 4 | 2014-01-26T21:27:46Z | 21,370,385 | 8 | 2014-01-26T22:56:25Z | [
"python",
"return",
"distance"
] | I'm still new to python and have been trying to get the hang of it. I've been trying to learn simple return methods but I can't seem to get the hang of it.
I have been trying to find the distance between two points and this is what I have so far.
If anyone could help me figure this out it would be very helpful! Thank y... | Why don't you use math.hypot() to calculate the distance?
```
>>> import math
>>> p1 = (3, 5) # point 1 coordinate
>>> p2 = (5, 7) # point 2 coordinate
>>> math.hypot(p2[0] - p1[0], p2[1] - p1[1]) # Linear distance
2.8284271247461903
``` |
How to preprocess data for machine learning? | 21,370,087 | 5 | 2014-01-26T22:25:39Z | 21,370,423 | 15 | 2014-01-26T23:00:55Z | [
"python",
"machine-learning",
"artificial-intelligence",
"preprocessor",
"scikit-learn"
] | I just wanted some general tips on how data should be pre-processed prior to feeding it into a machine learning algorithm. I'm trying to further my understanding of why we make different decisions at preprocessing times and if someone could please go through all of the different things we need to consider when cleaning... | There is a lot of things which need to be decided according to the actual data. It is not as simple as naming a few steps you need to do always when you get data.
However, I can try to name a few of things which usually help a lot. Still, the first and the most important thing is to thoroughly analyze the data and mak... |
How to Access Hive via Python? | 21,370,431 | 17 | 2014-01-26T23:01:46Z | 26,061,902 | 13 | 2014-09-26T14:24:36Z | [
"python",
"hadoop",
"hive"
] | <https://cwiki.apache.org/confluence/display/Hive/HiveClient#HiveClient-Python> appears to be outdated.
When I add this to /etc/profile:
```
export PYTHONPATH=$PYTHONPATH:/usr/lib/hive/lib/py
```
I can then do the imports as listed in the link, with the exception of `from hive import ThriftHive` which actually need ... | I assert that you are using HiveServer2, which is the reason that makes the code doesn't work.
You may use pyhs2 to access your Hive correctly and the example code like that:
```
import pyhs2
with pyhs2.connect(host='localhost',
port=10000,
authMechanism="PLAIN",
user='ro... |
How to Access Hive via Python? | 21,370,431 | 17 | 2014-01-26T23:01:46Z | 33,560,819 | 12 | 2015-11-06T06:33:28Z | [
"python",
"hadoop",
"hive"
] | <https://cwiki.apache.org/confluence/display/Hive/HiveClient#HiveClient-Python> appears to be outdated.
When I add this to /etc/profile:
```
export PYTHONPATH=$PYTHONPATH:/usr/lib/hive/lib/py
```
I can then do the imports as listed in the link, with the exception of `from hive import ThriftHive` which actually need ... | I believe the easiest way is to use PyHive.
To install you'll need these libraries:
```
pip install sasl
pip install thrift
pip install thrift-sasl
pip install PyHive
```
Please note that although you install the library as `PyHive`, you import the module as `pyhive`, all lower-case.
If you're on Linux, you may nee... |
pyparsing performance and memory usage | 21,370,697 | 8 | 2014-01-26T23:31:00Z | 21,371,472 | 10 | 2014-01-27T01:09:27Z | [
"python",
"performance",
"pyparsing"
] | Pyparsing worked fine for a very small grammar, but as the grammar has grown, the performance went down and the memory usage through the roof.
My current gramar is:
```
newline = LineEnd ()
minus = Literal ('-')
plus = Literal ('+')
star = Literal ('*')
dash = Literal ('/')
dashdash = Literal ('//')
percent = Literal... | After importing pyparsing enable packrat parsing to memoize parse behavior:
```
ParserElement.enablePackrat()
```
This should make a big improvement in performance. |
Cleanly setting max_retries on Python requests get or post method | 21,371,809 | 5 | 2014-01-27T01:54:28Z | 21,371,922 | 16 | 2014-01-27T02:10:25Z | [
"python",
"python-requests"
] | Related to older version of requests question: [Can I set max\_retries for requests.request?](http://stackoverflow.com/questions/15431044/can-i-set-max-retries-for-requests-request)
I have not seen an example to cleanly incorporate max\_retries in a requests.get() or requests.post() call.
Would love a requests.get(ur... | A quick search of the [python-requests docs](https://python-requests.org) will [reveal exactly how to set `max_retries`](http://docs.python-requests.org/en/latest/api/?highlight=max_retries#requests.adapters.HTTPAdapter) when using a `Session`.
To pull the code directly from the documentation:
```
import requests
s =... |
SWIG in typemap works, but argout does not | 21,373,259 | 10 | 2014-01-27T04:53:44Z | 21,414,174 | 13 | 2014-01-28T18:45:08Z | [
"python",
"swig"
] | I have this file `foobar.h`
```
class Foobar {
public: void method(int arg[2]) {};
};
```
After compiling SWIG interface to Python, if I try to run this method from Python it says
```
TypeError: in method 'Foobar_method', argument 2 of type 'int [2]'
```
Certainly. So I write this SWIG typemap:
```
%typemap(in) in... | ## What's wrong?
In short it's not an either/or proposition with these typemaps.
The key bit of information you're missing is the way multiple typemaps cooperate to wrap a single function.
`argout` gets inserted in the generated wrapper *after* the call has happened. It's your opportunity to copy the (now modified) ... |
django rest framework filter | 21,374,253 | 16 | 2014-01-27T06:21:18Z | 21,376,522 | 26 | 2014-01-27T08:56:02Z | [
"python",
"django",
"django-rest-framework",
"django-filter"
] | I'm working with API made from Django rest framework,
I am trying to make a filter to a JSON
This is my `serializers.py` file
```
from rest_framework import serializers
from .models import Establecimiento,Categoria,Ciudad,Zona
import django_filters
class EstablecimientoSerializer(serializers.ModelSerializer):
cla... | You need to define filter backend and all related fields you're planning to filter on:
```
class EstablecimientoViewSet(viewsets.ModelViewSet):
filter_backends = (filters.DjangoFilterBackend,)
filter_fields = ('categoria', 'categoria__titulo',)
```
example:
```
URL?categoria__titulo=Categoria 1
``` |
subtuples for a tuple | 21,384,752 | 6 | 2014-01-27T15:27:10Z | 21,385,106 | 7 | 2014-01-27T15:42:47Z | [
"python",
"algorithm",
"python-3.x"
] | I wish to yield the following:
```
(('A',), ('B',), ('C',), ('D',))
(('A',), ('B',), ('C','D'))
(('A',), ('B','C'), ('D',))
(('A',), ('B','C','D'))
(('A','B'), ('C',), ('D',))
(('A','B'), ('C','D'))
(('A','B','C'), ('D',))
(('A','B','C','D'),)
```
when calling `sub_combinations(('A', 'B', 'C', 'D'))`
Here's my attem... | Handle base case - when `segment` is empty:
```
def sub_combinations(segment, size=0):
if segment == ():
yield ()
return
stop = min(size or len(segment), len(segment))
for i in range(1, stop + 1):
for j in sub_combinations(segment[i:], size):
yield (segment[:i],) + j
```... |
How to check the version of scipy | 21,385,196 | 29 | 2014-01-27T15:46:37Z | 21,385,217 | 39 | 2014-01-27T15:47:21Z | [
"python",
"scipy"
] | How can I check the version of `scipy` installed on my system? | ```
In [95]: import scipy
In [96]: scipy.__version__
Out[96]: '0.12.0'
In [104]: scipy.version.*version?
scipy.version.full_version
scipy.version.short_version
scipy.version.version
In [105]: scipy.version.full_version
Out[105]: '0.12.0'
In [106]: scipy.version.git_revision
Out[106]: 'cdd6b32233bbecc3e8cbc82531905b... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.