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 |
|---|---|---|---|---|---|---|---|---|---|
Why not generating the secret key every time Flask application starts? | 27,287,391 | 11 | 2014-12-04T06:05:50Z | 27,287,455 | 12 | 2014-12-04T06:10:15Z | [
"python",
"session",
"flask",
"session-cookies"
] | When using sessions, Flask requires a secret key. In every example I've seen, the secret key is somehow generated and then stored either in source code or in configuration file.
What is the reason to store it permanently? Why not simply generating it when Flask application starts?
```
app.secret_key = os.urandom(50)
... | The secret key is used to sign the session cookie. If you had to restart your application, and regenerated the key, all the existing sessions would be invalidated. That's probably not what you want (or at least, not the right way to go about invalidating sessions). A similar case could be made for anything else that re... |
Pass column name as parameter to PostgreSQL using psycopg2 | 27,289,957 | 4 | 2014-12-04T09:04:08Z | 27,291,545 | 9 | 2014-12-04T10:24:05Z | [
"python",
"sql",
"postgresql",
"parameters",
"psycopg2"
] | I'm trying to add columns to a table using `psycopg2`
`row1` below is a list of column names to be added to the table. I can do it manually but when I try to do it programatically I get an error.
```
for c in row1:
cur.execute("ALTER TABLE HHV2PUB ADD COLUMN %s text", (c,))
```
The error is:
```
cur.execute... | Use `psycopg2.extensions.AsIs`
> [Adapter conform to the ISQLQuote protocol useful for objects whose string representation is already valid as SQL representation.](http://initd.org/psycopg/docs/extensions.html#psycopg2.extensions.AsIs)
```
import psycopg2
from psycopg2.extensions import AsIs
conn = psycopg2.connect(... |
Get area within contours Opencv Python? | 27,299,405 | 5 | 2014-12-04T16:46:23Z | 27,301,799 | 8 | 2014-12-04T18:56:47Z | [
"python",
"opencv",
"image-processing",
"opencv-contour"
] | I have used an adaptive thresholding technique to create a picture like the one below:

The code I used was:
```
image = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 45, 0)
```
Then, I use this code to get... | What you have is almost correct. If you take a look at your thresholded image, the reason why it isn't working is because your shoe object **has gaps** in the image. Specifically, what you're after is that you expect that the shoe has its perimeter to be **all** connected. If this were to happen, then if you extract th... |
How does one ignore CSRF tokens sent to Django REST Framework? | 27,299,825 | 5 | 2014-12-04T17:07:12Z | 27,301,522 | 10 | 2014-12-04T18:40:30Z | [
"python",
"django",
"angularjs",
"django-rest-framework",
"django-csrf"
] | I have a single page angularjs application utilizing JWT authentication. Because JWTs are sent with every single request, it seems redundant to use CSRF tokens in my forms. In order to disable CSRF checking, I commented out 'django.middleware.csrf.CsrfViewMiddleware' in my settings.py middleware classes. This all works... | It sounds like you have `SessionAuthentication` enabled, which is the part of Django REST Framework that enforces CSRF for cookie-based authentication. Since you are using JWT, and you mentioned that all pages use JWT for authentication, you should be able to just remove `SessionAuthentication` from your list of defaul... |
Selenium webdriver: How do I find ALL of an element's attributes? | 27,307,131 | 10 | 2014-12-05T01:05:39Z | 27,307,235 | 17 | 2014-12-05T01:16:14Z | [
"python",
"selenium",
"selenium-webdriver"
] | In the Python Selenium module, once I have a WebElement object I can get the value of any of its attributes with `get_attribute()`:
```
foo = elem.get_attribute('href')
```
If the attribute named 'href' doesn't exist, None is returned.
My question is, how can I get a list of all of the attributes that an element has... | It is **not possible** using a selenium webdriver API, but you can [*execute a javascript code* to get all attributes](http://stackoverflow.com/questions/21681897/getting-all-attributes-from-an-iwebelement-with-selenium-webdriver):
```
driver.execute_script('var items = {}; for (index = 0; index < arguments[0].attribu... |
Best way to access the Nth line of csv file | 27,307,385 | 17 | 2014-12-05T01:35:49Z | 27,307,452 | 17 | 2014-12-05T01:42:53Z | [
"python",
"file",
"csv",
"python-3.x"
] | I have to access the Nth line in a CSV file.
Here's what I did:
```
import csv
the_file = open('path', 'r')
reader = csv.reader(the_file)
N = input('What line do you need? > ')
i = 0
for row in reader:
if i == N:
print("This is the line.")
print(row)
break
i += 1
the_file.close()
... | It makes little difference but it is slightly cleaner to use `enumerate` rather than making your own counter variable.
```
for i, row in enumerate(reader):
if i == N:
print("This is the line.")
print(row)
break
```
You can also use `itertools.islice` which is designed for this type of scen... |
Best way to access the Nth line of csv file | 27,307,385 | 17 | 2014-12-05T01:35:49Z | 27,307,466 | 7 | 2014-12-05T01:45:26Z | [
"python",
"file",
"csv",
"python-3.x"
] | I have to access the Nth line in a CSV file.
Here's what I did:
```
import csv
the_file = open('path', 'r')
reader = csv.reader(the_file)
N = input('What line do you need? > ')
i = 0
for row in reader:
if i == N:
print("This is the line.")
print(row)
break
i += 1
the_file.close()
... | You can simply do:
```
n = 2 # line to print
fd = open('foo.csv', 'r')
lines = fd.readlines()
print lines[n-1] # prints 2nd line
fd.close()
```
Or even better to utilize less memory by not loading entire file into memory:
```
import linecache
n = 2
linecache.getline('foo.csv', n)
``` |
Python - how to count item in json data | 27,315,472 | 12 | 2014-12-05T12:01:04Z | 27,352,342 | 18 | 2014-12-08T06:10:56Z | [
"python",
"json",
"count",
"element"
] | How I can get numer of elements in node of JSON data, in Python language? This is example of JSON:
```
{
"result":[
{
"run":[
{
"action":"stop"
},
{
"action":"start"
},
{
"action":"start"
}
],
"find":true
}
]
}
... | ```
import json
json_data = json.dumps({
"result":[
{
"run":[
{
"action":"stop"
},
{
"action":"start"
},
{
"action":"start"
}
],
"find": "true"
}
]
})
item_dict = json.loads(json_data)
print len(item_dict['resu... |
@csrf_exempt does not work on generic view based class | 27,315,592 | 6 | 2014-12-05T12:08:49Z | 27,315,856 | 23 | 2014-12-05T12:25:37Z | [
"python",
"django"
] | ```
class ChromeLoginView(View):
def get(self, request):
return JsonResponse({'status': request.user.is_authenticated()})
@method_decorator(csrf_exempt)
def post(self, request):
username = request.POST['username']
password = request.POST['password']
user = authen... | You need to decorate the `dispatch` method for `csrf_exempt` to work. What it does is set an `csrf_exempt` attribute on the view function itself to `True`, and the middleware checks for this on the (outermost) view function. If only a few of the methods need to be decorated, you still need to use `csrf_exempt` on the `... |
Make division by zero equal to zero | 27,317,517 | 2 | 2014-12-05T13:57:50Z | 27,317,547 | 10 | 2014-12-05T13:59:30Z | [
"python",
"division",
"zero"
] | How can I ignore `ZeroDivisionError` and make `n / 0 == 0`? | You can use a `try`/`except` block for this.
```
def foo(x,y):
try:
return x/y
except ZeroDivisionError:
return 0
>>> foo(5,0)
0
>>> foo(6,2)
3.0
``` |
Make division by zero equal to zero | 27,317,517 | 2 | 2014-12-05T13:57:50Z | 27,317,595 | 11 | 2014-12-05T14:02:27Z | [
"python",
"division",
"zero"
] | How can I ignore `ZeroDivisionError` and make `n / 0 == 0`? | Check if the denominator is zero before dividing. This avoids the overhead of catching the exception, which may be more efficient if you expect to be dividing by zero a lot.
```
def weird_division(n, d):
return n / d if d else 0
``` |
Why can I pass an instance method to multiprocessing.Process, but not a multiprocessing.Pool? | 27,318,290 | 16 | 2014-12-05T14:39:52Z | 27,320,254 | 13 | 2014-12-05T16:19:14Z | [
"python",
"python-2.7",
"multiprocessing",
"pickle"
] | I am trying to write an application that applies a function concurrently with a `multiprocessing.Pool`. I would like this function to be an instance method (so I can define it differently in different subclasses). This doesn't seem to be possible; as I have learned elsewhere, apparently [bound methods can't be pickled]... | The `pickle` module normally can't pickle instance methods:
```
>>> import pickle
>>> class A(object):
... def z(self): print "hi"
...
>>> a = A()
>>> pickle.dumps(a.z)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/pickle.py", line 1374, in dumps
Pickle... |
Firefox Build does not work with Selenium | 27,321,907 | 22 | 2014-12-05T17:55:52Z | 27,574,843 | 12 | 2014-12-19T22:33:50Z | [
"python",
"firefox",
"selenium",
"build"
] | for my research, I did some source code modifications in firefox and build it myself. In order to automate testing, I opted to use Selenium but unfortunately, my newly built Firefox seem to not support Selenium.
I did the following:
```
from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary imp... | I have spent a long time debugging this and ultimately gave up trying to make incompatible versions of selenium/firefox work. I just don't have the expertise in firefox to go any further. My recommendation is downloading stable versions from <https://ftp.mozilla.org/pub/mozilla.org/firefox/releases/> and keep trying co... |
Firefox Build does not work with Selenium | 27,321,907 | 22 | 2014-12-05T17:55:52Z | 28,822,807 | 32 | 2015-03-03T01:57:55Z | [
"python",
"firefox",
"selenium",
"build"
] | for my research, I did some source code modifications in firefox and build it myself. In order to automate testing, I opted to use Selenium but unfortunately, my newly built Firefox seem to not support Selenium.
I did the following:
```
from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary imp... | Ubuntu 14.04, firefox 36.0, selenium 2.44.0.
The same problem, was solved by:
```
sudo pip install -U selenium
```
Selenium 2.45.0 is OK with FF36.
update: Selenium 2.53+ is compatible with FF45
You can get older FF versions [here](https://ftp.mozilla.org/pub/firefox/releases/) |
scrapy: convert html string to HtmlResponse object | 27,323,740 | 6 | 2014-12-05T19:59:10Z | 27,323,814 | 7 | 2014-12-05T20:04:18Z | [
"python",
"web-scraping",
"scrapy"
] | I have a raw html string that I want to convert to scrapy HTML response object so that I can use the selectors `css` and `xpath`, similar to scrapy's `response`. How can I do it? | First of all, if it is for debugging or testing purposes, you can use the [`Scrapy shell`](http://doc.scrapy.org/en/latest/topics/shell.html):
```
$ cat index.html
<div id="test">
Test text
</div>
$ scrapy shell index.html
>>> response.xpath('//div[@id="test"]/text()').extract()[0].strip()
u'Test text'
```
There... |
Convert word2vec bin file to text | 27,324,292 | 25 | 2014-12-05T20:39:00Z | 27,329,142 | 13 | 2014-12-06T06:49:04Z | [
"python",
"c",
"gensim",
"word2vec"
] | From the [word2vec](https://code.google.com/p/word2vec/) site I can download GoogleNews-vectors-negative300.bin.gz. The .bin file (about 3.4GB) is a binary format not useful to me. Tomas Mikolov [assures us](https://groups.google.com/d/msg/word2vec-toolkit/lxbl_MB29Ic/g4uEz5rNV08J) that "It should be fairly straightfor... | On the word2vec-toolkit mailing list Thomas Mensink has provided an [answer](https://groups.google.com/forum/#!topic/word2vec-toolkit/5Qh-x2O1lV4) in the form of a small C program that will convert a .bin file to text. This is a modification of the distance.c file. I replaced the original distance.c with Thomas's code ... |
Convert word2vec bin file to text | 27,324,292 | 25 | 2014-12-05T20:39:00Z | 33,183,634 | 19 | 2015-10-17T06:36:16Z | [
"python",
"c",
"gensim",
"word2vec"
] | From the [word2vec](https://code.google.com/p/word2vec/) site I can download GoogleNews-vectors-negative300.bin.gz. The .bin file (about 3.4GB) is a binary format not useful to me. Tomas Mikolov [assures us](https://groups.google.com/d/msg/word2vec-toolkit/lxbl_MB29Ic/g4uEz5rNV08J) that "It should be fairly straightfor... | I use this code to load binary model, then save the model to text file,
```
from gensim.models import word2vec
model = word2vec.Word2Vec.load_word2vec_format('path/to/GoogleNews-vectors-negative300.bin', binary=True)
model.save_word2vec_format('path/to/GoogleNews-vectors-negative300.txt', binary=False)
```
Reference... |
With Django, what is the best practice way to add up a specific field on each object in a queryset? | 27,324,989 | 2 | 2014-12-05T21:30:48Z | 27,325,048 | 7 | 2014-12-05T21:35:08Z | [
"python",
"django",
"django-models",
"django-queryset"
] | This is how I'm currently getting a total of each object.balance in my queryset. It feels wrong. Is there a better way? (I'm struggling to explain/write the question so just see the code below :) )
```
# models.py
...
class Foo(models.Model):
...
balance = models.DecimalField(
max_digits=10,
... | There is [`Sum()`](https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.Sum) built-in to Django:
```
Foo.objects.aggregate(Sum('balance'))
``` |
Visualizing time series in spirals using R or Python? | 27,325,044 | 6 | 2014-12-05T21:34:51Z | 27,326,970 | 9 | 2014-12-06T00:43:15Z | [
"python",
"visualization",
"data-visualization"
] | Does anyone know how to do this in R? That is, represent this cyclical data from the left plot to the right plot?
<http://cs.lnu.se/isovis/courses/spring07/dac751/papers/TimeSpiralsInfoVis2001.pdf>

Here is some example data.
```
Day = c(rep(1,5),re... | This seems pretty close:

```
# sample data - hourly for 10 days; daylight from roughly 6:00am to 6:00pm
set.seed(1) # for reproducibility
Day <- c(rep(1:10,each=24))
Hour <- rep(1:24)
data <- data.frame(Day,Hour)
data$Sunlight <- with(data,-10*cos(2*pi*(Hour-1+abs(rnorm(24... |
Python Pandas read_csv skip rows but keep header | 27,325,652 | 11 | 2014-12-05T22:24:32Z | 27,325,729 | 10 | 2014-12-05T22:29:50Z | [
"python",
"csv",
"pandas"
] | I'm having trouble figuring out how to skip n rows in a csv file but keep the header which is the 1 row.
What I want to do is iterate but keep the header from the first row. `skiprows` makes the header the first row after the skipped rows. What is the best way of doing this?
```
data = pd.read_csv('test.csv', sep='|'... | You can pass a list of row numbers to `skiprows` instead of an integer. The reader will then ignore those rows in the list.
By giving the function the integer 10, you're just skipping the first 10 lines.
To keep the first row 0 (as the header) and then skip to row 10, you could write:
```
pd.read_csv('test.csv', sep... |
dbscan indices are out-of-bounds python | 27,332,557 | 4 | 2014-12-06T14:11:33Z | 27,332,714 | 7 | 2014-12-06T14:31:07Z | [
"python",
"dbscan"
] | this is my code.
```
from sklearn.cluster import DBSCAN
dbscan = DBSCAN(random_state=111)
dbscan.fit(data3)
```
data3 is a pandas dataframe:
```
FAC1_2 FAC2_2
0 -0.227252 -0.685482
1 0.015251 -0.988252
2 -0.291176 -0.696146
3 -0.747702 -0.708030
4 -0.648103 -0.701741
5 -0.546777 -0.906151
6 ... | the problem was a bug. It doesn't work with pandas dataframe. The solution is to convert the pandas dataframe into a numpy array:
```
data3 = np.array(data3)
``` |
How do I encrypt and decrypt a string in python? | 27,335,726 | 3 | 2014-12-06T19:46:17Z | 27,335,837 | 9 | 2014-12-06T19:57:40Z | [
"python",
"python-3.x",
"encryption"
] | I have been looking for sometime on how to encrypt and decrypt a string. But most of it is in 2.7 and anything that is using 3.2 is not letting me print it or add it to a string.
So what I'm trying to do is the following:
```
mystring = "Hello stackoverflow!"
encoded = encode(mystring,"password")
print(encoded)
```
... | Take a look at [PyCrypto](https://pypi.python.org/pypi/pycrypto). It supports Python 3.2 and does exactly what you want.
From their pip website:
```
>>> from Crypto.Cipher import AES
>>> obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
>>> message = "The answer is no"
>>> ciphertext = obj.encrypt(m... |
How to send zip files in the python Flask framework? | 27,337,013 | 5 | 2014-12-06T21:54:09Z | 27,337,047 | 10 | 2014-12-06T21:57:51Z | [
"python",
"http",
"flask"
] | I have a flask server that grabs binary data for several different files from a database and puts them into a python 'zipfile' object. I want to send the generated zip file with my code using flask's "send\_file" method.
I was originally able to send non-zip files successfully by using the BytesIO(bin) as the first ar... | `BytesIO()` needs to be passed *bytes data*, but a `ZipFile()` object is not bytes-data; you actually created a file *on your harddisk*.
You can create a `ZipFile()` in memory by using `BytesIO()` *as the base*:
```
memory_file = BytesIO()
with zipfile.ZipFile(memory_file, 'w') as zf:
files = result['files']
... |
How do I fix 'ImportError: cannot import name IncompleteRead'? | 27,341,064 | 204 | 2014-12-07T08:44:01Z | 27,341,813 | 11 | 2014-12-07T10:43:07Z | [
"python",
"pip"
] | When I try to install anything with `pip` or `pip3`, I get:
```
$ sudo pip3 install python3-tk
Traceback (most recent call last):
File "/usr/bin/pip3", line 9, in <module>
load_entry_point('pip==1.5.6', 'console_scripts', 'pip3')()
File "/usr/lib/python3/dist-packages/pkg_resources.py", line 356, in load_entry... | The problem is the Python module `requests`. It can be fixed by
```
$ sudo apt-get purge python-requests
[now requests and pip gets deinstalled]
$ sudo apt-get install python-requests python-pip
```
If you have this problem with Python 3, you have to write `python3` instead of `python`. |
How do I fix 'ImportError: cannot import name IncompleteRead'? | 27,341,064 | 204 | 2014-12-07T08:44:01Z | 27,341,847 | 72 | 2014-12-07T10:48:43Z | [
"python",
"pip"
] | When I try to install anything with `pip` or `pip3`, I get:
```
$ sudo pip3 install python3-tk
Traceback (most recent call last):
File "/usr/bin/pip3", line 9, in <module>
load_entry_point('pip==1.5.6', 'console_scripts', 'pip3')()
File "/usr/lib/python3/dist-packages/pkg_resources.py", line 356, in load_entry... | This problem is caused by a mismatch between your pip installation and your requests installation.
As of requests version 2.4.0 `requests.compat.IncompleteRead` [has been removed](https://github.com/tweepy/tweepy/issues/501). Older versions of pip, e.g. [from July 2014](https://github.com/pypa/pip/blob/0dedf2b6f5adefc... |
How do I fix 'ImportError: cannot import name IncompleteRead'? | 27,341,064 | 204 | 2014-12-07T08:44:01Z | 27,425,458 | 320 | 2014-12-11T14:42:40Z | [
"python",
"pip"
] | When I try to install anything with `pip` or `pip3`, I get:
```
$ sudo pip3 install python3-tk
Traceback (most recent call last):
File "/usr/bin/pip3", line 9, in <module>
load_entry_point('pip==1.5.6', 'console_scripts', 'pip3')()
File "/usr/lib/python3/dist-packages/pkg_resources.py", line 356, in load_entry... | While [this previous answer](http://stackoverflow.com/a/27341847/2854723) might be the reason, this snipped worked for me as a solution (in `Ubuntu 14.04`):
First remove the package from the package manager:
```
# apt-get remove python-pip
```
And then install the latest version by side:
```
# easy_install pip
```
... |
How do I fix 'ImportError: cannot import name IncompleteRead'? | 27,341,064 | 204 | 2014-12-07T08:44:01Z | 27,439,807 | 16 | 2014-12-12T08:45:08Z | [
"python",
"pip"
] | When I try to install anything with `pip` or `pip3`, I get:
```
$ sudo pip3 install python3-tk
Traceback (most recent call last):
File "/usr/bin/pip3", line 9, in <module>
load_entry_point('pip==1.5.6', 'console_scripts', 'pip3')()
File "/usr/lib/python3/dist-packages/pkg_resources.py", line 356, in load_entry... | On Ubuntu 14.04 I resolved this by using the pip installation bootstrap script, as described in [the documentation](https://pip.pypa.io/en/latest/installing.html)
```
wget https://bootstrap.pypa.io/get-pip.py
sudo python get-pip.py
```
That's an OK solution for a development environment. |
How do I fix 'ImportError: cannot import name IncompleteRead'? | 27,341,064 | 204 | 2014-12-07T08:44:01Z | 27,790,679 | 58 | 2015-01-06T01:22:18Z | [
"python",
"pip"
] | When I try to install anything with `pip` or `pip3`, I get:
```
$ sudo pip3 install python3-tk
Traceback (most recent call last):
File "/usr/bin/pip3", line 9, in <module>
load_entry_point('pip==1.5.6', 'console_scripts', 'pip3')()
File "/usr/lib/python3/dist-packages/pkg_resources.py", line 356, in load_entry... | For fixing pip3 (worked on Ubuntu 14.10):
```
easy_install3 -U pip
``` |
How do I fix 'ImportError: cannot import name IncompleteRead'? | 27,341,064 | 204 | 2014-12-07T08:44:01Z | 31,982,614 | 9 | 2015-08-13T07:58:12Z | [
"python",
"pip"
] | When I try to install anything with `pip` or `pip3`, I get:
```
$ sudo pip3 install python3-tk
Traceback (most recent call last):
File "/usr/bin/pip3", line 9, in <module>
load_entry_point('pip==1.5.6', 'console_scripts', 'pip3')()
File "/usr/lib/python3/dist-packages/pkg_resources.py", line 356, in load_entry... | Or you can remove all `requests`.
For example:
* `rm -rf /usr/local/lib/python2.7/dist-packages/requests*` |
Decorator execution order | 27,342,149 | 21 | 2014-12-07T11:24:49Z | 27,342,171 | 30 | 2014-12-07T11:27:22Z | [
"python",
"decorator",
"python-decorators"
] | ```
def make_bold(fn):
return lambda : "<b>" + fn() + "</b>"
def make_italic(fn):
return lambda : "<i>" + fn() + "</i>"
@make_bold
@make_italic
def hello():
return "hello world"
helloHTML = hello()
```
Output: `"<b><i>hello world</i></b>"`
I roughly understand about decorators and how it works with one o... | Decorators *wrap* the function they are decorating. So `make_bold` decorated the result of the `make_italic` decorator, which decorated the `hello` function.
The `@decorator` syntax is really just syntactic sugar; the following:
```
@decorator
def decorated_function():
# ...
```
is really executed as:
```
def d... |
How to connect PyCharm to a python interpreter located inside a Docker container? | 27,343,452 | 26 | 2014-12-07T14:04:12Z | 31,078,256 | 9 | 2015-06-26T16:46:17Z | [
"python",
"docker",
"pycharm"
] | I'm starting with Docker, but I don't know how to configure PyCharm to use a python interpreter located in a container.
[It was easy to setup with Vagrant](https://www.jetbrains.com/pycharm/quickstart/configuring_for_vm.html), but there's [apparently no official way to do it with Docker](http://forum.jetbrains.com/thr... | Here is how I solved the problem. My circumstances are that I was assigned to do an intervention on a specific area of a web app that used docker-compose to create a set of four containers. Docker-compose is a kind of meta docker that manages multiple docker containers from one command. I did not want to mangle their e... |
Django Rest Framework {"detail":"Authentication credentials were not provided."} | 27,343,504 | 5 | 2014-12-07T14:11:11Z | 28,840,092 | 9 | 2015-03-03T19:17:00Z | [
"python",
"django",
"rest",
"django-rest-framework"
] | I have tried to add authentication to my Rest API using OAuth Toolkit. I get to the login page and enter in my username and password then redirect to my api. I then get a message {"detail":"Authentication credentials were not provided."} I have tried looking into this and most people who have the problem seem to have m... | In my case token authentication was working fine on development server and not on Apache. The reason was exactly the missing `WSGIPassAuthorization On`
<http://www.django-rest-framework.org/api-guide/authentication/#apache-mod_wsgi-specific-configuration> |
How Django atomic requests works? | 27,346,003 | 6 | 2014-12-07T18:10:59Z | 27,346,234 | 19 | 2014-12-07T18:30:38Z | [
"python",
"django",
"atomic",
"django-database"
] | I'd like my Django views to be atomic. I mean, if there is 2 DB-writes in the view, I want either 0 write, either 2 writes.
For example:
```
def test_view(request):
''' A test view from views.py '''
MyClass.objects.create()
raise Exception("whatever")
MyClass.objects.create()
```
What I found in doc... | ATOMIC\_REQUESTS is an an attribute of the database connection settings dict, not the top-level settings. So, for example:
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'mydatabase',
'USER': 'mydatabaseuser',
'PASSWORD': 'mypassword',
... |
Concurrrency issue with psycopg2.ThreadConnectionPool, uWSGI and Flask | 27,355,839 | 3 | 2014-12-08T10:24:18Z | 27,356,343 | 7 | 2014-12-08T10:51:16Z | [
"python",
"concurrency",
"flask",
"uwsgi",
"psycopg2"
] | I'm using Flask, psycopg2 and uWSGI. I'm using `psycopg2.ThreadConnectionPool` for DB connection pooling and only `cursor.callproc` is used for quering DB.
The problem: sometimes, during concurrent requests, procedure call results are mixed up, the code is querying `procedure_1` but is getting results for `procedure_2... | You are initializing the threadpool in the master, after it calls fork() (to generate workers) all will be messed up (unless you manage it). Ensure to initialize the pool one time per worker or use lazy-apps = true in uWSGI to load the app one time per worker. |
Celery task always PENDING | 27,357,732 | 5 | 2014-12-08T12:11:48Z | 27,358,974 | 7 | 2014-12-08T13:21:00Z | [
"python",
"windows",
"redis",
"celery"
] | I try to run Celery example on Windows with redis backend. The code looks like:
```
from celery import Celery
app = Celery('risktools.distributed.celery_tasks',
backend='redis://localhost',
broker='redis://localhost')
@app.task(ignore_result=False)
def add(x, y):
return x + y
@app.task... | Accroding to [Celery 'Getting Started' not able to retrieve results; always pending](https://stackoverflow.com/questions/25495613/celery-getting-started-not-able-to-retrieve-results-always-pending) and <https://github.com/celery/celery/issues/2146> it is a Windows issue. Celery `--pool=solo` option solves the issue. |
how to downgrade from Django 1.7 to Django 1.6 | 27,359,964 | 9 | 2014-12-08T14:17:57Z | 28,822,754 | 20 | 2015-03-03T01:52:18Z | [
"python",
"django",
"django-1.6",
"django-1.7"
] | I started a new project a few months back using Django 1.7. The company has decided to settle on using Django 1.6 for all projects.
Is there a nice way to downgrade from Django 1.7 to 1.6?
Are migrations the only thing I have to worry about? Are the changes between the two versions large enough that I need to rewrite... | sudo pip install Django==1.6.10 |
How to close socket connection on Ctrl-C in a python programme | 27,360,218 | 3 | 2014-12-08T14:30:13Z | 27,360,648 | 8 | 2014-12-08T14:53:18Z | [
"python",
"sockets",
"tcp",
"server"
] | ```
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
any_connection = False
while True:
try:
conn, addr = s.accept()
data = conn.recv(1024)
any_connection = True
# keep looking
if not data: continue
pid = os.fork()
if... | As per the [docs](https://docs.python.org/2/library/socket.html) the error `OSError: [Errno 48] Address already in use` occurs because
the previous execution of your script has left the socket in a TIME\_WAIT state, and canât be immediately reused. This can be resolved by using the `socket.SO_REUSEADDR` flag.
For eg... |
Kivy - Screen Manager - Accessing attribute in other class | 27,362,687 | 5 | 2014-12-08T16:45:02Z | 27,376,030 | 7 | 2014-12-09T09:57:29Z | [
"python",
"kivy",
"screens"
] | Using the Kivy Screen Manager, I create two Screens. Whilst being in screen 1, i want to change a label in screen two. I highlight the problematic area in my code:
my **test.ky:**
```
#: import ScreenManager kivy.uix.screenmanager.ScreenManager
#: import Screen kivy.uix.screenmanager.ScreenManager
#: import SettingsS... | How about this:
When you press the button on MenuScreen, it sets an attribute on itself containing the text you want to put in the SettingsScreen Label. Then the MenuScreen is assigned an id value in the kv file, which is used to reference this attribute. Example:
**main.py**
```
class MenuScreen(Screen):
text =... |
Why does argv have a 'v' | 27,363,115 | 3 | 2014-12-08T17:07:05Z | 27,363,150 | 7 | 2014-12-08T17:08:23Z | [
"python",
"argv"
] | I am studying Python as a novice programmer. I have seen argv, as in sys.argv used and I believe it is used in other languages as well. What is the significance of the 'v' in 'argv'? What does it stand for and where does the term originate?
I am hoping this will help me understand and remember the use of "argv". | The variables are named `argc` (*argument count*) and `argv` (*argument **vector***) by convention, from C.
note that in Python there's no `sys.argc`. You just use `len(sys.argv)` as pointed [fred-larson](http://stackoverflow.com/users/10077/fred-larson) |
Can't connect to redis using django-redis | 27,364,149 | 4 | 2014-12-08T18:09:02Z | 27,382,430 | 7 | 2014-12-09T15:18:21Z | [
"python",
"django",
"amazon-web-services",
"redis",
"django-redis"
] | I've got a django project using django-redis 3.8.0 to connect to an aws instance of redis. However, I receive `ConnectionError: Error 111 connecting to None:6379. Connection refused.` when trying to connect. If I ssh into my ec2 and use redis-py from the shell, I am able to read and write from the cache just fine, so I... | Ok, figured it out. What I needed to do was prefix my location with `redis://`. This is specific to the django-redis library and how it parses the location url. That explains why when I manually set up a StrictRedis connection using the python redis library I was able to connect. |
Get proxy ip address scrapy using to crawl | 27,364,630 | 3 | 2014-12-08T18:38:10Z | 27,373,901 | 8 | 2014-12-09T07:56:32Z | [
"python",
"proxy",
"web-scraping",
"scrapy",
"web-crawler"
] | I use Tor to crawl web pages.
I started tor and polipo service and added
```
class ProxyMiddleware(object): # overwrite process request def
process_request(self, request, spider):
# Set the location of the proxy
request.meta['proxy'] = "127.0.0.1:8123"
```
Now, how can I make sure that scrapy uses diff... | You can yield the first request to check your public IP, and compare this to the IP you see when you go to <http://checkip.dyndns.org/> without using Tor/VPN. If they are not the same, scrapy is using a different IP obviously.
```
def start_reqests():
yield Request('http://checkip.dyndns.org/', callback=self.check... |
python pandas: plot histogram of dates? | 27,365,467 | 18 | 2014-12-08T19:32:45Z | 29,036,738 | 32 | 2015-03-13T15:57:45Z | [
"python",
"pandas",
"matplotlib",
"time-series"
] | I've taken my Series and coerced it to a datetime column of dtype=`datetime64[ns]` (though only need day resolution...not sure how to change).
```
import pandas as pd
df = pd.read_csv('somefile.csv')
column = df['date']
column = pd.to_datetime(column, coerce=True)
```
but plotting doesn't work:
```
ipdb> column.plot... | Given this df:
```
date
0 2001-08-10
1 2002-08-31
2 2003-08-29
3 2006-06-21
4 2002-03-27
5 2003-07-14
6 2004-06-15
7 2003-08-14
8 2003-07-29
```
and, if it's not already the case:
```
df.date = df.date.astype("datetime64")
```
To show the count of dates by month:
```
df.groupby(df.date.dt.month).count().pl... |
pandas dataframe view vs copy, how do I tell? | 27,367,442 | 5 | 2014-12-08T21:37:59Z | 27,367,693 | 11 | 2014-12-08T21:54:13Z | [
"python",
"pandas"
] | What's the difference between:
pandas `df.loc[:,('col_a','col_b')]`
and
`df.loc[:,['col_a','col_b']]`
The link below doesn't mention the latter, though it works. Do both pull a view? Does the first pull a view and the second pull a copy? Love learning Pandas.
<http://pandas.pydata.org/pandas-docs/stable/indexing.h... | If your DataFrame has a simple column index, then there is no difference.
For example,
```
In [8]: df = pd.DataFrame(np.arange(12).reshape(4,3), columns=list('ABC'))
In [9]: df.loc[:, ['A','B']]
Out[9]:
A B
0 0 1
1 3 4
2 6 7
3 9 10
In [10]: df.loc[:, ('A','B')]
Out[10]:
A B
0 0 1
1 3 4
2... |
Django-Rest-Framework Relationships & Hyperlinked API issues | 27,368,024 | 6 | 2014-12-08T22:17:24Z | 27,368,994 | 12 | 2014-12-08T23:34:48Z | [
"python",
"django",
"django-rest-framework"
] | I am having a go at the django-rest-framework. It was all going fine until I got to the Relationships & Hyperlinked API part of the tutorial. The error I am getting now after messing with it for a bit is:
`ImproperlyConfigured at /api/users/ "^\.(?P<format>[a-z0-9]+)\.(?P<format>[a-z0-9]+)$" is not a valid regular exp... | You are calling `format_suffix_patterns` twice, so Django has no idea how to parse the URL because there are two `format` groups.
You shouldn't need the first call, as the second call takes care of it for you (and allows for `TokenAuthentication` to still have the suffixes). |
Python how can i get the timezone aware date in django | 27,368,950 | 4 | 2014-12-08T23:30:19Z | 27,370,916 | 8 | 2014-12-09T03:22:08Z | [
"python",
"django"
] | I am using delorean for datetime calculation in python django.
<http://delorean.readthedocs.org/en/latest/quickstart.html>
This is what i am using
```
now = Delorean(timezone=settings.TIME_ZONE).datetime
todayDate = now.date()
```
But i get this warning
```
RuntimeWarning: DateTimeField start_time received a naive... | It's not clear whether you're trying to end up with a `date` object or a `datetime` object, as Python doesn't have the concept of a "timezone aware date".
To get a `date` object corresponding to the current time in the current time zone, you'd use:
```
from django.utils.timezone import localtime, now
localtime(now()... |
Auto-import doesn't follow PEP8 | 27,369,138 | 14 | 2014-12-08T23:51:10Z | 27,465,126 | 7 | 2014-12-14T00:31:52Z | [
"python",
"import",
"pycharm",
"pep8"
] | Consider the following code:
```
from bs4 import BeautifulSoup
data = "<test>test text</test>"
soup = BeautifulSoup(data)
print(soup.find(text=re.compile(r'test$')))
```
It is missing an `import re` line and would fail with a `NameError` without it.
Now, I'm trying to use `PyCharm`'s [Auto-Import feature](https://... | You can't. Reason is PyCharm doesn't tell you that you have violated any PEP8 Guidelines if you do that or any import statements at all. One, your PyCharm is outdated (newest version is 4.0.2/4.2) or second, your PyCharm seems to be having a bug, thus giving reason to file a bug report. If you can try to *safely* downl... |
Correct way to write to files? | 27,370,968 | 2 | 2014-12-09T03:28:49Z | 27,370,992 | 7 | 2014-12-09T03:31:46Z | [
"python"
] | I was wondering if there was any difference between doing:
```
var1 = open(filename, 'w').write("Hello world!")
```
and doing:
```
var1 = open(filename, 'w')
var1.write("Hello world!")
var1.close()
```
I find that there is no need (`AttributeError`) if I try to run `close()` after using the first method (all in one... | Using [`with` statement](https://docs.python.org/2/reference/compound_stmts.html#the-with-statement) is preferred way:
```
with open(filename, 'w') as f:
f.write("Hello world!")
```
It will ensure the file object is closed outside the `with` block. |
How do you apply the same action to multiple variables efficiently in Python? | 27,371,237 | 7 | 2014-12-09T04:02:33Z | 27,371,299 | 8 | 2014-12-09T04:10:16Z | [
"python",
"scope"
] | I would like to do something like the following:
```
x = 1
y = 2
z = 3
l = [x,y,z]
for variable in l:
variable += 2
print x
print y
print z
```
Unfortunately, when I print x,y and z after this block, the values have remained at 1,2 and 3 respectively.
I have looked at [this](http://stackoverflow.com/questions... | You cant change x,y,z like this. x,y,z are integers and they are immutable. You need to make new variables.
```
x, y, z = (v + 2 for v in l)
``` |
Why does the escape key have a delay in Python curses? | 27,372,068 | 5 | 2014-12-09T05:29:50Z | 28,020,568 | 7 | 2015-01-19T08:31:56Z | [
"python",
"keyboard",
"python-curses"
] | In the Python `curses` module, I have observed that there is a roughly 1-second delay between pressing the `esc` key and `getch()` returning. This delay does not seem to occur for other keys. Why does this happen and what can I do about it?
Test case:
```
import curses
import time
def get_delay(window, key):
whi... | In order to customize the Esc delay you can set the environment variable ESCDELAY which curses uses to determine the time in milliseconds it waits before it delivers the Escape Key.
In order to define this variable in Python you could for example call the following function prior to your call to `curses.wrapper(main)`... |
Bokeh plotting: 'NoneType' object has no attribute 'line' | 27,372,639 | 4 | 2014-12-09T06:22:09Z | 27,372,938 | 8 | 2014-12-09T06:44:50Z | [
"python",
"plot",
"bokeh"
] | I am new to Bokeh and Python, and I've just installed the latest version of Anaconda.
I am having a basic problem with Bokeh, from this [example](http://bokeh.pydata.org/docs/gallery/correlation.html).
```
from bokeh.plotting import *
f = figure()
f.line(x, y)
AttributeError: 'NoneType' object has no attribute 'line... | The example (and even the [user guide](http://bokeh.pydata.org/docs/user_guide/plotting.html#at-a-glance)) contradict the [documentation](http://bokeh.pydata.org/docs/reference/plotting.html?highlight=figure#bokeh.plotting.figure) for `bokeh.plotting.figure()`, which explicitly says it returns `None`, which explains th... |
Parsing Thread-Index Mail Header with Python | 27,374,077 | 9 | 2014-12-09T08:09:23Z | 27,422,859 | 8 | 2014-12-11T12:25:19Z | [
"python",
"email-headers"
] | Some mail clients, don't set the `References` headers, but `Thread-Index`.
Is there a way to parse this header in Python?
Related: [How does the email header field 'thread-index' work?](http://stackoverflow.com/questions/2278314/how-does-the-email-header-field-thread-index-work)
Mail 1
```
Date: Tue, 2 Dec 2014 08:... | Using the info [here](http://www.solutionary.com/resource-center/blog/2014/04/thread-index-value-analysis/), I was able to put the following together:
```
import struct, datetime
def parse_thread_index(index):
s = index.decode('base64')
guid = struct.unpack('>IHHQ', s[6:22])
guid = '{%08X-%04X-%04X-%04X... |
Python supports `else` in loop. Is there a similar feature in Ruby? | 27,377,964 | 2 | 2014-12-09T11:33:53Z | 27,377,966 | 7 | 2014-12-09T11:33:53Z | [
"python",
"ruby",
"loops",
"if-statement",
"break"
] | In Python, the else block will be executed unless the loop is broke:
```
for person in people:
if is_a_coder(person): break
# ... more code ...
else: # nobreak
print('There is no coder.')
```
How can I do it in Ruby? | Just use `and`:
```
people.each do |person|
break if is_a_coder(person)
# more code
end and puts 'There is no coder.'
``` |
scope of eval function in python | 27,378,660 | 20 | 2014-12-09T12:10:45Z | 27,379,749 | 13 | 2014-12-09T13:10:13Z | [
"python",
"eval",
"python-internals"
] | Consider the following example:
```
i=7
j=8
k=10
def test():
i=1
j=2
k=3
return dict((name,eval(name)) for name in ['i','j','k'])
```
It returns:
```
>>> test()
{'i': 7, 'k': 10, 'j': 8}
```
Why eval does not take into consideration the variables defined inside the function? From the documentation, ... | Generators are [implemented as function scopes](https://docs.python.org/2/reference/executionmodel.html):
> The scope of names defined in a class block is limited to the class
> block; it does not extend to the code blocks of methods â this
> **includes generator expressions since they are implemented using a
> func... |
how to initializeUnorderedBulkOp()? | 27,379,598 | 5 | 2014-12-09T13:02:11Z | 27,380,504 | 9 | 2014-12-09T13:49:31Z | [
"python",
"mongodb",
"pymongo"
] | New to `MongoDB`, I am trying to optimize bulk writes to the database. I do not understand how to initialize the `Bulk()` operations, though.
My understanding is that since the inserts will be done on a collection, this is where (or rather "on what") `initializeUnorderedBulkOp()` should be initialized:
The code below... | In Python (using the `pymongo` module), the method name is not `initializeUnorderedBulkOp` but `initialize_unordered_bulk_op`.
You have to call it, as you correctly guessed, on the collection (in your case, `coll.initialize_unordered_bulk_op()` should work). |
sklearn Kfold acces single fold instead of for loop | 27,380,636 | 5 | 2014-12-09T13:54:35Z | 27,381,010 | 10 | 2014-12-09T14:14:24Z | [
"python",
"scikit-learn",
"cross-validation"
] | After using cross\_validation.KFold(n, n\_folds=folds) I would like to access the indexes for training and testing of single fold, instead of going through all the folds.
So let's take the example code:
```
from sklearn import cross_validation
X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
y = np.array([1, 2, 3, 4])
... | You are on the right track. All you need to do now is:
```
kf = cross_validation.KFold(4, n_folds=2)
mylist = list(kf)
train, test = mylist[0]
```
`kf` is actually a generator, which doesn't compute the train-test split until it is needed. This improves memory usage, as you are not storing items you don't need. Makin... |
Where is the connect() method in PyQt5? | 27,382,053 | 4 | 2014-12-09T15:02:07Z | 27,383,066 | 7 | 2014-12-09T15:46:50Z | [
"python",
"qt",
"pyqt",
"pyqt5"
] | I'm following Mark Summerfield's `Rapid GUI Programming with Python and Qt` which is using PyQt4. I'd prefer to be working with PyQt5, but I have both on my machine. I'm on the second exercise in the book, which is as follows:
```
from __future__ import division
import sys
from math import *
from PyQt5.QtCore import *... | You are using old-style signals and slots which have [not been implemented in PyQt5](http://pyqt.sourceforge.net/Docs/PyQt5/pyqt4_differences.html#old-style-signals-and-slots). Try using [new-style signals and slots](http://pyqt.sourceforge.net/Docs/PyQt4/new_style_signals_slots.html).
```
self.lineedit.returnPressed.... |
Python: ImportError: /usr/local/lib/python2.7/lib-dynload/_io.so: undefined symbol: PyUnicodeUCS2_Replace | 27,383,054 | 7 | 2014-12-09T15:46:25Z | 27,383,515 | 9 | 2014-12-09T16:07:51Z | [
"python",
"python-2.7",
"ubuntu-12.04"
] | I am trying to build a triviol Python script that will grab data from URL and save it onto the server. Concider the below code:
```
#!/usr/bin/python
import pprint
import json
import urllib2
def getUSGS_json():
print "Fetch data from URL"
fileName = 'data/usgsEarthquacks_12Hrs.json'
url = 'http://earthqu... | You have (at least) two different versions of Python installed and you're mixing their files. Make sure that `$PYTHONPATH`, `$PYTHONHOME` and `sys.path` only contain folders for a single Python installation. In your case, one installation is in `/usr/local` and the other is probably in `/usr`.
Also, you can try instal... |
Class variable assigned by expression | 27,383,646 | 3 | 2014-12-09T16:14:20Z | 27,383,681 | 7 | 2014-12-09T16:16:00Z | [
"python",
"class",
"static-members"
] | I have a *class variable* - a list - which values generated dynamically by comprehension, for example:
```
class A:
Field = [2**x for x in range(8)]
. . .
```
My question: is this value calculated once the class `A` was imported or every time I call the `A.Field`? How Python treats such declarations, is there... | The expression is evaluated once, when the `class` statement is being executed (in Python, things like `class` and `def` [are executable statements](http://python-history.blogspot.co.uk/2009/03/how-everything-became-executable.html)).
When you do this, all instance of `A` or subclasses will share the same `Field`.
> ... |
What is the '@=' symbol for in Python? | 27,385,633 | 117 | 2014-12-09T17:59:34Z | 27,385,659 | 131 | 2014-12-09T18:00:48Z | [
"python",
"python-3.x",
"operators",
"matrix-multiplication",
"python-3.5"
] | I know `@` is for decorators, but what is `@=` for in Python? Is it just reservation for some future idea?
This is just one of my many questions while reading tokenizer.py. | From [the](https://docs.python.org/3.5/reference/expressions.html#binary-arithmetic-operations) [documentation](https://docs.python.org/3.5/reference/simple_stmts.html#augmented-assignment-statements):
> The `@` (at) operator is intended to be used for matrix multiplication. No builtin Python types implement this oper... |
What is the '@=' symbol for in Python? | 27,385,633 | 117 | 2014-12-09T17:59:34Z | 30,629,255 | 9 | 2015-06-03T19:44:18Z | [
"python",
"python-3.x",
"operators",
"matrix-multiplication",
"python-3.5"
] | I know `@` is for decorators, but what is `@=` for in Python? Is it just reservation for some future idea?
This is just one of my many questions while reading tokenizer.py. | `@=` and `@` are new operators introduced in Python **3.5** performing **matrix multiplication**. They are meant to clarify the confusion which existed so far with the operator `*` which was used either for element-wise multiplication or matrix multiplication depending on the convention employed in that particular libr... |
How to traverse a tree from sklearn AgglomerativeClustering? | 27,386,641 | 4 | 2014-12-09T18:54:35Z | 27,492,092 | 8 | 2014-12-15T19:58:28Z | [
"python",
"machine-learning",
"scipy",
"scikit-learn",
"hierarchical-clustering"
] | I have a numpy text file array at: <https://github.com/alvations/anythingyouwant/blob/master/WN_food.matrix>
It's a distance matrix between terms and each other, my list of terms are as such: <http://pastebin.com/2xGt7Xjh>
I used the follow code to generate a hierarchical cluster:
```
import numpy as np
from sklearn... | I've answered a similar question for sklearn.cluster.ward\_tree:
[How do you visualize a ward tree from sklearn.cluster.ward\_tree?](http://stackoverflow.com/q/22106425)
AgglomerativeClustering outputs the tree in the same way, in the children\_ attribute. Here's an adaptation of the code in the ward tree question for... |
Django collecstatic boto broken pipe on large file upload | 27,388,716 | 6 | 2014-12-09T20:59:02Z | 31,095,636 | 7 | 2015-06-28T02:41:21Z | [
"python",
"django",
"amazon-s3",
"boto",
"broken-pipe"
] | I am trying to upload the static files to my S3 bucket with collectstatic but i'm getting a broken pipe error with a 700k javascript file, this is the error
```
Copying '/Users/wedonia/work/asociados/server/asociados/apps/panel/static/panel/js/js.min.js'
Traceback (most recent call last):
File "manage.py", l... | Set `AWS_S3_HOST` in `settings.py` to your correct region, e.g. `s3-eu-west-1.amazonaws.com`.
`AWS_S3_HOST = "s3-eu-west-1.amazonaws.com"`
See the latest Amazon [list](https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region) for complete reference.
This [gist](https://gist.github.com/richleland/1324335) i... |
Python def without Indentation | 27,389,475 | 3 | 2014-12-09T21:48:26Z | 27,389,511 | 9 | 2014-12-09T21:51:02Z | [
"python"
] | There are multiple occurrences of following format(note there is no indentation after def lines) in a source file I have:
```
def sendSystemParms2(self, destAddress, subid, state):
raw = sysparms_format2.build(Container(
length = 0x0D,
command = MT_APP_MSG_CMD0))
def method2(parm2):
print parm2
```
and it's working... | You have a file that uses a mixture of tabs and spaces.
Python expands tabs to *eight spaces*, but you are looking at the file in an editor that uses a tabstop size of *four spaces*.
The function bodies use tabs for the indentation, but the `def` lines use 4 spaces instead. As such as far as Python is concerned the m... |
Converting the contents of a CSV file into a dictionary | 27,393,165 | 6 | 2014-12-10T04:05:03Z | 27,393,211 | 8 | 2014-12-10T04:08:57Z | [
"python",
"function",
"csv",
"dictionary"
] | The code I have so far is in a function that basically reads a csv file and prints it's contents:
```
def read(filename):
with open(filename, 'r') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for row in reader:
print(row)
```
Contents of `sailor.csv`:
```
name, mean perform... | using the `csv` standard library and a dictionary comprehension...
```
import csv
with open('sailor.csv') as csvfile:
reader = csv.reader(csvfile)
next(reader)
d = {r[0] : tuple(r[1:-1]) for r in reader}
```
Where `d` will be the dictionary you want. `d[1:-1]` slices the array from the second to the second t... |
ImportError cannot import name BytesIO when import caffe on ubuntu | 27,396,664 | 4 | 2014-12-10T08:49:26Z | 27,396,789 | 7 | 2014-12-10T08:56:52Z | [
"python",
"python-2.7",
"ubuntu",
"scikit-image",
"caffe"
] | I am trying to make [caffe](http://caffe.berkeleyvision.org/) running on my machine equipped with Ubuntu 12.04LTS.
After finishing all the steps on the [Installation page](http://caffe.berkeleyvision.org/installation.html), I trained the LeNet model successfully and tried to use it as the tutorial from [here](http://ra... | You appear to have a package or module named `io` in your Python path that is masking the standard library package. It is imported instead but doesn't have a `BytesIO` object to import.
Try running:
```
python -c 'import io; print io.__file__'
```
in the same location you are running the tutorial and rename or move ... |
Python memory mapping | 27,400,594 | 5 | 2014-12-10T12:06:28Z | 27,403,779 | 11 | 2014-12-10T14:41:10Z | [
"python",
"numpy"
] | I am working with big data and i have matrices with size like 2000x100000, so in order to to work faster i tried using the numpy.memmap to avoid storing in memory this large matrices due to the RAM limitations. The problem is that when i store the same matrix in 2 variables, i.e One with numpy.load and in the other wit... | The NPY format is not simply a dump of the array's data to a file. It includes a header that contains, among other things, the metadata that defines the array's data type and shape. When you use `memmap` directly like you have done, your memory map doesn't take into account the file's header where the metadata is store... |
Detect SQL injections in the source code | 27,402,426 | 10 | 2014-12-10T13:37:38Z | 27,402,708 | 11 | 2014-12-10T13:50:40Z | [
"python",
"sql",
"security",
"sql-injection",
"static-code-analysis"
] | Consider the following code snippet:
```
import MySQLdb
def get_data(id):
db = MySQLdb.connect(db='TEST')
cursor = db.cursor()
cursor.execute("SELECT * FROM TEST WHERE ID = '%s'" % id)
return cursor.fetchall()
print(get_data(1))
```
There is a major problem in the code - it is *vulnerable to SQL in... | There is a tool that tries to solve exactly what the question is about, [`py-find-injection`](https://pypi.python.org/pypi/py-find-injection):
> py\_find\_injection uses various heuristics to look for SQL injection
> vulnerabilities in python source code.
It uses [`ast` module](https://docs.python.org/2/library/ast.h... |
Multiple loops with asyncio | 27,402,796 | 11 | 2014-12-10T13:54:54Z | 27,608,695 | 19 | 2014-12-22T18:50:39Z | [
"python",
"python-3.x",
"asynchronous",
"python-asyncio",
"aiohttp"
] | Is it possible to have multiple loops with asyncio? If the response is yes how can I do that?
My use case is:
\* I extract urls from a list of websites in async
\* For each "sub url list", I would crawl them in async/
Example to extract urls:
```
import asyncio
import aiohttp
from suburls import extractsuburls
@asyn... | You don't need several event loops, just use `yield from gather(*subtasks)` in `extracturls()` coroutine:
```
import asyncio
import aiohttp
from suburls import extractsuburls
@asyncio.coroutine
def extracturls(url):
subtasks = []
response = yield from aiohttp.request('GET', url)
suburl_list = yield from r... |
vim's tab length is different for .py files | 27,403,413 | 4 | 2014-12-10T14:23:57Z | 27,403,643 | 7 | 2014-12-10T14:35:13Z | [
"python",
"vim",
"indentation"
] | In my `~/.vimrc` I set tab to me 2 spaces long
```
set shiftwidth=2
set tabstop=2
```
However when I open a `.py` file, tabs are 4 spaces long. I don't have specific configuration for pyhton files. `~/.vim/after` is empty and searching for `py` doesn't raise any suspect lines.
Have you ever experienced that ? How to... | Itâs defined in the general Python filetype plugin file (`$VIMRUNTIME/ftplugin/python.vim`):
```
" As suggested by PEP8.
setlocal expandtab shiftwidth=4 softtabstop=4 tabstop=8
```
It should be so in order to conform with [PEP 8](https://www.python.org/dev/peps/pep-0008/#indentation).
---
@Carpetsmoker adds:
The... |
How to loop over grouped Pandas dataframe? | 27,405,483 | 10 | 2014-12-10T16:01:40Z | 27,422,749 | 17 | 2014-12-11T12:20:01Z | [
"python",
"pandas"
] | DataFrame:
```
c_os_family_ss c_os_major_is l_customer_id_i
0 Windows 7 90418
1 Windows 7 90418
2 Windows 7 90418
```
Code:
```
print df
for name, group in df.groupby('l_customer_id_i').agg(lambda x: ','.join(x)):
print name... | `df.groupby('l_customer_id_i').agg(lambda x: ','.join(x))` does already return a dataframe, so you cannot loop over the groups anymore.
In general:
* `df.groupby(...)` returns a `GroupBy` object (a DataFrameGroupBy or SeriesGroupBy), and with this, you can iterate through the groups (as explained in the docs [here](h... |
How to install Python bindings originating from an apt package? | 27,406,641 | 7 | 2014-12-10T16:57:47Z | 27,407,027 | 7 | 2014-12-10T17:18:08Z | [
"python",
"linux",
"debian",
"apt",
"zbar"
] | I've got a website hosted at [Heroku](http://heroku.com/), and I now want to use the `python-qrtools` package which uses the [ZBar bar code scanner](http://zbar.sourceforge.net/). On a regular debian (based) I can do a simple:
```
sudo apt-get install python-qrtools
```
According to the command `dpkg-query -L python-... | ```
sudo apt-get install libzbar-dev
sudo pip install zbar
```
It is usually a -dev package that you are missing when you get those kind of errors, an easy way to find the package is `apt-cache search` like below:
```
~$ apt-cache search zbar
libbarcode-zbar-perl - bar code scanner and decoder (Perl bindings)
libzbar... |
Python WebDriver how to print whole page source (html) | 27,411,915 | 4 | 2014-12-10T22:17:54Z | 27,411,948 | 9 | 2014-12-10T22:20:04Z | [
"python",
"selenium-webdriver",
"webdriver"
] | I'm using Python 2.7 with Selenium WebDriver.
My question is how to print whole page source with `print` method.
There is webdriver method `page_source` but it returns WebDriver and I don't know how to convert it to String or just print it in terminal | [`.page_source`](https://selenium-python.readthedocs.org/api.html#selenium.webdriver.remote.webdriver.WebDriver.page_source) on a `webdriver` instance is what you need:
```
>>> from selenium import webdriver
>>> driver = webdriver.Firefox()
>>> driver.get('http://google.com')
>>> print(driver.page_source)
<!DOCTYPE ht... |
Dictionary sorting and removing | 27,414,454 | 3 | 2014-12-11T02:34:45Z | 27,414,489 | 7 | 2014-12-11T02:38:05Z | [
"python",
"sorting",
"dictionary"
] | I'm stuck on dictionaries and sorting in python, I have the following values stored in a dictionary:
```
{'PersonA': 87.0, 'PersonB': 89.0, 'PersonC': 101, 'PersonD': 94, 'PersonE': 112}
```
I want to:
1) Sort these so that they are ordered by highest score first, to lowest score
2) Remove the scores from the dic... | You can do this easily with [`sorted`](https://docs.python.org/3/library/functions.html#sorted):
```
>>> d = {'PersonA': 87.0, 'PersonB': 89.0, 'PersonC': 101, 'PersonD': 94, 'PersonE': 112}
>>> sorted(d, key=d.get, reverse=True)
['PersonE', 'PersonC', 'PersonD', 'PersonB', 'PersonA']
>>>
```
Note that the output is ... |
wtforms+flask today's date as a default value | 27,421,166 | 5 | 2014-12-11T10:55:54Z | 27,424,739 | 7 | 2014-12-11T14:05:01Z | [
"python",
"flask",
"wtforms"
] | I did a small Flask app with a form with two date fields, and this is how I populate the values:
```
class BoringForm(Form):
until = DateTimeField("Until",
format="%Y-%m-%dT%H:%M:%S",
default=datetime.today(),
validators=[validators.Dat... | Just drop the brackets on the callable:
```
class BoringForm(Form):
until = DateTimeField(
"Until", format="%Y-%m-%dT%H:%M:%S",
default=datetime.today, ## Now it will call it everytime.
validators=[validators.DataRequired()]
)
``` |
Python: how to check if an item was added to a set, without 2x (hash, lookup) | 27,427,067 | 5 | 2014-12-11T15:56:35Z | 27,427,447 | 7 | 2014-12-11T16:14:41Z | [
"python",
"python-3.x",
"set"
] | I was wondering if there was a clear/concise way to add something to a set and check if it was added without 2x hashes & lookups.
this is what you might do, but it has 2x hash's of item
```
if item not in some_set: # <-- hash & lookup
some_set.add(item) # <-- hash & lookup, to check the item already is in the... | I don't think there's a built-in way to do this. You could, of course, write your own function:
```
def do_add(s, x):
l = len(s)
s.add(x)
return len(s) != l
s = set()
print do_add(s, 1)
print do_add(s, 2)
print do_add(s, 1)
print do_add(s, 2)
print do_add(s, 4)
```
Or, if you prefer cryptic one-liners:
```
de... |
How can I simply calculate the rolling/moving variance of a timeseries in python? | 27,427,618 | 3 | 2014-12-11T16:22:18Z | 27,427,908 | 8 | 2014-12-11T16:37:13Z | [
"python",
"numpy",
"time-series",
"variance"
] | I have a simple time series and I am struggling to estimate the variance within a moving window. More specifically I cannot figure some issues out relating to the way of implementing a sliding window function. For example with NumPy (and a window e.g. 20):
```
def rolling_window(a, window):
shape = a.shape[:-1] + ... | You should take a look at [pandas](http://pandas.pydata.org). For example:
```
import pandas as pd
import numpy as np
# some sample data
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000)).cumsum()
#plot the time series
ts.plot(style='k--')
# calculate a 60 day rolling mean and plot... |
How does django know which migrations have been run? | 27,430,688 | 11 | 2014-12-11T19:18:56Z | 27,430,820 | 16 | 2014-12-11T19:26:16Z | [
"python",
"django",
"database-migration",
"django-migrations"
] | How does django know whether a migration has been applied yet? It usually gets it right, but when it doesn't I don't ever know where to start troubleshooting. | Django writes a record into the table `django_migrations` consisting of some information like the app the migration belongs to, the name of the migration, and the date it was applied. |
how to get argparse to read arguments from a file with an option rather than prefix | 27,433,316 | 6 | 2014-12-11T22:07:14Z | 27,434,050 | 10 | 2014-12-11T23:01:39Z | [
"python",
"python-2.7",
"argparse"
] | I would like to know how to use python's argparse module to read arguments both from the command line and possibly from text files. I know of argparse's `fromfile_prefix_chars` but that's not exactly what I want. I want the behavior, but I don't want the syntax. I want an interface that looks like this:
```
$ python m... | You can solve this by using a custom [`argparse.Action`](https://docs.python.org/3/library/argparse.html#argparse.Action) that opens the file, parses the file contents and then adds the arguments then.
For example this would be a very simple action:
```
class LoadFromFile (argparse.Action):
def __call__ (self, pa... |
What would cause WordNetCorpusReader to have no attribute LazyCorpusLoader? | 27,433,370 | 7 | 2014-12-11T22:11:11Z | 27,437,149 | 8 | 2014-12-12T05:00:49Z | [
"python",
"multithreading",
"exception",
"attributes",
"nltk"
] | I've got a short function to check whether a word is a real word by comparing it to the WordNet corpus from the Natural Language Toolkit. I'm calling this function from a thread that validates txt files. When I run my code, the first time the function is called it throws a AttributeError with the message
```
"'WordNet... | I have run your code and get the same error. For a working solution, see below. Here is the explanation:
[`LazyCorpusLoader`](http://www.nltk.org/_modules/nltk/corpus/util.html#LazyCorpusLoader) is a proxy object that stands in for a corpus object before the corpus is loaded. (This prevents the NLTK from loading massi... |
What is the difference between jit and autojit in numba? | 27,434,006 | 5 | 2014-12-11T22:58:21Z | 27,464,563 | 7 | 2014-12-13T23:02:17Z | [
"python",
"numba"
] | I'm confused as to what the difference is between `jit` and `autojit`.
I've read this:
<http://numba.pydata.org/numba-doc/0.6/doc/userguide.html>
But can't say I know feel confident in choosing between the two options. Could someone elaborate, ideally with an example.
Thank you | I should've read this which is for the newer version of numba.
<http://numba.pydata.org/numba-doc/0.15.1/tutorial_firststeps.html#compiling-a-function-with-numba-jit-using-an-explicit-function-signature>
2) jit(function) -> dispatcher
```
Same as old autojit. Create a dispatcher function object that
specialize at c... |
django-rest-framework 3.0 create or update in nested serializer | 27,434,593 | 44 | 2014-12-11T23:48:59Z | 27,585,066 | 60 | 2014-12-20T22:48:59Z | [
"python",
"json",
"django",
"serialization",
"django-rest-framework"
] | With **django-rest-framework 3.0** and having these simple models:
```
class Book(models.Model):
title = models.CharField(max_length=50)
class Page(models.Model):
book = models.ForeignKey(Books, related_name='related_book')
text = models.CharField(max_length=500)
```
And given this JSON request:
```
{
... | Firstly, do you want to support creating new book instances, or only updating existing ones?
If you only ever wanted to create new book instances you could do something like this...
```
class PageSerializer(serializers.Serializer):
text = serializers.CharField(max_length=500)
class BookSerializer(serializers.Ser... |
multiprocessing vs threading vs asyncio in Python 3.4 | 27,435,284 | 13 | 2014-12-12T01:03:57Z | 27,436,735 | 17 | 2014-12-12T04:13:02Z | [
"python",
"python-3.x"
] | I found that in Python 3.4 there are few different libraries for multiprocessing/threading: [multiprocessing](https://docs.python.org/3/library/multiprocessing.html) vs [threading](https://docs.python.org/3/library/threading.html) vs [asyncio](https://docs.python.org/3/library/asyncio.html).
But I don't know which one... | They are intended for (slightly) different purposes and/or requirements. CPython (a typical, mainline Python implementation) still has the [global interpreter lock](https://wiki.python.org/moin/GlobalInterpreterLock) so a multi-threaded application (a standard way to implement parallel processing nowadays) is suboptima... |
Pandas Groupby Agg Function Does Not Reduce | 27,439,023 | 6 | 2014-12-12T07:45:03Z | 29,848,546 | 9 | 2015-04-24T13:16:45Z | [
"python",
"pandas"
] | I am using an aggregation function that I have used in my work for a long time now. The idea is that if the Series passed to the function is of length 1 (i.e. the group only has one observation) then that observations is returned. If the length of the Series passed is greater than one, then the observations are returne... | I can't really explain you why, but from my experience `list` in `pandas.DataFrame` don't work all that well.
I usually use `tuple` instead.
That will work:
```
def MakeList(x):
T = tuple(x)
if len(T) > 1:
return T
else:
return T[0]
DF_Agg = DFGrouped.agg({'s.m.v.' : MakeList})
date... |
Python: What's the difference between set.difference and set.difference_update? | 27,439,192 | 3 | 2014-12-12T07:56:56Z | 27,439,300 | 8 | 2014-12-12T08:04:43Z | [
"python",
"set",
"difference"
] | **s.difference(t)** returns a new set with no elements in **t**.
**s.difference\_update(t)** returns an updated set with no elements in **t**.
What's the difference between these two set methods?
Because the difference\_update updates set s, what precautions should be taken to avoid receiving a result of None from th... | **Q.** What's the difference between these two set methods?
**A.** The *update* version subtracts from an existing set, mutating it, and potentially leaving it smaller than it originally was. The *non-update* version produces a new set, leaving the originals unchanged.
**Q.** Because the difference\_update updates se... |
How to fix ImportError: No module named packages.urllib3? | 27,440,060 | 4 | 2014-12-12T08:59:57Z | 27,440,556 | 7 | 2014-12-12T09:30:35Z | [
"python",
"urllib2",
"urllib3",
"twill"
] | I'm running Python 2.7.6 on an Ubuntu machine. When I run `twill-sh` (Twill is a browser used for testing websites) in my Terminal, I'm getting the following:
```
Traceback (most recent call last):
File "dep.py", line 2, in <module>
import twill.commands
File "/usr/local/lib/python2.7/dist-packages/twill/__ini... | There is a difference between the standard `urllib` and `urllib2` and the third-party `urllib3`.
It looks like twill does not install the dependencies so you have to do it yourself. Twill depends on `requests` library which comes with and uses `urllib3` behind the scenes. You also need `lxml` and `cssselect` libraries... |
Django Model MultipleChoice | 27,440,861 | 12 | 2014-12-12T09:47:18Z | 27,442,810 | 15 | 2014-12-12T11:35:01Z | [
"python",
"django",
"django-models"
] | I know there isn't `MultipleChoiceField` for a **Model**, you can only use it on Forms.
Today I face an issue when analyzing a new project related with Multiple Choices.
I would like to have a field like a `CharField` with `choices` with the option of multiple choice.
I solved this issue other times by creating a `C... | You need to think about how you are going to store the data at a database level. This will dictate your solution.
Presumably, you want a single column in a table that is storing multiple values. This will also force you to think about how to will serialize - for example, you can't simply do comma separated if you need... |
Django 1.7 google oauth2 token validation failure | 27,441,567 | 7 | 2014-12-12T10:25:28Z | 28,969,409 | 11 | 2015-03-10T16:44:52Z | [
"python",
"django",
"oauth-2.0",
"google-api",
"oauth2client"
] | I'm trying to get through the process of authenticating a Google token for accessing a user's calendar within a Django application. Although I've followed several indications found on the web, I'm stuck with a 400 error code response to my callback function (Bad Request).
**views.py**
```
# -*- coding: utf-8 -*-
impo... | I have struggled exact the same issue for several hours, and I figured out the solution of which @Ryan Spaulding and @Hans Z answered. It works!
> This is due to the fact Django 1.7 returns a unicode object for the state variable above using request.REQUEST. I was previously using Django 1.6 which used to return a str... |
What is with this change of unpacking behavior from Python2 to Python3 | 27,443,857 | 18 | 2014-12-12T12:37:56Z | 27,444,692 | 8 | 2014-12-12T13:27:34Z | [
"python",
"python-2.7",
"python-3.x",
"difference",
"iterable-unpacking"
] | Yesterday I came across this odd unpacking difference between Python 2 and Python 3, and did not seem to find any explanation after a quick Google search.
**Python 2.7.8**
```
a = 257
b = 257
a is b # False
a, b = 257, 257
a is b # False
```
**Python 3.4.2**
```
a = 257
b = 257
a is b # False
a, b = 257, 257
a is... | I think this is actually by accident, as I can't reproduce the behaviour with Python 3.2.
There is this issue <http://bugs.python.org/issue11244> that introduces a `CONST_STACK` to fix problems with constant tuples with negative numbers not being optimised (look at the patches against `peephole.c`, which contains Pyth... |
What is with this change of unpacking behavior from Python2 to Python3 | 27,443,857 | 18 | 2014-12-12T12:37:56Z | 27,445,745 | 24 | 2014-12-12T14:26:45Z | [
"python",
"python-2.7",
"python-3.x",
"difference",
"iterable-unpacking"
] | Yesterday I came across this odd unpacking difference between Python 2 and Python 3, and did not seem to find any explanation after a quick Google search.
**Python 2.7.8**
```
a = 257
b = 257
a is b # False
a, b = 257, 257
a is b # False
```
**Python 3.4.2**
```
a = 257
b = 257
a is b # False
a, b = 257, 257
a is... | This behaviour is at least in part to do with how the interpreter does constant folding
and how the REPL executes code.
First, remember that CPython first compiles code (to AST and then bytecode). It then evaluates the
bytecode. During compilation, the script looks for objects that are immutable and caches them. It
al... |
Why my Python regular expression pattern run so slowly? | 27,448,200 | 2 | 2014-12-12T16:44:43Z | 27,448,381 | 7 | 2014-12-12T16:54:33Z | [
"python",
"regex"
] | Please see my regular expression pattern code:
```
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import re
print 'Start'
str1 = 'abcdefgasdsdfswossdfasdaef'
m = re.match(r"([A-Za-z\-\s\:\.]+)+(\d+)\w+", str1) # Want to match something like 'Moto 360x'
print m # None is expected.
print 'Done'
```
It takes 49 seconds ... | See [Runaway Regular Expressions: Catastrophic Backtracking](http://www.regular-expressions.info/catastrophic.html).
In brief, if there are extremely many combinations a substring can be split into the parts of the regex, the regex matcher may end up trying them all.
Constructs like `(x+)+` and `x+x+` practically gua... |
How numpy.cov() function is implemented? | 27,448,352 | 3 | 2014-12-12T16:53:03Z | 27,448,417 | 7 | 2014-12-12T16:56:35Z | [
"python",
"numpy",
"scipy"
] | I have my own implementation of the covariance function based on the equation:

```
'''
Calculate the covariance coefficient between two variables.
'''
import numpy as np
X = np.array([171, 184, 210, 198, 166, 167])
Y = np.array([78, 77, 98, 110, 80... | The numpy function has a different normalization to yours as a default setting. Try instead
```
>>> np.cov([X, Y], ddof=0)
array([[ 273.88888889, 190.61111111],
[ 190.61111111, 197.88888889]])
```
References:
* <http://docs.scipy.org/doc/numpy/reference/generated/numpy.cov.html>
* <http://en.wikipedia.org/w... |
python if-elif-else always goes to else | 27,450,320 | 2 | 2014-12-12T18:58:58Z | 27,450,368 | 10 | 2014-12-12T19:02:00Z | [
"python",
"python-3.x"
] | I think there is something wrong with the if-elif-else statement because it always goes to else
```
#initialize total
total=0.0
#ask for inputs
budget=float(input("Plz Enter amount that you budgeted for a month: "))
expense=float(input("Plz Enter 1st expense - to quit enter 0: "))
while expense!=0:
# Add the expense t... | Both `if` and `elif` are doing the same thing
```
if total>budget:
print("You are over-budget by",total-budget)
elif budget<total:
print("You have",budget-total,"to spare")
```
It should be:
```
if total>budget:
print("You are over-budget by",total-budget)
elif budget>total:
print("You have",budget-t... |
How to select all children text but excluding a tag with Scapy's XPath? | 27,451,550 | 3 | 2014-12-12T20:24:28Z | 27,451,861 | 7 | 2014-12-12T20:47:39Z | [
"python",
"html",
"xpath",
"scrapy"
] | I have this html:
```
<div id="content">
<h1>Title 1</h1><br><br>
<h2>Sub-Title 1</h2>
<br><br>
Description 1.<br><br>Description 2.
<br><br>
<h2>Sub-Title 2</h2>
<br><br>
Description 1<br>Description 2<br>
<br><br>
<div class="infobox">
<font style="color:#000000"><b... | Use the `descendant::` axis to find descendant text nodes, and state explicitly that the parent of those text nodes must not be a `div[@class='infobox']` element.
Turning the above into an XPath expression:
```
//div[@id = 'content']/descendant::text()[not(parent::div/@class='infobox')]
```
Then, the result is simil... |
How to flatten a list of tuples into a pythonic list | 27,454,390 | 3 | 2014-12-13T00:55:37Z | 27,454,398 | 7 | 2014-12-13T00:57:25Z | [
"python",
"list",
"flatten"
] | Given the following list of tuples:
```
INPUT = [(1,2),(1,),(1,2,3)]
```
How would I flatten it into a list?
```
OUTPUT ==> [1,2,1,1,2,3]
```
Is there a one-liner to do the above?
Similar: [Flatten list of Tuples in Python](http://stackoverflow.com/questions/15994124/flatten-list-of-tuples-in-python) | You could use a [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions):
```
>>> INPUT = [(1,2),(1,),(1,2,3)]
>>> [y for x in INPUT for y in x]
[1, 2, 1, 1, 2, 3]
>>>
```
[`itertools.chain.from_iterable`](https://docs.python.org/3/library/itertools.html#itertools.chain.from_it... |
Is it unpythonic to use a package imported by another package, or should I import it directly? | 27,455,271 | 6 | 2014-12-13T03:30:06Z | 27,455,593 | 10 | 2014-12-13T04:38:46Z | [
"python",
"import"
] | For instance, I want to use `numpy`'s `isnan` function. I've already loaded the pandas library:
```
import pandas as pd
pd.np.isnan(1) #=> False
```
That works, but is there any disadvantage to that? Or should I write
```
import pandas as pd
import numpy as np
np.isnan(1) #=> False
```
What is good practice? | You should use the second approach for at least four reasons:
1. As @abarnert said in the comments, it follows the official guidelines for Python code as stated in PEP 0008 under [Public and internal interfaces](https://www.python.org/dev/peps/pep-0008/#public-and-internal-interfaces). Specifically, the PEP says:
... |
custom conversion program in python? | 27,457,803 | 2 | 2014-12-13T10:24:19Z | 27,457,832 | 7 | 2014-12-13T10:27:57Z | [
"python",
"converter"
] | I would like to do something like as follows:
```
h=@ , e=( , l=& , o=!
```
So, in the above example, when you type `hello`, it gives back `@(&&!`, and vise versa.
(I would perfer it in Python, but it doesn't have to be.)
I would like to make a small utility of this sort. Can anyone help? Thanks!
**EDIT:** "Basica... | **In Python2**, you could use [str.translate](https://docs.python.org/2/library/stdtypes.html#str.translate):
```
import string
table = string.maketrans(
'helo',
'@(&!',)
In [17]: 'hello'.translate(table)
Out[17]: '@(&&!'
In [18]: 'looleh'.translate(table)
Out[18]: '&!!&(@'
```
Or, you could use `unicode.tr... |
Python regex alternative for join | 27,457,970 | 4 | 2014-12-13T10:45:43Z | 27,457,995 | 9 | 2014-12-13T10:48:48Z | [
"python",
"regex"
] | Suppose I have a string `string = 'abcdefghi'` and I want the output as `'a-b-c-d-e-f-g-h-i'` I can easily use `'-'.join(string)` and get the required output. But what if I want to do the same using regex? How would I do the same using regex?
I am asking because I'm learning to use regex and would like to know how to ... | A solution using look arounds will be
```
>>> import re
>>> str="abcdefghi"
>>> re.sub(r'(?<=\w)(?=\w)', '-', str)
'a-b-c-d-e-f-g-h-i'
```
* `(?<=\w)` asserts that a letter is presceded by the postion
* `(?=\w)` asserts that a letter is followed by the postion
**OR**
```
>>> re.sub(r'(?<=.)(?=.)', '-', str)
'a-b-c-... |
Internals for python tuples | 27,459,663 | 9 | 2014-12-13T14:06:10Z | 27,459,733 | 9 | 2014-12-13T14:14:15Z | [
"python",
"tuples",
"python-internals"
] | ```
>>> a=1
>>> b=1
>>> id(a)
140472563599848
>>> id(b)
140472563599848
>>> x=()
>>> y=()
>>> id(x)
4298207312
>>> id(y)
4298207312
>>> x1=(1)
>>> x2=(1)
>>> id(x1)
140472563599848
>>> id(x2)
140472563599848
```
until this point I was thinking there will be only one copy of immutable object and that will be shared(poi... | ```
>>> x1=(1)
>>> x2=(1)
```
is actually the same as
```
>>> x1=1
>>> x2=1
```
In Python, [smaller numbers are internally cached](http://stackoverflow.com/q/306313/1903116). So they will not be created in the memory multiple times. That is why `id`s of `x1` and `x2` are the same till this point.
An one element tup... |
Django Rest Framework 3.0 to_representation not implemented | 27,462,330 | 4 | 2014-12-13T18:42:20Z | 27,462,974 | 12 | 2014-12-13T19:52:36Z | [
"python",
"django",
"django-rest-framework"
] | I'm upgrading from Django Rest Framework 2.4 to 3.0.1 using Django 1.7.1 and Python 2.7 and can't get past the following error:
```
File "/Users/bjacobel/.virtualenvs/hey/lib/python2.7/site-packages/rest_framework/fields.py", line 375, in to_representation
raise NotImplementedError('to_representation() must be imp... | The issue is in your pagination serializer, as you are using `serializer.Field` which is now `serializer.ReadOnlyField` in Django REST Framework 3.0. This is a subtle change that was made, though it is called out in the release announcement, and it's most noticeable for those who were overriding pagination serializers.... |
How multiarray.correlate2(a, v, mode) is actually implemented? | 27,462,627 | 4 | 2014-12-13T19:14:19Z | 27,463,137 | 7 | 2014-12-13T20:10:16Z | [
"python",
"numpy",
"scipy"
] | On my way to understand how the `Numpy.correlate()` function actually works, I get to it's implementation in pure Python, but what I saw was very disappointing:
```
def correlate(a, v, mode='valid', old_behavior=False):
mode = _mode_from_name(mode)
if old_behavior:
warnings.warn("""Warning.""", Depreca... | The speed of python code can be very poor compared to other languages like c. `numpy` aims to provide highly performant operations on arrays, therefore the developers decided to implement some operations in `c`.
Unfortunately, won't find a python implementation of `correlate` in `numpy`'s code base, but if you are fam... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.