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 |
|---|---|---|---|---|---|---|---|---|---|
Creating ngrams from scikit learn and count vectorizer throws Memory Error | 26,887,745 | 2 | 2014-11-12T13:07:23Z | 26,891,673 | 7 | 2014-11-12T16:23:17Z | [
"python",
"memory",
"numpy",
"scikit-learn",
"n-gram"
] | I am building **ngrams** from multiple text documents using **scikit-learn**. I need to build **document-frequency** using **countVectorizer**.
**Example** :
```
document1 = "john is a nice guy"
document2 = "person can be a guy"
```
So, **document-frequency** will be
```
{'be': 1,
'can': 1,
'guy': 2,
'is': 1,
... | As the comments have mentioned, you're running into memory issues when you convert the large sparse matrices to dense format. Try something like this:
```
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
document = [Huge amount of data around 7MB] # ['john is a guy', 'person guy']
vectori... |
Is it possible to disable pylint missing docstring error for short functions and methods? | 26,889,188 | 6 | 2014-11-12T14:20:05Z | 26,889,689 | 12 | 2014-11-12T14:45:41Z | [
"python",
"coding-style",
"pylint"
] | Pylint reports an error for every function and method (except `__init__`) that has no docstring.
This is generally desirable, so I don't want to disable it globally (in `pylintrc`, or at file level).
However, in my opinion, there are cases where a docstring is not necessary, and even harmful. For example:
```
def ge... | Using pylint 1.3.1 add a line to you pylintrc `docstring-min-length=10` for example.
It is described in the generated pylintrc `pylint --generate-rcfile` file as
> Minimum line length for functions/classes that require docstrings, shorter ones are exempt.
[Documentation reference](https://docs.pylint.org/en/latest/r... |
Flipping zeroes and ones in one-dimensional NumPy array | 26,890,477 | 7 | 2014-11-12T15:25:25Z | 26,890,710 | 17 | 2014-11-12T15:35:33Z | [
"python",
"arrays",
"numpy"
] | I have a one-dimensional NumPy array that consists of zeroes and ones like so:
```
array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
```
I'd like a quick way to just "flip" the values such that zeroes become ones, and ones become zeroes, resulting in a NumPy array like this:
```
array([1, 1, 1, 1, 1, 0, 0, 0, 0, ... | There must be something in your Q that i do not understand...
Anyway
```
In [2]: from numpy import array
In [3]: a = array((1,0,0,1,1,0,0))
In [4]: b = 1-a
In [5]: print a ; print b
[1 0 0 1 1 0 0]
[0 1 1 0 0 1 1]
In [6]:
``` |
Flipping zeroes and ones in one-dimensional NumPy array | 26,890,477 | 7 | 2014-11-12T15:25:25Z | 26,893,313 | 7 | 2014-11-12T17:50:39Z | [
"python",
"arrays",
"numpy"
] | I have a one-dimensional NumPy array that consists of zeroes and ones like so:
```
array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
```
I'd like a quick way to just "flip" the values such that zeroes become ones, and ones become zeroes, resulting in a NumPy array like this:
```
array([1, 1, 1, 1, 1, 0, 0, 0, 0, ... | A sign that you should probably be using a boolean datatype
```
a = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=np.bool)
# or
b = ~a
b = np.logical_not(a)
``` |
Selecting pandas cells with None value | 26,893,419 | 7 | 2014-11-12T17:57:19Z | 26,893,443 | 11 | 2014-11-12T17:58:36Z | [
"python",
"pandas",
null,
"na"
] | I have have a column of a pandas dataframe that I got from a database query with blanck cells. The blank cells become "None" and I want to check if each of the rows is None:
```
In [325]: yes_records_sample['name']
Out[325]:
41055 John J Murphy Professional Building
25260 None
417... | Call it like this:
```
yes_records_sample['name'].isnull()
``` |
AttributeError: 'module' object has no attribute 'TestCase' | 26,893,504 | 4 | 2014-11-12T18:02:07Z | 26,894,284 | 16 | 2014-11-12T18:47:19Z | [
"python",
"unit-testing",
"assertions"
] | I have file with unittest named: test.py
My code:
```
import unittest
class Test(unittest.TestCase):
def myTest(self):
a = 1
self.assertEqual(a, 1)
if __name__ == '__main__':
unittest.main()
```
When I press F5, I get an error:
```
Traceback (most recent call last):
File "/home/mariusz... | You have a local file named `unittest.py` that is being imported instead:
```
/home/mariusz/Pulpit/unittest.py
```
Rename that file or remove it altogether. Make sure you remove any corresponding `unittest.pyc` file in the same folder if it is there.
The file is masking the standard library package. |
sum of squares in a list in one line? | 26,894,227 | 2 | 2014-11-12T18:44:12Z | 26,894,273 | 9 | 2014-11-12T18:46:34Z | [
"python",
"list",
"sum"
] | To demonstrate I have done sth.
This is my code do sum in three lines.
```
l=[1,2,3,4,5];
sum=0
for i in l:
sum+=i*i;
print sum
```
I am curious can I do it in just one line? | yes you can : here it is using `sum` function
```
l = [1,2,3,4,5]
sum( i*i for i in l)
``` |
Renaming PyCharm project does not change name at top of window | 26,894,942 | 4 | 2014-11-12T19:27:28Z | 26,895,823 | 14 | 2014-11-12T20:19:42Z | [
"python",
"pycharm"
] | In PyCharm, I can refactor the project by right clicking on it in the menu on the left. However, this does not change the name in the blue bar right at the top of the PyCharm window, where it also shows the project path on your machine. Why not? | The UI doesn't seem to set the configuration files correctly. It is probably a bug.
If you edit: `<projectdir>/.idea/.name` you can set the name there.
You will have to restart PyCharm for this to take effect. |
Is there a way to find out if A is a submatrix of B? | 26,896,687 | 6 | 2014-11-12T21:14:11Z | 26,896,942 | 10 | 2014-11-12T21:29:40Z | [
"python",
"algorithm",
"math",
"numpy",
"matrix"
] | I give quotation mark because what I mean is for example:
```
B = [[1,2,3,4,5],
[6,7,8,9,10],
[11,12,13,14,15],
[16,17,18,19,20]]
```
suppose we select row 2,4 and col 1,3, the intersections will give us
```
A = [[6,8],
[16,18]]
```
My question is suppose I have A and B, is there a way that I ca... | This is a very hard combinatorial problem. In fact the [Subgraph Isomorphism Problem](http://en.wikipedia.org/wiki/Subgraph_isomorphism_problem) can be reduced to your problem (in case the matrix `A` only has 0-1 entries, your problem is exactly a subgraph isomorphism problem). This problem is known to be NP-complete.
... |
Python NLTK: SyntaxError: Non-ASCII character '\xc3' in file (Senitment Analysis -NLP) | 26,899,235 | 15 | 2014-11-13T00:22:35Z | 26,899,264 | 44 | 2014-11-13T00:25:03Z | [
"python",
"unicode",
"nlp",
"nltk"
] | I am playing around with NLTK to do an assignment on sentiment analysis. I am using Python 2.7. NLTK 3.0 and NUMPY 1.9.1 version.
This is code :
```
__author__ = 'karan'
import nltk
import re
import sys
def main():
print("Start");
# getting the stop words
stopWords = open("english.txt","r");
stop_w... | Add the following to the top of your file `# coding=utf-8`
If you go to the link in the error you can seen the reason why:
**Defining the Encoding**
*Python will default to ASCII as standard encoding if no other
encoding hints are given.
To define a source code encoding, a magic comment must
be placed into the sourc... |
How to find perfect squares in a range efficiently when the inputs are large numbers in Python | 26,901,210 | 2 | 2014-11-13T04:12:06Z | 26,901,240 | 7 | 2014-11-13T04:15:53Z | [
"python",
"largenumber",
"perfect-square"
] | The question is how to find perfect squares in a given range efficiently when the inputs are very large numbers. My solution is giving `Time Limit Exceeded` error. I have already checked the following links, but they didn't solve my problem:
- [Python Program on Perfect Squares](http://stackoverflow.com/questions/175... | Instead of looping from `A` to `B` and checking for perfect squares, why not just loop through the integers from `sqrt(A)` to `sqrt(B)` and square each, giving you your answer.
For example, let's find the square numbers between 1000 and 2000:
```
sqrt(1000) = 31.6 --> 32 (need the ceiling here)
sqrt(2000) = 44.7 ... |
How to use refresh token for getting new access token(django-oauth-toolkit)? | 26,903,087 | 3 | 2014-11-13T07:00:55Z | 27,751,200 | 8 | 2015-01-03T02:37:27Z | [
"python",
"django",
"oauth"
] | I am using [django-oauth-toolkit 0.7](https://github.com/evonove/django-oauth-toolkit) in my django project for providing oauth through my website, I have followed the steps [here](https://django-oauth-toolkit.readthedocs.org/en/0.7.0/tutorial/tutorial_01.html) and successfully got the access token.But i am unable to g... | To get a new `access_token`, by using your existing `refresh_token` you need to send a POST request to the same url you used to get the token in the first place (`/o/token/`, assuming the default url). The `grant_type` would now be `refresh_token`, and you also need to authenticate with your client credentials, since y... |
Django Rest Framework - Authentication credentials were not provided | 26,906,630 | 13 | 2014-11-13T10:27:45Z | 26,907,225 | 20 | 2014-11-13T10:55:32Z | [
"python",
"django",
"django-rest-framework"
] | I'm developing an API using Django Rest Framework. I'm trying to list or create an "Order" object, but when i'm trying to access the console gives me this error:
```
{"detail": "Authentication credentials were not provided."}
```
**Views:**
```
from django.shortcuts import render
from rest_framework import viewsets
... | Solved by adding "DEFAULT\_AUTHENTICATION\_CLASSES" to my settings.py
```
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAdminUser'
),
}
``` |
Django Rest Framework - Authentication credentials were not provided | 26,906,630 | 13 | 2014-11-13T10:27:45Z | 33,783,391 | 24 | 2015-11-18T15:01:11Z | [
"python",
"django",
"django-rest-framework"
] | I'm developing an API using Django Rest Framework. I'm trying to list or create an "Order" object, but when i'm trying to access the console gives me this error:
```
{"detail": "Authentication credentials were not provided."}
```
**Views:**
```
from django.shortcuts import render
from rest_framework import viewsets
... | If you are runnig Django on Apache using mod\_wsgi you have to add
```
WSGIPassAuthorization On
```
in your httpd.conf. Otherwise authorization header will be stripped out by mod\_wsgi. |
Optional dot in regex | 26,907,640 | 18 | 2014-11-13T11:15:46Z | 26,907,702 | 13 | 2014-11-13T11:19:34Z | [
"python",
"regex",
"python-2.7"
] | Say I want to replace all the matches of `Mr.` and `Mr` with `Mister`.
I am using the following regex: `\bMr(\.)?\b` to match either `Mr.` or just `Mr`. Then, I use the [`re.sub()` method](https://docs.python.org/2/library/re.html#re.sub) to do the replacement.
What is puzzling me is that it is replacing `Mr.` with `... | I think you want to capture `'Mr'` followed by *either a `'.'` **or** a word boundary*:
```
r"\bMr(?:\.|\b)"
```
In use:
```
>>> import re
>>> re.sub(r"\bMr(?:\.|\b)", "Mister", "a rMr. Nobody Mr. Nobody is Mr Nobody and Mra Nobody.")
'a rMr. Nobody Mister Nobody is Mister Nobody and Mra Nobody.'
``` |
Which function in spark is used to combine two RDDs by keys | 26,908,031 | 13 | 2014-11-13T11:37:23Z | 26,913,550 | 7 | 2014-11-13T16:21:35Z | [
"python",
"scala",
"bigdata",
"apache-spark"
] | Let us say I have the following two RDDs, with the following key-pair values.
```
rdd1 = [ (key1, [value1, value2]), (key2, [value3, value4]) ]
```
and
```
rdd2 = [ (key1, [value5, value6]), (key2, [value7]) ]
```
Now, I want to join them by key values, so for example I want to return the following
```
ret = [ (ke... | Just use `join` and then `map` the resulting rdd.
```
rdd1.join(rdd2).map(case (k, (ls, rs)) => (k, ls ++ rs))
``` |
Gunicorn will not bind to my application | 26,912,487 | 4 | 2014-11-13T15:30:36Z | 26,912,549 | 11 | 2014-11-13T15:33:45Z | [
"python",
"django",
"nginx",
"gunicorn"
] | I have made a django web app using the default localhost, however I am trying to set it up on a server so that I can configure a postgre database and continue on without having to redo the database later on.
I am hosting the site though a digital ocean ubuntu 14 droplet. When I created the droplet I selected that it a... | Well that's not how you refer to the WSGI file with gunicorn. See [the docs](http://gunicorn-docs.readthedocs.org/en/19.1.1/run.html#commands):
> The module name can be a full dotted path. The variable name refers to a WSGI callable that should be found in the specified module.
So if your wsgi.py file is in GenericRe... |
Behaviour of truncate() method in Python | 26,917,197 | 4 | 2014-11-13T19:50:45Z | 26,917,275 | 11 | 2014-11-13T19:55:47Z | [
"python",
"file-io"
] | This is from [exercise 16](http://learnpythonthehardway.org/book/ex16.html) from Zed Shaw's Python tutorials. I'm having a hard time understanding what exactly the `truncate` function does in this case. So the logic is that we open a file and then...shorten it? For what? What exactly is happening here?
```
from sys im... | You're right to be suspicious.
First, [`file.truncate`](https://docs.python.org/2/library/stdtypes.html#file.truncate) does this:
> Truncate the fileâs size. If the optional *size* argument is present, the file is truncated to (at most) that size. The size defaults to the current positionâ¦
Not quite the same as ... |
How to restore python on OS X Yosemite after I've deleted something? | 26,917,765 | 7 | 2014-11-13T20:26:40Z | 26,917,983 | 17 | 2014-11-13T20:40:33Z | [
"python",
"terminal"
] | I think I previously installed python through homebrew. It was not a good idea but I did:
```
$ which python
/Library/Frameworks/Python.framework/Versions/2.7/bin/python
$ sudo rm -R /Library/Frameworks/Python.framework/Versions/2.7/bin/python
```
.. and then the terminal told me...
```
$ which python
/usr/local/bin... | You've got a multitude of problems here.
Let's start off with this:
`/Library/Frameworks/Python/2.7` is neither the Apple Python nor the Homebrew Python. You apparently installed a *third* Python, maybe the one from the official python.org binary installers. Removing that one won't affect the Homebrew one.
`/usr/loc... |
dateutil.tz package apparently missing when using Pandas? | 26,920,164 | 4 | 2014-11-13T23:07:21Z | 26,920,307 | 10 | 2014-11-13T23:20:10Z | [
"python",
"pandas"
] | My python 2.7 code is as follows:
```
import pandas as pd
from pandas import DataFrame
DF_rando = DataFrame([1,2,3])
```
...and then when I execute, I get a strange error regarding `dateutil.tz`.
```
/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /Users/mattobrien/pandas_test.py
No module named dat... | Needed these 2 lines.
`sudo pip install python-dateutil --upgrade`
`sudo pip install pytz --upgrade` |
Pandas - intersection of two data frames based on column entries | 26,921,943 | 5 | 2014-11-14T02:27:53Z | 26,921,975 | 13 | 2014-11-14T02:31:21Z | [
"python",
"pandas"
] | Suppose I have two DataFrames like so:
```
>>dfA
S T prob
0 ! ! ! ! ! ! ! 8.1623999e-05
1 ! ! ! ! ! ! " 0.00354090007
2 ! ! ! ! ! ! . 0.00210241997
3 ! ! ! ! ! ! ? 6.55684998e-05
... | You can merge them so:
```
s1 = pd.merge(dfA, dfB, how='inner', on=['S', 'T'])
```
To drop NA rows:
```
s1.dropna(inplace=True)
``` |
Does bottle handle requests with no concurrency? | 26,923,101 | 5 | 2014-11-14T04:50:28Z | 26,923,256 | 9 | 2014-11-14T05:03:18Z | [
"python",
"bottle"
] | At first, I think Bottle will handle requests concurrently, so I wrote test code bellow:
```
import json
from bottle import Bottle, run, request, response, get, post
import time
app = Bottle()
NUMBERS = 0
@app.get("/test")
def test():
id = request.query.get('id', 0)
global NUMBERS
n = NUMBERS
time.s... | Concurrency isn't a function of your web framework -- it's a function of the web server you use to serve it. Since Bottle is WSGI-compliant, it means you can serve Bottle apps through any WSGI server:
* wsgiref (reference server in the Python stdlib) will give you no concurrency.
* CherryPy dispatches through a thread... |
python sort list of json by value | 26,924,812 | 9 | 2014-11-14T07:14:31Z | 26,924,872 | 9 | 2014-11-14T07:18:48Z | [
"python",
"json",
"lambda",
"sorted"
] | I have a file consists of JSON, each a line, and want to sort the file by update\_time reversed.
sample JSON file:
```
{ "page": { "url": "url1", "update_time": "1415387875"}, "other_key": {} }
{ "page": { "url": "url2", "update_time": "1415381963"}, "other_key": {} }
{ "page": { "url": "url3", "update_time": "141538... | The answer should be obvious: Write a function that uses `try...except` to handle the `KeyError`, then use this as the `key` argument instead of your lambda.
```
def extract_time(json):
try:
# Also convert to int since update_time will be string. When comparing
# strings, "10" is smaller than "2".... |
How to check whether two lists are circularly identical in Python | 26,924,836 | 140 | 2014-11-14T07:16:20Z | 26,924,896 | 122 | 2014-11-14T07:20:24Z | [
"python",
"algorithm"
] | For instance, I have lists:
```
a[0] = [1, 1, 1, 0, 0]
a[1] = [1, 1, 0, 0, 1]
a[2] = [0, 1, 1, 1, 0]
# and so on
```
They seem to be different, but if it is supposed that the start and the end are connected, then they are *circularly* identical.
The problem is, each list which I have has a length of 55 and contains ... | First off, this can be done in `O(n)` in terms of the length of the list
You can notice that if you will duplicate your list 2 times (`[1, 2, 3]`) will be `[1, 2, 3, 1, 2, 3]` then your new list will definitely hold all possible cyclic lists.
So all you need is to check whether the list you are searching is inside a 2... |
How to check whether two lists are circularly identical in Python | 26,924,836 | 140 | 2014-11-14T07:16:20Z | 26,926,501 | 37 | 2014-11-14T09:14:31Z | [
"python",
"algorithm"
] | For instance, I have lists:
```
a[0] = [1, 1, 1, 0, 0]
a[1] = [1, 1, 0, 0, 1]
a[2] = [0, 1, 1, 1, 0]
# and so on
```
They seem to be different, but if it is supposed that the start and the end are connected, then they are *circularly* identical.
The problem is, each list which I have has a length of 55 and contains ... | Not knowledgeable enough in Python to answer this in your requested language, but in C/C++, given the parameters of your question, I'd convert the zeros and ones to bits and push them onto the least significant bits of an uint64\_t. This will allow you to compare all 55 bits in one fell swoop - 1 clock.
Wickedly fast,... |
How to check whether two lists are circularly identical in Python | 26,924,836 | 140 | 2014-11-14T07:16:20Z | 26,929,063 | 12 | 2014-11-14T11:33:57Z | [
"python",
"algorithm"
] | For instance, I have lists:
```
a[0] = [1, 1, 1, 0, 0]
a[1] = [1, 1, 0, 0, 1]
a[2] = [0, 1, 1, 1, 0]
# and so on
```
They seem to be different, but if it is supposed that the start and the end are connected, then they are *circularly* identical.
The problem is, each list which I have has a length of 55 and contains ... | Repeat the first array, then use the [Z algorithm](https://www.cs.umd.edu/class/fall2011/cmsc858s/Lec02-zalg.pdf) (O(n) time) to find the second array inside the first.
(Note: you don't have to physically copy the first array. You can just wrap around during matching.)
The nice thing about the Z algorithm is that it'... |
How to check whether two lists are circularly identical in Python | 26,924,836 | 140 | 2014-11-14T07:16:20Z | 26,933,996 | 31 | 2014-11-14T16:00:38Z | [
"python",
"algorithm"
] | For instance, I have lists:
```
a[0] = [1, 1, 1, 0, 0]
a[1] = [1, 1, 0, 0, 1]
a[2] = [0, 1, 1, 1, 0]
# and so on
```
They seem to be different, but if it is supposed that the start and the end are connected, then they are *circularly* identical.
The problem is, each list which I have has a length of 55 and contains ... | Reading between the lines, it sounds as though you're trying to enumerate one representative of each circular equivalence class of strings with 3 ones and 52 zeros. Let's switch from a dense representation to a sparse one (set of three numbers in `range(55)`). In this representation, the circular shift of `s` by `k` is... |
Check if dataframe column is Categorical | 26,924,904 | 7 | 2014-11-14T07:21:05Z | 26,925,850 | 7 | 2014-11-14T08:32:48Z | [
"python",
"pandas"
] | I can't seem to get a simple dtype check working with Pandas' improved Categoricals in v0.15+. Basically I just want something like `is_categorical(column) -> True/False`.
```
import pandas as pd
import numpy as np
import random
df = pd.DataFrame({
'x': np.linspace(0, 50, 6),
'y': np.linspace(0, 20, 6),
'... | Use the `name` property to do the comparison instead, it should always work because it's just a string:
```
>>> import numpy as np
>>> arr = np.array([1, 2, 3, 4])
>>> arr.dtype.name
'int64'
>>> import pandas as pd
>>> cat = pd.Categorical(['a', 'b', 'c'])
>>> cat.dtype.name
'category'
```
So, to sum up, you can end... |
How to add search parameters to GET request in Django REST Framework? | 26,924,968 | 3 | 2014-11-14T07:26:19Z | 26,925,428 | 7 | 2014-11-14T07:59:25Z | [
"python",
"django",
"rest",
"django-rest-framework"
] | After having read through and completed the [Django REST Framework tutorial](http://www.django-rest-framework.org/tutorial/1-serialization), it is not completely obvious how one would implement a filter on a GET request. For example, [ListAPIView](http://www.django-rest-framework.org/api-guide/generic-views#listapiview... | Search parameters are called filter parameters in terms of django-rest-framework. There are many ways to apply the filtering, check the [documentation](http://www.django-rest-framework.org/api-guide/filtering).
In most cases, you need to override just view, not serializer or any other module.
One obvious approach to ... |
Django : How to override the CSRF_FAILURE_TEMPLATE | 26,925,244 | 4 | 2014-11-14T07:45:58Z | 26,925,544 | 7 | 2014-11-14T08:07:46Z | [
"python",
"django",
"django-templates",
"django-csrf"
] | If csrf checking fails, Django display a page with 403 error.

It seems to me that this error can occur in regular use, for example, when the user disable cookie usage in his browser settings.
Unfortunately, this error message is not very helpf... | Refer to the [Django document](https://docs.djangoproject.com/en/dev/ref/settings/#csrf-failure-view), you can set `CSRF_FAILURE_VIEW` in your `settings.py`, such as:
```
CSRF_FAILURE_VIEW = 'your_app_name.views.csrf_failure'
```
Also, you'll need to define a `csrf_failure` function in your view (need to have this si... |
Multiple inheritance in python3 with different signatures | 26,927,571 | 9 | 2014-11-14T10:13:51Z | 26,927,718 | 13 | 2014-11-14T10:21:04Z | [
"python",
"inheritance",
"python-3.x",
"multiple-inheritance"
] | I have three classes: `A`, `B` and `C`.
`C` inherits from `A` and `B` (in this order). The constructor signatures of `A` and `B` are different. How can I call the `__init__` methods of both parent classes?
My endeavour in code:
```
class A(object):
def __init__(self, a, b):
super(A, self).__init__()
... | Do **not** use `super(baseclass, ...)` unless you know what you are doing. The first argument to `super()` tells it what class to **skip** when looking for the next method to use. E.g. `super(A, ...)` will look at the MRO, find `A`, then start looking for `__init__` on the **next** baseclass, **not** `A` itself. For `C... |
Detect touching/overlapping circles/ellipses with OpenCV and Python | 26,932,891 | 10 | 2014-11-14T15:03:59Z | 26,971,178 | 23 | 2014-11-17T11:00:17Z | [
"python",
"opencv",
"image-processing",
"feature-detection",
"hough-transform"
] | i want to measure the circularity of circles (difference of the "circles" height and width or ellipse parameters). The circles are given in pictures as shown here:

After doing usual stuff like color2gray, thresholding and border detection, I get the following picture as shown:
... | Here's my attempt at detecting the circles. In summary
* perform a BGR->HSV conversion and use the V channel for processing
V channel:

* threshold, apply morphological closing, then take the distance transform (I'll call it **dist**)
**dist** imag... |
ploting filled polygons in python | 26,935,701 | 2 | 2014-11-14T17:34:46Z | 26,935,798 | 7 | 2014-11-14T17:40:42Z | [
"python",
"matplotlib"
] | I have two matrices `Tri` and `V` for faces (Nx3) and vertices (Mx3) of polygons that I want to plot. Is there any matplotlib (or any alternative) way to do that? Something similar to Matlab command
```
patch('faces',Tri,'vertices',V,'facecolor',
'flat','edgecolor','none','facealpha',1)
``` | I'm not exactly sure what matlab does, but you can draw a polygon using [`matplotlib.patches.polygons`](http://matplotlib.org/api/patches_api.html?highlight=patches.polygon#matplotlib.patches.Polygon). Adapted from an [example](http://matplotlib.org/examples/api/patch_collection.html) in the docs:
```
import numpy as ... |
Show legend and label axes in plotly 3D scatter plots | 26,941,135 | 4 | 2014-11-15T00:35:33Z | 26,941,745 | 8 | 2014-11-15T02:07:34Z | [
"python",
"plotly"
] | Sorry for keeping you busy with plotly questions today. Here would be another one:
How would I show the legend and axes labels on plotly's new 3D scatter plots?
E.g., if I have the following scatter plot in 2D that produced everything fine, I added another dimension but the axes labels don't show anymore (see code bel... | You're close! 3D axes are actually embedded in a `Scene` object. Here is a simple example:
```
import plotly.plotly as py
from plotly.graph_objs import *
trace1 = Scatter3d(
x=[1, 2],
y=[1, 2],
z=[1, 2]
)
data = Data([trace1])
layout = Layout(
scene=Scene(
xaxis=XAxis(title='x axis title'),
... |
Python String Replace not working | 26,943,256 | 2 | 2014-11-15T06:33:10Z | 26,943,350 | 9 | 2014-11-15T06:49:08Z | [
"python",
"string",
"replace"
] | I initially tried using **'='** operator to assign value but it returned an error
Then i tried using **string.replace()**
```
`encrypted_str.replace(encrypted_str[j], dec_str2[k], 2)`
```
and
```
`encrypted_str.replace(encrypted_str[j], unichr(ord(dec_str2[k]) - 32), 2)`
```
But it is returning the orignal value
He... | Strings in Python are immutable. That means that a given string object will never have its value changed after it has been created. This is why an element assignment like `some_str[4] = "x"` will raise an exception.
For a similar reason, none of the methods provided by the `str` class can mutate the string. So, the `s... |
Sum all unique pair differences in a vector | 26,943,898 | 2 | 2014-11-15T08:07:23Z | 26,943,956 | 7 | 2014-11-15T08:14:20Z | [
"python"
] | I have the following problem: given a vector `x` of length `n`, find all but sum of unique pairwise differences of the vector elements.
One should not consider the pairs where the operands are merely exchanged, just one of them (e.g. do not consider `(x_i - x_j)` if `(x_j - x_i)` was computed).
For example:
```
v =... | If I understand your question correctly, the `k`th element is added `(n - 1 - 2 * k)` times, where `n` is the length of the array. So you can just do this:
```
v = [4, 2, 1, 5]
n = len(v)
s = 0 # this is going to be the sum
for idx, x in enumerate(v):
s += (n - 1 - 2 * idx) * x
print s
``` |
ValueError: dict contains fields not in fieldnames | 26,944,274 | 5 | 2014-11-15T09:04:17Z | 26,944,505 | 32 | 2014-11-15T09:39:52Z | [
"python",
"csv"
] | Can someone help me with this.
I have my Select query
```
selectAttendance = """SELECT * FROM table """
```
And I want the content of my select query and include a header when I download the csv file,
So I did this query:
```
with open(os.path.join(current_app.config['UPLOAD_FOLDER'], 'csv.csv'), 'wb') as csvfile:
... | As the error message clearly states, your dictionary contains keys that don't have a corresponding entry in your `fieldnames` parameter. Assuming that these are just extra fields, you can ignore them [by using the `extrasaction` parameter during construction of your `DictWriter` object](https://docs.python.org/2/librar... |
ValueError: dict contains fields not in fieldnames | 26,944,274 | 5 | 2014-11-15T09:04:17Z | 26,944,519 | 7 | 2014-11-15T09:41:23Z | [
"python",
"csv"
] | Can someone help me with this.
I have my Select query
```
selectAttendance = """SELECT * FROM table """
```
And I want the content of my select query and include a header when I download the csv file,
So I did this query:
```
with open(os.path.join(current_app.config['UPLOAD_FOLDER'], 'csv.csv'), 'wb') as csvfile:
... | As the error states: the dictionary that comes from the query contains more key than the field names you specified in the DictWriter constructor.
One solution would be to filter that in advance, something like this:
```
field_names = ["Bio_Id","Last_Name", ...]
writer = csv.DictWriter(csvfile,fieldnames=field_names ,... |
'str' does not support the buffer interface Python3 from Python2 | 26,945,613 | 10 | 2014-11-15T12:02:12Z | 26,949,760 | 11 | 2014-11-15T19:23:57Z | [
"python",
"string",
"python-3.x",
"unicode",
"bytearray"
] | Hi have this two funtions in Py2 works fine but it doesn´t works on Py3
```
def encoding(text, codes):
binary = ''
f = open('bytes.bin', 'wb')
for c in text:
binary += codes[c]
f.write('%s' % binary)
print('Text in binary:', binary)
f.close()
return len(binary)
def decoding(codes,... | In Python 2, bare literal strings (e.g. `'string'`) are *bytes*, whereas in Python 3 they are *unicode*. This means if you want literal strings to be treated as bytes in Python 3, you always have to explicitly mark them as such.
So, for instance, the first few lines of the `encoding` function should look like this:
`... |
'str' does not support the buffer interface Python3 from Python2 | 26,945,613 | 10 | 2014-11-15T12:02:12Z | 30,481,195 | 15 | 2015-05-27T11:30:04Z | [
"python",
"string",
"python-3.x",
"unicode",
"bytearray"
] | Hi have this two funtions in Py2 works fine but it doesn´t works on Py3
```
def encoding(text, codes):
binary = ''
f = open('bytes.bin', 'wb')
for c in text:
binary += codes[c]
f.write('%s' % binary)
print('Text in binary:', binary)
f.close()
return len(binary)
def decoding(codes,... | The fix was simple for me
Use
```
f = open('bytes.bin', 'w')
```
instead of
```
f = open('bytes.bin', 'wb')
```
In python 3 `'w'` is what you need, not `'wb'`. |
Timezone.now() vs datetime.datetime.now() | 26,949,959 | 5 | 2014-11-15T19:45:53Z | 26,950,056 | 7 | 2014-11-15T19:55:58Z | [
"python",
"django",
"datetime"
] | When should I be using django's `timezone.now()` and when should I be using pythong's `datetime.datetime.now()`.
For example, in the following `INSERT` which would make more sense?
```
- Product.objects.create(title='Soap', date_added=datetime.datetime.now())
- Product.objects.create(title='Soap', date_added=timezone... | Just always use `timezone.now()`. Django now has timezone support which requires timezone 'aware' datetime objects. `datetime.now()` will return a timezone naive object, whereas `timezone.now()` will return a timezone aware object. |
Is Haskell's laziness an elegant alternative to Python's generators? | 26,952,366 | 19 | 2014-11-16T00:19:47Z | 26,953,506 | 7 | 2014-11-16T03:41:58Z | [
"python",
"haskell",
"lazy-evaluation"
] | In a programming exercise, it was first asked to program the factorial function and then calculate the sum: `1! + 2! + 3! +... n!` in `O(n)` multiplications (so we can't use the factorial directly). I am not searching the solution to this specific (trivial) problem, I'm trying to explore Haskell abilities and this prob... | Basically, yes: Haskell's lazy-lists are a lot like Python's generators, if those generators were effortlessly cloneable, cacheable, and composeable. Instead of raising `StopIteration` you return `[]` from your recursive function, which can thread state into the generator.
They do some cooler stuff due to self-recursi... |
Is Haskell's laziness an elegant alternative to Python's generators? | 26,952,366 | 19 | 2014-11-16T00:19:47Z | 26,954,033 | 9 | 2014-11-16T05:13:26Z | [
"python",
"haskell",
"lazy-evaluation"
] | In a programming exercise, it was first asked to program the factorial function and then calculate the sum: `1! + 2! + 3! +... n!` in `O(n)` multiplications (so we can't use the factorial directly). I am not searching the solution to this specific (trivial) problem, I'm trying to explore Haskell abilities and this prob... | Your examples are **not** equivalent in memory usage. It is easy to see if you replace `*` with a `+` (so that the numbers don't get big too quickly) and then run both examples on a big `n` such as 10^7. Your Haskell version will consume a lot of memory and python will keep it low.
Python generator will not generate a... |
Is Haskell's laziness an elegant alternative to Python's generators? | 26,952,366 | 19 | 2014-11-16T00:19:47Z | 26,955,557 | 14 | 2014-11-16T09:33:53Z | [
"python",
"haskell",
"lazy-evaluation"
] | In a programming exercise, it was first asked to program the factorial function and then calculate the sum: `1! + 2! + 3! +... n!` in `O(n)` multiplications (so we can't use the factorial directly). I am not searching the solution to this specific (trivial) problem, I'm trying to explore Haskell abilities and this prob... | Indeed, lazy lists can be used this way. There are some subtle differences though:
* Lists are data structures. So you can keep them after evaluating them, which can be both good and bad (you can avoid recomputation of values and to recursive tricks as @ChrisDrost described, at the cost of keeping memory unreleased).
... |
Key Error while setting width of column - OpenPyXL | 26,955,028 | 2 | 2014-11-16T08:01:33Z | 26,955,286 | 7 | 2014-11-16T08:47:11Z | [
"python",
"python-3.x",
"openpyxl"
] | I am getting an error when setting the width of a column
```
workbook = Workbook()
#Add a sheet
worksheet = workbook.active
worksheet.column_dimensions["C"].width = 60.0
```
Here is the error.
```
KeyError: 'C'
``` | There is no column "C" to resize.
Verify this with:
```
worksheet.columns
```
If you first create a cell in column C:
```
import openpyxl
wb = openpyxl.Workbook()
ws = wb.active
_cell = ws.cell(row=1, column=3)
```
You can then resize it, and not throw a KeyError:
```
ws.column_dimensions["C"].width = 60.0
``` |
how to implement the python `zip` function in golang? | 26,957,040 | 8 | 2014-11-16T12:44:46Z | 26,957,765 | 9 | 2014-11-16T14:00:39Z | [
"python",
"go"
] | Sometimes, it's convenient to combine two lists into a tuple using `zip` built-in function in Python. How to make this similarly in golang? | You could do something like [this](http://play.golang.org/p/CYtr4Z-UQ-), where you give the tuple type a name:
```
package main
import "fmt"
type intTuple struct {
a, b int
}
func zip(a, b []int) ([]intTuple, error) {
if len(a) != len(b) {
return nil, fmt.Errorf("zip: arguments must be of same leng... |
Edit existing excel workbooks and sheets with xlrd and xlwt | 26,957,831 | 9 | 2014-11-16T14:07:23Z | 26,958,437 | 24 | 2014-11-16T15:10:52Z | [
"python",
"excel",
"xlrd",
"xlwt"
] | In the [documentation](http://www.simplistix.co.uk/presentations/python-excel.pdf) for `xlrd` and `xlwt` I have learned the following:
How to read from existing work-books/sheets:
```
from xlrd import open_workbook
wb = open_workbook("ex.xls")
s = wb.sheet_by_index(0)
print s.cell(0,0).value
#Prints contents of cell ... | As I wrote in the edits of the op, to edit existing excel documents you must use the `xlutils` module (Thanks Oliver)
Here is the proper way to do it:
```
#xlrd, xlutils and xlwt modules need to be installed.
#Can be done via pip install <module>
from xlrd import open_workbook
from xlutils.copy import copy
rb = op... |
What do the keywords "Some" and "Simple" do in Rust? | 26,960,537 | 3 | 2014-11-16T18:32:04Z | 26,960,638 | 8 | 2014-11-16T18:42:08Z | [
"python",
"rust"
] | I'm trying to get more in the habit of programming by giving myself a directed task, and the one I found at <http://limpet.net/mbrubeck/2014/08/08/toy-layout-engine-1.html> seemed to be a good match. Since I'm focusing on learning Python, I figured it would be good practice to convert the tutorial into Python. I figure... | Rust features [Algebraic Data Types](http://en.wikipedia.org/wiki/Algebraic_data_type) which in short are data types with several possible shapes, for example:
```
enum OptionInt {
None,
Some(int)
}
```
Is a data type which is either `None` (a singleton value) or `Some(int)` (an `int`). In this case, `Non... |
How to speed up multiple inner products in python | 26,960,749 | 17 | 2014-11-16T18:53:52Z | 26,960,960 | 7 | 2014-11-16T19:14:45Z | [
"python",
"performance",
"algorithm",
"cython",
"numba"
] | I have some simple code that does the following.
It iterates over all possible length n lists `F` with +-1 entries . For each one it iterates over all possible length `2n` lists `S` with +-1 entries where the first half of $S$ is simply a copy of the second half. The code computes the inner product of `F` with each su... | One very simple speed up of a factor of n is to change this code:
```
def innerproduct(A, B):
assert (len(A) == len(B))
for j in xrange(len(A)):
s = 0
for k in xrange(0,n):
s+=A[k]*B[k]
return s
```
to
```
def innerproduct(A, B):
assert (len(A) == len(B))
s = 0
f... |
How to speed up multiple inner products in python | 26,960,749 | 17 | 2014-11-16T18:53:52Z | 27,025,255 | 20 | 2014-11-19T19:24:32Z | [
"python",
"performance",
"algorithm",
"cython",
"numba"
] | I have some simple code that does the following.
It iterates over all possible length n lists `F` with +-1 entries . For each one it iterates over all possible length `2n` lists `S` with +-1 entries where the first half of $S$ is simply a copy of the second half. The code computes the inner product of `F` with each su... | This new code gets another order of magnitude speedup by taking advantage of the cyclic symmetry of the problem. This Python version enumerates necklaces with Duval's algorithm; the C version uses brute force. Both incorporate the speedups described below. **On my machine, the C version solves n = 20 in 100 seconds!** ... |
Round half to even on decimal | 26,962,575 | 3 | 2014-11-16T22:04:12Z | 26,962,661 | 7 | 2014-11-16T22:12:20Z | [
"python",
"rounding"
] | R by default uses [round half to even](http://en.wikipedia.org/wiki/Rounding#Round_half_to_even) on the `round()` function.
But it not seems to be always true when rounding to a defined number of decimal places:
```
# R code
round(1.225,2)
#[1] 1.23
round(1.2225,3)
#[1] 1.222
round(1.22225,4)
#[1] 1.2223
round(1.22222... | The problem is the finite precision of floating point values:
```
>>> '%.18f' % 1.225
'1.225000000000000089'
>>> '%.18f' % 1.2225
'1.222499999999999920'
>>> '%.18f' % 1.22225
'1.222250000000000059'
>>> '%.18f' % 1.222225
'1.222224999999999895'
```
Pythons Decimal-class is exact in this sense. |
Python inspect module: keyword only args | 26,963,319 | 6 | 2014-11-16T23:27:30Z | 26,963,763 | 8 | 2014-11-17T00:31:25Z | [
"python",
"function",
"python-3.x",
"arguments",
"signature"
] | The phrase "keyword only args" in Python is a bit ambiguous - usually I take it to mean args passed in to a `**kwarg` parameter. However, the `inspect` module seems to make a distinction between `**kwarg` and something called "keyword only arguments".
From [**the docs**](https://docs.python.org/3.4/library/inspect.htm... | **TL;DR**: Keyword-only arguments are not the same as normal keyword arguments.
---
Keyword-only arguments are arguments that come after `*args` and before `**kwargs` in a function call. As an example, consider this generic function header:
```
def func(arg, *args, kwonly, **kwargs):
```
In the above, `kwonly` take... |
What's the correct way to use a unix domain socket in requests framework? | 26,964,595 | 12 | 2014-11-17T02:27:21Z | 27,268,999 | 10 | 2014-12-03T10:16:51Z | [
"python",
"python-requests"
] | Usually, doing a post request using [requests](http://docs.python-requests.org/en/latest/) framework is done by:
```
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", data=payload)
```
But: How do I connect to a unix socket instead of doing a TCP connection?
On a related not... | There's no need to reinvent the wheel:
<https://github.com/msabramo/requests-unixsocket>
URL scheme is `http+unix` and socket path is percent-encoded into the host field:
```
import requests_unixsocket
session = requests_unixsocket.Session()
# Access /path/to/page from /tmp/profilesvc.sock
r = session.get('http+un... |
Sorting a list of strings by their components | 26,967,497 | 3 | 2014-11-17T07:22:16Z | 26,967,560 | 7 | 2014-11-17T07:27:16Z | [
"python",
"list"
] | A long list contains some elements to be sorted.
Actually each element has 4 contents: name, in/out, area and date&time, joined by â~â. (The â~â can be changed.) I want to reorganize the list into a sorted order.
```
a_list = ["Chris~Check-in~Zoom A~11/13/2013 05:20",
"Chris~Check-in~Zoom G~11/15/2013 14:09",... | You can split the list, then sort with a custom `key` function. But you need to parse the date first to sort them correctly.
```
import datetime
new_l = sorted((x.split('~') for x in l),
key=lambda x: (x[0],
datetime.datetime.strptime(x[3], '%m/%d/%Y %H:%M'),
... |
Matplotlib can't suppress figure window | 26,970,002 | 3 | 2014-11-17T09:59:41Z | 26,974,098 | 8 | 2014-11-17T13:47:10Z | [
"python",
"matplotlib",
"window",
"figure",
"suppress"
] | I'm having trouble with matplotlib insisting on displaying a figure wnidow even when I haven't called show().
The function in question is:
```
def make_plot(df):
fig, axes = plt.subplots(3, 1, figsize=(10, 6), sharex=True)
plt.subplots_adjust(hspace=0.2)
axes[0].plot(df["Date_Time"], df["T1"], df["Date_T... | **Step 1**
Check whether you're running in [interactive mode](http://matplotlib.org/faq/usage_faq.html#what-is-interactive-mode). The default is non-interactive, but you may never know:
```
>>> import matplotlib as mpl
>>> mpl.is_interactive()
False
```
You can set the mode explicitly to non-interactive by using
``... |
How do i link to images not in Static folder in flask | 26,971,491 | 4 | 2014-11-17T11:15:44Z | 26,972,238 | 8 | 2014-11-17T11:58:37Z | [
"python",
"static",
"flask",
"openshift",
"url-for"
] | In flask, how do I serve images that are not in the static folder?
I currently save the user uploaded photos on a directory that is outside the flask folder (On openshift, im currently saving in the data folder under app-root/data and the flask files are in app-root/repo/).
In my templates, how do i serve the image f... | You have the **[send\_from\_directory](http://flask.pocoo.org/docs/0.10/api/#flask.send_from_directory)** function that does what you want, what I would do is declare a constant called **MEDIA\_FOLDER** with the path where the media files are located and then, the only thing you need to do is to call the function like ... |
Deploying flask site/application on pythonanywhere.com | 26,972,495 | 5 | 2014-11-17T12:13:40Z | 26,973,640 | 7 | 2014-11-17T13:19:24Z | [
"python",
"flask",
"web-deployment",
"pythonanywhere"
] | I have a working sample site with the file system as such (<https://github.com/alvations/APE>):
```
APE
\app
\templates
base.html
index.html
instance.html
__init__.py
hamlet.py
config.py
run.py
```
I have created a flask project on www.pythonanyw... | PythonAnywhere dev here -- you don't need a run.py on [PythonAnywhere](http://www.pythonanywhere.com). The code that normally goes in there is to run a local Flask server that can serve your app -- that's all handled for you by our system.
Instead, you need to change the WSGI file (linked from the "Web" tab) to import... |
Python if more than one of N variables is true | 26,975,992 | 2 | 2014-11-17T15:25:25Z | 26,976,041 | 7 | 2014-11-17T15:27:52Z | [
"python",
"function",
"if-statement",
"argument-passing"
] | I need to check if more than one of a, b, c, and d are being defined:
```
def myfunction(input, a=False, b=False, c=False, d=False):
if <more than one True> in a, b, c, d:
print("Please specify only one of 'a', 'b', 'c', 'd'.)
```
I am currently nesting if statements, but that looks horrid. Could you suggest ... | First thing that comes to mind:
```
if [a, b, c, d].count(True) > 1:
``` |
How to get most informative features for scikit-learn classifier for different class? | 26,976,362 | 5 | 2014-11-17T15:44:13Z | 26,980,472 | 7 | 2014-11-17T19:32:19Z | [
"python",
"machine-learning",
"scikit-learn",
"nltk"
] | NLTK package provides a method `show_most_informative_features()` to find the most important features for both class, with output like:
```
contains(outstanding) = True pos : neg = 11.1 : 1.0
contains(seagal) = True neg : pos = 7.7 : 1.0
contains(wonderfully) = Tr... | In the case of binary classification, it seems like the coefficient array has been flatten.
Let's try to relabel our data with only two labels:
```
import codecs, re, time
from itertools import chain
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import Multi... |
pandas unique values multiple columns | 26,977,076 | 23 | 2014-11-17T16:21:12Z | 26,977,495 | 33 | 2014-11-17T16:42:34Z | [
"python",
"pandas",
"unique"
] | ```
df = pd.DataFrame({'Col1' : ['Bob', 'Joe', 'Bill', 'Mary', 'Joe'],
'Col2' : ['Joe', 'Steve', 'Bob', 'Bob', 'Steve'],
'Col3' : np.random.random(5)})
```
What is the best way to return the unique values of 'Col1' and 'Col2'?
desired output is
'Bob', 'Joe', 'Bill', 'Mary', 'Steve' | One way is to select the columns and pass them to [`np.unique`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html):
```
>>> np.unique(df[['Col1', 'Col2']])
array(['Bill', 'Bob', 'Joe', 'Mary', 'Steve'], dtype=object)
```
Note that some versions of Pandas/NumPy may require you to explicitly pass th... |
Why does `yield from` in a generator expression yield `None`s? | 26,979,803 | 3 | 2014-11-17T18:54:34Z | 26,979,908 | 10 | 2014-11-17T19:01:16Z | [
"python",
"python-3.x",
"generator",
"yield",
"generator-expression"
] | I have the following code:
```
import itertools
for c in ((yield from bin(n)[2:]) for n in range(10)):
print(c)
```
The output is:
```
0
None
1
None
1
0
None
1
1
None
```
... etc. Why do the `None`s appear? If I instead have:
```
def hmm():
for n in range(10):
yield from bin(n)[2:]
for c in h... | `yield` is an expression, and its value is whatever is sent into the generator with `send`. If nothing is sent in, the value of `yield` is None. In your example `yield from` yields the values from the list, but the value of the `yield from` expression itself is None, which is yielded at each iteration of the enclosing ... |
How do you find the average of a list with numbers in quotes, in python? | 26,983,111 | 3 | 2014-11-17T22:24:01Z | 26,983,145 | 9 | 2014-11-17T22:25:52Z | [
"python",
"linux",
"unix"
] | I have two types of lists. The first **without** quotes, which **works** and prints the average fine:
```
l = [15,18,20]
print l
print "Average: ", sum(l)/len(l)
```
This prints:
```
[15,18,20]
Average: 17
```
The second list has numbers **with** quotes, which returns an **error**:
```
x = ["15","18","20"]
print x... | The quotes mean that you have a list of strings:
```
>>> x = ["15","18","20"]
>>> type(x[0])
<type 'str'>
>>>
```
`sum` only works with lists of numbers (integers such as `1` or floats such as `1.0`).
To fix your problem, you must first convert your list of strings into a list of integers. You can use the built-in [... |
why do perl, ruby use /dev/urandom | 26,983,419 | 12 | 2014-11-17T22:46:17Z | 26,984,108 | 15 | 2014-11-17T23:46:59Z | [
"python",
"ruby",
"linux",
"bash",
"perl"
] | I `strace`'d a simple script using perl and bash.
```
$ strace perl -e 'echo "test";' 2>&1 | grep 'random'
open("/dev/urandom", O_RDONLY) = 3
$ strace bash 'echo "test"' 2>&1 | grep 'random'
$
```
Why does perl need the [pseudorandom number generator](http://en.wikipedia.org/?title=/dev/random) for such a tr... | Try searching for "Denial of Service via Algorithmic Complexity Attacks".
In brief, if a Perl script accepts outside input (from a file, network, etc) and stores that data in a hash, an attacker who can influence the data can exploit the hashing algorithm to deteriorate hashes (O(1) lookups) into linked lists (O(N) lo... |
Efficiently sorting a numpy array in descending order? | 26,984,414 | 14 | 2014-11-18T00:16:02Z | 26,984,520 | 16 | 2014-11-18T00:26:33Z | [
"python",
"arrays",
"sorting",
"numpy"
] | I am surprised this specific question hasn't been asked before, but I really didn't find it on SO nor on the documentation of `np.sort`.
Say I have a random numpy array holding integers, e.g:
```
> temp = np.random.randint(1,10, 10)
> temp
array([2, 4, 7, 4, 2, 2, 7, 6, 4, 4])
```
If I sort it, I get ascending o... | `temp[::-1].sort()` sorts the array in place, `np.sort(temp)[::-1]` create a new array.
```
In [25]: temp = np.random.randint(1,10, 10)
In [26]: temp
Out[26]: array([5, 2, 7, 4, 4, 2, 8, 6, 4, 4])
In [27]: id(temp)
Out[27]: 139962713524944
In [28]: temp[::-1].sort()
In [29]: temp
Out[29]: array([8, 7, 6, 5, 4, 4, ... |
PyQt5 and Matplotlib 1.4.2 - installing one breaks the other | 26,984,652 | 7 | 2014-11-18T00:38:36Z | 27,456,446 | 11 | 2014-12-13T07:07:03Z | [
"python",
"matplotlib",
"pyqt4",
"pyqt5"
] | I am trying to write a PyQt5 application that embeds a matplotlib plot within it. However, I am having a maddening time where if I install matplotlib PyQt5 breaks due to the interference by PyQt4. This can be seen in this error:
```
In [2]: from PyQt5 import QtCore, QtGui, QtWidgets
-----------------------------------... | As your matplotlib depends on PyQt4, you need to force Matplotlib to use PyQt5 backend. Like this:
```
import matplotlib
matplotlib.use("Qt5Agg")
```
This function must be called *before* importing pyplot for
the first time; or, if you are not using pyplot, it must be called
before importing matplotlib.backen... |
How to do simple inheritance in Go | 26,985,191 | 3 | 2014-11-18T01:42:51Z | 26,985,492 | 7 | 2014-11-18T02:19:39Z | [
"python",
"inheritance",
"go"
] | I'm a Python developer, trying to learn Go. Currently I'm trying to refactor my first small project, but I am not too sure how to share a method between structs.
Long story short, how would you do something like this Python code in Go?
```
class Super(object):
def CommonMethod(self):
print 'I am the common met... | **TL;DR**
In Go methods aren't just magically inherited with subclassing as you would do in other languages like Python or Java. You can define interfaces and using embedding but you'll have to implement the methods you need for each type. Of course you can just call the method of the embedded from the outer method, h... |
Python Matplotlib line plot aligned with contour/imshow | 26,985,210 | 9 | 2014-11-18T01:44:56Z | 27,030,928 | 8 | 2014-11-20T02:52:28Z | [
"python",
"matplotlib"
] | How can I set the visual width of one subplot equal to the width of another subplot using Python and Matplotlib? The first plot has a fixed aspect ratio and square pixels from imshow. I'd then like to put a lineplot below that, but am not able to do so and have everything aligned.
I'm fairly sure the solution involves... | The outline of matplotlib axes are controlled by three things:
1. The axes' bounding box within the figure (controlled by a subplot specification or a specific extent such as `fig.add_axes([left, bottom, width, height])`. The axes limits (not counting tick labels) will always be within this box.
2. The `adjustable` pa... |
Why does Python have `reversed`? | 26,985,749 | 2 | 2014-11-18T02:45:56Z | 26,985,788 | 7 | 2014-11-18T02:49:43Z | [
"python",
"language-design"
] | Why does Python have the built-in function [`reversed`](https://docs.python.org/3/library/functions.html#reversed)?
Why not just use `x[::-1]` instead of `reversed(x)`?
---
**Edit**: *@TanveerAlam [pointed out](http://stackoverflow.com/a/26985860/2223706) that* `reversed` *is not actually a function, but rather a cl... | ```
>>> a= [1,2,3,4,5,6,7,8,9,10]
>>> a[::-1]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> reversed(a)
<listreverseiterator object at 0x10dbf5390>
```
The first notation is generating the reverse eagerly; the second is giving you a reverse iterator, which is possibly cheaper to acquire, as it has potential to only generate ele... |
Django REST Framework: Could not resolve URL for hyperlinked relationship using view name | 26,986,014 | 2 | 2014-11-18T03:18:54Z | 26,986,273 | 7 | 2014-11-18T03:48:55Z | [
"python",
"django",
"rest",
"django-rest-framework"
] | I've extensively researched this fairly common issue, but none of the fixes worked for me. I'm building a Django project in REST framework and want to use hyperlinked relations. The User can have many Cars and Routes, which are independent. A Route is a collection of Positions.
These are my serializers:
```
class Car... | The `view_name` should typically be `[route]-detail` for routers, where `[route]` is the name of the model you registered the `ViewSet` under.
In your case, the `view_name` should be `position-detail`, not just `position`. You are also using `routes-detail` instead of `drivingroutes-detail`, which is using the long na... |
how to configure and run celery worker on remote system | 26,986,746 | 7 | 2014-11-18T04:45:11Z | 26,987,544 | 12 | 2014-11-18T05:52:08Z | [
"python",
"django",
"celery"
] | i am working on celery and using rabbitmq server and created a project in django project in a server(where message queue,database exists) and it is working fine, i have created multiple workers also
```
from kombu import Exchange, Queue
CELERY_CONCURRENCY = 8
CELERY_ACCEPT_CONTENT = ['pickle', 'json', 'msgpack', 'yam... | Here is the gist of the idea:
**On Machine A:**
1. Install Celery & RabbitMQ.
2. Configure rabbitmq so that Machine B can connect to it.
3. Create my\_tasks.py with some tasks and put some tasks in queue.
**On Machine B:**
1. Install Celery.
2. Copy my\_tasks.py file from machine A to this machine.
3. Run a worker ... |
MongoEngine: storing EmbeddedDocument in DictField | 26,991,880 | 6 | 2014-11-18T10:21:27Z | 27,022,295 | 8 | 2014-11-19T16:45:39Z | [
"python",
"mongodb",
"nosql",
"mongoengine",
"flask-mongoengine"
] | I'm modelling a MongoBD database in MongoEngine for a web project. I want to store the data in a slightly unusual way to be able to efficiently query it later.
Our data in MongoDB looks something like this:
```
// "outer"
{
"outer_data": "directors",
"embed": {
"some_md5_key": { "name": "P.T. Anderson" },
... | I finally found the answer to my problem. The correct way to achieve this pattern is by making use of a [`MapField`](http://docs.mongoengine.org/apireference.html#mongoengine.fields.MapField).
The corresponding model in MongoEngine looks like:
```
class Inner(EmbeddedDocument):
name = StringField()
class Outer(Doc... |
Python3 Django -> HTML to PDF | 26,996,976 | 4 | 2014-11-18T14:42:36Z | 26,997,081 | 8 | 2014-11-18T14:48:03Z | [
"python",
"django",
"pdf",
"html-to-pdf"
] | There are a lot of different ways of generating pdfs from a django webpage in python2. The most clean, probably, is pisa and reportlab.
These do not work for python3 though.
So far, the only method I've had success with is to render the template, write it to a file, and then use wkhtmltopdf via subprocess.popen. This ... | You could use [Weasyprint](http://weasyprint.org/). You could easily render directly.
You could do something like that:
```
html = HTML(string=htmlstring)
main_doc = html.render()
pdf = main_doc.write_pdf()
return HttpResponse(pdf, content_type='application/pdf')
```
To render your Django view to HTM... |
Writing a CSV from Flask framework | 26,997,679 | 5 | 2014-11-18T15:16:59Z | 26,998,089 | 19 | 2014-11-18T15:37:55Z | [
"python",
"csv",
"flask"
] | I have no problems writing a CSV outside of the Flask framework. But when I try to write it from Flask, it writes to the CSV, but only on one line.
Here is the template I'm following
```
@app.route('/download')
def download():
csv = """"REVIEW_DATE","AUTHOR","ISBN","DISCOUNTED_PRICE"
"1985/01/21","Douglas Adams",... | I did something like this recently, I found that I needed to first place the csv into a StringIO and then return the StringIO. If you want the csv to be a download, here's what I did:
```
si = StringIO.StringIO()
cw = csv.writer(si)
cw.writerows(csvList)
output = make_response(si.getvalue())
output.headers["Content-Di... |
What is the difference between contiguous and non-contiguous arrays? | 26,998,223 | 17 | 2014-11-18T15:45:08Z | 26,999,092 | 22 | 2014-11-18T16:25:25Z | [
"python",
"arrays",
"numpy",
"memory"
] | In the [numpy manual](http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html) about the reshape() function, it says
```
>>> a = np.zeros((10, 2))
# A transpose make the array non-contiguous
>>> b = a.T
# Taking a view makes it possible to modify the shape without modifying the
# initial object.
>>> c =... | A contiguous array is just an array stored in an unbroken block of memory: to access the next value in the array, we just move to the next memory address.
Consider the 2D array `arr = np.arange(12).reshape(3,4)`. It looks like this:

In the computer'... |
Reduce a key-value pair into a key-list pair with Apache Spark | 27,002,161 | 24 | 2014-11-18T19:15:18Z | 27,002,657 | 28 | 2014-11-18T19:43:45Z | [
"python",
"mapreduce",
"apache-spark"
] | I am writing a Spark application and want to combine a set of Key-Value pairs (K, V1), (K, V2), ..., (K, Vn) into one Key-Multivalue pair (K, [V1, V2, ..., Vn]). I feel like I should be able to do this using the ReduceByKey function with something of the flavor:
`My_KMV = My_KV.reduce(lambda a, b: a.append([b]))`
The... | **Map and ReduceByKey**
Input type and output type of `reduce` must be the same, therefore if you want to aggregate a list, you have to `map` the input to lists. Afterwards you combine the lists into one list.
**Combining lists**
You'll need a method to combine lists into one list. Phyton provides some [methods to c... |
Reduce a key-value pair into a key-list pair with Apache Spark | 27,002,161 | 24 | 2014-11-18T19:15:18Z | 28,201,837 | 7 | 2015-01-28T20:31:41Z | [
"python",
"mapreduce",
"apache-spark"
] | I am writing a Spark application and want to combine a set of Key-Value pairs (K, V1), (K, V2), ..., (K, Vn) into one Key-Multivalue pair (K, [V1, V2, ..., Vn]). I feel like I should be able to do this using the ReduceByKey function with something of the flavor:
`My_KMV = My_KV.reduce(lambda a, b: a.append([b]))`
The... | I'm kind of late to the conversation, but here's my suggestion:
```
>>> foo = sc.parallelize([(1, ('a','b')), (2, ('c','d')), (1, ('x','y'))])
>>> foo.map(lambda (x,y): (x, [y])).reduceByKey(lambda p,q: p+q).collect()
[(1, [('a', 'b'), ('x', 'y')]), (2, [('c', 'd')])]
``` |
Reduce a key-value pair into a key-list pair with Apache Spark | 27,002,161 | 24 | 2014-11-18T19:15:18Z | 29,845,381 | 7 | 2015-04-24T10:42:41Z | [
"python",
"mapreduce",
"apache-spark"
] | I am writing a Spark application and want to combine a set of Key-Value pairs (K, V1), (K, V2), ..., (K, Vn) into one Key-Multivalue pair (K, [V1, V2, ..., Vn]). I feel like I should be able to do this using the ReduceByKey function with something of the flavor:
`My_KMV = My_KV.reduce(lambda a, b: a.append([b]))`
The... | You can use the RDD [groupByKey](https://spark.apache.org/docs/1.3.1/api/python/pyspark.html#pyspark.RDD.groupByKey) method.
*Input:*
```
data = [(1, 'a'), (1, 'b'), (2, 'c'), (2, 'd'), (2, 'e'), (3, 'f')]
rdd = sc.parallelize(data)
result = rdd.groupByKey().collect()
```
*Output:*
```
[(1, ['a', 'b']), (2, ['c', '... |
Contour/imshow plot for irregular X Y Z data | 27,004,422 | 5 | 2014-11-18T21:30:44Z | 27,004,916 | 14 | 2014-11-18T22:00:38Z | [
"python",
"plot",
"contour",
"imshow"
] | I have data in X, Y, Z format where all are 1D arrays, and Z is the amplitude of the measurement at coordinate (X,Y). I'd like to show this data as a contour or 'imshow' plot where the contours/color represent the the value Z (amplitude).
The grid for measurements and X and Y look are irregularly spaced.
Many thanks,... | Does `plt.tricontourf(x,y,z)` satisfy your requirements?
It will plot filled contours for irregularly spaced data (non-rectilinear grid).
You might also want to look into `plt.tripcolor()`.
```
import numpy as np
import matplotlib.pyplot as plt
x = np.random.rand(100)
y = np.random.rand(100)
z = np.sin(x)+np.cos(y)
... |
Changing color and marker of each point using seaborn jointplot | 27,005,783 | 6 | 2014-11-18T23:00:44Z | 27,007,802 | 7 | 2014-11-19T02:17:23Z | [
"python",
"matplotlib",
"seaborn"
] | I have this code slightly modified from [here](http://web.stanford.edu/~mwaskom/software/seaborn/examples/regression_marginals.html) :
```
import seaborn as sns
sns.set(style="darkgrid")
tips = sns.load_dataset("tips")
color = sns.color_palette()[5]
g = sns.jointplot("total_bill", "tip", data=tips, kind="reg", stat_f... | Solving this problem is almost no different than that from matplotlib (plotting a scatter plot with different markers and colors), except I wanted to keep the marginal distributions:
```
import seaborn as sns
from itertools import product
sns.set(style="darkgrid")
tips = sns.load_dataset("tips")
color = sns.color_pal... |
Selenium: Iterating through groups of elements | 27,006,698 | 4 | 2014-11-19T00:17:28Z | 27,006,741 | 7 | 2014-11-19T00:20:39Z | [
"python",
"html",
"selenium",
"beautifulsoup",
"html-parsing"
] | I've done this with BeautifulSoup but it's a bit cumbersome, and I'm trying to figure out if I can do it directly with Selenium.
Let's say I have the following HTML, which repeats multiple times in the page source with identical elements but different contents:
```
<div class="person">
<div class="title">
... | Use [`find_elements_by_class_name()`](http://selenium-python.readthedocs.org/api.html#selenium.webdriver.remote.webdriver.WebDriver.find_elements_by_class_name) to get all blocks and [`find_element_by_xpath()`](http://selenium-python.readthedocs.org/api.html#selenium.webdriver.remote.webdriver.WebDriver.find_element_by... |
Why does running Flask with Nginx require a WSGI wrapper? | 27,010,092 | 3 | 2014-11-19T06:04:43Z | 27,010,381 | 8 | 2014-11-19T06:27:55Z | [
"python",
"nginx",
"flask",
"wsgi"
] | So from the Python/Flask docs, they both recommend not running the Flask web server as the production web server which makes sense. My question is, am I then able to run my Flask application on top of an Nginx server? Why do all the guides on the internet recommend wrapping Flask around uWSGI, Tornado, or some other WS... | Nginx is a web server and is concerned with web server stuff, not with how to run Python programs. uWSGI is an application server and knows how to speak WSGI with Python (and other languages now). Both Nginx and uWSGI speak the WSGI-protocol, which is an efficient protocol over UNIX sockets.
Nginx deals with http requ... |
Python cStringIO take more time than StringIO in writing (performance of string methods) | 27,010,962 | 7 | 2014-11-19T07:07:40Z | 28,639,226 | 10 | 2015-02-20T22:19:22Z | [
"python",
"string",
"file",
"cstringio"
] | In my way to profile string methods in python so that I can use the fastest one.
I have this code to test string concatenation in files, StringIO, StringIO and normal string.
```
#!/usr/bin/env python
#title : pythonTiming.py
#description : Will be used to test timing function in python
#author ... | The reason that `StringIO` performs better is behind the scenes it just keeps a list of all the strings that have been written to it, and only combines them when necessary. So a write operation is as simple as appending an object to a list. However, the `cStringIO` module does not have this luxury and must copy over th... |
forward fill specific columns in pandas dataframe | 27,012,151 | 8 | 2014-11-19T08:31:39Z | 27,018,394 | 11 | 2014-11-19T13:45:13Z | [
"python",
"pandas"
] | If I have a dataframe df with multiple columns ['x', 'y', 'z'] how do I forward fill only one column 'x'
or a group of columns ['x','y']?
I only know to do it by axis. | The for loop as suggested by @Woody Pride is unnecessary. You can reduce it to:
```
cols = ['X', 'Y']
df[cols] = df[cols].ffill()
```
And I have also added a self containing example:
```
>>> import pandas as pd
>>> import numpy as np
>>>
>>> #%% create dataframe
... ts1 = [0, 1, np.nan, np.nan, np.nan, np.nan]
>>> ... |
Remove null fields from Django Rest Framework response | 27,015,931 | 2 | 2014-11-19T11:38:48Z | 28,870,066 | 7 | 2015-03-05T04:33:44Z | [
"python",
"django",
"api",
"django-rest-framework"
] | I have developed an API using django-rest-framework.
I am using ModelSerializer to return data of a model.
**models.py**
```
class MetaTags(models.Model):
title = models.CharField(_('Title'), max_length=255, blank=True, null=True)
name = models.CharField(_('Name'), max_length=255, blank=True, null=True)
```
... | The answer from CubeRZ didn't work for me, using DRF 3.0.5. I think the method to\_native has been removed and is now replaced by to\_representation, defined in Serializer instead of BaseSerializer.
I used the class below with DRF 3.0.5, which is a copy of the method from Serializer with a slight modification.
```
fr... |
Does virtualenv serve a purpose (in production) when using docker? | 27,017,715 | 11 | 2014-11-19T13:11:53Z | 27,017,843 | 13 | 2014-11-19T13:18:04Z | [
"python",
"virtualenv",
"docker"
] | For development we use virtualenv to have an isolated development when it comes to dependencies. From [this question](https://stackoverflow.com/questions/9337149/is-virtualenv-recommended-for-django-production-server) it seems deploying Python applications in a [virtualenv](/questions/tagged/virtualenv "show questions ... | Virtualenv was created long before docker. Today, I lean towards docker instead of virtualenv for these reasons:
* Virtualenv still means people consuming your product need to download eggs. With docker, they get something which is "known to work". No strings attached.
* Docker can do much more than virtualenv (like c... |
Does virtualenv serve a purpose (in production) when using docker? | 27,017,715 | 11 | 2014-11-19T13:11:53Z | 29,359,760 | 7 | 2015-03-31T02:48:33Z | [
"python",
"virtualenv",
"docker"
] | For development we use virtualenv to have an isolated development when it comes to dependencies. From [this question](https://stackoverflow.com/questions/9337149/is-virtualenv-recommended-for-django-production-server) it seems deploying Python applications in a [virtualenv](/questions/tagged/virtualenv "show questions ... | Yes. You should still use virtualenv. Also, you should be building wheels instead of eggs now. Finally, you should make sure that you keep your Docker image lean and efficient by building your wheels in a container with the full build tools and installing no build tools into your application container.
You should read... |
Move seaborn plot legend to a different position? | 27,019,079 | 8 | 2014-11-19T14:15:52Z | 27,084,389 | 9 | 2014-11-23T00:59:34Z | [
"python",
"seaborn"
] | I'm using `factorplot(kind="bar")` with seaborn.
The plot is fine except the legend is misplaced: too much to the right, text goes out of the plot's shaded area.
How do I make seaborn place the legend somewhere else, such as in top-left instead of middle-right? | Building on @user308827's answer: you can use `legend=False` in factorplot and specify the legend through matplotlib:
```
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="whitegrid")
titanic = sns.load_dataset("titanic")
g = sns.factorplot("class", "survived", "sex",
data=titan... |
How to scale Seaborn's y-axis with a bar plot? | 27,019,153 | 6 | 2014-11-19T14:19:15Z | 27,107,856 | 7 | 2014-11-24T15:04:34Z | [
"python",
"seaborn"
] | I'm using `factorplot(kind="bar")`.
How do I scale the y-axis, for example with log-scale?
I tried tinkering with the plot's axes, but that always messed up the bar plot in one way or another, so please try your solution first to make sure it really works. | You can use Matplotlib commands after calling `factorplot`.
For example:
```
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="whitegrid")
titanic = sns.load_dataset("titanic")
g = sns.factorplot("class", "survived", "sex",
data=titanic, kind="bar",
size=6, pa... |
Drop row in pandas dataframe if any value in the row equals zero | 27,020,312 | 4 | 2014-11-19T15:14:36Z | 27,020,741 | 7 | 2014-11-19T15:33:47Z | [
"python",
"pandas"
] | How do I drop a row if any of the values in the row equal zero?
I would normally use df.dropna() for NaN values but not sure how to do it with "0" values. | i think the easiest way is looking at rows where all values are not equal to 0:
```
df[(df != 0).all(1)]
``` |
Drop row in pandas dataframe if any value in the row equals zero | 27,020,312 | 4 | 2014-11-19T15:14:36Z | 27,020,744 | 8 | 2014-11-19T15:33:53Z | [
"python",
"pandas"
] | How do I drop a row if any of the values in the row equal zero?
I would normally use df.dropna() for NaN values but not sure how to do it with "0" values. | You could make a boolean frame and then use `any`:
```
>>> df = pd.DataFrame([[1,0,2],[1,2,3],[0,1,2],[4,5,6]])
>>> df
0 1 2
0 1 0 2
1 1 2 3
2 0 1 2
3 4 5 6
>>> df == 0
0 1 2
0 False True False
1 False False False
2 True False False
3 False False False
>>> df = df[~(df =... |
Python Requests: Don't wait for request to finish | 27,021,440 | 4 | 2014-11-19T16:05:49Z | 27,022,707 | 7 | 2014-11-19T17:05:10Z | [
"python",
"python-requests"
] | In Bash, it is possible to execute a command in the background by appending `&`. How can I do it in Python?
```
while True:
data = raw_input('Enter something: ')
requests.post(url, data=data) # Don't wait for it to finish.
print('Sending POST request...') # This should appear immediately.
``` | I use `multiprocessing.dummy.Pool`. I create a singleton thread pool at the module level, and then use `pool.apply_async(requests.get, [params])` to launch the task.
This command gives me a future, which I can add to a list with other futures indefinitely until I'd like to collect all or some of the results.
`multipr... |
Filter RDD based on row_number | 27,022,059 | 6 | 2014-11-19T16:34:23Z | 27,022,925 | 9 | 2014-11-19T17:16:25Z | [
"python",
"csv",
"apache-spark"
] | sc.textFile(path) allows to read an HDFS file but it does not accept parameters (like skip a number of rows, has\_headers,...).
in the "Learning Spark" O'Reilly e-book, it's suggested to use the following function to read a CSV (Example 5-12. Python load CSV example)
```
import csv
import StringIO
def loadRecord(lin... | Don't worry about loading the rows/lines you don't need. When you do:
```
input = sc.textFile(inputFile)
```
you are not loading the file. You are just getting an object that will allow you to operate on the file. So to be efficient, it is better to think in terms of getting only what you want. For example:
```
head... |
plotting 3d vectors using matplot lib | 27,023,068 | 5 | 2014-11-19T17:23:24Z | 27,025,181 | 7 | 2014-11-19T19:19:55Z | [
"python",
"vector",
"matplotlib",
"3d"
] | I am trying to plot vectors in 3d using matplotlib. I used the following code based on a previous example of plotting 2d vectors but added components for 3d vectors.
```
#!/usr/bin/python
import numpy as np
import matplotlib.pyplot as plt
soa =np.array( [ [0,0,1,1,-2,0], [0,0,2,1,1,0],[0,0,3,2,1,0],[0,0,4,0.5,0.7,0]... | You need to use Axes3D from mplot3d in mpl\_toolkits, then set the subplot projection to 3d:
```
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
soa =np.array( [ [0,0,1,1,-2,0], [0,0,2,1,1,0],[0,0,3,2,1,0],[0,0,4,0.5,0.7,0]])
X,Y,Z,U,V,W = zip(*soa)
fig = plt.figure()
ax =... |
Sublime Text Auto-Indent Python Keyword Arguments | 27,023,833 | 4 | 2014-11-19T18:04:57Z | 27,175,462 | 13 | 2014-11-27T16:44:39Z | [
"python",
"sublimetext",
"sublimetext3",
"pep8"
] | I'm having an issue making Sublime act the way I like with keyword arguments.
PEP-8 allows for two conventions for function calls:
```
function_name(
arg=1,
arg2=blah)
```
And:
```
function_name(arg=1,
arg2=blah)
```
I much prefer the latter for lines less then 80 characters. but Sublime Text ... | You need to change Sublime Text Preferences.
1. Open Preferences
2. Settings - User
3. Add this line there:
{"indent\_to\_bracket": true,}
4. Restart Sublime
After this you code will be formated in this way:
```
def function(*arg,
**kwargs):
#body
``` |
Celery tasks not throwing exception in Django Tests | 27,029,745 | 4 | 2014-11-20T00:38:34Z | 27,031,659 | 8 | 2014-11-20T04:16:28Z | [
"python",
"django",
"testing",
"celery",
"celery-task"
] | I have a couple of celery tasks that are included in my Django tests. Unfortunately exceptions are not thrown when tasks are invoked via *.delay()*. I am setting [CELERY\_ALWAYS\_EAGER](http://celery.readthedocs.org/en/latest/configuration.html#celery-always-eager "CELERY_ALWAYS_EAGER") to True.
**tasks.py**
```
impo... | Seems I additionally had to set [CELERY\_EAGER\_PROPAGATES\_EXCEPTIONS](http://celery.readthedocs.org/en/latest/configuration.html#celery-eager-propagates-exceptions) to True. |
Indentation not working properly in emacs for python | 27,032,218 | 9 | 2014-11-20T05:10:56Z | 27,035,992 | 14 | 2014-11-20T09:28:58Z | [
"python",
"emacs"
] | I am using emacs-for-python provided by gabrielelanaro at this [link](https://github.com/gabrielelanaro/emacs-for-python).
Indentation doesn't seem to be working for me at all.
It doesn't happen automatically when I create a class, function or any other block of code that requires automatic indentation(if, for etc.) ... | Check the value of `python-indent-offset`. If it is 0, change it `M-x set-variable RET python-indent-offset RET 4 RET`.
Emacs tries to guess the offset used in a Python file when opening it. It might get confused and set that variable to 0 for some badly-formatted Python file. If this is indeed the problem, please do ... |
Flask cannot import enumerate? UndefinedError: 'enumerate' is undefined | 27,035,728 | 3 | 2014-11-20T09:15:55Z | 27,036,691 | 11 | 2014-11-20T10:01:22Z | [
"python",
"flask",
"jinja2"
] | I just write this code in a HTML page.
```
{% for i, val in enumerate(['a', 'b', 'c']) %}
<td>
{{ val }}
</td>
{% endfor %}
UndefinedError: 'enumerate' is undefined
```
So, Flask do not support the enumerate? | As Or Duan says, Jinja2 has its own language. Looks like Python but it's not Python. So the Python `enumerate` built-in function is not part of Jinja2 template engine. There are, however, some alternatives you can use:
If you want to enumerate the items in a list you can use the [`loop.index0`](http://jinja.pocoo.org/... |
Changing the rotation of tick labels in Seaborn heatmap | 27,037,241 | 11 | 2014-11-20T10:28:33Z | 27,037,427 | 20 | 2014-11-20T10:36:18Z | [
"python",
"heatmap",
"seaborn"
] | I'm plotting a heatmap in Seaborn. The problem is that I have too many squares in my plot so the x and y labels are too close to each other to be useful. So I'm creating a list of xticks and yticks to use. However passing this list to the function rotates the labels in the plot. It would be really nice to have seaborn ... | `seaborn` uses `matplotlib` internally, as such you can use `matplotlib` functions to modify your plots. I've modified the code below to use the [`plt.yticks`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.yticks) function to set `rotation=0` which fixes the issue.
```
import pandas as pd
import numpy as... |
How to load JSON data into nested classes? | 27,038,259 | 9 | 2014-11-20T11:18:18Z | 27,039,109 | 8 | 2014-11-20T12:01:17Z | [
"python",
"json",
"json-deserialization"
] | I have JSON data as follows:
```
{
"Address": {
"House_Number": 2,
"State": "MA",
"Street_Number": 13
},
"Name": "John"
}
```
I want to load it into a class defined as follows:
```
class Address:
def __init__(self):
self.House_Number = 0
class Employee:
def __init... | You can identify objects by looking at their keys. You can then map them to the appropriate class.
Using your example data:
```
class AddressClass:
# The parameters to init needs to be the same as the json keys
def __init__(self, House_Number, Street_Number, State):
self.house_number = House_Number
... |
Tornado coroutine | 27,043,076 | 8 | 2014-11-20T15:18:34Z | 27,043,961 | 20 | 2014-11-20T15:58:51Z | [
"python",
"tornado"
] | I am trying to learn tornado coroutines, but I have error using below code.
```
Traceback (most recent call last):
File "D:\projekty\tornado\env\lib\site-packages\tornado\web.py", line 1334, in _execute
result = yield result
File "D:\projekty\tornado\env\lib\site-packages\tornado\gen.py", line 628, in run
... | As Lutz Horn pointed out, the `tornado.coroutine` decorator requires that you yield only `Future` objects or certain containers containing `Future` objects. So trying to yield a `str` will raise an error. I think the piece you're missing is that any place inside of a coroutine where you want to call `yield something()`... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.