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
class takes exactly three arguments and two are given
17,934,317
3
2013-07-29T21:14:30Z
17,934,369
8
2013-07-29T21:18:04Z
[ "python" ]
I am trying to make my first game, it is similar to the tron game with the bikes,so far I have created a bike class and several functions to help. However when it runs as below I get an error when I try to declare a Bike object with the velocity, it says that the: > class Vector takes exactly three arguments and two a...
Your `what_direction()` function returns a tuple of values, and you're trying to pass that tuple to a function that takes 2 arguments. Python thinks you're passing a single argument (that 2-tuple). You need to unpack the tuple before using it in the expression `Vector(what_direction())`. You can do this yourself: ``` ...
AttributeError with numpy in IDLE but not in Python Shell
17,936,016
4
2013-07-29T23:38:01Z
17,936,038
8
2013-07-29T23:40:05Z
[ "python", "numpy" ]
The following code executed from an IDLE window produces an error shown below. ``` import numpy as np testarray = np.array([1,2,3], int) ``` Here is the error... ``` Traceback (most recent call last): File "C:\Test\numpy.py", line 1, in <module> import numpy as np File "C:\Test\numpy.py", line 2, in <m...
You named a file `numpy.py`. Python sees that in the module search path and thinks it's the implementation of `numpy`. Pick a different name.
In Numpy, find Euclidean distance between each pair from two arrays
17,936,587
2
2013-07-30T00:45:54Z
17,936,744
8
2013-07-30T01:04:32Z
[ "python", "arrays", "numpy", "scipy", "euclidean-distance" ]
I have two arrays of 2D coordinate points (x,y) ``` a = [ (x1,y1), (x2,y2), ... (xN,yN) ] b = [ (X1,Y1), (X2,Y2), ... (XN,YN) ] ``` How can I find the Euclidean distances between each aligned pairs `(xi,yi) to (Xi,Yi)` in an `1xN` array? The `scipy.spatial.cdist` function gives me distances between all pairs in an `...
I'm not seeing a built-in, but you could do it yourself pretty easily. ``` distances = (a-b)**2 distances = distances.sum(axis=-1) distances = np.sqrt(distances) ```
updated django from 1.4 to 1.5.1; now DeprecationWarning on setup_environ
17,937,017
2
2013-07-30T01:41:09Z
17,937,357
8
2013-07-30T02:27:22Z
[ "python", "django", "updates", "django-1.5" ]
updated django from 1.4 to 1.5.1 now its throwing this: > DeprecationWarning: The 'setup\_environ' function is deprecated, you > likely need to update your 'manage.py'; please see the Django 1.4 > release notes (<https://docs.djangoproject.com/en/dev/releases/1.4/>). First, I was already on v1.4 so why its showing th...
I end up adding: ``` os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") ``` not only to my manage.py file, but also in the app files where I was calling 'setup\_environ'. So, I replace this code: ``` from django.core.management import setup_environ from mysite import settings setup_environ(settings) ...
pygame.key.get_pressed() is not working
17,938,170
4
2013-07-30T04:12:51Z
17,940,879
8
2013-07-30T07:32:02Z
[ "python", "pygame" ]
I've read similar questions to this on Stack Overflow but they have not helped. Here is my code: ``` import pygame from pygame.locals import * pygame.init() screen = pygame.display.set_mode((640, 480)) pygame.display.set_caption('Hello World') pygame.mouse.set_visible(1) done = False clock = pygame.time.Clock() whi...
The problem is that you don't process pygame's event queue. You should simple call `pygame.event.pump()` at the end of your loop and then your code works fine: ``` ... while not done: clock.tick(60) keyState = pygame.key.get_pressed() if keyState[pygame.K_ESCAPE]: print('\nGame Shuting Down!') ...
For loop with custom steps in python
17,944,235
6
2013-07-30T10:14:16Z
17,944,355
14
2013-07-30T10:20:12Z
[ "python", "for-loop" ]
I can make simple for loops in python like: ``` for i in range(10): ``` However, I couldn't figure out how to make more complex ones, which are really easy in c++. How would you implement a for loop like this in python: ``` for(w = n; w > 1; w = w / 2) ``` The closest one I made so far is: ``` for w in reversed(r...
``` for i in range(0, 10, 2): print i >>> 0 >>> 2 >>> 4 >>> 6 >>> 8 ``` <http://docs.python.org/2/library/functions.html> ``` >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(1, 11) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> range(0, 30, 5) [0, 5, 10, 15, 20, 25] >>> range(0, 10, 3) [0, 3, 6, 9] ```
Pandas groupby: get size of a group knowing its id (from .grouper.group_info[0])
17,945,247
7
2013-07-30T11:01:24Z
17,945,528
10
2013-07-30T11:15:25Z
[ "python", "group-by", "pandas" ]
In the following snippet `data` is a `pandas.DataFrame` and `indices` is a set of columns of the `data`. After grouping the data with `groupby` I am interested in the ids of the groups, but only those with a size greater than a threshold (say: 3). ``` group_ids=data.groupby(list(data.columns[list(indices)])).grouper.g...
One way is to use the [`size`](http://pandas.pydata.org/pandas-docs/stable/groupby.html#aggregation) method of the [`groupby`](http://pandas.pydata.org/pandas-docs/stable/groupby.html): ``` g = data.groupby(...) size = g.size() size[size > 3] ``` For example, here there is only one group of size > 1: ``` In [11]: df...
Deactivate function with decorator
17,946,024
3
2013-07-30T11:37:54Z
17,946,107
10
2013-07-30T11:42:28Z
[ "python" ]
Is it possible to "deactivate" a function with a python decorator? Here an example: ``` cond = False class C: if cond: def x(self): print "hi" def y(self): print "ho" ``` Is it possible to rewrite this code with a decorator, like this?: ``` class C: @cond def x(self): print "hi" def ...
You can turn functions into no-ops (that log a warning) with a decorator: ``` def conditional(cond, warning=None): def noop_decorator(func): return func # pass through def neutered_function(func): def neutered(*args, **kw): if warning: log.warn(warning) ...
Is it safe to rely on python function arguments evaluation order?
17,948,369
20
2013-07-30T13:26:50Z
17,948,425
14
2013-07-30T13:29:03Z
[ "python" ]
Is it safe to assume that function arguments are evaluated from left to right in python? Reference states that it happens that way but perhaps there is some way to change this order which may break my code. What I want to do is to add time stamp for function call: ``` l = [] l.append(f(), time.time()) ``` I...
Yes, Python always evaluates function arguments from left to right. This goes for any comma seperated list as far as I know: ``` >>> from __future__ import print_function >>> def f(x, y): pass ... >>> f(print(1), print(2)) 1 2 >>> [print(1), print(2)] 1 2 [None, None] >>> {1:print(1), 2:print(2)} 1 2 {1: None, 2: Non...
Is it safe to rely on python function arguments evaluation order?
17,948,369
20
2013-07-30T13:26:50Z
17,948,641
20
2013-07-30T13:37:58Z
[ "python" ]
Is it safe to assume that function arguments are evaluated from left to right in python? Reference states that it happens that way but perhaps there is some way to change this order which may break my code. What I want to do is to add time stamp for function call: ``` l = [] l.append(f(), time.time()) ``` I...
Quoting from the [reference documentation](http://docs.python.org/2/reference/expressions.html#evaluation-order): > Python evaluates expressions from left to right. So yes, you can count on that.
Python: read all text file lines in loop
17,949,508
19
2013-07-30T14:14:47Z
17,949,527
8
2013-07-30T14:15:46Z
[ "python", "file" ]
I want to read huge text file line by line (and stop if a line with "str" found). How to check, if file-end is reached? ``` fn = 't.log' f = open(fn, 'r') while not _is_eof(f): ## how to check that end is reached? s = f.readline() print s if "str" in s: break ```
Just iterate over each line in the file. Python automatically checks for the End of file and closes the file for you (using the `with` syntax). ``` with open('fileName', 'r') as f: for line in f: if 'str' in line: break ```
Python: read all text file lines in loop
17,949,508
19
2013-07-30T14:14:47Z
17,949,545
53
2013-07-30T14:16:19Z
[ "python", "file" ]
I want to read huge text file line by line (and stop if a line with "str" found). How to check, if file-end is reached? ``` fn = 't.log' f = open(fn, 'r') while not _is_eof(f): ## how to check that end is reached? s = f.readline() print s if "str" in s: break ```
There's no need to check for EOF in python, simply do: ``` with open('t.ini') as f: for line in f: print line if 'str' in line: break ``` [Why the `with` statement](http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects): > It is good practice to use the `with` keyword ...
Logarithmic y-axis bins in python
17,952,279
21
2013-07-30T16:18:10Z
17,952,890
39
2013-07-30T16:50:41Z
[ "python", "matplotlib", "histogram", "logarithm" ]
I'm trying to create a histogram of a data column and plot it logarithmically (`y-axis`) and I'm not sure why the following code does not work: ``` import numpy as np import matplotlib.pyplot as plt data = np.loadtxt('foo.bar') fig = plt.figure() ax = fig.add_subplot(111) plt.hist(data, bins=(23.0, 23.5,24.0,24.5,25.0...
try ``` plt.yscale('log', nonposy='clip') ``` <http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.yscale> The issue is with the bottom of bars being at y=0 and the default is to mask out in-valid points (`log(0)` -> undefined) when doing the log transformation (there was discussion of changing this, but I d...
Python: Finding the last index of min element?
17,952,612
7
2013-07-30T16:34:44Z
17,952,763
10
2013-07-30T16:42:41Z
[ "python", "list", "min" ]
For example [1,2,3,4,1,2] has min element 1, but it occurs for the last time at index 4.
``` >>> values = [1,2,3,4,1,2] >>> -min((x, -i) for i, x in enumerate(values))[1] 4 ``` No modification to the original list, works for arbitrary iterables, and only requires one pass. This creates an iterable of tuples with the first value being the original element from the list, and the second element being the ne...
python is not recognized as an internal or external command why?
17,953,124
26
2013-07-30T17:04:20Z
17,953,148
12
2013-07-30T17:06:14Z
[ "python", "cmd" ]
So I have recently installed Python Version 2.7.5 and I have made a little loop thing with it but the problem is, when I go to cmd and type `python testloop.py` I get the error: `'python' is not recognized as an internal or external command`. I have tried setting the path but no avail. Here is my path: > C:\Program F...
You need to add that folder to your Windows Path: **This link is broken:** <https://code.google.com/p/tryton/wiki/AddingPythonToWindowsPath> **Working link** to official guide: <https://docs.python.org/2/using/windows.html> Taken from [this](http://stackoverflow.com/questions/35065742/environmental-path-to-python-n...
python is not recognized as an internal or external command why?
17,953,124
26
2013-07-30T17:04:20Z
27,385,986
56
2014-12-09T18:17:53Z
[ "python", "cmd" ]
So I have recently installed Python Version 2.7.5 and I have made a little loop thing with it but the problem is, when I go to cmd and type `python testloop.py` I get the error: `'python' is not recognized as an internal or external command`. I have tried setting the path but no avail. Here is my path: > C:\Program F...
Try "py" instead of "python" from command line: > C:\Users\Cpsa>py > Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>>
retrieve dynamic frame names w/ Selenium WebDriver and Python?
17,954,652
2
2013-07-30T18:28:22Z
17,954,806
7
2013-07-30T18:36:44Z
[ "python", "python-2.7", "selenium", "selenium-webdriver" ]
I need to run thousands of searches on a certain database and I'm using Python and Selenium WebDriver to automate it. The thing is, the frame that contains the search results has a name that is dynamically generated. That name always begins the same way (say, "results\_frame") and then it's followed by a bunch of numbe...
`find_elements_by_xpath` returns an object of type `WebElement`. You need to use `get_attribute` to retrieve the value of an attribute from the `WebElement`. ``` framename = driver.find_element_by_xpath("//frame[contains(@name, 'results_frame')]").get_attribute("name") ``` That should return the name you're looking f...
Performance of row vs column operations in NumPy
17,954,990
9
2013-07-30T18:48:03Z
17,956,470
9
2013-07-30T20:11:10Z
[ "python", "numpy", "benchmarking" ]
There are [a few articles](http://undocumentedmatlab.com/blog/matrix-processing-performance/) that show that MATLAB prefers column operations than row operations, and that depending on you lay out your data the performance [can vary significantly](http://undocumentedmatlab.com/blog/matrix-processing-performance/). This...
Like many benchmarks, this really depends on the particulars of the situation. It's true that, by default, numpy creates arrays in C-contiguous (row-major) order, so, in the abstract, operations that scan over columns should be faster than those that scan over rows. However, the shape of the array, the performance of t...
how to reload a cython module interactively using pyximport
17,955,194
12
2013-07-30T19:00:00Z
18,134,343
22
2013-08-08T19:21:41Z
[ "python", "optimization", "cython" ]
When writing python code, my typical workflow is to use the interactive prompt and do something like ``` write function repeat until working: test function edit function ``` Once I'm pretty sure everything's ok, I'll run the code in non-interactive mode and collect the results. Sometimes the functions run a litt...
I found a poorly documented feature in the "pyximport.install" function that allows a cython module to be reloaded. With this feature set to True, you can load/reload your cython modules interactively without having to restart python. If you initialize your cython module with: ``` import pyximport pyximport.install(r...
openpyxl python3 -- formatting whole rows ellicits strange behavior
17,955,243
10
2013-07-30T19:02:35Z
33,974,541
7
2015-11-28T17:56:42Z
[ "python", "openpyxl" ]
I'm working with pivot-tabled XLSX files and writing a script to parse them out in to a new file per tab. Since openpyxl doesn't support pivot tables by default I need to do some work to reinsert the pivot 'style' that is lost during copy. To do this I'm iterating through each row and col, looking for the value `Tota...
Prior to openpyxl 2.0 cell styles were shared between cells: this was a holdover from the implementation using pointers in the source XML: two (or more) cells would both use style "1". Changing this style for one cell would mean changing it for all cells, which sounds like the behaviour being observed here. Since then...
Python defaultdict that does not insert missing values
17,956,927
8
2013-07-30T20:40:46Z
17,956,989
9
2013-07-30T20:43:47Z
[ "python", "collections", "defaultdict" ]
So the [defaultdict documentation](http://docs.python.org/2/library/collections.html#collections.defaultdict) mentions that, if an item is missing, the value returned by `default_factory` "is inserted in the dictionary for the key, and returned." That's great most of the time, but what I actually want in this case is f...
You can subclass `dict` and implement `__missing__`: ``` class missingdict(dict): def __missing__(self, key): return 'default' # note, does *not* set self[key] ``` Demo: ``` >>> d = missingdict() >>> d['foo'] 'default' >>> d {} ``` You *could* subclass `defaultdict` too, you'd get the factory handling ...
When to drop list Comprehension and the Pythonic way?
17,957,181
2
2013-07-30T20:53:04Z
17,957,246
7
2013-07-30T20:56:24Z
[ "python", "list-comprehension", "pylint", "code-complete" ]
I created a line that appends an object to a list in the following manner ``` >>> foo = list() >>> def sum(a, b): ... c = a+b; return c ... >>> bar_list = [9,8,7,6,5,4,3,2,1,0] >>> [foo.append(sum(i,x)) for i, x in enumerate(bar_list)] [None, None, None, None, None, None, None, None, None, None] >>> foo [9, 9, 9,...
I think it's generally frowned upon to use list comprehensions just for side-effects, so I would say a for loop is better in this case. But in any case, couldn't you just do `foo = [sum(i,x) for i, x in enumerate(bar_list)]`?
Jinja2 round filter not rounding
17,957,511
4
2013-07-30T21:14:25Z
19,038,257
7
2013-09-26T20:38:09Z
[ "python", "flask", "jinja2", "template-engine" ]
I have the following code in my template: ``` data: [{% for deet in deets %} {{ deet.value*100|round(1) }}{% if not loop.last %},{% endif %} {% endfor %}] ``` I am expecting data rounded to 1 decimal place. However, when I view the page or source, this is the output I'm getting: ``` data: [ 44.2765833818, 44.276583...
You can put parens around the value that you want to round. (This works for division as well, contrary to what @sobri wrote.) ``` {{ (deet.value/100)|round }} ``` NOTE: `round` returns a `float` so if you really want the `int` you have to pass the value through that filter as well. ``` {{ (deet.value/100)|round|int ...
pandas select from Dataframe using startswith
17,957,890
8
2013-07-30T21:37:24Z
17,958,424
16
2013-07-30T22:16:05Z
[ "python", "numpy", "pandas" ]
This works (using Pandas 12 dev) ``` table2=table[table['SUBDIVISION'] =='INVERNESS'] ``` Then I realized I needed to select the field using "starts with" Since I was missing a bunch. So per the Pandas doc as near as I could follow I tried ``` criteria = table['SUBDIVISION'].map(lambda x: x.startswith('INVERNESS')) ...
You can use the [`str.startswith`](http://pandas.pydata.org/pandas-docs/dev/basics.html#vectorized-string-methods) DataFrame method to give more consistent results: ``` In [11]: s = pd.Series(['a', 'ab', 'c', 11, np.nan]) In [12]: s Out[12]: 0 a 1 ab 2 c 3 11 4 NaN dtype: object In [13]: s.str.s...
Numpy warning:Casting Complex to real discards imaginary part
17,958,223
2
2013-07-30T22:00:10Z
17,958,387
9
2013-07-30T22:13:07Z
[ "python", "matlab", "numpy" ]
i am trying a Matlab code in Python my code gives a warning /usr/lib/python2.7/dist-packages/numpy/core/numeric.py:235: ComplexWarning: Casting complex values to real discards the imaginary part return array(a, dtype, copy=False, order=order) Python Code ``` demod_1_a=mod_noisy*2*cos((2*pi*Fc*t)+phi) N=10 Fc=40 F...
The warning is coming from the plot command -- I'm pretty sure. "plot" is meant to take a 1d, real array and put it on the screen. When it sees an array of complex numbers it does the best it can, i.e. discards the imaginary part and plot the real part. You might want to try something like ``` plot(numpy.real(demod),...
How can I convert a python urandom to a string?
17,958,347
15
2013-07-30T22:09:55Z
17,958,373
14
2013-07-30T22:11:54Z
[ "python", "string", "random", "python-3.x", "byte" ]
If I call os.urandom(64), I am given 64 random bytes. With reference to [Convert byte array to Python string](http://stackoverflow.com/questions/606191/convert-byte-array-to-python-string) I tried ``` a = os.urandom(64) a.decode() a.decode("utf-8") ``` but got the traceback error stating that the bytes are not in utf...
You can use base-64 encoding. In this case: ``` a = os.urandom(64) a.encode('base-64') ``` Also note that I'm using `encode` here rather than `decode`, as `decode` is trying to take it from whatever format you specify into unicode. So in your example, you're treating the random bytes as if they form a valid `utf-8` s...
How can I convert a python urandom to a string?
17,958,347
15
2013-07-30T22:09:55Z
21,927,326
17
2014-02-21T06:51:37Z
[ "python", "string", "random", "python-3.x", "byte" ]
If I call os.urandom(64), I am given 64 random bytes. With reference to [Convert byte array to Python string](http://stackoverflow.com/questions/606191/convert-byte-array-to-python-string) I tried ``` a = os.urandom(64) a.decode() a.decode("utf-8") ``` but got the traceback error stating that the bytes are not in utf...
In python 3, the answer is ``` from base64 import b64encode from os import urandom random_bytes = urandom(64) token = b64encode(random_bytes).decode('utf-8') ```
Matplotlib not using latex font while text.usetex==True
17,958,485
18
2013-07-30T22:20:58Z
17,967,324
19
2013-07-31T09:59:45Z
[ "python", "matplotlib", "latex" ]
I want to create labels to my plots with the latex computer modern font. However, the only way to persuade matplotlib to use the latex font is by inserting something like: ``` title(r'$\mathrm{test}$') ``` This is of course ridiculous, I tell latex to start math mode, and then exit math mode temporary to write the ac...
The default Latex font is known as `Computer Modern`: ``` from matplotlib import rc import matplotlib.pylab as plt rc('font', **{'family': 'serif', 'serif': ['Computer Modern']}) rc('text', usetex=True) x = plt.linspace(0,5) plt.plot(x,plt.sin(x)) plt.ylabel(r"This is $\sin(x)$", size=20) plt.show() ``` ![enter ima...
Matplotlib not using latex font while text.usetex==True
17,958,485
18
2013-07-30T22:20:58Z
18,241,190
7
2013-08-14T20:02:04Z
[ "python", "matplotlib", "latex" ]
I want to create labels to my plots with the latex computer modern font. However, the only way to persuade matplotlib to use the latex font is by inserting something like: ``` title(r'$\mathrm{test}$') ``` This is of course ridiculous, I tell latex to start math mode, and then exit math mode temporary to write the ac...
The marked answer can be enabled by default by changing a few lines in the `matplotlibrc` file: ``` text.usetex = True font.family = serif font.serif = cm ```
Get python class object from class name string in the same module
17,959,996
6
2013-07-31T01:12:43Z
17,960,039
13
2013-07-31T01:17:23Z
[ "python" ]
I have a class ``` class Foo(): def some_method(): pass ``` And another class **in the same module**: ``` class Bar(): def some_other_method(): class_name = "Foo" #can I access the class Foo above using the string "Foo"? ``` I want to be able to access the `Foo` class using the strin...
``` import sys getattr(sys.modules[__name__], "Foo") # or globals()['Foo'] ```
in Numpy, how to zip two 2-D arrays?
17,960,441
13
2013-07-31T02:07:34Z
17,960,617
16
2013-07-31T02:29:19Z
[ "python", "arrays", "numpy", "zip" ]
For example I have 2 arrays ``` a = array([[0, 1, 2, 3], [4, 5, 6, 7]]) b = array([[0, 1, 2, 3], [4, 5, 6, 7]]) ``` How can I `zip` `a` and `b` so I get ``` c = array([[(0,0), (1,1), (2,2), (3,3)], [(4,4), (5,5), (6,6), (7,7)]]) ``` ?
You can use [dstack](http://docs.scipy.org/doc/numpy/reference/generated/numpy.dstack.html): ``` >>> np.dstack((a,b)) array([[[0, 0], [1, 1], [2, 2], [3, 3]], [[4, 4], [5, 5], [6, 6], [7, 7]]]) ``` If you must have tuples: ``` >>> np.array(zip(a.ravel(),b.ravel...
Pandas: Subindexing dataframes: Copies vs views
17,960,511
9
2013-07-31T02:16:42Z
17,961,468
12
2013-07-31T04:12:35Z
[ "python", "pandas" ]
Say I have a dataframe ``` import pandas as pd import numpy as np foo = pd.DataFrame(np.random.random((10,5))) ``` and I create another dataframe from a subset of my data: ``` bar = foo.iloc[3:5,1:4] ``` does `bar` hold a copy of those elements from `foo`? Is there any way to create a `view` of that data instead? I...
Your answer lies in the pandas docs: [returning-a-view-versus-a-copy](http://pandas-docs.github.io/pandas-docs-travis/indexing.html?highlight=view#indexing-view-versus-copy). > Whenever an array of labels or a boolean vector are involved > in the indexing operation, **the result will be a copy**. > With single label /...
Can this be done by using a loop? Or maybe by using lists?
17,960,939
2
2013-07-31T03:13:08Z
17,961,124
7
2013-07-31T03:33:24Z
[ "python", "loops" ]
I wrote this to calculate the minimum number of bills and coins needed to make change. Can this be done using a loop? ``` def user_change(balance): twen = int(balance/20) balance=balance%20 ten = int(balance/10) balance=balance%10 five = int(balance/5) balance = balance%...
This is a good time (okay it's *always* a good time) to make things easier on yourself and first think about data structures. You have a list of currency (keys) that, for each key, you want to find one unique amount for (value). k:v pairings mean a `dict`, so fill one up in lieu of just printing the value; you can alwa...
How to write custom django manage.py commands in multiple apps
17,962,454
5
2013-07-31T05:43:18Z
17,964,973
15
2013-07-31T08:11:39Z
[ "python", "django", "django-admin", "manage.py" ]
Imagine I have two or more apps in my django project, I was able to successfully write and execute custom manage.py commands when I had only one app, `A`. Now I have a new app, `B`, and as mentioned in <https://docs.djangoproject.com/en/dev/howto/custom-management-commands/> I created directory structure of `B/manange...
As @Babu said in the comments, It looks like you may not have added your app to `INSTALLED_APPS` in your `settings.py`. It's also possible that you're missing the `__init__.py` files (that are required in python modules) from the `management` and `commands` folders. Alternatively, (sorry to say this) you may have mis...
Python: 'str' object is not callable
17,963,264
2
2013-07-31T06:36:04Z
17,963,292
7
2013-07-31T06:37:43Z
[ "python", "string" ]
Log: ``` Traceback (most recent call last): File "gen_big_file.py", line 8, in <module> print str(i)+'% done' TypeError: 'str' object is not callable ``` Code: ``` 1 2 f = open('BigTestFile','w'); 3 str = '0123456789' 4 i = 0; 5 while i<100000000: 6 i=i+1 7 if i %...
It's because you overrode the function `str` on line 3. `str()` is a [builtin function](http://docs.python.org/2/library/functions.html#str) in Python which takes care of returning a nice string representation of an object. Change line 3 from ``` str = '0123456789' ``` to ``` number_string = '0123456789' ```
Python: 'str' object is not callable
17,963,264
2
2013-07-31T06:36:04Z
17,963,327
10
2013-07-31T06:39:50Z
[ "python", "string" ]
Log: ``` Traceback (most recent call last): File "gen_big_file.py", line 8, in <module> print str(i)+'% done' TypeError: 'str' object is not callable ``` Code: ``` 1 2 f = open('BigTestFile','w'); 3 str = '0123456789' 4 i = 0; 5 while i<100000000: 6 i=i+1 7 if i %...
Call the variable something other than `str`. It is a built in function. [Details Here](http://docs.python.org/2/library/functions.html#str) **Edit:** Also, use `[ ]` instead of `()` to access the characters in the string.
Google-Forms response with Python?
17,964,429
3
2013-07-31T07:41:47Z
17,965,510
7
2013-07-31T08:39:44Z
[ "python" ]
I'm trying to write a Python-Script which makes it possible to submit responses in Google-Forms like this one: <https://docs.google.com/forms/d/152CTd4VY9pRvLfeACOf6SmmtFAp1CL750Sx72Rh6HJ8/viewform> But how to I actually send the POST and how can I find out, what this POST should actually contain?
First `pip install requests` You have to post some specific form data to a specific url,you can use requests.The form\_data dict params are correspondent to options,if you don't need some options,just remove it from form\_data. ``` import requests url = 'https://docs.google.com/forms/d/152CTd4VY9pRvLfeACOf6SmmtFAp1CL...
CertificateError when trying to install packages on a virtualenv
17,964,475
8
2013-07-31T07:43:50Z
17,967,170
7
2013-07-31T09:52:55Z
[ "python", "virtualenv" ]
Hey I'm trying to install some packages from a `requires` file on a new virtual environment (2.7.4), but I keep running into the following error: ``` CertificateError: hostname 'pypi.python.org' doesn't match either of '*.addvocate.com', 'addvocate.com' ``` I cannot seem to find anything helpful on the error when...
The issue is being documented on the python status site at <http://status.python.org/incidents/jj8d7xn41hr5>
Addition of chars adding one character in front
17,965,480
6
2013-07-31T08:38:30Z
17,966,171
9
2013-07-31T09:10:24Z
[ "python", "algorithm" ]
what I'm trying to implement is a function that increments a string by one character, for example: ``` 'AAA' + 1 = 'AAB' 'AAZ' + 1 = 'ABA' 'ZZZ' + 1 = 'AAAA' ``` I've implemented function for the first two cases, however I can't think of any solution for the third case. Here's my code : ``` def new_sku(s): s = ...
If you're dealing with [bijective numeration](http://en.wikipedia.org/wiki/Bijective_numeration#The_bijective_base-26_system), then you probably have (or should have) functions to convert to/from bijective representation anyway; it'll be a lot easier just to convert to an integer, increment it, then convert back: ``` ...
django countries currency code
17,966,592
5
2013-07-31T09:28:29Z
17,967,245
7
2013-07-31T09:56:32Z
[ "python", "django", "python-2.7", "django-1.5", "django-countries" ]
I am using `django_countries` to show the countries list. Now, I have a requirement where I need to show currency according to country. Norway - NOK, Europe & Afrika (besides UK) - EUR, UK - GBP, AMERICAS & ASIA - USDs. Could this be achieved through django\_countries project? or are there any other packages in python...
There are several modules out there: * [pycountry](https://pypi.python.org/pypi/pycountry): ``` import pycountry country = pycountry.countries.get(name='Norway') currency = pycountry.currencies.get(numeric=country.numeric) print currency.letter print currency.name ``` prints: ``` NOK Norweg...
Python OpenCV convert image to byte string?
17,967,320
5
2013-07-31T09:59:36Z
25,592,959
7
2014-08-31T14:31:48Z
[ "python", "image", "opencv", "binary" ]
I'm working with PyOpenCV. How to convert cv2 image (numpy) to binary string for writing to MySQL db without a temporary file and `imwrite`? I'm google it but nothing found... I'm trying `imencode`, but it doesn't works ``` capture = cv2.VideoCapture(url.path) capture.set(cv2.cv.CV_CAP_PROP_POS_MSEC, float(url.query...
If you have an image `img` (which is a numpy array) you can convert it into string using: ``` >>> img_str = cv2.imencode('.jpg', img)[1].tostring() >>> type(img_str) 'str' ``` No you can easily store the image inside your database, and then recover it by using: ``` >>> nparr = np.fromstring(STRING_FROM_DATABASE, np...
Migrating to MongoDB: how to query GROUP BY + WHERE
17,967,586
4
2013-07-31T10:12:10Z
17,967,770
13
2013-07-31T10:21:50Z
[ "python", "mongodb", "aggregate-functions", "pymongo" ]
I have a MYSQL table with records of people's names and the time of arrival expresed as a number. Think of it as a marathon. I want to know how many people arrived into a certain gap of time who where named the same, so: ``` SELECT name, COUNT(*) FROM mydb.mytable WHERE Time>=100 AND Time<=1000 GROUP BY name ``` And ...
There are examples of this all over the documentation, Google and this site. Some references: * <http://api.mongodb.org/python/current/examples/aggregation.html> * <http://docs.mongodb.org/manual/reference/aggregation/group/> * <http://docs.mongodb.org/manual/reference/aggregation/sum/> And for some code: ``` self....
How to add button next to Add User button in Django Admin Site
17,968,781
12
2013-07-31T11:13:14Z
18,052,643
23
2013-08-05T07:24:03Z
[ "python", "django", "django-forms", "django-templates", "django-admin" ]
I am working on Django Project where I need to extract the list of user to excel from the Django Admin's Users Screen. I added `actions` variable to my Sample Class for getting the CheckBox before each user's id. ``` class SampleClass(admin.ModelAdmin): actions =[make_published] ``` Action make\_published is alre...
1. Create a template in you template folder: admin/YOUR\_APP/YOUR\_MODEL/change\_list.html 2. Put this into that template ``` {% extends "admin/change_list.html" %} {% block object-tools-items %} {{ block.super }} <li> <a href="export/" class="grp-state-focus addlink">Export</a> ...
How to Normalize similarity measures from Wordnet
17,969,532
2
2013-07-31T11:48:16Z
17,970,113
7
2013-07-31T12:14:31Z
[ "python", "nlp", "nltk", "similarity", "wordnet" ]
I am trying to calculate semantic similarity between two words. I am using Wordnet-based similarity measures i.e Resnik measure(RES), Lin measure(LIN), Jiang and Conrath measure(JNC) and Banerjee and Pederson measure(BNP). To do that, I am using nltk and Wordnet 3.0. Next, I want to combine the similarity values obtai...
## How to normalize a single measure Let's consider a single arbitrary similarity measure `M` and take an arbitrary word `w`. Define `m = M(w,w)`. Then m takes maximum possible value of `M`. Let's define `MN` as a normalized measure `M`. For any two words `w, u` you can compute `MN(w, u) = M(w, u) / m`. It's easy ...
Cant get NaN elements dropped in pandas dataFrame
17,969,878
5
2013-07-31T12:03:54Z
17,970,198
12
2013-07-31T12:18:21Z
[ "python", "pandas", "dataframe" ]
I dont understand the how NaN's are being treated in pandas, would be happy to get some explanation, because the logic seems "broken" to me. I have a csv file, which im loading using read csv. i have a "comments" column in that file, which is empty most of the times. I've isolated that column, and tried varies ways t...
You should use `isnull` and `notnull` to test for NaN (these are more robust using pandas dtypes than numpy), see ["values considered missing" in the docs](http://pandas.pydata.org/pandas-docs/stable/missing_data.html#values-considered-missing). Using the Series method [`dropna`](http://pandas.pydata.org/pandas-docs/s...
Sending packets with Scapy within Python environment
17,971,398
4
2013-07-31T13:12:27Z
17,982,399
10
2013-07-31T22:54:59Z
[ "python", "scapy" ]
I am playing around with Scapy and I want to use it within a Python script but sending packets seem to be a problem. Here is my code. Scapy Shell: ``` send(IP(src="10.0.99.100",dst="10.1.99.100")/ICMP()/"Hello World") ``` This works fine and sends the packet. Python script: ``` #! /usr/bin/env python from scapy.a...
When you run this in the Python environment you are using the `sr1` function. The `sr1` function will send a packet and then wait for an answer, keeping a count of received packets. See more here - <http://www.secdev.org/projects/scapy/doc/usage.html#send-and-receive-packets-sr> To get the behavior you desire, you ne...
How to execute raw SQL in SQLAlchemy-flask app
17,972,020
72
2013-07-31T13:39:42Z
17,987,782
107
2013-08-01T07:32:51Z
[ "python", "sql", "sqlalchemy", "flask", "flask-sqlalchemy" ]
How do you execute raw SQL in SQLAlchemy? I have a python web app that runs on flask and interfaces to the database through SQLAlchemy. I need a way to run the raw SQL. The query involves multiple table joins along with Inline views. I've tried: ``` connection = db.session.connection() connection.execute( <sql here...
Have you tried: ``` result = db.engine.execute("<sql here>") ``` or: ``` from sqlalchemy import text sql = text('select name from penguins') result = db.engine.execute(sql) names = [] for row in result: names.append(row[0]) print names ```
How to execute raw SQL in SQLAlchemy-flask app
17,972,020
72
2013-07-31T13:39:42Z
18,808,942
35
2013-09-15T04:35:32Z
[ "python", "sql", "sqlalchemy", "flask", "flask-sqlalchemy" ]
How do you execute raw SQL in SQLAlchemy? I have a python web app that runs on flask and interfaces to the database through SQLAlchemy. I need a way to run the raw SQL. The query involves multiple table joins along with Inline views. I've tried: ``` connection = db.session.connection() connection.execute( <sql here...
docs: [SQL Expression Language Tutorial - Using Text](http://docs.sqlalchemy.org/en/rel_0_8/core/tutorial.html#using-text) example: ``` from sqlalchemy.sql import text connection = engine.connect() # recommended cmd = 'select * from Employees where EmployeeGroup == :group' employeeGroup = 'Staff' employees = connec...
How to execute raw SQL in SQLAlchemy-flask app
17,972,020
72
2013-07-31T13:39:42Z
22,084,672
36
2014-02-28T01:56:51Z
[ "python", "sql", "sqlalchemy", "flask", "flask-sqlalchemy" ]
How do you execute raw SQL in SQLAlchemy? I have a python web app that runs on flask and interfaces to the database through SQLAlchemy. I need a way to run the raw SQL. The query involves multiple table joins along with Inline views. I've tried: ``` connection = db.session.connection() connection.execute( <sql here...
If you want to use a session (as your question suggests), use its `execute` method directly: ``` import sqlalchemy from sqlalchemy.orm import sessionmaker, scoped_session engine = sqlalchemy.create_engine('my connection string') Session = scoped_session(sessionmaker(bind=engine)) s = Session() result = s.execute('SE...
How to execute raw SQL in SQLAlchemy-flask app
17,972,020
72
2013-07-31T13:39:42Z
26,714,562
10
2014-11-03T12:39:44Z
[ "python", "sql", "sqlalchemy", "flask", "flask-sqlalchemy" ]
How do you execute raw SQL in SQLAlchemy? I have a python web app that runs on flask and interfaces to the database through SQLAlchemy. I need a way to run the raw SQL. The query involves multiple table joins along with Inline views. I've tried: ``` connection = db.session.connection() connection.execute( <sql here...
You can get the results of SELECT SQL queries using `from_statement()` and `text()` as shown [here](http://docs.sqlalchemy.org/en/rel_0_9/orm/tutorial.html#using-literal-sql). You don't have to deal with tupules this way. As an example for a class User having the tablename 'users' you can try, ``` from sqlalchemy.sql ...
Error: command 'gcc' failed: No such file or directory
17,972,347
11
2013-07-31T13:52:36Z
17,979,541
12
2013-07-31T19:46:25Z
[ "python", "windows", "gcc", "mingw", "installation" ]
I'm trying to run a ``` python setup.py build --compiler=mingw32 ``` but it results in the error mentioned in the subject: ``` error: command 'gcc' failed: No such file or directory ``` but I am capable of running gcc from command prompt (i have added it to my PATH env var): ``` >gcc gcc: fatal error: no input fil...
After hours and hours of searching, I've discovered that this is a problem between MinGW and Python. They don't communicate well with one another. There exists a binary package of MinGW (unofficial) that was meant for use with Python located [here](https://github.com/develersrl/gccwinbinaries) It fixes the problem!
Using Beautiful Soup to get the full URL in source code
17,972,496
5
2013-07-31T13:59:01Z
17,999,502
10
2013-08-01T16:24:04Z
[ "python" ]
So I was looking at some source code and I came across this bit of code ``` <img src="/gallery/2012-winners-finalists/HM_Watching%20birds2_Shane%20Conklin_MA_2012.jpg" ``` now in the source code the link is blue and when you click it, it takes you to the full URL where that picture is located, I know how to get what ...
``` <a href="/folder/big/a.jpg"> ``` That’s an absolute address for the current host. So if the HTML file is at `http://example.com/foo/bar.html`, then applying the url `/folder/big/a.jpg` will result in this: ``` http://example.com/folder/big/a.jpg ``` I.e. take the host name and apply the new path to it. Python...
check if string in pandas dataframe column is in list
17,972,938
16
2013-07-31T14:18:28Z
17,973,255
28
2013-07-31T14:31:27Z
[ "python", "python-2.7", "pandas" ]
If I have a frame like this ``` frame = pd.DataFrame({'a' : ['the cat is blue', 'the sky is green', 'the dog is black']}) ``` and I want to check if any of those rows contain a certain word I just have to do this. ``` frame['b'] = frame.a.str.contains("dog") | frame.a.str.contains("cat") | frame.a.str.contains("fish...
The [`str.contains`](http://pandas.pydata.org/pandas-docs/stable/basics.html#vectorized-string-methods) method accepts a regular expression pattern: ``` In [11]: pattern = '|'.join(mylist) In [12]: pattern Out[12]: 'dog|cat|fish' In [13]: frame.a.str.contains(pattern) Out[13]: 0 True 1 False 2 True Name: ...
Function that returns a tuple gives TypeError: 'NoneType' object is not iterable
17,974,383
4
2013-07-31T15:20:00Z
17,974,408
7
2013-07-31T15:21:14Z
[ "python" ]
What does this error mean? I'm trying to make a function that returns a tuple. I'm sure i'm doing all wrong. Any help is appreciated. ``` from random import randint A = randint(1,3) B = randint(1,3) def make_them_different(a,b): while a == b: a = randint(1,3) b = randint(1,3) return (a,b) n...
Your code returns `None` if `a != b`. Since, you have the `return` statement inside the while loop, if the while loop never gets executed, Python returns the default value of `None` which cannot be assigned to `new_A, new_B`. ``` >>> print make_them_different(2, 3) None >>> print make_them_different(2, 2) (2, 1) ```...
Using Python's Requests library to navigate webpages / Click buttons
17,974,826
9
2013-07-31T15:40:44Z
20,138,837
7
2013-11-22T06:53:07Z
[ "python", "webpage", "python-requests" ]
I'm new to web programming, and have recently began looking into using Python to automate some manual processes. What I'm trying to do is log into a site, click some drop-down menus to select settings, and run a report. I've found the acclaimed requests library: <http://docs.python-requests.org/en/latest/user/advanced...
The only solution to this I have found is [Selenium](http://www.seleniumhq.org/). If it werent a javascript heavy website you could try [mechanize](http://wwwsearch.sourceforge.net/mechanize/) but for this you need to render the javascript and then inject javascript...like Selenium does. Upside: You can record actions...
selenium with scrapy for dynamic page
17,975,471
25
2013-07-31T16:08:28Z
17,979,285
46
2013-07-31T19:33:04Z
[ "python", "selenium", "selenium-webdriver", "web-scraping", "scrapy" ]
I'm trying to scrape product information from a webpage, using scrapy. My to-be-scraped webpage looks like this: * starts with a product\_list page with 10 products * a click on "next" button loads the next 10 products (url doesn't change between the two pages) * i use LinkExtractor to follow each product link into th...
It really depends on how do you need to scrape the site and how and what data do you want to get. Here's an example how you can follow pagination on ebay using `Scrapy`+`Selenium`: ``` import scrapy from selenium import webdriver class ProductSpider(scrapy.Spider): name = "product_spider" allowed_domains = [...
How to create tzinfo when I have UTC offset?
17,976,063
11
2013-07-31T16:37:35Z
28,270,767
7
2015-02-02T03:38:29Z
[ "python", "python-2.7" ]
I have one timezone's offset from UTC in seconds (`19800`) and also have it in string format - `+0530`. How do I use them to create a `tzinfo` instance? I looked into `pytz`, but there I could only find APIs that take timezone name as input.
If you can, take a look at the excellent [dateutil](https://labix.org/python-dateutil) package instead of implementing this yourself. Specifically, [tzoffset](https://labix.org/python-dateutil#head-8bf499d888b70bc300c6c8820dc123326197c00f). It's a fixed offset `tzinfo` instance initialized with `offset`, given in seco...
Matplotlib - Broken axis example: uneven subplot size
17,976,103
3
2013-07-31T16:39:59Z
17,989,016
7
2013-08-01T08:37:48Z
[ "python", "matplotlib", "subplot" ]
I haven't found a solution to adjust the height of the bottom and top plot of the [broken axis example](http://matplotlib.org/examples/pylab_examples/broken_axis.html) of [matplotlib](http://matplotlib.org/examples). BTW: The space between the two plots can be adjusted by: ``` plt.subplots_adjust(hspace=0.03) ``` **...
My own solution looks like (using gridspec, assuming that the units of the two y-axis should be equal): ``` """ Broken axis example, where the y-axis will have a portion cut out. """ import matplotlib.pylab as plt import matplotlib.gridspec as gridspec import numpy as np pts = np.array([ 0.015, 0.166, 0.133,...
Pandas: Looking up the list of sheets in an excel file
17,977,540
22
2013-07-31T17:57:19Z
17,977,609
42
2013-07-31T18:01:21Z
[ "python", "pandas" ]
The new version of Pandas uses [the following interface](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.io.excel.read_excel.html#pandas.io.excel.read_excel) to load Excel files: ``` read_excel('path_to_file.xls', 'Sheet1', index_col=None, na_values=['NA']) ``` but what if I don't know the sheets that are a...
You can still use the [ExcelFile](http://pandas.pydata.org/pandas-docs/dev/io.html#excel-files) class (and the `sheet_names` attribute): ``` xl = pd.ExcelFile('foo.xls') xl.sheet_names # see all sheet names xl.parse(sheet_name) # read a specific sheet to DataFrame ``` *see [docs for parse](http://pandas.pydata.or...
Python: importing another .py file
17,977,564
5
2013-07-31T17:58:44Z
17,978,157
7
2013-07-31T18:31:56Z
[ "python", "import", "function" ]
I have a class and I want to import a def function by doing: ``` import <file> ``` but when I try to call it, it says that the def can not be found. I also tried: ``` from <file> import <def> ``` but then it says global name 'x' is not defined. So how can I do this? Edit: Here is a example of what I am trying to...
``` import file2 ``` loads the module `file2` and binds it to the name `file2` in the current namespace. `b` from `file2` is available as `file2.b`, not `b`, so it isn't recognized as a method. You could fix it with ``` from file2 import b ``` which would load the module and assign the `b` function from that module ...
Combine Date and Time columns using python pandas
17,978,092
20
2013-07-31T18:27:40Z
17,978,188
30
2013-07-31T18:33:05Z
[ "python", "pandas" ]
I have a pandas dataframe with the following columns; ``` Date Time 01-06-2013 23:00:00 02-06-2013 01:00:00 02-06-2013 21:00:00 02-06-2013 22:00:00 02-06-2013 23:00:00 03-06-2013 01:00:00 03-06-2013 21:00:00 03-06-2013 22:00:00 03-06-2013 23:00:00 04-06-2013 ...
It's worth mentioning that you may have been able to read this in **directly** e.g. if you were using [`read_csv`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.parsers.read_csv.html) using `parse_dates=[['Date', 'Time']]`. Assuming these are just strings you could simply add them together (with a sp...
Python Pandas merge only certain columns
17,978,133
16
2013-07-31T18:30:28Z
17,978,414
13
2013-07-31T18:46:03Z
[ "python", "merge", "pandas" ]
Is it possible to only merge some columns? I have df1 with columns x,y,x and df2 with columns x,a,b,c,d,e,f,etc. I want to merge the two dfs on x, but I only want to merge columns df2.a, df2.b - not the entire dataframe. The result would be df1=x,y,z,a,b I could merge then delete the unwanted columns, but it seems l...
You could merge the sub-DataFrame (with just those columns): ``` df2[list('xab')] # df2 but only with columns x, a, and b df1.merge(df2[list('xab')]) ```
How to implement autoretry for Celery tasks
17,979,655
10
2013-07-31T19:52:43Z
17,979,656
9
2013-07-31T19:52:43Z
[ "python", "celery" ]
In Celery, you can `retry` any task in case of exception. You can do it like so: ``` @task(max_retries=5) def div(a, b): try: return a / b except ZeroDivisionError, exc: raise div.retry(exc=exc) ``` In this case, if you want to to divide by zero, task will be retied five times. But you have to...
I searched this issue for a while, but found only [this feature request](https://github.com/celery/celery/issues/1175). I decide to write my own decorator for doing auto-retries: ``` def task_autoretry(*args_task, **kwargs_task): def real_decorator(func): @task(*args_task, **kwargs_task) @functool...
Writing Python ctypes for Function pointer callback function in C
17,980,167
5
2013-07-31T20:19:50Z
17,982,521
7
2013-07-31T23:07:14Z
[ "python", "c", "ctypes" ]
I am trying to write python code to call dll functions and stuck at the function below, which I believe is related to the typedef callback function or the function pointer thing. I have tested the code below, when the callback function is called, python crashes (Window notification-- python.exe has stop responding) wi...
Your callback type has the wrong signature; you forgot the result type. It's also getting garbage collected when the function exits; you need to make it global. Your `GetStatus` call is missing the argument `pArg`. Plus when working with pointers you need to define `argtypes`, else you'll have problems on 64-bit platf...
Using python 'requests' to send JSON boolean
17,980,362
2
2013-07-31T20:30:48Z
17,980,622
7
2013-07-31T20:43:40Z
[ "python", "rest", "python-requests" ]
I've got a really simple question, but I can't figure it out how to do it. The problem I have is that I want to send the following payload using Python and Requests: ``` { 'on': true } ``` Doing it like this: ``` payload = { 'on':true } r = requests.put("http://192.168.2.196/api/newdeveloper/lights/1/state", data = ...
You need to json encode it to get it to a string. ``` import json payload = json.dumps({"on":True}) ```
How to change list of str into list of floats
17,981,093
2
2013-07-31T21:13:27Z
17,981,141
9
2013-07-31T21:16:06Z
[ "python", "string", "list", "floating-point" ]
``` def avg_temp_march(f): """(file open for reading) -> float Return the average temperature for the month of March over all years in f. """ file = open(f, 'r') file.readline() file.readline() file.readline() lines = file.read().strip().split('\n') file.close for line in...
Simply use `map`: ``` >>> l = ["1.2", "2.4"] >>> print map(float, l) [1.2, 2.4] >>> ```
Matrix completion in Python
17,982,931
8
2013-07-31T23:47:45Z
18,001,880
11
2013-08-01T18:34:11Z
[ "python", "numpy", "machine-learning", "scikit-learn", "mathematical-optimization" ]
Say I have a matrix: ``` > import numpy as nap > a = np.random.random((5,5)) array([[ 0.28164485, 0.76200749, 0.59324211, 0.15201506, 0.74084168], [ 0.83572213, 0.63735993, 0.28039542, 0.19191284, 0.48419414], [ 0.99967476, 0.8029097 , 0.53140614, 0.24026153, 0.94805153], [ 0.92478 ...
If you install the latest scikit-learn, version 0.14a1, you can use its shiny new `Imputer` class: ``` >>> from sklearn.preprocessing import Imputer >>> imp = Imputer(strategy="mean") >>> a = np.random.random((5,5)) >>> a[(1,4,0,3),(2,4,2,0)] = np.nan >>> a array([[ 0.77473361, 0.62987193, nan, 0.11367791, ...
Understanding python try catch else finally clause behavior
17,983,240
3
2013-08-01T00:23:21Z
17,983,282
7
2013-08-01T00:27:48Z
[ "python" ]
Python 2.6.5 (r265:79063, Oct 1 2012, 22:07:21) I have this: ``` def f(): try: print "a" return except: print "b" else: print "c" finally: print "d" f() ``` This gives: ``` a d ``` and not the expected ``` a c d ``` If I comment out the return, then I wil...
When in doubt, consult [the docs](http://docs.python.org/2/reference/compound_stmts.html#try): > The optional `else` clause is executed if and when control flows off the end of the `try` clause > > Currently, control “flows off the end” except in the case of an exception or the execution of a `return`, `continue`,...
How do I create a incrementing filename in python?
17,984,809
2
2013-08-01T03:31:01Z
17,984,925
12
2013-08-01T03:46:04Z
[ "python", "file-io" ]
I'm creating a program that will create a file and save it to the directory with the filename sample.xml. Once the file is saved when i try to run the program again it overwrites the old file into the new one because they do have the same file name. How do I increment the file names so that whenever I try to run the co...
I would iterate through `sample[int].xml` for example and grab the next available name that is not used by a file or directory. ``` import os i = 0 while os.path.exists("sample%s.xml" % i): i += 1 fh = open("sample%s.xml" % i, "w") .... ``` That should give you *sample0.xml* initially, then *sample1.xml*, etc. ...
In python c = pickle.load(open(fileName, 'r')) does this close the file?
17,985,224
4
2013-08-01T04:20:35Z
17,985,230
9
2013-08-01T04:22:10Z
[ "python", "pickle" ]
I tried to Google but cannot find an answer. If I just do ``` c = pickle.load(open(fileName, 'r')) ``` Will the file be automatically closed after this operation?
No, but you can simply adapt it to close the file: ``` # file not yet opened with open(fileName, 'r') as f: # file opened c = pickle.load(f) # file opened # file closed ``` What `with` statement does, is (among other things) calling `__exit__()` method of object listed in `with` statement (in this case: o...
String comparison in python words ending with
17,985,407
7
2013-08-01T04:44:43Z
17,985,424
8
2013-08-01T04:46:05Z
[ "python" ]
I have a set of words as follows: ``` ['Hey, how are you?\n','My name is Mathews.\n','I hate vegetables\n','French fries came out soggy\n'] ``` In the above sentences i need to identify all sentences ending with `?` or `.` or 'gy'. and print the final word. My approach is as follows: ``` # words will contain the st...
Use [`endswith()`](http://docs.python.org/2/library/stdtypes.html#str.endswith) method. ``` >>> for line in testList: for word in line.split(): if word.endswith(('?', '.', 'gy')) : print word ``` Output: ``` you? Mathews. soggy ```
Running selenium behind a proxy server
17,988,821
10
2013-08-01T08:28:27Z
17,988,970
14
2013-08-01T08:35:45Z
[ "python", "selenium", "selenium-webdriver", "proxy", "web-scraping" ]
I have been using selenium for automatic browser simulations and web scraping in python and it has worked well for me. But now, I have to run it behind a proxy server. So now selenium open up the window but could not open the requested page because of proxy settings not set on the opened browser. Current code is as fol...
You need to set desired capabilities or browser profile, like this: ``` profile = webdriver.FirefoxProfile() profile.set_preference("network.proxy.type", 1) profile.set_preference("network.proxy.http", "proxy.server.address") profile.set_preference("network.proxy.http_port", "port_number") profile.update_preferences()...
Imshow subplots with the same colorbar
17,989,917
8
2013-08-01T09:18:02Z
17,995,116
15
2013-08-01T13:14:59Z
[ "python", "matplotlib" ]
I want to make 4 `imshow` subplots but all of them share the same colormap. Matplotlib automatically adjusts the scale on the colormap depending on the entries of the matrices. For example, if one of my matrices has all entires as 10 and the other one has all entries equal to 5 and I use the `Greys` colormap then one o...
To get this right you need to have all the images with the same intensity scale, otherwise the `colorbar()` colours are meaningless. To do that, use the `vmin` and `vmax` arguments of `imshow()`, and make sure they are the same for all your images. E.g., if the range of values you want to show goes from 0 to 10, you c...
Scanning a list
17,990,500
11
2013-08-01T09:43:01Z
17,990,617
13
2013-08-01T09:47:43Z
[ "python" ]
I need to scan a list in Python. I'm able to load it from file and do simple operation, but I was trying to do the following: ``` L = [1,2,3,4,5,6,7,8] ``` Starting from the first element I want to produce the following output: ``` 1 2,3,4,5,6,7,8 3,4,5,6,7,8 4,5,6,7,8 5,6,7,8 6,7,8 7,8 8 2 3,4,5,6,7...
How's this? Nice and simple to read: ``` >>> for i, j in enumerate(L): ... print L[i] ... temp = map(str, L[j:]) ... while temp: ... print ' ', ','.join(temp) ... temp = temp[1:] ... 1 2,3,4,5,6,7,8 3,4,5,6,7,8 4,5,6,7,8 5,6,7,8 6,7,8 7,8 8 2 3,4,5,6,7,8 4,5,6,7,8...
How to equalize the scales of x-axis and y-axis in Python matplotlib?
17,990,845
31
2013-08-01T09:58:28Z
17,992,093
11
2013-08-01T10:55:13Z
[ "python", "matplotlib" ]
I wish to draw lines on a **SQUARE** graph. The scales of `x-axis` and `y-axis` should be the same. e.g. x ranges from 0 to 10 and it is 10cm on the screen. y has to also range from 0 to 10 and has to be also 10 cm. **The SQUARE shape has to be maintained, even if I mess around with the window size.** Currently, my...
Try something like: ``` import pylab as p p.plot(x,y) p.axis('equal') p.show() ```
How to equalize the scales of x-axis and y-axis in Python matplotlib?
17,990,845
31
2013-08-01T09:58:28Z
17,996,099
41
2013-08-01T13:56:22Z
[ "python", "matplotlib" ]
I wish to draw lines on a **SQUARE** graph. The scales of `x-axis` and `y-axis` should be the same. e.g. x ranges from 0 to 10 and it is 10cm on the screen. y has to also range from 0 to 10 and has to be also 10 cm. **The SQUARE shape has to be maintained, even if I mess around with the window size.** Currently, my...
You need to dig a bit deeper into the api to do this: ``` plt.plot(range(5)) plt.xlim(-3, 3) plt.ylim(-3, 3) plt.gca().set_aspect('equal', adjustable='box') plt.draw() ``` [doc for set\_aspect](http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.set_aspect)
Installing python packages in nitrousio
17,992,580
6
2013-08-01T11:17:18Z
17,992,898
11
2013-08-01T11:33:10Z
[ "python", "package", "pip", "nitrousio" ]
I've just started trying to use Nitrous.io. I've made a box with python, and am trying to use pip to install a python package called praw. It downloads all of the information fine, but on running the install script, I get an error stating that it could not create a file due to permission restrictions in the /usr direc...
You could try `pip install --user praw` <https://pip.pypa.io/en/latest/user_guide.html#user-installs>
Python two list lists shuffle
17,993,008
2
2013-08-01T11:38:26Z
17,993,064
9
2013-08-01T11:41:20Z
[ "python", "list" ]
I have two list: ``` a = [1, 2, 3, 4] b = [5, 6, 7, 8] ``` I need to get something like this: ``` c = [1, 5, 2, 6, 3, 7, 4, 8] ``` I use this solution: ``` c = list(reduce(lambda x, y: x + y, zip(a, b))) ``` Is there a better way to do this?
Using *List Comprehension*: ``` >>> [x for tup in zip(a, b) for x in tup] [1, 5, 2, 6, 3, 7, 4, 8] ``` The above nested list comprehension is equivalent to following nested for loops (Just in case you get confused): ``` result = [] for tup in zip(a, b): for x in tup: result.append(x) ```
Can a django formset that dynamically adds fields have persistent data?
17,996,537
7
2013-08-01T14:13:50Z
18,106,485
7
2013-08-07T14:44:28Z
[ "python", "database", "django", "django-forms" ]
I am making a formset in python/django and need to dynamically add more fields to a formset as a button is clicked. The form I'm working on is for my school asking students who they would like to disclose certain academic information to, and the button here allows them to add more fields for entering family members/peo...
I've had trouble with dynamically adding fields in Django before and this stackoverflow question helped me: [dynamically add field to a form](http://stackoverflow.com/questions/6142025/dynamically-add-field-to-a-form) To be honest, I'm not entirely sure what you mean by "persistent" in your case - are the values of yo...
Best practice for refactoring a python function to return a tuple, instead of a single variable?
18,000,918
2
2013-08-01T17:38:58Z
18,000,946
8
2013-08-01T17:40:40Z
[ "python", "tuples", "return-value" ]
I am refactoring a python function in a large codebase. Currently, it looks like: ``` def GetEvents(file_path): ... return events #a list of Event objects ``` A bunch of code depends on this function returning a list object already. However, I want to refactor it so it returns: ``` def GetEvents(file_path)...
*Rename* the function to `GetEventsAndHeader()`, and add a new function `GetEvents()`: ``` def GetEvents(*args, **kw): return GetEventsAndHeader(*args, **kw)[0] ``` or just bite the bullet and update all code that calls `GetEvents()` and adjust that code to either use the returnvalue indexed to `[0]` or make use ...
Latex Citation in matplotlib Legend
18,001,485
9
2013-08-01T18:11:07Z
18,022,601
8
2013-08-02T17:14:37Z
[ "python", "matplotlib", "latex" ]
I am generating figures for a technical paper using Python with matplotlib. Is there a way to include a Latex/Bibtex citation in the legend text? Ideally I would like a solution something like the following but haven't found anything that works: ``` import numpy as np import matplotlib as mp import matplotlib.pyplot a...
This can be done using the matplotlib pgf backend for python. The python file for generating the graph is as follows: ``` import numpy as np import matplotlib as mpl mpl.use('pgf') import matplotlib.pyplot as plt x = np.linspace(0., 1., num=100) y = x**2 plt.plot(x, y, label=r'Data \cite{<key>}') plt.legend(loc=0) p...
xlsxwriter: is there a way to open an existing worksheet in my workbook?
18,002,133
7
2013-08-01T18:48:03Z
25,121,481
12
2014-08-04T14:50:01Z
[ "python", "worksheet", "xlsxwriter" ]
I'm able to open my pre-existing workbook, but I don't see any way to open pre-existing worksheets within that workbook. Is there any way to do this?
You cannot append to an existing xlsx file with `xlsxwriter`. There is a module called [openpyxl](https://pythonhosted.org/openpyxl/) which allows you to read and write to preexisting excel file, but I am sure that the method to do so involves reading from the excel file, storing all the information somehow (database ...
Local variable referenced before assignment in Python?
18,002,794
17
2013-08-01T19:24:37Z
18,002,911
10
2013-08-01T19:30:22Z
[ "python", "python-2.7", "python-3.x", "variable-assignment" ]
I am using the PyQt library to take a screenshot of a webpage, then reading through a CSV file of different URLs. I am keeping a variable feed that incremements everytime a URL is processed and therefore should increment to the number of URLs. Here's code: ``` webpage = QWebPage() fo = open("C:/Users/Romi/Desktop/res...
Put a global statement at the top of your function and you should be good: ``` def onLoadFinished(result): global feed ... ``` To demonstrate what I mean, look at this little test: ``` x = 0 def t(): x += 1 t() ``` this blows up with your exact same error where as: ``` x = 0 def t(): global x x...
Local variable referenced before assignment in Python?
18,002,794
17
2013-08-01T19:24:37Z
18,002,922
28
2013-08-01T19:31:09Z
[ "python", "python-2.7", "python-3.x", "variable-assignment" ]
I am using the PyQt library to take a screenshot of a webpage, then reading through a CSV file of different URLs. I am keeping a variable feed that incremements everytime a URL is processed and therefore should increment to the number of URLs. Here's code: ``` webpage = QWebPage() fo = open("C:/Users/Romi/Desktop/res...
When Python parses the body of a function definition and encounters an assignment such as ``` feed = ... ``` Python interprets `feed` as a local variable by default. If you do not wish for it to be a local variable, you must put ``` global feed ``` in the function definition. The global statement does not have to b...
Dynamically calculated zero padding in format string in python
18,004,646
11
2013-08-01T21:11:21Z
18,004,686
17
2013-08-01T21:13:50Z
[ "python", "string-formatting" ]
So I know that `"%02d to %02d"%(i, j)` in Python will zero pad `i` and `j`. But, I was wondering if there is any way to dynamically zero pad in a format string (I have a list of numbers and I want the zero pad size to be equal to the longest number in that list). I know that I could use `zfill`, but I was hoping I co...
Use the `str.format()` method of string formatting instead: ``` '{number:0{width}d}'.format(width=2, number=4) ``` Demo: ``` >>> '{number:0{width}d}'.format(width=2, number=4) '04' >>> '{number:0{width}d}'.format(width=8, number=4) '00000004' ``` The [`str.format()` formatting specification](http://docs.python.org/...
Get the object with the max attribute's value in a list of objects
18,005,172
7
2013-08-01T21:44:06Z
18,005,197
23
2013-08-01T21:45:55Z
[ "python", "class", "python-3.x", "attributes" ]
Even though this is my first post on stackoverflow, the topics here have been of great help while learning Python. I'm still in the early stages of learning the programming language and there's one thing i have a hard time wrapping my mind around. This is the code i written so far, and the point with the program is to ...
`max()` takes a `key` parameter, a function that when passed one of the objects returns the value by which to compare them. Use `operator.attrgetter()` to get that value: ``` from operator import attrgetter max(self.allPartners, key=attrgetter('attrOne')) ``` This returns the matching object for which that attribut...
Django 1.5 GET 404 on static files
18,005,574
5
2013-08-01T22:15:25Z
18,005,942
7
2013-08-01T22:47:26Z
[ "python", "django", "static", "http-status-code-404" ]
I need a little help with this, I've been searching for a solution with no results. This are my settings: settings.py: ``` STATIC_ROOT = '' # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = '/static/' PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATICFILES_DI...
Are you sure your `STATICFILE_DIRS` is correct? If your settings is like at the moment, the `static` folder is supposed to be in same level as `settings.py`. ``` PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) # it means settings.py is in PROJECT_ROOT? STATICFILES_DIRS = ( PROJECT_ROOT + '/static/', # <=...
Is there a way to get the Pyramid json renderer to output formatted, pretty printed, output?
18,005,861
5
2013-08-01T22:40:26Z
18,005,946
9
2013-08-01T22:47:42Z
[ "python", "json", "rest", "pyramid" ]
I like my json output to be nicely formatted, even for a REST API. It helps when debugging, etc. The extra overhead is minimal, especially when using gzip Is there anyway to tell the pyramid json renderer (i.e, this thing) ``` @view_config(request_method='POST', renderer='json') ``` to output formatted, pretty-p...
I just figured it out myself. In my **init** I added ``` from pyramid.renderers import JSON # ... config.add_renderer('prettyjson', JSON(indent=4)) ``` and then I just do this in my view ``` @view_config(request_method='POST', renderer='prettyjson') ```
Python bottle vs uwsgi/bottle vs nginx/uwsgi/bottle
18,006,014
4
2013-08-01T22:53:51Z
18,006,120
8
2013-08-01T23:05:09Z
[ "python", "nginx", "uwsgi", "bottle" ]
I am developing a Python based application (HTTP -- REST or jsonrpc interface) that will be used in a production automated testing environment. This will connect to a Java client that runs all the test scripts. I.e., no need for human access (except for testing the app itself). We hope to deploy this on Raspberry Pi's...
Flask vs Bottle comes down to a couple of things for me. 1. How simple is the app. If it is *very* simple, then bottle is my choice. If not, then I got with Flask. The fact that bottle is a single file makes it incredibly simple to deploy with by just including the file in our source. But the fact that bottle is a sin...
How to pass dictionary as command line argument to python script?
18,006,161
6
2013-08-01T23:10:19Z
18,006,814
12
2013-08-02T00:22:37Z
[ "python", "python-2.7" ]
How to pass dictionary as command line argument to python script ? I need to get dictionary where key is string and value is list of some elements ( for example to look like : ``` command_line_arguments = {"names" : ["J.J.", "April"], "years" : [25, 29]} ``` I have tried like ``` if __name__ == '__main__': args ...
The important thing to note here is that at the command line you cannot pass in python objects as arguments. The current shell you are using will parse the arguments and pass them in according to it's own argument parsing rules. That being said, you cannot pass in a python dictionary. However, things like JSON can all...
Comparing elements in different lists python
18,006,355
2
2013-08-01T23:29:36Z
18,006,372
11
2013-08-01T23:31:50Z
[ "python", "list", "compare" ]
I have four elements to compare with ``` A= [1,2,3,4] B=[1,2] C= [3,5,6] D= [2, 4, 5, 6,7] ``` How do I compare which one has the greatest len?
You can use [`max`](http://docs.python.org/2/library/functions.html#max) with a key. ``` max(a,b,c,d,key=len) ```
How to check if a couchdb document exists using python
18,010,876
4
2013-08-02T07:12:58Z
18,011,933
8
2013-08-02T08:13:17Z
[ "python", "couchdb" ]
I was wondering if there is a way to check if a document with a particular ID exists in couchdb using couch python library. It seems that if I do this: ``` server = couchdb.Server('http://localhost:5984') db = server['tweets'] mytemp = db[MyDocId] ``` and the document doesn't exist, the code throws a "ResourceNotFoun...
The database object mimics to dict api, so it's very simple and native to check for docs in database: ``` server = couchdb.Server('http://localhost:5984') db = server['tweets'] if MyDocId in db: mytemp = db[MyDocId] mytemp = db.get(MyDocId) if mytemp is None: print "missed" ``` See [couchdb-python docs](http://p...
py.test: Pass a parameter to a fixture function
18,011,902
20
2013-08-02T08:11:46Z
18,098,713
7
2013-08-07T08:44:45Z
[ "python", "fixtures", "py.test" ]
I am using py.test to test some DLL code wrapped in a python class MyTester. For validating purpose I need to log some test data during the tests and do more processing afterwards. As I have many test\_... files I want to reuse the tester object creation (instance of MyTester) for most of my tests. As the tester objec...
You can access the requesting module/class/function from fixture functions (and thus from your Tester class), see [interacting with requesting test context from a fixture function](http://pytest.org/latest/fixture.html#fixtures-can-introspect-the-requesting-test-context). So you could declare some parameters on a class...
py.test: Pass a parameter to a fixture function
18,011,902
20
2013-08-02T08:11:46Z
28,570,677
22
2015-02-17T20:36:40Z
[ "python", "fixtures", "py.test" ]
I am using py.test to test some DLL code wrapped in a python class MyTester. For validating purpose I need to log some test data during the tests and do more processing afterwards. As I have many test\_... files I want to reuse the tester object creation (instance of MyTester) for most of my tests. As the tester objec...
I had a similar problem--I have a fixture called `test_package`, and I later wanted to be able to pass an optional argument to that fixture when running it in specific tests. For example: ``` @pytest.fixture() def test_package(request, version='1.0'): ... request.addfinalizer(fin) ... return package ``...
py.test: Pass a parameter to a fixture function
18,011,902
20
2013-08-02T08:11:46Z
33,879,151
7
2015-11-23T19:34:42Z
[ "python", "fixtures", "py.test" ]
I am using py.test to test some DLL code wrapped in a python class MyTester. For validating purpose I need to log some test data during the tests and do more processing afterwards. As I have many test\_... files I want to reuse the tester object creation (instance of MyTester) for most of my tests. As the tester objec...
This is actually supported natively in py.test via [indirect parametrization](https://pytest.org/latest/example/parametrize.html#apply-indirect-on-particular-arguments). In your case, you would have: ``` @pytest.fixture def tester(request): """Create tester object""" return MyTester(request.param) class Tes...
python pandas dataframe columns convert to dict key and value
18,012,505
9
2013-08-02T08:46:33Z
18,013,682
23
2013-08-02T09:42:17Z
[ "python", "dictionary", "data-conversion", "dataframe" ]
A python pandas dataframe with multi-columns, there are only two columns needed for dict. One as dict's keys and another as dict's values. How can I do that? Dataframe: ``` area count co tp DE Lake 10 7 Forest 20 5 FR Lake 30 2 Forest 40 3 ``` Need to define area...
If `lakes` is your `DataFrame`, you can do something like ``` area_dict = dict(zip(lakes.area, lakes.count)) ```
How can one customize Django Rest Framework serializers output?
18,012,665
6
2013-08-02T08:53:59Z
18,013,475
11
2013-08-02T09:33:12Z
[ "python", "django", "json", "django-rest-framework" ]
I have a Django model that is like this: ``` class WindowsMacAddress(models.Model): address = models.TextField(unique=True) mapping = models.ForeignKey('imaging.WindowsMapping', related_name='macAddresses') ``` And two serializers, defined as: ``` class WindowsFlatMacAddressSerializer(serializers.Serializer)...
Create a [custom serializer field](http://www.django-rest-framework.org/api-guide/fields/#custom-fields) and implement `to_native` so that it returns the list you want. If you use the [`source="*"` technique](http://django-rest-framework.org/api-guide/fields/#core-arguments) then something like this might work: ``` c...
Drawing lattices and graphs with Networkx
18,013,580
5
2013-08-02T09:38:08Z
18,018,534
7
2013-08-02T13:48:22Z
[ "python", "matplotlib", "networkx" ]
I want to draw a square lattice with `Networkx`. I did something like this: ``` import matplotlib.pyplot as plt import numpy as np import networkx as nx L=4 G = nx.Graph() pos={} for i in np.arange(L*L): pos[i] = (i/L,i%L) nx.draw_networkx_nodes(G,pos,node_size=50,node_color='k') plt.show() ``` However the...
These is an explicit graph constructor for this [`nx.grid_2d_graph`](http://networkx.lanl.gov/reference/generated/networkx.generators.classic.grid_2d_graph.html#networkx.generators.classic.grid_2d_graph): ``` G = nx.grid_2d_graph(L,L) nx.draw(G,node_size=2000) plt.show() ``` ![enter image description here](http://i.s...
Length of a finite generator
18,014,437
6
2013-08-02T10:14:47Z
18,014,500
11
2013-08-02T10:18:01Z
[ "python", "generator" ]
I have these two implementations to compute the length of a finite generator, while keeping the data for further processing: ``` def count_generator1(generator): '''- build a list with the generator data - get the length of the data - return both the length and the original data (in a list) WA...
If you have to do this, the first method is much better - as you consume all the values, `itertools.tee()` will have to store all the values anyway, meaning a list will be more efficient. To quote from [the docs](http://docs.python.org/3/library/itertools.html#itertools.tee): > This itertool may require significant a...
Slice pandas series with elements not in the index
18,015,094
7
2013-08-02T10:49:44Z
18,015,520
7
2013-08-02T11:14:58Z
[ "python", "pandas", "series", "slice" ]
I have a pandas series indexed by tuples, like this: ``` from pandas import Series s = Series({(0, 0): 1, (0, 1): 2, (0, 3): 3, (1, 0): 1, (1, 2): 4, (3, 0): 5}) ``` I want to slice such a series by using indexes that are also tuples (using lexicographic ordering), but not necessarily in the index. Slicing seems to w...
This works if you have a MultiIndex rather than an index of tuples: ``` In [11]: s.index = pd.MultiIndex.from_tuples(s.index) In [12]: s Out[12]: 0 0 1 1 2 3 3 1 0 1 2 4 3 0 5 dtype: int64 In [13]: s[:(1,1)] Out[13]: 0 0 1 1 2 3 3 1 0 1 dtype: int64 ``` *In a prev...