text
stringlengths 226
34.5k
|
---|
Getting very high values in linear regression
Question: I am trying to make a simple MLP to predict values of a pixel of an image -
[original blog](http://evolvingstuff.blogspot.in/2012/12/generating-mona-lisa-
pixel-by-pixel.html) . Here's my earlier attempt using Keras in python -
[link](https://github.com/goelakash/MonaNet/blob/master/MonaNet.py)
I've tried to do the same in tensorflow, but I am getting very large output
values (~10^12) when they should be less than 1.
Here's my code:
import numpy as np
import cv2
from random import shuffle
import tensorflow as tf
'''
Image preprocessing
'''
image_file = cv2.imread("Mona Lisa.jpg")
h = image_file.shape[0]
w = image_file.shape[1]
preX = []
preY = []
for i in xrange(h):
for j in xrange(w):
preX.append([i,j])
preY.append(image_file[i,j,:].astype('float32')/255.0)
print preX[:5], preY[:5]
zipped = [i for i in zip(preX,preY)]
shuffle(zipped)
X_train = np.array([i for (i,j) in zipped]).astype('float32')
Y_train = np.array([j for (i,j) in zipped]).astype('float32')
print X_train[:10], Y_train[:10]
'''
Tensorflow code
'''
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
x = tf.placeholder(tf.float32, shape=[None,2])
y = tf.placeholder(tf.float32, shape=[None,3])
'''
Layers
'''
w1 = weight_variable([2,300])
b1 = bias_variable([300])
L1 = tf.nn.relu(tf.matmul(X_train,w1)+b1)
w2 = weight_variable([300,3])
b2 = bias_variable([3])
y_model = tf.matmul(L1,w2)+b2
'''
Training
'''
# criterion
MSE = tf.reduce_mean(tf.square(tf.sub(y,y_model)))
# trainer
train_op = tf.train.GradientDescentOptimizer(learning_rate = 0.01).minimize(MSE)
nb_epochs = 10
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
cost = 0
for i in range(nb_epochs):
sess.run(train_op, feed_dict ={x: X_train, y: Y_train})
cost += sess.run(MSE, feed_dict ={x: X_train, y: Y_train})
cost /= nb_epochs
print cost
'''
Prediction
'''
pred = sess.run(y_model,feed_dict = {x:X_train})*255.0
print pred[:10]
output_image = []
index = 0
h = image_file.shape[0]
w = image_file.shape[1]
for i in xrange(h):
row = []
for j in xrange(w):
row.append(pred[index])
index += 1
row = np.array(row)
output_image.append(row)
output_image = np.array(output_image)
output_image = output_image.astype('uint8')
cv2.imwrite('out_mona_300x3_tf.png',output_image)
Answer: First of all, I think that instead of running the train_op and then the MSE
you can run both ops in a list and reduce your computational cost
significantly.
for i in range(nb_epochs):
cost += sess.run([MSE, train_op], feed_dict ={x: X_train, y: Y_train})
Secondly, I suggest always writing out your cost function so you can see what
is going on during the training phase. Either manually print it out or use
tensorboard to log your cost and plot it (you can find examples on the
official tf page). You can also monitor your weights to see that they aren't
blowing up.
A few things you can try: Reduce learning rate, add regularization to weights.
Check that your training set (pixels) really consist of the values that you
expect them to.
|
Python: Accessing array elements
Question: I have the following array (list?). I need to access each number of this
array. What is the syntax for this?
[[-0.04376741 0.03017034 0.0315476 ]
[ 0.01211464 0.03405497 -0.04028852]
[ 0.00958469 0.00675439 -0.02219515]
[-0.00708102 -0.00963563 -0.01555123]
[ 0.0360187 -0.02951471 -0.00613775]
[-0.00686961 -0.03182936 0.05262505]]
Answer: It is a 2 d array. You can double loop if you need to maintain the importance
of the columns and rows:
for row in theArray:
for item in row:
#do stuff with item
|
Python: weird rounding behavior of math.sqrt()
Question: Using Python 2.7.10, I have found quite by accident that 5*math.sqrt(3) and
math.sqrt(5**2*3) are not the same float:
import math
import decimal
print decimal.Decimal(5*math.sqrt(3))
print decimal.Decimal(math.sqrt(5**2*3))
print 5*math.sqrt(3) == math.sqrt(5**2*3)
returns
8.660254037844385521793810767121613025665283203125
8.6602540378443872981506501673720777034759521484375
False
which shows that they differ on the 15th decimal place. Intriguingly, this
does not happen for numbers neighboring 5 and 3. The following code show a few
pairs of numbers for which the equality fails:
for j in range(1,10+1):
for i in range(1,10+1):
a = i*math.sqrt(j)
b = math.sqrt(i**2*j)
if not(a == b):
print [i,j],
The list of problematic [i,j] pairs include: [3, 2] , [6, 2] , [9, 2] , [5, 3]
, [9, 3] , [10, 3] , [3, 6] , [6, 6] , [7, 6] , [3, 8] , [6, 8] , [9, 8] , [5,
10] , [7, 10] , [10, 10]... Any ideas on why the rounding breaks, and why
precisely for these pairs, and not others?
Answer: This is because floating point arithmetic is tricky. Neither of your results
is actually correct. They have rounding issues because of the floating point
and it looks weird because it's not rounding on powers of 10 but powers of 2.
If you need arbitrary precision arithmetic, you can use the mpmath module like
this:
from mpmath import *
mp.dps=50
mp.pretty = True
sqrt3 = fmul(5, mp.sqrt(3))
sqrt75 = mp.sqrt(fmul(power(5,2), 3))
print "5*sqrt(3) = ", sqrt3
print "sqrt(5**2*3) = ", sqrt75
That gives:
5*sqrt(3) = 8.6602540378443864676372317075293618347140262690519
sqrt(5**2*3) = 8.6602540378443864676372317075293618347140262690519
[The link provided by Rad Lexus](http://stackoverflow.com/questions/588004/is-
floating-point-math-broken) is a good read on this topic.
|
How to find point of intersection of two line segments in Python?
Question: I have data with one independent variable x and two dependent variables y1 and
y2 as shown below:
x y1 y2
-1.5 16.25 1.02
-1.25 17 1.03
-1 15 1.03
-0.75 9 1.09
-0.5 5.9 1.15
-0.25 5.2 1.17
0 4.77 1.19
+0.25 3.14 1.35
+0.5 2.5 1.54
+0.75 2.21 1.69
+1 1.91 1.96
+1.25 1.64 2.27
+1.5 1.52 2.56
+1.75 1.37 3.06
+2 1.24 4.12
+2.25 1.2 4.44
+2.5 1.18 4.95
+2.75 1.12 6.49
+3 1.07 10
So, here the value of `x where y1 = y2` is somewhere around `+1`. How do I
read the data and calculate this in python?
Answer: The naive solution goes like this:
txt = """-1.5 16.25 1.02
-1.25 17 1.03
-1 15 1.03
-0.75 9 1.09
-0.5 5.9 1.15
-0.25 5.2 1.17
0 4.77 1.19
+0.25 3.14 1.35
+0.5 2.5 1.54
+0.75 2.21 1.69
+1 1.91 1.96
+1.25 1.64 2.27
+1.5 1.52 2.56
+1.75 1.37 3.06
+2 1.24 4.12
+2.25 1.2 4.44
+2.5 1.18 4.95
+2.75 1.12 6.49
+3 1.07 10"""
import numpy as np
# StringIO behaves like a file object, use it to simulate reading from a file
from StringIO import StringIO
x,y1,y2=np.transpose(np.loadtxt(StringIO(txt)))
p1 = np.poly1d(np.polyfit(x, y1, 1))
p2 = np.poly1d(np.polyfit(x, y2, 1))
print 'equations: ',p1,p2
#y1 and y2 have to be equal for some x, that you solve for :
# a x+ b = c x + d --> (a-c) x= d- b
a,b=list(p1)
c,d=list(p2)
x=(d-b)/(a-c)
print 'solution x= ',x
output:
equations:
-3.222 x + 7.323
1.409 x + 1.686
solution x= 1.21717324767
But then you plot the 'lines':
import matplotlib.pyplot as p
%matplotlib inline
p.plot(x,y1,'.-')
p.plot(x,y2,'.-')
[](http://i.stack.imgur.com/77clE.png)
And you realize you can't use a linear assumption but for a few segments.
x,y1,y2=np.transpose(np.loadtxt(StringIO(txt)))
x,y1,y2=x[8:13],y1[8:13],y2[8:13]
p1 = np.poly1d(np.polyfit(x, y1, 1))
p2 = np.poly1d(np.polyfit(x, y2, 1))
print 'equations: ',p1,p2
a,b=list(p1)
c,d=list(p2)
x0=(d-b)/(a-c)
print 'solution x= ',x0
p.plot(x,y1,'.-')
p.plot(x,y2,'.-')
Output:
equations:
-1.012 x + 2.968
1.048 x + 0.956
solution x= 0.976699029126
[](http://i.stack.imgur.com/TBmK1.png)
Even now one could improve by leaving two more points out (looking very
linear, but that can be coincidental for a few points).
x,y1,y2=np.transpose(np.loadtxt(StringIO(txt)))
x1,x2=x[8:12],x[9:13]
y1,y2=y1[8:12],y2[9:13]
p1 = np.poly1d(np.polyfit(x1, y1, 1))
p2 = np.poly1d(np.polyfit(x2, y2, 1))
print 'equations: ',p1,p2
a,b=list(p1)
c,d=list(p2)
x0=(d-b)/(a-c)
print 'solution x= ',x0
import matplotlib.pyplot as p
%matplotlib inline
p.plot(x1,y1,'.-')
p.plot(x2,y2,'.-')
Output:
equations:
-1.152 x + 3.073
1.168 x + 0.806
solution x= 0.977155172414
[](http://i.stack.imgur.com/9ml2F.png)
Possibly better would be to use more points and apply a 2nd order
interpolation `np.poly1d(np.polyfit(x,y1,2))` and then solve the equality for
two 2nd order polynomials, which I leave as an exercise (quadratic equation)
for the reader.
|
cv2.createBackgroundSubtractorMOG2() error
Question: Could anyone help me on this one? I'm trying for a background Subtracting
method and used to perfectly run fine while using the
cv2.BackgroundSubtractorMOG() method in previous opencv versions.
import cv2
backsub = cv2.createBackgroundSubtractorMOG2()
capture = cv2.VideoCapture("headcount.avi")
i = 0
if capture:
while True:
ret, frame = capture.read()
if ret:
fgmask = backsub.apply(frame, None, 0.01)
erode=cv2.erode(fgmask,Nonei,terations=3)
moments=cv2.moments(erode,True)
But using opencv 3.1.0 i'm facing problems while using the
cv2.createBackgroundSubtractorMOG2() function and this is the error i'm
getting,while applying mask operation
Error: fgmask = backsub.apply(frame, 1, 0.01) error:
C:\builds\master_PackSlaveAddon-
win32-vc12-static\opencv\modules\python\src2\cv2.cpp:163: error: (-215) The
data should normally be NULL! in function NumpyAllocator::allocate
Answer: This is OpenCV 3.1 bug. You could disable OpenCL support as workaround.
Details is here <https://github.com/Itseez/opencv/issues/6055>
|
python - regex parsing log
Question: i have the following log line i want to parse
<log pos_start="40652288" end_position="40689664" log_type="1" length="37376" block_id="4024" block_position="18"/>
i am using python regex, this is what i did so far
regexParse = re.match(".*pos_start=(\d+).*end_position=(\d+).*log_type=(\d+).*length=(\d+).*block_id=(\d+).*block_position=(\d+).*",StatelogLine)
start_position = regexParse.group(1)
end_position = regexParse.group(2)
i am getting the following error
AttributeError: 'NoneType' object has no attribute 'group'
anyone has any ideas what is the problem
Answer: Pretty simple: your [regex does not match your
string](https://regex101.com/r/aW9aR7/1) **because of the not specified double
quotes** , that is. If you add them, [your regex
works](https://regex101.com/r/aW9aR7/2).
As a side node, the dot-star soup (`.*`) is very inefficient. Why not use a
parser instead?
Consider the following code with `BeautifulSoup`:
from bs4 import BeautifulSoup
string = """<log pos_start="40652288" end_position="40689664" log_type="1" length="37376" block_id="4024" block_position="18"/>"""
xml = BeautifulSoup(string)
print xml.log["pos_start"]
# 40652288
You can access your element like an array afterwards, no druidic regex needed.
Have a look at [their homepage and
documentation](https://www.crummy.com/software/BeautifulSoup/).
|
Execute shell command from Python Script
Question: I want to execute this command from a python script:
iw wlan0 scan | sed -e 's#(on wlan# (on wlan#g' | awk -f > scan.txt
I tried like the following
from subprocess import call
call(["iw wlan0 scan | sed -e 's#(on wlan# (on wlan#g' | awk -f > scan.txt"])
but I get an error
SyntaxError: EOL while scanning string literal
How can I do that?
Answer: Pass `shell=True` to `subprocess.call`:
call("iw wlan0 scan | sed -e 's#(on wlan# (on wlan#g' | awk -f scan.txt", shell=True)
Note that `shell=True` is not a safe option always.
|
Translations with Django 1.5.11 and Apache
Question: I am using django 1.5.11 with translations having the locale folder not in the
site directory. I used the LOCALE_PATHS variable to set the correct folder.
When I start my application using runserver, either in my machine or the
server, the translation work correctly. The problems come when I do it with
wsgi. My django app is served with apache 2.4 and mod_wsgi compiled with
python 2.7.10 with the following wsgi script:
import os
import sys
import site
site.addsitedir('/path/to/virtualenvs/site-packages')
sys.path.append('/app/folder/')
sys.path.append('/settings/folder/')
sys.path.append('/virtualenvs/site-packages')
sys.path.append('/virtualenvs/bin')
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
activate_env=os.path.expanduser("/virtualenvs/bin/activate_this.py")
execfile(activate_env, dict(__file__=activate_env))
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
when started apache the translation is not working, it looks like the
LOCALE_PATHS is ignored and look for the translation in the site folder
instead. I don't understand where this behaviour is coming from (apache
mod_wsgi maybe?). Has anyone else experienced the same?
Answer: I just stumbled upon this issue, albeit with Django 1.8.15. It seems that
you'll have to provide an absolute path for the `LOCALE_PATHS` for this to
work with Apache. Relative paths do not seem to work on the server, while they
do work locally. Not sure what causes this behavior though.
|
How to use Flask-Migrate with Google App Engine?
Question: Since I moved to Google App Engine I cannot run the Flask-Migrate command
`python manage.py db migrate` because I have exceptions regarding some GAE
related imports (`No module named google.appengine.ext` for example).
Is there a way to run this, or an alternative, to upgrade my database on GAE?
Answer: Yes, there is a way to run it, though it's not as straightforward as you'd
might like:
1. You need to [configure your Google Cloud SQL](https://cloud.google.com/sql/docs/mysql-client#configure-instance-mysql), add yourself as an authorized user (by entering your ip address) and request to have an IPv4 address. Deal with SSL as appropriate.
2. Using a script:
Replacing `user`, `password`, `instance_id`, `db_name`, and `path` below
# migrate_prod.py
DB_MIGRATION_URI = "mysql+mysqldb://user:password@instance_id/db_name?ssl_key=path/client-key.pem&ssl_cert=path/client-cert.pem&&ssl_ca=path/server-ca.pem"
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from models import * # not needed if migration file is already generated
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = DB_MIGRATION_URI
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
3. Run the script as you would to migrate locally: `python migrate_prod.py db upgrade`, assuming your migration file is already there.
4. Release the IPv4, so that you're not charged for it.
I give much credit to other answers: [how to connect via
SSL](http://%20%20http://stackoverflow.com/questions/25785252/how-to-connect-
to-mysql-server-with-ssl-from-a-flask-app) and [run alembic migrations on
GAE](http://stackoverflow.com/questions/35391120/run-alembic-migrations-on-
google-app-engine/35395267) (of which this is probably a duplicate).
|
Error fireware on centos 7
Question: I'm using the code below to open port 80 on my sever:
sudo firewall-cmd --zone=public --add-port=80/tcp --permanent
but I get this error:
Traceback (most recent call last):
File "/bin/firewall-cmd", line 24, in <module>
from gi.repository import GObject
File "/usr/lib64/python2.7/site-packages/gi/__init__.py", line 37, in <module>
from . import _gi ImportError: /lib64/libgirepository-1.0.so.1:
undefined symbol: g_type_class_adjust_private_offset
Please help me fix it. Thanks!
Answer: I had the same problem on some Centos 7, OpenVZ VMs which came without
firewalld installed. Simply installing the firewalld RPM package didn't work
because on startup, firewalld would say:
# /usr/sbin/firewalld --nofork --nopid
Traceback (most recent call last):
File "/usr/sbin/firewalld", line 132, in <module>
from firewall.server import server
File "/usr/lib/python2.7/site-packages/firewall/server/server.py", line 32, in <module>
from gi.repository import GObject, GLib
File "/usr/lib64/python2.7/site-packages/gi/__init__.py", line 37, in <module>
from . import _gi
ImportError: /lib64/libgirepository-1.0.so.1: undefined symbol: g_type_class_adjust_private_offset
After a great deal of faffing about, I've found that (as of June 2016) a
simple 'yum update' is enough to make it all work. I'm none the wiser which
packages are actually the culprit, but getting everything up to date is
probably a good thing.
|
Script returns output in IDLE not when executed at CLI
Question: I have a script that runs a few external commands and returns their values. I
am able to run the script within IDLE just fine, and I get the expected
results.
When I execute the script in a Linux shell (Bash), it runs, but with no
output.
The exit status is 0.
#!/usr/bin/python
import array,os,subprocess
def vsdIndex(vmVsd):
index = subprocess.call(["/root/indeces.sh", vmVsd], stdout=subprocess.PIPE, shell=TRUE).communicate()[0]
print index
return (firstSerial,lastSerial)
def main():
vsdArray = []
vsdProc = subprocess.Popen(["sc vsd show | tail -n +2 | grep -Ev 'iso|ISO|vfd' | awk '{{print $1}}'"], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0]
while True:
line = vsdProc.stdout.readline()
if line != '':
vsdIndex(line)
print "VSD:", line.rstrip()
print firstSerial
print lastSerial
else:
break
If I simplify it, and run without the function, I have the same behaviour:
def main():
vsdArray = []
vsdProc = subprocess.Popen(["sc vsd show | tail -n +2 | grep -Ev 'iso|ISO|vfd' | awk '{{print $1}}'"], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0]
while True:
line = vsdProc.stdout.readline()
if line != '':
print "VSD:", line.rstrip()
else:
break
Answer: You need to call your main() function. Here is a common way of doing that
automatically when you run on the command line:
if __name__ == "__main__":
main()
|
Grabbing a number from Entry and doing calculations using Tkinter
Question: I'm working on my final project for my Intro to Programming classes and I'm
having the hardest time working with Tkinter and Python.
Here is my task: Have a user enter their income from their paycheck. The
program will then do the following calculations: What is 60% of their income
for expenses, what is 10% for BOTH short-term and long-term savings and what
is 20% of their paycheck for guilt-free spending?
Once the program has completed the calculations, it will then display each of
these calculations so the user can make the appropriate transfers with their
accounts.
**Here is the code I currently have:**
from tkinter import *
from tkinter import ttk
def calculate(*args):
try:
value = float(income.get())
expenses.set(value * .60)
shortSavings.set(value * .10)
longSavings.set(value * .10)
guiltFree.set(value * .20)
except ValueError:
pass
root = Tk()
root.title("Monthly Finance Calculater")
mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)
income = StringVar()
expenses = StringVar()
shortSavings = StringVar()
longSavings = StringVar()
guiltFree = StringVar()
income_entry = ttk.Entry(mainframe, width=7, textvariable=income)
income_entry.grid(column=2, row=1, sticky=(W, E))
expenses = ttk.Entry(mainframe, width=7, textvariable=expenses)
expenses.grid(column=2, row=1, sticky=(W, E))
ttk.Label(mainframe, textvariable=income).grid(column=2, row=2, sticky=(W, E))
ttk.Button(mainframe, text="Calculate", command=calculate).grid(column=3, row=3, sticky=W)
income_entry.focus()
root.bind('<Return>', calculate)
root.mainloop()
I've been searching for days and I'm completely stuck. I don't want this done
for me, but could really use some guidance and advice on how to make this work
in a GUI using Tkinter.
Answer: One Problem was mentioned by Max already. The second problem is this one:
except ValueError:
pass
It's clear why you don't get anything if you pass an exception. Use at least a
print so you will get the errors shown in the console:
except Exception as ex:
print(ex)
The last real problem that i see is that you use the variable `expenses` two
times! First time as a `StringVar()` and the second time as a `Entry`. In the
end you don't have a StringVar because you overwrite it. Also consider to
label your entrys, because the user don't know what he is entering there yet.
Furthermore learn how to use the debugger in eclipse, it's much easier than
you think. So you can find the bugs yourself. I wish you good luck with your
project.
|
Shared pool map between processes with object-oriented python
Question: (**python2.7**)
I'm trying to do a kind of scanner, that has to walk through CFG nodes, and
split in different processes on branching for parallelism purpose.
The scanner is represented by an object of class Scanner. This class has one
method **traverse** that walks through the said graph and splits if necessary.
Here how it looks:
class Scanner(object):
def __init__(self, atrb1, ...):
self.attribute1 = atrb1
self.process_pool = Pool(processes=4)
def traverse(self, ...):
[...]
if branch:
self.process_pool.map(my_func, todo_list).
My problem is the following: How do I create a instance of
multiprocessing.Pool, that is shared between all of my processes ? I want it
to be shared, because since a path can be splitted again, I do not want to end
with a kind of fork bomb, and having the same Pool will help me to limit the
number of processes running at the same time.
The above code does not work, since Pool can not be pickled. In consequence, I
have tried that:
class Scanner(object):
def __getstate__(self):
self_dict = self.__dict__.copy()
def self_dict['process_pool']
return self_dict
[...]
But obviously, it results in having **self.process_pool** not defined in the
created processes.
Then, I tried to create a Pool as a module attribute:
process_pool = Pool(processes=4)
def my_func(x):
[...]
class Scanner(object):
def __init__(self, atrb1, ...):
self.attribute1 = atrb1
def traverse(self, ...):
[...]
if branch:
process_pool.map(my_func, todo_list)
It does not work, and this
[answer](http://stackoverflow.com/questions/2782961/yet-another-confusion-
with-multiprocessing-error-module-object-has-no-attribu) explains why. But
here comes the thing, wherever I create my Pool, something is missing. If I
create this Pool at the end of my file, it does not see self.attribute1, the
same way it did not see
[answer](http://stackoverflow.com/questions/2782961/yet-another-confusion-
with-multiprocessing-error-module-object-has-no-attribu) and fails with an
AttributeError.
I'm not even trying to share it yet, and I'm already stuck with
Multiprocessing way of doing thing.
I don't know if I have not been thinking correctly the whole thing, but I can
not believe it's so complicated to handle something as simple as "having a
worker pool and giving them tasks".
Thank you,
**EDIT** : I resolved my first problem (AttributeError), my class had a
callback as its attribute, and this callback was defined in the main script
file, after the import of the scanner module... But the concurrency and "do
not fork bomb" thing is still a problem.
Answer: What you want to do can't be done safely. Think about if you somehow had a
single shared `Pool` shared across parent and worker processes, with, say, two
worker processes. The parent runs a `map` that tries to perform two tasks, and
each task needs to `map` two more tasks. The two parent dispatched tasks go to
each worker, and the parent blocks. Each worker sends two more tasks to the
shared pool and blocks for them to complete. But now all workers are now
occupied, waiting for a worker to become free; you've deadlocked.
A safer approach would be to have the workers return enough information to
dispatch additional tasks in the parent. Then you could do something like:
class MoreWork(object):
def __init__(self, func, *args):
self.func = func
self.args = args
pool = multiprocessing.Pool()
try:
base_task = somefunc, someargs
outstanding = collections.deque([pool.apply_async(*base_task)])
while outstanding:
result = outstanding.popleft().get()
if isinstance(result, MoreWork):
outstanding.append(pool.apply_async(result.func, result.args))
else:
... do something with a "final" result, maybe breaking the loop ...
finally:
pool.terminate()
What the functions are is up to you, they'd just return information in a
`MoreWork` when there was more to do, not launch a task directly. The point is
to ensure that by having the parent be solely responsible for task dispatch,
and the workers solely responsible for task completion, you can't deadlock due
to all workers being blocked waiting for tasks that are in the queue, but not
being processed.
This is also not at all optimized; ideally, you wouldn't block waiting on the
first item in the queue if other items in the queue were complete; it's a lot
easier to do this with the `concurrent.futures` module, specifically with
[`concurrent.futures.wait`](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.wait)
to wait on the first available result from an arbitrary number of outstanding
tasks, but you'd need a third party PyPI package to get `concurrent.futures`
on Python 2.7.
|
Find Average Of a key with multiple values
Question: I have a dictionary e.g:
Jhon: 3, 4, 5
Mark: 5, 5, 5
Matthew: 7, 8 , 9
This is my code:
from statistics import mean
class1 = {}
for line in f:
columns = line.split(":")
if len(columns) == 2:
names = columns[0]
scores = columns[1].strip()
else:
pass
if class1.get(names):
class1[names].append(scores)
else:
class1[names] = list(scores)
I have already tried:
for k, v in class1.items()
print("{} : {scores}".format(names , mean(scores)
I get the error:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
And I have also tried:
for k, v in class1.items():
average = float(sum(v))/len(v)
for k, v in class1.items():
print("{} : {}".format(names=k, average=v)
The error is:
Traceback (most recent call last):
File "C:/Users/Onyeka/PycharmProjects/untitled/task3.py", line 59, in <module>
print("{} : {scores}".format(names , mean(scores)))
File "C:\Python34\lib\statistics.py", line 331, in mean
T, total, count = _sum(data)
File "C:\Python34\lib\statistics.py", line 161, in _sum
for n,d in map(_exact_ratio, values):
File "C:\Python34\lib\statistics.py", line 247, in _exact_ratio
raise TypeError(msg.format(type(x).__name__))
TypeError: can't convert type 'str' to numerator/denominator
I want the output to be like this
Jhon: 4
Mark: 3
Matthew: 8
Would it also be possible to print these averages in order from highest to
lowest?
Answer: I'm a little confused about some of what you've posted, including strange
formatting for your dictionary, but I think I understand basically what you
want. This is how I solved it:
from statistics import mean
f = {'Jhon': [3, 4, 5], 'Mark': [5, 5, 5], 'Matthew': [7, 8 , 9]}
averages = {}
for key in f:
averages[key] = int(mean(f[key]))
print(averages)
Output is:
{'Matthew': 8, 'Mark': 5, 'Jhon': 4}
|
How to properly make taggit use in wagtail
Question: Here is my code in wagtail, and I am not sure why Taggable gives me an error
when trying to add new content based on the page.
class BlogPage(Page):
body = StreamField([
('heading', blocks.CharBlock(classname="full title")),
('paragraph', blocks.RichTextBlock()),
('image', ImageChooserBlock()),
('python', TextBlock()),
])
tags = TaggableManager()
This is the error that I get.
BlogPage objects need to have a primary key value before you can access their tags.
Answer: There's a specific recipe for using tags in wagtail pages
(<http://docs.wagtail.io/en/v1.4.3/reference/pages/model_recipes.html?highlight=tags#tagging>).
I'm copying here from the wagtail docs:
from modelcluster.fields import ParentalKey
from modelcluster.contrib.taggit import ClusterTaggableManager
from taggit.models import TaggedItemBase
class BlogPageTag(TaggedItemBase):
content_object = ParentalKey('demo.BlogPage', related_name='tagged_items')
class BlogPage(Page):
...
tags = ClusterTaggableManager(through=BlogPageTag, blank=True)
promote_panels = Page.promote_panels + [
...
FieldPanel('tags'),
]
|
Python docstrings templated
Question: Why doesn't dynamically formatting docstrings work? Is there an acceptable
workaround for doing this _at function definition time_?
>>> DEFAULT_BAR = "moe's tavern"
>>> def foo(bar=DEFAULT_BAR):
... """
... hello this is the docstring
...
... Args:
... bar (str) the bar argument (default: {})
... """.format(DEFAULT_BAR)
...
>>> foo.__doc__
>>> foo.__doc__ is None
True
I tried with old-skool style %s formatting and that didn't work either.
Answer: Your string requires the function to be called, but function bodies are not
executed when a function is created.
A proper docstring is not _executed_ , it is simply taken from the parsed
sourcecode and attached to the function object, no code is ever executed for
this. Python stores the docstring as the first constant value in a code
object:
>>> def f():
... """docstring"""
... pass
...
>>> f.__code__.co_consts
('docstring', None)
where the code object was passed to the function type when constructing a new
function (see the [`PyFunction_New()`
function](https://hg.python.org/cpython/file/v2.7.11/Objects/funcobject.c#l28)).
See the [_Function definitions_ reference
documentation](https://docs.python.org/2/reference/compound_stmts.html#id3):
> The function definition does not execute the function body; this gets
> executed only when the function is called. [3]
>
> _[...]_
>
> [3] A string literal appearing as the first statement in the function body
> is transformed into the function’s `__doc__` attribute and therefore the
> function’s docstring.
Your definition is otherwise valid; there is just no stand-alone string
literal at the top of the function body. Your string literal is instead part
of the function itself, and is only executed when the function is called (and
the result discarded as you don't store that).
Note that the `__doc__` attribute on a function object is writable; you can
always apply variables _after_ creating the function:
>>> DEFAULT_BAR = "moe's tavern"
>>> def foo(bar=DEFAULT_BAR):
... """
... hello this is the docstring
...
... Args:
... bar (str) the bar argument (default: {})
... """
...
>>> foo.__doc__ = foo.__doc__.format(DEFAULT_BAR)
>>> print(foo.__doc__)
hello this is the docstring
Args:
bar (str) the bar argument (default: moe's tavern)
You could do that in a decorator with the help of `functionobject.__globals__`
and `inspect.getargspec()` perhaps, but then do use named slots in the
template so you can apply everything as a dictionary and have the docstring
choose what to interpolate:
from inspect import getargspec
def docstringtemplate(f):
"""Treat the docstring as a template, with access to globals and defaults"""
spec = getargspec(f)
defaults = {} if not spec.defaults else dict(zip(spec.args[-len(spec.defaults):], spec.defaults))
f.__doc__ = f.__doc__ and f.__doc__.format(**dict(f.__globals__, **defaults))
return f
Demo:
>>> @docstringtemplate
... def foo(bar=DEFAULT_BAR):
... """
... hello this is the docstring
...
... Args:
... bar (str) the bar argument (default: {bar!r}, or {DEFAULT_BAR!r})
...
... """
...
>>> print(foo.__doc__)
hello this is the docstring
Args:
bar (str) the bar argument (default: "moe's tavern", or "moe's tavern")
Function keyword arguments override globals, as they would in the function.
|
Python (2.7) Operation on a closed file error
Question: Another user here recently helped me refine the code below. I have the sorted
list of the integers, but I don't know how to get the original list since the
with statement closes the file it is reading from. I have already returned the
variable "List" and have a print statement for it, if I can just find a way to
produce it. I thought it would be easy enough to use the readlines fuction,
but I can't figure out how to do that. Thanks for any help! I am still new to
Python...
import random
with open("1000.txt", "w") as f:
for x in range(1000):
f.write(str(random.randint(0, 9999))+"\n")
def readList():
infile = raw_input("Input File Name: ")
rawList = list()
with open(infile, 'r') as infi:
for line in infi:
rawList.append(int(line))
sortedList = sortList(rawList) #function call for sorting the list, returned sorted list is stored
n = int(raw_input("Which number do you want to return?: "))
user_num = int(float(n-1))
return sortedList, user_num, List
def sortList(inpList): #function needs list as input and returns sorted list
inpList.sort()
return inpList
if __name__=='__main__': #This is how the main is defined in python
sortedList, List, user_num = readList() #function call of readList, returned two objects are stored in variables
first = sortedList[0]
lines = len(sortedList)
orig_min_val = min(List)
orig_max_val = max(List)
minimum_val = min(sortedList)
maximum_val = max(sortedList)
if user_num > 1000:
print user_num, "is greater than 1000!" # you don't need brackets when printing
elif user_num > lines:
print "There aren't that many numbers in the list!"
elif lines < 1000:
print "WARNING: only", lines, "numbers were read into the list!"
print "Before sort:"
print "Min is", orig_min_val
print "Max is", orig_max_val
print "After sort:"
print "Min is", minimum_val
print "Max is", maximum_val
print user_num
Answer: Spelling and ordering are VERY important in programming. You have a couple
small blunders.
First, this line:
return sortedList, user_num, List
Is returning something called `List`. However, you don't actually have a
variable called `List` anywhere in that method; what you're actually returning
is a reference to the python class `List` (Notice how the syntax highlighting
in your post colors it blue? That's why). You probably want to instead return
`rawList` like this:
return sortedList, user_num, rawList
Second, this line:
sortedList, List, user_num = readList()
Is getting the results back from that return. If you look closely, you'll see
that they're actually in the wrong order. Not only that, but you are assigning
one of the values to the python class `List`! This is very bad. I recommend
you rename your variable in the `__main__` method from `List` to `rawList`,
and make sure your variables are correctly ordered like so:
sortedList, user_num, rawList = readList()
|
Connect QPushButton Jambi
Question: I'm pretty new to Java programming. I wrote the application listed below, but
I can't connect the button to my function. Any idea what I'm doing wrong?
package com.teat;
import com.trolltech.qt.gui.*;
public class Application
{
public static void main(String[] args)
{
QApplication.initialize(args);
QWidget mainWidget = new QWidget();
mainWidget.setWindowTitle("Simple Example");
QHBoxLayout main_layout = new QHBoxLayout();
mainWidget.setLayout(main_layout);
QPushButton new_action = new QPushButton("Working");
new_action.released.connect("Tata()");
main_layout.addWidget(new_action);
SumNum(5,3);
mainWidget.show();
QApplication.execStatic();
QApplication.shutdown();
}
private static int SumNum(int num1,int num2)
{
int sum = num1 + num2;
System.out.println(sum);
return sum;
}
private static void Tata(){
System.out.println("Yes, it's Working");
}
}
When I call the function like `SumNum(5,3);` it works perfectly, but when I
call it from button, It don't work. I'm using
`new_action.released.connect("Tata()");`
I've looked into Qt, it's giving me
`void com.trolltech.qt.QSignalEmitter.AbstractSignal.connect(Object receiver,
String method)` but what is Object receiver?
I even give itself as object receiver,
`new_action.released.connect(new_action,"Tata()");` but, nope, it didn't work
either.
Any idea?
**Edit:** here the same application in python:
import sys
from PyQt4 import QtGui, QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.setWindowTitle('Simple Example')
main_layout = QtGui.QHBoxLayout()
self.setLayout(main_layout)
new_action = QtGui.QPushButton("Working")
new_action.released.connect(self.Tata)
main_layout.addWidget(new_action)
self.show()
def SumNum(self, num1, num2):
print num1+num2
return num1+num2
def Tata(self):
print "Yes, it's Working"
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
in Python it didn't ask for Object receiver, and it's just run it, but in java
it seems like completely different.
Answer: as what Smar said, it needed to run in a loop, so i extend from `QWidget`,
initial the settings in `Application()`, setup the layout in `initUI()` and
run it in `main()`.
import com.trolltech.qt.core.*;
import com.trolltech.qt.gui.*;
public class Application extends QWidget {
public Application() {
setWindowTitle("Simple Example");
setMinimumHeight(100);
setMinimumWidth(100);
setGeometry(250, 250, 350, 100);
initUI();
show();
}
private void initUI() {
QHBoxLayout main_layout = new QHBoxLayout(this);
QPushButton new_action = new QPushButton("Working");
new_action.released.connect(this,"Tata()");
main_layout.addWidget(new_action);
}
private void Tata(){
System.out.println("Yes, it's Working");
}
public static void main(String[] args) {
QApplication.initialize(args);
new Application();
QApplication.execStatic();
QApplication.shutdown();
}
}
since i extended from `QWidget`, i only need to set the layout like so
`QHBoxLayout main_layout = new QHBoxLayout(this);` Notice the **this**
as well as connecting the button `new_action.released.connect(this,"Tata()");`
Object receiver is this or in another word current `QWidget`
it's exactly same as Python, just python use `self` and Java use `this`.
that's what worked for me, hope that help however having the same problem.
|
Sympy and lambda functions
Question: I want to generate a list of basic monomial from x^0 to x^n (in particular,
n=9) using Sympy. My quick solution is a simple list comprehension combined
with Python's lambda function syntax:
import sympy as sym
x = sym.symbols('x')
monomials = [lambda x: x**n for n in range(10)]
However, when I verify that `monomials` is constructed as expected, I find
that:
print([f(x) for f in monomials])
>>> [x**9, x**9, x**9, x**9, x**9, x**9, x**9, x**9, x**9, x**9]
If I redefine `monomials` without using the lambda syntax, I get what I would
otherwise expect:
monomials = [x**n for n in range(10)]
print(monomials)
>>> [1, x, x**2, x**3, x**4, x**5, x**6, x**7, x**8, x**9]
Why do I get this behavior?
* * *
**Specs** :
* Python 3.5.1
* Sympy 1.0
I am using the Anaconda 2.5.0 (64-bit) package manager.
Answer: You need to use second arg with default value
monomials = [lambda x, n=n: x**n for n in range(10)]
otherwise you have a closure and get not value but reference to `n`.
|
How to get media_url from tweets using the Tweepy API
Question: I am using this code:
import tweepy
from tweepy.api import API
import urllib
import os
i = 1
consumer_key="xx"
consumer_secret="xx"
access_token="xx"
access_token_secret="xx"
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.secure = True
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
class MyStreamListener(tweepy.StreamListener):
def __init__(self, api=None):
self.api = api or API()
self.n = 0
self.m = 10
def on_status(self, status):
if 'media' in status.entities:
for image in status.entities['media']:
global i
#picName = status.user.screen_name
picName = "pic%s.jpg" % i
i += 1
link = image['media_url']
filename = os.path.join("C:/Users/Charbo/Documents/Python/",picName)
urllib.urlretrieve(link,filename)
#use to test
print(status.user.screen_name)
else:
print("no media_url")
self.n = self.n+1
if self.n < self.m:
return True
else:
print ('tweets = '+str(self.n))
return False
def on_error(self, status):
print (status)
myStreamListener = MyStreamListener()
myStream = tweepy.Stream(auth, MyStreamListener(),timeout=30)
myStream.filter(track=['#feelthebern'])
I am trying the access the media_url under 'photo' in my dictionary. But I am
getting the following error: 'dict' object has no attribute 'media'. I would
appreciate help navigating the JSON.
Thanks in advance!
Answer: You should try two things :
* Add entities to your request
>
tweepy.Cursor(api.search, q="#hashtag", count=5, include_entities=True)
* Check if media is not nul :
>
if 'media' in tweet.entities:
for image in tweet.entities['media']:
(do smthing with image['media_url'])
Hope this will help
|
Error handling in Django REST framework - empty file returned instead of Error view
Question: I have a piece of code in a Django REST framework that looks like the
following. It works if the request arguments are valid, but if I specify a
non-valid search keyword, the browser returns an empty python file with length
of 0 bytes instead of an HTML error code. What am I doing wrong with respect
to error catching?
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.renderers import JSONRenderer, StaticHTMLRenderer
from rest_framework.exceptions import ParseError
class GetDataseriesId(APIView):
renderer_classes = (JSONRenderer, StaticHTMLRenderer)
def get(self, request, format=None):
# check format keyword and overrule default rendering format
if 'format' in request.query_params:
request.accepted_renderer.format = request.query_params['format']
# build keyword arguments (left out for clarity)
search_dict = {'station_name':'Example'}
# render query
try:
res = DataseriesIdSerializer(**search_dict)
except Exception as e:
raise ParseError("Malformed REST service request.\nDetail: %s", e)
return Response(res.data)
The server error log reports the psycopsg2 error which I wanted to generate:
[Tue Apr 19 13:09:53 2016] [error] Error when executing query SELECT [...]
[Tue Apr 19 13:09:53 2016] [error] column s.station_itgd does not exist
This is indeed the error I wanted to generate.
The issue is that I thought my code would capture this error and then generate
a proper eror view. But this doesn't happen. I am aware that catching any
Exception is not a good practice - this is just the first step. Once I get the
response to work I will analyze which errors may occur and improve this part.
Answer: In a DRF view, you are always supposed to return a Response object. You could,
instead of raising a ParseError, ` from rest_framework import status return
Response({'detail':"Your error message"}, status=status.HTTP_400_BAD_REQUEST),
` Any uncatched exception will simply return
`Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)`
|
Appending a Numpy array to a list
Question: I am new to Python and even newer to Numpy so apologies if I've made a blunder
somewhere.
Essentially I am taking a list of angles (of indeterminate length) calculating
an array based on trig functions of those values, and then creating a new list
where at each index is a "trig array" corresponding to the index of the value
that created it in the angles list.
Currently the loop calculates the correct arrays and prints them one at a time
as expected however, the final output of the function is a single array rather
than a list of each array.
Any help would be greatly appreciated!
def tmatrices(angles):
for angle in angles:
tmatrices = []
cos = math.cos(angle)
cos2 = (math.cos(angle)) ** 2)
sin = math.sin(angle)
sin2 = (math.sin(angle)) ** 2)
T = np.array( (((cos2), (sin2), (sin*cos)), ((sin2), (cos2), ((-sin) * cos)), ((-2 * sin * cos), (2 * sin * cos), (cos2 - sin2))) )
print (T)
tmatrices.append(T)
return tmatrices
Answer: I think you have made a bit of a blunder and
tmatrices = []
should probably be outside the loop?
That said, you might prefer to use numpy more numpythonically and go for
import numpy
def tmatrix(angles):
cos = numpy.cos(angles)[numpy.newaxis, :]
cos2 = cos**2
sin = numpy.sin(angles)[numpy.newaxis, :]
sin2 = sin**2
T = numpy.concatenate( (cos2, sin2, sin*cos, sin2, cos2, -sin * cos, -2 * sin * cos, 2 * sin * cos, cos2 - sin2 ), axis=0)
return T
angles = numpy.arange(0, 2*numpy.pi, numpy.pi/10)
print tmatrix(angles)
which will return a matrix whose rows represent the different functions and
whose columns determined by the angles.
|
psycopg2 OperationalError: invalid connection option
Question: I am using
[records](https://github.com/kennethreitz/records/blob/master/records.py)
library to connect to redshift database. My db_url is something like
postgresql://xxxxx.us-east-1.redshift.amazonaws.com:5439/customer?user=xxxxx&password=xxxxx
I am using this piece of code to connect to db. On my local machine it works
perfectly fine.
import records
>>> conn_url = 'postgresql://xxxxx.us-east-1.redshift.amazonaws.com:5439/customer?user=xxxxx&password=xxxxx'
>>> db = records.Database(conn_url)
but on the server machine its giving me this error
File "<stdin>", line 1, in <module>
File "/opt/extractor/virtualenv/hge/lib/python2.7/site-packages/records.py", line 177, in __init__
self.db = psycopg2.connect(self.db_url, cursor_factory=RecordsCursor)
File "/opt/extractor/virtualenv/hge/lib/python2.7/site-packages/psycopg2/__init__.py", line 164, in connect
conn = _connect(dsn, connection_factory=connection_factory, async=async)
psycopg2.OperationalError: invalid connection option "postgresql://xxxxx.us-east-1.redshift.amazonaws.com:5439/customer?user"
Both the machines have same version of library installed
psycopg2==2.6.1
records==0.3.0
The only thing that differ is the OS. My local has Mac OX whereas the server
is on `CentOS 6.7`
I am not able to fix this error.
Answer: I have upgraded my records library to `records==0.4.3` and it worked
|
Python, selenium and catching specific text in div outside any span or something
Question: I came across a page i want to scrap a bit - and i cried a lot looking at the
structure of address details section. But let's be specific:
I have a result structure like this:
<div class="A">
<div class="B">
<div class="INFO">
Foo Bar School of Baz and Qux
<br>
<span class="TYPE">
Wibble school of Wobble
</span>
<br>
<br>
12th Hurr Durr Street, 12345 Derp
<br>
<span>Phone: 123 567 890 </span> <br>
<span>Fax: 666 69 69 69 </span>
<br>
</div>
</div>
</div>
and i want to extract the name and adress of the place using selenium in
python. So i wrote xpath which happen to work:
(//div[@class='INFO'])[1]//text()[not(parent::span) and normalize-space()]
But since things i want to extract aren't elements, just text, they are
specified with text() with "don't be inside span" and "don't be whitespace".
driver.find_element_by_xpath(thing_i_wrote_above)
throws
mon.exceptions.InvalidSelectorException: Message: The given selector <the same xpath> is: [object Text]. It should be an element.
I don't see any way to select the element, because closest one is INFO, which
happens to contain all of the informations. How to grab these things?
Answer: You could get the children text nodes with a piece of JavaScript:
# get the container
element = driver.find_element_by_css_selector(".INFO")
# return an array with the text from the children text nodes
texts = driver.execute_script("""
return Array.from(arguments[0].childNodes)
.filter(function(o){return o.nodeType === 3 && o.nodeValue.trim().length;})
.map(function(o){return o.nodeValue.trim();})
""", element)
print texts
You could also use BeautifulSoup to parse the html from the container:
from bs4 import BeautifulSoup
# get the container
element = driver.find_element_by_css_selector(".INFO")
# parse the HTML from the container
bs = BeautifulSoup(element.get_attribute("outerHTML"))
# list all the children text nodes
texts = [v.strip() for v in bs.html.body.div.findAll(text=True, recursive=False) if v.strip()]
print texts
|
How can I get an oauth2 access_token using Python
Question: For a project someone gave me this data that I have used in Postman for
testing purposes:
In Postman this works perfectly.
Auth URL: <https://api.example.com/oauth/access_token>
Access Token URL: <https://api.example.com/access_token>
client ID: abcde
client secret: 12345
Token name: access_token
Grant type: Client Credentials
All I need to get back is the access token.
One I got the access token I can continue.
I have already tried several Python packages and some custom code, but somehow
this seemingly simple task starts to create a real headache.
One exemple I tried:
import httplib
import base64
import urllib
import json
def getAuthToken():
CLIENT_ID = "abcde"
CLIENT_SECRET = "12345"
TOKEN_URL = "https://api.example.com/oauth/access_token"
conn = httplib.HTTPSConnection("api.example.com")
url = "/oauth/access_token"
params = {
"grant_type": "client_credentials"
}
client = CLIENT_ID
client_secret = CLIENT_SECRET
authString = base64.encodestring('%s:%s' % (client, client_secret)).replace('\n', '')
requestUrl = url + "?" + urllib.urlencode(params)
headersMap = {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic " + authString
}
conn.request("POST", requestUrl, headers=headersMap)
response = conn.getresponse()
if response.status == 200:
data = response.read()
result = json.loads(data)
return result["access_token"]
Then I have got this one:
import requests
import requests.auth
CLIENT_ID = "abcde"
CLIENT_SECRET = "12345"
TOKEN_URL = "https://api.example.com/oauth/access_token"
REDIRECT_URI = "https://www.getpostman.com/oauth2/callback"
def get_token(code):
client_auth = requests.auth.HTTPBasicAuth(CLIENT_ID, CLIENT_SECRET)
post_data = {"grant_type": "client_credentials",
"code": code,
"redirect_uri": REDIRECT_URI}
response = requests.post(TOKEN_URL,
auth=client_auth,
data=post_data)
token_json = response.json()
return token_json["access_token"]
If this would work, what should I put into the `code` parameter
I really hope someone can help me out here.
Thanks in advance.
Answer: I was finally able to get it done
This is the code I used:
class ExampleOAuth2Client:
def __init__(self, client_id, client_secret):
self.access_token = None
self.service = OAuth2Service(
name="foo",
client_id=client_id,
client_secret=client_secret,
access_token_url="http://api.example.com/oauth/access_token",
authorize_url="http://api.example.com/oauth/access_token",
base_url="http://api.example.com/",
)
self.get_access_token()
def get_access_token(self):
data = {'code': 'bar',
'grant_type': 'client_credentials',
'redirect_uri': 'http://example.com/'}
session = self.service.get_auth_session(data=data, decoder=json.loads)
self.access_token = session.access_token
|
Fiji (ImageJ) cannot run any script : java.lang.NoClassDefFoundError
Question: I'm trying to run some python scripts on Fiji, but it seems it cannot run a
simple code such as: `print("something")`. It always throw this
`java.lang.NoClassDefFoundError`, and a weirder thing is that the error always
points at some random line (even if the line contains no contents, it always
picks a random number each time I start fiji and keeps pointing at that line).
I'm running this on my machine: Ubuntu 15.10 64 bit and my Java and fiji are
all up to date.
Here is the detailed error script:
Started gamepad_socket.py at Tue Apr 19 15:03:16 CEST 2016
[WARNING] Auto-imports are active, but deprecated.
Traceback (most recent call last):
File "/home/peterpark/cti/Tutorials/gamepad_socket.py", line 33, in <module>
java.lang.NoClassDefFoundError: javax/vecmath/Point3f
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.privateGetPublicMethods(Class.java:2902)
at java.lang.Class.getMethods(Class.java:1615)
at org.python.core.PyJavaType.init(PyJavaType.java:273)
at org.python.core.PyType.createType(PyType.java:1264)
at org.python.core.PyType.addFromClass(PyType.java:1201)
at org.python.core.PyType.fromClass(PyType.java:1291)
at org.python.core.adapter.ClassicPyObjectAdapter$6.adapt(ClassicPyObjectAdapter.java:76)
at org.python.core.adapter.ExtensiblePyObjectAdapter.adapt(ExtensiblePyObjectAdapter.java:44)
at org.python.core.adapter.ClassicPyObjectAdapter.adapt(ClassicPyObjectAdapter.java:120)
at org.python.core.Py.java2py(Py.java:1563)
at org.python.core.PyJavaPackage.addClass(PyJavaPackage.java:89)
at org.python.core.PyJavaPackage.__findattr_ex__(PyJavaPackage.java:138)
at org.python.core.PyObject.__findattr__(PyObject.java:863)
at org.python.core.imp.importFromAs(imp.java:1015)
at org.python.core.imp.importFrom(imp.java:987)
at org.python.pycode._pyx1.f$0(/home/peterpark/cti/Tutorials/gamepad_socket.py:124)
at org.python.pycode._pyx1.call_function(/home/peterpark/cti/Tutorials/gamepad_socket.py)
at org.python.core.PyTableCode.call(PyTableCode.java:165)
at org.python.core.PyCode.call(PyCode.java:18)
at org.python.core.Py.runCode(Py.java:1275)
at org.scijava.plugins.scripting.jython.JythonScriptEngine.eval(JythonScriptEngine.java:76)
at org.scijava.script.ScriptModule.run(ScriptModule.java:174)
at org.scijava.module.ModuleRunner.run(ModuleRunner.java:167)
at org.scijava.module.ModuleRunner.call(ModuleRunner.java:126)
at org.scijava.module.ModuleRunner.call(ModuleRunner.java:65)
at org.scijava.thread.DefaultThreadService$2.call(DefaultThreadService.java:191)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: javax.vecmath.Point3f
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 32 more
Thanks for your help in advance.
Answer: This seems to be a [bug](https://github.com/scijava/scijava-ui-
swing/issues/20) in the deprecated auto-import functionality of the script
editor.
Try **disabling auto-imports** via _Edit > Auto-import (deprecated)_ in the
menu of the script editor.
|
Draggable Matplotlib Subplot using wxPython
Question: I'm attempting to expand on a draggable plot tutorial by creating a subplot
that can be dragged (the matplotlib curve, not the whole window). I feel like
I'm close but just missing a critical detail.
Most of the code is just creating cookie cutter subplots, figure 3 is the only
one where I'm trying to drag the plot data.
Any help would be appreciated!
import wxversion
wxversion.ensureMinimal('2.8')
import numpy as np
import matplotlib
matplotlib.interactive(True)
matplotlib.use('WXAgg')
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.figure import Figure
import wx
class DraggableCurve:
def __init__(self,curve):
self.curve = curve[0]
self.press = None
def connect(self):
'connect to all the events we need'
self.cidpress = self.curve.figure.canvas.mpl_connect(
'button_press_event', self.on_press)
self.cidrelease = self.curve.figure.canvas.mpl_connect(
'button_release_event', self.on_release)
self.cidmotion = self.curve.figure.canvas.mpl_connect(
'motion_notify_event', self.on_motion)
def on_press(self, event):
print "on_press"
'on button press we will see if the mouse is over us and store some data'
if event.inaxes != self.curve.axes: return
contains, attrd = self.curve.contains(event)
if not contains: return
print 'event contains', self.curve.xy
x0, y0 = self.curve.xy
# print x0,y0
self.press = x0, y0, event.xdata, event.ydata
def on_motion(self, event):
print "on_motion"
'on motion we will move the curve if the mouse is over us'
if self.press is None: return
if event.inaxes != self.curve.axes: return
x0, y0, xpress, ypress = self.press
print xpress, ypress
dx = event.xdata - xpress
dy = event.ydata - ypress
#print 'x0=%f, xpress=%f, event.xdata=%f, dx=%f, x0+dx=%f'%(x0, xpress, event.xdata, dx, x0+dx)
self.curve.set_x(x0+dx)
self.curve.set_y(y0+dy)
# print x0+dx, y0+dy
#self.curve.figure.canvas.draw()
self.curve.figure.canvas.draw_idle()
def on_release(self, event):
print "on_release"
'on release we reset the press data'
self.press = None
#self.curve.figure.canvas.draw()
self.curve.figure.canvas.draw_idle()
def disconnect(self):
'disconnect all the stored connection ids'
self.curve.figure.canvas.mpl_disconnect(self.cidpress)
self.curve.figure.canvas.mpl_disconnect(self.cidrelease)
self.curve.figure.canvas.mpl_disconnect(self.cidmotion)
class CanvasFrame(wx.Frame):
def __init__(self):
#create frame
frame = wx.Frame.__init__(self,None,-1,
'Test',size=(550,350))
#set background
self.SetBackgroundColour(wx.NamedColour("WHITE"))
#initialize figures
self.figure1 = Figure()
self.figure2 = Figure()
self.figure3 = Figure()
self.figure4 = Figure()
#initialize figure1
self.axes1 = self.figure1.add_subplot(111)
self.axes1.text(0.5,0.5, 'Test 1', horizontalalignment='center', fontsize=15)
self.axes1.get_xaxis().set_visible(False)
self.axes1.get_yaxis().set_visible(False)
self.canvas1 = FigureCanvas(self, -1, self.figure1)
#initialize figure2
self.axes2 = self.figure2.add_subplot(111)
self.axes2.text(0.5,0.5, 'Test 2', horizontalalignment='center', fontsize=15)
self.axes2.get_xaxis().set_visible(False)
self.axes2.get_yaxis().set_visible(False)
self.canvas2 = FigureCanvas(self, -1, self.figure2)
#initialize figure3
self.axes3 = self.figure3.add_subplot(111)
curve = self.axes3.plot(np.arange(1,11),10*np.random.rand(10),color='r',marker='o')
self.canvas3 = FigureCanvas(self, -1, self.figure3)
# self.axes3.get_xaxis().set_visible(True)
# self.axes3.get_yaxis().set_visible(True)
# self.canvas3.draw()
# self.canvas3.draw_idle()
dc = DraggableCurve(curve)
dc.connect()
#initialize figure4
self.axes4 = self.figure4.add_subplot(111)
self.axes4.text(0.5,0.5, 'Test4', horizontalalignment='center', fontsize=15)
self.axes4.get_xaxis().set_visible(False)
self.axes4.get_yaxis().set_visible(False)
self.canvas4 = FigureCanvas(self, -1, self.figure4)
#create figures into the 2x2 grid
self.sizer = wx.GridSizer(rows=2, cols=2, hgap=5, vgap=5)
self.sizer.Add(self.canvas1, 1, wx.EXPAND)
self.sizer.Add(self.canvas2, 1, wx.EXPAND)
self.sizer.Add(self.canvas3, 1, wx.EXPAND)
self.sizer.Add(self.canvas4, 1, wx.EXPAND)
self.SetSizer(self.sizer)
self.Fit()
return
class App(wx.App):
def OnInit(self):
'Create the main window and insert the custom frame'
frame = CanvasFrame()
frame.Show(True)
return True
app = App(0)
app.MainLoop()
[](http://i.stack.imgur.com/DYTJD.png)
Answer: Check this example:
# -*- coding: utf-8 -*-
import wxversion
wxversion.ensureMinimal('2.8')
import wx
import numpy as np
import matplotlib
matplotlib.use('WXAgg')
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg
from matplotlib.figure import Figure
class FigureCanvas(FigureCanvasWxAgg):
def __init__(self,parent,id,figure,**kwargs):
FigureCanvasWxAgg.__init__(self,parent=parent, id=id, figure=figure,**kwargs)
self.figure = figure
self.axes = self.figure.get_axes()[0] # Get axes
self.connect() # Connect event
def connect(self):
"""Connect pick event"""
self.MOVE_LINE_EVT = self.mpl_connect("pick_event", self.on_pick)
def on_pick(self,event):
self._selected_line = event.artist # Get selected line
# Get initial x,y data
self._p0 = (event.mouseevent.xdata, event.mouseevent.ydata)
self._xdata0 = self._selected_line.get_xdata()
self._ydata0 = self._selected_line.get_ydata()
# Connect events for motion and release.
self._on_motion = self.mpl_connect("motion_notify_event", self.on_motion)
self._on_release = self.mpl_connect("button_release_event", self.on_release)
def on_motion(self,event):
cx = event.xdata # Current xdata
cy = event.ydata # Current ydata
deltax = cx - self._p0[0]
deltay = cy - self._p0[1]
self._selected_line.set_xdata(self._xdata0 + deltax)
self._selected_line.set_ydata(self._ydata0 + deltay)
self.draw()
def on_release(self,event):
"""On release, disconnect motion and release"""
self.mpl_disconnect(self._on_motion)
self.mpl_disconnect(self._on_release)
self.axes.relim()
self.axes.autoscale_view(True,True,True)
self.draw()
class Frame(wx.Frame):
def __init__(self,parent,title):
wx.Frame.__init__(self,parent,title=title,size=(800,600))
self.initCtrls()
self.plotting()
self.Centre(True)
self.Show()
def initCtrls(self):
self.mainsizer = wx.GridSizer(rows=2, cols=2, hgap=2, vgap=2)
# 1
self.figure = Figure()
self.axes = self.figure.add_subplot(111)
self.canvas = FigureCanvas(self, wx.ID_ANY, self.figure)
# 2
self.figure2 = Figure()
self.axes2 = self.figure2.add_subplot(111)
self.canvas2 = FigureCanvas(self, wx.ID_ANY, self.figure2)
self.figure3 = Figure()
self.axes3 = self.figure3.add_subplot(111)
self.canvas3 = FigureCanvas(self, wx.ID_ANY, self.figure3)
self.figure4 = Figure()
self.axes4 = self.figure4.add_subplot(111)
self.canvas4 = FigureCanvas(self, wx.ID_ANY, self.figure4)
self.mainsizer.Add(self.canvas, 1, wx.EXPAND)
self.mainsizer.Add(self.canvas2, 1, wx.EXPAND)
self.mainsizer.Add(self.canvas3, 1, wx.EXPAND)
self.mainsizer.Add(self.canvas4, 1, wx.EXPAND)
self.SetSizer(self.mainsizer)
def plotting(self):
# Set picker property -> true
self.axes2.plot(np.arange(1,11),10*np.random.rand(10),color='b',
marker='o', picker=True)
self.axes3.plot(np.arange(1,11),10*np.random.rand(10),color='r',
marker='o', picker=True)
self.canvas.draw()
if __name__=='__main__':
app = wx.App()
frame = Frame(None, "Matplotlib Demo")
frame.Show()
app.MainLoop()
Basically the idea is to define a custom FigureCanvas, which supports the
selection and movement of the lines using the pick event.
Obviously this code still needs a lot of review, to work properly.
|
python How can I parse html and print specific output inside html tag
Question:
#!/usr/bin/env python
import requests, bs4
res = requests.get('https://betaunityapi.webrootcloudav.com/Docs/APIDoc/APIReference')
web_page = bs4.BeautifulSoup(res.text, "lxml")
for d in web_page.findAll("div",{"class":"actionColumnText"}):
print d
Result:
<div class="actionColumnText">
<a href="/Docs/APIDoc/Api/POST-api-console-gsm-gsmKey-sites-siteId-endpoints-reactivate">/service/api/console/gsm/{gsmKey}/sites/{siteId}/endpoints/reactivate</a>
</div>
<div class="actionColumnText">
Reactivates a list of endpoints, or all endpoints on a site. </div>
I am interested to see output with only the last line (_Reactivates a list of
endpoints, or all endpoints on a site_) removing start and end . Not
interested in the line with _href_
Any help is greatly appreciated.
Answer: In a simple case, you can just [get the
text](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#get-text):
for d in web_page.find_all("div", {"class": "actionColumnText"}):
print(d.get_text())
Or/and, if there is only single element you want to find, you can get the last
match by index:
d = web_page.find_all("div", {"class": "actionColumnText"})[-1]
print(d.get_text())
Or, you can also find `div` elements with a specific class which don't have an
`a` child element:
def filter_divs(elm):
return elm and elm.name == "div" and "actionColumnText" in elm.attrs and elm.a is None
for d in web_page.find_all(fitler_divs):
print(d.get_text())
Or, in case of a single element:
web_page.find(fitler_divs).get_text()
|
Retrieve a single item from DynamoDB using Python
Question: I want to retrieve single item from DynamoDB but I'm unable to do that. I
think I am missing something. I am able to scan the table using scan()
function of boto but the fetching of a single item is not working. So it would
be great if someone can tell me the correct way to do this.
**models.py** file:
import os
import boto
from boto import dynamodb2
from boto.dynamodb2.table import Table
from boto.dynamodb2.fields import HashKey, RangeKey, KeysOnlyIndex, GlobalAllIndex
AWS_ACCESS_KEY_ID = '****************'
AWS_SECRET_ACCESS_KEY = '***************************'
REGION = 'us-east-1'
TABLE_NAME = 'Users'
conn = dynamodb2.connect_to_region(REGION, aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
table = Table(
TABLE_NAME,
connection=conn
)
results = table.scan()
for dynamo_item in results:
print dict(dynamo_item.items())
I've tried using following:
results = table.scan(scan_filter={'email':'new'})
but got this error
> boto.dynamodb2.exceptions.UnknownFilterTypeError: Operator 'scan_filter'
> from 'scan_filter' is not recognized.
results = table.query_2(email = 'new')
> boto.dynamodb2.exceptions.UnknownFilterTypeError: Operator 'email' from
> 'email' is not recognized.
results = table.get_item(email='new')
> boto.dynamodb2.exceptions.ValidationException: ValidationException: 400 Bad
> Request {u'message': u'The provided key element does not match the schema',
> u'__type': u'com.amazon.coral.validate#ValidationException'}
Answer: if table hash key is email then
`results = table.get_item(email='new')` should works.
check if email is in type STRING (and not NUMBER) in table scheme.
|
Python on Apache: Internal Server Error
Question: I'm getting `Internal Server Error` from my Python script on Apache.
The script has `chmod 755` and is in a directory different from `cgi-bin`.
Its content is
#!/usr/bin/python
print "Content-Type: text/html\n"
print "test"
I'm on shared hosting with limited options. In particular I cannot view the
Apache logfile.
Answer: Apache tries to execute the script, but fails to do so because it is missing
`Options +ExecCGI` in the `.htaccess` located in the script's directory.
It is important to begin the script with the two lines
#!/usr/bin/python
print "Content-Type: text/html\n"
Without those, or without a trailing `\n`, Apache would throw an `Internal
Server Error`, too.
|
Sending corrupted csv line over the socket in Python 3
Question: I build a sensor unit where data are gathered at one Raspberry Pi and send to
another's over the network. My first Pi creates a line with multiple readings
from different sensors. It supposed to create a server and send it to clients.
The client Pis needs to receive the sentence, do further processing or
visualisation.
To test my solutions I want to read data from a txt file, which was build in
an experiment. The problem is that sometimes data are corrupted, has different
format depending on sensor and rows can be different for different set-ups.
I have build a function which suppose to change the input line to bytes. (I
tried different methods but only this clunky function is the closest to any
results). But it does not convert over the network
import struct
message = ['First sensor', 'second data', 'third',1, '19.04.2016', 0.1]
def packerForNet(message):
pattern = ''
newMessage = []
for cell in message:
if isinstance( cell, int ):
pattern += ('I')
newMessage.append(cell)
elif isinstance( cell, float ):
pattern += ('d')
newMessage.append(cell)
elif isinstance(cell, str):
pattern += (str(len(cell)))
pattern += ('s')
newMessage.append(cell.encode('UTF-8'))
else:
cell = str(cell)
pattern += (len(cell))
pattern += ('s')
newMessage.append(cell.encode('UTF-8'))
return (newMessage, pattern)
newMessage, pattern = packerForNet(message)
patternStruct = struct.Struct(pattern)
packedM = patternStruct.pack(*newMessage)
The output from the function does not unpack correctly:
packedM = b'First sensorsecond datathird\x01\x00\x00\x0019.04.2016\x00\x00\x00\x00\x00\x00\x9a\x99\x99\x99\x99\x99\xb9?'
56
print('unpacked = %s' % patternStruct.unpack(packedM))
TypeError: not all arguments converted during string formatting
In addition I need to know the `pattern` to unpack it on the client side so in
general it doesn't have sense.
In final version the server needs to work in the way that after client
connects it will send to the client line from the sensors every millisecond.
Sensors parsing is implemented in C and at the moment it creates a txt file
for off-line processing. I can't change the way the sensor's line are made.
I don't know how to pack the list of different types and constantly send such
lists to the client.
Answer: Actually it does unpack correctly. The problem is not with the unpacking, but
with the print.
Try:
unpackedM = patternStruct.unpack(packedM)
print(unpackedM)
unpackedM is a tuple of multiple values. The formatting of the string with the
tuple failed.
EDIT: To convert entire objects you can use python
[msgpack](https://pypi.python.org/pypi/msgpack-python). That is what we use in
communication python to python and php to python.
|
Python - Import CSV file and save it into Database SQLAlchemy
Question: i have a prblem with importing CSV-file into Database... Im using SQLAlchemy
in Python and wanted to open a CSV-File than show it in QTableWidget to maybe
change the values and after write it to DB (New Table).
def setinTable(self):
colcnt = len(self.title)
rowcnt = len(self.data)
self.tabel_model = QtGui.QTableWidget(rowcnt, colcnt)
vheader = QtGui.QHeaderView(QtCore.Qt.Orientation.Vertical)
self.tabel_model.setVerticalHeader(vheader)
hheader = QtGui.QHeaderView(QtCore.Qt.Orientation.Horizontal)
self.tabel_model.setHorizontalHeader(hheader)
self.tabel_model.setHorizontalHeaderLabels(self.title)
for i in range(rowcnt):
for j in range(len(self.data[0])):
item = QtGui.QTableWidgetItem(str(self.data[i][j]))
self.tabel_model.setItem(i, j, item)
self.tabel_model.horizontalHeader().sectionDoubleClicked.connect(self.changeHorizontalHeader)
self.setCentralWidget(self.tabel_model)
# Get CSV-Data
def getdata(filepath):
with open(filepath, 'r') as csvfile:
sample = csvfile.read(1024)
dialect = csv.Sniffer().sniff(sample, [';',',','|'])
csvfile.seek(0)
reader = csv.reader(csvfile,dialect=dialect)
header = next(reader)
lines = []
for line in reader:
lines.append(line)
return lines
Reading and showing the CSV-File data in a QTableWidget is working .. but i
dont know how to save it to a MySQL Database
Answer: For an easier way to load a csv into a database table, check out the 'odo'
python project - <https://pypi.python.org/pypi/odo/0.3.2>
\--
To use a table via SQL Alchemy one approach is to use a
[session](http://docs.sqlalchemy.org/en/latest/orm/session_basics.html) and
call "update":
myRow = myTable(
column_a = 'foo',
column_b = 'bar')
myRow.column_c = 1 + 2
mySession.update(myRow)
|
How to automatically load data from json file on startup with kivy
Question: I am making an android app with python and kivy that keeps track of diabetes
entries and has a basic profile page. I figured out how to save input from
textinput widgets into a json file which works fine. However I cannot figure
out how to automatically load this information back into the textinput widets
on the startup. Loading into the labels could work too but it would be
sloppier. I know there is an on_start module, but I have no idea how to use
it. Any suggestions would be greatly appreciated.
.kv file
<Phone>:
result: _result
h: _h
w: _w
n: name_input
g: gender_input
t: _type
ti: _times
m: _meds
AnchorLayout:
anchor_x: 'center'
anchor_y: 'top'
ScreenManager:
size_hint: 1, .9
id: _screen_manager
Screen:
name: 'home'
canvas.before:
Rectangle:
pos: self.pos
size: self.size
source: "/home/aaron/Desktop/main.png"
Label:
markup: True
text: '[size=100][color=ff3333]Welcome to [color=ff3333]Diabetes Manager[/color][/size]'
Screen:
name: 'menu'
GridLayout:
cols: 2
padding: 50
canvas.before:
Rectangle:
pos: self.pos
size: self.size
source: "/home/aaron/Desktop/main.png"
Button:
text: 'My Profile'
on_press: _screen_manager.current = 'profile'
Button:
text: 'History'
on_press: _screen_manager.current = 'history'
Button:
text: 'New Entry'
on_press: _screen_manager.current = 'new_entry'
Button:
text: 'Graph'
on_press: _screen_manager.current = 'graph'
Button:
text: 'Diet'
on_press: _screen_manager.current = 'diet'
Button:
text: 'Settings'
on_press: _screen_manager.current = 'settings'
Screen:
name: 'profile'
GridLayout:
cols: 1
BoxLayout:
Label:
size_hint_x: 0.22
bold: True
markup: True
text: '[size=40][color=0000ff]Name[/color][/size]'
TextInput:
id: name_input
hint_text: 'Name'
Button:
size_hint_x: 0.15
text: 'Load'
on_press: root.load()
BoxLayout:
Label:
size_hint_x: 0.22
bold: True
markup: True
text: '[size=40][color=0000ff]Gender[/color][/size]'
TextInput:
id: gender_input
hint_text: 'Gender'
BoxLayout:
Label:
size_hint_x: 0.22
bold: True
markup: True
text: '[size=34][color=0000ff]Type of Diabetes[/color][/size]'
TextInput:
id: _type
hint_text: 'Type of Diabetes'
BoxLayout:
Label:
size_hint_x: 0.22
bold: True
markup: True
text: '[size=40][color=0000ff]Height (in)[/color][/size]'
TextInput:
id: _h
hint_text: 'Height in inches'
BoxLayout:
Label:
size_hint_x: 0.22
bold: True
markup: True
text: '[size=40][color=0000ff]Weight (lb)[/color][/size]'
TextInput:
id: _w
hint_text: 'Weight in pounds'
BoxLayout:
Button:
text: 'Calculate BMI'
on_press: root.product(*args)
Label:
size_hint_x: 4.5
id:_result
bold: True
markup: True
text: '[size=40][color=0000ff]BMI[/color][/size]'
BoxLayout:
Label:
size_hint_x: 0.22
bold: True
markup: True
text: '[size=30][color=0000ff]List of Medications[/color][/size]'
TextInput:
id: _meds
hint_text: 'List of Medications'
BoxLayout:
Label:
size_hint_x: 0.22
bold: True
markup: True
text: '[size=38][color=0000ff]Insulin Times[/color][/size]'
TextInput:
id: _times
hint_text: 'Please Enter Times to Take Insulin'
Button:
size_hint_x: 0.15
text: 'Done'
on_press: root.save()
Screen:
name: 'history'
GridLayout:
cols:1
Screen:
name: 'new_entry'
GridLayout:
cols:1
BoxLayout:
Label:
size_hint_x: 0.22
bold: True
markup: True
text: '[size=40][color=0000ff]Time[/color][/size]'
TextInput:
id: _time
hint_text: 'Current Time'
BoxLayout:
Label:
size_hint_x: 0.22
bold: True
markup: True
text: '[size=28][color=0000ff]Blood Sugar (mg/dL)[/color][/size]'
TextInput:
id: _glucose_reading
hint_text: 'Current Blood Sugar'
BoxLayout:
Label:
size_hint_x: 0.22
bold: True
markup: True
text: '[size=40][color=0000ff]Carbs[/color][/size]'
TextInput:
id: _food
hint_text: 'Total Carbs for meal'
BoxLayout:
Label:
size_hint_x: 0.22
bold: True
markup: True
text: '[size=30][color=0000ff]Medications Taken[/color][/size]'
TextInput:
id: _meds_taken
hint_text: 'Please Enter Any Medications Taken'
Screen:
name: 'graph'
GridLayout:
cols: 3
padding: 50
Label:
markup: True
text: '[size=24][color=dd88ff]Your Graph[/color][/size]'
Screen:
name: 'diet'
GridLayout:
cols: 3
padding: 50
Label:
markup: True
text: '[size=24][color=dd88ff]Reccomended Diet[/color][/size]'
Screen:
name: 'settings'
GridLayout:
cols: 3
padding: 50
Label:
markup: True
text: '[size=24][color=dd88ff]Settings[/color][/size]'
AnchorLayout:
anchor_x: 'center'
anchor_y: 'bottom'
BoxLayout:
orientation: 'horizontal'
size_hint: 1, .1
Button:
id: btnExit
text: 'Exit'
on_press: app.save(_name.text, gender.txt)
Button:
text: 'Menu'
on_press: _screen_manager.current = 'menu'
.py
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.popup import Popup
from kivy.uix.button import Button
from kivy.graphics import Color, Rectangle
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.image import AsyncImage
from kivy.uix.label import Label
from kivy.properties import StringProperty, ListProperty
from kivy.uix.behaviors import ButtonBehavior
from kivy.uix.textinput import TextInput
from kivy.network.urlrequest import UrlRequest
from kivy.storage.jsonstore import JsonStore
from os.path import join
from os.path import exists
from kivy.compat import iteritems
from kivy.storage import AbstractStore
from json import loads, dump
from kivy.config import Config
class Phone(FloatLayout):
def __init__(self, **kwargs):
# make sure we aren't overriding any important functionality
super(Phone, self).__init__(**kwargs)
with self.canvas.before:
Color(0, 1, 0, 1) # green; colors range from 0-1 instead of 0-255
self.rect = Rectangle(size=self.size, pos=self.pos)
self.bind(size=self._update_rect, pos=self._update_rect)
def _update_rect(self, instance, value):
self.rect.pos = instance.pos
self.rect.size = instance.size
def product(self, instance):
self.result.text = str(float(self.w.text) * 703/ (float(self.h.text) * float(self.h.text)))
def save(self):
store = JsonStore('hello.json')
name = self.n.text
gender = self.g.text
dtype = self.t.text
height = self.h.text
weight = self.w.text
medications = self.m.text
store.put('profile', name=name, gender=gender, dtpe=dtype, height=height, weight=weight, medications=medications)
presentation = Builder.load_file("main.kv")
class PhoneApp(App):
def build(self):
store = JsonStore('hello.json')
return Phone()
if __name__ == '__main__':
PhoneApp().run()
Answer: You can just do the reverse of what you're already doing in `save()`. For
example:
def load(self):
store = JsonStore('hello.json')
profile = store.get('profile')
self.n.text = profile['name']
self.g.text = profile['gender']
...
Then just call that method somewhere, like in `__init__()`.
|
Analysing URL's using Google Cloud Vision - Python
Question: Is there anyway I can analyse URL's using Google Cloud Vision. I know how to
analyse images that I store locally, but I can't seem to analyse jpg's that
exist on the internet:
import argparse
import base64
import httplib2
from googleapiclient.discovery import build
import collections
import time
import datetime
import pyodbc
time_start = datetime.datetime.now()
def main(photo_file):
'''Run a label request on a single image'''
API_DISCOVERY_FILE = 'https://vision.googleapis.com/$discovery/rest?version=v1'
http = httplib2.Http()
service = build('vision', 'v1', http, discoveryServiceUrl=API_DISCOVERY_FILE, developerKey=INSERT API KEY HERE)
with open(photo_file, 'rb') as image:
image_content = base64.b64encode(image.read())
service_request = service.images().annotate(
body={
'requests': [{
'image': {
'content': image_content
},
'features': [{
'type': 'LOGO_DETECTION',
'maxResults': 10,
}]
}]
})
response = service_request.execute()
try:
logo_description = response['responses'][0]['logoAnnotations'][0]['description']
logo_description_score = response['responses'][0]['logoAnnotations'][0]['score']
print logo_description
print logo_description_score
except KeyError:
print "logo nonexistent"
pass
print time_start
if __name__ == '__main__':
main("C:\Users\KVadher\Desktop\image_file1.jpg")
Is there anyway I can analyse a URL and get an answer as to whether there are
any logo's in them?
Answer: I figured out how to do it. Re-wrote my code and added used urllib to open the
image and then I passed it through base64 and the google cloud vision logo
recognition api:
import argparse
import base64
import httplib2
from googleapiclient.discovery import build
import collections
import time
import datetime
import pyodbc
import urllib
import urllib2
time_start = datetime.datetime.now()
#API AND DEVELOPER KEY DETAILS
API_DISCOVERY_FILE = 'https://vision.googleapis.com/$discovery/rest?version=v1'
http = httplib2.Http()
service = build('vision', 'v1', http, discoveryServiceUrl=API_DISCOVERY_FILE, developerKey=INSERT DEVELOPER KEY HERE)
url = "http://www.lcbo.com/content/dam/lcbo/products/218040.jpg/jcr:content/renditions/cq5dam.web.1280.1280.jpeg"
opener = urllib.urlopen(url)
#with open(photo_file) as image:
image_content = base64.b64encode(opener.read())
service_request = service.images().annotate(
body={
'requests': [{
'image': {
'content': image_content
},
'features': [{
'type': 'LOGO_DETECTION',
'maxResults': 10,
}]
}]
})
response = service_request.execute()
try:
logo_description = response['responses'][0]['logoAnnotations'][0]['description']
logo_description_score = response['responses'][0]['logoAnnotations'][0]['score']
print logo_description
print logo_description_score
except KeyError:
print "logo nonexistent"
pass
print time_start
|
Python worker crashes when loading CSV file with many columns
Question: I'm trying to load
[this](https://www.dropbox.com/s/ltwg63jpm55845m/pivot.csv?dl=0) CSV file with
many columns and calculate the correlation between columns using Spark.
from pyspark import SparkContext, SparkConf
from pyspark.mllib.stat import Statistics
conf = SparkConf()\
.setAppName("Movie recommender")\
.setMaster("local[*]")\
.set("spark.driver.memory", "10g")\
.set("spark.driver.maxResultSize", "4g")
sc = SparkContext(conf=conf)
pivot = sc.textFile(r"pivot.csv")
header = pivot.first()
pivot = pivot.filter(lambda x:x != header)
pivot = pivot.map(lambda x:x.split()).cache()
corrs = Statistics.corr(pivot)
I get this error:
Py4JJavaError: An error occurred while calling z:org.apache.spark.api.python.PythonRDD.runJob.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 0.0 failed 1 times, most recent failure: Lost task 0.0 in stage 0.0 (TID 0, localhost): java.net.SocketException: Connection reset by peer: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(Unknown Source)
at java.net.SocketOutputStream.write(Unknown Source)
Answer: I managed to run this with increased partitions. But the performance is really
slow on my local machine that it's not actually working. Performance issue
seems to be expected when the number of columns are high.
def extract_sparse(str_lst, N):
if len(str_lst) == 0:
return (0, {})
else:
keyvalue = {}
length = len(str_lst)
if length > N:
length = N
for i in range(length):
if str_lst[i] != '': # not missing
keyvalue[i] = float(str_lst[i])
return (length, keyvalue)
pivot = sc.textFile(r"pivot.csv", 24)
header = pivot.first()
pivot = pivot.filter(lambda x:x != header)
pivot = pivot.map(lambda x:x.split(','))
pivot = pivot.map(lambda x: extract_sparse(x, 50000))
pivot = pivot.map(lambda x: Vectors.sparse(x[0], x[1]))
pivot = pivot.map(lambda x: x.toArray()).collect()
corrs = Statistics.corr(pivot)
|
unregistered task type import errors in celery
Question: I'm having headaches with getting celery to work with my folder structure.
Note I am using virtualenv but it should not matter.
cive /
celery_app.py
__init__.py
venv
framework /
tasks.py
__init__.py
civeAPI /
files tasks.py need
cive is my root project folder.
celery_app.py:
from __future__ import absolute_import
from celery import Celery
app = Celery('cive',
broker='amqp://',
backend='amqp://',
include=['cive.framework.tasks'])
# Optional configuration, see the application user guide.
app.conf.update(
CELERY_TASK_RESULT_EXPIRES=3600,
)
if __name__ == '__main__':
app.start()
tasks.py (simplified)
from __future__ import absolute_import
#import other things
#append syspaths
from cive.celery_app import app
@app.task(ignore_result=False)
def start(X):
# do things
def output(X):
# output files
def main():
for d in Ds:
m = []
m.append( start.delay(X) )
output( [n.get() for n in m] )
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
I then start workers via (outside root cive dir)
celery -A cive worker --app=cive.celery_app:app -l info
which seems to work fine, loading the workers and showing
[tasks]
. cive.framework.tasks.start_sessions
But when I try to run my tasks.py via another terminal:
python tasks.py
I get the error:
Traceback (most recent call last):
File "tasks.py", line 29, in <module>
from cive.celery_app import app
ImportError: No module named cive.celery_app
If I rename the import to:
from celery_app import app #without the cive.celery_app
I can eventually start the script but celery returns error:
Received unregistered task of type 'cive.start_sessions'
I think there's something wrong with my imports or config but I can't say
what.
Answer: So this was a python package problem, not particularly a celery issue. I found
the solution by looking at [Attempted relative import in non-package even with
__init__.py](http://stackoverflow.com/questions/11536764/attempted-relative-
import-in-non-package-even-with-init-py) .
I've never even thought about this before, but I wasn't running python in
package mode. The solution is cd'ing out of your root project directory, then
running python as a package (note there is no .py after tasks):
python -m cive.framework.tasks
Now when I run the celery task everything works.
|
How to merge xArray datasets with conflicting coordinates
Question: Let's say I have two data sets, each containing a different variable of
interest and with incomplete (but not conflicting) indices:
In [1]: import xarray as xr, numpy as np
In [2]: ages = xr.Dataset(
{'ages': (['kid_ids'], np.random.rand((3))*20)},
coords={'kid_names':(['kid_ids'], ['carl','kathy','gail']), 'kid_ids': [10,14,16]})
In [3]: heights = xr.Dataset(
{'heights': (['kid_ids'], np.random.rand((3))*160)},
coords={'kid_names':(['kid_ids'], ['carl','keith','gail']), 'kid_ids': [10,13,16]})
This creates two data sets that seem like they should merge well:
In [4]: ages
Out[4]:
<xarray.Dataset>
Dimensions: (kid_ids: 3)
Coordinates:
* kid_ids (kid_ids) int32 10 14 16
kid_names (kid_ids) <U5 'carl' 'kathy' 'gail'
Data variables:
ages (kid_ids) float64 13.28 1.955 4.327
In [5]: heights
Out[5]:
<xarray.Dataset>
Dimensions: (kid_ids: 3)
Coordinates:
* kid_ids (kid_ids) int32 10 13 16
kid_names (kid_ids) <U5 'carl' 'keith' 'gail'
Data variables:
heights (kid_ids) float64 115.0 38.2 31.65
but they don't - attempting `ages.merge(heights)` causes a `ValueError`:
ValueError: conflicting value for variable kid_names:
first value: <xarray.Variable (kid_ids: 4)>
array(['carl', nan, 'kathy', 'gail'], dtype=object)
second value: <xarray.Variable (kid_ids: 4)>
array(['carl', 'keith', nan, 'gail'], dtype=object)
dropping the coordinate `kid_names` solves the problem:
In [7]: ages.reset_coords('kid_names', drop=True).merge(
heights.reset_coords('kid_names', drop=True))
Out[7]:
<xarray.Dataset>
Dimensions: (kid_ids: 4)
Coordinates:
* kid_ids (kid_ids) int64 10 13 14 16
Data variables:
ages (kid_ids) float64 0.4473 nan 6.45 6.787
heights (kid_ids) float64 78.42 78.43 nan 113.4
It seems as though the coordinates are being handled like `DataArrays`, in
that any non-identical values raise an error. But shouldn't they be handled
more like the base coordinates, e.g. extended to the superset of the two
indices? Or is there another operation I should be doing?
I'm on python 3.5 using xarray 0.7.2 and numpy 1.10.4
Answer: This isn't currently easy to achieve in xarray, but it should be!
In fact, I think it should be safe to merge any non-conflicting values under
most circumstances (unless the user requests higher scrutiny).
I opened a GitHub issue to track this:
<https://github.com/pydata/xarray/issues/835>
|
why pool.map in python doesn't work
Question:
import multiprocessing as mul
def f(x):
return x**2
pool = mul.Pool(5)
rel = pool.map(f,[1,2,3,4,5,6,7,8,9,10])
print(rel)
When I run the program above, the application is stuck in a loop and can't
stop. I am using python 3.5 in windows, is there something wrong?
This is what I see on my screen:

I am new to finance data analysis; and I am trying to find out a way to solve
the big data problem with parallel computing.
Answer: Its not working because you are typing the commands in a shell; try saving the
code in a file and running it directly.
Don't forget to copy the code correctly, you were missing a very important
`if` statement (see the
[documentation](https://docs.python.org/2/library/multiprocessing.html#introduction)).
Save this to a file, for example `example.py` on the desktop:
import multiprocessing as mul
def f(x):
return x**2
if __name__ == '__main__':
pool = mul.Pool(5)
rel = pool.map(f,[1,2,3,4,5,6,7,8,9,10])
print(rel)
Then, open a command prompt and type:
python %USERPROFILE%\Desktop\example.py
|
Linux command equivalent of hash() in python
Question: In my program In have a log directory. Name of the log directory is very long
so in my python script I used hash function to get the unique code and append
it to fixed string ie:
LOG_DIR = "abcdefghijklmnopqrstuvwxyz"
log_dir_hashed = hash(LOG_DIR)
new_log_dir = "log_%s" %log_dir_hashed
Since I am new to python please tell me if anything can go wrong with above
code? also How to do similar thing in shell script so that result of the
python directory name and shell directory name obtained after hashing is same.
Answer: [`hash()`](https://docs.python.org/3/library/functions.html#hash) is an
implementation detail of python and [`__hash__`
dunders](https://docs.python.org/3/reference/datamodel.html#object.__hash__)
can even override what it does, so you shouldn't be using it like that. It
also has some possibly [surprising
properties](http://stackoverflow.com/questions/7648129/when-is-a-python-
objects-hash-computed-and-why-is-the-hash-of-1-different), like:
# This is not a collision produced by the used hashing method, it is
# how hash() functions. The result though is a collision.
>>> hash(-2) == hash(-1)
True
Use a well known hash like MD5 or SHA1 etc. If you need cryptographically
secure log dirs, choose a suitable hash based on that. Have a look at
<https://docs.python.org/3/library/hashlib.html>. These have equivalent
command line tools available.
For example:
from hashlib import md5
log_dir_hashed = md5('abcdefghijklmnopqrstuvwxyz'.encode('utf-8')).hexdigest()
new_log_dir = "log_%s" % log_dir_hashed
Comparing python:
>>> md5('abcdefghijklmnopqrstuvwxyz'.encode('utf-8')).hexdigest()
'c3fcd3d76192e4007dfb496cca67e13b'
and equivalent command line (one way to do it):
% echo -n 'abcdefghijklmnopqrstuvwxyz' | md5sum - | awk '{print $1}'
c3fcd3d76192e4007dfb496cca67e13b
|
Python Tkinter multiple frames with some animation on each frame
Question: inspired by Bryan Oakley post [question] [Switch between two frames in
tkinter](http://stackoverflow.com/questions/7546050/switch-between-two-frames-
in-tkinter) I wrote this program with three pages, each page having an
animation: a clock, a measuring device, three bar graphs on the last page.
Following the execution of this program i found that it have an increase in
the use of memory and CPU utilization rate, on Windows and on Linux. I use
Python 2.7. I'm sure I'm wrong somewhere but I have not found what to do to
keep the memory and the CPU usage percentage at a constant level. Any advice
is welcome. Thanks.
Here is the code:
#import tkinter as tk # python3
import Tkinter as tk # python
import time
import datetime
import os
import random
from math import *
TITLE_FONT = ("Helvetica", 18, "bold")
LABPOZ4 = 480
LABVERT = 5
if (os.name == 'nt'):
cale = 'images\\gif\\'
elif (os.name == 'posix'):
cale = 'images/gif/'
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
# the container is where we'll stack a bunch of frames
# on top of each other, then the one we want visible
# will be raised above the others
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, PageOne, PageTwo, PageThree):
page_name = F.__name__
frame = F(container, self)
self.frames[page_name] = frame
# put all of the pages in the same location;
# the one on the top of the stacking order
# will be the one that is visible.
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("StartPage")
def show_frame(self, page_name):
'''Show a frame for the given page name'''
frame = self.frames[page_name]
frame.tkraise()
#frame.winfo_toplevel().overrideredirect(1) #pentru teste se comenteaza
frame.winfo_toplevel().geometry("640x480")
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is the start page", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
# DATA SI TIMPUL
DataOra = tk.StringVar()
DataOra.set('2016-04-06 16:20:00')
label4 = tk.Label(self, textvariable=DataOra, fg='blue', bg='white', relief="ridge", width=20)
label4.config(font=('courier', 10, 'bold'))
label4.place(x=LABPOZ4, y=LABVERT)
button1 = tk.Button(self, text="Go to\nPage One", height=2, width=10,
command=lambda: controller.show_frame("PageOne"))
button2 = tk.Button(self, text="Go to\nPage Two", height=2, width=10,
command=lambda: controller.show_frame("PageTwo"))
button3 = tk.Button(self, text="Go to\nPage Three", height=2, width=10,
command=lambda: controller.show_frame("PageThree"))
button1.place(x=100,y=430)
button2.place(x=200,y=430)
button3.place(x=300,y=430)
def afisare():
date1=datetime.datetime.now().strftime("%Y-%m-%d")
time1=datetime.datetime.now().strftime("%H:%M:%S")
tmx= '%s %s' % (date1, time1)
DataOra.set(tmx)
label4.after(1000,afisare)
afisare()
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is page 1", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
# DATA SI TIMPUL
DataOra = tk.StringVar()
DataOra.set('2016-04-06 16:20:00')
label4 = tk.Label(self, textvariable=DataOra, fg='blue', bg='white', relief="ridge", width=20)
label4.config(font=('courier', 10, 'bold'))
label4.place(x=LABPOZ4, y=LABVERT)
button = tk.Button(self, text="Go to the\n start page", height=2, width=10,
command=lambda: controller.show_frame("StartPage"))
button.place(x=100,y=430)
# CEAS TEST
def Clock0(w, nx, ny): # clock draw function
x0 = nx/2; lx = 9*nx/20 # center and half-width of clock face
y0 = ny/2; ly = 9*ny/20
r = 5
r0 = 0.9 * min(lx,ly) # distance of hour labels from center
r1 = 0.6 * min(lx,ly) # length of hour hand
r2 = 0.8 * min(lx,ly) # length of minute hand
w.create_oval(x0-lx, y0-ly, x0+lx, y0+ly, width=3) # clock face
for i in range(1,13): # label the clock face
phi = pi/6 * i # angular position of label
x = x0 + r0 * sin(phi) # Cartesian position of label
y = y0 - r0 * cos(phi)
w.create_text(x, y, text=str(i)) # hour label
t = time.localtime() # current time
t_s = t[5] # seconds
t_m = t[4] + t_s/60 # minutes
t_h = t[3] % 12 + t_m/60 # hours [0,12]
phi = pi/6 * t_h # hour hand angle
x = x0 + r1 * sin(phi) # position of arrowhead
y = y0 - r1 * cos(phi) # draw hour hand
w.create_line(x0, y0, x, y, arrow=tk.LAST, fill="red", width=5)
phi = pi/30 * t_m # minute hand angle
x = x0 + r2 * sin(phi) # position of arrowhead
y = y0 - r2 * cos(phi) # draw minute hand
w.create_line(x0, y0, x, y, arrow=tk.LAST, fill="blue", width=4)
phi = pi/30 * t_s # second hand angle
x = x0 + r2 * sin(phi) # position of arrowhead
y = y0 - r2 * cos(phi)
w.create_line(x0, y0 , x, y, arrow=tk.LAST, fill="yellow", width=3) # draw second hand
centru_ace = w.create_oval(x0-r,y0-r,x0+r,y0+r, fill="red")
def Clock(w, nx, ny): # clock callback function
w.delete(tk.ALL) # delete canvas
Clock0(w, nx, ny) # draw clock
w.after(10, Clock, w, nx, ny) # call callback after 10 ms
nx = 250; ny = 250 # canvas size
w = tk.Canvas(self, width=nx, height=ny, bg = "white") # create canvas w
w.place(x=200,y=50) # make canvas visible
Clock(w, nx, ny)
### END CEAS TEST
def afisare():
date1=datetime.datetime.now().strftime("%Y-%m-%d")
time1=datetime.datetime.now().strftime("%H:%M:%S")
tmx= '%s %s' % (date1, time1)
DataOra.set(tmx)
label4.after(1000,afisare)
afisare()
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is page 2", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
# DATA SI TIMPUL
DataOra = tk.StringVar()
DataOra.set('2016-04-06 16:20:00')
label4 = tk.Label(self, textvariable=DataOra, fg='blue', bg='white', relief="ridge", width=20)
label4.config(font=('courier', 10, 'bold'))
label4.place(x=LABPOZ4, y=LABVERT)
button = tk.Button(self, text="Go to the\nstart page", height=2, width=10,
command=lambda: controller.show_frame("StartPage"))
button.place(x=100,y=430)
# APARAT TEST
global red, bulina
red = 0
bulina = 0
def Aparat0(w, nx, ny, valoare): # clock draw function
global red, bulina
x0 = nx/2; lx = 9*nx/20 # center and half-width of clock face
y0 = ny/2+14; ly = 9*ny/20
r1 = 0.8 * min(lx,ly) # length of indicator
t_h = valoare # 90 jos, 45 stanga, 180 sus
phi = pi/6 * t_h # hand angle
x = x0 + r1 * sin(phi) # position of arrowhead
y = y0 - r1 * cos(phi) # draw hand
red = w.create_line(x0, y0, x, y, arrow=tk.LAST, fill="red", width=3)
r = 5
bulina = w.create_oval(x0-r,y0-r,x0+r,y0+r, fill="red")
def Aparat(w, nx, ny, valoare): # clock callback function
global red, bulina
w.delete(red) # delete canvas
w.delete(bulina)
Aparat0(w, nx, ny, valoare) # draw clock
w.after(5000, Aparat, w, nx, ny, valoare) # call callback after 10 ms
# IMAGINE SCALA APARAT
photo4 = tk.PhotoImage(file=cale+'scala1.gif') #scala1.gif
self.ph1 = photo4
nx = 350; ny = 350 # canvas size
w = tk.Canvas(self, width=nx, height=ny, bg = "white") # create canvas w
w.create_image(175, 175, image=photo4)
w.place(x=150,y=50) # make canvas visible
#Aparat(w, nx, ny, 180)
def afisare_Aparat():
valoare = random.randint(100,270)
Aparat(w,nx,ny,valoare)
w.after(5000,afisare_Aparat)
afisare_Aparat()
### END APARAT TEST
def afisare():
date1=datetime.datetime.now().strftime("%Y-%m-%d")
time1=datetime.datetime.now().strftime("%H:%M:%S")
tmx= '%s %s' % (date1, time1)
DataOra.set(tmx)
label4.after(1000,afisare)
afisare()
class PageThree(tk.Frame): # Parametrii AC
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is page 3", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
# DATA SI TIMPUL
DataOra = tk.StringVar()
DataOra.set('2016-04-06 16:20:00')
label4 = tk.Label(self, textvariable=DataOra, fg='blue', bg='white', relief="ridge", width=20)
label4.config(font=('courier', 10, 'bold'))
label4.place(x=LABPOZ4, y=LABVERT)
button = tk.Button(self, text="Go to the\nstart page", height=2, width=10,
command=lambda: controller.show_frame("StartPage"))
button.place(x=100,y=430)
# APARAT TEST
global red1
red1 = 0
bulina1 = 0
def Aparat01(w1, nx, ny, valoare): # bar draw function
global red1
x0 = 50
y0 = ny
for i in range(0,450,50):
x = 20 # Cartesian position of label
y = y0 - i/2 - 5
#print y
w1.create_text(x, y, text=str(i)) # value label
w1.create_line(x+20, y, x+15, y, fill="black", width=2)
t_h = valoare # valoare
x = x0 + 20 # position of head
y = y0 - t_h # draw bar
red1 = w1.create_rectangle(x0, y0, x, y, fill="red")
w1.create_line(50, 200, 71, 200, fill="green", width=4)
def Aparat1(w1, nx, ny, valoare): # bar callback function
global red1
w1.delete(tk.ALL) # delete canvas
Aparat01(w1, nx, ny, valoare) # draw bar
w1.after(3000, Aparat1, w1, nx, ny, valoare) # call callback after 5000 ms
nx = 70; ny = 350 # canvas size
w1 = tk.Canvas(self, width=nx, height=ny, bg = "white", relief='ridge') # create canvas
w1.place(x=150,y=50) # make canvas visible at x,y
def afisare_Aparat1():
valoare = random.randint(100,270)
Aparat1(w1,nx,ny,valoare)
w1.after(3000,afisare_Aparat1)
afisare_Aparat1()
### END APARAT TEST
# APARAT TEST1
global red2
red2 = 0
def Aparat02(w2, nx, ny, valoare): # clock draw function
global red2
x0 = 50 # center and half-width of clock face
y0 = ny # length of indicator
for i in range(0,450,50):
x = 20 # Cartesian position of label
y = y0 - i/2 - 5
#print y
w2.create_text(x, y, text=str(i)) # value label
w2.create_line(x+20, y, x+15, y, fill="black", width=2)
t_h = valoare # 90 jos, 45 stanga, 180 sus
x = x0 + 20 # position of arrowhead
y = y0 - t_h # draw hand
red2 = w2.create_rectangle(x0, y0, x, y, fill="blue")
w2.create_line(50, 200, 71, 200, fill="yellow", width=4)
def Aparat2(w2, nx, ny, valoare): # clock callback function
global red2
w2.delete(tk.ALL) # delete canvas
Aparat02(w2, nx, ny, valoare) # draw clock
w2.after(4000, Aparat2, w2, nx, ny, valoare) # call callback after 10 ms
nx2 = 70; ny2 = 350 # canvas size
w2 = tk.Canvas(self, width=nx2, height=ny2, bg = "white", relief='ridge') # create canvas w
w2.place(x=250,y=50) # make canvas visible
def afisare_Aparat2():
valoare = random.randint(100,270)
Aparat2(w2,nx,ny,valoare)
w2.after(4000,afisare_Aparat2)
afisare_Aparat2()
### END APARAT TEST1
# APARAT TEST2
global red3
red3 = 0
def Aparat03(w3, nx, ny, valoare): # clock draw function
x0 = 50 # center and half-width of clock face
y0 = ny # length of indicator
for i in range(0,450,50):
x = 20 # Cartesian position of label
y = y0 - i/2 - 5
#print y
w3.create_text(x, y, text=str(i)) # value label
w3.create_line(x+20, y, x+15, y, fill="black", width=2)
t_h = valoare # 90 jos, 45 stanga, 180 sus
x = x0 + 20 # position of arrowhead
y = y0 - t_h # draw hand
red3 = w3.create_rectangle(x0, y0, x, y, fill="green")
w3.create_line(50, 200, 71, 200, fill="red", width=4)
def Aparat3(w3, nx, ny, valoare): # clock callback function
global red3
w3.delete(tk.ALL) # delete canvas
Aparat03(w3, nx, ny, valoare) # draw clock
w3.after(5000, Aparat3, w3, nx, ny, valoare) # call callback after 10 ms
nx3 = 70; ny3 = 350 # canvas size
w3 = tk.Canvas(self, width=nx3, height=ny3, bg = "white", relief='ridge') # create canvas
w3.place(x=350,y=50) # make canvas visible
def afisare_Aparat3():
valoare = random.randint(100,270)
Aparat3(w3,nx,ny,valoare)
w3.after(5000,afisare_Aparat3)
afisare_Aparat3()
### END APARAT TEST2
def afisare():
date1=datetime.datetime.now().strftime("%Y-%m-%d")
time1=datetime.datetime.now().strftime("%H:%M:%S")
tmx= '%s %s' % (date1, time1)
DataOra.set(tmx)
label4.after(1000,afisare)
afisare()
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
Answer: Finally, I found the problem. Here's the right code, if someone will be
interested. I have simplified the code as much as possible. Thanks, for yours
advice.
#import tkinter as tk # python3
import Tkinter as tk # python
import time
import datetime
import os
import random
from math import *
TITLE_FONT = ("Helvetica", 18, "bold")
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
# the container is where we'll stack a bunch of frames
# on top of each other, then the one we want visible
# will be raised above the others
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, PageOne, PageTwo, PageThree):
page_name = F.__name__
frame = F(container, self)
self.frames[page_name] = frame
# put all of the pages in the same location;
# the one on the top of the stacking order
# will be the one that is visible.
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("StartPage")
def show_frame(self, page_name):
'''Show a frame for the given page name'''
frame = self.frames[page_name]
frame.tkraise()
#frame.winfo_toplevel().overrideredirect(1) #pentru teste se comenteaza
frame.winfo_toplevel().geometry("640x480")
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is the start page", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
# DATA SI TIMPUL
DataOra = tk.StringVar()
DataOra.set('2016-04-06 16:20:00')
label4 = tk.Label(self, textvariable=DataOra, fg='blue', bg='white', relief="ridge", width=20)
label4.config(font=('courier', 10, 'bold'))
label4.place(x=480, y=5)
button1 = tk.Button(self, text="Go to\nPage One", height=2, width=10,
command=lambda: controller.show_frame("PageOne"))
button2 = tk.Button(self, text="Go to\nPage Two", height=2, width=10,
command=lambda: controller.show_frame("PageTwo"))
button3 = tk.Button(self, text="Go to\nPage Three", height=2, width=10,
command=lambda: controller.show_frame("PageThree"))
button1.place(x=100,y=430)
button2.place(x=200,y=430)
button3.place(x=300,y=430)
def afisare():
date1=datetime.datetime.now().strftime("%Y-%m-%d")
time1=datetime.datetime.now().strftime("%H:%M:%S")
tmx= '%s %s' % (date1, time1)
DataOra.set(tmx)
label4.after(1000,afisare)
afisare()
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is page 1", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
# DATA SI TIMPUL
DataOra = tk.StringVar()
DataOra.set('2016-04-06 16:20:00')
label4 = tk.Label(self, textvariable=DataOra, fg='blue', bg='white', relief="ridge", width=20)
label4.config(font=('courier', 10, 'bold'))
label4.place(x=430, y=5)
button = tk.Button(self, text="Go to the\n start page", height=2, width=10,
command=lambda: controller.show_frame("StartPage"))
button.place(x=100,y=430)
# CEAS TEST
global line1, line2, line3
line1 = 0; line2 = 0; line3 = 0
def Clock0(w, nx, ny): # clock draw function
global line1, line2, line3
x0 = nx/2; lx = 9*nx/20 # center and half-width of clock face
y0 = ny/2; ly = 9*ny/20
r = 5
r0 = 0.9 * min(lx,ly) # distance of hour labels from center
r1 = 0.6 * min(lx,ly) # length of hour hand
r2 = 0.8 * min(lx,ly) # length of minute hand
w.create_oval(x0-lx, y0-ly, x0+lx, y0+ly, width=3) # clock face
for i in range(1,13): # label the clock face
phi = pi/6 * i # angular position of label
x = x0 + r0 * sin(phi) # Cartesian position of label
y = y0 - r0 * cos(phi)
w.create_text(x, y, text=str(i)) # hour label
t = time.localtime() # current time
t_s = t[5] # seconds
t_m = t[4] + t_s/60 # minutes
t_h = t[3] % 12 + t_m/60 # hours [0,12]
phi = pi/6 * t_h # hour hand angle
x = x0 + r1 * sin(phi) # position of arrowhead
y = y0 - r1 * cos(phi) # draw hour hand
line1 = w.create_line(x0, y0, x, y, arrow=tk.LAST, fill="red", width=5, tag='ceas')
w.coords(line1, x0, y0, x, y)
phi = pi/30 * t_m # minute hand angle
x = x0 + r2 * sin(phi) # position of arrowhead
y = y0 - r2 * cos(phi) # draw minute hand
line2 = w.create_line(x0, y0, x, y, arrow=tk.LAST, fill="blue", width=4, tag='ceas')
w.coords(line2, x0, y0, x, y)
phi = pi/30 * t_s # second hand angle
x = x0 + r2 * sin(phi) # position of arrowhead
y = y0 - r2 * cos(phi)
line3 = w.create_line(x0, y0 , x, y, arrow=tk.LAST, fill="yellow", width=3, tag='ceas')
w.coords(line3, x0, y0, x, y)
centru_ace = w.create_oval(x0-r,y0-r,x0+r,y0+r, fill="red")
def Clock(w, nx, ny): # clock callback function
global line1, line2, line3
w.delete('ceas') # delete canvas
Clock0(w, nx, ny)
#w.coords(line1, 100,100,200,200) # draw clock
#w.coords(line2, 100,100,200,200)
#w.coords(line3, 100,100,200,200)
w.after(10, Clock, w, nx, ny) # call callback after 10 ms
nx = 250; ny = 250 # canvas size
w = tk.Canvas(self, width=nx, height=ny, bg = "white") # create canvas w
w.place(x=200,y=50) # make canvas visible
Clock(w, nx, ny)
### END CEAS TEST
def afisare():
date1=datetime.datetime.now().strftime("%Y-%m-%d")
time1=datetime.datetime.now().strftime("%H:%M:%S")
tmx= '%s %s' % (date1, time1)
DataOra.set(tmx)
label4.after(1000,afisare)
afisare()
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is page 2", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
# DATA SI TIMPUL
DataOra = tk.StringVar()
DataOra.set('2016-04-06 16:20:00')
label4 = tk.Label(self, textvariable=DataOra, fg='blue', bg='white', relief="ridge", width=20)
label4.config(font=('courier', 10, 'bold'))
label4.place(x=480, y=5)
button = tk.Button(self, text="Go to the\nstart page", height=2, width=10,
command=lambda: controller.show_frame("StartPage"))
button.place(x=100,y=430)
# APARAT TEST
global red, bulina
red = 0
bulina = 0
def Aparat0(w, nx, ny, valoare): # scale draw function
global red, bulina
x0 = nx/2; lx = 9*nx/20 # center and half-width of clock face
y0 = ny/2+14; ly = 9*ny/20
r1 = 0.8 * min(lx,ly) # length of indicator
t_h = valoare # 90 jos, 45 stanga, 180 sus
phi = pi/6 * t_h # hand angle
x = x0 + r1 * sin(phi) # position of arrowhead
y = y0 - r1 * cos(phi) # draw hand
red = w.create_line(x0, y0, x, y, arrow=tk.LAST, fill="red", width=3)
r = 5
bulina = w.create_oval(x0-r,y0-r,x0+r,y0+r, fill="red")
def Aparat(w, nx, ny, valoare): # callback function
global red, bulina
w.delete(red) # delete red, bulina
w.delete(bulina)
Aparat0(w, nx, ny, valoare) # draw clock
#####w.after(5000, Aparat, w, nx, ny, valoare) ###### PROBLEM !!!
nx = 350; ny = 350 # canvas size
w = tk.Canvas(self, width=nx, height=ny, bg = "white") # create canvas w
w.place(x=150,y=50) # make canvas visible
#Aparat(w, nx, ny, 180)
def afisare_Aparat():
valoare = random.randint(100,270)
Aparat(w,nx,ny,valoare)
w.after(1000,afisare_Aparat)
afisare_Aparat()
### END APARAT TEST
def afisare():
date1=datetime.datetime.now().strftime("%Y-%m-%d")
time1=datetime.datetime.now().strftime("%H:%M:%S")
tmx= '%s %s' % (date1, time1)
DataOra.set(tmx)
label4.after(1000,afisare)
afisare()
class PageThree(tk.Frame): # Parametrii AC
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is page 3", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
# DATA SI TIMPUL
DataOra = tk.StringVar()
DataOra.set('2016-04-06 16:20:00')
label4 = tk.Label(self, textvariable=DataOra, fg='blue', bg='white', relief="ridge", width=20)
label4.config(font=('courier', 10, 'bold'))
label4.place(x=480, y=5)
button = tk.Button(self, text="Go to the\nstart page", height=2, width=10,
command=lambda: controller.show_frame("StartPage"))
button.place(x=100,y=430)
# APARAT TEST
def Aparat01(w1, nx, ny, valoare): # bar draw function
#global red1
x0 = 50
y0 = ny
for i in range(0,450,50):
x = 20 # Cartesian position of label
y = y0 - i/2 - 5
#print y
w1.create_text(x, y, text=str(i)) # value label
w1.create_line(x+20, y, x+15, y, fill="black", width=2)
t_h = valoare # valoare
x = x0 + 20 # position of head
y = y0 - t_h # draw bar
w1.create_rectangle(x0, y0, x, y, fill="red")
w1.create_line(50, 200, 71, 200, fill="green", width=4)
def Aparat1(w1, nx, ny, valoare): # bar callback function
w1.delete(tk.ALL) # delete canvas
Aparat01(w1, nx, ny, valoare) # draw bar
######w1.after(3000, Aparat1, w1, nx, ny, valoare) ###### PROBLEM !!!!
nx = 70; ny = 350 # canvas size
w1 = tk.Canvas(self, width=nx, height=ny, bg = "white", relief='ridge') # create canvas
w1.place(x=150,y=50) # make canvas visible at x,y
def afisare_Aparat1():
valoare = random.randint(100,270)
Aparat1(w1,nx,ny,valoare)
w1.after(1000,afisare_Aparat1)
afisare_Aparat1()
### END APARAT TEST
def afisare():
date1=datetime.datetime.now().strftime("%Y-%m-%d")
time1=datetime.datetime.now().strftime("%H:%M:%S")
tmx= '%s %s' % (date1, time1)
DataOra.set(tmx)
label4.after(1000,afisare)
afisare()
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
|
I need help in python2 to making a counter that can count up and store the count data into a file
Question: This is my code, I have to add a counter into my code so that every time the
button is pressed it will count up once and i would like to to keep on
counting up every time the button is pressed. I searched online and found out
that I have to store the counter data to a file but i do not know how to write
a code to do the count and store the count to a file. please help
from time import sleep
import RPi.GPIO as GPIO
import os
import sys
import webbrowser
GPIO.setmode(GPIO.BOARD)
button=40
button1=11
car=("/home/pi/Desktop/htb.mp4")
car2=("/home/pi/Desktop/htb2.mp4")
GPIO.setup(button,GPIO.IN)
GPIO.setup(button1,GPIO.IN)
quit_video=True
player=False
while(1):
if GPIO.input(button)==0 and GPIO.input(button1)==1:
print " thru beam "
os.system('pkill omxplayer')
os.system('omxplayer -r htb.mp4')
sleep(.5)
if GPIO.input(button1)==0 and GPIO.input(button)==1:
print " that other sensor "
os.system('pkill omxplayer')
os.system('omxplayer -r htb2.mp4')
sleep(.5)
else:
print " home "
webbrowser.open('https://www.google.com.sg/')
sleep(.5)
Answer: Such a program will help you:
import os
if not os.path.isfile("counter.txt"):
counter = 1
f = open("counter.txt","w+")
f.write(str(counter))
f.close()
print (counter)
else:
f = open("counter.txt","r+")
counter = int(f.readline())
counter += 1
f.seek(0)
f.write(str(counter))
f.close()
print (counter)
As you see below, it shares a counter between different runs:
Python 2.7.10 (default, May 23 2015, 09:44:00) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
1
>>> ================================ RESTART ================================
>>>
2
>>> ================================ RESTART ================================
>>>
3
>>> ================================ RESTART ================================
>>>
4
>>> ================================ RESTART ================================
>>>
5
>>>
|
spark-submit python file ‘home/.python-eggs’ permission denied
Question: I had a problem when I use spark-submit to run a python file.When the 'map'
code run in 'executor', the problem like this :
Traceback (most recent call last):
File "/usr/lib64/python2.7/runpy.py", line 151, in _run_module_as_main
mod_name, loader, code, fname = _get_module_details(mod_name)
File "/usr/lib64/python2.7/runpy.py", line 101, in _get_module_details
loader = get_loader(mod_name)
File "/usr/lib64/python2.7/pkgutil.py", line 464, in get_loader
return find_loader(fullname)
File "/usr/lib64/python2.7/pkgutil.py", line 474, in find_loader
for importer in iter_importers(fullname):
File "/usr/lib64/python2.7/pkgutil.py", line 430, in iter_importers
__import__(pkg)
File "/data8/yarn/local-dir/usercache/bo.feng/appcache/application_1448854352032_70810/container_1448854352032_70810_01_000002/pyspark.zip/pyspark/__init__.py", line 41, in <module>
File "/data8/yarn/local-dir/usercache/bo.feng/appcache/application_1448854352032_70810/container_1448854352032_70810_01_000002/pyspark.zip/pyspark/context.py", line 35, in <module>
File "/data8/yarn/local-dir/usercache/bo.feng/appcache/application_1448854352032_70810/container_1448854352032_70810_01_000002/pyspark.zip/pyspark/rdd.py", line 51, in <module>
File "/data8/yarn/local-dir/usercache/bo.feng/appcache/application_1448854352032_70810/container_1448854352032_70810_01_000002/pyspark.zip/pyspark/shuffle.py", line 33, in <module>
File "build/bdist.linux-x86_64/egg/psutil/__init__.py", line 89, in <module>
File "build/bdist.linux-x86_64/egg/psutil/_pslinux.py", line 24, in <module>
File "build/bdist.linux-x86_64/egg/_psutil_linux.py", line 7, in <module>
File "build/bdist.linux-x86_64/egg/_psutil_linux.py", line 4, in __bootstrap__
File "/usr/lib/python2.7/site-packages/pkg_resources.py", line 945, in resource_filename
self, resource_name
File "/usr/lib/python2.7/site-packages/pkg_resources.py", line 1633, in get_resource_filename
self._extract_resource(manager, self._eager_to_zip(name))
File "/usr/lib/python2.7/site-packages/pkg_resources.py", line 1661, in _extract_resource
self.egg_name, self._parts(zip_path)
File "/usr/lib/python2.7/site-packages/pkg_resources.py", line 1025, in get_cache_path
self.extraction_error()
File "/usr/lib/python2.7/site-packages/pkg_resources.py", line 991, inextraction_error
raise err
pkg_resources.ExtractionError: Can't extract file(s) to egg cache
The following error occurred while trying to extract file(s) to the Python egg
cache:
[Errno 13] Permission denied: '/home/.python-eggs'
The Python egg cache directory is currently set to:
/home/.python-eggs
Perhaps your account does not have write access to this directory? You can
change the cache directory by setting the PYTHON_EGG_CACHE environment
variable to point to an accessible directory.
I set the PYTHON_EGG_CACHE environment variable to every executor,and I also
write 'os.environ['PYTHON_EGG_CACHE'] = "/tmp/"' in my program,but the problem
is still happen.
My code :
import os,sys
print "env::::"+os.environ['PYTHON_EGG_CACHE']
from pyspark import SparkConf, SparkContext
# Load and parse the data
def parsePoint(line):
import os
print "env::::"+os.environ['PYTHON_EGG_CACHE']
os.environ['PYTHON_EGG_CACHE'] = "/tmp/"
values = [float(x) for x in line.split(' ')]
return line
if __name__ == "__main__":
os.environ['PYTHON_EGG_CACHE'] = "/tmp/"
print "env::::"+os.environ['PYTHON_EGG_CACHE']
conf = SparkConf()
sc = SparkContext(conf = conf)
data = sc.textFile(sys.argv[1])
parsedData = data.map(parsePoint)
parsedData.collect()
I run this python program in 'standalone' model and succeeded. This is my
submit command:
spark-submit --name test_py --master yarn-client testpy.py input/sample_svm_data.txt
Is the yarn's problem?
Answer: I solved this problem: unzip the pyspark.zip then find rdd.py file open this
file , under "import os" line ,add code as :
os.environ['PYTHON_EGG_CACHE'] = '/tmp/.python-eggs/'
os.environ['PYTHON_EGG_DIR']='/tmp/.python-eggs/'
save file and zip pyspark
|
Python3 lxml builder
Question: I'm trying to create XML-file with python lxml builder lke below:
<entityset>
<entity>
<temp code="1stCode"/>
<attr code="2ndCode">
<value>PythonIsFun</value>
</attr>
<attr code="3rdCode">
<value>PythonIsStillFun</value>
</attr>
</entity>
</entityset>
My attempt:
import lxml.builder as lb
def generate_xml(temp_code, value, value2):
temp = lb.E.entityset(
lb.E.entity(
lb.E.temp(code='{0}'.format(temp_code)),
lb.E.attr(code='2ndCode'),
lb.E.value('{0}'.format(value)),
lb.E.attr(code='3rdCode'),
lb.E.value('{0}'.format(value2))
)
)
print(etree.tounicode(temp, pretty_print=True))
generate_xml('1stCode', 'PythonIsFun', 'PythonIsStillFun')
Output:
<entityset>
<entity>
<temp code="1stCode"/>
<attr code="2ndCode"/>
<value>PythonIsFun</value>
<attr code="3rdCode"/>
<value>PythonIsStillFun</value>
<attribute/>
</entity>
</entityset>
Problem is that I don't know how to add `<value> </value>` elements between
`<attr code="code here"> </attr>` tags. Is there a way to do it with lxml
element builder?
Answer: Just move `lb.E.value()` to be parameter of `lb.E.attr()` :
temp = lb.E.entityset(
lb.E.entity(
lb.E.temp(code='{0}'.format(temp_code)),
lb.E.attr(lb.E.value('{0}'.format(value)), code='2ndCode'),
lb.E.attr(lb.E.value('{0}'.format(value2)), code='3rdCode'),
)
)
|
How to get the equation of the boundary line in Linear Discriminant Analysis with sklearn
Question: I classified some data being split in 2 categories, with
LinearDiscriminantAnalysis classifier from sklearn, and it works well, so I
did this:
from sklearn.cross_validation import train_test_split
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25) # 25% of the dataset are not used for the training
clf = LDA()
clf.fit(x_train, y_train)
Then I manage to make prediction with it and that is fine here.
But, all that is in an ipython notebook, and I'd like to use the classifier
elsewhere. I've seen the possibility of using pickles and joblib, but as I
only have 2 groups and 2 features, so I though that I could _just_ get the
equation of the boundary line, and then check whether a given point is above
or below the line to tell which group it belongs.
From what I understood, this line is orthogonal to the projection line and
goes through the mean of the clusters' mean. I think I got the clusters' mean
with `np.mean(clf.means_, axis=0)`.
But here I'm stuck on how to use all the attributes like `clf.coef_`,
`clf.intercept_`, etc... to find the equation of the projection line.
_So, my question is how can I get the boundary line equation given my
classifier._
It is also possible that I did not understood LDA properly, and I'd be
delighted to have more explanations.
Thanks
Answer: The decision boundary is simply line given with
np.dot(clf.coef_, x) - clf.intercept_ = 0
(up to the sign of intercept, which depending on the implementation may be
flipped) as this is where the sign of the decision function flips.
|
How do I extract a row of a file in python?
Question: I have an rfid reader hooked up to a raspberry pi. When i scan a card, I get a
UID number stored in my python file as "backData" I would like to store all of
my users in a separate file (IE: csv or txt file), instead of at the top of my
code and then read that file to authenticate and extract the relevant row. My
current python code is as follows:
user1 = [1,23,45,678,987]
user2 = [9,87,65,432,123]
if backData == user1:
f = open("/mnt/lock_logs/lock_log.csv", "a");
print f
value = ('\n' 'user1,FOB,') + (',') + time.strftime("%c")
myString = str(value)
f.write(myString)
f.close()
GPIO.digitalWrite(RELAY, GPIO.HIGH)
GPIO.digitalWrite(LEDBLUE, GPIO.LOW)
GPIO.digitalWrite(LEDGREEN, GPIO.HIGH)
print "Access Granted"
time.sleep(1)
GPIO.digitalWrite(RELAY, GPIO.LOW)
time.sleep(3)
GPIO.digitalWrite(LEDGREEN, GPIO.LOW)
GPIO.digitalWrite(LEDBLUE, GPIO.HIGH)
So Ideally, I would read a csv file, find the UID, and print the row to a log.
The csv file would look like this.
[1,23,456,78,987], Full Name
Thanks in advance for reviewing my issue.
Answer: Something like the below will read the file into a dict in the script.
import csv
users = {}
with open('users.csv', 'r') as fp:
reader = csv.reader(fp)
for row in reader:
id = row[0][1:-1].split(',')
name = row[1]
users[id] = name
That will build you a dict of ids to names. But honestly why not just use json
and dump()/load() the file as a whole? Is it being used by some other program
or service? Your main difficulty is translational of a text representation to
a data representation, that what formats like json do, why not use them?
if it was json format it would be:
import json
users = {}
with open('users.json', 'r') as fp:
users = json.load(fp)
And it would be much less error prone than the assumption I made in the first
version. The resulting `users` would look like this once loaded:
{
[1,23,45,678,987]: 'name1',
[9,87,65,432,123]: 'name2'
}
So to get the user would be:
if users.get(backData, None) in ('name1', 'name2'):
#stuff
of
if users.get(backData, None) is not None:
#stuff
json is just a serialization format. So whatever data structure you call
dump() on is what you'll get back when you call load(). Check out the
[docs](https://docs.python.org/2/library/json.html).
|
1 producer, 1 consumer, only 1 piece of data to communicate, is queue an overkill?
Question: This question is related to **Python Multiprocessing**. I am asking for a
suitable interprocess communication data-structure for my specific scenario:
### My scenario
I have one producer and one consumer.
1. The producer produces a _single_ fairly small panda Dataframe every 10-ish secs, then the producer puts it on a `python.multiprocess.queue`.
2. The consumer is a GUI polling that `python.multiprocess.queue` every 100ms. It is VERY CRITICAL that the consumer catches every single DataFrame the producer produces.
### My thinking
`python.multiprocess.queue` is serving the purpose (I think), and amazingly
simple to use! (praise the green slithereen lord!). But **_I am clearly not
utilizing queue's full potential with only one producer one consumer and a max
of one item on the queue. That leads me to believe that there is simpler
thing_** than queue. I tried to search for it, I got overwhelmed by options
listed in: `python 3.5 documentation: 18. Interprocess Communication and
Networking`. I am also suspecting there may be a way not involving
interprocess communication data-structure at all for my need.
Please Note
1. Performance is not very important
2. I will stick with multiprocessing for now, instead of multithreading.
### My Question
Should I be content with queue? or is there a more recommended way? I am not a
professional programmer, so I insist on doing things the tried and tested way.
I also welcome any suggestions of alternative ways of approaching my problem.
Thanks
Answer: To me, the most important thing you mentioned is this:
> It is VERY CRITICAL that the consumer catches every single DataFrame the
> producer produces.
So, let's suppose you used a _variable_ to store the DataFrame. The producer
would set it to the produced value, and the consumer would just read it. That
would work very fine, I guess.
But what would happen if somehow the consumer got blocked by more than one
producing cycle? Then some old value would be overwritten before reading. And
that's why I think a (thread-safe) queue is the way to go almost "by
definition".
Besides, beware of premature optimization. If it works for your case,
excellent. If some day, for some other case, performance comes to be a
problem, only then you should spend the extra work, IMO.
|
Retrieving information from Instagram using an unauthenticated request?
Question: I'm attempting to use the Instagram with Python and I'm running into an issue
just using the stock examples on their [GitHub
page.](https://github.com/facebookarchive/python-instagram) I'm following the
steps exactly in the first unauthenticated request section, and I'm being
thrown the following errors.
My code:
from instagram.client import InstagramAPI
access_token = "..."
client_secret = "..."
client_id = "..."
api = InstagramAPI(client_id=client_id, client_secret=client_secret)
popular_media = api.media_popular(count=20)
for media in popular_media:
print media.images['standard_resolution'].url
The error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Python/2.7/site-packages/instagram/bind.py", line 197, in _call
return method.execute()
File "/Library/Python/2.7/site-packages/instagram/bind.py", line 189, in execute
content, next = self._do_api_request(url, method, body, headers)
File "/Library/Python/2.7/site-packages/instagram/bind.py", line 131, in _do_api_request
raise InstagramClientError('Unable to parse response, not valid JSON.', status_code=response['status'])
instagram.bind.InstagramClientError: (404) Unable to parse response, not valid JSON.
Any help would be appreciated! Again, this code is just straight from the docs
so I'm not sure why it's not working.
Answer: According to the Instagram Developers page,
"**Instagram Platform and documentation update**. Apps created on or after Nov
17, 2015 will start in Sandbox Mode and function on newly updated API rate-
limits and behaviors."
As a result, if you created your app before Nov 17, 2015, you will not be able
to perform unauthenticated requests.
Those docs from the python-instagram page(Last updated over 9 months ago) are
outdated if your app was created before Nov 17, 2015.
|
I need to connect to a single IP using multiple telnet sessions, is there a way to do it? Below is my code in python
Question: This is one session of telnet, I want such multiple sessions to be connected.
import telnetlib
import time
tn = telnetlib.Telnet("10.13.135.3",23)
time.sleep(10)
tn.write("/H")
print tn.read_until("Enter Password:")
tn.write("power" + "\r\n")
time.sleep(5)
print tn.read_eager()
tn.read_until("IPS>")
tn.write("/OFF 1" +"\r\n")
time.sleep(2)
Answer: It is simple ... you can make additional connection like this.
tn1 = telnetlib.Telnet(...)
tn2 = telnetlib.Telnet(...)
and then you can work with them as usuall
|
How to handle different exceptions raised in different Python version
Question: Trying to parse a malformed XML content with xml.etree.ElementTree.parse()
raises different exception in Python 2.6.6 and Python 2.7.5
Python 2.6: xml.parsers.expat.ExpatError
Python 2.7: xml.etree.ElementTree.ParseError
I'm writing code which must run in Python 2.6 and 2.7. afaik there is no way
to define code which runs only in a Python version in Python (analogous to
what we could do with #ifdef in C/C++). The only way I see to handle both
exceptions is to catch a common parent exception of both (eg Exception).
However, that is not ideal because other exceptions will be handled in the
same catch block. Is there any other way?
Answer: This isn't pretty, but it should be workable ...
ParseError = xml.parsers.expat.ExpatError if sys.version < (2, 7) else xml.etree.ElementTree.ParseError
try:
...
except ParseError:
...
You _might_ need to modify what you import based on versions (or catch
`ImportError` while importing the various submodules from `xml` if they don't
exist on python2.6 -- I don't have that version installed, so I can't do a
robust test at the moment...)
|
Wrapping all possible method calls of a class in a try/except block
Question: I'm trying to wrap all methods of an existing Class (not of my creation) into
a try/except suite. It could be any Class, but I'll use the
**pandas.DataFrame** class here as a practical example.
So if the invoked method succeeds, we simply move on. But if it should
generate an exception, it is appended to a list for later inspection/discovery
(although the below example just issues a print statement for simplicity).
_(Note that the kinds of data-related exceptions that can occur when a method
on the instance is invoked, isn't yet known; and that's the reason for this
exercise: discovery)._
This [post](http://stackoverflow.com/questions/11349183/how-to-wrap-every-
method-of-a-class) was quite helpful (particularly @martineau Python-3
answer), but I'm having trouble adapting it. Below, I expected the second call
to the (wrapped) _info()_ method to emit print output but, sadly, it doesn't.
#!/usr/bin/env python3
import functools, types, pandas
def method_wrapper(method):
@functools.wraps(method)
def wrapper(*args, **kwargs): #Note: args[0] points to 'self'.
try:
print('Calling: {}.{}()... '.format(args[0].__class__.__name__, method.__name__))
return method(*args, **kwargs)
except Exception:
print('Exception: %r' % sys.exc_info()) # Something trivial.
#<Actual code would append that exception info to a list>.
return wrapper
class MetaClass(type):
def __new__(mcs, class_name, base_classes, classDict):
newClassDict = {}
for attributeName, attribute in classDict.items():
if type(attribute) == types.FunctionType: # Replace it with a wrapper (decorated) version.
attribute = method_wrapper(attribute)
newClassDict[attributeName] = attribute
return type.__new__(mcs, class_name, base_classes, newClassDict)
class WrappedDataFrame2(MetaClass('WrappedDataFrame',(pandas.DataFrame, object,), {}), metaclass=type):
pass
print('Unwrapped pandas.DataFrame().info():')
pandas.DataFrame().info()
print('\n\nWrapped pandas.DataFrame().info():')
WrappedDataFrame2().info()
print()
This outputs:
Unwrapped pandas.DataFrame().info():
<class 'pandas.core.frame.DataFrame'>
Index: 0 entries
Empty DataFrame
Wrapped pandas.DataFrame().info(): <-- Missing print statement after this line.
<class '__main__.WrappedDataFrame2'>
Index: 0 entries
Empty WrappedDataFrame2
In summary,...
>>> unwrapped_object.someMethod(...)
# Should be mirrored by ...
>>> wrapping_object.someMethod(...)
# Including signature, docstring, etc. (i.e. all attributes); except that it
# executes inside a try/except suite (so I can catch exceptions generically).
Answer: Your metaclass only applies your decorator to the methods defined in classes
that are instances of it. It doesn't decorate inherited methods, since they're
not in the `classDict`.
I'm not sure there's a good way to make it work. You could try iterating
through the MRO and wrapping all the inherited methods as well as your own,
but I suspect you'd get into trouble if there were multiple levels of
inheritance after you start using `MetaClass` (as each level will decorate the
already decorated methods of the previous class).
|
Querying a remote API from a Python script
Question: I would like to integrate the `reviews API` from Zomato in my Python script.
I know basic programming in Python, but as for API integration, I want to know
* how to proceed with the API
* what steps should be taken to query the API from Python
* how to integrate the results in my script
What are the viable options?
Answer: You may get started with Python's `requests` module.
Quick example to get a list of categories:
import requests
domain = "https://developers.zomato.com/api/v2.1"
headers = {'user-key': 'your_api_key_here'}
response = requests.get("{}/categories".format(domain), headers=headers).json()
for category in response["categories"]:
print(category)
This will output something like:
{"categories": {"id": 1, "name": "Delivery"}}
{"categories": {"id": 2, "name": "Dine-out"}}
{"categories": {"id": 3, "name": "Nightlife"}}
{"categories": {"id": 4, "name": "Catching-up"}}
{"categories": {"id": 5, "name": "Takeaway"}}
# etc...
Documentation for `requests` [can be found here.](http://docs.python-
requests.org/en/master/)
|
Python XML Grab IP from File Between CDATA
Question: I have an XML dump file that I want to parse for the first occurrence of
'ETH0_IP'. However, the cdata field is throwing me. It ends up returning
'None'. There are other IPs that appear further in the file but I don't care
about those.
I have something like this so far:
q = etree.parse(outputfile)
fileoutputip = q.findtext("ETH0_IP")
This is the XML:
<VM>
<ID>####</ID>
<UID>0</UID>
<GID>0</GID>
<UNAME>####</UNAME>
<GNAME>###</GNAME>
<NAME>###</NAME>
<PERMISSIONS>
<OWNER_U>1</OWNER_U>
<OWNER_M>1</OWNER_M>
<OWNER_A>0</OWNER_A>
<GROUP_U>0</GROUP_U>
<GROUP_M>0</GROUP_M>
<GROUP_A>0</GROUP_A>
<OTHER_U>0</OTHER_U>
<OTHER_M>0</OTHER_M>
<OTHER_A>0</OTHER_A>
</PERMISSIONS>
<LAST_POLL>1461191030</LAST_POLL>
<STATE>3</STATE>
<LCM_STATE>3</LCM_STATE>
<PREV_STATE>3</PREV_STATE>
<PREV_LCM_STATE>3</PREV_LCM_STATE>
<RESCHED>0</RESCHED>
<STIME>1461189864</STIME>
<ETIME>0</ETIME>
<DEPLOY_ID>###</DEPLOY_ID>
<MEMORY>###</MEMORY>
<CPU>0</CPU>
<NET_TX>1000</NET_TX>
<NET_RX>73254</NET_RX>
<TEMPLATE>
<AUTOMATIC_REQUIREMENTS><![CDATA[!(PUBLIC_CLOUD = YES)]]></AUTOMATIC_REQUIREMENTS>
<CONTEXT>
<DISK_ID><![CDATA[1]]></DISK_ID>
<ETH0_DNS><![CDATA[####]]></ETH0_DNS>
<ETH0_GATEWAY><![CDATA[###]]></ETH0_GATEWAY>
<ETH0_IP><![CDATA[10.**.***.**]]></ETH0_IP>
Answer: `q.findtext("ETH0_IP")` would try to find `ETH0_IP` element _directly under
the root element in the tree_ and in this case it results into `None` since
`VM` does not have a direct `ETH0_IP` child.
You can solve it by providing the XPath expression (to look for the `ETH0_IP`
element anywhere in the tree) to `find()` or `findtext()`, or by using
`xpath()` method directly:
>>> from lxml import etree
>>>
>>> tree = etree.parse("input.xml")
>>> print(tree.find(".//ETH0_IP").text)
10.**.***.**
>>> print(tree.findtext(".//ETH0_IP"))
10.**.***.**
>>> print(tree.xpath("//ETH0_IP")[0].text)
10.**.***.**
|
a function that modifies its class's data objects
Question: I want to define a function, call it `test_controller()`, and I want to pass
this function to a constructor: `my_thing = TestClass(test_controller)`. This
function needs to be able to modify its class's data objects. I've heard of
the `nonlocal` keyword for Python 3, but I'm running Python 2.7. Is it
possible? How do I do this? Here's what I have tried already.
class TestClass(object):
def __init__(self, ctrl_func):
self.a = 4
self.ctrl_func = ctrl_func
def do_stuff(self):
self.ctrl_func()
def test_controller():
global a
a = 20
my_thing = TestClass(test_controller)
print my_thing.a #this prints 4
my_thing.ctrl_func()
print my_thing.a #this prints 4 but I want it to print 20
Answer: You can pass in a reference to whatever object you intend to modify.
class TestClass(object):
def __init__(self, ctrl_func):
self.a = 4
self.ctrl_func = ctrl_func
def do_stuff(self):
self.ctrl_func(self)
def test_controller(self):
self.a = 20
my_thing = TestClass(test_controller)
print my_thing.a #this prints 4
my_thing.ctrl_func(my_thing)
print my_thing.a #this prints 4 but I want it to print 20
Alternatively, you can convert ctrl_func into a bound method of the object:
import types
class TestClass(object):
def __init__(self, ctrl_func):
self.a = 4
self.ctrl_func = types.MethodType(ctrl_func, self)
def do_stuff(self):
self.ctrl_func()
def test_controller(self):
self.a = 20
my_thing = TestClass(test_controller)
print my_thing.a #this prints 4
my_thing.ctrl_func()
print my_thing.a #this prints 4 but I want it to print 20
Reference:
* <http://stackoverflow.com/a/1015405/8747>
* <http://igorsobreira.com/2011/02/06/adding-methods-dynamically-in-python.html>
|
MNIST Python numpy eigen vectors visualization error
Question: I am trying to perform PCA on [MNIST](http://yann.lecun.com/exdb/mnist/)
dataset, as part of the process I need to generate the eigen vectors and
visualize the top features. Following is my algorithm:
1. Load images
2. Subtract mean
3. Generate Covariance matrix
4. Derive eigen vectors and eigen values
It's fairly a simple algorithm to run; my first task is to visualize the top
10 eigen vectors as images. Following is the code that I have so far:
__author__ = "Ajay Krishna Teja Kavuri"
import numpy as np
import random
from mnist import MNIST
import matplotlib.pylab as plt
class PCAMNIST:
#Initialization
def __init__(self):
#Load MNIST datset
mnistData = MNIST('./mnistData')
self.imgTrain,self.lblTrain=mnistData.load_training()
self.imgTrainSmpl=self.imgTrain[:60000]
np.seterr(all='warn')
#1. Subtract the mean because the PCA will work better
def subMean(self):
try:
self.sumImg = np.empty([784,])
#calculate the sum
for img in self.imgTrainSmpl:
imgArr = np.asarray(img)
self.sumImg = np.add(imgArr,self.sumImg)
#Calculate the mean array
self.meanImg = self.sumImg/(len(self.imgTrainSmpl))
self.meanImg = np.nan_to_num(self.meanImg)
#subtract it out
index=0
for img in self.imgTrainSmpl:
imgArr = np.asarray(img)
self.imgTrainSmpl[index] = np.subtract(imgArr,self.meanImg).tolist()
index += 1
#for img in self.imgTrainSmpl:
#print img
except:
print Exception
#2. get the covaraince matrix for each digit
def getCov(self):
self.imgCov=[]
dgtArr = np.asarray(self.imgTrainSmpl).T
dgtCov = np.cov(dgtArr)
self.imgCov.append(dgtCov)
#for img in self.imgCov:
#print img
#3. get the eigen vectors from the covariance matrix
def getEigen(self):
self.eigVec=[]
self.eigVal=[]
dgtArr = np.asarray(self.imgCov)
tmpEigVal,tmpEigVec=np.linalg.eig(dgtArr)
self.eigVal.append(tmpEigVal.tolist())
self.eigVec.append(tmpEigVec.tolist())
#print "\nEigen values:\n"
#for img in self.eigVal:
#print img
#print "\nEigen vectors:\n"
#for img in self.eigVec:
#print img
def sortEV(self):
self.eigValArr = np.asarray(self.eigVal[0][0])
self.eigVecArr = np.asarray(self.eigVec[0][0])
self.srtdInd = np.argsort(np.abs(self.eigValArr))
self.srtdEigValArr = self.eigValArr[self.srtdInd]
self.srtdEigVecArr = self.eigVecArr[self.srtdInd]
self.srtdEigVec = self.srtdEigVecArr.real.tolist()
#print self.srtdEigValArr[0]
print len(self.srtdInd.tolist())
#print self.eigVec[self.srtdInd[0]]
#print np.asarray(self.srtdEigVec).shape
#for img in self.srtdEigVecArr:
#print img
#self.drawEig()
def plotVal(self):
"""
plt.figure()
plt.scatter(np.asarray(self.eigVal).real)
plt.show()
"""
def drawEig(self):
for vec in self.srtdEigVec[:10]:
self.drawEigV(vec)
def drawEigV(self,digit):
plt.figure()
fig=plt.imshow(np.asarray(digit).reshape(28,28),origin='upper')
fig.set_cmap('gray_r')
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)
plt.savefig(str(random.randint(0,10000))+".png")
#plt.show()
plt.close()
def drawChar(self,digit):
plt.figure()
fig=plt.imshow(np.asarray(digit).reshape(28,28),clim=(-1,1.0),origin='upper')
fig.set_cmap('gray_r')
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)
plt.show()
plt.close()
def drawSmpl(self):
for img in self.imgTrainSmpl:
self.drawChar(img)
def singleStep(self):
self.val, self.vec = np.linalg.eig(np.cov(np.array(self.imgTrainSmpl).transpose()))
self.srtd = np.argsort(self.val)[::-1]
print self.val
#asnmnt4=PCAMNIST()
#asnmnt4.singleStep()
asnmnt4=PCAMNIST()
asnmnt4.subMean()
asnmnt4.getCov()
asnmnt4.getEigen()
asnmnt4.sortEV()
asnmnt4.drawEig()
#asnmnt4.plotVal()
"""
asnmnt4.getSorted()
asnmnt4.printTopEigenVal()
"""
Although the above code runs perfectly and all the array sizes match the given
dataset, it generates the following images a eigen vectors: [](http://i.stack.imgur.com/H3Xhn.png)
Clearly the eigen vectors make no sense as they have to represent the features
of the dataset which in this case should be digits. Any help is appreciated.
If you are trying to run this code you might have to install the MNIST package
and download data from link.
Answer: You're plotting the **rows** of the eigenvector matrix. The eigenvectors are
in the **columns** of the matrix, as you can see in the [`np.linalg.eig`
documentation](http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.linalg.eig.html).
You should change
self.eigVec.append(tmpEigVec.tolist())
to
self.eigVec.append(np.transpose(tmpEigVec).tolist())
and I believe it will work as expected.
|
How to open a file through python with folder name a regular expression?
Question: I want to open a file ex: xyz.txt which is in a folder named ex:
abc_4564536_01_r4897934. Now let suppose I only know that folder name consist
of "4564536_01" and there is no other folder with the same string in its name.
Answer: Your post title asks for a solution involving regular expressions, but `glob`
is probably a better choice.
`glob.glob()` returns a list of filenames that match a certain pattern.
import glob
fname = glob.glob("*4564536_01*/xyz.txt")[0]
with open(fname) as fp:
print fp.read()
|
How do I search for a word within repository?
Question: For e.g. I am looking for all the words "import" and I can use the search box
that returns something like this...
[https://github.com/charlesdaniel/s3_uploader/search?l=python&q=import&utf8=%E2%9C%93](https://github.com/charlesdaniel/s3_uploader/search?l=python&q=import&utf8=%E2%9C%93)
This lists only 8 results for s3_uploader.py file. When I checked the file,
there are 12 import statements, some of those are not returned in the search.
Why?
Answer: > This lists only 8 results for s3_uploader.py file. When I checked the file,
> there are 12 import statements
Not exactly: it shows the _top_ height results
[](http://i.stack.imgur.com/3Fd97.png)
That means it isn't meant to reflect the accurate number of occurrences, but
rather indicate the most prominent ones.
|
Server not working for multiple clients
Question: Please tell me what is the problem with my server code. It is not working for
the two clients simultaneously. It is running only for the client that I run
first. I am new to python and socket programming. Kindly help me out here.
import socket
import sys
import thread
import time
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the address given on the command line
server_address = ('127.0.0.1', 10001)
data = " ".join(sys.argv[1:])
sock.bind(server_address)
print >>sys.stderr, 'starting up on %s port %s' % sock.getsockname()
sock.listen(1)
connection, client_address = sock.accept()
def my(threadName , delay):
while True:
print >>sys.stderr, 'waiting for a connection'
try:
print >>sys.stderr, 'client connected:', client_address
while True:
data = connection.recv(16)
print >>sys.stderr, 'received "%s"' % data
a=['a' ,'e', 'i' , 'o' , 'u']
for i in data:
if i in a:
data = data.replace(i, '')
data=data.upper()
print data
print'\nUpper case string:'
if data:
connection.sendall(data)
else:
break
finally:
connection.close()
thread.start_new_thread(my , ("Thread-1" , 8,))
thread.start_new_thread(my , ("Thread-2" , 10,))
Answer: Have a look at **socketServer** module it easy to use for multiple clients
<https://docs.python.org/3.4/library/socketserver.html>
|
Interactive countinuous plotting of an ODE model in Python
Question: I would like to create a script that integrates an ode model, such that I can
change one of the parameters and see the response of the systems to this
change. If for, for example, I have a Lotka-Volterra model (as taken from this
[example](http://scipy-
cookbook.readthedocs.org/items/LoktaVolterraTutorial.html)):
import numpy as np
from scipy import integrate
a = 1.
b = 0.1
c = 1.5
d = 0.75
def dX_dt(X, t=0):
""" Return the growth rate of fox and rabbit populations. """
return array([ a*X[0] - b*X[0]*X[1] ,
-c*X[1] + d*b*X[0]*X[1] ])
t = np.linspace(0, 15, 1000) # time
X0 = np.array([10, 5]) # initials conditions: 10 rabbits and 5 foxes
X, infodict = integrate.odeint(dX_dt, X0, t, full_output=True)
I would like to create a slider for parameters `a` and `c`, as in the
[slider_demo of
matplotlib](http://matplotlib.org/examples/widgets/slider_demo.html), or any
other tool. The plot should display a certain window of time that always spans
`[t_current - delta_t ,t_current]`. And so I will be able to explore the
parameters space continuously by changing the sliders of the parameters.
Any idea how to do it?
Answer: You have all the pieces, basically just change the update method in the widget
[example](http://matplotlib.org/examples/widgets/slider_demo.html) to
recalculate the integral of dX_dt using the new value based on the sliders and
then use this to set the y line values. The code would look like:
import numpy as np
from scipy import integrate
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons
b = 0.1
d = 0.75
a=1
c=1.5
def dX_dt(X, t=0, a=1, c=1.5):
""" Return the growth rate of fox and rabbit populations. """
return np.array([ a*X[0] - b*X[0]*X[1] ,
-c*X[1] + d*b*X[0]*X[1] ])
t = np.linspace(0, 15, 1000) # time
X0 = np.array([10, 5]) # initials conditions: 10 rabbits and 5 foxes
fig, ax = plt.subplots()
plt.subplots_adjust(left=0.25, bottom=0.25)
l1, l2 = plt.plot(t, integrate.odeint(dX_dt, X0, t, (a, c)))
axcolor = 'black'
ax_a = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
ax_c = plt.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor)
sa = Slider(ax_a, 'a', 0.1, 10.0, valinit=1)
sc = Slider(ax_c, 'c', 0.1, 10.0, valinit=1.5)
def update(val):
a = sa.val
c = sc.val
x = integrate.odeint(dX_dt, X0, t, (a, c))
l1.set_ydata(x[:,0])
l2.set_ydata(x[:,1])
fig.canvas.draw_idle()
sa.on_changed(update)
sc.on_changed(update)
plt.show()
|
Using Python Flask-restful with mod-wsgi
Question: I am trying to use mod-wsgi with Apache 2.2
I have the following directory structure:
scheduling-algos
-lib
-common
-config
-config.json
resources
-Optimization.py
optimization.wsgi
optimization_app.py
My `optimization_app.py` is the following:
from flask import Flask
from flask_restful import Api
from resources.Optimization import OptimizationAlgo
def optimizeInstances():
optimization_app = Flask(__name__)
api = Api(optimization_app)
api.add_resource(OptimizationAlgo, '/instances')
if __name__ == '__main__':
optimizeInstances()
optimization_app.run(host='0.0.0.0', debug=True)
My `Optimization.py` code looks like the following:
class OptimizationAlgo(Resource):
def post(self):
return "success"
When I make a `POST` request to the url `http://<host>:5000/instances`, it
works just as expected. I want make this work using `WSGI`. I have `mod-wsgi`
installed with Apache 2.2.
My `optimization.wsgi` file looks like the following
import sys
sys.path.insert(0, '<path to app>')
from optimization_app import optimizeInstances as application
I get the following error: `TypeError: optimizeInstances() takes no arguments
(2 given)` . Apparently this is not the correct way to use WSGI. What is the
correct way to use WSGI? Apparently, this is not the correct way to use
`WSGI`.
Answer: As I told you in your other question, you should perhaps go back and read the
Flask [documentation](http://flask.pocoo.org) again. That way you will learn
and understand properly. By ignoring advice and expecting others to tell you,
it only annoys people and they will stop helping you. Would suggest you take
heed of that rather than leave a trail of separate questions hoping someone
will solve your problems for you.
That said, I can't see how the code you give can even work with the Flask
development server as you claim. The problem is that `optimization_app =
Flask(__name__)` is setting a local variable within function scope. It isn't
setting a global variable. As a result the call of
`optimization_app.run(host='0.0.0.0', debug=True)` should fail with a
`LookupError` as it will not see a variable called `optimization_app`. Not
even sure why you are bothering with the function.
If you go look at the Flask documentation, the pattern it would likely use is:
# optimisation.wsgi
import sys
sys.path.insert(0, '<path to app>')
# We alias 'app' to 'application' here as mod_wsgi expects it to be called 'application'.
from optimization_app import app as application
# optimization_app.py
from flask import Flask
from flask_restful import Api
from resources.Optimization import OptimizationAlgo
app = Flask(__name__)
api = Api(app)
api.add_resource(OptimizationAlgo, '/instances')
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)
|
Python only find string with specific length numbers
Question: I am trying to create a script that search for strings of numbers with only
specific length numbers from an output.txt.
Example output.txt:
12345678
77777
12123887
When I use:
import re
f = open('output.txt', 'r')
strings = re.findall(r'(\d{5,5})', f.read())
print strings
I would like to get only output: `77777` instead of:
12345
77777
12123
Answer: Use `^(\d{5})$` and `re.MULTILINE`
>>> import re
>>> data = '''12345678
77777
12123887'''
>>> p = re.compile(r'^(\d{5})$', re.MULTILINE)
>>> re.findall(p, data)
['77777']
>>>
|
Cosine similarity using TFIDF
Question: There are several questions on SO and the web describing how to take the
`cosine similarity` between two strings, and even between two strings with
TFIDF as weights. But the output of a function like scikit's
[`linear_kernel`](http://scikit-
learn.org/stable/modules/generated/sklearn.metrics.pairwise.linear_kernel.html)
confuses me a little.
Consider the following code:
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
a = ['hello world', 'my name is', 'what is your name?']
b = ['my name is', 'hello world', 'my name is what?']
df = pd.DataFrame(data={'a':a, 'b':b})
df['ab'] = df.apply(lambda x : x['a'] + ' ' + x['b'], axis=1)
print(df.head())
a b ab
0 hello world my name is hello world my name is
1 my name is hello world my name is hello world
2 what is your name? my name is what? what is your name? my name is what?
**Question** : I'd like to have a column that is the cosine similarity between
the strings in `a` and the strings in `b`.
**What I tried** :
I trained a TFIDF classifier on `ab`, so as to include all the words:
clf = TfidfVectorizer(ngram_range=(1, 1), stop_words='english')
clf.fit(df['ab'])
I then got the sparse TFIDF matrix of both `a` and `b` columns:
tfidf_a = clf.transform(df['a'])
tfidf_b = clf.transform(df['b'])
Now, if I use scikit's `linear_kernel`, which is what others recommended, I
get back a Gram matrix of (nfeatures,nfeatures), as mentioned in their docs.
from sklearn.metrics.pairwise import linear_kernel
linear_kernel(tfidf_a,tfidf_b)
array([[ 0., 1., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]])
But what I need is a simple vector, where the first element is the cosin_sim
between the first row of `a` and the first row of `b`, the second element is
the cos_sim(a[1],b[1]), and so forth.
Using python3, scikit-learn 0.17.
Answer: I think your example is falling down a little bit because your TfidfVectorizer
is filtering out the majority of your words because you have the stop_words =
'english' parameter (you've included almost all stop words in the example).
I've removed that and made your matrices dense so we can see what's happening.
What if you did something like this?
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from scipy import spatial
a = ['hello world', 'my name is', 'what is your name?']
b = ['my name is', 'hello world', 'my name is what?']
df = pd.DataFrame(data={'a':a, 'b':b})
df['ab'] = df.apply(lambda x : x['a'] + ' ' + x['b'], axis=1)
clf = TfidfVectorizer(ngram_range=(1, 1))
clf.fit(df['ab'])
tfidf_a = clf.transform(df['a']).todense()
tfidf_b = clf.transform(df['b']).todense()
row_similarities = [1 - spatial.distance.cosine(tfidf_a[x],tfidf_b[x]) for x in range(len(tfidf_a)) ]
row_similarities
[0.0, 0.0, 0.72252389079716417]
This shows the distance between each row. I'm not fully on board with how
you're building the full corpus, but the example isn't optimized at all, so
I'll leave that for now. Hope this helps.
|
How to get a method called (decorator?) after every object method
Question: This is a question similar to [How to call a method implicitly after every
method call?](http://stackoverflow.com/questions/33075283/how-to-call-a-
method-implicitly-after-every-method-call) but for python
Say I have a crawler class with some attributes (e.g. self.db) with a
`crawl_1(self, *args, **kwargs)` and another one `save_to_db(self, *args,
**kwargs)` which saves the crawling results to a database (`self.db)`.
I want somehow to have `save_to_db` run after every `crawl_1, crawl_2, etc.`
call. I've tried making this as a "global" util decorator but I don't like the
result since it involves passing around `self` as an argument.
Answer: If you want to implicitly run a method after all of your `crawl_*` methods,
the simplest solution may be to set up a metaclass that will programatically
wrap the methods for you. Start with this, a simple wrapper function:
import functools
def wrapit(func):
@functools.wraps(func)
def _(self, *args, **kwargs):
func(self, *args, **kwargs)
self.save_to_db()
return _
That's a basic decorator that wraps `func`, calling `self.save_to_db()` after
calling `func`. Now, we set up a metaclass that will programatically apply
this to specific methods:
class Wrapper (type):
def __new__(mcls, name, bases, nmspc):
for attrname, attrval in nmspc.items():
if callable(attrval) and attrname.startswith('crawl_'):
nmspc[attrname] = wrapit(attrval)
return super(Wrapper, mcls).__new__(mcls, name, bases, nmspc)
This will iterate over the methods in the wrapped class, looking for method
names that start with `crawl_` and wrapping them with our decorator function.
Finally, the wrapped class itself, which declares `Wrapper` as a metaclass:
class Wrapped (object):
__metaclass__ = Wrapper
def crawl_1(self):
print 'this is crawl 1'
def crawl_2(self):
print 'this is crawl 2'
def this_is_not_wrapped(self):
print 'this is not wrapped'
def save_to_db(self):
print 'saving to database'
Given the above, we get the following behavior:
>>> W = Wrapped()
>>> W.crawl_1()
this is crawl 1
saving to database
>>> W.crawl_2()
this is crawl 2
saving to database
>>> W.this_is_not_wrapped()
this is not wrapped
>>>
You can see the our `save_to_database` method is being called after each of
`crawl_1` and `crawl_2` (but not after `this_is_not_wrapped`).
The above works in Python 2. In Python 3, replase this:
class Wrapped (object):
__metaclass__ = Wrapper
With:
class Wrapped (object, metaclass=Wrapper):
|
Python matplotlib animation randomly jumping to initial position
Question: I'm adapting code from [this matplotlib
example](http://matplotlib.org/1.4.1/examples/animation/simple_3danim.html)
but am finding that within my animation each particle seems to jump back to
it's initial position, but not all at the same time? I can't figure out why
this would be the case (am I inputting the data correctly?).
I have a program simulating test particles orbiting a central mass. The
program outputs data in blocks separated by a new line. Each block consists of
a new line for each particle, and each line has 3 numbers, 1 for each
dimension.
Here's the code in question:
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3
import matplotlib.animation as animation
import csv
#read in data
with open('tmpfile', 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter='\t')
data = np.array([[float(field) for field in row]
for row in filter(lambda x: x != [], reader)])
print(data.shape)
data = data.reshape((21, -1, 3)).swapaxes(1,2)
print(data.shape)
def update_points(num, dataPoints, points) :
for point, data in zip(points, dataPoints) :
point.set_data(data[0:2, num-1:num])
point.set_3d_properties(data[2,num-1:num])
return points
#prepare plot
fig = plt.figure()
ax = p3.Axes3D(fig)
points = [ax.plot(dat[0, 0:1], dat[1, 0:1], dat[2, 0:1], c='b', marker='o')[0] for dat in data]
# Set the axes properties
ax.view_init(90, 90)
ax.set_xlim3d([-8.0, 8.0])
ax.set_xlabel('X')
ax.set_ylim3d([-8.0, 8.0])
ax.set_ylabel('Y')
ax.set_zlim3d([-1.0, 1.0])
ax.set_zlabel('Z')
#Create the Animation object
ani = animation.FuncAnimation(fig, update_points, 101, fargs=(data, points),
interval=500, blit=False)
plt.show()
And here's an example of the output file format (for 21 particles and 2 time
steps, [link to full file with all 100
timesteps](https://www.dropbox.com/s/buv2ocqjblq7zty/tmpfile?dl=0)):
0 0 0
1.954 -0.4259 0
0.7562 -1.852 0
2.308 1.917 0
-1.032 -2.817 0
2.001 2.235 0
3.813 1.208 0
-1.888 3.526 0
2.298 -3.274 0
2.556 3.077 0
-4.664 1.802 0
2.719 4.196 0
-3.991 3.012 0
-4.018 2.976 0
4.398 -2.379 0
3.924 -4.539 0
-1.954 -5.673 0
-2.751 5.332 0
3.87 4.585 0
5.725 -1.796 0
5.369 -2.678 0
0 0 0
1.956 -0.419 0
0.7627 -1.849 0
2.304 1.922 0
-1.026 -2.819 0
1.996 2.239 0
3.812 1.212 0
-1.892 3.524 0
2.302 -3.271 0
2.553 3.08 0
-4.666 1.798 0
2.715 4.198 0
-3.994 3.008 0
-4.02 2.973 0
4.4 -2.375 0
3.927 -4.536 0
-1.95 -5.674 0
-2.755 5.33 0
3.867 4.588 0
5.726 -1.792 0
5.371 -2.674 0
Thanks in advance.
Answer: Let's consider a smaller example with 2 timesteps and 3 particles:
In [175]: data = np.arange(6*3).reshape(6,3); data
Out[175]:
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]])
If we use `data.reshape(3, -1, 3).swapaxes(1, 2)` then we obtain
In [176]: data.reshape(3, -1, 3).swapaxes(1, 2)
Out[176]:
array([[[ 0, 3],
[ 1, 4],
[ 2, 5]],
[[ 6, 9],
[ 7, 10],
[ 8, 11]],
[[12, 15],
[13, 16],
[14, 17]]])
Notice that the first particle's positions become [0,1,2] and [3,4,5]. But we
want the first particle's positions to be [0,1,2] and [9,10,11].
So instead use
In [177]: data.reshape((-1, 3, 3)).transpose([1, 2, 0])
Out[177]:
array([[[ 0, 9],
[ 1, 10],
[ 2, 11]],
[[ 3, 12],
[ 4, 13],
[ 5, 14]],
[[ 6, 15],
[ 7, 16],
[ 8, 17]]])
* * *
Therefore, change
data = data.reshape((21, -1, 3)).swapaxes(1,2)
to
data = data.reshape((-1, 21, 3)).transpose([1, 2, 0])
|
Extracting selected columns from a datafile using python
Question: I have a data file like this
0.000 1.185e-01 1.185e-01 3.660e-02 2.962e-02 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00
0.001 1.185e-01 1.185e-01 3.660e-02 2.962e-02 -1.534e-02 -1.534e-02 8.000e-31 8.000e-31 0.000e+00
0.002 1.185e-01 1.185e-01 3.659e-02 2.961e-02 -1.541e-02 -1.541e-02 -6.163e-01 -6.163e-01 -4.284e-05
0.003 1.186e-01 1.186e-01 3.657e-02 2.959e-02 -1.547e-02 -1.547e-02 -8.000e-31 -8.000e-31 0.000e+00
0.004 1.186e-01 1.186e-01 3.657e-02 2.959e-02 -2.005e-32 -2.005e-32 -8.000e-31 -8.000e-31 0.000e+00
0.005 1.186e-01 1.186e-01 3.657e-02 2.959e-02 -2.005e-32 -2.005e-32 -8.000e-31 -8.000e-31 0.000e+00
0.006 1.187e-01 1.186e-01 3.657e-02 2.959e-02 -2.005e-32 -2.005e-32 -8.000e-31 -8.000e-31 0.000e+00
0.007 1.187e-01 1.187e-01 3.657e-02 2.959e-02 -2.005e-32 -2.005e-32 -8.000e-31 -8.000e-31 0.000e+00
0.008 1.188e-01 1.187e-01 3.657e-02 2.959e-02 -2.005e-32 -2.005e-32 -8.000e-31 -8.000e-31 0.000e+00
0.009 1.188e-01 1.187e-01 3.657e-02 2.959e-02 -2.005e-32 -2.005e-32 -8.000e-31 -8.000e-31 0.000e+00
I want to copy only selected columns from this file to another file. Suppose I
copy the 1st, 2nd and 6th columns to a file, then that file should look like
0.000 1.185e-01 0.000e+00
0.001 1.185e-01 -1.534e-02
0.002 1.185e-01 -1.541e-02
0.003 1.186e-01 -1.547e-02
0.004 1.186e-01 -2.005e-32
0.005 1.186e-01 -2.005e-32
0.006 1.187e-01 -2.005e-32
0.007 1.187e-01 -2.005e-32
0.008 1.188e-01 -2.005e-32
0.009 1.188e-01 -2.005e-32
This is a very large formatted text file which was initially written like this
f=open('myMD.dat','w')
s='%8.3e %8.3e %8.3e %8.3e %8.3e %8.3e %8.3e %8.3e %8.3e\t\t'%(xpos1[i],ypos1[i],xvel1[i],yvel1[i],xacc1[i],yacc1[i],xforc[i],yforc[i],potn[i])
f.write(s)
f.close()
I am programming in python. How can I do this?
Answer: This will read a given input file and select rows using a given comma
separated list of rows:
import sys
input_name = sys.argv[1]
column_list = [(int(x) - 1) for x in sys.argv[2].split(',')]
with open(input_name) as input_file:
for line in input_file:
row = line.split()
for col in column_list:
print row[col],
print ""
It reads and prints one line at a time, which means it should be able to
handle an arbitrarily large input file. Using your example data as
`input.txt`, I ran it like this:
python selected_columns.py input.txt 1,2,6
It produced the following output (ellipsis used to show lines removed for
brevity):
0.000 1.185e-01 0.000e+00
0.001 1.185e-01 -1.534e-02
...
0.009 1.188e-01 -2.005e-32
You can save the output to a file using redirection:
python selected_columns.py input.txt 1,2,6 > output.txt
|
How to schedule a periodic task that is immune to system time change using Python
Question: I am using python's sched module to run a task periodically, and I think I
have come across a bug.
I find that it relies on the time of the system on which the python script is
run. For example, let's say that I want to run a task every 5 seconds. If I
forward the system time, the scheduled task will run as expected. However, if
I rewind the system time to, say 1 day, then the next scheduled task will run
in 5 seconds + 1 day.
If you run the script below and then change your system time by a few days
back, then you can reproduce the issue. The problem can be reproduced on Linux
and Windows.
import sched
import time
import threading
period = 5
scheduler = sched.scheduler(time.time, time.sleep)
def check_scheduler():
print time.time()
scheduler.enter(period, 1, check_scheduler, ())
if __name__ == '__main__':
print time.time()
scheduler.enter(period, 1, check_scheduler, ())
thread = threading.Thread(target=scheduler.run)
thread.start()
thread.join()
exit(0)
Anyone has any python solution around this problem?
Answer: From [the sched
documentation](https://docs.python.org/2/library/sched.html#module-sched):
> class sched.scheduler(timefunc, delayfunc)
>
> The scheduler class defines a generic interface to scheduling events. It
> needs two functions to actually deal with the “outside world” — timefunc
> should be callable without arguments, and return a number (the “time”, in
> any units whatsoever). The delayfunc function should be callable with one
> argument, compatible with the output of timefunc, and should delay that many
> time units. delayfunc will also be called with the argument 0 after each
> event is run to allow other threads an opportunity to run in multi-threaded
> applications.
The problem you have is that your code uses `time.time()` as `timefunc`, whose
return value (when called without arguments) is the current system time and is
thus affected by re-winding the system clock.
To make your code immune to system time changes you'd need to provide a
`timefunc` which doesn't depend on the system time, start/current timestamps,
etc.
You can write your own function, for example one returning the number of
seconds since your process is started, which you'd have to **actually count**
in your code (i.e. don't `compute it` based on timestamp deltas). The
`time.clock()` function _might_ help, if it's based on CPU time counters, but
I'm not sure if that's true or not.
|
how to find right version of bson from pip for pymongo/mongoengine
Question: I am working on a (python 2.7) flask-mongoengine application which uses bson's
ObjectId. The project requires bson in one or another way. I don't have root
access on the host i'm trying to deploy the application and pip install bson
fails:
-bash-4.1$ pip install bson
Collecting bson
Using cached bson-1.1.0.tar.gz
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/tmp/pip-build-BBOawV/bson/setup.py", line 24, in <module>
import bson
File "bson/__init__.py", line 66, in <module>
from . import codec
File "bson/codec.py", line 28, in <module>
from .objects import *
File "bson/objects.py", line 36
class BSONObject(object, metaclass=ABCMeta):
^
SyntaxError: invalid syntax
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-BBOawV/bson/
On the other hand, <https://api.mongodb.org/python/current/installation.html>
states that i shouldn't use this version of bson and rely on pymongo's
implementation. However, on my computer where I have pymongo-3.2.1 installed,
I cannot import pymongo.objectId - so what am I doing wrong and how can I get
bson to work with my setup?
Thank you soo much!
Answer: I had a similar issue.
Just download the tarball from <https://pypi.python.org/pypi/bson/0.4.3> and
do a manual install:
python setup.py install
|
How to save information in json file without deleting previous information python
Question: I am making an app using python and kivy that allows the user to make a new
entry for their glucose readings. Right now it saves into the json file but
another new entry deletes the previous data. How can I make it so that each
entry saves separately so that I can access the information for the user's
history?
**.py file**
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.popup import Popup
from kivy.uix.button import Button
from kivy.graphics import Color, Rectangle
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.image import AsyncImage
from kivy.uix.label import Label
from kivy.properties import StringProperty, ListProperty
from kivy.uix.behaviors import ButtonBehavior
from kivy.uix.textinput import TextInput
from kivy.network.urlrequest import UrlRequest
from kivy.storage.jsonstore import JsonStore
from os.path import join
from os.path import exists
from kivy.compat import iteritems
from kivy.storage import AbstractStore
from json import loads, dump
from kivy.config import Config
import os
import errno
class Phone(FloatLayout):
def __init__(self, **kwargs):
# make sure we aren't overriding any important functionality
super(Phone, self).__init__(**kwargs)
with self.canvas.before:
Color(0, 1, 0, 1) # green; colors range from 0-1 instead of 0-255
self.rect = Rectangle(size=self.size, pos=self.pos)
self.bind(size=self._update_rect, pos=self._update_rect)
if not os.path.exists('hello.json'):
with open('hello.json', 'wt') as inFile:
inFile.write("")
else:
with open('hello.json') as inFile:
try:
data = Phone.load(self)
except KeyError:
data = []
def _update_rect(self, instance, value):
self.rect.pos = instance.pos
self.rect.size = instance.size
def product(self, instance):
self.result.text = str(float(self.w.text) * 703/ (float(self.h.text) * float(self.h.text)))
def save(self):
store = JsonStore('hello.json')
name = self.n.text
gender = self.g.text
dtype = self.t.text
height = self.h.text
weight = self.w.text
bmi = self.result.text
medications = self.m.text
insulin = self.ti.text
store.put('profile', name=name, gender=gender, dtype=dtype, height=height, weight=weight, bmi=bmi, medications=medications, insulin=insulin)
def save_entry(self):
time = self.gt.text
glucose = self.gr.text
carbs = self.c.text
medications_taken = self.mt.text
store.put('entry', time=time, glucose=glucose, carbs=carbs, medications_taken=medications_taken)
def load(self):
store = JsonStore('hello.json')
profile = store.get('profile')
self.n.text = profile['name']
self.g.text = profile['gender']
self.t.text = profile['dtype']
self.h.text = profile['height']
self.w.text = profile['weight']
self.result.text = profile['bmi']
self.m.text = profile['medications']
self.ti.text = profile['insulin']
presentation = Builder.load_file("main.kv")
class PhoneApp(App):
def build(self):
store = JsonStore('hello.json')
return Phone()
if __name__ == '__main__':
PhoneApp().run()
Answer: Use some small json database like [this](https://pypi.python.org/pypi/tinydb)
to keep it clean. Example usage:
from tinydb import TinyDB, Query
db = TinyDB('./db.json')
User = Query()
db.insert({'name': 'John', 'age': 22})
result = db.search(User.name == 'John')
print result
|
Python Requests Not Returning Same Header as Browser Request/cURL
Question: I'm looking to write a script that can automatically download `.zip` files
from the [Bureau of Transportation Statistics Carrier
Website](http://www.transtats.bts.gov/DL_SelectFields.asp?Table_ID=293), but
I'm having trouble getting the same response headers as I can see in Chrome
when I download the zip file. I'm looking to get a response header that looks
like this:
HTTP/1.1 302 Object moved
Cache-Control: private
Content-Length: 183
Content-Type: text/html
Location: http://tsdata.bts.gov/103627300_T_T100_SEGMENT_ALL_CARRIER.zip
Server: Microsoft-IIS/8.5
X-Powered-By: ASP.NET
Date: Thu, 21 Apr 2016 15:56:31 GMT
However, when calling `requests.post(url, data=params, headers=headers)` with
the same information that I can see in the Chrome network inspector I am
getting the following response:
>>> res.headers
{'Cache-Control': 'private', 'Content-Length': '262', 'Content-Type': 'text/html', 'X-Powered-By': 'ASP.NET', 'Date': 'Thu, 21 Apr 2016 20:16:26 GMT', 'Server': 'Microsoft-IIS/8.5'}
It's got pretty much everything except it's missing the `Location` key that I
need in order to download the `.zip` file with all of the data I want.
**Also** the `Content-Length` value is different, but I'm not sure if that's
an issue.
I think that my issue has something to do with the fact that when you click
"Download" on the page it actually sends two requests that I can see in the
Chrome network console. The first request is a `POST` request that yields an
`HTTP` response of 302 and then has the `Location` in the response header. The
second request is a `GET` request to the url specified in the `Location` value
of the response header.
Should I really be sending two requests here? Why am I not getting the same
response headers using `requests` as I do in the browser? FWIW I used `curl -X
POST -d /*my data*/` and got back this in my terminal:
<head><title>Object moved</title></head>
<body><h1>Object Moved</h1>This object may be found <a HREF="http://tsdata.bts.gov/103714760_T_T100_SEGMENT_ALL_CARRIER.zip">here</a>.</body>
Really appreciate any help!
Answer: I was able to download the zip file that I was looking for by using _almost_
all of the headers that I could see in the Google Chrome web console. My
headers looked like this:
{'Connection': 'keep-alive', 'Cache-Control': 'max-age=0', 'Referer': 'http://www.transtats.bts.gov/DL_SelectFields.asp?Table_ID=293', 'Origin': 'http://www.transtats.bts.gov', 'Upgrade-Insecure-Requests': 1, 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36', 'Cookie': 'ASPSESSIONIDQADBBRTA=CMKGLHMDDJIECMNGLMDPOKHC', 'Accept-Language': 'en-US,en;q=0.8', 'Accept-Encoding': 'gzip, deflate', 'Content-Type': 'application/x-www-form-urlencoded'}
And then I just wrote:
res = requests.post(url, data=form_data, headers=headers)
where `form_data` was copied from the "Form Data" section of the Chrome
console. Once I got that request, I used the `zipfile` and `io` modules to
parse the content of the response stored in `res`. Like this:
import zipfile, io
zipfile.ZipFile(io.BytesIO(res.content))
and then the file was in the directory where I ran the Python code.
Thanks to the users who answered on [this
thread](http://stackoverflow.com/questions/9419162/python-download-returned-
zip-file-from-url).
|
saving multiple dicts and variables in disk
Question: My code typically runs for several days and spews out intermediate results as
Python dicts and float variables. I cannot afford to append all intermediate
values to a Python list and save all outputs to a physical file using pickle
etc in one go after the run. This is because, in case there is interruption, I
might loose all data I have collected so far.
So I have to dump (and append) multiple dicts and other variables
periodically. What is the best way to do this ? I've looked at JSON (but not
sure how to do store (and later read) multiple JSON objects from a single
file. Can I append my data to a pickle file ? Saving these data in a simple
text file or csv file would be my last resort.
Answer: Use [`json`](https://docs.python.org/2/library/json.html). This is a good
variant for conservation with the ability to edit the file:
import json
list_of_dict = [
{'a': 1},
{'b': 2}
]
with open('filename.json', 'w') as f:
json.dump(list_of_dict, f, sort_keys=True, indent=4)
|
searching for a word in a file using command argument? in python3, popping up no answers
Question: trying to write a program that searches the dictionary file for words which
start with the first command line argument, which is their stem but I'm
getting nothing.
here's my code, what am I doing wrong?
import sys
import os
stem = str(sys.argv[1:])
searchline = open("american-english-insane")
for line in searchline:
if line.startswith(stem):
print(word)
On the other hand, this works and spits out hello, helloes, helloeing, etc...
but it's not passed as a command line argument.
import sys
import os
stem = sys.argv[1:]
searchline = open("american-english-insane")
for line in searchline:
if line.startswith('hello'):
print(line)
Answer: Use a below snippet, which returns a string object
stem = sys.argv[1]
|
How to use boto3 (or other Python) to list the contents of a _RequesterPays_ S3 bucket?
Question: You can download a file via boto3 from a RequesterPays S3 bucket, as follows:
s3_client.download_file('aws-naip', 'md/2013/1m/rgbir/38077/{}'.format(filename), full_path, {'RequestPayer':'requester'})
What I can't figure out is how to list the objects in the bucket... I get an
authentication error when I try and call objects.all() on the bucket.
How can I use boto3 to enumerate the contents of a RequesterPays bucket?
**Please note this is a particular kind of bucket where the requester pays the
S3 charges.**
Answer: From
[boto3](http://boto3.readthedocs.org/en/latest/reference/services/s3.html#S3.Client.list_objects),
we can see that there is a `#S3.Client.list_objects` method. This can be used
to enumerate objects:
import boto3
s3_client = boto3.client('s3')
resp = s3_client.list_objects(Bucket='RequesterPays')
# print names of all objects
for obj in resp['Contents']:
print 'Object Name: %s' % obj['Key']
Output:
Object Name: pic.gif
Object Name: doc.txt
Object Name: page.html
If you are getting a 401 then make sure that IAM user calling the API has
`s3:GetObject` permissions on the bucket.
|
Python - control application started by the different user in Windows
Question: I am making application that controls a browser with SendKeys. But as SendKeys
get the full control over the keyboard, I want to run this app under the
different user. This way I will be working, the application will do what it
have to do, and we will not make problems for each other).
The simplest code is
import time
import SendKeys
time.sleep(10)
SendKeys.SendKeys('hello')
I run it, focus on the field where I want to insert my text "hello", and wait.
If I don't change the user, all is done as expected. But when I run it, change
the user and return after 10 seconds, I see that SendKeys sent nothing to the
program.
How to send keystrokes to the program under the different user?
(I was trying to do the same with pywinauto, but the result was almost the
same - all is good if I don't change the user, and error if I change it. So I
thought that it is much simplier to resolve this problem with only SendKeys).
Answer: Just to summarize our discussion in comments and in the chat. Your wishes are
very wide. I'm just trying to show you some directions to learn.
If you want to use `SendKeys/TypeKeys/ClickInput` methods (working as a real
user), you need to run your automation script in the remote session, not
locally. This is explained in details in my other answer: [SetCursorPos fail
with "the parameter is incorrect" after rdp session
terminated](http://stackoverflow.com/questions/35008138/setcursorpos-fail-
with-the-parameter-is-incorrect-after-rdp-session-terminated).
If you want to run the automation on the same machine silently (in minimized
state), there is an example for dealing with hidden windows: [Python - Control
window with pywinauto while the window is minimized or
hidden](http://stackoverflow.com/questions/32846550/python-control-window-
with-pywinauto-while-the-window-is-minimized-or-hidden). Just minimize the
window and use silent methods (almost all except `ClickInput` and `TypeKeys`).
Feel free to ask more detailed questions about pywinauto and GUI automation.
|
Delete NaNs and Infs in Numpy array
Question: Recently I got a problem when learning Python numpy. Actually I was testing a
self-defined function on a remote server, and this function uses
_numpy.linalg.eig_ :
import numpy
from numpy import *
def myfun(xAr,yAr) #xAr, yAr are Matrices
for i in xrange(xAr.shape[1]):
Mat=xAr.T*yAr*yAr.T*xAr
val,vec=linalg.eig(Mat)
# and so on...
and the test gives error report " line 1088, in eig: Array must not contain
infs or NaNs".
Thus I tried to delete those columns containing NaNs or Infs, and my code is:
def myfun(xAr,yAr)
id1=isfinite(sum(xAr,axis=1))
id2=isfinite(sum(yAr,axis=1))
xAr=xAr[id1&id2]
yAr=yAr[id1&id2]
for i in xrange(xArr.shape[1]):
Mat=xAr.T*yAr*yAr.T*xAr
val,vec=linalg.eig(Mat)
# and so on...
However the same error arose again.
I don't know the exact data values for this testing, as this test is on a
remote server and original data values are forbidden to show. What I know is
the data is a matrix containing NaNs and Infs.
Could anyone give me some suggestions why _isfinite_ fails to work here, or
where I did wrong for deleting these NaNs and Infs?
Answer: Given two arays like this:
In [1]: arr_1
Out[1]:
array([[ 0., nan, 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.],
[ 12., nan, 14., 15.],
[ 16., 17., 18., 19.]])
In [2]: arr_2
Out[2]:
array([[ -0., -1., -2., nan],
[ -4., -5., -6., -7.],
[ -8., -9., -10., -11.],
[-12., -13., -14., -15.],
[-16., -17., -18., -19.]])
You probably want to ignore columns 1 and 3. We can create a mask for that:
In [3]: mask_1 = np.isfinite(arr_1).all(axis=0)
In [4]: mask_1
Out[4]: array([ True, False, True, True], dtype=bool)
In [5]: mask_2 = np.isfinite(arr_2).all(axis=0)
In [6]: mask_2
Out[6]: array([ True, True, True, False], dtype=bool)
Combining these masks leaves us with the right column selection:
In [7]: mask_1 & mask_2
Out[7]: array([ True, False, True, False], dtype=bool)
In [8]: arr_1[:, mask_1 & mask_2]
Out[8]:
array([[ 0., 2.],
[ 4., 6.],
[ 8., 10.],
[ 12., 14.],
[ 16., 18.]])
If we decide to filter out the invalid rows instead, we need to swap axes:
In [9]: mask_1 = np.isfinite(arr_1).all(axis=1)
In [10]: mask_2 = np.isfinite(arr_2).all(axis=1)
In [11]: arr_1[mask_1 & mask_2, :]
Out[11]:
array([[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.],
[ 16., 17., 18., 19.]])
It seems you've messed up slightly with the axes, nothing more.
|
Unable to print logs in default color, when no color is specified explicitly using Colorama
Question: I am trying to get colored logs using colorama and logging module in python.
If I am not giving any color then it should print default terminal color, but
in my logs I am getting color of previously set logs if no color is set
explicitly.
Below is my setup_logging.yml file
import os
import yaml
import logging.config
def setup_logging(
default_path='logging.yml', default_level=logging.INFO, env_key='LOG_CFG'):
path = os.path.join('/etc', 'module', default_path)
value = os.getenv(env_key, None)
if value:
path = value
if os.path.exists(path):
with open(path, 'rt') as f:
config = yaml.load(f.read())
logging.config.dictConfig(config)
else:
logging.basicConfig(level=default_level)
Logging.yml file
version: 1
disable_existing_loggers: True
formatters:
default:
format: "%(asctime)s - %(name)s - %(levelname)s - \n %(message)s"
handlers:
console:
class: logging.StreamHandler
level: INFO
formatter: default
stream: ext://sys.stdout
info_file_handler:
class: logging.handlers.RotatingFileHandler
level: INFO
formatter: default
filename: /var/log/jsnapy/test.log
maxBytes: 10485760 # 10MB
backupCount: 20
encoding: utf8
I have stripped my code for logging functions:
import logging
import colorama
class Test:
def __init__(self):
self.logger = logging.getLogger(__name__)
colorama.init(autoreset=True)
setup_logging.setup_logging()
def testing(self):
self.logger.debug(colorama.Fore.RED + "this is a debugging message")
self.logger.info(colorama.Fore.BLUE+"this is an informational message")
self.logger.warn(colorama.Fore.BLUE+"this is a warning message")
self.logger.error(colorama.Fore.YELLOW + "this is an error message")
self.logger.critical("this is a critical message")
t = Test()
t.testing()
How to get default color in logs when no color is specified explicitly.
Answer: You need to use `init(autoreset=True)` for that, as written in the official
documentation:
> If you find yourself repeatedly sending reset sequences to turn off color
> changes at the end of every print, then init(autoreset=True) will automate
> that:
from colorama import init
init(autoreset=True)
print(Fore.RED + 'some red text')
print('automatically back to default color again')
|
How do I print tables from an SQLite databse in python?
Question: So I have a database of information that I would like to print in a nice table
format, held as an SQLite db file.
The only print statements I have seen print the information in a confusing
manner, not aligning the attributes of different entities, no column headers
etc.
Procedure that creates the table:
def create_table():
c.execute('CREATE TABLE IF NOT EXISTS orders ( ' #CREATES TABLE named 'orders':
'name TEXT, ' #name
'type_ TEXT, ' #type of product
'location STRING, ' #location of product
'amount INTEGER, ' #'weight' of item, g, kg, ml, cl, l, etc.
'wholesale_cost REAL, ' #wholesale cost
'tax REAL, ' #tax %
'sale_pre_tax REAL, ' #sale value before tax
'sale_post_tax REAL, ' #sale value after tax
'quantity REAL, ' #how many sold
'total_sale_pre_tax REAL, ' #total sales before tax
'total_sale_post_tax, ' #total sales after tax
'total_tax REAL, ' #total tax in GBP
'total_wholesale_cost REAL, ' #total wholesale cos
'profit REAL)') #total sale profit
And this is the print procedure:
def read_from_db():
c.execute ('SELECT * FROM orders ')
for row in c.fetchall():
print(row)
When I execute this it prints:
> ('NORI', 'DRY', 'SHELVES', '50G', 3.4, 20.0, 4.42, 5.303999999999999, 3.0,
> 13.26, 15.911999999999999, 2.6519999999999992, 10.2, 3.0600000000000005)
>
> ('CURRY SAUCE', 'DRY', 'SHELVES', '500G', 5.65, 25.0, 7.345000000000001,
> 9.18125, 1.0, 7.345000000000001, 9.18125, 1.8362499999999997, 5.65,
> 1.6950000000000003)
>
> ('SALMON', 'CHILLED', 'FRIDGE', '100G', 1.25, 20.0, 1.625, 1.95, 3.0, 4.875,
> 5.85, 0.9749999999999996, 3.75, 1.125)
>
> ('EDAMAME', 'CHILLED', 'FRIDGE', '100G', 3.0, 19.0, 4.0, 5.0, 3.0, 12.0, 15,
> 3.0, 9.0, 3.0)
Which is the information from my database but is there any way to print this
as a table instead?
Answer: Adding column names to your rows using `row_factory` is [well
documented](https://docs.python.org/3.5/library/sqlite3.html#sqlite3.Connection.row_factory):
import sqlite3
con = sqlite3.Connection('my.db')
con.row_factory = sqlite3.Row
cur = con.cursor()
cur.execute('SELECT * FROM tbl')
for row in cur.fetchall():
# can convert to dict if you want:
print(dict(row))
You could then use `str.rjust` and related functions to print the table, or
use a `csv.DictWriter` with `sys.stdout` as the "file":
import csv
import sys
wtr = csv.DictWriter(sys.stdout, fieldnames=[i[0] for i in cur.description])
wtr.writeheader()
for row in cur.fetchall():
wtr.writerow(dict(row))
|
Error while installing flask framework on ubuntu 15.04
Question: I am trying to install flask framework on my ubuntu 15.04. It is giving me
this error and I am unable to figure it out. It would be great if someone
could help
Error:
pragati@pragati-ubuntu:~/Python-2.7.11$ sudo pip install flask
[sudo] password for pragati:
Downloading/unpacking flask
Downloading Flask-0.10.1.tar.gz (544kB): 544kB downloaded
Cleaning up...
Exception:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 122, in main
status = self.run(options, args)
File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 304, in run
requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle)
File "/usr/lib/python2.7/dist-packages/pip/req.py", line 1230, in prepare_files
req_to_install.run_egg_info()
File "/usr/lib/python2.7/dist-packages/pip/req.py", line 293, in run_egg_info
logger.notify('Running setup.py (path:%s) egg_info for package %s' % (self.setup_py, self.name))
File "/usr/lib/python2.7/dist-packages/pip/req.py", line 266, in setup_py
import setuptools
File "/usr/share/python-wheels/setuptools-18.4-py2.py3-none-any.whl/setuptools/__init__.py", line 12, in <module>
from setuptools.extension import Extension
File "/usr/share/python-wheels/setuptools-18.4-py2.py3-none-any.whl/setuptools/extension.py", line 8, in <module>
File "/usr/share/python-wheels/setuptools-18.4-py2.py3-none-any.whl/setuptools/dist.py", line 21, in <module>
AttributeError: 'module' object has no attribute 'packaging'
Storing debug log for failure in /home/pragati/.pip/pip.log
Answer: You need to uninstall the `distribute` library and reinstall it:
sudo pip uninstall distribute
Then try again.
|
Multi body animation in python returns static picture
Question: Here is a program that I have written to do an animation in `matplotlib`. The
program concerns a system of 18 particles arranged initially in a hexagonal
lattice. The initial configuration is given under the definition of
`simPoints(simData)`.
The system is evolved over time according to the rule `x[i]=x[i]+L/2.0`, in
both x and y direction. Particles going out of the window are brought in
through the other side. These updates are mentioned under the function
`simData()`.
But all I get out of this code is a static picture of the initial
configuration of particles.
from numpy import*
import matplotlib.pyplot as plt
import matplotlib.animation as animation
L=1 # lattice constant = sigma*2**0.5 (Let)
x=zeros(18,float)
y=zeros(18,float)
#~~~~~~~~~~~~~~~~~ ANIMATION ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def simData():
t = 1
while t<=20:
for i in range(18):
x[i]=x[i]+L/2.0
y[i]=y[i]+L/2.0
if x[i]>L*3: # translate back the particle if it goes out of window limit 0 to L*cell
x[i]=x[i]-L*3
elif x[i]<0:
x[i]=L*3-x[i]
if y[i]>L*3: # translate back the particle if it goes out of window limit 0 to L*cell
y[i]=y[i]-L*3
elif y[i]<0:
y[i]=L*3-y[i]
t=t+1
yield x, y
def simPoints(simData):
k=0
for i in range(0,6,1):
for j in range(0,6,1):
if (i+j)%2==0:
x[k]=i*L*.5+.25*L
y[k]=j*L*.5+.25*L
k=k+1
line.set_data(x, y)
return line,
fig = plt.figure()
ax = fig.add_subplot(111)
line, = ax.plot(x, y,'bo', ms=8)
ax.set_ylim(0, L*3)
ax.set_xlim(0, L*3)
ani = animation.FuncAnimation(fig, simPoints, simData, blit=False, interval=100)
plt.show()
How can I animate the lattice? I have a feeling that the argument
`interval=100` is not used wisely.
Answer: I've made some minor changes in Your code, as You can see below. It's
animating now, however the `simPoints()` is commented out. The major issue is
that if You initialize the points like that, after each step they end up in
the same places. Dots move, but another dots take their places, so it looks
like the plot isn't moving. You may want to change the `simData()` function,
for example make the changes more subtle or random, to avoid that case.
from numpy import*
import matplotlib.pyplot as plt
import matplotlib.animation as animation
L=1 # lattice constant = sigma*2**0.5 (Let)
x=array([0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,0.1,0.11,0.12,0.13,0.14,0.15,0.16,0.17,0.18])
#x=zeros(18,float)
y=zeros(18,float)
#~~~~~~~~~~~~~~~~~ ANIMATION ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def simData():
t = 1
while t<=20:
for i in range(18):
x[i]=x[i]+L/2.0
y[i]=y[i]+L/2.0
if x[i]>L*3: # translate back the particle if it goes out of window limit 0 to L*cell
x[i]=x[i]-L*3
elif x[i]<0:
x[i]=L*3-x[i]
if y[i]>L*3: # translate back the particle if it goes out of window limit 0 to L*cell
y[i]=y[i]-L*3
elif y[i]<0:
y[i]=L*3-y[i]
t=t+1
def simPoints():
k=0
for i in range(0,6,1):
for j in range(0,6,1):
if (i+j)%2==0:
x[k]=i*L*.5+.25*L
y[k]=j*L*.5+.25*L
k=k+1
fig = plt.figure()
ax = plt.axes()
#simPoints()
line, = ax.plot(x, y,'bo', ms=8)
ax.set_ylim(0, L*3)
ax.set_xlim(0, L*3)
def animate(i):
simData()
print x
line.set_data(x, y)
return line,
ani = animation.FuncAnimation(fig, animate, blit=False, interval=100, frames=200)
plt.show()
|
How do I set axes to add text outside a plot?
Question: (Using python3.4)
This is the code I'm using to plot. I'm trying to add additional text which
can help explain what this plot is about.
import matplotlib.pyplot as plt
import numpy as np
somecode.....
somecode.....
xv=np.array(x1)
yv=np.array(y1)
txt='''
Text to be printed outside the plot
Text to be printed outside the plot
Text to be printed outside the plot
Text to be printed outside the plot
Text to be printed outside the plot
'''
plt.figure(1)
plt.scatter(yv,zv, label="Cap vs Percentage Diff", color="m")
plt.xlabel('Latest Cap in FF')
plt.ylabel('Percentage Diff')
plt.title('Variable Cap')
plt.grid(True)
plt.legend()
plt.text(0.95, 0.95, txt)
I used plt.text to print the text 0.95 below the X-axis the and 0.95 away from
Y axis. But matplotlib is picking the co-ordinates relative to the graph.
This issue is reported on couple of other threads and most of the answers are
explained using plt.text format.
Is there a way to print text beyond the axis?
As a work around I'm currently adding this information to plt.xlabel so that
it can be printed under the x-axis label. But, I'd like to know the
possibilities to add text outside the plot by not specifying the co-ordinates.
Reason I don't want to use/Specify X, Y co-ordinates is, XY coordinates can be
negative values in the data I'm reading in.
I tried to understand the syntax and usage from documentation but it is far
beyond my expertise as I started using python fairly couple of weeks ago.
Appreciate if any one can explain/tell how to use text and figtext to add data
outside the plot.
And does both text and figtext need axes info?
Current plot displays the image without the text I want to add outside the
plot
[](http://i.stack.imgur.com/fSBFm.png)
Required plot style: I'd like to the stddev, avg, min and max under the
x-label of subplot:
[](http://i.stack.imgur.com/0g2iK.png)
Thanks
Edit 1: Adding original code.
import matplotlib
import sys
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import os
x1=[1, 2, 3, 4]
y1=[5, 6, 7, 8]
z1=[9, 10 ,11, 12]
xv=np.array(x1)
yv=np.array(y1)
zv=np.array(z1)
#Find Max, Min, Avg and StdDev for the delta(C) i.e. zv numpy array
MaxCapDiff =str (np.amax(zv))
MinCapDiff =str (np.amin(zv))
AvgOfCapDiff =str (np.average(zv))
StdDevOfCapDiff =str (np.std(zv))
print ('Max Cap Diff in Percent:'+MaxCapDiff) print ('Min Cap Diff in Percent:'+MinCapDiff) print ('Avg of Cap Difference :'+AvgOfCapDiff)
print ('STD DEV of Cap Diff :'+StdDevOfCapDiff)
plt.figure(1)
plt.subplot(211)
plt.scatter(xv,yv, label="Cap vs Cap")
plt.xlabel('Golden Cap in (FF)')
plt.ylabel('Latest Cap in (FF)')
plt.title('Cap Comparison')
plt.legend()
plt.subplot(212)
plt.scatter(yv,zv, label="Cap vs Percentage Diff", color="m")
plt.xlabel('Latest cap in (FF)') plt.ylabel('Percentage Diff')
plt.title('Variable Cap')
plt.legend()
plt.tight_layout()
plt.savefig('plot.jpg')
plt.show()
Answer: The function you want to use is annotate, and the [documentation can be found
here](http://matplotlib.org/users/annotations_intro.html.).
I can't reproduce your plots with the code above but you should be able to use
the code below. The key here is to set `annotation_clip` to `False` in order
to alow the text to be dispayed outside of the axes
fig, ax = plt.subplots()
plt.scatter(yv,zv, label="Cap vs Percentage Diff", color="m")
plt.xlabel('Latest Cap in FF')
plt.ylabel('Percentage Diff')
plt.title('Variable Cap')
plt.grid(True)
plt.legend()
##insert the line below:
ax.annotate('Insert text here',xy=(0,0),xytext=(x1,y1), annotation_clip=False)
plt.show()
Note that you will need to change the values of `x1` and `y1` in the `xytext`
to the position that you would like the text to be. This might require some
trial and error to get it exactly right.
|
How to make an equivalent to Fortran's 'access=stream' in python
Question: Let's say i'm making a loop, and after each iteration, y want to extend some
array.
iter 1 ------------> iter 2 --------------> iter 3-------------->....
shape=[2,4]---->shape=[2,12]----->shape=[2,36]---->....
in fortran i used to do this by appending the new numbers to a binary file
with:
OPEN(2,file='array.in',form='unformatted',status='unknown',access='stream')
write(2) newarray
so this would extend the old array with new values at the end.
i wish to do the same in python. This is my attempt so far:
import numpy as np
#write 2x2 array to binfile
bintest=open('binfile.in','wb')
np.ndarray.tofile(np.array([[1.0,2.0],[3.0,4.0]]),'binfile.in')
bintest.close()
#read array from binfile
artest=np.fromfile('binfile.in',dtype=np.float64).reshape(2,2)
But i can't get it to extend the array. Lets say.. by appeding another
[[5.0,5.0],[5.0,5.0]] at the end,
#append new values.
np.ndarray.tofile(np.array([[5.0,5.0],[5.0,5.0]]),'binfile.in')
to make it [[1.0,2.0,5.0,5.0],[3.0,4.0,5.0,5.0]] after the reading. How can i
do this?
The other problem i have, is that i would like to be able to make this without
knowing the shape of the final array (i know it would be 2 x n ). But this is
not so important.
edit: the use of 'access=stream' is only to skip having to read format headers
and tails.
Answer: This does the trick:
import numpy as np
#write
bintest=open('binfile.in','ab')
a=np.array([[1.0,2.0],[3.0,2.0]])
a.tofile(bintest)
bintest.close()
#read
array=np.fromfile('binfile.in',dtype=np.float64)
this way, each time its run, it appends the new array to the end of the file.
|
What is the fastest way to check if a number is in specific range in python?
Question: I have 5 ranges:
1-50 ---> "range1"
51-100 ---> "range2"
101-150 ---> "range3"
151-200 ---> "range4"
201-250 ---> "range5"
Ranges do not overlap, each range has lower and upper bound, next range starts
where the previous one ends. I decide the range lengths. they might not be
equal in size.
I have a variable that shows a number, for example
x = 153
If x is between 1 and 50 then it should return "range1", if between 51 and 100
then "range2", and so on. What is the fastest way of doing it in python,
considering there may be much more than 5 ranges, and the number is large?
Answer: Because your ranges are strictly adjacent and in increasing order, you can use
bisection:
from bisect import bisect
ranges = [1, 51, 101, 151, 201]
if 0 < x <= 250:
print('range{}'.format(bisect(ranges, x))
else:
print('Out of bounds')
Bisection takes O(logN) steps to find the matching range out of N
possibilities.
|
CherryPy and CORS
Question: I have an nginx server set up where I would like to set up a service that
receives a string and returns a result. I plan to use Python to do the
processing, with CherryPy as an interface. I've tested the CherryPy part, and
know it receives properly. When I try to connect to the CherryPy service with
a web page, I get CORS errors. How can I get them to communicate?
Here's the Python Code:
import cherrypy
import random
import urllib
class DataView(object):
exposed = True
@cherrypy.tools.accept(media='application/json')
def GET(self):
rawData = cherrypy.request.body.read(int(cherrypy.request.headers['Content-Length']))
b = json.loads(rawData)
return json.dumps({'x': 4, 'c': b})
def CORS():
cherrypy.response.headers["Access-Control-Allow-Origin"] = "*"
if __name__ == '__main__':
conf = {
'/': {
'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
'tools.CORS.on': True,
}
}
cherrypy.tools.CORS = cherrypy.Tool('before_handler', CORS)
cherrypy.config.update({'server.socket_port': 3000})
cherrypy.quickstart(DataView(), '', conf)
Here's my web page:
<html lang="en">
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
<script type="text/javascript">
$(document).on('click', "#submitButton", function(){
$.ajax({
type: 'GET',
url: 'http://localhost:3000',
contentType: 'text/plain',
xhrFields: {
// The 'xhrFields' property sets additional fields on the XMLHttpRequest.
// This can be used to set the 'withCredentials' property.
// Set the value to 'true' if you'd like to pass cookies to the server.
// If this is enabled, your server must respond with the header
// 'Access-Control-Allow-Credentials: true'.
withCredentials: false
},
headers: {
},
success: function() {
console.log("Success");
},
error: function() {
console.log("Fail");
}
});
});
</script>
</head>
<body>
<div id="header">
<h2>PDE Grammar Engine</h2>
<form>
Input Sentence:<br>
<input type="text" name="query" id="query"><br>
<input type="submit" id="submitButton" value="Submit">
</form>
</div>
</div id="results">
</div>
</body>
</html>
Answer: Turned out that the CherryPy server was not actually listening to the correct
address. It was allowing connections from localhost, but not external
connections. I had to add the following entry to the cherrypy.config.update
cherrypy.config.update({'server.socket_host': '0.0.0.0',
'server.socket_port': 3000})
|
Unpack Python URL Request
Question: I'm using:
import requests
data = 'text=great'
print(requests.post('http://text-processing.com/api/sentiment/', data=data).text)
which returns:
{"probability": {"neg": 0.30135019761690551, "neutral": 0.27119050546800266, "pos": 0.69864980238309449}, "label": "pos"}
and I want to browse that using the structure not just as a string of text.
How can I turn it into a dictionary?
Answer: Use the [`json()` method](http://docs.python-
requests.org/en/master/user/quickstart/#json-response-content) which would
load the JSON response content and return you a Python data structure:
response = requests.post('http://text-processing.com/api/sentiment/', data=data)
print(response.json())
|
How to fetch paragraphs from html using Python
Question: How to fetch paragraphs from bad-structured html?
I have this original html text:
This position is responsible for developing and implementing age appropriate lesson and activity plans for preschool children, ages 4-5 years-old. Maintain a fun and interactive classroom that is clean and well organized, provide a safe, healthy and welcoming learning environment. The ideal candidate will have:
<br>
<ul>
<li>AA Early Childhood Education, or related field. </li>
<li>2+ years experience in a licensed childcare facility </li>
<li>Ability to meet state requirements, including finger print clearance. </li>
<li>Excellent oral and written communication skills </li>
<li>Strong organization and time management skills. </li>
<li>Creativity in expanding children's learning through play.<br> </li>
<li>Strong classroom management skills.<br> </li>
</ul>
<p>The ideal candidate must be a reliable, self-starting professional who is passionate about teaching young children.
<br>
</p>
I use Python and try to do something like that:
soup = BeautifulSoup(html)
It returns a new html text with 2 **short** paragraphs:
<html>
<body>
<p>This position is responsible for developing and implementing age appropriate lesson and activity plans for preschool children, ages 4-5 years-old. Maintain a fun and interactive classroom that is clean and well organized, provide a safe, healthy and welcoming learning environment. The ideal candidate will have:
<br/>
</p>
<ul>
<li>AA Early Childhood Education, or related field. </li>
<li>2+ years experience in a licensed childcare facility </li>
<li>Ability to meet state requirements, including finger print clearance. </li>
<li>Excellent oral and written communication skills </li>
<li>Strong organization and time management skills. </li>
<li>Creativity in expanding children's learning through play.
<br/> </li>
<li>Strong classroom management skills.
<br/> </li>
</ul>
<p>The ideal candidate must be a reliable, self-starting professional who is passionate about teaching young children.
<br/> </p>
</body>
</html>
But it is not what I expected. In the result, I would like to get this html
text:
<html>
<body>
<p>This position is responsible for developing and implementing age appropriate lesson and activity plans for preschool children, ages 4-5 years-old. Maintain a fun and interactive classroom that is clean and well organized, provide a safe, healthy and welcoming learning environment. The ideal candidate will have:
AA Early Childhood Education, or related field.
2+ years experience in a licensed childcare facility
Ability to meet state requirements, including finger print clearance.
Excellent oral and written communication skills
Strong organization and time management skills.
Creativity in expanding children's learning through play.
Strong classroom management skills.
</p>
<p>The ideal candidate must be a reliable, self-starting professional who is passionate about teaching young children.</p>
</body>
</html>
For getting above html, I think that the best approach is to remove all html
tags except `<p>` and `</p>` from original html.
For this purpose I tried the following regular expression:
new_html = re.sub('<[^<]+?>', '', html)
Obviously, the regular expession removes all html tags. So, how to remove all
html tags except `<p>` and `</p>`?
If someone help me to write the r.e. then I feed `new_html` to
`BeautifulSoup()` and get html that I expect.
Answer: This is sort of a manual document manipulation, but, you can loop over the
`li` elements and
[remove](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#extract) them
after
[appending](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#append) to
the first paragraph. Then, remove the `ul` element as well:
from bs4 import BeautifulSoup
data = """
This position is responsible for developing and implementing age appropriate lesson and activity plans for preschool children, ages 4-5 years-old. Maintain a fun and interactive classroom that is clean and well organized, provide a safe, healthy and welcoming learning environment. The ideal candidate will have:
<br>
<ul>
<li>AA Early Childhood Education, or related field. </li>
<li>2+ years experience in a licensed childcare facility </li>
<li>Ability to meet state requirements, including finger print clearance. </li>
<li>Excellent oral and written communication skills </li>
<li>Strong organization and time management skills. </li>
<li>Creativity in expanding children's learning through play.<br> </li>
<li>Strong classroom management skills.<br> </li>
</ul>
<p>The ideal candidate must be a reliable, self-starting professional who is passionate about teaching young children.
<br>
</p>"""
soup = BeautifulSoup(data, "lxml")
p = soup.p
for li in soup.find_all("li"):
p.append(li.get_text())
li.extract()
soup.find("ul").extract()
print(soup.prettify())
Prints the 2 paragraphs as you've planned to have:
<html>
<body>
<p>
This position is responsible for developing and implementing age appropriate lesson and activity plans for preschool children, ages 4-5 years-old. Maintain a fun and interactive classroom that is clean and well organized, provide a safe, healthy and welcoming learning environment. The ideal candidate will have:
<br/>
AA Early Childhood Education, or related field.
2+ years experience in a licensed childcare facility
Ability to meet state requirements, including finger print clearance.
Excellent oral and written communication skills
Strong organization and time management skills.
Creativity in expanding children's learning through play.
Strong classroom management skills.
</p>
<p>
The ideal candidate must be a reliable, self-starting professional who is passionate about teaching young children.
<br/>
</p>
</body>
</html>
Note that there is an important difference in the way `lxml`, `html.parser`
and `html5lib` parse the input HTML you've posted. `html5lib` and
`html.parser` don't automatically create the first paragraph making the code
above really `lxml` specific.
* * *
A better approach would probably be making a separate "soup" object. Sample:
from bs4 import BeautifulSoup
data = """
This position is responsible for developing and implementing age appropriate lesson and activity plans for preschool children, ages 4-5 years-old. Maintain a fun and interactive classroom that is clean and well organized, provide a safe, healthy and welcoming learning environment. The ideal candidate will have:
<br>
<ul>
<li>AA Early Childhood Education, or related field. </li>
<li>2+ years experience in a licensed childcare facility </li>
<li>Ability to meet state requirements, including finger print clearance. </li>
<li>Excellent oral and written communication skills </li>
<li>Strong organization and time management skills. </li>
<li>Creativity in expanding children's learning through play.<br> </li>
<li>Strong classroom management skills.<br> </li>
</ul>
<p>The ideal candidate must be a reliable, self-starting professional who is passionate about teaching young children.
<br>
</p>"""
soup = BeautifulSoup(data, "lxml")
# create new soup
new_soup = BeautifulSoup("<body></body>", "lxml")
new_body = new_soup.body
# create first paragraph
first_p = new_soup.new_tag("p")
first_p.append(soup.p.get_text())
for li in soup.find_all("li"):
first_p.append(li.get_text())
new_body.append(first_p)
# create second paragraph
second_p = soup.find_all("p")[-1]
new_body.append(second_p)
print(new_soup.prettify())
Prints:
<html>
<body>
<p>
This position is responsible for developing and implementing age appropriate lesson and activity plans for preschool children, ages 4-5 years-old. Maintain a fun and interactive classroom that is clean and well organized, provide a safe, healthy and welcoming learning environment. The ideal candidate will have:
AA Early Childhood Education, or related field.
2+ years experience in a licensed childcare facility
Ability to meet state requirements, including finger print clearance.
Excellent oral and written communication skills
Strong organization and time management skills.
Creativity in expanding children's learning through play.
Strong classroom management skills.
</p>
<p>
The ideal candidate must be a reliable, self-starting professional who is passionate about teaching young children.
<br/>
</p>
</body>
</html>
|
Can't get true/false value from command line in python 2.7
Question: I'm trying to incorporate a flag in to a program:
python2.7 hello.py --showxy
and `argparse` is giving me trouble.
this is my example test code:
import os
import sys
import argparse
print (os.getcwd())
print ("___________________________________________________")
print ("A: " + sys.argv[0])
print ("B: " + sys.argv[1])
print ("C: " + sys.argv[2])
print ("___________________________________________________")
parser = argparse.ArgumentParser()
parser.add_argument('--showxy', action='store_true')
args = argparse.Namespace()
d = vars(args)
print Namespace()
And while I _should_ be getting:
Namespace(showxy=True)
I am _actually_ getting an error:
A: hello.py
B: haarcascade_frontalface_default.xml
C: euromil.jpg
___________________________________________________
Traceback (most recent call last):
File "hello.py", line 19, in <module>
print Namespace()
NameError: name 'Namespace' is not defined
How should I be formatting this?
Answer: You are missing the parsing step
args = parser.parse_args()
`args = argparse.Namespace()` just creates an new empty `Namespace` object.
`argparse` is the module. `parser` is the `ArgumentParser` object. `Namespace`
is a class defined in that module. `parse_args` creates a `Namespace`, fills
it with values that that it parses from `sys.argv`, and returns it as `args`.
Defining the `parser` by itself does not do any parsing.
* * *
The very first example in the docs is:
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args()
print(args.accumulate(args.integers))
Some claim this is too advanced for beginners, but the key pieces are there.
parser = ...
parser.add_argument...
args = parser.parse_args()
# look at args, print it, access attributes, etc.
`argparse.Namespace` isn't mentioned until section
<https://docs.python.org/3/library/argparse.html#the-namespace-object>
|
shadowing a site module by my own module in Python
Question: I have a script `foo.py`, which tries to `from bar import baz`: basically the
hierarchy is the following:
/
foo.py
bar/
__init__.py
baz.py
The problem is that the system ships its own version of `bar` in `site-
packages`, and I want to avoid importing that (I want to make sure I use the
module I ship instead of whatever version might be on the system).
Initially I thought that the order of the paths in `sys.path` will be enough
to solve the problem. However, on some systems, there's a `bar.pth` file in
`site-packages` that adds `bar` to `sys.modules`, which results in ignoring
`sys.path` completely when importing `bar` and just importing the `site-
packages` version.
How can I make sure that I import my local version of `bar`, regardless of
what might be set up on the system?
Answer: According to the
[documentation](https://docs.python.org/2/tutorial/modules.html), if you
define an environment variable, `PYTHONPATH`, which contains the folder `bar`,
that will be tried first, and thus it will import your module.
|
This error while downloading datasets: ValueError: I/O operation on closed file
Question: I have started with deep learning with Theano and Keras. However, for any
program, I will have to load the dataset, and i'm not able to load any
dataset.
Even if I run these two lines:-
from keras.datasets import cifar10
(X_train, y_train), (X_test, y_test) = cifar10.load_data()
I even tried the above with minst dataset. Exact same error.
I tried to run the commands one by one, the first import goes well. In the
second command, it runs and python begins downloading. However, after a few
seconds, it breaks.
This is the exact error:-
> (X_train, y_train), (X_test, y_test) = cifar10.load_data() Downloading data
> from <http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz>
> 8929280/170498071 [>.............................] - ETA: 82sTraceback
> (most recent call last):
>
> File "", line 1, in (X_train, y_train), (X_test, y_test) =
> cifar10.load_data()
>
> File "C:\Users\Aseem\Anaconda3\envs\AnacondaAseem\lib\site-
> packages\keras\datasets\cifar10.py", line 11, in load_data path =
> get_file(dirname, origin=origin, untar=True)
>
> File "C:\Users\Aseem\Anaconda3\envs\AnacondaAseem\lib\site-
> packages\keras\utils\data_utils.py", line 76, in get_file raise e
>
> ValueError: I/O operation on closed file
I do not know why this is happening. Seems like something is wrong in the file
data_utils.py
What do I do?
Answer: I tried your exact code and it works fine on my computer. The failure could be
due to several reasons, like a unstable internet connection or not enough free
space in your home folder.
What you can do is to download the
[file](http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz) manually using
a download manager, put it in ~/.keras/datasets and rename it to
cifar-10-batches-py.tar.gz and run the code again, it should pick up the file
and continue processing from there.
|
Python3 Rename files in a directory importing the new names from a txt file
Question: I have a directory containing multiple files. The name of the files follows
this pattern 4digits.1.4digits.[barcode] The barcode specifies each file and
it is composed by 7 leters. I have a txt file where in one column I have that
barcode and in the other column the real name of the file. What I would like
to do is to right a pyhthon script that automatically renames each file
according to the barcode to it s new name written in the txt file.
Is there anybody that could help me?
Thanks a lot!
Answer: I will give you the logic:
**1.** read the text file that contains barcode and
name.<http://www.pythonforbeginners.com/files/reading-and-writing-files-in-
python>.
for each line in txt file do as follows:
**2.** Assign the value in first(barcode) and second(name) column in two
separate variables say 'B' and 'N'.
**3.** Now we have to find the filename which has the barcode 'B' in it. the
link [Find a file in python](http://stackoverflow.com/questions/1724693/find-
a-file-in-python) will help you do that.(first answer, 3 rd example, for your
case the name you are going to find will be like '*B')
**4.** The previous step will give you the filename that has B as a part. Now
use the rename() function to rename the file to 'N'. this link will hep
you.<http://www.tutorialspoint.com/python/os_rename.htm>
Suggestion: Instead of having a txt file with two columns. You can have a csv
file, that would be easy to handle.
|
Can't start Mercurial
Question: When I put “hg —version” in my mac terminal, it shows below Error…
Traceback (most recent call last):
File "/usr/local/bin/hg", line 41, in <module>
mercurial.util.setbinary(fp)
File "/Library/Python/2.7/site-packages/mercurial/demandimport.py", line 106, in __getattribute__
self._load()
File "/Library/Python/2.7/site-packages/mercurial/demandimport.py", line 78, in _load
mod = _hgextimport(_import, head, globals, locals, None, level)
File "/Library/Python/2.7/site-packages/mercurial/demandimport.py", line 47, in _hgextimport
return importfunc(name, globals, *args)
File "/Library/Python/2.7/site-packages/mercurial/util.py", line 70, in <module>
statfiles = getattr(osutil, 'statfiles', platform.statfiles)
File "/Library/Python/2.7/site-packages/mercurial/demandimport.py", line 106, in __getattribute__
self._load()
File "/Library/Python/2.7/site-packages/mercurial/demandimport.py", line 78, in _load
mod = _hgextimport(_import, head, globals, locals, None, level)
File "/Library/Python/2.7/site-packages/mercurial/demandimport.py", line 47, in _hgextimport
return importfunc(name, globals, *args)
ImportError: dlopen(/Library/Python/2.7/site-packages/mercurial/osutil.so, 2): Symbol not found: _fdopendir$INODE64
Referenced from: /Library/Python/2.7/site-packages/mercurial/osutil.so
Expected in: /usr/lib/libSystem.B.dylib
in /Library/Python/2.7/site-packages/mercurial/osutil.so
How I fix this?
Thank you in advance for any help you can provide.
PS : Sorry for my poor English.
Answer: Finally I got Answer…!
_Step1:_ Go to “**/Library/Python/2.7/site-packages** ” folder.
>$ cd /Library/Python/2.7/site-packages
_Step2:_ Remove below files in "**site-packages** " folder.
>$ rm -rf hgext
>$ rm -rf mercurial
>$ rm -rf mercurial-3.7.3-py2.7.egg-info
_Step 3:_ Now **install mercurial**
|
How do I plot a 2D array graph in Python using matplotlib
Question: I'm having a little bit of trouble in creating a graph using 2D array data in
python.
I have a txt file which holds data like this:
0 2 4 6 8
-1 -2 -1 2 4
0 1 0 -1 0
1 3 5 7 6
0 1 -1 -3 2
1 -1 1 1 0
(this is shortened, my actual file is 100*10000
So essentially a 5x6 array.
I would like the x axis to be the total number of elements in each array which
is always going to be a fixed limit of 5. The Y axis needs to be the actual
data point from the txt file. Which leaves 6 lines in total being created.
Below is a quickly drawn photo in paint: [Image here (low score, cannot
embed)](http://i.stack.imgur.com/mOW7J.png) So Y = data value, X = length of
each individual array and the lines are how many total arrays their are.
I would like to use this style, however if possible make the line width 1px as
there are going to be roughly 10,000 lines drawn.
<http://matplotlib.org/examples/style_sheets/plot_fivethirtyeight.html>
I have had a try with some of the code, and this is where I got stuck, I could
read in the data and store it in some kind of array, but then was unable to
use that for making the graph. (Top part is my code for reading it in, bottom
part is the example code from the fivethirtyeight style.
import numpy as np
import matplotlib.pyplot as plt
with open('thisone.txt') as file:
array2d = [[int(digit) for digit in line.split()] for line in file]
from matplotlib import pyplot as plt
import numpy as np
x = np.linspace(0, 10)
with plt.style.context('fivethirtyeight'):
plt.plot(x, np.sin(x) + x + np.random.randn(50))
plt.plot(x, np.sin(x) + 0.5 * x + np.random.randn(50))
plt.plot(x, np.sin(x) + 2 * x + np.random.randn(50))
plt.show()
Answer: After you read in the data, iterate over the rows in the data and plot a graph
row vs. range(len(row)).
import numpy as np
import matplotlib.pyplot as plt
with open('thisone.txt') as file:
array2d = [[int(digit) for digit in line.split()] for line in file]
with plt.style.context('fivethirtyeight'):
for row in array2d:
plt.plot(xrange(len(row)), row)
plt.show()
|
Create python array from first element of array 1, first element of array 2, second element of array 1, second element of array 2, etc
Question: I am attempting to create a state vector representing the positions and
velocities of a series of particles at a given time, for a simulation. I have
created individual vectors x,y,vx,vy which give the value of that variable for
each particle. Is there a good way of automatically combining them into one
array, which contains all the info for particle one, followed by all the info
for particle two etc etc)? Thanks
Answer: Do you mean like this?
x = [0, 1, 2]
y = [3, 4, 5]
vx = [6, 7, 8]
vy = [9, 10, 11]
c = zip(x, y, vx, vy)
print(c) # -> [(0, 3, 6, 9), (1, 4, 7, 10), (2, 5, 8, 11)]
if you're using Python 3, you would need to use `c = list(zip(x, y, vx, vy))`.
If you don't want the values for each particle grouped into a tuple like that
for some reason, the result could be flattened:
c = [item for group in zip(x, y, vx, vy) for item in group]
print(c) # -> [0, 3, 6, 9, 1, 4, 7, 10, 2, 5, 8, 11]
**However** , I would recommend just "naming" the tuples instead:
from collections import namedtuple
Particle = namedtuple('Particle', 'x, y, vx, vy')
c = [Particle._make(group) for group in zip(x, y, vx, vy)]
print(c)
Output:
[Particle(x=0, y=3, vx=6, vy=9),
Particle(x=1, y=4, vx=7, vy=10),
Particle(x=2, y=5, vx=8, vy=11)]
That way you can reference the fields by name — i.e. `c[1].x` — which could
make subsequent code and calculations a lot more readable.
|
Opening other Python 3 files using tkinter
Question: I am currently working on making a program using tkinter that when pressing a
button it opens the Python program, however I am having some problems with it.
I have tried using `os.system('filename.py')`. That opens the file, but then
crashes the GUI, making the user have to restart the GUI. I have also tried
importing it as a module but that just does the same as when using
`os.system`.
Can anyone possibly help me open a Python file in a completely new
window/terminal?
Answer: The problem is filename.py will not be recognised by your os. Instead of that
use:
os.system('python filename.py')
This will successfully open your python file inside your GUI Hope this helps
|
How to handle with Django HTTP.Request, request content-type, query parameters
Question: Hi all I'm new in Python and Django actually also in Coding.
I would like to build an app, that can receive a POST-Request with the
Content_Type 'application/xml'.
I don't understand how to handle with the HTTP.Request.META in django. First I
would like to check the Content_type, then the Query_string, then
Content_Lenght.
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render
from django.http import (
HttpResponse, HttpResponseNotAllowed, HttpRequest,)
@csrf_exempt
# Check the HTTP Request Method
def app(request):
if request.method != "POST":
return HttpResponseNotAllowed(permitted_methods=('POST',))
else:
# checkcontent(request)
return HttpResponse('OK')
“““
def checkcontent(request):
if not 'application/xml' in request.meta['CONTENT_TYPE']:
raise Exception("Invalid content-type. The expected request content-type is 'application/xml'")
“““
The Comment Block Doesn't Work!
Can someone explain me?
Thx
Anas Syed
Answer: first of all, [here are all available
headers](https://docs.djangoproject.com/en/1.9/ref/request-
response/#django.http.HttpRequest.META) of http request in django
so you need:
request.META['CONTENT_TYPE']
instead of
request.meta['CONTENT_TYPE']
|
Python openpyxl select sheet
Question: I am writing some data into an Excel file, but I dont know how to adjust the
code in order to be able to control which sheet I am writing into:
wb= load_workbook(filename)
active_ws=wb.active
Instead of `wb.active`, how can I say something like `Sheets('Data')` (this is
how the VBA syntax would look like...)?
Answer: You should use `wb[sheetname]`
from openpyxl import load_workbook
wb2 = load_workbook('test.xlsx')
ws4 = wb2["New Title"]
PS: You should check if your sheet in sheet names `wb.sheetnames`
print(wb2.sheetnames)
['Sheet2', 'New Title', 'Sheet1']
|
using an array in python
Question: I am currently trying to figure out how to store two sets of values, t and y,
in my program so that I can plot these data points on a graph. I believe the
correct method is to use an array, but I am not sure how to proceed.
import numpy as np
import matplotlib.pyplot as plt
t = 0.0
y = 0.0
u = 0.0
F = 0.2
Wd = 2*3.14
w0 = 1.5*Wd
b = w0/4
h= 0.05
while (t <= 5.95):
m1 = u
k1 = (-w0**2)*np.sin(y) + u*(1-2*b) + F*(w0**2)*np.cos(Wd*t)
m2 = u + (h / 2.) * k1
t_2 = t + (h / 2.)
y_2 = y +(h / 2.) * m1
u_2 = m2
k2 = (-w0**2)*np.sin(y_2) + u_2*(1-2*b) + F*(w0**2)*np.cos(Wd*t_2)
m3 = u + (h / 2.) * k2
t_3 = t + (h / 2.)
y_3 = y + (h / 2.) * m2
u_3 = m3
k3 = (-w0**2)*np.sin(y_3) + u_3*(1-2*b) + F*(w0**2)*np.cos(Wd*t_3)
m4 = u + h * k3
t_4 = t + h
y_4 = y + h * m3
u_4 = m4
k4 = (-w0**2)*np.sin(y_4) + u_4*(1-2*b) + F*(w0**2)*np.cos(Wd*t_4)
t = t + h
y = y + (h / 6.) * (m1 + (2 * m2) + (2 * m3) + m4)
u = u + (h / 6.) * (k1 + (2 * k2) + (2 * k3) + k4)
print t, y
Answer: While printing `t` and `y` use `plt.scatter(t, y)` After the loop use
`plt.show()`
Or
You can save `t` and `y` in array `T` and `Y` and later use `plt.scatter(T,
Y)` and `plt.show()` to plot.
[](http://i.stack.imgur.com/qOQzW.png)
To draw line
T, Y = [], []
# loop starts
....
....
t = t + h
y = y + (h / 6.) * (m1 + (2 * m2) + (2 * m3) + m4)
T.append(t)
Y.append(y)
....
....
# loop ends
plt.plot(T, Y)
plt.show()
[](http://i.stack.imgur.com/fPxql.png)
|
Interrupting a Queue.get
Question: How can I interrupt a blocking `Queue.get()` in Python 3.X?
In Python 2.X [setting a long
timeout](http://stackoverflow.com/q/212797/1658617) seems to work but the same
cannot be said for Python 3.5.
Running on Windows 7, CPython 3.5.1, 64 bit both machine and Python. Seems
like it does not behave the same on Ubuntu.
Answer: The reason it works on Python 2 is that `Queue.get` with a timeout on Python 2
is implemented incredibly poorly, [as a polling loop with increasing sleeps
between non-blocking attempts to acquire the underlying
lock](https://hg.python.org/cpython/file/2.7/Lib/threading.py#l343); Python 2
doesn't actually feature a lock primitive that supports a timed blocking
acquire (which is what a `Queue` internal `Condition` variable needs, but
lacks, so it uses the busy loop). When you're trying this on Python 2, all
you're checking is whether the `Ctrl-C` is processed after one of the (short)
`time.sleep` calls finishes, and [the longest sleep in `Condition` is only
0.05 seconds](https://hg.python.org/cpython/file/2.7/Lib/threading.py#l358),
which is so short you probably wouldn't notice even if you hit Ctrl-C the
instant a new sleep started.
Python 3 has true timed lock acquire support (thanks to narrowing the number
of target OSes to those which feature a native timed mutex or semaphore of
some sort). As such, you're actually blocking on the lock acquisition for the
whole timeout period, not blocking for 0.05s at a time between polling
attempts.
It looks like Windows allows for registering handlers for Ctrl-C that mean
that [`Ctrl-C` doesn't necessarily generate a true
signal](https://stackoverflow.com/questions/5056567/ctrlc-and-ctrlbreak-are-
different), so the lock acquisition isn't interrupted to handle it. Python is
informed of the `Ctrl-C` when the timed lock acquisition eventually fails, so
if the timeout is short, you'll eventually see the `KeyboardInterrupt`, but it
won't be seen until the timeout lapses. Since Python 2 `Condition` is only
sleeping 0.05 seconds at a time (or less) the Ctrl-C is always processed
quickly, but Python 3 will sleep until the lock is acquired.
`Ctrl-Break` is guaranteed to behave as a signal, but it also can't be handled
by Python properly (it just kills the process) which probably isn't what you
want either.
If you want `Ctrl-C` to work, you're stuck polling to some extent, but at
least (unlike Python 2) you can effectively poll for `Ctrl-C` while live
blocking on the queue the rest of the time (so you're alerted to an item
becoming free immediately, which is the common case).
import time
import queue
def get_timed_interruptable(q, timeout):
stoploop = time.monotonic() + timeout - 1
while time.monotonic() < stoploop:
try:
return q.get(timeout=1) # Allow check for Ctrl-C every second
except queue.Empty:
pass
# Final wait for last fraction of a second
return q.get(timeout=max(0, stoploop + 1 - time.monotonic()))
This blocks for a second at a time until:
1. The time remaining is less than a second (it blocks for the remaining time, then allows the `Empty` to propagate normally)
2. `Ctrl-C` was pressed during the one second interval (after the remainder of that second elapses, `KeyboardInterrupt` is raised)
3. An item is acquired (if `Ctrl-C` was pressed, it will raise at this point too)
|
Categorize data into n category with same interval size in python
Question: Assume I want to categorize data below in 12 category:
no. grades
0 9.08
1 8.31
2 7.42
3 7.42
4 7.42
5 7.46
6 9.67
7 11.77
8 8.81
9 6.44
10 9.40
11 9.06
12 10.52
13 6.19
14 5.04
15 5.04
16 9.44
17 5.87
18 2.67
19 6.99
20 9.08
21 6.64
22 4.83
23 4.47
24 6.61
25 6.61
26 7.42
27 6.42
28 10.00
29 9.11
It is possible to do it with something like this:
df.a[df.a <= 1 and df.a>0] = 1
df.a[df.a <= 2 and df.a>1] = 2
.
.
.
df.a[df.a <= 12 and df.a>11] = 12
Is there any other way to categorize item to categories with constant and
equal intervals?
P.S:
my data is here and I want to categorize its grades column:
psechoice hscath grades faminc famsiz parcoll female black
0 1 0 9.08 62.50 5 0 0 0
1 1 0 8.31 42.50 4 0 1 0
2 1 0 7.42 62.50 4 0 1 0
3 1 0 7.42 62.50 4 0 1 0
4 1 0 7.42 62.50 4 0 1 0
5 1 0 7.46 12.50 2 0 1 0
6 1 0 9.67 30.00 5 0 0 0
7 0 0 11.77 42.50 4 0 0 0
8 1 0 8.81 17.50 3 0 1 0
9 1 0 6.44 42.50 6 0 0 0
10 1 0 9.40 30.00 5 1 0 0
11 1 0 9.06 62.50 6 0 0 0
12 0 0 10.52 62.50 3 0 0 0
13 1 0 6.19 62.50 2 0 1 0
14 1 0 5.04 42.50 6 0 1 0
15 1 0 5.04 42.50 6 0 1 0
16 0 0 9.44 22.50 2 0 1 0
17 1 1 5.87 87.50 5 1 0 0
18 1 1 2.67 62.50 4 0 0 0
19 1 1 6.99 42.50 5 0 0 0
20 1 1 9.08 150.00 4 1 1 0
21 1 0 6.64 42.50 9 0 1 0
22 1 1 4.83 0.50 4 1 0 0
23 1 1 4.47 62.50 3 0 1 0
24 1 1 6.61 87.50 6 1 0 0
25 1 1 6.61 87.50 6 1 0 0
26 1 1 7.42 42.50 4 1 0 0
27 1 1 6.42 87.50 5 1 0 0
28 1 0 10.00 8.75 4 1 1 0
29 1 0 9.11 22.50 3 0 0 1
Answer: You could use [`pd.cut`](http://pandas.pydata.org/pandas-
docs/stable/generated/pandas.cut.html) to assign values to categories:
import pandas as pd
df = pd.DataFrame(
{'grades': [9.08, 8.31, 7.42, 7.42, 7.42, 7.46, 9.67, 11.77,
8.81, 6.44, 9.40, 9.06, 10.52, 6.19, 5.04, 5.04, 9.44, 5.87,
2.67, 6.99, 9.08, 6.64, 4.83, 4.47, 6.61, 6.61, 7.42, 6.42,
10.0, 9.11],
'no.': range(30)})
df['category'] = pd.cut(df['grades'], bins=range(0, 13), labels=range(1, 13))
print(df)
yields
grades no. category
0 9.08 0 10
1 8.31 1 9
2 7.42 2 8
3 7.42 3 8
4 7.42 4 8
5 7.46 5 8
6 9.67 6 10
7 11.77 7 12
...
With `pd.cut(..., bins=range(0, 13))`, the categories are
[(0, 1] < (1, 2] < (2, 3] < (3, 4] ... (8, 9] < (9, 10] < (10, 11] < (11, 12]]
Notice the intervals are open on the left and closed on the right.
|
Convert datetime (e.g. 2016-01-01, 2016-01-11) to integer days (e.g. 0, 11) in Python
Question: **Is it possible to convert a timestamp object in the format "2016-01-01"
(year month day) into number of days from new years?**
I'm getting my timestamp object by `str(pandas.to_datetime('today')).split("
")[0]`
I would put code that I used to get it started but I don't even know where to
begin except by making a dictionary for how many days are in each month and
then calculating it the long way. Is there something built in that I can use
for this?
Answer:
from datetime import datetime, timedelta, date
import dateutil
st_date = '2016-11-01'
dt = dateutil.parser.parse(st_date).date()
tm_diff = dt - date(2016, 1, 1);
print tm_diff.days
|
accessing a list of urls via Multi-processing in Python2.7
Question: I've been playing with multiprocessing and my code works when looking at
smaller numbers but when I want to run a larger sample 2 things happen: Either
the code locks up or I get the following error message: "urlopen error [Errno
10054] An existing connection was forcibly closed by the remote host" . I
can't figure out how to get it to work. Thanks.
from multiprocessing import cpu_count
import urllib2
from bs4 import BeautifulSoup
import json
import timeit
import socket
import errno
def parseWeb(id):
url = 'https://carhood.com.au/rent/car_detail/'+str(id)+'/'
hdr = {'Accept': 'text/html,application/xhtml+xml,*/*',"user-agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36"}
html = urllib2.urlopen(url).read()
soup=BeautifulSoup(html,"lxml")
car=soup.find("h1",{"class":"intro-title intro-title-tertiary"}).text
return car
if __name__ == '__main__':
start = timeit.default_timer()
pool = Pool(cpu_count()*100)
#This works for me when xrange(1,70)
results=pool.map(parseWeb,xrange(1,400))
print results
##I've tried this as a solution but it didn't work
## startNum=1
## endNum=470
## for x in range(startNum,endNum,70):
## print x
## results=pool.map(parseWeb,xrange(startNum,x))
## print results
## startNum=x
stop = timeit.default_timer()
print stop - start
Answer: John Zwinck's advice in the question comments is pretty on the ball.
**Part of the issue is that you have no control over the receiving server.**
When you place an excessive number of processes, you force the server on the
other end to figure out the right way to handle all of your requests at once.
That causes your processes to sit there idly waiting for the server to get
back to them at some point - since `pool.map()` only finishes when all of your
processes finish (it is a _blocking_ call), that means you wait for as long as
it takes the server to service each of them.
Everything now depends on the server.
* The server can choose to dedicate its resources to serving all of your requests one by one - that effectively means your requests are now waiting in _a queue_ , offering no advantage than if you had just sent your requests serially, one by one. Single-threaded servers can be modelled like this, although their major speedup comes from the fact that they are asynchronous and jump rapidly between request and request.
* Some servers typically have a small number of processes or threads that spawn a large number of child threads that all handle incoming requests one by one - the Apache server, for instance, [starts off with 2 dedicated processes with 25 threads each](http://stackoverflow.com/questions/3389496/how-do-you-increase-the-max-number-of-concurrent-connections-in-apache), so theoretically it can handle 50 concurrent requests and scale as high as it is configured to. It will service as many as it can at this moment, and either put the remainder of your excess requests on hold or deny them service.
* Some servers will simply kill or close connections if they threaten to overload the system or if an internal timeout is arrived at. The latter is more likely and more often encountered.
**The other aspect of it is simply that your own CPU cores can't handle what
you're asking them to do.** A core can handle _one_ thread at a time - when we
speak of parallelism, we are really talking about multiple cores handling a
thread simultaneously. Processes with a large number of smaller threads can
have those threads be distributed among different CPU cores, so you can
benefit from that.
But you have one hundred processes, each of which induce a _blocking_ I/O call
(`urlopen` is [blocking](http://stackoverflow.com/questions/11664185/python-
urllib2-urlopenurl-process-block)). If that I/O call is instantly responded
to, so far so good - if not, now the other processes are waiting for this
process to finish, taking up a valuable CPU core. You have successfully
introduced _waiting_ into a system where you want to explicitly _avoid_
waiting. If you compound this issue with the stress you induce on the
receiving server, you find a number of delays stemming from open connections.
## Solutions
There are quite a few solutions, but in my own opinion they all boil down to
the same thing:
* _Avoid_ blocking calls. Use a solution which fires off a request, puts the thread responsible for that to sleep and off the scheduler run queue, and wakes it up when an event is registered.
* _Use_ asynchronicity to your advantage. A single thread can make more than one request without blocking, you just have to be able to intelligently handle the responses as they come in one by one. You can even pass responses to other threads that aren't doing any work (like using a `Queue`, for example). The trick is to get them to work together seamlessly.
`multiprocessing`, though a good solution for handling processes, is not a
bundled-in solution for handling the interaction between HTTP requests and the
process's appropriate behaviour. This is logic you would usually have to write
yourself, and it _can_ be done if you had greater control over how `urlopen`
works - you'd have to figure out a way to make sure `urlopen` doesn't block,
or at least is willing to subscribe to event notifications immediately after
sending a request.
Certainly, this can all be done - but web scraping is a solved problem, and
there's no need to have to rewrite the wheel.
Instead, there are a couple of options that are tried and tested:
* [`asyncio`](https://docs.python.org/3/library/asyncio.html) is the standard as of Python 3.5. While not a full-fledged HTTP service, it offers asynchronous support for I/O bound operations. You can make HTTP requests using [`aiohttp`](http://aiohttp.readthedocs.org/en/stable/). Here's a [tutorial](https://compiletoi.net/fast-scraping-in-python-with-asyncio/) on how to scrape with the same.
* [Scrapy](http://scrapy.org/) is viable on Python 2.7 and Python 3. It uses [Twisted](http://twistedmatrix.com/trac/), `asyncio`'s non-standard fore-runner and the go-to tool for fast network requests. I mention Scrapy instead of Twisted simply because Scrapy has already taken care of the underlying architecture for you [which can be read about [here](https://www.dropbox.com/sh/eyqm70u681usy7j/AABZiMSgOkPR8FG7ZPLcWrQna?dl=0)] - you should certainly explore Twisted to get a feel of the underlying system if you want to. It is the most hand-holdy of all the solutions I'll mention here, but also, in my experience, the most performant.
* [`grequests`](https://github.com/kennethreitz/grequests) is an extension of the popular `requests` library (which is incidentally superior to `urllib2` and should be used at every opportunity) to support so-called coroutines: threads that can be suspended and resumed at multiple points in their execution, very ideal if you want the thread to do work while waiting for an I/O response. `grequests` builds on top of [`gevent`](http://www.gevent.org/) (a coroutine library) to let you make multiple requests in a single thread, and handle them at your own pace.
|
Python bs4 removes br tag
Question: I use bs4 to manipulate some rich-text. but it removes br tag inside where i
did character conversion. below is the simple form of the code.
import re
from bs4 import BeautifulSoup
#source_code = self.textInput.toHtml()
source_code = """.......<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu';">ABC ABC<br />ABC</span></p>......."""
soup = BeautifulSoup(source_code, "lxml")
for elm in soup.find_all('span', style=re.compile(r"font-family:'Ubuntu'")):
#actually there was a for loop
elm.string = elm.text.replace("A", "X")
elm.string = elm.text.replace("B", "Y")
elm.string = elm.text.replace("C", "Z")
print(soup.prettify())
this should give an output as
...<span style=" font-family:'Ubuntu';">XYZ XYZ<br />XYZ</span>...
#XYZ XYZ
#XYZ
but it gives output without br tag.
...<span style=" font-family:'Ubuntu';">XYZ XYZXYZ</span>...
#XYZ XYZXYZ
how can i correct this?
Answer: The problem is that you are redefining the `.string` of the element, but
instead I would find the "text" nodes and made the replacement there:
for text in elm.find_all(text=True):
text.replace_with(text.replace("A", "X").replace("B", "Y").replace("C", "Z"))
Works for me, produces:
</p>
<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">
<span style=" font-family:'Ubuntu';">
XYZ XYZ
<br/>
XYZ
</span>
</p>
> how can i include this part in a loop?
Here is a sample:
replacements = {
"A": "X",
"B": "Y",
"C": "Z"
}
for text in elm.find_all(text=True):
text_to_replace = text
for k, v in replacements.items():
text_to_replace = text_to_replace.replace(k, v)
text.replace_with(text_to_replace)
|
Python geoip find country using json
Question:
from urllib2 import urlopen
from contextlib import closing
import json
import time
import os
while True:
url = 'http://freegeoip.net/json/'
try:
with closing(urlopen(url)) as response:
location = json.loads(response.read())
location_city = location['city']
location_state = location['region_name']
location_country = location['country_name']
#print(location_country)
if location_country == "Germany":
print("You are now surfing from: " + location_country)
os.system(r'firefox /home/user/Documents/alert.html')
except:
print("Could not find location, searching again...")
time.sleep(1)
Its doesn't reply any country can I get help to solve the problem?
Answer: Besides of the wrong indentation, your code looks fine.
The problem seems to be that the page itself does not respond. If you try to
open it in a browser for example, the connection gets refused.
Probably the api is either overloaded, or does no longer exist.
|
Subsets and Splits