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 determine the learning rate and the variance in a gradient descent algorithm?
16,640,470
7
2013-05-19T23:13:00Z
16,648,182
10
2013-05-20T11:09:18Z
[ "python", "machine-learning", "gradient-descent" ]
I started to learn the machine learning last week. when I want to make a gradient descent script to estimate the model parameters, I came across a problem: How to choose a appropriate learning rate and variance。I found that,different (learning rate,variance) pairs may lead to different results, some times you eve...
Plotting is the best way to see how your algorithm is performing. To see if you have achieved convergence you can plot the evolution of the cost function after each iteration, after a certain given of iteration you will see that it does not improve much you can assume convergence, take a look to the following code: ``...
Converting string to ordered dictionary?
16,641,110
4
2013-05-20T00:51:50Z
16,641,215
10
2013-05-20T01:05:39Z
[ "python", "python-2.7", "dictionary" ]
I have a string which basically contains a bunch of JSON formatted text that I'd ultimately like to export to Excel in "pretty print" format with the proper indentations for nesting, etc. It's imperative that the original order of key/values is retained for readability purposes. My thought process to accomplish what I...
You can use the `object_pairs_hook` argument to [JSONDecoder](http://docs.python.org/2/library/json.html#json.JSONDecoder) to change the decoded dictionaries to OrderedDict: ``` import collections import json decoder = json.JSONDecoder(object_pairs_hook=collections.OrderedDict) json_string = '{"id":"0","last_modifie...
Python's argparse choose one of several optional parameter
16,641,502
2
2013-05-20T01:55:47Z
16,641,528
8
2013-05-20T02:00:09Z
[ "python", "command-line-arguments", "argparse" ]
I have a program which can be used in the following way: ``` program install -a arg -b arg program list program update ``` There can only ever be one of the positional arguments specified (`install`, `list` or `update`). And there can only be other arguments in the `install` scenario. The argparse documentation is a...
This seems like you want to use [`subparser`s](http://docs.python.org/2/library/argparse.html#sub-commands). ``` from argparse import ArgumentParser parser = ArgumentParser() subparsers = parser.add_subparsers() install = subparsers.add_parser('install') install.add_argument('-b') install.add_argument('-a') install....
Can Perspective Broker be used over stdio instead of TCP?
16,642,374
4
2013-05-20T03:57:36Z
16,649,030
8
2013-05-20T11:58:16Z
[ "python", "twisted", "perspective-broker" ]
I'm using Twisted's Perspective Broker for RMI between a process and subprocess. Rather than listen on a TCP socket (such as by passing `reactor.listenTCP()` an instance of `PBServerFactory`) and have the subprocess connect to it, I'd prefer to use the subprocess's stdin and stdout. I've found `twisted.internet.stdio...
Using a protocol like PB between a parent and child process over a stdio-like connection has two pieces. One piece is in the child process, using file descriptors 0 and 1 to communicate with the parent. The other piece is the parent process, using whatever file descriptors correspond to the child's 0 and 1. `StandardI...
string.lower in Python 3
16,643,166
8
2013-05-20T05:32:51Z
16,643,172
11
2013-05-20T05:33:56Z
[ "python", "string", "python-3.x" ]
I had a working python script, but something must have changed in python 3. For example if I wanted to convert argument 1 to lowercase: ``` import string print(string.lower(sys.argv[1])) ``` It says that `'module' object has no attribute 'lower'` - OK, I understand, `string` is a module now. If I remove the import,...
You can use `sys.argv[1].lower()` ``` >>> "FOo".lower() 'foo' ``` `lower()` is a method of string objects itself. `string` module has been changed in Python 3, it no longer contains the methods related to `str` objects, it now only contains the constants mentioned below. You can also use `str.lower("Mystring")` but...
pandas convert strings to float for multiple columns in dataframe
16,643,695
9
2013-05-20T06:23:34Z
16,648,510
10
2013-05-20T11:29:21Z
[ "python", "pandas" ]
I'm new to pandas and trying to figure out how to convert multiple columns which are formatted as strings to float64's. Currently I'm doing the below, but it seems like apply() or applymap() should be able to accomplish this task even more efficiently...unfortunately I'm a bit too much of a rookie to figure out how. Cu...
Starting in 0.11.1 (coming out this week), replace has a new option to replace with a regex, so this becomes possible ``` In [14]: df = DataFrame('10.0%',index=range(100),columns=range(10)) In [15]: df.replace('%','',regex=True).astype('float')/100 Out[15]: <class 'pandas.core.frame.DataFrame'> Int64Index: 100 entri...
When splitting an empty string in Python, why does split() return an empty list while split('\n') returns ['']?
16,645,083
89
2013-05-20T08:02:32Z
16,645,130
24
2013-05-20T08:06:28Z
[ "python", "string", "split" ]
I am using `split('\n')` to get lines in one string, and found that `''.split()` returns an empty list, `[]`, while `''.split('\n')` returns `['']`. Is there any specific reason for such a difference? And is there any more convenient way to count lines in a string?
It seems to simply be the way it's supposed to work, according to [the documentation](http://docs.python.org/2/library/stdtypes.html#str.split): > Splitting an empty string with a specified separator returns `['']`. > > If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive...
When splitting an empty string in Python, why does split() return an empty list while split('\n') returns ['']?
16,645,083
89
2013-05-20T08:02:32Z
16,645,307
176
2013-05-20T08:18:51Z
[ "python", "string", "split" ]
I am using `split('\n')` to get lines in one string, and found that `''.split()` returns an empty list, `[]`, while `''.split('\n')` returns `['']`. Is there any specific reason for such a difference? And is there any more convenient way to count lines in a string?
> Question: I am using split('\n') to get lines in one string, and found that > ''.split() returns empty list [], while ''.split('\n') returns ['']. The [*str.split()*](http://docs.python.org/2.7/library/stdtypes.html#str.split) method has two algorithms. If no arguments are given, it splits on repeated runs of whites...
How to create a word cloud from a corpus in Python?
16,645,799
15
2013-05-20T08:51:42Z
16,739,431
30
2013-05-24T16:17:17Z
[ "python", "nltk", "corpus", "gensim", "word-cloud" ]
From [Creating a subset of words from a corpus in R](http://stackoverflow.com/questions/15502802/creating-a-subset-of-words-from-a-corpus-in-r), the answerer can easily convert a `term-document matrix` into a word cloud easily. Is there a similar function from python libraries that takes either a raw word textfile or ...
Here's a blog post which does just that: <http://peekaboo-vision.blogspot.com/2012/11/a-wordcloud-in-python.html> The whole code is here: <https://github.com/amueller/word_cloud>
How to create a word cloud from a corpus in Python?
16,645,799
15
2013-05-20T08:51:42Z
16,799,878
8
2013-05-28T19:26:52Z
[ "python", "nltk", "corpus", "gensim", "word-cloud" ]
From [Creating a subset of words from a corpus in R](http://stackoverflow.com/questions/15502802/creating-a-subset-of-words-from-a-corpus-in-r), the answerer can easily convert a `term-document matrix` into a word cloud easily. Is there a similar function from python libraries that takes either a raw word textfile or ...
In case you require these word clouds for showing them in website or web app you can convert your data to json or csv format and load it to a JavaScript visualisation library such as [d3](http://d3js.org/). [Word Clouds on d3](http://www.jasondavies.com/wordcloud/) If not, Marcin's answer is a good way for doing what ...
The fastest way to find common elements at the beginning of 2 python lists?
16,646,062
4
2013-05-20T09:08:19Z
16,646,215
11
2013-05-20T09:15:52Z
[ "python", "list" ]
What is the fastest way to find common elements at the beginning of two python lists? I coded it using for loop but I think that writing it with list comprehensions would be faster... unfortunately I don't know how to put a break in a list comprehension. This is the code I wrote: ``` import datetime list1=[1,2,3,4,5,...
``` >>> from operator import ne >>> from itertools import count, imap, compress >>> list1[:next(compress(count(), imap(ne, list1, list2)), 0)] [1, 2] ``` Timings: ``` from itertools import * from operator import ne def f1(list1, list2, enumerate=enumerate, izip=izip): out = [] out_append = out.append for...
Crop an image in the centre using PIL
16,646,183
6
2013-05-20T09:14:30Z
16,648,197
13
2013-05-20T11:09:48Z
[ "python", "python-imaging-library", "crop" ]
How can I crop an image in the center? Because I know that the box is a 4-tuple defining the left, upper, right, and lower pixel coordinate but I don't know how to get these coordinates so it crops in the center.
Assuming you know the size you would like to crop to (new\_width X new\_height): ``` import Image im = Image.open(<your image>) width, height = im.size # Get dimensions left = (width - new_width)/2 top = (height - new_height)/2 right = (width + new_width)/2 bottom = (height + new_height)/2 im.crop((left, top, righ...
setting the timeout on a urllib2.request() call
16,646,322
10
2013-05-20T09:22:06Z
16,646,486
22
2013-05-20T09:31:50Z
[ "python", "urllib2" ]
I need to set the timeout on `urllib2.request()`. I do not use `urllib2.urlopen()` since i am using the `data` parameter of `request`. How can I set this?
Although `urlopen` does accept `data` param for `POST`, you can call `urlopen` on a `Request` object like this, ``` import urllib2 request = urllib2.Request('http://www.example.com', data) response = urllib2.urlopen(request, timeout=4) content = response.read() ```
Calling C functions in Python
16,647,186
6
2013-05-20T10:11:38Z
16,647,916
16
2013-05-20T10:52:41Z
[ "python", "c", "ctypes", "cython" ]
I have a bunch of functions that I've written in C and I'd like some code I've written in Python to be able to access those functions. I've read several questions on here that deal with a similar problem ([here](http://stackoverflow.com/questions/145270/calling-c-c-from-python) and [here](http://stackoverflow.com/ques...
You should call C from Python by writing a **ctypes** wrapper. Cython is for making python-like code run faster, ctypes is for making C functions callable from python. What you need to do is the following: 1. Write the C functions you want to use. (You probably did this already) 2. Create a shared object (.so, for lin...
How to change fontsize in excel using python
16,648,134
7
2013-05-20T11:06:44Z
16,648,387
11
2013-05-20T11:21:04Z
[ "python", "excel", "xlwt" ]
I have to create a content with font as Times New Roman and font size as 16.How to create using python script ? ## My sample script ``` import xlwt workbook = xlwt.Workbook(encoding = 'ascii') worksheet = workbook.add_sheet('My Worksheet') font = xlwt.Font() # Create the Font font.name = 'Times New Roman' style = xlw...
You set the font's height in "twips", which are 1/20 of a point: ``` font.height = 320 # 16 * 20, for 16 point ```
Python regex - Match words only containing A, B, or C
16,650,226
2
2013-05-20T13:06:07Z
16,650,240
8
2013-05-20T13:06:49Z
[ "python", "regex", "match" ]
What regex expression can I use to match words that are made of up ONLY the characters A, B, or C? For example the regex would catch ABCBACBACBABBABCC and A and B and C but would not catch ABCD, ABC1, etc.
What about `\b[ABC]+\b`? Does that work? ``` >>> regex = re.compile(r'\b[ABC]+\b') >>> regex.match('AACCD') #No match >>> regex.match('AACC') #match <_sre.SRE_Match object at 0x11bb578> >>> regex.match('A') #match <_sre.SRE_Match object at 0x11bb5e0> ``` `\b` is a word boundary. So here we match anything that...
Updating object properties in list comprehension way
16,650,369
3
2013-05-20T13:13:54Z
16,650,466
11
2013-05-20T13:19:15Z
[ "python", "list-comprehension" ]
Is that possible, in Python, to update a list of objects in list comprehension or some similar way? For example, I'd like to set property of all objects in the list: ``` result = [ object.name = "blah" for object in objects] ``` or with `map` function ``` result = map(object.name = "blah", objects) ``` Could it be ...
Ultimately, assignment is a "Statement", not an "Expression", so it can't be used in a lambda expression or list comprehension. You need a regular function to accomplish what you're trying. There is a builtin which will do it (returning a list of `None`): ``` [setattr(obj,'name','blah') for obj in objects] ``` But *...
How to save Scrapy crawl Command output
16,650,397
3
2013-05-20T13:15:12Z
16,650,605
7
2013-05-20T13:26:25Z
[ "python", "scrapy" ]
I am trying to save the output of the scrapy crawl command I have tried `scrapy crawl someSpider -o some.json -t json >> some.text` But it doesn't worked ...can some body tell me how i can save output to a text file....I mean the logs and information printed by scrapy...
You need to redirect stderr too. You are redirecting only stdout. You can redirect it somehow like this: `scrapy crawl someSpider -o some.json -t json 2> some.text` The key is number 2, which "selects" stderr as source for redirection. If you would like to redirect both stderr and stdout into one file, you can use: ...
how to make a efficient filter in python
16,651,176
3
2013-05-20T13:58:09Z
16,651,468
7
2013-05-20T14:13:00Z
[ "python" ]
I have a problem with two very large files(each more then 1.000.000 entries) in python: I need to generate a filter and I dont know why, I have two files like this: ``` 1,2,3 2,4,5 3,3,4 ``` and the second ``` 1,"fege" 2,"greger" 4,"feffg" ``` the first item of each file row is always the ID. Now I want to filter t...
``` [row for row in myRows if row[0] == item[0]] ``` is doing a linear scan for each `item`. If you use a `set` instead, you can bring this down to an expected constant time operation. First, read in the second file to get a `set` of valid ids: ``` with open("secondfile") as f: # note: only storing the ids, not t...
Python all() method
16,651,310
3
2013-05-20T14:04:27Z
16,651,363
7
2013-05-20T14:06:38Z
[ "python" ]
I'm wondering how the below result yields True.None of the condition is True? Any inputs? ``` >>> listitem=['a','h','o','t'] >>> valid_compare_diff ['0', '1', '2', '3', '4'] >>> all(x for x in listitem if x in valid_compare_diff) True ``` New changes:- ``` >>> listitem=['0'] >>> valid_compare_diff ['0', '1', '2', '...
The comprehension will be empty as no value of `x` meets the condition: `if x in valid_compare_diff` Hence: ``` >>> [x for x in listitem if x in valid_compare_diff] [] ``` results in `[]`, which when passed to `all` returns `True` ``` >>> all([]) True ``` This is so because the definition of `all` states that if ...
Pylint says 'string' module is deprecated. What's the new way to get range of lowercase characters?
16,651,323
11
2013-05-20T14:04:58Z
16,651,393
18
2013-05-20T14:08:41Z
[ "python", "pylint" ]
I was just pylinting some code and noticed a colleague had imported the old Python 'string' module, not to use any functions from it but simply to have access to the constant '**string.lowercase**'. I removed the deprecated import and substituted 'abcdef...' for string.lowercase, but I was wondering: is there a better...
`string` itself is not deprecated, just those methods like `string.join` that are better accessed through a string object. You can still import `string`, and get `string.ascii_lowercase` for what you want. pylint's reporting this as an error is a known bug - see <http://www.logilab.org/ticket/2481>.
Python iterate slice object
16,652,482
2
2013-05-20T15:05:31Z
16,652,549
9
2013-05-20T15:09:17Z
[ "python", "iteration", "slice" ]
If I have a slice object ``` s = slice(a,b,c) ``` and an array length `n`, is there a nice readymade iterator for the elements so that I can do something like: ``` for index in FUNCTION_I_WANT(s, n): do_whatever(index) ``` and have it behave like slicing of lists, beyond the really horrible: ``` def HACKY_VERS...
``` def FUNCTION_I_WANT(s, n): return range(*s.indices(n)) ```
Future-compatible enums in 2.7?
16,653,129
23
2013-05-20T15:40:55Z
21,394,224
14
2014-01-27T23:51:51Z
[ "python", "enums" ]
Many methods of implementing enums are shown in the answers to [this question](http://stackoverflow.com/questions/36932/how-can-i-represent-an-enum-in-python). However, [PEP0435](http://www.python.org/dev/peps/pep-0435/) is out now and describes how Enum and IntEnum will become official in Python 3.4. My question is n...
There is a backport of the PEP 435 enum module available on PyPI as [enum34](https://pypi.python.org/pypi/enum34/). The backport seems to be unofficial, however it is authored by Ethan Furman, who is a Python core committer and one of the co-authors of PEP 435. The backport is declared compatible with Python 2.4 and g...
Python/Flask best practice for service layer
16,653,421
6
2013-05-20T15:55:34Z
16,672,977
11
2013-05-21T14:48:46Z
[ "python", "flask" ]
I'm a little new to Python ( I come from a Java/C++ background ). I've been playing around with Flask for web development. My question relates somewhat to dependecy injection and thread safety. In the Java/Spring word you would have a Controller that has a Service say UserService injected into it. And when you have say...
As with all things thread-related, the question is "did you make it thread-safe"? If your user service looks like this: ``` # user_service.py from some.package import database def add_user(user_information=None): db = database.connect() db.insert(user_information) def update_user(user_information=None): ...
Python: Random Numbers into a List
16,655,089
9
2013-05-20T17:40:10Z
16,655,123
8
2013-05-20T17:42:14Z
[ "python", "list", "random" ]
Question: Create a 'list' called my\_randoms of 10 random numbers between 0 and 100. This is what I have so far: ``` import random my_randoms=[] for i in range (10): my_randoms.append(random.randrange(1,101,1)) print (my_randoms) ``` Unfortunately python's output is this: ``` [34] [34, 30] [...
Fix the indentation of the `print` statement ``` import random my_randoms=[] for i in range (10): my_randoms.append(random.randrange(1,101,1)) print (my_randoms) ```
Python: Random Numbers into a List
16,655,089
9
2013-05-20T17:40:10Z
16,655,135
17
2013-05-20T17:43:25Z
[ "python", "list", "random" ]
Question: Create a 'list' called my\_randoms of 10 random numbers between 0 and 100. This is what I have so far: ``` import random my_randoms=[] for i in range (10): my_randoms.append(random.randrange(1,101,1)) print (my_randoms) ``` Unfortunately python's output is this: ``` [34] [34, 30] [...
``` import random my_randoms=[random.randrange(1,101,1) for _ in range (10)] ```
Python: Random Numbers into a List
16,655,089
9
2013-05-20T17:40:10Z
16,655,177
32
2013-05-20T17:45:30Z
[ "python", "list", "random" ]
Question: Create a 'list' called my\_randoms of 10 random numbers between 0 and 100. This is what I have so far: ``` import random my_randoms=[] for i in range (10): my_randoms.append(random.randrange(1,101,1)) print (my_randoms) ``` Unfortunately python's output is this: ``` [34] [34, 30] [...
You could use `random.sample` to generate the list with one call: ``` import random my_randoms = random.sample(xrange(100), 10) ``` That generates numbers in the (inclusive) range from 0 to 99. If you want 1 to 100, you could use this (thanks to @martineau for pointing out my convoluted solution): ``` my_randoms = r...
django abstract models versus regular inheritance
16,655,097
35
2013-05-20T17:40:56Z
16,655,355
19
2013-05-20T17:55:01Z
[ "python", "django" ]
Besides the syntax, what's the difference between using a django abstract model and using plain Python inheritance with django models? Pros and cons? UPDATE: I think my question was misunderstood and I received responses for the difference between an abstract model and a class that inherits from django.db.models.Model...
An abstract model creates a table with the entire set of columns for each subchild, whereas using "plain" Python inheritance creates a set of linked tables (aka "multi-table inheritance"). Consider the case in which you have two models: ``` class Vehicle(models.Model): num_wheels = models.PositiveIntegerField() cl...
django abstract models versus regular inheritance
16,655,097
35
2013-05-20T17:40:56Z
16,838,663
62
2013-05-30T14:19:54Z
[ "python", "django" ]
Besides the syntax, what's the difference between using a django abstract model and using plain Python inheritance with django models? Pros and cons? UPDATE: I think my question was misunderstood and I received responses for the difference between an abstract model and a class that inherits from django.db.models.Model...
> I actually want to know the difference between a model class that > inherits from a django abstract class (Meta: abstract = True) and a > plain Python class that inherits from say, 'object' (and not > models.Model). Django will only generate tables for subclasses of `models.Model`, so the former... ``` class User(m...
Multiprocessing - Process owns my computer
16,656,199
2
2013-05-20T18:43:57Z
16,656,326
8
2013-05-20T18:51:08Z
[ "python", "python-2.7", "multiprocessing" ]
I was just having a go with how to use the multiprocessing.Lock() Working from the examples on: <http://docs.python.org/2/library/multiprocessing.html> This example in fact: ``` from multiprocessing import Process, Lock def f(l, i): l.acquire() print 'hello world', i l.release() if __name__ == '__main...
Your script doesn't take over my Ubuntu computer, but it will take over a Windows computer. Here's the explanation: `multiprocessing` requires that the child processes be able to [`import __main__`](http://docs.python.org/2/library/multiprocessing.html#introduction). What happens on \*NIX is that the child processes a...
How to use Unicode characters in a python string
16,658,068
4
2013-05-20T20:44:22Z
16,658,101
9
2013-05-20T20:46:19Z
[ "python", "string", "unicode" ]
I'd like to be able to use unicode in my python string. For instance I have an icon: ``` icon = '&#x25B2;' print icon ``` which should create icon = '▲' but instead it literally returns it in string form: `&#x25B2;` How can I make this string recognize unicode? Thank you for your help in advance.
You can use string escape sequences, as documented in [the “string and bytes literals” section](http://docs.python.org/3/reference/lexical_analysis.html#index-18) of the language reference. For Python 3 this would work simply like this: ``` >>> icon = '\u25b2' >>> print(icon) ▲ ``` In [Python 2](http://docs.pyt...
SublimeLinter not obeying "pep8_ignore" settings
16,660,030
5
2013-05-20T23:50:45Z
16,660,466
7
2013-05-21T00:50:02Z
[ "python", "sublimetext2" ]
I am using Sublime Linter and cannot get PEP 8 (W191) to go away with the following settings. Why? ``` { "color_scheme": "Packages/Color Scheme - Default/Mac Classic.tmTheme", "fold_buttons": false, "font_face": "SourceCodePro-Regular", "font_size": 13.0, "ignored_packages": [ "Vintage"...
Try setting `Packages/User/SublimeLinter.sublime-settings` to the following: ``` { "pep8": false, "pep8_ignore": [ "W191" ] } ``` and see if that fixes things. SublimeLinter may not be looking in your regular user settings file for these options.
Extracting arguments from kwargs in boost::python
16,660,049
6
2013-05-20T23:52:55Z
16,671,616
10
2013-05-21T13:44:29Z
[ "c++", "python", "boost-python", "kwargs" ]
I have a C++ class that I'm building into a python module using boost::python. I have a few functions that I want to take keyword arguments. I've set up wrapper functions to pass to raw\_arguments and that works fine, but I want to build in some error checking for the function arguments. Is there a standard way to do t...
The [`boost/python/args.hpp`](http://www.boost.org/doc/libs/1_53_0/libs/python/doc/v2/args.html) file provides a family of classes for specifying argument keywords. In particular, Boost.Python provides an [`arg`](http://www.boost.org/doc/libs/1_53_0/libs/python/doc/v2/args.html#arg-spec) type, that represents a potenti...
Is a function call an expression in python?
16,660,271
2
2013-05-21T00:25:16Z
16,660,288
7
2013-05-21T00:26:48Z
[ "python", "function", "call", "expression" ]
According to [this answer](http://stackoverflow.com/a/4782649/2403580), a function call is a statement, but in the course I'm following in Coursera they say a function call is an expression. *So this is my guess: a function call does something, that's why it's a statement, but after it's called it evaluates and passes...
A call is [an expression](http://docs.python.org/2/reference/expressions.html#calls); it is listed in the Expressions reference documentation. If it was a statement, you could not use it as part of an expression; statements *can* contain expressions, but not the other way around. As an example, `return expression` is...
Different results when using sklearn RandomizedPCA with sparse and dense matrices
16,660,771
3
2013-05-21T01:31:00Z
16,665,760
7
2013-05-21T08:49:37Z
[ "python", "numpy", "scipy", "scikit-learn" ]
I am getting different results when `Randomized PCA` with sparse and dense matrices: ``` import numpy as np import scipy.sparse as scsp from sklearn.decomposition import RandomizedPCA x = np.matrix([[1,2,3,2,0,0,0,0], [2,3,1,0,0,0,0,3], [1,0,0,0,2,3,2,0], [3,0,0,0,4,5,6,0]...
In the case of the sparse data, the `RandomizedPCA` does not center the data (mean removal) as it might blow up the memory usage. That probably explains what you observe. I agree this "feature" is poorly documented. Please feel free to report an issue on github to track it and improve the doc. **Edit**: we fixed that...
Difference between plt.close() and plt.clf()
16,661,790
6
2013-05-21T03:47:04Z
16,661,815
8
2013-05-21T03:50:01Z
[ "python", "matplotlib" ]
In Python, what is the difference between `plt.clf()` and `plt.close()`? Will they function the same way?
`plt.close()` will close the figure window entirely, where `plt.clf()` will just clear the figure - you can still paint another plot onto it. It sounds like, for your needs, you should be preferring `plt.clf()`, or better yet keep a handle on the line objects themselves (they are returned in lists by `plot` calls) and...
Why does __mro__ not show up in dir(MyClass)?
16,663,514
5
2013-05-21T06:29:06Z
16,663,643
9
2013-05-21T06:38:25Z
[ "python", "method-resolution-order" ]
``` class MyClass(object): pass print MyClass.__mro__ print dir(MyClass) ``` Output: ``` (<class '__main__.MyClass'>, <type 'object'>) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', ...
From the Python documentation: > Because dir() is supplied primarily as a convenience for use at an > interactive prompt, it tries to supply an interesting set of names > more than it tries to supply a rigorously or consistently defined set > of names, and its detailed behavior may change across releases. For > exampl...
Why does __mro__ not show up in dir(MyClass)?
16,663,514
5
2013-05-21T06:29:06Z
18,035,950
8
2013-08-03T18:27:49Z
[ "python", "method-resolution-order" ]
``` class MyClass(object): pass print MyClass.__mro__ print dir(MyClass) ``` Output: ``` (<class '__main__.MyClass'>, <type 'object'>) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', ...
I was recently wondering the same thing. I was looking for an answer more in line with "What about Python's implementation causes `mro`/`__mro__` not to be listed in `dir`? And what can I trust `dir` to list?" than simply "How does Python's documentation justify the non-inclusion of `mro` in `dir`?" I don't like it whe...
How can I add an element at the top of an OrderedDict in python?
16,664,874
28
2013-05-21T07:56:34Z
16,664,932
21
2013-05-21T07:59:45Z
[ "python", "python-3.x", "dictionary", "python-2.x", "ordereddictionary" ]
I have this ``` d1 = OrderedDict([('a', '1'), ('b', '2')]) ``` If i do this `d1.update({'c':'3'})` Then i get this `OrderedDict([('a', '1'), ('b', '2'), ('c', '3')])` but i want this ``` [('c', '3'), ('a', '1'), ('b', '2')] ``` without creating new Dictionary
There's no built-in method for doing this in Python 2. If you need this, you need to write a `prepend()` method/function that operates on the `OrderedDict` internals with O(1) complexity. For Python 3.2 and later, you can use the [`move_to_end`](https://hg.python.org/cpython/file/3.2/Lib/collections.py#l130)1 method. ...
How can I add an element at the top of an OrderedDict in python?
16,664,874
28
2013-05-21T07:56:34Z
18,080,548
10
2013-08-06T12:44:27Z
[ "python", "python-3.x", "dictionary", "python-2.x", "ordereddictionary" ]
I have this ``` d1 = OrderedDict([('a', '1'), ('b', '2')]) ``` If i do this `d1.update({'c':'3'})` Then i get this `OrderedDict([('a', '1'), ('b', '2'), ('c', '3')])` but i want this ``` [('c', '3'), ('a', '1'), ('b', '2')] ``` without creating new Dictionary
You have to make a new instance of `OrderedDict`. If your keys are unique: ``` d1=OrderedDict([("a",1),("b",2)]) d2=OrderedDict([("c",3),("d",99)]) both=OrderedDict(list(d2.items()) + list(d1.items())) print(both) #OrderedDict([('c', 3), ('d', 99), ('a', 1), ('b', 2)]) ``` But if not, beware as this behavior may or ...
How can I add an element at the top of an OrderedDict in python?
16,664,874
28
2013-05-21T07:56:34Z
18,326,914
11
2013-08-20T04:20:20Z
[ "python", "python-3.x", "dictionary", "python-2.x", "ordereddictionary" ]
I have this ``` d1 = OrderedDict([('a', '1'), ('b', '2')]) ``` If i do this `d1.update({'c':'3'})` Then i get this `OrderedDict([('a', '1'), ('b', '2'), ('c', '3')])` but i want this ``` [('c', '3'), ('a', '1'), ('b', '2')] ``` without creating new Dictionary
I just wrote a subclass of `OrderedDict` in a project of mine for a similar purpose. [Here's the gist](https://gist.github.com/jaredks/6276032). Insertion operations are also constant time `O(1)` (they don't require you to rebuild the data structure), unlike most of these solutions. ``` >>> d1 = ListDict([('a', '1'),...
why doesn't a simple python producer/consumer multi-threading program speed up by adding the number of workers?
16,665,367
2
2013-05-21T08:28:39Z
16,666,692
10
2013-05-21T09:33:27Z
[ "python", "multithreading", "queue", "producer-consumer" ]
The code below is almost identical to the python official Queue example at <http://docs.python.org/2/library/queue.html> ``` from Queue import Queue from threading import Thread from time import time import sys num_worker_threads = int(sys.argv[1]) source = xrange(10000) def do_work(item): for i in xrange(100000...
Yeah, Maxim's right concerning the GIL. But as soon as you do something worth doing in the worker, the situation changes in most cases. Typical things to be done in the threads involve waiting for I/O or other things in which a thread-switch can be done quite fine. If you don't just count numbers in your workers but in...
statsmodels: specifying non-linear regression models using patsy
16,665,833
2
2013-05-21T08:53:23Z
17,126,380
7
2013-06-15T17:57:50Z
[ "python", "regression", "statsmodels" ]
I am trying to calculate non-linear regression models using statsmodles. In particular I have problems learning the patsy syntax. Is there any tutorial or example how to formulate non-linear models using the patsy syntax? In particular, how would the non-linear model on this example (<http://statsmodels.sourceforge.n...
Patsy isn't really useful for fitting general non-linear models, but the models on the page you link to are a special sort of non-linear model -- they're using a *linear* model fitting method (OLS), and applying it to *non-linear transformations* of the basic variables. A standard and very useful trick is to combine mu...
Django GET and POST handling methods
16,668,441
3
2013-05-21T11:03:00Z
16,669,043
12
2013-05-21T11:35:55Z
[ "python", "django" ]
I want a way to automatically route GET and POST requests to subsequent methods in a centralized way. I want to create my handler in the following way. ``` class MyHandler(BaseHandler): def get(self): #handle get requests def post(self): #handle post requests ``` This is what webapp2 does and...
This is supported in Django as [class based views](https://docs.djangoproject.com/en/dev/topics/class-based-views/intro/#handling-forms-with-class-based-views). You can extend the generic class `View` and add methods like `get()`, `post()`, `put()` etc. E.g. - ``` from django.http import HttpResponse from django.views...
Python - dump dict as a json string
16,668,511
11
2013-05-21T11:07:50Z
16,668,533
29
2013-05-21T11:08:49Z
[ "python", "json" ]
What am I missing? I want to dump a dictionary as a json string. I am using python 2.7 With this code: ``` import json fu = {'a':'b'} output = json.dump(fu) ``` I get the following error: ``` Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/gevent-1.0b2-py2.7-linux-x86_64.egg/geven...
Use `json.dumps` to dump a `str` ``` >>> import json >>> json.dumps({'a':'b'}) '{"a": "b"}' ``` `json.dump` dumps to a file
SQLite cursor in Python with statement
16,668,623
3
2013-05-21T11:13:44Z
16,668,691
7
2013-05-21T11:17:21Z
[ "python", "sqlite", "cursor" ]
I have the following code: ``` def executeOne(self, query, parameters): with self.connection as cursor: cursor.execute(query, parameters) return cursor.fetchone() ``` When I call this method, it throws me the following error: `AttributeError: 'sqlite3.Connection' object has no attribute '...
The reason you are receiving the error is because the connection class does not have a method called `fetchone`. You need add `.cursor()` to create an instance of cursor and then wrap it with [closing](http://docs.python.org/2/library/contextlib.html#contextlib.closing) for it to work in a [with](http://docs.python.org...
Process very large (>20GB) text file line by line
16,669,428
14
2013-05-21T11:56:45Z
16,669,683
14
2013-05-21T12:09:48Z
[ "python", "line" ]
I have a number of very large text files which I need to process, the largest being about 60GB. Each line has 54 characters in seven fields and I want to remove the last three characters from each of the first three fields - which should reduce the file size by about 20%. I am brand new to Python and have a code whic...
It's more idiomatic to write your code like this ``` def ProcessLargeTextFile(): with open("filepath", "r") as r, open("outfilepath", "w") as w: for line in r: x, y, z = line.split(' ')[:3] w.write(line.replace(x,x[:-3]).replace(y,y[:-3]).replace(z,z[:-3])) ``` The main saving here...
Process very large (>20GB) text file line by line
16,669,428
14
2013-05-21T11:56:45Z
16,670,334
9
2013-05-21T12:43:53Z
[ "python", "line" ]
I have a number of very large text files which I need to process, the largest being about 60GB. Each line has 54 characters in seven fields and I want to remove the last three characters from each of the first three fields - which should reduce the file size by about 20%. I am brand new to Python and have a code whic...
Measure! You got quite some useful hints how to improve your python code and I agree with them. But you should first figure out, what your real problem is. My first steps to find your bottleneck would be: * Remove any processing from your code. Just read and write the data and measure the speed. If just reading and wr...
Request fields in Python Facebook SDK
16,669,977
3
2013-05-21T12:25:50Z
18,452,313
13
2013-08-26T20:16:43Z
[ "python", "facebook" ]
This is the way I am currently fetching the `/me` object: `self.facebook_user = facebook.GraphAPI(access_token).get_object('me')` But if I want, for example, to request only the `name` and `id` fields from `/me`, how do I build the request?
You can pass in extra query parameters using \*\*args: ``` graph = facebook.GraphAPI(access_token) profile = graph.get_object('me') args = {'fields' : 'id,name,email', } profile = graph.get_object('me', **args) ```
python format string thousand separator with spaces
16,670,125
16
2013-05-21T12:34:11Z
18,891,054
14
2013-09-19T09:30:55Z
[ "python", "string-formatting" ]
For printing number with thousand separator, one can use the python format string : ``` '{:,}'.format(1234567890) ``` But how can I specify that I want a space for thousands separator?
Here is bad but simple solution if you don't want to mess with `locale`: ``` '{:,}'.format(1234567890.001).replace(',', ' ') ```
How to perform arithmetic operation on a date in Python?
16,670,601
15
2013-05-21T12:57:53Z
16,670,674
33
2013-05-21T13:01:00Z
[ "python", "datetime", "python-2.7" ]
I have a date column in csv file say `Date` having dates in this format `04/21/2013` and I have one more column `Next_Day`. In `Next_Day` column I want to populate the date which comes immediately after the date mentioned in date column. For eg. if date column has `04/21/2013` as date then I want `04/22/2013` in Next\_...
``` >>> import datetime >>> s = '04/21/2013' >>> d = datetime.datetime.strptime(s, '%m/%d/%Y') + datetime.timedelta(days=1) >>> print d.strftime('%m/%d/%Y') 04/22/2013 ```
Python: Variance of a list of defined numbers
16,670,658
4
2013-05-21T13:00:08Z
26,957,270
8
2014-11-16T13:09:59Z
[ "python", "list", "numbers", "variance", "defined" ]
I am trying to make a function that prints the variance of a list of defined numbers: ``` grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5] ``` So far, I have tried proceeding on making these three functions: ``` def grades_sum(my_list): total = 0 for grade in my_list: total += grad...
Try [numpy](http://docs.scipy.org/doc/numpy/reference/generated/numpy.var.html#numpy.var). ``` import numpy as np variance = np.var(grades) ```
Specifying date format when converting with pandas.to_datetime
16,672,237
12
2013-05-21T14:12:21Z
16,672,514
10
2013-05-21T14:25:47Z
[ "python", "datetime", "pandas" ]
I have data in a csv file with dates stored as strings in a standard UK format - `%d/%m/%Y` - meaning they look like: ``` 12/01/2012 30/01/2012 ``` The examples above represent 12 January 2012 and 30 January 2012. When I import this data with pandas version 0.11.0 I applied the following transformation: ``` import ...
You can use the `parse_dates` option from `read_csv` to do the conversion directly while reading you data. The trick here is to use `dayfirst=True` to indicate your dates start with the day and not with the month. See here for more information: <http://pandas.pydata.org/pandas-docs/dev/generated/pandas.io.parsers.rea...
Specifying date format when converting with pandas.to_datetime
16,672,237
12
2013-05-21T14:12:21Z
16,673,019
7
2013-05-21T14:51:02Z
[ "python", "datetime", "pandas" ]
I have data in a csv file with dates stored as strings in a standard UK format - `%d/%m/%Y` - meaning they look like: ``` 12/01/2012 30/01/2012 ``` The examples above represent 12 January 2012 and 30 January 2012. When I import this data with pandas version 0.11.0 I applied the following transformation: ``` import ...
*I think you are calling it correctly, and I posted this as [an issue on github](https://github.com/pydata/pandas/issues/3669).* You can just specify the format to `to_datetime` directly, for example: ``` In [1]: s = pd.Series(['12/1/2012', '30/01/2012']) In [2]: pd.to_datetime(s, format='%d/%m/%Y') Out[2]: 0 2012...
python - can lambda have more than one return
16,674,004
13
2013-05-21T15:39:58Z
16,674,025
13
2013-05-21T15:40:54Z
[ "python", "lambda", "tuples" ]
I know lambda doesn't have a return expression. Normally ``` def one_return(a): #logic is here c = a + 1 return c ``` can be written: ``` lambda a : a + 1 ``` How about write this one in a lambda function: ``` def two_returns(a, b): # logic is here c = a + 1 d = b * 1 return c, d ```
Sure: ``` lambda a, b: (a + 1, b * 1) ```
python - can lambda have more than one return
16,674,004
13
2013-05-21T15:39:58Z
16,674,029
8
2013-05-21T15:41:00Z
[ "python", "lambda", "tuples" ]
I know lambda doesn't have a return expression. Normally ``` def one_return(a): #logic is here c = a + 1 return c ``` can be written: ``` lambda a : a + 1 ``` How about write this one in a lambda function: ``` def two_returns(a, b): # logic is here c = a + 1 d = b * 1 return c, d ```
what about: ``` lambda a,b: (a+1,b*1) ```
python - can lambda have more than one return
16,674,004
13
2013-05-21T15:39:58Z
16,674,091
19
2013-05-21T15:43:46Z
[ "python", "lambda", "tuples" ]
I know lambda doesn't have a return expression. Normally ``` def one_return(a): #logic is here c = a + 1 return c ``` can be written: ``` lambda a : a + 1 ``` How about write this one in a lambda function: ``` def two_returns(a, b): # logic is here c = a + 1 d = b * 1 return c, d ```
Yes, it's possible. Because an expression such as this at the end of a function: ``` return a, b ``` Is equivalent to this: ``` return (a, b) ``` And there, you're really returning a single value: a tuple which happens to have two elements. So it's ok to have a lambda return a tuple, because it's a single value: `...
What is the cleanest way to stop a python multiprocessing worker attached to a queue in an infinite loop?
16,674,485
16
2013-05-21T16:03:31Z
16,708,797
12
2013-05-23T08:12:48Z
[ "python", "multiprocessing", "gevent", "defunct" ]
I'm implementing a producer-consumer pattern in python using `multiprocessing.Pool` and `multiprocessing.Queue`. Consumers are pre-forked processes that uses `gevent` to spawn multiple tasks. Here is a trimmed down version of code: ``` import gevent from Queue import Empty as QueueEmpty from multiprocessing import Pr...
I figured out the problem. According to [documentation for `multiprocessing.Pool.join()`](http://docs.python.org/2/library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.join), `pool` needs to be `close()ed` before it can be `join()ed`. Adding `pool.close()` before `pool.join()` solved the problem.
Python/gspread - how can I update multiple cells with DIFFERENT VALUES at once?
16,675,258
4
2013-05-21T16:44:15Z
16,675,639
8
2013-05-21T17:06:41Z
[ "python", "google-app-engine", "google-spreadsheet", "gspread" ]
To update a range of cells, you use the following command. ``` ## Select a range cell_list = worksheet.range('A1:A7') for cell in cell_list: cell.value = 'O_o' ## Update in batch worksheet.update_cells(cell_list) ``` For my application, I would like it to update an entire range, but I am trying to set a differe...
You can use enumerate on a separate list containing the different values you want in the cells and use the index part of the tuple to match to the appropriate cells in cell\_list. ``` cell_list = worksheet.range('A1:A7') cell_values = [1,2,3,4,5,6,7] for i, val in enumerate(cell_values): #gives us a tuple of an inde...
Python: Making sense of references
16,675,351
5
2013-05-21T16:49:01Z
16,675,699
8
2013-05-21T17:10:41Z
[ "python", "numpy" ]
I understand basic python references like the difference between a+=b and a=a+b, but this confuses me. ``` import numpy as np arr1 = np.arange(6).reshape(2,3) arr2 = arr1[0] arr2 is arr1[0] #returns False, when I expect True arr1[0] = [7,8,9] arr2 #[7,8,9], when I expect [0,1,2] since the 'is' returned False ``` What...
When you index the numpy array, you create a new view (which is itself a numpy array). This is a different object, so `is` fails, but it's a view of the same piece of honestly-actually-on-the-hardware memory. When you modify that view, you therefore modify that bit of memory of which there may be another view. Edit: Y...
Python - Parsing JSON Data Set
16,675,849
4
2013-05-21T17:18:28Z
16,677,201
10
2013-05-21T18:40:11Z
[ "python", "json", "dictionary" ]
I am trying to parse a JSON data set that looks something like this: ``` {"data":[ { "Rest":0, "Status":"The campaign is moved to the archive", "IsActive":"No", "StatusArchive":"Yes", "Login":"some_login", "ContextStrategyName":"Default", "CampaignID":1111111, "StatusShow":"No", ...
Access dictionaries with `d[dict_key]` or `d.get(dict_key, default)` (to provide default value): ``` jsonResponse=json.loads(decoded_response) jsonData = jsonResponse["data"] for item in jsonData: name = item.get("Name") campaignID = item.get("CampaignID") ``` I suggest you read something about [dictionaries]...
Print the "approval" sign/check mark (✓) U+2713 in Python
16,676,101
11
2013-05-21T17:34:07Z
16,676,168
12
2013-05-21T17:37:58Z
[ "python", "unicode" ]
How can I print the check mark sign "✓" in Python? It's the sign for approval, not a square root.
You can print any Unicode character using an escape sequence. Make sure to make a Unicode string. ``` print u'\u2713' ```
Substitute class method with a string in Python
16,677,081
3
2013-05-21T18:33:56Z
16,677,136
7
2013-05-21T18:36:36Z
[ "python", "function", "md5", "substitution" ]
Lets say that I want to do this ``` hashlibAlgo = "md5" Hash= hashlib.**"hashlibAlgo"**("blah blah blah").hexdigest() ``` How can I do that. If I substitute the name of a method with a string it obviously does not work. How can I make it work? In powershell is easy, but I cannot figure it in Python.
You can get function to execute with `getattr`: ``` >>> import hashlib >>> hashlibAlgo = "md5" >>> getattr(hashlib, hashlibAlgo)("blah blah blah").hexdigest() '55e562bfee2bde4f9e71b8885eb5e303' ```
Printing lists onto tables in python
16,677,816
4
2013-05-21T19:19:12Z
16,677,909
8
2013-05-21T19:24:54Z
[ "python", "list" ]
If i had three lists such as ``` a = [1, 2, 3] b = [4, 5, 6] c = [7, 8, 9] ``` And wanted to print it like this ``` 1 4 7 2 5 8 3 6 9 ``` How would i do that?
The hard part of this is transposing the array. But that's easy, with [`zip`](http://docs.python.org/2.7/library/functions.html#zip): ``` a = [1, 2, 3] b = [4, 5, 6] c = [7, 8, 9] t = zip(a, b, c) ``` Now you just print it out: ``` print('\n'.join(' '.join(map(str, row)) for row in t)) ```
Flask-WTForms: how to check if a field is required?
16,678,317
4
2013-05-21T19:50:49Z
16,678,542
10
2013-05-21T20:05:15Z
[ "python", "templates", "flask", "jinja2", "flask-wtforms" ]
I defined a form in the following way: ``` class LoginForm(Form): login = EmailField(u'Email address', [required(), length(min=5, max=2048), validators.Email()]) password = PasswordField(u'Password', [required(), length(min=6, max=50)]) next = HiddenField() remember = BooleanField('Remember me') su...
Validators can [set flags](http://wtforms.simplecodes.com/docs/0.6.1/validators.html#setting-flags-on-the-field-with-validators) which you can check for: ``` {% if field.flags.required %}field.label(class_='required'){% endif %} ```
Python 3 How do I 'declare' an empty `bytes` variable
16,678,363
6
2013-05-21T19:53:10Z
16,678,392
19
2013-05-21T19:55:25Z
[ "python", "variables", "python-3.x", "byte", "variable-assignment" ]
How do I 'declare' an empty `bytes` variable in Python 3? I am trying to receive chunks of bytes, and later change that to a utf-8 string. However, I'm not sure how to declare the initial variable that will hold the entire series of bytes. This variable is called `msg`. I can't declare it as `None`, because you can't ...
Just use an empty byte string, `b''`. However, concatenating to a string repeatedly involves copying the string many times. A [`bytearray`](http://docs.python.org/3/library/stdtypes.html#typebytearray), which is mutable, will likely be faster: ``` msg = bytearray() # New empty byte array # Append data to the array m...
Priority of the logical statements NOT AND & OR in python
16,679,272
12
2013-05-21T20:50:47Z
16,679,309
18
2013-05-21T20:52:51Z
[ "python", "python-3.x", "boolean-expression" ]
As far as I know, in C & C++, the priority sequence for NOT AND & OR is NOT>AND>OR. But this doesn't seem to work in a similar way in Python. I tried searching for it in the Python documentation and failed (Guess I'm a little impatient.). Can someone clear this up for me?
It's NOT, AND, OR, from highest to lowest according to the documentation <http://docs.python.org/3/reference/expressions.html> Here is the complete precedence table, lowest precedence to highest. A row has the same precedence and chains from left to right 1. lambda 2. if – else 3. or 4. and 5. not x 6. in, not in, ...
How to pass anti-forgery state to the Google Sign-In button or javascript?
16,680,977
4
2013-05-21T23:08:32Z
16,681,730
7
2013-05-22T00:43:13Z
[ "python", "google-plus" ]
I'm following this tutorial to create a sign-in button. <https://developers.google.com/+/web/signin/server-side-flow> But I don't see how the anti-forgery state is passed to the button snippet (step 4). Should there be a parameter like data-state for the button? The whole tutorial doesn't mention how the state code...
After a little poking around, I found that there's an undocumented parameter, data-state, for the button. Once I set it, I could it coming back to my callback function. ``` <div id="signinButton"> <span class="g-signin" data-scope="https://www.googleapis.com/auth/plus.login" data-clientid="YOUR_CLIEN...
c# equivalent to pythons 'a in [1, 2, 3]'
16,682,552
2
2013-05-22T02:32:26Z
16,682,639
7
2013-05-22T02:41:17Z
[ "c#", "python", "syntax" ]
Is there an equivalent to python's `a in [1, 2, 3]` in C#? I've tried `new int[]{1, 2, 3}.Contains(a)` -- which is lot uglier, but does the same. Of course, I could also do, `(a==1 || a==2 || a==3)` but with different variables and namespaces, this can get a bit clunky too.
Just throwing this out there and is completely untested. ``` public static bool In(this object obj, params object[] items) { return items.Any(o => o.Equals(obj)); } ``` I think the extension method would be what you are looking for and then just tweak the actual comparison check to suit your needs. I went with ob...
How do I read numpy source?
16,682,672
11
2013-05-22T02:45:53Z
16,683,029
19
2013-05-22T03:31:13Z
[ "python", "class", "numpy", "dir" ]
I built it myself on Python 3.3, but I can't for the life of me find the class definition of `numpy.array()`. I've looked all through the code and even found the core `C` files, but where is the dang array class?? Can anyone tell me what directory to look in, or how to find out from the python shell?
* `np.array` is not a class itself, just a convenience function to create an `np.ndarray` * `ndarray` is just aliased to multiarray, which is implemented in C code (I think in an .so i.e. shared object, compiled code) * You can start looking at the ndarray interfaces here in [numeric.py](https://github.com/numpy/numpy/...
Why does Python have a format function as well as a format method
16,683,518
28
2013-05-22T04:33:40Z
16,683,882
33
2013-05-22T05:09:44Z
[ "python", "string", "format", "python-2.6", "builtin" ]
The [`format`](http://docs.python.org/2/library/functions.html#format) function in builtins seems to be like a subset of the [`str.format`](http://docs.python.org/2/library/stdtypes.html#str.format) method used specifically for the case of a formatting a single object. eg. ``` >>> format(13, 'x') 'd' ``` is apparent...
**tldr;** `format` just calls `obj.__format__` and is used by the `str.format` method which does even more higher level stuff. For the lower level it makes sense to teach an object how to format itself. # It is just syntactic sugar The fact that this function shares the name and format specification with `str.format`...
What is this operator *= -1
16,683,720
4
2013-05-22T04:53:48Z
16,683,793
12
2013-05-22T05:01:31Z
[ "python" ]
I'm going through some Python activities and was given example code with this operator: `y *= -1` I had a look through the [relevant Python docs](http://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not), to no avail. I know `y += 1`, for example, is short for `y = y + 1`. So is this `y = y * -1` ...
In the vast majority of the cases ``` y *= <expr> ``` is the same as ``` y = y * <expr> ``` but in the general case, it is interpreted as: ``` y = imul(y, <expr>) ``` which is then equivalent to: ``` y = y.__imul__(<expr>) ``` if `y`'s type overrides [`__imul__`](http://docs.python.org/2/library/operator.html#o...
Pandas group by operations on a data frame
16,684,346
3
2013-05-22T05:49:14Z
16,684,449
9
2013-05-22T05:57:04Z
[ "python", "pandas" ]
I have a pandas data frame like the one below. ``` UsrId JobNos 1 4 1 56 2 23 2 55 2 41 2 5 3 78 1 25 3 1 ``` I group by the data frame based on the UsrId. The grouped data frame will conceptually look like below. ``` UsrId JobNos 1 [4,56,25] ...
Something like `df.groupby('UsrId').JobNos.sum().idxmax()` should do it: ``` In [1]: import pandas as pd In [2]: from StringIO import StringIO In [3]: data = """UsrId JobNos ...: 1 4 ...: 1 56 ...: 2 23 ...: 2 55 ...: 2 41 ...: 2 5 ...: 3 78 ...
Finding the indices of matching elements in list in Python
16,685,384
12
2013-05-22T07:00:15Z
16,685,428
37
2013-05-22T07:02:32Z
[ "python", "list", "indexing", "find" ]
I have a long list of float numbers ranging from 1 to 5, called "average", and I want to return the list of indices for elements that are smaller than a or larger than b ``` def find(lst,a,b): result = [] for x in lst: if x<a or x>b: i = lst.index(x) result.append(i) return ...
You are using `.index()` which will only find the **first** occurrence of your value in the list. So if you have a value 1.0 at index 2, and at index 9, then `.index(1.0)` will *always* return `2`, no matter how many times `1.0` occurs in the list. Use [`enumerate()`](http://docs.python.org/2/library/functions.html#en...
SyntaxError: invalid token in datetime.datetime(2012,05,22,09,03,41)?
16,686,352
12
2013-05-22T07:53:13Z
16,686,365
18
2013-05-22T07:54:11Z
[ "python", "datetime" ]
I do something like this: ``` >>>import datetime >>>datetime.datetime(2012,05,22,05,03,41) datetime.datetime(2012, 5, 22, 5, 3, 41) >>> datetime.datetime(2012,05,22,07,03,41) datetime.datetime(2012,05,22,07,03,41) >>> datetime.datetime(2012,05,22,9,03,41) datetime.datetime(2012, 5, 22, 9, 3, 41) >>> datetime.dateti...
In Python 2, a number starting with `0` is interpreted as an *octal* number, often leading to confusion for those not familiar with C integer literal notations. In Python 3, you cannot start a number with `0` at all. Remove the leading 0s: ``` datetime.datetime(2012, 5, 22, 9, 3, 41) ``` The error is caused by `09` ...
Jinja2 Template - for loop
16,687,520
7
2013-05-22T08:55:35Z
16,689,160
10
2013-05-22T10:14:09Z
[ "python", "templates", "jinja2" ]
didn't find another post which has the similar problem, I'm trying to generate some checkboxes with flask and wtforms, at the moment I've got this piece of code: ``` <div class="control-group"> <p><strong>Check the enabled BRI Ports</strong></p> <label class="checkbox inline"> {{ form.bri1(value=1) }} ...
Try: ``` <div class="control-group"> <p><strong>Check the enabled BRI Ports</strong></p> {% for name, field in form._fields.items() %} {% if name != 'csrf_token' %} <label class="checkbox inline"> {{ field(value=1) }} {{ field.label }} </label> {% endif %...
how to get the average of dataframe column values
16,689,514
20
2013-05-22T10:32:38Z
16,689,573
42
2013-05-22T10:35:54Z
[ "python", "pandas", "dataframe" ]
``` A B DATE 2013-05-01 473077 71333 2013-05-02 35131 62441 2013-05-03 727 27381 2013-05-04 481 1206 2013-05-05 226 1733 2013-05-06 NaN 4064 2013-05-07 NaN 41151 2013-05-08 NaN ...
Simply using `df.mean()` will Do The Right Thing(tm) with respect to NaNs: ``` >>> df A B DATE 2013-05-01 473077 71333 2013-05-02 35131 62441 2013-05-03 727 27381 2013-05-04 481 1206 2013-05-05 226 1733 2013-05-06 NaN 4064 2013-05-07 NaN 41151...
Calculating the overlap distance of two 1D line segments
16,691,524
7
2013-05-22T12:16:34Z
16,691,908
21
2013-05-22T12:33:39Z
[ "python", "geometry" ]
Trying to build a function that will return the total overlapping distance between 2 line segments, denoted by start and end ints. Currently I have this: That I got off the internet somewhere, ``` def overlap(min1, max1, min2, max2): """returns the overlap between two lines that are 1D""" result = None if...
``` def overlap(min1, max1, min2, max2): return max(0, min(max1, max2) - max(min1, min2)) >>> overlap(0, 10, 80, 90) 0 >>> overlap(0, 50, 40, 90) 10 >>> overlap(0, 50, 40, 45) 5 >>> overlap(0, 100, 0, 20) 20 ```
How to download large file in python with requests.py?
16,694,907
133
2013-05-22T14:47:37Z
16,695,277
18
2013-05-22T15:02:49Z
[ "python", "stream", "python-requests" ]
[Requests](http://docs.python-requests.org/en/latest/) is a really nice library. I'd like to use it for download big files (>1GB). The problem is it's not possible to keep whole file in memory I need to read it in chunks. And this is a problem with the following code ``` import requests def DownloadFile(url) loca...
Your chunk size could be too large, have you tried dropping that - maybe 1024 bytes at a time? (also, you could use `with` to tidy up the syntax) ``` def DownloadFile(url) local_filename = url.split('/')[-1] r = requests.get(url) with open(local_filename, 'wb') as f: for chunk in r.iter_content(chu...
How to download large file in python with requests.py?
16,694,907
133
2013-05-22T14:47:37Z
16,696,317
269
2013-05-22T15:52:40Z
[ "python", "stream", "python-requests" ]
[Requests](http://docs.python-requests.org/en/latest/) is a really nice library. I'd like to use it for download big files (>1GB). The problem is it's not possible to keep whole file in memory I need to read it in chunks. And this is a problem with the following code ``` import requests def DownloadFile(url) loca...
I figured out what should be changed. The trick was to set `stream = True` in the `get()` method. After this python process stopped to suck memory (stays around 30kb regardless size of the download file). Thank you @danodonovan for you syntax I use it here: ``` def download_file(url): local_filename = url.split(...
google app engine: Error: HTTPError
16,698,621
7
2013-05-22T17:59:41Z
19,460,147
20
2013-10-18T22:42:58Z
[ "python", "google-app-engine", "python-2.7" ]
I am trying "Hello world" with python ``` import webapp2 class MainHandler(webapp2.RequestHandler): def get(self): self.response.write('Hello world!') app = webapp2.WSGIApplication([ ('/', MainHandler) ], debug=True) ``` app.yaml ``` application: engineapp version: 1 runtime: python27 api_version...
I had this very same issue with my MacOSX when using a proxy server using Google App Engine Launcher 1.8.6 behind a proxy server. Apparently there's an issue with "proxy\_bypass" on "urllib2.py". There are two possible solutions: 1. Downgrade to 1.7.5, but, who wants to downgrade? 2. Edit "[GAE Instalattion path]/goo...
How to transform an XML file using XSLT in Python?
16,698,935
32
2013-05-22T18:17:49Z
16,699,042
49
2013-05-22T18:23:50Z
[ "python", "xml", "xslt", "converter" ]
Good day! Need to convert xml using xslt in Python. I have a sample code in php. How to implement this in Python or where to find something similar? Thank you! ``` $xmlFileName = dirname(__FILE__)."example.fb2"; $xml = new DOMDocument(); $xml->load($xmlFileName); $xslFileName = dirname(__FILE__)."example.xsl"; $xsl ...
Using [lxml](http://lxml.de/), ``` import lxml.etree as ET dom = ET.parse(xml_filename) xslt = ET.parse(xsl_filename) transform = ET.XSLT(xslt) newdom = transform(dom) print(ET.tostring(newdom, pretty_print=True)) ```
What is the difference between cholesky in numpy and scipy?
16,699,163
10
2013-05-22T18:31:48Z
16,699,500
14
2013-05-22T18:51:42Z
[ "python", "numpy", "scipy" ]
I use Cholesky decomposition to sample random variables from multi-dimension Gaussian, and calculate the power spectrum of the random variables. The result I get from `numpy.linalg.cholesky` always has higher power in high frequencies than from `scipy.linalg.cholesky`. What are the differences between these two functi...
`scipy.linalg.cholesky` is giving you the upper-triangular decomposition by default, whereas `np.linalg.cholesky` is giving you the lower-triangular version. From the docs for `scipy.linalg.cholesky`: ``` cholesky(a, lower=False, overwrite_a=False) Compute the Cholesky decomposition of a matrix. Returns the C...
Python3 Error: TypeError: Can't convert 'bytes' object to str implicitly
16,699,362
20
2013-05-22T18:43:47Z
16,699,532
12
2013-05-22T18:53:59Z
[ "python", "type-conversion", "typeerror", "object-to-string" ]
I am working on exercise 41 in learnpythonthehardway and keep getting the error: ``` Traceback (most recent call last): File ".\url.py", line 72, in <module> question, answer = convert(snippet, phrase) File ".\url.py", line 50, in convert result = result.replace("###", word, 1) TypeError: Can't convert '...
`urlopen()` returns a bytes object, to perform string operations over it you should convert it to `str` first. ``` for word in urlopen(WORD_URL).readlines(): WORDS.append(word.strip().decode('utf-8')) # utf-8 works in your case ``` To get the correct charset : [How to download any(!) webpage with correct charset ...
Python3 Error: TypeError: Can't convert 'bytes' object to str implicitly
16,699,362
20
2013-05-22T18:43:47Z
16,699,591
10
2013-05-22T18:57:18Z
[ "python", "type-conversion", "typeerror", "object-to-string" ]
I am working on exercise 41 in learnpythonthehardway and keep getting the error: ``` Traceback (most recent call last): File ".\url.py", line 72, in <module> question, answer = convert(snippet, phrase) File ".\url.py", line 50, in convert result = result.replace("###", word, 1) TypeError: Can't convert '...
In Python 3, the [`urlopen` function](http://docs.python.org/3.3/library/urllib.request.html#urllib.request.urlopen) returns an [`HTTPResponse`](http://docs.python.org/3.3/library/http.client.html#httpresponse-objects) object, which acts like a binary file. So, when you do this: ``` for word in urlopen(WORD_URL).readl...
Use Python to Access Battery Status in Ubuntu
16,699,883
3
2013-05-22T19:15:28Z
16,699,910
7
2013-05-22T19:17:52Z
[ "python", "linux", "ubuntu" ]
I am trying to come out with a small python script to monitor the battery state of my ubuntu laptop and sound alerts if it's not charging as well as do other stuff (such as suspend etc). I really don't know where to start, and would like to know if there is any library for python i can use. Any help would be greatly ap...
I believe you can find the information you are looking for in ``` /sys/class/power_supply/BAT0 ```
Python - how can I dynamically remove a method from a class -- i.e. opposite of setattr
16,700,958
3
2013-05-22T20:24:12Z
16,700,973
11
2013-05-22T20:25:28Z
[ "python", "setattr" ]
I don't know if I have a good design here, but I have a class that is derived from unittest.TestCase and the way I have it set up, my code will dynamically inject a bunch of `test_*` methods into the class before invoking unittest to run through it. I use `setattr` for this. This has been working well, but now I have a...
It's called `delattr` and is documented [here](http://docs.python.org/2/library/functions.html#delattr).
get how much time python subprocess spends
16,701,310
10
2013-05-22T20:46:56Z
16,701,594
7
2013-05-22T21:08:00Z
[ "python", "python-2.7" ]
I'd like to time how long does the subprocess take. I tried to use ``` start = time.time() subprocess.call('....') elapsed = (time.time() - start) ``` However it's not very accurate (not sure related to multi-process or sth else) Is there a better way I can get how much time the subprocess really spends? Thank you!
It depends on which time you want; elapsed time, user mode, system mode? With [`resource.getrusage`](http://docs.python.org/2/library/resource.html#resource.getrusage) you can query the user mode and system mode time of the current process's children. This only works on UNIX platforms (like e.g. Linux, BSD and OS X): ...
matplotlib colorbar placement and size
16,702,479
6
2013-05-22T22:13:34Z
16,702,760
8
2013-05-22T22:39:56Z
[ "python", "layout", "matplotlib" ]
I'm using `quadmesh` to create a simple polar projection plot. Here's a minimal script which produces basically what I'm trying to do: ``` from __future__ import unicode_literals import numpy as np import matplotlib.pyplot as plt def make_plot(data,fig,subplot): nphi,nt = data.shape phi_coords = np.linspace(0...
You can do this with a combination of the `pad`, `shrink`, and `aspect` kwargs: ``` from __future__ import unicode_literals import numpy as np import matplotlib.pyplot as plt def make_plot(data,fig,subplot): nphi,nt = data.shape phi_coords = np.linspace(0,np.pi*2,nphi+1) - np.pi/2. theta_coords = np.linsp...
Rotate image and crop out black borders
16,702,966
29
2013-05-22T23:03:16Z
16,770,343
12
2013-05-27T09:39:04Z
[ "python", "algorithm", "opencv", "aabb" ]
My application: I am trying to rotate an image (using OpenCV and Python) ![Rotating Images](http://i.stack.imgur.com/KWoeo.jpg) At the moment I have developed the below code which rotates an input image, padding it with black borders, giving me A. What I want is B - the largest possible area crop window within the ro...
So, after investigating many claimed solutions, I have finally found a method that works; The answer by [Andri](http://stackoverflow.com/users/671973/andri) and [Magnus Hoff](http://stackoverflow.com/users/2971/magnus-hoff) on [Calculate largest rectangle in a rotated rectangle](http://stackoverflow.com/questions/57892...
Rotate image and crop out black borders
16,702,966
29
2013-05-22T23:03:16Z
16,778,797
43
2013-05-27T18:40:05Z
[ "python", "algorithm", "opencv", "aabb" ]
My application: I am trying to rotate an image (using OpenCV and Python) ![Rotating Images](http://i.stack.imgur.com/KWoeo.jpg) At the moment I have developed the below code which rotates an input image, padding it with black borders, giving me A. What I want is B - the largest possible area crop window within the ro...
The math behind this solution/implementation is equivalent to [this solution of an analagous question](http://stackoverflow.com/questions/5789239/calculate-largest-rectangle-in-a-rotated-rectangle#7519376), but the formulas are simplified and avoid singularities. This is python code with the same interface as `largest_...
Rotate image and crop out black borders
16,702,966
29
2013-05-22T23:03:16Z
27,137,047
10
2014-11-25T21:29:10Z
[ "python", "algorithm", "opencv", "aabb" ]
My application: I am trying to rotate an image (using OpenCV and Python) ![Rotating Images](http://i.stack.imgur.com/KWoeo.jpg) At the moment I have developed the below code which rotates an input image, padding it with black borders, giving me A. What I want is B - the largest possible area crop window within the ro...
Congratulations for the great work! I wanted to use your code in OpenCV with the C++ library, so I did the conversion that follows. Maybe this approach could be helpful to other people. ``` #include <iostream> #include <opencv.hpp> #define PI 3.14159265359 using namespace std; double degree_to_radian(double angle) ...
splitting line in python
16,703,150
2
2013-05-22T23:22:20Z
16,703,193
7
2013-05-22T23:26:13Z
[ "python", "python-2.7" ]
I have data of the below mentioned form: ``` <a> <b> <c> <This is a string> <World Bank> <provides> <loans for> <"a Country's Welfare"> <Facebook> <is a> <social networking site> <"Happy Facebooking => Enjoy"> ``` Now I want to split each line given above based on the delimiter <>. That is I want to split as: ``` ['...
You want to split on the whitespace *between* the `>` and `<` characters. For that you need a regular expression split with look-behind and look-ahead assertions: ``` import re re.split('(?<=>)\s+(?=<)', line) ``` This splits on any whitespace (`\s+`) that is preceded by a `>` and followed by a `<` character. The `...
File downloaded always blank in Python, Django
16,703,511
3
2013-05-22T23:59:00Z
16,703,686
7
2013-05-23T00:20:25Z
[ "python", "django", "web-applications", "django-views" ]
I am using the following view in Django to create a file and make the browser download it ``` def aux_pizarra(request): myfile = StringIO.StringIO() myfile.write("hello") response = HttpResponse(FileWrapper(myfile), content_type='text/plain') response['Content-Disposition'] ...
You have to move the pointer to the beginning of the buffer with `seek` and use `flush` just in case the writing hasn't performed. ``` from django.core.servers.basehttp import FileWrapper import StringIO def aux_pizarra(request): myfile = StringIO.StringIO() myfile.write("hello") myfile.flush() ...
Python Pandas - Removing Rows From A DataFrame Based on a Previously Obtained Subset
16,704,782
8
2013-05-23T02:39:31Z
16,704,977
14
2013-05-23T03:02:13Z
[ "python", "pandas" ]
I'm running `Python 2.7` with the `Pandas 0.11.0` library installed. I've been looking around a haven't found an answer to this question, so I'm hoping somebody more experienced than I has a solution. Lets say my data, in df1, looks like the following: `df1=` ``` zip x y access 123 1 1 4 123 1 1 ...
Two options come to mind. First, use `isin` and a mask: ``` >>> df zip x y access 0 123 1 1 4 1 123 1 1 6 2 133 1 2 3 3 145 2 2 3 4 167 3 1 1 5 167 3 1 2 >>> keep = [123, 133] >>> df_yes = df[df['zip'].isin(keep)] >>> df_no = df[~df['zip'].isin(keep)] >>> df_...
stale content types while syncdb in Django
16,705,249
13
2013-05-23T03:36:31Z
16,708,405
13
2013-05-23T07:50:13Z
[ "python", "django", "syncdb", "contenttypes" ]
While I'm trying to `syncdb` for my django project, I'm seeing following complains: ``` The following content types are stale and need to be deleted: myapp | Any objects related to these content types by a foreign key will also be deleted. Are you sure you want to delete these content types? If you're unsure, answe...
Normally you can delete them safely, as these are content types where no model exists anymore. The only thing you should be aware of is, that if you had other models pointing to the `ContentType` model via a `ForeignKey` these objects will be deleted as well. If you didn't set any foreign keys to `ContentType` at all n...
check if instance present in list
16,705,861
3
2013-05-23T04:48:18Z
16,705,879
9
2013-05-23T04:49:45Z
[ "python", "list" ]
Is there a built-in function to determine if instance of a class exists in a list? Currently I am doing it through a comprehension ``` >>> class A: ... pass ... >>> l1=[5,4,3,A(),8] >>> e=[e for e in l1 if isinstance(e,A)] ```
> [`any(iterable)`](http://docs.python.org/2/library/functions.html#any) > > Return `True` if any element of the iterable is true. If the iterable is empty, return `False`. ``` >>> class A(object): # subclass object for newstyle class (use them everywhere) pass >>> l1=[5,4,3,A(),8] >>> any(isinstance(x, A) fo...
Is there a difference between "raise exception()" and "raise exception" without parenthesis?
16,706,956
33
2013-05-23T06:26:12Z
16,709,222
30
2013-05-23T08:36:33Z
[ "python", "exception" ]
Defining a parameterless exception : ``` class myException(Exception): pass ``` When raised, is there any difference between : ``` raise myException ``` and ``` raise myException() ``` When trying, I could find none - Is it simply an overloaded syntax?
The short answer is that both `raise MyException` and `raise MyException()` do the same thing. This first form auto instantiates your exception. The [relevant section from the docs](http://docs.python.org/3/reference/simple_stmts.html#the-raise-statement) says, "*raise* evaluates the first expression as the exception ...
Checking the strength of a password (how to check conditions)
16,709,638
3
2013-05-23T08:59:41Z
32,542,964
8
2015-09-12T19:43:05Z
[ "python", "python-3.x" ]
I am trying to create a system that requires you to enter a password. If it is all lower, upper or num then print weak, if it is two of the conditions, then it is med and if all have been met it is strong. It just does not seem to work. The weak and strong work however the medium does not. I do not know where I have ...
Holá The best approach is using regular expression search Here is the function I am currently using ``` def password_check(password): """ Verify the strength of 'password' Returns a dict indicating the wrong criteria A password is considered strong if: 8 characters length or more 1...
python: iterate over dictionary sorted by key
16,710,112
20
2013-05-23T09:23:12Z
16,710,143
9
2013-05-23T09:24:30Z
[ "python", "sorting", "dictionary" ]
I have a Python dictionary ``` steps = {1:"value1", 5:"value2", 2:"value3"} ``` I need to iterate over this is sorted order by the key. I tried this: ``` x = sorted(steps, key=lambda key: steps[key]) ``` but the values are gone from x.
You need to iterate over `steps.items()`, because an iteration over dict only returns its keys. ``` >>> x = sorted(steps.items()) >>> x [(1, 'value1'), (2, 'value3'), (5, 'value2')] ``` Iterate over sorted keys: ``` >>> for key in sorted(steps): ... # use steps[keys] to get the value ```