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 |
|---|---|---|---|---|---|---|---|---|---|
Can't install PIL after Mac OS X 10.9 | 19,532,125 | 129 | 2013-10-23T03:14:19Z | 19,545,473 | 202 | 2013-10-23T15:05:07Z | [
"python",
"osx",
"python-imaging-library",
"pip",
"osx-mavericks"
] | I've just updated my Mac OS to 10.9 and I discovered that some (all?) of my Python modules are not here anymore, especially the Image one.
So I try to execute `sudo pip install pil`, but I get this error:
```
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/includ... | Following worked for me:
```
ln -s /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers/X11 /usr/local/include/X11
sudo pip install pil
```
UPDATE:
But there is more correct solution below, provided by Will.
>... |
Can't install PIL after Mac OS X 10.9 | 19,532,125 | 129 | 2013-10-23T03:14:19Z | 19,551,193 | 32 | 2013-10-23T20:00:53Z | [
"python",
"osx",
"python-imaging-library",
"pip",
"osx-mavericks"
] | I've just updated my Mac OS to 10.9 and I discovered that some (all?) of my Python modules are not here anymore, especially the Image one.
So I try to execute `sudo pip install pil`, but I get this error:
```
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/includ... | ```
sudo ln -s /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.8.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers/X11/ /usr/local/include/X11
```
helps for me!
os x 10.9
```
pip install pillow
```
but! after pip install ...
```
*** ZLIB (PNG/ZIP) support n... |
Can't install PIL after Mac OS X 10.9 | 19,532,125 | 129 | 2013-10-23T03:14:19Z | 19,569,943 | 9 | 2013-10-24T15:18:22Z | [
"python",
"osx",
"python-imaging-library",
"pip",
"osx-mavericks"
] | I've just updated my Mac OS to 10.9 and I discovered that some (all?) of my Python modules are not here anymore, especially the Image one.
So I try to execute `sudo pip install pil`, but I get this error:
```
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/includ... | installing command line tools fixed the issue for me
you have to install them separately as they are not part of the packages in xcode now:
<https://developer.apple.com/downloads/index.action?=command%20line%20tools#> |
Can't install PIL after Mac OS X 10.9 | 19,532,125 | 129 | 2013-10-23T03:14:19Z | 19,817,768 | 98 | 2013-11-06T16:44:34Z | [
"python",
"osx",
"python-imaging-library",
"pip",
"osx-mavericks"
] | I've just updated my Mac OS to 10.9 and I discovered that some (all?) of my Python modules are not here anymore, especially the Image one.
So I try to execute `sudo pip install pil`, but I get this error:
```
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/includ... | open your terminal and execute:
`xcode-select --install` |
Can't install PIL after Mac OS X 10.9 | 19,532,125 | 129 | 2013-10-23T03:14:19Z | 23,316,577 | 8 | 2014-04-26T21:14:04Z | [
"python",
"osx",
"python-imaging-library",
"pip",
"osx-mavericks"
] | I've just updated my Mac OS to 10.9 and I discovered that some (all?) of my Python modules are not here anymore, especially the Image one.
So I try to execute `sudo pip install pil`, but I get this error:
```
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/includ... | Non of those worked for me.. I kept receiving:
```
clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future]
clang: note: this will be a hard error (cannot be downgraded to a warning) in the future
error: command 'cc' failed with exit status 1
```
So I found a work around... |
Can't install PIL after Mac OS X 10.9 | 19,532,125 | 129 | 2013-10-23T03:14:19Z | 24,826,071 | 9 | 2014-07-18T13:22:40Z | [
"python",
"osx",
"python-imaging-library",
"pip",
"osx-mavericks"
] | I've just updated my Mac OS to 10.9 and I discovered that some (all?) of my Python modules are not here anymore, especially the Image one.
So I try to execute `sudo pip install pil`, but I get this error:
```
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/includ... | Here is what I did, some steps may not be necessary just for PIL but I needed libpng and others anyways:
1) Run xcode install, use this command or download updates from the app store:
```
xcode-select --install
```
1b) Add the Command Line Tools optional tool, in Mountain Lion this was an option on the xcode Downloa... |
Can't install PIL after Mac OS X 10.9 | 19,532,125 | 129 | 2013-10-23T03:14:19Z | 29,438,122 | 8 | 2015-04-03T18:59:26Z | [
"python",
"osx",
"python-imaging-library",
"pip",
"osx-mavericks"
] | I've just updated my Mac OS to 10.9 and I discovered that some (all?) of my Python modules are not here anymore, especially the Image one.
So I try to execute `sudo pip install pil`, but I get this error:
```
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/includ... | Works for me ( OS X Yosemite 10.10.2 - Python 2.7.9 ) :
```
xcode-select --install
sudo pip install pillow
```
Try this to check it:
```
from PIL import Image
image = Image.open("file.jpg")
image.show()
``` |
What's the point of the "is_authenticated" method used in Flask-Login? | 19,532,372 | 7 | 2013-10-23T03:41:39Z | 19,533,025 | 19 | 2013-10-23T04:50:11Z | [
"python",
"web",
"flask",
"flask-login",
"flask-extensions"
] | I'm working through the Flask Mega-Tutorial right now and I've come across this bit of code:
```
class User(db.Model):
id = db.Column(db.Integer, primary_key = True)
nickname = db.Column(db.String(64), unique = True)
email = db.Column(db.String(120), unique = True)
role = db.Column(db.SmallInteger, def... | First of all, `is_anonymous()` and `is_authenticated()` are each other's inverse. You could define one as the negation of the other, if you want.
You can use these two methods to determine if a user is logged in.
When nobody is logged in Flask-Login's `current_user` is set to an `AnonymousUser` object. This object re... |
Floor Plan Edge Detection - Image Processing? | 19,532,473 | 5 | 2013-10-23T03:55:38Z | 19,549,678 | 7 | 2013-10-23T18:33:15Z | [
"python",
"opencv",
"image-processing"
] | I am a guy from a completely different discipline who need some Image Processing techniques to achieve this goal in a project. I need to derive the edges from an indoor floor plan, as shown below

I have tried this particular Python edge detect snippe... | here's an example. you will need to have opencv package to run it.
there's a break there because the image has artifacts. if you use a higher quality image, it's probably going to be better. if you cant have a higher quality image, may be morphological operations can be used to connect the small gaps and remove quarte... |
Python Django send_mail newlines? | 19,535,369 | 2 | 2013-10-23T07:24:25Z | 19,536,412 | 8 | 2013-10-23T08:19:49Z | [
"python",
"django",
"email"
] | I'm using django send\_mail like this:
```
from django.core.mail import send_mail
send_mail('Test', 'asdfasdfasdf\nasdfasfasdfasdf\nasdfasdfasdf', '[email protected]', ['[email protected]'], fail_silently=False)
```
Gmail recieves this.
```
Content-type: multipart/alternative; boundary="----------=_1382512224-21042-5... | Try sending your email as HTML instead of plain text. Use [EmailMessage()](https://docs.djangoproject.com/en/dev/topics/email/#sending-alternative-content-types).
```
from django.core.mail import EmailMessage
msg = EmailMessage(
'Test',
'asdfasdfasdf<br>asdfasfasdfasdf<br... |
Slow division in cython | 19,537,673 | 10 | 2013-10-23T09:17:21Z | 19,576,057 | 8 | 2013-10-24T20:31:56Z | [
"python",
"cython"
] | In order to get fast division in cython, I can use the compiler directive
```
@cython.cdivision(True)
```
This works, in that the resulting c code has no zero division checking. However for some reason it is actually making my code slower. Here is an example:
```
@cython.boundscheck(False)
@cython.wraparound(False)
... | Firstly, you need to call the functions many (>1000) times, and take an average of the time spent in each, to get an accurate idea of how different they are. Calling each function once will not be accurate enough.
Secondly, the time spent in the function will be affected by other things, not just the loop with divisio... |
Add "nan" to numpy array 20 times without loop | 19,539,267 | 3 | 2013-10-23T10:33:57Z | 19,539,585 | 7 | 2013-10-23T10:48:17Z | [
"python",
"arrays",
"numpy"
] | Here is my code:
```
import numpy as np
n = np.array([1.1,2.3,3.4])
for x in range(20):
n = np.append(n, [np.nan])
```
How Can I add "nan" to my numpy array 20 times without loop, only uses numpy's tools?
Thanks | ```
n = np.append(n, np.repeat(np.nan, 20))
```
[Edit]
Ok, it seems that use of `np.repeat` is slower than use of `np.zeros(20) + np.nan` like in [Mr Eâs answer](http://stackoverflow.com/a/19539488/1517918):
```
In [1]: timeit np.zeros(10000) + np.nan
100000 loops, best of 3: 16.1 µs per loop
In [2]: timeit np.re... |
Solving non-linear equations in python | 19,542,801 | 14 | 2013-10-23T13:17:54Z | 19,544,703 | 34 | 2013-10-23T14:35:21Z | [
"python",
"numpy",
"scipy",
"nonlinear-functions"
] | I have 4 non-linear equations with three unknowns `X`, `Y`, and `Z` that I want to solve for. The equations are of the form:
```
F(m) = X^2 + a(m)Y^2 + b(m)XYcosZ + c(m)XYsinZ
```
...where `a`, `b` and `c` are constants which are dependent on each value of `F` in the four equations.
What is the best way to go about ... | There are two ways to do this.
1. Use a non-linear solver
2. Linearize the problem and solve it in the least-squares sense
## Setup
So, as I understand your question, you know F, a, b, and c at 4 different points, and you want to invert for the model parameters X, Y, and Z. We have 3 unknowns and 4 observed data poi... |
Running Mercurial on Mavericks | 19,544,595 | 21 | 2013-10-23T14:30:17Z | 19,545,740 | 21 | 2013-10-23T15:17:24Z | [
"python",
"osx",
"python-2.7",
"mercurial",
"osx-mavericks"
] | Seems that Mercurial doesn't run on Mavericks (Python 3.) Anyone find a solution.
```
abort: couldn't find mercurial libraries in [
/Library/Python/2.7/site-packages/
/usr/local/bin
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip
/System/Library/Frameworks/Python.framework/... | I had a similar problem to this last night after upgrading to OX 10.9 Mavericks. **Note: I'm using homebrew**, I had tried
`brew install hg` and `brew update` but they didn't work, as everyone's systems are different I would recommend running
`brew doctor`
to see what your particular issue is, in my case I had the foll... |
Monkey patching a class in another module in Python | 19,545,982 | 29 | 2013-10-23T15:28:54Z | 19,546,103 | 21 | 2013-10-23T15:34:45Z | [
"python",
"class",
"unit-testing",
"monkeypatching"
] | I'm working with a module written by someone else. I'd like to monkey patch the `__init__` method of a class defined in the module. The examples I have found showing how to do this have all assumed I'd be calling the class myself (e.g. [Monkey-patch Python class](http://stackoverflow.com/questions/3765222/monkey-patch-... | Use [`mock`](https://pypi.python.org/pypi/mock) library.
```
import thirdpartymodule_a
import thirdpartymodule_b
import mock
def new_init(self):
self.a = 43
with mock.patch.object(thirdpartymodule_a.SomeClass, '__init__', new_init):
thirdpartymodule_b.dosomething() # -> print 43
thirdpartymodule_b.dosomethin... |
Monkey patching a class in another module in Python | 19,545,982 | 29 | 2013-10-23T15:28:54Z | 19,546,169 | 35 | 2013-10-23T15:37:42Z | [
"python",
"class",
"unit-testing",
"monkeypatching"
] | I'm working with a module written by someone else. I'd like to monkey patch the `__init__` method of a class defined in the module. The examples I have found showing how to do this have all assumed I'd be calling the class myself (e.g. [Monkey-patch Python class](http://stackoverflow.com/questions/3765222/monkey-patch-... | The following should work:
```
import thirdpartymodule_a
import thirdpartymodule_b
def new_init(self):
self.a = 43
thirdpartymodule_a.SomeClass.__init__ = new_init
thirdpartymodule_b.dosomething()
```
If you want the new init to call the old init replace the `new_init()` definition with the following:
```
old... |
Find the index of minimum values in given array in Python | 19,546,863 | 12 | 2013-10-23T16:09:36Z | 19,547,078 | 16 | 2013-10-23T16:21:16Z | [
"python",
"arrays",
"numpy"
] | I need to find the index of more than one minimum values that occur in an array. I am pretty known with `np.argmin` but it gives me the index of very first minimum value in a array. For example.
```
a = np.array([1,2,3,4,5,1,6,1])
print np.argmin(a)
```
This gives me 0, instead I am expecting, 0,5,7.
Thanks! | This should do the trick:
```
a = np.array([1,2,3,4,5,1,6,1])
print np.where(a == a.min())
```
argmin doesn't return a list like you expect it to in this case. |
Cannot install Lxml on Mac os x 10.9 | 19,548,011 | 213 | 2013-10-23T17:07:32Z | 19,549,645 | 24 | 2013-10-23T18:31:33Z | [
"python",
"xcode",
"osx",
"scrapy",
"lxml"
] | I want to install Lxml so I can then install Scrapy.
When I updated my Mac today it wouldn't let me reinstall lxml, I get the following error:
```
In file included from src/lxml/lxml.etree.c:314:
/private/tmp/pip_build_root/lxml/src/lxml/includes/etree_defs.h:9:10: fatal error: 'libxml/xmlversion.h' file not found
#i... | This has been bothering me as well for a while. I don't know the internals enough about python distutils etc, but the include path here is wrong. I made the following ugly hack to hold me over until the python lxml people can do the proper fix.
```
sudo ln -s /Applications/Xcode.app/Contents/Developer/Platforms/MacOS... |
Cannot install Lxml on Mac os x 10.9 | 19,548,011 | 213 | 2013-10-23T17:07:32Z | 19,550,278 | 90 | 2013-10-23T19:05:26Z | [
"python",
"xcode",
"osx",
"scrapy",
"lxml"
] | I want to install Lxml so I can then install Scrapy.
When I updated my Mac today it wouldn't let me reinstall lxml, I get the following error:
```
In file included from src/lxml/lxml.etree.c:314:
/private/tmp/pip_build_root/lxml/src/lxml/includes/etree_defs.h:9:10: fatal error: 'libxml/xmlversion.h' file not found
#i... | You may solve your problem by running this on the commandline:
```
STATIC_DEPS=true pip install lxml
```
It sure helped me.
Explanations on [docs](http://lxml.de/installation.html#using-lxml-with-python-libxml2) |
Cannot install Lxml on Mac os x 10.9 | 19,548,011 | 213 | 2013-10-23T17:07:32Z | 19,604,913 | 474 | 2013-10-26T09:10:16Z | [
"python",
"xcode",
"osx",
"scrapy",
"lxml"
] | I want to install Lxml so I can then install Scrapy.
When I updated my Mac today it wouldn't let me reinstall lxml, I get the following error:
```
In file included from src/lxml/lxml.etree.c:314:
/private/tmp/pip_build_root/lxml/src/lxml/includes/etree_defs.h:9:10: fatal error: 'libxml/xmlversion.h' file not found
#i... | You should install or upgrade the commandline tool for xcode.
Try this in a terminal:
```
xcode-select --install
``` |
Cannot install Lxml on Mac os x 10.9 | 19,548,011 | 213 | 2013-10-23T17:07:32Z | 22,418,820 | 11 | 2014-03-15T02:31:59Z | [
"python",
"xcode",
"osx",
"scrapy",
"lxml"
] | I want to install Lxml so I can then install Scrapy.
When I updated my Mac today it wouldn't let me reinstall lxml, I get the following error:
```
In file included from src/lxml/lxml.etree.c:314:
/private/tmp/pip_build_root/lxml/src/lxml/includes/etree_defs.h:9:10: fatal error: 'libxml/xmlversion.h' file not found
#i... | instalation instructions on <http://lxml.de/installation.html> explain:
> To speed up the build in test environments, e.g. on a continuous integration server, disable the C compiler optimisations by setting the CFLAGS environment variable:
```
CFLAGS="-O0" pip install lxml
``` |
Cannot install Lxml on Mac os x 10.9 | 19,548,011 | 213 | 2013-10-23T17:07:32Z | 22,791,119 | 11 | 2014-04-01T16:05:45Z | [
"python",
"xcode",
"osx",
"scrapy",
"lxml"
] | I want to install Lxml so I can then install Scrapy.
When I updated my Mac today it wouldn't let me reinstall lxml, I get the following error:
```
In file included from src/lxml/lxml.etree.c:314:
/private/tmp/pip_build_root/lxml/src/lxml/includes/etree_defs.h:9:10: fatal error: 'libxml/xmlversion.h' file not found
#i... | None of the above worked for me on 10.9.2, as compilation bails out with following error:
```
clang: error: unknown argument: '-mno-fused-madd'
```
Which actually lead to cleanest solution (see more details in [1]):
```
export CFLAGS=-Qunused-arguments
export CPPFLAGS=-Qunused-arguments
pip install lxml
```
or fol... |
Cannot install Lxml on Mac os x 10.9 | 19,548,011 | 213 | 2013-10-23T17:07:32Z | 23,176,666 | 19 | 2014-04-19T23:16:18Z | [
"python",
"xcode",
"osx",
"scrapy",
"lxml"
] | I want to install Lxml so I can then install Scrapy.
When I updated my Mac today it wouldn't let me reinstall lxml, I get the following error:
```
In file included from src/lxml/lxml.etree.c:314:
/private/tmp/pip_build_root/lxml/src/lxml/includes/etree_defs.h:9:10: fatal error: 'libxml/xmlversion.h' file not found
#i... | Installing globally... OS X 10.9.2
```
xcode-select --install
sudo easy_install pip
sudo CPATH=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/include/libxml2 CFLAGS=-Qunused-arguments CPPFLAGS=-Qunused-arguments pip install lxml
``` |
Cannot install Lxml on Mac os x 10.9 | 19,548,011 | 213 | 2013-10-23T17:07:32Z | 26,544,099 | 155 | 2014-10-24T08:23:57Z | [
"python",
"xcode",
"osx",
"scrapy",
"lxml"
] | I want to install Lxml so I can then install Scrapy.
When I updated my Mac today it wouldn't let me reinstall lxml, I get the following error:
```
In file included from src/lxml/lxml.etree.c:314:
/private/tmp/pip_build_root/lxml/src/lxml/includes/etree_defs.h:9:10: fatal error: 'libxml/xmlversion.h' file not found
#i... | I solved this issue on Yosemite by both installing and linking `libxml2` and `libxslt` through brew:
```
brew install libxml2
brew install libxslt
brew link libxml2 --force
brew link libxslt --force
```
If you have solved the problem using this method but it pops up again at a later time, you might need to run this *... |
Cannot install Lxml on Mac os x 10.9 | 19,548,011 | 213 | 2013-10-23T17:07:32Z | 26,831,538 | 47 | 2014-11-09T18:15:12Z | [
"python",
"xcode",
"osx",
"scrapy",
"lxml"
] | I want to install Lxml so I can then install Scrapy.
When I updated my Mac today it wouldn't let me reinstall lxml, I get the following error:
```
In file included from src/lxml/lxml.etree.c:314:
/private/tmp/pip_build_root/lxml/src/lxml/includes/etree_defs.h:9:10: fatal error: 'libxml/xmlversion.h' file not found
#i... | I tried most of the solutions above, but none of them worked for me. I'm running Yosemite 10.10, the only solution that worked for me was to type this in the terminal:
```
sudo CPATH=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/include/libxml2 CFLAGS=-Qunused-a... |
Cannot install Lxml on Mac os x 10.9 | 19,548,011 | 213 | 2013-10-23T17:07:32Z | 27,658,815 | 10 | 2014-12-26T15:18:59Z | [
"python",
"xcode",
"osx",
"scrapy",
"lxml"
] | I want to install Lxml so I can then install Scrapy.
When I updated my Mac today it wouldn't let me reinstall lxml, I get the following error:
```
In file included from src/lxml/lxml.etree.c:314:
/private/tmp/pip_build_root/lxml/src/lxml/includes/etree_defs.h:9:10: fatal error: 'libxml/xmlversion.h' file not found
#i... | ```
xcode-select --install
sudo easy_install pip
sudo pip install lxml
``` |
Can I force pip to reinstall the current version? | 19,548,957 | 123 | 2013-10-23T17:54:50Z | 19,549,035 | 166 | 2013-10-23T17:59:22Z | [
"python",
"pip",
"packages"
] | I've come across situations where a current version of a package seems not to be working and requires reinstallation. But `pip install -U` won't touch a package that is already up-to-date. I see how to force a reinstallation by first uninstalling (with `pip uninstall`) and then installing, but is there a way to simply ... | ```
--force-reinstall
```
When upgrading, reinstall all packages even if they are already up-to-date.
```
-I, --ignore-installed
```
Ignore the installed packages (reinstalling instead). |
Can I force pip to reinstall the current version? | 19,548,957 | 123 | 2013-10-23T17:54:50Z | 21,108,538 | 15 | 2014-01-14T08:04:09Z | [
"python",
"pip",
"packages"
] | I've come across situations where a current version of a package seems not to be working and requires reinstallation. But `pip install -U` won't touch a package that is already up-to-date. I see how to force a reinstallation by first uninstalling (with `pip uninstall`) and then installing, but is there a way to simply ... | ```
--force-reinstall
```
doesn't appear to force reinstall using python2.7 with pip-1.5
I've had to use
```
--no-deps --ignore-installed
``` |
Can I force pip to reinstall the current version? | 19,548,957 | 123 | 2013-10-23T17:54:50Z | 27,254,355 | 61 | 2014-12-02T16:34:48Z | [
"python",
"pip",
"packages"
] | I've come across situations where a current version of a package seems not to be working and requires reinstallation. But `pip install -U` won't touch a package that is already up-to-date. I see how to force a reinstallation by first uninstalling (with `pip uninstall`) and then installing, but is there a way to simply ... | You might want to have all three options: `--upgrade` and `--force-reinstall` ensures reinstallation, while `--no-deps` avoids reinstalling dependencies.
```
$ sudo pip install --upgrade --no-deps --force-reinstall <packagename>
```
Otherwise you might run into the problem that pip starts to recompile Numpy or other ... |
find where a numpy array is equal to any value of a list of values | 19,549,634 | 10 | 2013-10-23T18:30:59Z | 19,549,750 | 12 | 2013-10-23T18:37:22Z | [
"python",
"arrays",
"numpy"
] | I have an array of integers and want to find where that array is equal to any value in a list of multiple values. This can easily be done by treating each value individually, or by using multiple "or" statements in a loop, but I feel like there must be a better/faster way to do it. I'm actually dealing with arrays of s... | The function [numpy.in1d](http://docs.scipy.org/doc/numpy/reference/generated/numpy.in1d.html) seems to do what you want. The only problems is that it only works on 1d arrays, so you should use it like this:
```
In [9]: np.in1d(fake, [0,2,6,8]).reshape(fake.shape)
Out[9]:
array([[ True, False, True],
[False, ... |
Terminal issue with virtualenvwrapper after Mavericks Upgrade | 19,549,824 | 28 | 2013-10-23T18:42:13Z | 19,550,535 | 53 | 2013-10-23T19:18:54Z | [
"python",
"terminal",
"virtualenvwrapper",
"osx-mavericks"
] | After upgrading to OSX Mavericks, I am getting this message in the terminal:
```
/usr/bin/python: No module named virtualenvwrapper
virtualenvwrapper.sh: There was a problem running the initialization hooks.
If Python could not import the module virtualenvwrapper.hook_loader,
check that virtualenv has been installed... | Try reinstalling pip and then reinstalling virtualenvwrapper (I had to go through these steps after upgrading to Mavericks):
```
$ sudo easy_install pip
$ sudo pip install --upgrade virtualenvwrapper
``` |
Why is "int + string" possible in statically-typed C# but not in dynamically-typed Python? | 19,552,571 | 10 | 2013-10-23T21:23:28Z | 19,552,612 | 9 | 2013-10-23T21:26:19Z | [
"c#",
"python",
"types"
] | While studying C# I found it really strange, that dynamically typed Python will rise an error in the following code:
```
i = 5
print i + " "
```
whereas statically typed C# will normally proceed the similar code:
```
int i = 5;
Console.Write(i + " ");
```
I would expect other way around (in python I would be able t... | This isnât really the area of static vs. dynamic typing. Rather itâs *strong* vs. *weak* typing (at least according to some commonly used terminology which Wikipedia also happens to be using in its characterisation of programming languages). And both C# and Python are strongly typed (by that definition).
All these... |
Why is "int + string" possible in statically-typed C# but not in dynamically-typed Python? | 19,552,571 | 10 | 2013-10-23T21:23:28Z | 19,552,993 | 9 | 2013-10-23T21:52:53Z | [
"c#",
"python",
"types"
] | While studying C# I found it really strange, that dynamically typed Python will rise an error in the following code:
```
i = 5
print i + " "
```
whereas statically typed C# will normally proceed the similar code:
```
int i = 5;
Console.Write(i + " ");
```
I would expect other way around (in python I would be able t... | This isn't really a static/dynamic question but rather a matter of language design philosophy.
In Python, `+` is defined to be addition for numbers and concatenation for strings. This is perfectly reasonable behavior if you have even a little programming experience.
But when you have one of each, what happens? Does i... |
Why is "int + string" possible in statically-typed C# but not in dynamically-typed Python? | 19,552,571 | 10 | 2013-10-23T21:23:28Z | 19,553,933 | 22 | 2013-10-23T23:04:27Z | [
"c#",
"python",
"types"
] | While studying C# I found it really strange, that dynamically typed Python will rise an error in the following code:
```
i = 5
print i + " "
```
whereas statically typed C# will normally proceed the similar code:
```
int i = 5;
Console.Write(i + " ");
```
I would expect other way around (in python I would be able t... | You are right that something is odd here. What is odd is that `+` means string concatenation in either language! Whether `+` can concatenate an int onto a string or not is a small point compared with the oddity that is `+` meaning "concatenate" at all.
I do not know which language first allowed `+` to be used to mean ... |
BioPython: How to convert the amino acid alphabet to | 19,552,897 | 4 | 2013-10-23T21:45:45Z | 19,553,118 | 7 | 2013-10-23T22:01:20Z | [
"python",
"bioinformatics",
"biopython"
] | When discussing how to import sequence data using Bio.SeqIO.parse(), the BioPython cookbook states that:
> There is an optional argument alphabet to specify the alphabet to be used. This is useful for file formats like FASTA where otherwise Bio.SeqIO will default to a generic alphabet.
How do I add this optional argu... | Like this:
```
# Import required alphabet
from Bio.Alphabet import IUPAC
# Pass imported alphabet as an argument for `SeqIO.parse`:
records = list(SeqIO.parse(handle, 'fasta', IUPAC.extended_protein))
``` |
Python Pandas Series of Datetimes to Seconds Since the Epoch | 19,553,464 | 8 | 2013-10-23T22:26:26Z | 19,554,166 | 10 | 2013-10-23T23:25:31Z | [
"python",
"datetime",
"pandas"
] | Following in the spirit of [this answer](http://stackoverflow.com/questions/7852855/how-to-convert-a-python-datetime-object-to-seconds), I attempted the following to convert a DataFrame column of datetimes to a column of seconds since the epoch.
```
df['date'] = (df['date']+datetime.timedelta(hours=2)-datetime.datetim... | Update:
In 0.15.0 `Timedeltas` became a full-fledged dtype.
So this becomes possible (as well as the methods below)
```
In [45]: s = Series(pd.timedelta_range('1 day',freq='1S',periods=5))
In [46]: s.dt.components
Out[46]:
days hours minutes seconds milliseconds microseconds nanos... |
dict's __repr__() in python2 and python3 | 19,554,339 | 4 | 2013-10-23T23:41:52Z | 19,554,383 | 8 | 2013-10-23T23:45:40Z | [
"python",
"testing",
"python-2.7",
"python-3.x",
"repr"
] | I'm porting a python library from python 2 only to python 2 and 3 in one codebase (2.6, 2.7 and 3.3+). The main problem left is that a lot of tests use something like this:
```
def test(self):
example = {u'foo': u'bar'}
self.assertEqual(str(example), "{u'foo': u'bar'}")
```
which works in python 2, but raises an ex... | Get rid of those tests; they are next to useless:
* This tests if the Python implementation of `dict.__repr__` is working. Python itself already tests for this; focus on the project codebase instead. If Python fails to render a dictionary representation correctly it's not your project's job to fix that.
* Python dicti... |
pymongo: Advantage of using MongoReplicaSetClient? | 19,554,764 | 6 | 2013-10-24T00:26:06Z | 19,795,139 | 8 | 2013-11-05T17:30:01Z | [
"python",
"mongodb",
"pymongo",
"replicaset"
] | It seems that both [MongoClient](http://api.mongodb.org/python/current/api/pymongo/mongo_client.html) and [MongoReplicaSetClient](http://api.mongodb.org/python/current/api/pymongo/mongo_replica_set_client.html) can connect to mongo replica sets. In fact, their documentation pages are nearly identical - same options, sa... | This is was a confusing API choice that we regret in PyMongo 2.x. We will merge all the client classes into MongoClient in PyMongo 3, in April 2015:
<http://emptysqua.re/blog/good-idea-at-the-time-pymongo-mongoreplicasetclient/>
Meanwhile:
1. Use MongoReplicaSetClient when you plan to connect to a whole replica set.... |
Python.framework is missing from OS X 10.9 SDK. Why? Also: Workaround? | 19,555,395 | 14 | 2013-10-24T01:39:26Z | 19,758,680 | 16 | 2013-11-03T21:59:23Z | [
"python",
"xcode",
"osx",
"sdk",
"osx-mavericks"
] | # **System**:
* OS X Mavericks 10.9 13A603
* Xcode Version 5.0.1 (5A2053)
# **Problem:**
**Python.framework** seems to be missing from Xcode's 10.9 SDK.
Python.framework exists in the Xcode 10.8 SDK:
```
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.8.sdk/System/Libra... | There is an official Apple support page on the subject:
[Changes To Embedding Python Using Xcode 5.0](https://developer.apple.com/library/ios/technotes/tn2328/_index.html)
Basically, what they say is that the method for integrating with Python with the SDK `Python.framework` is deprecated, and the standard \*nix meth... |
Change a string of integers separated by spaces to a list of int | 19,555,472 | 9 | 2013-10-24T01:48:55Z | 19,555,487 | 17 | 2013-10-24T01:50:34Z | [
"python",
"string",
"list",
"int"
] | How do i make something like
```
x = '1 2 3 45 87 65 6 8'
>>> foo(x)
[1,2,3,45,87,65,6,8]
```
I'm completely stuck, if i do it by index, then the numbers with more than 1 digit will be broken down. Help please. | You can use a list comprehension in combination with the [.split()](http://docs.python.org/2/library/string.html) method:
```
x = [int(i) for i in x.split()]
```
Alternatively you can use `map` aswell:
```
x = map(int, x.split())
```
This will create a `list` of `int`'s if you want integers.
or just use `.split()`... |
Saving plots (AxesSubPlot) generated from python pandas with matplotlib's savefig | 19,555,525 | 17 | 2013-10-24T01:55:50Z | 24,674,675 | 23 | 2014-07-10T10:51:42Z | [
"python",
"matplotlib",
"pandas"
] | I'm using pandas to generate a plot from a dataframe, which I would like to save to a file:
```
dtf = pd.DataFrame.from_records(d,columns=h)
fig = plt.figure()
ax = dtf2.plot()
ax = fig.add_subplot(ax)
fig.savefig('~/Documents/output.png')
```
It seems like the last line, using matplotlib's savefig, should do the tri... | The gcf method is depricated in V 0.14, The below code works for me:
```
plot = dtf.plot()
fig = plot.get_figure()
fig.savefig("output.png")
``` |
Why isn't my database working in this Python/Django app? | 19,555,796 | 4 | 2013-10-24T02:24:03Z | 19,555,819 | 7 | 2013-10-24T02:26:42Z | [
"python",
"mysql",
"django",
"shell"
] | I'm trying to complete the Django tutorial, and everything in my code is working until I try to save and print the instance variables of my object.
Here's the code for my class (this is in the models.py file of my app):
```
from django.db import models
class Question(models.Model):
question_text = models.CharFie... | Model.save is a method
You should run:
```
q.save()
```
Typing q.save in the console only prints the string representation of the method.
Because you never saved the model object to the database, the model object does not have a id. |
Get SQL query count during a Django shell session | 19,556,139 | 10 | 2013-10-24T03:02:12Z | 19,556,140 | 16 | 2013-10-24T03:02:12Z | [
"python",
"sql",
"django",
"shell"
] | Is there a way to print the number of raw SQL queries performed by the Django ORM during a Django shell session?
This sort of information is already provided by the Django debug toolbar (e.g, `5 QUERIES in 5.83MS` but it's not obvious how to get it from the shell. | You can use `connection.queries`:
```
>>> from django.conf import settings
>>> settings.DEBUG = True
>>> from django.db import connection
>>> Model.objects.count()
>>> print len(connection.queries)
1
``` |
Sort an array of tuples by product in python | 19,556,940 | 2 | 2013-10-24T04:28:49Z | 19,556,991 | 10 | 2013-10-24T04:33:05Z | [
"python",
"arrays",
"sorting"
] | I have an array of 3-tuples and I want to sort them in order of decreasing product of the elements of each tuple in Python. So, for example, given the array
> [(3,2,3), (2,2,2), (6,4,1)]
since 3\*2\*3 = 18, 2\*2\*2 = 8, 6\*4\*1 = 24, the final result would be
> [(6,4,1), (3,2,3), (2,2,2)]
I know how to sort by, for... | Use the `key` argument of [`sorted`](http://docs.python.org/2.7/library/functions.html#sorted)/[`list.sort`](http://docs.python.org/2.7/library/stdtypes.html#typesseq-mutable) to specify a function for computing the product, and set the `reverse` argument to `True` to make the results descending rather than ascending, ... |
requirements.txt depending on python version | 19,559,247 | 17 | 2013-10-24T07:09:41Z | 19,559,476 | 7 | 2013-10-24T07:22:01Z | [
"python",
"pip"
] | I'm trying to port a python2 package to python3 (not my own) using six so that it's compatible with both. However one of the packages listed in requirements.txt is now included in the python3 stdlib and the pypi version doesn't work in python3 so I want to conditionally exclude it. Doing this in setup.py is easy, I can... | You can create multiple requirements files, put those common packages in a common file, and include them in another pip requirements file with `-r file_path`
```
requirements/
base.txt
python2.txt
python3.txt
```
python2.txt:
```
-r base.txt
Django==1.4 #python2 only packages
```
python3.txt:
```
-r base.txt... |
requirements.txt depending on python version | 19,559,247 | 17 | 2013-10-24T07:09:41Z | 33,451,105 | 22 | 2015-10-31T11:39:26Z | [
"python",
"pip"
] | I'm trying to port a python2 package to python3 (not my own) using six so that it's compatible with both. However one of the packages listed in requirements.txt is now included in the python3 stdlib and the pypi version doesn't work in python3 so I want to conditionally exclude it. Doing this in setup.py is easy, I can... | You can use the [environment markers](https://www.python.org/dev/peps/pep-0496/) to achieve this in `requirements.txt` since `pip 6.0`:
```
SomeProject==5.4; python_version < '2.7'
SomeProject; sys.platform == 'win32'
```
It is supported by setuptools too by declaring extra requirements in `setup.py`:
```
setup(
... |
How to concatenate element-wise two lists in Python? | 19,560,044 | 3 | 2013-10-24T07:51:10Z | 19,560,097 | 9 | 2013-10-24T07:54:15Z | [
"python",
"list"
] | I have two lists and I want to concatenate them element-wise. One of the list is subjected to string-formatting before concatenation.
For example, `a = [0, 1, 5, 6, 10, 11] and b = ['asp1', 'asp1', 'asp1', 'asp1', 'asp2', 'asp2']`
In this case, `a` is subjected to string-formatting. That is, new `a` or `aa` should be... | Use [**`zip`**](http://docs.python.org/2/library/functions.html#zip):
```
>>> ["{}{:02}".format(b_, a_) for a_, b_ in zip(a, b)]
['asp100', 'asp101', 'asp105', 'asp106', 'asp210', 'asp211']
``` |
How to read python bytecode? | 19,560,057 | 9 | 2013-10-24T07:51:40Z | 19,560,286 | 20 | 2013-10-24T08:03:16Z | [
"python",
"python-2.7",
"bytecode"
] | I am having a lot of difficulty understanding Python's bytecode and its `dis` module.
```
import dis
def func():
x = 1
dis.dis(func)
```
The above code when typed in the interpreter produces the following output:
```
0 LOAD_CONST 1(1)
3 STORE_FAST 0(x)
6 LOAD_CONST ... | The numbers before the bytecodes are offsets into the original binary bytecodes:
```
>>> func.__code__.co_code
'd\x01\x00}\x00\x00d\x00\x00S'
```
Some bytecodes come with additional information (arguments) that influence how each bytecode works, the offset tells you at what position in the bytestream the bytecode was... |
Faster way to remove stop words in Python | 19,560,498 | 16 | 2013-10-24T08:13:45Z | 19,560,949 | 42 | 2013-10-24T08:35:43Z | [
"python",
"regex",
"stop-words"
] | I am trying to remove stopwords from a string of text:
```
from nltk.corpus import stopwords
text = 'hello bye the the hi'
text = ' '.join([word for word in text.split() if word not in (stopwords.words('english'))])
```
I am processing 6 mil of such strings so speed is important. Profiling my code, the slowest part i... | Try caching the stopwords object, as shown below. Constructing this each time you call the function seems to be the bottleneck.
```
from nltk.corpus import stopwords
cachedStopWords = stopwords.words("english")
def testFuncOld():
text = 'hello bye the the hi'
text = ' '.join([word for wor... |
duplicate output in simple python logging configuration | 19,561,058 | 10 | 2013-10-24T08:42:01Z | 19,561,320 | 18 | 2013-10-24T08:55:26Z | [
"python",
"logging"
] | I'm setting up python logging as follows:
```
def setup_logging():
loggers = (logging.getLogger("amcat"), logging.getLogger("scrapers"),logging.getLogger(__name__))
filename = "somefile.txt"
sys.stderr = open(filename, 'a')
handlers = (logging.StreamHandler(sys.stdout),logging.FileHandler(filename))
... | Basically, when one of your child logger displays a message, it goes backwards in the hierarchy, and the parents are also logging the same thing.
To cancel that behavior, you can add this:
```
logger.propagate = False
```
When it hits the child, it won't hit the parent afterwards.
Here is some [documentation](http:... |
Simulating linux terminal in browser | 19,561,188 | 15 | 2013-10-24T08:48:26Z | 20,809,785 | 19 | 2013-12-28T00:44:30Z | [
"javascript",
"python",
"linux",
"node.js",
"simulator"
] | I have read about Fabrice Bellard's linux simulation in browser.
[How does Linux emulator in Javascript by Fabrice Bellard work?](http://stackoverflow.com/questions/6030407/how-does-linux-emulator-in-javascript-by-fabrice-bellard-work)
Today I stumbled upon this site, where they are simulating full linux terminal in ... | The full linux is <http://docker.io>, the rest is <https://github.com/Runnable/dockworker>
We're not simulating the terminal but as Kyle says, replicating the terminal over websockets (with an ajax fallback).
In the browser we're using <https://github.com/chjj/term.js> which was derived from Fabrice Bellard's emulato... |
Ubuntu upstart will hang on start/stop/etc | 19,561,587 | 3 | 2013-10-24T09:08:23Z | 21,274,065 | 9 | 2014-01-22T04:18:21Z | [
"python",
"ubuntu",
"upstart",
"python-daemon",
"start-stop-daemon"
] | I've got a several services on Ubuntu which will start using 'upstart'. They are working as requested, but when I use 'stop/start/restart {myservice}' it will hang (but WILL do as requested).
I understand it has something to do with forking.
My services are python scripts, which will create new threads on startup. On... | I think you are confusing creating threads in python with linux forking. Python will manage its own threads while it is running (assuming you are using regular constructs), from upstarts view it is only monitoring the running python process that you have started - python should be set up to manage its own children.
##... |
What is the difference between the widgets of tkinter and tkinter.ttk in Python? | 19,561,727 | 8 | 2013-10-24T09:14:10Z | 19,564,114 | 14 | 2013-10-24T11:01:50Z | [
"python",
"tkinter",
"ttk"
] | The main `tkinter` module and its submodule `ttk` in Python 3 appear to contain identical widgets (i.e. `Buttons`, `CheckButtons`, etc.).
So, when creating a button, one has the freedom to either use a `tkinter.Button` widget or a `tkinter.ttk.Button`.
Do you know what is the difference between them? Why would you ch... | The widgets in `tkinter` are *highly and easily configurable*. You have almost complete control over how they look - border widths, fonts, etc.
`ttk` widgets are *themed*: they use styles to define how they look, so it takes a bit more work if you want a non-standard button. `ttk` widgets are also a little *under-docu... |
Chi Square Test of Independence in Python | 19,563,126 | 5 | 2013-10-24T10:15:25Z | 19,563,663 | 7 | 2013-10-24T10:40:55Z | [
"python",
"numpy",
"statistics",
"scipy"
] | Under Ubuntu 10.04.4, using Python 2.6.5, NumPy and SciPy, is it possible to do a chi square test of independence? In `R`, this is [achieved](http://ww2.coastal.edu/kingw/statistics/R-tutorials/independ.html) with the following:
```
> row1 = c(91,90,51)
> row2 = c(150,200,155)
> row3 = c(109,198,172)
> data.table = rb... | ```
import scipy
row1 = [91,90,51]
row2 = [150,200,155]
row3 = [109,198,172]
data=[row1,row2,row3]
chi2_contingency(data)
scipy.stats.chi2_contingency(data)
```
Output:
```
(25.085973274234959, 4.8346447416999636e-05, 4, array([[ 66.77631579, 93.10526316, 72.11842105],
[ 145.35361842, 202.66447368, 156.... |
Folder Structure for Python Django-REST-framework and Angularjs | 19,566,555 | 15 | 2013-10-24T12:55:32Z | 22,209,744 | 13 | 2014-03-05T21:30:04Z | [
"python",
"django",
"mongodb",
"rest",
"angularjs"
] | I am going to start one project in which i am going to use pyhon django with rest framework, AngularJs with restangular and Mongodb. Should I just start writing my client side application with angularjs and then concern about what should be folder structure such that i can hook my back-end. Or I should first think abou... | Here's how I approached this. Others have advocated completely decoupling your django and angularjs applications but this might work for you.
You have two apps, Account App and Other App. You want to create modular angular applications in both that can be "plugged" into another django project (with minimal modificatio... |
Why django uses a comma as decimal separator | 19,566,673 | 6 | 2013-10-24T13:00:19Z | 19,567,290 | 7 | 2013-10-24T13:26:10Z | [
"python",
"django",
"decimal"
] | I am using python 2.6 and django 1.27
my model
```
class Plan(models.Model):
price = models.DecimalField(max_digits=5, decimal_places=2,default=0)
.....
```
in my template i have
```
{{plan.price}}
```
My problem is that on my local machine i get dot used as separator for example '2.54'
While on my pro... | First of all, I assume you have L10N and I18N turned on in your `settings.py`, because that's the default. The difference you see is likely because you are accessing the website from two different computers with two different locales. Django tries to format things for the locale reported by the browser.
However, you c... |
Return a requests.Response object from Flask | 19,568,950 | 15 | 2013-10-24T14:37:28Z | 19,569,090 | 23 | 2013-10-24T14:43:09Z | [
"python",
"proxy",
"flask",
"python-requests"
] | I'm trying to build a simple proxy using Flask and requests. The code is as follows:
```
@app.route('/es/<string:index>/<string:type>/<string:id>',
methods=['GET', 'POST', 'PUT']):
def es(index, type, id):
elasticsearch = find_out_where_elasticsearch_lives()
# also handle some authentication
url... | Ok, found it:
> If a tuple is returned the items in the tuple can provide extra information. Such tuples have to be in the form (response, status, headers) where at least one item has to be in the tuple. The status value will override the status code and headers can be a list or dictionary of additional header values.... |
Using forever.js with Python | 19,571,282 | 8 | 2013-10-24T16:16:34Z | 19,571,283 | 14 | 2013-10-24T16:16:34Z | [
"python",
"forever"
] | Two questions:
* Is there a Python equivalent to forever.js to run a Python process in the background without requiring sudo?
* Is it possible to use forever.js with Python? How about with a virtualenv? | It is easy to use Python with forever.js:
```
forever start -c python python_script.py
```
To use it with virtualenv is a little bit more complicated, I did it using a bash script (call it `python_virtualenv`):
```
#!/bin/bash
# Script to run a Python file using the local virtualenv
source bin/activate
bin/python $@... |
parsing json fields in python | 19,573,747 | 5 | 2013-10-24T18:27:52Z | 19,573,810 | 10 | 2013-10-24T18:31:34Z | [
"python",
"django",
"simplejson"
] | Is there a good tutorial on parsing json attributes in python? I would like to be able to parse the true value for "ok" field. As well as the index named "client\_ind\_1". I don't understand the python document coverage on this topic. If someone could explain or point me to a better resource, it would be awesome.
My j... | ```
import json
a = """{
"ok": true,
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"indices": {
"client_ind_2": {
"index": {
"primary_size": "2.5mb",
"primary_size_in_bytes": 2710326,
"size": "2.5mb"... |
Open images from a folder one by one using python? | 19,573,809 | 7 | 2013-10-24T18:31:31Z | 19,575,539 | 9 | 2013-10-24T20:04:09Z | [
"python",
"python-imaging-library"
] | Hi all I need to open images from a folder one by one do some processing on images and save them back to other folder. I am doing this using following sample code.
```
path1 = path of folder of images
path2 = path of folder to save images
listing = os.listdir(path1)
for file in listing:
im = Image.ope... | Sounds like you want multithreading. Here's a quick rev that'll do that.
```
from multiprocessing import Pool
import os
path1 = "some/path"
path2 = "some/other/path"
listing = os.listdir(path1)
p = Pool(5) # process 5 images simultaneously
def process_fpath(path):
im = Image.open(path1 + path)
im.r... |
Is it possible to start an IPython session via ssh and log back in later? | 19,574,210 | 4 | 2013-10-24T18:53:55Z | 19,574,232 | 8 | 2013-10-24T18:55:10Z | [
"python",
"shell",
"ssh",
"ipython"
] | I work on a machine per ssh where I run `ipython` for interactive work. Can I start a long-running Python function from IPython, sever the ssh connection and log back in later into the IPython session to observe the result? | Yes. Use `screen`, `tmux` (superior), or similar software. Both use the concept of sessions that you attach to and detach from.
With `tmux`:
1. Run `tmux` and then `ipython`.
2. When you're finished, `<Ctrl+b> d` to detach. You're back in the normal shell.
3. When you come back, `tmux attach` will take you back to `i... |
How to store a numpy arrays in a column of a Pandas dataframe? | 19,574,258 | 5 | 2013-10-24T18:56:30Z | 19,574,569 | 7 | 2013-10-24T19:12:18Z | [
"python",
"python-2.7",
"numpy",
"pandas"
] | Is it possible to store arbitrary `numpy` arrays as the values of a *single* column in a dataframe of `Pandas`?
The arrays are all 2-dimensional, and I intend to use them to calculate values for other columns in the same dataframe.
To provide some context of what I'm trying to do here:
Each array is an adjacency mat... | Store them as elements as you would do for any other data:
```
import numpy as np
import pandas as pd
a = np.arange(10).reshape(2,5)
b = np.arange(10, 20).reshape(2,5)
pd.DataFrame({'foo':[42,51], 'arr':[a,b]})
Out[10]:
arr foo
0 [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9... |
Flask hit decorator before before_request signal fires | 19,574,694 | 5 | 2013-10-24T19:19:08Z | 19,575,396 | 8 | 2013-10-24T19:57:30Z | [
"python",
"flask",
"decorator"
] | I'm using Flask and using the before\_request decorator to send information about
requests to an analytics system. I'm now trying to create a decorator that would
prevent sending these events on a few routes.
The problem I'm running into is getting my decorator to get called before the before\_request
signal gets fire... | You can use the decorator to simply put an attribute on the function (in my example below, I'm using `_exclude_from_analytics` as the attribute). I find the view function using a combination of [request.endpoint](http://flask.pocoo.org/docs/api/#flask.Request.endpoint) and [app.view\_functions](http://flask.pocoo.org/d... |
Guessing Game Bug? | 19,574,998 | 3 | 2013-10-24T19:35:29Z | 19,575,033 | 7 | 2013-10-24T19:36:55Z | [
"python"
] | I have the following code written in Python as a project. I am 14 years old and have taken Computer Science as a GCSE. I am quite new to it, so do not know how to fix this bug. When I type in my first guess, e.g '5', it will say Too High. Then once the game is complete, it will say the answer is 7. It is a bug that I h... | You are reselecting a random number each time you make a guess. Instead I believe you would like to have the program pick a number first, then enter your while loop.
```
randomNumber = (random.randint(1,10))
while numberofGuesses < 3:
numberofGuesses = numberofGuesses +1
userInput = 0
userInput = in... |
python list from for loop into one list | 19,575,199 | 2 | 2013-10-24T19:46:40Z | 19,575,273 | 9 | 2013-10-24T19:50:52Z | [
"python",
"list",
"for-loop"
] | Python list in for loop, how do I have all in one list
```
import os
dir="/tmp/logvol/logs/fil/sap/archive/"
n=os.listdir(dir)
#print n
for x in n:
#print x
l = [];
l.append(os.path.join(dir,x))
print l
```
output:
```
['/tmp/logvol/logs/fil/sap/archive/m.log']
['/tmp/logvol/logs/fil/sap/archive/k.log']
['/tmp/... | Another way of doing it is with list comprehension.
```
l = [os.path.join(dir,x) for x in n]
``` |
How to write List of lists in csv file in python | 19,575,456 | 3 | 2013-10-24T19:59:56Z | 19,575,497 | 7 | 2013-10-24T20:02:07Z | [
"python",
"csv",
"python-3.x"
] | I have a list of lists and I want to write it in csv file
Example list:
```
data=[['serial', 'name', 'subject'],['1', 'atul','tpa'],['2', 'carl','CN'].......]
```
data[0] should be column names
everything else is row wise data
Please suggest me a way to do this. | This is trivial with the [`csv` module](http://docs.python.org/3/library/csv.html):
```
with open('output.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerows(data)
```
You already have the header in `data` as the first row; you can write all rows in one go with the `writer.writero... |
How to change python from UCS2 to UCS4 | 19,575,727 | 7 | 2013-10-24T20:13:21Z | 19,575,808 | 15 | 2013-10-24T20:17:44Z | [
"python",
"unicode",
"compilation",
"ucs"
] | I have a Python2.7 with UCS2 build installed on Ubuntu 12.10. I just want to recompile python with UCS4 or enable UCS4. How should I do this? | Use:
```
./configure --enable-unicode=ucs4
```
to configure the source to build with UCS4 support.
From the `./configure --help` output:
```
--enable-unicode[=ucs[24]]
Enable Unicode strings (default is ucs2)
``` |
Python programming beginner difficulties | 19,576,658 | 5 | 2013-10-24T21:06:55Z | 19,576,691 | 17 | 2013-10-24T21:09:00Z | [
"python",
"list",
"function",
"variables",
"return"
] | I am trying to write a program in Python, but I am stuck in this piece of code:
```
def function():
a=[3,4,5,2,4]
b=1
c=0
for x in range(5):
if a[x-1]>b:
c=c+1
return c
print(function())
```
It gives me value 1 instead of 5. Actually the function I am trying to write is... | Your `return` statements are incorrectly indented. You want to return **after** the loop ends, not **inside** the loop.
```
def function():
a = [3, 4, 5, 2, 4]
b = 1
c = 0
for x in range(5):
if a[x-1] > b:
c = c + 1
return c
```
Also, a couple of optimizations to the code:
`... |
Celery Worker Error: ImportError no module named celery | 19,577,172 | 17 | 2013-10-24T21:37:29Z | 21,066,694 | 20 | 2014-01-11T19:13:51Z | [
"python",
"flask",
"celery",
"celery-task"
] | I am getting an import error when I try to start my celery worker. I am not sure what the issue is. Any help would be highly appreciated.
My project:
```
email/__init__.py
/celery.py
```
I try to run the application by calling :
```
celery worker --app=email
```
I have followed all the steps here - <http://doc... | The problem is that you're saying "*hey bro I heard you liked celery have some celery*".
But really you should be saying, "*hey bro I heard you installed celery, lets make a file named something really similar so we don't confuse the hell out of our environment*".
Rename your `email/celery.py` file to `email/celery_a... |
Celery Worker Error: ImportError no module named celery | 19,577,172 | 17 | 2013-10-24T21:37:29Z | 25,316,153 | 14 | 2014-08-14T19:31:37Z | [
"python",
"flask",
"celery",
"celery-task"
] | I am getting an import error when I try to start my celery worker. I am not sure what the issue is. Any help would be highly appreciated.
My project:
```
email/__init__.py
/celery.py
```
I try to run the application by calling :
```
celery worker --app=email
```
I have followed all the steps here - <http://doc... | I was actually having a similar issue, assuming you were following the [Next Steps tutorial](http://docs.celeryproject.org/en/latest/getting-started/next-steps.html#next-steps) and all I had to do to resolve the issue was run the worker from the directory above **proj**, that is, assuming you're currently in the **proj... |
Writing an infinite sum (of a function that has an integral) in Python | 19,577,457 | 4 | 2013-10-24T21:56:44Z | 19,593,210 | 7 | 2013-10-25T14:55:36Z | [
"python",
"numpy",
"sum",
"infinite"
] | I am required to show that:

The annoying thing is that c\_i is equal to the integral of the function G. Here is my attempt.
```
import numpy as np
from scipy.integrate import quad
def G(x,n):
... | This problem has much pedagogic value.
As @alko points out, this problem can be solved analytically. If the intention is to prove that the sum is equal to one then it *should* be done analytically.
Perhaps, this is just a simpler version of something that needs to be done and the actual problem is not solvable analyt... |
Posting Data on Flask via form is giving 400 Bad Request | 19,578,613 | 4 | 2013-10-24T23:35:14Z | 19,578,663 | 12 | 2013-10-24T23:40:40Z | [
"javascript",
"python",
"html",
"http",
"flask"
] | I am trying to post data via my front end and the flask app is throwing 400 bad request. However If I am doing the same using Curl call it seems to work fine. I dont know what I am missing in the form.
The following is my form code
```
<script>
function sub() {
console.log('sub function');
$("#fquery").submit... | Ah, I think I see it: You only set the `id` but not the `name` for the `input` element. Yet the `name` is used in the form data that is sent to the server. This causes a `KeyError` at `request.form['query']` which causes the 400 error. |
Crawling on uncerficated website | 19,578,688 | 2 | 2013-10-24T23:44:09Z | 19,601,182 | 10 | 2013-10-25T23:55:59Z | [
"python",
"scrapy"
] | I am both new to Python and Scrapy, but I am trying to get some data from a website that has an untrusted certificate, and I think this is why I can't crawl it, although maybe I just did the spider wrongly
Here is the error log I get when I try to crawl
```
2013-10-24 21:19:08-0200 [scrapy] INFO: Scrapy 0.18.4 starte... | **UPDATE**: This workaround is for Scrapy<1.1. Newer version have a setting to change the tls method, see <http://doc.scrapy.org/en/1.1/topics/settings.html?highlight=context#downloader-client-tls-method>
My answer from the scrapy-users list:
Sometimes the openssl's negotiation metho don't get along with the server. ... |
inverting image in Python with OpenCV | 19,580,102 | 9 | 2013-10-25T02:25:45Z | 19,712,018 | 16 | 2013-10-31T16:35:50Z | [
"python",
"arrays",
"opencv",
"numpy",
"image-processing"
] | I want to load a color image, convert it to grayscale, and then invert the data in the file.
What I need: to iterate over the array in OpenCV and change every single value with this formula (it might be wrong but it seems reasonable for me):
```
img[x,y] = abs(img[x,y] - 255)
```
but I don't understand why doesn't i... | You almost did it. You were tricked by the fact that `abs(imagem-255)` will give a wrong result since your `dtype` is an unsigned integer. You have to do `(255-imagem)` in order to keep the integers unsigned:
```
def inverte(imagem, name):
imagem = (255-imagem)
cv2.imwrite(name, imagem)
``` |
Hashing (hiding) strings in Python | 19,580,412 | 12 | 2013-10-25T03:06:53Z | 19,580,599 | 30 | 2013-10-25T03:29:41Z | [
"python",
"string",
"encryption",
"hash"
] | What I need is to hash a string. It doesn't have to be secure because it's just going to be a hidden phrase in the text file (it just doesn't have to be recognizable for a human-eye).
It should not be just a random string because when the users types the string I would like to hash it and compare it with an already ha... | First off, let me say that you can't guarantee unique results. If you wanted unique results for all the strings in the universe, you're better off storing the string itself (or a compressed version).
More on that in a second. Let's get some hashes first.
# hashlib way
You can use any of the main cryptographic hashes... |
Python set Union and set Intersection operate differently? | 19,580,944 | 35 | 2013-10-25T04:09:08Z | 19,580,972 | 57 | 2013-10-25T04:12:15Z | [
"python",
"set",
"union",
"intersection"
] | I'm doing some set operations in Python, and I noticed something odd..
```
>> set([1,2,3]) | set([2,3,4])
set([1, 2, 3, 4])
>> set().union(*[[1,2,3], [2,3,4]])
set([1, 2, 3, 4])
```
That's good, expected behaviour - but with intersection:
```
>> set([1,2,3]) & set([2,3,4])
set([2, 3])
>> set().intersection(*[[1,2,3]... | When you do `set()` you are creating an empty set. When you do `set().intersection(...)` you are intersecting this empty set with other stuff. The intersection of an empty set with any other collection of sets is empty.
If you actually have a list of *sets*, you can get their intersection similar to how you did it.
`... |
Python set Union and set Intersection operate differently? | 19,580,944 | 35 | 2013-10-25T04:09:08Z | 19,581,007 | 7 | 2013-10-25T04:16:19Z | [
"python",
"set",
"union",
"intersection"
] | I'm doing some set operations in Python, and I noticed something odd..
```
>> set([1,2,3]) | set([2,3,4])
set([1, 2, 3, 4])
>> set().union(*[[1,2,3], [2,3,4]])
set([1, 2, 3, 4])
```
That's good, expected behaviour - but with intersection:
```
>> set([1,2,3]) & set([2,3,4])
set([2, 3])
>> set().intersection(*[[1,2,3]... | convert the list to set first
```
>>> set.intersection(*[set([1,2,3]), set([2,3,4])])
set([2, 3])
```
For multiple lists you can just use,
```
>>> set.intersection(*[set([1,2,3]), set([2,3,4]), set([5,3,4])])
set([3])
``` |
Python set Union and set Intersection operate differently? | 19,580,944 | 35 | 2013-10-25T04:09:08Z | 19,581,061 | 11 | 2013-10-25T04:23:34Z | [
"python",
"set",
"union",
"intersection"
] | I'm doing some set operations in Python, and I noticed something odd..
```
>> set([1,2,3]) | set([2,3,4])
set([1, 2, 3, 4])
>> set().union(*[[1,2,3], [2,3,4]])
set([1, 2, 3, 4])
```
That's good, expected behaviour - but with intersection:
```
>> set([1,2,3]) & set([2,3,4])
set([2, 3])
>> set().intersection(*[[1,2,3]... | ```
set().intersection(*[[1,2,3], [2,3,4]])
```
is of course empty because you start with the empty set and intersect it with all the others
You can try calling the method on the `class`
```
set.intersection(*[[1,2,3], [2,3,4]])
```
but that won't work because the first argument passed needs to be a set
```
set.in... |
Plotting histograms from grouped data in a pandas DataFrame | 19,584,029 | 17 | 2013-10-25T07:44:55Z | 19,603,918 | 60 | 2013-10-26T06:59:47Z | [
"python",
"pandas",
"histogram"
] | I need some guidance in working out how to plot a block of histograms from grouped data in a pandas dataframe. Here's an example to illustrate my question:
```
from pandas import DataFrame
import numpy as np
x = ['A']*300 + ['B']*400 + ['C']*300
y = np.random.randn(1000)
df = DataFrame({'Letter':x, 'N':y})
grouped = d... | I'm on a roll, just found an even simpler way to do it using the *by* keyword in the hist method:
```
df['N'].hist(by=df['Letter'])
```
That's a very handy little shortcut for quickly scanning your grouped data!
For future visitors, the product of this call is the following chart:
:
```
temp=[]
for row in df.iterrows():
index, data = row
temp.append(data.tolist())
```
Alternatively you can also use `apply`:
```
df.apply(lambda x: x.tolist(), axis=1)
```
**Update*... |
Convert a row in pandas into list | 19,585,280 | 12 | 2013-10-25T08:49:36Z | 19,585,413 | 16 | 2013-10-25T08:55:56Z | [
"python",
"pandas"
] | I have a pandas data frame like this:
```
admit gpa gre rank
0 3.61 380 3
1 3.67 660 3
1 3.19 640 4
0 2.93 520 4
```
Now I want to get a list of rows in pandas like:
```
[[0,3.61,380,3], [1,3.67,660,3], [1,3.19,640,4], [0,2.93,520,4]]
```
How can I do it? please help me.
Thanks ... | you can do it like this:
```
map(list, df.values)
``` |
Iterating through directories with Python | 19,587,118 | 41 | 2013-10-25T10:17:39Z | 19,587,581 | 90 | 2013-10-25T10:39:02Z | [
"python",
"directory"
] | I need to iterate through the subdirectories of a given directory and search for files. If I get a file I have to open it and change the content and replace it with my own lines.
I tried this:
```
import os
rootdir ='C:/Users/sid/Desktop/test'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
... | The actual walk through the directories works as you have coded it. If you replace the contents of the inner loop with a simple `print` statement you can see that each file is found:
```
import os
rootdir = 'C:/Users/sid/Desktop/test'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
print o... |
Multiply in django template | 19,588,160 | 3 | 2013-10-25T11:08:30Z | 19,588,661 | 11 | 2013-10-25T11:31:32Z | [
"python",
"django",
"django-templates"
] | I am looping through cart-items, and want to multiply quantity with unit-price like this:
```
{% for cart_item in cart.cartitem_set.all %}
{{cart_item.quantity}}*{{cart_item.unit_price}}
{% endfor %}
```
Is it possible to do something like that? any other way to do it !! Thanks | You need to use a custom template tag. Template filters only accept a single argument, while a custom template tag can accept as many parameters as you need, do your multiplication and return the value to the context.
You'll want to check out the Django [template tag documentation](https://docs.djangoproject.com/en/1.... |
Python reading from a file and saving to utf-8 | 19,591,458 | 17 | 2013-10-25T13:39:12Z | 19,591,815 | 53 | 2013-10-25T13:55:41Z | [
"python",
"utf-8"
] | I'm having problems reading from a file, processing its string and saving to an UTF-8 File.
Here is the code:
```
try:
filehandle = open(filename,"r")
except:
print("Could not open file " + filename)
quit()
text = filehandle.read()
filehandle.close()
```
I then do some processing on the variable text.
... | Process text to and from Unicode at the I/O boundaries of your program using the `codecs` module:
```
import codecs
with codecs.open(filename,'r',encoding='utf8') as f:
text = f.read()
# process Unicode text
with codecs.open(filename,'w',encoding='utf8') as f:
f.write(text)
```
**Edit:** The `io` module is no... |
How to get the value of the last assigned variable in iPython? | 19,593,108 | 3 | 2013-10-25T14:51:54Z | 19,593,325 | 12 | 2013-10-25T15:01:22Z | [
"python",
"ipython"
] | I am a total iPython newbie, but I was wondering if there is a way to get the value of the last assigned variable:
```
In [1]: long_variable_name = 333
In [2]: <some command/shortcut that returns 333>
```
In R we have `.Last.value`:
```
> long_variable_name = 333
> .Last.value
[1] 333
``` | There's a shortcut for the last *returned* object, `_`.
```
In [1]: 1 + 3
Out[1]: 4
In [2]: _
Out[2]: 4
``` |
What was midnight yesterday as an epoch time? | 19,594,747 | 5 | 2013-10-25T16:13:17Z | 19,594,889 | 18 | 2013-10-25T16:21:03Z | [
"python",
"datetime"
] | I'm trying to get my head around the datetime module. I know the time now as an epoch and the time an event last happened (as an epoch time). What I need to do is figure out whether that event happened between midnight and midnight of yesterday.
```
t = time.time() # is now
t2 = 1234567890 # some arbitrary time from m... | Generating the last midnight is easy:
```
from datetime import datetime, date, time
midnight = datetime.combine(date.today(), time.min)
```
That combines today's date, together with [`time.min`](http://docs.python.org/2/library/datetime.html#datetime.time.min) to form a `datetime` object at midnight.
With a `timede... |
UnicodeEncodeError after setting restrict_xpaths settings | 19,595,359 | 4 | 2013-10-25T16:48:04Z | 19,602,304 | 8 | 2013-10-26T02:56:38Z | [
"python",
"encoding",
"scrapy"
] | i'm new to python and scrapy. After setting restrict\_xpaths settings to "//table[@class="lista"]" I've received following traceback. What's strange, by using other xpath rule the crawler works properly.
```
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/... | That's a bug caused by the web page using the `»` entity which is translated by `lxml` to the unicode character `\xbb` and when you use the `restrict_xpaths` argument the link extractors encodes the content to the original encoding `iso8859-2` which fails because `\xbb` is not valid character in that encoding.
T... |
Trouble installing scipy in virtualenv on a amazon ec2 linux micro instance | 19,595,944 | 22 | 2013-10-25T17:23:43Z | 20,890,162 | 58 | 2014-01-02T19:18:34Z | [
"python",
"linux",
"amazon-ec2",
"scipy",
"virtualenv"
] | I have successfully installed `scipy` in the default python compiler on an amazon ec2 micro instance (Ubuntu 13.04). However i am not able to install `scipy` in a virtualenv.
`pip install scipy` ends with this error
```
scipy/sparse/sparsetools/csr_wrap.cxx: In function âvoid init_csr()â:
scipy/sparse/sparsetool... | One solution is to temporarily enable swap on your micro instance. As described at this [SO post](http://stackoverflow.com/questions/17173972/how-do-you-add-swap-to-an-ec2-instance), enable 1gb swap via:
```
sudo /bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
sudo /sbin/mkswap /var/swap.1
sudo /sbin/swapon /var/... |
Binary random array with a specific proportion of ones? | 19,597,473 | 10 | 2013-10-25T18:56:13Z | 19,597,662 | 9 | 2013-10-25T19:09:51Z | [
"python",
"arrays",
"random",
"numpy",
"random-sample"
] | What is the efficient(probably vectorized with Matlab terminology) way to generate random number of zeros and ones with a specific proportion? Specially with Numpy?
As my case is special for `1/3`, my code is:
```
import numpy as np
a=np.mod(np.multiply(np.random.randomintegers(0,2,size)),3)
```
But is there any bu... | A simple way to do this would be to first generate an `ndarray` with the proportion of zeros and ones you want:
```
>>> import numpy as np
>>> N = 100
>>> K = 30 # K zeros, N-K ones
>>> arr = np.array([0] * K + [1] * (N-K))
>>> arr
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0... |
Binary random array with a specific proportion of ones? | 19,597,473 | 10 | 2013-10-25T18:56:13Z | 19,597,805 | 11 | 2013-10-25T19:18:58Z | [
"python",
"arrays",
"random",
"numpy",
"random-sample"
] | What is the efficient(probably vectorized with Matlab terminology) way to generate random number of zeros and ones with a specific proportion? Specially with Numpy?
As my case is special for `1/3`, my code is:
```
import numpy as np
a=np.mod(np.multiply(np.random.randomintegers(0,2,size)),3)
```
But is there any bu... | Yet another approach, using [`np.random.choice`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.choice.html):
```
>>> np.random.choice([0, 1], size=(10,), p=[1./3, 2./3])
array([0, 1, 1, 1, 1, 0, 0, 0, 0, 0])
``` |
What's wrong with this code for solving integral equations in python | 19,598,023 | 2 | 2013-10-25T19:32:21Z | 19,598,888 | 7 | 2013-10-25T20:27:41Z | [
"python",
"scipy",
"integration",
"equation"
] | I have the following integral equation:

I'm trying to solve the integral equation to see whether f(u) is predicted as cos(2u). Since we know that the solution to the integral equation is cos(2u), we can approximate the integral from 0 to infinity to t... | This is not a programming question, but here goes: integral equations are quite often numerically badly conditioned.
Indeed, in your case,
```
u, s, vh = linalg.svd(A)
print(s.max()/s.min())
# -> 4.03758642411e+16
```
This is the condition number, and it's huge. The matrix `A` is nearly singular, so there will be a ... |
CSRF cookie not set django...verification failed | 19,598,993 | 3 | 2013-10-25T20:35:43Z | 23,787,559 | 7 | 2014-05-21T15:23:46Z | [
"python",
"django",
"cookies"
] | AoA
I am new to Django, I am trying to get data from POST, but getting error CSRF cookie not set, I tried alot to find the solution on google and stackoverflow via google too, but failed
here is the code
# views.py
```
from django.http import HttpResponse
from django.template.loader import get_template
f... | I had the same problem, and resolved it by adding the [ensure\_csrf\_cookie decorator](https://docs.djangoproject.com/en/1.8/ref/csrf/#page-uses-ajax-without-any-html-form) to your view:
```
from django.views.decorators.csrf import ensure_csrf_cookie
@ensure_csrf_cookie
def yourView(request):
#...
```
It will... |
Get particular row as series from pandas dataframe | 19,599,578 | 9 | 2013-10-25T21:18:07Z | 19,599,661 | 16 | 2013-10-25T21:24:32Z | [
"python",
"pandas"
] | How do we get a particular filtered row as series?
Example dataframe:
```
>>> df = pd.DataFrame({'date': [20130101, 20130101, 20130102], 'location': ['a', 'a', 'c']})
>>> df
date location
0 20130101 a
1 20130101 a
2 20130102 c
```
I need to select the row where `location` is `c` **as a... | Use the [`squeeze`](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.squeeze.html) function that will remove one dimension from the dataframe:
```
df[df["location"] == "c"].squeeze()
Out[5]:
date 20130102
location c
Name: 2, dtype: object
```
DataFrame.squeeze method acts the same... |
Flattening an array only one layer? | 19,599,579 | 3 | 2013-10-25T21:18:29Z | 19,599,652 | 7 | 2013-10-25T21:23:51Z | [
"python",
"arrays",
"numpy"
] | Is there any built-in numpy function that would get:
```
a=np.asarray([[[1,2],[3,4]],[[1,2],[3,4]]])
```
And would return:
```
b=[[1,2],[3,4],[1,2],[3,4]]
```
? Something like like one layer flattening.
P.S. I am looking for a vectorized option otherwise this dumb code is available:
```
flat1D(a):
b=np.array([... | You can simply reshape the array.
```
>>> a.reshape(-1,a.shape[-1])
array([[1, 2],
[3, 4],
[1, 2],
[3, 4]])
```
The shown code returns a 1D array, to do this:
```
>>> a.ravel()
array([1, 2, 3, 4, 1, 2, 3, 4])
```
Or, if you are sure you want to copy the array:
```
>>> a.flatten()
array([1, 2, ... |
How to read records terminated by custom separator from file in python? | 19,600,475 | 4 | 2013-10-25T22:39:51Z | 19,600,562 | 7 | 2013-10-25T22:48:04Z | [
"python",
"file",
"io",
"record",
"separator"
] | I would like a way to do `for line in file` in python, where the end of line is redefined to be any string that I want. Another way of saying that is I want to read records from file rather than lines; I want it to be equally fast and convenient to do as reading lines.
This is the python equivalent to setting perl's `... | There is nothing in the Python 2.x `file` object, or the Python 3.3 `io` classes, that lets you specify a custom delimiter for `readline`. (The `for line in file` is ultimately using the same code as `readline`.)
But it's pretty easy to build it yourself. For example:
```
def delimited(file, delimiter='\n', bufsize=4... |
python 2 support in vim | 19,601,729 | 7 | 2013-10-26T01:10:35Z | 19,601,746 | 7 | 2013-10-26T01:13:06Z | [
"python",
"ubuntu",
"vim",
"plugins"
] | I am trying to set up YouCompleteMe, a code-completion plugin for vim. When I run vim, it gives me this error message: "YouCompleteMe unavailable: requires python 2.x". I have the correct version of python installed on my ubuntu machine and this confused me. After some research, I have found that I needed python2 suppo... | Try `aptitude install vim-nox` or `aptitude install vim-gnome` if you want the GUI. `vim-python` is a virtual package provided by either of these.
By default, Ubuntu has `vim-tiny` installed, which has a bunch of the options switched off. |
How does all() in python work on empty lists | 19,601,802 | 5 | 2013-10-26T01:25:18Z | 19,601,813 | 9 | 2013-10-26T01:27:23Z | [
"python",
"python-2.7",
"list-comprehension"
] | I am referring to the following python code
```
all(a==2 for a in my_list)
```
I expect the above code to return True if all the elements in my\_list are 2.
but when I make my\_list empty and run it as
```
my_list = []
all(a==2 for a in my_list)
```
it returns True as well. I am confused with this behaviour. Is it ... | It's true because for every element in the list, all 0 of them, they all are equal to 2.
You can think of [all](http://docs.python.org/2/library/functions.html#all) being implemented as:
```
def all(list, condition):
for a in list:
if not condition(a):
return false
return true
```
Whereas [any](http://... |
Find the longest substring in alphabetical order | 19,601,903 | 7 | 2013-10-26T01:43:03Z | 19,610,523 | 12 | 2013-10-26T18:45:52Z | [
"python"
] | I have this code that I found on another topic, but it sorts the substring by contiguous characters and not by alphabetical order. How do I correct it for alphabetical order? It prints out `lk`, and I want to print `ccl`. Thanks
ps: I'm a beginner in python
```
s = 'cyqfjhcclkbxpbojgkar'
from itertools import count
... | ```
s = 'cyqfjhcclkbxpbojgkar'
r = ''
c = ''
for char in s:
if (c == ''):
c = char
elif (c[-1] <= char):
c += char
elif (c[-1] > char):
if (len(r) < len(c)):
r = c
c = char
else:
c = char
if (len(c) > len(r)):
r = c
print(r)
``` |
Numpy: Divide each row by a vector element | 19,602,187 | 25 | 2013-10-26T02:34:28Z | 19,602,209 | 50 | 2013-10-26T02:38:15Z | [
"python",
"arrays",
"numpy",
"scipy"
] | Suppose I have a numpy array:
```
data = np.array([[1,1,1],[2,2,2],[3,3,3]])
```
and I have a corresponding "vector:"
```
vector = np.array([1,2,3])
```
How do I operate on `data` along each row to either subtract or divide so the result is:
```
sub_result = [[0,0,0], [0,0,0], [0,0,0]]
div_result = [[1,1,1], [1,1,... | Here you go. You just need to use `None` (or alternatively `np.newaxis`) combined with broadcasting:
```
In [6]: data - vector[:,None]
Out[6]:
array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
In [7]: data / vector[:,None]
Out[7]:
array([[1, 1, 1],
[1, 1, 1],
[1, 1, 1]])
``` |
Basic http file downloading and saving to disk in python? | 19,602,931 | 65 | 2013-10-26T04:49:27Z | 19,602,990 | 89 | 2013-10-26T04:59:08Z | [
"python",
"file",
"download",
"save"
] | I'm new to Python and I've been going through the Q&A on this site, for an answer to my question. However, I'm a beginner and I find it difficult to understand some of the solutions. I need a very basic solution.
Could someone please explain a simple solution to 'Downloading a file through http' and 'Saving it to disk... | A clean way to download a file is:
```
import urllib
testfile = urllib.URLopener()
testfile.retrieve("http://randomsite.com/file.gz", "file.gz")
```
This downloads a file from a website and names it `file.gz`. This is one of my favorite solutions, from [Downloading a picture via urllib and python](http://stackoverfl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.