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
Python Sniffing from Black Hat Python book
29,306,747
7
2015-03-27T17:33:41Z
29,307,402
13
2015-03-27T18:08:02Z
[ "python", "linux", "sockets", "networking" ]
``` import socket import os import struct import sys from ctypes import * # host to listen on host = sys.argv[1] class IP(Structure): _fields_ = [ ("ihl", c_ubyte, 4), ("version", c_ubyte, 4), ("tos", c_ubyte), ("len", c_ushort), ("id"...
``` #raw_buffer = sniffer.recvfrom(65565)[0] raw_buffer = sniffer.recvfrom(65535)[0] ``` IP paket size is (2^16) - 1 The problem is with 32 vs 64 bit systems. `ip_header = IP(raw_buffer[:20])` works on x86 Ubuntu. `ip_header = IP(raw_buffer[:32])` works on amd64 CentOS 6.6 Python 2.6.6 `ip_header = IP(raw_buffe...
fabric Import Error: cannot import name 'isMappingType'
29,306,752
5
2015-03-27T17:34:04Z
29,306,872
9
2015-03-27T17:40:22Z
[ "python", "django", "fabric" ]
I came across this "ImportError: cannot import name 'isMappingType' " in the middle of process to deploy fabfile for a Django Project. 1.Here is the structure of my fabfile.py ``` from __future__ import with_statement from fabric.api import * from fabric.contrib.console import confirm from fabric.contrib.files import...
[`fabric` *doesn't support Python 3*](https://github.com/fabric/fabric): > Fabric is a Python (2.5-2.7) library and command-line tool for > streamlining the use of SSH for application deployment or systems > administration tasks. See also other points and workarounds at: * [Python 3 support for fabric](http://stacko...
Why am I getting a "Task was destroyed but it is pending" error in Python asyncio?
29,307,698
5
2015-03-27T18:27:04Z
29,307,819
9
2015-03-27T18:33:31Z
[ "python", "python-asyncio", "aiohttp" ]
I use `asyncio` and beautiful `aiohttp`. The main idea is that I make request to server (it returns links) and then I want to download files from all links in **parallel** (something like in an [example](https://docs.python.org/3/library/asyncio-task.html#example-parallel-execution-of-tasks)). Code: ``` import aiohtt...
You forgot to `yield from` the call to `asyncio.wait`. You also probably have the indentation on it wrong; you only want to run it after you've iterated over the entire `raw['files']` list. Here's the complete example with both mistakes fixed: ``` import aiohttp import asyncio @asyncio.coroutine def downloader(file):...
How to replace characters in string by the next one?
29,307,814
2
2015-03-27T18:33:14Z
29,307,923
8
2015-03-27T18:39:12Z
[ "python" ]
I would like to replace every character of a string with the next one and the last should become first. Here is an example: ``` abcdefghijklmnopqrstuvwxyz ``` should become: ``` bcdefghijklmnopqrstuvwxyza ``` Is it possible to do it without using the replace function 26 times?
You can use the [`str.translate()` method](https://docs.python.org/2/library/stdtypes.html#str.translate) to have Python replace characters by other characters in one step. Use the [`string.maketrans()` function](https://docs.python.org/2/library/string.html#string.maketrans) to map ASCII characters to their targets; ...
Converting List to Dict
29,309,643
4
2015-03-27T20:27:38Z
29,309,683
15
2015-03-27T20:30:14Z
[ "python", "python-2.7" ]
When I had a list that was in format of ``` list1 = [[James,24],[Ryan,21],[Tim,32]...etc] ``` I could use ``` dic1 =dict(list1) ``` However now lets say I have multiple values such as ``` list1 = [[James,24,Canada,Blue,Tall],[Ryan,21,U.S.,Green,Short [Tim,32,Mexico,Yellow,Average]...etc] ``` I have no idea how to...
You can use a [dict comprehension](https://docs.python.org/2/tutorial/datastructures.html#dictionaries) and slicing : ``` >>> list1 = [['James','24','Canada','Blue','Tall'],['Ryan','21','U.S.','Green','Short']] >>> {i[0]:i[1:] for i in list1} {'James': ['24', 'Canada', 'Blue', 'Tall'], 'Ryan': ['21', 'U.S.', 'Green', ...
Django Rest Framework 3 Serializers on non-Model objects?
29,310,000
7
2015-03-27T20:51:38Z
29,314,232
8
2015-03-28T06:05:36Z
[ "python", "django", "serialization", "django-rest-framework" ]
i'm doing an upgrade to DRF3.1.1 from 2.4. I was using a custom serializer to create an instance of an object that's not a Model. In 2.4, it was easy enough to do this because in the serializer, I would create the object in `restore_object()`. In the view, i'd call `serializer.is_valid()` and then pop the instance of ...
Thanks @levi for the beginnings of an answer, but unfortunately, that's not all of it, so I think this is a more complete answer. I originally asked: > Am I just missing some new DRF3 concept? Turns out...Yep. I was. The docs talk about the new `Single-step object creation`, which made me think the serialization and...
Django programming error 1146 table doesn't exist
29,310,117
2
2015-03-27T20:59:43Z
29,310,275
9
2015-03-27T21:11:52Z
[ "python", "mysql", "django", "database-migration" ]
I'm setting up my django project on a new remote server. When trying to setup the database running `python manage.py migrate' to run all migrations I get the following error: ``` Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/p...
There's a problem in the way your code is written, especially this line : ``` tag_choices = ((obj.id, obj.tag) for obj in BlogTag.objects.all()) ``` In forms.py : you shouldn't use any QuerySet filtering in module body because it is executed when the module load, you'd rather call it in a function. That's why your m...
Get the product of lists inside a dict while retaining the same keys
29,311,131
3
2015-03-27T22:19:19Z
29,311,222
7
2015-03-27T22:27:49Z
[ "python", "list", "dictionary", "product" ]
I have the following dict: `my_dict = {'A': [1, 2], 'B': [1, 4]}` And I want to end up with a list of dicts like this: ``` [ {'A': 1, 'B': 1}, {'A': 1, 'B': 4}, {'A': 2, 'B': 1}, {'A': 2, 'B': 4} ] ``` So, I'm after the product of dict's lists, expressed as a list of dicts using the same keys as the...
You can use [`itertools.product`](https://docs.python.org/2/library/itertools.html#itertools.product) for this, i.e calculate cartesian product of the value and then simply zip each of the them with the keys from the dictionary. Note that [ordering of a dict](https://docs.python.org/2/library/stdtypes.html#mapping-type...
How to set the timezone in Django?
29,311,354
24
2015-03-27T22:41:33Z
29,311,392
44
2015-03-27T22:45:07Z
[ "python", "django", "timezone", "utc" ]
In my django project's `settings.py` file, I have this line : ``` TIME_ZONE = 'UTC' ``` But I want my app to run in UTC+2 timezone, so I changed it to ``` TIME_ZONE = 'UTC+2' ``` It gives the error `ValueError: Incorrect timezone setting: UTC+2`. What is the correct way of doing this? Thanks!
Here is the list of valid timezones: <http://en.wikipedia.org/wiki/List_of_tz_database_time_zones> You can use ``` TIME_ZONE = 'Europe/Istanbul' ``` for UTC+02:00
Reverse a Python string without omitting start and end slice
29,312,383
20
2015-03-28T00:51:32Z
29,312,436
13
2015-03-28T00:59:56Z
[ "python", "reverse", "slice" ]
How do you reverse a Python string without omitting the start and end slice arguments? ``` word = "hello" reversed_word = word[::-1] ``` I understand that this works, but how would I get the result by specifying the start and end indexes? ``` word = "hello" reversed_word = word[?:?:-1] ```
Not quite sure why, but the following will return the reverse of `word`: ``` word = "hello" word[len(word):-(len(word)+1):-1] ``` Or... ``` word = "hello" word[len(word):-len(word)-1:-1] ``` **Edit (Explanation):** From jedward's comment: > The middle parameter is the trickiest, but it's pretty straightforward > ...
Reverse a Python string without omitting start and end slice
29,312,383
20
2015-03-28T00:51:32Z
29,313,612
15
2015-03-28T04:14:52Z
[ "python", "reverse", "slice" ]
How do you reverse a Python string without omitting the start and end slice arguments? ``` word = "hello" reversed_word = word[::-1] ``` I understand that this works, but how would I get the result by specifying the start and end indexes? ``` word = "hello" reversed_word = word[?:?:-1] ```
Some other ways to reverse a string: ``` word = "hello" reversed_word1 = word[-1: :-1] reversed_word2 = word[len(word): :-1] reversed_word3 = word[:-len(word)-1 :-1] ``` One thing you should note about the slicing notation `a[i:j:k]` is that **omitting `i` and `j` doesn't always mean that `i` will become `0` and ...
Is there a better way to run a randomly chosen function?
29,313,319
2
2015-03-28T03:25:50Z
29,313,360
9
2015-03-28T03:31:35Z
[ "python", "function", "eval" ]
I made a Tic-Tac-Toe game, and for one of the AI's I made, it chooses a random function enclosed in quotes (so it is a string) and calls `eval()` on it. Here's what it look like: ``` import random func_list = ["func1()", "func2()", "func3()"] eval(random.choice(func_list)) ``` I don't really like using `eval()` (no...
Functions are first-class objects in Python. That means you can pass them around, and store them in lists as well, just like any other object. So why not just do this? ``` func_list = [func1, func2, func3] random.choice(func_list)() ```
How do I remove the background from this kind of image?
29,313,667
5
2015-03-28T04:23:27Z
29,314,286
9
2015-03-28T06:12:59Z
[ "python", "image-processing", "scikit-image" ]
![Image_1](http://i.stack.imgur.com/SYxmp.jpg) I want to remove the background of this image to get the person only. I have thousand of images like this, basically, a person and a somewhat whitish background. What I have done is to use edge detector like canny edge detector or sobel filter (from `skimage` library). T...
The following code should get you started. You may want to play around with the parameters at the top of the program to fine-tune your extraction: ``` import cv2 import numpy as np #== Parameters ======================================================================= BLUR = 21 CANNY_THRESH_1 = 10 CANNY_THRESH_2 = 200...
Python Pandas DataFrame remove Empty Cells
29,314,033
5
2015-03-28T05:30:48Z
29,314,880
9
2015-03-28T07:46:29Z
[ "python", "pandas" ]
I have a pd.DataFrame that was created by parsing some excel spreadsheets. A column of which has empty cells. For example, below is the output for the frequency of that column, 32320 records have missing values for Tenant. ``` In [67]: value_counts(Tenant,normalize=False) Out[67]: 3...
Pandas will recognise a value as null if it is a `np.nan` object, which will print as `NaN` in the DataFrame. Your missing values are probably empty strings, which Pandas does not recognise as null. To rectify this, you can convert the empty stings (or whatever is in your empty cells) to `np.nan` objects using `replace...
Python Pandas DataFrame remove Empty Cells
29,314,033
5
2015-03-28T05:30:48Z
29,319,460
8
2015-03-28T16:19:17Z
[ "python", "pandas" ]
I have a pd.DataFrame that was created by parsing some excel spreadsheets. A column of which has empty cells. For example, below is the output for the frequency of that column, 32320 records have missing values for Tenant. ``` In [67]: value_counts(Tenant,normalize=False) Out[67]: 3...
value\_counts omits NaN by default so you're most likely dealing with "". So you can just filter them out like ``` filter = df["Tenant"] != "" dfNew = df[filter] ```
Itertools product without repeating duplicates
29,314,372
3
2015-03-28T06:27:55Z
29,314,389
9
2015-03-28T06:30:08Z
[ "python", "python-3.x", "itertools" ]
``` from itertools import product teams = ['india', 'australia', 'new zealand'] word_and = ['and'] tmp = '%s %s %s' items = [teams, word_and, teams] print(list(tmp % a for a in list(product(*items)))) ``` prints: ``` ['india and india', 'india and australia', 'india and new zealand', 'australia and india', 'austr...
You should use [`itertools.combinations`](https://docs.python.org/3/library/itertools.html#itertools.combinations) like this ``` >>> from itertools import combinations >>> teams = ['india', 'australia', 'new zealand'] >>> [" and ".join(items) for items in combinations(teams, r=2)] ['india and australia', 'india and ne...
Is it possible to get color gradients under curve in matplotlb?
29,321,835
8
2015-03-28T19:52:42Z
29,331,211
11
2015-03-29T15:46:24Z
[ "python", "matplotlib" ]
I happen to see beautiful graphs on this [page](http://hackaday.com/2015/01/28/raspberry-pi-learns-how-to-control-a-combustion-engine/#more-145076) which is shown below: ![enter image description here](http://i.stack.imgur.com/Ldrog.png) Is it possible to get such color gradients in matplotlib?
There have been a handful of previous answers to similar questions (e.g. <http://stackoverflow.com/a/22081678/325565>), but they recommend a sub-optimal approach. Most of the previous answers recommend plotting a white polygon over a `pcolormesh` fill. This is less than ideal for two reasons: 1. The background of the...
Is it possible to get color gradients under curve in matplotlb?
29,321,835
8
2015-03-28T19:52:42Z
29,347,731
10
2015-03-30T13:39:07Z
[ "python", "matplotlib" ]
I happen to see beautiful graphs on this [page](http://hackaday.com/2015/01/28/raspberry-pi-learns-how-to-control-a-combustion-engine/#more-145076) which is shown below: ![enter image description here](http://i.stack.imgur.com/Ldrog.png) Is it possible to get such color gradients in matplotlib?
*Please note [Joe Kington](http://stackoverflow.com/a/29331211/190597) deserves the lion's share of the credit here; my sole contribution is `zfunc`.* His method opens to door to many gradient/blur/drop-shadow effects. For example, to make the lines have an evenly blurred underside, you could use PIL to build an alpha ...
NumPy random seed produces different random numbers
29,324,735
5
2015-03-29T01:45:11Z
29,324,779
9
2015-03-29T01:54:24Z
[ "python", "numpy", "random" ]
I run the following code: ``` np.random.RandomState(3) idx1 = np.random.choice(range(20),(5,)) idx2 = np.random.choice(range(20),(5,)) np.random.RandomState(3) idx1S = np.random.choice(range(20),(5,)) idx2S = np.random.choice(range(20),(5,)) ``` The output I get is the following: ``` idx1: array([ 2, 19, 19...
You're confusing `RandomState` with `seed`. Your first line constructs an object which you can then use as your random source. For example, we make ``` >>> rnd = np.random.RandomState(3) >>> rnd <mtrand.RandomState object at 0xb17e18cc> ``` and then ``` >>> rnd.choice(range(20), (5,)) array([10, 3, 8, 0, 19]) >>>...
Global error handler for any exception
29,332,056
6
2015-03-29T16:58:14Z
29,332,131
10
2015-03-29T17:05:16Z
[ "python", "error-handling", "flask", "http-error" ]
Is there a way to add a global catch-all error handler in which I can change the response to a generic JSON response? I can't use the `got_request_exception` signal, as it is not allowed to modify the response (<http://flask.pocoo.org/docs/0.10/signals/>). > In contrast all signal handlers are executed in undefined o...
You can use `@app.errorhandler(Exception)`: Demo (the HTTPException check ensures that the status code is preserved): ``` from flask import Flask, abort, jsonify from werkzeug.exceptions import HTTPException app = Flask('test') @app.errorhandler(Exception) def handle_error(e): code = 500 if isinstance(e, HT...
Python class scoping rules
29,333,359
26
2015-03-29T18:48:47Z
29,333,740
7
2015-03-29T19:25:50Z
[ "python", "scoping" ]
**EDIT:** Looks like this is a very old "bug" or, actually, feature. See, e.g., [this mail](https://mail.python.org/pipermail/python-dev/2002-April/023428.html) I am trying to understand the Python scoping rules. More precisely, I thought that I understand them but then I found this code [here](http://lackingrhoticity...
First focus on the case of a closure -- a function within a function: ``` x = "xtop" y = "ytop" def func(): x = "xlocal" y = "ylocal" def inner(): # global y print(x) print(y) y='inner y' print(y) inner() ``` Note the commented out `global` in `inner` If you run ...
Python class scoping rules
29,333,359
26
2015-03-29T18:48:47Z
29,334,539
12
2015-03-29T20:35:53Z
[ "python", "scoping" ]
**EDIT:** Looks like this is a very old "bug" or, actually, feature. See, e.g., [this mail](https://mail.python.org/pipermail/python-dev/2002-April/023428.html) I am trying to understand the Python scoping rules. More precisely, I thought that I understand them but then I found this code [here](http://lackingrhoticity...
**TL;DR**: This behaviour has existed since Python 2.1 [PEP 227: Nested Scopes](https://docs.python.org/3/whatsnew/2.1.html#pep-227-nested-scopes), and was known back then. If a name is assigned to within a class body (like `y`), then it is assumed to be a local/global variable; if it is not assigned to (`x`), then it ...
pandas read csv file line by line
29,334,463
6
2015-03-29T20:29:18Z
29,334,672
14
2015-03-29T20:49:27Z
[ "python", "pandas" ]
I have a very big csv file so that I can not read them all into the memory. I only want to read and process a few lines in it. So I am seeking a function in Pandas which could handle this task, which the basic python can handle this well: ``` with open('abc.csv') as f: line = f.readline() # pass until it reach...
Use [`chunksize`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html#pandas.read_csv): ``` for df in pd.read_csv('matrix.txt',sep=',', header = None, chunksize=1): #do something ``` To answer your second part do this: ``` df = pd.read_csv('matrix.txt',sep=',', header = None, skiprows=1000...
Eval scope in Python 2 vs. 3
29,336,616
24
2015-03-30T00:22:53Z
29,336,695
24
2015-03-30T00:34:38Z
[ "python", "python-3.x", "compatibility", "python-3.4" ]
I came across bizarre eval behavior in Python 3 - local variables aren't picked up when eval is called in a list comprehension. ``` def apply_op(): x, y, z = [0.5, 0.25, 0.75] op = "x,y,z" return [eval(o) for o in op.split(",")] print(apply_op()) ``` It errors in Python 3: ``` ▶ python --version Python...
There is a *closed* issue in the bug tracker for this: [Issue 5242](http://bugs.python.org/issue5242). The resolution for this bug is **won't fix**. Some comments from the Issue read: > This is expected, and won't easily fix. The reason is that list > comprehensions in 3.x use a function namespace "under the hood" (...
Processing specific files in a directory in python
29,339,662
2
2015-03-30T06:29:04Z
29,339,715
8
2015-03-30T06:32:14Z
[ "python", "json" ]
I wrote a small python program which processes all the files in a directory. I want to restrict that to include only JSON files in that directory. For example, the line `fname in fileList:` in the code snipped below should only enumerate files with the extension \*.json ``` #Set the directory you want to start from ro...
Since your file name is string you can use the [**`str.endswith`**](https://docs.python.org/2/library/stdtypes.html#str.endswith) method to check if it is `json` file. ``` if fname.endswith('.json'): #do_something() ```
Two different values for same variable "args"
29,342,420
2
2015-03-30T09:17:16Z
29,342,509
12
2015-03-30T09:21:03Z
[ "python", "python-2.7", "pdb" ]
I am invoking a method from python script which has one of the variable as args. Once I step into the method, when I am trying to see the value of the the variable args, "print args" and just executing 'args' display two different values. Can anyone please let me know whats the difference between these two commands. I...
`args` is a PDB debugger command. Use `!args` to show the actual variable. See the [*Debugger Commands* section](https://docs.python.org/2/library/pdb.html#debugger-commands): > *a(rgs)* > Print the argument list of the current function. and > *[!]statement* > Execute the (one-line) statement in the context of ...
django difference between clear() and delete()
29,344,450
4
2015-03-30T11:00:02Z
29,344,522
7
2015-03-30T11:03:00Z
[ "python", "django" ]
I'm using django for a while now and recently bumped into this : ``` user.groups.clear() ``` usually what I'd do is this: ``` user.groups.all().delete() ``` what's the difference?
`user.groups.all().delete()` will *delete* the related group objects, while `user.groups.clear()` will only disassociate the relation: <https://docs.djangoproject.com/en/1.7/ref/models/relations/#django.db.models.fields.related.RelatedManager.clear> > Removes all objects from the related object set: > Note this doesn...
What's the pythonic way to parse such a URI 'foo://user:pass@host:port' into proper variables?
29,346,878
2
2015-03-30T12:58:13Z
29,346,928
7
2015-03-30T13:01:21Z
[ "python" ]
Only the `host` part is not optional, that is to say the URI may has the following forms: ``` 1. foo://user:pass@host:port 2. foo://host:port 3. user@host 4. host ``` and so on. If we have five variables to save the values of parts in such an URI, Is there a pythonic way to assign these values to the proper varia...
You'd use [`urlparse`](https://docs.python.org/2/library/urlparse.html) (python 2) / [`urllib.parse`](https://docs.python.org/3/library/urllib.parse.html) module. The [`urlparse()` function](https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlparse) can handle all forms you mention, but note that witho...
Why is it a syntax error to have an object attribute named "del", "return" etc?
29,346,945
3
2015-03-30T13:01:48Z
29,346,977
8
2015-03-30T13:03:59Z
[ "python" ]
I understand that one shouldn't be able to replace the behaviour of the "del" ("return" etc) keyword, but I do not understand why it is not possible to do this: ``` myobj.del(mystr) ``` What could the parser confuse it with? Is there a way to allow it? Of course, I could use a different name, but I want to have a li...
That is because such words are keywords. Keywords in Python are reserved words that cannot be used as ordinary identifiers. The list includes [from the doc function `keyword`](https://docs.python.org/3/library/keyword.html) ``` >>> import keyword >>> import pprint >>> pprint.pprint(keyword.kwlist) ['and', 'as', '...
Difference between IOError and OSError?
29,347,790
5
2015-03-30T13:42:14Z
29,347,946
7
2015-03-30T13:49:37Z
[ "python", "exception", "python-2.x" ]
I am always getting confused on whether a function would raise an IOError or OSError (or both?). What is the principle rule behind these exception types, what is the difference between them and when is which raised? I've initially thought OSError is for things like permission denial, but opening a file without permiss...
There is very little difference between the two types. In fact, even the core Python developers agreed that there is no real difference and removed `IOError` in Python 3 (it is now an alias for `OSError`). See [PEP 3151 - Reworking the OS and IO exception hierarchy](https://www.python.org/dev/peps/pep-3151/#confusing-s...
Why can't I suppress numpy warnings
29,347,987
10
2015-03-30T13:51:28Z
29,348,184
12
2015-03-30T14:00:38Z
[ "python", "numpy" ]
I really want to avoid these annoying numpy warnings since I have to deal with a lot of `NaNs`. I know this is usually done with seterr, but for some reason here it does not work: ``` import numpy as np data = np.random.random(100000).reshape(10, 100, 100) * np.nan np.seterr(all="ignore") np.nanmedian(data, axis=[1, 2...
Warnings can often be useful and in most cases I wouldn't advise this, but you can always make use of the [`Warnings`](https://docs.python.org/2/library/warnings.html) module to ignore all warnings with `filterwarnings`: ``` warnings.filterwarnings('ignore') ``` Should you want to suppress uniquely your particular er...
Declaring a multi dimensional dictionary in python
29,348,345
5
2015-03-30T14:06:50Z
29,348,412
12
2015-03-30T14:09:14Z
[ "python", "dictionary" ]
I need to make a two dimensional dictionary in python. e.g. `new_dic[1][2] = 5` When I make `new_dic = {}`, and try to insert values, I get a `KeyError`? ``` new_dic[1][2] = 5 KeyError: 1 ``` How to do this?
A multi-dimensional dictionary is simply a dictionary where the values are themselves also dictionaries, creating a nested structure: ``` new_dic = {} new_dic[1] = {} new_dic[1][2] = 5 ``` You'd have to detect that you already created `new_dic[1]` each time, though, to not accidentally wipe that nested object for add...
How to make a continuous alphabetic list python (from a-z then from aa, ab, ac etc)
29,351,492
5
2015-03-30T16:31:54Z
29,351,603
11
2015-03-30T16:38:20Z
[ "python", "excel" ]
I would like to make a alphabetical list for an application similar to an excel worksheet. A user would input number of cells and I would like to generate list. For example a user needs 54 cells. Then I would generate 'a','b','c',...,'z','aa','ab','ac',...,'az', 'ba','bb' I can generate the list from [[ref]](http://...
Use `itertools.product`. ``` from string import ascii_lowercase import itertools def iter_all_strings(): size = 1 while True: for s in itertools.product(ascii_lowercase, repeat=size): yield "".join(s) size +=1 for s in iter_all_strings(): print s if s == 'bb': brea...
Creating a processing queue in Tornado
29,354,044
6
2015-03-30T18:57:29Z
29,354,963
10
2015-03-30T19:49:02Z
[ "python", "tornado" ]
I'm using a Tornado web server to queue up items that need to be processed outside of the request/response cycle. In my simplified example below, every time a request comes in, I add a new string to a list called `queued_items`. I want to create something that will watch that list and process the items as they show up...
There is a library called [`toro`](http://toro.readthedocs.org/en/latest/index.html), which provides synchronization primitives for `tornado`. **[Update: As of tornado 4.2, `toro` has been merged into `tornado`.]** Sounds like you could just use a `toro.Queue` (or `tornado.queues.Queue` in `tornado` 4.2+) to handle th...
Pandas MultiIndex: Divide all columns by one column
29,354,553
7
2015-03-30T19:25:42Z
29,354,704
8
2015-03-30T19:34:03Z
[ "python", "pandas" ]
I have a data frame `results` of the form ``` TOTEXPPQ TOTEXPCQ FINLWT21 year quarter 13 1 9.183392e+09 5.459961e+09 1271559.398 2 2.907887e+09 1.834126e+09 481169.672 ``` and I was trying to divide all (the first two) colum...
You have to specify the axis for the divide (with the [`div`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.div.html) method): ``` In [11]: results.div(weights, axis=0) Out[11]: TOTEXPPQ TOTEXPCQ year quarter 13 1 7222.149445 4293.909517 2 6043.371329...
How to connect MySQL database using Python+SQLAlchemy remotely?
29,355,674
6
2015-03-30T20:28:35Z
29,429,717
7
2015-04-03T09:39:52Z
[ "python", "mysql", "tcp", "sqlalchemy", "ssh-tunnel" ]
I am having difficulty accessing MySQL remotely. I use SSH tunnel and want to connect the database MySQL using Python+SQLALchemy. When i use MySQL-client in my console and specify "`ptotocol=TCP`", then everything is fine! I use command: ``` mysql -h localhost —protocol=TCP -u USER -p ``` I get access to remote da...
The classic answer to this issue is to use `127.0.0.1` or the *IP of the host* or the *host name* instead of the "special name" `localhost`. From the [documentation](https://dev.mysql.com/doc/refman/5.0/en/connecting.html#idm140235558252992): > [...] connections on Unix to *localhost* are made using a Unix socket file...
Plot inline or a separate window using Matplotlib in Spyder IDE
29,356,269
9
2015-03-30T21:05:38Z
36,683,220
7
2016-04-17T23:10:32Z
[ "python", "matplotlib", "spyder" ]
When I use Matplotlib to plot some graphs, it is usually fine for the default inline drawing. However, when I draw some 3D graphs, I'd like to have them in a separate window so that interactions like rotation can be enabled. Can I configure in Python code which figure to display inline and which one to display in a new...
type ``` %matplotlib qt ``` when you want graphs in a separate window and ``` %matplotlib inline ``` when you want an inline plot
Python list() vs list comprehension building speed
29,356,846
12
2015-03-30T21:41:41Z
29,356,931
11
2015-03-30T21:46:45Z
[ "python", "performance", "list", "list-comprehension", "python-2.x" ]
This is interesting; `list()` to force an iterator to get the actual list is so much faster than `[x for x in someList]` (comprehension). Is this for real or is my test just too simple? Below is the code: ``` import time timer = time.clock() for i in xrange(90): #localList = [x for x in xrange(1000000)] #...
The list comprehension executes the loop in Python bytecode, just like a regular `for` loop. The `list()` call iterates entirely in C code, which is far faster. The bytecode for the list comprehension looks like this: ``` >>> import dis >>> dis.dis(compile("[x for x in xrange(1000000)]", '<stdin>', 'exec')) 1 ...
no module named urllib.parse (How should I install it?)
29,358,403
5
2015-03-31T00:03:15Z
29,358,613
8
2015-03-31T00:28:55Z
[ "python", "django", "urllib" ]
I'm trying to run a REST API on CentOS 7, I read urllib.parse is in Python 3 but I'm using Python 2.7.5 so I don't know how to install this module. I installed all the requirements but still can't run the project. When I'm looking for a URL I get this (I'm using the browsable interface): Output: ``` ImportError at ...
With the information you have provided, your best bet will be to use Python 3.x. Your error suggests that the code may have been written for Python 3 given that it is trying to import `urllib.parse`. If you've written the software and have control over its source code, you **should** change the import to: ``` from ur...
Can the name and the reference of a named tuple be different?
29,358,695
3
2015-03-31T00:39:28Z
29,358,763
8
2015-03-31T00:47:22Z
[ "python", "tuples", "namedtuple" ]
While reading `fmark`'s answer to the question [What are "named tuples" in Python?](http://stackoverflow.com/questions/2970608/what-are-named-tuples-in-python) I saw that the example given there had the same name and reference, i.e. the word `Point` appears twice in the following statement: `Point = namedtuple('Point'...
You can do it, it will just annoy you. ``` In [1]: import collections In [2]: Point = collections.namedtuple('Rectangle', 'x y') In [3]: Point(1, 2) Out[3]: Rectangle(x=1, y=2) ``` This is confusing, don't do it unless you have a very good reason. The reason why this happens is because `namedtuple()` is just a fun...
Inefficient multiprocessing of numpy-based calculations
29,358,872
4
2015-03-31T01:02:41Z
29,361,699
7
2015-03-31T06:06:43Z
[ "python", "numpy", "multiprocessing" ]
I'm trying to parallelize some calculations that use `numpy` with the help of Python's `multiprocessing` module. Consider this simplified example: ``` import time import numpy from multiprocessing import Pool def test_func(i): a = numpy.random.normal(size=1000000) b = numpy.random.normal(size=1000000) ...
It looks like the test function you're using is memory bound. That means that the run time you're seeing is limited by how fast the computer can pull the arrays from memory into cache. For example, the line `a = a + b` is actually using 3 arrays, `a`, `b` and a new array that will replace `a`. These three arrays are ab...
How does this function to remove duplicate characters from a string in python work?
29,360,607
13
2015-03-31T04:26:11Z
29,360,674
11
2015-03-31T04:33:35Z
[ "python" ]
I was looking up how to create a function that removes duplicate characters from a string in python and found this on stack overflow: ``` from collections import OrderedDict def remove_duplicates (foo) : print " ".join(OrderedDict.fromkeys(foo)) ``` It works, but how? I've searched what OrderedDict a...
I will give it a shot: [OrderedDict](https://docs.python.org/3/library/collections.html#collections.OrderedDict) are dictionaries that store keys in order they are added. Normal dictionaries don't. If you look at **doc** of `fromkeys`, you find: > OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S. So th...
Modify Python/PIP to automatically install modules when failed to import
29,364,473
6
2015-03-31T08:53:51Z
29,466,052
10
2015-04-06T05:53:16Z
[ "python", "automation", "pip" ]
Is there a way to modify python/pip to, whenever an import fails **at runtime**, it would try to install the module (by the same name) from pip and then import the module? I'd say it would be a nicer default than to just throw an error. If after loading the module from pip any problems happen, then it would also throw...
You can do this with [pipimport](https://pypi.python.org/pypi/pipimport/0.2.5), when using `virtualenv`. It probably works with the system python if you have appropriate privileges to write the necessary directories (at least `site-packages`, but your import might have some command that `pip` will try to put somewhere ...
How to code adagrad in python theano
29,365,370
2
2015-03-31T09:37:56Z
29,643,793
7
2015-04-15T07:12:23Z
[ "python", "gradient", "theano" ]
To simplify the problem, say when a dimension (or a feature) is already updated n times, the next time I see the feature, I want to set the learning rate to be 1/n. I came up with these codes: ``` def test_adagrad(): embedding = theano.shared(value=np.random.randn(20,10), borrow=True) times = theano.shared(value=...
Perhaps you can utilize the following [example for implementation of **adadelta**](http://deeplearning.net/tutorial/code/lstm.py), and use it to derive your own. Please update if you succeeded :-)
Select dataframe rows between two dates
29,370,057
15
2015-03-31T13:38:06Z
29,370,182
38
2015-03-31T13:49:49Z
[ "python", "pandas" ]
I am creating a dataframe from a csv as follows: ``` stock = pd.read_csv('data_in/' + filename + '.csv', skipinitialspace=True) ``` The dataframe has a date column. Is there a way to create a new dataframe (or just overwrite the existing one) which only containes rows that fall between a specific date range?
There are two possible solutions: * Use a boolean mask, then use `df.loc[mask]` * Set the date column as a DatetimeIndex, then use `df[start_date : end_date]` --- **Using a boolean mask**: Ensure `df['date']` is a Series with dtype `datetime64[ns]`: ``` df['date'] = pd.to_datetime(df['date']) ``` Make a boolean m...
pandas split string into columns
29,370,211
4
2015-03-31T13:51:07Z
29,370,709
13
2015-03-31T14:13:34Z
[ "python", "pandas", "split" ]
I have the following `DataFrame`, where `Track ID` is the row index. How can I split the string in the `stats` column into 5 columns of numbers? ``` Track ID stats 14.0 (-0.00924175824176, 0.41, -0.742016492568, 0.0036830094242, 0.00251748449963) 28.0 (0.0411538461538, 0.318230769231, 0.758717081514, 0.002640...
And for the other case, assuming it are strings that look like tuples: ``` In [74]: df['stats'].str[1:-1].str.split(',', return_type='frame').astype(float) Out[74]: 0 1 2 3 4 0 -0.009242 0.410000 -0.742016 0.003683 0.002517 1 0.041154 0.318231 0.758717 0.002640 0.01065...
Compressing multiple conditions in Python
29,370,317
2
2015-03-31T13:57:11Z
29,370,354
7
2015-03-31T13:58:47Z
[ "python", "if-statement", "python-3.x" ]
Suppose I have a list of numbers `mylist` and that I would like execute some code if all the elements of `mylist` are greater than 10. I might try ``` if mylist[0] > 10 and mylist[1] > 10 and ... : do something ``` but this is obviously very cumbersome. I was wondering if Python has a way of compressing multiple ...
Your attempt is pretty close. You just needed the `all` function to examine the results of the expression. ``` if all(mylist[i] > 10 for i in range(len(mylist))): do something ``` Incidentally, consider iterating over the items of the list directly, rather than its indices. ``` if all(item > 10 for item in mylis...
What is the difference between numpy.linalg.lstsq and scipy.linalg.lstsq?
29,372,559
11
2015-03-31T15:34:38Z
29,390,702
9
2015-04-01T12:20:37Z
[ "python", "numpy", "scipy", "least-squares" ]
`lstsq` tries to solve `Ax=b` minimizing `|b - Ax|`. Both scipy and numpy provide a `linalg.lstsq` function with a very similar interface. The documentation does not mention which kind of algorithm is used, neither for [scipy.linalg.lstsq](http://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.lstsq.html#scip...
If I read the source code right (Numpy 1.8.2, Scipy 0.14.1 ), `numpy.linalg.lstsq()` uses the LAPACK routine `xGELSD` and `scipy.linalg.lstsq()` uses`xGELSS`. The [LAPACK Manual Sec. 2.4](http://www.netlib.org/lapack/lug/node27.html#tabdrivellsq) states > The subroutine xGELSD is significantly faster than its older c...
How to group by multiple keys in spark?
29,372,792
5
2015-03-31T15:44:40Z
29,515,600
9
2015-04-08T13:10:25Z
[ "python", "apache-spark", "pyspark" ]
I have a bunch of tuples which are in form of composite keys and values. For example, ``` tfile.collect() = [(('id1','pd1','t1'),5.0), (('id2','pd2','t2'),6.0), (('id1','pd1','t2'),7.5), (('id1','pd1','t3'),8.1) ] ``` I want to perform sql like operations on this collection, where I can aggregate the...
My guess is that you want to transpose the data according to multiple fields. A simple way is to concatenate the target fields that you will group by, and make it a key in a paired RDD. For example: ``` lines = sc.parallelize(['id1,pd1,t1,5.0', 'id2,pd2,t2,6.0', 'id1,pd1,t2,7.5', 'id1,pd1,t3,8.1']) rdd = lines.map(la...
First month of quarter given month in Python
29,375,785
12
2015-03-31T18:25:50Z
29,375,792
10
2015-03-31T18:26:16Z
[ "python", "date" ]
Given a month in numeric form (e.g., 2 for February), how do you find the first month of its respective quarter (e.g., 1 for January)? I read through the `datetime` module documentation and the Pandas documentation of their datetime functions, which ought to be relevant, but I could not find a function that solves thi...
Here is an answer suggested by [TigerhawkT3](http://stackoverflow.com/users/2617068/tigerhawkt3). Perhaps the leanest suggestion so far and, apparently, also the fastest. ``` import math def first_month_quarter(month): return int(math.ceil(month / 3.)) * 3 - 2 ``` For example: ``` >> first_month_quarter(5) 4 ``...
First month of quarter given month in Python
29,375,785
12
2015-03-31T18:25:50Z
29,376,814
13
2015-03-31T19:23:22Z
[ "python", "date" ]
Given a month in numeric form (e.g., 2 for February), how do you find the first month of its respective quarter (e.g., 1 for January)? I read through the `datetime` module documentation and the Pandas documentation of their datetime functions, which ought to be relevant, but I could not find a function that solves thi...
``` def first_month(month): return (month-1)//3*3+1 for i in range(1,13): print i, first_month(i) ```
First month of quarter given month in Python
29,375,785
12
2015-03-31T18:25:50Z
29,377,400
19
2015-03-31T19:55:10Z
[ "python", "date" ]
Given a month in numeric form (e.g., 2 for February), how do you find the first month of its respective quarter (e.g., 1 for January)? I read through the `datetime` module documentation and the Pandas documentation of their datetime functions, which ought to be relevant, but I could not find a function that solves thi...
It's not so pretty, but if speed is important a simple list lookup slaughters `math`: ``` def quarter(month, quarters=[None, 1, 1, 1, 4, 4, 4, 7, 7, 7, 10, 10, 10]): """Return the first month of the quarter for a given month.""" return quarters[month] ``` A [`timeit`](https://docs...
First month of quarter given month in Python
29,375,785
12
2015-03-31T18:25:50Z
29,381,448
19
2015-04-01T01:37:24Z
[ "python", "date" ]
Given a month in numeric form (e.g., 2 for February), how do you find the first month of its respective quarter (e.g., 1 for January)? I read through the `datetime` module documentation and the Pandas documentation of their datetime functions, which ought to be relevant, but I could not find a function that solves thi...
It's a simple mapping function that needs to convert: ``` 1 2 3 4 5 6 7 8 9 10 11 12 | V 1 1 1 4 4 4 7 7 7 10 10 10 ``` This can be done in a number of ways with integral calculations, two of which are: ``` def firstMonthInQuarter(month): return (month - 1) // 3 * 3 + 1 ``` and: ``` def f...
What's a good strategy to find mixed types in Pandas columns?
29,376,026
3
2015-03-31T18:39:34Z
29,376,221
8
2015-03-31T18:49:41Z
[ "python", "pandas" ]
Ever so often I get this warning when parsing data files: ``` WARNING:py.warnings:/usr/local/python3/miniconda/lib/python3.4/site- packages/pandas-0.16.0_12_gdcc7431-py3.4-linux-x86_64.egg/pandas /io/parsers.py:1164: DtypeWarning: Columns (0,2,14,20) have mixed types. Specify dtype option on import or set low_memory=...
I'm not entirely sure what you're after, but it's easy enough to find the rows which contain elements which don't share the type of the first row. For example: ``` >>> df = pd.DataFrame({"A": np.arange(500), "B": np.arange(500.0)}) >>> df.loc[321, "A"] = "Fred" >>> df.loc[325, "B"] = True >>> weird = (df.applymap(type...
How to save S3 object to a file using boto3
29,378,763
36
2015-03-31T21:17:58Z
29,636,604
69
2015-04-14T20:15:44Z
[ "python", "amazon-web-services", "boto", "boto3" ]
I'm trying to do a "hello world" with new [boto3](https://github.com/boto/boto3) client for AWS. The use-case I have is fairly simple: get object from S3 and save it to the file. In boto 2.X I would do it like this: ``` import boto key = boto.connect_s3().get_bucket('foo').get_key('foo') key.get_contents_to_filename...
There is a customization that went into Boto3 recently which helps with this (among other things). It is currently exposed on the low-level S3 client, and can be used like this: ``` s3_client = boto3.client('s3') open('hello.txt').write('Hello, world!') # Upload the file to S3 s3_client.upload_file('hello.txt', 'MyBu...
How to save S3 object to a file using boto3
29,378,763
36
2015-03-31T21:17:58Z
35,367,531
17
2016-02-12T16:27:28Z
[ "python", "amazon-web-services", "boto", "boto3" ]
I'm trying to do a "hello world" with new [boto3](https://github.com/boto/boto3) client for AWS. The use-case I have is fairly simple: get object from S3 and save it to the file. In boto 2.X I would do it like this: ``` import boto key = boto.connect_s3().get_bucket('foo').get_key('foo') key.get_contents_to_filename...
boto3 now has a nicer interface than the client: ``` resource = boto3.resource('s3') my_bucket = resource.Bucket('MyBucket') my_bucket.download_file(key, local_filename) ``` This by itself isn't tremendously better than the `client` in the accepted answer (although the docs say that it does a better job retrying uplo...
aggregate a field in elasticsearch-dsl using python
29,380,198
3
2015-03-31T23:19:22Z
31,039,444
7
2015-06-25T00:45:21Z
[ "python", "elasticsearch", "elasticsearch-dsl" ]
Can someone tell me how to write Python statements that will aggregate (sum and count) stuff about my documents? --- SCRIPT ``` from datetime import datetime from elasticsearch_dsl import DocType, String, Date, Integer from elasticsearch_dsl.connections import connections from elasticsearch import Elasticsearch fro...
First of all. I notice now that what I wrote here, actually has no aggregations defined. The documentation on how to use this is not very readable for me. Using what I wrote above, I'll expand. I'm changing the index name to make for a nicer example. ``` from datetime import datetime from elasticsearch_dsl import DocT...
How to simulate HTML5 Drag and Drop in Selenium Webdriver?
29,381,233
5
2015-04-01T01:11:29Z
29,381,532
14
2015-04-01T01:48:11Z
[ "python", "html5", "selenium", "selenium-webdriver", "drag-and-drop" ]
I am using Python 2.7 and Selenium 2.44. I want to *automate drag and drop* action in Selenium WD but according to other related posts **Actions in HTML5 are not supported by Selenium** yet. Is there any way to simulate drag and drop in Python? Here is the code I tried: ``` driver = webdriver.Firefox() driver.get("h...
Yes, HTML5 "drag&drop" **is not currently supported** by Selenium: * [Issue 3604: HTML5 Drag and Drop with Selenium Webdriver](https://github.com/seleniumhq/selenium-google-code-issue-archive/issues/3604) One of the [suggested workarounds](http://elementalselenium.com/tips/39-drag-and-drop) is to *simulate HTML5 drag...
How to apply piecewise linear fit in Python?
29,382,903
9
2015-04-01T04:32:45Z
29,384,899
11
2015-04-01T07:11:02Z
[ "python", "numpy", "scipy", "curve-fitting", "piecewise" ]
I am trying to fit piecewise linear fit as shown in fig.1 for a data set ![enter image description here](http://i.stack.imgur.com/Thrit.png) This figure was obtained by setting on the lines. I attempted to apply a piecewise linear fit using the code: ``` from scipy import optimize import matplotlib.pyplot as plt imp...
You can use `numpy.piecewise()` to create the piecewise function and then use `curve_fit()`, Here is the code ``` from scipy import optimize import matplotlib.pyplot as plt import numpy as np x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ,11, 12, 13, 14, 15], dtype=float) y = np.array([5, 7, 9, 11, 13, 15, 28.92, 42.8...
How to get http headers in flask?
29,386,995
28
2015-04-01T09:16:56Z
29,387,151
42
2015-04-01T09:25:48Z
[ "python", "http", "flask", "http-headers", "authorization" ]
I am newbie to python and using Python Flask and generating REST API service. I want to check authorization header which is sent by angularjs. But I can't find way to get HTTP header in flask. Any help for getting HTTP header authorization is appreciated.
``` from flask import request request.headers.get('your-header-name') ``` `request.headers` is a dictionary, so you can also get your header like you would any dictionary: ``` request.headers['your-header-name'] ```
Does python iterate at a constant speed?
29,389,858
3
2015-04-01T11:42:06Z
29,389,945
10
2015-04-01T11:46:05Z
[ "python", "iteration", "gpio" ]
I writing some code to get sensor readings from GPIO against time. To make sure the measurements corresponds to a specific time, I want to know if python iterates at a constant speed (so that the gap between iterations is constant) - and what is its minimum time gap between iterations. If they're not, can someone let ...
No, Python does not and can not iterate at constant speed. Python is just another process on your Raspberry PI, and your OS is responsible for allocating it time to run on the CPU (called [multi-tasking](http://en.wikipedia.org/wiki/Computer_multitasking)). Other processes also get allotted time. This means Python is ...
Manually trigger Django email error report
29,392,281
20
2015-04-01T13:37:28Z
29,878,519
15
2015-04-26T13:54:50Z
[ "python", "django", "exception-handling", "django-email", "django-errors" ]
[Django error reporting](https://docs.djangoproject.com/en/1.7/howto/error-reporting/) handles uncaught exceptions by sending an email, and (optionally) shows user a nice 500 error page. This works very well, but in a few instances I'd like to allow users to continue with their business uninterrupted, but still have D...
You can use the following code to send manually an email about a `request` and an exception `e`: ``` import sys import traceback from django.core import mail from django.views.debug import ExceptionReporter def send_manually_exception_email(request, e): exc_info = sys.exc_info() reporter = ExceptionReporter(r...
SpooledTemporaryFile: units of maximum (in-memory) size?
29,393,847
5
2015-04-01T14:44:45Z
29,393,919
7
2015-04-01T14:47:58Z
[ "python", "temporary-files" ]
The parameter `max_size` of `tempfile.SpooledTemporaryFile()` is the maximum size of the temporary file that can fit in memory (before it is spilled to disk). What are the units of this parameter (bytes? kilobytes?)? The documentation (both for [Python 2.7](https://docs.python.org/2/library/tempfile.html#tempfile.Spool...
The size is in bytes. From the [`SpooledTemporaryFile()` source code](https://hg.python.org/cpython/file/d444496e714a/Lib/tempfile.py#l505): ``` def _check(self, file): if self._rolled: return max_size = self._max_size if max_size and file.tell() > max_size: self.rollover() ``` and `file.tell()` g...
Minimum of Numpy Array Ignoring Diagonal
29,394,377
4
2015-04-01T15:07:19Z
29,394,823
9
2015-04-01T15:26:35Z
[ "python", "numpy" ]
I have to find the maximum value of a numpy array ignoring the diagonal elements. np.amax() provides ways to find it ignoring specific axes. How can I achieve the same ignoring all the diagonal elements?
You could use a mask ``` mask = np.ones(a.shape, dtype=bool) np.fill_diagonal(mask, 0) max_value = a[mask].max() ``` where `a` is the matrix you want to find the max of. The mask selects the off-diagonal elements, so `a[mask]` will be a long vector of all the off-diagonal elements. Then you just take the max. Or, if...
Checking for duplicate lists at certain indices in a lists of lists
29,403,322
2
2015-04-02T00:51:52Z
29,403,380
7
2015-04-02T01:00:21Z
[ "python", "python-3.x" ]
Given a list of indices, how do I check if the lists at those indices in a list of lists are the same or not? ``` # Given: # indices = [0, 2, 3] # lsts = [['A', 'B'], ['1', '2', '3'], ['A', 'B'], ['B', 'C']] # would test if ['A', 'B'] == ['A', 'B'] == ['B', 'C'] # would return False # Given: # indices = [0, 2] # lsts...
This should do it: ``` >>> indices = [0, 2, 3] >>> lsts = [['A', 'B'], ['1', '2', '3'], ['A', 'B'], ['B', 'C']] >>> all(lsts[indices[0]] == lsts[i] for i in indices) False >>> indices = [0, 2] >>> lsts = [['A', 'B'], ['1', '2', '3'], ['A', 'B'], ['B', 'C']] >>> all(lsts[indices[0]] == lsts[i] for i in indices) True ``...
Python for loop and iterator behavior
29,403,401
35
2015-04-02T01:03:16Z
29,403,418
41
2015-04-02T01:06:06Z
[ "python", "iterator" ]
I wanted to understand a bit more about `iterators`, so please correct me if I'm wrong. An iterator is an object which has a pointer to the next object and is read as a buffer or stream (i.e. a linked list). They're particularly efficient cause all they do is tell you what is next by references instead of using indexi...
Your suspicion is correct: the iterator has been consumed. In actuality, your iterator is a [generator](https://wiki.python.org/moin/Generators), which is an object which has the ability to be iterated through *only once.* ``` type((i for i in range(5))) # says it's type generator def another_generator(): yield...
Python for loop and iterator behavior
29,403,401
35
2015-04-02T01:03:16Z
29,403,437
17
2015-04-02T01:09:51Z
[ "python", "iterator" ]
I wanted to understand a bit more about `iterators`, so please correct me if I'm wrong. An iterator is an object which has a pointer to the next object and is read as a buffer or stream (i.e. a linked list). They're particularly efficient cause all they do is tell you what is next by references instead of using indexi...
For loop basically calls the `next` method of an object that is applied to (`__next__` in Python 3). You can simulate this simply by doing: ``` iter = (i for i in range(5)) print(next(iter)) print(next(iter)) print(next(iter)) print(next(iter)) print(next(iter)) # this prints 1 2 3 4 ``` At this point there...
Can't convert len (x) into a usable int for string slicing?
29,403,827
2
2015-04-02T02:01:40Z
29,403,870
12
2015-04-02T02:07:04Z
[ "python" ]
I'm trying to write a function that takes a string and prints it normally, and then in reverse, like so: ``` string = "hello" mirror(string) 'helloolleh' ``` This is the code i have so far: ``` def mirror(x) : sentence = " " length = len(x) lengthstring = str(len(x)) l...
The error I get with your code is: ``` File "<stdin>", line 6, in mirror TypeError: string indices must be integers, not tuple ``` which says nothing about `len(x)`. In fact, it is referring to the line ``` sentence = x[lengthint, 0] ``` in which you are trying to index `x` using `lengthint, 0`. Python assume...
Python exponentiation order of operations and grouping
29,404,604
3
2015-04-02T03:41:04Z
29,404,645
10
2015-04-02T03:46:05Z
[ "python", "time", "operators", "exponentiation" ]
Simple question: Why does `(7**3) ** 24 % 25` take almost no time to run, but `7 ** 3 ** 24 % 25` not terminate?
Exponentiation groups [from right to left](https://docs.python.org/2/reference/expressions.html#operator-precedence). So, `7 ** 3 ** 24` is evaluated as `7 ** 282429536481` (hard), whereas `(7**3) ** 24` is just `343 ** 24` (easy). --- As an interesting sidenote: CPython, which has a peephole optimiser, is able to o...
How can I verify when a copy is made in Python?
29,411,707
3
2015-04-02T11:22:46Z
29,411,798
8
2015-04-02T11:27:15Z
[ "python", "arrays", "python-3.x", "numpy" ]
In Python 3.x, I'm working with large numpy arrays. I would like to have confirmation (without having to actually do some kind of experiment) that methods I have written are either working with a copy of the array OR are working with a direct reference to the array. I would like confirmation also that the array in que...
You can use [`np.ndarray.flags`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flags.html): ``` >>> a = np.arange(5) >>> a.flags C_CONTIGUOUS : True F_CONTIGUOUS : True OWNDATA : True WRITEABLE : True ALIGNED : True UPDATEIFCOPY : False ``` For example, you can set an array to not be w...
Pandas cumulative sum on column with condition
29,421,356
4
2015-04-02T19:54:18Z
29,421,580
8
2015-04-02T20:08:17Z
[ "python", "pandas", "dataframe" ]
I didn't found answer elsewhere, so I need to ask. Probably because I don't know how to correctly name it. (English is not my origin language) I have large datetime data frame. Time is important here. One column in df has values [Nan, 1, -1]. I need to perform quick calculation to have cumulative sum reseting when val...
see the last section [here](http://pandas.pydata.org/pandas-docs/stable/cookbook.html#grouping) This is an itertools like groupby ``` In [86]: v = df['value'].dropna() ``` The grouper is separated on the group breakpoints; cumsum makes it have separate groups ``` In [87]: grouper = (v!=v.shift()).cumsum() In [88]:...
How to count the number of occurences of `None` in a list?
29,422,691
4
2015-04-02T21:21:18Z
29,422,718
9
2015-04-02T21:23:22Z
[ "python", "boolean", "nonetype" ]
I'm trying to count things that are not `None`, but I want `False` and numeric zeros to be accepted too. Reversed logic: I want to count everything except what it's been explicitly declared as `None`. # Example Just the 5th element it's not included in the count: ``` >>> list = ['hey', 'what', 0, False, None, 14] >>...
Just use `sum` checking if each object `is not None` which will be `True` or `False` so 1 or 0. ``` lst = ['hey','what',0,False,None,14] print(sum(x is not None for x in lst)) ``` Or using `filter`: ``` print(len(filter(lambda x: x is not None, lst))) ``` The advantage of `sum` is it lazily evaluates an element at ...
Django setUpTestData() vs. setUp()
29,428,894
10
2015-04-03T08:37:18Z
29,442,551
9
2015-04-04T03:56:28Z
[ "python", "django", "unit-testing" ]
Django 1.8 shipped with [a refactored TestCase](https://docs.djangoproject.com/en/1.8/releases/1.8/#testcase-data-setup) which allows for data initialization at the class level using transactions and savepoints via the [setUpTestData()](https://docs.djangoproject.com/en/1.8/topics/testing/tools/#django.test.TestCase.se...
It's not uncommon for there to be set-up code that can't run as a class method. One notable example is the Django [test client](https://docs.djangoproject.com/en/1.8/topics/testing/tools/#the-test-client): you might not want to reuse the same client instance across tests that otherwise share much of the same data, and ...
Can't find the right energy using scipy.signal.welch
29,429,733
3
2015-04-03T09:41:15Z
33,251,324
8
2015-10-21T05:04:04Z
[ "python", "numpy", "signal-processing", "fft", "discrete-mathematics" ]
For a given discret time signal `x(t)` with spacing `dt` (which is equal to `1/fs`, `fs` being the sample rate), the energy is: ``` E[x(t)] = sum(abs(x)**2.0)/fs ``` Then I do a DFT of `x(t)`: ``` x_tf = np.fft.fftshift( np.fft.fft( x ) ) / ( fs * ( 2.0 * np.pi ) ** 0.5 ) ``` and compute the energy again: ``` E[x_...
The resolution to this apparent discrepancy lies in a careful understanding and application of * continuous vs. discrete Fourier transforms, and * energy, power, and power spectral density of a given signal I too have struggled with this exact question, so I will try to be as explicit as possible in the discussion be...
Correlation matrix using pandas
29,432,629
13
2015-04-03T12:57:22Z
29,432,741
27
2015-04-03T13:04:18Z
[ "python", "pandas", "matplotlib", "data-visualization", "information-visualization" ]
I have a data set with huge number of features, so analysing the correlation matrix has become very difficult. I want to plot a correlation matrix which we get using dataframe.corr() function from pandas library. Is there any inbuilt function provided by pandas library to plot this matrix?
You can use [`matshow()`](http://matplotlib.org/examples/pylab_examples/matshow.html) from matplotlib: `plt.matshow(dataframe.corr())`
Correlation matrix using pandas
29,432,629
13
2015-04-03T12:57:22Z
31,384,328
19
2015-07-13T13:10:12Z
[ "python", "pandas", "matplotlib", "data-visualization", "information-visualization" ]
I have a data set with huge number of features, so analysing the correlation matrix has become very difficult. I want to plot a correlation matrix which we get using dataframe.corr() function from pandas library. Is there any inbuilt function provided by pandas library to plot this matrix?
Try this function, which also displays variable names for the correlation matrix: ``` def plot_corr(df,size=10): '''Function plots a graphical correlation matrix for each pair of columns in the dataframe. Input: df: pandas DataFrame size: vertical and horizontal size of the plot''' corr =...
Convert a csv.DictReader object to a list of dictionaries?
29,432,912
4
2015-04-03T13:13:50Z
29,432,995
7
2015-04-03T13:19:19Z
[ "python", "csv", "dictionary" ]
A csv file `names.csv` has content: ``` first_name last_name Baked Beans Lovely Spam Wonderful Spam ``` I would like to read it into a list of dictionaries, with the first row containing the keys: ``` >>> import csv >>> with open('names.csv') as csvfile: ... reader = csv.DictReader(csvfile) ... for row in re...
``` import csv with open("in.csv") as csvfile: reader = csv.DictReader(csvfile,delimiter=" ") print(list(reader)) [{'first_name': 'Baked', 'last_name': 'Beans'}, {'first_name': 'Lovely', 'last_name': 'Spam'}, {'first_name': 'Wonderful', 'last_name': 'Spam'}] ``` If the delimiter is not actually a `,` you need ...
Token in query string with Django REST Framework's TokenAuthentication
29,433,416
2
2015-04-03T13:46:23Z
29,435,607
7
2015-04-03T16:00:58Z
[ "python", "django", "authentication", "django-rest-framework" ]
In an API built with [Django REST Framework](http://www.django-rest-framework.org/) authentication can be done using the TokenAuthentication method. Its [documentation](http://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication) says the authentication token should be sent via an `Authorization`...
By deafult DRF doesn't support query string to authenticate, but you can easily override their `authenticate` method in `TokenAuthentication` class to support it. An example would be: ``` class TokenAuthSupportQueryString(TokenAuthentication): """ Extend the TokenAuthentication class to support querystring authentica...
How to map a series of conditions as keys in a dictionary?
29,433,635
12
2015-04-03T14:01:01Z
29,433,705
15
2015-04-03T14:05:31Z
[ "python", "python-2.7", "dictionary", "lambda" ]
I know you can use a dictionary as an alternative to a switch statement such as the following: ``` def printMessage(mystring): # Switch statement without a dictionary if mystring == "helloworld": print "say hello" elif mystring == "byeworld": print "say bye" elif mystring == "goodaftern...
Your conditions are sequential in nature; you want to test one after the other, not map a small number of keys to a value here. Changing the order of the conditions could alter the outcome; a value of `5` results in `"greater than 0.5"` in your sample, not `"it is equal to 5"`. Use a list of tuples: ``` myconditions ...
Unable to "import matplotlib.pyplot as plt" in virtualenv
29,433,824
13
2015-04-03T14:11:37Z
33,447,513
9
2015-10-31T02:39:29Z
[ "python", "osx", "matplotlib", "flask", "virtualenv" ]
I am working with flask in a virtual environment. I was able to install matplotlib with pip, and I can `import matplotlib` in a Python session. However, when I import it as ``` matplotlib.pyplot as plt ``` I get the following error: ``` >>> import matplotlib.pyplot as plt Traceback (most recent call last): File "...
I had similar problem when I used pip to install matplotlib. By default, it installed the latest version which was 1.5.0. However, I had another virtual environment with Python 3.4 and matplotlib 1.4.3 and this environment worked fine when I imported matplotlib.pyplot. Therefore, I installed the earlier version of matp...
Unable to "import matplotlib.pyplot as plt" in virtualenv
29,433,824
13
2015-04-03T14:11:37Z
34,392,196
15
2015-12-21T09:13:15Z
[ "python", "osx", "matplotlib", "flask", "virtualenv" ]
I am working with flask in a virtual environment. I was able to install matplotlib with pip, and I can `import matplotlib` in a Python session. However, when I import it as ``` matplotlib.pyplot as plt ``` I get the following error: ``` >>> import matplotlib.pyplot as plt Traceback (most recent call last): File "...
I got the same error, and tried `Jonathan`'s answer: > You can fix this issue by using the backend Agg > > Go to `User/yourname/.matplotlib` and open/create `matplotlibrc` and add the following line `backend : Agg` and it should work for you. I run the program, no error, but also no plots, and I tried `backend: Qt4Ag...
Unable to "import matplotlib.pyplot as plt" in virtualenv
29,433,824
13
2015-04-03T14:11:37Z
35,107,136
25
2016-01-30T21:09:05Z
[ "python", "osx", "matplotlib", "flask", "virtualenv" ]
I am working with flask in a virtual environment. I was able to install matplotlib with pip, and I can `import matplotlib` in a Python session. However, when I import it as ``` matplotlib.pyplot as plt ``` I get the following error: ``` >>> import matplotlib.pyplot as plt Traceback (most recent call last): File "...
This [solution](http://stackoverflow.com/questions/21784641/installation-issue-with-matplotlib-python) worked for me. If you already installed matplotlib using pip on your virtual environment, you can just type the following: ``` $ cd ~/.matplotlib $ nano matplotlibrc ``` And then, write `backend: TkAgg` in there. If...
Error in Tumblelog Application development using Flask and MongoEngine
29,434,854
9
2015-04-03T15:12:16Z
29,477,297
18
2015-04-06T18:32:52Z
[ "python", "mongodb", "python-2.7", "flask" ]
I am trying to follow below tutorial but I am facing few issue, when i run manage.py. Any help could be great help. <http://docs.mongodb.org/ecosystem/tutorial/write-a-tumblelog-application-with-flask-mongoengine/#id1> manage.py run output: ``` (Tumbler)afiz Tumbler $ python manage.py Traceback (most recent call l...
I had the same problem as you are facing now. In models.py file I just wrote > class Comment(db.EmbeddedDocument): and it's content first then added > class Post(db.Document): and then it's content. In other words, I first wrote Comment class then Post class and problem got solved ;) :) Cheers!!
Bokeh Plotting: Enable tooltips for only some glyphs
29,435,200
8
2015-04-03T15:35:04Z
32,116,970
7
2015-08-20T11:25:17Z
[ "python", "plot", "hover", "tooltip", "bokeh" ]
I have a figure with some glyphs, but only want tooltips to display for certain glyphs. Is there currently a way to accomplish this in Bokeh? Alternatively, is there a way to plot two figures on top of each other? It seems like that would let me accomplish what I want to do.
Thanks to this page in Google Groups I figured out how this can be done. [Link here](https://www.google.co.uk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=4&cad=rja&uact=8&ved=0CDIQFjADahUKEwiMj_m6u7fHAhUDNj4KHTfEBww&url=https%3A%2F%2Fgroups.google.com%2Fa%2Fcontinuum.io%2Fd%2Ftopic%2Fbokeh%2FDg4oNVlwuDw&ei=jK3VVYyZA4Ps-AG3i...
Stratified Train/Test-split in scikit-learn
29,438,265
6
2015-04-03T19:11:22Z
29,477,256
20
2015-04-06T18:30:36Z
[ "python", "scikit-learn" ]
I need to split my data into a training set (75%) and test set (25%). I currently do that with the code below: ``` X, Xt, userInfo, userInfo_train = sklearn.cross_validation.train_test_split(X, userInfo) ``` However, I'd like to stratify my training dataset. How do I do that? I've been looking into the `StratifiedKFo...
[update for 0.17] ``` X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y) ``` [/update for 0.17] There is a pull request [here](https://github.com/scikit-learn/scikit-learn/pull/4438). But you can simply do `train, test = next(iter(StratifiedKFold(...)))` and use the train and test indices if you w...
How to create a pivot table on extremely large dataframes in Pandas
29,439,589
7
2015-04-03T20:58:52Z
29,439,946
8
2015-04-03T21:27:53Z
[ "python", "python-3.x", "pandas", "pivot-table" ]
I need to create a pivot table of 2000 columns by around 30-50 million rows from a dataset of around 60 million rows. I've tried pivoting in chunks of 100,000 rows, and that works, but when I try to recombine the DataFrames by doing a .append() followed by .groupby('someKey').sum(), all my memory is taken up and python...
You could do the appending with HDF5/pytables. This keeps it out of RAM. Use the [table format](http://pandas.pydata.org/pandas-docs/dev/io.html#table-format): ``` store = pd.HDFStore('store.h5') for ...: ... chunk # the chunk of the DataFrame (which you want to append) store.append('df', chunk) ``` Now...
How to install lxml on Windows
29,440,482
5
2015-04-03T22:24:35Z
29,441,115
8
2015-04-03T23:35:23Z
[ "python", "windows", "python-3.x", "pip", "lxml" ]
I'm trying to install `lmxl` on my Windows 8.1 laptop with Python 3.4 and failing miserably. First off, I tried the simple and obvious solution: `pip install lxml`. However, this didn't work. Here's what it said: ``` Downloading/unpacking lxml Running setup.py (path:C:\Users\CARTE_~1\AppData\Local\Temp\pip_build_ca...
First, following the comments, I downloaded the `lxml-3.4.2-cp34-none-win_amd64.whl` file and tried to open it with a `pip install`, but it just told me it wasn't a valid wheel file on my system or something. Then, I downloaded the `win_32` file and it worked! Maybe it's because I have an Intel processor and AMD64 is,...
What is the theorical foundation for scikit-learn dummy classifier?
29,441,943
6
2015-04-04T02:00:27Z
29,442,397
9
2015-04-04T03:25:41Z
[ "python", "machine-learning", "artificial-intelligence", "scikit-learn", "svm" ]
By the [documentation](http://scikit-learn.org/stable/modules/generated/sklearn.dummy.DummyClassifier.html) I read that a dummy classifier can be used to test it against a classification algorithm. > This classifier is useful as a simple baseline to compare with other > (real) classifiers. Do not use it for real probl...
The dummy classifier gives you a measure of "baseline" performance--i.e. the success rate one should expect to achieve even if simply guessing. Suppose you wish to determine whether a given object possesses or does not possess a certain property. If you have analyzed a large number of those objects and have found that...
Autocommit Migration from Django 1.7 to 1.8
29,443,216
9
2015-04-04T05:46:19Z
29,444,039
11
2015-04-04T07:53:19Z
[ "python", "django" ]
I was migrating from Django 1.7 to 1.8 via following steps 1. Active virtualenv 2. Uninstall Django 1.7 3. Install Django 1.8 4. python manage.py runserver On execution of step 4 for I am getting the following error. ``` Unhandled exception in thread started by <function wrapper at 0x7f4e473a8230> Traceback (most re...
The following was outlined in the [Django 1.7 Databases docs](https://docs.djangoproject.com/en/1.7/ref/databases/#autocommit-mode): > In previous versions of Django, database-level autocommit could be enabled by setting the autocommit key in the OPTIONS part of your database configuration in DATABASES. > > Since Djan...
How to create equal spaced values in between unequal spaced values in Python?
29,444,666
4
2015-04-04T09:14:08Z
29,444,822
7
2015-04-04T09:33:00Z
[ "python", "arrays", "numpy", "scipy" ]
I have an array A (*variable*) of the form: ``` A = [1, 3, 7, 9, 15, 20, 24] ``` Now I want to create 10 (*variable*) equally spaced values in between values of array A so that I get array B of the form: ``` B = [1, 1.2, 1.4, ... 2.8, 3, 3.4, 3.8, ... , 6.6, 7, 7.2, ..., 23.6, 24] ``` In essence B should always hav...
Alternative method using [interpolation](http://docs.scipy.org/doc/numpy/reference/generated/numpy.interp.html) instead of concatenation: ``` n = 10 x = np.arange(0, n * len(A), n) # 0, 10, .., 50, 60 xx = np.arange((len(A) - 1) * n + 1) # 0, 1, .., 59, 60 B = np.interp(xx, x, A) ``` Result: ``` In [31]: B Ou...
Easier way to write conditional statement
29,449,985
3
2015-04-04T18:30:21Z
29,450,002
11
2015-04-04T18:31:50Z
[ "python", "if-statement", "condition" ]
Is there any prettier way to write this if-statement: ``` if not (self.is_legal(l) or self.is_legal(u) or self.is_legal(r) or self.is_legal(d)): ``` I've tried this, but it didn't work. ``` if not self.is_legal(l or r or d or u): ``` Or maybe the first one is the prettiest?
You can use [`any`](https://docs.python.org/3/library/functions.html#any) and a [generator expression](https://docs.python.org/3/reference/expressions.html#grammar-token-generator_expression): ``` if not any(self.is_legal(x) for x in (l, u, r, d)): ``` Or, if you prefer [`all`](https://docs.python.org/3/library/funct...
Python: Why Does str.split() Return a list While str.partition() Returns a tuple?
29,451,794
5
2015-04-04T21:53:23Z
29,451,831
8
2015-04-04T21:56:47Z
[ "python" ]
Comparing Python's `str.split()` with `str.partition()`, I see that they not only have different functions (`split()` tokenizes the whole string at each occurrence of the delimiter, while `partition()` just returns everything before and everything after the first delimiter occurrence), but that they also have different...
The key difference between those methods is that `split()` returns a variable number of results, and `partition()` returns a fixed number. Tuples are usually not used for APIs which return a variable number of items.
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty
29,455,057
3
2015-04-05T07:19:26Z
29,455,099
11
2015-04-05T07:28:22Z
[ "python", "django" ]
I created a new project in django and pasted some files from another project. Whenever I try to run the server, I get the following error message: ``` Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Library/Python/2.7/site-pac...
Just like the error says, you have no `SECRET_KEY` defined. You need to add one to your **settings.py**. > Django will refuse to start if `SECRET_KEY` is not set. You can read more about this setting [in the docs](https://docs.djangoproject.com/en/1.7/ref/settings/#std:setting-SECRET_KEY). The `SECRET_KEY` can be ju...
unicode string equivalent of contain
29,456,800
6
2015-04-05T11:31:07Z
29,456,847
7
2015-04-05T11:36:58Z
[ "python", "string", "unicode" ]
I have an error when trying to use contain in python. ``` s = u"some utf8 words" k = u"one utf8 word" if s.contains(k): print "contains" ``` How do i achieve the same result? Example with normal ASCII string ``` s = "haha i am going home" k = "haha" if s.contains(k): print "contains" ``` I am using pytho...
The same for ascii and utf8 strings: ``` if k in s: print "contains" ``` There is no `contains()` on either ascii or uft8 strings: ``` >>> "strrtinggg".contains AttributeError: 'str' object has no attribute 'contains' ``` --- What you can use instead of `contains` is `find` or `index`: ``` if k.find(s) > -1: ...
Checking if string is only letters and spaces - Python
29,460,405
2
2015-04-05T17:55:27Z
29,460,426
8
2015-04-05T17:57:51Z
[ "python", "contain" ]
Trying to get python to return that a string contains ONLY alphabetic letters AND spaces ``` string = input("Enter a string: ") if all(x.isalpha() and x.isspace() for x in string): print("Only alphabetical letters and spaces: yes") else: print("Only alphabetical letters and spaces: no") ``` I've been trying ...
A character cannot be both an alpha **and** a space. It can be an alpha **or** a space. To require that the string contains only alphas and spaces: ``` string = input("Enter a string: ") if all(x.isalpha() or x.isspace() for x in string): print("Only alphabetical letters and spaces: yes") else: print("Only a...
Compare Python Pandas DataFrames for matching rows
29,464,234
8
2015-04-06T01:30:50Z
29,464,365
13
2015-04-06T01:54:35Z
[ "python", "pandas", "rows", "matching" ]
I have this DataFrame (`df1`) in Pandas: ``` df1 = pd.DataFrame(np.random.rand(10,4),columns=list('ABCD')) print df1 A B C D 0.860379 0.726956 0.394529 0.833217 0.014180 0.813828 0.559891 0.339647 0.782838 0.698993 0.551252 0.361034 0.833370 0.982056 0.741821 0.006864 0.8559...
One possible solution to your problem would be to use [merge](http://pandas.pydata.org/pandas-docs/version/0.15.2/merging.html). Checking if any row (all columns) from another dataframe (df2) are present in df1 is equivalent to determining the intersection of the the two dataframes. This can be accomplished using the f...
Memory error while using pip install Matplotlib
29,466,663
16
2015-04-06T06:47:11Z
29,467,260
10
2015-04-06T07:36:33Z
[ "python", "matplotlib" ]
I am using Python 2.7, If i try to install Matplotlib I am getting this error if i use "pip install matplotlib" ``` Exception: Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 232, in main status = self.run(options, args) File "/usr/local/lib/py...
It seems that you have insufficient RAM to build matplotlib from scratch. To overcome that, either turn on swap: ``` # create swap file of 512 MB dd if=/dev/zero of=/swapfile bs=1024 count=524288 # modify permissions chown root:root /swapfile chmod 0600 /swapfile # setup swap area mkswap /swapfile # turn swap on swapo...
Memory error while using pip install Matplotlib
29,466,663
16
2015-04-06T06:47:11Z
31,526,029
36
2015-07-20T20:46:26Z
[ "python", "matplotlib" ]
I am using Python 2.7, If i try to install Matplotlib I am getting this error if i use "pip install matplotlib" ``` Exception: Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 232, in main status = self.run(options, args) File "/usr/local/lib/py...
This error is coming up because, it seems, pip's caching mechanism is trying to read the entire file into memory before caching it… which poses a problem in a limited-memory environent, as matplotlib is ~50mb. A simpler solution, until pip is patched to use a constant-space caching algorithm, is to run `pip` with `-...
Generating random ID from list - jinja
29,472,403
3
2015-04-06T13:38:12Z
29,472,684
9
2015-04-06T13:54:54Z
[ "python", "random", "jinja2" ]
I am trying to generate a random ID from a list of contacts (in Python, with jinja2) to display in an HTML template. So I have a list of contacts, and for the moment I display all of them in a few cells in my HTML template by looping through the list of contacts: ``` # for contact_db in contact_dbs <tr> <td...
There is a `random` filter in `jinja2`. > **random(seq)** > > Return a random item from the sequence. Use it like this: ``` {% set selected_contact = contact_dbs|random %} ``` note: I assumed `contact_dbs` is `iterable`.
Python method available for both instantiated/uninstantiated class
29,473,131
4
2015-04-06T14:20:11Z
29,473,221
7
2015-04-06T14:25:30Z
[ "python", "methods", "class-method" ]
I have a class which fetches details and populates the class with information if it's instantiated already with an `id` using a `details` method. If it's not instantiated yet I want it to instead use an argument passed into `details` as the `id` and return a new instantiated object. Something like the following: ``` f...
You'll have to create your own descriptor to handle this; it'll have to bind to the class if no instance is available, otherwise to the instance: ``` class class_or_instance_method(object): def __init__(self, func): self.func = func def __get__(self, instance, cls=None): if instance is None: ...