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 __init__ a class method? | 28,577,378 | 5 | 2015-02-18T06:30:36Z | 28,577,485 | 8 | 2015-02-18T06:38:50Z | [
"python",
"python-2.7",
"inheritance",
"multiple-inheritance"
] | I was looking into Python's super method and multiple inheritance. I read along something like when we use super to call a base method which has implementation in all base classes, only one class' method will be called even with variety of arguments. For example,
```
class Base1(object):
def __init__(self, a):
... | As for your first question, `__init__` is neither a staticmethod nor a classmethod; it is an ordinary instance method. (That is, it receives the instance as its first argument.)
As for your second question, if you want to explicitly call multiple base class implementations, then doing it explicitly as you did is indee... |
Is __init__ a class method? | 28,577,378 | 5 | 2015-02-18T06:30:36Z | 28,577,660 | 10 | 2015-02-18T06:50:58Z | [
"python",
"python-2.7",
"inheritance",
"multiple-inheritance"
] | I was looking into Python's super method and multiple inheritance. I read along something like when we use super to call a base method which has implementation in all base classes, only one class' method will be called even with variety of arguments. For example,
```
class Base1(object):
def __init__(self, a):
... | `super()` in the face of multiple inheritance, especially on methods that are present on `object` [can get a bit tricky](https://rhettinger.wordpress.com/2011/05/26/super-considered-super/). The general rule is that if you use `super`, then *every class in the hierarchy* should use `super`. A good way to handle this fo... |
AttributeError: 'Context' object has no attribute 'wrap_socket' | 28,579,142 | 12 | 2015-02-18T08:35:41Z | 28,590,266 | 31 | 2015-02-18T17:44:14Z | [
"python",
"flask",
"openssl",
"werkzeug",
"pyopenssl"
] | I am trying to set up a Flask server that uses an OpenSSL context.
However, since I moved the script on a different server, it keeps throwing the following error, no matter if I am using Python 2.7 or 3.4 and no matter which SSL method I chose (SSLv23 / TLSv1/...):
```
File "/usr/lib/python3.4/threading.py", line 92... | As of 0.10, Werkzeug doesn't support OpenSSL contexts anymore. This decision was made because it is easier to support [`ssl.SSLContext`](https://docs.python.org/2/library/ssl.html#ssl.SSLContext) across Python versions. Your option to re-write this code is this one:
```
if __name__ == "__main__":
context = ('cert.... |
'str' object has no attribute 'decode'. Python 3 error? | 28,583,565 | 19 | 2015-02-18T12:20:05Z | 28,583,969 | 17 | 2015-02-18T12:41:35Z | [
"python",
"python-3.x",
"imaplib"
] | Here is my code:
```
import imaplib
from email.parser import HeaderParser
conn = imaplib.IMAP4_SSL('imap.gmail.com')
conn.login('[email protected]', 'password')
conn.select()
conn.search(None, 'ALL')
data = conn.fetch('1', '(BODY[HEADER])')
header_data = data[1][0][1].decode('utf-8')
```
at this point I get the erro... | You are trying to decode an object that is *already decoded*. You have a `str`, there is no need to decode from UTF-8 anymore.
Simply drop the `.decode('utf-8')` part:
```
header_data = data[1][0][1]
```
As for your `fetch()` call, you are explicitly asking for just the first message. Use a range if you want to retr... |
Anaconda python, PIL and imagingtk | 28,588,773 | 5 | 2015-02-18T16:35:07Z | 28,589,089 | 10 | 2015-02-18T16:48:53Z | [
"python",
"tkinter",
"python-imaging-library",
"anaconda"
] | Although this is a reasonably well [documented](https://github.com/ContinuumIO/anaconda-issues/issues/6) problem, I can't find a solution.
I cannot import PIL and ImageTK.
Minimal example:
```
import Tkinter as tk
from PIL import Image, ImageTk
root = tk.Tk()
image = Image.open('live.ppm')
photo = ImageTk.PhotoImag... | After uninstalling pillow and PIL:
```
pip install image
```
Fixed this issue. |
Python Facebook API - cursor pagination | 28,589,239 | 4 | 2015-02-18T16:55:11Z | 28,590,136 | 9 | 2015-02-18T17:37:15Z | [
"python",
"facebook",
"pagination"
] | My question involves learning how to retrieve my entire list of friends using Facebook's Python API. **The current result returns an object with limited number of friends and a link to the 'next' page. How do I use this to fetch the next set of friends ?** (Please post the link to possible duplicates) Any help would be... | Sadly the documentation of pagination is an open issue [since almost 2 years](https://github.com/pythonforfacebook/facebook-sdk/issues/85). You should be able to paginate like this (based on [this example](https://github.com/pythonforfacebook/facebook-sdk/commit/6169cae69949eb8948268b15c2dc21862b5cb7d8)) using [request... |
Simplify this dictionary of lists into a single list containing all/only unique values | 28,589,735 | 2 | 2015-02-18T17:17:45Z | 28,589,844 | 12 | 2015-02-18T17:23:16Z | [
"python",
"list",
"dictionary",
"list-comprehension"
] | I have a dictionary with lists as values, like this:
```
my_dict = {"a": [1, 6, 8, 4],
"b": [2, 7, 4, 9, 13],
"c": [9, 5, 6, 8, 11]
}
```
What I want is a list with one of each of the unique items in the lists from the dictionary.
So, `my_list` should be `[1, 6, 8, 4, 2, 7, 9, 13, 5, ... | Use [sets](https://docs.python.org/2/library/stdtypes.html#set-types-set-frozenset); you can produce the union of all values with:
```
set().union(*my_dict.values())
```
Demo:
```
>>> my_dict = {"a": [1, 6, 8, 4],
... "b": [2, 7, 4, 9, 13],
... "c": [9, 5, 6, 8, 11]
... }
>>> set().un... |
IOError: No space left on device - which device? | 28,590,344 | 4 | 2015-02-18T17:47:47Z | 28,593,522 | 9 | 2015-02-18T20:43:12Z | [
"python",
"flask",
"werkzeug"
] | I'm uploading a small file (8.5 Mb) to a flask test server.
When the file finishes uploading, the server reports:
```
File "/home/ubuntu/.virtualenvs/eco_app/lib/python2.7/site-packages/wtforms/form.py",
line 212, in __call__
return type.__call__(cls, *args, **kwargs)
File "/home/ubuntu/.virtuale... | @Tom Hunt's comment was on the right track.
This unix SE answer explains [what happened](http://unix.stackexchange.com/questions/60731/overflow-tmp-mounted-when-there-is-free-space-on).
> As a protection against low disc space, some daemons automatically "shadows" the current /tmp/ dir with a ram disc if the the root... |
Pandas dataframe to json without index | 28,590,663 | 9 | 2015-02-18T18:04:14Z | 28,590,865 | 16 | 2015-02-18T18:13:49Z | [
"python",
"json",
"pandas"
] | I'm trying to take a dataframe and transform it into a partcular json format.
Here's my dataframe example:
```
DataFrame name: Stops
id location
0 [50, 50]
1 [60, 60]
2 [70, 70]
3 [80, 80]
```
Here's the json format I'd like to transform into:
```
"stops":
[
{
"id": 1,
"location": [50, 50... | You can use [`orient='records'`](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.to_json.html)
```
print df.reset_index().to_json(orient='records')
[
{"id":0,"location":"[50, 50]"},
{"id":1,"location":"[60, 60]"},
{"id":2,"location":"[70, 70]"},
{"id":3,"location":"[80, 80]"}
]... |
Display username in URL - Django | 28,594,508 | 2 | 2015-02-18T21:43:16Z | 28,594,593 | 7 | 2015-02-18T21:48:30Z | [
"python",
"django",
"url",
"user",
"django-views"
] | When I try to display the username in the URL, I get this error:
Reverse for 'account\_home' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['/(?P\w+)/$'].
Here is my views.py
```
@login_required
def account_home(request, username):
u = MyUser.objects.get(username=username)
ret... | **Short answer:** The problem is with your template code. You are not passing the `username` parameter to your view. Instead of
```
<a href="{% url 'account_home' %}">Account<a>
```
try
```
<a href="{% url 'account_home' user.username %}">Account<a>
```
**Long answer**: That being said, you could probably get rid o... |
Pandas: Incrementally count occurrences in a column | 28,598,140 | 5 | 2015-02-19T03:27:28Z | 28,598,535 | 7 | 2015-02-19T04:19:02Z | [
"python",
"pandas",
"dataframe"
] | I have a DataFrame (df) which contains a 'Name' column. In a column labeled 'Occ\_Number' I would like to keep a running tally on the number of appearances of each value in 'Name'.
For example:
```
Name Occ_Number
abc 1
def 1
ghi 1
abc ... | You can use [`cumcount`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html)
to avoid a dummy column:
```
>>> df["Occ_Number"] = df.groupby("Name").cumcount()+1
>>> df
Name Occ_Number
0 abc 1
1 def 1
2 ghi 1
3 abc 2
4 abc ... |
How to convert a column or row matrix to a diagonal matrix in Python? | 28,598,572 | 4 | 2015-02-19T04:24:16Z | 28,598,619 | 11 | 2015-02-19T04:29:53Z | [
"python",
"numpy",
"matrix",
"scipy"
] | I have a row vector A, A = [a1 a2 a3 ..... an] and I would like to create a diagonal matrix, B = diag(a1, a2, a3, ....., an) with the elements of this row vector. How can this be done in Python?
**UPDATE**
This is the code to illustrate the problem:
```
import numpy as np
a = np.matrix([1,2,3,4])
d = np.diag(a)
prin... | You can use [diag](http://docs.scipy.org/doc/numpy/reference/generated/numpy.diag.html) method:
```
import numpy as np
a = np.array([1,2,3,4])
d = np.diag(a)
# or simpler: d = np.diag([1,2,3,4])
print(d)
```
Results in:
```
[[1 0 0 0]
[0 2 0 0]
[0 0 3 0]
[0 0 0 4]]
```
If you have row vector, you can do like t... |
Django Heroku Error "Your models have changes that are not yet reflected in a migration" | 28,598,676 | 8 | 2015-02-19T04:36:54Z | 28,599,499 | 16 | 2015-02-19T05:53:50Z | [
"python",
"django",
"heroku",
"django-1.7",
"django-migrations"
] | I recently added a model to my app (UserProfile) and when I pushed the changes to Heroku, I think I accidentally ran `heroku run python manage.py makemigrations`. Now when I try to run `heroku run python manage.py migrate` I get the error below
```
(leaguemaster) benjamins-mbp-2:leaguemaster Ben$ heroku run python man... | You need to first create the migrations locally, add them to your repository, commit the files with the new migrations and then push to heroku.
The sequence is something like this:
```
1. (add/modify some someapp/models.py)
2. python manage.py makemigrations someapp
3. python manage.py migrate
4. git add someapp/migr... |
How to store the values of two lists in a single dictionary where values of first list is a key and the values of second list are attributes? | 28,599,454 | 2 | 2015-02-19T05:49:31Z | 28,599,464 | 7 | 2015-02-19T05:50:52Z | [
"python",
"python-2.7",
"dictionary"
] | ```
road= []
distance=[]
i= input ('THE NUMBER OF NODES TO TEST')
for i in range(0,i):
a = input(' THE NODE NUMBER \n')
b= input ('ENTER NODE VALUE \n')
road.append(a)
distance.append(b)
print 'THE NODES AND RESPECTIVE VALUES ARE'
print "NODES: \t | \t VALUES:\n " ,words, distance
```
In ab... | Use [`zip`](https://docs.python.org/3.3/library/functions.html#zip) and [`dict`](https://docs.python.org/3.3/library/functions.html#func-dict) built-in functions.
```
dict(zip(road,distance))
```
**Example:**
```
>>> road = ['foo', 'bar']
>>> distance = [1,2]
>>> dict(zip(road,distance))
{'foo': 1, 'bar': 2}
``` |
How to pythonically have partially-mutually exclusive optional arguments? | 28,604,741 | 12 | 2015-02-19T11:07:08Z | 28,675,894 | 7 | 2015-02-23T14:20:43Z | [
"python",
"arguments",
"optional-parameters"
] | As a simple example, take a `class` [Ellipse](https://en.wikipedia.org/wiki/Ellipse) that can return its properties such as area `A`, circumference `C`, major/minor axis `a/b`, eccentricity `e`etc. In order to get that, one obviously has to provide precisely two of its parameters to obtain all the other ones, though as... | 1. Check that you have enough parameters
2. Calculate `a` from every pairing of the other parameters
3. Confirm every `a` is the same
4. Calculate `b` from every pairing of `a` and another parameter
5. Calculate the other parameters from `a` and `b`
Here's a shortened version with just `a`, `b`, `e`, and `f` that easi... |
How to pythonically have partially-mutually exclusive optional arguments? | 28,604,741 | 12 | 2015-02-19T11:07:08Z | 28,686,187 | 14 | 2015-02-24T00:24:00Z | [
"python",
"arguments",
"optional-parameters"
] | As a simple example, take a `class` [Ellipse](https://en.wikipedia.org/wiki/Ellipse) that can return its properties such as area `A`, circumference `C`, major/minor axis `a/b`, eccentricity `e`etc. In order to get that, one obviously has to provide precisely two of its parameters to obtain all the other ones, though as... | My proposal is focused on [data encapsulation](http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29) and code readability.
a) Pick pair on unambigous measurements to represent ellipse internally
```
class Ellipse(object):
def __init__(a, b):
self.a = a
self.b = b
```
b) Cr... |
Python asyncio force timeout | 28,609,534 | 5 | 2015-02-19T14:58:23Z | 28,610,066 | 11 | 2015-02-19T15:22:11Z | [
"python",
"python-asyncio"
] | Using asyncio a coroutine can be executed with a timeout so it gets cancelled after the timeout:
```
@asyncio.coroutine
def coro():
yield from asyncio.sleep(10)
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait_for(coro(), 5))
```
The above example works as expected (it times out after 5 secon... | No, you can't interrupt a coroutine unless it yields control back to the event loop, which means it needs to be inside a `yield from` call. `asyncio` is single-threaded, so when you're blocking on the `time.sleep(10)` call in your second example, there's no way for the event loop to run. That means when the timeout you... |
Use list comprehension to print out a list with words of length 4 | 28,610,568 | 3 | 2015-02-19T15:44:00Z | 28,610,585 | 11 | 2015-02-19T15:44:58Z | [
"python",
"list",
"list-comprehension"
] | I am trying to write a list comprehension that uses List1 to create a list of words of length 4.
```
List1 = ['jacob','batman','mozarella']
wordList = [words for i in range(1)]
print(wordList)
```
This prints out the wordList however with words of length higher than 4
I am looking for this program to print out ins... | You could use this list comp
```
>>> List1 = ['jacob','batman','mozarella']
>>> [i[:4] for i in List1]
['jaco', 'batm', 'moza']
```
Ref:
* `i[:4]` is a slice of the string of first 4 characters
Other ways to do it (All have their own disadvantages)
* `[re.sub(r'(?<=^.{4}).*', '', i) for i in List1]`
* `[re.match(r... |
How to get getting base_url in django template | 28,617,282 | 6 | 2015-02-19T21:29:24Z | 28,617,447 | 9 | 2015-02-19T21:39:08Z | [
"python",
"django"
] | Given a website, how would you get the HOST of that in a django template, without passing that var from the view?
```
http://google.com/hello --> {{ BASE_URL }} ==> 'http://google.com'
``` | This has been answered extensively in the following [post](http://stackoverflow.com/questions/1451138/how-can-i-get-the-domain-name-of-my-site-within-a-django-template)
There are several ways of doing it:
1. As david542 described \*\*
2. Using {{ request.get\_host }} in your template \*\*
3. Using the contrib.sites f... |
numpy.fft() what is the return value amplitude + phase shift OR angle? | 28,618,591 | 2 | 2015-02-19T22:54:37Z | 28,618,835 | 7 | 2015-02-19T23:13:44Z | [
"python",
"numpy",
"fft"
] | The np.fft.fft() returns a complex array .... what is the meaning of the complex number ?
I suppose the real part is the amplitude !
The imaginary part is phase-shift ? phase-angle ? Or something else !
I figured out the position in the array represent the frequency. | It's not really a programming question, and is not specific to `numpy`. Briefly, the absolute value of the complex number (`sqrt(x.real**2 + x.imag**2)`, or `numpy.abs()`) is the amplitude.
More detailed, when you apply FFT to an array `X` (which, say, contains a number of samples of a function `X(t)` at different val... |
What is the -H flag for pip? | 28,619,686 | 14 | 2015-02-20T00:29:42Z | 28,619,739 | 18 | 2015-02-20T00:35:13Z | [
"python",
"pip"
] | When using `sudo pip install ...` with pip version 6.0.4 or greater, I get some warnings like:
> The directory '/home/drevicko/.cache/pip/log' or its parent directory is not owned by the current user and the debug log has been disabled. Please check the permissions and owner of that directory. If executing pip with su... | The -H flag is actually for the **sudo** command and not for pip. As taken from the [docs](http://www.sudo.ws/sudo.man.html)
> The -H (HOME) option requests that the security policy set the HOME environment variable to the home directory of the target user (root by default) as specified by the password database. Depen... |
MSBUILD : error MSB3428: Could not load the Visual C++ component "VCBuild.exe" | 28,621,953 | 11 | 2015-02-20T05:04:46Z | 30,159,811 | 8 | 2015-05-11T04:43:34Z | [
"python",
"ruby",
"node.js",
"msbuild",
"node-gyp"
] | I am trying to install `nodejs` from a long time now. I tried it searching over the google but seriously i had not got any working solutions.
My first question is that
1. Why Nodejs require Microsoft Visual component?
Secondly as per suggestion on google i tried below things
* Installed Visual C++ 2010 (updated pat... | You can tell npm to use Visual studio 2010 by doing this...
```
npm install socket.io --msvs_version=2010
```
Replace socket.io with the package that is giving the issue.
It is also possible to set the global settings for npm:
```
npm config set msvs_version 2010 --global
``` |
Will a UNICODE string just containing ASCII characters always be equal to the ASCII string? | 28,627,444 | 13 | 2015-02-20T11:03:43Z | 28,627,705 | 10 | 2015-02-20T11:17:37Z | [
"python",
"python-2.7",
"unicode",
"python-unicode"
] | I noticed the following holds:
```
>>> u'abc' == 'abc'
True
>>> 'abc' == u'abc'
True
```
Will this always be true or could it possibly depend on the system locale?
(It seems strings are unicode in python 3: e.g. [this question](http://stackoverflow.com/questions/21615662/python-3-if-a-string-contains-only-ascii-is-it... | Python 2 coerces between `unicode` and `str` using the ASCII codec when comparing the two types. So yes, this is *always* true.
That is to say, unless you mess up your Python installation and use [`sys.setdefaultencoding()`](https://docs.python.org/2/library/sys.html#sys.setdefaultencoding) to change that default. You... |
Celery autodiscover_tasks not working for all Django 1.7 apps | 28,628,868 | 7 | 2015-02-20T12:19:54Z | 38,628,748 | 8 | 2016-07-28T06:36:16Z | [
"python",
"django",
"celery"
] | I have a Django 1.7 project with Celery 3.1. All the apps in my Django project work with the new AppConfig. The problem is that not all the tasks are found with `autodiscover_tasks`:
```
app.autodiscover_tasks(settings.INSTALLED_APPS)
```
If i use autodiscover\_tasks like this it wil work:
```
app.autodiscover_tasks... | This is discussed in a number of Celery issues, such as [#2596](https://github.com/celery/celery/issues/2596) and [#2597](https://github.com/celery/celery/pull/2597).
If you are using Celery 3.x, the fix is to use:
```
from django.apps import apps
app.autodiscover_tasks(lambda: [n.name for n in apps.get_app_configs()... |
Why str(reversed(...)) doesn't give me the reversed string? | 28,632,804 | 3 | 2015-02-20T15:41:49Z | 28,632,838 | 7 | 2015-02-20T15:43:41Z | [
"python",
"string",
"list",
"iterator"
] | I'm trying to get used to iterators. Why if I type
```
b = list(reversed([1,2,3,4,5]))
```
It will give me a reversed list, but
```
c = str(reversed('abcde'))
```
won't give me a reversed string? | In Python, [`reversed`](https://docs.python.org/3/library/functions.html#reversed) actually returns a reverse iterator. So, [`list`](https://docs.python.org/3/library/functions.html#func-list) applied on the iterator will give you the list object.
In the first case, input was also a list, so the result of `list` appli... |
How to handle FileNotFoundError when "try .. except IOError" does not catch it? | 28,633,555 | 5 | 2015-02-20T16:21:19Z | 28,633,573 | 7 | 2015-02-20T16:23:02Z | [
"python",
"exception",
"python-3.x",
"try-catch"
] | How can I catch an error on python 3? I've googled a lot but none of the answers seem to be working. The file open.txt doesn't exist so it should print e.errno.
This is what I tried now:
This is in my defined function
```
try:
with open(file, 'r') as file:
file = file.read()
return file.encode('U... | `FileNotFoundError` is a subclass of `OSError`, catch that or the exception itself:
```
except OSError as e:
```
Operating System exceptions have been reworked in Python 3.3; `IOError` has been merged into `OSError`. See the [*PEP 3151: Reworking the OS and IO exception hierarchy* section](https://docs.python.org/3/w... |
Pandas unstack problems: ValueError: Index contains duplicate entries, cannot reshape | 28,651,079 | 9 | 2015-02-21T20:40:22Z | 28,652,153 | 10 | 2015-02-21T22:29:20Z | [
"python",
"pandas"
] | I am trying to unstack a multi-index with pandas and I am keep getting:
```
ValueError: Index contains duplicate entries, cannot reshape
```
Given a dataset with four columns:
* id (string)
* date (string)
* location (string)
* value (float)
I first set a three-level multi-index:
```
In [37]: e.set_index(['id', 'd... | Here's an example DataFrame which show this, it has duplicate values with the same index. The question is, do you want to aggregate these or keep them as multiple rows?
```
In [11]: df
Out[11]:
0 1 2 3
0 1 2 a 16.86
1 1 2 a 17.18
2 1 4 a 17.03
3 2 5 b 17.28
In [12]: df.pivot_table(values=3, ... |
how to plot histograms from dataframes in pandas | 28,654,003 | 6 | 2015-02-22T03:00:17Z | 28,654,419 | 7 | 2015-02-22T04:06:39Z | [
"python",
"matplotlib",
"pandas"
] | I have a simple dataframe in pandas that has two numeric columns. I want to make a histogram out of the columns using matplotlib through pandas. The example below does not work:
```
In [6]: pandas.__version__
Out[6]: '0.14.1'
In [7]: df
Out[7]:
a b
0 1 20
1 2 40
2 3 30
3 4 30
4 4 3
5 3 5
In [8]: ... | `DataFrame` has its own `hist` method:
```
df =pd.DataFrame({'col1':np.random.randn(100),'col2':np.random.randn(100)})
df.hist(layout=(1,2))
```
draws a histogram for each valid column of the `data frame`.
 |
pandas convert some columns into rows | 28,654,047 | 5 | 2015-02-22T03:08:28Z | 28,654,127 | 15 | 2015-02-22T03:21:24Z | [
"python",
"pandas"
] | So my dataset has some information by location for n dates. The problem is each date is actually a different column header. For example the CSV looks like
```
location name Jan-2010 Feb-2010 March-2010
A "test" 12 20 30
B "foo" 18 20 25
```
What I... | You can use [`pd.melt`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html) to get most of the way there, and then sort:
```
>>> df
location name Jan-2010 Feb-2010 March-2010
0 A test 12 20 30
1 B foo 18 20 25
>>> df2 = pd.melt(df... |
Plot the whole pandas DataFrame with Bokeh | 28,655,096 | 4 | 2015-02-22T06:07:46Z | 28,662,599 | 7 | 2015-02-22T20:03:53Z | [
"python",
"pandas",
"bokeh"
] | I would like to plot a whole pandas DataFrame with Bokeh. I.e., I am looking for a Bokeh equivalent of the third line:
```
import pandas as pd
income_df = pd.read_csv("income_2013_dollars.csv", sep='\t', thousands=',')
income_df.plot(x="year")
```
Is there currently a way to do that, or do I have to pass each y-value... | You may find the charts examples useful: <https://github.com/bokeh/bokeh/tree/master/examples/charts>
If you wanted a bar chart it would be:
```
from bokeh.charts import Bar
Bar(income_df, notebook=True).show() # assuming the index is corretly set on your df
```
You may want a `Line` or `TimeSeries` which work simi... |
Dangers of sys.setdefaultencoding('utf-8') | 28,657,010 | 17 | 2015-02-22T10:55:25Z | 29,561,747 | 10 | 2015-04-10T12:42:30Z | [
"python",
"python-2.7",
"encoding",
"utf-8"
] | There is a trend of discouraging setting `sys.setdefaultencoding('utf-8')` in Python 2. Can anybody list real examples of problems with that? Arguments like `it is harmful` or `it hides bugs` don't sound very convincing.
**UPDATE**: Please note that this question is only about `utf-8`, it is not about changing default... | Because you don't always *want* to have your strings automatically decoded to Unicode, or for that matter your Unicode objects automatically encoded to bytes. Since you are asking for a concrete example, here is one:
Take a WSGI web application; you are building a response by adding the product of an external process ... |
Dangers of sys.setdefaultencoding('utf-8') | 28,657,010 | 17 | 2015-02-22T10:55:25Z | 29,832,646 | 9 | 2015-04-23T19:27:47Z | [
"python",
"python-2.7",
"encoding",
"utf-8"
] | There is a trend of discouraging setting `sys.setdefaultencoding('utf-8')` in Python 2. Can anybody list real examples of problems with that? Arguments like `it is harmful` or `it hides bugs` don't sound very convincing.
**UPDATE**: Please note that this question is only about `utf-8`, it is not about changing default... | The original poster asked for code which demonstrates that the switch is harmfulâ*except* that it "hides" bugs unrelated to the switch.
## Summary of conclusions
Based on both experience and evidence I've collected, here are the conclusions I've arrived at.
1. Setting the defaultencoding to UTF-8 nowadays is **saf... |
How to count the occurrence of certain item in an ndarray in Python? | 28,663,856 | 20 | 2015-02-22T22:05:48Z | 28,663,910 | 33 | 2015-02-22T22:10:25Z | [
"python",
"numpy",
"multidimensional-array",
"count"
] | In Python, I have an ndarray `y`
that is printed as `array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])`
I'm trying to count how many 0 and how many 1 are there in this array.
But when I type `y.count(0)` or `y.count(1)`, it says `'numpy.ndarray'` object has no attribute 'count'
What should I do? | Use [`collections.Counter`](https://docs.python.org/2/library/collections.html#collections.Counter);
```
>> import collections, numpy
>>> a = numpy.array([0, 3, 0, 1, 0, 1, 2, 1, 0, 0, 0, 0, 1, 3, 4])
>>> collections.Counter(a)
Counter({0: 7, 1: 4, 3: 2, 2: 1, 4: 1})
```
Thanks to [@ali\_m](http://stackoverflow.com/... |
How to count the occurrence of certain item in an ndarray in Python? | 28,663,856 | 20 | 2015-02-22T22:05:48Z | 28,664,837 | 8 | 2015-02-22T23:45:06Z | [
"python",
"numpy",
"multidimensional-array",
"count"
] | In Python, I have an ndarray `y`
that is printed as `array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])`
I'm trying to count how many 0 and how many 1 are there in this array.
But when I type `y.count(0)` or `y.count(1)`, it says `'numpy.ndarray'` object has no attribute 'count'
What should I do? | For your case you could also look into [numpy.bincount](http://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html)
```
In [56]: a = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])
In [57]: np.bincount(a)
Out[57]: array([8, 4]) #count of zeros is at index 0 : 8
#count of ones is a... |
How to count the occurrence of certain item in an ndarray in Python? | 28,663,856 | 20 | 2015-02-22T22:05:48Z | 35,549,699 | 20 | 2016-02-22T09:14:18Z | [
"python",
"numpy",
"multidimensional-array",
"count"
] | In Python, I have an ndarray `y`
that is printed as `array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])`
I'm trying to count how many 0 and how many 1 are there in this array.
But when I type `y.count(0)` or `y.count(1)`, it says `'numpy.ndarray'` object has no attribute 'count'
What should I do? | What about using `numpy.count_nonzero`, something like
```
>>> y = np.random.randint(4, size=15)
>>> y
array([1, 2, 2, 2, 2, 0, 2, 3, 3, 3, 0, 0, 2, 2, 0])
>>> type(y)
<class 'numpy.ndarray'>
>>>
>>>
>>> np.count_nonzero(y == 0)
4
>>> np.count_nonzero(y == 1)
1
>>> np.count_nonzero(y == 2)
7
``` |
How to count the occurrence of certain item in an ndarray in Python? | 28,663,856 | 20 | 2015-02-22T22:05:48Z | 37,060,037 | 10 | 2016-05-05T20:51:53Z | [
"python",
"numpy",
"multidimensional-array",
"count"
] | In Python, I have an ndarray `y`
that is printed as `array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])`
I'm trying to count how many 0 and how many 1 are there in this array.
But when I type `y.count(0)` or `y.count(1)`, it says `'numpy.ndarray'` object has no attribute 'count'
What should I do? | Personally, I'd go for:
`(y == 0).sum()` and `(y == 1).sum()`
E.g.
```
import numpy as np
y = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])
num_zeros = (y == 0).sum()
num_ones = (y == 1).sum()
``` |
Deploying Django with gunicorn No module named ImportError: No module named validation | 28,664,535 | 3 | 2015-02-22T23:12:22Z | 30,815,009 | 8 | 2015-06-13T04:15:36Z | [
"python",
"django",
"python-2.7",
"nginx",
"gunicorn"
] | I m trying to deploy my Django project with using nginx, gunicorn and virtualenv. But i m getting following error while run this comment
```
sudo gunicorn_django --bind test.com:8001
```
Log :
```
Traceback (most recent call last):
File "/opt/postjust/lib/python2.7/site-packages/gunicorn/arbiter.py", line 503, in ... | Changing `gunicorn_django` to `gunicorn newApp.wsgi:application` should fix this.
Using `gunicorn_django` is no longer recommended. This is because it calls `django_wsgi.py` which is deprecated and throws the import error.
More info:
<http://www.rkblog.rk.edu.pl/w/p/first-impressions-django-17-beta-upgrade-young-proj... |
How to create global lock/semaphore with multiprocessing.pool in Python? | 28,664,720 | 7 | 2015-02-22T23:33:28Z | 28,721,419 | 7 | 2015-02-25T14:21:56Z | [
"python",
"python-multiprocessing"
] | I want limit resource access in children processes. For example - limit **http downloads**, **disk io**, etc.. How can I achieve it expanding this basic code?
Please share some basic code examples.
```
pool = multiprocessing.Pool(multiprocessing.cpu_count())
while job_queue.is_jobs_for_processing():
for job in job_... | Use the initializer and initargs arguments when creating a pool so as to define a global in all the child processes.
For instance:
```
from multiprocessing import Pool, Lock
from time import sleep
def do_job(i):
"The greater i is, the shorter the function waits before returning."
with lock:
sleep(1-(... |
Python Requests getting SSLerror | 28,667,684 | 5 | 2015-02-23T05:58:38Z | 28,667,850 | 11 | 2015-02-23T06:14:59Z | [
"python",
"ssl",
"ssl-certificate",
"python-requests"
] | Trying to make a simple get request using Requests session but I keep getting SSLerror for a specific site. I think maybe the problem is with the site (I did a scan using <https://www.ssllabs.com>, results are down bellow), but I cant be sure because I have no knowledge in this area :) I would sure like to understand w... | The certificate itself for www.reporo.com (not reporo.com) is valid, but it is missing a chain certificate as shown in the report by [ssllabs](https://www.ssllabs.com/ssltest/analyze.html?d=reporo.com&s=198.12.15.168):
```
Chain issues Incomplete
....
2 Extra download Thawte DV SSL CA
Fingerprint: 3ca958f3e7d68... |
Can't install pip packages inside a docker container with Ubuntu | 28,668,180 | 20 | 2015-02-23T06:41:46Z | 31,806,938 | 17 | 2015-08-04T10:32:51Z | [
"python",
"docker",
"pip",
"fig"
] | I'm following the [fig guide](http://www.fig.sh/index.html) to using docker with a python application, but when docker gets up to the command
```
RUN pip install -r requirements.txt
```
I get the following error message:
```
Step 3 : RUN pip install -r requirements.txt
---> Running in fe0b84217ad1
Collecting blinke... | Your problem comes from the fact that Docker is not using the proper DNS server.
You can fix it in three different ways :
# 1. Adding Google DNS to your local config
Modifying /etc/resolv.conf and adding the following lines at the end
`# Google IPv4 nameservers
nameserver 8.8.8.8
nameserver 8.8.4.4`
If you want to ... |
How to print variables without spaces between values | 28,669,459 | 7 | 2015-02-23T08:21:27Z | 28,669,484 | 15 | 2015-02-23T08:23:45Z | [
"python",
"whitespace",
"python-2.x"
] | I would like to know how to remove additional spaces when I print something.
Like when I do:
```
print 'Value is "', value, '"'
```
The output will be:
```
Value is " 42 "
```
But I want:
```
Value is "42"
```
Is there any way to do this? | Don't use `print ...,` if you don't want spaces. Use string concatenation or formatting.
Concatenation:
```
print 'Value is "' + str(value) + '"'
```
Formatting:
```
print 'Value is "{}"'.format(value)
```
The latter is far more flexible, see the [`str.format()` method documentation](https://docs.python.org/2/libr... |
Python socket client Post parameters | 28,670,835 | 2 | 2015-02-23T09:47:29Z | 28,671,231 | 7 | 2015-02-23T10:08:45Z | [
"python",
"sockets",
"http",
"post"
] | Fir let me clear **I don't want to to use higher level APIs, I only want to use socket programming**
I have wrote following program to connect to server using POST request.
```
import socket
import binascii
host = "localhost"
port = 9000
message = "POST /auth HTTP/1.1\r\n"
parameters = "userName=Ganesh&password=pass... | This line `finalMessage = binascii.a2b_qp(finalMessage)` is certainly wrong, so you should remove the line completely, another problem is that there is no new-line missing after `Content-Length`. In this case the request sent to the socket is (I am showing the `CR` and `LF` characters here as `\r\n`, but also splitting... |
How to read constituency based parse tree | 28,674,417 | 4 | 2015-02-23T13:00:45Z | 28,674,667 | 7 | 2015-02-23T13:14:37Z | [
"python",
"parsing",
"nlp",
"parse-tree"
] | I have a corpus of sentences that were preprocessed by Stanford's [CoreNLP](http://nlp.stanford.edu/software/corenlp.shtml) systems. One of the things it provides is the sentence's Parse Tree (Constituency-based). While I can understand a parse tree when it's drawn (like a tree), I'm not sure how to read it in this for... | `NLTK` has a class for reading parse trees: `nltk.tree.Tree`. The relevant method is called `fromstring`. You can then iterate its subtrees, leaves, etc...
As an aside: you might want to remove the bit that says `sent28:` as it confuses the parser (it's also not a part of the sentence). You are not getting a full pars... |
Calculate new value based on decreasing value | 28,676,916 | 14 | 2015-02-23T15:13:16Z | 28,677,342 | 8 | 2015-02-23T15:33:54Z | [
"python",
"pandas"
] | **Problem:**
What'd I like to do is step-by-step reduce a value in a `Series` by a continuously decreasing base figure.
I'm not sure of the terminology for this - I did think I could do something with `cumsum` and `diff` but I think I'm leading myself on a wild goose chase there...
**Starting code:**
```
import pan... | Your idea with `cumsum` and `diff` works. It doesn't look too complicated; not sure if there's an even shorter solution. First, we compute the cumulative sum, operate on that, and then go back (`diff` is kinda sorta the inverse function of `cumsum`).
```
import math
c = values.cumsum() - ALLOWANCE
# now we've got [-1... |
Calculate new value based on decreasing value | 28,676,916 | 14 | 2015-02-23T15:13:16Z | 28,677,358 | 8 | 2015-02-23T15:34:31Z | [
"python",
"pandas"
] | **Problem:**
What'd I like to do is step-by-step reduce a value in a `Series` by a continuously decreasing base figure.
I'm not sure of the terminology for this - I did think I could do something with `cumsum` and `diff` but I think I'm leading myself on a wild goose chase there...
**Starting code:**
```
import pan... | Following your initial idea of `cumsum` and `diff`, you could write:
```
>>> (values.cumsum() - ALLOWANCE).clip_lower(0).diff().fillna(0)
0 0
1 0
2 20
3 30
dtype: float64
```
This is the cumulative sum of `values` minus the allowance. Negative values are clipped to zeros (since we don't care about numbe... |
Use TLS and Python for authentication | 28,677,455 | 7 | 2015-02-23T15:39:58Z | 28,682,511 | 13 | 2015-02-23T20:09:48Z | [
"python",
"authentication",
"ssl",
"twisted"
] | I want to make a little update script for a software that runs on a Raspberry Pi and works like a local server. That should connect to a master server in the web to get software updates and also to verify the license of the software.
For that I set up two python scripts. I want these to connect via a TLS socket. Then t... | In a word: **yes**, this is quite possible, and all the necessary stuff is
ported to python 3 - I tested all the following under Python 3.4 on my Mac and it seems to
work fine.
The short answer is
"[use `twisted.internet.ssl.Certificate.peerFromTransport`](http://twistedmatrix.com/documents/15.0.0/api/twisted.internet... |
Read every fourth line in Python | 28,677,539 | 2 | 2015-02-23T15:44:04Z | 28,677,613 | 7 | 2015-02-23T15:47:49Z | [
"python"
] | I have a file where I am trying to read (and write to another file) every fourth line. The solution I'm using doesn't give the desired outcome.
**sample.txt**
`line1
line2
line3
line4
line5
line6
line7
line8
line9
line10`
**script.py**
```
from itertools import islice
with open('sample.txt') as fin, open('output.txt... | You're almost there. [`islice`](https://docs.python.org/2/library/itertools.html#itertools.islice) comes with a `start` parameter. In your case, it's the second one, that you've set to `None`. Try this:
```
fout.writelines(islice(fin,3,None,4)) # line with index 3 is the fourth line
``` |
Why isn't PyCharm's autocomplete working for libraries I install? | 28,677,670 | 7 | 2015-02-23T15:51:01Z | 28,679,116 | 20 | 2015-02-23T16:59:46Z | [
"python",
"pycharm"
] | PyCharm's autocomplete isn't working for installed libraries. I have the following code:
```
from boto.emr.connection import EmrConnection
conn = EmrConnection(aws_keys.access_key_id, aws_keys.secret_key)
```
I want the editor to tell me what methods I have available to me when I press `ctrl``space`.
The boto librar... | You've installed the 3rd-party library into a virtualenv, but PyCharm doesn't know about that by default. If nothing is specified, it will choose the system Python install as the interpreter. You need to go into the project settings and configure the interpreter to point at the virtualenv. PyCharm will then index the i... |
How do I inspect one specific object in IPython | 28,678,438 | 5 | 2015-02-23T16:28:39Z | 28,678,554 | 11 | 2015-02-23T16:34:08Z | [
"python",
"ipython"
] | I'm coming from MATLAB and am used to the `whos` command to get variable information such as shape and data type and often used this with a specific names (e.g., `whos Var1`).
I know I can use `whos` in IPython as well; however, when I have a ton of variables and objects I'd like to be able to inspect one at a time an... | The command `whos` and linemagic `%whos` are available in IPython, but are not part of standard Python. Both of these will list current variables, along with some information about them. You can specify a `type` to filter by, e.g.
```
whos
Variable Type Data/Info
----------------------------
a list n=... |
How to drop rows from pandas data frame that contains a particular string in a particular column? | 28,679,930 | 9 | 2015-02-23T17:43:01Z | 28,680,078 | 16 | 2015-02-23T17:49:32Z | [
"python",
"pandas"
] | I have a very large data frame in python and I want to drop all rows that have a particular string inside a particular column.
For example, I want to drop all rows which have the string "XYZ" as a substring in the column C of the data frame.
Can this be implemented in an efficient way using .drop() method? | pandas has vectorized string operations, so you can just filter out the rows that contain the string you don't want:
```
In [91]: df = pd.DataFrame(dict(A=[5,3,5,6], C=["foo","bar","fooXYZbar", "bat"]))
In [92]: df
Out[92]:
A C
0 5 foo
1 3 bar
2 5 fooXYZbar
3 6 bat
In [93]: df[d... |
How can I get the 3rd Friday of a month in Python? | 28,680,896 | 6 | 2015-02-23T18:36:45Z | 28,681,097 | 17 | 2015-02-23T18:48:21Z | [
"python",
"python-2.7",
"date"
] | I'm trying to get stock data from Yahoo! Finance using Python 2.7.9, but I only need data for the 3rd Friday of the month. I have a function to get the data, but need a way to get the dates. I want something like this:
```
def get_third_fris(how_many):
# code and stuff
return list_of_fris
```
So that calling ... | You can use the [`calendar`](https://docs.python.org/3/library/calendar.html) module to list weeks, then grab the Friday of that week.
```
import calendar
c = calendar.Calendar(firstweekday=calendar.SUNDAY)
year = 2015; month = 2
monthcal = c.monthdatescalendar(year,month)
third_friday = [day for week in monthcal f... |
override python function-local variable in unittest | 28,688,057 | 6 | 2015-02-24T04:16:09Z | 28,688,135 | 7 | 2015-02-24T04:24:07Z | [
"python",
"mocking",
"unit-testing"
] | I have a method in python (2.7) that does foo, and gives up after 5 minutes if foo didn't work.
```
def keep_trying(self):
timeout = 300 #empirically derived, appropriate timeout
end_time = time.time() + timeout
while (time.time() < end_time):
result = self.foo()
if (result == 'success'):
... | Rather than trying to mock the value if `timeout`, you'll want to mock the return value of `time.time()`.
e.g.
```
@patch.object(time, 'time')
def test_keep_trying(self, mock_time):
mock_time.side_effect = iter([100, 200, 300, 400, 500, 600, 700, 800])
...
```
Now the first time `time.time()` is called, you'... |
ImportError at / No module named quickstart in django rest framework | 28,688,556 | 4 | 2015-02-24T05:09:59Z | 28,688,619 | 9 | 2015-02-24T05:15:31Z | [
"python",
"django",
"django-rest-framework"
] | i am getting error when i try tutorial in <http://www.django-rest-framework.org/tutorial/quickstart/>
error like this:
```
Traceback:
File "/home/apsijogja/drfdjango/end/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
98. resolver_match = resolver.resolve(request.pat... | You shouldn't use the `drf` project name for importing from `quickstart` app. Import like this:
```
from quickstart import views
``` |
Nginx Django and Gunicorn. Gunicorn sock file is missing? | 28,689,445 | 3 | 2015-02-24T06:27:12Z | 28,827,138 | 12 | 2015-03-03T08:26:32Z | [
"python",
"django",
"python-2.7",
"nginx",
"gunicorn"
] | I have an ansible provisioned VM based on this one <https://github.com/jcalazan/ansible-django-stack> but for some reason trying to start Gunicorn gives the following error:
> Can't connect to /path/to/my/gunicorn.sock
and in nginx log file:
> connect() to unix:/path/to/my/gunicorn.sock failed (2: No such file or di... | Well, since I don't have enough rep to comment, I'll mention here that there is not a lot of specificity suggested by the missing socket, but I can tell you a bit about how I started in your shoes and got things to work.
The long and short of it is that gunicorn has encountered a problem when run by upstart and either... |
Using GPU despite setting CPU_Only, yielding unexpected keyword argument | 28,692,209 | 8 | 2015-02-24T09:33:33Z | 28,979,649 | 12 | 2015-03-11T06:02:18Z | [
"python",
"caffe"
] | I'm installing Caffe on an Ubuntu 14.04 virtual server with CUDA installed (without driver) using <https://github.com/BVLC/caffe/wiki/Ubuntu-14.04-VirtualBox-VM> as inspiration. During the installation process I edited the MakeFile to include `"CPU_ONLY := 1"` before building it. However, it seems that Caffe is still t... | I'm gonna add a few words to Mailerdaimon's answer.
I followed the installation guide (<https://github.com/BVLC/caffe/wiki/Ubuntu-14.04-VirtualBox-VM>) to setup Caffe in my vagrant virtual machine. FYI, virtual machines DO NOT support GPU accelerating. Back to the point, after I fix 'CPU / GPU switch in example script... |
pylint says "Unnecessary parens after %r keyword" | 28,694,380 | 7 | 2015-02-24T11:17:34Z | 28,694,569 | 12 | 2015-02-24T11:26:42Z | [
"python",
"python-2.7",
"python-3.x"
] | After my [first CodeReview Q](http://codereview.stackexchange.com/questions/61798/mysql-class-to-add-user-database) - I got tip in answer:
> Your code appears to be for Python 2.x. To be a bit more ready for a possible future migration to Python 3.x, I recommend to start writing your print ... statements as print(...)... | To make pylint aware that you want to use the new print statement and not put erroneous brackets simply use
```
from __future__ import print_function
```
at the beginning of your script. This has also the advantage that you **always** need to use `print(...)` instead of `print ...`. Accordingly, your program will thr... |
Log Normal Random Variables with Scipy | 28,700,694 | 4 | 2015-02-24T16:10:05Z | 28,701,211 | 7 | 2015-02-24T16:34:50Z | [
"python",
"scipy"
] | I fail to understand the very basics of creating lognormal variables as documented [here](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.lognorm.html).
[The log normal distribution takes on mean and variance as parameters](http://en.wikipedia.org/wiki/Log-normal_distribution). I would like to create a... | # The mystery is solved (edit 3)
* μ corresponds to `ln(scale)` (!)
* Ï corresponds to shape (`s`)
* `loc` is not needed for setting any of Ï and μ
I think it is a severe problem that this is not clearly documented. I guess many have fallen for this when doing simple tests with the lognormal distribution in SciPy... |
Why is ,,b = 1,2,3 parsed as (',b', '=', '1,2,3') in IPython? | 28,700,883 | 8 | 2015-02-24T16:19:00Z | 28,701,044 | 7 | 2015-02-24T16:27:03Z | [
"python",
"ipython"
] | I've noticed that IPython has some very strange parsing behaving for syntax that isn't legal Python.
```
In [1]: ,,b = 1,2,3
Out[1]: (',b', '=', '1,2,3')
```
There's something similar going on with semicolons, but it's not splitting into a tuple.
```
In [4]: ;;foo = 1;2;3
Out[4]: ';foo = 1;2;3'
```
Whilst it looks ... | It's a convenience method for forcing the quotation, see the docs: <http://ipython.org/ipython-doc/2/interactive/reference.html>
From the docs:
> You can force automatic quoting of a functionâs arguments by using ,
> or ; as the first character of a line. For example:
```
In [1]: ,my_function /home/me # becomes m... |
Dicts in Python | 28,701,878 | 4 | 2015-02-24T17:04:50Z | 28,701,956 | 7 | 2015-02-24T17:08:21Z | [
"python",
"dictionary"
] | I have a multidimensionnal dict, I need to return a specific value.
```
ConsomRatio={"DAP_Local":[],"MAP11_52":[]}
ConsomRatio["DAP_Local"].append({"Ammonia":"0.229", "Amine":"0.0007"})
ConsomRatio["MAP11_52"].append({"Ammonia":"0.138", "Fuel":"0.003"})
print(ConsomRatio["DAP_Local"])
```
The result of the print is:... | You can get to it like this. You're appending your `dict` to a `list`, so you must select the correct index in the `list` where the `dict` is located. In this case the first element in the list or index `0`.
```
ConsomRatio["DAP_Local"][0]["Ammonia"]
```
By the way, depending on what you are trying to achieve you mig... |
Why do some methods use dot notation and others don't? | 28,703,834 | 4 | 2015-02-24T18:49:04Z | 28,703,945 | 7 | 2015-02-24T18:55:20Z | [
"python",
"methods",
"dot-notation"
] | So, I'm just beginning to learn Python (using Codecademy), and I'm a bit confused.
Why are there some methods that take an argument, and others use the dot notation?
len() takes an arugment, but won't work with the dot notation:
```
>>> len("Help")
4
>>>"help".len()
Traceback (most recent call last):
File "<stdin>... | The key word here is method. There is a slight difference between a function and a method.
### Method
Is a function that is defined in the class of the given object. For example:
```
class Dog:
def bark(self):
print 'Woof woof!'
rufus = Dog()
rufus.bark() # called from the object
```
### Function
A fu... |
In Python how to obtain a partial view of a dict? | 28,704,526 | 7 | 2015-02-24T19:27:41Z | 28,704,691 | 9 | 2015-02-24T19:36:06Z | [
"python",
"python-2.7",
"dictionary"
] | Is it possible to get a partial view of a `dict` in Python analogous of pandas `df.tail()/df.head()`. Say you have a very long `dict`, and you just want to check some of the elements (the beginning, the end, etc) of the `dict`. Something like:
```
dict.head(3) # To see the first 3 elements of the dictionary.
{[1,2],... | Kinda perverted desire, but you can get that by using this
```
dict(islice(mydict.iteritems(), 0, 2))
```
or for short dictionaries
```
# Python 2.x
dict(mydict.items()[0:2])
# Python 3.x
dict(list(mydict.items())[0:2])
``` |
PyCharm error: 'No Module' when trying to import own module (python script) | 28,705,029 | 24 | 2015-02-24T19:53:53Z | 35,553,721 | 25 | 2016-02-22T12:29:37Z | [
"python",
"module",
"pycharm"
] | I have written a module (a file `my_mod.py` file residing in the folder `my_module`).
Currently, I am working in the file `cool_script.py` that resides in the folder `cur_proj`. I have opened the folder in PyCharm using File -- open (and I assume, hence, it is a PyCharm project).
In ProjectView (CMD-7), I can see my p... | If your own module is in the same path you need mark the path as Sources Root. Click with mouse right button in the directory that you want import. Then select **Mark Directory As** and select **Sources Root**.
*I hope it help.* |
Python subclassing process with constructor | 28,711,396 | 4 | 2015-02-25T04:54:04Z | 28,711,506 | 7 | 2015-02-25T05:03:08Z | [
"python",
"class",
"constructor",
"multiprocessing"
] | I'm trying to create a object as a new process. If I give a constructor to the class, program is showing an error.
**Code**
```
import multiprocessing as mp
import time
class My_class(mp.Process):
def __init__(self):
self.name = "Hello "+self.name
self.num = 20
def run(self):
... | When you add your own `__init__()` here, you are *overriding* the `__init__()` in the superclass. However, the superclass often (as in this case) has some stuff it needs in its `__init__()`. Therefore, you either have to re-create that functionality (e.g. initializing `_popen` as described in your error, among other th... |
Composite primary key in django | 28,712,848 | 13 | 2015-02-25T06:45:38Z | 28,712,960 | 16 | 2015-02-25T06:54:28Z | [
"python",
"django",
"postgresql"
] | I have a legacy db table which has composite primary key. I don't think I will be able to change the structure to include a surrogate key, as there is some code written that uses that table. And in django, I cannot use that table, as it doesn't have a primary key(non-composite).
Do django models support composite prim... | Try similar below code:
```
class MyTable(models.Model):
class Meta:
unique_together = (('key1', 'key2'),)
key1 = models.IntegerField(primary_key=True)
key2 = models.IntegerField()
```
or if you want only unique mixed fields:
```
class MyTable(models.Model):
class Meta:
unique_togeth... |
How to implement `Unary function chainer` using python? | 28,713,934 | 3 | 2015-02-25T07:58:26Z | 28,714,069 | 7 | 2015-02-25T08:07:26Z | [
"python"
] | I am doing codewar, i can't win this changell.
Here is the link:
<http://www.codewars.com/kata/54ca3e777120b56cb6000710/train/python>
This is my implemt, but there is an error 'TypeError: 'generator' object is not callable
':
```
def chained(functions):
for f in functions:
yield f
def f1(x): return x*2
d... | Instead of returning a generator, you need to return a function, which takes one parameter and applies it to each chained function.
Your calling syntax is:
```
chained([f1, f2, f3])(0)
```
This means you want `chained` to return something you can call with a single parameter. A function will do fine.
A function whi... |
How do I switch to the active tab in Selenium? | 28,715,942 | 6 | 2015-02-25T09:56:53Z | 28,716,311 | 9 | 2015-02-25T10:14:53Z | [
"python",
"selenium",
"google-chrome-extension"
] | We developed a Chrome extension, and I want to test our extension with Selenium. I created a test, but the problem is that our extension opens a new tab when it's installed, and I think I get an exception from the other tab. Is it possible to switch to the active tab I'm testing? Or another option is to start with the ... | Some possible approaches:
**1** - Switch between the tabs using the send\_keys (CONTROL + TAB)
```
self.driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)
```
**2** - Switch between the tabs using the using ActionsChains (CONTROL+TAB)
```
actions = ActionChains(self.driver)
actions.key... |
Error while fetching Tweets with Tweepy | 28,717,249 | 2 | 2015-02-25T11:00:36Z | 28,723,758 | 7 | 2015-02-25T16:04:36Z | [
"python",
"mongodb",
"twitter",
"tweepy"
] | I have a Python script that fetch tweets. In the script i use the libary **Tweepy** . I use a valid authentication parameters. After running this script some tweets are stored in my MongoDB and some are refused by the if statement. But still i get the error
```
requests.packages.urllib3.exceptions.ProtocolError: ('Co... | This `IncompleteRead` error generally tends to occur when your consumption of incoming tweets [starts to fall behind](https://github.com/tweepy/tweepy/issues/448), which makes sense in your case given your long list of terms to track. The general approach most people seem to be taking (myself included) is simply to sup... |
Select -> option abstraction | 28,723,419 | 9 | 2015-02-25T15:50:10Z | 28,736,559 | 16 | 2015-02-26T07:19:11Z | [
"python",
"testing",
"selenium",
"selenium-webdriver",
"protractor"
] | In Python, Java and several other selenium bindings, there is a very convenient abstraction over `select->option` HTML constructions, a [`Select` class](http://selenium-python.readthedocs.org/en/latest/api.html#selenium.webdriver.support.select.Select).
For example, imagine there is the following `select` tag:
```
<s... | No such thing in Protractor, but we can write our own:
**select-wrapper.js**
```
'use strict';
var SelectWrapper = function(selector) {
this.webElement = element(selector);
};
SelectWrapper.prototype.getOptions = function() {
return this.webElement.all(by.tagName('option'));
};
SelectWrapper.prototype.getSel... |
Can I use python 're' to parse complex human names? | 28,728,834 | 8 | 2015-02-25T20:20:53Z | 28,729,819 | 8 | 2015-02-25T21:19:52Z | [
"python",
"regex",
"parsing",
"string-parsing"
] | So one of my major pain points is name comprehension and piecing together household names & titles. I have a 80% solution with a pretty massive regex I put together this morning that I probably shouldn't be proud of (but am anyway in a kind of sick way) that matches the following examples correctly:
```
John Jeffries
... | Regular expressions like this are the work of the Dark One.
Who, looking at your code later, will be able to understand what is going on? Will you even?
How will you test all of the possible edge cases?
Why have you chosen to use a regular expression at all? If the tool you are using is so difficult to work with, it... |
Combine two Pyplot patches for legend | 28,732,845 | 3 | 2015-02-26T01:16:37Z | 28,735,010 | 8 | 2015-02-26T05:21:18Z | [
"python",
"matplotlib",
"data-visualization",
"legend"
] | I am trying to plot some data with confidence bands. I am doing this with two plots for each data stream: `plot`, and `fill_between`. I would like the legend to look similar to the plots, where each entry has a box (the color of the confidence region) with a darker, solid line passing through the center. So far I have ... | The solution is borrowed from the comment by CrazyArm, found here: [Matplotlib, legend with multiple different markers with one label](http://stackoverflow.com/questions/9262307/matplotlib-legend-with-multiple-different-markers-with-one-label). Apparently you can make a list of handles and assign only one label and it ... |
Most pythonic way to convert to boolean? | 28,733,116 | 3 | 2015-02-26T01:49:23Z | 28,733,134 | 9 | 2015-02-26T01:51:04Z | [
"python"
] | What is the most pythonic way to convert to boolean based on the truthiness of the object?
`return bool(an_object)`
or
```
if an_object:
return True
else:
return False
```
or something else entirely?
In this instance we can't get by relying on the truthiness of the object. | If you really **need** a boolean, use `bool(something)`...
However, usually you don't *need* a boolean so rather than `return bool(something)`, you can just `return something` and the user can then decide what context to use it in. |
Why print in Python doesn't pause when using sleep in a loop? | 28,736,175 | 8 | 2015-02-26T06:51:09Z | 28,736,217 | 11 | 2015-02-26T06:54:38Z | [
"python",
"python-3.x"
] | This code:
```
import time
for i in range(10):
print(i)
time.sleep(.5)
```
Causes my computer to hang for 5 seconds, and then print out 0-9, as opposed to printing a digit every half second. Am I doing something wrong? | [`print`](https://docs.python.org/3/library/functions.html#print), by default, prints to `sys.stdout` and that buffers the output to be printed, internally.
> Whether output is buffered is usually determined by file, but if the `flush` keyword argument is true, the stream is forcibly flushed.
>
> Changed in version 3.... |
Creating json array in django | 28,740,338 | 6 | 2015-02-26T10:45:43Z | 28,741,028 | 13 | 2015-02-26T11:17:53Z | [
"python",
"arrays",
"json",
"django"
] | I am trying to make a json array in django but I am getting error -
```
In order to allow non-dict objects to be serialized set the safe parameter to False
```
and my views.py -
```
def wall_copy(request):
if True:
posts = user_post.objects.order_by('id')[:20].reverse()
return JsonResponse(posts)... | Would this solve your problem?
```
from django.core import serializers
def wall_copy(request):
posts = user_post.objects.all().order_by('id')[:20].reverse()
posts_serialized = serializers.serialize('json', posts)
return JsonResponse(posts_serialized, safe=False)
``` |
pytesseract-no such file or directory error | 28,741,563 | 9 | 2015-02-26T11:43:26Z | 28,741,799 | 23 | 2015-02-26T11:54:39Z | [
"python",
"python-2.7",
"ubuntu-14.04"
] | I am using Ubuntu 14.04. I have the following code:
```
import Image
import pytesseract
im = Image.open('test.png')
print pytesseract.image_to_string(im)
```
but I keep getting the following error:
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/s... | You need to install `tesseract-ocr`:
```
sudo apt-get install tesseract-ocr
``` |
Importing bs4 in Python 3.5 | 28,745,153 | 9 | 2015-02-26T14:35:00Z | 28,745,374 | 11 | 2015-02-26T14:45:39Z | [
"python",
"python-3.x",
"beautifulsoup",
"html-parser",
"python-3.5"
] | I have installed both Python 3.5 and Beautifulsoup4. When I try to import bs4, I get the error below. Is there any fix for that? Or should I just install Python 3.4 instead?
Please be very explicit - I am new to programming. Many thanks!
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Fi... | **Update:** Starting with 4.4.0, `BeautifulSoup` is compatible with Python 3.5. Upgrade:
```
pip install --upgrade beautifulsoup4
```
---
**Old answer:**
Because of the changes made for [Deprecate strict mode of HTMLParser](http://bugs.python.org/issue15114) issue:
> Issue #15114: the strict mode and argument of H... |
Importing bs4 in Python 3.5 | 28,745,153 | 9 | 2015-02-26T14:35:00Z | 32,589,332 | 16 | 2015-09-15T14:59:00Z | [
"python",
"python-3.x",
"beautifulsoup",
"html-parser",
"python-3.5"
] | I have installed both Python 3.5 and Beautifulsoup4. When I try to import bs4, I get the error below. Is there any fix for that? Or should I just install Python 3.4 instead?
Please be very explicit - I am new to programming. Many thanks!
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Fi... | Update: BeautifulSoup 4.4.0 has been updated to be python3.5 compatible, so a `pip install --upgrade beautifulsoup4` should do the trick if you are still hitting this issue. |
Loc vs. iloc vs. ix vs. at vs. iat? | 28,757,389 | 44 | 2015-02-27T04:12:39Z | 30,022,658 | 29 | 2015-05-04T04:31:58Z | [
"python",
"pandas"
] | Recently began branching out from my safe place (R) into Python and and am a bit confused by the cell localization/selection in `Pandas`. I've read the documentation but I'm struggling to understand the practical implications of the various localization/selection options.
Is there a reason why I should ever use `.loc`... | **loc:** only work on index
**iloc:** work on position
**ix:** You can get data from dataframe without it being in the index
**at:** get scalar values. It's a very fast loc
**iat:** Get scalar values. It's a very fast iloc
<http://pyciencia.blogspot.com/2015/05/obtener-y-filtrar-datos-de-un-dataframe.html> |
Loc vs. iloc vs. ix vs. at vs. iat? | 28,757,389 | 44 | 2015-02-27T04:12:39Z | 31,859,215 | 19 | 2015-08-06T15:00:52Z | [
"python",
"pandas"
] | Recently began branching out from my safe place (R) into Python and and am a bit confused by the cell localization/selection in `Pandas`. I've read the documentation but I'm struggling to understand the practical implications of the various localization/selection options.
Is there a reason why I should ever use `.loc`... | ```
df = pd.DataFrame({'A':['a', 'b', 'c'], 'B':[54, 67, 89]}, index=[100, 200, 300])
df
A B
100 a 54
200 b 67
300 c 89
In [19]:
df.loc[100]
Out[19]:
A a
B 54
Name: 100, dtype: object
In [20]:
df.iloc[0]
Out[... |
AttributeError while using Django Rest Framework with serializers | 28,760,356 | 8 | 2015-02-27T08:17:23Z | 28,760,574 | 26 | 2015-02-27T08:32:38Z | [
"python",
"django",
"serialization",
"django-rest-framework",
"django-1.7"
] | I am following a tutorial located [here](https://godjango.com/41-start-your-api-django-rest-framework-part-1/) that uses [Django Rest Framework](http://www.django-rest-framework.org/), and I keep getting a weird error about a field.
I have the following model in my `models.py`
```
from django.db import models
class ... | Simple specify `many=True` when creating a serializer from queryset, `TaskSerializer(tasks)` will work only with one instance of `Task`:
```
tasks = Task.objects.all()
serializer = TaskSerializer(tasks, many=True)
``` |
Intersection of two graphs in Python, find the x value: | 28,766,692 | 3 | 2015-02-27T13:52:34Z | 28,766,902 | 17 | 2015-02-27T14:03:28Z | [
"python",
"matplotlib"
] | Let 0<= x <=1. I have two columns f and g of length 5000 respectively. Now I plot:
```
plt.plot(x, f, '-')
plt.plot(x, g, '*')
```
I want to find the point 'x' where the curve intersects. I don't want to find the intersection of f and g.
I can do it simply with:
```
set(f) & set(g)
``` | You can use `np.sign` in combination with `np.diff` and `np.argwhere` to obtain the indices of points where the lines cross (in this case, the points are `[ 0, 149, 331, 448, 664, 743]`):
```
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 1000)
f = np.arange(0, 1000)
g = np.sin(np.arange(0, 10, 0... |
How to compare two lists in python | 28,767,642 | 6 | 2015-02-27T14:41:52Z | 28,767,692 | 12 | 2015-02-27T14:43:48Z | [
"python",
"list",
"python-3.x",
"numpy",
"itertools"
] | Suppose I have two lists (or `numpy.array`s):
```
a = [1,2,3]
b = [4,5,6]
```
How can I check if each element of `a` is smaller than corresponding element of `b` at the same index? (I am assuming indices are starting from 0)
i.e.
```
at index 0 value of a = 1 < value of b = 4
at index 1 value of a = 2 < value of b =... | Answering both parts with `zip` and `all`
```
all(i < j for (i, j) in zip(a, b))
```
`zip` will pair the values from the beginning of `a` with values from beginning of `b`; the iteration ends when the shorter iterable has run out. `all` returns `True` if and only if all items in a given are true in boolean context. A... |
Combine two Pandas dataframes with the same index | 28,773,683 | 3 | 2015-02-27T20:28:11Z | 28,773,733 | 9 | 2015-02-27T20:30:55Z | [
"python",
"pandas"
] | I have two dataframes with the same index but different columns. How do I combine them into one with the same index but containing all the columns?
I have:
```
A
1 10
2 11
B
1 20
2 21
```
and I need the following output:
```
A B
1 10 20
2 11 21
``` | ```
pandas.concat([df1, df2], axis=1)
``` |
Pyinstaller error ImportError: No module named 'requests.packages.chardet.sys | 28,775,276 | 11 | 2015-02-27T22:17:02Z | 28,793,874 | 9 | 2015-03-01T13:05:39Z | [
"python",
"python-2.7",
"python-requests",
"pyinstaller"
] | I can't seem to find the root cause of this. I don't know if it's pyinstaller, a pip problem, the requests module, or something else as nothing can be eliminated conclusively.
I wrote a script in python that properly configures a new hardware sonicwall for our enterprise network when we have to deploy a new unit. It c... | I don't have a solution for this yet, but this is caused by latest changes in `requests` module (versions 2.5.2 & 2.5.3).
For now you can use version 2.5.1 until PyInstaller will have suitable hook for solving this issue.
I cannot really explain the issue, but it looks like there's some kind of collision between `PyI... |
How to set same color for markers and lines in a matplotlib plot loop? | 28,779,559 | 8 | 2015-02-28T08:08:29Z | 28,779,637 | 7 | 2015-02-28T08:19:42Z | [
"python",
"matplotlib"
] | I have to plot multiple lines and markers with matplotlib by creating a loop and I have already set the axes color cycle in the matplolibrc param file. In each cycle of the loop a set of markers and lines are created (lines are created by a separate command). But the marker and line colors are different as per the axes... | If you don't want to send a color in as an argument, you can reset the color cycle and go through the loop twice. Here I reset it before the first loop and then again before the second loop just to make sure it's starting from the same place.
```
import numpy as np
import itertools
import matplotlib.pyplot as plt
m = ... |
Load CSV file with Spark | 28,782,940 | 12 | 2015-02-28T14:41:00Z | 28,784,117 | 14 | 2015-02-28T16:37:17Z | [
"python",
"csv",
"apache-spark",
"pyspark"
] | I'm new to Spark and I'm trying to read CSV data from a file with Spark.
Here's what I am doing :
```
sc.textFile('file.csv')
.map(lambda line: (line.split(',')[0], line.split(',')[1]))
.collect()
```
I would expect this call to give me a list of the two first columns of my file but I'm getting this error :
... | Are you sure that *all* the lines have at least 2 columns? Can you try something like, just to check?:
```
sc.textFile("file.csv")
.map(lambda line: line.split(","))
.filter(lambda line: len(line)>1)
.map(lambda line: (line[0],line[1]))
.collect()
```
Alternatively, you could print the culprit (if any... |
Load CSV file with Spark | 28,782,940 | 12 | 2015-02-28T14:41:00Z | 34,528,938 | 24 | 2015-12-30T11:44:53Z | [
"python",
"csv",
"apache-spark",
"pyspark"
] | I'm new to Spark and I'm trying to read CSV data from a file with Spark.
Here's what I am doing :
```
sc.textFile('file.csv')
.map(lambda line: (line.split(',')[0], line.split(',')[1]))
.collect()
```
I would expect this call to give me a list of the two first columns of my file but I'm getting this error :
... | **Spark 2.0.0+**
You can use csv data source directly:
```
spark.read.csv(
"some_input_file.csv", header=True, mode="DROPMALFORMED", schema=schema
)
```
**Spark < 2.0.0**:
Instead of manual parsing, which is far from trivial in a general case, I would recommend [`spark-csv`](https://github.com/databricks/spark-... |
Can luigi rerun tasks when the task dependencies become out of date? | 28,793,832 | 3 | 2015-03-01T13:01:25Z | 29,304,506 | 10 | 2015-03-27T15:34:39Z | [
"python",
"luigi"
] | As much as I know, a luigi Target can either exists, or not exists.
Therefore, if a Target exists it wouldn't be recomputed.
I'm looking for a may to force re computation of the task if one of it's dependencies is modified, or if the code of one of the tasks changes. | One way you could accomplish your goal is by overriding the `complete(...)` method.
[The documentation for `complete` is straightforward](http://luigi.readthedocs.org/en/latest/api/luigi.task.html#luigi.task.Task.complete).
Simply implement a function that checks your constraint, and returns `False` if you want to re... |
Support multiple API versions in flask | 28,795,561 | 14 | 2015-03-01T15:52:08Z | 28,797,512 | 24 | 2015-03-01T18:44:17Z | [
"python",
"flask"
] | I started to design a RESTful webservice with Flask and Python and I'm wondering how one would support multiple API versions in the same project.
I'm thinking of putting the requested API version in the URL like this:
```
/myapp/v1/Users
```
After some time I want to add another endpoint in Version 1.1 of the API and... | I am the author of the accepted answer on the question you referenced. I think the `/<version>/users` approach is not very effective as you say. If you have to manage three or four different versions you'll end up with spaghetti code.
The nginx idea I proposed there is better, but has the drawback that you have to hos... |
Infinite horizontal line in Bokeh | 28,797,330 | 10 | 2015-03-01T18:28:24Z | 35,019,983 | 10 | 2016-01-26T17:26:09Z | [
"python",
"plot",
"line",
"bokeh"
] | Is there a way to plot an infinite horizontal line with Bokeh?
The endpoints of the line should never become visible, no matter how far out the user is zooming.
This is what I've tried so far. It just prints an empty canvas:
```
import bokeh.plotting as bk
import numpy as np
p = bk.figure()
p.line([-np.inf,np.inf], ... | You are looking for "spans":
> Spans (line-type annotations) have a single dimension (width or height) and extend to the edge of the plot area.
Please, take a look at <http://bokeh.pydata.org/en/latest/docs/user_guide/plotting.html#spans>
So, the code will look like:
```
import numpy as np
import bokeh.plotting as ... |
How do I identify individual characters in a string | 28,802,782 | 3 | 2015-03-02T04:36:14Z | 28,802,917 | 8 | 2015-03-02T04:51:34Z | [
"python"
] | I'm trying to create a function that returns 'true' if a inputted string has no numbers in it and 'false' if it has any numbers in it
ex:
> 'Ohio' = true , 'agent 007' = false
So far I've tried
```
numbers = '0123456789'
Lowercase = 'abcdefghijklmnopqrstuvwxyz'
Uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def alphabet... | Use isalpha() from the standard library
```
>>> test='test1'
>>> test.isalpha()
>>> False
``` |
Python logging and Pydev debugger? | 28,806,403 | 6 | 2015-03-02T09:32:14Z | 29,228,332 | 8 | 2015-03-24T08:54:02Z | [
"python",
"debugging",
"logging",
"configuration",
"pycharm"
] | **Edit :**
Using Liclipse 1.2.1 instead of 1.3.0 or 1.4.0 is working fine. Changelog indicate both Pydev 3.9.1 and Eclipse 4.4.1 updates for 1.3.0. Seems to break logging debug.
---
Using Liclipse and Pydev debugger (and CPython) with the following code sample, getting that error :
```
logging.config.dictConfig(co... | same problem with PyCharm.
possible workaround - to comment out pydev\_monkey\_qt.patch\_qt() line in pycharm/helpers/pydev/pydevd.py, for Eclipse it should be located somewhere else |
How can i set the location of minor ticks in matplotlib | 28,810,403 | 4 | 2015-03-02T12:58:39Z | 28,810,556 | 10 | 2015-03-02T13:06:33Z | [
"python",
"matplotlib"
] | I want to draw a grid on the x-axis in a matplotlib plot at the positions of the minor ticks but not at the positions of the major ticks. My mayor ticks are at the positions 0, 1, 2, 3, 4, 5 and have to remain there. I want the grid at 0.5, 1.5, 2.5, 3.5, 4.5.
```
....
from matplotlib.ticker import MultipleLocator
...... | You can use [`matplotlib.ticker.AutoMinorLocator`](http://matplotlib.org/api/ticker_api.html#matplotlib.ticker.AutoMinorLocator). This will automatically place N-1 minor ticks at locations spaced equally between your major ticks.
For example, if you used `AutoMinorLocator(5)` then that will place 4 minor ticks equally... |
Game of Life patterns carried out incorrectly | 28,812,183 | 14 | 2015-03-02T14:26:26Z | 28,812,389 | 11 | 2015-03-02T14:36:55Z | [
"python",
"conways-game-of-life"
] | My Conway's game of life implementation in Python doesn't seem to follow the rules correctly, and I can't figure out what could be wrong. When I put a final configuration into Golly, it continues past what mine did.
I first identified the program by putting a configuration at which my program stopped into Golly, and t... | For the logic that loops through the board and checks adjacent cells, it is turning cells on/off while continuing to check others. It is likely you are reading adjacent cells as live or dead not because they were in the previous time step (which matters), but because you've changed their state as they have been already... |
How do I get Python's ElementTree to pretty print to an XML file? | 28,813,876 | 7 | 2015-03-02T15:48:53Z | 28,814,053 | 10 | 2015-03-02T15:57:06Z | [
"python",
"xml",
"python-2.6",
"elementtree",
"pretty-print"
] | # Background
I am using SQLite to access a database and retrieve the desired information. I'm using ElementTree in Python version 2.6 to create an XML file with that information.
# Code
```
import sqlite3
import xml.etree.ElementTree as ET
# NOTE: Omitted code where I acccess the database,
# pull data, and add elem... | Whatever your XML string is, you can write it to the file of your choice by opening a file for writing and writing the string to the file.
```
xmlstr = minidom.parseString(ET.tostring(root)).toprettyxml(indent=" ")
with open("New_Database.xml", "w") as f:
f.write(xmlstr)
```
There is one possible complication, ... |
How do I select elements inside an iframe with Xpath? | 28,814,916 | 6 | 2015-03-02T16:37:52Z | 28,816,113 | 8 | 2015-03-02T17:39:28Z | [
"python",
"selenium",
"iframe",
"xpath"
] | I want to create a Selenium test to test our extensions with AOL mail. I managed to login to AOL and compose an email, but I also need to select elements inside the editor, which is inside an iframe. I checked and even when the editor is open the following test fails:
```
self.assertEqual(first=1, second=len(self.driv... | You cannot traverse through `<iframe>`'s until switching to them. Your xPath,
```
//iframe[@name='editor_body']//body[@contenteditable='true']
```
will not work because the `<body>` tag is within an iFrame, which is not in the current context. you need to switch to it first:
```
driver.switch_to.frame('editor_body')... |
How to find linearly independent rows from a matrix | 28,816,627 | 3 | 2015-03-02T18:12:37Z | 28,817,934 | 8 | 2015-03-02T19:29:35Z | [
"python",
"numpy",
"matrix",
"linear-algebra"
] | How to identify the linearly independent rows from a matrix? For instance,

The 4th rows is independent. | First, your 3rd row is linearly dependent with 1t and 2nd row. However, your 1st and 4th column are linearly dependent.
Two methods you could use:
**Eigenvalue**
If one eigenvalue of the matrix is zero, its corresponding eigenvector is linearly dependent. The documentation [eig](http://docs.scipy.org/doc/numpy/refer... |
Reading a big text file and memory | 28,817,030 | 2 | 2015-03-02T18:37:50Z | 28,817,103 | 7 | 2015-03-02T18:42:16Z | [
"python"
] | I am going to read about 7 GB text file.
Whenever I try to read this file, it takes long than what I expected.
For example, suppose I have 350 MB text file and my laptop takes about a minute or less. If I suppose to read 7GB, ideally it should take 20 minutes or less. Isn't it? Mine takes much longer than what I expe... | The 7GB file is likely taking significantly longer than 20 x 350mb file because you don't have enough memory to hold all the data in memory. This means that, at some point, your operating system will start [swapping out](https://en.wikipedia.org/wiki/Paging) some of the data â writing it from memory onto disk â so ... |
AttributeError during Django-rest-framework tutorial 4: authentication | 28,818,129 | 3 | 2015-03-02T19:39:50Z | 28,818,770 | 7 | 2015-03-02T20:21:17Z | [
"python",
"django",
"django-rest-framework"
] | I'm following the django-rest-framework tutorial and I can't figure out what is happening here.
I've created a UserSerializer class with a snippets attribute and I did all the imports
```
#--!-coding: utf-8
from rest_framework import serializers
from snippets.models import Snippet
from django.contrib.auth.models impo... | In your snippets model, you need to add a related name to your owner field.
```
owner = models.ForeignKey('auth.User', related_name='snippets')
``` |
Create new list by adding the elements of three lists together - associated error (PYTHON) | 28,822,190 | 2 | 2015-03-03T00:51:27Z | 28,822,227 | 8 | 2015-03-03T00:54:13Z | [
"python",
"list",
"append",
"unpack"
] | I have 3 lists, say:
```
a = [1,2,3,4,5]
b = [0,2,4,6,8]
c = [2,3,4,5,6]
```
I want to create a new list which adds the respective elements together, i.e.
```
d = [3,7,11,15,19]
```
**My code:**
```
d = []
for i,j,k in a,b,c:
d.append(i+j+k)
```
However, I keep getting the error :
> ValueError: too many... | try like this:
```
>>> map(sum, zip(a,b,c))
[3, 7, 11, 15, 19]
```
for python 3x you need to call list:
```
>>> list(map(sum, zip(a,b,c)))
[3, 7, 11, 15, 19]
``` |
Getting model attributes from scikit-learn pipeline | 28,822,756 | 4 | 2015-03-03T01:52:37Z | 28,837,740 | 9 | 2015-03-03T17:07:08Z | [
"python",
"scikit-learn"
] | I typically get `PCA` loadings like this:
```
pca = PCA(n_components=2)
X_t = pca.fit(X).transform(X)
loadings = pca.components_
```
If I run `PCA` using a `scikit-learn` pipline ...
```
from sklearn.pipeline import Pipeline
pipeline = Pipeline(steps=[
('scaling',StandardScaler()),
('pca',PCA(n_components=2))
])... | Did you look at the documentation: <http://scikit-learn.org/dev/modules/pipeline.html>
I feel it is pretty clear.
There are two ways to get to the steps in a pipeline, either using indices or using the string names you gave:
```
pipeline.named_steps['pca']
pipeline.steps[1][1]
```
This will give you the PCA object, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.