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 |
|---|---|---|---|---|---|---|---|---|---|
Unexpected keyword argument "context" when using appcfg.py | 27,463,779 | 16 | 2014-12-13T21:25:38Z | 27,499,261 | 21 | 2014-12-16T07:04:29Z | [
"python",
"google-app-engine"
] | I tried to update a project on Google App Engine via appcfg.py:
```
C:\> "C:\Program Files (x86)\Google\google_appengine\appcfg.py" update c:\secondApp
```
But I get the following error immediately (top lines are ignored):
```
File "C:\Python27\lib\urllib2.py", line 1240, in https_open
context=self._context)
Typ... | I ran in to the same problem about half an hour ago.. It's actually nothing to do with the urllib2 file, it's got something to do with the authentication. This fixed it for me..
Use **appcfg.py** with **--oauth2** flag. Try this, **appcfg.py --oauth2 update /path/to/your/app**. In the first time you will see the brows... |
Why the performance difference between numpy.zeros and numpy.zeros_like? | 27,464,039 | 12 | 2014-12-13T21:55:38Z | 27,464,738 | 8 | 2014-12-13T23:27:07Z | [
"python",
"numpy"
] | I finally found a performance bottleneck in my code but am confused as to what the reason is. To solve it I changed all my calls of `numpy.zeros_like` to instead use `numpy.zeros`. But why is `zeros_like` sooooo much slower?
For example (note `e-05` on the `zeros` call):
```
>>> timeit.timeit('np.zeros((12488, 7588, ... | My timings in Ipython are (with a simplier timeit interface):
```
In [57]: timeit np.zeros_like(x)
1 loops, best of 3: 420 ms per loop
In [58]: timeit np.zeros((12488, 7588, 3), np.uint8)
100000 loops, best of 3: 15.1 µs per loop
```
When I look at the code with IPython (`np.zeros_like??`) I see:
```
res = empty_l... |
Python coding convention "Wrong continued indentation before block: found by pylint | 27,466,303 | 12 | 2014-12-14T04:17:51Z | 27,473,965 | 21 | 2014-12-14T20:53:22Z | [
"python",
"coding-style",
"pylint"
] | I used pylint to check my python code, and found this convention problem:
```
C:11, 0: Wrong continued indentation before block.
+ this_time <= self.max):
^ | (bad-continuation)
```
I tried to refine for times but the problem is still present, can someone help? Thanks!
```
i... | Pylint doesn't want such continuation to start on the same column as the next indentation block. Also, notice that the message includes a hint on columns that it considers correct. |
What is the most efficient way to subdivide a large list? | 27,466,550 | 3 | 2014-12-14T05:09:45Z | 27,466,588 | 7 | 2014-12-14T05:15:14Z | [
"python",
"numpy"
] | I have a list that contains the `RGBA` color data for a `1024*1024` image, meaning `4,194,304` integers in that list. I need to split it down into `1024` sub-lists with each of those having `1024` sub-lists containing the 4 channels in order to be able to use it for what I need.
I have tried using for loops to append ... | It sounds like you could use [`numpy.reshape`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html#numpy.reshape) to get what you're after. Say you have a list of 12 elements:
```
>>> import numpy as np
>>> x = np.arange(12)
>>> x
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
```
We'll re... |
How to use Gensim doc2vec with pre-trained word vectors? | 27,470,670 | 15 | 2014-12-14T15:13:43Z | 30,337,118 | 11 | 2015-05-19T22:19:44Z | [
"python",
"nlp",
"gensim",
"word2vec"
] | I recently came across the doc2vec addition to Gensim. How can I use pre-trained word vectors (e.g. found in word2vec original website) with doc2vec?
Or is doc2vec getting the word vectors from the same sentences it uses for paragraph-vector training?
Thanks. | Note that the "DBOW" (`dm=0`) training mode doesn't require or even create word-vectors as part of the training. It merely learns document vectors that are good at predicting each word in turn (much like the word2vec skip-gram mode).
(Before gensim 0.12.0, there was the parameter `train_words` mentioned in another com... |
How to use Django's assertJSONEqual to verify response of view returning JsonResponse | 27,472,663 | 8 | 2014-12-14T18:38:18Z | 28,399,670 | 11 | 2015-02-08T21:39:09Z | [
"python",
"django",
"python-3.x",
"django-testing",
"jsonresponse"
] | I'm using Python 3.4 and Django 1.7. I have a view returning [`JsonResponse`](https://docs.djangoproject.com/en/1.7/ref/request-response/#jsonresponse-objects).
```
def add_item_to_collection(request):
#(...)
return JsonResponse({'status':'success'})
```
I want to verify if that view returns correct response ... | It looks like you're working with Python 3 so you'll need to turn `response.content` into a UTF-8 encoded string before passing it to `self.assertJSONEqual`:
```
class AddItemToCollectionTest(TestCase):
def test_success_when_not_added_before(self):
response = self.client.post('/add-item-to-collection')
... |
download only audio from youtube video using youtube-dl in python script | 27,473,526 | 4 | 2014-12-14T20:09:10Z | 27,481,870 | 7 | 2014-12-15T10:22:56Z | [
"python",
"audio",
"youtube",
"youtube-dl"
] | There's a [few](http://stackoverflow.com/questions/14185867/extract-audio-with-youtube-dl-on-windows) [posts](http://stackoverflow.com/questions/15241076/download-only-audio-from-a-youtube-video) on [downloading audio](http://stackoverflow.com/questions/2884588/streaming-audio-youtube) from YouTube using `youtube-dl`, ... | Read on in the [developer instructions](https://github.com/rg3/youtube-dl/blob/master/README.md#embedding-youtube-dl) for an amended example:
```
from __future__ import unicode_literals
import youtube_dl
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
... |
Compare two columns using pandas | 27,474,921 | 7 | 2014-12-14T22:33:45Z | 27,475,029 | 11 | 2014-12-14T22:46:24Z | [
"python",
"pandas"
] | Using this as a starting point
```
a = [['10', '1.2', '4.2'], ['15', '70', '0.03'], ['8', '5', '0']]
df = pd.DataFrame(a, columns=['one', 'two', 'three'])
Out[8]:
one two three
0 10 1.2 4.2
1 15 70 0.03
2 8 5 0
```
I want to use something like an if statement within pandas.
```
if df['one']... | You could use apply() and do something like this
```
df['que'] = df.apply(lambda x : x['one'] if x['one'] >= x['two'] and x['one'] <= x['three'] else "", axis=1)
```
or if you prefer not to use a lambda
```
def que(x):
if x['one'] >= x['two'] and x['one'] <= x['three']:
return x['one']
else:
... |
Compare two columns using pandas | 27,474,921 | 7 | 2014-12-14T22:33:45Z | 27,475,514 | 9 | 2014-12-14T23:51:22Z | [
"python",
"pandas"
] | Using this as a starting point
```
a = [['10', '1.2', '4.2'], ['15', '70', '0.03'], ['8', '5', '0']]
df = pd.DataFrame(a, columns=['one', 'two', 'three'])
Out[8]:
one two three
0 10 1.2 4.2
1 15 70 0.03
2 8 5 0
```
I want to use something like an if statement within pandas.
```
if df['one']... | You could use [np.where](http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html). If `cond` is a boolean array, and `A` and `B` are arrays, then
```
C = np.where(cond, A, B)
```
defines C to be equal to `A` where `cond` is True, and `B` where `cond` is False.
```
import numpy as np
import pandas as pd
... |
Find longest non-breaking common elements in a list | 27,476,771 | 3 | 2014-12-15T03:03:40Z | 27,476,860 | 11 | 2014-12-15T03:16:29Z | [
"python",
"algorithm",
"list"
] | I have this list which contain only Ws and Ss:
```
ls = ['W', 'S', 'S', 'S', 'W', 'W', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'W', 'W', 'W', 'W', 'W', 'W', 'S']
```
What I want to do is to extract the longest nonbreaking "S" in that list?
and return the index of that Ss, returning:
```
['S', 'S', 'S'... | Use [`itertools.groupby`](https://docs.python.org/2/library/itertools.html#itertools.groupby) with [`enumerate`](https://docs.python.org/2/library/functions.html#enumerate) and [`max`](https://docs.python.org/2/library/functions.html#max):
```
>>> from operator import itemgetter
>>> from itertools import groupby
>>> v... |
Why does the asyncio's event loop suppress the KeyboardInterrupt on Windows? | 27,480,967 | 11 | 2014-12-15T09:32:42Z | 27,492,344 | 10 | 2014-12-15T20:13:48Z | [
"python",
"windows",
"python-3.4",
"python-asyncio",
"keyboardinterrupt"
] | I have this really small test program which does nothing apart from a executing an `asyncio` event loop:
```
import asyncio
asyncio.get_event_loop().run_forever()
```
When I run this program on Linux and press `Ctrl`+`C`, the program will terminate correctly with a `KeyboardInterrupt` exception. On Windows pressing `... | This is a bug, sure.
See [issue on python bug-tracker](http://bugs.python.org/issue23057) for the problem solving progress. |
How to add a list under a dictionary? | 27,482,419 | 7 | 2014-12-15T10:52:57Z | 27,482,441 | 8 | 2014-12-15T10:54:30Z | [
"python"
] | I have as input a csv file of the following format:
```
#date,time,process(id),thread(id),cpuusage
201412120327,03:27,process1(10),thread1(12),10
201412120327,03:27,process2(11),thread1(13),10
201412120328,03:28,process1(10),thread2(12),10
201412120328,03:28,process2(10),thread2(13),10
```
I'm trying to create a data... | You can use [`dict.setdefault()`](https://docs.python.org/2/library/stdtypes.html#dict.setdefault) to create an empty list if the key isn't there yet, and append your rows to the list (freshly created or not):
```
threads = {}
for row in csv_f:
# Populate already the list of processes
processes.append(row[2])
... |
Assertion error at: Django-rest-Framework | 27,484,344 | 6 | 2014-12-15T12:40:50Z | 27,484,906 | 18 | 2014-12-15T13:12:58Z | [
"python",
"django",
"postgresql",
"backbone.js",
"django-rest-framework"
] | I am using python 3.4, Django 1.7.1 (the version considered in the book), Postgres 9.3 and my IDE is Eclipse.
I have been studying the book "Lightweight Django - Elman and Lavin" and I have been stuck for days in the chapters 4 and 5, where we are supposed to use the rest framework and backbone.js. See for instance,
... | Read the DRF docs [here](http://www.django-rest-framework.org/api-guide/relations/#the-queryset-argument).
> In version 2.x a serializer class could sometimes automatically determine the queryset argument if a ModelSerializer class was being used.
>
> This behavior is now replaced with always using an explicit queryse... |
Python pandas - filter rows after groupby | 27,488,080 | 7 | 2014-12-15T15:59:19Z | 27,489,248 | 9 | 2014-12-15T17:05:39Z | [
"python",
"pandas",
"filter",
"lambda",
"group-by"
] | For example I have following table:
```
index,A,B
0,0,0
1,0,8
2,0,8
3,1,0
4,1,5
```
After grouping by `A`:
```
0:
index,A,B
0,0,0
1,0,8
2,0,8
1:
index,A,B
3,1,5
4,1,3
```
What I need is to drop rows from each group, where the number in column `B` is less than maximum value from all rows from group's column `B`. We... | You just need to use `apply` on the `groupby` object. I modified your example data to make this a little more clear:
```
import pandas
from io import StringIO
csv = StringIO("""index,A,B
0,1,0.0
1,1,3.0
2,1,6.0
3,2,0.0
4,2,5.0
5,2,7.0""")
df = pandas.read_csv(csv, index_col='index')
groups = df.groupby(by=['A'])
pri... |
scikit-learn: Finding the features that contribute to each KMeans cluster | 27,491,197 | 6 | 2014-12-15T19:01:24Z | 27,588,767 | 7 | 2014-12-21T11:06:08Z | [
"python",
"scikit-learn",
"cluster-analysis",
"k-means"
] | Say you have 10 features you are using to create 3 clusters. Is there a way to see the level of contribution each of the features have for each of the clusters?
What I want to be able to say is that for cluster k1, features 1,4,6 were the primary features where as cluster k2's primary features were 2,5,7.
This is the... | You can use
# [Principle Component Analysis (PCA)](http://en.wikipedia.org/wiki/Principal_component_analysis)
> PCA can be done by eigenvalue decomposition of a data covariance (or correlation) matrix or singular value decomposition of a data matrix, usually after mean centering (and normalizing or using Z-scores) th... |
how to directly import now() from datetime.datetime submodule | 27,491,472 | 6 | 2014-12-15T19:19:17Z | 27,491,556 | 8 | 2014-12-15T19:24:29Z | [
"python",
"datetime",
"import",
"git-submodules"
] | **Background:** I have a few tight loops in a Python program that are called repeatedly, which include the `datetime.datetime.now()` method, as well as the `datetime.datetime.min` and `datetime.datetime.max` attributes. For optimization, I would like to import them into the local namespace, avoiding the repeated, unnec... | `datetime.datetime` is not a submodule. `datetime` is a class within the `datetime` module. `now` is a method of that class. You can't use `from...import...` to import individual methods of a class. You can only use it to import individual modules from a package, or individual objects that exist at the top level of a m... |
Inline conditional between more than 2 values | 27,493,055 | 7 | 2014-12-15T21:01:03Z | 27,493,085 | 8 | 2014-12-15T21:03:06Z | [
"python",
"if-statement"
] | I need to do something like this:
```
if A
function(a)
elif B
function(b)
else
function(c)
```
I found here simpler version:
```
function(a if A else c)
```
Is there version for `elif`? Something like:
```
function(a if A b elif B else c)
```
How should I write this (if this exists)? The code above doesn't loo... | No, no `elif`s. Just chain the `if`s:
```
function(a if A else b if B else c)
```
Which is equivalent to (as [precedence](https://docs.python.org/3/reference/expressions.html#operator-precedence) is left to right):
```
function(a if A else (b if B else c))
```
Obviously this could get complicated (and over the PEP8... |
TypeError: split() takes no keyword arguments | 27,493,703 | 7 | 2014-12-15T21:43:56Z | 27,493,744 | 11 | 2014-12-15T21:46:09Z | [
"python",
"string",
"python-2.7",
"split"
] | I am trying to separate a section of a document into its different components which are separated by ampersands. This is what I have:
```
name,function,range,w,h,k,frac,constraint = str.split(str="&", num=8)
```
Error:
```
TypeError: split() takes no keyword arguments
```
Can someone explain the error to me and als... | The parameters of [`str.split`](https://docs.python.org/2/library/stdtypes.html#str.split) are called `sep` and `maxsplit`:
```
str.split(sep="&", maxsplit=8)
```
But you can only use the parameter names like this in Python 3.x. In Python 2.x, you need to do:
```
str.split("&", 8)
```
which in my opinion is the bes... |
Django Rest API urlsplit error | 27,497,676 | 5 | 2014-12-16T04:45:08Z | 27,534,745 | 8 | 2014-12-17T20:58:43Z | [
"python",
"django",
"rest",
"django-rest-framework"
] | I am trying to set up an API using Django Rest, I've attempted to use the quick start guide, but all I can get is this error:
`'Module_six_moves_urllib_parse' object has no attribute 'urlsplit'`
I can't find any reference to this error on the internet, let alone how to solve it.
Here is my urls file:
```
from djang... | Try upgrading your version of Django. Base 1.6 doesn't have this function, but 1.6.3 does.
<https://docs.djangoproject.com/en/dev/releases/1.6.3/> |
sqlalchemy primary key without auto-increment | 27,498,991 | 10 | 2014-12-16T06:44:35Z | 27,506,856 | 12 | 2014-12-16T14:26:09Z | [
"python",
"database",
"sqlalchemy"
] | I'm trying to establish a table with a layout approximately like the following:
```
class Widget(db.Model):
__tablename__ = 'widgets'
ext_id = db.Column(db.Integer, primary_key=True)
w_code = db.Column(db.String(34), unique=True)
# other traits follow...
```
All field values are provided through an ex... | Set `autoincrement=False` to disable creating a sequence or serial for the primary key.
```
ext_id = db.Column(db.Integer, primary_key=True, autoincrement=False)
``` |
How to match strings even if only they match partially? | 27,504,113 | 3 | 2014-12-16T11:56:10Z | 27,504,270 | 7 | 2014-12-16T12:04:29Z | [
"python",
"regex"
] | I have two lists which I'd like to compare and if there is any match (even if partial) then carry out some action. I've set up this test code:
```
keywords = ['social media','social business','social networking','social marketing','online marketing','social selling',
'social customer experience management','social... | If you want to find out if any item in `keywords` is contained in any item in `metakeywords`, you can do this:
```
if any(key in metakey for key in keywords for metakey in metakeywords):
print 'ok'
``` |
pydata blaze: does it allow parallel processing or not? | 27,505,764 | 7 | 2014-12-16T13:27:36Z | 27,507,041 | 7 | 2014-12-16T14:36:57Z | [
"python",
"numpy",
"pandas",
"multiprocessing",
"blaze"
] | I am looking to parallelise numpy or pandas operations. For this I have been looking into pydata's [blaze](http://blaze.pydata.org/docs/latest/index.html). My understanding was that seemless parallelisation was its major selling point.
Unfortunately I have been unable to find an operation that runs on more than one co... | **Note:** The example below requires the latest version of `blaze`, which you can get via
```
conda install -c blaze blaze
```
You'll also need the latest version of the nascent [`into`](https://github.com/ContinuumIO/into) project. You'll need to install `into` from `master`, which you can do with
```
pip install g... |
How to byte-swap a 32-bit integer in python? | 27,506,474 | 9 | 2014-12-16T14:05:38Z | 27,506,692 | 14 | 2014-12-16T14:16:57Z | [
"python",
"integer",
"endianness"
] | Take this example:
```
i = 0x12345678
print("{:08x}".format(i))
# shows 12345678
i = swap32(i)
print("{:08x}".format(i))
# should print 78563412
```
What would be the `swap32-function()`? Is there a way to byte-swap an `int` in python, ideally with built-in tools? | One method is to use the [`struct`](https://docs.python.org/2/library/struct.html) module:
```
def swap32(i):
return struct.unpack("<I", struct.pack(">I", i))[0]
```
First you pack your integer into a binary format using one endianness, then you unpack it using the other (it doesn't even matter which combination ... |
How to byte-swap a 32-bit integer in python? | 27,506,474 | 9 | 2014-12-16T14:05:38Z | 27,506,699 | 11 | 2014-12-16T14:17:21Z | [
"python",
"integer",
"endianness"
] | Take this example:
```
i = 0x12345678
print("{:08x}".format(i))
# shows 12345678
i = swap32(i)
print("{:08x}".format(i))
# should print 78563412
```
What would be the `swap32-function()`? Is there a way to byte-swap an `int` in python, ideally with built-in tools? | Big endian means the layout of a 32 bit int has the most significant byte first,
e.g. 0x12345678 has the memory layout
```
msb lsb
+------------------+
| 12 | 34 | 56 | 78|
+------------------+
```
while on little endian, the memory layout is
```
lsb msb
+------------------+
| 78 | 56 | 34 |... |
How to pass in a dictionary with additional elements in python? | 27,508,561 | 9 | 2014-12-16T15:52:22Z | 27,508,707 | 7 | 2014-12-16T15:58:25Z | [
"python",
"dictionary"
] | I have a dictionary:
```
big_dict = {1:"1",
2:"2",
...
1000:"1000"}
```
(Note: My dictionary isn't actually numbers to strings)
I am passing this dictionary into a function that calls for it. I use the dictionary often for different functions. However, on occasion I want to send i... | As pointed out by [Veedrac](http://stackoverflow.com/users/1763356/veedrac) in [his answer](http://stackoverflow.com/a/27527606/2642204), this problem has already been solved in Python 3.3+ in the form of the [`ChainMap`](https://docs.python.org/3/library/collections.html#chainmap-objects) class:
```
function_that_use... |
Apply vs transform on a group object | 27,517,425 | 20 | 2014-12-17T02:27:43Z | 27,951,930 | 29 | 2015-01-14T20:34:49Z | [
"python",
"pandas"
] | Consider the following dataframe:
```
A B C D
0 foo one 0.162003 0.087469
1 bar one -1.156319 -1.526272
2 foo two 0.833892 -1.666304
3 bar three -2.026673 -0.322057
4 foo two 0.411452 -0.954371
5 bar two 0.765878 -0.095968
6 foo one -0.654890 0.678091
7 foo t... | As I felt similarly confused with `.transform` operation vs. `.apply` I found a few answers shedding some light on the issue. [This answer](http://stackoverflow.com/a/13854901/4077912) for example was very helpful.
My takeout so far is that `.transform` will work (or deal) with `Series` (columns) **in isolation from e... |
Extract Word from Synset using Wordnet in NLTK 3.0 | 27,517,924 | 3 | 2014-12-17T03:38:38Z | 27,518,073 | 7 | 2014-12-17T03:55:09Z | [
"python",
"nlp",
"nltk",
"wordnet"
] | Some time ago, someone on SO asked [how to retrieve a list of words for a given synset](http://stackoverflow.com/questions/24664250/how-do-i-print-out-just-the-word-itself-in-a-wordnet-synset-using-python-nltk) using NLTK's wordnet wrapper. Here is one of the suggested responses:
```
for synset in wn.synsets('dog'):
... | WordNet works fine in NLTK 3.0. You are just accessing the lemmas (and names) in the wrong way. Try this instead:
```
>>> import nltk
>>> nltk.__version__
'3.0.0'
>>> from nltk.corpus import wordnet as wn
>>> for synset in wn.synsets('dog'):
for lemma in synset.lemmas():
print lemma.name()
dog
domestic_d... |
Why does from __future__ import * raise an error? | 27,518,487 | 7 | 2014-12-17T04:44:15Z | 27,518,569 | 8 | 2014-12-17T04:54:51Z | [
"python",
"python-internals"
] | I used the following import:
```
from __future__ import *
```
but got this error:
```
SyntaxError: future feature * is not defined (<pyshell#0>, line 1)
```
What does this error mean? | While importing `*` from the future module is probably dangerous and should be avoided for the reasons John Zwinck mentions, it was interesting to find out why this doesn't work. It does work differently to the usual Python import syntax which lets you grab everything from the module using `*`.
You can see what's happ... |
hash function in Python 3.3 returns different results between sessions | 27,522,626 | 14 | 2014-12-17T09:48:17Z | 27,522,708 | 22 | 2014-12-17T09:52:11Z | [
"python",
"hash"
] | I've implemented a BloomFilter in python 3.3, and got different results every session. Drilling down this weird behavior got me to the internal hash() function - it returns different hash values for the same string every session.
Example:
```
>>> hash("235")
-310569535015251310
```
----- opening a new python console... | Python uses a random hash seed to prevent attackers from tar-pitting your application by sending you keys designed to collide. See the [original vulnerability disclosure](http://www.ocert.org/advisories/ocert-2011-003.html). By offsetting the hash with a random seed (set once at startup) attackers can no longer predict... |
How to update code from git to a Docker container | 27,529,191 | 15 | 2014-12-17T15:35:43Z | 27,530,136 | 13 | 2014-12-17T16:23:42Z | [
"python",
"git",
"deployment",
"continuous-integration",
"docker"
] | I have a Dockerfile trying to deploy a Django code to a container
```
FROM ubuntu:latest
MAINTAINER { myname }
#RUN echo "deb http://archive.ubuntu.com/ubuntu/ $(lsb_release -sc) main universe" >> /etc/apt/sou$
RUN apt-get update
RUN DEBIAN_FRONTEND=noninteractive apt-get install -y tar git curl dialog wget net-too... | There are a couple of approaches you can use.
1. You can use docker build --no-cache to avoid using the cache of the git clone.
2. The startup command calls git pull. So instead of running `python manage.py`, you'd have something like `CMD cd /repo && git pull && python manage.py` or use a start script if things are m... |
How to do Django JSON Web Token Authentication without forcing the user to re-type their password? | 27,529,690 | 12 | 2014-12-17T15:59:51Z | 27,532,341 | 14 | 2014-12-17T18:29:11Z | [
"python",
"django",
"django-rest-framework",
"jwt"
] | My Django application uses the [Rest Framework JWT](https://github.com/GetBlimp/django-rest-framework-jwt) for authentication. It works great and very elegant.
However, I have a use-case which I am struggling to build. I have already coded up a working solution for the "Forgot Password" workflow. I allow an un-authent... | When working with Django REST Framework JWT, it is typically expected that the user is generating the token on their own. Because you are generating the token on behalf of the user, you can't use any of the standard views to make it work.
You are going to need to generate the token on your own, similar to [how DRF JWT... |
Datetime Timezone conversion using pytz | 27,531,718 | 6 | 2014-12-17T17:48:06Z | 27,592,919 | 8 | 2014-12-21T19:28:12Z | [
"python",
"python-2.7",
"datetime",
"timezone",
"pytz"
] | This is just another post on `pytz`.
There are two functions to convert datetime objects between two timezones. The second functions works for all cases. The first function fails in two cases, (3) and (4). Similar [SO post](http://stackoverflow.com/questions/1379740/pytz-localize-vs-datetime-replace) did not have an i... | I assume you have these questions:
* why does the first function work for UTC timezone?
* why does it fail for `'US/Eastern'` timezone (`DstTzInfo` instance)?
* why does the second function work for all provided examples?
The first function is incorrect because it uses `d.replace(tzinfo=dsttzinfo_instance)` instead o... |
If condition expression not working | 27,531,912 | 2 | 2014-12-17T17:59:37Z | 27,531,945 | 8 | 2014-12-17T18:02:24Z | [
"python",
"if-statement"
] | I have two lists with the following values
```
List1=['6', '9', '16', '19', '0', '3', '6', '0', '6', '12', '18']
List2=['9', '16', '19', '24', '3', '6', '19', '6', '12', '18', '24']
```
Below is loop from my python code, where the if condition does not
work when idk is 60, time=60/60=1k
In this case it should go in... | You are comparing strings and integers. Numbers are always sorted before strings, so `time` is always going to be lower than both `List1[i]` and `List2[i]`.
Use *integers* in your lists instead:
```
List1 = [6, 9, 16, 19, 0, 3, 6, 0, 6, 12, 18]
List2 = [9, 16, 19, 24, 3, 6, 19, 6, 12, 18, 24]
```
Python 2 tries to m... |
Altering the definition of a function without an assignment | 27,532,304 | 4 | 2014-12-17T18:26:54Z | 27,532,551 | 9 | 2014-12-17T18:42:17Z | [
"python"
] | I was given this task:
> Write a one-line expression that transforms an f(x) function into f(x)
> +1. Hint: think about how a local frame binding for saved value of f, can be created **without an assignment**.
>
> Example:
>
> ```
> >>> f = lambda x: x*x
> >>> f(5) 25
> >>> ---your one line expression---
> >>> f(5) 26... | This will work, but it may be cheating:
```
>>> f = lambda x: x*x
>>> f(5)
25
>>> globals().update({'f': (lambda g: lambda x: g(x)+1)(f)})
>>> f(5)
26
>>> f, g = None, f
>>> g(5)
26
``` |
Altering the definition of a function without an assignment | 27,532,304 | 4 | 2014-12-17T18:26:54Z | 27,532,558 | 10 | 2014-12-17T18:42:35Z | [
"python"
] | I was given this task:
> Write a one-line expression that transforms an f(x) function into f(x)
> +1. Hint: think about how a local frame binding for saved value of f, can be created **without an assignment**.
>
> Example:
>
> ```
> >>> f = lambda x: x*x
> >>> f(5) 25
> >>> ---your one line expression---
> >>> f(5) 26... | This is not something that should be used in general, but I suppose you could do this:
```
def f(x, f=f): return f(x) + 1
```
And there's "no (explicit) assignments" since we're just defining a new function name which happens to be the same as the original. |
Python NLTK Using the .generate() function cannot be used | 27,537,023 | 2 | 2014-12-18T00:00:05Z | 27,537,114 | 7 | 2014-12-18T00:09:46Z | [
"python",
"nltk"
] | I shouldn't be getting this error. This has worked before and any tutorial goes over this in the same way and it works. Please help.
```
import nltk
from nltk.book import *
text3.generate()
```
---
```
AttributeError Traceback (most recent call last)
<ipython-input-2-e0816ba18b61> in <mo... | The fourth note in the [first online chapter of the NLTK](http://www.nltk.org/book/ch01.html#searching-text) book says that:
> The generate() method is not available in NLTK 3.0 but will be
> reinstated in a subsequent version |
Why python debugger always get this timeout waiting for response on 113 when using Pycharm? | 27,537,942 | 8 | 2014-12-18T01:45:22Z | 27,539,359 | 7 | 2014-12-18T04:41:37Z | [
"python",
"python-3.x",
"pycharm"
] | 
[Bigger image](http://i.stack.imgur.com/QY4rl.jpg)
Especially I run code perhaps running a little long time(10 mins roughly), and hit the break point.
The python debugger always show me this kind of error "timeout waiting for response on 113"
I circl... | I had a similar thing happen to me a few months ago, it turned out I had a really slow operation within a `__repr__()` for a variable I had on the stack. When PyCharm hits a breakpoint it grabs all of the variables in the current scope and calls `__repr__` on them. Here's an amusement that demonstrates this issue:
```... |
bug of autocorrelation plot in matplotlibâs plt.acorr? | 27,541,290 | 4 | 2014-12-18T07:29:34Z | 27,558,293 | 13 | 2014-12-19T00:55:59Z | [
"python",
"matplotlib",
"pandas",
"statsmodels"
] | I am plotting autocorrelation with python. I used three ways to do it: 1. pandas, 2. matplotlib, 3. statsmodels. I found the graph I got from matplotlib is not consistent with the other two. The code is:
```
from statsmodels.graphics.tsaplots import *
# print out data
print mydata.values
#1. pandas
p=autocorrela... | This is a result of different common definitions between statistics and signal processing. Basically, the signal processing definition assumes that you're going to handle the detrending. The statistical definition assumes that subtracting the mean is all the detrending you'll do, and does it for you.
First off, let's ... |
adjusting x_axis_label or y_axis_label font/font size (Bokeh) | 27,548,153 | 4 | 2014-12-18T13:51:00Z | 27,550,797 | 9 | 2014-12-18T16:03:43Z | [
"python",
"bokeh"
] | Is there a way to adjust `x_axis_label` and `y_axis_label` font/font size in Bokeh (0.70)? I am aware of a way to adjust title font size with the `title_text_font_size` property, with:
```
figure (..., title_text_font_size="12pt")
```
Is there a way to then specify something like:
```
figure (..., x_axis_label_text_... | Figure exposes xaxis and yaxis attributes that you can use for that. In your use case it should be able to use:
```
p.xaxis.axis_label = 'whatever'
p.xaxis.axis_label_text_font_size = "40pt"
``` |
From Voronoi tessellation to Shapely polygons | 27,548,363 | 4 | 2014-12-18T14:03:33Z | 27,703,081 | 10 | 2014-12-30T09:48:27Z | [
"python",
"gis",
"voronoi",
"shapely"
] | from a set of points I built the Voronoi tessellation using [scipy](http://docs.scipy.org/doc/scipy-dev/reference/generated/scipy.spatial.Voronoi.html):
```
from scipy.spatial import Voronoi
vor = Voronoi(points)
```
Now I would like to build a [Polygon in Shapely](http://toblerity.org/shapely/manual.html#polygons) f... | If you're just after a collection of polygons you don't need to pre-order the point to build them.
The `scipy.spatial.Voronoi` object has a `ridge_vertices` attribute containing indices of vertices forming the lines of the Voronoi ridge. If the index is `-1` then the ridge goes to infinity.
First start with some rand... |
Python returns TypeError when method returns string | 27,549,595 | 3 | 2014-12-18T15:06:03Z | 27,549,635 | 9 | 2014-12-18T15:07:49Z | [
"python",
"string",
"class",
"methods",
"return"
] | What's is wrong with the code? Python returns TypeError when method returns class string.
```
class window:
def __init__(self, title='window'):
self.title = title
def title(self, title):
if title:
self.title = title
else:
return self.title
window = window()
wind... | Methods are attributes too. You cannot reuse the name `title` for both a method and an attribute. On your instance, you set `self.title` to a string, and that's not callable:
```
>>> class window:
... def __init__(self, title='window'):
... self.title = title
... def title(self, title):
... if ... |
Can you patch *just* a nested function with closure, or must the whole outer function be repeated? | 27,550,228 | 27 | 2014-12-18T15:35:42Z | 27,550,237 | 30 | 2014-12-18T15:36:02Z | [
"python",
"closures",
"monkeypatching"
] | A 3rd party library we use contains a rather long function that uses a nested function inside it. Our use of that library triggers a bug in that function, and we very much would like to solve that bug.
Unfortunately, the library maintainers are somewhat slow with fixes, but we don't want to have to fork the library. W... | Yes, you can replace an inner function, even if it is using a closure. You'll have to jump through a few hoops though. Please take into account:
1. You need to create the replacement function as a nested function too, to ensure that Python creates the same closure. If the original function has a closure over the names... |
Can you patch *just* a nested function with closure, or must the whole outer function be repeated? | 27,550,228 | 27 | 2014-12-18T15:35:42Z | 27,554,198 | 13 | 2014-12-18T19:27:57Z | [
"python",
"closures",
"monkeypatching"
] | A 3rd party library we use contains a rather long function that uses a nested function inside it. Our use of that library triggers a bug in that function, and we very much would like to solve that bug.
Unfortunately, the library maintainers are somewhat slow with fixes, but we don't want to have to fork the library. W... | Martijn's answer is good, but there is one drawback that would be nice to remove:
> You want to make sure that the replacement inner code object only ever lists those same names as free variables, and does so in the same order.
This isn't a particularly difficult constraint for the normal case, but it isn't pleasant ... |
AWS Elastic Beanstalk logging with python (django) | 27,552,859 | 4 | 2014-12-18T18:00:23Z | 27,851,916 | 7 | 2015-01-09T00:18:03Z | [
"python",
"django",
"amazon-web-services",
"elastic-beanstalk"
] | How do you manage your application logs in AWS elastic beanstalk? I mean you write you application logs to which file?
I'm using the following Logging configuration in my development environment but this doesn't work when I deploy in AWS.
Thanks in advance!
```
DEBUG_LOG_DIR = BASE_DIR + "/django_debug.log"
LOGGING =... | Ok, I figured out a way to do it.
First I connected via ssh to ec2 machine, then I create a folder in /var/log called app\_logs with root user:
```
mkdir /var/log/app_logs
```
After that I did the follow:
```
cd /var/log/
chmod g+s app_logs/
setfacl -d -m g::rw app_logs/
chown wsgi:wsgi app_logs/
```
That ensures ... |
Why doesn't range() return a list? | 27,553,329 | 4 | 2014-12-18T18:31:03Z | 27,553,393 | 13 | 2014-12-18T18:35:02Z | [
"python",
"list",
"range"
] | I ran into some problems when using the `range()` function to create `list`s.
Doing some experimenting, I get the following:
```
>>> isinstance([], list)
True
>>> isinstance(range(10), list)
False
```
Also, reading its documentation:
```
>>> print(range.__doc__)
range(stop) -> range object
range(start, stop[, step... | A `range()` object calculates numbers *on demand*, e.g. when iterated over or when you try to access specific indices:
```
>>> r = range(2, 80, 3)
>>> len(r)
26
>>> r[15]
47
>>> 42 in r
False
>>> r[:10]
range(2, 32, 3)
```
It is a sequence because the object supports membership testing, indexing, slicing and has a le... |
Why does creating a list from a list make it larger? | 27,554,464 | 49 | 2014-12-18T19:44:47Z | 27,554,621 | 11 | 2014-12-18T19:54:56Z | [
"python",
"list",
"python-internals"
] | I'm seeing some inconsistencies when using `sys.getsizeof` on what should be identical lists. (Python 2.7.5)
```
>>> lst = [0,1,2,3,4,5,6,7,8,9]
>>> sys.getsizeof(lst)
76
>>> lst2 = list(lst)
>>> sys.getsizeof(lst2)
104
>>> lst3 = list(lst2)
>>> sys.getsizeof(lst3)
104
>>> sys.getsizeof(lst[:])
76
>>> sys.getsizeof(ls... | When you create a list literal, the size reported is the minimum size needed to hold the data. You can see this because the size jumps up if you append a single element. However, when you use `list` to copy it, it allocates some extra space - it takes a few appends before it reallocates (in your case, I suspect the 8th... |
Why does creating a list from a list make it larger? | 27,554,464 | 49 | 2014-12-18T19:44:47Z | 27,554,624 | 53 | 2014-12-18T19:55:10Z | [
"python",
"list",
"python-internals"
] | I'm seeing some inconsistencies when using `sys.getsizeof` on what should be identical lists. (Python 2.7.5)
```
>>> lst = [0,1,2,3,4,5,6,7,8,9]
>>> sys.getsizeof(lst)
76
>>> lst2 = list(lst)
>>> sys.getsizeof(lst2)
104
>>> lst3 = list(lst2)
>>> sys.getsizeof(lst3)
104
>>> sys.getsizeof(lst[:])
76
>>> sys.getsizeof(ls... | With a list literal, the VM creates the list with a set length. When passing a sequence to the `list()` constructor the elements are added one by one (via [`list.extend()`](https://hg.python.org/releasing/3.4.2/file/10298f4f42dc/Objects/listobject.c#l781)) and as such the list is resized when appropriate. Since the [re... |
Is it better to store big number in list? | 27,554,932 | 20 | 2014-12-18T20:16:29Z | 27,554,970 | 30 | 2014-12-18T20:19:05Z | [
"python"
] | Is it memory efficient to store big number in list? Why does the following happens?
```
>>> A = 100**100
>>> sys.getsizeof(A)
102
>>> B = [100**100]
>>> sys.getsizeof(B)
40
```
Why size of A and B are not equal?
```
>>> C = [1,100**100]
>>> sys.getsizeof(C)
44
>>> D = [1000**1000, 100**100]
>>> sys.getsizeof(D)
44
`... | `sys.getsizeof()` returns the *shallow* size, i.e. the size of the list object itself but not of the objects it contains.
From the [documentation](https://docs.python.org/3/library/sys.html#sys.getsizeof):
> Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of ... |
Is it better to store big number in list? | 27,554,932 | 20 | 2014-12-18T20:16:29Z | 27,554,987 | 8 | 2014-12-18T20:20:07Z | [
"python"
] | Is it memory efficient to store big number in list? Why does the following happens?
```
>>> A = 100**100
>>> sys.getsizeof(A)
102
>>> B = [100**100]
>>> sys.getsizeof(B)
40
```
Why size of A and B are not equal?
```
>>> C = [1,100**100]
>>> sys.getsizeof(C)
44
>>> D = [1000**1000, 100**100]
>>> sys.getsizeof(D)
44
`... | The size of A and B are not equal because you've put B into a list. In this case, A is a long and B is a list type. C and D are the same size because their numerical contents are the same width inside the list container.
Further, `sys.getsizeof()` [returns the size of the topmost object](https://docs.python.org/3/libr... |
How can I add a foreign key constraint on an existing table column via SQLAlchemy? | 27,556,906 | 3 | 2014-12-18T22:33:47Z | 27,557,798 | 7 | 2014-12-18T23:54:57Z | [
"python",
"flask",
"sqlalchemy",
"flask-sqlalchemy",
"alembic"
] | I'm using Flask, Alembic, and PostgreSQL with SQLAlchemy. I have an existing table `location_messages` with a column `campaign_id`. This was created initially in the model with the code
```
campaign_id = db.Column(db.Integer)
```
I want to add a foreign key to it, so I updated the model with
```
campaign_id = db.Col... | The Alembic op you are looking for is [`create_foreign_key`](https://alembic.readthedocs.org/en/latest/ops.html#alembic.operations.Operations.create_foreign_key).
```
op.create_foreign_key(
'fk_location_message_campaign',
'location_messages', 'campaigns',
['campaign_id'], ['id'],
)
```
It is recommended t... |
Why can't the import command be found? | 27,563,854 | 6 | 2014-12-19T10:17:10Z | 27,563,880 | 16 | 2014-12-19T10:18:21Z | [
"python",
"shebang"
] | I am using the `input` function from `fileinput` module to accept script via `pipes` or `input file` Here is the minimum script:
***finput.py***
```
import fileinput
with fileinput.input() as f:
for line in f:
print(line)
```
After making this script executable, I run `ls | ./finput.py` and get `unexpec... | Your need to tell your OS that this is a Python program, otherwise, it's interpreted as a shell script (where the `import` command cannot be found).
Like you identified, this is done by using a shebang line:
```
#!/usr/bin/env python3
```
---
This is only needed if you are going to run your script like this: `./scr... |
What kind of python magic does dir() perform with __getattr__? | 27,567,290 | 12 | 2014-12-19T13:38:21Z | 27,567,367 | 11 | 2014-12-19T13:43:35Z | [
"python",
"python-2.7"
] | The following is in python 2.7 with MySQLdb 1.2.3.
I needed a class wrapper to add some attributes to objects which didn't support it (classes with `__slots__` and/or some class written in C) so I came out with something like this:
```
class Wrapper(object):
def __init__(self, obj):
self._wrapped_obj = o... | There are two deprecated attributes in Python 2, [`object.__members__` and `object.__methods__`](https://docs.python.org/2/library/stdtypes.html#object.__methods__); these were aimed at supporting `dir()` on extension types (C-defined objects):
> `object.__methods__`
> Deprecated since version 2.2: Use the built-in ... |
Anaconda vs miniconda space | 27,567,560 | 12 | 2014-12-19T13:56:24Z | 27,584,745 | 10 | 2014-12-20T22:08:08Z | [
"python",
"anaconda",
"miniconda"
] | On my desktop PC I have anaconda installed, and on my laptop - to save space - I thought i'd install miniconda and be selective about the modules I install. So I installed a handful, numpy, scipy etc. I didn't install anything which isn't part of the default anaconda install, but I just realized my miniconda install is... | You can safely delete the tar.bz2 files. They are only used as a cache. The command `conda clean -t` will clean them automatically. |
populating matplotlib subplots through a loop and a function | 27,569,306 | 2 | 2014-12-19T15:43:27Z | 27,569,541 | 7 | 2014-12-19T15:56:37Z | [
"python",
"matplotlib",
"subplot"
] | I need to draw subplots of a figure through loop iterations; each iteration calls a function defined in another module (=another py file), which draws a pair of subplots. Here is what I tried -- and alas does not work:
1) Before the loop, create a figure with the adequate number of rows, and 2 columns:
```
import ma... | The code you've posted seems largely correct. Other than the indexing, as @hitzg mentioned, nothing you're doing looks terribly out of the ordinary.
However, it doesn't make much sense to return the figure and axes array from your plotting function. (If you need access to the figure object, you can always get it throu... |
Is there an easy way to get all common module extensions? | 27,569,690 | 6 | 2014-12-19T16:05:23Z | 27,569,691 | 7 | 2014-12-19T16:05:23Z | [
"python",
"python-3.x",
"python-import",
"file-extension"
] | I am making a library that deals with Python modules. Without getting into details, I need a list of the common Python module extensions.
Obviously, I want `.py`, but I'd also like to include ones such as `.pyw`, `.pyd`, etc. In other words, I want anything that you can import.
Is there a tool in the standard library... | This functionality can be found in the [`importlib.machinery` module](https://docs.python.org/3/library/importlib.html#module-importlib.machinery). Inside, there are numerous constants which relate to the various Python module extensions:
```
>>> import importlib
>>> importlib.machinery.SOURCE_SUFFIXES
['.py', '.pyw']... |
Difference between these array shapes in numpy | 27,570,756 | 4 | 2014-12-19T17:11:07Z | 27,570,778 | 8 | 2014-12-19T17:12:04Z | [
"python",
"arrays",
"numpy"
] | What is the difference between 2 arrays whose shapes are-
**(442,1)** and **(442,)** ?
Printing both of these produces an identical output, but when I check for equality **==**, I get a 2D vector like this-
```
array([[ True, False, False, ..., False, False, False],
[False, True, False, ..., False, False, Fa... | An array of shape `(442, 1)` is 2-dimensional. It has 442 rows and 1 column.
An array of shape `(442, )` is 1-dimensional and consists of 442 elements.
Note that their reprs should look different too. There is a difference in the number and placement of parenthesis:
```
In [7]: np.array([1,2,3]).shape
Out[7]: (3,)
... |
How do I deploy a Python application to Amazon Elastic Beanstalk from Jenkins? | 27,571,507 | 6 | 2014-12-19T18:04:37Z | 32,468,115 | 11 | 2015-09-08T22:14:30Z | [
"python",
"amazon-web-services",
"jenkins",
"amazon-elastic-beanstalk"
] | I am trying to deploy to Amazon Elastic Beanstalk programmatically from a Jenkins job. On my development machine, this is as simple as:
```
eb deploy $(AWS_ELASTIC_BEANSTALK_ENVIRONMENT)
```
On Jenkins, it should be as simple as configuring the following as a build command:
```
virtualenv env && source env/bin/activ... | To correct the `config profile (eb-cli) could not be found` error, drop the credentials you are using to deploy to EB into `~/.aws/config` for your jenkins user on your jenkins machine. If you built your deployment on a local machine, you should be able to pull the file directly from `~/.aws/config` locally. It will lo... |
Dynamically update attributes of an object that depend on the state of other attributes of same object | 27,571,546 | 4 | 2014-12-19T18:07:18Z | 27,571,588 | 9 | 2014-12-19T18:10:38Z | [
"python"
] | Say I have an class that looks like this:
```
class Test(object):
def __init__(self, a, b):
self.a = a
self.b = b
self.c = self.a + self.b
```
I would like the value of `self.c` to change whenever the value of attributes `self.a` or `self.b` changes for the same instance.
e.g.
```
test1 = Test(... | Yes, there is! It's called properties.
## Read Only Properties
```
class Test(object):
def __init__(self,a,b):
self.a = a
self.b = b
@property
def c(self):
return self.a + self.b
```
With the above code, `c` is now a read-only property of the `Test` class.
## Mutable Properties
... |
Sum values according to an index array | 27,572,958 | 2 | 2014-12-19T19:49:20Z | 27,573,104 | 8 | 2014-12-19T20:00:35Z | [
"python",
"arrays",
"numpy"
] | I have two arrays of the same dimension:
```
a = np.array([ 1, 1, 2, 0, 0, 1])
b = np.array([50, 51, 6, 10, 3, 2])
```
I want to sum the elements of `b` according to the indices in `a`.
The `i`th element of the matrix I want will be the sum of all values `b[j]` such that `a[j]==i`.
So the result should be a 3-dim... | [numpy.bincount](http://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html) has a `weights` parameter which does just what you need:
```
In [36]: np.bincount(a, weights=b)
Out[36]: array([ 13., 103., 6.])
``` |
Why does numpy.zeros takes up little space | 27,574,881 | 5 | 2014-12-19T22:39:06Z | 27,582,592 | 11 | 2014-12-20T17:28:39Z | [
"python",
"arrays",
"numpy",
"cython"
] | I am wondering why numpy.zeros takes up such little space?
```
x = numpy.zeros(200000000)
```
This takes up no memory while,
```
x = numpy.repeat(0,200000000)
```
takes up around 1.5GB. Does numpy.zeros create an array of empty pointers?
If so, is there a way to set the pointer back to empty in the array after chan... | Are you using Linux? Linux has lazy allocation of memory. The underlying calls to `malloc` and `calloc` in numpy always 'succeed'. No memory is actually allocated until the memory is first accessed.
The `zeros` function will use `calloc` which zeros any allocated memory before it is first accessed. Therfore, numpy nee... |
Is it acceptable to have two functions that run each endlessly? | 27,575,354 | 2 | 2014-12-19T23:31:24Z | 27,575,427 | 11 | 2014-12-19T23:39:25Z | [
"python",
"function",
"python-2.7"
] | I built a simple Python program to find if an input is a power of two or not. I have two functions, `power_of_two` and `play_again`. After `power_of_two` runs, `play_again` then runs and reruns `power_of_two`
Here's my code:
```
num = int(raw_input('Input a number (type 0 to quit): '))
def power_of_two(x):
y=1
... | One problem with this approach is that you will eventually run out of stack, because we have a pair of mutually recursive functions. Each call uses up memory in the stack, which is never recovered.
This isn't obvious with an interactive program since it will take a long time to create enough recursive calls, but if we... |
Condense successive 'try' blocks | 27,575,520 | 2 | 2014-12-19T23:50:49Z | 27,575,560 | 7 | 2014-12-19T23:54:42Z | [
"python",
"try-catch"
] | I'm trying to take an existing dict with, say, five possible entries and move its entries into a new dict, 'translating' the keys along the way. The keys of the first dict are structured in a way that the move cannot be done procedurally. There is no guarantee that all of the entries will be present in the first dict.
... | You could do this with a loop:
```
# This is a simple mapping which associates the old keys with the new ones
translations = {'translated_key_1': 'key_one',
'translated_key_2': 'key_two'}
# iterate through the map
for k,v in translations.iteritems():
# you could also replace with try except
if... |
Checking for overlaps in two long lists of items in Python | 27,576,667 | 3 | 2014-12-20T03:34:43Z | 27,576,675 | 7 | 2014-12-20T03:36:10Z | [
"python"
] | I have two lists (list1 and list2) that contain 10 million names of companies. Each list has no duplicates, but some companies appear in both lists. And I want to find what those companies are. I wrote the code below:
```
list_matched = []
for i in range(len(list1)):
for j in range(len(list2)):
if list1[i]... | Use set logic. It is specifically designed for this task.
```
a = set(list1)
b = set(list2)
companies_in_both = a & b
```
(This will produce a `set` as the output. If you need it as a list, just pass the set to `list()`.) |
Appropriate choice of authentication class for python REST API used by web app | 27,578,726 | 5 | 2014-12-20T09:12:41Z | 27,582,256 | 18 | 2014-12-20T16:45:24Z | [
"python",
"django",
"rest",
"authentication",
"django-rest-framework"
] | I would like build a REST API using the Django REST framework. Initially its client would be a web application, but conceivably future clients could include mobile applications.
Unfortunately I'm finding the list of authentication classes listed in the [documentation](http://www.django-rest-framework.org/api-guide/aut... | Django REST Framework gives you the flexibility of having multiple authentication methods. Since I've got some time, and it will be useful to future visitors who have similar questions, I'll outline the benefits of the most common authentication methods.
> Initially its client would be a web application, but conceivab... |
Codility Counting Lesson | 27,581,933 | 4 | 2014-12-20T16:01:53Z | 27,581,991 | 7 | 2014-12-20T16:09:02Z | [
"python",
"arrays",
"algorithm",
"swap"
] | I'm studying Codility Counting Lesson (<https://codility.com/media/train/2-CountingElements.pdf>) and I need help to understand the fastest solution.
I am wondering why the difference is divided by 2 in line 8 `d //= 2`? Shouldn't the difference be sufficient to find the elements that we can swap between the arrays?
... | A swap between `A[i`] and `B[j]` adds `B[j]-A[i]` to `sum(A)` and **subtracts** the same value from `sum(B)`; therefore it affects the difference of the sums by **twice** `B[j]-A[i]`.
As a consequence, it's correct to halve the original difference (after checking it's even -- if it's odd no swap will work!-) to form t... |
Django : Table doesn't exist | 27,583,744 | 10 | 2014-12-20T19:49:36Z | 27,583,836 | 23 | 2014-12-20T20:03:08Z | [
"python",
"mysql",
"django",
"django-models"
] | I dropped some table related to an app. and again tried the syncdb command
```
python manage.py syncdb
```
It shows error like
```
django.db.utils.ProgrammingError: (1146, "Table 'someapp.feed' doesn't exist")
```
models.py
```
class feed(models.Model):
user = models.ForeignKey(User,null=True,blank=True)
f... | 1. drop tables (you already did),
2. comment-out the model in model.py,
3. and ..
if django version >= 1.7:
```
python manage.py makemigrations
python manage.py migrate --fake
```
else
```
python manage.py schemamigration someapp --auto
python manage.py migrate someapp --fake
```
4. comment-in your model in models... |
Deterministic python script behaves in non-deterministic way | 27,583,780 | 12 | 2014-12-20T19:55:23Z | 27,586,945 | 7 | 2014-12-21T05:17:54Z | [
"python",
"windows",
"numpy",
"scipy",
"non-deterministic"
] | I have a script which uses no randomisation that gives me different answers when I run it. I expect the answer to be the same, every time I run the script. The problem appears to only happen for certain (ill-conditioned) input data.
The snippet comes from an algorithm to compute a specific type of controller for a lin... | In general, linalg libraries on Windows give different answers on different runs at machine precision level. I never heard of an explanation why this happens only or mainly on Windows.
If your matrix is ill conditioned, then the inv will be largely numerical noise. On Windows the noise is not always the same in consec... |
Why isn't my Django User Model's Password Hashed? | 27,586,095 | 6 | 2014-12-21T01:59:57Z | 27,586,289 | 10 | 2014-12-21T02:47:58Z | [
"python",
"django",
"django-rest-framework"
] | I am using the Django REST Framework (DRF) to create an endpoint with which I can register new users. However, when I hit the creation endpoint with a POST, the new user is saved via a serializer, but the password is saved in cleartext in the database. The code for my serializer is as follows:
```
from django.contrib.... | The issue is DRF will simply set the field values onto the model. Therefore, the password is set on the password field, and saved in the database. But to properly set a password, you need to call the `set_password()` method, that will do the hashing.
There are several ways to do this, but the best way on rest framewor... |
How to convert datetime.date.today() to UTC time? | 27,587,127 | 4 | 2014-12-21T06:03:05Z | 27,587,542 | 7 | 2014-12-21T07:33:55Z | [
"python",
"pytz"
] | How to make sure the `datetime.date.today()` is converted to UTC time?
This is my code so far:
```
#today : 2014-12-21
today = datetime.date.today()
#1900-01-01 16:00:00+00:00
timeformat = datetime.datetime.strptime('16:00', '%H:%M').replace(tzinfo=pytz.utc)
#combine today and timeformat 2014-12-21 16:00:00
now = ... | Use `utcnow`:
```
today = datetime.datetime.utcnow().date()
``` |
Error loading IPython notebook | 27,588,128 | 10 | 2014-12-21T09:23:11Z | 27,595,587 | 11 | 2014-12-22T01:39:38Z | [
"python",
"ipython",
"ipython-notebook"
] | Once I opened a notebook file with Jupyter (it asks me to convert the file) I never can open it in the standard IPython notebook anymore. I get the following error:
```
Error loading notebook
Bad Request
2014-12-21 04:13:03.203 [NotebookApp] WARNING | Unreadable Notebook: /FunIT experiment.ipynb global name 'NBForma... | This problem has to do with incompatibility of the notebook and your IPython version. In my current version of IPython:
```
ipython --version
2.3.1
```
When I try to open the file (FunIT\ experiment.ipynb):
```
ipython notebook FunIT\ experiment.ipynb
```
I get the following error message
> **Error loading notebo... |
Error loading IPython notebook | 27,588,128 | 10 | 2014-12-21T09:23:11Z | 29,948,141 | 10 | 2015-04-29T15:26:08Z | [
"python",
"ipython",
"ipython-notebook"
] | Once I opened a notebook file with Jupyter (it asks me to convert the file) I never can open it in the standard IPython notebook anymore. I get the following error:
```
Error loading notebook
Bad Request
2014-12-21 04:13:03.203 [NotebookApp] WARNING | Unreadable Notebook: /FunIT experiment.ipynb global name 'NBForma... | Upgrading IPython fixed it for me:
`pip install ipython --upgrade` |
Error loading IPython notebook | 27,588,128 | 10 | 2014-12-21T09:23:11Z | 33,785,181 | 8 | 2015-11-18T16:22:16Z | [
"python",
"ipython",
"ipython-notebook"
] | Once I opened a notebook file with Jupyter (it asks me to convert the file) I never can open it in the standard IPython notebook anymore. I get the following error:
```
Error loading notebook
Bad Request
2014-12-21 04:13:03.203 [NotebookApp] WARNING | Unreadable Notebook: /FunIT experiment.ipynb global name 'NBForma... | This works for me perfectly:
```
pip install jupyter
``` |
How to replace all \W (none letters) with exception of '-' (dash) with regular expression? | 27,588,522 | 8 | 2014-12-21T10:27:51Z | 27,588,531 | 11 | 2014-12-21T10:29:11Z | [
"python",
"regex",
"string"
] | I want replace all `\W` not letters with exception of `-` dash to spaces i.e:
1. `black-white` will give `black-white`
2. `black#white` will give `black white`
I know regular expression very well but I have no idea how to deal with it.
Consider that I want use Unicode so `[a-zA-Z]` is not `\w` like in English only.
... | Using negated character class: (`\W` is equivalent to `[^\w]`; `[^-\w]` => `\W` except `-`)
```
>>> re.sub(r'[^-\w]', ' ', 'black-white')
'black-white'
>>> re.sub(r'[^-\w]', ' ', 'black#white')
'black white'
```
If you use [`regex`](https://pypi.python.org/pypi/regex) package, you can use [nested sets, set operations... |
Running ansible-playbook using Python API | 27,590,039 | 15 | 2014-12-21T14:00:08Z | 27,597,987 | 27 | 2014-12-22T07:03:39Z | [
"python",
"ansible",
"ansible-playbook"
] | How can I run a playbook in python script? What is the equivalent of the following using ansible module in python:
```
ansible -i hosts dbservers -m setup
ansible-playbook -i hosts -vvvv -k site.yml
```
I was looking at their documenation in <http://docs.ansible.com/developing_api.html> but they have very limited exa... | This covered in the [Ansible documentation](http://docs.ansible.com/developing_api.html) under "Python API."
For example, `ansible -i hosts dbservers -m setup` is implemented via:
```
import ansible.runner
runner = ansible.runner.Runner(
module_name='setup',
module_args='',
pattern='dbservers',
)
dbservers_... |
Python: 'ascii' codec can't encode characters | 27,591,015 | 2 | 2014-12-21T15:52:04Z | 27,591,139 | 7 | 2014-12-21T16:05:14Z | [
"python",
"beautifulsoup"
] | I am using the following code to scrape a webpage that contains Japanese characters:
```
import urllib2
import bs4
import time
url = 'http://www.city.sapporo.jp/eisei/tiiki/toban.html'
pagecontent = urllib2.urlopen(url)
soup = bs4.BeautifulSoup(pagecontent.read().decode("utf8"))
print(soup.prettify())
print(soup)
`... | You need to configure your environment locale correctly; once your locale is set, Python will pick it up automatically when printing to a terminal.
Check your locale with the `locale` command:
```
$ locale
LANG="en_GB.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_CTYPE="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_MONETARY="en_US.... |
Additional Serializer Fields in Django REST Framework 3 | 27,591,184 | 7 | 2014-12-21T16:11:02Z | 27,591,289 | 13 | 2014-12-21T16:24:10Z | [
"python",
"django",
"django-rest-framework"
] | **Situation**
I am creating a simple endpoint that allows for the creation of a user. I need a field that is not in my user model (i.e., `confirm_password`). I will run validation that compares this field and another field that is in my model, and then never use the additional field again in the serializer.
**Problem... | You are looking for a write-only field, as I'm assuming you won't want to display the password confirmation in the API. Django REST Framework introduced the `write_only` parameter in the 2.3.x timeline to complement the `read_only` parameter, so the only time validation is run is when an update is being made. The `writ... |
Order of Serializer Validation in Django REST Framework | 27,591,574 | 12 | 2014-12-21T16:52:48Z | 27,591,842 | 32 | 2014-12-21T17:21:54Z | [
"python",
"django",
"validation",
"django-rest-framework"
] | **Situation**
While working with validation in the Django REST Framework's `ModelSerializer`, I have noticed that the `Meta.model` fields are always validated, even when it does not necessarily make sense to do so. Take the following example for a `User` model's serialization:
1. I have an endpoint that creates a use... | Since most likely your `username` field has `unique=True` set, Django REST Framework automatically adds a validator that checks to make sure the new username is unique. You can actually confirm this by doing `repr(serializer())`, which will show you all of the automatically generated fields, which includes the validato... |
NLTK convert tokenized sentence to synset format | 27,591,621 | 5 | 2014-12-21T16:58:07Z | 27,619,941 | 7 | 2014-12-23T11:59:09Z | [
"python",
"nltk",
"sentiment-analysis"
] | I'm looking to get the similarity between a single word and each word in a sentence using NLTK.
NLTK can get the similarity between two specific words as shown below. This method requires that a specific reference to the word is given, in this case it is 'dog.n.01' where dog is a noun and we want to use the first (01)... | You can use a simple conversion function:
```
from nltk.corpus import wordnet as wn
def penn_to_wn(tag):
if tag.startswith('J'):
return wn.ADJ
elif tag.startswith('N'):
return wn.NOUN
elif tag.startswith('R'):
return wn.ADV
elif tag.startswith('V'):
return wn.VERB
r... |
How to produce a "Callable function" | 27,592,161 | 7 | 2014-12-21T18:00:04Z | 27,592,194 | 12 | 2014-12-21T18:03:25Z | [
"python",
"numpy",
"callable"
] | I am currently writing a python definition called f\_from\_data which uses interpolation find point on a line so far I have written this:
```
def f_from_data(xs, ys, x):
xfine = np.linspace(min(xs), max(xs), 10000)
y0 = inter.interp1d(xs, ys, kind = 'linear')
ans = (y0(xfine))[numpy.searchsorted(xfine, x)]... | Using `functools.partial`:
```
from functools import partial
f = partial(f_from_data, [3, 4, 6], [0, 1, 2])
```
`partial` will create a callable object with the first 2 arguments already set. |
Floor or ceiling of a pandas series in python? | 27,592,456 | 5 | 2014-12-21T18:32:24Z | 27,592,508 | 8 | 2014-12-21T18:37:02Z | [
"python",
"pandas",
"series",
"floor",
"ceiling"
] | I have a pandas series `series`. If I want to get the element-wise floor or ceiling, is there a built in method or do I have to write the function and use apply? I ask because the data is big so I appreciate efficiency. Also this question has not been asked with respect to the Pandas package. | You can use NumPy's built in methods to do this: `np.ceil(series)` or `np.floor(series)`.
Both return a Series object (not an array) so the index information is preserved. |
Browser performance tests through selenium | 27,596,229 | 13 | 2014-12-22T03:31:51Z | 27,653,643 | 8 | 2014-12-26T06:33:12Z | [
"python",
"selenium",
"selenium-webdriver",
"protractor",
"performance-testing"
] | We are using `protractor` for testing internal AngularJS applications.
Besides functional tests, we check for performance regressions with the help of [`protractor-perf`](http://npmjs.org/package/protractor-perf) which is based on nodejs [`browser-perf`](https://github.com/axemclion/browser-perf) library. Because, ["P... | There is a possibility to get closer to [what `browser-perf` is doing](https://github.com/axemclion/browser-perf/wiki/Architecture) by collecting the [chrome performance logs](https://sites.google.com/a/chromium.org/chromedriver/logging/performance-log) and analyzing them.
To [get performance logs](http://stackoverflo... |
Flask, Keep getting 404 serving static files using send_static_file | 27,596,297 | 3 | 2014-12-22T03:40:50Z | 27,598,141 | 12 | 2014-12-22T07:16:20Z | [
"python",
"flask"
] | I followed the instructions from [How to serve static files in Flask](http://stackoverflow.com/questions/20646822/how-to-serve-static-files-in-flask), but still couldn't get it working.
Here's my project structure:
```
Project_path
|
+--app
| |
| +--main.py
+--static
|
+--js
|
+--jquery... | Finally got it working. use **[`flask.send_from_directory`](http://flask.pocoo.org/docs/0.10/api/#flask.send_from_directory)**
```
from flask import send_from_directory
@app.route('/js/<path:filename>')
def serve_static(filename):
root_dir = os.path.dirname(os.getcwd())
return send_from_directory(os.path.join... |
Matplotlib Unknown Property "headwidth" and "head_width" | 27,598,976 | 3 | 2014-12-22T08:23:41Z | 27,611,041 | 8 | 2014-12-22T21:58:29Z | [
"python",
"python-2.7",
"matplotlib"
] | I am scratching my head all over for a seemingly easy problem. I am trying to just adjust the headwidth of an arrow in Matplotlib.
Here's a working code:
```
import numpy as np
import matplotlib.pyplot as plt
t = np.linspace(0,2*np.pi,500)
y = np.sin(t)
fig = plt.figure(figsize=(10,5))
ax = fig.add_subplot(111)
ax.p... | When you specify an `arrowstyle` in your arrowprops dict, you get in instance of a FancyArrowPatch rather than YAArrow, which takes different keywords (but, you probably knew that given your attempt to use `head_width`). What is unintuitive from the documentation is that when you specify the arrowstyle, which has defau... |
Why does numpy std() give a different result to matlab std()? | 27,600,207 | 38 | 2014-12-22T09:52:11Z | 27,600,240 | 59 | 2014-12-22T09:54:15Z | [
"python",
"matlab",
"numpy",
"standard-deviation"
] | I try to convert matlab code to numpy and figured out that numpy has a different result with the std function.
in matlab
```
std([1,3,4,6])
ans = 2.0817
```
in numpy
```
np.std([1,3,4,6])
1.8027756377319946
```
Is this normal? And how should I handle this? | The NumPy function [`np.std`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.std.html) takes an optional parameter `ddof`: "Delta Degrees of Freedom". By default, this is `0`. Set it to `1` to get the MATLAB result:
```
>>> np.std([1,3,4,6], ddof=1)
2.0816659994661326
```
To add a little more context, in t... |
Why does numpy std() give a different result to matlab std()? | 27,600,207 | 38 | 2014-12-22T09:52:11Z | 27,601,280 | 34 | 2014-12-22T10:55:03Z | [
"python",
"matlab",
"numpy",
"standard-deviation"
] | I try to convert matlab code to numpy and figured out that numpy has a different result with the std function.
in matlab
```
std([1,3,4,6])
ans = 2.0817
```
in numpy
```
np.std([1,3,4,6])
1.8027756377319946
```
Is this normal? And how should I handle this? | The standard deviation is the square root of the variance. The variance of a random variable `X` is defined as

An estimator for the variance would therefore be

where .until(
EC.presence_of_element_located((By.ID, "myElement"))
```
**Implicit wait :**
```
driver.implicitly_wait(20) # seconds
driver.get("Your-URL")
myElement = driver.find_element_by_id("myElement")
```
You can... |
How to import and use user defined classes in robot framework with python | 27,603,242 | 6 | 2014-12-22T13:00:32Z | 27,604,076 | 7 | 2014-12-22T13:53:40Z | [
"python",
"testing",
"robotframework"
] | Assume I have a class in python:
```
class TestClass(object):
def __init__(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2
def print_args(self):
print arg1, arg2
```
I want to use `robotframework` to implement my tests scenarios. I want to make an instance from above class and ca... | To import the library with arguments, just [add them after the library name](http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#using-library-setting):
```
Library TestClass ARG1 ARG2
```
So the "import" and the instantiation are done in one shot. Now, the thing that can be tricky is to u... |
Why Python returns True when checking if an empty string is in another? | 27,603,885 | 20 | 2014-12-22T13:42:06Z | 27,604,083 | 44 | 2014-12-22T13:53:57Z | [
"python",
"string",
"python-internals"
] | My limited brain cannot understand why this happens:
```
>>> print '' in 'lolsome'
True
```
---
In PHP, a equivalent comparison returns false:
```
var_dump(strpos('', 'lolsome'));
``` | [From the documentation](https://docs.python.org/2/reference/expressions.html#not-in):
> For the Unicode and string types, `x in y` is true if and only if *x* is a substring of *y*. An equivalent test is `y.find(x) != -1`. Note, *x* and *y* need not be the same type; consequently, `u'ab' in 'abc'` will return `True`. ... |
Why Python returns True when checking if an empty string is in another? | 27,603,885 | 20 | 2014-12-22T13:42:06Z | 27,604,169 | 18 | 2014-12-22T13:59:07Z | [
"python",
"string",
"python-internals"
] | My limited brain cannot understand why this happens:
```
>>> print '' in 'lolsome'
True
```
---
In PHP, a equivalent comparison returns false:
```
var_dump(strpos('', 'lolsome'));
``` | Quoting from the [PHP's `strpos` documentation](http://php.net/manual/en/function.strpos.php),
> ```
> mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
> ```
>
> Find the numeric position of the **first occurrence of `needle`** in the **`haystack` string**.
So what you have actually tried is sim... |
OSError: [Errno 8] Exec format error | 27,606,653 | 6 | 2014-12-22T16:34:17Z | 27,608,363 | 26 | 2014-12-22T18:26:35Z | [
"python",
"subprocess"
] | I am having hard time parsing the arguments to subprocess.Popen. I am trying to execute a script on my Unix server. The script syntax when running on shell prompt is as follows:
`/usr/local/bin/script hostname = <hostname> -p LONGLIST`. No matter how I try, the script is not running inside subprocess.Popen
The space b... | `OSError: [Errno 8] Exec format error` can happen if there is no shebang line at the top of the shell script and you are trying to execute the script directly. Here's an example that reproduces the issue:
```
>>> with open('a','w') as f: f.write('exit 0') # create the script
...
>>> import os
>>> os.chmod('a', 0b1111... |
"TypeError": 'list' object is not callable flask | 27,608,987 | 7 | 2014-12-22T19:12:46Z | 27,609,429 | 10 | 2014-12-22T19:46:22Z | [
"python",
"flask"
] | I am trying to show the list of connected devices in browser using flask. I enabled flask on port 8000:
in server.py:
```
@server.route('/devices',methods = ['GET'])
def status():
return app.stat()
if __name__ == '__main__':
app.run()
```
in app.py:
```
def stat():
return(glob.glob("/dev/tty57") +... | The problem is that your endpoint is returning a list. Flask only likes certain return types. The two that are probably the most common are
* a `Response` object
* a `str` (along with `unicode` in Python 2.x)
You can also return any callable, such as a function.
If you want to return a list of devices you have a cou... |
Django Management Command Argument | 27,611,468 | 8 | 2014-12-22T22:35:21Z | 34,992,659 | 8 | 2016-01-25T12:29:54Z | [
"python",
"django"
] | I need to pass in an integer argument to a base command in Django. For instance if my code was
```
from django.core.management import BaseCommand
class Command(BaseCommand):
def handle(self, *args, **options, number_argument):
square = number_argument ** 2
print square
```
I would want to say pyt... | Add this function to your Command class:
```
def add_arguments(self, parser):
parser.add_argument('my_int_argument', type=int)
```
You can then use your option in the code, like this:
```
def handle(self, *args, **options):
my_int_argument = options['my_int_argument']
```
The benefit of doing it like this; ... |
Restrict static file access to logged in users | 27,611,671 | 5 | 2014-12-22T22:55:01Z | 27,611,882 | 10 | 2014-12-22T23:16:23Z | [
"python",
"nginx",
"flask"
] | I want to restrict files to be available to logged in users, but otherwise return a 403 error or similar. For example a user should be able to view/download `/static/data/example.csv` only if they're logged in.
I know how to control the actual displaying of the files using Flask-Login if they're not logged in, but not... | Flask [adds a static route](https://github.com/mitsuhiko/flask/blob/master/flask/app.py#L521) to serve static files. When you're in production, you typically "short circuit" this route so that Nginx serves the files before the request ever gets to your app. Instead of adding this "short circuit", leave it out and let F... |
Case insensitive argparse choices | 27,616,778 | 11 | 2014-12-23T08:39:09Z | 27,616,814 | 17 | 2014-12-23T08:42:36Z | [
"python",
"argparse",
"case-insensitive"
] | Is it possible to check [argparse choices](https://docs.python.org/3/library/argparse.html#choices) in case-insensitive manner?
```
import argparse
choices = ["win64", "win32"]
parser = argparse.ArgumentParser()
parser.add_argument("-p", choices=choices)
print(parser.parse_args(["-p", "Win32"]))
```
results in:
```
... | Transform the argument into lowercase by using
```
type = lambda s : s.lower()
```
for the `-p` switch.
As pointed out by [chepner](https://stackoverflow.com/users/1126841/chepner) in the comments, since `str.lower` is already an appropriate function, the lambda wrapper is not necessarily needed and you could instea... |
httplib.BadStatusLine: '' | 27,619,258 | 7 | 2014-12-23T11:16:13Z | 27,620,850 | 11 | 2014-12-23T12:56:20Z | [
"python",
"selenium",
"scrapy"
] | As always, I frequently have issues, and I have thoroughly searched for an answer to the current one but find myself at a loss. Here are some of the places I have searched:
- [How to fix httplib.BadStatusLine exception?](http://stackoverflow.com/questions/10708828/how-to-fix-httplib-badstatusline-exception)
- [Python h... | Based on [Python Doc](https://docs.python.org/2/library/httplib.html#httplib.HTTPConnection), `httplib.BadStatusLine` raised if a server responds with a HTTP status code that we donât understand.
You can try to pass this exception. You should not close your driver if you are going to call more than one url.
Try this... |
Weighted Gaussian kernel density estimation in `python` | 27,623,919 | 4 | 2014-12-23T16:06:37Z | 27,623,920 | 8 | 2014-12-23T16:06:37Z | [
"python",
"statistics",
"scipy",
"kernel-density"
] | It is currently not possible to use `scipy.stats.gaussian_kde` to estimate the density of a random variable based on [weighted samples](http://en.wikipedia.org/wiki/Sampling_%28statistics%29#Survey_weights). What methods are available to estimate densities of continuous random variables based on weighted samples? | Neither [`sklearn.neighbors.KernelDensity`](http://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KernelDensity.html#sklearn.neighbors.KernelDensity) nor [`statsmodels.nonparametric`](http://statsmodels.sourceforge.net/stable/nonparametric.html) seem to support weighted samples. I modified `scipy.stats.gau... |
Launch a completely independent process | 27,624,850 | 6 | 2014-12-23T17:03:44Z | 27,625,288 | 7 | 2014-12-23T17:34:34Z | [
"python",
"python-2.7",
"subprocess",
"fork",
"child-process"
] | I wanted to initiate a process from my python script `(main.py)`, specifically I want to run the below command
```
`nohup python ./myfile.py &`
```
and this file `myfile.py` should even after my main python script exits.
Additionally I wish to get the `pid` of the new process.
I tried `os.spawnl*`, `os.exec*` & `su... | You open your long-running process and *keep a pipe to it*. So you expect to talk to it. When yor launcher script exits, you can no longer talk to it. ~~The long-running process receives a `SIGPIPE` and exits.~~
The following just worked for me (Linux, Python 2.7).
Create a long-running executable:
```
$ echo "sleep... |
Counting consecutive positive value in Python array | 27,626,542 | 4 | 2014-12-23T19:09:58Z | 27,626,699 | 16 | 2014-12-23T19:22:53Z | [
"python",
"pandas",
"statistics"
] | I'm trying to count consecutive up days in equity return data - so if a positive day is 1 and a negative is 0, a list `y=[0,0,1,1,1,0,0,1,0,1,1]` should return `z=[0,0,1,2,3,0,0,1,0,1,2]`.
I've come to a solution which is neat in terms of number of lines of code, but is *very* slow:
```
import pandas
y=pandas.Series(... | This may seem a little magical, but actually uses some common idioms: since `pandas` doesn't yet have nice native support for a contiguous `groupby`, you often find yourself needing something like this.
```
>>> y * (y.groupby((y != y.shift()).cumsum()).cumcount() + 1)
0 0
1 0
2 1
3 2
4 3
5 0
6 ... |
Python selenium browser driver.back() | 27,626,783 | 5 | 2014-12-23T19:28:55Z | 27,628,410 | 15 | 2014-12-23T21:40:31Z | [
"python",
"selenium"
] | I have created a little screen scraper and everything seems to be working great, the information is being pulled and saved in a db the only problem i am having is sometimes python doesn't use the driver.back() so it then trys to get the information on the wrong page and crashes, i have tried adding a time.sleep(5) but ... | This is the best solution. The back() and forward() methods aren't guaranteed to work.
```
driver.execute_script("window.history.go(-1)")
```
The JavaScript passed in accesses the pages Dom to navigate to the previous url. I hope that this solves your problem. |
Uploading and Downloading Files with Flask | 27,628,053 | 10 | 2014-12-23T21:12:04Z | 27,638,470 | 13 | 2014-12-24T14:34:20Z | [
"python",
"python-2.7",
"file-upload",
"flask",
"pythonanywhere"
] | I'm trying to write a really simply webapp with PythonAnywhere and Flask that has lets the user upload a text file, generates a csv file, then lets the user download the csv file. It doesn't have to be fancy, it only has to work. I have already written the program for generating the csv from a txt file on the drive.
R... | PythonAnywhere dev here. This is a good question about Flask and web development in general rather than specific to our system, so I'll try to give a generic answer without anything specific to us :-)
There are a few things that I'd need to know to give a definitive answer to your question, so I'll start by listing th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.