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 |
|---|---|---|---|---|---|---|---|---|---|
pylint false positive for unused argument | 20,881,733 | 2 | 2014-01-02T11:17:35Z | 20,881,954 | 7 | 2014-01-02T11:30:09Z | [
"python",
"pylint"
] | I'm in the process of cleaning up code with pylint in order to be able to use it for pre-commit validation. I have a lot of "unused-argument" warning when in fact they are used. Here is an example triggering a false positive.
```
def addSeven(foo): #Here I have a warning "Unused argument 'foo'"
foo += [7]
example... | You can disable it for any scope by adding:
```
def myfunc(a):
# pylint: disable=W0612,W0613
```
see <http://docs.pylint.org/faq.html#is-it-possible-to-locally-disable-a-particular-message> |
_fastmath error in python: HAVE_DECL_MPZ_POWM_SEC | 20,881,768 | 7 | 2014-01-02T11:19:48Z | 20,901,761 | 16 | 2014-01-03T10:44:09Z | [
"python",
"paramiko",
"pycrypto"
] | I am running python 2.6 on Red Hat 6.4
I had a script running on one machine using paramiko sftp. When I transferred it to another machine I got an exception: `SFTP file has no attribute __exit__` (something along those lines).
I decided to upgrade paramiko (thought it would solve the problem) with pip. Now I am gett... | It seems you have a mix of PyCrypto libraries installed in your system.
This [bug report](https://bugs.launchpad.net/pycrypto/+bug/1206836) on the PyCrypto trackiong system seems related:
> My guess is that you have the python-crypto-2.0.1 RPM installed system-wide,
> and you didn't have gmp-devel installed when you b... |
_fastmath error in python: HAVE_DECL_MPZ_POWM_SEC | 20,881,768 | 7 | 2014-01-02T11:19:48Z | 24,328,169 | 14 | 2014-06-20T13:14:35Z | [
"python",
"paramiko",
"pycrypto"
] | I am running python 2.6 on Red Hat 6.4
I had a script running on one machine using paramiko sftp. When I transferred it to another machine I got an exception: `SFTP file has no attribute __exit__` (something along those lines).
I decided to upgrade paramiko (thought it would solve the problem) with pip. Now I am gett... | For me, the issue was that I had the python-crypto package installed via yum, and then had also installed the pycrypto module via pip.
```
yum remove python-crypto
```
worked for me. |
Warning (from warnings module): ResourceWarning: unclosed <socket.socket object, fd=404, family=2, type=1, proto=0> using selenium | 20,885,561 | 8 | 2014-01-02T14:54:02Z | 21,500,796 | 12 | 2014-02-01T16:52:04Z | [
"python",
"sockets",
"selenium"
] | ```
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class PythonOrgSearch(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
def test_search_in_python_org(self):
driver = self.driver
driver.get("http://www.python.org"... | It's a known bug:
<http://code.google.com/p/selenium/issues/detail?id=5923>
It's safe to ignore it though. If you're using Python 3, you can do:
```
unittest.main(warnings='ignore')
```
See [Python 3 unittest docs](http://docs.python.org/3/library/unittest.html#unittest.main).
In Python 2, you'd use something like... |
How to get back an overridden python built-in function? | 20,885,760 | 12 | 2014-01-02T15:05:03Z | 20,885,776 | 25 | 2014-01-02T15:06:09Z | [
"python",
"python-2.7"
] | When I was exploring a solution for the StackOverflow problem, [Python Use User Defined String Class](http://stackoverflow.com/questions/20884949/python-use-user-defined-string-class), I came with this strange python behavior.
```
def overriden_print(x):
print "Overriden in the past!"
from __future__ import print... | Just delete the override:
```
del print
```
This deletes the name from the `globals()` dictionary, letting search fall back to the built-ins.
You can always refer directly to the built-in via the [`__builtin__` module](http://docs.python.org/2/library/__builtin__.html) as well:
```
import __builtin__
__builtin__.p... |
How to add dot's graph attribute into final dot output | 20,885,986 | 4 | 2014-01-02T15:19:24Z | 20,890,899 | 7 | 2014-01-02T20:05:28Z | [
"python",
"graph",
"graphviz",
"networkx",
"dot"
] | I create representation of graph with NetworkX library in my python project.
Making directed graph I need to add an attribute to our graph output:
rankdir=LR
So I'm writing the code:
```
import networkx as nx
graph = nx.DiGraph(rankdir="LR")
#adding deps based on our database data
add_deps(graph)
dot_file_path = "som... | It's not very well documented. You can add default "graph" properties like this:
```
In [1]: import networkx as nx
In [2]: G = nx.DiGraph()
In [3]: G.add_edge(1,2)
In [4]: G.graph['graph']={'rankdir':'LR'}
In [5]: import sys
In [6]: nx.write_dot(G, sys.stdout)
strict digraph {
graph [rankdir=LR];
1 -> 2;... |
Python - Using multiprocessing.Process with a maximum number of simultaneous processes | 20,886,565 | 22 | 2014-01-02T15:51:37Z | 20,886,753 | 25 | 2014-01-02T16:02:29Z | [
"python",
"multithreading",
"multiprocessing"
] | I have the `Python` code:
```
from multiprocessing import Process
def f(name):
print 'hello', name
if __name__ == '__main__':
for i in range(0, MAX_PROCESSES):
p = Process(target=f, args=(i,))
p.start()
```
which runs well. However, `MAX_PROCESSES` is variable and can be any value between `1... | It might be most sensible to use `multiprocessing.Pool` which produces a pool of worker processes based on the max number of cores available on your system, and then basically feeds tasks in as the cores become available.
The example from the standard docs (<http://docs.python.org/2/library/multiprocessing.html#using-... |
Dead simple example of using Multiprocessing Queue, Pool and Locking | 20,887,555 | 21 | 2014-01-02T16:45:52Z | 20,888,445 | 43 | 2014-01-02T17:36:18Z | [
"python",
"python-2.7"
] | I tried to read the documentation at <http://docs.python.org/dev/library/multiprocessing.html> but I'm still struggling with multiprocessing Queue, Pool and Locking. And for now I was able to build the example below.
Regarding Queue and Pool, I'm not sure if I understood the concept in the right way, so correct me if ... | The best solution for your problem is to utilize a `Pool`. Using `Queue`s and having a separate "queue feeding" functionality is probably overkill.
Here's a slightly rearranged version of your program, this time with **only 2 processes** coralled in a `Pool`. I believe it's the easiest way to go, with minimal changes ... |
Google Cloud endpoints and service accounts returning :Oauth framework user didn't match oauth token user | 20,888,401 | 4 | 2014-01-02T17:33:54Z | 20,888,817 | 9 | 2014-01-02T17:56:42Z | [
"python",
"google-app-engine",
"oauth",
"google-cloud-endpoints",
"endpoints-proto-datastore"
] | Im trying to access a google cloud endpoint from a cmdline using service account similar to
<https://code.google.com/p/google-api-python-client/source/browse/samples/service_account/tasks.py>
As instructed from the example, I created a clientid + pk12 cert and using them to create the credential with the SignedJwtAse... | From extensive research I have come to the conclusion that implementing OAuth is not a viable authentication method for apps because of the simple fact that it is horrible to implement. After spending countless hours debugging and asking questions on Stackoverflow about a simple Twitter oAuth implementation, all while ... |
Regex django url | 20,888,624 | 13 | 2014-01-02T17:45:30Z | 20,888,740 | 24 | 2014-01-02T17:51:43Z | [
"python",
"regex",
"django"
] | Hello I have a url and I want to match the uuid
the url looks like this:
> /mobile/mobile-thing/**68f8ffbb-b715-46fb-90f8-b474d9c57134/**
```
urlpatterns = patterns("mobile.views",
url(r'^$', 'something_cool', name='cool'),
url(r'^mobile-thing/(?P<uuid>[.*/])$', 'mobile_thing', name='mobile-thinger'),
)
```
... | The `[.*/]` expression only matches **one** character, which can be `.`, `*` or `/`. You need to write instead (this is just one of many options):
```
urlpatterns = patterns("mobile.views",
url(r'^$', 'something_cool', name='cool'),
url(r'^mobile-thing/(?P<uuid>[^/]+)/$', 'mobile_thing', name='mobile-thinger')... |
Python - One line if-elif-else statement | 20,888,693 | 4 | 2014-01-02T17:48:53Z | 20,888,751 | 11 | 2014-01-02T17:52:14Z | [
"python",
"if-statement"
] | I'm trying to condense an if-elif-else statement into one line. I tried:
```
a == 1 ? print "one" : a == 2 ? print "two" : print "none"
```
But I got a syntax-error. I have also tried:
```
print "one" if a == 1 else print "two" if a == 2 else print "none"
```
But I also got a syntax-error.
What can I do to make an... | Try:
```
print {1: 'one', 2: 'two'}.get(a, 'none')
``` |
Django reverse error: NoReverseMatch | 20,889,242 | 12 | 2014-01-02T18:21:12Z | 20,889,525 | 21 | 2014-01-02T18:37:16Z | [
"python",
"django"
] | I've looked at a lot of different posts, but they're all either working with a different version of django or don't seem to work. Here is what I'm trying to do:
urls.py (for the entire project):
```
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^blog/', include('b... | You've used a namespace when including the URLs, so you probably need to use `"blog:postdetail"` to reverse it. |
resampled time using scipy.signal.resample | 20,889,501 | 4 | 2014-01-02T18:36:02Z | 20,889,651 | 9 | 2014-01-02T18:46:36Z | [
"python",
"numpy",
"scipy",
"resampling"
] | I have a signal that is not sampled equidistant; for further processing it needs to be. I thought that scipy.signal.resample would do it, but I do not understand its behavior.
The signal is in y, corresponding time in x.
The resampled is expected in yy, with all corresponding time in xx. Does anyone know what I do wro... | Even when you give the `x` coordinates (which corresponds to the `t` argument), [`resample`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.resample.html) assumes that the sampling is uniform.
Consider using one of the univariate interpolators in [`scipy.interpolate`](http://docs.scipy.org/doc/scipy/... |
Get text of childrens in a div with beautifulsoup | 20,889,790 | 2 | 2014-01-02T18:55:04Z | 20,889,820 | 8 | 2014-01-02T18:56:46Z | [
"python",
"html",
"beautifulsoup",
"urllib2"
] | Hi i want the description of an App in the Google Playstore. (<https://play.google.com/store/apps/details?id=com.wetter.androidclient&hl=de>)
```
import urllib2
from bs4 import BeautifulSoup
soup = BeautifulSoup(urllib2.urlopen("https://play.google.com/store/apps/details?id=com.wetter.androidclient&hl=de"))
result = ... | Use the `.text` attribute on the elements; you have a *list* of results, so loop:
```
for res in result:
print res.text
```
Alternatively, if there is only ever supposed to be *one* such `<div>`, use `.find()` instead of `.find_all()`:
```
result = soup.find("div", {"class":"show-more-content text-body"})
print ... |
isalpha python function won't consider spaces | 20,890,618 | 4 | 2014-01-02T19:46:50Z | 20,890,671 | 8 | 2014-01-02T19:50:22Z | [
"python",
"string",
"python-2.7"
] | So the code below takes an input and makes sure the input consists of letters and not numbers. How would i make it also print orginal if the input contains a space
```
original = raw_input("Type the name of the application: ")
if original.isalpha() and len(original) > 0:
print original
else:
print "empty"
```... | It looks like that's just how string works.
Two options:
```
if all(x.isalpha() or x.isspace() for x in original):
```
(modified on inspectorG4dget's recommendation below)
or
```
original.replace(' ','').isalpha()
```
should work. |
convert list of dicts to list | 20,891,141 | 3 | 2014-01-02T20:20:47Z | 20,891,185 | 7 | 2014-01-02T20:23:12Z | [
"python",
"list",
"python-2.7",
"dictionary"
] | I have a list of fields in this form
```
fields = [{'name':'count', 'label':'Count'},{'name':'type', 'label':'Type'}]
```
I'd like to extract just the names and put it in a list. Currently, I'm doing this:
```
names = []
for field in fields:
names.append(field['name'])
```
Is there another way to do the same t... | You can use a list comprehension:
```
>>> fields = [{'name':'count', 'label':'Count'},{'name':'type', 'label':'Type'}]
>>> [f['name'] for f in fields]
['count', 'type']
``` |
What magic prevents Tkinter programs from blocking in interactive shell? | 20,891,710 | 15 | 2014-01-02T20:56:49Z | 20,892,684 | 9 | 2014-01-02T21:57:19Z | [
"python",
"tkinter",
"interactive-shell"
] | *Note: This is somewhat a follow-up on the question: [Tkinter - when do I need to call mainloop?](http://stackoverflow.com/questions/8683217/tkinter-when-do-i-need-to-call-mainloop)*
Usually when using [Tkinter](http://docs.python.org/3/library/tkinter.html), you call [Tk.mainloop](http://www.tcl.tk/man/tcl8.5/TkLib/M... | It's actually not being an interactive interpreter that matters here, but waiting for input on a TTY. You can get the same behavior from a script like this:
```
import tkinter
t = tkinter.Tk()
input()
```
(On Windows, you may have to run the script in pythonw.exe instead of python.exe, but otherwise, you don't have t... |
An efficient way to convert document to pdf format | 20,891,787 | 16 | 2014-01-02T21:00:44Z | 20,950,290 | 14 | 2014-01-06T12:42:25Z | [
"python",
"pdf",
"ubuntu",
"document-conversion",
"docsplit"
] | I have been trying to find the efficient way to convert document e.g. doc, docx, ppt, pptx to pdf. So far i have tried [docsplit](http://documentcloud.github.io/docsplit/) and `oowriter`, but both took > 10 seconds to complete the job on [pptx file](http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=6&cad=rja... | Try calling [unoconv](http://dag.wiee.rs/home-made/unoconv/) from your Python code, it took 8 seconds on my local machine, I don't know if it's fast enough for you:
```
time unoconv 15.\ Text-Files.pptx
real 0m8.604s
``` |
Contours with map overlay on irregular grid in python | 20,892,251 | 6 | 2014-01-02T21:28:20Z | 20,893,341 | 8 | 2014-01-02T22:44:49Z | [
"python",
"matplotlib"
] | Here is my data:
```
Lon Lat Z Z2 pos
32.6 -13.6 41 9 CHIP
27.1 -16.9 43 12 CHOM
32.7 -10.2 46 14 ISOK
24.2 -13.6 33 13 KABO
28.5 -14.4 43 11 KABW
28.1 -12.6 33 16 KAFI
27.9 -15.8 46 13 KAFU
24.8 -14.8 44 9 KAOM
31.1 -10.2 35 14 KASA
25.9 -13.5 24 8 KASE
29... | To start with, let's ignore the map-based part of things, and just treat your lat, long coordinates as a cartesian coordinate system.
```
import numpy as np
import pandas as pd
from matplotlib.mlab import griddata
import matplotlib.pyplot as plt
#-- Read the data.
# I'm going to use `pandas` to read in and work with ... |
Python â time.time() vs. bash time | 20,892,626 | 5 | 2014-01-02T21:52:44Z | 20,892,693 | 10 | 2014-01-02T21:58:20Z | [
"python",
"osx",
"bash",
"time"
] | I've been working on some Project Euler problems in Python 3 [osx 10.9], and I like to know how long they take to run.
I've been using the following two approaches to time my programs:
1)
```
import time
start = time.time()
[program]
print(time.time() - start)
```
2) On the bash command line, typing `time python3... | The interpreter imports `site.py` and can touch upon various other files on start-up. This all takes time before your `import time` line is ever executed:
```
$ touch empty.py
$ time python3 empty.py
real 0m0.158s
user 0m0.033s
sys 0m0.021s
```
When timing code, take into account that other processes, dis... |
python: split string after comma and dots | 20,893,839 | 2 | 2014-01-02T23:25:35Z | 20,893,949 | 7 | 2014-01-02T23:34:29Z | [
"python",
"regex"
] | I have a piece of code which splits a string after commas and dots (but not when a digit is before or after a comma or dot):
```
text = "This is, a sample text. Some more text. $1,200 test."
print re.split('(?<!\d)[,.]|[,.](?!\d)', text)
```
The result is:
```
['This is', ' a sample text', ' Some more text', ' $1,20... | Unfortunately you can't use `re.split()` on a zero-length match, so unless you can guarantee that there will be whitespace after the comma or dot you will need to use a different approach.
Here is one option that uses `re.findall()`:
```
>>> text = "This is, a sample text. Some more text. $1,200 test."
>>> print re.f... |
Problems deploying Flask app on Google App Engine | 20,895,266 | 3 | 2014-01-03T01:57:54Z | 20,898,526 | 7 | 2014-01-03T07:14:29Z | [
"python",
"json",
"google-app-engine",
"deployment",
"flask"
] | I'm trying to deploy a Flask app on GAE using Windows. It runs fine locally but runs into problems when I try to run it on GAE.
First I get this error in flask\json.py:
```
from itsdangerous import json as _json
```
> ImportError: No module named itsdangerous
Downloading and unpacking <https://pypi.python.org/pypi/... | You put the `itsdangerous.py` in the wrong directory. Because json.py and itsdangerous.py both exist in the /flask directory, itsdangerous.py will import /flask/json.py intead of the right one.
The GAE official [doc](https://developers.google.com/appengine/docs/python/) mentioned a way to include 3rd-party libraries:
... |
Problems deploying Flask app on Google App Engine | 20,895,266 | 3 | 2014-01-03T01:57:54Z | 22,759,593 | 8 | 2014-03-31T10:46:25Z | [
"python",
"json",
"google-app-engine",
"deployment",
"flask"
] | I'm trying to deploy a Flask app on GAE using Windows. It runs fine locally but runs into problems when I try to run it on GAE.
First I get this error in flask\json.py:
```
from itsdangerous import json as _json
```
> ImportError: No module named itsdangerous
Downloading and unpacking <https://pypi.python.org/pypi/... | Google now makes it super-easy:
<https://console.developers.google.com/start/appengine> |
How exactly do Django content types work? | 20,895,429 | 63 | 2014-01-03T02:16:11Z | 21,440,397 | 142 | 2014-01-29T19:12:46Z | [
"python",
"django"
] | I hate wasting people's time. This is my first post here and it is really only a last resort after days of searching extensively for an answer. I'm really having a difficult time grasping the concept of Django's content types. It feels very hackish and, ultimately, against how Python tends to do things. That being said... | ## So you want to use the Content Types framework on your work?
Start by asking yourself this question: "Do any of these models need to be related in the same way to other models and/or will I be reusing these relationships in unforseen ways later down the road?" The reason why we ask this question is because this is ... |
Forbidden (403) CSRF verification failed. Request aborted. Even using the {% csrf_token %} | 20,895,526 | 10 | 2014-01-03T02:29:33Z | 20,895,547 | 11 | 2014-01-03T02:32:36Z | [
"python",
"django",
"login",
"csrf"
] | i am trying to do a login in django but i get this error, i check the CSRF documentation and nothing works for me.
Here is the HTML:
```
<body>
<section class="container">
<div class="login">
<h1>Login to Web App</h1>
{% if form.errors %}
<p class="error">Lo sentimos, la combinacion de usua... | # Theory
---
A couple of things are required to make the csrf protection work (check out the [docs](https://docs.djangoproject.com/en/1.6/ref/contrib/csrf/)):
1. Your browser has to accept cookies from your server
2. Make sure you have '`django.middleware.csrf.CsrfViewMiddleware'` included as middleware in your `set... |
Uninstall Django completely | 20,897,851 | 10 | 2014-01-03T06:24:07Z | 20,897,900 | 9 | 2014-01-03T06:27:58Z | [
"python",
"django",
"python-2.7",
"pip"
] | I uninstalled django on my machine using `pip uninstall Django`. It says successfully uninstalled whereas when I see django version in python shell, it still gives the older version I installed.
To remove it from python path, I deleted the `django` folder under `/usr/local/lib/python-2.7/dist-packages/`.
However `sud... | `pip search` command does not show installed packages, but search packages in pypi.
Use `pip freeze` command and `grep` to see installed packages:
```
pip freeze | grep Django
``` |
Custom sort of list of dicts Python | 20,899,401 | 3 | 2014-01-03T08:19:56Z | 20,899,531 | 7 | 2014-01-03T08:28:39Z | [
"python",
"sorting"
] | I have a list of dicts :
```
ldicts = [{'name': '120-150'}, {'name': '90-120'}, {'name': '150-180'}, {'name': '>= 180'}, {'name': '<90'}, {'name': 'total'}]
```
I'd like to sort it by value ascending so that the output would be like this :
```
sortedldicts = [{'name': 'total'}, {'name': '<90'}, {'name': '90-120'},{... | Extract digits using `re.findall`:
```
>>> ldicts = [{'name': '120-150'}, {'name': '90-120'}, {'name': '150-180'}, {'name': '>= 180'}, {'name': '<90'}, {'name': 'total'}]
>>>
>>> import re
>>> sorted(ldicts, key=lambda d: map(int, re.findall(r'\d+', d['name'])))
[{'name': 'total'}, {'name': '<90'}, {'name': '90-120'},... |
Write the digits of a number into an array | 20,902,785 | 2 | 2014-01-03T11:38:12Z | 20,902,816 | 14 | 2014-01-03T11:39:55Z | [
"python",
"list",
"python-2.7"
] | I want to calculate with seperated digits of a very long number. How can I do this in Python2.7? I thought about somehow write the digits in an array so that I can access the digits with array(x):
```
number = 123456789123456789
array = [1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9]
```
The problem is, that the number has so ... | You can use [`map`](http://docs.python.org/2/library/functions.html#map), [`int`](http://docs.python.org/2/library/functions.html#int) and [`str`](http://docs.python.org/2/library/functions.html#str) functions like this
```
print map(int, str(number))
```
`str` function converts the `number` to a string.
`map` funct... |
Installing matplotlib and its dependencies without root privileges | 20,904,841 | 9 | 2014-01-03T13:32:48Z | 20,905,735 | 7 | 2014-01-03T14:22:32Z | [
"python",
"module",
"installation",
"dependencies"
] | I want to use matplotlib on a server where I have an account `/myhome` without root privileges.
I downloaded the matplotlib sources and tried to install it using the distutils with the user sheme, say `python setup.py install --user`, but it returned the following message :
```
=======================================... | From what I can see, matplot setup will eventually call the prompt with
```
pkg-config freetype2 --modversion
```
to try and find the package. It seems like it fails on this call.
Try to see what error that command gives you and let us know. See <http://people.freedesktop.org/~dbn/pkg-config-guide.html> for more inf... |
Latest 'pip' fails with "requires setuptools >= 0.8 for dist-info" | 20,905,350 | 79 | 2014-01-03T14:00:42Z | 20,906,394 | 144 | 2014-01-03T14:56:00Z | [
"python",
"pip",
"setuptools",
"python-wheel"
] | Using the recent (1.5) version of `pip`, I get an error when attempting to update several packages. For example, `sudo pip install -U pytz` results in failure with:
```
Wheel installs require setuptools >= 0.8 for dist-info support.
pip's wheel support requires setuptools >= 0.8 for dist-info support.
```
I don't und... | This worked for me:
```
sudo pip install setuptools --no-use-wheel --upgrade
```
Note it's usage of sudo
**UPDATE**
On window you just need to execute `pip install setuptools --no-use-wheel --upgrade` as an administrator. In unix/linux, `sudo` command is for elevating permissions.
**UPDATE**
This appears to have ... |
Latest 'pip' fails with "requires setuptools >= 0.8 for dist-info" | 20,905,350 | 79 | 2014-01-03T14:00:42Z | 21,047,830 | 8 | 2014-01-10T15:15:00Z | [
"python",
"pip",
"setuptools",
"python-wheel"
] | Using the recent (1.5) version of `pip`, I get an error when attempting to update several packages. For example, `sudo pip install -U pytz` results in failure with:
```
Wheel installs require setuptools >= 0.8 for dist-info support.
pip's wheel support requires setuptools >= 0.8 for dist-info support.
```
I don't und... | First, you should never run 'sudo pip'.
If possible you should use your system package manager because it uses GPG signatures to ensure you're not running malicious code.
Otherwise, try upgrading setuptools:
```
easy_install -U setuptools
```
Alternatively, try:
```
pip install --user <somepackage>
```
This is of... |
TypeError: argument of type 'char const *' | 20,905,702 | 4 | 2014-01-03T14:20:22Z | 20,911,570 | 7 | 2014-01-03T19:47:55Z | [
"python",
"freeswitch"
] | I'm currently working with Freeswitch and its [event socket library](http://wiki.freeswitch.org/wiki/Event_Socket_Library) (through the [mod event socket](http://wiki.freeswitch.org/wiki/Mod_event_socket)). For instance:
```
from ESL import ESLconnection
cmd = 'uuid_kill %s' % active_call # active_call comes from a D... | Short answer: `cmd` likely contains a Unicode string, which cannot be trivially converted to a `const char *`. The error message likely comes from a wrapper framework that automates writing Python bindings for C libraries, such as SWIG or ctypes. The framework knows what to do with a byte string, but punts on Unicode s... |
Iterating nested Python dictionaries | 20,905,898 | 4 | 2014-01-03T14:31:42Z | 20,905,953 | 7 | 2014-01-03T14:33:52Z | [
"python",
"json",
"loops",
"dictionary",
"iteration"
] | I am trying to collect info from nested dictionaries (loaded from json). I am trying to do that with for loop. I was unable to get a dictionary inside dictionary that is named "players". "players" contains dictionary with player names and their ids. I would like to extract that dictionary. You can find my code and samp... | Each `value` in the outer loop is itself a dictionary:
```
for key, value in dct.iteritems():
if 'players' in value:
for name, player in value['players'].iteritems():
print name, player
```
Here, you test first if the `players` key is actually present in the nested dictionary, then if it is, i... |
Import error cannot import name execute_manager in windows environment | 20,906,305 | 25 | 2014-01-03T14:51:03Z | 20,906,461 | 44 | 2014-01-03T15:00:01Z | [
"python",
"django",
"virtualenv",
"virtualenvwrapper"
] | I'll get you up to speed. I'm trying to setup a windows dev environment. I've successfully installed python, django, and virtualenv + virtualenwrapper([windows-cmd installer](http://virtualenvwrapper.readthedocs.org/en/latest/install.html))
```
workon env
Python 2.7.6 (default, Nov 10 2013, 19:24:24) [MSC v.1500 64 bi... | `execute_manager` deprecated in Django 1.4 as part of the project layout refactor and was removed in 1.6 per the deprecation timeline: <https://docs.djangoproject.com/en/1.4/internals/deprecation/#id3>
To fix this error you should either install a compatible version of Django for the project or update the `manage.py` ... |
Import multiple csv files into pandas and concatenate into one DataFrame | 20,906,474 | 64 | 2014-01-03T15:00:46Z | 21,232,849 | 63 | 2014-01-20T11:29:19Z | [
"python",
"csv",
"pandas",
"concatenation"
] | I would like to read several csv files from a directory into pandas and concatenate them into one big DataFrame. I have not been able to figure it out though. Here is what I have so far:
```
import glob
import pandas as pd
# get data file names
path =r'C:\DRO\DCL_rawdata_files'
filenames = glob.glob(path + "/*.csv")
... | If you have same columns in all your `csv` files then you can try the code below.
I have added `header=0` so that after reading `csv` first row can be assigned as the column names.
```
path =r'C:\DRO\DCL_rawdata_files' # use your path
allFiles = glob.glob(path + "/*.csv")
frame = pd.DataFrame()
list_ = []
for file_ in... |
Import multiple csv files into pandas and concatenate into one DataFrame | 20,906,474 | 64 | 2014-01-03T15:00:46Z | 36,416,258 | 36 | 2016-04-05T02:47:11Z | [
"python",
"csv",
"pandas",
"concatenation"
] | I would like to read several csv files from a directory into pandas and concatenate them into one big DataFrame. I have not been able to figure it out though. Here is what I have so far:
```
import glob
import pandas as pd
# get data file names
path =r'C:\DRO\DCL_rawdata_files'
filenames = glob.glob(path + "/*.csv")
... | An alternative to [darindaCoder's answer](http://stackoverflow.com/a/21232849/3888455):
```
path = r'C:\DRO\DCL_rawdata_files' # use your path
all_files = glob.glob(os.path.join(path, "*.csv")) # advisable to use os.path.join as this makes concatenation OS independent
df_from_each_file = (pd.r... |
what do _ and __ mean in PYTHON | 20,906,673 | 4 | 2014-01-03T15:11:33Z | 20,906,785 | 8 | 2014-01-03T15:17:00Z | [
"python"
] | When I input `_` or `__` in the python shell I get values returned. For instance:
```
>>> _
2
>>>__
8
```
What is happening here? | If you are using IPython then the following GLOBAL variables always exist:
* `_` *(a single underscore)*: stores previous output, like Pythonâs default interpreter.
* `__` *(two underscores)*: next previous.
* `___` *(three underscores)*: next-next previous.
Read more about it from IPython documentation: [Output ca... |
Google App Engine: UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 48: ordinal not in range(128) | 20,906,948 | 22 | 2014-01-03T15:23:50Z | 20,907,062 | 39 | 2014-01-03T15:28:47Z | [
"python",
"google-app-engine",
"unicode",
"jinja2",
"python-unicode"
] | I'm working on a small application using Google App Engine which makes use of the Quora RSS feed. There is a form, and based on the input entered by the user, it will output a list of links related to the input. Now, the applications works fine for one letter queries and most of two-letter words if the words are separa... | Python is **likely** trying to decode a unicode string into a normal str with the ascii codec and is failing. When you're working with unicode data you need to decode it:
```
content = content.decode('utf-8')
``` |
Getting console.log output from Chrome with Selenium Python API bindings | 20,907,180 | 29 | 2014-01-03T15:34:25Z | 20,910,684 | 39 | 2014-01-03T18:49:10Z | [
"python",
"google-chrome",
"logging",
"selenium"
] | I'm using Selenium to run tests in Chrome via the Python API bindings, and I'm having trouble figuring out how to configure Chrome to make the `console.log` output from the loaded test available. I see that there are `get_log()` and `log_types()` methods on the WebDriver object, and I've seen [Get chrome's console log]... | Ok, finally figured it out:
```
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
# enable browser logging
d = DesiredCapabilities.CHROME
d['loggingPrefs'] = { 'browser':'ALL' }
driver = webdriver.Chrome(desired_capabilities=d)
# load some site
driver.get... |
python-social-auth AuthCanceled exception | 20,907,276 | 17 | 2014-01-03T15:39:02Z | 20,958,644 | 16 | 2014-01-06T20:26:50Z | [
"python",
"django",
"facebook",
"facebook-authentication",
"python-social-auth"
] | I'm using python-social-auth in my Django application for authentication via Facebook.
But when a user tries to login and when it's been refirected to Facebook app page clicks on "Cancel" button, appears the following exception:
```
ERROR 2014-01-03 15:32:15,308 base :: Internal Server Error: /complete/facebook/
Trace... | you can create a middleware and catch any exceptions,
exception list: <https://github.com/omab/python-social-auth/blob/master/social/exceptions.py>
in this case your AuthCanceled Exception.
**middleware.py**
```
from social.apps.django_app.middleware import SocialAuthExceptionMiddleware
from django.shortcuts ... |
python-social-auth AuthCanceled exception | 20,907,276 | 17 | 2014-01-03T15:39:02Z | 21,899,939 | 16 | 2014-02-20T06:28:24Z | [
"python",
"django",
"facebook",
"facebook-authentication",
"python-social-auth"
] | I'm using python-social-auth in my Django application for authentication via Facebook.
But when a user tries to login and when it's been refirected to Facebook app page clicks on "Cancel" button, appears the following exception:
```
ERROR 2014-01-03 15:32:15,308 base :: Internal Server Error: /complete/facebook/
Trace... | This is slight modification of @Nicolas answer and this works for me.
**middleware.py**
```
from social.apps.django_app.middleware import SocialAuthExceptionMiddleware
from django.shortcuts import render
from social.exceptions import AuthCanceled
class SocialAuthExceptionMiddleware(SocialAuthExceptionMiddleware):
... |
python-social-auth AuthCanceled exception | 20,907,276 | 17 | 2014-01-03T15:39:02Z | 25,388,201 | 27 | 2014-08-19T16:11:52Z | [
"python",
"django",
"facebook",
"facebook-authentication",
"python-social-auth"
] | I'm using python-social-auth in my Django application for authentication via Facebook.
But when a user tries to login and when it's been refirected to Facebook app page clicks on "Cancel" button, appears the following exception:
```
ERROR 2014-01-03 15:32:15,308 base :: Internal Server Error: /complete/facebook/
Trace... | `python-social-auth` is a newer, derived version of `django-social-auth`.
AlexYar's [answer](http://stackoverflow.com/a/22059897/554894 "AlexYar") can be slightly modified to work with `python-social-auth` by modify `settings.py` with following changes:
1. Add a middleware to handle the SocialAuthException
```
... |
Proper way of building Gtk3 applications in Python | 20,907,897 | 10 | 2014-01-03T16:09:30Z | 31,497,623 | 8 | 2015-07-19T03:07:29Z | [
"python",
"gtk3"
] | I have just started learning about creating GUI apps in Python. I decided to use Gtk version 3.
According to the (official?) tutorial on <http://python-gtk-3-tutorial.readthedocs.org/> the proper way of building a hello world application is:
```
from gi.repository import Gtk
class MyWindow(Gtk.Window):
def __init... | Choosing to write your new program with a GtkApplication or just a GtkWindow depends on the functionality you require, and to some extent the intended audience.
For most cases, especially when you are still learning the toolkit, I would tend to agree with valmynd that GtkApplication is unnecessarily complicated. GtkAp... |
Remove duplicates from list, including original matching item | 20,908,337 | 4 | 2014-01-03T16:33:37Z | 20,908,353 | 13 | 2014-01-03T16:34:35Z | [
"python",
"list",
"duplicates",
"duplicate-removal"
] | I tried searching and couldn't find this exact situation, so apologies if it exists already.
I'm trying to remove duplicates from a list as well as the original item I'm searching for. If I have this:
```
ls = [1, 2, 3, 3]
```
I want to end up with this:
```
ls = [1, 2]
```
I know that using set will remove duplic... | Use a list comprehension and `list.count`:
```
>>> ls = [1, 2, 3, 3]
>>> [x for x in ls if ls.count(x) == 1]
[1, 2]
>>>
```
Here is a [reference](http://docs.python.org/2/tutorial/datastructures.html#data-structures) on both of those.
---
**Edit:**
@Anonymous made a good point below. The above solution is perfect ... |
how to speed up a vector cross product calculation | 20,908,754 | 7 | 2014-01-03T16:55:14Z | 20,910,319 | 14 | 2014-01-03T18:25:29Z | [
"python",
"performance",
"numpy",
"outer-join"
] | Hi I'm relatively new here and trying to do some calculations with numpy. I'm experiencing a long elapse time from one particular calculation and can't work out any faster way to achieve the same thing.
Basically its part of a ray triangle intersection algorithm and I need to calculate all the vector cros products fro... | If you look at [the source code](https://github.com/numpy/numpy/blob/v1.8.0/numpy/core/numeric.py#L1358) of `np.cross`, it basically moves the `xyz` dimension to the front of the shape tuple for all arrays, and then has the calculation of each of the components spelled out like this:
```
x = a[1]*b[2] - a[2]*b[1]
y = ... |
Error when writing python pandas dataframe to csv file | 20,908,786 | 8 | 2014-01-03T16:56:41Z | 20,908,982 | 12 | 2014-01-03T17:06:53Z | [
"python",
"pandas",
"export-to-csv"
] | I have a problem writing a Pandas dataframe to a csv file. I guess there are som characters that can not be translated but I do not know how to fix the problem. I need help on this.
Here is my simple call and the error message:
```
big_frame.to_csv('C:\DRO\test.csv')
```
error:
```
C:\Python27\lib\site-packages\pan... | Try using a different file encoding:
`big_frame.to_csv('C:\DRO\test.csv', encoding='utf-8')` |
Getting Python version using Go | 20,909,598 | 6 | 2014-01-03T17:43:58Z | 20,909,764 | 8 | 2014-01-03T17:52:13Z | [
"python",
"go"
] | I'm trying to get my Python version using Go:
```
import (
"log"
"os/exec"
"strings"
)
func verifyPythonVersion() {
_, err := exec.LookPath("python")
if err != nil {
log.Fatalf("No python version located")
}
out, err := exec.Command("python", "--version").Output()
log.Print(ou... | ```
$ python --version
Python 2.7.2
$ python --version 1>/dev/null # hide stdout
Python 2.7.2
$ python --version 2>/dev/null # hide stderr
```
We can conclude that the output goes to stderr. Now I took a look at Go's docs, and guess what, `cmd.Output` only captures stdout ([docs](http://golang.org/pkg/os/exec/#Cmd.Out... |
concatenate strings based on ints from a list | 20,909,632 | 3 | 2014-01-03T17:45:51Z | 20,909,679 | 9 | 2014-01-03T17:47:55Z | [
"python"
] | I had a similar question [here](http://stackoverflow.com/questions/20908669/join-list-of-lists-the-proper-way) but it's a different issue. I have two lists. list0 is a list of strings and list1 is a list of lists consisting of ints.
```
# In this example are 8 strings
list0 = ["Test", "Test2", "More text", "Te... | Use list comprehensions and `str.join()`:
```
new_list = [''.join([list0[i] for i in indices]) for indices in list1]
```
Demo:
```
>>> list0 = ["Test", "Test2", "More text", "Test123", "ttt", "abc", "okokok", "Hello"]
>>> list1 = [ [0, 1], [2], [3], [4,5,6], [7]]
>>> [''.join([list0[i] for i in indices]) for indices... |
Loop over two generator together | 20,910,213 | 6 | 2014-01-03T18:18:48Z | 20,910,242 | 16 | 2014-01-03T18:20:23Z | [
"python",
"loops",
"for-loop",
"generator",
"yield"
] | I have two generators say `A()` and `B()`. I want to iterate over both the generators together. Something like:
```
for a,b in A(),B(): # I know this is wrong
#do processing on a and b
```
One way is to store the results of both the functions in lists and then loop over the merged list. Something like this:
`... | You were *almost* there. In Python 3, just pass the generators to `zip()`:
```
for a, b in zip(A(), B()):
```
`zip()` takes any iterable, not just lists. It will consume the generators one by one.
In Python 2, use [`itertools.izip()`](http://docs.python.org/2/library/itertools.html#itertools.izip):
```
from itertoo... |
Choose random seed and save it | 20,911,147 | 6 | 2014-01-03T19:20:04Z | 20,911,799 | 7 | 2014-01-03T20:04:14Z | [
"python",
"numpy"
] | I would like to choose a random seed for `numpy.random` and save it to a variable. I can set the seed using `numpy.random.seed(seed=None`) but how do you get numpy to choose a random seed and tell you what it is?
Number seems to use `/dev/urandom` on linux by default. | The full state of the [MT19937](http://en.wikipedia.org/wiki/Mersenne_twister) PRNG that underlies `RandomState` cannot be contained in a single (normally-sized, e.g. 32-bit or 64-bit) integer. It has an array of 624 32-bit integers for its state. Seeding with an integer actually runs a smaller, simpler PRNG to generat... |
why does from `from itertools import chain` works but not `import itertools.chain as chain`? | 20,912,088 | 3 | 2014-01-03T20:22:57Z | 20,912,113 | 8 | 2014-01-03T20:24:24Z | [
"python",
"import",
"itertools"
] | Why does the following work:
```
from itertools import chain
```
but the following does not?
```
import itertools.chain as chain
``` | The `import foo.bar` syntax can only be used to import a module from a package, not an object in a module. `from foo import bar` can be used to import a module from a package or an object from a module. |
remove stopwords and tokenize for collocationbigramfinder NLTK | 20,912,364 | 2 | 2014-01-03T20:43:00Z | 20,919,649 | 7 | 2014-01-04T10:20:32Z | [
"python",
"nltk",
"tokenize",
"stop-words"
] | I keep getting this error
```
sub
return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or buffer
```
when i try to run this script. Not sure what is wrong. I am essentially reading from a text file, filtering out the stopwords and tokenizing them using NLTK.
```
import nltk
from nl... | I am presuming that sentiment\_test.txt is just plain text, and not a specific format.
You are trying to filter lines and not words. You should first tokenize and then filter the stopwords.
```
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
stopset = set(stopwords.words('english'))
with op... |
Is there a way to automatically close a Python temporary file returned by mkstemp() | 20,912,896 | 2 | 2014-01-03T21:21:16Z | 20,912,974 | 11 | 2014-01-03T21:26:58Z | [
"python",
"mkstemp"
] | Normally I process files in Python using a with statement, as in this chunk for downloading a resource via HTTP:
```
with (open(filename), "wb"):
for chunk in request.iter_content(chunk_size=1024):
if chunk:
file.write(chunk)
file.flush()
```
But this assumes I know the filename. S... | The *simplest* coding pattern for this is `try:`/`finally:`:
```
fd, pathname = tempfile.mkstemp()
try:
dostuff(fd)
finally:
os.close(fd)
```
However, if you're doing this more than once, it's trivial to wrap it up in a context manager:
```
@contextlib.contextmanager
def mkstemping(*args):
fd, pathname =... |
color detection using opencv python | 20,912,948 | 10 | 2014-01-03T21:25:22Z | 21,073,548 | 12 | 2014-01-12T10:22:23Z | [
"python",
"opencv"
] | I am trying to run a script written using opencv in python which uses webcam to track colored objects (here the object is blue colored), which is also mentioned in opencv's documentation [here](https://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_imgproc/py_colorspaces/py_colorspaces.html#converting... | The range of blue color in HSV should be given as :
```
lower_blue = np.array([110, 50, 50], dtype=np.uint8)
upper_blue = np.array([130,255,255], dtype=np.uint8)
``` |
Test if an internet connection is present in python | 20,913,411 | 11 | 2014-01-03T21:57:16Z | 20,913,928 | 17 | 2014-01-03T22:31:40Z | [
"python",
"python-2.7",
"networking"
] | I have the following code that checks if an internet connection is present.
```
import urllib2
def internet_on():
try:
response=urllib2.urlopen('http://74.125.228.100',timeout=20)
return True
except urllib2.URLError as err: pass
return False
```
This will test for an internet connection, ... | My approach would be something like this:
```
import socket
REMOTE_SERVER = "www.google.com"
def is_connected():
try:
# see if we can resolve the host name -- tells us if there is
# a DNS listening
host = socket.gethostbyname(REMOTE_SERVER)
# connect to the host -- tells us if the host is actually
... |
Python multiprocessing pool, join; not waiting to go on? | 20,914,828 | 8 | 2014-01-03T23:47:59Z | 20,915,149 | 11 | 2014-01-04T00:21:33Z | [
"python",
"python-2.7",
"multiprocessing"
] | (1) I'm trying to use `pool.map` followed by `pool.join()`, but python doesn't seem to be waiting for `pool.map` to finish before going on past the `pool.join()`. Here's a simple example of what I've tried:
```
from multiprocessing import Pool
foo = {1: []}
def f(x):
foo[1].append(x)
print foo
def main():
... | This is not the correct way to use `map`.
1. Using a global variable that way is absolutely wrong. Processes do not share the same memory (normally) so every `f` will have his own copy of `foo`. To share a variable between differente process you should use a `Manager`
2. Function passed to `map` are, usually, expected... |
Speedup scipy griddata for multiple interpolations between two irregular grids | 20,915,502 | 10 | 2014-01-04T01:02:51Z | 20,930,910 | 17 | 2014-01-05T06:41:39Z | [
"python",
"numpy",
"scipy"
] | I have several values that are defined on the same irregular grid (x, y, z) that I want to interpolate onto a new grid (x1, y1, z1). I.e I have f(x, y, z), g(x, y, z), h(x, y, z) and I want to calculate f(x1, y1, z1), g(x1, y1, z1), h(x1, y1, z1).
At the moment I am doing this using scipy.interpolate.griddata and it w... | There are several things going on every time you make a call to `scipy.interpolate.griddata`:
1. First, a call to `sp.spatial.qhull.Dealunay` is made to triangulate the irregular grid coordinates.
2. Then, for each point in the new grid, the triangulation is searched to find in which triangle (actually, in which simpl... |
Cannot create virtualenv instance in python 2.7.5 because of pip installation error | 20,916,712 | 12 | 2014-01-04T04:06:54Z | 20,926,173 | 23 | 2014-01-04T20:12:04Z | [
"python",
"flask",
"virtualenv",
"pip"
] | I'm trying to follow the directions on the Flask installation website but I encountered an error after I used "sudo easy\_install virtualenv" to install virtual environment. Not sure
```
Opals-MacBook-Pro:~ opalkale$ mkdir myproject
Opals-MacBook-Pro:~ opalkale$ cd myproject
Opals-MacBook-Pro:myproject opalkale$ virtu... | This is logged as an [issue](https://github.com/pypa/virtualenv/issues/524) with the recently released virtualenv 1.11. I had similar issues on Windows with this release.
I believe installing virtualenv 1.10.1 will let you continue working until this issue is addressed. |
When python descriptor method would be called? | 20,919,168 | 2 | 2014-01-04T09:25:26Z | 20,919,274 | 8 | 2014-01-04T09:37:00Z | [
"python",
"descriptor"
] | I simulate some data using python descriptor.
```
class Number:
def __init__(self):
self.num = 0
def __get__(self, instance, obj):
print("is getting number")
return self.number
def __set__(self, instance, value):
print("is setting number")
self.number = value
... | Your descriptors are not being called, and there is no way to write a descriptor or anything else to do what you seem to want.
When you do `num = 2`, you have thrown away your `Number` object and set the variable `num` to the ordinary number 2. When you then add 7 to it, it equals 9, because it's just a regular number... |
negation of list in python | 20,919,847 | 2 | 2014-01-04T10:38:02Z | 20,919,854 | 17 | 2014-01-04T10:38:37Z | [
"python",
"list"
] | I have a list :
```
v=[0, -0.01, 0, 0, 0.01, 0.25, 1]
```
I wanted the list to be :
```
v=[0, 0.01, 0, 0, -0.01, -0.25, -1]
```
which is the best way to do that? -v wont work. | Using list comprehension:
```
>>> v=[0, -0.01, 0, 0, 0.01, 0.25, 1]
>>> [-x for x in v]
[0, 0.01, 0, 0, -0.01, -0.25, -1]
```
Using [`map`](http://docs.python.org/2/library/functions.html#map) with [`operator.neg`](http://docs.python.org/2/library/operator.html#operator.neg):
```
>>> import operator
>>> map(operator... |
Python, what does an underscore before parenthesis do | 20,920,956 | 11 | 2014-01-04T12:26:55Z | 20,920,984 | 8 | 2014-01-04T12:29:34Z | [
"python",
"syntax"
] | Looking through some of the Django code at authentication forms I noticed the following syntax
```
label=_("Username")
```
Normally I would have just used a pair of quotes around the string. Can someone exaplain to me what the underscore and parenthesis around "Username" do? | The underscore is just another Python object, but by convention the `gettext` library scans for it to find translatable text.
Usually it is bound to the `ugettext` callable:
```
from django.utils.translation import ugettext as _
```
See [the translation chapter](https://docs.djangoproject.com/en/1.6/topics/i18n/tran... |
Python, what does an underscore before parenthesis do | 20,920,956 | 11 | 2014-01-04T12:26:55Z | 20,921,011 | 18 | 2014-01-04T12:31:40Z | [
"python",
"syntax"
] | Looking through some of the Django code at authentication forms I noticed the following syntax
```
label=_("Username")
```
Normally I would have just used a pair of quotes around the string. Can someone exaplain to me what the underscore and parenthesis around "Username" do? | The `_` is the name of a callable (function, [callable object](http://stackoverflow.com/questions/111234/what-is-a-callable-in-python)). It's usually used for the `gettext` function, [for example in Django](https://docs.djangoproject.com/en/stable/topics/i18n/translation/#standard-translation):
```
from django.utils.... |
UnicodeEncodeError: 'ascii' codec can't encode character in position 0: ordinal not in range(128) | 20,923,663 | 20 | 2014-01-04T16:39:19Z | 20,923,794 | 15 | 2014-01-04T16:51:19Z | [
"python",
"encoding",
"python-3.2"
] | I'm working on a Python script that uses the scissor character (9986 - â) and I'm trying to port my code to Mac, but I'm running into this error.
The scissor character shows up fine when run from IDLE (Python 3.2.5 - OS X 10.4.11 iBook G4 PPC) and the code works entirely fine on Ubuntu 13.10, but when I attempt to r... | When Python prints and output, it automatically encodes it to the target medium. If it is a file, UTF-8 will be used as default and everyone will be happy, but if it is a terminal, Python will figure out the encoding the terminal is using and will try to encode the output using that one.
This means that if your termin... |
UnicodeEncodeError: 'ascii' codec can't encode character in position 0: ordinal not in range(128) | 20,923,663 | 20 | 2014-01-04T16:39:19Z | 20,923,915 | 10 | 2014-01-04T17:01:19Z | [
"python",
"encoding",
"python-3.2"
] | I'm working on a Python script that uses the scissor character (9986 - â) and I'm trying to port my code to Mac, but I'm running into this error.
The scissor character shows up fine when run from IDLE (Python 3.2.5 - OS X 10.4.11 iBook G4 PPC) and the code works entirely fine on Ubuntu 13.10, but when I attempt to r... | [`test_io_encoding.py`](https://gist.github.com/zed/5898423) output suggests that you should change your `locale` settings e.g., set `LANG=en_US.UTF-8`.
---
The first error might be due to you are trying to decode a string that is already Unicode. Python 2 tries to encode it using a default character encoding (`'asci... |
Python conversion between coordinates | 20,924,085 | 19 | 2014-01-04T17:15:33Z | 26,757,297 | 24 | 2014-11-05T12:31:47Z | [
"python",
"coordinate-systems"
] | Are there functions for conversion between different coordinate systems?
For example, Matlab has `[rho,phi] = cart2pol(x,y)` for conversion from cartesian to polar coordinates. Seems like it should be in numpy or scipy. | Using numpy, you can define the following:
```
import numpy as np
def cart2pol(x, y):
rho = np.sqrt(x**2 + y**2)
phi = np.arctan2(y, x)
return(rho, phi)
def pol2cart(rho, phi):
x = rho * np.cos(phi)
y = rho * np.sin(phi)
return(x, y)
``` |
trouble with creating a virtual environment in Windows 8, python 3.3 | 20,925,329 | 7 | 2014-01-04T18:58:57Z | 20,959,427 | 20 | 2014-01-06T21:16:49Z | [
"python",
"virtualenv",
"pip",
"windows-8.1",
"setuptools"
] | I'm trying to create a virtual environment in Python, but I always get an error no matter how many times I re-install python-setuptools and pip.
My computer is running Windows 8, and I'm using Python 3.3.
```
E:\Documents\proj>virtualenv venv --distribute
Using base prefix 'c:\\Python33'
New python executable in venv... | I've found a solution to this problem. Only the latest virtualenv (v1.11) which was released just a few days ago has this problem. Remove the egg from your site-packages folder and install the previous version via `easy_install virtualenv==1.10.1`, virtualenv will work fine. |
Python check if function exists without try | 20,926,909 | 13 | 2014-01-04T21:21:28Z | 20,926,976 | 19 | 2014-01-04T21:28:27Z | [
"python",
"function",
"python-2.7",
"try-catch"
] | In python how do you check if a function exists without actually running the function (i.e. using try)? I would be testing if it exists in a module. | You can use [`dir`](http://docs.python.org/2.7/library/functions.html#dir) to check if a name is in a module:
```
>>> import os
>>> "walk" in dir(os)
True
>>>
```
In the sample code above, we test for the [`os.walk`](http://docs.python.org/2/library/os.html#os.walk) function. |
Python: how to normalize a confusion matrix? | 20,927,368 | 5 | 2014-01-04T22:10:34Z | 20,934,655 | 10 | 2014-01-05T14:22:24Z | [
"python",
"matrix",
"normalization",
"scikit-learn"
] | I calculated a confusion matrix for my classifier using the method confusion\_matrix() from the sklearn package. The diagonal elements of the confusion matrix represent the number of points for which the predicted label is equal to the true label, while off-diagonal elements are those that are mislabeled by the classif... | Suppose that
```
>>> y_true = [0, 0, 1, 1, 2, 0, 1]
>>> y_pred = [0, 1, 0, 1, 2, 2, 1]
>>> C = confusion_matrix(y_true, y_pred)
>>> C
array([[1, 1, 1],
[1, 2, 0],
[0, 0, 1]])
```
Then, to find out how many samples per class have received their correct label, you need
```
>>> C / C.astype(np.float).sum(... |
Input and output numpy arrays to h5py | 20,928,136 | 22 | 2014-01-04T23:41:12Z | 20,938,742 | 47 | 2014-01-05T20:27:49Z | [
"python",
"arrays",
"numpy",
"h5py"
] | I have a Python code whose output is a  sized matrix, whose entries are all of the type `float`. If I save it with the extension `.dat` the file size is of the order of 500 MB. I read that using `h5py` reduces the file size considerably. So, let's say I... | h5py provides a model of **datasets** and **groups**. The former is basically arrays and the latter you can think of as directories. Each is named. You should look at the documentation for the API and examples:
<http://docs.h5py.org/en/latest/quick.html>
A simple example where you are creating all of the data upfront... |
Conda: installing local development package into single conda environment | 20,928,566 | 9 | 2014-01-05T00:34:47Z | 20,928,632 | 7 | 2014-01-05T00:41:57Z | [
"python",
"pip",
"anaconda",
"conda"
] | If I were using a virtualenv, I would activate my project's virtual environment then install the package I am developing in develop mode. Something like the following:
```
workon superbad
pip install -e fnawesome
```
This allows my package `fnawesome` to be accessible with any code updates in my `superbad` virtual en... | Okay, I figured out the issue behind the question.
If you create a conda environment, make sure to include pip and ipython. Otherwise, it will not setup the path to point to environment specific versions of these utilities.
so:
```
conda create -n superbad scikit-learn
source activate superbad
pip install -e fnaweso... |
Conda: installing local development package into single conda environment | 20,928,566 | 9 | 2014-01-05T00:34:47Z | 20,958,097 | 12 | 2014-01-06T19:53:55Z | [
"python",
"pip",
"anaconda",
"conda"
] | If I were using a virtualenv, I would activate my project's virtual environment then install the package I am developing in develop mode. Something like the following:
```
workon superbad
pip install -e fnawesome
```
This allows my package `fnawesome` to be accessible with any code updates in my `superbad` virtual en... | You can configure a list of default packages that will be installed into any conda environment automatically
```
conda config --add create_default_packages pip --add create_default_packages ipython
```
will make it so that `conda create` will always include `pip` and `ipython` in new environments (this command is the... |
Python TfidfVectorizer throwing : empty vocabulary; perhaps the documents only contain stop words" | 20,928,769 | 3 | 2014-01-05T01:00:51Z | 20,933,883 | 10 | 2014-01-05T13:06:10Z | [
"python",
"pandas",
"scikit-learn",
"tf-idf"
] | I'm trying to use Python's Tfidf to transform a corpus of text.
However, when I try to fit\_transform it, I get a value error ValueError: empty vocabulary; perhaps the documents only contain stop words.
```
In [69]: TfidfVectorizer().fit_transform(smallcorp)
------------------------------------------------------------... | I guess it's because you just have one string. Try splitting it into a list of strings, e.g.:
```
In [51]: smallcorp
Out[51]: 'Ah! Now I have done Philosophy,\nI have finished Law and Medicine,\nAnd sadly even Theology:\nTaken fierce pains, from end to end.\nNow here I am, a fool for sure!\nNo wiser than I was before:... |
What is an (int) prefix on floating point arithmetic actually doing? | 20,928,799 | 3 | 2014-01-05T01:04:41Z | 20,928,814 | 9 | 2014-01-05T01:07:15Z | [
"python",
"python-2.7"
] | In some sample code I see this syntax being used:
```
float1 = 7.0
float2 = 2.0
result = (int)(float1/float2)
```
The point seems to be to force the result to an integer, but I can't find any place that documents the `(int)` syntax being used, or why it would be preferable to `int(float1/float2)`. A call to int() its... | Whoever wrote that code had too much exposure to languages that are more closely related to C than Python is. In C, C++, Java, C# and others, `(int)something` is the syntax to cast `something` to `(int)`. In Python, it's just a strange way to spell `int(something)`. `int` is the builtin function which converts `somethi... |
How to repeat a block in a jinja2 template? | 20,929,241 | 13 | 2014-01-05T02:16:32Z | 20,929,334 | 27 | 2014-01-05T02:31:53Z | [
"python",
"templates",
"jinja2"
] | I'm using [Jinja2](http://jinja.pocoo.org/docs/) as the template engine to a static HTML site generated through a Python script.
I want to repeat the content of a block in the layout template, which goes something like this:
```
<html>
<head>
<title>{% block title %}{% endblock %} - {{ sitename }}</title>
</head>... | Use the [special `self` variable](http://jinja.pocoo.org/docs/templates/#child-template) to access the block by name:
```
<title>{% block title %}{% endblock %} - {{ sitename }}</title>
<!-- ... snip ... -->
<h1>{{ self.title() }}</h1>
``` |
Resizing numpy.memmap arrays | 20,932,361 | 20 | 2014-01-05T10:14:22Z | 21,012,153 | 10 | 2014-01-09T05:19:09Z | [
"python",
"arrays",
"numpy",
"resize",
"mmap"
] | I'm working with a bunch of large numpy arrays, and as these started to chew up too much memory lately, I wanted to replace them with `numpy.memmap` instances. The problem is, now and then I have to resize the arrays, and I'd preferably do that inplace. This worked quite well with ordinary arrays, but trying that on me... | The issue is that the flag OWNDATA is False when you create your array. You can change that by requiring the flag to be True when you create the array:
```
>>> a = np.require(np.memmap('bla.bin', dtype=int), requirements=['O'])
>>> a.shape
(10,)
>>> a.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : True
OWNDATA : True
... |
Creating a tastypie resource for a "singleton" non-model object | 20,933,214 | 8 | 2014-01-05T11:51:43Z | 21,169,139 | 8 | 2014-01-16T17:47:32Z | [
"python",
"django",
"rest",
"tastypie"
] | I'm using tastypie and I want to create a `Resource` for a "singleton" non-model object.
For the purposes of this question, let's assume what I want the URL to represent is some system settings that exist in an `ini` file.
What this means is that...:
1. The fields I return for this URL will be custom created for this... | You should be able to achieve this with the following. Note I haven't actually tested this, so some tweaking may be required. A more rich example can be found in the [Tastypie Docs](http://django-tastypie.readthedocs.org/en/latest/non_orm_data_sources.html)
```
class SettingsResource(Resource):
value = fields.Char... |
Changing static variable from instance method in Python | 20,934,109 | 2 | 2014-01-05T13:30:02Z | 20,934,149 | 7 | 2014-01-05T13:33:13Z | [
"python"
] | I am trying to change a static variable in python
```
>>> class A():
... i = 0
... def add_i(self):
... self.i = self.i + 1
...
>>> A.i
0
>>> a = A()
>>> a.add_i()
>>> A.i
0
>>> a.i
1
```
When I call `a.add_i()`, why is it not incrementing the 'static' variable `i`? | When you assign to `self.i`, you are creating a new *instance* variable called `i`:
```
>>> print id(A.i), id(a.i)
9437588 9437576
```
The following will change `A.i` instead of rebinding `a.i`:
```
A.i = A.i + 1
```
or, shorter:
```
A.i += 1
``` |
how do I redraw an image using python's matplotlib? | 20,936,817 | 7 | 2014-01-05T17:34:47Z | 20,937,428 | 8 | 2014-01-05T18:29:37Z | [
"python",
"matplotlib",
"imshow"
] | What I am trying to do seems to be fairly straightforward, but I'm having a heck of a time trying to get it to work. I am simply trying to draw an image using imshow and then re-draw it periodically as new data arrives.
I've started out with this:
```
fig = figure()
ax = plt.axes(xlim=(0,200),ylim=(0,200))
myimg = ax... | You can simply call figure.canvas.draw() each time you append something new to the figure. This will refresh the plot.
```
from matplotlib import pyplot as plt
f = plt.figure()
ax = f.gca()
f.show()
for i in range(10):
ax.plot(i, i, 'ko')
f.canvas.draw()
raw_input('pause : press any key ...')
f.close()
`... |
How can I create a random number that is cryptographically secure in python? | 20,936,993 | 31 | 2014-01-05T17:51:07Z | 20,937,025 | 26 | 2014-01-05T17:53:44Z | [
"python",
"random",
"cryptography"
] | I'm making a project in python and I would like to create a random number that is cryptographically secure, How can I do that? I have read online that the numbers generated by the regular randomizer are not cryptographically secure, and that the function `os.urandom(n)` returns me a string, and not a number. | You can get a list of random numbers by just applying [`ord`](https://docs.python.org/2/library/functions.html#ord) function over the bytes returned by [`os.urandom`](https://docs.python.org/2/library/os.html#os.urandom), like this
```
>>> import os
>>> os.urandom(10)
'm\xd4\x94\x00x7\xbe\x04\xa2R'
>>> type(os.urandom... |
How can I create a random number that is cryptographically secure in python? | 20,936,993 | 31 | 2014-01-05T17:51:07Z | 20,937,265 | 28 | 2014-01-05T18:14:22Z | [
"python",
"random",
"cryptography"
] | I'm making a project in python and I would like to create a random number that is cryptographically secure, How can I do that? I have read online that the numbers generated by the regular randomizer are not cryptographically secure, and that the function `os.urandom(n)` returns me a string, and not a number. | Since you want to generate integers in some specific range, it's a lot easier to use the `random.SystemRandom` class instead. Creating an instance of that class gives you an object that supports all the methods of the `random` module, but using `os.urandom()` under the covers. Examples:
```
>>> from random import Syst... |
time zone "Eastern Standard Time" not recognized | 20,937,499 | 6 | 2014-01-05T18:35:25Z | 21,461,967 | 10 | 2014-01-30T16:25:41Z | [
"python",
"django",
"timezone",
"views"
] | I keep getting this error:
> time zone "Eastern Standard Time" not recognized
here is the code:
```
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super(IndexView, self).get_context_data(**kwargs)
"""Return the last five published posts."""
conte... | Installed `pytz` and the error went away:
```
pip install pytz
```
This may be a Windows only issue, see the note <https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-TIME_ZONE>. |
how to display pandas DataFrame using a format string for columns? | 20,937,538 | 38 | 2014-01-05T18:39:43Z | 20,937,592 | 61 | 2014-01-05T18:44:21Z | [
"python",
"python-2.7",
"pandas",
"ipython",
"dataframe"
] | I would like to display a pandas dataframe with a given format using `print()` and the IPython `display()`. For example:
```
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
index=['foo','bar','baz','quux'],
columns=['cost'])
print df
cost
foo 123.4567
bar 2... | ```
import pandas as pd
pd.options.display.float_format = '${:,.2f}'.format
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
index=['foo','bar','baz','quux'],
columns=['cost'])
print(df)
```
yields
```
cost
foo $123.46
bar $234.57
baz $345.68
quux $456.79
```
... |
how to display pandas DataFrame using a format string for columns? | 20,937,538 | 38 | 2014-01-05T18:39:43Z | 23,922,119 | 27 | 2014-05-28T21:24:04Z | [
"python",
"python-2.7",
"pandas",
"ipython",
"dataframe"
] | I would like to display a pandas dataframe with a given format using `print()` and the IPython `display()`. For example:
```
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
index=['foo','bar','baz','quux'],
columns=['cost'])
print df
cost
foo 123.4567
bar 2... | If you don't want to modify the dataframe, you could use a custom formatter for that column.
```
import pandas as pd
pd.options.display.float_format = '${:,.2f}'.format
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
index=['foo','bar','baz','quux'],
columns=['cost'])
... |
Parsing iCal feed with Python using icalendar | 20,937,754 | 7 | 2014-01-05T18:59:55Z | 20,941,078 | 13 | 2014-01-06T00:31:24Z | [
"python",
"icalendar"
] | I'm trying to parse a feed with multiple events using the icalendar lib in python.
'summary' , 'description' and so on works fine, but for 'dtstart' and 'dtend' it's returning me:
`icalendar.prop.vDDDTypes object at 0x101be62d0`
```
def calTest():
req = urllib2.Request('https://www.google.com/calendar/ical/XXXXXX... | The objects representing `dtstart` and `dtend` have an attribute `dt` which contains a standard `datetime.datetime` object.
```
start = event.get('dtstart')
print(start.dt)
``` |
Does Python support multithreading? Can it speed up execution time? | 20,939,299 | 23 | 2014-01-05T21:17:12Z | 20,939,442 | 31 | 2014-01-05T21:31:22Z | [
"python",
"multithreading"
] | I'm slightly confused about whether multithreading works in Python or not.
I know there has been a lot of questions about this and I've read many of them, but I'm still confused. I know from my own experience and have seen others post their own answers and examples here on StackOverflow that multithreading is indeed p... | The GIL does not prevent threading. All the GIL does is make sure only one thread is executing Python code at a time; control still switches between threads.
What the GIL prevents then, is making use of more than one CPU core or separate CPUs to run threads in parallel.
This only applies to Python code. C extensions ... |
Empty a variable without destroying it | 20,939,808 | 7 | 2014-01-05T22:05:40Z | 20,939,844 | 17 | 2014-01-05T22:07:52Z | [
"python",
"variables"
] | I have this piece of code:
```
a = "aa"
b = 1
c = { "b":2 }
d = [3,"c"]
e = (4,5)
letters = [a, b, c, d, e]
```
And I want to do something with it, which will empty them. Without losing their type.
Something like this:
```
>>EmptyVars(letters)
['',0,{},[],()]
```
Any hint? | Do this:
```
def EmptyVar(lst):
return [type(i)() for i in lst]
```
`type()` produces the type object for each value, which when called produces an 'empty' new value.
Demo:
```
>>> a = "aa"
>>> b = 1
>>> c = { "b":2 }
>>> d = [3,"c"]
>>> e = (4,5)
>>> letters = [a, b, c, d, e]
>>> def EmptyVar(lst):
... ret... |
How to get if checkbox is checked on flask | 20,941,539 | 5 | 2014-01-06T01:27:11Z | 21,451,879 | 8 | 2014-01-30T09:04:31Z | [
"python",
"flask",
"twitter-bootstrap-3"
] | I'm using Bootstrap with Flask Python.
```
request.form.get("name")
#name is the name of the form element(checkbox)
<label class="btn btn-danger pzt active">
<input type="checkbox" name="name" value="1" data-id="0"> Check
</label>
```
When checkbox is checked, parent label has class "active", I want to get ... | you can try the following:
```
HTML:
<div class="checkbox">
<label>
<input type="checkbox" name="check" value="edit"> New entry
</label>
</div>
```
In flask:
```
value = request.form.getlist('check')
```
This will give you the value of the the checkbox. Here value will be a list.
```
value = [u'edit']
```
Y... |
Python - Decorators | 20,945,366 | 12 | 2014-01-06T07:50:04Z | 20,945,424 | 17 | 2014-01-06T07:54:14Z | [
"python",
"python-decorators"
] | I'm trying to learn [Decorators](http://www.artima.com/weblogs/viewpost.jsp?thread=240808) .
I understood the concept of it and now trying to implement it.
**Here is the code that I've written**
The code is self-explanatory. It just checks whether the argument passed in `int` or not.
```
def wrapper(func):
def in... | Your decorator should look like:
```
def wrapper(func):
def inner(x, y): # inner function needs parameters
if issubclass(type(x), int): # maybe you looked for isinstance?
return func(x, y) # call the wrapped function
else:
return 'invalid values'
return inner # return t... |
Can't install Pillow on centos | 20,945,610 | 4 | 2014-01-06T08:07:51Z | 20,945,731 | 10 | 2014-01-06T08:18:17Z | [
"python",
"setuptools",
"python-2.6",
"pillow"
] | I have cenots 6.3 and python 2.6 on it when I try to install it via easyinstall I get following error:
```
_imaging.c:76:20: error: Python.h: No such file or directory
In file included from /tmp/easy_install-HY7WI1/Pillow-2.3.0/libImaging/Imaging.h:14,
from _imaging.c:82:
/tmp/easy_install-HY7WI1/Pill... | You need to install `python26-devel` before you can compile *any* Python extension.
To compile Pillow, you'll also need to install the development headers for various other libraries, including `libjpeg-devel` and `zlib-devel`. See the [Pillow installation instructions](http://pillow.readthedocs.org/en/latest/installa... |
How to access a sharepoint site via the REST API in Python? | 20,945,822 | 3 | 2014-01-06T08:24:55Z | 21,505,184 | 9 | 2014-02-01T23:43:35Z | [
"python",
"rest",
"authentication",
"sharepoint",
"sharepoint-2013"
] | I have the following site in SharePoint 2013 in my local VM:
`http://win-5a8pp4v402g/sharepoint_test/site_1/`
When I access this from the browser, it prompts me for the username and password and then works fine. However I am trying to do the same using the REST API in Python. I am using the requests library, and this... | It's possible that your SharePoint site uses a different authentication scheme. You can check this by inspecting the network traffic in Firebug or the Chrome Developer Tools.
Luckily, the requests library supports many authentication options: <http://docs.python-requests.org/en/latest/user/authentication/>
Fore examp... |
Convert a IP to Hex by Python | 20,948,393 | 5 | 2014-01-06T10:52:33Z | 20,948,457 | 9 | 2014-01-06T10:55:03Z | [
"python",
"string",
"python-2.7"
] | I am writing a script to convert a IP to HEX. Below is my script:
```
import string
ip = raw_input('Enter IP')
a = ip.split('.')
b = hex(int(a[0])) + hex(int(a[1])) + hex(int(a[2])) + hex(int(a[3]))
b = b.replace('0x', '')
b = b.upper()
print b
```
My Problem is that for IP like 115.255.8.97, I am getting this:
Answ... | [`hex`](http://docs.python.org/2/library/functions.html#hex) function does not pad with leading zero.
```
>>> hex(8).replace('0x', '')
'8'
```
Use [`str.format`](http://docs.python.org/2/library/stdtypes#str.format) with `02X` format specification:
```
>>> '{:02X}'.format(8)
'08'
>>> '{:02X}'.format(100)
'64'
```
-... |
ipython %store magic not working | 20,948,465 | 4 | 2014-01-06T10:55:30Z | 20,952,929 | 7 | 2014-01-06T15:09:33Z | [
"python",
"alias",
"ipython",
"ipython-magic"
] | I'm trying to get my ipython alias to be persistent, and according to the docs the %store magic function offers this feature. But it's not working for me.
```
wim@SDFA100461C:/tmp$ echo 'print("hello world!")' > test.py
wim@SDFA100461C:/tmp$ ipython
In [1]: alias potato python /tmp/test.py
In [2]: potato
hello world!... | You need to run [`%store -r`](https://github.com/ipython/ipython/blob/0ca701d56a2d12074b725d3fd99cacc30c5c62cb/IPython/extensions/storemagic.py#L106) to retrieve stored variables (and aliases).
Of course, you can add this to your ipython startup script. |
Changing Pipe separated data to Dataframe in Python Pandas | 20,949,955 | 3 | 2014-01-06T12:23:15Z | 20,950,081 | 9 | 2014-01-06T12:31:04Z | [
"python",
"pandas",
"dataframe"
] | I have pipe-separated values like this:
```
https|clients4.google.com|application/octet-stream|2296|
https|clients4.google.com|text/html; charset=utf-8|0|
....
....
https|clients4.google.com|application/octet-stream|2291|
```
I have to create a Pandas `DataFrame` out of this data, with each column given a name
Any h... | Here you go:
```
>>> import pandas as pd
>>> pd.read_csv('data.csv', sep='|', index_col=False,
names=['protocol', 'server', 'type', 'value'])
Out[7]:
protocol server type value
0 https clients4.google.com application/octet-stream 2296
1 http... |
How to sort Counter by value? - python | 20,950,650 | 21 | 2014-01-06T13:02:52Z | 20,950,686 | 42 | 2014-01-06T13:05:18Z | [
"python",
"sorting",
"collections",
"counter"
] | Other than doing list comprehensions of reversed list comprehension, is there a pythonic way to sort Counter by value? If so, it is faster than this:
```
>>> from collections import Counter
>>> x = Counter({'a':5, 'b':3, 'c':7})
>>> sorted(x)
['a', 'b', 'c']
>>> sorted(x.items())
[('a', 5), ('b', 3), ('c', 7)]
>>> [(l... | Use the [`Counter.most_common()` method](http://docs.python.org/2/library/collections.html#collections.Counter.most_common), it'll sort the items *for you*:
```
>>> from collections import Counter
>>> x = Counter({'a':5, 'b':3, 'c':7})
>>> x.most_common()
[('c', 7), ('a', 5), ('b', 3)]
```
It'll do so in the most eff... |
Is path broken for anaconda ipython? | 20,951,424 | 6 | 2014-01-06T13:51:11Z | 20,964,099 | 9 | 2014-01-07T04:46:35Z | [
"python",
"bash",
"ipython",
"anaconda"
] | I wish to use anaconda distribution of ipython, but typing `ipython` at the terminal produces an error message:
```
Traceback (most recent call last):
File "/usr/local/bin/ipython", line 5, in <module>
from pkg_resources import load_entry_point
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Ext... | Your problem is in your $PATH. If you look at your traceback, it's running /usr/local/bin/ipython - this is the one that is installed by Homebrew, and not by Anaconda. (Anaconda installs everything into /anaconda/bin.)
The reason this is getting picked up is because the very last line of your .bash\_profile sticks /us... |
Is it possible to embed python without the standard library? | 20,951,624 | 5 | 2014-01-06T14:02:54Z | 20,967,400 | 8 | 2014-01-07T08:53:53Z | [
"python",
"python-embedding"
] | Is it possible to embed python without the standard library?
I'm working with a [cmake build for python 2.7.6](https://github.com/shadowmint/cmake-python-embed-nostdlib) and I've got a basic embedded script running, like so:
```
#include <stdio.h>
#include <Python.h>
int main(int argc, char *argv[]) {
/* Setup */... | Simple answer is yes you can.
```
int main(int argc, char *argv[]) {
/* Setup */
Py_NoSiteFlag = 1; // <--- This
Py_SetProgramName(argv[0]);
Py_Initialize();
/* Run the 'main' module */
int rtn = Py_Main(argc, argv);
Py_Finalize();
return rtn;
}
```
As far as I can tell, nothing breaks and you can ... |
Most Pythonic for / enumerate loop? | 20,951,649 | 5 | 2014-01-06T14:04:12Z | 20,951,658 | 11 | 2014-01-06T14:04:47Z | [
"python"
] | I have a loop condition:
```
for count, item in enumerate(contents):
```
but only want to use the first 10 elements of contents. What is the most pythonic way to do so?
Doing a:
```
if count == 10: break
```
seems somewhat un-Pythonic. Is there a better way? | Use a slice (slice notation)
```
for count, item in enumerate(contents[:10]):
```
If you are iterating over a generator, or the items in your list are large and you don't want the overhead of creating a new list (as slicing does) you can use [`islice`](http://docs.python.org/2/library/itertools.html#itertools.islice)... |
pip installing in global site-packages instead of virtualenv | 20,952,797 | 40 | 2014-01-06T15:03:08Z | 20,954,767 | 34 | 2014-01-06T16:40:50Z | [
"python",
"osx",
"virtualenv",
"pip"
] | Using pip to install a package in a virtualenv causes the package to be installed in the global site-packages folder instead of the one in the virtualenv folder. Here's how I set up Python3 and virtualenv on OS X Mavericks (10.9.1):
I installed python3 using Homebrew:
```
ruby -e "$(curl -fsSL https://raw.github.com/... | Funny you brought this up, I just had the exact same problem. I solved it eventually, but I'm still unsure as to what caused it.
Try checking your `bin/pip` and `bin/activate` scripts. In `bin/pip`, look at the shebang. Is it correct? If not, correct it. Then on line ~`42` in your `bin/activate`, check to see if your ... |
pip installing in global site-packages instead of virtualenv | 20,952,797 | 40 | 2014-01-06T15:03:08Z | 24,001,948 | 13 | 2014-06-02T19:37:34Z | [
"python",
"osx",
"virtualenv",
"pip"
] | Using pip to install a package in a virtualenv causes the package to be installed in the global site-packages folder instead of the one in the virtualenv folder. Here's how I set up Python3 and virtualenv on OS X Mavericks (10.9.1):
I installed python3 using Homebrew:
```
ruby -e "$(curl -fsSL https://raw.github.com/... | For me this was not a pip or virtualenv problem. It was a python problem. I had set my $PYTHONPATH manually in ~/.bash\_profile (or ~/.bashrc) after following some tutorial online. This manually set $PYTHONPATH was available in the virtualenv as it probably should be allowed.
Additionally `add2virtualenv` was not addi... |
Why built-in functions like abs works on numpy array? | 20,953,127 | 11 | 2014-01-06T15:20:49Z | 20,953,194 | 16 | 2014-01-06T15:23:44Z | [
"python",
"arrays",
"numpy"
] | I feel surprised that `abs` works on numpy array but not on lists. Why is that?
```
import numpy as np
abs(np.array((1,-2)))
array([1, 2])
abs([1,-1])
TypeError: bad operand type for abs(): 'list'
```
Also, built in functions like `sum` also works on numpy array. I guess it is because numpy array supports `__getite... | That's because `numpy.ndarray` implements the `__abs__(self)` method. Just provide it for your own class, and `abs()` will magically work. For non-builtin types you can also provide this facility after-the-fact. E.g.
```
class A:
"A class without __abs__ defined"
def __init__(self, v):
self.v = v
def ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.