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 |
|---|---|---|---|---|---|---|---|---|---|
"ÅÃÃ" is 6 characters long | 25,705,853 | 2 | 2014-09-06T23:56:54Z | 25,705,884 | 8 | 2014-09-07T00:01:05Z | [
"python",
"python-2.7",
"utf-8"
] | Here is the script:
```
#!/usr/bin/python
#coding: utf-8
str='ÅÃÃ'
a = len(str)
print str
print a
```
the output is:
```
ÅÃÃ
6
```
first question is: how to get it to show me 6 characters that it claims..
and second question is..
is it possible to ensure python can see these as "1" character for each charac... | In Python2, a `str` is a sequence of bytes. This string is composed of 6 bytes:
```
In [136]: text = 'ÅÃÃ'
In [137]: list(text)
Out[137]: ['\xc5', '\x9e', '\xc3', '\x9c', '\xc3', '\x96']
```
If you decode the `str` to make a `unicode`:
```
In [138]: unitext = text.decode('utf-8')
```
Then the `unitext` is compo... |
JSON ValueError: Expecting property name: line 1 column 2 (char 1) | 25,707,558 | 13 | 2014-09-07T06:07:00Z | 25,715,580 | 28 | 2014-09-07T23:08:06Z | [
"python",
"json",
"pymongo"
] | I am having trouble using json.loads to convert to a dict object and I can't figure out what I'm doing wrong.The exact error I get running this is
```
ValueError: Expecting property name: line 1 column 2 (char 1)
```
Here is my code:
```
__author__ = 'xxdpavelxx'
from kafka.client import KafkaClient
from kafka.consu... | `json.loads` will load a json object into a python `dict`, `json.dumps` will dump a python `dict` to a json object, for example:
```
>>> json_string = '{"favorited": false, "contributors": null}'
'{"favorited": false, "contributors": null}'
>>> value = json.loads(json_string)
{u'favorited': False, u'contributors': Non... |
JSON ValueError: Expecting property name: line 1 column 2 (char 1) | 25,707,558 | 13 | 2014-09-07T06:07:00Z | 36,599,122 | 16 | 2016-04-13T12:56:51Z | [
"python",
"json",
"pymongo"
] | I am having trouble using json.loads to convert to a dict object and I can't figure out what I'm doing wrong.The exact error I get running this is
```
ValueError: Expecting property name: line 1 column 2 (char 1)
```
Here is my code:
```
__author__ = 'xxdpavelxx'
from kafka.client import KafkaClient
from kafka.consu... | I encountered another problem which return same error.
I use a json string with **single quotes** :
```
{
'property': 1
}
```
But **json.loads accepts only double quotes for json properties** :
```
{
"property": 1
}
```
I hope it will help |
socket.error: [Errno 13] Permission denied when creating a fake email server | 25,709,716 | 3 | 2014-09-07T11:33:45Z | 25,709,886 | 12 | 2014-09-07T11:55:33Z | [
"python",
"sockets",
"flask"
] | I'm trying to create a fake email server as part of a Flask app to print out errors on the console by using the following script. However, it throws an error. How can I fix this?
```
dpadmins-MacBook:microblog presentation$ python -m smtpd -n -c DebuggingServer localhost:25
Traceback (most recent call last):
File "... | In unix (Linux, Mac OS X, BSD etc) systems, ports less than 1024 can not be bound to by normal users, only the root user can bind to those ports.
To get around this, you could run your python application as root (by using sudo), however this is not preferable. Is it possible instead to get your Flask application to ta... |
How to avoid "RuntimeWarning: invalid value encountered in divide" in NumPy? | 25,709,818 | 12 | 2014-09-07T11:45:09Z | 25,709,850 | 18 | 2014-09-07T11:50:17Z | [
"python",
"numpy"
] | I am trying to avoid the warning `RuntimeWarning: invalid value encountered in divide` in NumPy.
I thought I could do:
```
import numpy as np
A=np.array([0.0])
print A.dtype
with np.errstate(divide='ignore'):
B=A/A
print B
```
but this gives:
```
float64
./t.py:9: RuntimeWarning: invalid value encountered in d... | You need to set `invalid` rather than `divide`:
```
with np.errstate(invalid='ignore'):
^^^^^^^
``` |
python equivalent of R table | 25,710,875 | 4 | 2014-09-07T13:47:11Z | 25,710,906 | 7 | 2014-09-07T13:51:21Z | [
"python",
"table",
"frequency"
] | I have a list
```
[[12, 6], [12, 0], [0, 6], [12, 0], [12, 0], [6, 0], [12, 6], [0, 6], [12, 0], [0, 6], [0, 6], [12, 0], [0, 6], [6, 0], [6, 0], [12, 0], [6, 0], [12, 0], [12, 0], [0, 6], [0, 6], [12, 6], [6, 0], [6, 0], [12, 6], [12, 0], [12, 0], [0, 6], [6, 0], [12, 6], [12, 6], [12, 6], [12, 0], [12, 0], [12, 0], ... | A `Counter` object from the `collections` library will function like that.
```
from collections import Counter
x = [[12, 6], [12, 0], [0, 6], [12, 0], [12, 0], [6, 0], [12, 6], [0, 6], [12, 0], [0, 6], [0, 6], [12, 0], [0, 6], [6, 0], [6, 0], [12, 0], [6, 0], [12, 0], [12, 0], [0, 6], [0, 6], [12, 6], [6, 0], [6, 0],... |
python equivalent of R table | 25,710,875 | 4 | 2014-09-07T13:47:11Z | 25,710,986 | 12 | 2014-09-07T14:01:26Z | [
"python",
"table",
"frequency"
] | I have a list
```
[[12, 6], [12, 0], [0, 6], [12, 0], [12, 0], [6, 0], [12, 6], [0, 6], [12, 0], [0, 6], [0, 6], [12, 0], [0, 6], [6, 0], [6, 0], [12, 0], [6, 0], [12, 0], [12, 0], [0, 6], [0, 6], [12, 6], [6, 0], [6, 0], [12, 6], [12, 0], [12, 0], [0, 6], [6, 0], [12, 6], [12, 6], [12, 6], [12, 0], [12, 0], [12, 0], ... | ```
import pandas
x = [[12, 6], [12, 0], [0, 6], [12, 0], [12, 0], [6, 0], [12, 6], [0, 6], [12, 0], [0, 6], [0, 6], [12, 0], [0, 6], [6, 0], [6, 0], [12, 0], [6, 0], [12, 0], [12, 0], [0, 6], [0, 6], [12, 6], [6, 0], [6, 0], [12, 6], [12, 0], [12, 0], [0, 6], [6, 0], [12, 6], [12, 6], [12, 6], [12, 0], [12, 0], [12, 0... |
pip install requests exception and pip install beautifulsoup4 exception | 25,711,420 | 9 | 2014-09-07T14:45:37Z | 25,711,926 | 7 | 2014-09-07T15:34:36Z | [
"python",
"exception",
"beautifulsoup",
"pip",
"python-requests"
] | I have installed Python 3.4.1 on Windows 7, pip included and during install have selected add python.exe to PATH.
When running pip install requests I get:
```
C:\Python34>pip install requests
Requirement already satisfied (use --upgrade to upgrade): requests in c:\python3
4\lib\site-packages
Cleaning up...
Exce... | All the permission exceptions means that your command prompt has no administrator rights.
Run the command prompt as Administrator (search for cmd in start menu, right click, Run as Administrator). If that doesn't work, try reinstalling pip; the file permissions things might have been screwed up somehow. |
Setting path to firefox binary on windows with selenium webdriver | 25,713,824 | 8 | 2014-09-07T19:13:08Z | 25,715,497 | 9 | 2014-09-07T22:56:01Z | [
"python",
"firefox",
"selenium",
"selenium-webdriver"
] | I am trying to build a utility function to output beautiful soup code to a browser I have the following code:
```
def bs4_to_browser(data):
from selenium import webdriver
driver = webdriver.Firefox(path="F:\FirefoxPortable\Firefox.exe")
driver.get("about:blank")
data = '<h1>test</h1>' # supposed to... | To set the custom path to `Firefox` you need to use `FirefoxBinary`:
```
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
binary = FirefoxBinary('F:\FirefoxPortable\Firefox.exe')
driver = webdriver.Firefox(firefox_binary=binary)
```
Or, alternatively, add `F:\FirefoxPortable` to the `PATH` environ... |
python: Interplay between lib/site-packages/site.py and lib/site.py | 25,715,039 | 6 | 2014-09-07T21:41:16Z | 26,035,458 | 7 | 2014-09-25T09:47:29Z | [
"python",
"linux",
"python-2.7",
"sys.path"
] | Due to a specific [problem](http://stackoverflow.com/questions/25710724/prevent-python-from-loading-a-pth-file) which I managed to solve, I spent most of today figuring out how site.py(s) work. There is a point which I don't understand.
As far as I understand, when python is loaded, first `lib/python2.7/site-packages/... | The `lib/python2.7/site-packages/site.py` file is **not normally loaded**. That's because it is `lib/python2.7/site.py`'s job to add the `site-packages` paths to `sys.path` to begin with, and the `site.py` in `site-packages` is simply not visible. If you have a `site.py` in `site-packages` then that is an error, there ... |
Why isn't Odoo picking up my module? | 25,722,833 | 7 | 2014-09-08T11:04:39Z | 25,723,976 | 19 | 2014-09-08T12:11:28Z | [
"python",
"openerp",
"openerp-8"
] | Iâve added a module directory to /home/deploy/host-addons. Starting up Odoo definitely knows about it:
> 2014-09-08 10:50:08,533 5198 INFO ? openerp: addons
> paths:['/home/deploy/odoo/local/data/addons/8.0',
> u'/home/deploy/odoo/build/8.0/openerp/addons',
> u'/home/deploy/odoo/build/8.0/addons', u'/home/deploy/hos... | Restarting the server or just clicking on update doesn't update the list of installable modules. You have to go to Settings -> Users -> Enable Technical Features. Then there will be a new option that says "Update Modules List" in the Module category to the left on the settings page.
 class:
> Each FluentWait instance defines the maximum amount of time to wait
> for a condition, as well as the frequency with which to check the
> condit... | I believe you can do this with Python, however it isn't packaged as simply as a FluentWait class. Some of this was covered in the documentation you provided by not extensively.
The WebDriverWait class has optional arguments for timeout, poll\_frequency, and ignored\_exceptions. So you could supply it there. Then combi... |
Django 1.7 - updating base_site.html not working | 25,727,687 | 12 | 2014-09-08T15:24:20Z | 25,733,423 | 13 | 2014-09-08T21:30:08Z | [
"python",
"django",
"django-templates",
"django-admin"
] | I'm following the tutorial for django 1.7 (again). I cannot get the admin site to update. I've followed this:
[Django: Overrideing base\_site.html](http://stackoverflow.com/questions/21571237/django-overrideing-base-site-html)
this:
[Custom base\_site.html not working in Django](http://stackoverflow.com/questions/17... | To start off, I am not sure if it was a copy/paste issue or if you actually have TEMPLATE\_DIRS commented out. It will need to be a non-commented line:
```
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
```
As for the real problem, you have to replace more of your template to make it work because site\_title i... |
Understanding len function with iterators | 25,728,092 | 3 | 2014-09-08T15:45:38Z | 25,731,567 | 7 | 2014-09-08T19:19:47Z | [
"python",
"python-3.x"
] | Reading the documentation I have noticed that the built-in function `len` doesn't support all iterables but just sequences and mappings (and sets). Before reading that, I always thought that the `len` function used the *iteration protocol* to evaluate the length of an object, so I was really surprised reading that.
I ... | The biggest reason is that *it reduces type safety*.
How many programs have you written where you actually *needed* to *consume* an iterable just to know how many elements it had, throwing away anything else?
I, in quite a few years of coding in Python, *never* needed that. It's a non-sensical operation in normal pro... |
How to get HTML from a beautiful soup object | 25,729,589 | 8 | 2014-09-08T17:13:57Z | 25,729,636 | 17 | 2014-09-08T17:16:49Z | [
"python",
"html",
"beautifulsoup",
"html-parsing"
] | I have the following bs4 object listing:
```
>>> listing
<div class="listingHeader">
<h2>
....
>>> type(listing)
<class 'bs4.element.Tag'>
```
I want to extract the raw html as a string. I've tried:
```
>>> a = listing.contents
>>> type(a)
<type 'list'>
```
So this does not work. How can I do this? | Just get the [string representation](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#non-pretty-printing):
```
html_content = str(listing)
```
This is a non-prettified version.
If you want a prettified one, use [`prettify()`](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#pretty-printing) method:
```
h... |
Installing theano on Windows 8 with GPU enabled | 25,729,969 | 14 | 2014-09-08T17:37:48Z | 26,073,714 | 27 | 2014-09-27T10:30:52Z | [
"python",
"windows",
"cuda",
"mingw",
"theano"
] | I understand that the Theano support for Windows 8.1 is at experimental stage only but I wonder if anyone had any luck with resolving my issues. Depending on my config, I get three distinct types of errors. I assume that the resolution of any of my errors would solve my problem.
I have installed Python using WinPython... | Theano is a great tool for machine learning applications, yet I found that its installation on Windows is not trivial especially for beginners (like myself) in programming. In my case, I see 5-6x speedups of my scripts when run on a GPU so it was definitely worth the hassle.
I wrote this guide based on my installation... |
Operator NOT IN with Peewee | 25,734,566 | 6 | 2014-09-08T23:24:53Z | 25,752,997 | 12 | 2014-09-09T20:21:34Z | [
"python",
"sqlite",
"peewee"
] | The documentation shows [here](http://peewee.readthedocs.org/en/latest/peewee/querying.html#filtering-records) how to use the `IN` operator, but I couldn't find how to use the `NOT IN` operator.
If I put a `not <<` I get a syntax error.
If I put a `not <FieldName> <<` there is a `WHERE False` instead of a subquery li... | You need to use unary negation:
```
Tweet.select().where(~(Tweet.user << a_users))
```
**Edit**: I've also updated the docs: <http://docs.peewee-orm.com/en/latest/peewee/querying.html#query-operators>
Also, if you want, you can use:
```
Tweet.select().where(Tweet.user.not_in(a_users))
``` |
Plotting a Fast Fourier Transform in Python | 25,735,153 | 8 | 2014-09-09T00:45:05Z | 25,735,274 | 19 | 2014-09-09T01:02:46Z | [
"python",
"numpy",
"scipy",
"fft"
] | I have access to numpy and scipy and want to create a simple FFT of a dataset. I have two lists one that is y values and the other is timestamps for those y values.
What is the simplest way to feed these lists into a scipy or numpy method and plot the resulting FFT?
I have looked up examples, but they all rely on cre... | So I run a functionally equivalent form of your code in an IPython notebook:
```
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack
# Number of samplepoints
N = 600
# sample spacing
T = 1.0 / 800.0
x = np.linspace(0.0, N*T, N)
y = np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * ... |
Python - RegEx for splitting text into sentences (sentence-tokenizing) | 25,735,644 | 7 | 2014-09-09T01:55:57Z | 25,735,848 | 10 | 2014-09-09T02:22:37Z | [
"python",
"regex",
"nlp",
"tokenize"
] | I want to make a list of sentences from a string and then print them out. I don't want to use NLTK to do this. So it needs to split on a period at the end of the sentence and not at decimals or abbreviations or title of a name or if the sentence has a .com This is attempt at regex that doesn't work.
```
import re
tex... | Ok so sentence-tokenizers are something I looked at in a little detail, using regexes, nltk, CoreNLP. You end up writing your own and it depends on the application. This stuff is tricky and valuable and people don't just give their tokenizer code away.
**In general you can't rely on one single Great White infallible r... |
How to break nested for loop in Python? | 25,742,107 | 4 | 2014-09-09T10:15:57Z | 25,742,239 | 12 | 2014-09-09T10:23:24Z | [
"python",
"loops",
"for-loop",
"break"
] | I wonder how to get out from loop like this:
```
for a in range(95):
for b in range(95):
for c in range(95):
for d in range(95):
...
do some computings
...
if condition:
task completed
```
After task is complet... | Using itertools product:
```
from itertools import product
for a, b, c, d in product(range(95), range(95), range(95), range(95)):
print a, b, c, d
if a == 1: break
```
Shorter version, thanks Ashwini:
```
for a, b, c, d in product(range(95), repeat=4):
print a, b, c, d
if a == 1: break
``` |
About char b prefix in Python3.4.1 client connect to redis | 25,745,053 | 5 | 2014-09-09T12:46:39Z | 25,745,110 | 9 | 2014-09-09T12:49:47Z | [
"python",
"redis"
] | I am run into trouble .My code below.But I do not know why there is a char 'b' before output string "Hello Python".
```
>>> import redis
>>> redisClient = redis.StrictRedis(host='192.168.3.88',port=6379)
>>> redisClient.set('test_redis', 'Hello Python')
True
>>> value = redisClient.get('test_redis')
>>> print(value)
b... | It means it's a byte string
You can use:
```
redis.StrictRedis(host="localhost", port=6379, charset="utf-8", decode_responses=True)
```
using `decode_responses=True` to make a unicode string. |
NotImplementedError: The gflags library must be installed to use tools.run(). Please install gflags or preferrably switch to using tools.run_flow() | 25,745,496 | 5 | 2014-09-09T13:08:43Z | 26,841,698 | 8 | 2014-11-10T10:33:05Z | [
"python",
"django",
"google-app-engine"
] | I am developing GAE django non-rel app. I am facing gflags related error.
> NotImplementedError: The gflags library must be installed to use
> tools.run(). Please install gflags or preferrably switch to using
> tools.run\_flow()
To solve this error, i downloaded glags.py and gflags\_validators.py and put them into my... | Try this
```
pip install python-gflags
```
or
```
sudo easy_install --upgrade python-gflags
``` |
Python force a condition | 25,748,151 | 8 | 2014-09-09T15:13:02Z | 25,748,199 | 8 | 2014-09-09T15:15:20Z | [
"python"
] | Is there a way to force a condition to be true in Python? I've seen it being done in Haskell before and am wondering if you can do it Python. For example:
```
>>> 2+2==5
True
``` | You can redefine the equality operator for a subclassed int:
```
>>> class MyInt(int):
... def __eq__(self, other):
... return True
...
>>> five = MyInt(5)
>>> five
5
>>> 2+2 == five
True
```
This is the least harmful of these answers to try out yourself. But if you do this (or any of these) in p... |
Python force a condition | 25,748,151 | 8 | 2014-09-09T15:13:02Z | 25,749,083 | 8 | 2014-09-09T15:54:27Z | [
"python"
] | Is there a way to force a condition to be true in Python? I've seen it being done in Haskell before and am wondering if you can do it Python. For example:
```
>>> 2+2==5
True
``` | Well you just need to set four equal to five.
```
import ctypes
def deref(addr, typ):
return ctypes.cast(addr, ctypes.POINTER(typ))
deref(id(4), ctypes.c_int)[6] = 5
2 + 2
#>>> 5
2 + 2 == 5
#>>> True
```
Obviously... |
Getting a strange % when printing using a formatted string | 25,748,589 | 2 | 2014-09-09T15:31:48Z | 25,748,640 | 7 | 2014-09-09T15:34:15Z | [
"python"
] | I'm trying to use a formatted string to print an message to sys.stderr but I am getting a mysterious % at the end.
If I write:
```
sys.stderr.write("One argument (file name) expected, got %d" % (len(sys.argv) -1))
```
I get an output of:
`One argument (file name) expected, got 0%`
If I replace it with a print fun... | The `%` is probably the `zsh` shell marking output that is missing a newline.
`print` adds a newline, add one manually when using `sys.stderr.write()`:
```
sys.stderr.write("One argument (file name) expected, got %d\n" % (len(sys.argv) -1))
``` |
Python - Pandas sum dataframe rows for given columns | 25,748,683 | 29 | 2014-09-09T15:36:03Z | 25,748,826 | 43 | 2014-09-09T15:42:55Z | [
"python",
"pandas"
] | new to pandas since today, I have the following dataframe:
```
import pandas as pd
df = pd.DataFrame({'a': [1,2,3], 'b': [2,3,4], 'c':['dd','ee','ff'], 'd':[5,9,1]})
```
It is a really basic question, but I simply would like to add a column 'e' which is the sum of column 'a', 'b' and 'd'.
Going accross forums, I tho... | You can just `sum` and set param `axis=1` to sum the rows, this will ignore none numeric columns:
```
In [91]:
df = pd.DataFrame({'a': [1,2,3], 'b': [2,3,4], 'c':['dd','ee','ff'], 'd':[5,9,1]})
df['e'] = df.sum(axis=1)
df
Out[91]:
a b c d e
0 1 2 dd 5 8
1 2 3 ee 9 14
2 3 4 ff 1 8
```
If you... |
What's the difference between pip install and python -m pip install? | 25,749,621 | 2 | 2014-09-09T16:24:44Z | 25,749,976 | 7 | 2014-09-09T16:47:17Z | [
"python",
"python-3.x",
"pip"
] | I have a local version of Python 3.4.1 and I can run python -m pip install but I'm unable to find the pip binary to run pip install. What's the difference between these two? | They do exactly the same thing. In fact, the docs for distributing Python modules were [just updated](http://bugs.python.org/issue22295) to suggest using `python -m pip` instead of the `pip` executable, because it's easier to tell which version of python is going to be used to actually run `pip` that way.
**Edit:**
H... |
Can I show decimal places and scientific notation on the axis of a matplotlib plot using Python 2.7? | 25,750,170 | 5 | 2014-09-09T16:59:26Z | 25,750,438 | 14 | 2014-09-09T17:16:28Z | [
"python",
"python-2.7",
"matplotlib",
"axis-labels",
"significant-digits"
] | I am plotting some big numbers with matplotlib in a pyqt program using python 2.7. I have a y-axis that ranges from 1e+18 to 3e+18 (usually). I'd like to see each tick mark show values in scientific notation and with 2 decimal places. For example 2.35e+18 instead of just 2e+18 because values between 2e+18 and 3e+18 sti... | This is really easy to do if you use the `matplotlib.ticker.FormatStrFormatter` as opposed to the `LogFormatter`. The following code will label everything with the format `'%.2e'`:
```
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
fig = plt.figure()
ax = fig.add_subplot(111)
x... |
Handling computationally intensive tasks in a Django webapp | 25,750,764 | 3 | 2014-09-09T17:40:50Z | 25,751,047 | 7 | 2014-09-09T18:01:19Z | [
"python",
"django",
"numpy"
] | I have a desktop app that I'm in the process of porting to a Django webapp. The app has some quite computationally intensive parts (using numpy, scipy and pandas, among other libraries). Obviously importing the computationally intensive code into the webapp and running it isn't a great idea, as this will force the clie... | We developed a Django web app which does heavy computation(Each process will take 11 to 88 hours to complete on high end servers).
**[Celery:](http://www.celeryproject.org/)** Celery is an asynchronous task queue/job queue based on distributed message passing. It is focused on real-time operation, but supports schedul... |
Scipy error: numpy.dtype size changed, may indicate binary incompatibility (and associated strange behavior) | 25,752,444 | 3 | 2014-09-09T19:45:46Z | 25,753,627 | 7 | 2014-09-09T21:10:06Z | [
"python",
"osx",
"numpy",
"scipy",
"scikit-learn"
] | I am installing numpy/scipy/scikit-learn on OS X 10.9.4, and am getting errors about "numpy.dtype size changed, may indicate binary incompatibility".
Here's what I did to construct the repo:
```
mkvirtualenv thm
workon thm
pip install numpy scipy pandas ipython # and some other stuff
cd /path/to/our/repo
# run tests
... | How did you build sklearn 0.14.1? Did you build it against the same version of numpy as you did for scipy?
Recent versions of scikit-learn, scipy and numpy have prebuilt-packages. In particular scikit-learn 0.15.2 should be binary compatible with numpy 1.7+. I think the same is true with scipy 0.14.0 but you said you ... |
Why won't this django-rest-swagger API documentation display/work properly? | 25,752,983 | 3 | 2014-09-09T20:20:58Z | 25,803,206 | 7 | 2014-09-12T07:42:12Z | [
"python",
"django",
"rest",
"django-rest-framework"
] | I've built a Django API that when given an email address via POST will respond with a boolean value indicating weather or not that email address already exists in my database:
```
class isEmailTaken(views.APIView):
permission_classes = [permissions.AllowAny,]
def post(self, request, *args, **kwargs):
... | I tested this with cigar\_example which is made by django-rest-swagger and in that example they written one [custom view](https://github.com/marcgibbons/django-rest-swagger/blob/master/cigar_example/cigar_example/restapi/views.py#L75) which is also not rendering input parameters
Lastly i look into source code and foun... |
Python comparison operators chaining/grouping left to right? | 25,753,474 | 4 | 2014-09-09T20:59:03Z | 25,753,528 | 8 | 2014-09-09T21:02:23Z | [
"python",
"comparison",
"operator-precedence",
"associativity"
] | The Python documentation for operator precedence states:
> Operators in the same box group left to right (except for
> comparisons, including tests, which all have the same precedence and
> chain from left to right â see section Comparisons...) [<https://docs.python.org/2/reference/expressions.html#operator-preceden... | Grouping (this is what non-comparison operators do):
```
a + b + c means (a + b) + c
```
Chaining (this is what comparison operators do):
```
a < b < c means (a < b) and (b < c)
```
Grouping left to right (this is the way things are grouped):
```
5 - 2 - 1 means (5 - 2) - 1 == 2
```
as opposed to grou... |
tkinter: how to use after method | 25,753,632 | 8 | 2014-09-09T21:10:51Z | 25,753,719 | 15 | 2014-09-09T21:19:04Z | [
"python",
"user-interface",
"tkinter",
"pycharm"
] | Hey I am new to python and am using tkinter for my gui. I am having trouble using the "after" method.
The goal is to make a random letter appear every 5 seconds.
Here is my code:
```
import random
import time
from tkinter import *
root = Tk()
w = Label(root, text="GAME")
w.pack()
frame = Frame(root, width=300, he... | You need to give a function to be called after the time delay as the second argument to [`after`](http://effbot.org/tkinterbook/widget.htm#Tkinter.Widget.after-method):
> **after(delay\_ms, callback=None, \*args)**
>
> Registers an alarm callback that is called after a given time.
So what you really want to do is thi... |
Using Selenium with Python and PhantomJS to download file to filesystem | 25,755,713 | 13 | 2014-09-10T00:49:30Z | 25,756,960 | 9 | 2014-09-10T03:43:00Z | [
"python",
"selenium",
"selenium-webdriver",
"download",
"phantomjs"
] | I've been grappling with using PhantomJS/Selenium/python-selenium to download a file to the filesystem.
I'm able to easily navigate through the DOM and click, hover etc. Downloading a file is, however, proving to be quite troublesome. I've tried a headless approach with Firefox and pyvirtualdisplay but that wasn't work... | PhantomJS doesn't currently support file downloads. Relevant issues with workarounds:
* [File download](https://github.com/ariya/phantomjs/issues/10052)
* [How to handle file save dialog box using Selenium webdriver and PhantomJS?](https://github.com/ariya/phantomjs/issues/12283)
As far as I understand, you have at l... |
How to add my module to travis-ci pythonpath | 25,756,134 | 5 | 2014-09-10T01:48:25Z | 27,091,478 | 7 | 2014-11-23T16:44:38Z | [
"python",
"python-import",
"travis-ci"
] | I'm setting up Travis-CI for my project, and oddly, I can't import my project:
```
$ python tests/tests.py
Traceback (most recent call last):
File "tests/tests.py", line 11, in <module>
from my_module.lib.importer import build_module_list
ImportError: No module named my_module.lib.importer
```
In production, I ... | > What's the best way to make this work, so my code is added as an importable module?
The answer is unequivocally to use `distutils` (and definitely not `ln`).
> In production, I just create a symlink ...
B-b-but why? The complexity to do it the Right Way⢠is so low! It even fits in a few lines:
From [The Fine Ma... |
Django - Cannot create migrations for ImageField with dynamic upload_to value | 25,767,787 | 15 | 2014-09-10T14:17:07Z | 25,768,034 | 33 | 2014-09-10T14:27:27Z | [
"python",
"django",
"django-migrations"
] | I just upgraded my app to 1.7 (actually still trying).
This is what i had in models.py:
```
def path_and_rename(path):
def wrapper(instance, filename):
ext = filename.split('.')[-1]
# set filename as random string
filename = '{}.{}'.format(uuid4().hex, ext)
# return the whole path ... | I am not sure if it is OK to answer my own question, but i just figured out (i think).
According to [this bug report](https://code.djangoproject.com/ticket/22999), i edited my code:
```
from django.utils.deconstruct import deconstructible
@deconstructible
class PathAndRename(object):
def __init__(self, sub_path... |
Python Windows service pyinstaller executables error 1053 | 25,770,873 | 9 | 2014-09-10T16:45:57Z | 25,934,756 | 12 | 2014-09-19T13:11:19Z | [
"python",
"windows",
"service",
"py2exe",
"pyinstaller"
] | I have written a Windows service in python. If I run my script from the command prompt
```
python runService.py
```
When I do this the service installs and starts correctly. I have been trying to create an executable using pyinstaller because i've seen the same issue with py2exe. When I run the .exe the service insta... | Try changing the last few lines to
```
if __name__ == '__main__':
if len(sys.argv) == 1:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(Service)
servicemanager.StartServiceCtrlDispatcher()
else:
win32serviceutil.HandleCommandLine(Service)
``` |
Ambiguity in Pandas Dataframe / Numpy Array "axis" definition | 25,773,245 | 38 | 2014-09-10T19:11:14Z | 25,774,395 | 74 | 2014-09-10T20:20:45Z | [
"python",
"numpy",
"pandas",
"dataframe"
] | I've been very confused about how python axes are defined, and whether they refer to a DataFrame's rows or columns. Consider the code below:
```
>>> df = pd.DataFrame([[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]], columns=["col1", "col2", "col3", "col4"])
>>> df
col1 col2 col3 col4
0 1 1 1 1
1 2... | It's perhaps simplest to remember it as *0=down* and *1=across*.
This means:
* Use `axis=0` to apply a method down each column, or to the row labels (the index).
* Use `axis=1` to apply a method across each row, or to the column labels.
Here's a picture to show the parts of a DataFrame that each axis refers to:
![]... |
Colon in file names in Python | 25,774,337 | 6 | 2014-09-10T20:17:23Z | 25,896,961 | 7 | 2014-09-17T17:37:39Z | [
"python",
"windows",
"filenames",
"ioerror"
] | As we all know, filenames in Windows can't contain colons.
However, I ran into a problem, that can be reproduced with the following sample code:
```
import os
os.chdir('./temp')
names = ['a', 'b', 'word1: word2', 'c: file', 'd: file']
for name in names:
with open(name, 'w') as f:
f.write('foo')
```
This ... | Windows NTFS supports file "stream". You basically append data to a file, outside of the file, and can't be viewed normally. When you created the file "word1:word2", the hidden stream "word2" is attached to "word1". If you copied the file word1 to another NTFS machine, the word2 data would come with you
Go here <http:... |
mkvirtualenv: command not found | 25,774,829 | 5 | 2014-09-10T20:49:19Z | 29,236,350 | 12 | 2015-03-24T15:17:07Z | [
"python",
"bash",
"virtualenv",
"virtualenvwrapper"
] | I'm new to Python virtual environments, so after reading [this tutorial](http://simononsoftware.com/virtualenv-tutorial-part-2/) I tried to create my first environment using `virtualenvwrapper`. My python3 installation is at the bare bones now:
```
$ pip3 list
argparse (1.2.1)
pip (1.5.6)
setuptools (2.1)
stevedore (0... | I added the following in my .bashrc, referring [this](http://virtualenvwrapper.readthedocs.org/en/latest/install.html#python-interpreter-virtualenv-and-path)
```
export PATH=/usr/local/bin:$PATH
source /usr/local/bin/virtualenvwrapper.sh
```
Now mkvirtualenv works-
```
pkoli@pkoli-SVE15136CNB:~/Desktop$ mkvirtualenv... |
Django test runner fails in virtualenv on Ubuntu | 25,775,185 | 11 | 2014-09-10T21:12:35Z | 34,078,881 | 12 | 2015-12-04T00:31:07Z | [
"python",
"django",
"ubuntu",
"virtualenv",
"python-unittest"
] | I've been struggling with a problem with the Django test runner installed in a Python virtualenv on Ubuntu 14.04. The same software runs fine on MacOS, and I think it was fine on an earlier version of Ubuntu.
The failure message is:
```
ImportError: '<test>' module incorrectly imported from '<base-env>/local/lib/pyth... | I had exactly the same problem and couldn't figure out what was going on. Finally it was a stupid thing:
I had a layout similar to this one:
```
my_app/
__init__.py
tests.py
tests/
__init__.py
test_foo.py
```
The problem was generated by having both a "tests.py" module and a "tests" packag... |
.format() returns ValueError when using {0:g} to remove trailing zeros | 25,775,197 | 4 | 2014-09-10T21:13:33Z | 25,775,271 | 11 | 2014-09-10T21:18:54Z | [
"python",
"string",
"formatting",
"floating-point-precision"
] | I'm trying to generate a string that involves an occasional float with trailing zeros. This is a MWE of the text string and my attempt at removing them with `{0:g}`:
```
xn, cod = 'r', 'abc'
ccl = [546.3500, 6785.35416]
ect = [12.350, 13.643241]
text = '${}_{{t}} = {0:g} \pm {0:g}\;{}$'.format(xn, ccl[0], ect[0], cod... | `{}` uses automatic field numbering.
`{0:g}` uses manual field numbering.
Don't mix the two. If you are going to use manual field numbering, use it everywhere:
```
text = '${0}_{{t}} = {1:g} \pm {2:g}\;{3}$'.format(xn, ccl[0], ect[0], cod)
``` |
Python socket stress concurrency | 25,779,767 | 7 | 2014-09-11T05:33:16Z | 25,780,105 | 8 | 2014-09-11T06:00:35Z | [
"python",
"multithreading",
"sockets"
] | I need a Python TCP server that can handle at least tens of thousands of concurrent socket connections. I was trying to test Python SocketServer package capabilities in both multiprocessor and multithreaded modes, but both were far from desired performance.
At first, I'll describe client, because it's common for both ... | `socketserver` is not going to handle anywhere near 10k connections. No threaded or forked server will on current hardware and OS's. Thousands of threads means you spend more time context-switching and scheduling than actually working. Modern linux is getting very good at scheduling threads and processes, and Windows i... |
Understanding time.perf_counter() and time.process_time() | 25,785,243 | 5 | 2014-09-11T10:36:46Z | 25,787,875 | 10 | 2014-09-11T12:48:57Z | [
"python",
"python-3.x"
] | I have some questions about the new functions `time.perf_counter()` and `time.process_time()`.
For the former, from the documentation:
> Return the value (in fractional seconds) of a performance counter, i.e. **a clock with the highest available resolution** to measure a short duration. It does include time elapsed d... | There are two distincts types of 'time', in this context: absolute time and relative time.
Absolute time is the 'real-world time', which is returned by `time.time()` and which we are all used to deal with. It is usually measured from a fixed point in time in the past (e.g. the UNIX epoch of 00:00:00 UTC on 01/01/1970)... |
Django 1.7 app config ImportError: No module named appname.apps | 25,785,667 | 8 | 2014-09-11T10:57:06Z | 25,794,339 | 11 | 2014-09-11T18:09:25Z | [
"python",
"django",
"django-1.7"
] | I'm trying to setup a custom application configuration for one of my Django app called 'articles' following the documentation at <https://docs.djangoproject.com/en/dev/ref/applications/>, but I keep getting `ImportError: No module named articles.apps` when execute `./manage.py check` (or any other management command su... | According to the specific Django project structure (all applications are located in `projectname/apps/` module) the **full path** including the project name should be used.
As the doc <https://docs.djangoproject.com/en/dev/ref/applications/#django.apps.AppConfig.name> says:
> AppConfig.name
>
> Full Python path to th... |
python: unexpected behavior from struct pack() | 25,785,702 | 4 | 2014-09-11T10:59:24Z | 25,785,801 | 8 | 2014-09-11T11:05:23Z | [
"python"
] | I'm having trouble using the `struct.pack()` for packing an integer.
With
```
struct.pack("BIB", 1, 0x1234, 0)
```
I'm expecting
```
'\x01\x00\x00\x034\x12\x00'
```
but instead I got
```
'\x01\x00\x00\x004\x12\x00\x00\x00'
```
I'm probably missing something here. Please help. | ```
'\x01\x00\x00\x004\x12\x00\x00\x00'
^ this '4' is not part of a hex escape
```
is actually the same as:
```
'\x01\x00\x00\x00\x34\x12\x00\x00\x00'
```
Because the ASCII code for "4" is 0x34.
Because you used the default (native) format, Python used native alignment for the data, so the second f... |
Cython Numpy warning about NPY_NO_DEPRECATED_API when using MemoryView | 25,789,055 | 13 | 2014-09-11T13:43:17Z | 31,988,588 | 11 | 2015-08-13T12:42:18Z | [
"python",
"numpy",
"cython",
"memoryview"
] | I am converting a Cython memoryview to a numpy array (to be able to use it in pure Python code):
```
from libc.stdlib cimport realloc
cimport numpy as np
DTYPE = np.float64
ctypedef np.float64_t DTYPE_t
cpdef np.ndarray[DTYPE_t] compute(DTYPE_t[:,::1] data):
cdef unsigned int Nchannels = data.shape[0]
cdef u... | Just for a further reference, [cython online docs](http://docs.cython.org/src/reference/compilation.html#configuring-the-c-build) says this is because Cython is using a deprecated Numpy API, and for the time being, it's just a warning that we can ignore. |
Pandas make new column from string slice of another column | 25,789,445 | 4 | 2014-09-11T13:59:14Z | 25,789,512 | 8 | 2014-09-11T14:02:02Z | [
"python",
"pandas"
] | I want to create a new column in Pandas using a string sliced for another column in the dataframe.
For example.
```
Sample Value New_sample
AAB 23 A
BAB 25 B
```
Where `New_sample` is a new column formed from a simple `[:1]` slice of `Sample`
I've tried a number of things to no avail - I feel I'm ... | You can call the `str` method and apply a slice, this will be much quicker than the other method as this is vectorised (thanks @unutbu):
```
df['New_Sample'] = df.Sample.str[:1]
```
You can also call a lambda function on the df but this will be slower on larger dataframes:
```
In [187]:
df['New_Sample'] = df.Sample... |
How to hide <matplotlib.lines.Line2D> in IPython notebook | 25,790,062 | 16 | 2014-09-11T14:27:00Z | 25,790,871 | 29 | 2014-09-11T15:00:16Z | [
"python",
"matplotlib",
"plot",
"ipython",
"ipython-notebook"
] | I am plotting a NumPy array of values, `I`, using IPython notebook in `%matplotlib` inline mode with the plot command `plt.plot(I,'o')`.
The resulting output is:
```
<matplotlib.figure.Figure at 0x119e6ead0>
Out[159]:
[<matplotlib.lines.Line2D at 0x11ac57090>,
<matplotlib.lines.Line2D at 0x11ac57310>,
<matplotlib.l... | Using a semi-colon `;` to end the line suppresses the unwanted output when generating plots:
```
plt.plot(I,'o');
```
In general, using a semi-colon stops IPython from outputting a value (e.g. the line `In [1]: 1+1;` would not have a corresponding output `2`).
An alternative way would be to bind a variable to the pl... |
What is correct syntax to swap column values for selected rows in a pandas data frame using just one line? | 25,792,619 | 7 | 2014-09-11T16:28:32Z | 25,792,812 | 9 | 2014-09-11T16:40:46Z | [
"python",
"pandas"
] | I am using [pandas](http://pandas.pydata.org/) version 0.14.1 with Python 2.7.5, and I have a data frame with three columns, e.g.:
```
import pandas as pd
d = {'L': ['left', 'right', 'left', 'right', 'left', 'right'],
'R': ['right', 'left', 'right', 'left', 'right', 'left'],
'VALUE': [-1, 1, -1, 1, -1, 1]}... | One way you could avoid alignment on column names would be to drop down to the underlying array via `.values`:
```
In [33]: df
Out[33]:
L R VALUE
0 left right -1
1 right left 1
2 left right -1
3 right left 1
4 left right -1
5 right left 1
In [34]: df.loc[idx,... |
Can't install Python-MySQL on OS X 10.10 Yosemite | 25,794,121 | 10 | 2014-09-11T17:58:05Z | 27,439,907 | 10 | 2014-12-12T08:50:09Z | [
"python",
"mysql",
"osx",
"osx-yosemite"
] | I can't install Python-MySQL, I already tried with easy\_install, pip and sources..
And I always get the same error. This is what I get:
```
Matts-MacBook:Python matt$ sudo easy_install MySQL-python
Searching for MySQL-python
Reading https://pypi.python.org/simple/MySQL-python/
Best match: MySQL-python 1.2.5
Downloadi... | I've solved the problem as follows:
1. After installing the [OSX command line tools](http://railsapps.github.io/xcode-command-line-tools.html), to install the MySQL-python.
`$ xcode-select --install`
`$ sudo pip install MySQL-python`
(Three warning message is issued, but, "Successfully installed MySQL-pyth... |
How to properly add hours to a pandas.tseries.index.DatetimeIndex? | 25,797,245 | 7 | 2014-09-11T21:30:13Z | 25,797,313 | 10 | 2014-09-11T21:34:42Z | [
"python",
"pandas",
"indexing",
"time-series",
"dataframe"
] | I have a normal df.index that I would like to add some hours to it.
```
In [1]: test[1].index
Out[2]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2010-03-11, ..., 2014-08-14]
Length: 52, Freq: None, Timezone: None
```
This is how the first element looks like:
```
In [1]: test[1].index[0]
Out[2]: Timestamp('2010-0... | You can use [pd.DateOffset](http://pandas.pydata.org/pandas-docs/stable/timeseries.html#dateoffset-objects):
```
test[1].index + pd.DateOffset(hours=16)
```
`pd.DateOffset` accepts the same keyword arguments as [dateutil.relativedelta](https://labix.org/python-dateutil#head-ba5ffd4df8111d1b83fc194b97ebecf837add454).
... |
adding backslash to symbols in python while using the regex library | 25,797,690 | 2 | 2014-09-11T22:05:14Z | 25,797,717 | 7 | 2014-09-11T22:07:31Z | [
"python",
"regex",
"string",
"list"
] | So I need to selectively add backslashes to characters that already have pre-defined meaning (such as + and \*)in the re library in python.
Say that I am give an array
```
arr = ["five", "+", "two", "*", "zero", "=", "five"]
```
are there any functions within re (or python ) that will allow me to add a \ to "+" and ... | Use [`re.escape`](https://docs.python.org/2/library/re.html#re.escape) with either [`map`](https://docs.python.org/2/library/functions.html#map) or a list comprehension:
```
>>> import re
>>> arr = ["five", "+", "two", "*", "zero", "=", "five"]
>>> map(re.escape, arr)
['five', '\\+', 'two', '\\*', 'zero', '\\=', 'five... |
what's Python asyncio.Lock() for? | 25,799,576 | 5 | 2014-09-12T01:55:09Z | 25,799,871 | 11 | 2014-09-12T02:36:05Z | [
"python",
"python-asyncio"
] | Is it because coroutines may be preempted in the future? Or it allows people to use yield from in critical section (which IMO shouldn't be encouraged)? | You use it for the same reason you'd use a lock in threaded code: to protect a critical section. `asyncio` is primarily meant for use in single-threaded code, but there is still concurrent execution happening, which means sometimes you need synchronization.
For example, consider a function that fetches some data from ... |
Reduce set size while preserving minimum frequency | 25,801,269 | 6 | 2014-09-12T05:19:20Z | 25,813,605 | 7 | 2014-09-12T17:23:00Z | [
"python",
"algorithm"
] | Lets say I have the following set:
```
{(2,), (3,), (1, 4), (1, 2, 3), (2, 3), (3, 4), (2, 4)}
```
This gives each number the following frequency:
```
2: 4, 3: 4, 4: 3, 1: 2
```
Can you propose a way of reducing the set such that each number exists in it at least 2 times but where the number of tuples in the set is... | As noted in the comments, the NP-hard problem Set Cover is a special
case of this problem where the minimum frequency is `k = 1`, making this
problem NP-hard as well. I would recommend a library like
[PuLP](https://pythonhosted.org/PuLP/) with the following integer
program.
```
minimize sum over tuples T of x(T)
subje... |
Django filter with regex | 25,803,822 | 7 | 2014-09-12T08:21:32Z | 25,803,837 | 7 | 2014-09-12T08:22:46Z | [
"python",
"regex",
"django"
] | I want to write regex for django's model's charField. That regex contains all letters and last character contains "/".
Eg: "sequences/"
I return regex as follows,
```
Model.objects.filter(location_path__iregex=r'^[a-zA-Z]/$')
```
It is not showing filter data.
demo data for location\_path is ['sequences/', 'abc/xyz... | You need to add `+` after the character class, so that it would match one or more letters,
```
r'^[a-zA-Z]+/$'
``` |
Python multiplication of two list | 25,804,647 | 2 | 2014-09-12T09:08:56Z | 25,804,743 | 7 | 2014-09-12T09:13:31Z | [
"python",
"python-3.x"
] | I am new to Python and noticed that the following.
```
>>> 'D'*1
'D'
```
Therefore i wonder whether we can do multiplication and join the string (for choice, element can be 0 or 1 only)
```
>>> print(choice)
[1, 1, 1, 1]
>>> print(A)
['D', 'e', '0', '}']
```
My desired output would be `'De0}'` | You can explicity zip the lists, mulitply and then join the result:
```
''.join([c * i for c, i in zip(A, choice)])
```
The [`zip()` function](https://docs.python.org/3/library/functions.html#zip) pairs up the characters from `A` with the integers from `choice`, the list comprehension then multiplies the character wi... |
Python 'for word in word' loop | 25,807,731 | 3 | 2014-09-12T11:53:50Z | 25,807,814 | 12 | 2014-09-12T11:57:59Z | [
"python",
"variables",
"for-loop",
"foreach"
] | Basic for loop, I need help understanding how this loop words:
```
word = "hello"
for word in word:
print word
```
Wouldn't the `word=hello` variable be overwritten with `word=h` as soon as the for loop started?
If so, how does it still loop through all the letters in the word string?
Thanks in advance for the cla... | Let's look at the bytecode:
```
>>> def so25807731():
... word = "hello"
... for word in word:
... print word
...
>>> import dis
>>> dis.dis(so25807731)
2 0 LOAD_CONST 1 ('hello')
3 STORE_FAST 0 (word)
3 6 SETUP_LOOP 19 (to 28)
... |
How to fix locale issue in Red Hat distro? | 25,809,430 | 5 | 2014-09-12T13:26:37Z | 33,787,168 | 8 | 2015-11-18T18:05:46Z | [
"python",
"locale",
"rhel"
] | I'm having a strange problem today in my RHEL system. My python script is returning:
```
>>> locale.setlocale(locale.LC_ALL, '')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.6/locale.py", line 513, in setlocale
return _setlocale(category, locale)
locale.Error:... | Add this to your /etc/environment
LC\_ALL=en\_US.UTF-8
LC\_CTYPE=en\_US.UTF-8
Then logout and login to shell again and try executing your commands. |
Python list to list of lists | 25,812,033 | 2 | 2014-09-12T15:43:44Z | 25,812,044 | 18 | 2014-09-12T15:44:40Z | [
"python",
"list"
] | Is there an easy way to convert a list of doubles into a list of lists of doubles?
For example:
```
[1.0, 2.0, 3.0]
```
into
```
[[1.0], [2.0], [3.0]]
```
The code I'm using requires the second as inputs to a bunch of functions but it's annoying to have two copies of the same data. | Just use a [list-comprehension](https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions) wrapping each element in a list:
```
l = [1.0, 2.0, 3.0]
print [[x] for x in l]
[[1.0], [2.0], [3.0]]
``` |
Row and column headers in matplotlib's subplots | 25,812,255 | 17 | 2014-09-12T15:56:18Z | 25,814,386 | 13 | 2014-09-12T18:16:22Z | [
"python",
"matplotlib",
"subplot"
] | What's the best practise to add a row and a column header to a grid of subplots generated in a loop in `matplotlib`? I can think of a couple, but not particularly neat:
1. For columns, with a counter to your loop you can use `set_title()` for the first row only. For rows this doesn't work. You would have to draw `text... | There are several ways to do this. The easy way is to exploit the y-labels and titles of the plot and then use `fig.tight_layout()` to make room for the labels. Alternatively, you can place additional text in the right location with `annotate` and then make room for it semi-manually.
---
If you don't have y-labels on... |
Using pipeline with sklearn | 25,817,161 | 2 | 2014-09-12T21:31:12Z | 25,817,201 | 7 | 2014-09-12T21:35:00Z | [
"python",
"machine-learning",
"scikit-learn"
] | I'm trying to define a quantizer to use with Pipeline/GridSearchCV in sklearn. When defining as below
```
class Quantizer(base.BaseEstimator, base.TransformerMixin):
def __init__(self):
def transform(X, y=None):
some code
```
I'm getting something like
> method fit is missing
Am I missing something i... | If you are only transforming data in an intermediate state of your pipeline you don't need to implement a fit method, so you just return `self`:
```
class Quantizer(base.BaseEstimator, base.TransformerMixin):
def __init__(self):
def transform(self, X, y=None):
# some code
def fit(self, X, y=None, ... |
Are element-wise operations faster with NumPy functions than operators? | 25,817,226 | 8 | 2014-09-12T21:36:41Z | 25,817,270 | 11 | 2014-09-12T21:40:12Z | [
"python",
"arrays",
"performance",
"numpy",
"element"
] | I recently came across a [great SO post](http://stackoverflow.com/questions/10922231/pythons-sum-vs-numpys-numpy-sum) in which a user suggests that `numpy.sum` is faster than Python's `sum` when it comes to dealing with NumPy arrays.
This made me think, are element-wise operations on NumPy arrays faster with NumPy fun... | No, not in a significant way.
The reason `np.sum` is faster than `sum` is that `sum` is implemented to "naively" iterate over the iterable (in this case, the numpy array), calling elements' `__add__` operator (which imposes a significant overhead), while numpy's implementation of `sum` is optimized, e.g. taking advant... |
Are element-wise operations faster with NumPy functions than operators? | 25,817,226 | 8 | 2014-09-12T21:36:41Z | 25,817,286 | 7 | 2014-09-12T21:41:54Z | [
"python",
"arrays",
"performance",
"numpy",
"element"
] | I recently came across a [great SO post](http://stackoverflow.com/questions/10922231/pythons-sum-vs-numpys-numpy-sum) in which a user suggests that `numpy.sum` is faster than Python's `sum` when it comes to dealing with NumPy arrays.
This made me think, are element-wise operations on NumPy arrays faster with NumPy fun... | Not really. You can check the timings pretty easily though.
```
a = np.random.normal(size=1000)
b = np.random.normal(size=1000)
%timeit np.subtract(a, b)
# 1000000 loops, best of 3: 1.57 µs per loop
%timeit a - b
# 1000000 loops, best of 3: 1.47 µs per loop
%timeit np.divide(a, b)
# 100000 loops, best of 3: 3.51 ... |
Fastest way to sort each row in a pandas dataframe | 25,817,930 | 4 | 2014-09-12T22:45:54Z | 25,818,117 | 7 | 2014-09-12T23:06:37Z | [
"python",
"performance",
"pandas"
] | I need to find the quickest way to sort each row in a dataframe with millions of rows and around a hundred columns.
So something like this:
```
A B C D
3 4 8 1
9 2 7 2
```
Needs to become:
```
A B C D
8 4 3 1
9 7 2 2
```
Right now I'm applying sort to each row and building up a ... | I think I would do this in numpy:
```
In [11]: a = df.values
In [12]: a.sort(axis=1) # no ascending argument
In [13]: a = a[:, ::-1] # so reverse
In [14]: a
Out[14]:
array([[8, 4, 3, 1],
[9, 7, 2, 2]])
In [15]: pd.DataFrame(a, df.index, df.columns)
Out[15]:
A B C D
0 8 4 3 1
1 9 7 2 2
```
-... |
relation "account_emailaddress" does not exist - django error | 25,821,768 | 5 | 2014-09-13T09:25:59Z | 25,825,249 | 8 | 2014-09-13T16:29:04Z | [
"python",
"django",
"facebook",
"django-allauth"
] | I am following this tutorial to integrate social media login to my django project -
<http://www.sarahhagstrom.com/2013/09/the-missing-django-allauth-tutorial/>
However after completing all the steps, when I try to login using facebook, I get this error
```
relation "account_emailaddress" does not exist
```
I don't ... | I figured out what the problem was. the `allauth` uses `account` app which doesn't support migrations as yet. Initially I had run
```
python manage.py migrate allauth.socialaccount
python manage.py migrate allauth.socialaccount.providers.facebook
```
Along with this we need to run the `syncdb` to complete the puzzle. |
Find matching rows in 2 dimensional numpy array | 25,823,608 | 6 | 2014-09-13T13:17:34Z | 25,823,710 | 8 | 2014-09-13T13:29:54Z | [
"python",
"numpy",
"scipy"
] | I would like to get the index of a 2 dimensional Numpy array that matches a row. For example, my array is this:
```
vals = np.array([[0, 0],
[1, 0],
[2, 0],
[0, 1],
[1, 1],
[2, 1],
[0, 2],
[1, 2],
... | You need the `np.where` function to get the indexes:
```
>>> np.where((vals == (0, 1)).all(axis=1))
(array([ 3, 15]),)
```
To dissassemble that:
```
>>> vals == (0, 1)
array([[ True, False],
[False, False],
...
[ True, False],
[False, False],
[False, False]], dtype=bool)
```
and c... |
Calling one method from another within same class in Python | 25,825,693 | 5 | 2014-09-13T17:18:47Z | 25,825,737 | 12 | 2014-09-13T17:24:25Z | [
"python",
"class",
"methods",
"event-handling",
"python-watchdog"
] | I am very new to python. I was trying to pass value from one method to another within the class. I searched about the issue but i could not get proper solution. Because in my code, "if" is calling class's method "on\_any\_event" that in return should call my another method "dropbox\_fn", which make use of the value fro... | To call the method, you need to qualify function with `self.`. In addition to that, if you want to pass a filename, add a `filename` parameter (or other name you want).
```
class MyHandler(FileSystemEventHandler):
def on_any_event(self, event):
srcpath = event.src_path
print (srcpath, 'has been ',... |
Generating smooth line graph using matplotlib | 25,825,946 | 6 | 2014-09-13T17:47:48Z | 25,826,265 | 12 | 2014-09-13T18:22:31Z | [
"python",
"matplotlib"
] | Following is the python script to generate a plot using matplotlib.
```
#!/usr/bin/python
import matplotlib.pyplot as plt
import time
import numpy as np
from scipy.interpolate import spline
# Local variables
x = []
y = []
# Open the data file for reading lines
datafile = open('testdata1.txt', 'r')
sepfile = datafil... | I got this working! Thanks for the comments. Here is the updated code.
```
#!/usr/bin/python
import matplotlib.pyplot as plt
import time
import numpy as np
from scipy.interpolate import spline
# Local variables
x = []
y = []
# Open the data file for reading lines
datafile = open('testdata1.txt', 'r')
sepfile = data... |
AttributeError: 'FreqDist' object has no attribute 'inc' | 25,827,058 | 5 | 2014-09-13T19:51:59Z | 25,828,485 | 9 | 2014-09-13T22:48:36Z | [
"python",
"python-2.7",
"attributes",
"nltk"
] | I am a beginner in Python and NLTK. I am trying to run the following code from a tutorial:
```
from nltk.corpus import gutenberg
from nltk import FreqDist
fd = FreqDist()
for word in gutenberg.words('austen-sense.txt'):
fd.inc(word)
```
If I run this I get the following error:
```
AttributeError: 'FreqDist' ob... | You should do it like so:
```
fd[word] += 1
```
But usually FreqDist is used like this:
```
fd = FreqDist(my_text)
```
Also look at the examples here:
<http://www.nltk.org/book/ch01.html> |
Applying a decorator to an imported function? | 25,829,364 | 6 | 2014-09-14T01:46:55Z | 25,829,389 | 8 | 2014-09-14T01:51:00Z | [
"python",
"function",
"decorator"
] | I want to import a function:
```
from random import randint
```
and then apply a decorator to it:
```
@decorator
randint
```
I was wondering if there was some syntactic sugar for this (like what I have above), or do I have to do it as follows:
```
@decorator
def randintWrapper(*args):
return random.randint(*ar... | Decorators are just syntactic sugar to replace a function object with a decorated version, where *decorating* is just *calling* (passing in the original function object). In other words, the syntax:
```
@decorator_expression
def function_name():
# function body
```
translates to:
```
def function_name():
# f... |
R Lattice like plots with Python, Pandas and Matplotlib | 25,830,588 | 5 | 2014-09-14T06:10:53Z | 25,833,310 | 7 | 2014-09-14T12:39:38Z | [
"python",
"matplotlib",
"pandas",
"lattice"
] | I have a pandas dataframe of "factors", floats and integers. I would like to make "R Lattice" like plots on it using conditioning and grouping on the categorical variables. I've used R extensively and wrote custom panel functions to get the plots formatted exactly how I wanted them, but I'm struggling with matplotlib t... | [Seaborn](http://web.stanford.edu/~mwaskom/software/seaborn/) is the most effective library I have found for doing faceted plots in python.
Its a pandas aware wrapper around matplotlib which takes care of all the subplotting for you and updates the matplotlib styling to look more modern. It produces some really lovely ... |
tabular legend layout for matplotlib | 25,830,780 | 3 | 2014-09-14T06:45:01Z | 25,995,730 | 7 | 2014-09-23T12:57:38Z | [
"python",
"matplotlib",
"plot",
"legend"
] | I have a plot with 9 lines, representing datasets with two varying parameters, say f\_11, f\_12, f\_13, ..., f\_33. To make the plot (a bit) clearer, I encode the first parameter as the color of the line and the second one as the linestyle (so f\_11 is red & dashed, f12 is red & dotted, f21 is green & dashed, f22 is gr... | Not a very easy question but I figured it out. The trick I use is to initialize an empty rectangle which acts as a handle. These additional empty handles are used to construct the table. I get rid of any excessive space using `handletextpad`:
```
import numpy
import pylab
import matplotlib.pyplot as plt
from matplotli... |
Download Attachments from gmail using Gmail API | 25,832,631 | 4 | 2014-09-14T11:13:07Z | 27,335,699 | 11 | 2014-12-06T19:44:12Z | [
"python",
"email",
"gmail",
"gmail-api"
] | I am using Gmail API to access my gmail data and google python api client.
According to documentation to get the message attachment they gave one sample for python
<https://developers.google.com/gmail/api/v1/reference/users/messages/attachments/get>
but the same code i tried then i am getting error:
```
AttributeEr... | Expanding @Eric answer, I wrote the following corrected version of GetAttachments function from the docs:
```
# based on Python example from
# https://developers.google.com/gmail/api/v1/reference/users/messages/attachments/get
# which is licensed under Apache 2.0 License
import base64
from apiclient import errors
d... |
UUID as default value in Django model | 25,835,069 | 2 | 2014-09-14T15:48:56Z | 25,835,191 | 11 | 2014-09-14T16:02:17Z | [
"python",
"django",
"django-models"
] | I've noticed the strange behaviour of default value in django model. For example we have a simple django model:
```
import uuid
...
class SiteUser(models.Model):
...
username = models.CharField(max_length=255, verbose_name=u"Username")
activation_key = models.CharField(max_length=64, verbose_name=u"Activa... | Problem is the `default` attribute that you are setting as
```
activation_key = models.CharField(max_length=64, verbose_name=u"Activation key",
default=uuid.uuid1())
```
Here you are setting the default value as not a callable but value returned by `uuid.uuid1()` call when this model class is initial... |
Why an object in python is of type 'instance'? | 25,839,360 | 3 | 2014-09-15T00:35:26Z | 25,839,378 | 7 | 2014-09-15T00:38:39Z | [
"python",
"python-2.7"
] | I have the following code:
```
>>> class MyClass:
pass
>>> myObj=MyClass()
>>> type(myObj)
<type 'instance'> <==== Why it is not type MyClass ?
>>> type(MyClass)
<type 'classobj'> <=== Why it is not just 'MyClass'?
>>> isinstance(myObj, instance) <==== Why the 'instance' is not defined?
Traceback (most ... | This is because you're using [old-style classes](http://stackoverflow.com/q/54867/646543). Instead of doing:
```
class MyClass:
pass
```
You need to do:
```
class MyClass(object):
pass
```
...in order to use new-style classes. Now, if you do `type(myObj)`, you get back `<class '__main__.MyClass'>` as expect... |
How to solve TypeError: cannot serialize float Python Elementtree | 25,839,855 | 4 | 2014-09-15T01:59:51Z | 25,839,908 | 8 | 2014-09-15T02:05:00Z | [
"python",
"serialization",
"pandas",
"elementtree",
"marytts"
] | I got a debugging question.
Since I am quite new here, please forgive possible janky walls-of-text.
After many hours I finally got elementtree to do what I want, but I cannot output my results, because
```
tree.write("output3.xml")
```
as well as
```
print(ET.tostring(root))
```
give me
TypeError: cannot seriali... | **You should boil your problem down to a [simple example](http://stackoverflow.com/help/mcve).** This may help you solve the problem on your own, but more importantly, anyone who reads it now basically has to guess at your intentions since you haven't showed examples of your code, the input, or the intended output.
Li... |
List insert at index that is well out of range - behaves like append | 25,840,177 | 11 | 2014-09-15T02:47:28Z | 25,840,242 | 12 | 2014-09-15T02:56:47Z | [
"python",
"python-2.7"
] | I had a list
```
a = [1, 2, 3]
```
when I did
```
a.insert(100, 100)
[1, 2, 3, 100]
```
as list was originally of size 4 and I was trying to insert value at index 100 , it behaved like append instead of throwing any errors as I was trying to insert in an index that did not even existed .
Should it not throw
> I... | From the *[docs](https://docs.python.org/2/tutorial/datastructures.html)*:
> **list.insert(i, x)**
> Insert an item at a given position. The first argument is the index of the element before which to insert, so
> a.insert(0, x) inserts at the front of the list, and a.insert(len(a),
> x) is equivalent to a.append(x)... |
django best approach for creating multiple type users | 25,841,712 | 5 | 2014-09-15T06:05:05Z | 25,842,236 | 7 | 2014-09-15T06:45:22Z | [
"python",
"django"
] | I want to create multiple users in django. I want to know which method will be the best..
```
class Teachers(models.Model):
user = models.ForeignKey(User)
is_teacher = models.BooleanField(default=True)
.......
```
or should I use..
```
class Teacher(User):
is_teacher = models.BooleanField(default=Tru... | Django doesn't have multiple users - it only has one user and then based on permissions users can do different things.
So, to start off with - there is only one user type in django. If you use the default authentication framework, the model for this user is called `User`, from `django.contrib.auth.models`.
If you wan... |
Unwanted space in Python | 25,843,487 | 2 | 2014-09-15T08:13:23Z | 25,843,535 | 7 | 2014-09-15T08:16:01Z | [
"python",
"python-2.7"
] | ```
name = raw_input ("What's your name? ")
print "Hello",name, "!"
```
It returns the following:
```
What's your name? John
Hello John !
```
How do I make it so that the space between John and ! doesn't appear?
This is in Python-2.7 by the way | Use the [`str.format()` method](http://docs.python.org/2/library/stdtypes.html#str.format):
```
print "Hello {0}!".format(name)
```
> This method of string formatting is the new standard in Python 3, and should be preferred to the `%` formatting [...] in new code. |
ValueError: unsupported pickle protocol: 3, python2 pickle can not load the file dumped by python 3 pickle? | 25,843,698 | 14 | 2014-09-15T08:26:29Z | 25,843,743 | 21 | 2014-09-15T08:29:06Z | [
"python",
"python-2.7",
"python-3.x",
"pickle"
] | I use pickle to dump a file on python 3, and I use pickle to load the file on python 2, the ValueError appears.
So, python 2 pickle can not load the file dumped by python 3 pickle?
If I want it? How to do? | You should write the pickled data with a lower protocol number in Python 3. Python 3 introduced a new protocol with the number `3` (and uses it as default), so switch back to a value of `2` which can be read by Python 2.
Check the `protocol`parameter in [`pickle.dump`](https://docs.python.org/3/library/pickle.html#pic... |
ValueError: unsupported pickle protocol: 3, python2 pickle can not load the file dumped by python 3 pickle? | 25,843,698 | 14 | 2014-09-15T08:26:29Z | 25,843,801 | 13 | 2014-09-15T08:32:18Z | [
"python",
"python-2.7",
"python-3.x",
"pickle"
] | I use pickle to dump a file on python 3, and I use pickle to load the file on python 2, the ValueError appears.
So, python 2 pickle can not load the file dumped by python 3 pickle?
If I want it? How to do? | Pickle uses different `protocols` to convert your data to a binary stream.
* In python 2 there are [3 different protocols](https://docs.python.org/2/library/pickle.html#data-stream-format) (`0`, `1`, `2`) and the default is `0`.
* In python 3 there are [5 different protocols](https://docs.python.org/3/library/pickle.h... |
Unhandled exception when validating models in Django | 25,845,238 | 3 | 2014-09-15T09:51:26Z | 25,845,838 | 7 | 2014-09-15T10:22:49Z | [
"python",
"django",
"django-models"
] | I have encountered an error while compiling code for a Django web application that I am writing
In console, it shows:
```
Validating models...
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x028A2BB8>
```
The error tracking in the console up to where the error is in my program i... | You just forget to add parentheses () after `BooleanField`. So, add them:
```
userShare = models.BooleanField()
``` |
How to compare two JSON objects with the same elements in a different order equal? | 25,851,183 | 17 | 2014-09-15T15:07:56Z | 25,851,972 | 39 | 2014-09-15T15:48:33Z | [
"python",
"json",
"django",
"comparison",
"order"
] | How can I test whether two JSON objects are equal in python, disregarding the order of lists?
For example ...
JSON document **a**:
```
{
"errors": [
{"error": "invalid", "field": "email"},
{"error": "required", "field": "name"}
],
"success": false
}
```
JSON document **b**:
```
{
"s... | If you want two objects with the same elements but in a different order to compare equal, then the obvious thing to do is compare sorted copies of them - for instance, for the dictionaries represented by your JSON strings `a` and `b`:
```
import json
a = json.loads("""
{
"errors": [
{"error": "invalid", "... |
Converting pandas.tslib.Timestamp to datetime python | 25,852,044 | 3 | 2014-09-15T15:52:31Z | 35,953,204 | 9 | 2016-03-12T02:53:56Z | [
"python",
"pandas"
] | I have a `df` time series. I extracted the indexes and want to convert them each to `datetime`. How do you go about doing that? I tried to use `pandas.to_datetime(x)` but it doesn't convert it when I check after using `type()` | Just try [to\_datetime()](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.to_pydatetime.html?highlight=to_pydatetime#pandas.DatetimeIndex.to_pydatetime)
```
>>> import pandas as pd
>>> t = pd.tslib.tslib.Timestamp('2016-03-03 00:00:00')
>>> type(t)
pandas.tslib.Timestamp
>>> t.to_datetime()
... |
How to return data with 403 error in Django Rest Framework? | 25,854,595 | 2 | 2014-09-15T18:34:39Z | 25,863,424 | 7 | 2014-09-16T07:54:58Z | [
"python",
"django",
"django-rest-framework"
] | When a GET request goes to the API backend at `/obj/1`
I check a custom permissions class to see if user has access, if not, a 403 is sent back.
However, I would like to attach the object ID so the user can click a button on the front-end to request access.
My current implementation is to override the `retrieve` met... | ```
from rest_framework import permissions
from rest_framework.exceptions import PermissionDenied
class CustomPerm(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
if request.user.is_staff:
return True
raise PermissionDenied({"message":"You don't have permission to acce... |
Vectorizing / Contrasting a Dataframe with Categorical Variables | 25,857,409 | 4 | 2014-09-15T21:45:37Z | 25,857,496 | 7 | 2014-09-15T21:52:02Z | [
"python",
"pandas",
"scikit-learn",
"statsmodels"
] | Say I have a dataframe like the following:
```
A B
0 bar one
1 bar three
2 flux six
3 bar three
4 foo five
5 flux one
6 foo two
```
I would like to apply [**dummy-coding** contrasting](http://www.ats.ucla.edu/stat/sas/webbooks/reg/chapter5/sasreg5.htm) on it so that I get:
```
... | You could use [pd.factorize](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.factorize.html):
```
In [124]: df.apply(lambda x: pd.factorize(x)[0])
Out[124]:
A B
0 0 0
1 0 1
2 1 2
3 0 1
4 2 3
5 1 0
6 2 4
``` |
Django tests - patch object in all tests | 25,857,655 | 7 | 2014-09-15T22:06:10Z | 25,857,701 | 9 | 2014-09-15T22:11:04Z | [
"python",
"django",
"unit-testing",
"django-testing",
"python-mock"
] | I need to create some kind of `MockMixin` for my tests. It should include mocks for everything that calls external sources.
For example, each time I save model in admin panel I call some remote URLs. It would be good, to have that mocked and use like that:
```
class ExampleTestCase(MockedTestCase):
# tests
```
So... | According to the [`mock` documentation](http://www.voidspace.org.uk/python/mock/patch.html#mock.patch):
> Patch can be used as a TestCase class decorator. It works by
> decorating each test method in the class. This reduces the boilerplate
> code when your test methods share a common patchings set.
This basically mea... |
TypeError at / __init__() takes exactly 1 argument (2 given) | 25,858,494 | 7 | 2014-09-15T23:32:51Z | 25,862,240 | 13 | 2014-09-16T06:46:12Z | [
"python",
"django"
] | I am a bit confused why I am getting this error. I do not know where it's getting this extra argument.
```
Environment:
Request Method: GET
Request URL: http://0.0.0.0:5000/
Django Version: 1.6.4
Python Version: 2.7.5
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contentt... | Home is a class-based view. For those, you need to use the `as_view` method in your URL pattern:
```
url(r'^$', home.as_view(), name='home'),
```
See the [documentation](https://docs.djangoproject.com/en/1.7/topics/class-based-views/). |
Django 1.5 is finally insecure? | 25,859,139 | 7 | 2014-09-16T00:57:43Z | 25,859,813 | 10 | 2014-09-16T02:30:42Z | [
"python",
"django",
"security",
"versioning",
"django-1.5"
] | I am django user and using 1.5 version and almost finish developing application.
But I finally realized that whenever I read the documents of django 1.5 there is a banner on the top that 1.5 is insecure version.. Should I have to move to higher version? | The message is there because of the [Django's release process](https://docs.djangoproject.com/en/dev/internals/release-process/#supported-versions) philosophy:
> The rule of thumb is that fixes will be backported to the last major
> release for bugs that would have prevented a release in the first
> place (release blo... |
How do I set response headers in Flask? | 25,860,304 | 21 | 2014-09-16T03:42:46Z | 25,860,353 | 20 | 2014-09-16T03:49:49Z | [
"python",
"flask"
] | This is my code:
```
@app.route('/hello', methods=["POST"])
def hello():
resp = make_response()
resp.headers['Access-Control-Allow-Origin'] = '*'
return resp
```
However, when I make a request from the browser to my server I get this error:
```
XMLHttpRequest cannot load http://localhost:5000/hello.
No ... | You can do this pretty easily:
```
@app.route("/")
def home():
resp = flask.Response("Foo bar baz")
resp.headers['Access-Control-Allow-Origin'] = '*'
return resp
```
Look at [flask.Response](http://flask.pocoo.org/docs/0.10/api/#response-objects) and [flask.make\_response()](http://flask.pocoo.org/docs/0.... |
pymongo error when writing | 25,861,174 | 2 | 2014-09-16T05:20:32Z | 25,880,899 | 8 | 2014-09-17T01:30:05Z | [
"python",
"mongodb",
"pymongo"
] | I am unable to do any writes to a remote mongodb database. I am able to connect and do lookups (e.g. find). I connect like this:
```
conn = pymongo.MongoClient(db_uri,slaveOK=True)
db = conn.test_database
coll = db.test_collection
```
But when I try to insert,
```
coll.insert({'a':1})
```
I run into an error:
```
... | `AutoReconnect: not master` means that your operation is failing because the node on which you are attempting to issue the command is not the primary of a replica set, where the command (e.g., a write operation) requires that node to be a primary. Setting `slaveOK=True` just enables you to read from a secondary node, w... |
How to install Python MySQLdb module using pip? | 25,865,270 | 129 | 2014-09-16T09:31:57Z | 25,865,271 | 190 | 2014-09-16T09:31:57Z | [
"python",
"mysql",
"pip"
] | How can I install the [MySQLdb](http://mysql-python.sourceforge.net/MySQLdb.html) module for Python using pip? | It's easy to do, but hard to remember the correct spelling:
```
pip install MySQL-python
```
Note: Some dependencies might have to be in place when running the above command. Some hints on how to install these on various platforms:
## Ubuntu 14, Ubuntu 16, Debian 8.6 (jessie)
```
sudo apt-get install python-pip pyt... |
How to install Python MySQLdb module using pip? | 25,865,270 | 129 | 2014-09-16T09:31:57Z | 29,150,749 | 111 | 2015-03-19T17:05:22Z | [
"python",
"mysql",
"pip"
] | How can I install the [MySQLdb](http://mysql-python.sourceforge.net/MySQLdb.html) module for Python using pip? | Starting from a fresh Ubuntu 14.04.2 system, these two commands were needed:
```
apt-get install python-dev libmysqlclient-dev
pip install MySQL-python
```
Just doing the "pip install" by itself did not work.
From <http://codeinthehole.com/writing/how-to-set-up-mysql-for-python-on-ubuntu/> |
Explain the extra padding in struct.pack with native byte order | 25,870,816 | 2 | 2014-09-16T13:58:29Z | 25,870,945 | 7 | 2014-09-16T14:04:00Z | [
"python"
] | Can someone explain why I get extra bytes when I use native Byte order with struct.pack?
```
>>> import struct
>>> struct.pack('cI', 'a', 1)
'a\x00\x00\x00\x01\x00\x00\x00'
>>> struct.pack('<cI', 'a', 1)
'a\x01\x00\x00\x00'
```
so the native Byte order has 'a' and then 3-(00 bytes) before it. Why does the native Byt... | This is explain in the [`struct` module documentation](https://docs.python.org/2/library/struct.html):
> Note: **By default, the result of packing a given C struct includes pad bytes in order to maintain proper alignment for the C types involved;** similarly, alignment is taken into account when unpacking. This behavi... |
How to square or raise to a power (elementwise) a 2D numpy array? | 25,870,923 | 7 | 2014-09-16T14:03:17Z | 25,877,966 | 9 | 2014-09-16T20:35:01Z | [
"python",
"arrays",
"numpy"
] | I need to square a 2D numpy array (elementwise) and I have tried the following code:
```
import numpy as np
a = np.arange(4).reshape(2, 2)
print a^2, '\n'
print a*a
```
that yields:
```
[[2 3]
[0 1]]
[[0 1]
[4 9]]
```
Clearly, the notation `a*a` gives me the result I want and not `a^2`.
I would like to know if an... | The fastest way is to do `a*a` or `a**2` or `np.square(a)` whereas `np.power(a, 2)` showed to be considerably slower.
`np.power()` allows you to use different exponents for each element if instead of `2` you pass another array of exponents. From the comments of @GarethRees I just learned that this function will give y... |
Django 1.7 - How do I suppress "(1_6.W001) Some project unittests may not execute as expected."? | 25,871,261 | 35 | 2014-09-16T14:20:05Z | 25,873,547 | 9 | 2014-09-16T16:06:31Z | [
"python",
"django",
"python-2.7",
"python-2.x",
"django-1.7"
] | I have a Django application that has parts originally written in Django 1.2, and the application has been upgraded all the way up to 1.7. After upgrading to 1.7, I'm getting the following warning from `python manage.py check`:
```
System check identified some issues:
WARNINGS:
?: (1_6.W001) Some project unittests may... | You can silence individual system check warnings with the [SILENCED\_SYSTEM\_CHECKS](https://docs.djangoproject.com/en/stable/ref/settings/#std:setting-SILENCED_SYSTEM_CHECKS) setting.
Regarding your other question about how to find the reasons why this warning was triggered, the only place I could find was by looking... |
Django 1.7 - How do I suppress "(1_6.W001) Some project unittests may not execute as expected."? | 25,871,261 | 35 | 2014-09-16T14:20:05Z | 25,874,838 | 40 | 2014-09-16T17:19:12Z | [
"python",
"django",
"python-2.7",
"python-2.x",
"django-1.7"
] | I have a Django application that has parts originally written in Django 1.2, and the application has been upgraded all the way up to 1.7. After upgrading to 1.7, I'm getting the following warning from `python manage.py check`:
```
System check identified some issues:
WARNINGS:
?: (1_6.W001) Some project unittests may... | Found a [blog post](http://daniel.hepper.net/blog/2014/04/fixing-1_6-w001-when-upgrading-from-django-1-5-to-1-7/) that reveals explicitly specifying
```
TEST_RUNNER = 'django.test.runner.DiscoverRunner'
```
in `settings.py` will stop this warning from occurring. |
Django 1.7 - How do I suppress "(1_6.W001) Some project unittests may not execute as expected."? | 25,871,261 | 35 | 2014-09-16T14:20:05Z | 26,452,988 | 9 | 2014-10-19T16:57:28Z | [
"python",
"django",
"python-2.7",
"python-2.x",
"django-1.7"
] | I have a Django application that has parts originally written in Django 1.2, and the application has been upgraded all the way up to 1.7. After upgrading to 1.7, I'm getting the following warning from `python manage.py check`:
```
System check identified some issues:
WARNINGS:
?: (1_6.W001) Some project unittests may... | It looks like the developers have decided to remove this warning:
<https://code.djangoproject.com/ticket/23469> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.