text
stringlengths 226
34.5k
|
---|
Python insert text after last match in search
Question: I would like to find the last line matching a certain pattern, in python. What
I am trying to do is find the last line that contains a certain item
(line_end), and insert a block of information as a few new lines after it. So
far I have:
text = open( path ).read()
match_found=False
for line in text.splitlines():
if line_pattern in line:
match_found=True
if not match_found:
(`line_end='</PropertyGroup>`' and not sure how to use regex even with nice
search words) Can somebody help with advice on how to find the last search
item, and not go beyond, so that I can insert a block of text right there ?
Thank you.
Answer: Using [re](http://docs.python.org/library/re.html)
import re
text = open( path ).read()
match_found=False
matches = re.finditer(line_pattern, text)
m = None # optional statement. just for clarification
for m in matches:
match_found=True
pass # just loop to the end
if (match_found):
m.start() # equals the starting index of the last match
m.end() # equals the ending index of the last match
# now you can do your substring of text to add whatever
# you wanted to add. For example,
text[1:m.end()] + "hi there!" + text[(m.end()+1):]
|
Why my merge sort in python exceeded maximum recursion depth?
Question: I am learning MIT's open course 6.046 "Introduction to Algorithms" in Youtube,
and I was trying to implement the merge sort in python.
My code is
def merge(seq_list, start, middle, end):
left_list = seq_list[start:middle]
left_list.append(float("inf"))
right_list = seq_list[middle:end]
right_list.append(float("inf"))
i = 0
j = 0
for k in range(start, end):
if left_list[i] < right_list[j]:
seq_list[k] = left_list[i]
i = i + 1
else:
seq_list[k] = right_list[j]
j = j + 1
def merge_sort(seq_list, start, end):
if start < end:
mid = len(seq_list)/2
merge_sort(seq_list[0:mid], start, mid)
merge_sort(seq_list[mid:], mid, end)
merge(seq_list, start, mid, end)
And the unittest code is
import unittest
from sorting import *
class SortingTest(unittest.TestCase):
def testMergeSort(self):
test_list = [3, 4, 8, 0, 6, 7, 4, 2, 1, 9, 4, 5]
merge_sort(test_list, 0, 9)
self.assertEqual(test_list, [0, 1, 2, 3, 4, 4, 4, 5, 6, 7, 8, 9])
def testMerge(self):
test_list = [13,17,18,9,2,4,5,7,1,2,3,6,0,38,12]
merge(test_list, 4, 8, 12)
self.assertEqual(test_list, [13,17,18,9,1,2,2,3,4,5,6,7,0,38,12])
if __name__ == "__main__":
unittest.main()
The function merge() seems work perfectly, but the merge_sort() function was
wrong, and I don't know what's going on. The terminal show me:
> RuntimeError: maximum recursion depth exceeded
Answer: You need to add a base clause when the list is empty or of size 1, other wise
you keep "shrinking" an empty list, [and actually stay with the same list].
**EDIT:**
Also, I think it is actually deriving from a different bug: **you are
using`len(seq)` some times, and `start`,`end` sometimes** \- you should just
stick to one of them.
mid = len(seq_list)/2
merge_sort(seq_list[0:mid], start, mid)
merge_sort(seq_list[mid:], mid, end)
Have a look on the test case `[0,1,2,3]`
start = 0, end = 3 -> mid = 2
Now you recurse with
mergesort([2,3],2,3) #2 == mid, 3 == end
And later you will set:
mid = len([2,3])/2 == 1
and try recursing again with
mergesort([3],1,3)
You will never reach the "stop condition" of `start >= end`, because `end`
never changes, and is out of the current list's bounds!
**Another bug:**
merge_sort(seq_list[0:mid], start, mid)
does not do anything on `seq_list`, it does not change it - it only changes
the new list object you passd to the recursion, and thus `merge()` will also
fail.
|
Django django-extensions commands unavailable ( graph_models )
Question: I'm trying to install django-extensions + graphviz + pygraph but i can't. I
have done the following steps ( under Ubuntu ):
sudo apt-get install graphviz libgraphviz-dev graphviz-dev python-pygraphviz
in the project virtualenv (running python 2.7.2+):
source <path to virtualenv>/bin/activate
pip install django django-extensions
if i run
which python
it selects the python in my virtualenv, so the python i'm using is the right
one. in the virtualenv's site-package i have pygraphviz and django-extensions
python manage.py shell
import django_extensions
import pygraphviz
RUNS OK
in my django project i have added 'django_extensions' in my INSTALLED_APPS
But when i run
python manage.py help
i can't see the commands and they are unavailable.
python manage.py graph_models -a -g -o model.png
Unknown command: 'graph_models'
Type 'manage.py help' for usage.
How can I fix this ? Thanks!
Answer: Run this in `manage.py shell`:
from django.conf import settings; 'django_extensions' in settings.INSTALLED_APPS
If it doesn't return True, then it means that you didn't add
'django_extensions' properly in INSTALLED_APPS, and that would be the only
reason why Django doesn't find the command.
|
Intersection in sqlite3 in Python
Question: I am trying to extract data that corresponds to a stock that is present in
both of my data sets (given in a code below).
This is my data:
#(stock,price,recommendation)
my_data_1 = [('a',1,'BUY'),('b',2,'SELL'),('c',3,'HOLD'),('d',6,'BUY')]
#(stock,price,volume)
my_data_2 = [('a',1,5),('d',6,6),('e',2,7)]
Here are my questions:
Question 1:
I am trying to extract price, recommendation, and volume that correspond to
asset 'a'. Ideally I would like to get a tuple like this:
(u'a',1,u'BUY',5)
Question 2:
What if I wanted to get intersection for all the stocks (not just 'a' as in
Question 1), in this case it is stock 'a', and stock 'd', then my desired
output becomes:
(u'a',1,u'BUY',5)
(u'd',6,u'BUY',6)
How should I do this?
Here is my try (Question 1):
import sqlite3
my_data_1 = [('a',1,'BUY'),('b',2,'SELL'),('c',3,'HOLD'),('d',6,'BUY')]
my_data_2 = [('a',1,5),('d',6,6),('e',2,7)]
#I am using :memory: because I want to experiment
#with the database a lot
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute('''CREATE TABLE MY_TABLE_1
(stock TEXT, price REAL, recommendation TEXT )''' )
c.execute('''CREATE TABLE MY_TABLE_2
(stock TEXT, price REAL, volume REAL )''' )
for ele in my_data_1:
c.execute('''INSERT INTO MY_TABLE_1 VALUES(?,?,?)''',ele)
for ele in my_data_2:
c.execute('''INSERT INTO MY_TABLE_2 VALUES(?,?,?)''',ele)
conn.commit()
# The problem is with the following line:
c.execute( 'select* from my_table_1 where stock = ? INTERSECT select* from my_table_2 where stock = ?',('a','a') )
for entry in c:
print entry
I get no error, but also no output, so something is clearly off.
I also tried this line:
c.execute( 'select* from my_table_1 where stock = ? INTERSECT select volume from my_table_2 where stock = ?',('a','a')
but it does not work, I get this error:
c.execute( 'select* from my_table_1 where stock = ? INTERSECT select volume from my_table_2 where stock = ?',('a','a') )
sqlite3.OperationalError: SELECTs to the left and right of INTERSECT do not have the same number of result columns
I understand why I would have different number of resulting columns, but don't
quite get why that triggers an error.
How should I do this?
Thank You in advance
Answer: It looks like those two questions are really the same question.
**Why your query doesn't work:** Let's reformat the query.
SELECT * FROM my_table_1 WHERE stock=?
INTERSECT
SELECT volume FROM my_table_2 WHERE stock=?
There are two queries in the intersection,
1. `SELECT * FROM my_table_1 WHERE stock=?`
2. `SELECT volume FROM my_table_2 WHERE stock=?`
The meaning of "intersect" is "give me the rows that are in both queries".
That doesn't make any sense if the queries have a different number of columns,
since it's impossible for any row to appear in both queries.
Note that `SELECT volume FROM my_table_2` isn't a very useful query, since it
doesn't tell you which stock the volume belongs to. The query will give you
something like `{100, 15, 93, 42}`.
**What you're actually trying to do:** You want a join.
SELECT my_table_1.stock, my_table_2.price, recommendation, volume
FROM my_table_1
INNER JOIN my_table_2 ON my_table_1.stock=my_table_2.stock
WHERE stock=?
Think of join as "glue the rows from one table onto the rows from another
table, giving data from both tables in a single row."
It's bizarre that the price appears in both tables; when you write the query
with the join you have to decide whether you want `my_table_1.price` or
`my_table_2.price`, or whether you want to join on
`my_table_1.price=my_table_2.price`. You may want to consider redesigning your
schema so this doesn't happen, it may make your life easier.
|
Trying to make simple minesweeper game in python
Question: Trying to make simple minesweeper game in python, but have one problem. I have
a 7x7 board of x's and when the player enters a row and column it deletes the
column and replaces it with a -. I also tried to have a 1 appear if the
players guess one space away, but its not working and I can't figure out why.
Instead it ends the loop. Below is what I have done. Its probably a simple fix
but i cant see it. Thanks for the help! print("Welcome to Minesweeper/n")
import random
LA=["X","X","X","X","X","X","X"]
LB=["X","X","X","X","X","X","X"]
LC=["X","X","X","X","X","X","X"]
LD=["X","X","X","X","X","X","X"]
LE=["X","X","X","X","X","X","X"]
LF=["X","X","X","X","X","X","X"]
LG=["X","X","X","X","X","X","X"]
print("", LA, "\n" , LB, "\n" , LC, "\n" , LD, "\n" , LE, "\n" ,
LF, "\n" , LG, "\n")
print("\n select row starting from top = 1 and column from left = 0")
numa = random.randint(1,7)
numb = random.randint(0,6)
MINE = "O"
row=9
column = 9
one = "1"
blank = "-"
while row != numa and column != numb:
print("", LA, "\n" , LB, "\n" , LC, "\n" , LD, "\n" , LE, "\n" ,
LF, "\n" , LG, "\n")
#cheeter
print(numa , "" , numb)
row = int(input("\nEnter row"))
column = int(input("\nEnter column"))
columA = column + 1
columB = column - 1
rowA = row + 1
rowB = row - 1
if rowA == numa and column == numb:
if row ==1:
del LA[column]
LA.insert(column, one)
if row ==2:
del LB[column]
LB.insert(column, one)
if row ==3:
del LC[column]
LC.insert(column, one)
if row ==4:
del LD[column]
LD.insert(column, one)
if row ==5:
del LE[column]
LE.insert(column, one)
if row ==6:
del LF[column]
LF.insert(column, one)
if row ==7:
del LG[column]
LG.insert(column, one)
elif rowB == numa and column == numb:
if row ==1:
del LA[column]
LA.insert(column, one)
if row ==2:
del LB[column]
LB.insert(column, one)
if row ==3:
del LC[column]
LC.insert(column, one)
if row ==4:
del LD[column]
LD.insert(column, one)
if row ==5:
del LE[column]
LE.insert(column, one)
if row ==6:
del LF[column]
LF.insert(column, one)
if row ==7:
del LG[column]
LG.insert(column, one)
elif row == numa and columA == numb:
if row ==1:
del LA[column]
LA.insert(column, one)
if row ==2:
del LB[column]
LB.insert(column, one)
if row ==3:
del LC[column]
LC.insert(column, one)
if row ==4:
del LD[column]
LD.insert(column, one)
if row ==5:
del LE[column]
LE.insert(column, one)
if row ==6:
del LF[column]
LF.insert(column, one)
if row ==7:
del LG[column]
LG.insert(column, one)
elif row == numa and columB == numb:
if row ==1:
del LA[column]
LA.insert(column, one)
if row ==2:
del LB[column]
LB.insert(column, one)
if row ==3:
del LC[column]
LC.insert(column, one)
if row ==4:
del LD[column]
LD.insert(column, one)
if row ==5:
del LE[column]
LE.insert(column, one)
if row ==6:
del LF[column]
LF.insert(column, one)
if row ==7:
del LG[column]
LG.insert(column, one)
else:
if row ==1:
del LA[column]
LA.insert(column, blank)
if row ==2:
del LB[column]
LB.insert(column, blank)
if row ==3:
del LC[column]
LC.insert(column, blank)
if row ==4:
del LD[column]
LD.insert(column, blank)
if row ==5:
del LE[column]
LE.insert(column, blank)
if row ==6:
del LF[column]
LF.insert(column, blank)
if row ==7:
del LG[column]
LG.insert(column, blank)
if row ==1:
del LA[column]
LA.insert(column, MINE)
if row ==2:
del LB[column]
LB.insert(column, MINE)
if row ==3:
del LC[column]
LC.insert(column, MINE)
if row ==4:
del LD[column]
LD.insert(column, MINE)
if row ==5:
del LE[column]
LE.insert(column, MINE)
if row ==6:
del LF[column]
LF.insert(column, MINE)
if row ==7:
del LG[column]
LG.insert(column, MINE)
print("", LA, "\n" , LB, "\n" , LC, "\n" , LD, "\n" , LE, "\n" ,
LF, "\n" , LG, "\n")
print("Game over")
input("Press enter to quit")
Answer: I think your problem is in the loop condition:
while row != numa and column != numb:
That will enter the loop only if there is no mine in **either** the row or the
column. You need to combine them with or, not with and:
while row != numa or column != numb:
This way it will enter the loop unless both the row and the column corresponds
to the position the mine is on.
|
python keyring download error
Question: I keep getting this error when I try to install a package:
Download error on http://keyring-python.org/: (-2, 'Name or service not known') -- Some packages may not be found!
Download error on http://home.python-keyring.org/: (-3, 'Temporary failure in name resolution') -- Some packages may not be found!
Download error on http://home.python-keyring.org/: (-3, 'Temporary failure in name resolution') -- Some packages may not be found!
Download error on http://home.python-keyring.org/: (-3, 'Temporary failure in name resolution') -- Some packages may not be found!
Download error on http://home.python-keyring.org/: (-3, 'Temporary failure in name resolution') -- Some packages may not be found!
Download error on http://home.python-keyring.org/: (-3, 'Temporary failure in name resolution') -- Some packages may not be found!
Download error on http://home.python-keyring.org/: (-3, 'Temporary failure in name resolution') -- Some packages may not be found!
Download error on http://home.python-keyring.org/: (-3, 'Temporary failure in name resolution') -- Some packages may not be found!
My `setup.py` is:
from setuptools import setup, find_packages
setup(
name="blah",
version='0.9dev',
description="blah",
package_dir = {'': 'src'},
packages=find_packages('src'),
include_package_data=True,
zip_safe=False,
install_requires=[
'setuptools',
'keyring',
'argparse',
'Cheetah'
],
entry_points = """
[console_scripts]
A = A:main
""",
)
Answer: Neither hostname `home.python-keyring.org` nor `keyring-python.org` resolves
in DNS. You need to figure out where the package is hosted and use the correct
hostname.
|
python csv write only certain fieldnames, not all
Question: I must be missing something, but I don't get it. I have a csv, it has 1200
fields. I'm only interested in 30. How do you get that to work? I can
read/write the whole shebang, which is ok, but i'd really like to just write
out the 30. I have a list of the fieldnames and I'm kinda hacking the header.
How would I translate below to use DictWriter/Reader?
for file in glob.glob( os.path.join(raw_path, 'P12*.csv') ):
fileReader = csv.reader(open(file, 'rb'))
fileLength = len(file)
fileGeom = file[fileLength-7:fileLength-4]
table = TableValues[fileGeom]
filename = file.split(os.sep)[-1]
with open(out_path + filename, "w") as fileout:
for line in fileReader:
writer = csv.writer(fileout, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
if 'ID' in line:
outline = line.insert(0,"geometryTable")
else:
outline = line.insert(0,table) #"%s,%s\n" % (line, table)
writer.writerow(line)
Answer: Here's an example of using `DictWriter` to write out only fields you care
about. I'll leave the porting work to you:
import csv
headers = ['a','b','d','g']
with open('in.csv','rb') as _in, open('out.csv','wb') as out:
reader = csv.DictReader(_in)
writer = csv.DictWriter(out,headers,extrasaction='ignore')
writer.writeheader()
for line in reader:
writer.writerow(line)
### in.csv
a,b,c,d,e,f,g,h
1,2,3,4,5,6,7,8
2,3,4,5,6,7,8,9
### Result (out.csv)
a,b,d,g
1,2,4,7
2,3,5,8
|
Python fastest way to find values in big data
Question: I have a huge database with rows structured by the fields "date, ad, site,
impressions, clicks"
I got all of them via python using:
cursor.execute(select * from dabase)
data = cursor.fetchall()
From all this data, I need to sample only the rows that happened in a certain
time an ad when printed in certain site has lead to an amount of clicks bigger
than zero, so for instance:
row(1) : (t1, ad1, site1) -> clicks = 1 (t is time)
row(2) : (t2, ad1, site1) -> clicks = 0
So the ad1 and site1 at point t1 had clicks > 0 and therefore **all points in
data containing ad1 and site1 must be taken and put into another list** ,
which I called final_list that would contain row(1) and row(2) (row(2) has 0
clicks, but since in time t1 ad1 and site1 had clicks > 0, so this row must be
taken as well)
When I tried making it via MySQL Workbench it took so long that I got the
error message "Lost Connection to Database". I think it happens because the
table has almost 40 million rows, even though I´ve seem people working with
much bigger amounts of data here MySQL is not being able to handle it, that´s
why I used python (in fact, to get the rows with clicks > 0 it took a few
seconds in python whereas it took more than 10 minutes via MySQL, I´m not sure
precisely how long it was)
What I did then was to first select points ad and site with clicks > 0:
points = [(row[1], row[2]) for row in data if row[4]]
points = list(set(points))
dic = {}
for element in points:
dic[element] = 1
This code took just a few seconds to run. Having a dictionary with the wanted
points I began to insert data into the final_list:
final_list = []
for row in data:
try:
if dic[(row[1], row[2])] == 1: final_list.append(row)
except: continue
But it´s taking too long and I´ve been trying to figure out a way to make it
go faster. Is it possible?
I appreciate any help!
Answer: I know the comments have asked why you aren't able to just do this in the
database, which I wonder as well... but as for at least addressing your code,
you probably don't need a bunch of steps in the middle such as converting to
list -> set -> list -> dictionary. I'm sure the list append()'s are killing
you, as well as the for loops.
What about this?
points = set((row[1], row[2]) for row in data if row[4])
final_list = [d for d in data if (d[1], d[2]) in points]
You could even see if this is faster to get your point set:
from operator import itemgetter
from itertools import ifilter
points = set(ifilter(itemgetter(4), data))
getter = itemgetter(1,2)
final_list = [d for d in data if getter(d) in points]
_My answer gives your question the benefit of the doubt that you have no
option for doing this regularily from sql with a better sql query_
|
Multiplexing string of numbers in python for the parallel port
Question: I'm trying to do something like
[this](http://www.youtube.com/watch?v=BB9E67KfvFw). The problem is that i
can't build the loop that does that.

Here is my code:
import parallel
import time
p=parallel.Parallel() #object to use the parallel port
print ("Enter a string of numbers: ")
numStr = raw_input() #read line
numList=list(numSTr) #converts string to list
numlen=len(numList) #the length of the list
numBin=[['1','0001'], ['2','0010'],
['4','0100'], ['5','0101'],
['6','0110'], ['7','0111'],
['8','1000'], ['9','1001'],
['3','0011'], ['0','0000']] #Less significant bits of the numbers from 0 to 9 in a bidimesional array
p.setData(0) #clear the displays
pos=['0001','0010','0100','1000'] #Unique possible positions for the number from 0 to 9.
c=(str(pos[])+str((numBin[][1]))) #here if the number in the list numList exist and also is in numBin. It joins the position and the number in binary, creating an number that will be send in decimal to the parallel port.
p.setData(int(c,2)) #send the binary number in decimal
If someone can help me, that would be gratifying
The most significant bits that are in numBin, define what display to turn on.
And the less significant define the number. For example:
The string is {'7', '1', '5', '4', '8'}. So the first number to show in the
last display is '7'. SO we take the binary 7 that is '0111' and join that
binary string with the first display position that is '0001'. SO we create a
binary number: '00010111'. We conver that number to decimal and send it to the
parallel port. The parallel port turns on the las display and shows the number
7. The second time, it must show a '7' and a '1' in the second and fist
position and so.
X X X X
X X X 7
X X 7 1
X 7 1 5
7 1 5 4
1 5 4 8
5 4 8 X
4 8 X X
8 X X X
X X X X
The 'X' represents that the display is off and the number represents itself in
the display position as you can see in the circuit.
Answer:
import parallel
import time
p=parallel.Parallel() # object to use the parallel port
print ("Enter a string of numbers: ")
numStr = bytearray(raw_input())
p.setData(0) # clear the displays
while True: # refresh as fast as you need to
for i,n in enumerate(numStr,4):
p.setData(1<<i | n&0xf)
In the for loop, `i` takes the values 4,5,6,7 so for `1<<i` we get:
4 => 0b00010000
5 => 0b00100000
6 => 0b01000000
7 => 0b10000000
This is bitwise or'd with the last 4 bits of the ascii code of the number to
give the value you need to write to the parallel port
|
Setting the log level causes fabric to complain with 'No handlers could be found for logger "ssh.transport"'
Question: The following script:
#!/usr/bin/env python
from fabric.api import env, run
import logging
logging.getLogger().setLevel(logging.INFO)
env.host_string = "%s@%s:%s" % ('myuser', 'myhost', '22')
res = run('date', pty = False)
Produces the following output:
[myuser@myhost:22] run: date
No handlers could be found for logger "ssh.transport"
[myuser@myhost:22] out: Thu Mar 29 16:15:15 CEST 2012
I would like to get rid of this annoying error message: `No handlers could be
found for logger "ssh.transport"` The problem happens when setting the log
level (setLevel).
How can I solve this? I need to set the log level, so skipping that won't
help.
Answer: You need to initialize the logging system. You can make the error go away by
doing so in your app thusly:
import logging
logging.basicConfig( level=logging.INFO )
Note: this uses the default Formatter, which is not terribly useful. You might
consider something more like:
import logging
FORMAT="%(name)s %(funcName)s:%(lineno)d %(message)s"
logging.basicConfig(format=FORMAT, level=logging.INFO)
|
Numpy needs the ucs2
Question: I have installed Numpy using ActivePython and when I try to import numpy
module, it is throwing the following error:
> ImportError: /opt/ActivePython-2.7/lib/python2.7/site-
> packages/numpy/core/multiarray.so: undefined symbol:
> PyUnicodeUCS2_FromUnicode
I am fairly new to python, and I am not sure what to do. I appreciate if you
could point me to the right direction.
* Should I remove python and configure its compilation with the "--enable-unicode=ucs2" or "--with-wide-unicode" option?
Cheers
* * *
* OS: Fedora 16, 64bit;
* Python version: Python 2.7.2 (default, Mar 26 2012, 10:29:24);
* The current compile Unicode version: ucs4
Answer: I suggest that a quick solution to these sort of complications is that you use
the Enthought Python Distribpotion (EPD) on Linux which includes a wide range
of extensions. Cheers.
|
Fabric error when connecting to multiple hosts with ssh config file & RSA keys
Question: I have an error when i connect to multiple servers with Fabric using RSA keys
and ssh config file. My client is snow leopard 10.6.8 with python 2.7.2,
Fabric 1.4.0, ssh (library) 1.7.13. I use multiple RSA keys with passphrase
(using without passphrase is not a possibility). I added my passphrases to
ssh-add. I can ssh to all my servers without problem. I added
env.use_ssh_config = True to my fab file to read my ssh config file.
When i connect to one server with RSA keys (with passphrases) all works fine.
But when i connect to 2 or more hosts, i keep getting "Login password" for the
second server.
fab -H server1,server2 test
[server1] Executing task 'test'
[server1] run: uname -s
[server1] out: Linux
[server2] Executing task 'test'
[server2] run: uname -s
[server2] Login password:
**My fabfile**
from fabric.api import *
import ssh
ssh.util.log_to_file("paramiko.log", 10)
env.use_ssh_config = True
def test():
run('uname -s')
**My ssh config file**
Host server1
HostName xx.xx.xx.xx
Port 6666
User AB1
HashKnownHosts yes
PreferredAuthentications publickey
AddressFamily inet
Host server2
HostName xx.xx.xx.xx
Port 6666
User BC2
HashKnownHosts yes
PreferredAuthentications publickey
AddressFamily inet
In my ssh config file, I tried removing "HashKnownHosts yes" but that didn't
change anything.
**paramiko.log**
DEB [20120329-17:33:30.747] thr=1 ssh.transport: starting thread (client mode): 0x1382350L
INF [20120329-17:33:30.769] thr=1 ssh.transport: Connected (version 2.0, client OpenSSH_4.3)
DEB [20120329-17:33:30.786] thr=1 ssh.transport: kex algos:['diffie-hellman-group-exchange-sha1', 'diffie-hellman-group14-sha1', 'diffie-hellman-group1-sha1'] server key:['ssh-rsa', 'ssh-dss'] client encrypt:['aes128-ctr', 'aes192-ctr', 'aes256-ctr', 'arcfour256', 'arcfour128', 'aes128-cbc', '3des-cbc', 'blowfish-cbc', 'cast128-cbc', 'aes192-cbc', 'aes256-cbc', 'arcfour', '[email protected]'] server encrypt:['aes128-ctr', 'aes192-ctr', 'aes256-ctr', 'arcfour256', 'arcfour128', 'aes128-cbc', '3des-cbc', 'blowfish-cbc', 'cast128-cbc', 'aes192-cbc', 'aes256-cbc', 'arcfour', '[email protected]'] client mac:['hmac-md5', 'hmac-sha1', 'hmac-ripemd160', '[email protected]', 'hmac-sha1-96', 'hmac-md5-96'] server mac:['hmac-md5', 'hmac-sha1', 'hmac-ripemd160', '[email protected]', 'hmac-sha1-96', 'hmac-md5-96'] client compress:['none', '[email protected]'] server compress:['none', '[email protected]'] client lang:[''] server lang:[''] kex follows?False
DEB [20120329-17:33:30.786] thr=1 ssh.transport: Ciphers agreed: local=aes128-ctr, remote=aes128-ctr
DEB [20120329-17:33:30.786] thr=1 ssh.transport: using kex diffie-hellman-group1-sha1; server key type ssh-rsa; cipher: local aes128-ctr, remote aes128-ctr; mac: local hmac-sha1, remote hmac-sha1; compression: local none, remote none
DEB [20120329-17:33:30.866] thr=1 ssh.transport: Switch to new keys ...
DEB [20120329-17:33:30.875] thr=2 ssh.transport: Trying SSH agent key ar8298z4c935cde079ef98763678ecc5
DEB [20120329-17:33:30.935] thr=1 ssh.transport: userauth is OK
INF [20120329-17:33:31.017] thr=1 ssh.transport: Authentication (publickey) failed.
DEB [20120329-17:33:31.039] thr=2 ssh.transport: Trying SSH agent key 0273aff478dddddd05378738dhe98798
DEB [20120329-17:33:31.055] thr=1 ssh.transport: userauth is OK
INF [20120329-17:33:31.135] thr=1 ssh.transport: Authentication (publickey) successful!
DEB [20120329-17:33:31.140] thr=2 ssh.transport: [chan 1] Max packet in: 34816 bytes
DEB [20120329-17:33:31.159] thr=1 ssh.transport: [chan 1] Max packet out: 32768 bytes
INF [20120329-17:33:31.159] thr=1 ssh.transport: Secsh channel 1 opened.
DEB [20120329-17:33:31.189] thr=1 ssh.transport: [chan 1] Sesch channel 1 request ok
DEB [20120329-17:33:31.218] thr=1 ssh.transport: [chan 1] Sesch channel 1 request ok
DEB [20120329-17:33:31.237] thr=1 ssh.transport: [chan 1] EOF received (1)
DEB [20120329-17:33:31.237] thr=1 ssh.transport: [chan 1] EOF sent (1)
DEB [20120329-17:33:31.275] thr=3 ssh.transport: starting thread (client mode): 0x10f9050L
INF [20120329-17:33:32.126] thr=3 ssh.transport: Connected (version 2.0, client OpenSSH_5.3)
DEB [20120329-17:33:32.156] thr=3 ssh.transport: kex algos:['diffie-hellman-group-exchange-sha256', 'diffie-hellman-group-exchange-sha1', 'diffie-hellman-group14-sha1', 'diffie-hellman-group1-sha1'] server key:['ssh-rsa', 'ssh-dss'] client encrypt:['blowfish-cbc', 'aes256-cbc', 'aes256-ctr'] server encrypt:['blowfish-cbc', 'aes256-cbc', 'aes256-ctr'] client mac:['hmac-sha1', 'hmac-sha1-96'] server mac:['hmac-sha1', 'hmac-sha1-96'] client compress:['none', '[email protected]', 'zlib'] server compress:['none', '[email protected]', 'zlib'] client lang:[''] server lang:[''] kex follows?False
DEB [20120329-17:33:32.156] thr=3 ssh.transport: Ciphers agreed: local=aes256-ctr, remote=aes256-ctr
DEB [20120329-17:33:32.156] thr=3 ssh.transport: using kex diffie-hellman-group1-sha1; server key type ssh-rsa; cipher: local aes256-ctr, remote aes256-ctr; mac: local hmac-sha1, remote hmac-sha1; compression: local none, remote none
DEB [20120329-17:33:32.209] thr=3 ssh.transport: Switch to new keys ...
DEB [20120329-17:33:32.243] thr=2 ssh.transport: Trying SSH agent key ar8298z4c935cde079ef98763678ecc5
DEB [20120329-17:33:32.307] thr=3 ssh.transport: userauth is OK
INF [20120329-17:33:32.426] thr=3 ssh.transport: Authentication (publickey) failed.
DEB [20120329-17:33:32.444] thr=2 ssh.transport: Trying SSH agent key 0273aff478dddddd05378738dhe98798
DEB [20120329-17:33:32.476] thr=3 ssh.transport: userauth is OK
INF [20120329-17:33:32.570] thr=3 ssh.transport: Authentication (publickey) failed.
DEB [20120329-17:33:32.578] thr=2 ssh.transport: Trying SSH agent key 7382deeeee873897883ccc9878972878
DEB [20120329-17:33:32.608] thr=3 ssh.transport: userauth is OK
INF [20120329-17:33:32.702] thr=3 ssh.transport: Authentication (publickey) failed.
DEB [20120329-17:33:32.711] thr=2 ssh.transport: Trying SSH agent key 98792098cccccccccccceeeeeeee9878
DEB [20120329-17:33:32.743] thr=3 ssh.transport: userauth is OK
INF [20120329-17:33:32.843] thr=3 ssh.transport: Authentication (publickey) failed.
SSH agent key 0273aff478dddddd05378738dhe98798 is the same for both servers.
It connects on the first server but fails on the second server. I tried with
different servers in different orders, but i am always having the same issue
with fabric asking for a password for the second server.
How can i fix this?
Thank you
Answer: With the use_ssh_config option set to true, that should pick up the username.
You can test it out [by running these lines](http://bpaste.net/show/27769/) in
a python repl.
|
Server returns 403 error after submitting a form?
Question: So I just recently bought some web hosting and I'm trying to get my site setup
and when I try submitting the form I get a "`Forbidden (403) CSRF verification
failed. Request aborted.`" And then it emails me the details on what went
wrong and it says "`ViewDoesNotExist: Could not import users.views. Error was:
No module named users.views`" when I clearly have a folder named users with a
Python file named views inside of it. Is there some reason that it wouldn't be
recognizing the folder?
Answer: With regard the 403 error; If you have a form you need to provide a CSRF token
too:
<form action="." method="post">{% csrf_token %}
<https://docs.djangoproject.com/en/dev/ref/contrib/csrf/>
|
Unique lists from a list
Question: Given a list I need to return a list of lists of unique items. I'm looking to
see if there is a more Pythonic way than what I came up with:
def unique_lists(l):
m = {}
for x in l:
m[x] = (m[x] if m.get(x) != None else []) + [x]
return [x for x in m.values()]
print(unique_lists([1,2,2,3,4,5,5,5,6,7,8,8,9]))
Output:
[[1], [2, 2], [3], [4], [5, 5, 5], [6], [7], [8, 8], [9]]
Answer:
>>> L=[1,2,2,3,4,5,5,5,6,7,8,8,9]
>>> from collections import Counter
>>> [[k]*v for k,v in Counter(L).items()]
[[1], [2, 2], [3], [4], [5, 5, 5], [6], [7], [8, 8], [9]]
|
Run django application on apache with uWSGI
Question: I wanted to run my django application using apache and uWSGI. So I installed
apache which use worker_module. When I finally run my app and tested its
performance using httperf I noticed that system is able to serve only one user
at the same time. The strange thing is that when I run uWSGI using the same
command as below with nginx I can serve 97 concurrent users. Is it possible
that apache works so slow?
My apache configuration looks like (most important elements - the extant
settings are default):
<IfModule mpm_worker_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadsPerChild 25
MaxClients 63
MaxRequestsPerChild 0
</IfModule>
...
<Location />
SetHandler uwsgi-handler
uWSGISocket 127.0.0.1:8000
</Location>
I run uwsgi using:
uwsgi --socket :8000 --chmod-socket --module wsgi_app --pythonpath /home/user/directory/uwsgi -p 6
Answer: I recommend that you put Apache behind Nginx. For example:
* bind Apache to 127.0.0.1:81
* bind nginx to 0.0.0.0:80
* make nginx proxy domains that Apache should serve
It's not a direct answer to your question but that's IMHO the best solution:
* best performance
* best protection for Apache
* allows to migrate Apache websites to Nginx step by step (uWSGI supports PHP now ...), again for best performance and security
|
Add image to .spec file in Pyinstaller
Question: Does anybody know how to modify the `.spec` file created with the
`Makespec.py` of Pyinstaller such that it includes an image data in the
`_MEIPASS2` Temp dir? I want to be able to add an icon to my exe. I've done
what's written [here](http://stackoverflow.com/questions/7674790/bundling-
data-files-with-pyinstaller-onefile/7675014#7675014), but I just don't know
how to add my data in the `.spec`.
I'm adding this line in the end of the `.spec` file:
a.datas += [('iconName.ico','DATA','C:\\Python26\\pyinstaller-1.5.1\\iconName.ico')]
Answer: Here is my spec file (`Collector.spec`) I used for a simple python program
called `"Collector.py"`.
# -*- mode: python -*-
a = Analysis(['Collector.py'],
pathex=['C:\\Users\\vijay\\Python\\Collector'],
hiddenimports=[],
hookspath=None,
runtime_hooks=None)
a.datas += [('logo.png','C:\\Users\\vijay\\System\\icon\\logo.png','DATA')]
pyz = PYZ(a.pure)
exe = EXE(pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
name='Collector.exe',
debug=False,
strip=None,
upx=True,
console=False , icon='C:\\Users\\vijay\\System\\icon\\logo.ico')
The line `"a.datas += .... "` just above pyz variable holds the path to png
image that will be displayed on various windows of my GUI application. The
`"icon=...."` variable set inside exe variable, holds the path to ico image
that will be displayed on Windows Desktop as the Desktop Icon.
You can now use what Max has done
[here](http://stackoverflow.com/a/13790741/2883164) in your main program
(`Collector.py`, for me).
Here is a snippet of my script `Collector.py`, where I've made use of
[Max](http://stackoverflow.com/a/13790741/2883164)'s Code:
path = self.resource_path("logo.png")
icon = wx.Icon(path, wx.BITMAP_TYPE_PNG)
self.SetIcon(icon)
Now, when I run `pyinstaller Collector.spec`, I have both a Desktop Icon and
an Icon for my Collector App windows.
Hope this helps!
|
Input from Serial (FTDI) to a php/python script
Question: I and some other people are working on a project that includes using an
Arduino with an Ubuntu Server (running Ubuntu 10.04 64 bit). Currently we have
the device connected and we can see the Arduino putting data in /dev/ttyUSB0.
I can successfully cat it to another file.
We have a MySQL database that this information will be translated to, via
either a python or php script. I need to know how to get the input from the
serial port to be the input for that script. The device will be responding at
least 20 times a second. The script essentially just needs to take whatever
response it gets and insert the corresponding row to the MySQL database.
Has anyone done this before who could help out?
Answer: It seems you are doing just fine. You could directly open `/dev/ttyUSB0` like
a file in your code, but as write and read access should be done at a certain
pace (serial baudrate, ...), it may be problematic (but still possible: I
never tried it, but you can [configure the
TTY](http://arduino.cc/playground/Interfacing/LinuxTTY) to directly write in
it).
The missing link is you have to access `/dev/ttyUSB0` like a serial port.
You mentionned Python: with it you can use
[PySerial](http://pyserial.sourceforge.net/). It also makes your code more
portable toward other operating systems. A quick `apt-get install python-
serial` or `apt-get install python3-serial` should work.
You have some examples in the [Arduino
playground](http://arduino.cc/playground/Interfacing/Python):
import serial
ser = serial.Serial('/dev/ttyUSB0', 9600)
while 1:
ser.readline()
There are plenty others in the [PySerial
introduction](http://pyserial.sourceforge.net/shortintro.html).
|
Python: Import Source Code into Eclipse
Question: I've recently started using `eclipse` for my class over `IDLE`. So far I have
no problems writing new code and creating new projects in eclipse.
However, when I open older code that was not originally written in my current
project, eclipse seems to only open it as a text file.
For example, when I want to run a piece of code, I get a popup asking for an
ANT build instead of running it using `pydev`. Also the code will not show up
in the `pydev package explorer`.
How do I go about importing the `source code` into my project so `eclipse`
will treat it as such.
Answer: File > Import > "General" Folder > "File System" Folder > "Browse" button
|
Escape PCRE metacharacters in Haskell
Question: Do any of the Haskell PCRE libraries provide a function to escape regex
metacharacters in a string? I.e. a function to take a string like "[$100]" and
turn it into "\\[\$100\\]".
I'm looking for the equivalent of Python's
[re.escape](http://docs.python.org/library/re.html#re.escape), which I can't
seem to find in regex-pcre.
Answer: I'm not aware of such a function in any of the PCRE libraries, but depending
on what you are trying to accomplish you could use PCRE quoting:
{-# LANGUAGE OverloadedStrings #-}
import qualified Data.ByteString.Char8 as B
import Text.Regex.PCRE
quotePCRE bs = B.concat [ "\\Q" , bs , "\\E" ]
-- Of course, this won't work if the
-- string to be quoted contains `\E` ,
-- but that would be much eaiser to fix
-- than writing a function taking into
-- account all the necessary escaping.
literal = "^[$100]$"
quoted = quotePCRE literal
main :: IO ()
main = do B.putStr "literal: " >> B.putStrLn literal
-- literal: ^[$100]$
B.putStr "quoted: " >> B.putStrLn quoted
-- quoted: \Q^[$100]$\E
putStrLn "literal =~ literal :: Bool"
print ( literal =~ literal :: Bool )
-- literal =~ literal :: Bool
-- False
putStrLn "literal =~ quoted :: Bool"
print ( literal =~ quoted :: Bool )
-- literal =~ quoted :: Bool
-- True
|
PyDev is trying to import non-test-related files?
Question: When I try to auto-discover and run my tests in PyDev I get many import
errors...
For example:
Finding files... done.
Importing test modules ... Traceback (most recent call last):
File "C:\Users\User\Documents\eclipse\dropins\plugins\org.python.pydev.debug_2.4.0.2012020116\pysrc\pydev_runfiles.py", line 307, in __get_module_from_str
mod = __import__(modname)
ImportError: No module named docs.conf
ERROR: Module: docs.conf could not be imported (file: C:/Users/User/Documents/workspaces/workspace1/test/docs/conf.py).
done.
As you can see the "conf.py" file is just a file that is needed for
documentation: not actual code. How do I limit PyDev from being over-zealeous
when searching for tests?
Answer: This is currently possible only in the latest PyDev nightly build.
Go to: window > preferences > pydev > pyunit and add a parameter:
--include_files=test*.py
This will be actually released on PyDev 2.6.0.
To grab the nightly build, see: <http://pydev.org/download.html>
|
Virtual Memory Page Replacement Algorithms
Question: I have a project where I am asked to develop an application to simulate how
different page replacement algorithms perform (with varying working set size
and stability period). My results:




* Vertical axis: page faults
* Horizontal axis: working set size
* Depth axis: stable period
Are my results reasonable? I expected LRU to have better results than FIFO.
Here, they are approximately the same.
For random, stability period and working set size doesnt seem to affect the
performance at all? I expected similar graphs as FIFO & LRU just worst
performance? If the reference string is highly stable (little branches) and
have a small working set size, it should still have less page faults that an
application with many branches and big working set size?
**More Info**
**[My Python Code](https://gist.github.com/2259298)** | **[The Project Question](https://docs.google.com/viewer?a=v&q=cache%3aN4txsyBvve8J%3aics.uci.edu/~bic/courses/OS-2012/Lectures-on-line/VM-proj-NUS.pptx+&hl=en&gl=sg&pid=bl&srcid=ADGEESjy7SHm-YBMJ9kHJXbjILI751xst7xTEWnnhabelNMgn0WHSI-1hkFintnO7htxdmvPazAqQ73XtgzUG05dU1g9duZCfTyfFHRrBhqrtWz7ZUdFYRkkNErT-t6vdty8cMnnpQBd&sig=AHIEtbSZ7JrKOoDJhyGsy8F5dDETDwGNQA)**
* Length of reference string (RS): 200,000
* Size of virtual memory (P): 1000
* Size of main memory (F): 100
* number of time page referenced (m): 100
* Size of working set (e): 2 - 100
* Stability (t): 0 - 1
Working set size (e) & stable period (t) affects how reference string are
generated.
|-----------|--------|------------------------------------|
0 p p+e P-1
So assume the above the the virtual memory of size P. To generate reference
strings, the following algorithm is used:
* Repeat until reference string generated
* pick `m` numbers in [p, p+e]. `m` simulates or refers to number of times page is referenced
* pick random number, 0 <= r < 1
* if r < t
* generate new p
* else (++p)%P
**UPDATE (In response to @MrGomez's answer)**
> However, recall how you seeded your input data: using random.random, thus
> giving you a uniform distribution of data with your controllable level of
> entropy. Because of this, all values are equally likely to occur, and
> because you've constructed this in floating point space, recurrences are
> highly improbable.
I am using `random`, but it is not totally random either, references are
generated with some locality though the use of working set size and number
page referenced parameters?
I tried increasing the `numPageReferenced` relative with `numFrames` in hope
that it will reference a page currently in memory more, thus showing the
performance benefit of LRU over FIFO, but that didn't give me a clear result
tho. Just FYI, I tried the same app with the following parameters
(Pages/Frames ratio is still kept the same, I reduced the size of data to make
things faster).
--numReferences 1000 --numPages 100 --numFrames 10 --numPageReferenced 20
The result is

Still not such a big difference. Am I right to say if I increase
`numPageReferenced` relative to `numFrames`, LRU should have a better
performance as it is referencing pages in memory more? Or perhaps I am mis-
understanding something?
For random, I am thinking along the lines of:
* Suppose theres high stability and small working set. It means that the pages referenced are very likely to be in memory. So the need for the page replacement algorithm to run is lower?
Hmm maybe I got to think about this more :)
**UPDATE: Trashing less obvious on lower stablity**

Here, I am trying to show the trashing as working set size exceeds the number
of frames (100) in memory. However, notice thrashing appears less obvious with
lower stability (high `t`), why might that be? Is the explanation that as
stability becomes low, page faults approaches maximum thus it does not matter
as much what the working set size is?
Answer: **These results are reasonable given your current implementation.** The
rationale behind that, however, bears some discussion.
When considering algorithms in general, it's most important to consider the
_properties_ of the algorithms currently under inspection. Specifically, note
their [_corner cases_](http://en.wikipedia.org/wiki/Corner_case) and best and
worst case conditions. You're probably already familiar with this terse method
of evaluation, so this is mostly for the benefit of those reading here whom
may not have an algorithmic background.
Let's break your question down by algorithm and explore their component
properties in context:
1. _FIFO_ shows an increase in page faults as the size of your working set (length axis) increases.
This is correct behavior, consistent with [Bélády's
anomaly](http://en.wikipedia.org/wiki/B%C3%A9l%C3%A1dy%27s_anomaly) for FIFO
replacement. As the size of your working page set increases, the number of
page faults should also increase.
2. _FIFO_ shows an increase in page faults as system stability (_1 - depth axis_) _decreases_.
Noting your algorithm for seeding stability (`if random.random() <
stability`), your results become _less_ stable as stability (_S_) approaches
1. As you sharply increase the
[entropy](http://en.wikipedia.org/wiki/Entropy_%28information_theory%29) in
your data, the number of page faults, too, sharply increases and propagates
the Bélády's anomaly.
So far, so good.
3. _LRU_ shows consistency with _FIFO_. Why?
Note your seeding algorithm. [Standard
_LRU_](http://en.wikipedia.org/wiki/Page_replacement_algorithm#Least_recently_used)
is most optimal when you have paging requests that are structured to smaller
operational frames. For ordered, predictable lookups, it improves upon FIFO
_by aging off results that no longer exist in the current execution frame,_
which is a very useful property for staged execution and encapsulated, modal
operation. Again, so far, so good.
However, recall how you seeded your input data: using `random.random`, thus
giving you a _[uniform
distribution](http://en.wikipedia.org/wiki/Uniform_distribution_%28continuous%29)_
of data with your controllable level of entropy. Because of this, all values
are equally likely to occur, and because you've constructed this in [floating
point space](http://en.wikipedia.org/wiki/IEEE_754-2008), recurrences are
highly improbable.
As a result, your _LRU_ is perceiving each element to occur a small number of
times, then to be completely discarded when the next value was calculated. It
thus correctly pages each value as it falls out of the window, giving you
performance exactly comparable to _FIFO_. If your system properly accounted
for recurrence or a compressed character space, you would see markedly
different results.
4. For _random,_ stability period and working set size doesn't seem to affect the performance at all. Why are we seeing this scribble all over the graph instead of giving us a relatively [smooth manifold](http://en.wikipedia.org/wiki/Manifold)?
In the case of a _random_ paging scheme, you age off each entry
[stochastically](http://en.wikipedia.org/wiki/Stochastic_process).
Purportedly, this should give us some form of a manifold bound to the entropy
and size of our working set... right?
Or should it? For each set of entries, you randomly assign a subset to page
out as a function of time. This should give relatively even paging
performance, regardless of stability and regardless of your working set, as
long as your access profile is again uniformly random.
So, based on the conditions you are checking, this is entirely correct
behavior [consistent with what we'd
expect](http://en.wikipedia.org/wiki/Page_replacement_algorithm#Random). You
get an even paging performance that doesn't degrade with other factors (but,
conversely, isn't improved by them) that's suitable for high load, efficient
operation. Not bad, just not what you might intuitively expect.
So, in a nutshell, that's the breakdown as your project is currently
implemented.
As an exercise in further exploring the properties of these algorithms in the
context of different dispositions and distributions of input data, I highly
recommend digging into
[`scipy.stats`](http://docs.scipy.org/doc/scipy/reference/stats.html) to see
what, for example, a Gaussian or logistic distribution might do to each graph.
Then, I would come back to [the documented expectations of each
algorithm](http://en.wikipedia.org/wiki/Page_replacement_algorithm) and draft
cases where each is uniquely most and least appropriate.
All in all, I think your teacher will be proud. :)
|
Why the syntax for open() and .read() is different?
Question: This is a newbie question, but I looked around and I'm having trouble finding
anything specific to this question (perhaps because it's too simple/obvious to
others).
So, I am working through Zed Shaw's "Learn Python the Hard Way" and I am on
exercise 15. This isn't my first exposure to python, but this time I'm really
trying to understand it at a more fundamental level so I can really do
something with a programming language for once. I should also warn that I
don't have a good background in object oriented programming or fully
internalized what objects, classes, etc. etc. are.
Anyway, here is the exercise. The ideas is to understand basic file opening
and reading:
from sys import argv
script, filename = argv
txt = open(filename)
print "Here's your file %r:" % filename
print txt.read()
print "I'll also ask you to type it again:"
file_again = raw_input("> ")
txt_again = open(file_again)
print txt_again.read()
txt.close()
txt_again.close()
My question is, why are the `open` and `read` functions used differntly?
For example, to read the example file, why don't/can't I type `print
read(txt)` on line 8?
Why do I put a period in front of the variable and the function after it?
Alternatively, why isn't line 5 written `txt = filename.open()`?
This is so confusing to me. Is it simply that some functions have one syntax
and others another syntax? Or am I not understanding something with respect to
how one passes variables to functions.
Answer: ## Syntax
Specifically to the syntactical differences: _open()_ is a function, _read()_
is an object **method**.
When you call the _open()_ function, it returns an object (first _txt_ , then
_txt_again_).
_txt_ is an **object** of class _file_. Objects of class _file_ are defined
with the method _read()_. So, in your code above:
txt = open(filename)
Calls the _open()_ function and assigns an object of class _file_ into _txt_.
Afterwards, the code:
txt.read()
calls the method _read()_ that is associated with the object _txt_.
## Objects
In this scenario, it's important to understand that **objects** are defined
not only as data entities, but also with built-in actions against those
entities.
e.g. A hypothetical object of class _car_ might be defined with _methods_ like
_start_engine()_ , _stop_engine()_ , _open_doors()_ , etc.
So as a parallel to your file example above, code for creating and using a car
might be:
my_car = create_car(type_of_car)
my_car.start_engine()
[(Wikipedia entry on OOP.)](https://en.wikipedia.org/wiki/Object-
oriented_programming)
|
In Python, is there a way to validate a user input in a certain format?
Question: In python, I'm asking the user to input an office code location which needs to
be in the format: XX-XXX (where the X's would be letters)
How can I ensure that their input follows the format, and if it doesn't ask
them to input the office code again?
Thanks!
Answer: The standard (and language-agnostic) way of doing that is by using [regular
expressions](http://www.regular-expressions.info/):
import re
re.match('^[0-9]{2}-[0-9]{3}$', some_text)
The above example returns `True` (in fact, a "truthy" return value, but you
can pretend it's `True`) if the text contains 2 digits, a hyphen and 3 other
digits. Here is the regex above broken down to its parts:
^ # marks the start of the string
[0-9] # any character between 0 and 9, basically one of 0123456789
{2} # two times
- # a hyphen
[0-9] # another character between 0 and 9
{3} # three times
$ # end of string
I suggest you read more about regular expressions (or re, or regex, or regexp,
however you want to name it), they're some kind of swiss army knife for a
programmer.
|
Cannot import PyBrain after installation on OSX 10.6.8
Question: Check the python version
✈ python --version
Python 2.7.2
List the packages within the `virtualenv`
✈ pip freeze
PyBrain==0.3
numpy==1.6.1
scipy==0.10.1
wsgiref==0.1.2
Load the intepreter
>>> import numpy
>>> print numpy.__version__
1.6.1
>>> import scipy
>>> print scipy.__version__
0.10.1
>>> import pybrain
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/milktrader/.virtualenvs/pybrain/lib/python2.7/site-packages/pybrain/__init__.py", line 1, in <module>
from structure.__init__ import *
File "/Users/milktrader/.virtualenvs/pybrain/lib/python2.7/site-packages/pybrain/structure/__init__.py", line 2, in <module>
from modules.__init__ import *
File "/Users/milktrader/.virtualenvs/pybrain/lib/python2.7/site-packages/pybrain/structure/modules/__init__.py", line 2, in <module>
from gate import GateLayer, DoubleGateLayer, MultiplicationLayer, SwitchLayer
File "/Users/milktrader/.virtualenvs/pybrain/lib/python2.7/site-packages/pybrain/structure/modules/gate.py", line 11, in <module>
from pybrain.tools.functions import sigmoid, sigmoidPrime
File "/Users/milktrader/.virtualenvs/pybrain/lib/python2.7/site-packages/pybrain/tools/functions.py", line 4, in <module>
from scipy.linalg import inv, det, svd
File "/Users/milktrader/.virtualenvs/pybrain/lib/python2.7/site-packages/scipy/linalg/__init__.py", line 116, in <module>
from basic import *
File "/Users/milktrader/.virtualenvs/pybrain/lib/python2.7/site-packages/scipy/linalg/basic.py", line 14, in <module>
from scipy.linalg import calc_lwork
ImportError: dlopen(/Users/milktrader/.virtualenvs/pybrain/lib/python2.7/site-packages/scipy/linalg/calc_lwork.so, 2): Symbol not found: __gfortran_concat_string
Referenced from: /Users/milktrader/.virtualenvs/pybrain/lib/python2.7/site-packages/scipy/linalg/calc_lwork.so
Expected in: dynamic lookup
Answer:
ImportError: dlopen(/Users/milktrader/.virtualenvs/pybrain/lib/python2.7/site-packages/scipy/linalg/calc_lwork.so, 2): Symbol not found: __gfortran_concat_string
I'm not sure - as I haven't messed with this library before - but do you need
to compile one of those packages with Fortran support? When I installed
numpy/scipy on my Mac up at work, I had to install
[GFortran](http://gcc.gnu.org/wiki/GFortran) so all the bindings and
underpinnings of the frameworks would be set correctly. Perhaps that's why
scipy is dying on you.
|
How do I use Python to pack a big integer treating four characters as an unsigned long in network byte order as Ruby's .pack("N") does?
Question: This is the bit of Ruby I want to implement in Python:
Base64.urlsafe_encode64([Digest::MD5.hexdigest(url).to_i(16)].pack("N")).sub(/==\n?$/, '')
You see, this helps turn a URL like this:
http://stackoverflow.com/questions/ask
Into a small code like thise:
sUEBtw
The big integer that gets generated in the process is this:
307275247029202263937236026733300351415
I've been able to pack this into binary form using this Python code:
url = 'http://stackoverflow.com/questions/ask'
n = int(hashlib.md5(url).hexdigest(), 16)
s = struct.Struct('d')
values = [n]
packed_data = s.pack(*values)
short_code = base64.urlsafe_b64encode(packed_data)[:-1]
print short_code
The short code I get is this:
zgMM62Hl7Ec
As you can see it's larger than the one I get with Ruby this the packing is
using a different format.
You're help will be appreciated.
Answer: This does the trick:
import hashlib
import base64
url = 'http://stackoverflow.com/questions/ask'
print base64.urlsafe_b64encode(hashlib.md5(url).digest()[-4:])[:-2]
### Output
sUEBtw
`.digest()` gives the packed bytes of the full 16-byte digest so no need for
`struct.pack`, but it seems Ruby's `.pack('N')` only converts the last four
bytes of the digest.
|
Manipulating DateTime and TimeDelta objects in python
Question: I am wondering how to manipulate Datetime and Time delta objects. I am writing
a game where different planets have different timescales. And I was wondering
how it might be possible to mod datetime objects.
For example if I have a date time object - some past datetime object I was
wondering if it was possible to know how many times 6 hours might into the
different and what the remainder in minutes was?
For example...
now = datetime.now()
then = some datetime object
diff = now - then
num 6 hour blocks = diff / 6 (rounded down)
minutes = diff % 6
Thanks!
Answer: timedelta objects have a total_seconds method in Python 2.7. So you could use
that to work it out. You get a timedelta object back when you subtract one
datetime object from another.
from datetime import timedelta
minutes = 60
hours = 60 * minutes
days = 24 * hours
diff = timedelta(days=6)
days_in_the_past = int(diff.total_seconds() / days)
hours_remainder = diff.total_seconds() % days
hours_in_the_past = int(diff.total_seconds() / hours)
seconds_remainder = diff.total_seconds() % hours
Is that pretty much what you wanted to do? If you are using an older version
of Python then you could define a function that did the same thing as the
total_seconds method like this:
def total_seconds(timedelta_object):
return timedelta_object.days * 86400 + timedelta_object.seconds
|
Can I still use StringIO when the containing Writer() closes it?
Question: I am using the [Python avro library](http://pypi.python.org/pypi/avro/1.6.3).
I want to send an avro file over http, but I don't particularly want to save
that file to disk first, so I thought I'd use StringIO to house the file
contents until I'm ready to send. But avro.datafile.DataFileWriter
thoughtfully takes care of closing the file handle for me, which makes it
difficult for me to get the data back out of the StringIO. Here's what I mean
in code:
from StringIO import StringIO
from avro.datafile import DataFileWriter
from avro import schema, io
from testdata import BEARER, PUBLISHURL, SERVER, TESTDATA
from httplib2 import Http
HTTP = Http()
##
# Write the message data to a StringIO
#
# @return StringIO
#
def write_data():
message = TESTDATA
schema = getSchema()
datum_writer = io.DatumWriter(schema)
data = StringIO()
with DataFileWriter(data, datum_writer, writers_schema=schema, codec='deflate') as datafile_writer:
datafile_writer.append(message)
# If I return data inside the with block, the DFW buffer isn't flushed
# and I may get an incomplete file
return data
##
# Make the POST and dump its response
#
def main():
headers = {
"Content-Type": "avro/binary",
"Authorization": "Bearer %s" % BEARER,
"X-XC-SCHEMA-VERSION": "1.0.0",
}
body = write_data().getvalue() # AttributeError: StringIO instance has no attribute 'buf'
# the StringIO instance returned by write_data() is already closed. :(
resp, content = HTTP.request(
uri=PUBLISHURL,
method='POST',
body=body,
headers=headers,
)
print resp, content
I do have some workarounds I can use, but none of them are terribly elegant.
Is there any way to get the data from the StringIO after it's closed?
Answer: Not really.
The docs are very clear on this:
> **StringIO.close()**
>
> Free the memory buffer. Attempting to do further operations with a closed
> StringIO object will raise a ValueError.
The cleanest way of doing it would be to inherit from StringIO and override
the `close` method to do nothing:
class MyStringIO(StringIO):
def close(self):
pass
def _close(self):
super(MyStringIO, self).close()
And call `_close()` when you're ready.
|
Python argument parser list of list or tuple of tuples
Question: I'm trying to use argument parser to parse a 3D coordinate so I can use
--cord 1,2,3 2,4,6 3,6,9
and get
((1,2,3),(2,4,6),(3,6,9))
My attempt is
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--cord', help="Coordinate", dest="cord", type=tuple, nargs=3)
args = parser.parse_args(["--cord","1,2,3","2,4,6","3,6,9"])
vars(args)
{'cord': [('1', ',', '2', ',', '3'),
('2', ',', '4', ',', '6'),
('3', ',', '6', ',', '9')]}
What would the replacement of the comma be?
Answer: You can add your own
[type](http://docs.python.org/library/argparse.html#type). This also allows
for additional validations, for example:
def coords(s):
try:
x, y, z = map(int, s.split(','))
return x, y, z
except:
raise argparse.ArgumentTypeError("Coordinates must be x,y,z")
parser.add_argument('--cord', help="Coordinate", dest="cord", type=coords, nargs=3)
|
How to use the python interpreter in chef
Question: I am trying to use the python interpreter in chef. Below is my naive attempt
that did not work. What is the proper way to accomplish the below in python?
script "install_something" do
interpreter "python"
user "root"
cwd "/tmp"
code <<-EOH
import boto
f = open('test.txt','r')
f.write('adfadf')
f.close()
EOH
not_if {File.exists?("/tmp/test.txt")}
end
[Mon, 02 Apr 2012 15:20:35 +0000] ERROR: Chef::Exceptions::ShellCommandFailed: script[install_something] (rtb_server::default line 101) had an error: Chef::Exceptions::ShellCommandFailed: Expected process to exit with [0], but received '1'
---- Begin output of "python" "/tmp/chef-script20120402-26069-3d6hob-0" ----
STDOUT:
STDERR: File "/tmp/chef-script20120402-26069-3d6hob-0", line 1
import boto
^
IndentationError: unexpected indent
---- End output of "python" "/tmp/chef-script20120402-26069-3d6hob-0" ----
Ran "python" "/tmp/chef-script20120402-26069-3d6hob-0" returned 1
Answer: The contents of
code <<-EOH
import boto
f = open('test.txt','r')
f.write('adfadf')
f.close()
EOH
are passed to the interpreter verbatim, which is to say including the leading
indent. Because indentation forms a part of the python syntax, your script
(between the `<<-EOH`/`EOH`) is not valid python.
The solution in this case is to remove the indentation within the
`<<-EOH`/`EOH` block.
|
Efficiently Reshaping/Reordering Numpy Array to Properly Ordered Tiles (Image)
Question: I would like to be able to somehow reorder a numpy array for efficient
processing of tiles.
what I got:
>>> A = np.array([[1,2],[3,4]]).repeat(2,0).repeat(2,1)
>>> A # image like array
array([[[1, 1, 2, 2],
[1, 1, 2, 2]],
[[3, 3, 4, 4],
[3, 3, 4, 4]]])
>>> A.reshape(2,2,4)
array([[[1, 1, 2, 2],
[1, 1, 2, 2]],
[[3, 3, 4, 4],
[3, 3, 4, 4]]])
what I want: **How to get X:**
>>> X
array([[[1, 1, 1, 1],
[2, 2, 2, 2]],
[[3, 3, 3, 3],
[4, 4, 4, 4]]])
Is this possible without a slow python loop?
Bonus: Conversion back from X to A
Bago pointed out a similar question I had missed: [Creating a 4D view on 2D
array to divide it into cells of fixed
size](http://stackoverflow.com/questions/9006232/creating-a-4d-view-
on-2d-array-to-divide-it-into-cells-of-fixed-size)
* * *
Why all the trouble? To be able to do something like:
>>> X[X.sum(2)>12] -= 1
>>> X
array([[[1, 1, 1, 1],
[2, 2, 2, 2]],
[[3, 3, 3, 3],
[3, 3, 3, 3]]])
**Edit: Solution:**
# MIT - License
import numpy as np
def tile_reorder(A, t):
"""reshape and transpose quadratic array for easy access to quadratic tiles of size t"""
l = A.shape[0] / t
X = A.reshape((l, t, l, t))
X = X.transpose([0, 2, 1, 3])
return X
def tile_reorder_reverse(X):
l = X.shape[0] * X.shape[2]
A = X.transpose([0, 2, 1, 3])
A = A.reshape((l, l))
return A
if __name__ == "__main__":
A = np.array([[1,2,3],[3,4,5],[6,7,8]]).repeat(4,0).repeat(4,1)
print "A:\n", A, "\n\n"
print "A_tiled:\n", tile_reorder(A,4), "\n\n"
print "A_tiled_reversed:\n", tile_reorder_reverse(tile_reorder(A,4)), "\n\n"
X = tile_reorder(A,4)
X[X.sum((2)).sum(2)>63,:,:] += 10
B = tile_reorder_reverse(X)
print "B_processed:\n", B, "\n\n"
Answer: Do you want something like:
>>> X = A.reshape(2,2,2,2)
>>> X = X.transpose([0,2,1,3])
>>> X = X.reshape((2,2,-1))
>>> X
array([[[1, 1, 1, 1],
[2, 2, 2, 2]],
[[3, 3, 3, 3],
[4, 4, 4, 4]]])
>>> B = X.reshape((2,2,2,2))
>>> B = B.transpose([0,2,1,3])
>>> B = B.reshape((2,2,-1))
>>> B
array([[[1, 1, 2, 2],
[1, 1, 2, 2]],
[[3, 3, 4, 4],
[3, 3, 4, 4]]])
|
How do I check Active Directory user credentials using LDAP?
Question: I am looking for a basic ldap script that is checking if an Active Directory
for a user/password combination.
I mention that, the authentication to LDAP is done using another account than
the ones being verified.
Here is my incomplete script:
#!/usr/bin/env python
import ldap
import sys
Server = "ldap://pdc01.example.com"
DN = "EXAMPLE\username"
Secret = "pass"
un = "john"
un_password = "hispass"
Base = "dc=example,dc=com"
Scope = ldap.SCOPE_SUBTREE
Filter = "(&(objectClass=user)(sAMAccountName="+un+"))"
Attrs = ["displayName"]
l = ldap.initialize(Server)
l.set_option(ldap.OPT_REFERRALS, 0)
l.protocol_version = 3
print l.simple_bind_s(DN, Secret)
r = l.search(Base, Scope, Filter, Attrs)
Type,user = l.result(r,60)
Name,Attrs = user[0]
if hasattr(Attrs, 'has_key') and Attrs.has_key('displayName'):
displayName = Attrs['displayName'][0]
print displayName
# TODO: I get `john`'s Username but how to check his password ?
l.unbind()
Answer: If the distinguished name of the entry being checked and its credentials are
already known, **transmit a simple bind request including the credentials** ,
if successful, the password is correct ad the account is usable (as opposed to
being locked or disabled). Alternatively, a SASL mechanism could be used with
a bind request.
If the distinguished name is not known, transmit a search request to the
directory server using a connection with sufficient authorization to read the
distinguished name of the entry. The search request must contain the base
object to which the entry is expected to be subordinate, should use the
tightest possible scope (if the distinguished name is not known, this will be
`one`, or `sub`), should use the most restrictive filter as is possible given
known information, and request the attribute `1.1` since all that is required
is the distinguished name of the entry. The search response will contain the
distinguished name of the entry, assuming the search was successful. Once the
distinguished name is known, transmit a bind request as noted above.
### see also
* [LDAP: Mastering Search Filters](http://ff1959.wordpress.com/2011/09/21/mastering-ldap-search-filters/)
* [LDAP: Search best practices](http://www.ldapguru.info/ldap/ldap-search-best-practices.html)
* [LDAP: Programming practices](http://ff1959.wordpress.com/2011/10/27/ldap-programming-best-practices/)
|
Path routing in Flask
Question: I want to run a Python CGI on a shared hosting environment. I followed Flask's
example and came up with a tiny application as below:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
@app.route("/pi")
def pi():
return "3.1416"
if __name__ == "__main__":
app.run()
My `.htaccess` contains:
Options +ExecCGI
AddHandler cgi-script .cgi .py .rb
DirectoryIndex index.cgi index.htm
And my `index.cgi` is
#!/usr/bin/env python
from wsgiref.handlers import CGIHandler
from firstflask import app
CGIHandler().run(app)
It successfully maps the path `/` to `index()`, however it fails to map the
path `/pi` to `pi()`, instead returning a 404 error. I guess I miss something
obvious. Thanks for the help.
Answer: Comments about cgi vs. wsgi are valid, but if you really want to go with cgi
setup, you need some rewriting rules in order to catch URLs other than "/"
with the index.cgi. With your setup you basically say that index file is
index.cgi, but in case there is something else in the path index.cgi won't get
executed. This is why you get 404 Not Found for /pi request.
You can access the pi() function by requesting url /index.cgi/pi and it will
successfully render you 3.1416, but obviously that is not a very nice URL.
That gives a hint about what needs to be configured for rewriting though:
rewrite all requests with / to /index.cgi/. This gives very simple rewrite
rules together with your original configuration:
Options +ExecCGI
AddHandler cgi-script .cgi .py .rb
DirectoryIndex index.cgi index.htm
RewriteEngine On
RewriteRule ^index.cgi/(.*)$ - [S=1]
RewriteRule ^(.*)$ index.cgi/$1 [QSA,L]
|
Python - Classes and OOP Basics
Question: I do not fully understand classes. I have read the python documentation and
several other tutorials. I get the basic gist of it but don't understand the
nuance. For instance in my code here:
class whiteroom():
""" Pick a door: red, blue, green, or black. """
do = raw_input("> ")
if "red" in do:
print "You entered the red room."
elif "blue" in do:
print "You entered the blue room."
elif "green" in do:
print "You entered the green room."
elif "black" in do:
print "You entered the black room."
else:
print "You sit patiently but slowly begin to stave. You're running out of time."
return whiteroom()
game = whiteroom()
game
(original [codepad](http://codepad.org/IP8IpfOl))
I would like to return the class whiteroom. Which is, either not possible, or
not being done correctly. If you could clear up how to return a class or how
to "link" two classes together so that whiteroom repeats on the else and the
other rooms (which would be classes) are returned when called that would be
awesome.
Also I'm super shaky on `__init__` and am still not really sure what its
purpose is. Everyone keeps telling me that it "initializes", which I'm sure it
does, but that doesn't seem to be helping my brain out.
Answer: Functions are very different from classes. It looks like you took a function
and just changed the `def` to `class`. I guess that _mostly_ works in your
case, but it's not how classes are supposed to go.
Classes contain functions (methods) and data. For example, you have a ball:
class Ball(object):
# __init__ is a special method called whenever you try to make
# an instance of a class. As you heard, it initializes the object.
# Here, we'll initialize some of the data.
def __init__(self):
# Let's add some data to the [instance of the] class.
self.position = (100, 100)
self.velocity = (0, 0)
# We can also add our own functions. When our ball bounces,
# its vertical velocity will be negated. (no gravity here!)
def bounce(self):
self.velocity = (self.velocity[0], -self.velocity[1])
Now we have a `Ball` class. How can we use it?
>>> ball1 = Ball()
>>> ball1
<Ball object at ...>
It doesn't look very useful. The data is where it could be useful:
>>> ball1.position
(100, 100)
>>> ball1.velocity
(0, 0)
>>> ball1.position = (200, 100)
>>> ball1.position
(200, 100)
Alright, cool, but what's the advantage over a global variable? If you have
another `Ball` instance, it will remain independent:
>>> ball2 = Ball()
>>> ball2.velocity = (5, 10)
>>> ball2.position
(100, 100)
>>> ball2.velocity
(5, 10)
And `ball1` remains independent:
>>> ball1.velocity
(0, 0)
Now what about that `bounce` method (function in a class) we defined?
>>> ball2.bounce()
>>> ball2.velocity
(5, -10)
The `bounce` method caused it to modify the `velocity` data of itself. Again,
`ball1` was not touched:
>>> ball1.velocity
# Application
A ball is neat and all, but most people aren't simulating that. You're making
a game. Let's think of what kinds of things we have:
* **A room** is the most obvious thing we could have.
So let's make a room. Rooms have names, so we'll have some data to store that:
class Room(object):
# Note that we're taking an argument besides self, here.
def __init__(self, name):
self.name = name # Set the room's name to the name we got.
And let's make an instance of it:
>>> white_room = Room("White Room")
>>> white_room.name
'White Room'
Spiffy. This turns out not to be all that useful if you want different rooms
to have different functionality, though, so let's make a _subclass_. A
_subclass_ inherits all functionality from its _superclass_ , but you can add
more functionality or override the superclass's functionality.
Let's think about what we want to do with rooms:
> We want to interact with rooms.
And how do we do that?
> The user types in a line of text that gets responded to.
How it's responded do depends on the room, so let's make the room handle that
with a method called `interact`:
class WhiteRoom(Room): # A white room is a kind of room.
def __init__(self):
# All white rooms have names of 'White Room'.
self.name = 'White Room'
def interact(self, line):
if 'test' in line:
print "'Test' to you, too!"
Now let's try interacting with it:
>>> white_room = WhiteRoom() # WhiteRoom's __init__ doesn't take an argument (even though its superclass's __init__ does; we overrode the superclass's __init__)
>>> white_room.interact('test')
'Test' to you, too!
Your original example featured moving between rooms. Let's use a global
variable called `current_room` to track which room we're in.1 Let's also make
a red room.
1\. There's better options besides global variables here, but I'm going to use
one for simplicity.
class RedRoom(Room): # A red room is also a kind of room.
def __init__(self):
self.name = 'Red Room'
def interact(self, line):
global current_room, white_room
if 'white' in line:
# We could create a new WhiteRoom, but then it
# would lose its data (if it had any) after moving
# out of it and into it again.
current_room = white_room
Now let's try that:
>>> red_room = RedRoom()
>>> current_room = red_room
>>> current_room.name
'Red Room'
>>> current_room.interact('go to white room')
>>> current_room.name
'White Room'
**Exercise for the reader:** Add code to `WhiteRoom`'s `interact` that allows
you to go back to the red room.
Now that we have everything working, let's put it all together. With our new
`name` data on all rooms, we can also show the current room in the prompt!
def play_game():
global current_room
while True:
line = raw_input(current_room.name + '> ')
current_room.interact(line)
You might also want to make a function to reset the game:
def reset_game():
global current_room, white_room, red_room
white_room = WhiteRoom()
red_room = RedRoom()
current_room = white_room
Put all of the class definitions and these functions into a file and you can
play it at the prompt like this (assuming they're in `mygame.py`):
>>> import mygame
>>> mygame.reset_game()
>>> mygame.play_game()
White Room> test
'Test' to you, too!
White Room> go to red room
Red Room> go to white room
White Room>
To be able to play the game just by running the Python script, you can add
this at the bottom:
def main():
reset_game()
play_game()
if __name__ == '__main__': # If we're running as a script...
main()
And that's a basic introduction to classes and how to apply it to your
situation.
|
Python function won't start
Question: I'm writing a python calculator, here is the code:
#Python Calculator
import sys;
import cmath;
def plus():
num1 = float(input("Input the first number: "));
num2 = float(input("Input the second number: "));
ans = (num1 + num2);
print(ans);
exit();
return;
def minus():
num1 = float(input("Input the first number: "));
num2 = float(input("Input the second number: "));
ans = (num1 - num2);
print(ans);
exit();
return;
def divide():
num1 = float(input("Input the first number: "));
num2 = float(input("Input the second number: "));
ans = (num1 / num2);
print(ans);
exit();
return;
def multiply():
num1 = float(input("Input the first number: "));
num2 = float(input("Input the second number: "));
ans = (num1 * num2);
print(ans);
exit();
return;
def power():
num1 = float(input("Input the number: "));
num2 = float(input("Input the power: "));
ans = cmath.pow(num1, num2);
print(ans);
exit();
return;
def square():
num1 = float(input("Input the number: "));
ans = cmath.sqrt(num1);
print(ans);
exit();
return;
def inputs():
print("Select which function you would like to use:");
print("1 for Plus");
print("2 for Minus");
print("3 for Divide");
print("4 for Multiply");
print("5 for Power");
print("6 for Square Root");
func = input();
if func == 1:
plus();
elif func == 2:
minus();
elif func == 3:
divide();
elif func == 4:
multiply();
elif func == 5:
power();
elif func == 6:
square();
return;
def exit():
exit = str(input("Run again? y/n: "));
if exit == "Y" or exit == "y":
inputs();
print ("");
elif exit == "N" or exit == "n":
sys.exit();
else:
exit();
return;
print ("Python Calculator");
print("");
inputs();
Now the problem is, once you have inputted the function you want to run, the
program just closes. I am relatively new to python, but not to programming.
Also is anything wrong with the way this is coded (i.e. sloppy coding) please
tell me.
Answer: Your input is probably String (e.g. `"6"`) instead of the number `6`.
In general, I think that your code is unnecessary long, and breaks the [Don't
Repeat Yourself](http://en.wikipedia.org/wiki/Don%27t_repeat_yourself)
principle. For starters, you can ask for the two numbers in a single place,
and then call the relevant function to perform the relevant operation.
A more concise design would use Python operators:
funcs=[operator.add, operator.sub, operator.div,
operator.mul, operator.pow, your_square_function]
You can ask for the function type, then call the relevant function (see Lev's
answer).
There interesting case is `sqr`, which takes a single argument, instead if
two. This can be solved by specifying the number of arguments each function
takes:
funcs=[(operator.add, 1), (operator.sub, 2), (operator.div, 2),
(operator.mul, 2), (operator.pow, 2), (your_square_function, 1)]
The solution is now simple - ask for the function number, ask for the right
number of arguments, and call `funcs[input_number][0]`.
This idea can be elaborated, so that the function name is also stored:
funcs=[("Plus", operator.add, 1), ("Minus", operator.sub, 2),
("Divide", operator.div, 2), ("Multiply", operator.mul, 2),
("Power", operator.pow, 2), ("Square root", your_square_function, 1)]
Now you program should look like (pseudocode):
for f in funcs:
print id, function_name
ask for id
ask for relevant number of arguments
run funcs[id] with relevant number of arguments
|
Idiomatic form of dealing with un-initialized var
Question: I'm coding up my first Scala script to get a feel for the language, and I'm a
bit stuck as to the best way to achieve something.
My situation is the following, I have a method which I need to call N times,
this method returns an Int on each run (might be different, there's a random
component to the execution), and I want to keep the best run (the smallest
value returned on these runs).
Now, coming from a Java/Python background, I would simply initialize the
variable with null/None, and compare in the if, something like:
best = None
for...
result = executionOfThings()
if(best is None or result < best):
best = result
And that's that (pardon for the semi-python pseudo-code).
Now, on Scala, I'm struggling a bit. I've read about the usage of Option and
pattern matching to achieve the same effect, and I guess I could code up
something like (this was the best I could come up with):
best match {
case None => best = Some(res)
case Some(x) if x > res => best = Some(res)
case _ =>
}
I believe this works, but I'm not sure if it's the most idiomatic way of
writing it. It's clear enough, but a bit verbose for such a simple "use-case".
Anyone that could shine a functional light on me?
Thanks.
Answer: For this _particular_ problem, not in general, I would suggest initializing
with `Int.MaxValue` as long as you're guaranteed that `N >= 1`. Then you just
if (result < best) best = result
You could also, with `best` as an option,
best = best.filter(_ >= result).orElse( Some(result) )
if the optionality is important (e.g. it is possible that `N == 0`, and you
don't take a distinct path through the code in that case). This is a more
general way to deal with optional values that may get replaced: use `filter`
to keep the non-replaced cases, and `orElse` to fill in the replacement if
needed.
|
Python "classobj" error
Question: I have this code and I couldn't run it because i get this error: "TypeError:
'classobj' object is not subscriptable" and here is my code:
import cgi
import customerlib
form=cgi.FieldStorage
history = customerlib.find(form["f_name"].value,form["l_name"].value)
print "Content-type: text/html"
print
print """<html>
<head>
<title>Purchase history</title>
</head>
<body>
<h1>Purchase History</h1>"""
print "<p>you have a purchase history of:"
for i in history: "</p>"
print""" <body>
</html>"""
I have the customerlib file beside this file. Any idea how to fix it?
Answer:
form=cgi.FieldStorage
`FieldStorage` is a class, not an object. You need to instantiate it to create
a `FieldStorage` object:
form=cgi.FieldStorage()
It is erroring on `form["f_name"]` because form is currently an alias for the
class of `FieldStorage`, not an object of type `FieldStorage`. By
instantiating it, it's doing what you think it should be doing.
Check out the [cgi module
documentation](http://docs.python.org/library/cgi.html) for more detailed
information on how to use the CGI module.
|
How to create a grammar to the following data using Pyparsing
Question: I have data similar to YAML and need to create a grammar for it using
Pyparsing. Like Python, Yaml's data scope is defined by the whitespace
data:
object : object_name
comment : this object is created first
methods:
method_name:
input:
arg1: arg_type
arg2: arg2_type
output:
methond2_name:
input:
output:
arg1 : arg_type
After parsing the above, it should output something similar to this:
{'comment': 'this object is created first',
'object': 'object_name',
'methods': {'method_name': {'input': {'arg1': 'arg_type', 'arg2': 'arg2_type'},
'output': None}, 'methond2_name': {'input': None, 'output': {'arg1': 'arg_type'}}}}
[EDIT] The data is similar to YAML but not exactly the same. So YAML Python
parser is not able to parse it. I left of some of the details to make the
example data simpler
Answer: Instead of Pyparsing you could use [PyYAML](http://pyyaml.org/wiki/PyYAML) for
this.
import yaml
f = open('yyy.yaml', 'r')
print yaml.load(f)
output:
{'comment': 'this object is created first',
'object': 'object_name',
'methods': {'method_name': {'input': {'arg1': 'arg_type', 'arg2': 'arg2_type'},
'output': None}, 'methond2_name': {'input': None, 'output': {'arg1': 'arg_type'}}}}
|
How to send an email containing greek characters using rJython?
Question: The following function (found [here](http://r.789695.n4.nabble.com/Email-out-
of-R-code-tp3530671p3948061.html)) works well for messages containing ASCII
characters. Can you help me modify it for multilingual messages too, because I
don't know python at all?
send.email <- function(to, from, subject,
message, attachment=NULL,
username, password,
server="xxx.xxx.xxx.xxx",
confirmBeforeSend=FALSE){
# to: a list object of length 1. Using list("Recipient" = "[email protected]") will send the message to the address but
# the name will appear instead of the address.
# from: a list object of length 1. Same behavior as 'to'
# subject: Character(1) giving the subject line.
# message: Character(1) giving the body of the message
# attachment: Character(1) giving the location of the attachment
# username: character(1) giving the username. If missing and you are using Windows, R will prompt you for the username.
# password: character(1) giving the password. If missing and you are using Windows, R will prompt you for the password.
# server: character(1) giving the smtp server.
# confirmBeforeSend: Logical. If True, a dialog box appears seeking confirmation before sending the e-mail. This is to
# prevent me to send multiple updates to a collaborator while I am working interactively.
if (!is.list(to) | !is.list(from)) stop("'to' and 'from' must be lists")
if (length(from) > 1) stop("'from' must have length 1")
if (length(to) > 1) stop("'send.email' currently only supports one recipient e-mail address")
if (length(attachment) > 1) stop("'send.email' can currently send only one attachment")
if (length(message) > 1){
stop("'message' must be of length 1")
message <- paste(message, collapse="\\n\\n")
}
if (is.null(names(to))) names(to) <- to
if (is.null(names(from))) names(from) <- from
if (!is.null(attachment)) if (!file.exists(attachment)) stop(paste("'", attachment, "' does not exist!", sep=""))
if (missing(username)) username <- winDialogString("Please enter your e-mail username", "")
if (missing(password)) password <- winDialogString("Please enter your e-mail password", "")
require(rJython)
rJython <- rJython()
rJython$exec("import smtplib")
rJython$exec("import os")
rJython$exec("from email.MIMEMultipart import MIMEMultipart")
rJython$exec("from email.MIMEBase import MIMEBase")
rJython$exec("from email.MIMEText import MIMEText")
rJython$exec("from email.Utils import COMMASPACE, formatdate")
rJython$exec("from email import Encoders")
rJython$exec("import email.utils")
mail<-c(
#Email settings
paste("fromaddr = '", from, "'", sep=""),
paste("toaddrs = '", to, "'", sep=""),
"msg = MIMEMultipart()",
paste("msg.attach(MIMEText('", message, "'))", sep=""),
paste("msg['From'] = email.utils.formataddr(('", names(from), "', fromaddr))", sep=""),
paste("msg['To'] = email.utils.formataddr(('", names(to), "', toaddrs))", sep=""),
paste("msg['Subject'] = '", subject, "'", sep=""))
if (!is.null(attachment)){
mail <- c(mail,
paste("f = '", attachment, "'", sep=""),
"part=MIMEBase('application', 'octet-stream')",
"part.set_payload(open(f, 'rb').read())",
"Encoders.encode_base64(part)",
"part.add_header('Content-Disposition', 'attachment; filename=\"%s\"' % os.path.basename(f))",
"msg.attach(part)")
}
#SMTP server credentials
mail <- c(mail,
paste("username = '", username, "'", sep=""),
paste("password = '", password, "'", sep=""),
#Set SMTP server and send email, e.g., google mail SMTP server
paste("server = smtplib.SMTP('", server, "')", sep=""),
"server.ehlo()",
"server.starttls()",
"server.ehlo()",
"server.login(username,password)",
"server.sendmail(fromaddr, toaddrs, msg.as_string())",
"server.quit()")
message.details <-
paste("To: ", names(to), " (", unlist(to), ")", "\n",
"From: ", names(from), " (", unlist(from), ")", "\n",
"Using server: ", server, "\n",
"Subject: ", subject, "\n",
"With Attachments: ", attachment, "\n",
"And the message:\n", message, "\n", sep="")
if (confirmBeforeSend)
SEND <- winDialog("yesnocancel", paste("Are you sure you want to send this e-mail to ", unlist(to), "?", sep=""))
else SEND <- "YES"
if (SEND %in% "YES"){
jython.exec(rJython,mail)
cat(message.details)
}
else cat("E-mail Delivery was Canceled by the User")
}
I call it like this:
send.email(list("[email protected]"),
list("[email protected]"),
"Δοκιμή αποστολής email με attachment",
"Με χρήση της rJython",
attachment="monthly_report.xls",
username="gd047",password="xxxxxx")
Answer: The issue is how your enclosed Python code is structured. [This blog
entry](http://mg.pov.lt/blog/unicode-emails-in-python) goes into more detail
on how to properly [send Unicode
email](http://en.wikipedia.org/wiki/Unicode_and_email), which you're using
Python to manage the underling SMTP connection for. Note that according to R.
David Murray, [this will be fixed in later iterations of the `email` package
in Python](http://bugs.python.org/issue1685453).
Here's the salient Python code you can retrofit into your calls in rJython,
borrowing directly from [the aforementioned blog
post](http://mg.pov.lt/blog/unicode-emails-in-python):
from smtplib import SMTP
from email.MIMEText import MIMEText
from email.Header import Header
from email.Utils import parseaddr, formataddr
def send_email(sender, recipient, subject, body):
"""Send an email.
All arguments should be Unicode strings (plain ASCII works as well).
Only the real name part of sender and recipient addresses may contain
non-ASCII characters.
The email will be properly MIME encoded and delivered though SMTP to
localhost port 25. This is easy to change if you want something different.
The charset of the email will be the first one out of US-ASCII, ISO-8859-1
and UTF-8 that can represent all the characters occurring in the email.
"""
# Header class is smart enough to try US-ASCII, then the charset we
# provide, then fall back to UTF-8.
header_charset = 'ISO-8859-1'
# We must choose the body charset manually
for body_charset in 'US-ASCII', 'ISO-8859-1', 'UTF-8':
try:
body.encode(body_charset)
except UnicodeError:
pass
else:
break
# Split real name (which is optional) and email address parts
sender_name, sender_addr = parseaddr(sender)
recipient_name, recipient_addr = parseaddr(recipient)
# We must always pass Unicode strings to Header, otherwise it will
# use RFC 2047 encoding even on plain ASCII strings.
sender_name = str(Header(unicode(sender_name), header_charset))
recipient_name = str(Header(unicode(recipient_name), header_charset))
# Make sure email addresses do not contain non-ASCII characters
sender_addr = sender_addr.encode('ascii')
recipient_addr = recipient_addr.encode('ascii')
# Create the message ('plain' stands for Content-Type: text/plain)
msg = MIMEText(body.encode(body_charset), 'plain', body_charset)
msg['From'] = formataddr((sender_name, sender_addr))
msg['To'] = formataddr((recipient_name, recipient_addr))
msg['Subject'] = Header(unicode(subject), header_charset)
# Send the message via SMTP to localhost:25
smtp = SMTP("localhost")
smtp.sendmail(sender, recipient, msg.as_string())
smtp.quit()
Once ported, this should get your code working. Hopefully, better support for
[RFC2047](http://tools.ietf.org/html/rfc2047) and
[RFC3490](http://tools.ietf.org/html/rfc3490) will be added soon. For now, you
regrettably have to hack around the issue.
|
Python 3: Using a multiprocessing queue for logging
Question: I've recently been given the challenge of working multiprocessing into our
software. I want a main process to spawn subprocesses, and I need some way of
sending logging information back to the main process. This is mainly because a
module we use writes warning and error messages to a logging object, and we
want these messages to appear in the gui, which runs in the main process.
The obvious approach was to write a small class with a write() method that
puts() onto a queue, and then use this class in a logging stream handler. The
main process would then get() from this queue to send the text to the gui. But
this didn't seem to work, and I don't know why
I wrote some sample code to demonstrate the problem. It uses a logging object
to write a queue in a subprocess, and then the main process tries to read from
the queue, but fails. Can someone help me figure out what is wrong with this?
import time, multiprocessing, queue, logging
class FileLikeQueue:
"""A file-like object that writes to a queue"""
def __init__(self, q):
self.q = q
def write(self, t):
self.q.put(t)
def flush(self):
pass
def func(q):
"""This function just writes the time every second for five
seconds and then returns. The time is sent to the queue and
to a logging object"""
stream = FileLikeQueue(q)
log = logging.getLogger()
infohandler = logging.StreamHandler(stream)
infohandler.setLevel(logging.INFO)
infoformatter = logging.Formatter("%(message)s")
infohandler.setFormatter(infoformatter)
log.addHandler(infohandler)
t1 = time.time()
while time.time() - t1 < 5: #run for five seconds
log.info('Logging: ' + str(time.time()))
q.put('Put: %s' % str(time.time()))
time.sleep(1)
def main():
q = multiprocessing.Queue()
p = multiprocessing.Process(target=func, args=(q,))
p.start()
#read the queue until it is empty
while True:
try:
t = q.get()
except queue.Empty:
break
print(t)
if __name__ == '__main__':
main()
I expect the output to be:
Logging: 1333629221.01
Put: 1333629221.01
Logging: 1333629222.02
Put: 1333629222.02
Logging: 1333629223.02
Put: 1333629223.02
Logging: 1333629224.02
Put: 1333629224.02
Logging: 1333629225.02
Put: 1333629225.02
But what I get is:
Put: 1333629221.01
Put: 1333629222.02
Put: 1333629223.02
Put: 1333629224.02
Put: 1333629225.02
So the put() operation in func() works, but the logging doesn't. Why?
Thank you.
Answer: Your problem is with the configuration of the logging module:
You need to call `log.setLevel(logging.INFO)`. The default log level is
`WARNING`, so your logs have no effect.
You did call `setLevel` on the handler object, but the logged messages never
reach the handler because they are filtered by the logger. There is no need to
call `setLevel` on the handler itself, because it processes all messages by
default.
|
Boost::Python Forward Declaration of boost::python::object throwing python TypeError
Question: I'm trying to refactor parts of my project, particularly the Python/C++
interface. The standard boost::python python initialization was working
before:
boost::python::object main_module = boost::python::import("__main__");
boost::python::object globals(main_module.attr("__dict__"));
//...
However, after factoring that into a class of its own, I'm getting
TypeError: No to_python (by-value) converter found for C++ type: boost::python::api::proxy<boost::python::api::attribute_policies>
When an instantiating a PyInterface object, as below:
namespace py = boost::python;
class PyInterface
{
private:
py::object
main_module,
global,
tmp;
//...
public:
PyInterface();
//...
};
PyInterface::PyInterface()
{
std::cout << "Initializing..." << std::endl;
Py_Initialize();
std::cout << "Accessing main module..." << std::endl;
main_module = py::import("__main__");
std::cout << "Retrieve global namespace..." << std::endl;
global(main_module.attr("__dict__"));
//...
}
//in test.cpp
int main()
{
PyInterface python;
//...
}
Running gives the following output:
Initializing...
Accessing main module...
Retrieving global namespace...
TypeError: No to_python (by-value) converter found for C++ type: boost::python::api::proxy<boost::python::api::attribute_policies>
The only thing I can think is that it has something to do with declaring
"globals" before using it. In which case, is there another way that I can do
this?
Answer: Ah! Fixed it.
Changing the call to globals in the constructor from
globals(main_method.attr("__dict__"));
to using the assignment operator instead:
globals = main_method.attr("__dict__");
Looking back, that seems perfectly obvious, but at least I know I wasn't the
only one stumped judging by the lack of anyone derping me.
|
Python Frequency Distribution (FreqDist / NLTK) Issue
Question: I'm attempting to break a list of words (a tokenized string) into each
possible substring. I'd then like to run a FreqDist on each substring, to find
the most common substring. The first part works fine. However, when I run the
FreqDist, I get the error:
TypeError: unhashable type: 'list'
Here is my code:
import nltk
string = ['This','is','a','sample']
substrings = []
count1 = 0
count2 = 0
for word in string:
while count2 <= len(string):
if count1 != count2:
temp = string[count1:count2]
substrings.append(temp)
count2 += 1
count1 +=1
count2 = count1
print substrings
fd = nltk.FreqDist(substrings)
print fd
The output of `substrings` is fine. Here it is:
[['This'], ['This', 'is'], ['This', 'is', 'a'], ['This', 'is', 'a', 'sample'], ['is'], ['is', 'a'], ['is', 'a', 'sample'], ['a'], ['a', 'sample'], ['sample']]
However, I just can't get the FreqDist to run on it. Any insight would be
greatly appreciated. In this case, each substring would only have a FreqDist
of 1, but this program is meant to be run on a much larger sample of text.
Answer: I'm not completely certain what you want, but the error message is saying that
it wants to hash the list, which is usually a sign it's putting it in a set or
using it as a dictionary key. We can get around this by giving it tuples
instead.
>>> import nltk
>>> import itertools
>>>
>>> sentence = ['This','is','a','sample']
>>> contiguous_subs = [sentence[i:j] for i,j in itertools.combinations(xrange(len(sentence)+1), 2)]
>>> contiguous_subs
[['This'], ['This', 'is'], ['This', 'is', 'a'], ['This', 'is', 'a', 'sample'],
['is'], ['is', 'a'], ['is', 'a', 'sample'], ['a'], ['a', 'sample'],
['sample']]
but we still have
>>> fd = nltk.FreqDist(contiguous_subs)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/nltk/probability.py", line 107, in __init__
self.update(samples)
File "/usr/local/lib/python2.7/dist-packages/nltk/probability.py", line 437, in update
self.inc(sample, count=count)
File "/usr/local/lib/python2.7/dist-packages/nltk/probability.py", line 122, in inc
self[sample] = self.get(sample,0) + count
TypeError: unhashable type: 'list'
If we make the subsequences into tuples, though:
>>> contiguous_subs = [tuple(sentence[i:j]) for i,j in itertools.combinations(xrange(len(sentence)+1), 2)]
>>> contiguous_subs
[('This',), ('This', 'is'), ('This', 'is', 'a'), ('This', 'is', 'a', 'sample'), ('is',), ('is', 'a'), ('is', 'a', 'sample'), ('a',), ('a', 'sample'), ('sample',)]
>>> fd = nltk.FreqDist(contiguous_subs)
>>> print fd
<FreqDist: ('This',): 1, ('This', 'is'): 1, ('This', 'is', 'a'): 1, ('This', 'is', 'a', 'sample'): 1, ('a',): 1, ('a', 'sample'): 1, ('is',): 1, ('is', 'a'): 1, ('is', 'a', 'sample'): 1, ('sample',): 1>
Is that what you're looking for?
|
Python cgi script inserts only integers into mysql database
Question: I started scripting in Python and I ran a into weird problem.
I am trying to insert some values into mysql database. Database fields are
varchar, utf-8 unicode
Using Python 3.2 and wamp server 2.2(apache 2.2.21, mysql 5.5.20)
If I try print(ime), print(prezime) etc. it prints values of a form from
another page, so I am getting correct values.
if I write sql statement as:
"INSERT INTO Clanovi(CL_Ime,CL_Prezime, CL_Email, CL_Tel) VALUES ("aa","aa","aa","aa")"
it inserts those values into database
if I write:
sql = "INSERT INTO Clanovi(CL_Ime,CL_Prezime, CL_Email, CL_Tel) VALUES (%s,%s,%s,%s)",(ime,prezime,email,tel)
it doesnt work
finaly if I put
sql = "INSERT INTO Clanovi(CL_Ime,CL_Prezime, CL_Email, CL_Tel) VALUES
(%s,%s,%s,%s)"%(ime,prezime,email,tel)
if I put only numbers into form fields it will commit to database (add new
data) ime= 21 prezime= 232 email =123 tel=123 if I put anything else like
letters it wont add new row to database ime= smth prezime=blabla email = aa
tel =dada
(I know this method has security risk)
here is whole code ( I putted print(sql) just to see what my query looks like
at the end)
#!c:\python32\python.exe
import MySQLdb
import cgi
print ("Content-type: text/html\n\n")
form = cgi.FieldStorage()
ime =form["ime"].value
prezime = form["prezime"].value
email= form["email"].value
tel = form["tel"].value
print(ime)
db = MySQLdb.connect("localhost","root","","biblioteka" )
cursor = db.cursor()
sql = "INSERT INTO Clanovi(CL_Ime,CL_Prezime, CL_Email, CL_Tel) VALUES (%s,%s,%s,%s)"%(ime,prezime,email,tel)
print(sql)
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
Thank you for your time and help.
Answer: You shouldn’t assemble your query using Python’s string operations because
doing so is insecure; it makes your program vulnerable to an SQL injection
attack. Instead, use the DB-API’s parameter substitution. Put `?` as a
placeholder wherever you want to use a value, and then provide a tuple of
values as the second argument to the cursor’s `execute()` method:
sql = "INSERT INTO Clanovi(CL_Ime,CL_Prezime, CL_Email, CL_Tel) VALUES (?,?,?,?)"
print(sql)
try:
cursor.execute(sql, (ime, prezime, email, tel))
db.commit()
except:
db.rollback()
db.close()
**Update** : Luke is right (see comments): MySQL uses '%s' instead of '?
Updated sql-statement: `sql = "INSERT INTO Clanovi(CL_Ime,CL_Prezime,
CL_Email, CL_Tel) VALUES (?,?,?,?)"`
|
Datetime comparison behavior in python
Question: Hi I am writing a program that is dependent on time and observing some curious
behavior with datetime objects I cannot quite figure out. The code I am
working with / am having trouble with is...
now = datetime.now()
time_changed_state = some datettime object previously initialized
time_delay = some integer
time_arrival = time_changed_state + timedelta(minutes=time_delay)
if now < time_arrival:
do something
elif now >= time_arrival:
do something different
I have been working with test cases in order ot make sure the code behaves the
way I would like it to but it doesn't seem to.
I discovered the odd behavior when the time_delay = 0, and I know for a fact
that now would be >= time_arrival since time_changed_state was a datetime
object initilizated before this function call and now was initialized within
the function. However, the "do something" code is being executed rather than
the "do something different code".
Thanks so much!
Answer: I've edited your code, is this what you are expecting?
from datetime import datetime
from datetime import timedelta
now = datetime.now()
time_changed_state = now - timedelta(hours=2)
time_delay = 0
time_arrival = time_changed_state + timedelta(minutes=time_delay)
if now < time_arrival:
print 'something'
elif now >= time_arrival:
print 'something different'
|
python regular expression match comma
Question: In the following string,how to match the words including the commas
1. \--
process_str = "Marry,had ,a,alittle,lamb"
import re
re.findall(r".*",process_str)
['Marry,had ,a,alittle,lamb', '']
2. \--
process_str="192.168.1.43,Marry,had ,a,alittle,lamb11"
import re
ip_addr = re.findall(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}",l)
re.findall(ip_addr,process_str1)
How to find the words after the ip address excluding the first comma only i.e,
the outout again is expected to be `Marry,had ,a,alittle,lamb11`
3. In the second example above how to find if the string is ending with a digit.
Answer: In the second example, you just need to capture (using `()`) everything that
follows the ip:
import re
s = "192.168.1.43,Marry,had ,a,alittle,lamb11"
text = re.findall(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3},(.*)", s)[0]
// text now holds the string Marry,had ,a,alittle,lamb11
To find out if the string ends with a digit, you can use the following:
re.match(".*\d$", process_str)
That is, you match the entire string (`.*`), and then backtrack to test if the
last character (using `$`, which matches the end of the string) is a digit.
|
Is it possible to pass arguments to a python made exe at runtime?
Question: I'm experimenting with file I/O. I have a small practice program that creates
a text file when run. I packaged it with pyinstaller so that double clicking
on the exe creates a new folder and places a text file with "hello world"
inside of it. Easy peasy.
Then I started wondering about `main()`. This is just a function like any
other, right? So does that mean I can pass arguments to it at runtime?
I was thinking about the Steam client and how you can put stuff like '-dev'
and '-console' in the shortcut. Is there a way to do this to a python exe that
I have made?
I may be explaining terribly, so here's an example:
def makeFile(string):
if string:
f = open('mytext.txt', 'w') #create text file in local dir
print >> f, 'hello, ' + string + '! \nHow are ya?'
f.close()
else:
f = open('mytext.txt', 'w') #create text file in local dir
print >> f, 'hello, person! \nHow are ya?'
f.close()
def main(string = None):
makeFile(string)
So if I take this code and make it an exe, would I be able to add my optional
arguments somehow.
I tried the above code, and the running `test.exe --"myname"` but that didn't
work.
Is there a way to do this?
Answer: What you're looking for is either the sys module, or the optparse module.
sys will give you very basic control over command line args.
For example:
import sys
if __name__ == "__main__":
if len(sys.argv)>1:
print sys.argv[1]
In the above example, if you were to open up a shell and type -
test.exe "myname"
The resultant output would be:
myname
Note that sys.argv[0] is the name of the script you are currently running.
Each subsequent argument is defined by a space, so in your example above
test.exe -- myname
argv[0] = "test.exe"
argv[1] = "--"
argv[2] = "myname"
Optparse gives a much more robust solution that allows you to define command
line switches with multiple options and defines variables that will store the
appropriate options that can be accessed at runtime.
Re-writing your example:
from optparse import OptionParser
def makeFile(options = None):
if options:
f = open('mytext.txt', 'w') #create text file in local dir
print >> f, 'hello, ' + options.name + '! \nHow are ya?'
f.close()
else:
f = open('mytext.txt', 'w') #create text file in local dir
print >> f, 'hello, person! \nHow are ya?'
f.close()
if __name__ == "__main__":
parser = OptionParser()
parser.add_option('-n','--name',dest = 'name',
help='username to be printed out')
(options,args) = parser.parse_args()
makeFile(options)
You would run your program with :
test.exe -n myname
and the output (in myfile.txt) would be the expected:
Hello, myname!
How are ya?
Hope that helps!
|
Tkinter Button does not appear on TopLevel?
Question: This is a piece of code I write for this question: [Entry text on a different
window?](http://stackoverflow.com/questions/10051721/how-to-fetch-the-entry-
text-on-a-different-window/10051863#10051863)
It is really strange what happened at `mySubmitButton`, it appears that the
button does not want to appear when it is first started, it will, however
appear when you click on it. Even if you click on it and release it away from
the button, that way it won't be send. I am suspecting if this only happen on
a mac, or it only happen to my computer, because it is a very minor problem.
Or it is something silly I did with my code.
self.mySubmitButton = tk.Button(top, text='Hello', command=self.send)
self.mySubmitButton.pack()
Am I missing something? I googled and found this [question and answer on
daniweb](http://www.daniweb.com/software-
development/python/threads/341851/tkinter-button-not-appearing-but-still-
useable). And I do a diff on them, can't figure out what he did "fixed", but I
did see the line is changed to `command=root.quit`. But it is different from
mine anyway...
Here is the full source code, and there is no error message, but the button is
just missing.
import tkinter as tk
class MyDialog:
def __init__(self, parent):
top = self.top = tk.Toplevel(parent)
self.myLabel = tk.Label(top, text='Enter your username below')
self.myLabel.pack()
self.myEntryBox = tk.Entry(top)
self.myEntryBox.pack()
self.mySubmitButton = tk.Button(top, text='Hello', command=self.send)
self.mySubmitButton.pack()
def send(self):
global username
username = self.myEntryBox.get()
self.top.destroy()
def onClick():
inputDialog = MyDialog(root)
root.wait_window(inputDialog.top)
print('Username: ', username)
username = 'Empty'
root = tk.Tk()
mainLabel = tk.Label(root, text='Example for pop up input box')
mainLabel.pack()
mainButton = tk.Button(root, text='Click me', command=onClick)
mainButton.pack()
root.mainloop()


1. Adding another button right after this one, the second one actually appear. I thought it might be because I didn't call the same function, but I called the same one and it does the exact same thing it appears...
2. Adding a empty label between them, doesn't work. The button still isn't being draw.

PS: I am using Mac OS 10.5.8, and Tk 8.4.7.
Answer: I see the hello button, but I'm on windows 7.
I did a quick re-write of your example. I'll be curious if it makes any
difference for you.
import tkinter as tk
class GUI(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
mainLabel = tk.Label(self, text='Example for pop up input box')
mainLabel.pack()
mainButton = tk.Button(self, text='Click me', command=self.on_click)
mainButton.pack()
top = self.top = tk.Toplevel(self)
myLabel = tk.Label(top, text='Enter your username below')
myLabel.pack()
self.myEntryBox = tk.Entry(top)
self.myEntryBox.pack()
mySubmitButton = tk.Button(top, text='Hello', command=self.send)
mySubmitButton.pack()
top.withdraw()
def send(self):
self.username = self.myEntryBox.get()
self.myEntryBox.delete(0, 'end')
self.top.withdraw()
print(self.username)
def on_click(self):
self.top.deiconify()
gui = GUI()
gui.mainloop()
|
Python C++ extension with SWIG - calling a function by importing module
Question: how can I write an C++ lib and make it to an python extension with SWIG and by
importing the module `import module` it will automaticaly call an function
that initializes some global variables.
I have tried to rename the function to `__init__()`, but when I import the
module it isnt called.
what can I do?
Answer: Put the code in an init section in the SWIG interface file:
%init %{
my_init_function();
%}
This code will be added to the generated swig wrapper and be called when
module is imported.
[SWIG 2.0](http://www.swig.org/Doc2.0/SWIGDocumentation.html) Section 5.6.2:
[Code Insertion
Blocks](http://www.swig.org/Doc2.0/SWIGDocumentation.html#SWIG_nn42)
|
Finding the Maximum Route in a given input
Question: I have this as a homework and i need to do it in python.
Problem:
The Maximum Route is defined as the maximum total by traversing from the tip of the triangle to its base. Here the maximum route is (3+7+4+9) 23.
3
7 4
2 4 6
8 5 9 3
Now, given a certain triangle, my task is to find the Maximum Route for it.
Not sure how to do it....
Answer: We can solve this problem using backtracking. To do that for each element of
the triangle in any given row, we have to determine the maximum of sum of the
current element and the three connected neighbors in the next row, or
>
> if elem = triangle[row][col] and the next row is triangle[row+1]
>
> then backtrack_elem = max([elem + i for i in connected_neighbors of col
> in row])
>
First try to find a way to determine `connected_neighbors of col in row`
for an elem in position (row,col), connected neighbor in row = next would be
`[next[col-1],next[col],next[col+1]]` provided `col - 1 >=0` and `col+1 <
len(next)`. Here is am sample implementation
>>> def neigh(n,sz):
return [i for i in (n-1,n,n+1) if 0<=i<sz]
This will return the index of the connected neighbors.
now we can write `backtrack_elem = max([elem + i for i in connected_neighbors
of col in row])` as
triangle[row][i] = max([elem + next[n] for n in neigh(i,len(next))])
and if we iterate the triangle rowwise and curr is any given row then and i is
the ith col index of the row then we can write
curr[i]=max(next[n]+e for n in neigh(i,len(next)))
now we have to iterate the triangle reading the current and the next row
together. This can be done as
for (curr,next) in zip(triangle[-2::-1],triangle[::-1]):
and then we use enumerate to generate a tuple of index and the elem itself
for (i,e) in enumerate(curr):
Clubbing then together we have
>>> for (curr,next) in zip(triangle[-2::-1],triangle[::-1]):
for (i,e) in enumerate(curr):
curr[i]=max(next[n]+e for n in neigh(i,len(next)))
But the above operation is destructive and we have to create a copy of the
original triangle and work on it
route = triangle # This will not work, because in python copy is done by reference
route = triangle[:] #This will also not work, because triangle is a list of list
#and individual list would be copied with reference
So we have to use the `deepcopy` module
import copy
route = copy.deepcopy(triangle) #This will work
and rewrite out traverse as
>>> for (curr,next) in zip(route[-2::-1],route[::-1]):
for (i,e) in enumerate(curr):
curr[i]=max(next[n]+e for n in neigh(i,len(next)))
We end up with another triangle where every elem gives the highest route cost
possible. To get the actual route, we have to use the original triangle and
calculate backward
so for an elem at index `[row,col]`, the highest route cost is
route[row][col]. If it follows the max route, then the next elem should be a
connected neighbor and the route cost should be route[row][col] -
orig[row][col]. If we iterate row wise we can write as
i=[x for x in neigh(next,i) if x == curr[i]-orig[i]][0]
orig[i]
and we should loop downwards starting from the peak element. Thus we have
>>> for (curr,next,orig) in zip(route,route[1:],triangle):
print orig[i],
i=[x for x in neigh(i,len(next)) if next[x] == curr[i]-orig[i]][0]
Lets take a bit complex example, as yours is too trivial to solve
>>> triangle=[
[3],
[7, 4],
[2, 4, 6],
[8, 5, 9, 3],
[15,10,2, 7, 8]
]
>>> route=copy.deepcopy(triangle) # Create a Copy
Generating the Route
>>> for (curr,next) in zip(route[-2::-1],route[::-1]):
for (i,e) in enumerate(curr):
curr[i]=max(next[n]+e for n in neigh(i,len(next)))
>>> route
[[37], [34, 31], [25, 27, 26], [23, 20, 19, 11], [15, 10, 2, 7, 8]]
and finally we calculate the route
>>> def enroute(triangle):
route=copy.deepcopy(triangle) # Create a Copy
# Generating the Route
for (curr,next) in zip(route[-2::-1],route[::-1]): #Read the curr and next row
for (i,e) in enumerate(curr):
#Backtrack calculation
curr[i]=max(next[n]+e for n in neigh(i,len(next)))
path=[] #Start with the peak elem
for (curr,next,orig) in zip(route,route[1:],triangle): #Read the curr, next and orig row
path.append(orig[i])
i=[x for x in neigh(i,len(next)) if next[x] == curr[i]-orig[i]][0]
path.append(triangle[-1][i]) #Don't forget the last row which
return (route[0],path)
To Test our triangle we have
>>> enroute(triangle)
([37], [3, 7, 4, 8, 15])
* * *
Reading a comment by jamylak, I realized this problem is similar to Euler 18
but the difference is the representation. The problem in Euler 18 considers a
pyramid where as the problem in this question is of a right angle triangle. As
you can read my reply to his comment I explained the reason why the results
would be different. Nevertheless, this problem can be easily ported to work
with Euler 18. Here is the port
>>> def enroute(triangle,neigh=lambda n,sz:[i for i in (n-1,n,n+1) if 0<=i<sz]):
route=copy.deepcopy(triangle) # Create a Copy
# Generating the Route
for (curr,next) in zip(route[-2::-1],route[::-1]): #Read the curr and next row
for (i,e) in enumerate(curr):
#Backtrack calculation
curr[i]=max(next[n]+e for n in neigh(i,len(next)))
path=[] #Start with the peak elem
for (curr,next,orig) in zip(route,route[1:],triangle): #Read the curr, next and orig row
path.append(orig[i])
i=[x for x in neigh(i,len(next)) if next[x] == curr[i]-orig[i]][0]
path.append(triangle[-1][i]) #Don't forget the last row which
return (route[0],path)
>>> enroute(t1) # For Right angle triangle
([1116], [75, 64, 82, 87, 82, 75, 77, 65, 41, 72, 71, 70, 91, 66, 98])
>>> enroute(t1,neigh=lambda n,sz:[i for i in (n,n+1) if i<sz]) # For a Pyramid
([1074], [75, 64, 82, 87, 82, 75, 73, 28, 83, 32, 91, 78, 58, 73, 93])
>>>
|
How do I call Dajax / Dajaxice functions from my Django template
Question: I am writing a simple Django application and wish to add ajax paging using
Dajax / Dajaxice. I have started by trying to implement the simple paging
example from the Dajax website (http://dajaxproject.com/pagination/) - but
haven't managed to get it working. Whenever I press the "next" button I get
the following js error:
Uncaught TypeError: Cannot call method 'pagination' of undefined
My Django project is called "DoSomething" - and it contains a single app
called "core".
I have followed all of the instructions to install Dajaxice here:
<https://github.com/jorgebastida/django-dajaxice/wiki/installation>
I have an python file in the "core" directory called "ajax.py" which contains
the following code:
from views import get_pagination_page
from dajax.core.Dajax import Dajax
from django.template.loader import render_to_string
from dajaxice.decorators import dajaxice_register
from django.utils import simplejson
@dajaxice_register
def pagination(request, p):
try:
page = int(p)
except:
page = 1
items = get_pagination_page(page)
render = render_to_string('posts_paginator.html', { 'items': items })
dajax = Dajax()
dajax.assign('#pagination','innerHTML',render)
return dajax.json()
My views.py file contains the following method:
def index(request):
posts = Post.objects.order_by('id').reverse()
items = get_pagination_page(1)
return render_to_response('index.html', locals(), context_instance=RequestContext(request))
def get_pagination_page(page=1):
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.template.loader import render_to_string
items = Post.objects.order_by('id').reverse()
paginator = Paginator(items, 10)
try:
page = int(page)
except ValueError:
page = 1
try:
items = paginator.page(page)
except (EmptyPage, InvalidPage):
items = paginator.page(paginator.num_pages)
return items
My index template contains the following:
<div id="pagination">
{% include "posts_paginator.html" %}
</div>
My posts_paginator.html template contains the following link, to trigger the
pagination method:
{% for i in items.object_list %}
{{ i }}<br>
{% endfor %}
{% if items.has_next %}
<a href="#" onclick="Dajaxice.core.pagination(Dajax.process,{'p':{{ items.next_page_number }}})">next</a>
{% endif %}
My question is, **within the onClick value, how should I be referencing the
pagination method (from my ajax.py file)**. I can't find anything to explain
this - and I've tried every combination of project name/app name that I can
think of!
THANKS! :)
Answer: At least in my case I have to append the Project name as well as the
app_label.
Dajaxice.MyProject.core.my_dajax_method(Dajax.process, {'form' : data});
|
Python 2.7 on System, PIP and Virtualenv still using 2.6 - How do I switch them to use 2.7
Question: I am on MacOSx 10.6.8 and I have python 2.7 installed
python -v produces:
Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
dlopen("/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/readline.so", 2);
import readline # dynamically loaded from /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/readline.so
I them run:
$ virtualenv venv
and then
$ . venv/bin/activate
and do a python -v
and I get:
Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
dlopen("/Users/nkhdev/venv/lib/python2.6/lib-dynload/readline.so", 2);
import readline # dynamically loaded from /Users/nkhdev/venv/lib/python2.6/lib-dynload/readline.so
Can someone tell me the steps to use have virtualenv create and use python 2.7
from my system? Or have virtualenv, use python 2.7 period. I don't care if the
version is my system version.
Answer: You probably used an existing, Apple-supplied version of `easy_install` to
install `pip` et al. By default, `easy_install` is associated with a
particular instance of Python, in this case, the Apple-supplied system Python
2.6. In general, when you install a new version of Python, you need to also
install a new `easy_install` for it. Follow [the instructions
here](http://pypi.python.org/pypi/distribute) for the Distribute package which
provides `easy_install`, then use it to install `pip` and use that `pip` to
install `virtualenv`.
|
multiline gtk.Label ignores xalign=0.5
Question: A gtk.Label can't be aligned in center when line-wrap is turned on. Example
code:
import pygtk
pygtk.require('2.0')
import gtk
class testwin(gtk.Window):
def __init__(self):
gtk.Window.__init__(self)
width,height = 300,300
self.set_size_request(width,height)
self.set_position(gtk.WIN_POS_CENTER)
self.set_title("test window")
label = gtk.Label("test text")
label.set_line_wrap(True)
label.set_justify(gtk.JUSTIFY_CENTER)
label.set_alignment(0.5,0.5)
label.connect("size-allocate",lambda l,s: l.set_size_request(s.width-1, -1))
self.add(label)
self.connect("destroy", gtk.main_quit)
self.show_all()
testwin()
gtk.main()
It looks like this, that means, it's aligned left: <http://m45.img-
up.net/?up=pic122x97.png>
If you comment out line 14 (set_line_wrap) everything is perfectly fine:
<http://o54.img-up.net/?up=pic2y00p9.png>
Please note that yalign works fine. So it seems like the first argument in the
gtk.Misc.set_alignment-function has no effect when line wrap is turned on.
Using Fedora 16, 64bit, gtk 3.2.4, pygtk 2.24.0, python 2.7.2
Question: Is this intended or a bug? How is it supposed to be made or is a
workaround available?
Answer: This isn't really an answer, but it doesn't fit in a comment.
I'm going to guess this is a bug. When I convert your code to run on
[PyGObject](https://live.gnome.org/PyGObject) (PyGTK's successor), it works as
you'd expect.
from gi.repository import Gtk
class testwin(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self)
width,height = 300,300
self.set_size_request(width,height)
self.set_position(Gtk.WindowPosition.CENTER)
self.set_title("test window")
label = Gtk.Label("test text")
label.set_line_wrap(True)
label.set_justify(Gtk.Justification.CENTER)
label.set_alignment(0.5,0.5)
label.connect("size-allocate",lambda l,s: l.set_size_request(s.width-1, -1))
self.add(label)
self.connect("destroy", Gtk.main_quit)
self.show_all()
testwin()
Gtk.main()
Of course, if you're stuck on PyGTK and you can't switch over to PyGObject
right away, then this answer doesn't solve your problem.
|
Accessing Items In a ordereddict
Question: Lets say I have the following code:
import collections
d = collections.OrderedDict()
d['foo'] = 'python'
d['bar'] = 'spam'
Is there a way I can access the items in a numbered manner, like:
d(0) #foo's Output
d(1) #bar's Output
Answer: If its an `OrderedDict()` you can easily access the elements by indexing by
getting the tuples of (key,value) pairs as follows
>>> import collections
>>> d = collections.OrderedDict()
>>> d['foo'] = 'python'
>>> d['bar'] = 'spam'
>>> d.items()
[('foo', 'python'), ('bar', 'spam')]
>>> d.items()[0]
('foo', 'python')
>>> d.items()[1]
('bar', 'spam')
**Note for Python 3.X**
`dict.items` would return an [iterable dict view
object](http://docs.python.org/3.3/library/stdtypes.html#dict-views) rather
than a list. We need to wrap the call onto a list in order to make the
indexing possible
>>> items = list(d.items())
>>> items
[('foo', 'python'), ('bar', 'spam')]
>>> items[0]
('foo', 'python')
>>> items[1]
('bar', 'spam')
|
wsgi django not working
Question: im installing django,
the test for wsgi is ok, but when i point my default file to the django test,
it doesnt work,
this is the test that works fine:
default: `/etc/apache2/sites-available/default`
<VirtualHost *:80>
ServerName www.example.com
ServerAlias example.com
ServerAdmin [email protected]
DocumentRoot /var/www
<Directory /var/www/documents>
Order allow,deny
Allow from all
</Directory>
WSGIScriptAlias / /home/ubuntu/djangoProj/micopiloto/application.wsgi
<Directory /home/ubuntu/djangoProj/mysitio/wsgi_handler.py>
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
application.wsgi:: `~/djangoProj/micopiloto`
import os
import sys
sys.path.append('/srv/www/cucus/application')
os.environ['PYTHON_EGG_CACHE'] = '/srv/www/cucus/.python-egg'
def application(environ,
start_response):
status = '200 OK'
output = 'Hello World!MK SS9 tkt kkk'
response_headers = [('Content-type', 'text/plain'),
('Content-Length', str(len(output)))]
start_response(status, response_headers)
return [output]
but if I change the default to point to `application_sa.wsgi` the django test,
it doesnt work :(
`application_sa.wsgi`
import os, sys
sys.path.append('/home/ubuntu/djangoProj/micopiloto')
os.environ['DJANGO_SETTINGS_MODULE'] = 'micopiloto.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
I restart the apache server every time i change the wsgi to test,
so what im i missing?
thanks a lot!
Answer: Try changing your apache config to the following:
AddHandler wsgi-script .wsgi
WSGISocketPrefix /var/run/wsgi
WSGIRestrictEmbedded On
<VirtualHost *:80>
ServerName www.mydomain.com
WSGIDaemonProcess myprocess processes=2 threads=15
WSGIProcessGroup myprocess
WSGIScriptAlias / /home/ubuntu/djangoProj/micopiloto/application_sa.wsgi
</VirtualHost>
Then add the root folder of your project to sys.path as well in
application_sa.wsgi:
sys.path.append('/home/ubuntu/djangoProj')
sys.path.append('/home/ubuntu/djangoProj/micopiloto')
|
How to install python packages in virtual environment only with virtualenv bootstrap script?
Question: I want to create a bootstrap script for setting up a local environment and
installing all requirments in it. I have been trying with
virtualenv.create_bootstrap_script as described in their
[docs](http://pypi.python.org/pypi/virtualenv).
import virtualenv
s = virtualenv.create_bootstrap_script('''
import subprocess
def after_install(options, home_dir):
subprocess.call(['pip', 'install', 'django'])
''')
open('bootstrap.py','w').write(s)
When running the resulting bootstrap.py, it sets up the virtual environment
correctly, but it then attempts to install Django globally.
How can I write a bootstrap script that installs Django only in this local
virtual environment. It has to work on both Windows and Linux.
Answer: You could force pip to install into your virtualenv by:
subprocess.call(['pip', 'install', '-E', home_dir, 'django'])
Furthermore, it is a nice and useful convention to store your dependencies in
requirements.txt file, for django 1.3 that'd be:
django==1.3
and then in your `after_install`:
subprocess.call(['pip', 'install', '-E', home_dir, '-r', path_to_req_txt])
|
i update djang1.3.1 to djang1.4 , error: MOD_PYTHON ERROR
Question: I updated djang1.3.1 to djang1.4.
In my local env ,that's fine.
but when i ci my code to server ,error happened!
in my server , i can use 'python manage.py shell'
and can 'import settings', that's all right,
but still have this error, who can help me!
> finally, i uninstalled apache , and installed nginx + uwsgi ,fixed this
> problem.......
Traceback (most recent call last):
File "/usr/lib/python2.6/dist-packages/mod_python/importer.py", line 1537, in HandlerDispatch
default=default_handler, arg=req, silent=hlist.silent)
File "/usr/lib/python2.6/dist-packages/mod_python/importer.py", line 1229, in _process_target
result = _execute_target(config, req, object, arg)
File "/usr/lib/python2.6/dist-packages/mod_python/importer.py", line 1128, in _execute_target
result = object(arg)
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/modpython.py", line 180, in handler
return ModPythonHandler()(req)
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/modpython.py", line 142, in __call__
self.load_middleware()
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py", line 39, in load_middleware
for middleware_path in settings.MIDDLEWARE_CLASSES:
File "/usr/local/lib/python2.6/dist-packages/django/utils/functional.py", line 184, in inner
self._setup()
File "/usr/local/lib/python2.6/dist-packages/django/conf/__init__.py", line 42, in _setup
self._wrapped = Settings(settings_module)
File "/usr/local/lib/python2.6/dist-packages/django/conf/__init__.py", line 95, in __init__
raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
ImportError: Could not import settings 'guihuame.settings' (Is it on sys.path?): No module named guihuame.settings
my python version
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> django.VERSION
(1, 4, 0, 'final', 0)
use manage.py
python manage.py shell
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> import settings
Traceback (most recent call last):
File "<console>", line 1, in <module>
ImportError: No module named settings
>>> import guihuame.settings
>>>
thx!
my document tree is
guihuame
\-- manage.py
\-- guihuame (contains **init**.py wsgi.py settings.py urls.py)
\-- other apps
my wsgi.py , wsgi.py and settings.py are in the same folder
import os
import sys
sys.path.insert(0, '/var/web/trunk/guihuame/')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "guihuame.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
Answer: You need to add a line to `wsgi.py` to add the location of your `guihuame`
module to the PYTHONPATH:
import sys
sys.path.insert(0, 'Wherever guihuame is')
Update: It's up to you to actually provide the location of `guihame`. However,
don't do string manipulations on your paths. Python will choose the correct
separator. If there is an issue with that, use `normpath`.
Note also that `os.path.split(os.path.dirname(__file__))[0]` is selecting
either your filesystem root, or more likely, just one level below it. This is
probably not what you want.
|
Running profile startup files in an embedded IPython instance
Question: I want to use an embedded IPython shell with a user_ns dictionary and a my
profile configuration (ipython_config.py and the startup files). The purpose
is to run a Django shell with models imported on startup. django-extensions
implements a command called shell_plus that does this:
<https://github.com/django-extensions/django-
extensions/blob/master/django_extensions/management/commands/shell_plus.py>
from IPython import embed
embed(user_ns=imported_objects)
The problem is that this does not load my startup files. embed() calls
load_default_config() which I figure loads ipython_config.py.
How do I make the embedded IPython instance run my profile startup files?
Answer: I used the following workaround to run my own IPython startup script but still
take advantage of shell_plus:
1. Create a file called `shell_plus_startup.py` in the same directory as `manage.py`. For example:
# File: shell_plus_startup.py
# Extra python code to run after shell_plus starts an embedded IPython shell.
# Run this file from IPython using '%run shell_plus_startup.py'
# Common imports
from datetime import date
# Common variables
tod = date.today()
2. Launch shell plus (which launches an embedded IPython shell).
`python manage.py shell_plus`
3. Manually run the startup script.
In [1]: %run shell_plus_startup.py
4. Then you can use variables you've defined, modules you've imported, etc.
In [2]: tod
Out[2]: datetime.date(2012, 7, 14)
Also see this answer: [scripting ipython through django's
shell_plus](http://stackoverflow.com/questions/1266702/scripting-ipython-
through-djangos-shell-plus?rq=1)
|
date.timestamp not found in python?
Question: After changing the import as a from-import i'm running into this error:
from datetime import datetime, date, timedelta
today = date.today()
from time import mktime
from feedparser import feedparser
import settings
def check_calendar():
d = feedparser.parse(settings.personal_calendar_feed)
for entry in d.entries:
if(date.fromtimestamp(mktime(entry.date_parsed))==today):
Traceback (most recent call last):
File computer.py", line 734, in <module>
check_calendar()
File "computer.py", line 210, in check_calendar
if(date.fromtimestamp(mktime(entry.date_parsed))==today):
AttributeError: 'function' object has no attribute 'fromtimestamp'
Answer: It is highly possible that you have redeclared `date` as function `def
date():` earlier in code. Otherwise it makes no sense.
|
Post request with multipart/form-data in appengine python not working
Question: I'm attempting to send a multipart post request from an appengine app to an
external (django) api hosted on dotcloud. The request includes some text and a
file (pdf) and is sent using the following code
from google.appengine.api import urlfetch
from poster.encode import multipart_encode
from libs.poster.streaminghttp import register_openers
register_openers()
file_data = self.request.POST['file_to_upload']
the_file = file_data
send_url = "http://127.0.0.1:8000/"
values = {
'user_id' : '12341234',
'the_file' : the_file
}
data, headers = multipart_encode(values)
headers['User-Agent'] = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
data = str().join(data)
result = urlfetch.fetch(url=send_url, payload=data, method=urlfetch.POST, headers=headers)
logging.info(result.content)
When this method runs Appengine gives the following warning (I'm not sure if
it's related to my issue)
Stripped prohibited headers from URLFetch request: ['Content-Length']
And Django sends through the following error
<class 'django.utils.datastructures.MultiValueDictKeyError'>"Key 'the_file' not found in <MultiValueDict: {}>"
The django code is pretty simple and works when I use the postman chrome
extension to send a file.
@csrf_exempt
def index(request):
try:
user_id = request.POST["user_id"]
the_file = request.FILES["the_file"]
return HttpResponse("OK")
except:
return HttpResponse(sys.exc_info())
If I add
print request.POST.keys()
I get a dictionary containing user_id and the_file indicating that the file is
not being sent as a file. if I do the same for FILES i.e.
print request.FILES.keys()
I get en empty list [].
# EDIT 1:
I've changed my question to implement the suggestion of someone1 however this
still fails. I also included the headers addition recommended by the link
Glenn sent, but no joy.
# EDIT 2:
I've also tried sending the_file as variations of
the_file = file_data.file
the_file = file_data.file.read()
But I get the same error.
# EDIT 3:
I've also tried editing my django app to
the_file = request.POST["the_file"]
However when I try to save the file locally with
path = default_storage.save(file_location, ContentFile(the_file.read()))
it fails with
<type 'exceptions.AttributeError'>'unicode' object has no attribute 'read'<traceback object at 0x101f10098>
similarly if I try access the_file.file (as I can access in my appengine app)
it tells me
<type 'exceptions.AttributeError'>'unicode' object has no attribute 'file'<traceback object at 0x101f06d40>
Answer: Here is some code I tested locally that should do the trick (I used a
different handler than webapp2 but tried to modify it to webapp2. You'll also
need the poster lib found here <http://atlee.ca/software/poster/>):
In your POST handler on GAE:
from google.appengine.api import urlfetch
from poster.encode import multipart_encode
payload = {}
payload['test_file'] = self.request.POST['test_file']
payload['user_id'] = self.request.POST['user_id']
to_post = multipart_encode(payload)
send_url = "http://127.0.0.1:8000/"
result = urlfetch.fetch(url=send_url, payload="".join(to_post[0]), method=urlfetch.POST, headers=to_post[1])
logging.info(result.content)
Make sure your HTML form contains `method="POST" enctype="multipart/form-
data"`. Hope this helps!
**EDIT:** I tried using the webapp2 handler and realized the way files are
served are different than how the framework I used to test with works (KAY).
Here is updated code that should do the trick (tested on production):
import webapp2
from google.appengine.api import urlfetch
from poster.encode import multipart_encode, MultipartParam
class UploadTest(webapp2.RequestHandler):
def post(self):
payload = {}
file_data = self.request.POST['test_file']
payload['test_file'] = MultipartParam('test_file', filename=file_data.filename,
filetype=file_data.type,
fileobj=file_data.file)
payload['name'] = self.request.POST['name']
data,headers= multipart_encode(payload)
send_url = "http://127.0.0.1:8000/"
t = urlfetch.fetch(url=send_url, payload="".join(data), method=urlfetch.POST, headers=headers)
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write(t.content)
def get(self):
self.response.out.write("""
<html>
<head>
<title>File Upload Test</title>
</head>
<body>
<form action="" method="POST" enctype="multipart/form-data">
<input type="text" name="name" />
<input type="file" name="test_file" />
<input type="submit" value="Submit" />
</form>
</body>
</html>""")
|
Gnuplot: line 0: function to plot expected
Question: I've a python script who generate a graphic with gnuplot. But I've an error:
gnuplot> plot ^ line 0: function to plot expected
g=Gnuplot.Gnuplot(persist=1)
g.title('Read&Write Performance')
g.xlabel('minutes')
g.ylabel('MB/s')
g('set term png')
g('set out')
g('set yrange [0:70]')
d1=Gnuplot.Data(self.time,self.list1,title="perfr", with_="line")
d2=Gnuplot.Data(self.time,self.list2,title="perfw", with_="line")
time.sleep(2)
g.hardcopy('bench.png',terminal = 'png')
g.reset()
self.list1= [12, 15, 17] self.list2 = [43, 48, 49]
I don't understand why I've this error.
Thanks :)
Answer: After a **very brief** look at the source, it seems that g.plot() does not
send the plot to a window (e.g. x11), but to wherever gnuplot is currently
configured to send the plot. So, (I think) the easiest solution is --
g('set terminal png')
g('set output "bench.png"')
g.plot(d1) #d1 should not be in "bench.png"
#This might work to plot both datasets together ... g.plot(d1,d2)
This should work as long as the internals of gnuplot-py don't reset the
gnuplot script whenever a `plot` command is issued. I highly doubt this is the
case since the `__call__` method seems to be such an important part of the
API.
|
Python: Using sympy.sympify to perform a safe eval() on mathematical functions
Question: I am writing a program where users need to be able to use self written
mathematical functions containing functions from numpy and scipy, eg.
**scipy.special.wofz()**.
These functions will be stored in files and imported as strings by the
program. I looked around and saw, that **eval()** or **exec()** are not a safe
way to do it. eg. [here](http://stackoverflow.com/questions/3513292/python-
make-eval-safe).
The security issue would be that good users load a file from evil users who
get access to the good users system.
I was thinking about doing something like this:
#!/bin/python
from scipy.special import *
from numpy import *
import sympy
# Define variable a
vars = {"a":1}
# This is the string I get from a file
string = "wofz(a)"
parsed_string = sympy.sympify(string)
parsed_string.evalf(subs=vars)
However, this does not work. It only returns:
wofz(a)
wofz(a) is not evaluated. Is this even supposed to work that way?
I had another idea: So I thought, once this mathematical function got through
sympify, it should be safe. I could just simply do something like this:
globals = {wofz:wofz}
eval(str(parsed_string), vars, globals)
which works fine and returns:
(0.36787944117144233+0.60715770584139372j)
Is that safe? I know it's not nice.
Please help.
Answer: Use sympy, it's a way safer option.
import sympy
from sympy.core.function import Function
from sympy.core import S
from sympy import sympify
from sympy.functions import im
from scipy.special import wofz
class Wofz(Function):
is_real = True
@classmethod
def _should_evalf(csl,arg):
return True
def as_base_exp(cls):
return cls,S.One
def _eval_evalf(cls, prec):
return sympy.numbers.Number(im(wofz(float(cls.args[0]))))
print sympify("Wofz(2)",{'Wofz':Wofz}).evalf()
Output (you'll have to handle the imaginary part somehow):
0.340026217066065
|
Thousands Separator in Python
Question: > **Possible Duplicate:**
> [how to print number with commas as thousands separators in Python
> 2.x](http://stackoverflow.com/questions/1823058/how-to-print-number-with-
> commas-as-thousands-separators-in-python-2-x)
Does anyone know of an easier way to make numbers have thousands separation
than this:
def addComma(num):
(num, post) = str(num).split('.')
num = list(num)
num.reverse()
count = 0
list1 = []
for i in num:
count += 1
if count % 3 == 0:
list1.append(i)
list1.append(',')
else:
list1.append(i)
list1.reverse()
return ''.join(list1).strip(',') + '.' + post
It works, but it seems REALLY fragile...
Answer: Use `locale.format()` with `grouping=True`
>>> import locale
>>> locale.setlocale(locale.LC_NUMERIC, 'en_US')
'en_US'
>>> locale.format("%d", 1234567, grouping=True)
'1,234,456'
See <http://docs.python.org/library/locale.html#locale.format> for more
information.
|
Python: Strange behavior of datetime.astimezone with respect to US/Pacific and America/Los_Angeles time zones?
Question: Please, observe:
C:\dev\poc\SDR>python
Python 2.7.1 (r271:86832, Nov 27 2010, 17:19:03) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from pytz import timezone
>>> from datetime import datetime
>>> tz1=timezone('America/Los_Angeles')
>>> tz2=timezone('US/Pacific')
>>> ts1=datetime(2011,8,1,tzinfo=tz1)
>>> ts2=datetime(2011,8,1,tzinfo=tz2)
>>> ts1
datetime.datetime(2011, 8, 1, 0, 0, tzinfo=<DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD>)
>>> ts2
datetime.datetime(2011, 8, 1, 0, 0, tzinfo=<DstTzInfo 'US/Pacific' PST-1 day, 16:00:00 STD>)
>>> ts1.astimezone(tz1)
datetime.datetime(2011, 8, 1, 0, 0, tzinfo=<DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD>)
>>> ts2.astimezone(tz2)
datetime.datetime(2011, 8, 1, 0, 0, tzinfo=<DstTzInfo 'US/Pacific' PST-1 day, 16:00:00 STD>)
>>> ts1.astimezone(tz2)
datetime.datetime(2011, 8, 1, 1, 0, tzinfo=<DstTzInfo 'US/Pacific' PDT-1 day, 17:00:00 DST>)
>>> ts2.astimezone(tz1)
datetime.datetime(2011, 8, 1, 1, 0, tzinfo=<DstTzInfo 'America/Los_Angeles' PDT-1 day, 17:00:00 DST>)
>>>
Here is what I do not understand. US/Pacific (`tz1`) and America/Los_Angeles
(`tz2`) are supposed to denote the same time zone, aren't they? Then how come
that `datetime.astimezone` called to move from one zone to another changes the
hour?
Thanks.
Answer: Daylight Savings Time. Notice that the last two entries are listing `PDT-1`.
`astimezone` takes into account DST, but only if it actually goes through its
full logic.
The first two `astimezone` calls in your example _don't_ go through the full
logic, because they short-circuit (since the timezone they're converting "to"
already matches the one they're converting "from").
(You might wonder why the initial datetimes aren't using PDT already. This is
because the `datetime` constructor [doesn't take into account daylight savings
time](http://pytz.sourceforge.net/#localized-times-and-date-arithmetic), even
if you pass it a timezone - it just sets the timezone blindly.)
|
Python Regular Expressions: Capture lookahead value (capturing text without consuming it)
Question: I wish to use regular expressions to split words into groups of `(vowels,
not_vowels, more_vowels)`, using a marker to ensure every word begins and ends
with a vowel.
import re
MARKER = "~"
VOWELS = {"a", "e", "i", "o", "u", MARKER}
word = "dog"
if word[0] not in VOWELS:
word = MARKER+word
if word[-1] not in VOWELS:
word += MARKER
re.findall("([%]+)([^%]+)([%]+)".replace("%", "".join(VOWELS)), word)
In this example we get:
[('~', 'd', 'o')]
The issue is that I wish the matches to overlap - the last set of vowels
should become the first set of the next match. This appears possible with
lookaheads, if we replace the regex as follows:
re.findall("([%]+)([^%]+)(?=[%]+)".replace("%", "".join(VOWELS)), word)
We get:
[('~', 'd'), ('o', 'g')]
Which means we are matching what I want. However, it now doesn't return the
last set of vowels. The output I want is:
[('~', 'd', 'o'), ('o', 'g', '~')]
I feel this should be possible (if the regex can check for the second set of
vowels, I see no reason it can't return them), but I can't find any way of
doing it beyond the brute force method, looping through the results after I
have them and appending the first character of the next match to the last
match, and the last character of the string to the last match. Is there a
better way in which I can do this?
The two things that would work would be capturing the lookahead value, or not
consuming the text on a match, while capturing the value - I can't find any
way of doing either.
Answer: I found it just after posting:
re.findall("([%]+)([^%]+)(?=([%]+))".replace("%", "".join(VOWELS)), word)
Adding an extra pair of brackets inside the lookahead means that it becomes a
capture itself.
I found this pretty obscure and hard to find - I'm not sure if it's just
everyone else found this obvious, but hopefully anyone else in my position
will find this more easily in future.
|
Socket receiving no data. Why?
Question: I was learning socket programming and tried to design a basic http client of
mine. But somehow everything is going good but I am not receiving any data.
Can you please tell me what am I missing?
**CODE**
import socket
def create_socket():
return socket.socket( socket.AF_INET, socket.SOCK_STREAM )
def remove_socket(sock):
sock.close()
del sock
sock = create_socket()
print "Connecting"
sock.connect( ('en.wikipedia.org', 80) )
print "Sending Request"
print sock.sendall ('''GET /wiki/List_of_HTTP_header_fields HTTP/1.1
Host: en.wikipedia.org
Connection: close
User-Agent: Web-sniffer/1.0.37 (+http://web-sniffer.net/)
Accept-Encoding: gzip
Accept-Charset: ISO-8859-1,UTF-8;q=0.7,*;q=0.7
Cache-Control: no-cache
Accept-Language: de,en;q=0.7,en-us;q=0.3
Referer: d_r_G_o_s
''')
print "Receving Reponse"
while True:
content = sock.recv(1024)
if content:
print content
else:
break
print "Completed"
**OUTPUT**
Connecting
Sending Request
298
Receving Reponse
Completed
While I was expecting it show me html content of homepage of wikipedia :'(
Also, it would be great if somebody can share some web resources / books where
I can read in detail about python socket programming for HTTP Request Client
Thanks!
Answer: For a minimal HTTP client, you definitely shouldn't send `Accept-Encoding:
gzip` \-- the server will most likely reply with a gzipped response you won't
be able to make much sense of by eye. :)
You aren't sending the final double `\r\n` (nor are you actually terminating
your lines with `\r\n` as per the spec (unless you happen to develop on
Windows with Windows line endings, but that's just luck and not programming
per se).
Also, `del sock` there does not do what you think it does.
Anyway -- this works:
import socket
sock = socket.socket()
sock.connect(('en.wikipedia.org', 80))
for line in (
"GET /wiki/List_of_HTTP_header_fields HTTP/1.1",
"Host: en.wikipedia.org",
"Connection: close",
):
sock.send(line + "\r\n")
sock.send("\r\n")
while True:
content = sock.recv(1024)
if content:
print content
else:
break
EDIT: As for resources/books/reference -- for a reference HTTP client
implementation, look at Python's very own `httplib.py`. :)
|
date matching using python regex
Question: What am i doing wrong in the below regular expression matching
>>> import re
>>> d="30-12-2001"
>>> re.findall(r"\b[1-31][/-:][1-12][/-:][1981-2011]\b",d)
[]
Answer: `[1-31]` matches `1-3` and `1` which is basically 1, 2 or 3. You cannot match
a number rage unless it's a subset of 0-9. Same applies to `[1981-2011]` which
matches exactly one character that is 0, 1, 2, 8 or 9.
The best solution is simply matching _any_ number and then checking the
numbers later using python itself. A date such as `31-02-2012` would not make
any sense - and making your regex check that would be hard. Making it also
handle leap years properly would make it even harder or impossible. Here's a
regex matching anything that looks like a `dd-mm-yyyy` date:
`\b\d{1,2}[-/:]\d{1,2}[-/:]\d{4}\b`
However, I would highly suggest not allowing any of `-`, `:` and `/` as `:` is
usually used for times, `/` usually for the US way of writing a date
(`mm/dd/yyyy`) and `-` for the ISO way (`yyyy-mm-dd`). The EU `dd.mm.yyyy`
syntax is not handled at all.
If the string does not contain anything but the date, you don't need a regex
at all - use
[`strptime()`](http://docs.python.org/library/datetime.html#strftime-strptime-
behavior) instead.
All in all, tell the user what date format you expect and parse that one,
rejecting anything else. Otherwise you'll get ambiguous cases such as
`04/05/2012` (is it april 5th or may 4th?).
|
Reload all modules in a directory
Question: I need to reload all the python modules within a specified directory.
I've tried something like this:
import sys, os
import_folder = "C:\\myFolder"
sys.path.insert( 0 , import_folder )
for dir in os.listdir(import_folder):
name = os.path.splitext(dir)[0]
ext = os.path.splitext(dir)[1]
if ext == ".py":
import( eval(name) )
reload( eval(name) )
Anyone know how to do this correctly?
Answer:
import os # we use os.path.join, os.path.basename
import sys # we use sys.path
import glob # we use glob.glob
import importlib # we use importlib.import_module
import_folder = 'C:\\myFolder'
sys.path.append(import_folder) # this tells python to look in `import_folder` for imports
for src_file in glob.glob(os.path.join(import_folder, '*.py')):
name = os.path.basename(src_file)[:-3]
importlib.import_module(name)
reload(sys.modules[name])
importlib.import_module(name)
There is the code. Now to the semantics of the whole thing: using
[importlib](http://docs.python.org/2/library/importlib.html#importlib.import_module)
makes this a little bit more normal, but it still promotes some bugs. You can
see that this breaks for source files in a subdirectory. What you should
probably do is: import the package, (import the whole folder), and use the `.`
operator like so:
import sys # we use sys.path
sys.path.append('C:\\')
import myFolder
...
myFolder.func1(foo)
myFolder.val
bar = myFolder.Class1()
Perhaps you should take a look at the [documentation for
modules](http://docs.python.org/2/tutorial/modules.html#packages), but don't
forget to update the path to include the parent of the folder you want to
import.
|
python/bottle and returning a dict
Question: I am using python/bottle to return a dict/json to my android app ( the app
using GSON to parse into JSON). It doesn't seem to parse the python text
correctly.
Here is what python returns:
[{u'slot': -1.0, u'rnd': -1.0}]
But Gson sets slot = 0 and round =0, so it is either not reading it properly
or just setting it to default values. How can I get python to not return the
unicode encoded string and just a regular or string. Here is the offending
python code
...
return str(move)
Move is the object the is returned for a pymongo find query and at the time of
test it was [{u'slot': -1.0, u'rnd': -1.0}], well python added the 'u', when
we look at the values in rockmongo it doesn't have the 'u'.
Answer: If you want bottle to turn your dict into JSON, then return the dict. Not
str(...), not a list with a dict in it, but just the dict.
Example:
from bottle import route
@route('/some/path')
def some_callback():
return {'slot': -1.0, 'rnd': -1.0}
|
Problems with superscript using Python tkinter canvas
Question: I am trying to use canvas.create_text(...) to add text to a drawing. I have
been somewhat successful using unicode in the following way:
mytext = u'U\u2076' #U^6
canvas.create_text(xPos,yPos,text = mytext, font = ("Times","30")
canvas.pack()
It works, but when increasing the font size, superscripts 4,5,6,7,8,9,0 do not
increase in size. Only 1,2,3 work. I'm assuming it's the same for subscripts.
Also, when I save the canvas as a postscript, the problem superscripts are
gone...but when I print out that saved image, the superscripts return.
Am I just completely wrong with my approach? I'm just looking to make this
work so any help would be greatly appreciated. Thank you.
Answer: Your problem comes from the handling of Unicode on your platform and in your
fonts. As explained [on
wikipedia](http://en.wikipedia.org/wiki/Unicode_subscripts_and_superscripts) :
superscript 1,2 and 3 where previously handled in Latin-1 and thus get
different support in fonts.
I did not notice fixed size issue, but on most fonts (on Linux and MacOS),
1,2,3 are not properly aligned with 4-9.
My advice would be to select a font that match your need (you may look at
DejaVu family, which provide libre high quality fonts).
Here is a litte application to illustrate the handling of superscripts with
different fonts or size.
from Tkinter import *
import tkFont
master = Tk()
canvas = Canvas(master, width=600, height=150)
canvas.grid(row=0, column=0, columnspan=2, sticky=W+N+E+S)
list = Listbox(master)
for f in sorted(tkFont.families()):
list.insert(END, f)
list.grid(row=1, column=0)
font_size= IntVar()
ruler = Scale(master, orient=HORIZONTAL, from_=1, to=200, variable=font_size)
ruler.grid(row=1, column=1, sticky=W+E)
def font_changed(*args):
sel = list.curselection()
font_name = list.get(sel[0]) if len(sel) > 0 else "Times"
canvas.itemconfig(text_item, font=(font_name,font_size.get()))
#force redrawing of the whole Canvas
# dirty rectangle of text items has bug with "superscript" character
canvas.event_generate("<Configure>")
def draw():
supernumber_exception={1:u'\u00b9', 2:u'\u00b2', 3:u'\u00b3'}
mytext =""
for i in range(10):
mytext += u'U'+ (supernumber_exception[i] if i in supernumber_exception else unichr(8304+i))+" "
return canvas.create_text(50, 50,text = mytext, anchor=NW)
text_item = draw()
list.bind("<<ListboxSelect>>", font_changed)
font_size.trace("w", font_changed)
font_size.set(30)
master.grid_columnconfigure(0, weight=0)
master.grid_columnconfigure(1, weight=1)
master.grid_rowconfigure(0, weight=1)
master.grid_rowconfigure(1, weight=0)
master.mainloop()
|
csvkit & django a.k.a. using csvkit as modules instead of from command line
Question: I need to do some csv file processing in a django app.
I heard about csvkit and it looks pretty cool.
[github page](https://github.com/onyxfish/csvkit)
Want to try it out but I don't know how to consume csvkit as a module.
Specifically, I want to use the CSVJSON utility. I need to pass it a csv file
(and hopefully some other arguments,) but can't quite figure out how to do
this.
[CSV JSON Docs](http://csvkit.readthedocs.org/en/latest/scripts/csvjson.html)
I want to pass the utility an uploaded csv file, the uploaded file could be in
memory(if it is small enough) or in the temporary storage area. CSVJSON looks
like it takes a file path or stream. It will be a nice bonus if someone can
tell me what I need to do to the uploaded file for CSVJSON to be able to
consume it.
In django 1.3 i'm planning to do the work in the form_valid method.
Hoping someone with some python skills can help show me what i need to do.
Thanks
Answer: You can import the CSVKit JSON class using the following code:
from csvkit.utilities.csvjson import CSVJSON
The CSVKit classes take 2 constructor options; the first is the command-line
arguments list, the second is the output stream. If the output stream isn't
provided, it prints to the standard output.
The argparser module is used to parse the command-line arguments, so [it's
documentation](http://argparse.googlecode.com/svn/trunk/doc/parse_args.html)
will be helpful. The short version is that it's just like splitting the raw
string of arguments you'd use on the actual command-line by spaces. For
example:
$ csvjson --key Date /path/to/input/file
would translate into:
from csvkit.utilities.csvjson import CSVJSON
args = ["--key", "Date", "/path/to/input/file"]
CSVJSON(args).main()
If you don't want to read from an input file, but can't pass the input file
into stdin from the command-line, you can replace the sys.stdin object with
your in-memory version. The only stipulation is that the object must behave
like an input file. Presuming you have the string version of the CSV file in a
variable called **input_string** , you can use the [StringIO
library](http://docs.python.org/library/stringio.html) to create a string
buffer:
import StringIO
import sys
new_stdin = StringIO.StringIO(input_string)
sys.stdin = new_stdin
args = ["--key", "Date"]
CSVJSON(args).main()
Lastly, if you want to print to a file instead of stdout, pass an open file
object as the second parameter:
output_file = open("/path/to/output.txt", "w")
CSVJSON(args, output_file).main()
output_file.close()
Remember, it won't flush the buffer until you close the file object yourself;
CSVJSON won't close it for you.
|
Set a integer limit in a entry widget in tkinter (python)
Question: How do I make it so that if person enters a number higher than 3000, it prints
out a custom message instead of calculating the factorial of that certain
number?
I've tried 'if number > 3000, print "blah blah blah"', but it doesn't work.
Think it has something to do with tkinter.
from Tkinter import *
import tkMessageBox, os
#calculates factorial of inputNumber
def calculate():
number = inputNumber.get()
inputNumber.delete(0, END)
product = 1
for i in range(int(number)):
product = product * (i+1)
facAnswer.delete(1.0, END)
facAnswer.insert(END, product)
cal = Tk()
cal.title("Factorial Calculator")
cal.geometry('450x300+200+200')
#Enter the number you want the factorial of
factorialNumber = IntVar()
inputNumber = Entry(cal, textvariable=factorialNumber)
inputNumber.pack()
#executes calculate function by pressing button
enterButton= Button(cal, text="CALCULATE!", width=20,command=calculate)
enterButton.pack(side='bottom',padx=15,pady=15)
#Where the answer appears:
facAnswer = Text(cal)
facAnswer.insert(END, "Answer:")
facAnswer.pack()
cal.mainloop()
Answer: It seemed to work for me. You could put everything in a class,
and try using `get()` on `factorialNumber`, to see if it makes a difference.
import Tkinter as tk
class GUI(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.title("Factorial Calculator")
self.geometry('450x300+200+200')
# Enter the number you want the factorial of
self.factorialNumber = tk.IntVar()
self.inputNumber = tk.Entry(self, textvariable=
self.factorialNumber)
self.inputNumber.pack()
# executes calculate function by pressing button
enterButton= tk.Button(self, text="CALCULATE!",
width=20,command=self.calculate)
enterButton.pack(side='bottom',padx=15,pady=15)
# Where the answer appears
self.facAnswer = tk.Text(self)
self.facAnswer.insert('end', "Answer:")
self.facAnswer.pack()
def calculate(self):
number = self.factorialNumber.get()
if number > 3000:
print('The number is out of range.')
else:
self.inputNumber.delete(0, 'end')
product = 1
for i in range(int(number)):
product = product * (i+1)
self.facAnswer.delete(1.0, 'end')
self.facAnswer.insert('end', product)
gui = GUI()
gui.mainloop()
|
Using boost 1_48 with Apache qpid on Windows
Question: I stuck while trying to compile **qpid** c++ with **boost 1_47_0** using
**Visual Studio 2010**. Here is steps sequence, that I made:
1. Built _boost 1.48.0_
2. Added BOOST_ROOT, BOOST_INCLUDEDIR, BOOST_LIBRARYDIR, etc. to %PATH% env. variable
3. Installed _cmake_ , _Python_ , _Ruby_ and added their paths to %PATH% env. variable
4. Untared _qpid-cpp-0.14.tar.gz_
5. Applied patch from [https://bugzilla.redhat.com/attachment.cgi?id=542165&action=diff](https://bugzilla.redhat.com/attachment.cgi?id=542165&action=diff) due to last changes in _boost_ file hierarchy
6. Renamed a few, required by qpid, boost libraries from **libbost_LIBRARY-vc100-mt-1_48.lib** to **boost_LIBRARY.lib** format
7. Launched _"cmake -i -G 'Visual Studio 2010'"_ in the 'qpidc-0.14' directory and successfully received *.vcxproj files
Now, the problems were appeared.
I loaded 'ALL_BUILD.vcxproj' file, created on step 7, and tried to build one
project - **qpidcommon**. But I couldn't, due to 'missing a library' error. I
renamed _boost_ libraries from **libbost_LIBRARY-vc100-mt-1_48.lib** to
**boost_LIBRARY-vc100-mt-1_48.lib** file format again and tried to compile.
And, at least, I received next:
...
...
...
(__imp_??0variables_map@program_options@boost@@QAE@XZ) referenced in function
"public: void __thiscall qpid::Options::parse(int,char const * const *,class
std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &,bool)"
(?parse@Options@qpid@@QAEXHPBQBDABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@_N@Z)
3>D:\wc-gather\tplibs\qpidc-0.14\src\Release\qpidcommon.dll : fatal error LNK1120:
33 unresolved externals
========== Build: 2 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
I have no ideas, how to handle this, without adding a library direct to
project. Do you?
Thanks.
Answer: boost_LIBRARY-vc100-mt-1_48.lib should be an import library (for
boost_LIBRARY-vc100-mt-1_48.dll), not a static one. Rename it to its original
name (with lib prefix). Next, build a _full_ boost, to have any possible
variation
bjam -j8 toolset=msvc --build-type=complete
Use -j8 if you have 8-core (like intel i7) for a big speedup (8 minutes for a
full build), and install boost (bjam toolset=msvc --build-type=complete
install)
Then try to rebuild your application again.
|
easy_install matplotlib updates on Mac OS X
Question: I'm currently using matplotlib 1.0.1, running with Python 2.7.1, but like to
update it to at least 1.1.0. However, when I tried downloading
matplotlib-1.1.0-py2.7-python.org-macosx10.3.dmg from
<http://sourceforge.net/projects/matplotlib/files/matplotlib/>,
the subsequent installation states "matplotlib 1.1.0 can't be installed on
this disk. matplotlib requires System Python 2.7 to install."
Alternatively, I tried $easy_install matplotlib in the terminal and got the
following output:
> install_dir
> /Library/Frameworks/Python.framework/Versions/7.0/lib/python2.7/site-
> packages/ Searching for matplotlib Best match: matplotlib 1.0.1 Adding
> matplotlib 1.0.1 to easy-install.pth file
>
> Using /Library/Frameworks/Python.framework/Versions/7.0/lib/python2.7/site-
> packages Processing dependencies for matplotlib Finished processing
> dependencies for matplotlib
And $easy_install upgrade matplotlib got the following errors:
> BUILDING MATPLOTLIB matplotlib: 1.1.0 python: 2.7.1 |EPD 7.0-2 (32-bit)|
> (r271:86832, Dec 3 2010, 15:41:32) [GCC 4.0.1 (Apple Inc. build 5488)]
> platform: darwin
>
> REQUIRED DEPENDENCIES numpy: 1.5.1 freetype2: found, but unknown version (no
> pkg-config) * WARNING: Could not find 'freetype2' headers in any * of '.',
> './freetype2'.
>
> OPTIONAL BACKEND DEPENDENCIES libpng: found, but unknown version (no pkg-
> config) * Could not find 'libpng' headers in any of '.' Tkinter: Tkinter:
> 81008, Tk: 8.4, Tcl: 8.4 Gtk+: no * Building for Gtk+ requires pygtk; you
> must be able * to "import gtk" in your build/install environment Mac OS X
> native: yes Qt: no Qt4: no Cairo: no
>
> OPTIONAL DATE/TIMEZONE DEPENDENCIES datetime: present, version unknown
> dateutil: 1.5 pytz: 2010o
>
> OPTIONAL USETEX DEPENDENCIES dvipng: 1.13 ghostscript: 8.71 latex: 3.1415926
>
> [Edit setup.cfg to suppress the above messages]
> ============================================================================
> pymods ['pylab'] packages ['matplotlib', 'matplotlib.backends',
> 'matplotlib.backends.qt4_editor', 'matplotlib.projections',
> 'matplotlib.testing', 'matplotlib.testing.jpl_units', 'matplotlib.tests',
> 'mpl_toolkits', 'mpl_toolkits.mplot3d', 'mpl_toolkits.axes_grid',
> 'mpl_toolkits.axes_grid1', 'mpl_toolkits.axisartist',
> 'matplotlib.sphinxext', 'matplotlib.tri', 'matplotlib.delaunay'] warning: no
> files found matching 'KNOWN_BUGS' warning: no files found matching
> 'INTERACTIVE' warning: no files found matching 'MANIFEST' warning: no files
> found matching '**init**.py' warning: no files found matching
> 'examples/data/*' warning: no files found matching 'lib/mpl_toolkits'
> warning: no files found matching 'LICENSE*' under directory 'license' In
> file included from src/ft2font.h:16, from src/ft2font.cpp:3:
> /Library/Frameworks/Python.framework/Versions/7.0/include/ft2build.h:56:38:
> error: freetype/config/ftheader.h: No such file or directory In file
> included from src/ft2font.cpp:3: src/ft2font.h:17:10: error: #include
> expects "FILENAME" or src/ft2font.h:18:10: error: #include expects
> "FILENAME" or src/ft2font.h:19:10: error: #include expects "FILENAME" or
> src/ft2font.h:20:10: error: #include expects "FILENAME" or
> src/ft2font.h:21:10: error: #include expects "FILENAME" or In file included
> from src/ft2font.cpp:3: src/ft2font.h:35: error: ‘FT_Bitmap’ has not been
> declared src/ft2font.h:35: error: ‘FT_Int’ has not been declared
> src/ft2font.h:35: error: ‘FT_Int’ has not been declared src/ft2font.h:91:
> error: expected ‘,’ or ‘...’ before ‘&’ token src/ft2font.h:91: error: ISO
> C++ forbids declaration of ‘FT_Face’ with no type src/ft2font.h:138: error:
> ‘FT_Face’ does not name a type src/ft2font.h:139: error: ‘FT_Matrix’ does
> not name a type src/ft2font.h:140: error: ‘FT_Vector’ does not name a type
> src/ft2font.h:141: error: ‘FT_Error’ does not name a type src/ft2font.h:142:
> error: ‘FT_Glyph’ was not declared in this scope src/ft2font.h:142: error:
> template argument 1 is invalid src/ft2font.h:142: error: template argument 2
> is invalid src/ft2font.h:143: error: ‘FT_Vector’ was not declared in this
> scope src/ft2font.h:143: error: template argument 1 is invalid
> src/ft2font.h:143: error: template argument 2 is invalid src/ft2font.h:149:
> error: ‘FT_BBox’ does not name a type src/ft2font.cpp:51: error:
> ‘FT_Library’ does not name a type src/ft2font.cpp:114: error: variable or
> field ‘draw_bitmap’ declared void src/ft2font.cpp:114: error: ‘FT_Bitmap’
> was not declared in this scope src/ft2font.cpp:114: error: ‘bitmap’ was not
> declared in this scope src/ft2font.cpp:115: error: ‘FT_Int’ was not declared
> in this scope src/ft2font.cpp:116: error: ‘FT_Int’ was not declared in this
> scope error: Setup script exited with error: command 'gcc' failed with exit
> status 1
Sorry if this problem is too elementary, but I just can't figure out where the
error might be. Thank you for your help!
Answer: Try using pypi!
There is already matplotlib 1.1 <http://pypi.python.org/pypi/matplotlib/1.1.0>
|
Moving matplotlib legend outside of the axis makes it cutoff by the figure box
Question: I'm familiar with the following questions:
[Matplotlib savefig with a legend outside the
plot](http://stackoverflow.com/questions/8971834/matplotlib-savefig-with-a-
legend-outside-the-plot)
[How to put the legend out of the
plot](http://stackoverflow.com/questions/4700614/how-to-put-the-legend-out-of-
the-plot)
It seems that the answers in these questions have the luxury of being able to
fiddle with the exact shrinking of the axis so that the legend fits.
Shrinking the axes, however, is not an ideal solution because it makes the
data smaller making it actually more difficult to interpret; particularly when
its complex and there are lots of things going on ... hence needing a large
legend
The example of a complex legend in the documentation demonstrates the need for
this because the legend in their plot actually completely obscures multiple
data points.
<http://matplotlib.sourceforge.net/users/legend_guide.html#legend-of-complex-
plots>
**What I would like to be able to do is dynamically expand the size of the
figure box to accommodate the expanding figure legend.**
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(-2*np.pi, 2*np.pi, 0.1)
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(x, np.sin(x), label='Sine')
ax.plot(x, np.cos(x), label='Cosine')
ax.plot(x, np.arctan(x), label='Inverse tan')
lgd = ax.legend(loc=9, bbox_to_anchor=(0.5,0))
ax.grid('on')
Notice how the final label 'Inverse tan' is actually outside the figure box
(and looks badly cutoff - not publication quality!) 
Finally, I've been told that this is normal behaviour in R and LaTeX, so I'm a
little confused why this is so difficult in python... Is there a historical
reason? Is Matlab equally poor on this matter?
I have the (only slightly) longer version of this code on pastebin
<http://pastebin.com/grVjc007>
Answer: Sorry EMS, but I actually just got another response from the matplotlib
mailling list (Thanks goes out to Benjamin Root).
The code I am looking for is adjusting the savefig call to:
fig.savefig('samplefigure', bbox_extra_artists=(lgd,), bbox_inches='tight')
#Note that the bbox_extra_artists must be an iterable
This is apparently similar to calling tight_layout, but instead you allow
savefig to consider extra artists in the calculation. This did in fact resize
the figure box as desired.
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(-2*np.pi, 2*np.pi, 0.1)
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(x, np.sin(x), label='Sine')
ax.plot(x, np.cos(x), label='Cosine')
ax.plot(x, np.arctan(x), label='Inverse tan')
handles, labels = ax.get_legend_handles_labels()
lgd = ax.legend(handles, labels, loc='upper center', bbox_to_anchor=(0.5,-0.1))
ax.grid('on')
fig.savefig('samplefigure', bbox_extra_artists=(lgd,), bbox_inches='tight')
This produces:

|
Python NumPy Convert FFT To File
Question: I was wondering if it's possible to get the frequencies present in a file with
NumPy, and then alter those frequencies and create a new WAV file from them? I
would like to do some filtering on a file, but I have yet to see a way to read
a WAV file into NumPy, filter it, and then _output the filtered version_. If
anyone could help, that would be great.
Answer: [SciPy](http://scipy.org/) provides functions for [doing
FFTs](http://docs.scipy.org/doc/scipy/reference/fftpack.html) on NumPy arrays,
and also provides functions for
[reading](http://docs.scipy.org/doc/scipy/reference/generated/scipy.io.wavfile.read.html#scipy.io.wavfile.read)
and
[writing](http://docs.scipy.org/doc/scipy/reference/generated/scipy.io.wavfile.write.html#scipy.io.wavfile.write)
them to WAV files. e.g.
from scipy.io.wavfile import read, write
from scipy.fftpack import rfft, irfft
import np as numpy
rate, input = read('input.wav')
transformed = rfft(input)
filtered = function_that_does_the_filtering(transformed)
output = irfft(filtered)
write('output.wav', rate, output)
(`input`, `transformed` and `output` are all numpy arrays)
|
Propagate system call interruptions in threads
Question: I'm running two python threads (`import threading`). Both of them are blocked
on a `open()` call; in fact they try to open named pipes in order to write in
them, so it's a normal behaviour to block until somebody try to read from the
named pipe.
In short, it looks like:
import threading
def f():
open('pipe2', 'r')
if __name__ == '__main__':
t = threading.Thread(target=f)
t.start()
open('pipe1', 'r')
When I type a ^C, the `open()` in the main thread is interrupted (raises
`IOError` with errno == 4).
My problem is: the `t` threads still waits, and I'd like to propagate the
interruption behaviour, in order to make it raise `IOError` too.
Answer: I found this in python docs:
" ... only the main thread can set a new signal handler, and the main thread
will be the only one to receive signals (this is enforced by the Python signal
module, even if the underlying thread implementation supports sending signals
to individual threads). This means that signals can’t be used as a means of
inter-thread communication. Use locks instead. "
Maybe you should also check these docs:
[exceptions.KeyboardInterrupt](http://docs.python.org/release/2.6.7/library/exceptions.html#exceptions.KeyboardInterrupt)
[library/signal.html](http://docs.python.org/release/2.6.7/library/signal.html)
One other idea is to use select to read the pipe asynchronously in the
threads. This works in Linux, not sure about Windows (it's not the cleanest,
nor the best implementation):
#!/usr/bin/python
import threading
import os
import select
def f():
f = os.fdopen(os.open('pipe2', os.O_RDONLY|os.O_NONBLOCK))
finput = [ f ]
foutput = []
# here the pipe is scanned and whatever gets in will be printed out
# ...as long as 'getout' is False
while finput and not getout:
fread, fwrite, fexcep = select.select(finput, foutput, finput)
for q in fread:
if q in finput:
s = q.read()
if len(s) > 0:
print s
if __name__ == '__main__':
getout = False
t = threading.Thread(target=f)
t.start()
try:
open('pipe1', 'r')
except:
getout = True
|
Displaying inline images on iPhone, iPad
Question: I'm trying to create an email in Django with inline images.
msg = EmailMultiAlternatives(...)
image_file = open('file_path', 'rb')
img = MIMEImage(img_data)
image_file.close()
img.add_header('Content-ID', '<image1>')
img.add_header('Content-Disposition', 'inline')
msg.attach(img)
msg.send()
And in the template I would reference it like so:
<img src="cid:image1" />
This works fine in web browsers, outlook, thunderbird ... all except for the
apple mail client on OSX, iPad and iPhone. The images are displayed twice.
They are placed inline correctly but they are also attached to the bottom of
the email. My question is, how do I get rid of the images at the bottom? or
should I approach images in emails differently.
References:
<http://djangosnippets.org/snippets/1507/>
[Django: How to send HTML emails with embedded
images](http://stackoverflow.com/questions/3787755/django-how-to-send-html-
emails-with-embedded-images)
[creating a MIME email template with images to send with python /
django](http://stackoverflow.com/questions/1633109/creating-a-mime-email-
template-with-images-to-send-with-python-django)
Answer: Different email clients choose to render `multipart/mixed` messages in
different ways.
Most clients choose to render each part (in a "multipart" message) inline – in
the order they were added to the email. _However_ , if an image is referred to
in a `text/html` part, most clients _don't display that image again later on_
as part of the "inlining all parts" process.
Apple Mail on OSX and iOS are different, in so far as they _will_ display each
part in a `multipart/mixed` message in the order they were included,
regardless of any inner references between HTML and images. This results in
your images being displayed once within your HTML, and again at the end of the
message where they've been inlined automatically.
The solution is to group your HTML and image assets into a single `related`
part. i.e.:
from django.core.mail import EmailMultiAlternatives
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# HTML + image container
related = MIMEMultipart("related")
# Add the HTML
html = MIMEText('an image: <img src="cid:some_image"/>', "html")
related.attach(html)
# Add an image
with open("icon.png", "rb") as handle:
image = MIMEImage(handle.read())
image.add_header("Content-ID", "<some_image>")
image.add_header("Content-Disposition", "inline")
related.attach(image)
# top level container, defines plain text version
email = EmailMultiAlternatives(subject="demo", body="plain text body",
from_email="[email protected]",
to=["[email protected]"])
# add the HTML version
email.attach(related)
# Indicate that only one of the two types (text vs html) should be rendered
email.mixed_subtype = "alternative"
email.send()
|
How to turn a comma-delimited list of date attributes into a MySQL date value?
Question: Not sure if I've worded my title correctly but here goes. I have a file of
jobs which are all in a similar format to this:
423720,hparviz,RUN,512,22,Mar,10:38,11,April,14:06
Basically from this I need to covert the start date and end date to a format
which allows me to import it into mysql (22-Mar 10:38 - 11-Apr 14:06 or
however MySQL requires dates to be formatted). This data is extracted using a
command in linux, in which I'm manipulating the results to allow importation
to a MySQL database. Would it be easier to manipulate in Linux (during the
command), in Python (in the state I've shown) or MySQL (after importation).
If you need any more details let me know, thanks.
Answer: Assuming every line looks like what you posted:
f=open(filename,"r")
listOfLines=f.readlines()
for line in listOfLines:
splitLine=line.split(",")
print "Day of Month: "+splitLine[4]#this is an example of one piece of info.
print "Month: "+splitLine[5]#this is an example of one piece of info.
|
Is it possible to get a list of printer names in Windows?
Question: I'm trying to create an automatic printer installer for Windows.
If I wanted to pull a list of printers, how would I go about that in Python? I
know there's a way to get a list using a VB script on the command line, but
that gives me additional information I don't need, plus there's no real good
way to import the data into Python (that I know of)
The reasons for doing this is to get the values and put them in a list, and
then have them check against another list. Anything in the one list will be
removed. That ensures that the program won't install duplicate printers.
Answer: You can use [pywin32](http://sourceforge.net/projects/pywin32/files/)'s
`win32print.EnumPrinters()` (more convenient), or invoke the `EnumPrinters()`
API via the `ctypes` module (low dependency).
Here is a fully working `ctypes` version w/o error checking.
# Use EnumPrintersW to list local printers with their names and descriptions.
# Tested with CPython 2.7.10 and IronPython 2.7.5.
import ctypes
from ctypes.wintypes import BYTE, DWORD, LPCWSTR
winspool = ctypes.WinDLL('winspool.drv') # for EnumPrintersW
msvcrt = ctypes.cdll.msvcrt # for malloc, free
# Parameters: modify as you need. See MSDN for detail.
PRINTER_ENUM_LOCAL = 2
Name = None # ignored for PRINTER_ENUM_LOCAL
Level = 1 # or 2, 4, 5
class PRINTER_INFO_1(ctypes.Structure):
_fields_ = [
("Flags", DWORD),
("pDescription", LPCWSTR),
("pName", LPCWSTR),
("pComment", LPCWSTR),
]
# Invoke once with a NULL pointer to get buffer size.
info = ctypes.POINTER(BYTE)()
pcbNeeded = DWORD(0)
pcReturned = DWORD(0) # the number of PRINTER_INFO_1 structures retrieved
winspool.EnumPrintersW(PRINTER_ENUM_LOCAL, Name, Level, ctypes.byref(info), 0,
ctypes.byref(pcbNeeded), ctypes.byref(pcReturned))
bufsize = pcbNeeded.value
buffer = msvcrt.malloc(bufsize)
winspool.EnumPrintersW(PRINTER_ENUM_LOCAL, Name, Level, buffer, bufsize,
ctypes.byref(pcbNeeded), ctypes.byref(pcReturned))
info = ctypes.cast(buffer, ctypes.POINTER(PRINTER_INFO_1))
for i in range(pcReturned.value):
print info[i].pName, '=>', info[i].pDescription
msvcrt.free(buffer)
|
Cannot create test suite for Django
Question: I'm having trouble creating a test suite in Django 1.3.
Say I have an installed app in a directory called `app_name`. One of the files
in that directory is `foo.py` which defines a class named `Foo`. I want to
test that, so I also have a file that directory called `foo_test.py` which
defines a class named `FooTest`. That file looks like:
import unittest
import foo
class FooTest(unittest.TestCase):
def setUp(self):
self.foo_instance = foo.Foo()
... etc
Now down the line I'll have other test cases in other files, and I'll want to
run them all as part of a test suite. So in the same directory `app_name` I
created a file `tests.py` which will define the suite. At first I defined it
like:
import foo_test
from django.test.simple import DjangoTestSuiteRunner
def suite():
runner = DjangoTestSuiteRunner()
return runner.build_suite(['app_name'])
Unfortunately, this fails because calling `runner.build_suite(['app_name'])`
searches `app_name` for a `tests.py` file, executes `suite()`, and this
continues recursively until the Python interpreter stops everything for
exceeding the maximum recursion depth.
Changing `runner.build_suite(['app_name'])` to
runner.build_suite(['app_name.foo_test'])
or
runner.build_suite(['app_name.foo_test.FooTest'])
leads to errors like `ValueError: Test label 'app_name.foo_test' does not
refer to a test`.
And changing it to:
runner.build_suite(['foo_test'])
or
runner.build_suite(['foo_test.FooTest'])
leads to errors like `App with label foo_test could not be found`.
I'm kind of out of ideas at this point. Any help would be very much
appreciated. Thanks!
Answer: See the [Python documentation for organizing
tests](http://docs.python.org/library/unittest.html#organizing-tests), and use
one of the alternative methods there to build your test suite. Incidentally,
none of the recommended methods employ `build_suite`.
|
python string list to list ast.listeral_eval
Question:
>>> import ast
>>> string = '[Small, Medium, Large, X-Large]'
>>> print string
[Small, Medium, Large, X-Large]
>>> string = ast.literal_eval(string)
Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
string = ast.literal_eval(string)
File "C:\Python27\lib\ast.py", line 80, in literal_eval
return _convert(node_or_string)
File "C:\Python27\lib\ast.py", line 60, in _convert
return list(map(_convert, node.elts))
File "C:\Python27\lib\ast.py", line 79, in _convert
raise ValueError('malformed string')
ValueError: malformed string
How to fix?
Answer: [`ast.literal_eval()`](http://docs.python.org/library/ast.html#ast.literal_eval)
only accepts strings which contain valid Python literal structures (strings,
numbers, tuples, lists, dicts, booleans, and `None`).
This is a valid Python expression containing only those literal structures:
["Small", "Medium", "Large", "X-Large"]
This isn't:
[Small, Medium, Large, X-Large]
Two ways to create a string that works:
string = '["Small", "Medium", "Large", "X-Large"]'
string = "['Small', 'Medium', 'Large', 'X-Large']"
|
Sending Hex Values through UDP or TCP socket via parameter passing to script
Question: I know in order to send data through a UDP socket using python has to be in
the following format "\x41" = A .
I have a python script udp_send.py and I want to send in a hex value to
represent a register value on the server side.
I run my script through linux terminal >>python udp_send.py "\x41" . I read
the variable using argv[1] in my python script. I did a len check and it is 3
. It ignore \ and take x, 4 and 1 as 1 byte each whereas I want \x41 to
represent 1 byte only.
I was then trying to concatenate data="\x"+"41" but it did not work.
"\x" is interpreted as escape by python. I am trying to find a way to pass a
hex value into my script and send it via UDP socket?
I have achieved the following so far. Send a hex value defined in python
script via UDP socket .
from socket import *
from sys import *
## Set the socket parameters
host = <ip-define-here>
port = <port-define-here>
buf = 1024
addr = (host,port)
## Create socket
UDPSock = socket(AF_INET,SOCK_DGRAM)
## Send messages
data ='\x41'
#data=argv[1] #commented out
if not data:
print "No data"
else:
if(UDPSock.sendto(data,addr)):
print "Sending message ",data
## Close socket
UDPSock.close()
I used wireshark on server side and saw the hex value 41 appear.
Just to be clear "41"(made of 2 bytes) is not the same as "\x41"(one byte
only) in python.
My simple question is, how can I take a character "41" and join it with "\x"
to form "\x41" so I can assign it to data variable in my python script so I
can send it as hex value 41.
Answer: In your code, you can convert your arg to proper format, then you can call it
with `python udp_send.py 0x41`
arg = sys.argv[1]
# intarg = 65 == 0x41
intarg = int(arg, 16)
# now convert to byte string '\x41'
hexstring = struct.pack('B', intarg)
|
How to keep a C++ class name unmodified with Cython?
Question: I have a C++ class called Foo. If I follow the [Cython C++
tutorial](http://docs.cython.org/src/userguide/wrapping_CPlusPlus.html) I will
need to call the Python class differently, PyFoo for example. However I really
need to call the Python class Foo as well. How to do that efficiently?
Edit: I'm trying to interface an existing C++ library that was previously
interfaced with Boost Python. For different reasons I would like to test
Cython instead. Since with Boost:Python Python classes were called with the
same name as in C++, I would like to continue with this naming convention.
It's not a Python (CPython) requirement to call classes differently, but it
seems to be imposed by Cython, at least in the tutorial.
I can of course use a pure python module to define a Foo class that calls
PyFoo, but this seems both boring and inefficient.
Answer: There are two ways to handle this.
1. Declare C++ class with an alternate name; original name has to be specified in double quotes:
cdef extern from "defs.h" namespace "myns":
cdef cppclass CMyClass "myns::MyClass":
...
Then you can use `MyClass` for your python class and refer to C++ declaration
as `CMyClass`.
Note that original name has to include the namespace explicitly (if it is
namespaced). Cython template arguments (when present) should go after an
alternate name declaration.
2. Declare your C++ classes in a separate `.pxd` file, named differently from your `.pyx` file, then import them with `cimport`.
In cpp_defs.pxd:
cdef extern from "defs.h" namespace "myns":
cdef cppclass MyClass:
...
In py_wrapper.pyx:
cimport cpp_defs as cpp
cdef class MyClass:
cpp.MyClass *_obj
|
Pack array of namedtuples in PYTHON
Question: I need to send an array of namedtuples by a socket.
To create the array of namedtuples I use de following:
listaPeers=[]
for i in range(200):
ipPuerto=collections.namedtuple('ipPuerto', 'ip, puerto')
ipPuerto.ip="121.231.334.22"
ipPuerto.puerto="8988"
listaPeers.append(ipPuerto)
Now that is filled, i need to pack "listaPeers[200]"
How can i do it?
Something like?:
packedData = struct.pack('XXXX',listaPeers)
Answer: First of all you are using namedtuple incorrectly. It should look something
like this:
# ipPuerto is a type
ipPuerto=collections.namedtuple('ipPuerto', 'ip, puerto')
# theTuple is a tuple object
theTuple = ipPuerto("121.231.334.22", "8988")
As for packing, it depends what you want to use on the other end. If the data
will be read by Python, you can just use Pickle module.
import cPickle as Pickle
pickledTuple = Pickle.dumps(theTuple)
You can pickle whole array of them at once.
|
What modules should I use to create a game tree?
Question: I'm writing a project for a Python coding class and I have a question. I'm
writing a [Reversi](http://en.wikipedia.org/wiki/Reversi) engine that will
look several moves ahead in a game and then pick the move that it thinks is
best. While I understand that python isn't an ideal language for this (because
it's not as fast as some other languages), I think that it's possible to write
code that is at least functional while still maybe being a little slow.
That being said, I am in the process of trying to create two tables: a game
board (think a matrix) and a game tree that will hold integers. I want to use
something memory-efficient and fast to append, delete, and read entries.
The board that I am using right now is not very efficient. I wanted to ask
what modules anyone would suggest (with instructions on how to use them) to
write something that would make an equivalent of this but lighter on memory
(examples: array, numpy; except I don't know how to use either of these):
self.board = [[0, 0, 0, 0, 0, 0, 0, 0,],
[0, 0, 0, 0, 0, 0, 0, 0,],
[0, 0, 0, 0, 0, 0, 0, 0,],
[0, 0, 0, 1, 2, 0, 0, 0,],
[0, 0, 0, 2, 1, 0, 0, 0,],
[0, 0, 0, 0, 0, 0, 0, 0,]
[0, 0, 0, 0, 0, 0, 0, 0,],
[0, 0, 0, 0, 0, 0, 0, 0,]]
For the game tree I have ideas depending on how lightweight a list of lists
should be. An idea that I'm working with written in standard python is similar
to:
tree_zero = %
tree_one = [%, %, %]
tree_two = [[%, %, %], [%, %, %], [%, %, %]]
tree_thre = [[[%, %, %], [%, %, %], [%, %, %]],
[[%, %, %], [%, %, %], [%, %, %]],
[[%, %, %], [%, %, %], [%, %, %]]],
tree_four = [[[[%, %, %], [%, %, %], [%, %, %]],
[[%, %, %], [%, %, %], [%, %, %]],
[[%, %, %], [%, %, %], [%, %, %]]],
[[[%, %, %], [%, %, %], [%, %, %]],
[[%, %, %], [%, %, %], [%, %, %]],
[[%, %, %], [%, %, %], [%, %, %]]],
[[[%, %, %], [%, %, %], [%, %, %]],
[[%, %, %], [%, %, %], [%, %, %]],
[[%, %, %], [%, %, %], [%, %, %]]]]
Where each % would be one of the boards given above (and is more than ideal:
not every turn has exactly three options). But this is a slow and heavy object
that is difficult for python to use memory-efficiently (especially if I go
deeper than 4-ply).
If anyone has worked with programs like this before or has ideas of efficient
modules to import let me know!
For an example of a game tree, think of the [wikipedia
page](http://en.wikipedia.org/wiki/Game_tree) and especially the first picture
on the page.
EDIT: Ideally, I would like to look further than four moves ahead, this is
just an example of how the first four levels would look. Also, there will be
multiple copies of the given trees floating around for use. Speed is important
for something that grows exponentially like this.
Answer: In my opinion, Python is utterly perfect for this sort of work! That is, I had
a tremendously fun and productive time doing AI for a board game using Python.
My first recommendation is to explore [Bit
Boards](http://www.fzibi.com/cchess/bitboards.htm). Though the application
example here is for chess, the concept is perfectly transferable to Reversi.
Using zeroes and ones to represent the presence of pieces on a set-sized board
not only has the advantage of lower memory footprint, it has the advantage of
increased speed of calculating (bitwise operations are faster than equality
ones).
In addition, you should redesign your model to somehow implement recursion
(facilitated by a scoring function). Such an implementation means you can
write a single function and allow it to scale infinite move depth (or rather,
unlimited by your design, limited only by resources) rather than anticipate
and hard-code the logic for 1,2,3,4 moves. A well-designed function to this
effect works for both sides (players) and can then be halted to choose the
best options that fit within a threshold (halted by any criteria you choose,
positions calculated/real-time spent).
For reference, here is the github for a [board game called
Thud](https://github.com/hexparrot/thudgame) I made with almost exactly the
same requirements as your program. Here, I worked with a 17x17 board, three
different pieces and two different strategies--which we both can see is
already more complex than Reversi's rules.
Oh, and a good recursive model also accommodates multi-threading!
|
Using Requests python library to connect Django app failed on authentication
Question: Maybe a stupid question here: Is Requests(A python HTTP lib) support Django
1.4 ?
I use **Requests** follow the Official Quick Start like below:
requests.get('http://127.0.0.1:8000/getAllTracks', auth=('myUser', 'myPass'))
but i never get authentication right.(Of course i've checked the url,
username, password again and again.)
The above url '**http://127.0.0.1:8000/getAllTracks** ' matches an url pattern
of the url.py of a Django project, and that url pattern's callback is the
'**getAllTracks** ' view of a Django app.
If i comment out the authentication code of the '**getAllTracks** ' view, then
the above code works OK, but if i add those authentication code back for the
view, then the above code never get authenticated right.
The authentication code of the view is actually very simple, exactly like
below (The second line):
def getAllTracks(request):
if request.user.is_authenticated():
tracks = Tracks.objects.all()
if tracks:
# Do sth. here
Which means if i delete the above second line(with some indents adjustments of
course), then the **requests.get()** operation do the right thing for me, but
if not(keep the second line), then it never get it right.
Any help would be appreciated.
Answer: In Django authentication works in following way:
* There is a SessionMiddleware and AuthenticationMiddleware. The process_request() of both these classes is called before any view is called.
* SessionMiddleware uses cookies at a lower level. It checks for a cookie named `sessionid` and try to associate this cookie with a user.
* AuthenticationMiddleware checks if this cookie is associated with an user then sets `request.user` as that corresponding user. If the cookie `sessionid` is not found or can't be associated with any user, then `request.user` is set to an instance of `AnonymousUser()`.
* Since Http is a stateless protocol, django maintains session for a particular user using these two middlewares and using cookies at a lower level.
Coming to the code, so that `requests` can work with django.
You must first call the view where you authenticate and login the user. The
response from this view will contain `sessionid` in cookies.
You should use this cookie and send it in the next request so that django can
authenticate this particular user and so that your
`request.user.is_authenticated()` passes.
from django.contrib.auth import authenticate, login
def login_user(request):
user = authenticate(username=request.POST['username'], password=request.POST['password'])
login(request, user)
return HttpResponse("Logged In")
def getAllTracks(request):
if request.user.is_authenticated():
return HttpResponse("Authenticated user")
else:
return HttpResponse("Non Authenticated user")
Making the requests:
import requests
resp = requests.post('http://127.0.0.1:8000/login/', {'username': 'akshar', 'password': 'abc'})
print resp.status_code
200 #output
print resp.content
'Logged In' #output
cookies = dict(sessionid=resp.cookies['sessionid'])
print cookies
{'sessionid': '1fe38ea7b22b4d4f8d1b391e1ea816c0'} #output
response_two = requests.get('http://127.0.0.1:8000/getAllTracks/', cookies=cookies)
Notice that we pass cookies using `cookies` keyword argument
print response_two.status_code
200 #output
print response_two.content
'Authenticated user' #output
So, our `request.user.is_authenticated()` worked properly.
response_three = requests.get('http://127.0.0.1:8000/hogwarts/getAllTracks/')
Notice we do not pass the cookies here.
print response_three.content
'Non Authenticated user' #output
|
Scrapping: How to fetch an attribute in a <abbr> tag
Question: I am using **lxml and python** to scrap through a page. The link to the page
is **[HERE](http://www.insiderpages.com/b/3721895833/central-kia-of-irving-
irving)**. The hiccup I face right now is how to fetch the attribute in the
tag. For example the 3 Gold stars at the top of the page, they have a html
<abbr title="3" class="average rating large star3">★★★☆☆</abbr>
Here I want to fetch the title so that I know how many stars did this location
get.
I have tried doing a couple of things including this:
response = urllib.urlopen('http://www.insiderpages.com/b/3721895833/central-kia-of-irving-irving').read()
mo = re.search(r'<div class="rating_box">.*?</div>', response)
div = html.fromstring(mo.group(0))
title = div.find("abbr").attrib["title"]
print title
But does not work for me. Help would be appreciated.
Answer: [Don't use regex to extract data from
html.](http://stackoverflow.com/a/1732454/843822) You have lxml, use it's
power ([XPath](http://lxml.de/xpathxslt.html#xpath)).
>>> import lxml.html as html
>>> page = html.parse("http://www.insiderpages.com/b/3721895833/central-kia-of-irving-irving")
>>> print page.xpath("//div[@class='rating_box']/abbr/@title")
['3']
|
python: unable to specify relative path for dll import
Question: I am trying to load a dll in python, and can only do so if I enter the
absolute path. I would like to use a relative path, or environment variables.
The only thing that works is if I specify the exact path (C:...) I even tried
to get the dll to build directly in the same folder as the py file, it still
didn't work.
What I have:
MY_DLL = r'c:\full_path\output\Win32\Debug\my.dll'
#MY_DLL = r'my.dll' #this doesn't work but it is what I want
#MY_DLL = r'$(env_var)\dir\output\$(Platform)\$(Configuration)\my.dll' #this doesn't work either but would be good too
Help ?
Answer: I don't know about cdll on windows or really much about ctypes in general,
however, you can manipulate paths quite easily using os.path:
import os.path
p1="path.dll"
print (os.path.abspath(p1))
p2="${env_var}/path.dll" #Make sure you set env_var in the calling environment...Otherwise it won't be expanded...
print (os.path.expandvars(p2))
|
matplotlib bar plot errbar
Question: in the official example,we can use bar function like this:
#!/usr/bin/env python
# a stacked bar plot with errorbars
import numpy as np
import matplotlib.pyplot as plt
N = 5
menMeans = (20, 35, 30, 35, 27)
womenMeans = (25, 32, 34, 20, 25)
menStd = (2, 3, 4, 1, 2)
womenStd = (3, 5, 2, 3, 3)
ind = np.arange(N) # the x locations for the groups
width = 0.35 # the width of the bars: can also be len(x) sequence
p1 = plt.bar(ind, menMeans, width, color='r', yerr=womenStd,align='center')
p2 = plt.bar(ind, womenMeans, width, color='y',bottom=menMeans, yerr=menStd,align='center')
plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5') )
plt.yticks(np.arange(0,81,10))
plt.legend( (p1[0], p2[0]), ('Men', 'Women') )
plt.show()
What I don't understand is that, **why the womenStd is used as the menMeans's
yerr, and the menStd is used as womenMeans's yerr.**
Could you please explain that for me? Thanks very much.
Answer: It could very plausibly be a typo. It doesn't appear to be important to the
example at all, which exists to illustrate matplotlib functionality.
|
python websocket handshake (RFC 6455)
Question: I am trying to implement a simple websoket server on python, using RFC 6455
protocol. I took handshake format from
[here](http://en.wikipedia.org/wiki/WebSocket#WebSocket_protocol_handshake)
and [here](http://tools.ietf.org/html/rfc6455#section-1.3).
I am using Chromium 17 and Firefox 11 as clients, and getting this error:
`Uncaught Error: INVALID_STATE_ERR: DOM Exception 11`
I expect to see `hello from server` in my browser and `hello from client` in
server log.
I guess my handshake is wrong, can you point me to my mistake?
## Server log, request:
GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: 127.0.0.1:8999
Origin: null
Sec-WebSocket-Key: 8rYWWxsBPEigeGKDRNOndg==
Sec-WebSocket-Version: 13
## Server log, response:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: 3aDXXmPbE5e9i08zb9mygfPlCVw=
## Raw-string response:
HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: 3aDXXmPbE5e9i08zb9mygfPlCVw=\r\n\r\n
## Server code:
import socket
import re
from base64 import b64encode
from hashlib import sha1
websocket_answer = (
'HTTP/1.1 101 Switching Protocols',
'Upgrade: websocket',
'Connection: Upgrade',
'Sec-WebSocket-Accept: {key}\r\n\r\n',
)
GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 8999))
s.listen(1)
client, address = s.accept()
text = client.recv(1024)
print text
key = (re.search('Sec-WebSocket-Key:\s+(.*?)[\n\r]+', text)
.groups()[0]
.strip())
response_key = b64encode(sha1(key + GUID).digest())
response = '\r\n'.join(websocket_answer).format(key=response_key)
print response
client.send(response)
print client.recv(1024)
client.send('hello from server')
## Client code:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript">
var s = new WebSocket('ws://127.0.0.1:8999');
s.onmessage = function(t){alert(t)};
s.send('hello from client');
</script>
</head>
<body>
</body>
</html>
Answer: Your server handshake code looks good.
The client code looks like it'll try to send a message before the
(asynchronous) handshake completes however. You could avoid this by moving
your message send into your websocket's onopen method.
Once the connection is established, the server does not send or receive
messages as plain text. See the [data
framing](http://tools.ietf.org/html/rfc6455#section-5) section of the spec for
details. (Client code can ignore this as the browser takes care of data
framing for you.)
|
Unable to write into files
Question: This is a bit strange. My program isn't able to write the output to a file.
Its even not showing any error. I simultaneously used standard output and
found that its showing..
This is my code: (Python 2.7)
#!/usr/bin/env python
import re
def isRecycled(n,m):
n = str(n)
m = str(m)
try:
...........
...........
My Code.
except ValueError:
return False
ip = open("C-small-attempt0.in", "r")
op = open("output.txt", "a")
for num, eachLine in enumerate( ip.readlines()[1:] ):
......
......
My code
## This is WORKING
print "Case #%d: %d" %(num+1, count)
## This is NOT Working
op.write("Case #%d: %d" %(num+1, count))
Can anyone tell me why this is not writing to the file.
I tried to use `"w+"`, `"w"` modes and also `writelines()` method but they
didn't work.
**Edited**
However, it worked when I closed the file using `op.close()`
1. Why this is happening? (I didn't encounter it previously)
2. Does python immediately write to the file as soon as it finds `op.write()`?
Answer: You need to close the file for it to write to disk. Add op.close() to the end
of your code.
|
GAE datastore - count records between one minute ago and two minutes ago?
Question: I am using GAE datastore with python and I want to count and display the
number of records between two recent dates. for examples, how many records
exist with a time signature between two minutes ago and three minutes ago in
the datastore. Thank you.
#!/usr/bin/env python
import wsgiref.handlers
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from datetime import datetime
class Voice(db.Model):
when = db.DateTimeProperty(auto_now_add=True)
class MyHandler(webapp.RequestHandler):
def get(self):
voices = db.GqlQuery(
'SELECT * FROM Voice '
'ORDER BY when DESC')
values = {
'voices': voices
}
self.response.out.write(template.render('main.html', values))
def post(self):
voice = Voice()
voice.put()
self.redirect('/')
self.response.out.write('posted!')
def main():
app = webapp.WSGIApplication([
(r'.*', MyHandler)], debug=True)
wsgiref.handlers.CGIHandler().run(app)
if __name__ == "__main__":
main()
Answer:
count = db.Query().filter('when >', two_minutes_ago).filter('when <', one_minute_ago).count()
You can learn more about queries in the
[documentation](https://developers.google.com/appengine/docs/python/datastore/queryclass).
To get the values of `two_minutes_ago` and `one_minute_ago` you can use the
[`datetime`](http://docs.python.org/library/datetime.html) module:
>>> datetime.datetime.now()
datetime.datetime(2012, 4, 14, 14, 26, 18, 343269)
>>> datetime.datetime.now() - datetime.timedelta(minutes=1)
datetime.datetime(2012, 4, 14, 14, 25, 49, 860390)
Try it out in your Python REPL to get more familiar with it.
|
How do I get the visitor's current timezone then convert timezone.now() to string of the local time in Django 1.4?
Question: I understand that the best practice now with Django 1.4 is to store all
`datetime` in UTC and I agree with that. I also understand that all timezone
conversation should be done in the template level like this:
{% load tz %}
{% timezone "Europe/Paris" %}
Paris time: {{ value }}
{% endtimezone %}
However, I need to convert the UTC time to the `request`'s local time all in
Python. I can't use the template tags since I am returning the string in JSON
using Ajax (more specifically [Dajaxice](http://www.dajaxproject.com/)).
Currently this is my code `ajax.py`:
# checked is from the checkbox's this.value (Javascript).
datetime = timezone.now() if checked else None
$ order_pk is sent to the Ajax function.
order = Order.objects.get(pk=order_pk)
order.time = datetime
order.save()
return simplejson.dumps({
'error': False,
'datetime': dateformat.format(datetime, 'F j, Y, P') if checked else 'None'
})
So even if the current time is `April 14, 2012, 5:52 p.m.` in EST time (my
local timezone), the JSON response will return `April 14, 2012, 9:52 p.m`,
because that is the UTC time.
Also I noticed that Django stores a template variable called `TIME_ZONE` for
each request (not actually part of the `request` variable), so since my is
`America/New_York`, I'm assuming that Django can figure out each visitor's own
local timezone (based on HTTP header)?
Anyway, so my question is two-fold:
1. How do I get the visitor's local timezone in my `ajax.py`? (Probably pass it as a string argument like `{{ TIME_ZONE }}`)
2. With the visitor's local timezone, how to convert the UTC `timezone.now()` to the local timezone and output as a string using Django's `dateformat`?
**EDIT:** for @agf
`timezone.now()` gives the UTC time when `USE_TZ = True`:
# From django.utils.timezone
def now():
"""
Returns an aware or naive datetime.datetime, depending on settings.USE_TZ.
"""
if settings.USE_TZ:
# timeit shows that datetime.now(tz=utc) is 24% slower
return datetime.utcnow().replace(tzinfo=utc)
else:
return datetime.now()
Is there anyway to convert a `datetime` to something other than UTC? For
example, can I do something like `current_time = timezone.now()`, then
`current_time.replace(tzinfo=est)` (EST = Eastern Standard Time)?
Answer: You need to read the [Django Timezones
docs](https://docs.djangoproject.com/en/1.4/topics/i18n/timezones/) carefully.
One important point:
> there's no equivalent of the Accept-Language HTTP header that Django could
> use to determine the user's time zone automatically.
You have to ask the user what their timezone is or just use a default.
You also need to make sure:
USE_TZ = True
in your `settings.py`.
Once you have a timezone `tz`, you can:
from django.utils import timezone
timezone.activate(tz)
datetime = timezone.now() if checked else None
to get a timezone-aware `datetime` object in timezone `tz`.
|
Python thread waiting for copying the file
Question: I have a c program which is running in thread and appending some data in a
file. I want to run a python thread which will copy the same file(which c
thread is writing) after some time interval. Is there any safe way to do this?
I am doing this in linux OS.
Answer: There are a lot of important details to your scenario that aren't mentioned,
but working on the assumption that you can't write a locking mechanism in to
the C program and then use it in the Python program (for example, you're using
an existing application on your system), you could look in to os.stat and
check the last modified time, m_time. That is of course reliant on you knowing
that a recent m_time means the file won't be opened again in the C program and
used again.
If the file handle is kept open in the C program at all times, and written to
occasionally then there is a not a lot of easy options for knowing when it is
and isn't being written to.
|
Django MongoDB Engine DebugCursor "not JSON serializable"
Question: Trying to serialize a MongoDB cursor in Django
import json
from pymongo import json_util
results = json.dumps(results, default=json_util.default, separators=(',', ':'))
Where the original `results` is something like
[{u'_id': ObjectId('4f7c0f34705ff8294a00006f'),
u'identifier': u'1',
u'items': [{u'amount': 9.99, u'name': u'PapayaWhip', u'quantity': 1}],
u'location': None,
u'timestamp': datetime.datetime(2012, 4, 4, 10, 7, 0, 596000),
u'total': 141.25}]
_**Edit_** : Obtained by using something like
from django.db import connections
connection = connections['default']
results = connection.get_collection('papayas_papaya')
results = results.find({
'identifier': '1',
})
Gives me
TypeError: <django_mongodb_engine.utils.DebugCursor object> is not JSON serializable
Does anyone know what I'm doing wrong?
Using
[json_util](http://api.mongodb.org/python/1.7/api/pymongo/json_util.html)
should serialize MongoDB _documents_ , maybe my issue is that I'm trying to
serliaze a _cursor_. (How do I get the document from the cursor? A simple
_tuple_ "cast"?)
Cheers!
Answer: Are you trying to serialize just one piece of data? If so, just change
results = results.find({
'identifier': '1',
})
to
results = results.find_one({
'identifier': '1',
})
(Although you really should make a distinction between your results and the
variable representing your collection.)
If you are trying to serialize multiple pieces of data, you can keep the
`find` and then iterate through the cursor and serialize each piece of data.
serialized_results = [json.dumps(result, default=json_util.default, separators=(',', ':')) for result in results]
|
How to send an HTTP request from a Mac app to a Django server?
Question: I want to send an HTTP request like:
"http://.../mydjangosite?var1=value1&var2=value2&var3=value3"
to my Django server and want this last to send response with a boolean value
`"1"` if `value1,2,3` are equal to the ones in my database and `"0"` if not.
This is the first time I develop with Django so if anyone has tips to give me
I would be grateful.
Sorry for bad English, if anyone didn't understand my question please feel
free to tell it to me.
Kind regards.
EDIT :
first of all thanks for your fast answers!!
You're right i'm too generic i'll explain more precisly. I'm working on a
project where we have some mac applications. We want to create a "plateform"
where clients of those applications would be able to get last versions
developped of those lasts. The purpose is then to create at first, a django
server where we store informations about version of the software..etc. And
then, when user of the software execute it, it'll send automaticaly an http
request to the server in order to "check" if a new version exists. If yes, we
invite him to download new version, if no, then it continues.
From now, i've been working on the django server, i started with the tutorial
at django's site. I created my models.py example :
class Version(models.Model):
name = models.CharField(max_length = 200)
description = models.TextField()
id_version = models.IntegerField()
date_version = models.DateTimeField('Version published')
def was_published_today(self):
return self.date_version.date() == datetime.date.today()
def get_number_version(self):
return "%d" % (self.id_version)
def save(self):
top = Version.objects.order_by('-id_version')[0]
self.id_version = top.id_version + 1
super(Version, self).save()
I changed the urls.py like that :
urlpatterns = patterns('',
# Examples:
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
url(r'^versionsupdate/version/$','versionsupdate.views.version'),
So, what I want, is from a mac app, send an http request to the server django
like that "http://.../versionsupdate/version?version=1..." and then, in my
server catch the request, get the value after the "=" compare it to the value
of "id_version" and response back with a boolean value depending on if it
equals or not.
I hope this is clear i'm not sure^^ and please tell me if what i did from now
is good or not, i'm new to django/python so i'm note sure to be on the good
direction.
Thanks again for your help!
Answer: First. From Django-side you need to specific data type response
(render_to_response headers). For example it can be json.
Second. From python script on client-side you can get url using urllib or
urllib2.
import urllib
import urllib2
url = 'http://www.acme.com/users/details'
params = urllib.urlencode({
'firstName': 'John',
'lastName': 'Doe'
})
response = urllib2.urlopen(url, params).read()
Then just analyze response.
|
add boxplot to other graph in python
Question: 
These two graphs have exactly the same x axis value of each point, is it
possible to display the box whisker on top of the first graph?
I tried this:
fig1 = plt.figure()
ax = fig1.add_subplot(211)
ax.set_xscale('log')
ax.plot(x7,y7,'c+-')
ax.plot(x8,y8,'m+-')
ax.plot(x9,y9,'g+-')
ax.boxplot(dataset)
xtickNames = plt.setp(ax, xticklabels=boxx)
plt.setp(xtickNames)
The results only display the box whisker graph without the other three lines,
so, I tried this instead:
fig1 = plt.figure()
ax = fig1.add_subplot(211)
ax2 = fig1.add_subplot(212)
ax.set_xscale('log')
ax.plot(x7,y7,'c+-')
ax.plot(x8,y8,'m+-')
ax.plot(x9,y9,'g+-')
ax2.set_xscale('log')
ax2.boxplot(dataset)
xtickNames = plt.setp(ax2, xticklabels=boxx)
plt.setp(xtickNames)
But I want them to be shown in the same graph, is that possible?
Answer: If you want two graphs with comparable X and Y ranges to appear one on top of
the other, you can try "Hold". For example:
import pylab
pylab.plot([1,2,3,4],[4,3,2,1])
pylab.hold(True)
pylab.plot([1,2,3,4],[1,2,3,4])
|
Dymo Label Printer from QWebview?
Question: I am attempting to use the Dymo example pages to print a label from a QWebview
in a Python/Qt based application. The example works fine in a major browser
(IE, FF, Chrome have been tested). However, when the example page is loaded in
the QWebview, I get the following error:
`DYMO.Label.Framework.js line 1: Error: DYMO Label Framework Plugin is not
installed`
I'm unsure why it would work fine in another browser, but not in the web view
of my application. What is the proper way to get these Dymo examples to load
into the webview?
This is the sample page that works in the major browsers by fails in the
QWebview (You'll need a Dymo printer to print, but otherwise it'll load with
an alert telling that no printers were found):
<http://labelwriter.com/software/dls/sdk/samples/js/PreviewAndPrintLabel/PreviewAndPrintLabel.html>
When I load it in the webview, I don't even get the alert (which makes sense
since the error above is found on line 1).
Answer: I spoke with the vendor and was told that this is not a supported use of their
software. So, instead of using a QWebView, I used the `win32com` package to do
this with Dymo's SDK. The code below uses the Dymo LabelWriter to print a
single label with 1 variable field on it.
from win32com.client import Dispatch
labelCom = Dispatch('Dymo.DymoAddIn')
labelText = Dispatch('Dymo.DymoLabels')
isOpen = labelCom.Open('test.label')
selectPrinter = 'DYMO LabelWriter 450'
labelCom.SelectPrinter(selectPrinter)
labelText.SetField('VAR_TEXT', 'QGJ2148')
labelCom.StartPrintJob()
labelCom.Print(1,False)
labelCom.EndPrintJob()
The `StartPrintJob` and `EndPrintJob` wrap the `Print` because it is faster
according to the SDK notes.
|
TypeError: cannot concatenate 'str' and 'type' objects
Question: Before I get to my issue, I have searched around for an answer but cannot seem
to find anything specific to my case.
Ok, basically I call my script via cmd and pass in 16 args and use them to set
some variables I have. I am creating a custom html report for our company use.
These variables I just use to dynamically set the values I want where they are
in html string. The error I get is:
>>> python -u "htmltest.py" 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Traceback (most recent call last):
File "htmltest.py", line 162, in <module>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border- left: 1px solid #000000; border-right: 1px solid #000000" COLSPAN=3 ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;0;0.000000"><FONT FACE="Calibri" COLOR="#000000">"""+C9+"""</FONT></TD>
TypeError: cannot concatenate 'str' and 'type' objects
>>> Exit Code: 1
I have tried removing some of the variables like C9 etc to see what it does
but it just errors on the one previous to that so I assume I have to make the
variables the same as how I am doing my string?
The code is:
import sys
import datetime
#for each arg sent we can set each value starting at 2 since 1 is the actual name of the script
CalFixUsed = sys.argv[1]
StationNumber = sys.argv[2]
Operator = sys.argv[3]
MMCalDueDate = sys.argv[4]
MMEquipID = sys.argv[5]
MBCalDueDate = sys.argv[6]
MeterBoxID = sys.argv[7]
C1 = sys.argv[8]
C2 = sys.argv[9]
C3 = sys.argv[10]
C4 = sys.argv[11]
C5 = sys.argv[12]
C6 = sys.argv[13]
C7 = sys.argv[14]
C8 = sys.argv[15]
C9 = sys.argv[16]
filename = "Daily Verification Test.html"
today = datetime.date
html = """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<HTML>
<HEAD>
<META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; charset=windows-1252">
<TITLE></TITLE>
<META NAME="GENERATOR" CONTENT="OpenOffice.org 3.3 (Win32)">
<META NAME="CREATED" CONTENT="0;0">
<META NAME="CHANGED" CONTENT="0;0">
<STYLE>
<!--
BODY,DIV,TABLE,THEAD,TBODY,TFOOT,TR,TH,TD,P { font-family:"Arial"; font- size:x-small }
-->
</STYLE>
</HEAD>
<BODY TEXT="#000000">
<TABLE FRAME=VOID CELLSPACING=0 COLS=8 RULES=NONE BORDER=0>
<COLGROUP><COL WIDTH=43><COL WIDTH=65><COL WIDTH=57><COL WIDTH=65><COL WIDTH=81> <COL WIDTH=65><COL WIDTH=65><COL WIDTH=65></COLGROUP>
<TBODY>
<TR>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000" COLSPAN=3 WIDTH=164 HEIGHT=20 ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000">Calibration Fixture Used:</FONT></TD>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-right: 1px solid #000000" COLSPAN=3 WIDTH=210 ALIGN=CENTER VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000">"""+CalFixUsed+"""</FONT></TD>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000" WIDTH=65 ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000">Station #:</FONT></TD>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-right: 1px solid #000000" WIDTH=65 ALIGN=CENTER VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000">"""+StationNumber+"""</FONT></TD>
</TR>
<TR>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000" COLSPAN=2 HEIGHT=19 ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000">Operator Name:</FONT></TD>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-right: 1px solid #000000" COLSPAN=6 ALIGN=CENTER VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000">"""+Operator+"""</FONT></TD>
</TR>
<TR>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" COLSPAN=3 HEIGHT=19 ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD STYLE="border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" COLSPAN=3 ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000">Calibration Due Date</FONT></TD>
<TD STYLE="border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" COLSPAN=2 ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000">Equipment ID #</FONT></TD>
</TR>
<TR>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" COLSPAN=3 HEIGHT=20 ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000">Multimeter</FONT></TD>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" COLSPAN=3 ALIGN=CENTER VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000">"""+MMCalDueDate+"""</FONT></TD>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" COLSPAN=2 ALIGN=CENTER VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000">"""+MMEquipID+"""</FONT></TD>
</TR>
<TR>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000" HEIGHT=20 ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000">Meter Box</FONT></TD>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000" ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000" ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" COLSPAN=3 ALIGN=CENTER VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000">"""+MBCalDueDate+"""</FONT></TD>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" COLSPAN=2 ALIGN=CENTER VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000">"""+MeterBoxID+"""</FONT></TD>
</TR>
<TR>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" HEIGHT=19 ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000">Date:</FONT></TD>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" COLSPAN=2 ALIGN=CENTER VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000">"""+today+"""</FONT></TD>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" COLSPAN=5 ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
</TR>
<TR>
<TD STYLE="border-top: 1px solid #000000; border-left: 1px solid #000000" HEIGHT=19 ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD STYLE="border-top: 1px solid #000000" ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD STYLE="border-top: 1px solid #000000" ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD STYLE="border-top: 1px solid #000000" ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000" ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000" ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000" ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-right: 1px solid #000000" ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
</TR>
<TR>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" COLSPAN=4 HEIGHT=19 ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000">Contact Resistance Reading</FONT></TD>
<TD ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000">Comments:</FONT></TD>
<TD ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD STYLE="border-top: 1px solid #000000; border-right: 1px solid #000000" ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
</TR>
<TR>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" HEIGHT=19 ALIGN=CENTER VALIGN=BOTTOM SDVAL="1" SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000">1</FONT></TD>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" COLSPAN=3 ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;0;0.000000"><FONT FACE="Calibri" COLOR="#000000">"""+C1+"""</FONT></TD>
<TD ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD STYLE="border-right: 1px solid #000000" ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
</TR>
<TR>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" HEIGHT=19 ALIGN=CENTER VALIGN=BOTTOM SDVAL="2" SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000">2</FONT></TD>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" COLSPAN=3 ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;0;0.000000"><FONT FACE="Calibri" COLOR="#000000">"""+C2+"""</FONT></TD>
<TD ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD STYLE="border-right: 1px solid #000000" ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
</TR>
<TR>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" HEIGHT=19 ALIGN=CENTER VALIGN=BOTTOM SDVAL="3" SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000">3</FONT></TD>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" COLSPAN=3 ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;0;0.000000"><FONT FACE="Calibri" COLOR="#000000">"""+C3+"""</FONT></TD>
<TD ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD STYLE="border-right: 1px solid #000000" ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
</TR>
<TR>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" HEIGHT=19 ALIGN=CENTER VALIGN=BOTTOM SDVAL="4" SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000">4</FONT></TD>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" COLSPAN=3 ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;0;0.000000"><FONT FACE="Calibri" COLOR="#000000">"""+C4+"""</FONT></TD>
<TD ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD STYLE="border-right: 1px solid #000000" ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
</TR>
<TR>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" HEIGHT=19 ALIGN=CENTER VALIGN=BOTTOM SDVAL="5" SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000">5</FONT></TD>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" COLSPAN=3 ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;0;0.000000"><FONT FACE="Calibri" COLOR="#000000">"""+C5+"""</FONT></TD>
<TD ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD STYLE="border-right: 1px solid #000000" ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
</TR>
<TR>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" HEIGHT=19 ALIGN=CENTER VALIGN=BOTTOM SDVAL="6" SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000">6</FONT></TD>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" COLSPAN=3 ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;0;0.000000"><FONT FACE="Calibri" COLOR="#000000">"""+C6+"""</FONT></TD>
<TD ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD STYLE="border-right: 1px solid #000000" ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
</TR>
<TR>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" HEIGHT=19 ALIGN=CENTER VALIGN=BOTTOM SDVAL="7" SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000">7</FONT></TD>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" COLSPAN=3 ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;0;0.000000"><FONT FACE="Calibri" COLOR="#000000">"""+C7+"""</FONT></TD>
<TD ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD STYLE="border-right: 1px solid #000000" ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
</TR>
<TR>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" HEIGHT=19 ALIGN=CENTER VALIGN=BOTTOM SDVAL="8" SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000">8</FONT></TD>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" COLSPAN=3 ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;0;0.000000"><FONT FACE="Calibri" COLOR="#000000">"""+C8+"""</FONT></TD>
<TD ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
<TD STYLE="border-bottom: 1px solid #000000; border-right: 1px solid #000000" ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"><BR></FONT></TD>
</TR>
<TR>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" HEIGHT=19 ALIGN=CENTER VALIGN=BOTTOM SDVAL="9" SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000">9</FONT></TD>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" COLSPAN=3 ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;0;0.000000"><FONT FACE="Calibri" COLOR="#000000">"""+C9+"""</FONT></TD>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" COLSPAN=2 ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000">Verification Initials:</FONT></TD>
<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" COLSPAN=2 ALIGN=LEFT VALIGN=BOTTOM SDNUM="1033;1033;General"><FONT FACE="Calibri" COLOR="#000000"> <BR></FONT></TD>
</TR>
</TBODY>
</TABLE>
</BODY>
</HTML>
"""
# Create a file object:
# in "write" mode
FILE = open(filename,"w")
# Write all the lines at once:
FILE.write(html)
FILE.close()
Can someone point me in the right direction to fix this?
Thanks.
Answer:
today = datetime.date
sets `today` to the type `datetime.date`. Most likely, you want to set it to
an object of type `datetime.date`, like this:
today = datetime.date(2012, 4, 16)
# or, to always get the current day
today = datetime.datetime.now().date()
You'll also need to generate a string from that date object. You can do that
with [`str`](http://docs.python.org/library/functions.html#str):
"""...""" + str(today) + """..."""
If you want another representation, have a look at
[`datetime.date.isoformat`](http://docs.python.org/library/datetime.html#datetime.date.isoformat)
and
[`datetime.date.strftime`](http://docs.python.org/library/datetime.html#datetime.date.strftime).
|
Efficient iteration over a list representation of multidimensional indices (of arbitrary dimension)
Question: I work with multidimensional structures of arbitrary dimension. I have a
Python list of `xrange` iterators, with each iterator representing an index of
a multidimensional array:
indices = [ i, j, k ]
where
i = xrange(1,3)
j = xrange(3,5)
k = xrange(5,7)
To generate all the possible values, I use the following naive recursive code:
def travtree(index,depth):
"Recursion through index list"
if depth >= len(indices):
# Stopping Condition
print index
else:
# Recursion
currindexrange = indices[depth]
for currindex in xrange(len(currindexrange)):
newindex = list(index) # list copy
newindex.append(currindexrange[currindex])
travtree(newindex,depth+1)
travtree([],0)
This works fine, but I was wondering, is there a more efficient, Pythonic way
to do this? I tried looking in the `itertools` module but nothing jumps out at
me.
Answer:
>>> from itertools import product
>>> i = xrange(1,3)
>>> j = xrange(3,5)
>>> k = xrange(5,7)
>>> indices = [ i, j, k ]
>>> for item in product(*indices):
print item
(1, 3, 5)
(1, 3, 6)
(1, 4, 5)
(1, 4, 6)
(2, 3, 5)
(2, 3, 6)
(2, 4, 5)
(2, 4, 6)
|
Threading serializable operations in python is slower than running them sequentially
Question: I am attempting to have two long running operations run simultaneously in
python. They both operate on the same data set, but do not modify it. I have
found that a threaded implementation runs slower than simply running them one
after the other.
I have created a simplified example to show what I am experiencing.
Running this code, and commenting line 46 (causing it to perform the operation
threaded), results in a runtime on my machine of around 1:01 (minute:seconds).
I see two CPUs run at around 50% for the full run time.
Commenting out line 47 (causing sequential calculations) results in a runtime
of around 35 seconds, with 1 CPU being pegged at 100% for the full runtime.
Both runs result in the both full calculations being completed.
from datetime import datetime
import threading
class num:
def __init__(self):
self._num = 0
def increment(self):
self._num += 1
def getValue(self):
return self._num
class incrementNumber(threading.Thread):
def __init__(self, number):
self._number = number
threading.Thread.__init__(self)
def run(self):
self.incrementProcess()
def incrementProcess(self):
for i in range(50000000):
self._number.increment()
def runThreaded(x, y):
x.start()
y.start()
x.join()
y.join()
def runNonThreaded(x, y):
x.incrementProcess()
y.incrementProcess()
def main():
t = datetime.now()
x = num()
y = num()
incrementX = incrementNumber(x)
incrementY = incrementNumber(y)
runThreaded(incrementX, incrementY)
#runNonThreaded(incrementX, incrementY)
print x.getValue(), y.getValue()
print datetime.now() - t
if __name__=="__main__":
main()
Answer: CPython has a so-called [Global Interpreter
Lock](http://www.dabeaz.com/python/UnderstandingGIL.pdf), which means that
only one Python statement can run at a time even when multithreading. You
might want to look into
[multiprocessing](http://docs.python.org/library/multiprocessing.html), which
avoids this constraint.
The GIL means that Python multithreading is only useful for I/O-bound
operations, other things that wait for stuff to happen, or if you're calling a
C extension that releases the GIL while doing work.
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.