title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
python: a quick way to return list without a specific element
15,738,700
9
2013-04-01T06:29:25Z
26,875,847
10
2014-11-11T22:32:04Z
[ "python" ]
If I have a list of card suits in arbitrary order like so: ``` suits = ["h", "c", "d", "s"] ``` and I want to return a list without the `'c'` ``` noclubs = ["h", "d", "s"] ``` is there a simple way to do this?
This question has been answered but I wanted to address the comment that using list comprehension is much slower than using `.remove()`. Some profiles from my machine (using Python 2.7.6). ``` %%timeit x = ['a', 'b', 'c', 'd'] y = x[:] # fastest way to copy y.remove('c') 1000000 loops, best of 3: 405 ns per loop %...
does xlwt support xlsx Format
15,738,904
10
2013-04-01T06:46:45Z
15,739,319
9
2013-04-01T07:21:11Z
[ "python", "xlwt" ]
I have searched into google and found some contradiction. Does xlwt support xlsx file (MS office 2007). I heard that xlwt 0.7.4 support xlsx file. Does anyone tried xlsx file writing operation with xlwt 0.7.4 The purpose of this question is,I do not have permission to install library if I need to install I need to pro...
openpyxl is guaranteed to write xlsx files. From a cursory read through some of the xlwt code and docs/examples, I don't think xlwt supports xlsx. If openpyxl does what you need it to do, why look elsewhere? Edit: with xlwt version 0.7.4 I attempted to save a file as `sample.xlsx`. Upon attempting to open it I got a `...
does xlwt support xlsx Format
15,738,904
10
2013-04-01T06:46:45Z
15,740,504
9
2013-04-01T09:03:00Z
[ "python", "xlwt" ]
I have searched into google and found some contradiction. Does xlwt support xlsx file (MS office 2007). I heard that xlwt 0.7.4 support xlsx file. Does anyone tried xlsx file writing operation with xlwt 0.7.4 The purpose of this question is,I do not have permission to install library if I need to install I need to pro...
The xlwt module doesn't support the xlsx format. The xlsx file format is completely different from the xls format supported by xlwt. As an alternative have a look at [XlsxWriter](https://pypi.python.org/pypi/XlsxWriter) which is a Python module for creating xlsx files. It supports a lot of Excel features. Have a look...
Python : UnicodeEncodeError when I use grep
15,739,029
8
2013-04-01T06:56:38Z
15,740,847
16
2013-04-01T09:27:07Z
[ "python", "grep", "python-requests" ]
I am using a simple python script to get reservation results for my CID : **`simple.py`**: ``` data = {"minorRev":"current minorRev #","cid":"xxx","apiKey":"xxx","customerIpAddress":" ","creationDateStart":"03/31/2013","} url = 'http://someservice/services/rs/' req = requests.get(url,params=dat...
`print` **needs** to encode the string before sending to stdout but when the process is in a pipe, the value of `sys.stdout.encoding` is `None`, so `print` receives an `unicode` object and then it tries to encode this object using the `ascii` codec -- if you have non-ASCII characters in this `unicode` object, an except...
Stdout encoding in python
15,740,236
12
2013-04-01T08:41:13Z
15,740,694
7
2013-04-01T09:15:05Z
[ "python", "unicode", "character-encoding" ]
Is there a good reason why I shouldn't start **all** my python programs with this? Is there something special lost when doing exec like this? ``` #!/usr/bin/python import os, sys if sys.stdout.encoding == None: os.putenv("PYTHONIOENCODING",'UTF-8') os.execv(sys.executable,['python']+sys.argv) print sys.stdout....
Yes, there is a good reason not to start all your Python programs like that. First of all: `sys.stdout.encoding` is None if Python doesn't know what encoding the stdout supports. This, in most cases, is because it doesn't really support any encoding at all. In your case it's because the stdout is a file, and not a te...
python - How to remove punctuation in between words
15,740,579
3
2013-04-01T09:08:11Z
15,740,656
9
2013-04-01T09:12:27Z
[ "python" ]
I use the code to strip a line of text from punctuation: ``` line = line.rstrip("\n") line = line.translate(None, string.punctuation) ``` The problem is that words like `doesn't` turn to `doesnt` so now I want to remove the punctuation only between words but can't seem to figure out a way to do so. How should I go ab...
Assuming you consider words as groups of characters separated by spaces: ``` >>> from string import punctuation >>> line = "Isn't ., stackoverflow the - best ?" >>> ' '.join(word.strip(punctuation) for word in line.split() if word.strip(punctuation)) "Isn't stackoverflow the best" ``` or ``` >>> line =...
Wrapping long y labels in matplotlib tight layout using setp
15,740,682
11
2013-04-01T09:14:13Z
15,740,730
15
2013-04-01T09:18:18Z
[ "python", "matplotlib" ]
I've been trying to wrap text for long labels in my code. I tried the textwrap method suggested earlier [here](http://stackoverflow.com/questions/10351565/how-do-i-fit-long-title), but my code defines yticklabels through an array imported from a csv using the `pyplot.setp()` method. I'm using `tight_layout()` for the f...
I have tried using `textwrap` on the labels and it works for me. ``` from textwrap import wrap labels=['Really really really really really really long label 1', 'Really really really really really really long label 2', 'Really really really really really really long label 3'] labels = [ '\n'.join(wrap(...
Stuck at Flask tutorial step 3
15,740,964
11
2013-04-01T09:34:15Z
15,744,674
8
2013-04-01T13:45:26Z
[ "python", "sqlite", "python-2.7", "flask" ]
Following Flask tutorial, running Win 7, Python 2.7.3, virtualenv, and I am stuck in Step 3: Creating The Database <http://flask.pocoo.org/docs/tutorial/dbinit/#tutorial-dbinit> > Such a schema can be created by piping the schema.sql file into the sqlite3 command as follows: > > ``` > sqlite3 /tmp/flaskr.db < schema.s...
You are confused between Windows and UNIX filesystems. Find out where `sqllite.exe` file exists on the computer. lets say it is in `C:\sqllite`. Then you also need to determine where you will create the database file. `/tmp/flaskr.db` is for the UNIX filesystem. On windows, you should provide the exact path or in your...
Removing duplicate rows from a csv file using a python script
15,741,564
9
2013-04-01T10:16:20Z
15,741,627
21
2013-04-01T10:20:59Z
[ "python", "file-io" ]
**Goal** I have downloaded a CSV file from hotmail, but it has a lot of duplicates in it. These duplicates are complete copies and I don't know why my phone created them. I want to get rid of the duplicates. **Approach** Write a python script to remove duplicates. **Technical specification** ``` Windows XP SP 3 P...
**UPDATE: 2016** If you are happy to use the helpful [`more_itertools`](https://pythonhosted.org/more-itertools/api.html#more_itertools.unique_everseen) external library: ``` from more_itertools import unique_everseen with open('1.csv','r') as f, open('2.csv','w') as out_file: out_file.writelines(unique_everseen(...
Add one year in current date PYTHON
15,741,618
19
2013-04-01T10:19:56Z
15,742,722
15
2013-04-01T11:37:17Z
[ "python", "date" ]
I have fetched a **date** from **database** with the following **variable** ``` {{ i.operation_date }} ``` with which I got a value like ``` April 1, 2013 ``` I need to add one year to the above, so that I can get ``` April 1, 2014 ``` Please suggest, how can I do this?
You can use [Python-dateutil's](http://labix.org/python-dateutil) `relativedelta` to increment a `datetime` object while remaining sensitive to things like leap years and month lengths. Python-dateutil comes packaged with matplotlib if you already have that. You can do the following: ``` from dateutil.relativedelta im...
Add one year in current date PYTHON
15,741,618
19
2013-04-01T10:19:56Z
15,743,908
41
2013-04-01T12:56:06Z
[ "python", "date" ]
I have fetched a **date** from **database** with the following **variable** ``` {{ i.operation_date }} ``` with which I got a value like ``` April 1, 2013 ``` I need to add one year to the above, so that I can get ``` April 1, 2014 ``` Please suggest, how can I do this?
[AGSM's answer](http://stackoverflow.com/a/15742722/68063) shows a convenient way of solving this problem using the [`python-dateutil`](http://labix.org/python-dateutil) package. But what if you don't want to install that package? You could solve the problem in vanilla Python like this: ``` from datetime import date ...
Find maximum value of a column and return the corresponding row values using Pandas
15,741,759
12
2013-04-01T10:31:01Z
15,742,147
15
2013-04-01T10:58:15Z
[ "python", "pandas" ]
![Structure of data;](http://i.stack.imgur.com/a34it.png) Using Python Pandas I am trying to find the 'Country' & 'Place' with the maximum value. This returns the maximum value: ``` data.groupby(['Country','Place'])['Value'].max() ``` But how do I get the corresponding 'Country' and 'Place' name?
Assuming `df` has a unique index, this gives the row with the maximum value: ``` In [34]: df.loc[df['Value'].idxmax()] Out[34]: Country US Place Kansas Value 894 Name: 7 ``` Note that `idxmax` returns index *labels*. So if the DataFrame as duplicates in the index, the label may not uniquely ident...
Why is the name of the containing class not recognized as a return value function annotation?
15,741,887
13
2013-04-01T10:40:13Z
15,742,014
11
2013-04-01T10:48:58Z
[ "python", "python-3.x", "annotations" ]
I was going to use [Python function annotations](http://stackoverflow.com/q/3038033/1106367) to specify the type of the return value of a static factory method. I understand this is [one of the desired use cases](http://www.python.org/dev/peps/pep-3107/#fundamentals-of-function-annotations) for annotations. ``` class ...
`Trie` is a valid expression, and evaluates to the current value associated with the name name `Trie`. But that name is not defined yet -- a class object is only bound to its name *after* the class body has run to completition. You'll note the same behavior in this much simpler example: ``` class C: myself = C ...
How to filter in `sqlalchemy` by string length?
15,743,121
7
2013-04-01T12:01:44Z
15,743,220
9
2013-04-01T12:09:21Z
[ "python", "sqlalchemy" ]
How to filter in `sqlalchemy` by string length? This code snippet: ``` sess.query(db.ArticlesTable).filter(or_( and_(db.ArticlesTable.shorttext.length > 0), ... ``` gave me the following error: ``` File "./aggregate_news.py", line 69, in is_acceptable db.ArticlesTable.shorttext.length > 0), File ...
You need to use the [`func` SQL function generator](http://docs.sqlalchemy.org/en/rel_1_1/core/sqlelement.html?highlight=desc#sqlalchemy.sql.expression.func) to create a `LENGTH()` function: ``` from sqlalchemy.sql.expression import func sess.query(db.ArticlesTable).filter(or_( and_(func.length(db.ArticlesTable.s...
How to send a “multipart/related” with requests in python?
15,746,558
7
2013-04-01T15:41:51Z
15,763,629
16
2013-04-02T12:03:09Z
[ "python", "mime", "multipart", "python-requests" ]
I'm trying to send a multipart/related message using requests in Python. The script seems simple enough, except that requests only seems to allow multipart/form-data messages to be sent, though their documentation does not clearly state this one way or another. My use case is sending soap with attachments. I can provi...
You'll have to create the MIME encoding yourself. You can do so with the [`email.mime`](http://docs.python.org/2/library/email.mime.html) package: ``` import requests from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText related = MIMEMultipart('related') submission = MIMEText('text', '...
How to write a Python module?
15,746,675
145
2013-04-01T15:48:53Z
15,747,198
195
2013-04-01T16:24:12Z
[ "python", "python-2.7", "python-module" ]
I've been making Python scripts for simple tasks at work and never really bothered packaging them for others to use. Now I have been assigned to make a Python wrapper for a REST API. I have absolutely no idea on how to start and I need help. **What I have:** (Just want to be specific as possible) I have the [virtuale...
A module is a file containing Python definitions and statements. The file name is the module name with the suffix `.py` create `hello.py` then write the following function as its content: ``` def helloworld(): print "hello" ``` Then you can import `hello`: ``` >>> import hello >>> hello.helloworld() 'hello' >>> ...
How to write a Python module?
15,746,675
145
2013-04-01T15:48:53Z
33,770,042
71
2015-11-18T01:05:55Z
[ "python", "python-2.7", "python-module" ]
I've been making Python scripts for simple tasks at work and never really bothered packaging them for others to use. Now I have been assigned to make a Python wrapper for a REST API. I have absolutely no idea on how to start and I need help. **What I have:** (Just want to be specific as possible) I have the [virtuale...
**Python 3 - UPDATED 18th November 2015** *Found the accepted answer useful, yet wished to expand on several points for the benefit of others based on my own experiences.* **Module:** A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. **Mod...
What is the difference between rb and r+b modes in file objects
15,746,954
19
2013-04-01T16:06:47Z
15,746,971
29
2013-04-01T16:08:19Z
[ "python", "file", "file-io", "pickle" ]
I am using pickle module in Python and trying different file IO modes: ``` # works on windows.. "rb" with open(pickle_f, 'rb') as fhand: obj = pickle.load(fhand) # works on linux.. "r" with open(pickle_f, 'r') as fhand: obj = pickle.load(fhand) # works on both "r+b" with open(pickle_f, 'r+b') as fhan...
`r+` is used for reading, and writing mode. `b` is for binary. `r+b` mode is open the binary file in read or write mode. You can read more [here](http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files).
Nested tags in BeautifulSoup - Python
15,749,354
2
2013-04-01T18:33:47Z
15,749,456
7
2013-04-01T18:40:07Z
[ "python", "beautifulsoup" ]
I've looked at many examples on websites and on stackoverflow but I couldn't find a universal solution to my question. I'm dealing with a really messy website and I'd like to scrape some data. The markup looks like so: ``` ... <body> ... <table> <tbody> <tr> ... </tr> ...
You can use [CSS selectors in `select`](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors): ``` soup.select('table tr table tr td a') ``` --- ``` In [32]: bs4.BeautifulSoup(urllib.urlopen('http://google.com/?hl=en').read()).select('#footer a') Out[32]: [<a href="/intl/en/ads/">Advertising Programs...
Class properties and __setattr__
15,750,522
11
2013-04-01T19:42:10Z
15,751,159
14
2013-04-01T20:21:46Z
[ "python" ]
In Python class, when I use `__setattr__` it takes precedence over properties defined in this class (or any base classes). Consider the following code: ``` class Test(object): def get_x(self): x = self._x print "getting x: %s" % x return x def set_x(self, val): print "setting x:...
The search order that Python uses for attributes goes like this: 1. `__getattribute__` and `__setattr__` 2. Data descriptors, like `property` 3. Instance variables from the object's `__dict__` 4. Non-Data descriptors (like methods) and other class variables 5. `__getattr__` Since `__setattr__` is first in line, if yo...
Does PyCharm support Jinja2?
15,750,551
27
2013-04-01T19:44:00Z
15,750,552
63
2013-04-01T19:44:00Z
[ "python", "jinja2", "pycharm" ]
A bottle project of mine uses Jinja2. PyCharm does not automatically recognize it and shows such lines as errors. Is there a way to make Jinja2 work?
In the pro edition, Jinja2, Django and Mako are supported. You can configure the template language in the project's settings: ![In Python Template Settings the template langauge is set to Jinja2](http://i.stack.imgur.com/TS8P4.png) The community edition may lack certain template languages.
Does PyCharm support Jinja2?
15,750,551
27
2013-04-01T19:44:00Z
22,154,561
30
2014-03-03T18:36:34Z
[ "python", "jinja2", "pycharm" ]
A bottle project of mine uses Jinja2. PyCharm does not automatically recognize it and shows such lines as errors. Is there a way to make Jinja2 work?
I think it's worth to mention that PyCharm Community edition does not support Jinja2, Mako and Django. It's available only in PyCharm Professional. See [comparison](http://www.jetbrains.com/pycharm/features/editions_comparison_matrix.html) of the two.
Connecting to SQL Server 2012 using sqlalchemy and pyodbc
15,750,711
4
2013-04-01T19:53:59Z
15,750,953
13
2013-04-01T20:08:22Z
[ "python", "sql-server", "sqlalchemy", "pyodbc" ]
I'm trying to connect to a SQL Server 2012 database using SQLAlchemy (with pyodbc) on Python 3.3 (Windows 7-64-bit). I am able to connect using straight pyodbc but have been unsuccessful at connecting using SQLAlchemy. I have dsn file setup for the database access. I successfully connect using straight pyodbc like thi...
The file-based DSN string is being interpreted by SQLAlchemy as server name = `c`, database name = `users`. I prefer connecting without using DSNs, it's one less configuration task to deal with during code migrations. This syntax works using Windows Authentication: ``` engine = sa.create_engine('mssql+pyodbc://serve...
Converting a pandas MultiIndex DataFrame from rows-wise to column-wise
15,751,283
7
2013-04-01T20:28:44Z
15,751,555
12
2013-04-01T20:45:08Z
[ "python", "pandas", "multi-index", "zipline" ]
I'm working in zipline and pandas and have converted a `pandas.Panel` to a `pandas.DataFrame` using the `to_frame()` method. This is the resulting `pandas.DataFrame` which as you can see is multi-indexed: ``` price major minor 2008-01-03 00:00:00+00...
Because you have a MultiIndex in place already, `stack` and `unstack` are what you want to use to move rows to cols and vice versa. That being said, `unstack` should do exactly what you want to accomplish. If you have a DataFrame `df` then `df2 = df.unstack('minor')` should do the trick. Or more simply, since by defaul...
UnitTest Python mock only one function multiple call
15,751,467
6
2013-04-01T20:40:09Z
15,752,019
12
2013-04-01T21:15:07Z
[ "python", "unit-testing", "mocking" ]
I'm using Mock (<http://www.voidspace.org.uk/python/mock/mock.html>), and came across a particular mock case that I cant figure out the solution. I have a function with multiple calls to some\_function that is being Mocked. ``` def function(): some_function(1) some_function(2) some_function(3) ``` I only...
It seems that the `wraps` argument could be what you want: > *wraps*: Item for the mock object to wrap. If wraps is not None then calling the > Mock will pass the call through to the wrapped object (returning the > real result and ignoring return\_value). However, since you only want the second call to not be mocked,...
How to train a neural network to supervised data set using pybrain black-box optimization?
15,751,723
17
2013-04-01T20:55:20Z
15,868,489
18
2013-04-07T22:15:10Z
[ "python", "artificial-intelligence", "neural-network", "pybrain" ]
I have played around a bit with pybrain and understand how to generate neural networks with custom architectures and train them to supervised data sets using backpropagation algorithm. However I am confused by the optimization algorithms and the concepts of tasks, learning agents and environments. For example: How wo...
I finally worked it out!! Its always easy once you know how! Essentially the first arg to the GA is the fitness function (called evaluator in docs) which must take the second argument (an individual, called evaluable in docs) as its only arg. In this example will train to XOR ``` from pybrain.datasets.classification...
Grouping Python dictionary keys as a list and create a new dictionary with this list as a value
15,751,979
11
2013-04-01T21:12:02Z
15,751,984
19
2013-04-01T21:12:53Z
[ "python", "list", "dictionary", "python-2.7" ]
I have a python dictionary ``` d = {1: 6, 2: 1, 3: 1, 4: 9, 5: 9, 6: 1} ``` Since the values in the above dictionary are not unique. I want to group the all the keys of unique values as a list and create a new dictionary as follows: ``` v = {6:[1], 1:[2, 3, 6], 9: [4, 5]} ``` Note the keys of new dictionary **v** s...
Using [`collections.defaultdict`](http://docs.python.org/2/library/collections.html#collections.defaultdict) for ease: ``` from collections import defaultdict v = defaultdict(list) for key, value in sorted(d.iteritems()): v[value].append(key) ``` but you can do it with a bog-standard `dict` too: ``` v = {} fo...
Grouping Python dictionary keys as a list and create a new dictionary with this list as a value
15,751,979
11
2013-04-01T21:12:02Z
15,752,152
8
2013-04-01T21:24:09Z
[ "python", "list", "dictionary", "python-2.7" ]
I have a python dictionary ``` d = {1: 6, 2: 1, 3: 1, 4: 9, 5: 9, 6: 1} ``` Since the values in the above dictionary are not unique. I want to group the all the keys of unique values as a list and create a new dictionary as follows: ``` v = {6:[1], 1:[2, 3, 6], 9: [4, 5]} ``` Note the keys of new dictionary **v** s...
If you don't actually need a `dict` at the end of the day, you could use `itertools.groupby`: ``` from itertools import groupby from operator import itemgetter for k,v in groupby(sorted(d.items()),key=itemgetter(0)): print k,list(v) ``` Of course, you could use this to construct a dict if you really wanted to: ...
How to properly terminate child processes with multiprocessing in python
15,752,078
6
2013-04-01T21:19:04Z
15,754,005
8
2013-04-02T00:13:25Z
[ "python", "multiprocessing" ]
I have a few callback functions and I'd like to launch as multiple processes and have them all terminate via signal from the parent process. My current way of doing this is creating a shared c\_bool with `multiprocessing.Value` and setting it to `True`, then distributing it to all of my processes when they are created...
There are a lot of good reasons to go with your solution: * It's easier to think about than signals. * It's got fewer cross-platform issues to deal with. * You've already got code that works this way. * It makes it easy to add a "graceful shutdown" mechanism if you want to in the future. … and so on. Keep in mind ...
Please explain to me what this python code means?
15,752,413
5
2013-04-01T21:42:52Z
15,752,470
10
2013-04-01T21:46:48Z
[ "python", "python-2.7" ]
I still learn python but this code seems beyond my level. what does it means? ``` pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')] ```
You can convert any list comprehension to an equivalent explicit loop like this: ``` pairs = [] for s1 in qs.split('&'): for s2 in s1.split(';'): pairs.append(s2) ``` The rule is to take all of the `for` and `if` clauses, nest them in the order they appear, and then `append(foo)` for whatever `foo` comes ...
Python Pandas - Date Column to Column index
15,752,422
7
2013-04-01T21:43:42Z
15,752,582
10
2013-04-01T21:54:37Z
[ "python", "dataframe", "pandas" ]
I have a table of data imported from a CSV file into a DataFrame. The data contains around 10 categorical fields, 1 month column (in date time format) and the rest are data series. How do I convert the date column into an index across the the column axis?
You can use [`set_index`](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.set_index.html): ``` df.set_index('month') ``` For example: ``` In [1]: df = pd.DataFrame([[1, datetime(2011,1,1)], [2, datetime(2011,1,2)]], columns=['a', 'b']) In [2]: df Out[2]: a b 0 1 2011-01-01...
python mock Requests and the response
15,753,390
26
2013-04-01T23:01:53Z
15,775,162
20
2013-04-02T21:56:26Z
[ "python", "mocking", "request" ]
I am a beginner to using mock in python and trying to use <http://www.voidspace.org.uk/python/mock>. Please tell me the basic calls to get me working in below scenario. I am using pythons Requests module. In my views.py, I have a function that makes variety of requests.get() calls with different response each time ``...
Here is what worked for me: ``` import mock @mock.patch('requests.get', mock.Mock(side_effect = lambda k:{'aurl': 'a response', 'burl' : 'b response'}.get(k, 'unhandled request %s'%k))) ```
python mock Requests and the response
15,753,390
26
2013-04-01T23:01:53Z
23,914,464
14
2014-05-28T14:29:26Z
[ "python", "mocking", "request" ]
I am a beginner to using mock in python and trying to use <http://www.voidspace.org.uk/python/mock>. Please tell me the basic calls to get me working in below scenario. I am using pythons Requests module. In my views.py, I have a function that makes variety of requests.get() calls with different response each time ``...
try this: <https://github.com/dropbox/responses> provides quite a nice convenience over setting up all the mocking yourself there's also this: <https://github.com/gabrielfalcao/HTTPretty> it's not specific to `requests` library, more powerful in some ways though I found it doesn't lend itself so well to inspecti...
python mock Requests and the response
15,753,390
26
2013-04-01T23:01:53Z
28,507,806
36
2015-02-13T20:00:50Z
[ "python", "mocking", "request" ]
I am a beginner to using mock in python and trying to use <http://www.voidspace.org.uk/python/mock>. Please tell me the basic calls to get me working in below scenario. I am using pythons Requests module. In my views.py, I have a function that makes variety of requests.get() calls with different response each time ``...
This is how you can do it (you can run this file as-is): ``` import requests import unittest from unittest import mock # This is the class we want to test class MyGreatClass: def fetch_json(self, url): response = requests.get(url) return response.json() # This method will be used by the mock to r...
argparse option for passing a list as option
15,753,701
53
2013-04-01T23:34:58Z
15,753,721
102
2013-04-01T23:37:27Z
[ "python", "argparse" ]
I am trying to pass a list as an argument to a command line program. Is there an [`argparse`](https://docs.python.org/3/library/argparse.html) option to pass a list as option? ``` parser.add_argument('-l', '--list', type=list, action='store', dest='list', ...
Use the `nargs` option. ``` parser.add_argument('-l','--list', nargs='+', help='<Required> Set flag', required=True) ``` `nargs='+'` takes 1 or more arguments, `nargs='*'` takes zero or more. Let's take a look in more detail at some of the different ways one might try to do this, and the end result. ``` import argp...
argparse option for passing a list as option
15,753,701
53
2013-04-01T23:34:58Z
24,866,869
8
2014-07-21T13:55:57Z
[ "python", "argparse" ]
I am trying to pass a list as an argument to a command line program. Is there an [`argparse`](https://docs.python.org/3/library/argparse.html) option to pass a list as option? ``` parser.add_argument('-l', '--list', type=list, action='store', dest='list', ...
I prefer passing a delimited string which I parse later in the script. The reasons for this are; the list can be of any type `int` or `str`, and sometimes using `nargs` I run into problems if there are multiple optional arguments and positional arguments. ``` parser = ArgumentParser() parser.add_argument('-l',...
URL-parameters and logic in Django class-based views (TemplateView)
15,754,122
35
2013-04-02T00:26:28Z
15,754,497
44
2013-04-02T01:09:50Z
[ "python", "django", "django-class-based-views" ]
It is unclear to me how it is best to access URL-parameters in class-based-views in Django 1.5. Consider the following: **View:** ``` from django.views.generic.base import TemplateView class Yearly(TemplateView): template_name = "calendars/yearly.html" current_year = datetime.datetime.now().year curre...
To access the url parameters in class based views, use `self.args` or `self.kwargs` so you would access it by doing `self.kwargs['year']`
URL-parameters and logic in Django class-based views (TemplateView)
15,754,122
35
2013-04-02T00:26:28Z
21,366,037
23
2014-01-26T16:26:50Z
[ "python", "django", "django-class-based-views" ]
It is unclear to me how it is best to access URL-parameters in class-based-views in Django 1.5. Consider the following: **View:** ``` from django.views.generic.base import TemplateView class Yearly(TemplateView): template_name = "calendars/yearly.html" current_year = datetime.datetime.now().year curre...
In case you pass URL parameter like this: ``` http://<my_url>/?order_by=created ``` You can access it in class based view by using `self.request.GET` (its not presented in `self.args` nor in `self.kwargs`): ``` class MyClassBasedView(ObjectList): ... def get_queryset(self): order_by = self.request.GE...
how to make argument optional in python argparse
15,754,208
15
2013-04-02T00:34:13Z
15,754,361
8
2013-04-02T00:52:42Z
[ "python", "argparse" ]
I would like to make these invocations of myprog work, and no others. ``` $ python3 myprog.py -i infile -o outfile $ python3 myprog.py -o outfile $ python3 myprog.py -o $ python3 myprog.py ``` In particular I want to make it illegal to specify the infile but not the outfile. In the third case, a default name for the...
You specified a dfault argument for the outfile. ``` parser.add_argument('-o', '--outfile', nargs='?', type=argparse.FileType('w'), default='out.json', help='output file, in JSON format') ``` If the -o option isn't specified at the command line, the arg parser inserts the default argument. Change this to ``` parser...
how to make argument optional in python argparse
15,754,208
15
2013-04-02T00:34:13Z
20,950,971
7
2014-01-06T13:23:36Z
[ "python", "argparse" ]
I would like to make these invocations of myprog work, and no others. ``` $ python3 myprog.py -i infile -o outfile $ python3 myprog.py -o outfile $ python3 myprog.py -o $ python3 myprog.py ``` In particular I want to make it illegal to specify the infile but not the outfile. In the third case, a default name for the...
As an add-on to the selected answer: The option to run `-o` without specifying a file, can be done using `const` combined with `nargs='?'`. From the docs: > When add\_argument() is called with option strings (like -f or --foo) > and nargs='?'. This creates an optional argument that can be followed > by zero or one c...
Draw / Create Scatterplots of datasets with NaN
15,754,333
3
2013-04-02T00:48:36Z
15,754,453
9
2013-04-02T01:04:48Z
[ "python", "matplotlib" ]
I want to draw a scatter plot using pylab, however, some of my data are `NaN`, like this: ``` a = [1, 2, 3] b = [1, 2, None] ``` `pylab.scatter(a,b)` doesn't work. Is there some way that I could draw the points of real value while not displaying these `NaN` value?
Things will work perfectly if you use `NaN`s. `None` is not the same thing. A `NaN` is a float. As an example: ``` import numpy as np import matplotlib.pyplot as plt plt.scatter([1, 2, 3], [1, 2, np.nan]) plt.show() ``` ![enter image description here](http://i.stack.imgur.com/uBGLy.png) Have a look at `pandas` or ...
Keeping only certain characters in a string using Python?
15,754,587
3
2013-04-02T01:20:19Z
15,754,650
7
2013-04-02T01:27:17Z
[ "python", "string", "replace" ]
In my program I have a string like this: ag ct oso gcota Using python, my goal is to get rid of the white space and keep only the a,t,c,and g characters. I understand how to get rid of the white space (I'm just using line = line.replace(" ", "")). But how can I get rid of the characters that I don't need when they co...
A very elegant and fast way is to use regular expressions: ``` import re str = 'ag ct oso gcota' str = re.sub('[^atcg]', '', str) """str is now 'agctgcta""" ```
How to gzip while uploading into s3 using boto
15,754,610
6
2013-04-02T01:22:48Z
15,799,913
14
2013-04-03T23:17:06Z
[ "python", "amazon-s3", "gzip", "boto", "gzipfile" ]
I have a large local file. I want to upload a gzipped version of that file into S3 using the `boto` library. The file is too large to gzip it efficiently on disk prior to uploading, so it should be gzipped in a streamed way during the upload. The `boto` library knows a function `set_contents_from_file()` which expects...
I implemented the solution hinted at in the comments of the accepted answer by garnaat: ``` import cStringIO import gzip def sendFileGz(bucket, key, fileName, suffix='.gz'): key += suffix mpu = bucket.initiate_multipart_upload(key) stream = cStringIO.StringIO() compressor = gzip.GzipFile(fileobj=strea...
Using cumsum in pandas on group()
15,755,057
7
2013-04-02T02:28:06Z
15,756,128
7
2013-04-02T04:30:29Z
[ "python", "group-by", "pandas" ]
From a Pandas newbie: I have data that looks essentially like this - ``` data1=pd.DataFrame({'Dir':['E','E','W','W','E','W','W','E'], 'Bool':['Y','N','Y','N','Y','N','Y','N'], 'Data':[4,5,6,7,8,9,10,11]}, index=pd.DatetimeIndex(['12/30/2000','12/30/2000','12/30/2000','1/2/2001','1/3/2001','1/3/2001','12/30/2000','12/...
Try this: ``` data2 = data1.reset_index() data3 = data2.set_index(["Bool", "Dir", "index"]) # index is the new column created by reset_index running_sum = data3.groupby(level=[0,1,2]).sum().groupby(level=[0,1]).cumsum() ``` The reason you cannot simply use `cumsum` on `data3` has to do with how your data is structu...
How to Setup LIBSVM for Python
15,755,130
4
2013-04-02T02:34:51Z
15,755,258
7
2013-04-02T02:49:29Z
[ "python", "svm", "libsvm" ]
I built [libsvm](http://www.csie.ntu.edu.tw/~cjlin/libsvm/) on Mac OS X with Make. ``` $ tar xzfv libsvm-3.17.tar.gz $ cd libsvm-3.17 $ make ``` This built the various libsvm binaries: ``` $ ls COPYRIGHT heart_scale svm-predict.c svm-train.c tools FAQ.html java svm-scale svm.cpp w...
Instead of going through libsvm in order to access it with Python (I installed libsvm through MacPorts, and `import svmutil` fails), you might want to install the popular [scikit-learn](http://scikit-learn.org/stable/) package, which contains an optimized version of [libsvm with Python bindings](http://scikit-learn.org...
Scipy sparse matrices - purpose and usage of different implementations
15,755,270
12
2013-04-02T02:50:53Z
16,875,631
12
2013-06-01T18:01:39Z
[ "python", "matrix", "scipy", "sparse-matrix" ]
Scipy has [many different types of sparse matrices available](http://docs.scipy.org/doc/scipy/reference/sparse.html). What are the most important differences between these types, and what is the difference in their intended usage? I'm developing a code in python based on a sample code1 in Matlab. One section of the co...
Sorry if I'm not answering this completely enough, but hopefully I can provide some insight. CSC (Compressed Sparse Column) and CSR (Compressed Sparse Row) are more compact and efficient, but difficult to construct "from scratch". Coo (Coordinate) and DOK (Dictionary of Keys) are easier to construct, and can then be c...
expression or statement?:'if a : do_something()' or '(a and do_somthing())',which is better?
15,759,297
2
2013-04-02T08:20:28Z
15,759,323
7
2013-04-02T08:22:14Z
[ "python", "coding-style", "expression" ]
i found that python can easily coding in 'lisp' style. # exp: normal way: ``` if a: do_something() ``` 'function' way: ``` (a and do_something()) ``` normal way: ``` if not a: do_somthing() elif b: do_otherthing() ``` 'function' way ``` ((not a and do_something()) or (b and do_otherthing())) ``` n...
Definitely ``` if a: do_something() ``` The second one (`a and do_somthing())`) is horrible and hacky. As @limelights said, The Zen of Python says *Explicit is better than implicit* and *readability counts*. You should probably read [PEP-8](http://www.python.org/dev/peps/pep-0008/) if you haven't already.
How can I count occurrences of elements that are bigger than a given number in an list?
15,759,827
5
2013-04-02T08:51:07Z
15,759,839
15
2013-04-02T08:51:42Z
[ "python", "list", "count" ]
Let's say I have this list: ``` a = [1.1, 2, 3.1, 4, 5, 6, 7.2, 8.5, 9.1] ``` I want to know how many elements are there bigger than 7. The result should be `3`. Is there an elegant way to do this in Python? I tried with `count` but it won't work.
``` >>> a = [1.1 , 2 , 3.1 , 4 , 5 , 6 , 7.2 , 8.5 , 9.1] >>> sum(x > 7 for x in a) 3 ``` This uses the fact that `bool`s are `int`s too. (If you oppose this because you think it isn't clear or *pythonic* then read [this link](http://stackoverflow.com/a/3175293/1219006))
What is the Python equivalent of `set -x` in shell?
15,760,381
16
2013-04-02T09:17:58Z
15,760,418
18
2013-04-02T09:20:20Z
[ "python", "shell", "debugging" ]
Please suggest Python command which is equivalent of `set -x` in shell scripts. Is there a way to print/log each source file line executed by Python?
You can use the [trace](http://docs.python.org/3.3/library/trace.html) module: ``` python -m trace -t your_script.py ``` The command line above will display every line of code as it is executed.
Mocking two functions with patch for a unit test
15,763,394
21
2013-04-02T11:52:29Z
15,922,422
31
2013-04-10T09:47:39Z
[ "python", "unit-testing", "testing", "mocking", "nose" ]
I have a function I want to unit test contains calls two other functions. I am unsure how can I mock both functions at the same time properly using patch. I have provided an example of what I mean below. When I run nosetests, the tests pass but I feel that there must be a cleaner way to do this and I do not really Unde...
You can simplify your test by using the patch decorator and nesting them like so (they are `MagicMock` objects by default): ``` @patch('cPickle.dump') @patch('__builtin__.open') def test_write_out(mock_open, mock_pickle): path = '~/collection' f = mock_open.return_value f.method.return_value = path wr...
Mocking two functions with patch for a unit test
15,763,394
21
2013-04-02T11:52:29Z
30,799,104
10
2015-06-12T08:55:13Z
[ "python", "unit-testing", "testing", "mocking", "nose" ]
I have a function I want to unit test contains calls two other functions. I am unsure how can I mock both functions at the same time properly using patch. I have provided an example of what I mean below. When I run nosetests, the tests pass but I feel that there must be a cleaner way to do this and I do not really Unde...
In addition to the response @Matti John you can also use `patch` inside function `test_write_out`: ``` from mock import MagicMock, patch def test_write_out(): path = '~/collection' with patch('__builtin__.open') as mock_open, \ patch('cPickle.dump') as mock_pickle: f = mock_open.return_va...
How to get decimal precision in python?
15,768,483
2
2013-04-02T15:47:28Z
15,768,511
9
2013-04-02T15:49:02Z
[ "python", "floating-point" ]
Here is the situation: * I am writing a unit test and comparing the currency which is `NUMERIC` in `PostgreSQL` with precision `(10, 2)` My `test` has assert as ``` self.assertEquals(Decimal(89.12), user_two_transactions[0].amount) ``` I get failure as ``` AssertionError: Decimal('89.120000000000004547473508864641...
Initialize the Decimal with a string: ``` Decimal('89.12') ``` As you can see, 89.12 cannot be represented exactly as a float. [Decimal construction documentation.](http://docs.python.org/2/library/decimal.html#decimal.Decimal) Your other option is a `(sign, digits, exponent)` tuple: ``` In [3]: Decimal((0, (8, 9,...
How to construct a set out of list items?
15,768,757
15
2013-04-02T16:02:12Z
15,768,778
44
2013-04-02T16:02:53Z
[ "python", "list", "set" ]
I have a `list` of filenames in Python, and I would want to construct a `set` out of all the filenames. How would I do it?
If you have a list of hashable objects (filenames would probably be strings, so they should count): ``` lst = ['foo.py', 'bar.py', 'baz.py', 'qux.py', Ellipsis] ``` you can construct the set directly: ``` s = set(lst) ``` In fact, `set` will work this way with *any iterable object!* (Isn't duck typing great?) --- ...
Pythonic way to print list items
15,769,246
33
2013-04-02T16:24:15Z
15,769,313
67
2013-04-02T16:27:43Z
[ "python", "list", "printing", "list-comprehension" ]
I would like to know if there is a better way to print all objects in a Python list than this : ``` myList = [Person("Foo"), Person("Bar")] print("\n".join(map(str, myList))) Foo Bar ``` I read this way is not really good : ``` myList = [Person("Foo"), Person("Bar")] for p in myList: print(p) ``` Isn't there so...
Assuming you are using Python 3.x: ``` print(*myList, sep='\n') ``` You can get the same behavior on Python 2.x using `from __future__ import print_function`, as noted by mgilson in comments. With the print statement on Python 2.x you will need iteration of some kind, regarding your question about `print(p) for p in...
Pythonic way to print list items
15,769,246
33
2013-04-02T16:24:15Z
15,769,321
13
2013-04-02T16:28:06Z
[ "python", "list", "printing", "list-comprehension" ]
I would like to know if there is a better way to print all objects in a Python list than this : ``` myList = [Person("Foo"), Person("Bar")] print("\n".join(map(str, myList))) Foo Bar ``` I read this way is not really good : ``` myList = [Person("Foo"), Person("Bar")] for p in myList: print(p) ``` Isn't there so...
I use this all the time : ``` #!/usr/bin/python l = [1,2,3,7] print "".join([str(x) for x in l] ) ```
Converting a list in a dict to a Series
15,769,706
7
2013-04-02T16:47:41Z
15,770,083
7
2013-04-02T17:07:58Z
[ "python", "python-3.x", "pandas" ]
I'm trying to read lines from an HTML input file and prepare Series / DataFrames so I can eventually create graphs. I'm using lxml's objectify to take lines of HTML data and convert them to a list. Whenever I try to take the list data and make a Series or DataFrame, I get a Series (or DataFrame) containing a number of ...
The problem is the elements in htmldata are not simple types, and np.isscalar is fooled here (as this is how its determined whether we have list-of-lists or a list of scalars just stringify the elements are this will work ``` In [23]: print [ type(x) for x in htmldata ] [<type 'lxml.objectify.StringElement'>, <type 'l...
Return the current user with Django Rest Framework
15,770,488
32
2013-04-02T17:32:08Z
15,782,476
35
2013-04-03T08:35:59Z
[ "python", "django", "api", "django-rest-framework" ]
I am currently developping an API using Django. **However**, I would like to create a view that return the current User with the following endpoint: `/users/current`. To do so, I created a list view and filtered the queryset to the user that made the request. That works but the result is a list, not a single object. ...
With something like this you're probably best off breaking out of the generic views and writing the view yourself. ``` @api_view(['GET']) def current_user(request): serializer = UserSerializer(request.user) return Response(serializer.data) ``` You could also do the same thing using a class based view like so....
Return the current user with Django Rest Framework
15,770,488
32
2013-04-02T17:32:08Z
20,569,205
7
2013-12-13T14:44:51Z
[ "python", "django", "api", "django-rest-framework" ]
I am currently developping an API using Django. **However**, I would like to create a view that return the current User with the following endpoint: `/users/current`. To do so, I created a list view and filtered the queryset to the user that made the request. That works but the result is a list, not a single object. ...
I used a ModelViewSet like this: ``` class UserViewSet(viewsets.ModelViewSet): model = User serializer_class = UserSerializer def dispatch(self, request, *args, **kwargs): if kwargs.get('pk') == 'current' and request.user: kwargs['pk'] = request.user.pk return super(UserViewSe...
Pandas: rolling mean by time interval
15,771,472
29
2013-04-02T18:22:45Z
15,772,263
23
2013-04-02T19:03:58Z
[ "python", "pandas", "time-series" ]
I'm new to Pandas.... I've got a bunch of polling data; I want to compute a rolling mean to get an estimate for each day based on a three-day window. As I understand from [this question](http://stackoverflow.com/questions/9762193/pandas-rolling-median-for-duplicate-time-series-data), the rolling\_\* functions compute t...
What about something like this: First resample the data frame into 1D intervals. This takes the mean of the values for all duplicate days. Use the `fill_method` option to fill in missing date values. Next, pass the resampled frame into `pd.rolling_mean` with a window of 3 and min\_periods=1 : ``` pd.rolling_mean(df.r...
Pandas: rolling mean by time interval
15,771,472
29
2013-04-02T18:22:45Z
18,467,097
26
2013-08-27T13:38:11Z
[ "python", "pandas", "time-series" ]
I'm new to Pandas.... I've got a bunch of polling data; I want to compute a rolling mean to get an estimate for each day based on a three-day window. As I understand from [this question](http://stackoverflow.com/questions/9762193/pandas-rolling-median-for-duplicate-time-series-data), the rolling\_\* functions compute t...
I just had the same question but with irregularly spaced datapoints. Resample is not really an option here. So I created my own function. Maybe it will be useful for others too: ``` from pandas import Series, DataFrame import pandas as pd from datetime import datetime, timedelta import numpy as np def rolling_mean(da...
shuffling/permutating a DataFrame in pandas
15,772,009
30
2013-04-02T18:50:12Z
15,772,330
119
2013-04-02T19:09:05Z
[ "python", "numpy", "pandas" ]
What's a simple and efficient way to shuffle a dataframe in pandas, by rows or by columns? I.e. how to write a function `shuffle(df, n, axis=0)` that takes a dataframe, a number of shuffles `n`, and an axis (`axis=0` is rows, `axis=1` is columns) and returns a copy of the dataframe that has been shuffled `n` times. **...
Use numpy's random.permuation function: ``` In [1]: df = pd.DataFrame({'A':range(10), 'B':range(10)}) In [2]: df Out[2]: A B 0 0 0 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6 7 7 7 8 8 8 9 9 9 In [3]: df.reindex(np.random.permutation(df.index)) Out[3]: A B 0 0 0 5 5 5 6 6 6 3 3 3 8 8 8...
shuffling/permutating a DataFrame in pandas
15,772,009
30
2013-04-02T18:50:12Z
15,772,356
16
2013-04-02T19:10:49Z
[ "python", "numpy", "pandas" ]
What's a simple and efficient way to shuffle a dataframe in pandas, by rows or by columns? I.e. how to write a function `shuffle(df, n, axis=0)` that takes a dataframe, a number of shuffles `n`, and an axis (`axis=0` is rows, `axis=1` is columns) and returns a copy of the dataframe that has been shuffled `n` times. **...
``` In [16]: def shuffle(df, n=1, axis=0): ...: df = df.copy() ...: for _ in range(n): ...: df.apply(np.random.shuffle, axis=axis) ...: return df ...: In [17]: df = pd.DataFrame({'A':range(10), 'B':range(10)}) In [18]: shuffle(df) In [19]: df Out[19]: A B 0 8 ...
shuffling/permutating a DataFrame in pandas
15,772,009
30
2013-04-02T18:50:12Z
35,784,666
21
2016-03-03T22:51:38Z
[ "python", "numpy", "pandas" ]
What's a simple and efficient way to shuffle a dataframe in pandas, by rows or by columns? I.e. how to write a function `shuffle(df, n, axis=0)` that takes a dataframe, a number of shuffles `n`, and an axis (`axis=0` is rows, `axis=1` is columns) and returns a copy of the dataframe that has been shuffled `n` times. **...
Sampling randomizes, so just sample the entire data frame. ``` df.sample(frac=1) ```
How to make new line commands work in a .txt file opened from the internet?
15,772,498
2
2013-04-02T19:18:05Z
15,773,116
7
2013-04-02T19:51:39Z
[ "python", "replace", "runtime-error" ]
I just started using Python, I am trying to make a program that writes the lyrics of a song on the screen opened from the internet "www....../lyrics.txt". My first code: ``` import urllib.request lyrics=urllib.request.urlopen("http://hereIsMyUrl/lyrics.txt") text=lyrics.read() print(text) ``` When I a...
Your example is not working because the data returned by the `read` statement is a "bytes object". You need to decode it using an appropriate encoding. See also the docs for [`request.urlopen`](http://docs.python.org/3/library/urllib.request.html#urllib.request.urlopen), [`file.read`](http://docs.python.org/3/tutorial/...
Conditional statement in a one line lambda function in python?
15,772,617
12
2013-04-02T19:25:12Z
15,772,665
31
2013-04-02T19:27:55Z
[ "python", "if-statement", "lambda", "ternary-operator", "conditional-operator" ]
Apologies if this has been asked before, but I couldn't see it anywhere. Essentially I've come across a scenario where i need to make use of an if statement inside a lambda function. What makes it difficult is that ideally it needs to be in a single line of code (if thats even possible?) Normally, i would write this:...
Use the `exp1 if cond else exp2` syntax. ``` rate = lambda T: 200*exp(-T) if T>200 else 400*exp(-T) ``` Note you don't use `return` in lambda expressions.
Conditional statement in a one line lambda function in python?
15,772,617
12
2013-04-02T19:25:12Z
15,773,019
12
2013-04-02T19:45:37Z
[ "python", "if-statement", "lambda", "ternary-operator", "conditional-operator" ]
Apologies if this has been asked before, but I couldn't see it anywhere. Essentially I've come across a scenario where i need to make use of an if statement inside a lambda function. What makes it difficult is that ideally it needs to be in a single line of code (if thats even possible?) Normally, i would write this:...
The right way to do this is simple: ``` def rate(T): if (T > 200): return 200*exp(-T) else: return 400*exp(-T) ``` There is absolutely no advantage to using `lambda` here. The only thing `lambda` is good for is allowing you to create anonymous functions and use them in an expression (as oppose...
Flask: Get the size of request.files object
15,772,975
6
2013-04-02T19:43:40Z
15,773,118
7
2013-04-02T19:51:41Z
[ "python", "flask" ]
i want to get the size of uploading image to control if it is greater than max file upload limit.I tried this one: ``` @app.route("/new/photo",methods=["POST"]) def newPhoto(): form_photo = request.files['post-photo'] print form_photo.content_length ``` It printed `0` Where am i doing wrong? Should i find th...
The proper way to set a max file upload limit is via the `MAX_CONTENT_LENGTH` app configuration. For example, if you wanted to set an upload limit of 16 megabytes, you would do the following to your app configuration: ``` app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 ``` If the uploaded file is too large, Flask...
Flask: Get the size of request.files object
15,772,975
6
2013-04-02T19:43:40Z
15,782,516
11
2013-04-03T08:38:14Z
[ "python", "flask" ]
i want to get the size of uploading image to control if it is greater than max file upload limit.I tried this one: ``` @app.route("/new/photo",methods=["POST"]) def newPhoto(): form_photo = request.files['post-photo'] print form_photo.content_length ``` It printed `0` Where am i doing wrong? Should i find th...
There are a few things to be aware of here - the content\_length property will be the content length of the file upload as reported by the browser, but unfortunately many browsers dont send this, as noted in the [docs](http://werkzeug.pocoo.org/docs/wrappers/#werkzeug.wrappers.BaseRequest._get_file_stream) and [source]...
remove overlapping tick marks on subplot in matplotlib
15,773,049
8
2013-04-02T19:47:16Z
15,773,404
13
2013-04-02T20:09:17Z
[ "python", "matplotlib", "plot" ]
I've create the following set of subplots using the following function: ``` def create31fig(size,xlabel,ylabel,title=None): fig = plt.figure(figsize=(size,size)) ax1 = fig.add_subplot(311) ax2 = fig.add_subplot(312) ax3 = fig.add_subplot(313) plt.subplots_adjust(hspace=0.001) plt.subplots_adjus...
In the ticker module there is a class called [MaxNLocator](http://matplotlib.sourceforge.net/api/ticker_api.html#matplotlib.ticker.MaxNLocator) that can take a prune kwarg. Using that you can remove the topmost tick of the 2nd and 3rd subplots: ``` import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLo...
Compare rotated lists in python
15,773,738
2
2013-04-02T20:27:56Z
15,773,830
7
2013-04-02T20:33:56Z
[ "python", "readability" ]
I'm trying to compare two lists to determine if one is a rotation (cyclic permutation) of the other, e.g.: ``` a = [1, 2, 3] b = [1, 2, 3] or [2, 3, 1] or [3, 1, 2] ``` are all matches, whereas: ``` b = [3, 2, 1] is not ``` To do this I've got the following code: ``` def _matching_lists(a, b): return not [i fo...
You don't need the function `_matching_lists`, as you can just use `==`: ``` >>> [1,2,3] == [1,2,3] True >>> [1,2,3] == [3,1,2] False ``` I suggest using [`any()`](http://docs.python.org/3/library/functions.html#any) to return as soon a match is found, and using a generator expression to avoid constructing a list of ...
Python bdist_rpm -ba: unknown option error: command 'rpm' failed with exit status 1
15,774,549
3
2013-04-02T21:17:05Z
21,296,145
7
2014-01-22T23:18:42Z
[ "python", "rpm" ]
I'm getting the following error when trying to build a Python RMP package for my Linux distrubtion. I see warnings in the process but I don't think those have to do with the "-ba: unknown error", any ideas how to get this to run? **Error:** bdist\_rpm -ba: unknown option error: command 'rpm' failed with exit status 1...
Just run: ``` yum install rpm-build ``` It appears that if the rpmbuild command is not available, setuptools falls back to usig the "rpm" command, which (as I understand it) had the rpmbuild functionality built in long, long ago but has since beeen separated. So, installing the rpm-build package makes the rpmbuild co...
Can I use python slicing to access one "column" of a nested tuple?
15,775,956
2
2013-04-02T22:59:58Z
15,775,989
9
2013-04-02T23:02:41Z
[ "python", "slice" ]
I have a nested tuple that is basically a 2D table (returned from a MySQL query). Can I use slicing to get a list or tuple of one "column" of the table? For example: ``` t = ((1,2,3),(3,4,5),(1,4,5),(9,8,7)) x = 6 ``` How do I efficiently check whether `x` appears in the 3rd position of any of the tuples? All the ...
Your best bet here is to use a generator expression with the [`any()`](http://docs.python.org/2/library/functions.html#any) function: ``` if any(row[2] == x for row in t): # x appears in the third row of at least one tuple, do something ``` As far as using slicing to just get a column, here are a couple of option...
Beginner Python 3 syntax
15,776,387
2
2013-04-02T23:40:03Z
15,776,430
8
2013-04-02T23:43:10Z
[ "python", "syntax", "python-3.x" ]
I have been writing a simple quiz with python but keep getting a "SyntaxError: multiple statements found while compiling a single statement" in my Python GUI. Please help. ``` print("Welcome to my quiz!") score = 0 question1 = str(input("What colour is a banana.")) if question.lower() == 'yellow': print("Correct. ...
You've got a couple issues. First, `question` is not defined (line 4); that should be `question1`. Second, `print` is a function in Python 3, so your last line ought to be `print(score)`. Third, `input` already returns a string, so you don't need the `str` call. So line 3 ought to look like this: ``` question1 = input...
Manipulating x axis tick labels in matplotlib
15,777,945
2
2013-04-03T02:37:15Z
15,778,195
12
2013-04-03T03:05:49Z
[ "python", "matplotlib", "pandas", "bar-chart" ]
I have noticed that when I have 5 or less bars of data in my bar graph the x-axis automatically adds in extra ticks: ![enter image description here](http://i.stack.imgur.com/d2b5H.png) What I want is something like this: ![enter image description here](http://i.stack.imgur.com/QWtWM.png) Is there any way I can force ...
The `bar` method takes a parameter `align`. Set this parameter as `align='center'`. `align` aligns the bars on the center of the x values we give it, instead of aligning on the left side of the bar (which is the default). Then use the `xticks` method to specify how many ticks on the x-axis and where to place them. ``...
What is the purpose of the '==' operator when comparing values vs '='?
15,777,992
5
2013-04-03T02:42:15Z
15,778,027
11
2013-04-03T02:46:33Z
[ "python" ]
First, note that I understand that `==` is used for comparing two expressions, while `=` is used for assigning a value to a variable. However, python is such a clean language with minimal syntax requirements, that this seems like an easy operator to axe. Also I am not trying to start a debate or discussion, but rather ...
One very simple reason is that python allows boolean expressions: ``` a = b == c ``` and also multiple assignment: ``` a = b = c ``` In the first case, `a` gets assigned a boolean value\* (`True` or `False`) depending on whether `b` and `c` are equal. In the second case, `a` and `b` end up referencing the same obje...
Why do I have to do `sys.stdin = codecs.getreader(sys.stdin.encoding)(sys.stdin)`?
15,778,100
6
2013-04-03T02:55:21Z
17,505,295
10
2013-07-06T17:21:38Z
[ "python", "encoding", "locale" ]
I'm writing a python program which upper-cases all input (a replacement for the non-working `tr '[:lowers:]' '[:upper:]'`). The locale is `ru_RU.UTF-8` and I use `PYTHONIOENCODING=UTF-8` to set the STDIN/STDOUT encodings. This correctly sets `sys.stdin.encoding`. **So, why do I still need to explicitly create a decodin...
To answer "why", we need to understand Python 2.x's built-in [`file`](http://docs.python.org/2/library/stdtypes.html#bltin-file-objects) type, [`file.encoding`](http://docs.python.org/2/library/stdtypes.html#file.encoding), and their relationship. The built-in `file` object deals with raw bytes---always reads and writ...
Python class attribute referencing
15,778,138
2
2013-04-03T02:59:30Z
15,778,285
7
2013-04-03T03:17:31Z
[ "python", "class" ]
This is a sample code that i found from one of the python class tutorial. ``` class MyClass: i = 12345 def f(self): return 'hello world' print MyClass.f print MyClass.i ``` Once i run this, i am expecting the output result of "hello world" and "12345". But instead i am getting this ``` >>> <unbound...
Create an instance of MyClass first. ``` test = MyClass() print test.f() print MyClass.i ``` You don't need to create an instance of MyClass for i, because it is a class member, not an instance member.
Using Python Requests: Sessions, Cookies, and POST
15,778,466
12
2013-04-03T03:43:54Z
15,794,896
23
2013-04-03T18:15:02Z
[ "python", "python-3.x", "session-cookies", "scrape", "python-requests" ]
I'm relatively new to Python and I'm trying to scrape some selling data from the Stubhub, an example of this data seen here: <https://sell.stubhub.com/sellapi/event/4236070/section/null/seatmapdata> You'll notice that if you try and visit that url without logging into stubhub.com first, it won't work. You can sign in...
I don't know how stubhub's api works, but generally it should look like this: ``` s = requests.Session() data = {"login":"my_login", "password":"my_password"} url = "http://example.net/login" r = s.post(url, data=data) ``` Now your session contains cookies provided by login form. To access cookies of this session sim...
How to use python logging in multiple modules
15,780,151
7
2013-04-03T06:15:51Z
15,835,863
15
2013-04-05T13:58:19Z
[ "python", "logging" ]
I was wondering what the standard set up is for performing logging from within a Python app. I am using the Logging class, and I've written my own logger class that instantiates the Logging class. My main then instantiates my logger wrapper class. However, my main instantiates other classes and I want those other clas...
I don't know what you mean by the `Logging` class - there's no such class in Python's built-in logging. You don't really need wrappers: here's an example of how to do logging from arbitrary classes that you write: ``` import logging # This class could be imported from a utility module class LogMixin(object): @pro...
Python openCV detect parallel lines
15,780,210
5
2013-04-03T06:20:03Z
15,780,711
9
2013-04-03T06:53:37Z
[ "python", "opencv", "hough-transform" ]
I have an image and it has some shapes in it. I detected lines with using hough lines. How can I detect which lines are parallel?
Equation of a line in Cartesian coordinates: y = k \* x + b Two lines y = k1 \* x + b1, y = k2 \* x + b2 are parallel, if k1 = k2. So you need to calculate coefficient k for each detected line. In order to **uniquely** identify the equation of a line you need to know the coordinates of **two points** that belong to...
python requests is slow
15,780,679
3
2013-04-03T06:51:50Z
15,781,814
9
2013-04-03T07:55:18Z
[ "python", "download", "urllib2", "python-requests", "urllib" ]
I am developing a download manager. Using the requests module in python to check for a valid link (and hopefully broken links). My code for checking link below: ``` url='http://pyscripter.googlecode.com/files/PyScripter-v2.5.3-Setup.exe' r = requests.get(url,allow_redirects=False) #this line takes 40 seconds ...
Not all hosts support `head` requests. You can use this instead: ``` r = requests.get(url, stream=True) ``` This actually only download the headers, not the response content. Moreover, if the idea is to get the file afterwards, you don't have to make another request. See [here](http://docs.python-requests.org/en/lat...
how to make pycharm always show line numbers in ubuntu
15,781,326
5
2013-04-03T07:28:43Z
15,781,866
12
2013-04-03T07:58:49Z
[ "python", "ubuntu", "pycharm" ]
I know how to do it in the windows version but on ubuntu i dont have a 'show lines numbers' chekbox in settings/appearance thanks
You are looking in the wrong place, it's under `Settings` | **Editor** | `Appearance`, see the [related answer](http://stackoverflow.com/a/8086109/104891). ![Show line numbers](http://img202.imageshack.us/img202/9388/20130403120311.png)
Python Tkinter clearing a frame
15,781,802
11
2013-04-03T07:54:46Z
15,785,255
8
2013-04-03T10:46:15Z
[ "python", "tkinter", "frame" ]
I am trying to clear out a frame in the tkinter so that the new contents can be written (refresh information) but i could not manage to do it. I am aware of these ``` frame.destroy() frame.pack_forget() frame.grid_forget() ``` but frame.destroy() will totally remove the frame. And the other two also could not give me...
`pack_forget` and `grid_forget` will only remove widgets from view, it doesn't destroy them. If you don't plan on re-using the widgets, your only real choice is to destroy them with the `destroy` method. To do that you have two choices: destroy each one individually, or destroy the frame which will cause all of its ch...
Python Tkinter clearing a frame
15,781,802
11
2013-04-03T07:54:46Z
28,623,781
10
2015-02-20T07:36:17Z
[ "python", "tkinter", "frame" ]
I am trying to clear out a frame in the tkinter so that the new contents can be written (refresh information) but i could not manage to do it. I am aware of these ``` frame.destroy() frame.pack_forget() frame.grid_forget() ``` but frame.destroy() will totally remove the frame. And the other two also could not give me...
<http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/universal.html> > w.winfo\_children() > Returns a list of all w's children, in their > stacking order from lowest (bottom) to highest (top). ``` for widget in frame.winfo_children(): widget.destroy() ``` Will destroy all the widget in your frame. No need for a...
Python Popen sending to process on stdin, receiving on stdout
15,785,148
4
2013-04-03T10:41:17Z
15,785,564
8
2013-04-03T11:02:46Z
[ "python", "popen", "argv" ]
I pass an executable on the command-line to my python script. I do some calculations and then I'd like to send the result of these calculations on STDIN to the executable. When it has finished I would like to get the executable's result back from STDOUT. ``` ciphertext = str(hex(C1)) exe = popen([sys.argv[1]], stdout=...
A working example ``` #!/usr/bin/env python import subprocess text = 'hello' proc = subprocess.Popen( 'md5sum',stdout=subprocess.PIPE, stdin=subprocess.PIPE) proc.stdin.write(text) proc.stdin.close() result = proc.stdout.read() print result proc.wait() ``` to get the same thing as “`execuable < params.file ...
Python: How do I print a string that contains multiple words on different lines?
15,785,215
2
2013-04-03T10:44:29Z
15,785,235
8
2013-04-03T10:45:12Z
[ "python", "string" ]
So say I have ``` x = "this string" ``` I'm trying to print the two words on different lines. I'm thinking that I need to use `string.split()` in some way but I'm not sure how.
You can use this: ``` print '\n'.join(x.split()) ``` where ``` x = 'this string' x.split() # ['this', 'string'] ```
How to print a dictionary line by line in Python?
15,785,719
45
2013-04-03T11:10:57Z
15,785,761
21
2013-04-03T11:13:00Z
[ "python", "printing", "dictionary" ]
This is the dictionary ``` cars = {'A':{'speed':70, 'color':2}, 'B':{'speed':60, 'color':3}} ``` Using this `for loop` ``` for keys,values in cars.items(): print(keys) print(values) ``` It prints the following: ``` B {'color': 3, 'speed': 60} A {'color': 2, 'speed': 70} ``` But I w...
You have a nested structure, so you need to format the nested dictionary too: ``` for key, car in cars.items(): print(key) for attribute, value in car.items(): print('{} : {}'.format(attribute, value)) ``` This prints: ``` A color : 2 speed : 70 B color : 3 speed : 60 ```
How to print a dictionary line by line in Python?
15,785,719
45
2013-04-03T11:10:57Z
15,785,785
54
2013-04-03T11:14:05Z
[ "python", "printing", "dictionary" ]
This is the dictionary ``` cars = {'A':{'speed':70, 'color':2}, 'B':{'speed':60, 'color':3}} ``` Using this `for loop` ``` for keys,values in cars.items(): print(keys) print(values) ``` It prints the following: ``` B {'color': 3, 'speed': 60} A {'color': 2, 'speed': 70} ``` But I w...
``` for x in cars: print (x) for y in cars[x]: print (y,':',cars[x][y]) ``` output: ``` A color : 2 speed : 70 B color : 3 speed : 60 ```
How to print a dictionary line by line in Python?
15,785,719
45
2013-04-03T11:10:57Z
21,049,038
50
2014-01-10T16:10:22Z
[ "python", "printing", "dictionary" ]
This is the dictionary ``` cars = {'A':{'speed':70, 'color':2}, 'B':{'speed':60, 'color':3}} ``` Using this `for loop` ``` for keys,values in cars.items(): print(keys) print(values) ``` It prints the following: ``` B {'color': 3, 'speed': 60} A {'color': 2, 'speed': 70} ``` But I w...
A more generalized solution that handles arbitrarily-deeply nested dicts and lists would be: ``` def dumpclean(obj): if type(obj) == dict: for k, v in obj.items(): if hasattr(v, '__iter__'): print k dumpclean(v) else: print '%s : %s' %...
How to print a dictionary line by line in Python?
15,785,719
45
2013-04-03T11:10:57Z
34,306,670
15
2015-12-16T07:59:15Z
[ "python", "printing", "dictionary" ]
This is the dictionary ``` cars = {'A':{'speed':70, 'color':2}, 'B':{'speed':60, 'color':3}} ``` Using this `for loop` ``` for keys,values in cars.items(): print(keys) print(values) ``` It prints the following: ``` B {'color': 3, 'speed': 60} A {'color': 2, 'speed': 70} ``` But I w...
You could use the `json` module for this. The `dumps` function in this module converts a JSON object into a properly formatted string which you can then print. ``` import json cars = {'A':{'speed':70, 'color':2}, 'B':{'speed':60, 'color':3}} print(json.dumps(cars, indent = 4)) ``` The output looks like ```...
Python overriding getter without setter
15,785,982
13
2013-04-03T11:22:58Z
15,786,149
24
2013-04-03T11:30:21Z
[ "python", "oop", "setter", "getter" ]
``` class human(object): def __init__(self, name=''): self.name = name @property def name(self): return self._name @name.setter def name(self, value): self._name = value class superhuman(human): @property def name(self): return 'super ' + name s = superhum...
Use *just* the `.getter` decorator of the original property: ``` class superhuman(human): @human.name.getter def name(self): return 'super ' + self._name ``` Note that you have to use the full name to reach the original property descriptor on the parent class. Demonstration: ``` >>> class superhuman...
Python C API How to pass array of structs from C to Python
15,786,525
7
2013-04-03T11:48:16Z
15,833,209
7
2013-04-05T11:49:36Z
[ "python", "c", "python-c-api" ]
For a python module I'm creating, I want to pass to the python user an array of structs like this: ``` struct tcpstat { inet_prefix local; inet_prefix remote; int lport; int rport; int state; int rq, wq; int timer; int timeout; int retrs; unsigned ...
Finnally what I did was make a list Object with `PyListObject` and append to that list a dictionary with the values of the struct that I want to show to the python user. Hope this will help someone with the same doubt, here is the code: ``` PyObject *dict = NULL; PyListObject *list; list = (PyListObject *) Py_BuildV...
Dictionary for multiple lists
15,786,648
2
2013-04-03T11:54:16Z
15,786,822
9
2013-04-03T12:02:43Z
[ "python", "python-2.7" ]
I have a list like this: ``` list=[[21768L, u'2'], [1746L, u'2'], [2239L, u'2'],[2239L, u'2'], [1965L, u'2'],[1965L, u'2'], [2425L, u'1'], [2425L, u'1'],[2056L, u'1']] ``` How can I get the above list in the form of a dictionary like this: ``` d={u'1':[2425L,2],[2056L,1] , u'2': [21768L, 1],[1746L,1],[2239L,2],[1965...
Use a `defaultdict` and a `Counter`, both from the `collections` module: ``` from collections import defaultdict, Counter d = defaultdict(Counter) for value, key in yourlist: d[key].update([value]) ``` This gives you slightly different structure: ``` defaultdict(<class 'collections.Counter'>, {u'1': Counter({2...
Friendly URL for a REST WebService with CherryPy
15,786,961
12
2013-04-03T12:09:31Z
15,789,415
16
2013-04-03T13:57:19Z
[ "python", "web-services", "rest", "cherrypy" ]
I'm making a RESTful WebService using CherryPy 3 but I encounter a problem : I want to be able to answer requests like : **/customers/1/products/386** meaning I want all the product with ID 386 of the client with ID 1. So I try to make it with the CherryPy's MethodDispatcher like this : ``` class UserController(objec...
CherryPy uses a tree-based mapper which does not accommodate well with segments that have no physical reality as a Python object, here your /1/ segment. With that said, CherryPy does provide functionalities to reach your goal. * Swap to a more explicit mapper such as [selector](https://pypi.python.org/pypi/selector4c...
Python: Function always returns None
15,788,969
4
2013-04-03T13:40:19Z
15,789,017
9
2013-04-03T13:42:29Z
[ "python", "return" ]
I have some Python code that basically looks like this: ``` my_start_list = ... def process ( my_list ): #do some stuff if len(my_list) > 1: process(my_list) else: print(my_list) return my_list print(process(my_start_list)) ``` The strange thing is: **print(my\_list)** prints ou...
You're only returning the list when you have 1 or 0 elements in it (the base case). You need a return statement in the first block as well, where you make the recursive call, or else you drill down to the base case, return the length-1 list to the next level, and then return `None` the rest of the way up. So what you w...
python JSON only get keys in first level
15,789,059
18
2013-04-03T13:44:17Z
15,789,236
35
2013-04-03T13:50:35Z
[ "python", "json", "python-2.7", "iterator", "key" ]
I have a very long and complicated json object but I only want to get the items/keys in the first level! Example: ``` { "1": "a", "3": "b", "8": { "12": "c", "25": "d" } } ``` I want to get **1,3,8** as result! I found this code: ``` for key, value in data.iteritems(): print ...
Just do a simple `.keys()` ``` >>> dct = { ... "1": "a", ... "3": "b", ... "8": { ... "12": "c", ... "25": "d" ... } ... } >>> >>> dct.keys() ['1', '8', '3'] >>> for key in dct.keys(): print key ... 1 8 3 >>> ``` If you need a sorted list: ``` keylist = dct.keys() keylist.sort() `...
Django Serving a Download File
15,790,136
10
2013-04-03T14:27:25Z
15,790,345
17
2013-04-03T14:35:59Z
[ "python", "django", "file", "download" ]
I'm trying to serve a txt file generated with some content and i am having some issues. I'vecreated the temp files and written the content using NamedTemporaryFile and just set delete to false to debug however the downloaded file does not contain anything. My guess is the response values are not pointed to the correct...
Have you considered just sending `p.body` through the `response` like this: ``` response = HttpResponse(mimetype='text/plain') response['Content-Disposition'] = 'attachment; filename="%s.txt"' % p.uuid response.write(p.body) ```
Python Multiprocessing - apply class method to a list of objects
15,790,816
8
2013-04-03T14:55:42Z
16,202,411
9
2013-04-24T21:19:53Z
[ "python", "multiprocessing" ]
Is there a simple way to use Multiprocessing to do the equivalent of this? ``` for sim in sim_list: sim.run() ``` where the elements of sim\_list are "simulation" objects and run() is a method of the simulation class which **does** modify the attributes of the objects. E.g.: ``` class simulation: __init__(self):...
One way to do what you want is to have your computing class (`simulation` in your case) be a subclass of `Process`. When initialized properly, instances of this class will run in separate processes and you can set off a group of them from a list just like you wanted. Here's an example, building on what you wrote above...
Error with os.open in Python
15,791,284
2
2013-04-03T15:14:03Z
15,791,538
7
2013-04-03T15:24:45Z
[ "python", "file-io", "atomic" ]
I'm trying to create and write a file if it does not exist yet, so that it is co-operatively safe from race conditions, and I'm having (probably stupid) problem. First, here's code: ``` import os def safewrite(text, filename): print "Going to open", filename fd = os.open(filename, os.O_CREAT | os.O_EXCL, 0666...
Change the line: ``` fd = os.open(filename, os.O_CREAT | os.O_EXCL, 0666) ``` to be instead: ``` fd=os.open(filename, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0666) ```
DJANGO: How to list_display a reverse foreign key attribute?
15,791,330
5
2013-04-03T15:16:08Z
15,791,696
9
2013-04-03T15:32:35Z
[ "python", "django", "foreign-keys", "admin", "reverse-lookup" ]
I'm building a web app that tracks what library books a person checks out. I have the following models: ``` class Person(models.Model): name = models.CharField(max_length=100) def __unicode__(self): return self.name class Book(models.Model): name = models.CharField(max_length=100) person = mo...
Django admin is really flexible, you can simply add a helper method for it. ``` class PersonAdmin(admin.ModelAdmin): list_display = ('name', 'books') def books(self, obj): return ",".join([k.name for k in obj.book_set.all()]) ```