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 use valgrind with python?
20,112,989
23
2013-11-21T05:12:59Z
20,126,802
23
2013-11-21T16:40:18Z
[ "python", "memory-leaks", "valgrind" ]
I am trying to memcheck a C python extension I am writing, but I'm having trouble setting up valgrind to work with python. I would really appreciate some advice. Just for context, this is Ubuntu 13.10, python 2.7.5+, and valgrind 3.8.1. As per recommendation from [`Readme.valgrind`](http://svn.python.org/projects/pyth...
I found the answer [here](http://code.google.com/p/distnumpy/wiki/valgrind). Python also needs to be compiled in debug mode, i.e. ``` ./configure --prefix=/home/dejan/workspace/python --without-pymalloc --with-pydebug --with-valgrind ``` In addition, numpy has a [suppresion file](http://code.google.com/p/distnumpy/s...
Scikit Learn SVC decision_function and predict
20,113,206
24
2013-11-21T05:29:35Z
20,114,601
9
2013-11-21T07:09:48Z
[ "python", "numpy", "svm", "scikit-learn" ]
I'm trying to understand the relationship between decision\_function and predict, which are instance methods of SVC (<http://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html>). So far I've gathered that decision function returns pairwise scores between classes. I was under the impression that predict choo...
I don't fully understand your code, but let's go trough the example of the documentation page you referenced: ``` import numpy as np X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]]) y = np.array([1, 1, 2, 2]) from sklearn.svm import SVC clf = SVC() clf.fit(X, y) ``` Now let's apply both the decision function and pr...
Scikit Learn SVC decision_function and predict
20,113,206
24
2013-11-21T05:29:35Z
20,133,945
8
2013-11-21T23:18:00Z
[ "python", "numpy", "svm", "scikit-learn" ]
I'm trying to understand the relationship between decision\_function and predict, which are instance methods of SVC (<http://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html>). So far I've gathered that decision function returns pairwise scores between classes. I was under the impression that predict choo...
When you call `decision_function()`, you get the output from each of the pairwise classifiers (n\*(n-1)/2 numbers total). See [pages 127 and 128 of "Support Vector Machines for Pattern Classification"](http://books.google.com/books?id=Uy1pqRzABDgC&pg=PA127&lpg=PA127&dq=svm+argmax+decision+function&source=bl&ots=Vj8lpok...
Django Error : userprofile matching query does not exist
20,113,779
5
2013-11-21T06:13:12Z
20,139,839
8
2013-11-22T07:59:03Z
[ "python", "django" ]
I am newbie to Django. I am trying to create UserProfile. First I created one model and its handler in models.py as follows.. ``` class UserProfile(models.Model): user = models.ForeignKey(User,null=False) name = models.CharField(max_length=200) def __unicode__(self): return self.name def create_...
I have resolved the error. I am answering my own question as it might help someone facing same problem. I encountered error in get\_profile function , So I checked the code of models.py file located at `/contrib/auth/models.py` at 383 line in get\_profile() function by replacing `user__id__exact=self.id with user = se...
What does the second argument of the Session.pop method do in Python Flask?
20,115,662
8
2013-11-21T08:18:31Z
20,115,928
11
2013-11-21T08:34:44Z
[ "python", "session", "flask" ]
I'm working through the Flask tutorial and would just like to clarify exactly what the .pop attr of the session object does and why it would take a 'None' parameter. ``` @app.route('/logout') def logout(): session.pop('logged_in', None) flash('You were logged out') return redirect(url_for('show_entries')) ...
According to [Flask's API](http://flask.pocoo.org/docs/api/) their `Session` class is a wrapper around a python `Dict`. According to the [python documentation](http://docs.python.org/2/library/stdtypes.html#dict.pop) for `dict.pop()`: > `pop(key[, default])` > > If `key` is in the dictionary, remove it and return its ...
Make kwargs directly accessible
20,116,033
4
2013-11-21T08:41:18Z
20,116,131
7
2013-11-21T08:47:26Z
[ "python", "arguments", "kwargs" ]
I am refactoring a piece of code, and I have run into the following problem. I have a *huge* parameter list, which now I want to pass as `kwargs`. The code is like this: ``` def f(a, b, c, ...): print a ... f(a, b, c, ...) ``` I am refactoring it to: ``` data = dict(a='aaa', b='bbb', c='ccc', ...) f(**data) ```...
There are [some ways](http://stackoverflow.com/a/20116113/1561176) - but you can also wrap your function like this: ``` def f(**kwargs): arg_order = ['a', 'b', 'c', ...] args = [kwargs.get(arg, None) for arg in arg_order] def _f(a, b, c, ...): # The main code of your function return _f(*args)...
Python Scrapy - populate start_urls from mysql
20,118,753
2
2013-11-21T10:45:19Z
20,137,164
10
2013-11-22T04:43:19Z
[ "python", "mysql", "scrapy", "web-crawler" ]
I am trying to populate start\_url with a SELECT from a MYSQL table using **spider.py**. When i run "scrapy runspider spider.py" i get no output, just that it finished with no error. I have tested the SELECT query in a python script and start\_url get populated with the entrys from the MYSQL table. **spider.py** ```...
A better approach is to override the [start\_requests](http://doc.scrapy.org/en/latest/topics/spiders.html#scrapy.spider.BaseSpider.start_requests) method. This can query your database, much like `populate_start_urls`, and return a sequence of [Request](http://doc.scrapy.org/en/latest/topics/request-response.html#requ...
define aggfunc for each values column in pandas pivot table
20,119,414
7
2013-11-21T11:14:46Z
20,120,225
10
2013-11-21T11:50:24Z
[ "python", "python-2.7", "pandas" ]
Was trying to generate a pivot table with multiple "values" columns. I know I can use aggfunc to aggregate values the way I want to, but what if I don't want to sum or avg both columns but instead I want sum of one column while mean of the other one. So is it possible to do so using pandas? ``` df = pd.DataFrame({ ...
You can **concat two DataFrames**: ``` >>> df1 = pd.pivot_table(df, values=['D'], rows=['B'], aggfunc=np.sum) >>> df2 = pd.pivot_table(df, values=['E'], rows=['B'], aggfunc=np.mean) >>> pd.concat((df1, df2), axis=1) D E B A 1.810847 -0.524178 B 2.762190 -0.443031 C 0.867519 0....
define aggfunc for each values column in pandas pivot table
20,119,414
7
2013-11-21T11:14:46Z
24,542,540
20
2014-07-02T23:13:24Z
[ "python", "python-2.7", "pandas" ]
Was trying to generate a pivot table with multiple "values" columns. I know I can use aggfunc to aggregate values the way I want to, but what if I don't want to sum or avg both columns but instead I want sum of one column while mean of the other one. So is it possible to do so using pandas? ``` df = pd.DataFrame({ ...
You can apply a specific function to a specific column by passing in a dict. ``` pd.pivot_table(df, values=['D','E'], rows=['B'], aggfunc={'D':np.sum, 'E':np.mean}) ```
Iterative Closest Point (ICP) implementation on python
20,120,384
2
2013-11-21T11:56:52Z
20,146,045
8
2013-11-22T13:25:22Z
[ "python", "opencv", "nearest-neighbor" ]
I have been searching for an implementation of the ICP algorithm in python lately with no result. According to wikipedia article <http://en.wikipedia.org/wiki/Iterative_closest_point>, the algorithm steps are: * Associate points by the nearest neighbor criteria (for each point in one point cloud find the closest poin...
Finally, I managed to write my own implementation of ICP in Python, using the sklearn and opencv libraries. The function takes two datasets, an initial relative pose estimation and the desired number of iterations. It returns a transformation matrix that transforms the first dataset to the second. Enjoy! ``` import...
Python - Why is this code considered a generator?
20,123,912
2
2013-11-21T14:42:22Z
20,123,995
10
2013-11-21T14:45:06Z
[ "python", "list", "python-3.x", "generator" ]
I have a list called 'mb', its format is: ``` ['Company Name', 'Rep', Mth 1 Calls, Mth 1 Inv Totals, Mth 1 Inv Vol, Mth 2 ``` ...And so on In the below code I simply append a new list of 38 0's. This is fine. However in the next line I get an error: 'generator' object does not support item assignment Can anyone te...
In fact, you do not append a list of 38 0s: you append a **generator** that will **yield** `0` 38 times. This is not what you want. However, you can change can change `mb.append(0 for x in range(38))` to ``` mb.append([0 for x in range(38)]) # note the [] surrounding the original generator expression! This turns it ...
Python float to ratio
20,124,472
4
2013-11-21T15:04:59Z
20,124,529
10
2013-11-21T15:07:38Z
[ "python", "floating-point", "python-3.3", "fractions", "ratio" ]
I try get ration of variable and get unexpected result. Can somebody explain this? ``` >>> value = 3.2 >>> ratios = value.as_integer_ratio() >>> ratios (3602879701896397, 1125899906842624) >>> ratios[0] / ratios[1] 3.2 ``` I using python 3.3 But I think that `(16, 5)` is much better solution And why it correct for ...
Use the [`fractions` module](http://docs.python.org/2/library/fractions.html) to simplify fractions: ``` >>> from fractions import Fraction >>> Fraction(3.2) Fraction(3602879701896397, 1125899906842624) >>> Fraction(3.2).limit_denominator() Fraction(16, 5) ``` From the [`Fraction.limit_denominator()` function](http:/...
How bad is shadowing names defined in outer scopes?
20,125,172
59
2013-11-21T15:35:11Z
20,125,739
68
2013-11-21T15:56:56Z
[ "python", "coding-style", "pycharm" ]
I just switched to Pycharm and I am very happy about all the warnings and hints it provides me to improve my code. Except for this one which I don't understand: `This inspection detects shadowing names defined in outer scopes.` I know it is bad practice to access variable from the outer scope but what is the problem ...
No big deal in your above snippet, but imagine a function with a few more arguments and quite a few more lines of code. Then you decide to rename your `data` argument as `yadda` but miss one of the places it is used in the function's body... Now `data` refers to the global, and you start having weird behaviour - where ...
How to set default text for a Tkinter Entry widget
20,125,967
12
2013-11-21T16:05:46Z
20,126,024
14
2013-11-21T16:07:31Z
[ "python", "python-2.7", "user-interface", "tkinter" ]
How do I set the default text for a Tkinter Entry widget in the constructor? I checked the documentation, but I do not see a something like a `"string="` option to set in the constructor? There is a similar answer out there for using tables and lists, but this is for a simple Entry widget.
use [`Entry.insert`](http://effbot.org/tkinterbook/entry.htm#Tkinter.Entry.insert-method). For example: ``` from Tkinter import * root = Tk() e = Entry(root) e.insert(END, 'default text') e.pack() root.mainloop() ``` or use [`textvariable`](http://effbot.org/tkinterbook/entry.htm#Tkinter.Entry.config-method) option...
Creating a Confidence Ellipses in a sccatterplot using matplotlib
20,126,061
9
2013-11-21T16:09:03Z
20,127,387
13
2013-11-21T17:04:13Z
[ "python", "numpy", "matplotlib", "scipy" ]
How to creating a Confidence Ellipses in a sccatterplot using matplotlib? The following code works until creating scatter plot. Then, does anyone familiar with putting Confidence Ellipses over the scatter plot? ``` import numpy as np import matplotlib.pyplot as plt x = [5,7,11,15,16,17,18] y = [8, 5, 8, 9, 17, 18, 25...
The following code draws a one, two, and three standard deviation sized ellipses: ``` x = [5,7,11,15,16,17,18] y = [8, 5, 8, 9, 17, 18, 25] cov = np.cov(x, y) lambda_, v = np.linalg.eig(cov) lambda_ = np.sqrt(lambda_) from matplotlib.patches import Ellipse import matplotlib.pyplot as plt ax = plt.subplot(111, aspect='...
Creating a Confidence Ellipses in a sccatterplot using matplotlib
20,126,061
9
2013-11-21T16:09:03Z
25,022,642
9
2014-07-29T18:38:16Z
[ "python", "numpy", "matplotlib", "scipy" ]
How to creating a Confidence Ellipses in a sccatterplot using matplotlib? The following code works until creating scatter plot. Then, does anyone familiar with putting Confidence Ellipses over the scatter plot? ``` import numpy as np import matplotlib.pyplot as plt x = [5,7,11,15,16,17,18] y = [8, 5, 8, 9, 17, 18, 25...
After giving the accepted answer a go, I found that it doesn't choose the quadrant correctly when calculating theta, as it relies on [`np.arccos`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.arccos.html): ![oops](http://i.stack.imgur.com/9BB7X.png) Taking a look at the ['possible duplicate'](http://stac...
Split string by delimiter only if not wrapped in certain pattern
20,128,574
5
2013-11-21T18:03:29Z
20,128,769
7
2013-11-21T18:13:17Z
[ "python", "regex" ]
I am trying to split a string into a list by a delimiter (let's say `,`) but the delimiter character should be considered the delimiter only if it is not wrapped in a certain pattern, in my particular case `<>`. IOW, when a comma is nested in `<>`, it is ignored as a delimiter and becomes just a regular character not t...
**Update:** Since you mentioned that the brackets may be nested, I regret to inform you that a regex solution *is not possible* in Python. The following can work only if the angle brackets are always balanced and never nested nor escaped: ``` >>> import re >>> s = "first token, <second token part 1, second token part ...
Python No JSON object could be decoded
20,128,772
10
2013-11-21T18:13:19Z
20,128,856
13
2013-11-21T18:17:53Z
[ "python", "json" ]
I am having an issue with JSON, I can't seem to figure out why this is not working. This is supposed to output JSON. Here is my code ``` #!/usr/bin/env python import socket import struct import json def unpack_varint(s): d = 0 i = 0 while True: b = ord(s.recv(1)) d |= (b & 0x7F) << 7*i ...
It seems that you have invalid JSON. In that case, that's totally dependent on the data the server sends you which you have not shown. I would suggest running the response through a [JSON validator](http://jsonlint.com/).
Why does bool(xml.etree.ElementTree.Element) evaluate to False?
20,129,996
14
2013-11-21T19:19:11Z
20,130,061
9
2013-11-21T19:23:07Z
[ "python", "boolean" ]
``` import xml.etree.ElementTree as ET e = ET.Element('Brock',Role="Bodyguard") print bool(e) ``` Why is an `xml.etree.ElementTree.Element` considered `False`? I know that I can do `if e is not None` to check for existence. But I would **strongly** expect `bool(e)` to return `True`.
From the docs: <http://docs.python.org/2/library/xml.etree.elementtree.html#element-objects> > > Caution: Elements with no subelements will test as False. This behavior will change in future versions. Use specific len(elem) or elem is None test instead.
Why does bool(xml.etree.ElementTree.Element) evaluate to False?
20,129,996
14
2013-11-21T19:19:11Z
20,130,067
20
2013-11-21T19:23:24Z
[ "python", "boolean" ]
``` import xml.etree.ElementTree as ET e = ET.Element('Brock',Role="Bodyguard") print bool(e) ``` Why is an `xml.etree.ElementTree.Element` considered `False`? I know that I can do `if e is not None` to check for existence. But I would **strongly** expect `bool(e)` to return `True`.
As it turns out, `Element` objects are considered a `False` value if they have no children. I found this in the source: ``` def __nonzero__(self): warnings.warn( "The behavior of this method will change in future versions. " "Use specific 'len(elem)' or 'elem is not None' test instead.", ...
Python cast character to operation
20,130,007
4
2013-11-21T19:20:11Z
20,130,071
8
2013-11-21T19:23:31Z
[ "python" ]
I'm writing a simple Python program for a projecteuler question, and it involves generating a search space over operations, ex: ``` 8 = (4 * (1 + 3)) / 2 14 = 4 * (3 + 1 / 2) 19 = 4 * (2 + 3) − 1 36 = 3 * 4 * (2 + 1) ``` I'm storing possible operations in an array: ``` op = ['+', '-', '*', '/'] ``` I was wonderin...
You could use the [`operator`](http://docs.python.org/2/library/operator.html) module to get the functionality you're looking for. The `operator` module has "a set of efficient functions corresponding to the intrinsic operators of Python": ``` >>> import operator as op >>> ops = {"+": op.add, "-": op.sub, "/": op.div,...
Matplotlib connect scatterplot points with line - Python
20,130,227
23
2013-11-21T19:31:39Z
20,130,384
13
2013-11-21T19:40:42Z
[ "python", "matplotlib" ]
I have two lists, dates and values. I want to plot them using matplotlib. The following creates a scatter plot of my data. ``` import matplotlib.pyplot as plt plt.scatter(dates,values) plt.show() ``` `plt.plot(dates, values)` creates a line graph. But what I really want is a scatterplot where the points are connect...
For red lines an points ``` plt.plot(dates, values, '.r-') ``` or for x markers and blue lines ``` plt.plot(dates, values, 'xb-') ```
Matplotlib connect scatterplot points with line - Python
20,130,227
23
2013-11-21T19:31:39Z
20,132,200
38
2013-11-21T21:24:54Z
[ "python", "matplotlib" ]
I have two lists, dates and values. I want to plot them using matplotlib. The following creates a scatter plot of my data. ``` import matplotlib.pyplot as plt plt.scatter(dates,values) plt.show() ``` `plt.plot(dates, values)` creates a line graph. But what I really want is a scatterplot where the points are connect...
I think @Evert has the right answer: ``` plt.scatter(dates,values) plt.plot(dates, values) plt.show() ``` Which is pretty much the same as ``` plt.plot(dates, values, '-o') plt.show() ``` or whatever *linestyle* you prefer.
django TransactionManagementError when using signals
20,130,507
7
2013-11-21T19:48:41Z
20,132,059
14
2013-11-21T21:17:41Z
[ "python", "django", "django-models" ]
I have a one to one field with django's users and UserInfo. I want to subscribe to the post\_save callback function on the user model so that I can then save the UserInfo as well. ``` @receiver(post_save, sender=User) def saveUserAndInfo(sender, instance, **kwargs): user = instance try: user.user_info...
The error is caused by the `user.user_info.save()` line throwing an exception, and the transaction was flagged as broken (PostgreSQL enforces rolling back either the whole transaction, or to any savepoint stored before doing any more queries inside that transaction). You can rollback the transaction when an error occu...
Using Sklearn's TfidfVectorizer transform
20,132,070
16
2013-11-21T21:18:43Z
20,132,530
22
2013-11-21T21:41:28Z
[ "python", "document", "text-mining", "tf-idf" ]
I am trying to get the tf-idf vector for a single document using Sklearn's TfidfVectorizer object. I create a vocabulary based on some training documents and use fit\_transform to train the TfidfVectorizer. Then, I want to find the tf-idf vectors for any given testing document. ``` from sklearn.feature_extraction.text...
If you want to compute tf-idf only for a given vocabulary, use `vocabulary` argument to `TfidfVectorizer` constructor, ``` vocabulary = "a list of words I want to look for in the documents".split() vect = TfidfVectorizer(sublinear_tf=True, max_df=0.5, analyzer='word', stop_words='english', vocabulary=vocab...
How to concatenate two html file bodies with BeautifulSoup?
20,132,458
4
2013-11-21T21:37:53Z
20,132,718
8
2013-11-21T21:52:10Z
[ "python", "html", "beautifulsoup" ]
**I need to concatenate the bodies of two html files into one html file, with a bit of arbitrary html as a separator in between. I have code that used to work for this, but stopped working** when I upgraded from Xubuntu 11.10 (or was it 11.04?) to 12.10, probably due to a BeautifulSoup update (I'm currently using 3.2.1...
Trying to read the HTML as text just to insert it into HTML and fighting the encoding and decoding in both directions is making a whole lot of extra work that's very difficult to get right. The easy thing to do is just not do that. You want to insert everything in the body of test2 after everything in the body of test...
Format APNS-style JSON message in Python for use with Amazon SNS
20,133,285
13
2013-11-21T22:28:56Z
20,134,162
40
2013-11-21T23:34:21Z
[ "python", "json", "amazon-web-services", "apple-push-notifications", "amazon-sns" ]
I'm creating an iOS app, and for our push notifications, we're using Amazon's Simple Notification Service (SNS). SNS is wonderful, but the documentation is pretty sparse. I'm using [boto](http://docs.pythonboto.org/en/latest/ref/sns.html), Amazon's Python library, and I've figured out how to send plain-text push notif...
I figured it out! **Turns out, the APNS payload has to be encoded as a string within the larger payload** - and it totally works. Here's the final, working code: ``` apns_dict = {'aps':{'alert':'inner message','sound':'mySound.caf'}} apns_string = json.dumps(apns_dict,ensure_ascii=False) message = {'default':'default...
how to draw directed graphs using networkx in python?
20,133,479
27
2013-11-21T22:43:53Z
20,133,763
27
2013-11-21T23:04:30Z
[ "python", "graph", "plot", "networkx" ]
I have some nodes coming from a script that I want to map on to a graph. In the below, I want to use Arrow to go from A to D and probably have the edge colored too in (red or something). This is basically, like a path from A to D when all other nodes are present. you can imagine each nodes as cities and travelling from...
Fully fleshed out example with arrows for only the red edges: ``` import networkx as nx import numpy as np import matplotlib.pyplot as plt G = nx.DiGraph() G.add_edges_from( [('A', 'B'), ('A', 'C'), ('D', 'B'), ('E', 'C'), ('E', 'F'), ('B', 'H'), ('B', 'G'), ('B', 'F'), ('C', 'G')]) val_map = {'A': 1.0, ...
how to draw directed graphs using networkx in python?
20,133,479
27
2013-11-21T22:43:53Z
20,133,821
10
2013-11-21T23:08:24Z
[ "python", "graph", "plot", "networkx" ]
I have some nodes coming from a script that I want to map on to a graph. In the below, I want to use Arrow to go from A to D and probably have the edge colored too in (red or something). This is basically, like a path from A to D when all other nodes are present. you can imagine each nodes as cities and travelling from...
You need to use a [directed graph](http://networkx.lanl.gov/reference/classes.digraph.html) instead of a graph, i.e. ``` G = nx.DiGraph() ``` Then, create a list of the edge colors you want to use and pass those to `nx.draw` (as shown by @Marius). Putting this all together, I get the image below. Still not quite the...
how to draw directed graphs using networkx in python?
20,133,479
27
2013-11-21T22:43:53Z
20,134,664
27
2013-11-22T00:24:23Z
[ "python", "graph", "plot", "networkx" ]
I have some nodes coming from a script that I want to map on to a graph. In the below, I want to use Arrow to go from A to D and probably have the edge colored too in (red or something). This is basically, like a path from A to D when all other nodes are present. you can imagine each nodes as cities and travelling from...
I only put this in for completeness. I've learned plenty from marius and mdml. Here are the edge weights. Sorry about the arrows. Looks like I'm not the only one saying it can't be helped. I couldn't render this with ipython notebook I had to go straight from python which was the problem with getting my edge weights in...
Mario running across screen too fast in pygame
20,134,955
2
2013-11-22T00:53:58Z
20,135,411
10
2013-11-22T01:39:41Z
[ "python", "animation", "python-3.x", "pygame" ]
So first of all the code: ``` import pygame, sys from pygame.locals import * class Person(pygame.sprite.Sprite): def __init__(self, screen): self.screen = screen pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load("images/mariowalking0.png") self.rect = self.i...
Your program will run with different speed on different computer - it depends on computer speed. You can use [pygame.time.Clock()](http://www.pygame.org/docs/ref/time.html) to get the same speed on all computers (except very slow computers) and also to slow down game and Mario speed. ``` clock = pygame.time.Clock() w...
Is there a simple way to switch between using and ignoring metacharacters in Python regular expressions?
20,135,953
7
2013-11-22T02:35:37Z
20,135,976
7
2013-11-22T02:37:43Z
[ "python", "regex", "metacharacters" ]
Is there a way of toggling the compilation or use of metacharacters when compiling regexes? The current code looks like this: **Current code:** ``` import re the_value = '192.168.1.1' the_regex = re.compile(the_value) my_collection = ['192a168b1c1', '192.168.1.1'] my_collection.find_matching(the_regex) result =...
Nope. However: ``` the_regex = re.compile(re.escape(the_value)) ```
python3 nested list comprehension scope
20,136,955
13
2013-11-22T04:21:22Z
20,137,069
11
2013-11-22T04:33:53Z
[ "python", "scope", "cpython" ]
The best way to explain my question is with an example: example.py: ``` class A(object): integers = [1, 2, 3] singles = [i for i in integers] class B(object): integers = [1, 2, 3] pairs = [(i, j) for i in integers for j in integers] ``` When I run this under python 2 it works fine, but under python...
Class scopes are a bit strange in Python 3, but its for a good reason. In Python 2, the iteration variables (`i` and `j` in your examples) leaked out of list comprehensions and would be included in the outside scope. This is because they were developed early in Python 2's design, and they were based on explicit loops....
Using FFmpeg and IPython
20,137,792
8
2013-11-22T05:40:04Z
20,395,798
18
2013-12-05T09:13:18Z
[ "python", "matplotlib", "ffmpeg" ]
I am relatively new to Python (I used MATLAB a lot more). I essentially want to be able to make and save animations. So I went and checked how it's done and found this : <http://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/> I straight up copied/pasted the code in an IPython Notebook. I understand ...
I came across the exact same error as I started working with animations using the exact same example to start with. First of all, I am using Windows 7, Python 2.7.6, matplotlib 1.3.1 Short answer: Try to set up the FFMpegWriter yourself by ``` mywriter = animation.FFMpegWriter() anim.save('mymovie.mp4',writer=mywrit...
Any pythonic way to do "[['a', 2], ['b',1]] + [['b', 2], ['c', 1]] = [['b', 3], ['a', 2], ['c', 1]]"?
20,139,002
2
2013-11-22T07:04:05Z
20,139,129
8
2013-11-22T07:12:33Z
[ "python", "lambda", "functional-programming" ]
input: ``` [['a', 2], ['b',1]] (sorted by value) [['b', 2], ['c', 1]] ``` output: ``` [['b', 3], ['a', 2], ['c', 1]] ``` Any pythonic way? Of course, in Python! (better for 2.6x) Thanks!
Use [`collections.Counter`](http://docs.python.org/2/library/collections.html#collections.Counter) for Python2.7+: ``` >>> from collections import Counter >>> lis1 = [['a', 2], ['b',1]] >>> lis2 = [['b', 2], ['c', 1]] >>> c = Counter(dict(lis1)) + Counter(dict(lis2)) >>> c.most_common() [('b', 3), ('a', 2), ('c', 1)] ...
in Python 2.7, why do I have to enclose an `int` in brackets when I want to call a method on it?
20,140,606
6
2013-11-22T08:51:51Z
20,140,658
7
2013-11-22T08:54:44Z
[ "python" ]
in Python 2.7, why do I have to enclose an `int` in brackets when I want to call a method on it? ``` >>> 5.bit_length() SyntaxError: invalid syntax >>> (5).bit_length() 3 ```
That's a parser idiosyncrasy. When Python sees the `.`, it starts looking for decimals. Your decimal is a `b`, so that fails. If you do `(5).bit_length()`, then Python will *first* parse what's between the `()`, and *then* look for the `bit_length` method. --- If you try: ``` 5..zzz ``` You'll get the `AttributeE...
Ordering CONCAVE polygon vertices in (counter)clockwise?
20,141,812
5
2013-11-22T09:53:18Z
20,145,980
7
2013-11-22T13:22:24Z
[ "python", "algorithm" ]
I have a set of disordered vertices that may form a concave polygon. Now I wish to order them in either clockwise or counterclockwise. [An answer here](http://stackoverflow.com/a/13935419/2106753) suggests the following steps: * Find the polygon center * Compute angles * Order points by angle This is obviously only ...
In general, your problem seems ill-defined. For example, given the following set of vertices: ![Four points on the plane in a non-convex arrangement](http://i.stack.imgur.com/iO8JP.png) which of these non-convex polygons would you consider to be the "correct" way to connect them? ![Polygon ABCD](http://i.stack.imgur...
yield - statement or expression?
20,142,450
5
2013-11-22T10:22:11Z
20,142,817
8
2013-11-22T10:39:47Z
[ "python", "expression", "yield" ]
So, I've been reading [this](http://stackoverflow.com/questions/101268/hidden-features-of-python#101739), and found out about sending values to generator. And now I'm kinda confused. Is yield a statement or an expression? It doesn't use parenthesis syntax, like functions, so it looks like statement. But it returns val...
[`yield` is an expression](http://docs.python.org/release/2.7/reference/expressions.html#yield-expressions). It used to be a statement, and it's most commonly used as an entire statement, but in Python 2.5, it was turned into an expression as part of new coroutine support. It's still commonly referred to as the "yield ...
Understanding an issue with the namedtuple typename and pickle in Python
20,143,726
5
2013-11-22T11:23:59Z
20,145,104
7
2013-11-22T12:36:51Z
[ "python", "python-2.7", "serialization", "pickle", "namedtuple" ]
Earlier today I was having trouble trying to pickle a [namedtuple](http://docs.python.org/2/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields) instance. As a sanity check, I tried running some code that was posted [in another answer](http://stackoverflow.com/a/16377267/553404). Here it i...
In the section titled [***What can be pickled and unpickled?***](https://docs.python.org/3/library/pickle.html#what-can-be-pickled-and-unpickled) of the Python documentation it indicates that only "classes that are defined at the top level of a module" can be pickled. However [`namedtuple()`](https://docs.python.org/3/...
Shifted colorbar matplotlib
20,144,529
9
2013-11-22T12:06:32Z
20,146,989
22
2013-11-22T14:14:44Z
[ "python", "colors", "matplotlib" ]
I am trying to make a filled contour for a dataset. It should be fairly straightforward: ``` plt.contourf(x, y, z, label = 'blah', cm = matplotlib.cm.RdBu) ``` However, what do I do if my dataset is not symmetric about 0? Let's say I want to go from blue (negative values) to 0 (white), to red (positive values). If my...
First off, there's more than one way to do this. 1. Use the `colors` kwarg to `contourf` and manually specify the colors 2. Use a custom `Normalize` class and pass an instance in as the `norm` kwarg. 3. Use a discrete colormap constructed with `matplotlib.colors.from_levels_and_colors`. The simplest way is to pass in...
Python sorting by multiple criteria
20,145,842
2
2013-11-22T13:15:27Z
20,145,873
8
2013-11-22T13:16:56Z
[ "python", "sorting" ]
I have a list where each element is of the form `[list of integers, integer]`. For example, an element of the list may look like this `[[1,3,1,2], -1]`. I want to sort a list containing the described type of elements by the following criteria: 1. if the integer lists of two elements (i.e. `element[0]`) are of differe...
List the three criteria in your key: ``` sorted(inputlist, key=lambda e: (len(e[0]), e[0], e[1])) ``` Now you are sorting each element first by the length, then by comparing the first element directly (which in only used when the first element is of equal length), then by the value of the last integer. Python sorts ...
How to extract dictionary single key-value pair in variables
20,145,902
6
2013-11-22T13:18:03Z
20,145,927
16
2013-11-22T13:19:26Z
[ "python", "python-2.7", "iterable-unpacking" ]
I have only a single key-value pair in dictionary. I want to assign key to one variable and it's value to another variable. I have tried with below ways but I am getting error for same. ``` >>> d ={"a":1} >>> d.items() [('a', 1)] >>> (k,v) = d.items() Traceback (most recent call last): File "<stdin>", line 1, in <...
Add another level, with a tuple (just the comma): ``` (k, v), = d.items() ``` or with a list: ``` [(k, v)] = d.items() ``` or pick out the first element: ``` k, v = d.items()[0] ``` The first two have the added advantage that they throw an exception if your dictionary has more than one key. Demo: ``` >>> d = {'...
OpenCV-Python dense SIFT
20,146,570
11
2013-11-22T13:55:01Z
22,368,921
16
2014-03-13T04:12:57Z
[ "python", "opencv", "sift" ]
OpenCV has [very good documentation on generating SIFT descriptors](http://docs.opencv.org/trunk/doc/py_tutorials/py_feature2d/py_sift_intro/py_sift_intro.html), but this is a version of "weak SIFT", where the key points are detected by the original [Lowe algorithm](http://www.cs.ubc.ca/~lowe/keypoints/). The OpenCV ex...
You can use Dense Sift in opencv 2.4.6 <. Creates a feature detector by its name. > cv2.FeatureDetector\_create(detectorType) Then `"Dense"` string in place of detectorType eg:- ``` dense=cv2.FeatureDetector_create("Dense") kp=dense.detect(imgGray) kp,des=sift.compute(imgGray,kp) ```
Django per user view caching
20,146,741
3
2013-11-22T14:03:08Z
35,682,133
8
2016-02-28T11:49:28Z
[ "python", "django", "caching", "django-views" ]
I need a per user caching. The regular [view caching](https://docs.djangoproject.com/en/1.5/topics/cache/#the-per-view-cache) does unfortunately not support user-based caching. I tried the [template fragment caching](https://docs.djangoproject.com/en/1.5/topics/cache/#template-fragment-caching) like this: ``` {% load...
as of django >=1.7, using the [cache\_page](https://docs.djangoproject.com/en/1.7/topics/cache/#the-per-view-cache) along with [vary\_on\_cookie](https://docs.djangoproject.com/en/1.7/topics/cache/#using-vary-headers) decorators on your view should solve this. something like this. ``` from django.views.decorators.var...
How to know if a paramiko SSH channel is disconnected?
20,147,902
7
2013-11-22T14:59:23Z
20,161,163
8
2013-11-23T10:25:06Z
[ "python", "paramiko" ]
I'm desinging test cases in which I use paramiko for SSH connections. Test cases usually contain `paramiko.exec_command()` calls which I have a wrapper for (called `run_command()`). Here `self.ssh` is an intance of `paramiko.SSHClient()`. I use a decorator to check the ssh connection before each call. (`self.get_ssh()`...
In python, it's [easier to ask for forgiveness than permission](http://docs.python.org/2/glossary.html#term-eafp). Wrap each call to `ssh.exec_command` like so: ``` try: ssh.exec_command('ls') except socket.error as e: # Crap, it's closed. Perhaps reopen and retry? ```
Why is numpy's einsum slower than numpy's built-in functions?
20,149,201
8
2013-11-22T16:00:20Z
20,153,474
11
2013-11-22T20:00:14Z
[ "python", "performance", "numpy", "linear-algebra" ]
I've usually gotten good performance out of numpy's einsum function (and I like it's syntax). @Ophion's answer to [this question](http://stackoverflow.com/questions/18365073/why-is-numpys-einsum-faster-than-numpys-built-in-functions) shows that - for the cases tested - einsum consistently outperforms the "built-in" fun...
You can have the best of both worlds: ``` def func_dot_einsum(C, X): Y = X.dot(C) return np.einsum('ij,ij->i', Y, X) ``` On my system: ``` In [7]: %timeit func_dot(C, X) 10 loops, best of 3: 31.1 ms per loop In [8]: %timeit func_einsum(C, X) 10 loops, best of 3: 105 ms per loop In [9]: %timeit func_einsum2...
Django i18n: recommended size and formatting for {% blocktrans %} blocks?
20,150,773
10
2013-11-22T17:20:10Z
20,426,663
7
2013-12-06T14:42:27Z
[ "python", "django", "django-templates", "django-i18n" ]
I am just getting started with Django internationalization and trying to understand the best practices for using `{% blocktrans %}`. Is it preferable to use one `{% blocktrans %}` for each paragraph, or should I have one big `{% blocktrans %}` that contains many paragraphs? Having one big `{% blocktrans %}` is faster ...
Multiple small `{% blocktrans %}` blocks are beneficial for various reasons: * Each translatable string ends up in the translation files and these files should be translatable by people that speak the language. They should not have to deal with correctness of HTML tags but they should purely translate a few sentences ...
'int' object is not callable error in python
20,151,855
3
2013-11-22T18:23:11Z
20,151,867
14
2013-11-22T18:23:53Z
[ "python", "int", "callable" ]
Unfortunately I don't have much time so I have to be as short as I can. I'm getting this error: ``` Traceback (most recent call last): File "C:\Users\George\Desktop\ex3.py", line 15, in <module> s=s+d*2(-1/6.)*(u-1)*(u-2)*(u+2)*(u-4) TypeError: 'int' object is not callable ``` Here is my code: ``` x=input() z=...
You are trying to use `2` as a function: ``` 2(-1/6.) ``` Insert a `*` to multiply: ``` 2*(-1/6.) ``` or as a full expression: ``` s=s+d*2*(-1/6.)*(u-1)*(u-2)*(u+2)*(u-4) ```
algorithm to determine whether a value is within a range of a multiple
20,152,416
3
2013-11-22T18:57:13Z
20,152,597
7
2013-11-22T19:07:07Z
[ "python", "algorithm" ]
Algorithm question: Let's say I want to determine whether a value is within a range (eg 2) of a tens multiple -- so, 8-12, 18-22, 28-32, etc. My current solution is to add the range to the value, mod by 10, then re-subtract the range -- thus leaving me with something from -2 to 8 -- and then check whether the absolut...
I find this solution easier to understand: ``` remainder = (value % cycle) (remainder <= range) || (cycle - remainder) <= range ``` Basically I find the remainder of the `value` I search for in respect of the modulo (`cycle`) and then check if it is within the expected range. **Alternative:** An alternative solutio...
Converting tuples to multiple indices in a Pandas Dataframe
20,153,039
7
2013-11-22T19:31:43Z
20,153,210
9
2013-11-22T19:42:38Z
[ "python", "pandas" ]
I'm starting with a dictionary like this: ``` dict = {(100000550L, u'ActivityA'): {'bar__sum': 14.0, 'foo__sum': 12.0}, (100001799L, u'ActivityB'): {'bar__sum': 7.0, 'foo__sum': 3.0}} ``` Which, when converted to a DataFrame, puts as column headers the tuples of (id, activitytype): ``` df = DataFrame(dict).t...
If you want to **convert index** of your dataframe: ``` >>> df.index = pd.MultiIndex.from_tuples(df.index) >>> df bar__sum foo__sum 100000550 ActivityA 14 12 100001799 ActivityB 7 3 >>> df.index.names = ['id', 'act_type'] >>> df bar__sum foo__s...
Pandas read_csv expects wrong number of columns, with ragged csv file
20,154,303
9
2013-11-22T20:54:15Z
20,154,429
16
2013-11-22T21:02:28Z
[ "python", "csv", "pandas", "ragged" ]
I have a csv file that has a few hundred rows and 26 columns, but the last few columns only have a value in a few rows and they are towards the middle or end of the file. When I try to read it in using read\_csv() I get the following error. "ValueError: Expecting 23 columns, got 26 in row 64" I can't see where to expl...
You can use `names` parameter. For example, if you have csv file like this: ``` 1,2,1 2,3,4,2,3 1,2,3,3 1,2,3,4,5,6 ``` And try to read it, you'll receive and error ``` >>> pd.read_csv(r'D:/Temp/tt.csv') Traceback (most recent call last): ... Expected 5 fields in line 4, saw 6 ``` But if you pass `names` parameters...
Class with all possible methods defined/catched
20,155,029
3
2013-11-22T21:43:12Z
20,155,088
9
2013-11-22T21:47:50Z
[ "python", "class" ]
I was trying to put together a stringIO-like function, and I was wondering if it was possible to build a class that catches all possible methods, so that the following would work: ``` a = magicclass("Hello World!") #Hello world would be the return print a() #Would print Hello world print a.read() #should also print he...
``` class A(object): def __init__(self, msg): self.msg = msg def __call__(self): print self.msg def __getattr__(self, name): return self a = A('Hello World') a() a.b() a.b.c() ```
Python - is there any way to organize a group of yields in sub function to yield outside the main function?
20,155,194
5
2013-11-22T21:54:28Z
20,155,233
9
2013-11-22T21:57:29Z
[ "python", "generator", "yield" ]
I have a newbie question for python gurus. I have function A that hold a lot of repeated yield-actions like so: ``` yield a yield b yield c ``` so it looks like: ``` def funA(): … yield a yield b yield c … yield a yield b yield c … yield a yield b yield c ``` Is there a...
If you're using the latest and greatest `python` (>= 3.3), there's the [`yield from`](http://www.python.org/dev/peps/pep-0380/) construct. ``` yield from funB() ``` It does exactly what you want: you can invoke a function as a sub-generator, and yield back everything it yields to you. If you're using an earlier vers...
Why does Python create two refcounts for an object on creation?
20,155,355
5
2013-11-22T22:05:36Z
20,155,424
7
2013-11-22T22:09:19Z
[ "python", "memory", "memory-management" ]
So when I create an object without reference (as far as I can tell) why does Python maintain that there's a refcount for it? ``` >>> import sys >>> sys.getrefcount(object()) 1 ``` The following makes sense based on this extra refcount. ``` >>> o = object() >>> sys.getrefcount(o) 2 >>> l = list((o,)) >>> sys.getrefco...
When you invoke [`sys.getrefcount()`](http://docs.python.org/2/library/sys.html#sys.getrefcount), a reference is generated for local use inside the function. [`getrefcount()`](http://docs.python.org/2/library/sys.html#sys.getrefcount) will always add 1 to the actual count, because it counts its own internal ref.
How do I find which attributes my tree splits on, when using scikit-learn?
20,156,951
20
2013-11-23T00:29:51Z
20,159,279
20
2013-11-23T06:15:18Z
[ "python", "machine-learning", "scikit-learn", "decision-tree" ]
I have been exploring scikit-learn, making decision trees with both entropy and gini splitting criteria, and exploring the differences. My question, is how can I "open the hood" and find out exactly which attributes the trees are splitting on at each level, along with their associated information values, so I can see ...
Directly from the documentation ( <http://scikit-learn.org/0.12/modules/tree.html> ): ``` from StringIO import StringIO out = StringIO() out = tree.export_graphviz(clf, out_file=out) ``` There is also the `tree_` attribute in your decision tree object, which allows the direct access to the whole structure. And you c...
How to take input file from terminal for python script?
20,157,824
9
2013-11-23T02:34:18Z
20,158,514
15
2013-11-23T04:25:36Z
[ "python" ]
I have a python script which uses a text file and manipulate the data from the file and output to another file. Basically I want it to work for any text file input. Right now I readline from the file and then print the output to screen. I want the output in a file. So user can type the following and test for any file:...
The best way to do this is probably to call the input and output files as arguments for the python script: ``` import sys inFile = sys.argv[1] outFile = sys.argv[2] ``` Then you can read in all your data, do your manipulations, and write out the results: ``` with open(inFile,'r') as i: lines = i.readlines() pro...
How to qcut with non unique bin edges?
20,158,597
22
2013-11-23T04:37:44Z
29,930,255
10
2015-04-28T21:28:07Z
[ "python", "pandas" ]
My question is the same as this previous one: [Binning with zero values in pandas](http://stackoverflow.com/questions/18921570/binning-with-zero-values-in-pandas) however, I still want to include the 0 values in a fractile. Is there a way to do this? In other words, if I have 600 values, 50% of which are 0, and the r...
You ask about binning with non-unique bin edges, for which I have a fairly simple answer. In the case of your example, your intent and the behavior of qcut diverge where in the `pandas.tools.tile.qcut` function where bins are defined: `bins = algos.quantile(x, quantiles)` Which, because your data is 50% 0s, causes bi...
cx_Oracle: ImportError: DLL load failed: This application has failed
20,159,566
7
2013-11-23T06:53:45Z
20,193,861
8
2013-11-25T13:05:00Z
[ "python", "dll", "oracle11g", "cx-oracle" ]
Here's what I did: 1. I'm on Windows XP SP3 2. I already had Python 2.7.1 installed. 3. I downloaded `instantclient-basic-nt-11.2.0.3.0.zip`, unzipped it, and put it in `C:\Program Files\Oracle\instantclient_11_2`. 4. I added this path to the Windows `Path` environment variable. 5. I created a new environment variable...
OK, what finally solved the problem (not sure whether all steps are necessary and no idea why exactly this and only this worked so far): * Download and unzip **version 12** from [here](http://www.oracle.com/technetwork/topics/winsoft-085727.html). * Add "**ORACLE\_HOME**" as a Windows environment variable and set its ...
How to solve "requires python 2.x support" in linux vim,and it have python 2.6.6 in my system
20,160,902
5
2013-11-23T09:54:57Z
30,740,335
11
2015-06-09T18:46:27Z
[ "python", "linux", "vim" ]
``` [root@localhost bin]# python -V Python 2.6.6 [root@localhost bin]# ./vim UltiSnips requires py >= 2.6 or any py3 YouCompleteMe unavailable: requires Vim compiled with Python 2.x support ``` i have try it in centos 6.4 ,and fedora 20. It's the same problem. i am new coder ,i really do not know why it happen.
With Debian 8, installing `vim-nox` helped me. ``` apt-get install vim-nox ```
How to solve "requires python 2.x support" in linux vim,and it have python 2.6.6 in my system
20,160,902
5
2013-11-23T09:54:57Z
36,834,972
13
2016-04-25T08:02:51Z
[ "python", "linux", "vim" ]
``` [root@localhost bin]# python -V Python 2.6.6 [root@localhost bin]# ./vim UltiSnips requires py >= 2.6 or any py3 YouCompleteMe unavailable: requires Vim compiled with Python 2.x support ``` i have try it in centos 6.4 ,and fedora 20. It's the same problem. i am new coder ,i really do not know why it happen.
In Ubuntu/Lubuntu 16.04, I have success with installing `vim-gnome-py2` ``` sudo apt-get install vim-gnome-py2 ``` My `vim --version | grep python` after installing it: ``` $ vim --version | grep python +cryptv +linebreak +python +vreplace +cscope +lispindent -python3 +w...
How can I use scipy.ndimage.interpolation.affine_transform to rotate an image about its centre?
20,161,175
8
2013-11-23T10:26:15Z
20,161,742
9
2013-11-23T11:28:33Z
[ "python", "numpy", "matplotlib", "rotation", "scipy" ]
I am perplexed by the API to [`scipy.ndimage.interpolation.affine_transform`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.interpolation.affine_transform.html). And judging by [this issue](https://github.com/scipy/scipy/issues/2255) I'm not the only one. I'm actually wanting to do more interesting ...
Once treddy's answer got me a working baseline, I managed to get a better working model of `affine_transform`. It's not actually as odd as the issue linked in the original question hints. Basically, each point (coordinate) `p` in the output image is transformed to `pT+s` where `T` and `s` are the matrix and offset pas...
Deploying Django project with Gunicorn and nginx
20,163,233
11
2013-11-23T14:00:43Z
20,529,091
23
2013-12-11T20:16:36Z
[ "python", "django", "nginx", "gunicorn", "ubuntu-server" ]
I am new to django, i would like to know how to set up my django project with nginx and gunicorn. I read this guide: <http://michal.karzynski.pl/blog/2013/06/09/django-nginx-gunicorn-virtualenv-supervisor/> but it doesn't work for my project. I think that it is due to the particular structure of my project, that is: `...
I'll just summarize the steps for deploying a django application with nginx & gunicorn here: ### 1. Install nginx and add this to `/etc/nginx/sites-enabled/default` ``` server { server_name 127.0.0.1 [email protected]; access_log /var/log/nginx/domain-access.log; location / { proxy_pass_header Server; ...
Is deleteLater() necessary in PyQt/PySide?
20,164,015
6
2013-11-23T15:16:17Z
20,167,458
11
2013-11-23T20:26:48Z
[ "python", "qt", "pyqt", "pyside" ]
Since there is already a Garbage Collector in Python, is deleteLater() necessary in PyQt/PySide?
It depends what you mean by "necessary". An application could *potentially* consume a lot of memory if (for example) care is not taken when closing widgets. The QObject-based classes are designed to be (optionally) linked together in a hierarchy. When a top-level object is deleted, Qt will automatically delete all its...
Celery and Django simple example
20,164,688
28
2013-11-23T16:19:49Z
20,164,820
65
2013-11-23T16:31:05Z
[ "python", "django", "celery", "scalability" ]
Let's take a simple Django example. app/models.py ``` from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User) token = models.CharField(max_length=32) ``` app/views.py ``` from django.http import HttpResponse from django.vie...
Assuming you have both Python's [celery](http://www.celeryproject.org/) and [django-celery](https://pypi.python.org/pypi/django-celery) installed, create the following `tasks.py` file under your app: **utils/tasks.py** ``` from celery import task # other imports @task() def create_user(data): user = User.object...
Argparse: how to handle variable number of arguments (nargs='*')
20,165,843
24
2013-11-23T17:57:35Z
20,167,038
16
2013-11-23T19:47:11Z
[ "python", "argparse" ]
I thought that `nargs='*'` was enough to handle a variable number of arguments. Apparently it's not, and I don't understand the cause of this error. The code: ``` p = argparse.ArgumentParser() p.add_argument('pos') p.add_argument('foo') p.add_argument('--spam', default=24, type=int, dest='spam') p.add_argument('vars'...
<http://bugs.python.org/issue15112> `argparse: nargs='*' positional argument doesn't accept any items if preceded by an option and another positional` is the relevant Python bugs issue. When argparse parses `['1', '2', '--spam', '8', '8', '9']` it first tries to match `['1','2']` with as many of the positional argume...
How to convert an OrderedDict into a regular dict in python3
20,166,749
26
2013-11-23T19:21:04Z
20,166,896
15
2013-11-23T19:33:28Z
[ "python", "type-conversion", "ordereddictionary" ]
I am struggling with the following problem: I want to convert an `OrderedDict` like this: ``` OrderedDict([('method', 'constant'), ('data', '1.225')]) ``` into a regular dict like this: ``` {'method': 'constant', 'data':1.225} ``` because I have to store it as string in a database. After the conversion the order is...
``` >>> from collections import OrderedDict >>> OrderedDict([('method', 'constant'), ('data', '1.225')]) OrderedDict([('method', 'constant'), ('data', '1.225')]) >>> dict(OrderedDict([('method', 'constant'), ('data', '1.225')])) {'data': '1.225', 'method': 'constant'} >>> ``` However, to store it in a database it'd be...
How to convert an OrderedDict into a regular dict in python3
20,166,749
26
2013-11-23T19:21:04Z
27,373,027
13
2014-12-09T06:50:53Z
[ "python", "type-conversion", "ordereddictionary" ]
I am struggling with the following problem: I want to convert an `OrderedDict` like this: ``` OrderedDict([('method', 'constant'), ('data', '1.225')]) ``` into a regular dict like this: ``` {'method': 'constant', 'data':1.225} ``` because I have to store it as string in a database. After the conversion the order is...
Even though this is a year old question, I would like to say that using `dict` will not help if you have an ordered dict within the ordered dict. The simplest way that could convert those recursive ordered dict will be ``` import json from collection import OrderedDict input_dict = OrderedDict([('method', 'constant'),...
Insert a Pandas Dataframe into mongodb using PyMongo
20,167,194
10
2013-11-23T20:01:32Z
20,167,984
12
2013-11-23T21:17:09Z
[ "python", "mongodb", "python-2.7", "pandas", "pymongo" ]
What is the quickest way to insert a pandas DataFrame into mongodb using `PyMongo`? **Attempts** ``` db.myCollection.insert(df.to_dict()) ``` gave an error `InvalidDocument: documents must have only string keys, key was Timestamp('2013-11-23 13:31:00', tz=None)` ``` db.myCollection.insert(df.to_json()) ``` gave an...
I doubt there is a both *quickest* and *simple* method. If you don't worry about data conversion, you can do ``` >>> import json >>> df = pd.DataFrame.from_dict({'A': {1: datetime.datetime.now()}}) >>> df A 1 2013-11-23 21:14:34.118531 >>> records = json.loads(df.T.to_json()).values() >>> d...
Start index at 1 when writing Pandas DataFrame to CSV
20,167,930
9
2013-11-23T21:12:24Z
20,168,416
19
2013-11-23T21:57:00Z
[ "python", "csv", "pandas" ]
I need the index to start at 1 rather than 0 when writing a Pandas DataFrame to CSV. Here's an example: ``` In [1]: import pandas as pd In [2]: result = pd.DataFrame({'Count': [83, 19, 20]}) In [3]: result.to_csv('result.csv', index_label='Event_id') ``` Which produces the following output: ``` In [4]: !cat result...
Index is an object, and default index starts from `0`: ``` >>> result.index Int64Index([0, 1, 2], dtype=int64) ``` You can shift this index by `1` with ``` >>> result.index += 1 >>> result.index Int64Index([1, 2, 3], dtype=int64) ```
linalg.norm not taking axis argument
20,168,596
6
2013-11-23T22:18:21Z
20,168,725
10
2013-11-23T22:31:35Z
[ "python", "numpy", "norm" ]
I am using Python 3 within Pyzo. Please could you tell me why the linalg.norm function does not recognise the axis argument. This code: ``` c = np.array([[ 1, 2, 3],[-1, 1, 4]]) d=linalg.norm(c, axis=1) ``` returns the error: > TypeError: norm() got an unexpected keyword argument 'axis'
`linalg.norm` does not accept an `axis` argument. You can get around that with: ``` np.apply_along_axis(np.linalg.norm, 1, c) # array([ 3.74165739, 4.24264069]) ``` Or to be faster, implement it yourself with: ``` np.sqrt(np.einsum('ij,ij->i',c,c)) # array([ 3.74165739, 4.24264069]) ``` For timing: ``` timeit np...
Calling flask restful API resource methods
20,169,326
7
2013-11-23T23:42:41Z
20,171,443
7
2013-11-24T05:29:28Z
[ "python", "flask", "flask-restful" ]
I'm creating an API with Flask that is being used for a mobile platform, but I also want the application itself to digest the API in order to render web content. I'm wondering what the best way is to access API resource methods inside of Flask? For instance if I have the following class added as a resource: ``` class ...
The obvious way for your application to consume the API is to invoke it like any other client. The fact that the application would be acting as a server and a client at the same time does not matter, the client portion can place requests into `localhost` and the server part will get them in the same way it gets externa...
how to convert from longitude and latitude to country or city?
20,169,467
2
2013-11-24T00:00:13Z
20,169,528
10
2013-11-24T00:07:30Z
[ "python", "python-2.7", "python-3.x" ]
I need to convert longitude and latitude coordinates to either country or city, is there an example of this in python? thanks in advance!
I use Google's API. ``` from urllib2 import urlopen import json def getplace(lat, lon): url = "http://maps.googleapis.com/maps/api/geocode/json?" url += "latlng=%s,%s&sensor=false" % (lat, lon) v = urlopen(url).read() j = json.loads(v) components = j['results'][0]['address_components'] country ...
How to write a dictionary into a file?
20,169,493
9
2013-11-24T00:02:46Z
20,169,670
15
2013-11-24T00:29:00Z
[ "python", "dictionary", "python-3.3" ]
Let's say I have a dictionary and I want to write it into an existing file. How can I do so without losing anything that could potentially already exist in the file? What I was thinking of is doing the following: ``` def write_report(r, filename): input_filename=open(filename, "a") input_filename.close...
You can use [`json`](http://docs.python.org/2/library/json.html) module to read and write data structures in JSON format (in other words serialize to JSON and deserialize from JSON). For example: ``` import json # load from file: with open('/path/to/my_file.json', 'r') as f: try: data = json.load(f) #...
Exe created with py2exe doesn't work and returns logfile with errors
20,169,728
10
2013-11-24T00:35:43Z
22,493,655
11
2014-03-19T00:06:16Z
[ "python", "numpy", "scipy", "py2exe", "logfile-analysis" ]
it's my first post so go easy on me. My problem is similar as in here, but I couldn't make it work, though I really tried: " [py2exe with enthought and pandas](http://stackoverflow.com/questions/18869421/py2exe-with-enthought-and-pandas) ". Having installed separately both versions of python(x84-64, x32) with librarie...
I'm having more success with PyInstaller than Py2exe. In PyInstaller, the problem is solved by explicitly adding a reference: ``` pyinstaller myscript.py --hidden-import=scipy.special._ufuncs_cxx ``` PyInstaller also takes care of the matplotlib imbroglio, and Visual Studio DLLs.
How to run the Python program forever?
20,170,251
6
2013-11-24T02:04:55Z
20,170,306
7
2013-11-24T02:14:16Z
[ "python", "infinite-loop" ]
I need to run my Python program forever in an infinite loop.. Currently I am running it like this - ``` #!/usr/bin/python # some python code that I want # to keep on running # Is this the right way to run the python program forever? # And do I even need this time.sleep call? while True: time.sleep(5) ``` Is...
Yes, you can use a `while True:` loop that never breaks to run Python code continually. However, you will need to put the code you want to run continually *inside* the loop: ``` #!/usr/bin/python while True: # some python code that I want # to keep on running ``` Also, [`time.sleep`](http://docs.python.org...
How to run the Python program forever?
20,170,251
6
2013-11-24T02:04:55Z
31,577,274
7
2015-07-23T02:38:05Z
[ "python", "infinite-loop" ]
I need to run my Python program forever in an infinite loop.. Currently I am running it like this - ``` #!/usr/bin/python # some python code that I want # to keep on running # Is this the right way to run the python program forever? # And do I even need this time.sleep call? while True: time.sleep(5) ``` Is...
How about this one? ``` import signal signal.pause() ```
Mac + virtualenv + pip + postgresql = Error: pg_config executable not found
20,170,895
52
2013-11-24T03:55:23Z
22,396,735
58
2014-03-14T05:18:15Z
[ "python", "osx", "postgresql", "psycopg2" ]
I was trying to install postgres for a tutorial, but `pip` gives me error: ``` pip install psycopg ``` A snip of error I get: ``` Error: pg_config executable not found. Please add the directory containing pg_config to the PATH or specify the full executable path with the option: python setup.py build_ext --pg...
On Mac, the solution is to install `postgresql`: ``` brew install postgresql ``` On CentOS, the solution is to install `postgresql-devel`: ``` sudo yum install postgresql-devel ``` `pg_config` is in `postgresql-devel` package
Mac + virtualenv + pip + postgresql = Error: pg_config executable not found
20,170,895
52
2013-11-24T03:55:23Z
22,429,726
15
2014-03-15T21:06:34Z
[ "python", "osx", "postgresql", "psycopg2" ]
I was trying to install postgres for a tutorial, but `pip` gives me error: ``` pip install psycopg ``` A snip of error I get: ``` Error: pg_config executable not found. Please add the directory containing pg_config to the PATH or specify the full executable path with the option: python setup.py build_ext --pg...
Don't forget that your $PATH variable in the virtual environment != your global $PATH variable. You can confirm this with 'echo $PATH' in your virtualenv and also in a new shell. So, unless you want to install PostgreSQL as a unique instance inside your virtual environment (not a thing worth doing, imo), you'll need to...
Mac + virtualenv + pip + postgresql = Error: pg_config executable not found
20,170,895
52
2013-11-24T03:55:23Z
23,097,190
10
2014-04-16T01:04:08Z
[ "python", "osx", "postgresql", "psycopg2" ]
I was trying to install postgres for a tutorial, but `pip` gives me error: ``` pip install psycopg ``` A snip of error I get: ``` Error: pg_config executable not found. Please add the directory containing pg_config to the PATH or specify the full executable path with the option: python setup.py build_ext --pg...
Here's how I was able to solve this problem on my Mac (OSX 10.9): ``` brew update brew install --force ossp-uuid brew install postgresql pip install psycopg ``` I got a CLANG error when I tried `pip install psycopg` (an [LLVM 5.1 issue](http://bruteforce.gr/bypassing-clang-error-unknown-argument.html)), so I had to i...
Mac + virtualenv + pip + postgresql = Error: pg_config executable not found
20,170,895
52
2013-11-24T03:55:23Z
24,217,329
56
2014-06-14T06:38:41Z
[ "python", "osx", "postgresql", "psycopg2" ]
I was trying to install postgres for a tutorial, but `pip` gives me error: ``` pip install psycopg ``` A snip of error I get: ``` Error: pg_config executable not found. Please add the directory containing pg_config to the PATH or specify the full executable path with the option: python setup.py build_ext --pg...
On the Mac, if you're using [Postgres.app](http://postgresapp.com/), the pg\_config file is in your `/Applications/Postgres.app/Contents/Versions/<current_version>/bin` directory. That'll need to be added to your system path to fix this error, like this: ``` export PATH=$PATH:/Applications/Postgres.app/Contents/Versio...
Mac + virtualenv + pip + postgresql = Error: pg_config executable not found
20,170,895
52
2013-11-24T03:55:23Z
26,694,779
22
2014-11-02T00:31:53Z
[ "python", "osx", "postgresql", "psycopg2" ]
I was trying to install postgres for a tutorial, but `pip` gives me error: ``` pip install psycopg ``` A snip of error I get: ``` Error: pg_config executable not found. Please add the directory containing pg_config to the PATH or specify the full executable path with the option: python setup.py build_ext --pg...
I totally agree with [john hight](http://stackoverflow.com/users/1919371/john-hight) that most of posted answers are totally offtopic assuming the OP exactly specified need of using **virtualenv**. For me the answer was runing following command in prompt while having activated virtualenv: ``` export PATH="/Applicatio...
Why is my Flask app being detected as node.js on Heroku
20,171,169
12
2013-11-24T04:37:53Z
20,171,188
30
2013-11-24T04:41:33Z
[ "python", "node.js", "heroku", "flask" ]
I recently made some changes to the structure of my Flask app hosted on heroku and now heroku has decided to detect it as a Node.js app intead of a Python app. My application uses both python (Flask) for the backend api and javascript for the front end. The changes I made included integrating npm and bower into my app...
The problem was introduced when I added a `package.json` to my root directory when I started using npm. It seems that the build detection script runs the nodejs detection first ([here](https://github.com/heroku/heroku-buildpack-nodejs/blob/master/bin/detect)) which leads to this code: `if [ -f $1/package.json ]; then e...
Why is my Flask app being detected as node.js on Heroku
20,171,169
12
2013-11-24T04:37:53Z
24,718,536
22
2014-07-13T00:35:51Z
[ "python", "node.js", "heroku", "flask" ]
I recently made some changes to the structure of my Flask app hosted on heroku and now heroku has decided to detect it as a Node.js app intead of a Python app. My application uses both python (Flask) for the backend api and javascript for the front end. The changes I made included integrating npm and bower into my app...
The `package.json` file is causing Heroku to detect it as a node.js app. To prevent this, add the file name to a [`.slugignore`](https://devcenter.heroku.com/articles/slug-compiler#ignoring-files-with-slugignore) file: ``` echo 'package.json' >> .slugignore git add .slugignore ``` --- `.slugignore` is like `.gitigno...
python pprint dictionary on multiple lines
20,171,392
18
2013-11-24T05:19:47Z
20,171,410
26
2013-11-24T05:23:33Z
[ "python", "python-2.7", "pprint" ]
I'm trying to get a pretty print of a dictionary but I'm having no luck: ``` >>> import pprint >>> a = {'first': 123, 'second': 456, 'third': {1:1, 2:2}} >>> pprint.pprint(a) {'first': 123, 'second': 456, 'third': {1: 1, 2: 2}} ``` I wanted the output to be on multiple lines, something like this: ``` {'first': 123, ...
Use `width=1` or `width=-1`: ``` In [33]: pprint.pprint(a, width=1) {'first': 123, 'second': 456, 'third': {1: 1, 2: 2}} ```
python pprint dictionary on multiple lines
20,171,392
18
2013-11-24T05:19:47Z
23,497,198
8
2014-05-06T14:12:58Z
[ "python", "python-2.7", "pprint" ]
I'm trying to get a pretty print of a dictionary but I'm having no luck: ``` >>> import pprint >>> a = {'first': 123, 'second': 456, 'third': {1:1, 2:2}} >>> pprint.pprint(a) {'first': 123, 'second': 456, 'third': {1: 1, 2: 2}} ``` I wanted the output to be on multiple lines, something like this: ``` {'first': 123, ...
If you are trying to pretty print the environment variables, use: ``` pprint.pprint(dict(os.environ), width=1) ```
Large scale server application using DDD with Python?
20,172,839
7
2013-11-24T09:05:59Z
20,175,810
7
2013-11-24T14:40:51Z
[ "python", "dependency-injection", "domain-driven-design" ]
We are a python shop and are preparing to build a large scale server application. To model the logic effectively we're planning to use DDD, including the tactical patterns such as domain events, specifications, repositories and etc... Is onion architecture applicable in python? Are the abstraction abilities sufficien...
Not sure, but it sounds like you may be a new hire within this org coming from a java/.net shop ("...*considering that DI is how i'm used to instantiating complex objects in the application layer it seems suspicious*...). **Keep in mind** * You can do DDD with clean design in almost any programming language. * Take a...
how to install PIL with JPEG support on a raspberry pi?
20,176,883
6
2013-11-24T16:25:40Z
20,176,884
11
2013-11-24T16:25:40Z
[ "python", "python-imaging-library", "pip", "raspberry-pi" ]
I tried to install [PIL](http://www.pythonware.com/products/pil/) on my raspberry pi and read JPEG files. However, it does not work out of the box. When I run the following: ``` sudo pip install pil ``` I receive the following error, trying to open an Image: ``` ""decoder jpeg not available"" ``` While trying to i...
You have to re-install PIL and also install the needed libraries as well as link them manually. This answer is based on [this blog post](http://jj.isgeek.net/2011/09/install-pil-with-jpeg-support-on-ubuntu-oneiric-64bits/) for a regular ubuntu PIL installation and this [askubuntu question](http://askubuntu.com/question...
uWSGI: No request plugin is loaded, you will not be able to manage requests
20,176,959
18
2013-11-24T16:33:01Z
24,719,979
26
2014-07-13T05:54:31Z
[ "python", "uwsgi" ]
I've loaded uWSGI v 1.9.20, built from source. I'm getting this error, but how do I tell which plugin is needed? ``` !!!!!!!!!!!!!! WARNING !!!!!!!!!!!!!! no request plugin is loaded, you will not be able to manage requests. you may need to install the package for your language of choice, or simply load it with --plug...
I had this problem and was stuck for hours. my issue is different than the answer listed, make sure you have `plugins = python` in your uwsgi ini file and you install the `uwsgi python` plugin: ``` sudo apt-get install uwsgi-plugin-python ``` After I did the above my application worked. Obviously this is for `python...
Can not the computed centroid values to be plotted over the existing plot based on data
20,177,429
10
2013-11-24T17:17:32Z
20,179,838
10
2013-11-24T19:26:57Z
[ "python", "numpy", "matplotlib", "plot", "scipy" ]
EDIT: Ok, if the data are two dimensional as follows: ``` x = [1,1,1,2,2,2,3,3,3,4,4,4,5,5,5] y = [8,7,5,4,3,7,8,3,2,1,9,11,16,18,19] ``` Then, how to calculate the k means (3 values) and make plot? --- Can not the computed centroid values be plotted over the existing plot based on data here? I want to make the sim...
### A minor edit to answer your question about 2d: You can use the original answer below, just take: ``` data = np.column_stack([x,y]) ``` If you want to plot the centroids, it is the same as below in the original answer. If you want to color each value by the group selected, you can use `kmeans2` ``` from scipy.cl...
Django filter queryset on "tuples" of values for multiple columns
20,177,749
5
2013-11-24T17:46:21Z
20,177,875
7
2013-11-24T17:58:33Z
[ "python", "sql", "django", "django-queryset" ]
Say I have a model: ``` Class Person(models.Model): firstname = models.CharField() lastname = models.CharField() birthday = models.DateField() # etc... ``` and say I have a list of 2 first names: `first_list = ['Bob', 'Rob']` And I have a list of 2 last names: `last_list = ['Williams', 'Williamson']`....
I don't see much solutions except for a big OR clause: ``` import operator from itertools import izip query = reduce( operator.or_, (Q(firstname=fn, lastname=ln) for fn, ln in izip(first_list, last_list)) ) Person.objects.filter(query) ```
Python how to combine two matrices in numpy
20,180,210
8
2013-11-24T19:57:19Z
20,180,238
15
2013-11-24T19:59:59Z
[ "python", "numpy", "matrix" ]
new to Python, struggling in numpy, hope someone can help me, thank you! ``` from numpy import * A = matrix('1.0 2.0; 3.0 4.0') B = matrix('5.0 6.0') C = matrix('1.0 2.0; 3.0 4.0; 5.0 6.0') print "A=",A print "B=",B print "C=",C ``` results: ``` A= [[ 1. 2.] [ 3. 4.]] B= [[ 5. 6.]] C= [[ 1. 2.] [ 3. ...
Use [`numpy.concatenate`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html): ``` >>> import numpy as np >>> np.concatenate((A, B)) matrix([[ 1., 2.], [ 3., 4.], [ 5., 6.]]) ```
Bin pandas dataframe by every X rows
20,180,324
4
2013-11-24T20:06:56Z
20,180,364
8
2013-11-24T20:09:34Z
[ "python", "pandas", "dataframe", "binning" ]
I have a simple dataframe which I would like to bin for every 3 rows. It looks like this: ``` col1 0 2 1 1 2 3 3 1 4 0 ``` and I would like to turn it into this: ``` col1 0 2 1 0.5 ``` I have already posted a similar question [here](http://stackoverflow.com/questions/201343...
``` >>> df.groupby(df.index / 3).mean() col1 0 2.0 1 0.5 ```
How to check version of python modules?
20,180,543
147
2013-11-24T20:25:01Z
20,180,564
119
2013-11-24T20:28:04Z
[ "python", "version", "construct" ]
I just installed the python modules: `construct` and `statlib` with `setuptools` like this: ``` # Install setuptools to be able to download the following sudo apt-get install python-setuptools # Install statlib for lightweight statistical tools sudo easy_install statlib # Install construct for packing/unpacking bina...
You can try ``` >>> import statlib >>> print statlib.__version__ >>> import construct >>> print contruct.__version__ ```
How to check version of python modules?
20,180,543
147
2013-11-24T20:25:01Z
20,180,597
163
2013-11-24T20:30:33Z
[ "python", "version", "construct" ]
I just installed the python modules: `construct` and `statlib` with `setuptools` like this: ``` # Install setuptools to be able to download the following sudo apt-get install python-setuptools # Install statlib for lightweight statistical tools sudo easy_install statlib # Install construct for packing/unpacking bina...
I suggest using [pip in place of easy\_install](http://stackoverflow.com/a/3220572/1265154). With pip, you can list all installed packages and their versions with ``` pip freeze ``` For an individual module, you can try [`__version__` attribute](http://www.python.org/dev/peps/pep-0396/), however there are modules wit...
How to check version of python modules?
20,180,543
147
2013-11-24T20:25:01Z
23,324,265
35
2014-04-27T13:55:40Z
[ "python", "version", "construct" ]
I just installed the python modules: `construct` and `statlib` with `setuptools` like this: ``` # Install setuptools to be able to download the following sudo apt-get install python-setuptools # Install statlib for lightweight statistical tools sudo easy_install statlib # Install construct for packing/unpacking bina...
I think this can help ``` pip show YOUR_PACKAGE_NAME | grep Version ```
How to check version of python modules?
20,180,543
147
2013-11-24T20:25:01Z
26,626,247
9
2014-10-29T09:03:41Z
[ "python", "version", "construct" ]
I just installed the python modules: `construct` and `statlib` with `setuptools` like this: ``` # Install setuptools to be able to download the following sudo apt-get install python-setuptools # Install statlib for lightweight statistical tools sudo easy_install statlib # Install construct for packing/unpacking bina...
In python3 with brackets around print ``` >>> import celery >>> print(celery.__version__) 3.1.14 ```
How to check version of python modules?
20,180,543
147
2013-11-24T20:25:01Z
32,965,521
22
2015-10-06T08:46:28Z
[ "python", "version", "construct" ]
I just installed the python modules: `construct` and `statlib` with `setuptools` like this: ``` # Install setuptools to be able to download the following sudo apt-get install python-setuptools # Install statlib for lightweight statistical tools sudo easy_install statlib # Install construct for packing/unpacking bina...
Use `pkg_resources` module distributed with `setuptools` library. Note that the string that you pass to `get_distribution` method should correspond to the PyPI entry. ``` >>> import pkg_resources >>> pkg_resources.get_distribution("construct").version '2.5.2' ``` and if you want to run it from the command line you ca...
Pygame: Collision by Sides of Sprite
20,180,594
2
2013-11-24T20:30:22Z
20,183,823
7
2013-11-25T02:14:42Z
[ "python", "pygame", "sprite", "collision" ]
Is there a way in pygame to look for a collision between the a particular side of a sprite and a particular side of another sprite in pygame? For example, if the top of sprite A collides with the bottom of Sprite B, return True. I am certain there is a way to do this, but I can't find any particular method in the docu...
There is no function to get sides collision in PyGame. But you could try to use [pygame.Rect.collidepoint](http://pygame.org/docs/ref/rect.html#Rect.collidepoint) to test if `A.rect.midleft`, `A.rect.midright`, `A.rect.midtop`, `A.rect.midbottom`, `A.rect.topleft`, `A.rect.bottomleft` , `A.rect.topright`, `A.rect.bott...
Changing the background color of a Button in Kivy
20,181,250
6
2013-11-24T21:28:27Z
20,181,407
9
2013-11-24T21:44:10Z
[ "python", "kivy" ]
I'm new to Kivy and having trouble specifying the background color of a Button. Here's my simple example: ``` # custombutton.py from kivy.app import App from kivy.uix.widget import Widget class MyWidget(Widget): pass class CustomButtonApp(App): def build(self): return MyWidget() if __name__ == '...
Ah, this is a common confusion. The problem is that `Button.background_color` really works as a kind of *tint*, not just a block colour. Since the default background is a grey image (the one you normally see if you make an unstyled button), what you end up seeing is a red tint to that grey image - which comes out as th...
Sum up column values in Pandas DataFrame
20,181,456
10
2013-11-24T21:48:18Z
20,181,686
17
2013-11-24T22:06:15Z
[ "python", "python-2.7", "pandas" ]
In a pandas DataFrame, is it possible to collapse columns which have identical values, and sum up the values in another column? **Code** ``` data = {"score":{"0":9.397,"1":9.397,"2":9.397995,"3":9.397996,"4":9.3999},"type":{"0":"advanced","1":"advanced","2":"advanced","3":"newbie","4":"expert"},"count":{"0":394.18930...
This is a job for `groupby`: ``` >>> df.groupby(["score", "type"]).sum() count score type 9.397000 advanced 537.331573 9.397995 advanced 9.641728 9.397996 newbie 0.100000 9.399900 expert 19.6541374 >>> df.groupby(["score", "type"], as_index=False).sum() sco...