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 simulate HTTP post request using Python Requests module?
13,147,914
8
2012-10-30T21:35:32Z
16,240,784
7
2013-04-26T16:10:26Z
[ "python", "forms", "post", "python-requests" ]
[This](http://docs.python-requests.org/en/latest/) is the module that I'm trying to use and there is a form I'm trying to fill automatically. The reason I'd like to use Requests over Mechanize is because with Mechanize, I have to load the login page first before I can fill it out and submit, whereas with Requests, I ca...
In order to use authentication within a requests get or post function you just supply the `auth` argument. Like this: `response = requests.get(url, auth = ('username', 'password'))` Refer to the Requests [Authentication Documentation](http://docs.python-requests.org/en/latest/user/authentication/) for more detailed in...
How to change the order of DataFrame columns?
13,148,429
168
2012-10-30T22:22:59Z
13,148,611
255
2012-10-30T22:38:49Z
[ "python", "pandas" ]
I have the following `DataFrame` (`df`): ``` import numpy as np import pandas as pd df = pd.DataFrame(np.random.rand(10, 5)) ``` I add more column(s) by assignment: ``` df['mean'] = df.mean(1) ``` How can I move the column `mean` to the front, i.e. set it as first column leaving the order of the other columns unto...
One easy way would be to reassign the dataframe with a list of the columns, rearranged as needed. This is what you have now: ``` In [6]: df Out[6]: 0 1 2 3 4 mean 0 0.445598 0.173835 0.343415 0.682252 0.582616 0.445543 1 0.881592 0.696942 0.702232 0.696724 0.3...
How to change the order of DataFrame columns?
13,148,429
168
2012-10-30T22:22:59Z
13,316,001
34
2012-11-09T21:04:03Z
[ "python", "pandas" ]
I have the following `DataFrame` (`df`): ``` import numpy as np import pandas as pd df = pd.DataFrame(np.random.rand(10, 5)) ``` I add more column(s) by assignment: ``` df['mean'] = df.mean(1) ``` How can I move the column `mean` to the front, i.e. set it as first column leaving the order of the other columns unto...
How about: ``` df.insert(0, 'mean', df.mean(1)) ``` <http://pandas.pydata.org/pandas-docs/stable/dsintro.html#column-selection-addition-deletion>
How to change the order of DataFrame columns?
13,148,429
168
2012-10-30T22:22:59Z
23,741,480
51
2014-05-19T15:20:33Z
[ "python", "pandas" ]
I have the following `DataFrame` (`df`): ``` import numpy as np import pandas as pd df = pd.DataFrame(np.random.rand(10, 5)) ``` I add more column(s) by assignment: ``` df['mean'] = df.mean(1) ``` How can I move the column `mean` to the front, i.e. set it as first column leaving the order of the other columns unto...
You could also do something like this: ``` df = df[['mean', '0', '1', '2', '3']] ``` You can get the list of columns with: ``` cols = list(df.columns.values) ``` The output will produce: ``` ['0', '1', '2', '3', 'mean'] ``` ...which is then easy to rearrange manually before dropping it into the first function
How to change the order of DataFrame columns?
13,148,429
168
2012-10-30T22:22:59Z
29,922,207
19
2015-04-28T14:19:49Z
[ "python", "pandas" ]
I have the following `DataFrame` (`df`): ``` import numpy as np import pandas as pd df = pd.DataFrame(np.random.rand(10, 5)) ``` I add more column(s) by assignment: ``` df['mean'] = df.mean(1) ``` How can I move the column `mean` to the front, i.e. set it as first column leaving the order of the other columns unto...
Just assign the column names in the order you want them, to `<dataframe>.columns` like below: ``` In [39]: df Out[39]: 0 1 2 3 4 mean 0 0.172742 0.915661 0.043387 0.712833 0.190717 1 1 0.128186 0.424771 0.590779 0.771080 0.617472 1 2 0.125709 0.085894 0....
How to change the order of DataFrame columns?
13,148,429
168
2012-10-30T22:22:59Z
32,131,398
8
2015-08-21T02:18:52Z
[ "python", "pandas" ]
I have the following `DataFrame` (`df`): ``` import numpy as np import pandas as pd df = pd.DataFrame(np.random.rand(10, 5)) ``` I add more column(s) by assignment: ``` df['mean'] = df.mean(1) ``` How can I move the column `mean` to the front, i.e. set it as first column leaving the order of the other columns unto...
You need to create a new list of your columns in the desired order, then use `df = df[cols]` to rearrange the columns in this new order. ``` cols = ['mean'] + [col for col in df if col != 'mean'] df = df[cols] ``` You can also use a more general approach. In this example, the last column (indicated by -1) is inserte...
Removing last element of a list in Python fails
13,148,565
4
2012-10-30T22:35:06Z
13,148,660
11
2012-10-30T22:42:56Z
[ "python", "list", "dictionary" ]
I'm trying to remove the last element of a list in Python: ``` di = {"a": 3, "children": [{"b": 5}, {"c": 6}]} for el in di['children']: di['children'].remove(el) ``` What I'd expect is ``` print di {'a': 3, 'children: []} ``` But what I get is ``` print di {'a': 3, 'children': [{'c': 6}]} ``` Does anybody have...
As everyone else has explained, you can't modify a list while iterating over it. You can modify a list while iterating over a copy of it, but it's probably better to just generate a new filtered list: ``` di = {"a": 3, "children": [{"b": 5}, {"c": 6}]} di['children'] = [el for el in di['children'] if el not in di['ch...
Histogram of an Image's "Black Ink Level" by Horizontal Axis
13,148,835
8
2012-10-30T23:00:22Z
13,150,000
11
2012-10-31T01:25:00Z
[ "python", "linux", "image-processing", "imagemagick", "gnuplot" ]
I have a black and white image (or pdf) file, and want to get a histogram of the image's horizontal profile. That is, for each column in the image I want the sum of the grayscale values of the pixels in the column. If the image is X by Y pixels, I will end up with X numbers between 0 (for an entirely black column) and ...
I will give an answer in two acts, using two of my favorite free utilities: python and gnuplot. As a fellow (computational) graduate student, my advice is that if you want to do things for free python is one of the most versatile tools you can learn to use. Here's a python script that does the first part, counting th...
ipython: re-importing modules when using %run
13,150,259
18
2012-10-31T02:03:30Z
13,150,712
11
2012-10-31T03:07:31Z
[ "python", "import", "module", "ipython" ]
I love ipython, but I've discovered a problem with %run: imported modules are not reloaded when %run is called repeatedly. Suppose file ex1.py contains the lines: ``` import ex2 ex2.x.append(1) print ex2.x ``` And file ex2.py contains: ``` x = [] ``` Now, running python ex1.py from the command line repeatedly prin...
`%run ex1.py` (or any script for that matter) does not do deep reload of your imported module even with the autoreload extension set to 2. It is a "flaw" with how the `%run` command works in ipython. You will have to explicitly call ``` dreload(ex2) ``` for a deep reload before executing `%run ex1.py` again. See - ...
ipython: re-importing modules when using %run
13,150,259
18
2012-10-31T02:03:30Z
20,053,507
7
2013-11-18T17:04:41Z
[ "python", "import", "module", "ipython" ]
I love ipython, but I've discovered a problem with %run: imported modules are not reloaded when %run is called repeatedly. Suppose file ex1.py contains the lines: ``` import ex2 ex2.x.append(1) print ex2.x ``` And file ex2.py contains: ``` x = [] ``` Now, running python ex1.py from the command line repeatedly prin...
I am encountering the same problem. It seems to me this is an undesirable effect of ipython's run command - it doesn't reload imported modules. The author is right: If changes have been made to ex2.py, the following command will help reload ``` %load_ext autoreload %autoreload 2 ``` My simplest way to get around is ...
Automatically add key to Python dict
13,151,276
4
2012-10-31T04:28:05Z
13,151,294
22
2012-10-31T04:30:17Z
[ "python" ]
I want to automatically add keys to a Python dictionary if they don't exist already. For example, ``` a = "a" b = "b" c = "c" dict = {} dict[a][b] = c # doesn't work because dict[a] doesn't exist ``` How do I automatically create keys if they don't exist?
Use a [`collections.defaultdict`](http://docs.python.org/2/library/collections.html#collections.defaultdict): ``` def recursively_default_dict(): return collections.defaultdict(recursively_default_dict) my_dict = recursively_default_dict() my_dict['a']['b'] = 'c' ```
matplotlib plot window won't appear
13,151,514
7
2012-10-31T04:59:10Z
13,155,030
12
2012-10-31T09:40:42Z
[ "python", "plot", "matplotlib", "64bit", "pandas" ]
I'm using Python 2.7.3 in 64-bit. I installed pandas as well as matplotlib 1.1.1, both for 64-bit. Right now, none of my plots are showing. After attempting to plot from several different dataframes, I gave up in frustration and tried the following first example from <http://pandas.pydata.org/pandas-docs/dev/visualizat...
I'm not convinced this is a pandas issue at all. Does ``` import matplotlib.pyplot as plt plt.plot(range(10)) plt.show() ``` bring up a plot? If not: How did you install matplotlib? Was it from source or did you install it from a package manager/pre-built binary? I suspect that if you run: ``` import matplotlib ...
Remapping key names in a list of dictionaries
13,151,785
5
2012-10-31T05:30:16Z
13,151,881
7
2012-10-31T05:42:39Z
[ "python" ]
What is a pythonic way to remap each dictionary key in a list of identically-keyed dictionaries to different key names? E.g., ``` [{'type_id': 6, 'type_name': 'Type 1'}, {'type_id': 12, 'type_name': 'Type 2'}] ``` must transform into ``` [{'type': 6, 'name': 'Type 1'}, {'type': 12, 'name': 'Type 2'}] ``` (I need to...
Python >= 2.7 (using a [dict comprehension](http://www.python.org/dev/peps/pep-0274/)): ``` transform = {"type_id": "type", "type_name": "name"} new_list = [{transform[k]: v for k, v in d.items()} for d in old_list] ``` Python >= 2.4 (using the [dict](http://docs.python.org/2/library/stdtypes.html#dict) constructor):...
Is there a compact equivalent to Python range() in C++/STL
13,152,252
31
2012-10-31T06:16:16Z
13,152,274
43
2012-10-31T06:17:52Z
[ "c++", "python" ]
How can I do the equivalent of the following using C++/STL? I want to fill a `std::vector` with a range of values [min, max). ``` # Python >>> x = range(0, 10) >>> x [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ``` I suppose I could use `std::generate_n` and provide a functor to generate the sequence, but I was wondering if there ...
In C++11, there's `std::iota`: ``` std::vector<int> x(10); std::iota(std::begin(x), std::end(x), 0); //0 is the starting number ```
Is there a compact equivalent to Python range() in C++/STL
13,152,252
31
2012-10-31T06:16:16Z
13,152,323
17
2012-10-31T06:21:39Z
[ "c++", "python" ]
How can I do the equivalent of the following using C++/STL? I want to fill a `std::vector` with a range of values [min, max). ``` # Python >>> x = range(0, 10) >>> x [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ``` I suppose I could use `std::generate_n` and provide a functor to generate the sequence, but I was wondering if there ...
There is [boost::irange](http://www.boost.org/doc/libs/release/libs/range/doc/html/range/reference/ranges/irange.html): ``` std::vector<int> x; boost::push_back(x, boost::irange(0, 10)); ```
Strong numbers in python
13,152,364
2
2012-10-31T06:25:33Z
13,152,460
7
2012-10-31T06:33:38Z
[ "python", "algorithm", "python-3.x" ]
A number is strong number if the sum of the factorials of the individual digits is equal to the number itself. For example: 145 = 1! + 4! +5! I wrote the following code in python for this: ``` import math def strong_num(): return [x for x in range(1,1000) if x==int(reduce(lambda p,q:math.factorial(int(p))+math.fa...
Your `reduce` input is wrong, the you shouldn't compute the factorial of `p`. In fact, it is easier to just use `sum`: ``` return [x for x in range(1, 1000) if x == sum(math.factorial(int(q)) for q in str(x))] ``` --- The [`functools.reduce`](http://docs.python.org/3/library/functools.html#functools.reduc...
How to return multiple strings from a script to the rule sequence in booggie 2?
13,153,506
3
2012-10-31T07:58:03Z
13,153,832
7
2012-10-31T08:23:27Z
[ "python", "booggie" ]
This is an issue specific to the use of python scripts in booggie 2. I want to return multiple strings to the sequence and store them there in variables. The script should look like this: ``` def getConfiguration(config_id): """ Signature: getConfiguration(int): string, string""" return "string_1", "string...
Scripts in booggie 2 are restricted to a single return value. But you can return an array which then contains your strings. Sadly Python arrays are different from GrGen arrays so we need to convert them first. So your example would look like this: ``` def getConfiguration(config_id): """ Signature: getConfigurat...
Split words in a nested list into letters
13,154,748
4
2012-10-31T09:25:06Z
13,154,766
9
2012-10-31T09:26:26Z
[ "python" ]
I was wondering how I can split words in a nested list into their individual letters such that ``` [['ANTT'],['XSOB']] ``` becomes ``` [['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']] ```
A list comprehension: ``` [list(l[0]) for l in mylist] ``` Demo: ``` >>> mylist = [['ANTT'],['XSOB']] >>> [list(l[0]) for l in mylist] [['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']] ```
reorder byte order in hex string (python)
13,155,570
4
2012-10-31T10:10:52Z
13,155,805
12
2012-10-31T10:25:32Z
[ "python", "string", "hex", "swap", "python-2.x" ]
I want to build a small formatter in python giving me back the numeric values embedded in lines of hex strings. It is a central part of my formatter and should be reasonable fast to format more than 100 lines/sec (each line about ~100 chars). The code below should give an example where I'm currently blocked. 'data\_...
`array.arrays` have a [byteswap method](http://docs.python.org/2/library/array.html#array.array.byteswap): ``` import binascii import struct import array x = binascii.unhexlify('b62e000052e366667a66408d') y = array.array('h', x) y.byteswap() s = struct.Struct('<Id') print(s.unpack_from(y)) # (46638, 943.29999999943...
How to prevent pycallgraph from entering standard library functions?
13,155,735
14
2012-10-31T10:21:10Z
18,235,832
10
2013-08-14T15:25:06Z
[ "python", "profiling" ]
I'm using [pycallgraph](http://pycallgraph.slowchop.com/) from the command line to profile and draw the call graph of a relatively simple program. However, the resulting image includes the internals of standard libraries (threading, json, socket) even though I don't use the -s command line option. Using the -e option t...
Pycallgraph provides filtering capabilities to filter out any module, class or function you would like to exclude from call graph. Following function should be defined before you start the trace and passed to pycallgraph Example ``` def filtercalls(call_stack, modul, clas, func, full): mod_ignore = ['shutil','sci...
How to understand the functional programming code for converting IP string to an integer?
13,156,216
5
2012-10-31T10:51:49Z
13,156,359
13
2012-10-31T10:58:58Z
[ "python", "functional-programming", "ip" ]
In a python discusion, I saw a function to convert IP string into an integer in functional progamming way. Here is [the Link](http://www.daniweb.com/software-development/python/code/282977/ip-number-conversion-between-dotnumber-string-and-integer) . The function is implemented in a single line. ``` def ipnumber(ip): ...
`sum` and `chunk` are arguments to the `lambda` function passed to `reduce`. `|` is the binary or operator. The thing works like this: * `ip.split(".")` returns a list of strings, each corresponding to a piece of the dotted string (`"192.168.0.1"` => `["192", "168", "0", "1"]`; * `map` applies its first operand to ea...
Python load json file with UTF-8 BOM header
13,156,395
18
2012-10-31T11:01:29Z
13,156,715
30
2012-10-31T11:20:32Z
[ "python", "json" ]
I needed to parse files generated by other tool, which unconditionally outputs json file with UTF-8 BOM header (EFBBBF). I soon found that this was the problem, as Python 2.7 module can't seem to parse it: ``` >>> import json >>> data = json.load(open('sample.json')) ValueError: No JSON object could be decoded ``` R...
You can open with `codecs`: ``` import json import codecs json.load(codecs.open('sample.json', 'r', 'utf-8-sig')) ``` or decode with `utf-8-sig` yourself and pass to `loads`: ``` json.loads(open('sample.json').read().decode('utf-8-sig')) ```
How to store itertools.chain and use it more than once?
13,156,518
4
2012-10-31T11:09:45Z
13,156,533
9
2012-10-31T11:10:51Z
[ "python", "memoization", "itertools" ]
I would like to use `itertools.chain` for efficient concatenation of lists (memoization), but I need to be able to read (or `map`, etc.) the result multiple times. This example illustrates the problem: ``` import itertools a = itertools.chain([1, 2], [3, 4]) print list(a) # => [1, 2, 3, 4] print list(a) # => [] ``` W...
As with all generators, you'll need to convert it to a list and store that result instead: ``` a = list(a) ``` This is a fundamental principle of generators, they are expected to produce their sequence only *once*. Moreover, you cannot simply store a generator for memoization purposes, as the underlying lists *could...
Making a histogram of string values in python
13,156,657
8
2012-10-31T11:16:35Z
13,157,233
14
2012-10-31T11:48:55Z
[ "python", "string", "histogram" ]
OK so I have six possible values for data to be which are '32', '22', '12', '31', '21' and '11'. I have these stored as strings. Is it possible for python to sort through the data and just make six bins and show how many of each I have? Or do the inputs to a histogram HAVE to be numerical?
``` data = ['32', '22', '12', '32', '22', '12', '31', '21', '11'] dict((x, data.count(x)) for x in data) ``` **Result** ``` {'11': 1, '12': 2, '21': 1, '22': 2, '31': 1, '32': 2} ```
2d array of zeros
13,157,961
10
2012-10-31T12:27:57Z
13,157,994
20
2012-10-31T12:29:52Z
[ "python" ]
There is no array type in python, but to emulate it we can use lists. I want to have 2d array-like structure filled in with zeros. My question is: what is the difference, if any, in this two expressions: ``` zeros = [[0 for i in xrange(M)] for j in xrange(M)] ``` and ``` zeros = [[0]*M]*N ``` Will `zeros` be same? ...
You should use `numpy.zeros`. If that isn't an option, you want the first version. In the second version, if you change one value, it will be changed elsewhere in the list -- e.g.: ``` >>> a = [[0]*10]*10 >>> a [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0...
Any built-in do the job `range(len(lst))`?
13,159,041
2
2012-10-31T13:25:30Z
13,159,084
11
2012-10-31T13:27:48Z
[ "python", "python-3.x" ]
I find myself often use something like ``` for i in range(len(lst1)): lst1[i] += lst2[i] ``` Is there a built-in equivalent to `range(len(.))`? (BTW, I use Python3.)
``` for i, e in enumerate(lst2): lst1[i] += e ``` or ``` lst1 = [e1 + e2 for e1, e2 in zip(lst1, lst2)] ```
Regular expression matching [^a-z] or $
13,159,426
3
2012-10-31T13:45:50Z
13,159,457
9
2012-10-31T13:46:59Z
[ "python", "regex" ]
I need some help with string regex matching a word in a sentence accounting for punctuation and the end of the line. My attempt fails for the end of line case. The following examples evaluate as I need: ``` >>> print bool(re.search('test[^a-z]','test!'.lower())) True >>> print bool(re.search('test[^a-z]','test aaa'.l...
You can use a negative [lookahead](http://www.regular-expressions.info/lookaround.html): ``` 'test(?![a-z])' ``` Or an [alternation](http://www.regular-expressions.info/alternation.html): ``` 'test([^a-z]|$)' ```
Using absolute unix paths in windows with python
13,162,372
14
2012-10-31T16:19:00Z
13,162,639
20
2012-10-31T16:34:42Z
[ "python", "windows", "unix", "path", "cross-platform" ]
I'm creating an application that stores blob files into the hard drive, but this script must run in both linux and windows, the issue is that i want to give it an absolute path from the filesystem root and not one relative to the project files, this because im using git and dont want to deal with excluding all these fi...
Use `os.path.abspath()`, and also `os.path.expanduser()` for files relative to the user's home directory: ``` print os.path.abspath("/var/lib/blob_files/myfile.blob") >>> C:\var\lib\blob_files\myfile.blob print os.path.abspath(os.path.expanduser("~/blob_files/myfile.blob")) >>> C:\Users\jerry\blob_files\myfile.blob `...
Why use Tornado and Flask together?
13,163,990
14
2012-10-31T17:59:43Z
13,164,246
25
2012-10-31T18:18:07Z
[ "python", "web", "webserver", "flask", "tornado" ]
As far as I can tell Tornado is a server and a framework in one. It seems to me that using Flask and Tornado together is like adding another abstraction layer (more overhead). Why do people use Flask and Tornado together, what are the advantages?
According to [this question](http://stackoverflow.com/questions/8143141/using-flask-and-tornado-together) it is because Flask is blocking and Tornado is non-blocking. If one uses [Tornado as a WSGI server and Flask for url routing + templates](http://flask.pocoo.org/docs/0.10/deploying/wsgi-standalone/#tornado) there ...
Why use Tornado and Flask together?
13,163,990
14
2012-10-31T17:59:43Z
13,169,217
10
2012-11-01T00:09:24Z
[ "python", "web", "webserver", "flask", "tornado" ]
As far as I can tell Tornado is a server and a framework in one. It seems to me that using Flask and Tornado together is like adding another abstraction layer (more overhead). Why do people use Flask and Tornado together, what are the advantages?
I always thought using Flask & Tornado together was stupid, but it actually does make sense. It adds complexity though; my preference would be to just use Tornado, but if you're attached to Flask, then this setup works. Flask is (reportedly) very nice to use, and simpler than Tornado. However, [Flask requires a WSGI s...
Pagination in Amazon DynamoDB using Boto
13,164,026
4
2012-10-31T18:01:47Z
13,164,275
7
2012-10-31T18:20:10Z
[ "python", "boto", "amazon-dynamodb" ]
How do I paginate my results from DynamoDB using the Boto python library? From the Boto API documentation, I can't figure out if it even has support for pagination, although the DynamoDB API does have pagination support.
Boto does have support for "pagination" like behavior using a combination of "ExclusiveStartKey" and "Limit". For example, to paginate `Scan`. Here is an example that should parse a whole table by chunks of 10 ``` esk = None while True: # load this batch scan_generator = MyTable.scan(max_results=10, exclusiv...
Python: Use of dict derived class - strange behavior of self={
13,164,218
2
2012-10-31T18:16:14Z
13,164,251
9
2012-10-31T18:18:26Z
[ "python", "class", "dictionary", "self" ]
What is the difference between class A and class B? What's wrong with self? Why do I need to declare self line by line? ``` class A(dict): def __init__(self): self={1:"you", 2:"and me"} print "inside of class A",self class B(dict): def __init__(self): self[1]="you" self[2]="and me" print "ins...
``` def __init__(self): self={1:"you", 2:"and me"} ``` This doesn't modify the object passed as `self`, but re-binds the local variable `self` to a new dict.
Fill input of type text and press submit using python
13,166,395
2
2012-10-31T19:48:38Z
13,167,289
8
2012-10-31T20:56:06Z
[ "python", "html", "python-2.7", "beautifulsoup" ]
I have this html: ``` <input type="text" class="txtSearch"> <input type="submit" value="Search" class="sbtSearch"> ``` What I need is to write in the text field and then click on submit using python. The input tags are not inside **Form**. How I could do that?
You shouldn't have to actually populate the fields and 'click' submit. You can simulate the submission and get the desired results. Use [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) and urllib alongside firebug in Firefox. Watch the network traffic with firebug, and get the post parameters from the HT...
Setting up default pylint config.rc file in Windows
13,166,550
4
2012-10-31T19:58:52Z
13,173,687
11
2012-11-01T08:48:57Z
[ "python", "windows", "pylint" ]
I'm using Pylint under Windows, and it's not reading my pylint-config.rc file. Is there a way to set up a default .rc file for Python within windows so that I don't have to keep typing it into the command line? Thanks.
I don't have a windows box at hand to test, but the code uses `os.path.expanduser('~')` to find the current user's home directory, and looks for a file calle `.pylintrc` in that directory. According to the [python documentation](http://docs.python.org/3/library/os.path.html?highlight=expanduser#os.path.expanduser), on...
How can I pull a remote repository with GitPython?
13,166,595
7
2012-10-31T20:01:32Z
13,166,781
13
2012-10-31T20:16:23Z
[ "python", "git", "gitpython" ]
I am trying to find the way to pull a git repository using gitPython. So far this is what I have taken from the official docs [here](http://gitpython.readthedocs.org/en/latest/tutorial.html#handling-remotes). ``` test_remote = repo.create_remote('test', 'git@server:repo.git') repo.delete_remote(test_remote) # create a...
I managed this by getting the repo name directly: ``` repo = git.Repo('repo_name') o = repo.remotes.origin o.pull() ```
Linear Interpolation using numpy.interp
13,166,914
3
2012-10-31T20:26:22Z
13,167,028
7
2012-10-31T20:34:01Z
[ "python", "numpy", "interpolation", "linear-interpolation" ]
I have a 1 dimensional array A of floats that is mostly good but a few of the values are missing. Missing data is replace with nan(not a number). I have to replace the missing values in the array by linear interpolation from the nearby good values. So, for example: ``` F7(np.array([10.,20.,nan,40.,50.,nan,30.])) ``` ...
You could use [`scipy.interpolate.interp1d`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html): ``` >>> from scipy.interpolate import interp1d >>> import numpy as np >>> x = np.array([10., 20., np.nan, 40., 50., np.nan, 30.]) >>> not_nan = np.logical_not(np.isnan(x)) >>> indices = np...
Changing pixel color Python
13,167,269
5
2012-10-31T20:54:23Z
13,167,379
8
2012-10-31T21:02:57Z
[ "python", "image-processing" ]
I am suppose to get an image from my fluke robot and determine the color of each pixel in my image. Then if the pixel is mostly red, change it to completely green. If the pixel is mostly green, change it to completely blue. If the pixel is mostly blue, change it to completely red. This is what I am able to do, but I ca...
I assume you're trying to use the `Image` module. Here's an example: ``` import Image picture = Image.open("/path/to/my/picture.jpg") r,g,b = picture.getpixel( (0,0) ) print("Red: {0}, Green: {1}, Blue: {2}".format(r,g,b)) ``` Running this on this [image](http://image.gsfc.nasa.gov/image/image_launch_a5.jpg) I get th...
Python Simple Swap Function
13,167,300
8
2012-10-31T20:57:22Z
13,167,345
16
2012-10-31T21:00:25Z
[ "python", "swap" ]
I came across this problem when attempting to learn python. Consider the following function: ``` def swap0(s1, s2): assert type(s1) == list and type(s2) == list tmp = s1[:] s1 = s2[:] s2 = tmp return s1 = [1] s2 = [2] swap0(s1, s2) print s1, s2 ``` What will s1 and s2 print? After running the proble...
It's because it assigns new values to `s1` and `s2` inside the `swap0` function. These assignments do not propagate outside the function. You'll see that it works if you just copy and paste the function body in the place of the function call. You can work around this by modifying the objects referenced by the argument...
Python Simple Swap Function
13,167,300
8
2012-10-31T20:57:22Z
13,167,371
8
2012-10-31T21:02:09Z
[ "python", "swap" ]
I came across this problem when attempting to learn python. Consider the following function: ``` def swap0(s1, s2): assert type(s1) == list and type(s2) == list tmp = s1[:] s1 = s2[:] s2 = tmp return s1 = [1] s2 = [2] swap0(s1, s2) print s1, s2 ``` What will s1 and s2 print? After running the proble...
As it is, your final `print` will print out the original values of `s1` and `s2`. This is because you're only swapping them within the scope of the function. Doing so will not affect their values outside the function (i.e. after their values after the function has been called) If they are mutable types (`list`, `set`,...
filtering grouped df in pandas
13,167,391
17
2012-10-31T21:03:56Z
18,261,958
15
2013-08-15T21:13:15Z
[ "python", "pandas" ]
I am creating a `groupby` object from a Pandas `DataFrame` and want to select out all the groups with > 1 size. The following doesn't seem to work: ``` grouped[grouped.size > 1 ] ``` Also, how can one filter out certain values from a grouped `DataFrame`? For example, how could I remove all the rows from `grouped` wh...
As of pandas 0.12 you can do: ``` >>> grouped.filter(lambda x: len(x) > 1) A B 0 foo 0 2 foo 2 3 foo 3 ```
Python raw_input() replacement that uses a configurable text editor
13,168,083
3
2012-10-31T22:00:56Z
13,168,243
8
2012-10-31T22:16:08Z
[ "python" ]
I'm trying to implement a replacement for raw\_input() that would use a configurable text editor like vim as the interface to to the user. The ideal workflow would be like this: 1. Your python script is running, and makes a call to my\_raw\_input(). 2. Vim (or emacs, or gedit, or any other text editor) opens w/ a bla...
You write the data to a temporary file, and then read it when the editor returns. If you run `git commit` you'll notice that git is doing the same thing. There is no extra step to starting a program interactively, as long as the child process has `stdin` and `stdout` wired to a terminal it will be interactive. There ...
Comparing elements between elements in two lists of tuples
13,168,252
4
2012-10-31T22:16:49Z
13,168,274
7
2012-10-31T22:18:30Z
[ "python" ]
Here is what I am looking to do.I have two list of tuples. Build a list of elements such that the first element in a tuple in list1 matches the first element in a tuple in list 2 ``` list1 = [('a', 2), ('b', 3), ('z', 5)] list2 = [('a', 1), ('b', 2), ('c', 3)] list3 = ['a','b'] ``` Note: There can be no duplicate f...
I'd use `zip()`: ``` In [25]: l1 = [('a', 2), ('b', 3), ('z', 5)] In [26]: l2 = [('a', 1), ('b', 2), ('c', 3)] In [27]: [x[0] for x,y in zip(l1,l2) if x[0]==y[0]] Out[27]: ['a', 'b'] ``` **EDIT:** After reading your comment above it looks like you're looking for something like this: ``` In [36]: [x[0] for x in l1 ...
Python argparse argument with quotes
13,168,666
4
2012-10-31T23:00:31Z
13,168,677
7
2012-10-31T23:01:55Z
[ "python", "argparse", "optparse" ]
Is there any way I can tell argparse to not eat quotation marks? For example, When I give an argument with quotes, argparse only takes what's inside of the quotes as the argument. I want to capture the quotation marks as well (without having to escape them on the command line.) ``` pbsnodes -x | xmlparse -t "interact...
I think it is the shell that eats them, so python will actually never see them. Escaping them on the command line may be your only option. If it's the `\"backslash\"` style escaping you don't like for some reason, then this way should work instead: ``` pbsnodes -x | xmlparse -t '"interactive-00"' ```
When I crop an image in Python, it returns 'NoneType'
13,170,514
2
2012-11-01T03:24:57Z
13,170,546
8
2012-11-01T03:29:43Z
[ "python", "python-imaging-library" ]
``` croppedImage = image.crop(200, 200, 200, 200) window = Window(800, 800) window.add(croppedImage) window.wait() window.close() Error message: ParameterTypeError: Incorrect type for parameter 'graphic' : NoneType, expected GraphicalObject ```
This usually means that the `crop` function works by changing the image object it is applied to, instead of creating a new one - ie, you want to do this: ``` image.crop(200, 200, 200, 200) window.add(image) window.wait() window.close() ```
What does any = lambda v: v mean?
13,173,271
2
2012-11-01T08:15:12Z
13,173,314
9
2012-11-01T08:19:16Z
[ "python", "lambda" ]
What does `any = lambda v: v` mean? It seems `v` is only `v` itself. ``` class Object(object): """Common base class supporting automatic kwargs->attributes handling, and cloning.""" attrs = () def __init__(self, *args, **kwargs): any = lambda v: v for name, type_ in ...
`lambda v: v` creates an *identity function*, which just returns its argument unchanged. Assigning it to a local variable is equivalent to defining a local function like this: ``` def any(v): return v ``` It can be useful as a fallback for code that wants to call a function to do some processing on the argument, ...
Flushing all current figures in matplotlib
13,174,149
5
2012-11-01T09:25:43Z
13,174,720
9
2012-11-01T10:02:15Z
[ "python", "matplotlib" ]
Say I did ``` figure(1) plot(...) figure(2) plot(...) ``` and I want to create a third figure and show only that one. so that: ``` figure(1) plot(...) figure(2) plot(...) somemagicFuncToFlushFigures() figure(3) plot(...) show() ``` will only show the third figure. How do I do that?
You want to close the figures right? I wonder if the following helps? ``` import matplotlib.pyplot as plt plt.close() ``` **UPDATE**: As @jorgeca says, to close all the figures try using `plt.close('all')`
Python - start interactive debugger when exception would be otherwise thrown
13,174,412
10
2012-11-01T09:44:38Z
13,174,701
12
2012-11-01T10:01:01Z
[ "python", "debugging", "pdb" ]
Is there any way to make a python program start an interactive debugger, like what `import pdb; pdb.set_trace()` instead of actually throwing an exception? I know the difficulty of making this work, but it would be much more valuable than a huge stack trace after which I have to use to figure out where to insert break...
The simplest way is to wrap your entire code inside a `try` block like this: ``` if __name__ == '__main__': try: raise Exception() except: import pdb pdb.set_trace() ``` There is a more complicated solution which uses `sys.excepthook` to override the handling of uncaught exceptions, a...
Debugging options w/ Python, Flask and Sublime Text 2
13,174,476
8
2012-11-01T09:48:52Z
13,174,612
9
2012-11-01T09:56:11Z
[ "python", "flask", "sublimetext2" ]
I have just switched to Sublime Text 2 for my Python development. I usually do web programming with the Flask micro framework. What are my debugging options with this combination, and how do I set it up? I'm working on Windows 7.
Use [pdb](http://docs.python.org/library/pdb.html): ``` import pdb; pdb.set_trace() ``` (or the even better [pdb++](http://pypi.python.org/pypi/pdbpp/)) Also, Flask already include [Werkzeug](http://werkzeug.pocoo.org/docs/) which contains an interactive JavaScript based in-browser debugger, I highly recommend you u...
How to get callback when key expires in REDIS
13,174,615
8
2012-11-01T09:56:19Z
13,174,703
7
2012-11-01T10:01:05Z
[ "python", "redis", "bottle" ]
I'm developing application using Bottle. In my registration form, I'm confirming email by mail with a unique key. I'm storing this key in REDIS with expiry of 4 days. If user does not confirm email within 4 days, key gets expired. for this, I want to permanently delete the user entry from my database(mongoDB). Ofcours...
There are no such callbacks in redis (not that I know of). I would do it like this: * when user signs up, [put his id into a sorted set](http://redis.io/commands/zadd) where the score is a timestamp (now + 4 days) and member is user id. * have a periodic job that gets all records from that sorted set where timestamp ...
How to get callback when key expires in REDIS
13,174,615
8
2012-11-01T09:56:19Z
21,226,830
9
2014-01-20T05:29:06Z
[ "python", "redis", "bottle" ]
I'm developing application using Bottle. In my registration form, I'm confirming email by mail with a unique key. I'm storing this key in REDIS with expiry of 4 days. If user does not confirm email within 4 days, key gets expired. for this, I want to permanently delete the user entry from my database(mongoDB). Ofcours...
This feature implemented in Redis 2.8, read about it here <http://redis.io/topics/notifications>
Call Python function from Javascript code
13,175,510
25
2012-11-01T10:52:29Z
13,175,580
12
2012-11-01T10:56:25Z
[ "javascript", "python", "function", "integration" ]
I'd like to call a `Python` function from `Javascript` code, because there isn't an alternative in `Javascript` for doing what I want. Is this possible? Could you adjust the below snippet to work? Javascript part: ``` var tag = document.getElementsByTagName("p")[0]; text = tag.innerHTML; // Here I would like to call ...
From the `document.getElementsByTagName` I guess you are running the javascript in a browser. The traditional way to expose functionality to javascript running in the browser is calling a remote URL using AJAX. The X in AJAX is for XML, but nowadays everybody uses JSON instead of XML. For example, using jQuery you ca...
Call Python function from Javascript code
13,175,510
25
2012-11-01T10:52:29Z
13,175,665
26
2012-11-01T11:01:48Z
[ "javascript", "python", "function", "integration" ]
I'd like to call a `Python` function from `Javascript` code, because there isn't an alternative in `Javascript` for doing what I want. Is this possible? Could you adjust the below snippet to work? Javascript part: ``` var tag = document.getElementsByTagName("p")[0]; text = tag.innerHTML; // Here I would like to call ...
All you need is to make an ajax request to your pythoncode. You can do this with jquery <http://api.jquery.com/jQuery.ajax/>, or use just javascript ``` $.ajax({ type: "POST", url: "~/pythoncode.py", data: { param: text} }).done(function( o ) { // do something }); ```
Python 'startswith' equivalent for SqlAlchemy
13,176,252
6
2012-11-01T11:39:48Z
13,176,572
10
2012-11-01T11:57:21Z
[ "python", "sqlalchemy" ]
I have a string, for which I need to find all records with matching prefixs: ``` path = '/abc/123/456' session.query(Site).filter(path.startswith(Site.path_prefix)) ``` The following records would match when path\_prefix equals: ``` /abc /ab /abc/123 ``` But not: ``` /asd /abc/123/456/789 /kjk ``` Is this possibl...
If you wrap the `path` variable in a [`bindparam()` object](http://docs.sqlalchemy.org/en/rel_0_7/core/expression_api.html#sqlalchemy.sql.expression.bindparam) then you can treat it like any column, including using the [`.contains()`](http://docs.sqlalchemy.org/en/rel_0_7/core/expression_api.html#sqlalchemy.sql.operato...
How can I use a pip requirements file to uninstall as well as install packages?
13,176,968
29
2012-11-01T12:21:28Z
13,177,994
9
2012-11-01T13:20:48Z
[ "python", "pip" ]
I have a pip requirements file that changes during development. Can `pip` be made to **uninstall** packages that do not appear in the requirements file as well as installing those that do appear? Is there a standard method? This would allow the pip requirements file to be the canonical list of packages - an 'if and o...
It's not a feature of `pip`, no. If you really want such a thing, you could write a script to compare the output of `pip freeze` with your `requirements.txt`, but it would likely be more hassle than it's worth. Using [`virtualenv`](http://www.virtualenv.org/en/latest/), it is easier and more reliable to just create a ...
How can I use a pip requirements file to uninstall as well as install packages?
13,176,968
29
2012-11-01T12:21:28Z
15,708,711
60
2013-03-29T17:55:35Z
[ "python", "pip" ]
I have a pip requirements file that changes during development. Can `pip` be made to **uninstall** packages that do not appear in the requirements file as well as installing those that do appear? Is there a standard method? This would allow the pip requirements file to be the canonical list of packages - an 'if and o...
This should uninstall anything not in requirements.txt: ``` pip freeze | grep -v -f requirements.txt - | grep -v '^#' | xargs pip uninstall -y ``` Although this won't work quite right with packages installed with `-e`, i.e. from a git repository or similar. To skip those, just filter out packages starting with the `-...
Comparing speed of non-matching regexp
13,179,030
9
2012-11-01T14:19:28Z
13,179,439
13
2012-11-01T14:42:12Z
[ "python", "regex", "perl" ]
The following Python code is incredibly slow: ``` import re re.match( '([a]+)+c', 'a' * 30 + 'b' ) ``` and it gets worse if you replace 30 with a larger constant. I suspect that the parsing ambiguity due to the consecutive `+` is the culprit, but I'm not very expert in regexp parsing and matching. Is this a bug of t...
I assume that Perl is clever enough to collapse the two `+`s into one, while Python is not. Now let's imagine what the engine does, if this is not optimized away. And remember that capturing is generally expensive. Note also, that both `+`s are greedy, so the engine will try to use as many repetitions as possible in on...
Maintaining Logging and/or stdout/stderr in Python Daemon
13,180,720
10
2012-11-01T15:52:25Z
13,696,380
15
2012-12-04T05:01:26Z
[ "python", "logging", "fork", "daemon" ]
Every recipe that I've found for creating a daemon process in Python involves forking twice (for Unix) and then closing all open file descriptors. (See <http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/> for an example). This is all simple enough but I seem to have an issue. On the production...
I use the `python-daemon` library for my daemonization behavior. Interface described here: * <http://www.python.org/dev/peps/pep-3143/> Implementation here: * <http://pypi.python.org/pypi/python-daemon/> It allows specifying a `files_preserve` argument, to indicate any file descriptors that should *not* be closed ...
Maintaining Logging and/or stdout/stderr in Python Daemon
13,180,720
10
2012-11-01T15:52:25Z
15,329,299
7
2013-03-11T00:07:40Z
[ "python", "logging", "fork", "daemon" ]
Every recipe that I've found for creating a daemon process in Python involves forking twice (for Unix) and then closing all open file descriptors. (See <http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/> for an example). This is all simple enough but I seem to have an issue. On the production...
You can simplify the code for this if you set up your logging handler objects separately from your root logger object, and then add the handler objects as an independent step rather than doing it all at one time. The following should work for you. ``` import daemon import logging logger = logging.getLogger() logger.s...
Zip as a list comprehension
13,180,861
5
2012-11-01T15:59:57Z
13,180,879
12
2012-11-01T16:01:08Z
[ "python", "list", "zip", "list-comprehension" ]
I have a fairly last list of data like this: ``` data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] ``` I'm trying to zip it so that that I get something like this: ``` zipped_data = [(1, 4, 7), (2, 5, 8), (3, 6, 9)] ``` I know I could do that with ``` l = [(data[0]), (data[1]), (data[2])] zipped_data = zip(*l) ``` But I w...
Try the `*`: ``` In [2]: lis=[[1, 2, 3], [4, 5, 6], [7, 8, 9]] In [3]: zip(*lis) Out[3]: [(1, 4, 7), (2, 5, 8), (3, 6, 9)] ```
How to kill a while loop with a keystroke?
13,180,941
24
2012-11-01T16:04:18Z
13,181,036
40
2012-11-01T16:08:35Z
[ "python", "while-loop", "break" ]
I am reading serial data and writing to a csv file using a while loop. I want the user to be able to kill the while loop once they feel they have collected enough data. ``` while True: #do a bunch of serial stuff #if the user presses the 'esc' or 'return' key: break ``` I have done something like thi...
The easiest way is to just interrupt it with the usual `Ctrl-C` (SIGINT). ``` try: while True: do_something() except KeyboardInterrupt: pass ``` Since `Ctrl-C` causes `KeyboardInterrupt` to be raised, just catch it outside the loop and ignore it.
How to kill a while loop with a keystroke?
13,180,941
24
2012-11-01T16:04:18Z
25,442,391
11
2014-08-22T08:09:21Z
[ "python", "while-loop", "break" ]
I am reading serial data and writing to a csv file using a while loop. I want the user to be able to kill the while loop once they feel they have collected enough data. ``` while True: #do a bunch of serial stuff #if the user presses the 'esc' or 'return' key: break ``` I have done something like thi...
There is a solution that requires no non-standard modules and is 100% transportable ``` import thread def input_thread(list): raw_input() list.append(None) def do_stuff(): list = [] thread.start_new_thread(input_thread, (list,)) while not list: stuff() ```
Copying text from Word to Python makes Escape Characters unnecessary, Why?
13,181,465
2
2012-11-01T16:31:04Z
13,181,539
7
2012-11-01T16:35:40Z
[ "python", "exception", "python-3.x", "ms-word" ]
I'm new to Python and recently in a class I am taking we started the dragon realm tutorial. <http://inventwithpython.com/chapter6.html> I decided to go way off on my own with this little project and make a semi-long adventure story. About half way through I started pasting my text into Word. (I was using a previous adv...
Word is a terrible code editor. The quotes were replaced by a 'fancy' quote, not the normal double-quote from the ASCII alphabet, but one from elsewhere in the Unicode standard: ``` >>> u'”' u'\u201d' ``` My Unicode application tells me that's the RIGHT DOUBLE QUOTATION MARK symbol; Word normally uses matching LEF...
Importing modules: __main__ vs import as module
13,181,559
8
2012-11-01T16:37:09Z
13,181,615
15
2012-11-01T16:40:10Z
[ "python", "python-import", "python-module" ]
To preface, I think I may have figured out how to get this code working (based on [Changing module variables after import](http://stackoverflow.com/questions/12242417/changing-module-variables-after-import)), but my question is really about why the following behavior occurs so I can understand what to not do in the fut...
The `__name__` variable always contains the name of the module, *except* when the file has been loaded into the interpreter as a script instead. *Then* that variable is set to the string `'__main__'` instead. After all, the script is then run as the main file of the whole program, everything else are modules imported ...
How to convert a timezone aware string to datetime in python without dateutil?
13,182,075
15
2012-11-01T17:07:24Z
13,182,163
20
2012-11-01T17:13:35Z
[ "python", "datetime", "timezone", "rfc3339" ]
I have to convert a timezone-aware string to python datetime object. For example "2012-11-01T04:16:13-04:00". I find there's a `dateutil` module which have a parse function to do it, but I don't really want to use it as it adds a dependency. So how can I do it? I have tried something like the following, but with no ...
You can't, not without a whole lot of painstaking manual timezone defining. Python does not include a timezone database, because it would be outdated too quickly. Instead, Python relies on external libraries, which can have a far faster release cycle, to provide properly configured timezones for you. As a side-effect...
How to convert a timezone aware string to datetime in python without dateutil?
13,182,075
15
2012-11-01T17:07:24Z
36,566,185
7
2016-04-12T07:18:09Z
[ "python", "datetime", "timezone", "rfc3339" ]
I have to convert a timezone-aware string to python datetime object. For example "2012-11-01T04:16:13-04:00". I find there's a `dateutil` module which have a parse function to do it, but I don't really want to use it as it adds a dependency. So how can I do it? I have tried something like the following, but with no ...
Here is the Python [Doc](https://dateutil.readthedocs.org/en/latest/) for datetime object using dateutil package.. ``` from dateutil.parser import parse get_dobj = parse("2012-11-01T04:16:13-04:00") ```
Python: How to slice a string on a specific number of characters into a list?
13,182,185
2
2012-11-01T17:15:03Z
13,182,226
8
2012-11-01T17:17:14Z
[ "python", "slice" ]
I am reading a line of text data and I want to split the line into a list of values. For example the line has four numbers, each one allotted 5 spaces, so if the numbers are 18, 295, -9999, and 1780 then the original line will look like this (with ^ characters denoting the start and end of line, not included in actual ...
Using slicing... ``` >>> [int(s[i:i+5]) for i in xrange(0, len(s), 5)] [18, 295, -9999, 1780] ``` Or - if you really wanted to, some people find `re` a bit more readable... (just throwing this in as an alternative for reference - don't shoot me!) ``` >>> map(int, re.findall('.{5}', s)) [18, 295, -9999, 1780] ```
Haskell to Python: multiple-functions conversion issue
13,182,699
4
2012-11-01T17:46:26Z
13,182,866
7
2012-11-01T17:58:29Z
[ "python", "haskell", "code-conversion" ]
I am pretty new to programming and I was asked to convert 3 haskell functions into python as a practice exercise. The 3 functions are connected, since output of one is used as the input of the next one and so on. I get what the haskell functions do, but I have no idea how to start converting them! This is the haskell...
First off, ditch the `class` wrapper - that's not needed. A straight Python translation would be something like: ``` # factorial :: Int -> Int def factorial(n): return product(down(n)) # product :: [Int] -> Int def product(arr): if len(arr) == 0: return 1 a, ar = arr[0], arr[1:] return a * product(ar...
Installing pip for python3.3
13,183,112
22
2012-11-01T18:14:49Z
13,183,619
17
2012-11-01T18:51:31Z
[ "python", "osx", "unix", "pip", "python-3.3" ]
I downloaded pip from [Package Index > pip 1.2.1](http://pypi.python.org/pypi/pip) Then I installed it using ``` sudo python3.3 setup.py install ``` Still, when I try to use `pip-3.3` the terminal complains ``` -bash: pip-3.3: command not found ``` However, `pip-2.7` works swimmingly. I have also tried ``` curl ...
Chances are that `pip` did get installed successfully *somewhere*. However, *somewhere* is probably not on your `PATH` and so you shell (bash) doesn't know where to find it. For me, `pip-2.6` is installed in: ``` /Library/Frameworks/Python.framework/Versions/2.6/bin/ ``` It is probably a similar path for you (only 3....
staticmethod and recursion?
13,183,501
5
2012-11-01T18:42:21Z
13,183,523
13
2012-11-01T18:44:22Z
[ "python", "class", "methods" ]
I have following code: ``` class Foo(object): def __init__(self): baz=self.bar(10) @staticmethod def bar(n): if n==0: return 'bar' else: return bar(n-1) ``` bar() as a recursive function it needs reference to itself. However, bar() is inside a class, and ca...
You can refer to `bar` by prefixing it with the class name: ``` class Foo(object): def __init__(self): baz=self.bar(10) @staticmethod def bar(n): if n==0: return 'bar' else: return Foo.bar(n-1) ``` Static methods are nothing but regular functions contained ...
How can I find the first occurrence of a substring occurring after another substring in python?
13,183,889
3
2012-11-01T19:08:48Z
13,184,009
9
2012-11-01T19:18:34Z
[ "python", "string", "string-matching" ]
Strings in Python have a find("somestring") method that returns the index number for "somestring" in your string. But let's say I have a string like the following: "$5 $7 $9 Total Cost: $35 $14" And I want to find the index of the first occurrence of '$' that occurs *after* the string "Total Cost" -- I'd like to be ...
Use the optional second argument of [`str.find`](http://docs.python.org/2/library/stdtypes.html#str.find): ``` def findStrAfterStr(myString, searchText, afterText): after_index = myString.index(afterText) return myString.find(searchText, after_index) ``` Or, as pythonm suggests, you can use regexps. I recomm...
DNS over proxy?
13,184,205
11
2012-11-01T19:32:58Z
13,214,222
12
2012-11-03T22:40:53Z
[ "python", "dns", "proxy" ]
I've been pulling my hair out over the past few days looking around for a good solution to prevent DNS leaks over a socks4/5 proxy. I've looked into the SocksiPy(-branch) module, and tried to wrap a number of things (urllib,urllib2,dnstools), but they all seem to still leak DNS requests. So does pyCurl. I know that p...
Well I figured it out. You need to set your default proxy BEFORE you start using the socket (e.g. before you import anything that uses it.). You also need to monkeypatch the getaddrinfo part of socket, then everything works fine. ``` import socks import socket # Can be socks4/5 socks.setdefaultproxy(socks.PROXY_TYPE_...
I'd like to create a mock object in python
13,184,260
2
2012-11-01T19:36:50Z
13,184,278
7
2012-11-01T19:38:23Z
[ "python", "object", "setattr" ]
I want a dummy object I can instantiate in python and programmatically create attributes for via setattr(). I tried it on the built in object but probably for a good reason that didn't work. What base object can I use in python for such purposes without actually defining one myself?
You can't use `mock = object()`, instead just create a Mock derived from `object` ``` class Mock(object): pass mock = Mock() setattr(mock, 'test', 'whatever') ```
How to retrieve python list of SQLAlchemy result set?
13,184,275
8
2012-11-01T19:38:10Z
13,260,398
11
2012-11-06T22:23:28Z
[ "python", "sqlalchemy" ]
I have the following query to retrieve a single column of data: ``` routes_query = select( [schema.stop_times.c.route_number], schema.stop_times.c.stop_id == stop_id ).distinct(schema.stop_times.c.route_number) result = conn.execute(routes_query) return [r['route_number'] for r in result] ``` I am wondering ...
the most succinct way to pull out a list of 1-element tuples into a list is: ``` result = [r[0] for r in result] ``` or: ``` result = [r for r, in result] ```
Python dynamic function creation with custom names
13,184,281
14
2012-11-01T19:38:25Z
13,184,536
17
2012-11-01T19:56:33Z
[ "python", "python-2.7", "closures", "metaprogramming", "dynamic-function" ]
Apologies if this question has already been raised and answered. What I need to do is very simple in concept, but unfortunately I have not been able to find an answer for it online. I need to create dynamic functions in Python (Python2.7) with custom names at runtime. The body of each function also needs to be constru...
For what you describe, I don't think you need to descend into eval or macros — creating function instances by closure should work just fine. Example: ``` def bindFunction1(name): def func1(*args): for arg in args: print arg return 42 # ... func1.__name__ = name return func1 d...
easiest way to get %appdata% path variable in python
13,184,414
12
2012-11-01T19:48:02Z
13,184,486
30
2012-11-01T19:52:40Z
[ "python", "appdata" ]
Sorry if this is a redundant question, writing a Python file that needs to pull from the `%APPDATA%` directory. What is the easiest way to find the path to this folder?
``` import os print os.getenv('APPDATA') ```
Is there a concise emacs lisp equivalent of Python's [n:m] list slices?
13,184,450
15
2012-11-01T19:50:31Z
13,186,474
15
2012-11-01T22:27:43Z
[ "python", "emacs", "elisp" ]
One thing I find myself missing in emacs lisp is, surprisingly, a particular bit of list manipulation. I miss Python's concise list slicing. ``` >>> mylist = ["foo", "bar", "baz", "qux", "frobnitz"] >>> mylist[1:4] ['bar', 'baz', 'qux'] ``` I see the functions `butlast` and `nthcdr` in the emacs documentation, which ...
Sure there is: ``` (require 'cl) (setq mylist '("foo" "bar" "baz" "qux" "frobnitz")) (subseq mylist 1 4) ;; ("bar" "baz" "qux") ```
Efficiently split a string using multiple separators and retaining each separator?
13,186,067
23
2012-11-01T21:50:24Z
13,186,133
7
2012-11-01T21:56:33Z
[ "python", "string" ]
I need to split strings of data using each character from `string.punctuation` and `string.whitespace` as a separator. Furthermore, I need for the separators to remain in the output list, in between the items they separated in the string. For example, ``` "Now is the winter of our discontent" ``` should output: ``...
``` import re import string p = re.compile("[^{0}]+|[{0}]+".format(re.escape( string.punctuation + string.whitespace))) print p.findall("Now is the winter of our discontent") ``` I'm no big fan of using regexps for all problems, but I don't think you have much choice in this if you want it fast and short. I'll ...
Efficiently split a string using multiple separators and retaining each separator?
13,186,067
23
2012-11-01T21:50:24Z
13,186,274
21
2012-11-01T22:08:24Z
[ "python", "string" ]
I need to split strings of data using each character from `string.punctuation` and `string.whitespace` as a separator. Furthermore, I need for the separators to remain in the output list, in between the items they separated in the string. For example, ``` "Now is the winter of our discontent" ``` should output: ``...
A different non-regex approach from the others: ``` >>> import string >>> from itertools import groupby >>> >>> special = set(string.punctuation + string.whitespace) >>> s = "One two three tab\ttabandspace\t end" >>> >>> split_combined = [''.join(g) for k, g in groupby(s, lambda c: c in special)] >>> split_combi...
which python web framework(django or django-norel or pyramid) to use when MongoDB is used as a database
13,186,250
12
2012-11-01T22:06:24Z
13,186,525
8
2012-11-01T22:33:09Z
[ "python", "django", "mongodb", "pyramid" ]
I am using MongoDB as my primary(and only till now) database and because of google and the links it provided me i am confused between Django or Pyramid. I am comfortable with python but never done web development in python(i have done in PHP). Now because i will be using Mongo so i wont use Django ORM will that take a...
I'm going to suggest an alternative that has not been mentioned: [Flask](http://flask.pocoo.org/). Flask has a really great (albeit smaller than Django) community and there are a lot of extensions available for common web-app extensions, in the [extensions directory](http://flask.pocoo.org/extensions/). There are seve...
which python web framework(django or django-norel or pyramid) to use when MongoDB is used as a database
13,186,250
12
2012-11-01T22:06:24Z
13,202,331
12
2012-11-02T20:08:10Z
[ "python", "django", "mongodb", "pyramid" ]
I am using MongoDB as my primary(and only till now) database and because of google and the links it provided me i am confused between Django or Pyramid. I am comfortable with python but never done web development in python(i have done in PHP). Now because i will be using Mongo so i wont use Django ORM will that take a...
A year or two ago I was also deciding between django and pyramid w/ mongodb to build a high performance web application. I ultimately chose Pyramid : Pros: * Pyramid is very light weight for a full stack framework. There is a minmal amount of 'magic' going on under the hood. I was able to wrap my head around all the ...
Sublist in List
13,187,619
5
2012-11-02T00:34:38Z
13,187,638
10
2012-11-02T00:36:36Z
[ "python", "list", "sublist" ]
(a)Assign to variable flowers a list containing strings 'rose','bougainvillea', 'yucca','marigold','daylilly',and'lillyofthevalley'. I did this: ``` >>> flowers = ['rose','bougainvillea','yucca','marigold','daylilly','lilly of the valley'] ``` Then, (c)Assign to list thorny the sublist of list flowers consisting of...
Slicing notation is `[:3]` not `[0-3]`: ``` In [1]: flowers = ['rose','bougainvillea','yucca','marigold','daylilly','lilly of the valley'] In [2]: thorny=flowers[:3] In [3]: thorny Out[3]: ['rose', 'bougainvillea', 'yucca'] ```
Run python programs without opening a separate shell
13,187,641
4
2012-11-02T00:37:14Z
13,191,520
8
2012-11-02T08:11:50Z
[ "python", "powershell" ]
In powershell, when I run a python program with: ``` > python hello.py ``` The program runs and prints any output directly in the powershell window I'm working in. But when I try to do it without explicitly invoking python: ``` > hello.py ``` it opens up a separate window. How can I fix that so it behaves the same ...
If you add `.PY` to the `PATHEXT` environment variable, you should be able to run `.\hello.py` or just `.\hello` in the current console. Otherwise it will `ShellExecute` the associated `Python.File` command (check `ftype Python.File`), which launches a new console. I checked this by temporarily modifying the environmen...
Python threading override init
13,187,762
4
2012-11-02T00:55:31Z
13,187,790
7
2012-11-02T00:58:28Z
[ "python", "multithreading", "class", "inheritance", "initialization" ]
I am using threading.py and I have the following code: ``` import threading class MyClass(threading.Thread): def __init__(self,par1,par2): threading.Thread.__init__(self) self.var1 = par1 self.var2 = par2 def run(self): #do stuff with var1 and var2 while conditions are met...
You don't have to extend `Thread` to use threads. I usually use this pattern... ``` def worker(par1, par2): pass # do something thread = threading.Thread(target=worker, args=("something", 0.0)) thread.start() ```
Convert pandas dataframe to numpy array, preserving index
13,187,778
55
2012-11-02T00:57:33Z
13,193,256
17
2012-11-02T10:16:00Z
[ "python", "arrays", "numpy", "pandas", "type-conversion" ]
I am interested in knowing how to convert a pandas dataframe into a numpy array, including the index, and set the dtypes. dataframe: ``` label A B C ID 1 NaN 0.2 NaN 2 NaN NaN 0.5 3 NaN 0.2 0.5 4 0.1 0.2 NaN 5 0.1 0.2 0.5 6 0.1 NaN 0.5 7 0.1 NaN NaN...
You can use the `to_records` method, but have to play around a bit with the dtypes if they are not what you want from the get go. In my case, having copied your DF from a string, the index type is string (represented by an `object` dtype in pandas): ``` In [102]: df Out[102]: label A B C ID ...
Convert pandas dataframe to numpy array, preserving index
13,187,778
55
2012-11-02T00:57:33Z
22,653,050
11
2014-03-26T06:23:21Z
[ "python", "arrays", "numpy", "pandas", "type-conversion" ]
I am interested in knowing how to convert a pandas dataframe into a numpy array, including the index, and set the dtypes. dataframe: ``` label A B C ID 1 NaN 0.2 NaN 2 NaN NaN 0.5 3 NaN 0.2 0.5 4 0.1 0.2 NaN 5 0.1 0.2 0.5 6 0.1 NaN 0.5 7 0.1 NaN NaN...
I would just chain the [DataFrame.reset\_index()](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html) and [DataFrame.values](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.values.html) functions to get the Numpy representation of the dataframe, including the ...
Convert pandas dataframe to numpy array, preserving index
13,187,778
55
2012-11-02T00:57:33Z
24,793,359
28
2014-07-17T01:13:50Z
[ "python", "arrays", "numpy", "pandas", "type-conversion" ]
I am interested in knowing how to convert a pandas dataframe into a numpy array, including the index, and set the dtypes. dataframe: ``` label A B C ID 1 NaN 0.2 NaN 2 NaN NaN 0.5 3 NaN 0.2 0.5 4 0.1 0.2 NaN 5 0.1 0.2 0.5 6 0.1 NaN 0.5 7 0.1 NaN NaN...
Pandas has something built in... ``` numpyMatrix = df.as_matrix() ```
Convert pandas dataframe to numpy array, preserving index
13,187,778
55
2012-11-02T00:57:33Z
37,043,071
8
2016-05-05T05:29:51Z
[ "python", "arrays", "numpy", "pandas", "type-conversion" ]
I am interested in knowing how to convert a pandas dataframe into a numpy array, including the index, and set the dtypes. dataframe: ``` label A B C ID 1 NaN 0.2 NaN 2 NaN NaN 0.5 3 NaN 0.2 0.5 4 0.1 0.2 NaN 5 0.1 0.2 0.5 6 0.1 NaN 0.5 7 0.1 NaN NaN...
To convert a pandas dataframe (df) to a numpy ndarray, use this code: `df=df.values` df now becomes a numpy ndarray.
Django : Case insensitive matching of username from auth user?
13,190,758
8
2012-11-02T07:01:53Z
33,456,271
9
2015-10-31T20:29:34Z
[ "python", "django", "user", "operator-overloading" ]
Django by-default implements username as case sensitive, now for authentication I have written my own `Authentication Backend` to handle case insensitive usernames while authentication. As shown in : <http://blog.shopfiber.com/?p=220> Now, the problem is : I have various views and util methods which compares `userna...
As of Django 1.5, making usernames case insensitive is straightforward: ``` class MyUserManager(BaseUserManager): def get_by_natural_key(self, username): return self.get(username__iexact=username) ``` Sources: [1](https://djangosnippets.org/snippets/1368/), [2](https://code.djangoproject.com/ticket/2273#c...
Foreman start can't find Procfile, deploying Django app to Heroku
13,192,994
5
2012-11-02T09:59:47Z
13,193,175
18
2012-11-02T10:10:25Z
[ "python", "django", "heroku", "gunicorn" ]
Seems like a fairly simple problem, but can't seem to figure it out. I've been following Heroku's Django instructions (https://devcenter.heroku.com/articles/django#using-a-different-wsgi-server) I'm trying to create a Procfile, run it locally with Foreman start. I've downloaded and installed Gunicorn and Gevent alread...
The Procfile should not have a '.txt' extension. You have called it 'Procfile.txt'. Should be just 'Procfile'.
Understand python threading bug
13,193,278
13
2012-11-02T10:17:24Z
13,193,573
33
2012-11-02T10:37:36Z
[ "python", "python-multithreading" ]
Reading <http://bugs.python.org/msg160297>, I can see a simple script written by Stephen White which demonstrates how python threading bugs up with this exception ``` Exception AttributeError: AttributeError("'_DummyThread' object has no attribute '_Thread__block'",) in <module 'threading' ``` Given Stephen White's s...
[The bug](http://bugs.python.org/issue14308) occurs because of a bad interaction between dummy thread objects created by the `threading` API when you call `threading.currentThread()` on a foreign thread, and the `_after_fork` feature, called to clean up resources after a call to `os.fork()`. To work around the bug wit...
Using Celery on processes and gevent in tasks at the same time
13,194,064
17
2012-11-02T11:10:51Z
14,141,848
8
2013-01-03T15:24:39Z
[ "python", "multiprocessing", "celery", "gevent", "monkeypatching" ]
I'd like to use Celery as a queue for my tasks so my web app could enqueue a task, return a response and the task will be processed meanwhile / someday / ... I build a kind of API, so I don't know what sort of tasks will be there in advance - in future, there can be tasks dealing with HTTP requests, another IO, but als...
You can run celery with multiple threads containing multiple greenlets like this: ``` $ celery multi start 4 -P gevent -l info -c:1-4 1000 ```
Using Celery on processes and gevent in tasks at the same time
13,194,064
17
2012-11-02T11:10:51Z
16,801,990
10
2013-05-28T21:43:35Z
[ "python", "multiprocessing", "celery", "gevent", "monkeypatching" ]
I'd like to use Celery as a queue for my tasks so my web app could enqueue a task, return a response and the task will be processed meanwhile / someday / ... I build a kind of API, so I don't know what sort of tasks will be there in advance - in future, there can be tasks dealing with HTTP requests, another IO, but als...
I believe the recommended way to start the task is as follows. ``` python manage.py celery worker -P gevent --loglevel=INFO ``` Gevent needs to be patched as early as possible.
Why does Python change the value of an integer when there is a 0 in front of it?
13,195,202
3
2012-11-02T12:25:06Z
13,195,234
9
2012-11-02T12:26:35Z
[ "python", "integer", "python-2.x" ]
I implemented a function converting an integer number to its representation as a string `intToStr()` (code below). For testing I've passed in some values and observed an unexpected output: ``` print intToStr( 1223) # prints 1223 as expected print intToStr(01223) # prints 659, surprisingly ``` Now, I've tried to deb...
An integer literal starting with a 0 is interpreted as an [octal number, base 8](http://docs.python.org/2/reference/lexical_analysis.html#integer-and-long-integer-literals): ``` >>> 01223 659 ``` This has been changed in Python 3, where integers with a leading 0 are considered errors: ``` >>> 01223 File "<stdin>",...
How to use webscraping in Python using username and password for website
13,195,269
2
2012-11-02T12:28:37Z
13,195,306
7
2012-11-02T12:31:02Z
[ "python", "python-2.7", "web-scraping" ]
Hi I am using this code to get the data from the [timeanddate.com](http://timeanddate.com) site. But I need to do the same for my facebook accout using my username and password & grab the comments on my wall and write it to text file. Can I do this with python? How to do that? ``` import urllib2 from BeautifulSoup imp...
Use [Requests API](http://docs.python-requests.org/en/latest/). It handles authentication as well.
I think this should raise an error, but it doesn't
13,196,913
5
2012-11-02T14:12:41Z
13,196,934
9
2012-11-02T14:14:33Z
[ "python", "error-handling" ]
Below is a simple function to remove duplicates in a list while preserving order. I've tried it and it actually works, so the problem here is my understanding. It seems to me that the second time you run `uniq.remove(item)` for a given item, it will return an error (`KeyError` or `ValueError` I think?) because that ite...
There's a check `if item in uniq` which gets executed before the item is removed. The `and` operator is nice in that it "short circuits". This means that if the condition on the left evaluates to `False`-like, then the condition on the right doesn't get evaluated -- We already know the expression can't be `True`-like.
Python openpyxl column width size adjust
13,197,574
25
2012-11-02T14:50:05Z
14,450,572
37
2013-01-22T02:20:42Z
[ "python", "openpyxl" ]
I have following script which is converting a CSV file to an XLSX file but my column size is very narrow, each time i have to drag them with mouse to read data, Anybody know how to set column width in openpyxl, here is the code which i am using. ``` #!/usr/bin/python2.6 import csv from openpyxl import Workbook from op...
You could estimate (or use a mono width font) to achieve this. Let's assume data is a nested array like [['a1','a2'],['b1','b2']] We can get the max characters in each column. The set the width to that. Width is exactly the width of a monospace font (well not changing other styles at least). Even if you use a variable...
Python openpyxl column width size adjust
13,197,574
25
2012-11-02T14:50:05Z
35,790,441
8
2016-03-04T07:33:00Z
[ "python", "openpyxl" ]
I have following script which is converting a CSV file to an XLSX file but my column size is very narrow, each time i have to drag them with mouse to read data, Anybody know how to set column width in openpyxl, here is the code which i am using. ``` #!/usr/bin/python2.6 import csv from openpyxl import Workbook from op...
My variation of Bufke's answer. Avoids a bit of branching with the array and ignores empty cells / columns. ``` ws = your current worksheet dims = {} for row in ws.rows: for cell in row: if cell.value: dims[cell.column] = max((dims.get(cell.column, 0), len(cell.value))) for col, value in dims.i...
Counting consecutive characters in a string
13,197,668
5
2012-11-02T14:55:14Z
13,197,689
16
2012-11-02T14:56:49Z
[ "python", "string", "count", "character" ]
I need to write a code that slices the string (which is an input), append it to a list, count the number of each letter - and if it is identical to the letter before it, don't put it in the list, but rather increase the appearance number of that letter in the one before.. Well this is how it should look like : ``` ass...
Use [`Collections.Counter()`](http://docs.python.org/2/library/collections.html#collections.Counter), dictionary is a better way to store this: ``` >>> from collections import Counter >>> strs="assassin" >>> Counter(strs) Counter({'s': 4, 'a': 2, 'i': 1, 'n': 1}) ``` or using [`itertools.groupby()`](http://docs.pytho...
How do I ensure that a Python while-loop takes a particular amount of time to run?
13,197,686
5
2012-11-02T14:56:37Z
13,197,891
8
2012-11-02T15:06:25Z
[ "python", "python-2.7", "while-loop", "serial-port", "pyserial" ]
I'm reading serial data with a while loop. However, I have no control over the sample rate. The code itself seems to take 0.2s to run, so I know I won't be able to go any faster than that. But I would like to be able to control precisely how much slower I sample. I feel like I could do it using 'sleep', but the probl...
Just measure the time running your code takes every iteration of the loop, and `sleep` accordingly: ``` import time while True: now = time.time() # get the time do_something() # do your stuff elapsed = time.time() - now # how long was it running? time.sleep(1.-elapsed) ...
regex line start in character set
13,199,118
5
2012-11-02T16:15:44Z
13,199,255
7
2012-11-02T16:24:02Z
[ "python", "regex" ]
Let's say I want to search for a 'b' that occurs either at start of line or followed by 'a'. Why doesn't `re.match('[\^a]b','b')` match while `re.match('^b','b')` does? **Update:** I realised I should have been using `search` instead of `match`. I want it to be a positive for things like 'b', 'cab', 'ab', 'bc', and '...
The regex `[\^a]b` will match either `ab` or `^b`, so it should not match the string `'b'`. Note that `re.match()` only matches at the beginning of a string, it is as if you have a beginning of string anchor at the beginning of your regex (`^` or `\A` with multiline option enabled). So "to search for a 'b' that occur...