text
stringlengths 226
34.5k
|
---|
How to capture stdout output from a Python function call?
Question: I'm using a Python library that does something to an object
do_something(my_object)
and changes it. While doing so, it prints some statistics to stdout, and I'd
like to get a grip on this information. The proper solution would be to change
`do_something()` to return the relevant information,
out = do_something(my_object)
but it will be a while before the devs of `do_something()` get to this issue.
As a workaround, I thought about parsing whatever `do_something()` writes to
stdout.
How can I capture stdout output between two points in the code, e.g.,
start_capturing()
do_something(my_object)
out = end_capturing()
?
Answer: Try this context manager:
from cStringIO import StringIO
import sys
class Capturing(list):
def __enter__(self):
self._stdout = sys.stdout
sys.stdout = self._stringio = StringIO()
return self
def __exit__(self, *args):
self.extend(self._stringio.getvalue().splitlines())
sys.stdout = self._stdout
Usage:
with Capturing() as output:
do_something(my_object)
`output` is now a list containing the lines printed by the function call.
Advanced usage:
What may not be obvious is that this can be done more than once and the
results concatenated:
with Capturing() as output:
print 'hello world'
print 'displays on screen'
with Capturing(output) as output: # note the constructor argument
print 'hello world2'
print 'done'
print 'output:', output
Output:
displays on screen
done
output: ['hello world', 'hello world2']
|
How to get the top 10 students in the class using Python dict
Question: I have a dictionary with student-name and marks
dict1 = {'name1': 34, 'name2':45, 'name3': 98, 'name4':34, 'name5': 66}
I want to get the top 10 student names along with their marks from the above
dict.
**Result:**
name3 98
name5 66
name2 45
name1 34
name4 34
In case of multiple keys for same values, keys must be in alphabetical order
(Ex: name1 and name4 are in alphabetical order for same value 34)
How to get it done ?
Answer: Use
[`heapq.nlargest()`](http://docs.python.org/2/library/heapq.html#heapq.nlargest):
from heapq import nlargest
from operator import itemgetter
for name, score in nlargest(10, dictionary.iteritems(), key=itemgetter(1)):
print name, score
Demo:
>>> for name, score in nlargest(10, dictionary.iteritems(), key=itemgetter(1)):
... print name, score
...
name3 98
name5 66
name2 45
name4 34
name1 34
Note that because your sample dictionary is _smaller_ than the top `n` you
want, you could just as well have used `sorted()`:
for name, score in sorted(dictionary.iteritems(), key=itemgetter(1), reverse=True):
print name, score
but for any top `n` where `n` is smaller than `len(dictionary)` `heapq` is the
better choice.
Alternatively, use a `collections.Counter()` object, it has a `.most_common()`
method that gives you exactly that; the highest `n` scoring elements in the
counter:
>>> scores = Counter(dictionary)
>>> scores
Counter({'name3': 98, 'name5': 66, 'name2': 45, 'name4': 34, 'name1': 34})
>>> scores.most_common(3)
[('name3', 98), ('name5', 66), ('name2', 45)]
|
import error when cross importing django/python
Question: Hi all can anyone help me with this I am having import error when I do an
import I think its all clashing.all was fine till I imported B because I
really need to make a ForeignKey to B from A.
a/models.py
from b.models import B #there is the problem
Class A():
....
b = models.ForeignKey(B) # I really have to do this
b/models.py
from c.models import C
Class B():
....
c = models.ForeignKey(C)
c/models.py
from a.models import A
Class C():
a = models.ForeignKey(A)
Answer: You can do this (not import model B, just type a string in format
"app_name.model_name")
a/models.py
Class A():
....
b = models.ForeignKey("b.B")
[ForeignKey
docs](https://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey)
|
python - splitting a string without removing delimiters
Question: I'm trying to split a string without removing the delimiter and having trouble
doing so. The string I want to split is:
'+ {- 9 4} {+ 3 2}'
and I want to end up with
['+', '{- 9 4}', '{+ 3 2}']
yet everything I've tried hasn't worked. I was looking through this
stackoverflow post for answers as well as google: [Python split() without
removing the delimiter](http://stackoverflow.com/questions/7866128/python-
split-without-removing-the-delimiter)
Thanks!
Answer: re.split will keep the delimiters when they are captured, i.e., enclosed in
parentheses:
import re
s = '+ {- 9 4} {+ 3 2}'
p = filter(lambda x: x.strip() != '', re.split("([+{} -])", s))
will give you
['+', '{', '-', '9', '4', '}', '{', '+', '3', '2', '}']
which, IMO, is what you need to handle nested expressions
|
numpy genfromtxt issues in Python3
Question: I'm trying to use `genfromtxt` with Python3 to read a simple _csv_ file
containing strings and numbers. For example, something like (hereinafter
"test.csv"):
1,a
2,b
3,c
with Python2, the following works well:
import numpy
data=numpy.genfromtxt("test.csv", delimiter=",", dtype=None)
# Now data is something like [(1, 'a') (2, 'b') (3, 'c')]
in Python3 the same code returns `[(1, b'a') (2, b'b') (3, b'c')]`. This is
somehow [expected](http://docs.python.org/3.0/whatsnew/3.0.html#text-vs-data-
instead-of-unicode-vs-8-bit) due to the different way Python3 reads the files.
Therefore I use a converter to decode the strings:
decodef = lambda x: x.decode("utf-8")
data=numpy.genfromtxt("test.csv", delimiter=",", dtype="f8,S8", converters={1: decodef})
This works with Python2, but not with Python3 (same `[(1, b'a') (2, b'b') (3,
b'c')]` output. However, if in Python3 I use the code above to read only one
column:
data=numpy.genfromtxt("test.csv", delimiter=",", usecols=(1,), dtype="S8", converters={1: decodef})
the output strings are `['a' 'b' 'c']`, already decoded as expected.
I've also tried to provide the file as the output of an `open` with the `'rb'`
mode, as suggested at [this link](http://www.gossamer-
threads.com/lists/python/python/978888), but there are no improvements.
Why the converter works when only one column is read, and not when two columns
are read? Could you please suggest me the correct way to use `genfromtxt` in
Python3? Am I doing something wrong? Thank you in advance!
Answer: The answer to my problem is using the `dtype` for unicode strings (`U2`, for
example).
Thanks to the answer of E.Kehler, I found the solution. If I use `str` in
place of `S8` in the `dtype` definition, then the output for the 2nd column is
empty:
numpy.genfromtxt("test.csv", delimiter=",", dtype='f8,str')
the output is:
array([(1.0, ''), (2.0, ''), (3.0, '')], dtype=[('f0', '<f16'), ('f1', '<U0')])
This suggested me that correct `dtype` to solve my problem is an unicode
string:
numpy.genfromtxt("test.csv", delimiter=",", dtype='f8,U2')
that gives the expected output:
array([(1.0, 'a'), (2.0, 'b'), (3.0, 'c')], dtype=[('f0', '<f16'), ('f1', '<U2')])
Useful information can be also found at [the numpy datatype doc
page](http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html) .
|
Python - tokenizing, replacing words
Question: I'm trying to create something like sentences with random words put into them.
To be specific, I'd have something like:
"The weather today is [weather_state]."
and to be able to do something like finding all tokens in [brackets] and than
exchange them for a randomized counterpart from a dictionary or a list,
leaving me with:
"The weather today is warm."
"The weather today is bad."
or
"The weather today is mildly suiting for my old bones."
Keep in mind, that the position of the [bracket] token wouldn't be always in
the same position and there would be multiple bracketed tokens in my string,
like:
"[person] is feeling really [how] today, so he's not going [where]."
I really don't know where to start with this or is this even the best solution
to use tokenize or token modules with this. Any hints that would point me in
the right direction greatly appreciated!
EDIT: Just for clarification, I don't really need to use square brackets, any
non-standard character will do.
Answer: You're looking for re.sub with a callback function:
words = {
'person': ['you', 'me'],
'how': ['fine', 'stupid'],
'where': ['away', 'out']
}
import re, random
def random_str(m):
return random.choice(words[m.group(1)])
text = "[person] is feeling really [how] today, so he's not going [where]."
print re.sub(r'\[(.+?)\]', random_str, text)
#me is feeling really stupid today, so he's not going away.
Note that unlike the `format` method, this allows for more sophisticated
processing of placeholders, e.g.
[person:upper] got $[amount if amount else 0] etc
Basically, you can build your own "templating engine" on top of that.
|
python matplotlib giving peak position value
Question: I have two arrays which came from scripting. The two arrays are given below-
x = array([ 0.35970013, 0.36476619, 0.36983225, 0.3748983 , 0.37996435,
0.38503039, 0.39009642, 0.39516245, 0.40022847, 0.40529448,
0.41036049, 0.4154265 , 0.42049249, 0.42555848, 0.43062447,
0.43569044, 0.44075641, 0.44582237, 0.45088833, 0.45595428,
0.46102022, 0.46608615, 0.47115208, 0.476218 , 0.48128391,
0.48634982, 0.49141572, 0.49648161, 0.50154749, 0.50661336,
0.51167923, 0.51674509, 0.52181094, 0.52687678, 0.53194261,
0.53700844, 0.54207425, 0.54714006, 0.55220586, 0.55727165,
0.56233744, 0.56740321, 0.57246897, 0.57753473, 0.58260048,
0.58766622, 0.59273194, 0.59779766, 0.60286337, 0.60792907,
0.61299477, 0.61806045, 0.62312612, 0.62819178, 0.63325743,
0.63832308, 0.64338871, 0.64845433, 0.65351995, 0.65858555,
0.66365114, 0.66871672, 0.67378229, 0.67884785, 0.6839134 ,
0.68897894, 0.69404447, 0.69910999, 0.7041755 , 0.70924099,
0.71430648, 0.71937195, 0.72443741, 0.72950287, 0.73456831,
0.73963373, 0.74469915, 0.74976456, 0.75482995, 0.75989533,
0.7649607 , 0.77002606, 0.77509141, 0.78015674, 0.78522206,
0.79028737, 0.79535267, 0.80041795, 0.80548322, 0.81054848,
0.81561373, 0.82067897, 0.82574419, 0.8308094 , 0.83587459,
0.84093977, 0.84600494, 0.8510701 , 0.85613524, 0.86120037,
0.86626549, 0.87133059, 0.87639568, 0.88146075, 0.88652582,
0.89159086, 0.8966559 , 0.90172092, 0.90678592, 0.91185092,
0.91691589, 0.92198086, 0.9270458 , 0.93211074, 0.93717566,
0.94224056, 0.94730545, 0.95237033, 0.95743519, 0.96250004,
0.96756487, 0.97262968, 0.97769448, 0.98275927, 0.98782404,
0.99288879, 0.99795353, 1.00301826, 1.00808296, 1.01314766,
1.01821233, 1.02327699, 1.02834164, 1.03340627, 1.03847088,
1.04353547, 1.04860005, 1.05366462, 1.05872916, 1.06379369,
1.06885821, 1.07392271, 1.07898719, 1.08405165, 1.0891161 ,
1.09418053, 1.09924494, 1.10430933, 1.10937371, 1.11443807,
1.11950242, 1.12456674, 1.12963105, 1.13469534, 1.13975962,
1.14482387, 1.14988811, 1.15495233, 1.16001653, 1.16508071,
1.17014488, 1.17520903, 1.18027315, 1.18533727, 1.19040136,
1.19546543, 1.20052949, 1.20559352, 1.21065754, 1.21572154,
1.22078552, 1.22584948, 1.23091342, 1.23597734, 1.24104124,
1.24610512, 1.25116899, 1.25623283, 1.26129666, 1.26636046,
1.27142425, 1.27648801, 1.28155176, 1.28661548, 1.29167919,
1.29674288, 1.30180654, 1.30687019, 1.31193381, 1.31699741,
1.322061 , 1.32712456, 1.3321881 , 1.33725162, 1.34231512,
1.3473786 , 1.35244206, 1.3575055 , 1.36256892, 1.36763231,
1.37269568, 1.37775904, 1.38282237, 1.38788568, 1.39294896,
1.39801223, 1.40307547, 1.4081387 , 1.4132019 , 1.41826508,
1.42332823, 1.42839137, 1.43345448, 1.43851757, 1.44358063,
1.44864368, 1.4537067 , 1.4587697 , 1.46383267, 1.46889563,
1.47395856, 1.47902147, 1.48408435, 1.48914721, 1.49421005,
1.49927286, 1.50433566, 1.50939842, 1.51446117, 1.51952389,
1.52458659, 1.52964926, 1.53471191, 1.53977454, 1.54483714,
1.54989971, 1.55496227, 1.5600248 , 1.5650873 , 1.57014978,
1.57521224, 1.58027467, 1.58533708, 1.59039946, 1.59546182,
1.60052415, 1.60558646, 1.61064874, 1.61571099, 1.62077323,
1.62583543, 1.63089761, 1.63595977, 1.6410219 , 1.64608401,
1.65114609, 1.65620814, 1.66127017, 1.66633217, 1.67139414,
1.67645609, 1.68151802, 1.68657992, 1.69164179, 1.69670363,
1.70176545, 1.70682724, 1.71188901, 1.71695074, 1.72201246,
1.72707414, 1.7321358 , 1.73719743, 1.74225903, 1.74732061,
1.75238216, 1.75744368, 1.76250518, 1.76756664, 1.77262808,
1.7776895 , 1.78275088, 1.78781224, 1.79287357, 1.79793487,
1.80299614, 1.80805738, 1.8131186 , 1.81817979, 1.82324095,
1.82830208, 1.83336318, 1.83842426, 1.8434853 , 1.84854632,
1.85360731, 1.85866827, 1.8637292 , 1.8687901 , 1.87385097,
1.87891182, 1.88397263, 1.88903341, 1.89409417, 1.89915489,
1.90421559, 1.90927626, 1.91433689, 1.9193975 , 1.92445808,
1.92951862, 1.93457914, 1.93963963, 1.94470008, 1.94976051,
1.9548209 , 1.95988127, 1.9649416 , 1.97000191, 1.97506218,
1.98012242, 1.98518264, 1.99024282, 1.99530297, 2.00036308,
2.00542317, 2.01048323, 2.01554325, 2.02060325, 2.02566321,
2.03072314, 2.03578304, 2.0408429 , 2.04590274, 2.05096254,
2.05602232, 2.06108205, 2.06614176, 2.07120144, 2.07626108,
2.08132069, 2.08638027, 2.09143981, 2.09649933, 2.10155881,
2.10661826, 2.11167767, 2.11673705, 2.1217964 , 2.12685572,
2.131915 , 2.13697425, 2.14203347, 2.14709265, 2.1521518 ,
2.15721091, 2.16227 , 2.16732905, 2.17238806, 2.17744704,
2.18250599, 2.1875649 , 2.19262378, 2.19768263, 2.20274144,
2.20780021, 2.21285896, 2.21791766, 2.22297634, 2.22803498,
2.23309358, 2.23815215, 2.24321068, 2.24826918, 2.25332765,
2.25838607, 2.26344447, 2.26850283, 2.27356115, 2.27861944,
2.28367769, 2.28873591, 2.29379409, 2.29885224, 2.30391035,
2.30896842, 2.31402646, 2.31908446, 2.32414242, 2.32920035,
2.33425825, 2.3393161 , 2.34437393, 2.34943171, 2.35448946,
2.35954717, 2.36460484, 2.36966248, 2.37472008, 2.37977764,
2.38483517, 2.38989266, 2.39495011, 2.40000753, 2.4050649 ,
2.41012224, 2.41517955, 2.42023681, 2.42529404, 2.43035123,
2.43540838, 2.44046549, 2.44552257, 2.45057961, 2.45563661,
2.46069357, 2.46575049, 2.47080738, 2.47586422, 2.48092103,
2.4859778 , 2.49103453, 2.49609122, 2.50114787, 2.50620449,
2.51126106, 2.5163176 , 2.52137409, 2.52643055, 2.53148697,
2.53654335, 2.54159969, 2.54665599, 2.55171225, 2.55676847,
2.56182465, 2.56688079, 2.57193689, 2.57699295, 2.58204897,
2.58710495, 2.59216089, 2.59721679, 2.60227265, 2.60732847,
2.61238425, 2.61743999, 2.62249568, 2.62755134, 2.63260695,
2.63766253, 2.64271806, 2.64777355, 2.65282901, 2.65788441,
2.66293978, 2.66799511, 2.6730504 , 2.67810564, 2.68316084,
2.688216 , 2.69327112, 2.6983262 , 2.70338123, 2.70843623,
2.71349118, 2.71854608, 2.72360095, 2.72865577, 2.73371056,
2.73876529, 2.74381999, 2.74887464, 2.75392925, 2.75898382,
2.76403835, 2.76909283, 2.77414727, 2.77920166, 2.78425602,
2.78931033, 2.79436459, 2.79941881, 2.80447299, 2.80952713,
2.81458122, 2.81963527, 2.82468927, 2.82974323, 2.83479715,
2.83985102, 2.84490485, 2.84995863, 2.85501237, 2.86006607,
2.86511972, 2.87017332, 2.87522688, 2.8802804 , 2.88533387,
2.8903873 , 2.89544068, 2.90049402, 2.90554731, 2.91060056,
2.91565376, 2.92070691, 2.92576002, 2.93081309, 2.93586611,
2.94091908, 2.94597201, 2.95102489, 2.95607773, 2.96113052,
2.96618327, 2.97123596, 2.97628862, 2.98134122, 2.98639378,
2.9914463 , 2.99649876, 3.00155118, 3.00660356, 3.01165588,
3.01670816, 3.0217604 , 3.02681258, 3.03186472, 3.03691681,
3.04196886, 3.04702086, 3.05207281, 3.05712471, 3.06217657,
3.06722837, 3.07228013, 3.07733185, 3.08238351, 3.08743513,
3.0924867 , 3.09753822, 3.10258969, 3.10764111, 3.11269249,
3.11774382, 3.1227951 , 3.12784633, 3.13289751, 3.13794864,
3.14299973, 3.14805076, 3.15310175, 3.15815269, 3.16320358,
3.16825442, 3.17330521, 3.17835595, 3.18340664, 3.18845728,
3.19350787, 3.19855842, 3.20360891, 3.20865936, 3.21370975,
3.21876009, 3.22381039, 3.22886063, 3.23391082, 3.23896097,
3.24401106, 3.2490611 , 3.2541111 , 3.25916104, 3.26421093,
3.26926077, 3.27431056, 3.2793603 , 3.28440999, 3.28945962,
3.29450921, 3.29955875, 3.30460823, 3.30965766, 3.31470704,
3.31975637, 3.32480565, 3.32985488, 3.33490405, 3.33995317,
3.34500224, 3.35005126, 3.35510023, 3.36014914, 3.36519801,
3.37024682, 3.37529558, 3.38034428, 3.38539293, 3.39044154,
3.39549008, 3.40053858, 3.40558702, 3.41063541, 3.41568375,
3.42073203, 3.42578026, 3.43082844, 3.43587656, 3.44092463,
3.44597265, 3.45102062, 3.45606853, 3.46111638, 3.46616419,
3.47121194, 3.47625963, 3.48130727, 3.48635486, 3.49140239,
3.49644987, 3.5014973 , 3.50654467, 3.51159198, 3.51663925,
3.52168645, 3.5267336 , 3.5317807 , 3.53682775, 3.54187473,
3.54692167, 3.55196854, 3.55701537, 3.56206213, 3.56710885,
3.5721555 , 3.57720211, 3.58224865, 3.58729514, 3.59234158,
3.59738796, 3.60243428, 3.60748055, 3.61252676, 3.61757292,
3.62261901, 3.62766506, 3.63271104, 3.63775698, 3.64280285,
3.64784867, 3.65289443, 3.65794013, 3.66298578, 3.66803137,
3.67307691, 3.67812238, 3.6831678 , 3.68821317, 3.69325847,
3.69830372, 3.70334891, 3.70839404, 3.71343912, 3.71848414,
3.7235291 , 3.728574 , 3.73361885, 3.73866364, 3.74370837,
3.74875304, 3.75379765, 3.75884221, 3.7638867 , 3.76893114,
3.77397552, 3.77901984, 3.78406411, 3.78910831, 3.79415246,
3.79919654, 3.80424057, 3.80928454, 3.81432845, 3.8193723 ,
3.82441609, 3.82945982, 3.8345035 , 3.83954711, 3.84459066,
3.84963416, 3.85467759, 3.85972097, 3.86476428, 3.86980754,
3.87485073, 3.87989387, 3.88493694, 3.88997996, 3.89502291,
3.90006581, 3.90510864, 3.91015141, 3.91519413, 3.92023678,
3.92527937, 3.9303219 , 3.93536437, 3.94040678, 3.94544912,
3.95049141, 3.95553364, 3.9605758 , 3.9656179 , 3.97065994,
3.97570192, 3.98074384, 3.9857857 , 3.99082749, 3.99586923,
4.0009109 , 4.0059525 , 4.01099405, 4.01603554, 4.02107696,
4.02611832, 4.03115962, 4.03620085, 4.04124203, 4.04628314,
4.05132418, 4.05636517, 4.06140609, 4.06644695, 4.07148775,
4.07652848, 4.08156915, 4.08660976, 4.0916503 , 4.09669078,
4.1017312 , 4.10677155, 4.11181184, 4.11685207, 4.12189223,
4.12693233, 4.13197236, 4.13701233, 4.14205224, 4.14709208,
4.15213186, 4.15717157, 4.16221122, 4.16725081, 4.17229033,
4.17732978, 4.18236917, 4.1874085 , 4.19244776, 4.19748696,
4.20252609, 4.20756516, 4.21260416, 4.2176431 , 4.22268197,
4.22772077, 4.23275952, 4.23779819, 4.2428368 , 4.24787534,
4.25291382, 4.25795223, 4.26299058, 4.26802886, 4.27306707,
4.27810522, 4.2831433 , 4.28818132, 4.29321927, 4.29825715,
4.30329497, 4.30833272, 4.3133704 , 4.31840802, 4.32344557,
4.32848305, 4.33352047, 4.33855782, 4.3435951 , 4.34863231,
4.35366946, 4.35870654, 4.36374355, 4.3687805 , 4.37381737,
4.37885418, 4.38389093, 4.3889276 , 4.39396421, 4.39900075,
4.40403722, 4.40907362, 4.41410995, 4.41914622, 4.42418242,
4.42921854, 4.43425461, 4.4392906 , 4.44432652, 4.44936238,
4.45439816, 4.45943388, 4.46446953, 4.4695051 , 4.47454061,
4.47957606, 4.48461143, 4.48964673, 4.49468196, 4.49971713,
4.50475222, 4.50978724, 4.5148222 , 4.51985708, 4.5248919 ,
4.52992664, 4.53496132, 4.53999592, 4.54503046, 4.55006492,
4.55509931, 4.56013364, 4.56516789, 4.57020207, 4.57523618,
4.58027023, 4.5853042 , 4.5903381 , 4.59537192, 4.60040568,
4.60543937, 4.61047298, 4.61550653, 4.62054 , 4.6255734 ,
4.63060673, 4.63563999, 4.64067318, 4.64570629, 4.65073934])
y = array([ 1235.125 , 1279. , 1226.42307692, 1243.38461538,
1231.88461538, 1212.26923077, 1246.77777778, 1265.66666667,
1233.07142857, 1212.89655172, 1222.28571429, 1230.78571429,
1218.53571429, 1250. , 1270.86666667, 1240.7 ,
1232.53333333, 1237.06666667, 1280.16129032, 1284.84848485,
1259.71875 , 1260.21875 , 1254.93939394, 1292.90625 ,
1320.87878788, 1338.94117647, 1359.91176471, 1401.61764706,
1473.55882353, 1609.79411765, 1867.97142857, 2350.55555556,
2672.69444444, 2859.51351351, 3121.08333333, 3142.51351351,
3167. , 3371.28947368, 3591.10526316, 3850.71052632,
4146.84210526, 4479.94871795, 4849.325 , 5370.425 ,
5960.4 , 6383.4 , 6526.525 , 6826.53658537,
7286.1627907 , 6057.73809524, 4495.4047619 , 3057.51162791,
2650.34883721, 2122.31818182, 1865.72727273, 1697.47727273,
1619.68181818, 1532.79545455, 1550.17777778, 1482.15217391,
1443.97826087, 1402.52173913, 1381.7173913 , 1345.41304348,
1348.95744681, 1362.68085106, 1319.8125 , 1326.8 ,
1285.39583333, 1271.12244898, 1295.06122449, 1279.44897959,
1253.98 , 1241.08 , 1224.78 , 1206.6 ,
1245.33333333, 1219.61538462, 1205.53846154, 1213.73584906,
1176.86538462, 1175.74074074, 1190.58490566, 1167.31481481,
1145.6 , 1144.48148148, 1133.14814815, 1151.78181818,
1143.90909091, 1125.30357143, 1113.05357143, 1124.07017544,
1102.875 , 1106.07017544, 1081.3220339 , 1093.01724138,
1086.96551724, 1084.46551724, 1070.43103448, 1086.33333333,
1074.6 , 1064.23333333, 1061.2295082 , 1067.88333333,
1081.77419355, 1076.95081967, 1058.85483871, 1058.77777778,
1066.12903226, 1058.22580645, 1076.82539683, 1076.921875 ,
1070.75 , 1071.15625 , 1082.765625 , 1089.28125 ,
1103.29230769, 1098.10606061, 1131.60294118, 1131.10606061,
1134.25373134, 1179.25373134, 1197.94117647, 1211.63235294,
1239.52941176, 1279.39705882, 1333.76470588, 1394.72058824,
1485.38571429, 1597.81428571, 1772.87323944, 1990.07142857,
2297.14084507, 2739.32857143, 3701.05555556, 5263.45833333,
7445.34722222, 9988.61111111, 12308.80821918, 14355.02702703,
16645.01369863, 18399.08108108, 20258.56578947, 22983.22972973,
26834.24324324, 31780.61333333, 37120.09090909, 43428.60526316,
47800.81578947, 49052.61038961, 52014.39473684, 56239.26923077,
51390.08974359, 40128.32051282, 25536.18987342, 15170.30769231,
10301.01265823, 6747.6835443 , 4820.75308642, 3776.2625 ,
3125.5 , 2713. , 2433.37037037, 2166.93975904,
2024.03571429, 1839.37804878, 1711.27710843, 1640.62195122,
1578.01204819, 1514.45238095, 1448.39285714, 1390.6547619 ,
1351.6547619 , 1324.17647059, 1285.95294118, 1255.18604651,
1246.51136364, 1195.45348837, 1163.70930233, 1149.65909091,
1115.42222222, 1095.30681818, 1076.60227273, 1055.93181818,
1033.80681818, 1017.75555556, 996.35555556, 983.48888889,
962.28888889, 944.23076923, 930.14285714, 912.24175824,
892.25531915, 875.55434783, 868.31521739, 846.58695652,
836.47311828, 824.6344086 , 814.75531915, 813.41489362,
799.88421053, 726.39588198, 713.8469267 , 703.04992072,
691.98457674, 680.10919913, 673.6326038 , 666.42559083,
659.16221837, 661.85486338, 653.15733337, 645.55865728,
648.8569043 , 641.87927682, 648.47109253, 645.49435181,
636.09032841, 656.00820221, 661.94923401, 674.25558834,
685.32096893, 693.38880767, 711.46529833, 733.47792831,
751.31502664, 777.92629564, 818.99787176, 890.85957613,
954.53641627, 1096.29125105, 1203.90469099, 1309.64514509,
1438.80368812, 1628.98611365, 1863.78800302, 2181.8515625 ,
2658.4014402 , 3359.96094663, 4368.18610749, 5403.19278598,
6303.16474971, 7222.71911169, 8050.91538267, 8703.3873402 ,
9446.67687218, 10525.85152699, 11531.13483665, 12512.6875 ,
14126.15315315, 14916.11504425, 15388.52678571, 14986.30088496,
13977.69911504, 12017.03571429, 9857.92035398, 7075.38596491,
4684.64035088, 3138.87826087, 2247.16666667, 1746.45217391,
1395.4122807 , 1247.01694915, 1060.04273504, 978.88034188,
907.17948718, 868.41025641, 843.41025641, 810.25423729,
792.52542373, 774.05932203, 758.88983051, 748.16101695,
741.33613445, 722.66942149, 721.47540984, 704.36363636,
700.63333333, 682.10655738, 679.54918033, 668.86065574,
658.8699187 , 651.26229508, 639.87704918, 630.736 ,
624.6 , 622.04032258, 616.74193548, 618.02380952,
619.21774194, 622.53174603, 626.61417323, 633.69047619,
640.07086614, 657.88095238, 671.69047619, 692.07874016,
714.29457364, 745.046875 , 782.8984375 , 823.52307692,
875.48837209, 940.13740458, 1019.7480916 , 1118.71538462,
1243.89312977, 1480.76515152, 1660.48091603, 1695.22727273,
1846.6641791 , 2087.43939394, 2386.59398496, 2577.81203008,
2857.45112782, 3624.42537313, 3940.57462687, 4091.42222222,
4647.88059701, 5379.68382353, 6455.26277372, 8253.20588235,
8841.60294118, 8340.16666667, 7807.29927007, 7560.83333333,
6567.56115108, 4923.86956522, 2556.96376812, 1537.65942029,
1235.5 , 1102.69064748, 1031.68345324, 978.17730496,
961.39285714, 963.1048951 , 985.18571429, 1050.04964539,
1203.77777778, 1395.11888112, 1681.47916667, 2046.16197183,
2441.22535211, 2926.66666667, 3267.68275862, 3292.49655172,
3821.75694444, 4163.2137931 , 4583.14383562, 5125.49315068,
5615.02739726, 5812.05442177, 5754.93835616, 5446.11643836,
5050.37414966, 4514.35135135, 3932.95302013, 3077.58108108,
2323.08108108, 1760.21192053, 1332.33333333, 1056.38815789,
872.26490066, 759.80666667, 681.78289474, 619.74834437,
582.33774834, 547.39473684, 518.51315789, 502.19078947,
481.92156863, 470.70779221, 459.84415584, 446.56410256,
438.44230769, 431.72727273, 424.01935484, 421.17197452,
414.59615385, 413.41025641, 405.68589744, 404.17834395,
402.03205128, 397.62658228, 396.2721519 , 391.47169811,
389.9245283 , 384.48734177, 385.375 , 382.38509317,
379.05555556, 376.93125 , 379.30434783, 373.94375 ,
373.88888889, 372.2962963 , 366.63190184, 368.59259259,
367.19018405, 364.91411043, 368.43558282, 364.34146341,
361.01219512, 361.51515152, 360.28313253, 361.78658537,
361.47272727, 359.98809524, 357.23668639, 354.78313253,
355.66666667, 356.54491018, 356.56886228, 357.388738 ,
355.24436351, 354.40135906, 353.66823396, 352.09695108,
351.51668935, 351.08681448, 352.57701235, 353.66455006,
349.3038687 , 350.86788447, 348.06043292, 349.94521442,
347.63506569, 346.30903555, 348.14707308, 347.57515717,
351.41311084, 348.30222355, 348.99481062, 350.67152379,
347.70514143, 350.62315351, 351.39704145, 352.3644189 ,
355.43859725, 362.61229607, 367.29164684, 370.6738583 ,
373.11415854, 378.01654477, 382.76888578, 388.13758147,
391.55278535, 392.5140042 , 395.12058001, 397.95043996,
399.14833696, 396.52425422, 392.97060336, 384.73643879,
377.236749 , 365.52103806, 353.71274354, 341.00996407,
335.20592981, 330.47475704, 327.5923913 , 326.69189189,
321.7027027 , 323.96236559, 322.39459459, 320.91397849,
322.49197861, 324.22580645, 321.40425532, 320.1657754 ,
323.59259259, 320.90526316, 320.94708995, 320.71428571,
321.20744681, 321.85416667, 318.17460317, 319.84736842,
318.93684211, 316.66842105, 318.84895833, 319.2617801 ,
321.07253886, 318.37113402, 317.36787565, 317.58031088,
317.86010363, 319.58461538, 316.44845361, 319.19387755,
319.42564103, 322.29381443, 320.34693878, 318.7755102 ,
315.60606061, 316.89340102, 317.94416244, 316.56122449,
316.5959596 , 317.2979798 , 317. , 314.53 ,
320.66834171, 318. , 317.01492537, 316.04926108,
316.71641791, 315.485 , 318.51741294, 318.92537313,
316.39303483, 319.6039604 , 317.45049505, 318.7970297 ,
318.96551724, 319.46305419, 322.24271845, 322.31707317,
326.78846154, 324.7254902 , 323.17073171, 333.76442308,
341.42995169, 358.11111111, 370.5776699 , 387.68599034,
401.94174757, 414. , 430.48803828, 435.21052632,
427.17061611, 443.53588517, 469.05263158, 472.78571429,
459.26066351, 455.56398104, 456.43127962, 459.0047619 ,
462.12380952, 476.79245283, 502.09859155, 545.91588785,
602.42990654, 661.64485981, 715.20560748, 769.06976744,
815. , 863.53240741, 904.49302326, 956.31775701,
988.21860465, 987.06451613, 968.70833333, 934.77625571,
871.22222222, 793.8440367 , 725.11415525, 641.88073394,
562.09090909, 498.11415525, 455.25570776, 422.22727273,
395.456621 , 377.14545455, 363.16216216, 351.17488789,
342.92272727, 337.87946429, 331.31390135, 329.61711712,
325.2690583 , 323.29464286, 318.5470852 , 317.13839286,
316.0619469 , 314.24107143, 314.29777778, 313.92857143,
311.39380531, 312.61504425, 309.71491228, 308.94273128,
308.34070796, 308.39647577, 309.13656388, 305.80869565,
307.31441048, 308.42358079, 309.45021645, 306.67982456,
307.30434783, 305.81304348, 308.375 , 307.74568966,
308.17748918, 306.94347826, 309.05172414, 309.46753247,
311.35470085, 310.44206009, 311.32905983, 312.50854701,
310.25957447, 311.94092827, 312.2893617 , 313.85470085,
314.15677966, 312.18723404, 312.31914894, 314.88559322,
313.91139241, 313.1440678 , 312.65546218, 314.59414226,
312.62869198, 315.27385892, 313.11618257, 313.21848739,
311.78333333, 315.15 , 314.9125 , 313.93333333,
315.56666667, 310.85833333, 314.95454545, 304.45901639,
315.37084999, 315.96143404, 316.7021944 , 318.50014328,
319.95321505, 322.50028579, 323.87105554, 324.15103237,
327.74601758, 334.20550962, 339.27812176, 348.02340083,
358.41264695, 375.11453321, 397.47052334, 424.41021431,
455.92610187, 486.79992737, 516.14219059, 543.36431231,
569.13242656, 594.38432404, 614.36852574, 630.20933358,
641.99241487, 644.60920454, 635.55871716, 594.48700851,
585.04244486, 555.02574357, 520.70931512, 481.38397844,
449.48096018, 421.1867297 , 397.98770009, 380.57327294,
368.66721086, 357.72837258, 350.69768042, 347.84715247,
343.38971007, 343.59681541, 342.86784685, 339.71095223,
344.41369021, 344.9653407 , 348.93129771, 354.39382239,
360.92664093, 368.03846154, 377.82239382, 389.13740458,
401.83908046, 422.16153846, 438.65648855, 443.20769231,
446.5210728 , 467.62121212, 502.19847328, 523.64638783,
548.12781955, 585.51526718, 600.7518797 , 602.21969697,
658.50566038, 739.70943396, 827.08679245, 782.89015152,
678.06766917, 623.33458647, 555.67790262, 456.20074349,
399.38059701, 355.60299625, 331.23333333, 321.27941176,
315.21268657, 313.76492537, 312.79925651, 308.48708487,
308.35555556, 305.49259259, 302.47426471, 304.97785978,
302.01107011, 301.36764706, 297.55797101, 299.68978102,
297.79487179, 298.72893773, 299.28832117, 296.36727273,
298.44727273, 299.51824818, 298.49635036, 298.2173913 ,
299.08727273, 300.06545455, 299.39928058, 301.36785714,
300.82310469, 299.38129496, 299.74910394, 300.24548736,
302.84587814, 304.41577061, 305.82733813, 306.38434164,
306.67625899, 311.67730496, 315.25886525, 321.82978723,
329.70714286, 340.27402135, 354.68439716, 370.36491228,
391.04240283, 408.6819788 , 428.64084507, 441.25704225,
456.8415493 , 469.90526316, 482.45296167, 490.74736842,
494.48070175, 497.74385965, 493.03508772, 478.18466899,
462.22569444, 448.04895105, 422.16955017, 401.84083045,
379.0790378 , 359.21799308, 342.94827586, 331.20819113,
321.03472222, 314.32989691, 309.52758621, 306.03092784,
300.93793103, 297.79037801, 294.71821306, 291.34246575,
282.16271186, 278.19795222, 274.65306122, 273.87414966,
271.00677966, 269.77210884, 267.56610169, 266.71283784,
264.18707483, 263.3707483 , 266.49491525, 267.66666667,
269.97674419, 268.77027027, 268.09731544, 268.41471572,
269.62541806, 270.00333333, 270.56856187, 268.39666667,
268.23745819, 268.73 , 270.6722408 , 268.10631229,
270.6986755 , 268.71523179, 267.91089109, 268.08278146,
269.78877888, 269.01315789, 266.45364238, 267.1986755 ,
268.12171053, 268.13907285, 269.45874587, 272.16393443,
273.61237785, 273.85294118, 274.41558442, 276.77124183,
279.15533981, 282.10032362, 284.02922078, 286.44771242,
285.5487013 , 285.04220779, 287.81493506, 287.34415584,
288.61165049, 291.19417476, 291.84565916, 293.24437299,
293.66237942, 293.42307692, 297.39871383, 296.93910256,
300.13694268, 302.68589744, 304.4778481 , 308.38977636,
316.17142857, 318.31948882, 324.2133758 , 335.13607595,
348.27707006, 363.88924051, 383.17515924, 394.2943038 ,
419.5015873 , 453.50314465, 499.46540881, 551.90851735,
613.18181818, 679.85534591, 733.91900312, 786.64596273,
846.70846395, 876.10031348, 803.84012539, 668.19375 ,
499.56386293, 190.10280374])
However, I also calculated the peak position of each peak which are also given
by two arrays-
a =array([[ 0.39516245, 0.60286337, 1.12456674, 1.62583543, 1.98012242,
2.12685572, 2.62755134, 3.13289751, 3.64280285, 3.84963416,
4.14709208]])
b=array([[ 1265.66666667, 7286.1627907 , 56239.26923077, 15388.52678571,
8841.60294118, 5812.05442177, 399.14833696, 988.21860465,
644.60920454, 827.08679245, 497.74385965]])
Now I can simply put marker on top of each peak using few lines of command-
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,y)
ax.plot(a, b,'D')
fig.show()
But I also calculated the value each peak position should show from certain
formula. And that is the following array-
peak_position_value = array([[ 15.90025912, 10.42223758, 5.58720534, 3.86458874,
3.17312972, 2.95421323, 2.39127023, 2.00555086,
1.72482167, 1.63215128, 1.51508218]])
So what I want is actually putting this peak_position_values on top of each
peak instead of diamond marker. If I use annotate it would be quite tiring to
do for all peak. Are there any easier way of doing that?
Answer: If you want to give a visual clue of the `peak_position_value` you can
substitute `ax.plot(a, b,'D')` with
[`ax.scatter'](http://matplotlib.org/api/axes_api.html?highlight=scatter#matplotlib.axes.Axes.scatter),
that allows you to give a colour and/or size to each points.
Example:
ax.scatter(a, b, s=3*peak_position_value)
each point is a circle with a size in pixels 3 times the values in
`peak_position_value`. You can do something similar with the points colours.
If you want to have the values on the plot, I think that you have to use
either `ax.annotate` or `ax.text`. Here is how you can do in one line (but you
have to get rid of one of the `[]` in `a`, `b`, `peak_position_value`)
import itertools as it
texts = [ax.annotate('{0:.2f}'.format(s), [x,y], xytext=[x-0.2,y+1000])
for x,y,s in it.izip(a,b,peak_position_value)]
|
command input splits after each letter python remote control program
Question: I am working on a backdoor program for remote operations over my PC's at home.
The server connects fine but I have a problem in executing the commands as the
letters split up as a new command for each alphabet typed... Something like
when I type 'echo', the results print something as 'e' is not recognized as an
internal or external command and blah blah. then comes: 'c' is not recognized
etc. etc.
Got my point???
How do I make this work that when I type echo it waits for the complete
command
Here is the code:
import socket
import subprocess
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((ipadd_of_pc_running_this_appl,12345))
s.listen(3) #ignore this plz..i will change this later
cli,addr=s.accept()
while 1:
data=cli.recv(1024)
if data:
data=data.decode() #string type conversion
proc=subprocess.Popen(data,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
output=proc.stdout.readline()+proc.stderr.readline()
cli.send(output)
Btw I want to use telent or similar to connect to it plz thanks in advance
sorry about the recv_into...i forgot to change it recv thanks
**NOTE: The problem isn't solved yet. I copied and pasted content from my
other file [minute changes ;)]. Now the code is edited. Kindly help me out**
Answer: Popen expects a list of arguments, so try this:
Popen([data],
|
Saving port 9600 datas in given time
Question: I'm using Arduino and getting values from my shields and sensors. And also I
send some of them to serial.println because of listening port 9600. I'm
listening port 9600 and save these values to txt. After that I upload these
values to database and use web services.
But I couldn't save the 9600 port in given time. Because if I didn't close the
python application, it never close and never save txt file.
My code is below. I want to save txt for every 1 minutes.
How can I do it?
import serial
ser = serial.Serial('/dev/tty.usbmodem1411', 9600, timeout=1)
while 1:
line = ser.readline() # read a '\n' terminated line
line2=line.decode("utf-8")
ths = open("/Users/macproretina//Desktop/data.txt", "a")
ths.write(line2)
ser.close()
Answer: You can use a simple timer to stop the loop. I cleaned up the resource
management a bit, context managers are really useful.
import threading
from contextlib import closing
import serial
continue_looping = True
def stopper():
global continue_looping
continue_looping = False
timer = threading.Timer(60, stopper)
timer.start()
with open("/Users/macproretina/Desktop/data.txt", 'w') as out_file:
with closing(serial.Serial('/dev/tty.usbmodem1411', 9600, timeout=1)) as ser:
while continue_looping:
line = ser.readline() # read a '\n' terminated line
out_file.write(line.decode('utf-8')
out_file.flush()
It might be off a bit due to serial timeouts. Notice that you get the output
written to the file if you call `f.flush()` in case you need that.
|
Best Canvas for WxPython
Question: I am a Java programmer working on a project in Python and the latest version
of WxPython. In Java Swing, you can draw on JPanel elements by overriding
their paint method.
I am looking for a similar class in WxPython for a GUI application.
I saw this question here:
[Best canvas for drawing in
wxPython?](http://stackoverflow.com/questions/2327918/best-canvas-for-drawing-
in-wxpython)
but the fact that the projects are not being updated has me worried.
Three years later, is there anything else I should look into other than
FloatCanvas or OGL?
The end use case i drawing a sound waves at varying degrees of zoom.
Answer: Just use a `wx.Panel`.
Here is some documentation on the drawing context functions:
<http://docs.wxwidgets.org/stable/wx_wxdc.html>
<http://www.wxpython.org/docs/api/wx.DC-class.html>
import wx
class View(wx.Panel):
def __init__(self, parent):
super(View, self).__init__(parent)
self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
self.Bind(wx.EVT_SIZE, self.on_size)
self.Bind(wx.EVT_PAINT, self.on_paint)
def on_size(self, event):
event.Skip()
self.Refresh()
def on_paint(self, event):
w, h = self.GetClientSize()
dc = wx.AutoBufferedPaintDC(self)
dc.Clear()
dc.DrawLine(0, 0, w, h)
dc.SetPen(wx.Pen(wx.BLACK, 5))
dc.DrawCircle(w / 2, h / 2, 100)
class Frame(wx.Frame):
def __init__(self):
super(Frame, self).__init__(None)
self.SetTitle('My Title')
self.SetClientSize((500, 500))
self.Center()
self.view = View(self)
def main():
app = wx.App(False)
frame = Frame()
frame.Show()
app.MainLoop()
if __name__ == '__main__':
main()

|
How can I improve this boolean function?
Question: I often find myself returning a boolean from a method, that's used in multiple
locations, in order to contain all the logic around that method in a single
place. All the (internal) calling method needs to know is whether the
operation was successful, or not.
I'm using Python but the question isn't necessarily specific to that language.
There are only two options I can think of Raise an exception, though the
circumstances are not exceptional, and remember to catch that exception in
every place the function is called Return a boolean as I'm doing.
This is a really simple example that demonstrates what I'm talking about.
import os
class DoSomething(object):
def remove_file(self, filename):
try:
os.remove(filename)
except OSError:
return False
return True
def process_file(self, filename):
do_something()
if remove_file(filename):
do_something_else()
Although it works, its a bad design. How can I improve this?
Answer: Building upon @Joran Beasley's answer, I'd put the something else in an else
block:
class DoSomething(object):
def process_file(self, filename):
do_something()
try:
os.remove(filename)
except OSError:
return False
else:
do_something_else()
|
Trying to update a label in tkinter class
Question: Im new to python and this forum. I tried searching a solution for the errors i
get in my code but this only made me try a lot of different stuff, still i
couldn't get my label updated.
Now i think it has something to do with my inability tot properly define a
variable at the class level. But to be honest, i have a hard time grasping the
concept of class, self, global, local etc. So this may well add to my
confusion.
I cut the code that gives me the errors from my larger program to post here. I
hope some of you can enlighten me what i do wrong. Sorry in advance for
breaking python code etiquette, i'm still learning.
Some of the things i tried i commented out in the posted code...The code i
posted here gives the following error:
Traceback (most recent call last):
File "C:/Users/User/Desktop/smaller example.py", line 35, in <module>
app = cbgui(root)
File "C:/Users/User/Desktop/smaller example.py", line 8, in __init__
self.initUI()
File "C:/Users/User/Desktop/smaller example.py", line 23, in initUI
labelupdate = Tkinter.Label(frame, width = 50, textvariable = self.var)
AttributeError: cbgui instance has no attribute 'var'
My code:
import sys, Tkinter, tkFileDialog
class cbgui(Tkinter.Frame):
def __init__(self, master):
Tkinter.Frame.__init__(self,master)
self.master = master
self.initUI()
self.var = Tkinter.StringVar()
#self.var = Tkinter.StringVar()
self.var.set = "hello"
def UpdateLabel(self):
#var.set = "bye"
self.var.set = "bye"
def initUI(self):
self.master.title("a small update test")
frame = Tkinter.Frame(self, relief=Tkinter.RAISED, borderwidth = 1)
frame.pack(fill = Tkinter.BOTH, expand = 1)
self.pack(fill = Tkinter.BOTH, expan = 1)
#labelupdate = Tkinter.Label(frame, width = 50, textvariable = var)
labelupdate = Tkinter.Label(frame, width = 50, textvariable = self.var)
#labelupdate = Tkinter.Label(frame, width = 50, text = "hello")
labelupdate.grid(row=3, column=2)
labelspace = Tkinter.Label(frame, width = 1)
labelspace.grid(row=3, column=3)
UpdateButton = Tkinter.Button(frame, text="Update label", command = self.UpdateLabel)
UpdateButton.grid(row=3, column=4)
root = Tkinter.Tk()
root.geometry("700x300+10+10")
app = cbgui(root)
Tkinter.mainloop()
Answer: You need to create `self.var` _before_ you call `self.initUI` since `initUI`
uses `self.var`
def __init__(self, master):
Tkinter.Frame.__init__(self,master)
self.master = master
self.var = Tkinter.StringVar()
#self.var = Tkinter.StringVar()
self.var.set("hello")
self.initUI()
|
Generating Tableau Trusted Tickets with curl or Python?
Question: I'm working on a portal site that will use Tableau Trusted Ticket
authentication ([as described
here](http://onlinehelp.tableausoftware.com/current/server/en-
us/trusted_auth_how.htm)), but having some trouble generating tickets.
One thing I wanted to verify before continuing development was that the web
server I'll be using has been properly white-listed for generating Trusted
Ticket requests.
I've run the white-listing command as described, but my PHP developer's code
keeps returning `-1`, indicating failure.
If all Tableau needs to generate and return a Trusted Ticket code is an HTTP
POST, I figure I should be able to test this by curl. I'm a little surprised
it's not suggested as a troubleshooting step, given how many web servers are
Linux-based.
Does anyone know the proper way to send a test POST in order to generate a
ticket, just to verify the white-listing? Since I have some little familiarity
with curl and Python, I've tried those (python using the requests module) with
no luck.
curl version:
curl --data "username=exampleuser" http://webserver.example.com/trusted
Python version:
import requests
url = "http://webserver.example.com/trusted"
postdata = "username=exampleuser"
r = requests.post(url, postdata)
print r.text
Both of these return a `-1`, which could just be that the white-listing failed
somehow, or could be that these are not properly formatted requests. Has
anyone tried something similar and met with success?
Conversely, does anyone have the cleartext string of what a correct `POST`
request should look like for this?
There is a useful chunk of HTML and JavaScript [over
here](http://kb.tableausoftware.com/articles/knowledgebase/testing-trusted-
authentication), with which I have been able to successfully generate tickets,
but since it's JavaScript-based I haven't figured a way to run it on my
headless webserver or capture the request it sends for analysis.
Answer: So first of all, when working with verbs using curl, you have to use `-X
VERBNAME`, e.g.,
~# curl -X POST http://httpbin.org/post
{
"url": "http://httpbin.org/post",
"data": "",
"json": null,
"args": {},
"form": {},
"origin": "127.0.0.1",
"headers": {
"User-Agent": "curl/7.19.6 (x86_64-unknown-linux-gnu) libcurl/7.19.6 OpenSSL/0.9.8n zlib/1.2.3 libidn/1.5",
"Connection": "close",
"Accept": "*/*",
"Content-Length": "0",
"Host": "httpbin.org"
},
"files": {}
}
Second of all, with the parameter being mentioned I would try these
variations:
import requests
# Variation 1
r = requests.post(url, data={'username': 'exampleuser'})
# Variation 2
r = requests.post(url, params={'username': 'exampleuser'})
# Followed by these lines
print r.status_code
print r.text
The equivalents in cURL should look something like this:
# Variation 1 equivalent
curl --data='username=exampleuser' -X POST http://httpbin.org/post
# Variation 2 equivalent
curl -X POST http://httpbin.org/post?username=exampleuser
I'm guessing by the second line that this is supposed to be an
`application/x-www-form-urlencoded` `POST` request so the first variations of
both should work. I'm not at all familiar with tableau though, so I can't
guarantee either will work.
|
nltk.download() hangs on OS X
Question: `nltk.download()` is hanging for me on OS X. Here is what happens:
$python
>>> Python 2.7.2 (default, Oct 11 2012, 20:14:37)
>>> [GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
>>> import nltk
>>> nltk.download()
showing info http://nltk.github.com/nltk_data/
After that, it completely freezes.
I installed everything according to [the ntlk install
page](http://nltk.org/install.html). I'm on OS X 10.8.3. On my Linux box, it
just works with no problems.
Any ideas?
Answer: Try running `nltk.download_shell()` instead as there is most likely an issue
displaying the downloader UI. Running the `download_shell()` function will
bypass it.
|
Trying to run crontab
Question: I'm trying to run a cron job with crontab -e. I'm using a python code
#!/usr/bin/env python
import webbrowser
handle = webbrowser.get()
handle.open_new_tab('http://www.youtube.com/watch?v=Y4QGPWLY-EM')
running crontab -e i have:
* * * * * python /home/sean/imBlue.py >>/tmp/out.txt 2>&1
And i keep getting these error messages
Traceback (most recent call last):
File "/home/sean/imBlue.py", line 3, in <module>
handle = webbrowser.get()
File "/usr/lib/python2.7/webbrowser.py", line 52, in get
raise Error("could not locate runnable browser")
webbrowser.Error: could not locate runnable browser
I'm not sure what I need to include or what I am doing wrong. When I run the
script in bash: python scriptName.py I don't have any issues. Also i have
changed the settings of the file to chmod a+x.
Answer: A `crontab` entry will run even if you are not logged, and does not keep the
environment.
You need at least to set and export the `DISPLAY` variable in your crontab
(assuming that indeed you are logged to an X11 session at time of crontab)
Perhaps changing the `crontab` entry to
* * * * * env DISPLAY=:0.0 python /home/sean/imBlue.py >>/tmp/out.txt 2>&1
could help. Of course if you are not logged on at that time it won't work
My feeling is that your whole script is a huge mistake, or a bad trick: you
don't want to play every minute a video of more than 5 minutes!
|
how to make a UDP python localhost go public
Question: I have a python localhost set up on a raspberry pi to listen for UDP packets.
But I'm wondering how I can make this a public server in order to send UDP
packets from roaming devices.
The below code works perfectly sending UDP packets from a device on the same
wireless network.
import SocketServer
PORTNO = 14
class handler(SocketServer.DatagramRequestHandler):
def handle(self):
newmsg = self.rfile.readline().rstrip()
print (newmsg)
self.wfile.write(self.server.oldmsg)
self.server.oldmsg = newmsg
s = SocketServer.UDPServer(('',PORTNO), handler)
print "Awaiting UDP messages on port %d" % PORTNO
s.oldmsg = "This is the starting message."
s.serve_forever()
Answer: This is more a networking issue. You will have to configure your router with
appropriate [port forwarding](http://en.wikipedia.org/wiki/Port_forwarding).
If your ISP does not have static IP's you may also need to set-up some
[dynamic DNS](http://dyn.com/dns/) service.
The NAT traversal required to connect to external networks requires a static
IP outside the 192.168._._ or 10._._.* range. This is typically assigned by
the ISP DHCP server to the external facing MAC Address of the router.
The port forward settings are shown here: 
|
Table of widgets in Python with Tkinter
Question: I want to put a table into a Label Frame in GUI with using Tkinter under
python the table will not contents only static data but also widgets like
Buttons, Input Entries, Check Buttons ... etc
for example:
Table 1:
[ Nr. | Name | Active | Action ]
----------------------------------
[ 1 | ST | [x] | [Delete] ]
[ 2 | SO | [ ] | [Delete] ]
[ 3 | SX | [x] | [Delete] ]
`[x]` is a Check Button and `[Delete]` is a Button
Answer: You can use the `grid` geometry manager in a frame to layout the widgets
however you want. Here's a simple example:
import Tkinter as tk
import time
class Example(tk.LabelFrame):
def __init__(self, *args, **kwargs):
tk.LabelFrame.__init__(self, *args, **kwargs)
data = [
# Nr. Name Active
[1, "ST", True],
[2, "SO", False],
[3, "SX", True],
]
self.grid_columnconfigure(1, weight=1)
tk.Label(self, text="Nr.", anchor="w").grid(row=0, column=0, sticky="ew")
tk.Label(self, text="Name", anchor="w").grid(row=0, column=1, sticky="ew")
tk.Label(self, text="Active", anchor="w").grid(row=0, column=2, sticky="ew")
tk.Label(self, text="Action", anchor="w").grid(row=0, column=3, sticky="ew")
row = 1
for (nr, name, active) in data:
nr_label = tk.Label(self, text=str(nr), anchor="w")
name_label = tk.Label(self, text=name, anchor="w")
action_button = tk.Button(self, text="Delete", command=lambda nr=nr: self.delete(nr))
active_cb = tk.Checkbutton(self, onvalue=True, offvalue=False)
if active:
active_cb.select()
else:
active_cb.deselect()
nr_label.grid(row=row, column=0, sticky="ew")
name_label.grid(row=row, column=1, sticky="ew")
active_cb.grid(row=row, column=2, sticky="ew")
action_button.grid(row=row, column=3, sticky="ew")
row += 1
def delete(self, nr):
print "deleting...nr=", nr
if __name__ == "__main__":
root = tk.Tk()
Example(root, text="Hello").pack(side="top", fill="both", expand=True, padx=10, pady=10)
root.mainloop()
|
Finding out Age in Months and Years given DOB in a CSV using python
Question: I making several adjustments to an automatically gennerated CSV report. I am
currently stuck on a part where I need to take a patient's DOB and convert
that into an Age in Months and Years. There is already a Column for age in the
original CSV, and I've figured out how to convert the data in the DOB Column
to find the Age in Days, however, I need to be able to convert that to
Months/years and then also take that calculated value and replace the value in
the current field. The current field is a hand-typed string which has no real
consistent formattin. The actual CSV has about 1700 rows and 18 column, and
uses the standard comma to separate them, so I'm just makign up a shorter form
for an example, and using indents to make it easier to see:
Last_Name First_Name MI age DOB SSN visit_date
Stalone Frank P 62yrs 10 months 07-30-1950 123456789 05-02-2013
Astley Richard P 47years3mo 02-06-1966 987654321 05-03-2013
What I want should look like this:
Last_Name First_Name MI Age DOB SSN
Stalone Frank P 62y10mo 07-30-1950 123456789
Astley Richard P 47y3mo 02-06-1966 987654321
EDIT: I realized I could jsut use the date.year and date.month to jsut
subtract year and month, making those values much easier to find. I'm editing
my code now and will update it when I got it working, btu I'm still having
trouble wiht the second part of my question.
My code so far:
import re
import csv
import datetime
with open(inputfile.csv','r') as fin, open(outputfile.csv','w') as fout:
reader = csv.DictReader(fin)
fieldnames = reader.fieldnames
writer_clinics = csv.DictWriter(fout, fieldnames, dialect="excel")
writer_clinics.writeheader()
for row in reader:
data = next(reader)
today = datetime.date.today()
DOB = datetime.datetime.strptime(data["DOB"], "%m/%d/%Y").date()
age_y = (today.year - DOB.year)
age_m = (today.month - DOB.month)
if age_m < 0:
age_y = age_y - 1
age_m = age_m + 12
age = str(age_y) + " y " + str(age_m) + " mo "
print (age)
So, I'm tryign to figure out how to write the age into the correct field in
the outputfile.csv?
Update 2: Managed to get most of it to write, however, it is having errors
with certain fields being left empty in the input file. My boss also wanted me
to make the age, dependant ont he actual date of the appointment. my current
chunk of code:
import re
import csv
import datetime
def getage(visit, dob):
years = visit.year - dob.year
months = visit.month - dob.month
if visit.day < dob.day:
months -= 1
if months < 0:
months += 12
years -= 1
return '%sy%smo'% (years, months)
with open('inputfile.csv','r') as fin, open('outputfile.csv','w') as fout:
reader = csv.DictReader(fin)
writer_clinics = csv.DictWriter(fout, reader.fieldnames, dialect="excel")
writer_clinics.writeheader()
for data in reader:
visit_date = datetime.strptime(data["visit_date"], "%m-%d-%Y").date()
DOB = datetime.datetime.strptime(data["DOB"], "%m-%d-%Y").date()
data["Age"] = getage(visit_date, DOB)
writer_clinics.writerow(data)
Answer: You can't convert days into years and months, since years and months have
different numbers of days in them. You need to take the differences of the
years and months themselves.
dob = datetime.datetime.strptime('07-30-1950', '%m-%d-%Y')
now = datetime.datetime.now()
years = now.year - dob.year
months = now.month - dob.month
if now.day < dob.day:
months -= 1
while months < 0:
months += 12
years -= 1
age = '{}y{}mo'.format(years, months)
>>> print age
62y9mo
|
Looking for a fold-like idiom
Question: So my friend presented a problem for me to solve, and I'm currently writing a
solution in functional-style Python. The problem itself isn't my question; I'm
looking for a possible idiom that I can't find at the moment.
What I need is a fold, but instead of using the same function for every one of
it's applications, it would do a map-like exhaustion of another list
containing functions. For example, given this code:
nums = [1, 2, 3]
funcs = [add, sub]
special_foldl(nums, funcs)
the function (special_foldl) would fold the number list down with ((1 + 2) -
3). Is there a function/idiom that elegantly does this, or should I just roll
my own?
Answer: There is no such function in the Python standard library. You'll have to roll
you own, perhaps something like this:
import operator
import functools
nums = [1, 2, 3]
funcs = iter([operator.add, operator.sub])
def special_foldl(nums, funcs):
return functools.reduce(lambda x,y: next(funcs)(x,y), nums)
print(special_foldl(nums, funcs))
# 0
|
pygst + pyinstaller under OSX
Question: I'm currently trying to bundle this dead simple python script (player.py):
#!/usr/bin/env python
import sys, os
import gobject, glib
import pygst
pygst.require("0.10")
import gst
class Player(object):
def __init__(self):
self.player = gst.element_factory_make("playbin2", "player")
fakesink = gst.element_factory_make("fakesink", "fakesink")
self.player.set_property("video-sink", fakesink)
bus = self.player.get_bus()
bus.add_signal_watch()
bus.connect("message", self.on_message)
def play(self, url):
self.player.set_state(gst.STATE_NULL)
self.player.set_property("uri", url)
self.player.set_state(gst.STATE_PLAYING)
def on_message(self, bus, message):
t = message.type
if t == gst.MESSAGE_EOS:
global loop
loop.quit()
elif t == gst.MESSAGE_ERROR:
self.player.set_state(gst.STATE_NULL)
err, debug = message.parse_error()
print "Error: %s" % err, debug
p = Player()
p.play("file:///path/to/something.mp3")
gobject.threads_init()
loop = glib.MainLoop()
loop.run()
into an OSX (my machine runs Mountain Lion) application using pyinstaller
(2.1.0-dev).
My aim is to create a .app bundle that I can easily distribute. I could also
ask the final user to install GStreamer SDK, even though a self-contained
application would be my primary goal.
The spec file follows (player.spec):
# -*- mode: python -*-
import pygst
pygst.require('0.10')
a = Analysis(['player.py'],
pathex=['/Users/mymy/devel/t/simple'],
hiddenimports=[],
hookspath=None,
runtime_hooks=None)
pyz = PYZ(a.pure)
exe = EXE(pyz,
a.scripts,
exclude_binaries=True,
name='player',
debug=False,
strip=None,
upx=True,
console=True )
coll = COLLECT(exe,
a.binaries,
a.zipfiles,
a.datas,
strip=None,
upx=True,
name='player')
I attempted two strategies, so far:
1. macports: python (2.7.2), pygst (0.10), gst-plugins-*
2. system python, GStreamer 0.10 SDK (Framework)
In both cases I can successfully run the script.
When I attempt to run the bundled executable, though, I get the following:
1. (Macports)
Showing a partial GST debug log:
~/devel/t/simple/dist/player > GST_DEBUG=4 ./player
[..]
0:00:00.113260000 8313 0x1001b1a00 DEBUG GST_REGISTRY gstregistrychunks.c:573:gboolean gst_registry_chunks_load_feature(GstRegistry *, gchar **, gchar *, GstPlugin *): Plugin 'playback' feature 'playbin2' typename : 'GstElementFactory'
0:00:00.113286000 8313 0x1001b1a00 DEBUG GST_REGISTRY gstregistrychunks.c:621:gboolean gst_registry_chunks_load_feature(GstRegistry *, gchar **, gchar *, GstPlugin *): Element factory : 'Player Bin 2' with npadtemplates=0
0:00:00.113300000 8313 0x1001b1a00 DEBUG GST_REGISTRY gstregistrychunks.c:649:gboolean gst_registry_chunks_load_feature(GstRegistry *, gchar **, gchar *, GstPlugin *): Reading 2 Interfaces at address 0x101971191
0:00:00.113318000 8313 0x1001b1a00 DEBUG GST_REGISTRY gstregistry.c:558:gboolean gst_registry_add_feature(GstRegistry *, GstPluginFeature *):<registry0> adding feature 0x10097da20 (playbin2)
0:00:00.113332000 8313 0x1001b1a00 DEBUG GST_REFCOUNTING gstobject.c:844:gboolean gst_object_set_parent(GstObject *, GstObject *):<playbin2> set parent (ref and sink)
0:00:00.113346000 8313 0x1001b1a00 DEBUG GST_REGISTRY gstregistrychunks.c:709:gboolean gst_registry_chunks_load_feature(GstRegistry *, gchar **, gchar *, GstPlugin *): Added feature playbin2, plugin 0x100975be0 playback
[..]
0:00:00.242584000 8297 0x1001b1a00 DEBUG GST_PLUGIN_LOADING gstpluginfeature.c:106:GstPluginFeature *gst_plugin_feature_load(GstPluginFeature *): loading plugin for feature 0x10097da20; 'playbin2'
0:00:00.242620000 8297 0x1001b1a00 DEBUG GST_PLUGIN_LOADING gstpluginfeature.c:110:GstPluginFeature *gst_plugin_feature_load(GstPluginFeature *): loading plugin playback
0:00:00.242632000 8297 0x1001b1a00 DEBUG GST_PLUGIN_LOADING gstplugin.c:1293:GstPlugin *gst_plugin_load_by_name(const gchar *): looking up plugin playback in default registry
0:00:00.242662000 8297 0x1001b1a00 DEBUG GST_PLUGIN_LOADING gstplugin.c:1296:GstPlugin *gst_plugin_load_by_name(const gchar *): loading plugin playback from file /opt/local/lib/gstreamer-0.10/libgstplaybin.so
0:00:00.242677000 8297 0x1001b1a00 DEBUG GST_PLUGIN_LOADING gstplugin.c:737:GstPlugin *gst_plugin_load_file(const gchar *, GError **): attempt to load plugin "/opt/local/lib/gstreamer-0.10/libgstplaybin.so"
0:00:00.248338000 8297 0x1001b1a00 INFO GST_PLUGIN_LOADING gstplugin.c:859:GstPlugin *gst_plugin_load_file(const gchar *, GError **): plugin "/opt/local/lib/gstreamer-0.10/libgstplaybin.so" loaded
0:00:00.248374000 8297 0x1001b1a00 DEBUG GST_PLUGIN_LOADING gstpluginfeature.c:115:GstPluginFeature *gst_plugin_feature_load(GstPluginFeature *): loaded plugin playback
0:00:00.248390000 8297 0x1001b1a00 INFO GST_PLUGIN_LOADING gstpluginfeature.c:145:GstPluginFeature *gst_plugin_feature_load(GstPluginFeature *): Tried to load plugin containing feature 'playbin2', but feature was not found.
0:00:00.248402000 8297 0x1001b1a00 WARN GST_ELEMENT_FACTORY gstelementfactory.c:410:GstElement *gst_element_factory_create(GstElementFactory *, const gchar *):<playbin2> loading plugin containing feature player returned NULL!
0:00:00.248412000 8297 0x1001b1a00 INFO GST_ELEMENT_FACTORY gstelementfactory.c:472:GstElement *gst_element_factory_make(const gchar *, const gchar *):<playbin2> couldn't create instance!
Traceback (most recent call last):
File "<string>", line 33, in <module>
File "<string>", line 11, in __init__
gst.ElementNotFoundError: playbin2
Getting the same result pre-pending:
GST_PLUGIN_PATH=/opt/local/lib/gstreamer-0.10/
I tried to copy the plugins and their dependencies into the dist/player
folder, scripting a wild install_name_tool mangling in order to correct the
paths of the dylibs, but the result doesn't change either.
1. (GStreamer SDK)
(PYTHONPATH=/Library/Frameworks/GStreamer.framework/Versions/0.10/lib/python2.7/site-
packages/)
~/devel/t/simple/dist/player > ./player
** Message: pygobject_register_sinkfunc is deprecated (GstObject)
player.py:11: Warning: cannot register existing type `GstObject'
player.py:11: Warning: g_once_init_leave: assertion `result != 0' failed
player.py:11: Warning: gtype.c:2720: You forgot to call g_type_init()
and here it hangs. If I sample the process via Activity Monitor, I get this:
[..]
_wrap_gst_element_factory_make (in gst._gst.so)
gst_element_factory_make (in libgstreamer-0.10.0.dylib)
gst_element_factory_create (in libgstreamer-0.10.0.dylib)
gst_plugin_feature_load (in libgstreamer-0.10.0.dylib)
gst_plugin_load_by_name (in libgstreamer-0.10.0.dylib)
gst_plugin_load_file (in libgstreamer-0.10.0.dylib)
gst_plugin_register_func (in libgstreamer-0.10.0.dylib)
plugin_init (in libgstplaybin.so)
gst_play_bin2_plugin_init (in libgstplaybin.so)
gst_pipeline_get_type (in libgstreamer-0.10.0.dylib)
gst_bin_get_type (in libgstreamer-0.10.0.dylib)
gst_child_proxy_get_type (in libgstreamer-0.10.0.dylib)
gst_object_get_type (in libgstreamer-0.10.0.dylib)
g_once_init_enter (in libglib-2.0.0.dylib)
g_cond_wait (in libglib-2.0.0.dylib)
_pthread_cond_wait (in libsystem_c.dylib)
__psynch_cvwait (in libsystem_kernel.dylib)
A hint would be immensely appreciated!
Answer: I finally have a working solution for the following setup:
* macports (python @2.7.3, py27-gst-python @0.10.22, gstreamer010 @0.10.36)
* pyinstaller 2.1-dev (ccb6f3d3d924a0dc2f9e92aa6278c28a2d743d39)
* OSX 10.8.3
## pyinstaller spec file (player.spec):
# -*- mode: python -*-
import os
import pygst
pygst.require('0.10')
a = Analysis(['rthook.py', 'player.py'],
pathex=[os.curdir],
hiddenimports=[],
hookspath=None,
runtime_hooks=None)
pyz = PYZ(a.pure)
exe = EXE(pyz,
a.scripts,
exclude_binaries=True,
name='player',
debug=False,
strip=None,
upx=True,
console=True )
coll = COLLECT(exe,
a.binaries,
a.zipfiles,
a.datas,
strip=None,
upx=True,
name='player')
## _gst.so hook (hook-gst._gst.py):
I created a very primitive hook for gst. I tried to put it inside a local
directory, referencing it via the _hookspath_ parameter of the Analysis
object, but I couldn't figure out why pyinstaller ignored it. Therefore I
moved it to the _/path/to/pyinstaller/PyInstaller/hooks_ folder:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
GST_PLUGINS = '/opt/local/lib/gstreamer-0.10/'
def hook(mod):
for f in [so for so in os.listdir(GST_PLUGINS) if so[-3:].lower() == '.so']:
mod.binaries.append((os.path.join('gst-plugins', f),
os.path.join(GST_PLUGINS, f),
'BINARY'))
return mod
pyinstaller takes care of computing the dependencies trees of the plugins,
copying the .sos into place, along with the dependent dylibs and finally
mangling the mach'o headers of both.
I also created an empty file _/path/to/pyinstaller/PyInstaller/hooks/hook-
gst.py_ to stop pyinstaller to complain about the missing parent hook. And,
anyway, the hook code could go directly to _hook-gst.py_.
## runtime hook file (rthook.py)
Finally I added a runtime hook file, referenced on the Analysis object, that
sets up the environment variables that help gstreamer to locate the plugins.
This code gets executed on the bundled executable before _player.py_
(following the way [Kivy](http://kivy.org/docs/guide/packaging-macosx.html)
sets up pyinstaller and thanks for their precious hint):
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
if hasattr(sys, '_MEIPASS'):
# PyInstaller >= 1.6
root = sys._MEIPASS
elif '_MEIPASS2' in environ:
# PyInstaller < 1.6 (tested on 1.5 only)
root = os.environ['_MEIPASS2']
else:
root = os.path.dirname(sys.argv[0])
os.chdir(root)
os.environ['GST_REGISTRY_FORK'] = 'no'
os.environ['GST_PLUGIN_PATH'] = os.path.join(root, 'gst-plugins')
It seems that disabling
[GST_REGISTRY_FORK](http://gstreamer.freedesktop.org/data/doc/gstreamer/head/gstreamer/html/gst-
running.html) is the only way to have a working outcome. Leaving the default
setting (active) leads to a segmentation fault as soon as the first plugin
gets scanned.
## pyinstaller invocation
pyinstaller can be invoked with:
$ /path/to/pyinstaller/pyinstaller.py player.spec
|
Parsing large xml data using python's elementtree
Question: I'm currently learning how to parse xml data using elementtree. I got an error
that say:ParseError: not well-formed (invalid token): line 1, column 2.
My code is right below, and a bit of the xml data is after my code.
import xml.etree.ElementTree as ET
tree = ET.fromstring("C:\pbc.xml")
root = tree.getroot()
for article in root.findall('article'):
print ' '.join([t.text for t in pub.findall('title')])
for author in article.findall('author'):
print 'Author name: {}'.format(author.text)
for journal in article.findall('journal'): # all venue tags with id attribute
print 'journal'
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE dblp SYSTEM "dblp.dtd">
<dblp>
<article mdate="2002-01-03" key="persons/Codd71a">
<author>E. F. Codd</author>
<title>Further Normalization of the Data Base Relational Model.</title>
<journal>IBM Research Report, San Jose, California</journal>
<volume>RJ909</volume>
<month>August</month>
<year>1971</year>
<cdrom>ibmTR/rj909.pdf</cdrom>
<ee>db/labs/ibm/RJ909.html</ee>
</article>
<article mdate="2002-01-03" key="persons/Hall74">
<author>Patrick A. V. Hall</author>
<title>Common Subexpression Identification in General Algebraic Systems.</title>
<journal>Technical Rep. UKSC 0060, IBM United Kingdom Scientific Centre</journal>
<month>November</month>
<year>1974</year>
</article>
Any ideas will be appreciated. Thanks in advance.
Answer:
with open("C:\pbc.xml", 'rb') as f:
root = ET.fromstring(f.read().strip())
* * *
Unlike `ET.parse`, `ET.fromstring` expects a string with XML content, not the
name of a file.
Also in contrast to `ET.parse`, `ET.fromstring` returns a root Element, not a
Tree. So you should omit
root = tree.getroot()
* * *
Also, the XML snippet you posted needs a closing `</dblp>` to be parsable. I
assume your real data has that closing tag...
* * *
The iterparse provided by `xml.etree.ElementTree` does not have a `tag`
argument, although `lxml.etree.iterparse` does have a `tag` argument.
Try:
import xml.etree.ElementTree as ET
import htmlentitydefs
filename = "test.xml"
# http://stackoverflow.com/a/10792473/190597 (lambacck)
parser = ET.XMLParser()
parser.entity.update((x, unichr(i)) for x, i in htmlentitydefs.name2codepoint.iteritems())
context = ET.iterparse(filename, events = ('end', ), parser=parser)
for event, elem in context:
if elem.tag == 'article':
for author in elem.findall('author'):
print 'Author name: {}'.format(author.text)
for journal in elem.findall('journal'): # all venue tags with id attribute
print(journal.text)
elem.clear()
Note: To use `iterparse` your XML must be valid, which means among other
things that there can not be empty lines at the beginning of the file.
|
Formatted headers/footers? Colour Code
Question: I've found out the way to format header and footer using xlwt (see
<https://groups.google.com/forum/?fromgroups#!topic/python-
excel/3hZP_hK_LSc>),
I'm looking for docs or example on how to define the font color for this
header and footer? any example.
Answer: According to the xlwt [docs](http://open-hea.googlecode.com/hg-
history/e3c022eb2a9a895519930b891dc9ac0a8c09020d/docs/html/xlwt.html#xlwt.BIFFRecords.HeaderRecord),
you can manage just font, font style and font height. You may have found that
there is a special `&K` (e.g. for red `&Kff0000`) notation for header/footer
font color, but it doesn't really work for `xls` (2003) format files.
If you are ok to generate `xlsx` instead - you can choose from
[openpyxl](https://openpyxl.readthedocs.org/en/latest/) or
[xlsxwriter](https://xlsxwriter.readthedocs.org/en/latest/).
Here's an example using `openpyxl`:
from openpyxl import Workbook
wb = Workbook()
ws = wb.worksheets[0]
ws.header_footer.center_header.font_size = 14
ws.header_footer.center_header.font_name = "Tahoma,Bold"
ws.header_footer.center_header.text = "Hello, World!"
ws.header_footer.center_header.font_color = "FF0000"
wb.save('output.xlsx')
Here's an example using `xlsxwriter`:
from xlsxwriter.workbook import Workbook
workbook = Workbook('output.xlsx')
worksheet = workbook.add_worksheet()
worksheet.set_header('&"Tahoma,Bold"&14&Kff0000Hello, World!')
workbook.close()
Hope that helps.
|
TimeField format in Django
Question: I am trying to use a TimeField model which only consists of MM:SS.xx (ie
43:31.75) format. Is it possible to format a regular Python time object like
this?
Thanks.
Answer: Absolutely, you can find it in the datetime module here.
<http://docs.python.org/release/2.5.2/lib/datetime-time.html>
>>> from datetime import time
>>> time_obj = time(0, 43, 31, 750000)
datetime.time(0, 43, 31, 750000)
>>> time_obj.strftime('%M:%S.%f')
'43:31.750000'
|
Unable to successfully dump emails retrieved from gmail to mbox file using python
Question: I have written below 2 code snippets. Second one work's as expected but not
the first one.I am unable to find out why output list of print(msg_obj.keys())
at line #22 in first snippet doesn't contain 'Subject','From' keys while
msg_obj contains header fields like 'Subject','From'. When I dump emails to
mbox file using this script and later open that file using some
utility(mboxview.exe for windows) ,utility doesn't recognise any email
dumped.Please help me out of this. Any suggestions are most welcomed.
import imaplib,email,mailbox
M=imaplib.IMAP4_SSL('imap.gmail.com',993)
status,data=M.login('[email protected]', 'password')
M.select()
#create new mbox file if doesn't exist
mbox_file=mailbox.mbox('gmail_mails.mbox')
mbox_file.lock()
#get all mails number
status,data=M.search(None, 'ALL')
try:
for mail_no in data[0].split():
status,msg=M.fetch(mail_no,'(RFC822)')
msg_obj=email.message_from_string(str(msg[0][1]))
#print for debugging purpose
print(msg_obj.keys())
print(msg_obj["Subject"])
mbox_msg_obj=mailbox.mboxMessage(msg_obj)
mbox_file.add(mbox_msg_obj)
mbox_file.flush()
finally:
mbox_file.unlock()
mbox_file.close()
M.close()
M.logout()
Also what I found is in case of below code it works:
from email.parser import Parser
str="""Received: (qmail 8580 invoked from network); 15 Jun 2010 21:43:22 -0400\r\nReceived: from mail-fx0-f44.google.com (209.85.161.44) by ip-73-187-35-131.ip.secureserver.net with SMTP; 15 Jun 2010 21:43:22 -0400\r\nReceived: by fxm19 with SMTP id 19so170709fxm.3 for <[email protected]>; Tue, 15 Jun 2010 18:47:33 -0700 (PDT)\r\nMIME-Version: 1.0\r\nReceived: by 10.103.84.1 with SMTP id m1mr2774225mul.26.1276652853684; Tue, 15 Jun 2010 18:47:33 -0700 (PDT)\r\nReceived: by 10.123.143.4 with HTTP; Tue, 15 Jun 2010 18:47:33 -0700 (PDT)\r\nDate: Tue, 15 Jun 2010 20:47:33 -0500\r\nMessage-ID: <[email protected]>\r\nSubject: TEST 12\r\nFrom: Full Name <[email protected]>\r\nTo: [email protected]\r\nContent-Type: text/plain; charset=ISO-8859-1 ONE\nTWO\nTHREE"""
msg=Parser().parsestr(str)
print (msg['Subject'])
print (msg['From'])
print (msg['to'])
Here output is
TEST 12
Full Name <[email protected]>
[email protected]
Problem solved using email.parser.BytesParser().parsebytes() instead of
email.message_from_string().But not getting why?
Answer: From your example code, I'm trying the following:
import email
estr = """Received: (qmail 8580 invoked from network); 15 Jun 2010 21:43:22 -0400\r\nReceived: from mail-fx0-f44.google.com (209.85.161.44) by ip-73-187-35-131.ip.secureserver.net with SMTP; 15 Jun 2010 21:43:22 -0400\r\nReceived: by fxm19 with SMTP id 19so170709fxm.3 for <[email protected]>; Tue, 15 Jun 2010 18:47:33 -0700 (PDT)\r\nMIME-Version: 1.0\r\nReceived: by 10.103.84.1 with SMTP id m1mr2774225mul.26.1276652853684; Tue, 15 Jun 2010 18:47:33 -0700 (PDT)\r\nReceived: by 10.123.143.4 with HTTP; Tue, 15 Jun 2010 18:47:33 -0700 (PDT)\r\nDate: Tue, 15 Jun 2010 20:47:33 -0500\r\nMessage-ID: <[email protected]>\r\nSubject: TEST 12\r\nFrom: Full Name <[email protected]>\r\nTo: [email protected]\r\nContent-Type: text/plain; charset=ISO-8859-1 ONE\nTWO\nTHREE"""
msg = email.message_from_string(estr)
print (msg['Subject'])
print (msg['From'])
print (msg['to'])
That prints the results fine.
TEST 12
Full Name <[email protected]>
[email protected]
So from your first code snippet, the function input `str(msg[0][1])` must
contain some unparsable contents. you'll have to have a closer look at the
contents of `str(msg[0][1])` that is failing to parse.
|
How to center align columns of different lengths using numpy.savetxt in Python?
Question: I have several lists that contain both strings and floats as their elements.
import numpy as num
COLUMN_1 = ['KIC 7742534', 'Variable Star of RR Lyr type' , 'V* V368 Lyr',
'KIC 7742534', '4.0', '0.4564816']
COLUMN_2 = ['KIC 76', 'Variable Star' , 'V* V33 Lyr',
'KIC 76', '5.0', '0.45']
DAT = num.column_stack((COLUMN_1, COLUMN_2))
num.savetxt('SAVETXT.txt', DAT, delimiter=' ', fmt='{:^10}'.format('%s'))
The output I get when running this file is the following:
KIC 7742534 , KIC 76
Variable Star of RR Lyr type , Variable Star
V* V368 Lyr , V* V33 Lyr
KIC 7742534 , KIC 76
4.0 , 5.0
0.4564816 , 0.45
The ideal output would look like this (including an aligned header)
#ELEMENT1 ELEMENT2
KIC 7742534 , KIC 76
Variable Star of RR Lyr type , Variable Star
V* V368 Lyr , V* V33 Lyr
KIC 7742534 , KIC 76
4.0 , 5.0
0.4564816 , 0.45
How could I get an output like this (with aligned header), if the strings
don't have a max width defined. I have tried modifying the format of the
strings (fmt), but no luck so far.
-Thanks!
Answer: You will need to calculate the maximum string length of of the longest row of
your output (or input depending on how you look at it), which a method similar
to
max_len = max(max(map(len,l)) for l in zip(COLUMN_1,COLUMN_2))
Will achieve. After that you need to change the `fmt` parameters dynamically
based on the value of max_len which you can do like so:
`fmt=('{:^%d}' % max_len).format('%s')`
The following non-numpy example shows the expected output:
with open('ofile.txt','w+') as f:
max_len = max(max(map(len,l)) for l in zip(COLUMN_1,COLUMN_2))
for line in zip(COLUMN_1,COLUMN_2):
f.write(','.join(('{:<%s}' % (max_len)).format(e) for e in line)+'\n')
Produces a text file `ofile.txt` containing:
KIC 7742534 ,KIC 76
Variable Star of RR Lyr type,Variable Star
V* V368 Lyr ,V* V33 Lyr
KIC 7742534 ,KIC 76
4.0 ,5.0
0.4564816 ,0.45
|
How can I make a ball move in pygame when dragged by mouse?
Question: I am making a small game in python where balls are fired by a catapult, and
then the balls destroy a structure of boxes and a snake. At the moment I have
made the boxes and the snakes however, I am unable to make the balls come from
the left direction to destroy the boxes. I want to make a catapult on the left
side which can hold a ball and fire it. How can I go about making this? Here
is my code
import pygame
from pygame.locals import *
from pygame.color import *
import pymunk as pm
from pymunk import Vec2d
import sys
## ~~~~~~~~~~~~~~~~~~~~~~~~~
class Ball(pygame.sprite.Sprite):
def __init__(self,screen):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('ball1.jpg')
self.original = pygame.image.load('ball1.jpg')
self.rect = self.image.get_rect()
self.area = screen.get_rect()
def add_ball(self, space, offset):#offset
self.mass = 3
self.radius = 15
self.inertia = pm.moment_for_circle(self.mass, 0, self.radius, (0,0))
self.body = pm.Body(self.mass, self.inertia)
self.body.position = offset+200, 550
self.rect.center = to_pygame(self.body.position)
self.shape = pm.Circle(self.body, self.radius, (0,0))
space.add(self.body, self.shape)
def draw(self,screen):
pygame.draw.circle(screen, (255,255,255), self.rect.center, int(15), 3)
def update(self):
print("{0} {1}".format(self.rect.center, self.body.position))
self.rect.center = to_pygame(self.body.position)
## ~~~~~~~~~~~~~~~~~~~~~~~~~
class Box(pygame.sprite.Sprite):
def __init__(self,screen):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('box1.jpg')
self.original = pygame.image.load('box1.jpg')
#self.image = pygame.image.load('snake.jpg')
self.rect = self.image.get_rect()
self.area = screen.get_rect()
def add_box(self, space, posX, posY):
global screen
self.size= 30
self.points = [(-self.size, -self.size), (-self.size, self.size), (self.size,self.size), (self.size, -self.size)]
self.mass = 0.3
self.moment = pm.moment_for_poly(self.mass, self.points, (0,0))
self.body = pm.Body(self.mass, self.moment)
self.body.position = Vec2d(posX, posY)
#print("Box a {0}".format(self.body.position))
self.rect.center = to_pygame(self.body.position)
#print("Box b {0}".format(self.rect))
self.shape = pm.Poly(self.body, self.points, (0,0))
self.shape.friction = 1
#self.shape.group = 1
space.add(self.body, self.shape)
def draw(self,screen):
pygame.draw.rect(screen, (255,255,255), self.rect, 2)
def update(self):
self.rect.center = to_pygame(self.body.position) #pysics simulations is movin the body
## ~~~~~~~~~~~~~~~~~~~~~~~~~
class Snake(pygame.sprite.Sprite):
def __init__(self,screen):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('snake.jpg')
self.original = pygame.image.load('snake.jpg')
self.rect = self.image.get_rect()
self.area = screen.get_rect()
def add_snake(self, space, posX, posY):
global screen
self.size= 30
self.points = [(-self.size, -self.size), (-self.size, self.size), (self.size,self.size), (self.size, -self.size)]
self.mass = 0.1
self.moment = pm.moment_for_poly(self.mass, self.points, (0,0))
self.body = pm.Body(self.mass, self.moment)
self.body.position = Vec2d(posX, posY)
#print("Box a {0}".format(self.body.position))
self.rect.center = to_pygame(self.body.position)
#print("Box b {0}".format(self.rect))
self.shape = pm.Poly(self.body, self.points, (0,0))
self.shape.friction = 1
#self.shape.group = 1
space.add(self.body, self.shape)
def draw(self,screen):
pygame.draw.rect(screen, (5,5,255), self.rect, 2)
def update(self):
self.rect.center = to_pygame(self.body.position) #pysics simulations is movin the body
## ~~~~~~~~~~~~~~~~~~~~~~~~~
def to_pygame(p):
"""Small hack to convert pymunk to pygame coordinates"""
return int(p[0]), int(-p[1]+600)
def main():
pygame.init()
screen = pygame.display.set_mode((600, 600))
pygame.display.set_caption("Piling boxes")
clock = pygame.time.Clock()
space = pm.Space()
space.gravity = (0.0, -900.0)
space.damping = 0.5
### ground
body = pm.Body()
shape = pm.Segment(body, (0,100), (600,100), .0)
shape.friction = 1.0
space.add(shape)
allsprites = pygame.sprite.Group()
offsetY = 62
offsetX = 92
posX = 180
posY = 130
for j in range(3):
for i in range(5):
box = Box(screen) #Add more boxes
box.add_box(space, posX, posY)
allsprites.add(box)
posY = posY + offsetY
posY = 130
posX = posX + offsetX
snake = Snake(screen)
snake.add_snake(space, posX, posY)
allsprites.add(snake)
selected = None
##
## posY = 130
## offset = 92
## for i in range(5):
## #offset = offset - 248
## box = Box(screen) #Add more boxes
## #box.add_box(space)
## box.add_box(space, posX, posY)
## allsprites.add(box)
## posX = posX + offset
##
## #offset = offset + 62
posY =0
offset = 0
for i in range(5):
ball = Ball(screen)
ball.add_ball(space, offset)
offset = offset + 16
allsprites.add(ball)
#background = pygame.Surface(screen.get_size())
#background = background.convert()
#background.fill((0,0,0))
#screen.blit(background, (0,0))
test_image = pygame.image.load("AngryCloneBg.jpg")
#screen.blit(test_image, (0,0)) #coordinates (0,500))
#pygame.display.flip()
while 1:
clock.tick(60)
space.step(1/90.0)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit(0)
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit(0)
allsprites.update()
screen.blit(test_image, (0,0))
#pygame.draw.line(screen, THECOLORS["red"], to_pygame((150,100)), to_pygame((450,100)), 3)
allsprites.draw(screen)
for item in allsprites:
item.draw(screen)
pygame.display.flip()
## ~~~~~~~~~~~~~~~~~~~~~~~~~
if __name__ == '__main__':
main()
How can I make the balls to be used with a catapult to fire the balls?
Answer: After 2 minutes of looking over the pymunk docs:
<http://pymunk.googlecode.com/svn/tags/pymunk-2.0.0/docs/api/index.html>
To create a cannon like game. Create a ball object, and call apply_force. It's
as simple as that.
If you wish to create a catapult, a bit more physics are involved. You need to
create line(Segment) with a fixed joint to the ground. Then connect the ball
to the other end of the segment. Apply some force to the segment, and when the
ball will be high enough, release the joint.
EDIT:
I also found a very helpful tutorial with joints:
<http://code.google.com/p/pymunk/wiki/SlideAndPinJointsExample>
|
Python networkx and persistence (perhaps in neo4j)
Question: I have an application that creates many thousands of graphs in memory per
second. I wish to find a way to persist these for subsequent querying. They
aren't particularly large (perhaps max ~1k nodes).
I need to be able to store the entire graph object including node attributes
and edge attributes. I then need to be able to search for graphs within
specific time windows based on a time attribute in a node.
Is there a simple way to coerce this data into neo4j ? I've yet to find any
examples of this. Though I have found several python libs including an
embedded neo4j and a rest client.
Is the common approach to manually traverse the graph and store it in that
manner?
Are there any better persistence alternatives?
Answer: Networkx has several serialization method.
In your case, I would choose graphml serialization :
<http://networkx.github.io/documentation/latest/reference/readwrite.graphml.html>
It's quite simple to use :
import networkx as nx
nx.write_graphml('/path/to/file')
To load it in Neo4j, provided you have Neo4j<2.0, you could use Tinkerpop
Gremlin to load your graphml dump in Neo4J
g.loadGraphML('/path/to/file')
The Tinkerpop are quite useful - not only for serialization/deserialization.
It will allow you to use different graph database with a commion "dialect"
(provided they have a "Blueprint" driver which most of them do)
|
How to import an existing Plone-based site to a new Ubuntu server
Question: I am new to Plone framework. All I need to do might seem quite simple but I
need some guidance.
I obtained files of an existing Plone-based site and want to integrate into a
new Ubuntu computer. Here are the file list.
* buildout-cache
* Plone-docs
* Python-2.6
* zinstance
And in Zinstance directory I have
* adminPassword.txt
* buildout.cfg
* PloneController.app
* var
* base.cfg
* develop.cfg
* products
* versions.cfg
* bin
* develop-eggs
* README.html
* zope_versions.cg
* bootstrap.py
* parts
* src
I ran
> ./bin/plonectl start
under this site path, but I got improtError for module _md5
> ImportError: No module named _md5
I have installed openssl according to a quick internet search but I don't know
if that's the problem or not.
What is the correct way to import and publish this Plone site? Thanks~
Answer: This issue is more about "how to enable the md5 module in Python". After
installing the required OS libs you should re-compile your python. Normally
using system's python it just works because the packages management system
takes care of everything but in your case, your Plone installation is using
that local installation of the Python intepreter that you see in the root
directory tree (Python-2.6). The shortest way to proceed for you is to
[download Python](http://www.python.org/ftp/python/2.6.5/Python-2.6.5.tgz) and
compile it again. After this, you should use your new Python interpreter to
run this:
$ /<whatever>/python -c "import md5"
if it returns nothing then you are ready to go with this:
$ cd zinstance
$ /<whatever>/python bootstrap.py -v 1.7.5
$ bin/buildout -Nv
**Edit** : BTW, before recompiling the Python intepreter you should take the
chance to install many other system dependencies that you may need:
sudo apt-get install build-essential libglib2.0-dev libssl-dev \
libxslt-dev libldap2-dev libsasl2-dev zlib1g-dev libjpeg62-dev \
libxml2-dev python-ldap python-dev python-tk python-lxml \
python-libxml2 wv poppler-utils xpdf libncurses5-dev libbz2-dev \
git liblcms1-dev libreadline-dev gettext
|
Wrong import of waxeye parser
Question: So I tried to use parses generator [waxeye](http://waxeye.org/), but as I try
to use tutorial example of program in python using generated parser I get
error:
AttributeError: 'module' object has no attribute 'Parser'
Here's part of code its reference to:
import waxeye
import parser
p = parser.Parser()
The last line cause the error. Parser generated by waxeye I put in the same
directory as the **init**.py . It's parser.py .
Anyone have any idea what's wrong with my code?
* * *
**Edit 20-05-2013:**
Beggining of the parser.py file:
from waxeye import Edge, State, FA, WaxeyeParser
class Parser (WaxeyeParser):
Answer: It might be that the `parser` module you're importing is not the one you want.
Try inserting a:
print parser.__file__
right after the imports, or try naming your parser module differently.
Also, if working with Python 2.7 its good to enable `absolute_imports` from
the `__future__` module.
|
WebDriver claiming editable element is not editable
Question: I'm running a simple test with Selenium WebDriver and Python to send/verify
receipt of email.
Once I switch to the iframe containing the message body and locate the
editable body element and try to clear it out, the following exception is
thrown:
Traceback (most recent call last):
driver.find_element_by_xpath("//body[@role='textbox']").clear()
selenium.common.exceptions.WebDriverException: Message: 'Element must be user-editable in order to clear it.'
Here is the script used to create an email:
driver.find_element_by_name("to").clear()
driver.find_element_by_name("to").send_keys("[email protected]")
localtime = time.asctime( time.localtime(time.time()) )
subj = ("TEST - " + localtime)
print(subj)
driver.find_element_by_name("subjectbox").clear()
driver.find_element_by_name("subjectbox").send_keys(subj)
body = ("TEST")
bodyFrame = driver.find_element_by_xpath("//td[@class='Ap']//iframe")
driver.switch_to_frame(bodyFrame)
driver.find_element_by_xpath("//body[@role='textbox']").clear()
driver.find_element_by_xpath("//body[@role='textbox']").send_keys(body)
driver.find_element_by_xpath("/div[@role='button' and contains(text(), 'Send')]").click()
driver.find_element_by_link_text("Inbox (1)").click()
However, the message body is explicitly user-editable. Below I've included a
snippet of the message body HTML that I have WebDriver directed to within the
iframe nested in the td class "Ap" that explicitly shows that it's editable.
<body id=":3" class="editable LW-avf" style="min-width: 0px; width: 437px;
border: 0px none; margin: 0px; background: none repeat scroll 0% 0% transparent;
height: 100%; overflow: hidden; direction: ltr; min-height: 121px;" hidefocus="true"
g_editable="true" role="textbox">
IDE is able to access all of the elements, but what could be keeping WebDriver
from accessing them?
**EDIT**
Well, I just found out what was causing the exception:
I found that by removing the following line from the script allowed WebDriver
to write in the textbox.
driver.find_element_by_xpath("//body[@role='textbox']").clear()
Though I wonder why it would throw the exception that the element must be
editable, but allows it to send_keys to the element without issue?
Answer: Have you tried with [Action Chains](http://selenium-
python.readthedocs.org/en/latest/api.html#module-
selenium.webdriver.common.action_chains)?
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
driver.switch_to_frame(bodyFrame)
ActionChains(driver).send_keys(Keys.CONTROL, "a").perform()
ActionChains(driver).send_keys("Test").perform()
# alternative:
# body_ele = driver.find_element_by_xpath("//body[@role='textbox']")
# body_ele.send_keys(Keys.CONTROL, 'a')
# body_ele.send_keys("Test")
In C#, `IWebElement.Clear` says "If this element is a text entry element, the
Clear() method will clear the value. It has no effect on other elements. Text
entry elements are defined as elements with INPUT or TEXTAREA tags.".
Similarly, in [python source
code](https://code.google.com/p/selenium/source/browse/py/selenium/webdriver/remote/webelement.py#61),
it says "Clears the text if it's a text entry element.", while in your case,
`body` is not a text entry element.
|
A simple regexp in python
Question: My program is a simple calculator, so I need to parse te expression which the
user types, to get the input more user-friendly. I know I can do it with
regular expressions, but I'm not familar enough about this.
So I need transform a input like this:
import re
input_user = "23.40*1200*(12.00-0.01)*MM(H2O)/(8.314 *func(2*x+273.15,x))"
re.some_stuff( ,input_user) # ????
in this:
"23.40*1200*(12.00-0.01)*MM('H2O')/(8.314 *func('2*x+273.15',x))"
just adding these simple quotes inside the parentheses. How can I do that?
UPDATE:
To be more clear, I want add simple quotes after every sequence of characters
"MM(" and before the ")" which comes after it, and after every sequence of
characters "func(" and before the "," which comes after it.
Answer: This is the sort of thing where regexes can work, but they can potentially
result in major problems unless you consider exactly what your input will be
like. For example, can whatever is inside MM(...) contain parentheses of its
own? Can the first expression in func( contain a comma? If the answers to both
questions is no, then the following could work:
input_user2 = re.sub(r'MM\(([^\)]*)\)', r"MM('\1')", input_user)
output = re.sub(r'func\(([^,]*),', r"func('\1',", input_user)
However, this will _not_ work if the answer to either question is yes, and
even without that could cause problems depending upon what sort of inputs you
expect to receive. Essentially, the first re.sub here looks for MM( ('MM('),
followed by any number (including 0) of characters that aren't a close-
parenthesis ('([^)]*)') that are then stored as a group (caused by the extra
parentheses), and then a close-parenthesis. It replaces that section with the
string in the second argument, where \1 is replaced by the first and only
group from the pattern. The second re.sub works similarly, looking for any
number of characters that aren't a comma.
If the answer to either question is yes, then regexps aren't appropriate for
the parsing, as your language would not be regular. [The answer to this
question](http://stackoverflow.com/questions/1732348/regex-match-open-tags-
except-xhtml-self-contained-tags/1732454#1732454), while discussing a
different application, may give more insight into that matter.
|
mod_wsgi loading python script from wrong Pyramid app directory
Question: I have two apps with nearly identical code base (same functionality, just
different branding) that I am trying to do virtual hosting with using mod_wsgi
and apache.
the virtual host settings for both apps (in two separate files) are identical
(with the exception of paths of course)
WSGIPythonHome /home/ubuntu/BASELINE
<VirtualHost *:80>
ServerName appA.com
ServerAlias www.appA.com
ServerAdmin [email protected]
DocumentRoot /home/ubuntu/appA_virtualenv/appA-server/appA
ErrorLog /home/ubuntu/appA_virtualenv/appA-server/error.log
CustomLog /home/ubuntu/appA_virtualenv/appA-server/access.log combined
Alias /static/ /home/ubuntu/appA_virtualenv/appA-server/appA/appA/static/
WSGIApplicationGroup %{GLOBAL}
WSGIPassAuthorization On
WSGIDaemonProcess appA user=www-data group=www-data \
python-path=/home/ubuntu/appA_virtualenv/lib/python2.7/site-packages/ \
home=/home/ubuntu/appA_virtualenv/appA-server/appA/
WSGIProcessGroup appA
WSGIScriptAlias / /home/ubuntu/appA_virtualenv/appA-server/appA.wsgi
<Directory /home/ubuntu/appA_virtualenv/appA-server>
WSGIProcessGroup appA
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
.
<VirtualHost *:80>
ServerName appB.com
ServerAlias www.appB.com
ServerAdmin [email protected]
DocumentRoot /home/ubuntu/appB_virtualenv/server/appB
ErrorLog /home/ubuntu/appB_virtualenv/server/error.log
CustomLog /home/ubuntu/appB_virtualenv/server/access.log combined
Alias /static/ /home/ubuntu/appB_virtualenv/server/appB/appB/static/
WSGIApplicationGroup %{GLOBAL}
WSGIPassAuthorization On
WSGIDaemonProcess appB user=www-data group=www-data \
python-path=/home/ubuntu/appB_virtualenv/lib/python2.7/site-packages/ \
home=/home/ubuntu/appB_virtualenv/server/appB/
WSGIProcessGroup appB
WSGIScriptAlias / /home/ubuntu/appB_virtualenv/server/appB.wsgi
<Directory /home/ubuntu/appB_virtualenv/server>
WSGIProcessGroup appB
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
Contents of `appA.wsgi`
import os
os.environ['PYTHON_EGG_CACHE'] = '/home/ubuntu/appA_virtualenv/appA-server/python-eggs'
from pyramid.paster import get_app, setup_logging
ini_path = '/home/ubuntu/appA_virtualenv/appA-server/appA/development.ini'
setup_logging(ini_path)
application = get_app(ini_path, 'main')
Contents of `appB.wsgi`
import os
os.environ['PYTHON_EGG_CACHE'] = '/home/ubuntu/appB_virtualenv/server/python-eggs'
from pyramid.paster import get_app, setup_logging
ini_path = '/home/ubuntu/appB_virtualenv/server/appB/development.ini'
setup_logging(ini_path)
application = get_app(ini_path, 'main')
I enabled both sites in apache and realize that when accessing appA, the
python scripts in appB's directory is loaded instead. I confirmed this by
adding a `print` statement in the `__init__.py` of both apps and the text for
appB is printed even when I try to access appA.
I then disabled appB by `$ sudo a2dissite appB`. appB.com fails to load, but
appA.com is still loading appB's codes...
I added the following to **appB** `__init__.py` (Note: NOT **appA**)
print sys.path[0]
print os.getcwd()
the outputs are
/home/ubuntu/appA_virtualenv/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg
/home/ubuntu/appA_virtualenv/appA-server/appA
which is beyond my comprehension because the output point correctly to appA's
directory, yet the `print` are added to appB's `__init__.py` which is located
in `/home/ubuntu/appB_virtualenv/server/appB/appB/__init__.py`
Also, I have already disabled appB and the apache settings no longer refer to
appB's directory anywhere anymore, so why is appA still loading appB's
scripts?!
what am I doing wrong? What settings do I need to change to get appA to load
the scripts in its own directory? Thanks
* * *
Additional checks as suggested by Graham
[Embedded or Daemon
Mode](http://code.google.com/p/modwsgi/wiki/CheckingYourInstallation#Embedded_Or_Daemon_Mode)
* Daemon mode: `mod_wsgi.process_group = 'appA'`
[Sub Interpreter Being
Used](http://code.google.com/p/modwsgi/wiki/CheckingYourInstallation#Sub_Interpreter_Being_Used)
* Main Interpreter: `mod_wsgi.application_group = ''`
[Request
Environment](http://code.google.com/p/modwsgi/wiki/DebuggingTechniques#Displaying_Request_Environment)
* `PATH_TRANSLATED: '/home/ubuntu/appA_virtualenv/appA-server/appA.wsgi/'`
* `SERVER_NAME: 'appA.com'`
* `SCRIPT_FILENAME: '/home/ubuntu/appA_virtualenv/appA-server/appA.wsgi'`
* `mod_wsgi.application_group: ''`
* `mod_wsgi.process_group: 'appA'`
* `mod_wsgi.version: (3, 4)`
Answer: Nothing looks an issue on first glance.
Use:
* <http://code.google.com/p/modwsgi/wiki/CheckingYourInstallation#Embedded_Or_Daemon_Mode>
* <http://code.google.com/p/modwsgi/wiki/CheckingYourInstallation#Sub_Interpreter_Being_Used>
to confirm what process and application group they are each executing in.
Use:
* <http://code.google.com/p/modwsgi/wiki/DebuggingTechniques#Displaying_Request_Environment>
to see what SERVER_NAME is set to for each in requests.
Edit your question with the results.
* * *
UPDATE 1
Where there are two VirtualHost's in the Apache configuration, one cause of
requests always ending up at the first VirtualHost and never reaching the
second is because NameVirtualHost directive isn't being specified for the port
the VirtualHost's are listening on. Normally on Linux this isn't a problem
though for port 80 as it would be on by default.
The other reason it can occur is because the host name used in the URL doesn't
actually match either the ServerName or ServerAlias in the desired
VirtualHost. When this happens Apache will fallback to directing the URL to
the first VirtualHost it found when the Apache configuration file was read. To
catch when this is occurring, it is generally a good idea to declare a default
VirtualHost which is read first and which denies all access. At least this way
a request will not end up at the wrong VirtualHost and will be blocked.
For details of this issue with it falling back to the first read VirtualHost,
see discussion in:
* <http://blog.dscpl.com.au/2012/10/requests-running-in-wrong-django.html>
Try defining the default VirtualHost and see whether this issue of it falling
back to the first VirtualHost is the issue. Then you can workout what is the
issue with the Apache configuration which is causing that to occur.
|
Python unity indicator applet and glade child window
Question: I have created an unity indicator applet with python and glade. Here is the
screenshot that appears when indicator applet is clicked. You can see the
preferences menu. When this preferences menu is clicked, it opens a new
window.
`Indicator Applet Menu`

`Preference Window`

Now the problem is when I click on close button, the whole application exists.
The code that triggers the preference window is as shown below :
def action_preferences(self, widget):
'''
Show the preferences window
'''
base = PreferenceWindow()
base.main()
self.menu_setup()
**preference.py** has the following code :
import sys
import json
import pynotify
try:
import pygtk
pygtk.require("2.0")
except:
pass
try:
import gtk
import gtk.glade
except:
print("GTK is not Available")
sys.exit(1)
class PreferenceWindow:
ui = None
configs = {}
notify = None
window = None
def __init__(self):
if not pynotify.init ("nepal-loadshedding"):
sys.exit (1)
self.ui = gtk.glade.XML("pref_ui.glade")
# Get the preference saved previously
self.configs = self.parse_configs()
saved_group_value = str(self.configs.get("GROUP"))
self.ui.get_widget("text_group_number").set_text(saved_group_value)
dic = {
"on_btn_pref_ok_clicked":self.on_save_preference,
"on_btn_pref_close_clicked":self.on_close,
"on_preference_window_destroy":self.on_quit,
}
self.ui.signal_autoconnect(dic)
if self.window is None:
self.window = self.main()
def parse_configs(self):
self.configs = json.load(open("config.txt"))
return self.configs
def save_configs(self, key, value):
self.configs[key] = int(value)
json.dump(self.configs, open("config.txt", "wb"))
return True
def on_save_preference(self, widget):
group_number = self.ui.get_widget("text_group_number").get_text()
self.save_configs("GROUP", group_number)
# try the icon-summary case
if self.notify == None:
self.notify = pynotify.Notification ("Nepal Loadshedding", "Group saved successfully to : " + group_number)
else:
self.notify.update("Nepal Loadshedding", "Group saved successfully to : " + group_number)
self.notify.set_timeout(100)
self.notify.show()
print "Saved successfully"
def on_close(self, widget):
print 'close event called'
def on_quit(self, widget):
sys.exit(0)
def main(self):
gtk.main()
Answer: You can't call `sys.exit()` because it will make your entire application to
terminate (as you can see). What you have to do is call
[`gtk.main_quit()`](http://www.pygtk.org/docs/pygtk/gtk-
functions.html#function-gtk--main-quit). When you click _close_ button, you
can destroy the window.
def on_close(self, widget):
self.ui.get_widget("<window-name>").destroy()
def on_quit(self, widget):
gtk.main_quit()
Additionally, you call two times `PreferencesWindow.main()` (one at the bottom
of `__init__()` and the second time after instantiation, with `base.main()`),
which in turn calls to [`gtk.main()`](http://www.pygtk.org/docs/pygtk/gtk-
functions.html#function-gtk--main). You have to remove one of them or your
application will get stuck on the second one.
|
Best way to specify path to binary for a wrapper module
Question: I write a module that wraps functionality of an external binary.
For example, I wrap `ls` program into a python module `my_wrapper.py`
import my_wrapper
print my_wrapper.ls('some_directory/')
# list files in some_directory
and in my_wrapper.py I do:
# my_wrapper.py
PATH_TO_LS = '/bin/ls'
def ls(path):
proc = subprocess.Popen([PATH_TO_LS, path], ...)
...
return paths
(of course, I do not wrap `ls` but some other binary)
The binary might be installed with an arbitrary location, like `/usr/bin/`,
`/opt/` or even at the same place as the python script (`./binaries/`)
**Question:**
What would be the cleanest (from the user perspective) way to set the path to
the binary?
* Should the user specify `my_wrapper.PATH_TO_LS = ...` or invoke some `my_wrapper.set_binary_path(path)` at the beginning of his script?
* Maybe it would be better to specify it in `env`, and the wrapper would find it with `os.environ`?
* If the wrapper is distributed as egg, can I require during the installation, that the executable is already present in the system (see below)?
egg example:
# setup.py
setup(
name='my_wrapper',
requires_binaries=['the_binary'] # <--- require that the binary is already
# installed and on visible
# on execution path
)
or
easy_install my_wrapper BINARY_PATH=/usr/local/bin/the_binary
Answer: Create a "configuration object" with sane defaults. Allow the consumer to
modify the values as appropriate. Accept a configuration object instance to
your functions, taking the one you created by default.
|
Custom markers with screen coordinate size in (older) matplotlib
Question: Originally, I was hoping that I could create a sort of a class for a marker in
`matplotlib`, which would be a square with text showing the, say, x coordinate
and a label, so I could instantiate it with something like (pseudocode):
plt.plot(..., marker=myMarkerClass(label="X:"), ... )
... but as far as I can see, you cannot do stuff like that.
However, it seems that customization of markers is not available in older
`matplotlib`; so I'd like to reduce my question to: how to get custom (path)
markers in older `matplotlib`, so their sizes are defined in screen
coordinates (so markers don't scale upon zoom)? To clarify, here are some
examples:
## Default (uncustomized) markers
Below is an example with the default `matplotlib` markers, which works with
older `matplotlib`. Note that I've tried instead of using `pyplot.plot()`, I'm
trying to work with `matplotlib.figure.Figure` directly (as that is the form
usually used with diverse backends), requiring use of "figure manager" (see
also [matplotlib-devel - Backends object
structure](http://matplotlib.1069221.n5.nabble.com/Backends-object-structure-
td29565.html)):
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.figure
import numpy as np
t = np.arange(0.0,1.5,0.25)
s = np.sin(2*np.pi*t)
mfigure = matplotlib.figure.Figure(figsize=(5,4), dpi=100)
ax = mfigure.add_subplot(111)
ax.plot(t,s, marker='o', color='b', markerfacecolor='orange', markersize=10.0)
fig = plt.figure() # create something (fig num 1) for fig_manager
figman = matplotlib._pylab_helpers.Gcf.get_fig_manager(1)
figman.canvas.figure = mfigure # needed
mfigure.set_canvas(figman.canvas) # needed
plt.show()
If we do an arbitrary zoom rect here, the markers remain the same size:

## Customized markers via Path
This is documented in [artists (Line2D.set_marker) — Matplotlib 1.2.1
documentation](http://matplotlib.org/api/artist_api.html#matplotlib.lines.Line2D.set_marker);
however, it doesn't work with older `matplotlib`; here's an example:
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.figure
import matplotlib.path
import numpy as np
print("matplotlib version {0}".format(matplotlib.__version__))
def getCustomSymbol1(inx, iny, sc, yasp):
verts = [
(-0.5, -0.5), # left, bottom
(-0.5, 0.5), # left, top
(0.5, 0.5), # right, top
(0.5, -0.5), # right, bottom
(-0.5, -0.5), # ignored
]
codes = [matplotlib.path.Path.MOVETO,
matplotlib.path.Path.LINETO,
matplotlib.path.Path.LINETO,
matplotlib.path.Path.LINETO,
matplotlib.path.Path.CLOSEPOLY,
]
pathCS1 = matplotlib.path.Path(verts, codes)
return pathCS1, verts
t = np.arange(0.0,1.5,0.25)
s = np.sin(2*np.pi*t)
mfigure = matplotlib.figure.Figure(figsize=(5,4), dpi=100)
ax = mfigure.add_subplot(111)
pthCS1, vrtCS1 = getCustomSymbol1(0,0, 1,1)
# here either marker=pthCS1 or marker=np.array(vrtCS1)
# have the same effect:
ax.plot(t,s, marker=pthCS1, markerfacecolor='orange', markersize=10.0)
#ax.plot(t,s, marker=np.array(vrtCS1), markerfacecolor='orange', markersize=10.0)
fig = plt.figure() # create something (fig num 1) for fig_manager
figman = matplotlib._pylab_helpers.Gcf.get_fig_manager(1)
figman.canvas.figure = mfigure # needed
mfigure.set_canvas(figman.canvas) # needed
plt.show()
This runs fine for me in newer `matplotlib`, but fails in the older:
$ python3.2 test.py
matplotlib version 1.2.0
$ python2.7 test.py # marker=pthCS1
matplotlib version 0.99.3
Traceback (most recent call last):
File "test.py", line 36, in <module>
ax.plot(t,s, marker=pthCS1, markerfacecolor='orange', markersize=10.0)
...
File "/usr/lib/pymodules/python2.7/matplotlib/lines.py", line 804, in set_marker
self._markerFunc = self._markers[marker]
KeyError: Path([[-0.5 -0.5]
[-0.5 0.5]
[ 0.5 0.5]
[ 0.5 -0.5]
[-0.5 -0.5]], [ 1 2 2 2 79])
$ python2.7 test.py # marker=np.array(vrtCS1)
matplotlib version 0.99.3
Traceback (most recent call last):
File "test.py", line 38, in <module>
ax.plot(t,s, marker=np.array(vrtCS1), markerfacecolor='orange', markersize=10.0)
...
File "/usr/lib/pymodules/python2.7/matplotlib/lines.py", line 798, in set_marker
if marker not in self._markers:
TypeError: unhashable type: 'numpy.ndarray'
However, when it works in Python 3.2, the markers again keep their size across
zoom of the graph, as I'd expect:

... though note this issue: [Custom marker created from vertex list scales
wrong · Issue #1980 · matplotlib/matplotlib ·
GitHub](https://github.com/matplotlib/matplotlib/issues/1980), in respect to
this type of custom markers.
## Through Paths in PatchCollection
I've picked up parts of this code from some internet postings, but cannot find
the links now. In any case, we can avoid drawing the markers and
PatchCollection can be used, to draw what should be the markers. Here is the
code, which runs in older `matplotlib`:
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.figure
import matplotlib.path, matplotlib.patches, matplotlib.collections
import numpy as np
def getCustomSymbol1(inx, iny, sc, yasp):
verts = [
(inx-0.5*sc, iny-0.5*sc*yasp), # (0., 0.), # left, bottom
(inx-0.5*sc, iny+0.5*sc*yasp), # (0., 1.), # left, top
(inx+0.5*sc, iny+0.5*sc*yasp), # (1., 1.), # right, top
(inx+0.5*sc, iny-0.5*sc*yasp), # (1., 0.), # right, bottom
(inx-0.5*sc, iny-0.5*sc*yasp), # (0., 0.), # ignored
]
codes = [matplotlib.path.Path.MOVETO,
matplotlib.path.Path.LINETO,
matplotlib.path.Path.LINETO,
matplotlib.path.Path.LINETO,
matplotlib.path.Path.CLOSEPOLY,
]
pathCS1 = matplotlib.path.Path(verts, codes)
return pathCS1
def getXyIter(inarr):
# this supports older numpy, where nditer is not available
if np.__version__ >= "1.6.0":
return np.nditer(inarr.tolist())
else:
dimensions = inarr.shape
xlen = dimensions[1]
xinds = np.arange(0, xlen, 1)
return np.transpose(np.take(inarr, xinds, axis=1))
t = np.arange(0.0,1.5,0.25)
s = np.sin(2*np.pi*t)
mfigure = matplotlib.figure.Figure(figsize=(5,4), dpi=100)
ax = mfigure.add_subplot(111)
ax.plot(t,s)
customMarkers=[]
for x, y in getXyIter(np.array([t,s])): #np.nditer([t,s]):
#printse("%f:%f\n" % (x,y))
pathCS1 = getCustomSymbol1(x,y,0.05,1.5*500.0/400.0)
patchCS1 = matplotlib.patches.PathPatch(pathCS1, facecolor='orange', lw=1) # no
customMarkers.append(patchCS1)
pcolm = matplotlib.collections.PatchCollection(customMarkers)
pcolm.set_alpha(0.9)
ax.add_collection(pcolm)
fig = plt.figure() # create something (fig num 1) for fig_manager
figman = matplotlib._pylab_helpers.Gcf.get_fig_manager(1)
figman.canvas.figure = mfigure # needed
mfigure.set_canvas(figman.canvas) # needed
plt.show()
Now, here I tried to take figure initial aspect ratio into consideration and
indeed, at first render, the "markers" look right in respect to size - but...:

... when we try to do arbitrary zoom, it is obvious that the paths have been
specified in data coordinates, and so their sizes change depending on the zoom
rect. (Another nuissance is that `facecolor='orange'` is not obeyed; but that
can be fixed with `pcolm.set_facecolor('orange')`)
So, is there a way that I can use PatchCollection as markers for older
`matplotlib`, in the sense that the rendered paths would be defined in screen
coordinates, so they would not change their size upon arbitrary zooming?
Answer: Many thanks to @tcaswell for the
[comment](http://stackoverflow.com/questions/16649970/custom-markers-with-
screen-coordinate-size-in-older-matplotlib#comment23952132_16649970) on
[blended
transform](http://matplotlib.org/users/transforms_tutorial.html#blended-
transformations) \- in trying to figure out why _that_ doesn't work for me, I
finally found the solution. First, the code - using, essentially, the default
marker engine of matplotlib (depending on whether using older matplotlib
(0.99) or newer one):
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.figure
import numpy as np
# create vertices and Path of custom symbol
def getCustomSymbol1():
verts = [
(0.0, 0.0), # left, bottom
(0.0, 0.7), # left, top
(1.0, 1.0), # right, top
(0.8, 0.0), # right, bottom
(0.0, 0.0), # ignored
]
codes = [matplotlib.path.Path.MOVETO,
matplotlib.path.Path.LINETO,
matplotlib.path.Path.LINETO,
matplotlib.path.Path.LINETO,
matplotlib.path.Path.CLOSEPOLY,
]
pathCS1 = matplotlib.path.Path(verts, codes)
return pathCS1, verts
if matplotlib.__version__ < "1.0.0":
# define a marker drawing function, that uses
# the above custom symbol Path
def _draw_mypath(self, renderer, gc, path, path_trans):
gc.set_snap(renderer.points_to_pixels(self._markersize) >= 2.0)
side = renderer.points_to_pixels(self._markersize)
transform = matplotlib.transforms.Affine2D().translate(-0.5, -0.5).scale(side)
rgbFace = self._get_rgb_face()
mypath, myverts = getCustomSymbol1()
renderer.draw_markers(gc, mypath, transform,
path, path_trans, rgbFace)
# add this function to the class prototype of Line2D
matplotlib.lines.Line2D._draw_mypath = _draw_mypath
# add marker shortcut/name/command/format spec '@' to Line2D class,
# and relate it to our custom marker drawing function
matplotlib.lines.Line2D._markers['@'] = '_draw_mypath'
matplotlib.lines.Line2D.markers = matplotlib.lines.Line2D._markers
else:
import matplotlib.markers
def _set_mypath(self):
self._transform = matplotlib.transforms.Affine2D().translate(-0.5, -0.5)
self._snap_threshold = 2.0
mypath, myverts = getCustomSymbol1()
self._path = mypath
self._joinstyle = 'miter'
matplotlib.markers.MarkerStyle._set_mypath = _set_mypath
matplotlib.markers.MarkerStyle.markers['@'] = 'mypath'
matplotlib.lines.Line2D.markers = matplotlib.markers.MarkerStyle.markers
# proceed as usual - use the new marker '@'
t = np.arange(0.0,1.5,0.25)
s = np.sin(2*np.pi*t)
mfigure = matplotlib.figure.Figure(figsize=(5,4), dpi=100)
ax = mfigure.add_subplot(111)
ax.plot(t,s, marker='@', color='b', markerfacecolor='orange', markersize=20.0)
fig = plt.figure() # create something (fig num 1) for fig_manager
figman = matplotlib._pylab_helpers.Gcf.get_fig_manager(1)
figman.canvas.figure = mfigure # needed
mfigure.set_canvas(figman.canvas) # needed
plt.show()
It shows a slightly "creative" marker (if I may say so myself `:)` ) - and
this is how it behaves under zoom:

... that is, exactly as I want it - markers keep their position in data
coordinates; however preserve their size under zooming.
* * *
### Discussion
One of the most confusing things for me here, was the following: Essentially,
you can specify a rectangle through an x,y coordinate as "location", and size
(height/width). So if I specify a rectangle at x,y=(2,3); with halfsize 2 (so,
square); then I can calculate its path _as vertices_ through:
[(x-hs,y-hs), (x-hs,y+hs), (x+hs,y+hs), (x+hs,y-hs)]
This is, essentially, what `getCustomSymbol1` was trying to return all along.
In addition, for instance `matplotlib.patches.Rectangle` is instantiated
through location and size, as in `Rectangle((x,y), width, height)`.
Now, the problem is - what I actually wanted, is that markers, as shapes,
_stay_ on their position - in data coordinates, so moving and zooming the
graph keeps their position _as data_ ; however, they should have kept their
size under zooming.
This means that I want `(x,y)` specified in one coordinate system (data), and
`size` (or `width`, `height`, or `halfsize`) specified in _another_ coordinate
system, in this case, the screen coordinate system: since I want the shapes to
keep their size under zoom, I actually want to keep their size _in screen
pixels_ the same!
That is why _no transformation_ as such would help in my case - any
transformation would work on _all_ the vertices of a path, as interpreted in a
single coordinate system! Whereas, what I want, would be to get something
like:
hsd = screen2dataTransform(10px)
[(x-hsd,y-hsd), (x-hsd,y+hsd), (x+hsd,y+hsd), (x+hsd,y-hsd)]
... and this recalculation of the vertices of the marker path would have to be
repeated each time the zoom level, or the figure pan, or the window size
changes.
As such, vertices/paths (and patches) and transformation alone cannot be used
for this purpose. However, thankfully, we can use `matplotlib`s own engine; we
simply have to know that any call to `ax.plot(...marker=...)` actually
delegates the drawing of markers to `matplotlib.lines.Line2D`; and `Line2D`
maintains an internal dict, which relates the marker one-character format
specifier/command (like `'o'`, `'*'` etc) to a specific drawing function; and
the drawing function, finally, does the size transformation in code like (in
the solution code above, the drawing is for the most part taken from the `'s'`
(square) marker implementation):
side = renderer.points_to_pixels(self._markersize)
transform = matplotlib.transforms.Affine2D().translate(-0.5, -0.5).scale(side)
Note that this is the case for older `matplotlib` (0.99.3 in my case); for
newer `matplotlib` (1.2.0 in my case), there is a separate class `MarkerStyle`
which maintains the relationship between the marker format specifier, and the
function - and the function is not `_draw_` anymore, it is just `_set_` \- but
other than that, it is the same principle.
NB: I'm actually not sure when `MarkerStyle` was introduced, I could only find
[matplotlib.markers — Matplotlib 1.3.x
documentation](http://cbio.ensmp.fr/~nvaroquaux/matplotlib/doc/api/markers_api.html)
and it doesn't say; so that `if matplotlib.__version__ < "1.0.0":` in the code
above could be wrong; but worksforme (fornow).
Because the markers size is, so to speak, managed separately (from its
position) - that means that you don't have to do any special calculation in
your custom marker Path specification; all you need to do is make sure its
vertices fit in the range (0.0,0.0) to (1.0, 1.0) - the marker drawing engine
will do the rest.
Well, I hope I understood this right - but if there are other approaches that
work like this, I'd sure like to know about those :)
Hope this helps someone,
Cheers!
|
Given f, is there an automatic way to calculate fprime for Newton's method?
Question: The following was ported from the pseudo-code from the Wikipedia article on
[Newton's method](http://en.wikipedia.org/wiki/Newton%27s_method):
#! /usr/bin/env python3
# https://en.wikipedia.org/wiki/Newton's_method
import sys
x0 = 1
f = lambda x: x ** 2 - 2
fprime = lambda x: 2 * x
tolerance = 1e-10
epsilon = sys.float_info.epsilon
maxIterations = 20
for i in range(maxIterations):
denominator = fprime(x0)
if abs(denominator) < epsilon:
print('WARNING: Denominator is too small')
break
newtonX = x0 - f(x0) / denominator
if abs(newtonX - x0) < tolerance:
print('The root is', newtonX)
break
x0 = newtonX
else:
print('WARNING: Not able to find solution within the desired tolerance of', tolerance)
print('The last computed approximate root was', newtonX)
**Question**
Is there an automated way to calculate some form of `fprime` given some form
of `f` in Python 3.x?
Answer: A common way of approximating the derivative of `f` at `x` is using a finite
difference:
f'(x) = (f(x+h) - f(x))/h Forward difference
f'(x) = (f(x+h) - f(x-h))/2h Symmetric
The best choice of `h` depends on `x` and `f`: mathematically the difference
approaches the derivative as h tends to 0, but the method suffers from loss of
accuracy due to catastrophic cancellation if `h` is too small. Also x+h should
be distinct from x. Something like `h = x*1e-15` might be appropriate for your
application. See also [implementing the derivative in
C/C++](http://stackoverflow.com/questions/1559695/implementing-the-derivative-
in-c-c).
You can avoid approximating f' by using the [secant
method](http://en.wikipedia.org/wiki/Secant_method). It doesn't converge as
fast as Newton's, but it's computationally cheaper and you avoid the problem
of having to calculate the derivative.
|
Training the OpenCV NormalBayesClassifier in Python
Question: I'm trying to use the NormalBayesClassifier to classify images produced by a
Foscam 9821W webcam. They're 1280x720, initially in colour but I'm converting
them to greyscale for classification.
I have some Python code (up at <http://pastebin.com/YxYWRMGs>) which tries to
iterate over sets of ham/spam images to train the classifier, but whenever I
call train() OpenCV tries to allocate a huge amount of memory and throws an
exception.
mock@behemoth:~/OpenFos/code/experiments$ ./cvbayes.py --ham=../training/ham --spam=../training/spam
Image is a <type 'numpy.ndarray'> (720, 1280)
...
*** trying to train with 8 images
responses is [2, 2, 2, 2, 2, 2, 1, 1]
OpenCV Error: Insufficient memory (Failed to allocate 6794772480020 bytes) in OutOfMemoryError, file /build/buildd/opencv-2.3.1/modules/core/src/alloc.cpp, line 52
Traceback (most recent call last):
File "./cvbayes.py", line 124, in <module>
classifier = cw.train()
File "./cvbayes.py", line 113, in train
classifier.train(matrixData,matrixResp)
cv2.error: /build/buildd/opencv-2.3.1/modules/core/src/alloc.cpp:52: error: (-4) Failed to allocate 6794772480020 bytes in function OutOfMemoryError
I'm experienced with Python but a novice at OpenCV so I suspect I'm missing
out some crucial bit of pre-processing.
Examples of the images I want to use it with are at
<https://mocko.org.uk/choowoos/?m=20130515>. I have tons of training data
available but initially I'm only working with 8 images.
Can someone tell me what I'm doing wrong to make the NormalBayesClassifier
blow up?
Answer: Eventually found the problem - I was using NormalBayesClassifier wrong. It
isn't meant to be fed dozens of HD images directly: one should first munge
them using OpenCV's other algorithms.
I have ended up doing the following: \+ Crop the image down to an area which
may contain the object \+ Turn image to greyscale \+ Use
cv2.goodFeaturesToTrack() to collect features from the cropped area to train
the classifier.
A tiny number of features works for me, perhaps because I've cropped the image
right down and its fortunate enough to contain high-contrast objects that get
obscured for one class.
The following code gets as much as 95% of the population correct:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import cv2
import sys, os.path, getopt
import numpy, random
def _usage():
print
print "cvbayes trainer"
print
print "Options:"
print
print "-m --ham= path to dir of ham images"
print "-s --spam= path to dir of spam images"
print "-h --help this help text"
print "-v --verbose lots more output"
print
def _parseOpts(argv):
"""
Turn options + args into a dict of config we'll follow. Merge in default conf.
"""
try:
opts, args = getopt.getopt(argv[1:], "hm:s:v", ["help", "ham=", 'spam=', 'verbose'])
except getopt.GetoptError as err:
print(err) # will print something like "option -a not recognized"
_usage()
sys.exit(2)
optsDict = {}
for o, a in opts:
if o == "-v":
optsDict['verbose'] = True
elif o in ("-h", "--help"):
_usage()
sys.exit()
elif o in ("-m", "--ham"):
optsDict['ham'] = a
elif o in ('-s', '--spam'):
optsDict['spam'] = a
else:
assert False, "unhandled option"
for mandatory_arg in ('ham', 'spam'):
if mandatory_arg not in optsDict:
print "Mandatory argument '%s' was missing; cannot continue" % mandatory_arg
sys.exit(0)
return optsDict
class ClassifierWrapper(object):
"""
Setup and encapsulate a naive bayes classifier based on OpenCV's
NormalBayesClassifier. Presently we do not use it intelligently,
instead feeding in flattened arrays of B&W pixels.
"""
def __init__(self):
super(ClassifierWrapper,self).__init__()
self.classifier = cv2.NormalBayesClassifier()
self.data = []
self.responses = []
def _load_image_features(self, f):
image_colour = cv2.imread(f)
image_crop = image_colour[327:390, 784:926] # Use the junction boxes, luke
image_grey = cv2.cvtColor(image_crop, cv2.COLOR_BGR2GRAY)
features = cv2.goodFeaturesToTrack(image_grey, 4, 0.02, 3)
return features.flatten()
def train_from_file(self, f, cl):
features = self._load_image_features(f)
self.data.append(features)
self.responses.append(cl)
def train(self, update=False):
matrix_data = numpy.matrix( self.data ).astype('float32')
matrix_resp = numpy.matrix( self.responses ).astype('float32')
self.classifier.train(matrix_data, matrix_resp, update=update)
self.data = []
self.responses = []
def predict_from_file(self, f):
features = self._load_image_features(f)
features_matrix = numpy.matrix( [ features ] ).astype('float32')
retval, results = self.classifier.predict( features_matrix )
return results
if __name__ == "__main__":
opts = _parseOpts(sys.argv)
cw = ClassifierWrapper()
ham = os.listdir(opts['ham'])
spam = os.listdir(opts['spam'])
n_training_samples = min( [len(ham),len(spam)])
print "Will train on %d samples for equal sets" % n_training_samples
for f in random.sample(ham, n_training_samples):
img_path = os.path.join(opts['ham'], f)
print "ham: %s" % img_path
cw.train_from_file(img_path, 2)
for f in random.sample(spam, n_training_samples):
img_path = os.path.join(opts['spam'], f)
print "spam: %s" % img_path
cw.train_from_file(img_path, 1)
cw.train()
print
print
# spam dir much bigger so mostly unused, let's try predict() on all of it
print "predicting on all spam..."
n_wrong = 0
n_files = len(os.listdir(opts['spam']))
for f in os.listdir(opts['spam']):
img_path = os.path.join(opts['spam'], f)
result = cw.predict_from_file(img_path)
print "%s\t%s" % (result, img_path)
if result[0][0] == 2:
n_wrong += 1
print
print "got %d of %d wrong = %.1f%%" % (n_wrong, n_files, float(n_wrong)/n_files * 100, )
Right now I'm training it with a random subset of the spam, simply because
there's much more of it and you should have a roughly equal amount of training
data for each class. With better curated data (e.g. always include samples
from dawn and dusk when lighting is different) it would probably be higher.
Perhaps even a NormalBayesClassifier is the wrong tool for the job and I
should experiment with motion detection across consecutive frames - but at
least the Internet has an example to pick apart now.
|
How to pop up the python console?
Question: well what i am trying to do is, I'm building a small compiler only for
arithmetic evaluation using python! String of any length should be accepted
and also, i need to pop up a console where the user can enter his query! Can
anyone help me out with the popup of the console?
Answer:
os.system("python")
will open a new python window ...
raw_input("Enter Equation:")
would just get a single equation from the user
not sure if either of those is what you are looking for ...
import wx
a = wx.App()
user_string = wx.GetTextFromUser("Enter Equation:")
would pop up a prompt for user input (as long as you have wx installed)
|
Python issue editing tkinter canvas items in a 2darray
Question: I'm using a raspberry pi as a communication front end for more complex
devices. I'm coding it in python, and including a gui to display the
information going through it.
My issue involves a grid of canvas text items of size 4x4, as referenced by a
2d array `dataText[][]`. I am editing the items using `itemconfigure()` to
update the displayed data.
The issue: when i update `dataText[y][x]`, no matter the numbers, it updates
the item at position (3,x) instead.
Demonstrative code:
from Tkinter import *
from ttk import Style
#gui class (tkinter loop)
class UI(Frame):
#data value field
dataText = [[0]*4]*4
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
#sets up the main window
self.parent.title("Power Converter Controller")
self.style = Style()
self.style.theme_use("default")
self.pack(fill=BOTH, expand=YES)
#configures padding along columns and rows
for i in range(4):
self.columnconfigure(i, pad=3, weight=1)
for i in range(7):
self.rowconfigure(i, pad=3, weight=1)
#creates a canvas at the top of the window. The canvas is used for
#displaying data
self.display = Canvas(self, width=600, height=170)
self.display.grid(column=0, row=0, columnspan=4, rowspan=4)
#draws canvas items that can be updated
self.dynamicCanvasItems(self.display)
def dynamicCanvasItems(self, canvas):
#initializes the grid text handles
for i in range(4):
for j in range(4):
self.dataText[i][j] = canvas.create_text(75*(j+1),25*(i+1),text = data[i][j], font=("Helvetica",20))
for i in range(4):
for j in range(4):
self.display.itemconfigure(self.dataText[i][j], text=5)
def main():
global root
global data
#initialize 2d data array
data = [[x]*4 for x in xrange(4)]
#initialize the ui loop
root = Tk()
root.geometry("600x300+600+300")
ui = UI(root)
#enter the ui loop
root.mainloop()
if __name__ == '__main__':
main()
The whole program is rather large, so I've cut out irrelevant portions. I made
sure that the redacted portions had no effect on the issue (by disabling them
and checking if the problem changed).
in the `dynamicCanvasItems()` method, the widgets are set up correctly. If you
disable the second dual for-loop, it displays this:
0 0 0 0
1 1 1 1
2 2 2 2
3 3 3 3
So the second dual for-loop should overwrite all of the widgets with 5.
However, this happens:
0 0 0 0
1 1 1 1
2 2 2 2
5 5 5 5
Does anyone know why?
Answer: It is because your initialization code is creating a list of lists, where each
sublist is a reference to the same object. You don't have a list of four
different sublists, you have a list of four references to the same list.
To prove this, add the following right after you initialize `dataText`:
print [id(x) for x in dataText]
You'll see that all four lists have the exact same internal id, meaning they
all reference the exact same list.
Compare what happens when you change your initialization code to this:
dataText = [
[0,0,0,0],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]
]
In the above, you are explicitly creating four unique lists, each with four
unique values.
|
python 3 csv data structure problems
Question: I have a csv file like this
Category Subcategory
-----------------------
cat panther
cat tiger
dog wolf
dog heyena
cat lion
dog beagle
Im trying to write a script that outputs something like this (order not
important):
animals = [
[['cat'], ['panther', 'tiger', 'lion']],
[['dog'], ['wolf', 'heyena', 'beagle']]
]
So far I am able to make a list of unique categories, and a list of unique sub
categories.
for p in infile:
if(p[0] not in catlist):
catlist.append(p[0])
if(p[1] not in subcatlist) :
subcatlist.append(p[1])
But I am having trouble writing the logic that says "if Category 'cat' is in
animals[], but 'panther' is not in 'cat', append it."
Ive played with zip() and dict() some, but Im pretty much just flailing about
here. Fairly new to python. Using Python 3.
Answer: It is a lot easier to use dictionaries if you want to map keys to some values.
Especially convenient for building them is
[defaultdict](http://docs.python.org/2/library/collections.html#collections.defaultdict).
Assuming your infile splits the input lines on blank, the following should
help:
from collections import defaultdict
animals = defaultdict(list)
for p in infile:
animals[p[0]].append(p[1])
|
regex - specifying high Unicode codepoints in Python
Question: In Python 3.3 I have no trouble using ranges of Unicode codepoints within
regular expressions:
>>> import re
>>> to_delete = '[\u0020-\u0090\ufb00-\uffff]'
>>> s = 'abcdABCD¯˘¸ðﺉ﹅ffl你我他'
>>> print(s)
abcdABCD¯˘¸ðﺉ﹅ffl你我他
>>> print(re.sub(to_delete, '', s))
¯˘¸ð你我他
It's clean and simple. But if I include codepoints of five hex digits, that is
to say anything higher than `\uffff`, such as `\u1047f`, as part of a range
beginning in four hex digits, I get an error:
>>> to_delete = '[\u0020-\u0090\ufb00-\u1047f]'
>>> print(re.sub(to_delete, '', s))
...
sre_constants.error: bad character range
There is no error if I start a new five-digit range, but I also do not get the
expected behavior:
>>> to_delete = '[\u0020-\u0090\ufb00-\uffff\u10000-\u1047f]'
>>> print(re.sub(to_delete, '', s))
你我他
(The symbols are codepoints `\u10000`, `\u10308`, and `\u10192`, respectively
and should have been replaced in the last `re.sub` operation.)
* * *
Following the instructions of the accepted answer:
>>> to_delete = '[\u0020-\u0090\ufb00-\uffff\U00010000-\U0001047F]'
>>> print(re.sub(to_delete, '', s))
¯˘¸ð你我他
Perfect. Uglesome in the extreme, but perfect.
Answer: `\u` only supports 16-bit codepoints. You need to use the 32-bit version,
`\U`. Note that it requires 8 digits, so you have to prepend a few 0s (e.g.
`\U00010D2B`).
Source: <http://docs.python.org/3/howto/unicode.html#unicode-literals-in-
python-source-code>
|
How to let python use negative numbers
Question: I've been making a linear equation calculator and I'm wondering how to let
python use negative numbers. Like int(), float() etc...
here is my code.
import time
print("Hello and welcome to the linear equation calculator.")
time.sleep(2)
print("Enter the first co-ordinate like this - (xx, yy): ")
coordnte1 = input()
print("Now enter the second co-ordinate like this, with the brackets, - (xx,yy): ")
coordnte2 = input()
print("Now the y-intercept: ")
yintrcpt = input()
ydif = coordnte2[1] - coordnte1[1]
xdif = coordnte2[0] - coodrnte1[0]
g = ydif / xdif
print("y = " + g + "x + " + yintrcpt)
And the problem:
Traceback (most recent call last):
File "C:/Users/Dale/Documents/GitHub/new_python_rpi_experiments/linear.py", line 17, in <module>
ydif = coordnte2[1] - coordnte1[1]
TypeError: unsupported operand type(s) for -: 'str' and 'str'
I'm very new to Python, so any help would be appreciated.
Answer: What your are reading from the input is a _string_ , you need to extract the
coordinates and convert them to _float_ , for example:
print("Enter the first co-ordinate like this - (xx, yy): ")
s = input()
Now `s = "(34, 23)"` is a _string_ and you need to process it (eliminate
parens, comma, etc...):
coords = [float(coord) for coord in s.strip('()').split(',')]
Now coords is a list(array) of floats and you can do `coords[0]- coords[1]`
and so on.
|
How to get multiple lines <li> below <ul> tag with regex in python
Question: I got this HTML tags that I've pulled from a website:
<ul><li>Some Keys in the UL List</li>
</ul>
<li>HKEY_LOCAL_MACHINE\SOFTWARE\Description</li>
<li>HKEY_LOCAL_MACHINE\SOFTWARE\Description\Microsoft</li>
<li>HKEY_LOCAL_MACHINE\SOFTWARE\Description\Microsoft\Rpc</li>
<li>HKEY_LOCAL_MACHINE\SOFTWARE\Description\Microsoft\Rpc\UuidTemporaryData</li>
</ul></ul>
<ul><li>Some objects in the UL LIST</li>
</ul>
<li>_SHuassist.mtx</li>
<li>MuteX.mtx</li>
<li>Something.mtx</li>
<li>Default.mtx</li>
<li>3$5.mtx</li>
</ul></ul>
How can I get the lines(text beteween `<li>` tags) between the `<ul>` tags.
They don't have any class to diff then.
I don't know too much about BeautifulSoup and Regex.
I want this result as example:
<li>_SHuassist.mtx</li>
<li>MuteX.mtx</li>
<li>Something.mtx</li>
<li>Default.mtx</li>
<li>3$5.mtx</li>
Answer: With `BeautifulSoup`:
>>> html = textabove
>>> from bs4 import BeautifulSoup as BS
>>> soup = BS(html)
>>> for ultag in soup.findAll('ul'):
... for litag in ultag.findAll('li'):
... print litag.text
Which prints:
Some Keys in the UL List
Some objects in the UL LIST
* * *
To get the latter `<li>` tags:
>>> for litag in soup.findAll('li'):
... if litag.text.endswith('.mtx'):
... print litag
...
<li>_SHuassist.mtx</li>
<li>MuteX.mtx</li>
<li>Something.mtx</li>
<li>Default.mtx</li>
<li>3$5.mtx</li>
|
Soundcloud: Getting all users who contributed a song to a group
Question: Whats the best way to get ALL users who contributed a song to a group? I'm
working with Python, is there any curl url which can do this? Thanks!
Answer: Looking through the [soundcloud
API](http://developers.soundcloud.com/docs/api/reference#playlists) sounds
like a good place to start. From what I understand you want the following URL
GET /groups/{id}/contributors | list of users who contributed a track to the group
While you can use urllib or cURL for this task, I highly recommend using the
python [Requests](http://docs.python-requests.org/en/latest/) library which
will simplify any of the requests. The actual python requests code you will
probably end up using will look something like this
import requests
group_id = '' # FILL IN THE GROUP ID
client_id = '' # FILL IN THE CLIENT ID
r = requests.get('https://api.soundcloud.com/groups/%s/contributors?client_id=%s' %(group_id, client_id))
And then the variable `r` would contain the response from the server.
|
How to understand python classes?
Question: Hello I'm learning python, it is also my first language. I'm trying to figure
out how classes work. I have this small code and I can't get it to work after
a week of searching. Thank you for helping me.
Also I'm trying to figure out what getattr and super do. I read on the
documentation but its not easy for me to understand. English is not my native
language and its a little difficult to understand sometimes.If you can explain
this two things or if you know any website that explains it in a simple way I
would really thank you for it.
here is the code:
import sys
class Map(object):
dicti = {'stuff': stuff(),
'more_stuff': more_stuff()
}
class Stuff:
def stuff(self):
print "did it work?"
next = raw_input("type next: ")
if next == "next":
return 'more_stuff'
else:
print "what? lets try again."
return 'stuff'
class MoreStuff:
def more_stuff(self):
print "ok"
next = raw_input('type next: ')
if next == "next":
return 'stuff'
else:
print "bye."
sys.exit(0)
class NewClass(Map):
def __init__(self, themap):
self.themap = themap
def Continu(self):
next = self.themap
while True:
print "----"
room = next()
a_test = NewClass('stuff')
a_test.Continu()
Answer: You are passing the string `'stuff'` into `NewClass`, so that is becoming
`self.themap`
later you are assigning `next = self.themap`, so now `next` is also a
reference to the string `'stuff'`.
`room = next()` will fail because you can't call a string
|
"execution_count" error when running a job on a remote IPython cluster
Question: I am running an IPython cluster (SSH) on a remote Linux machine, and I am
using Mac OS X with IPython to use that cluster. In IPython on Mac I write:
from IPython.parallel import Client
c = Client('~/ipcontroller-client.json', sshserver="me@remote_linux_machine")
dview=c[:]
dview.scatter('m', arange(100))
where `'~/ipcontroller-client.json'` is the file copied from
`remote_linux_machine`. Everything works up to this point.
When I try to use parallel magic `%px` I get an error:
/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/IPython/parallel/client/client.pyc
in __init__(self, msg_id, content, metadata)
80 self.msg_id = msg_id
81 self._content = content
---> 82 self.execution_count = content['execution_count']
83 self.metadata = metadata
84
KeyError: 'execution_count'
Same idea, but when I run the cluster on _localhost_ it works perfectly.
Should parallel magic work at all for remote SSH cluster case?
Answer: The problem is now fixed: one needs to make sure the IPython versions are the
same (mine are 0.13.2) on the cluster and on the machine you are using it.
On the Linux machine I had to specify the version I needed to install as the
standard IPython was installed with version 0.12.1:
sudo apt-get install ipython=0.13.2-1~ubuntu12.04.1
|
Using bzr with SFTP on Windows/Cygwin
Question: **Note: I'm not sure if this belongs on ServerFault or StackOverflow**
I'm currently working on a project which has an SFTP-only `bzr` repository.
All works fine using my Linux machine, but when using Windows with Cygwin I
get the following issue:
$ bzr checkout sftp://user@hostname/var/bzr/project
bzr: ERROR: Unsupported protocol for url "sftp://user@hostname/var/bzr/project": Unable to import paramiko (required for sftp support): No module named Crypto
I have installed Cygwin's `python-paramiko` package, so I'm not sure why it's
refusing to use it.
Any suggestions much appreciated.
_Clarification: This does work with Windows bazaar GUI tool & Windows `cmd`
shell, I'm just wondering if I can make it work in Cygwin as I prefer UNIXy
command line tools._
Answer: Played around with this today.
Had to install `python-crypto` which should be a prerequisite of `python-
paramiko` but isn't.
|
Python unittest report passed test
Question: Hello I have a test module like the following under "test.py":
class TestBasic(unittest.TestCase):
def setUp(self):
# set up in here
class TestA(TestBasic):
def test_one(self):
self.assertEqual(1,1)
def test_two(self):
self.assertEqual(2,1)
if __name__ == "__main__":
unittest.main()
And this works pretty good, but I need a way to print which test passed, for
example I could print the output to the console:
test_one: PASSED
test_two: FAILED
Now the twist, I could add a print statement right after the
self.assertEqual() and that would be a passed test and I could just print it,
but I need to run the test from a different module, let's say
"test_reporter.py" where I have something like this:
import test
suite = unittest.TestLoader().loadTestsFromModule(test)
results = unittest.TextTestRunner(verbosity=0).run(suite)
at this point with results is when I build a report.
So please any suggestion is welcome
Thanks !!
Answer: Like [Corey's comment](http://stackoverflow.com/questions/16679660/python-
unittest-report-passed-test#comment24002393_16679660) mentioned, if you set
`verbosity=2` unittest will print the result of each test run.
results = unittest.TextTestRunner(verbosity=2).run(suite)
* * *
If you want a little more flexibility - and you might since you are creating
suites and using test runners - I recommend that you take a look at [Twisted
Trial](http://twistedmatrix.com/trac/wiki/TwistedTrial). It extends Python's
`unittest` module and provides a few more assertions and reporting features.
Writing your tests will be exactly the same (besides subclassing
twisted.trial.unittest.TestCase vs python's unittest) so your workflow won't
change. You can still use your `TestLoader` but you'll have the options of
many more TestReporters
<http://twistedmatrix.com/documents/11.1.0/api/twisted.trial.reporter.html>.
For example, the default TestReporter is `TreeReporter` which returns the
following output: 
|
How to serialize the result of a query in python?
Question: I'm having trouble to serialize the result array from a query where one of its
projection is of datetime property.
My model class looks as follows:
class ActivitySummaries(ndb.Model):
registered_users = ndb.IntegerProperty()
activated_users = ndb.IntegerProperty()
company_registered = ndb.IntegerProperty()
broker_registered = ndb.IntegerProperty()
investor_registered = ndb.IntegerProperty()
deal_approved = ndb.IntegerProperty()
broker_approved = ndb.IntegerProperty()
investor_approved = ndb.IntegerProperty()
company_searched = ndb.IntegerProperty()
broker_searched = ndb.IntegerProperty()
investor_searched = ndb.IntegerProperty()
watchlisting = ndb.IntegerProperty()
closed_deals = ndb.IntegerProperty()
timestamp = ndb.DateTimeProperty(auto_now_add=True)
Query:
activities = cls.query()
**I want to send the the result array of the query in serialized form from
Python using JSON and de-serialize in JavaScript using JSON.**
I'm getting the following error:
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: ActivitySummaries(key=Key('ActivitySummaries', 923), activated_users=0, broker_approved=0, broker_registered=0, broker_searched=1, closed_deals=0, company_registered=0, company_searched=1, deal_approved=0, investor_approved=0, investor_registered=0, investor_searched=0, registered_users=0, timestamp=datetime.datetime(2013, 5, 21, 22, 14, 28, 48000), watchlisting=0) is not JSON serializable
So I tried to use a subclass to handle the arbitrary value which is as
follows:
import datetime
from json import JSONEncoder
class DateEncoder(JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.date):
return obj.isoformat()
return JSONEncoder.default(self, obj)
And call it using `json.dumps(data, cls=DateEncoder)`
But I still get the same error.
I have read somewhere that NDB Class has to_dict() built in method which we
would normally call and then serialize the dictionary. Can any one help me out
to serialize for this particular instance using to_dict(). I can provide you
more details of the code if necessary.
**P.S : My project is not using "Django" or "simplejson".**
Answer: Many options elsewhere. One of them, from
<http://blog.codevariety.com/2012/01/06/python-serializing-dates-datetime-
datetime-into-json/>:
def date_handler(obj):
return obj.isoformat() if hasattr(obj, 'isoformat') else obj
print json.dumps(data, default=date_handler)
Note than in your example, you should have used 'default=' instead of 'cls='.
|
Python optparse not working - syntax error
Question: this script is based on another for an assignment. My code looks the same as
theirs and BOTH error out with a syntax error. I am running with ActiveState
Active Python 2.7 64-bit
def showEvents():
''' showEvents command
List events from event logger with the following options:
-t or -type (type of event to search for)
warning (default option)
error
information
all
-g or -goback (time in hours to search)
integer
default is 100 hours
>>>showEvents -t warning -g 100
type = warning
goBack = 100 hours
'''
import optparse
parser = optparse.OptionParser()
parser.add_option('-t', '--type', \
choices=('error', 'warning', 'information', 'all' ), \
help='write type to eventType',
default = 'warning')
parser.add_option('-g', '--goback', \
help='write goback to goback',
default = '100')
(options, args) = parser.parse_args()
return options
options = showEvents()
print 'type = ', options.type
print 'goBack =', options.goback, 'hours'
if options.type == 'all':
if options.goback == '24':
import os
os.startfile('logfile.htm')
This returns the defaults when it runs, but it wont accept input. What have I
missed?
>>> type = warning
goBack = 100 hours
>>> showEvents -t error
Traceback ( File "<interactive input>", line 1
showEvents -t error
^
SyntaxError: invalid syntax
>>>
Thanks for looking.
Answer: The problem isn't with your code, but with the way you're trying to test it.
`showEvents -t error` is not a valid line of Python, but it _is_ a valid line
of `sh` or `cmd`.
So, you don't type it into the Python interpreter, you type it into the
bash/DOS prompt in a Terminal/DOS window.
Also, if you're not on Windows, the script will have to be saved as
`showEvents` (rather than `showEvents.py`), and it will have to be installed
somewhere on your `PATH`, and it will have to have the executable flag set,
and it will need a `#!/usr/bin/env python` or similar first line. (Or you can
skip all that and type `python showEvents.py -t error` at the bash prompt.)
On Windows, you can call it `showEvents.py`; as long as you're `cd`'d to the
same directory it's saved in it's automatically on your `PATH`; and there is
no executable flag or shebang line to worry about.
|
Using Python to write dbf table with fpt memos
Question: I have a legacy application that uses .dbf and .fpt files. I am looking to
read and write those files, I have figured out a way to write these files but
not using fpt memos. I am using python 2.7.2 and dbf module 0.95.02. When I
try to use the [dbf module](https://pypi.python.org/pypi/dbf "dbf module") I
get an error when trying to use FpTable.
>>> import dbf
>>> table = dbf.FpTable('test','name C(25); age N(3,0); qualified M')
>>> table
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/doctor/.virtualenvs/dbf/lib/python2.7/site-packages/dbf.py", line 4428, in __repr__
return __name__ + ".Table(%r, status=%r)" % (self._meta.filename, self._meta.status)
File "/Users/doctor/.virtualenvs/dbf/lib/python2.7/site-packages/dbf.py", line 4213, in __getattr__
return object.__getattribute__(self, name)
AttributeError: 'Db3Table' object has no attribute '_meta'
>>> table.open()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/doctor/.virtualenvs/dbf/lib/python2.7/site-packages/dbf.py", line 4953, in open
meta = self._meta
File "/Users/doctor/.virtualenvs/dbf/lib/python2.7/site-packages/dbf.py", line 4213, in __getattr__
return object.__getattribute__(self, name)
AttributeError: 'Db3Table
I am looking to create a to read and write dbf files with fpt memos. The
ability to create index files .cdx would be a ideal. I am open to any way to
do any of the above.
Answer: Short answer is don't use `FpTable` directly. You should be able to, but I've
never actually tried since I always use `Table(name, fields, dbf_type='fp')`.
Thanks for the round-a-bout bug report. ;)
|
Python RuntimeError: Failed to import pydot
Question: I am learning concepts of logistic regression concepts. When i implement it in
python, it shows me some error mentioned below. I am beginner in python. Could
anybody help to rectify this error?
RuntimeError Traceback (most recent call last) in ()
64 theano.printing.pydotprint(predict,
65 outfile="pics/logreg_pydotprint_predic.png",
66 var_with_name_simple=True)
67 # before compilation
68 theano.printing.pydotprint_variables(prediction,
C:\Anaconda\lib\site-packages\theano\printing.pyc in pydotprint(fct, outfile,
compact, format, with_ids, high_contrast, cond_highlight, colorCodes,
max_label_size, scan_graphs, var_with_name_simple, print_output_file,
assert_nb_all_strings)
565
566 if not pydot_imported:
567 raise RuntimeError("Failed to import pydot. You must install pydot"
568 " for `pydotprint` to work.")
569 return
RuntimeError: Failed to import pydot. You must install pydot for `pydotprint`
to work.
Answer: I got the same error and I did the following sequence to make it work, in a
Python 3:
source activate anaconda
pip install pydot
pip install pydotplus
pip install pydot-ng
Then you download and install Graphviz from here according to your OS type:
<http://www.graphviz.org/Download..php>
If you are running Python on Anaconda, open Spyder from terminal, not from
Anaconda. Go to terminal and type:
spyder
Then:
import theano
import theano.tensor as T
.
.
.
import pydot
import graphviz
import pydot_ng as pydot
Develop your model and:
theano.printing.pydotprint(prediction, outfile="/Volumes/Python/prediction.png", var_with_name_simple=True)
You will have a picture like this: [](http://i.stack.imgur.com/CO8GR.png)
|
What is this operator *= -1
Question: I'm going through some Python activities and was given example code with this
operator: `y *= -1`
I had a look through the [relevant Python
docs](http://docs.python.org/3/library/stdtypes.html#boolean-operations-and-
or-not), to no avail.
I know `y += 1`, for example, is short for `y = y + 1`. So is this `y = y *
-1` y equals y times -1 maybe?
Closest thing in Python docs I could find is this: `x * y`: _product of x and
y_
Is this it?
Answer: In the vast majority of the cases
y *= <expr>
is the same as
y = y * <expr>
but in the general case, it is interpreted as:
y = imul(y, <expr>)
which is then equivalent to:
y = y.__imul__(<expr>)
if `y`'s type overrides
[`__imul__`](http://docs.python.org/2/library/operator.html#operator.__imul__).
This means that if `y`'s type overrides the _inplace_ multiplication operator,
`y*=<expr>` is performed _inplace_ , while `y=y*<expr>` is not.
* * *
**EDIT**
It might not be immediately clear why the assignment is needed, i.e. why it is
intrepreted as `y = imul(y, <expr>)`, and not just `imul(y, <expr>)`.
The reason is that it makes a lot of sense for the following two scenarios to
give the same result:
c = a * b
and
c = a
c *= b
Now, this of course works if `a` and `b` are of the same type (e.g. floats,
numpy arrays, etc.), but if they aren't, it is possible for the result of the
operation to have the type of `b`, in which case the operation cannot be an
inplace operation of `a`, thus the result needs to be assigned to `a`, in
order to achieve the correct behavior.
For example, this works, thanks to the assignment:
from numpy import arange
a = 2
a *= arange(3)
a
=> array([0, 2, 4])
Whereas if the assignment is dropped, `a` remains unchanged:
a = 2
imul(a, arange(3))
=> array([0, 2, 4])
a
=> 2
|
Python: Multiprocessing imap & dynamically-created pools freeze
Question: Could someone explain why this code freezes (hangs forever),
import multiprocessing
def foo(x): return x
def main():
print(list(multiprocessing.Pool().imap(foo, iter([1, 2, 3]))))
main()
While this variant works fine,
import multiprocessing
def foo(x): return x
pool = multiprocessing.Pool()
def main():
print(list(pool.imap(foo, iter([1, 2, 3]))))
main()
as with this one,
import multiprocessing
def foo(x): return x
def main():
print(list(multiprocessing.Pool().map(foo, [1, 2, 3])))
main()
Incidentally, being able to dynamically create multiprocessing.Pool() at a
non-initialization stage in the application, and then use imap would be really
helpful. I tried stepping through it in `gdb`, and it seems frozen at
`PyThread_acquire_lock` ... but I feel pretty out-of-element debugging at such
a low level.
Answer: Apparently this is a bug with Python 2.6.7, and has been fixed at least by
Python 2.7.3.
This can be worked around by using my `vimap` package [
<https://github.com/gatoatigrado/vimap> ].
|
PIL and Python27 - Save a screengrab?
Question: Here is the code
from PIL import ImageGrab
scrgrb = ImageGrab.grabclipboard()
scrgrbnum = 0
def saveimg():
scrgrb.save("screengrab.jpeg + str(scrgrbnum + 1)", "JPEG")
scrgrbnum = scrgrbnum + 1
saveimg()
And I get this error
Traceback (most recent call last): File
"C:/Python27/Programs/screengrab", line 10, in <module>
saveimg() File "C:/Python27/Programs/screengrab", line 7, in saveimg
scrgrb.save("screengrab.jpeg + str(scrgrbnum + 1)", "JPEG") AttributeError: 'NoneType' object has no attribute 'save'
Why can't I save a screengrab object?
Answer: try
import win32api, win32con, ImageGrab
win32api.keybd_event(win32con.VK_SNAPSHOT, 1)
im = ImageGrab.grabclipboard()
im.save("screenshot.jpg", "JPEG")
I think the key here is importing the winapi too.
[Source](http://traviscrowder.com/web/python-windows-print-screen-save)
|
How do I capture SIGINT in Python on Windows?
Question: (Similar to [this question](http://stackoverflow.com/questions/1112343/how-do-
i-capture-sigint-in-python))
On UNIX under Python 2.7, at the Python prompt:
>>> import signal
>>> def handler(signal, frame):
... print 'welcome to the handler'
...
>>> signal.signal(signal.SIGINT, handler)
<built-in function default_int_handler>
I press ctrl-c
>>> welcome to the handler
>>>
On Windows:
>>> import signal
>>> def handler(signal, frame):
... print 'welcome to the handler'
...
>>> signal.signal(signal.SIGINT, handler)
<built-in function default_int_handler>
Upon pressing ctrl-c:
>>>
KeyboardInterrupt
>>>
I can verify that `handler` is being installed Python-side as the handler for
SIGINT (calling `signal.signal` a second timer returns my `handler`). How can
I capture SIGINT on Windows?
Answer: After opening [the bug](http://bugs.python.org/issue18040) upstream the root
cause of the problem was found and a patch was written. This patch won't be
going into the python 2.x series.
|
Develop OpenERP in Eclipse error
Question: I installed again my openerp project in another machine and added pydev to
eclipse then when i going to run openerp-server file below error has
come.seems something missing with installing procedure. please help me to sort
out this issue
pydev debugger: starting
Traceback (most recent call last):
File "/home/priyan/Softwares/eclipse/dropins/PyDev 2.7.3/plugins/org.python.pydev_2.7.3.2013031601/pysrc/pydevd.py", line 1397, in <module>
debugger.run(setup['file'], None, None)
File "/home/priyan/Softwares/eclipse/dropins/PyDev 2.7.3/plugins/org.python.pydev_2.7.3.2013031601/pysrc/pydevd.py", line 1090, in run
pydev_imports.execfile(file, globals, locals) #execute the script
File "/home/priyan/Softwares/openerp-7.0/openerp-server.py", line 2, in <module>
import openerp
File "/home/priyan/Softwares/openerp-7.0/openerp/__init__.py", line 39, in <module>
import addons
File "/home/priyan/Softwares/openerp-7.0/openerp/addons/__init__.py", line 38, in <module>
from openerp.modules import get_module_resource, get_module_path
File "/home/priyan/Softwares/openerp-7.0/openerp/modules/__init__.py", line 27, in <module>
from . import db, graph, loading, migration, module, registry
File "/home/priyan/Softwares/openerp-7.0/openerp/modules/graph.py", line 32, in <module>
import openerp.osv as osv
File "/home/priyan/Softwares/openerp-7.0/openerp/osv/__init__.py", line 22, in <module>
import osv
File "/home/priyan/Softwares/openerp-7.0/openerp/osv/osv.py", line 28, in <module>
from psycopg2 import IntegrityError, OperationalError, errorcodes
ImportError: No module named psycopg2
when i use apt get for install it via terminal then error says as below
root@priyan-pc:~# sudo apt-get install python-psycopg2
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package python-psycopg2
root@priyan-pc:~#

Answer: It seems `psycopg2` is not installed in your system. First install `psycopg2`
and then run OpenERP server.
Command to install `psycopg2`:
sudo apt-get install python-psycopg2
or
sudo easy_install psycopg2
or
You can download latest package (tar.gz) from [Download
pysycopg2](https://pypi.python.org/pypi/psycopg2). After that extract it, open
terminal and run `setup.py` file.
sudo python setup.py install
|
Use Python to write on specific columns in csv file
Question: I have data in a file and I need to write it to CSV file in specific column.
The data in file is like this:
002100
002077
002147
My code is this:
import csv
f = open ("file.txt","r")
with open("watout.csv", "w") as output:
for line in f :
c.writerows(line)
It is always writes on the first column. How could I resolve this? Thanks.
Answer: This is how I solved the problem
f1 = open ("inFile","r") # open input file for reading
with open('out.csv', 'wb') as f: # output csv file
writer = csv.writer(f)
with open('in.csv','r') as csvfile: # input csv file
reader = csv.reader(csvfile, delimiter=',')
for row in reader:
row[7] = f1.readline() # edit the 8th column
writer.writerow(row)
f1.close()
|
how to read windows file in linux environment
Question: I'm trying to execute a python program on linux which i first created it on
windows, but the following error is shown: metadata = eval(metafile.read())
File "< string >", line 1
@
@
@
@
@
@
Any idea? thanks!
Answer:
dos2unix yourfile.py
python yourfile.py
If you don't have `dos2unix`, here is some python code you can use instead.
Just put this in dos2unix.py, and run `python dos2unix.py yourfile.py` above:
import sys
filename = sys.argv[1]
text = open(filename, 'rb').read().replace('\r\n', '\n')
open(filename, 'wb').write(text)
This code was copied from [Python dos2unix one
liner](http://mail.python.org/pipermail/python-
list/2010-February/569661.html).
|
How to get wxPython 2.9.4 running on Windows XP with Python 3.3.2?
Question: Hmm, I'm missing something. I installed wxPython under Python33. When typing
'import wx', I am getting an error message:
ImportError: No module named 'wx' Someone knows what this is about?
I looked at this Q&A on here: "“import wx fails after installation of wxPython
on Windows XP" and "importing the wx module in python" but it's vaguely
related to my issue. This one "Python ImportError: No module named wx" seems
to have good answers, but I don't know how to add C:\Python33\site-
package\wx-2.9.4-msw to my PYTHONPATH environment variable.
Obviously, I am too new for this and asking banal questions. However, I trust
someone is willing to provide an answer.
Answer: Project Phoenix is in alpha, but IS available for Python 3 right now. You can
get a snap shot build here: <http://wxpython.org/Phoenix/snapshot-builds/>
FYI: Project Phoenix only supports the standard widgets with very limited
support for the custom modules at the time of this writing.
The standard "classic" build for wxPython 2.9 does NOT currently support
Python 3.
For information about setting PYTHONPATH, see the following:
* <http://www.blog.pythonlibrary.org/2011/11/24/python-101-setting-up-python-on-windows/>
* <http://docs.python.org/2/using/windows.html>
* [How to add to the pythonpath in windows 7?](http://stackoverflow.com/questions/3701646/how-to-add-to-the-pythonpath-in-windows-7)
|
Executing a Python Script when Web Page is loaded
Question: I'm trying to have it so that when my web page is loaded, a python script is
executed. The website is run on an apache server and the script is in the same
directory as the index.html (it's a very small project).
Is there anyway I can do this? I'm not trying to output the data from the
python file to the webpage, nor am I trying to affect anything client-side, I
simply want the python script to execute and do it's thing whenever the web
page is loaded.
Is there some sort of javascript function that I can use? I've searched around
but really haven't found anything similar. Thanks!
Answer: Hopefully, your web server is already set up to run Python scripts. Presumably
it will recognize an `index.py` file as any other `index.(html|cgi|pl|etc.)`
document. Create the following as `index.py` in your DocumentRoot:
my_webpage = """
Content Type: text/html\n\n
<html>
<head>
<title>Python-generated text!</title>
</head>
<body>
<h1>I just made an HTML page with Python!</h1>
</body>
</html>
"""
print(my_webpage)
# now that that's out of the way, let's run our script
import stuff
def myfunc():
# awesomeness goes here...
and make sure it's executable. Now, whenever a user requests
`http://www.yourserver.com/` the server will run `index.py`, which prints out
the HTML content, including the headers, then goes on to run the rest of your
script.
|
Google App Engine import NLTK error
Question: I am trying to import NLTK library in Google App Engine it gives error, I
created another module "testx.py" and this module works without error but I
dont know why NLTK does not work.
My code nltk_test.py
import webapp2
import path_changer
import testx
import nltk
class MainPage(webapp2.RequestHandler):
def get(self):
#self.response.headers['Content-Type'] = 'text/plain'
self.response.write("TEST")
class nltkTestPage(webapp2.RequestHandler):
def get(self):
text = nltk.word_tokenize("And now for something completely different")
self.response.write(testx.test("Hellooooo"))
application = webapp2.WSGIApplication([
('/', MainPage), ('/nltk', nltkTestPage),
], debug=True)
testx.py code
def test(txt):
return len(txt)
path_changer.py code
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'nltk'))
sys.path.insert(1, os.path.join(os.path.dirname(__file__), 'new'))
app.yaml
application: nltkforappengine
version: 0-1
runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: /.*
script: nltk_test.application
- url: /nltk.*
script: nltk_test.application
libraries:
- name: numpy
version: "1.6.1"
This code works fine When I comment the import nltk and nltk related code, I
think NLTK is not imported, please help me to sort out this problem, thanks
Answer: Where do you have nltk installed?
GAE libraries need to be available in your app folder. If you have nltk
elsewhere in your pythonpath it won't work.
|
Detecting Close Scene or Change Scene
Question: HI I'm working with `Pyqt4` to make a UI in `Maya`, but I want that the UI
close or refresh when the user open or change Scene.
Is there a way in python to detect this change?
Answer: [`scriptJob`](http://download.autodesk.com/us/maya/2010help/CommandsPython/scriptJob.html)
is what you need.
The following might with some customization might be helpful.
import maya.cmds as cmds
def refresher():
# the function which does the closing/refreshing
pass
cmds.scriptJob(e=["NewSceneOpened", refresher])
cmds.scriptJob(e=["SceneOpened", refresher])
cmds.scriptJob(e=["flushingScene", refresher])
|
python: generalizing delegating a method
Question: I have a class like this containing one or more numeric elements.
class Foo:
# ... other methods ...
def _update(self, f):
# ... returns a new Foo() object based on transforming
# one or more data members with a function f()
def __add__(self, k):
return self._update(lambda x: x.__add__(k))
def __radd__(self, k):
return self._update(lambda x: x.__radd__(k))
def __sub__(self, k):
return self._update(lambda x: x.__sub__(k))
def __rsub__(self, k):
return self._update(lambda x: x.__rsub__(k))
def __mul__(self, k):
return self._update(lambda x: x.__mul__(k))
def __rmul__(self, k):
return self._update(lambda x: x.__rmul__(k))
def __div__(self, k):
return self._update(lambda x: x.__div__(k))
def __rdiv__(self, k):
return self._update(lambda x: x.__rdiv__(k))
# I want to add other numeric methods also
Is there any way to generalize this for all the [numeric
methods](http://docs.python.org/2/reference/datamodel.html#numeric-types),
without having to do this for each and every one of them?
I just want to delegate for any method in the list of numeric methods.
Answer: You want to use the [`operator`
module](http://docs.python.org/2/library/operator.html) here, together with a
(short) list of binary numeric operator names, without the underscores for
compactness:
import operator
numeric_ops = 'add div floordiv mod mul pow sub truediv'.split()
def delegated_arithmetic(handler):
def add_op_method(op, cls):
op_func = getattr(operator, op)
def delegated_op(self, k):
getattr(self, handler)(lambda x: op_func(x, k))
setattr(cls, '__{}__'.format(op), delegated_op)
def add_reflected_op_method(op, cls):
op_func = getattr(operator, op)
def delegated_op(self, k):
getattr(self, handler)(lambda x: op_func(k, x))
setattr(cls, '__r{}__'.format(op), delegated_op)
def decorator(cls):
for op in numeric_ops:
add_op_method(op, cls)
add_reflected_op_method(op, cls) # reverted operation
add_op_method('i' + op, cls) # in-place operation
return cls
return decorator
Now just decorate your class:
@delegated_arithmetic('_update')
class Foo:
# ... other methods ...
def _update(self, f):
# ... returns a new Foo() object based on transforming
# one or more data members with a function f()
The decorator takes the name you wanted to delegate the call to to make this a
little more generic.
Demo:
>>> @delegated_arithmetic('_update')
... class Foo(object):
... def _update(self, f):
... print 'Update called with {}'.format(f)
... print f(10)
...
>>> foo = Foo()
>>> foo + 10
Update called with <function <lambda> at 0x107086410>
20
>>> foo - 10
Update called with <function <lambda> at 0x107086410>
0
>>> 10 + foo
Update called with <function <lambda> at 0x107086410>
20
>>> 10 - foo
Update called with <function <lambda> at 0x107086410>
0
|
Python using ctypes to pass a char * array and populate results
Question: I'm trying to use ctypes to create a char * array in python to be passed to a
library for populating with strings. I'm expecting 4 strings back no more than
7 characters in length each.
My py code looks like this
**testlib.py**
from ctypes import *
primesmile = CDLL("/primesmile/lib.so")
getAllNodeNames = primesmile.getAllNodeNames
getAllNodeNames.argtypes = [POINTER(c_char_p)]
results = (c_char_p * 4)(addressof(create_string_buffer(7)))
err = getAllNodeNames(results)
**lib.cpp**
void getAllNodeNames(char **array){
DSL_idArray nodes; //this object returns const char * when iterated over
network.GetAllNodeIds(nodes);
for(int i = 0; i < (nodes.NumItems()); i++){
strcpy(array[i],nodes[i]);
}
}
I keep getting segmentation faults when I try to run this code. I've created a
test from C that works perfectly but in Python I must be setting up the
pointer array incorrectly or something. It seems to get to the second node in
the loop and then have a problem as I've seen from spitting out data into the
command line. Any insight would be much appreciated.
Answer: The following code works:
test.py:
import ctypes
lib = ctypes.CDLL("./libtest.so")
string_buffers = [ctypes.create_string_buffer(8) for i in range(4)]
pointers = (ctypes.c_char_p*4)(*map(ctypes.addressof, string_buffers))
lib.test(pointers)
results = [s.value for s in string_buffers]
print results
test.c (compiled to libtest.so with `gcc test.c -o libtest.so -shared -fPIC`):
#include <string.h>
void test(char **strings) {
strcpy(strings[0],"this");
strcpy(strings[1],"is");
strcpy(strings[2],"a");
strcpy(strings[3],"test!");
}
As Aya said, you should make sure there is room for the terminating zero. But
I think your main problem was that the string buffer was garbage collected or
something similar, as there was no direct reference to it anymore. Or
something else is causing trouble in the creation process of the string
buffers when no references are stored for them. For example this results in
four times the same address instead of different addresses:
import ctypes
pointers = [ctypes.addressof(ctypes.create_string_buffer(8)) for i in range(4)]
print pointers
|
get how much time python subprocess spends
Question: I'd like to time how long does the subprocess take. I tried to use
start = time.time()
subprocess.call('....')
elapsed = (time.time() - start)
However it's not very accurate (not sure related to multi-process or sth else)
Is there a better way I can get how much time the subprocess really spends?
Thank you!
Answer: It depends on which time you want; elapsed time, user mode, system mode?
With
[`resource.getrusage`](http://docs.python.org/2/library/resource.html#resource.getrusage)
you can query the user mode and system mode time of the current process's
children. This only works on UNIX platforms (like e.g. Linux, BSD and OS X):
import resource
info = resource.getrusage(resource.RUSAGE_CHILDREN)
On Windows you'll probably have to use
[`ctypes`](http://docs.python.org/2/library/ctypes.html) to get equivalent
information from the WIN32 API.
|
splitting line in python
Question: I have data of the below mentioned form:
<a> <b> <c> <This is a string>
<World Bank> <provides> <loans for> <"a Country's Welfare">
<Facebook> <is a> <social networking site> <"Happy Facebooking => Enjoy">
Now I want to split each line given above based on the delimiter <>. That is I
want to split as:
['<a>', '<b>', '<c>', '<This is a string>']
['<World Bank>', '<provides>', '<loans for>', '<"a Country\'s Welfare">']
['<Facebook>', '<is a>', '<social networking site>', '<"Happy Facebooking => Enjoy">']
I tried splitting based on space and "> " but it does not work. Is there some
other way in python by which I may split in the manner described above. Since
my file size is 1 TB therefore I can not do so manually.
Answer: You want to split on the whitespace _between_ the `>` and `<` characters. For
that you need a regular expression split with look-behind and look-ahead
assertions:
import re
re.split('(?<=>)\s+(?=<)', line)
This splits on any whitespace (`\s+`) that is preceded by a `>` and followed
by a `<` character.
The `(?<=...)` expression is a look-behind assertion; it matches a _location_
in the input text, namely anywhere the pattern inside the assertion precedes
the location. In the above it matches anywhere there is a `>` character just
before the current location.
The `(?=...)` expression works just like the look-behind assertion, but
instead looks for matching characters _after_ the current location. It is
known as a look-ahead assertion. `(?=<)` means it'll match to any location
that is followed by the `<` character.
Together these form two anchors, an the `\s+` in between will only match
whitespace that sits between a `>` and a `<`, but _not those two characters
themselves_. The split breaks up the input string by removing the matched
text, and only the spaces are matched, leaving the `>` and `<` characters
attached to the text being split.
Demo:
>>> re.split('(?<=>)\s+(?=<)', '<a> <b> <c> <This is a string>')
['<a>', '<b>', '<c>', '<This is a string>']
>>> re.split('(?<=>)\s+(?=<)', '''<World Bank> <provides> <loans for> <"a Country's Welfare">''')
['<World Bank>', '<provides>', '<loans for>', '<"a Country\'s Welfare">']
>>> re.split('(?<=>)\s+(?=<)', '<Facebook> <is a> <social networking site> <"Happy Facebooking => Enjoy">')
['<Facebook>', '<is a>', '<social networking site>', '<"Happy Facebooking => Enjoy">']
|
how to update a listbox in one window in one class using a different class python
Question: what i have is a window that opens up and it has a list box. this is created
using one class. when i click the search button and results are found using a
different class, i want the list box to update without having to open up
another window. below is my code so far\n
from Tkinter import *
class addTask:
def __init__(self):
self.addWindow = Tk()
self.addWindow.configure(background = "black")
self.addWindow.geometry("450x450")
self.addWindow.resizable(width = False, height = False)
self.addWindow.title("Add Task")
self.addNameLabel = Label(self.addWindow,text="Add the name of the task",font = ("Helvetica",10,"italic"),bg = "black",fg = "white")
self.addNameLabel.place(relx=0.01, rely=0.05)
self.nameWiget = Text (self.addWindow, width = 63, height = 1)
self.nameWiget.place(relx=0.0, rely=0.1)
self.addDateLabel = Label(self.addWindow,text="Add the date of the task",font = ("Helvetica",10,"italic"),bg = "black",fg = "white")
self.addDateLabel.place(relx=0.01, rely=0.2)
self.dateWiget = Text (self.addWindow, width = 63, height = 1)
self.dateWiget.place(relx=0.0, rely=0.25)
self.addTaskLabel = Label(self.addWindow,text="Add the details of the task",font = ("Helvetica",10,"italic"),bg = "black",fg = "white")
self.addTaskLabel.place(relx=0.01, rely=0.35)
self.taskWiget = Text (self.addWindow, width = 63, height = 1)
self.taskWiget.place(relx=0.0, rely=0.4)
addButton = Button(self.addWindow,height = 5, width = 20, text="Add Task",highlightbackground="black",font=("Helvetica",10,"bold"),command=lambda:self.saveFuntion())
addButton.place(relx=0.25, rely=0.55)
def saveFuntion(self):
nameInfo = (self.nameWiget.get(1.0, END))
dateInfo = self.dateWiget.get(1.0, END)
taskInfo = self.taskWiget.get(1.0, END)
print nameInfo
task1 = Task(nameInfo,dateInfo,taskInfo)
task1.save()
self.nameWiget.delete(1.0,END)
class Task:
def __init__(self,name,date,task):
self.__name = name
self.__date = date
self.__task = task
def save(self):
fileName = open("dataFile.txt","a")
fileName.write(self.__name)
fileName.write(self.__date)
fileName.write(self.__task)
class editTask:
def __init__(self):
self.editWindow = Tk()
self.newWindow = Tk()
self.newWindow.geometry("450x750")
self.editWindow.configure(background = "black")
self.editWindow.geometry("450x750")
self.editWindow.resizable(width = False, height = False)
self.editWindow.title("Edit Task")
self.listBox = Listbox(self.editWindow,heigh = 15, width = 30)
self.listBox.place(relx = 0.2, rely = 0.6)
#drop down menu
self.var = StringVar(self.editWindow)
self.var.set("Select search critria")
self.choices = ["Name","Date"]
self.option = OptionMenu(self.editWindow,self.var,*self.choices)
self.option.configure(bg = "black")
self.option.place(relx = 0.5, rely = 0.2)
#edit label and text box
self.editLabel = Label(self.editWindow,text="Add the name of the task",font = ("Helvetica",10,"italic"),bg = "black",fg = "white")
self.editLabel.place(relx=0.01, rely=0.05)
self.editInfoWiget = Text (self.editWindow, width = 63, height = 1)
self.editInfoWiget.place(relx=0.0, rely=0.1)
# search button
searchButton = Button(self.editWindow,height = 5, width = 20, text="Search for Task",highlightbackground="black",font=("Helvetica",10,"bold"),command=lambda:self.searchFuntion())
searchButton.place(relx=0.3, rely=0.4)
def searchFuntion(self):
critria = self.var.get()
info = self.editInfoWiget.get(1.0,END)
thing = info.split("\n")
thing2 = thing[0]
search = searchCritria(critria,thing2)
search.search()
# def openListBox(self):
class searchCritria():
def __init__(self,critria,info):
self.__critria = critria
self.__info = info
def search(self):
self.file = open("dataFile.txt", "r+")
fileData = self.file.readlines()
self.file.close()
lengthOfFile = len(fileData)
counter = 1
self.name = []
self.date = []
self.details = []
for i in range (lengthOfFile):
split = fileData[i].split("\n")
while counter == 1:
self.name.append(split)
break
while counter == 2:
self.date.append(split)
break
while counter == 3:
self.details.append(split)
break
counter = counter +1
if counter > 3:
counter = 1
if self.__critria == "Name":
for x in range (len(self.name)):
self.taskName = self.name[x]
self.taskName2 = self.taskName[0]
if self.__info == self.taskName2:
openWindow = True
else :
openWindow = False
if openWindow == True:
editTask().listBox.insert(END,self.taskName2)
if self.__critria == "Date":
for x in range (len(self.date)):
self.taskDate = self.date[x]
self.taskDate2 = self.taskDate[0]
if self.__info == self.taskDate2:
print "found"
else :
print"not found"
class editTask2():
def __init__(self):
self.edit2Window = Tk()
self.edit2Window.configure(background = "black")
self.edit2Window.geometry("450x350")
self.edit2Window.resizable(width = False, height = False)
self.edit2Window.title("Edit Task")
any help would be great
thanks
Answer: The biggest problem in your code is that you're creating multiple instances of
`Tk`. Tkinter simply isn't designed to work that way. You should only ever
create a single instance of `Tk`. If you need additional windows, create
instances of `Toplevel`.
Also, you need to call the `mainloop` function of this instance of `Tk`
exactly once. Without it, your GUI will not work.
If you want to update a listbox in another class than where it was created,
the concept is pretty simple: if A needs to update B, A needs a reference to
B. So, either pass in a reference to the listbox when you create the other
class, or give the other class a method you can call where you pass in the
reference to the listbox after it was created.
|
Python: Iterate alphabetically over OrderedDict
Question: In a script I have an OrderedDict `groups` that gets fed key/value pairs
alphabetically.
In another part of the script, I'm checking against files that have the same
same as `key` like so:
for (key, value) in groups.items():
file = open(key, 'r')
# do stuff
Stuff happens just fine, part of which is printing a status line for each
file, but how can I get Python to iterate through `groups` alphabetically, or
at least numerically as they are ordered (since they are being entered in
alphabetical order anyways)?
Answer: The whole point of an `OrderedDict` is that you can iterate through it
normally in the order that keys were entered:
>>> from collections import OrderedDict
>>> d = OrderedDict()
>>> d[1] = 2
>>> d[0] = 3
>>> d[9] = 2
>>> for k, v in d.items():
print(k, v)
(1, 2)
(0, 3)
(9, 2)
Just make sure you don't feed `OrderedDict(...)` a dictionary to initialize it
or it starts off unordered.
|
Accessing values from a Unicode dictionary in Python
Question: I have Unicode values similar to this in a dictionary:
{u'id': u'100000000265946', u'name': u'Sophia N Art Fuentes'}
{u'id': u'100000538132142', u'name': u'Tatiana Vargas'}
{u'id': u'1669912701', u'name': u'Milvia Albanez'}
I need to access keys and values but I'm getting this error
> AttributeError: 'unicode' object has no attribute 'keys'
I am using Python 2.7. Is there any method to convert Unicode to ASCII? Or how
do I access the values as Unicode itself?
Answer:
>>> s = u"{u'id': u'100000000265946', u'name': u'Sophia N Art Fuentes'}"
>>> s.keys()
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
s.keys()
AttributeError: 'unicode' object has no attribute 'keys'
>>> import ast
>>> d = ast.literal_eval(s)
>>> d.keys()
[u'id', u'name']
|
re.sub in Python 3.3
Question: I am trying to change the text string from the form of `file1` to `file01`. I
am really new to python and can't figure out what should go in 'repl' location
when trying to use a pattern. Can anyone give me a hand?
text = 'file1 file2 file3'
x = re.sub(r'file[1-9]',r'file\0\w',text) #I'm not sure what should go in repl.
Answer: You could try this:
>>> import re
>>> text = 'file1 file2 file3'
>>> x = re.sub(r'file([1-9])',r'file0\1',text)
'file01 file02 file03'
The brackets wrapped around the `[1-9]` captures the match, and it is the
first match. You will see I used it in the replace using `\1` meaning the
first catch in the match.
Also, if you don't want to add the zero for files with 2 digits or more, you
could add `[^\d]` in the regexp:
x = re.sub(r'file([1-9](\s|$))',r'file0\1',text)
|
Adding list data to a .txt file and re-opening these lists where prompted
Question: I have done some research and found various examples but as my python
knowledge is so basic I do not understand them.
Is there a method for importing ONLY the lists to another python window as any
import i try seems to import the list and then run that files functions which
I don't want it to do? I only want the other python pages to import the lists
to either show them or modify them further? I have no code for this but I
presume it would be something such as
from 'filename' import task[],date[],description[]
The code this is on is as follows (Bear in mind I only want to lists. I don't
want the other functions to be run)
import sys
import os
task=[]
date=[]
description=[]
def addtask():
"""adds a task to the task list"""
print("Please re-enter your filename with .txt on the end.")
f=(raw_input("filename: "))
file= open(f, "w+")
add=(raw_input("Enter a task: "))
if add=="helpme":
os.startfile("C:\Users\Dale\Desktop\Python coursework\helpme.txt")
add=(addtask())
else:
file.write(add)
task.append(add)
add1=(raw_input("Please enter a date for this task: "))
if add1=="helpme":
os.startfile("C:\Users\Dale\Desktop\Python coursework\helpme.txt")
add=(addtask())
else:
file.write(add1)
date.append(add1)
add2=(raw_input("Please enter a description of the task: "))
if add2=="helpme":
os.startfile("C:\Users\Dale\Desktop\Python coursework\helpme.txt")
add=(addtask())
else:
file.write(add2)
description.append(add2)
a=(raw_input("would you like to add another?: "))
if a=="yes":
print(addtask())
elif a=="helpme":
os.startfile("C:\Users\Dale\Desktop\Python coursework\helpme.txt")
add=(addtask())
else:
import choices
b=(raw_input("Would you like to add a task?"))
if b=="yes":
add=addtask()
elif b=="no":
import choices
elif b=="helpme":
os.startfile("C:\Users\Dale\Desktop\Python coursework\helpme.txt")
add=(addtask())
else:
import choices
Hopefully that has come out correctly... Note* the three lists are called
`task[]`, `date[]` and `description[]`
Answer: Do you mean something like this?
$ cat task.py
task=[1,2,3,4,5,6,7,8,9,0]
$ python
Python 2.7.3 (default, Sep 26 2012, 21:51:14)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from task import task
>>> task
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
|
Python: My script will not allow me to create large files
Question: I'm making a small python script which will create random files in all shapes
and sizes but it will not let me create large files. I want to be able to
create files up to around 8GB in size, I know this would take a long amount of
time but I'm not concerned about that.
The problem is that Python 2.7 will not handle the large numbers I am throwing
at it in order to create the random text that will fill my files.
The aim of my code is to create files with random names and extentions, fill
the files with a random amount of junk text and save the files. It will keep
on repeating this until I close the command line window.
import os
import string
import random
ext = ['.zip', '.exe', '.txt', '.pdf', '.msi', '.rar', '.jpg', '.png', '.html', '.iso']
min = raw_input("Enter a minimum file size eg: 112 (meaning 112 bytes): ")
minInt = int(min)
max = raw_input("Enter a maximum file size: ")
maxInt = int(max)
def name_generator(chars=string.ascii_letters + string.digits):
return ''.join(random.choice(chars) for x in range(random.randint(1,10)))
def text_generator(chars=string.printable + string.whitespace):
return ''.join(random.choice(chars) for x in range(random.randint(minInt,maxInt)))
def main():
fileName = name_generator()
extension = random.choice(ext)
file = fileName + extension
print 'Creating ==> ' + file
fileHandle = open ( file, 'w' )
fileHandle.write ( text_generator() )
fileHandle.close()
print file + ' ==> Was born!'
while 1:
main()
Any help will be much appreciated!
Answer: Make it lazy, as per the following:
import string
import random
from itertools import islice
chars = string.printable + string.whitespace
# make infinite generator of random chars
random_chars = iter(lambda: random.choice(chars), '')
with open('output_file','w', buffering=102400) as fout:
fout.writelines(islice(random_chars, 1000000)) # write 'n' many
|
How to efficiently generate this matrix in python
Question: I have already had a row vector a of dimension d which only contains elements
0 or 1.
I want generate a r by d matrix A, where A satisfies
for column j = 1,2 .... d
if a[j] = 1, then A[:,j] = 1. That's, the corresponding column will be all 1's
if a[j] = 0, then A[:,j] = 0. ....
I think it looks quite straightforward. But I don't know how to generate it
efficiently in python ( or in other languages).
Note that r = 1,000 and d = 100,000
(The reason why I want to generate this matrix A is that given another d by n
matrix B, C = A*B will be r by n which the rows of C correspond to the non-
zero elements in vector a.)
Answer: If you are going to be doing matrix multiplication or math in general in
Python, use [NumPy](http://www.numpy.org).
The rows of `A` all have the same value, so the _efficient_ way to calculate
it is to build only one row. You already have that row, `a`.
NumPy can also broadcast the values of an array, making a 1-dimensional vector
act like a 2-dimensional array with repeated values. This is memory-efficient
since you do not need to actually allocate space for the repeated values.
So, in NumPy you might perform the calculation like this:
import numpy as np
r, d, n = 1000, 100000, 1000
a = np.random.randint(2, size=d)
A = a
print(A.shape)
# (100000,)
B = np.random.random((d, n))
print(B.shape)
# (100000, 1000)
C = A.dot(B)
print(C.shape)
# (1000,)
The result, `C` is "`of shape (n,)`" -- which is NumPy-talk for a 1D vector of
`n` elements -- rather than an array of shape `(r,n)` since, just like `A`,
all the rows have the same value. There is no need to repeat them.
|
Questions about running a program (pygame)
Question: I have installed pygame and I dont know how to allow my python to read it...
I do
# import modules
import os
import pygame
And I got this: `ImportError: No module named 'pygame'`
Answer: I think you are missing something here. Download the correct package from the
pygame website. it should be a .exe. Then, go to your downloads folder.
Double-click on the file to run it and follow the on-screen prompts to install
pygame. After you have done that, try importing pygame. You don't need to
click-and-drag anything. just run the file you downloaded. Let me know if this
works.
Assuming you have windows 32 bit, you would download these files:
python 2.7:
<http://www.python.org/ftp/python/2.7.5/python-2.7.5.msi>
pygame for 2.7:
<http://pygame.org/ftp/pygame-1.9.1.win32-py2.7.msi>
|
Is convolution slower in Numpy than in Matlab?
Question: Convolution in Matlab appears to be twice as fast as convolution in Numpy.
Python code (takes 19 seconds on my machine):
import numpy as np
from scipy import ndimage
import time
img = np.ones((512,512,512))
kernel = np.ones((5,5,5))/125
start_time = time.time()
ndimage.convolve(img,kernel,mode='constant')
print "Numpy execution took ", (time.time() - start_time), "seconds"
Matlab code (takes 8.7 seconds on my machine):
img = ones(512,512,512);
kernel = ones(5,5,5) / 125;
tic
convn(img, kernel, 'same');
toc
The two give identical results.
Is there a way to improve Numpy to match or beat Matlab's performance here?
Interestingly, this factor or ~2 difference in runtimes is consistent at many
input sizes.
Answer: What exact operation are you doing? There are a number of optimizations that
`ndimage` provides if you don't need general N-d convolution.
For example, your current operation:
img = np.ones((512,512,512))
kernel = np.ones((5,5,5))/125
result = ndimage.convolve(img, kernel)
is equivalent to:
img = np.ones((512,512,512))
result = ndimage.uniform_filter(img, 5)
However, there's a large difference in execution speed:
In [22]: %timeit ndimage.convolve(img, kernel)
1 loops, best of 3: 25.9 s per loop
In [23]: %timeit ndimage.uniform_filter(img, 5)
1 loops, best of 3: 8.69 s per loop
The difference is caused by `uniform_filter` preforming a 1-d convolution
along each axis, instead of a generic 3D convolution.
In cases where the kernel is symmetric, you can make these simplifications and
get a significant speed up.
I'm not certain about `convn`, but often matlab's functions make these kind of
optimizations behind-the-scenes if your input data matches certain criteria.
Scipy more commonly uses one-algorithm-per-function, and expects the user to
know which one to pick in which case.
* * *
You mentioned a "Laplacian of Gaussian" filter. I always get a touch confused
with terminology here.
I think what you want in terms of `ndimage` functions is either
[`scipy.ndimage.gaussian_laplace`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.filters.gaussian_laplace.html#scipy.ndimage.filters.gaussian_laplace)
or `scipy.ndimage.gaussian_filter` with `order=2` (which filters by the second
derivative of the gaussian).
At any rate, both simplify the operation down to a 1-d convolution over each
axis, which should give a significant (2-3x) speedup.
|
Check items in multidimensionaly array in Python
Question: I have a dynamic multidimensional array, that can have a different number of
columns each time. The user is asked to select which columns to extract from a
file with N-columns, and based on this number, a multidimensional array
'ARRAY_VALUES' is created.
import numpy as num
DIRECTORY = '/Users/user/Desktop/'
DATA_DIC_FILE = "%sOUTPUT_DIC/OUTPUT_DICTIONARIES.txt" %(DIRECTORY)
Choice = str( raw_input( 'Which columns do you want to use (separated by a comma):\t' ) ).split(',')
# Input something like this: 1,2,3,4
String_choice = []
PCA_INDEX = []
Columns = len(Choice)
PCA_INDEX = {}
# PCA_INDEX is a dictionary that the key is a string whose value is a float number.
PCA_INDEX['any_string'] = float_number # The dictionary has about 50 entries.
ARRAY_VALUES = [ [] for x in xrange( Columns) ]
""" Creating the N-dimensional array that will contain the data from the file """
""" This list has the form ARRAY_VALUES = [ [], [], [], ... ] for n-repetitions. """
ARRAY_VALUES2 = ARRAY_VALUES
lines = open( DATA_DIC_FILE ).readlines() #Read lines from the file
for i in range( 0, len(ARRAY_VALUES) ):
ARRAY_VALUES[i] = num.loadtxt( fname = DATA_DIC_FILE, comments= '#', delimiter=',', usecols = [ int( PCA_INDEX[i] ) ], unpack = True )
""" This saves the lists from the file to the matrix 'ARRAY_VALUES' """
Now that I have the multidimensional array in the form of ARRAY_VALUES = [[],
[], ...] for n-columns.
I want to eliminate the corresponding rows from each of the columns if any of
the values are 'inf's. I tried to use the following code, but I don't know how
to make it dynamic for the number of columns:
for j in range(0, len(ARRAY_VALUES)):
for i in range(0, len(ARRAY_VALUES[0])):
if num.isinf( ARRAY_VALUES[j][i] ) or num.isinf( ARRAY_VALUES[]): # This is where the problem is.
# if num.isinf( ARRAY_VALUES[0][i] ) or num.isinf(ARRAY_VALUES[1][i] or ... num.isinf(ARRAY_VALUES[last_column][i]:
continue
else:
ARRAY_VALUES2[j].append( ARRAY_VALUES[j][i] ) #Save the values into ARRAY_VALUES2.
Can anyone help me out and tell me how to do this part:
# if num.isinf( ARRAY_VALUES[0][i] ) or num.isinf(ARRAY_VALUES[1][i] or ... num.isinf(ARRAY_VALUES[last_column][i]:
for a multi-dimensional array with n-columns, so that the output is like the
following:
ARRAY_VALUES = [ [8, 2, 3 , inf, 5],
[1, 9, inf, 4 , 5],
[7, 2, inf, inf, 6] ]
ARRAY_VALUES2 = [ [8, 2, 5],
[1, 9, 5],
[7, 2, 6] ]
\--Thanks!
Answer:
>>> a = np.array([[8, 2, 3 , np.inf, 5],[1, 9, np.inf, 4 , 5],[7, 2, np.inf, n
p.inf, 6]])
>>> col_mask = [i for i in range(ncols) if not any(a[:,i] == np.inf)]
>>> print a[:,col_mask]
[[ 8. 2. 5.]
[ 1. 9. 5.]
[ 7. 2. 6.]]
first use a numpy.array if you arent already.
then we iterate over each column and check for any np.infs to create a mask of
allowable columns
lastly we just use numpy's column indexing to access only our columns of
interest
as DSM points out you can create the mask with just numpy and avoid the list
comprehension
col_mask = np.isfinite(a).all(axis=0)
|
mongoengine OperationError on saving
Question: I'm writing a python script to populate a mongodb database, my models look
like the following:
from mongoengine import *
from mongoengine.django.auth import User
class TrackGroup (Document):
name = StringField(required=True)
users = ListField(ReferenceField('User'))
devices = ListField(ReferenceField('Device'))
class Device(Document):
name = StringField(max_length=50, required=True)
grp = ListField(ReferenceField(TrackGroup))
class User(User):
first_name = StringField(max_length=50)
last_name = StringField(max_length=50)
grp = ListField(ReferenceField(TrackGroup))
And my script goes like this:
#Create a group
gName = 'group name'
g = TrackGroup(name=gName)
g.users = []
g.devices = []
g.save()
#create a user
u = User.create_user(username='name', password='admin', email='[email protected]')
gRef = g
u.grp = [gRef, ]
u.first_name = 'first'
u.last_name = 'last'
u.save()
gRef.users.append(u)
gRef.save()
#create a device
dev = Device(name='name').save()
gRef = g
dev.grp = [gRef, ]
dev.save()
gRef.devices.append(dev)
gRef.save() #Problem happens here
The problem happens when I call `gRef.save()` I get the following error:
raise OperationError(message % unicode(err))
mongoengine.errors.OperationError: Could not save document (LEFT_SUBFIELD only supports Object: users.0 not: 7)
I looked around for a while, and
[here](http://comments.gmane.org/gmane.comp.db.mongodb.user/64059) it says
that this means I'm trying to set a filed with an empty key, like this: (The
example is from the link above, not mine)
{
"_id" : ObjectId("4e52b5e08ead0e3853320000"),
"title" : "Something",
"url" : "http://www.website.org",
"" : "",
"tags" : [ "international"]
}
I don't know where such a field can come from, but I opened a mongo shell and
looked at my documents from the three collections, and I couldn't find such a
field.
Note: If I add the device first, the same error occurs while saving the group
after adding the user.
Answer: I had the same error, and this trick work for me:
the_obj_causing_error.reload()
/* make some change */
the_obj_causing_error.price = 5
the_obj_causing_error.save()
just try `reload()` the object before changing it.
|
How to interpret addresses in a kernel oops
Question: I have a kernel oops in a linux device driver I wrote. I want to determine
which line is responsible for the oops. I have the following output, but I do
not know how to interpret it.
Does it mean my code crashed at the instruction at write_func + 0x63? How can
I relate the value in EIP to my own function? What do the values after the
backslash mean?
[10991.880354] BUG: unable to handle kernel NULL pointer dereference at (null)
[10991.880359] IP: [<c06969d4>] iret_exc+0x7d0/0xa59
[10991.880365] *pdpt = 000000002258a001 *pde = 0000000000000000
[10991.880368] Oops: 0002 [#1] PREEMPT SMP
[10991.880371] last sysfs file: /sys/devices/platform/coretemp.3/temp1_input
[10991.880374] Modules linked in: nfs lockd fscache nfs_acl auth_rpcgss sunrpc hdrdmod(F) coretemp(F) af_packet fuse edd cpufreq_conservative cpufreq_userspace cpufreq_powersave acpi_cpufreq mperf microcode dm_mod ppdev sg og3 ghes i2c_i801 igb hed pcspkr iTCO_wdt dca iTCO_vendor_support parport_pc floppy parport ext4 jbd2 crc16 i915 drm_kms_helper drm i2c_algo_bit video button fan processor thermal thermal_sys [last unloaded: preloadtrace]
[10991.880400]
[10991.880402] Pid: 4487, comm: python Tainted: GF 2.6.37.1-1.2-desktop #1 To be filled by O.E.M. To be filled by O.E.M./To be filled by O.E.M.
[10991.880408] EIP: 0060:[<c06969d4>] EFLAGS: 00210246 CPU: 0
[10991.880411] EIP is at iret_exc+0x7d0/0xa59
[10991.880413] EAX: 00000000 EBX: 00000000 ECX: 0000018c EDX: b7837000
[10991.880415] ESI: b7837000 EDI: 00000000 EBP: b7837000 ESP: e2a81ee0
[10991.880417] DS: 007b ES: 007b FS: 00d8 GS: 0033 SS: 0068
[10991.880420] Process python (pid: 4487, ti=e2a80000 task=df940530 task.ti=e2a80000)
[10991.880422] Stack:
[10991.880423] 00000000 0000018c 00000000 0000018c e5e903dc e4616353 00000009 df99735c
[10991.880428] df900a7c df900a7c b7837000 df80ad80 df99735c 00000009 e46182a4 e2a81f70
[10991.880433] e28cd800 e09fc840 e28cd800 fffffffb e09fc888 c03718c1 e4618290 0000018c
[10991.880438] Call Trace:
[10991.882006] Inexact backtrace:
[10991.882006]
[10991.882012] [<e4616353>] ? write_func+0x63/0x160 [mymod]
[10991.882017] [<c03718c1>] ? proc_file_write+0x71/0xa0
[10991.882020] [<c0371850>] ? proc_file_write+0x0/0xa0
[10991.882023] [<c036c971>] ? proc_reg_write+0x61/0x90
[10991.882026] [<c036c910>] ? proc_reg_write+0x0/0x90
[10991.882031] [<c0323060>] ? vfs_write+0xa0/0x160
[10991.882034] [<c03243c6>] ? fget_light+0x96/0xb0
[10991.882037] [<c0323331>] ? sys_write+0x41/0x70
[10991.882040] [<c0202f0c>] ? sysenter_do_call+0x12/0x22
[10991.882044] [<c069007b>] ? _lock_kernel+0xab/0x180
[10991.882046] Code: f3 aa 58 59 e9 5a f9 d7 ff 8d 0c 88 e9 12 fa d7 ff 01 d9 e9 7b fa d7 ff 8d 0c 8b e9 73 fa d7 ff 01 d9 eb 03 8d 0c 8b 51 50 31 c0 <f3> aa 58 59 e9 cf fa d7 ff 01 d9 e9 38 fb d7 ff 8d 0c 8b e9 30
[10991.882069] EIP: [<c06969d4>] iret_exc+0x7d0/0xa59 SS:ESP 0068:e2a81ee0
[10991.882072] CR2: 0000000000000000
[10991.889660] ---[ end trace 26fe339b54b2ea3e ]---
Answer: All the information you need is right there:
[10991.880354] BUG: unable to handle kernel NULL pointer dereference at (null)
That's the reason.
[10991.880359] IP: [<c06969d4>] iret_exc+0x7d0/0xa59
That's the instruction pointer at the time of fault. We'll get back to this
momentarily.
[10991.880365] *pdpt = 000000002258a001 *pde = 0000000000000000
These are physical page table entries. the descriptor table, and the page
descriptor entry. Naturally, the latter is NULL, since it's a NULL pointer.
The above values are rarely useful (only in cases where physical memory
mapping is required)
[10991.880368] Oops: 0002 [#1] PREEMPT SMP
That's the oops code. PREEMPT SMP shows you the kernel is preemptible, and
compiled for SMP, rather than UP. This is important for cases where the bug is
from some race condition, etc.
[10991.880371] last sysfs file: /sys/devices/platform/coretemp.3/temp1_input
That's not necessarily the culprit, but oftentimes is. sys files are exported
by various kernel modules, and oftentimes an I/O operation on the sys file
leads to the faulty module code execution.
[10991.880374] Modules linked in: ... [last unloaded: preloadtrace]
The kernel doesn't necessarily know which module is to blame, so it's giving
you all of them. Also, it may very well be that a recently unloaded module
didn't clean up and left some residue (like some timer, or callback) in the
kernel - which is a classic case for oops or panic. So the kernel reports the
last unloaded one, as well.
[10991.880402] Pid: 4487, comm: python Tainted: GF 2.6.37.1-1.2-desktop #1 To be filled by O.E.M. To be filled by O.E.M./To be filled by O.E.M.
If the faulting thread is a user mode thread, you get the PID and command
line. "Tainted" flags are the kernel's way of saying it's not a kernel fault
(the kernel source is open and "pure". "Taint" comes from the blasphemous non-
GPL modules, and others.
[10991.880408] EIP: 0060:[<c06969d4>] EFLAGS: 00210246 CPU: 0
[10991.880411] EIP is at iret_exc+0x7d0/0xa59
That gives you the faulting instruction pointer, both directly and in
symbol+offset form. The part after the slash is the size of the function.
[10991.880413] EAX: 00000000 EBX: 00000000 ECX: 0000018c EDX: b7837000
[10991.880415] ESI: b7837000 EDI: 00000000 EBP: b7837000 ESP: e2a81ee0
[10991.880417] DS: 007b ES: 007b FS: 00d8 GS: 0033 SS: 0068
The registers are shown here. Your NULL is likely EAX.
[10991.880420] Process python (pid: 4487, ti=e2a80000 task=df940530 task.ti=e2a80000)
[10991.880422] Stack:
[10991.880423] 00000000 0000018c 00000000 0000018c e5e903dc e4616353 00000009 df99735c
[10991.880428] df900a7c df900a7c b7837000 df80ad80 df99735c 00000009 e46182a4 e2a81f70
[10991.880433] e28cd800 e09fc840 e28cd800 fffffffb e09fc888 c03718c1 e4618290 0000018c
The area near the stack pointer is displayed. The kernel has no idea what
these values mean, but they are the same output as you'd get from gdb
displaying the $rsp. So it's up to you to figure what they are. (For example,
c03718c1 is a kernel return address, likely - so you can go to /proc/kallsyms
to figure it out, or rely on it being in the trace, as it is , next). This
tells you that all the data up to it is the stack frame
Now, because you have the stack call trace, you can put the fragments
together:
[10991.880423] 00000000 0000018c 00000000 0000018c e5e903dc e4616353 --> back to write_func
[ ] ..................................................... 00000009 df99735c
[10991.880428] df900a7c df900a7c b7837000 df80ad80 df99735c 00000009 e46182a4 e2a81f70
[10991.880433] e28cd800 e09fc840 e28cd800 fffffffb e09fc888 c03718c1 --> back to proc_file_write
[10991.882046] Code: f3 aa 58 59 e9 5a f9 d7 ff 8d 0c 88 e9 12 fa d7 ff 01 d9 e9 7b fa d7 ff 8d 0c 8b e9 73 fa d7 ff 01 d9 eb 03 8d 0c 8b 51 50 31 c0 <f3> aa 58 59 e9 cf fa d7 ff 01 d9 e9 38 fb d7 ff 8d 0c 8b e9 30
Again, kernel can't disassemble for you (it's oopsing, and might very well
panic, give it a break!). But you can use gdb to disassemble these values.
So now you know everything. You can actually disassemble your own module and
figure out where exactly in write_func the NULL pointer is dereferenced.
(You're probably passing it as an argument to some function).
|
A consistent way to check types in python
Question: I'm finding that type checking in python (pre py3, I'm not sure about the
state in py3) is bit of a mess, here's what I mean:
First, there are the built in types (int, str etc), and the types defined in
the 'types' module, where you have to import the types module and use it as a
prefix. You can jump this hurdle easily if you get a 'name undefined error'
for the type you're using, and try the types in the types module.
Then, there are the names printed out by the type() function that you can't
figure out what type they correspond to - examples:
In [38]: type(Session.__dict__['mix'])
Out[38]: staticmethod
In [39]: type(Session.__dict__['mix']) == staticmethod
Out[39]: True
Ok, so this one is a built-in type. But then:
In [47]: type(Session.__dict__['Cuser'])
Out[47]: classobj
In [48]: type(Session.__dict__['Cuser']) == classobj
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-48-b062b09548fb> in <module>()
----> 1 type(Session.__dict__['Cuser']) == classobj
NameError: name 'classobj' is not defined
In [49]: type(Session.__dict__['Cuser']) == types.classobj
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-49-2a88e0b8e176> in <module>()
----> 1 type(Session.__dict__['Cuser']) == types.classobj
AttributeError: 'module' object has no attribute 'classobj'
'classobj' is not mentoned in the types module
[documentation](http://docs.python.org/2/library/types.html), but after some
search, I find out it corresponds to `types.ClassType`:
In [50]: type(Session.__dict__['Cuser']) == types.ClassType
Out[50]: True
Seeing from the above examples that type checking is not so straight forward,
my question is: is there a more consistent way to check types out there that
I'm not aware of?
Answer: python stresses duck-typing:
> if it walks like a duck and quacks like a duck, it's a duck.
Instead of focusing on type, focus on attributes. For example, if
hasattr(a,'next') (`hasattr(a,'__next__')` in python 3), then you know `a` can
be treated as an iterable.
|
Python sendmail with text file content
Question: I want to send mail via python script, I need it to alert me about some missed
files.
scripy have to read log file(*.txt) and send content of this file into my
mail, so I made it:
import smtplib, os
from email.mime.text import MIMEText
raport_file = open('alert.txt','rb')
alert_msg = MIMEText(raport_file.read().encode("utf-8"), 'plain', 'utf-8')
raport_file.close()
m = smtplib.SMTP()
m.connect("*****", 25)
m.sendmail("Check_Files", "*****", alert_msg.as_string())
m.quit()
script run, but there is no mail at all. If I replace alert_msg.as_string()
with "any text", everything works fine.
Answer:
import smtplib
import base64
import os
import sys
FROM = '[email protected]'
TO = '[email protected]'
MARKER = 'SIMPLE_MARKER_GOES_HERE'
if __name__ == "__main__":
filename = 'name_of_file'
# Read a file and encode it into base64 format
fo = open(filename, "rb")
filecontent = fo.read()
encodedcontent = base64.b64encode(filecontent) # base64
filename = os.path.basename(filename)
body ="""
Insert whatever message you want here or dynamically create.
"""
# Define the main headers.
part1 = """From: Matt Vincent <[email protected]>
To: %s
Subject: Sending Attachment
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (TO, MARKER, MARKER)
# Define the message action
part2 = """Content-Type: text/plain
Content-Transfer-Encoding:8bit
%s
--%s
""" % (body, MARKER)
# Define the attachment section
part3 = """Content-Type: multipart/mixed; name=\"%s\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename=%s
%s
--%s--
""" %(filename, filename, encodedcontent, MARKER)
message = part1 + part2 + part3
try:
smtpObj = smtplib.SMTP('domainhere')
smtpObj.sendmail(FROM, TO, message)
print "Successfully sent email"
except Exception:
print "Error: unable to send email"
|
Selectively printing values from a python dictionary
Question: I have have a huge graph consisting of well over 100000 keys so efficiency is
a huge issue. I am going through every keys' value, and for every value, I
want it to be a key in another dictionary, with the values being the remaining
values... E.g...
graph = {'foobar': ['1', '2', '3']}
result = {'1' : ['2', '3'], '2' : ['1', '3'], '3' : ['1', '2']} #in no particular order
Here is my code at the moment...
for i in heroDict.values():
for j in i:
if graph.has_key(j):
tempDict = copy.deepcopy(i)
tempDict.remove(j)
heroList = tempDict
graph[j] += heroList
else:
tempDict = copy.deepcopy(i)
tempDict.remove(j)
heroList = tempDict
graph[j] = heroList
return graph
'heroDict' is a dictionary similar to the example except very very large.
The problem I am having is that my code is running very slowly because of the
deepcopy() I am performing. so for the foobar example for example, I get '1'
as a key. I copy ['1', '2', '3'] into a temporary dict so the changes to it
wont affect my final dictionary that i return. Then I remove the key from the
['1', '2', '3'] and assign the key '1' to it. So I'm left with {'1' : ['2',
'3']} which is what I want but its taking too long because its iterating
100000+ times.
My final question is, can I improve this in any way so it runs faster?
Any help is greatly appreciated.
Answer: Permutations is included in `itertools`.
A typical use in your example is :
>>> from itertools import permutations
>>> values = graph['foobar']
>>> result = {x[0]:x[1:] for x in permutations(values)}
>>> print result
{'1': ('3', '2'), '2': ('3', '1'), '3': ('2', '1')}
Works with any number of values in foobar. Permutations is a generator, so you
may call one item at a time instead of generating the whole dict at once.
Not sure how fast that would be, though.
|
Python letters duplicates replace in Unicode string
Question: I need to replace two mistyped letters in a string, for example "bbig". But it
works only for Latin Letters, not for Cyrillic. I am using Python version
2.6.6 under Centos Linux.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import re
def reg(item):
item = re.sub(r'([A-ZА-ЯЁЄЇІ])\1', r'\1', item, re.U)
#this work only with latin too
#item = re.sub(r'(.)\1', r'\1', item, re.U)
return item
print reg('ББООЛЛЬЬШШООЙЙ')
print reg('BBIIGG')
The code above returns:
* ББООЛЛЬЬШШООЙЙ
* BIG
What did I do wrong? Thanks for your help.
Answer: You are using byte strings. This makes everything you use match and replace
bytes. That won't work if you want to match and replace letters.
Use unicode strings instead:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import re
def reg(item):
item = re.sub(ur'([A-ZА-ЯЁЄЇІ])\1', r'\1', item, re.U)
#this work only with latin too
#item = re.sub(r'(.)\1', r'\1', item, re.U)
return item
print reg(u'ББООЛЛЬЬШШООЙЙ')
print reg(u'BBIIGG')
Note that this works fine for precomposed characters but will fall flat with
characters composed using combining marks.
It will also be disastrous if the user tries to type this very sentence (hint:
check its second word).
|
Change the file extension for files in a folder in Python
Question: I would like to change the extension of the files in specific folder. i read
about this topic in the forum. using does ideas, I have written following code
and I expect that it would work but it does not. I would be thankful for any
guidance to find my mistake.
import os,sys
folder = 'E:/.../1936342-G/test'
for filename in os.listdir(folder):
infilename = os.path.join(folder,filename)
if not os.path.isfile(infilename): continue
oldbase = os.path.splitext(filename)
infile= open(infilename, 'r')
newname = infilename.replace('.grf', '.las')
output = os.rename(infilename, newname)
outfile = open(output,'w')
Answer: The `open` on the source file is unnecessary, since `os.rename` only needs the
source and destination paths to get the job done. Moreover, `os.rename` always
returns `None`, so it doesn't make sense to call `open` on its return value.
import os,sys
folder = 'E:/.../1936342-G/test'
for filename in os.listdir(folder):
infilename = os.path.join(folder,filename)
if not os.path.isfile(infilename): continue
oldbase = os.path.splitext(filename)
newname = infilename.replace('.grf', '.las')
output = os.rename(infilename, newname)
I simply removed the two `open`. Check if this works for you.
|
How to tell distutils to use gcc?
Question: I want to wrap a test project containing C++ and OpenMP code with Cython, and
build it with distutils via a `setup.py` file. The content of my file looks
like this:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
from Cython.Distutils import build_ext
modules = [Extension("Interface",
["Interface.pyx", "Parallel.cpp"],
language = "c++",
extra_compile_args=["-fopenmp"],
extra_link_args=["-fopenmp"])]
for e in modules:
e.cython_directives = {"embedsignature" : True}
setup(name="Interface",
cmdclass={"build_ext": build_ext},
ext_modules=modules)
The `-fopenmp` flag is used with gcc to compile and link against OpenMP.
However, if I just invoke
cls ~/workspace/CythonOpenMP/src $ python3 setup.py build
this flag is not recognized, because the compiler is clang:
running build
running build_ext
skipping 'Interface.cpp' Cython extension (up-to-date)
building 'Interface' extension
cc -Wno-unused-result -fno-common -dynamic -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I/usr/local/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python3/3.3.0/Frameworks/Python.framework/Versions/3.3/include/python3.3m -c Interface.cpp -o build/temp.macosx-10.8-x86_64-3.3/Interface.o -fopenmp
clang: warning: argument unused during compilation: '-fopenmp'
cc -Wno-unused-result -fno-common -dynamic -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I/usr/local/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python3/3.3.0/Frameworks/Python.framework/Versions/3.3/include/python3.3m -c Parallel.cpp -o build/temp.macosx-10.8-x86_64-3.3/Parallel.o -fopenmp
clang: warning: argument unused during compilation: '-fopenmp'
Parallel.cpp:24:10: warning: unknown pragma ignored [-Wunknown-pragmas]
#pragma omp parallel for
^
1 warning generated.
c++ -bundle -undefined dynamic_lookup -L/usr/local/lib -L/usr/local/opt/sqlite/lib build/temp.macosx-10.8-x86_64-3.3/Interface.o build/temp.macosx-10.8-x86_64-3.3/Parallel.o -o build/lib.macosx-10.8-x86_64-3.3/Interface.so -fopenmp
ld: library not found for -lgomp
clang: error: linker command failed with exit code 1 (use -v to see invocation)
error: command 'c++' failed with exit status 1
I've unsucessfully tried to specify gcc:
cls ~/workspace/CythonOpenMP/src $ python3 setup.py build --compiler=g++-4.7
running build
running build_ext
error: don't know how to compile C/C++ code on platform 'posix' with 'g++-4.7' compiler
How can I tell distutils to use gcc?
Answer: Try setting the "CC" and "CXX" environment variables from inside the setup.py
with os.environ.
|
Imports not working in Google App Engine project
Question: Im working in python to build a webapp using GAE. The project was originally
built with out GAE, and it worked just great, then I brought those files into
the GAE project, and all of a sudden they don't play so nice anymore. One file
land.py has 4 classes representing different land types, and a list of list
containing several instances of each one. They are all based off the land
class, in the land.py file.
class Land():
def __init__(self):
self.elevation = 0
self.neighbors = []
self.creatures = []
self.location = (0, 0)
self.was = None#to keep track of when flooded
def __str__(self):
return("location " + str(self.location) +
" elevation " + str(self.elevation) +
" neighbors " + str(len(self.neighbors)) +
" creatures " + str(x.name for x in self.creatures) + " | ")
def redefine(self, land):
self.elevation = land.elevation
self.neighbors = land.neighbors
self.creatures = land.creatures
self.location = land.location
self.was = land
The other class simulation.py imports land, and should be able to use it, but
when I try
self.map = Land.landMass(the list of list's)
for row in self.map:
print(row)
It will print `'[,,,,,,,][,,,,,,,][,,,,,,,][,,,,,,,]'` it does see that there
are objects in there because when I do
for i in self.map:
for x in i:
output += x.__str__()
it prints each land object's proper output. This is a problem because when I
want to check
for row in self.map:
for column in row:
if isinstance(land, Land.Water): #or type(land)
it first has no clue what land is but it also does know what Land.Water is. I
can provide code if you like, but it's hard to figure out exactly where the
problem could be. Again, in its own project file it all works but in the GAE
project it doesn't. Anyone know why?
Answer: print(row) is doing a repr(object) not str(obj) If you look at the source of
the page you will see something like
As for the rest of your code, without knowing the definition of Land it's hard
to tell. Is Land a db/ndb Model ?
Also your title for this question doesn't really have anything to do with the
question you have asked. I don't see any problems with imports.
As to the specific question about "it first has no clue what land is" I assume
you are getting a `NameError name 'land' is not defined` , if not please
include a bit more detail as to the error. And if it is the correct error,
where are you defining `land` ?
Also this line looks wrong `if isinstance(land, Land.Water): or type(land)`
that would give you a SyntaxError
|
Django - how to not loose verbose_name and other attributes of Field when overriding its form in ModelForm?
Question: Given:
#models.py
from django.db import models
class MyModel(models.Model):
myfield = models.IntegerField('Detailed description')
#forms.py
from django import forms
from models import MyModel
class MyModelForm(forms.ModelForm):
myfield = forms.IntegerField()
class Meta:
model = MyModel
With this setup - verbose_name will not be shown on admin page, name of field
will be instead (with capitalized first letter). If remove overriding field
from MyModelForm - verbose name will be shown as usual. If provide string with
description as argument `label`, `forms.IntegerField()` \- it will be
displayed on admin page.
Im looking for pythonic way to display verbose_name defined in model class in
case if this field form is overrided in ModelForm, without using `label` hint.
Any thoughts?
Answer: You can access the verbose name of the model in the form like this:
myfield = models.IntegerField(label=MyModel._meta.get_field_by_name('myfield')[0].verbose_name)
|
Use numpy in python3 - Ubuntu
Question: I'm trying to use `numpy` with `python3` in Ubuntu 12.04. The command
`python3` in the terminal returns:
Python 3.2.3 (default, Oct 19 2012, 20:13:42)
[GCC 4.6.3] on linux2
When I try to import `numpy` I get the error:
import numpy as np
ImportError: No module named numpy
So I tried to install it with:
sudo pip install numpy
which returns:
Requirement already satisfied (use --upgrade to upgrade): numpy in /usr/lib/python2.7/dist-packages
So it is installed but for python2.7 and apparently I need to install `numpy`
for python3. If I do:
sudo pip install upgrade
I get:
Could not find any downloads that satisfy the requirement upgrade
No distributions at all found for upgrade
I've tried the solution posted
[here](http://stackoverflow.com/questions/16096143/why-doesnt-numpy-import-in-
idle-3-30-on-ubuntu-12-10-64-bit?rq=1), namely doing:
sudo apt-get install python3-pip
which is not found. I've also gone
[here](https://pypi.python.org/pypi/numpy/1.7.1) but I only see Windows
versions available for download for python3.
Answer: If you want to install it from Ubuntu repositories, which is easier, but the
version is older, try
sudo apt-get install python3-numpy
If you want it via `pip`, you should probably start with
sudo apt-get install python3-setuptools
and then you'll have something like `easy_install-3.2` which you can use to
sudo easy_install pip
and then
sudo pip-3.2 install numpy
|
New django project: Cannot import name connections
Question: I'm having a problem with Django. If you could help me, I'd very much
appreciate it.
So, I've found lots of people with a similar problem, but none of the
"solutions" work for me. I'm learning how to use django and I've successfully
installed it.
But, I get an error when executing the import from the **init**.py file:
from django.db import connections
Here's the error:
raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
ImportError: Could not import settings 'TestProject.settings' (Is it on sys.path?): cannot import name connections
The containing django folder is included on my PYTHONPATH, and my file
structure looks like this:
TestProject
--manage.py
--TestProject
----__init__.py
----settings.py
etc.
This is my manage.py file:
#!/usr/bin/env python import os import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "TestProject.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
I don't really know how to troubleshoot this. I'm also new to Python, so
forgive me if this is completely obvious to someone else.
Thanks for your help.
Answer: This is a weird quirk indeed. I found the following to work in my program:
1. Import django settings.
2. Set the default environment.
3. ACCESS e.g. SITE_ID (or another property, but just use e.g. SITE_ID) through settings.
4. Finally, you should be able to import.
E.g.
from django.conf import settings
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")
settings.SITE_ID
or use another variable like `DEBUG`; note.. this line does nothing.. it just
accesses the settings and seems to 'activate' the environment. You could also
do a simple print statement like `print settings.SITE_ID`, but that's not
necessary.)
from myapp.models import MyModel, MyOtherModel
If you do everything in that order.. well it worked for me! The magic happens
when you access an actual setting before you do the import of a model.
I think this might be a bug/error in Django 1.5
|
elif giving syntax error python?
Question: I'm trying to parse an XML document and get certain tags. I'd like to grab the
name tag (only if it's the name tag nested within artist) and the title tag
(only if it's the one nested within release).
That's not too important, though, the important thing is that I'm for some
reason getting an error saying the elif statement is invalid syntax
I've looked through other posts and made sure that my tabbing is correct and
that there aren't any extra newlines after any of the if's.
This is the code snippet:
from lxml import etree
import sys
#infile = raw_input("Please enter an XML file to parse: ")
outfile = open('results.txt', 'a')
path = []
for event, elem in etree.iterparse('releases7.xml', events=("start", "end")):
if event == 'start':
path.append(elem.tag)
elif event == 'end':
# process the tag
if elem.tag == 'name':
if 'artist' in path and not 'extraartists' in path and not 'track' in path:
outfile.write( 'artist = ' + elem.text.encode('utf-8') + '\n' )
elif elem.tag == 'title':
if 'release' in path and not 'track' in path:
outfile.write( 'release title = ' + elem.text.encode('utf-8') + '\n')
else:
print 'nonrelease'
path.pop()
This is the error:
File "DataDestroy_Fast.py", line 18
elif elem.tag == 'title':
^
SyntaxError: invalid syntax
(Note: Using Python2.7 on Mac OSX)
Answer: As I mentioned in a comment, I had an error like this once that was due to a
extra tab character that just happened to be right at a position where it did
nothing visible.
If your editor will let you view invisible characters like tabs and newlines,
you may be able to actually see if that the case. My editor also has an option
to convert tabs to spaces which would fix such a problem. If all else fails,
just delete all the whitespace at the beginning of the line and then carefully
do it over and then see if the error still occurs.
Recently I ran across a really good
[answer](http://stackoverflow.com/a/20308966/355230) to a similar question
[_How can I add a print statement to this code without getting an indentation
error_](http://stackoverflow.com/questions/20308918/how-can-i-add-a-print-
statement-to-this-code-without-getting-an-indentation-erro).
|
$ python syntaxerror HELP (version 2.5.4)
Question: Downloaded Python 2.5.4 (Windows)
Opened Python Shell and entered
print "hello world"
got back
hello world
Opened Notepad++
entered `print "hello world"`
saved as hello.py
exited that file and went back to the shell
entered in the shell
$ python hello.py
got
SyntaxError: invalid syntax
I am not sure what is causing this. I have tried to change the directory,
atleast I think I did control panel > environment variables > path > added
;C:\Python26 to the very end I then restarted my comp and tried
$ python hello.py
still got nothing but the error again. I am literally going nuts trying to get
this to work. I am very very new to python and programming languages in
general. So, if you do respond, please make it understandable to a beginner.
Thank you in advance for your help.
Answer: You are running the `python hello.py` command within the python shell itself
which is not possible. If you are in the python shell you can run `import
hello` to run the script as you want to.
|
Regular idetifying repeatative patterns
Question: My data patterns looks like below,
t_hat_1
t_hat_2
t_hat_3
name
s_flower_1
s_flower_2
s_flower_3
s_flower_22
s_flower_23
address
I need to identify all the repeating matches like t_hat_1,2,3 &
s_flower_1,2,3,22,23...I don't have the fixed number of repeatative items..for
example:-hat will have [1-3] and flower[1-50]
What would be the most efficient way to identify these elements in Python
regular expression..
Answer: `re.findall` will return all matches:
import re
data = """
t_hat_1
t_hat_2
t_hat_3
name
s_flower_1
s_flower_2
s_flower_3
s_flower_22
s_flower_23
address
"""
flowers_patterns = re.findall('(s_flower_\d+)', data)
hat_patterns = re.findall('(t_hat_\d+)', data)
|
How to access pubmed data for forms with multiple pages in python crawler
Question: I am trying to crawl pubmed with python and get the pubmed ID for all papers
that an article was cited by.
For example this article (ID: 11825149)
<http://www.ncbi.nlm.nih.gov/pubmed/11825149> Has a page linking to all
articles that cite it:
[http://www.ncbi.nlm.nih.gov/pubmed?linkname=pubmed_pubmed_citedin&from_uid=11825149](http://www.ncbi.nlm.nih.gov/pubmed?linkname=pubmed_pubmed_citedin&from_uid=11825149)
The problem is it has over 200 links but only shows 20 per page. The 'next
page' link is not accessible by url.
Is there a way to open the 'send to' option or view the content on the next
pages with python?
How I currently open pubmed pages:
def start(seed):
webpage = urlopen(seed).read()
print webpage
citedByPage = urlopen('http://www.ncbi.nlm.nih.gov/pubmedlinkname=pubmed_pubmed_citedin&from_uid=' + pageid).read()
print citedByPage
From this I can extract all the cited by links on the first page, but how can
I extract them from all pages? Thanks.
Answer: I was able to get the cited by IDs using a method from this page
<http://www.bio-cloud.info/Biopython/en/ch8.html>
Back in Section 8.7 we mentioned ELink can be used to search for citations of a given paper. Unfortunately this only covers journals indexed for PubMed Central (doing it for all the journals in PubMed would mean a lot more work for the NIH). Let’s try this for the Biopython PDB parser paper, PubMed ID 14630660:
>>> from Bio import Entrez
>>> Entrez.email = "[email protected]"
>>> pmid = "14630660"
>>> results = Entrez.read(Entrez.elink(dbfrom="pubmed", db="pmc",
... LinkName="pubmed_pmc_refs", from_uid=pmid))
>>> pmc_ids = [link["Id"] for link in results[0]["LinkSetDb"][0]["Link"]]
>>> pmc_ids
['2744707', '2705363', '2682512', ..., '1190160']
Great - eleven articles. But why hasn’t the Biopython application note been found (PubMed ID 19304878)? Well, as you might have guessed from the variable names, there are not actually PubMed IDs, but PubMed Central IDs. Our application note is the third citing paper in that list, PMCID 2682512.
So, what if (like me) you’d rather get back a list of PubMed IDs? Well we can call ELink again to translate them. This becomes a two step process, so by now you should expect to use the history feature to accomplish it (Section 8.15).
But first, taking the more straightforward approach of making a second (separate) call to ELink:
>>> results2 = Entrez.read(Entrez.elink(dbfrom="pmc", db="pubmed", LinkName="pmc_pubmed",
... from_uid=",".join(pmc_ids)))
>>> pubmed_ids = [link["Id"] for link in results2[0]["LinkSetDb"][0]["Link"]]
>>> pubmed_ids
['19698094', '19450287', '19304878', ..., '15985178']
This time you can immediately spot the Biopython application note as the third hit (PubMed ID 19304878).
Now, let’s do that all again but with the history …TODO.
And finally, don’t forget to include your own email address in the Entrez calls.
|
AttributeError: 'NoneType' object has no attribute 'get_width'
Question: This is simple script on Ascii art generator from image , I get this error : I
run it in cmd line , and I am using windows 7 operating system
Traceback (most recent call last):
File "C:\Python33\mbwiga.py", line 251, in <module>
converter.convertImage(sys.argv[-1])
File "C:\Python33\mbwiga.py", line 228, in convertImage
self.getBlobs()
File "C:\Python33\mbwiga.py", line 190, in getBlobs
width, height = self.cat.get_width(), self.cat.get_height()
AttributeError: 'NoneType' object has no attribute 'get_width'
what am I messing here..?? can some one help..?
Here is full source code some one asked :
import sys
import pygame
NAME = sys.argv[0]
VERSION = "0.1.0" # The current version number.
HELP = """ {0} : An ASCII art generator. Version {1}
Usage:
{0} [-b BLOB_SIZE] [-p FONT_WIDTH:HEIGHT] [-c] image_filename
Commands:
-b | --blob Change the blob size used for grouping pixels. This is the width of the blob; the height is calculated by multiplying the blob size by the aspect ratio.
-p | --pixel-aspect Change the font character aspect ratio. By default this is 11:5, which seems to look nice. Change it based on the size of your font. Argument is specified in the format "WIDTH:HEIGHT". The colon is important.
-c | --colour Use colour codes in the output. {0} uses VT100 codes by default, limiting it to 8 colours, but this might be changed later.
-h | --help Shows this help.""""
.format(NAME, VERSION)
NO_IMAGE = \
""" Usage: %s [-b BLOB_SIZE] [-p FONT_WIDTH:HEIGHT] image_filename """ % (NAME)
import math
CAN_HAS_PYGAME = False
try:
import pygame
except ImportError:
sys.stderr.write("Can't use Pygame's image handling! Unable to proceed, sorry D:\n")
exit(-1)
VT100_COLOURS = {"000": "[0;30;40m",
"001": "[0;30;41m",
"010": "[0;30;42m",
"011": "[0;30;43m",
"100": "[0;30;44m",
"101": "[0;30;45m",
"110": "[0;30;46m",
"111": "[0;30;47m",
"blank": "[0m"}
VT100_COLOURS_I = {"000": "[0;40;30m",
"001": "[0;40;31m",
"010": "[0;40;32m",
"011": "[0;40;33m",
"100": "[0;40;34m",
"101": "[0;40;35m",
"110": "[0;40;36m",
"111": "[0;40;37m",
"blank": "[0m"}
# Convenient debug function.
DO_DEBUG = True
def debug(*args):
if not DO_DEBUG: return # Abort early, (but not often).
strrep = ""
for ii in args:
strrep += str(ii)
sys.stderr.write(strrep + "\n") # Write it to stderr. Niiicce.
# System init.
def init():
""" Start the necessary subsystems. """
pygame.init() # This is the only one at the moment...
# Get a section of the surface.
def getSubsurface(surf, x, y, w, h):
try:
return surf.subsurface(pygame.Rect(x, y, w, h))
except ValueError as er:
return getSubsurface(surf, x, y, w - 2, h - 2)
# The main class.
class AAGen:
""" A class to turn pictures into ASCII "art". """
def __init__(self):
""" Set things up for a default conversion. """
# Various blob settings.
self.aspectRatio = 11.0 / 5.0 # The default on my terminal.
self.blobW = 12 # The width. Also, the baseline for aspect ratio.
self.blobH = self.aspectRatio * self.blobW # The height.
self.blobList = []
self.cat = None # The currently open file.
self.chars = """#@%H(ks+i,. """ # The characters to use.
self.colour = False # Do we use colour?
def processArgs(self):
""" Process the command line arguments, and remove any pertinent ones. """
cc = 0
for ii in sys.argv[1:]:
cc += 1
if ii == "-b" or ii == "--blob":
self.setBlob(int(sys.argv[cc + 1]))
elif ii == "-p" or ii == "--pixel-aspect":
jj = sys.argv[cc + 1]
self.setAspect(float(jj.split(":")[1]) / float(jj.split(":")[0]))
elif ii == "-c" or ii == "--colour":
self.colour = True
elif ii == "-h" or ii == "--help":
print(HELP)
exit(0)
if len(sys.argv) == 1:
print(NO_IMAGE)
exit(0)
def setBlob(self, blobW):
""" Set the blob size. """
self.blobW = blobW
self.blobH = int(math.ceil(self.aspectRatio * self.blobW))
def setAspect(self, aspect):
""" Set the aspect ratio. Also adjust the blob height. """
self.aspectRatio = aspect
self.blobH = int(math.ceil(self.blobW * self.aspectRatio))
def loadImg(self, fname):
""" Loads an image into the store. """
try:
tmpSurf = pygame.image.load(fname)
except:
print("Either this is an unsupported format, or we had problems loading the file.")
return None
self.cat = tmpSurf.convert(32)
if self.cat == None:
sys.stderr.write("Problem loading the image %s. Can't convert it!\n"
% fname)
return None
def makeBlob(self, section):
""" Blob a section into a single ASCII character."""
pxArr = pygame.surfarray.pixels3d(section)
colour = [0, 0, 0]
size = 0 # The number of pixels.
# Get the density/colours.
for i in pxArr:
for j in i:
size += 1
# Add to the colour.
colour[0] += j[0]
colour[1] += j[1]
colour[2] += j[2]
# Get just the greyscale.
grey = apply(lambda x, y, z: (x + y + z) / 3 / size,
colour)
if self.colour:
# Get the 3 bit colour.
threshold = 128
nearest = ""
nearest += "1" if (colour[0] / size > threshold) else "0"
nearest += "1" if (colour[1] / size > threshold) else "0"
nearest += "1" if (colour[2] / size > threshold) else "0"
return VT100_COLOURS[nearest], grey
return grey
# We just use a nasty mean function to find the average value.
# total = 0
# for pix in pxArr.flat:
# total += pix # flat is the array as a single-dimension one.
# return total / pxArr.size # This is a bad way to do it, it loses huge amounts of precision with large blob size. However, with ASCII art...
def getBlobs(self):
""" Get a list of blob locations. """
self.blobList = [] # Null it out.
width, height = self.cat.get_width(), self.cat.get_height()
# If the image is the wrong size for blobs, add extra space.
if height % self.blobH != 0 or width % self.blobW != 0:
oldimg = self.cat
newW = width - (width % self.blobW) + self.blobW
newH = height - (height % self.blobH) + self.blobH
self.cat = pygame.Surface((newW, newH))
self.cat.fill((255, 255, 255))
self.cat.blit(oldimg, pygame.Rect(0, 0, newW, newH))
# Loop over subsections.
for row in range(0, height, int(self.blobH)):
rowItem = []
for column in range(0, width, self.blobW):
# Construct a Rect to use.
src = pygame.Rect(column, row, self.blobW, self.blobH)
# Now, append the reference.
rowItem.append(self.cat.subsurface(src))
self.blobList.append(rowItem)
return self.blobList
def getCharacter(self, value, colour = False):
""" Get the correct character for a pixel value. """
col = value[0] if colour else ""
value = value[1] if colour else value
if not 0 <= value <= 256:
sys.stderr.write("Incorrect pixel data provided! (given %d)\n"
% value)
return "E"
char = self.chars[int(math.ceil(value / len(self.chars))) % len(self.chars)]
return char + col
def convertImage(self, fname):
""" Convert an image, and print it. """
self.loadImg(fname)
self.getBlobs()
pval = "" # The output value.
# Loop and add characters.
for ii in converter.blobList:
for jj in ii:
ch = self.makeBlob(jj)
pval += self.getCharacter(ch, self.colour) # Get the character.
# Reset the colour at the end of the line.
if self.colour: pval += VT100_COLOURS["blank"]
pval += "\n" # Split it up by line.
pval = pval[:-1] # Cut out the final newline.
print(pval) # Print it.
# Main program execution.
if __name__ == "__main__":
init()
converter = AAGen()
converter.processArgs()
converter.convertImage(sys.argv[-1])
sys.exit(1)
Answer: The problem is hidden somewhere in the `loadImg`. The error says that
`self.cat` is `None`. The `self.cat` could get the `None` when initialised at
the line 97, or it was assigned the result of `tmpSurf.convert(32)` and the
result of that call is `None`. In the first case, you should observe the
message `Either this is an unsupported format...`, in the later case you
should see the message `Problem loading the image...` as you are testing
`self.cat` against `None`:
def loadImg(self, fname):
""" Loads an image into the store. """
try:
tmpSurf = pygame.image.load(fname)
except:
print("Either this is an unsupported format, or we had problems loading the file.")
return None
self.cat = tmpSurf.convert(32)
if self.cat == None:
sys.stderr.write("Problem loading the image %s. Can't convert it!\n"
% fname)
return None
By the way, `return None` is exactly the same as `return` without argument.
Also, the last `return None` can be completely removed because any function
implicitly returns `None` when the end of the body is reached.
For testing to `None`, the `is` operator is recommended -- i.e. `if self.cat
is None:`.
**Update** based on the comment from May 31.
If you want to make a step further, you should really learn Python a bit. Have
a look at the end of the original script (indentation fixed):
# Main program execution.
if __name__ == "__main__":
init() # pygame is initialized here
converter = AAGen() # you need the converter object
converter.processArgs() # the command-line arguments are
# converted to the object attributes
converter.convertImage(sys.argv[-1]) # here the conversion happens
sys.exit(1) # this is unneccessary for the conversion
If the original script is saved in the `mbwiga.py`, then you can or call it as
a script, or you can use it as a module. In the later case, the body below the
`if __name__ == "__main__":` is not executed, and you have to do it in the
caller script on your own. Say you have `test.py` that tries to do that. Say
it is located at the same directory. It must import the `mbwiga`. Then the
`mbwiga.` becomes the prefix of the functionality from inside the module. Your
code may look like this:
import mbwiga
mbwiga.init() # pygame is initialized here
converter = mbwiga.AAGen() # you need the converter object
# Now the converter is your own object name. It does not take the mbwiga. prefix.
# The original converter.processArgs() took the argumens from the command-line
# when mbwiga.py was called as a script. If you want to use some of the arguments
# you can set the converter object's attributes the way that is shown
# in the .processArgs() method definition. Or you can call it the same way to
# extract the information from the command line passed when you called the test.py
#
converter.processArgs()
# Now the conversion
converter.convertImage('myImageFilename.xxx') # here the conversion happens
|
importing pygame on python3 on virtualenv cause ImportError
Question: I have python3.3.1 on ubuntu lucid,which I invoke thru virtualenvwrapper ' .I
wanted to learn pygame,so I used pip to install it.Before that I installed the
sdl and smpeg dev libraries
me@ubuntu: sudo apt-get install libsdl1.2-dev
...
me@ubuntu: sudo apt-get install libsmpeg-dev
...
me@ubuntu: workon envpy331
(envpy331)me@ubuntu:~$ pip install pygame
Downloading pygame-1.9.1release.tar.gz (2.1MB): 2.1MB downloaded
Running setup.py egg_info for package pygame
WARNING, No "Setup" File Exists, Running "config.py"
Using UNIX configuration...
Hunting dependencies...
SDL : found 1.2.14
FONT : not found
IMAGE : not found
MIXER : not found
SMPEG : found 0.4.5
PNG : found
JPEG : found
SCRAP : found
PORTMIDI: not found
PORTTIME: not found
....
Continuing With "setup.py"
Successfully installed pygame
Cleaning up...
Then I tried to import pygame and this caused an import error
(envpy331)me@ubuntu:~$ python
Python 3.3.1 (default, Apr 19 2013, 11:41:37)
[GCC 4.4.3] on linux
>>> import pygame
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/me/.virtualenvs/envpy331/lib/python3.3/site-packages/pygame/__init__.py", line 95, in <module>
from pygame.base import *
ImportError: /home/me/.virtualenvs/envpy331/lib/python3.3/site-packages/pygame/base.cpython-33m.so: undefined symbol: PyCObject_FromVoidPtr
Any idea how to correct this?
Answer: Pygame has not been entirely ported to Python 3, only some of the modules. If
you use Python 2.7 everything should work. I recently had the same problem.
Some suggested using individual modules of Pygame with Python 3 but this may
be tricky to set up.
|
wxPython Drag and Drop exit code 139 crash
Question: I am experimenting with wxPython trying to learn drag and drop. Why doesn't
the following work on Linux? The app starts up, but when I drag the static
text into the text field, I get a 139 exit code with version 2.8 using python
2.7.
import wx
class DropTarget(wx.DropTarget):
def __init__(self):
wx.DropTarget.__init__(self)
self.dataobject = wx.PyTextDataObject()
self.SetDataObject(self.dataobject)
def OnData(self, x, y, d):
pass
class Txt(wx.StaticText):
def __init__(self, parent, label_):
wx.StaticText.__init__(self, parent, label=label_)
self.Bind(wx.EVT_LEFT_DOWN, self.handle)
def handle(self, event):
ds = wx.DropSource(self)
d = wx.PyTextDataObject('some text')
ds.SetData(d)
ds.DoDragDrop(True)
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, 'whatevs')
main_panel = wx.Panel(self)
txt = Txt(main_panel, 'ONE')
txt2 = wx.TextCtrl(main_panel)
s = wx.BoxSizer(wx.VERTICAL)
s.Add(txt)
s.Add(txt2)
main_panel.SetSizer(s)
dt = DropTarget()
txt2.SetDropTarget(dt)
if __name__ == '__main__':
app = wx.App()
MyFrame().Show(True)
app.MainLoop()
Answer: Try replacing the line
ds = wx.DropSource(self)
with
ds = wx.DropSource(self.GetParent())
I was able to reproduce the crash you are seeing, but once I made the above
change the crash went away.
It seems that for some reason, wx doesn't like instances of `wx.StaticText`
(or subclasses of it in your case) being passed to the `wx.DropSource`
constructor. I'm not sure why.
I changed your code so that `Txt` derived from `wx.TextCtrl` instead of
`wx.StaticText` and I couldn't reproduce the problem any more. I also tried
playing around with the first sample program found on
<http://wiki.wxpython.org/DragAndDrop>, and found that I could make it crash
if I set the drop source to be one of the `StaticText` objects this code
creates instead of a `TextCtrl`.
If there's anything in the wxWidgets or wxPython documentation that says you
can't use a `wx.StaticText` as a drop source, I didn't find it. It certainly
wasn't obvious to me. (The [documentation for
wxDropSource](http://docs.wxwidgets.org/trunk/classwx_drop_source.html) says
that you pass to each constructor
> The window which initiates the drag and drop operation.
However, there doesn't appear to be any restriction on the types of 'window'
(or 'widget') that you can use as a drop source.)
|
neo4django: AttributeError: type object 'Model' has no attribute '__metaclass__'
Question: I was just trying neo4django's [very own
example](https://neo4django.readthedocs.org/en/latest/writing-models.html),
namely
from neo4django.db import models
class Person(models.NodeModel):
name = models.StringProperty()
age = models.IntegerProperty()
friends = models.Relationship('self',rel_type='friends_with')
However, when running `python manage.py syncdb` I get the following error:
AttributeError: type object 'Model' has no attribute '__metaclass__'
Any ideas?
(I would use label "neo4django" here in Stackoverflow, but it does not let me
create a new label yet).
Answer: See <https://github.com/scholrly/neo4django/issues/143-> we won't support
Django 1.5+ until the next release!
|
cx_Freeze and Python 3.3
Question: So, I have some Python 3.3 code that I need to make an .exe from on Windows. I
discovered the only way to do it is using cx_Freeze. But, I haven't even got
further than installation. This question describes my problem perfectly
(except I run Python 3.3), and has not been answered yet:
[installing/using
cx_freeze](http://stackoverflow.com/questions/13906343/installing-using-cx-
freeze)
When I try to run "python setup.py build" from cmd I get:
"importerror: no module named cx_freeze"
I can't get past this step, and have searched for a solution for an hour
unsuccessfully.
In case it's relevant Python is installed at C:\Python33. Both Python and
cx_Freeze I installed are 64-bit versions. Version of cx_Freeze I installed
was: cx_Freeze-4.3.1.win-amd64-py3.3. I tried reinstalling. When I do "import
cx_Freeze" in IDLE, it doesn't show any errors.
Please also note I'm a programming beginner.
Answer: Answer to the question is in my other answer. Make sure you read it first as
this one expands on it.
Ok, so after a few more hours of pain I got my game to run as an .exe on
computers of people who don't have Python installed, which was my goal! I was
using Pygame to make the game if anyone needs to know.
So, here's shortly what I did after the step in the other answer I gave:
This is the setup.py I used:
from cx_Freeze import setup, Executable
includefiles = ['add_all_your_files_here, example.png, example.mp3']
includes = []
excludes = []
packages = []
setup(
name = 'yourgame',
version = '1.0.0',
description = '',
author = 'John Doe',
author_email = '[email protected]',
options = {'build_exe': {'excludes':excludes,'packages':packages,'include_files':includefiles}},
executables = [Executable('yourgame.py')]
)
Note that I couldn't figure (and didn't want to bother) about how to include
files from other folders, so I put them all together where the setup.py was. I
tried putting the relative path, but seems like I should've put the absolute.
To notice what files were missing I had to run the exe from cmd so when it
would crash I could read what was the error. This wasn't possible to do when I
opened the .exe from Windows because the window would close too fast.
Other than files that my code required, it also wanted some other .py files.
Namely:
re.py
sre_compile.py
sre_constants.py
sre_parse.py
I copied them from python (c:\Python33\Lib) to my game folder.
The .exe was then able to run my game without problems on my and another
computer that doesn't have python installed (no font problems for example, as
I heard some people have).
I've spent 9 hours in two days to figure all this out. Hope it helps other
beginners.
|
Python pandas an efficient way to see which column contains a value and use its coordinates as an offset
Question: As part of trying to learn pandas I'm trying to reshape a spreadsheet. After
removing non zero values I need to get some data from a single column.
For the sample columns below, I want to find the most effective way of finding
the row and column index of the `cell` that contains the value `date` and get
the value next to it. (e.g. here it would be `38477`.
In practice this would be a much bigger DataFrame and the `date` row could
change and it may not always be in the first column.
What is the best way to find out where `date` is in the array and return the
value in the adjacent cell?
Thanks
<bound method DataFrame.head of 0 1 2 4 5 7 8 10 \
1 some title
2 date 38477
5 cat1 cat2 cat3 cat4
6 a b c d e f g
8 Z 167.9404 151.1389 346.197 434.3589 336.7873 80.52901 269.1486
9 X 220.683 56.0029 73.73679 428.8939 483.7445 251.1877 243.7918
10 C 433.0189 390.1931 251.6636 418.6703 12.21859 113.093 136.28
12 V 226.0135 418.1141 310.2038 153.9018 425.7491 73.08073 277.5065
13 W 295.146 173.2747 2.187459 401.6453 51.47293 175.387 397.2021
14 S 306.9325 157.2772 464.1394 216.248 478.3903 173.948 328.9304
15 A 19.86611 73.11554 320.078 199.7598 467.8272 234.0331 141.5544
Answer: This really just reformats a lot of the iteration you are doing to make it
clearer and take advantage of pandas ability to easily select, etc.
First, we need a dummy dataframe (with date in the last row and explicitly
ordered the way you have in your setup)
import pandas as pd
df = pd.DataFrame({"A": [1,2,3,4,np.NaN],
"B":[5, 3, np.NaN, 3, "date"],
"C":[np.NaN,2, 1,3, 634]})[["A","B","C"]]
A clear way to do it is to find the row and then enumerate over the row to
find `date`:
row = df[df.apply(lambda x: (x == "date").any(), axis=1)].values[0] # will be an array
for i, val in enumerate(row):
if val == "date":
print row[i + 1]
break
If your spreadsheet only has a few non-numeric columns, you could go by
column, check for date and get a row and column index (this may be faster
because it searches by column rather than by row, though I'm not sure)
# gives you column labels, which are `True` if at least one entry has `date` in it
# have to check `kind` otherwise you get an error.
col_result = df.apply(lambda x: x.dtype.kind == "O" and (x == "date").any())
# select only columns where True (this should be one entry) and get their index (for the label)
column = col_result[col_result].index[0]
col_index = df.columns.get_loc(column)
# will be True if it contains date
row_selector = df.icol(col_index) == "date"
print df[row_selector].icol(col_index + 1).values
|
solve ode using multistep solver
Question: The following is the code for multiple solvers so far. The system for this
problem is here, [our
system](http://stackoverflow.com/questions/16747624/setup-odes-in-
python?noredirect=1#comment24123067_16747624) However, when I execute it in
Python, it shows me the following error:
Traceback (most recent call last): File
"G:\math3511\assignment\assignment5\qu2", line 59, in X =
AdamsBashforth4(equation, init, t) File
"G:\math3511\assignment\assignment5\qu2", line 32, in AdamsBashforth4 k2 = h *
f( x[i] + 0.5 * k1, t[i] + 0.5 * h ) TypeError: can't multiply sequence by
non-int of type 'float'
the code:
import numpy
from numpy import array, exp, linspace
def AdamsBashforth4( f, x0, t ):
"""
Fourth-order Adams-Bashforth method::
u[n+1] = u[n] + dt/24.*(55.*f(u[n], t[n]) - 59*f(u[n-1], t[n-1]) +
37*f(u[n-2], t[n-2]) - 9*f(u[n-3], t[n-3]))
for constant time step dt.
RK2 is used as default solver for first steps.
"""
n = len( t )
x = numpy.array( [ x0 ] * n )
# Start up with 4th order Runge-Kutta (single-step method). The extra
# code involving f0, f1, f2, and f3 helps us get ready for the multi-step
# method to follow in order to minimize the number of function evaluations
# needed.
f1 = f2 = f3 = 0
for i in xrange( min( 3, n - 1 ) ):
h = t[i+1] - t[i]
f0 = f( x[i], t[i] )
k1 = h * f0
k2 = h * f( x[i] + 0.5 * k1, t[i] + 0.5 * h )
k3 = h * f( x[i] + 0.5 * k2, t[i] + 0.5 * h )
k4 = h * f( x[i] + k3, t[i+1] )
x[i+1] = x[i] + ( k1 + 2.0 * ( k2 + k3 ) + k4 ) / 6.0
f1, f2, f3 = ( f0, f1, f2 )
for i in xrange( n - 1 ):
h = t[i+1] - t[i]
f0 = f( x[i], t[i] )
k1 = h * f0
k2 = h * f( x[i] + 0.5 * k1, t[i] + 0.5 * h )
k3 = h * f( x[i] + 0.5 * k2, t[i] + 0.5 * h )
k4 = h * f( x[i] + k3, t[i+1] )
x[i+1] = x[i] + h * ( 9.0 * fw + 19.0 * f0 - 5.0 * f1 + f2 ) / 24.0
f1, f2, f3 = ( f0, f1, f2 )
return x
def equation(X, t):
x, y = X
return [ x+y-exp(t), x+y+2*exp(t) ]
init = [ -1.0, -1.0 ]
t = linspace(0, 4, 50)
X = AdamsBashforth4(equation, init, t)
Answer: It seems that f is returning a sequence (list, tuple, or like) and there's no
operation to multiply all items in a sequence by a value.
Dirk is right, looking at your algorithm, your equation should return (even if
it small) a numpy array, as you can scalar-multiply a numpy array. So keeping
your code but embedding your return in equation with an array. Like this:
np.array([1,2]) # a numpy array containing [1,2]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.