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 |
|---|---|---|---|---|---|---|---|---|---|
How do I write JSON data to a file in Python? | 12,309,269 | 287 | 2012-09-06T22:21:21Z | 20,776,329 | 81 | 2013-12-25T20:04:24Z | [
"python",
"json"
] | I have JSON data stored in the variable `data`.
I want to write this to a text file for testing so I don't have to grab the data from the server each time.
Currently, I am trying this:
```
obj = open('data.txt', 'wb')
obj.write(data)
obj.close
```
And am receiving the error:
```
TypeError: must be string or buffer... | I would answer with slight modification with aforementioned answers and that is to write a prettified JSON file which human eyes can read better. For this, pass `sort_keys` as `True` and `indent` with 4 space characters and you are good to go. Also take care of ensuring that the ascii codes will not be written in your ... |
How do I write JSON data to a file in Python? | 12,309,269 | 287 | 2012-09-06T22:21:21Z | 31,343,739 | 10 | 2015-07-10T14:45:29Z | [
"python",
"json"
] | I have JSON data stored in the variable `data`.
I want to write this to a text file for testing so I don't have to grab the data from the server each time.
Currently, I am trying this:
```
obj = open('data.txt', 'wb')
obj.write(data)
obj.close
```
And am receiving the error:
```
TypeError: must be string or buffer... | For those of you who are trying to dump greek or other "exotic" languages such as me but are also having problems (unicode errors) with weird characters such as the peace symbol (\u262E) or others which are often contained in json formated data such as Twitter's, the solution could be as follows (sort\_keys is obviousl... |
How do I write JSON data to a file in Python? | 12,309,269 | 287 | 2012-09-06T22:21:21Z | 34,574,105 | 7 | 2016-01-03T06:52:36Z | [
"python",
"json"
] | I have JSON data stored in the variable `data`.
I want to write this to a text file for testing so I don't have to grab the data from the server each time.
Currently, I am trying this:
```
obj = open('data.txt', 'wb')
obj.write(data)
obj.close
```
And am receiving the error:
```
TypeError: must be string or buffer... | I don't have enough reputation to add in comments, so I just write some of my findings of this annoying TypeError here:
Basically, I think it's a bug in the `json.dump()` function in Python **2** only - It can't dump a Python (dictionary / list) data containing non-ASCII characters, *even* you open the file with the `... |
How do I write JSON data to a file in Python? | 12,309,269 | 287 | 2012-09-06T22:21:21Z | 37,795,053 | 13 | 2016-06-13T16:43:33Z | [
"python",
"json"
] | I have JSON data stored in the variable `data`.
I want to write this to a text file for testing so I don't have to grab the data from the server each time.
Currently, I am trying this:
```
obj = open('data.txt', 'wb')
obj.write(data)
obj.close
```
And am receiving the error:
```
TypeError: must be string or buffer... | ## Writing data to a json file
Just like phiphags answer, but with nice formatting:
```
import json
data = {'key': 'value', 'whatever': [1, 42, 3.141, 1337]}
with open('data.json', 'w') as outfile:
json.dump(data, outfile, indent=4, sort_keys=True, separators=(',', ':'))
```
Explanation of the parameters of [`js... |
convert list into string with spaces in python | 12,309,976 | 20 | 2012-09-06T23:50:35Z | 12,309,982 | 45 | 2012-09-06T23:51:25Z | [
"python",
"string",
"list",
"spaces"
] | I have a question about how to convert a list into a string in python?
Let's say if I have
```
list = [how,are,you]
```
to a string `"how are you"`
The spaces are important, i don't want to get `howareyou` as I have with my attempt so far of using
```
"".join(list)
```
Thank you. | ```
" ".join(my_list)
```
you need to join with a space not an empty string ... |
Python counting elements of a list within a list | 12,310,141 | 4 | 2012-09-07T00:14:14Z | 12,310,146 | 7 | 2012-09-07T00:15:17Z | [
"python"
] | Say I have the following list:
```
L=[ [0,1,1,1],[1,0,1,1],[1,1,0,1],[1,1,1,0] ]
```
I want to write a code will take a list like this one and tell me if the number of '1s' in each individual list is equal to some number x. So if I typed in code(L,3) the return would be "True" because each list within L contains 3 '1... | To see if each sublist has 3 1's in it,
```
all( x.count(1) == 3 for x in L )
```
Or as a function:
```
def count_function(lst,number,value=1):
return all( x.count(value) == number for x in lst )
L=[ [0,1,1,1],[1,0,1,1],[1,1,0,1],[1,1,1,0] ]
print(count_function(L,3)) #True
print(count_function(L,4)) #False
pri... |
Print number in engineering format | 12,311,148 | 8 | 2012-09-07T03:00:21Z | 12,311,245 | 16 | 2012-09-07T03:16:10Z | [
"python",
"python-2.7",
"decimal"
] | I am trying to print a number into engineering format with python, but I cannot seem to get it to work. The syntax SEEMS simple enough, but it just doesn't work.
```
>>> import decimal
>>> x = decimal.Decimal(1000000)
>>> print x
1000000
>>>> print x.to_eng_string()
1000000
```
I cannot figure out why this is. The ... | To get this to work, you have to normalize the decimal first:
```
>>> x = decimal.Decimal ('10000000')
>>> x.normalize()
Decimal('1E+7')
>>> x.normalize().to_eng_string()
'10E+6'
```
---
The reason for this can be discovered by delving in to the source code.
If you examine `to_eng_string()` in the Python 2.7.3 so... |
Python Error: name 'admin' is not defined | 12,311,390 | 9 | 2012-09-07T03:38:26Z | 12,311,907 | 7 | 2012-09-07T04:52:10Z | [
"python",
"django",
"django-models",
"django-admin",
"django-urls"
] | I am creating a Python application in Django for the first time. I know that I must uncomment the admin tools in the urls.py, I have done that. I have also added `autodiscover`. Everytime I try to add a new feature to the administration panel, I get this error:
"NameError: name 'admin' is not defined"
Here is the cod... | `from django.config import admin` should be `from django.contrib import admin` |
How to plot files with numpy | 12,311,767 | 5 | 2012-09-07T04:32:30Z | 12,322,314 | 10 | 2012-09-07T16:51:39Z | [
"python",
"numpy",
"plot"
] | I have a .dat file that contains two columns of numbers so it looks something like this:
```
111 112
110.9 109
103 103
```
and so on.
I want to plot the two columns against one another. I have never dealt with a .dat file before so I am not sure where to start.
So far I figured out that numpy has something I... | Numpy doesn't support plotting by itself. You usually would use [`matplotlib`](http://matplotlib.sourceforge.net/) for plotting numpy arrays.
If you just want to "look into the file", I think the easiest way would be to use [`plotfile`](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.plotfile).... |
verify is a string is encoded in base64 python | 12,315,398 | 8 | 2012-09-07T09:30:27Z | 12,315,449 | 19 | 2012-09-07T09:32:39Z | [
"python",
"base64"
] | Is there a good way to verify if a string is encoded in base 64 with python?
Thank you | ```
import base64
import binascii
try:
base64.decodestring("foo")
except binascii.Error:
print "no correct base64"
``` |
append to list in defaultdict | 12,317,261 | 4 | 2012-09-07T11:30:41Z | 12,317,323 | 10 | 2012-09-07T11:33:43Z | [
"python",
"dictionary"
] | I'm trying to append objects to lists which are values in a defaultdict:
```
dic = defaultdict(list)
groups = ["A","B","C","D"]
# data_list is a list of objects from a self-defined class.
# Among others, they have an attribute called mygroup
for entry in data_list:
for mygroup in groups:
if entry.mygrou... | Try
```
if entry.mygroup == mygroup:
dic[mygroup].append(entry)
```
That's the same way you use `append` on any list. `append` doesn't return anything, so when you assign the result to `dic[mygroup]`, it turns into `None`. Next time you try to append to it, you get the error. |
urllib2.urlopen(): getting the size of the content | 12,317,493 | 5 | 2012-09-07T11:44:35Z | 12,317,574 | 15 | 2012-09-07T11:51:54Z | [
"python",
"urllib2"
] | Still working my way round python whenever work permits it...
I'm querying a load of internal webUI's using a script that uses `urllib2.urlopen`. I'm wondering how it is possible to get the size of the page content from each request. I can't seem to figure this one out.
Thanks in advance,
MHibbin | ```
print len(urlopen(url).read())
```
or
```
>>> result = urllib2.urlopen('http://www.spiegel.de')
>>> result.headers['content-length']
'181291'
``` |
Flask long routines | 12,317,667 | 5 | 2012-09-07T11:59:10Z | 12,318,574 | 9 | 2012-09-07T12:56:50Z | [
"python",
"flask",
"gunicorn",
"long-running-processes"
] | I have to do some long work in my Flask app. And I want to do it async. Just start working, and then check status from javascript.
I'm trying to do something like:
```
@app.route('/sync')
def sync():
p = Process(target=routine, args=('abc',))
p.start()
return "Working..."
```
But this it creates defunct... | There are many options. You can develop your own solution, use Celery or Twisted (I'm sure there are more already-made options out there but those are the most common ones).
Developing your in-house solution isn't difficult. You can use the `multiprocessing` module of the Python standard library:
* When a task arrive... |
Python threading: can I sleep on two threading.Event()s simultaneously? | 12,317,940 | 13 | 2012-09-07T12:01:21Z | 12,320,352 | 15 | 2012-09-07T14:44:02Z | [
"python",
"multithreading"
] | If I have two `threading.Event()` objects, and wish to sleep until either one of them is set, is there an efficient way to do that in python? Clearly I could do something with polling/timeouts, but I would like to really have the thread sleep until one is set, akin to how `select` is used for file descriptors.
So in t... | Here is a non-polling non-excessive thread solution: modify the existing `Event`s to fire a callback whenever they change, and handle setting a new event in that callback:
```
import threading
def or_set(self):
self._set()
self.changed()
def or_clear(self):
self._clear()
self.changed()
def orify(e, ... |
python replace multiple patterns in the lines of a file | 12,318,340 | 3 | 2012-09-07T12:41:10Z | 12,318,434 | 7 | 2012-09-07T12:46:47Z | [
"python",
"file"
] | Here is a problem which is annoying me during these last two hours.
I have a template file with multiple lines and in some lines some words have to be changed by some others. Here is how my template looks like:
```
subnet {{ MY_SUBNET }} netmask {{ MY_NETMASKÂ }} {}
subnet {{ MY_SUBNET }} netmask {{ MY_NETMASK }}
{
o... | @eumiro guessed right: one of your spaces isn't a space.
```
>>> repr('subnet {{ MY_SUBNET }} netmask {{ MY_NETMASKÂ }} {}')
"'subnet {{ MY_SUBNET }} netmask {{ MY_NETMASK\\xc2\\xa0}} {}'"
^^^^^^^^^^
```
Looks like a non-breaking space. |
Filters in Python | 12,319,025 | 42 | 2012-09-07T13:25:22Z | 12,319,034 | 73 | 2012-09-07T13:26:13Z | [
"python",
"list",
"filter"
] | I am learning the concept of filters in Python. I am running a simple code like this.
```
>>> def f(x): return x % 2 != 0 and x % 3 != 0
>>> filter(f, range(2, 25))
```
But instead of getting a list, I am getting some message like this.
```
<filter object at 0x00FDC550>
```
What does this mean? Does it means that m... | It looks like you're using python 3.x. In python3, `filter`, `map`, `zip`, etc return an object which is iterable, but not a list. In other words,
```
filter(func,data) #python 2.x
```
is equivalent to:
```
list(filter(func,data)) #python 3.x
```
I think it was changed because you (often) want to do the filtering i... |
Filters in Python | 12,319,025 | 42 | 2012-09-07T13:25:22Z | 12,319,040 | 13 | 2012-09-07T13:26:27Z | [
"python",
"list",
"filter"
] | I am learning the concept of filters in Python. I am running a simple code like this.
```
>>> def f(x): return x % 2 != 0 and x % 3 != 0
>>> filter(f, range(2, 25))
```
But instead of getting a list, I am getting some message like this.
```
<filter object at 0x00FDC550>
```
What does this mean? Does it means that m... | It's an [iterator](http://getpython3.com/diveintopython3/iterators.html) returned by the [filter](http://docs.python.org/release/3.0.1/library/functions.html#filter) function.
If you want a list, just do
```
list(filter(f, range(2, 25)))
```
Nonetheless, you can just iterate over this object with a `for` loop.
```
... |
Dynamically add/create subplots in matplotlib | 12,319,796 | 14 | 2012-09-07T14:10:16Z | 12,320,482 | 10 | 2012-09-07T14:50:53Z | [
"python",
"matplotlib"
] | I want to create a plot consisting of several subplots with shared x/y axes.
It should look something like this from the documentation (though my subplots will be scatterblots): [(code here)](http://matplotlib.sourceforge.net/mpl_examples/pylab_examples/subplots_demo.py)

y = np.sin(x**2)
subplots_adjust(hspace=0.000)
number_of_subplots=3
for i,v in enumerate(xrange(number_of_subplots)):
v = v+1
ax1 = subplot(number_of_subplots,1,v)
ax1.plot(x,y)
plt.show()
```
Th... |
How to use numpy.genfromtxt when first column is string and the remaining columns are numbers? | 12,319,969 | 30 | 2012-09-07T14:20:47Z | 12,320,403 | 36 | 2012-09-07T14:47:06Z | [
"python",
"numpy"
] | Basically, I have a bunch of data where the first column is a string (label) and the remaining columns are numeric values. I run the following:
```
data = numpy.genfromtxt('data.txt', delimiter = ',')
```
This reads most of the data well, but the label column just gets 'nan'. How can I deal with this? | By default, `np.genfromtxt` uses `dtype=float`: that's why you string columns are converted to NaNs because, after all, they're Not A Number...
You can ask `np.genfromtxt` to try to guess the actual type of your columns by using `dtype=None`:
```
>>> from StringIO import StringIO
>>> test = "a,1,2\nb,3,4"
>>> a = np.... |
How to use numpy.genfromtxt when first column is string and the remaining columns are numbers? | 12,319,969 | 30 | 2012-09-07T14:20:47Z | 12,320,831 | 17 | 2012-09-07T15:11:33Z | [
"python",
"numpy"
] | Basically, I have a bunch of data where the first column is a string (label) and the remaining columns are numeric values. I run the following:
```
data = numpy.genfromtxt('data.txt', delimiter = ',')
```
This reads most of the data well, but the label column just gets 'nan'. How can I deal with this? | If your data file is structured like this
```
col1, col2, col3
1, 2, 3
10, 20, 30
100, 200, 300
```
then `numpy.genfromtxt` can interpret the first line as column headers using the `names=True` option. With this you can access the data very conveniently by providing the column header:
```
data = np... |
gevent library: "Import Error: no module named greenlet" | 12,322,247 | 8 | 2012-09-07T16:46:28Z | 12,322,843 | 8 | 2012-09-07T17:36:10Z | [
"python",
"gevent"
] | hello guys I have downloaded a script that require gevent python library and every time I run the script it says :
```
File "shodan.py", line 7, in <module>
from gevent import monkey
File "C:\Python27\lib\site-packages\gevent\__init__.py", line 48, in <module>
from gevent.greenlet import Greenlet, joinall, kil... | Try to install `greenlet` via [pip](http://www.pip-installer.org/en/latest/index.html) like so: `pip install greenlet`. |
KDB+ like asof join for timeseries data in pandas? | 12,322,289 | 8 | 2012-09-07T16:49:21Z | 12,326,113 | 7 | 2012-09-07T22:16:09Z | [
"python",
"join",
"time-series",
"pandas",
"kdb"
] | kdb+ has an [aj](http://code.kx.com/wiki/Reference/aj) function that is usually used to join tables along time columns.
Here is an example where I have trade and quote tables and I get the prevailing quote for every trade.
```
q)5# t
time sym price size
-----------------------------
09:30:00.439 NVDA 13.42 ... | As you mentioned in the question, looping through each column should work for you:
```
df1.apply(lambda x: x.asof(df2.index))
```
We could potentially create a faster NaN-naive version of DataFrame.asof to do all the columns in one shot. But for now, I think this is the most straightforward way. |
KDB+ like asof join for timeseries data in pandas? | 12,322,289 | 8 | 2012-09-07T16:49:21Z | 12,336,039 | 11 | 2012-09-09T02:22:04Z | [
"python",
"join",
"time-series",
"pandas",
"kdb"
] | kdb+ has an [aj](http://code.kx.com/wiki/Reference/aj) function that is usually used to join tables along time columns.
Here is an example where I have trade and quote tables and I get the prevailing quote for every trade.
```
q)5# t
time sym price size
-----------------------------
09:30:00.439 NVDA 13.42 ... | I wrote an under-advertised `ordered_merge` function some time ago:
```
In [27]: quotes
Out[27]:
time bid ask bsize asize
0 2012-09-06 09:30:00.026000 13.34 13.44 3 16
1 2012-09-06 09:30:00.043000 13.34 13.44 3 17
2 2012-09-06 09:30:00.121000 13.36 13.65 1 ... |
Jenkins python api authentication "403 forbidden" | 12,322,668 | 2 | 2012-09-07T17:21:37Z | 14,278,804 | 8 | 2013-01-11T13:03:41Z | [
"python",
"jenkins",
"urllib2"
] | I'm trying to use [jenkinsapi python library](http://pypi.python.org/pypi/jenkinsapi) to work with Jenkins. My Jenkins is setup to authenticate with LDAP (with [Active Directory Plugin](https://wiki.jenkins-ci.org/display/JENKINS/Active+Directory+plugin)). However, when I run my script to authenticate I fails (actually... | Solution for this problem is to use different [python-jenkins module](http://packages.python.org/python-jenkins/)
With this module everything works fine:
```
import jenkins
j = jenkins.Jenkins(base_url, username, password)
``` |
How do I change the axis tick font in a matplotlib plot when rendering using Latex? | 12,322,738 | 13 | 2012-09-07T17:27:17Z | 12,323,891 | 13 | 2012-09-07T18:57:33Z | [
"python",
"latex",
"matplotlib"
] | The font of the axis tick mark labels produced from the following code isn't Helvetica, but is still the default serif Computer Modern. Any suggestions are greatly appreciated.
```
from matplotlib import rc, font_manager
from numpy import arange, cos, pi
from matplotlib.pyplot import figure, axes, plot, xlabel, ylabel... | Okay, this worked for me. Replace the following lines:
```
for label in ax.get_xticklabels():
label.set_fontproperties(ticks_font)
for label in ax.get_yticklabels():
label.set_fontproperties(ticks_font)
```
with this:
```
from matplotlib.pyplot import gca
a = gca()
a.set_xticklabels(a.get_xticks(), fontProp... |
How do I change the axis tick font in a matplotlib plot when rendering using Latex? | 12,322,738 | 13 | 2012-09-07T17:27:17Z | 16,345,065 | 12 | 2013-05-02T18:21:36Z | [
"python",
"latex",
"matplotlib"
] | The font of the axis tick mark labels produced from the following code isn't Helvetica, but is still the default serif Computer Modern. Any suggestions are greatly appreciated.
```
from matplotlib import rc, font_manager
from numpy import arange, cos, pi
from matplotlib.pyplot import figure, axes, plot, xlabel, ylabel... | I think the confusion here stems from the fact that you're mixing TeX and non-TeX font commands.
This turns on TeX mode, so all of the text is rendered with an external TeX installation:
```
rc('text', usetex=True)
```
In this line, setting it to sans-serif will get passed along to TeX, but a specific ttf font name ... |
From tick by tick data to candlestick | 12,322,869 | 4 | 2012-09-07T17:38:32Z | 12,323,759 | 8 | 2012-09-07T18:49:06Z | [
"python",
"numpy",
"scipy",
"finance",
"pandas"
] | I've tick by tick data for Forex pairs
Here is a sample of `EURUSD/EURUSD-2012-06.csv`
```
EUR/USD,20120601 00:00:00.207,1.23618,1.2363
EUR/USD,20120601 00:00:00.209,1.23618,1.23631
EUR/USD,20120601 00:00:00.210,1.23618,1.23631
EUR/USD,20120601 00:00:00.211,1.23623,1.23631
EUR/USD,20120601 00:00:00.240,1.23623,1.2362... | ```
In [59]: df
Out[59]:
Symbol Bid Ask
Datetime
2012-06-01 00:00:00.207000 EUR/USD 1.23618 1.23630
2012-06-01 00:00:00.209000 EUR/USD 1.23618 1.23631
2012-06-01 00:00:00.210000 EUR/USD 1.23618 1.23631
2012-06-01 00:00:00.211000 EUR/USD 1.23623 1.23631
2012-06-01 00:00... |
Reading a .JPG Image and Saving it without file size change | 12,323,085 | 4 | 2012-09-07T17:55:46Z | 12,323,175 | 7 | 2012-09-07T18:01:54Z | [
"python",
"opencv",
"pygame",
"jpeg"
] | I want to write a python code that reads a .jpg picture, alter some of its RBG components and save it again, without changing the picture size.
I tried to load the picture using OpenCV and PyGame, however, when I tried a simple Load/Save code, using three different functions, the resulting images is greater in size th... | JPEG is a lossy image format. When you open and save one, youâre encoding the entire image again. You can adjust the quality settings to approximate the original file size, but youâre going to lose some image quality regardless. Thereâs no general way to know what the original quality setting was, but if the file... |
How do I find an element that contains specific text in Selenium Webdriver (Python)? | 12,323,403 | 71 | 2012-09-07T18:20:06Z | 12,323,689 | 15 | 2012-09-07T18:44:23Z | [
"python",
"selenium",
"selenium-webdriver"
] | I'm trying to test a complicated javascript interface with Selenium (using the Python interface, and across multiple browsers). I have a number of buttons of the form:
```
<div>My Button</div>
```
I'd like to be able to search for buttons based on "My Button" (or non-case-sensitive, partial matches such as "my button... | you could try an xpath like:
```
'//div[contains(text(), "{0}") and @class="inner"]'.format(text)
``` |
How do I find an element that contains specific text in Selenium Webdriver (Python)? | 12,323,403 | 71 | 2012-09-07T18:20:06Z | 18,701,085 | 84 | 2013-09-09T14:54:21Z | [
"python",
"selenium",
"selenium-webdriver"
] | I'm trying to test a complicated javascript interface with Selenium (using the Python interface, and across multiple browsers). I have a number of buttons of the form:
```
<div>My Button</div>
```
I'd like to be able to search for buttons based on "My Button" (or non-case-sensitive, partial matches such as "my button... | Try the following:
```
driver.find_elements_by_xpath("//*[contains(text(), 'My Button')]")
``` |
Fast cross correlation method in Python | 12,323,959 | 7 | 2012-09-07T19:03:38Z | 12,324,600 | 14 | 2012-09-07T19:58:10Z | [
"python",
"opencv",
"numpy",
"scipy",
"correlation"
] | I have been recently trying to find a fast and efficient way to perform cross correlation check between two arrays using Python language. After some reading, I found these two options:
1. The `NumPy.correlate()` method, which is too slow when it comes to large arrays.
2. The `cv.MatchTemplate()` method, which seems to... | You're unlikely to get much faster than using an fft based correlation method.
```
import numpy
from scipy import signal
data_length = 8192
a = numpy.random.randn(data_length)
b = numpy.zeros(data_length * 2)
b[data_length/2:data_length/2+data_length] = a # This works for data_length being even
# Do an array flipp... |
Matplotlib imshow offset to match axis? | 12,324,176 | 9 | 2012-09-07T19:22:47Z | 12,324,384 | 12 | 2012-09-07T19:40:21Z | [
"python",
"numpy",
"matplotlib",
"gis",
"coordinate-systems"
] | I'm plotting a bunch of UTM coordinates using a matplotlib.pyplot.scatter. I also have a background air photo that I know matches the extent of the figure exactly. When I plot my data and set the axis I can display the scatter correctly. If I plot the air photo using imshow it uses the pixel number as the axis location... | You need to use the `extent` keyword argument to imshow.
As a quick example:
```
import numpy as np
import matplotlib.pyplot as plt
# Random points between 50000 and 51000
x, y = 1000 * np.random.random((2, 10)) + 50000
# A 10x10 "image"...
image = np.arange(100).reshape((10,10))
# In a lot of cases, image data wi... |
Why does using an attribute instead of a method provide such a significant boost in Python speed | 12,324,272 | 7 | 2012-09-07T19:31:50Z | 12,324,315 | 8 | 2012-09-07T19:35:18Z | [
"python",
"regex",
"performance"
] | I've been experimenting with a class that does pattern matching. My class looks something like this:
```
class Matcher(object):
def __init__(self, pattern):
self._re = re.compile(pattern)
def match(self, value):
return self._re.match(value)
```
All told, my script takes ~45 seconds to run. As an experime... | It's probably mostly the overhead of the additional function call. Calling a Python function is relatively expensive performance wise, because of the need to set up an additional stack frame, etc. Here is a bare-bones example that demonstrates similar performance:
```
>>> timeit.timeit("f()", "g = (lambda: 1); f = lam... |
Python: tuple indices must be integers, not str when selecting from mysql table | 12,325,234 | 11 | 2012-09-07T20:52:43Z | 12,325,294 | 15 | 2012-09-07T20:57:43Z | [
"python",
"mysql",
"tuples"
] | I have following method that I select all the ids from table and append them to a list and return that list. But when execute this code I end up getting tuple indicies must be integers... error. I have attached the error and the print out along with my method:
```
def questionIds(con):
print 'getting all the quest... | The python standard mysql library returns tuples from cursor.execute. To get at the question\_id field you'd use `row[0]`, not `row['question_id']`. The fields come out in the same order that they appear in the select statement.
A decent way to extract multiple fields is something like
```
for row in cursor.execute("... |
How to get text of an element in Selenium WebDriver (via the Python api) without including child element text? | 12,325,454 | 20 | 2012-09-07T21:11:21Z | 19,040,341 | 12 | 2013-09-26T23:26:51Z | [
"python",
"selenium",
"selenium-webdriver"
] | ```
<div id="a">This is some
<div id="b">text</div>
</div>
```
Getting "This is some" is non-trivial. For instance, this returns "This is some text":
```
driver.find_element_by_id('a').text
```
How does one, in a general way, get the text of a specific element without including the text of it's children?
(I'm pr... | Here's a general solution:
```
def get_text_excluding_children(driver, element):
return driver.execute_script("""
return jQuery(arguments[0]).contents().filter(function() {
return this.nodeType == Node.TEXT_NODE;
}).text();
""", element)
```
The element passed to the function can be something ... |
Iterate over a dict or list in Python | 12,325,608 | 12 | 2012-09-07T21:25:38Z | 12,325,691 | 12 | 2012-09-07T21:33:07Z | [
"python",
"list",
"dictionary",
"loops"
] | Just wrote some nasty code that iterates over a `dict` or a `list` in Python. I have a feeling this was not the best way to go about it.
The problem is that in order to iterate over a dict, this is the convention:
```
for key in dict_object:
dict_object[key] = 1
```
But modifying the object properties by key doe... | I've never needed to do this, ever. But if I did, I'd probably do something like this:
```
seq_iter = x if isinstance(x, dict) else xrange(len(x))
```
For example, in function form:
```
>>> def seq_iter(obj):
... return obj if isinstance(obj, dict) else xrange(len(obj))
...
>>> x = [1,2,3]
>>> for i in seq_iter... |
Various errors while parsing JSON in Python | 12,326,370 | 3 | 2012-09-07T22:46:18Z | 12,326,418 | 8 | 2012-09-07T22:54:28Z | [
"python",
"json",
"simplejson"
] | Attempting to parse json from a url requiring login. Including all my code here as I'm not sure where the error is.
```
try: import simplejson as json
except ImportError: import json
import urllib2
username = 'user'
password = '1234'
url = "https://www.blah.com/someplace"
# set up the username/password/url request
p... | You want to decode the *response*, not the request:
```
json_object = json.load(response)
```
The response is a file-like object, so you can use `.load()` to have the json library read it directly.
Alternatively (at the cost of some temporary memory use), use the `.loads()` function with the fully read response:
``... |
Django redirect to custom URL | 12,326,504 | 4 | 2012-09-07T23:07:36Z | 13,747,266 | 12 | 2012-12-06T15:46:07Z | [
"python",
"ios",
"django",
"oauth-2.0",
"custom-url"
] | From my Django app, how to I redirect a user to somescheme://someurl.com?
To give you some context in case it helps, I have a working oauth2 server written in Python/Django and I need to allow users to register redirect\_uris that have a custom URL scheme. This custom URL scheme is used for [handling the redirect with... | This actually **should not** work as Django is only allowing redirects to `http`, `https` and `ftp` by default for security reasons:
<https://www.djangoproject.com/weblog/2012/jul/30/security-releases-issued/>
I was having the same issue with OAuth and redirect to custom schemes.
Django (on Apache) is throwing 500'... |
Django app deployment on nGINX | 12,329,807 | 4 | 2012-09-08T10:07:20Z | 12,541,292 | 12 | 2012-09-22T06:19:17Z | [
"python",
"django",
"web-services",
"nginx",
"uwsgi"
] | I want to deploy Django application on nGINX server. I'm using uWSGI. I looked up in many tutorials but none worked.
Django application runs perfectly as a standalone app. What is the simplest way to have the same app running on nGINX??
I'm stuck here and want a solution.. :-(
my www folder is in `/usr/share/nginx/ww... | Once you have created an dJango application. Just follow these steps:
**STEP 1.** Create a file say uwsgi.ini in your Django Project Directory. i.e besides manage.py
```
[uwsgi]
# set the http port
http = :<port_no>
# change to django project directory
chdir = <project directory>
# add /var/www to the pythonpath, i... |
How to rearrange Pandas column sequence? | 12,329,853 | 8 | 2012-09-08T10:16:04Z | 23,741,704 | 11 | 2014-05-19T15:32:06Z | [
"python",
"pandas"
] | ```
>>> df =DataFrame({'a':[1,2,3,4],'b':[2,4,6,8]})
>>> df['x']=df.a + df.b
>>> df['y']=df.a - df.b
>>> df
a b x y
0 1 2 3 -1
1 2 4 6 -2
2 3 6 9 -3
3 4 8 12 -4
```
Now I want to rearrange the column sequence, which makes 'x','y' column to be the first & second columns by :
```
>>> df = df[['x',... | You could also do something like this:
```
df = df[['x', 'y', 'a', 'b']]
```
You can get the list of columns with:
```
cols = list(df.columns.values)
```
The output will produce something like this:
```
['a', 'b', 'x', 'y']
```
...which is then easy to rearrange manually before dropping it into the first function |
Lifetime of variable after if block | 12,330,002 | 2 | 2012-09-08T10:43:10Z | 12,330,029 | 10 | 2012-09-08T10:46:49Z | [
"python"
] | There is this code:
```
>>> if True:
... a = 4
...
>>> print a
4
```
Why variable **a** is still alive after **if** block? Shouldn't it be destroyed when block **if** ends? | Python variables have scope inside a `function`, `class` or `module`. Variables initialised in `if` statements, `while` statements and `for` statements are available outside the if/while/for statement for use
This is different to many other languages where accessing the variable would throw an exception because of it ... |
Reading a file without newlines | 12,330,522 | 102 | 2012-09-08T11:55:15Z | 12,330,535 | 158 | 2012-09-08T11:57:07Z | [
"python",
"readlines"
] | In Python, calling
```
temp = open(filename,'r').readlines()
```
results in a list in which each element is a line in the file. Its a little stupid but still: `readlines()` also writes newline character to each element, something I do not wish to happen. How can I avoid it? | You can read the whole file and split lines using `str.splitlines`:
```
temp = file.read().splitlines()
```
Or you can strip the newline by hand:
```
temp = [line[:-1] for line in file]
```
**Note:** this last solution only works if the file ends with a newline, otherwise the last line will lose a character.
This ... |
Reading a file without newlines | 12,330,522 | 102 | 2012-09-08T11:55:15Z | 12,330,540 | 12 | 2012-09-08T11:57:56Z | [
"python",
"readlines"
] | In Python, calling
```
temp = open(filename,'r').readlines()
```
results in a list in which each element is a line in the file. Its a little stupid but still: `readlines()` also writes newline character to each element, something I do not wish to happen. How can I avoid it? | ```
temp = open(filename,'r').read().split('\n')
``` |
Can't connect to remote server with Fabric and SSH using key file | 12,330,712 | 4 | 2012-09-08T12:25:42Z | 12,451,061 | 7 | 2012-09-16T21:53:51Z | [
"python",
"ssh",
"fabric"
] | I'm trying to use a Fabric python script to log into the production server then run the 'ls' command remotely. Well I actually have lots of other commands to run, but I'm starting off with a simple list to get it working. My production server uses SSH and is locked down so it needs a private key file and password.
Now... | I ended up testing the SSH config separately from the command line first to get that part working. I think there was a problem with the SSH keys as I had used PuTTY to generate them and that format may have been incompatible with the OpenSSH ones that Linux uses.
So first I made new SSH keys on my linux machine withou... |
Python 3.3's yield from | 12,331,174 | 6 | 2012-09-08T13:32:53Z | 12,331,695 | 14 | 2012-09-08T14:40:03Z | [
"python",
"functional-programming",
"yield"
] | Python 3 brings the [`yield from`](http://docs.python.org/dev/whatsnew/3.3.html#pep-380) semantics. As far as I understand it's supposed to yield to the outermost generator in which case I'd expect this code to be linear in `N`.
```
from collections import Iterable
def flatten(L):
for e in L:
if isinstance(e, I... | `yield from`, just like `for item in x: yield x`, *is* linear. However, function calls are slow, and because of the nesting in your `l`, when you double N, you're not merely doubling the number of terms, you're doubling the number of calls needed. Anything which scales with the number of calls, like function overhead i... |
Triangle wave shaped array in Python | 12,332,392 | 9 | 2012-09-08T16:17:49Z | 12,332,512 | 7 | 2012-09-08T16:33:57Z | [
"python",
"arrays",
"numpy",
"geometry"
] | What is the most efficient way to produce an array of 100 numbers that form the shape of the triangle wave below, with a max/min amplitude of 0.5?
Triangle waveform in mind:
 | Use a generator:
```
def triangle(length, amplitude):
section = length // 4
for direction in (1, -1):
for i in range(section):
yield i * (amplitude / section) * direction
for i in range(section):
yield (amplitude - (i * (amplitude / section))) * direction
```
This... |
Why is enthought mkl routine slower than matlab | 12,332,611 | 3 | 2012-09-08T16:45:58Z | 12,332,960 | 8 | 2012-09-08T17:30:42Z | [
"python",
"matlab",
"numpy",
"scipy"
] | I am testing the speed of linear algebra runtines of python enthought distribution which claims to be linked with intel MKL on windows platform. I did in IPython interactive shell the following:
```
import scipy.linalg as la
import numpy.random
M = random.rand(1000,1000)
%timeit la.svd(M);
```
`svd()` took typically ... | Numpy's `la.svd(M)` is calculating U, S, and V, while Matlab's `svd(M)` is calculating only S. Try comparing to `la.svd(M, compute_uv=False)` or `[U,S,V]=svd(M)`. |
context manager exit called before code in body | 12,332,881 | 3 | 2012-09-08T17:23:11Z | 12,332,934 | 8 | 2012-09-08T17:28:02Z | [
"python",
"contextmanager"
] | I've been playing around with making my own context managers in Python. I'm seeing some strange behavior most likely due to my implementation.
I see the `__exit__` code called before a statement in the 'with' context. For example, here is the code snippet:
```
with ProgressBar(10) as p:
p.update(1)
```
and it's ex... | From the documentation:
> `object.__enter__(self)`
>
> Enter the runtime context related to this object. The `with` statement
> will bind this methodâs return value to the target(s) specified in
> the `as` clause of the statement, if any.
You're not returning anything from `__enter__` (and thus you're returning Non... |
Installing python module within code | 12,332,975 | 77 | 2012-09-08T17:33:02Z | 15,950,647 | 121 | 2013-04-11T13:54:43Z | [
"python",
"pip",
"python-module",
"pypi"
] | I need to install a package from PyPi straight within my script.
Maybe there's exists module or distutils (distribute, pip) ability which allows me just execute something like `pypi.install('requests')` and requests will be installed into my virtualenv, and I should not type `pip install requests` in my shell? | You can also use something like:
```
import pip
def install(package):
pip.main(['install', package])
# Example
if __name__ == '__main__':
install('argh')
``` |
Installing python module within code | 12,332,975 | 77 | 2012-09-08T17:33:02Z | 24,773,951 | 31 | 2014-07-16T06:45:37Z | [
"python",
"pip",
"python-module",
"pypi"
] | I need to install a package from PyPi straight within my script.
Maybe there's exists module or distutils (distribute, pip) ability which allows me just execute something like `pypi.install('requests')` and requests will be installed into my virtualenv, and I should not type `pip install requests` in my shell? | If you want to use `pip` to install required package and import it after installation, you can use this code:
```
def install_and_import(package):
import importlib
try:
importlib.import_module(package)
except ImportError:
import pip
pip.main(['install', package])
finally:
... |
Using tuple as a dictionary key in Python | 12,333,091 | 3 | 2012-09-08T17:49:36Z | 12,333,123 | 9 | 2012-09-08T17:54:09Z | [
"python",
"tuples"
] | I am trying to work with a dictionary with tuples of n values as keys. I want to find tuples whose 2nd value is 10 (for example)
```
('HI', '10', '10', '10', '10', '10000', 'true', '0.5GiB', '8', '100000s', '100MiB')
('HI', '100', '10', '10', '10', '100', 'false', '0.5GiB', '8', '100000s', '100MiB')
('HI', '100', '10'... | For that particular scenario, you'd have to iterate over all of the keys and test them against your predicate:
```
results = set(k for k in your_dict if k[1] == '10')
```
If you wanted to do this more quickly for repeated lookups and you knew ahead of time what field(s) you'd be checking, you could build indices that... |
Setting Environment variable in LINUX using python in threads | 12,333,158 | 2 | 2012-09-08T17:58:20Z | 12,333,181 | 8 | 2012-09-08T18:01:08Z | [
"python",
"linux",
"environment-variables"
] | i have five threads in my code...
five threads are initiated by the main.py
so for each running thread i need to set diff IP as environment value
```
thread-1: has to set 192.168.10.2
thread-2: has to set 192.168.10.3
thread-3: has to set 192.168.10.4
thread-4: has to set 192.168.10.5
thread-5: has to set 192.168.10... | Environment variables are set on a per-process basis, not a per-thread one. |
Give the Python Terminal a Persistent History | 12,334,316 | 20 | 2012-09-08T20:43:36Z | 12,334,331 | 15 | 2012-09-08T20:45:16Z | [
"python",
"linux",
"python-2.7"
] | Is there a way to tell the interactive Python shell to preserve its history of executed commands between sessions?
While a session is running, after commands have been executed, I can arrow up and access said commands, I'm just wondering if there is some way for a certain number of these commands to be saved until the... | Use [IPython](http://ipython.org/).
You should, anyway, because it's awesome: persistent command history is just one of the many many ways it's better than the stock Python shell. |
Give the Python Terminal a Persistent History | 12,334,316 | 20 | 2012-09-08T20:43:36Z | 12,334,344 | 18 | 2012-09-08T20:47:13Z | [
"python",
"linux",
"python-2.7"
] | Is there a way to tell the interactive Python shell to preserve its history of executed commands between sessions?
While a session is running, after commands have been executed, I can arrow up and access said commands, I'm just wondering if there is some way for a certain number of these commands to be saved until the... | Sure you can, with a small startup script. From [Interactive Input Editing and History Substitution](http://docs.python.org/tutorial/interactive.html) in the python tutorial:
```
# Add auto-completion and a stored history file of commands to your Python
# interactive interpreter. Requires Python 2.0+, readline. Autoco... |
Does Python have a linspace function in its std lib? | 12,334,442 | 2 | 2012-09-08T20:59:56Z | 12,334,458 | 7 | 2012-09-08T21:02:26Z | [
"python",
"matlab"
] | Does Python have a function like matlab's `linspace` in its standard library?
If not, is there an easy way to implement it without installing an external package?
Here's a quick and easy [definition of linspace](http://www.mathworks.com/help/matlab/ref/linspace.html) in matlab terms.
**Note**
I don't need a "vector... | No, it doesn't. You can write your own (whicn isn't difficult), but if you are using Python to fulfil some of matlab's functionality then you definitely want to install `numpy`, which has `numpy.linspace`.
You may find [NumPy for Matlab users](http://www.scipy.org/NumPy_for_Matlab_Users) informative. |
Does Python have a linspace function in its std lib? | 12,334,442 | 2 | 2012-09-08T20:59:56Z | 12,334,459 | 8 | 2012-09-08T21:02:38Z | [
"python",
"matlab"
] | Does Python have a function like matlab's `linspace` in its standard library?
If not, is there an easy way to implement it without installing an external package?
Here's a quick and easy [definition of linspace](http://www.mathworks.com/help/matlab/ref/linspace.html) in matlab terms.
**Note**
I don't need a "vector... | The easiest way to implement this is a generator function:
```
from __future__ import division
def linspace(start, stop, n):
if n == 1:
yield stop
return
h = (stop - start) / (n - 1)
for i in range(n):
yield start + h * i
```
Example usage:
```
>>> list(linspace(1, 3, 5))
[1.0, 1... |
Why was an old .pyc file breaking Django? | 12,334,869 | 9 | 2012-09-08T22:07:48Z | 12,334,942 | 8 | 2012-09-08T22:19:32Z | [
"python",
"django"
] | I pulled the latest code using git today and I got the following error:
```
ImportError at /
cannot import name Like
```
This might have something to do with circular imports. I examined the traceback:
```
Traceback:
File "/Library/Python/2.7/site-packages/Django-1.4.1-py2.7.egg/django/core/handlers/base.py" in get_... | No, in fact, Python will use the `.pyc` file preferably and only access the `.py` file if it a) exists and b) is newer than the `.pyc` file.
This allows you to distribute a Python app in compiled form without the source code (although it's not much of a code "obfuscation" technique). |
Python: What Does a Semi Colon Do? | 12,335,358 | 25 | 2012-09-08T23:39:28Z | 12,335,362 | 39 | 2012-09-08T23:40:35Z | [
"python",
"function",
"if-statement",
"break",
"semicolon"
] | I got a function online to help me with my current project and it had semi colons on some of the lines. I was wondering why? Is it to break the function?
```
def containsAny(self, strings=[]):
alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789'
for string in strings:
for char in string:
if ch... | The semicolon does nothing in the code you show.
I suspect this is someone who programs in another language (C, Java, ...) that requires semicolons at the end of statements and it's just a habit (happens to me sometimes too).
If you want to put several Python statements on the same line, you can use a semi-colon to s... |
Python: What Does a Semi Colon Do? | 12,335,358 | 25 | 2012-09-08T23:39:28Z | 12,335,367 | 13 | 2012-09-08T23:41:47Z | [
"python",
"function",
"if-statement",
"break",
"semicolon"
] | I got a function online to help me with my current project and it had semi colons on some of the lines. I was wondering why? Is it to break the function?
```
def containsAny(self, strings=[]):
alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789'
for string in strings:
for char in string:
if ch... | The semicolon here does not do anything. People who come from C/C++/Java/(many other language) backgrounds tend to use the semicolon out of habit. |
Multiple conditions with if/elif statements | 12,335,382 | 7 | 2012-09-08T23:44:16Z | 12,335,410 | 9 | 2012-09-08T23:51:39Z | [
"python",
"python-2.7",
"if-statement"
] | I'm trying to get an if statement to trigger from more than one condition without rewriting the statement multiple times with different triggers. e.g.:
```
if user_input == "look":
print description
if user_input == "look around":
print description
```
How would you condense those into one statement?
I'v... | What you're trying to do is
```
if user_input == "look" or user_input == "look around":
print description
```
Another option if you have a lot of possibilities:
```
if user_input in ("look", "look around"):
print description
```
Since you're using 2.7, you could also write it like this (which works in 2.7 o... |
Eclipse Pydev: Run selected lines of code | 12,335,424 | 12 | 2012-09-08T23:53:38Z | 12,774,197 | 11 | 2012-10-08T01:07:32Z | [
"python",
"eclipse",
"pydev"
] | Is there a command in Eclipse Pydev which allows me to only run a few selected (highlighted) lines of code within a larger script?
If not, is it possible to run multiple lines of code in the PyDev console at once? | press `CTRL+ALT+ENTER` to send the selected lines to the interactive console |
Cannot use environment variables for settings in Django | 12,335,488 | 8 | 2012-09-09T00:07:32Z | 12,464,707 | 27 | 2012-09-17T17:57:11Z | [
"python",
"django",
"environment-variables"
] | In trying to find a place to store and save settings beyond settings.py and the database, I used an environment.json for environment variables. I import these in settings.py.
My problem is that when I try to change or store new values in my environment, `env`, `settings.py` does not notice the change - perhaps because... | You might want to look into `foreman` ([GitHub](https://github.com/ddollar/foreman)) or `honcho` ([GitHub](https://github.com/nickstenning/honcho)). Both of these look for a `.env` file in your current directory from which to load local environment variables.
My `.env` looks like this for most projects (I use dj-datab... |
calculating cubic root in python | 12,335,589 | 7 | 2012-09-09T00:32:29Z | 12,335,593 | 10 | 2012-09-09T00:33:47Z | [
"python"
] | I'm trying to evaluate the following function in python:
```
f(x) = (1 + cos(x))^(1/3)
def eval( i ):
return math.pow( (1 + math.cos( i )), 1/3)
```
why is it always returning me `1`?
I'm trying to calculate the `Right` and `Left` approximation of an integral, and latter apply `Simpson's Rule`, but `Python` does... | Use
```
1/3.0
```
instead of
```
1/3
```
in your code. Otherwise your exponent will always be `0` due to integer truncation.
Whether to use `**` or `math.pow()` is up to your preference, most would probably just use `**`.
It's probably *not* a good idea to define a function named `eval` since [**eval()**](http://... |
calculating cubic root in python | 12,335,589 | 7 | 2012-09-09T00:32:29Z | 12,335,596 | 16 | 2012-09-09T00:34:31Z | [
"python"
] | I'm trying to evaluate the following function in python:
```
f(x) = (1 + cos(x))^(1/3)
def eval( i ):
return math.pow( (1 + math.cos( i )), 1/3)
```
why is it always returning me `1`?
I'm trying to calculate the `Right` and `Left` approximation of an integral, and latter apply `Simpson's Rule`, but `Python` does... | Use floating point math (1 / 3 truncates to zero). Also, no need for math.pow (\*\* for exponentiation)...
```
(1 + math.cos(i)) ** (1 / 3.0)
```
Also, `min`, `max` and `eval` are built-in functions - you are shadowing them.
Also, the extra spaces you are adding in your function call arguments are against [PEP-8](ht... |
pip giving "ImportError: No module named setuptools" but I can import setuptools in python interpreter | 12,335,662 | 7 | 2012-09-09T00:48:31Z | 12,335,681 | 7 | 2012-09-09T00:53:48Z | [
"python",
"pip",
"setuptools"
] | I'm getting setup on a new mac and I was humming along just fine, installing pip and a few packages. When suddenly, every pip command I'd try to run would throw
```
Exception:
Traceback (most recent call last):
File "/Library/Python/2.6/site-packages/pip-1.2.1-py2.6.egg/pip/basecommand.py", line 107, in main
sta... | Your `pip` doesn't seem to be in agreement with your Python. Compare:
```
File "/Library/Python/2.6/site-packages/pip-1.2.1-py2.6.egg/pip/basecommand.py", line 107, in main
```
to
```
Installed /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg
```
If python2.7... |
Read CSV file to numpy array, first row as strings, rest as float | 12,336,234 | 12 | 2012-09-09T03:11:19Z | 12,337,556 | 9 | 2012-09-09T08:20:31Z | [
"python",
"csv",
"numpy"
] | I have data stored in a CSV where the first row is strings (column names) and the remaining rows are numbers. How do I store this to a numpy array? All I can find is how to set data type for columns but not for rows.
Right now I'm just skipping the headers to do the calculations but I need to have the headers in the f... | I'm not sure what you mean when you say you need the headers in the final version, but you can generate a structured array where the columns are accessed by strings like this:
```
data = np.genfromtxt(path_to_csv, dtype=None, delimiter=',', names=True)
```
and then access columns with `data['col1_name']`, `data['col2... |
Read CSV file to numpy array, first row as strings, rest as float | 12,336,234 | 12 | 2012-09-09T03:11:19Z | 12,340,302 | 22 | 2012-09-09T15:18:37Z | [
"python",
"csv",
"numpy"
] | I have data stored in a CSV where the first row is strings (column names) and the remaining rows are numbers. How do I store this to a numpy array? All I can find is how to set data type for columns but not for rows.
Right now I'm just skipping the headers to do the calculations but I need to have the headers in the f... | You can keep the column names if you use the `names=True` argument in `np.genfromxt`
```
data = np.genfromtxt(path_to_csv, dtype=float, delimiter=',', names=True)
```
Please note the `dtype=float`, that will convert your data to float. This is more efficient than using `dtype=None`, that asks `np.genfromtxt` to gues... |
How to open ssl socket using certificate stored in string variables in python | 12,336,239 | 16 | 2012-09-09T03:13:40Z | 13,905,835 | 16 | 2012-12-16T21:53:10Z | [
"python",
"sockets",
"ssl",
"certificate"
] | In Python, ssl.wrap\_socket can read certificates from files, ssl.wrap\_socket require the certificate as a file path.
How can I start an SSL connection using a certificate read from string variables?
My host environment does not allow write to files, and tempfile module is not functional
I'm using Python 2.7.
I ... | Looking at the source, ssl.wrap\_socket calls directly into the native code (openssl) function SSL\_CTX\_use\_cert\_chain\_file which requires a path to a file, so what you are trying to do is not possible.
For reference:
In ssl/**init**.py we see:
```
def wrap_socket(sock, keyfile=None, certfile=None,
... |
Saving dictionary whose keys are tuples with json, python | 12,337,583 | 7 | 2012-09-09T08:25:22Z | 12,337,657 | 7 | 2012-09-09T08:37:51Z | [
"python",
"json",
"tuples"
] | I am writing a little program in python and I am using a dictionary whose (like the title says) keys and values are tuples. I am trying to use json as follows
```
import json
data = {(1,2,3):(a,b,c),(2,6,3):(6,3,2)}
print json.dumps(data)
```
Problem is I keep getting `TypeError: keys must be a string`.
How can I go... | You'll need to convert your tuples to strings first:
```
json.dumps({str(k): v for k, v in data.iteritems()})
```
Of course, you'll end up with strings instead of tuples for keys:
```
'{"(1, 2, 3)": ["a", "b", "c"], "(2, 6, 3)": [6, 3, 2]}'
``` |
Python nested scopes with dynamic features | 12,338,713 | 10 | 2012-09-09T11:34:37Z | 12,338,782 | 14 | 2012-09-09T11:45:23Z | [
"python",
"name-binding"
] | Need help with understanding the following sentence from [PEP 227](http://www.python.org/dev/peps/pep-0227/) and the [Python Language Reference](http://docs.python.org/reference/executionmodel.html#interaction-with-dynamic-features)
> If a variable is referenced in an enclosed scope, it is an error to
> delete the nam... | The following raises the execption:
```
def foo():
spam = 'eggs'
def bar():
print spam
del spam
```
because the `spam` variable is being used in the enclosed scope of `bar`:
```
>>> def foo():
... spam = 'eggs'
... def bar():
... print spam
... del spam
...
SyntaxError: can n... |
beautifulsoup findAll find_all | 12,339,323 | 8 | 2012-09-09T13:08:00Z | 12,339,416 | 24 | 2012-09-09T13:21:17Z | [
"python",
"xml-parsing",
"html-parsing",
"beautifulsoup"
] | I would like to parse a html file with Python, and the module I used is beautifulsoup.
After I used it, something strange happened.It is said that the function "find\_all" is
same as "findAll", but I've tried both of them. But it is different.
Can anyone tell me the different?
```
import urllib, urllib2, cookielib
... | In BeautifulSoup version 4, the methods are exactly the same; the mixed-case versions (`findAll`, `findAllNext`, `nextSibling`, etc.) have all been renamed to conform to the [Python style guide](http://www.python.org/dev/peps/pep-0008/), but the *old* names are still available to make porting easier. See [Method Names]... |
Querying by "_id" doesn't return file in MongoDB in Python, using PyMongo | 12,339,583 | 2 | 2012-09-09T13:43:40Z | 12,344,404 | 9 | 2012-09-10T01:30:07Z | [
"python",
"django",
"mongodb",
"pymongo",
"gridfs"
] | I'm using Python + MongoDB + PyMongo in Openshift
```
import os
import gridfs
from django.http import HttpResponse
from pymongo.connection import Connection
from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from django.template import Context,... | For pymongo versions < 2.2, you need to import ObjectId with
```
from pymongo.objectid import ObjectId
```
For versions 2.2 and above, the import is instead
```
from bson.objectid import ObjectId
```
Then you can query gridfs like so:
```
fs.exists(ObjectId('504a36d93324f20944247af2'))
``` |
installing django 1.5(development version) in virtualenv | 12,339,608 | 19 | 2012-09-09T13:46:58Z | 12,339,645 | 26 | 2012-09-09T13:50:36Z | [
"python",
"django",
"virtualenv"
] | I am trying to start developing a web apps using django 1.5 but I can't figure out how to install the django 1.5 in the `virtualenv` because django 1.5 is still a development version.
I've tried installing it using `easy_install` and `pip` but all I get is django 1.4 because it is the official version.
Can anybody he... | Directly from the github repository.
```
pip install git+git://github.com/django/django.git@1.5b2
``` |
installing django 1.5(development version) in virtualenv | 12,339,608 | 19 | 2012-09-09T13:46:58Z | 13,117,080 | 42 | 2012-10-29T06:50:27Z | [
"python",
"django",
"virtualenv"
] | I am trying to start developing a web apps using django 1.5 but I can't figure out how to install the django 1.5 in the `virtualenv` because django 1.5 is still a development version.
I've tried installing it using `easy_install` and `pip` but all I get is django 1.4 because it is the official version.
Can anybody he... | [Django 1.5 was released!](https://www.djangoproject.com/weblog/2013/feb/26/15/). To install it use:
```
pip install django
```
To install the latest development version without git, on your own risk use:
```
pip install https://github.com/django/django/zipball/master
```
[Django 1.5 Release Candidate 2 (RC2) was r... |
installing django 1.5(development version) in virtualenv | 12,339,608 | 19 | 2012-09-09T13:46:58Z | 13,960,686 | 11 | 2012-12-19T20:33:21Z | [
"python",
"django",
"virtualenv"
] | I am trying to start developing a web apps using django 1.5 but I can't figure out how to install the django 1.5 in the `virtualenv` because django 1.5 is still a development version.
I've tried installing it using `easy_install` and `pip` but all I get is django 1.4 because it is the official version.
Can anybody he... | Now that the github version is 1.6 'alpha' (atm), to get the 1.5.x branch, you can:
```
pip install --upgrade git+http://github.com/django/django.git@stable/1.5.x#egg=django
```
Edit: You may need to `pip uninstall Django` to remove previous versions. |
How to compile python script to binary executable | 12,339,671 | 57 | 2012-09-09T13:54:05Z | 12,339,706 | 10 | 2012-09-09T13:58:44Z | [
"python",
"compilation",
"executable"
] | I have to convert python script to windows executable.
I have installed `python 2.6` in my system.
I can see a folder in c drive naming python26 which contain all the files.
I have created one script and kept it in `C:\pythonscript`
inside this folder there are two files
`Setup.py` and `oldlogs.py` (this file need... | You'll need [py2exe](http://www.py2exe.org). Read a [Tutorial](http://www.py2exe.org/index.cgi/Tutorial). |
How to compile python script to binary executable | 12,339,671 | 57 | 2012-09-09T13:54:05Z | 12,339,729 | 28 | 2012-09-09T14:02:04Z | [
"python",
"compilation",
"executable"
] | I have to convert python script to windows executable.
I have installed `python 2.6` in my system.
I can see a folder in c drive naming python26 which contain all the files.
I have created one script and kept it in `C:\pythonscript`
inside this folder there are two files
`Setup.py` and `oldlogs.py` (this file need... | Or use [PyInstaller](http://www.pyinstaller.org/) as an alternative to [py2exe](http://www.py2exe.org/). Here is a good [starting point](http://www.pyinstaller.org/export/v2.0/project/doc/Manual.html?format=raw#getting-started). PyInstaller let's you also create executables for linux and mac... |
Escape strings for javascript using jinja2? | 12,339,806 | 16 | 2012-09-09T14:12:57Z | 18,900,930 | 8 | 2013-09-19T17:07:29Z | [
"javascript",
"python",
"jinja2"
] | How do I escape HTML with jinja2 so that it can be used as a string in javascript (jquery)?
If I were using django's templating system I could write:
`$("#mydiv").append("{{ html_string|escapejs }}");`
Django's [`|escapejs` filter](https://github.com/django/django/blob/ebc773ada3e4f40cf5084268387b873d7fe22e8b/django... | This is a `escapejs` filter, based on Django's one, that I wrote for use in Jinja2 templates:
```
_js_escapes = {
'\\': '\\u005C',
'\'': '\\u0027',
'"': '\\u0022',
'>': '\\u003E',
'<': '\\u003C',
'&': '\\u0026',
'=': '\\u003D',
'-': '\\u002D',
';'... |
uwsgi: your server socket listen backlog is limited to 100 connections | 12,340,047 | 10 | 2012-09-09T14:44:49Z | 12,340,078 | 17 | 2012-09-09T14:49:52Z | [
"python",
"flask",
"wsgi",
"uwsgi",
"supervisord"
] | I run a flask app on uwsgi. I use supervisor to manage uwsgi process. I find the log saying that
> your server socket listen backlog is limited to 100 connections.
How to overcome 100 connections limitation?
My running script is as below:
```
[program:myapp]
command=uwsgi --master -s /tmp/app.sock --module myapp:app... | Note that a "listen backlog" of 100 connections doesn't mean that your server can only handle 100 simultaneous (or total) connections - this is instead dependent on the number of configured processes or threads. The listen backlog is a socket setting telling the kernel how to limit the number of outstanding (as yet una... |
How can one load an AppEngine cloud storage backup to a local development server? | 12,340,468 | 3 | 2012-09-09T15:41:48Z | 13,349,621 | 7 | 2012-11-12T18:48:08Z | [
"python",
"google-app-engine"
] | I'm experimenting with the Google cloud storage backup feature for an application.
After downloading the backup files using gsutil, how can they be loaded into a local development server?
Is there a parser available for these formats (eg, protocol buffers)? | Greg Bayer wrote some Python code showing how to do this in a [blog post](http://gbayer.com/big-data/app-engine-datastore-how-to-efficiently-export-your-data/):
```
# Make sure App Engine SDK is available
import sys
sys.path.append('/usr/local/google_appengine')
from google.appengine.api.files import records
from goog... |
Jinja 2 safe keyword | 12,341,496 | 5 | 2012-09-09T17:58:05Z | 12,341,532 | 8 | 2012-09-09T18:02:55Z | [
"python",
"template-engine",
"jinja2"
] | I have a little problem understanding what an expression like `{{ something.render() | safe }}` does .
From what I have seen, without the `safe` keyword it outputs the entire html document, not just the true content.
What I would like to know, is what it actually does, how it functions . | The `safe` filter explicitly marks a string as "safe", i.e., it should not be automatically-escaped if auto-escaping is enabled.
The documentation on this filter is [here](http://jinja.pocoo.org/docs/templates/#working-with-automatic-escaping).
See the section on [manual escaping](http://jinja.pocoo.org/docs/template... |
Jinja 2 safe keyword | 12,341,496 | 5 | 2012-09-09T17:58:05Z | 12,341,539 | 11 | 2012-09-09T18:03:43Z | [
"python",
"template-engine",
"jinja2"
] | I have a little problem understanding what an expression like `{{ something.render() | safe }}` does .
From what I have seen, without the `safe` keyword it outputs the entire html document, not just the true content.
What I would like to know, is what it actually does, how it functions . | Normally text is HTML-escaped (so `<b>` would be written out as `<b>`, which would render as `<b>`).
When you put `|safe` after something, you're telling the template engine that you have already escaped the text yourself, i.e. "it's safe to render this directly". So it will not do that encoding for you.
For mo... |
Trouble setting Python version in Sublime Text2 | 12,342,004 | 2 | 2012-09-09T18:59:38Z | 12,342,473 | 15 | 2012-09-09T20:00:57Z | [
"python",
"macports",
"sublimetext2"
] | I'm having trouble setting the build environment in Sublime Text2.
I'm using Macports for Python and package installation.
My python.sublime-build file looks like this:
```
{
"cmd": ["python", "-u", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python"
}
```
I think ... | Your Sublime Text 2 environment is different from your shell environment; the `$PATH` variable is probably not pointing to the same directories and the wrong executable is selected.
You have several options to work around that:
1. Set a `"path"` option that includes `/opt/local/bin` need to use an absolute path for y... |
statsmodels forecasting using ARMA model | 12,342,653 | 10 | 2012-09-09T20:23:24Z | 12,361,198 | 8 | 2012-09-11T00:27:36Z | [
"python",
"time-series",
"forecasting",
"statsmodels"
] | I want to forecast timeseries data. I read in previous posts that module statsmodels has the required tool for using ARMA method for forecasting which is exactly the one I have been looking for. In spite of that I am having trouble in forecasting the data. Can someone explain the various parameters used in the model an... | The question is very general, for background information Rob Hyndman's link or any text book for time series analysis will be useful.
Skipper Seabold presented a tutorial at the scipy conference that includes an ARMA example
<https://github.com/jseabold/tutorial/blob/master/tsa_arma.py>
The various methods and optio... |
SciPy instead of GNU Octave | 12,343,271 | 12 | 2012-09-09T21:47:16Z | 12,343,528 | 20 | 2012-09-09T22:30:13Z | [
"python",
"numpy",
"scipy",
"octave"
] | For my lab experiments I write small programs to help with the data analysis. I usually just need basic calculations, means, standard deviation, arbitrary weighted function fitting and plots with errorbars and fitted function.
With GNU Octave, I can do this. I started to read more into the language of it and I start t... | Yes, the Python ecosystem makes it a viable platform for everyday data analysis tasks, especially using the IPython interface (but I'll stick to the standard one here.) The "[not having] to learn yet another language" argument is a strong one, IMHO, and is one of the reasons why I tend to use Python for this stuff.
``... |
building Python from source with zlib support | 12,344,970 | 22 | 2012-09-10T03:16:14Z | 12,344,972 | 10 | 2012-09-10T03:16:14Z | [
"python",
"python-3.x"
] | When building Python 3.2.3 from source on Ubuntu 12.04, the zlib module is not available.
I downloaded the official source distribution from python.org, and attempted to build and install it with the following commands.
```
tar xfa Python3.2.3.tar.bz2
cd Python-3.2.3
./configure --prefix=/opt/python3.2
make
sudo make... | The solution is to install the Ubuntu package `dpkg-dev`.
```
sudo apt-get install dpkg-dev
```
The reason is explained [here](http://fnch.users.sourceforge.net/pythononubuntu1104.html).
In short, recent versions of Ubuntu don't store `libz.so` in the standard `/usr/lib` location, but rather in a platform specific l... |
building Python from source with zlib support | 12,344,970 | 22 | 2012-09-10T03:16:14Z | 15,013,895 | 44 | 2013-02-21T23:01:06Z | [
"python",
"python-3.x"
] | When building Python 3.2.3 from source on Ubuntu 12.04, the zlib module is not available.
I downloaded the official source distribution from python.org, and attempted to build and install it with the following commands.
```
tar xfa Python3.2.3.tar.bz2
cd Python-3.2.3
./configure --prefix=/opt/python3.2
make
sudo make... | I had a similar problem on CentOS 6.3 and python 3.2.3
I solved it by:
Edit `/Modules/Setup` and uncomment the line:
```
zlib zlibmodule.c -I$(prefix)/include -L$(exec_prefix)/lib -lz
```
change to directory /Modules/zlib:
```
./configure
make
sudo make install
```
then compiled my python3.2 source.
and was then... |
building Python from source with zlib support | 12,344,970 | 22 | 2012-09-10T03:16:14Z | 27,132,584 | 9 | 2014-11-25T17:04:42Z | [
"python",
"python-3.x"
] | When building Python 3.2.3 from source on Ubuntu 12.04, the zlib module is not available.
I downloaded the official source distribution from python.org, and attempted to build and install it with the following commands.
```
tar xfa Python3.2.3.tar.bz2
cd Python-3.2.3
./configure --prefix=/opt/python3.2
make
sudo make... | I am using CentOS 6.6 and was recieving zlib errors. None of the other answers proposed here worked for me (including the fix for CentOS 6.3 of uncommenting a line in Modules/Setup). I have fixed it using the following commands.
```
yum groupinstall "Development tools"
yum install zlib-devel bzip2-devel openssl-devel ... |
Sqlalchemy get last X rows in order | 12,345,015 | 9 | 2012-09-10T03:27:45Z | 12,345,374 | 14 | 2012-09-10T04:34:03Z | [
"python",
"sqlalchemy"
] | I need to get the last X rows from a table, but in order of the ID. How could I achieve this? | ```
query = users.select().order_by(users.c.id.desc()).limit(5)
print reversed(conn.execute(query).fetchall() )
```
something like that anyway |
Does '[ab]+' equal '(a|b)+' in python re module? | 12,345,047 | 9 | 2012-09-10T03:34:04Z | 12,345,188 | 9 | 2012-09-10T04:02:27Z | [
"python",
"regex",
"python-2.7"
] | I think pat1 = '[ab]' and pat2 = 'a|b' have the same function in Python(python2.7, windows) 're' module as a regular expression pattern. But I am confused with '[ab]+' and '(a|b)+', do they have the same function, if not can you explain details.
```
'''
Created on 2012-9-4
@author: melo
'''
import re
pat1 = '(a|b)+'... | You have a capturing group in the first pattern.
According to [the docs](http://docs.python.org/library/re.html#re.split),
> **re.split()**
> ... If capturing parentheses are used in *pattern*, then the text of all groups in the pattern are also returned as part of the resulting list. ...
Try making the group non-... |
Removing _id element from Pymongo results | 12,345,387 | 9 | 2012-09-10T04:36:40Z | 12,345,646 | 32 | 2012-09-10T05:10:04Z | [
"python",
"mongodb",
"pymongo"
] | I'm attempting to create a web service using MongoDB and Flask (using the pymongo driver). A query to the database returns documents with the "\_id" field included, of course. I don't want to send this to the client, so how do I remove it?
Here's a Flask route:
```
@app.route('/theobjects')
def index():
objects =... | To exclude the `_id` field in a find query in pymongo, you can use:
```
db.collection.find({}, {'_id': False})
```
The documentation is somewhat missleading on this as it says the `_id` field is always included. But you can exclude it like shown above. |
South: Unknown command 'migrate' | 12,346,033 | 10 | 2012-09-10T05:57:06Z | 12,348,410 | 8 | 2012-09-10T09:03:15Z | [
"python",
"django",
"migration",
"pip",
"django-south"
] | I'm getting a merciless
```
$ python manage.py migrate
Unknown command: 'migrate'
Type 'manage.py help' for usage.
```
I pulled the code from github onto a fresh computer. This code is tested and is working on other computers. The entire code runs fine except for the fact I can't run migrations!
Installed my virtual... | Successful import of package is not enough for Django management commands. Python can import a package easy from a zipped egg but Django needs a normal uncompressed file.
Advices that simplify your problem initially:
1. Management commands must exist as files in a normal directory `path..to..south/management/commands... |
South: Unknown command 'migrate' | 12,346,033 | 10 | 2012-09-10T05:57:06Z | 22,188,207 | 14 | 2014-03-05T03:57:28Z | [
"python",
"django",
"migration",
"pip",
"django-south"
] | I'm getting a merciless
```
$ python manage.py migrate
Unknown command: 'migrate'
Type 'manage.py help' for usage.
```
I pulled the code from github onto a fresh computer. This code is tested and is working on other computers. The entire code runs fine except for the fact I can't run migrations!
Installed my virtual... | **This is caused largely by following the 1.7 (DEV version) tutorial when we all get the last stable version (1.6) installed by pip.**
Either follow the [1.6 tutorial](https://docs.djangoproject.com/en/1.6/intro/tutorial01/) or follow the instructions to install 1.7 dev version of Django. |
Python - get UTC offset by seconds | 12,346,164 | 2 | 2012-09-10T06:09:52Z | 12,346,261 | 9 | 2012-09-10T06:19:39Z | [
"python",
"timezone",
"pytz"
] | Based on this code, how do I get the UTC offset of a given date by seconds. [get UTC offset from time zone name in python](http://stackoverflow.com/questions/5537876/get-utc-offset-from-time-zone-name-in-python)
Currently, I have this code:
```
Python 2.7.3 (default, Jul 3 2012, 19:58:39)
[GCC 4.7.1] on linux2
Type... | ```
>>> import datetime, pytz
>>> melbourne = pytz.timezone("Australia/Melbourne")
>>> melbourne.utcoffset(datetime.datetime.now())
datetime.timedelta(0, 36000)
>>> pacific = pytz.timezone("US/Pacific")
>>> pacific.utcoffset(datetime.datetime.now())
datetime.timedelta(-1, 61200)
>>> -1*86400+61200
-25200
>>> pacific.u... |
unresolved import in python opencv samples | 12,347,256 | 5 | 2012-09-10T07:44:41Z | 20,273,596 | 10 | 2013-11-28T19:30:56Z | [
"python",
"opencv",
"pydev"
] | I am having problem running the opt\_flow.py in /opencv/samples/python2.
In /samples/python everything is okay. But in python2, there seems something missing.
The python version: 2.7.3
IDE: pyDev in Eclipse
running opt\_flow.py from
<https://github.com/jonmarimba/OpenCVMirror/blob/ff81e19a7a12764c657e2765d69ef166065f... | I had the same problem so here's the answer just to make it clear to others:
The opencv examples import other files in the same folder. The video.py file is in the same place you found the sample you were running. If you copy one of the examples out, you will also need to copy out other files that it imports, includin... |
Python - test whether object is a builtin function | 12,347,647 | 4 | 2012-09-10T08:13:00Z | 12,347,687 | 8 | 2012-09-10T08:15:13Z | [
"python"
] | Is there a nice way to check whether object o is a builtin Python function?
I know I can use, for example
```
type(o) == type(pow)
```
because type(pow) is 'builtin\_function\_or\_method'.
But is there some nicer way? | The types module:
```
>>> import types
>>> types.BuiltinFunctionType
<type 'builtin_function_or_method'>
```
Though, if you look under the hood, you'll find it's not that different from what you're doing now.
So, in your case, use
```
isinstance(o, types.BuiltinFunctionType)
``` |
Can I mix character classes in Python RegEx? | 12,349,118 | 4 | 2012-09-10T09:45:59Z | 12,349,512 | 10 | 2012-09-10T10:11:45Z | [
"python",
"regex"
] | Special sequences (character classes) in Python RegEx are escapes like `\w` or `\d` that matches a set of characters.
In my case, I need to be able to match all alpha-numerical characters except numbers.
That is, `\w` minus `\d`.
I need to use the special sequence `\w` because I'm dealing with **non-ASCII** characte... | You can use `r"[^\W\d]"`, ie. invert the union of non-alphanumerics and numbers. |
ElementTree and unicode | 12,349,728 | 15 | 2012-09-10T10:23:25Z | 12,349,833 | 11 | 2012-09-10T10:30:52Z | [
"python",
"unicode",
"encoding",
"utf-8",
"elementtree"
] | I have this char in an xml file:
```
<data>
<products>
<color>fumè</color>
</product>
</data>
```
I try to generate an instance of ElementTree with the following code:
```
string_data = open('file.xml')
x = ElementTree.fromstring(unicode(string_data.encode('utf-8')))
```
and I get the following error:
`... | You need to **decode** utf-8 strings into a unicode object. So
```
string_data.encode('utf-8')
```
should be
```
string_data.decode('utf-8')
```
assuming `string_data` is actually an utf-8 string.
So to summarize: To get an utf-8 string from a unicode object you **encode** the unicode (using the utf-8 encoding), a... |
ElementTree and unicode | 12,349,728 | 15 | 2012-09-10T10:23:25Z | 12,349,894 | 9 | 2012-09-10T10:35:18Z | [
"python",
"unicode",
"encoding",
"utf-8",
"elementtree"
] | I have this char in an xml file:
```
<data>
<products>
<color>fumè</color>
</product>
</data>
```
I try to generate an instance of ElementTree with the following code:
```
string_data = open('file.xml')
x = ElementTree.fromstring(unicode(string_data.encode('utf-8')))
```
and I get the following error:
`... | You do *not* need to decode XML for ElementTree to work. XML carries it's own encoding information (defaulting to UTF-8) and ElementTree does the work for you, outputting unicode:
```
>>> data = '''\
... <data>
... <products>
... <color>fumè</color>
... </products>
... </data>
... '''
>>> x = ElementTree.fr... |
ElementTree and unicode | 12,349,728 | 15 | 2012-09-10T10:23:25Z | 20,825,396 | 19 | 2013-12-29T13:00:20Z | [
"python",
"unicode",
"encoding",
"utf-8",
"elementtree"
] | I have this char in an xml file:
```
<data>
<products>
<color>fumè</color>
</product>
</data>
```
I try to generate an instance of ElementTree with the following code:
```
string_data = open('file.xml')
x = ElementTree.fromstring(unicode(string_data.encode('utf-8')))
```
and I get the following error:
`... | Might you have stumbled upon this problem while using [Requests (HTTP for Humans)](http://docs.python-requests.org/en/latest/index.html), `response.text` decodes the response by default, you can use `response.content` to get the undecoded data, so ElementTree can decode it itself. Just remember to use the correct encod... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.