text
stringlengths 226
34.5k
|
---|
The line print(var) gives me b'mystring'
Question: In Python, this code:
import serial
ser = serial.Serial('COM6', 115200)
while 1:
a = ser.readline()
print(a)
x = input("don't exit :)")
Gives me:
b'my serial data'
How do I take off this b''?
Answer: Python 3 makes a distinction between bytes and text. If you're sure the serial
data is actually text, you can use `decode`. `decode` needs to know what
character encoding your data is. If it's only going to be sending English text
without anything tricky like "café" or "naïve", ASCII will probably be okay:
text = data.decode('ascii')
If, however, it is not textual data, then you really _do not_ want to be
removing that `b''` part. You'll want to process it while it's still in its
`bytes` form. How to do that depends on what exactly you want to do with it,
just as if it were a textual string.
|
Python CSV Module - Can't hold text format
Question: EDIT* Solution was to wrap text in the column. This will restore the original
format.
I am trying to create a CSV using the CSV module provided in Python. My issue
is when the CSV is created the contents of the file inserted into the field
loses it's format.
Example input can be pulled from 'whois 8.8.8.8'. I want the field to hold the
formatting from that input.
Is there a way to maintain the files original format within the cell?
#!/usr/bin/python
import sys
import csv
file1 = sys.argv[1]
file2 = sys.argv[2]
myfile1 = open(file1, "rb")
myfile2 = open(file2, "rb")
ofile = open('information.csv', "wb")
stuffwriter = csv.writer(ofile, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL)
stuffwriter.writerow([myfile1.read(),myfile2.read()])
myfile1.close()
myfile2.close()
ofile.close()
Example Input(All In One Cell):
#
# ARIN WHOIS data and services are subject to the Terms of Use
# available at: https://www.arin.net/whois_tou.html
#
#
# Query terms are ambiguous. The query is assumed to be:
# "n 8.8.8.8"
#
# Use "?" to get help.
#
#
# The following results may also be obtained via:
# http://whois.arin.net/rest/nets;q=8.8.8.8?showDetails=true&showARIN=false&ext=netref2
#
Level 3 Communications, Inc. LVLT-ORG-8-8 (NET-8-0-0-0-1) 8.0.0.0 - 8.255.255.255
Google Incorporated LVLT-GOOGL-1-8-8-8 (NET-8-8-8-0-1) 8.8.8.0 - 8.8.8.255
#
# ARIN WHOIS data and services are subject to the Terms of Use
# available at: https://www.arin.net/whois_tou.html
#
Would like the cell to hold the format above. Currently when I open in Excel
it is all one line.
I am getting my data from executing:
whois 8.8.8.8 > inputData.txt
echo "8.8.8.8 - Google" > inputData2.txt
python CreateCSV inputData2.txt inputData.txt
This is what I would like to see:
<http://www.2shared.com/photo/WZwDC7w2/Screen_Shot_2013-06-06_at_1231.html>
This is what I'm seeing:
<http://www.2shared.com/photo/9dRFGCxh/Screen_Shot_2013-06-06_at_1222.html>
Answer: 1. Convert .CSV to an .XLSX
2. In Excel, right click column with data that lost it's format
3. Select 'Format Cells...'
4. Select the 'Alignment' tab
5. Check 'Wrap Text'
6. All is good!
|
Grouping python pandas
Question: Could you tell me how to group a table (from products1.txt file) like
following:
Age;Name;Country
10;Valentyn;Ukraine
12;Igor;Russia
12;Valentyn;
10;Valentyn;Russia
So I can find out how many Valentyns have an empty "Country" cell.
I ran the following code:
import pandas as pd
df = pd.read_csv('d:\products1.txt', sep = ";")
result = df[(df["Name"] == "Valentyn") & (df["Country"] == None)]
But I get an error...
Answer: You should use `isnull` (rather than `== None`) to check for `NaN`:
In [11]: df[(df.Country.isnull()) & (df.Name == 'Valentyn')]
Out[11]:
Age Name Country
2 12 Valentyn NaN
Another option would be to check those which had Country `NaN` and then count
the values:
In [12]: df.Name[df.Country.isnull()]
Out[12]:
2 Valentyn
Name: Name, dtype: object
In [13]: df.Name[df.Country.isnull()].value_counts()
Out[13]:
Valentyn 1
dtype: int64
|
Error installing matplotlib - python2.7 (RHEL 5.9)
Question: I have an altinstall of python 2.7 on my RHEL 5.9 desktop (python 2.4 ships
with rhel5). I have installed `numpy1.7.1` and `scipy-0.12.0` successfully
from source. However when I try to build `matplotlib1.2.1` (`python2.7
setup.py build`) I get the following error message which I am unable to debug
============================================================================
BUILDING MATPLOTLIB
matplotlib: 1.2.1
python: 2.7.5 (default, May 16 2013, 15:45:29) [GCC 4.1.2
20080704 (Red Hat 4.1.2-54)]
platform: linux2
REQUIRED DEPENDENCIES
numpy: 1.7.1
freetype2: found, but unknown version (no pkg-config)
* WARNING: Could not find 'freetype2' headers in any
* of '/usr/local/include', '/usr/include',
* '/usr/local/include', '/usr/include', '.',
* '/usr/local/include/freetype2',
* '/usr/include/freetype2',
* '/usr/local/include/freetype2',
* '/usr/include/freetype2', './freetype2'.
OPTIONAL BACKEND DEPENDENCIES
libpng: found, but unknown version (no pkg-config)
* Could not find 'libpng' headers in any of
* '/usr/local/include', '/usr/include',
* '/usr/local/include', '/usr/include', '.'
Tkinter: Tkinter: 81008, Tk: 8.4, Tcl: 8.4
Gtk+: no
* Building for Gtk+ requires pygtk; you must be able
* to "import gtk" in your build/install environment
Mac OS X native: no
Qt: no
Qt4: no
PySide: no
Cairo: no
OPTIONAL DATE/TIMEZONE DEPENDENCIES
dateutil: matplotlib will provide
pytz: matplotlib will provide
OPTIONAL USETEX DEPENDENCIES
dvipng: 1.5
ghostscript: 8.70
latex: 3.141592
pdftops: 3.00
[Edit setup.cfg to suppress the above messages]
============================================================================
pymods ['pylab']
packages ['matplotlib', 'matplotlib.backends', 'matplotlib.backends.qt4_editor', 'matplotlib.projections', 'matplotlib.testing', 'matplotlib.testing.jpl_units', 'matplotlib.tests', 'mpl_toolkits', 'mpl_toolkits.mplot3d', 'mpl_toolkits.axes_grid', 'mpl_toolkits.axes_grid1', 'mpl_toolkits.axisartist', 'matplotlib.sphinxext', 'matplotlib.tri', 'matplotlib.delaunay', 'pytz', 'dateutil', 'dateutil.zoneinfo']
running build
running build_py
copying lib/matplotlib/mpl-data/matplotlibrc -> build/lib.linux-x86_64-2.7/matplotlib/mpl-data
running build_ext
building 'matplotlib.ft2font' extension
gcc -DNDEBUG -g -fwrapv -O3 -Wall -Wall -g -O -fPIC -DPY_ARRAY_UNIQUE_SYMBOL=MPL_ARRAY_API -DPYCXX_ISO_CPP_LIB=1 -I/usr/local/include -I/usr/include -I/usr/local/lib/python2.7/site-packages/numpy/core/include -I/usr/local/include -I/usr/include -I. -I/usr/local/include/freetype2 -I/usr/include/freetype2 -I/usr/local/lib/python2.7/site-packages/numpy/core/include/freetype2 -I/usr/local/include/freetype2 -I/usr/include/freetype2 -I./freetype2 -I/usr/local/include/python2.7 -c src/ft2font.cpp -o build/temp.linux-x86_64-2.7/src/ft2font.o
In file included from src/ft2font.cpp:3:
src/ft2font.h:16:22: error: ft2build.h: No such file or directory
src/ft2font.h:17:10: error: #include expects "FILENAME" or <FILENAME>
src/ft2font.h:18:10: error: #include expects "FILENAME" or <FILENAME>
src/ft2font.h:19:10: error: #include expects "FILENAME" or <FILENAME>
src/ft2font.h:20:10: error: #include expects "FILENAME" or <FILENAME>
src/ft2font.h:21:10: error: #include expects "FILENAME" or <FILENAME>
In file included from /usr/local/lib/python2.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1728,
from /usr/local/lib/python2.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:17,
from /usr/local/lib/python2.7/site-packages/numpy/core/include/numpy/arrayobject.h:15,
from src/ft2font.cpp:7:
/usr/local/lib/python2.7/site-packages/numpy/core/include/numpy/npy_deprecated_api.h:11:2: warning: #warning "Using deprecated NumPy API, disable it by #defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION"
src/ft2font.h:34: error: ‘FT_Bitmap’ has not been declared
src/ft2font.h:34: error: ‘FT_Int’ has not been declared
src/ft2font.h:34: error: ‘FT_Int’ has not been declared
src/ft2font.h:86: error: expected ‘,’ or ‘...’ before ‘&’ token
src/ft2font.h:86: error: ISO C++ forbids declaration of ‘FT_Face’ with no type
src/ft2font.h:132: error: ‘FT_Face’ does not name a type
src/ft2font.h:133: error: ‘FT_Matrix’ does not name a type
src/ft2font.h:134: error: ‘FT_Vector’ does not name a type
src/ft2font.h:135: error: ‘FT_Error’ does not name a type
src/ft2font.h:136: error: ‘FT_Glyph’ was not declared in this scope
src/ft2font.h:136: error: template argument 1 is invalid
src/ft2font.h:136: error: template argument 2 is invalid
src/ft2font.h:137: error: ‘FT_Vector’ was not declared in this scope
src/ft2font.h:137: error: template argument 1 is invalid
src/ft2font.h:137: error: template argument 2 is invalid
src/ft2font.h:143: error: ‘FT_BBox’ does not name a type
src/ft2font.cpp:41: error: ‘FT_Library’ does not name a type
src/ft2font.cpp:106: error: variable or field ‘draw_bitmap’ declared void
src/ft2font.cpp:106: error: ‘int FT2Image::draw_bitmap’ is not a static member of ‘class FT2Image’
src/ft2font.cpp:106: error: ‘FT_Bitmap’ was not declared in this scope
src/ft2font.cpp:106: error: ‘bitmap’ was not declared in this scope
src/ft2font.cpp:107: error: ‘FT_Int’ was not declared in this scope
src/ft2font.cpp:108: error: ‘FT_Int’ was not declared in this scope
src/ft2font.cpp:108: error: initializer expression list treated as compound expression
src/ft2font.cpp:109: error: expected ‘,’ or ‘;’ before ‘{’ token
/usr/local/lib/python2.7/site-packages/numpy/core/include/numpy/__multiarray_api.h:1594: warning: ‘int _import_array()’ defined but not used
error: command 'gcc' failed with exit status 1
I get similar error messages when using pip-2.7 and easy_install-2.7. Any
ideas?
* * *
Following Huy Phan's suggestion to install freetype-devel I get a new error
log
basedirlist is: ['/usr/local', '/usr']
============================================================================
BUILDING MATPLOTLIB
matplotlib: 1.2.1
python: 2.7.5 (default, May 16 2013, 15:45:29) [GCC 4.1.2
20080704 (Red Hat 4.1.2-54)]
platform: linux2
REQUIRED DEPENDENCIES
numpy: 1.7.1
freetype2: 9.10.3
OPTIONAL BACKEND DEPENDENCIES
libpng: found, but unknown version (no pkg-config)
* Could not find 'libpng' headers in any of
* '/usr/local/include', '/usr/include',
* '/usr/local/include', '/usr/include', '.'
Tkinter: Tkinter: 81008, Tk: 8.4, Tcl: 8.4
Gtk+: no
* Building for Gtk+ requires pygtk; you must be able
* to "import gtk" in your build/install environment
Mac OS X native: no
Qt: no
Qt4: no
PySide: no
Cairo: no
OPTIONAL DATE/TIMEZONE DEPENDENCIES
dateutil: matplotlib will provide
pytz: matplotlib will provide
OPTIONAL USETEX DEPENDENCIES
dvipng: 1.5
ghostscript: 8.70
latex: 3.141592
pdftops: 3.00
[Edit setup.cfg to suppress the above messages]
============================================================================
pymods ['pylab']
packages ['matplotlib', 'matplotlib.backends', 'matplotlib.backends.qt4_editor', 'matplotlib.projections', 'matplotlib.testing', 'matplotlib.testing.jpl_units', 'matplotlib.tests', 'mpl_toolkits', 'mpl_toolkits.mplot3d', 'mpl_toolkits.axes_grid', 'mpl_toolkits.axes_grid1', 'mpl_toolkits.axisartist', 'matplotlib.sphinxext', 'matplotlib.tri', 'matplotlib.delaunay', 'pytz', 'dateutil', 'dateutil.zoneinfo']
running build
running build_py
copying lib/matplotlib/mpl-data/matplotlibrc -> build/lib.linux-x86_64-2.7/matplotlib/mpl-data
running build_ext
building 'matplotlib._png' extension
gcc -DNDEBUG -g -fwrapv -O3 -Wall -Wall -g -O -fPIC -DPY_ARRAY_UNIQUE_SYMBOL=MPL_ARRAY_API -DPYCXX_ISO_CPP_LIB=1 -I/usr/local/include -I/usr/include -I/usr/local/include -I/usr/include -I. -I/usr/local/lib/python2.7/site-packages/numpy/core/include -I. -I/usr/local/include/python2.7 -c src/_png.cpp -o build/temp.linux-x86_64-2.7/src/_png.o
src/_png.cpp:10:20: error: png.h: No such file or directory
In file included from /usr/local/lib/python2.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1728,
from /usr/local/lib/python2.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:17,
from /usr/local/lib/python2.7/site-packages/numpy/core/include/numpy/arrayobject.h:15,
from src/_png.cpp:28:
/usr/local/lib/python2.7/site-packages/numpy/core/include/numpy/npy_deprecated_api.h:11:2: warning: #warning "Using deprecated NumPy API, disable it by #defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION"
src/_png.cpp:67: error: variable or field ‘write_png_data’ declared void
src/_png.cpp:67: error: ‘png_structp’ was not declared in this scope
src/_png.cpp:67: error: ‘png_bytep’ was not declared in this scope
src/_png.cpp:67: error: ‘png_size_t’ was not declared in this scope
src/_png.cpp:67: error: initializer expression list treated as compound expression
src/_png.cpp:68: error: expected ‘,’ or ‘;’ before ‘{’ token
/usr/local/lib/python2.7/site-packages/numpy/core/include/numpy/__multiarray_api.h:1594: warning: ‘int _import_array()’ defined but not used
src/_png.cpp:67: warning: ‘write_png_data’ defined but not used
error: command 'gcc' failed with exit status 1
Answer: Looks like your system doesn't have `freetype-devel` installed. Try
sudo yum install freetype-devel
first.
In addition you may need to install `libpng-devel`,
sudo yum install libpng-devel
|
Magnitude calculation in python
Question: i'm trying to calculate magnitudes of some stars based on their flux but I
keep getting the wrong values and I don't know why. For example:
The first star has a flux in the V-band of 39,984. Its V-magnitude is equal to
10.1 - 2.5log(39,984/1,220,000) = 13,8 (the 10.1 and 1,220,000 are from a
reference star). But my program calculates a magnitude of 18.65. Here's my
code:
import numpy as np
import asciidata
fv = []
fb = []
data = asciidata.open('Flux.txt')
for i in data[1]:
fv.append(float(i))
for i in data[2]:
fb.append(float(i))
mv = []
mb = []
mbv = []
for i in range (0,25):
mv.append(10.1 - 2.5 * np.log(fv[i]/1220000))
mb.append(11.0 - 2.5 * np.log(fb[i]/339368))
print i+1, mv[i], mb[i]
Answer: I'm assuming you want to use `numpy.log10` (log base 10) instead of
`numpy.log` (base 2).
>>> import numpy as np
>>> 10.1 - 2.5*np.log(39984./1220000)
18.645316909086766
>>> 10.1 - 2.5*np.log10(39984./1220000)
13.811183979730934
|
Calling python script from C++ and using its output
Question: I want to call a python script from C++ and wish to use the output .csv file
generated by this script back into C++. I tried this in main():
std::string filename = "/home/abc/xyz/script.py";
std::string command = "python ";
command += filename;
system(command.c_str());
This does call and execute the python script.
**EDIT_2** The '**print** ' commands in the python are being executed...things
are being printed on the screen when the script is called. So far so good.
But! it is not creating the .csv file (part of the same script). like: i had a
**training.csv** file with **100 entries**. I called the python script, with
little changes to the script so that the trainig.csv file **now should contain
only 50 entries instead of 100. Its overwritten**. But, no such thing
happening. Rest of the commands in script (print, etc) are working perfectly.
The **training.csv** file is to be read with C++ normally using **fstream**
and **getline**...
Any idea how to do it?
**EDIT** using linux
Thanks!
Answer: Here is a solution to embed the execution of your python module from within
your C++ application. It's not better or worst than forking/executing your
python script through a system call, it just is a different way to do it.
Whether it is best or not depend on your context and usage.
Some time ago I have coded a way to load python modules as plugins to a C++
application, here's the [interesting part](https://github.com/hackable-
devices/polluxnzcity/blob/master/PolluxGateway/src/pollux/pollux_extension.C).
Basically, you need to `#include <Python.h>`, then `Py_Initialize()` to start
your python interpreter.
Then you do `import sys`, using : `PyRun_SimpleString("import sys");`, and you
can load your plugin by doing
`PyRun_SimpleString('sys.path.append("path/to/my/module/")')`.
To exchange values between C++ and Python, things get harder, you have to to
transform all your C++ objects into python objects (starting line 69 in my
script).
Then you can call your function using `PyObject_Call_Object(...)`, using all
the python objects you created as arguments.
You get the return value, and transforms all those values in C++ objects. And
don't forget the memory management in all that!
To end your python interpreter, a simple call to `Py_Finalize()`.
It really looks harder than it is really, but you have to be really careful
doing this, because it could lead to leaks, security issues etc..
|
Process information using Python, NOT using wmi, psutil, tasklist
Question: I'm writing a Python script that gets information on processes (PID, Command
Line, etc.) running on a PC.
On my Windows 7 PC I can use 'wmic' and use the output from that:
_output = subprocess.Popen(['wmic process get
creationdate,commandline,processid'], stdout=subprocess.PIPE,
shell=True).communicate()[0]_
Example of the info I can get from this output:
_PROCESS PID START TIME COMMAND: blah.exe 1234 Thu Jun 06 15:33:40 2013
C:\blah\blah.exe -a -b blah.txt_
This gives me all the info I need... HOWEVER not all machines will let me use
'wmic' as I'm not an Administrator.
I can use 'tasklist', but it doesn't give me the 'commandline' info that wmic
does.
I can't use 'psutils' (or the 'wmi' module), as it's not installed on any of
the PCs I need it to work on, and I don't want to have to get admin install
modules on all these PCs
Any ideas on how I can get the above process information using standard Python
2.6?
Thanks in advance, Nick
PYTHON 2.6 on Windows XP/7
=====================================================================
EDIT (12 June 2013):
I'm trying to do as suggested below, but having trouble... I've put the psutil
directory (psutil-0.7.1) in the same directory as my script and added the
following to my script:
path = '.\psutil-0.7.1'
sys.path.append(path)
import psutil
I now get the below error:
Traceback (most recent call last):
File "C:\Users\nickw\Desktop\ProcessMonitor\ProcessMonitor_MODPS2.py", line 21, in <module>
import psutil
File ".\psutil-0.7.1\psutil\__init__.py", line 77, in <module>
import psutil._psmswindows as _psplatform
File ".\psutil-0.7.1\psutil\_psmswindows.py", line 15, in <module>
import _psutil_mswindows
ImportError: No module named _psutil_mswindows
Any idea what I'm doing wrong?
Answer: The technique to retrieve a process's command line is somewhat hacky but was
included into WMI since XP. Basically, it's reading another process's memory.
See e.g. [Getting another process command line in
Windows](http://stackoverflow.com/questions/6530565/getting-another-process-
command-line-in-windows) and links from there for details.
So, you either
* re-implement it yourself by hand, with `ctypes` or whatever, like the link above says, or
* somehow, utilize existing modules that will do that for you. There's [`zipimport`](http://docs.python.org/2/library/zipimport.html) to make this easier for multiple files and [`virtualenv`](https://pypi.python.org/pypi/virtualenv) to create whole environments anywhere on the filesystem, the latter likely being an overkill.
|
Reusing code from different IPython notebooks
Question: I am using IPython and want to run functions from one notebook from another
(without cutting and pasting them between different notebooks). Is this
possible and reasonably easy to do?
Answer: Starting your notebook server with:
ipython notebook --script
will save the notebooks (`.ipynb`) as Python scripts (`.py`) as well, and you
will be able to import them.
Or have a look at: <http://nbviewer.ipython.org/5491090/> that contains 2
notebook, one executing the other.
|
Twitter Search Query in Python
Question: I am trying to pull tweets matching the given search query. I'm using the
following code :
import urllib2 as urllib
import json
response = urllib.urlopen("https://search.twitter.com/search.json?q=microsoft")
pyresponse = json.load(response)
print pyresponse
This was working a few days ago, but suddenly stopped working now. With some
help from google, I learned that this type of url in not supported anymore.
How do I perform this search query. What url shall I use?
Answer: Twitter is deprecating non-authenticated searches. You should look into Tweepy
or another Python library that interacts with Twitter.
<https://github.com/tweepy/tweepy>
|
Pythonic way to split a line into groups of four words?
Question: Suppose I have string that look like the following, of varying length, but
with the number of "words" always equal to multiple of 4.
9c 75 5a 62 32 3b 3a fe 40 14 46 1c 6e d5 24 de
c6 11 17 cc 3d d7 99 f4 a1 3f 7f 4c
I would like to chop them into strings like `9c 75 5a 62` and `32 3b 3a fe`
I could use a regex to match the exact format, but I wonder if there is a more
straightforward way to do it, because regex seems like overkill for what
should be a simple problem.
Answer: A staight-forward way of doing this is as follows:
wordlist = words.split()
for i in xrange(0, len(wordlist), 4):
print ' '.join(wordlist[i:i+4])
If for some reason you can't make a list of all words (e.g. an infinite
stream), you could do this:
from itertools import groupby, izip
words = (''.join(g) for k, g in groupby(words, ' '.__ne__) if k)
for g in izip(*[iter(words)] * 4):
print ' '.join(g)
Disclaimer: I didn't come up with this pattern; I found it in a similar topic
a while back. It arguably relies on an implementation detail, but it would be
quite a bit more ugly when done in a different way.
|
How can I select an element from this drop down menu in Python/Selenium?
Question: I've looked through a few solutions to select drop down elements, but none of
them are working for me.
This is the html for the dropdown.
<div class="goog-inline-block goog-flat-menu-button" role="button" style="-moz-user-select: none;" tabindex="3" aria-haspopup="true">
<div class="goog-inline-block goog-flat-menu-button-caption">Resolved</div>
<div class="goog-inline-block goog-flat-menu-button-dropdown"> </div>
</div>
I've tried finding the dropdown by xpath and link text with no success.
EDIT: Here's the code I'm using
import contextlib
import selenium.webdriver as webdriver
import selenium.webdriver.support.ui as ui
from selenium.webdriver.common.keys import Keys
import re
with contextlib.closing(webdriver.Firefox()) as driver:
driver.get("https://websitename.com/#ticket/123456")
wait = ui.WebDriverWait(driver, 30)
wait.until(lambda driver: driver.find_element_by_xpath("//div[@class='goog-inline-block goog-flat-menu-button"))
driver.find_element_by_xpath("//div[@class='goog-inline-block goog-flat-menu-button").click()
driver.find_element_by_xpath("//div[@class='goog-inline-block goog-flat-menu-button").send_keys("R")
wait6 = ui.WebDriverWait(driver, 30)
The code is supposed to change the selected drop down list element from
assigned to resolved.
Answer: What xpath did you try?
The simplest I can see is:
driver.find_element_by_xpath("//div[contains(@class, 'goog-flat-menu-button-dropdown')]")
However I'm a little confused about your request about 'selecting' as this
isn't a `select` element so I'm sorry, I'm not sure I can help there.
Try the given below method with the help of CSS Selector
driver.find_element_by_cssselector(".goog-flat-menu-button > .goog-flat-menu-button-dropdown").click();
I am sure the above CSS Selector will work.
|
Does python have built in type values?
Question: Not a typo. I mean type values. Values who's type is 'type'.
I want to write a confition to ask:
if type(f) is a function : do_something()
Do I NEED to created a temporary function and do:
if type(f) == type(any_function_name_here) : do_something()
or is that a built-in set of type types that I can use? Like this:
if type(f) == functionT : do_something()
Answer: For functions you would usually check
>>> callable(lambda: 0)
True
to respect duck typing. However there is the `types` module:
>>> import types
>>> dir(types)
['BooleanType', 'BufferType', 'BuiltinFunctionType', 'BuiltinMethodType', 'ClassType', 'CodeType', 'ComplexType', 'DictProxyType', 'DictType', 'DictionaryType', 'EllipsisType', 'FileType', 'FloatType', 'FrameType', 'FunctionType', 'GeneratorType', 'GetSetDescriptorType', 'InstanceType', 'IntType', 'LambdaType', 'ListType', 'LongType', 'MemberDescriptorType', 'MethodType', 'ModuleType', 'NoneType', 'NotImplementedType', 'ObjectType', 'SliceType', 'StringType', 'StringTypes', 'TracebackType', 'TupleType', 'TypeType', 'UnboundMethodType', 'UnicodeType', 'XRangeType', '__builtins__', '__doc__', '__file__', '__name__', '__package__']
However you shouldn't check `type` equality, instead use `isinstance`
>>> isinstance(lambda: 0, types.LambdaType)
True
|
python test result reporting
Question: My question is regarding python unittest reporting. I am using the xmlrunner
package which produces the xunit output which is used by Jenkins. In addition
to that, I want to either produce an html output or print out the output in a
nice custom format. Note: I already know about HTMLTestRunner and it did not
make me happy. There are 3 problems:
* my tests are not displayed as suite groups (the report does not show the grouping)
* the test details are not shown (purpose of the test)
* the failure stack traces should not be shown in a report that is made for the management
**The question is how to iterate through the test results?**
Here is my test runner code:
import unittest
import os, sys
import xmlrunner
def getSuites(root):
testSets = {"ts1":["tc1","tc2"], "ts2":["tc3","tc4"]}
suites = unittest.TestSuite()
for ts_name,ts in testSets.iteritems():
ts_dir = "%s/%s" % (root, ts_name)
sys.path.append(ts_dir)
print "ts_dir = %s" % ts_dir
for tc in ts:
module = __import__(tc,{},{},['1'])
suites.addTest(unittest.TestLoader().loadTestsFromModule(module))
return suites
if __name__ == "__main__":
root = os.path.dirname(os.path.abspath(__file__))
suites = getSuites(root)
results = xmlrunner.XMLTestRunner(output='test_reports').run(suites)
Note:
for r in results:
print r
throws an exception saying that _XMLTestResult is not iterable. Thanks
Answer:
for x in results.successes + results.failures + results.errors:
print x
#print x.get_description(), x.outcome
|
Server Error (500) on Django when template debug is set to False?
Question: I am seeing `Django 500 Error` when I set `DEBUG = False` in Django. I am
using `Django 1.5 and Python 2.7`. I have also included `ALLOWED_HOSTS` in my
template. Here's my full settings.py:
# Django settings for genalytics project.
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS
import djcelery
import os
__file__ = os.getcwd()
ROOT_PATH = os.path.dirname(__file__)
djcelery.setup_loader()
#New in Django 1.5
ALLOWED_HOSTS = ['localhost', '127.0.0.1:8000']
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('sachit', '[email protected]')
)
BROKER_TRANSPORT = "sqlalchemy"
BROKER_URL = "sqla+mysql://root:password@localhost/galaxy"
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'galaxy', # Or path to database file if using sqlite3.
'USER': 'root', # Not used with sqlite3.
'PASSWORD': 'password', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '' # Set to empty string for default. Not used with sqlite3.
}
}
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = ''
STATIC_URL = '/static/'
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
AUTHENTICATION_BACKENDS = (
'fileupload.backend.AuthBackend',
)
# Additional locations of static files
STATICFILES_DIRS = (
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = '$ec_7m$05ddhhc_cy(j-i^%70ochjmx*$0_o!$u1q9rkkd(ai$'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
TEMPLATE_CONTEXT_PROCESSORS += (
'django.core.context_processors.request',
'django.contrib.messages.context_processors.messages'
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'fileupload.middleware.AutoLogout'
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'
#Pagination Setting
ENDLESS_PAGINATION_PREVIOUS_LABEL = '<'
ENDLESS_PAGINATION_NEXT_LABEL = '>'
ENDLESS_PAGINATION_FIRST_LABEL = '|<'
ENDLESS_PAGINATION_LAST_LABEL = '>|'
ROOT_URLCONF = 'genalytics.urls'
SESSION_COOKIE_AGE = 30 * 60
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'genalytics.wsgi.application'
TEMPLATE_DIRS = (
os.path.join(ROOT_PATH, 'fileupload/templates'),
)
DESTINATION = '/home/zurelsoft/files/'
AUTO_LOGOUT_DELAY = 30
AUTH_USER_MODEL = 'fileupload.user'
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'fileupload',
'django.contrib.admin',
'endless_pagination',
'djcelery',
'endless_pagination'
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
What's wrong?
Updated the logging as Ryu_hayabusa suggested and I am getting this error in
the console:
Unhandled exception in thread started by <bound method Command.inner_run of <django.contrib.staticfiles.management.commands.runserver.Command object at 0x22e08d0>>
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 114, in inner_run
ipv6=self.use_ipv6, threading=threading)
File "/usr/local/lib/python2.7/dist-packages/django/core/servers/basehttp.py", line 193, in run
httpd.serve_forever()
File "/usr/lib/python2.7/SocketServer.py", line 235, in serve_forever
r, w, e = _eintr_retry(select.select, [self], [], [],
AttributeError: 'NoneType' object has no attribute 'select'
Answer: For django v 1.5+ , in your settings.py file, Make the configuration
ALLOWED_HOSTS = ['*'] if you want a quick fix
If you are really going production (and concerned about security), put allowed
host names in ALLOWED_HOSTS
this SO link has more info
[Setting DEBUG = False causes 500
Error](http://stackoverflow.com/questions/15128135/setting-debug-false-
causes-500-error/19268741#19268741)
|
Character encoding in a GET request with http.client lib (Python)
Question: I am a beginner in python and I coded this little script to send an HTTP GET
request on my local server (localhost). It works great, except that I wish I
could send Latin characters such as accents.
import http.client
httpMethod = "GET"
url = "localhost"
params = "Hello World"
def httpRequest(httpMethod, url, params):
conn = http.client.HTTPConnection(url)
conn.request(httpMethod, '/?param='+params)
conn.getresponse().read()
conn.close()
return
httpRequest(httpMethod, url, params)
When I insert the words with accent in my parameter "params", this is the
error message that appears:
_UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position
14: ordinal not in range(128)_
I don't know if there is a solution using http.client library but I think so.
When I look in the documentation http.client, I can see this:
**HTTPConnection.request**
Strings are encoded as ISO-8859-1, the default charset for HTTP
Answer: You shouldn't construct arguments manually. Use
[`urlencode`](http://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlencode)
instead:
>>> from urllib.parse import urlencode
>>> params = 'Aserejé'
>>> urlencode({'params': params})
'params=Aserej%C3%A9'
So, you can do:
conn.request(httpMethod, '/?' + urlencode({'params': params}))
_Also note that yout string will be encoded as UTF-8 before being URL-
escaped_.
|
Ipython deep_reload Exception when importing from sqlalchemy
Question: I am working on several modules of my python library, doing most of the
testing through IPython.
Anytime I attempt to reload (deep_reload) a module that uses sqlalchemy, the
reload throws an Exception and fails to reload the module (I must start a new
kernel and re-import). More specifically, any module that imports my
sqlalchemy declarative models.
The traceback is quite long, so I will summarize for now, and provide more if
requested.
* * *
**Before the Exception, StdOUT reads (this is only the bottom portion):**
Reloading pysqlite2
Reloading sqlalchemy.dialects.sqlite.sqlite3
Reloading sqlite3
Reloading sqlite3.dbapi2
Reloading sqlite3.datetime
Reloading sqlite3.time
Reloading sqlite3._sqlite3
Reloading _sqlite3
**Then the exception is thrown, and here is the most recent entry of the
traceback:**
\pydir\lib\site-packages\sqlalchemy-0.7.9-py2.7.egg\sqlalchemy\util\_collections.pyc in __setitem__(self, object, value)
697 if oid not in self._weakrefs:
698 self._weakrefs[oid] = self._ref(object)
--> 699 weakref.WeakKeyDictionary.__setitem__(self, object, value)
700
701 def __delitem__(self, object):
TypeError: unbound method __setitem__() must be called with WeakKeyDictionary instance as first argument (got WeakIdentityMapping instance instead)
* * *
* * *
## Edit: Problem Update
When calling reload, I started adding exclusions based on the module on the
top of the traceback stack ('_sqlite3' in the example above).
What I found was that I kept getting the same Error, only it would come from a
new module ('pysqlite2', 'sqlite3'). And in each case, there was always
SqlAlchemy higher up on the traceback, more specifically,
'sqlalchemy.orm.mapper'.
When defining my model orm classes, I was defining my orm classes and adding
them to the session directly from the module on import. The solution was to
wrap these few lines in a function that should not be executed on import.
Seems to fix.
I think this was just a case of some lazy coding finally catching up with me.
Answer: You might add sqlite3 (or pysqlite2) to deep reload's exclusions:
dreload(mymod, exclude=['sys', 'os.path', '__builtin__', '__main__', 'sqlite3'])
etc.
|
Increment variable in callback during upload
Question: I have the following python script for an upload that needs to show percent
done. I am having trouble incrementing the variable that tracks the amount of
data transferred. I get an
_UnboundLocalError: local variable 'intProgress' referenced before assignment_
error. Yet if I try to print this variable it prints fine so it seems that it
is referenced.
import os, sys, ftplib
pathname = 'C:/Paradigm1/1.PNG'
intFileSize = os.path.getsize(pathname)
intPercentDone = 0
intProgress = 0
def callback(p):
intProgress = intProgress + 1024
##sys.stdout.write(str(intProgress))
sys.stdout.write("-")
session = ftplib.FTP('Server','UserName','Password')
f = open(pathname,'rb')# file to send
session.storbinary('STOR /Ftp Accounts/PublicDownloads/test.png', f, 1024, callback)
f.close()
Answer: If you want the `callback()` function to change the global variable
`intProgress`, you have to declare it as `global` in the function...
def callback(p):
global intProgress
intProgress = intProgress + 1024
##sys.stdout.write(str(intProgress))
sys.stdout.write("-")
...otherwise it'll assume `intProgress` is a local variable, and get confused
by the fact that you're trying to reference it when setting it.
|
Command line argument as default to a function defined in another module
Question: Lets say I have two modules within a package, `one.py` and `two.py`, plus a
`config.py`. I want to execute `one.py` on the command line and pass an
argument that is available as the default to a function in `two.py`... By way
of example:
## one.py:
import sys, getopt
import config
def main(argv):
opts, _ = getopt.getopt(argv, 'hs', ['--strict='])
for opt, _ in opts:
if opt in ('-s', '--strict'):
config.strict = True
import two
two.foo()
if __name__ == '__main__':
main(sys.argv[1:])
## two.py
from config import strict
def foo(s=strict):
if s:
print "We're strict"
else:
print "We're relaxed around these parts"
## config.py
strict = False
Now, this works but seems clunky and poor form what with the import in the
middle of my `main` function... I assume there is a way to do this with
decorators? Or one of the lazy evaluation modules, but I'm at a loss! What is
the most pythonic way to use a command line argument as a default to a
function defined in another module?
Answer: You can change the default by overwriting the function's `func_defaults`
(`__defaults__` in python3.x) attribute:
>>> def foo(a=True):
... print a
...
>>> foo()
True
>>> foo.func_defaults
(True,)
>>> foo.func_defaults = (False,)
>>> foo()
False
>>>
I don't know that I would say that this is "pythonic". As far as I'm
concerned, the most pythonic solution would be to just pass the argument:
import two
def main(argv):
opts, _ = getopt.getopt(argv, 'hs', ['--strict='])
for opt, _ in opts:
if opt in ('-s', '--strict'):
config.strict = True
two.foo(s=config.strict)
|
Render template to escaped string for json in Django
Question: This is more of a general python question, but it becomes a little more
complicated in the context of Django.
I have a template, like this, simplified:
<span class="unit">miles</span>
I'm replacing an element with jquery and ajax:
$.getJSON('/getunit/', function(data){
$('#unitHolder').html(data.unit_html);
});
Which goes to a view function to retrieve json data (more data than just this
template). So I wanted to serve it up as json, and not just a string. So, the
relevant code is this:
...
context = { 'qs' : queryset }
data['unit'] = render_to_string('map/unit.html', context)
data = str(data).replace('\'','"') #json wants double quotes
return HttpResponse(data, mimetype="application/json")
This works for all of our other data, but not the template, because it has
double quotes in it, that are not escaped. My question is, how do you escape a
string in python to be used in a json format? Note that render_to_string()
renders the string in unicode, thus `u"<span>...</span>"`.
## I've tried
import json
data['unit'] = json.dumps(render_to_string('map/unit.html', context))
But that gives me `"unit": ""<span class=\\"unit\\">miles</span>""`.
Also:
data['unit'] = str(render_to_string('map/unit.html', context)).replace('"','\"')
and:
data['unit'] = str(render_to_string('map/unit.html', context)).replace('"','\\"')
But neither escape the double quotes properly.
Answer: I hadn't tried `json.dumps` until I came into this problem. Previously I was
just converting python dictionaries to strings and then replacing single
quotes with double quotes. And for most of the data we've been passing to the
client, it rendered correct JSON format. Now that I've tried `json.dumps` here
in this problem, I realized that I don't need to convert dictionaries with
`str` or `replace` anything. I can render the script as follows:
...
context = { 'qs' : queryset }
data['unit'] = render_to_string('map/unit.html', context)
import json # I'll import this earlier
data = json.dumps(data)
return HttpResponse(data, mimetype="application/json")
This works with all the data I'm passing to JSON format, so that works
perfectly fine, and that's how I should have been doing it all along.
|
Python 3 Regex Last Match
Question: How do I grab the `123` part of the following string using Python 3 regex
module?
....XX (a lot of HTML characters)123
Here the `...` Part denotes a long string consisting of HTML characters, words
and numbers.
The number `123` is a characteristic of `XX`. So if anybody could suggest a
universal method in which `XX` can be any letters like `AA` or `AB`, it would
be more helpful.
Side Note:
I thought of using Perl's `\G` operator by first identifying `XX` in the
string and then identifying the first number appearing after `XX`. But it
seems `\G` operator doesn't work in Python 3.
My code:
import re
source='abcd XX blah blah 123 more blah blah'
grade=str(input('Which grade?'))
#here the user inputs XX
match=re.search(grade,source)
match=re.search('\G\D+',source)
#Trying to use the \G operator to get the location of last match.Doesn't work.
match=re.search('\G\d+',source)
#Trying to get the next number after XX.
print(match.group())
Answer: # Description
This regex will match the string value `XX` which can be replaced with the
user input. The regex will also require that the `XX` string be surrounded by
white space or at the beginning of your sample text which prevents the
accidental edge case where `XX` is found inside a word like `EXXON`.
`(?<=\s|^)\b(xx)\b\s.*?\s\b(\d+)\b(?=\s|$)`

# Code Example:
I don't know python well enough to offer a proper python example, so I'm
including a PHP example to simply show how the regex would work and the
captured groups
<?php
$sourcestring="EXXON abcd XX blah blah 123 more blah blah";
preg_match('/(?<=\s|^)\b(xx)\b\s.*?\s\b(\d+)\b(?=\s|$)/im',$sourcestring,$matches);
echo "<pre>".print_r($matches,true);
?>
$matches Array:
(
[0] => XX blah blah 123
[1] => XX
[2] => 123
)
If you need the actual string position, then in PHP that would look like
$position = strpos($sourcestring, $matches[0])
|
Why don't my unit tests run in Python?
Question: I have
myapp/
__init__.py
lib.py
tests/
lib_test.py
In lib_test.py I have:
import lib
When running from myapp:
python tests/lib_test.py
I get an error
ImportError: No module named lib
It's some sort of beginner error no doubt. However I can't figure out what is
going wrong.
Answer: When you try to do `import lib` like you have above, Python tries to find the
import, starting with the directory you are in (so, for example, if you were
right in the `myapp` directory, it would find `lib.py` and be able to `import
lib`). However, when importing within a package (basically, anything with
`__init__.py`) you should go towards using explicit package imports (like
`from myapp import lib`) so that the python interpreter will know where to
look. This also has the advantage of avoiding namespace collisions with `lib`
(i.e., if you were in a different folder that had `lib.py` in it).
Bottom line: replace `import lib` with `from myapp import lib` and you'll be
good.
|
What's the difference between module, package and library in Haskell?
Question: What's the difference between module, package and library in Haskell?
From <http://www.haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html>
Prelude: a standard **module** imported by default into all Haskell modules.
From <http://www.haskell.org/haskellwiki/Base_package>
Base package: The base **package** contains the Prelude and its support
libraries, and a large collection of useful **libraries** ranging from data
structures to parsing combinators and debugging utilities.
Thanks.
See also: [What's the difference between a Python module and a Python
package?](http://stackoverflow.com/questions/7948494/whats-the-difference-
between-a-python-module-and-a-python-package)
Answer: A **module** is a set of functions, types, classes, ... put together in a
common namespace.
A **library** is a set of modules which makes sense to be together and that
can be used in a program or another library.
A **package** is a unit of distribution that can contain a library or an
executable or both. It's a way to share your code with the community.
Note that a library doesn't have to be in isolation in a package. That is,
it's perfectly acceptable to have a library in your project that is used
inside this project. The code is therefore seperated from the rest for clarity
and maintainability. This is also a good way to isolate some general-purpose
from your business logic code and this lib could eventually be extracted and
shared between projects or with the community if needed.
|
Parse date/time from a string
Question: I'm using Python 3.3. I'm getting an email from an IMAP server, then
converting it to an instance of an email from the [standard email
library](http://docs.python.org/2/library/email.message.html).
I do this:
message.get("date")
Which gives me this for example:
Wed, 23 Jan 2011 12:03:11 -0700
I want to convert this to something I can put into `time.strftime()` so I can
format it nicely. I want the result in local time, not UTC.
There are so many functions, deprecated approaches and side cases, not sure
what is the modern route to take?
Answer: Something like this?
>>> import time
>>> s = "Wed, 23 Jan 2011 12:03:11 -0700"
>>> newtime = time.strptime(s, '%a, %d %b %Y %H:%M:%S -0700')
>>> print(time.strftime('Two years ago was %Y', newtime))
Two years ago was 2011 # Or whatever output you wish to receive.
|
Python: Find monotonic sequences in a list
Question: I'm new in Python but basically I want to create sub-groups of element from
the list with a double loop, therefore I gonna compare the first element with
the next to figure out if I can create these sublist, otherwise I will break
the loop inside and i want continue with the last element but in the main
loop:
Example: `5,7,8,4,11`
Compare 5 with 7, is minor? yes so include in the newlist and with the inside
for continue with the next 8, is minor than 5? yes, so include in newlist, but
when compare with 4, I break the loop so I want continue in m with these 4 to
start with the next, in this case with 11...
for m in xrange(len(path)):
for i in xrange(m+1,len(path)):
if (path[i] > path[m]):
newlist.append(path[i])
else:
break
m=m+i
Thanks for suggestions or other ideas to achieve it!
PD. Some input will be: input:[45,78,120,47,58,50,32,34] output:
[45,78,120],[47,58],50,[32,34]
the idea why i want make a double loops due to to compare sub groups of the
full list,in other way is while 45 is minor than the next one just add in the
new list, if not take the next to compare in this case will be 47 and start to
compare with 58
Answer: No loop! Well at least, no _explicit_ looping...
import itertools
def process(lst):
# Guard clause against empty lists
if len(lst) < 1:
return lst
# use a dictionary here to work around closure limitations
state = { 'prev': lst[0], 'n': 0 }
def grouper(x):
if x < state['prev']:
state['n'] += 1
state['prev'] = x
return state['n']
return [ list(g) for k, g in itertools.groupby(lst, grouper) ]
Usage (work both with Python 2 & Python 3):
>>> data = [45,78,120,47,58,50,32,34]
>>> print (list(process(data)))
[[45, 78, 120], [47, 58], [50], [32, 34]]
Joke apart, if you need to _group_ items in a list
[`itertools.groupby`](http://docs.python.org/2/library/itertools.html#itertools.groupby)
deserves a little bit of attention. Not always the easiest/best answer -- but
worth to make a try...
* * *
**EDIT:** If you don't like _closures_ \-- and prefer using an _object_ to
hold the state, here is an alternative:
class process:
def __call__(self, lst):
if len(lst) < 1:
return lst
self.prev = lst[0]
self.n = 0
return [ list(g) for k, g in itertools.groupby(lst, self._grouper) ]
def _grouper(self, x):
if x < self.prev:
self.n += 1
self.prev = x
return self.n
data = [45,78,120,47,58,50,32,34]
print (list(process()(data)))
* * *
**EDIT2:** Since I prefer closures ... but @torek don't like the _dictionary_
syntax, here a third variation around the same solution:
import itertools
def process(lst):
# Guard clause against empty lists
if len(lst) < 1:
return lst
# use an object here to work around closure limitations
state = type('State', (object,), dict(prev=lst[0], n=0))
def grouper(x):
if x < state.prev:
state.n += 1
state.prev = x
return state.n
return [ list(g) for k, g in itertools.groupby(lst, grouper) ]
data = [45,78,120,47,58,50,32,34]
print (list(process(data)))
|
How to run unittest discover from "python setup.py test"?
Question: I'm trying to figure out how to get `python setup.py test` to run the
equivalent of `python -m unittest discover`. I don't want to use a
run_tests.py script and I don't want to use any external test tools (like
`nose` or `py.test`). It's OK if the solution only works on python 2.7.
In `setup.py`, I think I need to add something to the `test_suite` and/or
`test_loader` fields in config, but I can't seem to find a combination that
works correctly:
config = {
'name': name,
'version': version,
'url': url,
'test_suite': '???',
'test_loader': '???',
}
**Is this possible using only`unittest` built into python 2.7?**
FYI, my project structure looks like this:
project/
package/
__init__.py
module.py
tests/
__init__.py
test_module.py
run_tests.py <- I want to delete this
setup.py
**Update** : This is possible with `unittest2` but I want find something
equivalent using only `unittest`
From <https://pypi.python.org/pypi/unittest2>
> unittest2 includes a very basic setuptools compatible test collector.
> Specify test_suite = 'unittest2.collector' in your setup.py. This starts
> test discovery with the default parameters from the directory containing
> setup.py, so it is perhaps most useful as an example (see
> unittest2/collector.py).
For now, I'm just using a script called `run_tests.py`, but I'm hoping I can
get rid of this by moving to a solution that only uses `python setup.py test`.
Here's the `run_tests.py` I'm hoping to remove:
import unittest
if __name__ == '__main__':
# use the default shared TestLoader instance
test_loader = unittest.defaultTestLoader
# use the basic test runner that outputs to sys.stderr
test_runner = unittest.TextTestRunner()
# automatically discover all tests in the current dir of the form test*.py
# NOTE: only works for python 2.7 and later
test_suite = test_loader.discover('.')
# run the test suite
test_runner.run(test_suite)
Answer: If you use py27+ or py32+, the solution is pretty simple:
test_suite="tests",
|
How to handle urls in python urllib2 appengine with plus signs?
Question: Here's my problem. I'm trying to request a url from the rotten tomatoes API.
Now the thing is that they require you to have your movie titles contain +
signs where ever there should be spaces. However I'm not sure how to implement
this on the app engine side, because whenever I try doing the same thing on
app engine, I get the same error:
Traceback (most recent call last):
File "/programming/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1535, in __call__
rv = self.handle_exception(request, response, e)
File "/programming/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1529, in __call__
rv = self.router.dispatch(request, response)
File "/programming/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1278, in default_dispatcher
return route.handler_adapter(request, response)
File "/programming/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1102, in __call__
return handler.dispatch()
File "/programming/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 572, in dispatch
return self.handle_exception(e, self.app.debug)
File "/programming/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 570, in dispatch
return method(*args, **kwargs)
File "/Users/student/Desktop/Movie Rater/MovieRaterBackend/higgsmovies.py", line 12, in get
page = urllib2.urlopen(site)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 400, in open
response = meth(req, response)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 513, in http_response
'http', request, response, code, msg, hdrs)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 438, in error
return self._call_chain(*args)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 372, in _call_chain
result = func(*args)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 521, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 400: Bad Request
Here's my code:
title = self.request.get("title")
site = "http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=" + constants.ROTTEN_TOMATOES_KEY + "&q=" + title + "&page_limit=1"
page = urllib2.urlopen(site)
soup = BeautifulSoup(page)
self.response.out.write(soup)
constants is just a python file containing all of my passwords and stuff, and
I'm using beautiful soup to clean things up, but I'm sure that's not the
problem. This code is just accessed by going to the url
myapplication.com/about?title=your+title+goes+here, where myapplication will
be the url of the website, probably some appspot.com url.
This works for URLs that don't contain + signs.
Any help would be greatly appreciated!
Answer: This does not directly answer your question, but have you tried using the [url
fetch service](https://developers.google.com/appengine/docs/python/urlfetch/),
directly:
eg:
from google.appengine.api import urlfetch
title = self.request.get("title")
site = "http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=" + constants.ROTTEN_TOMATOES_KEY + "&q=" + title + "&page_limit=1"
result = urlfetch.fetch(site)
|
dock widget loaded from separate ui file to main window
Question: I'm building an application using PySide and would like the ability to load
widgets from separate .ui files. below is some code I've tried out but it wont
let me dock the dock widget loaded separately from the main window to the main
window. The main window ui file contains a simple main window and a few items
already docked into it, the dock_widget ui contains a dock widget and a few
buttons inside. When I double click the dock widget's bar once its loaded it
seems to 'dock' to nothing and when i drag it over the main window it wont
dock. The main window definitely accepts dock widgets as there are some
defined inside it that behave normally.
#!/usr/bin/python
# Import PySide classes
import sys
from PySide.QtGui import *
from PySide.QtCore import *
from PySide.QtUiTools import QUiLoader
def load_ui(ui_file, parent=None):
loader = QUiLoader()
file = QFile(ui_file)
file.open(QFile.ReadOnly)
myWidget = loader.load(file, None)
myWidget.show()
file.close()
myWidget.show()
return myWidget
# Create a Qt application
app = QApplication(sys.argv)
# Create a Label and show it
main_window = load_ui("ui/main_window.ui")
dock_widget = load_ui("ui/console.ui", main_window)
# Enter Qt application main loop
app.exec_()
sys.exit()
console.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>DockWidget</class>
<widget class="QDockWidget" name="DockWidget">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>542</width>
<height>261</height>
</rect>
</property>
<property name="contextMenuPolicy">
<enum>Qt::DefaultContextMenu</enum>
</property>
<property name="windowTitle">
<string>DockWidget</string>
</property>
<widget class="QWidget" name="dockWidgetContents">
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QTextEdit" name="textEdit_2"/>
</item>
<item>
<widget class="QTextEdit" name="textEdit"/>
</item>
</layout>
</widget>
</widget>
<resources/>
<connections/>
</ui>
Any thoughts on what I should do differently
Answer: You should not call `QDockWidget::show`. This forces it to act like an usual
QWidget. Use `QMainWindow::addDockWidget` instead.
def load_ui(ui_file, parent=None):
loader = QUiLoader()
file = QFile(ui_file)
file.open(QFile.ReadOnly)
myWidget = loader.load(file, None)
file.close()
return myWidget
main_window = load_ui("ui/main_window.ui")
dock_widget = load_ui("ui/console.ui", main_window)
main_window.show()
main_window.addDockWidget(Qt.LeftDockWidgetArea, dock_widget)
|
Python plot log scale set xticks?
Question: I am trying to plot between in Log scale but there are problems ;
from pylab import *
import matplotlib.pyplot as pyplot
Ds = pow(10,5)
D = np.linspace(0, pow(10,6), 6)
alpha=1.44
beta=0.44
A=alpha*pow((D/Ds), beta)
L=1.65
a=exp(-(A*L/4.343))
fig = pyplot.figure()
ax = fig.add_subplot(1,1,1)
ax.set_xscale('log')
xlim(0.001,1)
ylim(0.1,1)
ax.grid()
line, = ax.plot(D/(Ds),a, color='blue', lw=2, marker='o')
show()
but I can not set the value labels of x axis and ticks for it.I want y axis to
show between 0 to 1 with 0.1 increments ; x axis to show between 0 to 10 in
logscale like 0.001 0.002 0.003 0.004 0.005....0.01 0.02 0.03 ... and so on
but I can not do it ?
set_xscale automates the ticks and value labels.Any idea ?
Answer: Yes, you can do it like:
import numpy as np
xticks = [0.001, 0.002, 0.003, 0.004, 0.005, 0.01, 0.02, 0.03, 0.04, 0.05,
0.1, 0.2, 0.3, 0.4, 0.5, 1., 2., 3., 4., 5., 10.]
yticks = np.arange(0,1,0.1)
ax.xaxis.set_ticks( xticks )
ax.yaxis.set_ticks( yticks )
To force labels in all given positions you can you the `set_ticklabels()`
method, where you can also control the string format:
ax.xaxis.set_ticklabels( ['%1.e' % i for i in xticks] )
ax.yaxis.set_ticklabels( ['%1.1f' % i for i in yticks] )
|
How to change the word order of phrasal verbs in a POS-tagged corpus file
Question: I have a POS-tagged parallel corpus text file in which I would like to do word
reordering, so that the "separable phrasal verb particle" will appear next to
the "verb" of the phrasal verb ('make up a plan' instead of 'make a plan up')
. This used for preprocessing in a statistical machine translation system.
Here are some example lines from the POS-tagged text file:
1. you_PRP mean_VBP we_PRP should_MD kick_VB them_PRP out_RP ._.
2. don_VB 't_NNP take_VB it_PRP off_RP until_IN I_PRP say_VBP so_RB ._.
3. please_VB help_VB the_DT man_NN out_RP ._.
4. shut_VBZ it_PRP down_RP !_.
I would like to move all the particles (in the examples: out_RP, off_RP,
out_RP, down_RP) right next to the closest preceding verb (i.e. the verb that
in combination with the particle makes up the phrasal verb). Here's what the
lines should looks like after having changed the word order:
1. you_PRP mean_VBP we_PRP should_MD kick_VB out_RP them_PRP ._.
2. don_VB 't_NNP take_VB off_RP it_PRP until_IN I_PRP say_VBP so_RB ._.
3. please_VB help_VB out_RP the_DT man_NN ._.
4. shut_VBZ down_RP it_PRP !_.
So far I've tried using python and regular expressions to sort the problem by
using re.findall:
import re
file=open('first100k.txt').read()
matchline3='\w*_VB.?\s\w*_DT\s\w*_NN\s\w*_RP'
wordorder1=re.findall(matchline3,file)
print wordorder1
This will find all the phrasal verbs in word order 1(see below), but that's as
far as I've got since I can't figure out how to move the particle next to the
verb. Any ideas how to solve this problem properly (not necessarily by using
python and regex)? I would like to be able to search for all phrasal verbs and
move the particles in the following word orders:
(The used tags are taken from the Penn Treebank tagset
(<http://www.ling.upenn.edu/courses/Fall_2003/ling001/penn_treebank_pos.html>
)(the x denotes an optional character in order to include all verb forms, and
* denotes a wildcard word))
1. *_VBx+*_DT+*_NN+*_RP
2. *_VBx+*_DT+*_NNS+*_RP
3. *__VBx+*_ _DT+*_.JJ+*_NN+*_RP
4. *__VBx+*_ _DT+*_.JJ+*_NNS+*_RP
5. *_VBx+*_PRP$+*_NN+*_RP
6. *_VBx+*_PRP$+*_NNS+*_RP
7. *__VBx+*_ _PRP$+*_.JJ+*_NN+*_RP
8. *__VBx+*_ _PRP$+*_.JJ+*_NNS+*_RP
9. *_VBx+*_NNP+*_RP
10. *_VBx+*_JJ+*_NNP+*_RP
11. *_VBx+*_NNPS+*_RP
12. *_VBx+*_PRP+*_RP
In advance, thanks for your help!
Answer: I wouldn't recommend using regular expressions here. It's definitely not as
intuitive as just iterating over each line after being split on whitespace,
possibly rearranging the list, and finally joining. You can try something like
this,
reordered_corpus = open('reordered_corpus.txt', 'w')
with open('corpus.txt', 'r') as corpus:
for phrase in corpus:
phrase = phrase.split() # split on whitespace
vb_index = rp_index = -1 # variables for the indices
for i, word_pos in enumerate(phrase):
pos = word_pos.split('_')[1] # POS at index 1 splitting on _
if pos == 'VB' or pos == 'VBZ': # can add more verb POS tags
vb_index = i
elif vb_index >= 0 and pos == 'RP': # or more particle POS tags
rp_index = i
break # found both so can stop
if vb_index >= 0 and rp_index >= 0: # do any rearranging
phrase = phrase[:vb_index+1] + [phrase[rp_index]] + \
phrase[vb_index+1:rp_index] + phrase[rp_index+1:]
reordered_corpus.write(' '.join(word_pos for word_pos in phrase)+'\n')
reordered_corpus.close()
Using this code, if `corpus.txt` reads,
you_PRP mean_VBP we_PRP should_MD kick_VB them_PRP out_RP ._.
don_VB 't_NNP take_VB it_PRP off_RP until_IN I_PRP say_VBP so_RB ._.
please_VB help_VB the_DT man_NN out_RP ._.
shut_VBZ it_PRP down_RP !_.
after running, `reordered_corpus.txt` will be,
you_PRP mean_VBP we_PRP should_MD kick_VB out_RP them_PRP ._.
don_VB 't_NNP take_VB off_RP it_PRP until_IN I_PRP say_VBP so_RB ._.
please_VB help_VB out_RP the_DT man_NN ._.
shut_VBZ down_RP it_PRP !_.
|
Python - How to print Sqlite table
Question: Here I have some simple python code to query a sqlite3 database.
import sqlite3 as lite
conn = lite.connect('db/posts.db')
cur = conn.cursor()
def get_posts():
cur.execute("SELECT * FROM Posts")
print(cur.fetchall())
get_posts()
I have already created the table `Posts`. When I run this I get no errors, and
it just prints out `[]`. I know that the table Posts isn't empty, I created it
in a REPL. Why is this not working?
Any help is appreciated!
Answer: Turns out I just forgot to use `conn.commit()`. Hope this helps someone.
|
IO Error [Errno 2]
Question: So I'm a beginning programmer, and python is my first language. I'm trying to
write a script that will open a random PDF from a directory and select a
random page from that PDF to read. When I run my script I get the error code
IO ERROR: [Errno 2] and then displays the title of the selected PDF. How can I
fix this? I am using the pyPdf module. Are there any other problems in the
code you can see?
import os, random, pyPdf
from pyPdf import PdfFileReader
b = random.choice(os.listdir("/home/illtic/PDF"))
pdf_toread = pyPdf.PdfFileReader(open(b, 'r'))
last_page = pdf_toread.getNumPages() - 1
page_one = pdf_toread.getPage(random.randint(0, last_page))
print " %d " % page_one
Answer: what value does `b` have? I am pretty sure that it is just the filename
without the path. Try adding the path in front of the filename and it should
be ok.
pdf_toread = pyPdf.PdfFileReader(open('/home/illtic/PDF/' + b, 'r'))
|
Portable programming - Linking fails fails with Win32 but links with linux
Question: I am working on a portable application which is running under Linux and
Windows. I am cross compiling on a linux system using cmake, gcc 4.4.4 and
mingw-gcc 4.4.4.
I can compile and link the Linux version of my application without problems.
However if I try to cross-compile for Windows, the application compiles fine,
but the linker ends with an 'undefined reference' error.
Here is the excerpt from the source code:
Header File (fileactions.hpp):
class FileActions {
bool CopyFile(const std::string &source, const std::string &destination);
bool CopyFile(const boost::filesystem::path& source, const boost::filesystem::path& destination);
};
Source file (fileactions.cpp):
bool FileActions::CopyFile(const boost::filesystem::path& source, const boost::filesystem::path& destination)
{
return this->CopyFile(source.string(), destination.string());
}
bool FileActions::CopyFile(const std::string &source, const std::string &destination)
{
/* ... do something */
}
Excerpt from code which causes the link-error:
bool TmmProject::PostImportOldVersion(int old_version) {
namespace fs = boost::filesystem;
FileActions dd;
fs::path backup;
/* fs::path _location; // This is actually defined in the class declaration */
/* do something more */
if( !dd.CopyFile(_location, backup ) ) { <-- I get the linker error at this line
log << "<span style=\"color:red\">Failed to create backup file. Stopping import </span><br>";
log << "The error message is: " << dd.GetError() << "<br>";
_last_error = log.str();
return false;
}
/* do something more */
}
As said, above code links fine if I compile for linux system, but fails if I
use mingw to compile for Win32. The exact linker error is:
CMakeFiles/tmm.dir/tmmproject.cpp.obj:/.../tmm/tmmproject.cpp:408: undefined reference
to 'tmm::fileActions::CopyFileA(
boost::filesystem::basic_path<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, boost::filesystem::path_traits> const &,
boost::filesystem::basic_path<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, boost::filesystem::path_traits> const &
)'
The file fileactions.cpp is linked into a static libray libtmm. The TmmProject
class, which causes the error, is part of the the same library.
The CMakeLists.txt which is used to link the library looks like this
(shortened):
include_directories( ... )
link_directories ( ${Boost_LIBRARY_DIRS} )
file(GLOB TMM_HEADERS *.h)
file(GLOB TMM_SOURCES *.cpp)
set ( TMM_LIBS
${Boost_LIBRARIES}
${PYTHON_LIBRARIES}
m
)
IF( WIN32 )
ADD_LIBRARY( tmm STATIC ${TMM_SOURCES} )
target_link_libraries( tmm ${TMM_LIBS} )
# I found the following option from a similar quesiton in this froum, but
# actually it does not seem to make any difference
SET_TARGET_PROPERTIES( tmm PROPERTIES LINK_FLAGS -Wl,--export-all-symbols )
ELSE( WIN32 )
ADD_LIBRARY( tmm SHARED ${TMM_SOURCES} )
target_link_libraries( tmm ${TMM_LIBS} )
INSTALL(TARGETS tmm DESTINATION lib)
ENDIF( WIN32 )
Has anyone an Idea what could be the reason for the failure?
Answer: Microsoft is using a lot of defines in their header for unicode support. In
your case the name `OpenFile` seems also to be defined to be eiter `OpenFileA`
or if you switch to unicode it would be `OpenFileW`.
To get rid of this problem add this after including the headers from
microsoft.
#undef CopyFile
You can of course pack it into a `#ifdef` to limit it to the microsoft
platform.
|
Getting brackets while executing query into mysql database using python
Question: I need help!! I have written a python code which queries the database and
prints the result in the Linux shell prompt here is the code :
#!/usr/bin/python
import MySQLdb
import sys
import config
import csv
db = MySQLdb.connect(config.host,config.user,config.password,config.dbname)
cursor=db.cursor()
print "Connected to the Mysql database"
cursor.execute("use " + config.dbname)
cursor.execute('SELECT DISTINCT LEARNER FROM EMS_data LIMIT 5')
result= cursor.fetchall()
print result
db.commit()
cursor.close()
This is what i get :
(("'Fang ",), ("'Nikhil '",), ("'Gavin '",), ("'Vamsi'",), ("'Shah'",))
How to remove these braces..?
Answer: The result returned by cursor.fetchall() is a tuple of tuples containing the
fetched data. Each tuple represents a fetched row.
Because you are printing a tuple of tuples, you are seeing the braces. In
order to display the data in a prefered format you'll have to iterate over the
result and print each row accordingly.
The example below would print each row on a new line, and will separate the
columns with a vertical bar:
for row in result:
print " | ".join(row)
|
What are other options for faster io in Python 2.7
Question: I have been struggling with [this](http://www.codechef.com/problems/INTEST)
practice problem on codechef.com for some time. I was finally able to make a
working solution.
import sys
def p():
numbers, div = map(int,sys.stdin.readline().split())
ans = 0
for i in xrange(numbers):
if int(sys.stdin.readline()) % div == 0:
ans += 1
i += 1
print ans
p()
But this executed in 43.60 as is shown
[here](http://www.codechef.com/status/INTEST,anshbansal). It is much worse
than the best given solutions. They are all using psyco module which is not
working for Python 2.7.
Is there some faster method of IO in Python 2.7 which can improve the time-
efficiency of this practice problem and in general programming problems
requiring huge inputs? Please also consider the cases when memory use may be
increased for getting desired time-efficiency.
EDIT:
Faster IO for floating point numbers is not required for this problem but it
may be required for some other problem so suggest something for them also.
EDIT2:
nums = int(sys.stdin.readline())
float_nums = map(float,next(sys.stdin).split())
for p in islice(sys.stdin, float_nums, None):
I was using something like the above for use with @Martijn Pieters answer for
floating point numbers. I am not using `xrange()`
Answer: Use the file as an iterator (different, potentially more optimal buffer
strategy), and take advantage of generator expressions:
import sys
from itertools import islice
def p():
numbers, div = map(int, next(sys.stdin).split())
print sum(int(l) % div == 0 for l in islice(sys.stdin, numbers))
p()
This treats booleans as integers (they are a subclass; `True` is 1 in an
integer context, `False` is 0).
Or try:
import sys
from itertools import islice
def p():
numbers, div = map(int, next(sys.stdin).split())
print sum(1 for l in islice(sys.stdin, numbers) if int(l) % div == 0)
p()
These do different amounts of work, and depending on the amount of divisible
numbers present, one could be faster than the other (`if` tests versus summing
0s and 1s).
|
why can't this wxPython frame (and a panel inside) keep its size?
Question: _**The background colour of panel is applied to the whole frame! why'd that be
happening, I wonder. Here, frame is (300,400) whereas the panel is supposed to
be (300,180). I might be doing something wrong._**
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import wx
class Panel(wx.Panel):
def __init__(self, parent, id, pos, size):
wx.Panel.__init__(self, parent, id, pos, size)
class Frame(wx.Frame):
def __init__(self, parent, id, title, pos, size, style):
wx.Frame.__init__(self, parent, id, title, pos, size, style)
self.userpanel = Panel(self, -1, (0,0), (300,180))
self.userpanel.SetBackgroundColour('Gold')
class Application(wx.App):
def __init__(self):
wx.App.__init__(self)
frame = Frame(None, -1, "Internet Login Tool", (-1,-1), (300,400),\
wx.DEFAULT_FRAME_STYLE ^ (wx.RESIZE_BORDER | wx.MAXIMIZE_BOX))
frame.Show()
self.SetTopWindow(frame)
if __name__ == '__main__':
app = Application()
app.MainLoop()
Answer: When you add a panel to a frame it takes up the whole area of the frame, add a
panel to the frame and then add your panel to the frames panel as shown in
your modified code below
import wx
class Panel(wx.Panel):
def __init__(self, parent, id, pos, size):
wx.Panel.__init__(self, parent, id, pos, size)
class Frame(wx.Frame):
def __init__(self, parent, id, title, pos, size, style):
wx.Frame.__init__(self, parent, id, title, pos, size, style)
framePanel = wx.Panel(self)
self.userpanel = Panel(framePanel, -1, (0,0), (300,180))
self.userpanel.SetBackgroundColour('Gold')
class Application(wx.App):
def __init__(self):
wx.App.__init__(self)
frame = Frame(None, -1, "Internet Login Tool", (-1,-1), (300,400),\
wx.DEFAULT_FRAME_STYLE ^ (wx.RESIZE_BORDER | wx.MAXIMIZE_BOX))
frame.Show()
self.SetTopWindow(frame)
if __name__ == '__main__':
app = Application()
app.MainLoop()
|
Find the type of boost python object
Question: I have been embedding python into c++ and I would like to know if there is a
way to find the type of the boost::python::object which is a result after
executing a function of a python module. I have my code like this:
boost::python::object module_ = boost::python::import("..libName");
boost::python::object result_ = module_.attr("..functionName")(arg1, arg2,...);
//suppose if the result is int,
int a_ = boost::python::extract<int>(result_);
From the above code snippet, what i would like to know is if there is way to
find the type of the result before extracting it. In the above code, the
result_ might be any type like list, tuple...
Answer: You can try this
std::vector<std::string> list_to_vector(boost::python::list& l)
{
for (int i = 0; i < len(n); ++i)
{
boost::python::extract<boost::python::object> objectExtractor(l[i]);
boost::python::object o=objectExtractor();
std::string object_classname = boost::python::extract<std::string>(o.attr("__class__").attr("__name__"));
std::cout<<"this is an Object: "<<object_classname<<std::endl;
}
...................................................
...................................................
}
It works for me.
|
How to skip the extra newline while printing lines read from a file?
Question: I am reading input for my python program from stdin (I have assigned a file
object to stdin). The number of lines of input is not known beforehand.
Sometimes the program might get 1 line, 100 lines or even no lines at all.
import sys
sys.stdin = open ("Input.txt")
sys.stdout = open ("Output.txt", "w")
def main():
for line in sys.stdin:
print line
main()
This is the closest to my requirement. But this has a problem. If the input is
3
7 4
2 4 6
8 5 9 3
it prints
3
7 4
2 4 6
8 5 9 3
It prints an extra newline after every line. How do I fix this program or
whats the best way to solve this problem?
**EDIT:** Here is the sample run <http://ideone.com/8GD0W7>
* * *
**EDIT2:** Thanks for the Answer. I got to know the mistake.
import sys
sys.stdin = open ("Input.txt")
sys.stdout = open ("Output.txt", "w")
def main():
for line in sys.stdin:
for data in line.split():
print data,
print ""
main()
Changed the program like this and it works as expected. :)
Answer: the python `print` statement adds a newline, but the original line already had
a newline on it. You can suppress it by adding a comma at the end:
print line , #<--- trailing comma
For python3, (where `print` becomes a function), this looks like:
print(line,end='') #rather than the default `print(line,end='\n')`.
* * *
Alternatively, you can strip the newline off the end of the line before you
print it:
print line.rstrip('\n') # There are other options, e.g. line[:-1], ...
but I don't think that's nearly as pretty.
|
Python - How to make REST POST request
Question: I have implemented a REST service with Java:
@POST
@Path("/policyinjection")
@Produces(MediaType.APPLICATION_JSON)
public String policyInjection(String request) {
String queryresult = null;
String response = null;
if (request == null) {
logger.warning("empty request");
} else {
//call query() to query redisDB with the request
queryresult = query(request);
// call inject() to inject returned policy to floodlight
response = inject(queryresult);
}
return response;
}
But I need to use Python to implement the client to make a POST request to the
above service. I am new to python, I want to implement a method do it like
this:
def callpolicyInjection():
Answer: I'm not sure this is the answer to your _exact_ question, but you should take
a look at the [`requests`](http://docs.python-requests.org/en/latest/) module.
It allows to send http POST requests (as well as (m)any other http methods)
mostly in one line:
>>> import requests
>>> keys = {'username':'Sylvain', 'key':'6846135168464431', 'cmd':'do_something'}
>>> r = requests.post("http://httpbin.org/post",params=keys)
* * *
Now, the answer is in the `r` objects:
>>> print(r)
<Response [200]>
>>> print(r.text)
{
"origin": "70.57.167.19",
"files": {},
"form": {},
"url": "http://httpbin.org/post?cmd=do_something&key=6846135168464431&username=Sylvain",
"args": {
"username": "Sylvain",
"cmd": "do_something",
"key": "6846135168464431"
},
"headers": {
"Content-Length": "0",
"Accept-Encoding": "identity, gzip, deflate, compress",
"Connection": "close",
"Accept": "*/*",
"User-Agent": "python-requests/1.2.3 CPython/3.3.1 Linux/3.2.0-0.bpo.4-amd64",
"Host": "httpbin.org"
},
"json": null,
"data": ""
}
... those are only examples. See requests [response
content](http://www.python-requests.org/en/latest/user/quickstart/#response-
content) documentation for details.
|
Simplify Python iterations
Question: Everytime I try to solve some math problem such as finding a specific product
of certain number of factors I do this in Python
for x in xrange(1,10):
for y in xrange(1,10):
for z in xrange(1,10):
product = x * y * z
if product == 36:
print "factors : {0},{1},{2}".format(x,y,z)
It is very straightforward and gets the job done fast in this example, but I
was wondering if you guys know an easier or simpler way to write this. Any
ideas on how to do this without using that many for iterations or repeating
almost the same code over and over. These is obviously for 3 factors, but the
more factors I add the longer and more repetitive the code keeps getting. Any
ideas on how to simplify code for this simple type of problem? thanks
Answer: Itertool's [cartesian
product](http://docs.python.org/3/library/itertools.html?highlight=itertools#itertools.product)
simulates the effect of multiple nested for loops.
import itertools
for x, y, z in itertools.product(range(1,10), range(1,10), range(1,10)):
product = x * y * z
if product == 36:
print "factors : {0},{1},{2}".format(x,y,z)
Result:
factors : 1,4,9
factors : 1,6,6
factors : 1,9,4
(...etc)
If the range is always the same for each of x,y, and z, you can specify it
just once:
for x, y, z in itertools.product(range(1,10), repeat=3):
If you're sick of typing a zillion asterisks for the `product =` line, you can
use `reduce` to multiply together an arbitrary number of arguments:
for factors in itertools.product(range(1,3), repeat=10):
product = reduce(lambda x, y: x*y, factors)
Once your format string becomes unwieldy, you can depend on `join` to string
together factors:
if product == 512:
#use `map` to turn the factors into strings, first
print "factors: " + ",".join(map(str, factors))
|
ValueError: need more than 1 value to unpack, PoolManager request
Question: The following code in `utils.py`
manager = PoolManager()
data = json.dumps(dict) #takes in a python dictionary of json
manager.request("POST", "https://myurlthattakesjson", data)
Gives me `ValueError: need more than 1 value to unpack` when the server is
run. Does this most likely mean that the JSON is incorrect or something else?
Answer: Your Json data needs to be URLencoded for it to be POST (or GET) safe.
# import parser
import urllib.parse
manager = PoolManager()
# stringify your data
data = json.dumps(dict) #takes in a python dictionary of json
# base64 encode your data string
encdata = urllib.parse.urlencode(data)
manager.request("POST", "https://myurlthattakesjson", encdata)
I believe in python3 they made some changes that the data needs to be binary.
See [unable to Post data to a login form using urllib python
v3.2.1](http://stackoverflow.com/questions/7188561/unable-to-post-data-to-a-
login-form-using-urllib-python-v3-2-1)
|
How to include resource file in cx_Freeze binary
Question: I am trying to convert a python package to a linux binary (and eventually a
windows executable as well) using cx_Freeze. The package has dependency upon
multiple egg files, as i understand cx_Freeze doesn't play nice with egg
files, so i unzipped the egg files. One of the egg files has a resource string
file 'test.resource' in some package 'test.package', to include this resource
string file i used -
include_files = ['test/package/test.resource']
Now i see this file is being copied to the target directory along with the
binary but when i try to run the binary i get the error - "IOError: [Errno 2]
No such file or directory: 'test/package/test.resource'"
The code trying to read the file is doing this:
from pkg_resources import resource_string
strings = resource_string("test.package", "test.resource")
How can i add this resource file so that it's available to the generated
binary?
Answer: Since the accepted answer is light on details, I thought I'd provide a
solution that worked for me. It does not require that you unzip your egg
files, but does not preclude it either.
**The situation** : I have an application that we package with
[esky](https://pypi.python.org/pypi/esky) using the `cx_Freeze` freezer, but
this information should apply equally well to applications just using
`cx_Freeze` directly. The application makes use of the
[treq](https://github.com/twisted/treq) library which includes the following
line in `treq.__import__`:
__version__ = resource_string(__name__, "_version").strip()
I use `pkg_resources` to determine the filepath of the `_version` file and
manually add it to my `zip_includes`. We make sure it gets placed into its
expected location alongside the rest of the `treq` library files. In my
`setup.py` file I have:
setup(
name=...,
version=...,
install_requires=[
...,
treq==15.0.0,
...
],
...,
options={
...,
"bdist_esky": {
...,
"freezer_options": {
# This would be "zip_includes" in options if just using cx_Freeze without esky
"zipIncludes": [
# Manually copy the treq _version resource file into our library.zip
(pkg_resources.resource_filename('treq', '_version'), 'treq/_version')
],
"packages": [..., "treq", ...]
...,
...,
...,
...,
)
**Bonus** : While one does not have to unzip libraries in order for this to
work, it seems to be useful enough in general that you might want to always
unzip them upon installation (a la `python setup.py develop`). It's a simple
matter of adding the following lines to your application's `setup.cfg`:
[easy_install]
zip_ok = 0
Then, when you run `python setup.py develop`, your dependencies are installed
into `site-packages` in their expanded directory form.
|
Pyscripter - ImportError: DLL load failed: %1 is not a valid Win32 application
Question: I am new to Pyscripter and found it interesting but getting the below error.
lumberjack is an internal framework to work with.
>>> import lumberjack
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "C:\Perforce\svasudevan\HPro\lumberjack\__init__.py", line 1, in <module> import analysis
File "C:\Perforce\svasudevan\HPro\lumberjack\analysis.py", line 11, in <module> import scipy.signal
File "C:\Python27\lib\site-packages\scipy\signal\__init__.py", line 227, in <module> from . import sigtools
ImportError: DLL load failed: %1 is not a valid Win32 application.
I am sure that nothing wrong with the code above as I tried with Enthought
Canopy and it works fine, since Pyscripter has more options to do with, I am
using it but getting the above error.
FYI, all the modules like Numpy, Matplotlib, Scipy and Pyaudio has been
imported successfully.
Could you please let me know the pre requisites to be done to correct this
error. I think there is some problem with the env variables.
Thanks Shobith
Answer: I'm guessing that the version of Python that PyScripter is running is
different than the one you get in EPD/Canopy (Python is compiled C code, so
the version matters). [There's another question about controlling the version
of Python used with
PyScripter](http://stackoverflow.com/questions/17155392/how-to-change-the-
version-of-python-that-pyscripter-uses).
|
How can I use py2exe with arcpy?
Question: I'm trying to convert a python script to a stand-alone executable using
py2exe. The script is built mostly using arcpy, with a Tkinter GUI.
The setup.py script is as follows:
from distutils.core import setup
import py2exe
script = r"pathtoscript.py"
options = {'py2exe':{
"includes": ['arcpy', 'arcgisscripting'],
"packages": ['arcpy', 'arcgisscripting'],
"dll_excludes": ["mswsock.dll", "powrprof.dll"]
}}
setup(windows=[script], options=options)
When run, setup.py creates the .exe as expected, but when I try to run the
executable, I get the following error:
Traceback (most recent call last):
File "autolim.py", line 7, in <module>
File "arcpy\__init__.pyc", line 21, in <module>
File "arcpy\geoprocessing\__init__.pyc", line 14, in <module>
File "arcpy\geoprocessing\_base.pyc", line 14, in <module>
File "arcgisscripting.pyc", line 12, in <module>
File "arcgisscripting.pyc", line 10, in __load
ImportError: DLL load failed: The specified module could not be found.
I use python 2.7 and arcgis 10.1 - feel free to ask if I've forgotten any
useful information.
Can anyone tell me what I need to do to get the executable working properly?
Many thanks!
Answer: I had the same problem...
Since your users will have python/arcpy installed on their machines have your
arcpy scripts in a data_files directory.
setup(windows=[script], data_files=[('scripts', glob(r'/path/to/scripts/*.py')], options=options)
Then call them using
[subprocess.Popen](https://docs.python.org/2/library/subprocess.html#subprocess.Popen)
import subprocess
subprocess.Popen(r'python "%s\scripts\autolim.py"' % self.basedir)
Popen is non-blocking so it won't freeze your GUI while the arcpy script runs.
If you want to print any print statements in your arcpy script change to
p = subprocess.Popen(r'python "%s\scripts\autolim.py"' % self.basedir, stdout=subprocess.PIPE)
while True:
line = p.stdout.readline()
if not line:
break
sys.stdout.write(line)
sys.stdout.flush()
|
Import at file level inside a function? (Python 2)
Question: Is it possible to do something like this?
def loadModules():
import time
from myModule import *
def runFunction():
try:
print str(time.time())
print myFunction() # myFunction is in myModule (myModule.myFunction)
except NameError:
raise RuntimeError("Module was not initialized. Call loadModules() first.")
if (__name__ == "__main__"):
# this should fail
try:
runFunction()
except RuntimeError:
print "Exception raised as expected."
loadModules()
runFunction() # it should work now
This will not work as expected because importing the modules _inside_ the
loadModules function will not declare them at a file level.
For modules like `time` I could add a `global time` statement after the
import. However, how can I accomplish this for a situation where the items
imported are unknown, as in `from myModule import *`? I won't automatically
know the name of every function in `myModule`. And even if I did, that'd be an
ugly global statement.
Essentially, can I basically take all local variables and make them global?
EDIT: This seemed to work in test code:
def test():
import time
global time
print "Inside test function: %s" % str(time.time())
test()
print "outside function: %s" % str(time.time())
This also worked:
def test():
from time import time
global time
print "Inside test function: %s" % str(time())
test()
print "outside function: %s" % str(time())
This however did not work:
def test():
import time
print "Inside test function: %s" % str(time.time())
test()
print "outside function: %s" % str(time.time())
Answer: This is a horrible idea, even if it could ever work, which it couldn't.
Putting a `global` statement after the import will have exactly zero effect.
The only thing that does is mark that name as global _within the current
scope_. Once the function returns, the caller will still have no knowledge of
the imported names.
In any case, you shouldn't ever be using `from MyModule import *` anyway.
|
Python Bottle how to pass parameter as json
Question: I created an api for openerp using bottle
It works well while access using browser
I don't know how to pass it as json parameters
The Problem is
how can i call using api and pass json parameters like
http://localhost/api?name=admin&password=admin&submit=Submit
Here is my wsgi code app.wsgi
import json
import os
import sys
import bottle
from bottle import get, post, run,request,error,route,template,validate,debug
def login():
import xmlrpclib
username = request.forms.get('name')
pwd = request.forms.get('password')
dbname = 'more'
sock_common = xmlrpclib.ServerProxy ('http://localhost:8069/xmlrpc/common')
uid = sock_common.login(dbname, username, pwd)
if uid:
return json.dumps({'Success' : 'Login Sucessful'])
def index():
return '''
<html>
<head>
<title> Portal</title>
</head>
<body>Welcome To PORTAL
<form method="GET" action="/api/links" enctype="multipart/form-data">
Name:<input name="name" type="text"/><br>
Password:<input name="password" type="password"/><br>
<input type="submit" value="Submit" name="submit">
</form>
</body>
</html>'''
def links():
return '''
<html>
<head>
<title> Portal</title>
</head>
<body>
<a href="/api/advisor">Advisor<br>
</body>
</html>'''
application = bottle.default_app()
application.route('/', method="GET", callback=index)
application.route('/', method="POST",callback=login)
Answer: [`request.forms`](http://bottlepy.org/docs/dev/api.html#bottle.BaseRequest.forms)
is used for POST or PUT requests. The form in your code uses GET, not POST, so
you should use
[`request.query.getall`](http://bottlepy.org/docs/dev/api.html#bottle.BaseRequest.query),
which gives you access to "URL arguments".
|
Python dump dict to json file
Question: I have a dict like this:
sample = {'ObjectInterpolator': 1629, 'PointInterpolator': 1675, 'RectangleInterpolator': 2042}
I can't figure out how to dump the dict to a `json` file as showed below:
{
"name": "interpolator",
"children": [
{"name": "ObjectInterpolator", "size": 1629},
{"name": "PointInterpolator", "size": 1675},
{"name": "RectangleInterpolator", "size": 2042}
]
}
Is there a pythonic way to do this?
You may guess that I want to generate a `d3` treemap.
Answer:
import json
with open('result.json', 'w') as fp:
json.dump(sample, fp)
This is an easier way to do it.
The second line of code determines the destination of your new json file. In
this case it is the file `result.json` which will be created and get filled in
the third line: Your dict `sample` gets written into the `result.json`!
|
Importing a custom module from a custom-built Python fails
Question: I've a weird problem. I'm setting up a project with an embedded Python
interpreter. I've rebuilt Python from the sources (3.3.2) and then copied the
Python libs as well as the .DLL into my application redistribution folder.
The weird stuff is that, while I'm being able to import a .py module, my
recompiled interpreter fails to import a .pyd custom-built file. The same file
imports file launching the interpreter from a Python regular distribution.
This is my code:
Py_SetPythonHome((wchar_t *)wideBasePath.c_str());
Py_InitializeEx(0);
PyRun_SimpleString("import MClientAPI");
It fails stating _unable to find MClientAPI_ , while I have a _MClientAPI.pyd
file available. I've tried to move it either under site-packages, libs or the
root folder with no difference.
Any advice?
Answer: Well I discovered that, if you want to import a pyd file and you're in debug
mode, no matter what you type, Python will always look for a _d postfixed
file, in my case MClientAPI_d.pyd
|
urllib2/requests and HTTP relative path
Question: How can I force urllib2/requests modules to use relative paths instead of
full/absolute URL??
when I send request using urllib2/requests I see in my proxy that it resolves
it to:
GET https://xxxx/path/to/something HTTP/1.1
Unfortunately, the server to which I'm sending it, cannot understand that
request and gives me weird 302. I know it's in RFC, it just doesn't work and
I'm tryign to fix it in python code. I don't have access to that server.
Relative path, works well
GET /path/to/something HTTP/1.1
Host: xxxx
So how can I force requests/urllib2 to not use absolute paths? and use simple
relative paths?
Answer: Probably the following code would do for your case:
from urlparse import urljoin
import requests
class RelativeSession(requests.Session):
def __init__(self, base_url):
super(RelativeSession, self).__init__()
self.__base_url = base_url
def request(self, method, url, **kwargs):
url = urljoin(self.__base_url, url)
return super(RelativeSession, self).request(method, url, **kwargs)
session = RelativeSession('http://server.net')
response = session.get('/rel/url')
|
Packaging python libraries with version-specific (2/3) code
Question: I have a Python library written to work under both Python 2 and Python 3, with
all the version-specific code localized in one module that exists in two
variants, one source code file for Python 2 and one for Python 3. Each file
contains code that raises a SyntaxError if imported into the wrong Python
version.
When I package my library with distutils and install it, I always get a syntax
error report for one or the other file. Is there a way to get rid of this?
Ideally, I would like to tell distutils/setuptools to ignore the file that is
not for the currently running Python version.
Answer: distutils imports all modules to byte-compile them (i.e. create the pyc and
maybe pyo files) at build time and/or install time. There is no option
currently to have a module skipped. You could write your setup script so that
a different sdist is generated for Python 2 and Python 3 (so for example
somemodule2.py would not be included in the Python 3 sdist), but not all tools
work well with different sdists, including PyPI.
At the current time, I would try to make each module not raise a SyntaxError
when imported by either Python 2 or 3. Or I would follow Martijn’s advice and
write just one module, possibly using the six modules, if the end result is
not too messy (I’ve seen really horrible 2-and-3 code so I don’t like that
solution, but a big part of the community has chosen it because it works).
|
Bad File Descriptor - Heroku Foreman
Question: I'm trying to run _hello.py_ from [this Python Heroku
tutorial](https://devcenter.heroku.com/articles/python). My problems began
after running this command: `foreman start`. I got the following error even
though I installed the [Heroku Toolbelt](https://toolbelt.heroku.com/):
> foreman is not recognized as an internal or external command, operable
> program or batch file
So I added the location of the foreman file (version 0.63.0) to my _path_ :
> C:\Program Files (x86)\Heroku\ruby-1.9.2\bin
and restarted the command prompt and reran `foreman start`. Now, I'm getting
this error:
Microsoft Windows [Version 6.2.9200]
(c) 2012 Microsoft Corporation. All rights reserved.
C:\Users\me\Desktop\Code\heroku_python_app>venv\Scripts\activate
(venv) C:\Users\me\Desktop\Code\heroku_python_app>foreman start
Bad file descriptor
C:/Program Files (x86)/Heroku/ruby-1.9.2/lib/ruby/gems/1.9.1/gems/foreman-0.63.0
/lib/foreman/engine.rb:372:in `read_nonblock'
C:/Program Files (x86)/Heroku/ruby-1.9.2/lib/ruby/gems/1.9.1/gems/foreman-0.63.0
/lib/foreman/engine.rb:372:in `block (2 levels) in watch_for_output'
C:/Program Files (x86)/Heroku/ruby-1.9.2/lib/ruby/gems/1.9.1/gems/foreman-0.63.0
/lib/foreman/engine.rb:368:in `loop'
C:/Program Files (x86)/Heroku/ruby-1.9.2/lib/ruby/gems/1.9.1/gems/foreman-0.63.0
/lib/foreman/engine.rb:368:in `block in watch_for_output'
12:57:38 web.1 | exited with code 1
12:57:38 system | sending SIGKILL to all processes
(venv) C:\Users\me\Desktop\Code\heroku_python_app>
**hello.py**
import os
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello World'
**Procfile**
web: gunicorn hello:app
**EDIT 1**
After reading [this answer](http://stackoverflow.com/questions/15399637/cant-
start-foreman-in-heroku-tutorial-using-python), I did the following:
gem uninstall foreman
gem install foreman -v 0.61.0
However, when I reran `foreman start` I'm getting this error now
(venv) C:\Users\me\Desktop\Code\heroku_python_app>foreman start
14:13:20 web.1 | started with pid 252
14:13:20 web.1 | exited with code 1
14:13:20 system | sending SIGKILL to all processes
14:13:20 | Traceback (most recent call last):
14:13:20 | File "C:\Users\me\Desktop\Code\heroku_python_app\venv\Scri
pts\gunicorn-script.py", line 9, in <module>
(venv) C:\Users\me\Desktop\Code\heroku_python_app>
Any assistance will be really appreciated. Thanks in advance.
Answer: I fixed this problem by running the following:
gem uninstall foreman
gem install foreman -v 0.61.0 [EDIT]
As mentioned [here](http://stackoverflow.com/questions/15399637/cant-start-
foreman-in-heroku-tutorial-using-python).
|
Deleting axis in matplotlib v1.2.1 does not work similar to v1.1.1
Question: I have a code that uses matplotlib (python win32 v2.7.5) to plot contour plots
with color bars that are animated or the contour gets updated. In order to
update the plot, I delete the color bar axis while keeping the original plot
axis untouched. In version 1.1.1 of matplotlib, the program was working okay,
however, when I upgraded to 1.2.1 of matplotlib I started to notice my plot is
getting squashed to the left by the color bar as seen in the attached images.
In V1.1.1, the plot looked like this after multiple iterations: 
whereas in V1.2.1 the plot looks now like this: 
As seen, the major plot is getting pushed to the left even if I am using
subplots_adjust.
The code for the above plots is as follows:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.mlab import bivariate_normal
from matplotlib.colors import LogNorm
delta = 0.5
x = np.arange(-3.0, 4.001, delta)
y = np.arange(-4.0, 3.001, delta)
X, Y = np.meshgrid(x, y)
Z = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
fig = plt.figure()
fig.subplots_adjust(left=0.1, bottom=0.1, right=0.97, top=0.92)
ax = fig.add_subplot(1,1,1)
axim = ax.imshow(Z,norm = LogNorm())
cb = fig.colorbar(axim)
#Note: These are not replicated, I put them here to show how a refresh of the
# contour plot multiple times will look like
fig.delaxes(fig.axes[1])
fig.subplots_adjust(left=0.1, bottom=0.1, right=0.97, top=0.92)
cb = fig.colorbar(axim)
fig.delaxes(fig.axes[1])
fig.subplots_adjust(left=0.1, bottom=0.1, right=0.97, top=0.92)
cb = fig.colorbar(axim)
plt.show()
If i delete ALL axis and re-create them each time, then it looks ok even in
new version, but I am thinking that this is not efficient process with
animation.
Any ideas why what changed in 1.2.1 to make such behavior? Or any other
suggestions to make it work again?
Answer: In matplotlib 1.4 [this pull
request](https://github.com/matplotlib/matplotlib/pull/3110) was merged adding
a `remove()` method to the colorbar. This method will remove the colorbar and
restore the gridspec if needed. Meaning a call to `subplots_adjust` will work
as expected.
If you are stuck with an older version of matplotlib (like I am at the
moment), have a look at the changes for colorbar.py in the pull request and
you should be able to get it to work.
|
Making Combinations (Python)
Question: In Python, is there a better way to get the set of combinations of n elements
from a k-element set than nested for loops or list comprehensions?
For example, say from the set [1,2,3,4,5,6] I want to get
[(1,2),(1,3),(1,4),(1,5),(1,6),(2,3),(2,4),(2,5),(2,6),(3,4),(3,5),(3,6),(4,5),(4,6),(5,6)].
Is there a better of of making it than
nums=[1,2,3,4,5,6]
doubles=[]
for a in nums:
for b in nums[a+1:]
doubles.append((a,b))
? It's okay if the elements of the list we end up with are sets, tuples, or
lists; I just feel there should be an easier way to do this.
Answer: The [`itertools`](http://docs.python.org/2/library/itertools.html) module has
a lot of really powerful tools that can be used in situations like this. In
this case, you want
[`itertools.combinations`](http://docs.python.org/2/library/itertools.html#itertools.combinations).
Some other ones that you might find useful are
[`itertools.combinations_with_replacement`](http://docs.python.org/2/library/itertools.html#itertools.combinations_with_replacement)
and
[`itertools.permutations`](http://docs.python.org/2/library/itertools.html#itertools.permutations).
Example:
>>> import itertools
>>> list(itertools.combinations(range(1,7),2))
[(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 3), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6), (4, 5), (4, 6), (5, 6)]
>>> list(itertools.combinations_with_replacement(range(1,7),2))
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (3, 3), (3, 4), (3, 5), (3, 6), (4, 4), (4, 5), (4, 6), (5, 5), (5, 6), (6, 6)]
>>> list(itertools.permutations(range(1,7),2))
[(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 1), (2, 3), (2, 4), (2, 5), (2, 6), (3, 1), (3, 2), (3, 4), (3, 5), (3, 6), (4, 1), (4, 2), (4, 3), (4, 5), (4, 6), (5, 1), (5, 2), (5, 3), (5, 4), (5, 6), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5)]
|
How do I assign a vector to a subset of rows of a column in a pandas DataFrame with NaNs?
Question: i'm having trouble assigning to a DataFrame column for a subset of rows, if
there are NaNs in the DataFrame. i can't tell, is this a bug or am i
misunderstanding something?
first off, if there are no NaNs, what i want appears to work :
>>> import pandas as pd
>>> d = pd.DataFrame({ 'one' : [1, 2, 3], 'two' : [1,2,3] })
>>> d
one two
0 1 1
1 2 2
2 3 3
>>> d.ix[d['one']>1, 'two'] = -d['two']
>>> d
one two
0 1 1
1 2 -2
2 3 -3
however, adding nuisance NaN rows causes non-intuitive results :
>>> nan = float('nan')
>>> d = pd.DataFrame({ 'one' : [1, 2, 3, nan, nan], 'two' : [1,2,3,4,5] })
>>> d
one two
0 1 1
1 2 2
2 3 3
3 NaN 4
4 NaN 5
>>> d.ix[d['one']>1, 'two'] = -d['two']
>>> d
one two
0 1 1
1 2 -2
2 3 -2
3 NaN 4
4 NaN 5
what is going on here? this is with Python 2.7.5 and pandas 0.11.
Answer: This is a [bug](https://github.com/pydata/pandas/issues/3668) in 0.11 and has
since been fixed in dev (so will be in 0.11.1, out soon).
_Thanks for reporting, this test case~~will be~~ [has been added to
pandas](https://github.com/pydata/pandas/pull/3858) testing suite._
|
How to convert, sort and save to CSV MS Access database .mdb file in Python
Question: I tried researching the answer but was not able to find a good solution. I
have files with strange extensions .res. I was told that they are MS Access
files. Not sure if they are the same as .mdb but I was able to open them in MS
Access. How can I open those files, extract necessary data, sort that data and
produce .csv file? I tried using this script:
<http://mazamascience.com/WorkingWithData/?p=168> and mdb tools on Linux. I
got some output with errors in terminal but all the files produced were blank.
It could be due to encoding. I am not sure. The file is in ASCII encoding I
think.
Error: Table fo_Table
Smart_Battery_Data_Table
MCell_Aci_Data_Table
Aux_Global_Data_Table
Smart_Battery_Clock_Stretch_Table
does not exist in this database.
On Windows I have no idea how to do it. My first step for now is just to dump
the necessary table from that database file into .csv. But ideally I need the
script to take the file, sort it, extract necessary data, do some calculations
(like data in one column divided by data in another column) and save all that
stuff into nice .csv. Thanks a lot. I am not an experienced programmer so
please have mercy.
Answer: Using the generic pyodbc library should do it. Looks like it has already an
embedded MS access driver. [This
question](http://stackoverflow.com/questions/1047580/ms-access-library-for-
python) can probably help you out.
I dont have any MS Access database files with me (It has been ages that I dont
have to work with them), but following [the
examples](https://code.google.com/p/pyodbc/wiki/GettingStarted) your code
should be something like this:
import pyodbc
db_file = r'''/path/to/the/file.res'''
user = 'admin'
password = 'password'
odbc_conn_str = 'DRIVER={Microsoft Access Driver (*.mdb)};DBQ=%s;UID=%s;PWD=%s' % (db_file, user, password)
conn = pyodbc.connect(odbc_conn_str)
cursor = conn.cursor()
cursor.execute("select * from table order by some_column")
for row in cursor.fetchall():
print ", ".join((row.column1, row.column2, row.columnN))
|
TypeError: 'tuple' object is not callable in python's multiprocessing
Question: I'm trying to use multiprocessing for doing some works. But, I got that error.
Why did that happen? Below is my sample code
def work(x, y):
#doing something
def work_process(x, y):
p = []
for i in x:
p.append(Process(target=work, args=(x, y)))
p[i].start()
for t in p:
t.join()
return result
Answer: I have written something helpful for debugging multiprocessing errors. It can
show you the full traceback of an exception/error in the other process.
Download [RemoteException.py](https://gist.github.com/niccokunzmann/5763860)
import RemoteException
@RemoteException.showError
def work(x, y):
#doing something
|
A good pythonic way to map bits to characters in python?
Question: `the_map = { 1:'a',0:'b'}`
Now to generate, 8 patterns of `a` and `b` , we create 8 bit patterns:
>>> range(8)
[0, 1, 2, 3, 4, 5, 6, 7]
# 001,010,011....111
How to map the bits to characters 'a' and 'b' , to receive output like :
['aaa','aab','aba'.......'bbb']
I am looking for an efficient one liner. My approaches using translate or
format seem a bit inefficient to me:
>>> import string
>>> [bin(x)[2:].zfill(3).translate(string.maketrans('01','ab')) for x in xrange(8)]
['aaa', 'aab', 'aba', 'abb', 'baa', 'bab', 'bba', 'bbb']
Answer: I think you are looking for
[`product`](http://docs.python.org/2/library/itertools.html#itertools.product):
>>> from itertools import product
>>> [''.join(i) for i in product('ABC',repeat=3)]
['AAA', 'AAB', 'AAC', 'ABA', 'ABB', 'ABC', 'ACA', 'ACB', 'ACC', 'BAA', 'BAB', 'B
AC', 'BBA', 'BBB', 'BBC', 'BCA', 'BCB', 'BCC', 'CAA', 'CAB', 'CAC', 'CBA', 'CBB'
, 'CBC', 'CCA', 'CCB', 'CCC']
|
Python 2.7 reading and writing "éèàçê" from utf-8 file
Question: I made this script which removes every trailing whitespace characters and
replace all bad french characters by the right ones.
Removing the trailing whitespace characters works but not the part about
replacing the french characters.
The file to read/write are encoded in UTF-8 so I added the utf-8 declaration
above my script but in the end every bad characters (like \u00e9) are being
replaced by litte square.
Any idea why?
script :
# --*-- encoding: utf-8 --*--
import fileinput
import sys
CRLF = "\r\n"
ACCENT_AIGU = "\\u00e9"
ACCENT_GRAVE = "\\u00e8"
C_CEDILLE = "\\u00e7"
A_ACCENTUE = "\\u00e0"
E_CIRCONFLEXE = "\\u00ea"
CURRENT_ENCODING = "utf-8"
#Getting filepath
print "Veuillez entrer le chemin du fichier (utiliser des \\ ou /, c'est pareil) :"
path = str(raw_input())
path.replace("\\", "/")
#removing trailing whitespace characters
for line in fileinput.FileInput(path, inplace=1):
if line != CRLF:
line = line.rstrip()
print line
print >>sys.stderr, line
else:
print CRLF
print >>sys.stderr, CRLF
fileinput.close()
#Replacing bad wharacters
for line in fileinput.FileInput(path, inplace=1):
line = line.decode(CURRENT_ENCODING)
line = line.replace(ACCENT_AIGU, "é")
line = line.replace(ACCENT_GRAVE, "è")
line = line.replace(A_ACCENTUE, "à")
line = line.replace(E_CIRCONFLEXE, "ê")
line = line.replace(C_CEDILLE, "ç")
line.encode(CURRENT_ENCODING)
sys.stdout.write(line) #avoid CRLF added by print
print >>sys.stderr, line
fileinput.close()
# EDIT
the input file contains this type of text :
* Cette m\u00e9thode permet d'appeller le service du module de tourn\u00e9e
* <code>rechercherTechnicien</code> et retourne la liste repr\u00e9sentant le num\u00e9ro
* de la tourn\u00e9e ainsi que le nom et le pr\u00e9nom du technicien et la dur\u00e9e
* th\u00e9orique por se rendre au point d'intervention.
*
# EDIT2
Final code if someone is interested, the first part replaces the badly encoded
caracters, the second part removes all right trailing whitespaces caracters.
# --*-- encoding: iso-8859-1 --*--
import fileinput
import re
CRLF = "\r\n"
print "Veuillez entrer le chemin du fichier (utiliser des \\ ou /, c'est pareil) :"
path = str(raw_input())
path = path.replace("\\", "/")
def unicodize(seg):
if re.match(r'\\u[0-9a-f]{4}', seg):
return seg.decode('unicode-escape')
return seg.decode('utf-8')
print "Replacing caracter badly encoded"
with open(path,"r") as f:
content = f.read()
replaced = (unicodize(seg) for seg in re.split(r'(\\u[0-9a-f]{4})',content))
with open(path, "w") as o:
o.write(''.join(replaced).encode("utf-8"))
print "Removing trailing whitespaces caracters"
for line in fileinput.FileInput(path, inplace=1):
if line != CRLF:
line = line.rstrip()
print line
else:
print CRLF
fileinput.close()
print "Done!"
Answer: You are looking for `s.decode('unicode_escape')`:
>>> s = r"""
... * Cette m\u00e9thode permet d'appeller le service du module de tourn\u00e9e
... * <code>rechercherTechnicien</code> et retourne la liste repr\u00e9sentant le num\u00e9ro
... * de la tourn\u00e9e ainsi que le nom et le pr\u00e9nom du technicien et la dur\u00e9e
... * th\u00e9orique por se rendre au point d'intervention.
... *
... """
>>> print(s.decode('unicode_escape'))
* Cette méthode permet d'appeller le service du module de tournée
* <code>rechercherTechnicien</code> et retourne la liste représentant le numéro
* de la tournée ainsi que le nom et le prénom du technicien et la durée
* théorique por se rendre au point d'intervention.
*
And don't forget to `encode` your string before writing it to a file (e.g. as
UTF-8):
writable_s = s.decode('unicode_escape').encode('utf-8')
|
Python Keep Named Pipe Open
Question: In bash, a named pipe can be kept open with `cat > mypipe`. How can this be
done in python? This is what I have so far:
import subprocess
import os
if not os.path.exists("/tmp/mypipe"):
os.mkfifo("/tmp/mypipe")
Answer:
import os
import subprocess
path = '/tmp/mypipe'
if not os.path.exists(path):
os.mkfifo(path)
with open(path, 'w') as f:
subprocess.call(['cat'], stdout=f)
|
Intercept python's `print` statement and display in GUI
Question: I have this somewhat complicated command line function in Python (lets call it
`myFunction()`), and I am working to integrate it in a graphical interface
(using PySide/Qt).
The GUI is used to help select inputs, and display outputs. However,
`myFunction` is designed to work as a stand-alone command line function, and
it occasionnaly prints out the progress.
My question is: how can I intercept these `print` calls and display them in
the GUI? I know it would be possible to modify `myFunction()` to send
`processEvents()` to the GUI, but I would then lose the ability to execute
`myFunction()` in a terminal.
Ideally, I would like something similar to Ubuntu's graphical software
updater, which has a small embeded terminal-looking widget displaying what
`apt-get` would display were it executed in a terminal.
Answer: you could redirect stdout and restore after. for example:
import StringIO
import sys
# somewhere to store output
out = StringIO.StringIO()
# set stdout to our StringIO instance
sys.stdout = out
# print something (nothing will print)
print 'herp derp'
# restore stdout so we can really print (__stdout__ stores the original stdout)
sys.stdout = sys.__stdout__
# print the stored value from previous print
print out.getvalue()
|
associating files to a program from python
Question: So, I have written a python app that runs on system startup on
Windows7/8/Vista/XP. The first time it is ran, I want it to associate a few
file types/extensions with a certain program which is on the system. For the
time being, I accomplish this like so:
import win32com.shell.shell as shell
def runAssoc():
shell.ShellExecuteEx(
lpVerb="runas",
lpFile='c:\\Users\\myUser\\assoc.bat')
Problem is, when ran from startup this sometimes fails to work. I've read
[here](http://stackoverflow.com/questions/130763/request-uac-elevation-from-
within-a-python-script) that `ShellExecuteEx` does not output it's errors to
the calling process, so i don't see what's going loose on that end, and also
read on the articles given
[there](http://stackoverflow.com/questions/130763/request-uac-elevation-from-
within-a-python-script) that `lpVerb="runas"` is generally considered a bad
practice.
My assoc.bat requires administrator approval as it is written the following
way:
assoc .txt=myNotepad
assoc .hello=myNotepad
ftype myNotepad="C:\Windows\system32\notepad.exe" "%%1"
(Here I'm associating Microsoft's Notepad that comes with Windows to "txt" and
"hello" extensions. That of course makes no sense but is a good example.)
I understand that Windows does not provide a command line tool that allows us
to associate file extensions to programs **for the current user only** (which
will do fine for what i'm trying to achieve).
[On this article](http://vim.wikia.com/wiki/Windows_file_associations) I read
`assoc` effects an area of the registry used by every user account in your
Windows installation, instead of `HKEY_CURRENT_USER` that could be written to
without admin permissions.
I read another answer
[here](http://stackoverflow.com/questions/130763/request-uac-elevation-from-
within-a-python-script) suggesting to check `sys.argv[-1] != "asadmin"`, but
`sys.argv` seems to be an empty array every time my app runs.
1) Can I make sure `ShellExecuteEx` runs and prompts for admin privileges when
required?
2) Maybe there's a way I can create a batch file that will associate these
extensions to the current user only? Than, I won't need to use the 'runas'
parameter which is supposedly the source of error.
A little side note: in actuallity I build this batch file 'programmatically'
on the fly, but this is not discussed here as it is not really related to the
issue.
Answer: Probably the easiest thing to do would be to make a .reg file and execute that
you can just write the registry keys you need directly in the reg file. Like
for example:
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Classes\.hello]
@="txtfile"
You can obviously make the myNotepad type too. You can assoc and then use
_regedit_ to make the reg file (select key and rmb + export) You can tell
window to install the reg silently if you use:
regedit -s your_reistration_file.reg
Now you can call the line above with the ShellExecuteEx. Please note the uer
may not have rights to edit the registry with reg files.
You can also edit registry in python directly, here is an example of above see
docs for winreg for more info:
import _winreg #just winreg in Python 3
key = _winreg.OpenKey(
_winreg.HKEY_CURRENT_USER,
r"Software\Classes"
)
hello = _winreg.CreateKeyEx(key, ".hello")
_winreg.SetValue(hello, '', _winreg.REG_SZ, 'txtfile')
|
Python thinks Euler has identity issues (cmath returning funky results)
Question: My code:
import math
import cmath
print "E^ln(-1)", cmath.exp(cmath.log(-1))
What it prints:
E^ln(-1) (-1+1.2246467991473532E-16j)
What it should print:
-1
(For Reference, [Google checking my
calculation](https://www.google.com/search?q=ln+-1&oq=ln+-1&aqs=chrome.0.57j0j62l3.1058j0&sourceid=chrome&ie=UTF-8#sclient=psy-
ab&q=e%5E%28ln+-1%29&oq=e%5E%28ln+-1%29&gs_l=serp.3...1276195.1278527.0.1278866.4.4.0.0.0.2.492.1669.2-1j0j3.4.0...0.0.0..1c.1.17.psy-
ab.Qu5LLcMf-
RM&pbx=1&bav=on.2,or.r_cp.r_qf.&bvm=bv.47810305,d.cGE&fp=9cc36caf4d2cdbc4&biw=1600&bih=813))
According to [the documentation at
python.org](http://docs.python.org/2/library/cmath.html) `cmath.exp(x)`
returns e^(x), and `cmath.log(x)` returns ln (x), so unless I'm missing a
semicolon or something , this is a pretty straightforward three line program.
When I test `cmath.log(-1)` it returns π _i_ (technically
`3.141592653589793j`). Which is right. [Euler's
identity](http://en.wikipedia.org/wiki/Euler%27s_identity) says e^(π _i_) =
-1, yet Python says when I raise e^(π _i_), I get some kind of crazy talk
(specifically `-1+1.2246467991473532E-16j`).
Why does Python hate me, and how do I appease it?
Is there a library to include to make it do math right, or a sacrifice I have
to offer to van Rossum? Is this some kind of floating point precision issue
perhaps?
The big problem I'm having is that the precision is off enough to have other
values appear closer to 0 than actual zero in the final function (not shown),
so boolean tests are worthless (i.e. `if(x==0)`) and so are local minimums,
etc...
For example, in an iteration below:
X = 2 Y= (-2-1.4708141202500006E-15j)
X = 3 Y= -2.449293598294706E-15j
X = 4 Y= -2.204364238465236E-15j
X = 5 Y= -2.204364238465236E-15j
X = 6 Y= (-2-6.123233995736765E-16j)
X = 7 Y= -2.449293598294706E-15j
3 & 7 are both actually equal to zero, yet they appear to have the largest
imaginary parts of the bunch, and 4 and 5 don't have their real parts at all.
Sorry for the tone. Very frustrated.
Answer: As you've already demonstrated, `cmath.log(-1)` doesn't return **exactly**
`i*pi`. Of course, returning `pi` exactly is impossible as `pi` is an
irrational number...
Now you raise `e` to the power of something that isn't exactly `i*pi` and you
expect to get exactly `-1`. However, if `cmath` returned that, you would be
getting an incorrect result. (After all, `exp(i*pi+epsilon)` shouldn't equal
`-1` \-- Euler doesn't make that claim!).
For what it's worth, the result is very close to what you expect -- the real
part is `-1` with an imaginary part close to floating point precision.
|
Python Threads not finishing
Question: I'm currently testing something with Threading/ workpool; I create 400 Threads
which download a total of 5000 URLS... The problem is that some of the 400
threads are "freezing", when looking into my Processes I see that +- 15
threads in every run freeze, and after a time eventually close 1 by 1.
My question is if there is a way to have some sort of 'timer' / 'counter' that
kills a thread if it isn't finished after x seconds.
# download2.py - Download many URLs using multiple threads.
import os
import urllib2
import workerpool
import datetime
from threading import Timer
class DownloadJob(workerpool.Job):
"Job for downloading a given URL."
def __init__(self, url):
self.url = url # The url we'll need to download when the job runs
def run(self):
try:
url = urllib2.urlopen(self.url).read()
except:
pass
# Initialize a pool, 400 threads in this case
pool = workerpool.WorkerPool(size=400)
# Loop over urls.txt and create a job to download the URL on each line
print datetime.datetime.now()
for url in open("urls.txt"):
job = DownloadJob(url.strip())
pool.put(job)
# Send shutdown jobs to all threads, and wait until all the jobs have been completed
pool.shutdown()
pool.wait()
print datetime.datetime.now()
Answer: > The problem is that some of the 400 threads are "freezing"...
That's most likely because of this line...
url = urllib2.urlopen(self.url).read()
By default, Python will wait forever for a remote server to respond, so if a
one of your URLs points to a server which is ignoring the
[`SYN`](http://en.wikipedia.org/wiki/Transmission_Control_Protocol#Connection_establishment)
packet, or is otherwise just _really_ slow, the thread could potentially be
blocked forever.
You can use the `timeout` parameter of
[`urlopen()`](http://docs.python.org/2/library/urllib2.html#urllib2.urlopen)
set a limit as to how long the thread will wait for the remote host to
respond...
url = urllib2.urlopen(self.url, timeout=5).read() # Time out after 5 seconds
...or you can set it globally instead with
[`socket.setdefaulttimeout()`](http://docs.python.org/2/library/socket.html#socket.setdefaulttimeout)
by putting these lines at the top of your code...
import socket
socket.setdefaulttimeout(5) # Time out after 5 seconds
|
Python : why a method from super class not seen?
Question: i am trying to implement my own version of a `DailyLogFile`
from twisted.python.logfile import DailyLogFile
class NDailyLogFile(DailyLogFile):
def __init__(self, name, directory, rotateAfterN = 1, defaultMode=None):
DailyLogFile.__init__(self, name, directory, defaultMode) # why do not use super. here? lisibility maybe?
#
self.rotateAfterN = rotateAfterN
def shouldRotate(self):
"""Rotate when N days have passed since file creation"""
delta = datetime.date(*self.toDate()) - datetime.date(*self.toDate(self.createdOn))
return delta > datetime.timedelta(self.rotateAfterN)
def __getstate__(self):
state = BaseLogFile.__getstate__(self)
del state["rotateAfterN"]
return state
threadable.synchronize(NDailyLogFile)
but it looks like i miss a fundamental of Python subclassing process...as i
get this error :
Traceback (most recent call last):
File "/home/twistedtestproxy04.py", line 88, in <module>
import ndailylogfile
File "/home/ndailylogfile.py", line 56, in <module>
threadable.synchronize(NDailyLogFile)
File "/home/lt/mpv0/lib/python2.6/site-packages/twisted/python/threadable.py", line 71, in synchronize
sync = _sync(klass, klass.__dict__[methodName])
KeyError: 'write'
so i need to explicitly add and define others methods like `Write` and
`rotate` method like this:
class NDailyLogFile(DailyLogFile):
[...]
def write(self, data): # why must i add these ?
DailyLogFile.write(self, data)
def rotate(self): # as we do nothing more than calling the method from the base class!
DailyLogFile.rotate(self)
threadable.synchronize(NDailyLogFile)
while i thought it would be correctly inherit from the base mother class.
Notice that i do nothing, only calling "super",
please can someone explain why i am wrong on my first idea that it was not
necessary to add the Write method?
is there a way to say to Python inside my NDailyLogFile that it shoud have all
the methods DailyLogFile that are not defined directly from its mother class?
So that it prevents this king of error `_sync(klass,
klass.__dict__[methodName]` and that avoid to specify excplicitly ?
( original code of DailyLogFile that inspired me it taken from the twisted
source here
<https://github.com/tzuryby/freespeech/blob/master/twisted/python/logfile.py>
)
EDIT: about using `super`, i get:
File "/home/lt/inwork/ndailylogfile.py", line 57, in write
super.write(self, data)
exceptions.AttributeError: type object 'super' has no attribute 'write'
so will not use it. My thoughs was it was right... i must have definitively
missed something
Answer: There is one workaround, just do:
NDailyLogFile.__dict__ = dict( NDailyLogFile.__dict__.items() + DailyLogFile.__dict__.items() )
threadable.synchronize(NDailyLogFile)
There is a problem here that you are using the class without having
instantiated it. This workaround works because you are forcing to change the
class attributes before the instantiation.
Another important comment ist that for a subclass of `DailyLogFile` the
command `super` would not work, since `DailyLogFile` is a so called "old style
class", or "classobj". The `super` works for the "new style" classes only.
[See this question for further information about
this](http://stackoverflow.com/q/9698614/832621).
|
Write Python classes that have different behavior for Mac and Windows
Question: I want to be able to instantiate an object whose methods will behave
differently depending on the platform.
import sys
class MyClass(object):
@property
def os_is_darwin(self):
return sys.platform == 'darwin'
def get_home_directory(self):
if self.os_is_darwin:
return '/Users/travis/'
else:
return 'C:\\Users\\travis\\'
Is there a cleaner way to do this by using an abstract base class and dividing
the Mac and Windows implementations into subclasses? The important thing is
abstracting away the platform for the caller as the above class does:
my_object = MyClass()
print my_object.get_home_directory()
Answer: Is it necessary that `MyClass` really is a class, or could it just seem like a
class in that you can call it to create an object? Let's call it `MyObject` so
it doesn't sound entirely perverse, and you end up with something like this:
def MyObject():
import sys
if sys.platform == 'darwin':
return MyDarwinObject()
else:
return MyDefaultObject()
my_object = MyObject()
print my_object.get_home_directory()
This "quacks like a duck" in the way you are most likely to use, and allows
you to keep the actual different classes entirely separate if you wish. (If
you want to share functionality you can of course use inheritance.)
Naturally the if-else chain can be replaced with a more extensible approach
such as a dictionary.
|
Python is Garbling a Salt Generated from PHP and Stored in Mysql
Question: I am exporting, by scraping it with http requests since the host won't give me
database access, a forum and importing it into a mysql database for vbulletin.
In vbulletin users have unique password salts, and it generates password
hashes using this algorithm:
$hash = md5(md5($plaintext) . $salt);
I'm using a python script to read stored data from my sqlite database of user
information to generate a new password and salt for users, then storing that
data into the mysql database so vbulletin can use it.
My problem is that python is changing the value of strings in unexpected ways.
I'm testing my script using a known password and salt to compare the hashes.
However, the salt that I'm using is this:
D(A\3*w/lo6Coo\Mc,H!0!2Z3d@O&R
When I try to store that in python, when I retrieve the string I get this:
D(A\x03*w/lo6Coo\\Mc,H!0!2Z3d@O&R
This is the python code I'm using to mimic the vbulletin hashing algorithm:
salt = 'D(A\3*w/lo6Coo\Mc,H!0!2Z3d@O&R'
password = hashlib.md5()
password.update('*snipped password*')
password = password.hexdigest()
password_hash = hashlib.md5()
password_hash.update(password + salt)
password_hash = password_hash.hexdigest()
For comparison, this PHP matches what vbulletin stores as the password hash in
the database:
$plaintext = '*snipped password*';
$salt = 'D(A\3*w/lo6Coo\Mc,H!0!2Z3d@O&R';
$hash = md5(md5($plaintext) . $salt);
$hash matches what vbulletin stores and password_hash does not. What am I
doing wrong to cause the difference?
Answer: The way you're defining `salt` is the problem. You have to either make it a
raw string:
salt = r'D(A\3*w/lo6Coo\Mc,H!0!2Z3d@O&R'
Or escape the backslashes:
salt = 'D(A\\3*w/lo6Coo\\Mc,H!0!2Z3d@O&R'
Otherwise, `\3` is interpreted as the escape sequence for the character with a
character code of `3`.
Also, for readability, you may want to make an `md5` function:
def md5(text):
return hashlib.md5(text).hexdigest()
hash = md5(md5(plaintext) + salt)
|
Reading hdf5 into c++ with memory problems
Question: I am rewriting a code I had developed in python into c++ mainly for an
improvement in speed; while also hoping to gain more experience in this
language. I also plan on using openMP to parallelize this code onto 48 cores
which share 204GB of memory.
The program I am writing is simple, I import an hdf5 file which is 3D :
A[T][X][E], where T is associated to each timestep from a simulation, X
represents where the field is measured, and E(0:2) represents the electric
field in x,y,z.
Each element in A is a double, and the bin sizes span: A[15000][80][3].
The first hiccup I have run into is inputting this 'large' h5 file into an
array and would like a professional opinion before I continue. My first
attempt:
...
#define RANK 3
#define DIM1 15001
#define DIM2 80
#define DIM3 3
using namespace std;
int main (void)
{
// Define HDF5 variables for opening file.
hid_t file1, dataset1;
double bufnew[DIM1][DIM2][DIM3];
herr_t ret;
uint i, j, k;
file1 = H5Fopen (FILE1, H5F_ACC_RDWR, H5P_DEFAULT);
dataset1 = H5Dopen (file1, "EFieldOnLine", H5P_DEFAULT);
ret = H5Dread (dataset1, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL,
H5P_DEFAULT, bufnew);
cout << "Let's try dumping 0->100 elements" << endl;
for(i=1; i < 100; i++) cout << bufnew[i][20][2] << endl;
...
which leads to a segmentation fault from array declaration. My next move was
to use either a 3D array (new), or a 3D vector. However, I have seen much
debate against these methods, and more importantly, I only need ONE component
of the E, i.e. I would like to reshape A[T][X][E] -> B[T][X] for say, the
x-component of E.
Sorry for the lengthy post, but I wanted to be as clear as possible and would
like to emphasize again that I am interested in learning how to write the
fastest, and most efficient code. I appreciate all of your suggestions, time
and wisdom.
Answer: Defining an array as a local variable means allocating it on stack. The stack
is usually limited with several megabytes, and stack overflow surely leads to
a segfault. Large data structures should be allocated at heap dynamically
(using `new` operator) or statically (when defined as global variables).
I wouldn't advise to make a vector of vectors of vectors for such dimensions.
Instead, creating a one-dimensional array to store all values
double *bufnew = new double[DIM1*DIM2*DIM3];
and accessing it with the following formula to calculate linear position of a
given 3D item
bufnew[(T*DIM2+X)*DIM3+E] = ... ; // bufnew[T][X][E]
should work ok.
|
PyOpenGL - A tutorial about shaders that doesn't work
Question: This is an example from:
<http://pyopengl.sourceforge.net/context/tutorials/shader_1.xhtml>
It is creating a vbo, binging it, and running it with a shader, but somewhere
along the way, it is not working properly. I searched a lot on the internet
and didn't find any precise answers for my problem (the best pick I had was on
this topic on StackOverflow : [Why is this tutorial example of a shader not
displaying any geometry as it is supposed
to?](http://stackoverflow.com/questions/16945500/why-is-this-tutorial-example-
of-a-shader-not-displaying-any-geometry-as-it-is-su) but even if the author
was working on the same tutorial, he didn't have the same problem and solved
it by himself...)
from OpenGLContext import testingcontext
BaseContext = testingcontext.getInteractive()
from OpenGL.GL import *
from OpenGL.arrays import vbo
from OpenGLContext.arrays import *
from OpenGL.GL import shaders
class TestContext( BaseContext ):
def OnInit( self ):
VERTEX_SHADER = shaders.compileShader("""#version 330
void main() {
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}""", GL_VERTEX_SHADER)
FRAGMENT_SHADER = shaders.compileShader("""#version 330
void main() {
gl_FragColor = vec4( 0, 3, 6, 1 );
}""", GL_FRAGMENT_SHADER)
self.shader = shaders.compileProgram(VERTEX_SHADER,FRAGMENT_SHADER)
self.vbo = vbo.VBO(
array( [
[ 0, 1, 0 ],
[ -1,-1, 0 ],
[ 1,-1, 0 ],
[ 2,-1, 0 ],
[ 4,-1, 0 ],
[ 4, 1, 0 ],
[ 2,-1, 0 ],
[ 4, 1, 0 ],
[ 2, 1, 0 ],
],'f')
)
def Render( self, mode):
shaders.glUseProgram(self.shader)
try:
self.vbo.bind()
try:
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointerf(self.vbo)
glDrawArrays(GL_TRIANGLES, 0, 9)
finally:
self.vbo.unbind()
glDisableClientState(GL_VERTEX_ARRAY);
finally:
shaders.glUseProgram(0)
if __name__ == "__main__":
TestContext.ContextMainLoop()
Running this program from the windows command-line give me that error:
Traceback(most recent call last):
File "openGL-test.py', line 70, in <module>
TestContext.ContextMainLoop()
File "C:\Python27\lib\site-package\openglcontext-2.2.0a2-py2.7.egg\OpenGLContext\glutcontext.py", line 159, in ContextMainLoop
render = cls( *args, **named)
File "C:\Python27\lib\site-package\openglcontext-2.2.0a2-py2.7.egg\OpenGLContext\glutcontext.py", line 35, in __init__
glutInitDisplayMode( self.DISPLAYMODE )
File "C:\Python27\lib\site-package\OpenGL\platform\baseplatform.py", line 384, in __call__
self.__name__, self.__name__,
OpenGL.error.NullFunctionError: Attempt to call an undefined function glutInitDisplayMode, check for bool(glutInitDisplayMode) before calling
Any idea of what that means ? I have to precise, I began to learn Python two
months ago, so I'm pretty newbie, even if I had to work it a lot for my
internship period. (ho, and that's my first question on StackOverflow :)
Answer: It is failing because you don't have GLUT installed.
GLUT is the GL Utility Toolkit, a very widely used simple framework for
creating OpenGL programs that runs on MS Windows, Macs, Linux, SGI, ... All
the functions and constants have a glut or GLUT_ prefix, and
glutInitDisplayMode is the usually the first function that gets called.
[ REMOVE INSTALLATION NOTES ]
OK, you've done the install and it still doesn't work. That means that while
you have GLUT installed, the Python program can't load the GLUT DLL. Dynamic
linking, oh joy.
Find where glut32.dll got installed.
A quick and dirty solution for a single program is to copy the glut DLL into
the same directory as the program itself.
GLUT is 32 bit (AFAIK, unless you built it yourself) and this can be tricky if
you have a 64 bit version of Windows 7. The advice online is that on 64 bit
Windows a 32 bit DLL should be in C:\Windows\SysWoW64\ and a 64 bit DLL in
C:\Windows\System32\
(Seriously. I have not swapped the two directory names by mistake.)
If that doesn't work, I'm out of ideas.
|
unit testing python how tos
Question: I am new to Github. I am new to writing Unit Test Cases. I have contributed to
a project but the owner has asked me to provide unit testcases that fail
before the fix and work after the fix. How can I go about doing it? Shall I
write them all together? As at one time I will have one copy of the code (i.e
with fix or without fix). I am using Python and importing unittest. I am
confused. Before the fix I get an exception so should I use assertRaises() for
that. I did read a lot but am not able to start.
Answer: Assume you have a fix for following broken `delta` function:
Broken version:
def delta(a, b):
return a - b
Fixed version:
def delta(a, b):
return abs(a - b)
Then, provide following testcase. It will fail with the broken version, and
work with the fixed version.
import unittest
from module_you_fixed import delta
class TestDelta(unittest.TestCase):
def test_delta(self):
self.assertEqual(delta(9, 7), 2)
self.assertEqual(delta(2, 5), 3)
if __name__ == '__main__':
unittest.main()
I assumed the project use standard library unittest module. You should use the
framework that the project use.
|
Python Tkinter Double Scrollbar
Question: I am trying to display a bunch of very long labels with a scrollbar frame.
For some reason, I need to set the width and height of each label to a fixed
value.
But in that case, when the `label text` exceeds the `label width` and `label
height` some portion of label is not displayed.
So, I want to add another scrollbar for each label that has longer label text
than the label width and height. Here is what I have tried:
from Tkinter import*
def myfunction(event):
canvas1.configure(scrollregion=canvas1.bbox("all"),width=300,height=400)
root=Tk()
root.wm_geometry("%dx%d+%d+%d" % (500, 500, 5, 5))
data1="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
frame1=Frame(root)
frame1.place(x=20,y=20)
canvas1=Canvas(frame1)
frame2=Frame(canvas1,bg='white',relief=GROOVE,bd=0,width=1230,height=400)
scrollbar1=Scrollbar(frame1,orient="vertical",command=canvas1.yview)
canvas1.configure(yscrollcommand=scrollbar1.set)
scrollbar1.pack(side="right",fill="y")
canvas1.pack(side="left")
canvas1.create_window((0,0),window=frame2,anchor='nw')
frame2.bind("<Configure>",myfunction)
for i in range(10):
Label(frame2,text=data1,width=30,height=4,bg='white',relief=GROOVE,bd=1,wraplength=200,anchor=NW,justify=LEFT).grid(row=i,column=1)
root.mainloop()
Currently, I have a bunch of labels displayed using grid method on the canvas
that has a scrollbar attached. As you can see, a potion of my data "aaaa..."
is not displayed. Is there anyway I can add a scrollbar to each label boxes? I
don't want to change the size of label box.
Or should I use `Text box` instead of labels?
**\--EDIT--**
This is what I have tried:
from Tkinter import*
def myfunction(event):
canvas1.configure(scrollregion=canvas1.bbox("all"),width=400,height=200)
def myfunctionx(event):
canvas1x.configure(scrollregion=canvas1x.bbox("all"),width=100,height=50)
root=Tk()
root.wm_geometry("%dx%d+%d+%d" % (500, 500, 5, 5))
data1="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
frame1=Frame(root)
frame1.place(x=20,y=20)
canvas1=Canvas(frame1)
frame2=Frame(canvas1,bg='white',relief=GROOVE,bd=0,width=1230,height=400)
scrollbar1=Scrollbar(frame1,orient="vertical",command=canvas1.yview)
canvas1.configure(yscrollcommand=scrollbar1.set)
scrollbar1.pack(side="right",fill="y")
canvas1.pack(side="left")
canvas1.create_window((0,0),window=frame2,anchor='nw')
frame2.bind("<Configure>",myfunction)
frame1x=Frame(frame1,bg='green',width=100,height=50,bd=1,relief=GROOVE)
frame1x.place(x=10,y=20)
canvas1x=Canvas(frame1x,bg='yellow',relief=GROOVE,bd=0,width=100,height=50)
frame2x=Frame(canvas1x,bg='white',relief=GROOVE,bd=0,width=100,height=50)
scrollbar1x=Scrollbar(frame1x,orient="vertical",command=canvas1x.yview)
canvas1x.configure(yscrollcommand=scrollbar1x.set)
scrollbar1x.pack(side="right",fill="y")
canvas1x.pack(side="left")
canvas1x.create_window((0,0),window=frame2x,anchor='nw')
frame2x.bind("<Configure>",myfunctionx)
for i in range(10):
Label(frame2x,text=data1,width=20,height=4,bg='white',relief=GROOVE,bd=1,wraplength=200,anchor=NW,justify=LEFT).grid(row=i,column=1)
root.mainloop()
But instead of adding scrollbar to each label, it puts all labels into 1
scrollbar. Is there any way I can have 1 scrollbar for each label box?
(Assuming I will use looping to create several label boxes.)
Answer: You cannot use a scrollbar to scroll a label.
If you need text that is scrollable, use an Entry or Text widget.
|
Avoid Django to strip text file upload
Question: I've been asked to convert a Python application into a Django one but I'm
totally new to Django.
I have the following problem, when I upload a file text that must be read to
save its content into a database I find that Django is striping the "extra"
whitespaces and I must keep those whitespaces.
This is my template
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
{% if newdoc %}
<ul>
{% for line in newdoc %}
<li>{{ line }} </li>
{% endfor %}
</ul>
{% endif %}
<form action="{% url 'exam:upload' %}" method="post" enctype="multipart/form-data" content-type="text/plain">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<p><input type="submit" value="Upload" /></p>
</form>
</body>
This is what I have in the views.py
def upload(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = request.FILES['docfile']
form = DocumentForm()
return render(request, 'exam/upload.html', {'newdoc': newdoc, 'form': form})
else:
form = DocumentForm() # A empty, unbound form
return render(request, 'exam/upload.html', {
'form': form,
})
And this is my forms.py:
from django import forms
class DocumentForm(forms.Form):
docfile = forms.FileField(
label='Select a file',
help_text='max. 42 megabytes'
)
Now when I upload the file, it shows a random line like this:
"09000021009296401 02 b a b a b b b d b b d d a +8589 +03+6942 +03+1461 +00+5093 +00+2 +00+9237 +01+60 +01+00 +00"
While it should be this:
"09000021009296401 02 b a b a b b b d b b d d a +8589 +03+6942 +03+1461 +00+5093 +00+2 +00+9237 +01+60 +01+00 +00 "
I must keep the extra spaces and they save this information into a database,
which I cannot correctly do if I don't have all the spaces that the file has.
Also, before you ask, It is not related with the print format of Django, since
in a previous test I already tryed to save the information into the model, but
it has the same problem with spaces.
Thanks everyone.
Answer: Change the template as follow:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
{% if newdoc %}
<pre><code>{% for line in newdoc %}{{ line|safe }}{% endfor %}</code></pre>
{% endif %}
<form action="{% url 'exam:upload' %}" method="post" enctype="multipart/form-data" content-type="text/plain">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<p><input type="submit" value="Upload" /></p>
</form>
</body>
|
Python 2.7 and xml.etree: how to create an XML file with multiple namespaces?
Question: I'm trying to _create_ an XML file so that it has the following skeleton,
preferably using the xml.etree modules in Python 2.7:
<?xml version="1.0"?>
<foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" thing1="this" thing2="that">
....
<somedata bar="1">
<moredata whatsit="42"></moredata>
</somedata>
....
</foo>
**It's the "foo ...." line that vexes me.** I tried using nsmap for bringing
in xsi and xsd, but that led to a "cannot serialize" error.
I could construct or otherwise hack that line's text to be exactly as I want
it, but **I'd like to learn to do this programmatically using xml.etree**
(pulling in an external library is not preferable in this situation).
I'd think this is a common pattern but I'm just not finding it anywhere for
Python and etree.
Answer: If the prefixes are used in the document; you could call
`register_namespace()` to add them:
import sys
import xml.etree.ElementTree as etree
xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsd = "http://www.w3.org/2001/XMLSchema"
ns = {"xmlns:xsi": xsi, "xmlns:xsd": xsd}
for attr, uri in ns.items():
etree.register_namespace(attr.split(":")[1], uri)
foo = etree.Element("foo",
dict(thing1="this", thing2="that")) # put `**ns))` if xsi, xsd are unused
somedata = etree.SubElement(foo, "somedata", dict(bar="1"))
etree.SubElement(somedata, "moredata",
{"whatsit": "42", etree.QName(xsi, "type"): etree.QName(xsd, "string")})
etree.ElementTree(foo).write(sys.stdout, xml_declaration=True)
Otherwise, you could set the attributes explicitly (`ns` dict) if you need it.
|
Imported modules become None when running a function
Question: **Update** : some more debugging info at the bottom of this post, which
reveals something very screwy in the python state.
I have a module which imports, among other things, the django User object.
The import works fine, and the code loads. However, when you call a function
in that module that uses the User object, it errors saying that User is a
NoneType.
There are also a number of other imports, and some module level global
variables which are also None by the time the function is called.
Oddly, this is only a problem in our staging environments (Ubuntu 12.04). It
works fine locally, which probably most closely resembles staging with extra
python packages for dev work. Also fine in production.
Has anyone come across this before, and have any ideas what might cause it?
Here's the code:
import urllib
import time
import urlparse
# Django imports
from django.db.models.signals import post_delete
from django.db import models
from django.contrib.auth.models import User
from backends.cache.dualcache import cache
# Piston imports
from managers import TokenManager, ConsumerManager
from signals import consumer_post_delete
KEY_SIZE = 18
SECRET_SIZE = 32
VERIFIER_SIZE = 10
CONSUMER_STATES = (
('pending', 'Pending'),
('accepted', 'Accepted'),
('canceled', 'Canceled'),
('rejected', 'Rejected')
)
def generate_random(length=SECRET_SIZE):
return User.objects.make_random_password(length=length)
class Consumer(models.Model):
name = models.CharField(max_length=255)
description = models.TextField()
key = models.CharField(max_length=KEY_SIZE)
secret = models.CharField(max_length=SECRET_SIZE)
status = models.CharField(max_length=16, choices=CONSUMER_STATES, default='pending')
objects = ConsumerManager()
def __unicode__(self):
return u"Consumer %s with key %s" % (self.name, self.key)
def generate_random_codes(self):
key = User.objects.make_random_password(length=KEY_SIZE)
secret = generate_random(SECRET_SIZE)
while Consumer.objects.filter(key__exact=key, secret__exact=secret).count():
secret = generate_random(SECRET_SIZE)
self.key = key
self.secret = secret
self.save()
and here's the work around, which means basically to import what you need
again inside the function:
import urllib
import time
import urlparse
# Django imports
from django.db.models.signals import post_delete
from django.db import models
from django.contrib.auth.models import User
from backends.cache.dualcache import cache
# Piston imports
from managers import TokenManager, ConsumerManager
from signals import consumer_post_delete
KEY_SIZE = 18
SECRET_SIZE = 32
VERIFIER_SIZE = 10
CONSUMER_STATES = (
('pending', 'Pending'),
('accepted', 'Accepted'),
('canceled', 'Canceled'),
('rejected', 'Rejected')
)
def generate_random(length=SECRET_SIZE):
return User.objects.make_random_password(length=length)
class Consumer(models.Model):
name = models.CharField(max_length=255)
description = models.TextField()
key = models.CharField(max_length=KEY_SIZE)
secret = models.CharField(max_length=SECRET_SIZE)
status = models.CharField(max_length=16, choices=CONSUMER_STATES, default='pending')
objects = ConsumerManager()
def __unicode__(self):
return u"Consumer %s with key %s" % (self.name, self.key)
def generate_random_codes(self):
from piston.models import KEY_SIZE, SECRET_SIZE, Consumer
from django.contrib.auth.models import User
from piston.models import generate_random
key = User.objects.make_random_password(length=KEY_SIZE)
secret = generate_random(SECRET_SIZE)
while Consumer.objects.filter(key__exact=key, secret__exact=secret).count():
secret = generate_random(SECRET_SIZE)
self.key = key
self.secret = secret
self.save()
Here's the stack trace. The error is caused by the line:
key = User.objects.make_random_password(length=KEY_SIZE)
in the generate_random_codes function.
Traceback:
File "/sites/tellybug/shared/webserver/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/sites/tellybug/shared/webserver/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in wrapper
366. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/sites/tellybug/shared/webserver/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
91. response = view_func(request, *args, **kwargs)
File "/sites/tellybug/shared/webserver/local/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
89. response = view_func(request, *args, **kwargs)
File "/sites/tellybug/shared/webserver/local/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner
196. return view(request, *args, **kwargs)
File "/sites/tellybug/shared/webserver/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper
25. return bound_func(*args, **kwargs)
File "/sites/tellybug/shared/webserver/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
91. response = view_func(request, *args, **kwargs)
File "/sites/tellybug/shared/webserver/local/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func
21. return func(self, *args2, **kwargs2)
File "/sites/tellybug/shared/webserver/local/lib/python2.7/site-packages/django/db/transaction.py" in inner
224. return func(*args, **kwargs)
File "/sites/tellybug/shared/webserver/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in add_view
970. form = ModelForm(initial=initial)
File "/sites/tellybug/shared/webserver/local/lib/python2.7/site-packages/django/forms/models.py" in __init__
234. self.instance = opts.model()
File "/sites/tellybug/shared/webserver/local/lib/python2.7/site-packages/django/db/models/base.py" in __init__
349. val = field.get_default()
File "/sites/tellybug/shared/webserver/local/lib/python2.7/site-packages/django/db/models/fields/related.py" in get_default
983. field_default = super(ForeignKey, self).get_default()
File "/sites/tellybug/shared/webserver/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in get_default
379. return self.default()
File "/sites/tellybug/releases/b92109dd526607b2af92ad6b7f494f3f06e31bb2/webserver/tellybug/tbapp/models/tellybugapp.py" in generate_new_consumer
11. consumer.generate_random_codes()
File "/sites/tellybug/releases/b92109dd526607b2af92ad6b7f494f3f06e31bb2/webserver/tellybug/piston/models.py" in generate_random_codes
57. key = User.objects.make_random_password(length=KEY_SIZE)
Exception Type: AttributeError at /admin/tbapp/tellybugapp/add/
Exception Value: 'NoneType' object has no attribute 'objects'
**Update** : It's not something just deleting the User object - something is
wrecking the entire context in the function.
def generate_random_codes(self):
"""
Used to generate random key/secret pairings. Use this after you've
added the other data in place of save().
c = Consumer()
c.name = "My consumer"
c.description = "An app that makes ponies from the API."
c.user = some_user_object
c.generate_random_codes()
"""
import sys
print "Globals", globals()
print "Name ", __name__
print "Package ", __package__
print "Sys modules", sys.modules['piston.models'].__dict__
key = User.objects.make_random_password(length=KEY_SIZE)
With these print statements, the output is:
Globals {'ColumnFamilyMap': None, 'datetime': None, 'KEY_SIZE': None, 'TokenManager': None, 'ConsistencyLevel': None, 'Nonce': None, 'uuid': None, 'cache': None, 'urllib': None, '__package__': None, 'models': None, 'User': None, .... }
Name None
Package None
Sys modules {'ColumnFamilyMap': <class 'pycassa.columnfamilymap.ColumnFamilyMap'>, 'datetime': <type 'datetime.datetime'>, 'KEY_SIZE': 18, 'NonceType': <class 'piston.models.NonceType'>, 'OAuthToken': <class 'piston.models.OAuthToken'>, 'TokenManager': <class 'piston.managers.TokenManager'>, 'ConsistencyLevel': <class 'pycassa.cassandra.ttypes.ConsistencyLevel'>, 'Nonce': <class 'piston.models.Nonce'>, 'uuid': <module 'uuid' from '/usr/lib/python2.7/uuid.pyc'>, ...}
Note that both `__package__` and `__name__` are undefined, which I thought was
pretty much impossible, and that while the sys.modules version of the module
has a correct `__dict__`, the return value from `globals()` is nonsense.
Answer: This happens to a function in an imported module that is still executing after
that module is garbage collected.
Since your code isn't enough to reproduce the issue, here's a simplified
example that shows the behaviour. Create a file containing the following and
import it either from the Python command line or from another file. It doesn't
work if you just run it at the top level.
import sys
import threading
x = "foo"
def run():
while True:
print "%s %s\n" % (sys, x)
threading.Thread(target = run).start()
sys.stdin.readline()
Running it:
$ python
>>> import evil_threading
<module 'sys' (built-in)> foo
<module 'sys' (built-in)> foo
... press Ctrl-C
None None
None None
... press Ctrl-\ to kill the Python interpreter
During Python shutdown, modules are set to `None`. [This is an obscure Python
behaviour that was removed in
3.4](http://stackoverflow.com/q/25649676/509706). In this example, terminating
the main thread results in shutdown, but the other thread is still running, so
it sees the modules as `None`.
There is a simpler example [from here](http://grokbase.com/t/python/python-
list/035r7sjsnj/module-gets-garbage-collected-its-globals-become-none) which
does the same thing by deleting the module reference directly from
sys.modules.
import sys
print sys
del sys.modules['__main__']
print sys
|
Is there a python module that convert a value and an error to a scientific notation?
Question: Suppose I have two numbers, `v = 0.01342` and `err = 0.0004`. Under scientific
notation, this would be written as `(13.4 ± 0.4)e-3`. Is there a function that
does that conversion (probably on scipy)? Naturally, the important thing is
the numbers and not the `±` sign. Searching the web, I learned that there is
(are?) function(s?) which eat a number to transform and a number of desired
digit and they spit the result. This is not what I'm searching for. I've
written once but it turned out to be quite ugly.
Answer: I didn't understand what you meant by the last few lines, but when you have a
specific output like yours, you usually have to write you own.
def sci_not(v,err,rnd=1):
power = - int(('%E' % v)[-3:])+1
return '({0} +/- {1})e{2}'.format(
round(v*10**power,rnd),round(err*10**power,rnd),power)
This does the trick
>>> v = .01342
>>> err = .0004
>>> sci_not(v,err)
(13.4 +/- 0.4)e3
**EDIT :** You can put in the ± character if you make the string unicode, but
the results only look pretty when you use a print statment.
Replace the previous return statement with
return u'({0} \u00B1 {1})e{2}'.format(
round(v*10**power,rnd),round(err*10**power,rnd),power)
This returns
>>> sci_not(v,err)
u'(13.4 \xb1 0.4)e3'
>>> print sci_not(v,err)
(13.4 ± 0.4)e3
|
App Engine dev server: bad runtime process port ['']
Question: I get following error message when I run the local dev server:
bad runtime process port ['']
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.py", line 565, in <module>
main()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.py", line 547, in main
known_paths = addusersitepackages(known_paths)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.py", line 278, in addusersitepackages
user_site = getusersitepackages()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.py", line 253, in getusersitepackages
user_base = getuserbase() # this will also set USER_BASE
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.py", line 242, in getuserbase
from sysconfig import get_config_var
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sysconfig.py", line 104, in <module>
_PROJECT_BASE = os.path.dirname(_safe_realpath(sys.executable))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sysconfig.py", line 99, in _safe_realpath
return realpath(path)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.py", line 366, in realpath
if islink(component):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.py", line 136, in islink
return stat.S_ISLNK(st.st_mode)
AttributeError: 'module' object has no attribute 'S_ISLNK'
I have tried to revert a couple of days and run the project in a well known
working state, I get the same error. No problem to upload to google. Other
projects work locally. I use the 1.8.1 SDK.
Answer: I had similar problems locally. I solved deleting all the files .pyc and
reload page.
|
python ultrajson: how to use?
Question: I've just installed ultrajson (ujson) to see if I can't get the json decoding
to go faster (string to object). However, I'm not seeing any examples of how
to use it.
with regular json it's just
import json
my_object = json.loads(my_string)
Answer: Change the import statement to `import ujson as json`
Then you can leave the other parts of your program as it is.
|
Arabic, Unicode and files in python
Question: I am trying to grab some text written in Arabic from Youtube, writting it into
a file and reading it again.
The source file to grab the text has:
#!/usr/bin/python
#encoding: utf-8
in the beginning of the file.
Writing the text are done like this:
f.write(comment + '\n' )
The file contents is readable Arabic, so I assume the previous steps were
correct.
But the problem appears when trying to read the contents from the file (and
writing them for example into another file) like this:
in = open('data_Pass1/EG', 'rb')
out.write(in.read())
Which results in output file like this:
\xd8\xa7\xd9\x8a\xd9\x87
What is causing this?
Answer: In python 3.x
in = open('data_Pass1/EG', 'r', encoding='utf-8')
out = open('_file_name_', 'w', encoding='utf-8')
In python 2.x.
import codecs
in = codecs.open('data_Pass1/EG', 'r', encoding='utf-8')
out = codecs.open('_file_name_', 'w', encoding='utf-8')
|
cx_freeze yields "NameError: name 'build_exe_options' is not defined" on build attempt
Question: I am running Python 3.3 and cx_freeze 3.3 x86 on Win XP x86.
I have a setup file and my application file in the same directory, the setup
file contains the following:
import sys
from cx_Freeze import setup, Executable
setup( name = "Duplicate Finder x86",
version = "1.0",
description = "Duplicate Finder x86",
options = {"build_exe": build_exe_options},
executables = [Executable("Comparator Source.py", base=base)])
I attempt my build using this command:
C:\Documents and Settings\user\Desktop\Construction Yard>C:\Python33\Python setup.py build
And I receive this error:
Traceback (most recent call last):
File "setup.py", line 7, in <module>
options = <"build_exe": build_exe_options>,
NameError: name 'build_exe_options' is not defined
I am not experienced with using cx_freeze, but I feel that I have most of the
pieces in place here. Any help as to what I am missing?
Answer: I figured this out. I was using a modified version of the example setup script
given on the documentation page. I needed to remove unnecessary portions,
modifying it to the following:
import sys
from cx_Freeze import setup, Executable
setup( name = "Duplicate Finder x86",
version = "1.0",
description = "Duplicate Finder x86",
executables = [Executable("Comparator Source.py")])
|
Python Bytearray Printing
Question: I have an integer list in Python that should correspond to the following int
values (which can be changed to hex byte values):
[10, 145, 140, 188, 212, 198, 210, 25, 152, 20, 120, 15, 49, 113, 33, 220, 124, 67, 174, 224, 220, 241, 241]
However, when I convert that list to a bytearray (using
bytearray(nameOfList)), I get the following printout.
bytearray(b'\n\x91\x8c\xbc\xd4\xc6\xd2\x19\x98\x14x\x0f1q!\xdc|C\xae\xe0\xdc\xf1\xf1')
I can pull the correct values from this byte array, regardless of how it
prints, but shouldn't the bytearray printout correspond to the hex values of
the byte array? (I mean, it seems to mostly follow the hex values up until
after \x0f, where it starts putting out gibberish...)
Answer:
>>> x = bytearray(b'\n\x91\x8c\xbc\xd4\xc6\xd2\x19\x98\x14x\x0f1q!\xdc|C\xae\xe0
\xdc\xf1\xf1')
>>> import binascii
>>> print binascii.hexlify(x)
0a918cbcd4c6d2199814780f317121dc7c43aee0dcf1f1
Use binascii if you want all of it to be printed as a hex string
|
Python Terminology of "pairs"
Question: I sort of learned backyard python without all of the fancy terminology, and I
came across this description of a pickled file...
"The pickled file represents a tuple of 3 lists : the training set, the
validation set and the testing set. **Each of the three lists is a pair formed
from a list of images and a list of class labels for each of the images.** An
image is represented as numpy 1-dimensional array of 784 (28 x 28) float
values between 0 and 1 (0 stands for black, 1 for white). The labels are
numbers between 0 and 9 indicating which digit the image represents."
(From <http://deeplearning.net/tutorial/gettingstarted.html>)
I'm trying to visualize it in my head (this is the format they want pickled so
I cant just modify it), does that mean that the file is
(1) Three Lists, Each of which is made up of two lists, one with images, and
one with labels,
(2) Three Lists, Each of which is composed of tuples, with (tuple[0] being
image and tuple[1] being label)
or something else?
Answer: Here's how you can investigate the topology of the data:
In [1]: import cPickle
In [2]:
In [3]: f = cPickle.load(open('mnist.pkl', 'rb'))
In [4]: type(f)
Out[4]: tuple
In [5]: len(f)
Out[5]: 3
In [6]: type(f[0])
Out[6]: tuple
In [7]: len(f[0])
Out[7]: 2
In [8]: type(f[0][0])
Out[8]: numpy.ndarray
In [9]: len(f[0][0])
Out[9]: 50000
In [10]: f[0][0].shape
Out[10]: (50000, 784)
|
Building python pylab/matplotlib exe using pyinstaller
Question: The following code runs fine and displays a simple pie chart when run as an
interpreted python py program.
A month ago, I used pyinstaller to create a stand-alone exe and that worked
great.
Recently, I decided to rebuild the exe. The pyinstaller build completes
successfully without errors, but the generated exe does nothing when run. When
I run it, it ends quickly without any errors and without displaying a pie
chart. Something has changed since a month ago, but I can't figure out what.
I've tried uninstalling python and all modules and reinstalling, but that made
no difference.
from pylab import *
from matplotlib import pyplot as plt
figure(1, figsize=(6,6))
ax = axes([0.1, 0.1, 0.8, 0.8])
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15, 30, 45, 10]
explode=(0, 0.05, 0, 0)
pie(fracs, explode=explode, labels=labels,
autopct='%1.1f%%', startangle=90)
title('Pie Chart Example', bbox={'facecolor':'0.8', 'pad':5})
show()
This is the pyinstaller command I am using to build the exe. This command
works for other pyqt gui builds and their exe's work fine. I am only having a
problem building pylab/matplotlib python code.
c:/python27/python.exe c:/pyinstaller/pyinstaller.py --noconfirm --noconsole --onefile --icon=pie.ico pie.py
Answer: Found the solution. Apparently there was a bug in the version of pyinstaller I
had. Found this post on pyinstaller's site:
<http://www.pyinstaller.org/ticket/651>
So I downloaded the latest pyinstaller and I can build an exe of my piechart
python program again!
|
Python script from Cron
Question: I have finished a program in Python and I intend for it to be run from my RPi
every _n_ hours. This will be my first time running such program/script in
this way and I would like to know if there is anything I should know/have
written into the script before I add it to my crontab?
I'm also not sure how such an entry in the crontab would look. Do I write
something like:
* 2 * * * pi `python /home/pi/Desktop/myProg.py`
With back-ticks around the command or would I launch myProg.py from within a
shell script that I would call from the crontab?
* 2 * * * pi /home/pi/Desktop/launchMyProg.sh
Also, I had some `print` statements in the program that I commented out as
they were mainly for debug during writing it, but on second thoughts it would
be useful for me to have these for debug info but directed to the
`/var/log/messages` or other log file which I can monitor with `tail -f
/var/log/messages` command.
How would I do that exactly? Thanks.
Answer: You are on the right track. To fire a python script every _n_ hours, do this:
* */n * * * python /home/pi/Desktop/myProg.py
That's it. Make sure that you are editing the sudo level crontab, which is
accessed via `sudo crontab -e`.
Your code would actually have the script run at 2 am every day - it
technically says "run whenever the hour is equal to `2`". `* */n * * *` says
"run whenever the hour is divisible by `n`". A GREAT resource on crontab can
be found here: [Schedule tasks on Linux using
crontab](http://kvz.io/blog/2007/07/29/schedule-tasks-on-linux-using-crontab/)
Logging the output is also easy. If you had a log file on your desktop called
myLog.log, you would add `>> /home/pi/Desktop/myLog.log` to end of the crontab
entry. That would make the entry look like this:
* */2 * * * python /home/pi/Desktop/myProg.py >> /home/pi/Desktop/myLog.log
**EDIT** (thanks to @Iamreck): Another option for outputting to a file is with
sys.stdout. This would accomplish the same goal. To do it this way, add the
following to your Python script:
import sys
sys.stdout = open("myLog.log","w")
sys.stderr = open("myLogErr.log","w")
print "stdout test"
You would also have to change the working directory to your Desktop when doing
this, and this can be done with the top answer at [this SO
post](http://stackoverflow.com/questions/1432924/python-change-the-scripts-
working-directory-to-the-scripts-own-directory)
|
Python TweetStream Access Denied
Question: I keep getting this exception from TweetStream 1.1.1, "exception.code ==
404:uthenticationError("Access denied")" It worked last week and now it
doesn't. I have tried different usernames and passwords. I can log into
twitter with my account information. I even deleted and reinstalled the
module. what gives? Thanks for the help!
I try running this...
import tweetstream
stream = tweetstream.SampleStream("MY_USERNAME", "MY_PASSWORD")
for tweet in stream:
print tweet
The error actually looks like this:
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
for tweet in stream:
File "C:\Python27\lib\site-packages\tweetstream-1.1.1-py2.7.egg\tweetstream\streamclasses.py", line 165, in __iter__
self._init_conn()
File "C:\Python27\lib\site-packages\tweetstream-1.1.1-py2.7.egg\tweetstream\streamclasses.py", line 103, in _init_conn
raise AuthenticationError("Access denied")
AuthenticationError: Access denied
Answer: Twitter released the next version of API
([1.1](https://dev.twitter.com/docs/api/1.1)). And tweetstream doesn't support
it yet. See [relevant
issue](https://bitbucket.org/runeh/tweetstream/issue/26/upgrading-to-
streaming-api-version-11) on tweetstream project issue tracker.
|
How to replace a character in some specific word in a text file using python
Question: I got a task to replace "O"(capital O) by "0" in a text file by using python.
But one condition is that I have to preserve the other words like Over, NATO
etc. I have to replace only the words like 9OO to 900, 2OO6 to 2006 and so on.
I tried a lot but yet not successful. My code is given below. Please help me
any one. Thanks in advance
import re
srcpatt = 'O'
rplpatt = '0'
cre = re.compile(srcpatt)
with open('myfile.txt', 'r') as file:
content = file.read()
wordlist = re.findall(r'(\d+O|O\d+)',str(content))
print(wordlist)
for word in wordlist:
subcontent = cre.sub(rplpatt, word)
newrep = re.compile(word)
newcontent = newrep.sub(subcontent,content)
with open('myfile.txt', 'w') as file:
file.write(newcontent)
print('"',srcpatt,'" is successfully replaced by "',rplpatt,'"')
Answer: `re.sub` can take in a replacement function, so we can pare this down pretty
nicely:
import re
with open('myfile.txt', 'r') as file:
content = file.read()
with open('myfile.txt', 'w') as file:
file.write(re.sub(r'\d+[\dO]+|[\dO]+\d+', lambda m: m.group().replace('O', '0'), content))
|
I was trying to make it so something would equal something else Python 2.7.3
Question: I decided to make a code with a friend and wanted to be able to crack (decode)
it with this program. Basically what I want is one word to equal another for
example the word "be" would show in the program as the word "ok".
So I have the raw_input to put the words to crack in. Say I put in the
sentence "hi friend" how would I get it to come out as for example "dog
crazy". Also if I put in "dog crazy" to come out as "hi friend".
Sorry if this is hard to understand but I'm not sure how to explain it to
well.
I am using Python 2.7.3. Thanks.
Answer:
import operator
mapping={
'hi': 'dog',
'friend': 'crazy',
}
for k,v in list(mapping.items()):
mapping[v]=k
print(' '.join(map(lambda w: mapping.get(w,w),input().split())))
|
Steps of interpreting how this operation runs
Question: I was wondering if anyone could tell me step by step how these operations run.
I'm not sure how they are being executed the way they are and I would like to
understand. Thank you
>>>s = 'Fuzzy wuzzy was a bear'
>>>t=''
>>>j=4
>>>for w in s.split():
if j%2 == 0:
t = w[0] + t
j-=1
>>>print(t)
bwF
As well as this one:
>>>s = 'Fuzzy wuzzy was a bear'
>>>p = ''
>>>q = False
>>>for ch in s[:5]:
if q:
p+=ch
if ch == 'u':
q = not q
>>>print(p)
zzy
If anyone could explain the steps python takes to interpreting this and
executing it to get the results that it does, I would really appreciate it.
Answer: What you could do is use python debugger pdb like so :
import pdb
pdb.set_trace()
s = 'Fuzzy wuzzy was a bear'
t=''
j=4
for w in s.split():
if j%2 == 0:
t = w[0] + t
j-=1
print(t)
With this, you will be able to execute your code step by step and print the
values after any instruction. You can read more about it
[here](http://docs.python.org/2/library/pdb.html)
|
Using MySQLdb to return values - Python
Question: I have a table called `coords` and it is defined as:
mysql> describe coords;
+-----------+--------------+------+-----+------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+------------------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| location | varchar(150) | NO | UNI | NULL | |
| latitude | float(20,14) | YES | | 0.00000000000000 | |
| longitude | float(20,14) | YES | | 0.00000000000000 | |
-----------------------------------------------------------------------------
I am using the `MySQLdb` import in my Python script. The purpose of this table
is to store (as you can guess, but for clarity) location coordinates (but only
when I do not have the coordinates already for a particular location).
I will be querying this table in my Python program to see if I already have
coordinates for a pre-requested location. I'm doing this to speed up the use
of the `geopy` package that interrogates Google's Geolocation Service.
How do I store the returned floats that correspond to a location? So far I
have the following:
myVar = cur.execute("SELECT latitude, longitude FROM coords WHERE location ='" + jobLocation + "';")
if myVar == 1:
print(cur.fetchone())
else:
try:
_place, (_lat, _lon) = geos.geocode(jobLocation, region='GB', exactly_one=False)
print("%s: %.5f, %.5f" % _place, (_lat, _lon))
except ValueError as err:
print(err)
The code works (well, not really...) but I have no idea of how to get the
returned coordinates into separate float variables.
Can you help?
Answer: When you do `cur.fetchone()`, you need to store the result somewhere:
row = cur.fetchone()
print row[0], row[1]
Now `row[0]` will contain the latitude, and row[1] the longitude.
If you do this when connecting:
cur = con.cursor(mdb.cursors.DictCursor)
you can then use a dictionary to refer to the columns by name:
row = cur.fetchone()
print row["latitude"], row["longitude"]
|
Writing Python ElementTree to file throws TypeError
Question: I'm trying to write an XML file using Python's ElementTree package. Basically
I make a root element called `allDepts`, and then in each iteration of my for
loop I call a function that returns a `deptElement` containing a bunch of
information about a university department. I add every `deptElement` to
`allDepts`, make an `ElementTree` out of `allDepts`, and try to write it to a
file.
def crawl(year, season, campus):
departments = getAllDepartments(year, season, campus)
allDepts = ET.Element('depts')
for dept in departments:
deptElement = getDeptElement(allDepts, dept, year, season, campus)
print ET.tostring(deptElement) #Prints fine here!
ET.SubElement(allDepts, deptElement)
if deptElement == None:
print "ERROR: " + dept
with open(str(year) + season + "_" + campus + "_courses.xml", 'w') as f:
tree = ET.ElementTree(allDepts)
tree.write(f)
For some reason, at the `tree.write(f)` line, I get this error: "TypeError:
cannot concatenate 'str' and 'instance' objects". Each `deptElement` prints
out fine in the for loop, making me think that `getDeptElement()` is working
fine. I never get my "ERROR" message printed out. Does anyone know what I'm
doing wrong?
EDIT: Here's the full stack trace:
File "./CourseInfoCrawl.py", line 210, in <module>
crawl("2013", "S", "UBC")
File "./CourseInfoCrawl.py", line 207, in crawl
tree.write(f)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xml/etree/ElementTree.py", line 663, in write
self._write(file, self._root, encoding, {})
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xml/etree/ElementTree.py", line 707, in _write
self._write(file, n, encoding, namespaces)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xml/etree/ElementTree.py", line 681, in _write
file.write("<" + _encode(tag, encoding))
Answer: Seem following line is cause.
print "ERROR: " + dept
Change as follow and retry:
print "ERROR: ", dept
OR
print "ERROR: " + str(dept)
**ADD**
Second argument to ET.SubElement should be str. Is `deptElement` is str? If
`deptElement` is Element, use `allDepts.append(deptElement)`.
<http://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.SubElement>
<http://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.append>
**ADD 2** To reproduce error (Python 2.6):
>>> from xml.etree import ElementTree as ET
>>> allDepts = ET.Element('depts')
>>> ET.SubElement(allDepts, ET.Element('a'))
<Element <Element a at b727b96c> at b727b22c>
>>> with open('a', 'wb') as f:
... tree = ET.ElementTree(allDepts)
... tree.write(f)
...
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
File "/home/falsetru/t/Python-2.6/Lib/xml/etree/ElementTree.py", line 663, in write
self._write(file, self._root, encoding, {})
File "/home/falsetru/t/Python-2.6/Lib/xml/etree/ElementTree.py", line 707, in _write
self._write(file, n, encoding, namespaces)
File "/home/falsetru/t/Python-2.6/Lib/xml/etree/ElementTree.py", line 681, in _write
file.write("<" + _encode(tag, encoding))
TypeError: cannot concatenate 'str' and 'instance' objects
To reproduce error (Python 2.7, different error message):
>>> from xml.etree import ElementTree as ET
>>> allDepts = ET.Element('depts')
>>> ET.SubElement(allDepts, ET.Element('a'))
<Element <Element 'a' at 0xb745a8ec> at 0xb74601ac>
>>> with open('a', 'wb') as f:
... tree = ET.ElementTree(allDepts)
... tree.write(f)
...
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 817, in write
self._root, encoding, default_namespace
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 886, in _namespaces
_raise_serialization_error(tag)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 1052, in _raise_serialization_error
"cannot serialize %r (type %s)" % (text, type(text).__name__)
TypeError: cannot serialize <Element 'a' at 0xb745a8ec> (type Element)
|
ImportError: No module named httplib2, but httplib2 is installed
Question: I know this may be somewhat of a duplicate, but the difference is that i have
httplib2 installed, look:
D4zk1tty@kali:~$ sudo apt-get install python-httplib2
Reading package lists... Done
Building dependency tree
Reading state information... Done
python-httplib2 is already the newest version.
python-httplib2 set to manually installed.
0 upgraded, 0 newly installed, 0 to remove and 2 not upgraded
maybe it is not in the right directory?
here is my traceback:
Traceback (most recent call last):
File "test.py", line 9, in <module>
import httplib2
ImportError: No module named httplib2
Answer: In Ubuntu python2/python3 modules are split in separated packages. So to
install `httplib2` in `python3` the correct command is
$ sudo apt-get install python3-httplib2
Usually you can assume if there is any package named `python-???`, you also
have `python3-???` (`python-django` is one example which don't have a python3
package available).
|
twitter api not working simple command
Question: I am trying to extract tweets from a user using python. It is 3 lines of code,
but python is giving me a hard time.
>>> import twitter
>>> api = twitter.Api()
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
api = twitter.Api()
AttributeError: 'module' object has no attribute 'Api'
and the final line of code would be:
>>> status = api.GetUserTimeline('username')
how do I fixed that 2nd line's error. I have python 3.2.2.3
Answer: You need to authenticate first:
api = twitter.Api(consumer_key='consumer_key',
consumer_secret='consumer_secret',
access_token_key='access_token',
access_token_secret='access_token_secret')
The consumer key, consumer secret, access_token, and access_token_secret are
found on the Twitter Development Page: <https://dev.twitter.com/apps>
Use it to create a fake app and it'll give you the information you need.
If you need more help, here is website: <https://code.google.com/p/python-
twitter/>
Cheers
|
Django Forum App Project Structure
Question: **EDIT: I'm new to this site but if you are going to down vote me, could you
perhaps explain why? I've searched Google, this site and others but have not
found anything that makes any sense and I thought this was a site to ask
questions and get some help.**
I've got a Custom PHP Forum that I am trying to convert to Python/Django as a
learning experience and I'm having some problems. I've been reading up on
Django and it is encouraged that our application is split into multiple apps.
I went through the 6 part tutorial and many other parts of the documentation
but I'm left with some questions.
Let's assume that I have about 30 tables.
Tables such as: posts_index, posts, users, user_groups, user_activity,
user_sessions, forums, payment_gateways, payment_logs, etc for a basic forum
I'm having issues structuring my models. With PHP all I needed was index.php,
/admin/index.php, view_forum.php, view_thread.php and a few others, everything
could pull directly from the database and I had no issues but now I have to
deal with apps/modules.
I'm thinking I'd need to structure my apps in a manner similar to this:
/admin/ app
/forums/ app
/view_forum/ app
/view_thread/ app
/forums/view_forum/ app (instead of just /view_forum/, could be a sub app)
/forums/view_thread/ app (instead of /view_thread/, could be a sub app)
**My problem and only question here is dealing with global state. For example
Users/Group/Session/Logging/Permission information is going to need to be
shared across multiple apps through importing in the other apps models file.
To do this I need to reference their model information, what is the correct
way to handle this?**
Would either of these be acceptable?
1. Create a ton of different apps such as /users/ which would model my users_groups, users, user_sessions, another app for /posts/ that would include models for posts_index, forums, and so forth with these models existing but not actually being used publicly, they would be used in other apps only. They would be imported in areas such as the /view_forum/ app since when viewing a forum I might need to determine if the user is logged in, is a member of a particular group, etc and because of that would need access to a number of the hidden apps and hence would be imported from the hidden app.
2. What if I just had one single app, instead of it being an app it would just be my entire project. This sounds like the best solution to me but it seems to be suggested if we cannot summarize the entire application into a sentence it needs to be broken up. If I went with one single app being used as my entire project, my models file will have 30+ different models, is this acceptable? I assume not but figured I'd ask.
Do either of the above make any sense? If not what would you do fix it? I'll
admit I'm lost so any feedback would mean a lot.
I'm new to Python/Django and am trying to figure things out. I hope I am clear
on what I am trying to do. I'm more than welcome to any advice. I've been
trying to play around with things but I figure it would be better to ask for
advice from more experienced developers. I'm not a professional programmer and
am still learning so please be nice :).
Answer: I have voted this up... I had similar questions when I first moved to Django
(also coming from PHP)
Try not to think of apps in terms of db tables (or url paths), you want to
create apps for independent pieces of functionality.
I would say most of your code will be in a single `forum` app with `Forum` and
`Post` models in it and all your forum-related urls like `/view_forum/` and
`/view_thread/`. Note there's not really such thing as a sub-app in Django...
these are different views which all belong to one related set of functionality
in a single app.
The 'users' stuff... you normally want to hook in to the Django auth system
(<https://docs.djangoproject.com/en/dev/topics/auth/default/#user-objects>)
though if you are trying to keep the legacy database structure this may be
harder... you may end up needing your own `users` app.
The payment gateways stuff sounds like another app again.
For the admin, you get this (almost) for free with Django:
<https://docs.djangoproject.com/en/1.5/ref/contrib/admin/>
You need an `admin.py` inside each app, where you register the models that you
want to expose to the admin site.
You might find it's best to follow a tutorial and build a simple blog (or try
and build a very simple minimal forum from scratch) to get a feel for Django
before tackling your re-write. Because trying to exactly recreate the old
functionality with legacy db tables will be a bit harder and may lead you into
patterns which are not 'good Django'.
You might also find it useful to look at the source code of an existing Django
forum app, such as this one:
<https://bitbucket.org/slav0nic/djangobb/src/>
They have just a single `djangobb_forum` app that does everything. I think
this is entirely justified as a forum is a single complicated piece of
functionality.
Note how their `Profile` model effectively extends the built-in Django
`auth.User` model via a `OneToOneField`. It makes it easier to integrate with
the built-in login and authentication system that way.
|
unable to thread multiple external scripts in python interpreter using stdin
Question: I have the following scripts The perl script(fasta.pl) takes an input
file(abc) and gives string.
$ ./fasta.pl abc.txt
I first tried
p1= subprocess.Popen(["./pdb_fasta.pl","abc.txt"],stdout=subprocess.PIPE);
then I confirmed that p1 is a file object
>>> type(p1.stdout)
<type 'file'>
I have another script, count.py that takes a file as input
$ ./count.py p1.stdout
now when I try to use the p1.stdout for this script, I get error. I tried two
different methods first one
p2= subprocess.Popen(["./count_aa.py",p1.stdout],stdout=subprocess.PIPE).stdout.read()
and the error is
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 595, in __init__
errread, errwrite)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 1106, in _execute_child
raise child_exception
TypeError: execv() arg 2 must contain only strings
second method: Here the error is because the script count_aa.py needs a file
as an argument and stdin is not providing.
>>> p2= subprocess.Popen(["./count_aa.py"],stdin=p1.stdout,stdout=subprocess.PIPE).stdout.read()
Traceback (most recent call last):
File "./count_aa.py", line 4, in <module>
fil=open(sys.argv[1],'r').read()
IndexError: list index out of range
>>>
I was thinking on this line to achieve the desired result where I pass the
output from one child process as input to another. But this does not work as
explained above.
p1= subprocess.Popen(["./pdb_fasta.pl","abc.txt"],stdout=subprocess.PIPE)
p2= subprocess.Popen(["./count_aa.py"],stdin=p1.stdout,stdout=subprocess.PIPE).stdout.read()
can some explain the mistakes here and give an example where stdin could be
useful or how to use in this scenario. Thank you so much!!
Answer: Your last code is equivalent to following shell command.
./pdb_fasta.pl abc.txt | ./count_aa.py
To make your last code to work, change `count_aa.py` to get input from stdin.
For example:
import sys
n = 0
for line in sys.stdin:
n += 1
print(n)
|
The 'import' key in Zed's Learn Python the hard way Exercise 25
Question: I'm having trouble importing my code into the python interpreter (powershell).
I open python through powershell and when I type in "import ex24" simply
nothing appears, this is using the code I copy and pasted from his site (Just
to be sure):
def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ')
return words
def sort_words(words):
"""Sorts the words."""
return sorted(words)
def print_first_word(words):
"""Prints the first word after popping it off."""
word = words.pop(0)
print word
def print_last_word(words):
"""Prints the last word after popping it off."""
word = words.pop(-1)
print word
def sort_sentence(sentence):
"""Takes in a full sentence and returns the sorted words."""
words = break_words(sentence)
return sort_words(words)
def print_first_and_last(sentence):
"""Prints the first and last words of the sentence."""
words = break_words(sentence)
print_first_word(words)
print_last_word(words)
def print_first_and_last_sorted(sentence):
"""Sorts the words then prints the first and last one."""
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
When he executes it he gets this:
>>> import ex25
>>> sentence = "All good things come to those who wait."
>>> words = ex25.break_words(sentence)
>>> words
['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait.']
>>> sorted_words = ex25.sort_words(words)
>>> sorted_words
['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']
>>> ex25.print_first_word(words)
All
>>> ex25.print_last_word(words)
wait.
>>> wrods
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'wrods' is not defined
>>> words
['good', 'things', 'come', 'to', 'those', 'who']
>>> ex25.print_first_word(sorted_words)
All
>>> ex25.print_last_word(sorted_words)
who
>>> sorted_words
['come', 'good', 'things', 'those', 'to', 'wait.']
>>> sorted_words = ex25.sort_sentence(sentence)
>>> sorted_words
['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']
>>> ex25.print_first_and_last(sentence)
All
wait.
>>> ex25.print_first_and_last_sorted(sentence)
All
who
Also, when I manually type out the code like I usually do, I get this error. I
can't to seem what mistake I made:
> > > import ex25 Traceback (most recent call last): File "", line 1, in File
> "ex25.py", line 1 SyntaxError: Non-ASCII character '\xff' in file ex25.py on
> line 1, but no encoding declared; eps/pep-0263.html for details
This is my manual copy (ex25):
def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ')
return words
def sort_words(words):
"""Sorts the words"""
return sorted (words)
def print_first_word(words):
"""Prints the first word after popping it off"""
word = words.pop(0)
print word
def print_last_word(words):
"""Prints the last word after popping it off"""
word = words.pop(-1)
print word
def sort_sentence(sentence):
"""Takes in a full sentence and returns the sorted words."""
words = break_words(sentence)
return sort_words(words)
def print_first_and_last(sentence):
"""Prints the first and last words of the sentence."""
words = break_words(sentence)
print_first_word(words)
print_last_word(words)
def print_first_and_last_sorted(sentence):
"""Sorts the words then prints the first and last one."""
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
Answer: Seems like your editor is putting a
[BOM](https://en.wikipedia.org/wiki/Byte_order_mark) at the file start. These
marks are invisible in many editors.
BOM makes no sense in UTF-8, so just **set your editor for saving in "unicode
without BOM"** or equivalent (should be somewhere in `settings` or
`preferences`).
> The byte order mark (BOM) is a Unicode character used to signal the
> endianness (byte order) of a text file or stream. It is encoded at U+FEFF
> byte order mark (BOM). BOM use is optional, and, if used, should appear at
> the start of the text stream.
In UTF-16 or UTF-32, the 16 or 32 bit units may be represented in [big-
endian](https://en.wikipedia.org/wiki/Endianess) or [little-
endian](https://en.wikipedia.org/wiki/Endianess) byte order, depending on the
platform.
Since UTF-8 is stored in bytes and bytes are the same in every platform,
signaling the endianness is useless. Why the Unicode Standard permits the BOM
in UTF-8 - and worst yet, why some editors do it if not required nor
recommended, is beyond my reach (dumb and dumber).
|
Extract and sort data from .mdb file using mdbtools in Python
Question: I'm quite new to Python, so any help will be appreciated. I am trying to
extract and sort data from 2000 .mdb files using `mdbtools` on Linux. So far I
was able to just take the .mdb file and dump all the tables into .csv. It
creates huge mess since there are lots of files that need to be processed.
What I need is to extract particular sorted data from particular table. Like
for example, I need the table called "Voltage". The table consists of numerous
cycles and each cycle has several rows also. The cycles usually go in
chronological order, but in some cases time stamp get recorded with delay.
Like cycle's one first row can have later time than cycles 1 first row. I need
to extract the latest row of the cycle based on time for the first or last
five cycles. For example, in table below, I will need the second row.
Cycle# Time Data
1 100.59 34
1 101.34 54
1 98.78 45
2
2
2 ...........
Here is the script I use. I am using the command `python extract.py
table_files.mdb.` But I would like the script to just be invoked with
./extract.py. The path to filenames should be in the script itself.
import sys, subprocess, os
DATABASE = sys.argv[1]
subprocess.call(["mdb-schema", DATABASE, "mysql"])
# Get the list of table names with "mdb-tables"
table_names = subprocess.Popen(["mdb-tables", "-1", DATABASE],
stdout=subprocess.PIPE).communicate()[0]
tables = table_names.splitlines()
print "BEGIN;" # start a transaction, speeds things up when importing
sys.stdout.flush()
# Dump each table as a CSV file using "mdb-export",
# converting " " in table names to "_" for the CSV filenames.
for table in tables:
if table != '':
filename = table.replace(" ","_") + ".csv"
file = open(filename, 'w')
print("Dumping " + table)
contents = subprocess.Popen(["mdb-export", DATABASE, table],
stdout=subprocess.PIPE).communicate()[0]
file.write(contents)
file.close()
Answer: Personally, I wouldn't spend a whole lot of time fussing around trying to get
`mdbtools`, `unixODBC` and `pyodbc` to work together. As Pedro suggested in
his comment, if you can get `mdb-export` to dump the tables to CSV files then
you'll probably save a fair bit of time by just importing those CSV files into
SQLite or MySQL, i.e., something that will be more robust than using
`mdbtools` on the Linux platform.
A few suggestions:
1. Given the sheer number of `.mdb` files (and hence `.csv` files) involved, you'll probably want to import the CSV data into one big table with an additional column to indicate the source filename. That will be much easier to manage than ~2000 separate tables.
2. When creating your target table in the new database you'll probably want to use a `decimal` (as opposed to `float`) data type for the [Time] column.
3. At the same time, rename the [Cycle#] column to just [Cycle]. "Funny characters" in column names can be a real nuisance.
Finally, to select the "last" reading (largest [Time] value) for a given
[SourceFile] and [Cycle] you can use a query something like this:
SELECT
v1.SourceFile,
v1.Cycle,
v1.Time,
v1.Data
FROM
Voltage v1
INNER JOIN
(
SELECT
SourceFile,
Cycle,
MAX([Time]) AS MaxTime
FROM Voltage
GROUP BY SourceFile, Cycle
) v2
ON v1.SourceFile=v2.SourceFile
AND v1.Cycle=v2.Cycle
AND v1.Time=v2.MaxTime
|
scikit-learn install and use
Question: I have installed WinPython-64bit-2.7.5.1
I am trying to play around with scikit - learn but when I use the code:
From sklearn.ensemble import RandomForestClassifier
I get SyntaxError: Invalid syntax inside of the Spyder coding app. Do I still
need to run all this pip stuff I read about even though I am using WinPython?
Answer:
From sklearn.ensemble import RandomForestClassifier
should be:
from sklearn.ensemble import RandomForestClassifier
"from" should be lowercase.
|
How to use list[list.index('')] queries in python
Question: I tried the following code in python IDLE. But I didn't seem to find the
elements swapped.
>>> a = [1,2,3,4,5,6,7]
>>> if(a.index(2)<a.index(4)):
... a[a.index(2)],a[a.index(4)] = a[a.index(4)],a[a.index(2)]
According to the code, It should reverse the positions of 2 and 4. Correct me
If I am wrong.
Answer: The assignment list expressions are evaluated left-to-right _while assigning_.
Here is what happens:
* The right-hand-expression is evaluated to yield `(4, 2)`
* `a[a.index(2)]` is evaluated to assign `4` to, `a[2]` is altered, the list becomes `[1, 4, 3, 4, 5, 6, 7]`
* `a[a.index(4)]` is evaluated to assign `2` to, `a[2]` is altered _again_ because that is now the first position `4` is back to `[1, 2, 3, 4, 5, 6, 7]`.
You can see this in the disassembled Python byte code:
>>> def foo():
... a = [1,2,3,4,5,6,7]
... a[a.index(2)],a[a.index(4)] = a[a.index(4)],a[a.index(2)]
...
>>> import dis
>>> dis.dis(foo)
2 0 LOAD_CONST 1 (1)
3 LOAD_CONST 2 (2)
6 LOAD_CONST 3 (3)
9 LOAD_CONST 4 (4)
12 LOAD_CONST 5 (5)
15 LOAD_CONST 6 (6)
18 LOAD_CONST 7 (7)
21 BUILD_LIST 7
24 STORE_FAST 0 (a)
3 27 LOAD_FAST 0 (a)
30 LOAD_FAST 0 (a)
33 LOAD_ATTR 0 (index)
36 LOAD_CONST 4 (4)
39 CALL_FUNCTION 1
42 BINARY_SUBSCR
43 LOAD_FAST 0 (a)
46 LOAD_FAST 0 (a)
49 LOAD_ATTR 0 (index)
52 LOAD_CONST 2 (2)
55 CALL_FUNCTION 1
58 BINARY_SUBSCR
59 ROT_TWO
60 LOAD_FAST 0 (a)
63 LOAD_FAST 0 (a)
66 LOAD_ATTR 0 (index)
69 LOAD_CONST 2 (2)
72 CALL_FUNCTION 1
75 STORE_SUBSCR
76 LOAD_FAST 0 (a)
79 LOAD_FAST 0 (a)
82 LOAD_ATTR 0 (index)
85 LOAD_CONST 4 (4)
88 CALL_FUNCTION 1
91 STORE_SUBSCR
92 LOAD_CONST 0 (None)
95 RETURN_VALUE
By instruction index 59, Python has evaluated the right-hand-side expression;
next up are the assignments. You can see that `a.index(2)` (63-72) is
evaluated first, then the `STORE_SUBSCR` stores the `4`, and only _then_
`a.index(4)` is evaluated (instructions 79-85).
The workaround is to call `.index()` _once_ for each value, and storing the
indices in variables:
index_two, index_four = a.index(2), a.index(4)
if index_two < index_four:
a[index_two], a[index_four] = a[index_four], a[index_two]
|
Python's struct.pack/unpack equivalence in C++
Question: I used struct.pack in Python to transform a data into serialized byte stream.
>>> import struct
>>> struct.pack('i', 1234)
'\xd2\x04\x00\x00'
What is the equivalence in C++?
Answer: There isn't one. C++ doesn't have built-in serialization.
You would have to write individual objects to a byte array/vector, and being
careful about [endianness](http://en.wikipedia.org/wiki/Endianness) (if you
want your code to be portable).
|
Why does the Django time zone setting effect epoch time?
Question: I have a small Django project that imports data dumps from MongoDB into MySQL.
Inside these Mongo dumps are dates stored in epoch time. I would expect epoch
time to be the same regardless of time zone but what I am seeing is that the
Django
[TIME_ZONE](https://docs.djangoproject.com/en/dev/ref/settings/#std%3asetting-
TIME_ZONE) setting has an effect on the data created in MySQL.
I have been testing my database output with the MySQL
[UNIX_TIMESTAMP](http://dev.mysql.com/doc/refman/5.1/en/date-and-time-
functions.html#function_unix-timestamp) function. If I insert a date with the
epoch of `1371131402880` (this includes milliseconds) I have my timezone set
to `'America/New_York'`, UNIX_TIMESTAMP gives me `1371131402`, which is the
same epoch time excluding milliseconds. However if I set my timezone to
`'America/Chicago'` I get `1371127802`.
This is my code to convert the epoch times into Python `datetime` objects,
from datetime import datetime
from django.utils.timezone import utc
secs = float(epochtime) / 1000.0
dt = datetime.fromtimestamp(secs)
I tried to fix the issue by putting an explict timezone on the `datetime`
object,
# epoch time is in UTC by default
dt = dt.replace(tzinfo=utc)
[PythonFiddle for the code](http://pythonfiddle.com/tests-for-epoch-issue)
I've tested this Python code in isolation and it gives me the expected
results. However it does not give the correct results after inserting these
object into MySQL through a Django model
[DateTimeField](https://docs.djangoproject.com/en/dev/ref/models/fields/#datetimefield)
field.
Here is my MySQL query,
SELECT id, `date`, UNIX_TIMESTAMP(`date`) FROM table
I test this by comparing the unix timestamp column in the result of this query
against the MongoDB JSON dumps to see if the epoch matches.
What exactly is going on here? Why should timezone have any effect on epoch
times?
Just for reference, I am using Django 1.5.1 and MySQL-python 1.2.4. I also
have the Django
[USE_TZ](https://docs.djangoproject.com/en/dev/topics/i18n/timezones/) flag
set to `true`.
Answer: I am no python or Django guru, so perhaps someone can answer better than me.
But I will take a guess at it anyway.
You said that you were storing it in a Django `DateTimeField`, which according
to [the documents you
referenced](https://docs.djangoproject.com/en/dev/ref/models/fields/#datetimefield),
stores it as a Python `datetime`.
Looking at [the docs for
`datetime`](http://docs.python.org/3.3/library/datetime.html), I think the key
is understanding the difference between "naive" and "aware" values.
And then researching further, I came across [this excellent
reference](https://docs.djangoproject.com/en/dev/topics/i18n/timezones/). Be
sure the read the second section, "Naive and aware datetime objects". That
gives a bit of context to how much of this is being controlled by Django.
Basically, by setting `USE_TZ = true`, you are asking Django to use _aware_
datetimes instead of _naive_ ones.
So then I looked back at you question. You said you were doing the following:
dt = datetime.fromtimestamp(secs)
dt = dt.replace(tzinfo=utc)
Looking at the
[fromtimestamp](http://docs.python.org/3.3/library/datetime.html#datetime.datetime.fromtimestamp)
function documentation, I found this bit of text:
> If optional argument `tz` is `None` or not specified, the `timestamp` is
> converted to the platform’s local date and time, and the returned `datetime`
> object is naive.
So I think you could do this:
dt = datetime.fromtimestamp(secs, tz=utc)
Then again, right below that function, the docs show `utcfromtimestamp`
function, so maybe it should be:
dt = datetime.utcfromtimestamp(secs)
I don't know enough about python to know if these are equivalent or not, but
you could try and see if either makes a difference.
Hopefully one of these will make a difference. If not, please let me know. I'm
intimately familiar with date/time in JavaScript and in .Net, but I'm always
interested in how these nuances play out differently in other platforms, such
as Python.
## Update
Regarding the MySQL portion of the question, take a look at [this
fiddle](http://sqlfiddle.com/#!2/bbcfa/1).
CREATE TABLE foo (`date` DATETIME);
INSERT INTO foo (`date`) VALUES (FROM_UNIXTIME(1371131402));
SET TIME_ZONE="+00:00";
select `date`, UNIX_TIMESTAMP(`date`) from foo;
SET TIME_ZONE="+01:00";
select `date`, UNIX_TIMESTAMP(`date`) from foo;
Results:
DATE UNIX_TIMESTAMP(`DATE`)
June, 13 2013 13:50:02+0000 1371131402
June, 13 2013 13:50:02+0000 1371127802
It would seem that the behavior of `UNIX_TIMESTAMP` function is indeed
affected by the MySQL `TIME_ZONE` setting. That's not so surprising, since
it's in the documentation. What's surprising is that the string output of the
`datetime` has the same UTC value regardless of the setting.
Here's what I think is happening. In the docs for the `UNIX_TIMESTAMP`
function, it says:
> `date` may be a `DATE` string, a `DATETIME` string, a `TIMESTAMP`, or a
> number in the format `YYMMDD` or `YYYYMMDD`.
Note that it doesn't say that it can be a `DATETIME` \- it says it can be a
`DATETIME` **_string_**. So I think the actual value being implicitly
converted to a string before being passed into the function.
So now look at [this updated fiddle](http://sqlfiddle.com/#!2/bbcfa/2) that
converts explicitly.
SET TIME_ZONE="+00:00";
select `date`, convert(`date`, char), UNIX_TIMESTAMP(convert(`date`, char)) from foo;
SET TIME_ZONE="+01:00";
select `date`, convert(`date`, char), UNIX_TIMESTAMP(convert(`date`, char)) from foo;
Results:
DATE CONVERT(`DATE`, CHAR) UNIX_TIMESTAMP(CONVERT(`DATE`, CHAR))
June, 13 2013 13:50:02+0000 2013-06-13 13:50:02 1371131402
June, 13 2013 13:50:02+0000 2013-06-13 13:50:02 1371127802
You can see that when it converts to character data, it strips away the
offset. So of course, it makes sense now that when `UNIX_TIMESTAMP` takes this
value as input, it is assuming the local time zone setting and thus getting a
different UTC timestamp.
Not sure if this will help you or not. You need to dig more into exactly how
Django is calling MySQL for both the read and the write. Does it actually use
the `UNIX_TIMESTAMP` function? Or was that just what you did in testing?
|
Python Request Module - Google App Engine
Question: I'm trying to import the requests module for my app which I want to view
locally on Google App Engine. I am getting a log console error telling me that
"no such module exists".
I've installed it in the command line (using `pip`) and even tried to install
it in my project directory. When I do that the shell tells me:
> "Requirement already satisfied (use --upgrade to upgrade): requests in
> /Library/Python/2.7/site-packages".
App Engine is telling me that the module doesn't exist and the shell says it's
already installed it.
I don't know if this is a path problem. If so, the only App Engine related
application I can find in my mac is the launcher?
Answer: You need to put the requests module i.e. [the contents of the requests
folder](https://github.com/kennethreitz/requests/tree/master/requests) within
your project directory. Just for the sake of clarity, your app directory
should look like
/myapp/app.yaml
/myapp/main.py
/myapp/requests/packages/
/myapp/requests/__init__.py
/myapp/requests/adapters.py
etc...
then within main.py put something like
import webapp2
import requests
class MainHandler(webapp2.RequestHandler):
def get(self):
g = requests.get('http://www.google.com')
self.response.write(g.text)
app = webapp2.WSGIApplication([
('/', MainHandler)
], debug=True)
|
Deleting text from an edit control in Python 2.7?
Question: How can I program the example below to delete all contents from the Edit box?
(this is example is taken from <http://www.java2s.com/Code/Python/GUI-
Tk/SimpleEditor.htm>)
My guess is that one must select all the contents and then do some sort of
`.tag_remove(SEL, '1.0', END)` but I can't find the commands to program it to
select all the text.
from Tkinter import *
from tkSimpleDialog import askstring
from tkFileDialog import asksaveasfilename
from tkMessageBox import askokcancel
class Quitter(Frame):
def __init__(self, parent=None):
Frame.__init__(self, parent)
self.pack()
widget = Button(self, text='Quit', command=self.quit)
widget.pack(expand=YES, fill=BOTH, side=LEFT)
def quit(self):
ans = askokcancel('Verify exit', "Really quit?")
if ans: Frame.quit(self)
class ScrolledText(Frame):
def __init__(self, parent=None, text='', file=None):
Frame.__init__(self, parent)
self.pack(expand=YES, fill=BOTH)
self.makewidgets()
self.settext(text, file)
def makewidgets(self):
sbar = Scrollbar(self)
text = Text(self, relief=SUNKEN)
sbar.config(command=text.yview)
text.config(yscrollcommand=sbar.set)
sbar.pack(side=RIGHT, fill=Y)
text.pack(side=LEFT, expand=YES, fill=BOTH)
self.text = text
def settext(self, text='', file=None):
if file:
text = open(file, 'r').read()
self.text.delete('1.0', END)
self.text.insert('1.0', text)
self.text.mark_set(INSERT, '1.0')
self.text.focus()
def gettext(self):
return self.text.get('1.0', END+'-1c')
class SimpleEditor(ScrolledText):
def __init__(self, parent=None, file=None):
frm = Frame(parent)
frm.pack(fill=X)
Button(frm, text='Save', command=self.onSave).pack(side=LEFT)
Button(frm, text='Cut', command=self.onCut).pack(side=LEFT)
Button(frm, text='Paste', command=self.onPaste).pack(side=LEFT)
Button(frm, text='Find', command=self.onFind).pack(side=LEFT)
Quitter(frm).pack(side=LEFT)
ScrolledText.__init__(self, parent, file=file)
self.text.config(font=('courier', 9, 'normal'))
def onSave(self):
filename = asksaveasfilename()
if filename:
alltext = self.gettext()
open(filename, 'w').write(alltext)
def onCut(self):
text = self.text.get(SEL_FIRST, SEL_LAST)
self.text.delete(SEL_FIRST, SEL_LAST)
self.clipboard_clear()
self.clipboard_append(text)
def onPaste(self):
try:
text = self.selection_get(selection='CLIPBOARD')
self.text.insert(INSERT, text)
except TclError:
pass
def onFind(self):
target = askstring('SimpleEditor', 'Search String?')
if target:
where = self.text.search(target, INSERT, END)
if where:
print where
pastit = where + ('+%dc' % len(target))
#self.text.tag_remove(SEL, '1.0', END)
self.text.tag_add(SEL, where, pastit)
self.text.mark_set(INSERT, pastit)
self.text.see(INSERT)
self.text.focus()
if __name__ == '__main__':
try:
SimpleEditor(file=sys.argv[1]).mainloop()
except IndexError:
SimpleEditor().mainloop()
Answer: The text widget has a `delete` method, which you can use to delete characters.
You don't need to select the characters first.
If you want to delete all of the text, just do:
self.text.delete("1.0", "end")
(you can also use a tkinter constant instead of the string `"end"`, but I
don't see the point)
|
AndroidViewClient: content is not allowed in trailing section
Question: I installed AndroidViewClient via Git on my Windows Vista machine at home and
I setup the path variables and ran the check-imports.py script to make sure
everything was ok. Next, I tried to run the settings.py script from the
/examples folder and got the following error:
C:\Users\Allen>monkeyrunner C:\Users\Allen\AndroidViewClient\AndroidViewClient\e
xamples\settings.py
130615 22:24:56.666:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions
] Script terminated due to an exception
130615 22:24:56.666:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions
]Traceback (most recent call last):
File "C:\Users\Allen\AndroidViewClient\AndroidViewClient\examples\settings.py"
, line 49, in <module>
vc = ViewClient(device, serialno)
File "C:\Users\Allen\AndroidViewClient\AndroidViewClient\src\com\dtmilano\andr
oid\viewclient.py", line 1188, in __init__
self.dump()
File "C:\Users\Allen\AndroidViewClient\AndroidViewClient\src\com\dtmilano\andr
oid\viewclient.py", line 1766, in dump
self.setViewsFromUiAutomatorDump(received)
File "C:\Users\Allen\AndroidViewClient\AndroidViewClient\src\com\dtmilano\andr
oid\viewclient.py", line 1530, in setViewsFromUiAutomatorDump
self.__parseTreeFromUiAutomatorDump(received)
File "C:\Users\Allen\AndroidViewClient\AndroidViewClient\src\com\dtmilano\andr
oid\viewclient.py", line 1688, in _ViewClient__parseTreeFromUiAutomatorDump
self.root = parser.Parse(receivedXml)
File "C:\Users\Allen\AndroidViewClient\AndroidViewClient\src\com\dtmilano\andr
oid\viewclient.py", line 988, in Parse
parserStatus = parser.Parse(uiautomatorxml, 1)
File "C:\Users\Allen\android-sdks\tools\lib\jython-standalone-2.5.3.jar\Lib\xm
l\parsers\expat.py", line 212, in Parse
xml.parsers.expat.ExpatError: Content is not allowed in trailing section.
I can't seem to figure out what the error is. I tried deleting the
AndroidViewClient folder and re-downloading everything, but I still get the
same error. Any ideas what the issue could be?
EDIT: this is the output after turning the DEBUG and DEBUG_RECEIVED FLAGS on
in viewclient.py
checkable="false" checked="false" clickable="true" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="true" password="false" selected="false" bounds="[1022,712][2258,840]"><node index="0" text="" class="android.widget.LinearLayout" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[1038,712][1150,840]" /><node index="1" text="" class="android.widget.RelativeLayout" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[1150,720][2110,831]"><node index="0" text="asgqa2" class="android.widget.TextView" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[1150,732][1269,781]" /><node index="1" text="Secured with WPA" class="android.widget.TextView" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[1150,781][1379,819]" /></node><node index="2" text="" class="android.widget.LinearLayout" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[2110,712][2238,840]"><node index="0" text="" class="android.widget.ImageView" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[2142,744][2206,808]" /></node></node><node index="4" text="" class="android.widget.LinearLayout" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="true" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="true" password="false" selected="false" bounds="[1022,842][2258,970]"><node index="0" text="" class="android.widget.LinearLayout" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[1038,842][1150,970]" /><node index="1" text="" class="android.widget.RelativeLayout" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[1150,850][2110,961]"><node index="0" text="CEAudit" class="android.widget.TextView" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[1150,862][1276,911]" /><node index="1" text="Secured with WPA2 (WPS available)" class="android.widget.TextView" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[1150,911][1598,949]" /></node><node index="2" text="" class="android.widget.LinearLayout" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[2110,842][2238,970]"><node index="0" text="" class="android.widget.ImageView" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[2142,874][2206,938]" /></node></node><node index="5" text="" class="android.widget.LinearLayout" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="true" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="true" password="false" selected="false" bounds="[1022,972][2258,1100]"><node index="0" text="" class="android.widget.LinearLayout" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[1038,972][1150,1100]" /><node index="1" text="" class="android.widget.RelativeLayout" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[1150,980][2110,1091]"><node index="0" text="asgqa3" class="android.widget.TextView" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[1150,992][1269,1041]" /><node index="1" text="Secured with WPA" class="android.widget.TextView" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[1150,1041][1379,1079]" /></node><node index="2" text="" class="android.widget.LinearLayout" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[2110,972][2238,1100]"><node index="0" text="" class="android.widget.ImageView" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[2142,1004][2206,1068]" /></node></node><node index="6" text="" class="android.widget.LinearLayout" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="true" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="true" password="false" selected="false" bounds="[1022,1102][2258,1230]"><node index="0" text="" class="android.widget.LinearLayout" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[1038,1102][1150,1230]" /><node index="1" text="" class="android.widget.RelativeLayout" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[1150,1110][2110,1221]"><node index="0" text="asgqa" class="android.widget.TextView" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[1150,1122][1249,1171]" /><node index="1" text="Secured with WPA" class="android.widget.TextView" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[1150,1171][1379,1209]" /></node><node index="2" text="" class="android.widget.LinearLayout" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[2110,1102][2238,1230]"><node index="0" text="" class="android.widget.ImageView" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[2142,1134][2206,1198]" /></node></node><node index="7" text="" class="android.widget.LinearLayout" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="true" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="true" password="false" selected="false" bounds="[1022,1232][2258,1360]"><node index="0" text="" class="android.widget.LinearLayout" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[1038,1232][1150,1360]" /><node index="1" text="" class="android.widget.RelativeLayout" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[1150,1240][2110,1351]"><node index="0" text="hs-dlink" class="android.widget.TextView" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[1150,1252][1281,1301]" /><node index="1" text="Secured with WPA/WPA2 (WPS available)" class="android.widget.TextView" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[1150,1301][1669,1339]" /></node><node index="2" text="" class="android.widget.LinearLayout" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[2110,1232][2238,1360]"><node index="0" text="" class="android.widget.ImageView" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[2142,1264][2206,1328]" /></node></node><node index="8" text="" class="android.widget.LinearLayout" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="true" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="true" password="false" selected="false" bounds="[1022,1362][2258,1490]"><node index="0" text="" class="android.widget.LinearLayout" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[1038,1362][1150,1490]" /><node index="1" text="" class="android.widget.RelativeLayout" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[1150,1370][2110,1481]"><node index="0" text="ASUS" class="android.widget.TextView" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[1150,1382][1241,1431]" /><node index="1" text="Secured with WPA2 (WPS available)" class="android.widget.TextView" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[1150,1431][1598,1469]" /></node><node index="2" text="" class="android.widget.LinearLayout" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[2110,1362][2238,1490]"><node index="0" text="" class="android.widget.ImageView" package="com.android.settings" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[2142,1394][2206,1458]" /></node></node></node></node></node></node></node></node></node></node></node></hierarchy>Killed
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] Script terminated due to an exception
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions]Traceback (most recent call last):
File "/home/allen/projects/AndroidViewClient/AndroidViewClient/examples/settings.py", line 49, in <module>
vc = ViewClient(device, serialno)
File "/home/allen/projects/AndroidViewClient/AndroidViewClient/src/com/dtmilano/android/viewclient.py", line 1153, in __init__
self.dump()
File "/home/allen/projects/AndroidViewClient/AndroidViewClient/src/com/dtmilano/android/viewclient.py", line 1731, in dump
self.setViewsFromUiAutomatorDump(received)
File "/home/allen/projects/AndroidViewClient/AndroidViewClient/src/com/dtmilano/android/viewclient.py", line 1495, in setViewsFromUiAutomatorDump
self.__parseTreeFromUiAutomatorDump(received)
File "/home/allen/projects/AndroidViewClient/AndroidViewClient/src/com/dtmilano/android/viewclient.py", line 1653, in _ViewClient__parseTreeFromUiAutomatorDump
self.root = parser.Parse(receivedXml)
File "/home/allen/projects/AndroidViewClient/AndroidViewClient/src/com/dtmilano/android/viewclient.py", line 953, in Parse
parserStatus = parser.Parse(uiautomatorxml, 1)
File "/home/allen/android/android-sdks/tools/lib/jython-standalone-2.5.3.jar/Lib/xml/parsers/expat.py", line 212, in Parse
xml.parsers.expat.ExpatError: Content is not allowed in trailing section.
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyException.fillInStackTrace(PyException.java:70)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at java.lang.Throwable.<init>(Throwable.java:181)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at java.lang.Exception.<init>(Exception.java:29)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at java.lang.RuntimeException.<init>(RuntimeException.java:32)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyException.<init>(PyException.java:46)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyException.doRaise(PyException.java:219)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.Py.makeException(Py.java:1239)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.Py.makeException(Py.java:1243)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.Py.makeException(Py.java:1247)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at xml.parsers.expat$py.Parse$14(/home/allen/android/android-sdks/tools/lib/jython-standalone-2.5.3.jar/Lib/xml/parsers/expat.py:213)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at xml.parsers.expat$py.call_function(/home/allen/android/android-sdks/tools/lib/jython-standalone-2.5.3.jar/Lib/xml/parsers/expat.py)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyTableCode.call(PyTableCode.java:165)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyBaseCode.call(PyBaseCode.java:166)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyFunction.__call__(PyFunction.java:338)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyMethod.__call__(PyMethod.java:139)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at com.dtmilano.android.viewclient$py.Parse$54(/home/allen/projects/AndroidViewClient/AndroidViewClient/src/com/dtmilano/android/viewclient.py:954)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at com.dtmilano.android.viewclient$py.call_function(/home/allen/projects/AndroidViewClient/AndroidViewClient/src/com/dtmilano/android/viewclient.py)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyTableCode.call(PyTableCode.java:165)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyBaseCode.call(PyBaseCode.java:149)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyFunction.__call__(PyFunction.java:327)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyMethod.__call__(PyMethod.java:124)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at com.dtmilano.android.viewclient$py._ViewClient__parseTreeFromUiAutomatorDump$81(/home/allen/projects/AndroidViewClient/AndroidViewClient/src/com/dtmilano/android/viewclient.py:1654)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at com.dtmilano.android.viewclient$py.call_function(/home/allen/projects/AndroidViewClient/AndroidViewClient/src/com/dtmilano/android/viewclient.py)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyTableCode.call(PyTableCode.java:165)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyBaseCode.call(PyBaseCode.java:149)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyFunction.__call__(PyFunction.java:327)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyMethod.__call__(PyMethod.java:124)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at com.dtmilano.android.viewclient$py.setViewsFromUiAutomatorDump$78(/home/allen/projects/AndroidViewClient/AndroidViewClient/src/com/dtmilano/android/viewclient.py:1497)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at com.dtmilano.android.viewclient$py.call_function(/home/allen/projects/AndroidViewClient/AndroidViewClient/src/com/dtmilano/android/viewclient.py)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyTableCode.call(PyTableCode.java:165)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyBaseCode.call(PyBaseCode.java:149)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyFunction.__call__(PyFunction.java:327)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyMethod.__call__(PyMethod.java:124)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at com.dtmilano.android.viewclient$py.dump$84(/home/allen/projects/AndroidViewClient/AndroidViewClient/src/com/dtmilano/android/viewclient.py:1794)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at com.dtmilano.android.viewclient$py.call_function(/home/allen/projects/AndroidViewClient/AndroidViewClient/src/com/dtmilano/android/viewclient.py)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyTableCode.call(PyTableCode.java:165)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyBaseCode.call(PyBaseCode.java:301)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyBaseCode.call(PyBaseCode.java:127)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyFunction.__call__(PyFunction.java:317)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyMethod.__call__(PyMethod.java:109)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at com.dtmilano.android.viewclient$py.__init__$62(/home/allen/projects/AndroidViewClient/AndroidViewClient/src/com/dtmilano/android/viewclient.py:1153)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at com.dtmilano.android.viewclient$py.call_function(/home/allen/projects/AndroidViewClient/AndroidViewClient/src/com/dtmilano/android/viewclient.py)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyTableCode.call(PyTableCode.java:165)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyBaseCode.call(PyBaseCode.java:301)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyBaseCode.call(PyBaseCode.java:194)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyFunction.__call__(PyFunction.java:387)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyFunction.__call__(PyFunction.java:381)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyInstance.__init__(PyInstance.java:120)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyClass.__call__(PyClass.java:194)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyObject.__call__(PyObject.java:404)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyObject.__call__(PyObject.java:408)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.pycode._pyx0.f$0(/home/allen/projects/AndroidViewClient/AndroidViewClient/examples/settings.py:66)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.pycode._pyx0.call_function(/home/allen/projects/AndroidViewClient/AndroidViewClient/examples/settings.py)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyTableCode.call(PyTableCode.java:165)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyCode.call(PyCode.java:18)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.Py.runCode(Py.java:1275)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.__builtin__.execfile_flags(__builtin__.java:522)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.util.PythonInterpreter.execfile(PythonInterpreter.java:225)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at com.android.monkeyrunner.ScriptRunner.run(ScriptRunner.java:116)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at com.android.monkeyrunner.MonkeyRunnerStarter.run(MonkeyRunnerStarter.java:77)
130617 10:20:00.138:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] at com.android.monkeyrunner.MonkeyRunnerStarter.main(MonkeyRunnerStarter.java:189)
Answer: Hmm I reset my device to factory settings and suddenly it works ok :o
EDIT: I figured out what the issue was. I'm trying to automate the CTS testing
and when the Delegating Accessibility Testing Service is enabled, it somehow
causes AndroidViewClient to fail after that point in the script and on
monkeyrunner executions for other scripts. Turning it off allows any script
using AndroidViewClient to behave normally again...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.