text
stringlengths 226
34.5k
|
---|
png loading in pygame
Question: I am writing a simple game in python, and I need to load an image from a
bmp/png file and draw it to the screen. The important part of my code looks
like this:
temp = pygame.image.load("debris.bmp").convert()
temp.convert_alpha()
temp.blit(screen, (250,250))
pygame.display.flip()
fps.tick(20)
So I expect a small brick to appear on screen. This does not happen. I made it
to draw a small graphic primitive immediately after the blit, and that appears
to work. This indicates that I am not drawing over it, and that the
display.flip() is working well. Any thoughts?
Answer: well, one reason it might not be working is how you 'blit' your image to the
screen, if your pygame window is named 'screen' then it would be like this
screen.blit(img, (coord1, coord2))
like that
|
dynamically update module using exec and compile in Python
Question: I would like to dynamically import and update modules. The more efficient way
would likely be to use `importlib` and `imp.reload` [as suggested by
abarnet](http://stackoverflow.com/questions/18500283/how-do-you-reload-a-
module-in-python-version-3-3-2). However another solution would be to use
`exec` and `compile`. I have a sample script below that demonstrates how a
module stored in a string can be called and used on the fly. However, when I
call this module in function `test` (see below), it does not work, and is
giving me an error message `global name 'FRUITS' is not defined`. I need some
fresh pairs of eyes to point me out why this does not work. Thanks.
module_as_string = """
class FRUITS:
APPLE = "his apple"
PEAR = "her pear"
class foo(object):
def __init__(self):
self.x = 1
def get_fruit(self):
return FRUITS.APPLE
_class_name = foo """
def get_code_object():
return compile(module_as_string, "<string>", "exec")
def test():
exec(get_code_object())
a = eval("_class_name()")
print(a.get_fruit())
if __name__ == "__main__":
# below doesn't work
test()
# below works
exec(get_code_object())
a = eval("_class_name()")
print(a.get_fruit())
\-- Edit: Let me know how I can improve this question if you think it is not
worthy of asking. Don't just down vote. Thanks.
Answer: Within function `test`, while FRUIT is a local variable, we do not have direct
access to it. To access `FRUIT`, an additional container, `dict_obj` should be
passed in to `exec`, which we can then use to access the executed classes from
that container. A working example is shown below.
def test():
dict_obj = {}
exec(get_code_object(),dict_obj)
a = dict_obj["_class_name"]()
print(a.get_fruit())
|
Django can't find any views but index
Question: I'm pretty new to Python and Django as well, but I'm going through the
tutorial as closely as I can and I must be missing something. I can get my
default index view to load, but I want to send an ajax call to a view called
'search' and I have another view called 'show' that would take an integer
(show_id) and I get 404s on both of the calls to those pages.
What am I missing? Do I need anything else in my settings? My index view works
fine, but these other routes aren't jiving. Thanks for the help in advance!
EDIT: Here is a screengrab of my folder structure: 
mediamanager/urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'mediamanager.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^manager', include('manager.urls')),
url(r'^admin/', include(admin.site.urls))
)
Settings:
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'manager'
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'mediamanager.urls'
WSGI_APPLICATION = 'mediamanager.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
manager.urls.py:
from django.conf.urls import patterns, url
from manager import views
urlpatterns = patterns('',
url(r'^$',views.index, name='index'),
url(r'^(?P<show_id>\d+)/$', views.show, name='show'),
url(r'^search/$', views.search, name='search')
)
views.py
from django.shortcuts import render
from django.http import HttpResponse
from manager.models import Show, Episode
import urllib2
# Create your views here.
def index(request):
context = {'shows' : Show.objects.all().order_by('show_name')}
return render(request, 'manager/index.html', context)
def show(request, show_id):
s = Show.objects.get(show_id).order_by('-air_date')
context = {'show': s, 'episodes': s.episodes}
return render(request, 'manager/show.html', context)
def search(request):
search_term = request.GET['show_search']
search_results = urllib2.urlopen("http://thetvdb.com/3BBD3F7E1043129C/GetSeries.php?seriesname=%s" % search_term)
return HttpResponse(search_results)
Answer: This is your problem:
url(r'^manager', include('manager.urls')),
should be
url(r'^manager/', include('manager.urls')),
# ^ The missing /
Now, the reason `index` works is, there is a pattern that matches `/manager`
Note that: `manager123/` (#where 123 is the show id) or `managersearch/`
would be valid URLs (non-404) in your application.
|
Using 'r+' mode to overwrite a line in a file with another line of the same length
Question: I have a file called `vegetables`:
> carrots
> apples_
> cucumbers
What I want to do is open the file in python, and modify it in-place, without
overwriting large portions of the file. Specifically, I want to overwrite
`apples_` with `lettuce`, such that the file would look like this:
> carrots
> lettuce
> cucumbers
To do this, I've been told to use `'r+'` mode. However, I don't know how to
overwrite that line in place. Is that possible? All the solutions I am
familiar with involve caching the entire file, and then overwriting the entire
file, for a small amendment. Is this really the best option?
**Important note** : the replacement line is always the same length as the
original line.
For context: I'm not really concerned with a file on vegetables. Rather, I
have a textfile of about 400 lines to which I need to make revisions roughly
every two minutes. I have a script to do this, but I want to do it more
efficiently.
Answer: an answer that works with your example
with open("vegetables","r+") as t:
data = t.read()
t.seek(data.index("apples_"))
t.write("lettuce")
although, it might not be worth it to complicate things like this,
it's fine to just read the entire file, and then overwriting the entire file,
you aren't going to save much by doing something like my example
NOTE: this only works if it has the exactly the same length as the original
text you are replacing
edit1: a (possibly bad) example to replace all match:
import re
with open("test","r+") as t:
data = t.read()
for m in re.finditer("apples_", data):
t.seek(m.start())
t.write("lettuce")
edit2: something a little more complex using closure so that it can check for
multiple words to replace
import re
def get_find_and_replace(f):
"""f --> a file that is open with r+ mode"""
data = f.read()
def find_and_replace(old, new):
for m in re.finditer(old, data):
f.seek(m.start())
f.write(new)
return find_and_replace
with open("test","r+") as f:
find_and_replace = get_find_and_replace(f)
find_and_replace("apples_","lettuce")
#find_and_replace(...,...)
#find_and_replace(...,...)
|
paramiko SSHClient connect stuck
Question: i have 3 source code(main and imported from it).
## test.py - just import file
import test_child
## test_child.py - call function defined in imported file
import test_grandchild
test_grandchild.check_sshd()
## test_grandchild.py - define function
import paramiko
def check_sshd():
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print('checking ssh connection to local host')
client.connect('127.0.0.1')
client.close()
print('finished')
check_ssd() is a fucntion just for checking sshd is running on localhost, So
it is my expecting that Authentication execption occur when sshd is not
running, otherwise socket error. When i run test_child.py, result is in my
expecting. but paramiko client get stucked on connect() and I have to
terminate the process.
$ python test.py
checking ssh connection to local host
^CTraceback (most recent call last):
File "test.py", line 4, in <module>
import test_child
File "/root/tests/test_child.py", line 6, in <module>
test_grandchild.check_sshd()
File "/root/tests/test_grandchild.py", line 10, in check_sshd
client.connect('127.0.0.1')
File "build/bdist.linux-x86_64/egg/paramiko/client.py", line 242, in connect
File "build/bdist.linux-x86_64/egg/paramiko/transport.py", line 342, in start_client
File "/usr/lib64/python2.7/threading.py", line 621, in wait
self.__cond.wait(timeout, balancing)
File "/usr/lib64/python2.7/threading.py", line 361, in wait
_sleep(delay)
KeyboardInterrupt
how can i solve this problem?
Paramiko 1.12.4 on CentOS 7
Thanks.
Answer: **Paramiko** uses **Threading** library to distribute tasks to different
threads, and event is set then they communicate with each other and return
output. The problem here is in **test.py** you are just importing the
test_child not calling any of its function specifically.
So the execution point to call **check_sshd()** is **test_child.py** not
**test.py**. Hence threading event is not set. So for this either you call
function from same file or you need to specifically call function from test.py
rather than just importing file.
**test.py**
import test_child
test_child.check_ssh_connection()
**test_child.py**
import test_grandchild
def check_ssh_connection():
test_grandchild.check_sshd()
**test_grandchild.py**
import paramiko
def check_sshd():
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print('checking ssh connection to local host')
client.connect('127.0.0.1')
client.close()
print('finished')
Hopefully this would solve your problem.
|
Python3 urllib.request will not close connections immediately
Question: I've got the following code to run a continuous loop to fetch some content
from a website:
from http.cookiejar import CookieJar
from urllib import request
cj = CookieJar()
cp = request.HTTPCookieProcessor(cj)
hh = request.HTTPHandler()
opener = request.build_opener(cp, hh)
while True:
# build url
req = request.Request(url=url)
p = opener.open(req)
c = p.read()
# process c
p.close()
# check for abort condition, or continue
The contents are correctly read. But for some reason, the TCP connections
won't close. I'm observing the active connection count from a dd-wrt router
interface, and it goes up consistently. If the script continue to run, it'll
exhaust the 4096 connection limit of the router. When this happens, the script
simply enter waiting state (the router won't allow new connections, but
timeout hasn't hit yet). After couple minutes, those connections will be
closed and the script can resume again.
I was able to observe the state of those hanging connections from the router.
They share the same state: TIME_WAIT .
I'm expecting this script to use no more than 1 TCP connection simultaneously.
What am I doing wrong?
I'm using Python 3.4.2 on Mac OS X 10.10.
Answer: Through some research, I discovered the cause of this problem: [the design of
TCP protocol](http://superuser.com/questions/173535/what-are-close-wait-and-
time-wait-states) . In a nutshell, when you disconnect, the connection isn't
dropped immediately, it enters 'TIME_WAIT' state, and will time out after 4
minutes. Unlike what I was expecting, the connection doesn't immediately
disappear.
According to [this question](http://serverfault.com/questions/329845/how-to-
forcibly-close-a-socket-in-time-wait), it's also not possible to forcefully
drop a connection (without restarting the network stack).
It turns out in my particular case, like [this question
stated](http://stackoverflow.com/questions/9772854/persistence-of-urllib-
request-connections-to-a-http-server), a better option would be to use a
persistent connection, a.k.a. HTTP keep-alive. As I'm querying the same
server, this will work.
|
Jinja2.5 Syntax error on import
Question: I am using Python 3.2.3. And I installed Jinja2.5 by downloading from this
page: `https://pypi.python.org/pypi/Jinja2/2.5.5`
Then I used the setup.py to install it. This seemed worked like a charm. When
I tested it by using this line:
from jinja2 import Template
I got the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.2/dist-packages/Jinja2-2.5.5-py3.2.egg/jinja2/__init__.py", line 37, in <module>
from jinja2.environment import Environment, Template
File "/usr/local/lib/python3.2/dist-packages/Jinja2-2.5.5-py3.2.egg/jinja2/environment.py", line 13, in <module>
from jinja2 import nodes
File "/usr/local/lib/python3.2/dist-packages/Jinja2-2.5.5-py3.2.egg/jinja2/nodes.py", line 18, in <module>
from jinja2.utils import Markup, MethodType, FunctionType
File "/usr/local/lib/python3.2/dist-packages/Jinja2-2.5.5-py3.2.egg/jinja2/utils.py", line 585, in <module>
from markupsafe import Markup, escape, soft_unicode
File "/usr/local/lib/python3.2/dist-packages/markupsafe/__init__.py", line 70
def __new__(cls, base=u'', encoding=None, errors='strict'):
^
SyntaxError: invalid syntax
This is on my Raspberry pi with Raspbian installed. I don't know why this
error occures, because the docs say Jinja2.5 and Python 3.2 are compatible.
Can anyone help me out? Thanks in advance!
Answer: Try typing `python --version` if the reply does not say Python 3. something
then your default python is python 2 and so does not support `u''` for unicode
strings.
If this is the case you need to install `jinja2` by using `pip3 install
jinja2` and run your scripts with `python3 scriptname.py`.
Other than that see: [Syntax error in jinja 2
library](http://stackoverflow.com/questions/18252804/syntax-error-in-
jinja-2-library?rq=1) basically python 3.2 is no longer supported so the
choice is pick another library or upgrade python.
|
Python Calculator Error output
Question: So I made a Calculator using python 2.7.8 and everything works like it should,
unless one thing. I want to receive the error message "ERROR: Minimum Input:
Number Operator Number!" when i for example try to calculate "2 +". But I
can't get it working. Would be amazing if someone could point out what
mistake(s) I made. Here is what is not working correctly:
except len(self.input) < 3:
print "ERROR: Minimum Input: Number Operator Number!"
And here is the whole code:
import sys
class Calculator(object):
def __init__(self, input):
self.input = input
def divide(self, number1, number2):
return number1 / number2
def add(self, number1, number2):
return number1 + number2
def sub(self, number1, number2):
return number1 - number2
def mult(self, number1, number2):
return number1 * number2
def modulo(self, number1, number2):
return number1 % number2
def exponentiate(self, number1, number2):
return number1 ** number2
def print_error(self, error):
print error
sys.exit(-1)
def print_result(self, result):
print result
sys.exit(0)
def process_input(self):
try:
result = float(self.input[1])
current_operator = ""
for element in self.input[2:]:
if element in ["/", "+", "-", "*", "%", "**"]:
current_operator = element
else:
number2 = float(element)
if current_operator == "/":
result = self.divide(result, number2)
elif current_operator == "+":
result = self.add(result, number2)
elif current_operator == "-":
result = self.sub(result, number2)
elif current_operator == "*":
result = self.mult(result, number2)
elif current_operator == "%":
result = self.modulo(result, number2)
elif current_operator == "**":
result = self.exponentiate(result, number2)
else:
self.print_error(error)
self.print_result(result)
except ZeroDivisionError:
print "ERROR: Caught division by zero!"
except ValueError:
print "ERROR: Input number could not be parsed!"
except OverflowError:
print "ERROR: Result too large! Overflow encountered."
except len(self.input) < 3:
print "ERROR: Minimum Input: Number Operator Number!"
calc = Calculator(sys.argv)
calc.process_input()
Thanks for any answer!
Answer: As you have it, the code won't work. Instead, you'll need to either change
this part into an `if` statement or manually `raise` an exception:
### Old version - won't work.
try:
# ...code...
except len(self.input) < 3:
print "ERROR: Minimum Input: Number Operator Number!"
### New version - Option A.
if len(self.input) < 3:
print "ERROR: Minimum Input: Number Operator Number!"
else:
# ...code...
### New version - Option B.
try:
if len(self.input) < 3:
raise RuntimeError("Not enough arguments.")
# ...code...
except RuntimeError:
print "ERROR: Minimum Input: Number Operator Number!"
I've used `RuntimeError` as an example, you might want to use [something more
suitable](https://docs.python.org/2/library/exceptions.html) instead.
|
Parse error with same name nested tags using python xml to json
Question: I have a small set back I have a large xml file in the following format
<doc id="1">Some text</doc>
<doc id="2">more text</doc>
Im using the following python script to convert into a json format:
from sys import stdout
import xmltodict
import gzip
import json
count = 0
xmlSrc = 'text.xml.gz'
jsDest = 'js/cd.js'
def parseNode(_, node):
global count
count += 1
stdout.write("\r%d" % count)
jsonNode = json.dumps(node)
f.write(jsonNode + '\n')
return True
f = open(jsDest, 'w')
xmltodict.parse(gzip.open(xmlSrc), item_depth=2, item_callback=parseNode)
f.close()
stdout.write("\n") # move the cursor to the next line
Is it possible to detected the end `</doc>` and break and then continue
converting? Ive looked at other stackoverflow question but none help. [How do
you parse nested XML tags with
python?](http://stackoverflow.com/questions/8186343/how-do-you-parse-nested-
xml-tags-with-python)
Answer: As your `<doc>` tag isn't nested itself, you can iterate the document and
manually serialize the object and dump to `json`, here is an example:
import xml.etree.ElementTree as ET
import json
s= '''
<root>
<abc>
<doc id="12" url="example.com" title="Anarchism"> Anarchism .... </doc>
</abc>
<doc id="123" url="example2" title="Laptop"> Laptop .... </doc>
<def>
<doc id="3">Final text</doc>
</def>
</root>
'''
tree = ET.fromstring(s)
j = []
# use iterfind will iterate the element tree and find the doc element
for node in tree.iterfind('.//doc'):
# manually build the dict with doc attribute and text
attrib = {}
attrib.update(node.attrib)
attrib.update({'text': node.text})
d = {'doc': [ attrib ] }
j.append(d)
json.dumps(j)
'[{"doc": [{"url": "example.com", "text": " Anarchism .... ", "id": "12", "title": "Anarchism"}]}, {"doc": [{"url": "example2", "text": " Laptop .... ", "id": "123", "title": "Laptop"}]}, {"doc": [{"text": "Final text", "id": "3"}]}]'
# to write to a json file
with open('yourjsonfile', 'w') as f:
f.write(json.dumps(j))
|
I like Python; do I have to use Django/Flask/etc?
Question: I like Python a lot (check out my username!), and I'm building a web
application. I've used Django for a couple of projects. Most of my web dev
friends prefer Node, or Rails, though.
Python provides data analysis tools that are important to my application.
Is it possible to use Python with Node/Rails/other web frameworks? Is it easy
to do?
EDIT: Hmm, it looks like this question was not received very well. Let me try
to be clearer. Essentially I am asking if I can use Python for its data
analysis tools but use something like Node for the server -- a few of the SDKs
for libraries that we are thinking of using are not compatible with Python.
I had a look at this: [Combining node.js and
Python](http://stackoverflow.com/questions/10775351/combining-node-js-and-
python), but it seems to have a steep learning curve to setup. Can someone who
has combined the two technologies comment on the pros/cons of using a Python
web framework vs. using Python for data analysis and integrating it with
something like Node?
I hope this is clearer. Thanks.
Answer: If you need to use Python, then you should use a Python web framework. You
don't need to use Django or Flask, but you should use
[something](https://wiki.python.org/moin/WebFrameworks).
|
Python Need Access to variable created in a function from another function
Question: As i have set search term to global for the first function - shouldnt the
second function be able to access it - if not how would i get this to work?
import sys
import os.path
from tkinter import *
import math
def setupsearch():
exist = os.path.isfile('messages.txt')
if exist == True:
global searchterm
gui2 = Toplevel(master=gui)
Label(gui2, text = "Search Term").grid(row = 0)
searchterm = Entry(gui2).grid(row = 1)
Button(gui2, text="Search", command = search).grid(row = 2)
else:
labelprint = "No Stored Messages"
add = Label(gui, text = labelprint, width = 30)
add.grid(row = 2, column =2)
def search():
searchterm =
with open('messages.txt', 'r') as inF:
i = 1
for line in inF:
if searchterm in line:
print("found it in line " + str(i))
i = i + 1
else:
print("Not in line " + str(i))
i = i + 1
gui = Tk()
Button(gui, text="Retriever", command=setupsearch).grid(row = 5, column = 0)
mainloop( )
Answer: Each function that wants to change the value of the `searchterm` global
variable needs to declare `global searchterm`. The `global` statement doesn't
change properties of the variable itself—rather, it changes properties of the
function, specifically the way the current function sets and gets values for
the variable name in question.
You can get away with accessing a global variable from inside a function,
without declaring it global, provided (a) there is no local variable of the
same name to conflict with it, and (b) you don't need to change its global
value.
If you don't say `global searchterm` but then assign something to
`searchterm`, the function will simply create a local variable of that name.
|
Apply reduce on generator output with multiprocessing
Question: I have a generator function (Python) that works like this
def Mygenerator(x, y, z, ...):
while True:
# code that makes two matrices based on sequences of input arrays
yield (matrix1, matrix2)
What I want to do is to add the output from this generator. This line does the
job:
M1, M2 = reduce(lambda x, y: x[0] + y[0], x[1] + y[1], Mygenerator(x, y, z, ...))
I would like to parallelize this to speed up the computations. It is important
that the outputs from Mygenerator is reduced as it is yielded, since
`list(Mygenerator(...))` would take too much memory.
Answer: To answer my own question, I found a solution that seems to work as I had
hoped:
First, `Mygenerator` is no longer a generator but a function. Also, instead of
looping through segments of x, y and z, I now pass one segment to the function
at the time:
def Myfunction(x_segment, y_segment, z_segment):
# code that makes two matrices based on input arrays
return (matrix1, matrix2)
Using `multiprocessing.Pool` with the `imap` (generator) function seems to
work:
pool = multiprocessing.Pool(ncpus)
results = pool.imap(Myfunction,
( (x[i], y[i], z[i]) for i in range(len(x)) )
M1, M2 = reduce(lambda r1, r2: (r1[0] + r2[0], r1[1] + r2[1]),
(result for result in results))
pool.close()
pool.join()
where I changed the `x` and `y` in the lambda expression to `r1` and `r2` to
avoid confusion with the other variables with the same name. When trying to
use a generator with `multiprocessing` I got some trouble with pickle.
The only disappointment with this solution is that it didn't really speed up
the computations that much. I guess that has to do with overhead operations.
When using 8 cores, the processing speed was increased by approximately 10%.
When reducing to 4 cores the speed was doubled. This seems to be the best I
can do with my particular task, unless there is some other way of doing the
parallelizing...
The `imap` function was necessary to use here, since `map` would store all the
returned values in memory before the `reduce` operation, and in this case that
would not be possible.
|
Combination list python
Question: I want to make a list of all posible combinations of a list
example:
list = [1, 2, 3, 4]
and the output should give me: [[1], [2], [3], [4], [1, 2] ... [1, 2, 3, 4]]
(I have to look for a combination which sum gives me the highest possible
value which is less than or equal to variable B, in this case if B = 9 the
output that I would like to get is [2, 3, 4])
My current solution is to use loops which have a gives a value of either 0 or
1, when value == 1 the number is added to a list. The problem with this is
that the maximum amount of nested loops is lower then the amount of items in
my list, it is rather slow and this is absolutely not an elegant solution.
Can somebody help me?
Answer:
from itertools import combinations,chain
l= [1, 2, 3, 4]
print(list(chain.from_iterable(map(list,combinations(l,i)) for i in range(1,len(l)+1))))
[[1], [2], [3], [4], [1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4], [1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4], [1, 2, 3, 4]]
|
Difference between php and python mongodb adapter
Question: I have code in php which reads example record from mongodb:
<?php
$client = new MongoClient("mongodb://localhost:27017");
$db = $client->foo;
$collection = $db->bar;
$item = $collection->findOne();
var_dump($item);
And similar code in python:
import pymongo
client = pymongo.MongoClient('localhost', 27017)
db = client.foo
collection = db.bar
item = collection.find_one()
print(item)
When I run php script i get expected result:
array(11) {
'_id' => class MongoBinData#6 (2) {
public $bin => string(10) "somestring"
public $type => int(3)
}
'a' => double(62051.444165621)
'b' => int(974386)
'c' => string(10) "some string"
... some int, float and string fields ...
'tags' => array(0) {}
}
But, python script return error:
Traceback (most recent call last):
File "example.py", line 5, in <module>
item = collection.find_one()
File "/usr/local/lib/python2.7/dist-packages/pymongo/collection.py", line 724, in find_one
for result in cursor.limit(-1):
File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 1058, in next
if len(self.__data) or self._refresh():
File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 1002, in _refresh
self.__uuid_subtype))
File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 940, in __send_message
self.__compile_re)
File "/usr/local/lib/python2.7/dist-packages/pymongo/helpers.py", line 117, in _unpack_response
compile_re)
bson.errors.InvalidBSON: invalid length or type code
Why I can read data in php script and can't read data in python? Is it
possible to read this data in python?
Answer: Looks like you have stored some data in MongoDB that PyMongo considers
corrupt, but the PHP driver does not. If possible, please use "mongodump" to
dump only the offending document, or as few documents as possible, and attach
it to a new bug report. When you describe the problem, please tell us how you
**stored** the data: what driver version, what programming language, what code
you wrote to create the document. Register and click "Create Issue" at
<https://jira.mongodb.org/browse/PYTHON>
|
Intersection of two list in N time
Question: I have two lists `(['a', 's', 'f', 'f', 's'], ['f', 'f', 'a', 's'])`. The
required output is `['a','s','f','f']`. The output should give the
intersection of two lists. The arrangement of characters in the output list is
according to the order of occurrence in the first list `['a', 's', 'f', 'f',
's']`.
How can I implement this in python? I have already done this in N**2 time. Is
it possible to do this in N time?
My current solution:
def com(string1, string2):
string2_list=list(string2)
store=""
for check in string1:
for i,v in enumerate(string2_list):
if v==check:
store=store+check
del(string2_list[i])
return store
Answer: Use `collections.Counter`'s built-in intersection operation.
>>> l1, l2 = (['a', 's', 'f', 'f', 's'], ['f', 'f', 'a', 's'])
>>> import collections
>>> collections.Counter(l1) & collections.Counter(l2)
Counter({'f': 2, 'a': 1, 's': 1})
From here it is not hard to build a suitable list:
>>> counter = collections.Counter(l1) & collections.Counter(l2)
>>> out = list(counter.elements())
>>> print out
['a', 's', 'f', 'f']
Or, to order according to one of the lists:
>>> out = []
>>> for k in l1:
... if counter[k] > 0:
... counter[k] -= 1
... out.append(k)
...
>>> print out
['a', 's', 'f', 'f']
This is expected-time O(N): Counter creation is expected O(N) time, and
counter intersection is expected O(N) time as well.
|
Praw AttributeError: 'NoneType' object has no attribute 'get_comments'
Question: I wrote a simple script for identifying users who contribute to certain
subreddits. As a disclaimer, if you plan on using this code you should be sure
to anonymize the data (as I will, by aggregating data and removing all
usernames). It works with certain subreddits but does not seem to be very
robust, as seen by the following error I get when I run it with /r/nba:
AttributeError: 'NoneType' object has no attribute 'get_comments'
Below is my code:
import praw
import pprint
users = [] #[username, flair, comments]
r=praw.Reddit(user_agent="user_agent")
r.login("username", "password")
submissions = r.get_subreddit('nba').get_top(limit=1) #won't work with higher limit?
for submission in submissions:
submission.replace_more_comments(limit=3, threshold=5)
flat_comments = praw.helpers.flatten_tree(submission.comments)
for comment in flat_comments:
user_comments = []
for i in comment.author.get_comments(limit=2):
user_comments.append(i.body)
#user_comments.append(str(i.body)) #sometimes causes an error as well
users.append([str(comment.author), comment.author_flair_text, user_comments])
pprint.pprint(users)
When I change the subreddit to 'python' it seems to encounter less problems,
so hopefully someone can point out what I'm missing. Thanks in advance!
Answer: Ok, so you see the line
for i in comment.author.get_comments(limit=2):
I presume your code is failing because
comment.author is None
|
Cuda out of resources error when running python numbapro
Question: I am trying to run a cuda kernel in numbapro python, but I keep getting an out
of resources error. I then tried to execute the kernel into a loop and send
smaller arrays, but that still gave me the same error.
Here is my error message:
Traceback (most recent call last):
File "./predict.py", line 418, in <module>
predict[griddim, blockdim, stream](callResult_d, catCount, numWords, counts_d, indptr_d, indices_d, probtcArray_d, priorC_d)
File "/home/mhagen/Developer/anaconda/lib/python2.7/site-packages/numba/cuda/compiler.py", line 228, in __call__
sharedmem=self.sharedmem)
File "/home/mhagen/Developer/anaconda/lib/python2.7/site-packages/numba/cuda/compiler.py", line 268, in _kernel_call
cu_func(*args)
File "/home/mhagen/Developer/anaconda/lib/python2.7/site-packages/numba/cuda/cudadrv/driver.py", line 1044, in __call__
self.sharedmem, streamhandle, args)
File "/home/mhagen/Developer/anaconda/lib/python2.7/site-packages/numba/cuda/cudadrv/driver.py", line 1088, in launch_kernel
None)
File "/home/mhagen/Developer/anaconda/lib/python2.7/site-packages/numba/cuda/cudadrv/driver.py", line 215, in safe_cuda_api_call
self._check_error(fname, retcode)
File "/home/mhagen/Developer/anaconda/lib/python2.7/site-packages/numba/cuda/cudadrv/driver.py", line 245, in _check_error
raise CudaAPIError(retcode, msg)
numba.cuda.cudadrv.driver.CudaAPIError: Call to cuLaunchKernel results in CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES
Here is my source code:
from numbapro.cudalib import cusparse
from numba import *
from numbapro import cuda
@cuda.jit(argtypes=(double[:], int64, int64, double[:], int64[:], int64[:], double[:,:], double[:] ))
def predict( callResult, catCount, wordCount, counts, indptr, indices, probtcArray, priorC ):
i = cuda.threadIdx.x + cuda.blockIdx.x * cuda.blockDim.x
correct = 0
wrong = 0
lastDocIndex = -1
maxProb = -1e6
picked = -1
for cat in range(catCount):
probSum = 0.0
for j in range(indptr[i],indptr[i+1]):
wordIndex = indices[j]
probSum += (counts[j]*math.log(probtcArray[cat,wordIndex]))
probSum += math.log(priorC[cat])
if probSum > maxProb:
maxProb = probSum
picked = cat
callResult[i] = picked
predictions = []
counter = 1000
for i in range(int(math.ceil(numDocs/(counter*1.0)))):
docTestSliceList = docTestList[i*counter:(i+1)*counter]
numDocsSlice = len(docTestSliceList)
docTestArray = np.zeros((numDocsSlice,numWords))
for j,doc in enumerate(docTestSliceList):
for ind in doc:
docTestArray[j,ind['term']] = ind['count']
docTestArraySparse = cusparse.ss.csr_matrix(docTestArray)
start = time.time()
OPT_N = numDocsSlice
blockdim = 1024, 1
griddim = int(math.ceil(float(OPT_N)/blockdim[0])), 1
catCount = len(music_categories)
callResult = np.zeros(numDocsSlice)
stream = cuda.stream()
with stream.auto_synchronize():
probtcArray_d = cuda.to_device(numpy.asarray(probtcArray),stream)
priorC_d = cuda.to_device(numpy.asarray(priorC),stream)
callResult_d = cuda.to_device(callResult, stream)
counts_d = cuda.to_device(docTestArraySparse.data, stream)
indptr_d = cuda.to_device(docTestArraySparse.indptr, stream)
indices_d = cuda.to_device(docTestArraySparse.indices, stream)
predict[griddim, blockdim, stream](callResult_d, catCount, numWords, counts_d, indptr_d, indices_d, probtcArray_d, priorC_d)
callResult_d.to_host(stream)
#stream.synchronize()
predictions += list(callResult)
print "prediction %d: %f" % (i,time.time()-start)
Answer: I found out this was in the cuda procedure.
When you call predict the blockdim is set to 1024. predict[griddim, blockdim,
stream](callResult_d, catCount, numWords, counts_d, indptr_d, indices_d,
probtcArray_d, priorC_d)
But the procedure is called iteratively with slice sizes of 1000 elements not
1024. So, in the procedure it will attempt to write 24 elements that are out
of bounds in the return array.
Sending a number of elements parameter (n_el) and placing an error checking
call in the cuda procedure solves it.
@cuda.jit(argtypes=(double[:], int64, int64, int64, double[:], int64[:], int64[:], double[:,:], double[:] ))
def predict( callResult, n_el, catCount, wordCount, counts, indptr, indices, probtcArray, priorC ):
i = cuda.threadIdx.x + cuda.blockIdx.x * cuda.blockDim.x
if i < n_el:
....
|
generating emails group by tuple values python
Question: I have a tuple in the format (Name, email, units sold). I would like to
generate an HTML table, grouped by Name and then embed that table into an
email through Outlook.
My Code:
from itertools import groupby
from operator import itemgetter
import win32com.client
mytuple = [('Andrew','[email protected]','20'),('Jim',"[email protected]",'12'),("Sarah","[email protected]",'43'),("Jim","[email protected]",'15'),("Andrew","[email protected]",'56')]
mytuple = sorted(mytuple)
FULL_HTML = []
for name, rows in groupby(mytuple, itemgetter(0)):
table = []
for name, value2 in rows:
table.append(
"<tr><td>{}</td><td>{}</td></tr>".format(
name, value2 ))
html_code = "<html><table>" + str(table) + "</table></html>"
olMailItem = 0x0
obj = win32com.client.Dispatch("Outlook.Application")
newMail = obj.CreateItem(olMailItem)
newMail.Subject = "This is the subject"
newMail.HTMLBody = html_code
newMail.To = "[email protected]"
newMail.Display()
Desired output:
This would open 3 emails with HTML code in their body.
Email 1:
<html>
<table>
<tr><td>Andrew</td><td>20</td><td></tr>
<tr><td>Andrew</td><td>56</td><td></tr>
</table>
</html>
Email 2:
<html>
<table>
<tr><td>Jim</td><td>12</td><td></tr>
<tr><td>Jim</td><td>15</td><td></tr>
</table>
</html>
Email 3:
<html>
<table>
<tr><td>Sarah</td><td>43</td><td></tr>
</table>
</html>
Answer: Here's your problem:
for name, value2 in rows:
table.append(
"<tr><td>{}</td><td>{}</td></tr>".format(
name, value2 ))
Change this to:
for n, e, id in rows:
table.append(
"<tr><td>{}</td><td>{}</td></tr>".format(
n, id ))
html_code = "<html><table>" + ''.join(table) + "</table></html>"
The groupby function still returns 3-tuples.
|
Sending a URL in a GET request to a Python server on Google App Engine
Question: I have written a very simple server in Python on Google Apps engine. I want to
be able to send it a command via a GET request, such as
`"http://myserver.appspot.com/?do=http://webpage.com/?secondary=parameter"`
This does not work, as the secondary parameter gets interpreted separately and
sent to my app as well. Any help?
Answer: The url
`http://myserver.appspot.com/?do=http://webpage.com/?secondary=parameter` is
uncorrectly formed. Perhaps you can `urlencode` the string data and then send
it
from urllib import urlencode
data = {"do": "http://webpage.com/?secondary=parameter"}
encoded_data = urlencode(data)
url = "http://myserver.appspot.com/?" + encoded_data
Gives output
>>> print url
http://myserver.appspot.com/?do=http%3A%2F%2Fwebpage.com%2F%3Fsecondary%3Dparameter
Alternatively, if you are using python [`requests`](http://docs.python-
requests.org/en/latest/user/quickstart/#passing-parameters-in-urls) module,
you can do
import requests
payload = {"do": "http://webpage.com/?secondary=parameter"}
r = requests.get("http://myserver.appspot.com/", params=payload)
which gives output
>>> print r.url
u'http://myserver.appspot.com/?do=http%3A%2F%2Fwebpage.com%2F%3Fsecondary%3Dparameter'
|
Scrapy on Mac OS 10.10 tries to use Python 3.4
Question: I've had some trouble installing Scrapy on Yosemite. I've gotten all the
dependencies installed, but when I try to run scrapy I get this error.
$ scrapy crawl my_crawler
----------
File "/Library/Frameworks/Python.framework/Versions/3.4/bin/scrapy", line 5, in <module>
from pkg_resources import load_entry_point
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/pkg_resources.py", line 2697, in <module>
working_set.require(__requires__)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/pkg_resources.py", line 669, in require
needed = self.resolve(parse_requirements(requirements))
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/pkg_resources.py", line 572, in resolve
raise DistributionNotFound(req)
pkg_resources.DistributionNotFound: cryptography>=0.2.1
I know that scrapy doesn't support 3.4, but for some reason its trying to use
it. Anyone got any suggestions?
Answer: **I solved this yesterday on my server, but the solution was found using
Google Translate on Chinese websites**
pkg_resources.DistributionNotFound: cryptography>=0.2.1
This problem indicates that you are missing a package on your distribution
called libffi-dev.
Please locate that package for OSX and install it. Use the easy_install
utility to install the cryptography 0.2.2 package for Python.
You're scrapy application should work after you completely meet the
dependencies.
Python is masking the true dependency issue by reporting it as a problem with
the cryptography packages, when in fact it is a missing [libffi-
dev](https://trac.macports.org/browser/trunk/dports/devel/libffi/Portfile)
package for OSX. You may explicitly need the DEV package for libffi.
Good luck! I was able to solve this by meeting the libffi dependency.
|
How can I optimize this double-loop over an array using numpy?
Question: This code is quite slow in Python. How can I optimize this using numpy. The
array m and z are already numpy arrays but I assume I need to vectorize this
somehow though I can't find an example where the vectorized function also has
access to the value coordinates.
for i in xrange(states):
for j in xrange(states):
if i != j and z[i, j] != 0 and m[i, j] < 0.0:
m[i, i] += m[i, j]
m[i, j] = 0.0
z[i, j] = 0
Answer: You can translate your code to vectorized Numpy using arrays of indices:
import numpy as np
i, j = np.indices([states, states])
bool_index = (i != j) & (z != 0) & (m < 0.0)
z[bool_index] = 0
But since you already know what `i != j` will evaluate to, it's faster to just
use a diagonal array. This also makes it easier to do the slightly awkward
operation on `m`:
I = np.eye(states, dtype=bool)
bool_index = ~I & (z != 0) & (m < 0.0)
m[I] += (bool_index * m).sum(axis=1)
m[bool_index] = 0.0
z[bool_index] = 0
Note that the `&` operator does `np.bitwise_and` and not `np.logical_and` but
they're equivalent in this case, because all operands are Boolean arrays.
|
Calculate the frequency of words in python
Question: I have to calculate the frequency of each word which is there in text file if
it matches with the word which is there in an array but i am getting this
error **TypeError: unhashable type: 'list'**
import string
from collections import Counter
from array import *
cnt=Counter()
word =[ ]
word_count = [ ]
new_array =['CC','CD','DT','EX','FW','IN','JJ','JJR','JJS','LS','MD','NN','NNS','NNP','NNPS','PDT',
'POS','PRP','PRP','RB','RBR','RBS','RP','SYM','TO','UH','VB','VBD','VBZ','WDT','WP','WP','WRB']
file = open('output.txt', 'rU')
for line in file:
new_line = line.replace("_"," ")
words = new_line.split()
word.append(words)
[(w, word.count(w)) for w in set(word) if w in new_array]
Answer: When you do `word.append(words)`, you are appending a list to a list, there by
making a list of lists. As a list is not hashable, a list of lists cannot be
converted into a set and you were getting that error.
I think you were intending to do `word += words` instead.
|
wget not working in python
Question: I am using the os module to issue a wget request through python. It looks
something like this:
os.system("wget 'http://superawesomeurl.com'")
If I issue the wget request straight from terminal, it works, but I have two
problems:
1. When I build this in sublime, it give me the error: `sh: wget: command not found`
2. When I enter this into a python shell command line it sends the request but comes back bad: `400 bad request`
I noticed that other people don't use the quotes around the url, but in
terminal this is the only way it works. I am using python 2.7.8 and running
Yosemite.
Answer: Your code should work if wget is on your PYTHONPATH.
## But seriously, do not use wget in Python!
Better use a Python-native function like urlopen:
<https://docs.python.org/2/library/urllib2.html#urllib2.urlopen> It's as
simple as this:
from urllib2 import urlopen
response = urlopen("http://stackoverflow.com").read()
Now `response` contains the whole contents of the html page. You can also use
`readlines()` if you wanted to iterate over it line by line. To save the html
file to disk use:
download = open("index.html", "w")
download.write(response.read())
download.close()
|
keep only lowest value per row in a Python Pandas dataset
Question: In a Pandas dataset I only want to keep the lowest value per line. All other
values should be deleted. I need the original dataset intact. Just remove all
values (replace by NaN) which are not the minimum.
What is the best way to do this - speed/performance wise.
I can also transpose the dataset if the operation is easier per column.
Thanks Robert
Answer: Since the operation you are contemplating does not rely on the columns or
index, it might be easier (and faster) to do this using NumPy rather than
Pandas.
You can find the location (i.e. column index) of the minimums for each row
using
idx = np.argmin(arr, axis=1)
You could then make a new array filled with NaNs and copy the minimum values
to the new array.
* * *
import numpy as np
import pandas as pd
def nan_all_but_min(df):
arr = df.values
idx = np.argmin(arr, axis=1)
newarr = np.full_like(arr, np.nan, dtype='float')
newarr[np.arange(arr.shape[0]), idx] = arr[np.arange(arr.shape[0]), idx]
df = pd.DataFrame(newarr, columns=df.columns, index=df.index)
return df
df = pd.DataFrame(np.random.random((4,3)))
print(df)
# 0 1 2
# 0 0.542924 0.499702 0.058555
# 1 0.682663 0.162582 0.885756
# 2 0.389789 0.648591 0.513351
# 3 0.629413 0.843302 0.862828
df = nan_all_but_min(df)
print(df)
yields
0 1 2
0 NaN NaN 0.058555
1 NaN 0.162582 NaN
2 0.389789 NaN NaN
3 0.629413 NaN NaN
* * *
Here is a benchmark comparing `nan_all_but_min` vs `using_where`:
def using_where(df):
return df.where(df.values == df.min(axis=1)[:,None])
In [73]: df = pd.DataFrame(np.random.random(100*100).reshape(100,100))
In [74]: %timeit using_where(df)
1000 loops, best of 3: 701 µs per loop
In [75]: %timeit nan_all_but_min(df)
10000 loops, best of 3: 105 µs per loop
* * *
Note that `using_where` and `nan_all_but_min` behave differently if a row
contains the same min value more than once. `using_where` will preserve all
the mins, `nan_all_but_min` will preserve only one min. For example:
In [76]: using_where(pd.DataFrame([(0,0,1), (1,2,1)]))
Out[76]:
0 1 2
0 0 0 NaN
1 1 NaN 1
In [77]: nan_all_but_min(pd.DataFrame([(0,0,1), (1,2,1)]))
Out[77]:
0 1 2
0 0 NaN NaN
1 1 NaN NaN
|
Python os.walk() loop directories for attribute
Question: I have a text file containing directory names on each line (1, 2, 3), how can
I iterate through the text file and have the result inserted into os.walk?
So far, I have
import os
from os import listdir
dir_file = open("list.txt", "r")
for root, dirs, files in os.walk(dir_file):
for name in files:
print(os.path.join(root, name))
for name in dirs:
print(os.path.join(root, name))
I have used a combination of while loops and for loops and if statements to
try and perform this, but I've had no luck.
Any help?
Thanks
Answer: How about:
rdf = []
for fff in dir_file:
for r, d, f in os.walk(fff):
rdf.append(r, d, f)
|
Access HTTP Header Details Through Python Instagram API
Question: I'm using the Instagram API to retrieve all photos from a list of hashtags.
Starting today, I've been hitting the API rate limits (429 error,
specifically). To debug this, I've been trying to see how to get the number of
calls I have left per hour and incorporate that into my script.
The Instagram API says that you can access the number of calls left in the
hour through the HTTP header, but I'm not sure how to access that in Python.
> The following fields are provided in the header of each response and their
> values are related to the type of call that was made (authenticated or
> unauthenticated):
>
> X-Ratelimit-Remaining: the remaining number of calls available to your app
> within the 1-hour window
>
> X-Ratelimit-Limit: the total number of calls allowed within the 1-hour
> window
<http://instagram.com/developer/limits>
How would I access this data in Python?
Answer: I assumed it was much a much fancier solution based on a few other answers on
SO, but after some researching, I found a really simple solution!
import requests
r = requests.get('URL of the API response here')
r.headers
|
Ruby gem equivalent of "pip install -e"?
Question: In Python I can install a package from source in ["editable"
mode](https://pip.pypa.io/en/latest/reference/pip_install.html#editable-
installs) using `pip install -e`. Then I can carry on editing the code, and
any changes will be automatically picked by other Python scripts that `import
library`
Is there a comparable workflow for developing Ruby gems? What is the "Ruby
way" of using libs as they are being developed rather than, for example,
compiling and installing a gem every time I make a change to the source?
Answer: There are two common approaches one might use with `bundler`:
1. one executes `bundle install --path vendor/bundle` and _does not run`bundle update` unless everything is tested_.
2. one tells a bundler to use a local version of the gem:
* in `Gemfile` (this is not supported in `mymaingem.gemspec` due to rubygems maintainence issues): `gem 'mycutegem', :git => 'git://github.com/myname/mycutegem', :branch => 'master'`;
* in command line: `bundle config local.mycutegem /path_to_local_git/mycutegem`.
The first approach will download everything into subfolder of your current
project (here it’d be `vendor/bundle`.) Feel free to modify everything there,
it’ll be reflected.
The second approach is likely better. You are to clone the gem from github and
instruct `bundle` to use your local clone of the respective git repository.
This approach provides you with an ability to publish the changes to your main
gem into the repository. As soon as dependent repo is published as well, the
up-to-date version will be retrieven by your gem subscribers, assuming they
have not instructed their `bundler`s to use their locals.
Hope this helps.
|
Connect Python to MS SQL Server using pyodbc
Question: I am having a problem connecting pyodbc to my SQL Server. When I run it, there
is no output at all and there is not error message or anything to tell me what
is wrong? Even after I hit enter a few times nothing?
import pyodbc
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=marketing-sql01.onlive.corp;DATABASE=grok;UID=austin.trombley;PWD=XXXX')
cursor = cnxn.cursor()
cursor.execute("select * from user")
rows = cursor.fetchall()
for row in rows:
print row.user_id, row.user_name
Answer: Try...
...
for row in rows:
print row['user_id'], row['user_name']
|
Python : redirected message order
Question: I can redirect Python script output simply with ">" character in command line.
However, if Python script has subprocess.call(), the order of output lines is
missed.
test.py
import subprocess
print("Message from Python... this should appear at 1st line")
subprocess.call(r"c:\src\python\redirect2\hi.bat")
hi.bat
@echo off
echo Message from batch file. this should appear at 2nd line.
Below is the message I expect.
C:\src\python\redirect2>\Python34\python.exe test.py
Message from Python... this should appear at 1st line
Message from batch file. this should appear at 2nd line.
However, once I redirect its output, the order of these lines got swapped.
C:\src\python\redirect2>\Python34\python.exe test.py > console.txt
C:\src\python\redirect2>type console.txt
Message from batch file. this should appear at 2nd line.
Message from Python... this should appear at 1st line
Does anyone know how to prevent this ? Putting sleep() doesn't seem help. I'm
using Windows 8.1.
Answer: you should use subprocess.Popen instead, so you can capture the output.
import subprocess
print("Message from Python... this should appear at 1st line")
p = subprocess.Popen("c:\src\python\redirect2\hi.bat", stdout=subprocess.PIPE)
out, err = p.communicate()
print out
|
Get the length of each line in file with C and write in output file
Question: I am a biology student and I am trying to learn perl, python and C and also
use the scripts in my work. So, I have a file as follows:
>sequence1
ATCGATCGATCG
>sequence2
AAAATTTT
>sequence3
CCCCGGGG
The output should look like this, that is the name of each sequence and the
count of characters in each line and printing the total number of sequences in
the end of the file.
sequence1 12
sequence2 8
sequence3 8
Total number of sequences = 3
I could make the perl and python scripts work, this is the python script as an
example:
#!/usr/bin/python
import sys
my_file = open(sys.argv[1]) #open the file
my_output = open(sys.argv[2], "w") #open output file
total_sequence_counts = 0
for line in my_file:
if line.startswith(">"):
sequence_name = line.rstrip('\n').replace(">","")
total_sequence_counts += 1
continue
dna_length = len(line.rstrip('\n'))
my_output.write(sequence_name + " " + str(dna_length) + '\n')
my_output.write("Total number of sequences = " + str(total_sequence_counts) + '\n')
Now, I want to write the same script in C, this is what I have achieved so
far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
input = FILE *fopen(const char *filename, "r");
output = FILE *fopen(const char *filename, "w");
double total_sequence_counts = 0;
char sequence_name[];
char line [4095]; // set a temporary line length
char buffer = (char *) malloc (sizeof(line) +1); // allocate some memory
while (fgets(line, sizeof(line), filename) != NULL) { // read until new line character is not found in line
buffer = realloc(*buffer, strlen(line) + strlen(buffer) + 1); // realloc buffer to adjust buffer size
if (buffer == NULL) { // print error message if memory allocation fails
printf("\n Memory error");
return 0;
}
if (line[0] == ">") {
sequence_name = strcpy(sequence_name, &line[1]);
total_sequence_counts += 1
}
else {
double length = strlen(line);
fprintf(output, "%s \t %ld", sequence_name, length);
}
fprintf(output, "%s \t %ld", "Total number of sequences = ", total_sequence_counts);
}
int fclose(FILE *input); // when you are done working with a file, you should close it using this function.
return 0;
int fclose(FILE *output);
return 0;
}
But this code, of course is full of mistakes, my problem is that despite
studying a lot, I still can't properly understand and use the memory
allocation and pointers so I know I especially have mistakes in that part. It
would be great if you could comment on my code and see how it can turn into a
script that actually work. By the way, in my actual data, the length of each
line is not defined so I need to use malloc and realloc for that purpose.
Answer: For a simple program like this, where you look at short lines one at a time,
you shouldn't worry about dynamic memory allocation. It is probably good
enough to use local buffers of a reasonable size.
Another thing is that C isn't particularly suited for quick-and-dirty string
processing. For example, there isn't a `strstrip` function in the standard
library. You usually end up implementing such behaviour yourself.
An example implementation looks like this:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAXLEN 80 /* Maximum line length, including null terminator */
int main(int argc, char *argv[])
{
FILE *in;
FILE *out;
char line[MAXLEN]; /* Current line buffer */
char ref[MAXLEN] = ""; /* Sequence reference buffer */
int nseq = 0; /* Sequence counter */
if (argc != 3) {
fprintf(stderr, "Usage: %s infile outfile\n", argv[0]);
exit(1);
}
in = fopen(argv[1], "r");
if (in == NULL) {
fprintf(stderr, "Couldn't open %s.\n", argv[1]);
exit(1);
}
out = fopen(argv[2], "w");
if (in == NULL) {
fprintf(stderr, "Couldn't open %s for writing.\n", argv[2]);
exit(1);
}
while (fgets(line, sizeof(line), in)) {
int len = strlen(line);
/* Strip whitespace from end */
while (len > 0 && isspace(line[len - 1])) len--;
line[len] = '\0';
if (line[0] == '>') {
/* First char is '>': copy from second char in line */
strcpy(ref, line + 1);
} else {
/* Other lines are sequences */
fprintf(out, "%s: %d\n", ref, len);
nseq++;
}
}
fprintf(out, "Total number of sequences. %d\n", nseq);
fclose(in);
fclose(out);
return 0;
}
A lot of code is about enforcing arguments and opening and closing files. (You
could cut out a lot of code if you used `stdin` and `stdout` with file
redirections.)
The core is the big `while` loop. Things to note:
* `fgets` returns `NULL` on error or when the end of file is reached.
* The first lines determine the length of the line and then remove white-space from the end.
* It is not enough to decrement length, at the end the stripped string must be terminated with the null character `'\0'`
* When you check the first character in the line, you should check against a char, not a string. In C, single and double quotes are not interchangeable. `">"` is a string literal of two characters, `'>'` and the terminating `'\0'`.
* When dealing with countable entities like chars in a string, use integer types, not floating-point numbers. (I've used (signed) `int` here, but because there can't be a negative number of chars in a line, it might have been better to have used an unsigned type.)
* The notation `line + 1` is equivalent to `&line[1]`.
* The code I've shown doesn't check that there is always one reference per sequence. I'll leave this as exercide to the reader.
For a beginner, this can be quite a lot to keep track of. For small text-
processing tasks like yours, Python and Perl are definitely better suited.
**Edit** : The solution above won't work for long sequences; it is restricted
to `MAXLEN` characters. But you don't need dynamic allocation if you only need
the length, not the contents of the sequences.
Here's an updated version that doesn't read lines, but read characters
instead. In `'>'` context, it stored the reference. Otherwise it just keeps a
count:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h> /* for isspace() */
#define MAXLEN 80 /* Maximum line length, including null terminator */
int main(int argc, char *argv[])
{
FILE *in;
FILE *out;
int nseq = 0; /* Sequence counter */
char ref[MAXLEN]; /* Reference name */
in = fopen(argv[1], "r");
out = fopen(argv[2], "w");
/* Snip: Argument and file checking as above */
while (1) {
int c = getc(in);
if (c == EOF) break;
if (c == '>') {
int n = 0;
c = fgetc(in);
while (c != EOF && c != '\n') {
if (n < sizeof(ref) - 1) ref[n++] = c;
c = fgetc(in);
}
ref[n] = '\0';
} else {
int len = 0;
int n = 0;
while (c != EOF && c != '\n') {
n++;
if (!isspace(c)) len = n;
c = fgetc(in);
}
fprintf(out, "%s: %d\n", ref, len);
nseq++;
}
}
fprintf(out, "Total number of sequences. %d\n", nseq);
fclose(in);
fclose(out);
return 0;
}
Notes:
* `fgetc` reads a single byte from a file and returns this byte or `EOF` when the file has ended. In this implementation, that's the only reading function used.
* Storing a reference string is implemented via `fgetc` here too. You could probably use `fgets` after skipping the initial angle bracket, too.
* The counting just reads bytes without storing them. `n` is the total count, `len` is the count up to the last non-space. (Your lines probably consist only of ACGT without any trailing space, so you could skip the test for space and use `n` instead of `len`.)
|
How to override a function in a package?
Question: I am using a package from `biopython` called `SubsMat`, I want to override a
function that is located in SubsMats `__init__.py`.
I tried making a class that inherits `SubsMat` like this:
from Bio import SubsMat
class MyOwnSubsMat(SubsMat):
but you cannot inherit a package I guess. I cannot alter the source code
literally since it is a public package on the network. Is there any workaround
for a noob like me?
Answer: You can do that:
from Bio import SubsMat
SubsMat.function = my_own_replacement_for_function
But it will change the package for everyone using it.
|
Python - Metmatplotlib error
Question: I am using Windows 7. I have installed Python 3.4 and Metmatplotlib.
I have tried the below code
from pylab import *
plot([1,2,3])
show()
But i am getting the follwoign error
Traceback (most recent call last):
File "E:/Work/Python/Training/Samples.py", line 1, in <module>
from pylab import *
File "C:\Python34\lib\site-packages\pylab.py", line 1, in <module>
from matplotlib.pylab import *
File "C:\Python34\lib\site-packages\matplotlib\__init__.py", line 169, in <module>
from urllib2 import urlopen
ImportError: No module named 'urllib2'
I have searched for the package urllib2 but not seems to be find it.
Can any one help me
Thanks,
Answer: The urllib2 module has been split across several modules in Python 3 named
urllib.request and urllib.error. The 2to3 tool will automatically adapt
imports when converting your sources to Python 3.
<https://docs.python.org/2/library/urllib2.html>
|
Best way to handle multiple table query linked to "main" table
Question: I am tracking visitor sessions and have a "master" table that contains the
session start, end and some visitor info.
CREATE TABLE "sessions" (
session_id BIGSERIAL PRIMARY KEY,
session_start TIMESTAMP NOT NULL,
session_end TIMESTAMP NOT NULL
user_ip TEXT NOT NULL,
user_agent TEXT NOT NULL
)
For each session I have three metrics - pageviews, downloads and video plays.
Each table follows this formula
CREATE TABLE "sessions_<x>" (
session_id BIGINT REFERENCES sessions (session_id),
data_1 TEXT NOT NULL,
data_2 TEXT NOT NULL,
...
)
The three tables are not identical, but the data itself is not important - the
only thing they share is the `session_id` reference to the `sessions` table.
Data is inserted so, in a single transaction, the relevant
pageview/download/video play record is added and the `session_start` /
`session_end` is updated.
For my code, I wish to extract each session with associated pageviews,
downloads and video plays. In an effort to minimize the number of queries I
figured I'd do the following:
1. Do a query on the `sessions` table to get the identifying information + `session_id` for each session.
2. For each of the three metric tables, do a `SELECT * FROM table WHERE session_id IN (<sessions>)`
3. In code, "collect" the data from each result set from #2 and associate it with the base session information.
I am wondering if this is the best approach. I have some worries that for
large data sets this might be a bad idea (lots of in-memory data at a time),
but is there an alternative where I can in one query get session information +
associated metrics (for all three tables) easily? Or at least in a way where I
can iterate through it in my program one session at a time?
This is not a user-facing web service, so super-fast, sub-second replies are
not the goal, but performance is a factor. The service is being built in
python if it matters and I am using postgresql 9.2.
Answer: Try:
SELECT * FROM session s
LEFT OUTER JOIN session_<x> sx
ON s.session_id = sx.session_id
LEFT OUTER JOIN session_<y> sy
ON s.session_id = sy.session_id;
|
Process hangs on urllib2 socket reset
Question: We have a server program which occasionally hangs in a `read` call on a
`urllib2` socket when getting a connection reset, like so:
Traceback (most recent call last):
File "run.py", line 112, in fetch_stuff
raw = response.read()
File "/usr/lib/python2.7/socket.py", line 351, in read
data = self._sock.recv(rbufsize)
File "/usr/lib/python2.7/httplib.py", line 573, in read
s = self.fp.read(amt)
File "/usr/lib/python2.7/socket.py", line 380, in read
data = self._sock.recv(left)
error: [Errno 104] Connection reset by peer
Edit: With hang I mean the program doesn't crash and is still active a couple
of hours later, however, it seems that it's still stuck after having printed
that one error message.
However, AFAIK the code handles outside of the library handles exceptions
correctly:
for i in range(retries):
try:
response = urllib2.urlopen(url)
raw = response.read() # fails here
...
except urllib2.HTTPError as e:
logging.error("HTTP Error for url=%s (code=%s, message=%s, headers=%s)" % (url, e.code, e.msg, e.hdrs))
except Exception as e:
logging.exception(e)
else:
logging.error(('Connection failed after {} tries').format(retries))
sys.exit(0)
I can't see why this would hang the entire process with no further progress.
We're now trying to set the `timeout` parameter to `urlopen`, but I'm having
my doubts that that will fix the issue.
So, since I've found no useful links thus far ([except maybe this
answer](https://stackoverflow.com/questions/5565291/detecting-hangs-with-
python-urllib2-urlopen)), is there an (obvious) fix for this, should we use
another library, ...?
Also, what actually happens? I get that the connection is reset, but what
happens next?
Answer: The read call is blocking unless you are working on a non-blocking socket.
Therefore, your process is blocked on the read() call.
For some reason, the other side of the connection sends a packet with the RST
flag set, closing the connection. When the OS detects this event, the recv
system call returns with ECONNRESET, defined in linux/include/errno.h and
corresponding to error code 104.
Python translates the error code with the errno module
(<https://docs.python.org/2/library/errno.html#module-errno>) and raises an
Exception. Error code 104 is, as expected, errno.ECONNRESET:
>>> import errno
>>> print errno.ECONNRESET
104
You are then catching that exception and calling
logging.exception(e)
which prints the stack trace. Afterwards, either you keep on looping or you
follow the else branch. Given your output, it is not clear to me what happens.
This can be easily reproduced. Very simple client code:
import urllib2
import logging
r = urllib2.urlopen("http://localhost:8080")
try:
print "Reading!"
r.read()
except Exception as e:
logging.exception(e)
On the server side, directly from the command line:
➜ ~ [1] at 22:50:53 [Wed 12] $ nc -l -p 8080
Once the connection is established, the client blocks on the read call.
tcpkill can be used to kill the connection with a RST flag once some traffic
is detected:
~ [1] at 22:51:19 [Wed 12] $ sudo tcpkill -i lo port 8080
And, as expected, the result on the client side is:
➜ ~ [1] at 23:12:37 [Wed 12] $ python m.py
Reading!
ERROR:root:[Errno 104] Connection reset by peer
Traceback (most recent call last):
File "m.py", line 7, in <module>
r.read()
File "/usr/lib/python2.7/socket.py", line 351, in read
data = self._sock.recv(rbufsize)
File "/usr/lib/python2.7/httplib.py", line 561, in read
s = self.fp.read(amt)
File "/usr/lib/python2.7/httplib.py", line 1302, in read
return s + self._file.read(amt - len(s))
File "/usr/lib/python2.7/socket.py", line 380, in read
data = self._sock.recv(left)
error: [Errno 104] Connection reset by peer
Adding a timeout would not solve much. If your connection is reset while your
process is blocked on the read call (even if with a timeout) the outcome will
be exactly the same. I think you should first of all try to understand why the
connection is being reset. But reading on a socket which has been closed with
a RST flag is an event that you can't avoid and you should handle.
|
Again urllib.error.HTTPError: HTTP Error 400: Bad Request
Question: Hy! I tried to open web-page, that is normally opening in browser, but python
just swears and does not want to work.
import urllib.request, urllib.error
f = urllib.request.urlopen('http://www.booking.com/reviewlist.html?cc1=tr;pagename=sapphire')
And another way
import urllib.request, urllib.error
opener=urllib.request.build_opener()
f=opener.open('http://www.booking.com/reviewlist.html?cc1=tr;pagename=sapphi
re')
Both options give one type of error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python34\lib\urllib\request.py", line 461, in open
response = meth(req, response)
File "C:\Python34\lib\urllib\request.py", line 571, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python34\lib\urllib\request.py", line 493, in error
result = self._call_chain(*args)
File "C:\Python34\lib\urllib\request.py", line 433, in _call_chain
result = func(*args)
File "C:\Python34\lib\urllib\request.py", line 676, in http_error_302
return self.parent.open(new, timeout=req.timeout)
File "C:\Python34\lib\urllib\request.py", line 461, in open
response = meth(req, response)
File "C:\Python34\lib\urllib\request.py", line 571, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python34\lib\urllib\request.py", line 499, in error
return self._call_chain(*args)
File "C:\Python34\lib\urllib\request.py", line 433, in _call_chain
result = func(*args)
File "C:\Python34\lib\urllib\request.py", line 579, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 400: Bad Request
Any ideas?
Answer: This URL seems to be doing user agent string checking. If I adjust my user
agent string in Firefox to `Python-urllib/2.7`, it fails with the `Bad
Request` you are seeing.
As you are using `urllib`, you can adjust the User Agent following this
[tutorial](http://wolfprojects.altervista.org/articles/change-urllib-user-
agent/)
from urllib.request import FancyURLopener
class MyOpener(FancyURLopener):
version = 'My new User-Agent' # Set this to a string you want for your user agent
myopener = MyOpener()
page = myopener.open('http://www.booking.com/reviewlist.html?cc1=tr;pagename=sapphire')
|
python return list from linux command output
Question: I am new to python and I'm learning rapidly, but this is beyond my current
level of understanding. I'm trying to to pull the output from the linux
command apcaccess into a list in python.
apcaccess is a linux command to get the status of an APC UPS. The output is
this:
$ apcaccess
APC : 001,035,0933
DATE : 2014-11-12 13:38:27 -0500
HOSTNAME : doormon
VERSION : 3.14.10 (13 September 2011) debian
UPSNAME : UPS
CABLE : USB Cable
DRIVER : USB UPS Driver
UPSMODE : Stand Alone
STARTTIME: 2014-11-12 12:28:00 -0500
MODEL : Back-UPS ES 550G
STATUS : ONLINE
LINEV : 118.0 Volts
LOADPCT : 15.0 Percent Load Capacity
BCHARGE : 100.0 Percent
TIMELEFT : 46.0 Minutes
MBATTCHG : 5 Percent
MINTIMEL : 3 Minutes
MAXTIME : 0 Seconds
SENSE : Medium
LOTRANS : 092.0 Volts
HITRANS : 139.0 Volts
ALARMDEL : 30 seconds
BATTV : 13.6 Volts
LASTXFER : No transfers since turnon
NUMXFERS : 2
XONBATT : 2014-11-12 12:33:35 -0500
TONBATT : 0 seconds
CUMONBATT: 53 seconds
XOFFBATT : 2014-11-12 12:33:43 -0500
STATFLAG : 0x07000008 Status Flag
SERIALNO : 4B1335P17084
BATTDATE : 2013-08-28
NOMINV : 120 Volts
NOMBATTV : 12.0 Volts
FIRMWARE : 904.W1 .D USB FW:W1
END APC : 2014-11-12 13:38:53 -0500
I've tried different iterations of `Popen` such as:
def check_apc_ups():
output = subprocess.Popen("apcaccess", stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
x1, x2, x3, x4, x5 = output
I would like to be able to pull each line into a list or tuple containing all
32 and then only display/print what I need, such as `TIMELEFT` and `BCHARGE`.
Any help would be greatly appreciated.
Answer:
from subprocess import check_output
out = check_output(["apcaccess"])
spl = [ele.split(":",1)for ele in out.splitlines()]
d = {k.rstrip():v.lstrip() for k,v in spl}
print(d['BCHARGE'])
print(d["TIMELEFT"])
100.0 Percent
46.0 Minutes
from subprocess import check_output
def get_apa():
out = check_output(["apcaccess"])
spl = [ele.split(":", 1) for ele in out.splitlines()]
d = {k.rstrip(): v.lstrip() for k, v in spl}
return d
output = get_apa()
print (output['BCHARGE'])
100.0 Percent
To print all key/values pairings:
for k,v in get_apa().items():
print("{} = {}".format(k,v))
|
Faster way to build a tree graph using Networkx Python?
Question: Is there any faster, nicer way of building a Networkx tree. Currently, my code
is
for numb in range(0,len(previous)):
nodos = list(chunks(current,3))
for i in range(0,3):
G.add_edge(previous[numb],nodos[numb][i])
This works in the following way: 1. The tree has 3 branches (or edges). I have
two arrays:
previous = [x,y,z] #These nodes have already been added to the graph
current = [xx,xy,xz, xy,yy,yz, xz,yz,zz] #This nodes need to be added.
Ideally, I should do the following:
1. Start with x in previous:
1.1 Pick the first 3 nodes in current (i.e. xx,xy,xz)
1.1.1 Add the nodes-edges: x->xx, x->xy, x->xz
So far my codes does:
1. Start with x in previous
2. Partition current into chunks of 3 items: [[xx,xy,xz], [xy,yy,yz], [xz,yz,zz]]
3. Loop through all the nodes in these chunks:
4. Add x->xx, loop again, add x->xy... etc.
My implementation is extremely inefficient. How would you do this efficiently?
Thank you
Answer: You could use the helper function from
<https://github.com/networkx/networkx/blob/master/networkx/generators/classic.py#L50>
def _tree_edges(n,r):
# helper function for trees
# yields edges in rooted tree at 0 with n nodes and branching ratio r
nodes=iter(range(n))
parents=[next(nodes)] # stack of max length r
while parents:
source=parents.pop(0)
for i in range(r):
try:
target=next(nodes)
parents.append(target)
yield source,target
except StopIteration:
break
print list(_tree_edges(13,3))
#[(0, 1), (0, 2), (0, 3), (1, 4), (1, 5), (1, 6), (2, 7), (2, 8), (2, 9), (3, 10), (3, 11), (3, 12)]
import networkx as nx
G = nx.Graph(_tree_edges(13,3))
If you want nodes other than integers you can either relabel or specify them
on input like this
def _tree_edges(nodes,r):
# helper function for trees
# yields edges in rooted tree with given nodes and branching ratio r
nodes=iter(nodes)
parents=[next(nodes)] # stack of max length r
while parents:
source=parents.pop(0)
for i in range(r):
try:
target=next(nodes)
parents.append(target)
yield source,target
except StopIteration:
break
nodes = list('abcdefghijklm')
print list(_tree_edges(nodes,3))
|
Pygame - How to stop an image from leaving the edge of the screen?
Question: A section of jetfighterx leaves the screen when the mouse hovers over the edge
of the window, this causes tarantula to explode from time to time as soon as
it respawns to the top of the window, how can I stop this from happening
(without the use of classes)?
Code:
import pygame, sys, pygame.mixer
from pygame.locals import *
import random
pygame.init()
bif = "space.jpg"
jf = "spacefightersprite.png"
enemy = "TarantulaSpaceFighter.png"
laser = pygame.mixer.Sound("LaserBlast.wav")
explosionsound = pygame.mixer.Sound("Explosion.wav")
screen = pygame.display.set_mode((1000,900),0,32)
caption = pygame.display.set_caption("Jet Fighter X")
background = pygame.image.load(bif).convert()
jetfighterx = pygame.image.load(jf)
jetfighterx = pygame.transform.scale(jetfighterx, (400,400))
tarantula = pygame.image.load(enemy)
tarantula = pygame.transform.scale(tarantula, (100,100))
laserblast = pygame.image.load("C:\Python27\laser.png")
explosion=pygame.image.load("C:\Python27\explosion.png")
explosion=pygame.transform.scale(explosion, (150,150))
ex,ey = 450,0
movex,movey = 0,0
clock = pygame.time.Clock()
speed = 300
shoot_y = 0
laser_fired = False
collision = False
alive = True
explo_timer = 25
while True:
pygame.mouse.set_visible(False)
mx,my = pygame.mouse.get_pos()
jetfighterx_rect = jetfighterx.get_rect(center=(mx, my))
jetfighterx_rect = jetfighterx_rect.inflate(-200,-200)
tarantula_rect = tarantula.get_rect(center=(ex, ey))
tarantula_rect = tarantula_rect.inflate(-180,-200)
# Check for player inputs
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_ESCAPE or event.key == K_q:
sys.exit()
if event.type == MOUSEBUTTONDOWN:
laser_fired = True
laser.play()
shoot_y = my-200
shoot_x = mx-16
# Update Game
milli = clock.tick()
seconds = milli/1000.
dmy = seconds * speed
ey += dmy
if ey > 900:
explo_timer = 25
collision = False
alive = True
ey = 0
ex = random.randint(50,900)
if laser_fired:
shoot_y -= 10
if shoot_y < 0:
laser_fired = False
else:
laserblast_rect = laserblast.get_rect(center=(shoot_x, shoot_y))
if laserblast_rect.colliderect(tarantula_rect):
explosionsound.play()
collision = True
alive = False
if jetfighterx_rect.colliderect(tarantula_rect) and alive:
explosionsound.play()
collision = True
alive = False
# Draw on screen
screen.blit(background, (0,0))
screen.blit(jetfighterx,(mx-200,my-200))
if not collision:
screen.blit(tarantula, (ex, ey))
elif collision:
explo_timer-=2
if explo_timer > 0 and alive == False:
screen.blit(explosion, (ex, ey-50))
if laser_fired:
screen.blit(laserblast, (shoot_x, shoot_y))
pygame.display.update()
Answer: Just add a limit that does not allow the fighter to move within x pixels of
the border.
Assuming that the x,y coordinates of the centre of your fighter are
jetfighter_x, jetfighter_y (You will need to change the variable names to
whatever your code has) then write something like this:
LBuffer = 16
RBuffer = 1000 - 16
TBuffer = 900 - 16
BBuffer = 16
if jetfighter_x > RBuffer:
jetfighter_x = RBuffer
if jetfighter_x < LBuffer:
jetfighter_x = LBuffer
if jetfighter_y > TBuffer:
jetfighter_y = TBuffer
if jetfighter_y < BBuffer:
jetfighter_y = BBuffer
This should prevent the center of the ship from getting closer than 16 pixels
from the edge. Obviously you will need to tweak this to accommodate the size
of your ship. (The buffer for the sides would be the width of the image/2
.Respectively the buffer for the top and bottom would be the height of the
image/2).
|
Multiprocessing Python with RPYC "ValueError: pickling is disabled"
Question: I am trying to use the multiprocessing package within an `rpyc` service, but
get `ValueError: pickling is disabled` when I try to call the exposed function
from the client. I understand that the `multiprocesing` package uses pickling
to pass information between processes and that pickling is not allowed in
`rpyc` because it is an insecure protocol. So I am unsure what the best way
(or if there is anyway) to use multiprocessing with rpyc. How can I make use
of multiprocessing within a rpyc service? Here is the server side code:
import rpyc
from multiprocessing import Pool
class MyService(rpyc.Service):
def exposed_RemotePool(self, function, arglist):
pool = Pool(processes = 8)
result = pool.map(function, arglist)
pool.close()
return result
if __name__ == "__main__":
from rpyc.utils.server import ThreadedServer
t = ThreadedServer(MyService, port = 18861)
t.start()
And here is the client side code that produces the error:
import rpyc
def square(x):
return x*x
c = rpyc.connect("localhost", 18861)
result = c.root.exposed_RemotePool(square, [1,2,3,4])
print(result)
Answer: You can enable pickling in the protocol configuration. The configuration is
stored as a dictionary, you can modify the
[default](http://rpyc.readthedocs.org/en/latest/api/core_protocol.html#rpyc.core.protocol.DEFAULT_CONFIG)
and pass it to both the server (`protocol_config` = ) and client (`config =`).
You also need to define the function being parallelized on both the client and
server side. So here is the full code for `server.py`:
import rpyc
from multiprocessing import Pool
rpyc.core.protocol.DEFAULT_CONFIG['allow_pickle'] = True
def square(x):
return x*x
class MyService(rpyc.Service):
def exposed_RemotePool(self, function, arglist):
pool = Pool(processes = 8)
result = pool.map(function, arglist)
pool.close()
return result
if __name__ == "__main__":
from rpyc.utils.server import ThreadedServer
t = ThreadedServer(MyService, port = 18861, protocol_config = rpyc.core.protocol.DEFAULT_CONFIG)
t.start()
And for `client.py` the code is:
import rpyc
rpyc.core.protocol.DEFAULT_CONFIG['allow_pickle'] = True
def square(x):
return x*x
c = rpyc.connect("localhost", port = 18861, config = rpyc.core.protocol.DEFAULT_CONFIG)
result = c.root.exposed_RemotePool(square, [1,2,3,4])
print(result)
|
python seaborn to reset back to the matplotlib
Question: I'm using seaborn version o.4 and matplotlib version 1.42 I have a chart
displays both line and marker through simple plot command eg.
plt.plot([1,5,3,8,4],'-bo');
Due to a potential bug (<https://github.com/mwaskom/seaborn/issues/344>),
after import seaborn, same code shows line only without marker.
import seaborn as sb
plt.plot([1,5,3,8,4],'-bo');
So my question is: after import seaborn, Is there a way to reset all the
parameters back to original?
Answer: Yes, call
[`seaborn.reset_orig`](http://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.reset_orig.html#seaborn.reset_orig).
|
How to find perfect squares in a range efficiently when the inputs are large numbers in Python
Question: The question is how to find perfect squares in a given range efficiently when
the inputs are very large numbers. My solution is giving `Time Limit Exceeded`
error. I have already checked the following links, but they didn't solve my
problem:
\- [Python Program on Perfect
Squares](http://stackoverflow.com/questions/17508859/python-program-on-
perfect-squares)
\- [How could I check if a number is a perfect
square?](http://stackoverflow.com/questions/2489435/how-could-i-check-if-a-
number-is-a-perfect-square)
\- [Fastest way to determine if an integer's square root is an
integer](http://stackoverflow.com/questions/295579/fastest-way-to-determine-
if-an-integers-square-root-is-an-integer) (I have no idea how to implement the
solution given in this link in Python).
The problem question is:
> Input Format: First line contains T, the number of testcases. T test cases
> follow, each in a newline. Each testcase contains two space separated
> integers denoting A and B. Find all the perfect squares in the range A and B
> (both inclusive).
Example of an input:
2
3 9
17 24
The code I wrote is:
import math
def is_perfect_square(n):
return n % n**0.5 == 0
t = int(raw_input())
for i in range(t):
numbers = map(int, raw_input().split())
count = 0
for j in xrange(numbers[0], numbers[1] + 1): # I also tried range() which gave memory error
if (is_perfect_square(j)):
count = count + 1
print count
While this code is working for smaller numbers, it is giving `Time limit
exceeded` error for large inputs.
(NOTE : `gmpy` is not an option as the code has to be run on an online
compiler which does not have the `gmpy` module)
Answer: Instead of looping from `A` to `B` and checking for perfect squares, why not
just loop through the integers from `sqrt(A)` to `sqrt(B)` and square each,
giving you your answer.
For example, let's find the square numbers between 1000 and 2000:
sqrt(1000) = 31.6 --> 32 (need the ceiling here)
sqrt(2000) = 44.7 --> 44 (need the floor here)
Therefore, our answer is:
322 = 1024
332 = 1089
342 = 1156
352 = 1225
362 = 1296
372 = 1369
382 = 1444
392 = 1521
402 = 1600
412 = 1681
422 = 1764
432 = 1849
442 = 1936
|
logic for String replacement in python
Question: How to replace a string in python For example If the text is 'new words are
newest n ew' and i want to replace 'new' word with 'y' If I use string.replace
command The above text will change to 'y words are yest n ew' I don't want
this to happen Ideally it should be 'y words are newest y' Could some body
throw some light on how to achieve this using python.
Answer:
>>> s = 'new words are newest n ew'
>>> import re
>>> re.sub(r'\bn\s*e\s*w\b', 'y', s)
'y words are newest y'
`'\bn\s*e\s*w\b'` is a [regular
expression](https://docs.python.org/2/library/re.html)
`\b` means a word break
`n`, `e`, `w` mean the letter "n", "e", "w" respectively
`\s*` means zero or more whitespace characters
The regex given here may not be exactly what you need. You need to describe
the rules exactly if you need a more (or less) restrictive regex.
|
ipython notebook on linux VM running matplotlib interactive with nbagg
Question: I want buttons and other interactive matplotlib objects to appear from within
my ipython notebook. 
Here is what I've done:
1. Installed <http://datasciencetoolbox.org>, it is a vagrant box with ipython installed and version 1.3.1 of matplotlib.
2. I needed to upgrade matplotlib to the latest version, because it has this capability to do inline interactive plots. [What's new in Matplotlib 1.4.1](http://matplotlib.org/users/whats_new.html#the-nbagg-backend)
I needed to run `sudo apt-get install pkg-config` and
`sudo pip install matplotlib --upgrade`in order to get that going.
3. Then, in order to produce the nice (i.e. error-free) screenshot below, I went into the `.ipython/dst-profile/ipython_notebook_config.py` file and erased the line about `IPKernelApp.pylab='inline'` to be able to run the `matplotlib.use('nbagg')` command.
4. Then I was able to create the screenshot below. However, things still look poor. Those buttons are not buttons. That is an image of buttons. Please advise on how to make those buttons come to life!
Oh... and check [this](http://stackoverflow.com/questions/19902984/always-
start-ipython-with-pylab-being-equal-to-inline-but-toggle-it-off-at-some) out
if this helps you help me.
Thanks!

Answer: Basically you are facing two issues
* the `%pylab inline`call overrides the `matplotlib.use('nbagg')`call, to use the _inline_ backend instead of the _nbagg_ backend which you are actually wanting. If you use a recent version of IPython (2.3) you can directly use `%matplotlib nbagg` (or `%matplotlib notebook`) to load the nbagg backend instead of your `%pylab`call.
* once you enabled the _nbagg_ backend you will need to explicitly show it, ie. add a `plt.show()` call at the end of your script -> **Update** : with IPython 2.3.1 this is no longer needed (thanks @tcaswell for the hint)
With this you get the interactive matplotlib experience embedded in the
IPython notebook. However, a quick try of your code does't yield to the
desired result. The Button reacts and the callback is executed but the `print`
call doesn't show anything. Anyway, to see that it's working try the following
simple example (requires IPython 2.3):
%matplotlib nbagg
from matplotlib.widgets import Button
import matplotlib.pyplot as plt
def callback(event):
plt.text(event.xdata, event.ydata, 'clicked')
f,a = plt.subplots(1)
b1 = Button(a,'Button1')
b1.on_clicked(callback)
plt.show()
Btw. it is highly recommended to use %matplotlib instead of %pylab as later
leads to some side effects, see
[here](http://nbviewer.ipython.org/github/Carreau/posts/blob/master/10-No-
PyLab-Thanks.ipynb).
|
Revit API : "PickObject" not displaying dialog window
Question: I just did what is written
[here](http://stackoverflow.com/questions/21296317/revit-python-pick-object-
select-object), but I got a problem with `__window__.Topmost = True`.
(So, I'm running directly from the Shell)
Here is my complete code :
def Test(self) :
__window__.Hide()
sel = __revit__.ActiveUIDocument.Selection
pickedRef = sel.PickObject(ObjectType.Element, "Please select a group");
__window__.Show()
__window__.Topmost = True
return pickedRef
Indeed, if I do that, I got an error message saying that 'return' is outside
function. If I change the 'return' line with something else, like `elem =
Element.GetGeometryObjectFromReference(pickedRef)`, then it says that there is
an unexpected indent (of course I checked indentation, should be ok normally).
Finally, if I comment the `__window__.Topmost` line, then I got no error
message.
Do you also experience problems with that ?
But then my biggest issue is that in the end, I get to select an element, but
I see no dialog window popping up with the expected message "please select a
group"). Where does that come from ? I guess the "topmost" command just brings
back the shell on top, so it doesn't come from that...
Any clue ?
Thanks a lot !
Answer: I answered to your comment in french on my website :
[here](http://pythoncvc.net/?p=51#comments)
PickObject Method is not supposed to make any window popping up. It shows an
help message at bottom left corner, check this image : ! [Revit extract with
message](http://pythoncvc.net/wordpress/wp-
content/uploads/2014/11/selectionner_objet.png)
Here is a working code :
def pickobject():
from Autodesk.Revit.UI.Selection import ObjectType
__window__.Hide()
picked = uidoc.Selection.PickObject(ObjectType.Element, "Select object")
__window__.Show()
__window__.Topmost = True
return picked
Moreover, you are not supposed to add "self" in this context. It will return
the following error : Traceback (most recent call last): File "", line 1, in
TypeError: pickobject() takes exactly 1 argument (0 given)
|
Optional dot in regex
Question: Say I want to replace all the matches of `Mr.` and `Mr` with `Mister`.
I am using the following regex: `\bMr(\.)?\b` to match either `Mr.` or just
`Mr`. Then, I use the [`re.sub()`
method](https://docs.python.org/2/library/re.html#re.sub) to do the
replacement.
What is puzzling me is that it is replacing `Mr.` with `Mister.`. Why is this
keeping the dot `.` at the end? It looks like it is not matching the `Mr\.`
case but just `Mr`.
import re
s="a rMr. Nobody Mr. Nobody is Mr Nobody and Mra Nobody."
re.sub(r"\bMr(\.)?\b","Mister", s)
Returns:
'a rMr. Nobody Mister. Nobody is Mister Nobody and Mra Nobody.'
I also tried with the following, but also without luck:
re.sub(r"\b(Mr\.|Mr)\b","Mister", s)
My desired output is:
'a rMr. Nobody Mister Nobody is Mister Nobody and Mra Nobody.'
^ ^
no dot this should be kept as it is
Answer: I think you want to capture `'Mr'` followed by _either a`'.'` **or** a word
boundary_:
r"\bMr(?:\.|\b)"
In use:
>>> import re
>>> re.sub(r"\bMr(?:\.|\b)", "Mister", "a rMr. Nobody Mr. Nobody is Mr Nobody and Mra Nobody.")
'a rMr. Nobody Mister Nobody is Mister Nobody and Mra Nobody.'
|
Access/Edit pixel values of a jpeg image in python
Question: I'm involved in a image processing project and I use python. I'm new to
python, so please bear my lack of knowledge. I want to read a `jpeg` image,
split it into `r,g,b`. Then I have to change add a value to each pixel `r,g,b`
separately. Finally, I have to merge three of them to create a new image and
save it.
from PIL import Image
im = Image.open("/home/pi/desktop/codes/lena.jpg")
im.show()
r,g,b =im.split()
Are `r,g,b` matrices containing pixel values? Can I change the values of the
pixels directly? And can some one please tell me how to access each pixel?
Answer: First you
[split](https://pillow.readthedocs.org/reference/Image.html#PIL.Image.Image.split)
the image into individual bands.
Then maniplulate each pixels as you want using
[point](https://pillow.readthedocs.org/reference/Image.html#PIL.Image.Image.point).
Then merge three bands using
[merge](https://pillow.readthedocs.org/reference/Image.html#PIL.Image.merge).
The `split` method returns a tuple
> **Image.split()**
> Split this image into individual bands. This method returns a tuple of
> individual image bands from an image. For example, splitting an “RGB” image
> creates three new images each containing a copy of one of the original bands
> (red, green, blue).
|
python decimal print all internal decimal places
Question: i am looking for a way to print all internal decimal places of a python
decimal. has anyone an idea how to achieve following. The example code is
written in Python.
from decimal import *
bits = 32
precision = Decimal(1) / Decimal(2**bits)
val = decimal(1078947848)
what happens now for following if i multiply val * precision i get following
result
val * precision
Decimal('0.2512121219187974929809570312')
but i know the last number 2 is not the end of my number, so i can do
following which gives me this result
"%.100f" % x
'0.2512121219187974929809570312500000000000000000000000000000000000000000000000000000000000000000000000'
however all the trailing zeros are not desired, and the size of %.100f depends
on the given bits. It should be simple math and maybe I should give myself a
break, but how can I derive the number of internal decimal places from the
given number of bits 32.
Answer: From the [documentation](https://docs.python.org/2/library/decimal.html):
> the decimal module has a user alterable precision (defaulting to 28 places)
> which can be as large as needed for a given problem
Your number is 29 digits long, so it's just a little too much for the default
precision. Try increasing it. 29 would work for this instance, but you may
wish to choose a larger number if you don't know how many decimal places
you'll need later.
from decimal import *
getcontext().prec = 100
bits = 32
precision = Decimal(1) / Decimal(2**bits)
val = Decimal(1078947848)
print val * precision
Result:
0.25121212191879749298095703125000
Also, you can strip those trailing zeroes with a call to `normalize`.
>>> print (val * precision).normalize()
0.25121212191879749298095703125
|
Read out RGB data from images with C on Raspberry PI
Question: After looking for a long time on the internet I could not find a real solution
for my "problem".
* * *
**What I want to do:**
Compare 2 images (created with the Raspberry Pi camera in a Python script) in
C. I have tried this in Python but it is too slow (+/- 1 minute per 2 images).
So I would like to try it in C. I call a C function with ctypes from my Python
script. The C function expect to get 2 strings containing the paths of the 2
images. The C function must return a double variable (percentage of
difference) back to the Python script.
* * *
**What I tried:**
I store the images as .JPG, so I searched for a c-library that can handle the
jpg-format. I found a post here on stackoverflow advising CImg. I could not
get that to work on my Raspberry Pi. Said it could not find the imports.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "cimg/CImg.h"
using namespace cimg_library;
double compare_pictures(const char* path1, const char* path2);
// Compares two Pictures and returns the difference value
double compare_pictures(const char* path1, const char* path2)
{
CImg<unsigned char> image1(path1);
CImg<unsigned char> image2(path2);
double totalDiff = 0.0;
unsigned int x, y;
if (image1 == NULL || image2 == NULL)
{
fprintf(stderr, "One of the images does not exist\n");
return -1;
}
if ((image1.width() != image2.width()) || (image1.height() != image2.height()))
{
fprintf(stderr, "width/height of the images must match!\n");
return -1;
}
else
{
for (y = 0; y < image1.height; y++)
{
for (x = 0; x < image1.width; x++)
{
totalDiff += fabs((int)image1(x, y, 0, 0) - (int)image2(x, y, 0, 0)) / 255.0;
totalDiff += fabs((int)image1(x, y, 0, 1) - (int)image2(x, y, 0, 1)) / 255.0;
totalDiff += fabs((int)image1(x, y, 0, 2) - (int)image2(x, y, 0, 2)) / 255.0;
}
}
totalDiff = 100.0 * totalDiff / (double)(image1.width() * image1.height() * 3);
printf("%lf\n", totalDiff);
return totalDiff;
}
}
> CImg.h:73:18: fatal error: cstdio: No such file or directory. compilation
> terminated.
After some tries I gave up and went back to the internet to find another
library. I found libjpeg8-dev which is suitable for the Raspberry Pi and C.
Nonetheless this did not help me much either, because I couldn't really find
good tutorials/documentation how to use it for my purposes.
* * *
I just want to be able to compare images created by the Raspberry Pi camera
and calculate a difference percentage in a fast way (best would be in less
than a second)
Answer: Your code is C++, but your error suggests you are trying to compile it as a C
program because `cstdio` is the C++ version of C's `stdio.h`.
Your compile command:
gcc -shared -o mycfile.so -fPIC mycfile.c
Is trying to compile `mycfile.c` as C (not C++) which is causing your error.
GCC detects the type of file based upon extension (`.c` for C, `.cpp`, `.cxx`,
`.cc` , and `.C` for C++). Rename `mycfile.c` to `mycfile.cpp`, link the C++
runtime library `stdc++`, and run:
gcc -lstdc++ -shared -o mycfile.so -fPIC mycfile.cpp
* * *
I am unfamiliar with _CImg_ , but if you're open to suggestions, you can give
[_stb_image.h_](https://github.com/nothings/stb/blob/master/stb_image.h) a
try:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "stb_image.h"
double compare_pictures(const char* path1, const char* path2);
double compare_pictures(const char* path1, const char* path2)
{
double totalDiff = 0.0;
unsigned int x, y;
int width1, height1, comps1;
unsigned char * image1 = stbi_load(path1, &width1, &height1, &comps1, 0);
int width2, height2, comps2;
unsigned char * image2 = stbi_load(path2, &width2, &height2, &comps2, 0);
if (image1 == NULL || image2 == NULL)
{
fprintf(stderr, "One of the images does not exist\n");
return -1;
}
if ((width1 != width2) || (height1 != height2))
{
fprintf(stderr, "width/height of the images must match!\n");
return -1;
}
else
{
for (y = 0; y < height1; y++)
{
for (x = 0; x < width1; x++)
{
totalDIff += fabs((int)image1[(x + y*width1) * comps1 + 0] - (int)image2[(x + y*width2) * comps2 + 0]) / 255.0;
totalDiff += fabs((int)image1[(x + y*width1) * comps1 + 1] - (int)image2[(x + y*width2) * comps2 + 1]) / 255.0;
totalDiff += fabs((int)image1[(x + y*width1) * comps1 + 2] - (int)image2[(x + y*width2) * comps2 + 2]) / 255.0;
}
}
totalDiff = 100.0 * totalDiff / (double)(width1 * height1 * 3);
printf("%lf\n", totalDiff);
return totalDiff;
}
}
|
reverse geocoding with python geocoder
Question: I'm trying my hands on reverse geocoding with python and the module geocoder
I built this script
#!/Users/admin/anaconda/bin/python
import geocoder
import unicodecsv
import logging
with open('locs2.csv', 'rb') as f:
reader = unicodecsv.DictReader(f, encoding='iso-8859-1')
for line in reader:
lat = line['lat']
lon = line['lon']
g = geocoder.google(['lat','lon'], method=reverse)
if g.ok:
g.postal
logging.info('Geocoding SUCCESS: ' + address)
else:
logging.warning('Geocoding ERROR: ' + address)
According to the doc [here](https://pypi.python.org/pypi/geocoder/0.9.1), we
can do reverse. However, when I'm running the script , I have this error
`NameError: name 'reverse' is not defined`
Why?
TIA
**This is a sample from my file**
lat, lon
48.7082,2.2797
48.7577,2.2188
47.8333,2.2500
48.9833,1.7333
47.9333,1.9181
46.2735,4.2586
**Edit **: I've amended the script a bit (see below) and I have this error
WARNING:root:Geocoding ERROR:
**the amended script**
#!/Users/admin/anaconda/bin/python
import geocoder
import unicodecsv
import logging
pcode=[]
lat=[]
lon=[]
with open('locs2.csv', 'rb') as f:
reader = unicodecsv.DictReader(f, encoding='iso-8859-1')
for line in reader:
lat = line['lat']
lon = line['lon']
g = geocoder.google([lat,lon], method='reverse')
if g.ok:
pcode.extend(g.postal)
logging.info('Geocoding SUCCESS: '+
str(lat)+','+str(lon)+','+str(pcode))
else:
logging.warning('Geocoding ERROR: ' + str(lat)+','+str(lon))
fields= 'lat', 'lon', 'pcode'
rows=zip(lat,lon,pcode)
with open('/Users/admin/python/myfile.csv', 'wb') as outfile:
w = unicodecsv.writer(outfile, encoding='iso-8859-1')
w.writerow(fields)
for i in rows:
w.writerow(i)
Answer: The problem is that you forgot to add quotes around your option `reverse`:
g = geocoder.google(['lat','lon'], method='reverse')
I consider that a mistake in their documentation. You could send a message to
the author to inform him/her of this, he/she might want to update their docs.
Furthermore, you'll want to call it with the actual parameters `lat` and
`lon`, not the strings. Otherwise you'll get an error. So,
g = geocoder.google([lat, lon], method='reverse') # lat and lon you've extracted already, but maybe you'll still need to cast them to float.
* * *
_Update: if you're running into reverse lookups that give`g.ok == False`_,
then the problem is related to the throttling of your requests by the API
provider (in the examples above, this is Google). For example, the [Google
Maps API specifies fair
use](https://developers.google.com/maps/documentation/business/articles/usage_limits)
and should not be polled overly fast. This information is clear when you call
`g.debug()`. Among the output will be:
## Provider's Attributes
* status: OVER_QUERY_LIMIT
* error_message: You have exceeded your rate-limit for this API.
To throttle your requests, you could do the following:
import geocoder
import unicodecsv
import logging
import time
import csv
pcode=[]
with open('locs2.csv', 'rb') as f:
reader = csv.DictReader(f)
for line in reader:
lat = float(line['lat'])
lon = float(line['lon'])
g = geocoder.google([lat,lon], method='reverse')
attempts = 1 # number of lookups
while not(g.ok) and attempts < 4:
logging.warning('Geocoding ERROR: {}'.format(g.debug()))
time.sleep(2) # 2 seconds are specified in the API. If you still get errors, it's because you've reached the daily quota.
g = geocoder.google([lat,lon], method='reverse')
attempts += 1
if attempts > 3:
logging.warning('Daily quota of google lookups exceeded.')
break
pcode.extend(g.postal)
logging.info('Geocoding SUCCESS: ({},{},{})'.format(lat,lon,pcode))
Some of the providers, such as Mapquest, don't impose throttling at the
moment.
One bug present in geocoder version 0.9.1 is that `lat`and `lon` should both
differ from `0.0`. The lookup will generate a `TypeError` if you have
coordinates like that (along the equator or the Greenwhich meridian).
|
Python tornado stop function
Question: I've got a tornado web server running on my Raspberry and a ultrasonic sensor
connected to it. I've got a html page with a start and stop button, when I
click start the script is sending a message "start" to the serwer and it runs
a function that prints the distance.
Now i'm trying to stop the function when clicking stop button. But when te
function is printing the distances and I click the stop button on my website
the server doesnt recive the "stop" message.

The code is here: <http://pastebin.com/SVRZNXgH>
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.websocket
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
# Ta funkcja dokonuje pomiaru odleglosci
def pomiar():
# Ustawienie pinow czujnika odleglosci
GPIO_TRIGGER = 16
GPIO_ECHO = 18
# Ustawienie pinu buzzera
GPIO_BUZZER = 22
# Ustawienie pinu serwomechanizmu
GPIO_SERVO = 13
# Ustawienie pinow
GPIO.setup(GPIO_TRIGGER,GPIO.OUT)
GPIO.setup(GPIO_ECHO,GPIO.IN)
GPIO.setup(GPIO_SERVO,GPIO.OUT)
# Ustawienie Trigget jako false (stan niski)
GPIO.output(GPIO_TRIGGER, False)
GPIO.setup(GPIO_TRIGGER,GPIO.OUT)
GPIO.output(GPIO_TRIGGER, True)
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)
start = time.time()
while GPIO.input(GPIO_ECHO)==0:
start = time.time()
while GPIO.input(GPIO_ECHO)==1:
stop = time.time()
elapsed = stop-start
distance = (elapsed * 34300)/2
print "odleglosc : %.1f" % distance
time.sleep(2)
return distance
# Funkcja dokonujaca sprawdzenia kata
def sprawdz_kat():
GPIO_SERVO = 13
GPIO.setup(GPIO_SERVO,GPIO.OUT)
p = GPIO.PWM(GPIO_SERVO,50)
katy = [10,12.5,5,2.5];
start = 20.0;
for x in katy:
p.ChangeDutyCycle(x)
time.sleep(0.5)
odleglosc = pomiar()
print "odleglosc : %.1f" % odleglosc
if(odleglosc>start):
start=odleglosc
kat = x
if(kat==10):
return float(-45)
if(kat==12.5):
return float(-90)
if(kat==5):
return float(45)
if(kat==2.5):
return float(90)
# Funkcja do obrotu robota o zadany kat
def obrot(kat):
obrot=abs(kat/100)
print(obrot)
if(kat<0):
GPIO.output(M1_EN, True) # True - do przodu, False - do tylu
GPIO.output(M2_EN, True) # False - do przodu, True - do tylu
else:
GPIO.output(M1_EN, False) # True - do przodu, False - do tylu
GPIO.output(M2_EN, False) # False - do przodu, True - do tylu
LEWA_PWM.ChangeDutyCycle(25)
PRAWA_PWM.ChangeDutyCycle(25)
time.sleep(obrot)
LEWA_PWM.ChangeDutyCycle(0)
PRAWA_PWM.ChangeDutyCycle(0)
GPIO.output(M1_EN, True)
GPIO.output(M2_EN, False)
# Program labiryntu
def labirynt():
distance = pomiar()
p.start(7.5)
while True:
distance = pomiar()
GPIO.setup(GPIO_BUZZER,GPIO.OUT)
GPIO.output(GPIO_BUZZER, False)
time.sleep(0.08)
GPIO.setup(GPIO_BUZZER,GPIO.IN)
time.sleep(distance/500)
LEWA_PWM.ChangeDutyCycle(10)
PRAWA_PWM.ChangeDutyCycle(10)
if(distance<50):
LEWA_PWM.ChangeDutyCycle(0)
PRAWA_PWM.ChangeDutyCycle(0)
kat = sprawdz_kat()
print kat
obrot(kat)
p.ChangeDutyCycle(7.5)
time.sleep(0.5)
GPIO.setup(GPIO_SERVO,GPIO.IN)
GPIO.cleanup
def stop_all():
GPIO.output(GPIO_TRIGGER, False)
GPIO.output(GPIO_ECHO, False)
GPIO.cleanup()
# Ustawienie pinow czujnika odleglosci
GPIO_TRIGGER = 16
GPIO_ECHO = 18
# Ustawienie pinu buzzera
GPIO_BUZZER = 22
# Ustawienie pinu serwomechanizmu
GPIO_SERVO = 13
# Ustawienie pinow
GPIO.setup(GPIO_TRIGGER,GPIO.OUT)
GPIO.setup(GPIO_ECHO,GPIO.IN)
GPIO.setup(GPIO_SERVO,GPIO.OUT)
# Ustawienie Trigget jako false (stan niski)
GPIO.output(GPIO_TRIGGER, False)
# Ustawienia dla serwa
p = GPIO.PWM(GPIO_SERVO,50) #Ustawienie czestotliwosci na 50Hz
#poczatkowy kat serwa 90 stopni (neutralny)
# Ustawienia buzzera
GPIO.setup(GPIO_BUZZER,GPIO.IN)
# -----------------------
# Ustawienia silnikow
# -----------------------
# Prawa strona
M1_PWM = 26
M1_EN = 24
# Lewa strona
M2_PWM = 23
M2_EN = 21
# Prawa strona ustawienia jako output
GPIO.setup(M1_PWM,GPIO.OUT)
GPIO.setup(M1_EN,GPIO.OUT)
# Lewa strona ustawienia jako output
GPIO.setup(M2_PWM,GPIO.OUT)
GPIO.setup(M2_EN,GPIO.OUT)
# Prawa strona ustawienie stanow niskich
GPIO.output(M1_PWM, False)
GPIO.output(M1_EN, True) # True - do przodu, False - do tylu
# Lewa strona ustawienie stanow niskich
GPIO.output(M2_PWM, False)
GPIO.output(M2_EN, False) # False - do przodu, True - do tylu
# Ustawienie PWM dla prawej strony
PRAWA_PWM = GPIO.PWM(26,50)
# Ustawienie PWM dla lewej strony
LEWA_PWM = GPIO.PWM(23,50)
# Poczatkowe ustawienia PWM silnikow
PRAWA_PWM.start(0)
LEWA_PWM.start(0)
from tornado.options import define, options
define("port", default=8080, help="run on the given port", type=int)
class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.render('index.html')
class WebSocketHandler(tornado.websocket.WebSocketHandler):
def open(self):
print 'new connection'
self.write_message("connected")
def on_message(self, message):
print 'message received %s' % message
self.write_message('message received %s' % message)
aaa = message
if message == "gora":
GPIO.output(M1_EN, True)
GPIO.output(M2_EN, False)
LEWA_PWM.ChangeDutyCycle(8)
PRAWA_PWM.ChangeDutyCycle(8)
if message == "dol":
GPIO.output(M1_EN, False)
GPIO.output(M2_EN, True)
LEWA_PWM.ChangeDutyCycle(8)
PRAWA_PWM.ChangeDutyCycle(8)
if message == "stop":
LEWA_PWM.ChangeDutyCycle(0)
PRAWA_PWM.ChangeDutyCycle(0)
if message == "lewo":
GPIO.output(M1_EN, True)
GPIO.output(M2_EN, True)
LEWA_PWM.ChangeDutyCycle(20)
PRAWA_PWM.ChangeDutyCycle(20)
if message == "prawo":
GPIO.output(M1_EN, False)
GPIO.output(M2_EN, False)
LEWA_PWM.ChangeDutyCycle(20)
PRAWA_PWM.ChangeDutyCycle(20)
while (aaa == "start_maze"):
pomiar()
def on_close(self):
print 'connection closed'
if __name__ == "__main__":
tornado.options.parse_command_line()
app = tornado.web.Application(
handlers=[
(r"/", IndexHandler),
(r"/ws", WebSocketHandler),
(r'/js/(.*)', tornado.web.StaticFileHandler, {'path': "/home/pi/js"}),
(r'/css/(.*)', tornado.web.StaticFileHandler, {'path': "/home/pi/css"}),
(r'/fonts/(.*)', tornado.web.StaticFileHandler, {'path': "/home/pi/fonts"}),
]
)
httpServer = tornado.httpserver.HTTPServer(app)
httpServer.listen(options.port)
print "Listening on port:", options.port
tornado.ioloop.IOLoop.instance().start()
Answer: The reason is that you got an endless loop in line 227.
One possible solution:
1. Make your `pomiar` function a method of the websocket handler
2. Use a variable on your websocket handler `self.running` and on start set it to true. And call `self.pomiar()`
3. On stop just set `self.running` to `false`
4. At the end of `pomiar` remove the `time.sleep` it does block the complete tornado server. Instead:
...
if self.running:
tornado.ioloop.IOLoop.instance().add_timeout(time.time() + 2, self.pomiar)
The add_timeout makes tornado call your pomiar function again in two seconds.
Checking first if `self.running` is still `true` makes sure your `pomiar`
function is only called as long as stop is not called.
There are a lot of other ways to solve this. You might want to read more about
tornado and the asynchronous functions it provides, for example:
<http://tornado.readthedocs.org/en/latest/gen.html>
|
How to change class object parameters from another module (python)
Question: So I've searched around and couldn't find an answer. I'm looking to change
parameters from an object created in my main file, in a module. For example,
I'm testing this with a simple piece of code here:
-this is my main file, from which i create the objects and define some properties
import class_test_2
class dog():
name=''
spots=0
def add_spots(self):
self.spots+=1
def main():
fido=dog()
fido.name='Fido'
print('Fido\'s spots: ',fido.spots)
fido.add_spots()
print('Fido\'s spots: ',fido.spots)
class_test_2.class_test()
print('Fido\'s spots: ',fido.spots)
if __name__=='__main__':
main()
* * *
-this is the module, from which I want to use functions to change the attributes in the main file
from class_test_1 import dog
def class_test():
fido.add_spots()
-So my question is how can I do this/why doesn't this piece of code above work? Running the main function on its own shows fido's spots increasing by 1 each time its printed. Running the code calling the module however gives a NameError so my module isn't recognising the class exists even though I've managed to import it. Thanks in advance for any help.
Answer: Your variable "fido" is only defined within your "main" function. You must
provide your "class_test" function with the variable.
For example:
class_test_2.class_test(fido)
Then your `class_test` function gets an argument. You can choose the name
freely. I used `the_dog` in the example:
def class_test(the_dog):
the_dog.add_spots()
In this case `the_dog` points to the same instance of your `dog` class as
`fido`.
|
Converting WxPython code to C++
Question: Let' say I have written a wxPython application
import wx
app = wx.PySimpleApp()
frame = wx.Frame(None, -1, "Just one child", size=(250,150))
button = wx.Button(frame, -1, "This is resized")
frame.Show()
app.MainLoop()
How can I reuse or converting this code easily into a c++ program which I can
compile with g++. Is this even possible?
Answer: No, it is not possible. What you want is the
[wxWidgets](https://www.wxwidgets.org/) library. The wxPython project is for
use with Python only.
I would recommend reading the "Hello World" tutorial on the wxWidgets website:
* <http://docs.wxwidgets.org/stable/overview_helloworld.html>
There are additional tutorials here:
* <https://www.wxwidgets.org/docs/tutorials/>
|
Normalize Small Probabilities in Python
Question: I have a list of probabilities, which I need to normalize to equal 1.0.
e.g. `probs = [0.01,0.03,0.005]`
I realize that this is done by dividing each probability by the sum of
`probs`. However, if the probabilities become really small, Python will tell
me that `sum(probs)=0.0`. I understand that this is an underflow issue. I
suppose I should use the log of each probability. How would I do this?
Answer: The sum of even very small floating point values will never truly be 0; they
may be _close_ to zero, but can never be exactly zero.
Just divide 1 by their sum, and multiply the probabilities by that factor:
def normalize(probs):
prob_factor = 1 / sum(probs)
return [prob_factor * p for p in probs]
Some probabilities may make up but a _very small_ percentage in the total sum,
of course, and that percentage may approach zero. But this just means that
when normalising you may end up with normalized probabilities that are either
very close to zero, or if smaller than the smallest representable floating
point value, equal to zero. The latter only happens if there are probabilities
in the list that are so much smaller than the others that they no longer
represent anything close to something that'll ever occur.
Demo:
>>> def normalize(probs):
... prob_factor = 1 / sum(probs)
... return [prob_factor * p for p in probs]
...
>>> normalize([0.0000000001,0.000000000003,0.000000000000005])
[0.9708266589000533, 0.029124799767001597, 4.854133294500266e-05]
And the extreme case:
>>> import sys
>>> normalize([sys.float_info.max, sys.float_info.min])
[0.9999999999999999, 0.0]
>>> normalize([sys.float_info.max, sys.float_info.min])[-1] == 0
True
|
How to Partition Pandas DataFrame using DateTime
Question: I am writing a Python script to import pictures from my digital cameras, and
I'm using Pandas to help with the bookkeeping of the incoming images. I am
using the EXIF data to tag individual images with information, such as the
Camera Model, image mode, image format and the timestamp of when the image was
acquired by the camera. These data are used to segregate the images into a
directory structure. What I'm struggling with is how to use Pandas to group
images based on a clump of timestamps that are, for example, all within half-
an-hour of each other. As an example, let's say I have six images, three of
which were taken within nine minutes of each other and then the other three,
also within nine minutes of each other, but an hour later.
import pandas
import datetime
rawdata = [{'filename': 'image_1.jpg',
'timestamp': datetime.datetime(2014, 11, 13, 19, 14, 16, 152847)},
{'filename': 'image_2.jpg',
'timestamp': datetime.datetime(2014, 11, 13, 19, 17, 16, 152847)},
{'filename': 'image_3.jpg',
'timestamp': datetime.datetime(2014, 11, 13, 19, 20, 16, 152847)},
{'filename': 'image_4.jpg',
'timestamp': datetime.datetime(2014, 11, 13, 20, 14, 16, 152847)},
{'filename': 'image_5.jpg',
'timestamp': datetime.datetime(2014, 11, 13, 20, 17, 16, 152847)},
{'filename': 'image_6.jpg',
'timestamp': datetime.datetime(2014, 11, 13, 20, 20, 16, 152847)}]
df = pandas.DataFrame(rawdata)
Is there an automatic way to partition this DataFrame with a half-an-hour
threshold such that I would have image_1, image_2 and image_3 in one DataFrame
and image_4, image_5 and image_6 in a second DataFrame?
Answer: IIUC, one way would be to use the `diff-compare-cumsum` idiom to get cluster
numbers which you can then use to `groupby`:
>>> df = df.sort("timestamp")
>>> cluster = (df["timestamp"].diff() > pd.Timedelta(minutes=30)).cumsum()
>>> dfs = [v for k,v in df.groupby(cluster)]
>>> for clust in dfs:
... print(clust)
...
filename timestamp
0 image_1.jpg 2014-11-13 19:14:16.152847
1 image_2.jpg 2014-11-13 19:17:16.152847
2 image_3.jpg 2014-11-13 19:20:16.152847
filename timestamp
3 image_4.jpg 2014-11-13 20:14:16.152847
4 image_5.jpg 2014-11-13 20:17:16.152847
5 image_6.jpg 2014-11-13 20:20:16.152847
* * *
This works because False ~ 0 and True ~ 1, so if we take the cumulative sum of
something which becomes 1 every time a new cluster is found, we'll get the ids
we want:
>>> df["timestamp"].diff()
0 NaT
1 00:03:00
2 00:03:00
3 00:54:00
4 00:03:00
5 00:03:00
Name: timestamp, dtype: timedelta64[ns]
>>> df["timestamp"].diff() > pd.Timedelta(minutes=30)
0 False
1 False
2 False
3 True
4 False
5 False
Name: timestamp, dtype: bool
>>> (df["timestamp"].diff() > pd.Timedelta(minutes=30)).cumsum()
0 0
1 0
2 0
3 1
4 1
5 1
Name: timestamp, dtype: int64
|
Script incompatibility for Python 2.x and Python 3.x
Question: I cannot understand what happens with python3 that prevents this from working,
when I try with python3, it just hungs on line 11.
import io,re,unittest,os,json,sys
from subprocess import PIPE, STDOUT, Popen
sub = Popen(["/usr/bin/python3.4", "test2.py", "pipe"], stdin=PIPE, stdout=PIPE, stderr=sys.stderr, close_fds=True, shell=False)
(writer,reader) = (sub.stdin, sub.stdout)
writer.write("HELO\t1\n".encode("utf-8"))
writer.flush()
sub.poll()
line = reader.readline().decode("utf-8")
assert(re.match("^OK\t", line))
writer.write("Q\ttest.com\tIN\tSOA\t-1\t127.0.0.1\n".encode("utf-8"))
line = reader.readline().decode("utf-8")
assert(re.match("^DATA\ttest.com\tIN\tSOA\t300\t-1\tsns.dns.icann.org. noc.dns.icann.org. 2013073082 7200 3600 1209600 3600", line))
sub.stdout.close()
sub.stdin.close()
sub.kill()
sub.wait()
Here's the `test2.py` file that the above code calls:
import sys
sys.stderr.write(sys.stdin.readline())
sys.stdout.write("OK\tversion foo bar hello\n")
sys.stdout.flush()
sys.stderr.write(sys.stdin.readline())
sys.stdout.write("DATA\ttest.com\tIN\tSOA\t300\t-1\tsns.dns.icann.org. noc.dns.icann.org. 2013073082 7200 3600 1209600 3600")
sys.stdout.flush()
Answer: On my system, I reproduced your problem and fixed it by adding a
`writer.flush()` after your second `writer.write()` call. E.g.:
import io,re,unittest,os,json,sys
from subprocess import PIPE, STDOUT, Popen
sub = Popen(["/usr/bin/python3.4", "test2.py", "pipe"], stdin=PIPE, stdout=PIPE, stderr=sys.stderr, close_fds=True, shell=False)
(writer,reader) = (sub.stdin, sub.stdout)
writer.write("HELO\t1\n".encode("utf-8"))
writer.flush()
sub.poll()
line = reader.readline().decode("utf-8")
assert(re.match("^OK\t", line))
writer.write("Q\ttest.com\tIN\tSOA\t-1\t127.0.0.1\n".encode("utf-8"))
writer.flush() # <<< INSERTED FLUSH <<<
line = reader.readline().decode("utf-8")
assert(re.match("^DATA\ttest.com\tIN\tSOA\t300\t-1\tsns.dns.icann.org. noc.dns.icann.org. 2013073082 7200 3600 1209600 3600", line))
sub.stdout.close()
sub.stdin.close()
sub.kill()
sub.wait()
sub.wait()
It now executes properly if the main script is run in Python 2 or Python 3
(tested: 2.7 and 3.4)
I say "on my system" because this sort of interleaved reader-writer
coordination across text pipes is intrinsically fragile. When it works great,
it's great! But very small variations in how the system, system libraries,
language implementations, etc. handle I/O can cause you all manner of grief.
|
How can I join two tables in Django and use the result in my template?
Question: I am having a hard time utilizing a foreign key in Django 1.7. For reference:
**models.py** looks like this:
from django.db import models
class Transaction(models.Model):
transaction_num = models.IntegerField(primary_key=True)
customer_name = models.CharField(max_length=255, blank=True)
transaction_date = models.DateField(blank=True, null=True)
phone = models.CharField(max_length=255, blank=True)
est_pickup_date = models.DateField(blank=True, null=True)
class Meta:
db_table = 'transaction'
def __str__(self): # __unicode__ on Python 2
return str(self.transaction_num)
class Item(models.Model):
itemid = models.IntegerField(primary_key=True)
transaction_num = models.ForeignKey(Transaction, db_column='transaction_num')
desc = models.CharField(max_length=255)
picked_up_on = models.DateField(blank=True, null=True)
class Meta:
db_table = 'item'
def __str__(self): # __unicode__ on Python 2
return str(self.itemid)
class TransactionNote(models.Model):
noteid = models.IntegerField(primary_key=True)
transaction_num = models.ForeignKey(Transaction, db_column='transaction_num')
content = models.CharField(max_length=255)
class Meta:
db_table = 'transaction_note'
def __str__(self): # __unicode__ on Python 2
return str(self.noteid)
**views.py** looks like this:
from django.http import HttpResponse
from django.shortcuts import render
from pickup.models import Transaction, Item, TransactionNote
# Current Inventory
def history(request):
t = Transaction.objects.all().order_by('-transaction_date', '-transaction_num')
return render(request, 'pickup/history.html', { 'transaction_list': t})
...and the relevant part of **history.html** , a table inside of a loop, where
I want to include the count of all of the related items attached to a
particular transaction:
{% for transaction in transaction_list %}
[...]
<td>{{ transaction.customer_name }}</td>
<td>{{ transaction.transaction_date }}</td>
<td>{{ transaction.est_pickup_date }}</td>
<td>{{ transaction.phone }}</td>
<td>{{ transaction.itemid.count }}</td>
[...]
{% endfor %}
Everything works except for that last line. I have no idea how to join the
Transaction and Item tables so that I can work with the relevant item objects
(specifically the descriptions or their counts) inside of the template. Any
help will be appreciated.
Answer: Django provides the ability to query all reverse relationships for an object.
To achieve this, Django provides what is consider a 'related_name' for a
reverse relationship object, and it is defaulted to the class name with '_set'
appended.
So, your code should look something like this,
{% for item in transaction.item_set.all %}
... do stuff ...
{% endfor %}
or
{{ transaction.item_set.count }}
Neither of these are tested, but I believe it should work closely to that.
|
PyOpenGL on Ubuntu for Python 2.7
Question: I am trying to install PyOpenGL and so far have tried the following ways:
1. $ pip install PyOpenGL PyOpenGL_accelerate
2. $ sudo python2.7 -m pip install PyOpenGL PyOpenGL_accelerate
3. Some variations of the above...
4. Installation from source.
Unfortunately I still can't run the following imports:
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
I am getting the error message:
> unable to detect undefined names
Am I missing something? Do I need to install more packages?
Do I need to get OpenGLContext seperately? If so, how do I install that, since
pip install PyDispatcher PyVRML97 OpenGLContext
doesn't work either.
Any help would be much appreciated!
Answer: Try sudo apt-get install python-opengl
|
export tkinter calendar to another tkinter
Question: I have a tkinter calendar file called `wckcalendar.py`.I wanted to import this
to another file,which is coded below.I wanted to display the calendar and my
button in the **same tkinter window** Please letme know the changes I need to
do,so that both will be displaed on the same window!
Getting error:
Traceback (most recent call last):
File "C:/Python27/qw.py", line 17, in <module>
app = myproject(None, None)
File "C:/Python27/qw.py", line 8, in __init__
self.calendar()
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1826, in __getattr__
return getattr(self.tk, attr)
AttributeError: calendar
My code:
import wckCalendar
from wckCalendar import *
import Tkinter
class myproject(Tkinter.Tk):
def __init__(self,parent, master):
Tkinter.Tk.__init__(self)
self.button2()
self.calendar()
win(root, data)
def button2(self):
button2 = Tkinter.Button(self, text = "Benny")
button2.grid(column=1,row=3)
def win(parent, d):
win = tk.Toplevel(parent)
cal = Calendar(win, d)
app = myproject(None, None)
app.mainloop()
My wckcalendar file coding:
import calendar
import Tkinter as tk
import datetime
class Data:
def __init__(self):
self.day_selected = 0
self.month_selected = 0
self.year_selected = 0
self.day_name = 0
class Calendar:
def __init__(self, parent, data):
self.data = data
self.parent = parent
self.cal = calendar.TextCalendar(calendar.SUNDAY)
self.year = 2014
self.month = 11
self.wid = []
self.day_selected = 1
self.month_selected = self.month
self.year_selected = self.year
self.day_name = ''
self.setup(self.year, self.month)
def clear(self):
for w in self.wid[:]:
w.grid_forget()
#w.destroy()
self.wid.remove(w)
def go_prev(self):
if self.month > 1:
self.month -= 1
else:
self.month = 12
self.year -= 1
#self.selected = (self.month, self.year)
self.clear()
self.setup(self.year, self.month)
def go_next(self):
if self.month < 12:
self.month += 1
else:
self.month = 1
self.year += 1
#self.selected = (self.month, self.year)
self.clear()
self.setup(self.year, self.month)
def selection(self, day, name):
self.day_selected = day
self.month_selected = self.month
self.year_selected = self.year
self.day_name = name
self.data.day_selected = day
self.data.month_selected = self.month
self.data.year_selected = self.year
self.data.day_name = name
#self.selected = day
self.clear()
self.setup(self.year, self.month)
def setup(self, y, m):
left = tk.Button(self.parent, text='<', command=self.go_prev)
self.wid.append(left)
left.grid(row=0, column=1)
header = tk.Label(self.parent, height=2, text='{} {}'.format(calendar.month_abbr[m], str(y)))
self.wid.append(header)
header.grid(row=0, column=2, columnspan=3)
right = tk.Button(self.parent, text='>', command=self.go_next)
self.wid.append(right)
right.grid(row=0, column=5)
days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
for num, name in enumerate(days):
t = tk.Label(self.parent, text=name[:3])
self.wid.append(t)
t.grid(row=1, column=num)
for w, week in enumerate(self.cal.monthdayscalendar(y, m), 2):
for d, day in enumerate(week):
if day:
#print(calendar.day_name[day])
b = tk.Button(self.parent, width=1, text=day, command=lambda day=day:self.selection(day, calendar.day_name[(day-1) % 7]))
self.wid.append(b)
b.grid(row=w, column=d)
sel = tk.Label(self.parent, height=2, text='{} {} {} {}'.format(
self.day_name, calendar.month_name[self.month_selected], self.day_selected, self.year_selected))
self.wid.append(sel)
sel.grid(row=8, column=0, columnspan=7)
ok = tk.Button(self.parent, width=5, text='OK', command='disabled')
self.wid.append(ok)
ok.grid(row=9, column=2, columnspan=3, pady=10)
def win(parent, d):
win = tk.Toplevel(parent)
cal = Calendar(win, d)
data = Data()
root = tk.Tk()
win(root, data)
root.mainloop()
Answer: I believe what you want is a reusable Calendar widget that subclasses Frame.
It should start something like this
class Calendar(tk.Frame):
def __init__(self, master, data, **config):
tk.Frame.__init__(self, master, cnf=config)
self.data = data
...
and end, as Jon said, with
if __name__ == "__main__":
# all the stuff not needed when importing Calendar into another module>
def win(parent, d):
win = tk.Toplevel(parent)
cal = Calendar(win, d)
data = Data()
root = tk.Tk()
win(root, data)
root.mainloop()
As near as I can tell, class Data belongs here also, unless you generalize it
to take arguments.
|
Python posting answer from function to entry box in GUI
Question: I am trying to return an answer from simple addition to an entry box in Python
3.4 but keep getting the following error. Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__
return self.func(*args)
File "H:\guitest.py", line 12, in calculate
enter3.configure(text=answer)
AttributeError: 'NoneType' object has no attribute 'configure'
#Imports The Default Graphical Library
import tkinter
from tkinter import *
#Addition Function
def calculate():
""" take the two numbers entered and process them """
firstnum=int(number1.get())
secondnum=int(number2.get())
answer=firstnum+secondnum
enter3.configure(text=answer)
return
#Creates Graphical Window
window = Tk()
# Assigns a Name To the Graphical Window
window.title("MY GUI")
# Set the Graphical Window Size
window.geometry("500x200")
number1=StringVar()
number2=StringVar()
label1 = Label(text='1st Number').place(x=50,y=30)
label2 = Label(text='2nd Number').place(x=150,y=30)
label3 = Label(text='ANSWER').place(x=100,y=80)
enter1 =Entry(width=10,textvariable=number1).place(x=50,y=50)
enter2 =Entry(width=10,textvariable=number2).place(x=150,y=50)
enter3 =Entry(width=10).place(x=100,y=100)
#Creates Button
w = Button(text='ADD',bd=10,command=calculate).place(x=100,y=150)
#Executes the above Code to Create the Graphical Window
window.mainloop()
Answer: There are at least three problems here.
1. The variables that are supposed to be holding UI elements (e.g. `label1`, `entry3`) are not, in fact, holding them. They are set to `None`. The `place` method is not returning the object being placed. It's just doing the placing. So you'd need to change your initialization strategy to something like:
enter3 = Entry(width=10)
enter3.place(x=100,y=100)
If you argued that non-fluid style is less graceful, I'd agree...but
apparently `place` does not return the object, so you can't do _en passant_
creation and placement.
2. `entry3.configure(text=answer)` is not going to work, because `answer` is not a string. It's an integer. You need `entry3.configure(text=str(answer))`. At minimum.
3. I lied. That is not going to work either, because `configure` is not how `Entry` widget text is usually set. Try instead:
entry3.delete(0, END) # delete whatever's there already
entry3.insert(0, str(answer))
entry3.update() # make sure update is flushed / immediately visible
See e.g. [this tutorial](http://effbot.org/tkinterbook/entry.htm) for more on
`Entry` objects. And while explicit `widget.update()` calls may look clunky,
trust me--they come in super-handy when things don't update as you think they
should.
4. I'm not sure why you're using a hybrid strategy. For inputs, you use `StringVar` objects, but then you shift to a raw update for the answer widget. Not that it won't work...but it might be easier just to set `number3 = StringVar()` and attach it as the `textvariable` of `entry3`, then `number3.set(str(answer))` when you want to update it. Pick your poison.
Even if you make these changes, you'll have some work to do to have a "good"
Tk app, but these will at least make the updates work as they should, and get
you on your way.
|
Searching basic comments in C++ by regex
Question: I'm writing a Python program for searching comments in c++ program using
regex. I wrote the following code:
import re
regex = re.compile(r'(\/\/(.*?))\n|(\/\*(.|\n)*\*\/)')
comments = []
text = ""
while True:
try:
x= raw_input()
text = text + "\n"+ x
except EOFError:
break
z = regex.finditer(text)
for match in z:
print match.group(1)
this code should detect comment of type `//I'm comment` and `/*blah blah blah
blah blah*/` I'm getting following output:
// my program in C++
None
//use cout
Which is I'm not expecting. My thought is match.group(1) should capture the
first parenthesis of `(\/\*(.|\n)*\*\/)`, but it is not. The c++ program I'm
testing is:
// my program in C++
#include <iostream>
/** I love c++
This is awesome **/
using namespace std;
int main ()
{
cout << "Hello World"; //use cout
return 0;
}
Answer: You didn't use the good order to do that since an inline comment can be
include inside a multiline comment. So you need to begin your pattern with the
multiline comment. Example:
/\*[\s\S]*?\*/|//.*
Note that you can improve this pattern if you have long multiline comments
_(this syntax is an emulation of the atomic group feature that is not
supported by the re module)_ :
/\*(?:(?=([^*]+|\*(?!/))\1)*\*/|//.*
But note too that there are other traps like a string that contains `/*...*/`
or `//.....`.
So if you want to avoid these cases, for example if you want to make a
replacement, you need to capture before strings and to use a backreference in
the replacement string, like this:
(pattern for strings)|/\*[\s\S]*?\*/|//.*
replacement: `$1`
|
Can't find getcwd() function definition in os.py file
Question: I thought that I should be able to see the source code of packages that I
import in Python from the Python Standard Library. When I opened the os.py
file, I didn't see any definition of getcwd(). Why is this so?
Answer: `os` imports system dependent functions with
from posix import *
or
from nt import *
where `getcwd` is defined as C function.
|
How to use Tkinter's 'file' variable across different functions in Python?
Question: I'm using Python 2.7. I'm also using a library known as id3reader to get
metadata from mp3 files. If I use this code:
import tkFileDialog
import id3reader
file = tkFileDialog.askopenfile()
id3r = id3reader.Reader(file)
print(id3r.getValue('performer')
everything works just fine, and the artist of the song's name will be printed
out in the console.
However, I am trying to do this across different functions. So if I use this
code:
import tkFileDialog
import id3reader
def Load(self):
file = tkFileDialog.askopenfile()
def Display(self):
id3r = id3reader.Reader(file)
print(id3r.getValue('performer')
I get an error coming from within the id3reader script. If I use:
self.file
or
fileName = file
global fileName
I get a global variable not defined error.
How would I be able to use the built-in 'file' variable across different
functions?
Answer: You're confusing a bunch of different things.
First, the built-in `file` variable is the actual type of file objects. You
don't want to use that, you're trying to hide it with the filename you got
back from `askopenfile()`.
And `file` is not a Tkinter variable—neither the builtin, nor the one you're
creating, have anything to do with Tkinter.
The reason your code isn't working is that, inside the `Load` function, when
you write `file = tkFileDialog.askopenfile()`, you're creating a local
variable. That local variable hides the name of the global variable of the
same name, until the function exits, at which point it goes away.
Your attempt to use `self.file` is a great solution—except you don't have any
classes. If you want to learn about how to use classes in general, and the
idiomatic way to use them with Tkinter in particular, that's a great thing to
learn, but it's too much to teach in a StackOverflow answer, and Python
already comes with a great tutorial.
If you want to use a global variable, you can do that, but (a) you have to use
`global file`, not `global fileName`, if you want `file` to be global, and (b)
you have to put that _inside the`Load` function_, not at the top level. If you
do both of those, then that `file = tkFileDialog.askopenfile()` will now
reassign the global variable `file`, instead of hiding it with a local
variable, so the value will still be available once you're done, to any other
function that wants to access it.
However, a better solution is to not try to share a global variable. Just
`return` the value, and have the caller hold onto it and pass it into
`Display`. Since I can't see the code you're using to call those functions,
I'll have to make something up, but hopefully you can understand it and apply
it to your own code:
def Load():
return tkFileDialog.askopenfile()
def Display(file):
id3r = id3reader.Reader(file)
print(id3r.getValue('performer')
f = Load()
Display(f)
|
Regarding ICMP "Fragmentation needed, DF bit set" or ICMP packet too big message
Question: I'm injecting ICMP "Fragmentation needed, DF bit set" into the server and
ideally server should start sending packets with the size mentioned in the
field 'next-hop MTU' in ICMP. But this is not working.
Here is the server code:
#!/usr/bin/env python
import socket # Import socket module
import time
import os
range= [1,2,3,4,5,6,7,8,9]
s = socket.socket() # Create a socket object
host = '192.168.0.17' # Get local machine name
port = 12349 # Reserve a port for your service.
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port)) # Bind to the port
rand_string = os.urandom(1600)
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
for i in range:
c.sendall(rand_string)
time.sleep(5)
c.close()
Here is the client code:
#!/usr/bin/python # This is client.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = '192.168.0.17' # Get local machine name
port = 12348 # Reserve a port for your service.
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.connect((host, port))
while 1:
print s.recv(1024)
s.close()
Scapy to inject ICMP:
###[ IP ]###
version= 4
ihl= None
tos= 0x0
len= None
id= 1
flags= DF
frag= 0
ttl= 64
proto= ip
chksum= None
src= 192.168.0.45
dst= 192.168.0.17
\options\
###[ ICMP ]###
type= dest-unreach
code= fragmentation-needed
chksum= None
unused= 1300
Send(ip/icmp)
Unused field shows as next-hop MTU in wireshark. Is server smart enough to
check that DF Bit was not set when it was communicating with client and it is
still receiving ICMP "Fragmentation needed, DF bit set" message? If it is not
then why is server not reducing its packet size from 1500 to 1300?
Answer: First of all, let's answer your first question (is ICMP sent over TCP?).
ICMP runs directly over IP, as specified in [RFC
792](http://www.ietf.org/rfc/rfc0792.txt):
> ICMP messages are sent using the basic IP header.
This can be a bit confusing as [ICMP is classified as a network layer protocol
rather than a transport layer
protocol](http://stackoverflow.com/a/26275365/3903832) but it makes sense when
taking into account that it's merely an addition to IP to carry error, routing
and control messages and data. Thus, it can't rely on the TCP layer to
transfer itself since the TCP layer depends on the IP layer which ICMP helps
to manage and troubleshoot.
* * *
Now, let's deal with your second question (How does TCP come to know about the
MTU if ICMP isn't sent over TCP?). I've tried to answer this question to the
best of my understanding, with reliance on official specifications, but
perhaps the best approach would be to analyze some open source network stack
implementation in order to see what's really going on...
The TCP layer may come to know of the path's MTU value even though the ICMP
message is not layered upon TCP. It's up to the implementation of OS the
network stack to notify the TCP layer of the MTU so it can then use this value
to update its MSS value.
[RFC 1122](http://tools.ietf.org/html/rfc1122) requires that the ICMP message
includes the IP header as well as the first 8 bytes of the problematic
datagram that triggered that ICMP message:
> Every ICMP error message includes the Internet header and at least the first
> 8 data octets of the datagram that triggered the error; more than 8 octets
> MAY be sent; this header and data MUST be unchanged from the received
> datagram.
>
> In those cases where the Internet layer is required to pass an ICMP error
> message to the transport layer, the IP protocol number MUST be extracted
> from the original header and used to select the appropriate transport
> protocol entity to handle the error.
This illustrates how the OS can pinpoint the TCP connection whose MSS should
be updated, as these 8 bytes include the source and destination ports.
RFC 1122 also states that there MUST be a mechanism by which the transport
layer can learn the maximum transport-layer message size that may be sent for
a given {source, destination, TOS} triplet. Therefore, I assume that once an
`ICMP Fragmentation needed and DF set` error message is received, the MTU
value is somehow made available to the TCP layer that can use it to update its
MSS value.
Furthermore, I think that the application layer that instantiated the TCP
connection and taking use of it may handle such messages as well and fragment
the packets at a higher level. The application may open a socket that expects
ICMP messages and act accordingly when such are received. However, fragmenting
packets at the application layer is totally transparent to the TCP & IP
layers. Note that most applications would allow the TCP & IP layers to handle
this situation by themselves.
However, once an `ICMP Fragmentation needed and DF set` error message is
received by a host, its behavior as dictated by the lower layers is not
conclusive.
[RFC 5927, section 2.2](http://tools.ietf.org/html/rfc5927#section-2.2) refers
to RFC 1122, section 4.2.3.9 which states that TCP should abort the connection
when an `ICMP Fragmentation needed and DF set` error message is passed up from
the IP layer, since it signifies a hard error condition. The RFC states that
the host should implement this behavior, but it is not a must (section 4.2.5).
This RFC also states in section 3.2.2.1 that a Destination Unreachable message
that is received MUST be reported to the TCP layer. Implementing both of these
would result in the destruction of a TCP connection when an `ICMP
Fragmentation needed and DF set` error message is received on that connection,
which doesn't make any sense, and is clearly not the desired behavior.
On the other hand, [RFC 1191](http://www.ietf.org/rfc/rfc1191.txt) states
[this](http://seclists.org/bugtraq/2001/Jan/219) in regard to the required
behavior:
> RFC 1191 does not outline a specific behavior that is expected from the
> sending host, because different applications may have different
> requirements, and different implementation architectures may favor different
> strategies [This leaves a room for this method-OA].
>
> The only required behavior is that a host must attempt to avoid sending more
> messages with the same PMTU value in the near future. A host can either
> cease setting the Don't Fragment bit in the IP header (and allow
> fragmentation by the routers in the way) or reduce the datagram size. The
> better strategy would be to lower the message size because fragmentation
> will cause more traffic and consume more Internet resources.
For conclusion, I think that the specification is not definitive in regard to
the required behavior from a host upon receipt of an `ICMP Fragmentation
needed and DF set` error message. My guess is that both layers (IP & TCP) are
notified of the message in order to update their MTU & MSS values,
respectively and that one of them takes upon the responsibility of
retransmitting the problematic packet in smaller chunks.
* * *
Lastly, regarding your implementation, I think that for full compliance with
RFC 1122, you should update the ICMP message to include the IP header of the
problematic packet, as well as its next 8 bytes (though you may include more
than just the first 8 bytes). Moreover, you should verify that the ICMP
message is received before the corresponding ACK for the packet to which that
ICMP message refers. In fact, just in order to be on the safe side, I would
abolish that ACK altogether.
[Here](http://www.packetlevel.ch/html/scapy/download/pmtu.py) is a sample
implementation of how the ICMP message should be built. If sending the ICMP
message as a response to one of the TCP packets fails, I suggest you try
sending the ICMP message before even receiving the TCP packet to which it
relates at first, in order to assure it is received before the ACK. Only if
that fails as well, try abolishing the ACK altogether.
|
Python read a file and make a nth list from the
Question: I have a file that each line has 2 element like below which have nth lines:
1 2
2 3
3 4
4 5
1 6
2 7
1 8
I need to make a list in python.
list[1]=[2,6,8]
list[2]=[3,7]
list[3]=[4]
list[4]=[5]
How can I do?
Answer: Try
import pandas as pd
a = [[1,2], [2,3], [3,4], [4, 5], [1, 6], [2,7], [1,8]]
df = pd.DataFrame(a,columns=['b','c'])
print df
z = df.groupby(['b']).apply(lambda tdf:pd.Series(dict([[vv,tdf[vv].unique().tolist()] for vv in tdf if vv not in ['b']])))
z = z.sort_index()
print z
print z['c'][1]
print z['c'][2]
print z['c'][3]
print z['c'][4]
z['d'] = 0.000
z[['d']] = z[['d']].astype(float)
len_b = len(z.index)
z['d'] = float(len_b)
z['e'] = 1/z['d']
z = z[['c', 'e']]
z.to_csv('your output folder')
print z
See this answer for more details:
<http://stackoverflow.com/a/24112443/2632856>
|
Is there a more pythonic way to write
Question: Learning to be pythonic in 2.7. Is there a way to avoid the explicit loop?
answer = `[5, 4, 4, 3, 3, 2]`
import numpy as np
import scipy.special as spe
nmax = 5 # n = 0, 1 ...5
mmax = 7 # m = 1, 2 ...7
big = 15.
z = np.zeros((nmax+1, mmax))
for i in range(nmax+1):
z[i] = spe.jn_zeros(i, mmax)
answer = [np.max(np.where(z[i]<big))+1 for i in range(nmax+1)]
print answer # list of the largest m for each n where the mth zero of Jn < big
Answer: What does "more Pythonic" really mean here. One of the core tenets of Python
is readability, so if there is no real performance reason to get rid of the
loops, just keep them.
If you really wanted to see some other ways to do the same thing, then:
z = np.zeros((nmax+1, mmax))
for i in range(nmax+1):
z[i] = spe.jn_zeros(i, mmax)
could be replaced with:
func = lambda i:spe.jn_zeros(i,mmax)
np.vstack(np.vectorize(func, otypes=[np.ndarray])(np.arange(nmax+1)))
which is slightly faster (1.35 ms vs. 1.77 ms) but probably less Pythonic and
[np.max(np.where(z[i]<big))+1 for i in range(nmax+1)]
could be replaced by
np.cumsum(z < big,axis=1)[:,-1]
which I would argue is more Pythonic (or numpythonic) and much faster (20 us
vs. 212 us).
|
How to use the liblinearutil package to train and predict test file in python?
Question: Can anyone give any insight about the liblinearutil package in python? I want
to train and test files. I did read the documentation but don't quite
understand. I'm doing it this way:
from liblinearutil import *
def testing_func(train_file, test_file)
prob, param = svm_read_problem(train_file)
m = liblinear.train(prob, param)
print "m"
print m
p_labels, p_acc, p_vals = liblinear.predict(y,x, m, '-b 1')
print (p_labels, p_acc, p_vals)
But, I'm getting "No module named liblinearutil error"! Could somebody please
explain!!
Answer: this error tell you that liblinearutil is not installed ;) it's not available
in pipy so you need to build from source for the good interpret (care if you
have different python version installed)
|
categorizing string according to length in Python
Question: I have given n different strings. I have to form different lists of strings
according to the list. For example, given strings are
`this,that,is,am,are,i,j` then four lists should be generated like:
s[1] = [i,j]
s[2] = [is,am]
s[3] = [are]
s[4] = [this,that]
These lists must be easily accessible by their index (in this case, length)
Answer: You could use
[defaultdict](https://docs.python.org/2/library/collections.html#collections.defaultdict):
from collections import defaultdict
words = ['this','that','is','am','are','i','j']
with_lengths = [(word, len(word)) for word in words]
output = defaultdict(list)
for k, v in with_lengths:
output[v].append(k)
for key in output:
print '%i -> %s' % (key, output[key])
Output:
1 -> ['i', 'j']
2 -> ['is', 'am']
3 -> ['are']
4 -> ['this', 'that']
|
Python finite difference method for differential equations
Question: I must solve the Euler Bernoulli differential beam equation which is:
u’’’’(x) = f(x) ;
(x is the coordinate of the beam axis points)
and boundary conditions:
u(0)=0, u’(0)=0, u’’(1)=0, u’’’(1)=a
I have studied the theory of numerically finite differences which expresses
the series of derivations as:
U’k = (1/2*h)(Uk+1 - Uk-1)
U’’k = (1/h2)(Uk+1 - 2 Uk + Uk-1)
U’’’k = (1/2h3)(Uk+2 - 2 Uk+1 + 2 Uk-1 + Uk-2)
U’’’’k = (1/h4)(Uk+2 - 4 Uk+1 + 6 Uk - 4 Uk-1 + Uk-2)
(`k+1`, `k+2`, etc. etc are subscripts)
and I found a script which expresses it as follows:
import numpy as np
from scipy.linalg import solveh_banded
import matplotlib.pyplot as plt
def beam4(n,ffun,a):
x = np.linspace(0,1,n+1)
h = 1.0/n
stencil = np.array((1,-4,6))
B = np.outer(stencil,np.ones(n))
B[1,-1] = -2; B[2,0] = 7; B[2,-1] = 1; B[2,-2] = 5
f = ffun(x)
f *= h** 4; f[-1] *= 0.5; f[-1] -= a*h**3
u = np.zeros(n+1)
u[1:] = solveh_banded(B,f[1:],lower=False)
return x,u
But I can't understand why the coefficient matrix is built this way:
stencil = np.array((1,-4,6))
B = np.outer(stencil,np.ones(n))
B[1,-1] = -2; B[2,0] = 7; B[2,-1] = 1; B[2,-2] = 5
f = ffun(x)
f *= h**4; f[-1] *= 0.5; f[-1] -= a*h**3 "
Thanks in advance!!!!
Answer: Hope this is helpful. (due to this is my first time to post an answer)
The coefficients of this Hermitian positive-definite banded matrix are due to
applied of ghost node method. It is one of most efficient and popular method
for treating the boundary conditions of FDM without lossing of accuracy (here
these coefficients will give a second order converge rate in general). If you
have trouble to visual the matrix please check the 'K' matrix in my code
below:
from numpy import linspace,zeros,array,eye,dot
from numpy.linalg import solve
from pylab import plot,xlabel,ylabel,legend,show
a = 0.2 ;b = 0.0
LX,dx = 1.0,0.05 ;nx = int(LX/dx)+1
X = linspace(0.0,LX,nx)
Fs = X**2.0
""""""""""""""""""""""""""""""""""""""""""""""""""""""
def calcB(l,b):
if b==0: return [0.0,0.0]
elif b==1: return 1.0/l/l/l/l*array([-4.0,7.0,-4.0,1.0])
elif b==nx-2: return 1.0/l/l/l/l*array([1.0,-4.0,5.0,-2.0])
elif b==nx-1: return 1.0/l/l/l/l*array([2.0,-4.0,2.0])
else: return 1.0/l/l/l/l*array([1.0,-4.0,6.0,-4.0,1.0])
U = zeros(nx) ;V = zeros(nx)
M = eye(nx) ;K = zeros((nx,nx))
F = zeros(nx) ;F[nx-2] = -b/dx/dx
F[nx-1] = 2.0*b/dx/dx-2.0*a/dx
for i in range(nx):
if i == 0: I = [i,i+1]
elif i == 1: I = [i-1,i,i+1,i+2]
elif i == nx-2: I = [i-2,i-1,i,i+1]
elif i == nx-1: I = [i-2,i-1,i]
else: I = [i-2,i-1,i,i+1,i+2]
for k,j in enumerate(I):
K[i,j] += calcB(dx,i)[k]
""""""""""""""""""""""""""""""""""""""""""""""""""""""
pn = [0] ;eq2 = pn
eq1 = [i for i in range(nx) if i not in pn]
MM1_ = K[eq1,:]; MM11,MM12 = MM1_[:,eq1],MM1_[:,eq2]
RR = F+Fs
U[eq2] = [0.0]
U[eq1] = solve(MM11,(RR[eq1]-dot(MM12,U[eq2])))
######################Plotting#########################
Us = lambda x: x**6.0/360.0+x**3.0/6.0*(a-1.0/3.0)+x**2.0/2.0*(1.0/4.0-a)
plot(X,U,'bo',label='FDM') ;plot(X,Us(X),'g-',label='solution')
xlabel('X'); ylabel('U'); legend(loc='best')
show()
cheers
|
Selenium get http response headers or access the browsers's download history
Question: I use python 2.7 and the selenium driver as downloaded from
pip install selenium
How can I get the http headers from a web request.
In particular I click a button/link and the server replies with a response
containing a csv file.
It would be awesome if I could get the filename from the http headers.
Another option would e to access the browser's download history.
Any ideas how the above can be achieved?
Answer: Selenium can't actually do this (capture network traffic). I would suggest
using a third party tool like [Browser
Mob](https://github.com/lightbody/browsermob-proxy)
I don't know if you can get your browser's download history... but as a
workaround you can just [download files](http://selenium-
python.readthedocs.org/faq.html) to an empty directory, and just call that
your download history. You could also rank files by time downloaded using
`os.path.getmtime`
import os
from selenium import webdriver
fp = webdriver.FirefoxProfile()
fp.set_preference("browser.download.folderList",2)
fp.set_preference("browser.download.manager.showWhenStarting",False)
fp.set_preference("browser.download.dir", "/tmp/empty-dir")
fp.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/octet-stream")
browser = webdriver.Firefox(firefox_profile=fp)
browser.get("http://pypi.python.org/pypi/selenium")
browser.find_element_by_partial_link_text("selenium-2").click()
os.listdir("/tmp/empty-dir")
['selenium-2.44.0.tar.gz']
|
check date range with only month and year in Python
Question: I only have `month` and `year`, and I want to compare if that **period** (of
an entire month) is between two `datetime` objects. For example if I have
these two dates:
min_post_date = 2013-03-07 00:00:00
max_post_date = 2014-01-01 00:00:00
And I only have year `2013`, and month `03`, it should give me `True`,
`02-2013` should give `False`, `04-2014` should give `False` and of course
`08-2013` should give `True`.
What would you recommend?
Thanks.
Answer: You can first compute the two dates at the beginning and the end of your
month:
from calendar import monthrange
from datetime import date, datetime
begin = date(year, month, 1)
end = date(year, month, monthrange(year, month)[1])
Then you can simply check that either `begin` or `end` fall within your range:
(min_post_date <= begin <= max_post_date) or (min_post_date <= end <= max_post_date)
This is assuming that you parsed `min_post_date` and `max_post_date` with:
min_post_date = datetime.strptime(min_post_date.split()[0], "%Y-%m-%d").date()
and similarly for `max_post_date`.
|
How to use a wrapper function that i generated using swig in python?
Question: Okay, I am new to swig. I have finally successfully wrapped the most expensive
part of my python program using swig and also numpy.i . The program is a
finite difference scheme for the 2D wave PDE . My question is how do I use it
now ? I can see it after I import it within IPython.
In [1]: import wave2
In [2]: wave2.wave_prop
Out[2]: <function _wave2.wave_prop>
But, when I go to use it I get an error saying:
TypeError: in method 'wave_prop', argument 1 of type 'float **'
How can I transform my 2D numpy arrays to some form that will enable me to use
this. There is another stackoverflow that is very similar that did not help
me, although I have found a lot of help with this matter along the way.
Here is the header:
void wave_prop(float** u_prev ,int Lx, int Ly,float** u ,int Lx2, int Ly2,float** u_next,int Lx3,int Ly3 );
Here is the c code:
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#define n 100
void wave_prop(float** u_prev ,int Lx,int Ly,float** u ,int Lx2,int Ly2,float** u_next,int Lx3,int Ly3 ){
int dx=1;
int dy=1;
float c=1;
float dt =1;
int t_old=0;int t=0;int t_end=150;
int x[Lx];
int y[Ly];
for(int i=0;i<=99;i++){
x[i]=i;
y[i]=i;
}
while(t<t_end){
t_old=t; t +=dt;
//the wave steps through time
for (int i=1;i<99;i++){
for (int j=1;j<99;j++){
u_next[i][j] = - u_prev[i][j] + 2*u[i][j] + \
(c*dt/dx)*(c*dt/dx)*u[i-1][j] - 2*u[i][j] + u[i+1][j] + \
(c*dt/dx)*(c*dt/dx)*u[i][j-1] - 2*u[i][j] + u[i][j+1];
}
}
//set boundary conditions to 0
for (int j=0;j<=99;j++){ u_next[0][j] = 0;}
for (int i=0;i<=99;i++){ u_next[i][0] = 0;}
for (int j=0;j<=99;j++){ u_next[Lx-1][j] = 0;}
for (int i=0;i<=99;i++){ u_next[i][Ly-1] = 0;}
//memcpy(dest, src, sizeof (mytype) * rows * coloumns);
memcpy(u_prev, u, sizeof (float) * Lx * Ly);
memcpy(u, u_next, sizeof (float) * Lx * Ly);
}
}
And here is my interface:
%module wave2
%{
#define SWIG_FILE_WITH_INIT
#include "wave2.h"
%}
%include "numpy.i"
%init %{
import_array();
%}
%include "wave2.h"
%apply (float** INPLACE_ARRAY2, int DIM1, int DIM2) { (float** u_prev,int Lx,int Ly ),(float** u,int Lx2,int Ly2),(float* u_next,int Lx3,int Ly3)}
These are the commands I used to compile and link:
$ swig -python wave2.i
$ gcc -c -fpic wave2.c wave2_wrap.c -I/usr/include/python2.7 -std=c99
$ gcc -shared wave2.o wave2_wrap.o -o _wave2.so
Without any errors or warnings. There is a lack of intermediate examples like
this on the internet, trust me I have scoured!, so if WE can get this working
it could serve as a good tutorial for someone. Please do not mark my question
down then go away into the night . If you think some of my coding needs
improvement please let me know I am trying to basically teach myself
everything right now... Thank you very much for your help
Oh and also here is a script that I am trying to use it in. I have also tried
to use the function in other ways within IPython...
'''George Lees Jr.
2D Wave pde '''
from numpy import *
import numpy as np
import matplotlib.pyplot as plt
from wave2 import *
import wave2
#declare variables
#need 3 arrays u_prev is for previous time step due to d/dt
Lx=Ly = (100)
n=100
dx=dy = 1
x=y = np.array(xrange(Lx))
u_prev = np.array(zeros((Lx,Ly),float))
u = np.array(zeros((Lx,Ly),float))
u_next = np.array(zeros((Lx,Ly),float))
c = 1 #constant velocity
dt = (1/float(c))*(1/sqrt(1/dx**2 + 1/dy**2))
t_old=0;t=0;t_end=150
#set Initial Conditions and Boundary Points
#I(x) is initial shape of the wave
#f(x,t) is outside force that creates waves set =0
def I(x,y): return exp(-(x-Lx/2.0)**2/2.0 -(y-Ly/2.0)**2/2.0)
def f(x,t,y): return 0
#set up initial wave shape
for i in xrange(100):
for j in xrange(100):
u[i,j] = I(x[i],y[j])
#copy initial wave shape for printing later
u1=u.copy()
#set up previous time step array
for i in xrange(1,99):
for j in xrange(1,99):
u_prev[i,j] = u[i,j] + 0.5*((c*dt/dx)**2)*(u[i-1,j] - 2*u[i,j] + u[i+1,j]) + \
0.5*((c*dt/dy)**2)*(u[i,j-1] - 2*u[i,j] + u[i,j+1]) + \
dt*dt*f(x[i], y[j], t)
#set boundary conditions to 0
for j in xrange(100): u_prev[0,j] = 0
for i in xrange(100): u_prev[i,0] = 0
for j in xrange(100): u_prev[Lx-1,j] = 0
for i in xrange(100): u_prev[i,Ly-1] = 0
wave2.wave_prop( u_prev ,Lx ,Ly , u , Lx, Ly, u_next,Lx,Ly )
#while t<t_end:
# t_old=t; t +=dt
#the wave steps through time
# for i in xrange(1,99):
# for j in xrange(1,99):
# u_next[i,j] = - u_prev[i,j] + 2*u[i,j] + \
# ((c*dt/dx)**2)*(u[i-1,j] - 2*u[i,j] + u[i+1,j]) + \
# ((c*dt/dx)**2)*(u[i,j-1] - 2*u[i,j] + u[i,j+1]) + \
# dt*dt*f(x[i], y[j], t_old)
#
# #set boundary conditions to 0
#
# for j in xrange(100): u_next[0,j] = 0
# for i in xrange(100): u_next[i,0] = 0
# for j in xrange(100): u_next[Lx-1,j] = 0
# for i in xrange(100): u_next[i,Ly-1] = 0
#set prev time step equal to current one
# u_prev = u.copy(); u = u_next.copy();
fig = plt.figure()
plt.imshow(u,cmap=plt.cm.ocean)
plt.colorbar()
plt.show()
print u_next
Also yes I checked to make sure that the arrays were all numpy nd array types
Answer: Okay so i was able to accomplish what i wanted to in Cython, thank god. In the
process I found Cython much more powerful of a tool !
So the result is a 2D wave PDE solved using a finite difference. The main
computation has been exported to a Cythonized function. The function takes in
three 2D np.ndarrays and returns one back. Much easier to work with numpy and
other data types as well.
Here is the Cythonized function:
from numpy import *
cimport numpy as np
def cwave_prop( np.ndarray[double,ndim=2] u_prev, np.ndarray[double,ndim=2] u, np.ndarray[double,ndim=2] u_next):
cdef double t = 0
cdef double t_old = 0
cdef double t_end = 100
cdef int i,j
cdef double c = 1
cdef double Lx = 100
cdef double Ly = 100
cdef double dx = 1
cdef double dy = 1
cdef double dt = (1/(c))*(1/(sqrt(1/dx**2 + 1/dy**2)))
while t<t_end:
t_old=t; t +=dt
#wave steps through time and space
for i in xrange(1,99):
for j in xrange(1,99):
u_next[i,j] = - u_prev[i,j] + 2*u[i,j] + \
((c*dt/dx)**2)*(u[i-1,j] - 2*u[i,j] + u[i+1,j]) + \
((c*dt/dx)**2)*(u[i,j-1] - 2*u[i,j] + u[i,j+1])
#set boundary conditions of grid to 0
for j in xrange(100): u_next[0,j] = 0
for i in xrange(100): u_next[i,0] = 0
for j in xrange(100): u_next[Lx-1,j] = 0
for i in xrange(100): u_next[i,Ly-1] = 0
#set prev time step equal to current one
for i in xrange(100):
for j in xrange(100):
u_prev[i,j] = u[i,j];
u[i,j] = u_next[i,j];
print u_next
And here is my python script that calls it and also returns it back then plots
the result. Any suggestions on writing better code are welcome...
'''George Lees Jr.
2D Wave pde '''
from numpy import *
import numpy as np
import matplotlib.pyplot as plt
import cwave2
np.set_printoptions(threshold=np.nan)
#declare variables
#need 3 arrays u_prev is for previous time step due to time derivative
Lx=Ly = (100) #Length of x and y dims of grid
dx=dy = 1 #derivative of x and y respectively
x=y = np.array(xrange(Lx)) #linspace to set the initial condition of wave
u_prev=np.ndarray(shape=(Lx,Ly), dtype=np.double) #u_prev 2D grid for previous time step needed bc of time derivative
u=np.ndarray(shape=(Lx,Ly), dtype=np.double) #u 2D grid
u_next=np.ndarray(shape=(Lx,Ly), dtype=np.double) #u_next for advancing the time step #also these are all numpy ndarrays
c = 1 #setting constant velocity of the wave
dt = (1/float(c))*(1/sqrt(1/dx**2 + 1/dy**2)) #we have to set dt specifically to this or numerical approx will fail!
print dt
#set Initial Conditions and Boundary Points
#I(x) is initial shape of the wave
def I(x,y): return exp(-(x-Lx/2.0)**2/2.0 -(y-Ly/2.0)**2/2.0)
#set up initial wave shape
for i in xrange(100):
for j in xrange(100):
u[i,j] = I(x[i],y[j])
#set up previous time step array
for i in xrange(1,99):
for j in xrange(1,99):
u_prev[i,j] = u[i,j] + 0.5*((c*dt/dx)**2)*(u[i-1,j] - 2*u[i,j] + u[i+1,j]) + \
0.5*((c*dt/dy)**2)*(u[i,j-1] - 2*u[i,j] + u[i,j+1])
#set boundary conditions to 0
for j in xrange(100): u_prev[0,j] = 0
for i in xrange(100): u_prev[i,0] = 0
for j in xrange(100): u_prev[Lx-1,j] = 0
for i in xrange(100): u_prev[i,Ly-1] = 0
#call C function from Python
cwave2.cwave_prop( u_prev , u , u_next )
#returned u (2D np.ndarray)
from tempfile import TemporaryFile
outfile = TemporaryFile()
np.save(outfile,u)
fig = plt.figure()
plt.imshow(u,cmap=plt.cm.ocean)
plt.colorbar()
plt.show()
|
Python 2.7.6 - Printing a string on a fixed position while creating a dynamic histogram
Question: I created a little script that check virtual memory and how much is being
used. According to the number that comes back it creates a histogram. The
original script creates the following output.
VIRT MEMORY USAGE: 43.5
0----------------100%
||||||||
However I want the output to be like
VIRT MEMORY USAGE: 43.5
0|||||||| 100%
The problem I am having is that the "100%" is not in a fixed position. It will
move left or right according to how many "|" are being generated by the loop.
This does not create the effect desired. :(
The code follows below.
#!/usr/bin/python
import psutil
import socket
print "Hostname: ", (socket.gethostname())
print ""
virtu_full_num = psutil.virtual_memory().percent
print "VIRT MEMORY USAGE: ", virtu_full_num
#print "0----------------100%" # From original version of script
number = int(float(psutil.virtual_memory().percent))
for loop_hist in range (1):
number = number / 10
print "0 %s " % ("||" *number), " 100"
#print "%s" % ("||" *number) #From original version of script
Answer: It should be pretty straightforward. Figure out how many space characters
there would be between `0` and `100`. For every `|` character you add, remove
one space character. Add the two up at the end, and you should be all set.
|
Python: Find closest match of multiple words in text file
Question: I need to parse multiple financial statement .txt files similarly to this
[one](http://www.sec.gov/Archives/edgar/data/320193/000104746904035975/0001047469-04-035975.txt).
The .txt files do not have standardized format. However, they have similar
headings. My objective is to extract the section of the .txt files that starts
with the following keywords `['Item', '7', 'Management', 'Analysis']` and ends
with `['Item', '8', 'Financial', 'Statements']`. The order of the words in
both list matter and `['Item', '7', 'Management', 'Analysis']` comes before
`['Item', '8', 'Financial', 'Statements']`.
What I have in mind is to start with:
fdir = open('C:\\0001193125-13-416534.txt','r')
lines = fdir.readlines()
and loop over each line in `lines` and use
[`difflib.get_close_matches`](http://stackoverflow.com/questions/10018679/python-
find-closest-string-from-a-list-to-another-string) to find the above keywords.
However, I have two issues: (1) How can I use `difflib` to search for more
than one word? (2) I know that `difflib` will simply extract the match word,
but how can I use it to find the `index` (location in the list `lines`) of
where exactly in `lines` are located these words?
Let me add a third issue: Is using `.readlines()` the appropriate way to read
the txt file and start searching for the match words or should I simply use
`.read()`?
Answer: You can use `re` here with f.read().
f.read() return a string whereas f.readlines() returns a list.
import re
x=f.read()
print re.findall(r"Item(?:(?!Item).)*7(?:(?!Item|7).)*Management(?:(?!Item|7|Management).)*Analysis[\s\S]*Item(?:(?!Item).)*8(?:(?!Item|8).)*Financial(?:(?!Item|8|Financial).)*Statements",x)
|
Where does Whoosh (Python) physically store the indexed content?
Question: I am beginning to research on content indexing implementation, and was having
a look at Whoosh (<https://pypi.python.org/pypi/Whoosh/>).
I am curious to know where Whoosh stores its content physically - Is it using
files?
Answer: Whoosh uses a [pluggable storage
system](http://pythonhosted.org//Whoosh/api/filedb/filestore.html?highlight=filestorage#whoosh.filedb.filestore.Storage);
if you use the [`create_in()`
function](http://pythonhosted.org//Whoosh/api/index.html?highlight=create_in#whoosh.index.create_in)
then a [`FileStorage()`
class](http://pythonhosted.org//Whoosh/api/filedb/filestore.html?highlight=filestorage#whoosh.filedb.filestore.FileStorage)
is used that stores indexes in files in a directory.
See the [Whoosh quickstart](https://pythonhosted.org/Whoosh/quickstart.html):
> Once you have the schema, you can create an index using the `create_in`
> function:
>
>
> import os.path
> from whoosh.index import create_in
>
> if not os.path.exists("index"):
> os.mkdir("index")
> ix = create_in("index", schema)
>
>
> (At a low level, this creates a `Storage` object to contain the index. A
> `Storage` object represents that medium in which the index will be stored.
> Usually this will be `FileStorage`, which stores the index as a set of files
> in a directory.)
|
how to implement the python `zip` function in golang?
Question: Sometimes, it's convenient to combine two lists into a tuple using `zip`
built-in function in Python. How to make this similarly in golang?
Answer: You could do something like [this](http://play.golang.org/p/CYtr4Z-UQ-), where
you give the tuple type a name:
package main
import "fmt"
type intTuple struct {
a, b int
}
func zip(a, b []int) ([]intTuple, error) {
if len(a) != len(b) {
return nil, fmt.Errorf("zip: arguments must be of same length")
}
r := make([]intTuple, len(a), len(a))
for i, e := range a {
r[i] = intTuple{e, b[i]}
}
return r, nil
}
func main() {
a := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}
b := []int{0, 9, 8, 7, 6, 5, 4, 3, 2, 1}
fmt.Println(zip(a, b))
}
Or alternatively use an unnamed type for the tuple, like
[this](http://play.golang.org/p/afX6bxzWRd):
package main
import "fmt"
func zip(a, b []int) ([][3]int, error) {
if len(a) != len(b) {
return nil, fmt.Errorf("zip: arguments must be of same length")
}
r := make([][4]int, len(a), len(a))
for i, e := range a {
r[i] = [2]int{e, b[i]}
}
return r, nil
}
func main() {
a := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}
b := []int{0, 9, 8, 7, 6, 5, 4, 3, 2, 1}
fmt.Println(zip(a, b))
}
And finally [here's](http://play.golang.org/p/4M8yXQaLe_) a soft-generic way
of doing it:
package main
import (
"fmt"
"reflect"
)
func zip(a, b, c interface{}) error {
ta, tb, tc := reflect.TypeOf(a), reflect.TypeOf(b), reflect.TypeOf(c)
if ta.Kind() != reflect.Slice || tb.Kind() != reflect.Slice || ta != tb {
return fmt.Errorf("zip: first two arguments must be slices of the same type")
}
if tc.Kind() != reflect.Ptr {
return fmt.Errorf("zip: third argument must be pointer to slice")
}
for tc.Kind() == reflect.Ptr {
tc = tc.Elem()
}
if tc.Kind() != reflect.Slice {
return fmt.Errorf("zip: third argument must be pointer to slice")
}
eta, _, etc := ta.Elem(), tb.Elem(), tc.Elem()
if etc.Kind() != reflect.Array || etc.Len() != 2 {
return fmt.Errorf("zip: third argument's elements must be an array of length 2")
}
if etc.Elem() != eta {
return fmt.Errorf("zip: third argument's elements must be an array of elements of the same type that the first two arguments are slices of")
}
va, vb, vc := reflect.ValueOf(a), reflect.ValueOf(b), reflect.ValueOf(c)
for vc.Kind() == reflect.Ptr {
vc = vc.Elem()
}
if va.Len() != vb.Len() {
return fmt.Errorf("zip: first two arguments must have same length")
}
for i := 0; i < va.Len(); i++ {
ea, eb := va.Index(i), vb.Index(i)
tt := reflect.New(etc).Elem()
tt.Index(0).Set(ea)
tt.Index(1).Set(eb)
vc.Set(reflect.Append(vc, tt))
}
return nil
}
func main() {
a := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}
b := []int{0, 9, 8, 7, 6, 5, 4, 3, 2, 1}
c := [][2]int{}
e := zip(a, b, &c)
if e != nil {
fmt.Println(e)
return
}
fmt.Println(c)
}
|
Installing Pygame on mac (OS X Yosemite)
Question: I have been trying to get pygame working on my mac for ages. I have been using
it on a windows laptop but it is far too slow. I tried taking all the files
from there and putting them into the correct location on my mac because
downloading the mac versions was not working. However, I had .pyd extensions
so does anyone know what they should be changed to? I tried .so and now this
error is coming up:
import pygame
File "/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/site-packages/pygame/__init__.py", line 95, in <module>
from pygame.base import *
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/site-packages/pygame/base.so, 2): no suitable image found. Did find:
/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/site-packages/pygame/base.so: unknown file type, first eight bytes: 0x4D 0x5A 0x90 0x00 0x03 0x00 0x00 0x00
Does anyone know how to fix this?
Thanks :)
UPDATE: I have gone through the proper route and now this error is appearing:
Traceback (most recent call last): File "", line 1, in import pygame File
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-
packages/pygame/**init**.py", line 95, in from pygame.base import *
ImportError:
dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-
packages/pygame/base.so, 2): no suitable image found. Did find:
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-
packages/pygame/base.so: no matching architecture in universal wrapper
I have heard that this is due to conflicting 32bit and 64bit but I am not sure
how to overcome this.. Thanks again :)
Answer: Download 32-bit python and 32-bit pygame.
It worked for me and I am currently using pygame with (almost) no problems
whatsoever.
|
How do I make Python 3.4 keep score of the amount of guesses made?
Question: I am making a Guess the Number game in Python, and I want to make Python keep
score of how many times it took you to guess the number before you got it
right. How would I go about doing this? If needed, I can post my code to view.
Thank you.
import time
import os
from random import randrange, uniform
#Difficulty - Easy
def easy():
print ("")
print ("Difficulty: Easy")
print ("")
irand = randrange(1,10)
with open("GTN.txt", "a") as text_file:
text_file.write(str(irand) + " Easy" + "\n")
while True:
number = input("Pick a number 1 - 10: ")
try:
number = int(number)
except ValueError:
print(" ")
print(number, 'is not a number, try again.')
continue
if number > irand:
print("That's too high, try again.")
print(" ")
time.sleep(1)
elif number < irand:
print("That's too low, try again.")
print(" ")
time.sleep(1)
elif number == irand:
print(" ")
print("You got it right! You won!")
print(" ")
time.sleep(2)
main()
break
#Difficulty - Medium
def medium():
print ("")
print ("Difficulty: Medium")
print ("")
irand = randrange(1,100)
with open("GTN.txt", "a") as text_file:
text_file.write(str(irand) + " Medium" + "\n")
while True:
number = input("Pick a number 1 - 100: ")
try:
number = int(number)
except ValueError:
print(" ")
print(number, 'is not a number, try again.')
continue
if number > irand:
print("That's too high, try again.")
print(" ")
time.sleep(1)
elif number < irand:
print("That's too low, try again.")
print(" ")
time.sleep(1)
elif number == irand:
print(" ")
print("You got it right! You won!")
print(" ")
time.sleep(2)
main()
break
#Difficulty - Hard
def hard():
print ("")
print ("Difficulty: Hard")
print ("")
irand = randrange(1,1000)
with open("GTN.txt", "a") as text_file:
text_file.write(str(irand) + " Hard" + "\n")
while True:
number = input("Pick a number 1 - 1,000: ")
try:
number = int(number)
except ValueError:
print(" ")
print(number, 'is not a number, try again.')
continue
if number > irand:
print("That's too high, try again.")
print(" ")
time.sleep(1)
elif number < irand:
print("That's too low, try again.")
print(" ")
time.sleep(1)
elif number == irand:
print(" ")
print("You got it right! You won!")
print(" ")
time.sleep(2)
main()
break
#Difficulty - Ultra
def ultra():
print ("")
print ("Difficulty: Ultra")
print ("")
irand = randrange(1,100000)
with open("GTN.txt", "a") as text_file:
text_file.write(str(irand) + " Ultra" + "\n")
while True:
number = input("Pick a number 1 - 100,000: ")
try:
number = int(number)
except ValueError:
print(" ")
print(number, 'is not a number, try again.')
continue
if number > irand:
print("That's too high, try again.")
print(" ")
time.sleep(1)
elif number < irand:
print("That's too low, try again.")
print(" ")
time.sleep(1)
elif number == irand:
print(" ")
print("You got it right! You won!")
print(" ")
time.sleep(2)
main()
break
#Difficulty - Master
def master():
print ("")
print ("Difficulty: Master")
print ("")
irand = randrange(1,1000000)
with open("GTN.txt", "a") as text_file:
text_file.write(str(irand) + " Master" + "\n")
while True:
number = input("Pick a number 1 - 1,000,000: ")
try:
number = int(number)
except ValueError:
print(" ")
print(number, 'is not a number, try again.')
continue
if number > irand:
print("That's too high, try again.")
print(" ")
time.sleep(1)
elif number < irand:
print("That's too low, try again.")
print(" ")
time.sleep(1)
elif number == irand:
print(" ")
print("You got it right! You won!")
print(" ")
time.sleep(2)
main()
break
#This is the MainMenu
def main():
time.sleep(2)
while True:
print ("Please select a difficulty when prompted!")
time.sleep(1)
print ("[1] Easy")
time.sleep(1)
print ("[2] Medium")
time.sleep(1)
print ("[3] Hard")
time.sleep(1)
print ("[4] Ultra")
time.sleep(1)
print ("[5] Master")
time.sleep(1)
print ("[6] Exit")
print ("")
time.sleep(1)
choice = input ("Please Choose: ")
if choice == '1':
time.sleep(2)
print ("")
print ("Loading game...")
time.sleep(2)
easy()
elif choice == '2':
time.sleep(2)
print ("")
print ("Loading game...")
time.sleep(2)
medium()
elif choice == '3':
time.sleep(2)
print ("")
print ("Loading game...")
time.sleep(2)
hard()
elif choice == '4':
time.sleep(2)
print ("")
print ("Loading game...")
time.sleep(2)
ultra()
elif choice == '5':
time.sleep(2)
print ("")
print ("Loading game...")
time.sleep(2)
master()
elif choice == '6':
time.sleep(2)
print ("")
print ("Exiting the game!")
print ("")
print ("3")
time.sleep(0.5)
print ("2")
time.sleep(0.5)
print ("1")
time.sleep(2)
SystemExit
else:
print ("Invalid Option: Please select from those available.")
print("")
time.sleep(1)
print ("Welcome to GTN!")
time.sleep(2)
print ("Developed by: oysterDev")
time.sleep(2)
print ("Version 1.1.0")
print (" ")
main()
Answer: @Benjamin's answer would work. But to answer your question about how to start
enforcing DRY, you could do something like this:
Your whole main game code could go into this function, taking in some key
parameters that define the hardness:
def the_game(difficulty_name, range_start, range_end):
score = 0
print ("")
print ("Difficulty: %s" % difficulty_name)
print ("")
irand = randrange(range_start, range_end)
with open("GTN.txt", "a") as text_file:
text_file.write(str(irand) + " %s" % difficulty_name + "\n")
while True:
number = input("Pick a number 1 - 10: ")
try:
number = int(number)
except ValueError:
print(" ")
print(number, 'is not a number, try again.')
continue
if number > irand:
print("That's too high, try again.")
print(" ")
score += 1
time.sleep(1)
elif number < irand:
print("That's too low, try again.")
print(" ")
score += 1
time.sleep(1)
elif number == irand:
print(" ")
print("You got it right! You won!")
print(" ")
print("You guessed wrong " + str(score) + " times")
time.sleep(2)
main()
break
Then you could define little functions that call the game based on the
hardness level chosen by the user, like so:
#Difficulty - Easy
def easy():
the_game("Easy", 1, 10)
#Difficulty - Medium
def medium():
the_game("Medium", 1, 100)
#Difficulty - Hard
def hard():
the_game("Hard", 1, 1000)
#Difficulty - Ultra
def ultra():
the_game("Ultra", 1, 100000)
#Difficulty - Master
def master():
the_game("Master", 1, 1000000)
And finally, you can define the main function like so:
#This is the MainMenu
def main():
time.sleep(2)
while True:
print ("Please select a difficulty when prompted!")
time.sleep(1)
print ("[1] Easy")
time.sleep(1)
print ("[2] Medium")
time.sleep(1)
print ("[3] Hard")
time.sleep(1)
print ("[4] Ultra")
time.sleep(1)
print ("[5] Master")
time.sleep(1)
print ("[6] Exit")
print ("")
time.sleep(1)
choice = input ("Please Choose: ")
def show_loading_screen():
time.sleep(2)
print ("")
print ("Loading game...")
time.sleep(2)
def show_exit_screen():
time.sleep(2)
print ("")
print ("Exiting the game!")
print ("")
print ("3")
time.sleep(0.5)
print ("2")
time.sleep(0.5)
print ("1")
time.sleep(2)
if choice == '1':
show_loading_screen()
easy()
elif choice == '2':
show_loading_screen()
medium()
elif choice == '3':
show_loading_screen()
hard()
elif choice == '4':
show_loading_screen()
ultra()
elif choice == '5':
show_loading_screen()
master()
elif choice == '6':
show_exit_screen()
SystemExit
else:
print ("Invalid Option: Please select from those available.")
print("")
time.sleep(1)
You will find that we have extracted some repeating screen loading lines of
code into inline functions, that we can reuse.
In the end, you can call this main function IF this Python file is being
executed as a script. This is a good practice. You can do it like so:
if __name__ == "__main__":
print ("Welcome to GTN!")
time.sleep(2)
print ("Developed by: oysterDev")
time.sleep(2)
print ("Version 1.1.0")
print (" ")
main()
Hopefully, this was helpful to understand how to start refactoring for DRY.
|
Why does this class-scope variable not get updated in recursive function?
Question: I'm writing a small class for an LED controller, that runs as a process. The
idea is that some code runs constantly to blink LEDs over an i2c bus.
I'm new to OOP with Python, and I'm also new to Processes in python. I'm using
Multiprocessing with Python 3.4, but with the new print function should also
run in 2.7x.
If you run the code, I add three things to the blinkgroup list, which is shown
locally to have had an effect, however this never gets detected in the
ledblinkloop function, which calls itself so that it keeps running.
I suspect I've fundamentally mis-understood something in Python here.
from multiprocessing import Process, Queue
import time
class LedController(Process):
def __init__(self):
super(LedController, self).__init__()
print("ledcontroller started: ",self.name)
self.blinkgroup = [0x04,0x05]
def run(self):
self.ledblinkloop()
def led_blink_on(self,led):
if(led not in self.blinkgroup):
print("LED not in blink group, adding. New blinkgroup length:",len(self.blinkgroup))
self.blinkgroup.append(led)
def ledblinkloop(self):
print("Length of blinkgroup:",len(self.blinkgroup))
time.sleep(1)
self.ledblinkloop()
class myclass:
def __init__(self):
ledcontroller = LedController()
ledcontroller.start()
while(1):
time.sleep(5)
ledcontroller.led_blink_on(0x08)
ledcontroller.led_blink_on(0x09)
ledcontroller.led_blink_on(0x10)
time.sleep(5)
if __name__ == "__main__":
Code should run as is with Python 3.
Answer: The multiprocessing library works by spawning additional Python processes.
They do not share memory.
I see you did import `Queue` from the multiprocessing library, but proceeded
not to use it. That `Queue` is one of two ways you can communicate between
`Process`es, the other being a `Pipe`.
Probably worthwhile to read through the
[documentation](https://docs.python.org/3.4/library/multiprocessing.html) for
the multiprocessing library before continuing.
|
No way to convert this string to raw format for parsing
Question: I am writing a program to find the latency of the following IP:
'141.101.115.212' (A game server)
To find the latency I use the following commands:
x = subprocess.Popen(["ping.exe", "141.101.115.212"], stdout=subprocess.PIPE)
x = str(x.communicate()[0])
If I print x, I find it contains the following output:
...Minimum = 46ms, Maximum = 54ms, Average = 48ms\r\n'
So I parse the output to obtain `48ms` with the following code:
import subprocess
x = subprocess.Popen(["ping.exe", "141.101.115.212"], stdout=subprocess.PIPE)
x = str(x.communicate()[0])
lhs, rhs = x.split("Average = ")
lhs, rhs = rhs.split("\\")
print(lhs)
But I receive the following error because `rhs` is not a raw string.
Traceback (most recent call last):
File "C:/Users/Michael/PycharmProjects/untitled/expiriment.py", line 6, in <module>
lhs, rhs = rhs.split("\\")
ValueError: too many values to unpack (expected 2)
How do I convert the string `rhs` to a raw string?
**edit:**
As you can see by printing `rhs`, the code works after the first split, but
not the second.
import subprocess
x = subprocess.Popen(["ping.exe", "141.101.115.212"], stdout=subprocess.PIPE)
x = str(x.communicate()[0])
print(x)
lhs, rhs = x.split("Average = ")
print(rhs)
lhs, rhs = rhs.split("\\")
print (lhs)
**edit:**
I do infact need to cast communicate as a string.
**edit:**
The only way to split a string at a back slash with Python is to convert the
string to raw e.g.
string = r"asdasd\asdasd"
lhs, rhs = string.split("\\")
print(rhs)
Answer: You get this error because you try to assign the result to exactly two
variables, but there are more than that.
Your string most certainly contains more than one backslash
You could get all of them with
res = rhs.split("\\")
Then search res for what you need
Edit
By your comments, rhs is `57ms\r\n` before the split. This will cause split to
return 3 values, 57ms, r, n. lhs could get 57ms, rhs will get r, but n is not
handled so python panics and shows that error.
I think that what you really want to do is to remove the line break. This
should sanitize to 57ms
res = rhs.replace('\r\n','')
|
Printing json results in python
Question: I'm using two files for this project. Snapchat.py and test.py
Snapchat.py contains the following (showing the important part):
def add_friend(self, username):
"""Add user as friend
Returns JSON response.
Expected messages:
Success: '{username} is now your friend!'
Pending: '{username} is private. Friend request sent.'
Failure: 'Sorry! Couldn't find {username}'
:param username: Username to add as a friend
"""
r = self._request('friend', {
'action': 'add',
'friend': username,
'username': self.username
})
return r.json()
The file test.py, that I am currently working on has the following code:
#including Snapchat in test.py
from snapchat import Snapchat
s = Snapchat()
username = raw_input('Enter your username: ')
password = raw_input('Enter your password: ')
friend = raw_input('Enter friend name: ')
s.login(username, password)
s.add_friend(friend)
The important part here is:
Returns JSON response.
Expected messages:
Success: '{username} is now your friend!'
Pending: '{username} is private. Friend request sent.'
Failure: 'Sorry! Couldn't find {username}'
I want that response printed at the end of the test.py file in the command
shell.
Though I have no clue on how to do this, I have tried importing it in the
test.py file and printing it, but not working.
Answer: Please note that the Messages you pasted in your question will infact be
returned by the add_friend method, so you don't need to do anything.
Simply print them like;
#First you need to see what is the response for your login call
login_response = s.login(username, password)
print str(login_response)
#if you wish to access some value in this response
value = login_response.get("the_value", {the default value})
if value: #incase you want to make sure you logged in correctly
json_response = s.add_friend(friend)
print str(json_response)
|
Two Xbee in API mode - Python
Question: First, I tested the communication of 2 XBee (series 2) in AT mode and all
worked correctly.
Then I changed the Coordinator to API mode and ran the below script while the
router was in AT mode. I was successful and received the routers message.
However, I can't get the router to be in API mode and send messages to the
coordinator. I'm not sure if i can just do simple send command or if I need to
specify the address or if the fames have to be formatted.
Each xbee is connected to a PC. I'm using python 3.4.
Coordinator in API mode to receive messages:
# Continuously read the serial port and process IO data received from a remote
XBee.
from xbee import XBee,ZigBee
import serial
ser = serial.Serial('/dev/...', 9600)
xbee = ZigBee(ser)
while True:
try:
response = xbee.wait_read_frame()
print(response)
except KeyboardInterrupt:
break
ser.close()
Has someone else done this or know of a site that could help me explain how
the router in API works? All I want to do is to send messages from the router
to the coordinator.
Answer: API mode works the same whether the device is configured as coordinator,
router or end device. If your router is always sending data to the
coordinator, there's no need to run it in API mode -- just keep it in AT mode
with `DH` and `DL` set to `0`. It will automatically send frames to the
coordinator containing all data that comes in on the serial port.
If you need to use API mode on the router for some reason, just use the
[python-xbee](http://code.google.com/p/python-xbee/) library you're already
using on the coordinator.
|
Qt Framework, PyQt5 and AttributeError: 'MyApp' object has no attribute 'myAttribute'
Question: Last week I started to learn Python and I developed some command line apps.
Now I would like to develop apps with GUI. I searched in internet and I found
a project that fits my needs: Qt Project (<http://qt-project.org>) and PyQt
(<http://www.riverbankcomputing.com/software/pyqt/intro>). I installed Qt
5.3.2 Open Source, SIP 4.16.4, PyQt5 5.3.2 on Mac OS X 10.10 and python 2.7.6.
After some troubles on installing Qt and PyQt, finally I managed to make them
work. If I open example projects from PyQt example folder the gui appears
without any problems. So I created my GUI with Qt Creator and then I used
pyuic5 to generate python code. This is what pyuic5 created (file name
"**myapp_auto.py** "):
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/Users/andrea/Developer/Qt/mainwindow.ui'
#
# Created: Mon Nov 17 14:20:14 2014
# by: PyQt5 UI code generator 5.3.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(400, 300)
self.centralWidget = QtWidgets.QWidget(MainWindow)
self.centralWidget.setObjectName("centralWidget")
self.ok = QtWidgets.QPushButton(self.centralWidget)
self.ok.setGeometry(QtCore.QRect(140, 120, 115, 32))
self.ok.setAccessibleName("")
self.ok.setObjectName("ok")
self.text = QtWidgets.QLabel(self.centralWidget)
self.text.setGeometry(QtCore.QRect(100, 70, 181, 16))
self.text.setAccessibleName("")
self.text.setAlignment(QtCore.Qt.AlignCenter)
self.text.setObjectName("text")
self.time = QtWidgets.QDateTimeEdit(self.centralWidget)
self.time.setGeometry(QtCore.QRect(100, 180, 194, 24))
self.time.setAccessibleName("")
self.time.setObjectName("time")
MainWindow.setCentralWidget(self.centralWidget)
self.menuBar = QtWidgets.QMenuBar(MainWindow)
self.menuBar.setGeometry(QtCore.QRect(0, 0, 400, 22))
self.menuBar.setObjectName("menuBar")
self.menuMyApp = QtWidgets.QMenu(self.menuBar)
self.menuMyApp.setObjectName("menuMyApp")
self.menuEdit = QtWidgets.QMenu(self.menuBar)
self.menuEdit.setObjectName("menuEdit")
MainWindow.setMenuBar(self.menuBar)
self.mainToolBar = QtWidgets.QToolBar(MainWindow)
self.mainToolBar.setObjectName("mainToolBar")
MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar)
self.statusBar = QtWidgets.QStatusBar(MainWindow)
self.statusBar.setObjectName("statusBar")
MainWindow.setStatusBar(self.statusBar)
self.menuBar.addAction(self.menuMyApp.menuAction())
self.menuBar.addAction(self.menuEdit.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.ok.setText(_translate("MainWindow", "Ok"))
self.text.setText(_translate("MainWindow", "I\'m a GUI"))
self.menuMyApp.setTitle(_translate("MainWindow", "MyApp"))
self.menuEdit.setTitle(_translate("MainWindow", "Edit"))
After that I added a new python file where I put my code; this is what i wrote
(file name "**myapp.py** "):
#!/usr/bin/env python
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from myapp_auto import Ui_MainWindow
import sys
import time
class MyApp(Ui_MainWindow):
parse_triggered = pyqtSignal()
def __init__(self, parent=None, name=None):
Ui_MainWindow.__init__(self)
if __name__ == "__main__":
app = QApplication(sys.argv)
MainWindow = QMainWindow()
ui = MyApp()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
Then, I run myapp.py and I verified that all GUI elements appeared to be where
they should be. Well...now arrive my issue: I tried to access with code the
"time" element in MainWindow modifying init def thus:
def __init__(self, parent=None, name=None):
Ui_MainWindow.__init__(self)
# Set the date to now
now = QDateTime()
now.setTime_t(int(time.time()))
self.time.setDateTime(now)
But the compiler shows alway this error:
> AttributeError: 'MyApp' object has no attribute 'time'
This happen even if I try to access any other element ("ok", "text"). Will
surely be a stupid mistake but I just can not figure out where I went wrong.
Thank you all guys! Have a good day,
Andrea
Answer: You're not far off.
The `MyApp` class needs to inherit `QMainWindow`, and you don't need to use
the `time` module. Try something like this:
class MyApp(QMainWindow, Ui_MainWindow):
parse_triggered = pyqtSignal()
def __init__(self, parent=None, name=None):
super(MyApp, self).__init__(parent)
self.setupUi(self)
# Set the date to now
self.time.setDateTime(QDateTime.currentDateTime())
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MyApp()
window.show()
sys.exit(app.exec_())
|
How to use multiple templates that inherits from one base template? python, Flask
Question: I have my directory structure as such (from
<https://github.com/alvations/APE>):
APE
\app
\templates
base.html
index.html
instance.html
__init__.py
hamlet.py
config.py
run.py
My `hamlet.py` application, initializes 2 pages with these functions:
from flask import render_template
from app import app
@app.route('/')
@app.route('/index')
@app.route('/instance')
def index():
return render_template('index.html')
def instance():
return render_template('instance.html')
And the `instance.html` and `index.html` are both inheriting from `base.html`
with different block content, the base.html looks as such:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Post Editor Z</title>
</head>
<body>
<div class="container">
{% block content %}{% endblock %}
</div><!-- /.container -->
</body>
</html>
My index.html looks like this:
{% extends "base.html" %}
{% block content %}
<div class="row">
<div class="col-lg-12">
Hello World
</div>
</div>
{% endblock %}
And my instance.html looks like this:
{% extends "base.html" %}
{% block content %}
<div class="row">
<div class="col-lg-12">
Some instance.
</div>
</div>
{% endblock %}
After deploying and going to `http://127.0.0.1:5000/index` and
`http://127.0.0.1:5000/instance`. They were both giving the content of
`index.html`
**Is that because base.html can only be inherited by one other html? In my
case, I have both`instance` and `index` html inheriting from base.html.**
I have tried making a copy of `base.html` and call it `abase.html` and made
`instance.html` inherits from `abase.html` but `instance.html` still outputs
`Hello World` instead of `Some instance.`, i.e. i did this change to
`instance.html`:
{% extends "abase.html" %}
{% block content %}
<div class="row">
<div class="col-lg-12">
Hello World
</div>
</div>
{% endblock %}
**How do I resolve the problem such that instance.html and index.html will
display the two different pages as defined in the templates?**
Is it because I am initializing my pages wrongly in `hamlet.py`?
Answer: I found the fix for the problem but I don't know why it works.
Shifting the `@app.route('/instance')` to before the `instance()` worked:
from flask import render_template
from app import app
@app.route('/')
@app.route('/index')
def index():
return render_template('index.html')
@app.route('/instance')
def instance():
return render_template('instance.html')
|
datetime.strptime extracting from dataframe: error
Question: Strptime doesn't do what I (starting Python data-scientist) want it to do.
I've got a data file formatted as follows:
STN,YYYYMMDD,HH,RH
210,20121001,1,0
210,20121001,2,0
210,20121001,3,0
210,20121001,4,0
...
In the second column the dates, in the third the hour (1-24) of an
observation. I'd like to get the date and time in a datetime format to merge
it with other data. My try:
import pandas as pd
from datetime import datetime
meteo = pd.read_csv("x:\\hourly.txt", parse_dates=[[1,2]])
# dataframe created with a column 'YYYYMMDD_HH'
meteo['datetime']=meteo['YYYYMMDD_HH'].apply(lambda x: datetime.strptime(x,'%Y%m%d %H'))
Python crashes on the last line with a (for me) very cryptic error:
Traceback (most recent call last):
File "X:\test.py", line 11, in <module>
meteo['datetime']=meteo['YYYYMMDD_HH'].apply(lambda x: datetime.strptime(x,'%Y%m%d %H'))
File "C:\Program Files\Anaconda3\lib\site-packages\pandas\core\series.py", line 1998, in apply
mapped = lib.map_infer(values, f, convert=convert_dtype)
File "inference.pyx", line 1016, in pandas.lib.map_infer (pandas\lib.c:53184)
File "X:\test.py", line 11, in <lambda>
meteo['datetime']=meteo['YYYYMMDD_HH'].apply(lambda x: datetime.strptime(x,'%Y%m%d %H'))
File "C:\Program Files\Anaconda3\lib\_strptime.py", line 500, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "C:\Program Files\Anaconda3\lib\_strptime.py", line 340, in _strptime
data_string[found.end():])
ValueError: unconverted data remains: 4
What am I doing wrong? Thanks for your help in advance, Niels
Answer: Parse the columns when you read the CSV file.
import pandas as pd
from datetime import datetime
parse = lambda x: datetime.strptime(x, '%Y%m%d %H')
df = pd.read_csv("time.csv", parse_dates = [['YYYYMMDD', 'HH']], date_parser=parse)
print df
Output:
YYYYMMDD_HH STN RH
0 2012-10-01 01:00:00 210 0
1 2012-10-01 02:00:00 210 0
2 2012-10-01 03:00:00 210 0
3 2012-10-01 04:00:00 210 0
|
Error on ScrollView+StackLayout when binding minimum_height on Kivy
Question: I'm new to Kivy and I am trying to create a scroll view based the official
ScrollView [example](http://kivy.org/docs/api-kivy.uix.scrollview.html) on
Kivy docs.
I'm using the Kivy portable package for Windows with Python version 3.3.3.
When i try to run the code below with the layout.bind line uncommented i got
repeated lines of the following error:
> Warning, too much iteration done before the next frame. Check your code, or
> increase the Clock.max_iteration attribute
When i comment the layout.bind line I get a normal startup with the buttons i
added where i would expect them, but the scroll doesn't work.
from kivy.app import App
from kivy.uix.scrollview import ScrollView
from kivy.uix.stacklayout import StackLayout
from kivy.uix.button import Button
class Example(App):
def build(self):
layout = StackLayout(size_hint_y=None)
# If i uncomment this line, i got the error:
# layout.bind(minimum_height=layout.setter('height'))
for i in range(30):
btn = Button(text=str(i), size_hint=(.33,.8))
layout.add_widget(btn)
root = ScrollView(size_hint=(None,None), size=(400, 400))
root.add_widget(layout)
return root
if __name__ == '__main__':
Example().run()
The question is why the scroll doesn't work? and why the layout.bind is
causing an error.
How should i do to have the same visual and the scroll working on x axis
without the error?
I made this piece of code as close as possible to the Kivy official
[example](http://kivy.org/docs/api-kivy.uix.scrollview.html).
Answer: This is happening because you're creating an infinite loop. The size of each
`Button` is set based on the size of the `StackLayout`. This causes the
`StackLayout` to increase in size, causing the `Button` sizes to be
recalculated, causing the `StackLayout` to increase in size, ad infinitum.
You're telling Kivy that you want the `Button` size based on the `StackLayout`
size, while also wanting the `StackLayout` size based on the combined
`Button`s size.
To fix this, you need to specify a real size instead of using `size_hint`:
btn = Button(text=str(i), size_hint=(None, None), size=(100, 100))
|
Using "Open with" on a text file with a python application
Question: I've been looking for a way to open a text file with a text editor I made with
python, and assumed it had something to do with system arguments, so made a
simple application which would write the arguments sent by the system to a
text window, and used "open with" on the text file and application, but the
only argument was the path of the application. Many questions similar to mine
have been answered on here but none of the answers have worked for me. How
would I do this?
Thanks for any responses. (I'm using OS X 10.9.5, with python 2.7)
Tried code:
from Tkinter import *
import sys, time
root = Tk()
root.geometry('300x200')
text = Text(root)
text.pack(side=TOP, fill="both", expand=True)
text.insert(END, sys.argv)
for x in xrange(len(sys.argv)):
text.insert(END,sys.argv[x])
root.mainloop()
Displayed text:
['/Path/pyfe.app/Contents/Resources/file_opener.py']/Path/pyfe.app/Contents/Resources/file_opener.py
Answer: If I understand your question correctly, you are talking about opening a file
with the Finder's `Open with` context menu when clicking on a file. If so,
it's probably a duplicate of [MacOSX - File extension associate with
application -
Programatically](http://stackoverflow.com/questions/2969987/macosx-file-
extension-associate-with-application-programatically). The standard way is to
create an OS X app bundle (for Python programs, you can use `py2app` to do
that) and then set proper key type in its `Info.plist`. That's assuming your
text editor is a true GUI app (uses Tkinter or Cocoa or whatever) and not just
a program that runs in a shell terminal window (in `Terminal.app` for
example). In that case, you might be able to create a simple wrapper app (even
using AppleScript or Automator and modifying its `Info.plist` as above) to
launch your Python program in a terminal window and pass in the file name from
the open event. To properly handle multiple files opened at different times
would require more work.
UPDATE: as you have clarified, you are using Python Tkinter and a real GUI
app. The native OS X Tk implementation provides an Apple Event handler to
allow you to process Apple Events like `Open Document`. The support is
[described in `tcl` terms in the `Tcl/Tk`
documentation](http://www.tcl.tk/man/tcl8.6/TkCmd/tk_mac.htm#M11) so you need
to translate it to Python but it's very straightforward. Python's IDLE app has
an example of one, see, for instance, [`addOpenEventSupport` in
`macosxSupport.py`](https://hg.python.org/cpython/file/cf5b910ac4c8/Lib/idlelib/macosxSupport.py#l89).
For simple apps using py2app, you could instead use py2app's `argv` emulation.
|
Python statsmodels return values missing
Question: I am trying to use Robust Linear Models from statsmodels on a simple test set
of x-y data. However, as return values with model.params I only get one single
value. How can I get slope and intercept of the fit? Minimal example (in which
I'm trying to exclude the outliers from the fit, hence rlm):
import statsmodels.api as sm
a = np.array([1,2,3,4,5,6,7,8,9])
b = 2. * np.array([1,2,9,4,5,6,7,13,9])
model = sm.RLM(b, a, M=sm.robust.norms.HuberT()).fit()
model.params
The last line only returns `array([2.])`. I tried the same thing with ols from
the same package, which does give me intercept and slope in return.
Answer: statsmodels is not automatically adding a constant or intercept if you use
arrays. There is a helper function add_constant to add a constant.
>>> import statsmodels.api as sm
>>> a = np.array([1,2,3,4,5,6,7,8,9])
>>> b = 2. * np.array([1,2,9,4,5,6,7,13,9])
>>> model = sm.RLM(b, a, M=sm.robust.norms.HuberT()).fit()
>>> model.params
array([ 2.])
with a constant
>>> a2 = sm.add_constant(a)
>>> model = sm.RLM(b, a2, M=sm.robust.norms.HuberT()).fit()
>>> model.params
array([ 2.85893087e-10, 2.00000000e+00])
>>> print model.summary()
...
This is the same for all models except for some time series models which have
an option to add a constant or trend.
In the formula interface a constant is added by default.
|
Python Matplotlib line plot aligned with contour/imshow
Question: How can I set the visual width of one subplot equal to the width of another
subplot using Python and Matplotlib? The first plot has a fixed aspect ratio
and square pixels from imshow. I'd then like to put a lineplot below that, but
am not able to do so and have everything aligned.
I'm fairly sure the solution involves the information on this [Transform
Tutorial](http://matplotlib.org/users/transforms_tutorial.html) page. I've
tried working with fig.transFigure, ax.transAxes, ax.transData, etc. but have
not been successful. I need to find the width and height and offsets of the
axes in the upper panel, and then be able to set the width, height, and
offsets of the axes in the lower panel. Axis labels and ticks and etc. should
not be included or change the alignment.
For example, the following code
fig = plt.figure(1)
fig.clf()
data = np.random.random((3,3))
xaxis = np.arange(0,3)
yaxis = np.arange(0,3)
ax = fig.add_subplot(211)
ax.imshow(data, interpolation='none')
c = ax.contour(xaxis, yaxis, data, colors='k')
ax2 = fig.add_subplot(212)

Answer: The outline of matplotlib axes are controlled by three things:
1. The axes' bounding box within the figure (controlled by a subplot specification or a specific extent such as `fig.add_axes([left, bottom, width, height])`. The axes limits (not counting tick labels) will always be within this box.
2. The `adjustable` parameter that controls whether changes in limits or aspect ratio are accomodated by changing data limits or the shape of the axes "box". This can be `"datalim"`, `"box"`, or `"box-forced"`. (The latter is for use with shared axes.)
3. The axes limits and aspect ratio. For plots with a fixed aspect ratio, the axes box or data limits (depending on `adjustable`) will be changed to maintain the specified aspect ratio. The aspect ratio refers to data coordinates, _not_ the shape of the axes directly.
For the simplest case:
import numpy as np
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=2)
data = np.random.random((3,3))
xaxis = np.arange(0,3)
yaxis = np.arange(0,3)
axes[0].imshow(data, interpolation='none')
c = axes[0].contour(xaxis, yaxis, data, colors='k')
axes[1].set_aspect(1)
plt.show()

* * *
## Shared Axes
However, if you want to ensure that it stays the same shape regardless, and
you're okay with both plots having the same data limits, you can do:
import numpy as np
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=2), sharex=True, sharey=True)
plt.setp(axes.flat, adjustable='box-forced')
data = np.random.random((5,3))
xaxis = np.arange(0,3)
yaxis = np.arange(0,5)
axes[0].imshow(data, interpolation='none')
c = axes[0].contour(xaxis, yaxis, data, colors='k')
axes[1].plot([-0.5, 2.5], [-0.5, 4.5])
axes[1].set_aspect(1)
plt.show()

However, you may notice that this doesn't look quite right. That's because the
second subplot is controlling the extents of the first subplot due to the
order we plotted things in.
Basically, with shared axes, whatever we plot last will control the initial
extent, so if we just swap the order we're plotting in:
import numpy as np
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=2, sharex=True, sharey=True)
plt.setp(axes.flat, adjustable='box-forced')
data = np.random.random((5,3))
xaxis = np.arange(0,3)
yaxis = np.arange(0,5)
axes[1].plot([-0.5, 2.5], [-0.5, 4.5])
axes[1].set_aspect(1)
axes[0].imshow(data, interpolation='none')
c = axes[0].contour(xaxis, yaxis, data, colors='k')
plt.show()

Of course, if you don't care about the interactive zooming/panning of the
plots being linked, you can skip the shared axes altogether and just to:
import numpy as np
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=2)
data = np.random.random((5,3))
xaxis = np.arange(0,3)
yaxis = np.arange(0,5)
axes[0].imshow(data, interpolation='none')
c = axes[0].contour(xaxis, yaxis, data, colors='k')
axes[1].plot([-0.5, 2.5], [-0.5, 4.5])
# Copy extents and aspect from the first axes...
axes[1].set_aspect(axes[0].get_aspect())
axes[1].axis(axes[0].axis())
plt.show()
* * *
## Non-Shared Axes
If you don't want the two axes to have the same data extents, it is possible
to force them to be the same size (though if you interactively zoom, they
won't be linked). To do this, you need to calculate what the aspect ratio for
the second plot should be based on its extents and the extents/aspect of the
first plot.
import numpy as np
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=2)
data = np.random.random((3,3))
xaxis = np.arange(0,3)
yaxis = np.arange(0,3)
axes[0].imshow(data, interpolation='none')
c = axes[0].contour(xaxis, yaxis, data, colors='k')
axes[1].plot(np.linspace(0, 10, 100), np.random.normal(0, 1, 100).cumsum())
# Calculate the proper aspect for the second axes
aspect0 = axes[0].get_aspect()
if aspect0 == 'equal':
aspect0 = 1.0
dy = np.abs(np.diff(axes[1].get_ylim()))
dx = np.abs(np.diff(axes[1].get_xlim()))
aspect = aspect0 / (float(dy) / dx)
axes[1].set_aspect(aspect)
plt.show()

|
Argparse - do not catch positional arguments with `nargs`.
Question: I am trying to write a function wo which you can parse a variable amount of
arguments via argparse - I know I can do this via `nargs="+"`. Sadly, the way
argparse help works (and the way people generally write arguments in the CLI)
puts the positional arguments last. This leads to my positional argument being
caught as part of the optional arguments.
#!/usr/bin/python
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("positional", help="my positional arg", type=int)
parser.add_argument("-o", "--optional", help="my optional arg", nargs='+', type=float)
args = parser.parse_args()
print args.positional, args.optional
running this as `./test.py -h` shows the following usage instruction:
usage: test.py [-h] [-o OPTIONAL [OPTIONAL ...]] positional
but if I run `./test.py -o 0.21 0.11 0.33 0.13 100` gives me
test.py: error: too few arguments
to get a correct parsing of args, I have to run `./test.py 100 -o 0.21 0.11
0.33 0.13`
So how do I:
* make argparse reformat the usage output so that it is less misleading, OR, even better:
* tell argparse to not catch the last element for the optional argument `-o` if it is the last in the list
?
Answer: There is a bug report on this: <http://bugs.python.org/issue9338>
> argparse optionals with nargs='?', '*' or '+' can't be followed by
> positionals
A simple (user) fix is to use `--` to separate postionals from optionals:
./test.py -o 0.21 0.11 0.33 0.13 -- 100
I wrote a patch that reserves some of the arguments for use by the positional.
But it isn't a trivial one.
As for changing the usage line - the simplest thing is to write your own,
e.g.:
usage: test.py [-h] positional [-o OPTIONAL [OPTIONAL ...]]
usage: test.py [-h] [-o OPTIONAL [OPTIONAL ...]] -- positional
I wouldn't recommend adding logic to the usage formatter to make this sort of
change. I think it would get too complex.
Another quick fix is to turn this positional into an (required) optional. It
gives the user complete freedom regarding their order, and might reduce
confusion. If you don't want to confusion of a 'required optional' just give
it a logical default.
usage: test.py [-h] [-o OPTIONAL [OPTIONAL ...]] -p POSITIONAL
usage: test.py [-h] [-o OPTIONAL [OPTIONAL ...]] [-p POS_WITH_DEFAULT]
* * *
One easy change to the Help_Formatter is to simply list the arguments in the
order that they are defined. The normal way of modifying formatter behavior is
to subclass it, and change one or two methods. Most of these methods are
'private' (_ prefix), so you do so with the realization that future code might
change (slowly).
In this method, `actions` is the list of arguments, in the order in which they
were defined. The default behavior is to split 'optionals' from 'positionals',
and reassemble the list with positionals at the end. There's additional code
that handles long lines that need wrapping. Normally it puts positionals on a
separate line. I've omitted that.
class Formatter(argparse.HelpFormatter):
# use defined argument order to display usage
def _format_usage(self, usage, actions, groups, prefix):
if prefix is None:
prefix = 'usage: '
# if usage is specified, use that
if usage is not None:
usage = usage % dict(prog=self._prog)
# if no optionals or positionals are available, usage is just prog
elif usage is None and not actions:
usage = '%(prog)s' % dict(prog=self._prog)
elif usage is None:
prog = '%(prog)s' % dict(prog=self._prog)
# build full usage string
action_usage = self._format_actions_usage(actions, groups) # NEW
usage = ' '.join([s for s in [prog, action_usage] if s])
# omit the long line wrapping code
# prefix with 'usage:'
return '%s%s\n\n' % (prefix, usage)
parser = argparse.ArgumentParser(formatter_class=Formatter)
Which produces a usage line like:
usage: stack26985650.py [-h] positional [-o OPTIONAL [OPTIONAL ...]]
|
Multiple updating plot with pyqtgraph in Python
Question: I have to plot 3 updating curves of data I read from a sensor. The updating
plot is very fast when I use just a curve but when I try to plot them all each
of them is drastically slower. The code I use is following:
#!/usr/bin/python
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
import time
import numpy as np
app = QtGui.QApplication([])
win = pg.GraphicsWindow()
p1 = win.addPlot()
p2 = win.addPlot()
p3 = win.addPlot()
curve1 = p1.plot()
curve2 = p2.plot()
curve3 = p3.plot()
readData = [0.0, 0.0, 0.0]
y1=[0.0]
y2=[0.0]
y3=[0.0]
temp = [0.0]
start = time.time()
def update():
global curve1, curve2, curve3
t = time.time()-start # measure of time as x-coordinate
readData= readfun() #function that reads data from the sensor it returns a list of 3 elements as the y-coordinates for the updating plots
y1.append(readData[0])
y2.append(readData[1])
y3.append(readData[2])
temp.append(t)
curve1.setData(temp,y1)
curve2.setData(temp,y2)
curve3.setData(temp,y3)
app.processEvents()
timer = QtCore.QTimer()
timer.timeout.connect(update)
timer.start(0)
if __name__ == '__main__':
import sys
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_'):
QtGui.QApplication.instance().exec_()
How can I speed up the updating plotting for the three curves ? Thanks
**EDIT:** Inspired by dirkjot's solution I want edit my above code in the case
someone will need it for the same purpose. It works fine:
#!/usr/bin/python
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
import time
import numpy as np
app = QtGui.QApplication([])
win = pg.GraphicsWindow()
p1 = win.addPlot()
p2 = win.addPlot()
p3 = win.addPlot()
curve1 = p1.plot()
curve2 = p2.plot()
curve3 = p3.plot()
readData = [0.0, 0.0, 0.0]
y1=np.zeros(1000,dtype=float)
y2=np.zeros(1000,dtype=float)
y3=np.zeros(1000,dtype=float)
indx = 0
def update():
global curve1, curve2, curve3, indx, y1,y2,y3
readData= readfun() #function that reads data from the sensor it returns a list of 3 elements as the y-coordinates for the updating plots
y1[indx]=readData[0]
y2[indx]=readData[1]
y3[indx]=readData[2]
if indx==99:
y1=np.zeros(1000,dtype=float)
y2=np.zeros(1000,dtype=float)
y3=np.zeros(1000,dtype=float)
else:
indx+=1
curve1.setData(y1)
curve2.setData(y2)
curve3.setData(y3)
app.processEvents()
timer = QtCore.QTimer()
timer.timeout.connect(update)
timer.start(0)
if __name__ == '__main__':
import sys
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_'):
QtGui.QApplication.instance().exec_()
Answer: One problem is that you are appending to lists. This gets to be very slow when
the lists grow large, as Python has to copy the full list to a new location
that is one cell larger than the previous one. You could test this by running
your code again with the appends removed, but continuing to read the data
(which you throw away for that test).
If that is the problem, there are several solutions:
1. preallocate a big list (say `[None] * 1000`) and keep a counter where you are writing. Wrap around when you reach 1k. This way, you get a continuous updating display like you see that on an old fashioned scope.
2. Use numpy and preallocate a fixed buffer of say 1k samples. Add samples to the end (position -10 to -1). When you reach -1, move the buffer content 10 to the left in an efficient numpy data statement (something like `buffer[0:-10] = buffer[10:]`, but there may be a dedicated numpy shift instruction) and start writing at -10 again.
|
Unspecified Python error
Question: Here is the pet class program. If I understand it correctly the class petinfo
program is supposed to be separate from the other code. Is that correct?
The display list function accepts a list containing pets as an argument and
displays the data stored in each object.
class petinfo(object):
# The __ init__ method inititalizes the attributes.
def __init__(self, name, animal_type, age):
self.__name = name
self.__animal_type = animal_type
self.__age = age
# The set_name method accepts an argument for the pet's name.
def set_name(self, name):
self.__name = name
# The set_type method accepts an argument for the pet's type.
def set_type(self, animal_type):
self.__animal_type = animal_type
# The set_age method accepts an argument for the pets's age.
def set_age(self, age):
self.__age = age
# The get_name function returns the pet's name.
def get_name(self):
return self.__name
# The get animat_type returns the pet's type.
def get_animal_type(self):
return self.__animal_type
# The get_age function returns the pet's age.
def get_age(self):
return self.__age
I keep getting this error:
`Traceback (most recent call last): File "C:\Program Files\Wing IDE 101
5.0\src\debug\tserver_sandbox.py", line 59, in <module> File "C:\Program
Files\Wing IDE 101 5.0\src\debug\tserver_sandbox.py", line 16, in main File
"C:\Program Files\Wing IDE 101 5.0\src\debug\tserver_sandbox.py", line 40, in
make_list builtins.AttributeError: 'module' object has no attribute 'Petinfo'`
Here is my code.
import petinfo
def main():
# Get a list of pets.
pets = make_list()
# Display the data in the list.
print('Here are the pets you entered: ')
display_list(pets)
# The make list function gets data from the user for 3 pets. The function returns
# a list of pets containing the data.
def make_list():
#Create an empty list.
pet_list = []
# Add 3 pets to the list.
print('Please enter the data for your pets by answering the following questions')
for count in range(1,4):
#Get the pet data.
name = (input('What is your pets name? '))
age = float(input('How old is your pet? '))
animal_type = (input('What type of animal is it? '))
print()
#Create a new pet in memory and assign it to the pet variable.
pet = petinfo.Petinfo(name, age, animal_type)
# Add the pet to the list
pet_list.append(pet)
# return the list
return pet_list
# The display list function accepts a list containing pets as an arugment and
# displays the data stored in each object.
def display_list(pet_list):
for item in pet_list:
print(item.get_name())
print(item.get_animal_type())
print(item.get_age())
print()
# Return the main function.
main()
Can anyone tell me what is wrong with this?
Answer: Your error message is telling you that you tried to import `Petinfo` but
Python couldn't find anything by that name.
In the beginning of your posted code you have `import petinfo` but the error
code shows you had `import Petinfo` when you got that error. The code you
posted will not produce that error message, this is a type-o error.
|
exceptions.AttributeError: class KeyAgent has no attribute 'delele_customer_node()'
Question: I've 2 files: customer.py & agent.py. It looks like this:
customer.py:
from agent import KeyAgent
class CustomerController(object):
def __init__(self, container):
self.key = container.agent
def delete(self, path):
KeyAgent.delele_customer_node()
agent.py:
class KeyAgent(service.Service):
def __init__(self):
pass
def delele_customer_node():
....
Python is throwing this exception while running:
exceptions.AttributeError: class KeyAgent has no attribute 'delele_customer_node()'
Even though I've imported KeyAgent class from agent.py why method
`delele_customer_node()` is not accessible from delete() of customer.py?
Answer: You must have misspelled the method name (dele**l** e? or dele**t** e?). The
KeyAgent class **does** have a method `delete_customer_node` (I will assume
that was a typo).
>>> class KeyAgent(object):
... def delete_customer():
... pass
...
>>> KeyAgent.delete_customer
<unbound method KeyAgent.delete_customer>
That means, the method is there. However your code is quite broken. Unless you
use the `staticmethod` or `classmethod` decorators, the first argument of a
method "must be" `self`, and you need to instantiate the class to call it. See
what happens if you try to call this method directly:
>>> KeyAgent.delete_customer()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method delete_customer() must be called with KeyAgent instance as first argument (got nothing instead)
|
Python: NullPointerException for os.system() and os.popen()
Question: I am getting a `NullPointerException` for `os.system()` and `os.popen()` on
python 2.2.1. The weird thing is that i have two servers and this same code
works fine on one but not on the other. What could be missing in the second
server?
Below is the code snippet
import sys
import os
print (sys.version) #This line works on both servers and gives 2.2.1 os output
os.system('pwd')
os.popen('hostname -f').read().rstrip('\n')
I get the following error in the second server:
*File "/u01/oracle/mwhome/wlserver_10.3/common/wlst/modules/jython-modules.jar/Lib/javaos$py.class", line 333, in system
File "/u01/oracle/mwhome/wlserver_10.3/common/wlst/modules/jython-modules.jar/Lib/popen2.py", line 31, in ?
File "/u01/oracle/mwhome/wlserver_10.3/common/wlst/modules/jython-modules.jar/Lib/javashell.py", line 17, in ?
File "/u01/oracle/mwhome/wlserver_10.3/common/wlst/modules/jython-modules.jar/Lib/string$py.class", line 434, in ?
at java.io.File.<init>(File.java:222)
at java.lang.Package$1.run(Package.java:527)
at java.lang.Package.defineSystemPackage(Package.java:520)
at java.lang.Package.getSystemPackages(Package.java:511)
at java.lang.ClassLoader.getPackages(ClassLoader.java:1513)
at java.lang.ClassLoader.getPackages(ClassLoader.java:1511)
at java.lang.Package.getPackages(Package.java:281)
at org.python.core.JavaImportHelper.buildLoadedPackages(Unknown Source)
at org.python.core.JavaImportHelper.tryAddPackage(Unknown Source)
at org.python.core.imp.import_next(Unknown Source)
at org.python.core.imp.import_name(Unknown Source)
at org.python.core.imp.importName(Unknown Source)
at org.python.core.ImportFunction.load(Unknown Source)
at org.python.core.ImportFunction.__call__(Unknown Source)
at org.python.core.PyObject.__call__(Unknown Source)
at org.python.core.__builtin__.__import__(Unknown Source)
at org.python.core.imp.importFromAs(Unknown Source)
at org.python.core.imp.importFrom(Unknown Source)
at string$py.f$0(C:\wlst\jython_2.2.1\Lib\string.py:434)
at string$py.call_function(C:\wlst\jython_2.2.1\Lib\string.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyCode.call(Unknown Source)
at org.python.core.imp.createFromCode(Unknown Source)
at org.python.core.imp.createFromPyClass(Unknown Source)
at org.python.core.ZipFileImporter$ZipFileLoader.load_module(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
java.lang.NullPointerException: java.lang.NullPointerException*
Answer: I could be wrong here but I noticed that there is 'C:\' in the stacktrace. If
this is running on a windows system 'pwd' and 'hostname' likely wont work if
os.system / popen are executing exactly what you put in the argument which is
likely why you are getting the error.
I am not a windows guru by any means but I dont think those commands exist
outside of *nix based OS's.
|
PyQt5 && QML exporting enum
Question: Is it possible to export `enum` from `Python` to `QML` instance?
class UpdateState():
Nothing = 0
CheckingUpdate = 1
NoGameFound = 2
Updating = 3
How I want to use it in `qml`:
import PythonController 1.0
PythonController {
id: controller
}
Item {
visible: controller.UpdateState.Nothing ? true : false
}
Answer: It works fine, as long as the enum is registered with `Q_ENUMS` and defined
inside a class registered with the QML engine. Here's a small example:
**example.py**
from sys import exit, argv
from PyQt5.QtCore import pyqtSignal, pyqtProperty, Q_ENUMS, QObject
from PyQt5.QtQml import QQmlApplicationEngine, qmlRegisterType
from PyQt5.QtGui import QGuiApplication
class Switch(QObject):
class State:
On = 0
Off = 1
Q_ENUMS(State)
stateChanged = pyqtSignal(State, arguments=['state'])
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._state = Switch.State.Off
@pyqtProperty(State, notify=stateChanged)
def state(self):
return self._state
@state.setter
def state(self, state):
if state != self._state:
self._state = state
self.stateChanged.emit(self._state)
app = None
def main():
global app
app = QGuiApplication(argv)
qmlRegisterType(Switch, 'Switch', 1, 0, 'Switch')
engine = QQmlApplicationEngine()
engine.load('example.qml')
exit(app.exec_())
if __name__ == '__main__':
main()
**example.qml**
import QtQuick 2.0
import QtQuick.Window 2.0
import Switch 1.0
Window {
title: 'QML Enum Example'
visible: true
width: 400
height: 400
color: colorSwitch.state === Switch.On ? "green" : "red"
Switch {
id: colorSwitch
state: Switch.Off
}
Text {
text: "Press window to switch state"
}
MouseArea {
anchors.fill: parent
onClicked: {
if (colorSwitch.state === Switch.Off)
colorSwitch.state = Switch.On
else
colorSwitch.state = Switch.Off
}
}
}
Hope that helps.
|
How to use python-twisted-web2 in Ubuntu 14.04?
Question: I am new to python twisted and I just start trying to use python twisted. My
purpose is to build a simple **reverse proxy** that supports **HTTP/1.1** ,
which requires module **web2**. But I find that `import twisted.web2` does not
work...
I tried `python -c "import twisted.web2"`
Here is what I get:
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named web2
I am using python2.7 and I did see those web2 related files located in
`/usr/lib/python2.7/dist-packages/twisted/web2`
And I also tried re-install `twisted` and `python-twisted-web2`, but it does
not help. Any ideas?
Answer: Twisted Web2 never progressed beyond the experimental stage. Development of
the project was abandoned many years ago. The source was removed from the
upstream Twisted repository many years ago.
You do not want to use Twisted Web2. Twisted Web includes client and server
implementations of the HTTP/1.1 protocol. You want to use Twisted Web.
|
Multiple python installations - setting path variable
Question: I have several python installations on my system, in /usr/lib/ I have
python2.7, python 3, python3.2. I am trying to upgrade my version of scipy
from .9. When I do a
sudo pip install --upgrade scipy
It doesn't work saying that it's already done in
/usr/local/lib/python3.2/dist-packages
When I import it in ipython, however, it finds the old version of Scipy:
/usr/lib/python2.7/dist-packages/scipy/__init__.pyc
How do I tell python to load the 3.2 version of scipy and not the 2.7? I
believe this has something to do with the PYTHONPATH variable, but I'm not
sure which one to change.
James
Answer: > How do I tell python to load the 3.2 version of scipy and not the 2.7
Every python version manages its own set of installed modules. The idea is to
invoke the `pip` executable that belongs to the right python version.
From what you described it seems that you have installed the ipython module in
your `python2.7` interpreter, but your pip executable belongs to the
`python3.2` interpreter.
The easiest way to execute `python2.7`'s `pip` is:
sudo ipython -m pip install --upgrade scipy
However this installs scipy as root into your system files and thus usually
interferes with versions installed by package managers.
An arguably better way is to install packages in your user's home directory.
ipython -m pip install --upgrade scipy --user
As pointed out in the comments, probably the best way is to get familiar with
`virtualenv`.
I myself find `anaconda` particularly appealing, since it comes with a clean
way of installing and managing multiple python interpreters with a focus on
scientific packages across many platforms.
|
python: gettng multiple results for getElementsByTagName
Question: I'm trying to get each instance of an XML tag but I can only seem to return
one or none.
#!/usr/software/bin/python
# import libraries
import urllib
from xml.dom.minidom import parseString
# variables
startdate = "2014-01-01"
enddate = "2014-05-01"
rest_client = "test"
rest_host = "restprd.test.com"
rest_port = "80"
rest_base_url = "asup-rest-interface/ASUP_DATA"
rest_date = "/start_date/%s/end_date/%s/limit/5000" % (startdate,enddate)
rest_api = "http://" + rest_host + ":" + rest_port + "/" + rest_base_url + "/" + "client_id" + "/" + rest_client
response = urllib.urlopen(rest_api + rest_date + '/sys_serial_no/700000667725')
data = response.read()
response.close()
dom = parseString(data)
xmlVer = dom.getElementsByTagName('sys_version').toxml()
xmlDate = dom.getElementsByTagName('asup_gen_date').toxml()
xmlVerTag=xmlVer.replace('<sys_version>','').replace('</sys_version>','')
xmlDateTag=xmlDate.replace('<asup_gen_date>','').replace('</asup_gen_date>','').replace('T',' ')[0:-6]
print xmlDateTag , xmlVerTag
The above code generates the following error:
Traceback (most recent call last):
File "./test.py", line 23, in <module>
xmlVer = dom.getElementsByTagName('sys_version').toxml()
AttributeError: 'NodeList' object has no attribute 'toxml'
If I change the `.toxml()` to `[0].toxml()` I can get the first element, but I
need to get all the elements. Any ideas?
Also, if I try something like this I get no output at all:
response = urllib.urlopen(rest_api + rest_date + '/sys_serial_no/700000667725')
DOMTree = xml.dom.minidom.parse(response)
collection = DOMTree.documentElement
if collection.hasAttribute("results"):
print collection.getAttribute("sys_version")
* * *
The original data looks like this.
There are repeating sections of XML like this:
<xml><status request_id="58f39198-2c76-4e87-8e00-f7dd7e69519f1416354337206" response_time="00:00:00:833"></status><results start="1" limit="1000" total_results_count="1" results_count="1"><br/><system><tests start="1" limit="50" total_results_count="18" results_count="18"><test> <biz_key>C|BF02F1A3-3C4E-11DC-8AAE-0015171BBD90|8594169899|700000667725</biz_key><test_id>2014071922090465</test_id><test_subject>HA Group Notification (WEEKLY_LOG) INFO</test_subject><test_type>DOT-REGULAR</test_type><asup_gen_date>2014-07-20T00:21:40-04:00</asup_gen_date><test_received_date>Sat Jul 19 22:09:19 PDT 2014</test_received_date><test_gen_zone>EDT</test_gen_zone><test_is_minimal>false</test_is_minimal><sys_version>9.2.2X22</sys_version><sys_operating_mode>Cluster-Mode</sys_operating_mode><hostname>rerfdsgt</hostname><sys_domain>test.com</sys_domain><cluster_name>bbrtp</cluster_name> ... etc
<xml>
<results>
<system>
-<sys_version>
<asup>
-<asup_gen_date>
I simply want to extract the sys_version and asup_gen_date
9.2.2X22 2014-07-20 00:21:40
9.2.2X21 2014-06-31 12:51:40
8.5.2X1 2014-07-20 04:33:22
Answer: You need to loop over the results of `getElementsByTagName()`:
for version in dom.getElementsByTagName('sys_version'):
version = version.toxml()
version = version.replace('<sys_version>','').replace('</sys_version>','')
print version
Also, instead of replacing opening and closing tags, you probably want yo use
[`getText()`](https://docs.python.org/2/library/xml.dom.minidom.html#dom-
example):
def getText(nodelist):
rc = []
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
rc.append(node.data)
return ''.join(rc)
for version in dom.getElementsByTagName('sys_version'):
print getText(version.childNodes)
* * *
Another point is that it would be much more easy and pleasant to parse `xml`
with
[`xml.etree.ElementTree`](https://docs.python.org/2/library/xml.etree.elementtree.html),
example:
import xml.etree.ElementTree as ET
tree = ET.parse(response)
root = tree.getroot()
for version in root.findall('sys_version'):
print version.text
|
python 3: Adding .csv column sums in to dictionaries with header keys
Question: I have a .csv file laid out like this:
name1 name2 name3
value1 value2 value3
value4 value5 value6
value7 value8 value9
I need to find a way in Python3 to create a dictionary where the keys are the
head names (name1, name2, name3) and the values are the sum of all the values
underneath eg. name1 : (value1 + value4 + value7).
So far I've come up with:
def sumColumns(columnfile):
import csv
with open(columnfile) as csvfile:
rdr = csv.reader(csvfile)
output = {}
head = next(rdr)
total = 0
for column in head:
for row in rdr:
total += int(row[head.index(column)])
output[column] = total
total = 0
return output
I end up returning a dictionary with correct headers but something is going
wrong with the sum that I can't pinpoint. One column gets summed and the rest
are 0.
Answer: Definitely not my prettiest piece of code. But here it is. Basically, just
store all the information in a list of lists, then iterate over it from there.
def sumColumns1(columnfile):
import csv
with open(columnfile) as csvfile:
r = csv.reader(csvfile)
names = next(r)
Int = lambda x: 0 if x=='' else int(x)
sums = reduce(lambda x,y: [ Int(a)+Int(b) for a,b in zip(x,y) ], r)
return dict(zip(names,sums))
In an expanded form (or one that doesn't have `reduce` \- before someone
complains):
def sumColumns1(columnfile):
import csv
with open(columnfile) as csvfile:
r = csv.reader(csvfile)
names = next(r)
sums = [ 0 for _ in names ]
for line in r:
for i in range(len(sums)):
sums[i] += int(0 if line[i]=='' else line[i])
return dict(zip(names,sums))
Gives me the correct output. Hopefully someone comes up with something more
pythonic.
|
python module and command line program
Question: I have a code which I'd like people to be able to use as a stand alone python
program, or to import as a module for their own codes. Is there a way to
package a module which can also include a program that can be run from the
command line?
I.e. from the command-line:
> ZHermesCode
or within ipython or a python script:
import ZHermesCode
Answer: Look up [Setuptools automatic script
creation](https://pythonhosted.org/setuptools/setuptools.html#automatic-
script-creation). For example, [`python-scss`](https://github.com/klen/python-
scss) uses this technique to make `scss` an executable shell command.
In [`setup.py`](https://github.com/klen/python-scss/blob/master/setup.py):
setup(
# ...
entry_points={
'console_scripts': [
'scss = scss.tool:main',
]
},
)
Then defining a function `main` in
[`scss/tool.py`](https://github.com/klen/python-
scss/blob/master/scss/tool.py). It also uses the technique mentioned by Loocid
to make the `tool.py` file itself directly executable (as opposed to the
wrapper script that is publicly installed by setuptools according to the
recipe above):
if __name__ == '__main__':
main()
|
Python program not looping/restarting
Question: I have a school assessment which is to make a child's spelling game, it has to
loop/restart when the player clicks yes. So far when I test the game, the
option/the easygui.buttonbox that asks the player if they want to play again
and the yes/no options to play again or exit the game dose not appear. The
program just closes after the player final score is displayed.
Here is my coding for the game, I can't find what I've done wrong and i had
tried 3 suggestions to fix the coding and none of them have worked.
import easygui
#Childs Litercay Game
#Charlotte Lowe 03/09/2015
#Declare Constants and Variables
Score = 0
PlayerAnswer = 0
playOn = 0
while playOn != "Yes":
playOn = easygui.buttonbox ("Hey there, are you ready to test your spelling?", choices = ["Yes"])
if "Yes":
PlayerName = easygui.enterbox ("Before we begin, what's your name?")
easygui.msgbox ("Hi " + PlayerName +"! Here are the rules of the game.")
easygui.msgbox ("There will be 3 words you can choose from, 2 will be incorrect and 1 will be right.")
easygui.msgbox ("All you have to do is select the correctly spelt word.")
easygui.msgbox ("For every right word you pick you will earn a point! There are 10 questions in this quiz")
easygui.msgbox ("Let's begin!")
PlayerAnswer = easygui.buttonbox ("Which word is spelt correctly?", choices = ["Awesome","Awsome","Awesom"])
if PlayerAnswer == "Awesome":
Score += 1
easygui.msgbox ("You're right! Your score is " + str(Score))
elif PlayerAnswer == "Awsome":
Score += 0
easygui.msgbox ("Sorry Incorrect! Your score is " + str(Score))
elif PlayerAnswer == "Awesom":
Score += 0
easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
print(Score) #To check if programme is calculating score properly
PlayerAnswer = easygui.buttonbox ("Which word is spelt correctly?", choices =["Becuse","Becus","Because"])
if PlayerAnswer == "Becuse":
Score += 0
easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
elif PlayerAnswer == "Becus":
Score += 0
easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
elif PlayerAnswer == "Because":
Score += 1
easygui.msgbox ("Correct! Your score is now " + str(Score))
print(Score) #To check if programme is calculating score properly
PlayerAnswer = easygui.buttonbox ("Which word is spelt correctly?", choices =["Morning","Moring","Morening"])
if PlayerAnswer == "Morning":
Score += 1
easygui.msgbox ("Well done! Your score is now " + str(Score))
elif PlayerAnswer == "Moring":
Score += 0
easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
elif PlayerAnswer == "Morening":
Score += 0
easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
print(Score) #To check if programme is calculating score properly
PlayerAnswer = easygui.buttonbox ("Which word is spelt correctly?", choices =["Beleave","Believe","Belive"])
if PlayerAnswer == "Believe":
Score += 1
easygui.msgbox ("Well done! Your score is now " + str(Score))
elif PlayerAnswer == "Beleave":
Score += 0
easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
elif PlayerAnswer == "Belive":
Score += 0
easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
print(Score) #To check if programme is calculating score properly
PlayerAnswer = easygui.buttonbox ("Which word is spelt correctly?", choices =["Jewelry","Jewlery","Jewley"])
if PlayerAnswer == "Jewelry":
Score += 1
easygui.msgbox ("Well done! Your score is now " + str(Score))
elif PlayerAnswer == "Jewlery":
Score += 0
easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
elif PlayerAnswer == "Jewley":
Score += 0
easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
print(Score) #To check if programme is calculating score properly
PlayerAnswer = easygui.buttonbox ("Which word is spelt correctly?", choices =["Mispelled","Misspelled","Misspeled",])
if PlayerAnswer == "Misspelled":
Score += 1
easygui.msgbox ("Well done! Your score is now " + str(Score))
elif PlayerAnswer == "Mispelled":
Score += 0
easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
elif PlayerAnswer == "Misspeled":
Score += 0
easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
print(Score) #To check if programme is calculating score properly
PlayerAnswer = easygui.buttonbox ("Which word is spelt correctly?", choices =["acceptable","aceptable","acceptble",])
if PlayerAnswer == "acceptable":
Score += 1
easygui.msgbox ("Well done! Your score is now " + str(Score))
elif PlayerAnswer == "aceptable":
Score += 0
easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
elif PlayerAnswer == "acceptble":
Score += 0
easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
print(Score) #To check if programme is calculating score properly
PlayerAnswer = easygui.buttonbox ("Which word is spelt correctly?", choices =["calendar","calender","callendar",])
if PlayerAnswer == "calendar":
Score += 1
easygui.msgbox ("Well done! Your score is now " + str(Score))
elif PlayerAnswer == "calender":
Score += 0
easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
elif PlayerAnswer == "callendar":
Score += 0
easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
print(Score) #To check if programme is calculating score properly
PlayerAnswer = easygui.buttonbox ("Which word is spelt correctly?", choices =["equepment","equiptment","equipment",])
if PlayerAnswer == "equipment":
Score += 1
easygui.msgbox ("Well done! Your score is now " + str(Score))
elif PlayerAnswer == "equiptment":
Score += 0
easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
elif PlayerAnswer == "equipment":
Score += 0
easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
print(Score) #To check if programme is calculating score properly
PlayerAnswer = easygui.buttonbox ("Which word is spelt correctly?", choices =["library","liebary","libary",])
if PlayerAnswer == "library":
Score += 1
easygui.msgbox ("Well done! Your score is now " + str(Score))
elif PlayerAnswer == "liebary":
Score += 0
easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
elif PlayerAnswer == "lieberry":
Score += 0
easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
print(Score) #To check if programme is calculating score properly
if Score == 10:
easygui.msgbox ("You got a score of " + str(Score) + " out of 10, you got them all right " + PlayerName+ "!")
elif Score == 9:
easygui.msgbox ("You got a score of " + str(Score) + " out of 10, one away " + PlayerName+ "!")
elif Score == 8:
easygui.msgbox ("You got a score of " + str(Score) + " out of 10, so close "+ PlayerName+"!")
elif Score == 7:
easygui.msgbox ("You got a score of " + str(Score) + " out of 10, nearly there " + PlayerName+"!")
elif Score == 6:
easygui.msgbox ("You got a score of " + str(Score) + " out of 10, amlost made it " + PlayerName+ "!")
elif Score == 5:
easygui.msgbox ("You got a score of " + str(Score) + " out of 10, half way there " + PlayerName+ "!")
elif Score == 4:
easygui.msgbox ("You got a score of " + str(Score) + " out of 10, a little more pratice " + PlayerName+ "!")
elif Score == 3:
easygui.msgbox ("You got a score of " + str(Score) + " out of 10, pratice makes perfect "+ PlayerName+"!")
elif Score == 2:
easygui.msgbox ("You got a score of " + str(Score) + " out of 10, try again " + PlayerName+"!")
elif Score == 1:
easygui.msgbox ("You got a score of " + str(Score) + " out of 10, better luck next time " + PlayerName+ "!")
elif Score == 0:
easygui.msgbox ("You got a score of " + str(Score) + "out of 10, better luck next time " + PlayerName+ "!")
while playOn != "Yes":
playOn = easygui.buttonbox ("Do you want to play again?", choices = ["Yes", "No"])
if playOn == "Yes":
Score = 0 #resets score count, if player wants to play again
elif playOn == "No":
easygui.msgbox ("Bye for now. Hope you'll play the game again soon!")
I'm hoping someone out in the world wide web can pick up on what I've done
wrong. I'm very new to python so any help I can get will be so awesome. I know
I have asked for help with this piece of coding before, but I only just made
an account today, so I don't know how to reply to any comments or anything!
Answer: You are setting `playOn` to `"Yes"` in your first loop.
while playOn != "Yes":
playOn = easygui.buttonbox ("Hey there, are you ready to test your spelling?", choices = ["Yes"])
if "Yes":
PlayerName = easygui.enterbox ("Before we begin, what's your name?")
At the end of the program, you are going into a `while` loop only while
`playOn` does not equal `"Yes"`.
while playOn != "Yes":
playOn = easygui.buttonbox ("Do you want to play again?", choices = ["Yes", "No"])
if playOn == "Yes":
Score = 0 #resets score count, if player wants to play again
elif playOn == "No":
easygui.msgbox ("Bye for now. Hope you'll play the game again soon!")
But, you set (and did not change) `playOn` at the beginning of your program to
`"Yes"`, so the loop is skipped and the program ends.
* * *
A few notes to help you out
* "amlost made it"/"little more pratice"/"pratice makes perfect" - You have some spelling errors in your spell checker program.
* The program is very verbose and you have a lot of redundant code. You mentioned this was a school assignment so I'm not going to provide shorter code samples, but I'd encourage you to look up functions.
* Even fixing the main issue with `playOn`, clicking "Yes" isn't going to reset your program. You still need a way to get to the beginning of your spell check code (hint: functions again are your friend/alternatively an outer loop will also help)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.