text
stringlengths 226
34.5k
|
---|
Find ports a program uses with python
Question: I want to find the ports used by 'plugin-container.exe' so I can monitor what
IP addresses interact with that program, The problem is there are two 'plugin-
container.exe's. I use Firefox Developer Edition.
I already have the monitoring part down but I need to automate getting the
ports some how. From what I've seen, getting them means knowing what PID the
process is using, two processes = 2 PIDs. ;_;
I could add BOTH of them but there is a ton of traffic going though my browser
and it kills my program when I put all 4 ports in manually.
Right now I'm using this to get the list, re.findall to filter the 'plugin-
container.exe' in the list, I then use psutil to find what ports.
I feel like there is an easier way to do all of this.
> import os, sys, win32api, re, psutil
>
> tasklistrl = os.popen("tasklist").readlines()
>
> tasklistr = os.popen("tasklist").read()
Answer: If you want a nice way to find processes by executable name using psutil, then
you should use
[process_iter](https://pythonhosted.org/psutil/#psutil.process_iter) and
[cmdline](https://pythonhosted.org/psutil/#psutil.Process.cmdline):
my_processes = [x for x in psutil.process_iter() if os.path.split(x.cmdline()[0])[1] == 'python']
(substitute `'python'` with executable name you want)
|
How to read the file which is in other directory?
Question: My project
et->datacollector
->eventprocessor->multilang->resources->python->tenderevent->rules->Table.py
->target->inpout->Read.csv
Table.py
import pandas as pd
df_LFB1 = pd.read_csv('Read.csv', sep = ',', usecols = [1,2,7,59])
Now above I want to use `Read.csv` file how should I give the directory of
`Read.csv` file in `pd.read_csv`
Answer:
import os
os.getcwd()
Out[42]: '/Users/Documents'
## os.path.abspath(__file__) ## inside script
If I have the `'Read.csv'` file in my current working directory
`'/Users/Documents'`, I can read the file like below.
df_LFB1 = pd.read_csv('Read.csv', sep = ',', usecols = [1,2,7,59])
and if my file is not in current working dierctory but in some other directory
lets say `et` directory is in `/home/project`,
df_LFB1 = pd.read_csv(r'/home/project/et/eventprocessor/target/inpout/ Read.csv',
sep = ',', usecols = [1,2,7,59])
Above statement will read the file.
Note: when you provide absolute path to file. It doesnt not matter where your
script resides.
|
Why the frame area drawed by the pyplot is black?
Question: My test codes are
import numpy as np
import time
import matplotlib
from matplotlib import pyplot as plt
def run(genxy, style='point'):
fig, ax = plt.subplots(1, 1)
#ax.set_aspect('equal')
ax.set_xlim(0, 5.2)
ax.set_ylim(-1.1, 1.1)
ax.hold(True)
plt.show(False)
plt.draw()
background = fig.canvas.copy_from_bbox(ax.bbox)
x, y = genxy.next()
if style == 'point':
sincurve = ax.plot(x, y, '.')[0]
else:
sincurve = ax.plot(x, y)[0]
while True:
try:
x, y = genxy.next()
except StopIteration:
break
sincurve.set_data(x, y)
# restore background
fig.canvas.restore_region(background)
# redraw just the points
ax.draw_artist(sincurve)
# fill in the axes rectangle
fig.canvas.blit(ax.bbox)
time.sleep(0.1)
plt.close(fig)
from copy import copy
X = np.arange(0, 5, 0.1)
def generate_curve(x):
x = copy(x)
y = np.sin(x)
for i in range(0, len(y)):
yield x[0:i+1], y[0:i+1]
genxy = generate_curve(X)
run(genxy, 'line')
And the screenshot image is
[](http://i.stack.imgur.com/Q8sFO.png)
And more there is a warning printed out
> QGtkStyle could not resolve GTK. Make sure you have installed the proper
> libraries.
My python is 2.7, my system is LMDE2(Linux Mint Debian Edition 2).
Answer: Have a look in your `matplolibrc` file - this contains all the plotting
defaults. On my Windows system it's here:
`C:\Python27\Lib\site-packages\matplotlib\mpl-data\matplotlibrc`
You should have a line like this:
`#figure.facecolor : 0.75 # figure facecolor; 0.75 is scalar gray`
On my system if I un-comment this and change `0.75` to `0.0`, I get a black
frame with your code, otherwise it's grey as it should be.
If the the line is not un-commented then I don't know where your black is
coming from. Adding the line `matplotlib.rc('figure', facecolor='0.75')`
immediately after your imports should hopefully fix the problem, but doesn't
answer where the black has come from if not from your `matplotlibrc` file
Edit: [this](https://bbs.archlinux.org/viewtopic.php?id=99175) link may help
you solve the GTK problem.
|
subprocess use two way, but result is not same
Question: I use `subprocess`'s `check_output()` function two ways,find the result are
different, I don't known why.
1. First way:
from subprocess import check_output as qc
output = qc(['exit', '1'], shell=True)
2. Second way:
from subprocess import check_output as qc
output = qc(['exit 1'], shell=True)
Error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/work/cloud/python2.7_64/lib/python2.7/subprocess.py", line 544, in check_output
raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command '['exit 1']' returned non-zero exit status 1
Second way is right, but first way why is not right?
Answer: Quoting [subprocess
docs](https://docs.python.org/2/library/subprocess.html#frequently-used-
arguments):
> _args_ is required for all calls and **should be a string, or a sequence of
> program arguments**. Providing a sequence of arguments is generally
> preferred, as it allows the module to take care of any required escaping and
> quoting of arguments (e.g. to permit spaces in file names). **If passing a
> single string, either shell must be True (see below) or else the string must
> simply name the program to be executed without specifying any arguments.**
What you actually do in each case is:
1. You pass a sequence of arguments: `['exit', '1']`. Sequence is equivalent of shell command `exit 1`. Arguments are separated by spaces and there are no quotations to alter separation process.
2. You pass a sequence of arguments: `['exit 1']`, which has length 1. This is equivalent to shell command `"exit 1"`. Your first (and only) argument has space in it, which is analogous with enclosing it in quoting marks.
As you can verify, exit codes of both commands are different, therefore your
Python script output is different.
|
To detect digits from an image using cv2 and python
Question: I am trying to detect digits located inside a grid and to tell their positions
in an image and don't know where to start. So any help is welcome. So far I
have used GT Text software but it didn't solve the purpose. Any helper
function, libraries, tutorials, links or anything is welcome.
Answer: You should check out the pytesseract module:
<https://pypi.python.org/pypi/pytesseract/0.1>
It has a one-liner for what you're trying to do:
try:
import Image
except ImportError:
from PIL import Image
import pytesseract as tes
results = tes.image_to_string(Image.open('test.png'),boxes=True)
This will give you `results`, which has each digit and the image coordinates
of its bounding box.
You will need to install PIL (python image library, `pip install PIL`) and the
tesseract c library (`brew install tesseract` if you have homebrew..) so it's
not super trivial but once you have it working, this is the most straight
forward OCR in python, and requires no training whatsoever.
|
How can i covert a 3x3 grid from python to tkinter
Question: SO I have this piece of code and it only prints out in the python shell, I
would like to know how I can get the words and put them into a grid using
labels in tkinter. Sorry for my lack of explanation.
import random
with open('Words.txt') as f:
words = random.sample([x.rstrip() for x in f],9)
grid = [words[i:i +3] for i in range(0, len(words),3)]
for x,y,z in grid:
print(x,y,z)
Answer: This should get you started. I generally use pack for my projects. But for
this I would suggest grid because it allows you to position your labels
easily.
import tkinter as tk
words = [['Word 1', 'Word 2', 'Word 3'],\
['Word 4', 'Word 5', 'Word 6'],\
['Word 7', 'Word 8', 'Word 9']]
root = tk.Tk()
for i, (x, y, z) in enumerate(words):
tk.Label(root, text=x).grid(row=i, column=0)
tk.Label(root, text=y).grid(row=i, column=1)
tk.Label(root, text=z).grid(row=i, column=2)
root.mainloop()
|
On Ctrl-d, call Close() like with file objects happen
Question: I've [wrote a
class](https://github.com/srgblnch/scpi/blob/master/scpi/scpi.py) that
inherits from _object_ and has instances of sub-objects that uses some
_threads_ for tasks. There are two socket _listeners_ that creates other
threads for each _accept_ ed connection. They do what they have to do. To
finish them, they are looking on a _Threading.Event_ object to know that they
have to finish.
I've noticed that, when exit the python console they are not notified (or
don't catch the notification) and the exit don't return control to the bash
console, unless a _Close()_ is called before.
First idea to fix it has been to implement the _'__del__'_ method to use the
garbage collector to clean it when exit.
class ServiceProvider(object):
def __init__(self):
super(ServiceProvider,self).__init__()
#...
self.Open()
def Open(self):
#... Some threads are created.
def Close(self):
#.... Threading.Event to report the threads to finish
def __del__(self):
self.Close()
But the behaviour is the same. If I place a print in those methods, non in
_'__del__'_ , neither in _'Close'_ they are written. Unless it is closed
before, then the print in the _del_ is wrote.
Then I've implemented the _'__enter__'_ and _'__exit__'_ methods to manage the
_with_ statement. And the _exit_ behaves as expected and when the _with_ ends,
things are release. But what I really want is to have something like the _file
descriptors_ that event if _file.close()_ is not called, it is executed when
exits the program.
class ServiceProvider(object):
#...
def __enter__(self):
return self
def __exit__(self):
self.Close()
Searching for more solutions I've tried with
[atexit](https://docs.python.org/2/library/atexit.html) but not. I have
similar results that doesn't fix the issue. Even I collect all the objects
created of this class, the _doOnExit_ only writes its print if the objects in
the list are already _Close_.
import atexit
global objects2Close
objects2Close = []
@atexit.register
def doOnExit():
for obj in objects2Close:
obj.Close()
class ServiceProvider(object):
def __init__(self):
super(ServiceProvider,self).__init__()
objects2Close.append(self)
Answer: It's usually a good idea to use `with` when you have resources that you don't
want to leak (files, connections, whatever else you care about).
Somewhere, just outside your main loop you should have something like:
with ServiceProvider(some_params) as service_provider:
rest_of_the_code()
What this does is that regardless of how you exit rest_of_the_code() (except
for kill -9) it will call service_provider.Close() at the end. This works for
exceptions and interrupts as well. Kill -9 doesn't work because the process is
kill at os level and doesn't have a chance to attempt to recover.
|
Progress bar while uploading a file to dropbox
Question:
import dropbox
client = dropbox.client.DropboxClient('<token>')
f = open('/ssd-scratch/abhishekb/try/1.mat', 'rb')
response = client.put_file('/data/1.mat', f)
I want to upload a big file to dropbox. How can I check the progress?
[[Docs]](https://www.dropbox.com/developers-v1/core/docs/python#ChunkedUploader)
EDIT: The uploader offeset is same below somehow. What am I doing wrong
import os,pdb,dropbox
size=1194304
client = dropbox.client.DropboxClient(token)
path='D:/bci_code/datasets/1.mat'
tot_size = os.path.getsize(path)
bigFile = open(path, 'rb')
uploader = client.get_chunked_uploader(bigFile, size)
print "uploading: ", tot_size
while uploader.offset < tot_size:
try:
upload = uploader.upload_chunked()
print uploader.offset
except rest.ErrorResponse, e:
print("something went wrong")
EDIT 2:
size=1194304
tot_size = os.path.getsize(path)
bigFile = open(path, 'rb')
uploader = client.get_chunked_uploader(bigFile, tot_size)
print "uploading: ", tot_size
while uploader.offset < tot_size:
try:
upload = uploader.upload_chunked(chunk_size=size)
print uploader.offset
except rest.ErrorResponse, e:
print("something went wrong")
Answer: `upload_chunked`, as [the
documentation](https://www.dropbox.com/developers-v1/core/docs/python#ChunkedUploader.upload_chunked)
notes:
> Uploads data from this `ChunkedUploader`'s `file_obj` in chunks, until an
> error occurs. Throws an exception when an error occurs, and can be called
> again to resume the upload.
So yes, it uploads the entire file (unless an error occurs) before returning.
If you want to upload a chunk at a time on your own, you should use
[`upload_chunk`](https://www.dropbox.com/developers-v1/core/docs/python#DropboxClient.upload_chunk)
and
[`commit_chunked_upload`](https://www.dropbox.com/developers-v1/core/docs/python#DropboxClient.commit_chunked_upload).
Here's some working code that shows you how to upload a single chunk at a time
and print progress in between chunks:
from io import BytesIO
import os
from dropbox.client import DropboxClient
client = DropboxClient(ACCESS_TOKEN)
path = 'test.data'
chunk_size = 1024*1024 # 1MB
total_size = os.path.getsize(path)
upload_id = None
offset = 0
with open(path, 'rb') as f:
while offset < total_size:
offset, upload_id = client.upload_chunk(
BytesIO(f.read(chunk_size)),
offset=offset, upload_id=upload_id)
print('Uploaded so far: {} bytes'.format(offset))
# Note the "auto/" on the next line, which is needed because
# this method doesn't attach the root by itself.
client.commit_chunked_upload('auto/test.data', upload_id)
print('Upload complete.')
|
Python subprocess check output not working
Question: I'm trying to run my test_script.py in main_script.py with subprocess.
test_script.py is a siple sum program, and main_script.py should call it with
2 arguments, and catch output. Here is the code:
**test_script.py**
a = int(input())
b = int(input())
print(a+b)
**main_script.py**
import subprocess
subprocess.check_output(['python', 'test_script.py', 2,3])
This is the error im getting:
Traceback (most recent call last):
File "C:/Users/John/Desktop/main_script.py", line 2, in <module>
subprocess.check_output(['python', 'test_script.py', 2,3])
File "C:\Python34\lib\subprocess.py", line 607, in check_output
with Popen(*popenargs, stdout=PIPE, **kwargs) as process:
File "C:\Python34\lib\subprocess.py", line 858, in __init__
restore_signals, start_new_session)
File "C:\Python34\lib\subprocess.py", line 1085, in _execute_child
args = list2cmdline(args)
File "C:\Python34\lib\subprocess.py", line 663, in list2cmdline
needquote = (" " in arg) or ("\t" in arg) or not arg
TypeError: argument of type 'int' is not iterable
Answer: All parts of argument must a string. Do the following instead:
subprocess.check_output(['python', 'test_script.py', "2", "3"])
If this command fails to run, you'll get an exception. To catch it and see the
output:
try:
subprocess.check_output(['python', 'test_script.py', "2", "3"], stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
print e.output
Your second script will fail because it's expecting input from the stdin,
while your master script is sending the `2` and `3` as arguments. Investigate
`sys.argv`
|
Which character encoding is the IPython terminal using?
Question: I used to think I had this whole encoding stuff pretty figured out. I seem to
be wrong because I can't explain what's happening here.
What I was trying to do is to use the
[`tabulate`](https://pypi.python.org/pypi/tabulate) module to print a nicely
formatted table using
from tabulate import tabulate
s = tabulate([[1,2],[3,4]], ["x","y"], tablefmt="fancy_grid")
print(s)
in IPython 3.5.0's interactive console under Windows 10. I expected the result
to be
βββββββ€ββββββ
β x β y β
βββββββͺββββββ‘
β 1 β 2 β
βββββββΌββββββ€
β 3 β 4 β
βββββββ§ββββββ
but instead, I got a
UnicodeEncodeError: 'charmap' codec can't encode character '\u2552' in position 0: character maps to <undefined>
Puzzled, I tried to find out where the problem was and looked at the `repr` of
the string:
In [15]: s
Out[15]: 'βββββββ€ββββββ\nβ x β y β\nβββββββͺββββββ‘\nβ 1 β 2 β\nβββββββΌββββββ€\nβ 3 β 4 β\nβββββββ§ββββββ'
Hmm, all the characters _can_ be displayed by the terminal (even the first one
that triggered the error).
Just checking some details:
In [16]: sys.stdout.encoding
Out[16]: 'cp850'
In [17]: s.encode("cp850")
[...]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2552' in position 0: character maps to <undefined>
So which encoding _is_ the terminal using? Python says that it's `cp850`, and
it tells me that `cp850` doesn't have a `β` character ([which is
true](https://en.wikipedia.org/wiki/Code_page_850), it's one of the characters
from `cp437` that had to make room for accented letters), but I can _see_ it
in the terminal window!
To complicate things further, when using the native Python console instead of
IPython, the error seems more understandable:
>>> s
'\u2552βββ\u2564βββ\u2555\nβ 1 β 2 β\nβββββΌββββ€\nβ 3 β 4 β\n\u2558βββ\u2567βββ\u255b'
>>> sys.stdout.encoding
'cp850'
>>> print(s)
Traceback (most recent call last):
[...]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2552' in position 0: character maps to <undefined>
So at least Python is consistent, but what's happening with IPython?
Answer: IPython uses OEM code page in the interactive mode like any other Python
console program:
In [1]: '\u2552'
ERROR - failed to write data to stream: <_io.TextIOWrapper name='<stdout>' mode=
'w' encoding='cp850'>
Out[1]:
In [2]: !chcp
Active code page: 850
The result changes if `pyreadline` is installed (it enables colors in the
IPython console among other things):
In [1]: '\u2552'
Out[1]: 'β'
In [2]: import sys
In [3]: sys.stdout.encoding
Out[3]: 'cp850'
In [4]: !chcp
Active code page: 850
Once `pyreadline` has been installed, IPython's `sys.displayhook` writes the
result to readline's console object that uses `WriteConsoleW()` Windows
Unicode API that allows to print even unencodable in the current code page
Unicode characters (to see them, you might need to configure a (TrueType) font
such as Lucida Console in the Windows console).
|
How to make a variable equate to another variable (Python)
Question: I don't even know how to explain this one.
Question1 = "a"
Question2 = "b"
Question3 = "c"
Question4 = "d"
Question5 = "e"
etc.
Answer1 = "a"
Answer2 = "b"
Answer3 = "c"
Answer4 = "d"
Answer5 = "e"
etc.
questioninteger = random.randint(1,20)
if(questioninteger == 1):
Boolean1 = True
Question == Question1
Answer == Answer1
FlashCard()
if(questioninteger == 2):
Boolean2 = True
Question == Question2
Answer == Answer2
FlashCard()
if(questioninteger == 3):
Boolean3 = True
Question == Question3
Answer == Answer3
FlashCard()
etc.
print("")
print(Question)
print("")
key = raw_input()
if(key == Answer):
print("Correct!")
time.sleep(1)
QuestionPicker()
(all are within functions)
Problem is Python won't change the variable Question, and no error comes up.
'Answer is successfully changed, 'Question' just won't be.
Answer: Global variables are generally a bad idea; you would do well to rewrite your
code to something like
from random import choice
from time import sleep
class Question:
def __init__(self, question, options, answer):
self.question = question
self.options = options
self.answer = answer
def ask(self):
print("\n" + self.question)
for opt in self.options:
print(opt)
response = input().strip()
return (response == self.answer)
# define a list of questions
questions = [
Question("What is 10 * 2?", ["5", "10", "12", "20", "100"], "20"),
Question("Which continent has alligators?", ["Africa", "South America", "Antarctica"], "South America")
]
# ask a randomly chosen question
def ask_a_question(questions):
q = choice(questions)
got_it = q.ask()
sleep(1)
if got_it:
print("Correct!")
else:
print("Sorry, the proper answer is " + q.answer)
|
Image conversion Function using python and open
Question: Recently I have started learning opencv and python for image processing .I am
facing problems with writing a function .
I was given a task as follows:
_Write a function in python to open a color image and convert the image into
grayscale._
_You are required to write a function color_grayscale(filename,g) which takes
two arguments:_
a. filename: a color image (Test color image is in folder βTask1_Practice/test_imagesβ. Pick first image to perform the experiment.)
b. g: an integer
_Output of program should be a grayscale image if g = 1 and a color image
otherwise._
The code i wrote is as follows :
import cv2
def color_grayscale(filename,g):
filename = cv2.imread("a15.jpg")
" Enter Value of g:"
if g == 1:
gray = cv2.cvtColor(filename, cv2.COLOR_BGR2GRAY)
img = cv2.imshow("gray",gray)
else:
img = cv2.imshow("original",filename)
return(img)
color_grayscale("a15.jpg",1)
The code when run gives no output whatsoever.
Answer: `cv2.imshow` should be followed by `waitKey` function which displays the image
for specified milliseconds. Otherwise, it wonβt display the image. For
example, `waitKey(0)` will display the window infinitely until any keypress
(it is suitable for image display). `waitKey(25)` will display a frame for 25
ms, after which display will be automatically closed. (If you put it in a loop
to read videos, it will display the video frame-by-frame)
Just add `cv2.waitKey(0)` before you return `img` and then it will display the
grayscale image
|
Why is the program taking so much time even after threading?
Question: I have been trying to look up for active hosts connected to a gateway with
specific masks, but it is taking a lot of time even after threading. Also the
total host are not showing correct.
CODE is:
import subprocess, sys, threading, time, queue
t = 0
[a,b,c,d] = list(sys.argv[1].split("."))
mask = int(sys.argv[2])
p = queue.Queue()
def alive(host):
reply = str(subprocess.Popen(["ping", "-n","1","-w","5",host],
stdout=subprocess.PIPE).communicate()[0])
if "TTL=" in reply :
if host != sys.argv[1]:
print(host," is UP")
p.put(1)
else:
p.put(0)
else:
p.put(0)
start_time = time.time()
if mask == 8:
for i in range(1,256):
for j in range(1,256):
for k in range(1,256):
iplist = [a,str(i),str(j),str(k)]
ip = '.'.join(iplist)
thread = threading.Thread(target = alive(ip))
thread.start()
elif mask == 16:
for i in range(1,256):
for j in range(1,256):
iplist = [a,b,str(i),str(j)]
ip = '.'.join(iplist)
thread = threading.Thread(target = alive(ip))
thread.start()
elif mask == 24:
for i in range(1,256):
iplist = [a,b,c,str(i)]
ip = '.'.join(iplist)
thread = threading.Thread(target = alive(ip))
thread.start()
else:
print("Mask must be 8 , 16 or 24")
for i in range(p.qsize()):
if p.get == 1:
t+=1
else:
pass
print("\nTotal no. of hosts connected to ",sys.argv[1], " is ",t)
print("Total time taken is ",time.time() - start_time)
COMMAND LINE INPUT:
python uphost.py 192.168.1.1 24
OUTPUT:
192.168.1.20 is UP
192.168.1.30 is UP
Total no. of hosts connected to 192.168.1.1 is 0
Total time taken is 125.90091395378113
Answer: You are creating way over too many threads (256, 256^2, 256^3). And thread
creation has an overhead which you need to balance with the amount of work
each thread is doing.
I think a better solution is to use a Thread pool (see
<https://docs.python.org/2/library/multiprocessing.html#module-
multiprocessing.pool>) with a predetermined number (as many as the number of
threads your machine supports).
|
python, importing function from other file which uses variable in the functions file
Question: I currently have a python program which imports a function from a file, but
this function uses a variable which is stored in the file the functon is
called from.
The code for the main function:
from second_file import second
while True:
print second(param)
The code for the second function:
counter = 0
def second(param):
counter +=1
return param + counter
When running the programm i get the following error:
local variable 'counter' referenced before assignment
So the question is, how can i get the "second" function to use this variable.
Answer: Since you are modifying global variable you need to explicitly state that
using
global counter
counter += 1
Otherwise here variable scope is limited to function and in this function
scope, counter is not defined and hence the error.
|
Python: How to send message to client from server at any time?
Question: I'm building a discussion board style server/client application were the
client connects to the server, is able to post messages, read messages, and
quit.
See client code below:
import socket
target_host = "0.0.0.0"
target_port = 9996
#create socket object
client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#connect the client
client.connect((target_host,target_port))
#receiving user name prompt
print client.recv(1024)
usrname = str(raw_input())
#send username
client.send(usrname)
#check if username was unique
while client.recv(1024) == "NU": #should exit once "ACK" received
print client.recv(1024) #print username promt again
usrname = str(raw_input()) #client enters in another username
client.send(usrname)
#receive user joined message/welcome message/help menu
response = client.recv(1024)
print response
print client.recv(1024)
#loops until client disconnects
while True:
request = str(raw_input("\n\nWhat would you like to do? "))
client.send(request)
if request == "-h":
help_menu = client.recv(1024)
print help_menu
elif request == "-p":
#get subject
subject_request = client.recv(1024)
print subject_request
subject = str(raw_input())
client.send(subject)
#get contents of post
contents_request = client.recv(1024)
print contents_request
contents = str(raw_input())
client.send(contents)
#get post notification
message_post = client.recv(1024)
print message_post
elif request == "-r":
#get id value of post
id_request = client.recv(1024)
print id_request
message_id = str(raw_input())
client.send(message_id)
#get contents of post
message_contents = client.recv(2048)
print message_contents
elif request == "-q":
break
else:
print client.recv(1024)
When a client joins though, I wish to notify all other clients that are
connected that a new client has joined, but each client may be at a different
point in the code (some may be in the middle of a post, sitting idle at the
"what would you like to do?" statement, etc).
So how would I set my client code up that it will be able to accept a message
from the server the moment another client joins?
Answer: There are many ways to do it. Here an overview of how I would.
Are you familiar with
["select"](https://docs.python.org/2/library/select.html) operations? They
allow you to listen on multiple file descriptors and get notified whenever one
becomes active. I would start by using that to both listen for keyboard inputs
and server messages.
Then there are 2 things to be done. Branch depending on the active canal. If
it's a keyboard input you can relay the command to the server. If it's a
server message, you need to branch again on the message type to act
accordingly.
Edit: Never assume what the server message is about. Even though you may have
just sent a query, the server may be sending data about something else.
|
Need to set up a GUI that shows output from Pocketsphinx on Raspberry Pi 2 using Python
Question: I need to set up a GUI that simply shows the output of Pocketsphinx on
Raspberry Pi. I have installed Pocketsphinx and can run it from command line,
but am not quite clear on how to set up the GUI. I have been using Python 2.7,
and have seen online that others have tried importing it? Please help me
figure this out. Thanks,
Answer: There is [pocketsphinx wrapper for
python](https://github.com/cmusphinx/pocketsphinx-python).
|
Python parsing the lines from a file
Question: New to python. I'm reading from file line by line:
with open("graph.txt", "r") as f:
comList = f.readlines()
print(comList)
edge_u = [x[0] for x in comList]
edge_v = [x[1] for x in comList]
graph.txt has :
> [(0, 7), (1, 9), (1, 9), (2, 0)]
>
> [(2, 1), (2, 1), (3, 6)]
I was expecting that readlines will parse the file line by line hence will
parse the text as a list of list. But its parsing it as List of strings. Hence
i;m unable to perform the other two operations. Tried to print edge_u and get
to know what its parsing. How to deal with this? Thanks.
Answer: You may try this:
import ast
with open("test.txt", "r") as f:
for line in f:
li = ast.literal_eval(line)
edge_u = [x[0] for x in li]
edge_v = [x[1] for x in li]
|
compling python 3.5 program with pyinstall - missing tkinter
Question: I am trying to compile a python 3.5 program, which uses tkinter as a GUI. To
do that I am using pyinstall, but I run into a problem during compliation
process I get warning messages" tkinter not found" and the program does not
work afterwards (as a dist version). It seems pyinstaller is looking for
tkinter.py but from what I undersant python 3.x uses __init__py. How should I
proceed compiling this program? I have ran through the documentation on
pyinstaller page, but it wasn't helpful, or I missed something...
[enter image description here](http://i.stack.imgur.com/DbHfl.png)
Answer: You probably need the hidden import feature when compiling. Add the following
as an option when compiling your script: \--hidden-import tkinter
|
Python HTML to Text File UnicodeDecodeError?
Question: So I am writing a program to read a webpage using urllib, then using
"html2text", write the basic text to a file. However, the raw contents given
from urllib.read() has various characters, so it would continuously raise
_UnicodeDecodeError_.
I of course Googled this for 3 hours, got plenty of answers like using
HTMLParser, or reload(sys), using external modules like pdfkit or
BeautifulSoup, and of course .encode/.decode.
Reloading sys and then executing _sys.setdefaultencoding("utf-8")_ grants me
the desired results, but IDLE and the program becomes unresponsive after that.
I tried every variation of the .encode/.decode with 'utf-8' and 'ascii', with
arguments like 'replace', 'ignore', etc. For some reason, it raises the same
error everytime regardless of the arguments I supply in the encode/decode.
def download(self, url, name="WebPage.txt"):
## Saves only the text to file
page = urllib.urlopen(url)
content = page.read()
with open(name, 'wb') as w:
HP_inst = HTMLParser.HTMLParser()
content = content.encode('ascii', 'xmlcharrefreplace')
if True:
#w.write(HTT.html2text( (HP_inst.unescape( content ) ).encode('utf-8') ) )
w.write( HTT.html2text( content) )#.decode('ascii', 'ignore') ))
w.close()
print "Saved!"
There has to be another method or encoding I am missing... Please help!
Side Quest: I sometimes have to write it to a file where the name includes
unsupported chars like _"G\u00e9za Teleki"+".txt"_. How do I filter those
characters out?
Note:
* This function was stored inside a class (hint "self").
* Using python2.7
* Don't want to use BeautfiulSoup
* Windows 8 64-bit
Answer: You should decode the content get from urllib with the properly encoding eg,
utf-8 latin1 depends on the page you get.
The way to detect the encoding of the content are various. From headers or
meta in html. I'd like to use a encoding detective module which I forget the
name, you could google it.
Once you decode it properly, you can encode it to any encoding you like before
write to a file
======================================
Here's the example using [chardet](https://pypi.python.org/pypi/chardet)
import urllib
import chardet
def main():
page = urllib.urlopen('http://bbc.com')
content = page.read()
# detect the encoding
try:
encoding = chardet.detect(content)['encoding']
except:
# use utf-8 as default encoding
encoding = 'utf-8'
# decode the content into unicode
content = content.decode(encoding)
# write to file
with open('test.txt', 'wb') as f:
f.write(content.encode('utf-8'))
|
Got a TypeError of the upload form in Django
Question: Now I want to add a form which is to update the existing lyrics for users.
Here is my code:
urls.py:
from django.conf.urls import url
from . import views
from django.conf import settings
urlpatterns = [
url(r'^$', views.lyric_list, name = 'lyric_list'),
url(r'^lyric/(?P<lyric_id>[0-9]+)/$', views.lyric_detail, name ='lyric_detail'),
url(r'^add_lyric/$', views.add_lyric, name = "add_lyric"),
url(r'^delete/(?P<pk>\d+)$', views.delete_lyric, name = 'delete_lyric'),
url(r'^update/$', views.update_lyric, name = 'update_lyric'),
url(r'^update/(?P<pk>\d+)$', views.update_lyric_page, name = 'update_lyric_page'),]
views.py:
@login_required
def update_lyric(request, pk):
lyric = get_object_or_404(Lyric, pk = pk)
form = LyricForm(request.POST, initial = {'title': lyric.title, 'body': lyric.body})
if lyric:
username = lyric.user.username
if form.is_valid():
title = form.cleaned_data['title']
body = form.cleaned_data['body']
lyric.title = title
lyric.body = body
lyric.save()
update_topic(request.user)
return HttpResponseRedirect(reverse('rap_song:lyric_list'))
return render(request, 'rap_song/update_lyric_page.html',{'pk':pk})
@login_required
def update_lyric_page(request, pk):
lyric = get_object_or_404(Lyric, pk = pk)
form = LyricForm()
return render(request, 'rap_song/update_lyric_page.html', {'pk': pk, 'form':form})
update_lyric_page.html:
<div class = "col-md-6 col-md-offset-3">
<form action="{% url 'rap_song:update_lyric' lyric_id %}" method="post" class="form">
{% csrf_token %}
{% bootstrap_form form layout="inline" %}
{% buttons %}
<button type="submit" class="btn btn-primary">
{% bootstrap_icon "star" %} Edit
</button>
{% endbuttons %}
</form >
But I got a error: TypeError at /rap_song/update/
update_lyric() missing 1 required positional argument: 'pk'
The whole Traceback is as below:
Traceback:
File "/Users/yobichi/wi/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/yobichi/wi/lib/python3.5/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
22. return view_func(request, *args, **kwargs)
Exception Type: TypeError at /rap_song/update/
Exception Value: update_lyric() missing 1 required positional argument: 'pk'
Anyone can help me with this issue? I have been struggling for this issue for
a whole day. Thank you in advance!
Answer: You need to pass the `id` of lyric in the url which needs to be updated:
url(r'^update/(?P<pk>\d+)/$', views.update_lyric, name='update_lyric')
Besides, it looks like you can easily merge `update_lyrics` and
`update_lyrics_page` views into a single view function, so you'll saving an
extra url in **urls.py** :
First, remove the following url as we won't need `update_lyrics_page` anymore:
url(r'^update/(?P<pk>\d+)$', views.update_lyric_page, name='update_lyric_page'),
Then, merge those two views as follows:
@login_required
def update_lyric(request, pk):
lyric = get_object_or_404(Lyric, pk=pk)
username = lyric.user.username
if request.POST:
form = LyricForm(request.POST,
initial={'title': lyric.title, 'body': lyric.body})
if form.is_valid():
title = form.cleaned_data['title']
body = form.cleaned_data['body']
lyric.title = title
lyric.body = body
lyric.save()
update_topic(request.user)
return HttpResponseRedirect(reverse('rap_song:lyric_list'))
else:
return render(request,
'rap_song/update_lyric_page.html',{'pk': pk, 'form': form})
else:
form = LyricForm()
return render(request,
'rap_song/update_lyric_page.html',{'pk': pk, 'form': form})
At last, I don't think you have such a variable named `lyric_id` in the
template. I suspect it should be replaced with `pk` variable that was sent so
that
<form action="{% url 'rap_song:update_lyric' pk %}" ...
will resolve to a url like this:
> `/rap_song/update/1234/`
where `1234` is the id of the lyric object.
|
Trying to add string to float variable in tkinter label/entry widgets
Question: I'm hoping to get some guidance on an issue I've been spending far too much
time trying to solve. Every time I find a solution another problem takes its
place.
My aim is to 'simply' do some basic maths on some figures and then add a '$'
at the start of the float variable.
At first I tried this:
self.paid_main.set("$", self.paid_entry.get())
Error:
TypeError: set() takes 2 positional arguments but 3 were given
I'm obviously missing something here as I thought I gave 2 arguments - "$" and
self.paid_entry.get()
Then I tried:
paid = ("$", self.paid_entry.get())
self.paid_main.set(paid)
This works but gives a horrible looking result on the GUI. Instead of just
placing a dollar sign there, it puts curly braces around it. e.g. {$}
However beggars can't be choosers so I stick with the horrible curly braces
option, until a little bit further down I run into this issue.
total_main = ("$", "%.2f" % self.quantity_entry.get() * self.paid_entry.get() + self.brokerage_entry.get())
self.total_main.set(total_main)
Error:
TypeError: can't multiply sequence by non-int of type 'float'
Again, I must be missing something since when can't you multiply a float?
I can solve all my issues if I choose not to add a dollar sign in front of
anything, but then I'll be settling for second best. I'm hoping someone can
help me with the following questions:
1. What are the 3 positional arguments, as I can only count 2?
2. Is there a way to provision for another argument?
3. Is there a way to add a dollar sign without curly braces?
4. Why am I getting the error trying to multiply a float?
I should note, I have to set the IntVar and DoubleVar variables to an empty
string as leaving it will add 0 and 0.0 respectively to the label coordinates
before I even click on 'add.' Unless there's another way of avoiding this?
Thanks in advance to anyone who can help me.
Full code below:
#!/usr/bin/env python3.4
from tkinter import *
import ystockquote
import urllib.request
from urllib.request import urlopen
from bs4 import BeautifulSoup
import decimal
class Shares(Frame):
def __init__(self, master):
Frame.__init__(self, master)
Frame(self ,width = 500, height = 300)
self.configure()
self.grid()
Label(self, font = "Helvetica 14 bold", text = " Name ").grid(row = 8, column = 1, columnspan = 2, sticky = W, padx = 5, pady = 5)
Label(self, font = "Helvetica 14 bold", text = " Code ").grid(row = 8, column = 3, padx = 5, pady = 5)
Label(self, font = "Helvetica 14 bold", text = " Buy Date ").grid(row = 8, column = 4, padx = 5, pady = 5)
Label(self, font = "Helvetica 14 bold", text = " Quantity ").grid(row = 8, column = 5, padx = 5, pady = 5)
Label(self, font = "Helvetica 14 bold", text = " Paid ").grid(row = 8, column = 6, padx = 5, pady = 5)
Label(self, font = "Helvetica 14 bold", text = " Brokerage ").grid(row = 8, column = 7, padx = 5, pady = 5)
Label(self, font = "Helvetica 14 bold", text = " Total ").grid(row = 8, column = 8, padx = 5, pady = 5)
Label(self, font = "Helvetica 14 bold", text = " Current ").grid(row = 8, column = 9, padx = 5, pady = 5)
Label(self, font = "Helvetica 14 bold", text = " Total ").grid(row = 8, column = 10,padx = 5, pady = 5)
Label(self, font = "Helvetica 14 bold", text = " % Loss/Gain ").grid(row = 8, column = 11, padx = 5, pady = 5)
Button(self, text = "New Record", command = self.dialogue_box).grid(row = 9, column = 0)
def dialogue_box(self):
top = self.top = Toplevel()
Label(top, text = "Code: ").grid(row = 0, column = 0, sticky = E, padx = 5, pady = 5)
Label(top, text = "Buy Date: ").grid(row = 1, column = 0, sticky = E, padx = 5, pady = 5)
Label(top, text = "Quantity: ").grid(row = 2, column = 0, sticky = E, padx = 5, pady = 5)
Label(top, text = "Paid: ").grid(row = 3, column = 0, sticky = E, padx = 5, pady = 5)
Label(top, text = "Brokerage: ").grid(row = 4, column = 0, sticky = E, padx = 5, pady = 5)
self.code_main = StringVar()
Label(self, textvariable = self.code_main).grid(row = 9, column = 3, padx = 5, pady = 5)
self.code_entry = StringVar()
Entry(top, textvariable = self.code_entry).grid(row = 0, column = 1, padx = 5, pady = 5)
self.code_entry.set("")
self.date_main = StringVar()
Label(self, textvariable = self.date_main).grid(row = 9, column = 4, padx = 5, pady = 5)
self.date_main.set("")
self.date_entry = StringVar()
Entry(top, textvariable = self.date_entry).grid(row = 1, column = 1, padx = 5, pady = 5)
self.date_entry.set("")
self.quantity_main = IntVar()
Label(self, textvariable = self.quantity_main).grid(row = 9, column = 5, padx = 5, pady = 5)
self.quantity_main.set("")
self.quantity_entry = IntVar()
Entry(top, textvariable = self.quantity_entry).grid(row = 2, column = 1, padx = 5, pady = 5)
self.quantity_entry.set("")
self.paid_main = DoubleVar()
Label(self, textvariable = self.paid_main).grid(row = 9, column = 6, padx = 5, pady = 5)
self.paid_main.set("")
self.paid_entry = DoubleVar()
Entry(top, textvariable = self.paid_entry).grid(row = 3, column = 1, padx = 5, pady = 5)
self.paid_entry.set("")
self.brokerage_main = DoubleVar()
Label(self, textvariable = self.brokerage_main).grid(row = 9, column = 7, padx = 5, pady = 5)
self.brokerage_main.set("")
self.brokerage_entry = DoubleVar()
Entry(top, textvariable = self.brokerage_entry).grid(row = 4, column = 1, padx = 5, pady = 5)
self.brokerage_entry.set(29.95)
self.total_main = DoubleVar()
Label(self, textvariable = self.total_main).grid(row = 9, column = 8, padx = 5, pady = 5)
self.total_main.set("")
self.current_main = DoubleVar()
Label(self, textvariable = self.current_main).grid(row = 9, column = 9, padx = 5, pady = 5)
self.current_main.set("")
self.total_two_main = DoubleVar()
Label(self, textvariable = self.total_two_main).grid(row = 9, column = 10, padx = 5, pady = 5)
self.total_two_main.set("")
self.loss_gain_main = DoubleVar()
Label(self, textvariable = self.loss_gain_main).grid(row = 9, column = 11, padx = 5, pady = 5)
self.loss_gain_main.set("")
Button(top, text = "Add", command = self.add).grid(row = 5, column = 0)
def add(self):
self.code_main.set(self.code_entry.get())
self.date_main.set(self.date_entry.get())
self.quantity_main.set(self.quantity_entry.get())
paid = ("$", "%.2f" % self.paid_entry.get())
self.paid_main.set(paid)
brokerage = ("$", self.brokerage_entry.get())
self.brokerage_main.set(brokerage)
total_main = ("$", "%.2f" % self.quantity_entry.get() * self.paid_entry.get() + self.brokerage_entry.get())
self.total_main.set(total_main)
self.current_main.set(ystockquote.get_price(self.code_entry.get() + ".AX"))
total_two = (self.current_main.get() * self.quantity_entry.get())
self.total_two_main.set(total_two)
rounded = ((self.total_two_main.get() / self.total_main.get() * 100) - 100)
self.loss_gain_main.set("%.2f" % rounded)
self.top.destroy()
if __name__ == "__main__":
master = Tk()
master.title("Shares program")
app = Shares(master)
master.geometry("1280x550+0+0")
master.mainloop()
Answer: You have to concatenate text using `+` and `str()` if element is not text.
self.paid_main.set( "$" + str(self.paid_entry.get()) )
`self.paid_main` is treated as first argument for `set()`.
* * *
paid = ("$", self.paid_entry.get())
This creates tuple `("$", some_value)` \- it doesn't concatenate elements.
`,` creates tuple or separates arguments in function like `print(args1, args2,
...)`
* * *
It can be one problem: `self.paid_main` is `DoubleVar()` and you can't set
text to it. You have to use `StringVar()` to set text with `$`
* * *
In this
total_main = ("$", "%.2f" % self.quantity_entry.get() * self.paid_entry.get() + self.brokerage_entry.get())
use bracket to calculate value before you use it with `%`
total_main = "$%.2f" % (self.quantity_entry.get()*self.paid_entry.get() + self.brokerage_entry.get())
or
value = self.quantity_entry.get()*self.paid_entry.get() + self.brokerage_entry.get()
total_main = "$%.2f" % value
without brackets Python treads this as
text = "$%.2f" % self.quantity_entry.get()
total_main = text * self.paid_entry.get() + self.brokerage_entry.get()
|
Why python executable opens new window instance when function by multiprocessing module is called on windows
Question: Short Question: Why python executable generated by pyinstaller opens new
window instance when function by multiprocessing module is called on windows
operating system
I have a GUI code written using pyside. Where when we click on simple button
it will calculate factorial in another process (using multiprocessing module).
It works as expected when I run python program. But after I create executable
using PyInstaller and when I run using exe it is creating new window when
function by multiprocessing module gets called. Here is the code and step by
step process to reproduce the issue.
Code:
import sys
import multiprocessing
from PySide import QtGui
from PySide import QtCore
def factorial():
f = 4
r = 1
for i in reversed(range(1, f+1)):
r *= i
print 'factorial', r
class MainGui(QtGui.QWidget):
def __init__(self):
super(MainGui, self).__init__()
self.initGui()
def initGui(self):
b = QtGui.QPushButton('click', self)
b.move(30, 30)
b.clicked.connect(self.onClick)
self.resize(600, 400)
self.show()
def onClick(self):
print 'button clicked'
self.forkProcess()
def forkProcess(self):
p = multiprocessing.Process(target=factorial)
p.daemon = True
p.start()
if __name__ == "__main__":
print 'ok'
app = QtGui.QApplication(sys.argv)
ex = MainGui()
sys.exit(app.exec_())
1. Run the above code using windows command prompt or power shell
pyinstaller.exe gui.py
2. Open the dist/gui/gui.exe (dist\gui\gui.exe). You will have one window opens
[](http://i.stack.imgur.com/gJoIZ.png)
When we click on button **click** it's calculating factorial but create a new
window instance. It's weird. It's not happening when I execute program before
I create executable or on linux. It's only happening when I execute generated
python executable file
The screen shot after I click **click** button
[](http://i.stack.imgur.com/3Y7bH.png)
Answer: If you want to use multiprocessing as a frozen executable, you need to call
`multiprocessing.freeze_support()` at the beginning of your main script. This
will allow multiprocessing to "take over" when it spawns its worker processes.
See also <https://github.com/pyinstaller/pyinstaller/wiki/Recipe-
Multiprocessing>
|
Can't run a linux .sh script with python subprocess?
Question: I am trying:
import subprocess
subprocess.call(["file.sh"])
But I keep getting:
Traceback (most recent call last):
File "project.py", line 85, in <module>
subprocess.call(["file.sh"])
File "/usr/local/lib/python2.7/subprocess.py", line 522, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/local/lib/python2.7/subprocess.py", line 710, in __init__
errread, errwrite)
File "/usr/local/lib/python2.7/subprocess.py", line 1335, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
However when I try and run the script from the shell `bash file.sh` it works.
So I'm confused as to why it doesn't work?
I am not committed to using subprocess so if there are other options please
let me know.
Answer: The `call` function of the `subprocess` package runs the command specified in
arg as a list of strings (to simplify).
To call your file you have put in your script:
import subprocess
subprocess.call(["sh", "file.sh"])
|
Python, Imagemagick, and subprocess call
Question: Trying to use a subprocess call in a python script to run an Imagemagick
command. **I installed imagemagick in /usr/local/Cellar, so I tried two
options** since it looked like it wasn't finding the convert command.
By the way, the 'convert' command is an imagemagick one. :) Here is the part
of my code that directly relates to it.
import sys, os, subprocess, string
tempo = 8; #this is just for sample purposes, in the actual code this variable is imported from a csv file
# test with just captioning one image and not whole loop
subprocess.call('convert rgb10.png -pointsize 50 -draw "text 180,180 ' + str(tempo) + '" rgb10-n.png')
I've also tried
_"subprocess.call('/usr/local/Cellar/imagemagick/6.8.9-8/bin/c...."_ since I
thought it maybe wasn't finding the command.
Also, I **when I run this command in my terminal command line (not in a
script), it works** `(ex: convert rgb298.png -pointsize 50 -draw "text 180,180
'test' " rgb298-n.png)` so I know it must be an issue with my subprocess call.
This is the **error I receive** when I run it:
subprocess.call('/usr/local/Cellar/imagemagick/6.8.9-8/bin/convert rgb10.png -pointsize 50 -draw "text 180,180 ' + str(tempo[9]) + '" rgb10-n.png')
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 470, in call
return Popen(*popenargs, **kwargs).wait()
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 623, in __init__
errread, errwrite)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 1141, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
_NOTE: I also tried subprocess.call('python2.6 convert rgb10.png ..._
Answer: ... And I've gotten it to work, it was silly!
Added , shell=True
subprocess.call('convert rgb10.png -pointsize 50 -draw "text 180,180 ' + str(tempo) + '" rgb10-n.png', shell=True)
and it works now for anyone else running into this issue.
**Except it's NOT actually drawing or taking into the account the variable
'tempo', aka not processing the + str(tempo) + bit**
|
python lxml not showing all content
Question: I am trying to scrape a specific section of a web page, and eventually
calculate word frequency. But I am finding it difficult to get the entire
text. As far as I understand from looking at the HTML code, my script omits
the part of that section that are in a break line but without `<br>` tag. My
code:
import urllib
from lxml import html as LH
import lxml
import requests
scripturl="http://www.springfieldspringfield.co.uk/view_episode_scripts.php?tv-show=the-sopranos&episode=s06e21"
scripthtml=urllib.urlopen(scripturl).read()
scripthtml=requests.get(scripturl)
tree = LH.fromstring(scripthtml.content)
script=tree.xpath('//div[@class="scrolling-script-container"]/text()')
print script
print type(script)
This is the output:
> ["\n\n\n\n \t\t\t ( radio clicks, \r music plays ) \r \r Disc jockey: \r
> New York's classic rock \r q104.", '3.', '
> \r \r Good morning.', " \r I'm jim kerr.", ' \r \r Coming up \r
When I iterate the result only the phrases that follow the /r and are followed
by a comma or double comma.
for res in script:
print res
The output is:
> q104. 3\. Good morning. I'm jim kerr.
I am not confined to lxml, but because I am rather new, I am less familiar
with other methods.
Answer: An lxml element has both a text and tail method. You are searching for text,
but if there is am HTML element embedded in the element (br, for example),
your search for text will only go as deep as the first text the parser gets
from the element's text() method.
try:
script = tree.xpath('//div[@class="scrolling-script-container"]')
print join(" ", (script[0].text(), script[0].tail()))
|
Appending to a list gives 'int' object has no attribute 'append'
Question: My question was to make a python program that fills the main diagonal of a
square matrix with its row number and the right to left diagonal with its
column number. The rest of the elements of the matrix are initialized to the
sum of indexes of the elements.
So I approached this problem with the following code but when ever I tried
running it, it has given the following error:
Traceback (most recent call last):
File "/home/shinigami/prac5.py", line 21, in <module>
a[i].append(p)
AttributeError: 'int' object has no attribute 'append'
Please also Let me know if there is another way to make a 2D List in python
and take input in it from the User!
a=[]
dimen=input('Enter the no of rows you want ? ')
for i in range(dimen):
for j in range(dimen):
i=int(i)
j=int(j)
#print('ENter the value for the',i+1,'row and',j+,'column')
#p=input()
if(j==0):
if (j==i):
a.append(i+1)
else:
a.append(i+j+2)
else:
if ((i+j)==(dimen-1)):
a[i].append(j+1)
else:
p=i+j+2
a[i].append(p)
for i in range(dimen):
for j in range(dimen):
i=int(i)
j=int(j)
print(" ",a[i][j])
print("")
Answer: > `Traceback (most recent call last): File "/home/shinigami/prac5.py", line
> 21, in a[i].append(p) AttributeError: 'int' object has no attribute
> 'append'`
Your variable `a` is a `list` of `int`egers. When you write `a[i].append(...)`
you're trying to call an `append` method on an `int` type, which causes the
error.
Writing `a.append(...)` is fine because `a` is a `list`, but as soon as you
_index_ into the `list`, you're dealing with with the numbers within the list,
and they have no `append` method. For example:
>>> a = [i for i in range(5)]
>>> a
[0, 1, 2, 3, 4]
>>> a.append(5)
>>> a
[0, 1, 2, 3, 4, 5]
>>> a[2].append(6) # won't work!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'append'
Simply make sure you're using the correct types. The logic in your code is
currently very complicated, so you should simplify it.
> Also Let me know is their a another way to make a 2D LIST
You can use list comprehensions. For example:
>>> from pprint import pprint as pp
>>> dim = 2 # take user input here
>>> matrix = [(i, j) for i in range(dim) for j in range(dim)]
>>> pp(matrix)
[(0, 0), (0, 1), (1, 0), (1, 1)]
#
# Index into the matrix as you normally would.
#
>>> matrix[1][0]
0
>>> matrix[1][1]
1
The above was tested using Python3, but you can adapt it to Python2 if
necessary.
|
Python sorting files in a folder error
Question: I have a folder where I have names as
file_1.txt,file_2.txt,file_3.txt,file_10.txt,file_100.txt.
I am reading these files using os.walk.i want print file names in a sorted
order.My code is as follows:
import os
import fnmatch
rootDir = "lecture1"
for root, dirs, files in os.walk(rootDir):
files = sorted(files)
for file in fnmatch.filter(files, '*.wav'):
print os.path.join(rootDir, file)
But the above code is not printing the file in a sorted order.please suggest
me a way so that i can print it in a sorted order as follows:
file_1.txt,file_2.txt,file3_txt,file_10.txt,file_100.txt
Currently its printing
file_1.txt,file_1.txt,file_100.txt,file_2.txt,file_3.txt
Answer: It doesn't sorted the output because
files = sorted(files)
and files is `file_1.txt`, `file_100.txt`, etc.
But as the above example, `file_1.txt` or `file_100.txt` is string, and
`sorted` thinks that `file_2.txt` > `file_100.txt` because `'2'` > `'1'` (note
that `''`).
To explain this more clear:
>>> '2' > '100'
True
>>> 2 > 100
False
>>> int('2') > int('100')
False
>>>
* * *
So you need use regex to get the number, covert it to int use `int()`
function, and then set a sort key like the following code:
import os
import re
import fnmatch
rootDir = "lecture1"
for root, dirs, files in os.walk(rootDir):
files.sort(key=lambda x: int(re.search('file_(\d+)\.txt', x).group(1)))
for file in fnmatch.filter(files, '*.wav'):
print os.path.join(rootDir, file)
|
issue in encoding non-numeric feature to numeric in Spark and Ipython
Question: I am working on something where I have to make predictions for `numeric` data
(monthly employee spending) using `non-numeric` features. I am using `Spark
MLlibs` `Random Forests algorthim`. I have my `features` data in a `dataframe`
which looks like this:
_1 _2 _3 _4
0 Level1 Male New York New York
1 Level1 Male San Fransisco California
2 Level2 Male New York New York
3 Level1 Male Columbus Ohio
4 Level3 Male New York New York
5 Level4 Male Columbus Ohio
6 Level5 Female Stamford Connecticut
7 Level1 Female San Fransisco California
8 Level3 Male Stamford Connecticut
9 Level6 Female Columbus Ohio
Here columns are - `employee level`,`gender`,`city`,`state` and these are my
`features` using which I want to make predictions of employee monthly
spending(the label,in $).
The training label set looks like this:
3528
4958
4958
1652
4958
6528
4958
4958
5528
7000
Since the `features` are in `non-numeric` form so I need to `encode` them to
`numeric`. So I am following [this link](http://fastml.com/converting-
categorical-data-into-numbers-with-pandas-and-scikit-learn/) to encode
`categorical data` into `numbers`. I wrote this code for this (following the
process mentioned in linked article):
import numpy as np
from sklearn.feature_extraction import DictVectorizer as DV
import pandas as pd
def extract(line):
return (line[1],line[2],line[3],line[7],line[9],line[10],line[22])
inputfile = sc.textFile('file1.csv').zipWithIndex().filter(lambda (line,rownum): rownum>0).map(lambda (line, rownum): line)
input_data = (inputfile
.map(lambda line: line.split(","))
.filter(lambda line: len(line) >1 )
.map(extract)) # Map to tuples
(train_data, test_data) = input_data.randomSplit([0.8, 0.2])
# converting RDD to dataframe
train_dataframe = train_data.toDF()
# converting to pandas dataframe
train_pandas = train_dataframe.toPandas()
# filtering features
train_pandas_features = train_pandas.iloc[:,:6]
# filtering label
train_pandas_label = train_pandas.iloc[:,6]
train_pandas_features_dict = train_pandas_features.T.to_dict().values()
# encoding features to numeric
vectorizer = DV( sparse = False )
vec_train = vectorizer.fit_transform( train_pandas_features_dict )
When I do `print vec_train` all I see is `0.` in all features columns.
Something like this:
[[ 0. 0. 0. ..., 0. 0. 0.]
[ 0. 0. 0. ..., 0. 0. 0.]
[ 0. 0. 0. ..., 0. 0. 0.]
...,
[ 0. 0. 0. ..., 0. 0. 0.]
[ 0. 0. 0. ..., 0. 0. 0.]
[ 0. 0. 0. ..., 0. 0. 0.]]
I think somewhere I am making some mistake because of which this `encoding` is
not producing correct result. What mistake am I doing? And is there some other
better way to `encode` `non-numeric` `features` to `numeric` for the case I
described at the top(predicting numeric monthly expenditure based on non-
numeric employee data)?
Answer: Generally speaking if you have data that can be processed using Pandas data
frames and `scikit-learn` using Spark seems to be a serious overkill. Still,
if you do it probably make more sense to use Spark tools all the way. Lets
start with indexing your features:
from pyspark.ml.feature import StringIndexer
from pyspark.ml.pipeline import Pipeline
from pyspark.ml.feature import VectorAssembler
label_col = "x3" # For example
# I assume this comes from your previous question
df = (rdd.map(lambda row: [row[i] for i in columns_num])
.toDF(("x0", "x1", "x2", "x3")))
# Indexers encode strings with doubles
string_indexers = [
StringIndexer(inputCol=x, outputCol="idx_{0}".format(x))
# For classifications problems
# - if you want to use ML you should index label as well
# - if you want to use MLlib it is not necessary
# For regression problems you should omit label in the indexing
# as shown below
for x in df.columns if x not in {label_col} # Exclude other columns if needed
]
# Assembles multiple columns into a single vector
assembler = VectorAssembler(
inputCols=["idx_{0}".format(x) for x in df.columns if x != label_col],
outputCol="features"
)
pipeline = Pipeline(stages=string_indexers + [assembler])
model = pipeline.fit(df)
indexed = model.transform(df)
Pipeline defined above will create following data frame:
indexed.printSchema()
## root
## |-- x0: string (nullable = true)
## |-- x1: string (nullable = true)
## |-- x2: string (nullable = true)
## |-- x3: string (nullable = true)
## |-- idx_x0: double (nullable = true)
## |-- idx_x1: double (nullable = true)
## |-- idx_x2: double (nullable = true)
## |-- features: vector (nullable = true)
where `features` should be a valid input for `mllib.tree.DecisionTree` (see
[SPARK: How to create categoricalFeaturesInfo for decision trees from
LabeledPoint?](http://stackoverflow.com/q/33956720/1560062)).
You can create label points out of it as follows:
from pyspark.mllib.regression import LabeledPoint
from pyspark.sql.functions import col
label_points = (indexed
.select(col(label_col).alias("label"), col("features"))
.map(lambda row: LabeledPoint(row.label, row.features)))
|
Print a big integer with punctions with Python3 string formating mini-language
Question: I want a point after each three digits in a big number (e.g. `4.100.200.300`).
>>> x = 4100200300
>>> print('{}'.format(x))
4100200300
This question is specific to Pythons string formating mini-language.
Answer: There's only one available thousands separator.
> The `','` option signals the use of a comma for a thousands separator.
([docs](https://docs.python.org/3/library/string.html#format-specification-
mini-language))
Example:
'{:,}'.format(x) # 4,100,200,300
If you need to use a dot as a thousand separator, consider replacing commas
with `'.'` or setting the locale (_LC_NUMERIC_ category) appropriately.
You could use [this](http://lh.2xlibre.net/values/thousands_sep/) list to find
the right locale. Note that you'll have to use the `n` integer presentation
type for locale-aware formatting:
import locale
locale.setlocale(locale.LC_NUMERIC, 'de_DE') # or da_DK, or lt_LT, or mn_MN, or ...
'{:n}'.format(x) # 4.100.200.300
In my opinion, the former approach is much simpler:
'{:,}'.format(x).replace(',', '.') # 4.100.200.300
or
format(x, ',').replace(',', '.') # 4.100.200.300
|
hide chromeDriver console in python
Question: I'm using chrome driver in Selenium to open chrome , log into a router, press
some buttons ,upload configuration etc. all code is written in Python.
here is the part of the code to obtain the driver:
chrome_options = webdriver.ChromeOptions()
prefs = {"download.default_directory": self.user_local}
chrome_options.add_experimental_option("prefs", prefs)
chrome_options.experimental_options.
driver = webdriver.Chrome("chromedriver.exe", chrome_options=chrome_options)
driver.set_window_position(0, 0)
driver.set_window_size(0, 0)
return driver
when i fire up my app, i get a chromedriver.exe console (a black window)
followed by a chrome window opened and all my requests are done.
**My question** : is there a way in python to hide the console window ?
(as you can see i'm also re-sizing the chrome window ,my preference would be
doing things in a way the user wont notice anything happening on screen)
thanks Sivan
Answer: While launching chrome browser not seeing chromedriver console with the given
sample code.
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from time import sleep
options = webdriver.ChromeOptions()
prefs = {"download.default_directory": r"C:\New_Download"}
options.add_experimental_option("prefs", prefs)
print(options.experimental_options)
chromeDriverPath = r'C:\drivers\chromedriver.exe'
driver = webdriver.Chrome(chromeDriverPath,chrome_options=options)
driver.get("http://google.com")
driver.set_window_position(0, 0)
driver.set_window_size(0, 0)
|
lambda in for loop only takes last value
Question: **Problemset:**
Context Menu should show filter variables dynamically and execute a function
with parameters defined inside the callback. Generic descriptions show
properly, but function call is always executed with last set option.
**What I have tried:**
#!/usr/bin/env python
import Tkinter as tk
import ttk
from TkTreectrl import MultiListbox
class SomeClass(ttk.Frame):
def __init__(self, *args, **kwargs):
ttk.Frame.__init__(self, *args, **kwargs)
self.pack(expand=True, fill=tk.BOTH)
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
self.View=MultiListbox(self)
__columns=("Date","Time","Type","File","Line","-","Function","Message")
self.View.configure(columns=__columns, expandcolumns=(0,0,0,0,0,0,0,1))
self.View.bind("", self.cell_context)
self.View.grid(row=0, column=0, sticky=tk.NW+tk.SE)
self.__recordset = []
self.__recordset_filtered = False
#Some dummy values
self.__recordset.append(["Date", "Time", "INFO", "File", "12", "-", "Function", "Message Info"])
self.__recordset.append(["Date", "Time", "DEBUG", "File", "12", "-", "Function", "Message Info"])
self.__recordset.append(["Date", "Time", "WARNING", "File", "12", "-", "Function", "Message Info"])
self.__refresh()
def cleanView(self):
self.View.delete(0, tk.END)
def __refresh(self):
self.cleanView()
for row in self.__recordset:
self.View.insert(tk.END, *row)
def filter_records(self, column, value):
print("Filter Log Recordset by {column} and {value}".format(**locals()))
# Filter functionality works as expected
# [...]
def cell_context(self, event):
__cMenu=tk.Menu(self, tearoff=0)
if self.__recordset_filtered:
__cMenu.add_command(label="Show all", command=lambda: filter_records(0, ""))
else:
column=2
options=["INFO", "WARNING", "DEBUG"]
for i in range(len(options)):
option=options[i]
__cMenu.add_command(label="{}".format(option), command=lambda: self.filter_records(column, option))
# Also tried using for option in options here with same result as now
__cMenu.post(event.x_root, event.y_root)
if __name__=="__main__":
root=tk.Tk()
app=SomeClass(root)
root.mainloop()
The current output i get is:
> Filter Log Recordset by 2 and DEBUG
No matter which of the three options i choose. I assume it has sth to do with
the garbage collection that only the last option remains but i cannot figure
out how to avoid this.
Any help is recommended.
Answer: Please read about [minimal examples](https://stackoverflow.com/help/mcve).
Without reading your code, I believe you have run into a well known issue
addressed in previous questions and answers that needs 2 lines to illustrate.
Names in function bodies are evaluated when the function is executed.
funcs = [lambda: i for i in range(3)]
for f in funcs: print(f())
prints '2' 3 times because the 3 functions are identical and the 'i' in each
is not evaluated until the call, when i == 2. However,
funcs = [lambda i=i:i for i in range(3)]
for f in funcs: print(f())
makes three different functions, each with a different captured value, so 0,
1, and 2 are printed. In your statement
__cMenu.add_command(label="{}".format(option),
command=lambda: self.filter_records(column, option))
add `option=option` before `:` to capture the different values of `option`.
You might want to rewrite as
lambda opt=option: self.filter_records(column, opt)
to differentiate the loop variable from the function parameter. If `column`
changed within the loop, it would need the same treatment.
|
Python List interpretation (w/ Turtles)
Question: Little python question, how to make the turtle move according to `[(160, 20),
(-43, 10), (270, 8), (-43, 12)]` where the first number is the angle turned
and the second is distance traveled.
My attempt:
print('Question 11')
import turtle
wn = turtle.Screen()
wn.bgcolor("hot pink")
tess = turtle.Turtle()
tess.shape("turtle")
tess.color("blue")
def path(x):
for a, b in len(x): # Not so sure about this line.
tess.forward(a)
tess.right(b)
l = [(160, 20), (-43, 10), (270, 8), (-43, 12)]
path(l)
wn.mainloop()
Errors I have gotten:
> TypeError: 'list' object cannot be interpreted as an integer
and
> TypeError: 'int' object is not iterable
Answer: I'm not familiar with turtle, but the follow line:
for a, b in len(x): # Not so sure about this line.
this line is wrong: x as the follow code means a list. len(x) returns an
integer, but integer is not iterable.
which you means:
for a, b in x:
instead your code.
|
Import a Python module when using WSGI
Question: I just installed WSGI on Apache to start using Python as a web programming
language. I only added this line to my Apache config (except for the loading
of the `mod_wsgi` module)
WSGIScriptAlias MyApp/ /path/to/app.wsgi
I have my `app.wsgi` running fine, but I want to use separate files for
separate functionality. So, I created an `extras.py` in the same dir as
`app.wsgi`, with not much in it:
class MyClass:
pass
and put a
from extras import MyClass
on the top of my `app.wsgi`. But, unfortunately, I get this error:
ImportError: cannot import name MyClass
Am I missing something?
Answer: use the `WSGIPythonPath` to specify the modules which are to be searched while
running ur wsgi application.
more about it could be found
[here](https://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIPythonPath
"mod_wsgi")
|
Python context manager that measures time
Question: I am struggling to make a piece of code that allows to measure time spent
within a "with" statement and assigns the time measured (a float) to the
variable provided in the "with" statement.
import time
class catchtime:
def __enter__(self):
self.t = time.clock()
return 1
def __exit__(self, type, value, traceback):
return time.clock() - self.t
with catchtime() as t:
pass
This code leaves `t=1` and not the difference between clock() calls. How to
approach this problem? I need a way to assign a new value from within the exit
method.
[PEP 343 describes](https://www.python.org/dev/peps/pep-0343/) in more detail
how contect manager works but I do not understand most of it.
Answer: You can't get that to assign your timing to `t`. As described in the PEP, the
variable you specify in the `as` clause (if any) gets assigned the result of
calling `__enter__`, not `__exit__`. In other words, `t` is only assigned at
the _start_ of the `with` block, not at the end.
What you could do is change your `__exit__` so that instead of returning the
value, it does `self.t = time.clock() - self.t`. Then, after the `with` block
finishes, the `t` attribute of the context manager will hold the elapsed time.
To make that work, you also want to return `self` instead of `1` from
`__enter__`. Not sure what you were trying to achieve by using `1`.
So it looks like this:
class catchtime(object):
def __enter__(self):
self.t = time.clock()
return self
def __exit__(self, type, value, traceback):
self.t = time.clock() - self.t
with catchtime() as t:
time.sleep(1)
print(t.t)
And a value pretty close to 1 is printed.
|
Interactive labels on nodes using python and networkx
Question: I am trying to make a graph using python with networkx which has many nodes
that can be interactively investigated. I want to be able to click or hover
above a node and reveal a label which is otherwise not shown.
[D3](http://d3js.org/) seems able to do this well, and there are a couple of
python implementations
[mpld3](http://mpld3.github.io/examples/scatter_tooltip.html)
and
[Drew Conway's Networkx fork](https://github.com/drewconway/networkx)
mpld3 works fine for scatter plots but I don't know how to get it to do what I
want for a graph...
implementing [ example code ](http://drewconway.com/zia/2013/3/26/visualizing-
networkx-graphs-in-the-browser-using-d3) from Drew Conway:
import networkx as nx
from networkx.readwrite import d3_js
gives
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name d3_js
This looks like an error which might have resulted if the forked networkx
package was not placed in python's system path....However, I checked the sys
path contents and found networkx...so I'm stumped.
Answer: It looks like mpld3 will work. You can get the scatter data by calling
`draw_networkx_nodes()` which is just a wrapper for `scatter()`.
import matplotlib.pyplot as plt
import numpy as np
import mpld3
import networkx as nx
G = nx.path_graph(4)
pos = nx.spring_layout(G)
fig, ax = plt.subplots(subplot_kw=dict(axisbg='#EEEEEE'))
scatter = nx.draw_networkx_nodes(G, pos, ax=ax)
nx.draw_networkx_edges(G, pos, ax=ax)
labels = G.nodes()
tooltip = mpld3.plugins.PointLabelTooltip(scatter, labels=labels)
mpld3.plugins.connect(fig, tooltip)
mpld3.show()
|
python distance formula coordinate plane error
Question: My goal is to make a circle shape out of lines in pygame, using random
endpoints around the edge of a circle and a constant starting point (the
middle of the circle). So I decided that I would give the pygame.draw.line
function: screen, aRandomColor, startingPosition, and endingPosition as
arguments. Ending position is a tuple containing a randomly generated x value,
and a helper function will calculate the y value based on the radius of the
circle. My first function calculates the y value like this:
import math
import random
def findY(pos1, pos2, distance, bothValues=False):
p1 =pos1
p2 = pos2
x1 = float(p1[0])
y1 = float(p1[1])
x2 = float(p2[0])
d = float(distance)
y2 = y1 - math.sqrt(d**2 - (x1-x2)**2)
_y2 = y1 + math.sqrt(d**2 - (x1-x2)**2)
if bothValues==True:
return y2, _y2
else:
return y2
and the line drawer:
width = 500
height = 500
def randLine(surface, color=rand, start=rand, end=rand,length=rand):
if start==rand:
start = randPos()
if end==rand:
end = randPos()
if color==rand:
color = randColor()
if length != rand:
end_x = float(random.randint(0,width))
end_pos = (end_x, "y")
y2=findMissing(start_pos, end_pos,l,bothValues=True)
a = random.randint(0,1)
if a==0:
y2 = float(y2[0])
else:
y2 = float(y2[1])
lst = list(end_pos)
lst[1] = y2
end_pos = tuple(lst)
pygame.draw.line(surface, color, start_pos, end_pos)
Then:
drawRandLine(screen,start=(200,200),lenght=100)
(the other functions that those ones called like randPos aren't the problem).
This for some reason generated an error that I diagnosed as the value inside
the math.sqrt() was a negative number. But that can't happen, since every
value in there is raised to power of 2, and thats what I'm confused about. So
I changed the value inside math.sqrt() to its absolute value. This made the
function not raise any errors, but the circle drawn looked like this:
[](http://i.stack.imgur.com/FibfJ.png)
I know that pygame's coordinate plane's y values upside down, but should that
make a difference?
Answer: One way of getting a a uniform distribution of angles would be to generate a
random angle `theta` between `0` and `2 * math.pi`, and use trigonometry to
find the co-ordinates of the end point of the line:
def drawRandLineTrig(start_pos, length):
theta = random.rand() * 2 * math.pi
end_pos = (start_pos[0] + length*math.cos(theta), start_pos[1] + length*math.sin(theta))
# ...
|
Map object is not JSON serializable
Question: This happens when returning a `JSONResponse`, which was added in Django 1.7.
and is a wrapper around `json.dumps`. However, in this case it results in an
error. I'm sure the data is correct and can be serialized to JSON through
Python shell.
What is the right way to serialize the data to JSON?
from django.http import JsonResponse
from collections import OrderedDict
data = OrderedDict([('doc', '546546545'), ('order', '98745'), ('nothing', '0.0')])
return JsonResponse(data) # doesn't work, JSONRenderer().render(data) works
Results in this error:
<map object at 0x7fa3435f3048> is not JSON serializable
`print(data)` gives:
`OrderedDict([('doc', '546546545'), ('order', '98745'), ('nothing', '0.0')])`
Answer: `map()` in Python 3 is a generator function, which is not serializeable in
JSON. You can make it serializeable by converting it to a list:
from django.http import JsonResponse
from collections import OrderedDict
def order(request):
bunch = OrderSerializer(Order.objects.all(), many=True)
headers = bunch.data[0].keys()
# consume the generator and convert it to a list here
headers_prepared = list(map(lambda x: {'data': x} , headers))
ordered_all = (('columns', headers_prepared), ('lines', bunch.data))
data = OrderedDict(ordered_all)
return JsonResponse(data)
|
How to run two non-terminating scripts in parallel in a GUI?
Question: I know I can easily do this manually by opening two terminal windows. I am
trying to automate the process as much as possible by creating a GUI with two
buttons. One to connect and run the listener, and one to run the talker.
This is my code:
#python 3
#from tkinter import *
#from tkinter import ttk
#python 2
from Tkinter import *
import ttk
import time
import subprocess
import paramiko
def calculate(*args):
try:
value = float(feet.get())
meters.set((0.3048 * value * 10000.0 + 0.5)/10000.0)
except ValueError:
pass
def connect():
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.1.2', username='pi', password='raspberry')
stdin, stdout, stderr = ssh.exec_command('cd')
stdin, stdout, stderr = ssh.exec_command('roscore &')
time.sleep(20)
stdin, stdout, stderr = ssh.exec_command('\n')
stdin, stdout, stderr = ssh.exec_command('cd scripts')
stdin, stdout, stderr = ssh.exec_command('python /home/pi/scripts/listener2.py')
return
def run():
stdin, stdout, stderr = ssh.exec_command('python ES96_Vivaldi/talker2.py')
root = Tk()
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)
ttk.Button(mainframe, text="Connect", command=connect).grid(column=1, row=3, sticky=S)
ttk.Button(mainframe, text="Run", command=run).grid(column=3, row=3, sticky=S)
ttk.Label(mainframe, text="Click 'Connect' to establish link.").grid(column=1, row=1, sticky=W)
ttk.Label(mainframe, text="Click 'Run' to control using the arrow keys").grid(column=1, row=2, sticky=W)
for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5)
root.mainloop()
It opens a small GUI with a Connect button and a Run button. Connect works
fine but since the listener2.py script doesn't terminate, the GUI freezes and
I can't press the Run button (same problem when trying in the opposite order).
Is there a way to start a script and leave it running in the background so
that the GUI isn't frozen and I can start the next script?
Thank you!
Answer: You can run the handlers in background threads. In your current setup, the
handlers don't give any feedback to the gui, so its really just a matter of
switching the button commands to functions that start the threads.
I added a bit of code to disable the buttons so the handlers can only be
started once. The trick there is that you need some place to store the button
widgets so that you can access them again later.
#python 3
#from tkinter import *
#from tkinter import ttk
#python 2
from Tkinter import *
import ttk
import time
import subprocess
import paramiko
import threading
# keep track of widgets for event handlers
widget_track = {}
# event handler creates connect thread
def connect_evt():
t = threading.Thread(target=connect)
t.daemon = True
t.start()
widget_track['connect'].config(text="Connected", state="disabled", command=None)
def connect():
time.sleep(5) # todo: temporary for test
return
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.1.2', username='pi', password='raspberry')
stdin, stdout, stderr = ssh.exec_command('cd')
stdin, stdout, stderr = ssh.exec_command('roscore &')
time.sleep(20)
stdin, stdout, stderr = ssh.exec_command('\n')
stdin, stdout, stderr = ssh.exec_command('cd scripts')
stdin, stdout, stderr = ssh.exec_command('python /home/pi/scripts/listener2.py')
return
# event handler creates run thread
def run_evt():
t = threading.Thread(target=run)
t.daemon = True
t.start()
widget_track['run'].config(text="Running", state="disabled", command=None)
def run():
time.sleep(5) # todo: temporary for test
return
stdin, stdout, stderr = ssh.exec_command('python ES96_Vivaldi/talker2.py')
root = Tk()
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)
# connect button starts connect background thread
btn = ttk.Button(mainframe, text="Connect", command=connect_evt)
btn.grid(column=1, row=3, sticky=S)
widget_track['connect'] = btn
# run button start run background thread
btn = ttk.Button(mainframe, text="Run", command=run_evt)
btn.grid(column=3, row=3, sticky=S)
widget_track['run'] = btn
ttk.Label(mainframe, text="Click 'Connect' to establish link.").grid(column=1, row=1, sticky=W)
ttk.Label(mainframe, text="Click 'Run' to control using the arrow keys").grid(column=1, row=2, sticky=W)
for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5)
root.mainloop()
|
CentOS 6.7, python distutils and bloody brp-python-bytecompile
Question: I am trying to get python distutils to build me an RPM. This is proving to be
very difficult tho!
On my mac everything works fine, but on CentOS 6.7 (my CI server) it doesn't
due to the differences RPMs are built for different platforms.
On CentOS `.py` files are being precompiled by `rpm/brp-python-bytecompile`.
This creates `.pyc` and `.pyo` files, that are not listed by `bdist_rpm` and
thus I get an error!
I have found [this issue](http://bugs.python.org/issue1533164) and [this
issue](https://bugzilla.redhat.com/show_bug.cgi?id=236535), but they are from
long long time ago! So I am surprised I still see this happening! Is there any
work-around? I do not want to have to create spec file, I use bdist_rpm to
avoid it... Thanks.
Here is example structure of the stuff I am trying to package:
<root>/
setup.py
my-awesome-app.py
help-scripts/
extract-config.py
Here is my setup.py:
from distutils.core import setup
setup(name='my-awesome-app',
version='1.0',
author='Daniel Gruszczyk',
scripts=['my-awesome-app.py'],
data_files=[('/etc/bake',['help-scripts/extract-config.py'])],
)
Here is example output from running `python setup.py bdist_rpm` (just lines
leading to error):
+ /usr/lib/rpm/find-debuginfo.sh --strict-build-id /var/lib/jenkins/workspace/my-awesome-app/build/bdist.linux-x86_64/rpm/BUILD/my-awesome-app-1.0
+ /usr/lib/rpm/check-buildroot
+ /usr/lib/rpm/redhat/brp-compress
+ /usr/lib/rpm/redhat/brp-strip-static-archive /usr/bin/strip
+ /usr/lib/rpm/redhat/brp-strip-comment-note /usr/bin/strip /usr/bin/objdump
+ /usr/lib/rpm/brp-python-bytecompile
+ /usr/lib/rpm/redhat/brp-python-hardlink
+ /usr/lib/rpm/redhat/brp-java-repack-jars
Processing files: my-awesome-app-1.0-1.noarch
Requires(rpmlib): rpmlib(CompressedFileNames) <= 3.0.4-1 rpmlib(FileDigests) <= 4.6.0-1 rpmlib(PayloadFilesHavePrefix) <= 4.0-1
Requires: /var/lib/jenkins/.pyenv/versions/2.7.5/bin/python
Checking for unpackaged file(s): /usr/lib/rpm/check-files /var/lib/jenkins/workspace/my-awesome-app/build/bdist.linux-x86_64/rpm/BUILDROOT/my-awesome-app-1.0-1.x86_64
error: Installed (but unpackaged) file(s) found:
/etc/help-scripts/extract-config.pyc
/etc/help-scripts/extract-config.pyo
I think the `+ /usr/lib/rpm/brp-python-bytecompile` line is the issue (given
the links I included). Is there any way to get rid of this crap, as it seems
to cause problems all around?
Answer: Those bugs are old, but so is CentOS6.
Bdist_rpm is very simple and once you reach its limit, you are in dead end.
And I'm really afraid no one will tell you how to fix it using setup.py. More
on this topic is written here: <http://ziade.org/2011/03/25/bdist_rpm-is-dead-
long-life-to-py2rpm/>
I really recommend you to use: pyp2rpm - <https://github.com/fedora-
python/pyp2rpm>
|
NameError: name "webdriver" is not defined
Question: I have create a python script which requires the webdrive. In my code I have
imported it like so, `from selenium import webdriver`.
I went to their website
[here](https://pypi.python.org/pypi/selenium#downloads) downloaded and ran
setup.py but still does not import it. I don't know if this helps but I have
python 2.7, I also do not have installed pip.
Answer: This means that you have installed `selenium`, but interpreter can not find
`webdriver` folder inside. Please use :
import selenium
selenium.__file__
in `Python2.7` shell to find out a path to exact `selenium` folder that you
import. If it not located in `C:\Python27\Lib\site-packages` (default Windows
path for new package installation) then delete it or rename (if you don't
really need it). Or just download `selenium` from another source
|
Removing Characters from python Output
Question: I did alot of work to remove the characters from the spark python output like
**u u' u" [()/'"** which are creating problem for me to do the further work.
So please put a focus on the same .
I have the input like,
(u"(u'[25145, 12345678'", 0.0)
(u"(u'[25146, 25487963'", 43.0) when i applied code to summing out the result. this gives me the output like
(u'(u"(u\'[54879, 5125478\'"', 0.0)
(u"(u'[25145, 25145879'", 11.0)
(u'(u"(u\'[56897, 22548793\'"', 0.0) so i want to remove all the character like (u'(u"(u\'["'')
I want output like
54879,5125478,0.0
25145,25145879,11.0
the code is i tried is
from pyspark import SparkContext
import os
import sys
sc = SparkContext("local", "aggregate")
file1 = sc.textFile("hdfs://localhost:9000/data/first/part-00000")
file2 = sc.textFile("hdfs://localhost:9000/data/second/part-00000")
file3 = file1.union(file2).coalesce(1).map(lambda line: line.split(','))
result = file3.map(lambda x: ((x[0]+', '+x[1],float(x[2][:-1])))).reduceByKey(lambda a,b:a+b).coalesce(1)
result.saveAsTextFile("hdfs://localhost:9000/Test1")
Answer: I think your only problem is that you have to reformat you result before
saving it to the file, i.e. something like:
result.map(lambda x:x[0]+','+str(x[1])).saveAsTextFile("hdfs://localhost:9000/Test1")
|
Error in Reading a csv file in pandas[CParserError: Error tokenizing data. C error: Buffer overflow caught - possible malformed input file.]
Question: So i tried reading all the csv files from a folder and then concatenate them
to create a big csv(structure of all the files was same), save it and read it
again. All this was done using Pandas. The Error occurs while reading. I am
Attaching the code and the Error below.
import pandas as pd
import numpy as np
import glob
path =r'somePath' # use your path
allFiles = glob.glob(path + "/*.csv")
frame = pd.DataFrame()
list_ = []
for file_ in allFiles:
df = pd.read_csv(file_,index_col=None, header=0)
list_.append(df)
store = pd.concat(list_)
store.to_csv("C:\work\DATA\Raw_data\\store.csv", sep=',', index= False)
store1 = pd.read_csv("C:\work\DATA\Raw_data\\store.csv", sep=',')
Error:-
CParserError Traceback (most recent call last)
<ipython-input-48-2983d97ccca6> in <module>()
----> 1 store1 = pd.read_csv("C:\work\DATA\Raw_data\\store.csv", sep=',')
C:\Users\armsharm\AppData\Local\Continuum\Anaconda\lib\site-packages\pandas\io\parsers.pyc in parser_f(filepath_or_buffer, sep, dialect, compression, doublequote, escapechar, quotechar, quoting, skipinitialspace, lineterminator, header, index_col, names, prefix, skiprows, skipfooter, skip_footer, na_values, na_fvalues, true_values, false_values, delimiter, converters, dtype, usecols, engine, delim_whitespace, as_recarray, na_filter, compact_ints, use_unsigned, low_memory, buffer_lines, warn_bad_lines, error_bad_lines, keep_default_na, thousands, comment, decimal, parse_dates, keep_date_col, dayfirst, date_parser, memory_map, float_precision, nrows, iterator, chunksize, verbose, encoding, squeeze, mangle_dupe_cols, tupleize_cols, infer_datetime_format, skip_blank_lines)
472 skip_blank_lines=skip_blank_lines)
473
--> 474 return _read(filepath_or_buffer, kwds)
475
476 parser_f.__name__ = name
C:\Users\armsharm\AppData\Local\Continuum\Anaconda\lib\site-packages\pandas\io\parsers.pyc in _read(filepath_or_buffer, kwds)
258 return parser
259
--> 260 return parser.read()
261
262 _parser_defaults = {
C:\Users\armsharm\AppData\Local\Continuum\Anaconda\lib\site-packages\pandas\io\parsers.pyc in read(self, nrows)
719 raise ValueError('skip_footer not supported for iteration')
720
--> 721 ret = self._engine.read(nrows)
722
723 if self.options.get('as_recarray'):
C:\Users\armsharm\AppData\Local\Continuum\Anaconda\lib\site-packages\pandas\io\parsers.pyc in read(self, nrows)
1168
1169 try:
-> 1170 data = self._reader.read(nrows)
1171 except StopIteration:
1172 if nrows is None:
pandas\parser.pyx in pandas.parser.TextReader.read (pandas\parser.c:7544)()
pandas\parser.pyx in pandas.parser.TextReader._read_low_memory (pandas\parser.c:7784)()
pandas\parser.pyx in pandas.parser.TextReader._read_rows (pandas\parser.c:8401)()
pandas\parser.pyx in pandas.parser.TextReader._tokenize_rows (pandas\parser.c:8275)()
pandas\parser.pyx in pandas.parser.raise_parser_error (pandas\parser.c:20691)()
CParserError: Error tokenizing data. C error: Buffer overflow caught - possible malformed input file.
I tried using csv reader as well:-
import csv
with open("C:\work\DATA\Raw_data\\store.csv", 'rb') as f:
reader = csv.reader(f)
l = list(reader)
Error:-
Error Traceback (most recent call last)
<ipython-input-36-9249469f31a6> in <module>()
1 with open('C:\work\DATA\Raw_data\\store.csv', 'rb') as f:
2 reader = csv.reader(f)
----> 3 l = list(reader)
Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode?
Answer: Not an answer, but too long for a comment (not speaking of code formatting)
As it breaks when you read it in csv module, you can at least locate the line
where the error occurs:
import csv
with open(r"C:\work\DATA\Raw_data\store.csv", 'rb') as f:
reader = csv.reader(f)
linenumber = 1
try:
for row in reader:
linenumber += 1
except Exception as e:
print (("Error line %d: %s %s" % (linenumber, str(type(e)), e.message)))
Then look in store.csv what happens at that line.
|
Convert exception to string in Python 2.7
Question:
import httplib
webservice = httplib.HTTPSConnection(host)
# ....
try:
webservice.endheaders()
except Exception, exc:
handle_failure(request, exc_str=unicode(exc))
The exception contains:
> error(110, 'Die Wartezeit f\xc3\xbcr die Verbindung ist abgelaufen')
Don't ask me why this message is in German.
The `uncode(exc)` fails like this:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 27:
ordinal not in range(128)
What is the failsafe way to convert an exception to a string in Python 2.7?
Definition of failsafe in this context: I must not get a UnicodeError. The
expection goes to the logs. It is ok if non-ascii characters get lost.
Answer: Add `errors='replace'` or `errors='ignore'` parameter to the `unicode`
function.
The following text is from
[this](https://docs.python.org/2/howto/unicode.html#the-unicode-type)
documentation:
> The `errors` argument specifies the response when the input string canβt be
> converted according to the encodingβs rules. Legal values for this argument
> are βstrictβ (raise a `UnicodeDecodeError` exception), βreplaceβ (add
> U+FFFD, βREPLACEMENT CHARACTERβ), or βignoreβ (just leave the character out
> of the Unicode result). The following examples show the differences:
>
>
> $ unicode('\x80abc', errors='strict')
> Traceback (most recent call last):
> ...
> UnicodeDecodeError: 'ascii' codec can't decode byte 0x80 in position 0:
> ordinal not in range(128)
> $ unicode('\x80abc', errors='replace')
> u'\ufffdabc'
> $ unicode('\x80abc', errors='ignore')
> u'abc'
>
|
importing module with same name as file
Question: I want to import logging <https://docs.python.org/3/library/logging.html> into
a document named logging.py . When I try to import logging.handlers though, it
fails because I believe it's searching the document for a handlers function,
instead of importing from the module. How can I fix this so it will look for
the higher level logging instead of looking inside the file?
Answer: You can do it by removing current directory (first in sys.path) from python
path:
import sys
sys.path = sys.path[1:]
import logging
print dir(logging)
test:
$ python logging.py
['BASIC_FORMAT', 'BufferingFormatter', 'CRITICAL', 'DEBUG', 'ERROR',
'FATAL', 'FileHandler', 'Filter', 'Filterer', 'Formatter', 'Handler',
'INFO', 'LogRecord', 'Logger', 'LoggerAdapter', 'Manager', 'NOTSET',
'NullHandler', 'PlaceHolder', 'RootLogger', 'StreamHandler', 'WARN',
'WARNING', '__all__', '__author__', '__builtins__', '__date__',
'__doc__', '__file__', '__name__', '__package__', '__path__',
'__status__', '__version__', '_acquireLock', '_addHandlerRef',
'_checkLevel', '_defaultFormatter', '_handlerList', '_handlers',
'_levelNames', '_lock', '_loggerClass', '_releaseLock',
'_removeHandlerRef', '_showwarning', '_srcfile', '_startTime',
'_unicode', '_warnings_showwarning', 'addLevelName', 'atexit',
'basicConfig', 'cStringIO', 'captureWarnings', 'codecs', 'critical',
'currentframe', 'debug', 'disable', 'error', 'exception', 'fatal',
'getLevelName', 'getLogger', 'getLoggerClass', 'info', 'log',
'logMultiprocessing', 'logProcesses', 'logThreads', 'makeLogRecord',
'os', 'raiseExceptions', 'root', 'setLoggerClass', 'shutdown', 'sys',
'thread', 'threading', 'time', 'traceback', 'warn', 'warning',
'warnings', 'weakref']
|
Indexing through a list in python
Question: I have a list that I'm trying to loop through and index the number of each
number in the list. The total list is around 1500-2000 numbers where each
number represents subject behavior. I imported the list of numbers via an
excel sheet:
import openpyxl
from openpyxl import load_workbook
wb = load_workbook('/data.xlsx')
ws = wb['bhv.TrialError']
trialerror10_22=[]
for column in ws.columns:
for cell in column:
trialerror10_22=(cell.value)
print(trialerror10_22)
This all works fine and well and prints out my 1500 or so numbers in a list.
Next I try to index the numbers, which range from 0 to 9 and are associated
with the labels in this order:
labels = ['C','NR', 'LR', 'BF', 'NF', 'ER', 'IR', 'LB', 'I', 'A']
def bhvread(trialerror10_22):
test=False
results = [0] * (max(data) + 1)
for val in data:
results[val] +=1
return results
for index, val in enumerate(results):
print(index, labels[index], val)
But when I run this part it says `Index Error: list index out of range` and
points to the last line of my code.
Output:
0 C 1
1 NR 0
2 LR 0
3 BF 0
4 NF 0
5 ER 0
6 IR 0
7 LB 0
8 I 0
9 A 0
Answer: **Update 2:**
If I understand you correctly you want to do something like:
data = [0, 1, 2, 0, 1, 0, 9, 8]
#dictionary keeping track of our number counters
results = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0}
labels = ['C', 'NR', 'LR', 'BF', 'NF', 'ER', 'IR', 'LB', 'I', 'A']
for x in data:
#is the data valid?
if x >= 0 and x < 10:
results[x] += 1 #increment the correct entry in the dict
#print everything
for i in range(10):
print(i, labels[i], results[i])
**output**
0 C 3
1 NR 2
2 LR 1
3 BF 0
4 NF 0
5 ER 0
6 IR 0
7 LB 0
8 I 1
9 A 1
**Original:**
The problem is definitely with `labels[index]`.
If `len(results)` is greater than 10 you will run into troubles on the tenth
iteration.
**Example:**
results = [1,2,3,4,5,6,7,8,9,10,11]
#len(results) = 11
#first run
index v
results [1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11]
labels ['C','NR', 'LR', 'BF', 'NF', 'ER', 'IR', 'LB', 'I', 'A']
#second run
index v
results [1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11]
labels ['C','NR', 'LR', 'BF', 'NF', 'ER', 'IR', 'LB', 'I', 'A']
#More runs
#tenth run
index v
results [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11]
labels ['C','NR', 'LR', 'BF', 'NF', 'ER', 'IR', 'LB', 'I', 'A']
#eleventh run
index v
results [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11]
labels ['C','NR', 'LR', 'BF', 'NF', 'ER', 'IR', 'LB', 'I', 'A'] #INDEX ERROR!!!
It is pretty unclear what you try to accomplish but I hope this gets you on
the right track.
**Update:**
As @Elzell said you may want to use `itertools.cycle`
import itertools
#...
labels_iterator = itertools.cycle(labels)
for index, val in enumerate(results):
print(index, labels_iterator.next() , val)
|
Telnet from inside a telnet session (Python)
Question: I am trying to telnet to a remote device from another remote device, doing a
nested telnet using telnetlib. While I can easily communicate with the first
device, I am not able to get the output from the second device. Below is my
code, am I doing this correctly?
import telnetlib
HOST = "firstDevice"
user = "lab"
password = "lab"
tn = telnetlib.Telnet(HOST)
tn.read_until("Username: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
#Nested telnet
tn2 = telnetlib.Telnet("secondDevice")
tn2.read_until("#")
tn2.write("sh clock\n")
#Close tn2
tn2.write("exit\n")
print tn2.read_all()
#Close tn
tn.write("exit\n")
print tn.read_all()
**Edit 1**
import telnetlib
HOST = "firstDevice"
user = "lab"
password = "lab"
tn = telnetlib.Telnet(HOST)
tn.read_until("Username: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
#Nested telnet
tn.write("telnet secondDevice\n")
tn.write("sh clock\n")
#Close nested session
tn.write("exit\n")
#Close tn
tn.write("exit\n")
print tn.read_all()
Answer: You are not doing a nested connection in your code. You are just connecting to
two different computers from localhost, but apparently you can not actually
connect to the second one. To do a nested Telnet to the second host, you have
to tell the first one to telnet to the second one: replace `tn2 =
telnetlib.Telnet("secondDevice")` with
tn.write("telnet secondDevice\n")
Since you have a nested connection, all your localhost should see is `tn`. You
can get rid of the `tn2` object entirely. All interaction with the second
device will be done by sending strings to the first device, which is in a
session connected to the second device.
|
Theano -- Unresolved symbol when multiplying two matrices. All works for vectors and tensor3
Question: When I try to run the following code:
a = T.matrix('a')
b = T.matrix('b')
f = theano.function([a, b], T.batched_dot(a,b))
f([[1, 2], [5, 6]],[[3,4],[7,8]])
I get the following error and stack trace:
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-13-42cb5508791b> in <module>()
1 a = T.matrix('a')
2 b = T.matrix('b')
----> 3 f = theano.function([a, b], T.batched_dot(a,b))
4 f([[1, 2], [5, 6]],[[3,4],[7,8]])
/usr/local/lib/python2.7/dist-packages/theano/compile/function.pyc in function(inputs, outputs, mode, updates, givens, no_default_updates, accept_inplace, name, rebuild_strict, allow_input_downcast, profile, on_unused_input)
264 allow_input_downcast=allow_input_downcast,
265 on_unused_input=on_unused_input,
--> 266 profile=profile)
267 # We need to add the flag check_aliased inputs if we have any mutable or
268 # borrowed used defined inputs
/usr/local/lib/python2.7/dist-packages/theano/compile/pfunc.pyc in pfunc(params, outputs, mode, updates, givens, no_default_updates, accept_inplace, name, rebuild_strict, allow_input_downcast, profile, on_unused_input)
509 return orig_function(inputs, cloned_outputs, mode,
510 accept_inplace=accept_inplace, name=name, profile=profile,
--> 511 on_unused_input=on_unused_input)
512
513
/usr/local/lib/python2.7/dist-packages/theano/compile/function_module.pyc in orig_function(inputs, outputs, mode, accept_inplace, name, profile, on_unused_input)
1464 profile=profile,
1465 on_unused_input=on_unused_input).create(
-> 1466 defaults)
1467
1468 t2 = time.time()
/usr/local/lib/python2.7/dist-packages/theano/compile/function_module.pyc in create(self, input_storage, trustme)
1322 theano.config.traceback.limit = 0
1323 _fn, _i, _o = self.linker.make_thunk(
-> 1324 input_storage=input_storage_lists)
1325 finally:
1326 theano.config.traceback.limit = limit_orig
/usr/local/lib/python2.7/dist-packages/theano/gof/link.pyc in make_thunk(self, input_storage, output_storage)
517 def make_thunk(self, input_storage=None, output_storage=None):
518 return self.make_all(input_storage=input_storage,
--> 519 output_storage=output_storage)[:3]
520
521 def make_all(self, input_storage, output_storage):
/usr/local/lib/python2.7/dist-packages/theano/gof/vm.pyc in make_all(self, profiler, input_storage, output_storage)
895 storage_map,
896 compute_map,
--> 897 no_recycling))
898 if not hasattr(thunks[-1], 'lazy'):
899 # We don't want all ops maker to think about lazy Ops.
/usr/local/lib/python2.7/dist-packages/theano/scan_module/scan_op.pyc in make_thunk(self, node, storage_map, compute_map, no_recycling)
592 name=self.name,
593 profile=profile,
--> 594 on_unused_input='ignore')
595
596 try:
/usr/local/lib/python2.7/dist-packages/theano/compile/function.pyc in function(inputs, outputs, mode, updates, givens, no_default_updates, accept_inplace, name, rebuild_strict, allow_input_downcast, profile, on_unused_input)
264 allow_input_downcast=allow_input_downcast,
265 on_unused_input=on_unused_input,
--> 266 profile=profile)
267 # We need to add the flag check_aliased inputs if we have any mutable or
268 # borrowed used defined inputs
/usr/local/lib/python2.7/dist-packages/theano/compile/pfunc.pyc in pfunc(params, outputs, mode, updates, givens, no_default_updates, accept_inplace, name, rebuild_strict, allow_input_downcast, profile, on_unused_input)
509 return orig_function(inputs, cloned_outputs, mode,
510 accept_inplace=accept_inplace, name=name, profile=profile,
--> 511 on_unused_input=on_unused_input)
512
513
/usr/local/lib/python2.7/dist-packages/theano/compile/function_module.pyc in orig_function(inputs, outputs, mode, accept_inplace, name, profile, on_unused_input)
1464 profile=profile,
1465 on_unused_input=on_unused_input).create(
-> 1466 defaults)
1467
1468 t2 = time.time()
/usr/local/lib/python2.7/dist-packages/theano/compile/function_module.pyc in create(self, input_storage, trustme)
1322 theano.config.traceback.limit = 0
1323 _fn, _i, _o = self.linker.make_thunk(
-> 1324 input_storage=input_storage_lists)
1325 finally:
1326 theano.config.traceback.limit = limit_orig
/usr/local/lib/python2.7/dist-packages/theano/gof/link.pyc in make_thunk(self, input_storage, output_storage)
517 def make_thunk(self, input_storage=None, output_storage=None):
518 return self.make_all(input_storage=input_storage,
--> 519 output_storage=output_storage)[:3]
520
521 def make_all(self, input_storage, output_storage):
/usr/local/lib/python2.7/dist-packages/theano/gof/vm.pyc in make_all(self, profiler, input_storage, output_storage)
895 storage_map,
896 compute_map,
--> 897 no_recycling))
898 if not hasattr(thunks[-1], 'lazy'):
899 # We don't want all ops maker to think about lazy Ops.
/usr/local/lib/python2.7/dist-packages/theano/sandbox/cuda/__init__.pyc in make_thunk(self, node, storage_map, compute_map, no_recycling)
257 enable_cuda=False)
258 return super(GpuOp, self).make_thunk(node, storage_map,
--> 259 compute_map, no_recycling)
260
261 theano.compile.debugmode.default_make_thunk.append(
/usr/local/lib/python2.7/dist-packages/theano/gof/op.pyc in make_thunk(self, node, storage_map, compute_map, no_recycling)
737 logger.debug('Trying CLinker.make_thunk')
738 outputs = cl.make_thunk(input_storage=node_input_storage,
--> 739 output_storage=node_output_storage)
740 fill_storage, node_input_filters, node_output_filters = outputs
741
/usr/local/lib/python2.7/dist-packages/theano/gof/cc.pyc in make_thunk(self, input_storage, output_storage, keep_lock)
1071 cthunk, in_storage, out_storage, error_storage = self.__compile__(
1072 input_storage, output_storage,
-> 1073 keep_lock=keep_lock)
1074
1075 res = _CThunk(cthunk, init_tasks, tasks, error_storage)
/usr/local/lib/python2.7/dist-packages/theano/gof/cc.pyc in __compile__(self, input_storage, output_storage, keep_lock)
1013 input_storage,
1014 output_storage,
-> 1015 keep_lock=keep_lock)
1016 return (thunk,
1017 [link.Container(input, storage) for input, storage in
/usr/local/lib/python2.7/dist-packages/theano/gof/cc.pyc in cthunk_factory(self, error_storage, in_storage, out_storage, keep_lock)
1440 else:
1441 module = get_module_cache().module_from_key(
-> 1442 key=key, lnk=self, keep_lock=keep_lock)
1443
1444 vars = self.inputs + self.outputs + self.orphans
/usr/local/lib/python2.7/dist-packages/theano/gof/cmodule.pyc in module_from_key(self, key, lnk, keep_lock)
1074 try:
1075 location = dlimport_workdir(self.dirname)
-> 1076 module = lnk.compile_cmodule(location)
1077 name = module.__file__
1078 assert name.startswith(location)
/usr/local/lib/python2.7/dist-packages/theano/gof/cc.pyc in compile_cmodule(self, location)
1352 lib_dirs=self.lib_dirs(),
1353 libs=libs,
-> 1354 preargs=preargs)
1355 except Exception, e:
1356 e.args += (str(self.fgraph),)
/usr/local/lib/python2.7/dist-packages/theano/sandbox/cuda/nvcc_compiler.pyc in compile_str(module_name, src_code, location, include_dirs, lib_dirs, libs, preargs, rpaths, py_module)
432 #touch the __init__ file
433 open(os.path.join(location, "__init__.py"), 'w').close()
--> 434 return dlimport(lib_filename)
/usr/local/lib/python2.7/dist-packages/theano/gof/cmodule.pyc in dlimport(fullpath, suffix)
291 importlib.invalidate_caches()
292 t0 = time.time()
--> 293 rval = __import__(module_name, {}, {}, [module_name])
294 t1 = time.time()
295 import_time += t1 - t0
ImportError: ('The following error happened while compiling the node', for{gpu,scan_fn}(Elemwise{minimum,no_inplace}.0, GpuSubtensor{int64:int64:int8}.0, GpuSubtensor{int64:int64:int8}.0, Elemwise{minimum,no_inplace}.0), '\n', 'The following error happened while compiling the node', GpuAlloc{memset_0=True}(CudaNdarrayConstant{0.0}, TensorConstant{1}), '\n', '/home/alex/.theano/compiledir_Linux-3.13--generic-x86_64-with-Ubuntu-14.04-trusty-x86_64-2.7.6-64/tmppLzatX/e0c22e1de788a177e13f39a93c579f18.so: undefined symbol: _Z17CudaNdarray_SIZEtPK11CudaNdarray', '[GpuAlloc{memset_0=True}(CudaNdarrayConstant{0.0}, TensorConstant{1})]')
If I replace `matrix` with `vector` or `tensor3` (and supply properly shaped
tensors to the function call), it compiles and runs. For `matrix` none of
`dot`, `tensor_dot`, `batched_dot` work, but addition and subtraction work.
I ran `pip install --upgrade theano`, and the errors stayed. `pip` reports my
current version to be `0.7`. Since it only fails for matrices, could it be
because of some library `theano` depends on that I somehow happen to have
misconfigured?
Answer: What I did wrong was `pip install --upgrade theano`. Turned out I already had
theano 0.7, which is the latest, so `pip install --upgrade` did nothing (but
it was not apparent because it did upgrade the dependencies).
`pip uninstall theano && pip install theano` fixed the problem
|
Uploading a zip file in python flask without form
Question: I'm trying to upload a zip file to my server using python flask request and
then unzip it using zipfile module.
Here is my code:
@app.route('/uoload', methods=['POST'])
def upload ():
data = request.data
current_path = os.getcwd()
filename = "file.zip"
with open(os.path.join(upload_path, filename), 'w') as file:
file.write(data)
try:
with zipfile.ZipFile(os.path.join(current_path + filename)) as zf:
zf.extractall(os.path.join(upload_path))
except BadZipfile as e:
print e
return "", 406
But it seems like the uploaded file is damaged somehow. Because when i'm
trying to unzip it, BadzipFile exception occurs and it says : "Bad magic
number for file header" .
Answer: The problem seems to be that you are using `open` to create a zip archive.
When you use `open`, python will create write the data to the file and will
name it like you wanted. That doesn't make it a zip archive. That is why it
fails to extract data from the file.
If you want to create a zip archive use:
import zipfile
zf = zipfile.ZipFile('file.zip', mode='w')
zf.write('add_this_file_to_zip_archive.txt')
zf.close()
|
iPython/jupyter qtconsole fails to start in anaconda 2.4.0
Question: After upgrading Anaconda3 (32-bit) from version 2.3.0 to 2.4.0 (by
reinstalling Anaconda) on my Windows 7 64-bit machine, the iPython/jupyter
qtconsole fails to start: when executing `jupyter-qtconsole.exe` or `jupyter-
qtconsole-script.py`, the following error appears:
Traceback (most recent call last):
File "C:\Anaconda3\Scripts\jupyter-qtconsole-script.py", line 1, in <module>
from qtconsole.qtconsoleapp import main
File "C:\Anaconda3\lib\site-packages\qtconsole\qtconsoleapp.py", line 45, in <module>
from qtconsole.qt import QtCore, QtGui
File "C:\Anaconda3\lib\site-packages\qtconsole\qt.py", line 23, in <module>
QtCore, QtGui, QtSvg, QT_API = load_qt(api_opts)
File "C:\Anaconda3\lib\site-packages\qtconsole\qt_loaders.py", line 285, in load_qt
result = loaders[api]()
File "C:\Anaconda3\lib\site-packages\qtconsole\qt_loaders.py", line 192, in import_pyqt4
from PyQt4 import QtGui, QtCore, QtSvg
ImportError: DLL load failed: The specified procedure could not be found.
The qtconsole still works in an Anaconda 2.3.0 environment I created. After
comparing the `.\Lib\site-packages\PyQt4` directories of both the 2.3.0 and
2.4.0 environments, I noticed that the latter is missing all the Qt dll's and
Qt directories. After a quick search, I discovered the Qt dll's are now
located in `C:\Anaconda3\Library\bin`. This directory is also set in the
system PATH environment variable, but the problem is still there. How to solve
this issue?
Answer: After copying QtCore4.dll and QtGui4.dll from `C:\Anaconda3\Library\bin` to
`.\Lib\site-packages\PyQt4`, as suggested
[here](http://stackoverflow.com/a/5869748/1504026 "here"), I got the qtconsole
going again. However, this is not a very elegant solution.
|
Python Requests - Azure Graph API Authentication
Question: I am trying to access the Azure AD Graph API using the Python requests
library. My steps are to first get the authorization code. Then, using the
authorization code, I request an access token/refresh token and then finally
query the API.
When I go through the browser, I am able to get my authorization code. I copy
that over to get the access token. However, I've been unable to do the same
with a Python script. I'm stuck at the part where I get the authorization
code.
My script returns a response code of 200, but the response headers don't
include that field. I would've expected the new URL with the code to be in the
response headers. I would have also expected a response code of 301.
Does anyone know why my response headers don't have the auth code? Also, given
the auth code, how would I pull it out to then get the access/refresh tokens
using Python?
My code is below:
import requests
s = requests.Session()
s.auth = (USERNAME, PASSWORD)
# Authorize URL
authorize_url = 'https://login.microsoftonline.com/%s/oauth2/authorize' % TENANT_ID
# Token endpoint.
token_url = 'https://login.microsoftonline.com/%s/oauth2/token' % TENANT_ID
payload = { 'response_type': 'code',
'client_id': CLIENT_ID,
'redirect_uri': REDIRECT_URI
}
request = s.get(authorize_url, json=payload, allow_redirects=True)
print request.headers
Answer: This blog post shows how to properly authenticate against the Azure REST API
using Python:
<http://blogs.msdn.com/b/shwetasblogs/archive/2015/10/21/authentication-with-
azure-ad-for-azure-resource-manager-the-multitenant-app-approach.aspx>. The
MSDN documentation, which is not Python specific is here:
<https://msdn.microsoft.com/en-us/library/azure/dn790557.aspx>.
|
CSV file with random double quotes
Question: I have a CSV file that has a double quote character in some fields. When
parsing with Python, it begins ignoring the delimiter in between these quotes.
For instance:
5695|258|03/21/2012| 15:16:02.000|info|Microsoft-Windows-Defrag|shrink estimation, (C:)|36|"6ybSr: c{q6: |Application|WKS-WIN732test.test.local|http://schemas.microsoft.com/win/2004/08/events/event|0x0080000000000000|0|0||0|0|C:\Users\test\EventLog\win7-32-test-c-drive\Application.evtx
5770|258|03/24/2012| 04:21:02.000|info|Microsoft-Windows-Defrag|boot optimization, (C:)|36|00 00 00 00 d3 03 00 00 ae 03 00 00 00 00 00 00 22 b6 30 df 64 79 c7 f6 e2 6c 1c 00 00 00 00 00 00 00 00 00|Application|WKS-WIN732test.test.local|http://schemas.microsoft.com/win/2004/08/events/event|0x0080000000000000|0|0||0|0|C:\Users\test\EventLog\win7-32-test-c-drive\Application.evtx
5843|258|03/27/2012| 07:38:36.000|info|Microsoft-Windows-Defrag|boot optimization, (C:)|36|jbg54t5t"gfb:*&hgfh|Application|WKS-WIN732test.test.local|http://schemas.microsoft.com/win/2004/08/events/event|0x0080000000000000|0|0||0|0|C:\Users\test\EventLog\win7-32-test-c-drive\Application.evtx
As such, it reads everything between the two double quotes as a single field:
5695|258|03/21/2012| 15:16:02.000|info|Microsoft-Windows-Defrag|shrink estimation, (C:)|36|"6ybSr: c{q6: |Application|WKS-WIN732test.test.local|http://schemas.microsoft.com/win/2004/08/events/event|0x0080000000000000|0|0||0|0|C:\Users\test\EventLog\win7-32-test-c-drive\Application.evtx
^
5770|258|03/24/2012| 04:21:02.000|info|Microsoft-Windows-Defrag|boot optimization, (C:)|36|00 00 00 00 d3 03 00 00 ae 03 00 00 00 00 00 00 22 b6 30 df 64 79 c7 f6 e2 6c 1c 00 00 00 00 00 00 00 00 00|Application|WKS-WIN732test.test.local|http://schemas.microsoft.com/win/2004/08/events/event|0x0080000000000000|0|0||0|0|C:\Users\test\EventLog\win7-32-test-c-drive\Application.evtx
5843|258|03/27/2012| 07:38:36.000|info|Microsoft-Windows-Defrag|boot optimization, (C:)|36|jbg54t5t"gfb:*&hgfh|Application|WKS-WIN732test.test.local|http://schemas.microsoft.com/win/2004/08/events/event|0x0080000000000000|0|0||0|0|C:\Users\test\EventLog\win7-32-test-c-drive\Application.evtx
^
(see the carets (`^`) in above example).
How do I get it to ignore the double quote?
**CAVEAT: I do not want to read the entire file into RAM and replace the
character. The solution must work while iterating through rows from the
reader.**
The delimiter is the pipe. I read it using standard CSV techniques and decode
it with known encoding:
import csv
known_encoding = 'utf-8' # for mwe, real code fetches for each file
with open(self.current_file.file_path, 'rb') as f:
reader = csv.reader(f, delimiter='|')
for row in reader:
row = [s.decode(known_encoding) for s in row]
# do stuff with data in row
Answer: I _guess_ your CSV files never contains quoted fields, so you can switch that
off using the `quoting` parameter:
csv.reader(f, delimiter='|', quoting=csv.QUOTE_NONE)
|
Django get class from string
Question: I'm looking for a generic way in Python to instantiate class by its name in
similar way how it is done in Java without having to explicitly specify the
class name in IF..ELIF condition.
This is because I have several different models and serializers and want to
make them addressable by parameters in the HTTP request. It is to enhance
loose coupling and modularity.
For example `https://www.domain.com/myapp/sampledata.json?model=<modelname>`
should get the classes `<modelname>` and `<modelname>Serializer`.
There are some changes to this since Django 1.7
`https://docs.djangoproject.com/en/1.7/ref/models/queries/`, before
`get_model` was used for similar purpose.
> As of Django 1.7 the django.db.models.loading is deprecated (to be removed
> in 1.9) in favor of the the new application loading system.
The warning:
> RemovedInDjango19Warning: The utilities in django.db.models.loading are
> deprecated in favor of the new application loading system.
> return f(*args, **kwds)
How should the following code be modified to get class from string?
views.py
from myapp.models import Samplemodel, Simplemodel1, Simplemodel2
from myapp.serializers import SamplemodelSerializer, Simplemodel1Serializer, Simplemodel2Serializer
from django.db.models.loading import get_model # deprecated
from myapp.jsonp_decorator import json_response
@json_response
def sampledata(request):
model = request.GET.get('model','Samplemodel')
if model=='Samplemodel':
modelName = "Samplemodel"
serializer = SamplemodelSerializer
elif model=='Simplemodel1':
modelName = "Simplemodel1"
serializer = Simplemodel1Serializer
elif model=='Simplemodel2':
modelName = "Simplemodel2"
serializer = Simplemodel2Serializer
return serializer(get_model("myapp",modelName).objects.all(), many=True)
Answer: You could use `getattr`:
import my_serializers
serializer_class = getattr(my_serializers, 'SimpleSerializer')
serializer = serializer_class()
|
UDP connection do not receive any reply from server - Python (potentially also c++ using boost)
Question: I am trying to establish a connection to a server, and send some data to it.. The problem is that, if i try to debug the connection using this MICHAEL SIEGENTHALER | TCP/UDP Debugging Tools which clearly shows that there is no issue with the communication, and even some form of random input will result in a data coming out.
but when i try to code it in python, using the same settings, are no response
received.. It stalls after it has sent the message, i am not sure whether
whether it has send the message, or skipped it?
It seems like my server aren't receiving the message i sent to it, and
therefore don't reply.. but what is different?
import socket #for sockets
import sys #for exit
# create dgram udp socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
except socket.error:
print ('Failed to create socket')
sys.exit()
host = 'localhost';
port = 5634;
while(1) :
try :
#Set the whole string
s.sendto(("-1-117230").encode('utf-8'),('10.2.140.183', 9008))
print("sent")
# receive data from client (data, addr)
d = s.recvfrom(1024)
reply = d[0]
addr = d[1]
print ('Server reply : ' + reply)
except socket.error as msg:
print ('Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
sys.exit()
[](http://i.stack.imgur.com/5jD17.png)
what is different from the code, and the way the debugging tool test it?
I tried to code it in c++ using boost, but as i had the same issue, i went on
to trying in python to see whether that would make a bit more sense.
\---Updated --
import socket #for sockets
import sys #for exit
# create dgram udp socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_adress = ('10.2.140.183',5634)
s.bind(server_adress)
except socket.error:
print ('Failed to create socket')
sys.exit()
while(1) :
try :
#Set the whole string
s.sendto(("-1-117230").encode('utf-8'),('10.2.140.183', 9008))
print("sent")
# receive data from client (data, addr)
d = s.recvfrom(1024)
reply = d[0]
addr = d[1]
print ('Server reply : ' + reply)
except socket.error as msg:
print ('Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
sys.exit()
Answer: You are missing the
[binding](https://docs.python.org/3.5/library/socket.html#socket.socket.bind)
method.
This is kind of an echo server:
import socket
import sys
host = ''
port = 8888
buffersize = 1
server_address = (host, port)
socket_UDP = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
socket_UDP.bind(server_address)
while True:
data, from_address = socket_UDP.recvfrom(buffersize)
if data:
socket_UDP.sendto(bytes("b"*buffersize, "utf-8"), from_address)
socket_UDP.close()
|
scikit-neuralnetwork mismatch error in dataset size
Question: I'm trying to train an MLP classifier for the XOR problem using sknn.mlp
from sknn.mlp import Classifier, Layer
X=numpy.array([[0,1],[0,0],[1,0]])
print X.shape
y=numpy.array([[1],[0],[1]])
print y.shape
nn=Classifier(layers=[Layer("Sigmoid",units=2),Layer("Sigmoid",units=1)],n_iter=100)
nn.fit(X,y)
This results in:
No handlers could be found for logger "sknn"
Traceback (most recent call last):
File "xorclassifier.py", line 10, in <module>
nn.fit(X,y)
File "/usr/local/lib/python2.7/site-packages/sknn/mlp.py", line 343, in fit
return super(Classifier, self)._fit(X, yp)
File "/usr/local/lib/python2.7/site-packages/sknn/mlp.py", line 179, in _fit
X, y = self._initialize(X, y)
File "/usr/local/lib/python2.7/site-packages/sknn/mlp.py", line 37, in _initialize
self._create_specs(X, y)
File "/usr/local/lib/python2.7/site-packages/sknn/mlp.py", line 64, in _create_specs
"Mismatch between dataset size and units in output layer."
AssertionError: Mismatch between dataset size and units in output layer.
Answer: Scikit seems to turn your `y` vector into a binary vector of shape
(n_samples,n_classes). n_classes is in your case two. So try
nn=Classifier(layers=[Layer("Sigmoid",units=2),Layer("Sigmoid",units=2)],n_iter=100)
|
Reconcile np.fromiter and multidimensional arrays in Python
Question: I love using `np.fromiter` from `numpy` because it is a resource-lazy way to
build `np.array` objects. However, it seems like it doesn't support
multidimensional arrays, which are quite useful as well.
import numpy as np
def fun(i):
""" A function returning 4 values of the same type.
"""
return tuple(4*i + j for j in range(4))
# Trying to create a 2-dimensional array from it:
a = np.fromiter((fun(i) for i in range(5)), '4i', 5) # fails
# This function only seems to work for 1D array, trying then:
a = np.fromiter((fun(i) for i in range(5)),
[('', 'i'), ('', 'i'), ('', 'i'), ('', 'i')], 5) # painful
# .. `a` now looks like a 2D array but it is not:
a.transpose() # doesn't work as expected
a[0, 1] # too many indices (of course)
a[:, 1] # don't even think about it
How can I get `a` to be a multidimensional array while keeping such a lazy
construction based on generators?
Answer: By itself,
[`np.fromiter`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromiter.html)
only supports constructing 1D arrays, and as such, it expects an iterable that
will yield individual values rather than tuples/lists/sequences etc. One way
to work around this limitation would be to use
[`itertools.chain.from_iterable`](https://docs.python.org/2/library/itertools.html#itertools.chain.from_iterable)
to lazily 'unpack' the output of your generator expression into a single 1D
sequence of values:
import numpy as np
from itertools import chain
def fun(i):
return tuple(4*i + j for j in range(4))
a = np.fromiter(chain.from_iterable(fun(i) for i in range(5)), 'i', 5 * 4)
a.shape = 5, 4
print(repr(a))
# array([[ 0, 1, 2, 3],
# [ 4, 5, 6, 7],
# [ 8, 9, 10, 11],
# [12, 13, 14, 15],
# [16, 17, 18, 19]], dtype=int32)
|
Multiple assignment from a function
Question: In Python, is it possible to make multiple assignments in the following manner
(or, rather, is there a shorthand):
import random
def random_int():
return random.randint(1, 100)
a, b = # for each variable assign the return values from random_int
Answer: Do you want to assign different return values from two different calls to your
random function or a single value to two variables generated by a single call
to the function.
For the former, use tuple unpacking
t = (2,5)
a,b = t #valid!
def random_int():
return random.randint(1, 100)
#valid: unpack a 2-tuple to a 2-tuple of variables
a, b = random_int(), random_int()
#invalid: tries to unpack an int as a 2-tuple
a, b = random_int()
#valid: you can also use comprehensions
a, b = (random_int() for i in range(2))
For the second, you can chain assignments to assign the same values to
multiple variables.
#valid, "normal" way
a = random_int()
b = a
#the same, shorthand
b = a = random_int()
|
Django: 'WSGIRequest' object has no attribute 'PUT'
Question:
def my_view(request, someid=None):
if request.method == 'GET':
# do stuff
return HttpResponse({})
elif request.method == 'PUT':
print request.body
print request.PUT
print json.loads(request.body)
return HttpResponse({})
this is my view and I'm making a PUT request (using Postman-an api simulator)
`x-www-form-urlencode`
when I do `request.body` it prints all data I'm sending in the form of
`a=1&b=2&c=3`. so when I do `json.loads(request.body)`, it raises value error,
`no json object could be decoded`. thats understandable. json.loads needs a
json data.
but when I print `request.PUT` it says `object has no attribute PUT`. we
generally do `request.GET` or `request.POST`, right? but why not 'PUT'?.
so I have two questions-
1) how do I convert this `request.body` format into python dictionary?
2 why I'm not able to print request.PUT
I have even tried `request.POST` in the 'PUT' block but its empty.
similar question has been asked here [ValueError: No JSON object could be
decoded - Django
request.body](http://stackoverflow.com/questions/31984481/valueerror-no-json-
object-could-be-decoded-django-request-body)
but its not exactly same this might be having issue in POST block.
apart from this, I need request.body, I donβt want to manually extract field
like
put = QueryDict(request.body)
description = put.get('description')
...
there are many fields so i cant do this.
Answer: try this
from django.http import QueryDict
qd = QueryDict(request.body)
put_dict = {k: v[0] if len(v)==1 else v for k, v in qd.lists()}
. now you can directly update an object by `**put_dict`
OR
one liner
put_dict = {k: v[0] if len(v)==1 else v for k, v in QueryDict(request.body).lists()}
|
Python Pattern Design
Question: I'm trying to achieve the pattern below.
Got as far as doing the first line, then I have no clue how to code the rest
of the pattern.
[](http://i.stack.imgur.com/96C7z.png)
Here's what I've done so far:
#Timothy Shek
from graphics import*
#open Graph Window
def main():
win = GraphWin("Example",100,100)
x = 7
y = 7
radius = 5
while x<=30 :
centre = Point(x,y)
circle1 = Circle(centre,radius)
circle1.setFill("red")
circle1.draw(win)
x = x+10
while x>=35 and x<=65 :
centre = Point(x+5,y)
circle2 = Circle(centre,radius)
circle2.setFill("red")
circle2.draw(win)
x = x+10
print(x)
while x>=67:
centre = Point(x+10,y)
circle1 = Circle(centre,radius)
circle1.setFill("red")
circle1.draw(win)
x = x+10
main()
Answer: I got it guys, thanks Heres the solution
#Timothy Shek
from graphics import*
#open Graph Window
def main():
win = GraphWin("Patch2" ,100,100)
for x in (5, 15, 25, 40,50,60,75,85,95):
for y in (5, 15, 25, 40,50,60,75,85,95):
c = Circle(Point(x+2,y), 5)
d = Circle(Point(x+2,y), 5)
c.draw(win)
d.draw(win)
c.setFill("Red")
d.setFill("Red")
if x==15 or x==50 or x== 85:
if y==15 or y==50 or y== 85:
c2 = Circle(Point(x+2,y),5)
c2.draw(win)
c2.setFill("White")
main()
|
How to list commits unique to a branch using Dulwich
Question: If I have two release branches v1.25 and v1.25-SOC how to I get commits only
in v1.250-SOC and I want to do this for every branch (get only branch specific
commits in git). I use dulwich python library.
Main idea is I want to find commits which are first committed to the given
branch. If these commits are there in later release versions its ok as long as
those are not in older release versions.
Answer: You can find all the commits that are in one branch but not the other by using
the revision graph Walker:
from dulwich.repo import Repo
r = Repo('.')
for entry in r.get_walker(include=[r['refs/heads/branch1'].id], exclude=[r['refs/heads/branch2'].id]):
print entry.commit.id
|
Check if String is a concatenation of elements in a list
Question: Is there an elegant way (preferably pythonic too) to check if a String _s_ is
a concatenation of elements of a subset of set _L_? An element of _L_ may
appear more than once in _s_.
For example:
L = set(["a", "ab", "c", "e"])
Then "abac" is a valid concatenation of elements of a subset of _L_
"aaaaaaa" is also a valid concatenation.
But "ad" is not since "d" not in L.
Answer:
import re
L = ["no", "force", "in", "the", "verse", "can", "stop", "me"]
# make this: "(?:no|force|in|the|verse|can|stop|me)*$"
r = re.compile( "(?:" + "|".join(L) + ")*$")
r.match("shiny") # -> None
r.match("canme") # -> not None
That works for the given set of strings. There is a function in the `re`
library to quote strings (escaping `|` etc) so that you can safely make such
an expression at run time.
r = re.compile( "(?:" + "|".join( re.escape(s) for s in L) + ")*$" )
It will match no matter how many times the substrings appear; and strange
results might occur, if some of the strings are prefixes of others and so
forth. It may have nasty runtime. If all of the strings are distinguished
easily from each other by their beginnings, it shouldn't.
|
Sorting JSON response with Python
Question: Need to help to figure out how to sort JSON reponse by highest to lowest
number, for example. here is part of JSON reponse below:
{
"queue": "RANKED_SOLO_5x5",
"name": "Riven's Cutthroats",
"entries": [
{
"leaguePoints": 812,
"isFreshBlood": false,
"isHotStreak": false,
"division": "I",
"isInactive": false,
"isVeteran": false,
"losses": 277,
"playerOrTeamName": "CLG Bunso",
"playerOrTeamId": "19732914",
"wins": 356
},
{
"leaguePoints": 567,
"isFreshBlood": false,
"isHotStreak": false,
"division": "I",
"isInactive": false,
"isVeteran": false,
"losses": 56,
"playerOrTeamName": "SKT Frost",
"playerOrTeamId": "66401633",
"wins": 160
},
{
"leaguePoints": 751,
"isFreshBlood": false,
"isHotStreak": false,
"division": "I",
"isInactive": false,
"isVeteran": true,
"losses": 421,
"playerOrTeamName": "C9 Hard",
"playerOrTeamId": "47836799",
"wins": 494
},
{
"leaguePoints": 587,
"isFreshBlood": false,
"isHotStreak": true,
"division": "I",
"isInactive": false,
"isVeteran": false,
"losses": 157,
"playerOrTeamName": "ShadowFiendv",
"playerOrTeamId": "71181475",
"wins": 265
},
{
"leaguePoints": 1109,
"isFreshBlood": false,
"isHotStreak": false,
"division": "I",
"isInactive": false,
"isVeteran": true,
"losses": 353,
"playerOrTeamName": "ApoIlo Price",
"playerOrTeamId": "7250",
"wins": 425
},
Now, I already grabbed the necessary info i needed, as below:
def getChallengerLadder(region, APIKey):
URL = "https://" + region + ".api.pvp.net/api/lol/" + region + "/v2.5/league/challenger?type=RANKED_SOLO_5x5&api_key=" + APIKey
print (URL)
response = requests.get(URL)
return response.json()
responseJSON3 = getChallengerLadder(region, APIKey)
x = 0
while True:
print (responseJSON3['entries'][x]['leaguePoints'], responseJSON3['entries'][x]['playerOrTeamName'] )
x += 1
As a result i get a list as follows (again, below is only a small sample):
608 Z Y Xydra
552 Silas Kroeger
1109 ApoIlo Price
601 Blem
587 Boy vs Girl
701 l am Bjerg
560 duo to homecomin
I want to sort this list from largest to smallest number, but i cant figure
out how to do it. Any help would be appreaciated! IS there a better way to do
it then i already done? I assume you would have to put the response in the
array and sort the array? Or is there a better way to do it?
Answer: Sorted by `leaguePoints`
(I use `json` module only to create full working example)
text = '''{
"queue": "RANKED_SOLO_5x5",
"name": "Riven's Cutthroats",
"entries": [
{
"leaguePoints": 812,
"isFreshBlood": false,
"isHotStreak": false,
"division": "I",
"isInactive": false,
"isVeteran": false,
"losses": 277,
"playerOrTeamName": "CLG Bunso",
"playerOrTeamId": "19732914",
"wins": 356
},
{
"leaguePoints": 567,
"isFreshBlood": false,
"isHotStreak": false,
"division": "I",
"isInactive": false,
"isVeteran": false,
"losses": 56,
"playerOrTeamName": "SKT Frost",
"playerOrTeamId": "66401633",
"wins": 160
},
{
"leaguePoints": 751,
"isFreshBlood": false,
"isHotStreak": false,
"division": "I",
"isInactive": false,
"isVeteran": true,
"losses": 421,
"playerOrTeamName": "C9 Hard",
"playerOrTeamId": "47836799",
"wins": 494
},
{
"leaguePoints": 587,
"isFreshBlood": false,
"isHotStreak": true,
"division": "I",
"isInactive": false,
"isVeteran": false,
"losses": 157,
"playerOrTeamName": "ShadowFiendv",
"playerOrTeamId": "71181475",
"wins": 265
},
{
"leaguePoints": 1109,
"isFreshBlood": false,
"isHotStreak": false,
"division": "I",
"isInactive": false,
"isVeteran": true,
"losses": 353,
"playerOrTeamName": "ApoIlo Price",
"playerOrTeamId": "7250",
"wins": 425
}
]
}'''
import json
# simulate `getChallengerLadder`
responseJSON3 = json.loads(text)
result = sorted(responseJSON3['entries'], key=lambda x:x['leaguePoints'])
print result
|
How to scatter plot a dict of lists containing arrays in Matplotlib? (Screenshot in details)
Question: What I want to do is plotting data in a _dict_ , preferably using Matplotlib.
Below is a screenshot since I think looking at the data structure makes it
easier to understand. But here is also a description.
* A _dict_ contains 7 _lists_.
* Each _list_ represents a cluster.
* Each _list_ contains a number of _arrays_ with two items in it.
* Each _array_ represents a two-dimensional point.
I want to recreate the results in this Blog post. Unfortunately the author
didn't provide the code he used for the plots.
<https://datasciencelab.wordpress.com/2013/12/12/clustering-with-k-means-in-
python/>
Here is the screenshot:
[](http://i.stack.imgur.com/eONjG.png)
In case it helps, here is the full code I used to generate the clusters:
import numpy as np
import random
import matplotlib.pyplot as plt # STACKOVERFLOW
# k-Means Algorithm (Lloyd's Algorithm)
def cluster_points(X, mu):
clusters = {}
for x in X:
bestmukey = min([(i[0], np.linalg.norm(x-mu[i[0]])) \
for i in enumerate(mu)], key=lambda t:t[1])[0]
try:
clusters[bestmukey].append(x)
except KeyError:
clusters[bestmukey] = [x]
return clusters
def reevaluate_centers(mu, clusters):
newmu = []
keys = sorted(clusters.keys())
for k in keys:
newmu.append(np.mean(clusters[k], axis = 0))
return newmu
def has_converged(mu, oldmu):
return set([tuple(a) for a in mu]) == set([tuple(a) for a in oldmu])
def find_centers(X, K):
# Initialize to K random centers
oldmu = random.sample(X, K)
mu = random.sample(X, K)
while not has_converged(mu, oldmu):
oldmu = mu
# Assign all points in X to clusters
clusters = cluster_points(X, mu)
# Reevaluate centers
mu = reevaluate_centers(oldmu, clusters)
return(mu, clusters)
# initialization
def init_board_gauss(N, k):
n = float(N)/k
X = []
for i in range(k):
c = (random.uniform(-1, 1), random.uniform(-1, 1))
s = random.uniform(0.05,0.5)
x = []
while len(x) < n:
a, b = np.array([np.random.normal(c[0], s), np.random.normal(c[1], s)])
# Continue drawing points from the distribution in the range [-1,1]
if abs(a) < 1 and abs(b) < 1:
x.append([a,b])
X.extend(x)
X = np.array(X)[:N]
return X
X = init_board_gauss(200,3)
# generating clusters
mu, clusters = find_centers(X, 7)
clusters = cluster_points(X, mu)
Answer: I came up with a solution. [](http://i.stack.imgur.com/lugVE.png)
Here is what I changed/added to the code:
# Initialize points
n_points = 200
n_clusters = 7
X = init_board_gauss(n_points, n_clusters)
# Cluster points
mu, clusters = find_centers(X, n_clusters)
clusters = cluster_points(X, mu)
# Generate random colors
def generate_random_color():
r = lambda: random.randint(0,255)
return '#%02X%02X%02X' % (r(),r(),r())
# Plot each cluster
for i in range(0, n_clusters):
colx = tuple(x[0] for x in clusters[i])
coly = tuple(x[1] for x in clusters[i])
cluster_color = generate_random_color()
plt.scatter(colx,coly, color=cluster_color)
And here is the full code:
import matplotlib.pyplot as plt
import numpy as np
import random
# k-Means Algorithm (Lloyd's Algorithm)
def cluster_points(X, mu):
clusters = {}
for x in X:
bestmukey = min([(i[0], np.linalg.norm(x-mu[i[0]])) \
for i in enumerate(mu)], key=lambda t:t[1])[0]
try:
clusters[bestmukey].append(x)
except KeyError:
clusters[bestmukey] = [x]
return clusters
def reevaluate_centers(mu, clusters):
newmu = []
keys = sorted(clusters.keys())
for k in keys:
newmu.append(np.mean(clusters[k], axis = 0))
return newmu
def has_converged(mu, oldmu):
return set([tuple(a) for a in mu]) == set([tuple(a) for a in oldmu])
def find_centers(X, K):
# Initialize to K random centers
oldmu = random.sample(X, K)
mu = random.sample(X, K)
while not has_converged(mu, oldmu):
oldmu = mu
# Assign all points in X to clusters
clusters = cluster_points(X, mu)
# Reevaluate centers
mu = reevaluate_centers(oldmu, clusters)
return(mu, clusters)
# Initialization
def init_board(N):
X = np.array([(random.uniform(-1, 1), random.uniform(-1, 1)) for i in range(N)])
return X
def init_board_gauss(N, k):
n = float(N)/k
X = []
for i in range(k):
c = (random.uniform(-1, 1), random.uniform(-1, 1))
s = random.uniform(0.05,0.5)
x = []
while len(x) < n:
a, b = np.array([np.random.normal(c[0], s), np.random.normal(c[1], s)])
# Continue drawing points from the distribution in the range [-1,1]
if abs(a) < 1 and abs(b) < 1:
x.append([a,b])
X.extend(x)
X = np.array(X)[:N]
return X
# Initialize points
n_points = 200
n_clusters = 7
X = init_board_gauss(n_points, n_clusters)
# Cluster points
mu, clusters = find_centers(X, n_clusters)
clusters = cluster_points(X, mu)
# Generate random colors
def generate_random_color():
r = lambda: random.randint(0,255)
return '#%02X%02X%02X' % (r(),r(),r())
# Plot each cluster
for i in range(0, n_clusters):
colx = tuple(x[0] for x in clusters[i])
coly = tuple(x[1] for x in clusters[i])
cluster_color = generate_random_color()
plt.scatter(colx,coly, color=cluster_color)
|
How to do One Hot Encoding for Linear Regression in Spark with Python?
Question: I have this code which I had written for `Random Forest regression` encoding.
But `Random Forest regression` does not require `One Hot Encoding` after
`indexer`. Now I want to try the `Linear Regression` which requires `One Hot
Encoding`. I went through the Sparks [One Hot
Encoder](http://spark.apache.org/docs/latest/ml-features.html#onehotencoder)
documentation but couldn't get how to incorporate that in my current code. How
can I add the `One Hot Encoding` step in my current code?
from pyspark.ml.feature import StringIndexer
from pyspark.ml.pipeline import Pipeline
from pyspark.ml.feature import VectorAssembler
import org.apache.spark.ml.feature.OneHotEncoder
label_col = "x4"
# converting RDD to dataframe
train_data_df = train_data.toDF(("x0","x1","x2","x3","x4"))
# Indexers encode strings with doubles
string_indexers = [
StringIndexer(inputCol=x, outputCol="idx_{0}".format(x))
for x in train_data_df.columns if x != label_col
]
# Assembles multiple columns into a single vector
assembler = VectorAssembler(
inputCols=["idx_{0}".format(x) for x in train_data_df.columns if x != label_col],
outputCol="features"
)
pipeline = Pipeline(stages=string_indexers + [assembler])
model = pipeline.fit(train_data_df)
indexed = model.transform(train_data_df)
label_points = (indexed
.select(col(label_col).cast("double").alias("label"), col("features"))
.map(lambda row: LabeledPoint(row.label, row.features)))
**UPDATE:**
from pyspark.mllib.regression import LinearRegressionWithSGD, LinearRegressionModel
###### FOR TEST DATA ######
label_col_test = "x4"
# converting RDD to dataframe
test_data_df = test_data.toDF(("x0","x1","x2","x3","x4"))
# Indexers encode strings with doubles
string_indexers_test = [
StringIndexer(inputCol=x, outputCol="idx_{0}".format(x))
for x in testData_df_1.columns if x != label_col_test
]
# encoders
encoders_test = [
StringIndexer(inputCol="idx_{0}".format(x), outputCol="enc_{0}".format(x))
for x in testData_df_1.columns if x != label_col_test
]
# Assembles multiple columns into a single vector
assembler_test = VectorAssembler(
inputCols=["idx_{0}".format(x) for x in testData_df_1.columns if x != label_col_test],
outputCol="features"
)
pipeline_test = Pipeline(stages=string_indexers_test + encoders_test + [assembler_test])
model_test = pipeline_test.fit(test_data_df)
indexed_test = model_test.transform(test_data_df)
label_points_test = (indexed_test
.select(col(label_col_test).cast("float").alias("label"), col("features"))
.map(lambda row: LabeledPoint(row.label, row.features)))
# Build the model
model = LinearRegressionWithSGD.train(label_points)
valuesAndPreds = label_points_test.map(lambda p: (p.label, model.predict(p.features)))
MSE = valuesAndPreds.map(lambda (v, p): (v - p)**2).reduce(lambda x, y: x + y) / valuesAndPreds.count()
print("Mean Squared Error = " + str(MSE))
Answer: You can simply add it as a step between indexing and assembling:
encoders = [
StringIndexer(inputCol="idx_{0}".format(x), outputCol="enc_{0}".format(x))
for x in train_data_df.columns if x != label_col
]
assembler = VectorAssembler(
inputCols=[
"enc_{0}".format(x) for x in train_data_df.columns if x != label_col
],
outputCol="features"
)
pipeline = Pipeline(stages=string_indexers + encoders + [assembler])
|
How to loop through a dataframe, create a new column and append values to it in python
Question: I have the following problem. I have a dataframe with several columns, one of
those contains strings as values. I want to loop through this column, change
those values and save the changed values in a new column.
The code I have written so far looks like this:
def get_classes(x):
for index, string in df['column'].iteritems():
listi = string.split(',')
Classes=[]
for value in listi:
count=listi.count(value)
if count >= 3:
Classes.append(value)
Unique=(',').join(sorted(list(set(Classes))))
df['NewColumn']=Unique
End.apply(get_classes)
It loops through the rows of `df['column']`, splitting the string at each
`,`(creating a list called listi) and creates an empty `list` called classes.
It then counts each value in listi and appends it to Classes if it occures at
least three times in the list. The finished list is then `sorted` and `set()`,
so that all objects in the list are unique, and finally joined at comma to a
string again. Then I want to append this unique list of value in a new column,
at the same index position as the row value the changed value is derived from.
As example:
df
column NewColumn
0 A,A,A,C A
1 C,B,C,C C
2 B,B,B,B B
My code seems to work fine when I do `print Unique` instead of
`df['NewColumn']=Unique`, as it then prints all the transformed values. If I
execute the code like in my example however, the `NewColumn` of the dataframe
is completely filled with the same value, which seems to correspond to the
original value of the last row in the df. Can someone explain to me what the
problem here is?
Answer: You can use powerfull `Counter` from Collections:
from collections import Counter
foo = lambda x: ','.join(sorted([k for k,v in Counter(x).iteritems() if v>=3]))
df['new'] = df['column'].str.split(',').map(foo)
#In [33]: df
#Out[33]:
# column NewColumn new
#0 A,A,A,C A A
#1 C,B,C,C C C
#2 B,B,B,B B B
|
How to create json file having array in Python
Question: I want to create a json file like
{
"a":["12","34","23",...],
"b":["13","14","45",....],
.
.
.
}
key should come from the list:
lis = ['a','b',...]
and value from the sql query "select id from" + i , where I am iterating
through the list through "i". This query simply returns the column id.
Here is the sample code:
lis = ['a','b','c']
len_obj = len(lis)
with open("Dataset.json", 'w') as file:
for i in lis:
file.write(i)
obj_query = i + '_query'
obj_query = sf.query("select id from " + i)
jsondata = json.loads(json.dumps(obj_query['records']))
length = len(jsondata)
i = {}
k = 0
for j in range(length):
obj_id = jsondata[j]['Id']
# print("id " + obj_id)
if k == 0:
ids = "\"" + obj_id + "\""
k = 1
else:
ids = ids + ",\"" + obj_id + "\""
if count != len_obj - 1:
file.write(ids)
else:
file.write(ids)
count += 1
file.write("}")
final output should be like:
{
"a":["12","23",...],
"b":["234","456",...],
}
This is my first blog and 1st program also. Please guide me through this.
Please forgive the indentation of the program as I am not able to write it
here properly.
Answer: You can simply create a dictionary containing the values you are after and
then convert it to json using `json.dumps`
import json
data = {}
data['a'] = ["12","34","23"]
data['b'] = ["13","14","45"]
json_data = json.dumps(data)
print json_data
|
python pyparsing word excludeChars
Question: I am trying to make a parser for a number which can contain an '_'. I would
like the underscore to be suppressed in the output. For example, a valid word
would be 1000_000 which should return a number: 1000000. I have tried the
excludeChars keyword argument for this as _my understanding_ is that this
should do the following:
> "If supplied, this argument specifies characters not to be considered to
> match, even if those characters are otherwise considered to match."
Taken from <http://infohost.nmt.edu/tcc/help/pubs/pyparsing/pyparsing.pdf> \-
page 33 section 5.35 (great pyparsing reference btw)
So below is my attempt:
import pyparsing as pp
num = pp.Word(pp.nums+'_', excludeChars='_')
num.parseString('123_4')
but I end up with the result '123' instead of '1234'
In [113]: num.parseString('123_4')
Out[113]: (['123'], {})
Any suggestions?
Answer: How about simply replacing the underscore char?
"123_4".replace("_", "")
# "1234"
|
python ISO 8601 date format
Question: i'm trying to format the date like this,
2015-12-02T12:57:17+00:00
here's my code
time.strftime("%Y-%m-%dT%H:%M:%S%z", time.gmtime())
which gives this result,
2015-12-02T12:57:17+0000
i can't see any other variations of %z that can provide the correct format of
+00:00 ? what's the correct way to go about this?
Answer: That can work for you:
[Python - Convert UTC datetime string to local
datetime](http://stackoverflow.com/questions/4770297/python-convert-utc-
datetime-string-to-local-datetime)
I copied the code to make it easier to tackle, I indicate it's another
person's answer anyway.
from datetime import datetime,tzinfo,timedelta
class Zone(tzinfo):
def __init__(self,offset,isdst,name):
self.offset = offset
self.isdst = isdst
self.name = name
def utcoffset(self, dt):
return timedelta(hours=self.offset) + self.dst(dt)
def dst(self, dt):
return timedelta(hours=1) if self.isdst else timedelta(0)
def tzname(self,dt):
return self.name
GMT = Zone(0,False,'GMT')
EST = Zone(-5,False,'EST')
print datetime.utcnow().strftime('%m/%d/%Y %H:%M:%S %Z')
print datetime.now(GMT).strftime('%m/%d/%Y %H:%M:%S %Z')
print datetime.now(EST).strftime('%m/%d/%Y %H:%M:%S %Z')
t = datetime.strptime('2011-01-21 02:37:21','%Y-%m-%d %H:%M:%S')
t = t.replace(tzinfo=GMT)
print t
print t.astimezone(EST)
I've tried it in my Python Notebook and works perfectly.
|
encoding issue when reading CSV file with python
Question: I have hit a road block when trying to read a CSV file with python.
UPDATE: if you want to just skip the character or error you can open the file
like this:
with open(os.path.join(directory, file), 'r', encoding="utf-8", errors="ignore") as data_file:
So far I have tried.
for directory, subdirectories, files in os.walk(root_dir):
for file in files:
with open(os.path.join(directory, file), 'r') as data_file:
reader = csv.reader(data_file)
for row in reader:
print (row)
the error I am getting is:
UnicodeEncodeError: 'charmap' codec can't encode characters in position 224-225: character maps to <undefined>
I have Tried
with open(os.path.join(directory, file), 'r', encoding="UTF-8") as data_file:
Error:
UnicodeEncodeError: 'charmap' codec can't encode character '\u2026' in position 223: character maps to <undefined>
Now if I just print the data_file it says they are cp1252 encoded but if I try
with open(os.path.join(directory, file), 'r', encoding="cp1252") as data_file:
The error I get is:
UnicodeEncodeError: 'charmap' codec can't encode characters in position 224-225: character maps to <undefined>
I also tried the recommended package.
The error I get is:
UnicodeEncodeError: 'charmap' codec can't encode characters in position 224-225: character maps to <undefined>
The line I am trying to parse is:
2015-11-28 22:23:58,670805374291832832,479174464,"MarkCrawford15","RT @WhatTheFFacts: The tallest man in the world was Robert Pershing Wadlow of Alton, Illinois. He was slighty over 8 feet 11 inches tall.","None
any thoughts or help is appreciated.
Answer: I would use [csvkit](https://csvkit.readthedocs.org/en/0.9.1/), that uses
automatic detection of apposite encoding and decoding. e.g.
import csvkit
reader = csvkit.reader(data_file)
As disscussed in the chat- solution is-
for directory, subdirectories, files in os.walk(root_dir):
for file in files:
with open(os.path.join(directory, file), 'r', encoding="utf-8") as data_file:
reader = csv.reader(data_file)
for row in reader:
data = [i.encode('ascii', 'ignore').decode('ascii') for i in row]
print (data)
|
Whats wrong with the image scaling in igraph?
Question: I have a problem in controlling the size of objects in network plots done by
igraph. The documentation of the `plot` command says:
* **bbox:** : The bounding box of the plot. This must be a tuple containing the desired width and height of the plot. The default plot is 600 pixels wide and 600 pixels high.
* **arrow_size:** Size (length) of the arrowhead on the edge if the graph is directed, relative to 15 pixels.
* **vertex_size:** Size of the vertex in pixels
So to my understanding all these arguments represent numbers of pixels.
Therefore, multiplying all of them, say, by a factor of `2`, I would expect
the images to scale completely with this factor.
Consider this following minimal example in python:
from igraph import Graph, plot
def visualize(res=1.0):
g=Graph([(0,1), (1,0)], directed=True)
layout = g.layout_fruchterman_reingold()
plot(g, target='plot.png',
layout=layout,
bbox=(120*res,120*res),
vertex_size=5*res,
arrow_size=10*res)
This plots a trivial graph,
However for `res=1.0` and `res=2.0` the arrows and vertices become smaller
compared to the image size.
How is that possible?
Answer: Just a wild guess, but could the stroke width account for the difference? The
default stroke width is 1 units, and you don't seem to scale the stroke width.
Try setting `vertex_frame_width=res` in the call to `plot()`.
|
Python Clustering 'purity' metric
Question: I'm using a [Gaussian Mixture Model (GMM)](http://scikit-
learn.org/stable/modules/generated/sklearn.mixture.GMM.html) from
`sklearn.mixture` to perform clustering of my data set.
I could use the function `score()` to compute the log probability under the
model.
However, I am looking for a metric called 'purity' which is defined in [this
article](http://nlp.stanford.edu/IR-book/html/htmledition/evaluation-of-
clustering-1.html).
How can I implement it in Python? My current implementation looks like this:
from sklearn.mixture import GMM
# X is a 1000 x 2 array (1000 samples of 2 coordinates).
# It is actually a 2 dimensional PCA projection of data
# extracted from the MNIST dataset, but this random array
# is equivalent as far as the code is concerned.
X = np.random.rand(1000, 2)
clusterer = GMM(3, 'diag')
clusterer.fit(X)
cluster_labels = clusterer.predict(X)
# Now I can count the labels for each cluster..
count0 = list(cluster_labels).count(0)
count1 = list(cluster_labels).count(1)
count2 = list(cluster_labels).count(2)
But I can not loop through each cluster in order to compute the confusion
matrix (according this
[question](http://stats.stackexchange.com/a/154379/89612))
Answer: `sklearn` doesn't implement a cluster purity metric. You have 2 options:
1. Implement the measurement using `sklearn` data structures yourself. [This](http://www.caner.io/purity-in-python.html) and [this](https://pml.readthedocs.org/en/latest/_modules/pml/unsupervised/clustering.html) have some python source for measuring purity, but either your data or the function bodies need to be adapted to how you're representing your data.
2. Use the (much less mature) [PML](https://pml.readthedocs.org/en/latest/clustering.html) library, which does implement cluster purity.
|
Simple migration to __init__.py
Question: I'm upgrading a bunch of scripts where the ecosystem is a bit of a mess. The
scripts always relied on external modules, and didn't have any package
infrastructure of their own (they also didn't do much OOP, as you can
imagine). There's nothing at the top level, but it is the working directory
when starting Python and I'd like to keep it that way. At the top-level, I've
just created `__init__.py` file (based on [another
question](http://stackoverflow.com/q/14886143/320399)). As I'm less
experienced with Python `__init__.py` confuses me a bit. All of the
`__init__.py` files I've created are empty, it's my understanding that this is
all that's required.
Assume I have the following directory structure:
__init__.py
dev.properties
prod.properties
F/
Foo.py
__init__.py
B/
bar.py
__init__.py
And the code is like this :
# Foo.py
from ..b import bar
barFunc()
# bar.py
def barFunc():
print "Hello, World!"
sys.stdout.flush()
I've created `__init__.py` at the root, in `F/` and in `B/`. However, when I
run `python F/Foo.py`, I get an error:
Traceback (most recent call last):
File "F/Foo.py", line 3, in <module>
from ..b import bar
ValueError: Attempted relative import in non-package
What exactly would I need to do to invoke `python F/Foo.py` and be able to
depend on things defined in sibling directories?
**_Update_**
Thanks to [@user2455127](http://stackoverflow.com/a/34048288/320399), I
realized that I forgot to remove the file extension `.py` and my working
directory was wrong. From the `mypackage` directory, running `python -m
mypackage/F/Foo`, the error was : `myvirtualenv/bin/python: No module named
mypackage/B/bar`.
Re-reading [@user2455127](http://stackoverflow.com/a/34048288/320399)'s post,
I ran from the directory above and get a long Traceback:
Traceback (most recent call last):
File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
exec code in run_globals
File "<full path>/mypackage/foo/Foo.py", line 24, in <module>
from ..b import bar
ValueError: Attempted relative import in non-package
I'm not quite sure what needs to be done to fix this, but it seems like the
`__package__` attribute may help. I'll try and figure that out, and post
another update.
Answer: Have a look to this : [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) and brenBarn's answer
If you run it from the folder upper than the one with dev.properties and the
others files (called lambda in my case), with this command line :
python -m lambda.F.Foo
it works.
|
Event listener in python script on a server
Question: I want to write a python script to run on a server that will be checking for
changes on a database (e.g. total number of records), and when one occurs it
will perform an action.
I am new in python and I don't know how I should approach this, is there a
proposed event listening methodology to optimize cpu consumption and ensure
smooth running?
I'm not asking for specific code but more like the high-level idea.
EDIT: After KT.'s helpful response I built this code to implement a listener
for changes in a json response from a URI api:
import json
import time
import requests
class Test():
def __init__(self):
self.total_services = self.__get_total_services()
def __get_total_services(self):
url = "my_url_that_responds_with_json"
response = requests.get(url)
json_data = response.json()
dict_data = json.loads(json.dumps(json_data))
total = len(dict_data['services'])
return total
def listen_for_changes(self):
while 1:
if (self.__get_total_services() != self.total_services):
self.total_services = self.__get_total_services()
"""do something"""
time.sleep(60)
return 0
my_test = Test()
my_test.listen_for_changes()
My question is should this code run somehow in the background or it is ok to
run it like this from my server?
Answer: In general, there are two ways you can detect changes in the database (or
anywhere else, in fact):
* **Polling** \- query the database regularly from your code and detect changes in your Python code. This approach is simple and straightforward, although it may indeed be a bit wasteful on the resources, if you poll too frequently.
* **Notifications** \- configure the database to track changes and notify your application. This method might seem more reasonable in terms of resource usage, but it is may turn out to be so annoying and messy to implement that you would not want to go this way unless you are forced to. In the most general case this approach will require you to:
* Decide on a way to notify your application (e.g. keep a network socket open, listen to OS signals, track an open file or a pipe, etc).
* Implement a [trigger](http://dev.mysql.com/doc/refman/5.1/en/faqs-triggers.html) in the database that will react to row insertions or deletions and invoke the notification process (e.g. execute a script that will send a message to your server).
* If your application and the database server run on different machines, you might need to think about having a queue inbetween to make sure the notifications are not lost in transit.
Alternatively, if your database is only changed from one other application,
you can configure _that_ application to send you notifications whenever
something changes. If your database does not support triggers, this may be
your only chance (if any) to implement the notification-based solution.
|
Read numbers without spaces in text-file with ython
Question: I'm a newbie with Python and struggle to read a text file like this:
0.42617E-03-0.19725E+09-0.21139E+09 0.37077E+08
0.85234E-03-0.18031E+09-0.18340E+09 0.28237E+08
0.12785E-02-0.16583E+09-0.15887E+09 0.20637E+08
There are thus no comma or space delimiters between the numbers in the file.
With Matlab I know how to specify the formats, but how to do it in Python?
I have been trying np.loadtxt but don't know how to set number of digits to
read, so if anyone could give me a hint on this I would be much grateful.
Thanks in advance, Erik
Answer: To expand on my comment, based on the fact that you can successfully parse
this with MATLAB, I assume that these fields are fixed width. In that case,
you can just slice each row based on the field width, and then convert that to
a numpy array if that's what you need. As an example:
import numpy
input_data = """ 0.42617E-03-0.19725E+09-0.21139E+09 0.37077E+08
0.85234E-03-0.18031E+09-0.18340E+09 0.28237E+08
0.12785E-02-0.16583E+09-0.15887E+09 0.20637E+08
"""
input_rows = input_data.split('\n')
width = 12
num_fields = 4
data = []
for input_row in input_rows:
if not input_row:
continue
data.append([float(input_row[width * i:width * (i + 1)].strip()) for i in range(num_fields)])
data = numpy.array(data)
print(data)
This outputs:
[[ 4.26170000e-04 -1.97250000e+08 -2.11390000e+08 3.70770000e+07]
[ 8.52340000e-04 -1.80310000e+08 -1.83400000e+08 2.82370000e+07]
[ 1.27850000e-03 -1.65830000e+08 -1.58870000e+08 2.06370000e+07]]
Of course, this example uses a fixed string to represent the input data, but
you can imagine doing a similar thing with your input stream.
|
python count keywords in a python file without counting inside quotation marks
Question: For example:
import codecs
def main():
fileName = input("Please input a python file: ")
file = codecs.open(fileName, encoding = "utf8")
fornum = 0
for line in file:
data = line.split()
if "for" in data:
fornum += 1
print("The number of for loop in", fileName, ":", fornum)
main()
There are 1 for-statement in above codes. But the program counts the 'for'
inside the quotation mark which is not expected and it displays 2. How can I
change the codes to make it counts the keywords(for) without counting the
words inside ""? Thx
Answer: As mentioned in comments to propely count for loops you should parse Python
file and walk through it AST. You could do it with
[ast](https://docs.python.org/2/library/ast.html) module. Example code:
import ast
def main():
fileName = input("Please input a python file: ")
with open(fileName) as f:
src = f.read()
source_tree = ast.parse(src) # get AST of source file
fornum = 0
# and recursively walk through all AST nodes
for n in ast.walk(source_tree):
if n.__class__.__name__ == "For":
fornum = fornum+1
print("The number of for loop in ", fileName, ":", fornum)
main()
|
Python Requests, getting back: Unexpected character encountered while parsing value: L. Path
Question: I am attempting to get an auth token from The Trade Desk's (sandbox) api but I
get back a 400 response stating:
> "Error reading Content-Type 'application/json' as JSON: Unexpected character
> encountered while parsing value: L. Path '', line 0, position 0."
Whole `response.json()`:
{u'ErrorDetails': [{u'Reasons': [u"Error reading Content-Type 'application/json' as JSON: Unexpected character encountered while parsing value: L. Path '', line 0, position 0."], u'Property': u'TokenRequest'}], u'Message': u'The request failed validation. Please check your request and try again.'}
My script (runnable):
import requests
def get_token():
print "Getting token"
url = "https://apisb.thetradedesk.com/v3/authentication"
headers = {'content-type': 'application/json'}
data = {
"Login":"logintest",
"Password":"password",
"TokenExpirationInMinutes":60
}
response = requests.post(url, headers=headers, data=data)
print response.status_code
print response.json()
return
get_token()
[Sandbox docs here](https://apisb.thetradedesk.com/v3/doc)
I believe this means my `headers` var is not being serialized correctly by
`requests`, which seems impossible, or not being deserialized correctly by The
Trade Desk. I've gotten into the `requests` lib but I can't seem to crack it
and am looking for other input.
Answer: You need to do
import json
and convert your dict into json:
response = requests.post(url, headers=headers, data=json.dumps(data))
Another way would be to explicitely use `json` as parameter:
response = requests.post(url, headers=headers, json=data)
_Background:_ In the `prepare_body` method of requests a dictionary is
explicitely converted to json and a content-header is also automatically set:
if not data and json is not None:
content_type = 'application/json'
body = complexjson.dumps(json)
If you pass `data=data` then your data will be only form-encoded (see
<http://docs.python-requests.org/en/latest/user/quickstart/#more-complicated-
post-requests>). You will need to explicitely convert it to json, if you want
json to be the content-type of your http body.
Your follow-up question was about why headers don't have to be converted to
json. Headers can be simply passed as dictionary into the request. There's no
need to convert it to json. The reason is implementation specific.
|
Python xlrd returns a no attribute error
Question: I'm trying to get a list of list with the values of certain cells within my
xlsx worksheet but when I run it, it says there is no attribute called value.
when I run the code without the ".value" method it will return a list of lists
formatted the way I want but they all have the value None.
import xlrd
gmails = "/home/ro/Downloads/100 Gmail (1).xlsx"
def open_worksheet(file_path):
wb = xlrd.open_workbook(file_path)
ws = wb.sheet_by_index(0)
return ws
def get_cell(worksheet, row, col):
cell = worksheet.cell(row, col)
def get_email_list(worksheet):
email_list = []
first_gmail = [1, 3]
first_password = [1, 3]
first_recovery_gmail = [1, 5]
for row in range(1, worksheet.nrows):
gmail = get_cell(worksheet, first_gmail[0], first_gmail[1])
password = get_cell(worksheet, first_password[0], first_password[1])
recovery = get_cell(worksheet, first_recovery_gmail[0], first_recovery_gmail[1])
first_gmail[0] += 1
first_password[0] += 1
first_recovery_gmail[0] += 1
email_list.append([gmail.value, password.value, recovery.value])
return email_list
print get_email_list(open_worksheet(gmails))
My Traceback
Traceback (most recent call last):
File "twitter.py", line 36, in <module>
print get_email_list(open_worksheet(gmails))
File "twitter.py", line 33, in get_email_list
email_list.append([gmail.value, password.value, recovery.value])
AttributeError: 'NoneType' object has no attribute 'value'
Answer:
def get_cell(worksheet, row, col):
cell = worksheet.cell(row, col)
needs to be:
def get_cell(worksheet, row, col):
return worksheet.cell(row, col)
|
Get drag-n-drop qtreewidget items - Python
Question: Is there a way I can get the items being drag/dropped and their destination
parent?
In an ideal scenario what I want to happen is once the **dropEvent** finishes,
it prints the qtreewidgetitems which were moved, as well as the new parent
which the items were moved to. The parent would either be the qtreewidget
itself or another qtreewidgetitem depending on where the drop happened.
Can someone help me out here please?
Below is the code i have so far.
[](http://i.stack.imgur.com/7XQRQ.png)
# Imports
# ------------------------------------------------------------------------------
import sys
from PySide import QtGui, QtCore, QtSvg
class TreeNodeItem( QtGui.QTreeWidgetItem ):
def __init__( self, parent, name="" ):
super( TreeNodeItem, self ).__init__( parent )
self.setText( 0, name )
self.stuff = "Custom Names - " + str(name)
class TreeWidget(QtGui.QTreeWidget):
def __init__(self, parent=None):
QtGui.QTreeWidget.__init__(self, parent)
self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
self.setItemsExpandable(True)
self.setAnimated(True)
self.setDragEnabled(True)
self.setDropIndicatorShown(True)
self.setDragDropMode(QtGui.QAbstractItemView.InternalMove)
self.setAlternatingRowColors(True)
# def dropEvent(self, event):
# print "finished"
def dropEvent(self, event):
return_val = super( TreeWidget, self ).dropEvent( event )
print ("Drop finished")
d = event.mimeData()
print d, event.source()
return return_val
# Main
# ------------------------------------------------------------------------------
class ExampleWidget(QtGui.QWidget):
def __init__(self,):
super(ExampleWidget, self).__init__()
self.initUI()
def initUI(self):
# formatting
self.resize(250, 400)
self.setWindowTitle("Example")
# widget - passes treewidget
self.itemList = QtGui.QTreeWidget()
self.itemList = TreeWidget()
headers = [ "Items" ]
self.itemList.setColumnCount( len(headers) )
self.itemList.setHeaderLabels( headers )
# layout Grid - row/column/verticalpan/horizontalspan
self.mainLayout = QtGui.QGridLayout(self)
self.mainLayout.setContentsMargins(5,5,5,5)
self.mainLayout.addWidget(self.itemList, 0,0,1,1)
# display
self.show()
# Functions
# --------------------------------------------------------------------------
def closeEvent(self, event):
print "closed"
def showEvent(self, event):
print "open"
for i in xrange(20):
TreeNodeItem( parent=self.itemList , name=str(i) )
# Main
# ------------------------------------------------------------------------------
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
ex = ExampleWidget()
sys.exit(app.exec_())
Answer: I would suggest using a View/Model approach. Decoding the
'application/x-qabstractitemmodeldatalist' will only return the item dragged,
and the dropMimeData isn't used in the QTreeWidget.
Look here for an example.
<https://wiki.python.org/moin/PyQt/Handling%20Qt's%20internal%20item%20MIME%20type>
|
Python module not callable when importing getopt
Question: I am new to python and the getopt function. I am trying to import getopt,
however I run into an error.
My code is literally just:
import getopt
and also tried
from getopt import * /// from getopt import getopt
Output below:
python asdfasdf.py
ARGV : []
Traceback (most recent call last):
File "asdfasdf.py", line 1, in <module>
import getopt
File "/home/STUDENTS/~~/csc328/TCP/pyExample/getopt.py", line 12, in <module>
'version=',
TypeError: 'module' object is not callable
My python is 2.6 something and this was implemented in 2.3 I believe.
edit: I'm using unix
Answer: you might be have getotp module in your code. When you refere python third
party module, it try to import your module.
Pleas remove `getopt.py` in your example or rename it.
|
Passing Arguments from Javascript to Python Function
Question: I am trying to execute/call a python method(with one parameter) from inside
Ajax Call. But I am having trouble passing the parameter from Ajax Call to
Python Function. I am using Flask to connect the two.
Updated Code: Ajax Call(Javascript):
$.ajax({
type: 'GET',
url: "http://127.0.0.1:5000/get_result/" + input.value,
dataType: "text",
success: function(response) {
output.value = response;
alert(response);
}
}).done(function(data){
console.log(data);
});
Python Code:
from flask import Flask
app = Flask(__name__)
@app.route("/get_result/<url>", methods=['GET', 'POST'])
def get_result(url):
return "Hello World"
if __name__ == "__main__":
app.run(debug = True)
I have a backend Python Server running locally. But I am getting this as the
error. (Running <http://127.0.0.1:5000/get_result/google.com> directly from
browser shows me correct result, if it helps).
[Expected End Result: alertbox with message "Hello World"]
Error:
127.0.0.1 - - [03/Dec/2015 13:38:21] "GET /get_result/google.com HTTP/1.1" 200 -
Error on request:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 194, in run_wsgi
execute(self.server.app)
File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 185, in execute
write(data)
File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 153, in write
self.send_header(key, value)
File "/usr/lib/python2.7/BaseHTTPServer.py", line 401, in send_header
self.wfile.write("%s: %s\r\n" % (keyword, value))
IOError: [Errno 32] Broken pipe
Can you please suggest a work around for this ?
Thanks,
Answer: According to the flask documentation, functions decorated with `@app.route`
don't take a `url` parameter. That explains the error you're getting.
It looks like you need to also do
from flask import request
so that you can access the request in your function. See here:
<http://flask.pocoo.org/docs/0.10/quickstart/#the-request-object>
Once you do that you can access the data/query params sent over by the ajax
call according to the docs here
<http://flask.pocoo.org/docs/0.10/api/#incoming-request-data>
|
Django debug toolbar import error of analysisdebug_toolbar
Question: Trying to install the django debug toolbar and receiving the following error:
Traceback (most recent call last):
File "/home/user/project/manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/user/project/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/home/user/project/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 312, in execute
django.setup()
File "/home/user/project/env/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/user/project/env/local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate
app_config = AppConfig.create(entry)
File "/home/user/project/env/local/lib/python2.7/site-packages/django/apps/config.py", line 86, in create
module = import_module(entry)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
ImportError: No module named analysisdebug_toolbar
Package versions:
Django==1.8.2
django-debug-toolbar==1.3.0
Funny thing is this used to work but somehow broke due to some changes in the
project.
Answer: It looks like you are missing a comma in your `INSTALLED_APPS` setting.
Instead of:
INSTALLED_APPS = (
...
'analysis'
'debug_toolbar',
...
)
It should be:
INSTALLED_APPS = (
...
'analysis',
'debug_toolbar',
...
)
When you forget the comma, Python concatonates `'analysis'` and
`'debug_toolbar'` into the string `analysisdebug_toolbar`. In Python, it's a
good idea to include a trailing comma in the last element in your list or
tuple. It allows you to add new items or rearrange the order without hitting
bugs like this.
|
csv, python, update line
Question: I am looking to update specific lines of a csv as I run through them in a for
loop. For example:
line_of_csv = "item1,item2"
for row in csv: if action: #line of code to write "action occurred" output:
(for lines that action occurred: "item1,item2,action occured") (for lines that
action didn't occur: "item1,item2"
ideally this would remain in the same file and not have to write a second
file. I hope this makes sense and any input is greatly apprecaited!
Answer: my.csv
col1,col2
item1,item2
item3,item4
item5,item6
item7,item8
item9,item10
code
import csv
result = []
with open('my.csv', 'rb') as in_file:
reader = csv.reader(in_file)
for line_num, line in enumerate(reader):
if line_num == 1:
line = ['modified', 'line']
result.append(line)
with open('my.csv', 'wb') as out_file:
writer = csv.writer(out_file)
writer.writerows(result)
|
Best way to receive the 'return' value from a python generator
Question: Since Python 3.3, if a generator function returns a value, that becomes the
value for the StopIteration exception that is raised. This can be collected a
number of ways:
* The value of a `yield from` expression, which implies the enclosing function is also a generator.
* Wrapping a call to `next()` or `.send()` in a try/except block.
However, if I'm simply wanting to iterate over the generator in a for loop -
the easiest way - there doesn't appear to be a way to collect the value of the
StopIteration exception, and thus the return value. Im using a simple example
where the generator yields values, and returns some kind of summary at the end
(running totals, averages, timing statistics, etc).
for i in produce_values():
do_something(i)
values_summary = ....??
One way is to handle the loop myself:
values_iter = produce_values()
try:
while True:
i = next(values_iter)
do_something(i)
except StopIteration as e:
values_summary = e.value
But this throws away the simplicity of the for loop. I can't use `yield from`
since that requires the calling code to be, itself, a generator. Is there a
simpler way than the roll-ones-own for loop shown above?
## Answer summary
Combining answers from @Chad S. and @KT, the simplest appears to turn my
generator function into a class using the iterator protocol:
class ValueGenerator():
def __iter__(self):
yield 1
yield 2
# and so on
self.summary = {...}
vg = ValueGenerator()
for i in vg:
do_something(i)
values_summary = vg.summary
And @Ferdinand Beyer's answer is simplest if I can't refactor the value
producer.
Answer: You could make a helper wrapper, that would catch the `StopIteration` and
extract the value for you:
from functools import wraps
class ValueKeepingGenerator(object):
def __init__(self, g):
self.g = g
self.value = None
def __iter__(self):
self.value = yield from self.g
def keep_value(f):
@wraps(f)
def g(*args, **kwargs):
return ValueKeepingGenerator(f(*args, **kwargs))
return g
@keep_value
def f():
yield 1
yield 2
return "Hi"
v = f()
for x in v:
print(x)
print(v.value)
|
How can I extract specific elements out of a unstructured list and put them into a dataframe using Python
Question: I have a long list of strings and I want to extract only rows that have
"Town":"Some City" & "State":"Some State" and then put those values into a
dataframe with town and state as column headers. I've copied an extract of the
strings below (it excludes the beginning [ and ending ] because the list is
really long. Any ideas?
' "IsPayAtLocation": null,',
' "IsMembershipRequired": null,',
' "IsAccessKeyRequired": null,',
' "ID": 1,',
' "Title": "Public"',
' },',
' "UsageCost": "Free",',
' "AddressInfo": {',
' "ID": 57105,',
' "Title": "Somerset North",',
' "AddressLine1": "2800 W. Big Beaver Rd",',
' "AddressLine2": null,',
' "Town": "Troy",',
' "StateOrProvince": "MI",',
' "Postcode": "48084",',
' "CountryID": 2,',
' "Country": {',
' "ISOCode": "US",'
Answer:
^[^,]*\b(?:Town|State).*$
You can use this `re.findall`.See demo.
<https://regex101.com/r/hE4jH0/34>
import re
p = re.compile(r'^[^,]*\b(?:Town|State).*$', re.MULTILINE)
test_str = "\"UsageCost\"', ' \"Free\",']\n[' \"AddressInfo\"', ' {']\n[' \"ID\"', ' 57105,']\n[' \"Title\"', ' \"Somerset North\",']\n[' \"AddressLine1\"', ' \"2800 W. Big Beaver Rd\",']\n[' \"AddressLine2\"', ' null,']\n[' \"Town\"', ' \"Troy\",']\n[' \"StateOrProvince\"', ' \"MI\",']\n[' \"Postcode\"', ' \"48084\",']\n[' \"CountryID\"', ' 2,']\n[' \"Country\"', ' {']\n[' \"ISOCode\"', ' \"US\",']\n[' \"ContinentCode\"', ' \"NA\",']\n[' \"ID\"', ' 2,']\n[' \"Title\"', ' \"United States\"']"
re.findall(p, test_str)
|
String format function does not parse my slashes character?
Question: I am doing a small python script to perform a wget call, however I am
encountering an issue when I am replacing the string that contains the url/ip
address and that it will be given to my "wget" string
import os
import sys
usr = sys.argv[1]
pswd = sys.argv[2]
ipAddr = sys.argv[3]
wget = "wget http://{IPaddress}"
wget.format(IPaddress=ipAddr)
print "The command wget is %s" %wget
os.system(wget)
If I run that script I get the snippet below, wher I know that wget fails,
because the variable ipAddr has not replaced IPaddress pattern, so I guess
that the issue has to do with the slashes in the url. My question is why that
pattern is not replaced?
python test.py 1 2 www.website.org The command wget is wget http://{IPaddress}
--2015-12-03 20:26:11-- http://%7Bipaddress%7D/
Resolving {ipaddress} ({ipaddress})... failed: Name or service not known.
Answer: You aren't assigning the result of the `format` call to anything - you're just
throwing it away. Try this instead:
wget = "wget http://{IPaddress}"
wget = wget.format(IPaddress=ipAddr)
print "The command wget is %s" %wget
os.system(wget)
Alternatively, this seems a bit cleaner:
wget = "wget http://{IPaddress}".format(IPaddress=ipAddr)
print "The command wget is %s" %wget
os.system(wget)
|
Python - Finding keywords in a CSV
Question: Okay, so basically, I have this project to create a troubleshooting program
for an electronic device. It asks which device you have, so for example phone,
then asks for the make, model, etcetera..
I then want the program to ask, 'What is the problem', which is fine, but I
want to have a CSV file with problems in one column, and solutions in the next
column.
So from the users input of for example saying 'My phone will not charge' I
want it to search the CSV file for, for example 'charge', or 'not charge', and
then print out the solution.
How would I go about doing this? I've been sat here thinking for a while now,
but I have no clue.
If you guys have any other suggestions of doing this, please offer away.
Answer: So you have keywords, problems and solutions.
Usually, one problem can, and will have multiple solutions.
So basically, if you are using a csv, that means that you'll have a column
'solution' with a few times the same solution. Which isn't very good in terms
of maintenance (let's say you've made a typo error in the solution, how do you
change it everywhere?)
It's really easy to import a csv to a relational database (for instance MySQL
and using MySQL Workbench). Using SQL allows you to use great functions, is
way faster than using csv, and overall allows you later to use an ORM to make
something great like plugging django on your database.
Tables :
- word : id_word, word
- problem : id_problem, problem
- solution : id_solution, solution
- problem_solution : id_problem, id_solution (a problem can have multiple solutions).
- word_problem : id_word, id_problem (a word can be found in multiple problems).
Logic :
ask user for problem.
split problem on space (" ") to get words.
for every word, ask your db for related problems.
show your user distinct related problems (ordering by the most occuring problem)
user selects a problem
fetch solutions for the problem and show them.
|
Python call URL with key=value pairs
Question: Since I do my first steps in Python, I try to figure out, how can I do a
simple URL call in Python with key=value pairs like:
http://somehost/somecontroller/action?key1=value1&key2=value2
I tried with some things like:
key1 = 'value'
key2 = 10
requests.get("http://somehost/somecontroller/action?key1=" + value + "&key2=" + str(10))
or
data={'key1': 'value', 'key2': str(10)}
requests.get("http://somehost/somecontroller/action", params=data)
(from [here](http://stackoverflow.com/questions/22974772/querystring-array-
parameters-in-python-using-requests))
But this don't work. I also tried it by calling `curl` with
`subprocess.Popen()` on different ways, but uhm...
I don't want to check the request, the URL call will be enough.
Answer: Using the `requests` library you can use
[`PreparedRequest.prepare_url`](http://docs.python-
requests.org/en/latest/api/#requests.PreparedRequest.prepare_url) to encode
the parameters to an url, like:
import requests
p = requests.models.PreparedRequest()
data={'key1': 'value', 'key2': str(10)}
p.prepare_url(url='http://somehost.com/somecontroller/action', params=data)
print p.url
In the last print, you should get:
http://somehost.com/somecontroller/action?key2=10&key1=value
|
Django S3BotoStorage __init__ override error , "has no attribute 'rsplit'"
Question: The last lines of the trace:
File "/usr/local/lib64/python3.4/site-packages/django/core/files/storage.py", line 328, in get_storage_class
return import_string(import_path or settings.DEFAULT_FILE_STORAGE)
File "/usr/local/lib64/python3.4/site-packages/django/utils/module_loading.py", line 15, in import_string
module_path, class_name = dotted_path.rsplit('.', 1)
AttributeError: type object 'S3StaticStorage' has no attribute 'rsplit'
`S3StaticStorage`:
class S3StaticStorage(S3BotoStorage):
def __init__(self, *args, **kwargs):
kwargs['bucket'] = getattr(settings, 'AWS_BUCKET_STATIC')
super(S3StaticStorage, self).__init__(*args, **kwargs)
I have a file called `prod.py` which imports `common.py`, and this is
configured accordingly as the settings source in `wsgi.py` and `manage.py`. A
line in `prod.py` sets the bucket name:
AWS_BUCKET_STATIC = 'myproject-static'
This was not a problem without the override, when I was putting everything in
one bucket. Do I need to import `rsplit` when using this class or something?
It looks like it should be in-built to Python so wouldn't need an import. If I
understood it correctly, `getattr(settings, 'AWS_BUCKET_STATIC')` would get
the variable from whatever settings files Django finds, so that shouldn't be a
problem either.
* * *
Full trace:
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib64/python3.4/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line
utility.execute()
File "/usr/local/lib64/python3.4/site-packages/django/core/management/__init__.py", line 342, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib64/python3.4/site-packages/django/core/management/__init__.py", line 195, in fetch_command
klass = load_command_class(app_name, subcommand)
File "/usr/local/lib64/python3.4/site-packages/django/core/management/__init__.py", line 40, in load_command_class
return module.Command()
File "/usr/local/lib64/python3.4/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 32, in __init__
self.storage.path('')
File "/usr/local/lib64/python3.4/site-packages/django/utils/functional.py", line 204, in inner
self._setup()
File "/usr/local/lib64/python3.4/site-packages/django/contrib/staticfiles/storage.py", line 394, in _setup
self._wrapped = get_storage_class(settings.STATICFILES_STORAGE)()
File "/usr/local/lib64/python3.4/site-packages/django/core/files/storage.py", line 328, in get_storage_class
return import_string(import_path or settings.DEFAULT_FILE_STORAGE)
File "/usr/local/lib64/python3.4/site-packages/django/utils/module_loading.py", line 15, in import_string
module_path, class_name = dotted_path.rsplit('.', 1)
AttributeError: type object 'S3StaticStorage' has no attribute 'rsplit'
Answer: It [looks like](https://django-
storages.readthedocs.org/en/latest/backends/amazon-S3.html)
`STATICFILES_STORAGE` is expecting a string representing the module path:
`STATICFILES_STORAGE='path.to.your.S3StaticStorage'`
|
lxml can not parse xml (wether encoding is utf-8 or not) [python]
Question: My code:
import re
import requests
from lxml import etree
url = 'http://weixin.sogou.com/gzhjs?openid=oIWsFt__d2wSBKMfQtkFfeVq_u8I&ext=2JjmXOu9jMsFW8Sh4E_XmC0DOkcPpGX18Zm8qPG7F0L5ffrupfFtkDqSOm47Bv9U'
r = requests.get(url)
items = r.json()['items']
1. without encode('utf-8'):
`etree.fromstring(items[0])` output:
ValueError
Traceback (most recent call last)
<ipython-input-69-cb8697498318> in <module>()
----> 1 etree.fromstring(items[0])
lxml.etree.pyx in lxml.etree.fromstring (src\lxml\lxml.etree.c:68121)()
parser.pxi in lxml.etree._parseMemoryDocument (src\lxml\lxml.etree.c:102435)()
ValueError: Unicode strings with encoding declaration are not supported. Please use bytes input or XML fragments without declaration.
2. with encode('utf-8'):
`etree.fromstring(items[0].encode('utf-8'))` output:
File "<string>", line unknown
XMLSyntaxError: CData section not finished
ιΆζ₯εΊιΆγ€ζ«ιΉιε§€:ιε²ε―³Iη»Ύζ, line 1, column 281
Have not idea to parse this xml..
Answer: As a workaround, you can remove `encoding` attribute before pass the string to
`etree.fromstring`:
xml = re.sub(r'\bencoding="[-\w]+"', '', items[0], count=1)
root = etree.fromstring(xml)
**UPDATE** after seeing @Lea's comment in the question:
Specify parser with explicit encoding:
xml = r.json()['items'].encode('utf-8')
root = etree.fromstring(xml, parser=etree.XMLParser(encoding='utf-8'))
|
Why does heroku local:run wants to use the global python installation instead of the currently activated virtual env?
Question: Using Heroku to deploy our Django application, everything seems to work by the
spec, except the `heroku local:run` command.
We oftentimes need to run commands through Django's manage.py file. Running
them on the **remote** , as one-off dynos, works flawlessly. To run them
**locally** , we try:
heroku local:run python manage.py the_command
Which fails, despite the fact that the current virtual env contains a Django
installation, with
ImportError: No module named django.core.management
## Diagnostic through the python path
Then `heroku local:run which python` returns:
/usr/local/bin/python
Whereas `which python` returns:
/Users/myusername/MyProject/venv/bin/python #the correct value
* * *
* Is this a bug in Heroku local:run ? Or are we missunderstanding its expected behaviour ?
* And more importantly: is there a way to have `heroku local:run` use the currently installed virtual env ?
Answer: After contacting Heroku's support, we understood the problem.
The support confirmed that `heroku local:run` should as expected use the
currently active virtual env.
The problem is a local configuration problem, due to our `.bashrc` content:
`heroku local:run` sources `.bashrc` (and in our case, this was prepending
$PATH with the path to the global Python installation, making it found before
the virtual env's). On the other hand, `heroku local` does not source this
file. To quote the last message from their support:
> heroku local:run runs the command using bash in interactive mode, which does
> read your profile, vs heroku local (aliased to heroku local:start) which
> does not run in interactive mode.
|
Can't use lable in gtk3
Question: I can't use lable in gtk3(python3), it does not work and does not give an
error.
This is my try:
from gi.repository import Gtk
window = Gtk.Window(title="About")
window.set_border_width(10)
window.connect("destroy", lambda w: Gtk.main_quit())
hbox = Gtk.Box(spacing=6)
window.add(hbox)
lbl=gtk.Label("add")
hbox.pack_start(lbl, True, True, 0)
lbl2=gtk.Label("add")
hbox.pack_start(lbl2, True, True, 0)
lbl3=gtk.Label("add")
hbox.pack_start(lbl3, True, True, 0)
lbl4=gtk.Label("add")
hbox.pack_start(lbl4, True, True, 0)
def ex(button1):
exit()
button2 = Gtk.Button.new_with_label("Exit")
button2.connect("clicked", ex)
hbox.pack_start(button2, True, True, 0)
window.show_all()
Gtk.main()
What is wrong?
Answer: You use the identifier `gtk` without previously defining it. You probably
meant to say `Gtk` instead. Remember: Python identifiers are case-sensitive.
After fixing that error, I get this, presumably correct, result:
[](http://i.stack.imgur.com/qBX3M.png)
|
No module name celery with uWSGI and Python3
Question:
Traceback (most recent call last):
File "./fb_archive/__init__.py", line 5, in <module>
from .celery import app as celery_app
File "./fb_archive/celery.py", line 5, in <module>
from celery import Celery
ImportError: No module named 'celery'
unable to load app 0 (mountpoint='') (callable not found or import error)
uWGSI says `No module name celery`. It works well without uWGSI. I use python
3.5 and virtualenv.
I test with python 2.7 and uWGSI, it can load celery. How can I load celery
with python 3.x?
This is my celery.py.
from __future__ import absolute_import
import os
from celery import Celery
from django.conf import settings
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'fb_archive.settings')
app = Celery('fb_archive')
# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
app.conf.update(
CELERY_RESULT_BACKEND='djcelery.backends.database:DatabaseBackend',
)
app.conf.update(
CELERY_RESULT_BACKEND='djcelery.backends.cache:CacheBackend',
)
@app.task(bind=True)
def debug_task(self):
print('Request: {0!r}'.format(self.request))
And this is my **init**.py.
from __future__ import absolute_import
# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app
Answer: It's possible that you have celery installed for Python2.7 but not for
Python3. You can try installing it for Python3 using `pip3 install celery`.
It is also possible that you _do_ have celery installed for Python3 in your
normal environment, but that it's not installed in your virtualenv.
|
How do I change directory in python so it remains after running the script?
Question: I'm trying to change the terminal directory through a python script. I've seen
this [post](http://stackoverflow.com/questions/431684/how-do-i-cd-in-
python/431715 "post") and others like it so I know about os.chdir, but it's
not working the way I'd like. os.chdir appears to change the directory, but
only for the python script. For instance I have this code.
#! /usr/bin/env python
import os
os.chdir("/home/chekid/work2/")
print os.getcwd()
Unfortunately after running I'm still in the directory of the python script
(e.g. /home/chekid) rather than the directory I want to be in. See below.
gandalf(pts/42):~> pwd
/home/chekid
gandalf(pts/42):~> ./changedirectory.py
/home/chekid/work2
gandalf(pts/42):~> pwd
/home/chekid
Any thoughts on what I should do?
_Edit_ : Looks like what I'm trying to do doesn't exist in 'normal' python. I
did find a work around, although it doesn't look so elegant to me.
cd `./changedirectory.py`
Answer: The current working directory is an attribute of a process. It cannot be
changed by another program, such as changing the current working directory in
your shell by running a separate Python program. This is why `cd` is _always_
a shell built-in command.
|
python 3 make subsection for configparser
Question: I'm trying to convert one open source project from Python 2 to Python 3
Project uses configobj module which is not supported for Python 3.
Project uses subsections in config file.
How to realize similar functionality with configparser module?
e.q. configfile.txt is:
[General Log]
filename = log.txt
[Thread1]
filename = thread1.txt
[[log]]
filename = thread1_log.txt
and with this config file i can do like
from configparser import ConfigParser
congfile = ConfigParser()
configfile.read('configfile.txt')
print(configfile['Thread1']['Log']['filename'])
should print thread1_log.txt
is it possible to make new class of configparser class to do this? Any modules
to support this functionality with ython 3
Answer: Per the
[documentation](https://docs.python.org/3.4/library/configparser.html#supported-
ini-file-structure), `ConfigParser` only supports one section level, so
unfortunately you can't do that using the `ConfigParser` library.
If you're using [this `configobj`
module](https://pypi.python.org/pypi/configobj/5.0.6), it says it supports
Python 3. Since you're porting the project from 2 to 3, you might consider
upgrading to the new version of the `configobj` library at the same time.
|
Python XPath : Is it possible to have optional XPath query?
Question: i have the following way of parsing an xml
import re
from lxml.html.soupparser import fromstring
inString = """
<doc>
<q></q>
<p1>
<p2 dd="ert" ji="pp">
<p3>1</p3>
<p3>2</p3>
<p3>32</p3>
<p3>3</p3>
</p2>
<p2 dd="ert" ji="pp">
<p3>4</p3>
<p3>5</p3>
<p3>ABC</p3>
<p3>6</p3>
</p2>
</p1>
<r></r>
<p1>
<p2 dd="ert" ji="pp">
<p3>7</p3>
<p3>8</p3>
<p3>ABC</p3>
<p3>9</p3>
</p2>
<p2 dd="ert" ji="pp">
<p3>10</p3>
<p3>11</p3>
<p3>XYZ</p3>
<p3>12</p3>
</p2>
</p1>
</doc>
"""
root = fromstring(inString)
#nodes = root.xpath("./doc//p1/p2/p3[contains(text(),'ABC') or contains(text(),'XYZ')]/preceding-sibling::p3")
ns = {"re": "http://exslt.org/regular-expressions"}
nodes = root.xpath(".//p3[re:match(.,'XYZ') or re:match(.,'ABC')]/preceding-sibling::p3", namespaces=ns)
which gives me
4 5 7 8 10 11
so it completely skips the first `<p2>` my ideal output is
1 2 32 3 4 5 7 8 10 11
so, if i cant find a `<p3>ABC<p3>` or `<p3>XYZ<p3>` in a `<p2>`, i still want
all the `<p3>` s of that `<p2>`. is that possible?
**EDIT**
i tried
".//p3[re:match(.,'XYZ') or re:match(.,'ABC')]/preceding-sibling::p3 | .//p3"
but that gives me
1 2 32 3 4 5 ABC 6 7 8 ABC 9 10 11 XYZ 12
which is everything
**Partial Solution**
i tried the following xpath
".//p3[re:match(.,'XYZ') or re:match(.,'ABC')]/preceding-sibling::p3 | .//p3[not (contains(text(),'ABC') or contains(text(),'XYZ'))]/preceding-sibling::p3"
which gives me
1 2 32 4 5 ABC 7 8 ABC 10 11 XYZ
which is better but still incorrect. note that it is missing `6` and it
includes the `ABC` and `XYZ` which i did not want
Answer: Good start, how about:
.//p3[text() = 'XYZ' or text() = 'ABC']/preceding-sibling::p3 | .//p2[not(p3[text() = 'ABC' or text() = 'XYZ'])]/p3
That is: for each p2 which has no p3 children equal to ABC or XYZ, give me the
p3 children.
(string equals instead of regexp, because regexps are not needed in this
example, but you could use regexp instead)
|
Understanding "Bitwise-And (&)" and "Unary complement(~)" in c++
Question: I have some trouble understanding `Bitwise-And` and `Unary Complement` when
both are used in this code snippet
if((oldByte==m_DLE) & (newByte==m_STX)) {
int data_index=0;
//This below line --- does it returns true if both the oldByte and newByte are not true
//and within timeout
while((timeout.read_s()<m_timeout) & ~((oldByte==m_DLE) & (newByte==m_ETX))) {
if(Serial.available()>0) {
oldByte=newByte;
newByte=Serial.read();
if(newByte==m_DLE) {
.
.
.
are the both operators `& ~`are performing a logical not operation like
checking until if both `oldByte` and `newByte` are false
The above code is from the [link](https://github.com/GraemeWilson/Arduino-
Python-Framing-
CRC16/blob/af28e4c5106505c7d1227bf840fef55db0f679af/Arduino/Framing.cpp) \-->
line 227 of the code
I am trying to use the implement the code for my application in C but without
the timing functions
if((oldByte==DLE) && (newByte== STX)) {
data_index = 0;
// is this the correct implematation for above C++ code to C
while(! ((oldByte== DLE) && (newByte== ETX))){
oldByte = newByte;
Is this method correct for implementing in C
Answer:
(timeout.read_s()<m_timeout) & ~((oldByte==m_DLE) & (newByte==m_ETX))
is equivalent to (but probably less readable than)
(timeout.read_s()<m_timeout) && !(oldByte==m_DLE && newByte==m_ETX)
which is equivalent to (and IMO less readable than)
(timeout.read_s()<m_timeout) && (oldByte!=m_DLE || newByte!=m_ETX)
Edit: should add a caveat about short-circuiting. Although the particular
example statements will all return the same value, using && or || will skip
evaluating pieces that can't impact the result. This isn't important in your
specific example, but could be very important in an example like this:
(oldByte!=nullptr & *oldByte == m_ETX) // will crash when oldByte=nullptr.
(oldByte!=nullptr && *oldByte == m_ETX) // will evaluate to false when oldByte=nullptr.
|
No module named django.core.wsgi with nginx, uwsgi and virtualenv
Question: uwsgi.ini
[uwsgi]
vhost = true
plugin = python
socket = /tmp/pjwards.sock
master = true
enable-threads = true
processes = 2
wsgi-file = /home/ubuntu/workspace/ward/www/fb_archive/wsgi.py
virtualenv = /home/ubuntu/.virtualenvs/fb_archive
chdir = /home/ubuntu/workspace/ward/www/fb_archive
touch-reload = /home/ubuntu/workspace/ward/www/reload
wsgi.py
import site
import os
import sys
from django.core.wsgi import get_wsgi_application
from mezzanine.utils.conf import real_project_name
site.addsitedir('/home/ubuntu/.virtualenvs/fb_archive/lib/python3.4/site-packages')
sys.path.insert(0, '/home/ubuntu/workspace/ward')
os.environ.setdefault("DJANGO_SETTINGS_MODULE",
"%s.settings" % real_project_name("fb_archive"))
application = get_wsgi_application()
uWSGI does not work by `ImportError: No module named django.core.wsgi`. I use
nginx, uwsgi and virtualenv with python3.
Traceback (most recent call last):
File "/home/ubuntu/workspace/ward/www/fb_archive/wsgi.py", line 13, in <module>
from django.core.wsgi import get_wsgi_application
ImportError: No module named django.core.wsgi
unable to load app 0 (mountpoint='') (callable not found or import error)
Answer: You're doing the import before you've added your virtualenv to the pythonpath,
so naturally the module can't be found. Move the import to just before the
`get_wsgi_application()` call itself.
|
Connecting to MongoDB remotely and getting ServerSelectioinTimeoutError
Question: New to MongoDB here and I'm having some trouble connecting to the server. I
get the error ServerSelectionTimeoutError: xxx.xxx.xxx.xxx:27017:timed out
I'm using PyMongo 2.8 on OSX 10.10.
import sys
sys.path.append('/usr/local/lib/python2.7/site-packages')
from pymongo import MongoClient
client = MongoClient('mongodb://dba:[password]@xxx.xxx.xxx.xxx:27017/Admin') #the real password has the square brackets
db = client['MyDB']
x=[]
userData = db.users.find()
for user in userData:
x.append(user)
print x
Answer: I was using an internal ip address in the client string. External ip fixed it.
|
Python: itertools.product consuming too much resources
Question: I've created a Python script that generates a list of words by permutation of
characters. I'm using `itertools.product` to generate my permutations. My char
list is composed by letters and numbers
**01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVXYZ**. Here is my
code:
#!/usr/bin/python
import itertools, hashlib, math
class Words:
chars = '01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVXYZ'
def __init__(self, size):
self.make(size)
def getLenght(self, size):
res = []
for i in range(1, size+1):
res.append(math.pow(len(self.chars), i))
return sum(res)
def getMD5(self, text):
m = hashlib.md5()
m.update(text.encode('utf-8'))
return m.hexdigest()
def make(self, size):
file = open('res.txt', 'w+')
res = []
i = 1
for i in range(1, size+1):
prod = list(itertools.product(self.chars, repeat=i))
res = res + prod
j = 1
for r in res:
text = ''.join(r)
md5 = self.getMD5(text)
res = text+'\t'+md5
print(res + ' %.3f%%' % (j/float(self.getLenght(size))*100))
file.write(res+'\n')
j = j + 1
file.close()
Words(3)
This script works fine for list of words with max 4 characters. If I try 5 or
6 characters, my computer consumes 100% of CPU, 100% of RAM and freezes.
Is there a way to restrict the use of those resources or optimize this heavy
processing?
Answer: Does this do what you want?
I've made all the changes in the make method:
def make(self, size):
with open('res.txt', 'w+') as file_: # file is a builtin function in python 2
# also, use with statements for files used on only a small block, it handles file closure even if an error is raised.
for i in range(1, size+1):
prod = itertools.product(self.chars, repeat=i)
for j, r in enumerate(prod):
text = ''.join(r)
md5 = self.getMD5(text)
res = text+'\t'+md5
print(res + ' %.3f%%' % ((j+1)/float(self.get_length(size))*100))
file_.write(res+'\n')
Be warned this will still chew up gigabytes of memory, but not virtual memory.
EDIT: As noted by Padraic, there is no **file** keyword in Python 3, and as it
is a "bad builtin", it's not too worrying to override it. Still, I'll name it
file_ here.
EDIT2:
To explain why this works so much faster and better than the previous,
original version, you need to know how **lazy** evaluation works.
Say we have a simple expression as follows (for Python 3) (use xrange for
Python 2):
a = [i for i in range(1e12)]
This immediately evaluates 1 trillion elements into memory, overflowing your
memory.
So we can use a generator to solve this:
a = (i for i in range(1e12))
Here, none of the values have been evaluated, just given the interpreter
instructions on how to evaluate it. We can then iterate through each item
**one by one** and do work on each separately, so almost nothing is in memory
at a given time (only 1 integer at a time). This makes the seemingly
impossible task very manageable.
The same is true with itertools: it allows you to do memory-efficient, fast
operations by using iterators rather than lists or arrays to do operations.
In your example, you have 62 characters and want to do the cartesian product
with 5 repeats, or 62**5 (nearly a billion elements, or over 30 gigabytes of
ram). This is prohibitively large."
In order to solve this, we can use iterators.
chars = '01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVXYZ'
for i in itertools.product(chars, repeat=5):
print(i)
Here, only a single item from the cartesian product is in memory at a given
time, meaning it is very memory efficient.
However, if you evaluate the full iterator using list(), it then exhausts the
iterator and adds it to a list, meaning the nearly one billion combinations
are suddenly in memory again. We don't need all the elements in memory at
once: just 1. Which is the power of iterators.
Here are links to the [itertools
module](https://docs.python.org/2/library/itertools.html) and another
explanation on [iterators in Python 2](http://anandology.com/python-practice-
book/iterators.html) (mostly true for 3).
|
POS tagging using spaCy
Question: I am trying to do POS tagging using the spaCy module in Python.
Here is my code for the same
from spacy.en import English, LOCAL_DATA_DIR
import spacy.en
import os
data_dir = os.environ.get('SPACY_DATA', LOCAL_DATA_DIR)
nlp = English(parser=False, tagger=True, entity=False)
def print_fine_pos(token):
return (token.tag_)
def pos_tags(sentence):
sentence = unicode(sentence, "utf-8")
tokens = nlp(sentence)
tags = []
for tok in tokens:
tags.append((tok,print_fine_pos(tok)))
return tags
a = "we had crispy dosa"
print pos_tags(a)
Output:
[(We , u'PRP'), (had , u'VBD'), (crispy , u'NN'), (dosa, u'NN')]
Here it returns crispy as a noun instead of an adjective. However, if I use a
test sentence like
a="we had crispy fries"
It recognizes that crispy is an adjective. Here is the output:
[(we , u'PRP'), (had , u'VBD'), (crispy , u'JJ'), (fries, u'NNS')]
I think the primary reason why crispy wasn't tagged as an adjective in the
first case was because dosa was tagged as 'NN' whereas fries was tagged as
'NNS' in the second case.
Is there any way I can get crispy to be tagged as an adjective in the second
case too?
Answer: `TL;DR: You should accept the occasional error.`
Details:
Spacy's tagger is statistical, meaning that the tags you get are its best
estimate based on the data it was shown during training. I would guess those
data did not contain the word `dosa`. The tagger had to guess, and guessed
wrong. There isn't an easy way to correct its output, because it is not using
rules or anything you can modify easily. The model has been trained on a
standard corpus of English, which may be quite different to the kind of
language you are using it for (domain). If error rate is too high for your
purposes, you can re-train the model using domain-specific data. This will be
very laborious though. Ask yourself what you are trying to achieve and whether
3% error rate in PoS tagging is the worst of your problems.
In general, you shouldn't judge the performance of a statistical system on a
case-by-case basis. The accuracy of modern English PoS taggers is [around
97%](http://nlp.stanford.edu/pubs/CICLing2011-manning-tagging.pdf), which is
roughly the same as the average human. You will inevitably get some errors.
However, the errors of the model will not be the same as the human errors, as
the two have "learnt" how to solve the problem in a different way. Sometimes
the model will get confused by things you and I consider obvious, e.g. your
example. This doesn't mean it is bad overall, or that PoS tagging is your real
problem.
|
Python stuck in a single thread of a multi-threaded program
Question: I'm currently writing a program that is attempting to synchronize a visitor,
car, pump, and gas station thread at a zoo where guests arrive, wait for an
available car, take a tour, then exit, the cars must refuel every 5 rides, and
the gas station must refuel every time 3 cars are refilled. My tests are with
35 visitors, 6 cars, 5 gas pumps, and a time interval of 2. The program reads
a text file with the number of guests, cars, pumps, and a time interval
between visitors boarding vehicles, then uses the data to fill a class. I
create methods for each thread, then create the threads themselves in main. My
problem is that my program gets stuck at 6 vehicles, which is the number
specified by the text file, after running my first thread method,
visitor_thread, and I cannot tell if any other threads are even running
concurrently. I am a total novice at multithreading and python alike, and I'm
not sure what the problem is. I have worked on the project for twelve hours
straight and have been stuck at this point for the past four hours. In theory,
visitor_thread, car_thread, and gas_station_thread should all run concurrently
from main, and visitor_thread should have vehicles to work with again after
some visitors finish their ride, but I just get stuck with six full cars in an
infinite loop within visitor_thread. What is causing this infinite loop and
how can I make sure all of my threads are actually running?
My code:
from threading import Thread
from threading import Lock
from threading import Event
event = Event()
lock = Lock()
done = Event()
is_done = 0
class Arguments:
def __init__(self, m_visitors, n_cars, k_pumps, t_time, thread_num, _done):
self.m_visitors = m_visitors
self.n_cars = n_cars
self.k_pumps = k_pumps
self.t_time = t_time
self.thread_num = thread_num
self.done = _done
class Car:
def __init__(self, control, rides, time, in_service, int_cus, in_queue):
self.control = control
self.rides = rides
self.time = time
self.in_service = in_service
self.int_cus = int_cus
self.in_queue = in_queue
class Pump:
def __init__(self, control, in_use, car_num, time):
self.control = control
self.in_use = in_use
self.car_num = car_num
self.time = time
class PumpQueue:
def __init__(self, pQueue, MAXsize, front, back, size):
self.q = Lock()
self.pQueue = pQueue
self.MAXsize = MAXsize
self.front = front
self.back = back
self.size = size
def visitor_thread(_visitor):
global is_done
visitor = _visitor
v = visitor.m_visitors
c = visitor.n_cars
p = visitor.k_pumps
t = visitor.t_time
id = visitor.thread_num
i = 0
j = 0
while i < v:
for j in range(0, c):
lock.acquire()
if cars[j].in_service is False and cars[j].rides < 5:
print('\nVisitor %d is currently in car %d' % (i+1, j+1))
cars[j].in_service = True
i += 1
print('\n%d customers waiting for a ride.' % (v - i))
lock.release()
break
lock.release()
lock.acquire()
is_done += 1
lock.release()
def car_thread(_car):
global is_done
carThread = _car
cars_done = 0
v = carThread.m_visitors
c = carThread.n_cars
p = carThread.k_pumps
t = carThread.t_time
id = carThread.thread_num
i = 0
while cars_done == 0:
cars_in_service = 0
while i < c:
lock.acquire()
if cars[i].in_service is True and cars[i].rides < 5:
# Car still being used, add more time
cars[i].time += 1
if cars[i].time == t:
cars[i].in_service = False
cars[i].rides += 1
cars[i].time = 0
if cars[i].rides == 5 and cars[i].in_queue is False:
push(i)
cars[i].in_queue = True
if cars[i].in_service is False:
cars_in_service += 1
i += 1
lock.release()
if cars_in_service == c and is_done >= 1:
cars_done = 1
lock.acquire()
is_done += 1
lock.release()
def gas_station_thread(_gas_station):
global is_done
gas_station = _gas_station
truck = False
cars_filled = 0
v = gas_station.m_visitors
c = gas_station.n_cars
p = gas_station.k_pumps
t = gas_station.t_time
id = gas_station.thread_num
gas_done = 0
pumps_in_service = 0
j = 0
while gas_done == 0:
while j < p:
lock.acquire()
if pumps[j].in_use is True:
pumps[j].time += 1
if pumps[j].time == 3:
lock.acquire()
cars[j].in_service = 0
cars[j].rides = 0
cars[j].time = 0
cars[j].in_queue = False
lock.release()
pumps[j].time = 0
pumps[j].in_use = False
cars_filled += 1
pumps_in_service -= 1
if truck is True and pumps[j].in_use is False:
truck = False
print('Fuel Truck is currently filling up the gas station.')
elif pumps[j].in_use is True and pump_line.size > 0:
pumps_in_service += 1
pumps[j].in_use = True
pumps[j].car_num.pop()
print('Car %d, pump %d' % (pumps[j].car_num + 1, i + 1))
pumps[j].time = 0
j += 1
lock.release()
if cars_filled > 3:
print('The Fuel Truck is on its way')
truck = True
cars_filled = 0
if pumps_in_service == 0 and is_done == 2:
gas_done = True
lock.acquire()
is_done += 1
lock.release()
def pop():
lock.acquire()
fr = pump_line.front
f = pump_line.pQueue[fr]
print("\n%d cars are waiting for pumps" % int(pump_line.size - 1))
if fr < (pump_line.MAXsize - 1):
pump_line.front += 1
else:
pump_line.front = 0
lock.release()
return f
def push(_c):
c =_c
lock.acquire()
b = pump_line.back
pump_line.pQueue[b] = c
print("\n%d cars are waiting for pumps" % int(pump_line.size + 1))
if b < (pump_line.MAXsize - 1):
pump_line.back += 1
else:
pump_line.back = 0
lock.release()
def isEmpty():
lock.acquire()
if (pump_line.front == pump_line.back):
boolean = True
else:
boolean = False
lock.release()
return boolean
if __name__ == "__main__":
arguments = Arguments(0, 0, 0, 0, 0, False)
main = Arguments(0, 0, 0, 0, 0, False)
thread = []
round_number = 0
io_control = 0
input_file = []
number_of_threads = 3
print("Enter the name of the text file to use as input:")
while io_control == 0:
try:
filename = input()
input_file = open(filename)
io_control = 1
except IOError:
print("Specified file does not exist, enter a different text file:")
# parse file into lines, separating by endlines
file_lines = []
num_lines = 0
for line in input_file:
line = line.replace(",", " ")
line = line.split()
num_lines += 1
if line:
line = [int(i) for i in line]
file_lines.append(line)
while main.done is False and round_number < num_lines:
main.m_visitors = int(file_lines[round_number][0])
main.n_cars = int(file_lines[round_number][1])
main.k_pumps = int(file_lines[round_number][2])
main.t_time = int(file_lines[round_number][3])
print("\nRound Number: %d" % (round_number + 1))
if main.n_cars == 0:
print('No data to read in this round, press enter to continue:')
input()
print("Number of Visitors: %d" % main.m_visitors)
print("Number of Cars: %d" % main.n_cars)
print("Number of Pumps: %d" % main.k_pumps)
print("Units of Time: %d" % main.t_time)
M = main.m_visitors
N = main.n_cars
K = main.k_pumps
T = main.t_time
thread_info = []
cars = []
pumps = []
for i in range(0, 3):
temp = Arguments(M, N, K, T, i, False)
thread_info.append(temp)
for i in range(0, N):
temp = Car(0, 0, 0, False, 0, False)
cars.append(temp)
for i in range(0, K):
temp = Pump(0, False, 0, 0)
pumps.append(temp)
pump_line = PumpQueue(0, 0, 0, 0, N)
visitorThread = Thread(target=visitor_thread, args=(thread_info[0],))
thread.append(visitorThread)
carsThread = Thread(target=car_thread, args=(thread_info[1],))
thread.append(carsThread)
gasThread = Thread(target=gas_station_thread, args=(thread_info[2],))
thread.append(gasThread)
visitorThread.start()
carsThread.start()
gasThread.start()
visitorThread.join()
carsThread.join()
gasThread.join()
round_number += 1
My output:
> Round Number: 1 Number of Visitors: 35 Number of Cars: 6 Number of Pumps: 5
> Units of Time: 2
>
> Visitor 1 is currently in car 1
>
> 34 customers waiting for a ride.
>
> Visitor 2 is currently in car 2
>
> 33 customers waiting for a ride.
>
> Visitor 3 is currently in car 3
>
> 32 customers waiting for a ride.
>
> Visitor 4 is currently in car 4
>
> 31 customers waiting for a ride.
>
> Visitor 5 is currently in car 5
>
> 30 customers waiting for a ride.
>
> Visitor 6 is currently in car 6
>
> 29 customers waiting for a ride.
Answer: I think there's an index problem here:
if cars[j].in_service is False and cars[i].rides < 5:
should be
if cars[j].in_service is False and cars[j].rides < 5:
Index for cars is j not i
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.