text
stringlengths 226
34.5k
|
---|
can't get object from swift tempurl
Question: I setup SAIO on VirtualBox and want to check how's temp url feature works for
Swift.
here is the object I created call test.txt under container "testCon", you can
see the content and swift list the object
swift@swift-VirtualBox:~/bin$ curl -X GET -H 'X-Auth-Token: AUTH_tkba199b23eeec4998b7119d2c9c903216' http://127.0.0.1:8080/v1/AUTH_test/testCon/test.txt
this is a test
swift@swift-VirtualBox:~/bin$ swift -A http://127.0.0.1:8080/auth/v1.0 -U test:tester -K testing list testCon
test.txt
I follow the link (<http://ceph.com/docs/master/radosgw/swift/tempurl/>) to
setup temp url key for temp url
swift@swift-VirtualBox:~/bin$ curl -X POST -H 'X-Auth-Token: AUTH_tkba199b23eeec4998b7119d2c9c903216' -H 'X-Account-Meta-Temp-URL-Key: secret' http://127.0.0.1:8080/v1/AUTH_test/testCon/test.txt
<html><h1>Accepted</h1><p>The request is accepted for processing.</p></html>swift@swift-VirtualBox:~/bin$
swift@swift-VirtualBox:~/bin$ swift -A http://127.0.0.1:8080/auth/v1.0 -U test:tester -K testing post -m "Temp-URL-Key:secret"
and follow the python example to generate the temp url links
* * *
import hmac
from hashlib import sha1
from time import time
method = 'GET'
host = "http://127.0.0.1:8080"
duration_in_seconds = 300 # Duration for which the url is valid
expires = int(time() + duration_in_seconds)
path = '/v1/AUTH_test/testCon/test.txt'
key = 'secret'
hmac_body = '%s\n%s\n%s' % (method, expires, path)
hmac_body = hmac.new(key, hmac_body, sha1).hexdigest()
sig = hmac.new(key, hmac_body, sha1).hexdigest()
rest_uri = "{host}{path}?temp_url_sig={sig}&temp_url_expires={expires}".format(
host=host, path=path, sig=sig, expires=expires)
print rest_uri
* * *
but when i put the link in cli, it always show: **No such file or directory**
swift@swift-VirtualBox:~/bin$ http://127.0.0.1:8080/v1/AUTH_test/testCon/test.txt?temp_url_sig=83fa35362613a18c2ca0b48203ccda61d2229daa&temp_url_expires=1439938672
[1] 6125
swift@swift-VirtualBox:~/bin$ -bash: http://127.0.0.1:8080/v1/AUTH_test/testCon/test.txt?temp_url_sig=83fa35362613a18c2ca0b48203ccda61d2229daa: **No such file or directory**
can anyone help ? Please provide some suggestions to me ?
Thanks Million !
Answer: You need to browse to the URL generated by the python script. You can do this
either in a web browser or using the curl command from the command line:
curl http://127.0.0.1:8080/v1/AUTH_test/testCon/test.txt?temp_url_sig=83fa35362613a18c2ca0b48203ccda61d2229daa&temp_url_expires=1439938672
Just placing the url on the command line by itself won't do anything.
|
Ipython Notebook Widget displays 'None' (the return value)
Question: I have the following (example) code to display a widget and update a value
based on the widget. It works fine, except in my Ipython notebook, None is
displayed at the end (which is what was returned from my function). How do I
hide that/ return something that won't be displayed?
from ipywidgets import widgets, interact, interactive
from IPython.display import display, clear_output
opts = 'dog'
def update_val(a):
ValuesWidget.options = [a]
ArrayWidget = interactive(update_val,a=widgets.Dropdown(description="Pick an animal: ",options=['dog','cat','mouse']))
ValuesWidget = widgets.Dropdown(description="Display this value: ",options=[opts])
display(ArrayWidget,ValuesWidget)
If I do a 'return 5' at the end of the function five is displayed instead, so
I know the issue is with the return value of the function.
Answer: In the code you're posting, you aren't returning anything so it's returning
`None` by default. Try using:
return ValuesWidget.options = [a]
|
Parallelising Python code
Question: I have written a function that returns a Pandas data frame (sample as a row
and descriptor as columns) and takes input as a list of peptides (a biological
sequence as strings data). "my_function(pep_list)" takes pep_list as a
parameter and return data frame. it iterates eache peptide sequence from
pep_list and calculates descriptor and combined all the data as pandas data
frame and returns df:
pep_list = [DAAAAEF,DAAAREF,DAAANEF,DAAADEF,DAAACEF,DAAAEEF,DAAAQEF,DAAAGEF,DAAAHEF,DAAAIEF,DAAALEF,DAAAKEF]
example:
I want to parallelising this code with the given algorithm bellow:
1. get the number of processor available as .
n = multiprocessing.cpu_count()
2. split the pep_list as
sub_list_of_pep_list = pep_list/n
sub_list_of_pep_list = [[DAAAAEF,DAAAREF,DAAANEF],[DAAADEF,DAAACEF,DAAAEEF],[DAAAQEF,DAAAGEF,DAAAHEF],[DAAAIEF,DAAALEF,DAAAKEF]]
4. run "my_function()" for each core as (example if 4 cores )
df0 = my_function(sub_list_of_pep_list[0])
df1 = my_function(sub_list_of_pep_list[1])
df2 = my_functonn(sub_list_of_pep_list[2])
df3 = my_functonn(sub_list_of_pep_list[4])
5. join all df = concat[df0,df1,df2,df3]
6. returns df with nX speed.
Please suggest me the best suitable library to implement this method.
thanks and regards.
Updated
With some reading i am able to write down a code which work as per my
expectation like 1\. without parallelising it takes ~10 second for 10 peptide
sequence 2\. with two processes it takes ~6 second for 12 peptide 3\. with
four processes it takes ~4 second for 12 peptides
from multiprocessing import Process
def func1():
structure_gen(pep_seq = ["DAAAAEF","DAAAREF","DAAANEF"])
def func2():
structure_gen(pep_seq = ["DAAAQEF","DAAAGEF","DAAAHEF"])
def func3():
structure_gen(pep_seq = ["DAAADEF","DAAALEF"])
def func4():
structure_gen(pep_seq = ["DAAAIEF","DAAALEF"])
if __name__ == '__main__':
p1 = Process(target=func1)
p1.start()
p2 = Process(target=func2)
p2.start()
p3 = Process(target=func1)
p3.start()
p4 = Process(target=func2)
p4.start()
p1.join()
p2.join()
p3.join()
p4.join()
but this code easily work with 10 peptide but not able to implement it for a
PEP_list contains 1 million peptide
thanks
Answer: [multiprocessing.Pool.map](https://docs.python.org/3.5/library/multiprocessing.html#multiprocessing.pool.Pool.map)
is what you're looking for.
Try this:
from multiprocessing import Pool
# I recommend using more partitions than processes,
# this way the work can be balanced.
# Of course this only makes sense if pep_list is bigger than
# the one you provide. If not, change this to 8 or so.
n = 50
# create indices for the partitions
ix = np.linspace(0, len(pep_list), n+1, endpoint=True, dtype=int)
# create partitions using the indices
sub_lists = [pep_list[i1:i2] for i1, i2 in zip(ix[:-1], ix[1:])]
p = Pool()
try:
# p.map will return a list of dataframes which are to be
# concatenated
df = concat(p.map(my_function, sub_lists))
finally:
p.close()
The pool will automatically contain as many processes as there are available
cores. But you can overwrite this number if you want to, just have a look at
the docs.
|
Within IPython how to get the path of the Python driver
Question: When I am running a script get the path of Python kernel (not mater if it is
Python, IPython, or IPython Notebook with non-standard kernel, where I can
switch between Py2 and Py3).
When writting (in IPython)
import sys
sys.argv
I get the path to IPython: `['/usr/local/bin/ipython']`.
Is it possible to get the path to Python as well?
I need it so to match versions of Python from IPython (Notebook) to Spark
worker (`PYSPARK_PYTHON`).
Answer: A general way to do so (i.e. working both in scripts, ipython shell and
IPython Notebook) is:
import sys
sys.executable
([Thx
Carreau](https://github.com/minrk/findspark/issues/6#issuecomment-132625554)!)
|
Python Django RestFramework route trigger
Question: I'am building an API using python 2.7 and django 1.7 and I'm facing a problem.
I'm not an expert in Rest Framework but I understand the basic mechanisms.
I can resume my problem by giving you an example. I have a route lets say
/api/project/
Django Rest Framework provides me all basic operations for this route and I
don't need to write them e.g:
POST, GET, PUT, DELETE => /api/project/
The fact is, I want to do some operation when I create a new project. I want
to add the id of the user who has created the new project.
I want to add some kind of trigger/callback to the create function:
class ProjectViewSet(viewsets.ModelViewSet):
queryset = Project.objects.all()
serializer_class = ProjectSerializer
def create(self, request, *args, **kwargs):
I want to keep the internal behavior of Rest Framework (I don't want to
rewrite the route functions), but I want the route to do extra stuff and I
need the request object in my trigger/callback. Something like
def callback(request, instance):
instance.created_by = request.user
instance.save()
Do you have any ideas?
Thank you.
Answer: You need to add creator_id field to your serializer as well as to model
represented by the resource. Then you can do something like this in your
view:-
import copy
class ProjectViewSet(viewsets.ModelViewSet):
...
def create(self, request, *args, **kwargs):
data = copy.deepcopy(request.data)
data['creator_id'] = request.user.id
request._data = data
return super(ProjectViewSet, self).create(request, *args, **kwargs)
|
Python pipeline using GNU Parallel
Question: I'm trying to write a wrapper around GNU Parallel in Python to run a command
in parallel, but seem to be misunderstanding either how GNU Parallel works,
system pipes and/or python subprocess pipes.
Essentially I am looking to use GNU Parallel to handle splitting up an input
file and then running another command in parallel on multiple hosts.
I can investigate some pure python way to do this in the future, but it seems
like it should be easily implemented using GNU Parallel.
**t.py**
#!/usr/bin/env python
import sys
print
print sys.stdin.read()
print
**p.py**
from subprocess import *
import os
from os.path import *
args = ['--block', '10', '--recstart', '">"', '--sshlogin', '3/:', '--pipe', './t.py']
infile = 'test.fa'
fh = open('test.fa','w')
fh.write('''>M02261:11:000000000-ADWJ7:1:1101:16207:1115 1:N:0:1
CAGCTACTCGGGGAATCCTTGTTGCTGAGCTCTTCCCTTTTCGCTCGCAGCTACTCGGGGAATCCTTGTTGCTGAGCTCTTCCCTTTTCGCTCGCAGCTACTCGGGGAATCCTTGTTGCTGAGCTCTTCCCTTTTCGCTCGCAGCTACTCGGGGAATCCTTGTTGCTGAGCTCTTCCCTTT
>M02261:11:000000000-ADWJ7:1:1101:21410:1136 1:N:0:1
ATAGTAGATAGGGACATAGGGAATCTCGTTAATCCATTCATGCGCGTCACTAATTAGATGACGAGGCATTTGGCTACCTTAAGAGAGTCATAGTTACTCCCGCCGTTTACC
>M02261:11:000000000-ADWJ7:1:1101:13828:1155 1:N:0:1
GGTTTAGAGTCTCTAGTCGATAGATCAATGTAGGTAAGGGAAGTCGGCAAATTAGATCCGTAACTTCGGGATAAGGATTGGCTCTGAAGGCTGGGATGACTCGGGCTCTGGTGCCTTCGCGGGTGCTTTGCCTCAACGCGCGCCGGCCGGCTCGGGTGGTTTGCGCCGCCTGTGGTCGCGTCGGCCGCTGCAGTCATCAATAAACAGCCAATTCAGAACTGGCACGGCTGAGGGAATCCGACGGTCTAATTAAAACAAAGCATTGTGATGGACTCCGCAGGTGTTGACACAATGTGATTTT
>M02261:11:000000000-ADWJ7:1:1101:14120:1159 1:N:0:1
GAGTAGCTGCGAGCGAAAAGGGAAGAGCTCAAGGGGAGGAAAAGAAACTAACAAGGATTCCCCGAGTAGCTGCGAGCGAAAAGGGAAGCGCCCAAGGGGGGCAACAGGAACTAACAAGAATTCGCCGACTAGCTGCGACCTGAAAAGGAAAAACCCAAGGGGAGGAAAAGAAACTAACAAGGATTCCCCGAGTAGCTGCGAGCAGAAAAGGAAAAGCACAAGAGGAGGAAACGACACTAATAAGACTTCCCATACAAGCGGCGAGCAAAACAGCACGAGCCCAACGGCGAGAAAAGCAAAA
>M02261:11:000000000-ADWJ7:1:1101:8638:1172 1:N:0:1
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
''')
fh.close()
# Call 1
Popen(['parallel']+args, stdin=open(infile,'rb',0), stdout=open('output','w')).wait()
# Call 2
_cat = Popen(['cat', infile], stdout=PIPE)
Popen(['parallel']+args, stdin=_cat.stdout, stdout=open('output2','w')).wait()
# Call 3
Popen('cat '+infile+' | parallel ' + ' '.join(args), shell=True, stdout=open('output3','w')).wait()
Call 1 and Call 2 produce the same output while Call 3 produces the output I
would expect where the input file was split up and contains empty lines
between records.
I'm more curious about what the differences are between Call 1,2 and Call 3.
Answer: _TL;DR_ Don't quote `">"` when `shell=False`.
If you use `shell=True`, you can use all the shell's facilities, like
globbing, I/O redirection, etc. You will need to quote anything which needs to
be escaped from the shell. You can pass the entire command line as a single
string, and the shell will parse it.
unsafe = subprocess.Popen('echo `date` "my files" * >output', shell=True)
With `shell=False`, you have no "secret" side effects behind the scenes, and
none of the shell's facilities are available to you. So you need to take care
of globbing, redirection, etc on the Python side. On the plus account, you
save a (potentially significant) extra process, you have more control, and you
don't need (and indeed mustn't) quote things which had to be quoted when the
shell was involved. In summary, this is also safer, because you can see
exactly what you are doing.
cmd = ['echo']
cmd.append(datestamp())
cmd.append['my files'] # notice absence of shell quotes around string
cmd.extend(glob('*'))
safer = subprocess.Popen(cmd, shell=False, stdout=open('output', 'w+'))
(This still differs slightly, because with modern shells, `echo` is a builtin,
whereas now, we will be executing an external utility `/bin/echo` or whichever
executable with that name comes first in your `PATH`.)
Now, returning to your examples, the problem in your `args` is that you are
quoting a literal `">"` as the record separator. When a shell is involved, an
unquoted right broket would invoke redirection, so to specify it as a string,
it has to be escaped or quoted; but when no shell is in the picture, there
isn't anything which handles (or requires) those quotes, so to pass a literal
`>` argument, simply pass that literally.
With that out of the way, your call #1 definitely seems like the way to go.
(Though I'm not entirely convinced that it's sane to write a Python wrapper
for a shell command implemented in Perl. I suspect that juggling a bunch of
parallel child processes in Python directly would not be more complicated.)
|
PyQt no module named
Question: I try to use PyQt 5.5 with Python 3.5. I installed Python 3.5 (C:\Python3) and
intalled PyQt 5.5 (C:\Python3\Lib\site-packages\PyQt5). Then I type
import PyQt5.QWidgets
and have the following error
ImportError: DLL load failed: no module named PyQt5.QWidgets
My OS is Windows 8 x32
It's not helped:
[ImportError: No module named
PytQt5](http://stackoverflow.com/questions/20672918/importerror-no-module-
named-pytqt5)
[ImportError: No module named PyQt5 - OSX
Mavericks](http://stackoverflow.com/questions/20179761/importerror-no-module-
named-pyqt5-osx-mavericks)
[PyQt5 and QtGui module not
found](http://stackoverflow.com/questions/17388082/pyqt5-and-qtgui-module-not-
found)
Answer: **SOLVED:** problem is gone when I installed Python 3.4 instead of Python 3.5
|
Cannot get python3 in Jupyter notebook
Question: How can I get python3 to run in Jupyter? I cannot get it to supply that kernel
as well. When I run `ipython3 notebook` at the terminal, I check the version
of Python:
import sys
print(sys.version)
where I get the output:
3.4.0 (default, Jun 19 2015, 14:20:21)
[GCC 4.8.2]
When I run `jupyter notebook`, I have only the option of a new `python 2`
notebook and
import sys
print(sys.version)
where I get the output:
2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2]
I try to run:
sudo ipython3 kernelspec install-self
[TerminalIPythonApp] WARNING | File not found: 'kernelspec'
Answer: I had this same problem, but solved it by making a virtualenv using Python3 as
the Python binary; installed iPython; and launched iPython notebook from
virtualenv. I will test to see if the same procedure works with Jupyter (I
expect that it will). Note that when I did this, I only had the option of
making Python 3 notebooks.
The following steps worked for me:
mkvirtualenv --python=/full/path/to/python3.5 p35
pip install jupyter
jupyter notebook
A web page popped up and I was allowed to make a Python 3 notebook.
|
python script to interact with embedded board
Question: I want to write a Python script to interact with an Embedded board through
COM4.
I used Teraterm and could able to execute what I wanted. Basically, I just
want to get some information from the board.
Ex: If I send Ver, the board replies back with Version number If I send Serv,
the board replies back with the list of its services
I don't know how to write a Python script to achieve the same.
Following is my code. _The problem is that ser.readline() is reading what I am
sending_. The output is: b'ver' and b'serv'.
Please suggest me what changes should I do in my script to make it work.
Thanks.
import serial
import time
import sys
ser = serial.Serial(baudrate=115200, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=5.0)
ser.port = "COM4"
ser.open()
if ser.isOpen():
print("Open: ",ser.portstr)
print('--------')
ser.write(bytes('ver',encoding='ascii'))
time.sleep(1)
print(ser.readline())
time.sleep(1)
ser.write(bytes('serv',encoding='ascii'))
time.sleep(1)
print(ser.readline())
ser.close()
To make it simple, I just used the following code. In this case, I am getting
a blank output as b' ' continuously.
import serial
import time
import sys
ser = serial.Serial(baudrate=115200, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=5.0)
ser.port = "COM4"
ser.open()
if ser.isOpen():
print("Open: ",ser.portstr)
print('--------')
ser.write(bytes('ver',encoding='ascii'))
while 1:
print(ser.readline())
ser.close()
Answer: Your code looks fine. When you send something over pySerial, what you get back
is what you sent, along with anything the board responds with. I think your
problem relates the the following lines:
print(ser.readline())
If you look through the [readline()
documentation](http://pyserial.sourceforge.net/pyserial_api.html#serial.FileLike.readline)
you will notice that the readline() only reads up to the the eol character.
What your board returns might look something like this:
serv #your input
\n #newline character
output_text #board output
\n #newline character
but ser.readline() stops reading at the newline character because it only
reads one line.
You should be able to fix this by calling ser.readline() several times (at
least twice) until all of the output is read or use one of the [other reading
methods](http://pyserial.sourceforge.net/pyserial_api.html#serial.Serial.read)
|
SQL syntax error in absurdly simple sql?
Question: Calling:
INSERT IGNORE INTO standard_group (group_name, subject, grade, country, state) VALUES (%(group_name), %(subject), %(grade), %(country), %(state));
With
('Arizona Social Studies Standards', 'Social Studies', '1', 'United States', 'AZ')
eg:
print group_columns
print group_sql
print group
cur.execute(group_sql, dict(zip(group_columns, group)))
But I always get:
['group_name', 'subject', 'standard_category', 'standard_sub_category', 'standard_name', 'standard_description', 'grade', 'country', 'state', 'is_common_core', 'is_state_standard']
INSERT IGNORE INTO standard_group (group_name, subject, grade, country, state) VALUES (%(group_name), %(subject), %(grade), %(country), %(state));
('Arizona Social Studies Standards', 'Social Studies', '1', 'United States', 'AZ')
Traceback (most recent call last):
File "standards-import/simport.py", line 167, in <module>
cur.execute(group_sql, dict(zip(group_columns, group)))
File "/Library/Python/2.7/site-packages/mysql/connector/cursor.py", line 507, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "/Library/Python/2.7/site-packages/mysql/connector/connection.py", line 722, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "/Library/Python/2.7/site-packages/mysql/connector/connection.py", line 640, in _handle_result
raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%(group_name), %(subject), %(grade), %(country), %(state))' at line 1
I've tried with named params, `?` and `%s`, and get
* Not all arguments used
* Wrong number of arguments for named parameter
* SQL syntax
**What's going on?? What am I missing???**
Answer: It looks like a small typo. You forgot to add `s` to the params
INSERT IGNORE INTO standard_group (group_name, subject, grade, country, state) VALUES (%(group_name)s, %(subject)s, %(grade)s, %(country)s, %(state)s);
The relevant code is here:
* [`execute(self, operation, params=None, multi=False)`](https://github.com/mysql/mysql-connector-python/blob/master/lib/mysql/connector/cursor.py#L460)
* [`_process_params_dict(self, params)`](https://github.com/mysql/mysql-connector-python/blob/master/lib/mysql/connector/cursor.py#L351)
|
Why is successful jQuery cross domain post request not firing success handler?
Question: I am making the following JQuery cross domain ajax post request from a
phonegap (appgyver steroids) app.
function do_something(callback_method, some_vars)
{
var stringified_some_vars = JSON.stringify(some_vars);
$.ajax({
type: "POST",
url:"http://www.somedomain.com/endpoint",
data: {'some_vars' : stringified_some_vars},
async: true,
dataType: 'json',
crossDomain: true,
xhrFields: {
withCredentials: true
},
success: function(result)
{
var myObject = $.parseJSON(result);
callback_method(myObject);
},
error: function(fail)
{
supersonic.logger.debug(fail);
}
});
}
The post request is successfully sent to the server (Google Appengine -
Python) - i.e. the server fires the relevant method. However, when the server
response is received the jQuery Ajax method doesn't fire the success handler -
it instead fires the error handler. The error text prints to console as
{"readyState":0,"responseText":"","status":0,"statusText":"error"}
The headers in the json response from the server are as follows:
Content-Length: 0
Cache-Control: no-cache
Access-Control-Allow-Origin: *
Content-Type: application/json
the content of the response is as expected. and is written using
text_to_send = json.dumps(python_dict)
self.response.headers.add_header('Access-Control-Allow-Origin', '*')
self.response.headers['Content-Type'] = 'application/json'
self.response.write(text_to_send)
It's not clear to me where this error is coming from. Allowing cross domain
requests doesn't seem to have fixed the issue. jsonp GET requests work fine -
but obviously these aren't allowed for POST requests. Could anyone tell me
where I'm going wrong?
## Edit 1
Following the suggestion of @Faisal I adjusted the server code as follows
from urlparse import urlparse
uri = urlparse(self.request.referer)
origin = '{}://{}'.format(uri.scheme, uri.netloc)
self.response.headers.add_header('Access-Control-Allow-Origin', origin)
self.response.headers['Content-Type'] = 'application/json'
The headers are now
Content-Length: 0
Cache-Control: no-cache
Access-Control-Allow-Origin: http://localhost
Content-Type: application/json
However the same error is encountered
Answer: I think if it's withCredentials: true you need your origin to be exact match
instead of wildcard (*). Here is a quick code to get it from referer. But you
should probably also check if its one of the allowed origins:
from urlparse import urlparse
uri = urlparse(self.request.referer)
origin = '{}://{}'.format(uri.scheme, uri.netloc)
**Edit**
Try adding:
self.response.headers.add_header('Access-Control-Allow-Credentials', 'true')
|
Python socket multiple calls using Eventlet
Question: I need to call a socker server multiple times and print its output.
Here is my below code:-
server.py
import socket
s = socket.socket()
host = socket.gethostname()
port = 1234
s.bind((host, port))
s.listen(5)
print "Server started"
while True:
c, addr = s.accept()
print('Got connection from', addr)
#sprint('Received message == ',c.recv(50))
s = c.recv(50)[::-1]
c.send(s)
c.close()
client.py
import socket
from time import sleep
import eventlet
def socket_client():
s = socket.socket()
host = socket.gethostname()
port = 1234
s.connect((host, port))
print "Sending data"
s.sendall("Hello!! How are you")
print(s.recv(1024))
#socket_client()
pile = eventlet.GreenPile()
for x in range(10):
print 'new process started'
pile.spawn(socket_client())
print 'new process started over'
print 'over'
I use a python eventlet to call the socket_client() 10 times but its not
returning the correct result..
Answer: You're overriding variable with socket by string received from socket:
s = socket.socket()
...
s = c.recv(50)[::-1]
Pick different variable name for the second case.
|
NLTK Brill Tagger Splitting Words
Question: I am using python version 3.4.1 and NLTK version 3 and I am trying to use
their Brill Tagger.
Here is the training code for the brill tagger:
import nltk
from nltk.tag.brill import *
import nltk.tag.brill_trainer as bt
from nltk.corpus import brown
Template._cleartemplates()
templates = fntbl37()
tagged_sentences = brown.tagged_sents(categories = 'news')
tagged_sentences = tagged_sentences[:]
tagger = nltk.tag.BigramTagger(tagged_sentences)
tagger = bt.BrillTaggerTrainer(tagger, templates, trace=3)
tagger = tagger.train(tagged_sentences, max_rules=250)
print(tagger.evaluate(brown.tagged_sents(categories='fiction')[:]))
print(tagger.tag("Hi I am Harry Potter."))
The output to the last command however is:
[('H', 'NN'), ('i', 'NN'), (' ', 'NN'), ('I', 'NN'), (' ', 'NN'), ('a', 'AT'), ('m', 'NN'), (' ', 'NN'), ('H', 'NN'), ('a', 'AT'), ('r', 'NN'), ('r', 'NN'), ('y', 'NN'), (' ', 'NN'), ('P', 'NN'), ('o', 'NN'), ('t', 'NN'), ('t', 'NN'), ('e', 'NN'), ('r', 'NN'), ('.', '.')]
How do I stop it from splitting the words into letters and tagging the letters
instead of the word?
Answer: Tag `tag()` function expects a list of tokens as input. Since you give it a
string as input, this string gets interpreted as a list. Turning a string into
a list gives you a list of characters:
>>> list("abc")
['a', 'b', 'c']
All you need to do is turn your string into a list of tokens before tagging.
For example with [nltk](http://www.nltk.org/api/nltk.tokenize.html) or simply
by splitting at whitespaces:
>>> import nltk
>>> nltk.word_tokenize("Hi I am Harry Potter.")
['Hi', 'I', 'am', 'Harry', 'Potter', '.']
>>> "Hi I am Harry Potter.".split(' ')
['Hi', 'I', 'am', 'Harry', 'Potter.']
Adding tokenization in the tagging gives the following result:
print(tagger.tag(nltk.word_tokenize("Hi I am Harry Potter.")))
[('Hi', 'NN'), ('I', 'PPSS'), ('am', 'VB'), ('Harry', 'NN'), ('Potter', 'NN'), ('.', '.')]
|
How to Convert Soundcloud API Responses into CSV in Python?
Question: I, a newbie, am playing around with the Soundcloud API in Python, and when I
get a chunk of data in return (as an object, I'm guessing) I am not really
sure how to manipulate it:
favorites = client.get('/me/favorites')
<class 'soundcloud.resource.ResourceList'>
I'm guessing this is sort of of a package of data, which has its own
attributes. I can do:
for favorite in favorites:
print favorite.id
And this will give me a list of the IDs of the songs I have favorited.
146967741
136766472
But, how can I see what attributes this object has for me to play with, and
more importantly, how can I convert this into a CSV that I can look into?
Thanks!
Answer: Assuming that you're using soundcloud-python you can use the `fields` method
to get the internal dict or `keys` to just look at the available names.
Source: [resource.py](https://github.com/soundcloud/soundcloud-
python/blob/master/soundcloud/resource.py)
As for the csv question, it would be helpful to have more information about
what you've already tried, but you could use the csv module's `DictWriter`
class, and pass it the dictionaries from `fields()`. More details are
available in the [python
documentation](https://docs.python.org/2/library/csv.html#csv.DictWriter).
Putting the two together:
import csv
with open('names.csv', 'w') as csvfile:
fieldnames = favorites[0].keys()
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for favorite in favorites:
writer.writerow(favorite.fields())
Keep in mind I haven't tested this and I don't have an API key. The
[SoundCloud API Guide](https://developers.soundcloud.com/docs/api/guide) also
has a wealth of valuable information.
|
Need python class decorator of parent to run when class is inherited
Question: I'm working with an example from py.test(using xdist) that uses the unittest
library.
I have a class:
def on_platforms(platforms):
def decorator(base_class):
module = sys.modules[base_class.__module__].__dict__
for i, platform in enumerate(platforms):
d = dict(base_class.__dict__)
d['desired_capabilities'] = platform
name = "%s_%s" % (base_class.__name__, i + 1)
module[name] = new.classobj(name, (base_class,), d)
return decorator
@on_platforms(browsers)
class BaseTest:
def setUp(self):
pass
This contains common code that I need to run in all the test classes I will
create. In the files that contain actual tests to run I have:
from BaseTest.py import BaseTest
class FirstTest(BaseTest):
def test_to_run(self):
pass
Then I have a single main file which will import all the test classes and run
them all when the main.py file is executed.
main.py: import unittest from FirstTest.py import FirstTest
if __name__ == "__main__":
unittest.main()
Finally, I attempt to execute with:
py.test main.py -n3 --boxed
But what happens is it executes main.py succesfully but no tests are run. Why
aren't the test being run? Thanks.
Answer: I think you want to use a metaclass, rather than a decorator to create the
extra versions of your `BaseClass`. The metaclass will be called to create any
subclasses that are created by later code (while the decorator will not). This
means you'll get copies of the subclasses automatically.
import sys
browsers=['x','y','z']
class Meta(type):
def __new__(meta, name, bases, dct):
cls = type.__new__(meta, name, bases, dct)
mod_dct = sys.modules[cls.__module__].__dict__
if 'desired_capabilities' not in dct:
for i, platform in enumerate(cls.platforms):
sub_name = "%s_%s" % (name, i + 1)
sub_cls = meta(sub_name, (cls,), {'desired_capabilities': platform})
mod_dct[sub_name] = sub_cls
return cls
class BaseTest(metaclass=Meta): # metaclass code will create BaseTest_1, BaseTest_2, ...
platforms = browsers
def setUp(self):
pass
class SubTest(BaseTest): # metaclass code will create SubTest_1, SubTest_2, ...
pass
This uses Python 3 syntax for the metaclass. If you're using Python 2, inherit
from `object` and use the `__metaclass__` class variable instead:
class BaseTest(object):
__metaclass__ = Meta
# ...
The `platforms` class attribute will be inherited by subclasses of `BaseTest`
(though they can override it with their own list) and the metaclass will
create the extra subclasses for them. The `if 'desired_capabilities' not in
dct` test is needed to make sure the platform-specific subclasses the
metaclass creates for you do not recursively get their own subclasses.
|
GPIO Error on Raspberry Pi when following Adafruit Tutorial
Question: Having a very strange issue on my Raspberry Pi when following this tutorial...
<https://learn.adafruit.com/adafruit-16x2-character-lcd-plus-keypad-for-
raspberry-pi/usage>
When I run the example script, I'm getting the below error:
pi@thethingbox ~/Adafruit_Python_CharLCD/examples $ sudo python char_lcd_plate.py
Traceback (most recent call last):
File "char_lcd_plate.py", line 6, in <module>
import Adafruit_CharLCD as LCD
File "build/bdist.linux-armv6l/egg/Adafruit_CharLCD/__init__.py", line 1, in <module>
File "build/bdist.linux-armv6l/egg/Adafruit_CharLCD/Adafruit_CharLCD.py",line 23, in <module>
ImportError: No module named Adafruit_GPIO
It was working fine. But when I rebooted I was forced to run fsck - now it's
throwing the above error :-(
I've tried deleting the directory and starting again but I get the same issue.
Answer: The library was probably corrupted when you rebooted. Just run the command
below from the `Adafruit_Python_CharLCD` directory and you should be fine.
sudo python setup.py install
|
Importing module provides SyntaxError
Question: I have a module using Pygame and sys:
import pygame, sys
font = pygame.font.SysFont('sans-serif', 72)
class console:
def text(self, surface, text, pos):
text = font.render(text, 1, (255, 255, 255))
surface.blit(text, (pos[0], pos[1]))
This module returns no errors of any kind. I also have a short main program
designed to import and use the module:
import pygame
pygame.init()
import pygame-console.py
screen = pygame.display.set_mode([640, 480])
console = pygame-console.console()
console.text(screen, 'Hello World!', (0, 0))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
The main program returns a SyntaxError on the third line, like so:
File "C:\Python25\pgTESTimport.py" line 3
import pygame-console.py
^
SyntaxError: invalid syntax
Script terminated.
I'm using Stani's Python Editor due to IDLE's difficulty with sys.exit(). Can
anybody tell me what the problem is with this code? Why does it return
SyntaxError on normal-looking code?
Answer: That is not how you import modules, you do not need to give the `.py` at the
end, also you cannot directly import modules with `-` in the name.
You would either need to rename your file to something without a `-` in it,
like `pygameconsole.py` and then import it using -
import pygameconsole
Or, if you are do not want to rename the file, and want to keep the `-` in the
name, you can use `importlib` to import it -
import importlib
pygameconsole = importlib.import_module('pygame-console')
Then you can use it using `pygameconsole` .
|
how can i properly copy this file to another directory in Ubuntu 14.0
Question:
cp -i /usr/local/lib/python2.7/dist-packages/django/template/admin/base_site.html /usr/local/lib/python2.7/dist-packages/django/template/admin
I am trying to 'CUSTOMIZE MY PROJECT TEMPLATE' from the Django 1.8 POLLS
tutorial <https://docs.djangoproject.com/en/1.8/intro/tutorial02/>
but no avail, i am having a hard time trying to copy the "base_site.html" file
to the "django/contrib/admin/templates"
help me learn!
Answer: You may misunderstand the tutorial, It said: copy it from the default
directory into your custom directory, and make changes, it seems that you
command above is trying to duplicate the file.
first, find your Django source file location:
python -c "
import sys
sys.path = sys.path[1:]
import django
print(django.__path__)"
you will get a link, go deep into the folder, find that template, then copy
the `base_site.html` to your project's template folder.
|
Python | Loop statement to creat file for every sheet in excel file
Question: I am fairly new to python and am trying to figure out how i can export data
from every sheet in an excel workbook in to a different file for every sheet.
For example, in the first workbook, every sheet has data from a different
brand; lets call this file my allbrandsmasterlist excel file. I also have a
perbrandbreakdown file which is the template i want every brand to pasted in
to but with a different file for every brand.
In summary, I want to copy all the contents of every brand in to a new
finalbrand file which keeps the same template from perbrandbreakdown but has
automatically moved the data from each brand in the allbrandsmasterlist sheet
in to its own file. The end result should be 1 file for every sheet/brand in
the first file.
I have made some progress but i need help cleaning up this code and making it
run the loop for all sheets in the first file where as now it is just running
it once and only creates the file for the first brand ( only file output is
for brand0 or first sheet). Thanks in advance and let me know if i can clear
up any confusion
# here are the latest changes
#import excel writing and reading modules
import xlwt
import xlrd
file = 'i:/My Client Data/CLASSHOG FINAL TEMPLATES AND FILES/item master new august.xlsx'
workbook1 = xlrd.open_workbook(file)
print ('There are %s sheets in %s'% (workbook1.nsheets,file))
"""for i in range(workbook.nsheets):
print(i)"""
for i in range(workbook1.nsheets):
if workbook1.nsheets > 1:
workbookwt = xlwt.Workbook()
sheet1 = workbookwt.add_sheet('ITEM DETAILS')
#open template file to copy from
workbook = xlrd.open_workbook('I:\My Client Data\CLASSHOG FINAL TEMPLATES AND FILES/PERFORMANCE MACHINE.xlsx')
#set current sheet to first one in workbook
sheet = workbook.sheet_by_index(0)
#declare contents of rows individually - manual
datarow0 = [sheet.cell_value(0, col) for col in range(sheet.ncols)]
datarow1 = [sheet.cell_value(1, col) for col in range(sheet.ncols)]
datarow2 = [sheet.cell_value(2, col) for col in range(sheet.ncols)]
datarow3 = [sheet.cell_value(3, col) for col in range(sheet.ncols)]
datarow4 = [sheet.cell_value(4, col) for col in range(sheet.ncols)]
#declare contents of columns individually - manual
datacolA = [sheet.cell_value(row,0) for row in range(sheet.nrows)]
datacolB = [sheet.cell_value(row,1) for row in range(sheet.nrows)]
#number of worksheets, columns and rows respectively
print("The number of worksheets is %s:" % (workbook.nsheets))
print("The number of columns is %s:" % (sheet.ncols))
print("The number of rows is %s:" % (sheet.nrows))
#add first sheet and paste columns-manual
for index, value in enumerate(datarow0):
sheet1.write(0, index, value)
for index, value in enumerate(datarow1):
sheet1.write(1, index, value)
for index, value in enumerate(datarow2):
sheet1.write(2, index, value)
for index, value in enumerate(datarow3):
sheet1.write(3, index, value)
#----------------------------------------------------
sheet = workbookwt.add_sheet('CLEAN FILE')
sheetswb1 = workbook1.sheet_by_index(i)
datarow0 = [sheetswb1.cell_value(0, col) for col in range(sheetswb1.ncols)]
datarow1 = [sheetswb1.cell_value(1, col) for col in range(sheetswb1.ncols)]
for r in range(sheetswb1.nrows):
for c in range(sheetswb1.ncols):
sheet.write(r, c, sheetswb1.cell_value(r, c))
#for index, value in enumerate(datarow0):
#sheet.write(0, index, value)
#for index, value in enumerate(datarow1):
#sheet.write(1, index, value)
#----------------------------------------------------
sheet = workbookwt.add_sheet('SC FILE')
sheet3 = workbook.sheet_by_index(2)
#----------------------------------------------------
sheet = workbookwt.add_sheet('EBAY FILE')
sheet4 = workbook.sheet_by_index(3)
#----------------------------------------------------
sheet = workbookwt.add_sheet('PRICING STRATEGY')
sheet5 = workbook.sheet_by_index(4)
datarow0 = [sheet5.cell_value(0, col) for col in range(sheet5.ncols)]
datarow1 = [sheet5.cell_value(1, col) for col in range(sheet5.ncols)]
datarow2 = [sheet5.cell_value(2, col) for col in range(sheet5.ncols)]
for index, value in enumerate(datarow0):
sheet.write(0, index, value)
for index, value in enumerate(datarow1):
sheet.write(1, index, value)
for index, value in enumerate(datarow2):
sheet.write(2, index, value)
workbookwt.save('i:/pythonvirioutput/output%s.xls' % ("brand" + str(i)))
print('Operation run and file saved for brand' + str(i))
else: print('The workbook has less than 2 sheets')
break
# output
There are 441 sheets in i:/My Client Data/CLASSHOG FINAL TEMPLATES AND FILES/item master new august.xlsx
The number of worksheets is 5:
The number of columns is 2:
The number of rows is 5:
Operation run and file saved for brand0
Answer: Yes, this seems to be only working , because you get the current sheet as -
sheet = workbook.sheet_by_index(0)
You are only getting the first sheet, always, hence it always only writes out
the data from the first sheet, you should instead use `i` here, to get each
sheet separately. Code -
sheet = workbook.sheet_by_index(i)
|
Document Frequency in Python
Question: I want to count in how many documents a particular word appears. For example,
the word "Dog" appeared in 67 documents out of 100 documents.
1 document is equivalent to 1 file.
So therefore, the frequency of the word "Dog" need not to count. For example
in document 1, "Dog" appeared 250 times, BUT it will only considered as one
count, since my goal is to count the documents not how many times did the word
"Dog" appeared in a specific document.
Example:
* Document 1: Dog appeared 250 times
* Document 2: Dog appeared 1000 times
* Document 3: Dog appeared 1 time
* Document 4: Dog appeared 0 time
* Document 5: Dog appeared 2 times
So answer must be 4
I have my own algorithm but I believe there's an efficient way to do this. I'm
using Python 3.4 with NLTK libraries. I need help. Thank yoy guys!
Here's my code
# DOCUMENT FREQUENCY
for eachadd in wordwithsource:
for eachaddress in wordwithsource:
if eachaddress == eachadd:
if eachaddress not in copyadd:
countofdocs=0
copyadd.append(eachaddress)
countofdocs = countofdocs+1
addmanipulation.append(eachaddress[0])
for everyx in addmanipulation:
documentfrequency = addmanipulation.count(everyx)
if everyx not in otherfilter:
otherfilter.append(everyx)
documentfrequencylist.append([everyx,documentfrequency])
#COMPARE WORDS INTO DOC FREQUENCY
for everywords in tempwords:
for everydocfreq in documentfrequencylist:
if everywords.find(everydocfreq[0]) !=-1:
docfreqofficial.append(everydocfreq[1])
for everydocfrequency in docfreqofficial:
docfrequency=(math.log10(numberofdocs/everydocfrequency))
docfreqanswer.append(docfrequency)
Answer: You could store a frequency dictionary for each document and use another
global dictionary for the document frequency of words. I have used Counter for
simplicity.
from collections import Counter
#using a list to simulate document store which stores documents
documents = ['This is document %d' % i for i in range(5)]
#calculate words frequencies per document
word_frequencies = [Counter(document.split()) for document in documents]
#calculate document frequency
document_frequencies = Counter()
map(document_frequencies.update, (word_frequency.keys() for word_frequency in word_frequencies))
print(document_frequencies)
>>>...Counter({'This': 5, 'is': 5, 'document': 5, '1': 1, '0': 1, '3': 1, '2': 1, '4': 1})
|
Take data from private google spreadsheet
Question: I have a Google Spreadsheet which I'm sharing with several person. I want to
built a script to search for some rows and take cells values and process a
program locally afterwards. I was thinking going with python, as it seems
Google provide a good API for it.
Have someone an example on how to connect to Google Spreadsheet ? I read the
api, but I don't get how does the OAuth 2.0 thing works...
Many thanks :)
Answer: To perform read and write operations on a Google Spreadsheet, OAuth 2.0 will
not be necessary. As shown in these samples for
[reading](http://www.payne.org/index.php/Reading_Google_Spreadsheets_in_Python)
as well as [writing](https://www.mattcutts.com/blog/write-google-spreadsheet-
from-python/) to a Google Spreadsheet, in order to be able to access the
SpreadSheet you must include the username-password of the related account in
your in your code. And then using them in the following manner (as shown in
the writing sample) to access the Spreadsheet:
spr_client = gdata.spreadsheet.service.SpreadsheetsService()
spr_client.email = email
spr_client.password = password
spr_client.source = 'Example Spreadsheet Writing Application'
spr_client.ProgrammaticLogin()
Also, do remember to `import gdata.spreadsheet.service` and any other related
library that you might need for your code. And if you're new,
[this](https://developers.google.com/gdata/articles/python_client_lib?hl=en#top_of_page)
would also be a good place to start. Hope this helps!
|
Python unicode: how to replace character that cannot be decoded using utf8 with whitespace?
Question: How to replace characters that cannot be decoded using utf8 with whitespace?
# -*- coding: utf-8 -*-
print unicode('\x97', errors='ignore') # print out nothing
print unicode('ABC\x97abc', errors='ignore') # print out ABCabc
How can I print out `ABC abc` instead of `ABCabc`? Note, `\x97` is just an
example character. The characters that cannot be decoded are unknown inputs.
* If we use `errors='ignore'`, it will print out nothing.
* If we use `errors='replace'`, it will replace that character with some special chars.
Answer: Take a look at `codecs.register_error`. You can use it to register custom
error handlers
<https://docs.python.org/2/library/codecs.html#codecs.register_error>
import codecs
codecs.register_error('replace_with_space', lambda e: (u' ',e.start + 1))
print unicode('ABC\x97abc', encoding='utf-8', errors='replace_with_space')
|
PostgreSQL issue inserting data
Question: i want to insert the data into a `PostgreSQL` database but when i try to
insert data is not stored in the database and error is not generated so I am
unable to find out what the error is, please help
#!/usr/bin/python
import psycopg2
import psycopg2.extras
import sys
con = None
try:
con = psycopg2.connect("dbname='mydb' user='merlin' host='192.168.0.104' password='merlin123'")
cursor = con.cursor(cursor_factory=psycopg2.extras.DictCursor)
cursor.execute("SELECT * FROM table1")
rows = cursor.fetchall()
except psycopg2.DatabaseError, e:
print 'Error %s' % e
finally:
if con:
con.close()
try:
con = psycopg2.connect("dbname='mydb2' user='merlin' host='192.168.0.104'")
cursor = con.cursor(cursor_factory=psycopg2.extras.DictCursor)
query = "INSERT INTO table3 VALUES ('%s', '%s', '%d' , %s)" % (raw[0][0], raw[0][1],raw[0][2],0)
#while raw!=None:
cursor.execute(query)
con.commit()
except psycopg2.DatabaseError, e:
print 'Error %s' % e
finally:
if con:
con.close()
sys.exit(1)
Can anyone help solving the error?
Answer: Your problem not seeing the exception stack trace is because you are doing
`sys.exit(1)` in the `finally` clause -- so you are exiting before python has
a chance to display the error.
I would simplify your script a lot (comment out the unnecessary portions) and
then gradually add in the complexity you need if/when you need it.
BTW I think The error will be that `raw` is not defined
|
localized duration format for french
Question: What is the Python analog of [Time4J's code
example](https://github.com/MenoData/Time4J/blob/1d73d3ed38a546fe6e91c75a6720c288f54a842a/README.md):
// duration in seconds normalized to hours, minutes and seconds
Duration<?> dur = Duration.of(337540, ClockUnit.SECONDS).with(Duration.STD_CLOCK_PERIOD);
// custom duration format => hh:mm:ss
String s1 = Duration.Formatter.ofPattern("hh:mm:ss").format(dur);
System.out.println(s1); // output: 93:45:40
// localized duration format for french
String s2 = PrettyTime.of(Locale.FRANCE).print(dur, TextWidth.WIDE);
System.out.println(s2); // output: 93 heures, 45 minutes et 40 secondes
It is easy to get `93:45:40`:
#!/usr/bin/env python3
from datetime import timedelta
dur = timedelta(seconds=337540)
print(dur) # -> 3 days, 21:45:40
fields = {}
fields['hours'], seconds = divmod(dur // timedelta(seconds=1), 3600)
fields['minutes'], fields['seconds'] = divmod(seconds, 60)
print("%(hours)02d:%(minutes)02d:%(seconds)02d" % fields) # -> 93:45:40
but how do I emulate `PrettyTime.of(Locale.FRANCE).print(dur, TextWidth.WIDE)`
Java code in Python (without hardcoding the units)?
Answer: [`babel` module](http://babel.pocoo.org/) allows to get close to desired
output:
from babel.dates import format_timedelta # $ pip install babel
print(", ".join(format_timedelta(timedelta(**{unit: fields[unit]}),
granularity=unit.rstrip('s'),
threshold=fields[unit] + 1,
locale='fr')
for unit in "hours minutes seconds".split()))
# -> 93 heures, 45 minutes, 40 secondes
It handles locale and plural forms automatically e.g., for `dur =
timedelta(seconds=1)` it produces:
0 heure, 0 minute, 1 seconde
Perhaps a better solution would be to translate the format string manually
using standard tools such as `gettext`.
|
How to convert an string to json in Python
Question: I'm trying to convert an string into `json` output from **local Data** or
Those datas from `BeautifulSoup` output as `Json`.for example:
#! /usr/bin/python
data = ('Hello')
print data
and i need to convert this `Hello` as json output.
How can do that?
is this possible?
Answer: Check out the json module in Python
<https://docs.python.org/2/library/json.html>
import json
json.dumps({"hello": 0}, sort_keys=True)
|
Python: numpy.var yields unknown number
Question: numpy.var yields this number: 6.0037250324777306e-28.
I suppose by looking at the data that this number is close to 0. Am I correct?
If so, how could I interpret this number?
Answer: It is indeed a number very very close to 0. For example:
import numpy as np
list_to_check_var = [2,2,2,2,2.00000000001]
np.var(list_to_check_var)
yields
1.6000002679246418e-23
As you intuitively know, the variance of the list is very small. The `e-23`
part at the end means you need to multiply the number with `10^-23`.
|
Re-use http connection Python 3
Question: So every second I am making a bunch of requests to website X every second, as
of now with the standard `urllib` packages like so (the requestreturns a
json):
import urllib.request
import threading, time
def makerequests():
request = urllib.request.Request('http://www.X.com/Y')
while True:
time.sleep(0.2)
response = urllib.request.urlopen(request)
data = json.loads(response.read().decode('utf-8'))
for i in range(4):
t = threading.Thread(target=makerequests)
t.start()
However because I'm making so much requests after about 500 requests the
website returns `HTTPError 429: Too manyrequests`. I was thinking it might
help if I re-use the initial TCP connection, however I noticed it was not
possible to do this with the `urllib` packages.
So I did some googling and discovered that the following packages might help:
* `Requests`
* `http.client`
* `socket` ?
So I have a question: which one is best suited for my situation and can
someone show an example of either one of them (for Python 3)?
Answer: `requests` handles [keep alive](http://docs.python-
requests.org/en/latest/user/advanced/#keep-alive) automatically if you use a
session. This might not actually help you if the server is rate limiting
requests, however, `requests` also handles parsing JSON so that's a good
reason to use it. Here's an example:
import requests
s = requests.Session()
while True:
time.sleep(0.2)
response = s.get('http://www.X.com/y')
data = response.json()
|
How to play a sound when my bluetooth device is detected
Question: Started with python programming this morning and wanted to make a simple
application that sniffs my phone's Bluetooth when I am around and play a song.
This app continues to search for my bluetooth every 27 seconds. If I am still
around, it will continue playing but I leave or switch off my bluetooth, I
want it to stop the song. I have the following code, everything works fine but
I get an error that stops the execution if there is no bluetooth device
detected and when I leave or switch off my device, the song continues to play.
Please help.
import socket
import mmap
from bluetooth import *
import msvcrt
import bluetooth
import pygame, time
from pygame.locals import *
pygame.mixer.pre_init(44100, 16, 2, 4096) #frequency, size, channels, buffersize
pygame.init() #turn all of pygame on.
DISPLAYSURF = pygame.display.set_mode((500, 400))
soundObj = pygame.mixer.Sound('sleep.wav')
target_name = "Joelk"
target_address = None
loop = False
isHome = False
playing = False
print("Press Esc to end....")
while loop == False:
print("Perfoming Enquire")
if msvcrt.kbhit():
if ord(msvcrt.getch()) == 27:
break
nearby_devices = discover_devices(lookup_names = True)
print ("found %d devices" % len(nearby_devices))
if 0 == len(nearby_devices):
print("There is no device nearby")
else:
print("There is a device")
for name, addr in nearby_devices:
print (" %s - %s" % (addr, name))
if "Joelk" == addr:
isHome = True
if(isHome == True):
if(playing == True):
print("Playing")
else:
soundObj.play()
playing = True
else:
isHome = False
soundObj.stop()
print("Not Playing")
Answer: You never set `is_home` to `False` within the main loop. The only assignment
to `False` happens in an `else` branch that is only executed iff `is_home` was
`False` anyway so this statement has no effect.
It has to be set to false if no suitable bluetooth device is detected. This
can be done with the help of `break` and an `else` clause on the `for` loop
over the detected devices.
Without all the unnecessary imports, without star imports, without unnecessary
names, without unnecessary parenthesis and comparisons to `bool` literals, and
untested:
import pygame
from bluetooth import discover_devices
def main():
pygame.mixer.pre_init(44100, 16, 2, 4096)
pygame.init()
_display = pygame.display.set_mode((500, 400))
sound = pygame.mixer.Sound('sleep.wav')
is_home = False
print('Press Esc to end....')
while True:
print('Performing Enquire')
for event in pygame.event.get():
if event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE:
break
nearby_devices = discover_devices(lookup_names=True)
print('found {0} devices'.format(len(nearby_devices)))
if nearby_devices:
for address, name in nearby_devices:
print(' {0} - {1}'.format(address, name))
if name == 'Joelk':
is_home = True
break
else:
is_home = False
if is_home:
if sound.get_num_channels() > 0:
print('Playing')
else:
sound.play()
else:
sound.stop()
print('Not Playing')
if __name__ == '__main__':
main()
The `playing` flag was replaced by querying the `Sound` object on how many
channels it is currently playing. If you wand the sound playing in a gapless
loop you should have a look at the optional arguments of the `play()` method
regarding looping the sound.
|
How to extract file size from youtube-dl in python script?
Question: I'm new to python programming. I want to extract a video/audio size ( any
youtube video) before downloading it ??
Answer:
>>> from youtube_dl import YoutubeDL
>>> url = 'https://www.youtube.com/watch?v=PSYxT9GM0fQ'
>>> ytdl = YoutubeDL()
>>> info = ytdl.extract_info(url, download=False)
[youtube] PSYxT9GM0fQ: Downloading webpage
[youtube] PSYxT9GM0fQ: Downloading video info webpage
[youtube] PSYxT9GM0fQ: Extracting video information
[youtube] PSYxT9GM0fQ: Downloading DASH manifest
>>> formats = info['formats']
formats is a list of dictionaries, pick the format you are looking for
>>> format = formats[0]
>>> format['filesize']
2594621
In general
>>> info.keys()
dict_keys(['extractor_key', 'upload_date', 'thumbnail', 'playlist_index', 'format_id', 'width', 'display_id', 'is_live', 'dislike_count', 'thumbnails', 'annotations', 'age_limit', 'formats', 'id', 'playlist', 'subtitles', 'average_rating', 'player_url', 'height', 'requested_subtitles', 'like_count', 'extractor', 'uploader_id', 'ext', 'automatic_captions', 'format', 'webpage_url', 'end_time', 'uploader', 'webpage_url_basename', 'duration', 'start_time', 'view_count', 'title', 'http_headers', 'description', 'url', 'tags', 'categories'])
are the different keys you can use to gain information about the youtube link
|
How to deserialize with Python a JSON date exported with DataContractJsonSerializer?
Question: How to deserialize with Python a JSON date exported with
DataContractJsonSerializer?
The dates exported look like `/Date(1440051107000-0500)/` and I need to create
real DateTime objects in Python.
Is there an already existing code that does this, or I do have to code it
myself?
Answer: I think you'll find the answer in this thread: [Converting ASP.Net JSON Date
into Python datetime](http://stackoverflow.com/questions/18039625/converting-
asp-net-json-date-into-python-datetime)
Hope it helps.
EDIT: Following @SuperBiasedMan advice, here is the answer provided by the
link.
Apparently there is no code in python's standard library to cast this string
in a datetime object.
However, this code will do the trick:
#!/usr/bin/env python
import datetime
EPOCH = datetime.datetime.utcfromtimestamp(0)
def parse_date(datestring):
timepart = datestring.split('(')[1].split(')')[0]
milliseconds = int(timepart[:-5])
hours = int(timepart[-5:]) / 100
adjustedseconds = milliseconds / 1000 + hours * 3600
return EPOCH + datetime.timedelta(seconds=adjustedseconds)
ScheduleDate = "\/Date(1374811200000-0400)\/"
StartTime = "\/Date(-2208931200000-0500)\/"
print(parse_date(ScheduleDate))
print(parse_date(StartTime))
|
Access varaibles from csv file Python
Question: I have a python file that communicates with a device and access its
parameters. As I have to access more than 100 parameters, I have stored those
parameter names into one column in csv file. I want to access values assigned
to these parameters. But what I am getting the parameters names instead of its
values.
My csv file is like
parameter1
parameter2
parameter3
parameter4
...
I am using the following code:
import csv
TagList = []
with open('parameters.csv', 'rb') as file:
reader = csv.reader(file)
for row in reader:
TagList.append(row[0])
for tag in TagList:
print tag
Output:
parameter1
parameter2
parameter3
parameter4
...
What I want to access is the data assigned to these parameters. I can access
its value through its name. i.e.
print parameter1
output: 1.0
I have tried `print "%d" %(tag)`, that is also not working. Please help me in
that. Thanks in advance.
Answer: I'm not sure what the interface for your controller looks like, however I
think you would be looking to use reflection here.
so `TagList[0]` sounds like it is equal to `"parameter1"` at this point.
If you access your controller through a python class you'd be looking to do
something like `getattr(controller, TagList[0]`.
Here is a code example that shows how that would work:
class foo(object):
x = 3
var = "x"
print getattr(foo(), var)
EDIT:
Okay from what you are saying it sounds like it would be more like this:
variable1 = 0
variable2 = "true"
paramList = ["variable1", "variable2"]
for param in paramList:
print eval(param)
The docstring for `eval()` is: Evaluate the source in the context of globals
and locals. So this should pick up those variables if they do not belong to an
instance.
Also see [How to get the value of a variable given its name in a
string?](http://stackoverflow.com/questions/9437726/how-to-get-the-value-of-a-
variable-given-its-name-in-a-string) which has an answer using
`globals()['a']` to narrow the scope of the evaluation.
|
Tkinkter Grid() alignment not as expected: Python 2.7
Question: I am trying to use grid() function to align the labels and option menu side by
side. Here's the code which I used to create a simple GUI:
from Tkinter import *
win1 = Tk()
win1.title("Chumma")
#Option selection frame:
f3 = Frame(win1)
f3.grid(column=0,row=0)
f3.pack()
l1 = Label(f3, text="Select the function which you want to perform: ", bg = "yellow")
moduleList = StringVar(f3)
moduleList.set("Normal Walk") #to display the default module name
o1 = OptionMenu(f3, moduleList, "Normal Walk", "Brisk Walk", "Running", "Custom")
b3 = Button(f3, text="Execute the option", fg="blue")
b4 = Button(f3, text="Stop", fg="red")
#Packing the stuffs in required order:
l1.grid(row=0, column=0, sticky=W) #E means east
l1.grid_rowconfigure(0, weight=1)
l1.grid_columnconfigure(0, weight=1)
l1.pack(fill = X, padx = 5)
o1.grid(row=0,column=1)
o1.grid_rowconfigure(0, weight=1)
o1.grid_columnconfigure(1, weight=1)
o1.pack()
b4.pack()
win1.mainloop()
The result is:
[](http://i.stack.imgur.com/HgWLB.png)
I am expecting the option menu `o1` to be at the right of the `l1`. If I
comment the pack command [ `l1.pack()` and `o1.pack()` ], the program is not
displaying any GUI at all.
Answer: After you call `grid`, a couple of lines later you call `pack` which cancels
out the use of grid. Use one or the other but not both for each widget. Sinc
`pack` defaults to `side='top'`, your widgets appear stacked on top of each
other.
The reason you see nothing if you comment out those _two_ calls to `pack` is
because you are still calling `b4.pack()`, and you can't use both `pack` and
`grid` for different widgets with the same parent.
Also, the calls to `rowconfigure` and `columnconfigure` need to be on the
parent widget. Calling them on the label widget will only affect widgets you
put inside the label (which is possible, but unusual)
|
How to access localStorage of a firefox browser via Python?
Question: following case. I have a python script that opens a firefox browser on windows
which has a firefox addon installed that writes logs into the local storage.
Before I close the browser via python I would like to read out the log
information out of the local storage of the firefox.
So how can I access the localStorage in the firefox?
Help very appreciated.
Answer: You will have to use [PyXPCOM](https://developer.mozilla.org/en-
US/docs/Mozilla/Tech/XPCOM/Language_bindings/PyXPCOM) and the
[nsIDOMStorageManager](https://developer.mozilla.org/en-
US/docs/Mozilla/Tech/XPCOM/Reference/Interface/NsIDOMStorageManager)
interface.
Have a look at this [tutorial](http://www.ibm.com/developerworks/library/co-
pyxp2/) to see how to use PyXPCOM.
You may start from this code (untested):
from xpcom import components
principal = (components.classes['@mozilla.org/scriptsecuritymanager;1']
.getService(components.interfaces.nsIScriptSecurityManager)
.getNoAppCodebasePrincipal(YOUR_URL))
dom_storage_manager = (components.classes['@mozilla.org/dom/localStorage-manager;1']
.getService(components.interfaces.nsIDOMStorageManager))
local_storage = dom_storage_manager.getLocalStorageForPrincipal(principal, YOUR_URL)
|
Searching for files with os.walk if no files are found matching the search criteria- Python
Question: Right now I am using os.walk to recursively search directories and
subdirectories for any autorun.inf file. I know I'm not doing it in the best
way so if you have a better way for that too, please let me know. If it finds
anything matching autorun it will output the file's contents for each file
found matching the criteria. However when I try to make an else statement for
if no files were found that matched, it prints "No file matching the criteria
found" for each file that doesn't match instead of only one time if that makes
sense. I only want it to say it once if no file matching the criteria is
found. Here's what I have so far.
import os
from os.path import join
for (dirname, dirs, files) in os.walk('/home/user/Documents/mystuff'):
for filename in files:
if filename.startswith('autorun'):
thefile = os.path.join(dirname,filename)
f = open(thefile)
print f.read()
else:
print "No file matched the criteria"
Answer:
found = False
for (dirname, dirs, files) in os.walk('/home/user/Documents/mystuff'):
for filename in files:
if filename.startswith('autorun'):
thefile = os.path.join(dirname,filename)
f = open(thefile)
print f.read()
found = True
if not found:
print "No file matched the criteria"
|
How to parse Cisco IOS output into an object or JSON
Question: Right now, I can get nearly what I want with a simple `re.split("\n([^\s])",
data)` as shown below, but the problem is that the resulting list contains the
single non-whitespace character match as it's own item in the list. Example
output below script. Notice how the "V" in "VLAN" has been captured into this
as it's own item?
I'm wondering also if there's just a better way to do this, perhaps a library
I can include that handles converting tabular data into a dictionary or
something.
#!/usr/bin/python
import re
import sys
data = """
VLAN Name Status Ports
---- -------------------------------- --------- -------------------------------
1 default active Fa0/2, Fa0/3, Fa0/4, Fa0/5, Fa0/6, Fa0/7
Fa0/8, Fa0/9, Fa0/10, Fa0/11, Fa0/12
Fa0/13, Fa0/14, Fa0/15, Fa0/16, Fa0/17
Fa0/18, Fa0/19, Fa0/20, Fa0/21, Fa0/22
Fa0/23, Fa0/24, Gi0/2
1002 fddi-default act/unsup
1003 token-ring-default act/unsup
1004 fddinet-default act/unsup
1005 trnet-default act/unsup
"""
lines = re.split("\n([^\s])", data)
print lines
Output:
> ['', 'V', 'LAN Name Status Ports', '-', '---
> -------------------------------- ---------
> \-------------------------------', '1', ' default active Fa0/2, Fa0/3,
> Fa0/4, Fa0/5, Fa0/6, Fa0/7\n
> Fa0/8, Fa0/9, Fa0/10, Fa0/11, Fa0/12\n
> Fa0/13, Fa0/14, Fa0/15, Fa0/16, Fa0/17\n
> Fa0/18, Fa0/19, Fa0/20, Fa0/21, Fa0/22\n
> Fa0/23, Fa0/24, Gi0/2', '1', '002 fddi-default
> act/unsup', '1', '003 token-ring-default act/unsup', '1', '004 fddinet-
> default act/unsup', '1', '005 trnet-default act/unsup\n']
Thanks!
**Edit** : ~~`lines = re.findall(".*[^\n\W]*", data)` seems like it's probably
a better approach ~~ (nm that doesn't work, sorry) but this whole thing still
feels pretty hacky so I'd love to hear any alternative suggestions.
Answer: This is probably not the best way, but it's at least a solution. Use the regex
module instead of the re module.
lines = regex.split("\n(?=[^\s])", data)
Unlike the builtin re module, the regex module allows splitting on zero-width
matches, so you can use a lookahead to split at positions where the next
character matches.
References:
* [Python re.split and attaching matched group to either right or left side of the split](http://stackoverflow.com/questions/28402004/python-re-split-and-attaching-matched-group-to-either-right-or-left-side-of-the)
* <https://pypi.python.org/pypi/regex>
|
Exscript - Network Device Discovery/config gathering script (Python)
Question: I'm fairly new to python and am having difficulty with a script I am trying to
use to gather config info from cisco network devices.
After a ping test to discover which devices are up, a file is created
containing the responding IP's, and then parsed by an Exscript (python tool
for SSH/telnet access) function.
The problem is that after the ping test is complete, and the file is created
with the appropriate IP's, the script ends without beginning the quickstart or
getdevinfo functions.
Any idea why this might be?
from Exscript.util.start import quickstart
from Exscript.util.interact import read_login
from Exscript.util.file import get_hosts_from_file
from Exscript import Account
import os
account = read_login()
hosts = open("hosts",'w')
for x in range(65,85):
if os.system("ping -c 1 -W 2 172.16.200.%s" % x) == 0:
print 'reachable'
hosts.write("ssh://172.16.200.%s" % x + "\n")
else:
print 'unreachable'
hosts.close
def getdevinfo(job,host,conn):
print 'connection started'
conn.execute('show ver | i Ver')
devtypeinfo = str(conn.response)
forparse = devtypeinfo.split()
for word in forparse:
if word.lower() == "security":
file = open("hostinfo - " + str(conn.host),'w')
print "Device Type Detected: ASA"
conn.send("enable\r")
conn.app_authorize(account)
conn.execute("show run hostname")
file.write(conn.response)
conn.execute("show int ip bri | excl unassigned")
file.write(conn.response)
conn.execute("show route")
file.write(conn.response)
conn.send("exit\r")
conn.close()
file.close()
elif word.lower() == "ios":
file = open("hostinfo - " + str(conn.host),'w')
print "Device Type Detected: Router"
conn.send("enable\r")
conn.app_authorize(account)
conn.execute("show run | i hostname")
file.write(conn.response)
conn.execute("show ip int bri | excl unassigned")
file.write(conn.response)
conn.execute("show ip route")
file.write(conn.response)
conn.execute("show cdp nei")
file.write(conn.response)
conn.send("exit\r")
conn.close()
file.close()
hosts2 = get_hosts_from_file('hosts')
quickstart(hosts2, getdevinfo, max_threads = 6)
Answer: In case anyone runs into something similar (which I kind of doubt because this
script is so specific, maybe this wasn't the right place to post this) - the
issue was that the quickstart function was being passed an empty list of
hosts, so no connections were made.
To fix this, I skipped the get_hosts_from_file function and just added
responding hosts to a list, and passed that list to the quickstart function.
|
Windows 10 and pip upgrading - Access denied
Question: I have done a fresh Windows 10 install, installed python, cygwin and a
improved console called ConEmu. After installing python 3.4.3 I execute:
pip install -U pip
And got this error.
File "C:\Anwendungsentwicklung\Python34\lib\site-packages\pip\utils\__init__.py", line 70, in rmtree_errorhandler
os.makedirs(path)
PermissionError: [WinError 5] Zugriff verweigert: 'C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\pip-dxm8d3xg-uninstall\\anwendungsentwicklung\\python34\\scripts\\pip.exe'
I'm logged in with pre-defined Administrator account and the temp dir as well
as the installation dir of Python (C:\Anwendungsentwicklung\Python34) has full
access.
Please I have tested all variations by setting different rights but Windows
won't let me. I even added "Everyone" to security tab but this didn't help
although I remember it was working with Windows 7 with this "trick". It must
be a problem with Windows 10. Can someone help??
[](http://i.stack.imgur.com/HCuYy.png)
* * *
This is full traceback
Exception:
Traceback (most recent call last):
File "c:\anwendungsentwicklung\python34\lib\shutil.py", line 372, in _rmtree_unsafe
os.unlink(fullname)
PermissionError: [WinError 5] Zugriff verweigert: 'C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\pip-k7g0hd6t- uninstall\\anwendungsentwicklung\\python34\\scripts\\pip.exe'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\anwendungsentwicklung\python34\lib\site-packages\pip\basecommand.py", line 232, in main
logger.critical('Operation cancelled by user')
File "c:\anwendungsentwicklung\python34\lib\site-packages\pip\commands\install.py", line 347, in run
ensure_dir(options.target_dir)
File "c:\anwendungsentwicklung\python34\lib\site-packages\pip\req\req_set.py", line 560, in install
missing_requested = sorted(
File "c:\anwendungsentwicklung\python34\lib\site-packages\pip\req\req_install.py", line 677, in commit_uninstall
logger.debug(
File "c:\anwendungsentwicklung\python34\lib\site-packages\pip\req\req_uninstall.py", line 153, in commit
self.save_dir = None
File "c:\anwendungsentwicklung\python34\lib\site-packages\pip\utils\__init__.py", line 58, in rmtree
SUPPORTED_EXTENSIONS = ZIP_EXTENSIONS + TAR_EXTENSIONS
File "c:\anwendungsentwicklung\python34\lib\shutil.py", line 484, in rmtree
return _rmtree_unsafe(path, onerror)
File "c:\anwendungsentwicklung\python34\lib\shutil.py", line 368, in _rmtree_unsafe
_rmtree_unsafe(fullname, onerror)
File "c:\anwendungsentwicklung\python34\lib\shutil.py", line 368, in _rmtree_unsafe
_rmtree_unsafe(fullname, onerror)
File "c:\anwendungsentwicklung\python34\lib\shutil.py", line 368, in _rmtree_unsafe
_rmtree_unsafe(fullname, onerror)
File "c:\anwendungsentwicklung\python34\lib\shutil.py", line 376, in _rmtree_unsafe
print(fullname)
File "c:\anwendungsentwicklung\python34\lib\site-packages\pip\utils\__init__.py", line 70, in rmtree_errorhandler
try:
PermissionError: [WinError 5] Zugriff verweigert: 'C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\pip-k7g0hd6t-uninstall\\anwendungsentwicklung\\python34\\scripts\\pip.exe'
Now I added a breakpoint in "c:\anwendungsentwicklung\python34\lib\shutil.py":
# version vulnerable to race conditions
def _rmtree_unsafe(path, onerror):
try:
if os.path.islink(path):
# symlinks to directories are forbidden, see bug #1669
raise OSError("Cannot call rmtree on a symbolic link")
except OSError:
onerror(os.path.islink, path, sys.exc_info())
# can't continue even if onerror hook returns
return
names = []
try:
names = os.listdir(path)
except OSError:
onerror(os.listdir, path, sys.exc_info())
for name in names:
fullname = os.path.join(path, name)
try:
mode = os.lstat(fullname).st_mode
except OSError:
mode = 0
if stat.S_ISDIR(mode):
_rmtree_unsafe(fullname, onerror)
else:
try:
#import pdb
os.unlink(fullname)
#pdb.set_trace()
except OSError:
import pdb; pdb.set_trace()
print(fullname)
import getpass
print(getpass.getuser())
onerror(os.unlink, fullname, sys.exc_info())
try:
os.rmdir(path)
except OSError:
onerror(os.rmdir, path, sys.exc_info())
When i execute
os.unlink(fullname) # 'C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\pip-k7g0hd6t- uninstall\\anwendungsentwicklung\\python34\\scripts\\pip.exe'
I get this `PermissionError`, so i checked the rights of this .exe file with
oct(os.stat(fullname)[ST_MODE])
and it returns: '0o100777'
And when i'm right, this means full permission for everyone (owner, group and
others).
I'm frustrated :/ Someone an idea?
Answer: As discussed [here](https://github.com/pypa/pip/issues/1299), it's a Windows
limitation. In brief, the pip.exe file is in use and thus locked and can't be
deleted. Use `python -m pip install --upgrade pip`.
|
Key press event not registered properly by matplotlib
Question: I'm working with some image data where it is helpful to click on different
elements in the image. I would like to have "shift-click" be the triggering
mechanism for registering the cursor position.
I wrote a "click" function which does the right thing. However, when I tried
to upgrade it to "shift-click" it simply does not work. The weird thing is
that it DOES work on my coworker's computer using an older version of
Matplotlib (1.1, running on a linux box, where mine is 1.4.2, running on a
Mac. Both are running Python 2.7)
Does anyone have any idea what is going on? I'm completely out of ideas. Other
possibly relevant info is I installed Seaborn recently (and then uninstalled
it) and upgraded matplotlib (and tried to downgrade, but that failed)
**EDIT** OK, I think I understand now. Shift must be pressed and released at
least once before starting to work properly. Maybe there is a workaround to
this.
import numpy as np
import matplotlib.pyplot as plt
def shiftclick(refimage, comment=None, eq=True):
class EventHandler:
def __init__(self, spotlist):
fig.canvas.mpl_connect('button_press_event', self.onpress)
fig.canvas.mpl_connect('key_press_event', self.on_key_press)
fig.canvas.mpl_connect('key_release_event', self.on_key_release)
self.shift_is_held = False
def on_key_press(self, event):
if event.key == 'shift':
self.shift_is_held = True
def on_key_release(self, event):
if event.key == 'shift':
self.shift_is_held = False
def onpress(self, event):
if event.inaxes!=ax:
return
if self.shift_is_held:
xi, yi = (int(round(n)) for n in (event.xdata, event.ydata))
value = im.get_array()[xi,yi]
print xi, yi
spotlist.append((xi, yi))
im = plt.imshow(refimage, interpolation='nearest', origin='lower')
plt.title('SHIFT-click on locations')
fig = plt.gcf()
ax = plt.gca()
spotlist = []
handler=EventHandler(spotlist)
plt.show()
return spotlist
def click(refimage, comment=None):
class EventHandler:
def __init__(self, spotlist):
fig.canvas.mpl_connect('button_press_event', self.onpress)
def onpress(self, event):
if event.inaxes!=ax:
return
xi, yi = (int(round(n)) for n in (event.xdata, event.ydata))
value = im.get_array()[xi,yi]
print xi, yi
spotlist.append((xi, yi))
im = plt.imshow(refimage, interpolation='nearest', origin='lower')
fig = plt.gcf()
ax = plt.gca()
spotlist = []
handler=EventHandler(spotlist)
plt.show()
return spotlist
if __name__ == "__main__":
a = np.random.random((100, 100))
#this works
click(a)
#this doesn't work
shiftclick(a)
Answer: OK, here was the problem. After upgrading Matplotlib, the MacOSX backend
refused to deal with event handling properly. It ignored all shift-button
presses.
Using the TKAgg backend fixed the problem, as long as shift is pressed at
least once before trying to select points. This is still undesirable.
Using the Qt4Agg backend had the best possible behavior. As long as the window
was selected, it responded to the first shift press correctly.
|
Take a list of coordinates and plot them on a graph
Question: Right now I have a list of coordinates that are in the following format:
(1,12),(2,3),(3,9)....
All the coordinates are in brackets as above, and the format is exactly the
same for the rest of the string (the list is in string format). The x-values
of the coordinates increase by one throughout the string (and could continue
on to even 100000. The y-values are random and could range from 1 to 2048 or
even higher numbers. I want to find a way to take that string (which is a list
of coordinates in the above format) and turn it into a picture or virtual
graph, with each point plotted on it. I am currently using Python 2.7 in
visual studio, but am open to using other programs, as the string itself is
stored in a .txt file in the above format.
Once that is done, I'd like to be able to take that graph and using only it as
a base point, be able to regenerate the entire string again.
Answer: You can use [matplotlib](http://matplotlib.org/users/pyplot_tutorial.html) to
plot and
[ast.literal_eval](https://docs.python.org/2/library/ast.html#ast.literal_eval)
to evaluate your string:
import matplotlib.pylab as plt
from ast import literal_eval
from operator import itemgetter
with open("your_file") as f:
lst = literal_eval(f.read())
x,y = map(itemgetter(0),lst), map(itemgetter(1),lst)
plt.plot(x,y)
plt.show()
|
how to convert a txt file to a array python. "could not convert string to float"
Question: I need to import a array value of a txt file but when i print to see my values
i get this error: "could not convert string to float: vector(0.1013, 0.2395,
1.1926), vector(0.1276, 0.2361, 1.1760), vector(0.13952644965926353,
0.23617897201269641, 1.1760001652770353), vector(0.16723382973344353,
0.23617897201269641, 1.176000165277035" showing only a few values of the
array. Any idea as to what I am doing wrong and what would be the correct way
to do it ?
def load_files(self):
dlg = wx.FileDialog(None,message="Choose File",wildcard= 'Points (*.txt; *.csv)|*.txt;*.csv', defaultFile="",style=wx.FD_OPEN|wx.FD_FILE_MUST_EXIST|wx.FD_CHANGE_DIR)
if dlg.ShowModal() == wx.ID_CANCEL:
print ('buh cancelaste')
else:
filename=dlg.GetFilename()
f = open(filename)
data = f.read()
data = np.array(data).astype(float)
print(data)
files = wx.Button(pan, label='Load Coordinates', pos=(x1+158,570), size = (150,40))
files.Bind(wx.EVT_BUTTON, load_files)
txt file.
vector(0.1013, 0.2395, 1.1926), vector(0.1276, 0.2361, 1.1760),
vector(0.13952644965926353, 0.23617897201269641, 1.1760001652770353),
vector(0.16723382973344353, 0.23617897201269641, 1.1760001652770353),
vector(0.18306661834726065, 0.23617897201269641, 1.1760001652770353),
vector(0.21077399842144068, 0.23219954535704859, 1.1760001652770353),
vector(0.22264858988180353, 0.22822011870140083, 1.1760001652770353),
vector(0.23452318134216635, 0.22822011870140083, 1.1760001652770353)
vector(-3.22925576, 0.78085742, 8.2709313 ), vector(0.12270437, 0.29943441,
1.65709467), vector(0.1278586, 0.09019178, 1.24548948), vector(0.25600214,
-0.04258577, 0.6109198)
vector(0.12795994, 0.30532043, 1.6896684 ), vector( 0.13624277, 0.09229906,
1.24548948), vector(0.29656594, -0.08827312, 0.69378916), vector (0.19870717,
-0.09120946, 1.19266453)
Answer: The error message indicates that `data` as passed to `np.array` is one or more
strings of the form
vector(0.1013, 0.2395, 1.1926), vector(0.1276, 0.2361, 1.1760), vector(0.13952644965926353, 0.23617897201269641, 1.1760001652770353), vector(0.16723382973344353, 0.23617897201269641, 1.176000165277035
One long string. You did nothing to break it up on spaces, commas or even
newlines.
With `astype(float)` you are trying to convert that string to a float, or
sequence of floats. The Python `float(astr)` function works with strings like
`"0.1013"`, not long ones with many numbers. Even if you broke the `data` into
substrings like
vector(0.1013, 0.2395, 1.1926)
it would have problems, because `vector` means nothing.
You need to do more parsing of those file lines. You need to split them into
lines (e.g. `readline()`), strip off `\n`, split them up into blocks like
`vector()`, and further split that into strings with one number each. In other
words, a list of strings like this will work:
In [848]: np.array(['0.1013', '0.2395', '1.1926'])
Out[848]:
array(['0.1013', '0.2395', '1.1926'],
dtype='<U6')
In [849]: np.array(['0.1013', '0.2395', '1.1926']).astype(float)
Out[849]: array([ 0.1013, 0.2395, 1.1926])
* * *
Observe what happens when `data` is that 'vector()' string:
In [852]: np.array('vector(0.1013, 0.2395, 1.1926)')
Out[852]:
array('vector(0.1013, 0.2395, 1.1926)',
dtype='<U30')
In [853]: np.array('vector(0.1013, 0.2395, 1.1926)').astype(float)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-853-413e30b24430> in <module>()
----> 1 np.array('vector(0.1013, 0.2395, 1.1926)').astype(float)
ValueError: could not convert string to float: 'vector(0.1013, 0.2395, 1.1926)'
`astype(float)` does not search the string(s) for substrings that look like
numbers. Try `float('123 45')` and variations. `float()` needs something that
looks exactly like a float or integer.
|
Python, launch concurrent.futures.ProcessPoolExecutor with initialization?
Question: I'm planning to use `concurrent.futures.ProcessPoolExecutor` to parallelize
execution of functions. According to the
[documentation](https://docs.python.org/3/library/concurrent.futures.html),
its `executor` object can only accept a simple function in `map`. My actual
situation involves initialization (loading of data) prior to execution of the
'to-be-parallelized' function. How do I arrange that?
The 'to-be-parallelized' function is called in an iteration for many times. I
don't want it to be re-initialized each time.
In other words, there's an `init` function that produces some output to this
tbp function. Each child should have its own copy of that output, because the
function depended on that.
Answer: It sounds like you're looking for an equivalent to the
`initializer`/`initargs` options that
[`multiprocessing.Pool`](https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool)
takes. Currently, that behavior doesn't exist for
`concurrent.futures.ProcessPoolExecutor`, though there is a [patch waiting for
review](http://bugs.python.org/issue21423) that adds that behavior.
So, you can either use `multiprocessing.Pool` (which might be fine for your
usecase), wait for that patch to get merged and released (you might be waiting
a while :)), or roll your own solution. Turns out, it's not too hard to write
a wrapper function for map that takes an `initializer`, but only calls it one
per process:
from concurrent.futures import ProcessPoolExecutor
from functools import partial
inited = False
initresult = None
def initwrapper(initfunc, initargs, f, x):
# This will be called in the child. inited
# Will be False the first time its called, but then
# remain True every other time its called in a given
# worker process.
global inited, initresult
if not inited:
inited = True
initresult = initfunc(*initargs)
return f(x)
def do_init(a,b):
print('ran init {} {}'.format(a,b))
return os.getpid() # Just to demonstrate it will be unique per process
def f(x):
print("Hey there {}".format(x))
print('initresult is {}'.format(initresult))
return x+1
def initmap(executor, initializer, initargs, f, it):
return executor.map(partial(initwrapper, initializer, initargs, f), it)
if __name__ == "__main__":
with ProcessPoolExecutor(4) as executor:
out = initmap(executor, do_init, (5,6), f, range(10))
print(list(out))
Output:
ran init 5 6
Hey there 0
initresult is 4568
ran init 5 6
Hey there 1
initresult is 4569
ran init 5 6
Hey there 2
initresult is 4570
Hey there 3
initresult is 4569
Hey there 4
initresult is 4568
ran init 5 6
Hey there 5
initresult is 4571
Hey there 6
initresult is 4570
Hey there 7
initresult is 4569
Hey there 8
initresult is 4568
Hey there 9
initresult is 4570
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
Python file() function
Question: I've been adapting an old piece of code to be Python 3 compliant and I came
across this individual script
"""Utility functions for processing images for delivery to Tesseract"""
import os
def image_to_scratch(im, scratch_image_name):
"""Saves image in memory to scratch file. .bmp format will be read
correctly by Tesseract"""
im.save(scratch_image_name, dpi=(200, 200))
def retrieve_text(scratch_text_name_root):
inf = file(scratch_text_name_root + '.txt')
text = inf.read()
inf.close()
return text
def perform_cleanup(scratch_image_name, scratch_text_name_root):
"""Clean up temporary files from disk"""
for name in (scratch_image_name, scratch_text_name_root + '.txt',
"tesseract.log"):
try:
os.remove(name)
except OSError:
pass
On the second function, `retrieve_text` the first line fails with:
Traceback (most recent call last):
File ".\anpr.py", line 15, in <module>
text = image_to_string(Img)
File "C:\Users\berna\Documents\GitHub\Python-ANPR\pytesser.py", line 35, in image_to_string
text = util.retrieve_text(scratch_text_name_root)
File "C:\Users\berna\Documents\GitHub\Python-ANPR\util.py", line 10, in retrieve_text
inf = file(scratch_text_name_root + '.txt')
NameError: name 'file' is not defined
Is this a deprecated function or another problem alltogether? Should I be
replacing `file()` with something like
[`open()`](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-
writing-files)?
Answer: In Python 2, `open` and `file` are mostly equivalent. `file` is the type and
`open` is a function with a slightly friendlier name; both take the same
arguments and do the same thing when called, but calling `file` to create
files is discouraged and trying to do type checks with `isinstance(thing,
open)` doesn't work.
In Python 3, the file implementation in the `io` module is the default, and
the `file` type in the builtin namespace is gone. `open` still works, and is
what you should use.
|
Calling a FORTRAN DLL using ctypes
Question: I am trying to learn how to complie FORTRAN code into a DLL that I can call
from Python using ctypes. Even a simple example is not working, can anyone
help?
I have a single procedure in FORTRAN:
subroutine ex(i)
integer i
i=i+1
return
end
Then I try to run this from Python
I compile it with the MinGW complier as follows
gfortran -c test.f
gfortran -shared -mrtd -o test.dll test.o
Looking at the DLL created I see
Microsoft (R) COFF/PE Dumper Version 12.00.30723.0
Copyright (C) Microsoft Corporation. All rights reserved.
Dump of file test.dll
File Type: DLL
Section contains the following exports for test.dll
00000000 characteristics
0 time date stamp Thu Jan 01 13:00:00 1970
0.00 version
1 ordinal base
1 number of functions
1 number of names
ordinal hint RVA name
1 0 00001280 ex_
Summary
1000 .CRT
1000 .bss
1000 .data
1000 .edata
1000 .eh_fram
1000 .idata
1000 .rdata
1000 .reloc
1000 .text
1000 .tls
Then I try to access this from Python
from ctypes import *
DLL = windll.test
print DLL
print getattr(DLL,'ex_')
print DLL[1]
print DLL.ex_
x = pointer( c_int(3) )
DLL.ex_( x )
The output is
<WinDLL 'test', handle 6bec0000 at 2143850>
<_FuncPtr object at 0x020E88A0>
<_FuncPtr object at 0x020E8918>
<_FuncPtr object at 0x020E88A0>
Traceback (most recent call last):
File "C:\proj_py\test.py", line 20, in <module>
DLL.ex_( x )
ValueError: Procedure probably called with too many arguments (4 bytes in excess)
So although the function is there, I'm not calling it correctly. I'm stumped.
I am using python 2.7.10 (32 bit) on a 64-bit Windows-7 machine, I have a
recent version of the MinGW compiler:
$ gfortran -v
Using built-in specs.
COLLECT_GCC=c:\mingw\bin\gfortran.exe
COLLECT_LTO_WRAPPER=c:/mingw/bin/../libexec/gcc/mingw32/4.8.1/lto-wrapper.exe
Target: mingw32
Configured with: ../gcc-4.8.1/configure --prefix=/mingw --host=mingw32 --build=mingw32 --without-pic --enable-shared --e
nable-static --with-gnu-ld --enable-lto --enable-libssp --disable-multilib --enable-languages=c,c++,fortran,objc,obj-c++
,ada --disable-sjlj-exceptions --with-dwarf2 --disable-win32-registry --enable-libstdcxx-debug --enable-version-specific
-runtime-libs --with-gmp=/usr/src/pkg/gmp-5.1.2-1-mingw32-src/bld --with-mpc=/usr/src/pkg/mpc-1.0.1-1-mingw32-src/bld --
with-mpfr= --with-system-zlib --with-gnu-as --enable-decimal-float=yes --enable-libgomp --enable-threads --with-libiconv
-prefix=/mingw32 --with-libintl-prefix=/mingw --disable-bootstrap LDFLAGS=-s CFLAGS=-D_USE_32BIT_TIME_T
Thread model: win32
gcc version 4.8.1 (GCC)
Can anyone offer a solution?
Thanks
Answer: Fortran is generally pass-by-reference. When calling from other languages like
C, that means passing a memory address into the Fortran subroutine. Apparently
the Python implementation is similar. Before your edit, you had an error that
said something like "Illegal access at 0x000003" which was suspiciously the
same value "3" as you were trying to pass as the value. You entered the
Fortran subroutine just fine, but when it tried to do the add, it looked for
the integer at memory location 3 instead of using the value 3 in the addition
itself.
After your edit, you are passing a pointer (based on my comment, I think).
That gives a different error. It suggests that you passed an extra argument
because it got 4 bytes more data than it expected. I think that's likely an
incompatibility between some 32 bit libraries and some 64 bit libraries, with
4 bytes being a likely difference in length between pointers in the two
architectures.
|
logical or on list of pandas masks
Question: I have a list of boolean masks obtained by applying different search criteria
to a dataframe. Here is an example list containing 4 masks:
mask_list = [mask1, mask2, mask3, mask4]
I would like to find the logical or of all of the masks in the list. In other
words,
or_mask = mask_list[0] | mask_list[1] | mask_list[2] | mask_list[3]
Is there a compact way to accomplish this for a list containing an arbitrary
number of masks? I understand that I can write a for loop as below, but is
there a shorter, more pythonic way to do this?
for i in range(len(mask_list)):
if i == 0:
temp_mask_or = mask_list[i]
else:
temp_mask_or = temp_mask_or | mask_list[i]
Answer: You can use reduce:
`or_(x,y)` means `x|y` so this will work:
from operator import or_
or_mask = reduce(or_,mask_list)
Edit: As suggested by JoeCondron, instead of `operator.or_` you could use
`numpy.logical_or` which gives the same result but is faster.
|
In flask how to get current time in GMT?
Question: I want to get current time in GMT, like `2015-08-21 05:13:13+00:00` Here you
can see that correction is made like 00:00 for GMT, In django they are using
`from django.utils import timezone` and `date_to = timezone.now()` to
calculate the current time. How I will get the same functionality in flask,
Formate of time should be like `2015-08-21 05:13:13+00:00` not like
`2015-03-30 07:19:06.746037+02`. I got this
[link](http://stackoverflow.com/questions/29344289/python-strftime-a-utc-
timestamp-to-local-time-format) but they are using `2015-03-30 07:19:06+02`. I
don't want. Just GTM time
Following code is in Django, I want same in Flask, Here they are using `from
django.utils import timezone`. In Flask what is equivalent of it, which gives
current time in this format `2015-08-21 05:13:13+00:00`
import datetime
import pytz
from django.utils import timezone
def calc_date_args(date_from, date_to, date_options):
try:
date_to = timezone.now()
print 'calc_date_args, date_to', date_to #calc_date_args, date_to 2015-08-21 05:13:13.615541+00:00
date_from = date_to - datetime.timedelta(days=float(date_options))
except Exception:
raise ValueError(_("The time delta must be a number representing "
"the time span in days"))
return date_from, date_to
Answer: Not sure if you mean UTC time instead of GMT, as most machines consume UTC and
most timestamps are in UTC.
In Python 3 to get UTC timezone-aware timestamp:
import datetime
def now():
"""Get timezone-aware UTC timestamp."""
return datetime.datetime.now(datetime.timezone.utc)
|
Where do I get the Authorized Gmail API service instance? (python, gmail api)
Question: I'm trying to call from my gmail api code so I can create a draft, but I can't
figure out where to get the "Authorized Gmail API service instance." Here's my
code:
def CreateDraft(service, user_id, message_body):
CreateDraft('SERVICE THING NEEDS TO BE HERE','me','thisisbody')
"""Create and insert a draft email. Print the returned draft's message and id.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
message_body: The body of the email message, including headers.
Returns:
Draft object, including draft id and message meta data.
"""
try:
message = {'message': message_body}
draft = service.users().drafts().create(userId=user_id, body=message).execute()
print 'Draft id: %s\nDraft message: %s' % (draft['id'], draft['message'])
return draft
except errors.HttpError, error:
print 'An error occurred: %s' % error
return None
Does anyone know where the Authorized Gmail API service instance is found? I
have a client id and secret but it's nothing to do with that right?
Answer: So I figured it out. I did the following:
1) Change SCOPES to:
SCOPES = 'https://mail.google.com/'
2) On your computer (Windows 7) go to "C:\Users\YOURUSERNAME\\.credentials
3) Delete the file "gmail-quickstart"
4) Run the code again (quickstart.py)
5) When the message pops up in your browser, click accept.
6) Check mail, you should have your message in there if you're looking to send
email through the api.
The credentials file seems to hold the permissions. Changing your permissions
and then deleting that file seems to make it all work perfectly. So overall
your code should look something like this if you were looking to send mail
through the api:
import httplib2
import os
from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
SCOPES = 'https://mail.google.com/'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Gmail API Quickstart'
def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'gmail-quickstart.json')
store = oauth2client.file.Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatability with Python 2.6
credentials = tools.run(flow, store)
print 'Storing credentials to ' + credential_path
return credentials
import base64
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import mimetypes
from httplib2 import Http
from apiclient import errors
from apiclient.discovery import build
credentials = get_credentials()
service = build('gmail', 'v1', http=credentials.authorize(Http()))
def SendMessage(service, user_id, message):
"""Send an email message.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
message: Message to be sent.
Returns:
Sent Message.
"""
try:
message = (service.users().messages().send(userId=user_id, body=message)
.execute())
print 'Message Id: %s' % message['id']
return message
except errors.HttpError, error:
print 'An error occurred: %s' % error
def CreateMessage(sender, to, subject, message_text):
"""Create a message for an email.
Args:
sender: Email address of the sender.
to: Email address of the receiver.
subject: The subject of the email message.
message_text: The text of the email message.
Returns:
An object containing a base64 encoded email object.
"""
message = MIMEText(message_text)
message['to'] = to
message['from'] = sender
message['subject'] = subject
return {'raw': base64.b64encode(message.as_string())}
testMessage = CreateMessage('EMAIL ADDRESS', 'EMAIL ADDRESS', 'subject', 'YOUR MESSAGE')
testSend = SendMessage(service, 'me', testMessage)
|
Unable to launch python scripts on the YARN Hadoop cluster via remote
Question: Since a few weeks i tried to submit python scripts via remote access or
connecting to the pyspark shell of the YARN cluster.
I am new to the HADOOP world. What I want is submitting spark scripts in my
local shell on the external HADOOP cluster.
My situation: External hadoop YARN cluster. Have access to the important
ports. I have Windows 7 64 Bit / Python 2.7.9 64 Bit / Spark 1.4.1. The HADOOP
cluster is running without any problems.
My problem: Submitting python scripts via remote access on the HADOOP cluster
doesnt work.
If i try spark-submit --master yarn-cluster --num-executors 2 --driver-memory
512m --executor-memory 512m --executor-cores 4 ... example.py
It says
Error: Cluster deploy mode is not applicable to Spark shells.
Exception: Java gateway process exited before sending the driver its port number
So as far as I understand the problem I think the question is
> > How do I set the yarn-config correctly to connect with my local client
> (not part of the cluster) to the external YARN cluster.
Answer: **SPARK VERSION 1.6.0 (which is the current version writing this).**
Python code cannot be executed in YARN-cluster mode. Python can only executed
in a cluster mode on a native spark cluster.
You can switch to use a spark cluster or you re-implement your code in Java or
Scala.
|
Append with date_range() in Python
Question: I have a csv file which contains start dates and end dates, with format
`dd/mm/yy`. These are read by :
dateparse = lambda x: pnd.datetime.strptime(x, '%d/%m/%y')
df = pnd.read_csv('file.csv',sep=';',parse_dates=['StartDate','EndDate'], date_parser=dateparse)
A sample of the dataframe looks like this:
StartDate EndDate
0 2015-07-15 2015-07-18
1 2015-06-06 2015-06-08
I want to get all the dates listed in these intervals in a column in a new
dataframe:
Date
0 2015-07-15
1 2015-07-16
2 2015-07-17
3 2015-07-18
4 2015-06-06
5 2015-06-07
6 2015-06-08
I use iteratively `date_range(StartDate, EndDate)`, appending each time the
result, but I get either an empty array, or something like
[[2015-07-15, 2015-07-16, 2015-07-17, 2015-07-18], [ 2015-06-06, 2015-06-07 , 2015-06-08 ]]
and I would like
[ 2015-07-15, 2015-07-16, 2015-07-17, 2015-07-18, 2015-06-06, 2015-06-07 , 2015-06-08 ]
What to do?
Answer: You can chain the ranges together using `itertools.chain` to create your list
of dates:
from itertools import chain
new_df = pnd.DataFrame(list(chain.from_iterable(pnd.date_range(r["StartDate"],r["EndDate"])
for _,r in df.iterrows())), columns=("Date",))
Output:
Date
0 2015-07-15
1 2015-07-16
2 2015-07-17
3 2015-07-18
4 2015-06-06
5 2015-06-07
6 2015-06-08
|
html data scrapping in python
Question: I am getting the data in the html format. how to get the specific data from
that format. The complete html is coming in the post request of the django.
Now I have to fetch the data in the between the tables tags in html. Tried
beautifulSoup but is taking data from urls. Any possible way to get data
between the tags in python .
python version:2.7
Answer: beautiful soup and requests.
requests to get the data then beautiful soup to read from tags eg.
from bs4 import BeautifulSoup
import requests
r = requests.get("https://www.google.com")
soup = BeautifulSoup(r.text)
div_style = div.find('div')['style']
If the page is javascript based you may need to use selenium and webdriver
with the browser of your choice. If its css based you may need cssutils to
parse it.
|
How to hide stdout/stderr on python extension
Question: I want to hide stdout/stderr in a python script **BUT** the print is not done
into the python script itself but inside the underlying .c extension when a
python module needs one.
it is the case for _netsnmp_ python module, it requires compilation, the
problem is that there are some 'printf' directly into the C (client_intf.c)
code that I would like to capture and hide :
from netsnmp import *
import sys,os
devnull = open(os.devnull, 'w')
sys.stdout, sys.stderr = devnull, devnull
session = Session(DestHost='myhostthatdoesnotexisttogenerateerror',Version=2,Community='demopublic')
When I run it I still have some traces :
python test.py
getaddrinfo: myhostthatdoesnotexisttogenerateerror nodename nor servname provided, or not known
error:snmp_new_session: Couldn't open SNMP session
How can I get rid of these messages on stdout/stderr ? this is important
because I am developping Nagios plugins, and I can afford such output
(nevertheless, I want to capture them to raise a custom exception)
Answer: Depending on your OS (seems to work on both Windows and Linux at least) the
following would shut up fx `stdout` completely, by replacing the (low level)
file descriptor:
nulf = os.open(os.devnull, os.O_WRONLY)
os.dup2(nulf, stdout.fileno())
os.close(nulf)
the same to `stderr` doesn't seem to work that well in interactive mode (I
guess that the python interpreter tries to write it's stuff to stderr).
This solution will have the same effect that redirect to `/dev/null` or
equivalent when starting the interpreter (except it takes effect later),
including any printouts that are made in native code (and of course any
printout your script is trying to do). If you want to do any logging you would
have to open a file for that (you could also open a file other than
`os.devnull` in the first place if you'd like to redirect `stdout` to a file
instead).
Note that normally a program doesn't check the result of printouts and in that
case one could simply close the descriptor (ie `os.close(stdout.fileno())`),
but that would fail if the extension actually checks the results and acts
differently based on that.
|
Unable to set the Entry box to correct position in python
Question: I am trying to learn creating GUI using Tkinter .I created a window which
includes text,Messagebox,Entry widget,labels and Radio buttons.
I used grid method for frames and tried to make entry boxes in row0 and row1
.And a message Box with Some text.But these are not properly aligned even
though i gave correct rows and columns but output is not in order.
Entry box is created very far though i mentioned column1 .And message box is
created as per the column specified.Can anyone help me how to solve this.If i
am missing anything please let me now .
from Tkinter import*
import tkMessageBox
class Example:
def __init__(self,root):
root.title("Sample")
#Entry functions ---------------------------------------
Label(root, text="First Name").grid(row=0)
Label(root, text="Last Name").grid(row=1)
self.e1 = Entry(root)
self.e1.bind("<Return>",self.ShowChoice_radio)
self.e2 = Entry(root)
self.e2.bind("<Return>",self.ShowChoice_radio)
self.e1.grid(row=0,column=1)
self.e2.grid(row =1,column = 1)
#------------------------------------------------------------------------
self.frame=Frame(root)
self.frame.grid(row=3,sticky=W)
self.label=Label(self.frame, text="mine", width=12,bg="green",fg="white",justify=LEFT)
self.label.grid(row=3,column=4,sticky=W,pady=4)
root.minsize(width=666, height=220)
self.v=IntVar()
role=[("ENGLISH",1),("SPANISH",2),("GERMAN",3)]
Label(self.frame,text="Choose your role of target:",justify=LEFT,padx=2,pady=2).grid(row=4,sticky=W)
i=0
for txt,val in role:
i=i+1
self.rad_bt=Radiobutton(self.frame,text=txt,padx=20,variable=self.v,
command=self.ShowChoice_radio,value=val)
self.rad_bt.grid(row=4,column=i+1)
self.bottomframe = Frame(root)
self.bottomframe.grid(row=12,sticky=W)
self.hello(12)
T=Text(self.bottomframe,height=2,width=30)
T.pack(padx=100,side=TOP)
T.insert(END,"just a normal text to display!\n")
self.mbutton=Button(self.bottomframe,text='Quit',command=self.callback,state='normal')
self.mbutton.pack(padx=3,pady=3,side='left')
self.help=Button(self.bottomframe,text='Help',command=self.help_msg,width=5,justify=CENTER)
self.help.pack(padx=93,pady=3,side='left')
def ShowChoice_radio(self):
print self.v.get()
def help_msg(self):
tkMessageBox.showinfo("Help to print ",message="Not yet implemented")
root.minsize(width=666, height=666)
self.show_entry_fields()
self.help.config(state=DISABLED)
def callback(self):
if tkMessageBox.askyesno('verify','Really Quit?'):
root.destroy()
def hello(self,name):
w=Label(root,text="Hello Tkinter!",width=15).grid(row=10)
whatever_you_do = "Whatever . it is my test that \n i can anble to display manner in this case find out whether it is correct one or wrong \n)"
msg=Message(root, anchor='s',width=200,text = whatever_you_do)
msg.config(bg='lightgreen', font=('times', 14, 'italic'))
msg.grid(row=10,column=1,sticky=W)
def show_entry_fields(self):
print "First Name: %s\nLast Name: %s" % (self.e1.get(), self.e2.get())
if __name__=="__main__":
root=Tk()
app=Example(root)
root.mainloop()
Even the quit and Help buttons are not proper...!!!
Answer: I initially voted to close this because there is not a clear question, but
mostly only a series of statements and opinions, at least one of which is
incorrect. After looking more, I think I can answer your implied question "Why
is tkinter behaving in a way that seems wrong to me?". The answer, I believe,
is that you do not understand that grid coordinates are independent (start
over) for each container gridded. Also, coordinates not used are ignored. In
particular:
Root has a grid of 5 rows and 2 columns. Renumbering the rows 0, 1, 2, 3, 4
instead of the confusing labeling you used, there is no entry in column 1 for
rows 2 and 4. The width of column 0 is determined by the width of self.frame
in row 2, column 0. The entry boxes are far to the right because column 0 is
very wide.
Self.frame has a grid of 2 rows and 4 columns. The first 3 columns of row 0
are empty. Self.bottomframe is packed instead of gridded. The buttons are to
the left of where you want because you packed them to the left. In other
words, tkinter did just what you said, which is apparently not what you want.
You might list the result better if you got rid of self.frame, put 'mine' in
(2,0) or (2,0), 'Choose...' in (3, 0), and a frame with 3 radio buttoms in
(3,1). Then root column 0 would not be so overly wide.
|
Is there other ways to convert a string to int in python2 without int and string.atoi?
Question: Is there other ways to convert a string to int in python2 without int and
string.atoi? Like convert a "2" to 2.
Answer:
>>> a="2"
>>> int(a)
2
>>>
I would recommend using try catch,
try:
a = int(a)
except:
#do something
You can also use `ast` module,
>>> import ast
>>> ast.literal_eval("2")
2
>>>
|
Python rock, paper, scissors game. not always give correct answers
Question: I'm trying to make a simple **_Rock, Paper, Scissors_** game in **python 3.4**
and it works to a certain degree but some time i get an output of "You Won
Rock crushes Rock" even though i thought i have stop this from happening and
only allowed certain outcomes of the code with my elif and if statements. So
can anyone tell me why isn't this working sometimes. :)
import random
count = 0
OPTIONS = ['rock', 'paper', 'scissors']
# then check if the user lose's, wins ties
def computer():
return random.choice(OPTIONS)
print("\n"+"-=-"*11)
print("Welcome to ROCK, PAPER, SCISSORS")
print(" GAME")
print(" It's you Vs. the computer!")
print("-=-"*11)
while True:
user = input("What do you choose Rock, Paper, Scissors: ").lower()
if user in OPTIONS:
# Possible user time a user can succeeds rock beats sicissor, sicissors cuts paper, paper covers rock
if user == computer():
print("tie")
elif user == 'rock' and computer() == 'scissors':
print("\nYou Won! {} crushes {}".format(user.title(), computer().title()))
elif user == 'scissors' and computer() =='rock':
print("\nComputer Won! {} crushes {}".format(computer().title(), user.title() ))
elif user == 'scissors' and computer() == 'paper':
print("\nYou Won! {} cuts {}".format(user.title(), computer().title()))
elif user == 'paper' and computer() == 'scissors':
print("\nComputer Won! {} cuts {}".format(computer().title(), user.title()))
elif user == 'paper' and computer() == 'rock':
print("\nYou Won! {} covers {}".format(user.title(), computer().title()))
elif user == 'rock' and computer() == 'paper':
print("\nComputer Won! {} covers {}".format(computer().title(), user.title()))
else:
print("\nMake sure you choose ethier Rock, Paper or Scissors")
enter code here
Answer:
elif user == 'rock' and computer() == 'scissors':
print("\nYou Won! {} crushes {}".format(user.title(), computer().title()))
Every time you call `computer()`, it generates a completely new value,
independent of any previous calls. For example, in the code above it's
entirely possible that the first `computer()` call returns "scissors", and the
second one returns "rock".
Call `computer()` only once in the loop, and store the result. Then use that
value for the rest of your code.
while True:
user = input("What do you choose Rock, Paper, Scissors: ").lower()
if user in OPTIONS:
computer_move = computer()
# Possible user time a user can succeeds rock beats sicissor, sicissors cuts paper, paper covers rock
if user == computer_move:
print("tie")
elif user == 'rock' and computer_move == 'scissors':
print("\nYou Won! {} crushes {}".format(user.title(), computer_move.title()))
#etc
|
Pythonic way to select elements of an array based on values?
Question: I'm looking for a pythonic (1-line) way to extract a range of values from an
array Here's some sample code that will extract the array elements that are >2
and <8 from x,y data, and put them into a new array. Is there a way to
accomplish this on a single line? The code below works but seems kludgier than
it needs to be. (Note I'm actually working with floats in my application)
import numpy as np
x0 = np.array([0,3,9,8,3,4,5])
y0 = np.array([2,3,5,7,8,1,0])
x1 = x0[x0>2]
y1 = y0[x0>2]
x2 = x1[x1<8]
y2 = y1[x1<8]
print x2, y2
This prints
[3 3 4 5] [3 8 1 0]
Part (b) of the problem would be to extract values say `1 < x < 3` _and_ `7 <
x < 9` as well as their corresponding `y` values.
Answer: You can chain together boolean arrays using `&` for element-wise `logical and`
and `|` for element-wise `logical or`, so that the condition `2 < x0` and `x0
< 8` becomes
mask = (2 < x0) & (x0 < 8)
* * *
For example,
import numpy as np
x0 = np.array([0,3,9,8,3,4,5])
y0 = np.array([2,3,5,7,8,1,0])
mask = (2 < x0) & (x0 < 8)
x2 = x0[mask]
y2 = y0[mask]
print(x2, y2)
# (array([3, 3, 4, 5]), array([3, 8, 1, 0]))
mask2 = ((1 < x0) & (x0 < 3)) | ((7 < x0) & (x0 < 9))
x3 = x0[mask2]
y3 = y0[mask2]
print(x3, y3)
# (array([8]), array([7]))
|
how do we know the first 4 bytes read on a tcp socket are the length of the message?
Question: The ["Sending and receiving logging events across a
network"](https://docs.python.org/2/howto/logging-cookbook.html#sending-and-
receiving-logging-events-across-a-network) section of the python logging
cookbook demonstrates how a clients can send logs via a TCP session.
Log messages are pickled and sent to the server thanks to the [socket
handler](https://docs.python.org/2/library/logging.handlers.html#logging.handlers.SocketHandler).
The server then unpickle the messages and log them.
The code to get a message from the tcp socket is this one:
class LogRecordStreamHandler(SocketServer.StreamRequestHandler):
"""Handler for a streaming logging request.
This basically logs the record using whatever logging policy is
configured locally.
"""
def handle(self):
"""
Handle multiple requests - each expected to be a 4-byte length,
followed by the LogRecord in pickle format. Logs the record
according to whatever policy is configured locally.
"""
while True:
chunk = self.connection.recv(4)
if len(chunk) < 4:
break
slen = struct.unpack('>L', chunk)[0]
chunk = self.connection.recv(slen)
while len(chunk) < slen:
chunk = chunk + self.connection.recv(slen - len(chunk))
obj = self.unPickle(chunk)
record = logging.makeLogRecord(obj)
self.handleLogRecord(record)
# then, methods to handle the record, but that's not the interesting part
class LogRecordSocketReceiver(SocketServer.ThreadingTCPServer):
"""
Simple TCP socket-based logging receiver suitable for testing.
"""
allow_reuse_address = 1
def __init__(self, host='localhost',
port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
handler=LogRecordStreamHandler):
SocketServer.ThreadingTCPServer.__init__(self, (host, port), handler)
self.abort = 0
self.timeout = 1
self.logname = None
def serve_until_stopped(self):
import select
abort = 0
while not abort:
rd, wr, ex = select.select([self.socket.fileno()], [], [], self.timeout)
if rd:
self.handle_request()
abort = self.abort
What I don't understand in this example is: how do we know that the first 4
bytes we read from the socket constitute the length of the message? I looked
at the `socket`, and `logging` documentation but could not find mention of it.
Also, the docstring implicitly states that this code is not good enough for
production. What is so bad about that code?
Answer: As suggested in the comments, the answer is in the sending code (handlers.py
in python 2.7.10). I just removed the docstrings/comments that were obvious or
irrelevant to this question to make the code more readable.
def makePickle(self, record):
ei = record.exc_info
if ei:
dummy = self.format(record)
record.exc_info = None
d = dict(record.__dict__)
d['msg'] = record.getMessage()
d['args'] = None
s = cPickle.dumps(d, 1)
if ei:
record.exc_info = ei
# slen represents a "long integer", which is usually 32 bits large.
slen = struct.pack(">L", len(s))
# Here is where the 4 byte length is prepended to the message
return slen + s
def emit(self, record):
try:
s = self.makePickle(record)
# s is actually (length of the message) + (message)
self.send(s)
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)
def send(self, s):
"""
Send a pickled string to the socket.
This function allows for partial sends which can happen when the
network is busy.
"""
if self.sock is None:
self.createSocket()
if self.sock:
try:
if hasattr(self.sock, "sendall"):
self.sock.sendall(s)
else:
sentsofar = 0
left = len(s)
while left > 0:
sent = self.sock.send(s[sentsofar:])
sentsofar = sentsofar + sent
left = left - sent
except socket.error:
self.sock.close()
self.sock = None # so we can call createSocket next time
|
float random.uniform to 4 decimal places in python
Question: I am having problem rounding floating value to a decimal number greater than
1.
def float_generator(size=6, chars = 6):
return random.uniform(size,chars)
and i tried
target.write(str(float_generator(7,3)))
the above returns random float to 1 decimal num like 1.2222 , 1.333333 I want
to generate 7 decimal and 3 points as illustrated in the 7,3
i tried rounding off below. It round up the points instead .
target.write(str(format(float_generator(7,3),'.3f')))
Please how do i achieve 12345432.123 instead of 1.222343223 ? Any help would
be appreciated.
Answer: here is a solution for you:
import random
def float_generator(size = 6, chars = 6):
return round(random.uniform(10**(size-1),10**(size)), chars)
call it:
float_generator(7,3)
output example:
2296871.988
or better:
float_generator = lambda size, chars: round(random.uniform(10**(size-1),10**(size)), chars)
call it the same way.
|
Parsing a text file in python and outputting to a CSV
Question: Preface - I'm pretty new to Python, having had more experience in another
language.
I have a text file with single column list of strings in the generic (but
slightly varying) format "./abc123a1/type/1ab2_x_data_type.file.type"
I need to extract the abc123a1 and the 1ab2 portions from all several hundred
of the rows and put them under two columns (column a and b) in a csv.
Sometimes there may be a "1ab2_a" and a "1ab2_b", but I _only_ want one 1ab2.
So I'd want to grab "1ab2_a" and ignore all others.
I have the regex which I THINK will work:
tmp = list()
if re.findall(re.compile(r'^([a-zA-Z0-9]{4})_'), x):
tmp = re.findall(re.compile(r'^([a-zA-Z0-9]{4})_'), x)
elif re.findall(re.compile(r'_([a-zA-Z0-9]{4})_'), x):
tmp = re.findall(re.compile(r'_([a-zA-Z0-9]{4})_'), x)
if len(tmp) == 0:
return None
elif len(tmp) > 1:
print "ERROR found multiple matches"
return "ERROR"
else:
return tmp[0].upper()
I am trying to make this script step by step and testing things to make sure
it works, but it's just not.
import sys
import csv
listOfData = []
with open(sys.argv[1]) as f:
print "yes"
for line in f:
print line
for line in f:
listOfData.append([line])
print listOfData
with open('extracted.csv', 'w') as out_file:
writer = csv.writer(out_file)
writer.writerow(('column a', 'column b'))
writer.writerows(listOfData)
print listOfData
Still failing to get anything in the csv other than column headers, much less
a parsed version!
Does anyone have any better ideas or formats I could do this in? A friend
mentioned looking into glob.glob, but I haven't had luck getting that to work
either.
Answer: IMHO, you were not far from making it work. The problem is that you read once
the whole file just to print the lines, and then (once at end of file) you try
to put them into a list... and get an empty list !
You should read the file only once:
import sys
import csv
listOfData = []
with open(sys.argv[1]) as f:
print "yes"
for line in f:
print line
listOfData.append([line])
print listOfData
with open('extracted.csv', 'w') as out_file:
writer = csv.writer(out_file)
writer.writerow(('column a', 'column b'))
writer.writerows(listOfData)
print listOfData
once it works, you still have to use the regex to get relevant data to put
into the csv file
|
How do I display an image from an array in python
Question: I am trying to use PIL to display an image from an array. The array is a long
list of elements which are pixel values of an image. How do I display these
pixel values as an image ?
Answer: You don't specify what kind of data is in your list, so I assume it is an
array with 25 elements (grouped in 5 groups of 5), which will be converted to
a 5 by 5 black & white image.
from PIL import Image
import random
data = [
[1,0,0,1,0],
[1,1,1,0,0],
[1,1,0,1,0],
[1,0,1,1,0],
[0,1,1,0,1],
]
img = Image.new("1", (5, 5))
pixels = img.load()
for i in range(img.size[0]):
for j in range(img.size[1]):
pixels[i, j] = data[i][j]
img.show()
img.save("img.png")
This is similar to this question: [How can I write a binary array as an image
in Python?](http://stackoverflow.com/questions/32105954/how-can-i-write-a-
binary-array-as-an-image-in-python)
|
Python Pandas drop columns not found in both dataframes
Question: **Problem Setup** :
import pandas as pd
df1 = pd.DataFrame({'D': {0: 'D0', 1: 'D1', 2: 'D2', 3: 'D3'}, 'B': {0: 'B0', 1: 'B1', 2: 'B2', 3: 'B3'}, 'A': {0: 'A0', 1: 'A1', 2: 'A2', 3: 'A3'}, 'C': {0: 'C0', 1: 'C1', 2: 'C2', 3: 'C3'}})
df2 = pd.DataFrame({'E': {4: 'B4', 5: 'B5', 6: 'B6', 7: 'B7'}, 'D': {4: 'C4', 5: 'C5', 6: 'C6', 7: 'C7'}, 'F': {4: 'D4', 5: 'D5', 6: 'D6', 7: 'D7'}, 'C': {4: 'A4', 5: 'A5', 6: 'A6', 7: 'A7'}})
df1
A B C D
0 A0 B0 C0 D0
1 A1 B1 C1 D1
2 A2 B2 C2 D2
3 A3 B3 C3 D3
df2
C D E F
4 A4 C4 B4 D4
5 A5 C5 B5 D5
6 A6 C6 B6 D6
7 A7 C7 B7 D7
I'm trying to determine the best way to return a dataframe that contains ONLY
columns that appear in 2 OTHER dataframes.
I've come up with a solution but it's problematic because it will drop `any`
column that has `NaN`.
df3 = pd.concat([df1, df2])
A B C D E F
0 A0 B0 C0 D0 NaN NaN
1 A1 B1 C1 D1 NaN NaN
2 A2 B2 C2 D2 NaN NaN
3 A3 B3 C3 D3 NaN NaN
4 NaN NaN A4 C4 B4 D4
5 NaN NaN A5 C5 B5 D5
6 NaN NaN A6 C6 B6 D6
7 NaN NaN A7 C7 B7 D7
df3 = df3.dropna(axis=1)
#This is the correct result I'm going for
C D
0 C0 D0
1 C1 D1
2 C2 D2
3 C3 D3
4 A4 C4
5 A5 C5
6 A6 C6
7 A7 C7
Or as a one-liner:
df3 = pd.concat([df1, df2]).dropna(axis=1)
I have a feeling there's an easier way to return a dataframe containing only
the columns that are found in both two different dataframes (columns
intersection). More elegant approach?
Answer: You can use the [`intersection`](http://pandas.pydata.org/pandas-
docs/stable/generated/pandas.Index.intersection.html#pandas.Index.intersection)
of the 2 df columns:
In [177]:
cols = df1.columns.intersection(df2.columns)
cols
Out[177]:
Index(['C', 'D'], dtype='object')
In [178]:
pd.concat([df1[cols],df2[cols]])
Out[178]:
C D
0 C0 D0
1 C1 D1
2 C2 D2
3 C3 D3
4 A4 C4
5 A5 C5
6 A6 C6
7 A7 C7
|
Hook on arguments in argparse python
Question: I am interested in hook extra arguments parsed using argparse in one class to
another method in another class which already has few arguments parsed using
argparse module.
Project 1
def x():
parser = argparse.ArgumentParser()
parser.add_argument('--abc')
Project 2
def y():
parser = argparse.ArgumentParser()
parser.add_argument('--temp1')
parser.add_argument('--temp2')
When I run x(), I want to add the "--abc" argument to the list of argument y()
has which is "temp1", "temp2" at runtime. Is inheritance the best way to go
and defining the constructors accordingly ? Could someone provide some sample
code snippet ?
Thanks !
Answer: You can inspire yourself from Django's [management
commands](https://github.com/django/django/blob/master/django/core/management/base.py#L116).
They are basically setup as follow:
* The entry point is `run_from_argv` which calls `create_parser`, parse the command line, extract the parsed arguments and provide them to `execute`;
* The `create_parser` method creates an argparse parser and uses `add_argument` to prepopulate default options available for all commands. This function then calls the `add_arguments` method of the class which is meant to be overloaded by subclasses;
* The `execute` method is responsible to handle the various behaviours associated to the default options. It then calls `handle` which is meant to be overloaded by subclasses to handle the specific options introduced by `add_arguments`.
Your requirements are not completely clear but I think that in your case you
don't need to bother with an execute method. I’d go with:
import argparse
import sys
class BaseParser:
def create_parser(self, progname):
parser = argparse.ArgumentParser(prog=progname)
parser.add_argument('--temp1')
parser.add_argument('--temp2')
self.add_arguments(parser)
return parser
def add_arguments(self, parser):
pass # to be optionnally defined in subclasses
def parse_command_line(self, argv):
parser = create_parser(argv[0])
options = parser.parse_args(argv[1:])
parsed_options = vars(options)
self.handle(**parsed_options) # HAS TO be defined in subclasses
class X(BaseParser):
def add_arguments(self, parser):
parser.add_argument('--abc')
def handle(self, **options):
abc = options['abc']
temp1 = options['temp1']
temp2 = options['temp2']
# do stuff with thoses variables
class Y(BaseParser):
def handle(self, **options):
temp1 = options['temp1']
temp2 = options['temp2']
# do stuff
x = X()
y = Y()
args = sys.argv
x.parse_command_line(args)
y.parse_command_line(args)
You could simplify the code further if X is a subclass of Y.
|
Error when using multiple character in Python csv module
Question: I'm getting this:
with open(filename, 'rb') as csvfile:
rows = csv.reader(csvfile, delimiter=';;')
`delimiter` must be an 1-character string
is it possible to make it work with two characters?
Answer: No you cannot do it with the csv module, you could do update the file and
replace the `;;` with tabs or some common delimiter or you could use
[pandas.read_csv](http://pandas.pydata.org/pandas-
docs/stable/generated/pandas.read_csv.html):
import pandas as pd
df = pd.read_csv("test.csv",sep=";;")
print(df.A)
print(df.B)
print(df.C)
test.csv:
A;;B;;C
1;;2;;3
4;;5;;6
Output:
0 1
1 4
Name: A, dtype: int64
0 2
1 5
Name: B, dtype: int64
0 3
1 6
Name: C, dtype: int64
To get rows:
for _,row in df.iterrows():
print(row.values)
[1 2 3]
[4 5 6]
|
importing the module in python
Question: I am learning Python and while studying modules two doubts came to my mind.
* **Doubt #1:**
I know that module is just simply python file such as `filename.py`, but what
is a sub-module in Python?
* **Doubt #2:**
Consider the following three lines of code:
import modulename
from pkgname import modulename
from pkgname import *
Do all three statements use `__init__.py` (which is inside `pkgname` package)
or only the third statement?
Answer: To make things a bit more clearer about your second question.
* * *
When you do -
import packagename.modulename
or
from packagename import modulename
Python internally first imports `packagename` , and when I say python imports
`packagename` , I mean it imports the `__init__.py` of that package , and then
after that it imports `modulename` . This is the reason why when you do any of
the above it imports the `__init__.py` .
* * *
When you do -
from packagename import *
Please note, this does not import `modulename` from packagename by default ,
this would only import the `__init__.py` from packagename , and all modules
that you have listed in `__all__` list in `__init__.py` , if no modules are
listed in that list, none would be imported. Example -
Lets say I have
shared
-- __init__.py
-- a.py
`__init__.py` looks like -
print("In Shared")
`a.py` look like -
print("In A")
Now when in the directory above `shared` ,and openning python, if you do -
from shared import *
It would print out -
In Shared
But if you change that code in `__init__.py` to -
print("In Shared")
__all__ = ['a']
And do the same import from same location, It would print out -
In Shared
In A
As you can see it only imports submodules that are defined in the `__all__`
list.
* * *
Finally , when you do -
import modulename
Lets say you do that directly from within `packagename` , by changing the
directory to it and openning python interactive interpreter there. At that
time, you are not asking Python to import packagename for you, so it does not
need to import packagename , and hence it does not import `__init__.py` .
|
How to install Vowpal Wabbit python interface
Question: VW recently added a [python
interface](https://github.com/JohnLangford/vowpal_wabbit/tree/master/python),
however I am having trouble finding instructions for how to install it. If I
install VW from homebrew (brew install vowpal-wabbit) and I open python, and
call
`import pyvw`
I get an ImportError.
Answer: I was able to successfully install the Python interface to VW using the
following steps. Note that this is on an Ubuntu 14.04 machine with Anaconda
Python 2.7.10.
1. Prerequisites: Boost & miscellaneous Python development libraries:
sudo apt-get install libboost-all-dev
sudo apt-get install python-dev libxml2-dev libxslt-dev
2. `git clone` the [Vowpal Wabbit repo](https://github.com/JohnLangford/vowpal_wabbit) & enter the `python` directory.
3. `make` Vowpal Wabbit & test your installation using `python test.py`.
`import pyvw` should work from within a Python console as well.
|
Can't access Environment Variables Remote Server Django
Question: On my remote server, running Ubuntu 14.04, with server configuration: Django,
Nginx and Gunicorn, I can't access environment variables although set under
the right user and server restarted.
On my local box, I set the environment variables, and django can access during
startup and works nicely. On the remote server, although the environment
variables are in place, django complains of keyerror.
# from two scoops
import os
from django.core.exceptions import ImproperlyConfigured
def get_env_variable(var_name):
"""Get the environment variable or return exception"""
try:
return os.environ[var_name]
except KeyError:
error_msg = "Set the {} environment variable".format(var_name)
raise ImproperlyConfigured(error_msg)
On the server, the user running the django instance is the same user in which
the environment variables were set to.
Everything works on the local PC. On the remote machine, it doesn't. I've
restarted the server, still.
When I run `export` in terminal on the remote server, I get the list of
environment variables including what I customly set.
To confirm, i went into python to verify.
import os
os.environ['THE_CUSTOM_KEY']
>> returns the Key
If Django **is** Python, then what step am I missing, because python sees the
environment variables?
**Edit** : I set the variables in the `~/.profile` file of the user account.
My ~/.profile with the variables
# top part cut for brevity
export LOG_ECG_DB="name"
export LOG_ECG_EMAIL="[email protected]"
export LOG_ECG_EMAIL_PW="password"
export LOG_ECG_PW="password"
export LOG_ECG_SECRET="secret_key"
Answer: Eventually, below is how I solved the issue. Might help someone. Inspired by
example in two scoops
Steps in brief:
* Created a json file in ~/.env
* Lets settings.py read the json file upon load
* Keys from the file are used to fill in the sensitive parts
## created json file
I put the file in ~/.env of both my local and remote machine, with the content
{
"SECRET_KEY": "my_secret_key",
"DB": "db_name",
"USER": "db_user",
"USER_PW": "db_user_password",
"EMAIL": "[email protected]",
"EMAIL_PW": "password"
}
If your app isn't sending any emails, you might not need the last two lines in
the above snippet
## Read json
In my settings.py (or you could put into a utils.py file, whatever), I have
this snippet:
import json
from os.path import expanduser
from django.core.exceptions import ImproperlyConfigured
# with this, no need to hardcode
# home directory
home_directory = expanduser("~")
with open(home_directory + "/.env") as f:
secrets = json.loads(f.read())
def get_secret(setting, secrets=secrets):
"""Get the secret variable or return explicit exception."""
try:
return secrets[setting]
except KeyError:
error_msg = "Set the {0} environment variable".format(setting)
raise ImproperlyConfigured(error_msg)
## Fill in the pieces
Like so `SECRET_KEY = get_secret('SECRET_KEY')`
and so on..
|
Why is the command string not passed entirely from Python to system?
Question: My Python code is:
import os
targetdir = os.getenv('APPDATA')
command = "elev.cmd {0}\data\nssm.exe install service {1}\data\service.exe".format(targetdir,targetdir)
os.system(command)
I am completely fine with using `os.system`. `elev.cmd` generates UAC dialog
and elevates and executes everything what's passed to it.
But my suspect is that the arguments are passed to the command in two lines.
What is the reason for command line string being passed not completely in one
line?
Answer: Yes, you are not escaping your command string properly , so `\` is interpreted
as escape character, hence `\n` would get interpreted as newline, and not `\`
followed by `n`.
Prefix the string with `r` to make it raw-string, so that `\` does not act as
escape characters.
command = r"elev.cmd {0}\data\nssm.exe install service {1}\data\service.exe".format(targetdir,targetdir)
|
Python 3 name tuple position
Question: If I have the coordinate tuple `(10.1, 15.2)`, how can I make it so that I can
call `10.1` as simply `x` instead of `coordinates[0]`, and `y` instead of
`coordinates[1]`?
I want to do this so that I can pass a tuple from function to function while
still being able to call `x` and `y` easily. I could just:
x = coordinates[0]
y = coordinated[1]
but that seems like a bad idea -- lengthy and I'd have to repeat it for each
function.
Answer: Use
[namedtuple](https://docs.python.org/3.4/library/collections.html#collections.namedtuple):
> from collections import namedtuple
> c = namedtuple('Coords',['x','y'])
> xy = c(5,6)
> xy
=> Coords(x=5, y=6)
> xy.x
=> 5
> xy.y
=> 6
|
Handle multiple questions for Telegram bot in python
Question: I'm programming a telegram bot in Python using the Telegram bot API. I'm
facing the problem of managing questions that need an answer of the user. The
problem arises when the program is waiting for an answer of one user and
another user request information or ask another question **before** the first
user responds.
The Telegram API uses a code to handle the request. When you ask for updates
you include a code. If the code you send is higher than a request code, it is
mark as handled and telegram delete it and no longer appears in the updates.
This code is sequential, so if you mark update 3 as handled, updates 1 and 2
are erased as well.
The question is **why is the best phytonic/elegant way to handle multiple
requests that needs an answer for the users?**
Answer: There is not a most pythonic way of doing this. It is a problem you have to
_program_ to solve.
Basically, you have to maintain some state variables concerning each user.
When a new message arrives, the bot checks what state that user is in, and
responds accordingly.
Suppose you have a function, `handle(msg)`, that gets called for each arriving
message:
user_states = {}
def handle(msg):
chat_id = msg['chat']['id']
if chat_id not in user_states:
user_states[chat_id] = some initial state ...
state = user_states[chat_id]
# respond according to `state`
This will do for a simple program.
For more complicated situations, I recommend using
**[telepot](https://github.com/nickoala/telepot), a Python framework I have
created for Telegram Bot API**. It has features that specifically solve this
kind of problems.
For example, below is a bot that counts how many messages have been sent by an
individual user. If no message is received after 10 seconds, it starts over
(timeout). The counting is done _per chat_ \- that's the important point.
import sys
import telepot
from telepot.delegate import per_chat_id, create_open
class MessageCounter(telepot.helper.ChatHandler):
def __init__(self, seed_tuple, timeout):
super(MessageCounter, self).__init__(seed_tuple, timeout)
self._count = 0
def on_message(self, msg):
self._count += 1
self.sender.sendMessage(self._count)
TOKEN = sys.argv[1] # get token from command-line
bot = telepot.DelegatorBot(TOKEN, [
(per_chat_id(), create_open(MessageCounter, timeout=10)),
])
bot.notifyOnMessage(run_forever=True)
Run the program by:
python messagecounter.py <token>
[Go to the project page](https://github.com/nickoala/telepot) to learn more if
you are interested. There are a lot of documentations and non-trivial
examples.
|
What topics (basics or foundations or fundamentals or what) to learn/study before studying K&R's "The C Programming Language"?
Question: I don't know programming, I don't know any programming language (only some
HTML if it can be called programming language). I only studied Petzold's
"CODE" so far just to learn basics.
I decided to learn basics and (at least) some C first (even if some suggest
JS, Python or other languages first).
To learn C, people often suggest studying K&R's book "The C Programming
Language" after learning basics of programming. (Even in the book they say
that the book is not for beginners)
People often sat "it's important to learn basics/fundamental/foundations
first" and stress about basics and foundations without telling what they are.
**Basics basics basics. . . foundations foundations foundations. . . what
topics, concepts, etc. do the basics (or foundations or fundamemtals or what
they call it) involve?**
NOTE: I don't ask for book or course recommendation, but I ask for what
topics/concepts to learn to get a foundation.
Answer: Hell, raw theory is boring and that's not what programming is!
I'm not expecting _anyone_ who's learning to program to study _raw and crude_
theory first. The best way you can learn is by trail-and-return-non-zero,
trail-and-SIGSEGV, and some day, trail-and-return-zero.
Anyway, if you already have some knowledge of algebra, electronics, or even
some computer science, that'll definitely help you, **But** , if you don't
know something like that, _don't_ learn it just for the sake of preparation.
It's pretty debatable whether HTML is a programming language, but anyway,
you'll enter in another world/dimension/universe/existence by learning C.
The C language is, IMHO, a very neat language. May it not be as flexible (and
thus, dirty) as C++, but it's neat and elegant. It's simple. Once you know C,
and can read/write it fluently, you could even (more or less) understand parts
of the [Linux kernel](https://en.wikipedia.org/wiki/Linux_kernel) for example.
You mentioned both Javascript and Python. I wouldn't go with Javascript unless
you're of those impure people who want to learn programming just for a job,
and not for entertainment/fun, _which is the real magic and beatifulness
behind it!_ Python would be something I would recommend, but you already know
C is somewhat harder, and you want to go that way, so go that way!
I'm not sure how much to recommend to you K&R. It was never updated after ANSI
C (a standard from _1988-90_!). That makes it pretty outdated (the latest C
standard is from 2011, and the previous one was from 1999 (without C99 you'll
experiment hell sooner or later)). Many (and I mean _too much_) people has
though of _The C Programming Language_ as "being the authoritative reference
for C", because it was (in part) written by [Dennis MacAlistair Ritchie
(1941-2011)](https://en.wikipedia.org/wiki/Dennis_Ritchie), or in other words,
the Messiah and Creator of C, who came to save us from
[Fortran](https://en.wikipedia.org/wiki/Fortran).
Although some other answer may better answer you which books may be
recommended (I can't, because I wasn't taught by books, but by Google), I hope
this answer will give some light on what you should do. Happy programming :)!
|
Tk Canvas Usage in Python
Question: There is a post of this code, posted by mgilson, that I don't understand. All
up to the reference to `big_widget` makes sense. But, what does the reference
to `big_widget` contribute? The particular post [is
here](https://stackoverflow.com/questions/14846063/what-is-a-better-tkinter-
geometry-manager-than-grid). I am trying to refine my code and, I think, use
the `Frame` object. But, the reference to `Canvas` threw me. I tried to
comment but I need 50+ reputation to do so. Not there yet.
import Tkinter as Tk
root = Tk.Tk()
f = Tk.Frame(root)
f.grid(row=0,column=0)
#place buttons on the *frame*
b1 = Tk.Button(f,text="Button1")
b1.grid(row=0,column=0)
b2 = Tk.Button(f,text="Button2")
b2.grid(row=0,column=1)
big_widget = Tk.Canvas(root)
big_widget.grid(row=1,column=0) #don't need columnspan any more.
Answer: > big_widget = Tk.Canvas(root) \--> A Canvas object is initialized, anchored
> to root and assigned to big_widget
The next line places the canvas (big_widget) at row=1 column=0 on the grid
(in the same way, a frame (f) was previously initialized and placed at row=0
column=0 on the grid inside root)
|
uwsgi installation error in windows 7
Question: Trying to install uwsgi according to [documentation.](http://uwsgi-
docs.readthedocs.org/en/latest/tutorials/Django_and_nginx.html) I'm getting
the below error on Windows 7.
What should I do?
(uwsgi-tutorial) C:\Users\Home\Videos\uwsgi-tutorial\mysite>pip install uwsgi
Collecting uwsgi
Using cached uwsgi-2.0.11.1.tar.gz
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 20, in <module>
File "c:\users\home\appdata\local\temp\pip-build-04g1m6\uwsgi\setup.py", line 3, in <module>
import uwsgiconfig as uc
File "uwsgiconfig.py", line 8, in <module>
uwsgi_os = os.uname()[0]
AttributeError: 'module' object has no attribute 'uname'
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in c:\users\home\appdata\local\temp\pip-build-04g1m6\uwsgi
Answer: uWSGI can be compiled on Windows only using cygwin. There is no such thing as
uname in normal Windows console, but it exists inside cygwin. If you're
already in cygwin console, try to run `uname` command, if that exists, check
if `os.uname()` in python inside cygwin is also working.
|
ValueError: invalid shape for input data points in griddata operation
Question: I am running into an error when using scipy.interpolate.griddata. My goal is
to prepare data for contouring using matplotlib. I have read that the best way
to perform this is to separate the x any y as 1D arrays using linspace before
passing to griddata.
The min and max values of my x and y values are used to input into the
linspace, so as to keep the co-ordinates the same for GIS mapping purposes
(not sure if this is necessary to have the data points in the same xy area as
the grid co-ordinates, but am doing so any way)
The file Watertable CSV is imported as a numpy array with x,y and z values.
The z is supplied to griddata as a straight array column index.
I am running into the error "valueError: invalid shape for input data points"
I am sure it is something very simple and hopefully someone can shed light on
my error.
[EDIT]
I have linked the csv file using pastebin as suggested:
<http://pastebin.com/nj7THgMw>
import numpy as np
from scipy.interpolate import griddata
from numpy import genfromtxt
my_data = genfromtxt('WaterTable.csv', delimiter=',')
x = my_data[1:,0:1]
y = my_data[1:,1:2]
z = my_data[1:,2:3]
xmax = max(x)
xmin = min(x)
ymax = max(y)
ymin = min(y)
xi = np.linspace(xmin, xmax, 2000)
yi = np.linspace(ymin, ymax, 2000)
zi = griddata((x, y), z, (xi, yi), method='cubic')
I script then exits with the following error:
Traceback (most recent call last):
File "C:/Users/Hp/PycharmProjects/GISdev/Irregular_Grid03.py", line 60, in <module>
zi = griddata((x, y), z, (xi, yi), method='cubic')
File "C:\Python27\lib\site-packages\scipy\interpolate\ndgriddata.py", line 212, in griddata
rescale=rescale)
File "scipy/interpolate/interpnd.pyx", line 840, in scipy.interpolate.interpnd.CloughTocher2DInterpolator.__init__ (scipy\interpolate\interpnd.c:9961)
File "scipy/interpolate/interpnd.pyx", line 78, in scipy.interpolate.interpnd.NDInterpolatorBase.__init__ (scipy\interpolate\interpnd.c:2356)
File "scipy/interpolate/interpnd.pyx", line 123, in scipy.interpolate.interpnd.NDInterpolatorBase._check_init_shape (scipy\interpolate\interpnd.c:3128)
ValueError: invalid shape for input data points
Answer: Your arrays `x`, `y` and `z` are _two-dimensional_ , with shape `(n, 1)`.
`griddata` expects _one-dimensional_ arrays (i.e. with shape `(n,)`).
To fix this, use a single index instead of a slice in the second index
position when you pull the arrays out of `my_data`:
x = my_data[1:, 0]
y = my_data[1:, 1]
z = my_data[1:, 2]
|
Replace "&&" with "and" using re.sub in python.
Question: I have a string containing `&&`.
I want to replace all `&&` which have **SPACE** on both right and left side.
**Sample String** :
x&& &&& && && x
**Desired Output** :
x&& &&& and and x
**My Code** :
import re
print re.sub(r'\B&&\B','and','x&& &&& && && x')
**My Output**
x&& and& and and x
Please suggest me, how can I prevent `&&&` from getting replaced with `and&`.
Answer: You can search using this lookaround regex:
(?<= )&&(?= )
and replace by `and`
**Code:**
p = re.compile(ur'(?<= )&&(?= )', re.IGNORECASE)
test_str = u"x&& &&& && && x"
result = re.sub(p, "and", test_str)
[RegEx Demo](https://regex101.com/r/gX7wY0/5)
|
Saving bitarrays in MongoDB
Question: I'm building Bloom filters at my company and need to serialize and save them
into a MongoDB. The document structure I'm currently using looks like this:
{
'_id': unique ID,
'm': number of bits in Bloom filter,
'n': capacity of Bloom filter,
'k': number of hashes,
'bitarray': a string of the Bloom filter’s bitarray,
'seeds': a list of seeds for the k hashes
}
As you can see, the bitarray is currently represented as a string and Bloom
filter bitarrays can get _huge_ for a larger capacity. A single document in my
database is around **5 megabytes** right now which is terrible.
If it helps in anyway, I am programming in Python and using PyMongo as an
adapter.
I certainly believe this is not the right way to save bitarrays and I can't
find help elsewhere on the internet. Help me out please.
Answer: I figured out I could use the BSON binary data type to get my work done. To
serialize my Bloom filter objects, I did this:
from bson.binary import Binary
obj = BloomFilter()
serialized = obj.__dict__.copy()
serialized['bitarray'] = Binary(obj.bitarray.tobytes())
Please note that bitarray is the Python
[bitarray](https://pypi.python.org/pypi/bitarray/) library and not
`BitString`. The final dictionary `serialized` was easy to insert into a
MongoDB.
Hope this helps out anyone looking for this. Cheers :)
|
How do I replace a class variable for the duration of a single test in Python?
Question: I'm trying to test a cache class where old items should be automatically
deleted. The amount of items the cache can hold is controlled by a "constant"
class variable like this:
class Cache(dict):
MAX_ITEMS = 100
For testing purposes I would like to change that constant for the duration of
a single test case. Using `unittest.mock.patch` I could replace the class
variable with a `MagicMock` but that's not really what I'm trying to do. I
just need to replace it with a different number.
Is there an elegant way to do this in Python (like `patch`), or should I just
reset the variable myself on `tearDown`?
* * *
I'm using Python 3.4.3
Answer: patch can do this already. try:
from unittest.mock import patch
class A:
val = 1
assert A.val == 1
with patch.object(A, "val", "patched_value"):
assert A.val == "patched_value"
assert A.val == 1
Of course you can use `patch.object` as a decorator as well.
|
Extracting data from .rsa files
Question: I have a folder labeled cstruct with several with 20,000 .rsa files. In each
of the files I need to extract each row that contain cys values and write the
to a new file. Is there a way in python to loop through these files in this
folder and extract this information?
RES SER A 102 17.74 15.2 17.22 22.0 0.52 1.4 11.89 24.5 5.85 8.6 RES HIS A 103
17.32 9.5 16.53 11.2 0.78 2.2 12.22 12.6 5.10 5.9 **RES CYS A 104 0.00 0.0
0.00 0.0 0.00 0.0 0.00 0.0 0.00 0.0** RES LEU A 105 8.67 4.9 8.67 6.1 0.00 0.0
8.67 6.1 0.00 0.0 RES LEU A 106 5.72 3.2 5.72 4.1 0.00 0.0 5.72 4.0 0.00 0.0
Answer: Something like the following Python script should get you going in the right
direction:
import re, glob
with open("output.txt", "w") as f_output:
for rsa_file in glob.glob(r"cstruct\*.rsa"):
with open(rsa_file, "r") as f_input:
f_output.write(rsa_file + "\n")
for row in f_input:
for cys in re.findall(r"(RES CYS\s+\w+.*?)(?= RES|\Z)", row):
f_output.write(cys+"\n")
|
Does converting an interpreted script to an executable increase speed?
Question: In general I'm curious, does using a utility that converts a non-exe to an exe
increase speed? It's my understanding that they just package the interpreter
inside the exe.
In specific, if you have a python script and use py2exe on it, does the
resulting executable run faster than the .py? My boss seems to have the
assumption it does but I'm not so sure.
Especially when dealing with multiple modules. For example say you have
modules `first.py` and `second.py`. You compile them all to executables. When
they were .py they `second.py` could be called as
from second import main
main()
Now that they're executables you have to start a new process, which surely is
slower?
`subproccess.call(["second.exe"], shell=True)`
Do I understand this correctly? Or does `import`ing from another python module
actually start a new instance of the python interpreter or something?
In our case the target platform is always Windows.
Answer: Your boss is misinformed. All py2exe does is package your program into a self-
contained package capable of running without dependencies. It is still the
same bytecode running on the same interpreter (well, whatever one is
packaged).
See [this other answer](http://stackoverflow.com/a/2830413/1798683) for about
all of the "optimization" you can get out of using -o flags.
Also, yes, definitely run some benchmarks to confirm for yourself.
|
ValuError using import function in class
Question: I'm sure there's a simple explanation for this (beyond just that I'm new to
Python), but let's say I have two file in the same directory. One is this
little script in a file named `lexicon.py` that checks user input:
def string_checker3(action):
try:
check = isinstance(action, basestring)
if check:
return True
else:
raise ValueError
except ValueError:
print "We need a string here!"
return None
def Chipcar_testgreeting(action):
action_split = action.split()
for i in action_split:
strcheck = string_checker3(action)
if strcheck == None:
StartGame
else:
pass
The other script, my main script, is called `newGame.py` and has a class like
this, within which I would like to call the `Chipcar_testgreeting(action)`
function.
from lexicon import *
class ChipCar(Scene):
def enter(self):
print "What's up mothafucka! Get in the Bran Muffin car!"
action = raw_input("> ")
user_test = lexicon.Chipcar_testgreeting(action)
user_test
if(action == "shut up chip" or action == "oh no, it's chip"):
print "forget you!"
print action
return next_scene('Your_death')
#return 'Death'
elif(action == "hi chip" or action == "hello chip"):
print "What's up?!?! Let's go to O&A..."
return next_scene('Chip_in_studio')
else:
print "what's wrong with ya are ya stupid or sumptin? Let's go to my mudda's house, I think Lamar's there..."
return next_scene('Chip_mom_house')
FirstScene = ChipCar()
StartGame = FirstScene.enter()
However, I get this error now:
user_test = lexicon.Chipcar_testgreeting(action)
NameError: global name 'lexicon' is not defined
What am I doing wrong?
Answer: As you wrote `from lexicon import *`, all the importable names from that
module are available to you directly (in other words, you don't need
`lexicon.` anymore).
If you write `import lexicon`, now you have only imported the `lexicon` name
into your module, and you need to use it and the scope-resolution operator
(that's the `.`) to get to the other names of objects inside that module. In
this case, you can use `lexicon.Chipcar_testgreeting(action)`.
So, either replace `from lexicon import *` with `import lexicon`, or change
`lexicon.Chipcar_testgreeting(action)` to `Chipchar_testgreeting(action)`.
**The recommended option is to use`import lexicon`**.
* * *
Once you sort that out, you need to resolve another major issue which is this:
if strcheck == None:
StartGame
else:
pass
Not sure what do you expect `StartGame` to do here, since there is nothing
with this name in the `lexicon.py` module.
|
Find if point inside polygon on google maps using python
Question: I would like to know if I can use google maps api to check if a point (lat,
long) is within a given polygon (list of vertices) via the back-end using
python or i will have to compulsory write a python algo for that.
Answer: I don't think there is a straightforward way of doing this using Google Map
API and Python.
If you have the point and polygon coordinates available, it will certainly be
easier doing this using the Python library
[Shapely](https://pypi.python.org/pypi/Shapely). Here is an example code using
Shapely:
from shapely.geometry import Point, Polygon
pt = Point(0.75, 0.25)
poly = Polygon([(0, 0), (1, 1), (1, 0)])
poly.contains(pt)
|
how to apply binary search in python on sorted list of string elements?
Question: I have a sorted list of string elements(names of cities) and I would like to
implement binary search on this and filter out cities by giving initial
letters?
for example input by user: <http://127.0.0.1:8000/api/?city=New>
So here in this case I need to find out cities starting from New
Sample Output:
[
"New Abbey|Ceredigion|United Kingdom",
"New Albany|Indiana|United States",
"New Albany|Kansas|United States",
"New Albany|Mississippi|United States",
"New Albany|Ohio|United States"
]
Please advise.
Answer: The following approach should work. It uses Python's own binary search library
called `bisect` to find the initial index into you list. For the search term
`New` it returns 2 for my example list. `itertools.takewhile` can then be used
to return entries until your search term fails:
import bisect, itertools
locations = [
"Aaaa|aaaa|Test",
"Bbbb|bbbb|Test",
"New Abbey|Ceredigion|United Kingdom",
"New Albany|Indiana|United States",
"New Albany|Kansas|United States",
"New Albany|Mississippi|United States",
"New Albany|Ohio|United States",
"Zzzz|zzzz|Test"
]
search = "New"
start_index = bisect.bisect_left(locations, search)
print list(itertools.takewhile(lambda x: x.startswith(search), itertools.islice(locations, start_index, None)))
Giving the following output:
['New Abbey|Ceredigion|United Kingdom', 'New Albany|Indiana|United States', 'New Albany|Kansas|United States', 'New Albany|Mississippi|United States', 'New Albany|Ohio|United States']
|
Snake problems - Movement
Question: I am having some issues with my code in python, I am making a version of
snake, my issue concerns the movement of the snake itself. I have gotten the
directions working fine, I just need to make it so that the snake continues
moving in the direction it has been told to do so via the key press, I also
need to make it so that it is the one block, currently it shows all previous
blocks once it has been moved.
import pygame, sys, time, random
from pygame.locals import *
pygame.init()
size = width,height = 480, 480 #16x30,16x30
grey = (128,128,128)
screen = pygame.display.set_mode(size)
icon = pygame.image.load('snakeIcon.png')
newDir = 0
prevDir = 0
FPS = 8
xCoord = 10.0
yCoord = 10.0
#Main Program:
pygame.display.set_caption('Anthony\'s Snake')
pygame.display.set_icon(icon)
screen.fill(grey)
fpsTime = pygame.time.Clock()
gameB = pygame.image.load('gameB.png')
border = {}
createLvl()
snakeH = pygame.image.load('snakeH.png')
snake = {}
refreshScreen()
keyCheck = {'LEFT':bool(0), 'RIGHT':bool(0), 'UP':bool(0), 'DOWN':bool(0), 'ESC':bool(0)}
pygame.mixer.music.load('retroMusik.mp3')
pygame.mixer.music.set_volume(0.5)
pygame.mixer.music.play(-1)
while bool(1):
for i in range(1):
snake[str(len(snake))]=snakeH.get_rect()
x = xCoord
y = yCoord
for i in range(len(snake)):
snake[str(i)].x = x*16
snake[str(i)].y = y*16
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_UP :
keyCheck['UP'] = bool(1)
if event.key == K_DOWN :
keyCheck['DOWN'] = bool(1)
if event.key == K_LEFT :
keyCheck['LEFT'] = bool(1)
if event.key == K_RIGHT :
keyCheck['RIGHT'] = bool(1)
if event.key == K_ESCAPE :
keyCheck['ESC'] = bool(1)
if event.type == KEYUP:
if event.key == K_UP :
keyCheck['UP'] = bool(0)
elif event.key == K_DOWN :
keyCheck['DOWN'] = bool(0)
elif event.key == K_LEFT :
keyCheck['LEFT'] = bool(0)
elif event.key == K_RIGHT :
keyCheck['RIGHT'] = bool(0)
elif event.key == K_ESCAPE :
keyCheck['ESC'] = bool(0)
if keyCheck['UP']:
if prevDir != 'DOWN':
newDir = 'UP'
print('Direction changed to UP')
if keyCheck['DOWN']:
if prevDir != 'UP':
newDir = 'DOWN'
print('Direction changed to DOWN')
if keyCheck['LEFT']:
if prevDir != 'RIGHT':
newDir = 'LEFT'
print('Direction changed to LEFT')
if keyCheck['RIGHT']:
if prevDir != 'LEFT':
newDir = 'RIGHT'
print('Direction changed to RIGHT')
prevDir = newDir
if keyCheck['UP'] == bool(1):
yCoord -= 1
if keyCheck['DOWN'] == bool(1):
yCoord += 1
if keyCheck['LEFT'] == bool(1):
xCoord -= 1
if keyCheck['RIGHT'] == bool(1):
xCoord += 1
refreshScreen()
fpsTime.tick(FPS)
Please be soft on me, I am still new to this. Thank you in advance.
Answer: I think your animation doesn't work right because you don't erase (cover with
background) the screen before drawing. See
[this](http://www.pygame.org/docs/tut/MoveIt.html) Pygame tutorial for slow
and detailed explanation.
Don't use `bool(1)`. Use `True` and `False`.
I'm not sure but I think the problem with the snake not moving is either A)
you reset your control/movement variable or B) you don't check it every
"round"/frame.
I'd really recommend finding some tutorial (or something) and read some Python
code by other people, your code could use a lot of improvement (this isn't
_bad_ , the important thing is trying to improve).
|
Python:Why readline() function doesn't work for file looping
Question: I have the following code:
#!/usr/bin/python
f = open('file','r')
for line in f:
print line
print 'Next line ', f.readline()
f.close()
This gives the following output:
This is the first line
Next line
That was the first line
Next line
Why doesn't the readline() function works inside the loop? Shouldn't it print
the next line of the file?
I am using the following file as input
This is the first line
That was the first line
Answer: You are messing up the internal state of the file-iteration, because for
optimization-reasons, iterating over a file will read it chunk-wise, and
perform the split on that. The explicit `readline()`-call will be confused by
this (or confuse the iteration).
To achieve what you want, make the iterator explicit:
import sys
with open(sys.argv[1]) as inf:
fit = iter(inf)
for line in fit:
print "current", line
try:
print "next", fit.next()
except StopIteration:
pass
|
antlr return values as key-value
Question: I want to parse the sentence `"i am looking for a java developer from india"`.
The output i need is language=java and place=india
I created a grammar file as follows.
grammar Job;
eval returns [String value]
: output=jobExp {System.out.println($output.text); $value = $output.text;}
;
jobExp returns [String value]
: ind=indro whitespace var1=language ' developer from ' var2=place
{
System.out.println($var1.text);
System.out.println($var2.text);
$value = $var1.text+$var2.text; }
;
indro
:
'i am looking for a'
|
'i am searching for a'
;
language :
'java' | 'python' | 'cpp'
;
place :
'india' | 'america' | 'africa'
;
whitespace :
(' '|'\t')+
;
inside `jobExp` i am getting the values for `place` and `language`. And I am
just returning only those two variables. But in `eval` i am getting the whole
sentence(i am looking for a java developer from india). What should i need to
get the exact matching output in `eval` ? Is it possible to get the output as
`json` or `hashMap` in `antlr`?
My `java` class for testing the grammar as follows:
import org.antlr.runtime.*;
public class JobTest {
public static void main(String[] args) throws Exception {
ANTLRStringStream in = new ANTLRStringStream("i am looking for a java developer from india" );
JobLexer lexer = new JobLexer(in);
CommonTokenStream tokens = new CommonTokenStream(lexer);
JobParser parser = new JobParser(tokens);
System.out.println(parser.eval()); // print the value
}
}
Answer: You can have a `@header` block in your grammar to add it to the generated
parser file.
grammar Job;
@header {
import java.util.HashMap;
}
You can further on your grammar file use the `HashMap` class just as you're
using `String`.
There's also the `@members` block to define private fields of the parser. You
can check an example using both blocks to define an expression evaluator in
[this
tutorial](https://theantlrguy.atlassian.net/wiki/display/ANTLR3/Expression+evaluator).
|
difference in russian language pack between OSX and Ubuntu, how to get the same output for strftime?
Question: I am running into an issue with the use of Russian dates in python.
When I run the following on a local OSX virtualenv with python 2.7.9:
import locale
import datetime
locale.setlocale(locale.LC_ALL, 'ru_RU.UTF-8')
temp = datetime.date(2015, 8, 11)
print temp.strftime("%d %B %Y")
The output is:
11 августа 2015
When I run almost the same code on an Ubuntu server in a virtualenv with
python 2.7.9:
import locale
import datetime
locale.setlocale(locale.LC_ALL, 'ru_RU.UTF-8')
temp = datetime.date(2015, 8, 11)
print temp.strftime("%d %B %Y")
The output is different
11 Август 2015
Where does this difference come from and is there a way to force one
implementation over the other?
When using strptime this difference is causing errors when the wrong
implementation is used since the formats do not match.
Answer: I have the same case with `strftime` on OSx and Ubuntu. I solve it with
`django.utils.formats`:
import datetime
from django.utils import formats
temp = datetime.date(2015, 8, 11)
print formats.date_format(temp, 'DATE_FORMAT')
There are some default date formats like 'DATE_FORMAT',
'SHORT_DATETIME_FORMAT', but you also can define your own format in Settings.
|
Making Python run a few lines before my script
Question: I need to run a script `foo.py`, but I need to also insert some debugging
lines to run before the code in `foo.py`. Currently I just put those lines in
`foo.py` and I'm careful not to commit that to Git, but I don't like this
solution.
What I want is a separate file `bar.py` that I don't commit to Git. Then I
want to run:
python /somewhere/bar.py /somewhere_else/foo.py
What I want this to do is first run some lines of code in `bar.py`, and then
run `foo.py` as `__main__`. It should be in the same process that the `bar.py`
lines ran in, otherwise the debugging lines won't help.
Is there a way to make `bar.py` do this?
Someone suggested this:
import imp
import sys
# Debugging code here
fp, pathname, description = imp.find_module(sys.argv[1])
imp.load_module('__main__', fp, pathname, description)
The problem with that is that because it uses import machinery, I need to be
on the same folder as `foo.py` to run that. I don't want that. I want to
simply put in the full path to `foo.py`.
Also: The solution needs to work with `.pyc` files as well.
Answer: You can use
[`execfile()`](https://docs.python.org/2/library/functions.html#execfile) if
the file is `.py` and
[uncompyle2](https://github.com/wibiti/uncompyle2/blob/master/scripts/uncompyle2)
if the file is `.pyc`.
Let's say you have your file structure like:
test|-- foo.py
|-- bar
|--bar.py
**foo.py**
import sys
a = 1
print ('debugging...')
# run the other file
if sys.argv[1].endswith('.py'): # if .py run right away
execfile(sys.argv[1], globals(), locals())
elif sys.argv[1].endswith('.pyc'): # if .pyc, first uncompyle, then run
import uncompyle2
from StringIO import StringIO
f = StringIO()
uncompyle2.uncompyle_file(sys.argv[1], f)
f.seek(0)
exec(f.read(), globals(), locals())
**bar.py**
print a
print 'real job'
And in `test/`, if you do:
$ python foo.py bar/bar.py
$ python foo.py bar/bar.pyc
Both, outputs the same:
debugging...
1
real job
Please also see this [answer](http://stackoverflow.com/a/32261548/547820).
|
Reading json in pythonanywhere flask app
Question: First I have seen [this
question](http://stackoverflow.com/questions/25464539/flask-app-on-
pythonanywhere-python-json-decode-error). My problem is I have a flask app
running on pythonanywhere that reads info from a json file in the same
directory on the server, and get the following error: `Internal Server
Error:The server encountered an internal error and was unable to complete your
request. Either the server is overloaded or there is an error in the
application.`.
I simplified the app down to:
from flask import Flask
import json
app = Flask(__name__)
@app.route('/')
@app.route('/index')
def index():
return 'Index'
@app.route('/courses')
def courses():
with open('courses.json', 'r') as f:
these_courses = json.load(f)
return str(these_courses)
If I go to the index page I see index, as expected, but if I try to go to
`/courses` then I get the error.The whole things runs fine on `localhost`,
then with the same code I get an error on the server, so I know reading from
the file works fine. This makes me think it might be a problem unique to json
combined with pythonanywhere.
Edit: Perhaps a problem with the path name for `courses.json`, but it's in the
same directory so I feel like it should be fine, just a thought
Answer: Turns out it was a pathname problem. I guess on files need to be routed from
the root directory.
I ran:
def courses():
my_dir = os.path.dirname(__file__)
json_file_path = os.path.join(my_dir, 'courses.json')
return json_file_path
to find the path, then changed the function to:
def courses():
with open('/home/username/path/to/file/courses.json', 'r') as f:
these_courses = json.load(f)
return str(these_courses)
and now it worked :D
Then to make a better version that doesn't break when you move the project I
did it like this:
def courses():
my_dir = os.path.dirname(__file__)
json_file_path = os.path.join(my_dir, 'courses.json')
with open(json_file_path, 'r') as f:
these_courses = json.load(f)
return str(these_courses)
|
Updating a line of text in Python 3
Question: I want to update a line of text, so that I don't have too many lines of
output. Look at an installer program for an example:
Instead of...
> Installation status: 1%
>
> Installation status: 2%
>
> Installation status: 3%
>
> ...
... I want the same line to update every time the percentage changes.
I already found a way to do so (well, it's actually tricking the user), but it
is kind of bad, because all the lines from above disappear. I'm talking about
importing 'os' and then doing 'os.system("clear")'.
Is there a better way of doing so?
BTW: I'm talking about a few hundred changes per second. The installer is just
an example.
Answer: Use the appendage `\r` and then `sys.stdout.flush()`
To continue to use the installer example:
import sys
import time
for i in range(100):
sys.stdout.write("\rInstallation Progress: %d percent" % i)
time.sleep(.05)
sys.stdout.flush()
Happy coding!
EDIT--I used % to represent percent completed. The result was an incomplete
placeholder. My apologies!
|
from matplotlib.backends import _tkagg ImportError: cannot import name _tkagg
Question: While trying to run
[this](http://matplotlib.org/examples/user_interfaces/embedding_in_tk.html)
example to test how matplotlib works with Tkinter, I am getting the error:
(env)fieldsofgold@fieldsofgold-VirtualBox:~/new$ python test.py
Traceback (most recent call last):
File "test.py", line 7, in <module>
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
File "/home/fieldsofgold/new/env/local/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py", line 13, in <module>
import matplotlib.backends.tkagg as tkagg
File "/home/fieldsofgold/new/env/local/lib/python2.7/site-packages/matplotlib/backends/tkagg.py", line 7, in <module>
from matplotlib.backends import _tkagg
ImportError: cannot import name _tkagg
Using the solution provided
[here](http://stackoverflow.com/questions/13110403/matplotlib-backend-missing-
modules-with-underscore), I've tried to uninstall matplotlib and install the
tk and tk-dev packages by using these commands :
sudo apt-get install tk8.5
sudo apt-get install tk-dev
and then re-installing matplotlib again by `pip install matplotlib` but I am
still getting the same error. Any help would be appreciated. I am using Ubuntu
14.04 on VirtualBox and working inside a virtualenv environment. Thanks so
much.
Answer: I just ran into this (Ubuntu 15.10 but same idea) and fixed it by:
sudo apt-get install tk-dev
pip uninstall -y matplotlib
pip --no-cache-dir install -U matplotlib
I think the third step was the critical one; if the cache is permitted then
`pip` appeared to be just using the previously-built installation of
`matplotlib`.
You can also manually remove the previously-built matplotlib; on Ubuntu it
lives in `~/.cache/pip` somewhere. (I couldn't find a way for pip to clean up
its cache unfortunately.)
|
Python subprocess.check_output, with pipeline
Question: I'm trying to get output of
dmesg | grep -i 'bios'
I've tried this:
dmsg = subprocess.check_output("dmesg | grep -i 'bios'").decode('utf-8')
, but I'm getting an error.
How can I obtain a full `sdtoutput` message?
Answer:
import subprocess
p1 = subprocess.Popen(['dmesg'], stdout=subprocess.PIPE)
p2 = subprocess.Popen(['grep', '-i', 'bios'], stdin=p1.stdout, stdout=subprocess.PIPE)
p1.stdout.close()
out, err = p2.communicate()
print(out)
|
Threading using pool and map function
Question: Ok so I want to build an app that uses para threads. So I thought Id
understand the threading first. I found this
[example](http://chriskiehl.com/article/parallelism-in-one-line/), for the
life of me I cant work out why Im not getting any results back. It doesnt
throw any exceptions or anything it just runs and then finishes. Can anyone
explain why the below doesnt show any results. I assumed that it was due to
not using `print' or return at the end of the function but I played around
with that to no avail. Helpss :) please
import urllib2
from multiprocessing.dummy import Pool as ThreadPool
urls = [
'http://www.python.org',
'http://www.python.org/about/',
'http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html',
'http://www.python.org/doc/',
'http://www.python.org/download/',
'http://www.python.org/getit/',
'http://www.python.org/community/',
'https://wiki.python.org/moin/',
'http://planet.python.org/',
'https://wiki.python.org/moin/LocalUserGroups',
'http://www.python.org/psf/',
'http://docs.python.org/devguide/',
'http://www.python.org/community/awards/'
# etc..
]
# Make the Pool of workers
pool = ThreadPool(4)
# Open the urls in their own threads
# and return the results
results = pool.map(urllib2.urlopen, urls)
#close the pool and wait for the work to finish
pool.close()
pool.join()
Answer: To elaborate on @figs suggestion:
def opener(url):
site = urllib2.urlopen(url)
return site.read()
results = pool.map(opener, urls)
The problem is that you're not using the `read()` method, which returns the
html of the page.
|
generating cert for use with python requests getting PEM lib error
Question: I have an application which I'm doing self-signing certificates for using the
documentation [here](http://stackoverflow.com/questions/652916/converting-a-
java-keystore-into-pem-format).
The application loads that keystore into a jetty config and loads properly and
I get a warning of an untrusted certification when browsing to the site.
Then I want to use python to connect to it and I've tried all variations of
generating a cert, pem, etc. nothing I do gets me to connect. Simply doing the
following -
import requests
requests.get('https://servername:8443', cert=('path\
\to\\cert\\app.cert', '\\\\path\\to\\keystore\\keystore'))
Gives me the following traceback -
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\requests\api.py", line 69, in get
return request('get', url, params=params, **kwargs)
File "C:\Python27\lib\site-packages\requests\api.py", line 50, in request
response = session.request(method=method, url=url, **kwargs)
File "C:\Python27\lib\site-packages\requests\sessions.py", line 465, in request
resp = self.send(prep, **send_kwargs)
File "C:\Python27\lib\site-packages\requests\sessions.py", line 573, in send
r = adapter.send(request, **kwargs)
File "C:\Python27\lib\site-packages\requests\adapters.py", line 431, in send
raise SSLError(e, request=request)
requests.exceptions.SSLError: [SSL] PEM lib (_ssl.c:2580)
Answer: `cert` in requests is used for client site certificates, not for the CA store.
Use the `verify` parameter to specify the CA file, e.g.:
requests.get('https://www.example.com', verify='/etc/ssl/certs/ca-certificates.crt')
|
How to do while() the "pythonic way"
Question: I want to do this:
from django.db import connection
cursor = connection.cursor()
cursor.execute("PRAGMA table_info(ventegroupee)")
while row = cursor.fetchone():
print(row)
I get this:
File "<input>", line 1
while row = cursor.fetchone():
^
SyntaxError: invalid syntax
What is the "pythonic" way of doing this?
Answer: You don't have to use `while` loop at all, because cursors are iterable:
for row in cursor:
print(row)
From the "Connections and cursors" section of [Django
documentation](https://docs.djangoproject.com/en/1.8/topics/db/sql/#connections-
and-cursors):
> _connection_ and _cursor_ mostly implement the standard Python DB-API
> described in PEP 249 — except when it comes to transaction handling.
From the mentioned [PEP 249](https://www.python.org/dev/peps/pep-0249/#next):
> _Cursor.next()_
>
> Return the next row from the currently executing SQL statement using the
> same semantics as _.fetchone()_
>
> _Cursor.__iter__()_
>
> Return self to make cursors compatible to the iteration protocol
|
How to stop one scheduler iteration in Python
Question: I am new to the Python (and programming in general). I have a pcode that
periodically downloads the website content through PyCURL and do some
searching. I have used scheduler inside the While-True to set up an infinite
loop where I create an object and call its method start()to grab the website
and perform some searchs.. Problem occurs when getbody() methon can't fetch
the website, due to the connection problems (or another reasons).
BeautifulSoup expects the string, raises an Error otherwise.
How to stop a Thread of the scheduler programme when an Error/Exception occurs
right in the getbody() method and so wait for another Thread? Returning an
empty string as a result of getbody() method is a waste of cpu time.
#Parser_module
class Parser(object):
def __init__(self):
self.body = BeautifulSoup(self.getbody(), "lxml")
self.buffer = BytesIO()
def getbody(self):
# some code to set pycurl up
try:
c.perform()
except pycurl.error:
print("connection error")
# returns an emptry string to feed the BeautifulSoup with
return ""
body = self.buffer.getvalue().decode("utf-8")
return body
def start(self):
#calls other functions to perform some searching
self.otherfunction()
def otherfunction(self):
.
.
.
#Scheduler module
import Parser_module
from threading import Timer
def start_search():
parser = Parser()
parser.start()
t = Timer(20.0, start_search)
t.start()
Answer: Instead of fetching the URL in the `Parser.__init__`, you could just do that
in `Parser.start` and return if an error occurs.
class Parser(object):
def __init__(self):
self.body = None
self.buffer = BytesIO()
def start():
data = self.getbody()
if not data:
return
self.body = BeautifulSoup(data, "lxml")
self.otherfunction()
def getbody(self):
...
def otherfunction(self):
...
On a side note, I suggest that you use the much nicer
[requests](http://docs.python-requests.org/en/latest/) library instead of
pycurl, if you can. Also check out
[PEP8](https://www.python.org/dev/peps/pep-0008/), the Python Style Guide,
e.g. for some suggestions on how to name things.
|
Python3 urlopen read weirdness (gzip)
Question: I'm getting an URL from Schema.org. It's content-type="text/html"
Sometimes, read() functions as expected b'< !DOCTYPE html> ....'
Sometimes, read() returns something else b'\x1f\x8b\x08\x00\x00\x00\x00 ...'
try:
with urlopen("http://schema.org/docs/releases.html") as f:
txt = f.read()
except URLError:
return
I've tried solving this with `txt = f.read().decode("utf-8").encode()` but
this results in an error... sometimes: UnicodeDecodeError: 'utf-8' codec can't
decode byte 0x8b in position 1: invalid start byte
The obvious work-around is to test if the first byte is hex and treat this
accordingly.
My question is: Is this a bug or something else?
[](http://i.stack.imgur.com/mzWfR.png)
**Edit** Related [question](http://stackoverflow.com/questions/3746993/change-
python-byte-type-to-string). Apparently, sometimes I'm getting a gzipped
stream.
**Lastly** I solved this by adding the following code as [proposed
here](http://stackoverflow.com/questions/2695152/in-python-how-do-i-decode-
gzip-encoding)
if 31 == txt[0]:
txt = decompress(txt, 16+MAX_WBITS)
The question remains; why does this return text/html sometimes and zipped some
other times?
Answer: You are indeed receiving a gzipped response. You should be able to avoid it
by:
from urllib import request
try:
req = request.Request("http://schema.org/docs/releases.html")
req.add_header('Accept-Encoding', 'identity;q=1')
with request.urlopen(req) as f:
txt = f.read()
except request.URLError:
return
|
Can't execute queries until end of atomic block in my data migration on django 1.7
Question: I have a pretty long data migration that I'm doing to correct an earlier bad
migration where some rows were created incorrectly. I'm trying to assign
values to a new column based upon old ones, however, sometimes this leads to
integrity errors. When this happens, I want to throw away the one that's
causing the integrity error
Here is a code snippet:
def load_data(apps, schema_editor):
MyClass = apps.get_model('my_app', 'MyClass')
new_col_mapping = {old_val1: new_val1, ....}
for inst in MyClass.objects.filter(old_col=c):
try:
inst.new_col = new_col_mapping[c]
inst.save()
except IntegrityError:
inst.delete()
Then in the operations of my `Migration` class I do
operations = [
migrations.RunPython(load_data)
]
I get the following error when running the migration
django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block
I get the feeling that doing
with transaction.atomic():
somewhere is my solution but I'm not exactly sure where the right place is.
More importantly I'd like to understand WHY this is necessary
Answer: This is similar to the [example in the
docs](https://docs.djangoproject.com/en/1.8/topics/db/transactions/#controlling-
transactions-explicitly).
First, add the required import if you don't have it already.
from django.db import transaction
Then wrap the code that might raise an integrity error in an atomic block.
try:
with transaction.atomic():
inst.new_col = new_col_mapping[c]
inst.save()
except IntegrityError:
inst.delete()
The reason for the error is explained in the warning block 'Avoid catching
exceptions inside atomic!' in the docs. Once Django encounters a database
error, it will roll back the atomic block. Attempting any more database
queries will cause a `TransactionManagementError`, which you are seeing. By
wrapping the code in an atomic block, only that code will be rolled back, and
you can execute queries outside of the block.
|
Python type hinting: how to tell X is a subclass for Foo?
Question: How should I write a type hint for class types in Python? Consider this code:
class A(object):
pass
class B(A):
pass
def register(cls: type[A]):
assert issubclass(cls, A)
register(A)
register(B)
Is `type[A]` the correct way to write this? If I'd just use `cls: A` it would
mean `cls` is an instance of `A`, but I want to to say `cls` is a class/type,
which at least subclasses `A`.
Specifically, what I want to indicate is that the parameter should be a Django
model type.
Answer: To solve your general case, you would have to write a metaclass with a
suitable `__subclasscheck__`. Possible, but cumbersome.
In your specific case of Django model classes, an explicit metaclass already
exists, so annotating that should do the job:
import django.db.model as model
def register(cls: model.base.ModelBase): ...
This will work because `isinstance(models.Model, models.base.ModelBase)` is
true.
|
Parsing XML: Finding Interesting Elements Using ElementTree
Question: I am using urllib and ElementTree to parse XML API calls from pubmed.
An example of this is:
#Imports Modules that can send requests to URLs
#Python Version 3.4 Using IEP (Interactive Editor for Python) as IDE
import urllib.request
import urllib.parse
import re
import xml.etree.ElementTree as ET
from urllib import request
#Obtain API Call and assign Element Object to Root
id_request = urllib.request.urlopen('http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed&id=1757056')
id_pubmed = id_request.read()
root = ET.fromstring(id_pubmed)
I now have been able to use Element Tree to import the data to the object root
from ET.fromstring. My issue now, is that I am having trouble finding
interesting elements from this object.
I am referring to:
<https://docs.python.org/2/library/xml.etree.elementtree.html> and my XML
format looks like:
[http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed&id=1757056](http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed&id=1757056)
I have tried:
#Parse Attempts. Nothing returned.
for author in root.iter('Author'):
print (author.attrib)
As well as
#No Return for author
for author in root.findall('Id'):
author = author.find('author').text
print (author)
Answer: Try to iterate by the tag
for author in root.iter('Item'):
if author.attrib['Name'] == 'Author':
print("Success")
Or:
author_list = [x for x in root.iter('Item') if x.attrib['Name'] == 'Author']
I don't know if you can iterate by attribute
|
Numpy String Encoding
Question: The module numpy is an excellent tool for memory-efficient storage of python
objects, among them strings. For ANSI strings in numpy arrays only 1 byte per
character is used.
However, there is one inconvenience. The type of stored objects is no more
`string` but `bytes`, which means that have to be decoded for further use in
most cases, which in turn means quite bulky code:
>>> import numpy
>>> my_array = numpy.array(['apple', 'pear'], dtype = 'S5')
>>> print("Mary has an {} and a {}".format(my_array[0], my_array[1]))
Mary has an b'apple' and a b'pear'
>>> print("Mary has an {} and a {}".format(my_array[0].decode('utf-8'),
... my_array[1].decode('utf-8')))
Mary has an apple and a pear
This inconvenience can be eliminated by using another data type, e.g:
>>> my_array = numpy.array(['apple', 'pear'], dtype = 'U5')
>>> print("Mary has an {} and a {}".format(my_array[0], my_array[1]))
Mary has an apple and a pear
However, this is achieved only by cost of 4-fold increase in memory usage:
>>> numpy.info(my_array)
class: ndarray
shape: (2,)
strides: (20,)
**itemsize: 20**
aligned: True
contiguous: True
fortran: True
data pointer: 0x1a5b020
byteorder: little
byteswap: False
type: <U5
Is there a solution that combines advantages of both efficient memory
allocation and convenient usage for ANSI strings?
Answer: Given:
>>> my_array = numpy.array(['apple', 'pear'], dtype = 'S5')
You can decode on the fly:
>>> print("Mary has an {} and a {}".format(*map(lambda b: b.decode('utf-8'), my_array)))
Mary has an apple and a pear
Or you can create a specific formatter:
import string
class ByteFormatter(string.Formatter):
def __init__(self, decoder='utf-8'):
self.decoder=decoder
def format_field(self, value, spec):
if isinstance(value, bytes):
return value.decode(self.decoder)
return super(ByteFormatter, self).format_field(value, spec)
>>> print(ByteFormatter().format("Mary has an {} and a {}", *my_array))
Mary has an apple and a pear
|
How can I execute a function that is inside a string from inside another function?
Question: I'm trying to make a Reddit Bot in Python but I have encountered an issue. The
objective of the bot is to read the comments of Reddit searching for
"get_tweets". When it finds this it will read the whole comment that will look
similar to this:
get_tweets("TWITTER_USERNAME",NUMBER_OF_TWEETS,"INCLUDE_RE_TWEETS","INCLUDE_REPLIES")
The comment will serve as a function and the 4 parameters will be determined
by the user commenting. An example can be:
get_tweets("BarackObama",5,"no","yes")
I think I have everything covered except for the fact that I can't execute the
comment as a function because when I try it gives this error:
SyntaxError: unqualified exec is not allowed in function 'run_bot' it contains a nested function with free variables
Here is the whole code (except for the authentication for twitter and reddit):
keywords = ['get_tweets']
cache = []
tweets_list = []
def get_tweets(user,num,rt,rp):
tline = api.user_timeline(screen_name=user, count=num)
tweets = []
for t in tline:
reply = t.in_reply_to_screen_name
tweet = t.text
if rt.lower() == 'no' and rp.lower() == 'no':
if tweet[0:2] != 'RT' and reply == None:
tweets.append(tweet + ' | Date Tweeted: ' + str(t.created_at))
if rt.lower() == 'yes' and rp.lower() == 'no':
if tweet[0:2] == 'RT' and reply == None:
tweets.append(tweet + ' | Date Tweeted: ' + str(t.created_at))
if rt.lower() == 'no' and rp.lower() == 'yes':
if tweet[0:2] != 'RT' and reply != None:
tweets.append(tweet + ' | Date Tweeted: ' + str(t.created_at))
if rt.lower() == 'yes' and rp.lower() == 'yes':
if tweet[0:2] == 'RT' and reply != None:
tweets.append(tweet + ' | Date Tweeted: ' + str(t.created_at))
tweets_list = tweets
def run_bot():
subreddit = r.get_subreddit('test')
print('Searching...')
comments = subreddit.get_comments(limit=100)
for comment in comments:
comment_text = comment.body.lower()
isMatch = any(string in comment_text for string in keywords)
if comment.id not in cache and isMatch:
print('Found comment: ' + comment_text)
exec comment_text
cache.append(comment.id)
start = []
end = []
open_p = comment.index('(')
text = ''
for a in re.finditer(',', comment):
start.append(a.start())
end.append(a.end())
num = comment_text[end[0]:start[1]]
user = comment_text[open_p:start[0]]
for tweet in tweets_list:
text.append(' | ' + tweet + '\n\n')
if num == 1:
reply = 'Here is the latest tweet from ' + user + ':\n\n' + text + '\n\n***\nI am a bot.'
else:
reply = 'Here are the last ' + num + ' tweets from ' + user + ':\n\n' + text + '\n\n***\nI am a bot.'
comment.reply(reply)
run_bot()
Answer: Using `exec` or `eval` is a huge security problem! The best you can try is to
extract the parameters from the string using regex or simply decompose it
using the `,` and then call your function with that. Luckily you only need
strings and numbers and therefore no dangerous parsing is necessary.
One possible solution would be:
import re
def get_tweets(user, num, rt, rp):
num = int(num)
print user, num, rt, rp
comment_text = 'get_tweets("BarackObama",5,"no","yes")'
# capture 5 comma separated parts between '(' and ')'
pattern = r'get_tweets\(([^,]*),([^,]*),([^,]*),([^,]*)\)'
param_parts = re.match(pattern,comment_text).groups()
# strip away surrounding ticks and spaces
user,num,rt,rp = map(lambda x:x.strip('\'" '), param_parts)
# parse the number
num = int(num)
# call get tweets
get_tweets(user,num,rt,rp)
prints:
BarackObama 5 no yes
Disadvantage:
* Only works if the username does not contain a comma or begin/end with `'` or `"`, which I guess can be assumed (correct me if I'm wrong here).
Advantages:
* Since the splitting is done at `,` you can also get rid of the ticks entirely which makes `get_tweets(BarackObama,5,no,yes)` valid as well.
* We're using regex which means that the comment may contain additional text and we extract only what we need.
* If anyone wanted to inject code, you would just get a weird username, or a wrong number of arguments or an int which is not parsable or an invalid argument for `rt`/`rp`... which would all lead to an exception or no tweets at all.
* You can actually return a value from `get_tweets` and don't need to use a global variable.
|
Tuple to datetime object
Question: I have a tuple that looks like this
(datetime.datetime(2015, 8, 25, 14, 8, 56),)
And I want to convert it to a datetime object, in python?
How can I do this?
I have tried
import datetime
time = datetime.datetime(my_tuple)
Bu that didn't work.
Answer: Just get the first element of the tuple, which is a `datetime` object already.
time = my_tuple[0]
|
improve Frame of Tkinter in Python
Question: I am quite new to use Frame of Tkinter in Python. I discovered Frame from the
following [post](http://stackoverflow.com/questions/32198849/set-the-correct-
tkinter-widgets-position-in-python) When i run the GUI the Check box are not
in the same line.
[](http://i.stack.imgur.com/jB3jB.png)
For this reason i have the following two questions:
1) is it possible to use "grid" in the frame in order to place the widget
where i wish?
2) Is it possible to place for example "Camera white balance" and "average
white balance" in the same row? in grid is for example row=0, column=0 and
row=0, column=1
3) if i add a line below the button "Input raw image file" using the code:
self.sep = Frame(self, height=2, width=450, bd=1, relief=SUNKEN)
self.sep.grid(row=1, column=0, columnspan=4, padx=5, pady=5)
The Run works forever without showing the GUI.
My code is:
from __future__ import division
from Tkinter import *
import tkMessageBox
import tkFileDialog
class MainWindow(Frame):
def __init__(self):
Frame.__init__(self)
self.master.title("FOO frame")
self.master.minsize(350, 150)
self.grid(sticky=W+N+S+E)
top_frame = Frame(self)
middle_frame = Frame(self)
bottom_frame = Frame(self)
top_frame.pack(side="top", fill="x")
middle_frame.pack(side="top", fill="x")
bottom_frame.pack(side="top", fill="x")
self.open = Button(top_frame,text="Input raw image file",
command=self.open,
activeforeground="red")
self.open.pack(side="left")
self.CheckVar_camera_white_balance = IntVar()
self.CheckVar_camera_white_balance = Checkbutton(middle_frame,
text="Camera white balance",
variable=self.CheckVar_camera_white_balance,
onvalue=1,
offvalue=0)
self.CheckVar_camera_white_balance.pack(side="top", fill="x")
self.CheckVar_average_whole_image_white_balance = IntVar()
self.CheckVar_average_whole_image_white_balance = Checkbutton(middle_frame,
text="Average white balance",
variable=self.CheckVar_average_whole_image_white_balance,
onvalue=1,
offvalue=0)
self.CheckVar_average_whole_image_white_balance.pack()
self.CheckVar_correct_chromatic_aberration = IntVar()
self.CheckVar_correct_chromatic_aberration = Checkbutton(middle_frame,
text="Correct chromatic aberration",
variable=self.CheckVar_correct_chromatic_aberration,
onvalue=1,
offvalue=0)
self.CheckVar_correct_chromatic_aberration.pack()
self.CheckVar_fix_dead_pixels = IntVar()
self.CheckVar_fix_dead_pixels = Checkbutton(middle_frame,
text="Fix dead pixels",
variable=self.CheckVar_fix_dead_pixels,
onvalue=1,
offvalue=0)
self.CheckVar_fix_dead_pixels.pack()
# functions
def open(self):
self.filename_open = tkFileDialog.askopenfilenames(defaultextension='.*')
if __name__ == "__main__":
d = MainWindow()
d.mainloop()
Answer: 1. Yes, it is possible to use `grid` In any frame you wish
2. Yes, it is possible to place "Camera white balance" and "average white balance" in the same row.
3. The reason the code runs forever without displaying anything is because you are using both grid (for the separator) and pack (for the frames). They both have the same parent so you can only use one or the other.
To get things to align you should read the documentation to learn about all of
the options available when calling `grid` and `pack`. These options allow you
to center itemsm or align them alon an edge, control padding, and so on.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.