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
Linear regression with pandas dataframe
19,379,295
6
2013-10-15T10:47:22Z
19,380,761
12
2013-10-15T12:04:34Z
[ "python", "numpy", "matplotlib", "pandas", "regression" ]
I have a dataframe in pandas that I'm using to produce a scatterplot, and want to include a regression line for the plot. Right now I'm trying to do this with polyfit. Here's my code: ``` import pandas as pd import matplotlib import matplotlib.pyplot as plt from numpy import * table1 = pd.DataFrame.from_csv('upregul...
Instead of replacing '#DIV/0!' by hand, force the data to be numeric. This does two things at once: it ensures that the result is numeric type (not str), and it substitutes `NaN` for any entries that cannot be parsed as a number. Example: ``` In [5]: Series([1, 2, 'blah', '#DIV/0!']).convert_objects(convert_numeric=Tr...
TypeError: 'str' object is not callable (I'm not calling it?)
19,382,639
2
2013-10-15T13:34:39Z
19,382,660
8
2013-10-15T13:35:33Z
[ "python", "string", "file", "function" ]
I'm trying to have a function write to a file with 4 different string variables passed into what is written, but for whatever reason when this is attempted, I get this: ``` Traceback (most recent call last): File "C:\Python Files\writePy\writePy.py", line 34, in <module> indent = writeIf(mFile, genCond(), lFile,...
You forgot the modulo operator (`%`): ``` file.write('%sif (%s %s %s):' % (indentation, cond[0], cond[1], cond[2])) # here --^ ```
How to parse the POST argument to a REST service?
19,384,526
6
2013-10-15T14:59:55Z
19,624,637
7
2013-10-27T22:54:20Z
[ "python", "json", "rest", "flask", "flask-restful" ]
It seems I have another JSON problem, this time when posting to the REST service. I am using `Flask-Restful`. ``` api.add_resource(Records, '/rest/records/<string:email>/<string:password>/<string:last_sync_date>') parser = reqparse.RequestParser() parser.add_argument('record_date', type=str) parser.add_argument('reco...
I ended up raising this as an issue on flask-resful github and got this solution, which works for me. Credit goes to Doug Black. reqparse doesn't really know how to handle JSON. To deal with JSON posts, you'll want to use the flask.request.json dict. Here's an updated example for what you probably want: ``` from fla...
How to count number of rows in a group in pandas group by object?
19,384,532
49
2013-10-15T15:00:12Z
19,385,591
72
2013-10-15T15:49:28Z
[ "python", "group-by", "pandas", "distinct" ]
I have a data frame `df` and I use several columns from it to `groupby`: ``` df['col1','col2','col3','col4'].groupby(['col1','col2']).mean() ``` In the above way I almost get the table (data frame) that I need. What is missing is an additional column that contains number of rows in each group. In other words, I have ...
On `groupby` object, the `agg` function can take a list to [apply several aggregation methods](http://pandas.pydata.org/pandas-docs/stable/groupby.html#applying-multiple-functions-at-once) at once. This should give you the result you need: ``` df[['col1', 'col2', 'col3', 'col4']].groupby(['col1', 'col2']).agg(['mean',...
How to count number of rows in a group in pandas group by object?
19,384,532
49
2013-10-15T15:00:12Z
32,801,170
71
2015-09-26T19:34:51Z
[ "python", "group-by", "pandas", "distinct" ]
I have a data frame `df` and I use several columns from it to `groupby`: ``` df['col1','col2','col3','col4'].groupby(['col1','col2']).mean() ``` In the above way I almost get the table (data frame) that I need. What is missing is an additional column that contains number of rows in each group. In other words, I have ...
## tl;dr If you just want to count the number of rows per group, do: ``` df.groupby(key_columns).size() ``` where `key_columns` is the column or list of columns you are grouping by. For example `key_columns = ['col1','col2']` ### A simple example: ``` In [1]: import pandas as pd In [2]: df = pd.DataFrame([['a', 1...
Duplicate items in legend in matplotlib?
19,385,639
6
2013-10-15T15:51:47Z
19,386,045
14
2013-10-15T16:13:22Z
[ "python", "matplotlib" ]
I am trying to add the legend to my plot with this snippet: ``` import matplotlib.pylab as plt fig = plt.figure() axes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # left, bottom, width, height (range 0 to 1) axes.set_xlabel('x (m)') axes.set_ylabel('y (m)') for i, representative in enumerate(representatives): axes.plot(...
As the [docs](http://matplotlib.org/users/legend_guide.html) say, although it's easy to miss: > If label attribute is empty string or starts with “\_”, those artists > will be ignored. So if I'm plotting similar lines in a loop and I only want one example line in the legend, I usually do something like ``` ax.pl...
Python Scrapy on offline (local) data
19,385,837
11
2013-10-15T16:02:06Z
19,386,118
20
2013-10-15T16:16:55Z
[ "python", "scrapy", "web-crawler" ]
I have a 270MB dataset (10000 html files) on my computer. Can I use Scrapy to crawl this dataset locally? How?
# SimpleHTTP Server Hosting If you truly want to host it locally and use scrapy, you could serve it by navigating to the directory it's stored in and run the SimpleHTTPServer (port 8000 shown below): ``` python -m SimpleHTTPServer 8000 ``` Then just point scrapy at 127.0.0.1:8000 ``` $ scrapy crawl 127.0.0.1:8000 `...
Python Scrapy on offline (local) data
19,385,837
11
2013-10-15T16:02:06Z
19,387,287
9
2013-10-15T17:25:03Z
[ "python", "scrapy", "web-crawler" ]
I have a 270MB dataset (10000 html files) on my computer. Can I use Scrapy to crawl this dataset locally? How?
Go to your Dataset folder : ``` import os files = os.listdir(os.getcwd()) for file in files: with open(file,"r") as f: page_content = f.read() #do here watever you want to do with page_content. I guess parsing with lxml or Beautiful soup. ``` No need to go for Scrapy !
Python: get OS language
19,387,200
2
2013-10-15T17:20:13Z
19,387,327
9
2013-10-15T17:27:15Z
[ "python" ]
What is a way to get current Windows (or OSX) Locale id on Python 2.x. I want to get an int (or str) which tells what language in OS is active. Is possible without using WinAPI?
This is the documentation related to the **[locale](http://www.python.org/doc//current/library/locale.html)** module in Python 2.6. To be more specific, here is an example (from the above link) of how to get your system's locale: ``` import locale loc = locale.getlocale() # get current locale locale.getdefaultlocale(...
`AttributeError: rint` when using numpy.round
19,387,608
8
2013-10-15T17:42:59Z
19,387,989
10
2013-10-15T18:02:38Z
[ "python", "arrays", "numpy" ]
I have a numpy array that looks like this: ``` [[41.743617 -87.626839] [41.936943 -87.669838] [41.962665 -87.65571899999999]] ``` I want to round the numbers in the array to two decimal places, or three. I tried using numpy.around and numpy.round, but both of them give me the following error: ``` File "/Library/...
You cannot round numpy arrays that are objects, this can be changed with `astype` as long as your array can be safely converted to floats: ``` >>> a = np.random.rand(5).astype(np.object) >>> a array([0.5137250555772075, 0.4279757819721647, 0.4177118178603122, 0.6270676923544128, 0.43733218329094947], dtype=obje...
Does python support unicode beyond basic multilingual plane?
19,388,486
4
2013-10-15T18:29:43Z
19,388,574
9
2013-10-15T18:33:45Z
[ "python", "python-2.7", "unicode" ]
Below is a simple test. `repr` seems to work fine. yet `len` and `x for x in` doesn't seem to divide the unicode text correctly in Python 2.6 and 2.7: ``` In [1]: u"爨爵" Out[1]: u'\U0002f920\U0002f921' In [2]: [x for x in u"爨爵"] Out[2]: [u'\ud87e', u'\udd20', u'\ud87e', u'\udd21'] ``` Good news is...
Yes, provided you compiled your Python with wide-unicode support. By default, Python is built with narrow unicode support only. Enable wide support with: ``` ./configure --enable-unicode=ucs4 ``` You can verify what configuration was used by testing [`sys.maxunicode`](http://docs.python.org/3.1/library/sys.html#sys....
How do Python's any and all functions work?
19,389,490
53
2013-10-15T19:31:14Z
19,389,954
7
2013-10-15T20:00:16Z
[ "python" ]
I'm trying to understand how the `any()` and `all()` Python built-in functions work. I'm trying to compare the tuples so that if any value is different then it will return `True` and if they are all the same it will return `False`. How are they working in this case to return [False, False, False]? `d` is a `defaultdi...
The code in question you're asking about comes from my answer given [here](http://stackoverflow.com/questions/19258605/difference-between-multiple-elements-in-list-with-same-string-python-2-7/). It was intended to solve the problem of comparing multiple bit arrays - i.e. collections of `1` and `0`. `any` and `all` are...
How do Python's any and all functions work?
19,389,490
53
2013-10-15T19:31:14Z
19,389,957
102
2013-10-15T20:00:29Z
[ "python" ]
I'm trying to understand how the `any()` and `all()` Python built-in functions work. I'm trying to compare the tuples so that if any value is different then it will return `True` and if they are all the same it will return `False`. How are they working in this case to return [False, False, False]? `d` is a `defaultdi...
You can roughly think of `any` and `all` as series of logical `or` and `and` operators, respectively. **any** `any` will return `True` when **atleast one of the elements** is Truthy. Read about [Truth Value Testing.](http://docs.python.org/2/library/stdtypes.html#truth-value-testing) **all** `all` will return `True...
In Python NumPy what is a dimension and axis?
19,389,910
16
2013-10-15T19:57:48Z
19,390,939
23
2013-10-15T20:58:24Z
[ "python", "numpy" ]
I am coding with Pythons NumPy module. If coordinates of a point in 3D space are described as [1, 2, 1], wouldnt that be 3 dimensions, 3 axis, a rank of 3? Or if that is 1 dimension then shouldnt it be points (plural), not point? Here is the documentation: > In Numpy dimensions are called axes. The number of axes is ...
In numpy `array`s, dimensionality refers to the number of `axes` needed to index it, not the dimensionality of any geometrical space. For example, you can describe the locations of points in 3D space with a 2D array: ``` array([[0, 0, 0], [1, 2, 3], [2, 2, 2], [9, 9, 9]]) ``` Which has `shape` of...
Scatterplot Contours In Matplotlib
19,390,320
11
2013-10-15T20:22:06Z
19,391,256
33
2013-10-15T21:16:53Z
[ "python", "matplotlib", "contour", "scatter-plot" ]
I have a massive scatterplot (~100,000 points) that I'm generating in matplotlib. Each point has a location in this x/y space, and I'd like to generate contours containing certain percentiles of the total number of points. Is there a function in matplotlib which will do this? I've looked into contour(), but I'd have t...
Basically, you're wanting a density estimate of some sort. There multiple ways to do this: 1. Use a 2D histogram of some sort (e.g. `matplotlib.pyplot.hist2d` or `matplotlib.pyplot.hexbin`) (You could also display the results as contours--just use `numpy.histogram2d` and then contour the resulting array.) 2. Make a ke...
Matplotlib plot with variable line width
19,390,895
16
2013-10-15T20:55:22Z
20,474,765
40
2013-12-09T15:51:25Z
[ "python", "matplotlib", "plot" ]
Is it possible to plot a line with variable line width in matplotlib? For example: ``` from pylab import * x = [1, 2, 3, 4, 5] y = [1, 2, 2, 0, 0] width = [.5, 1, 1.5, .75, .75] plot(x, y, linewidth=width) ``` This doesn't work because *linewidth* expects a scalar. *Note:* I'm aware of \*fill\_between()\* and \*fil...
Use LineCollections. A way to do it along the lines of [this](http://matplotlib.org/examples/pylab_examples/multicolored_line.html) Matplotlib example is ``` from matplotlib.collections import LineCollection x=linspace(0,4*pi,10000) y=cos(x) lwidths=1+x[:-1] points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np....
Numpy mean AND variance from single function?
19,391,149
14
2013-10-15T21:10:29Z
19,391,264
19
2013-10-15T21:17:21Z
[ "python", "numpy" ]
Using Numpy/Python, is it possible to return the mean AND variance from a single function call? I know that I can do them separately, but the mean is required to calculate the sample standard deviation. So if I use separate functions to get the mean and variance I am adding unnecesary overhead. I have tried looking a...
You can't pass a known mean to `np.std` or `np.var`, you'll have to wait for the [new standard library `statistics` module](http://www.python.org/dev/peps/pep-0450/), but in the meantime you can save a little time by using the formula: ``` In [329]: a = np.random.rand(1000) In [330]: %%timeit .....: a.mean() .....
Keeping large dictionary in Python affects application performance
19,391,648
16
2013-10-15T21:42:19Z
19,391,867
34
2013-10-15T22:00:04Z
[ "python", "dictionary", "garbage-collection" ]
I'm having some difficulties understanding (and ultimately solving) why having a large dictionary in memory makes creation of other dictionaries longer. Here's the test code that I'm using ``` import time def create_dict(): # return {x:[x]*125 for x in xrange(0, 100000)} return {x:(x)*125 for x in xrange(0, ...
"Dictionary creation" is really a red herring here. What the dictionary creation does in this case that's *relevant* is that it creates a hundred thousand new 125-element lists. Because lists can be involved in reference cycles, that creates 12.5 million list elements CPython's cyclic garbage collection has to examine ...
Python Random List Comprehension
19,394,805
3
2013-10-16T03:38:19Z
19,395,093
7
2013-10-16T04:10:58Z
[ "python" ]
I have a list similar to: ``` [1 2 1 4 5 2 3 2 4 5 3 1 4 2] ``` I want to create a list of x random elements from this list where none of the chosen elements are the same. The difficult part is that I would like to do this by using list comprehension... So possible results if x = 3 would be: ``` [1 2 3] [2 4 5] [3 1...
Disclaimer: the "use a list comprehension" requirement is absurd. Moreover, if you want to use the weights, there are many excellent approaches listed at Eli Bendersky's page on [weighted random sampling](http://eli.thegreenplace.net/2010/01/22/weighted-random-generation-in-python/). The following is inefficient, doe...
What's going on in this code?
19,395,365
7
2013-10-16T04:40:14Z
19,395,477
8
2013-10-16T04:51:52Z
[ "python", "python-3.x" ]
``` x,y,z = [1,2,3], [4,5,6], [7,8,9] for a,b,c in x,y,z: print(a,b,c) ``` The output is : ``` 1 2 3 4 5 6 7 8 9 ``` I can't mentally navigate whatever logic is going on here to produce this output. I am aware of the zip function to make this code behave in the way I clearly intend it to; but I'm just trying to ...
You have good answers already, but I think considering this equivalent variation will help to make it clearer: ``` x,y,z = [1,2,3], [4,5,6], [7,8,9] for t in x,y,z: a, b, c = t print(a,b,c) ``` You're not surprised that `t` is successively bound to `x`, `y` and `z`, right? Exactly the same thing is happening ...
How to iterate over two different-size lists to get a new list?
19,395,774
2
2013-10-16T05:19:57Z
19,395,793
8
2013-10-16T05:21:56Z
[ "python" ]
Now I wish to build a list containing `100*50` 2-D points. I have tried the following: ``` [(x+0.5, y+0.5) for x, y in zip(range(100), range(50))] ``` This only gives me 50\*50 points. I found the reason accounting for this in [this answer](http://stackoverflow.com/a/1919402/2881553) that pointed out > for zip the l...
Well, I think you want `itertools.product` instead of `zip`. `itertools.product` calculates the cartesian product of the two lists and will give you the total 100\*50 points. The way you would do this would be ``` import itertools [(x+0.5,y+0.5) for x,y in itertools.product(range(100),range(50))] ``` You could also...
Calling Python function from Go and getting the function return value
19,397,986
2
2013-10-16T07:56:06Z
19,403,046
7
2013-10-16T12:10:32Z
[ "python", "go" ]
I am writing a [Go](http://golang.org/) program. From this Go program, I would like to call a Python function defined in another file and receive the function's return value so I can use it in subsequent processing in my Go program. I am having trouble getting any returned data back in my Go program though. Below is a ...
I managed to have some working code for this by simply removing the quote around the command itself: ``` package main import "fmt" import "os/exec" func main() { cmd := exec.Command("python", "-c", "import pythonfile; print pythonfile.cat_strings('foo', 'bar')") fmt.Println(cmd.Args) out, err := cmd.Com...
TypeError: can only concatenate list (not "str") to list
19,398,993
7
2013-10-16T08:54:10Z
19,399,039
7
2013-10-16T08:56:28Z
[ "python" ]
I am trying to make an inventory program to use in an RPG game. The program needs to be able to add and remove things and add them to a list. This is what I have so far: ``` inventory=["sword","potion","armour","bow"] print(inventory) print("\ncommands: use (remove) and pickup (add)") selection=input("choose a command...
I think what you want to do is add a new item to your list, so you have change the line `newinv=inventory+str(add)` with this one: ``` newinv = inventory.append(add) ``` What you are doing now is trying to concatenate a list with a string which is an invalid operation in Python. However I think what you want is to a...
Accessing key in factory of defaultdict
19,399,032
8
2013-10-16T08:56:10Z
19,399,198
13
2013-10-16T09:03:53Z
[ "python", "python-2.7", "dictionary", "defaultdict" ]
I am trying to do something similar to this: ``` from collections import defaultdict import hashlib def factory(): key = 'aaa' return { 'key-md5' : hashlib.md5('%s' % (key)).hexdigest() } a = defaultdict(factory) print a['aaa'] ``` (actually, the reason why I need access to the key in the factory is not t...
[`__missing__`](http://docs.python.org/2/library/collections.html#collections.defaultdict.__missing__) of `defaultdict` does not pass `key` to factory function. > If `default_factory` is not `None`, it is called **without arguments** to > provide a default value for the given key, this value is inserted in > the dicti...
python-requests 2.0.0 - [Errno 8] _ssl.c:504: EOF occurred in violation of protocol
19,399,975
4
2013-10-16T09:40:05Z
19,403,657
7
2013-10-16T12:38:36Z
[ "python", "https", "python-requests" ]
I'm using Requests 2.0.0 and failed to complete https GET request using: ``` requests.get('https://backend.iddiction.com/rest/v1/s2s/confirm_install?apphandle=slotsjourneyofmagic&appsecret=5100d103e146e2c3f22af2c24ff4e2ec&mac=50:EA:D6:E7:9B:C2&idfa=134DA32A-A99F-4864-B69E-4A7A2EFC6C25') ``` I get this Error: ``` [Er...
The server requires that you use SNI, which isn't normally available in Python 2.x. If you open that URL in a browser and use Wireshark to trace out the TLS handshake, you can see that Chrome proposes the server name and that the remote server uses it to determine which certificate to use. To make this work in Reques...
Easy_install and pip broke: pkg_resources.DistributionNotFound: distribute==0.6.36
19,400,370
27
2013-10-16T09:58:36Z
19,400,718
64
2013-10-16T10:13:35Z
[ "python", "pip", "distribute" ]
I was tried to upgrade pip with `pip install --upgrade pip` on OSX and pip and easy\_install both dont work. When running pip ``` Traceback (most recent call last): File "/usr/local/bin/pip", line 5, in <module> from pkg_resources import load_entry_point File "/usr/local/Cellar/python/2.7.4/Frameworks/Python....
Install the distribute package as follows: ``` $ wget https://svn.apache.org/repos/asf/oodt/tools/oodtsite.publisher/trunk/distribute_setup.py $ python distribute_setup.py ``` You will have a working `easy_install` then. Happy Coding.
Easy_install and pip broke: pkg_resources.DistributionNotFound: distribute==0.6.36
19,400,370
27
2013-10-16T09:58:36Z
19,606,012
11
2013-10-26T11:13:02Z
[ "python", "pip", "distribute" ]
I was tried to upgrade pip with `pip install --upgrade pip` on OSX and pip and easy\_install both dont work. When running pip ``` Traceback (most recent call last): File "/usr/local/bin/pip", line 5, in <module> from pkg_resources import load_entry_point File "/usr/local/Cellar/python/2.7.4/Frameworks/Python....
If you do this then it will work: ``` cd /usr/local/lib/python2.7/site-packages && ls ``` Find `pip-1.4.1-py2.7.egg-info` and `distribute-0.6.49-py2.7.egg` in the directory. Then the following steps fixed the issue: * Changed the pip version to 1.4.1 in `/usr/local/bin/pip` * Changed distribute version to 0.6.49 in...
Easy_install and pip broke: pkg_resources.DistributionNotFound: distribute==0.6.36
19,400,370
27
2013-10-16T09:58:36Z
23,439,875
9
2014-05-03T03:25:59Z
[ "python", "pip", "distribute" ]
I was tried to upgrade pip with `pip install --upgrade pip` on OSX and pip and easy\_install both dont work. When running pip ``` Traceback (most recent call last): File "/usr/local/bin/pip", line 5, in <module> from pkg_resources import load_entry_point File "/usr/local/Cellar/python/2.7.4/Frameworks/Python....
None of the other answers worked for me. It was much simpler with [these instructions](http://backup.noiseandheat.com/blog/2012/09/easy-install-and-broken-setuptools-on-os-x/). I had installed an extra copy of easy\_install at /usr/local/bin/easy\_install and /usr/local/bin/easy\_install-2.7. I am pretty sure I did so ...
Pandas groupby and qcut
19,403,133
6
2013-10-16T12:15:41Z
19,403,897
12
2013-10-16T12:49:34Z
[ "python", "group-by", "pandas" ]
Is there a way to structure Pandas groupby and qcut commands to return one column that has nested tiles? Specifically, suppose I have 2 groups of data and I want qcut applied to each group and then return the output to one column. This would be similar to MS SQL Server's ntile() command that allows Partition by(). ```...
``` import pandas as pd df = pd.DataFrame({'A':'foo foo foo bar bar bar'.split(), 'B':[0.1, 0.5, 1.0]*2}) df['C'] = df.groupby(['A'])['B'].transform( lambda x: pd.qcut(x, 3, labels=range(1,4))) print(df) ``` yields ``` A B C 0 foo 0.1 1 1 foo 0.5 2 2 foo 1.0 ...
Python: using __getitem__ in a class and using in to find that item
19,406,373
4
2013-10-16T14:39:08Z
19,406,436
7
2013-10-16T14:41:25Z
[ "python" ]
I do the following ``` class dumb(object): def __init__(self): self.g = {} def __getitem__(self,key): return self.g[key] if key in self.g else None def __setitem__(self,key,val): self.g[key] = val te = dumb() te[1]=2 te[1] Out[4]: 2 1 in te ``` and it hangs.. So if I want to search s...
For `in` to work correctly, you need to override [`__contains__()`](http://infohost.nmt.edu/tcc/help/pubs/python/web/contains-method.html): ``` class dumb(object): ... def __contains__(self, key): return key in self.g ``` By the way, ``` self.g[key] if key in self.g else None ``` can be more succinc...
SQLAlchemy convert SELECT query result to a list of dicts
19,406,859
10
2013-10-16T15:00:09Z
19,415,231
12
2013-10-16T22:42:31Z
[ "python", "sqlalchemy" ]
When I was using session.query, I was able to convert the result to a list of dicts : ``` my_query = session.query(table1,table2).filter(all_filters) result_dict = [u.__dict__ for u in my_query.all()] ``` But now that I have to work with the `SELECT()` operation, how can I convert the results to a dict that looks lik...
This seems to be a RowProxy object. Try: ``` row = dict(zip(row.keys(), row)) ```
xlrd import issue with Python 2.7
19,407,469
2
2013-10-16T15:26:17Z
27,783,888
8
2015-01-05T16:38:25Z
[ "python", "python-2.7", "xlrd" ]
I have an assignment to read excel data in Python. I have Python 2.7 installed. I tried installing xlrd0.8.0 with the following commands in Windows. ``` C:\Python27\xlrd-0.8.0>python setup.py build running build running build_py creating build creating build\lib creating build\lib\xlrd copying xlrd\biffh.py -> build\l...
**How to reproduce and fix this error:** Open the python interpreter, try to import xlrt, you get an error: ``` python >>> import xlrt Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named xlrt ``` **1. Install, or make sure pip is installed:** [What is the official "...
Sample of Server to Server authentication using OAuth 2.0 with Google API's
19,407,600
3
2013-10-16T15:31:29Z
19,413,874
8
2013-10-16T21:05:13Z
[ "python", "google-app-engine", "oauth" ]
This is a follow-up question for [this question](http://stackoverflow.com/questions/19391252/how-to-obtain-a-private-key-for-a-legacy-google-app-engine-project): I have successfully created a private key and have read the various pages of Google documentation on the concepts of server to server authentication. I need...
After some digging I found a [couple of samples](https://code.google.com/p/google-api-python-client/source/browse/#hg/samples/service_account) based on the OAuth2 authentication. From this I cooked up the following simple sample that creates a JWT to access the calendar API: ``` import httplib2 import pprint from api...
Align vertically two plots in matplotlib provided one is an imshow plot?
19,407,950
3
2013-10-16T15:48:04Z
19,411,268
7
2013-10-16T18:43:15Z
[ "python", "matplotlib", "alignment" ]
I want to align the x-axis of two plots, provided one is an `imshow` plot. I have tried to use `gridspec` as it follows: ``` import matplotlib.pyplot as plt import numpy as np import matplotlib.gridspec as grd v1 = np.random.rand(50,150) v2 = np.random.rand(150) fig = plt.figure() gs = grd.GridSpec(2,1,height_rati...
The image isn't filling up the space because the aspect ratio of the figure is different than axis. One option is to change the aspect ratio of your image. You can keep the image and the line graph aligned by using a two by two grid and putting the color bar in it's own axis. ``` import matplotlib.pyplot as plt import...
Comparing Pandas Dataframe Rows & Dropping rows with overlapping dates
19,409,335
7
2013-10-16T16:59:40Z
19,409,827
11
2013-10-16T17:25:08Z
[ "python", "pandas" ]
I have a dataframe filled with trades taken from a trading strategy. The logic in the trading strategy needs to be updated to ensure that trade isn't taken if the strategy is already in a trade - but that's a different problem. The trade data for many previous trades is read into a dataframe from a csv file. Here's my...
You should use some kind of boolean mask to do this kind of operation. One way is to create a dummy column for the next trade: ``` df['EntryNextTrade'] = df['EntryDate'].shift() ``` Use this to create the mask: ``` msk = df['EntryNextTrade'] > df'[ExitDate'] ``` And use loc to look at the subDataFrame where msk is...
How to count the number of words in a sentence?
19,410,018
17
2013-10-16T17:33:40Z
19,410,071
26
2013-10-16T17:35:57Z
[ "python", "list" ]
How would I go about counting the words in a sentence? I'm using Python. For example, I might have the string: ``` string = "I am having a very nice 23!@$ day. " ``` That would be 7 words. I'm having trouble with the random amount of spaces after/before each word as well as when numbers or symbols are ...
[`str.split()`](http://docs.python.org/3/library/stdtypes.html#str.split) without any arguments splits on runs of whitespace characters: ``` >>> s = 'I am having a very nice day.' >>> >>> len(s.split()) 7 ``` From the linked documentation: > If *sep* is not specified or is `None`, a different splitting algorithm is...
How to count the number of words in a sentence?
19,410,018
17
2013-10-16T17:33:40Z
19,410,075
23
2013-10-16T17:36:11Z
[ "python", "list" ]
How would I go about counting the words in a sentence? I'm using Python. For example, I might have the string: ``` string = "I am having a very nice 23!@$ day. " ``` That would be 7 words. I'm having trouble with the random amount of spaces after/before each word as well as when numbers or symbols are ...
You can use [`regex.findall()`](http://docs.python.org/2/library/re.html#re.findall): ``` import re line = " I am having a very nice day." count = len(re.findall(r'\w+', line)) print (count) ```
How to make IPython notebook matplotlib plot inline
19,410,042
300
2013-10-16T17:34:42Z
24,444,083
17
2014-06-27T04:40:55Z
[ "python", "matplotlib", "ipython", "ipython-notebook" ]
I am trying to use IPython notebook on MacOS X with Python 2.7.2 and IPython 1.1.0. I cannot get matplotlib graphics to show up inline. ``` import matplotlib import numpy as np import matplotlib.pyplot as plt %matplotlib inline ``` I have also tried `%pylab inline` and the ipython command line arguments `--pylab=inl...
I'm not sure why joaquin posted his answer as a comment, but it is the correct answer: start ipython with `ipython notebook --pylab inline` Edit: Ok, this is now deprecated as per comment below. Use the %pylab magic.
How to make IPython notebook matplotlib plot inline
19,410,042
300
2013-10-16T17:34:42Z
24,884,342
419
2014-07-22T10:01:24Z
[ "python", "matplotlib", "ipython", "ipython-notebook" ]
I am trying to use IPython notebook on MacOS X with Python 2.7.2 and IPython 1.1.0. I cannot get matplotlib graphics to show up inline. ``` import matplotlib import numpy as np import matplotlib.pyplot as plt %matplotlib inline ``` I have also tried `%pylab inline` and the ipython command line arguments `--pylab=inl...
I used `%matplotlib inline` in the first cell of the notebook and it works. I think you should try: ``` %matplotlib inline import matplotlib import numpy as np import matplotlib.pyplot as plt ``` You can also always start all your IPython kernels in inline mode by default by setting the following config options in y...
How to make IPython notebook matplotlib plot inline
19,410,042
300
2013-10-16T17:34:42Z
25,351,828
8
2014-08-17T17:36:03Z
[ "python", "matplotlib", "ipython", "ipython-notebook" ]
I am trying to use IPython notebook on MacOS X with Python 2.7.2 and IPython 1.1.0. I cannot get matplotlib graphics to show up inline. ``` import matplotlib import numpy as np import matplotlib.pyplot as plt %matplotlib inline ``` I have also tried `%pylab inline` and the ipython command line arguments `--pylab=inl...
I have to agree with foobarbecue (I don't have enough recs to be able to simply insert a comment under his post): It's now recommended that python notebook isn't started wit the argument `--pylab`, and according to Fernando Perez (creator of ipythonnb) `%matplotlib inline` should be the initial notebook command. See ...
How to make IPython notebook matplotlib plot inline
19,410,042
300
2013-10-16T17:34:42Z
29,573,210
40
2015-04-11T02:01:06Z
[ "python", "matplotlib", "ipython", "ipython-notebook" ]
I am trying to use IPython notebook on MacOS X with Python 2.7.2 and IPython 1.1.0. I cannot get matplotlib graphics to show up inline. ``` import matplotlib import numpy as np import matplotlib.pyplot as plt %matplotlib inline ``` I have also tried `%pylab inline` and the ipython command line arguments `--pylab=inl...
Ctrl+Enter > %matplotlib inline Magic Line :D [Reference example](http://nbviewer.ipython.org/github/ipython/ipython/blob/1.x/examples/notebooks/Part%203%20-%20Plotting%20with%20Matplotlib.ipynb)
How to make IPython notebook matplotlib plot inline
19,410,042
300
2013-10-16T17:34:42Z
34,222,212
56
2015-12-11T11:13:17Z
[ "python", "matplotlib", "ipython", "ipython-notebook" ]
I am trying to use IPython notebook on MacOS X with Python 2.7.2 and IPython 1.1.0. I cannot get matplotlib graphics to show up inline. ``` import matplotlib import numpy as np import matplotlib.pyplot as plt %matplotlib inline ``` I have also tried `%pylab inline` and the ipython command line arguments `--pylab=inl...
If your matplotlib version is above 1.4, it is also possible to use IPython 3.x and above ``` %matplotlib notebook import matplotlib.pyplot as plt ``` older versions ``` %matplotlib nbagg import matplotlib.pyplot as plt ``` Both will activate the [nbagg backend](http://matplotlib.org/users/whats_new.html#the-nba...
Open a list of files using with/as context manager
19,412,376
14
2013-10-16T19:44:52Z
19,412,700
9
2013-10-16T20:02:37Z
[ "python", "with-statement", "contextmanager" ]
*Note:* I am aware of the ``` with open('f1') as f1, open('f2') as f2: ... ``` syntax. This is a different question. --- Given a list of strings `file_names` is there a way using `with`/`as` to open every file name in that using a single line. Something such as: ``` with [open(fn) for fn in file_names] as file...
If you have access to Python 3.3+, there is a special class designed exactly for this purpose: the [`ExitStack`](http://docs.python.org/3/library/contextlib.html#contextlib.ExitStack). It works just like you'd expect: ``` with contextlib.ExitStack() as stack: files = [stack.enter_context(open(fname)) for fname in ...
Getting distance between two points based on latitude/longitude [python]
19,412,462
14
2013-10-16T19:49:48Z
19,412,565
31
2013-10-16T19:55:11Z
[ "python", "geocoding", "geo", "geography" ]
I tried implementing this formula: <http://andrew.hedges.name/experiments/haversine/> The aplet does good for the two points I am testing: ![enter image description here](http://i.stack.imgur.com/FGED4.png) Yet my code is not working. ``` from math import sin, cos, sqrt, atan2 R = 6373.0 lat1 = 52.2296756 lon1 = 2...
It's because in Python, all the trig functions [use radians](http://docs.python.org/3/library/math.html#trigonometric-functions), not degrees. You can either convert the numbers manually to radians, or use the [`radians`](http://docs.python.org/3/library/math.html#math.radians) function from the math module: ``` from...
Plotting stochastic processes in Python
19,413,016
6
2013-10-16T20:17:35Z
19,413,521
8
2013-10-16T20:45:33Z
[ "python", "numpy", "matplotlib", "pandas", "scipy" ]
Say I have a stochastic process defined between `[0... N]`, e.g. `N=50`. For every location, I have several samples (e.g. `m=100` samples) (representing my sampling distribution at each location). One way to look at this is as a numpy 2D array of size `(m,N)`. How can I plot this intuitively in `matplotlib`? One poss...
For the first example, you can simply compute the percentiles at each fixed location, and then plot them using `plt.fill_between`. something like this ``` # Last-modified: 16 Oct 2013 05:08:28 PM import numpy as np import matplotlib.pyplot as plt # generating fake data locations = np.arange(0, 50, 1) medians = loc...
Efficient way to calculate distance matrix given latitude and longitude data in Python
19,413,259
7
2013-10-16T20:31:29Z
19,414,306
7
2013-10-16T21:32:20Z
[ "python", "numpy", "scipy", "distance" ]
I have data for latitude and longitude, and I need to calculate distance matrix between two arrays containing locations. I used this [This](http://stackoverflow.com/questions/120283/working-with-latitude-longitude-values-in-java/123305#123305) to get distance between two locations given latitude and longitude. Here is...
There's a lot of suboptimal things in the Haversine equations you are using. You can trim some of that and minimize the number of sines, cosines and square roots you need to calculate. The following is the best I have been able to come up with, and on my system runs about 5x faster than Ophion's code (which does mostly...
Timing difference on using timeit from interpreter and commandline
19,413,371
4
2013-10-16T20:36:56Z
19,413,429
8
2013-10-16T20:40:39Z
[ "python", "performance", "timeit" ]
From interpreter, I get: ``` >>> timeit.repeat("-".join( str(n) for n in range(10000) ) , repeat = 3, number=10000) [1.2294530868530273, 1.2298660278320312, 1.2300069332122803] # this is seconds ``` From commandline, I get: ``` $ python -m timeit -n 10000 '"-".join(str(n) for n in range(10000))' 10000 loops, best of...
The two lines aren't measuring the same thing. In the first snippet, you're timing the calculation `0-1-2-...-9999`. while in the second snippet you're timing the string concatenation `"-".join(str(n) for n in range(10000))`. In addition, `timeit` and `repeat` report the *total* time, while the CLI averages the time o...
Argparse: Required argument 'y' if 'x' is present
19,414,060
21
2013-10-16T21:16:45Z
19,414,853
25
2013-10-16T22:11:20Z
[ "python", "argparse" ]
I have a requirement as follows: ``` ./xyifier --prox --lport lport --rport rport ``` for the argument prox , I use action='store\_true' to check if it is present or not. I do not require any of the arguments. But, if --prox is set I *require* rport and lport as well. Is there an easy way of doing this with argparse ...
No, there isn't any option in argparse to make mutually *inclusive* sets of options. The simplest way to deal with this would be: ``` if args.prox and args.lport is None and args.rport is None: parser.error("--prox requires --lport and --rport.") ```
how to xor binary with python
19,414,093
3
2013-10-16T21:19:38Z
19,414,115
9
2013-10-16T21:20:50Z
[ "python", "binary", "xor" ]
I'm trying to xor 2 binaries using python like this but my output is not in binary any help? ``` a = "11011111101100110110011001011101000" b = "11001011101100111000011100001100001" y = int(a) ^ int(b) print y ```
``` a = "11011111101100110110011001011101000" b = "11001011101100111000011100001100001" y = int(a,2) ^ int(b,2) print '{0:b}'.format(y) ```
from scrapy.selector import selector error
19,415,089
2
2013-10-16T22:29:03Z
19,417,555
9
2013-10-17T03:07:04Z
[ "python", "osx", "web-scraping", "scrapy", "lxml" ]
I am unable to do the following: ``` from scrapy.selector import Selector ``` The error is: File "/Desktop/KSL/KSL/spiders/spider.py", line 1, in from scrapy.selector import Selector ImportError: cannot import name Selector It is as if LXML is not installed on my machine, but it is. Also, I thought this was a defau...
Try importing **HtmlXPathSelector** instead. ``` from scrapy.selector import HtmlXPathSelector ``` And then use the **.select()** method to parse out your html. For example, ``` sel = HtmlXPathSelector(response) site_names = sel.select('//ul/li') ``` If you are following the tutorial on the Scrapy site ...
Better "return if not None" in Python
19,415,614
19
2013-10-16T23:18:09Z
19,415,660
13
2013-10-16T23:22:12Z
[ "python", "syntax" ]
Is there a *better* way to write this code in python? ``` result = slow_function() if result: return result [...] ``` The function `slow_function` can return a value or `None` and it's slow, so this is not feasible: ``` if slow_function(): return slow_function() ``` There is nothing wrong with the first way...
Without knowing what else you might want to return there are a few options. 1. You could just return the result of the function, `None` or not: ``` return slow_function() ``` In this, you rely on the caller knowing what to do with the `None` value, and really just shift where your logic will be. 2. If yo...
Better "return if not None" in Python
19,415,614
19
2013-10-16T23:18:09Z
19,415,727
7
2013-10-16T23:27:47Z
[ "python", "syntax" ]
Is there a *better* way to write this code in python? ``` result = slow_function() if result: return result [...] ``` The function `slow_function` can return a value or `None` and it's slow, so this is not feasible: ``` if slow_function(): return slow_function() ``` There is nothing wrong with the first way...
Essentially you want to evaluate an expression and then use it twice without binding it to a local variable. The only way to do that, since we don't have anonymous variables, is to pass it into a function. Fortunately, the control flow for whether the current function returns isn't controlled by the functions it calls....
Better "return if not None" in Python
19,415,614
19
2013-10-16T23:18:09Z
19,416,193
7
2013-10-17T00:21:44Z
[ "python", "syntax" ]
Is there a *better* way to write this code in python? ``` result = slow_function() if result: return result [...] ``` The function `slow_function` can return a value or `None` and it's slow, so this is not feasible: ``` if slow_function(): return slow_function() ``` There is nothing wrong with the first way...
Your [latest comment](http://stackoverflow.com/questions/19415614/better-return-if-not-none-in-python/19416193#comment28782461_19415614) maybe makes it clearer what you want to do: > Imagine that you pass f a list and it select an item, then calls itself passing the list without the item and so on until you have no mo...
Python: Remove Duplicate Tuples from List if They are Exactly the Same Including Order Of Items
19,416,786
9
2013-10-17T01:30:02Z
19,416,806
15
2013-10-17T01:32:08Z
[ "python", "list", "duplicates", "tuples", "itertools" ]
I know questions similar to this have been asked many, many times on Stack Overflow, but I need to remove duplicate tuples from a list, but not just if their elements match up, their elements have to be in the same order. In other words, `(4,3,5)` and `(3,4,5)` would both be present in the output, while if there were b...
[`set`](http://docs.python.org/2.7/library/functions.html#func-set) will take care of that: ``` >>> a = [(1,2,2), (2,2,1), (1,2,2), (4,3,5), (3,3,5), (3,3,5), (3,4,5)] >>> set(a) set([(1, 2, 2), (2, 2, 1), (3, 4, 5), (3, 3, 5), (4, 3, 5)]) >>> list(set(a)) [(1, 2, 2), (2, 2, 1), (3, 4, 5), (3, 3, 5), (4, 3, 5)] >>> ``...
Get coordinates from the contour in matplotlib?
19,418,901
4
2013-10-17T05:28:31Z
19,419,899
9
2013-10-17T06:40:44Z
[ "python", "matplotlib" ]
# Background From [the documentation example here](http://matplotlib.org/examples/pylab_examples/contour_demo.html), one can easily produce the following contour plot with the code snippet. ``` import matplotlib import numpy as np import matplotlib.cm as cm import matplotlib.mlab as mlab import matplotlib.pyplot as p...
You can get the coordinates of the contours from the `CS.allsegs` list. Try: ``` dat0= CS.allsegs[0][0] plt.plot(dat0[:,0],dat0[:,1]) ``` to plot the first (-1) contour level.
How to cache requirements for a Django project on Travis-CI?
19,422,229
15
2013-10-17T08:58:13Z
19,460,794
18
2013-10-19T00:08:19Z
[ "python", "django", "travis-ci", "requirements.txt" ]
As Travis-CI is evolving and extending its feature set it naturally becomes nicer and nicer to use. I recently [read this article](http://about.travis-ci.org/docs/user/speeding-up-the-build/) about "Speeding up the build". A build for the Django project I am working on takes ~25-30 minutes. Almost half of this time is ...
**Update** This is now a first class feature of Travis: <http://blog.travis-ci.com/2013-12-05-speed-up-your-builds-cache-your-dependencies/> I've just been playing around with this, and it looks like you can cache the virtualenv site-packages like this (update the path to your python version): ``` cache: directorie...
Upload File using Django Rest Framework
19,422,803
5
2013-10-17T09:24:47Z
19,766,565
11
2013-11-04T11:14:24Z
[ "python", "django", "django-rest-framework", "serializer" ]
I am new to django. Can anybody help me... How can I upload a file using the Rest Framework API ? I have tried following this page: <http://www.django-rest-framework.org/api-guide/parsers/#fileuploadparser>
File uploading in Django REST framework is the same with uploading files in multipart/form in django. To test it you can use curl: ``` curl -X POST -H "Content-Type:multipart/form-data" -u {username}:{password} \ -F "{field_name}=@{filename};type=image/jpeg" http://{your api endpoint} ``` Other fields are just like ...
Python's decimal module doesn't like any number from 1 upwards
19,423,753
2
2013-10-17T10:06:49Z
19,423,997
8
2013-10-17T10:17:49Z
[ "python", "math" ]
Any idea why Python's `decimal` module doesn't like numbers 1 or more but 0.9 and less is okay? ``` >>> import decimal >>> max_digits = 5 >>> decimal_places = 5 >>> context = decimal.getcontext().copy() >>> context.prec = max_digits ``` 1 itself has too many digits: ``` >>> value = decimal.Decimal('1') >>> '%s' % st...
That's because you set the maximum precision `context.prec` to be 5 digits, while you also set the `decimal_places` into 5 places after the decimal point. Putting values 1 and above will give you 6 digits of precision (significant figures): ``` 1.00000 ^ ^^^^^ ``` which is the `1` plus 5 decimal places. That's why it...
lstrip gets rid of letter
19,425,813
2
2013-10-17T11:44:14Z
19,425,891
9
2013-10-17T11:47:46Z
[ "python", "string", "python-2.7" ]
With Python 2.7, I ran into the following problem: I have urls that I would like to clean, in particular I'd like to get rid of "http://". This works: ``` >>> url = 'http://www.party.com' >>> url.lstrip('http://') 'www.party.com' ``` But why does this not work? ``` >>> url = 'http://party.com' >>> url.lstrip('http:...
Think the argument of `lstrip` as characters, not a string. [`url.lstrip('http://')`](http://docs.python.org/2/library/stdtypes#str.lstrip) removes all leading `h`, `t`, `:`, `/` from `url`. Use [`str.replace`](http://docs.python.org/2/library/stdtypes#str.replace) instead: ``` >>> url = 'http://party.com' >>> url.r...
env: python\r: No such file or directory
19,425,857
14
2013-10-17T11:46:14Z
19,426,049
16
2013-10-17T11:55:02Z
[ "python", "osx", "osx-mountain-lion", "shebang", "env" ]
My Python script `beak` contains the following shebang: ``` #!/usr/bin/env python ``` When I run the script `$ ./beak`, I get ``` env: python\r: No such file or directory ``` I previously pulled this script from a repository. What could be the reason for this?
The script contains CR characters. The shell interprets these CR characters as arguments. Solution: Remove the CR characters from the script using the following script. ``` with open('beak', 'rb+') as f: content = f.read() f.seek(0) f.write(content.replace(b'\r', b'')) f.truncate() ```
env: python\r: No such file or directory
19,425,857
14
2013-10-17T11:46:14Z
22,496,306
7
2014-03-19T04:36:33Z
[ "python", "osx", "osx-mountain-lion", "shebang", "env" ]
My Python script `beak` contains the following shebang: ``` #!/usr/bin/env python ``` When I run the script `$ ./beak`, I get ``` env: python\r: No such file or directory ``` I previously pulled this script from a repository. What could be the reason for this?
You can convert the line ending into \*nix-friendly ones with ``` dos2unix beak ```
Creating a postgresql DB using psycopg2
19,426,448
15
2013-10-17T12:13:16Z
19,426,770
22
2013-10-17T12:28:16Z
[ "python", "postgresql", "psycopg2" ]
I'm trying to create a postgres DB using a python script. Some research showed that using the psycopg2 module might be a way to do it. I installed it and made the required changes in the `pg_hba.conf` file. I used the following code to create the DB: ``` #!/usr/bin/python # -*- coding: utf-8 -*- from psycopg2 import ...
PostgreSQL's client connects to a database named after the user by default. This is why you get the error FATAL: `database "nishant" does not exist`. You can connect to the default system database `postgres` and then issue your query to create the new database. ``` con = connect(dbname='postgres', user='nishant', hos...
Python: Where does if-endif-statement end?
19,430,190
7
2013-10-17T14:57:05Z
19,430,231
8
2013-10-17T14:58:47Z
[ "python", "vb.net", "vb6", "migration" ]
I have the following code: ``` for i in range(0,numClass): if breaks[i] == 0: classStart = 0 else: classStart = dataList.index(breaks[i]) classStart += 1 classEnd = dataList.index(breaks[i+1]) classList = dataList[classStart:classEnd+1] classMean = sum(classList)/len(classList) print ...
Yes. Python uses indentation to mark blocks. Both the `if` and the `for` end there.
How can I tell if Python setuptools is installed?
19,430,346
7
2013-10-17T15:03:11Z
19,430,450
7
2013-10-17T15:07:50Z
[ "python", "pip", "setuptools" ]
I'm writing a quick shell script to make it easier for some of our developers to run Fabric. (I'm also new to Python.) Part of installing Fabric is installing pip, and part of installing pip is installing setuptools. Is there any easy way to detect if setuptools is already installed? I'd like to make it possible to ru...
This isn't great but it'll work. A simple python script can do the check ``` import sys try: import setuptools except ImportError: sys.exit(1) else: sys.exit(0) ``` Then just check it's exit code in the calling script
Randomly use a Comparison operator?
19,430,641
8
2013-10-17T15:16:06Z
19,430,709
12
2013-10-17T15:18:39Z
[ "python", "python-2.7", "operators" ]
I have an array with a list of comparison operators. How can I randomly select one to use? I tried the following but failed. ``` from random import choice logi = ["<",">","=="] n=20 n2 = choice(range(1,100)) if n choice(logi) n2: print n2 ```
Take a look at [`operator`](http://docs.python.org/2/library/operator.html): ``` import operator logi = [operator.lt, operator.gt, operator.eq] ... if choice(logi)(n, n2): print n2 ```
How to use 'User' as foreign key in Django 1.5
19,433,630
24
2013-10-17T17:44:25Z
19,433,703
31
2013-10-17T17:48:12Z
[ "python", "django", "django-users" ]
I have made a custom profile model which looks like this: ``` from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user = models.ForeignKey('User', unique=True) name = models.CharField(max_length=30) occupation = models.CharField(max_length=50) city...
Change this: ``` user = models.ForeignKey('User', unique=True) ``` to this: ``` user = models.ForeignKey(User, unique=True) ```
How to use 'User' as foreign key in Django 1.5
19,433,630
24
2013-10-17T17:44:25Z
25,933,073
32
2014-09-19T11:37:38Z
[ "python", "django", "django-users" ]
I have made a custom profile model which looks like this: ``` from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user = models.ForeignKey('User', unique=True) name = models.CharField(max_length=30) occupation = models.CharField(max_length=50) city...
Exactly in Django 1.5 the `AUTH_USER_MODEL` setting [was introduced](https://docs.djangoproject.com/en/dev/releases/1.5/#configurable-user-model), allowing using a custom user model with auth system. If you're writing an app that's intended to work with projects on Django 1.5+, this is the proper way to reference user...
Selecting a random list element of length n in Python
19,436,153
3
2013-10-17T20:02:46Z
19,436,179
18
2013-10-17T20:03:57Z
[ "python", "random" ]
I know you can use random.choice to choose a random element from a list, but I am trying to choose random elements of length 3. For example, ``` list1=[a,b,c,d,e,f,g,h] ``` I want the output to look something like: ``` [c,d,e] ``` Essentially I want to generate random sub-lists from the list.
You want a *sample*; use [`random.sample()`](http://docs.python.org/2/library/random.html#random.sample) to pick a list of 3 elements: ``` random.sample(list1, 3) ``` Demo: ``` >>> import random >>> list1 = ['a', 'b', 'c' ,'d' ,'e' ,'f', 'g', 'h'] >>> random.sample(list1, 3) ['e', 'b', 'a'] ``` If you needed a subl...
How to make json-schema to allow one but not another field?
19,436,589
5
2013-10-17T20:26:36Z
19,438,930
9
2013-10-17T23:17:21Z
[ "python", "json", "jsonschema" ]
Is it possible to make `jsonschema` to have only one of two fields. For example, image if I want to have a `JSON` with ether `start_dt` or `end_dt` but not both of them at the same time. like this: ### OK ``` { "name": "foo", "start_dt": "2012-10-10" } ``` ### OK ``` { "name": "foo", "end_dt": "201...
You can express this using `oneOf`. This means that the data must match *exactly one* of the supplied sub-schemas, but not more than one. Combining this with `required`, this schema says that instances must either define `start_dt`, OR define `end_dt` - but if they contain both, then it is invalid: ``` { "type": ...
When scattering Flask Models, RuntimeError: 'application not registered on db' was raised
19,437,883
34
2013-10-17T21:44:39Z
19,438,054
74
2013-10-17T21:58:32Z
[ "python", "flask" ]
I am re-factoring my Flask application by scattering the models, blueprints but I am having a runtime error. ``` def create_app(): app = flask.Flask("app") app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' app.register_blueprint(api) db.init_app(app) db.create_all() return app ``` I have the...
This has to do with Flask's [application context](http://flask.pocoo.org/docs/appcontext/). When initialized with `db.init_app(app)`, Flask-SQLAlchemy doesn't know which app is the "current" app (remember, Flask allows for [multiple apps](http://flask.pocoo.org/docs/patterns/appdispatch/) in the same interpreter). You ...
Recursion Quiz - Couldn't Solve
19,439,763
11
2013-10-18T00:47:32Z
19,439,941
14
2013-10-18T01:09:21Z
[ "python", "recursion" ]
Today my CPSC professor assigned a quiz in python, the topic was recursion. The whole class got stuck on question number two, which is below. Nobody was able to even come close to a solution. ``` def sub_set(A): if A == []: return A X = sub_set(A[1:]) result = [] for L in X: result += _____ ...
I think there's a bug in the question. The base case for the recursion is wrong. The set of all subsets of an empty set is not the empty set, but rather, the set containing the empty set. ``` def sub_set(A): if A == []: return A ``` should be ``` def sub_set(A): if A == []: return [A] ``` **Added:** With t...
Is there a way to construct an object using PyYAML construct_mapping after all nodes complete loading?
19,439,765
11
2013-10-18T00:47:58Z
19,442,848
16
2013-10-18T06:17:27Z
[ "python", "yaml", "pyyaml" ]
I am trying to make a yaml sequence in python that creates a custom python object. The object needs to be constructed with dicts and lists that are deconstructed after `__init__`. However, it seems that the construct\_mapping function does not construct the entire tree of embedded sequences (lists) and dicts. Conside...
Well, what do you know. The solution I found was so simple, yet not so well documented. The [Loader class documentation](http://pyyaml.org/wiki/PyYAMLDocumentation#Loader) clearly shows the `construct_mapping` method only takes in a single parameter (`node`). However, after considering writing my own constructor, I ch...
Python Requests: Post JSON and file in single request
19,439,961
12
2013-10-18T01:11:32Z
20,210,802
9
2013-11-26T07:20:19Z
[ "python", "json", "urllib2" ]
I need to do a API call to upload a file along with a JSON string with details about the file. I am trying to use the python requests lib to do this: ``` import requests info = { 'var1' : 'this', 'var2' : 'that', } data = json.dumps({ 'token' : auth_token, 'info' : info, }) headers = {'Content-ty...
Don't encode using json. ``` import requests info = { 'var1' : 'this', 'var2' : 'that', } data = { 'token' : auth_token, 'info' : info, } headers = {'Content-type': 'multipart/form-data'} files = {'document': open('file_name.pdf', 'rb')} r = requests.post(url, files=files, data=data, headers=hea...
How do I check if raw input is integer in python 2.7?
19,440,952
11
2013-10-18T03:07:59Z
19,440,958
14
2013-10-18T03:09:14Z
[ "python", "string", "python-2.7", "integer", "raw-input" ]
Is there a method that I can use to check if a `raw_input` is an integer? I found this method after researching in the web: ``` print isinstance(raw_input("number: ")), int) ``` but when I run it and input `4` for example, I get `FALSE`. I'm kind of new to python, any help would be appreciated.
`isinstance(raw_input("number: ")), int)` always yields `False` because `raw_input` return string object as a result. Use `try: int(...) ... except ValueError`: ``` number = raw_input("number: ") try: int(number) except ValueError: print False else: print True ``` or use [`str.isdigit`](http://docs.pytho...
Search python docs offline?
19,441,031
15
2013-10-18T03:20:37Z
27,135,024
9
2014-11-25T19:26:29Z
[ "python", "documentation", "offline" ]
In python I can get some rudimentary documentation for any object using `help(<object>)`. But to be able to *search* the documentation, I have to go online. This isn't really helpful if I'm somewhere where the internet isn't accessible. In R, there is a handy double question mark feature (`??<topic>`) that allows me t...
Look in the python folder in the folder: `Doc`. This folder has the entire downloaded documentation of the python docs from [python.org](http://python.org). I know this is a VERY late answer, but it brings up an easy solution.
Trimmed Mean with Percentage Limit in Python?
19,441,730
16
2013-10-18T04:42:50Z
25,473,378
12
2014-08-24T15:40:20Z
[ "python" ]
I am trying to calculate the **trimmed mean**, which excludes the outliers, of an array. I found there is a module called [`scipy.stats.tmean`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.tmean.html#scipy.stats.tmean), but it requires the user specifies the **range by absolute value instead of perc...
At least for scipy v0.14.0, there is a dedicated (but undocumented?) function for this: ``` from scipy import stats m = stats.trim_mean(X, 0.1) # Trim 10% at both ends ``` which used [`stats.trimboth`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.trimboth.html) inside.
Matplotlib pyplot.title(string) returns error
19,442,060
6
2013-10-18T05:13:20Z
29,297,334
8
2015-03-27T09:32:33Z
[ "python", "matplotlib" ]
When I call pyplot,title('some string') it throws an excption ''str' object is not callable'. I copied the following from the matplotib online documentation: ``` mu, sigma = 100, 15 x = mu + sigma * np.random.randn(10000) # the histogram of the data n, bins, patches = plt.hist(x, 50, normed=1, facecolor='g', alpha=0....
I had the same problem. The code was fine, but in the interpreter, I had previoulsy used incorrect xlabel() calls. re-starting the interpreter (close and reopen it) was enough for me, no need to reinstall all python/matplotlib !
unbound method must be called with instance as first argument (got nothing instead)
19,442,466
2
2013-10-18T05:48:55Z
19,442,532
9
2013-10-18T05:53:16Z
[ "python", "class", "inheritance" ]
Im trying to move all classes from one Inheritance. I wrote this tiny script: ``` class c1: def move(): x+=1 y+=1 class c2(c1): y=1 x=2 c=c2 c.move() print(str(c.x)+" , "+str(c.y)) ``` when i run it i get: ``` Traceback (most recent call last): File "/home/tor/Workspace/try.py", line 9,...
1. You do not instantiate anything 2. All methods must take at least one parameter, traditionally called `self`. 3. You need `self` to access object fields. Your code right now modifies local variables which do not exist in that scope.
Weak reference to Python class method
19,443,440
10
2013-10-18T06:57:34Z
19,443,624
8
2013-10-18T07:07:14Z
[ "python", "python-2.7", "python-3.x" ]
Python 2.7 docs for weakref module say this: > Not all objects can be weakly referenced; those objects which can > include class instances, functions written in Python (but not in C), > methods (both bound and unbound), ... And Python 3.3 docs for weakref module say this: > Not all objects can be weakly referenced; ...
`Foo.bar` produces a new unbound method object every time you access it, due to some gory details about descriptors and how methods happen to be implemented in Python. The class doesn't own unbound methods; it owns functions. (Check out `Foo.__dict__['bar']`.) Those functions just happen to have a `__get__` which retu...
How to kill a python child process created with subprocess.check_output() when the parent dies?
19,447,603
13
2013-10-18T10:39:26Z
19,448,096
13
2013-10-18T11:03:08Z
[ "python", "linux", "subprocess" ]
I am running on a linux machine a python script which creates a child process using subprocess.check\_output() as it follows: ``` subprocess.check_output(["ls", "-l"], stderr=subprocess.STDOUT) ``` The problem is that even if the parent process dies, the child is still running. Is there any way I can kill the child p...
Yes, you can achieve this by two methods. Both of them require you to use `Popen` instead of `check_output`. The first is a simpler method, using try..finally, as follows: ``` from contextlib import contextmanager @contextmanager def run_and_terminate_process(*args, **kwargs): try: p = subprocess.Popen(*args, **k...
How to kill a python child process created with subprocess.check_output() when the parent dies?
19,447,603
13
2013-10-18T10:39:26Z
19,448,255
9
2013-10-18T11:10:42Z
[ "python", "linux", "subprocess" ]
I am running on a linux machine a python script which creates a child process using subprocess.check\_output() as it follows: ``` subprocess.check_output(["ls", "-l"], stderr=subprocess.STDOUT) ``` The problem is that even if the parent process dies, the child is still running. Is there any way I can kill the child p...
Your problem is with using `subprocess.check_output` - you are correct, you can't get the child PID using that interface. Use Popen instead: ``` proc = subprocess.Popen(["ls", "-l"], stdout=PIPE, stderr=PIPE) # Here you can get the PID global child_pid child_pid = proc.pid # Now we can wait for the child to complete...
Matplotlib scatter marker size
19,451,400
5
2013-10-18T13:51:50Z
19,451,456
8
2013-10-18T13:54:52Z
[ "python", "matplotlib", "size", "scatter-plot" ]
I'm trying to plot a 3D scatter with `matplotlib` The problem is that I can't change the marker's size I have this ``` scat = plt.scatter([boid_.pos[0] for boid_ in flock], [boid_.pos[1] for boid_ in flock], [boid_.pos[2] for boid_ in flock], marker='o', s=5) ``` But I get the error ``` TypeError: sca...
This function takes in two args before the keyword args: `scatter(x, y, s=20, ...)` And you are passing in three, so you are specifying `s` twice (once implicitly and once explicitly). Actually, I think you are trying to use the 2D scatter plot function instead of a 3D one. You probably want to do this instead: ```...
Is there a Python dict without values?
19,454,970
4
2013-10-18T16:51:22Z
19,454,984
13
2013-10-18T16:51:57Z
[ "python", "dictionary" ]
Instead of this: ``` a = {"foo": None, "bar": None} ``` Is there a way to write this? ``` b = {"foo", "bar"} ``` And still let `b` have constant time access (i.e. not a Python set, which cannot be keyed into)?
Yes, `sets`: ``` set() -> new empty set object set(iterable) -> new set object Build an unordered collection of unique elements. ``` Related: [How is CPython's set() implemented?](http://stackoverflow.com/questions/3949310/how-is-cpythons-set-implemented) Time complexity : <https://wiki.python.org/moin/TimeComplexi...
Is there a Python dict without values?
19,454,970
4
2013-10-18T16:51:22Z
19,455,038
14
2013-10-18T16:54:25Z
[ "python", "dictionary" ]
Instead of this: ``` a = {"foo": None, "bar": None} ``` Is there a way to write this? ``` b = {"foo", "bar"} ``` And still let `b` have constant time access (i.e. not a Python set, which cannot be keyed into)?
Actually, in Python 2.7 and 3.2+, this really does work: ``` >>> b = {"foo", "bar"} >>> b set(['foo', 'bar']) ``` You can't use `[]` access on a set ("key into"), but you can test for inclusion: ``` >>> 'x' in b False >>> 'foo' in b True ``` Sets are as close to value-less dictionaries as it gets. They have average...
Convert python list with None values to numpy array with nan values
19,456,239
13
2013-10-18T18:03:40Z
19,456,347
17
2013-10-18T18:10:38Z
[ "python", "numpy" ]
I am trying to convert a list that contains numeric values and `None` values to `numpy.array`, such that `None` is replaces with `numpy.nan`. For example: ``` my_list = [3,5,6,None,6,None] # My desired result: my_array = numpy.array([3,5,6,np.nan,6,np.nan]) ``` Naive approach fails: ``` >>> my_list [3, 5, 6, None...
You simply have to explicitly declare the data type: ``` >>> my_list = [3, 5, 6, None, 6, None] >>> np.array(my_list, dtype=np.float) array([ 3., 5., 6., nan, 6., nan]) ```
Memory error allocating list of 11,464,882 empty dicts
19,456,559
6
2013-10-18T18:23:55Z
19,456,746
10
2013-10-18T18:34:37Z
[ "python", "list", "memory", "python-2.7", "dictionary" ]
I'm using portable python 2.7.5.1. The following line: ``` x = [{} for i in range(11464882)] ``` Causes a memory error (with no other messages): ``` >>> Traceback (most recent call last): File "<module1>", line 12, in <module> MemoryError >>> ``` Note: there are only comments in lines 1-11. Decreasing one unit...
On my Mac OS X 10.8.5 64-bit laptop, a `range(11464882)` object requires: ``` >>> import sys >>> sys.getsizeof(range(11464882)) 91719128 >>> sys.getsizeof(11464881) # largest number 24 >>> sys.getsizeof(0) # smalest number 24 >>> 91719128 + (24 * 11464882) # bytes 366876296 >>> (91719128 + (24 * 11464882)) /...
How to print like printf in python3?
19,457,227
44
2013-10-18T19:03:03Z
19,457,247
68
2013-10-18T19:04:19Z
[ "python", "string", "python-3.x" ]
In python 2 i used ``` print "a=%d,b=%d" % (f(x,n),g(x,n)) ``` Ive tried ``` print("a=%d,b=%d") % (f(x,n),g(x,n)) ```
In Python2, `print` was a keyword which introduced a statement: ``` print "Hi" ``` In Python3, `print` is a function which may be invoked: ``` print ("Hi") ``` In both versions, `%` is an operator which requires a string on the left-hand side and a value or a tuple of values or a mapping object (like `dict`) on the...
How to print like printf in python3?
19,457,227
44
2013-10-18T19:03:03Z
19,457,279
23
2013-10-18T19:06:12Z
[ "python", "string", "python-3.x" ]
In python 2 i used ``` print "a=%d,b=%d" % (f(x,n),g(x,n)) ``` Ive tried ``` print("a=%d,b=%d") % (f(x,n),g(x,n)) ```
The most recommended way to do is to use `format` method. Read more about it [here](http://docs.python.org/2/library/string.html#format-string-syntax) ``` a, b = 1, 2 print("a={0},b={1}".format(a, b)) ```
Xpath to select only direct siblings with matching attributes
19,457,502
8
2013-10-18T19:20:42Z
19,458,548
8
2013-10-18T20:31:31Z
[ "python", "xpath" ]
I have the following example document: ``` <root> <p class="b">A</p> <p class="b">B</p> <p class="a">C</p> <p class="a">D</p> <p class="b">E</p> <x> <p class="b">F</p> </x> </root> ``` I am looking for an xpath expression which selects all *direct* siblings of a given node with matching class attrib...
To get the very next sibling, you can add the position - 1 meaning right beside. ``` following-sibling::*[1] ``` To ensure that the next sibling is of a specific node type, you can add the following filter, where p is the node type we want to match. ``` [self::p] ``` If you only want ones with the same attribute, y...
Efficient Vector / Point class in Python
19,458,291
7
2013-10-18T20:13:58Z
19,458,332
14
2013-10-18T20:16:40Z
[ "python", "performance", "python-3.x", "vector" ]
What is the best way of implementing an efficient Vector / Point class (or even better: is there one already), that can be used both in Python 2.7+ and 3.x? I've found [the blender-mathutils](http://code.google.com/p/blender-mathutils/), but they seem to only support Python 3.x. Then there's [this Vector class](http:/...
Yeah, there is a vector class: it's in the *de facto* standard [NumPy](http://docs.scipy.org/doc/numpy/user/index.html) module. You create vectors like so: ``` >>> v = numpy.array([1, 10, 123]) >>> 2*v array([ 2, 20, 246]) >>> u = numpy.array([1, 1, 1]) >>> v-u array([ 0, 9, 122]) ``` NumPy is very rich and give...
Numpy equivalent of if/else list comprehension
19,458,856
5
2013-10-18T20:52:31Z
19,458,919
8
2013-10-18T20:56:53Z
[ "python", "numpy" ]
Is there a numpy way of doing ``` n = [x-t if x > 0 else x for x in nps] ``` similar to this ``` n = np.array(a) n[np.abs(n) < t] = 0 ``` something like this perhaps? ``` n[n > 0] = n-t ```
Can't test now, but try ``` np.where(n > 0, n - t, n) ``` See [documentation](http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html)
How to convert a Numpy 2D array with object dtype to a regular 2D array of floats
19,459,017
9
2013-10-18T21:04:00Z
19,459,439
7
2013-10-18T21:38:12Z
[ "python", "arrays", "object", "numpy", "2d" ]
As part of broader program I am working on, I ended up with object arrays with strings, 3D coordinates and etc all mixed. I know object arrays might not be very favorite in comparison to structured arrays but I am hoping to get around this without changing a lot of codes. Lets assume every row of my array obj\_array (...
Nasty little problem... I have been fooling around with this toy example: ``` >>> arr = np.array([['one', [1, 2, 3]],['two', [4, 5, 6]]], dtype=np.object) >>> arr array([['one', [1, 2, 3]], ['two', [4, 5, 6]]], dtype=object) ``` My first guess was: ``` >>> np.array(arr[:, 1]) array([[1, 2, 3], [4, 5, 6]], dty...
Query whether Python's threading.Lock is locked or not
19,460,808
3
2013-10-19T00:10:45Z
19,460,875
11
2013-10-19T00:19:49Z
[ "python", "multithreading", "thread-safety", "locking" ]
I have a thread I am running (code below) which launches a blocking subprocess. To ensure that other threads do not launch the same subprocess, I have a lock around this `subprocess.call` call. I also want to be able to terminate this subprocess call, so I have a stop function which I call from somewhere else. In the e...
Sure! ``` >>> from threading import Lock >>> x = Lock() >>> x.locked() False >>> x.acquire() True >>> x.locked() True ``` You could also do a non-blocking acquire: ``` x.acquire(False) x.release() ``` In that case, if `x` was unlocked the code acquires it, and releases it. But if x was already lock, the non-blockin...
How many methods are there to add an element to a list and which is the fastest?
19,461,275
3
2013-10-19T01:20:55Z
19,461,305
12
2013-10-19T01:25:10Z
[ "python", "list" ]
When I take a job interview I got a question about Python: how many methods are there to add an element to a list and which one of them is the fastest? I know I can use list's methods such as `append`, `insert`, and of course `+`. So, is there any others? And which one is the fastest, why?
Let's find out! This is using ipython's `%%timeit` magic function. ``` In [5]: %%timeit x = [] ...: x = x + [1] ...: 10000 loops, best of 3: 21.5 us per loop In [6]: %%timeit x = [] x.append(1) ...: 1000000 loops, best of 3: 93.7 ns per loop In [7]: %%timeit x = [] x.insert(0, 1) ...: 100000 loops, best ...
Sum corresponding elements of multiple python dictionaries
19,461,747
2
2013-10-19T02:36:49Z
19,461,818
9
2013-10-19T02:48:13Z
[ "python", "dictionary", "zip", "list-comprehension" ]
I have an arbitrary number of equal-length python dictionaries with matching sets of keys, like this: ``` {'a':1, 'b':4, 'c':8, 'd':9} {'a':2, 'b':3, 'c':2, 'd':7} {'a':0, 'b':1, 'c':3, 'd':4} ... ``` How can I obtain a single dictionary with the same set of keys but with values as the sums of corresponding element...
`collections.Counter()` to the rescue ;-) ``` from collections import Counter dicts = [{'a':1, 'b':4, 'c':8, 'd':9}, {'a':2, 'b':3, 'c':2, 'd':7}, {'a':0, 'b':1, 'c':3, 'd':4}] c = Counter() for d in dicts: c.update(d) ``` Then: ``` >>> print c Counter({'d': 20, 'c': 13, 'b': 8, 'a': 3}) ``` O...
Pandas: Drop consecutive duplicates
19,463,985
14
2013-10-19T08:19:56Z
19,464,054
24
2013-10-19T08:27:32Z
[ "python", "pandas" ]
What's the most efficient way to drop only consecutive duplicates in pandas? drop\_duplicates gives this: ``` In [3]: a = pandas.Series([1,2,2,3,2], index=[1,2,3,4,5]) In [4]: a.drop_duplicates() Out[4]: 1 1 2 2 4 3 dtype: int64 ``` But I want this: ``` In [4]: a.something() Out[4]: 1 1 2 2 4 3...
Use [shift](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.shift.html): ``` a.loc[a.shift(-1) != a] Out[3]: 1 1 3 2 4 3 5 2 dtype: int64 ``` So the above uses boolean critieria, we compare the dataframe against the dataframe shifted by -1 rows to create the mask Another method is t...
Explain Tkinter text search method
19,464,813
6
2013-10-19T10:07:12Z
19,466,754
7
2013-10-19T13:49:55Z
[ "python", "search", "tkinter" ]
I don't quite understand how text.search method works. For example there is a sentence: `Today a red car appeared in the park.` I need to find `a red car` sequence and highlight it. It is found but here is how my highlighting looks like: ![enter image description here](http://i.stack.imgur.com/bHAag.png) ![enter imag...
The search method returns the index of the first match at or after the starting index, and optionally the number of characters that matched. You are responsible for highlighting what it found by using this information. For example, consider this search: ``` countVar = tk.StringVar() pos = text.search("1.0", "a red ca...
"ImportError: cannot import name mail" in Flask
19,466,045
5
2013-10-19T12:31:33Z
19,467,445
11
2013-10-19T15:02:09Z
[ "python", "flask" ]
I have built is a simple web app with Flask and Python, which I intend to upload to Heroku. When starting my app locally, with the following script: ``` #!venv/bin/python from app import app app.run(debug = True) ``` I get this error message: ``` Traceback (most recent call last): File "./run.py", line 2, in <modul...
You have a circular dependency. You have to realize what Python is doing when it imports a file. Whenever Python imports a file, Python looks to see if the file has already started being imported before. Thus, if module A imports module B which imports module A, then Python will do the following: * Start running modu...
Python How to override a class member in the child and access it from parent?
19,467,099
4
2013-10-19T14:24:11Z
19,467,124
7
2013-10-19T14:27:45Z
[ "python", "class", "inheritance" ]
So in Python I have one class like this: ``` class Parent(object): ID = None @staticmethod def getId(): return Parent.ID ``` Then I override the ID in a child class, like this: ``` class Child(Parent): ID = "Child Class" ``` Now I want to call the `getId()` method of the child: ``` ch = Ch...
Use a class method: ``` class Parent(object): ID = None @classmethod def getId(cls): return cls.ID class Child(Parent): ID = "Child Class" print Child.getId() # "Child Class" ```
Add user specific fields to Django REST Framework serializer
19,468,478
12
2013-10-19T16:47:00Z
19,491,560
7
2013-10-21T10:05:57Z
[ "python", "django", "django-rest-framework" ]
I want to add a field to a serializer that contains information specific to the user making the current request (I don't want to create a separate endpoint for this). Here is the way I did it: **The viewset:** ``` class ArticleViewSet(viewsets.ModelViewSet): queryset = Article.objects.all() serializer_class =...
I'd be inclined to try and put as much of this as possible on the `Like` model object and then bung the rest in a custom serializer field. In serializer fields you can access the `request` via the `context` parameter that they *inherit* from their parent serializer. So you might do something like this: ``` class Lik...