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
Installing pip on Mac OS X
17,271,319
873
2013-06-24T08:44:30Z
20,829,982
57
2013-12-29T20:55:29Z
[ "python", "osx", "pip" ]
I spent most of the day yesterday searching for a clear answer for installing pip. I can't find a good solution. Can somebody help me install it?
The simplest solution is to follow the [installation instruction from pip's home site](http://www.pip-installer.org/en/latest/installing.html#install-or-upgrade-pip). Basically, this consists in: * downloading [get-pip.py](https://raw.github.com/pypa/pip/master/contrib/get-pip.py). Be sure to do this by following a t...
Installing pip on Mac OS X
17,271,319
873
2013-06-24T08:44:30Z
21,655,094
7
2014-02-09T04:02:10Z
[ "python", "osx", "pip" ]
I spent most of the day yesterday searching for a clear answer for installing pip. I can't find a good solution. Can somebody help me install it?
To install or upgrade **pip**, download **get-pip.py** from <http://www.pip-installer.org/en/latest/installing.html> Then run the following: `sudo python get-pip.py` For example: ``` sudo python Desktop/get-pip.py Password: Downloading/unpacking pip Downloading pip-1.5.2-py2.py3-none-any.whl (1.2MB): 1.2MB down...
Installing pip on Mac OS X
17,271,319
873
2013-06-24T08:44:30Z
25,661,467
10
2014-09-04T09:09:48Z
[ "python", "osx", "pip" ]
I spent most of the day yesterday searching for a clear answer for installing pip. I can't find a good solution. Can somebody help me install it?
Download this file: [get-pip.py](https://bootstrap.pypa.io/get-pip.py) Then simply type ``` sudo python get-pip.py ``` Make sure you are on the same directory as get-pip.py or you supply the correct path for that file. For details, you can visit: <http://pip.readthedocs.org/en/latest/installing.html> or, <http://t...
Installing pip on Mac OS X
17,271,319
873
2013-06-24T08:44:30Z
27,287,725
67
2014-12-04T06:34:33Z
[ "python", "osx", "pip" ]
I spent most of the day yesterday searching for a clear answer for installing pip. I can't find a good solution. Can somebody help me install it?
`pip` is available on OS X via `easy_install`. Open a terminal and type: ``` sudo easy_install pip ``` When prompted for a password enter your normal login password. After the installation has completed you should be able to use `pip` as expected. *note: this works for other python packages too*
Installing pip on Mac OS X
17,271,319
873
2013-06-24T08:44:30Z
28,974,427
27
2015-03-10T21:28:55Z
[ "python", "osx", "pip" ]
I spent most of the day yesterday searching for a clear answer for installing pip. I can't find a good solution. Can somebody help me install it?
Installing a separate copy of Python is a popular option, even though Python already comes with MacOS. You take on the responsibility to make sure you're using the copy of Python you intend. But, the benefits are having the latest Python release and some protection from hosing your system if things go badly wrong. To ...
Installing pip on Mac OS X
17,271,319
873
2013-06-24T08:44:30Z
29,188,667
91
2015-03-21T22:12:48Z
[ "python", "osx", "pip" ]
I spent most of the day yesterday searching for a clear answer for installing pip. I can't find a good solution. Can somebody help me install it?
It's Easy (On Mac): 1. Install easy\_install ``` curl https://bootstrap.pypa.io/ez_setup.py -o - | sudo python ``` 2. Install pip ``` sudo easy_install pip ``` 3. Now, you could install external modules. For example ``` pip install regex # This is only an example for installing other modul...
Installing pip on Mac OS X
17,271,319
873
2013-06-24T08:44:30Z
38,043,109
39
2016-06-26T20:57:25Z
[ "python", "osx", "pip" ]
I spent most of the day yesterday searching for a clear answer for installing pip. I can't find a good solution. Can somebody help me install it?
OK, I read the solutions given above, but here's an **EASY** solution. First of all, make sure you have `Python` installed. How? Open terminal and run the following command. ``` python --version ``` If this command returns a version number that means python is already installed. That also means you already have acce...
How to install a missing python package from inside the script that needs it?
17,271,444
7
2013-06-24T08:50:21Z
17,272,588
9
2013-06-24T09:51:55Z
[ "python", "pip" ]
Assuming that you already have pip or easy\_install installed on your python distribution, I would like to know how can I installed a required package in the user directory from within the script itself. From what I know pip is also a python module so the solution should look like: ``` try: import zumba except Im...
Thanks to @Joop I was able to come-up with the proper answer. ``` try: import zumba except ImportError: import pip pip.main(['install', '--user', 'zumba']) import zumba ``` One important remark is that this will work without requiring root access as it will install the module in user directory. Not s...
Using MySQLdb module with Pypy compiler
17,272,645
5
2013-06-24T09:55:26Z
17,276,879
10
2013-06-24T13:36:49Z
[ "python", "mysql-python", "pypy" ]
I'm trying Pypy compiler to see if I can speed up my code. Nevertheless, I'm having troubles with MySQLdb module, which Pypy is unable to find. I have read that MySQLdb 1.2.4 should work fine with Pypy, so I upgraded the module, and I tested that it is the right version with CPython compiler: ``` import MySQLdb MySQL...
`MySQLdb` is mostly written in C which pypy can't use directly. You'd need to [patch and recompile](https://bitbucket.org/pypy/compatibility/wiki/mysql-python) it. The easier solution would be to use a pure python mysql connector library, like [pymysql](https://pypi.python.org/pypi/PyMySQL) or [mysql-connector-python]...
Long imports in Python
17,273,847
12
2013-06-24T10:59:32Z
17,273,926
16
2013-06-24T11:04:07Z
[ "python", "coding-style" ]
I seldom have to write something like ``` from blqblq.lqlqlqlq.bla import fobarbazbarbarbazar as foo from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas ``` which takes more than 80 characters. This situation is not covered in the [official Python coding style guide](http://www.python.org...
<http://www.python.org/dev/peps/pep-0008/#maximum-line-length> > The preferred way of wrapping long lines is by using Python's implied > line continuation inside parentheses, brackets and braces. Long lines > can be broken over multiple lines by wrapping expressions in > parentheses. These should be used in preference...
Replace x with y or append y if no x
17,274,039
13
2013-06-24T11:10:04Z
17,274,252
9
2013-06-24T11:21:38Z
[ "python", "regex" ]
If a string contains `foo`, replace `foo` with `bar`. Otherwise, append `bar` to the string. How to write this with one single `re.sub` (or any other function) call? No conditions or other logic. ``` import re regex = "????" repl = "????" assert re.sub(regex, repl, "a foo b") == "a bar b" assert re.sub(regex...
This is tricky. In Python, replacement text backreferences to groups that haven't participated in the match [are an error](http://www.regular-expressions.info/refreplace.html), so I had to build quite a convoluted construction using [lookahead assertions](http://www.regular-expressions.info/lookaround.html), but it see...
Replace x with y or append y if no x
17,274,039
13
2013-06-24T11:10:04Z
17,278,058
9
2013-06-24T14:32:58Z
[ "python", "regex" ]
If a string contains `foo`, replace `foo` with `bar`. Otherwise, append `bar` to the string. How to write this with one single `re.sub` (or any other function) call? No conditions or other logic. ``` import re regex = "????" repl = "????" assert re.sub(regex, repl, "a foo b") == "a bar b" assert re.sub(regex...
Try this simple one-liner, no regexp, no tricks: ``` a.replace("foo", "bar") + (a.count("foo") == 0) * "bar" ```
Field default timestamp set to table creation time instead of row creation time
17,274,282
4
2013-06-24T11:23:17Z
17,284,654
8
2013-06-24T20:37:19Z
[ "python", "postgresql", "datetime", "sqlalchemy", "alembic" ]
Using SQLAlchemy, alembic and postgres, when trying to set a column to the row creation time what I finally get is a field that defaults to the time when the table itself was created, instead of the time when the row was created. Model code: ``` datetime = sa.Column(sa.DateTime, nullable=False, server_default=func.no...
Aha, worked it out-- seems you need to tell the server\_default command if you're sending in some SQL that needs to be executed on the DBMS itself: ``` from sqlalchemy import text class Test(db.Model): id = db.Column(db.Integer, primary_key=True) created = db.Column(db.DateTime, server_default=text('now()')) ...
What is a correct way to filter different loggers using python logging?
17,275,334
18
2013-06-24T12:19:58Z
17,276,457
22
2013-06-24T13:16:37Z
[ "python", "logging", "filter" ]
# My purpose is to do a multi-module logging with hierarchical filtering the way it is proposed by *logging* author Vinay Sajip, at least as far as I guess ;-) You can skip to "**How I want it to work**" *Unfortunately, I learned very quickly that working with logging facilities is much more sophisticated than most ...
**Solution** Add the filter to the handler rather than the logger: ``` handler.addFilter(logging.Filter('foo')) ``` --- **Explanation** In the flow chart diagram you posted, notice there are two diamonds: * Does a filter attached to **logger** reject the record? * Does a filter attached to **hander** reject the r...
How to get all datetime instances of the current week, given a day?
17,277,002
4
2013-06-24T13:42:57Z
17,277,133
10
2013-06-24T13:48:39Z
[ "python", "date", "datetime", "python-datetime" ]
Given a day, I want to get all days(datetime instances) of the week in which day is present. I have a solution, please correct me if there is something wrong of if more efficient method exists. ``` >>> import datetime >>> today = datetime.datetime(2013, 06, 26) >>> today datetime.datetime(2013, 6, 26, 0, 0) >>> day_o...
I'd use `datetime.date()` instead to make it clear we are calculating dates here, and use [`date.weekday()`](http://docs.python.org/2/library/datetime.html#datetime.date.weekday) to get the current weekday instead of using the `.isocalendar()` call, giving us a 0-based weekday number (0 is Monday). ``` import datetime...
Python: slicing a multi-dimensional array
17,277,100
12
2013-06-24T13:47:23Z
17,277,125
14
2013-06-24T13:48:19Z
[ "python", "arrays", "numpy" ]
I'm new to Python and numpy. I've figured out how to slice 1 dimension: `arr[atart:end]`, and access an element in the array: `el = arr[row][col]`. Trying something like `slice = arr[0:2][0:2]` (where `arr` is a numpy array) doesn't give me the first 2 rows and columns, but repeats the first 2 rows. What did I just do...
If you use `numpy`, this is easy: ``` slice = arr[:2,:2] ``` or if you want the 0's, ``` slice = arr[0:2,0:2] ``` You'll get the same result. \*note that `slice` is actually the name of a builtin-type. Generally, I would advise giving your object a different "name". --- Another way, if you're working with lists ...
check os.path.isfile(filename) with case sensitive in python
17,277,566
5
2013-06-24T14:09:42Z
17,277,596
9
2013-06-24T14:11:01Z
[ "python", "windows", "python-2.7" ]
I need to check whether the given file is exist or not with case sensitive. ``` file = "C:\Temp\test.txt" if os.path.isfile(file): print "exist..." else: print "not found..." ``` TEST.TXT file is present under C:\Temp folder. but the script showing "file exist" output for file = "C:\Temp\test.txt", it should ...
List all names in the directory instead, so you can do a case-sensitive match: ``` def isfile_casesensitive(path): if not os.path.isfile(path): return False # exit early directory, filename = os.path.split(path) return filename in os.listdir(directory) if isfile_casesensitive(file): print "exist..."...
Defining my own None-like Python constant
17,277,816
3
2013-06-24T14:22:10Z
17,277,913
7
2013-06-24T14:26:32Z
[ "python", "constants" ]
I have a situation in which I'm asked to read collections of database update instructions from a variety of sources. All sources will contain a primary key value so that the code that applies the updates to the database can find the correct record. The files will vary, however, in what additional columns are reported. ...
I don't see anything particularly wrong with your implementation. however, `1` isn't necessarily the best sentinel value as it is a cached constant in Cpython. (e.g. `-1+2 is 1` will return `True`). In these cases, I might consider using a sentinel object instance: ``` NotInFile = object() ``` python also provides a ...
Can I repeat a string format descriptor in python?
17,278,636
16
2013-06-24T14:59:06Z
17,278,762
14
2013-06-24T15:05:30Z
[ "python", "string-formatting" ]
In fortran, I am able to repeat a format descriptor to save rewriting it many times, for example: ``` write(*,'(i5,i5,i5,i5,i5)')a,b,c,d,e ``` could be rewritten as ``` write(*,'(5(i5))')a,b,c,d,e ``` Can a similar approach be used in python? For example, say I wanted to do the same in python, I would have to writ...
You can repeat the formatting string itself: ``` print ('{:5d} '*5).format(*values) ``` Format string is a normal string, so you can [multiply it by int](http://en.wikibooks.org/wiki/Python_Programming/Strings#Numerical) ``` >>> '{:5d} '*5 '{:5d} {:5d} {:5d} {:5d} {:5d} ' ```
gstreamer python bindings for windows
17,278,953
6
2013-06-24T15:14:05Z
21,082,448
9
2014-01-13T01:06:17Z
[ "python", "windows", "gstreamer", "python-gstreamer" ]
I am looking into gstreamer as a means to choose a video device from a list to feed it to an opencv script. I absolutely do not understand how to use gstreamer with python in windows. I installed the **Windows gstreamer 1.07 binaries** from the [gstreamer official website](http://gstreamer.freedesktop.org/). However, ...
This is a bit late, but hopefully it will help. The easiest way to use GStreamer 1.0 is to download the latest version from: <http://sourceforge.net/projects/pygobjectwin32/files/> This will install Python (2.7 or 3.3) modules and, optionally, GStreamer with plugins. However, if you already have GStreamer 0.10 SDK (...
Prettyprint to a file?
17,280,534
9
2013-06-24T16:36:38Z
17,280,610
21
2013-06-24T16:41:11Z
[ "python", "hash", "dictionary", "tree", "pretty-print" ]
I'm using this [gist's](https://gist.github.com/hrldcpr/2012250/) tree, and now I'm trying to figure out how to prettyprint to a file. Any tips?
What you need is Pretty Print [`pprint`](http://docs.python.org/2/library/pprint.html) module: ``` from pprint import pprint # Build the tree somehow with open('output.txt', 'wt') as out: pprint(myTree, stream=out) ```
pdb/ipdb for python break on editable condition
17,280,575
14
2013-06-24T16:39:08Z
17,280,604
7
2013-06-24T16:40:53Z
[ "python", "pdb" ]
Say I have code the following code: ``` for i in range(100): print i ``` In general I can add one line to the code as: ``` for i in range(100): import ipdb;ipdb.set_trace() print i ``` However, now I want to debug it at condition of `i == 10`, and I don't want to bother by typing `c` for 10 times in ipd...
There's a quick dirty way like this: ``` for i in range(100): if i == 10: import ipdb;ipdb.set_trace() print i ``` It works and don't have to busy your mind with any other commands :)
pdb/ipdb for python break on editable condition
17,280,575
14
2013-06-24T16:39:08Z
17,281,976
13
2013-06-24T18:02:22Z
[ "python", "pdb" ]
Say I have code the following code: ``` for i in range(100): print i ``` In general I can add one line to the code as: ``` for i in range(100): import ipdb;ipdb.set_trace() print i ``` However, now I want to debug it at condition of `i == 10`, and I don't want to bother by typing `c` for 10 times in ipd...
alright, i did some exploration myself, here is my new understanding of pdb. when you input `import ipdb;ipdb.set_trace()` you actually add an entry point of ipdb to the line, not really a breakpoint. after you enter ipdb, you can then setup breakpoints so, to realize what i want for conditional debugging, i should ad...
Tkinter messagebox without window?
17,280,637
9
2013-06-24T16:43:14Z
17,280,890
13
2013-06-24T16:56:36Z
[ "python", "tkinter" ]
I want to show an info window in my python script running on ubuntu. I'm using the following code: ``` import tkMessageBox tkMessageBox.showinfo("Say Hello", "Hello World") ``` This works, but there's an empty window displayed, with the message box on top. How can I get rid of the window and just centre the message b...
Tkinter must have a root window. If you don't create one, one will be created for you. If you don't want this root window, create it and then hide it: ``` import Tkinter as tk root = tk.Tk() root.withdraw() tkMessageBox.showinfo("Say Hello", "Hello World") ``` Your other choice is to *not* use tkMessageBox, but inste...
Why is an empty dictionary greater than 1?
17,284,326
15
2013-06-24T20:17:51Z
17,284,362
8
2013-06-24T20:20:31Z
[ "python" ]
Why is the following code true? ``` >>> foo = {} >>> foo > 1 True >>> foo < 1 False >>> foo == 0 False >>> foo == -1 False >>> foo == 1 False ``` I understand what I wanted was len(foo) > 1, but as a beginner this surprised me.
rich comparison between incompatible types is based on the name(?) of the type in python2.x and has been disallowed in python3.x. In any event, in python2.x, the ordering is guaranteed to give the same results for a particular python implementation and version, but the ordering itself is not defined.
Why is an empty dictionary greater than 1?
17,284,326
15
2013-06-24T20:17:51Z
17,284,391
13
2013-06-24T20:21:56Z
[ "python" ]
Why is the following code true? ``` >>> foo = {} >>> foo > 1 True >>> foo < 1 False >>> foo == 0 False >>> foo == -1 False >>> foo == 1 False ``` I understand what I wanted was len(foo) > 1, but as a beginner this surprised me.
From the [docs](http://docs.python.org/release/2.5.2/ref/comparisons.html): > The operators <, >, ==, >=, <=, and != compare the values of two objects. The objects need not have the same type. If both are numbers, they are converted to a common type. Otherwise, objects of different types always compare unequal, and ar...
What's the best way to download file using urllib3
17,285,464
6
2013-06-24T21:30:28Z
17,285,906
9
2013-06-24T22:03:46Z
[ "python", "download", "urllib3" ]
I would like to download file over `HTTP` protocol using `urllib3`. I have managed to do this using following code: ``` url = 'http://url_to_a_file' connection_pool = urllib3.PoolManager() resp = connection_pool.request('GET',url ) f = open(filename, 'wb') f.write(resp.data) f.close() resp.release_conn() ``` B...
Your code snippet is close. Two things worth noting: 1. If you're using `resp.data`, it will consume the entire response and return the connection (you don't need to `resp.release_conn()` manually). This is fine if you're cool with holding the data in-memory. 2. You could use `resp.read(amt)` which will stream the res...
Flask redirecting multiple routes
17,285,826
17
2013-06-24T21:57:19Z
17,628,419
15
2013-07-13T08:31:12Z
[ "python", "redirect", "routing", "flask" ]
I'm trying to implement a redirecting pattern, similar to what StackOverflow does: ``` @route('/<int:id>/<username>/') @route('/<int:id>/') def profile(id, username=None): user = User.query.get_or_404(id) if user.clean_username != username: return redirect(url_for('profile', id=id, username=user.clean...
### debugging routes: Update: to address the primary question "what's wrong with my routes", the simplest way to debug that is to use `app.url_map`; e.g: ``` >>> app.url_map Map([<Rule '/user/<id>/<username>/' (HEAD, OPTIONS, GET) -> profile>, <Rule '/static/<filename>' (HEAD, OPTIONS, GET) -> static>, <Rule '/user...
Flask redirecting multiple routes
17,285,826
17
2013-06-24T21:57:19Z
17,640,458
13
2013-07-14T14:50:41Z
[ "python", "redirect", "routing", "flask" ]
I'm trying to implement a redirecting pattern, similar to what StackOverflow does: ``` @route('/<int:id>/<username>/') @route('/<int:id>/') def profile(id, username=None): user = User.query.get_or_404(id) if user.clean_username != username: return redirect(url_for('profile', id=id, username=user.clean...
You've almost got it. `defaults` is what you want. Here is how it works: ``` @route('/<int:id>/<username>/') @route('/<int:id>/', defaults={'username': None}) def profile(id, username): user = User.query.get_or_404(id) if username is None or user.clean_username != username: return redirect(url_for('pr...
Creating percentile buckets in pandas
17,286,672
17
2013-06-24T23:17:22Z
17,287,046
22
2013-06-24T23:55:58Z
[ "python", "pandas" ]
I am trying to classify my data in percentile buckets based on their values. My data looks like, ``` a = pnd.DataFrame(index = ['a','b','c','d','e','f','g','h','i','j'], columns=['data']) a.data = np.random.randn(10) print a print '\nthese are ranked as shown' print a.rank() data a -0.310188 b -0.191582 c 0.8...
``` In [13]: df[df > df.quantile(0.8)].dropna() Out[13]: data c 0.860467 j 1.887577 In [14]: list(df[df > df.quantile(0.8)].dropna().index) Out[14]: ['c', 'j'] ```
Install OpenCV for Python (multiple python versions)
17,287,250
4
2013-06-25T00:21:52Z
17,324,494
10
2013-06-26T15:38:32Z
[ "python", "opencv", "python-2.7" ]
I have two different versions of python installed on my machine: 2.4 and 2.7. I'm trying to install OpenCV(2.4.5) for the 2.7 version. ``` cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D BUILD_NEW_PYTHON_SUPPORT=ON -D BUILD_EXAMPLES=ON .. ``` It detects the python 2.4 as the current installati...
There are some Cmake flags which allow you to explicitly specify which version of Python to use. You will need to set the values of these flags to the correct location for your installation of Python. The flag names and likely locations are below: ``` PYTHON_EXECUTABLE=/usr/bin/python2.7/ PYTHON_INCLUDE=/usr/include/...
What is this "and" statement actually doing in the return?
17,288,432
10
2013-06-25T02:57:30Z
17,288,474
7
2013-06-25T03:01:42Z
[ "python", "object", "boolean", "return" ]
I am trying to get a better understanding of the following python code and why the author has used the "AND" statement in the return. ``` def valid_password(self, password): PASS_RE = re.compile(r'^.{6,128}$') return password and PASS_RE.match(password) ``` further down the code... ``` if not self.va...
The line in question verifies that the password is ['truthy'](http://docs.python.org/release/2.5.2/lib/truth.html) and that it matches a predefined password regular expression. Here's how it breaks down: * The function returns `password` if `password` is ['falsey'](http://docs.python.org/release/2.5.2/lib/truth.html)...
What is this "and" statement actually doing in the return?
17,288,432
10
2013-06-25T02:57:30Z
17,288,644
16
2013-06-25T03:23:43Z
[ "python", "object", "boolean", "return" ]
I am trying to get a better understanding of the following python code and why the author has used the "AND" statement in the return. ``` def valid_password(self, password): PASS_RE = re.compile(r'^.{6,128}$') return password and PASS_RE.match(password) ``` further down the code... ``` if not self.va...
In Python, both `and` and `or` will return one of their operands. With `or`, Python checks the first operand and, if it is a "truthy" value (more on truthiness later), it returns the first value without checking the second (this is called Boolean shortcut evaluation, and it can be important). If the first is "falsey", ...
AttributeError: 'tuple' object has no attribute
17,290,114
6
2013-06-25T05:57:06Z
17,290,166
8
2013-06-25T06:02:20Z
[ "python", "python-2.7" ]
I'm a beginner in python. I'm not able to understand what the problem is? ``` def list_benefits(): s1 = "More organized code" s2 = "More readable code" s3 = "Easier code reuse" s4 = "Allowing programmers to share and connect code together" return s1,s2,s3,s4 def build_sentence...
You return four variables s1,s2,s3,s4 and reveive them using a single variable obj. This is what is called a `tuple`, obj is associated with 4 values, the values of `s1,s2,s3,s4`. So, use index as you use in a list to get the value you want, in order. ``` obj=list_benefits() print obj[0] + " is a benefit of functions!...
Possible bug in pdb module in Python 3 when using list generators
17,290,314
14
2013-06-25T06:13:47Z
17,290,645
7
2013-06-25T06:34:43Z
[ "python", "python-3.x", "generator", "pdb", "ipdb" ]
After running this code in Python 3: ``` import pdb def foo(): nums = [1, 2, 3] a = 5 pdb.set_trace() foo() ``` The following expressions work: ``` (Pdb) print(nums) [1, 2, 3] (Pdb) print(a) 5 (Pdb) [x for x in nums] [1, 2, 3] ``` but the following expression fails: ``` (Pdb) [x*a for x in nums] **...
It works perfectly fine: ``` >>> import pdb >>> def f(seq): ... pdb.set_trace() ... >>> f([1,2,3]) --Return-- > <stdin>(2)f()->None (Pdb) [x for x in seq] [1, 2, 3] (Pdb) [x in seq for x in seq] [True, True, True] ``` Without showing what you are actually doing nobody can tell you why in your specific case you g...
How to get an average picture from 100 pictures using PIL?
17,291,455
9
2013-06-25T07:23:38Z
17,383,621
17
2013-06-29T18:49:58Z
[ "python", "image", "python-imaging-library" ]
For example, I have 100 pictures whose resolution is the same, and I want to merge them into one picture. For the final picture, the RGB value of each pixel is the average of the 100 pictures' at that position. I know the `getdata` function can work in this situation, but is there a simpler and faster way to do this in...
Let's assume that your images are all .png files and they are all stored in the current working directory. The python code below will do what you want. As Ignacio suggests, using numpy along with PIL is the key here. You just need to be a little bit careful about switching between integer and float arrays when building...
Python joining current directory and parent directory with os.path.join
17,295,086
7
2013-06-25T10:36:13Z
17,295,128
9
2013-06-25T10:38:02Z
[ "python", "os.path" ]
I want to do join the current directory path and a relative directory path `goal_dir` somewhere up in the directory tree, so I get the absolute path to the `goal_dir`. This is my attempt: ``` import os goal_dir = os.path.join(os.getcwd(), "../../my_dir") ``` Now, if the current directory is `C:/here/I/am/`, it joins ...
You can use [normpath](http://docs.python.org/2/library/os.path.html#os.path.normpath), [realpath](http://docs.python.org/2/library/os.path.html#os.path.realpath) or [abspath](http://docs.python.org/2/library/os.path.html#os.path.abspath): ``` import os goal_dir = os.path.join(os.getcwd(), "../../my_dir") print goal_d...
Can socket objects be shared with Python's multiprocessing? socket.close() does not seem to be working
17,297,810
4
2013-06-25T12:49:26Z
17,298,538
9
2013-06-25T13:21:50Z
[ "python", "sockets", "multiprocessing", "ipc" ]
I'm writing a server which uses multiprocessing.Process for each client. socket.accept() is being called in a parent process and the connection object is given as an argument to the Process. The problem is that when calling socket.close() the socket does not seem to be closing. The client's recv() should return immedi...
The problem is that the socket is not closed in the parent process. Therefore it remains open, and causes the symptom you are observing. Immediately after forking off the child process to handle the connection, you should close the parent process' copy of the socket, like so: ``` while True: print "accepting" ...
Python object creation from a function
17,297,932
2
2013-06-25T12:55:00Z
17,297,964
8
2013-06-25T12:56:37Z
[ "python", "oop" ]
My problem might be more linked to OOP than python. I wrote a class in order to describe a molecule and then I wrote a function in order to create a molecule object from a specific file format : `fromFILE`. Thus, for example, I do the following when I use my class : ``` import mymodule mol = mymodule.fromFILE("toto") ...
You can make it a class method: ``` class Molecule(object): # ... @classmethod def fromFile(cls, filename): data = # ... parse data from filename ... return cls(data) ``` This has the added advantage that subclasses can simply inherit it, or override it to adjust what the method does (inc...
Python Pandas: Convert Rows as Column headers
17,298,313
9
2013-06-25T13:12:10Z
17,298,454
18
2013-06-25T13:18:36Z
[ "python", "pandas" ]
I have the following dataframe: ``` Year Country medal no of medals 1896 Afghanistan Gold 5 1896 Afghanistan Silver 4 1896 Afghanistan Bronze 3 1896 Algeria Gold 1 1896 Algeria Silver 2 1896 Algeria Bronze 3 ``...
You're looking for [`pivot_table`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.tools.pivot.pivot_table.html): ``` In [11]: medals = df.pivot_table('no of medals', ['Year', 'Country'], 'medal') In [12]: medals Out[12]: medal Bronze Gold Silver Year Country 1896 Afghanistan 3 5 ...
Insert row into Excel spreadsheet using openpyxl in Python
17,299,364
6
2013-06-25T14:00:19Z
17,322,999
7
2013-06-26T14:31:42Z
[ "python", "excel", "xlrd", "xlwt", "openpyxl" ]
I'm looking for the best approach for inserting a row into a spreadsheet using openpyxl. Effectively, I have a spreadsheet (Excel 2007) which has a header row, followed by (at most) a few thousand rows of data. I'm looking to insert the row as the first row of actual data, so after the header. My understanding is that...
Answering this with the code that I'm now using to achieve the desired result. Note that I am manually inserting the row at position 1, but that should be easy enough to adjust for specific needs. You could also easily tweak this to insert more than one row, and simply populate the rest of the data starting at the rele...
Insert row into Excel spreadsheet using openpyxl in Python
17,299,364
6
2013-06-25T14:00:19Z
30,839,396
9
2015-06-15T07:20:20Z
[ "python", "excel", "xlrd", "xlwt", "openpyxl" ]
I'm looking for the best approach for inserting a row into a spreadsheet using openpyxl. Effectively, I have a spreadsheet (Excel 2007) which has a header row, followed by (at most) a few thousand rows of data. I'm looking to insert the row as the first row of actual data, so after the header. My understanding is that...
== Updated to a fully functional version, based on feedback here: groups.google.com/forum/#!topic/openpyxl-users/wHGecdQg3Iw. == As the others have pointed out, `openpyxl` does not provide this functionality, but I have extended the `Worksheet` class as follows to implement inserting rows. Hope this proves useful to o...
Output Multi-line strings with Python Flask or other framework
17,300,370
2
2013-06-25T14:41:30Z
17,310,038
7
2013-06-26T01:11:18Z
[ "python", "flask", "web2py", "redhat", "bottle" ]
I am trying to take Redhat kickstart files and modify them in python before using them in a server setup. My app uses python to curl the original kickstart file from my Redhat Satellite server then I'm doing a string replace on certain values in the kickstart file. When I curl the file in python it comes back as a mult...
Both Bottle and Flask can handle multi-line strings just fine. Your issue is that your data is being interpreted as `text/html` by default and in HTML any combination of whitespace is collapsed into a single space when displayed. In order to ensure that your data comes back exactly as you sent it you'll want to set the...
Python Sort On The Fly
17,300,419
6
2013-06-25T14:43:54Z
17,300,521
11
2013-06-25T14:47:52Z
[ "python", "algorithm", "sorting" ]
I am thinking about a problem I haven't encountered before and I'm trying to determine the most efficient algorithm to use. I am iterating over two lists, using each pair of elements to calculate a value that I wish to sort on. My end goal is to obtain the top twenty results. I could store the results in a third list,...
Take a look at [`heapq.nlargest`](http://docs.python.org/2/library/heapq.html#heapq.nlargest): > `heapq.nlargest(n, iterable[, key])` > > Return a list with the *n* largest elements from the dataset defined by *iterable*. *key*, if provided, specifies a function of one argument that is used to extract a comparison key...
Replace a character with backslash bug - Python
17,300,917
3
2013-06-25T15:04:20Z
17,300,929
10
2013-06-25T15:05:01Z
[ "python", "string", "escaping" ]
This feels like a bug to me. I am unable to replace a character in a string with a single backslash: ``` >>>st = "a&b" >>>st.replace('&','\\') 'a\\b' ``` I know that `'\'` isn't a legitimate string because the `\` escapes the last `'`. However, I don't want the result to be `'a\\b'`; I want it to be `'a\b'`. How is t...
You are looking at the string *representation*, which is itself a valid Python string literal. The `\\` is itself just *one* slash, but displayed as an escaped character to make the value a valid Python literal string. You can copy and paste that string back into Python and it'll produce the same value. Use `print st...
Python: Lifetime of module-global variables
17,301,091
2
2013-06-25T15:13:15Z
17,301,205
7
2013-06-25T15:19:16Z
[ "python", "global", "lifecycle", "cpython" ]
I have a shared resource with high initialisation cost and thus I want to access it across the system (it's used for some instrumentation basically, so has to be light weight). So I created a module managing the setup and access to it. It does a lazy initialise of the resource and stores it in a module global variable....
Objects that are no longer referenced are indeed garbage collected (they are deleted automatically when their reference count drops to 0). A module global, however, will never have it's reference count drop to 0; once imported a module object (its namespace), lives in the `sys.modules` mapping. The namespace itself re...
how to compute 'nearby' nodes with networkx
17,301,887
5
2013-06-25T15:49:49Z
17,302,185
7
2013-06-25T16:04:41Z
[ "python", "math", "networkx" ]
What I'm looking for here may well be a built-in function in `networkx`, and have a mathematical name - if so, I'd like to know what it is! it is very difficult to Google for, it seems. Given a graph `G` and a starting node `i`, I'd like to find the subgraph of all the nodes "within `P` edges" from `i` - that is, thos...
Use [`single_source_shortest_path`](http://networkx.readthedocs.io/en/stable/reference/generated/networkx.algorithms.shortest_paths.unweighted.single_source_shortest_path.html) or [`single_source_shortest_path_length`](http://networkx.readthedocs.io/en/stable/reference/generated/networkx.algorithms.shortest_paths.unwei...
Making a request to a RESTful API using python
17,301,938
39
2013-06-25T15:51:57Z
17,306,347
75
2013-06-25T19:55:36Z
[ "python", "api", "rest", "elasticsearch" ]
I have a RESTful API that I have exposed using an implementation of Elasticsearch on an EC2 instance to index a corpus of content. I can can query the search by running the following from my terminal (MacOSX): ``` curl -XGET 'http://ES_search_demo.com/document/record/_search?pretty=true' -d '{"query":{"bool":{"must":[...
Using [requests](http://docs.python-requests.org/en/latest/): ``` import requests url = 'http://ES_search_demo.com/document/record/_search?pretty=true' data = '{"query":{"bool":{"must":[{"text":{"record.document":"SOME_JOURNAL"}},{"text":{"record.articleTitle":"farmers"}}],"must_not":[],"should":[]}},"from":0,"size":5...
Making a request to a RESTful API using python
17,301,938
39
2013-06-25T15:51:57Z
32,721,995
19
2015-09-22T16:23:57Z
[ "python", "api", "rest", "elasticsearch" ]
I have a RESTful API that I have exposed using an implementation of Elasticsearch on an EC2 instance to index a corpus of content. I can can query the search by running the following from my terminal (MacOSX): ``` curl -XGET 'http://ES_search_demo.com/document/record/_search?pretty=true' -d '{"query":{"bool":{"must":[...
Using [requests](http://www.python-requests.org/en/latest/) and [json](https://docs.python.org/2/library/json.html) makes it simple. 1. Call the API 2. Assuming the API returns a JSON, parse the JSON object into a Python dict using `json.loads` function 3. Loop through the dict to extract information. [Requests](h...
How to pickle unicodes and save them in utf-8 databases
17,303,266
5
2013-06-25T16:59:20Z
17,307,606
9
2013-06-25T21:10:40Z
[ "python", "django", "unicode", "utf-8", "pickle" ]
I have a database (mysql) where I want to store pickled data. The data can be for instance a dictionary, which may contain unicode, e.g. ``` data = {1 : u'é'} ``` and the database (mysql) is in utf-8. When I pickle, ``` import pickle pickled_data = pickle.dumps(data) print type(pickled_data) # returns <type 'str'...
Pickle data is opaque, binary data, even when you use protocol version 0: ``` >>> pickle.dumps(data, 0) '(dp0\nI1\nV\xe9\np1\ns.' ``` When you try to store that in a `TextField`, Django will try to decode that data to UTF8 to store it; this is what fails because this is not UTF-8 encoded data; it is binary data inste...
How to delete from list?
17,304,895
2
2013-06-25T18:30:32Z
17,304,963
7
2013-06-25T18:34:02Z
[ "python" ]
Assuming I have the following list: ``` array1 = ['A', 'C', 'Desk'] ``` and another array that contains: ``` array2 = [{'id': 'A', 'name': 'Greg'}, {'id': 'Desk', 'name': 'Will'}, {'id': 'E', 'name': 'Craig'}, {'id': 'G', 'name': 'Johnson'}] ``` What is a good way to remove items from the list? The following does ...
You could also use a list comprehension for this: ``` >>> array2 = [{'id': 'A', 'name': 'Greg'}, ... {'id': 'Desk', 'name': 'Will'}, ... {'id': 'E', 'name': 'Craig'}, ... {'id': 'G', 'name': 'Johnson'}] >>> array1 = ['A', 'C', 'Desk'] >>> filtered = [item for item in array2 if item['id'] not in array1] >>> filtered [{...
How can I format a float using matplotlib's LaTeX formatter?
17,306,755
4
2013-06-25T20:19:37Z
17,307,525
8
2013-06-25T21:05:39Z
[ "python", "matplotlib", "tex", "python-2.4" ]
I have a number in my python script that I want to use as part of the title of a plot in matplotlib. Is there a function that converts a float to a formatted TeX string? Basically, ``` str(myFloat) ``` returns ``` 3.5e+20 ``` but I want ``` $3.5 \times 10^{20}$ ``` or at least for matplotlib to format the float ...
With old stype formatting: ``` print r'$%s \times 10^{%s}$' % tuple('3.5e+20'.split('e+')) ``` with new format: ``` print r'${} \times 10^{{{}}}$'.format(*'3.5e+20'.split('e+')) ```
Pass Scrapy Spider a list of URLs to crawl via .txt file
17,307,718
2
2013-06-25T21:18:27Z
17,307,762
11
2013-06-25T21:21:47Z
[ "python", "web-scraping", "scrapy", "command-line-arguments", "scrapy-spider" ]
I'm a little new to Python and very new to Scrapy. I've set up a spider to crawl and extract all the information I need. However, I need to pass a .txt file of URLs to the start\_urls variable. For exmaple: ``` class LinkChecker(BaseSpider): name = 'linkchecker' start_urls = [] #Here I want the list to start...
Run your spider with `-a` option like: ``` scrapy crawl myspider -a filename=text.txt ``` Then read the file in the `__init__` method of the spider and define `start_urls`: ``` class MySpider(BaseSpider): name = 'myspider' def __init__(self, filename=None): if filename: with open(filenam...
Is there a Java equivalent to Python's Easy String Splicing?
17,307,761
12
2013-06-25T21:21:47Z
17,307,852
8
2013-06-25T21:27:11Z
[ "java", "python", "string", "splice" ]
Ok, what I want to know is is there a way with Java to do what Python can do below... ``` string_sample = "hello world" string_sample[:-1] >>> "hello world" string_sample[-1] >>> "d" string_sample[3] >>> "l" ``` Because it seems to me that Java make you work for the same result (I'm particularly getting at having ...
Sorry, Java's `substring` is not as flexible as Python's slice notation. In particular: * You can give it just a begin, or a begin and end, but not just an end. (Also, no step, but you don't miss that as much.) * Negative indices are an error, not a count from the end. You can see the docs [here](http://docs.oracle....
why can't bind to 0.0.0.0:80 and 192.168.1.1:80 simultaneously?
17,307,779
7
2013-06-25T21:23:08Z
17,307,859
12
2013-06-25T21:27:39Z
[ "python", "linux", "sockets" ]
My python test code: ``` import socket s1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s1.bind(('192.168.1.1', 80)) s1.listen(5) s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s2.bind(('0.0.0.0', 80)) s2.listen(5) ``` I got this error: ``` fpemud-workstation test # ./test.py Traceback (most recent...
You cannot bind to both 0.0.0.0:80 and any other IP on port 80, because 0.0.0.0 covers every IP that exists on the machine, including your 192.168.1.1 address. It doesn't mean 'any other destination address', it means 'all interfaces on this box'.
"Too much contention" when creating new entity in dataStore
17,308,179
6
2013-06-25T21:48:40Z
25,810,972
7
2014-09-12T14:45:52Z
[ "python", "google-app-engine", "gae-datastore" ]
dear all This morning my GAE application generated several error log: "too much contention on these datastore entities. please try again.". In my mind, this type of error only happens when multiple requests try modify **the same entity** or entities in the **same entity group**. When I got this error, my code is inse...
Without seeing how the calls are made(you show the calling code but how often is it called, via loop or many pages calling the same put at the same time) but I believe the issue is better explained [here](https://developers.google.com/appengine/articles/scalability). In particular > You will also see this problem if y...
Python: How to check if keys exists and retrieve value from Dictionary in descending priority
17,308,695
11
2013-06-25T22:33:09Z
17,308,754
16
2013-06-25T22:38:07Z
[ "python", "dictionary", "key-value" ]
I have a dictionary and I would like to get some values from it based on some keys. For example, I have a dictionary for users with their first name, last name, username, address, age and so on. Let's say, I only want to get one value (name) - either last name or first name or username but in descending priority like s...
One option is to use chained gets: ``` value = myDict.get('lastName', myDict.get('firstName', myDict.get('userName'))) ``` But if you have keySet defined, this might be clearer: ``` value = None for key in keySet: if key in myDict: value = myDict[key] break ```
Check whether string is in CSV
17,308,872
9
2013-06-25T22:51:18Z
17,309,010
13
2013-06-25T23:03:46Z
[ "python", "csv" ]
I want to search a CSV file and print either `True` or `False`, depending on whether or not I found the string. However, I'm running into the problem whereby it will return a false positive if it finds the string embedded in a larger string of text. E.g.: It will return `True` if string is `foo` and the term `foobar` i...
when you look inside a csv file using the `csv` module, it will return each row as a list of columns. So if you want to lookup your string, you should modify your code as such: ``` import csv username = input() with open('Users.csv', 'rt') as f: reader = csv.reader(f, delimiter=',') # good point by @paco f...
End-to-end example with PyXB. From an XSD schema to an XML document
17,309,125
9
2013-06-25T23:18:44Z
17,321,253
8
2013-06-26T13:22:37Z
[ "python", "xml", "xsd", "pyxb" ]
I am having a hard time getting started with [PyXB](http://pyxb.sourceforge.net/). Say I have [an XSD file](http://en.wikipedia.org/wiki/XSD) (an XML schema). I would like to: 1. Use PyXB to define Python objects according to the schema. 2. Save those objects to disk as XML files that satisfy the schema. How can I d...
A simple google search brings this: <http://pyxb.sourceforge.net/userref_pyxbgen.html#pyxbgen> In particular the part that says: > Translate this into Python with the following command: ``` pyxbgen -u po1.xsd -m po1 ``` > The -u parameter identifies a schema > document describing contents of a namespace. The parame...
ImportError: No module named requests
17,309,288
143
2013-06-25T23:34:58Z
17,309,309
210
2013-06-25T23:36:57Z
[ "python", "python-requests", "python-import" ]
Whenever I run this code, I consistently get an error saying `No module Named requests`: ``` import requests ``` The error I get: ``` File "ex2.py", line 1, in <module> import requests ImportError: No module named requests ```
Requests is not a built in module, so you will have to download it. You can get it here: <https://pypi.python.org/pypi/requests> ## OSX/Linux Use `$ sudo pip install requests` if you have pip installed On OSX you can also use `sudo easy_install -U requests` if you have easy\_install installed. ## Windows Use `> Pa...
ImportError: No module named requests
17,309,288
143
2013-06-25T23:34:58Z
24,846,900
10
2014-07-20T02:50:16Z
[ "python", "python-requests", "python-import" ]
Whenever I run this code, I consistently get an error saying `No module Named requests`: ``` import requests ``` The error I get: ``` File "ex2.py", line 1, in <module> import requests ImportError: No module named requests ```
I had the same issue, so I copied the folder named "requests" from <https://pypi.python.org/pypi/requests#downloads>[requests download](https://pypi.python.org/pypi/requests#downloads) to "/Library/Python/2.7/site-packages". Now when you use: import requests, it should work fine.
How to debug a Flask app
17,309,889
17
2013-06-26T00:51:42Z
17,309,954
7
2013-06-26T00:58:45Z
[ "python", "debugging", "flask" ]
How are you meant to debug errors in Flask? Print to the console? Flash messages to the page? Or is there a more powerful option available to figure out what's happening when something goes wrong?
You can use `app.run(debug=True)` for the [Werkzeug Debugger](http://werkzeug.pocoo.org/) **edit** as mentioned below, and I should have known.
How to debug a Flask app
17,309,889
17
2013-06-26T00:51:42Z
17,322,636
15
2013-06-26T14:15:59Z
[ "python", "debugging", "flask" ]
How are you meant to debug errors in Flask? Print to the console? Flash messages to the page? Or is there a more powerful option available to figure out what's happening when something goes wrong?
Running the app in debug mode (`app.debug = True` or `app.run(debug=True`) will show an interactive traceback and console in the browser when there is an error. If you're using PyCharm you can take advantage of its debugger to step through the code with breakpoints. Just make sure you turn off Werkzeug's debugger and ...
Continue and pass: what's the difference?
17,310,257
3
2013-06-26T01:42:45Z
17,310,268
7
2013-06-26T01:44:00Z
[ "python" ]
What is the difference between `continue` and `pass` in Python? I am fairly new to Python and am trying to get my code looking and acting more professionally. I can see their value, but to my untrained mind, I can't see the clear difference. I have looked [here](http://docs.python.org/2/tutorial/controlflow.html#break-...
### Pass `pass` means that you're just filling a place where a statement is usually needed ``` while True: pass # The pass is needed syntactically ``` From the documentation: > pass is a null operation -- when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactic...
Compare decimals in python
17,314,028
2
2013-06-26T07:28:23Z
17,314,200
8
2013-06-26T07:38:02Z
[ "python", "testing", "decimal" ]
I want to be able to compare Decimals in Python. For the sake of making calculations with money, clever people told me to use Decimals instead of floats, so I did. However, if I want to verify that a calculation produces the expected result, how would I go about it? ``` >>> a = Decimal(1./3.) >>> a Decimal('0.33333333...
You are not using `Decimal` the right way. ``` >>> from decimal import * >>> Decimal(1./3.) # Your code Decimal('0.333333333333333314829616256247390992939472198486328125') >>> Decimal("1")/Decimal("3") # My code Decimal('0.3333333333333333333333333333') ``` In "your code", you actually perfor...
Improve quality of Wand conversion
17,314,382
10
2013-06-26T07:47:23Z
17,314,761
16
2013-06-26T08:07:35Z
[ "python", "imagemagick", "resolution", "wand" ]
I convert files of different formats (JPEG, PNG, TIFF, PDF) to JPEG using [Wand](http://wand-py.org), a ctypes-based ImageMagick binding for Python. The resulting files are very low-quality. If there is text in original file, it becomes almost unreadable in the resulting file. Before Wand i used Imagemagick console co...
[This](http://librelist.com/browser//wand/2012/12/12/change-density-to-resolution/) would help you. Pass `resolution` option to the constructor of `Image` e.g.: ``` with Image(filename='file.pdf', resolution=200) as image: image.compression_quality = 99 image.save(filename='file.jpg') ```
Import common modules by default when compiling SCSS
17,315,450
2
2013-06-26T08:46:13Z
17,317,098
7
2013-06-26T10:02:27Z
[ "python", "sass" ]
I have several modules that contain things like `border-radius`, `$btnBgColor`, `up-arrow`. Most of the other modules need to `import` them in one place or another, so I'm wondering if I can `import` them in the `SCSS` compiler level **so that I can use those common utilities as if they are built-in ones**. The SCSS ...
Yes, this is indeed possible and in fact there is already an existing mature solution. It's called [Compass](http://compass-style.org/). There's a lot of ambiguity about what Compass is, here's my kinda non-canonical attempt to resolve it. **Compass is three different things under one name:** 1. **A [standard](http...
CSV new-line character seen in unquoted field error
17,315,635
72
2013-06-26T08:56:14Z
17,315,921
118
2013-06-26T09:09:41Z
[ "python", "django", "csv" ]
the following code worked until today when I imported from a Windows machine and got this error: **new-line character seen in unquoted field - do you need to open the file in universal-newline mode?** ``` import csv class CSV: def __init__(self, file=None): self.file = file def read_file(self): ...
It'll be good to see the csv file itself, but this might work for you, give it a try, replace: ``` file_read = csv.reader(self.file) ``` with: ``` file_read = csv.reader(self.file, dialect=csv.excel_tab) ``` Or, open a file with `universal newline mode` and pass it to `csv.reader`, like: ``` reader = csv.reader(op...
CSV new-line character seen in unquoted field error
17,315,635
72
2013-06-26T08:56:14Z
27,890,720
26
2015-01-11T18:44:19Z
[ "python", "django", "csv" ]
the following code worked until today when I imported from a Windows machine and got this error: **new-line character seen in unquoted field - do you need to open the file in universal-newline mode?** ``` import csv class CSV: def __init__(self, file=None): self.file = file def read_file(self): ...
I realize this is an old post, but I ran into the same problem and don't see the correct answer so I will give it a try Python Error: ``` _csv.Error: new-line character seen in unquoted field ``` Caused by trying to read Macintosh (pre OS X formatted) CSV files. These are text files that use CR for end of line. If u...
CSV new-line character seen in unquoted field error
17,315,635
72
2013-06-26T08:56:14Z
30,380,644
17
2015-05-21T17:33:27Z
[ "python", "django", "csv" ]
the following code worked until today when I imported from a Windows machine and got this error: **new-line character seen in unquoted field - do you need to open the file in universal-newline mode?** ``` import csv class CSV: def __init__(self, file=None): self.file = file def read_file(self): ...
For Mac OS X, save your CSV file in "Windows Comma Separated (.csv)" format.
CSV new-line character seen in unquoted field error
17,315,635
72
2013-06-26T08:56:14Z
32,827,068
10
2015-09-28T15:53:53Z
[ "python", "django", "csv" ]
the following code worked until today when I imported from a Windows machine and got this error: **new-line character seen in unquoted field - do you need to open the file in universal-newline mode?** ``` import csv class CSV: def __init__(self, file=None): self.file = file def read_file(self): ...
If this happens to you **on mac** (as it did to me): 1. Save the file as `CSV (MS-DOS Comma-Separated)` 2. Run the following script ``` with open(csv_filename, 'rU') as csvfile: csvreader = csv.reader(csvfile) for row in csvreader: print ', '.join(row) ```
Split a large pandas dataframe
17,315,737
7
2013-06-26T09:01:24Z
17,315,875
23
2013-06-26T09:07:14Z
[ "python", "pandas" ]
I have a large dataframe with 423244 lines. I want to split this in to 4. I tried the following code which gave an error? `ValueError: array split does not result in an equal division` ``` for item in np.split(df, 4): print item ``` How to split this dataframe in to 4 groups?
Use `np.array_split`: ``` Docstring: Split an array into multiple sub-arrays. Please refer to the ``split`` documentation. The only difference between these functions is that ``array_split`` allows `indices_or_sections` to be an integer that does *not* equally divide the axis. ``` --- ``` In [1]: import pandas as ...
How can I check if a Pandas dataframe's index is sorted
17,315,881
13
2013-06-26T09:07:27Z
17,347,945
21
2013-06-27T16:01:11Z
[ "python", "pandas" ]
I have a vanilla pandas dataframe with an index. I need to check if the index is sorted. Preferably without sorting it again. e.g. I can test an index to see if it is unique by index.is\_unique() is there a similar way for testing sorted?
How about: `df.index.is_monotonic`
reading v 7.3 mat file in python
17,316,880
11
2013-06-26T09:53:15Z
17,316,965
14
2013-06-26T09:57:17Z
[ "python", "matlab", "io" ]
I am trying to read a matlab file with the following code ``` import scipy.io mat = scipy.io.loadmat('test.mat') ``` and it gives me the following error ``` raise NotImplementedError('Please use HDF reader for matlab v7.3 files') NotImplementedError: Please use HDF reader for matlab v7.3 files ``` so could anyone p...
Try using [`h5py`](http://www.h5py.org/) module ``` import h5py f = h5py.File('test.mat') f.keys() ```
Is there an platform independent equivalent of os.startfile()?
17,317,219
9
2013-06-26T10:08:28Z
17,317,468
14
2013-06-26T10:22:04Z
[ "python", "platform" ]
I want to run a program on several platforms (including Mac OS), so I try to keep it as platform independent as possible. I use Windows myself, and I have a line `os.startfile(file)`. That works for me, but not on other platforms (I read in the documentation, I haven't tested for myself). Is there an equivalent that w...
It appears that a cross-platform file opening module does not yet exist, but you can rely on existing infrastructure of the popular systems. This snippet covers Windows, MacOS and Unix-like systems (Linux, FreeBSD, Solaris...): ``` import os, sys, subprocess def open_file(filename): if sys.platform == "win32": ...
Celery and SQLAlchemy - This result object does not return rows. It has been closed automatically
17,317,344
4
2013-06-26T10:15:07Z
17,348,307
7
2013-06-27T16:20:49Z
[ "python", "multithreading", "sqlalchemy", "celery" ]
I have a celery project connected to a MySQL databases. One of the tables is defined like this: ``` class MyQueues(Base): __tablename__ = 'accepted_queues' id = sa.Column(sa.Integer, primary_key=True) customer = sa.Column(sa.String(length=50), nullable=False) accepted = sa.Column(sa.Boolean, default=T...
> All together: any advise to skip these difficulties? yes. you absolutely *cannot* use a Session (or any objects which are associated with that Session), or a Connection, in more than one thread simultaneously, especially with MySQL-Python whose DBAPI connections are very thread-unsafe\*. You must organize your appli...
Fixing "warning: GMP or MPIR library not found; Not building Crypto.PublickKey._fastmath" error on Python 2.7 with CentOS 6.4
17,319,033
13
2013-06-26T11:40:28Z
22,385,112
7
2014-03-13T16:35:16Z
[ "python", "python-2.7", "centos", "centos6" ]
I'm running a CentOS 6.4 server with Python 2.7 (installed via PythonBrew script) I have gmp installed via 'yum install gmp' and python-devel installed via 'yum install python-devel' (but it's for python 2.6 series) I'm trying to install pycrypto on my server, but it's giving me ``` warning: GMP or MPIR library not ...
I got the above error when trying to install Fabric at the system level on Centos 6.4 using pip. (Fabric uses pycrypto). ``` warning: GMP or MPIR library not found; Not building Crypto.PublickKey._fastmath ``` This is how I got it working: ``` yum install gmp-devel sudo pip uninstall ecdsa pycrypto paramiko fabric ...
Where to set maximum line length in pycharm
17,319,422
97
2013-06-26T12:00:31Z
17,319,775
164
2013-06-26T12:16:53Z
[ "python", "pycharm" ]
I am using pycharm on windows. I am not getting the settings to change the maximum line length to 79 characters. I see that it is 120 characters by default. Where can I change it to 79 characters? I searched in the settings but didn't find. Thanks
Here is screenshot of my Pycharm. Required settings is in following path: `File -> Settings -> Editor -> Code Style -> General: Right margin (columns)` [![Pycharm 4 Settings Screenshot](http://i.stack.imgur.com/V3BLg.png)](http://i.stack.imgur.com/V3BLg.png)
Where to set maximum line length in pycharm
17,319,422
97
2013-06-26T12:00:31Z
28,055,797
13
2015-01-20T21:51:06Z
[ "python", "pycharm" ]
I am using pycharm on windows. I am not getting the settings to change the maximum line length to 79 characters. I see that it is 120 characters by default. Where can I change it to 79 characters? I searched in the settings but didn't find. Thanks
For **PyCharm 4** File >> Settings >> Editor >> Code Style: Right margin (columns) **suggestion:** Take a look at other options in that tab, they're very helpful
python one-line list comprehension: if-else variants
17,321,138
57
2013-06-26T13:17:25Z
17,321,170
115
2013-06-26T13:18:58Z
[ "python", "list-comprehension", "ternary-operator", "conditional-operator" ]
It's more about python list comprehension syntax. I've got a list comprehension that produces list of odd numbers of a given range: ``` [x for x in range(1, 10) if x % 2] ``` This makes a filter - I've got a source list, where I remove even numbers (`if x % 2`). I'd like to use something like if-then-else here. Follo...
`x if y else z` is the syntax for the expression you're returning for each element. Thus you need: ``` [ x if x%2 else x*100 for x in range(1, 10) ] ``` The confusion arises from the fact you're using a *filter* in the first example, but not in the second. In the second example you're only *mapping* each value to ano...
python one-line list comprehension: if-else variants
17,321,138
57
2013-06-26T13:17:25Z
17,321,197
13
2013-06-26T13:19:43Z
[ "python", "list-comprehension", "ternary-operator", "conditional-operator" ]
It's more about python list comprehension syntax. I've got a list comprehension that produces list of odd numbers of a given range: ``` [x for x in range(1, 10) if x % 2] ``` This makes a filter - I've got a source list, where I remove even numbers (`if x % 2`). I'd like to use something like if-then-else here. Follo...
``` [x if x % 2 else x * 100 for x in range(1, 10) ] ```
python one-line list comprehension: if-else variants
17,321,138
57
2013-06-26T13:17:25Z
21,204,379
7
2014-01-18T12:54:12Z
[ "python", "list-comprehension", "ternary-operator", "conditional-operator" ]
It's more about python list comprehension syntax. I've got a list comprehension that produces list of odd numbers of a given range: ``` [x for x in range(1, 10) if x % 2] ``` This makes a filter - I've got a source list, where I remove even numbers (`if x % 2`). I'd like to use something like if-then-else here. Follo...
Just another solution, hope some one may like it : Using: [False, True][Expression] ``` >>> map(lambda x: [x*100, x][x % 2 != 0], range(1,10)) [1, 200, 3, 400, 5, 600, 7, 800, 9] >>> ```
python one-line list comprehension: if-else variants
17,321,138
57
2013-06-26T13:17:25Z
24,474,086
7
2014-06-29T07:40:36Z
[ "python", "list-comprehension", "ternary-operator", "conditional-operator" ]
It's more about python list comprehension syntax. I've got a list comprehension that produces list of odd numbers of a given range: ``` [x for x in range(1, 10) if x % 2] ``` This makes a filter - I've got a source list, where I remove even numbers (`if x % 2`). I'd like to use something like if-then-else here. Follo...
You can do that with list comprehension too: ``` A=[[x*100, x][x % 2 != 0] for x in range(1,11)] print A ```
get dataframe row count based on conditions
17,322,109
5
2013-06-26T13:56:02Z
17,322,585
9
2013-06-26T14:14:12Z
[ "python", "pandas" ]
I want to get the count of dataframe rows based on conditional selection. I tried the following code. ``` print df[(df.IP == head.idxmax()) & (df.Method == 'HEAD') & (df.Referrer == '"-"')].count() ``` output: ``` IP 57 Time 57 Method 57 Resource 57 Status 57 Bytes 57 Referrer 5...
You are asking for the condition where all the conditions are true, so len of the frame is the answer, unless I misunderstand what you are asking ``` In [17]: df = DataFrame(randn(20,4),columns=list('ABCD')) In [18]: df[(df['A']>0) & (df['B']>0) & (df['C']>0)] Out[18]: A B C D 12 ...
Multiple try codes in one block
17,322,208
9
2013-06-26T14:00:12Z
17,322,283
14
2013-06-26T14:03:11Z
[ "python", "exception", "exception-handling", "try-catch", "except" ]
I have a problem with my code in the try block. To make it easy this is my code: ``` try: code a code b #if b fails, it should ignore, and go to c. code c #if c fails, go to d code d except: pass ``` Is something like this possible?
You'll have to make this *separate* `try` blocks: ``` try: code a except ExplicitException: pass try: code b except ExplicitException: try: code c except ExplicitException: try: code d except ExplicitException: pass ``` This assumes you want to run ...
TypeError: 'dict_keys' object does not support indexing
17,322,668
18
2013-06-26T14:17:23Z
17,322,707
35
2013-06-26T14:19:04Z
[ "python" ]
``` def shuffle(self, x, random=None, int=int): """x, random=random.random -> shuffle list x in place; return None. Optional arg random is a 0-argument function returning a random float in [0.0, 1.0); by default, the standard random.random. """ randbelow = self._randbelow for i in reversed(ran...
Clearly you're passing in `d.keys()` to your `shuffle` function. Probably this was written with python2.x (when `d.keys()` returned a list). With python3.x, `d.keys()` returns a `dict_keys` object which behaves a lot more like a `set` than a `list`. As such, it can't be indexed. The solution is to pass `list(d.keys())...
Automatically play sound in IPython notebook
17,323,336
9
2013-06-26T14:45:22Z
20,806,969
13
2013-12-27T19:53:55Z
[ "python", "ipython", "ipython-notebook" ]
I often run long-running cells in my IPython notebook. I'd like the notebook to automatically beep or play a sound when the cell is finished executing. Is there some way to do this in iPython notebook, or maybe some command I can put at the end of a cell that will automatically play a sound? I'm using Chrome if that m...
## TL;DR At the top of your notebook ``` from IPython.display import Audio sound_file = './sound/beep.wav' ``` `sound_file` should point to a file on your server, or accessible on the internet. Then later, at the end of the long-running cell ``` <code that takes a long time> Audio(url=sound_file, autoplay=True) `...
Cannot import Tornado submodules
17,323,568
14
2013-06-26T14:55:57Z
17,323,652
36
2013-06-26T14:59:25Z
[ "python", "tornado" ]
Trying to install Tornado for first time (On EC2 Linux instance). I did ``` pip install tornado ``` and then tried running the hello world example: <http://www.tornadoweb.org/en/stable/#hello-world> ``` import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): ...
Don't name your file `tornado.py`; it shadows the actual Tornado import. Name it something like what you used in your example, e.g. `hello.py` Right now, your `import tornado.ioloop` is trying to import the member `ioloop` from your own file, because it's named `tornado` and in the current directory which has the high...
Python re module becomes 20 times slower when looping on more than 100 different regex
17,325,281
14
2013-06-26T16:12:56Z
17,325,325
26
2013-06-26T16:15:12Z
[ "python", "regex", "performance" ]
My problem is about parsing log files and removing variable parts on each line in order to group them. For instance: ``` s = re.sub(r'(?i)User [_0-9A-z]+ is ', r"User .. is ", s) s = re.sub(r'(?i)Message rejected because : (.*?) \(.+\)', r'Message rejected because : \1 (...)', s) ``` I have about 120+ matching rules ...
Python keeps an internal cache for compiled regular expressions. Whenever you use one of the top-level functions that takes a regular expression, Python first compiles that expression, and the result of that compilation is cached. [Guess how many items the cache can hold](http://hg.python.org/cpython/file/e95161820160...
How to open a new window on a browser using Selenium WebDriver for python?
17,325,629
7
2013-06-26T16:31:09Z
17,325,883
10
2013-06-26T16:44:12Z
[ "python", "selenium", "selenium-webdriver", "window" ]
I am attempting to open a new tab OR a new window in a browser using selenium for python. It is of little importance if a new tab or new window is opened, it is only important that a second instance of the browser is opened. I have tried several different methods already and none have succeeded. 1. Switching to a win...
How about you do something like this ``` driver = webdriver.Firefox() #First FF window second_driver = webdriver.Firefox() #The new window you wanted to open ``` Depending on which window you want to interact with, you send commands accordingly ``` print driver.title #to interact with the first driver print second_d...
Is Python's dict.pop atomic?
17,326,067
7
2013-06-26T16:53:43Z
17,326,099
17
2013-06-26T16:55:37Z
[ "python", "dictionary" ]
It seems reasonable to believe that [`dict.pop`](http://docs.python.org/2.7/library/stdtypes.html#dict.pop) operates atomically, since it raises `KeyError` if the specified key is missing and no default is provided, like so: ``` d.pop(k) ``` However, the documentation does not appear to specifically address that poin...
For the default type, `dict.pop()` is a C-function call, which means that it is executed with *one* bytecode evaluation. This makes that call atomic. Python threads switch only when the bytecode evaluation loop lets them, so at bytecode boundaries. Some Python C functions do call back into Python code (think `__dunder...
Python os.chdir is modifying the passed directory name
17,326,337
9
2013-06-26T17:07:43Z
17,326,444
19
2013-06-26T17:14:23Z
[ "python", "python-2.7", "directory", "chdir" ]
I am trying to change the current working directory in python using os.chdir. I have the following code: ``` import os os.chdir("C:\Users\Josh\Desktop\20130216") ``` However, when I run it, it seems to change the directory, as it comes out with the following error message: ``` Traceback (most recent call last): Fil...
Python is interpreting the `\2013` part of the path as the *escape sequence* `\201`, which maps to the character `\x81`, which is ü (and of course, `C:\Users\Josh\Desktopü30216` doesn't exist). Use a raw string, to make sure that Python doesn't try to interpret anything following a `\` as an escape sequence. ``` os...
Is there a way to auto-adjust Excel column widths with pandas.ExcelWriter?
17,326,973
12
2013-06-26T17:44:08Z
17,811,984
9
2013-07-23T13:43:09Z
[ "python", "excel", "pandas", "openpyxl" ]
I am being asked to generate some Excel reports. I am currently using pandas quite heavily for my data, so naturally I would like to use the pandas.ExcelWriter method to generate these reports. However the fixed column widths are a problem. The code I have so far is simple enough. Say I have a dataframe called 'df': ...
There is probably no automatic way to do it right now, but as you use openpyxl, the following line (adapted from another answer by user [Bufke](http://stackoverflow.com/users/443457/bufke) on [how to do in manually](http://stackoverflow.com/a/14450572/2375855)) allows you to specify a sane value (in character widths): ...
python replace single backslash with double backslash
17,327,202
18
2013-06-26T17:56:37Z
17,327,272
8
2013-06-26T18:00:48Z
[ "python", "string", "replace", "backslash" ]
In python, I am trying to replace a single backslash ("\") with a double backslash("\"). I have the following code: ``` directory = string.replace("C:\Users\Josh\Desktop\20130216", "\", "\\") ``` However, this gives an error message saying it doesn't like the double backslash. Can anyone help?
Use escape characters: `"full\\path\\here"`, `"\\"` and `"\\\\"`
python replace single backslash with double backslash
17,327,202
18
2013-06-26T17:56:37Z
17,327,500
29
2013-06-26T18:14:02Z
[ "python", "string", "replace", "backslash" ]
In python, I am trying to replace a single backslash ("\") with a double backslash("\"). I have the following code: ``` directory = string.replace("C:\Users\Josh\Desktop\20130216", "\", "\\") ``` However, this gives an error message saying it doesn't like the double backslash. Can anyone help?
No need to use `str.replace` or `string.replace` here, just convert that string to a raw string: ``` >>> strs = r"C:\Users\Josh\Desktop\20130216" ^ | notice the 'r' ``` Below is the `repr` version of the above string, that's why you're seeing `\\` here. But, in fact the actual string cont...
Python - parse IPv4 addresses from string (even when censored)
17,327,912
5
2013-06-26T18:37:50Z
17,328,350
8
2013-06-26T19:01:12Z
[ "python", "regex", "python-2.7", "ipv4", "data-extraction" ]
**Objective:** Write Python 2.7 code to extract IPv4 addresses from string. **String content example:** --- The following are IP addresses: 192.168.1.1, 8.8.8.8, 101.099.098.000. These can also appear as 192.168.1[.]1 or 192.168.1(.)1 or 192.168.1[dot]1 or 192.168.1(dot)1 or 192 .168 .1 .1 or 192. 168. 1. 1. and the...
Here is a regex that works: ``` import re pattern = r"((([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])[ (\[]?(\.|dot)[ )\]]?){3}([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5]))" text = "The following are IP addresses: 192.168.1.1, 8.8.8.8, 101.099.098.000. These can also appear as 192.168.1[.]1 or 192.168.1(.)1 or 192.168.1[dot]1 or 1...
Pandas Set DatetimeIndex
17,328,655
4
2013-06-26T19:19:10Z
17,328,858
7
2013-06-26T19:31:58Z
[ "python", "pandas" ]
Say I create a pandas DataFrame with two columns, `b` (a DateTime) and `c` (an integer). Now I want to make a DatetimeIndex from the values in the first column (`b`): ``` import pandas as pd import datetime as dt a=[1371215423523845, 1371215500149460, 1371215500273673, 1371215500296504, 1371215515568529, 137121553160...
`set_index` is not inplace (unless you pass `inplace=True`). otherwise all correct ``` In [7]: df = df.set_index(pd.DatetimeIndex(df['b'])) In [8]: df Out[8]: <class 'pandas.core.frame.DataFrame'> DatetimeIndex: 100 entries, 2013-06-14 09:10:23.523845 to 2013-06-14 10:12:51.650043 Data columns (total 2 columns): b ...
Django What is reverse relationship?
17,328,910
4
2013-06-26T19:34:44Z
17,329,054
8
2013-06-26T19:43:15Z
[ "python", "django" ]
Can someone tell me what is reverse relationship means? I have started using Django and in lot of places in the documentation I see 'reverse relationship, being mentioned. What is it exactly mean? why is it useful? What does it got to do with related\_name in reference to [this post](http://stackoverflow.com/questions/...
Here is the documentation on [related\_name](https://docs.djangoproject.com/en/dev/topics/db/queries/#backwards-related-objects) Lets say you have 2 models ``` class Group(models.Model): #some attributes class Profile(models.Model): group = models.ForeignKey(Group) #more attributes ``` Now, from a profi...
Upload a file to a python flask server using curl
17,329,087
9
2013-06-26T19:45:02Z
17,330,714
11
2013-06-26T21:23:44Z
[ "python", "curl", "flask" ]
I am trying to upload a file to a server using curl and python flask. Below I have the code of how I have implemented it. Any ideas on what I am doing wrong. ``` curl -i -X PUT -F name=Test -F [email protected] "http://localhost:5000/" @app.route("/", methods=['POST','PUT']) def hello(): file = request.file...
Your curl command means you're transmitting two form contents, one file called `filedata`, and one form field called `name`. So you can do this: ``` file = request.files['filedata'] # gives you a FileStorage test = request.form['name'] # gives you the string 'Test' ``` but `request.files['Test']` doesn't exi...
Convert list to lower-case
17,329,113
9
2013-06-26T19:46:30Z
17,329,140
27
2013-06-26T19:48:16Z
[ "python" ]
I'm trying to get this column of words in input.txt: ``` Suzuki music Chinese music Conservatory Blue grass Rock n roll Rhythm Composition Contra Instruments ``` into this format: ``` "suzuki music", "chinese music", "conservatory music", "blue grass", "rock n roll", "rhythm"... ``` This code: ``` with open ('arts...
Instead of ``` for item in list: item.lower() ``` change the name of the variable `list` to `l` or whatever you like that *isn't* a reserved word in Python and use the following line, obviously substituting whatever you name the list for `l`. ``` l = [item.lower() for item in l] ``` The `lower` method returns a...