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
How to extract specific digits after underscore from filename in python
16,816,379
2
2013-05-29T14:18:07Z
16,816,571
9
2013-05-29T14:26:07Z
[ "python", "regex", "python-2.7", "python-3.x", "filenames" ]
I have a number of file names like: ``` /home/abc/xyz/12345_993456_pqr /home/abc/xyz/12345_883456_pqr /home/abc/xyz/12345_773456_pqr ``` I need to extract the first two digits right after the first underscore i.e. `99` or `88` or `77`. It's not `99/88/77` always...just an example...I tried with: ``` re.search() ``` ...
Step by step: ``` >>> import os >>> os.path.basename('/home/abc/xyz/12345_993456_pqr') '12345_993456_pqr' >>> os.path.basename('/home/abc/xyz/12345_993456_pqr').split('_') ['12345', '993456', 'pqr'] >>> os.path.basename('/home/abc/xyz/12345_993456_pqr').split('_')[1] '993456' >>> os.path.basename('/home/abc/xyz/123...
django-allauth configuration doubts
16,817,157
5
2013-05-29T14:51:27Z
16,824,799
14
2013-05-29T22:14:07Z
[ "python", "django", "login", "django-allauth" ]
I'm using [django-allauth](https://github.com/pennersr/django-allauth) with Django 1.5.1 and I have a few questions when setting it up: **1. Configure `urls.py`** The docs says that you have to add the following to `urls.py` file: ``` urlpatterns = patterns('', ... (r'^accounts/', include('allauth.urls')), ...
With respect to 1): * There is no collision as long as there is no overlap in the fully matched URL patterns. For example: if your accounts app has a match for "/accounts/login/" then there is indeed a collision as allauth is gunning for that URL as well. But, if your accounts app simply matches other URLs with /accou...
I have need the N minimum (index) values in a numpy array
16,817,948
4
2013-05-29T15:24:49Z
16,818,047
11
2013-05-29T15:28:12Z
[ "python", "arrays", "numpy", "minimum" ]
Hi I have an array with X amount of values in it I would like to locate the indexs of the ten smallest values. In this link they calculated the maximum effectively, [How to get the N maximum values in a numpy array?](http://stackoverflow.com/questions/6910641/how-to-get-the-n-maximum-values-in-a-numpy-array) however I ...
If you call ``` arr.argsort()[:3] ``` It will give you the indices of the 3 smallest elements. ``` array([0, 2, 1], dtype=int64) ``` So, for `n`, you should call ``` arr.argsort()[:n] ```
What are the equivalents of .split() and .rstrip() for a tuple?
16,818,201
3
2013-05-29T15:35:57Z
16,818,229
8
2013-05-29T15:37:26Z
[ "python" ]
I have a tuple that looks like this: ``` ('1 2130 0 279 90 92 193 1\n', '1 186 0 299 14 36 44 1\n') ``` And i want to split it so that each column will be seperate so i can access it in an easier way. So for an example: ``` tuple[0][2] ``` would return `0` ``` tuple[1][3] ``` would return `299` The second part ...
You could use a list comprehension: ``` rows = [row.split() for row in your_tuple] ``` As for `.rstrip()`, you don't need it. `.split()` (with no argument!) takes care of that for you: ``` >>> ' a b c \t\n\n '.split() ['a', 'b', 'c'] ```
What's the purpose of the + (pos) unary operator in Python?
16,819,023
34
2013-05-29T16:14:12Z
16,819,260
20
2013-05-29T16:26:16Z
[ "python" ]
Generally speaking, what should the unary `+` do in Python? I'm asking because, so far, I have never seen a situation like this: ``` +obj != obj ``` Where `obj` is a generic object implementing `__pos__()`. So I'm wondering: why do `+` and `__pos__()` exist? Can you provide a real-world example where the expression...
I believe that Python operators where inspired by C, where the `+` operator was introduced for symmetry (and also some useful hacks, see comments). In weakly typed languages such as PHP or Javascript, + tells the runtime to coerce the value of the variable into a number. For example, in Javascript: ``` +"2" + 1 =>...
What's the purpose of the + (pos) unary operator in Python?
16,819,023
34
2013-05-29T16:14:12Z
16,819,334
23
2013-05-29T16:29:26Z
[ "python" ]
Generally speaking, what should the unary `+` do in Python? I'm asking because, so far, I have never seen a situation like this: ``` +obj != obj ``` Where `obj` is a generic object implementing `__pos__()`. So I'm wondering: why do `+` and `__pos__()` exist? Can you provide a real-world example where the expression...
Here's a "real-world" example from the `decimal` package: ``` >>> from decimal import Decimal >>> obj = Decimal('3.1415926535897932384626433832795028841971') >>> +obj != obj # The __pos__ function rounds back to normal precision True >>> obj Decimal('3.1415926535897932384626433832795028841971') >>> +obj Decimal('3.14...
Moving average of an array in Python
16,820,993
2
2013-05-29T18:09:38Z
16,821,054
7
2013-05-29T18:13:27Z
[ "python", "python-2.7", "moving-average" ]
I have an array where discreet sinewave values are recorded and stored. I want to find the max and min of the waveform. Since the sinewave data is recorded voltages using a DAQ, there will be some noise, so I want to do a weighted average. Assuming self.yArray contains my sinewave values, here is my code so far: ``` f...
`self.yArray[x+y]` is returning a single item out of the `self.yArray` list. If you are trying to get a subset of the `yArray`, you can use the slice operator instead: ``` summation = sum(self.yArray[x:y]) ``` to return an iterable that the `sum` builtin can use. A bit more information about python slices can be fou...
Moving average of an array in Python
16,820,993
2
2013-05-29T18:09:38Z
16,821,224
11
2013-05-29T18:24:01Z
[ "python", "python-2.7", "moving-average" ]
I have an array where discreet sinewave values are recorded and stored. I want to find the max and min of the waveform. Since the sinewave data is recorded voltages using a DAQ, there will be some noise, so I want to do a weighted average. Assuming self.yArray contains my sinewave values, here is my code so far: ``` f...
The other answers correctly describe your error, but this type of problem really calls out for using numpy. Numpy will [run faster, be more memory efficient, and is more expressive and convenient](http://stackoverflow.com/questions/993984/why-numpy-instead-of-python-lists) for this type of problem. Here's an example: ...
How to convert a pandas DataFrame into a TimeSeries?
16,822,996
13
2013-05-29T20:12:57Z
16,824,270
9
2013-05-29T21:35:44Z
[ "python", "pandas", "time-series" ]
I am looking for a way to convert a DataFrame to a TimeSeries without splitting the index and value columns. Any ideas? Thanks. ``` In [20]: import pandas as pd In [21]: import numpy as np In [22]: dates = pd.date_range('20130101',periods=6) In [23]: df = pd.DataFrame(np.random.randn(6,4),index=dates,columns=list('...
Here is one possibility ``` [3]: df Out[3]: A B C D 2013-01-01 -0.024362 0.712035 -0.913923 0.755276 2013-01-02 2.624298 0.285546 0.142265 -0.047871 2013-01-03 1.315157 -0.333630 0.398759 -1.034859 2013-01-04 0.713141 -0.109539 0.263706 -0.588048 2013-01-05 -1.1721...
Selenium webdriver and unicode
16,823,086
8
2013-05-29T20:19:46Z
16,823,278
14
2013-05-29T20:31:11Z
[ "python", "selenium", "unicode" ]
It's my 2nd day with Selenium 2 library and the pain with Unicode never seem to subside. I'm just doing the most basic operation, want to print the page source: ``` from selenium import webdriver driver = webdriver.Firefox() driver.get("http://google.com") print driver.page_source ``` Sure enough, I get an error:...
You have options, based on this similar [question](http://stackoverflow.com/questions/3224268/python-unicode-encode-error). You can either convert the source to all ascii losing the Unicode characters in the process. `(driver.page_source).encode('ascii', 'ignore')` Or, and I think you'll prefer this, you can encode ...
check whether a string is in a 2-GB list of strings in python
16,823,214
5
2013-05-29T20:28:34Z
16,823,273
7
2013-05-29T20:30:57Z
[ "python" ]
I have a large file (`A.txt`) of 2 GB containing a list of strings `['Question','Q1','Q2','Q3','Ans1','Format','links',...]`. Now I have another larger file(1TB) containing the above mentioned strings in 2nd position: Output: ``` a, Question, b The, quiz, is This, Q1, Answer Here, Ans1, is King1, links, King2 progra...
Don't use a list; use a set instead. Read the first file into a set: ``` with open('A.txt') as file_a: words = {line.strip() for line in file_a} ``` 0.5 GB of words isn't *that* much to store in a set. Now you can test against `words` in O(1) constant time: ``` if second_word in words: # .... ``` Open the...
Django -- Conditional Login Redirect
16,824,004
7
2013-05-29T21:19:20Z
16,824,337
11
2013-05-29T21:39:48Z
[ "python", "django", "django-admin", "django-views" ]
I am working on a Django application that will have two types of users: Admins and Users. Both are groups in my project, and depending on which group the individual logging in belongs to I'd like to redirect them to separate pages. Right now I have this in my settings.py ``` LOGIN_REDIRECT_URL = 'admin_list' ``` This...
Create a separate view that redirects user's based on whether they are in the admin group. ``` from django.shortcuts import redirect def login_success(request): """ Redirects users based on whether they are in the admins group """ if request.user.groups.filter(name="admins").exists(): # user i...
Pandas: Appending a row to a dataframe and specify its index label
16,824,607
11
2013-05-29T21:59:14Z
16,824,696
16
2013-05-29T22:05:55Z
[ "python", "pandas" ]
Is there any way to specify the index that I want for a new row, when appending the row to a dataframe? The original documentation provides [the following example](http://pandas.pydata.org/pandas-docs/stable/merging.html): ``` In [1301]: df = DataFrame(np.random.randn(8, 4), columns=['A','B','C','D']) In [1302]: df ...
The `name` of the Series becomes the `index` of the row in the DataFrame: ``` In [99]: df = pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D']) In [100]: s = df.xs(3) In [101]: s.name = 10 In [102]: df.append(s) Out[102]: A B C D 0 -2.083321 -0.153749 0.174436 1.081...
Is it possible to add a string as a legend item in matplotlib
16,826,711
13
2013-05-30T01:51:44Z
16,827,257
20
2013-05-30T03:00:24Z
[ "python", "matplotlib", "pandas", "legend", "legend-properties" ]
I am producing some plots in matplotlib and would like to add explanatory text for some of the data. I want to have a string inside my legend as a separate legend item above the '0-10' item. Does anyone know if there is a possible way to do this? ![enter image description here](http://i.stack.imgur.com/TDuGh.png) Thi...
Sure. `ax.legend()` has a two argument form that accepts a list of objects (handles) and a list of strings (labels). Use a dummy object (aka a ["proxy artist"](http://matplotlib.org/users/legend_guide.html#using-proxy-artist)) for your extra string. I picked a `matplotlib.patches.Rectangle` with no fill and 0 linewdith...
Request for example: Recurrent neural network for predicting next value in a sequence
16,830,946
25
2013-05-30T08:04:51Z
18,756,932
8
2013-09-12T06:30:27Z
[ "python", "machine-learning", "neural-network", "time-series", "pybrain" ]
Can anyone give me a practicale example of a recurrent neural network in (pybrain) python in order to predict the next value of a sequence ? (I've read the pybrain documentation and there is no clear example for it I think.) I also found this [question](http://stackoverflow.com/questions/12689293/event-sequences-recurr...
Issam Laradji's worked for me to predict sequence of sequences, except my version of pybrain required a tuple for the UnserpervisedDataSet object: ``` from pybrain.tools.shortcuts import buildNetwork from pybrain.supervised.trainers import BackpropTrainer from pybrain.datasets import SupervisedDataSet,UnsupervisedData...
How to click an element visible after hovering with selenium?
16,830,960
6
2013-05-30T08:06:08Z
16,831,448
7
2013-05-30T08:35:10Z
[ "python", "selenium", "selenium-webdriver", "hover" ]
I want to click a button which is visible after hovering. Its html is: ``` <span class="info"></span> ``` I used this code: ``` import selenium.webdriver as webdriver from selenium.webdriver.common.action_chains import ActionChains url = "http://example.com" driver = webdriver.Firefox() driver.get(url) element = d...
I bet you should wait for the element until it becomes visible. Three options: * call `time.sleep(n)` * use `WebDriverWait` like it's suggested [here](http://stackoverflow.com/a/9176713/771848), [here](http://stackoverflow.com/questions/8917785/python-webdriver-wait) and [here](http://blog.mozilla.org/webqa/2012/07/1...
TypeError: "quotechar" must be an 1-character string
16,833,209
2
2013-05-30T10:01:33Z
16,833,286
8
2013-05-30T10:05:57Z
[ "python", "csv", "python-2.7" ]
I am trying to read data from a csv file. I set quotechar to csv.QUOTE\_NONE. The four lines of Python I wrote for this purpose are just as follows - ``` import csv with open('mtz.gps.comfort_gps_logs_20110214_20110215.csv', 'rb') as csvfile: taxiDataReader = csv.reader(csvfile, delimiter = ',', quotechar = csv.QU...
`QUOTE_NONE` is meant as a value for the parameter `quoting`, not for `quotechar`. The correct way would be to use ``` taxiDataReader = csv.reader(csvfile, delimiter=',', quoting=csv.QUOTE_NONE) ``` [The docs state](http://docs.python.org/2/library/csv.html#dialects-and-formatting-parameters) that `quotechar` must a...
Assign new values to slice from MultiIndex DataFrame
16,833,842
10
2013-05-30T10:32:20Z
16,834,949
8
2013-05-30T11:27:18Z
[ "python", "pandas", "multi-index", "dataframe" ]
I would like to modify some values from a column in my DataFrame. At the moment I have a *view* from select via the multi index of my original `df` (and modifying does change `df`). Here's an example: ``` In [1]: arrays = [np.array(['bar', 'bar', 'baz', 'qux', 'qux', 'bar']), np.array(['one', 'two',...
Sort the frame, then select/set using a tuple for the multi-index ``` In [12]: df = pd.DataFrame(randn(6, 3), index=arrays, columns=['A', 'B', 'C']) In [13]: df Out[13]: A B C bar one 0 -0.694240 0.725163 0.131891 two 1 -0.729186 0.244860 0.530870 baz one 2 0.757816 1.1299...
Create own colormap using matplotlib and plot color scale
16,834,861
16
2013-05-30T11:22:38Z
16,836,182
37
2013-05-30T12:27:49Z
[ "python", "matplotlib", "plot" ]
I have the following problem, I want to create my own colormap (red-mix-violet-mix-blue) that maps to values between -2 and +2 and want to use it to color points in my plot. The plot should then have the colorscale to the right. That is how I create the map so far. But I am not really sure if it mixes the colors. ...
There is an illustrative example of [how to create custom colormaps here](http://matplotlib.org/examples/pylab_examples/custom_cmap.html). The docstring is essential for understanding the meaning of `cdict`. Once you get that under your belt, you might use a `cdict` like this: ``` cdict = {'red': ((0.0, 1.0, 1.0), ...
Python BeautifulSoup extract text between element
16,835,449
15
2013-05-30T11:54:36Z
16,835,522
7
2013-05-30T11:59:13Z
[ "python", "beautifulsoup" ]
I try to extract "THIS IS MY TEXT" from the following HTML: ``` <html> <body> <table> <td class="MYCLASS"> <!-- a comment --> <a hef="xy">Text</a> <p>something</p> THIS IS MY TEXT <p>something else</p> </br> </td> </table> </body> </html> ``` I tried it this way: ``` soup = ...
Use [`.children`](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#contents-and-children) instead: ``` from bs4 import NavigableString, Comment print ''.join(unicode(child) for child in hit.children if isinstance(child, NavigableString) and not isinstance(child, Comment)) ``` Yes, this is a bit of a dance. ...
Python BeautifulSoup extract text between element
16,835,449
15
2013-05-30T11:54:36Z
16,836,186
8
2013-05-30T12:27:58Z
[ "python", "beautifulsoup" ]
I try to extract "THIS IS MY TEXT" from the following HTML: ``` <html> <body> <table> <td class="MYCLASS"> <!-- a comment --> <a hef="xy">Text</a> <p>something</p> THIS IS MY TEXT <p>something else</p> </br> </td> </table> </body> </html> ``` I tried it this way: ``` soup = ...
You can use [`.contents`](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#contents-and-children): ``` >>> for hit in soup.findAll(attrs={'class' : 'MYCLASS'}): ... print hit.contents[6].strip() ... THIS IS MY TEXT ```
Python BeautifulSoup extract text between element
16,835,449
15
2013-05-30T11:54:36Z
16,836,626
16
2013-05-30T12:46:44Z
[ "python", "beautifulsoup" ]
I try to extract "THIS IS MY TEXT" from the following HTML: ``` <html> <body> <table> <td class="MYCLASS"> <!-- a comment --> <a hef="xy">Text</a> <p>something</p> THIS IS MY TEXT <p>something else</p> </br> </td> </table> </body> </html> ``` I tried it this way: ``` soup = ...
Learn more about how to navigate [through the parse tree in `BeautifulSoup`](http://www.crummy.com/software/BeautifulSoup/bs3/documentation.html#contents). Parse tree has got `tags` and `NavigableStrings` (as THIS IS A TEXT). An example ``` from BeautifulSoup import BeautifulSoup doc = ['<html><head><title>Page title...
TypeError for __init__()
16,835,651
2
2013-05-30T12:05:11Z
16,835,734
7
2013-05-30T12:09:04Z
[ "python", "python-2.7" ]
I'm trying to create a nutrition calculator and I'm having a bit of issues regarding **init**(). ``` def main(): print "Welcome to the MACRONUTRIENT CALCULATOR" User_nutrition = get_data() User_nutrition.calorie_budget() class get_data(object): def __init__(self, calorie_...
The problem is with: ``` User_nutrition = get_data() # one argument self # and def __init__(self, calorie_deficit): # two arguments ``` You should do ``` User_nutrition = get_data(5) # add one argument # or def __init__(self, calorie_deficit = 0): # make one argument default ```
Why is my Python instance being shared?
16,836,347
2
2013-05-30T12:35:04Z
16,836,387
8
2013-05-30T12:36:30Z
[ "python" ]
My code: ``` class Num: nums = [] def add(self, num): self.nums.append(num) def __str__(self): return str(self.nums) a = Num() b = Num() a.add(5) print str(a) print str(b) ``` produces ``` [5] [5] ``` even though nothing has been added to b
Because nums is a class attribute and not an instance attribute. ``` class Num: def __init__(self): self.nums = [] def add(self, num): self.nums.append(num) def __str__(self): return str(self.nums) ``` Implementing it like this will show the behavior you expect.
Why is Python 2.7 installed at root, unlike most programs today?
16,838,499
9
2013-05-30T14:11:00Z
16,838,597
10
2013-05-30T14:16:20Z
[ "python", "windows-7" ]
Apologies for a likely stupid question, but no amount of Googling or searching here for my query could get me anywhere. Just having issues with root installations lead me to wonder WHY Python 2.7 is naturally set up in the root directory of Windows, when everything else is in ProgramFiles? Is there a simple answer fo...
Comments in [this bug](http://bugs.python.org/issue1284316) explain that the main problem is the space in “Program Files”. > A long time ago, Python did install (by default) under "Program > Files". I changed that, because of the endless problems created by > the frickin' embedded space, and rarer but subtler prob...
Reading a Line From File Without Advancing [Pythonic Approach]
16,840,554
10
2013-05-30T15:48:18Z
16,840,747
16
2013-05-30T15:56:29Z
[ "python" ]
What's a pythonic approach for reading a line from a file but not advancing where you are in the file? For example, if you have a file of ``` cat1 cat2 cat3 ``` and you do `file.readline()` you will get `cat1\n` . The next `file.readline()` will return `cat2\n` . Is there some functionality like `file.some_function...
As far as I know, there's no builtin functionality for this, but such a function is easy to write, since most Python `file` objects support `seek` and `tell` methods for jumping around within a file. So, the process is very simple: * Find the current position within the file using `tell`. * Perform a `read` (or `write...
Python regex split without empty string
16,840,851
12
2013-05-30T16:01:58Z
16,840,963
9
2013-05-30T16:06:37Z
[ "python", "regex" ]
I have the following file names that exhibit this pattern: ``` 000014_L_20111007T084734-20111008T023142.txt 000014_U_20111007T084734-20111008T023142.txt ... ``` I want to extract the middle two time stamp parts after the second underscore `'_'` and before `'.txt'`. So I used the following Python regex string split: ...
I'm no Python expert but maybe you could just remove the empty strings from your list? ``` time_info = re.split('^[0-9]+_[LU]_|-|\.txt$', f) time_info = filter(None, str_list) ```
Python regex split without empty string
16,840,851
12
2013-05-30T16:01:58Z
16,841,075
10
2013-05-30T16:12:24Z
[ "python", "regex" ]
I have the following file names that exhibit this pattern: ``` 000014_L_20111007T084734-20111008T023142.txt 000014_U_20111007T084734-20111008T023142.txt ... ``` I want to extract the middle two time stamp parts after the second underscore `'_'` and before `'.txt'`. So I used the following Python regex string split: ...
Don't use `re.split()`, use the `groups()` method of regex `Match`/`SRE_Match` objects. ``` >>> f = '000014_L_20111007T084734-20111008T023142.txt' >>> time_info = re.search(r'[LU]_(\w+)-(\w+)\.', f).groups() >>> time_info ('20111007T084734', '20111008T023142') ``` You can even name the capturing groups and retrieve t...
how to get the original start_url in scrapy (before redirect)
16,843,088
6
2013-05-30T18:07:21Z
16,846,466
12
2013-05-30T21:51:39Z
[ "python", "redirect", "web-scraping", "scrapy" ]
I'm using Scrapy to crawl some pages. I fetch the start\_urls from an excel sheet and I need to save the url in the item. ``` class abc_Spider(BaseSpider): name = 'abc' allowed_domains = ['abc.com'] wb = xlrd.open_workbook(path + '/somefile.xlsx') wb.sheet_names() sh = wb.sheet_by_name(u'Sheet1...
You can find what you need in `response.request.meta['redirect_urls']`. Quote from [docs](http://doc.scrapy.org/en/latest/topics/downloader-middleware.html#std%3areqmeta-redirect_urls): > The urls which the request goes through (while being redirected) can > be found in the redirect\_urls Request.meta key. Hope that...
Quick way to reject a list in Python
16,843,775
5
2013-05-30T18:50:52Z
16,843,793
14
2013-05-30T18:52:01Z
[ "python", "list", "validation", "iterable" ]
I have a list of items in python, and a way to check if the item is valid or not. I need to reject the entire list if any one of items there is invalid. I could do this: ``` def valid(myList): for x in myList: if isInvalid(x): return False return True ``` Is there a more Pythonic way for do...
The typical way to do this is to use the builtin [`any`](http://docs.python.org/2/library/functions.html#any) function with a generator expression ``` if any(isInvalid(x) for x in myList): #reject ``` The syntax is clean and elegant and you get the same short-circuiting behavior that you had on your original funct...
Error code 2755 when attempting to install Python 2.7.5 or 3.3.2
16,846,336
2
2013-05-30T21:41:36Z
24,117,436
20
2014-06-09T09:36:07Z
[ "python", "failed-installation" ]
I am trying to install Python on my Windows 7 Ultimate 32bit machine, but after going through all of the installation settings 'n' stuff it shows this for a while: ![Installing..?](http://i.stack.imgur.com/HZXeW.png) before showing this, then the 'Installer quit prematurely' message and exiting: ![Oh dear...](http:/...
Make sure C:\Windows\Installer exists (if windows is installed in C:). If it doesn't, just create it and run the installer again.
Skip the last row of CSV file when iterating in Python
16,846,460
4
2013-05-30T21:51:16Z
16,846,511
14
2013-05-30T21:56:59Z
[ "python", "csv" ]
I am working on a data analysis using a CSV file that I got from a datawarehouse(Cognos). The CSV file has the last row that sums up all the rows above, but I do not need this line for my analysis, so I would like to skip the last row. I was thinking about adding "if" statement that checks a column name within my "for...
You can write a generator that'll return everything but the last entry in an input iterator: ``` def skip_last(iterator): prev = next(iterator) for item in iterator: yield prev prev = item ``` then wrap your `CSV_raw` reader object in that: ``` for row in skip_last(CSV_raw): ``` The generato...
Django aggregate count of records per day
16,847,601
4
2013-05-30T23:40:12Z
16,849,913
8
2013-05-31T04:46:39Z
[ "python", "django", "orm" ]
I've got a django app that is doing some logging. My model looks like this: ``` class MessageLog(models.Model): logtime = models.DateTimeField(auto_now_add=True) user = models.CharField(max_length=50) message = models.CharField(max_length=512) ``` What a want to do is get the average number of messages lo...
The reason your listed query always gives 1 is because you're not grouping by date. Basically, you've asked the database to take the `MessageLog` rows that fall on a given day of the week. For each such row, count how many ids it has (always 1). Then take the average of all those counts, which is of course also 1. Nor...
Python in Enthought Canopy: IOError No such file or directory
16,848,231
5
2013-05-31T00:57:37Z
16,848,410
17
2013-05-31T01:22:30Z
[ "python", "enthought" ]
Does anyone use Enthought Canopy? It keeps telling me IOError. But I am pretty sure the text file name is right and it is in the same directory with the python file, and the code works well in other python IDLE. Don't know where is wrong. Any suggestions? Thank you!! ``` ---> 21 inFile = open('words.txt', 'r') ...
UPDATE: The following hack is not required in Canopy versions 1.0.3 and greater. Right click inside the Python pane, and select `Keep Directory Synced to Editor`. The working directory of the python shell, isn't synchronized with the editor open. So, your python shell's working directory is probably not the same as yo...
Theano: Why does indexing fail in this case?
16,848,650
5
2013-05-31T01:54:35Z
16,860,115
8
2013-05-31T14:51:21Z
[ "python", "numpy", "theano" ]
I'm trying to get the max of a vector given a boolean value. With Numpy: ``` >>> this = np.arange(10) >>> this[~(this>=5)].max() 4 ``` But with Theano: ``` >>> that = T.arange(10, dtype='int32') >>> that[~(that>=5)].max().eval() 9 >>> that[~(that>=5).nonzero()].max().eval() Traceback (most recent call last): File...
You are using a version of Theano that is too old. In fact, tensor\_var.nonzero() isn't in any released version. You need to update to the development version. With the development version I have this: ``` >>> that[~(that>=5).nonzero()].max().eval() Traceback (most recent call last): File "<stdin>", line 1, in <mod...
Which is the recommended way to plot: matplotlib or pylab?
16,849,483
36
2013-05-31T03:52:05Z
16,849,816
54
2013-05-31T04:33:12Z
[ "python", "matplotlib" ]
I see that I can **plot** in **Python** using either: ``` import matplotlib matplotlib.pyplot.plot(...) ``` Or: ``` import pylab pylab.plot(...) ``` Both of these use the same **matplotlib** plotting code. So, which of these does the Python community recommend as the better method to plot? Why?
Official docs: <http://matplotlib.org/faq/usage_faq.html#matplotlib-pylab-and-pyplot-how-are-they-related> Both of those imports boil down do doing exactly the same thing and will run the exact same code, it is just different ways of importing the modules. Also note that `matplotlib` has two interface layers, a state...
ndb to_dict method does not include object's key
16,850,136
11
2013-05-31T05:09:01Z
16,850,717
22
2013-05-31T06:05:13Z
[ "python", "google-app-engine", "app-engine-ndb" ]
I am leveraging ndb's to\_dict method to convert an object's properties into a python dict. From everything I can tell, this method does not include the object's key or parent within the dict as per the documentation: <https://developers.google.com/appengine/docs/python/ndb/modelclass#Model_to_dict> However for my si...
You're not missing anything ;-) Just add the key to the dictionary after you call to\_dict, and yes override the method. If you have multiple models that don't share the same base class with your custom to\_dict, I would implement it as a mixin. to define to\_dict as a method of a Mixin class. you would ``` class M...
How to use a script to query android sqlite database
16,851,774
5
2013-05-31T07:16:22Z
16,851,992
11
2013-05-31T07:27:39Z
[ "android", "python", "perl", "sqlite3", "adb" ]
`Android` saved settings in a database file which is `/data/data/com.android.providers.settings/databases/settings.db`. Android use `sqlite3` as the database. We can use `adb` to manage the database file. I want to know if there is a way to run all these commands in a `perl/python` script to automate the whole query p...
To query a specific value: ``` adb shell sqlite3 /data/data/com.android.providers.settings/databases/settings.db "select value from 'system' where name = 'volume_alarm';" ``` Or to pull all records from a table: ``` adb shell sqlite3 /data/data/com.android.providers.settings/databases/settings.db "select name, value...
Python: how to import from all modules in dir?
16,852,811
9
2013-05-31T08:16:18Z
16,853,487
16
2013-05-31T08:56:06Z
[ "python", "import", "module" ]
Dir structure: ``` main.py my_modules/ module1.py module2.py ``` module1.py: ``` class fooBar(): .... class pew_pew_FooBarr() .... ... ``` How can I add all classes from module\* to main without prefixes (i.e. to use them like foo = fooBar(), not foo = my\_modules.module1.fooBar()). An obvious decisi...
In the `my_modules` folder, add a `__init__.py` file to make it a proper package. In that file, you can inject the globals of each of those modules in the global scope of the `__init__.py` file, which makes them available as your module is imported (after you've also added the name of the global to the `__all__` variab...
How do I convert dates in a Pandas data frame to a 'date' data type?
16,852,911
28
2013-05-31T08:23:02Z
16,853,161
29
2013-05-31T08:36:33Z
[ "python", "date", "pandas" ]
I have a Pandas data frame, one of the columns of which contains date strings in the format 'YYYY-MM-DD' e.g. '2013-10-28'. At the moment the dtype of the column is 'object'. How do I convert the column values to Pandas date format?
Use [astype](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html) ``` In [31]: df Out[31]: a time 0 1 2013-01-01 1 2 2013-01-02 2 3 2013-01-03 In [32]: df['time'] = df['time'].astype('datetime64[ns]') In [33]: df Out[33]: a time 0 1 2013-01-01 00:00:00...
How do I convert dates in a Pandas data frame to a 'date' data type?
16,852,911
28
2013-05-31T08:23:02Z
16,854,430
43
2013-05-31T09:46:26Z
[ "python", "date", "pandas" ]
I have a Pandas data frame, one of the columns of which contains date strings in the format 'YYYY-MM-DD' e.g. '2013-10-28'. At the moment the dtype of the column is 'object'. How do I convert the column values to Pandas date format?
Essentially equivalent to @waitingkuo, but I would use `to_datetime` here (it seems a little cleaner, and offers some additional functionality e.g. `dayfirst`): ``` In [11]: df Out[11]: a time 0 1 2013-01-01 1 2 2013-01-02 2 3 2013-01-03 In [12]: pd.to_datetime(df['time']) Out[12]: 0 2013-01-01 00:0...
How do I convert dates in a Pandas data frame to a 'date' data type?
16,852,911
28
2013-05-31T08:23:02Z
22,496,075
11
2014-03-19T04:15:07Z
[ "python", "date", "pandas" ]
I have a Pandas data frame, one of the columns of which contains date strings in the format 'YYYY-MM-DD' e.g. '2013-10-28'. At the moment the dtype of the column is 'object'. How do I convert the column values to Pandas date format?
I imagine a lot of data comes into Pandas from CSV files, in which case you can simply convert the date during the initial CSV read: `dfcsv = pd.read_csv('xyz.csv', parse_dates=[0])` where the 0 refers to the column the date is in. You could also add `, index_col=0` in there if you want the date to be your index. S...
How do I convert dates in a Pandas data frame to a 'date' data type?
16,852,911
28
2013-05-31T08:23:02Z
33,577,649
7
2015-11-07T00:22:59Z
[ "python", "date", "pandas" ]
I have a Pandas data frame, one of the columns of which contains date strings in the format 'YYYY-MM-DD' e.g. '2013-10-28'. At the moment the dtype of the column is 'object'. How do I convert the column values to Pandas date format?
Now you can do `df['column'].dt.date` Note that for datetime objects, if you don't see the hour when they're all 00:00:00, that's not pandas. That's iPython notebook trying to make things look pretty.
Executing Python script from Django shell
16,853,649
111
2013-05-31T09:05:36Z
16,853,755
76
2013-05-31T09:10:48Z
[ "python", "django", "django-shell" ]
I need to execute a Python script from the Django shell. I tried ``` ./manage.py shell << my_script.py ``` But it didn't work. It was just kinda waiting for me to write something.
You're not recommended to do that from the `shell` - and this is intended as you shouldn't really be executing random scripts from the django environment (but there *are* ways around this, see the other answers). If this is a script that you will be running multiple times, it's a good idea to set it up as a [custom co...
Executing Python script from Django shell
16,853,649
111
2013-05-31T09:05:36Z
16,853,799
191
2013-05-31T09:13:21Z
[ "python", "django", "django-shell" ]
I need to execute a Python script from the Django shell. I tried ``` ./manage.py shell << my_script.py ``` But it didn't work. It was just kinda waiting for me to write something.
The `<<` part is wrong, use `<` instead: ``` $ ./manage.py shell < myscript.py ``` You could also do: ``` $ ./manage.py shell ... >>> execfile('myscript.py') ```
Executing Python script from Django shell
16,853,649
111
2013-05-31T09:05:36Z
19,426,755
55
2013-10-17T12:27:33Z
[ "python", "django", "django-shell" ]
I need to execute a Python script from the Django shell. I tried ``` ./manage.py shell << my_script.py ``` But it didn't work. It was just kinda waiting for me to write something.
Late for the party :D but i hope that my response will help someone: You can do this in your python script: ``` import sys, os sys.path.append('/path/to/your/django/app') os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' from django.conf import settings ``` the rest of your stuff goes here ...
Executing Python script from Django shell
16,853,649
111
2013-05-31T09:05:36Z
24,456,404
51
2014-06-27T16:14:14Z
[ "python", "django", "django-shell" ]
I need to execute a Python script from the Django shell. I tried ``` ./manage.py shell << my_script.py ``` But it didn't work. It was just kinda waiting for me to write something.
For anyone using Django 1.7+, it seems that simply import the settings module is not enough. After some digging, I found this Stack Overflow answer: <http://stackoverflow.com/a/23241093> You now need to: ``` import os, django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings") django.setup() # now your...
Using distutils and build_clib to build C library
16,854,066
6
2013-05-31T09:27:28Z
16,871,085
7
2013-06-01T09:11:59Z
[ "python", "cython" ]
Does anyone have a good example of using the `build_clib` command in distutils to build an external (non-python) C library from setup.py? The documentation on the subject seems to be sparse or non-existent. My aim is to build a very simple external library, then build a cython wrapper which links to it. The simplest e...
Instead of passing a library name as a string, pass a tuple with the sources to compile: **setup.py** ``` import sys from distutils.core import setup from distutils.command.build_clib import build_clib from distutils.extension import Extension from Cython.Distutils import build_ext libhello = ('hello', {'sources': [...
How does multiple inheritance work with the super() and different __init__() arguments?
16,855,087
18
2013-05-31T10:23:56Z
16,855,581
9
2013-05-31T10:51:22Z
[ "python", "class", "constructor", "multiple-inheritance", "super" ]
I'm just diving into some more advanced python subjects (well, advanced to me at least). I am now reading about multiple inheritance and how you can use super(). I more or less understand the way the super function is used, but **(1) What's wrong with just doing it like this**?: ``` class First(object): def __init...
For question 2, you need to call super in each class: ``` class First(object): def __init__(self): super(First, self).__init__() print "first" class Second(object): def __init__(self): super(Second, self).__init__() print "second" class Third(First, Second): def __init__(s...
Yield multiple values
16,856,251
10
2013-05-31T11:28:50Z
16,856,289
14
2013-05-31T11:30:42Z
[ "python" ]
Can't we yield more than one value in the python generator functions? Example, ``` In [677]: def gen(): .....: for i in range(5): .....: yield i, i+1 .....: In [680]: k1, k2 = gen() --------------------------------------------------------------------------- ValueError ...
Because `gen()` returns a generator (a single item - so it can't be unpacked as two), it needs to be advanced *first* to get the values... ``` g = gen() a, b = next(g) ``` It works with `list` because that implicitly consumes the generator. Can we further make this a generator? Something like this: ``` g = gen(); d...
Yield multiple values
16,856,251
10
2013-05-31T11:28:50Z
16,856,294
8
2013-05-31T11:31:00Z
[ "python" ]
Can't we yield more than one value in the python generator functions? Example, ``` In [677]: def gen(): .....: for i in range(5): .....: yield i, i+1 .....: In [680]: k1, k2 = gen() --------------------------------------------------------------------------- ValueError ...
Your function `gen` returns a generator and not values as you might expect judging from the example you gave. If you iterate over the generator the pairs of values will be yielded: ``` In [2]: def gen(): ...: for i in range(5): ...: yield i, i+1 ...: In [3]: for k1, k2 in gen(): ...: ...
Is there a MATLAB accumarray equivalent in numpy?
16,856,470
13
2013-05-31T11:41:14Z
16,857,755
15
2013-05-31T12:53:54Z
[ "python", "numpy", "accumulator" ]
I'm looking for a fast solution to MATLAB's [`accumarray`](http://www.mathworks.com/help/matlab/ref/accumarray.html) in numpy. The `accumarray` accumulates the elements of an array which belong to the same index. An example: ``` a = np.arange(1,11) # array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) accmap = np.array([0...
Use [`np.bincount`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html) with the `weights` optional argument. In your example you would do: ``` np.bincount(accmap, weights=a) ```
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 74 supplied
16,856,647
59
2013-05-31T11:51:17Z
16,856,730
122
2013-05-31T11:56:33Z
[ "python", "sqlite", "sqlite3" ]
``` def insert(array): connection=sqlite3.connect('images.db') cursor=connection.cursor() cnt=0 while cnt != len(array): img = array[cnt] print(array[cnt]) cursor.execute('INSERT INTO images VALUES(?)', (img)) cnt+= 1 connection.commit() connection...
You need to pass in a sequence, but you forgot the comma to make your parameters a tuple: ``` cursor.execute('INSERT INTO images VALUES(?)', (img,)) ``` Without the comma, `(img)` is just a grouped expression, not a tuple, and thus the `img` string is treated as the input sequence. If that string is 74 characters lon...
Slice 2d array into smaller 2d arrays
16,856,788
14
2013-05-31T12:00:20Z
16,858,283
21
2013-05-31T13:19:32Z
[ "python", "numpy" ]
Is there a way to slice a 2d array in numpy into smaller 2d arrays? **Example** ``` [[1,2,3,4], -> [[1,2] [3,4] [5,6,7,8]] [5,6] [7,8]] ``` So I basically want to cut down a 2x4 array into 2 2x2 arrays. Looking for a generic solution to be used on images.
You should be able to break your array into "blocks" using some combination of `reshape` and `swapaxes`: ``` import numpy as np def blockshaped(arr, nrows, ncols): """ Return an array of shape (n, nrows, ncols) where n * nrows * ncols = arr.size If arr is a 2D array, the returned array should look lik...
Pandas: run length of NaN holes
16,857,407
7
2013-05-31T12:34:12Z
16,857,854
8
2013-05-31T12:58:38Z
[ "python", "pandas" ]
I have hundreds of timeseries objects with 100000's of entries in each. Some percentage of the data entries are missing (NaN). It is important to my application whether those are single, scattered NaNs or long sequences of NaNs. Therefore I would like a function for giving me the runlength of each contiguous sequence ...
``` import pandas as pd import numpy as np import itertools a = pd.Series([1, 2, 3, np.nan, 4, np.nan, np.nan, np.nan, 5, np.nan, np.nan]) len_holes = [len(list(g)) for k, g in itertools.groupby(a, lambda x: np.isnan(x)) if k] print len_holes ``` results in ``` [1, 3, 2] ```
Is any magic method called on an object in a list during join()?
16,858,598
10
2013-05-31T13:36:09Z
16,858,628
12
2013-05-31T13:37:06Z
[ "python", "join", "magic-methods" ]
Joining a list containing an object - is there any magic method I could set to convert the object to a string before join fails? ``` ', '.join([…, Obj, …]) ``` I tried `__str__` and `__repr__` but neither did work
Nope, there's no `join` hook (although I've wanted this feature as well). Commonly you'll see: ``` ', '.join(str(x) for x in iterable) ``` or (almost) equivalently: ``` ', '.join(map(str,iterable)) ', '.join([str(x) for x in iterable]) ``` --- (Note that all of the above are equivalent in terms of memory usage whe...
How to find the corresponding class in clf.predict_proba()
16,858,652
14
2013-05-31T13:38:38Z
16,859,091
22
2013-05-31T13:59:26Z
[ "python", "machine-learning", "scikit-learn" ]
I have a number of classes and corresponding feature vectors, and when I run predict\_proba() I will get this: ``` classes = ['one','two','three','one','three'] feature = [[0,1,1,0],[0,1,0,1],[1,1,0,0],[0,0,0,0],[0,1,1,1]] from sklearn.naive_bayes import BernoulliNB clf = BernoulliNB() clf.fit(feature,classes) clf....
Just use the `.classes_` attribute of the classifier to recover the mapping. In your example that gives: ``` >>> clf.classes_ array(['one', 'three', 'two'], dtype='|S5') ``` And thanks for putting a minimalistic reproduction script in your question, it makes answering really easy by just copy and pasting in a ...
Cannot find python xlrd version
16,859,904
4
2013-05-31T14:40:40Z
16,877,902
10
2013-06-01T22:28:50Z
[ "python", "excel", "version", "packages", "xlrd" ]
I have been using `xlrd` within python. However, `xlrd`does not seem to provide a standard way to find its version number! I have tried: * `xlrd.version()` * `xlrd.__version__` * `xlrd.version` * `xlrd.VERSION` * `xlrd.VERSION()`
You've almost got it: `xlrd.__VERSION__`. Usually it's useful to see available attributes and methods by calling [dir](http://docs.python.org/2/library/functions.html#dir): `dir(xlrd)`. --- You can even iterate through the results of `dir()` see if `version` is inside: ``` >>> import xlrd >>> getattr(xlrd, next(ite...
Can't pip install virtualenv in OS X 10.8 with brewed python 2.7
16,860,971
9
2013-05-31T15:36:02Z
19,755,902
19
2013-11-03T17:42:31Z
[ "python", "osx", "virtualenv", "homebrew" ]
When trying to install virtualenv using a brewed python, I get the following error: ``` $ pip install virtualenv Requirement already satisfied (use --upgrade to upgrade): \ virtualenv in /Library/Python/2.7/site-packages/virtualenv-1.9.1-py2.7.egg Cleaning up... ``` So clearly pip is somehow looking into the system...
I had the same problem and I managed to solve it by uninstalling any brew versions of Python and virtualenv ``` brew uninstall python brew uninstall pyenv-virtualenv ``` Manually moving all the virtualenv\* files I found under `/usr/local/bin` to another folder ``` sudo mkdir /usr/local/bin/venv-old sudo mv /usr/loc...
Down arrow symbol in matplotlib
16,861,339
3
2013-05-31T15:56:11Z
16,861,488
8
2013-05-31T16:04:22Z
[ "python", "matplotlib", "plot", "symbols", "arrow" ]
I would like to create a plot where some of the points have a downward pointing arrow (see image below). In Astronomy this illustrates that the true value is actually lower than what's measured.Note that only some of the points have this symbol. I would like to know how I can create such symbols in matplotlib. Are the...
Sure. When calling matplotlibs plot function, set a [`marker`](http://matplotlib.org/api/artist_api.html#matplotlib.lines.Line2D.set_marker) * If stuff like `caretdown` doesn't work for you, you can create your own marker by passing a list of (x,y) pairs, which are passed to a Path artist. x/y are 0…1 normalized co...
Python regex search for string at beginning of line in file
16,862,174
9
2013-05-31T16:49:38Z
16,862,342
14
2013-05-31T17:01:50Z
[ "python", "regex", "file-io" ]
Here's my code: ``` #!/usr/bin/python import io import re f = open('/etc/ssh/sshd_config','r') strings = re.search(r'.*IgnoreR.*', f.read()) print(strings) ``` That returns data, but I need specific regex matching: e.g.: ``` ^\s*[^#]*IgnoreRhosts\s+yes ``` If I change my code to simply: ``` strings = re.search(r'^...
You can use the multiline mode then ^ match the beginning of a line: ``` #!/usr/bin/python import io import re f = open('/etc/ssh/sshd_config','r') strings = re.search(r"^\s*[^#]*IgnoreRhosts\s+yes", f.read(), flags=re.MULTILINE) print(strings.group(0)) ``` Note that without this mode you can always replace `^` by `...
Why doesn't my docopt option have its default value?
16,863,371
16
2013-05-31T18:12:38Z
16,863,372
21
2013-05-31T18:12:38Z
[ "python", "docopt" ]
I'm using `docopt` in an example for a module I'm working on, and all the option default values are working except one. I've modified all the code containing and surrounding the option trying to identify the problem, but it won't take a default value! My options block looks like this: ``` Options: --help ...
So per the suggestion in the other question I cloned the docopt repo and installed the current tip with zero effect. Now that I had the source code though I decided to do some debugging and see if I could find the problem. On line 200 in the parse method on the Option class is the regex used to grab default values: `...
Python isnumeric function works only on unicode
16,863,696
7
2013-05-31T18:36:30Z
16,863,727
9
2013-05-31T18:38:13Z
[ "python" ]
Im trying to check if a string is numeric or not using the isnumeric function but the results are not as expected.The function works only if its a unicode string. ``` >>> a=u'1' >>> a.isnumeric() True >>> a='1' >>> a.isnumeric() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: '...
Just different name. '1'.isdigit() True
Run unittest from Python program via command line option
16,863,742
6
2013-05-31T18:39:37Z
16,866,179
19
2013-05-31T21:21:05Z
[ "python", "unit-testing", "python-2.7", "software-packaging" ]
Here is my set up - ``` project/ __init__.py prog.py test/ __init__.py test_prog.py ``` I would like to be able to run my unit tests by calling a command line option in prog.py, this way when I deploy my project I can deploy the ability to run the unit tests at any time. ``` python prog.p...
The Python `unittest` module contains its own test discovery function, which you can run from the command line: ``` $ python -m unittest discover ``` To run this command from within your module, you can use the `subprocess` module: ``` #!/usr/bin/env python import sys import subprocess # ... # the rest of your mod...
heatmap in matplotlib with vector format
16,864,401
6
2013-05-31T19:21:05Z
16,866,115
8
2013-05-31T21:15:23Z
[ "python", "svg", "matplotlib", "eps" ]
I'm trying to use matplotlib to plot 3D heatmap with results of my simulations. I've read [this topic](http://stackoverflow.com/questions/2369492/generate-a-heatmap-in-matplotlib-using-a-scatter-data-set?answertab=active#tab-top) and tried to use imshow. Unfortunately, when I save the figure in SVG or EPS formats, it c...
Use `pcolormesh` where you're using `imshow` if you want vector output. When using `pcolor` or `pcolormesh` you can't interpolate the image, however. On the other hand, you probably don't want interpolation if you're wanting vector output. That's basically the reason for the difference between `imshow` and `pcolor`/`...
Python count items in dict value that is a list
16,864,941
4
2013-05-31T19:56:39Z
16,864,953
24
2013-05-31T19:57:30Z
[ "python", "list", "dictionary", "count", "python-3.3" ]
Python 3.3, a dictionary with key-value pairs in this form. ``` d = {'T1': ['eggs', 'bacon', 'sausage']} ``` The values are lists of variable length, and I need to iterate over the list items. This works: ``` count = 0 for l in d.values(): for i in l: count += 1 ``` But it's ugly. There must be a more Pythonic w...
Use `sum()` and the lengths of each of the dictionary values: ``` count = sum(len(v) for v in d.itervalues()) ``` If you are using Python 3, then just use `d.values()`. Quick demo with your input sample and one of mine: ``` >>> d = {'T1': ['eggs', 'bacon', 'sausage']} >>> sum(len(v) for v in d.itervalues()) 3 >>> d...
Python count items in dict value that is a list
16,864,941
4
2013-05-31T19:56:39Z
16,865,016
7
2013-05-31T20:01:18Z
[ "python", "list", "dictionary", "count", "python-3.3" ]
Python 3.3, a dictionary with key-value pairs in this form. ``` d = {'T1': ['eggs', 'bacon', 'sausage']} ``` The values are lists of variable length, and I need to iterate over the list items. This works: ``` count = 0 for l in d.values(): for i in l: count += 1 ``` But it's ugly. There must be a more Pythonic w...
``` >>> d = {'T1': ['eggs', 'bacon', 'sausage'], 'T2': ['spam', 'ham', 'monty', 'python']} >>> sum(map(len, d.values())) 7 ```
Local and global variables in python functions
16,865,213
7
2013-05-31T20:12:58Z
16,865,251
11
2013-05-31T20:15:07Z
[ "python", "function", "variables", "global" ]
I started learning python few weeks ago (with no prior knowledge of programming). I know I am a bit tiresome with repeating the upper sentence over and over, but that' just to tell you that I might not understand some advanced concept which could be mentioned in possible replies. Anyhow, here is my problem: I do not u...
To use `global` variables inside a function, you need to do `global <varName>` inside the function, like so. ``` testVar = 0 def testFunc(): global testVar testVar += 1 print testVar testFunc() print testVar ``` gives the output ``` >>> 0 1 ``` Keep in mind, that you only need to declare them `global` in...
Why no len(file) in Python?
16,865,390
4
2013-05-31T20:23:37Z
16,865,516
12
2013-05-31T20:30:57Z
[ "python" ]
I'm not exactly new to Python, but I do still have trouble understanding what makes something "Pythonic" (and the converse). So forgive me if this is a stupid question, but why can't I get the size of a file by doing a len(file)? file.`__len__` is not even implemented, so it's not like it's needed for something else?...
Files have a broader definition, especially in Unix, than you may be thinking. What is the length of a printer, for example? Or a CDROM drive? Both are files in /dev, and sort of in Windows. For what we normally think of as a file, what would its length be? The size of the variable? The size of the file in bytes? The ...
Python bottle module causes "Error: 413 Request Entity Too Large"
16,865,997
10
2013-05-31T21:07:04Z
16,866,126
25
2013-05-31T21:16:01Z
[ "python", "http", "runtime-error", "bottle" ]
Using Python's module `bottle`, I'm getting HTTP 413 error when posting requests of body size > `bottle`'s internal `MEMFILE_MAX` constant. Minimal working example is shown below. Server part (`server.py`): ``` from bottle import * @post('/test') def test(): return str(len(request.forms['foo'])); def main(): ...
You should be able to just ``` import bottle bottle.BaseRequest.MEMFILE_MAX = 1024 * 1024 # (or whatever you want) ``` This appears to be the only way based on the [source](https://github.com/defnull/bottle/blob/master/bottle.py)
Kill a running subprocess call
16,866,602
7
2013-05-31T21:54:40Z
16,866,661
10
2013-05-31T21:59:50Z
[ "python", "multithreading", "subprocess" ]
I'm launching a program with `subprocess` on Python. In some cases the program may freeze. This is out of my control. The only thing I can do from the command line it is launched from is Ctrl-Esc which kills the program quickly. Is there any way to emulate this with `subprocess`? I am using `subprocess.Popen(cmd, she...
``` p = subprocess.Popen("echo 'foo' && sleep 60 && echo 'bar'", shell=True) p.kill() ``` Check out the docs on the `subprocess` module for more info: <http://docs.python.org/2/library/subprocess.html>
Kill a running subprocess call
16,866,602
7
2013-05-31T21:54:40Z
16,866,664
10
2013-05-31T22:00:07Z
[ "python", "multithreading", "subprocess" ]
I'm launching a program with `subprocess` on Python. In some cases the program may freeze. This is out of my control. The only thing I can do from the command line it is launched from is Ctrl-Esc which kills the program quickly. Is there any way to emulate this with `subprocess`? I am using `subprocess.Popen(cmd, she...
Well, there are a couple of methods on the object returned by `subprocess.Popen()` which may be of use: [`Popen.terminate()`](http://docs.python.org/2/library/subprocess.html#subprocess.Popen.terminate) and [`Popen.kill()`](http://docs.python.org/2/library/subprocess.html#subprocess.Popen.kill), which send a `SIGTERM` ...
set ipython's default scientific notation threshold
16,866,761
7
2013-05-31T22:10:00Z
16,867,604
8
2013-05-31T23:53:12Z
[ "python", "printing", "formatting", "ipython", "output" ]
How can I modify the point at which python decides to print in scientific notation? E.g. I'd like everything `> 1e4` or `< 1e-4` to be printed in scientific notation. Good: ``` In [11]: 5e20 Out[11]: 5e+20 ``` Bad: ``` In [12]: 5e10 Out[12]: 50000000000.0 ```
In IPython you can use ``` %precision %.4g ``` this will print floating point values who's absolute value is < 1e-4 or >= 1e4 in scientific notation. You can find more information about the `%precision` command in the [IPython API Docs](http://ipython.org/ipython-doc/stable/api/generated/IPython.core.magics.basic.ht...
Step-by-step debugging with IPython
16,867,347
84
2013-05-31T23:21:04Z
16,876,288
13
2013-06-01T19:10:09Z
[ "python", "debugging", "emacs", "ipython", "pdb" ]
From what I have read, there are two ways to debug code in Python: * With a traditional debugger such as `pdb` or `ipdb`. This supports commands such as `c` for `continue`, `n` for `step-over`, `s` for `step-into` etc.), but you don't have direct access to an IPython shell which can be extremely useful for object insp...
You can start IPython session from [pudb](https://pypi.python.org/pypi/pudb) and go back to the debugging session as you like. BTW, ipdb is using IPython behind the scenes and you can actually use IPython functionality such as TAB completion and magic commands (the one starts with `%`). If you are OK with ipdb you can...
Step-by-step debugging with IPython
16,867,347
84
2013-05-31T23:21:04Z
16,894,963
47
2013-06-03T10:46:18Z
[ "python", "debugging", "emacs", "ipython", "pdb" ]
From what I have read, there are two ways to debug code in Python: * With a traditional debugger such as `pdb` or `ipdb`. This supports commands such as `c` for `continue`, `n` for `step-over`, `s` for `step-into` etc.), but you don't have direct access to an IPython shell which can be extremely useful for object insp...
What about ipdb.set\_trace() ? In your code : `import ipdb; ipdb.set_trace()` This allows for full inspection of your code, and you have access to commands such as `c` (continue), `n` (execute next line) and so on. See the [ipdb repo](https://github.com/gotcha/ipdb) and [a list of commands](http://www.georgejhunt.co...
Step-by-step debugging with IPython
16,867,347
84
2013-05-31T23:21:04Z
23,388,116
31
2014-04-30T12:28:48Z
[ "python", "debugging", "emacs", "ipython", "pdb" ]
From what I have read, there are two ways to debug code in Python: * With a traditional debugger such as `pdb` or `ipdb`. This supports commands such as `c` for `continue`, `n` for `step-over`, `s` for `step-into` etc.), but you don't have direct access to an IPython shell which can be extremely useful for object insp...
# (Update on May 28, 2016) Using RealGUD in Emacs For anyone in Emacs, [this thread](https://github.com/rocky/emacs-dbgr/issues/96) shows how to accomplish everything described in the OP (and more) using 1. a new important debugger in Emacs called **RealGUD** which can operate with any debugger (including `ipdb`). 2....
Mock attributes in Python mock?
16,867,509
20
2013-05-31T23:40:19Z
16,867,539
29
2013-05-31T23:44:33Z
[ "python", "unit-testing", "testing", "mocking", "python-mock" ]
I'm having a fairly difficult time using `mock` in Python: ``` def method_under_test(): r = requests.post("http://localhost/post") print r.ok # prints "<MagicMock name='post().ok' id='11111111'>" if r.ok: return StartResult() else: raise Exception() class MethodUnderTestTest(TestCase):...
You need to use [`return_value`](http://www.voidspace.org.uk/python/mock/mock.html?highlight=return_value#mock.Mock.return_value) and [`PropertyMock`](http://www.voidspace.org.uk/python/mock/mock.html#mock.PropertyMock): ``` with patch('requests.post') as patched_post: type(patched_post.return_value).ok = Property...
python sorting dictionary by length of values
16,868,457
16
2013-06-01T02:19:56Z
16,868,476
30
2013-06-01T02:22:54Z
[ "python", "sorting", "dictionary" ]
I have found many threads for sorting by values like [here](http://stackoverflow.com/questions/613183/python-sort-a-dictionary-by-value) but it doesn't seem to be working for me... I have a dictionary of lists that have tuples. Each list has a different amount of tuples. I want to sort the dictionary by how many tuple...
``` >>> d = {"one": [(1,3),(1,4)], "two": [(1,2),(1,2),(1,3)], "three": [(1,1)]} >>> for k in sorted(d, key=lambda k: len(d[k]), reverse=True): print k, two one three ``` This also works: ``` >>> print ' '.join(sorted(d, key=lambda k: len(d[k]), reverse=True)) two one three ```
Python read website data line by line when available
16,870,648
6
2013-06-01T08:17:16Z
16,870,677
11
2013-06-01T08:21:22Z
[ "python" ]
I am using `urllib2` to read the data from the url, below is the code snippet : ``` data = urllib2.urlopen(urllink) for lines in data.readlines(): print lines ``` Url that I am opening is actually a cgi script which does some processing and prints the data in parallel. CGI script takes around 30 minutes to complete...
Just loop *directly* over the file object: ``` for line in data: print line ``` This reads the incoming data stream line by line (internally, the socket fileobject calls `.readline()` every time you iterate). This does assume that your server is sending data as soon as possible. Calling `.readlines()` (plural) g...
How do I validate a date string format in python?
16,870,663
38
2013-06-01T08:19:40Z
16,870,682
23
2013-06-01T08:21:42Z
[ "python", "date" ]
I have a python method which accepts **a date input as a string**. How do I add a validation to make sure the date string being passed to the method is in the ffg. format: ``` 'YYYY-MM-DD' ``` if it's not, method should raise some sort of error
The [Python `dateutil`](http://labix.org/python-dateutil) library is designed for this (and more). It will automatically convert this to a `datetime` object for you and raise a `ValueError` if it can't. As an example: ``` >>> from dateutil.parser import parse >>> parse("2003-09-25") datetime.datetime(2003, 9, 25, 0, ...
How do I validate a date string format in python?
16,870,663
38
2013-06-01T08:19:40Z
16,870,690
10
2013-06-01T08:22:18Z
[ "python", "date" ]
I have a python method which accepts **a date input as a string**. How do I add a validation to make sure the date string being passed to the method is in the ffg. format: ``` 'YYYY-MM-DD' ``` if it's not, method should raise some sort of error
``` from datetime import datetime datetime.strptime(date_string, "%Y-%m-%d") ``` ..this raises a `ValueError` if it receives an incompatible format. ..if you're dealing with dates and times a lot (in the sense of datetime objects, as opposed to unix timestamp floats), it's a good idea to look into the pytz module, a...
How do I validate a date string format in python?
16,870,663
38
2013-06-01T08:19:40Z
16,870,699
56
2013-06-01T08:23:42Z
[ "python", "date" ]
I have a python method which accepts **a date input as a string**. How do I add a validation to make sure the date string being passed to the method is in the ffg. format: ``` 'YYYY-MM-DD' ``` if it's not, method should raise some sort of error
``` >>> import datetime >>> def validate(date_text): try: datetime.datetime.strptime(date_text, '%Y-%m-%d') except ValueError: raise ValueError("Incorrect data format, should be YYYY-MM-DD") >>> validate('2003-12-23') >>> validate('2003-12-32') Traceback (most recent call last): File "<pysh...
trying to import a module: undefined symbol: PyUnicodeUCS4_DecodeUTF8
16,871,799
9
2013-06-01T10:40:27Z
16,872,055
16
2013-06-01T11:11:55Z
[ "python", "linux", "glib" ]
import glib fails with: `ImportError: /usr/lib/python2.7/dist-packages/glib/_glib.so: undefined symbol: PyUnicodeUCS4_DecodeUTF8` How can I fix this? Python version is Python 2.7.3rc2. The OS is Debian.
The module was built against a Python that was built with UCS-4 as its internal `unicode` representation. Your Python was built with UCS-2 as its internal representation. Rebuild the module, or rebuild Python. This issue is mentioned in [the official FAQ](http://docs.python.org/2.7/faq/extending.html#when-importing-mo...
How to programmatically get the MD5 Checksum of Amazon S3 file using boto
16,872,679
7
2013-06-01T12:23:10Z
16,874,368
8
2013-06-01T15:37:38Z
[ "python", "python-2.7", "amazon-s3", "md5", "boto" ]
Referred Posts: [Amazon S3 & Checksum](http://stackoverflow.com/questions/8618218/amazon-s3-checksum), [How to encode md5 sum into base64 in BASH](http://stackoverflow.com/questions/4583967/how-to-encode-md5-sum-into-base64-in-bash) I have to download a tar file from S3 bucket with limited access. [ Mostly access perm...
When boto downloads a file using any of the `get_contents_to_*` methods, it computes the MD5 checksum of the bytes it downloads and makes that available as the `md5` attribute of the `Key` object. In addition, S3 sends an `ETag` header in the response that represents the server's idea of what the MD5 checksum is. This ...
SQLite Data Change Notification Callbacks in Python or Bash or CLI
16,872,700
5
2013-06-01T12:26:15Z
16,920,926
9
2013-06-04T14:50:29Z
[ "python", "bash", "sqlite", "sqlite3", "command-line-interface" ]
SQLite has [Data Change Notification Callbacks](http://www.sqlite.org/c3ref/update_hook.html) available in the C API. Can these callbacks be used from the SQLite CLI, or from Bash or from Python? If so, how?
> Can these callbacks be used from the SQLite CLI... Reading through the SQLite source code, it doesn't look like that function is used anywhere in the CLI source code, so I doubt you can do it via the CLI. > ...or from Bash... Not sure what you mean by that. > ...or from Python? It's not exposed via the standard ...
Form a big 2d array from multiple smaller 2d arrays
16,873,441
4
2013-06-01T13:54:29Z
16,873,755
12
2013-06-01T14:32:46Z
[ "python", "numpy" ]
The question is the inverse of [this question](http://stackoverflow.com/q/16856788/1214214). I'm looking for a generic method to from the original big array from small arrays: ``` array([[[ 0, 1, 2], [ 6, 7, 8]], [[ 3, 4, 5], [ 9, 10, 11]], [[12, 13, 14], [18, 19, 20]],...
``` import numpy as np def blockshaped(arr, nrows, ncols): """ Return an array of shape (n, nrows, ncols) where n * nrows * ncols = arr.size If arr is a 2D array, the returned array looks like n subblocks with each subblock preserving the "physical" layout of arr. """ h, w = arr.shape r...
How do I fix this "TypeError: 'str' object is not callable" error?
16,873,727
9
2013-06-01T14:30:06Z
16,873,737
19
2013-06-01T14:31:21Z
[ "python", "string", "user-interface", "comparison", "callable" ]
I'm creating a basic program that will use a GUI to get a price of an item, then take 10% off of the price if the initial price is less than 10, or take 20% off of the price if the initial price is greater than ten: ``` import easygui price=easygui.enterbox("What is the price of the item?") if float(price) < 10: e...
You are trying to use the string as a function: ``` "Your new price is: $"(float(price) * 0.1) ``` Because there is nothing between the string literal and the `(..)` parenthesis, Python interprets that as an instruction to treat the string as a callable and invoke it with one argument: ``` >>> "Hello World!"(42) Tra...
Running a module from the pycharm console
16,874,046
8
2013-06-01T15:04:36Z
16,874,278
10
2013-06-01T15:28:06Z
[ "python", "console", "pycharm" ]
I'm new to python and pycharm and I'd like to run a module from the pycharm console in the same way as you can from IDLE, if it's possible. The idea is to create simple functions and test them "live" using the console. ...how do you do that in pycharm?
Running python scripts using pycharm is pretty straightforward, quote from [docs](http://www.jetbrains.com/pycharm/webhelp/running-applications.html): > To run a script with a temporary run/debug configuration Open the > desired script in the editor, or select it in the Project tool window. > Choose Run on the context...
Python `map` and arguments unpacking
16,874,244
6
2013-06-01T15:23:59Z
16,874,261
11
2013-06-01T15:25:51Z
[ "python", "map-function" ]
I know, that ``` map(function, arguments) ``` is equivalent to ``` for argument in arguments: function(argument) ``` Is it possible to use map function to do the following? ``` for arg, kwargs in arguments: function(arg, **kwargs) ```
You can with a lambda: ``` map(lambda a: function(a[0], **a[1]), arguments) ``` or you could use a generator expression or list comprehension, depending on what you want: ``` (function(a, **k) for a, k in arguments) [function(a, **k) for a, k in arguments] ``` In Python 2, `map()` returns a list (so the list compre...
How do I calculate the md5 checksum of a file in Python?
16,874,598
30
2013-06-01T16:05:09Z
16,876,405
81
2013-06-01T19:25:23Z
[ "python", "python-3.x", "md5", "md5sum" ]
I have made a code in python that checks for an md5 in a file and makes sure the md5 matches that of the original. Here is what I have developed: ``` #Defines filename filename = "file.exe" #Gets MD5 from file def getmd5(filename): return m.hexdigest() md5 = dict() for fname in filename: md5[fname] = getmd...
In regards to your error and what's missing in your code. m is name which was not defined for getmd5() function. No offence, I know you are a beginner, but your code is all over the place. Let's look at your issues one by one :) First off, you are not using hashlib.md5.hexdigest() method correctly. Please find explanat...
Where do this new line come from?
16,874,783
2
2013-06-01T16:30:10Z
16,874,801
8
2013-06-01T16:32:40Z
[ "python", "python-2.7" ]
Reading "Learn Python the Hard Way", I am playing with Exercise 10 ``` tabby_cat = "\tI'm tabbed in." persian_cat = "I'm split\non a line." backslash_cat = "I'm \\ a \\ cat." fat_cat = """ I'll do a list: \t* Cat food \t* Fishies \t* Catnip\n\t* Grass """ print tabby_cat print persian_cat print backslash_cat print f...
``` fat_cat = """ <-- here? I'll do a list: ``` That is, ``` fat_cat = """I'll do a list: ... ``` removes it.
Create a 100 % stacked area chart with matplotlib
16,875,546
4
2013-06-01T17:53:13Z
16,899,920
12
2013-06-03T15:06:49Z
[ "python", "matplotlib", "stacked-area-chart" ]
I was wondering how to create a 100 % stacked area chart in matplotlib. At the matplotlib page I couldn't find an example for it. Somebody here can show me how to achieve that?
A simple way to achieve this is to make sure that for every x-value, the y-values sum to 100. I assume that you have the y-values organized in an array as in the example below, i.e. ``` y = np.array([[17, 19, 5, 16, 22, 20, 9, 31, 39, 8], [46, 18, 37, 27, 29, 6, 5, 23, 22, 5], [15, 4...
python dict in list on for loop
16,875,701
3
2013-06-01T18:08:59Z
16,875,728
9
2013-06-01T18:11:42Z
[ "python", "list", "loops", "dictionary" ]
I don't understand why these 2 statements is not equal. ``` for item in tree.findAll('item'): names = [{ 'id': item.id.string, 'title': __decodefunction(item.entitle.string) }] ``` it has 1 item but if these statement ``` names = [{ 'id': item.id.string, 'title': __decodefunction(item.ent...
They do very different things. The first defines a new `names` value in each iteration of the loop, replacing any previous value. Each time you create a new list with *one* dictionary in it. The second is a list comprehension, which builds a list consisting of 0 or more dictionaries, one for each element returned by ...
How to customize pip's requirements.txt in Heroku on deployment?
16,876,816
3
2013-06-01T20:11:47Z
16,877,452
11
2013-06-01T21:30:15Z
[ "python", "heroku", "pip" ]
I'm deploying a Python Django app to Heroku, and I'd like to customize the requirements.txt file (by adding a git-backed dependency with password) only when I deploy to certain environments like Heroku. I'd love to set this in an environment variable or something, but I don't believe pip has any functionality like that...
You can include a requirements file in another requirements file. ``` # requirements.txt -r requirements/base.txt # requirements/base.txt django==1.6 # requirements/heroku.txt -r requirements/base.txt djpostgresurlthing==1.0.0 # requirements/dev.txt -r requirements/base.txt django-debug-toolbar ``` I typically...
Parsing JSON responses
16,877,422
38
2013-06-01T21:26:07Z
16,877,439
61
2013-06-01T21:28:30Z
[ "python", "json", "rest", "python-requests" ]
Im using the python module 'requests' to send a RESTful GET to a server. For which I get a response of a JSON response. The JSON response is basically just a list of lists. Whats the best way to get the response into a format (i.e python based object) so I can either iterate or print it out using pprint. Thanks,
You can use [`json.loads`](http://docs.python.org/2/library/json.html#json.loads): ``` import json import requests response = requests.get(...) json_data = json.loads(response.text) ``` This converts a given string into a dictionary which allows you to access your JSON data easily within your code.
Parsing JSON responses
16,877,422
38
2013-06-01T21:26:07Z
16,877,561
92
2013-06-01T21:44:29Z
[ "python", "json", "rest", "python-requests" ]
Im using the python module 'requests' to send a RESTful GET to a server. For which I get a response of a JSON response. The JSON response is basically just a list of lists. Whats the best way to get the response into a format (i.e python based object) so I can either iterate or print it out using pprint. Thanks,
Simeon Visser's answer is correct, but if you're using Requests anyway, you might as well use the [built-in JSON decoder](http://docs.python-requests.org/en/latest/user/quickstart/#json-response-content): ``` import requests response = requests.get(...) data = response.json() ```
what is the right way to treat Python argparse.Namespace() as a dictionary?
16,878,315
51
2013-06-01T23:33:56Z
16,878,364
78
2013-06-01T23:42:09Z
[ "python", "dictionary", "duck-typing" ]
If I want to use the results of `argparse.ArgumentParser()`, which is a `Namespace` object, with a method that expects a dictionary or mapping-like object (see [collections.Mapping](http://docs.python.org/2/library/collections.html#collections.Mapping)), what is the right way to do it? ``` C:\>python Python 2.7.3 (def...
You can access the namespace's dictionary with [*vars()*](http://docs.python.org/2.7/library/functions.html#vars): ``` >>> import argparse >>> args = argparse.Namespace() >>> args.foo = 1 >>> args.bar = [1,2,3] >>> d = vars(args) >>> d {'foo': 1, 'bar': [1, 2, 3]} ``` You can modify the dictionary directly if you wis...
what is the right way to treat Python argparse.Namespace() as a dictionary?
16,878,315
51
2013-06-01T23:33:56Z
28,546,857
9
2015-02-16T17:17:12Z
[ "python", "dictionary", "duck-typing" ]
If I want to use the results of `argparse.ArgumentParser()`, which is a `Namespace` object, with a method that expects a dictionary or mapping-like object (see [collections.Mapping](http://docs.python.org/2/library/collections.html#collections.Mapping)), what is the right way to do it? ``` C:\>python Python 2.7.3 (def...
[Straight from the horse's mouth](https://docs.python.org/3/library/argparse.html#the-namespace-object): If you prefer to have dict-like view of the attributes, you can use the standard Python idiom, [`vars()`](https://docs.python.org/3/library/functions.html#vars): ``` >>> parser = argparse.ArgumentParser() >>> pars...
Check to see if a collection of properties exist inside a dict object in Python
16,878,574
4
2013-06-02T00:19:20Z
16,878,580
8
2013-06-02T00:21:50Z
[ "python", "dictionary" ]
What is a good way to check to see if a collection of properties exist inside a dict object in Python? Currently we are doing this, but it seems like there may be a better way: ``` properties_to_check_for = ['name', 'date', 'birth'] for property in properties_to_check_for: if property not in dict_obj or dict_obj[...
You can use `all` with a generator: ``` all(key in dict_obj for key in properties_to_check_for) ``` It'll short-circuit, just like your `for` loop. Here's a direct translation of your current code: ``` all(dict_obj.get(key) is not None for key in properties_to_check_for) ``` `d.get(key)` will return `None` if the k...
How to find the index of n largest elements in a list or np.array, Python
16,878,715
4
2013-06-02T00:45:22Z
16,878,812
14
2013-06-02T01:03:54Z
[ "python", "arrays", "list" ]
Is there a built-in function or a very simple way of finding the index of n largest elements in a list or a numpy array? ``` K = [1,2,2,4,5,5,6,10] ``` Find the index of the largest 5 elements? I count the duplicates more than once, and the output should be a list of the indices of those largest numbers
Maybe something like: ``` >>> K [4, 5, 1, 6, 2, 5, 2, 10] >>> sorted(range(len(K)), key=lambda x: K[x]) [2, 4, 6, 0, 1, 5, 3, 7] >>> sorted(range(len(K)), key=lambda x: K[x])[-5:] [0, 1, 5, 3, 7] ``` or using `numpy`, you can use `argsort`: ``` >>> np.argsort(K)[-5:] array([0, 1, 5, 3, 7]) ``` `argsort` is also a m...