text
stringlengths 226
34.5k
|
---|
433MHz Sender and Receiver in Python on Raspberry PI
Question: Is there any way to get a working 433MHz-Sender or -Receiver in a Python
Thread?
I have tried those from Ninjablocks and those from Adafruit. But the Problem
is that these are all c or c++ scripts, that are outputting to stdout and have
no end of the output. I also tried piping them through a Unix-FIFO but there
no data is transmitted until I close the Program (Ctrl + C) the second problem
is, that the finished programs doesn't recognize my ninjablocks 433MHz
Temperature Sensor, that is one of the most important parts of the system.
The 433 MHz Sender/Receiver are connected with the GPIOs of my Raspberry PI
(Version B, Rev 2.0)
My Goal is to get the several 433 MHz Sensors (And some sonsors connected via
i2c or spi these are already working) working with a python script, that does
calculate some Rules (e.g. When Motion detected in Living Room, and between
Sunset and Sunrise, turn Light on; Turn on Heating when Temperature Drops
below 20°C etc.)
I have written a small program:
import RPi.GPIO as io
data = [] * 10000
while not interrupted:
data.append(io.input(rxPin))
io.wait_for_edge(rxPin, io.BOTH
I expected that code to output something like 1010101010101 because every Edge
is recognized. My next step would have been to measure time between the edges
and - based on that time - decide if it was a short 1/0 or a long 1/0 (433MHz
seems to be encoded like short 1 long = = 1 long 1 short 0 = 0 or vise versa)
but the output was something like:0110011001000000010110010 etc. so the python
thread is missing some 1s and 0s, I think.
has anybody an idea to get that Wireless input in my Program?
Answer: If you are running python I guess you are using some kind of linux on the
Raspberry Pi, am I right? Linux is not real time os, meaning your python loop
does not run all the the time and can skip some GPIO data. You can solve it by
either using a real time os like [Chibios](http://www.chibios.org) or use
kernel module to stop all interrupts and sample the GPIO continuously as
demonstrated in the [Panalyzer](https://github.com/richardghirst/Panalyzer)
project.
|
How can I add new methods to a COM server that I have already registered?
Question: **EDIT** : turns out VBA can see the new methods if I restart Excel. My
question still stands, though, albeit in a different form: how can I force
Excel to see the new methods without restarting it?
I have a simple COM server that looks something like this:
class COMServerThing:
_public_methods_ = ["DoStupidThing"]
_reg_progid_ = "COMServerThing.Utilities"
_reg_clsid_ = "{A9DAECC7-2154-42E6-95B3-53A27EAB63E2}"
def DoStupidThing(self):
return 'foo'
I register it like this:
import win32com.server.register
win32com.server.register.UseCommandLine(COMServerThing)
This lets me create a new COMServerThing object from VBA and call my Python
code from Excel. Now I want to add a new method to this server. I've tried
doing the obvious thing:
class COMServerThing:
# Add the new method to the list of public methods ...
_public_methods_ = ["DoStupidThing", "AnotherStupidThing"]
_reg_progid_ = "COMServerThing.Utilities"
_reg_clsid_ = "{A9DAECC7-2154-42E6-95B3-53A27EAB63E2}"
def DoStupidThing(self):
return 'foo'
# ... and implement it on the class.
def AnotherStupidThing(self):
return 42
After doing this, I still can't access the newly registered method from VBA.
Here are some other things I've tried that didn't work:
* I re-registered the server.
* I unregistered and then re-registered the server.
* I unregistered the server, changed the class ID, and then re-registered it.
The only thing that worked was renaming the server, changing its class ID,
renaming the source file that the server is in, and registering the new server
– at which point we're looking at a whole new COM server.
I'm not a Windows/COM developer, so I'm pretty sure I'm missing something
blatantly obvious. How can I add new methods to a COM server that I've already
registered?
Answer: Are you exposing your methods via [IDispatchEx](http://msdn.microsoft.com/en-
us/library/sky96ah7%28VS.94%29.aspx), or are you exposing them through custom
interfaces derived from IUnknown?
If you're exposing custom interfaces, then you'll most likely have to restart
Excel, since you're breaking [COM identity
rules](http://msdn.microsoft.com/en-
us/library/windows/desktop/ms686590%28v=vs.85%29.aspx). Even with
[IDispatch](http://msdn.microsoft.com/en-
us/library/windows/desktop/ms221608%28v=vs.85%29.aspx), the documentation
explicitly says
> The member and parameter DISPIDs must remain constant for the lifetime of
> the object. This allows a client to obtain the DISPIDs once, and cache them
> for later use.
|
python code returns none type object has no attribute error sometimes and works perfectly the other time
Question:
def dcrawl(link):
#importing the req. libraries & modules
from bs4 import BeautifulSoup
import urllib
#fetching the document
op = urllib.FancyURLopener({})
f = op.open(link)
h_doc = f.read()
#trimming for the base document
idoc1 = BeautifulSoup(h_doc)
idoc2 = str(idoc1.find(id = "bwStory"))
bdoc = BeautifulSoup(idoc2)
#extract the date as a string
dat = str(bdoc.div.div.string)[0:13]
date = dst(dat)
#extract the title as a string
title = str(bdoc.b.string)
#extract the full report as a string
freport = str(bdoc.find_all("p"))
#extract the place as a string
plc = bdoc.find(id = "bwStoryBody")
puni = plc.p.string
#encoding to ascii to eliminate discrepancies
pasi = puni.encode('ascii', 'ignore')
com = pasi.find("-")
place = pasi[:com]
the same conversion "bdoc.b.string" works here:
#extract the full report as a string
freport = str(bdoc.find_all("p"))
In the line:
plc = bdoc.find(id = "bwStoryBody")
`plc` returns some data. and `plc.p` returns the first `<p>....<p>`, but
converting it to string doesn't work.
because `puni` returned a string object earlier, I stumbled upon unicode
errors and so had to use the encode to handle the `pasi` result.
Answer: `.find()` returns `None` when an object was _not_ found. Evidently some pages
do not have the elements that you are looking for.
Test for it explicitly if you want to prevent attribute errors:
plc = bdoc.find(id = "bwStoryBody")
if plc is not None:
puni = plc.p.string
#encoding to ascii to eliminate discrepancies
#By default python processes in unicode
pasi = puni.encode('ascii', 'ignore')
com = pasi.find("-")
place = pasi[:com]
|
R's read.table equivalent in Python
Question: I'm trying to move some of my processing work from R to Python. In R, I use
read.table() to read REALLY messy CSV files and it automagically splits the
records in the correct format. E.g.
391788,"HP Deskjet 3050 scanner always seems to break","<p>I'm running a Windows 7 64 blah blah blah........ake this work permanently?</p>
<p>Update: It might have something to do with my computer. It seems to work much better on another computer, windows 7 laptop. Not sure exactly what the deal is, but I'm still looking into it...</p>
","windows-7 printer hp"
is correctly separated into 4 columns. 1 record can be split over many lines
and there are commas all over the place. In R I just do:
read.table(infile, header = FALSE, nrows=chunksize, sep=",", stringsAsFactors=FALSE)
Is there something in Python that can do this equally well?
Thanks!
Answer: You can use csv module.
from csv import reader
csv_reader = reader(open("C:/text.txt","r"), quotechar="\"")
for row in csv_reader:
print row
['391788', 'HP Deskjet 3050 scanner always seems to break', "<p>I'm running a Windows 7 64 blah blah blah........ake this work permanently?</p>\n\n<p>Update: It might have something to do with my computer. It seems to work much better on another computer, windows 7 laptop. Not sure exactly what the deal is, but I'm still looking into it...</p>\n", 'windows-7 printer hp']
length of output = 4
|
Filling a strange webform in python
Question: I am trying build a simple program that fills a webform and then extracts the
a data from the resulted website, it should be pretty straight-forward and
after a short web research (mostly from this website) I came to the conclusion
that python would be my best choice.(with urllib)
I would give a specific example of what I am trying to do and hopefully it
will clarify things:
1. Lets say I want an automatic script that gets the price for hotel, the website would be: the Hilton website
2. In that webpage I want to fill the query as follows: the "where are you going" should have N.Y.C and departure and arrival date.
3. If used from the browser, I will get a the next page with the results for the query I just filled and from that webpage I want to scrape the prices.
Lets assume that scraping the data can be done from the html source code.
Well, that's how I thought to do it (very general description....)
import urllib
import urllib.request
url = 'http://www3.hilton.com/en/index.html'
query_args = { 'searchQuery':' New York, NY ', 'arrivalDate':'31 Oct 2013' , 'departureDate': '04 Nov 2013' }
print (query_args)
data = urllib.parse.urlencode(query_args)
print (data)
request = urllib.request.Request(url);
response = urllib.request.urlopen(request,data)
html = response.read()
print (html)
1. First of all I get an the following error when I am sending the request:" TypeError: POST data should be bytes or an iterable of bytes. It cannot be of type str." anyone knows why?
2. If I got it right I would assume that I would accept the response for the following website. hilton_website with the urlencode segment in the end (searchQuery=+New+York%2C+NY&arrivalDate=31+Oct+2013&departureDate=04+Nov+2013)
But there is no such website ( when I am typing the full address to the
browser url) it looks like all the results (and it doesn't matter what was
your query or how you filled the form ) appear on the same webpage:
hilton_web_site...en_US/hi/search/findhotels/results.htm?view=LIST
So what am I doing wrong? I thought that the way to fill a web form.
Thanks a lot for the help
Answer: Here's a dump of hiltons search form (which, i instructed you how to get but
can not paste it all in the comment section so here you go), i forgot to
mention that you should check the "Form data" raw data in Chrome tho which was
my bad.. anyway..
RAW data (so you can understand how a POST request works)
## Request Header
POST /en_US/hi/search/findhotels/index.htm?WT.bid=Home,,,find_button HTTP/1.1
Host: www3.hilton.com
Connection: keep-alive
Content-Length: 475
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Origin: http://www3.hilton.com
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Referer: http://www3.hilton.com/en/index.html
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Cookie: mmcore.tst=0.626; ClrCSTO=T; ClrSSID=1382526492268-11812; ClrOSSID=1382526492268-11812; ClrSCD=1382526492268; mmid=-1914085652%7CAQAAAAq0Q+DZtwkAAA%3D%3D; mmcore.pd=-1914085652%7CAQAAAAq0Q+DZtwkAAA%3D%3D; mmcore.srv=ldnvwcgus01; K3R7=3U24QMiCUbjeh65LoEI31TTjisY8czr4zkIUe06gsA4A5lc0bIKrEhQ; GWSESSIONID=qYDpSnSLNFnJ5CrJrwlSWW7CNBHL7vXSMndGmnxghGns1rLjt2lX!-1490734837; __atuvc=1%7C43; mm_pc_HHonorsPoints=false; mm_pers_storage=loggedin%3Ano%7CStayDuration%3A1-2%20nights%7CDaysToBooking%3A0-1%7CSatStay%3Ano%7CChildren%3Ano%7CBrand%3Ahi%7CHHonorsPoints%3Afalse%7CFlexDates%3Afalse%7CPromoCode%3Ano%7Cproperties8%3Ano%7Chotelcode%3Ano; WT_FPC=id=6f7c5181-8354-430b-b943-9bb95bf2c75c:lv=1382490515002:ss=1382490495203
## Form data
searchQuery=N.Y.C&arrivalDate=23+Oct+2013&departureDate=24+Oct+2013&_flexibleDates=on&numberOfRooms=1&numberOfAdults%5B0%5D=1&numberOfChildren%5B0%5D=0&numberOfAdults%5B1%5D=1&numberOfChildren%5B1%5D=0&numberOfAdults%5B2%5D=1&numberOfChildren%5B2%5D=0&numberOfAdults%5B3%5D=1&numberOfChildren%5B3%5D=0&promoCode=&groupCode=&corporateId=&_travelAgentRate=on&_aaaRate=on&_aarpRate=on&_seniorRate=on&_governmentRate=on&offerId=&bookButton=false&searchType=ALL&roomKeyEnable=true
And these are they keys (not values) that you **need** to send with each
search query:
* searchQuery
* arrivalDate
* departureDate
* _flexibleDates
* numberOfRooms
* numberOfAdults%5B0%5D
* numberOfChildren%5B0%5D
* numberOfAdults%5B1%5D
* numberOfChildren%5B1%5D
* numberOfAdults%5B2%5D
* numberOfChildren%5B2%5D
* numberOfAdults%5B3%5D
* numberOfChildren%5B3%5D
* promoCode
* groupCode
* corporateId
* _travelAgentRate
* _aaaRate
* _aarpRate
* _seniorRate
* _governmentRate
* offerId
* bookButton
* searchType
* roomKeyEnable
And this is what a python build of the whole thing would look like:
from socket import *
s = socket()
POST = 'searchQuery=N.Y.C&arrivalDate=23+Oct+2013&departureDate=......'
header = ''
header += 'POST /en_US/hi/search/findhotels/index.htm?WT.bid=Home,,,find_button HTTP/1.1\r\n'
header += 'Host: www3.hilton.com\r\n'
header += 'Connection: keep-alive\r\n'
header += 'Content-Length: ' + str(len(POST)) + '\r\n'
header += 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\n'
header += 'Origin: http://www3.hilton.com\r\n'
header += 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) \r\n'
header += 'Chrome/30.0.1599.101 Safari/537.36\r\n'
header += 'Content-Type: application/x-www-form-urlencoded\r\n'
header += 'Referer: http://www3.hilton.com/en/index.html\r\n'
header += 'Accept-Encoding: gzip,deflate,sdch\r\n'
header += 'Accept-Language: en-US,en;q=0.8\r\n'
header += '\r\n'
s.connect(('www3.hilton.com', 80))
s.send(header+POST)
print(s.recv(8192))
And that would give you what you're looking for. Note that i left out the
cookie field in the header.. normally the server doesn't care to much about it
because it's an ancient technique and there for the server usually assumes
that if no cookies was given, just give the client new ones and assume it's
the first visit even tho (well technically it is but) it is'nt really the
actual first page.
## Also note:
All data in the `POST` variable must be URL encoded as such:
`urlencode(key)=urlencode(val)&` for each pair. Note how i did not url-encode
the `=` or the `&` in this raw POST data.
This is where you wouldn't need to worry about it because urllib does it for
you. But this gives you a understanding of how HTTP requests work.
|
AttributeError: 'NoneType' object has no attribute 'lower' python
Question: My abc.txtfile looks like this
Mary Kom 28 F
Emon Chatterje 32 M
Sunil Singh 35 M
Now i am getting the desired result with the following traceback:Please help
me out. I am not getting where am i going wrong
Enter for Search Criteria
1.FirstName 2.LastName 3.Age 4.Gender 5.Exit 1
Enter FirstName :m
Mary Kom 28 F
Emon Chatterje 32 M
Traceback (most recent call last):
File "testcode.py", line 50, in <module>
if (records.searchFName(StringSearch)):
File "testcode.py", line 12, in searchFName
return matchString.lower() in self.fname.lower()
AttributeError: 'NoneType' object has no attribute 'lower'
My Code:
#!usr/bin/python
import sys
class Person:
def __init__(self, firstname=None, lastname=None, age=None, gender=None):
self.fname = firstname
self.lname = lastname
self.age = age
self.gender = gender
def searchFName(self, matchString):
return matchString.lower() in self.fname.lower()
def searchLName(self, matchString):
return matchString.lower() in self.lname.lower()
def searchAge(self, matchString):
return str(matchString) in self.age
def searchGender(self, matchString):
return matchString.lower() in self.gender.lower()
def display(self):
print self.fname, self.lname, self.age, self.gender
f= open("abc","r")
list_of_records = [Person(*line.split()) for line in f]
f.close()
found = False
n=0
n1 = raw_input("Enter for Search Criteria\n1.FirstName 2.LastName 3.Age 4.Gender 5.Exit " )
if n1.isdigit():
n = int(n1)
else:
print "Enter Integer from given"
sys.exit(1)
if n == 0 or n>5:
print "Enter valid search "
if n == 1:
StringSearch = raw_input("Enter FirstName :")
for records in list_of_records:
if (records.searchFName(StringSearch)):
found = True
records.display()
if not found:
print "No matched record"
if n == 2:
StringSearch = raw_input("Enter LastName :")
for records in list_of_records:
if records.searchLName(StringSearch):
found = True
records.display()
if not found:
print "No matched record"
if n == 3:
StringSearch = raw_input("Enter Age :")
if (StringSearch.isdigit()):
StringSearch1 = int(StringSearch)
else:
print "Enter Integer"
sys.exit()
for records in list_of_records:
if records.searchAge(StringSearch):
found = True
records.display()
if not found:
print "No matched record"
if n == 4:
StringSearch = raw_input("Enter Gender(M/F) :")
for records in list_of_records:
if records.searchGender(StringSearch):
found = True
records.display()
if not found:
print "No matched record"
if n == 5:
sys.exit(1)
Please help solve my problrm to where am i going wrong ??
Answer: You have a `Person()` class with no `firstname`. You created it from an empty
line in your file:
list_of_records = [Person(*line.split()) for line in f]
An empty line results in an empty list:
>>> '\n'.split()
[]
which leads to `Person(*[])` being called, so a `Person()` instance was
created with no arguments, leaving the default `firstname=None`.
Skip empty lines:
list_of_records = [Person(*line.split()) for line in f if line.strip()]
You may also want to default to empty strings, or specifically test for `None`
values before treating attributes as strings:
def searchFName(self, matchString):
return bool(self.fname) and matchString.lower() in self.fname.lower()
Here `bool(self.fname)` returns `False` for empty or `None` values, giving you
a quick `False` return value when there is no first name to match against:
>>> p = Person()
>>> p.fname is None
True
>>> p.searchFName('foo')
False
|
Deterministic and non uniform long string generation from seed
Question: I had this weird idea for an encryption that I wanted to try out, it may be
bad, and it may have done before, but I'm just doing it for fun. The short
version of the question is: Is it possible to generate a long, deterministic
and non-uniformly distributed string/sequence of numbers from a small seed?
Long(er) version: I was thinking to encrypt a text by changing encoding. The
new encoding would be generated via Huffman algorithm. To work well, the
Huffman algorithm would need a fairly long text with non uniform distribution.
Then characters can have different bit-lengths which would be the primary
strength of this encryption. The problem is that its impractical to enter
in/remember a long text each time you want to decrypt the text. So I was
wondering if it was possible to generate a text from password seed?
It doesn't matter what the text is, as long as it has non uniform distribution
of characters and that the exact same sequence can be recreated each time you
give it the same seed. Preferably, are there any functions/extensions in
Python that can do this?
EDIT: To expand on the "strength" of varying bit length: if I have a string
"test", ASCII values 116, 101, 115, 116, which gives bit values of 1110100
1100101 1110011 1110100
Then, say my Huffman algorithm generates encoding like t = 101 e = 1100111 s =
10001
The final string is 101 1100111 10001 101, if we encode this back to ASCII, we
get 1011100 1111000 1101000, which is 3 entirely different characters, its
"\xh". Obviously its impossible to perform any kind of frequency analysis or
something like that on this.
Answer: This is a solution based on `random` module, which will generate the same
sequence if given the same seed.
import random
from string import ascii_lowercase
from collections import Counter
seed_value = 3334
string_length = 50
random.seed(seed_value)
seq = [(x,random.randint(1,10)) for x in ascii_lowercase]
weighted_choice = lambda s : random.choice(sum(([v]*wt for v,wt in s),[]))
random_list = [weighted_choice(seq) for x in range(string_length)]
print("".join(random_list))
print("Test non uniform distribution...")
print(Counter(random_list))
|
In SWIG , how can i use int * variable without typemaps.i
Question: I have a program where in a C function somewhat like below code. When i try to
call this function via python it it throwing error saying
argument 2 of type 'int *'. In swig i saw there is way to handle this that is
via typemaps is there any other way other typemaps. As there are bunch of
functions with numerous arguments having int * .
#include<stdio.h>
int check(int k, int *i) {
if( k%2 == 0)
*i = 1;
else
*i = 0;
}
Answer: Typemaps are really the way SWIG handles all types, but if you don't want
`typemaps.i` specifically, then how about:
%module x
%include <cpointer.i>
%pointer_functions(int,int)
%inline %{
void check(int k, int *i) {
if (k % 2 == 0)
*i = 1;
else
*i = 0;
}
%}
`cpointer.i` lets you create simple pointers to a type. Here's an example of
use:
>>> import x
>>> i=x.new_int()
>>> x.check(6,i)
>>> x.int_value(i)
1
>>> x.delete_int(i)
But really, it is simpler to use `typemaps.i`. Below `%apply` applies the
predefined `OUTPUT` typemap, declaring that all future `int *` parameters are
output parameters. Python will not require the parameter for the call, and
will return the parameter as an output instead. The normal return value and
all output parameters are returned using a tuple if necessary.
%module x
%include <typemaps.i>
%apply int *OUTPUT { int * };
%inline %{
void check(int k, int *i) {
if (k % 2 == 0)
*i = 1;
else
*i = 0;
}
%}
Use example:
>>> import x
>>> x.check(5)
0
>>> x.check(6)
1
|
Error in hierarchical clustering with hcluster in python
Question: I am trying to ran the following code, and I get an AttributeError: 'module'
object has no attribute 'hcluster', raised in the last line.
I am running in Mountain Lion, I use pip and homebrew, and hcluster is in
PYTHONPATH=/usr/local/lib/python2.7/site-packages.
Any idea what can be going wrong? Thanks.
import os
import hcluster
from numpy import *
from PIL import Image
# create a list of images
path = 'data/flickr-sunsets-small'
imlist = [os.path.join(path,f) for f in os.listdir(path) if f.endswith('.jpg')]
# extract feature vector (8 bins per color channel)
features = zeros([len(imlist), 512])
for i,f in enumerate(imlist):
im = array(Image.open(f))
# multi-dimensional histogram
h,edges = histogramdd(im.reshape(-1,3),8,normed=True,range=[(0,255),(0,255),(0,255)])
features[i] = h.flatten()
tree = hcluster.hcluster(features)
Answer: This error means that Python cannot find the function/class `hcluster` in the
module `hcluster`, so when you do `tree = hcluster.hcluster(features)` it
complains.
I'm not familiar with this module, but I had a quick look at this it, and it
lists a function called `fcluster`, but no `hcluster`.
|
Removing duplicates and preserving order when elements inside the list is list itself
Question: I have a following problem while trying to do some nodal analysis:
For example:
my_list=[[1,2,3,1],[2,3,1,2],[3,2,1,3]]
I want to write a function that treats the element_list inside my_list in a
following way:
> -The number of occurrence of certain element inside the list of my_list is
> not important and, as long as the unique elements inside the list are same,
> they are identical.
>
> Find the identical loop based on the above premises and only keep the first
> one and ignore other identical lists of my_list while preserving the order.
Thus, in above example the function should return just the first list which is
[1,2,3,1] because all the lists inside my_list are equal based on above
premises.
I wrote a function in python to do this but I think it can be shortened and I
am not sure if this is an efficient way to do it. Here is my code:
def _remove_duplicate_loops(duplicate_loop):
loops=[]
for i in range(len(duplicate_loop)):
unique_el_list=[]
for j in range(len(duplicate_loop[i])):
if (duplicate_loop[i][j] not in unique_el_list):
unique_el_list.append(duplicate_loop[i][j])
loops.append(unique_el_list[:])
loops_set=[set(x) for x in loops]
unique_loop_dict={}
for k in range(len(loops_set)):
if (loops_set[k] not in list(unique_loop_dict.values())):
unique_loop_dict[k]=loops_set[k]
unique_loop_pos=list(unique_loop_dict.keys())
unique_loops=[]
for l in range(len(unique_loop_pos)):
unique_loops.append(duplicate_loop[l])
return unique_loops
Answer:
from collections import OrderedDict
my_list = [[1, 2, 3, 1], [2, 3, 1, 2], [3, 2, 1, 3]]
seen_combos = OrderedDict()
for sublist in my_list:
unique_elements = frozenset(sublist)
if unique_elements not in seen_combos:
seen_combos[unique_elements] = sublist
my_list = seen_combos.values()
|
Using httplib to connect to a website in Python
Question: tl;dr: Used the httplib to create a connection to a site. I failed, I'd love
some guidance!
I've ran into some trouble. Read about socket and httplib of python's, altough
I have some problems with the syntax, it seems.
Here is it:
connection = httplib.HTTPConnection('www.site.org', 80, timeout=10, 1.2.3.4)
The syntax is this:
httplib.HTTPConnection(host[, port[, strict[, timeout[, source_address]]]])
How does "source_address" behave? Can I make requests with any IP from it?
Wouldn't I need an User-Agent for it?
Also, how do I check if the connect is successful?
if connection:
print "Connection Successful."
(As far as I know, HTTP doesn't need a "are you alive" ping every one second,
as long as both client & server are okay, when a request is made, it'll be
processed. So I can't constantly ping.)
Answer: Creating the object does not actually connect to the website:
`HTTPConnection.connect(): Connect to the server specified when the object was
created.`
`source_address` seems to be sent to the server with any request, but it
doesn't seem to have any effect. I'm not sure why you'd need to use a User-
Agent for it. Either way, it is an optional parameter.
You don't seem to be able to check if a connection was made, either, which is
strange.
Assuming what you want to do is get the contents of the website root, you can
use this:
from httplib import HTTPConnection
conn = HTTPConnection("www.site.org", 80, timeout=10)
conn.connect()
conn.request("GET", "http://www.site.org/")
resp = conn.getresponse()
data = resp.read()
print(data)
(slammed together from the [HTTPConnection
documentation](http://docs.python.org/2/library/httplib.html#httpconnection-
objects))
Honestly though, you should not be using `httplib`, but instead `urllib2` or
another HTTP library that is less... low-level.
|
Trying to get code to output multiple columns in Python
Question: I am importing a data set and trying to output some text analysis. However, I
can only get it to output the last column of data. Where do I put the
csv.writer in order to get all the lines of code in?
from __future__ import division
import csv
import re
from string import punctuation
faithwords = ['church', 'faith', 'faith']
with open('dataset.csv', 'rb') as csvfile:
data = csv.reader(csvfile, delimiter=",")
for row in data:
faithcounter = 0
row3 = row[3]
row3 = row3.lower().replace(' ', ' ')
row4 = row[4]
row4 = row4.lower().replace(' ', ' ')
for p in list(punctuation):
row3 = row3.replace(p, '')
row4 = row4.replace(p, '')
essay1= re.split(' ', row3)
essay2= re.split(' ', row4)
essay1len = len(essay1)
essay2len = len(essay2)
num_of_rows = len(row)
for word in essay1:
if word in faithwords:
faithcounter = faithcounter + 1
for word in essay2:
if word in faithwords:
faithcounter = faithcounter + 1
totallen = (essay2len + essay1len)
row.append(essay1len)
row.append(essay2len)
row.append(totallen)
row.append(faithcounter)
row.append(faithcounter / totallen)
output = zip(row)
writer = csv.writer(open('csvoutput.csv', 'wb'))
writer.writerows(output)
Answer: Your problem is with this line:
output=zip(row)
I'm not sure why you are doing `zip`, but I do know that your are overwriting
`output` on each iteration.
I recommend that you create your csv writer before your loop. Then, as the
last statement in your loop, do:
writer.writerow(row)
|
Decrypt using an RSA public key with PyCrypto
Question: As far as I understand, I should be able to use RSA to ensure authenticity or
privacy, as I wish. In my case, I want to ensure authenticity so I encrypt the
data with the private key and allow anyone to decrypt it with the public key.
The data is not really secret but I need to guarantee that it was created by
the owner of the public (and private) key.
When I try to decrypt using PyCrypto I get **No private key** error from
PyCrypto. The code is this:
def _decrypt_rsa(decrypt_key_file, cipher_text):
from Crypto.PublicKey import RSA
from base64 import b64decode
key = open(decrypt_key_file, "r").read()
rsakey = RSA.importKey(key)
raw_cipher_data = b64decode(cipher_text)
decrypted = rsakey.decrypt(raw_cipher_data)
return decrypted
I'm calling it with the path to the public key file (in OpenSSH format.) The
encrypted data isn't generated by me and it was not done with Python but PHP.
In PHP there's a `openssl_public_decrypt` function that decrypts this data
easily.
Is it possible at all to decrypt using the public key with PyCrypto?
Answer: That is totally insecure, because you are using raw RSA without padding.
Your application needs a signature, so you should not be dealing with
encryptions and decryptions. For instance, PKCS#1 v1.5 is a good protocol,
even though the signature is a piece of data that must be appended to what you
want to prove the authenticity of.
To verify a PKCS#1 v1.5 signature in Python, you do:
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA
rsa_key = RSA.importKey(open(verification_key_file, "rb").read())
verifier = PKCS1_v1_5.new(rsa_key)
h = SHA.new(data_to_verify)
if verifier.verify(h, signature_received_with_the_data):
print "OK"
else:
print "Invalid"
I would strongly recommend to change the PHP code so that it creates such a
signature.
|
My character won't move in python
Question: This is the code I used.
import pygame, sys
from pygame.locals import *
pygame.init()
def game():
width, height = 1000, 600
screen = pygame.display.set_mode((width,height))
pygame.display.set_caption('My game far now :P') #This command allows you make a title.
background=pygame.image.load('AE.jpg')
background = pygame.transform.scale(background, (width,height))
screen.blit(background, (0,0))
#Load target image and player
player = pygame.image.load('little.png')
player = pygame.transform.scale(player, (40,40))
px,py = width/2,height/2
screen.blit(player, (px,py))
movex = movey = 0
#Running of the game loop
while True:
screen.blit(background, (0,0))
#screen.blit(target,targetpos)
screen.blit(player, (px,py))
pygame.display.update()
#keyboard an/or mouse movements
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
elif event.type == pygame.KEYDOWN:
if event.key == K_RIGHT:
movex = 2
if event.key == K_LEFT:
movex = -2
if event.key == K_UP:
movey = -2
if event.key == K_DOWN:
movey = 2
elif event.type == pygame.KEYUP:
if event.key == K_RIGHT:
movex = 0
if event.key == K_LEFT:
movex = 0
if event.key == K_UP:
movey = 0
if event.key == K_DOWN:
movey = 0
px = px + movex
py = py + movey
#Python 's way of running the main routine
if __name__=='__main__':
game()
When I run the program it all starts right, the screen opens with background
and player spawning in the middle of the screen, but when I try to move
nothing happends, no errors nothing.
Would apriciate any help I can get :)
Thx for taking time to help me.
Answer: You seem to have code indentation problem in last two lines which may be
causing the bug.
Your curent code is equivalent to this if code block:
elif event.type == pygame.KEYUP:
if event.key == K_RIGHT:
movex = 0
if event.key == K_LEFT:
movex = 0
if event.key == K_UP:
movey = 0
if event.key == K_DOWN # IF BLOCK STARTS
movey = 0
px = px + movex # THIS FALLS IN THE PREVIOUS IF BLOCK
py = py + movey
Correct code would be :
elif event.type == pygame.KEYUP:
if event.key == K_RIGHT:
movex = 0
if event.key == K_LEFT:
movex = 0
if event.key == K_UP:
movey = 0
if event.key == K_DOWN # IF BLOCK STARTS
movey = 0 #IF BLOCK ENDS
px = px + movex # NOW THIS IS OUT OF THE IF BLOCK
py = py + movey
|
How to modify Jinja templates for nbconvert?
Question: I am trying to find alternate ways to display my IPython Notebooks.
What I am currently doing is modifying the Jinja templates found here
(C:\Anaconda\Lib\site-
packages\ipython-1.1.0-py2.7.egg\IPython\nbconvert\templates) and then simply
using the nbconvert command line tool to export them into an HTML file. This
method works but I have been unable to modify the actual layout of the
notebook.
Below are some examples on how I want my notebooks to look like.
[Example
1](http://www.google.com/imgres?espv=210&es_sm=93&biw=1600&bih=799&tbm=isch&tbnid=PNlyKvtTzF54_M%3a&imgrefurl=http://www.karenandarthritis.com/news-
time.shtml&docid=5OlDvxwbs1EJHM&imgurl=http://www.karenandarthritis.com/images/time-
article.jpg&w=800&h=1064&ei=Yx1oUsJqj6PgA-
WXgJgJ&zoom=1&ved=1t:3588,r:0,s:0,i:88&iact=rc&page=1&tbnh=201&tbnw=151&start=0&ndsp=27&tx=79&ty=35)
[Example
2](http://www.google.com/imgres?espv=210&es_sm=93&biw=1600&bih=799&tbm=isch&tbnid=uMkWsNYMZMYdsM%3a&imgrefurl=http://www.personal.psu.edu/cbp5032/blogs/pritts_art_203/2010/05/assignment-21-authorship-
and-
technology.html&docid=2ti40PeirOM4SM&imgurl=http://www.personal.psu.edu/cbp5032/blogs/pritts_art_203/ed_article_time-
magazine.jpg&w=1000&h=1357&ei=Yx1oUsJqj6PgA-
WXgJgJ&zoom=1&ved=1t:3588,r:1,s:0,i:91&iact=rc&page=1&tbnh=201&tbnw=148&start=0&ndsp=27&tx=110&ty=76)
[Example
3](http://www.google.com/imgres?espv=210&es_sm=93&biw=1600&bih=799&tbm=isch&tbnid=7SCjINSnUbXKEM%3a&imgrefurl=http://www.dezeen.com/2008/05/15/dezeen-
in-time-magazines-
design-100/&docid=k49Z4G2U__NZCM&imgurl=http://static.dezeen.com/uploads/2008/05/time-
article.jpg&w=450&h=450&ei=Yx1oUsJqj6PgA-
WXgJgJ&zoom=1&ved=1t:3588,r:92,s:0,i:372&iact=rc&page=3&tbnh=187&tbnw=187&start=63&ndsp=44&tx=72&ty=84)
[Example
4](http://www.google.com/imgres?start=261&espv=210&es_sm=93&biw=1600&bih=799&tbm=isch&tbnid=XpTF0HdpczeeGM%3a&imgrefurl=http://ozandends.blogspot.com/2012_10_01_archive.html&docid=pGA8a2buMjXN0M&imgurl=http://1.bp.blogspot.com/-Q4Wi1H4EDZE/UHs8ZVmGwBI/AAAAAAAAFM0/wZsSgED6Iwo/s1600/TTSpot%252B10%252BLyga%252Bletter.jpg&w=400&h=539&ei=UiBoUq_SHfe14APmsIHADQ&zoom=1&ved=1t:3588,r:89,s:200,i:271&iact=rc&page=9&tbnh=172&tbnw=127&ndsp=40&tx=40&ty=69)
**EDIT:**
**[Here](https://dl.dropboxusercontent.com/u/37919918/Untitled2.html)** is
what I was able to come up with adding a little html code to the notebook.
Sample Code:
from IPython.display import HTML
bottom = """
<div style="background:darkblue;color:white;border-radius:10px 10px 10px 10px;">
<br>
<div class="container-fluid">
<div class="row-fluid">
<div class="span12">
<!--Sidebar content-->
<font size="5"><strong><p>A powerful course of study for:</p></strong></font>
<br>
<ul>
<li>The basic foundation for Data Analysis</li>
<li>Hands-on experience with seasoned professionals</li>
<li>Entry-level IT professionals seeking a strong foundation</li>
<li>Managers who manage small to large scale analytical projects</li>
</ul>
</div>
</div>
</div>
</div>
"""
HTML(bottom)
Answer: At first I was not sure if this is a "real" question, as there is a
significant difference between a notebook and a newspaper!
However, if the question aims at getting multicolumns in the nbconverted
notebook, I would suggest googling for `html multicolumn`. There you will find
some options including CSS based styling.
Using this approach simply copy the html_full template and add a div style
like
div.mcolumn {
-webkit-colums: 3 200px;
-moz-column-count: 3;
-moz-column-width: 200px;
columns: 3 200px;
-moz-column-gap:30px; /* Firefox */
-webkit-column-gap:30px; /* Safari and Chrome */
column-gap:30px;
-moz-column-rule:1px dotted #aaaaaa; /* Firefox */
-webkit-column-rule:1px dotted #aaaaaa; /* Safari and Chrome */
column-rule:1px dotted #aaaaaa;
}
Embed the whole page (body block) in this div and voilá, you have a 3 column
layout. However, be aware that code cells and images might lead to some
issues.
|
select a random range of curves within current selection
Question: I am an absolute novice, but have a feeling this is an easy thing for someone
who knows python.
Basically I have a group of nurbs curves selected, and what I want to do is
randomize the selection with a specified range. For instance from a list of
100 curves, or basically whatever I have selected, give me a random random 50
back. Hope I made this clear enough.
All I've managed to get so far is printing a random curve within my selection.
import maya.cmds as m
import random
sel = m.ls(sl=True)
from random import choice
print choice(sel)
Answer: `random.choice(population)` gives you one random element from `population`.
`random.sample(population, k)` gives you a sampling of _k_ elements from
`population`.
|
Python and multiple select with a ListCtrl
Question: I have a custom listctrl in my application that I would like the ability to
select multiple rows (and deselect) much like one would do in a ListBox.
Currently I have a listctrl that I am able to grab single selections; however,
once I click on another row in my listctrl, the previous "un-highlights". I
would like it to stay highlighted unless I click on it again -- so the user
knows which rows he/she has selected (exact same way a ListBox works). I tried
adding `wx.LC_MULTIPLE_SEL` to the listctrl line, but this did not work.
Help? Thanks!
I took this example from the following site by Mike Driscoll [Python
Blog](http://www.blog.pythonlibrary.org/2011/01/04/wxpython-wx-listctrl-tips-
and-tricks/). I adapted to it to grab row selections. Essentially I select a
row and the index is appended to a list called `InfoList`. When I select a new
row, it appends correctly, but I would like the row to stay "highlighted" in
the actual list. Then I could add another line to remove an item from the list
if I select it again in the listctrl.
import wx
import wx.lib.mixins.listctrl as listmix
InfoList = []
musicdata = {
0 : ("Bad English", "The Price Of Love", "Rock"),
1 : ("DNA featuring Suzanne Vega", "Tom's Diner", "Rock"),
2 : ("George Michael", "Praying For Time", "Rock"),
3 : ("Gloria Estefan", "Here We Are", "Rock"),
4 : ("Linda Ronstadt", "Don't Know Much", "Rock"),
5 : ("Michael Bolton", "How Am I Supposed To Live Without You", "Blues"),
6 : ("Paul Young", "Oh Girl", "Rock"),
}
########################################################################
class TestListCtrl(wx.ListCtrl):
#----------------------------------------------------------------------
def __init__(self, parent, ID=wx.ID_ANY, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=0):
wx.ListCtrl.__init__(self, parent, ID, pos, size, style)
########################################################################
class TestListCtrlPanel(wx.Panel, listmix.ColumnSorterMixin):
#----------------------------------------------------------------------
def __init__(self, parent):
wx.Panel.__init__(self, parent, -1, style=wx.WANTS_CHARS)
self.list_ctrl = TestListCtrl(self, size=(-1,100),
style=wx.LC_REPORT
|wx.BORDER_SUNKEN
|wx.LC_SORT_ASCENDING
)
self.list_ctrl.InsertColumn(0, "Artist")
self.list_ctrl.InsertColumn(1, "Title", wx.LIST_FORMAT_RIGHT)
self.list_ctrl.InsertColumn(2, "Genre")
items = musicdata.items()
index = 0
for key, data in items:
self.list_ctrl.InsertStringItem(index, data[0])
self.list_ctrl.SetStringItem(index, 1, data[1])
self.list_ctrl.SetStringItem(index, 2, data[2])
self.list_ctrl.SetItemData(index, key)
index += 1
# Now that the list exists we can init the other base class,
# see wx/lib/mixins/listctrl.py
self.itemDataMap = musicdata
listmix.ColumnSorterMixin.__init__(self, 3)
self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColClick, self.list_ctrl)
### I ADDED THIS ###
self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectMustHave, self.list_ctrl)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.list_ctrl, 0, wx.ALL|wx.EXPAND, 5)
self.SetSizer(sizer)
### I ADDED THIS ###
def OnSelectMustHave(self,event):
info = event.GetData()
InfoList.append(info)
print info,InfoList
#----------------------------------------------------------------------
# Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py
def GetListCtrl(self):
return self.list_ctrl
#----------------------------------------------------------------------
def OnColClick(self, event):
print "column clicked"
event.Skip()
########################################################################
class MyForm(wx.Frame):
#----------------------------------------------------------------------
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "List Control Tutorial")
# Add a panel so it looks the correct on all platforms
panel = TestListCtrlPanel(self)
#----------------------------------------------------------------------
# Run the program
if __name__ == "__main__":
app = wx.App(False)
frame = MyForm()
frame.Show()
app.MainLoop()
Answer: A regular ListCtrl works:
import wx
########################################################################
class MyForm(wx.Frame):
#----------------------------------------------------------------------
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "List Control Tutorial")
# Add a panel so it looks the correct on all platforms
panel = wx.Panel(self, wx.ID_ANY)
self.index = 0
self.list_ctrl = wx.ListCtrl(panel, size=(-1,100),
style=wx.LC_REPORT
|wx.BORDER_SUNKEN
)
self.list_ctrl.InsertColumn(0, 'Subject')
self.list_ctrl.InsertColumn(1, 'Due')
self.list_ctrl.InsertColumn(2, 'Location', width=125)
btn = wx.Button(panel, label="Add Line")
btn.Bind(wx.EVT_BUTTON, self.add_line)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.list_ctrl, 1, wx.ALL|wx.EXPAND, 5)
sizer.Add(btn, 0, wx.ALL|wx.CENTER, 5)
panel.SetSizer(sizer)
#----------------------------------------------------------------------
def add_line(self, event):
line = "Line %s" % self.index
self.list_ctrl.InsertStringItem(self.index, line)
self.list_ctrl.SetStringItem(self.index, 1, "01/19/2010")
self.list_ctrl.SetStringItem(self.index, 2, "USA")
self.index += 1
#----------------------------------------------------------------------
# Run the program
if __name__ == "__main__":
app = wx.App(False)
frame = MyForm()
frame.Show()
app.MainLoop()
And if I modify this to use the two mixins you mentioned, it also works:
import wx
import wx.lib.mixins.listctrl as listmix
########################################################################
class MyListCtrl(wx.ListCtrl, listmix.TextEditMixin, listmix.ColumnSorterMixin):
""""""
#----------------------------------------------------------------------
def __init__(self, parent):
"""Constructor"""
wx.ListCtrl.__init__(self, parent, style=wx.LC_REPORT|wx.BORDER_SUNKEN)
listmix.ColumnSorterMixin.__init__(self, 3)
listmix.TextEditMixin.__init__(self)
#----------------------------------------------------------------------
def GetListCtrl(self):
return self
########################################################################
class MyForm(wx.Frame):
#----------------------------------------------------------------------
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "List Control Tutorial")
# Add a panel so it looks the correct on all platforms
panel = wx.Panel(self, wx.ID_ANY)
self.index = 0
self.list_ctrl = MyListCtrl(panel)
self.list_ctrl.InsertColumn(0, 'Subject')
self.list_ctrl.InsertColumn(1, 'Due')
self.list_ctrl.InsertColumn(2, 'Location', width=125)
btn = wx.Button(panel, label="Add Line")
btn.Bind(wx.EVT_BUTTON, self.add_line)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.list_ctrl, 1, wx.ALL|wx.EXPAND, 5)
sizer.Add(btn, 0, wx.ALL|wx.CENTER, 5)
panel.SetSizer(sizer)
#----------------------------------------------------------------------
def add_line(self, event):
line = "Line %s" % self.index
self.list_ctrl.InsertStringItem(self.index, line)
self.list_ctrl.SetStringItem(self.index, 1, "01/19/2010")
self.list_ctrl.SetStringItem(self.index, 2, "USA")
self.index += 1
#----------------------------------------------------------------------
# Run the program
if __name__ == "__main__":
app = wx.App(False)
frame = MyForm()
frame.Show()
app.MainLoop()
I am using wxPython 2.6 and wxPython 2.8.12 on Windows 7. I can select
multiple items one at a time and deselect them as well.
|
scikitlearn breaks pandas installation
Question: I have a problem having pandas and sklearn work together. Importing any module
from sklearn, makes pandas run havoc.
This is a minimal example of my problem:
#!/usr/bin/env python
import pandas as pd
import sklearn.metrics as sk
df_train = pd.DataFrame()
print df_train
Which prints:
/usr/local/lib/python2.7/site-packages/pandas/core/config.py:570: DeprecationWarning: height has been deprecated.
warnings.warn(d.msg, DeprecationWarning)
If I comment the line where I import `sklearn.metrics`, everything works
correctly
Help? :}
Jose
Answer: You can ignore the warning message with:
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning,
module="pandas", lineno=570)
which should be safe for now. As @Jeff notes, it'll be fixed in pandas 0.13.
|
Python xml.etree.ElemenTree, getting HTML entities
Question: I am trying to analyze xml data, and encountered an issue with regard to HTML
entities when I use
import xml.etree.ElementTree as ET
tree = ET.parse(my_xml_file)
root = tree.getroot()
for regex_rule in root.findall('.//regex_rule'):
print(regex_rule.get('input')) #this ".get()" method turns < into <, but I want to get < as written
print(regex_rule.get('input') == "(?<!\S)hello(?!\S)") #prints out false because ElementTree's get method turns < into < , is that right?
And here is the xml file contents:
<rules>
<regex_rule input="(?<!\S)hello(?!\S)" output="world"/>
</rules>
I would appreciate if anybody can direct me to getting the string as is from
the xml attribute for the input, without converting
<
into
<
Answer: `xml.etree.ElementTree` is doing exactly the standards-compliant thing, which
is to decode XML character entities with the understanding that they do in
fact encode the referenced character and should be interpreted as such.
The preferred course of action if you do need to encode the literal `<` is
to change your input file to use `&lt;` instead (i.e. we XML-encode the
`&`).
If you can't change your input file format then you'll probably need to use a
different module, or write your own parser: `xml.etree.ElementTree` translates
entities well before you can do anything meaningful with the output.
|
Sort an array of tuples by product in python
Question: I have an array of 3-tuples and I want to sort them in order of decreasing
product of the elements of each tuple in Python. So, for example, given the
array
> [(3,2,3), (2,2,2), (6,4,1)]
since 3*2*3 = 18, 2*2*2 = 8, 6*4*1 = 24, the final result would be
> [(6,4,1), (3,2,3), (2,2,2)]
I know how to sort by, for example, the first element of the tuple, but I'm
not sure how to tackle this. Any help would be greatly appreciated. Thanks!
Answer: Use the `key` argument of
[`sorted`](http://docs.python.org/2.7/library/functions.html#sorted)/[`list.sort`](http://docs.python.org/2.7/library/stdtypes.html#typesseq-
mutable) to specify a function for computing the product, and set the
`reverse` argument to `True` to make the results descending rather than
ascending, e.g.:
from operator import mul
print sorted([(3,2,3), (2,2,2), (6,4,1)], key=lambda tup: reduce(mul, tup), reverse=True)
|
Keeping to 79 char line limit in Python with multiple indents
Question: I understand that to write good Python code, I should keep my lines to no more
than 79 characters.
This is fine most of the time, but if I have various nested for loops and if
statements themselves nested within a class, I might easily find that I have 5
or 6 indents (ie 20-24 characters, if I'm indenting by 4 spaces a time) before
I start. Then the 79 character limit becomes quite tricky. I'm aware of
various tricks like implicit continuations within brackets and using brackets
to concatenate long strings, but even so, it gets a bit fiddly.
So, what do you gurus advise?
Indenting by 2 spaces instead of 4 would help, but is that considered good
style? Not sure it would help make my code more readable, and I note that PEP8
says to use 4 spaces.
If I find I have multiple levels of indents, is that perhaps I sign that I'm
writing bad code? And if so, any helpful tips or tricks for ways to avoid too
much nesting?
Am I right in trying to stick to the 79 character recommendation in the first
place?
Or do I just have to get used to a lot of statements broken over multiple
lines?
Thanks Adam
Answer: ### 1\. Loops
You can often use
[`itertools.product`](http://docs.python.org/3/library/itertools.html#itertools.product)
or
[`itertools.combinations`](http://docs.python.org/3/library/itertools.html#itertools.combinations)
to transform nested loops to a single loop.
When the loops are independent, use `product`. For example, these nested
loops:
for x in range(3):
for y in range(5):
for z in range(7):
print((x, y, z))
become the single loop:
from itertools import product
for x, y, z in product(range(3), range(5), range(7)):
print((x, y, z))
When the loop indices must be distinct, then you can use `combinations`. For
example, these nested loops:
for start in range(length - 1):
for end in range(start + 1, length):
print((start, end))
become the single loop:
from itertools import combinations
for start, end in combinations(range(length), 2):
print((start, end))
See [here](http://codereview.stackexchange.com/a/31872/11728) for a real-life
example using `product`, and
[here](http://codereview.stackexchange.com/a/18659/11728) for an example using
`combinations`.
### 2\. Conditions
When you have lots of `if` statements, it's often possible to reorganize the
code to save indentation steps, and at the same time make the code clearer.
The basic idea is to dispose of errors first, and then cases in which you can
`return` immediately, so that the main body of the condition doesn't need to
be indented so far (or, in many cases, at all). For example, if you have code
like:
if x >= 0:
if x == 0:
return 1
else:
# ... main body here ...
return result
else:
raise ValueError("Negative values not supported: {!r}".format(x))
Then you can reorganize the code like this:
if x < 0:
raise ValueError("Negative values not supported: {!r}".format(x))
if x == 0:
return 1
# ... main body here ...
return result
which saves you two levels of indentation for the main body.
|
how to store html form data into file
Question: My HTML code:
<html>
<head>
<title>INFORMATION</title>
</head>
<body>
<form action = "/cgi-bin/test.py" method = "post">
FirstName:
<input type = "text" name = "firstname" /><br>
LastName:
<input type = "text" name = "lastname" /><br>
<input type = "submit" name = "submit "value = "SUBMIT">
<input type = "reset" name = "reset" value = "RESET">
</form>
</body>
My PYTHON CODE (test.py) which is in cgi-bin directory:
#!usr/bin/python
form = web.input()
print form.firstname
print form.lastname
what should i do to store html data in some file ??
Answer: Just write it to a file!
#!usr/bin/python
import cgi
form = cgi.FieldStorage()
with open ('fileToWrite.txt','w') as fileOutput:
fileOutput.write(form.getValue('firstname'))
fileOutput.write(form.getValue'(lastname'))
Oh, and you need to have write permission into the file. So for example if you
are running apache, `sudo chown www-data:www-data fileToWrite.txt` should do
it.
|
PyMongo not working in Django Eclipse
Question: I am trying to integrate MongoDB in my Django Project. For this I have
installed Mongo and PyMongo in my Mac system and everything looks fine. I
tried executing some PyMongo code in python shell and it worked fine.
But when I try to `from pymongo import Connection` in my DJango project it
gives import error. I am not sure where I went wrong.
Can someone suggest a way to fix this problem.
Answer: OK. Issue fixed. Just uninstall and reinstal PyMongo.
sudo pip uninstall pymongo
sudo pip install pymongo -U
|
Gevent: NotImplementedError
Question: Why is gevent throwing this error? Running it in ipython, ubuntu 13
In [1]: from gevent import monkey
In [2]: monkey.patch_all()
In [3]: The history saving thread hit an unexpected error (NotImplementedError('gevent is only usable from a single thread',)).History will not be written to the database.
In [3]:
Answer: `ipython` uses a separate thread to save command history. Because `gevent`
patches threading methods, that pre-existing separate thread triggers the
gevent 'single thread' exception.
I would not use gevent in `ipython`; `ipython` is _not_ compatible with
gevent.
At the very least, try to patch out fewer things; try
`gevent.monkey.patch_all(thread=False)` and see if fewer things in `ipython`
break.
|
How to input a list of tuples
Question: I am coding a python program related to graphs.
My main is like this
if __name__=='__main__':
cns = [(0,1), (0,2),(1,2), (1,3),(3,1)]
G=make_graph(cns)
r=DFS(G)
I want to change the program such that the user can input the data.
cns = [(0,1), (0,2),(1,2), (1,3),(3,1)]
this list is to be read from the user. How to input a list of tuples, how to
do that?
Can I use `raw_input` for this purpose?
Answer:
from ast import literal_eval
cns = literal_eval(raw_input("Please enter the data: "))
|
Why does the collide happen many times?
Question: I'm using openGL with Pyglet which is a python package. I have to use this
language and this package, it is for an assignment. I have a basic
Brickbreaker style game that is basically a keep it up game.
I create a ball and a paddle.
I separately create a bounding box class that will be used to create the hit
boxes for each object.
class BoundBox:
def __init__ (self, width, height, pos):
self.width = width
self.height = height
self.pos = pos
Then I create the boxes themselves
paddleBox = BoundBox(200, 20, [0,0])
ballBox = BoundBox(40, 40, [236, 236])
In the update function which is running @
pyglet.clock.schedule_interval(update,1/100.0) I call the checkcollide()
function which checks if there was a collision:
def checkForCollide():
global collides
if overlap(ballBox, paddleBox):
vel = 1.05
ballVel[0] = ballVel[0]*vel #Ball speeds up when collide happens
ballVel[1] = ballVel[1]*vel
ballVel[1] = -ballVel[1] #Change direction on collision
ballPos[1] = -ballPos[1]
collides += 1 #counts how many collides happen
The overlap function is returning a boolean if there's an overlap in hit
boxes:
def overlap(box1, box2):
return (box1.pos[0] <= box2.width + box2.pos[0]) and(box1.width + box1.pos[0] >= box2.pos[0]) and(box1.pos[1] <= box2.height + box2.pos[1]) and(box1.height + box1.pos[1] >= box2.pos[1])
pos[0] is the minimum x width is the maximum x pos[1] is the minimum y height
is the maximum y
When I run the game and the ball hits the paddle it flickers about 15 times
and increments the collides counter every time it detects a hit. Collides then
prints in the console. Why does this flicker happen? How do I stop it?
Here is the program's full code (you must have pyglet installed to run it):
import sys, time, math
from pyglet.gl import *
from euclid import *
from pyglet.window import key
from pyglet.clock import *
window = pyglet.window.Window(512,512)
quadric = gluNewQuadric()
ballPos = Vector2(256,256)
ballVel = Vector2(200,145)
x1 = 0
bar = pyglet.graphics.vertex_list(4, ('v2f', [0,0, 0,20, 200,0, 200,20]))
startTime = time.clock()
collides = 0
#pos is minx, miny
class BoundBox:
def __init__ (self, width, height, pos):
self.width = width
self.height = height
self.pos = pos
def overlap(box1, box2):
return (box1.pos[0] <= box2.width + box2.pos[0]) and(box1.width + box1.pos[0] >= box2.pos[0]) and(box1.pos[1] <= box2.height + box2.pos[1]) and(box1.height + box1.pos[1] >= box2.pos[1])
paddleBox = BoundBox(200, 20, [0,0])
ballBox = BoundBox(40, 40, [236, 236])
@window.event
def on_draw():
glClear(GL_COLOR_BUFFER_BIT)
glPushMatrix()
glPushMatrix()
glColor3f(1,1,1)
glTranslatef(x1, 0, 0)
bar.draw(GL_TRIANGLE_STRIP)
glPopMatrix()
glTranslatef(ballPos[0], ballPos[1], 0)
glColor3f(1,0,0)
gluDisk(quadric, 0, 20, 32, 1)
glPopMatrix()
@window.event
def on_key_press(symbol, modifiers):
global x1
dist = 30
if symbol == key.RIGHT:
#print "right"
x1 += dist
elif symbol == key.LEFT:
#print "left"
x1 -= dist
def checkForBounce():
if ballPos[0] > 512.0:
ballVel[0] = -ballVel[0]
ballPos[0] = 512.0 - (ballPos[0] - 512.0)
elif ballPos[0] < 0.0:
ballVel[0] = -ballVel[0]
ballPos[0] = -ballPos[0]
if ballPos[1] > 512.0:
ballVel[1] = -ballVel[1]
ballPos[1] = 512.0 - (ballPos[1] - 512.0)
elif ballPos[1] < -100.0:
gameOver()
def gameOver():
global collides
'''global startTime
elapsed = (time.time() - startTime)
score = elapsed * .000000001
finalscore = '%.1f' % round(score, 1)'''
gostr = "GAME OVER"
print gostr
str = "Your score = "
print str
print collides
pyglet.app.exit()
def checkForCollide():
global collides
if overlap(ballBox, paddleBox):
vel = 1.05
ballVel[0] = ballVel[0]*vel #Ball speeds up when collide happens
ballVel[1] = ballVel[1]*vel
ballVel[1] = -ballVel[1] #Change direction on collision
ballPos[1] = -ballPos[1]
collides += 1 #counts how many collides happen
print collides
#glscale(0.5, 1, 1)
def update(dt):
global ballPos, ballVel, ballBox, x1, paddleBox
ballBox = BoundBox(40, 40, [ballPos[0], ballPos[1]])
paddleBox = BoundBox(200, 20, [x1,0])
#print paddleBox.pos
#print ballBox.pos
ballPos += ballVel * dt
checkForBounce()
checkForCollide()
pyglet.clock.schedule_interval(update,1/100.0)
pyglet.app.run()
Answer: I don't think you wanted to invert the position here:
def checkForCollide():
global collides
if overlap(ballBox, paddleBox):
vel = 1.05
ballVel[0] = ballVel[0]*vel #Ball speeds up when collide happens
ballVel[1] = ballVel[1]*vel
ballVel[1] = -ballVel[1] #Change direction on collision
ballPos[1] = -ballPos[1]
collides += 1 #counts how many collides happen
What were you trying to do with this line?
ballPos[1] = -ballPos[1]
I suspect that is why you are flickering.
|
Scope of function inside the function (understanding recursion)
Question: What is the scope of the function itself inside the function in python? My
question arises because I finally thought about venturing into recursion (
though I am not competent enough to understand it fully). I am using Eclipse
(PyDev) and inside the class, for example:
A simple recursion example for factorial widespread in every book is:
def factorial(n):
if (n==0):
return 1
else:
return n*factorial(n-1)
In another example, inside the class:
class test:
def factorial(self,n):
if (n==0):
return 1
else:
return n*factorial(n-1)
Do I have to use `self.factorial(n-1)`? ( I guess, I should because PyDev is
showing unidentified variable when I don't). Why is the reference to the
object itself is needed in this case? Am I missing some important thing I
should understand here.
Answer: `factorial` in your first example is a global function. The fact that you call
it recursively, does not change that you still first need to look up the
function object to be able to call it.
In other words, the current function being called is not in any way special.
`factorial` is still a name that needs to be dereferenced, and it doesn't
matter that that name happens to reference to the function being executed.
Thus, in your second example, where `factorial` is instead a method, there is
no global reference to that method. Instead, you find it like any other method
on the class, through the `self` reference.
When you define a function, Python stores a reference to that new function
object in the name you gave it, in the current scope. In a global scope that
means that `def foo()` becomes a global name `foo` bound to a function object.
You can _break_ recursion by removing that name:
>>> def foo(): return foo() # infinite recursion
...
>>> def foo(): return foo() # infinite recursion
...
>>> foo
<function foo at 0x108e4b500>
>>> bar = foo
>>> del foo
>>> foo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined
>>> bar
<function foo at 0x108e4b500>
>>> bar()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in foo
NameError: global name 'foo' is not defined
Note the `NameError` here; I deleted `foo` from the global namespace, but
still have a reference in `bar`, which I can call. But the function itself,
when executed, cannot find the global name `foo`.
Python functions otherwise, have no reference to themselves. From _inside_ the
function, you cannot retrieve the function object itself, not reliably. The
best you can do is get the original function name:
>>> def foo():
... return sys._getframe(0).f_code.co_name
...
>>> foo()
'foo'
>>> bar = foo
>>> bar()
'foo'
but that does not give you a guarantee that you can still access that function
object through that name.
|
Import csv as list of list in python 3.3
Question: i hav a list of list with 2 strings and 1 integer
list_of_ee = [["a","m",15],["w","p",34]]
i export this to csv file using this code.
import csv
myfile = open("pppp.csv", 'wb')
with open("pppp.csv", "w",newline='') as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_NONE)
wr.writerows(list_of_ee)
result was
a m 15
w p 34
and i export that using this code
data = csv.reader(open('pppp.csv','r', newline=''))
data = list(data)
print(data)
and the result was
[['a', 'm', '15'], ['w', 'p', '34']]
but I want to import this results same as it was (as list of list and with 2
str and 1 integer)(when my program restart)in `list_of_ee` and I want to add
them to `list_of_ee` (becoz when program starts there's no data in
`list_of_ee` .
Answer: If you use CSV, you get strings. See the documentation:
<http://docs.python.org/2/library/csv.html#module-contents>
"No automatic data type conversion is performed."
@hcwhsa pointed you to an answer that shows how to use `ast.literal_eval()` to
guess at the types. It's not too hard:
import ast
import csv
def convert_type(s):
try:
return ast.literal_eval(s)
except (ValueError, SyntaxError):
return s
def convert_csv_row(lst):
return [convert_type(x) for x in lst]
data = csv.reader(open('pppp.csv','r', newline=''))
converted = [convert_csv_row(row) for row in data]
print(converted)
But really, why are you even using CSV if you want to preserve the types?
Unless you are exporting data to a spreadsheet or something, I suggest you use
JSON format.
import json
list_of_ee = [["a","m",15],["w","p",34]]
with open("test.json", "wt") as f:
f.write(json.dumps(list_of_ee))
with open("test.json", "rt") as f:
s = f.read()
lst = json.loads(s)
print(lst)
assert list_of_ee == lst
JSON is a great way to export data to other programs.
But if you are just trying to save data for your own Python programs, it's
even easier: just use `pickle`. <http://docs.python.org/2/library/pickle.html>
import pickle
list_of_ee = [["a","m",15],["w","p",34]]
with open("test.pickle", "wb") as f:
f.write(pickle.dumps(list_of_ee))
with open("test.pickle", "rb") as f:
bytes_data = f.read()
lst = pickle.loads(bytes_data)
print(lst)
assert list_of_ee == lst
With `pickle` you need to write and read the file in binary mode, not text
mode. Also with `pickle` you can save pretty much any Python native type, not
just the basic ones supported by JSON. But pretty much only Python programs
read a `pickle` file.
|
Performance bottleneck in creating network with igraph in Python
Question: I am trying to create a huge network using the igraph python module. I am
iterating trough a list of dictionaries in the following format:
d1={'el1':2, 'el3':4, ...,'el12':32}
d2={'el3':5, 'el4':6, ...,'el12':21}
The network is created in the following way: every node is one of the keys of
the dictionaries that has an attribute that represents the sum of all the
values of the node (for example, it would be 9 for el3 considering the two
given dictionaries), and there is an edge between two nodes if they appear
together in the same dictionary, with a weight attribute equal to the number
of times they appear together (for instance it would be 2 for el3 and el12, as
they appear together in 2 dictionaries).
I am using the following loop to create the network, where 'item' is a
dictionary as the one described before. To be clear I have about 12.000
elements to analyze
g = ig.Graph()
for el in news_db:
item = dict(news_db.get(el))['commenters']
print count
count = count + 1
for user in item:
try:
g.vs.find(user)['comment'] = g.vs.find(user)['comment'] + 1
except:
g.add_vertex(user)
g.vs.find(user)['comment'] = 1
for source, target in itertools.combinations(item.keys(), 2):
source_id = g.vs.find(source).index
target_id = g.vs.find(target).index
if g.are_connected(source_id,target_id):
edge_id = g.get_eid(source_id,target_id)
g.es[edge_id]['weight'] = g.es[edge_id]['weight'] + 1
else:
g.add_edge(source_id,target_id,weight=1)
The problem is that the speed of this procedure is really slow. It takes about
23 seconds to cycle trough the first 25 elements and the loop execution time
gets worse as time passes. I have used a profiling tool and I've found out
that 97% of the time is spent in the 'add_edge' function. Am I using igraph at
its best? Is there the possibility of lowering this execution time?
To be clear, I have also an alternative networkx version, that takes about 3
minutes the create the graph. In that case the problem is that the procedure
for saving the graph to disk takes too much memory and my laptop freezes.
Besides I though that analyzing the graph with networkx would be really slow,
given its pure Python implementation, so I decided to switch directly to
igraph to solve both problems.
Answer: [Look here](http://stackoverflow.com/questions/13974279/igraph-why-is-add-
edge-function-so-slow-ompared-to-add-edges) for reasons why add_edge is so
slow.
Moreover, it seems that you do things very unefficently. It would be better to
collect all necessary data before instantiating a graph, instead of performing
so many updates. There is a `collections.Counter` class for those purposes:
import collections
import itertools
news_db = [{'el1':2, 'el3':4, 'el12':32},
{'el3':5, 'el4':6, 'el12':21}]
vertices = collections.Counter()
edges = collections.Counter()
for item in news_db:
vertices.update(**item)
edges.update(itertools.combinations(item.keys(), 2))
print vertices
print edges
outputs desired vertices and edges sets
Counter({'el12': 53, 'el3': 9, 'el4': 6, 'el1': 2})
Counter({('el3', 'el12'): 2, ('el3', 'el4'): 1, ('el3', 'el1'): 1, ('el1', 'el12'): 1, ('el12', 'el4'): 1})
and you can instantiate graph using them
|
datetime.date creating many problems with set_index, groupby, and apply in Pandas 0.8.1
Question: I'm using Pandas 0.8.1 in an environment where it is not possible to upgrade
for bureaucratic reasons.
You may want to skip down to the "simplified problem" section below, before
reading all about the initial problem and my goal.
My goal: group a DataFrame by a categorical column "D", and then for each
group, sort by a date column "dt", set the index to "dt", perform a rolling
OLS regression, and return the DataFrame `beta` of regression coefficients
indexed by date.
The end result would hopefully be a bunch of stacked `beta` frames, each one
unique to some specific categorical variable, so that the final index would be
two levels, one for category ID and one for date.
If I do something like
my_dataframe.groupby("D").apply(some_wrapped_OLS_caller)
then I am getting frustratingly uninformative `KeyError: 0` errors often, and
the tracebacks seems to be choking on datetime issues:
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/core/frame.pyc in set_index(self, keys, drop, inplace, verify_integrity)
2287 arrays.append(level)
2288
-> 2289 index = MultiIndex.from_arrays(arrays, names=keys)
2290
2291 if verify_integrity and not index.is_unique:
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/core/index.pyc in from_arrays(cls, arrays, sortorder, names)
1505 if len(arrays) == 1:
1506 name = None if names is None else names[0]
-> 1507 return Index(arrays[0], name=name)
1508
1509 cats = [Categorical.from_array(arr) for arr in arrays]
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/core/index.pyc in __new__(cls, data, dtype, copy, name)
102 if dtype is None:
103 if (lib.is_datetime_array(subarr)
--> 104 or lib.is_datetime64_array(subarr)
105 or lib.is_timestamp_array(subarr)):
106 from pandas.tseries.index import DatetimeIndex
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/lib.so in pandas.lib.is_datetime64_array (pandas/src/tseries.c:90291)()
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/core/series.pyc in __getitem__(self, key)
427 def __getitem__(self, key):
428 try:
--> 429 return self.index.get_value(self, key)
430 except InvalidIndexError:
431 pass
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/core/index.pyc in get_value(self, series, key)
639 """
640 try:
--> 641 return self._engine.get_value(series, key)
642 except KeyError, e1:
643 if len(self) > 0 and self.inferred_type == 'integer':
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/lib.so in pandas.lib.IndexEngine.get_value (pandas/src/tseries.c:103842)()
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/lib.so in pandas.lib.IndexEngine.get_value (pandas/src/tseries.c:103670)()
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/lib.so in pandas.lib.IndexEngine.get_loc (pandas/src/tseries.c:104379)()
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/lib.so in pandas.lib.Int64HashTable.get_item (pandas/src/tseries.c:15547)()
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/lib.so in pandas.lib.Int64HashTable.get_item (pandas/src/tseries.c:15501)()
KeyError: 0
If I perform the regression steps manually on each group in the group-by
object, one by one, everything works without a hitch.
**Code:**
import numpy as np
import pandas
import datetime
from dateutil.relativedelta import relativedelta as drr
def foo(zz):
zz1 = zz.sort("dt", ascending=True).set_index("dt")
r1 = pandas.ols(y=zz1["y1"], x=zz1["x"], window=60, min_periods=12)
return r1.beta
dfrm_test = pandas.DataFrame({"x":np.random.rand(731),
"y1":np.random.rand(731),
"y2":np.random.rand(731),
"z":np.random.rand(731)})
dfrm_test['d'] = np.random.randint(0,2, size= (len(dfrm_test),))
dfrm_test['dt'] = [datetime.date(2000, 1, 1) + drr(days=i)
for i in range(len(dfrm_test))]
Now here is what happens when I try to work with these using `groupby` and
`apply`:
In [102]: dfrm_test.groupby("d").apply(foo)
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-102-345a8d45df50> in <module>()
----> 1 dfrm_test.groupby("d").apply(foo)
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/core/groupby.pyc in apply(self, func, *args, **kwargs)
267 applied : type depending on grouped object and function
268 """
--> 269 return self._python_apply_general(func, *args, **kwargs)
270
271 def aggregate(self, func, *args, **kwargs):
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/core/groupby.pyc in _python_apply_general(self, func, *args, **kwargs)
402 group_axes = _get_axes(group)
403
--> 404 res = func(group, *args, **kwargs)
405
406 if not _is_indexed_like(res, group_axes):
<ipython-input-101-8b9184c63365> in foo(zz)
1 def foo(zz):
----> 2 zz1 = zz.sort("dt", ascending=True).set_index("dt")
3 r1 = pandas.ols(y=zz1["y1"], x=zz1["x"], window=60, min_periods=12)
4 return r1.beta
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/core/frame.pyc in set_index(self, keys, drop, inplace, verify_integrity)
2287 arrays.append(level)
2288
-> 2289 index = MultiIndex.from_arrays(arrays, names=keys)
2290
2291 if verify_integrity and not index.is_unique:
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/core/index.pyc in from_arrays(cls, arrays, sortorder, names)
1505 if len(arrays) == 1:
1506 name = None if names is None else names[0]
-> 1507 return Index(arrays[0], name=name)
1508
1509 cats = [Categorical.from_array(arr) for arr in arrays]
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/core/index.pyc in __new__(cls, data, dtype, copy, name)
102 if dtype is None:
103 if (lib.is_datetime_array(subarr)
--> 104 or lib.is_datetime64_array(subarr)
105 or lib.is_timestamp_array(subarr)):
106 from pandas.tseries.index import DatetimeIndex
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/lib.so in pandas.lib.is_datetime64_array (pandas/src/tseries.c:90291)()
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/core/series.pyc in __getitem__(self, key)
427 def __getitem__(self, key):
428 try:
--> 429 return self.index.get_value(self, key)
430 except InvalidIndexError:
431 pass
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/core/index.pyc in get_value(self, series, key)
639 """
640 try:
--> 641 return self._engine.get_value(series, key)
642 except KeyError, e1:
643 if len(self) > 0 and self.inferred_type == 'integer':
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/lib.so in pandas.lib.IndexEngine.get_value (pandas/src/tseries.c:103842)()
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/lib.so in pandas.lib.IndexEngine.get_value (pandas/src/tseries.c:103670)()
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/lib.so in pandas.lib.IndexEngine.get_loc (pandas/src/tseries.c:104379)()
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/lib.so in pandas.lib.Int64HashTable.get_item (pandas/src/tseries.c:15547)()
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/lib.so in pandas.lib.Int64HashTable.get_item (pandas/src/tseries.c:15501)()
KeyError: 0
If I save the `groupby` object and attempt to apply `foo` myself, then in the
straightforward way, this also fails:
In [103]: grps = dfrm_test.groupby("d")
In [104]: for grp in grps:
foo(grp[1])
.....:
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-104-f215ff55c12b> in <module>()
1 for grp in grps:
----> 2 foo(grp[1])
3
<ipython-input-101-8b9184c63365> in foo(zz)
1 def foo(zz):
----> 2 zz1 = zz.sort("dt", ascending=True).set_index("dt")
3 r1 = pandas.ols(y=zz1["y1"], x=zz1["x"], window=60, min_periods=12)
4 return r1.beta
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/core/frame.pyc in set_index(self, keys, drop, inplace, verify_integrity)
2287 arrays.append(level)
2288
-> 2289 index = MultiIndex.from_arrays(arrays, names=keys)
2290
2291 if verify_integrity and not index.is_unique:
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/core/index.pyc in from_arrays(cls, arrays, sortorder, names)
1505 if len(arrays) == 1:
1506 name = None if names is None else names[0]
-> 1507 return Index(arrays[0], name=name)
1508
1509 cats = [Categorical.from_array(arr) for arr in arrays]
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/core/index.pyc in __new__(cls, data, dtype, copy, name)
102 if dtype is None:
103 if (lib.is_datetime_array(subarr)
--> 104 or lib.is_datetime64_array(subarr)
105 or lib.is_timestamp_array(subarr)):
106 from pandas.tseries.index import DatetimeIndex
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/lib.so in pandas.lib.is_datetime64_array (pandas/src/tseries.c:90291)()
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/core/series.pyc in __getitem__(self, key)
427 def __getitem__(self, key):
428 try:
--> 429 return self.index.get_value(self, key)
430 except InvalidIndexError:
431 pass
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/core/index.pyc in get_value(self, series, key)
639 """
640 try:
--> 641 return self._engine.get_value(series, key)
642 except KeyError, e1:
643 if len(self) > 0 and self.inferred_type == 'integer':
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/lib.so in pandas.lib.IndexEngine.get_value (pandas/src/tseries.c:103842)()
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/lib.so in pandas.lib.IndexEngine.get_value (pandas/src/tseries.c:103670)()
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/lib.so in pandas.lib.IndexEngine.get_loc (pandas/src/tseries.c:104379)()
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/lib.so in pandas.lib.Int64HashTable.get_item (pandas/src/tseries.c:15547)()
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/lib.so in pandas.lib.Int64HashTable.get_item (pandas/src/tseries.c:15501)()
KeyError: 0
But if I store off one of the group data frames, and then call `foo` on it,
_this works just fine_ ... ??
In [105]: for grp in grps:
x = grp[1]
.....:
In [106]: x.head()
Out[106]:
x y1 y2 z dt d
0 0.240858 0.235135 0.196027 0.940180 2000-01-01 1
1 0.115784 0.802576 0.870014 0.482418 2000-01-02 1
2 0.081640 0.939411 0.344041 0.846485 2000-01-03 1
5 0.608413 0.100349 0.306595 0.739987 2000-01-06 1
6 0.429635 0.678575 0.449520 0.362761 2000-01-07 1
In [107]: foo(x)
Out[107]:
<class 'pandas.core.frame.DataFrame'>
Index: 360 entries, 2000-01-17 to 2001-12-29
Data columns:
x 360 non-null values
intercept 360 non-null values
dtypes: float64(2)
What's going on here? Does it have to do with cases when the logic to trigger
conversion to bad date/time types is tripped? How can I work around it?
**Simplified Problem**
I can simplify the problem just to the `set_index` call within the `apply`
function. But this is getting really weird. Here's an example with a simpler
test DataFrame, just with `set_index`.
In [154]: tdf = pandas.DataFrame(
{"dt":([datetime.date(2000,1,i+1) for i in range(12)] +
[datetime.date(2001,3,j+1) for j in range(13)]),
"d":np.random.randint(1,4,(25,)),
"x":np.random.rand(25)})
In [155]: tdf
Out[155]:
d dt x
0 1 2000-01-01 0.430667
1 3 2000-01-02 0.159652
2 1 2000-01-03 0.719015
3 1 2000-01-04 0.175328
4 3 2000-01-05 0.233810
5 3 2000-01-06 0.581176
6 1 2000-01-07 0.912615
7 1 2000-01-08 0.534971
8 3 2000-01-09 0.373345
9 1 2000-01-10 0.182665
10 1 2000-01-11 0.286681
11 3 2000-01-12 0.054054
12 3 2001-03-01 0.861348
13 1 2001-03-02 0.093717
14 2 2001-03-03 0.729503
15 1 2001-03-04 0.888558
16 1 2001-03-05 0.263055
17 1 2001-03-06 0.558430
18 3 2001-03-07 0.064216
19 3 2001-03-08 0.018823
20 3 2001-03-09 0.207845
21 2 2001-03-10 0.735640
22 2 2001-03-11 0.908427
23 2 2001-03-12 0.819994
24 2 2001-03-13 0.798267
`set_index` works fine here, no date changing or anything.
In [156]: tdf.set_index("dt")
Out[156]:
d x
dt
2000-01-01 1 0.430667
2000-01-02 3 0.159652
2000-01-03 1 0.719015
2000-01-04 1 0.175328
2000-01-05 3 0.233810
2000-01-06 3 0.581176
2000-01-07 1 0.912615
2000-01-08 1 0.534971
2000-01-09 3 0.373345
2000-01-10 1 0.182665
2000-01-11 1 0.286681
2000-01-12 3 0.054054
2001-03-01 3 0.861348
2001-03-02 1 0.093717
2001-03-03 2 0.729503
2001-03-04 1 0.888558
2001-03-05 1 0.263055
2001-03-06 1 0.558430
2001-03-07 3 0.064216
2001-03-08 3 0.018823
2001-03-09 3 0.207845
2001-03-10 2 0.735640
2001-03-11 2 0.908427
2001-03-12 2 0.819994
2001-03-13 2 0.798267
`groupby` cannot successfully `set_index` though (note it errors before
hitting any unpacking problems with incongruent sizes, it just cannot reset
indices at all).
In [157]: tdf.groupby("d").apply(lambda x: x.set_index("dt"))
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-157-cf2d3964f4d3> in <module>()
----> 1 tdf.groupby("d").apply(lambda x: x.set_index("dt"))
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/core/groupby.pyc in apply(self, func, *args, **kwargs)
267 applied : type depending on grouped object and function
268 """
--> 269 return self._python_apply_general(func, *args, **kwargs)
270
271 def aggregate(self, func, *args, **kwargs):
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/core/groupby.pyc in _python_apply_general(self, func, *args, **kwargs)
402 group_axes = _get_axes(group)
403
--> 404 res = func(group, *args, **kwargs)
405
406 if not _is_indexed_like(res, group_axes):
<ipython-input-157-cf2d3964f4d3> in <lambda>(x)
----> 1 tdf.groupby("d").apply(lambda x: x.set_index("dt"))
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/core/frame.pyc in set_index(self, keys, drop, inplace, verify_integrity)
2287 arrays.append(level)
2288
-> 2289 index = MultiIndex.from_arrays(arrays, names=keys)
2290
2291 if verify_integrity and not index.is_unique:
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/core/index.pyc in from_arrays(cls, arrays, sortorder, names)
1505 if len(arrays) == 1:
1506 name = None if names is None else names[0]
-> 1507 return Index(arrays[0], name=name)
1508
1509 cats = [Categorical.from_array(arr) for arr in arrays]
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/core/index.pyc in __new__(cls, data, dtype, copy, name)
102 if dtype is None:
103 if (lib.is_datetime_array(subarr)
--> 104 or lib.is_datetime64_array(subarr)
105 or lib.is_timestamp_array(subarr)):
106 from pandas.tseries.index import DatetimeIndex
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/lib.so in pandas.lib.is_datetime64_array (pandas/src/tseries.c:90291)()
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/core/series.pyc in __getitem__(self, key)
427 def __getitem__(self, key):
428 try:
--> 429 return self.index.get_value(self, key)
430 except InvalidIndexError:
431 pass
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/core/index.pyc in get_value(self, series, key)
639 """
640 try:
--> 641 return self._engine.get_value(series, key)
642 except KeyError, e1:
643 if len(self) > 0 and self.inferred_type == 'integer':
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/lib.so in pandas.lib.IndexEngine.get_value (pandas/src/tseries.c:103842)()
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/lib.so in pandas.lib.IndexEngine.get_value (pandas/src/tseries.c:103670)()
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/lib.so in pandas.lib.IndexEngine.get_loc (pandas/src/tseries.c:104379)()
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/lib.so in pandas.lib.Int64HashTable.get_item (pandas/src/tseries.c:15547)()
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/lib.so in pandas.lib.Int64HashTable.get_item (pandas/src/tseries.c:15501)()
KeyError: 0
**Very weird part**
Here I save off the group objects, and try to manually call `set_index` on
them. This doesn't work. Even if I save out the specific DataFrame element
from the group, it does not work.
In [159]: grps = tdf.groupby("d")
In [160]: grps
Out[160]: <pandas.core.groupby.DataFrameGroupBy at 0x7600bd0>
In [161]: grps_list = [(x,y) for x,y in grps]
In [162]: grps_list[2][1].set_index("dt")
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-162-77f985a6e063> in <module>()
----> 1 grps_list[2][1].set_index("dt")
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/core/frame.pyc in set_index(self, keys, drop, inplace, verify_integrity)
2287 arrays.append(level)
2288
-> 2289 index = MultiIndex.from_arrays(arrays, names=keys)
2290
2291 if verify_integrity and not index.is_unique:
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/core/index.pyc in from_arrays(cls, arrays, sortorder, names)
1505 if len(arrays) == 1:
1506 name = None if names is None else names[0]
-> 1507 return Index(arrays[0], name=name)
1508
1509 cats = [Categorical.from_array(arr) for arr in arrays]
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/core/index.pyc in __new__(cls, data, dtype, copy, name)
102 if dtype is None:
103 if (lib.is_datetime_array(subarr)
--> 104 or lib.is_datetime64_array(subarr)
105 or lib.is_timestamp_array(subarr)):
106 from pandas.tseries.index import DatetimeIndex
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/lib.so in pandas.lib.is_datetime64_array (pandas/src/tseries.c:90291)()
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/core/series.pyc in __getitem__(self, key)
427 def __getitem__(self, key):
428 try:
--> 429 return self.index.get_value(self, key)
430 except InvalidIndexError:
431 pass
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/core/index.pyc in get_value(self, series, key)
639 """
640 try:
--> 641 return self._engine.get_value(series, key)
642 except KeyError, e1:
643 if len(self) > 0 and self.inferred_type == 'integer':
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/lib.so in pandas.lib.IndexEngine.get_value (pandas/src/tseries.c:103842)()
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/lib.so in pandas.lib.IndexEngine.get_value (pandas/src/tseries.c:103670)()
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/lib.so in pandas.lib.IndexEngine.get_loc (pandas/src/tseries.c:104379)()
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/lib.so in pandas.lib.Int64HashTable.get_item (pandas/src/tseries.c:15547)()
/opt/epd/7.3-2_pandas0.8.1/lib/python2.7/site-packages/pandas/lib.so in pandas.lib.Int64HashTable.get_item (pandas/src/tseries.c:15501)()
KeyError: 0
_But if I construct a manual direct copy of the group's DataFrame,
then`set_index` **does** work on the manual reconstruction??_
In [163]: grps_list[2][1]
Out[163]:
d dt x
1 3 2000-01-02 0.159652
4 3 2000-01-05 0.233810
5 3 2000-01-06 0.581176
8 3 2000-01-09 0.373345
11 3 2000-01-12 0.054054
12 3 2001-03-01 0.861348
18 3 2001-03-07 0.064216
19 3 2001-03-08 0.018823
20 3 2001-03-09 0.207845
In [165]: recreation = pandas.DataFrame(
{"d":[3,3,3,3,3,3,3,3,3],
"dt":[datetime.date(2000,1,2), datetime.date(2000,1,5), datetime.date(2000,1,6),
datetime.date(2000,1,9), datetime.date(2000,1,12), datetime.date(2001,3,1),
datetime.date(2001,3,7), datetime.date(2001,3,8), datetime.date(2001,3,9)],
"x":[0.159, 0.233, 0.581, 0.3733, 0.054, 0.861, 0.064, 0.0188, 0.2078]})
In [166]: recreation
Out[166]:
d dt x
0 3 2000-01-02 0.1590
1 3 2000-01-05 0.2330
2 3 2000-01-06 0.5810
3 3 2000-01-09 0.3733
4 3 2000-01-12 0.0540
5 3 2001-03-01 0.8610
6 3 2001-03-07 0.0640
7 3 2001-03-08 0.0188
8 3 2001-03-09 0.2078
In [167]: recreation.set_index("dt")
Out[167]:
d x
dt
2000-01-02 3 0.1590
2000-01-05 3 0.2330
2000-01-06 3 0.5810
2000-01-09 3 0.3733
2000-01-12 3 0.0540
2001-03-01 3 0.8610
2001-03-07 3 0.0640
2001-03-08 3 0.0188
2001-03-09 3 0.2078
As the pirates might say in the first few episodes of Archer Season 3: What
hell damn guy?
Answer: Turns out this is based on something that happens in `groupby` which changes
indices of the groups into a MultiIndex.
By adding a call to reset the index inside of the function to be applied with
`apply`, it gets rid of the problem:
def foo(zz):
zz1 = zz.sort("dt", ascending=True).reset_index().set_index("dt", inplace=True)
r1 = pandas.ols(y=zz1["y1"], x=zz1["x"], window=60, min_periods=12)
return r1.beta
and this at least provides a workaround.
|
Python Beautiful Soup parsing a UTF-8 coded table (using mechanize)
Question: I'm trying to parse the following table, coded in UTF-8 (this is part of it):
<table cellspacing="0" cellpadding="3" border="0" id="ctl00_SPWebPartManager1_g_c001c0d9_0cb8_4b0f_b75a_7cc3b6f7d790_ctl00_HistoryData1_gridHistoryData_DataGrid1" style="width:100%;border-collapse:collapse;">
<tr class="gridHeader" valign="top">
<td class="titleGridRegNoB" align="center" valign="top"><span dir=RTL>שווי שוק (אלפי ש"ח)</span></td><td class="titleGridReg" align="center" valign="top">הון רשום למסחר</td><td class="titleGridReg" align="center" valign="top">שער נמוך</td><td class="titleGridReg" align="center" valign="top">שער גבוה</td><td class="titleGridReg" align="center" valign="top">שער בסיס</td><td class="titleGridReg" align="center" valign="top">שער פתיחה</td><td class="titleGridReg" align="center" valign="top"><span dir="rtl">שער נעילה (באגורות)</span>
</td><td class="titleGridReg" align="center" valign="top">שער נעילה מתואם</td><td class="titleGridReg" align="center" valign="top">תאריך</td>
</tr><tr onmouseover="this.style.backgroundColor='#FDF1D7'" onmouseout="this.style.backgroundColor='#ffffff'">
My code is:
html = br.response().read().decode('utf-8')
soup = BeautifulSoup(html)
table_id = "ctl00_SPWebPartManager1_g_c001c0d9_0cb8_4b0f_b75a_7cc3b6f7d790_ctl00_HistoryData1_gridHistoryData_DataGrid1"
table = soup.findall("table", id=table_id)
And I'm getting the following error:
TypeError: 'NoneType' object is not callable
Answer: Since you are just finding using an `id`, you can just use `id` and nothing
else, because `id`s are unique:
## UPDATE
Using your paste:
# encoding=utf-8
from bs4 import BeautifulSoup
import requests
data = requests.get('https://dpaste.de/EWCK/raw/')
soup = BeautifulSoup(data.text)
print soup.find("table",
id="ctl00_SPWebPartManager1_g_c001c0d9_0cb8_4b0f_b75a_7cc3b6f7d790_ctl00_HistoryData1_gridHistoryData_DataGrid1")
I'm using python requests to get the data from a webpage, its same as as you
trying to get the data. The above code works, and the correct ID is given. Try
this for a change, don't use `.decode('utf-8')`, instead, just use
`br.response().read()`.
|
Rules from accented letters to ascii ones
Question: Is there a rule that helps to find the UTF-8 codes of all accented letters
associated to an ascii one ? For example, can I have all the UTF-8 codes all
the accented letters `é`, `è`,... from the UTF-8 code of the letter `e`?
## Here is a showcase in Python 3 using the solution given above by Ramchandra
Apte
import unicodedata
def accented_letters(letter):
accented_chars = []
for accent_type in "acute", "double acute", "grave", "double grave":
try:
accented_chars.append(
unicodedata.lookup(
"Latin small letter {letter} with {accent_type}" \
.format(**vars())
)
)
except KeyError:
pass
return accented_chars
print(accented_letters("e"))
for kind in ["NFC", "NFKC", "NFD", "NFKD"]:
print(
'---',
kind,
list(unicodedata.normalize(kind,"é")),
sep = "\n"
)
for oneChar in "βεέ.¡¿?ê":
print(
'---',
oneChar,
unicodedata.name(oneChar),
# [Find characters that are similar glyphically in
Unicode?](http://stackoverflow.com/questions/4846365/find-characters-that-are-
similar-glyphically-in-unicode?answertab=votes#tab-top)
unicodedata.normalize('NFD', oneChar).encode('ascii','ignore'),
sep = "\n"
)
The corresponding output.
['é', 'è', 'ȅ']
---
NFC
['é']
---
NFKC
['é']
---
NFD
['e', '́']
---
NFKD
['e', '́']
---
β
GREEK SMALL LETTER BETA
b''
---
ε
GREEK SMALL LETTER EPSILON
b''
---
έ
GREEK SMALL LETTER EPSILON WITH TONOS
b''
---
.
FULL STOP
b'.'
---
¡
INVERTED EXCLAMATION MARK
b''
---
¿
INVERTED QUESTION MARK
b''
---
?
QUESTION MARK
b'?'
---
ê
LATIN SMALL LETTER E WITH CIRCUMFLEX
b'e'
## Technical informations about UTF-8 (reference given by cjc343)
<http://tools.ietf.org/html/rfc3629>
Answer: They're often supposed to be distinct characters in many languages. However if
you really need this, you will want to find a function that normalizes
strings. In thus case you will want to normalize to get decomposed characters
where these become two Unicode code points in the string.
|
Gtk MenuBar kills MenuItems after the pointer hovers over them
Question: I have a plain `gtk.MenuBar` frame below. Whenever the mouse hovers over an
item, and that submenu is hidden due to lost focus, upon revisiting that
submenu, all items are lost.
The expected behavior is that the menu items re-appear in the order they were
added to their menus and submenus each time 'File', 'Game' and 'Help' are
activated with the pointer.
What is the cause of this perceived bug? Does the `gtk.MenuBar` require more
"implementing" to function properly?
The undesired result is illustrated below:
 
#!/usr/bin/python
import gtk
def callbackz(*argv):
print str(*argv)
class ChessMenuBar(gtk.MenuBar):
def __init__(self):
super(ChessMenuBar, self).__init__()
menu_file = gtk.Menu()
item_open = gtk.MenuItem('Open')
item_save = gtk.MenuItem('Save')
item_quit = gtk.MenuItem('Quit')
menu_file.append(item_open)
menu_file.append(item_save)
menu_file.append(item_quit)
menu_game = gtk.Menu()
item_newg = gtk.MenuItem('Star New Game')
menu_game.append(item_newg)
menu_help = gtk.Menu()
item_help = gtk.MenuItem('Help')
menu_help.append(item_help)
# -- main categories
item_file = gtk.MenuItem('File')
item_game = gtk.MenuItem('Game')
item_help = gtk.MenuItem('Help')
item_file.set_submenu(menu_file)
item_game.set_submenu(menu_game)
item_help.set_submenu(menu_help)
self.append(item_file)
self.append(item_game)
self.append(item_help)
for _ in [ item_file, item_game, item_help,
item_help, item_newg, item_open,
item_quit, item_save]:
_.connect('activate', callbackz)
class PyApp(gtk.Window):
def __init__(self):
super(PyApp, self).__init__()
self.set_title("Simple menu")
self.set_size_request(250, 200)
self.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color(6400, 6400, 6440))
self.set_position(gtk.WIN_POS_CENTER)
mb = ChessMenuBar()
vbox = gtk.VBox(False, 2)
vbox.pack_start(mb, False, False, 0)
self.add(vbox)
self.connect("destroy", gtk.main_quit)
self.show_all()
PyApp()
gtk.main()
* * *
$ winPython --version
Python 2.7.3
$ cat /cygdrive/c/Python27/Lib/site-packages/gtk-2.0/pygtk-2.22.0-py2.7.egg-info
Metadata-Version: 1.1
Name: pygtk
Version: 2.22.0
( abbreviated )
Platform: MS Windows
Requires: pycairo (>=1.0.2)
Requires: pygobject (>=2.21.3)
Provides: p
Provides: y
Provides: g
Provides: t
Provides: k
Answer: Does it help if you store the menu items somewhere, e.g. in `self`, by
replacing
item_open = gtk.MenuItem('Open')
with
self.item_open = gtk.MenuItem('Open')
(and similarly for the other menu items)?
I don't know PyGTK that well, but I suspect that it creates Python objects
that correspond to GTK menu-item objects/structures. These Python objects
might be getting garbage collected at the end of the constructor, and when
they get garbage collected, they might delete the underlying GTK C/C++ object.
My suspicions are that the menu items are disappearing because they are
getting deleted.
By storing the Python objects, you're preventing them from being garbage
collected, which should prevent the corresponding C/C++ objects from being
deleted.
This is speculation, however; I haven't tested your code to verify that this
suggestion works, so I could be completely wrong.
|
Is there a way to clear your printed text in python?
Question: Hello guys I have wanted for a long time to find out how to clear something
like print("example") in python, but I cant seem to find anyway or figure
anything out.
print("Hey")
>Hey
Now I need to clear it, and write some new text.
print("How is your day?")
It would print.
> Hey
>How is your day?
But I want to clear the "Hey" so the user shouldnt look at both at same time,
and it looks kinda messy.
Answer:
import os
os.system('cls')
Or `os.system('clear')` on unix (mac and linux). If you don't want the scroll
up either, then you _can_ do this:
`os.system("printf '\033c'")` should get rid of scroll back too. Something
that works on all systems:
import os
os.system('cls' if os.name == 'nt' else "printf '\033c'")
|
How to send a stream with python fabric
Question: I need to send the stdout stream of a program across a network, to the stdin
of another program, running on another host.
This can be easily accomplished using ssh:
program 1 | ssh host 'program 2'
It's trivial to call this using `subprocess`:
subprocess.call("program 1 | ssh host 'program 2'", shell=True)
However, since I need to run many other commands on the remote host, I'm using
[fabric](http://fabfile.org).
Sending files with fabric is easy enough, but I can't find any documentation
on sending streams. I know fabric uses the paramiko ssh library, so I could
[use it's channel](http://stackoverflow.com/questions/2554292/how-to-send-eof-
to-stdin-in-paramiko) but there seems to be no documentation for accessing the
channel from fabric.
Answer: I ended up digging through the fabric source code
(`fabric.operations._execute`) and came up this:
from fabric.state import default_channel
import subprocess
def remote_pipe(local_command, remote_command, buf_size=1024):
'''executes a local command and a remove command (with fabric), and
sends the local's stdout to the remote's stdin.
based on fabric.operations._execute'''
local_p= subprocess.Popen(local_command, shell=True, stdout=subprocess.PIPE)
channel= default_channel() #fabric function
channel.set_combine_stderr(True)
channel.exec_command( remote_command )
read_bytes= local_p.stdout.read(buf_size)
while read_bytes:
channel.sendall(read_bytes)
read_bytes= local_p.stdout.read(buf_size)
local_ret= local_p.wait()
channel.shutdown_write()
received= channel.recv(640*1024) #ought to be enough for everyone
remote_ret= channel.recv_exit_status()
if local_ret!=0 or remote_ret!=0:
raise Exception("remote_pipe failed: "+received)
|
Python lib execute error
Question: I made this python lib and it had this function with uses urllib and urllib2
but when i execute the lib's functions from python shell i get this error
>>> from sabermanlib import geturl
>>> geturl("roblox.com","ggg.html")
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
geturl("roblox.com","ggg.html")
File "sabermanlib.py", line 21, in geturl
urllib.urlretrieve(Address,File)
File "C:\Users\Andres\Desktop\ddd\Portable Python 2.7.5.1\App\lib\urllib.py", line 94, in urlretrieve
return _urlopener.retrieve(url, filename, reporthook, data)
File "C:\Users\Andres\Desktop\ddd\Portable Python 2.7.5.1\App\lib\urllib.py", line 240, in retrieve
fp = self.open(url, data)
File "C:\Users\Andres\Desktop\ddd\Portable Python 2.7.5.1\App\lib\urllib.py", line 208, in open
return getattr(self, name)(url)
File "C:\Users\Andres\Desktop\ddd\Portable Python 2.7.5.1\App\lib\urllib.py", line 463, in open_file
return self.open_local_file(url)
File "C:\Users\Andres\Desktop\ddd\Portable Python 2.7.5.1\App\lib\urllib.py", line 477, in open_local_file
raise IOError(e.errno, e.strerror, e.filename)
IOError: [Errno 2] The system cannot find the file specified: 'roblox.com'
>>>
and here's the code for the lib i made:
import urllib
import urllib2
def geturl(Address,File):
urllib.urlretrieve(Address,File)
EDIT 2
I cant understand why i get this error in the python shell executing:
geturl(Address,File)
Answer: You don't want urllib.urlretrieve. This takes a file-like object. Instead, you
want urllib.urlopen:
>>> help(urllib.urlopen)
urlopen(url, data=None, proxies=None)
Create a file-like object for the specified URL to read from.
Additionally, if you want to download and save a document, you'll need a more
robust geturl function:
def geturl(Address, FileName):
html_data = urllib.urlopen(Address).read() # Open the URL
with open(FileName, 'wb') as f: # Open the file
f.write(html_data) # Write data from URL to file
geturl(u'http://roblox.com') # URL's must contain the full URI, including http://
|
Play video using libVLC from memory in python
Question: I am trying to make use of libVLC python bindings to play files after reading
them into memory. I have the following code that reads a valid video file into
the memory. I need to now play the video directly from the memory.
import vlc
File1 = open('vid.webm','rb')
Axel = File1.read()
Now i need to play the contents in Axel, how can I do this.
Information on how to do this in C, Java etc too can help.
**Edit:** Understood I will have to use the imem module but can't find any
help regarding how to get it done.
Answer: to do this you have to use the
[imem](https://forum.videolan.org/viewtopic.php?f=32&t=93842) module of
libvlc. This can be really confusing since it is not a publicly documented API
right now. However, I followed a couple other posts related to this here and
on the VideoLan forums. Below is some example code I got working today in C++
that uses JPEG images loaded into memory to create a video stream. You can
follow the similar steps, but you'll just have to change the codec of your
data in memory (see imem-codec=RV24 line).
// Local file/media source.
std::string IMEM_SOURCE_FOLDER = "settings/rvideo/samples/bigdog";
class MyImemData
{
public:
MyImemData() : mFrame(0), mDts(0), mPts(0) {}
~MyImemData() {}
std::vector<cv::Mat> mImages;
std::size_t mFrame;
int64_t mDts;
int64_t mPts;
};
/**
\brief Callback method triggered by VLC to get image data from
a custom memory source. This is used to tell VLC where the
data is and to allocate buffers as needed.
To set this callback, use the "--imem-get=<memory_address>"
option, with memory_address the address of this function in memory.
When using IMEM, be sure to indicate the format for your data
using "--imem-cat=2" where 2 is video. Other options for categories are
0 = Unknown,
1 = Audio,
2 = Video,
3 = Subtitle,
4 = Data
When creating your media instance, use libvlc_media_new_location and
set the location to "imem:/" and then play.
\param[in] data Pointer to user-defined data, this is your data that
you set by passing the "--imem-data=<memory_address>" option when
initializing VLC instance.
\param[in] cookie A user defined string. This works the same way as
data, but for string. You set it by adding the "--imem-cookie=<your_string>"
option when you initialize VLC. Use this when multiple VLC instances are
running.
\param[out] dts The decode timestamp, value is in microseconds. This value
is the time when the frame was decoded/generated. For example, 30 fps
video would be every 33 ms, so values would be 0, 33333, 66666, 99999, etc.
\param[out] pts The presentation timestamp, value is in microseconds. This
value tells the receiver when to present the frame. For example, 30 fps
video would be every 33 ms, so values would be 0, 33333, 66666, 99999, etc.
\param[out] flags Unused,ignore.
\param[out] bufferSize Use this to set the size of the buffer in bytes.
\param[out] buffer Change to point to your encoded frame/audio/video data.
The codec format of the frame is user defined and set using the
"--imem-codec=<four_letter>," where 4 letter is the code for your
codec of your source data.
*/
int MyImemGetCallback (void *data,
const char *cookie,
int64_t *dts,
int64_t *pts,
unsigned *flags,
size_t * bufferSize,
void ** buffer)
{
MyImemData* imem = (MyImemData*)data;
if(imem == NULL)
return 1;
// Loop...
if(imem->mFrame >= imem->mImages.size())
{
imem->mFrame = 0;
}
// Changing this value will impact the playback
// rate on the receiving end (if they use the dts and pts values).
int64_t uS = 33333; // 30 fps
cv::Mat img = imem->mImages[imem->mFrame++];
*bufferSize = img.rows*img.cols*img.channels();
*buffer = img.data;
*dts = *pts = imem->mDts = imem->mPts = imem->mPts + uS;
return 0;
}
/**
\brief Callback method triggered by VLC to release memory allocated
during the GET callback.
To set this callback, use the "--imem-release=<memory_address>"
option, with memory_address the address of this function in memory.
\param[in] data Pointer to user-defined data, this is your data that
you set by passing the "--imem-data=<memory_address>" option when
initializing VLC instance.
\param[in] cookie A user defined string. This works the same way as
data, but for string. You set it by adding the "--imem-cookie=<your_string>"
option when you initialize VLC. Use this when multiple VLC instances are
running.
\param[int] bufferSize The size of the buffer in bytes.
\param[out] buffer Pointer to data you allocated or set during the GET
callback to handle or delete as needed.
*/
int MyImemReleaseCallback (void *data,
const char *cookie,
size_t bufferSize,
void * buffer)
{
// Since I did not allocate any new memory, I don't need
// to delete it here. However, if you did in your get method, you
// should delete/free it here.
return 0;
}
/**
\brief Method to load a series of images to use as raw image data
for the network stream.
\param[in] sourceFolder Path to folder containing jpeg or png images.
*/
std::vector<cv::Mat> GetRawImageData(const std::string& sourceFolder)
{
namespace fs = boost::filesystem;
std::vector<cv::Mat> result;
std::vector<std::string> filenames;
if( fs::exists(sourceFolder) && fs::is_directory(sourceFolder) )
{
for(fs::directory_iterator dir(sourceFolder);
dir != fs::directory_iterator();
dir++)
{
std::string ext = dir->path().extension().string();
if( fs::is_regular_file( dir->status() ) &&
(dir->path().extension() == ".jpeg" ||
dir->path().extension() == ".png") )
{
filenames.push_back(dir->path().string());
}
}
}
if(filenames.size() > 0)
{
// Sort from 0 to N
std::sort(filenames.begin(), filenames.end());
std::vector<std::string>::iterator filename;
for(filename = filenames.begin();
filename != filenames.end();
filename++)
{
cv::Mat img = cv::imread(*filename);
result.push_back(img);
}
}
return result;
}
int main(int argc, char* argv[])
{
// Load images first since we need to know
// the size of the image data for IMEM
MyImemData data;
data.mImages =
GetRawImageData(IMEM_SOURCE_FOLDER);
if(data.mImages.size() == 0)
{
std::cout << "No images found to render/stream.";
return 0;
}
int w, h, channels;
w = data.mImages.front().cols;
h = data.mImages.front().rows;
channels = data.mImages.front().channels();
// You must create an instance of the VLC Library
libvlc_instance_t * vlc;
// You need a player to play media
libvlc_media_player_t *mediaPlayer;
// Media object to play.
libvlc_media_t *media;
// Configure options for this instance of VLC (global settings).
// See VLC command line documentation for options.
std::vector<const char*> options;
std::vector<const char*>::iterator option;
options.push_back("--no-video-title-show");
char imemDataArg[256];
sprintf(imemDataArg, "--imem-data=%#p", &data);
options.push_back(imemDataArg);
char imemGetArg[256];
sprintf(imemGetArg, "--imem-get=%#p", MyImemGetCallback);
options.push_back(imemGetArg);
char imemReleaseArg[256];
sprintf(imemReleaseArg, "--imem-release=%#p", MyImemReleaseCallback);
options.push_back(imemReleaseArg);
options.push_back("--imem-cookie=\"IMEM\"");
// Codec of data in memory for IMEM, raw 3 channel RGB images is RV24
options.push_back("--imem-codec=RV24");
// Video data.
options.push_back("--imem-cat=2");
// If using RAW image data, like RGB24, then you
// must specify the width, height, and number of channels
// to IMEM. Other codes may have that information within
// the data buffer, but RAW will not.
char imemWidthArg[256];
sprintf(imemWidthArg, "--imem-width=%d", w);
options.push_back(imemWidthArg);
char imemHeightArg[256];
sprintf(imemHeightArg, "--imem-height=%d", h);
options.push_back(imemHeightArg);
char imemChannelsArg[256];
sprintf(imemChannelsArg, "--imem-channels=%d", channels);
options.push_back(imemChannelsArg);
//options.push_back("--verbose=2");
// Load the VLC engine
vlc = libvlc_new (int(options.size()), options.data());
// Create a media item from file
media = libvlc_media_new_location (vlc, "imem://");
// Configure any transcoding or streaming
// options for the media source.
options.clear();
// Stream as MPEG2 via RTSP
//options.push_back(":sout=#transcode{venc=ffmpeg{keyint=1,min-keyint=1,tune=zerolatency,bframes=0,vbv-bufsize=1200}, vcodec=mp2v,vb=800}:rtp{sdp=rtsp://:1234/BigDog}");
// Stream as MJPEG (Motion JPEG) to http destination. MJPEG encoder
// does not currently support RTSP
//options.push_back(":sout=#transcode{vcodec=MJPG,vb=800,scale=1,acodec=none}:duplicate{dst=std{access=http,mux=mpjpeg,noaudio,dst=:1234/BigDog.mjpg}");
// Convert to H264 and stream via RTSP
options.push_back(":sout=#transcode{vcodec=h264,venc=x264,vb=0,vbv-bufsize=1200,bframes=0,scale=0,acodec=none}:rtp{sdp=rtsp://:1234/BigDog}");
// Set media options
for(option = options.begin(); option != options.end(); option++)
{
libvlc_media_add_option(media, *option);
}
// Create a media player playing environment
mediaPlayer = libvlc_media_player_new_from_media (media);
// No need to keep the media now
libvlc_media_release (media);
// play the media_player
libvlc_media_player_play (mediaPlayer);
boost::this_thread::sleep(boost::posix_time::milliseconds(60000));
// Stop playing
libvlc_media_player_stop (mediaPlayer);
// Free the media_player
libvlc_media_player_release (mediaPlayer);
// Free vlc
libvlc_release (vlc);
return 0;
}
|
python: avoiding zip truncation of list
Question: I have the following python code that uses zip() and it seems to cause
unintended data truncation.
inc_data = [[u'Period Ending', u'Dec 31, 2012', u'Dec 31, 2011', u'Dec 31, 2010'],
[u'Total Revenue\n', u'104,507,100\n', u'106,916,100\n', u'99,870,100\n'],
[u'Cost of Revenue\n',u'56,000,000\n']
]
inc_data2 = zip(*inc_data)
for i in inc_data2:
print i
It only prints:
(u'Period Ending', u'Total Revenue\n', u'Cost of Revenue\n')
(u'Dec 31, 2012', u'104,507,100\n', u'56,000,000\n')
But I want it to print the following, but apparently I have to add in fillers
`u''` by hand in order to prevent zip() from truncating the inc_data. But I
don't know how to code that.
(u'Period Ending', u'Total Revenue\n', u'Cost of Revenue\n')
(u'Dec 31, 2012', u'104,507,100\n', u'56,000,000\n')
(u'Dec 31, 2011', u'106,916,100\n', u'')
(u'Dec 31, 2010', u'99,870,100\n', u'')
To describe inc_data above,
inc_data = [ [x],
[y],
[z] ]
How do I make x, y and z to be the same length? And the length is the max
length of x, y, or z?
(u'Period Ending', u'Total Revenue\n', u'Cost of Revenue\n')
(u'Dec 31, 2012', u'104,507,100\n', u'56,000,000\n')
(u'Dec 31, 2011', u'106,916,100\n', u'')
(u'Dec 31, 2010', u'99,870,100\n', u'')
Sorry for the lengthy and wordy explanation of the problem. Could you help me
or point me to a similar question that has been answered, if one exists? many
thanks!
Answer: Use
[izip_longest](http://docs.python.org/2/library/itertools.html#itertools.izip_longest):
from itertools import izip_longest
inc_data = [[u'Period Ending', u'Dec 31, 2012', u'Dec 31, 2011', u'Dec 31, 2010'],
[u'Total Revenue\n', u'104,507,100\n', u'106,916,100\n', u'99,870,100\n'],
[u'Cost of Revenue\n',u'56,000,000\n']
]
print list(izip_longest(*inc_data, fillvalue=u''))
# [(u'Period Ending', u'Total Revenue\n', u'Cost of Revenue\n'),
(u'Dec 31, 2012', u'104,507,100\n', u'56,000,000\n'),
(u'Dec 31, 2011', u'106,916,100\n', u''),
(u'Dec 31, 2010', u'99,870,100\n', u'')]
|
python structure JSON serializing issue
Question: I've got a cache dictionary that stores a 3-element list for each key:
`[value, date_created, hits]`. The cache communication is done via JSON. There
is a `items` command in the cache that shall return all items. This is the set
cache method:
@status
def handle_set(self, key, value):
self.data[key] = [value, datetime.datetime.now(), 0]
return
The problem occurs when I have a non-empty cache and I call `items` on it.
Python datetime object is not serializable:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/twisted/python/log.py", line 84, in callWithLogger
return callWithContext({"system": lp}, func, *args, **kw)
File "/usr/lib/python2.7/dist-packages/twisted/python/log.py", line 69, in callWithContext
return context.call({ILogContext: newCtx}, func, *args, **kw)
File "/usr/lib/python2.7/dist-packages/twisted/python/context.py", line 118, in callWithContext
return self.currentContext().callWithContext(ctx, func, *args, **kw)
File "/usr/lib/python2.7/dist-packages/twisted/python/context.py", line 81, in callWithContext
return func(*args,**kw)
--- <exception caught here> ---
File "/usr/lib/python2.7/dist-packages/twisted/internet/selectreactor.py", line 146, in _doReadOrWrite
why = getattr(selectable, method)()
File "/usr/lib/python2.7/dist-packages/twisted/internet/tcp.py", line 460, in doRead
rval = self.protocol.dataReceived(data)
File "./server.py", line 17, in dataReceived
result = getattr(self.factory, command)(**request)
File "./server.py", line 35, in execute
return json.dumps(result)
File "/usr/lib/python2.7/json/__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "/usr/lib/python2.7/json/encoder.py", line 201, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python2.7/json/encoder.py", line 264, in iterencode
return _iterencode(o, 0)
File "/usr/lib/python2.7/json/encoder.py", line 178, in default
raise TypeError(repr(o) + " is not JSON serializable")
exceptions.TypeError: datetime.datetime(2013, 10, 26, 11, 38, 42, 348094) is not JSON serializable
I have found a similar [SO
question](http://stackoverflow.com/questions/3768895/python-how-to-make-a-
class-json-serializable/15538391#15538391). But the thing I don't like in the
accepted answer is that I have to provide a custom serializer.
in my cache I have different commands, but I'd like to use one JSON-formatting
method for all cache commands. I'm afraid I'd have to do an if-cascade if I
were to follow that answer.
Is there any way to override `datetime.datetime` to provide one simple method
that will be used by JSON serializer? Or any better solution to this?
datetime.datetime JSON serialization could be as simple as `str(d)` for me (a
string representation).
Answer: The generally accepted approach is to subclass the default encoder.
import json
class CustomJSONEncoder(json.JSONEncoder):
def default(self, obj):
if hasattr(obj, 'isoformat'): #handles both date and datetime objects
return obj.isoformat()
elif hasattr(obj, 'total_seconds'): #handles both timedelta objects
return str(obj)
if isinstance(obj, Decimal): #handles decimal timedelta objects
return float(obj)
else:
return json.JSONEncoder.default(self, obj)
To use the new class:
context['my_json_data'] = json.dumps(my_python_data, cls=CustomJSONEncoder)
The issue is that there is no universally accepted way to represent a date, so
Python forces you to choose. While it can be frustrating, Python is forcing
you to accept the fact that any time you convert a date you're making a
choice.
|
Excel fails to open Python-generated CSV files
Question: I have many Python scripts that output CSV files. It is occasionally
convenient to open these files in Excel. After installing OS X Mavericks,
Excel no longer opens these files properly: Excel doesn't parse the files and
it duplicates the rows of the file until it runs out of memory. Specifically,
when Excel attempts to open the file, a prompt appears that reads: "File not
loaded completely."
Example of code I'm using to generate the CSV files:
import csv
with open('csv_test.csv', 'wb') as f:
writer = csv.writer(f)
writer.writerow([1,2,3])
writer.writerow([4,5,6])
Even the simple file generated by the above code fails to load in Excel.
However, if I open the CSV file in a text editor and copy/paste the text into
Excel, parse it with text to columns, and then save as CSV from Excel, then I
can reopen the CSV file in Excel without issue. Do I need to pass an
additional parameter in my scripts to make Excel parse the CSV files the same
way it used to? Or is there some setting I can change in OS X Mavericks or
Excel? Thanks.
Answer: Possible solution1: use *.txt instead of *.csv. In this case Excel (at least,
2010) will show you an import data wizard where you can specify delimiters,
character encoding, field types, etc.
UPD: Solution2: The python "csv" module has a "dialect" feature. For example,
the following modification of your code generates valid csv file for my
environment (Python 2.7, Excel 2010, Windows7, locale with ";" list
delimiters):
import csv
with open('csv_test2.csv', 'wb') as f:
csv.excel.delimiter=';'
writer = csv.writer(f, dialect=csv.excel)
writer.writerow([1,2,3])
writer.writerow([4,5,6])
|
interpolate python array to minimize maximum difference between elements
Question: What is a concise and readable way of interpolating a 1D array such that the
maximum difference between elements is minimized?
For instance, if I had the array [4 9 13 25] and I was allowed to add 1 more
number in order to minimize the maximum difference between elements I would
insert a 19 between 13 and 25 (max difference is now 6 rather than 12).
Of course a good ole' for loop will get it done, but for posterity is there a
less verbose approach than below?
# current array
nums = np.array([4.0, 9.0, 13.0, 25.0])
# size of new array
N=10
# recursively find max gap (difference) and fill it with a mid point
for k in range(N-len(nums)):
inds = range(len(nums))
# get the maximum difference between two elements
max_gap = np.argmax(np.diff(nums))
# put a new number that's equidistant from the two element values
new_num = np.interp(np.mean([inds[max_gap],inds[max_gap+1]]), inds, nums)
nums = np.insert(nums, max_gap+1, new_num)
print nums
This example interpolates the 1D array, filling regions where the greatest
difference was:
[ 4. 9. 13. 19. 25.]
[ 4. 9. 13. 16. 19. 25.]
[ 4. 9. 13. 16. 19. 22. 25.]
[ 4. 6.5 9. 13. 16. 19. 22. 25. ]
[ 4. 6.5 9. 11. 13. 16. 19. 22. 25. ]
[ 4. 6.5 9. 11. 13. 14.5 16. 19. 22. 25. ]
**edit 1:** As comments suggest, there is a trade-off between readability,
efficiency, and accuracy. Of these three attributes, for me the most important
is readability. I still give +1 for any and all improvements to my above
algorithm though since it is a general problem and any answer that improves
either of those three attributes is beneficial to someone if not me later on.
Answer: And, if you want efficiency for long arrays, even if the code is not as short,
I suggest:
nums = np.array([4., 9., 13., 25])
diffs = np.diff(nums)
N = 10
# Number of interpolation points proportional to length of gaps
new_points = diffs/sum(diffs) * (N-len(nums))
while sum(np.floor(new_points)) != N -len(nums): # from continuum to discrete
pos = np.argmax(new_points - np.floor(new_points))
new_points[pos] = np.floor(new_points[pos] + 1)
new_points = np.floor(new_points)
# Now we interpolate by inserting linspace values starting from the end to
# avoid the loop limits being spoiled when introducing values.
for ii in range(len(new_points))[::-1]:
#linspace includes borders
introduce_these = np.linspace(nums[ii], nums[ii+1], new_points[ii] + 2)[1:-1]
nums = np.insert(nums, ii+1, introduce_these)
That produces:
In [205]: print nums
[4. 5.66666667 7.33333333 9. 11. 13. 16. 19. 22. 25. ]
|
Pandas MultiIndex names not working
Question: The `axis 0` in the `IndexError` strikes me as odd. Where is my mistake?
It works if I do not rename the columns before setting the MultiIndex
(uncomment line `df = df.set_index([0, 1])` and comment the three above).
Tested with stable and dev versions.
I am fairly new to python and pandas so any other suggestions for improvement
are much appreciated.
import itertools
import datetime as dt
import numpy as np
import pandas as pd
from pandas.io.html import read_html
dfs = read_html('http://www.epexspot.com/en/market-data/auction/auction-table/2006-01-01/DE',
attrs={'class': 'list hours responsive'},
skiprows=1)
df = dfs[0]
hours = list(itertools.chain.from_iterable([[x, x] for x in range(1, 25)]))
df[0] = hours
df = df.rename(columns={0: 'a'})
df = df.rename(columns={1: 'b'})
df = df.set_index(['a', 'b'])
#df = df.set_index([0, 1])
today = dt.datetime(2006, 1, 1)
days = pd.date_range(today, periods=len(df.columns), freq='D')
colnames = [day.strftime(format='%Y-%m-%d') for day in days]
df.columns = colnames
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/user/Optional/pandas_stable_env/lib/python3.3/site-packages/pandas/core/frame.py", line 2099, in __setattr__
super(DataFrame, self).__setattr__(name, value)
File "properties.pyx", line 59, in pandas.lib.AxisProperty.__set__ (pandas/lib.c:29330)
File "/Users/user/Optional/pandas_stable_env/lib/python3.3/site-packages/pandas/core/generic.py", line 656, in _set_axis
self._data.set_axis(axis, labels)
File "/Users/user/Optional/pandas_stable_env/lib/python3.3/site-packages/pandas/core/internals.py", line 1039, in set_axis
block.set_ref_items(self.items, maybe_rename=maybe_rename)
File "/Users/user/Optional/pandas_stable_env/lib/python3.3/site-packages/pandas/core/internals.py", line 93, in set_ref_items
self.items = ref_items.take(self.ref_locs)
File "/Users/user/Optional/pandas_stable_env/lib/python3.3/site-packages/pandas/core/index.py", line 395, in take
taken = self.view(np.ndarray).take(indexer)
IndexError: index 7 is out of bounds for axis 0 with size 7
Answer: This is a very subtle bug. Going to be fixed by:
<https://github.com/pydata/pandas/pull/5345> in upcoming release 0.13 (very
shortly).
As a workaround, you can do this after then `set_index` but before the column
assignment
df = DataFrame(dict([ (c,col) for c, col in df.iteritems() ]))
The internal state of the frame was off; it is the renames followed by the
set_index which caused this, so this recreates it so you can work with it.
|
Python multiprocessing EOF error on csv files
Question: I am trying to implement a
[multiprocessing](http://docs.python.org/library/multiprocessing.html)
approach for reading and comparing two csv files. To get me started, I started
with the code example from [embarassingly parallel
problems](http://stackoverflow.com/questions/2359253/solving-embarassingly-
parallel-problems-using-python-multiprocessing/2364667#2364667), which sums
integers in a file. The problem is that the example will not run for me. (I am
running Python 2.6 on Windows.)
I get the following EOF error:
File "C:\Python26\lib\pickle.py", line 880, in load_eof
raise EOFError
EOFError
At this line:
self.pin.start()
I found some [examples](http://stackoverflow.com/questions/15719930/pickle-
load-method-raising-eoferror-in-read-mode-in-windows) that suggested the
problem might be the csv opening method needs to be 'rb'. I tried, but that
did not work either.
Then I tried to simplify the code to reproduce the error at the most basic
level. I got the same error, on the same line. Even when I simplified such
that the parse_input_csv function does not even read the file. (Not sure how
EOF is triggered if the file does not get read?)
import csv
import multiprocessing
class CSVWorker(object):
def __init__(self, infile, outfile):
#self.infile = open(infile)
self.infile = open(infile, 'rb') #try rb for Windows
self.in_csvfile = csv.reader(self.infile)
self.inq = multiprocessing.Queue()
self.pin = multiprocessing.Process(target=self.parse_input_csv, args=())
self.pin.start()
self.pin.join()
self.infile.close()
def parse_input_csv(self):
# for i, row in enumerate(self.in_csvfile):
# self.inq.put( (i, row) )
# for row in self.in_csvfile:
# print row
# #self.inq.put( row )
print 'yup'
if __name__ == '__main__':
c = CSVWorker('random_ints.csv', 'random_ints_sums.csv')
print 'done'
Finally, I tried pulling it all outside a Class. This works if I do not
iterate over the csv, but gives the same error if I do.
def manualCSVworker(infile, outfile):
f = open(infile, 'rb')
in_csvfile = csv.reader(f)
inq = multiprocessing.Queue()
# this works (no reading csv file)
pin = multiprocessing.Process(target=manual_parse_input_csv, args=(in_csvfile,))
# this does not work (tries to read csv, and fails with EOFError)
#pin = multiprocessing.Process(target=print_yup, args=())
pin.start()
pin.join()
f.close()
def print_yup():
print 'yup'
def manual_parse_input_csv(csvReader):
for row in csvReader:
print row
if __name__ == '__main__':
manualCSVworker('random_ints.csv', 'random_ints_sums.csv')
print 'done'
Can someone please help me identify the problem here?
EDIT: Just thought I would post the working code. I ended up dropping the
Class implementation. As suggested by Tim Peters, I only pass filenames (not
open files).
On 5 million rows x 2 columns, I noticed about 20% time improvement with 2
processors vs 1. I expected a bit more, but I think the problem is extra
overhead of queueing. As per [this
thread](http://stackoverflow.com/questions/8514238/cant-pickle-type-csv-
reader-error-when-using-multiprocessing-on-windows), an improvement would
probably be to queue records in blocks of 100 or more (rather than each line).
import csv
import multiprocessing
from datetime import datetime
NUM_PROCS = multiprocessing.cpu_count()
def main(numprocsrequested, infile, outfile):
inq = multiprocessing.Queue()
outq = multiprocessing.Queue()
numprocs = min(numprocsrequested, NUM_PROCS)
pin = multiprocessing.Process(target=parse_input_csv, args=(infile,numprocs,inq,))
pout = multiprocessing.Process(target=write_output_csv, args=(outfile,numprocs,outq,))
ps = [ multiprocessing.Process(target=sum_row, args=(inq,outq,)) for i in range(numprocs)]
pin.start()
pout.start()
for p in ps:
p.start()
pin.join()
i = 0
for p in ps:
p.join()
#print "Done", i
i += 1
pout.join()
def parse_input_csv(infile, numprocs, inq):
"""Parses the input CSV and yields tuples with the index of the row
as the first element, and the integers of the row as the second
element.
The index is zero-index based.
The data is then sent over inqueue for the workers to do their
thing. At the end the input thread sends a 'STOP' message for each
worker.
"""
f = open(infile, 'rb')
in_csvfile = csv.reader(f)
for i, row in enumerate(in_csvfile):
row = [ int(entry) for entry in row ]
inq.put( (i,row) )
for i in range(numprocs):
inq.put("STOP")
f.close()
def sum_row(inq, outq):
"""
Workers. Consume inq and produce answers on outq
"""
tot = 0
for i, row in iter(inq.get, "STOP"):
outq.put( (i, sum(row)) )
outq.put("STOP")
def write_output_csv(outfile, numprocs, outq):
"""
Open outgoing csv file then start reading outq for answers
Since I chose to make sure output was synchronized to the input there
is some extra goodies to do that.
Obviously your input has the original row number so this is not
required.
"""
cur = 0
stop = 0
buffer = {}
# For some reason csv.writer works badly across threads so open/close
# and use it all in the same thread or else you'll have the last
# several rows missing
f = open(outfile, 'wb')
out_csvfile = csv.writer(f)
#Keep running until we see numprocs STOP messages
for works in range(numprocs):
for i, val in iter(outq.get, "STOP"):
# verify rows are in order, if not save in buffer
if i != cur:
buffer[i] = val
else:
#if yes are write it out and make sure no waiting rows exist
out_csvfile.writerow( [i, val] )
cur += 1
while cur in buffer:
out_csvfile.writerow([ cur, buffer[cur] ])
del buffer[cur]
cur += 1
f.close()
if __name__ == '__main__':
startTime = datetime.now()
main(4, 'random_ints.csv', 'random_ints_sums.csv')
print 'done'
print(datetime.now()-startTime)
Answer: Passing an object across processes requires "pickling" it on the sending end
(creating a string representation of the object) and "unpickling" it on the
receiving end (recreating an isomorphic object from the string
representation). Unless you know exactly what you're doing, you should stick
to passing builtin Python types (strings, ints, floats, lists, dicts, ...) or
types implemented _by_ `multiprocessing` (`Lock()`, `Queue()`, ...). Otherwise
chances are good the pickle-unpickle dance won't work.
There's no chance that passing an open file will ever work, let alone an open
file wrapped inside yet another object (such as returned by `csv.reader(f)`).
When I ran your code, I got an error message from `pickle`:
pickle.PicklingError: Can't pickle <type '_csv.reader'>: it's not the same object as _csv.reader
Didn't you? Never ignore errors - unless, again, you know exactly what you're
doing.
The solution is simple: as I said in a comment, open the file _in_ the worker
process, just passing its string path. For example, use this instead:
def manual_parse_input_csv(csvfile):
f = open(csvfile,'rb')
in_csvfile = csv.reader(f)
for row in in_csvfile:
print row
f.close()
and take all that code _out_ of `manualCSVworker`, and change the process
creation line to:
pin = multiprocessing.Process(target=manual_parse_input_csv, args=(infile,))
See? That passes the file _path_ , a plain string. That works :-)
|
Using XHR to update a server file and add option to html select
Question: I am trying to have the input field add text into a file that is on the server
and add it to the select element on the webpage dynamically but it is not
working out so well. Currently I am getting an error that e1 is null and the
text is not getting appended to my testdoc.txt text file. If I take out the
code to try and write to the text file this works without issue. I also tried
without the dynamic adding to the select field to see if it would append to
file and that does not go. In firebug I do see the post and I see a response
but it does not get appended to the file. Below is a snippet of my current
code.
function submitxhr(){
var e1=document.getElementById('item');
var e2=document.getElementById('items');
var o=document.createElement('option');
var xhr = new XMLHttpRequest();
xhr.overrideMimeType("text/plain; charset=x-user-defined");
o.value=e1.value;
o.text=e1.value;
e2.options.add(o);
xhr.open("POST","testdoc.txt");
xhr.send(e1);
};
<form id="myForm">
<input name="item" type="text" value="" />
<select size="3" id="items" name="items">
<input type="button" value="submit" ONCLICK="submitxhr()">
</form>
My next step is then to create a remove button for the options in the select
form but I have not gotten there yet but any help would be much appreciated.
[UPDATE] If I am able to pass the XHR POST into a python CGI script I could
figure out both adding and removing. Currently, I am unable to pass the POST
into the python CGI script. It cannot find the e1 variable when passed.
import cgi
import cgitb
cgitb.enable()
form = cgi.FieldStorage()
value1 = form.getvalue[e1]
f = open(r'testdoc.txt', 'a')
f.write(e1)
f.close()
I even checked out this question but when I make a test script using this, I
also get a null value, "message = 'writelines() requires an iterable
argument'". [In my Python CGI script, how do I save to disk a file uploaded
via POST request of data entered by the user in a
form?](http://stackoverflow.com/questions/15947988/in-my-python-cgi-script-
how-do-i-save-to-disk-a-file-uploaded-via-post-request)
It does look like the value is getting passed but maybe I am not pulling the
data out correctly. f = , f.writelines = , fileitem = FieldStorage('userfile',
None, 'sghjsjh')
Thanks
Answer: You've forgotten adding the `id` to the first `input` field! It should be:
<input id="item" name="item" type="text" value="" />
instead of
<input name="item" type="text" value="" />
|
Heavily confused by win32api + COM and an answer from SO
Question: From my other question here on SO, I asked how to retrieve the current playing
song from Windows Media Player and Zune, I got an answer from a c++ dev who
gave me an explanation of how I would do this for WMP.
However, I am no C++ dev, nor am I very experienced with the pywin32 library.
And on-top of all that, the documentation on all this (especially concerning
WMP) is _horrible_.
Therefor, I need your help understanding how I would do the following in
Python.
[Source](http://stackoverflow.com/questions/19452001/need-a-way-to-retrieve-
the-current-playing-song-from-zune-and-windows-media-play)
> I have working code in C++ to print the name of media currently playing in
> WMP. It's a simple console application (78 lines of code).
>
> Steps:
>
> **1)** implements a basic COM object implementing IUnknown, IOleClientSite,
> IServiceProvider and IWMPRemoteMediaServices. This is straightforward (sort
> of, your mileage may vary) using the ATL template CComObjectRootEx. The only
> methods needing (simple) code are IServiceProvider::QueryService and
> IWMPRemoteMediaServices::GetServiceType. All other methods may return
> E_NOTIMPL
>
> **2)** Instantiate the "WMPlayer.OCX" COM object (in my case, via
> CoCreateInstance)
>
> **3)** Retrieve from the object an IOleObject interface pointer via
> QueryInterface
>
> **4)** Instanciate an object from the class seen in 1) (I use the
> CComObject<>::CreateInstance template)
>
> **5)** Use the SetClientSite method from the interface you got at 3),
> passing a pointer to your OleClientSite implementation.
>
> **6)** During the SetClientSite call, WMP will callback you: fisrt asking
> for an IServiceProvider interface pointer, second calling the QueryService
> method, asking for an IWMPRemoteMediaServices interface pointer. Return your
> implementation of IWMPRemoteMediaServices and, third, you will be called
> again via GetServiceType. You must then return "Remote". You are now
> connected to the WMP running instance
>
> **7)** Query the COM object for an IWMPMedia interface pointer
>
> **8)** If 7) didn't gave NULL, read the the IWMPMedia::name property.
>
> **9)** DONE
>
> All the above was tested with VS2010 / Windows Seven, and with WMP running
> (if there is no Media Player process running, just do nothing).
>
> I don't know if yoy can/want to implement COM interface and object in
> Python. If you are interested by my C++ code, let me know. You could use
> that code in a C++ DLL, and then call it from python.
I know a little bit about the win32api.
At the first step, I really don't know what to do, googling IOleClientSite
results in the msdn documentation, it's an interface. However, that's where I
get stuck already. I can't find anything (might just be my horrendous googling
skills) on working with these things in Python.
The second step:
WMP = win32com.client.Dispatch("WMPlayer.OCX")
Alright, that's doable.
On to the third step. QueryInterface -
> "regardless of the object you have, you can always call its QueryInterface()
> method to obtain a new interface, such as IStream."
[source](http://oreilly.com/catalog/pythonwin32/chapter/ch12.html)
However, not for me. As I understand his explanation, I think it means that
every com object sort of "inherits" three methods from IUnknown, one of which
is QueryInterface, however this does not seem the case since calling
QueryInterface on my `WMP` object fails miserably. `(Object has no attribute
'QueryInterface')`
I could ramble on, but I believe you got the point, I have no idea how to work
with this. Can anyone help me out with this one? Preferably with code
examples, but resources/documentation is welcome too.
Answer: Almost final answser but CAN'T finish. I seems that pythoncom can't be used to
implement custom Interface without the help of a C++ module. Here is an
answser from Mark Hammon (Mon, 13 Jan 2003): [How to create COM Servers with
IID_IDTExtensibility2 interface](http://computer-programming-
forum.com/56-python/d575f9041208b21f.htm)
> Sorry - you are SOL. To support arbitary interfaces, you need C++ support,
> in the form of an extension module. There is a new "Univgw" that may help
> you out, but I dont know much about this
I am not able to find anything about that "Univgw" thing...
The comtypes python module is intended to resolve the problem, and I found
links saying it does, but I can't make it works with my fresh new Python 3.3.
It's Python 2.x code. comtypes seems outdated and unmaintained.
Step 1 OK for IOleClientSite and IServiceProvider, KO for
IWMPRemoteMediaServices
Step 2, 3, 4 and 5 OK
Step 6, 7 and 8 can't be implemented without IWMPRemoteMediaServices :-(
disclaimer: complete newbie in Python, please don't yell
import pythoncom
import win32com.client as wc
from win32com.axcontrol import axcontrol
import win32com.server as ws
from win32com.server import util
from win32com.server.exception import COMException
import winerror
import pywintypes
# Windows Media Player Custom Interface IWMPRemoteMediaServices
IWMPRemoteMediaServices = pywintypes.IID("{CBB92747-741F-44FE-AB5B-F1A48F3B2A59}")
class OleClientSite:
_public_methods_ = [ 'SaveObject', 'GetMoniker', 'GetContainer', 'ShowObject', 'OnShowWindow', 'RequestNewObjectLayout', 'QueryService' ]
_com_interfaces_ = [ axcontrol.IID_IOleClientSite, pythoncom.IID_IServiceProvider ]
def SaveObject(self):
print("SaveObject")
raise COMException(hresult=winerror.E_NOTIMPL)
def GetMoniker(self, dwAssign, dwWhichMoniker):
print("GetMoniker ")
raise COMException(hresult=winerror.E_NOTIMPL)
def GetContainer(self):
print("GetContainer")
raise COMException(hresult=winerror.E_NOTIMPL)
def ShowObject(self):
print("ShowObject")
raise COMException(hresult=winerror.E_NOTIMPL)
def OnShowWindow(self, fShow):
print("ShowObject" + str(fShow))
raise COMException(hresult=winerror.E_NOTIMPL)
def RequestNewObjectLayout(self):
print("RequestNewObjectLayout")
raise COMException(hresult=winerror.E_NOTIMPL)
def QueryService(self, guidService, riid):
print("QueryService",guidService,riid)
if riid == IWMPRemoteMediaServices:
print("Known Requested IID, but can't implement!")
raise COMException(hresult=winerror.E_NOINTERFACE)
else:
print("Requested IID is not IWMPRemoteMediaServices" )
raise COMException(hresult=winerror.E_NOINTERFACE)
if __name__=='__main__':
wmp = wc.Dispatch("WMPlayer.OCX")
IOO = wmp._oleobj_.QueryInterface(axcontrol.IID_IOleObject)
pyOCS = OleClientSite()
comOCS = ws.util.wrap(pyOCS, axcontrol.IID_IOleClientSite)
IOO.SetClientSite(comOCS)
|
Python: Non-Responsive multiprocessing.pool.map_async() function
Question: I have a strange problem here.
I have a python program that executes code held in seperate .py files,
designed to be executed in sequence, one after another. The codes work fine,
however they take too long to run. My plan was to split up processing each of
these .py files amongst 4 processors using
multiprocessing.pool.map_async(function, arguments) using execfile() as the
function and the filename as the argument.
So anyways, when I run the code, absolutely nothing happens at all, **not even
an error**.
Take a look and see if you can help me out, I run the file in
SeqFile.runner(SeqFile.file).
class FileRunner:
def __init__(self, file):
self.file = file
def runner(self, file):
self.run = pool.map_async(execfile, file)
SeqFile = FileRunner("/Users/haysb/Dropbox/Stuart/Sample_proteins/Code/SVS_CodeParts/SequencePickler.py")
VolFile = FileRunner("/Users/haysb/Dropbox/Stuart/Sample_proteins/Code/SVS_CodeParts/VolumePickler.py")
CWFile = FileRunner("/Users/haysb/Dropbox/Stuart/Sample_proteins/Code/SVS_CodeParts/Combine_and_Write.py")
(SeqFile.runner(SeqFile.file))
Answer: You have several problems here - I'm guessing you never used `multiprocessing`
before.
One of your problems is that you fire off an async operation but never wait
for it to end. If you _did_ wait for it to end, you'd get more info. For
example, add:
result = SeqFile.run.get()
Do that, and you'll see the exception raised in the child process: you're
mapping `execfile` over the _string_ bound to `file`, so `execfile` sees one
character at a time. `execfile` barfs when the first thing it tries to do is
(in effect):
execfile("/")
`apply_async()` would make a lot more sense, or `map_async()` passed a list of
all the files you want to run.
Etc - this gets tedious ;-)
## Specifics
Let's get rid of the irrelevant cruft here, and show a complete executable
program. I have three files `a.py`, `b.py` and `c.py`. Here's `a.py`:
print "I'm A!"
The other two are the obvious variations.
Here's my entire driver:
if __name__ == "__main__":
import multiprocessing as mp
files = ["a.py", "b.py", "c.py"]
pool = mp.Pool(2)
pool.imap_unordered(execfile, files)
pool.close()
pool.join()
That's all it takes, and prints (some permutation of):
I'm A!
I'm B!
I'm C!
`imap_unordered()` splits the list of files up among the worker processes, and
doesn't care ("unordered") which order they run in. That's maximally
efficient. Note that I restricted the number of workers to 2, just to show
that it works fine even though there are more files (3) than worker processes
(2).
You can get any of the `Pool` functions to work similarly. If you _have_ ;-)
to use `map_async()`, for example, replace the `imap_unordered()` call with:
async = pool.map_async(execfile, files)
async.get()
Or:
asyncs = [pool.apply_async(execfile, (fn,)) for fn in files]
for a in asyncs:
a.get()
Clearer? Keep it as simple as possible at first.
|
add title to collection of pandas hist plots
Question: I'm looking for advice on how to show a title at the top of a collection of
histogram plots that have been generated by a pandas df.hist() command. For
instance, in the histogram figure block generated by the code below I'd like
to place a general title (e.g. 'My collection of histogram plots') at the top
of the figure:
data = DataFrame(np.random.randn(500).reshape(100,5), columns=list('abcde'))
axes = data.hist(sharey=True, sharex=True)
I've tried using the _title_ keyword in the hist command (i.e. title='My
collection of histogram plots'), but that didn't work.
The following code _does_ work (in an ipython notebook) by adding text to one
of the axes, but is a bit of a kludge.
axes[0,1].text(0.5, 1.4,'My collection of histogram plots', horizontalalignment='center',
verticalalignment='center', transform=axes[0,1].transAxes)
Is there a better way?
Answer: You can use `suptitle()`:
import pylab as pl
from pandas import *
data = DataFrame(np.random.randn(500).reshape(100,5), columns=list('abcde'))
axes = data.hist(sharey=True, sharex=True)
pl.suptitle("This is Figure title")
|
Is there a good way to avoid memory deep copy or to reduce time spent in multiprocessing?
Question: I am making a memory-based real-time calculation module of "Big data" using
Pandas module of the Python environment.
So response time is the quality of this module and very critical and
important.
To process large data set, I split the data and process sub split data in
parallel.
In the part of storing the result of sub data, much time spend(21th line).
I think that internally memory deep copy arises or sub data passed are not
shared in memory.
If I written the module in C or C++, I will use pointer or reference like
below.
"process=Process(target=addNewDerivedColumn, args=[resultList, **&
sub_dataframe**])"
or
"process=Process(target=addNewDerivedColumn, args=[resultList, sub_dataframe])
def addNewDerivedColumn(resultList, **split_sub_dataframe &**):.... "
**Is there a good way to avoid memory deep copy or to reduce time spent in
multiprocessing?** "Not elegant" is fine. I am ready for making my codes
dirty. I tried weekref, RawValue, RawArray, Value, Pool but all failed.
The module is being developed in MacOS and finally is going to run in Linux or
Unix.
Do not consider Windows OS.
Here comes the code.
The real code is in my office but the structure and logic are the same as the
real one.
1 #-*- coding: UTF-8 -*-'
2 import pandas as pd
3 import numpy as np
4 from multiprocessing import *
5 import time
6
7
8 def addNewDerivedColumn(resultList, split_sub_dataframe):
9
10 split_sub_dataframe['new_column']= np.abs(split_sub_dataframe['column_01']+split_sub_dataframe['column_01']) / 2
11
12 print split_sub_dataframe.head()
13
14 '''
15 i think that the hole result of sub-dataframe is copied to resultList, not reference value
16 and in here time spend much
17 compare elapsed time of comment 21th line with the uncommented one
18 In MS Windows, signifiant difference of elapsed time doesn't show up
19 In Linux or Mac OS, the difference is big
20 '''
21 resultList.append(split_sub_dataframe)
22
23
24
25 if __name__ == "__main__":
26
27 # example data generation
28 # the record count of the real data is over 1 billion with about 10 columns.
29 dataframe = pd.DataFrame(np.random.randn(100000000, 4), columns=['column_01', 'column_02', 'column_03', 'column_04'])
30
31
32 print 'start...'
33 start_time = time.time()
34
35 # to launch 5 process in parallel, I split the dataframe to five sub-dataframes
36 split_dataframe_list = np.array_split(dataframe, 5)
37
38 # multiprocessing
39 manager = Manager()
40
41 # result list
42 resultList=manager.list()
43 processList=[]
44
45 for sub_dataframe in split_dataframe_list:
46 process=Process(target=addNewDerivedColumn, args=[resultList, sub_dataframe])
47 processList.append(process)
48
49 for proc in processList:
50 proc.start()
51 for proc in processList:
52 proc.join()
53
54
55 print 'elapsed time : ', np.round(time.time() - start_time,3)
Answer: You will get better performance if you keep interprocess communication to a
minimum. Therefore, instead of passing sub-DataFrames as arguments, just pass
index values. The subprocess can slice the common DataFrame itself.
When a subprocess is spawned, it gets a copy of all the globals defined in the
calling module of the parent process. Thus, if the large DataFrame, `df`, is
defined in the globals _before_ you spawn a multiprocessing pool, then each
spawned subprocess will have access to `df`.
On Windows, where there is no `fork()`, a new python process is started and
the calling module is imported. Thus, on Windows, the spawned subprocess has
to regenerate `df` from scratch, which could take time and much additional
memory.
On Linux, however, you have copy-on-write. This means that the spawned
subprocess accesses the original globals (of the calling module) _without
copying_ them. Only when the subprocess tries to modify the global does Linux
then make a separate copy before the value is modified.
So you can enjoy a performance gain if you avoid modifying globals in your
subprocesses. I suggest using the subprocess only for computation. Return the
value of the computation, and let the main process collate the results to
modify the original DataFrame.
import pandas as pd
import numpy as np
import multiprocessing as mp
import time
def compute(start, end):
sub = df.iloc[start:end]
return start, end, np.abs(sub['column_01']+sub['column_01']) / 2
def collate(retval):
start, end, arr = retval
df.ix[start:end, 'new_column'] = arr
def window(seq, n=2):
"""
Returns a sliding window (of width n) over data from the sequence
s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ...
"""
for i in range(len(seq)-n+1):
yield tuple(seq[i:i+n])
if __name__ == "__main__":
result = []
# the record count of the real data is over 1 billion with about 10 columns.
N = 10**3
df = pd.DataFrame(np.random.randn(N, 4),
columns=['column_01', 'column_02', 'column_03', 'column_04'])
pool = mp.Pool()
df['new_column'] = np.empty(N, dtype='float')
start_time = time.time()
idx = np.linspace(0, N, 5+1).astype('int')
for start, end in window(idx, 2):
# print(start, end)
pool.apply_async(compute, args=[start, end], callback=collate)
pool.close()
pool.join()
print 'elapsed time : ', np.round(time.time() - start_time,3)
print(df.head())
|
"NameError: Can't find file for module maya" while trying to run a Python script in Eclipse
Question: I setup Eclipse IDE for editing and debugging Maya scripts. When I try to run
the code:
import maya.cmds as cmds
cmds.ls()
in Eclipse I get the error:
import maya.cmds as cmds
NameError: Can't find file for module maya
(filename C:\Users\shivani\My Documents\maya)
I configured eclipse to use maya and python like the following:

I don't understand what is the problem or I'm not able to use Eclipse
properly?
Answer: [Configure](http://pydev.org/manual_101_interpreter.html) Eclipse to use
`mayapy` Python interpreter available in `<Maya_INSTALL_DIR>\bin`.
Or else you will have to initialize the default Python interpreter with Maya
as explained [here](http://stackoverflow.com/a/18566701/1309352).
|
How to use AES with GAE python?
Question: I would like to encrypt the data transferred between GAE app and my android
application (_https_ will not help since the key should be dynamic). I am
thinking about AES (128-bit) encryption.
I've tried to use `pycrypto` (GAE SDK 1.8.6, python 2.7, OS X 10.9):
libraries:
- name: pycrypto
version: "2.6"
But when I `import Crypto` it can not find the module:
ImportError: No module named Crypto
Is there any other built-in module I can use? Or, is there any way to be able
to use `pycrypto` (should I install it manually)?
Answer: This happens to be an App Engine supplied module, as detailed here:
<https://developers.google.com/appengine/docs/python/tools/libraries27>
> The Python 2.7 runtime includes some third-party modules. Some of these are
> available by default; others are only available if configured. You can
> specify which version you want to use.
> <https://developers.google.com/appengine/docs/python/python25/migrate27#Configuring_Libraries>
To enable included libraries edit your app.yaml like this:
libraries:
- name: pycrypto
version: latest
In general you'd need to add the files themselves to the same directory that
app.yaml is in, as per this question: [Uploading python third party libraries
with Google App engine](http://stackoverflow.com/questions/10648256/uploading-
python-third-party-libraries-with-google-app-engine) but this happens to be a
supplied library.
|
Find lowest value in a list of dictionaries in python
Question: I want to find and return the minimal value of an id in a string, for example:
find_min_id([{"nonid": "-222", "id": 0}, {"id": -101}])
-101
find_min_id([{’id’: 63, 'id': 42}])
42
So far I have this:
def find_min_id(list):
return min(list)
but that gives:
{'id': -101}
and I only want the value of the lowest id.
Answer: Use the `key` parameter of `min`:
def find_min_id(l):
return min(l, key=lambda d: d.get("id", float('inf')))["id"]
This actually finds the min id, and does it without creating a new list.
The only thing is, the elements in your list might not had an `'id'` key. For
that reason I had to use `.get("id", float('inf'))`. Thus the function will
return `inf` if there is no id key, which might not be desirable. What `min()`
does when given an empty list is it throws an exception, so we'd probably like
to do the same if none of the dicts we pass it have an `'id'` key. In that
case the min of a generator appoach might indeed be better:
def find_min_id(l):
return min(d["id"] for d in l if "id" in d)
The other approach would be to check for `inf` as the result of `min`, but
this is more cumbersome:
import math
def find_min_id(l):
res = min(l, key=lambda d: d.get("id", float('inf')))["id"]
if math.isinf(res):
raise ValueError("No dict has an 'id' key")
return res
|
Drawing Circles Python
Question: The function is supposed to loop, each time decreasing the size of the circle
by 10 and drawing a new circle, until the size is less than or equal to 0.
What am i missing
def circle(x):
turtle.up()
turtle.goto(0,0)
turtle.down()
turtle.color("blue")
turtle.circle(x)
if x>0:
turtle.up()
turtle.goto(0,0)
turtle.down()
turtle.color("blue")
turtle.circle(x-10)
else:
turtle.up()
turtle.goto(0,0)
turtle.down()
turtle.color("blue")
turtle.circle(x)
print(circle(80))
Answer: Here is a working version. Added recursion `circle(x-10)`, removed redundant
code, added `turtle.done()` to stop the app from crashing.
import turtle
def circle(x):
turtle.up()
turtle.goto(0,0)
turtle.down()
turtle.color("blue")
turtle.circle(x)
if x>0:
circle(x-10)
circle(80)
turtle.done()
|
Dynamically naming edited csv, to include part of the old csv name
Question: I am using some code to merge two csvs and sort these by two columns.
Ouputting a new csv. The input csvs are of the same name just numbered 1 & 2\.
I am repeating this code for multiple sets of data. I was wondering what the
method would be to make the code output a file name containing the first part
of the original file names.
My current code:
import pandas as pd
df1 = pd.read_csv("data csv 1\September 2013 1 UUedit1.csv", delimiter = ",")
df2 = pd.read_csv("data csv 1\September 2013 2 UUedit2.csv", delimiter = ",")
merged = df1.merge(df2, on="Unique Element")
delcols = "Element_y", "number_y", "date_y", "title_y", "name_y"
for delcol in delcols:
del merged[delcol]
merged.rename(columns={"name_x": "name", "rdate_x": "date", "title_x": "title", "number_x": "number", "Element_x": "Element"}, inplace = True)
merged = merged.sort("Element").reset_index(drop=True)
merged = merged.sort("date").reset_index(drop=True)
merged.to_csv("MRG.csv", index=False, sep = ",")
So in this example both the input files are called `September
2013`"number""UUedit" I want to make my code output the file name directly as
`September 2013 MRG.csv` how can this be coded? To clarify if the two original
files were `October 2013` then the output would be `October 2013 MRG.csv` Many
thanks GTPE
## Edit
Upon running the code supplied by Christian Ternus I received the following
print and traceback:
Usage: C:/Test.py <month> <year>
Traceback (most recent call last):
File "C:/Test.py", line 7, in <module>
month, year = sys.argv[1:]
ValueError: need more than 0 values to unpack
I am unsure what the second variable should be set to.
Many thanks
GTPE
### Edit 2
I managed to get the code to work by calling it CMD, however my attempts at
calling the script through python didn't seem to work. I tried the folowing:
import subprocess
p = subprocess.Popen(['python', 'RawDataSheetMergerPandasTest.py September 2013'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
print out
Answer: Here's how to get the name of the next month, given the name of the current
month:
import calendar
nextmonth = calendar.month_name[1:][(calendar.month_name[1:].index(month) + 1) % 12]
And here's that same logic applied to your script, with a few other
improvements :) Run this script as "`./myscript.py somemonth someyear`". It'll
output a CSV file named `nextmonth year MRG.csv`, even taking into account
localization and wrapping the year properly.
import pandas as pd
import calendar
import sys
if len(sys.argv) != 3:
print "Usage: {0} <month> <year>".format(sys.argv[0])
month, year = sys.argv[1:]
if not month in calendar.month_name:
print "Invalid month! Month must be one of:{0}".format(str(calendar.month_name))
if not year.isdigit():
print "Invalid year! Year must be a number."
nextmonth = calendar.month_name[1:][(calendar.month_name[1:].index(month) + 1) % 12]
df1 = pd.read_csv("data csv 1\{0} {1} 1 UUedit1.csv".format(month, year), delimiter = ",")
df2 = pd.read_csv("data csv 1\{0} {1} 2 UUedit2.csv".format(month, year), delimiter = ",")
merged = df1.merge(df2, on="Unique Element")
delcols = "Element_y", "number_y", "date_y", "title_y", "name_y"
for delcol in delcols:
del merged[delcol]
merged.rename(columns={"name_x": "name", "rdate_x": "date", "title_x": "title", "number_x": "number", "Element_x": "Element"}, inplace = True)
merged = merged.sort("Element").reset_index(drop=True)
merged = merged.sort("date").reset_index(drop=True)
if month == calendar.month_name[-1]: year = str(int(year + 1))
merged.to_csv("{0} {1} MRG.csv".format(nextmonth, year), index=False, sep = ",")
If you don't need the next-month feature (sounds like you actually don't),
take out these two lines:
nextmonth = calendar.month_name[1:][(calendar.month_name[1:].index(month) + 1) % 12]
[...]
if month == calendar.month_name[-1]: year = str(int(year + 1))
and replace the last line with:
merged.to_csv("{0} {1} MRG.csv".format(month, year), index=False, sep = ",")
|
write csv row (from within for loop) out to csv file without using python csv module
Question: **My goal is to avoid importing the csv module
I am working on a script that runs through an extremely large csv file and
selectively writes rows to a new csv file.
I have the following two lines:
with open(sys.argv[1]) as ifile, open(sys.argv[2], mode = 'w') as ofile:
for row in ifile:
and then this, a few nested-if statements down:
line = list(ifile)[row]
ofile.write(line)
I know that isn't right--I took a stab at it and was hoping someone here could
shed some light on how to correctly go about this. The essence of this
question is how to reference the row that I am in so that I can write it out
to the new csv file using 'ofile'. Please let me know if any further
clarifications are necessary. Thanks!
EDIT: Full Code included in pastebin link - <http://pastebin.com/a0jx85xR>
Answer: You're quite close. This is all you have to do:
with open(sys.argv[1]) as ifile, open(sys.argv[2], mode = 'w') as ofile:
for row in ifile:
#...
#You've defined some_condition to be met (you will have to replace this for yourself)
#E.g.: the number of entries in each row is greater than 5:
if len([term for term in row.split('#') if term.strip() != '']) > 5:
ofile.write(row)
UPDATE:
To answer the OP's question about splitting lines:
you split a line in Python by supplying the delimiting character. Since this
is a CSV file, you split the line by the `,`. Example:
If this is a line (a string):
0, 1, 2, 3, 4, 5
If you apply:
line.split(',')
You'll obtain _a list_ :
['0', '1', '2', '3', '4', '5']
UPDATE 2:
import sys
if __name__ == '__main__':
ticker = sys.argv[3]
allTypes = bool(int(sys.argv[4])) #argv[4] is a string, you have to convert it to an int, then to a bool
with open(sys.argv[1]) as ifile, open(sys.argv[2], mode = 'w') as ofile:
all_timestamps = [] #this is an empty list
n_rows = 0
for row in ifile:
#This splits the line into constituent terms as described earlier
#SAMPLE LINE:
#A,1,12884902522,B,B,4900,AAIR,0.1046,28800,390,B,AARCA,
#After applying this bit of code, the line should be split into this:
#['A', '1', '12884902522', 'B', 'B', '4900', 'AAIR', '0.1046', '28800', '390', 'B', 'AARCA']
#NOW, you can make comparisons against those terms. :)
terms = [term for term in row.split(',') if term.strip() != '']
current_timestamp = int(terms[2])
#compare the current against the previous
#starting from row 2: (index 1)
if n_rows > 1:
#Python uses circular indices, hence: -1 means the value at the last index
#That is, the previous time_stamp. Now perform the comparison and do something if that criterion is met:
if current_timestamp - all_timestamp[-1] >= 0:
pass #the pass keyword means to do nothing. You'll have to replace it with whatever code you want
#increment n_rows every time:
n_rows += 1
#always append the current timestamp to all the time_stamps
all_timestamps.append(current_timestamp)
if (terms[6] == ticker):
# add something to make sure chronological order hasn't been broken
if (allTypes == 1):
ofile.write(row)
#I don't know if this was a bad indent of not, but you should know
#where this goes
elif (terms[0] == "A" or terms[0] == "M" or terms[0] == "D"):
print row
ofile.write(row)
My original conjecture was correct. **You weren't splitting the row into the
the CSV components.** Hence, when you were making comparisons on the rows, you
weren't getting the correct results - thus, you weren't getting any output.
This ought to work now (given slight modifications as per your objectives). :)
|
Python xticks in subplots
Question: If I plot a single imshow plot I can use
fig, ax = plt.subplots()
ax.imshow(data)
plt.xticks( [4, 14, 24], [5, 15, 25] )
to replace my xtick labels.
Now, I am plotting 12 imshow plots using
f, axarr = plt.subplots(4, 3)
axarr[i, j].imshow(data)
How can I change my xticks just for one of these subplots? I can only access
the axes of the subplots with axarr[i, j]. How can I access "plt" just for one
particular subplot?
Thanks!
Answer: There are two ways:
1. Use the axes methods of the subplot object (e.g. `ax.set_xticks` and `ax.set_xticklabels`) or
2. Use `plt.sca` to set the current axes for the pyplot state machine (i.e. the `plt` interface).
As an example (this also illustrates using `setp` to change the properties of
all of the subplots):
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=3, ncols=4)
# Set the ticks and ticklabels for all axes
plt.setp(axes, xticks=[0.1, 0.5, 0.9], xticklabels=['a', 'b', 'c'],
yticks=[1, 2, 3])
# Use the pyplot interface to change just one subplot...
plt.sca(axes[1, 1])
plt.xticks(range(3), ['A', 'Big', 'Cat'], color='red')
fig.tight_layout()
plt.show()

|
Python 'requests' module and encoding?
Question: I am doing a simple POST request using the requests module, and testing it
against [httpbin](http://httpbin.org/)
import requests
url = 'http://httpbin.org/post'
params = {'apikey':'666666'}
sample = {'sample': open('test.bin', 'r')}
response = requests.post( url, files=sample, params=params, verify=False)
report_info = response.json()
print report_info
I have an issue with the encoding. It is not using `application/octet-stream`
and so the encoding is not correct. From the headers, I see:
{
u'origin': u'xxxx, xxxxxx',
u'files': {
u'sample': u'data:None;base64,qANQR1DBw..........
So, I get `data:None` instead of `data:application/octet-stream` when I try
with `curl`. The file size and encoding is incorrect.
How can I force or check that it is using `application/octet-stream`?
Answer: Sample taken from <http://www.python-
requests.org/en/latest/user/quickstart/#custom-headers>
>>> import json
>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}
>>> headers = {'content-type': 'application/json'}
>>> r = requests.post(url, data=json.dumps(payload), headers=headers)
You might want to change the `headers` to
headers = {'content-type': 'application/octet-stream'}
response = requests.post( url, files=sample, params=params, verify=False,
headers = headers)
|
Weird segmentation fault in python3 after updated to MAC OS X Mavericks
Question: I've updated my system to OS X Mavericks, just now when I tried to use hashlib
module a strange Segmentation fault Raised. I've tried to rebuild the
python3.3.2 and reinstall it again but it didn't help. So how could I fix this
annoying problem? The out put looks like below:
ZZ:Python-3.3.2 zhangzhao$ python3
Python 3.3.2 (default, Oct 28 2013, 16:27:26)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import hashlib
>>> a = hashlib.md5()
Segmentation fault: 11
Answer: There are known problems with Python 3.3.2 and Mavericks. Please try [Python
3.3.3rc1](http://www.python.org/download/releases/3.3.3/) as this may fix thes
problem:
> This release fully supports OS X 10.9 Mavericks. In particular, this release
> fixes an issue that could cause previous versions of Python to crash when
> typing in interactive mode on OS X 10.9
|
inspect.getsource() doesn't work in python
Question: I have a problem with this code , but don't no why...
import inspect
inspect.getsource(min)
and the error is:
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
inspect.getsource(min)
File "C:\Python33\lib\inspect.py", line 726, in getsource
lines, lnum = getsourcelines(object)
File "C:\Python33\lib\inspect.py", line 715, in getsourcelines
lines, lnum = findsource(object)
File "C:\Python33\lib\inspect.py", line 551, in findsource
file = getfile(object)
File "C:\Python33\lib\inspect.py", line 435, in getfile
'function, traceback, frame, or code object'.format(object))
TypeError: <built-in function min> is not a module, class, method, function, traceback, frame,or code object
Answer: The built-in `min()` is implemented in C code, and `inspect.getsource()` can
only show you _Python_ code:
>>> min
<built-in function min>
The `built-in function` type is always implemented in C.
The code for this function comes from the `bltinmodule.c` source file; the
[`builtin_min()`
function](http://hg.python.org/cpython/file/cd95f1276360/Python/bltinmodule.c#l1448)
delegates to the [`min_max()` utility
function](http://hg.python.org/cpython/file/cd95f1276360/Python/bltinmodule.c#l1345)
in the same source file.
|
accessing ctypes returned object's methods
Question: I need to wrap c++ dll to python. I'm using `ctypes` module for that.
c++ header is something like:
class NativeObj
{
void func();
}
extern "C"
{
NativeObj* createNativeObj();
}; //extern "C"
I want to create `NativeObj` in python code and then call its `func` method.
I wrote this code and get pointer to `NativeObj` but I didn't find how to
access `func`
>>> import ctypes
>>> d = ctypes.cdll.LoadLibrary('dll/path')
>>> obj = d.createNativeObj()
>>> obj
36408838
>>> type(obj)
<type 'int'>
Thanks.
Answer: You cannot call C++ instance methods from ctypes. You will need to export a
non-member function that will call the method. It will look like this in C++:
void callFunc(NativeObj* obj)
{
obj->func();
}
You can then call it like this:
import ctypes
d = ctypes.cdll.LoadLibrary('dll/path')
obj = d.createNativeObj()
d.callFunc(obj)
It would also be useful to tell `ctypes` about the types involved.
import ctypes
d = ctypes.cdll.LoadLibrary('dll/path')
createNativeObj = d.createNativeObj
createNativeObj.restype = ctypes.c_void_p
callFunc = d.callFunc
callFunc.argtypes = [ctypes.c_void_p]
obj = createNativeObj()
callFunc(obj)
|
Python doesn't allow me to do match.group() with regex?
Question: I wrote a regex in Python to just get the digits from a string. However, when
I run match.group(), it says that the object `list` has no attribute `group`.
What am I doing wrong? My code as typed pasted into the terminal, and the
terminal's response. Thanks.
>>> #import regex library
... import re
>>>
>>> #use a regex to just get the numbers -- not the rest of the string
... matcht = re.findall(r'\d', dwtunl)
>>> matchb = re.findall(r'\d', ambaas)
>>> #macht = re.search(r'\d\d', dwtunl)
...
>>> #just a test to see about my regex
... print matcht.group()
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
AttributeError: 'list' object has no attribute 'group'
>>> print matchb.group()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'group'
>>>
>>> #start defining the final variables
... if dwtunl == "No Delay":
... dwtunnl = 10
... else:
... dwtunnl = matcht.group()
...
Traceback (most recent call last):
File "<stdin>", line 5, in <module>
AttributeError: 'list' object has no attribute 'group'
>>> if ambaas == "No Delay":
... ammbaas = 10
... else:
... ammbaas = matchb.group()
...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
AttributeError: 'list' object has no attribute 'group'
Answer: `re.findall()` doesn't return a match object (or a list of them), it always
returns a list of strings (or a list of tuples of strings, in the case of
there being more than one capturing group). And a list doesn't have a
`.group()` method.
>>> import re
>>> regex = re.compile(r"(\w)(\W)")
>>> regex.findall("A/1$5&")
[('A', '/'), ('1', '$'), ('5', '&')]
`re.finditer()` will return an iterator that yields one match object per
match.
>>> for match in regex.finditer("A/1$5&"):
... print match.group(1), match.group(2)
...
A /
1 $
5 &
|
Python BeautifulSoup Print Info in CSV
Question: I can print the information I am pulling from a site with no problem. But when
I try to place the street names in one column and the zipcodes into another
column into a CSV file that is when I run into problems. All I get in the CSV
is the two column names and every thing in its own column across the page.
Here is my code. Also I am using Python 2.7.5 and Beautiful soup 4
from bs4 import BeautifulSoup
import csv
import urllib2
url="http://www.conakat.com/states/ohio/cities/defiance/road_maps/"
page=urllib2.urlopen(url)
soup = BeautifulSoup(page.read())
f = csv.writer(open("Defiance Steets1.csv", "w"))
f.writerow(["Name", "ZipCodes"]) # Write column headers as the first line
links = soup.find_all(['i','a'])
for link in links:
names = link.contents[0]
print unicode(names)
f.writerow(names)
Answer: The data you retrieve from the URL contains more `a` elements than `i`
elements. You must filter the `a` elements and then build pairs using the
Python `zip` buildin.
links = soup.find_all('a')
links = [link for link in links
if link["href"].startswith("http://www.conakat.com/map/?p=")]
zips = soup.find_all('i')
for l, z in zip(links, zips):
f.writerow((l.contents[0], z.contents[0]))
Output:
Name,ZipCodes
1ST ST,(43512)
E 1ST ST,(43512)
W 1ST ST,(43512)
2ND ST,(43512)
E 2ND ST,(43512)
W 2ND ST,(43512)
3 RIVERS CT,(43512)
3RD ST,(43512)
E 3RD ST,(43512)
...
|
Python Tkinter listbox with MySQLdb
Question: It's my first program in python and I'm trying to create a program that will
interface a MySql address book with a asterisk server and make a call. The
"asterisk code part" is ok, I will add later, but the problem is that I have a
listbox in Tkinter and I would like to fill it with values retrieved from a
mysqldb query. I only can add a single value to the listbox, but if I make a
print the results is correct. How can I solve this? I imagine that I will have
to do a for loop. Later I will have to know how select a value from the list
and store in a variable.
from Tkinter import *
import MySQLdb
root = Tk()
root.title("PyCall")
myContainer = Frame(root)
myContainer.pack(side=TOP, expand=YES, fill=BOTH)
db = MySQLdb.connect("localhost",port=3306, user="root", passwd="mypass", db="test" )
cursor = db.cursor()
cursor.execute("SELECT * FROM utenti")
db.commit()
numrows = int(cursor.rowcount)
for x in range(0,numrows):
row = cursor.fetchone()
print row[1]
listbox = Listbox(root)
listbox.pack()
listbox.insert(END, row[1])
root.mainloop()
db.close()
Answer: If that's your first program in Python, you're off to a good start! Your
question really has little to do with MySQL, and you seem to have a good
handle on that, so I'll leave that alone and just focus on the Tkinter issues
you are having. I don't have a MySQL database to test with anyway :)
It's generally a good idea in GUI applications, at least in Tkinter, to setup
your own application class with a Tk root frame as the application's master
container. The reason for this is that GUIs are a always a bit of slight of
hand, they are only a facade for real application data, and that real data
needs someplace to live. By creating your own application class, you have a
home for that data via `self`.
Okay, enough with all the boring stuff, let's just build something:
import Tkinter
class Application(Tkinter.Frame):
def __init__(self, master):
Tkinter.Frame.__init__(self, master)
self.master.minsize(width=256, height=256)
self.master.config()
self.pack()
self.main_frame = Tkinter.Frame()
self.some_list = [
'One',
'Two',
'Three',
'Four'
]
self.some_listbox = Tkinter.Listbox(self.main_frame)
# bind the selection event to a custom function
# Note the absence of parentheses because it's a callback function
self.some_listbox.bind('<<ListboxSelect>>', self.listbox_changed)
self.some_listbox.pack(fill='both', expand=True)
self.main_frame.pack(fill='both', expand=True)
# insert our items into the list box
for i, item in enumerate(self.some_list):
self.some_listbox.insert(i, item)
# make a label to show the selected item
self.some_label = Tkinter.Label(self.main_frame, text="Welcome to SO!")
self.some_label.pack(side='top')
# not really necessary, just make things look nice and centered
self.main_frame.place(in_=self.master, anchor='c', relx=.5, rely=.5)
def listbox_changed(self, *args, **kwargs):
selection_index = self.some_listbox.curselection()
selection_text = self.some_listbox.get(selection_index, selection_index)
self.some_label.config(text=selection_text)
root = Tkinter.Tk()
app = Application(root)
app.mainloop()
Hope this helps, and have fun building GUIs!
|
Execute another ipython notebook in a separate namespace
Question: I've been using some very nice code from [this
example](http://nbviewer.ipython.org/5491090/analysis.ipynb) to run one
ipython notebook from another, which I (basically) copy below. This turns out
to be a very nice way to organize my code.
But now, I want to compare some sympy expressions that I've coded up with
roughly equivalent sympy expressions that someone else has coded up. And since
there are some name clashes, I'd like to be able to execute the two notebooks
in their own namespaces, so that if Bob and I both define a sympy expression
`x`, I can just evaluate
Bob.x - Me.x
to see if they are the same (or find their differences). [Note that it's easy
to change a namespace dictionary into a "dottable" namespace using something
like [this Bunch object](http://stackoverflow.com/a/2597440/1194883).]
Here's the function:
def exec_nb(nbfile):
from io import open
from IPython.nbformat import current
with open(nbfile) as f:
nb = current.read(f, 'json')
ip = get_ipython()
for cell in nb.worksheets[0].cells:
if cell.cell_type != 'code':
continue
ip.run_cell(cell.input)
The basic problem is the `get_ipython` gets the currently running ipython
instance, and then `run_cell` executes the cells from the other notebook in
the current namespace of that instance.
I can't figure out how to change this. For example, running the whole command
in `exec` with a different namespace still finds the current ipython instance,
and uses that namespace.
Also, both notebooks actually need to be run in ipython; I can't export them
to a script and execute the scripts in a namespace.
Answer: For the record, the link Jakob pointed to has now moved
[here](https://jupyter-
notebook.readthedocs.io/en/master/examples/Notebook/Importing%20Notebooks.html),
and answered my question perfectly.
|
XSLT 2.0: Creating child elements from an element's text value via known semantic hierarchy
Question: A bit stuck on this one. Data is provided in the following format (non-
important content snipped):
<?xml version="1.0" encoding="UTF-8"?>
<Content Type="Statutes">
<Indexes>
<!--SNIP-->
<Index Level="3" HasChildren="0">
<!--SNIP-->
<Content><p> (1)(a)The statutes ... </p><p> (b)To ensure public ..: </p><p>
(I)Shall authorize ...; </p><p> (II)May authorize and ...: </p><p> (A)Compact disks;
</p><p> (B)On-line public ...; </p><p> (C)Electronic applications for ..;
</p><p> (D)Electronic books or ... </p><p> (E)Other electronic products or formats;
</p><p> (III)May, pursuant ... </p><p> (IV)Recognizes that ... </p><p>
(2)(a)Any person, ...: </p><p> (I)A statement specifying ...; </p><p> (II)A statement
specifying ...; </p><p> (3)A statement
specifying ...; </p><p> (4)A statement
specifying ...; </p></Content>
</Index>
<!--SNIP-->
</Indexes>
</Content>
Need to take the text value of element **Content** which contains a semantic
hierarchy:
(1)
+-(a)
+-(I)
+-(A)
...and place via XSLT 2.0 transformation as a parent-child element
relationship as the final output:
<?xml version="1.0" encoding="UTF-8"?>
<law>
<!--SNIP-->
<content>
<section prefix="(1)">
<section prefix="(a)">The statutes ...
<section prefix="(b)">To ensure public ..:
<section prefix="(I)">Shall authorize ...;</section>
<section prefix="(II)">May authorize and ...:
<section prefix="(A)">Compact disks;</section>
<section prefix="(B)">On-line public ...;</section>
<section prefix="(C)">Electronic applications for ..;</section>
<section prefix="(D)">Electronic books or ...</section>
<section prefix="(E)">Other electronic products or formats;</section>
</section>
<section prefix="(III)">May, pursuant ...</section>
<section prefix="(IV)">Recognizes that ...</section>
</section>
</section>
<section prefix="(2)">
<section prefix="(a)">Any person, ...:
<section prefix="(I)">A statement specifying ...;</section>
<section prefix="(II)">A statement specifying ...;</section>
</section>
</section>
<section prefix="(3)">Level 1 node with no children</section>
</content>
</law>
I was able to tokenize the ending html-encoded P tags from Content's text
value, but no clue how to get dynamically created elements to create child
elements on conditionals.
My XSLT 2.0 stylesheet:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xml" encoding="UTF-8" indent="yes"/>
<xsl:template match="/Content">
<!-- Work from the lowest index level with no children up -->
<xsl:apply-templates select=".//Index[@HasChildren=0]"/>
</xsl:template>
<xsl:template match="Index[@HasChildren=0]">
<law>
<structure>
<xsl:apply-templates select="Content"/>
</structure>
</law>
</xsl:template>
<!-- Template for Content element from originial -->
<xsl:template match="Content">
<content>
<!-- Loop through HTML encoded P tag endings -->
<xsl:for-each select="tokenize(.,'</p>')">
<!-- Set Token to a variable and remove P opening tags -->
<xsl:variable name="sectionText">
<xsl:value-of select="normalize-space(replace(current(),'<p>',''))"/>
</xsl:variable>
<!-- Output -->
<xsl:if test="string-length($sectionText)!=0">
<section>
<!-- Set the section element's prefix attribute (if exists) -->
<xsl:analyze-string select="$sectionText" regex="^(\(([\w]+)\)){{1,3}}">
<xsl:matching-substring >
<xsl:attribute name="prefix" select="." />
</xsl:matching-substring>
</xsl:analyze-string>
<!-- Set the section element's value -->
<xsl:value-of select="$sectionText"/>
</section>
</xsl:if>
</xsl:for-each>
</content>
</xsl:template>
</xsl:stylesheet>
...which gets me out this far - doesn't have the semantic hierarchy within the
**section** elements:
<?xml version="1.0" encoding="UTF-8"?>
<law>
<structure>
<content>
<section prefix="(1)(a)">(1)(a)The statutes ...</section>
<section prefix="(b)">(b)To ensure public ..:</section>
<section prefix="(I)">(I)Shall authorize ...;</section>
<section prefix="(II)">(II)May authorize and ...:</section>
<section prefix="(A)">(A)Compact disks;</section>
<section prefix="(B)">(B)On-line public ...;</section>
<section prefix="(C)">(C)Electronic applications for ..;</section>
<section prefix="(D)">(D)Electronic books or ...</section>
<section prefix="(E)">(E)Other electronic products or formats;</section>
<section prefix="(III)">(III)May, pursuant ...</section>
<section prefix="(IV)">(IV)Recognizes that ...</section>
<section prefix="(2)(a)">(2)(a)Any person, ...:</section>
<section prefix="(I)">(I)A statement specifying ...;</section>
<section prefix="(II)">(II)A statement specifying ...;</section>
<section prefix="(3)">(3)Level 1 section with no children ...;</section>
</content>
</structure>
</law>
Since the **Section** elements are being created _dynamically_ by the XSLT 2.0
stylesheet via tokenizing the end P tags, how do you build the **parent-child
relationship** _**dynamically_** with the known semantic hierarchy via the
**prefix** attribute?
Other programming language experiences point me in the direction of recursion
based on the tokenization and logic on the prefix to its previous prefix for
nesting - struggling to find any information on how to do this with my limited
XSLT knowledge with v2.0 (used v1.0 almost 10+ years ago). I know I could just
parse with an external Python script and be done, _but trying to stick to a
XSLT 2.0 stylesheet solution for maintainability._
**Any help is appreciated to get me on the right track and/or solution.**
Answer: You've tackled one tricky phase of the problem to create an intermediate
output with elements like this:
<section prefix="(1)(a)">text</section>
My next step would be to compute a level number, so it looks like this:
<section level="1" prefix="(1)(a)">text</section>
Computing the level number is simply a question of seeing which of several
regular expressions the prefix matches: (1) gives you level 1, (b) gives you
level 2, etc.
Once you've got level numbers you can use recursive positional grouping as
described in this paper: <http://www.saxonica.com/papers/ideadb-1.1/mhk-
paper.xml>
|
Numba autojit error on comparing numpy arrays
Question: When I compare two numpy arrays inside my function I get an error saying only
length-1 arrays can be converted to Python scalars:
from numpy.random import rand
from numba import autojit
@autojit
def myFun():
a = rand(10,1)
b = rand(10,1)
idx = a > b
return idx
myFun()
The error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-7-f7b68c0872a3> in <module>()
----> 1 myFun()
/Users/Guest/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/numba/numbawrapper.so in numba.numbawrapper._NumbaSpecializingWrapper.__call__ (numba/numbawrapper.c:3764)()
TypeError: only length-1 arrays can be converted to Python scalars
Answer: This may be secondary to your issue, but the way you have autojit shown you
will not get a speed increase. With numba you need to explicitly show the
`for` loops like so:
from numpy.random import rand
from numba import autojit
@autojit
def myFun():
a = rand(10,1)
b = rand(10,1)
idx = np.zeros((10,1),dtype=bool)
for x in range(10):
idx[x,0] = a[x,0] > b[x,0]
return idx
myFun()
This works just fine.
|
Unpickling from converted string in python/numpy
Question: I have a ton of numpy ndarrays that are stored picked to strings. That may
have been a poor design choice but it's what I did, and now the picked strings
seem to have been converted or something along the way, when I try to unpickle
I notice they are of type `str` and I get the following error:
TypeError: 'str' does not support the buffer interface
when I invoke
numpy.loads(bin_str)
Where `bin_str` is the thing I'm trying to unpickle. If I print out
`bin_str`it looks like
b'\x80\x02cnumpy.core.multiarray\n_reconstruct\nq\x00cnumpy\nndarray\nq\x01K\x00\x85q\x02c_codecs\nencode\nq\x03X\x01\x00\x00\ ...
continuing for some time, so the info seems to be there, I'm just not quite
sure how to convert it into whatever string format numpy/pickle need. On a
whim I tried
numpy.loads( bytearray(bin_str, encoding='utf-8') )
and
numpy.loads( bin_str.encode() )
which both throw an error `_pickle.UnpicklingError: unpickling stack
underflow`. Any ideas?
PS: I'm on python 3.3.2 and numpy 1.7.1
**Edit**
I discovered that if I do the following:
open('temp.txt', 'wb').write(...)
return numpy.load( 'temp.txt' )
I get back my array, and `...` denotes _copying and pasting_ the output of
`print(bin_str)` from another window. I've tried writing `bin_str` to a file
directly to unpickle but that doesn't work, it complains that `TypeError:
'str' does not support the buffer interface`. A few sane ways of converting
`bin_str` to something that _can_ be written directly to a binary file result
in pickle errors when trying to read it back.
**Edit 2** So I guess what's happened is that my binary pickle string ended up
encoded inside of a normal string, something like:
"b'pickle'"
which is unfortunate and I haven't figured out how to deal with that, except
this ridiculous and convoluted way to get it back:
open('temp.py', 'w').write('foo = ' + bin_str)
from temp import foo
numpy.loads( foo )
This seems like a very shameful solution to the problem, so please give me a
better one!
Answer: It sounds like your saved strings are the `repr`s of the original `bytes`
instances returned by your pickling code. That's a bit unfortunate, but not
too bad. `repr` is intended to return a "machine friendly" representation of
an object, and it can often be reversed by using `eval`:
import numpy as np
import pickle
# this part has already happened
orig_obj = np.array([1,2,3])
orig_pickle = pickle.dumps(orig_obj)
saved_str = repr(orig_pickle) # this was a mistake, but it's already done
# this is what you need to do to get something equivalent to orig_obj back
reconstructed_pickle = eval(saved_str)
reconstructed_obj = pickle.loads(reconstructed_pickle)
# test
if np.all(reconstructed_obj == orig_obj):
print("It worked!")
Obligatory note that using `eval` can be dangerous: Be aware that `eval` can
run any Python code it wants, so don't call it with untrusted data. However,
pickle data has the same risks (a malicious Pickle string can run arbitrary
code upon unpickling), so you're not losing much safety in this situation. I'm
guessing that you trust your data in this case anyway.
|
read a file into python and remove values
Question: I have the following code that reads in a file and stores the values into a
list. It also reads each line of the file and if it sees a '(' in the file it
splits it and everything that follows it on the line.
with open('filename', 'r') as f:
list1 = [line.strip().split('(')[0].split() for line in f]
Is there a way that I can change this to split not only at a '(' but also at a
'#'?
Answer: Use [re.split](http://docs.python.org/2/library/re.html#re.split).
With a sample of your data's format, it may be possible to do better than
this, but without context we can still show how to use this with the code you
have provided.
To use re.split():
import re
with open('filename', 'r') as f:
list1 = [re.split('[(#]+', line.strip())[0].split() for line in f]
Notice that the first parameter in re.split() is a regular expression to split
on, and the second parameter is the string to apply this operation to.
General idea from: [Splitting a string with multiple delimiters in
Python](http://stackoverflow.com/questions/10393157/splitting-a-string-with-
multiple-delimiters-in-python)
|
How do I force scatter points real pixel values when plotting in pyplot/python?
Question: I've taken an image and extracted some features from it using OpenCv. I'd like
to replot those points and their respective areas (which are real pixel
values) into a scatter window and then save it. Unfortunately, when I plot the
points, they resize to stay more visible. If I zoom in they resize. I'd like
to save the whole figure retaining the actual ratio of pixel (x,y) coordinates
to size of points plotted.
For instance:
import matplotlib.pyplot as plt
x=[5000,10000,20000]
y=[20000,10000,5000]
area_in_pixels=[100,200,100]
scatter(x,y,s=area_in_pixels)
I would like this to produce tiny dots on the image. They should span like 10
xy units. However, the dots it produces are large, and appear to span 1000 xy
units.
I've tried resizing the image with:
plt.figure(figsize=(10,10))
Which seems to resize the points relative to their position a little. But I'm
not sure what scale I would select to make this accurate. DPI settings on
plt.figsave seem to make the saved image larger but don't appear to alter
relative spot sizes.
Asked another way, is there another way to relate the s which is in points^2
to a real number or to the units of the x-y axis?
Answer: You can use [patches](http://matplotlib.org/api/artist_api.html#module-
matplotlib.patches) to create markers sized relative to the data coordinates.
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
xData=[5000,10000,20000, 15000]
yData=[20000,10000,5000, 15000]
radius_in_pixels=[100,200,100, 1000] # Circle takes radius as an argument. You could convert from area.
fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal')
for x, y, r in zip(xData, yData, radius_in_pixels):
ax.add_artist(Circle(xy=(x, y), radius = r))
plt.xlim(0, max(xData) + 200)
plt.ylim(0, max(yData) + 200)
plt.show()

|
Trigger a Python function exactly on the minute
Question: I have a function that I want to trigger at every turn of the minute — at 00
seconds. It fires off a packet over the air to a dumb display that will be
mounted on the wall.
I know I can brute force it with a while loop but that seems a bit harsh.
I have tried using sched but that ends up adding a second every minute.
What are my options?
Answer: You might try
[APScheduler](http://pythonhosted.org/APScheduler/cronschedule.html), a cron-
style scheduler module for Python.
From their examples:
from apscheduler.scheduler import Scheduler
# Start the scheduler
sched = Scheduler()
sched.start()
def job_function():
print "Hello World"
sched.add_cron_job(job_function, second=0)
will run `job_function` every minute.
|
Scraping Multiple Tables with Beautiful Soup
Question: I'm a python newbie trying to scrape tables with Beautiful Soup.
I want to scrape tables similar to the one below with Ubuntu CVE information
and output the table to a csv document.
<div class="pkg">
<div class="field">Package</div><div class="value">Source: <a href="http://people.canonical.com/~ubuntu-security/cve/pkg/mysql-cluster-7.0.html">mysql-cluster-7.0</a></div>
<table>
<tr><td>(Lucid Lynx):</td><td>ignored
</td></tr>
<tr><td>(Precise Pangolin):</td><td>DNE
</td></tr>
<tr><td>(Quantal Quetzal):</td><td>DNE
</td></tr>
<tr><td>(Raring Ringtail):</td><td>DNE
</td></tr>
<tr><td>(Saucy Salamander):</td><td>DNE
</td></tr>
</table>
</div>
<div class="pkg">
<div class="field">Package</div><div class="value"><a href="http://people.canonical.com/~ubuntu-security/cve/pkg/mysql-5.5.html">mysql-5.5</a></div>
<table>
<tr><td>(Lucid Lynx):</td><td>DNE
</td></tr>
<tr><td>(Precise Pangolin):</td><td>released
(5.5.32-0ubuntu0.12.04.1)
</td></tr>
<tr><td>(Quantal Quetzal):</td><td>released
(5.5.32-0ubuntu0.12.10.1)
</td></tr>
<tr><td>(Raring Ringtail):</td><td>released
(5.5.32-0ubuntu0.13.04.1)
</td></tr>
<tr><td>(Saucy Salamander):</td><td>released
(5.5.32-0ubuntu1)
</td></tr>
</table>
</div>
I want the csv output to be in this format:
1. release, status
2. (Lucid Lynx),ignored
3. (Precise Pangolin),DNE
4. etc....
I can pull all the tables with `table = soup.findAll("table")`But I'm unsure
of how to split the contents of all the table into two different cells onto a
spreadsheet.
Any advice would be much appreciated.
Answer: First, your file appears to be valid XML, so you should just use the normal
XML parsing in python. Beautiful Soup is not needed at all.
That said, you will really want to find_all rows, loop over them, and join the
columns.
import csv
with open('some.csv', 'rb') as f:
writer = csv.writer(f)
writer.writerow(['release', 'status'])
for row in table.find_all('tr'):
writer.writerow(col.string for col in row.find_all('td'))
|
Python - spaces
Question: I can't get over this little problem.

The second is right.
How can i print without spaces?
def square(n):
for i in range(n):
for j in range(n):
if i==0 or j==0 or i==n-1 or j==n-1: print "*",
else: print "+",
print
thanks for help!
Answer: By not using `print` plus a comma; the comma will insert a space instead of a
newline in this case.
Use `sys.stdout.write()` to get more control:
import sys
def square(n):
for i in range(n):
for j in range(n):
if i==0 or j==0 or i==n-1 or j==n-1: sys.stdout.write("*")
else: sys.stdout.write("+")
print
`print` just writes to `sys.stdout` for you, albeit that it also handles
multiple arguments, converts values to strings first and adds a newline unless
you end the expression with a comma.
You could also use the Python 3 [`print()`
_function_](http://docs.python.org/2/library/functions.html#print) in Python 2
and ask it not to print a newline:
from __future__ import print_function
def square(n):
for i in range(n):
for j in range(n):
if i==0 or j==0 or i==n-1 or j==n-1: print("*", end='')
else: print("+", end='')
print()
Alternatively, join the strings first with `''.join()`:
def square(n):
for i in range(n):
print ''.join(['*' if i in (0, n-1) or j in (0, n-1) else '+' for j in xrange(n)])
|
sqrt() argument after * must be a sequence
Question: First of all, I'm super new to python and I actually search for my problem but
the examples were to heavy to understand.
Here is my homework; I need a function which takes two functions as an
argument and returns if the results of the two functions are same or not?
Basically, it will give either TRUE of FALSE.
For that I wrote:
def f(x,y,z):
k=x(*z)
l=y(*z)
return k == l
The previos code I wrote for single function was working but when I modified
it for two function as above, it gives an error as following :
import math
>>> f(math.sqrt,math.cos,5)
Traceback (most recent call last):
File "<pyshell#56>", line 1, in <module>
f(math.sqrt,math.cos,5)
File "D:/Users/karabulut-ug/Desktop/yalanmakinesi.py", line 2, in f
k=x(*z)
TypeError: sqrt() argument after * must be a sequence
>>>
I could not figured it out since the error giving function is normally does
not take a sequence. So I dont think it makes a sense :) Any help is
appreciated.. Thanks :)
Answer: `z` is just a single number, but the `*` argument expansion syntax requires
that you pass in a sequence (like a `list`, `tuple` or `str`, for example).
Either _remove_ the `*` (and make your function work for just single
arguments), or use `*z` in the function signature to make `z` a tuple of 0 or
more captured arguments:
def f(x, y, z):
k = x(z)
l = y(z)
return k == l
or
def f(x, y, *z):
k = x(*z)
l = y(*z)
return k == l
The latter now works for functions with more than one argument too:
f(math.pow, math.log, 10, 10)
If you added a `**kw` argument to the signature, then keyword arguments could
be handled too:
def f(x, y, *args, **kwargs):
k = x(*args, **kwargs)
l = y(*args, **kwargs)
return k == l
Here I renamed `z` to `args` to better reflect its purpose.
|
Loop through every character in a sentence in python
Question: So I need to loop through a sentence character by character and total up the
different letters and how many times they occur. I can't think of a way of
doing the first bit (I'll do the totalling up myself I have a good enough idea
and I'd like to see if I can do it solo). I'm not top notch at Python but I
assume it'll be a
for letter in sentence
but I'm not sure how to loop through each letter.
Answer: You can use the
[`Counter`](http://docs.python.org/2/library/collections.html#collections.Counter)
class from `collections` (Python 2.7+):
>>> import collections
>>> sentence = "asdadasdsd"
>>> collections.Counter(sentence)
Counter({'d': 4, 'a': 3, 's': 3})
You can get the counts as follows:
>>> counts = collections.Counter(sentence)
>>> counts['d']
4
|
Fading Text in Python Turtle
Question: Is there anyway to fade a text for showing and hiding. Or clear part of screen
without cleaning other drawings.
import turtle
#fade this text
turtle.write("Hello")
#clear some shape
turtle.fd(100)
Answer: There is no function to fade text and clear shape.
You can write text on text with new color but it is not ideal.
import turtle
turtle.colormode(255)
for i in range(0,255,15):
turtle.pencolor(i,i,i)
turtle.write("Hello")
turtle.delay(100)
If you have white background you could clear shape by drawing the same shape
with white color. But it is too much work.
|
Python - TypeError: Can't convert 'int' object to str implicitly
Question: I try to write to a file but python gives me an error.
f.write('20/10/2013;SP;83428407;10:00;-;10:30;'.format(random.randrange(0,6))+';'.format(random.randrange(0,6))+';:00:15;:03:12;;;0;2;:00:58;50,0;2;0;0;0;0;0;0;0;0;0'+'\n')
Also try with str()
# f.write('20/10/2013;SP;83428407;10:00;-;10:30;'+str(random.randrange(0,6))+';'+str(random.randrange(0,6))+';:00:15;:03:12;;;0;2;:00:58;50,0;2;0;0;0;0;0;0;0;0;0'+'\n')
The same error:
TypeError: Can't convert 'int' object to str implicitly
Answer: Your first line is missing the format placeholders:
f.write('20/10/2013;SP;83428407;10:00;-;10:30;{};{};:00:15;:03:12;;;0;2;:00:58;50,0;2;0;0;0;0;0;0;0;0;0\n'.format(
random.randrange(0,6), random.randrange(0,6)))
It is the `{}` placeholders that `str.format()` fills. Note that you only need
**one** string, with placeholders where the arguments to `str.format()` are to
be filled in.
Demo output:
>>> import random
>>> '20/10/2013;SP;83428407;10:00;-;10:30;{};{};:00:15;:03:12;;;0;2;:00:58;50,0;2;0;0;0;0;0;0;0;0;0\n'.format(
... random.randrange(0,6), random.randrange(0,6))
'20/10/2013;SP;83428407;10:00;-;10:30;0;5;:00:15;:03:12;;;0;2;:00:58;50,0;2;0;0;0;0;0;0;0;0;0\n'
>>> '20/10/2013;SP;83428407;10:00;-;10:30;{};{};:00:15;:03:12;;;0;2;:00:58;50,0;2;0;0;0;0;0;0;0;0;0\n'.format(
... random.randrange(0,6), random.randrange(0,6))
'20/10/2013;SP;83428407;10:00;-;10:30;3;1;:00:15;:03:12;;;0;2;:00:58;50,0;2;0;0;0;0;0;0;0;0;0\n'
|
Comparing list in python
Question: Hey im starting to learn python and after a loop function i got a list which
looks like this
>>>print test
['a','b','c','d']
['a','c','d','e']
['b','d','e','f']
I want to compare it and found things like intersection BUT as the two lists
are under one name i can't get it done.
I want to compare the lists and count the letters. Expectation:
d, 3
a, 2
b, 2
etc
Someone can help me with that?
best regards
Answer: If you have list of lists, then you can use `collections.Counter` to count
letters:
>>> from collections import Counter
>>> test = [['a','b','c','d'],['a','c','d','e'],['b','d','e','f']]
>>> Counter(i for x in test for i in x)
Counter({'d': 3, 'a': 2, 'c': 2, 'b': 2, 'e': 2, 'f': 1})
or, as inspectorG4dget suggested in comments, use
`itertools.chain.from_iterable`:
>>> import itertools
>>> from collections import Counter
>>> test = ['test','test2']
>>> Counter(itertools.chain.from_iterable(test))
Counter({'t': 4, 's': 2, 'e': 2, '2': 1})
|
How do I end my while loop in python
Question: I am trying to create a guessing game for myself. I want to have the computer
have a random number which I have to guess. Based on what I guess, it would
then respond with "higher or lower" and this should keep happening before i
get the right number however what has happened is that now when I put in a
guess, it says higher or lower and just repeats this throughout the page. How
do I end this loop and make sure that after each "higher" or "lower" i just
get another change. Please find code below.
import random
the_number = random.randrange(100)+ 1
guess= int(raw_input("Take a guess: "))
tries = 1
while (guess != the_number):
if (guess > the_number):
print "Lower..."
break
elif (guess<the_number):
print " Higher..."
break
elif (guess == the_number):
print "Awesome achievement"
break
else:
print "Better luck next time."
guess = int(raw_input("Take another guess "))
Answer:
import random
the_number = random.randrange(100) + 1
tries = 0
while True:
tries += 1
guess = int(raw_input("Take a guess: "))
if guess > the_number:
print "Lower..."
elif guess < the_number:
print " Higher..."
else:
print "Awesome achievement, it took you", tries, "tries"
break
|
Python multiprocessing is taking much longer than single processing
Question: I am performing some large computations on 3 different numpy 2D arrays
sequentially. The arrays are huge, 25000x25000 each. Each computation takes
significant time so I decided to run 3 of them in parallel on 3 CPU cores on
the server. I am following standard multiprocessing guideline and creating 2
processes and a worker function. Two computations are running through the 2
processes and the third one is running locally without separate process. I am
passing the huge arrays as arguments of the processes like :
p1 = Process(target = Worker, args = (queue1, array1, ...)) # Some other params also going
p2 = Process(target = Worker, args = (queue2, array2, ...)) # Some other params also going
the Worker function sends back two numpy vectors (1D array) in a list appended
in the queue like:
queue.put([v1, v2])
I am not using `multiprocessing.pool`
but surprisingly I am not getting speedup, it is actually running 3 times
slower. Is passing large arrays taking time? I am unable to figure out what is
going on. Should I use shared memory objects instead of passing arrays?
I shall be thankful if anybody can help.
Thank you.
Answer: Here is an example using `np.memmap` and `Pool`. See that you can define the
number of processes and workers. In this case you don't have control over the
queue, which can be achieved using `multiprocessing.Queue`:
from multiprocessing import Pool
import numpy as np
def mysum(array_file_name, col1, col2, shape):
a = np.memmap(array_file_name, shape=shape, mode='r+')
a[:, col1:col2] = np.random.random((shape[0], col2-col1))
ans = a[:, col1:col2].sum()
del a
return ans
if __name__ == '__main__':
nop = 1000 # number_of_processes
now = 3 # number of workers
p = Pool(now)
array_file_name = 'test.array'
shape = (250000, 250000)
a = np.memmap(array_file_name, shape=shape, mode='w+')
del a
cols = [[shape[1]*i/nop, shape[1]*(i+1)/nop] for i in range(nop)]
results = []
for c1, c2 in cols:
r = p.apply_async(mysum, args=(array_file_name, c1, c2, shape))
results.append(r)
p.close()
p.join()
final_result = sum([r.get() for r in results])
print final_result
You can achieve better performances using shared memory parallel processing,
when possible. See this related question:
* [Shared-memory objects in python multiprocessing](http://stackoverflow.com/q/10721915/832621)
|
Bundling Data files with PyInstaller 2.1 and MEIPASS error --onefile
Question: This [question](http://stackoverflow.com/questions/7674790/bundling-data-
files-with-pyinstaller-onefile/13790741#13790741) has been asked before and I
can't seem to get my PyInstaller to work correctly. I have invoked the
following code in my mainscript.py file:
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
When I run the py file (within IDLE), my app runs perfectly and loads all of
the data files. However, when I bundle it with PyInstaller 2.1 (one file
method) I get the following error after the exe builds:
Traceback (most recent call last):
File "<string>", line 37, in <module>
WindowsError: [Error 3] The system cannot find the path
specified: 'C:\\Users\\Me\\AppData\\Local\\Temp\\_MEI188722\\eggs/*.*'
Does anyone have any idea where I went wrong? Thanks!
** EDIT **
Here is exactly what I want to do.
My main script has a setup (imports) that look like below. Essentially I want
to be able to have Matplotlib, Basemap, and resource path all in it:
import os,sys
import matplotlib
matplotlib.use('WX')
import wx
from matplotlib.backends.backend_wx import FigureCanvasWx as FigureCanvas
from matplotlib.backends.backend_wx import NavigationToolbar2Wx
from mpl_toolkits.basemap import Basemap
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import Calculate_Distance # A personal py file of mine
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
bmap=wx.Bitmap(resource_path('test_image.png'))
print 'hello'
I am using PyInstaller 2.1. I am also using Python 2.7.5 (32 bit). My OS is
Windows 8 (64bit). My Matplotlib is 1.3.0 and Basemap is 1.0.6. Wxpython is
2.8.12.1 (Unicode).
I go to command and do: `> pyinstaller myscript.py`. This generates my .spec
file which I slightly edit. Below is my edited spec file:
data_files = [('Calculate_Distance.py', 'C:\\Users\\Me\\Documents\\MyFolder\\Calculate_Distance.py',
'DATA'), ('test_image.png', 'C:\\Users\\Me\\Documents\\MyFolder\\test_image.png',
'DATA')]
includes = []
excludes = ['_gtkagg', '_tkagg', 'bsddb', 'curses', 'email', 'pywin.debugger',
'pywin.debugger.dbgcon', 'pywin.dialogs', 'tcl',
'Tkconstants', 'Tkinter']
packages = []
dll_excludes = []
dll_includes = []
a = Analysis(['myscript.py'],
pathex=['C:\\Users\\Me\\Documents\\MyFolder','C:\\Python27\\Lib\\site-packages\\mpl_toolkits\\basemap\\*'],
hiddenimports=[],
hookspath=None,
runtime_hooks=None)
pyz = PYZ(a.pure)
exe = EXE(pyz,
a.scripts,
a.binaries - dll_excludes + dll_includes + data_files,
name='MyApplication.exe',
debug=False,
strip=None,
upx=True,
console=True )
coll = COLLECT(exe,
a.binaries,
a.zipfiles,
a.datas,
strip=None,
upx=True,
name='MyApplication')
I want this to be a one-file executable so the data files should be packed
within the executable. On other pyinstallers I usually haven't had issues with
the MEIPASS. However, I need to use 2.1 because of Matplotlib and Basemap. If
someone can build this exe perfectly -- can you please tell me what I need to
adjust? Thanks!
* **_EDIT_ ***
If anyone can figure out how to do this with py2exe -- that would be great
too. Any way that I can get this into a single executable would be worth it!
Answer: I think I see the problem. You're not feeding data_files into your Analysis
object. Here's how I add my data files in my .spec file:
a = Analysis(....)
a.datas += [('7z.dll', '7z.dll', 'DATA')]
a.datas += [('7z.exe', '7z.exe', 'DATA')]
a.datas += [('collection.xml', 'collection.xml', 'DATA')]
a.datas += [('License.html', 'License.html', 'DATA')]
pyz = PYZ(a.pure)
exe = EXE(pyz,
a.scripts + [('O', '', 'OPTION')],
a.binaries,
a.zipfiles,
a.datas,
name=os.path.join('dist', 'blah.exe'),
debug=False,
strip=None,
upx=False,
console=True,
icon=r'..\NCM.ico')
Notice I'm not using COLLECT() at all.
If you checkout the 2.1 documentation at: [PyInstaller Spec File
Operation](http://pythonhosted.org/PyInstaller/#spec-file-operation) you'll
notice that COLLECT() isn't used for --onefile mode.
If you look at the extracted directory pointed at by sys._MEIPASS you'll
probably notice that with your spec file that the data file simply isn't there
at all.
I hope this helps.
|
List Comprehension Mystery - Python
Question: I have created two CSV lists. One is an original CSV file, the other is a
DeDuped version of that file. I have read each into a list and for all intents
and purposes they are the same format. Each list item is a string.
I am trying to use a list comprehension to find out which items were deleted
by the duplication. The length of the original is 16939 and the list of the
DeDupe is 15368. That's a difference of 1571, but my list comprehension length
is 368. Ideas?
deduped = open('account_de_ex.csv', 'r')
deduped_data = deduped.read()
deduped.close()
deduped = deduped_data.split("\r")
#read in file with just the account names from the full account list
account_names = open('account_names.csv', 'r')
account_data = account_names.read()
account_names.close()
account_names = account_data.split("\r")
# Get all the accounts that were deleted in the dedupe - i.e. get the duplicate accounts
dupes = [ele for ele in account_names if ele not in deduped]
**Edit:** For some notes in the comments, here is a test on my list comp and
the lists themselves. Pretty much the same difference, 20 or so off. Not the
1500 i need! thanks!
print len(deduped)
deduped = set(deduped)
print len(deduped)
print len(account_names)
account_names = set(account_names)
print len(account_names)
15368
15368
16939
15387
Answer: Try running this code and see what it reports. This requires Python 2.7 or
newer for `collections.Counter` but you could easily write your own counter
code, or copy my example code from another answer: [Python : List of dict, if
exists increment a dict value, if not append a new
dict](http://stackoverflow.com/questions/1692388/python-list-of-dict-if-
exists-increment-a-dict-value-if-not-append-a-new-dic/1692428#1692428)
from collections import Counter
# read in original records
with open("account_names.csv", "rt") as f:
rows = sorted(line.strip() for line in f)
# count how many times each row appears
counts = Counter(rows)
# get a list of tuples of (count, row) that only includes count > 1
dups = [(count, row) for row, count in counts.items() if count > 1]
dup_count = sum(count-1 for count in counts.values() if count > 1)
# sort the list from largest number of dups to least
dups.sort(reverse=True)
# print a report showing how many dups
for count, row in dups:
print("{}\t{}".format(count, row))
# get de-duped list
unique_rows = sorted(counts)
# read in de-duped list
with open("account_de_ex.csv", "rt") as f:
de_duped = sorted(line.strip() for line in f)
print("List lengths: rows {}, uniques {}/de_duped {}, result {}".format(
len(rows), len(unique_rows), len(de_duped), len(de_duped) + dup_count))
# lists should match since we sorted both lists
if unique_rows == de_duped:
print("perfect match!")
else:
# if lists don't match, find out what is going on
uniques_set = set(unique_rows)
deduped_set = set(de_duped)
# find intersection of the two sets
x = uniques_set.intersection(deduped_set)
# print differences
if x != uniques_set:
print("Rows in original that are not in deduped:\n{}".format(sorted(uniques_set - x)))
if x != deduped_set:
print("Rows in deduped that are not in original:\n{}".format(sorted(deduped_set - x)))
|
Error opening Python Serial Port
Question: I am attempting to run a script that a classmate has written and demonstrated
to me. So I know the code is correct, it just has to do with the difference in
how our machines are configured. Here is the code:
#!/usr/bin/python
#import statements
import serial
import os
import time
#global constants
control_byte = '\n'
ACL_1_X_addr = ord('X')
ACL_1_Y_addr = ord('Y')
ACL_1_Z_addr = ord('Z')
GYRO_1_X_addr = ord('I')
GYRO_1_Y_addr = ord('J')
GYRO_1_Z_addr = ord('K')
#clear the screen
os.system('clear')
#initialize the serial port
s = serial.Serial()
s.port = 10
s.baudrate = 56818
s.open()
Everything runs up to the last line `s.open` where it gives me the error:
Traceback (most recent call last):
File "serial_reader.py", line 25, in <module>
s.open()
File "/usr/lib/python2.7/dist-packages/serial/serialposix.py", line 282, in open
self._reconfigurePort()
File "/usr/lib/python2.7/dist-packages/serial/serialposix.py", line 311, in _reconfigurePort
raise SerialException("Could not configure port: %s" % msg)
serial.serialutil.SerialException: Could not configure port: (5, 'Input/output error')
My guess is I need to change the port I am opening, but I have tried a few
others without and luck. Anybody have any ideas of what is happening?
Btw, I am using Python 2.7.4
Answer: Im guessing you need something like `s.port="/dev/ttys0"` ... the numeric port
is for "COM10" style windows ports that dont have a mapping into the
filesystem
your serial ports should list if you do `ls/dev/tty*`
|
decorate xml subtree with lxml
Question: I want to transform this xml tree
<doc>
<a>
<op>xxx</op>
</a>
</doc>
to
<doc>
<a>
<cls>
<op>xxx</op>
</cls>
</a>
</doc>
I use this python code
from lxml import etree
f = etree.fromstring('<doc><a><op>xxx</op></a></doc>')
node_a = f.xpath('/doc/a')[0]
ele = etree.Element('cls')
node_a.insert(0, ele)
node_cls = f.xpath('/doc/a/cls')[0]
node_op = f.xpath('/doc/a/op')[0]
node_cls.append(node_op)
print etree.tostring(f, pretty_print=True)
Is it the best solution ?
Now I want to obtain
<cls>
<doc>
<a>
<op>xxx</op>
</a>
</doc>
</cls>
I am unable to find any solution.
Thanks for your help.
Answer: I prefer to use [beautifulsoup](/questions/tagged/beautifulsoup "show
questions tagged 'beautifulsoup'") better than [lxml](/questions/tagged/lxml
"show questions tagged 'lxml'"). I find it easier to handle.
Both problems can be solved using the same approach, first find the element,
get its parent, create the new element and put the old one inside it.
from bs4 import BeautifulSoup
import sys
soup = BeautifulSoup(open(sys.argv[1], 'r'), 'xml')
for e in soup.find_all(sys.argv[2]):
p = e.parent
cls = soup.new_tag('cls')
e_extracted = e.extract()
cls.append(e_extracted)
p.append(cls)
print(soup.prettify())
The script accepts two arguments, thr first one is the `xml` file and second
one the tag to surround with new tag. Run it like:
python3 script.py xmlfile op
That yields:
<?xml version="1.0" encoding="utf-8"?>
<doc>
<a>
<cls>
<op>
xxx
</op>
</cls>
</a>
</doc>
For `<doc>`, run it like:
python3 script.py xmlfile doc
With following result:
<?xml version="1.0" encoding="utf-8"?>
<cls>
<doc>
<a>
<op>
xxx
</op>
</a>
</doc>
</cls>
|
Can you set conditional dependencies for Python 2 and 3 in setuptools?
Question: When releasing a Python egg with support for both Python 2 and 3, can you
specify dependencies that change depending on which version you're using? For
example, if you use `dnspython` for Python 2, there is a Python 3 version that
is called `dnspython3`.
Can you write your `setuptools.setup()` function in such a way that your egg
is useable to both versions if that is the only roadblock, i.e., if you have
run `2to3` to ensure that the rest of your library is compatible with both
versions.
I have looked through these documents and can't seem to find the answer this
question:
* [Porting Python 2 Code to Python 3](http://docs.python.org/3.3/howto/pyporting.html)
* [setuptools' Declaring Dependencies](http://pythonhosted.org/distribute/setuptools.html#declaring-dependencies)
* [Travis CI Python documentation](http://about.travis-ci.org/docs/user/languages/python/)
* [pip Requirements Files](http://www.pip-installer.org/en/latest/cookbook.html#requirements-files)
Answer: Bogdan's comment helped point me on my way. I thought I'd post what I did in
case anyone else has my problem.
For the example in the question, I did exactly what Bogdan suggested:
## setup.py
import sys
if sys.version_info[0] == 2:
dnspython = "dnspython"
elif sys.version_info[0] == 3:
dnspython = "dnspython3"
setup(
... <snip> ...
install_requires=[
"%s >= 1.10.0" % dnspython,
]
)
However, this still has the issue of pip-style dependencies for Travis and
`tox` (I'm not sure why, given Bogdan's second comment). To work around this
problem, I created two extra requirements files, as shown below:
## requirements-py2.txt
dnspython>=1.10.0
## requirements-py3.txt
dnspython3>=1.10.0
Then for Travis, I made use of some environment variables that I gleaned from
the [tornado
.travis.yml](https://github.com/facebook/tornado/blob/b3520e5ded5a31c4ab8a96eea63304b1c64c2f7c/.travis.yml):
## .travis.yml
install:
- if [[ $TRAVIS_PYTHON_VERSION == 2* ]]; then pip install -r requirements-py2.txt --use-mirrors; fi
- if [[ $TRAVIS_PYTHON_VERSION == 3* ]]; then pip install -r requirements-py3.txt --use-mirrors; fi
Lastly, for `tox`, I had to use a rather hackish method of using these
multiple requirements files.
## tox.ini
[testenv:py27]
deps = -rrequirements-py2.txt
[testenv:py33]
deps = -rrequirements-py3.txt
|
I can't execute command inside vim but it can be executed in shell?
Question: I use vim, mac os x, virtualenv and zsh to develop python.
But i found a quite strange thing that, After i using virtualenv to create a
environment and install a python package with `pip install fabric` and execute
`fab` in command line. It works well.
Then i open vim and execute `fab` with `:!fab`, it give me following error:
Traceback (most recent call last): │ * Restarting with reloader
File "/usr/local/bin/fab", line 5, in <module> │ * Detected change in '/Users/ccheng/workspace/rms-rest/rms/account.py', reloading
from pkg_resources import load_entry_point │ * Restarting with reloader
File "build/bdist.macosx-10.9-intel/egg/pkg_resources.py", line 2793, in <module> │ * Detected change in '/Users/ccheng/workspace/rms-rest/rms/account.py', reloading
│ * Restarting with reloader
File "build/bdist.macosx-10.9-intel/egg/pkg_resources.py", line 673, in require │ * Detected change in '/Users/ccheng/workspace/rms-rest/rms/rms.py', reloading
def subscribe(self, callback): │ * Restarting with reloader
File "build/bdist.macosx-10.9-intel/egg/pkg_resources.py", line 576, in resolve │ * Detected change in '/Users/ccheng/workspace/rms-rest/rms/rms.py', reloading
plugin_env, full_env=None, installer=None, fallback=True │ * Restarting with reloader
pkg_resources.DistributionNotFound: Fabric==1.8.0 │ * Detected change in 'run.py', reloading
│ * Restarting with reloader
shell returned 1
I think it was caused by when i open vim, some `python path` variable has been
reset, so i can't find the packages installed in virtualenv.
Answer: I solve the issue through set a default shell in terminal configuration. I
don't know what is different between this and setting default shell using
'chsh', but it works. Thanks everyone.
|
Cleaning a tab delimited file with unescaped newlines
Question: I have a tab-delimited file where one of the columns has occasional newlines
that haven't been escaped (enclosed in quotes):
JOB REF Comment V2 Other
1 3 45 This was a small job NULL sdnsdf
2 4 456 This was a large job and I have to go onto a new line,
but I didn't properly escape so it's on the next row whoops! NULL NULL
3 7 354 NULL NULL NULL
# dat <- readLines("the-Dirty-Tab-Delimited-File.txt")
dat <- c("\tJOB\tREF\tComment\tV2\tOther", "1\t3\t45\tThis was a small job\tNULL\tsdnsdf",
"2\t4\t456\tThis was a large job and I have\t\t", "\t\"to go onto a new line, but I didn't properly escape so it's on the next row whoops!\"\tNULL\tNULL\t\t",
"3\t7\t354\tNULL\tNULL\tNULL")
I understand that this might not be possible, but these bad newlines only
occur in the one field (the 10thcolumn). I'm interested in solutions in R
(preferable) or python.
My thoughts were to introduce a regular expression looking for a newline after
10 and only 10 tabs. I started off by using `readLines` and trying to remove
all newlines that occur at the end of a space + word:
dat <- gsub("( [a-zA-Z]*)\t\n", "\\1", dat)
but it seems difficult to reverse the line structure of `readLines`. What
should I be doing?
**Edit** : Sometimes two newlines occurr (i.e. where the user has put a blank
line between paragraphs in a comment field. An example is below (the desired
result is that this should be made into a single row)
140338 28855 WA 2 NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL 1 NULL NULL NULL NULL NULL NULL NULL NULL 1000 NULL NULL NULL NULL NULL NULL YNNNNNNN (Some text with two newlines)
The remainder of the text beneath two newlines NULL NULL NULL 3534a NULL email NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL
Answer: Here's my answer in Python.
import re
# This pattern should match correct data lines and should not
# match "continuation" lines (lines added by the unquoted newline).
# This pattern means: start of line, then a number, then white space,
# then another number, then more white space, then another number.
# This program won't work right if this pattern isn't correct.
pat = re.compile("^\d+\s+\d+\s+\d+")
def collect_lines(iterable):
itr = iter(iterable) # get an iterator
# First, loop until we find a valid line.
# This will skip the first line with the "header" info.
line = next(itr)
while True:
line = next(itr)
if pat.match(line):
# found a valid line; hold it as cur
cur = line
break
for line in itr:
# Look at the line after cur. Is it a valid line?
if pat.match(line):
# Line after cur is valid!
yield cur # output cur
cur = line # hold new line as new cur
else:
# Line after cur is not valid; append to cur but do not output yet.
cur = cur.rstrip('\r\n') + line
yield cur
data = """\
JOB REF Comment V2 Other
@@@1 3 45 This was a small job NULL sdnsdf
@@@2 4 456 This was a large job and I have to go onto a new line,
@@@ but I didn't properly escape so it's on the next row whoops! NULL NULL
@@@3 7 354 NULL NULL NULL
"""
lines = data.split('@@@')
for line in collect_lines(lines):
print(">>>{}<<<".format(line))
For your real program:
with open("filename", "rt") as f:
for line in collect_lines(f):
# do something with each line
EDIT: I reworked this and added more comments. I also think I fixed the
problem you were seeing.
When I joined a line to `cur`, I didn't strip the newline off the end of `cur`
first. So, the joined line was still a split line, and when it was written out
to the file this didn't really fix things. Try it now.
I reworked the test data so that the test lines would have newlines on them.
My original test split the input on newlines, so the split lines didn't
contain any newlines. Now the lines will each end in a newline.
|
Cannot Import Daemon class
Question: I am trying to run a daemon but I am not able to import the module daemon.
My imports:
import os
import sys
import time
from daemon import Daemon
**Traceback (most recent call last): File "parser.py", line 11, in from daemon
import Daemon ImportError: cannot import name Daemon**
I tried with python-daemon package but it didn't solve my problem. Any idea?
Thanks.
Answer: There is just no class named `Daemon`. From [PEP
3143](http://www.python.org/dev/peps/pep-3143/#example-usage), the basic usage
is:
import daemon
from spam import do_main_program
with daemon.DaemonContext():
do_main_program()
I guess, you should follow this guidelines.
|
Send pandas dataframe data as html e-mail
Question: I want to send a pandas dataframe data as an HTML e-mail. Based on
[this](http://stackoverflow.com/questions/18096748/pandas-dataframes-to-html-
highlighting-table-rows) post I could create an html with the dataframe. Code
import pandas as pd
import numpy as np
HEADER = '''
<html>
<head>
</head>
<body>
'''
FOOTER = '''
</body>
</html>
'''
df = pd.DataFrame([[1.1, 1.1, 1.1, 2.6, 2.5, 3.4,2.6,2.6,3.4,3.4,2.6,1.1,1.1,3.3], list('AAABBBBABCBDDD')]).T
with open('test.html', 'w') as f:
f.write(HEADER)
f.write(df.to_html(classes='df'))
f.write(FOOTER)
Now I want to send this as a html e-mail. I tried
[this](http://stackoverflow.com/questions/882712/sending-html-email-using-
python). Can not figure out how to attach the html file?
Answer: Finally found. This is the way it should be done.
filename = "test.html"
f = file(filename)
attachment = MIMEText(f.read(),'html')
msg.attach(attachment)
|
python-fu Copy an Image
Question: I've a color list file I read it into a python list and I'd like to create one
(or several) image(s) composed by squares with background color read from file
and as foreground html string of the color (written with white). I.e. I read
#ff0000 from input file then I create a 100x100 square with red background and
a white string "#ff0000" as foreground...and so on for each color in input
file.
This is my script:
#!/usr/bin/env python
from gimpfu import *
def readColors(ifc):
"""Read colors from input file and return a python list with all them"""
a = []
fd = open(ifc,"r")
for i in fd:
if not i.startswith("//"):#skip comment lines
a.append(i.rstrip('\n'))
return a
def rgb2html(col):
"""Converts a color: from (255,255,255) to #ffffff"""
r,g,b = col
return "#%x%x%x" % (r,g,b)
def html2rgb(col):
"""Converts a color: from #ffffff to (255,255,255)"""
s=col.strip('#')
r=int(s[:2],16)
g=int(s[2:4],16)
b=int(s[4:6],16)
return r,g,b
def nextColor():
"""Gets next html color from color list"""
col = nextColor.array[nextColor.counter]
nextColor.counter +=1
return col
def isNextColor():
"""Is there another color or list is over?"""
return nextColor.counter<isNextColor.colorslenght
def isPageEnded(y,YSIZE):
"""Is there enough room to draw another square?"""
return (y+100)>=YSIZE
def newPage(XSIZE,YSIZE):
"""Returns a new image"""
return gimp.Image(XSIZE,YSIZE,RGB)
def createImage(color,text):
"""Draws a square filled with color and white color text. It works!"""
gimp.set_foreground((255,255,255))#text color
gimp.set_background(color) #background color
image = gimp.Image(100,100,RGB)
back = gimp.Layer(image,"font",100,100,RGB_IMAGE,100,NORMAL_MODE)
image.add_layer(back,1)
back.fill(BACKGROUND_FILL)
lay = back.copy()
lay.name = "font"
image.add_layer(lay,0)
lay = pdb.gimp_text_fontname(image,None,2,100/4,text,2,True,18,PIXELS,"Sans")
image.merge_down(lay, NORMAL_MODE)
image.flatten()
return image
def drawRect(image,x,y):
"""Here I'd like to copy the result of createImage at current x,y position of current image. It doesn't work!"""
text = nextColor()
color = html2rgb(text)
img = createImage(color,text)
drawable = pdb.gimp_image_active_drawable(image)
image.disable_undo()
pdb.gimp_selection_none(image)
pdb.gimp_image_select_rectangle(image, 2, x, y, 100, 100)
if pdb.gimp_edit_named_copy_visible(img, "buffer"):
floating_sel = pdb.gimp_edit_named_paste(drawable, "buffer", TRUE)
pdb.gimp_selection_none(image)
image.flatten()
gimp.Display(image)#to debug
image.enable_undo()
def savePage(image,directory,filename):
"""Saves composed image to filename"""
drawable = pdb.gimp_image_active_drawable(image)
pdb.file_png_save(image, drawable, directory+"\\"+filename, filename, 0,9,1,0,0,1,1)
def draw(ifile,savedir,prefix):
"""Main method. it manage page's room, slicing it in several 100x100 squares"""
YSIZE = 1000
XSIZE = 1000
x = y = pc = 0
colorArray = readColors(ifile)
nextColor.counter = 0
nextColor.array = colorArray
isNextColor.colorslenght = len(colorArray)
pdb.gimp_context_push()
image = newPage(XSIZE,YSIZE)
while(isNextColor()):
drawRect(image,x,y)
x += 100 # move to next column
if x+100>=XSIZE:#move to next row
x = 0
y += 100
if isPageEnded(y,YSIZE):
savePage(image,savedir,prefix+str(pc)+".png")
gimp.Display(image)#to debug
pc += 1
image = newPage(XSIZE,YSIZE)
x = 0
y = 0
savePage(image,savedir,prefix+str(pc)+".png")#save last page
pdb.gimp_context_pop()
ifc = '<path to color list file>\\colors.txt'
ofc = '<path to output directory>\\palette'
prefix = 'table' #prefix for each file(i.e.: table0.png, table1.png...)
draw(ifc,ofc,prefix) #main method call
My current problem is with drawRect method. I can't copy image returned by
createImage method at coords x,y of bigger image in drawRect method. In
drawRect method I tried to used gimp's "copy into selection": select an area,
and paste in it stuff copied from another image. But I have a trouble with
layers and I can't get image copied at right position.
Just for completeness this are few lines from ifc file:
#b6ffff
#f079f3
#9979f3
#79c2f3
#7a79f3
#79f380
#f3799a
Thanks in advance for any help.
Alberto
Answer: Maybe it could be useful for someone else (it must be saved as "draw-
colors.py" and copied to GIMP 2/lib/gimp/2.0/plug-ins folder):
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from gimpfu import *
def readColors(ifile):
"""Read colors from input file and return a python list with all them"""
a = []
fd = open(ifile,"r")
for i in fd:
if not i.startswith('//'):
a.append(i)
return a
def rgb2html(col):
"""Converts a color: from (255,255,255) to #ffffff"""
r,g,b = col
return "#%x%x%x" % (r,g,b)
def html2rgb(col):
"""Converts a color: from #ffffff to (255,255,255)"""
s=col.strip('#')
r=int(s[:2],16)
g=int(s[2:4],16)
b=int(s[4:6],16)
return r,g,b
def nextColor():
"""Gets next html color from color list"""
col = html2rgb(nextColor.array[nextColor.counter])
nextColor.counter +=1
return col
def isNextColor():
"""Is there another color or list is over?"""
return nextColor.counter<isNextColor.colorslenght
def isPageEnded(y,sizey):
"""Is there enough room to draw another square?"""
return (y+100)>=sizey
def newPage(sizex,sizey):
"""Returns a new image"""
image = pdb.gimp_image_new(sizex, sizey, RGB)
layer = pdb.gimp_layer_new(image, sizex, sizey, RGB, "layer", 0, 0)
pdb.gimp_image_add_layer(image, layer, 0)
drw = pdb.gimp_image_active_drawable(image)
pdb.gimp_context_set_background((255,255,255))
pdb.gimp_drawable_fill(drw, BACKGROUND_FILL)
pdb.gimp_context_set_brush('Circle (01)')
return image
def savePage(image,filename):
"""Saves composed image to filename"""
layers = image.layers
last_layer = len(layers)-1
try:
disable=pdb.gimp_image_undo_disable(image)
pdb.gimp_layer_add_alpha(layers[0])
pdb.plug_in_colortoalpha(image,image.active_layer,(0,0,0))
layer = pdb.gimp_image_merge_visible_layers(image, 1)
enable = pdb.gimp_image_undo_enable(image)
pdb.file_png_save(image, image.active_layer, filename, filename, 0,9,1,0,0,1,1)
except Exception as e:
raise e
def drawRect(x,y,color,image):
"""draw a single square"""
text = rgb2html(color)
pdb.gimp_image_select_rectangle(image, 2, x, y, 100, 100)
pdb.gimp_context_set_background(color)
pdb.gimp_edit_fill(image.active_layer, 1)
try:
text_layer = pdb.gimp_text_fontname(image, None, x, y+(100/2), text, 2, 1, 18, 0, "Sans")
pdb.gimp_image_merge_down(image, text_layer, 0)
except Exception as e:
raise e
def draw(ifile,odir,prefix,sizex,sizey):
"""Main method. it manage page's room, slicing it in several 100x100 squares"""
colorArray = readColors(ifile)
nextColor.counter = 0
nextColor.array = colorArray
isNextColor.colorslenght = len(colorArray)
pc = x = y = 0
image = newPage(sizex,sizey)
try:
while(isNextColor()):
pdb.gimp_context_push()
drawRect(x,y,nextColor(),image)
x += 100#cambia colonna
if x+100>=sizex:#cambia riga
x = 0
y += 100
if isPageEnded(y,sizey):#salva pagina
savePage(image,odir+'\\'+prefix+str(pc)+".png")
pc += 1
image = newPage(sizex,sizey)
x = y = 0
savePage(image,odir+'\\'+prefix+str(pc)+".png")
pdb.gimp_context_pop()
except Exception as e:
raise e
register(
"draw-colors",
N_("Create a color map from a text color file"),
"Create a color map from a text color file",
"Alberto",
"@Copyright Alberto 2014",
"2014/10/21",
N_("Draw Colors..."),
"",
[
(PF_FILE, "ifile", N_("Color input file:"), 'default\\input\\colorfile\\path\\colorlist.txt'),
(PF_DIRNAME, "odir", N_("Path for png export:"), 'default\\output\\path'),
(PF_STRING, "prefix", N_("Filename prefix for export:"), "table"),
(PF_INT8, "sizex", N_("Image's x size:"), 1024),
(PF_INT8, "sizey", N_("Image's y size:"), 1024)
],
[],
draw, #main method call
menu="<Image>/Filters/Alberto",
domain=("gimp20-python", gimp.locale_directory)
)
main()
Output example: 
|
Continually match values to a list of keys and values in Python
Question: I have a list of keys:
Keys=['Description of Supplier:', 'Locally Produced:', 'Imported:', 'Female Managed:', 'Female Owned:', 'Closest Landmark:', '% National Staff:', '% International Staff:', 'Operating since:', 'Previous Name:']
I am looping over several web pages to retrieve the contents of the table as a
dictionary of values and keys:
webpage1={'Description of Supplier:': 'Hardware, farm tools, articles for office and school supplies (Quincaillerie, outils agricoles, articles pour bureau et articles scolaires)', 'Female Owned:': 'NO', 'Operating since:': '01/1990', 'Female Managed:': 'NO', '% National Staff:': '100', 'Locally Produced:': '100%', 'Previous Name:': ''}
webpage2={'Description of Supplier:': 'Produce, foods', 'Female Owned:': 'YES', 'Operating since:': '1987', 'Female Managed:': 'NO', '% National Staff:': '80', 'Locally Produced:': '100%', 'Previous Name:': 'Kshop'}
I want to combine the dictionaries by the keys:
newdict={'Description of Supplier:': ['Hardware, farm tools, articles for office and school supplies (Quincaillerie, outils agricoles, articles pour bureau et articles scolaires)','Produce, foods'], 'Female Owned:': ['NO','YES'], 'Operating since:': ['01/1990','1987'], 'Female Managed:': ['NO','NO'], '% National Staff:': ['100','80'], 'Locally Produced:': ['100%','100%] , 'Previous Name:': ['','kshop']}
However the values have to be in the right order ( I am writing them to a csv
file).
I am stuck on how to do this in the most efficient way. Any suggestions?
Thanks so much in advance!
Answer: Using
[`collections.defaultdict`](http://docs.python.org/2/library/collections.html#collections.defaultdict):
from collections import defaultdict
newdict = defaultdict(list)
for webpage in (webpage1, webpage2):
for key, value in webpage1.items():
newdict[key].append(value)
newdict = dict(newdict)
* * *
`newdict`:
{'% National Staff:': ['100', '80'],
'Description of Supplier:': ['Hardware, farm tools, articles for office and school supplies (Quincaillerie, outils agricoles, articles pour bureau et articles scolaires)',
'Produce, foods'],
'Female Managed:': ['NO', 'NO'],
'Female Owned:': ['NO', 'YES'],
'Locally Produced:': ['100%', '100%'],
'Operating since:': ['01/1990', '1987'],
'Previous Name:': ['', 'Kshop']}
|
Pythonic way to sparsely randomly populate array?
Question: Problem: Populate a 10 x 10 array of zeros randomly with 10 1's, 20 2's, 30
3's.
**I don't actually have to use an array, rather I just need coordinates for
the positions where the values would be. It's just easier to think of in terms
of an array.**
I have written several solutions for this, but they all seem to be non-
straight forward and non-pythonic. I am hoping someone can give me some
insight. My method has been using a linear array of 0--99, choosing randomly
(np.random.choice) 10 values, removing them from the array, then choosing 20
random values. After that, I convert the linear positions into (y,x)
coordinates.
import numpy as np
dim = 10
grid = np.arange(dim**2)
n1 = 10
n2 = 20
n3 = 30
def populate(grid, n, dim):
pos = np.random.choice(grid, size=n, replace=False)
yx = np.zeros((n,2))
for i in xrange(n):
delPos = np.where(grid==pos[i])
grid = np.delete(grid, delPos)
yx[i,:] = [np.floor(pos[i]/dim), pos[i]%dim]
return(yx, grid)
pos1, grid = populate(grid, n1, dim)
pos2, grid = populate(grid, n2, dim)
pos3, grid = populate(grid, n3, dim)
**Extra** Suppose when I populate the 1's, I want them all on one half of the
"array." I can do it using my method (sampling from grid[dim**2/2:]), but I
haven't figured out how to do the same with the other suggestions.
Answer: To generate the array, you can use
[`numpy.random.choice`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.choice.html).
np.random.choice([0, 1, 2, 3], size=(10,10), p=[.4, .1, .2, .3])
Then you can convert to coordinates. Note that `numpy.random.choice` generates
a random sample using probabilities `p`, and thus you are not guaranteed to
get the _exact_ proportions in `p`.
**Extra**
If you want to have all the `1`s on a particular side of the array, you can
generate two random arrays and then
[`hstack`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.hstack.html#numpy.hstack)
them. The trick is to slightly modify the probabilities of each number on each
side.
In [1]: import numpy as np
In [2]: rem = .1/3 # amount to de- / increase the probability for non-1s
In [3]: A = np.random.choice([0, 1, 2, 3], size=(5, 10),
p=[.4-rem, .2, .2-rem, .3-rem])
In [4]: B = np.random.choice([0, 2, 3], size=(5, 10), p=[.4+rem, .2+rem, .3+rem])
In [5]: M = np.hstack( (A, B) )
In [6]: M
Out[1]:
array([[1, 1, 3, 0, 3, 0, 0, 1, 1, 0, 2, 2, 0, 2, 0, 2, 3, 3, 2, 0],
[0, 3, 3, 3, 3, 0, 1, 3, 1, 3, 0, 2, 3, 0, 0, 0, 3, 3, 2, 3],
[1, 0, 0, 0, 1, 0, 3, 1, 2, 2, 0, 3, 0, 3, 3, 0, 0, 3, 0, 0],
[3, 2, 3, 0, 3, 0, 1, 2, 3, 2, 0, 0, 0, 0, 3, 2, 0, 0, 0, 3],
[3, 3, 0, 3, 3, 3, 1, 3, 0, 3, 0, 2, 0, 2, 0, 0, 0, 3, 3, 3]])
Here, because I'm putting _all_ the `1`s on the left, I double the probability
of `1` and decrease the probability of each number equally. The same logic
applies when creating the other side.
|
How Do I Queue My Python Locks?
Question: Is there a way to make python locks queued? I have been assuming thus far in
my code that threading.lock operates on a queue. It looks like it just gives
the lock to a random locker. This is bad for me, because the program (game)
I'm working is highly dependent on getting messages in the right order. Are
there queued locks in python? If so, how much will I lose on processing time?
Answer: I wholly agree with the comments claiming that you're probably thinking about
this in an unfruitful way. Locks provide serialization, and aren't _at all_
intended to provide ordering. The bog-standard, easy, and reliable way to
enforce an order is to use a `Queue.Queue`
CPython leaves it up to the operating system to decide in which order locks
are acquired. On most systems, that will appear to be more-or-less "random".
That cannot be changed.
That said, I'll show a way to implement a "FIFO lock". It's neither hard nor
easy - somewhere in between - and you shouldn't use it ;-) I'm afraid only you
can answer your "how much will I lose on processing time?" question - we have
no idea how heavily you use locks, or how much lock contention your
application provokes. You can get a rough feel by studying this code, though.
import threading, collections
class QLock:
def __init__(self):
self.lock = threading.Lock()
self.waiters = collections.deque()
self.count = 0
def acquire(self):
self.lock.acquire()
if self.count:
new_lock = threading.Lock()
new_lock.acquire()
self.waiters.append(new_lock)
self.lock.release()
new_lock.acquire()
self.lock.acquire()
self.count += 1
self.lock.release()
def release(self):
with self.lock:
if not self.count:
raise ValueError("lock not acquired")
self.count -= 1
if self.waiters:
self.waiters.popleft().release()
def locked(self):
return self.count > 0
Here's a little test driver, which can be changed in the obvious way to use
either this `QLock` or a `threading.Lock`:
def work(name):
qlock.acquire()
acqorder.append(name)
from time import sleep
if 0:
qlock = threading.Lock()
else:
qlock = QLock()
qlock.acquire()
acqorder = []
ts = []
for name in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
t = threading.Thread(target=work, args=(name,))
t.start()
ts.append(t)
sleep(0.1) # probably enough time for .acquire() to run
for t in ts:
while not qlock.locked():
sleep(0) # yield time slice
qlock.release()
for t in ts:
t.join()
assert qlock.locked()
qlock.release()
assert not qlock.locked()
print "".join(acqorder)
On my box just now, 3 runs using `threading.Lock` produced this output:
BACDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSUVWXYZT
ABCEDFGHIJKLMNOPQRSTUVWXYZ
So it's certainly not random, but neither is it wholly predictable. Running it
with the `QLock` instead, the output should always be:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
|
How to subtract the 'for' loop counter in Python?
Question: The structure that I know for the `for` loop in Python is as follows:
for i in range(10)
and then range is actually `[0,1,2,3,4,5,6,7,9]`. Now there is a problem here
and that is I want to reduce the counter of my loop by putting a line `i-=1`,
however that does not show the result I expect.
The following example is a structure same as `while(True)` in e.g. Java and C,
but here it works and the counter in the loop ignores the line which was
intended to reduce it.
for i in range(10):
i-=1
print i
And it generates the output:
-1
0
1
2
3
4
5
6
7
8
What should I do to get what I want with the `for` loop! I know it can be
easily done by a while as follows:
i=0
while(i<10):
i-=1
print i
i+=1
Here is the Java code as an example and I expect to see an endless loop
printing `-1`:
Here is the Java code:
import static java.lang.System.out;
public class HelloWorld{
public static void main(String []args){
for(int i=0;i<10;i++)
{
i--;
out.println(i);
}
}
}
Answer: The `range` function takes 3 arguments: start, stop, and step:
for i in range(-1, 9):
yield i
To go in reverse
for i in range(10, 0, -1):
yield i
Take a look at the
[documentation](http://docs.python.org/2/library/functions.html#range).
**Edit:**
Of course, there's nothing to stop you from using the `range` directly. Thus
`map(print, range(10, 0, -1))` will print them all to the screen, while
`range(10, 0, -1)` will give you access to the integers directly.
|
Python/Pygame, Where do I put my pygame.time.wait loop?
Question: So, I am in the middle of making two, very similar games (Exact details are
irrelevant right now.)
Anyway, I need to know where to insert my "pygame.time.wait" code.
The exact code I need looks like this:
pygame.time.wait(100)
score = score + 1
Currently, my code looks like so:
import sys, pygame
from pygame.locals import *
pygame.init()
size = width, height = 800,500
screen = pygame.display.set_mode(size)
pygame.display.set_caption("One Score (Created by - Not Really Working Lamp Productions:)")
WHITE = (255,255,255)
score = 0
screen.fill (WHITE)
myfont = pygame.font.SysFont("monospace", 16)
scoretext = myfont.render("Score = "+str(score), 1, (0,0,0))
screen.blit(scoretext, (5, 10))
disclaimertext = myfont.render("Copyright, 2013, Not Really Working Lamp Productions.", 1, (0,0,0))
screen.blit(disclaimertext, (5, 480))
while 1:
for event in pygame.event.get():
pygame.display.flip()
if event.type == pygame.QUIT:sys.exit()
The problem is though, that I don't know WHERE in this code I should put my
pygame.time.wait code. Could anybody fill me in? (I think it goes in the
"while 1:" loop, but I don't know where.)
Answer: Good afternoon. You should put your 'wait code' into the body of FOR circle:
while 1:
for event in pygame.event.get():
pygame.display.flip()
if event.type == pygame.QUIT:sys.exit()
pygame.time.wait(100)
score = score + 1
|
Python itertools combinations in distance
Question: I'm using `itertools.combinations` to match all the possible combinations of a
list.
My list looks something like
[[1,2],[2,3],[3,4],[4,5],[5,6]]
I understand how to get all the combinations, but if i want to use the
distance formula on each combination how would I go about doing this?
I don't know how to use each individual combination in this matter.
Answer: Simply loop over the output of the `combinations()` function:
for xy1, xy2 in combinations(inputlist, 2):
distance = calculate_distance(xy1, xy2)
This uses tuple unpacking; `combinations` produces tuples of two items each,
and Python assigns these to the two names. The first combination produced is
`([1, 2], [2, 3])`, but the loop assigns these to `xy1` (set to `[1, 2]` and
`xy2` (set to `[2, 3]`) respectively.
Quick demo just printing:
>>> from itertools import combinations
>>> inputlist = [[1,2],[2,3],[3,4],[4,5],[5,6]]
>>> for xy1, xy2 in combinations(inputlist, 2):
... print(xy1, xy2)
...
[1, 2] [2, 3]
[1, 2] [3, 4]
[1, 2] [4, 5]
[1, 2] [5, 6]
[2, 3] [3, 4]
[2, 3] [4, 5]
[2, 3] [5, 6]
[3, 4] [4, 5]
[3, 4] [5, 6]
[4, 5] [5, 6]
|
Accessing Single Entries in Sparse Matrix in Python
Question: I want to use sparse matrices for BOW feature representation. I have
experimented with coo_matrix from scipy, but it doesn't seem to support what I
want to do:
I would like to initialize a matrix of all zeros and then change a given entry
to one when appropriate. But when I try to index the matrix how I think I
should -- myMatrix[0][0] = 1 (or even myMatrix[0][0][0] =1), for example -- it
changes all the values in a row to 1. I want to just make a single entry 1.
I can do this easily with numpy matrices, but I would like to use sparse
matrices for space efficiency.
Answer: Using the right `sparse` type helps.
from scipy import sparse
M = sparse.lil_matrix((10,10))
M[1,1] = 1
M[5,5] = 1
# <10x10 sparse matrix of type '<type 'numpy.float64'>'
# with 2 stored elements in LInked List format>
`dok` also works. `csr` suggests using `lil`. 'coo' can't be set this way.
Once filled it is easy to convert to another format.
|
Django CompositeField subclass not overwriting __unicode__ method
Question: I'm using [django-composite-field](https://bitbucket.org/bikeshedder/django-
composite-field) to create a currency field that includes both a dollar_value
and a dollar_year (i.e., "$200 in 2008 dollars").
I have the following models in a Django app:
#models.py
from composite_field import CompositeField
class DollarField(CompositeField):
""" Composite field to associate dollar values with dollar-years."""
dollar_value = models.DecimalField(max_digits=8, decimal_places=2)
dollar_year = models.PositiveSmallIntegerField(
blank=False,
null=False,
validators=[
MinValueValidator(1980),
MaxValueValidator(2020)])
def __unicode__(self):
return self.dollar_year+"$: $"+self.dollar_value # "2012$: $149.95"
class ProductStandard(models.Model):
product = models.ForeignKey(Product)
standard_level = models.ForeignKey(StandardLevel)
price = DollarField()
When I access the `price` attribute of a `ProductStandard` instance, I expect
to see a formatted string like this: `2012$: $199.99`. Instead, I see
`DollarField(dollar_value=Decimal('199.99'), dollar_year=2012)`, which is the
return value of [the CompositeField `__repr__`
method](https://bitbucket.org/bikeshedder/django-composite-
field/src/398e3be0a96111212b71abce3b95fd306a1f4228/composite_field/base.py?at=default).
But since I've sublassed CompositeField and added my own `__unicode__` method,
shouldn't Django overwrite? Or am I misunderstanding something?
I'm using Django 1.5.4 with Python 2.7.3 and django-composite-field 0.1.
Answer: The `__repr__` you are seeing is actually not a `__repr__` of a
CompositeField, but of it's Proxy (refer to composite_field/base.py, line
104). So you would have to provide your own proxy, and override the `__repr__`
method there, like so:
class DollarField(CompositeField):
""" Composite field to associate dollar values with dollar-years."""
dollar_value = models.DecimalField(max_digits=8, decimal_places=2)
dollar_year = models.PositiveSmallIntegerField(
blank=False,
null=False,
validators=[
MinValueValidator(1980),
MaxValueValidator(2020)])
def get_proxy(self, model):
return DollarField.Proxy(self, model)
class Proxy(CompositeField.Proxy):
def __repr__(self):
return "%s$: $%s" % (self.dollar_year, self.dollar_value) # "2012$: $149.95"
of course, if you would like to leave `__repr__` as it is, you can override
`__unicode__` instead of `__repr__`, like you did. The difference is that:
print(mymodel.price)
would call the `__repr__`, while
print(unicode(mymodel.price))
would call the `__unicode__` method.
|
Taking Screen shots of specific size
Question: What imaging modules for python will allow you to take a specific size
screenshot (not whole screen)? I have tried PIL, but can't seem to make
ImageGrab.grab() select a small rectangle and i have tried PyGame but i can't
make it take a screen shot outside of it's main display panel
Answer: You can use [pyscreenshot](https://pypi.python.org/pypi/pyscreenshot) module.
The `pyscreenshot` module can be used to copy the contents of the screen to a
`PIL` image memory or file. You can install it using `pip`.
$ sudo pip install pyscreenshot
Usage:
import pyscreenshot as ImageGrab
# fullscreen
im=ImageGrab.grab()
im.show()
# part of the screen
im=ImageGrab.grab(bbox=(10,10,500,500))
im.show()
# to file
ImageGrab.grab_to_file('im.png')
|
Solving Symbolic Boolean variables in Python
Question: I need to solve a set of symbolic Boolean expressions like:
>>> solve(x | y = False)
(False, False)
>>> solve(x & y = True)
(True, True)
>>> solve (x & y & z = True)
(True, True, True)
>>> solve(x ^ y = False)
((False, False), (True, True))
Number of such variables is large (~200) so that Brute Force strategy is not
possible. I searched the web and found that
[Sympy](http://sympy.org/en/index.html) and
[Sage](http://www.sagemath.org/index.html) have symbolic manipulation
capabilities (particularly
[this](http://www.sagemath.org/doc/reference/logic/sage/logic/booleval.html)
and
[this](http://www.sagemath.org/doc/reference/polynomial_rings/sage/rings/polynomial/pbori.html)
may be useful). How can I do that?
EDIT: I mainly tried to manipulate such things:
>>> from sympy import *
>>> x=Symbol('x', bool=True)
>>> y=Symbol('y', bool=True)
>>> solve(x & y, x)
which results in `NotImplementedError`. Then I tried `solve(x * y, x)` which
gave `[0]` (I don't know what does it mean), `solve(x * y = True, x)` resulted
in a `SyntaxError`, `solve(x * y, True, x)` and `solve(x & y, True, x)` gave
an `AttributeError`. I don't know what else to try!
EDIT (2): I also found
[this](ftp://ftp.iitb.ac.in/packages/sagemath/doc/en/reference/sat/sat.pdf),
may be useful!
Answer: First, to correct a few things that are just blatently wrong in your question:
* `solve` solves for algebraic expressions. `solve(expr, x)` solves the equation expr = 0 for `x`.
* `solve(x | y = False)` and so on are invalid syntax. You cannot use `=` to mean equality in Python. See <http://docs.sympy.org/latest/tutorial/gotchas.html#equals-signs> (and I recommend reading the rest of that tutorial as well).
* As I mentioned in the answer to [another](http://stackoverflow.com/questions/19703284/boolean-operation-with-symbol-in-sympy) question, `Symbol('y', bool=True)` does nothing. `Symbol('x', something=True)` sets the `is_something` assumption on `x`, but `bool` is not a recognized assumption by any part of SymPy. Just use regular `Symbol('x')` for boolean expressions.
As some commenters noted, what you want is `satisfiable`, which implements a
SAT solver. `satisfiable(expr)` tells you if `expr` is satisfiable, that is,
if there are values for the variables in `expr` that make it true. If it is
satisfiable, it returns a mapping of such values (called a "model"). If no
such mapping exists, i.e., `expr` is a contradiction, it returns `False`.
Therefore, `satisfiable(expr)` is the same as solving for `expr = True`. If
you want to solve for `expr = False`, you should use `satisfiable(~expr)` (`~`
in SymPy means not).
In [5]: satisfiable(x & y)
Out[5]: {x: True, y: True}
In [6]: satisfiable(~(x | y))
Out[6]: {x: False, y: False}
In [7]: satisfiable(x & y & z)
Out[7]: {x: True, y: True, z: True}
Finally, note that `satisfiable` only returns one solution, because in general
this is all you want, whereas finding all the solutions in general is
extremely expensive, as there could be as many as `2**n` of them, where `n` is
the number of variables in your expression.
If however, you want to find all of them, the usual trick is to append your
original expression with `~E`, where `E` is the conjunction of the previous
solution. So for example,
In [8]: satisfiable(x ^ y)
Out[8]: {x: True, y: False}
In [9]: satisfiable((x ^ y) & ~(x & ~y))
Out[9]: {x: False, y: True}
The `& ~(x & ~y)` means that you don't want a solution where `x` is true and
`y` is false (think of `&` as adding extra conditions on your solution).
Iterating this way, you can generate all solutions.
|
Multiprocessing with numpy makes Python quit unexpectedly on OSX
Question: I've run into a problem, where Python quits unexpectedly, when running
multiprocessing with numpy. I've isolated the problem, so that I can now
confirm that the multiprocessing works perfect when running the code stated
below:
import numpy as np
from multiprocessing import Pool, Process
import time
import cPickle as p
def test(args):
x,i = args
if i == 2:
time.sleep(4)
arr = np.dot(x.T,x)
print i
if __name__ == '__main__':
x = np.random.random(size=((2000,500)))
evaluations = [(x,i) for i in range(5)]
p = Pool()
p.map_async(test,evaluations)
p.close()
p.join()
The problem occurs when I try to evaluate the code below. This makes Python
quit unexpectedly:
import numpy as np
from multiprocessing import Pool, Process
import time
import cPickle as p
def test(args):
x,i = args
if i == 2:
time.sleep(4)
arr = np.dot(x.T,x)
print i
if __name__ == '__main__':
x = np.random.random(size=((2000,500)))
test((x,4)) # Added code
evaluations = [(x,i) for i in range(5)]
p = Pool()
p.map_async(test,evaluations)
p.close()
p.join()
Please help someone. I'm open to all suggestions. Thanks. Note: I have tried
two different machines and the same problem occurs.
Answer: This is a known issue with multiprocessing and numpy on MacOS X, and a bit of
a duplicate of:
[segfault using numpy's lapack_lite with multiprocessing on osx, not
linux](http://stackoverflow.com/questions/9879371/segfault-using-numpys-
lapack-lite-with-multiprocessing-on-osx-not-linux)
<http://mail.scipy.org/pipermail/numpy-discussion/2012-August/063589.html>
The answer seems to be to use a different BLAS other than the Apple accelerate
framework when linking Numpy... unfortunate :(
|
Cannot import correct version of numpy on OS X Mavericks
Question: I have upgraded from Mountain Lion to Mavericks ande also updated Macports and
its outdated packages. I have installed numpy 1.7, but the problem is the one
used by python is still numpy 1.6. The following are some information about my
system.
`>> python -c 'import numpy; print numpy.__version__'` gives
1.6.2
which shows the active numpy version is 1.6.2
`>> port installed | grep numpy` gives
py27-numpy @1.7.1_0 (active)
which shows the active numpy version is 1.7.1_0
`>> port installed | grep python` gives
gnome-doc-utils @0.20.10_0+python27 (active)
gtk-doc @1.18_0+python27 (active)
ipython_select @0.3_1 (active)
opencv @2.4.6.1_2+python27 (active)
py27-ipython @0.13.2_0+notebook+parallel+scientific
py27-ipython @1.1.0_0+scientific
py27-ipython @1.1.0_0+notebook+parallel+scientific (active)
py27-wxpython-3.0 @2.9.5.0_0 (active)
py27-wxpython-devel @2.9.4.0_0
python24 @2.4.6_10 (active)
python27 @2.7.5_0
python27 @2.7.5_1 (active)
python_select @0.3_2
python_select @0.3_3 (active)
swig-python @2.0.9_0
swig-python @2.0.10_0 (active)
xorg-libxcb @1.9.1_0+python27 (active)
xorg-xcb-proto @1.8_0+python27 (active)
which shows, the active python version is python27.
Also, `port select python` gives
Available versions for python:
none
python24
python25-apple
python26-apple
python27
python27-apple (active)
Answer: You're using the apple-installed version of python, you can see this by the
fact that
port select python
gives you
python27-apple (active)
Remedy this with:
sudo port select python python27
* * *
If this:
import sys
print sys.path
still shows that python is looking in `/System/Library` instead of (or before)
`/opt/local/Library` for packages, then the apple versions of packages might
be imported. To solve this, you might be able to fix it by using a `.pth` file
with [`site`](http://docs.python.org/2/library/site.html) to modify your
[`sys.path`](http://docs.python.org/2/library/sys.html#sys.path).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.