code stringlengths 1 1.49M | vector listlengths 0 7.38k | snippet listlengths 0 7.38k |
|---|---|---|
#!/usr/bin/env python
# encoding: utf-8
import sys
import os
import time
from pyfann import libfann
def main():
connection_rate = 1
learning_rate = 0.7
num_output = 1
max_iterations = 5000
iterations_between_reports = 100
parameters = [{"title": "Abalone", "train_file": "abalone_train.data", "test_file": "abalone_test.data", "inputs": 8, "hidden": [8, 16, 32, 64], "desired_error": .01},
{"title": "Chess", "train_file": "chess_train.data", "test_file": "chess_test.data", "inputs": 6, "hidden": [6, 12, 24, 48], "desired_error": .01},
{"title": "Wine", "train_file": "wine_train.data", "test_file": "wine_test.data", "inputs": 11, "hidden": [11, 22, 44, 88], "desired_error": .001}]
for p in parameters:
print "================= %s =================" % p["title"]
for h in p["hidden"]:
print "Hidden neurons: %s" % h
print "\nTraining..."
# initialize network
ann = libfann.neural_net()
ann.create_sparse_array(connection_rate, (p["inputs"], h, num_output))
ann.set_learning_rate(learning_rate)
# activation functions
ann.set_activation_function_hidden(libfann.SIGMOID)
ann.set_activation_function_output(libfann.SIGMOID)
# read training data
trainData = libfann.training_data()
trainData.read_train_from_file("../processed_data/%s" % p["train_file"])
# scale data
trainData.scale_train_data(0, 1)
start = time.time()
# train network
ann.train_on_data(trainData, max_iterations, iterations_between_reports, p["desired_error"])
end = time.time()
trainTime = (end - start) * 1000
print "\nTesting...",
# test
testData = libfann.training_data()
testData.read_train_from_file("../processed_data/%s" % p["test_file"])
ann.reset_MSE()
start = time.time()
testMSE = ann.test_data(testData)
testBitFail = ann.get_bit_fail()
end = time.time()
testTime = (end - start) * 1000
print " train time: %s, test time: %s, mse: %s, bit fail: %s\n" % (trainTime, testTime, testMSE, testBitFail)
if __name__ == '__main__':
main()
| [
[
1,
0,
0.0513,
0.0128,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0641,
0.0128,
0,
0.66,
0.2,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.0769,
0.0128,
0,
0.6... | [
"import sys",
"import os",
"import time",
"from pyfann import libfann",
"def main():\n\tconnection_rate \t\t\t\t= 1\n\tlearning_rate \t\t\t\t\t= 0.7\n\t\n\tnum_output \t\t\t\t\t\t= 1\n\t\n\tmax_iterations \t\t\t\t\t= 5000\n\titerations_between_reports \t\t= 100",
"\tconnection_rate \t\t\t\t= 1",
"\tlear... |
#!/usr/bin/env python
# encoding: utf-8
import sys
import os
import time
from pyfann import libfann
def main():
learning_rate = 0.7
num_output = 1
max_iterations = 5000
iterations_between_reports = 100
parameters = [{"title": "Abalone",
"train_file": "abalone_train.data",
"test_file": "abalone_test.data",
"inputs": 8,
"hidden": [32, 32, 32, 32],
"desired_error": .01,
"connection_rate": 0.92 },
{"title": "Chess",
"train_file": "chess_train.data",
"test_file": "chess_test.data",
"inputs": 6,
"hidden": [48, 48, 48, 48],
"desired_error": .01,
"connection_rate": 0.92 },
{"title": "Wine",
"train_file": "wine_train.data",
"test_file": "wine_test.data",
"inputs": 11,
"hidden": [11, 11, 11, 11],
"desired_error": .01,
"connection_rate": 0.92 }]
for p in parameters:
print "================= %s =================" % p["title"]
for h in p["hidden"]:
print "Hidden neurons: %s" % h
print "\nTraining..."
# initialize network
ann = libfann.neural_net()
ann.create_sparse_array(p["connection_rate"], (p["inputs"], h, num_output))
ann.set_learning_rate(learning_rate)
# activation functions
ann.set_activation_function_hidden(libfann.SIGMOID)
ann.set_activation_function_output(libfann.SIGMOID)
# read training data
trainData = libfann.training_data()
trainData.read_train_from_file("../processed_data/%s" % p["train_file"])
# scale data
trainData.scale_train_data(0, 1)
start = time.time()
# train network
ann.train_on_data(trainData, max_iterations, iterations_between_reports, p["desired_error"])
end = time.time()
trainTime = (end - start) * 1000
print "\nTesting...",
# test
testData = libfann.training_data()
testData.read_train_from_file("../processed_data/%s" % p["test_file"])
ann.reset_MSE()
start = time.time()
testMSE = ann.test_data(testData)
testBitFail = ann.get_bit_fail()
end = time.time()
testTime = (end - start) * 1000
print " train time: %s, test time: %s, mse: %s, bit fail: %s\n" % (trainTime, testTime, testMSE, testBitFail)
if __name__ == '__main__':
main()
| [
[
1,
0,
0.0421,
0.0105,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0526,
0.0105,
0,
0.66,
0.2,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.0632,
0.0105,
0,
0.6... | [
"import sys",
"import os",
"import time",
"from pyfann import libfann",
"def main():\n\tlearning_rate \t\t\t\t\t= 0.7\n\t\n\tnum_output \t\t\t\t\t\t= 1\n\t\n\tmax_iterations \t\t\t\t\t= 5000\n\titerations_between_reports \t\t= 100",
"\tlearning_rate \t\t\t\t\t= 0.7",
"\tnum_output \t\t\t\t\t\t= 1",
"\... |
#!/usr/bin/env python
# encoding: utf-8
import sys
import os
import time
from pyfann import libfann
def main():
learning_rate = 0.7
num_output = 1
max_iterations = 5000
iterations_between_reports = 100
parameters = [{"title": "Abalone",
"train_file": "abalone_train.data",
"test_file": "abalone_test.data",
"inputs": 8,
"hidden": [32, 32, 32, 32],
"desired_error": .01,
"connection_rate": 0.92 },
{"title": "Chess",
"train_file": "chess_train.data",
"test_file": "chess_test.data",
"inputs": 6,
"hidden": [48, 48, 48, 48],
"desired_error": .01,
"connection_rate": 0.92 },
{"title": "Wine",
"train_file": "wine_train.data",
"test_file": "wine_test.data",
"inputs": 11,
"hidden": [11, 11, 11, 11],
"desired_error": .01,
"connection_rate": 0.92 }]
for p in parameters:
print "================= %s =================" % p["title"]
for h in p["hidden"]:
print "Hidden neurons: %s" % h
print "\nTraining..."
# initialize network
ann = libfann.neural_net()
ann.create_sparse_array(p["connection_rate"], (p["inputs"], h, num_output))
ann.set_learning_rate(learning_rate)
# activation functions
ann.set_activation_function_hidden(libfann.SIGMOID)
ann.set_activation_function_output(libfann.SIGMOID)
# read training data
trainData = libfann.training_data()
trainData.read_train_from_file("../processed_data/%s" % p["train_file"])
# scale data
trainData.scale_train_data(0, 1)
start = time.time()
# train network
ann.train_on_data(trainData, max_iterations, iterations_between_reports, p["desired_error"])
end = time.time()
trainTime = (end - start) * 1000
print "\nTesting...",
# test
testData = libfann.training_data()
testData.read_train_from_file("../processed_data/%s" % p["test_file"])
ann.reset_MSE()
start = time.time()
testMSE = ann.test_data(testData)
testBitFail = ann.get_bit_fail()
end = time.time()
testTime = (end - start) * 1000
print " train time: %s, test time: %s, mse: %s, bit fail: %s\n" % (trainTime, testTime, testMSE, testBitFail)
if __name__ == '__main__':
main()
| [
[
1,
0,
0.0421,
0.0105,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0526,
0.0105,
0,
0.66,
0.2,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.0632,
0.0105,
0,
0.6... | [
"import sys",
"import os",
"import time",
"from pyfann import libfann",
"def main():\n\tlearning_rate \t\t\t\t\t= 0.7\n\t\n\tnum_output \t\t\t\t\t\t= 1\n\t\n\tmax_iterations \t\t\t\t\t= 5000\n\titerations_between_reports \t\t= 100",
"\tlearning_rate \t\t\t\t\t= 0.7",
"\tnum_output \t\t\t\t\t\t= 1",
"\... |
#!/usr/bin/env python
# encoding: utf-8
import sys
import os
import time
from pyfann import libfann
def main():
connection_rate = 1
learning_rate = 0.7
num_output = 1
max_iterations = 5000
iterations_between_reports = 100
parameters = [{"title": "Abalone", "train_file": "abalone_train.data", "test_file": "abalone_test.data", "inputs": 8, "hidden": [8, 16, 32, 64], "desired_error": .01},
{"title": "Chess", "train_file": "chess_train.data", "test_file": "chess_test.data", "inputs": 6, "hidden": [6, 12, 24, 48], "desired_error": .01},
{"title": "Wine", "train_file": "wine_train.data", "test_file": "wine_test.data", "inputs": 11, "hidden": [11, 22, 44, 88], "desired_error": .001}]
for p in parameters:
print "================= %s =================" % p["title"]
for h in p["hidden"]:
print "Hidden neurons: %s" % h
print "\nTraining..."
# initialize network
ann = libfann.neural_net()
ann.create_sparse_array(connection_rate, (p["inputs"], h, num_output))
ann.set_learning_rate(learning_rate)
# activation functions
ann.set_activation_function_hidden(libfann.SIGMOID)
ann.set_activation_function_output(libfann.SIGMOID)
# read training data
trainData = libfann.training_data()
trainData.read_train_from_file("../processed_data/%s" % p["train_file"])
# scale data
trainData.scale_train_data(0, 1)
start = time.time()
# train network
ann.train_on_data(trainData, max_iterations, iterations_between_reports, p["desired_error"])
end = time.time()
trainTime = (end - start) * 1000
print "\nTesting...",
# test
testData = libfann.training_data()
testData.read_train_from_file("../processed_data/%s" % p["test_file"])
ann.reset_MSE()
start = time.time()
testMSE = ann.test_data(testData)
testBitFail = ann.get_bit_fail()
end = time.time()
testTime = (end - start) * 1000
print " train time: %s, test time: %s, mse: %s, bit fail: %s\n" % (trainTime, testTime, testMSE, testBitFail)
if __name__ == '__main__':
main()
| [
[
1,
0,
0.0513,
0.0128,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0641,
0.0128,
0,
0.66,
0.2,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.0769,
0.0128,
0,
0.6... | [
"import sys",
"import os",
"import time",
"from pyfann import libfann",
"def main():\n\tconnection_rate \t\t\t\t= 1\n\tlearning_rate \t\t\t\t\t= 0.7\n\t\n\tnum_output \t\t\t\t\t\t= 1\n\t\n\tmax_iterations \t\t\t\t\t= 5000\n\titerations_between_reports \t\t= 100",
"\tconnection_rate \t\t\t\t= 1",
"\tlear... |
#!/usr/bin/python
import sys, hashlib
def write_file(fn, buf):
fp = open(fn, "wb")
fp.write(buf)
fp.close()
def usage():
print ("Usage: " + sys.argv[0] + " infile outfile label")
def main():
if( len(sys.argv) != 4):
usage()
sys.exit()
fp = open( sys.argv[1] , "rb")
hash_str = hashlib.md5( fp.read() ).hexdigest()
fp.close()
out_str = "u8 " + sys.argv[3] + "[16] = { "
i=0
for str in hash_str:
if i % 2 == 0:
out_str += "0x" + str
else:
out_str += str
if i < 31:
out_str += ", "
i += 1
out_str += " };"
print out_str
write_file( sys.argv[2] , out_str )
if __name__ == "__main__":
main()
| [
[
1,
0,
0.0714,
0.0238,
0,
0.66,
0,
509,
0,
2,
0,
0,
509,
0,
0
],
[
2,
0,
0.1548,
0.0952,
0,
0.66,
0.25,
725,
0,
2,
0,
0,
0,
0,
3
],
[
14,
1,
0.1429,
0.0238,
1,
0.9... | [
"import sys, hashlib",
"def write_file(fn, buf):\n\tfp = open(fn, \"wb\")\n\tfp.write(buf)\n\tfp.close()",
"\tfp = open(fn, \"wb\")",
"\tfp.write(buf)",
"\tfp.close()",
"def usage():\n\tprint (\"Usage: \" + sys.argv[0] + \" infile outfile label\")",
"\tprint (\"Usage: \" + sys.argv[0] + \" infile outfi... |
#!/usr/bin/python
import sys, re, os
def write_file(fn, buf):
fp = open(fn, "wb")
fp.write(buf)
fp.close()
def usage():
print ("Usage: " + os.path.split(__file__)[1] + " version outfile")
def crete_version_str(ver):
base = list("0.00")
version = str(ver)
ret = []
base[0] = version[0]
base[2] = version[1]
base[3] = version[2]
ret.append("".join(base))
version = str(int(ver) + 1)
base[0] = version[0]
base[2] = version[1]
base[3] = version[2]
ret.append("".join(base))
return ret
def main():
if( len(sys.argv) != 3):
usage()
sys.exit()
if len( sys.argv[1]) != 3:
print sys.argv[1] + ":Version error."
sys.exit()
fp = open( os.path.dirname(os.path.abspath(__file__)) + "/update_base.sfo" , "rb")
sfo_buf = fp.read()
fp.close()
after_str = crete_version_str(sys.argv[1])
print "Target version:" + after_str[0]
sfo_buf = re.sub("X.YZ", after_str[0], sfo_buf )
sfo_buf = re.sub("Z.YX", after_str[1], sfo_buf )
write_file( sys.argv[2] , sfo_buf )
if __name__ == "__main__":
main()
| [
[
1,
0,
0.0577,
0.0192,
0,
0.66,
0,
509,
0,
3,
0,
0,
509,
0,
0
],
[
2,
0,
0.125,
0.0769,
0,
0.66,
0.2,
725,
0,
2,
0,
0,
0,
0,
3
],
[
14,
1,
0.1154,
0.0192,
1,
0.35,... | [
"import sys, re, os",
"def write_file(fn, buf):\n\tfp = open(fn, \"wb\")\n\tfp.write(buf)\n\tfp.close()",
"\tfp = open(fn, \"wb\")",
"\tfp.write(buf)",
"\tfp.close()",
"def usage():\n\tprint (\"Usage: \" + os.path.split(__file__)[1] + \" version outfile\")",
"\tprint (\"Usage: \" + os.path.split(__file... |
#!/usr/bin/python
class FakeTime:
def time(self):
return 1225856967.109
import sys, os, struct, gzip, hashlib, StringIO
gzip.time = FakeTime()
def binary_replace(data, newdata, offset):
return data[0:offset] + newdata + data[offset+len(newdata):]
def prx_compress(output, hdr, input, mod_name="", mod_attr=0xFFFFFFFF):
a=open(hdr, "rb")
fileheader = a.read();
a.close()
a=open(input, "rb")
elf = a.read(4);
a.close()
if (elf != '\x7fELF'.encode()):
print ("not a ELF/PRX file!")
return -1
uncompsize = os.stat(input).st_size
f_in=open(input, 'rb')
temp=StringIO.StringIO()
f=gzip.GzipFile(fileobj=temp, mode='wb')
f.writelines(f_in)
f.close()
f_in.close()
prx=temp.getvalue()
temp.close()
digest=hashlib.md5(prx).digest()
filesize = len(fileheader) + len(prx)
if mod_name != "":
if len(mod_name) < 28:
mod_name += "\x00" * (28-len(mod_name))
else:
mod_name = mod_name[0:28]
fileheader = binary_replace(fileheader, mod_name.encode(), 0xA)
if mod_attr != 0xFFFFFFFF:
fileheader = binary_replace(fileheader, struct.pack('H', mod_attr), 0x4)
fileheader = binary_replace(fileheader, struct.pack('L', uncompsize), 0x28)
fileheader = binary_replace(fileheader, struct.pack('L', filesize), 0x2c)
fileheader = binary_replace(fileheader, struct.pack('L', len(prx)), 0xb0)
fileheader = binary_replace(fileheader, digest, 0x140)
a=open(output, "wb")
assert(len(fileheader) == 0x150)
a.write(fileheader)
a.write(prx)
a.close()
try:
os.remove("tmp.gz")
except OSError:
pass
return 0
def main():
if len(sys.argv) < 4:
print ("Usage: %s outfile prxhdr infile [modname] [modattr]\n"%(sys.argv[0]))
exit(-1)
if len(sys.argv) < 5:
prx_compress(sys.argv[1], sys.argv[2], sys.argv[3])
elif len(sys.argv) < 6:
prx_compress(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
else:
prx_compress(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], int(sys.argv[5], 16))
if __name__ == "__main__":
main()
| [
[
3,
0,
0.0488,
0.0366,
0,
0.66,
0,
425,
0,
1,
0,
0,
0,
0,
0
],
[
2,
1,
0.0549,
0.0244,
1,
0.81,
0,
654,
0,
1,
1,
0,
0,
0,
0
],
[
13,
2,
0.061,
0.0122,
2,
0.82,
... | [
"class FakeTime:\n def time(self):\n return 1225856967.109",
" def time(self):\n return 1225856967.109",
" return 1225856967.109",
"import sys, os, struct, gzip, hashlib, StringIO",
"gzip.time = FakeTime()",
"def binary_replace(data, newdata, offset):\n\treturn data[0:offset] + ... |
#!/usr/bin/python
import sys, hashlib
def toNID(name):
hashstr = hashlib.sha1(name.encode()).hexdigest().upper()
return "0x" + hashstr[6:8] + hashstr[4:6] + hashstr[2:4] + hashstr[0:2]
if __name__ == "__main__":
assert(toNID("sceKernelCpuSuspendIntr") == "0x092968F4")
for name in sys.argv[1:]:
print ("%s: %s"%(name, toNID(name)))
| [
[
1,
0,
0.2308,
0.0769,
0,
0.66,
0,
509,
0,
2,
0,
0,
509,
0,
0
],
[
2,
0,
0.4615,
0.2308,
0,
0.66,
0.5,
259,
0,
1,
1,
0,
0,
0,
4
],
[
14,
1,
0.4615,
0.0769,
1,
0.29... | [
"import sys, hashlib",
"def toNID(name):\n\thashstr = hashlib.sha1(name.encode()).hexdigest().upper()\n\treturn \"0x\" + hashstr[6:8] + hashstr[4:6] + hashstr[2:4] + hashstr[0:2]",
"\thashstr = hashlib.sha1(name.encode()).hexdigest().upper()",
"\treturn \"0x\" + hashstr[6:8] + hashstr[4:6] + hashstr[2:4] + ha... |
#!/usr/bin/python
from hashlib import *
import sys, struct
def sha512(psid):
if len(psid) != 16:
return "".encode()
for i in range(512):
psid = sha1(psid).digest()
return psid
def get_psid(str):
if len(str) != 32:
return "".encode()
b = "".encode()
for i in range(0, len(str), 2):
b += struct.pack('B', int(str[i] + str[i+1], 16))
return b
def main():
if len(sys.argv) < 2:
print ("Usage: sha512.py psid")
exit(0)
psid = get_psid(sys.argv[1])
xhash = sha512(psid)
if len(xhash) == 0:
print ("wrong PSID")
exit(0)
print ("{\n\t"),
for i in range(len(xhash)):
if i != 0 and i % 8 == 0:
print ("\n\t"),
print ("0x%02X, "%(struct.unpack('B', xhash[i])[0])),
print ("\n},")
if __name__ == "__main__":
main()
| [
[
1,
0,
0.0652,
0.0217,
0,
0.66,
0,
154,
0,
1,
0,
0,
154,
0,
0
],
[
1,
0,
0.087,
0.0217,
0,
0.66,
0.2,
509,
0,
2,
0,
0,
509,
0,
0
],
[
2,
0,
0.2065,
0.1739,
0,
0.66... | [
"from hashlib import *",
"import sys, struct",
"def sha512(psid):\n\tif len(psid) != 16:\n\t\treturn \"\".encode()\n\n\tfor i in range(512):\n\t\tpsid = sha1(psid).digest()\n\n\treturn psid",
"\tif len(psid) != 16:\n\t\treturn \"\".encode()",
"\t\treturn \"\".encode()",
"\tfor i in range(512):\n\t\tpsid =... |
#!/usr/bin/python
"""
pspbtcnf_editor: An script that add modules from pspbtcnf
"""
import sys, os, re
from getopt import *
from struct import *
BTCNF_MAGIC=0x0F803001
verbose = False
def print_usage():
print ("%s: pspbtcnf.bin [-o output.bin] [-a add_module_name:before_module_name:flag]" %(os.path.split(sys.argv[0]))[-1])
def replace_binary(data, offset, newdata):
newdata = data[0:offset] + newdata + data[offset+len(newdata):]
assert(len(data) == len(newdata))
return newdata
def dump_binary(data, offset, size):
newdata = data[offset:offset+size]
assert(len(newdata) == size)
return newdata
def dump_binary_str(data, offset):
ch = data[offset]
tmp = b''
while ch != 0:
tmp += pack('b', ch)
offset += 1
ch = data[offset]
return tmp.decode()
def add_prx_to_bootconf(srcfn, before_modname, modname, modflag):
"Return new bootconf data"
fn=open(srcfn, "rb")
bootconf = fn.read()
fn.close()
if len(bootconf) < 64:
raise Exception("Bad bootconf")
signature, devkit, modestart, nmodes, modulestart, nmodules, modnamestart, modnameend = unpack('LL8xLL8xLL8xLL8x', bootconf[:64])
if verbose:
print ("Devkit: 0x%08X"%(devkit))
print ("modestart: 0x%08X"%(modestart))
print ("nmodes: %d"%(nmodes))
print ("modulestart: 0x%08X"%(modulestart))
print ("nmodules: 0x%08X"%(nmodules))
print ("modnamestart: 0x%08X"%(modnamestart))
print ("modnameend: 0x%08X"%(modnameend))
if signature != BTCNF_MAGIC or nmodules <= 0 or nmodes <= 0:
raise Exception("Bad bootconf")
bootconf = bootconf + modname.encode() + b'\0'
modnameend += len(modname) + 1
i=0
while i < nmodules:
module_path, module_flags = unpack('L4xL4x16x', bootconf[modulestart+i*32:modulestart+(i+1)*32])
module_name = dump_binary_str(bootconf, modnamestart+module_path)
if verbose:
print ("[%02d]: Module path: %s flag: 0x%08X"%(i, module_name, module_flags))
if before_modname == module_name:
break
i+=1
if i >= nmodules:
raise Exception("module %s not found"%(before_modname))
module_path = modnameend - len(modname) - 1 - modnamestart
module_flag = 0x80010000 | (modflag & 0xFFFF)
newmod = dump_binary(bootconf, modulestart+i*32, 32)
newmod = replace_binary(newmod, 0, pack('L', module_path))
newmod = replace_binary(newmod, 8, pack('L', module_flag))
bootconf = bootconf[0:modulestart+i*32] + newmod + bootconf[modulestart+i*32:]
nmodules+=1
bootconf = replace_binary(bootconf, 0x24, pack('L', nmodules))
modnamestart += 32
bootconf = replace_binary(bootconf, 0x30, pack('L', modnamestart))
modnameend += 32
bootconf = replace_binary(bootconf, 0x34, pack('L', modnameend))
i = 0
while i < nmodes:
num = unpack('H', bootconf[modestart+i*32:modestart+i*32+2])[0]
num += 1
bootconf = replace_binary(bootconf, modestart + i * 32, pack('H', num))
i += 1
return bootconf
def write_file(output_fn, data):
fn = open(output_fn, "wb")
fn.write(data)
fn.close()
def main():
global verbose
try:
optlist, args = gnu_getopt(sys.argv, "a:o:vh")
except GetoptError as err:
print(err)
print_usage()
sys.exit(1)
# default configure
verbose = False
dst_filename = "-"
add_module = ""
for o, a in optlist:
if o == "-v":
verbose = True
elif o == "-h":
print_usage()
sys.exit()
elif o == "-o":
dst_filename = a
elif o == "-a":
add_module = a
else:
assert False, "unhandled option"
if verbose:
print (optlist, args)
if len(args) < 2:
print ("Missing input pspbtcnf.bin")
sys.exit(1)
src_filename = args[1]
if verbose:
print ("src_filename: " + src_filename)
print ("dst_filename: " + dst_filename)
# check add_module
if add_module != "":
t = (re.split(":", add_module, re.I))
if len(t) != 3:
print ("Bad add_module input")
sys.exit(1)
add_module, before_module, add_module_flag = (re.split(":", add_module, re.I))
if verbose:
print ("add_module: " + add_module)
print ("before_module: " + before_module)
print ("add_module_flag: " + add_module_flag)
if add_module != "":
result = add_prx_to_bootconf(src_filename, before_module, add_module, int(add_module_flag, 16))
if dst_filename == "-":
# print("Bootconf result:")
# print(result)
pass
else:
write_file(dst_filename, result)
if __name__ == "__main__":
main()
| [
[
8,
0,
0.022,
0.0165,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0385,
0.0055,
0,
0.66,
0.0769,
509,
0,
3,
0,
0,
509,
0,
0
],
[
1,
0,
0.044,
0.0055,
0,
0.66,
... | [
"\"\"\"\npspbtcnf_editor: An script that add modules from pspbtcnf\n\"\"\"",
"import sys, os, re",
"from getopt import *",
"from struct import *",
"BTCNF_MAGIC=0x0F803001",
"verbose = False",
"def print_usage():\n\tprint (\"%s: pspbtcnf.bin [-o output.bin] [-a add_module_name:before_module_name:flag]\" ... |
#!/usr/bin/python
import os
def main():
lists = [
"ISODrivers/Galaxy/galaxy.prx",
"ISODrivers/March33/march33.prx",
"ISODrivers/March33/march33_620.prx",
"ISODrivers/Inferno/inferno.prx",
"Popcorn/popcorn.prx",
"Satelite/satelite.prx",
"Stargate/stargate.prx",
"SystemControl/systemctrl.prx",
"usbdevice/usbdevice.prx",
"Vshctrl/vshctrl.prx",
"Recovery/recovery.prx",
]
for fn in lists:
path = "../" + fn
name=os.path.split(fn)[-1]
name=os.path.splitext(name)[0]
ret = os.system("bin2c %s %s.h %s"%(path, name, name))
assert(ret == 0)
if __name__ == "__main__":
main()
| [
[
1,
0,
0.1071,
0.0357,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
2,
0,
0.5357,
0.75,
0,
0.66,
0.5,
624,
0,
0,
0,
0,
0,
0,
3
],
[
14,
1,
0.4286,
0.4643,
1,
0.93,
... | [
"import os",
"def main():\n\tlists = [\n\t\t\t\"ISODrivers/Galaxy/galaxy.prx\",\n\t\t\t\"ISODrivers/March33/march33.prx\",\n\t\t\t\"ISODrivers/March33/march33_620.prx\",\n\t\t\t\"ISODrivers/Inferno/inferno.prx\",\n\t\t\t\"Popcorn/popcorn.prx\",\n\t\t\t\"Satelite/satelite.prx\",",
"\tlists = [\n\t\t\t\"ISODriver... |
#!/usr/bin/python
class FakeTime:
def time(self):
return 1225856967.109
import os, gzip, StringIO
gzip.time = FakeTime()
def create_gzip(input, output):
f_in=open(input, 'rb')
temp=StringIO.StringIO()
f=gzip.GzipFile(fileobj=temp, mode='wb')
f.writelines(f_in)
f.close()
f_in.close()
fout=open(output, 'wb')
temp.seek(0)
fout.writelines(temp)
fout.close()
temp.close()
def cleanup():
del_list = [
"installer.prx.gz",
"Rebootex.prx.gz",
]
for file in del_list:
try:
os.remove(file)
except OSError:
pass
def main():
create_gzip("../../Installer/installer.prx", "installer.prx.gz")
create_gzip("../../Rebootex/Rebootex.prx", "Rebootex.prx.gz")
os.system("bin2c installer.prx.gz installer.h installer")
os.system("bin2c Rebootex.prx.gz Rebootex_prx.h Rebootex_prx")
cleanup()
if __name__ == "__main__":
main()
| [
[
3,
0,
0.0909,
0.0682,
0,
0.66,
0,
425,
0,
1,
0,
0,
0,
0,
0
],
[
2,
1,
0.1023,
0.0455,
1,
0,
0,
654,
0,
1,
1,
0,
0,
0,
0
],
[
13,
2,
0.1136,
0.0227,
2,
0.77,
0... | [
"class FakeTime:\n def time(self):\n return 1225856967.109",
" def time(self):\n return 1225856967.109",
" return 1225856967.109",
"import os, gzip, StringIO",
"gzip.time = FakeTime()",
"def create_gzip(input, output):\n\tf_in=open(input, 'rb')\n\ttemp=StringIO.StringIO()\n\tf=g... |
#!/usr/bin/python
import os, sys, getopt
def usage():
print ("Usage: %s [-l size ] basefile input output" % (sys.argv[0]))
def write_file(fn, buf):
fp = open(fn, "wb")
fp.write(buf)
fp.close()
def main():
inputsize = 0
try:
optlist, args = getopt.getopt(sys.argv[1:], 'l:h')
except getopt.GetoptError:
usage()
sys.exit(2)
for o, a in optlist:
if o == "-h":
usage()
sys.exit()
if o == "-l":
inputsize = int(a, 16)
inputsize = max(inputsize, 0x4000);
if len(args) < 3:
usage()
sys.exit(2)
basefile = args[0]
inputfile = args[1]
outputfile = args[2]
fp = open(basefile, "rb")
buf = fp.read(0x1000)
fp.close()
if len(buf) < inputsize:
buf += b'\0' * (inputsize - len(buf))
assert(len(buf) == inputsize)
fp = open(inputfile, "rb")
ins = fp.read(0x3000)
fp.close()
buf = buf[0:0x1000] + ins + buf[0x1000+len(ins):]
assert(len(buf) == inputsize)
write_file(outputfile, buf)
if __name__ == "__main__":
main()
| [
[
1,
0,
0.0536,
0.0179,
0,
0.66,
0,
688,
0,
3,
0,
0,
688,
0,
0
],
[
2,
0,
0.0982,
0.0357,
0,
0.66,
0.25,
129,
0,
0,
0,
0,
0,
0,
1
],
[
8,
1,
0.1071,
0.0179,
1,
0.53... | [
"import os, sys, getopt",
"def usage():\n\tprint (\"Usage: %s [-l size ] basefile input output\" % (sys.argv[0]))",
"\tprint (\"Usage: %s [-l size ] basefile input output\" % (sys.argv[0]))",
"def write_file(fn, buf):\n\tfp = open(fn, \"wb\")\n\tfp.write(buf)\n\tfp.close()",
"\tfp = open(fn, \"wb\")",
"\t... |
#!/usr/bin/env python
from distutils.core import setup
import os
def get_build():
path = "./.build"
if os.path.exists(path):
fp = open(path, "r")
build = eval(fp.read())
if os.path.exists("./.increase_build"):
build += 1
fp.close()
else:
build = 1
fp = open(path, "w")
fp.write(str(build))
fp.close()
return str(build)
setup(name = "pylast",
version = "0.5." + get_build(),
author = "Amr Hassan <amr.hassan@gmail.com>",
description = "A Python interface to Last.fm (and other API compatible social networks)",
author_email = "amr.hassan@gmail.com",
url = "http://code.google.com/p/pylast/",
py_modules = ("pylast",),
license = "Apache2"
)
| [
[
1,
0,
0.0938,
0.0312,
0,
0.66,
0,
152,
0,
1,
0,
0,
152,
0,
0
],
[
1,
0,
0.1562,
0.0312,
0,
0.66,
0.3333,
688,
0,
1,
0,
0,
688,
0,
0
],
[
2,
0,
0.4375,
0.5312,
0,
... | [
"from distutils.core import setup",
"import os",
"def get_build():\n\tpath = \"./.build\"\n\t\n\tif os.path.exists(path):\n\t\tfp = open(path, \"r\")\n\t\tbuild = eval(fp.read())\n\t\tif os.path.exists(\"./.increase_build\"):\n\t\t\tbuild += 1",
"\tpath = \"./.build\"",
"\tif os.path.exists(path):\n\t\tfp =... |
# -*- coding: utf-8 -*-
#
# pylast - A Python interface to Last.fm (and other API compatible social networks)
#
# Copyright 2008-2010 Amr Hassan
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# http://code.google.com/p/pylast/
__version__ = '0.5'
__author__ = 'Amr Hassan'
__copyright__ = "Copyright (C) 2008-2010 Amr Hassan"
__license__ = "apache2"
__email__ = 'amr.hassan@gmail.com'
import hashlib
from xml.dom import minidom
import xml.dom
import time
import shelve
import tempfile
import sys
import collections
import warnings
def _deprecation_warning(message):
warnings.warn(message, DeprecationWarning)
if sys.version_info[0] == 3:
from http.client import HTTPConnection
import html.entities as htmlentitydefs
from urllib.parse import splithost as url_split_host
from urllib.parse import quote_plus as url_quote_plus
unichr = chr
elif sys.version_info[0] == 2:
from httplib import HTTPConnection
import htmlentitydefs
from urllib import splithost as url_split_host
from urllib import quote_plus as url_quote_plus
STATUS_INVALID_SERVICE = 2
STATUS_INVALID_METHOD = 3
STATUS_AUTH_FAILED = 4
STATUS_INVALID_FORMAT = 5
STATUS_INVALID_PARAMS = 6
STATUS_INVALID_RESOURCE = 7
STATUS_TOKEN_ERROR = 8
STATUS_INVALID_SK = 9
STATUS_INVALID_API_KEY = 10
STATUS_OFFLINE = 11
STATUS_SUBSCRIBERS_ONLY = 12
STATUS_INVALID_SIGNATURE = 13
STATUS_TOKEN_UNAUTHORIZED = 14
STATUS_TOKEN_EXPIRED = 15
EVENT_ATTENDING = '0'
EVENT_MAYBE_ATTENDING = '1'
EVENT_NOT_ATTENDING = '2'
PERIOD_OVERALL = 'overall'
PERIOD_7DAYS = "7day"
PERIOD_3MONTHS = '3month'
PERIOD_6MONTHS = '6month'
PERIOD_12MONTHS = '12month'
DOMAIN_ENGLISH = 0
DOMAIN_GERMAN = 1
DOMAIN_SPANISH = 2
DOMAIN_FRENCH = 3
DOMAIN_ITALIAN = 4
DOMAIN_POLISH = 5
DOMAIN_PORTUGUESE = 6
DOMAIN_SWEDISH = 7
DOMAIN_TURKISH = 8
DOMAIN_RUSSIAN = 9
DOMAIN_JAPANESE = 10
DOMAIN_CHINESE = 11
COVER_SMALL = 0
COVER_MEDIUM = 1
COVER_LARGE = 2
COVER_EXTRA_LARGE = 3
COVER_MEGA = 4
IMAGES_ORDER_POPULARITY = "popularity"
IMAGES_ORDER_DATE = "dateadded"
USER_MALE = 'Male'
USER_FEMALE = 'Female'
SCROBBLE_SOURCE_USER = "P"
SCROBBLE_SOURCE_NON_PERSONALIZED_BROADCAST = "R"
SCROBBLE_SOURCE_PERSONALIZED_BROADCAST = "E"
SCROBBLE_SOURCE_LASTFM = "L"
SCROBBLE_SOURCE_UNKNOWN = "U"
SCROBBLE_MODE_PLAYED = ""
SCROBBLE_MODE_LOVED = "L"
SCROBBLE_MODE_BANNED = "B"
SCROBBLE_MODE_SKIPPED = "S"
class _Network(object):
"""
A music social network website that is Last.fm or one exposing a Last.fm compatible API
"""
def __init__(self, name, homepage, ws_server, api_key, api_secret, session_key, submission_server, username, password_hash,
domain_names, urls):
"""
name: the name of the network
homepage: the homepage url
ws_server: the url of the webservices server
api_key: a provided API_KEY
api_secret: a provided API_SECRET
session_key: a generated session_key or None
submission_server: the url of the server to which tracks are submitted (scrobbled)
username: a username of a valid user
password_hash: the output of pylast.md5(password) where password is the user's password
domain_names: a dict mapping each DOMAIN_* value to a string domain name
urls: a dict mapping types to urls
if username and password_hash were provided and not session_key, session_key will be
generated automatically when needed.
Either a valid session_key or a combination of username and password_hash must be present for scrobbling.
You should use a preconfigured network object through a get_*_network(...) method instead of creating an object
of this class, unless you know what you're doing.
"""
self.name = name
self.homepage = homepage
self.ws_server = ws_server
self.api_key = api_key
self.api_secret = api_secret
self.session_key = session_key
self.submission_server = submission_server
self.username = username
self.password_hash = password_hash
self.domain_names = domain_names
self.urls = urls
self.cache_backend = None
self.proxy_enabled = False
self.proxy = None
self.last_call_time = 0
#generate a session_key if necessary
if (self.api_key and self.api_secret) and not self.session_key and (self.username and self.password_hash):
sk_gen = SessionKeyGenerator(self)
self.session_key = sk_gen.get_session_key(self.username, self.password_hash)
"""def __repr__(self):
attributes = ("name", "homepage", "ws_server", "api_key", "api_secret", "session_key", "submission_server",
"username", "password_hash", "domain_names", "urls")
text = "pylast._Network(%s)"
args = []
for attr in attributes:
args.append("=".join((attr, repr(getattr(self, attr)))))
return text % ", ".join(args)
"""
def __str__(self):
return "The %s Network" %self.name
def get_artist(self, artist_name):
"""
Return an Artist object
"""
return Artist(artist_name, self)
def get_track(self, artist, title):
"""
Return a Track object
"""
return Track(artist, title, self)
def get_album(self, artist, title):
"""
Return an Album object
"""
return Album(artist, title, self)
def get_authenticated_user(self):
"""
Returns the authenticated user
"""
return AuthenticatedUser(self)
def get_country(self, country_name):
"""
Returns a country object
"""
return Country(country_name, self)
def get_group(self, name):
"""
Returns a Group object
"""
return Group(name, self)
def get_user(self, username):
"""
Returns a user object
"""
return User(username, self)
def get_tag(self, name):
"""
Returns a tag object
"""
return Tag(name, self)
def get_scrobbler(self, client_id, client_version):
"""
Returns a Scrobbler object used for submitting tracks to the server
Quote from http://www.last.fm/api/submissions:
========
Client identifiers are used to provide a centrally managed database of
the client versions, allowing clients to be banned if they are found to
be behaving undesirably. The client ID is associated with a version
number on the server, however these are only incremented if a client is
banned and do not have to reflect the version of the actual client application.
During development, clients which have not been allocated an identifier should
use the identifier tst, with a version number of 1.0. Do not distribute code or
client implementations which use this test identifier. Do not use the identifiers
used by other clients.
=========
To obtain a new client identifier please contact:
* Last.fm: submissions@last.fm
* # TODO: list others
...and provide us with the name of your client and its homepage address.
"""
_deprecation_warning("Use _Network.scrobble(...), _Network.scrobble_many(...), and Netowrk.update_now_playing(...) instead")
return Scrobbler(self, client_id, client_version)
def _get_language_domain(self, domain_language):
"""
Returns the mapped domain name of the network to a DOMAIN_* value
"""
if domain_language in self.domain_names:
return self.domain_names[domain_language]
def _get_url(self, domain, type):
return "http://%s/%s" %(self._get_language_domain(domain), self.urls[type])
def _get_ws_auth(self):
"""
Returns a (API_KEY, API_SECRET, SESSION_KEY) tuple.
"""
return (self.api_key, self.api_secret, self.session_key)
def _delay_call(self):
"""
Makes sure that web service calls are at least a second apart
"""
# delay time in seconds
DELAY_TIME = 1.0
now = time.time()
if (now - self.last_call_time) < DELAY_TIME:
time.sleep(1)
self.last_call_time = now
def create_new_playlist(self, title, description):
"""
Creates a playlist for the authenticated user and returns it
title: The title of the new playlist.
description: The description of the new playlist.
"""
params = {}
params['title'] = title
params['description'] = description
doc = _Request(self, 'playlist.create', params).execute(False)
e_id = doc.getElementsByTagName("id")[0].firstChild.data
user = doc.getElementsByTagName('playlists')[0].getAttribute('user')
return Playlist(user, e_id, self)
def get_top_tags(self, limit=None):
"""Returns a sequence of the most used tags as a sequence of TopItem objects."""
doc = _Request(self, "tag.getTopTags").execute(True)
seq = []
for node in doc.getElementsByTagName("tag"):
tag = Tag(_extract(node, "name"), self)
weight = _number(_extract(node, "count"))
seq.append(TopItem(tag, weight))
if limit:
seq = seq[:limit]
return seq
def enable_proxy(self, host, port):
"""Enable a default web proxy"""
self.proxy = [host, _number(port)]
self.proxy_enabled = True
def disable_proxy(self):
"""Disable using the web proxy"""
self.proxy_enabled = False
def is_proxy_enabled(self):
"""Returns True if a web proxy is enabled."""
return self.proxy_enabled
def _get_proxy(self):
"""Returns proxy details."""
return self.proxy
def enable_caching(self, file_path = None):
"""Enables caching request-wide for all cachable calls.
* file_path: A file path for the backend storage file. If
None set, a temp file would probably be created, according the backend.
"""
if not file_path:
file_path = tempfile.mktemp(prefix="pylast_tmp_")
self.cache_backend = _ShelfCacheBackend(file_path)
def disable_caching(self):
"""Disables all caching features."""
self.cache_backend = None
def is_caching_enabled(self):
"""Returns True if caching is enabled."""
return not (self.cache_backend == None)
def _get_cache_backend(self):
return self.cache_backend
def search_for_album(self, album_name):
"""Searches for an album by its name. Returns a AlbumSearch object.
Use get_next_page() to retreive sequences of results."""
return AlbumSearch(album_name, self)
def search_for_artist(self, artist_name):
"""Searches of an artist by its name. Returns a ArtistSearch object.
Use get_next_page() to retreive sequences of results."""
return ArtistSearch(artist_name, self)
def search_for_tag(self, tag_name):
"""Searches of a tag by its name. Returns a TagSearch object.
Use get_next_page() to retreive sequences of results."""
return TagSearch(tag_name, self)
def search_for_track(self, artist_name, track_name):
"""Searches of a track by its name and its artist. Set artist to an empty string if not available.
Returns a TrackSearch object.
Use get_next_page() to retreive sequences of results."""
return TrackSearch(artist_name, track_name, self)
def search_for_venue(self, venue_name, country_name):
"""Searches of a venue by its name and its country. Set country_name to an empty string if not available.
Returns a VenueSearch object.
Use get_next_page() to retreive sequences of results."""
return VenueSearch(venue_name, country_name, self)
def get_track_by_mbid(self, mbid):
"""Looks up a track by its MusicBrainz ID"""
params = {"mbid": mbid}
doc = _Request(self, "track.getInfo", params).execute(True)
return Track(_extract(doc, "name", 1), _extract(doc, "name"), self)
def get_artist_by_mbid(self, mbid):
"""Loooks up an artist by its MusicBrainz ID"""
params = {"mbid": mbid}
doc = _Request(self, "artist.getInfo", params).execute(True)
return Artist(_extract(doc, "name"), self)
def get_album_by_mbid(self, mbid):
"""Looks up an album by its MusicBrainz ID"""
params = {"mbid": mbid}
doc = _Request(self, "album.getInfo", params).execute(True)
return Album(_extract(doc, "artist"), _extract(doc, "name"), self)
def update_now_playing(self, artist, title, album = None, album_artist = None,
duration = None, track_number = None, mbid = None, context = None):
"""
Used to notify Last.fm that a user has started listening to a track.
Parameters:
artist (Required) : The artist name
title (Required) : The track title
album (Optional) : The album name.
album_artist (Optional) : The album artist - if this differs from the track artist.
duration (Optional) : The length of the track in seconds.
track_number (Optional) : The track number of the track on the album.
mbid (Optional) : The MusicBrainz Track ID.
context (Optional) : Sub-client version (not public, only enabled for certain API keys)
"""
params = {"track": title, "artist": artist}
if album: params["album"] = album
if album_artist: params["albumArtist"] = album_artist
if context: params["context"] = context
if track_number: params["trackNumber"] = track_number
if mbid: params["mbid"] = mbid
if duration: params["duration"] = duration
_Request(self, "track.updateNowPlaying", params).execute()
def scrobble(self, artist, title, timestamp, album = None, album_artist = None, track_number = None,
duration = None, stream_id = None, context = None, mbid = None):
"""Used to add a track-play to a user's profile.
Parameters:
artist (Required) : The artist name.
title (Required) : The track name.
timestamp (Required) : The time the track started playing, in UNIX timestamp format (integer number of seconds since 00:00:00, January 1st 1970 UTC). This must be in the UTC time zone.
album (Optional) : The album name.
album_artist (Optional) : The album artist - if this differs from the track artist.
context (Optional) : Sub-client version (not public, only enabled for certain API keys)
stream_id (Optional) : The stream id for this track received from the radio.getPlaylist service.
track_number (Optional) : The track number of the track on the album.
mbid (Optional) : The MusicBrainz Track ID.
duration (Optional) : The length of the track in seconds.
"""
return self.scrobble_many(({"artist": artist, "title": title, "timestamp": timestamp, "album": album, "album_artist": album_artist,
"track_number": track_number, "duration": duration, "stream_id": stream_id, "context": context, "mbid": mbid},))
def scrobble_many(self, tracks):
"""
Used to scrobble a batch of tracks at once. The parameter tracks is a sequence of dicts per
track containing the keyword arguments as if passed to the scrobble() method.
"""
tracks_to_scrobble = tracks[:50]
if len(tracks) > 50:
remaining_tracks = tracks[50:]
else:
remaining_tracks = None
params = {}
for i in range(len(tracks_to_scrobble)):
params["artist[%d]" % i] = tracks_to_scrobble[i]["artist"]
params["track[%d]" % i] = tracks_to_scrobble[i]["title"]
additional_args = ("timestamp", "album", "album_artist", "context", "stream_id", "track_number", "mbid", "duration")
args_map_to = {"album_artist": "albumArtist", "track_number": "trackNumber", "stream_id": "streamID"} # so friggin lazy
for arg in additional_args:
if arg in tracks_to_scrobble[i] and tracks_to_scrobble[i][arg]:
if arg in args_map_to:
maps_to = args_map_to[arg]
else:
maps_to = arg
params["%s[%d]" %(maps_to, i)] = tracks_to_scrobble[i][arg]
_Request(self, "track.scrobble", params).execute()
if remaining_tracks:
self.scrobble_many(remaining_tracks)
class LastFMNetwork(_Network):
"""A Last.fm network object
api_key: a provided API_KEY
api_secret: a provided API_SECRET
session_key: a generated session_key or None
username: a username of a valid user
password_hash: the output of pylast.md5(password) where password is the user's password
if username and password_hash were provided and not session_key, session_key will be
generated automatically when needed.
Either a valid session_key or a combination of username and password_hash must be present for scrobbling.
Most read-only webservices only require an api_key and an api_secret, see about obtaining them from:
http://www.last.fm/api/account
"""
def __init__(self, api_key="", api_secret="", session_key="", username="", password_hash=""):
_Network.__init__(self,
name = "Last.fm",
homepage = "http://last.fm",
ws_server = ("ws.audioscrobbler.com", "/2.0/"),
api_key = api_key,
api_secret = api_secret,
session_key = session_key,
submission_server = "http://post.audioscrobbler.com:80/",
username = username,
password_hash = password_hash,
domain_names = {
DOMAIN_ENGLISH: 'www.last.fm',
DOMAIN_GERMAN: 'www.lastfm.de',
DOMAIN_SPANISH: 'www.lastfm.es',
DOMAIN_FRENCH: 'www.lastfm.fr',
DOMAIN_ITALIAN: 'www.lastfm.it',
DOMAIN_POLISH: 'www.lastfm.pl',
DOMAIN_PORTUGUESE: 'www.lastfm.com.br',
DOMAIN_SWEDISH: 'www.lastfm.se',
DOMAIN_TURKISH: 'www.lastfm.com.tr',
DOMAIN_RUSSIAN: 'www.lastfm.ru',
DOMAIN_JAPANESE: 'www.lastfm.jp',
DOMAIN_CHINESE: 'cn.last.fm',
},
urls = {
"album": "music/%(artist)s/%(album)s",
"artist": "music/%(artist)s",
"event": "event/%(id)s",
"country": "place/%(country_name)s",
"playlist": "user/%(user)s/library/playlists/%(appendix)s",
"tag": "tag/%(name)s",
"track": "music/%(artist)s/_/%(title)s",
"group": "group/%(name)s",
"user": "user/%(name)s",
}
)
def __repr__(self):
return "pylast.LastFMNetwork(%s)" %(", ".join(("'%s'" %self.api_key, "'%s'" %self.api_secret, "'%s'" %self.session_key,
"'%s'" %self.username, "'%s'" %self.password_hash)))
def __str__(self):
return "LastFM Network"
def get_lastfm_network(api_key="", api_secret="", session_key = "", username = "", password_hash = ""):
"""
Returns a preconfigured _Network object for Last.fm
api_key: a provided API_KEY
api_secret: a provided API_SECRET
session_key: a generated session_key or None
username: a username of a valid user
password_hash: the output of pylast.md5(password) where password is the user's password
if username and password_hash were provided and not session_key, session_key will be
generated automatically when needed.
Either a valid session_key or a combination of username and password_hash must be present for scrobbling.
Most read-only webservices only require an api_key and an api_secret, see about obtaining them from:
http://www.last.fm/api/account
"""
_deprecation_warning("Create a LastFMNetwork object instead")
return LastFMNetwork(api_key, api_secret, session_key, username, password_hash)
class LibreFMNetwork(_Network):
"""
A preconfigured _Network object for Libre.fm
api_key: a provided API_KEY
api_secret: a provided API_SECRET
session_key: a generated session_key or None
username: a username of a valid user
password_hash: the output of pylast.md5(password) where password is the user's password
if username and password_hash were provided and not session_key, session_key will be
generated automatically when needed.
"""
def __init__(self, api_key="", api_secret="", session_key = "", username = "", password_hash = ""):
_Network.__init__(self,
name = "Libre.fm",
homepage = "http://alpha.dev.libre.fm",
ws_server = ("alpha.dev.libre.fm", "/2.0/"),
api_key = api_key,
api_secret = api_secret,
session_key = session_key,
submission_server = "http://turtle.libre.fm:80/",
username = username,
password_hash = password_hash,
domain_names = {
DOMAIN_ENGLISH: "alpha.dev.libre.fm",
DOMAIN_GERMAN: "alpha.dev.libre.fm",
DOMAIN_SPANISH: "alpha.dev.libre.fm",
DOMAIN_FRENCH: "alpha.dev.libre.fm",
DOMAIN_ITALIAN: "alpha.dev.libre.fm",
DOMAIN_POLISH: "alpha.dev.libre.fm",
DOMAIN_PORTUGUESE: "alpha.dev.libre.fm",
DOMAIN_SWEDISH: "alpha.dev.libre.fm",
DOMAIN_TURKISH: "alpha.dev.libre.fm",
DOMAIN_RUSSIAN: "alpha.dev.libre.fm",
DOMAIN_JAPANESE: "alpha.dev.libre.fm",
DOMAIN_CHINESE: "alpha.dev.libre.fm",
},
urls = {
"album": "artist/%(artist)s/album/%(album)s",
"artist": "artist/%(artist)s",
"event": "event/%(id)s",
"country": "place/%(country_name)s",
"playlist": "user/%(user)s/library/playlists/%(appendix)s",
"tag": "tag/%(name)s",
"track": "music/%(artist)s/_/%(title)s",
"group": "group/%(name)s",
"user": "user/%(name)s",
}
)
def __repr__(self):
return "pylast.LibreFMNetwork(%s)" %(", ".join(("'%s'" %self.api_key, "'%s'" %self.api_secret, "'%s'" %self.session_key,
"'%s'" %self.username, "'%s'" %self.password_hash)))
def __str__(self):
return "Libre.fm Network"
def get_librefm_network(api_key="", api_secret="", session_key = "", username = "", password_hash = ""):
"""
Returns a preconfigured _Network object for Libre.fm
api_key: a provided API_KEY
api_secret: a provided API_SECRET
session_key: a generated session_key or None
username: a username of a valid user
password_hash: the output of pylast.md5(password) where password is the user's password
if username and password_hash were provided and not session_key, session_key will be
generated automatically when needed.
"""
_deprecation_warning("DeprecationWarning: Create a LibreFMNetwork object instead")
return LibreFMNetwork(api_key, api_secret, session_key, username, password_hash)
class _ShelfCacheBackend(object):
"""Used as a backend for caching cacheable requests."""
def __init__(self, file_path = None):
self.shelf = shelve.open(file_path)
def get_xml(self, key):
return self.shelf[key]
def set_xml(self, key, xml_string):
self.shelf[key] = xml_string
def has_key(self, key):
return key in self.shelf.keys()
class _Request(object):
"""Representing an abstract web service operation."""
def __init__(self, network, method_name, params = {}):
self.network = network
self.params = {}
for key in params:
self.params[key] = _unicode(params[key])
(self.api_key, self.api_secret, self.session_key) = network._get_ws_auth()
self.params["api_key"] = self.api_key
self.params["method"] = method_name
if network.is_caching_enabled():
self.cache = network._get_cache_backend()
if self.session_key:
self.params["sk"] = self.session_key
self.sign_it()
def sign_it(self):
"""Sign this request."""
if not "api_sig" in self.params.keys():
self.params['api_sig'] = self._get_signature()
def _get_signature(self):
"""Returns a 32-character hexadecimal md5 hash of the signature string."""
keys = list(self.params.keys())
keys.sort()
string = ""
for name in keys:
string += name
string += self.params[name]
string += self.api_secret
return md5(string)
def _get_cache_key(self):
"""The cache key is a string of concatenated sorted names and values."""
keys = list(self.params.keys())
keys.sort()
cache_key = str()
for key in keys:
if key != "api_sig" and key != "api_key" and key != "sk":
cache_key += key + _string(self.params[key])
return hashlib.sha1(cache_key).hexdigest()
def _get_cached_response(self):
"""Returns a file object of the cached response."""
if not self._is_cached():
response = self._download_response()
self.cache.set_xml(self._get_cache_key(), response)
return self.cache.get_xml(self._get_cache_key())
def _is_cached(self):
"""Returns True if the request is already in cache."""
return self.cache.has_key(self._get_cache_key())
def _download_response(self):
"""Returns a response body string from the server."""
# Delay the call if necessary
#self.network._delay_call() # enable it if you want.
data = []
for name in self.params.keys():
data.append('='.join((name, url_quote_plus(_string(self.params[name])))))
data = '&'.join(data)
headers = {
"Content-type": "application/x-www-form-urlencoded",
'Accept-Charset': 'utf-8',
'User-Agent': "pylast" + '/' + __version__
}
(HOST_NAME, HOST_SUBDIR) = self.network.ws_server
if self.network.is_proxy_enabled():
conn = HTTPConnection(host = self._get_proxy()[0], port = self._get_proxy()[1])
try:
conn.request(method='POST', url="http://" + HOST_NAME + HOST_SUBDIR,
body=data, headers=headers)
except Exception as e:
raise NetworkError(self.network, e)
else:
conn = HTTPConnection(host=HOST_NAME)
try:
conn.request(method='POST', url=HOST_SUBDIR, body=data, headers=headers)
except Exception as e:
raise NetworkError(self.network, e)
try:
response_text = _unicode(conn.getresponse().read())
except Exception as e:
raise MalformedResponseError(self.network, e)
self._check_response_for_errors(response_text)
return response_text
def execute(self, cacheable = False):
"""Returns the XML DOM response of the POST Request from the server"""
if self.network.is_caching_enabled() and cacheable:
response = self._get_cached_response()
else:
response = self._download_response()
return minidom.parseString(_string(response))
def _check_response_for_errors(self, response):
"""Checks the response for errors and raises one if any exists."""
try:
doc = minidom.parseString(_string(response))
except Exception as e:
raise MalformedResponseError(self.network, e)
e = doc.getElementsByTagName('lfm')[0]
if e.getAttribute('status') != "ok":
e = doc.getElementsByTagName('error')[0]
status = e.getAttribute('code')
details = e.firstChild.data.strip()
raise WSError(self.network, status, details)
class SessionKeyGenerator(object):
"""Methods of generating a session key:
1) Web Authentication:
a. network = get_*_network(API_KEY, API_SECRET)
b. sg = SessionKeyGenerator(network)
c. url = sg.get_web_auth_url()
d. Ask the user to open the url and authorize you, and wait for it.
e. session_key = sg.get_web_auth_session_key(url)
2) Username and Password Authentication:
a. network = get_*_network(API_KEY, API_SECRET)
b. username = raw_input("Please enter your username: ")
c. password_hash = pylast.md5(raw_input("Please enter your password: ")
d. session_key = SessionKeyGenerator(network).get_session_key(username, password_hash)
A session key's lifetime is infinie, unless the user provokes the rights of the given API Key.
If you create a Network object with just a API_KEY and API_SECRET and a username and a password_hash, a
SESSION_KEY will be automatically generated for that network and stored in it so you don't have to do this
manually, unless you want to.
"""
def __init__(self, network):
self.network = network
self.web_auth_tokens = {}
def _get_web_auth_token(self):
"""Retrieves a token from the network for web authentication.
The token then has to be authorized from getAuthURL before creating session.
"""
request = _Request(self.network, 'auth.getToken')
# default action is that a request is signed only when
# a session key is provided.
request.sign_it()
doc = request.execute()
e = doc.getElementsByTagName('token')[0]
return e.firstChild.data
def get_web_auth_url(self):
"""The user must open this page, and you first, then call get_web_auth_session_key(url) after that."""
token = self._get_web_auth_token()
url = '%(homepage)s/api/auth/?api_key=%(api)s&token=%(token)s' % \
{"homepage": self.network.homepage, "api": self.network.api_key, "token": token}
self.web_auth_tokens[url] = token
return url
def get_web_auth_session_key(self, url):
"""Retrieves the session key of a web authorization process by its url."""
if url in self.web_auth_tokens.keys():
token = self.web_auth_tokens[url]
else:
token = "" #that's gonna raise a WSError of an unauthorized token when the request is executed.
request = _Request(self.network, 'auth.getSession', {'token': token})
# default action is that a request is signed only when
# a session key is provided.
request.sign_it()
doc = request.execute()
return doc.getElementsByTagName('key')[0].firstChild.data
def get_session_key(self, username, password_hash):
"""Retrieve a session key with a username and a md5 hash of the user's password."""
params = {"username": username, "authToken": md5(username + password_hash)}
request = _Request(self.network, "auth.getMobileSession", params)
# default action is that a request is signed only when
# a session key is provided.
request.sign_it()
doc = request.execute()
return _extract(doc, "key")
TopItem = collections.namedtuple("TopItem", ["item", "weight"])
SimilarItem = collections.namedtuple("SimilarItem", ["item", "match"])
LibraryItem = collections.namedtuple("LibraryItem", ["item", "playcount", "tagcount"])
PlayedTrack = collections.namedtuple("PlayedTrack", ["track", "playback_date", "timestamp"])
LovedTrack = collections.namedtuple("LovedTrack", ["track", "date", "timestamp"])
ImageSizes = collections.namedtuple("ImageSizes", ["original", "large", "largesquare", "medium", "small", "extralarge"])
Image = collections.namedtuple("Image", ["title", "url", "dateadded", "format", "owner", "sizes", "votes"])
Shout = collections.namedtuple("Shout", ["body", "author", "date"])
def _string_output(funct):
def r(*args):
return _string(funct(*args))
return r
def _pad_list(given_list, desired_length, padding = None):
"""
Pads a list to be of the desired_length.
"""
while len(given_list) < desired_length:
given_list.append(padding)
return given_list
class _BaseObject(object):
"""An abstract webservices object."""
network = None
def __init__(self, network):
self.network = network
def _request(self, method_name, cacheable = False, params = None):
if not params:
params = self._get_params()
return _Request(self.network, method_name, params).execute(cacheable)
def _get_params(self):
"""Returns the most common set of parameters between all objects."""
return {}
def __hash__(self):
return hash(self.network) + \
hash(str(type(self)) + "".join(list(self._get_params().keys()) + list(self._get_params().values())).lower())
class _Taggable(object):
"""Common functions for classes with tags."""
def __init__(self, ws_prefix):
self.ws_prefix = ws_prefix
def add_tags(self, tags):
"""Adds one or several tags.
* tags: A sequence of tag names or Tag objects.
"""
for tag in tags:
self.add_tag(tag)
def add_tag(self, tag):
"""Adds one tag.
* tag: a tag name or a Tag object.
"""
if isinstance(tag, Tag):
tag = tag.get_name()
params = self._get_params()
params['tags'] = tag
self._request(self.ws_prefix + '.addTags', False, params)
def remove_tag(self, tag):
"""Remove a user's tag from this object."""
if isinstance(tag, Tag):
tag = tag.get_name()
params = self._get_params()
params['tag'] = tag
self._request(self.ws_prefix + '.removeTag', False, params)
def get_tags(self):
"""Returns a list of the tags set by the user to this object."""
# Uncacheable because it can be dynamically changed by the user.
params = self._get_params()
doc = self._request(self.ws_prefix + '.getTags', False, params)
tag_names = _extract_all(doc, 'name')
tags = []
for tag in tag_names:
tags.append(Tag(tag, self.network))
return tags
def remove_tags(self, tags):
"""Removes one or several tags from this object.
* tags: a sequence of tag names or Tag objects.
"""
for tag in tags:
self.remove_tag(tag)
def clear_tags(self):
"""Clears all the user-set tags. """
self.remove_tags(*(self.get_tags()))
def set_tags(self, tags):
"""Sets this object's tags to only those tags.
* tags: a sequence of tag names or Tag objects.
"""
c_old_tags = []
old_tags = []
c_new_tags = []
new_tags = []
to_remove = []
to_add = []
tags_on_server = self.get_tags()
for tag in tags_on_server:
c_old_tags.append(tag.get_name().lower())
old_tags.append(tag.get_name())
for tag in tags:
c_new_tags.append(tag.lower())
new_tags.append(tag)
for i in range(0, len(old_tags)):
if not c_old_tags[i] in c_new_tags:
to_remove.append(old_tags[i])
for i in range(0, len(new_tags)):
if not c_new_tags[i] in c_old_tags:
to_add.append(new_tags[i])
self.remove_tags(to_remove)
self.add_tags(to_add)
def get_top_tags(self, limit=None):
"""Returns a list of the most frequently used Tags on this object."""
doc = self._request(self.ws_prefix + '.getTopTags', True)
elements = doc.getElementsByTagName('tag')
seq = []
for element in elements:
tag_name = _extract(element, 'name')
tagcount = _extract(element, 'count')
seq.append(TopItem(Tag(tag_name, self.network), tagcount))
if limit:
seq = seq[:limit]
return seq
class WSError(Exception):
"""Exception related to the Network web service"""
def __init__(self, network, status, details):
self.status = status
self.details = details
self.network = network
@_string_output
def __str__(self):
return self.details
def get_id(self):
"""Returns the exception ID, from one of the following:
STATUS_INVALID_SERVICE = 2
STATUS_INVALID_METHOD = 3
STATUS_AUTH_FAILED = 4
STATUS_INVALID_FORMAT = 5
STATUS_INVALID_PARAMS = 6
STATUS_INVALID_RESOURCE = 7
STATUS_TOKEN_ERROR = 8
STATUS_INVALID_SK = 9
STATUS_INVALID_API_KEY = 10
STATUS_OFFLINE = 11
STATUS_SUBSCRIBERS_ONLY = 12
STATUS_TOKEN_UNAUTHORIZED = 14
STATUS_TOKEN_EXPIRED = 15
"""
return self.status
class MalformedResponseError(Exception):
"""Exception conveying a malformed response from Last.fm."""
def __init__(self, network, underlying_error):
self.network = network
self.underlying_error = underlying_error
def __str__(self):
return "Malformed response from Last.fm. Underlying error: %s" %str(self.underlying_error)
class NetworkError(Exception):
"""Exception conveying a problem in sending a request to Last.fm"""
def __init__(self, network, underlying_error):
self.network = network
self.underlying_error = underlying_error
def __str__(self):
return "NetworkError: %s" %str(self.underlying_error)
class Album(_BaseObject, _Taggable):
"""An album."""
title = None
artist = None
def __init__(self, artist, title, network):
"""
Create an album instance.
# Parameters:
* artist: An artist name or an Artist object.
* title: The album title.
"""
_BaseObject.__init__(self, network)
_Taggable.__init__(self, 'album')
if isinstance(artist, Artist):
self.artist = artist
else:
self.artist = Artist(artist, self.network)
self.title = title
def __repr__(self):
return "pylast.Album(%s, %s, %s)" %(repr(self.artist.name), repr(self.title), repr(self.network))
@_string_output
def __str__(self):
return _unicode("%s - %s") %(self.get_artist().get_name(), self.get_title())
def __eq__(self, other):
return (self.get_title().lower() == other.get_title().lower()) and (self.get_artist().get_name().lower() == other.get_artist().get_name().lower())
def __ne__(self, other):
return (self.get_title().lower() != other.get_title().lower()) or (self.get_artist().get_name().lower() != other.get_artist().get_name().lower())
def _get_params(self):
return {'artist': self.get_artist().get_name(), 'album': self.get_title(), }
def get_artist(self):
"""Returns the associated Artist object."""
return self.artist
def get_title(self):
"""Returns the album title."""
return self.title
def get_name(self):
"""Returns the album title (alias to Album.get_title)."""
return self.get_title()
def get_release_date(self):
"""Retruns the release date of the album."""
return _extract(self._request("album.getInfo", cacheable = True), "releasedate")
def get_cover_image(self, size = COVER_EXTRA_LARGE):
"""
Returns a uri to the cover image
size can be one of:
COVER_EXTRA_LARGE
COVER_LARGE
COVER_MEDIUM
COVER_SMALL
"""
return _extract_all(self._request("album.getInfo", cacheable = True), 'image')[size]
def get_id(self):
"""Returns the ID"""
return _extract(self._request("album.getInfo", cacheable = True), "id")
def get_playcount(self):
"""Returns the number of plays on the network"""
return _number(_extract(self._request("album.getInfo", cacheable = True), "playcount"))
def get_listener_count(self):
"""Returns the number of liteners on the network"""
return _number(_extract(self._request("album.getInfo", cacheable = True), "listeners"))
def get_top_tags(self, limit=None):
"""Returns a list of the most-applied tags to this album."""
doc = self._request("album.getInfo", True)
e = doc.getElementsByTagName("toptags")[0]
seq = []
for name in _extract_all(e, "name"):
seq.append(Tag(name, self.network))
if limit:
seq = seq[:limit]
return seq
def get_tracks(self):
"""Returns the list of Tracks on this album."""
uri = 'lastfm://playlist/album/%s' %self.get_id()
return XSPF(uri, self.network).get_tracks()
def get_mbid(self):
"""Returns the MusicBrainz id of the album."""
return _extract(self._request("album.getInfo", cacheable = True), "mbid")
def get_url(self, domain_name = DOMAIN_ENGLISH):
"""Returns the url of the album page on the network.
# Parameters:
* domain_name str: The network's language domain. Possible values:
o DOMAIN_ENGLISH
o DOMAIN_GERMAN
o DOMAIN_SPANISH
o DOMAIN_FRENCH
o DOMAIN_ITALIAN
o DOMAIN_POLISH
o DOMAIN_PORTUGUESE
o DOMAIN_SWEDISH
o DOMAIN_TURKISH
o DOMAIN_RUSSIAN
o DOMAIN_JAPANESE
o DOMAIN_CHINESE
"""
artist = _url_safe(self.get_artist().get_name())
album = _url_safe(self.get_title())
return self.network._get_url(domain_name, "album") %{'artist': artist, 'album': album}
def get_wiki_published_date(self):
"""Returns the date of publishing this version of the wiki."""
doc = self._request("album.getInfo", True)
if len(doc.getElementsByTagName("wiki")) == 0:
return
node = doc.getElementsByTagName("wiki")[0]
return _extract(node, "published")
def get_wiki_summary(self):
"""Returns the summary of the wiki."""
doc = self._request("album.getInfo", True)
if len(doc.getElementsByTagName("wiki")) == 0:
return
node = doc.getElementsByTagName("wiki")[0]
return _extract(node, "summary")
def get_wiki_content(self):
"""Returns the content of the wiki."""
doc = self._request("album.getInfo", True)
if len(doc.getElementsByTagName("wiki")) == 0:
return
node = doc.getElementsByTagName("wiki")[0]
return _extract(node, "content")
class Artist(_BaseObject, _Taggable):
"""An artist."""
name = None
def __init__(self, name, network):
"""Create an artist object.
# Parameters:
* name str: The artist's name.
"""
_BaseObject.__init__(self, network)
_Taggable.__init__(self, 'artist')
self.name = name
def __repr__(self):
return "pylast.Artist(%s, %s)" %(repr(self.get_name()), repr(self.network))
@_string_output
def __str__(self):
return self.get_name()
def __eq__(self, other):
return self.get_name().lower() == other.get_name().lower()
def __ne__(self, other):
return self.get_name().lower() != other.get_name().lower()
def _get_params(self):
return {'artist': self.get_name()}
def get_name(self, properly_capitalized=False):
"""Returns the name of the artist.
If properly_capitalized was asserted then the name would be downloaded
overwriting the given one."""
if properly_capitalized:
self.name = _extract(self._request("artist.getInfo", True), "name")
return self.name
def get_cover_image(self, size = COVER_MEGA):
"""
Returns a uri to the cover image
size can be one of:
COVER_MEGA
COVER_EXTRA_LARGE
COVER_LARGE
COVER_MEDIUM
COVER_SMALL
"""
return _extract_all(self._request("artist.getInfo", True), "image")[size]
def get_playcount(self):
"""Returns the number of plays on the network."""
return _number(_extract(self._request("artist.getInfo", True), "playcount"))
def get_mbid(self):
"""Returns the MusicBrainz ID of this artist."""
doc = self._request("artist.getInfo", True)
return _extract(doc, "mbid")
def get_listener_count(self):
"""Returns the number of liteners on the network."""
if hasattr(self, "listener_count"):
return self.listener_count
else:
self.listener_count = _number(_extract(self._request("artist.getInfo", True), "listeners"))
return self.listener_count
def is_streamable(self):
"""Returns True if the artist is streamable."""
return bool(_number(_extract(self._request("artist.getInfo", True), "streamable")))
def get_bio_published_date(self):
"""Returns the date on which the artist's biography was published."""
return _extract(self._request("artist.getInfo", True), "published")
def get_bio_summary(self, language=None):
"""Returns the summary of the artist's biography."""
if language:
params = self._get_params()
params["lang"] = language
else:
params = None
return _extract(self._request("artist.getInfo", True, params), "summary")
def get_bio_content(self, language=None):
"""Returns the content of the artist's biography."""
if language:
params = self._get_params()
params["lang"] = language
else:
params = None
return _extract(self._request("artist.getInfo", True, params), "content")
def get_upcoming_events(self):
"""Returns a list of the upcoming Events for this artist."""
doc = self._request('artist.getEvents', True)
ids = _extract_all(doc, 'id')
events = []
for e_id in ids:
events.append(Event(e_id, self.network))
return events
def get_similar(self, limit = None):
"""Returns the similar artists on the network."""
params = self._get_params()
if limit:
params['limit'] = limit
doc = self._request('artist.getSimilar', True, params)
names = _extract_all(doc, "name")
matches = _extract_all(doc, "match")
artists = []
for i in range(0, len(names)):
artists.append(SimilarItem(Artist(names[i], self.network), _number(matches[i])))
return artists
def get_top_albums(self):
"""Retuns a list of the top albums."""
doc = self._request('artist.getTopAlbums', True)
seq = []
for node in doc.getElementsByTagName("album"):
name = _extract(node, "name")
artist = _extract(node, "name", 1)
playcount = _extract(node, "playcount")
seq.append(TopItem(Album(artist, name, self.network), playcount))
return seq
def get_top_tracks(self):
"""Returns a list of the most played Tracks by this artist."""
doc = self._request("artist.getTopTracks", True)
seq = []
for track in doc.getElementsByTagName('track'):
title = _extract(track, "name")
artist = _extract(track, "name", 1)
playcount = _number(_extract(track, "playcount"))
seq.append( TopItem(Track(artist, title, self.network), playcount) )
return seq
def get_top_fans(self, limit = None):
"""Returns a list of the Users who played this artist the most.
# Parameters:
* limit int: Max elements.
"""
doc = self._request('artist.getTopFans', True)
seq = []
elements = doc.getElementsByTagName('user')
for element in elements:
if limit and len(seq) >= limit:
break
name = _extract(element, 'name')
weight = _number(_extract(element, 'weight'))
seq.append(TopItem(User(name, self.network), weight))
return seq
def share(self, users, message = None):
"""Shares this artist (sends out recommendations).
# Parameters:
* users [User|str,]: A list that can contain usernames, emails, User objects, or all of them.
* message str: A message to include in the recommendation message.
"""
#last.fm currently accepts a max of 10 recipient at a time
while(len(users) > 10):
section = users[0:9]
users = users[9:]
self.share(section, message)
nusers = []
for user in users:
if isinstance(user, User):
nusers.append(user.get_name())
else:
nusers.append(user)
params = self._get_params()
recipients = ','.join(nusers)
params['recipient'] = recipients
if message:
params['message'] = message
self._request('artist.share', False, params)
def get_url(self, domain_name = DOMAIN_ENGLISH):
"""Returns the url of the artist page on the network.
# Parameters:
* domain_name: The network's language domain. Possible values:
o DOMAIN_ENGLISH
o DOMAIN_GERMAN
o DOMAIN_SPANISH
o DOMAIN_FRENCH
o DOMAIN_ITALIAN
o DOMAIN_POLISH
o DOMAIN_PORTUGUESE
o DOMAIN_SWEDISH
o DOMAIN_TURKISH
o DOMAIN_RUSSIAN
o DOMAIN_JAPANESE
o DOMAIN_CHINESE
"""
artist = _url_safe(self.get_name())
return self.network._get_url(domain_name, "artist") %{'artist': artist}
def get_images(self, order=IMAGES_ORDER_POPULARITY, limit=None):
"""
Returns a sequence of Image objects
if limit is None it will return all
order can be IMAGES_ORDER_POPULARITY or IMAGES_ORDER_DATE.
If limit==None, it will try to pull all the available data.
"""
images = []
params = self._get_params()
params["order"] = order
nodes = _collect_nodes(limit, self, "artist.getImages", True, params)
for e in nodes:
if _extract(e, "name"):
user = User(_extract(e, "name"), self.network)
else:
user = None
images.append(Image(
_extract(e, "title"),
_extract(e, "url"),
_extract(e, "dateadded"),
_extract(e, "format"),
user,
ImageSizes(*_extract_all(e, "size")),
(_extract(e, "thumbsup"), _extract(e, "thumbsdown"))
)
)
return images
def get_shouts(self, limit=50):
"""
Returns a sequqence of Shout objects
"""
shouts = []
for node in _collect_nodes(limit, self, "artist.getShouts", False):
shouts.append(Shout(
_extract(node, "body"),
User(_extract(node, "author"), self.network),
_extract(node, "date")
)
)
return shouts
def shout(self, message):
"""
Post a shout
"""
params = self._get_params()
params["message"] = message
self._request("artist.Shout", False, params)
class Event(_BaseObject):
"""An event."""
id = None
def __init__(self, event_id, network):
_BaseObject.__init__(self, network)
self.id = event_id
def __repr__(self):
return "pylast.Event(%s, %s)" %(repr(self.id), repr(self.network))
@_string_output
def __str__(self):
return "Event #" + self.get_id()
def __eq__(self, other):
return self.get_id() == other.get_id()
def __ne__(self, other):
return self.get_id() != other.get_id()
def _get_params(self):
return {'event': self.get_id()}
def attend(self, attending_status):
"""Sets the attending status.
* attending_status: The attending status. Possible values:
o EVENT_ATTENDING
o EVENT_MAYBE_ATTENDING
o EVENT_NOT_ATTENDING
"""
params = self._get_params()
params['status'] = attending_status
self._request('event.attend', False, params)
def get_attendees(self):
"""
Get a list of attendees for an event
"""
doc = self._request("event.getAttendees", False)
users = []
for name in _extract_all(doc, "name"):
users.append(User(name, self.network))
return users
def get_id(self):
"""Returns the id of the event on the network. """
return self.id
def get_title(self):
"""Returns the title of the event. """
doc = self._request("event.getInfo", True)
return _extract(doc, "title")
def get_headliner(self):
"""Returns the headliner of the event. """
doc = self._request("event.getInfo", True)
return Artist(_extract(doc, "headliner"), self.network)
def get_artists(self):
"""Returns a list of the participating Artists. """
doc = self._request("event.getInfo", True)
names = _extract_all(doc, "artist")
artists = []
for name in names:
artists.append(Artist(name, self.network))
return artists
def get_venue(self):
"""Returns the venue where the event is held."""
doc = self._request("event.getInfo", True)
v = doc.getElementsByTagName("venue")[0]
venue_id = _number(_extract(v, "id"))
return Venue(venue_id, self.network)
def get_start_date(self):
"""Returns the date when the event starts."""
doc = self._request("event.getInfo", True)
return _extract(doc, "startDate")
def get_description(self):
"""Returns the description of the event. """
doc = self._request("event.getInfo", True)
return _extract(doc, "description")
def get_cover_image(self, size = COVER_MEGA):
"""
Returns a uri to the cover image
size can be one of:
COVER_MEGA
COVER_EXTRA_LARGE
COVER_LARGE
COVER_MEDIUM
COVER_SMALL
"""
doc = self._request("event.getInfo", True)
return _extract_all(doc, "image")[size]
def get_attendance_count(self):
"""Returns the number of attending people. """
doc = self._request("event.getInfo", True)
return _number(_extract(doc, "attendance"))
def get_review_count(self):
"""Returns the number of available reviews for this event. """
doc = self._request("event.getInfo", True)
return _number(_extract(doc, "reviews"))
def get_url(self, domain_name = DOMAIN_ENGLISH):
"""Returns the url of the event page on the network.
* domain_name: The network's language domain. Possible values:
o DOMAIN_ENGLISH
o DOMAIN_GERMAN
o DOMAIN_SPANISH
o DOMAIN_FRENCH
o DOMAIN_ITALIAN
o DOMAIN_POLISH
o DOMAIN_PORTUGUESE
o DOMAIN_SWEDISH
o DOMAIN_TURKISH
o DOMAIN_RUSSIAN
o DOMAIN_JAPANESE
o DOMAIN_CHINESE
"""
return self.network._get_url(domain_name, "event") %{'id': self.get_id()}
def share(self, users, message = None):
"""Shares this event (sends out recommendations).
* users: A list that can contain usernames, emails, User objects, or all of them.
* message: A message to include in the recommendation message.
"""
#last.fm currently accepts a max of 10 recipient at a time
while(len(users) > 10):
section = users[0:9]
users = users[9:]
self.share(section, message)
nusers = []
for user in users:
if isinstance(user, User):
nusers.append(user.get_name())
else:
nusers.append(user)
params = self._get_params()
recipients = ','.join(nusers)
params['recipient'] = recipients
if message:
params['message'] = message
self._request('event.share', False, params)
def get_shouts(self, limit=50):
"""
Returns a sequqence of Shout objects
"""
shouts = []
for node in _collect_nodes(limit, self, "event.getShouts", False):
shouts.append(Shout(
_extract(node, "body"),
User(_extract(node, "author"), self.network),
_extract(node, "date")
)
)
return shouts
def shout(self, message):
"""
Post a shout
"""
params = self._get_params()
params["message"] = message
self._request("event.Shout", False, params)
class Country(_BaseObject):
"""A country at Last.fm."""
name = None
def __init__(self, name, network):
_BaseObject.__init__(self, network)
self.name = name
def __repr__(self):
return "pylast.Country(%s, %s)" %(repr(self.name), repr(self.network))
@_string_output
def __str__(self):
return self.get_name()
def __eq__(self, other):
return self.get_name().lower() == other.get_name().lower()
def __ne__(self, other):
return self.get_name() != other.get_name()
def _get_params(self):
return {'country': self.get_name()}
def _get_name_from_code(self, alpha2code):
# TODO: Have this function lookup the alpha-2 code and return the country name.
return alpha2code
def get_name(self):
"""Returns the country name. """
return self.name
def get_top_artists(self):
"""Returns a sequence of the most played artists."""
doc = self._request('geo.getTopArtists', True)
seq = []
for node in doc.getElementsByTagName("artist"):
name = _extract(node, 'name')
playcount = _extract(node, "playcount")
seq.append(TopItem(Artist(name, self.network), playcount))
return seq
def get_top_tracks(self):
"""Returns a sequence of the most played tracks"""
doc = self._request("geo.getTopTracks", True)
seq = []
for n in doc.getElementsByTagName('track'):
title = _extract(n, 'name')
artist = _extract(n, 'name', 1)
playcount = _number(_extract(n, "playcount"))
seq.append( TopItem(Track(artist, title, self.network), playcount))
return seq
def get_url(self, domain_name = DOMAIN_ENGLISH):
"""Returns the url of the event page on the network.
* domain_name: The network's language domain. Possible values:
o DOMAIN_ENGLISH
o DOMAIN_GERMAN
o DOMAIN_SPANISH
o DOMAIN_FRENCH
o DOMAIN_ITALIAN
o DOMAIN_POLISH
o DOMAIN_PORTUGUESE
o DOMAIN_SWEDISH
o DOMAIN_TURKISH
o DOMAIN_RUSSIAN
o DOMAIN_JAPANESE
o DOMAIN_CHINESE
"""
country_name = _url_safe(self.get_name())
return self.network._get_url(domain_name, "country") %{'country_name': country_name}
class Library(_BaseObject):
"""A user's Last.fm library."""
user = None
def __init__(self, user, network):
_BaseObject.__init__(self, network)
if isinstance(user, User):
self.user = user
else:
self.user = User(user, self.network)
self._albums_index = 0
self._artists_index = 0
self._tracks_index = 0
def __repr__(self):
return "pylast.Library(%s, %s)" %(repr(self.user), repr(self.network))
@_string_output
def __str__(self):
return repr(self.get_user()) + "'s Library"
def _get_params(self):
return {'user': self.user.get_name()}
def get_user(self):
"""Returns the user who owns this library."""
return self.user
def add_album(self, album):
"""Add an album to this library."""
params = self._get_params()
params["artist"] = album.get_artist.get_name()
params["album"] = album.get_name()
self._request("library.addAlbum", False, params)
def add_artist(self, artist):
"""Add an artist to this library."""
params = self._get_params()
params["artist"] = artist.get_name()
self._request("library.addArtist", False, params)
def add_track(self, track):
"""Add a track to this library."""
params = self._get_params()
params["track"] = track.get_title()
self._request("library.addTrack", False, params)
def get_albums(self, artist=None, limit=50):
"""
Returns a sequence of Album objects
If no artist is specified, it will return all, sorted by playcount descendingly.
If limit==None it will return all (may take a while)
"""
params = self._get_params()
if artist:
params["artist"] = artist
seq = []
for node in _collect_nodes(limit, self, "library.getAlbums", True, params):
name = _extract(node, "name")
artist = _extract(node, "name", 1)
playcount = _number(_extract(node, "playcount"))
tagcount = _number(_extract(node, "tagcount"))
seq.append(LibraryItem(Album(artist, name, self.network), playcount, tagcount))
return seq
def get_artists(self, limit=50):
"""
Returns a sequence of Album objects
if limit==None it will return all (may take a while)
"""
seq = []
for node in _collect_nodes(limit, self, "library.getArtists", True):
name = _extract(node, "name")
playcount = _number(_extract(node, "playcount"))
tagcount = _number(_extract(node, "tagcount"))
seq.append(LibraryItem(Artist(name, self.network), playcount, tagcount))
return seq
def get_tracks(self, artist=None, album=None, limit=50):
"""
Returns a sequence of Album objects
If limit==None it will return all (may take a while)
"""
params = self._get_params()
if artist:
params["artist"] = artist
if album:
params["album"] = album
seq = []
for node in _collect_nodes(limit, self, "library.getTracks", True, params):
name = _extract(node, "name")
artist = _extract(node, "name", 1)
playcount = _number(_extract(node, "playcount"))
tagcount = _number(_extract(node, "tagcount"))
seq.append(LibraryItem(Track(artist, name, self.network), playcount, tagcount))
return seq
class Playlist(_BaseObject):
"""A Last.fm user playlist."""
id = None
user = None
def __init__(self, user, id, network):
_BaseObject.__init__(self, network)
if isinstance(user, User):
self.user = user
else:
self.user = User(user, self.network)
self.id = id
@_string_output
def __str__(self):
return repr(self.user) + "'s playlist # " + repr(self.id)
def _get_info_node(self):
"""Returns the node from user.getPlaylists where this playlist's info is."""
doc = self._request("user.getPlaylists", True)
for node in doc.getElementsByTagName("playlist"):
if _extract(node, "id") == str(self.get_id()):
return node
def _get_params(self):
return {'user': self.user.get_name(), 'playlistID': self.get_id()}
def get_id(self):
"""Returns the playlist id."""
return self.id
def get_user(self):
"""Returns the owner user of this playlist."""
return self.user
def get_tracks(self):
"""Returns a list of the tracks on this user playlist."""
uri = _unicode('lastfm://playlist/%s') %self.get_id()
return XSPF(uri, self.network).get_tracks()
def add_track(self, track):
"""Adds a Track to this Playlist."""
params = self._get_params()
params['artist'] = track.get_artist().get_name()
params['track'] = track.get_title()
self._request('playlist.addTrack', False, params)
def get_title(self):
"""Returns the title of this playlist."""
return _extract(self._get_info_node(), "title")
def get_creation_date(self):
"""Returns the creation date of this playlist."""
return _extract(self._get_info_node(), "date")
def get_size(self):
"""Returns the number of tracks in this playlist."""
return _number(_extract(self._get_info_node(), "size"))
def get_description(self):
"""Returns the description of this playlist."""
return _extract(self._get_info_node(), "description")
def get_duration(self):
"""Returns the duration of this playlist in milliseconds."""
return _number(_extract(self._get_info_node(), "duration"))
def is_streamable(self):
"""Returns True if the playlist is streamable.
For a playlist to be streamable, it needs at least 45 tracks by 15 different artists."""
if _extract(self._get_info_node(), "streamable") == '1':
return True
else:
return False
def has_track(self, track):
"""Checks to see if track is already in the playlist.
* track: Any Track object.
"""
return track in self.get_tracks()
def get_cover_image(self, size = COVER_EXTRA_LARGE):
"""
Returns a uri to the cover image
size can be one of:
COVER_MEGA
COVER_EXTRA_LARGE
COVER_LARGE
COVER_MEDIUM
COVER_SMALL
"""
return _extract(self._get_info_node(), "image")[size]
def get_url(self, domain_name = DOMAIN_ENGLISH):
"""Returns the url of the playlist on the network.
* domain_name: The network's language domain. Possible values:
o DOMAIN_ENGLISH
o DOMAIN_GERMAN
o DOMAIN_SPANISH
o DOMAIN_FRENCH
o DOMAIN_ITALIAN
o DOMAIN_POLISH
o DOMAIN_PORTUGUESE
o DOMAIN_SWEDISH
o DOMAIN_TURKISH
o DOMAIN_RUSSIAN
o DOMAIN_JAPANESE
o DOMAIN_CHINESE
"""
english_url = _extract(self._get_info_node(), "url")
appendix = english_url[english_url.rfind("/") + 1:]
return self.network._get_url(domain_name, "playlist") %{'appendix': appendix, "user": self.get_user().get_name()}
class Tag(_BaseObject):
"""A Last.fm object tag."""
# TODO: getWeeklyArtistChart (too lazy, i'll wait for when someone requests it)
name = None
def __init__(self, name, network):
_BaseObject.__init__(self, network)
self.name = name
def __repr__(self):
return "pylast.Tag(%s, %s)" %(repr(self.name), repr(self.network))
@_string_output
def __str__(self):
return self.get_name()
def __eq__(self, other):
return self.get_name().lower() == other.get_name().lower()
def __ne__(self, other):
return self.get_name().lower() != other.get_name().lower()
def _get_params(self):
return {'tag': self.get_name()}
def get_name(self, properly_capitalized=False):
"""Returns the name of the tag. """
if properly_capitalized:
self.name = _extract(self._request("tag.getInfo", True), "name")
return self.name
def get_similar(self):
"""Returns the tags similar to this one, ordered by similarity. """
doc = self._request('tag.getSimilar', True)
seq = []
names = _extract_all(doc, 'name')
for name in names:
seq.append(Tag(name, self.network))
return seq
def get_top_albums(self):
"""Retuns a list of the top albums."""
doc = self._request('tag.getTopAlbums', True)
seq = []
for node in doc.getElementsByTagName("album"):
name = _extract(node, "name")
artist = _extract(node, "name", 1)
playcount = _extract(node, "playcount")
seq.append(TopItem(Album(artist, name, self.network), playcount))
return seq
def get_top_tracks(self):
"""Returns a list of the most played Tracks by this artist."""
doc = self._request("tag.getTopTracks", True)
seq = []
for track in doc.getElementsByTagName('track'):
title = _extract(track, "name")
artist = _extract(track, "name", 1)
playcount = _number(_extract(track, "playcount"))
seq.append( TopItem(Track(artist, title, self.network), playcount) )
return seq
def get_top_artists(self):
"""Returns a sequence of the most played artists."""
doc = self._request('tag.getTopArtists', True)
seq = []
for node in doc.getElementsByTagName("artist"):
name = _extract(node, 'name')
playcount = _extract(node, "playcount")
seq.append(TopItem(Artist(name, self.network), playcount))
return seq
def get_weekly_chart_dates(self):
"""Returns a list of From and To tuples for the available charts."""
doc = self._request("tag.getWeeklyChartList", True)
seq = []
for node in doc.getElementsByTagName("chart"):
seq.append( (node.getAttribute("from"), node.getAttribute("to")) )
return seq
def get_weekly_artist_charts(self, from_date = None, to_date = None):
"""Returns the weekly artist charts for the week starting from the from_date value to the to_date value."""
params = self._get_params()
if from_date and to_date:
params["from"] = from_date
params["to"] = to_date
doc = self._request("tag.getWeeklyArtistChart", True, params)
seq = []
for node in doc.getElementsByTagName("artist"):
item = Artist(_extract(node, "name"), self.network)
weight = _number(_extract(node, "weight"))
seq.append(TopItem(item, weight))
return seq
def get_url(self, domain_name = DOMAIN_ENGLISH):
"""Returns the url of the tag page on the network.
* domain_name: The network's language domain. Possible values:
o DOMAIN_ENGLISH
o DOMAIN_GERMAN
o DOMAIN_SPANISH
o DOMAIN_FRENCH
o DOMAIN_ITALIAN
o DOMAIN_POLISH
o DOMAIN_PORTUGUESE
o DOMAIN_SWEDISH
o DOMAIN_TURKISH
o DOMAIN_RUSSIAN
o DOMAIN_JAPANESE
o DOMAIN_CHINESE
"""
name = _url_safe(self.get_name())
return self.network._get_url(domain_name, "tag") %{'name': name}
class Track(_BaseObject, _Taggable):
"""A Last.fm track."""
artist = None
title = None
def __init__(self, artist, title, network):
_BaseObject.__init__(self, network)
_Taggable.__init__(self, 'track')
if isinstance(artist, Artist):
self.artist = artist
else:
self.artist = Artist(artist, self.network)
self.title = title
def __repr__(self):
return "pylast.Track(%s, %s, %s)" %(repr(self.artist.name), repr(self.title), repr(self.network))
@_string_output
def __str__(self):
return self.get_artist().get_name() + ' - ' + self.get_title()
def __eq__(self, other):
return (self.get_title().lower() == other.get_title().lower()) and (self.get_artist().get_name().lower() == other.get_artist().get_name().lower())
def __ne__(self, other):
return (self.get_title().lower() != other.get_title().lower()) or (self.get_artist().get_name().lower() != other.get_artist().get_name().lower())
def _get_params(self):
return {'artist': self.get_artist().get_name(), 'track': self.get_title()}
def get_artist(self):
"""Returns the associated Artist object."""
return self.artist
def get_title(self, properly_capitalized=False):
"""Returns the track title."""
if properly_capitalized:
self.title = _extract(self._request("track.getInfo", True), "name")
return self.title
def get_name(self, properly_capitalized=False):
"""Returns the track title (alias to Track.get_title)."""
return self.get_title(properly_capitalized)
def get_id(self):
"""Returns the track id on the network."""
doc = self._request("track.getInfo", True)
return _extract(doc, "id")
def get_duration(self):
"""Returns the track duration."""
doc = self._request("track.getInfo", True)
return _number(_extract(doc, "duration"))
def get_mbid(self):
"""Returns the MusicBrainz ID of this track."""
doc = self._request("track.getInfo", True)
return _extract(doc, "mbid")
def get_listener_count(self):
"""Returns the listener count."""
if hasattr(self, "listener_count"):
return self.listener_count
else:
doc = self._request("track.getInfo", True)
self.listener_count = _number(_extract(doc, "listeners"))
return self.listener_count
def get_playcount(self):
"""Returns the play count."""
doc = self._request("track.getInfo", True)
return _number(_extract(doc, "playcount"))
def is_streamable(self):
"""Returns True if the track is available at Last.fm."""
doc = self._request("track.getInfo", True)
return _extract(doc, "streamable") == "1"
def is_fulltrack_available(self):
"""Returns True if the fulltrack is available for streaming."""
doc = self._request("track.getInfo", True)
return doc.getElementsByTagName("streamable")[0].getAttribute("fulltrack") == "1"
def get_album(self):
"""Returns the album object of this track."""
doc = self._request("track.getInfo", True)
albums = doc.getElementsByTagName("album")
if len(albums) == 0:
return
node = doc.getElementsByTagName("album")[0]
return Album(_extract(node, "artist"), _extract(node, "title"), self.network)
def get_wiki_published_date(self):
"""Returns the date of publishing this version of the wiki."""
doc = self._request("track.getInfo", True)
if len(doc.getElementsByTagName("wiki")) == 0:
return
node = doc.getElementsByTagName("wiki")[0]
return _extract(node, "published")
def get_wiki_summary(self):
"""Returns the summary of the wiki."""
doc = self._request("track.getInfo", True)
if len(doc.getElementsByTagName("wiki")) == 0:
return
node = doc.getElementsByTagName("wiki")[0]
return _extract(node, "summary")
def get_wiki_content(self):
"""Returns the content of the wiki."""
doc = self._request("track.getInfo", True)
if len(doc.getElementsByTagName("wiki")) == 0:
return
node = doc.getElementsByTagName("wiki")[0]
return _extract(node, "content")
def love(self):
"""Adds the track to the user's loved tracks. """
self._request('track.love')
def ban(self):
"""Ban this track from ever playing on the radio. """
self._request('track.ban')
def get_similar(self):
"""Returns similar tracks for this track on the network, based on listening data. """
doc = self._request('track.getSimilar', True)
seq = []
for node in doc.getElementsByTagName("track"):
title = _extract(node, 'name')
artist = _extract(node, 'name', 1)
match = _number(_extract(node, "match"))
seq.append(SimilarItem(Track(artist, title, self.network), match))
return seq
def get_top_fans(self, limit = None):
"""Returns a list of the Users who played this track."""
doc = self._request('track.getTopFans', True)
seq = []
elements = doc.getElementsByTagName('user')
for element in elements:
if limit and len(seq) >= limit:
break
name = _extract(element, 'name')
weight = _number(_extract(element, 'weight'))
seq.append(TopItem(User(name, self.network), weight))
return seq
def share(self, users, message = None):
"""Shares this track (sends out recommendations).
* users: A list that can contain usernames, emails, User objects, or all of them.
* message: A message to include in the recommendation message.
"""
#last.fm currently accepts a max of 10 recipient at a time
while(len(users) > 10):
section = users[0:9]
users = users[9:]
self.share(section, message)
nusers = []
for user in users:
if isinstance(user, User):
nusers.append(user.get_name())
else:
nusers.append(user)
params = self._get_params()
recipients = ','.join(nusers)
params['recipient'] = recipients
if message:
params['message'] = message
self._request('track.share', False, params)
def get_url(self, domain_name = DOMAIN_ENGLISH):
"""Returns the url of the track page on the network.
* domain_name: The network's language domain. Possible values:
o DOMAIN_ENGLISH
o DOMAIN_GERMAN
o DOMAIN_SPANISH
o DOMAIN_FRENCH
o DOMAIN_ITALIAN
o DOMAIN_POLISH
o DOMAIN_PORTUGUESE
o DOMAIN_SWEDISH
o DOMAIN_TURKISH
o DOMAIN_RUSSIAN
o DOMAIN_JAPANESE
o DOMAIN_CHINESE
"""
artist = _url_safe(self.get_artist().get_name())
title = _url_safe(self.get_title())
return self.network._get_url(domain_name, "track") %{'domain': self.network._get_language_domain(domain_name), 'artist': artist, 'title': title}
def get_shouts(self, limit=50):
"""
Returns a sequqence of Shout objects
"""
shouts = []
for node in _collect_nodes(limit, self, "track.getShouts", False):
shouts.append(Shout(
_extract(node, "body"),
User(_extract(node, "author"), self.network),
_extract(node, "date")
)
)
return shouts
class Group(_BaseObject):
"""A Last.fm group."""
name = None
def __init__(self, group_name, network):
_BaseObject.__init__(self, network)
self.name = group_name
def __repr__(self):
return "pylast.Group(%s, %s)" %(repr(self.name), repr(self.network))
@_string_output
def __str__(self):
return self.get_name()
def __eq__(self, other):
return self.get_name().lower() == other.get_name().lower()
def __ne__(self, other):
return self.get_name() != other.get_name()
def _get_params(self):
return {'group': self.get_name()}
def get_name(self):
"""Returns the group name. """
return self.name
def get_weekly_chart_dates(self):
"""Returns a list of From and To tuples for the available charts."""
doc = self._request("group.getWeeklyChartList", True)
seq = []
for node in doc.getElementsByTagName("chart"):
seq.append( (node.getAttribute("from"), node.getAttribute("to")) )
return seq
def get_weekly_artist_charts(self, from_date = None, to_date = None):
"""Returns the weekly artist charts for the week starting from the from_date value to the to_date value."""
params = self._get_params()
if from_date and to_date:
params["from"] = from_date
params["to"] = to_date
doc = self._request("group.getWeeklyArtistChart", True, params)
seq = []
for node in doc.getElementsByTagName("artist"):
item = Artist(_extract(node, "name"), self.network)
weight = _number(_extract(node, "playcount"))
seq.append(TopItem(item, weight))
return seq
def get_weekly_album_charts(self, from_date = None, to_date = None):
"""Returns the weekly album charts for the week starting from the from_date value to the to_date value."""
params = self._get_params()
if from_date and to_date:
params["from"] = from_date
params["to"] = to_date
doc = self._request("group.getWeeklyAlbumChart", True, params)
seq = []
for node in doc.getElementsByTagName("album"):
item = Album(_extract(node, "artist"), _extract(node, "name"), self.network)
weight = _number(_extract(node, "playcount"))
seq.append(TopItem(item, weight))
return seq
def get_weekly_track_charts(self, from_date = None, to_date = None):
"""Returns the weekly track charts for the week starting from the from_date value to the to_date value."""
params = self._get_params()
if from_date and to_date:
params["from"] = from_date
params["to"] = to_date
doc = self._request("group.getWeeklyTrackChart", True, params)
seq = []
for node in doc.getElementsByTagName("track"):
item = Track(_extract(node, "artist"), _extract(node, "name"), self.network)
weight = _number(_extract(node, "playcount"))
seq.append(TopItem(item, weight))
return seq
def get_url(self, domain_name = DOMAIN_ENGLISH):
"""Returns the url of the group page on the network.
* domain_name: The network's language domain. Possible values:
o DOMAIN_ENGLISH
o DOMAIN_GERMAN
o DOMAIN_SPANISH
o DOMAIN_FRENCH
o DOMAIN_ITALIAN
o DOMAIN_POLISH
o DOMAIN_PORTUGUESE
o DOMAIN_SWEDISH
o DOMAIN_TURKISH
o DOMAIN_RUSSIAN
o DOMAIN_JAPANESE
o DOMAIN_CHINESE
"""
name = _url_safe(self.get_name())
return self.network._get_url(domain_name, "group") %{'name': name}
def get_members(self, limit=50):
"""
Returns a sequence of User objects
if limit==None it will return all
"""
nodes = _collect_nodes(limit, self, "group.getMembers", False)
users = []
for node in nodes:
users.append(User(_extract(node, "name"), self.network))
return users
class XSPF(_BaseObject):
"A Last.fm XSPF playlist."""
uri = None
def __init__(self, uri, network):
_BaseObject.__init__(self, network)
self.uri = uri
def _get_params(self):
return {'playlistURL': self.get_uri()}
@_string_output
def __str__(self):
return self.get_uri()
def __eq__(self, other):
return self.get_uri() == other.get_uri()
def __ne__(self, other):
return self.get_uri() != other.get_uri()
def get_uri(self):
"""Returns the Last.fm playlist URI. """
return self.uri
def get_tracks(self):
"""Returns the tracks on this playlist."""
doc = self._request('playlist.fetch', True)
seq = []
for n in doc.getElementsByTagName('track'):
title = _extract(n, 'title')
artist = _extract(n, 'creator')
seq.append(Track(artist, title, self.network))
return seq
class User(_BaseObject):
"""A Last.fm user."""
name = None
def __init__(self, user_name, network):
_BaseObject.__init__(self, network)
self.name = user_name
self._past_events_index = 0
self._recommended_events_index = 0
self._recommended_artists_index = 0
def __repr__(self):
return "pylast.User(%s, %s)" %(repr(self.name), repr(self.network))
@_string_output
def __str__(self):
return self.get_name()
def __eq__(self, another):
return self.get_name() == another.get_name()
def __ne__(self, another):
return self.get_name() != another.get_name()
def _get_params(self):
return {"user": self.get_name()}
def get_name(self, properly_capitalized=False):
"""Returns the nuser name."""
if properly_capitalized:
self.name = _extract(self._request("user.getInfo", True), "name")
return self.name
def get_upcoming_events(self):
"""Returns all the upcoming events for this user. """
doc = self._request('user.getEvents', True)
ids = _extract_all(doc, 'id')
events = []
for e_id in ids:
events.append(Event(e_id, self.network))
return events
def get_friends(self, limit = 50):
"""Returns a list of the user's friends. """
seq = []
for node in _collect_nodes(limit, self, "user.getFriends", False):
seq.append(User(_extract(node, "name"), self.network))
return seq
def get_loved_tracks(self, limit=50):
"""Returns this user's loved track as a sequence of LovedTrack objects
in reverse order of their timestamp, all the way back to the first track.
If limit==None, it will try to pull all the available data.
This method uses caching. Enable caching only if you're pulling a
large amount of data.
Use extract_items() with the return of this function to
get only a sequence of Track objects with no playback dates. """
params = self._get_params()
if limit:
params['limit'] = limit
seq = []
for track in _collect_nodes(limit, self, "user.getLovedTracks", True, params):
title = _extract(track, "name")
artist = _extract(track, "name", 1)
date = _extract(track, "date")
timestamp = track.getElementsByTagName("date")[0].getAttribute("uts")
seq.append(LovedTrack(Track(artist, title, self.network), date, timestamp))
return seq
def get_neighbours(self, limit = 50):
"""Returns a list of the user's friends."""
params = self._get_params()
if limit:
params['limit'] = limit
doc = self._request('user.getNeighbours', True, params)
seq = []
names = _extract_all(doc, 'name')
for name in names:
seq.append(User(name, self.network))
return seq
def get_past_events(self, limit=50):
"""
Returns a sequence of Event objects
if limit==None it will return all
"""
seq = []
for n in _collect_nodes(limit, self, "user.getPastEvents", False):
seq.append(Event(_extract(n, "id"), self.network))
return seq
def get_playlists(self):
"""Returns a list of Playlists that this user owns."""
doc = self._request("user.getPlaylists", True)
playlists = []
for playlist_id in _extract_all(doc, "id"):
playlists.append(Playlist(self.get_name(), playlist_id, self.network))
return playlists
def get_now_playing(self):
"""Returns the currently playing track, or None if nothing is playing. """
params = self._get_params()
params['limit'] = '1'
doc = self._request('user.getRecentTracks', False, params)
e = doc.getElementsByTagName('track')[0]
if not e.hasAttribute('nowplaying'):
return None
artist = _extract(e, 'artist')
title = _extract(e, 'name')
return Track(artist, title, self.network)
def get_recent_tracks(self, limit = 10, page = None, from_time = None, to_time = None):
"""Returns this user's played track as a sequence of PlayedTrack objects
in reverse order of their playtime, all the way back to the first track.
If limit==None, it will try to pull all the available data.
If limit is set, it will only return the that amount of items.
If page is set, it will return the tracks of that page.
E.g: If limit is 10 and page is 3, it will return tracks 21-30.
If from_time and to_time are set, they will specify the time range to
get tracks from. Both are Unix Epoch (Important: Should be integers).
This method uses caching. Enable caching only if you're pulling a
large amount of data.
Use extract_items() with the return of this function to
get only a sequence of Track objects with no playback dates. """
params = self._get_params()
if limit:
params['limit'] = limit
if page:
params['page'] = page
if from_time:
params['from'] = from_time
if to_time:
params['to'] = to_time
seq = []
for track in _collect_nodes(limit, self, "user.getRecentTracks", True, params):
if track.hasAttribute('nowplaying'):
continue #to prevent the now playing track from sneaking in here
title = _extract(track, "name")
artist = _extract(track, "artist")
date = _extract(track, "date")
timestamp = track.getElementsByTagName("date")[0].getAttribute("uts")
seq.append(PlayedTrack(Track(artist, title, self.network), date, timestamp))
return seq
def get_recent_tracks_count(self, from_time = None, to_time = None):
"""Returns the amount of recently played tracks. Taken fro the 'total'
attribute of the <recenttracks> node of this user's recent played tracks.
This is unfortunately done in a separate call from get_recent_tracks,
as it's quite hard to mingle into the existing code in a meaningful way.
If from_time and to_time are set, they will specify the time range to
get tracks from. Both are Unix Epoch (Important: Should be integers).
This method uses caching. Enable caching only if you're pulling a
large amount of data.
"""
params = self._get_params()
params['limit'] = 1
if from_time:
params['from'] = from_time
if to_time:
params['to'] = to_time
doc = self._request("user.getRecentTracks", True, params)
return int(doc.documentElement.childNodes[1].getAttribute('total'))
def get_id(self):
"""Returns the user id."""
doc = self._request("user.getInfo", True)
return _extract(doc, "id")
def get_language(self):
"""Returns the language code of the language used by the user."""
doc = self._request("user.getInfo", True)
return _extract(doc, "lang")
def get_country(self):
"""Returns the name of the country of the user."""
doc = self._request("user.getInfo", True)
return Country(_extract(doc, "country"), self.network)
def get_age(self):
"""Returns the user's age."""
doc = self._request("user.getInfo", True)
return _number(_extract(doc, "age"))
def get_gender(self):
"""Returns the user's gender. Either USER_MALE or USER_FEMALE."""
doc = self._request("user.getInfo", True)
value = _extract(doc, "gender")
if value == 'm':
return USER_MALE
elif value == 'f':
return USER_FEMALE
return None
def is_subscriber(self):
"""Returns whether the user is a subscriber or not. True or False."""
doc = self._request("user.getInfo", True)
return _extract(doc, "subscriber") == "1"
def get_playcount(self):
"""Returns the user's playcount so far."""
doc = self._request("user.getInfo", True)
return _number(_extract(doc, "playcount"))
def get_top_albums(self, period = PERIOD_OVERALL):
"""Returns the top albums played by a user.
* period: The period of time. Possible values:
o PERIOD_OVERALL
o PERIOD_7DAYS
o PERIOD_3MONTHS
o PERIOD_6MONTHS
o PERIOD_12MONTHS
"""
params = self._get_params()
params['period'] = period
doc = self._request('user.getTopAlbums', True, params)
seq = []
for album in doc.getElementsByTagName('album'):
name = _extract(album, 'name')
artist = _extract(album, 'name', 1)
playcount = _extract(album, "playcount")
seq.append(TopItem(Album(artist, name, self.network), playcount))
return seq
def get_top_artists(self, period = PERIOD_OVERALL):
"""Returns the top artists played by a user.
* period: The period of time. Possible values:
o PERIOD_OVERALL
o PERIOD_7DAYS
o PERIOD_3MONTHS
o PERIOD_6MONTHS
o PERIOD_12MONTHS
"""
params = self._get_params()
params['period'] = period
doc = self._request('user.getTopArtists', True, params)
seq = []
for node in doc.getElementsByTagName('artist'):
name = _extract(node, 'name')
playcount = _extract(node, "playcount")
seq.append(TopItem(Artist(name, self.network), playcount))
return seq
def get_top_tags(self, limit=None):
"""Returns a sequence of the top tags used by this user with their counts as TopItem objects.
* limit: The limit of how many tags to return.
"""
doc = self._request("user.getTopTags", True)
seq = []
for node in doc.getElementsByTagName("tag"):
seq.append(TopItem(Tag(_extract(node, "name"), self.network), _extract(node, "count")))
if limit:
seq = seq[:limit]
return seq
def get_top_tracks(self, period = PERIOD_OVERALL):
"""Returns the top tracks played by a user.
* period: The period of time. Possible values:
o PERIOD_OVERALL
o PERIOD_7DAYS
o PERIOD_3MONTHS
o PERIOD_6MONTHS
o PERIOD_12MONTHS
"""
params = self._get_params()
params['period'] = period
doc = self._request('user.getTopTracks', True, params)
seq = []
for track in doc.getElementsByTagName('track'):
name = _extract(track, 'name')
artist = _extract(track, 'name', 1)
playcount = _extract(track, "playcount")
seq.append(TopItem(Track(artist, name, self.network), playcount))
return seq
def get_weekly_chart_dates(self):
"""Returns a list of From and To tuples for the available charts."""
doc = self._request("user.getWeeklyChartList", True)
seq = []
for node in doc.getElementsByTagName("chart"):
seq.append( (node.getAttribute("from"), node.getAttribute("to")) )
return seq
def get_weekly_artist_charts(self, from_date = None, to_date = None):
"""Returns the weekly artist charts for the week starting from the from_date value to the to_date value."""
params = self._get_params()
if from_date and to_date:
params["from"] = from_date
params["to"] = to_date
doc = self._request("user.getWeeklyArtistChart", True, params)
seq = []
for node in doc.getElementsByTagName("artist"):
item = Artist(_extract(node, "name"), self.network)
weight = _number(_extract(node, "playcount"))
seq.append(TopItem(item, weight))
return seq
def get_weekly_album_charts(self, from_date = None, to_date = None):
"""Returns the weekly album charts for the week starting from the from_date value to the to_date value."""
params = self._get_params()
if from_date and to_date:
params["from"] = from_date
params["to"] = to_date
doc = self._request("user.getWeeklyAlbumChart", True, params)
seq = []
for node in doc.getElementsByTagName("album"):
item = Album(_extract(node, "artist"), _extract(node, "name"), self.network)
weight = _number(_extract(node, "playcount"))
seq.append(TopItem(item, weight))
return seq
def get_weekly_track_charts(self, from_date = None, to_date = None):
"""Returns the weekly track charts for the week starting from the from_date value to the to_date value."""
params = self._get_params()
if from_date and to_date:
params["from"] = from_date
params["to"] = to_date
doc = self._request("user.getWeeklyTrackChart", True, params)
seq = []
for node in doc.getElementsByTagName("track"):
item = Track(_extract(node, "artist"), _extract(node, "name"), self.network)
weight = _number(_extract(node, "playcount"))
seq.append(TopItem(item, weight))
return seq
def compare_with_user(self, user, shared_artists_limit = None):
"""Compare this user with another Last.fm user.
Returns a sequence (tasteometer_score, (shared_artist1, shared_artist2, ...))
user: A User object or a username string/unicode object.
"""
if isinstance(user, User):
user = user.get_name()
params = self._get_params()
if shared_artists_limit:
params['limit'] = shared_artists_limit
params['type1'] = 'user'
params['type2'] = 'user'
params['value1'] = self.get_name()
params['value2'] = user
doc = self._request('tasteometer.compare', False, params)
score = _extract(doc, 'score')
artists = doc.getElementsByTagName('artists')[0]
shared_artists_names = _extract_all(artists, 'name')
shared_artists_seq = []
for name in shared_artists_names:
shared_artists_seq.append(Artist(name, self.network))
return (score, shared_artists_seq)
def get_image(self):
"""Returns the user's avatar."""
doc = self._request("user.getInfo", True)
return _extract(doc, "image")
def get_url(self, domain_name = DOMAIN_ENGLISH):
"""Returns the url of the user page on the network.
* domain_name: The network's language domain. Possible values:
o DOMAIN_ENGLISH
o DOMAIN_GERMAN
o DOMAIN_SPANISH
o DOMAIN_FRENCH
o DOMAIN_ITALIAN
o DOMAIN_POLISH
o DOMAIN_PORTUGUESE
o DOMAIN_SWEDISH
o DOMAIN_TURKISH
o DOMAIN_RUSSIAN
o DOMAIN_JAPANESE
o DOMAIN_CHINESE
"""
name = _url_safe(self.get_name())
return self.network._get_url(domain_name, "user") %{'name': name}
def get_library(self):
"""Returns the associated Library object. """
return Library(self, self.network)
def get_shouts(self, limit=50):
"""
Returns a sequqence of Shout objects
"""
shouts = []
for node in _collect_nodes(limit, self, "user.getShouts", False):
shouts.append(Shout(
_extract(node, "body"),
User(_extract(node, "author"), self.network),
_extract(node, "date")
)
)
return shouts
def shout(self, message):
"""
Post a shout
"""
params = self._get_params()
params["message"] = message
self._request("user.Shout", False, params)
class AuthenticatedUser(User):
def __init__(self, network):
User.__init__(self, "", network);
def _get_params(self):
return {"user": self.get_name()}
def get_name(self):
"""Returns the name of the authenticated user."""
doc = self._request("user.getInfo", True, {"user": ""}) # hack
self.name = _extract(doc, "name")
return self.name
def get_recommended_events(self, limit=50):
"""
Returns a sequence of Event objects
if limit==None it will return all
"""
seq = []
for node in _collect_nodes(limit, self, "user.getRecommendedEvents", False):
seq.append(Event(_extract(node, "id"), self.network))
return seq
def get_recommended_artists(self, limit=50):
"""
Returns a sequence of Event objects
if limit==None it will return all
"""
seq = []
for node in _collect_nodes(limit, self, "user.getRecommendedArtists", False):
seq.append(Artist(_extract(node, "name"), self.network))
return seq
class _Search(_BaseObject):
"""An abstract class. Use one of its derivatives."""
def __init__(self, ws_prefix, search_terms, network):
_BaseObject.__init__(self, network)
self._ws_prefix = ws_prefix
self.search_terms = search_terms
self._last_page_index = 0
def _get_params(self):
params = {}
for key in self.search_terms.keys():
params[key] = self.search_terms[key]
return params
def get_total_result_count(self):
"""Returns the total count of all the results."""
doc = self._request(self._ws_prefix + ".search", True)
return _extract(doc, "opensearch:totalResults")
def _retreive_page(self, page_index):
"""Returns the node of matches to be processed"""
params = self._get_params()
params["page"] = str(page_index)
doc = self._request(self._ws_prefix + ".search", True, params)
return doc.getElementsByTagName(self._ws_prefix + "matches")[0]
def _retrieve_next_page(self):
self._last_page_index += 1
return self._retreive_page(self._last_page_index)
class AlbumSearch(_Search):
"""Search for an album by name."""
def __init__(self, album_name, network):
_Search.__init__(self, "album", {"album": album_name}, network)
def get_next_page(self):
"""Returns the next page of results as a sequence of Album objects."""
master_node = self._retrieve_next_page()
seq = []
for node in master_node.getElementsByTagName("album"):
seq.append(Album(_extract(node, "artist"), _extract(node, "name"), self.network))
return seq
class ArtistSearch(_Search):
"""Search for an artist by artist name."""
def __init__(self, artist_name, network):
_Search.__init__(self, "artist", {"artist": artist_name}, network)
def get_next_page(self):
"""Returns the next page of results as a sequence of Artist objects."""
master_node = self._retrieve_next_page()
seq = []
for node in master_node.getElementsByTagName("artist"):
artist = Artist(_extract(node, "name"), self.network)
artist.listener_count = _number(_extract(node, "listeners"))
seq.append(artist)
return seq
class TagSearch(_Search):
"""Search for a tag by tag name."""
def __init__(self, tag_name, network):
_Search.__init__(self, "tag", {"tag": tag_name}, network)
def get_next_page(self):
"""Returns the next page of results as a sequence of Tag objects."""
master_node = self._retrieve_next_page()
seq = []
for node in master_node.getElementsByTagName("tag"):
tag = Tag(_extract(node, "name"), self.network)
tag.tag_count = _number(_extract(node, "count"))
seq.append(tag)
return seq
class TrackSearch(_Search):
"""Search for a track by track title. If you don't wanna narrow the results down
by specifying the artist name, set it to empty string."""
def __init__(self, artist_name, track_title, network):
_Search.__init__(self, "track", {"track": track_title, "artist": artist_name}, network)
def get_next_page(self):
"""Returns the next page of results as a sequence of Track objects."""
master_node = self._retrieve_next_page()
seq = []
for node in master_node.getElementsByTagName("track"):
track = Track(_extract(node, "artist"), _extract(node, "name"), self.network)
track.listener_count = _number(_extract(node, "listeners"))
seq.append(track)
return seq
class VenueSearch(_Search):
"""Search for a venue by its name. If you don't wanna narrow the results down
by specifying a country, set it to empty string."""
def __init__(self, venue_name, country_name, network):
_Search.__init__(self, "venue", {"venue": venue_name, "country": country_name}, network)
def get_next_page(self):
"""Returns the next page of results as a sequence of Track objects."""
master_node = self._retrieve_next_page()
seq = []
for node in master_node.getElementsByTagName("venue"):
seq.append(Venue(_extract(node, "id"), self.network))
return seq
class Venue(_BaseObject):
"""A venue where events are held."""
# TODO: waiting for a venue.getInfo web service to use.
id = None
def __init__(self, id, network):
_BaseObject.__init__(self, network)
self.id = _number(id)
def __repr__(self):
return "pylast.Venue(%s, %s)" %(repr(self.id), repr(self.network))
@_string_output
def __str__(self):
return "Venue #" + str(self.id)
def __eq__(self, other):
return self.get_id() == other.get_id()
def _get_params(self):
return {"venue": self.get_id()}
def get_id(self):
"""Returns the id of the venue."""
return self.id
def get_upcoming_events(self):
"""Returns the upcoming events in this venue."""
doc = self._request("venue.getEvents", True)
seq = []
for node in doc.getElementsByTagName("event"):
seq.append(Event(_extract(node, "id"), self.network))
return seq
def get_past_events(self):
"""Returns the past events held in this venue."""
doc = self._request("venue.getEvents", True)
seq = []
for node in doc.getElementsByTagName("event"):
seq.append(Event(_extract(node, "id"), self.network))
return seq
def md5(text):
"""Returns the md5 hash of a string."""
h = hashlib.md5()
h.update(_unicode(text).encode("utf-8"))
return h.hexdigest()
def _unicode(text):
if sys.version_info[0] == 3:
if type(text) in (bytes, bytearray):
return str(text, "utf-8")
elif type(text) == str:
return text
else:
return str(text)
elif sys.version_info[0] ==2:
if type(text) in (str,):
return unicode(text, "utf-8")
elif type(text) == unicode:
return text
else:
return unicode(text)
def _string(text):
"""For Python2 routines that can only process str type."""
if sys.version_info[0] == 3:
if type(text) != str:
return str(text)
else:
return text
elif sys.version_info[0] == 2:
if type(text) == str:
return text
if type(text) == int:
return str(text)
return text.encode("utf-8")
def _collect_nodes(limit, sender, method_name, cacheable, params=None):
"""
Returns a sequqnce of dom.Node objects about as close to
limit as possible
"""
if not params:
params = sender._get_params()
nodes = []
page = 1
end_of_pages = False
while not end_of_pages and (not limit or (limit and len(nodes) < limit)):
params["page"] = str(page)
doc = sender._request(method_name, cacheable, params)
main = doc.documentElement.childNodes[1]
if main.hasAttribute("totalPages"):
total_pages = _number(main.getAttribute("totalPages"))
elif main.hasAttribute("totalpages"):
total_pages = _number(main.getAttribute("totalpages"))
else:
raise Exception("No total pages attribute")
for node in main.childNodes:
if not node.nodeType == xml.dom.Node.TEXT_NODE and len(nodes) < limit:
nodes.append(node)
if page >= total_pages:
end_of_pages = True
page += 1
return nodes
def _extract(node, name, index = 0):
"""Extracts a value from the xml string"""
nodes = node.getElementsByTagName(name)
if len(nodes):
if nodes[index].firstChild:
return _unescape_htmlentity(nodes[index].firstChild.data.strip())
else:
return None
def _extract_all(node, name, limit_count = None):
"""Extracts all the values from the xml string. returning a list."""
seq = []
for i in range(0, len(node.getElementsByTagName(name))):
if len(seq) == limit_count:
break
seq.append(_extract(node, name, i))
return seq
def _url_safe(text):
"""Does all kinds of tricks on a text to make it safe to use in a url."""
return url_quote_plus(url_quote_plus(_string(text))).lower()
def _number(string):
"""
Extracts an int from a string. Returns a 0 if None or an empty string was passed
"""
if not string:
return 0
elif string == "":
return 0
else:
try:
return int(string)
except ValueError:
return float(string)
def _unescape_htmlentity(string):
#string = _unicode(string)
mapping = htmlentitydefs.name2codepoint
for key in mapping:
string = string.replace("&%s;" %key, unichr(mapping[key]))
return string
def extract_items(topitems_or_libraryitems):
"""Extracts a sequence of items from a sequence of TopItem or LibraryItem objects."""
seq = []
for i in topitems_or_libraryitems:
seq.append(i.item)
return seq
class ScrobblingError(Exception):
def __init__(self, message):
Exception.__init__(self)
self.message = message
@_string_output
def __str__(self):
return self.message
class BannedClientError(ScrobblingError):
def __init__(self):
ScrobblingError.__init__(self, "This version of the client has been banned")
class BadAuthenticationError(ScrobblingError):
def __init__(self):
ScrobblingError.__init__(self, "Bad authentication token")
class BadTimeError(ScrobblingError):
def __init__(self):
ScrobblingError.__init__(self, "Time provided is not close enough to current time")
class BadSessionError(ScrobblingError):
def __init__(self):
ScrobblingError.__init__(self, "Bad session id, consider re-handshaking")
class _ScrobblerRequest(object):
def __init__(self, url, params, network, type="POST"):
for key in params:
params[key] = str(params[key])
self.params = params
self.type = type
(self.hostname, self.subdir) = url_split_host(url[len("http:"):])
self.network = network
def execute(self):
"""Returns a string response of this request."""
connection = HTTPConnection(self.hostname)
data = []
for name in self.params.keys():
value = url_quote_plus(self.params[name])
data.append('='.join((name, value)))
data = "&".join(data)
headers = {
"Content-type": "application/x-www-form-urlencoded",
"Accept-Charset": "utf-8",
"User-Agent": "pylast" + "/" + __version__,
"HOST": self.hostname
}
if self.type == "GET":
connection.request("GET", self.subdir + "?" + data, headers = headers)
else:
connection.request("POST", self.subdir, data, headers)
response = _unicode(connection.getresponse().read())
self._check_response_for_errors(response)
return response
def _check_response_for_errors(self, response):
"""When passed a string response it checks for erros, raising
any exceptions as necessary."""
lines = response.split("\n")
status_line = lines[0]
if status_line == "OK":
return
elif status_line == "BANNED":
raise BannedClientError()
elif status_line == "BADAUTH":
raise BadAuthenticationError()
elif status_line == "BADTIME":
raise BadTimeError()
elif status_line == "BADSESSION":
raise BadSessionError()
elif status_line.startswith("FAILED "):
reason = status_line[status_line.find("FAILED ")+len("FAILED "):]
raise ScrobblingError(reason)
class Scrobbler(object):
"""A class for scrobbling tracks to Last.fm"""
session_id = None
nowplaying_url = None
submissions_url = None
def __init__(self, network, client_id, client_version):
self.client_id = client_id
self.client_version = client_version
self.username = network.username
self.password = network.password_hash
self.network = network
def _do_handshake(self):
"""Handshakes with the server"""
timestamp = str(int(time.time()))
if self.password and self.username:
token = md5(self.password + timestamp)
elif self.network.api_key and self.network.api_secret and self.network.session_key:
if not self.username:
self.username = self.network.get_authenticated_user().get_name()
token = md5(self.network.api_secret + timestamp)
params = {"hs": "true", "p": "1.2.1", "c": self.client_id,
"v": self.client_version, "u": self.username, "t": timestamp,
"a": token}
if self.network.session_key and self.network.api_key:
params["sk"] = self.network.session_key
params["api_key"] = self.network.api_key
server = self.network.submission_server
response = _ScrobblerRequest(server, params, self.network, "GET").execute().split("\n")
self.session_id = response[1]
self.nowplaying_url = response[2]
self.submissions_url = response[3]
def _get_session_id(self, new = False):
"""Returns a handshake. If new is true, then it will be requested from the server
even if one was cached."""
if not self.session_id or new:
self._do_handshake()
return self.session_id
def report_now_playing(self, artist, title, album = "", duration = "", track_number = "", mbid = ""):
_deprecation_warning("DeprecationWarning: Use Netowrk.update_now_playing(...) instead")
params = {"s": self._get_session_id(), "a": artist, "t": title,
"b": album, "l": duration, "n": track_number, "m": mbid}
try:
_ScrobblerRequest(self.nowplaying_url, params, self.network).execute()
except BadSessionError:
self._do_handshake()
self.report_now_playing(artist, title, album, duration, track_number, mbid)
def scrobble(self, artist, title, time_started, source, mode, duration, album="", track_number="", mbid=""):
"""Scrobble a track. parameters:
artist: Artist name.
title: Track title.
time_started: UTC timestamp of when the track started playing.
source: The source of the track
SCROBBLE_SOURCE_USER: Chosen by the user (the most common value, unless you have a reason for choosing otherwise, use this).
SCROBBLE_SOURCE_NON_PERSONALIZED_BROADCAST: Non-personalised broadcast (e.g. Shoutcast, BBC Radio 1).
SCROBBLE_SOURCE_PERSONALIZED_BROADCAST: Personalised recommendation except Last.fm (e.g. Pandora, Launchcast).
SCROBBLE_SOURCE_LASTFM: ast.fm (any mode). In this case, the 5-digit recommendation_key value must be set.
SCROBBLE_SOURCE_UNKNOWN: Source unknown.
mode: The submission mode
SCROBBLE_MODE_PLAYED: The track was played.
SCROBBLE_MODE_LOVED: The user manually loved the track (implies a listen)
SCROBBLE_MODE_SKIPPED: The track was skipped (Only if source was Last.fm)
SCROBBLE_MODE_BANNED: The track was banned (Only if source was Last.fm)
duration: Track duration in seconds.
album: The album name.
track_number: The track number on the album.
mbid: MusicBrainz ID.
"""
_deprecation_warning("DeprecationWarning: Use Network.scrobble(...) instead")
params = {"s": self._get_session_id(), "a[0]": _string(artist), "t[0]": _string(title),
"i[0]": str(time_started), "o[0]": source, "r[0]": mode, "l[0]": str(duration),
"b[0]": _string(album), "n[0]": track_number, "m[0]": mbid}
_ScrobblerRequest(self.submissions_url, params, self.network).execute()
def scrobble_many(self, tracks):
"""
Scrobble several tracks at once.
tracks: A sequence of a sequence of parameters for each trach. The order of parameters
is the same as if passed to the scrobble() method.
"""
_deprecation_warning("DeprecationWarning: Use Network.scrobble_many(...) instead")
remainder = []
if len(tracks) > 50:
remainder = tracks[50:]
tracks = tracks[:50]
params = {"s": self._get_session_id()}
i = 0
for t in tracks:
_pad_list(t, 9, "")
params["a[%s]" % str(i)] = _string(t[0])
params["t[%s]" % str(i)] = _string(t[1])
params["i[%s]" % str(i)] = str(t[2])
params["o[%s]" % str(i)] = t[3]
params["r[%s]" % str(i)] = t[4]
params["l[%s]" % str(i)] = str(t[5])
params["b[%s]" % str(i)] = _string(t[6])
params["n[%s]" % str(i)] = t[7]
params["m[%s]" % str(i)] = t[8]
i += 1
_ScrobblerRequest(self.submissions_url, params, self.network).execute()
if remainder:
self.scrobble_many(remainder)
| [
[
14,
0,
0.0055,
0.0003,
0,
0.66,
0,
162,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.0057,
0.0003,
0,
0.66,
0.0079,
777,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.006,
0.0003,
0,
0.... | [
"__version__ = '0.5'",
"__author__ = 'Amr Hassan'",
"__copyright__ = \"Copyright (C) 2008-2010 Amr Hassan\"",
"__license__ = \"apache2\"",
"__email__ = 'amr.hassan@gmail.com'",
"import hashlib",
"from xml.dom import minidom",
"import xml.dom",
"import time",
"import shelve",
"import tempfile",
... |
# Copyright 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you
# may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied. See the License for the specific language governing
# permissions and limitations under the License.
import os
import Options
srcdir = '.'
blddir = 'build'
VERSION = '0.1'
def set_options(opt):
opt.tool_options('compiler_cxx')
def configure(conf):
conf.check_tool('compiler_cxx')
conf.check_tool('node_addon')
conf.env.append_value('CCFLAGS', ['-O3'])
conf.env.append_value('CXXFLAGS', ['-O3'])
if Options.platform == 'darwin': conf.env.append_value('LINKFLAGS', ['-undefined', 'dynamic_lookup'])
conf.env.append_value("CPPPATH_PROTOBUF", "%s/include"%(os.environ['PROTOBUF']))
conf.env.append_value("LIBPATH_PROTOBUF", "%s/lib"%(os.environ['PROTOBUF']))
conf.env.append_value("LIB_PROTOBUF", "protobuf")
def build(bld):
# protobuf_for_node comes as a library to link against for services
# and an addon to use for plain serialization.
obj = bld.new_task_gen('cxx', 'shlib')
obj.target = 'protobuf_for_node_lib'
obj.source = 'protobuf_for_node.cc'
obj.uselib = ['NODE', 'PROTOBUF']
obj = bld.new_task_gen('cxx', 'shlib', 'node_addon')
obj.target = 'protobuf_for_node'
obj.source = 'addon.cc'
obj.uselib = ['PROTOBUF']
obj.uselib_local = 'protobuf_for_node_lib'
# Example service. If you build your own add-on that exports a
# protobuf service, you will need to replace uselib_local with
# uselib and point CPPPATH, LIBPATH and LIB to where you've
# installed protobuf_for_node.
obj = bld.new_task_gen('cxx', 'shlib', 'node_addon')
obj.target = 'protoservice'
obj.source = ['example/protoservice.pb.cc', 'example/protoservice.cc']
obj.uselib = ['PROTOBUF']
obj.uselib_local = 'protobuf_for_node_lib'
| [
[
1,
0,
0.2586,
0.0172,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.2759,
0.0172,
0,
0.66,
0.1429,
971,
0,
1,
0,
0,
971,
0,
0
],
[
14,
0,
0.3103,
0.0172,
0,
... | [
"import os",
"import Options",
"srcdir = '.'",
"blddir = 'build'",
"VERSION = '0.1'",
"def set_options(opt):\n opt.tool_options('compiler_cxx')",
" opt.tool_options('compiler_cxx')",
"def configure(conf):\n conf.check_tool('compiler_cxx')\n conf.check_tool('node_addon')\n\n conf.env.append_value(... |
import os, sys
import Tkinter as tk
import tkFileDialog
import bootloader
class bootloadergui:
def __init__(self):
self.flash = []
self.importingfile=None
for i in range(0x6000):
self.flash.append(0xFF)
self.eeprom = []
for i in range(0x100):
self.eeprom.append(0xFF)
self.root = tk.Tk()
self.root.title('USB Bootloader GUI')
self.write_bootloader_on_export = tk.BooleanVar()
self.write_bootloader_on_export.set(0)
self.write_eeprom_on_export = tk.BooleanVar()
self.write_eeprom_on_export.set(0)
self.verify_on_write = tk.BooleanVar()
self.verify_on_write.set(1)
self.clear_buffers_on_erase = tk.BooleanVar()
self.clear_buffers_on_erase.set(1)
self.display_bootloader = tk.BooleanVar()
self.display_bootloader.set(0)
self.menubar = tk.Menu(self.root)
self.filemenu = tk.Menu(self.menubar, tearoff=0)
self.filemenu.add_command(label='Import Hex...', command=self.import_hex)
self.filemenu.add_command(label='Export Hex...', command=self.export_hex)
self.filemenu.add_separator()
self.filemenu.add_checkbutton(label='Write Bootloader on Export Hex', variable=self.write_bootloader_on_export)
self.filemenu.add_checkbutton(label='Write EEPROM on Export Hex', variable=self.write_eeprom_on_export)
self.filemenu.add_separator()
self.filemenu.add_command(label='Quit', command=self.exit)
self.menubar.add_cascade(label='File', menu=self.filemenu)
self.bootloadermenu = tk.Menu(self.menubar, tearoff=0)
self.bootloadermenu.add_command(label='Read Device', command=self.read_device)
self.bootloadermenu.add_command(label='Write Device', command=self.write_device)
self.bootloadermenu.add_command(label='Verify', command=self.verify)
self.bootloadermenu.add_command(label='Erase', command=self.erase)
self.bootloadermenu.add_command(label='Blank Check', command=self.blank_check)
self.bootloadermenu.add_separator()
self.bootloadermenu.add_command(label='Read EEPROM', command=self.read_eeprom)
self.bootloadermenu.add_command(label='Write EEPROM', command=self.write_eeprom)
self.bootloadermenu.add_separator()
self.bootloadermenu.add_checkbutton(label='Verify on Write', variable=self.verify_on_write)
self.bootloadermenu.add_checkbutton(label='Clear Memory Buffers on Erase', variable=self.clear_buffers_on_erase)
self.bootloadermenu.add_separator()
self.bootloadermenu.add_command(label='Connect', command=self.connect)
self.bootloadermenu.add_command(label='Disconnect/Run', command=self.disconnect)
self.menubar.add_cascade(label='Bootloader', menu=self.bootloadermenu)
self.root.config(menu=self.menubar)
self.statusdisplay = tk.Text(self.root, height=2, width=70, font=('Courier', 10), background='#71FF71', state=tk.DISABLED)
self.statusdisplay.pack(anchor=tk.NW, padx=10, pady=10)
self.buttonframe = tk.Frame(self.root)
self.readbutton = tk.Button(self.buttonframe, text='Read', command=self.read_device)
self.readbutton.pack(side=tk.LEFT, padx=5)
self.writebutton = tk.Button(self.buttonframe, text='Write', command=self.write_device)
self.writebutton.pack(side=tk.LEFT, padx=5)
self.verifybutton = tk.Button(self.buttonframe, text='Verify', command=self.verify)
self.verifybutton.pack(side=tk.LEFT, padx=5)
self.erasebutton = tk.Button(self.buttonframe, text='Erase', command=self.erase)
self.erasebutton.pack(side=tk.LEFT, padx=5)
self.blankchkbutton = tk.Button(self.buttonframe, text='Blank Check', command=self.blank_check)
self.blankchkbutton.pack(side=tk.LEFT, padx=5)
self.connectbutton = tk.Button(self.buttonframe, text='Connect', command=self.connect)
self.connectbutton.pack(side=tk.LEFT, padx=5)
self.disconnectbutton = tk.Button(self.buttonframe, text='Disconnect/Run', command=self.disconnect)
self.disconnectbutton.pack(side=tk.LEFT, padx=5)
self.doitallbutton = tk.Button(self.buttonframe, text='Do it all', command=self.doitall)
self.doitallbutton.pack(side=tk.LEFT, padx=5)
self.buttonframe.pack(side=tk.TOP, anchor=tk.NW, padx=5)
self.flashdispframe = tk.LabelFrame(self.root, text='Program Memory', padx=5, pady=5)
self.flashdispframe.pack(anchor=tk.NW, padx=10, pady=10)
self.flashdisplaybootloader = tk.Checkbutton(self.flashdispframe, text='Display Bootloader', variable=self.display_bootloader, command=self.update_flash_display)
self.flashdisplaybootloader.pack(side=tk.TOP, anchor=tk.NW)
self.flashdisplay = tk.Frame(self.flashdispframe)
self.flashtext = tk.Text(self.flashdisplay, height=16, width=70, font=('Courier', 10))
self.flashscrollbar = tk.Scrollbar(self.flashdisplay, command=self.flashtext.yview)
self.flashtext.configure(yscrollcommand=self.flashscrollbar.set)
self.flashtext.pack(side=tk.LEFT)
self.flashscrollbar.pack(side=tk.RIGHT, fill=tk.Y)
self.flashdisplay.pack()
self.update_flash_display()
self.eepromdispframe = tk.LabelFrame(self.root, text='EEPROM Data', padx=5, pady=5)
self.eepromdispframe.pack(anchor=tk.NW, padx=10, pady=10)
# self.eeprombuttonframe = tk.Frame(self.eepromdispframe)
# self.eepromreadbutton = tk.Button(self.eeprombuttonframe, text='Read', command=self.read_eeprom)
# self.eepromreadbutton.pack(side=tk.LEFT, pady=5)
# self.eepromwritebutton = tk.Button(self.eeprombuttonframe, text='Write', command=self.write_eeprom)
# self.eepromwritebutton.pack(side=tk.LEFT, padx=10, pady=5)
# self.eeprombuttonframe.pack(side=tk.TOP, anchor=tk.NW)
self.eepromdisplay = tk.Frame(self.eepromdispframe)
self.eepromtext = tk.Text(self.eepromdisplay, height=8, width=70, font=('Courier', 10))
self.eepromscrollbar = tk.Scrollbar(self.eepromdisplay, command=self.eepromtext.yview)
self.eepromtext.configure(yscrollcommand=self.eepromscrollbar.set)
self.eepromtext.pack(side=tk.LEFT)
self.eepromscrollbar.pack(side=tk.RIGHT, fill=tk.Y)
self.eepromdisplay.pack()
self.update_eeprom_display()
self.connected = False
self.connect()
def bootloadermenu_disconnected(self):
self.bootloadermenu.entryconfig(0, state=tk.DISABLED)
self.bootloadermenu.entryconfig(1, state=tk.DISABLED)
self.bootloadermenu.entryconfig(2, state=tk.DISABLED)
self.bootloadermenu.entryconfig(3, state=tk.DISABLED)
self.bootloadermenu.entryconfig(4, state=tk.DISABLED)
self.bootloadermenu.entryconfig(6, state=tk.DISABLED)
self.bootloadermenu.entryconfig(7, state=tk.DISABLED)
self.bootloadermenu.entryconfig(12, state=tk.NORMAL)
self.bootloadermenu.entryconfig(13, state=tk.DISABLED)
self.readbutton.config(state=tk.DISABLED)
self.writebutton.config(state=tk.DISABLED)
self.verifybutton.config(state=tk.DISABLED)
self.erasebutton.config(state=tk.DISABLED)
self.blankchkbutton.config(state=tk.DISABLED)
self.connectbutton.config(state=tk.NORMAL)
self.disconnectbutton.config(state=tk.DISABLED)
# self.eepromreadbutton.config(state=tk.DISABLED)
# self.eepromwritebutton.config(state=tk.DISABLED)
def bootloadermenu_connected(self):
self.bootloadermenu.entryconfig(0, state=tk.NORMAL)
self.bootloadermenu.entryconfig(1, state=tk.NORMAL)
self.bootloadermenu.entryconfig(2, state=tk.NORMAL)
self.bootloadermenu.entryconfig(3, state=tk.NORMAL)
self.bootloadermenu.entryconfig(4, state=tk.NORMAL)
self.bootloadermenu.entryconfig(6, state=tk.NORMAL)
self.bootloadermenu.entryconfig(7, state=tk.NORMAL)
self.bootloadermenu.entryconfig(12, state=tk.DISABLED)
self.bootloadermenu.entryconfig(13, state=tk.NORMAL)
self.readbutton.config(state=tk.NORMAL)
self.writebutton.config(state=tk.NORMAL)
self.verifybutton.config(state=tk.NORMAL)
self.erasebutton.config(state=tk.NORMAL)
self.blankchkbutton.config(state=tk.NORMAL)
self.connectbutton.config(state=tk.DISABLED)
self.disconnectbutton.config(state=tk.NORMAL)
# self.eepromreadbutton.config(state=tk.NORMAL)
# self.eepromwritebutton.config(state=tk.NORMAL)
def display_message(self, message, clear_display = True):
self.statusdisplay.config(state=tk.NORMAL)
if clear_display==True:
self.statusdisplay.delete(1.0, tk.END)
self.statusdisplay.config(background='#71FF71')
self.statusdisplay.insert(tk.END, message)
self.statusdisplay.config(state=tk.DISABLED)
self.statusdisplay.update()
def display_warning(self, warning, clear_display = True):
self.statusdisplay.config(state=tk.NORMAL)
if clear_display==True:
self.statusdisplay.delete(1.0, tk.END)
self.statusdisplay.config(background='#FFFF71')
self.statusdisplay.insert(tk.END, warning)
self.statusdisplay.config(state=tk.DISABLED)
self.statusdisplay.update()
def display_error(self, error, clear_display = True):
self.statusdisplay.config(state=tk.NORMAL)
if clear_display==True:
self.statusdisplay.delete(1.0, tk.END)
self.statusdisplay.config(background='#FF7171')
self.statusdisplay.insert(tk.END, error)
self.statusdisplay.config(state=tk.DISABLED)
self.statusdisplay.update()
def exit(self):
sys.exit(0)
def write_device(self):
self.display_warning('Erasing program memory')
for address in range(0x0B00, 0x6000, 64):
self.bootloader.erase_flash(address)
if (address%512)==0:
self.display_warning('.', False)
self.display_warning('Writing program memory')
for address in range(0x0B00, 0x6000, 32):
bytes = []
for i in range(32):
bytes.append(self.flash[address+i])
for i in range(32):
if bytes[i]!=0xFF:
break
else:
continue
self.bootloader.write_flash(address, bytes)
if (address%512)==0:
self.display_warning('.', False)
self.display_warning('\nWriting data EEPROM...', False)
for address in range(0x100):
self.bootloader.write_eeprom(address, [self.eeprom[address]])
if self.verify_on_write.get()==1:
if self.verify()==0:
self.display_message('Write completed successfully.')
else:
self.display_warning('Write completed, but not verified.')
def read_device(self):
self.display_warning('Reading program memory')
for address in range(0x0000, 0x6000, 64):
bytes = self.bootloader.read_flash(address, 64)
for j in range(len(bytes)):
self.flash[address+j] = bytes[j]
if (address%512)==0:
self.display_warning('.', False)
self.display_warning('\nReading data EEPROM...', False)
for address in range(0x0000, 0x0100, 64):
bytes = self.bootloader.read_eeprom(address, 64)
for j in range(len(bytes)):
self.eeprom[address+j] = bytes[j]
self.display_message('Read device completed successfully.')
self.update_flash_display()
self.update_eeprom_display()
def verify(self):
self.display_warning('Verifying program memory')
for address in range(0x0B00, 0x6000, 64):
if (address%512)==0:
self.display_warning('.', False)
bytes = self.bootloader.read_flash(address, 64)
for i in range(64):
if bytes[i]!=self.flash[address+i]:
break
else:
continue
self.display_error('Verification failed.\nRead 0x%02X at location 0x%04X in program memory, expecting 0x%02X.' % (bytes[i], address+i, self.flash[address+i]))
return -1
self.display_warning('\nVerifying data EEPROM...', False)
for address in range(0x0000, 0x0100, 64):
bytes = self.bootloader.read_eeprom(address, 64)
for i in range(64):
if bytes[i]!=self.eeprom[address+i]:
break
else:
continue
self.display_error('Verification failed.\nRead 0x%02X at location 0x%04X in data EEPROM, expecting 0x%02X.' % (bytes[i], address+i, self.eeprom[address+i]))
return -1
self.display_message('Verification succeeded.')
return 0
def erase(self):
self.display_warning('Erasing program memory')
for address in range(0x0B00, 0x6000, 64):
self.bootloader.erase_flash(address)
if (address%512)==0:
self.display_warning('.', False)
self.display_warning('\nErasing data EEPROM...', False)
for address in range(0x100):
self.bootloader.write_eeprom(address, [0xFF])
self.display_message('Device erased sucessfully.')
if self.clear_buffers_on_erase.get()==1:
self.clear_flash()
self.clear_eeprom()
self.update_flash_display()
self.update_eeprom_display()
def blank_check(self):
self.display_warning('Checking program memory')
for address in range(0x0B00, 0x6000, 64):
if (address%512)==0:
self.display_warning('.', False)
bytes = self.bootloader.read_flash(address, 64)
for i in range(64):
if bytes[i]!=0xFF:
break
else:
continue
self.display_error('Device is not blank.\nRead 0x%02X at location 0x%04X in program memory.' % (bytes[i], address+i))
return
self.display_warning('\nChecking data EEPROM...', False)
for address in range(0x0000, 0x0100, 64):
bytes = self.bootloader.read_eeprom(address, 64)
for i in range(64):
if bytes[i]!=0xFF:
break
else:
continue
self.display_error('Device is not blank.\nRead 0x%02X at location 0x%04X in data EEPROM.' % (bytes[i], address+i))
return
self.display_message('Device is blank.')
def write_eeprom(self):
self.display_warning('Writing data EEPROM...')
for address in range(0x100):
self.bootloader.write_eeprom(address, [self.eeprom[address]])
if self.verify_on_write.get()==1:
self.display_warning('Verifying data EEPROM...')
for address in range(0x0000, 0x0100, 64):
bytes = self.bootloader.read_eeprom(address, 64)
for i in range(64):
if bytes[i]!=self.eeprom[address+i]:
break
else:
continue
self.display_error('Verification failed.\nRead 0x%02X at location 0x%04X in data EEPROM, expecting 0x%02X.' % (bytes[i], address+i, self.eeprom[address+i]))
return
self.display_message('Write data EEPROM succeeded.')
else:
self.display_warning('Write data EEPROM compleded, but not verified.')
def read_eeprom(self):
self.display_warning('Reading data EEPROM...')
for address in range(0x0000, 0x0100, 64):
bytes = self.bootloader.read_eeprom(address, 64)
for j in range(len(bytes)):
self.eeprom[address+j] = bytes[j]
self.display_message('Read data EEPROM completed successfully.')
self.update_eeprom_display()
def connect(self):
self.bootloader = bootloader.bootloader()
if self.bootloader.dev>=0:
self.connected = True
self.display_message('Connected to a USB bootloader device.')
self.bootloadermenu_connected()
else:
self.connected = False
self.display_error('Could not connect to a USB bootloader device.\nPlease connect one and then select Bootloader > Connect to proceed.')
self.bootloadermenu_disconnected()
def disconnect(self):
self.bootloader.start_user()
self.bootloader.close()
self.connected = False
self.bootloadermenu_disconnected()
self.display_message('Disconnected from USB bootloader device.\nPush button to start user code.')
def doitall(self):
self.connect()
if self.connected:
self.import_hex(True)
self.write_device()
self.disconnect()
def clear_flash(self):
for i in range(0x6000):
self.flash[i] = 0xFF
def clear_eeprom(self):
for i in range(0x100):
self.eeprom[i] = 0xFF
def update_flash_display(self):
self.flashtext.config(state=tk.NORMAL)
self.flashtext.delete(1.0, tk.END)
if self.display_bootloader.get()==1:
start = 0x0000
else:
start = 0x0B00
first = True
for address in range(start, 0x6000, 16):
if first==True:
first = False
line = ''
else:
line = '\n'
line = line + ('%04X: ' % address)
for i in range(16):
line = line + ('%02X ' % self.flash[address+i])
for i in range(16):
if (self.flash[address+i]>=32) and (self.flash[address+i]<127):
line = line + ('%c' % chr(self.flash[address+i]))
else:
line = line + '.'
self.flashtext.insert(tk.END, line)
self.flashtext.config(state=tk.DISABLED)
def update_eeprom_display(self):
self.eepromtext.config(state=tk.NORMAL)
self.eepromtext.delete(1.0, tk.END)
first = True
for address in range(0x00, 0x100, 16):
if first==True:
first = False
line = ''
else:
line = '\n'
line = line + ('%04X: ' % address)
for i in range(16):
line = line + ('%02X ' % self.eeprom[address+i])
for i in range(16):
if (self.eeprom[address+i]>=32) and (self.eeprom[address+i]<127):
line = line + ('%c' % chr(self.eeprom[address+i]))
else:
line = line + '.'
self.eepromtext.insert(tk.END, line)
self.eepromtext.config(state=tk.DISABLED)
def import_hex(self, usedefault=False):
filename=''
if ((not usedefault) or (not self.importingfile) or self.importingfile==''):
filename = tkFileDialog.askopenfilename(parent=self.root, title='Import Hex File', defaultextension='.hex', filetypes=[('HEX file', '*.hex'), ('All files', '*')])
self.importingfile=filename
else:
filename =self.importingfile
print filename
if filename=='':
print "import quitting"
return
hexfile = open(filename, 'r')
self.clear_flash()
eeprom_data_seen = False
address_high = 0
for line in hexfile:
line = line.strip('\n')
byte_count = int(line[1:3], 16)
address_low = int(line[3:7], 16)
record_type = int(line[7:9], 16)
if record_type==0:
address = (address_high<<16)+address_low
for i in range(byte_count):
if (address>=0) and (address<0x2A):
self.flash[address+0xB00] = int(line[9+2*i:11+2*i], 16)
elif (address>=0xB00) and (address<0x6000):
self.flash[address] = int(line[9+2*i:11+2*i], 16)
elif (address>=0xF00000) and (address<0xF00100):
if eeprom_data_seen==False:
eeprom_data_seen = True
self.clear_eeprom()
self.eeprom[address&0xFF] = int(line[9+2*i:11+2*i], 16)
address = address+1
elif record_type==4:
address_high = int(line[9:13], 16)
hexfile.close()
self.update_flash_display()
self.update_eeprom_display()
def export_hex(self):
filename = tkFileDialog.asksaveasfilename(parent=self.root, title='Export Hex File', defaultextension='.hex', filetypes=[('HEX file', '*.hex'), ('All files', '*')])
if filename=='':
return
hexfile = open(filename, 'w')
hexfile.write(':020000040000FA\n')
if self.write_bootloader_on_export.get()==1:
for address in range(0x0000, 0x0B00, 16):
for i in range(15, -1, -1):
if self.flash[address+i]!=0xFF:
end = i
break
else:
continue
for i in range(16):
if self.flash[address+i]!=0xFF:
start = i
break
line = ':%02X%04X00' % (end-start+1, address+start)
checksum = (end-start+1) + ((address+start)>>8) + ((address+start)&0xFF)
for i in range(start, end+1):
line = line + '%02X' % self.flash[address+i]
checksum = checksum + self.flash[address+i]
line = line + '%02X\n' % (0x100-(checksum&0xFF))
hexfile.write(line)
for address in range(0x0B00, 0x6000, 16):
for i in range(15, -1, -1):
if self.flash[address+i]!=0xFF:
end = i
break
else:
continue
for i in range(16):
if self.flash[address+i]!=0xFF:
start = i
break
line = ':%02X%04X00' % (end-start+1, address+start)
checksum = (end-start+1) + ((address+start)>>8) + ((address+start)&0xFF)
for i in range(start, end+1):
line = line + '%02X' % self.flash[address+i]
checksum = checksum + self.flash[address+i]
line = line + '%02X\n' % (0x100-(checksum&0xFF))
hexfile.write(line)
if self.write_eeprom_on_export.get()==1:
hexfile.write(':0200000400F00A\n')
for address in range(0x00, 0x100, 16):
for i in range(15, -1, -1):
if self.eeprom[address+i]!=0xFF:
end = i
break
else:
continue
for i in range(16):
if self.eeprom[address+i]!=0xFF:
start = i
break
line = ':%02X%04X00' % (end-start+1, address+start)
checksum = (end-start+1) + ((address+start)>>8) + ((address+start)&0xFF)
for i in range(start, end+1):
line = line + '%02X' % self.eeprom[address+i]
checksum = checksum + self.eeprom[address+i]
line = line + '%02X\n' % (0x100-(checksum&0xFF))
hexfile.write(line)
hexfile.write(':00000001FF\n')
hexfile.close()
if __name__=='__main__':
boot = bootloadergui()
boot.root.mainloop()
| [
[
1,
0,
0.0039,
0.0019,
0,
0.66,
0,
688,
0,
2,
0,
0,
688,
0,
0
],
[
1,
0,
0.0058,
0.0019,
0,
0.66,
0.2,
368,
0,
1,
0,
0,
368,
0,
0
],
[
1,
0,
0.0077,
0.0019,
0,
0.6... | [
"import os, sys",
"import Tkinter as tk",
"import tkFileDialog",
"import bootloader",
"class bootloadergui:\n\n def __init__(self):\n self.flash = []\n self.importingfile=None\n for i in range(0x6000):\n self.flash.append(0xFF)",
" def __init__(self):\n self.fl... |
import ctypes
import sys
if len(sys.argv) != 2:
print "Usage: %s <duty>\n" % sys.argv[0]
sys.exit(-1)
duty = int(sys.argv[1])
if (duty < 0) or (duty > 255):
print "Illegal duty cycle (%d) specified.\n" % duty
sys.exit(-1)
SET_RA1 = 1
CLR_RA1 = 2
GET_RA2 = 3
SET_DUTY = 4
usb = ctypes.cdll.LoadLibrary('usb.dll')
usb.initialize()
buffer = ctypes.c_buffer(8)
dev = usb.open_device(0x6666, 0x0003, 0)
if dev<0:
print "No matching device found...\n"
else:
ret = usb.control_transfer(dev, 0x40, SET_DUTY, duty, 0, 0, buffer)
if ret<0:
print "Unable to send SET_DUTY vendor request.\n"
usb.close_device(dev)
| [
[
1,
0,
0.0667,
0.0333,
0,
0.66,
0,
182,
0,
1,
0,
0,
182,
0,
0
],
[
1,
0,
0.1,
0.0333,
0,
0.66,
0.0769,
509,
0,
1,
0,
0,
509,
0,
0
],
[
4,
0,
0.2,
0.1,
0,
0.66,
... | [
"import ctypes",
"import sys",
"if len(sys.argv) != 2:\n print(\"Usage: %s <duty>\\n\" % sys.argv[0])\n sys.exit(-1)",
" print(\"Usage: %s <duty>\\n\" % sys.argv[0])",
" sys.exit(-1)",
"duty = int(sys.argv[1])",
"if (duty < 0) or (duty > 255):\n print(\"Illegal duty cycle (%d) specified.\... |
import ctypes
SET_RA1 = 1
CLR_RA1 = 2
GET_RA2 = 3
SET_DUTY = 4
usb = ctypes.cdll.LoadLibrary('usb.dll')
usb.initialize()
buffer = ctypes.c_buffer(8)
dev = usb.open_device(0x6666, 0x0003, 0)
if dev<0:
print "No matching device found...\n"
else:
ret = usb.control_transfer(dev, 0x40, CLR_RA1, 0, 0, 0, buffer)
if ret<0:
print "Unable to send CLR_RA1 vendor request.\n"
usb.close_device(dev)
| [
[
1,
0,
0.0952,
0.0476,
0,
0.66,
0,
182,
0,
1,
0,
0,
182,
0,
0
],
[
14,
0,
0.1905,
0.0476,
0,
0.66,
0.1111,
109,
1,
0,
0,
0,
0,
1,
0
],
[
14,
0,
0.2381,
0.0476,
0,
... | [
"import ctypes",
"SET_RA1 = 1",
"CLR_RA1 = 2",
"GET_RA2 = 3",
"SET_DUTY = 4",
"usb = ctypes.cdll.LoadLibrary('usb.dll')",
"usb.initialize()",
"buffer = ctypes.c_buffer(8)",
"dev = usb.open_device(0x6666, 0x0003, 0)",
"if dev<0:\n print(\"No matching device found...\\n\")\nelse:\n ret = usb.c... |
"""Wrapper classes for use with tkinter.
This module provides the following classes:
Gui: a sublass of Tk that provides wrappers for most
of the widget-creating methods from Tk. The advantages of
these wrappers is that they use Python's optional argument capability
to provide appropriate default values, and that they combine widget
creation and packing into a single step. They also eliminate the need
to name the parent widget explicitly by keeping track of a current
frame and packing new objects into it.
GuiCanvas: a subclass of Canvas that provides wrappers for most of the
item-creating methods from Canvas. The advantages of the wrappers
are, again, that they use optional arguments to provide appropriate
defaults, and that they perform coordinate transformations.
Transform: an abstract class that provides basic methods inherited
by CanvasTransform and the other transforms.
CanvasTransform: a transformation that maps standard Cartesian
coordinates onto the 'graphics' coordinates used by Canvas objects.
Callable: the standard recipe from Python Cookbook for encapsulating
a funcation and its arguments in an object that can be used as a
callback.
Thread: a wrapper class for threading.Thread that improves the
interface.
Watcher: a workaround for the problem multithreaded programs have
handling signals, especially the SIGINT generated by a
KeyboardInterrupt.
The most important idea about this module is the idea of using
a stack of frames to avoid keeping track of parent widgets explicitly.
Copyright 2005 Allen B. Downey
This file contains wrapper classes I use with tkinter. It is
mostly for my own use; I don't support it, and it is not very
well documented.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see
http://www.gnu.org/licenses/gpl.html or write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA
"""
from math import *
from Tkinter import *
import threading, time, os, signal, sys, operator
class Thread(threading.Thread):
"""this is a wrapper for threading.Thread that improves
the syntax for creating and starting threads. See Appendix A
of The Little Book of Semaphores, http://greenteapress.com/semaphores/
"""
def __init__(self, target, *args):
threading.Thread.__init__(self, target=target, args=args)
self.start()
class Semaphore(threading._Semaphore):
"""this is a wrapper class that makes signal and wait
synonyms for acquire and release, and also makes signal
take an optional argument.
"""
wait = threading._Semaphore.acquire
def signal(self, n=1):
for i in range(n): self.release()
def value(self):
return self._Semaphore__value
def pairiter(seq):
"""return an iterator that yields consecutive pairs from seq"""
it = iter(seq)
while True:
yield [it.next(), it.next()]
def pair(seq):
"""return a list of consecutive pairs from seq"""
return [x for x in pairiter(seq)]
def flatten(seq):
return sum(seq, [])
# Gui provides wrappers for many of the methods in the Tk
# class; also, it keeps track of the current frame so that
# you can create new widgets without naming the parent frame
# explicitly.
def underride(d, **kwds):
"""Add kwds to the dictionary only if they are not already set"""
for key, val in kwds.iteritems():
if key not in d:
d[key] = val
def override(d, **kwds):
"""Add kwds to the dictionary even if they are already set"""
d.update(kwds)
class Gui(Tk):
def __init__(self, debug=False):
"""initialize the gui.
turning on debugging changes the behavior of Gui.fr so
that the nested frame structure is apparent
"""
Tk.__init__(self)
self.debug = debug
self.frames = [self] # the stack of nested frames
frame = property(lambda self: self.frames[-1])
def endfr(self):
"""end the current frame (and return it)"""
return self.frames.pop()
popfr = endfr
endgr = endfr
def pushfr(self, frame):
"""push a frame onto the frame stack"""
self.frames.append(frame)
def tl(self, **options):
"""make a return a top level window."""
return Toplevel(**options)
"""The following widget wrappers all invoke widget to
create and pack the new widget. The first four positional
arguments determine how the widget is packed. Some widgets
take additional positional arguments. In most cases, the
keyword arguments are passed as options to the widget
constructor.
The default pack arguments are
side=TOP, fill=NONE, expand=0, anchor=CENTER
Widgets that use these defaults can just pass along
args and options unmolested. Widgets (like fr and en)
that want different defaults have to roll the arguments
in with the other options and then underride them.
"""
argnames = ['side', 'fill', 'expand', 'anchor']
def fr(self, *args, **options):
"""make a return a frame.
As a side effect, the new frame becomes the current frame
"""
options.update(dict(zip(Gui.argnames,args)))
underride(options, fill=BOTH, expand=1)
if self.debug:
override(options, bd=5, relief=RIDGE)
# create the new frame and push it onto the stack
frame = self.widget(Frame, **options)
self.pushfr(frame)
return frame
def gr(self, cols, cweights=[1], rweights=[1], **options):
"""create a frame and switch to grid mode.
cols is the number of columns in the grid (no need to
specify the number of rows). cweight and rweight control
how the widgets expand if the frame expands (see colweights
and rowweights below). options are passed along to the frame
"""
fr = self.fr(**options)
fr.gridding = True
fr.cols = cols
fr.i = 0
fr.j = 0
self.colweights(cweights)
self.rowweights(rweights)
return fr
def colweights(self, weights):
"""attach weights to the columns of the current grid.
These weights control how the columns in the grid expand
when the grid expands. The default weight is 0, which
means that the column doesn't expand. If only one
column has a value, it gets all the extra space.
"""
for i, weight in enumerate(weights):
self.frame.columnconfigure(i, weight=weight)
def rowweights(self, weights):
"""attach weights to the rows of the current grid.
These weights control how the rows in the grid expand
when the grid expands. The default weight is 0, which
means that the row doesn't expand. If only one
row has a value, it gets all the extra space.
"""
for i, weight in enumerate(weights):
self.frame.rowconfigure(i, weight=weight)
def grid(self, widget, i=None, j=None, **options):
"""pack the given widget in the current grid.
By default, the widget is packed in the next available
space, but i and j can override.
"""
if i == None: i = self.frame.i
if j == None: j = self.frame.j
widget.grid(row=i, column=j, **options)
# increment j by 1, or by columnspan
# if the widget spans more than one column.
try:
incr = options['columnspan']
except KeyError:
incr = 1
self.frame.j += 1
if self.frame.j == self.frame.cols:
self.frame.j = 0
self.frame.i += 1
# entry
def en(self, *args, **options):
options.update(dict(zip(Gui.argnames,args)))
underride(options, fill=BOTH, expand=1)
text = options.pop('text', '')
en = self.widget(Entry, **options)
en.insert(0, text)
return en
# canvas
def ca(self, *args, **options):
underride(options, fill=BOTH, expand=1)
return self.widget(GuiCanvas, *args, **options)
# label
def la(self, *args, **options):
return self.widget(Label, *args, **options)
# button
def bu(self, *args, **options):
return self.widget(Button, *args, **options)
# menu button
def mb(self, *args, **options):
mb = self.widget(Menubutton, *args, **options)
mb.menu = Menu(mb, relief=SUNKEN)
mb['menu'] = mb.menu
return mb
# menu item
def mi(self, mb, label='', **options):
mb.menu.add_command(label=label, **options)
# text entry
def te(self, *args, **options):
return self.widget(Text, *args, **options)
# scrollbar
def sb(self, *args, **options):
return self.widget(Scrollbar, *args, **options)
class ScrollableText:
def __init__(self, gui,
*args, **options):
self.frame = gui.fr(*args, **options)
self.scrollbar = gui.sb(RIGHT, fill=Y)
self.text = gui.te(LEFT, wrap=WORD,
yscrollcommand=self.scrollbar.set)
self.scrollbar.config(command=self.text.yview)
gui.endfr()
# scrollable text
# returns a ScrollableText object that contains a frame, a
# text entry and a scrollbar.
# note: the options provided to st apply to the frame only;
# if you want to configure the other widgets, you have to do
# it after invoking st
def st(self, *args, **options):
return self.ScrollableText(self, *args, **options)
class ScrollableCanvas:
def __init__(self, gui, width=500, height=500, **options):
self.grid = gui.gr(2, **options)
self.canvas = gui.ca(width=width, height=height, bg='white')
self.yb = self.sb(command=self.canvas.yview, sticky=N+S)
self.xb = self.sb(command=self.canvas.xview, orient=HORIZONTAL,
sticky=E+W)
self.canvas.configure(xscrollcommand=self.xb.set,
yscrollcommand=self.yb.set)
gui.endgr()
def sc(self, *args, **options):
return self.ScrollableCanvas(self, *args, **options)
def widget(self, constructor, *args, **options):
"""this is the mother of all widget constructors.
the constructor argument is the function that will
be called to build the new widget. args is rolled
into options, and then options is split into widget
option, pack options and grid options
"""
options.update(dict(zip(Gui.argnames,args)))
widopt, packopt, gridopt = split_options(options)
# make the widget and either pack or grid it
widget = constructor(self.frame, **widopt)
if hasattr(self.frame, 'gridding'):
self.grid(widget, **gridopt)
else:
widget.pack(**packopt)
return widget
def pop_options(options, names):
"""remove names from options and return a new dictionary
that contains the names and values from options
"""
new = {}
for name in names:
if name in options:
new[name] = options.pop(name)
return new
def split_options(options):
"""take a dictionary of options and split it into pack
options, grid options, and anything left is assumed to
be a widget option
"""
packnames = ['side', 'fill', 'expand', 'anchor']
gridnames = ['column', 'columnspan', 'row', 'rowspan',
'padx', 'pady', 'ipadx', 'ipady', 'sticky']
packopts = pop_options(options, packnames)
gridopts = pop_options(options, gridnames)
return options, packopts, gridopts
class BBox(list):
__slots__ = ()
"""a bounding box is a list of coordinates, where each
coordinate is a list of numbers.
Creating a new bounding box makes a _shallow_ copy of
the list of coordinates. For a deep copy, use copy().
"""
def copy(self):
t = [Pos(coord) for coord in bbox]
return BBox(t)
# top, bottom, left, and right can be accessed as attributes
def setleft(bbox, val): bbox[0][0] = val
def settop(bbox, val): bbox[0][1] = val
def setright(bbox, val): bbox[1][0] = val
def setbottom(bbox, val): bbox[1][1] = val
left = property(lambda bbox: bbox[0][0], setleft)
top = property(lambda bbox: bbox[0][1], settop)
right = property(lambda bbox: bbox[1][0], setright)
bottom = property(lambda bbox: bbox[1][1], setbottom)
def width(bbox): return bbox.right - bbox.left
def height(bbox): return bbox.bottom - bbox.top
def upperleft(bbox): return Pos(bbox[0])
def lowerright(bbox): return Pos(bbox[1])
def midright(bbox):
x = bbox.right
y = (bbox.top + bbox.bottom) / 2.0
return Pos([x, y])
def midleft(bbox):
x = bbox.left
y = (bbox.top + bbox.bottom) / 2.0
return Pos([x, y])
def offset(bbox, pos):
"""return the vector between the upper-left corner of bbox and pos"""
return Pos([pos[0]-bbox.left, pos[1]-bbox.top])
def pos(bbox, offset):
"""return the position at the given offset from bbox upper-left"""
return Pos([offset[0]+bbox.left, offset[1]+bbox.top])
def flatten(bbox):
"""return a list of four coordinates"""
return bbox[0] + bbox[1]
class Pos(list):
__slots__ = ()
"""a position is a list of coordinates.
Because Pos inherits __init__ from list, it makes a copy
of the argument to the constructor.
"""
copy = lambda pos: Pos(pos)
# x and y can be accessed as attributes
def setx(pos, val): pos[0] = val
def sety(pos, val): pos[1] = val
x = property(lambda pos: pos[0], setx)
y = property(lambda pos: pos[1], sety)
class GuiCanvas(Canvas):
"""this is a wrapper for the Canvas provided by tkinter.
The primary difference is that it supports coordinate
transformations, the most common of which is the CanvasTranform,
which make canvas coordinates Cartesian (origin in the middle,
positive y axis going up).
It also provides methods like circle that provide a
nice interface to the underlying canvas methods.
"""
def __init__(self, w, transforms=None, **options):
Canvas.__init__(self, w, **options)
# the default transform is a standard CanvasTransform
if transforms == None:
self.transforms = [CanvasTransform(self)]
else:
self.transforms = transforms
# the following properties make it possbile to access
# the width and height of the canvas as if they were attributes
width = property(lambda self: int(self['width']))
height = property(lambda self: int(self['height']))
def add_transform(self, transform, pos=None):
if pos == None:
self.transforms.append(transform)
else:
self.transforms.insert(pos, transform)
def trans(self, coords):
"""apply each of the transforms for this canvas, in order"""
for trans in self.transforms:
coords = trans.trans_list(coords)
return coords
def invert(self, coords):
t = self.transforms[:]
t.reverse()
for trans in t:
coords = trans.invert_list(coords)
return coords
def bbox(self, item):
if isinstance(item, list):
item = item[0]
bbox = Canvas.bbox(self, item)
if bbox == None: return bbox
bbox = pair(bbox)
bbox = self.invert(bbox)
return BBox(bbox)
def coords(self, item, coords=None):
if coords:
coords = self.trans(coords)
coords = flatten(coords)
Canvas.coords(self, item, *coords)
else:
"have to get the coordinates and invert them"
def move(self, item, dx=0, dy=0):
coords = self.trans([[dx, dy]])
pos = coords[0]
Canvas.move(self, item, pos[0], pos[1])
def flipx(self, item):
coords = Canvas.coords(self, item)
for i in range(0, len(coords), 2):
coords[i] *= -1
Canvas.coords(self, item, *coords)
def circle(self, x, y, r, fill='', **options):
options['fill'] = fill
coords = self.trans([[x-r, y-r], [x+r, y+r]])
tag = self.create_oval(coords, options)
return tag
def oval(self, coords, fill='', **options):
options['fill'] = fill
return self.create_oval(self.trans(coords), options)
def rectangle(self, coords, fill='', **options):
options['fill'] = fill
return self.create_rectangle(self.trans(coords), options)
def line(self, coords, fill='black', **options):
options['fill'] = fill
tag = self.create_line(self.trans(coords), options)
return tag
def polygon(self, coords, fill='', **options):
options['fill'] = fill
return self.create_polygon(self.trans(coords), options)
def text(self, coord, text='', fill='black', **options):
options['text'] = text
options['fill'] = fill
return self.create_text(self.trans([coord]), options)
def image(self, coord, image, **options):
options['image'] = image
return self.create_image(self.trans([coord]), options)
def dump(self, filename='canvas.eps'):
bbox = Canvas.bbox(self, ALL)
x, y, width, height = bbox
width -= x
height -= y
ps = self.postscript(x=x, y=y, width=width, height=height)
fp = open(filename, 'w')
fp.write(ps)
fp.close()
class Transform:
"""the parent class of transforms, Transform provides methods
for transforming lists of coordinates. Subclasses of Transform
are supposed to implement trans() and invert()
"""
def trans_list(self, points, func=None):
# the default func is trans; invert_list overrides this
# with invert
if func == None:
func = self.trans
if isinstance(points[0], (list, tuple)):
return [Pos(func(p)) for p in points]
else:
return Pos(func(points))
def invert_list(self, points):
return self.trans_list(points, self.invert)
class CanvasTransform(Transform):
"""under a CanvasTransform, the origin is in the middle of
the canvas, the positive y-axis is up, and the coordinate
[1, 1] maps to the point specified by scale.
"""
def __init__(self, ca, scale=[1, 1]):
self.ca = ca
self.scale = scale
def trans(self, p):
x = p[0] * self.scale[0] + self.ca.width/2
y = -p[1] * self.scale[1] + self.ca.height/2
return [x, y]
class ScaleTransform(Transform):
"""scale the coordinate system by the given factors.
The origin is half a unit from the upper-left corner.
"""
def __init__(self, scale=[1, 1]):
self.scale = scale
def trans(self, p):
x = p[0] * self.scale[0]
y = p[1] * self.scale[1]
return [x, y]
def invert(self, p):
x = p[0] / self.scale[0]
y = p[1] / self.scale[1]
return [x, y]
class RotateTransform(Transform):
"""rotate the coordinate system theta degrees clockwise
"""
def __init__(self, theta):
self.theta = theta
def rotate(self, p, theta):
s = sin(theta)
c = cos(theta)
x = c * p[0] + s * p[1]
y = -s * p[0] + c * p[1]
return [x, y]
def trans(self, p):
return self.rotate(p, self.theta)
def invert(self, p):
return self.rotate(p, -self.theta)
class SwirlTransform(RotateTransform):
def trans(self, p):
d = sqrt(p[0]*p[0] + p[1]*p[1])
return self.rotate(p, self.theta*d)
def invert(self, p):
d = sqrt(p[0]*p[0] + p[1]*p[1])
return self.rotate(p, -self.theta*d)
class Callable:
"""this class is used to wrap a function and its arguments
into an object that can be passed as a callback parameter
and invoked later. It is from the Python Cookbook 9.1, page 302
"""
def __init__(self, func, *args, **kwds):
self.func = func
self.args = args
self.kwds = kwds
def __call__(self):
return apply(self.func, self.args, self.kwds)
def __str__(self):
return self.func.__name__
class Watcher:
"""this class solves two problems with multithreaded
programs in Python, (1) a signal might be delivered
to any thread (which is just a malfeature) and (2) if
the thread that gets the signal is waiting, the signal
is ignored (which is a bug).
The watcher is a concurrent process (not thread) that
waits for a signal and the process that contains the
threads. See Appendix A of The Little Book of Semaphores.
I have only tested this on Linux. I would expect it to
work on the Macintosh and not work on Windows.
"""
def __init__(self):
""" Creates a child thread, which returns. The parent
thread waits for a KeyboardInterrupt and then kills
the child thread.
"""
self.child = os.fork()
if self.child == 0:
return
else:
self.watch()
def watch(self):
try:
os.wait()
except KeyboardInterrupt:
# I put the capital B in KeyBoardInterrupt so I can
# tell when the Watcher gets the SIGINT
print 'KeyBoardInterrupt'
self.kill()
sys.exit()
def kill(self):
try:
os.kill(self.child, signal.SIGKILL)
except OSError: pass
def tk_example():
tk = Tk()
def hello():
ca.create_text(100, 100, text='hello', fill='blue')
ca = Canvas(tk, bg='white')
ca.pack(side=LEFT)
fr = Frame(tk)
fr.pack(side=LEFT)
bu1 = Button(fr, text='Hello', command=hello)
bu1.pack()
bu2 = Button(fr, text='Quit', command=tk.quit)
bu2.pack()
tk.mainloop()
def gui_example():
gui = Gui()
ca = gui.ca(LEFT, bg='white')
def hello():
ca.text([0,0], 'hello', 'blue')
gui.fr(LEFT)
gui.bu(text='Hello', command=hello)
gui.bu(text='Quit', command=gui.quit)
gui.endfr()
gui.mainloop()
def main(script, n=0, *args):
if n == 0:
tk_example()
else:
gui_example()
if __name__ == '__main__':
main(*sys.argv)
| [
[
8,
0,
0.0433,
0.0852,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0907,
0.0014,
0,
0.66,
0.037,
526,
0,
1,
0,
0,
526,
0,
0
],
[
1,
0,
0.092,
0.0014,
0,
0.66,
... | [
"\"\"\"Wrapper classes for use with tkinter.\n\nThis module provides the following classes:\n\nGui: a sublass of Tk that provides wrappers for most\nof the widget-creating methods from Tk. The advantages of\nthese wrappers is that they use Python's optional argument capability\nto provide appropriate default value... |
from Tkinter import *
import math
import ctypes
SET_SERVO = 1
KILL_CREEPA = 2
TOWERTIMEARRAY = 3
KILL_CREEPB = 4
GET_RA0 = 5
FIRING = 6
GET_TOWERTYPE = 7
GET_TOWERPOS = 8
GET_TICK = 9
#[(32, 16, math.pi/4),(29, 24, 13*math.pi/12),(29, 33, math.pi/24),(9, 34, 23*math.pi/24),(17, 21.5, 13*math.pi/12),(9, 12, -math.pi/4)]
usb = ctypes.cdll.LoadLibrary('usb.dll')
usb.initialize()
buffer = ctypes.c_buffer(8)
def rad_to_delay(angle): #0 - 2pi --> 45 - 135 = ~240deg
angle = angle%(2*math.pi)
if 0 < angle < math.pi/3:
return 55*angle + 80
if math.pi/3 < angle <= math.pi/2:
return 135
if math.pi/2 < angle < 2*math.pi/3:
return 25
if 2*math.pi/3 < angle < 2*math.pi:
return 55*(angle-240) + 25
def set_servo_callback(value):
usb.control_transfer(dev, 0x40, SET_SERVO, int(value), 0, 0, buffer)
def update_clock():
usb.control_transfer(dev, 0xC0, GET_TICK, 0, 0, 1, buffer)
tick = ord(buffer[0])
print tick
update_clock()
root.after(50, update_status(tick))
def update_creep():
usb.control_transfer(dev, 0xC0, GET_CREEP, 0, 0, 1, buffer)
creep = ord(buffer[0])
print tick
root.after(50, update_status(tick))
def update_status(value):
status.configure(text = 'RA0 is currently %d.' % value)
root.after(50, update_status)
def update_towertype():
usb.control_transfer(dev, 0xC0, GET_TOWERTYPE, 0, 0, 1, buffer)
towertype = [0]
for i in range(len(buffer)):
towertype[i] = ord(buffer[i])
print towertype
root.after(50, update_status)
def get_towerpos():
usb.control_transfer(dev, 0xC0, GET_TOWERPOS, 0, 0, 1, buffer)
towerbyte = ord(buffer[0])
print towerbyte
active_tower = [0,0,0,0,0,0] #1 = 128, 2 = 64, 3 = 32, 4 = 16, 5 = 8, 6 = 4
for i in range(6):
if towerbyte >= 2**(7-i):
active_tower[i] = 1
towerbyte -= 2**(7-i)
print active_tower
def kill(value):
print "kill_spot is %s" %value
if value < 8:
usb.control_transfer(dev, 0x40, KILL_CREEPA, int(value), 0, 0, buffer)
else:
usb.control_transfer(dev, 0x40, KILL_CREEPB, int(value-8), 0, 0, buffer)
tower_delays = ctypes.c_buffer(64)
global n
n = 45
def update_tower_time():
global n
n += 5
firing_array = [0,0,0,1,0,1,0,0]
time_list = []
for i in range(8):
time_list.append(n)
update_towers(time_list, firing_array)
def update_towers(time_list, firing_array):
firing_byte = 0
for j in range(len(firing_array)):
firing_byte += (2**j)*firing_array[7-j]
for i in range (8):
val = int(70.*int(time_list[i])/256+45)
print val
tower_delays[i] = chr(val)
usb.control_transfer(dev, 0x40, TOWERTIMEARRAY, 0, 0, len(tower_delays), tower_delays)
usb.control_transfer(dev, 0xC0, FIRING, firing_byte, 0, 1, buffer)
root = Tk()
root.title('Lab 3 GUI')
fm = Frame(root)
#Button(fm, text = 'SET_RA1', command = set_ra1_callback).pack(side = LEFT)
#Button(fm, text = 'CLR_RA1', command = clr_ra1_callback).pack(side = LEFT)
# Button(fm, text = 'GET_RA2', command = get_ra2_callback).pack(side = LEFT)
Button(fm, text = 0, command = lambda : kill(0)).pack(side = LEFT)
Button(fm, text = 1, command = lambda : kill(1)).pack(side = LEFT)
Button(fm, text = 2, command = lambda : kill(2)).pack(side = LEFT)
Button(fm, text = 3, command = lambda : kill(3)).pack(side = LEFT)
Button(fm, text = 4, command = lambda : kill(4)).pack(side = LEFT)
Button(fm, text = 5, command = lambda : kill(5)).pack(side = LEFT)
Button(fm, text = 6, command = lambda : kill(6)).pack(side = LEFT)
Button(fm, text = 7, command = lambda : kill(7)).pack(side = LEFT)
Button(fm, text = 8, command = lambda : kill(8)).pack(side = LEFT)
Button(fm, text = 9, command = lambda : kill(9)).pack(side = LEFT)
Button(fm, text = 10, command = lambda : kill(10)).pack(side = LEFT)
Button(fm, text = 11, command = lambda : kill(11)).pack(side = LEFT)
Button(fm, text = 12, command = lambda : kill(12)).pack(side = LEFT)
Button(fm, text = 13, command = lambda : kill(13)).pack(side = LEFT)
Button(fm, text = 14, command = lambda : kill(14)).pack(side = LEFT)
Button(fm, text = 15, command = lambda : kill(15)).pack(side = LEFT)
fm.pack(side = TOP)
##servoslider = Scale(root, from_ = 0, to = 255, orient = HORIZONTAL, showvalue = FALSE, command = update_tower_time)
##servoslider.set(128)
##servoslider.pack(side = TOP)
fr=Frame(root)
Button(fr, text = 'update_clock', command = update_clock).pack(side = LEFT)
Button(fr, text = "update_towers", command = update_tower_time).pack(side = LEFT)
Button(fr, text = 'get_towerpos', command = get_towerpos).pack(side = LEFT)
fr.pack(side = TOP)
status = Label(root, text = 'creep_checkin is currently ?.')
status.pack(side = TOP)
dev = usb.open_device(0x6666, 0x0003, 0)
if dev<0:
print "No matching device found...\n"
else:
ret = usb.control_transfer(dev, 0x00, 0x09, 1, 0, 0, buffer)
if ret<0:
print "Unable to send SET_CONFIGURATION standard request.\n"
#root.after(50, update_status)
root.mainloop()
usb.close_device(dev)
| [
[
1,
0,
0.0126,
0.0063,
0,
0.66,
0,
368,
0,
1,
0,
0,
368,
0,
0
],
[
1,
0,
0.0189,
0.0063,
0,
0.66,
0.0182,
526,
0,
1,
0,
0,
526,
0,
0
],
[
1,
0,
0.0252,
0.0063,
0,
... | [
"from Tkinter import *",
"import math",
"import ctypes",
"SET_SERVO = 1",
"KILL_CREEPA = 2",
"TOWERTIMEARRAY = 3",
"KILL_CREEPB = 4",
"GET_RA0 = 5",
"FIRING = 6",
"GET_TOWERTYPE = 7",
"GET_TOWERPOS = 8",
"GET_TICK = 9",
"usb = ctypes.cdll.LoadLibrary('usb.dll')",
"usb.initialize()",
"buf... |
from Tkinter import *
import ctypes
SET_SERVO = 1
KILL_CREEPA = 2
KILL_CREEPB = 3
SET_DUTY = 4
global servospot
servospot=0
print "set servospot"
opponentpin = []
playerpin = []
usb = ctypes.cdll.LoadLibrary('usb.dll')
usb.initialize()
print "hey o"
buffer = ctypes.c_buffer(8)
player=True
dev = usb.open_device(0x6666, 0x0003, 0)
##def set_ra1_callback():
## usb.control_transfer(dev, 0x40, SET_RA1, 0, 0, 0, buffer)
##
##def clr_ra1_callback():
## usb.control_transfer(dev, 0x40, CLR_RA1, 0, 0, 0, buffer)
# def get_ra2_callback():
# usb.control_transfer(dev, 0xC0, GET_RA2, 0, 0, 1, buffer)
# status.configure(text = 'RA2 is currently %d.' % ord(buffer[0]))
def set_duty_callback(value):
usb.control_transfer(dev, 0x40, SET_SERVO, int(value), 0, 0, buffer)
def set_callback(pin):
global player
if not (pin in opponentpin or pin in playerpin):
usb.control_transfer(dev, 0x40, pin, 0, 0, 0, buffer)
img=PhotoImage(file=['X','O'][int(player)]+'.gif')
buttons[pin].configure(image=img)
buttons[pin].image=img
if player:
opponentpin.append(pin)
else:
playerpin.append(pin)
player = not player
def make_callback(pin):
return lambda: set_callback(pin)
def update_status():
global servospot
usb.control_transfer(dev, 0xC0, servospot, 0, 0, 1, buffer)
status.configure(text = 'Servo at %d' % servospot)
root.after(50, update_status)
servospot+=1
if servospot>255:
servospot=0
def kill_spot_number(kill_spot):
usb.control_transfer(dev, 0x40, kill_spot, 0, 0, 0, buffer)
##def clear_board():
## usb.control_transfer(dev, 0x40, 9, 0, 0, 0, buffer)
def make_updater(servospot=0):
def update():
usb.control_transfer(dev, 0xC0, servospot, 0, 0, 1, buffer)
status.configure(text = 'Servo at %d' % servospot)
servospot+=1
if servospot>255:
servospot=0
print servospot
root.after(1, make_updater(servospot))
return update
root = Tk()
root.title('Kill Tower GUI')
fm = Frame(root)
##b=Button(root, width=20,text="First").grid(row=0)
##b=Button(root, width=20,text="Second").grid(row=1)
##b=Button(root, width=18,text="PAUL BOOTH").grid(row=0, column=1)
##b=Button(root, width=19,text="Blair's hair").grid(row=7, column=8)
buttons=[]
##img=PhotoImage(file='blank.GIF')
##for i in xrange(9):
## print img
## b=Button(root, width=64,height=64, text=' ', image=img,command = make_callback(i))
## b.image=img
## b.grid(row=i/3, column=i%3)
## buttons.append(b)
#b.pack(side = LEFT, padx=2, pady=2)
#Button(fm, text = ' ', command = clr_ra1_callback).pack(side = LEFT)
# Button(fm, text = 'GET_RA2', command = get_ra2_callback).pack(side = LEFT)
dutyslider = Scale(root, from_ = 0, to = 255, orient = HORIZONTAL, showvalue = FALSE, command = set_duty_callback)
dutyslider.set(128)
dutyslider.pack(side = TOP)
for i in range(7):
b = Button(fm, text = 'button', command = kill_spot_number(i)).pack(side = LEFT)
##status = Label(root, text = 'Get Ready for FUN.')
##status.grid(row=3,column=0,columnspan=3)
##b=Button(root, text = 'clear board', command = clear_board);
##b.grid(row=4,column=0,columnspan=3)
#status.pack(side = TOP)
fm.pack(side = TOP)
dev = usb.open_device(0x6666, 0x0003, 0)
if dev<0:
print "No matching device found...\n"
else:
ret = usb.control_transfer(dev, 0x00, 0x09, 1, 0, 0, buffer)
if ret<0:
print "Unable to send SET_CONFIGURATION standard request.\n"
clear_board()
root.after(30, update_status)
root.mainloop()
usb.close_device(dev)
| [
[
1,
0,
0.0155,
0.0078,
0,
0.66,
0,
368,
0,
1,
0,
0,
368,
0,
0
],
[
1,
0,
0.0233,
0.0078,
0,
0.66,
0.0323,
182,
0,
1,
0,
0,
182,
0,
0
],
[
14,
0,
0.0388,
0.0078,
0,
... | [
"from Tkinter import *",
"import ctypes",
"SET_SERVO = 1",
"KILL_CREEPA = 2",
"KILL_CREEPB = 3",
"SET_DUTY = 4",
"servospot=0",
"print(\"set servospot\")",
"opponentpin = []",
"playerpin = []",
"usb = ctypes.cdll.LoadLibrary('usb.dll')",
"usb.initialize()",
"print(\"hey o\")",
"buffer = ct... |
import ctypes
SET_RA1 = 1
CLR_RA1 = 2
GET_RA2 = 3
SET_DUTY = 4
usb = ctypes.cdll.LoadLibrary('usb.dll')
usb.initialize()
buffer = ctypes.c_buffer(8)
dev = usb.open_device(0x6666, 0x0003, 0)
if dev<0:
print "No matching device found...\n"
else:
ret = usb.control_transfer(dev, 0xC0, GET_RA2, 0, 0, 1, buffer)
if ret<0:
print "Unable to send GET_RA2 vendor request.\n"
else:
print "RA2 is currently %d.\n" % ord(buffer.raw[0])
usb.close_device(dev)
| [
[
1,
0,
0.087,
0.0435,
0,
0.66,
0,
182,
0,
1,
0,
0,
182,
0,
0
],
[
14,
0,
0.1739,
0.0435,
0,
0.66,
0.1111,
109,
1,
0,
0,
0,
0,
1,
0
],
[
14,
0,
0.2174,
0.0435,
0,
0... | [
"import ctypes",
"SET_RA1 = 1",
"CLR_RA1 = 2",
"GET_RA2 = 3",
"SET_DUTY = 4",
"usb = ctypes.cdll.LoadLibrary('usb.dll')",
"usb.initialize()",
"buffer = ctypes.c_buffer(8)",
"dev = usb.open_device(0x6666, 0x0003, 0)",
"if dev<0:\n print(\"No matching device found...\\n\")\nelse:\n ret = usb.c... |
import ctypes
SET_RA1 = 1
CLR_RA1 = 2
GET_RA2 = 3
SET_DUTY = 4
usb = ctypes.cdll.LoadLibrary('usb.dll')
usb.initialize()
buffer = ctypes.c_buffer(8)
dev = usb.open_device(0x6666, 0x0003, 0)
if dev<0:
print "No matching device found...\n"
else:
ret = usb.control_transfer(dev, 0x00, 0x09, 1, 0, 0, buffer)
if ret<0:
print "Unable to send SET_CONFIGURATION standard request.\n"
usb.close_device(dev)
| [
[
1,
0,
0.0952,
0.0476,
0,
0.66,
0,
182,
0,
1,
0,
0,
182,
0,
0
],
[
14,
0,
0.1905,
0.0476,
0,
0.66,
0.1111,
109,
1,
0,
0,
0,
0,
1,
0
],
[
14,
0,
0.2381,
0.0476,
0,
... | [
"import ctypes",
"SET_RA1 = 1",
"CLR_RA1 = 2",
"GET_RA2 = 3",
"SET_DUTY = 4",
"usb = ctypes.cdll.LoadLibrary('usb.dll')",
"usb.initialize()",
"buffer = ctypes.c_buffer(8)",
"dev = usb.open_device(0x6666, 0x0003, 0)",
"if dev<0:\n print(\"No matching device found...\\n\")\nelse:\n ret = usb.c... |
import ctypes
SET_RA1 = 1
CLR_RA1 = 2
GET_RA2 = 3
SET_DUTY = 4
usb = ctypes.cdll.LoadLibrary('usb.dll')
usb.initialize()
buffer = ctypes.c_buffer(8)
dev = usb.open_device(0x6666, 0x0003, 0)
if dev<0:
print "No matching device found...\n"
else:
ret = usb.control_transfer(dev, 0x40, SET_RA1, 0, 0, 0, buffer)
if ret<0:
print "Unable to send SET_RA1 vendor request.\n"
usb.close_device(dev)
| [
[
1,
0,
0.0952,
0.0476,
0,
0.66,
0,
182,
0,
1,
0,
0,
182,
0,
0
],
[
14,
0,
0.1905,
0.0476,
0,
0.66,
0.1111,
109,
1,
0,
0,
0,
0,
1,
0
],
[
14,
0,
0.2381,
0.0476,
0,
... | [
"import ctypes",
"SET_RA1 = 1",
"CLR_RA1 = 2",
"GET_RA2 = 3",
"SET_DUTY = 4",
"usb = ctypes.cdll.LoadLibrary('usb.dll')",
"usb.initialize()",
"buffer = ctypes.c_buffer(8)",
"dev = usb.open_device(0x6666, 0x0003, 0)",
"if dev<0:\n print(\"No matching device found...\\n\")\nelse:\n ret = usb.c... |
#!/usr/bin/python
from decimal import Decimal, getcontext
getcontext.prec = 10
from copy import copy
import os
import random
import time
import tkFileDialog
import tkMessageBox
import tkSimpleDialog
import pickle
import math
import generate
import graphmath
from copy import deepcopy
from math import *
from Gui import *
from graph import *
import tkColorChooser
try:
import Image, ImageDraw
except:
pass
import warnings
try:
import psyco
except:
pass
#Graph Types (do we need this?)
PETERSEN = 0
CYCLE = 1
STAR = 2
PRISM = 3
#Graph Commands
CONNECT = 0
MAXUNDO = 100
myFormats = [('Graph','*.graph')]
class FakeEvent():
def __init__(self,x,y):
self.x = x
self.y = y
class GraphInterface(Gui):
def __init__(self):
Gui.__init__(self)
self.graph = Graph()
self.ca_width = 600
self.ca_height = 600
self.rectangle = ['','']
self.backups = []
self.cancelled = False
self.dragging = False
self.box = False
self.handles = {}
self.clicked_on = None
self.product_verts=[]
self.product_edges=[]
self.click_mode = "vertex"
#self.clicked_time = 0
self.copied_verts = []
self.copied_edges = []
self.pasting = False
self.shift_pressed=False
self.control_pressed = False
self.attraction=.0005
self.spacing=10.0
self.setup()
self.mainloop()
def control_up(self, event=None):
self.control_pressed = False
self.redraw()
def control_down(self, event=None):
self.control_pressed = True
def setup(self):
self.title("Olin Graph Program")
self.makemenus()
#TODO: put in "keybindings" function
self.bind("<KeyRelease-Control_L>", self.control_up)
self.bind("<Control_L>", self.control_down)
self.bind("<Control-c>", self.copy)
self.bind("<Control-x>", self.cut)
self.bind("<Control-v>", self.paste)
self.bind("<Control-n>", self.new)
self.bind("<Control-s>", self.saveas)
self.bind("<Control-o>", self.open)
self.bind("<Control-p>", self.printcanv)
self.bind("<Control-k>", self.connect)
self.bind("<Control-l>", self.label_message)
# self.bind("<Control-r>", self.label_real_message)
self.bind("<Control-q>", self.clear_labeling)
self.bind("<Control-u>", self.unlabel_vertex)
self.bind("<Control-a>", self.select_all)
self.bind("<Control-b>", self.select_vertices)
self.bind("<Control-e>", self.select_edges)
self.bind("<Control-d>", self.deselect_all)
self.bind("<Control-i>", self.invert_selected)
self.bind("<Control-z>", self.undo)
self.bind("<Control-y>", self.redo)
self.bind("<Control-h>", self.start_physics)
self.bind("<Control-f>", self.finishklabeling)
self.bind("<Control-minus>", self.finishklabeling)
self.bind("<Control-space>", self.change_cursor)
self.bind("<Control-[>",self.box_none)
self.bind("<Control-]>",self.box_all)
# self.bind("<Control-s>", self.snapping)
# self.bind("<Control-m>", self.curve_selected)
# self.bind("<Control-w>", self.wrap_selected)
self.bind("<Control-KeyPress-1>", self.autolabel_easy)
self.bind("<Control-KeyPress-2>", self.autolabel_easy)
self.bind("<Control-KeyPress-3>", self.autolabel_easy)
self.bind("<Control-KeyPress-4>", self.autolabel_easy)
self.bind("<Control-KeyPress-5>", self.autolabel_easy)
self.bind("<Control-6>", self.autolabel_easy)
self.bind("<Control-7>", self.autolabel_easy)
self.bind("<Control-8>", self.autolabel_easy)
self.bind("<Control-9>", self.autolabel_easy)
self.bind("<Control-0>", self.autolabel_easy)
self.bind("<Delete>", self.delete_selected)
self.bind("<Configure>", self.redraw)
# self.bind("<Up>", self.curve_height)
# self.bind("<Down>", self.curve_height)
self.bind("<KeyPress-F1>", self.helptext)
self.bind("<Escape>", self.deselect_all)
self.bind("<Shift_L>",self.shift_down)
self.bind("<Shift_R>",self.shift_down)
self.bind("<KeyRelease-Shift_L>", self.shift_up)
self.bind("<Up>",self.change_physics)
self.bind("<Down>",self.change_physics)
self.bind("<Left>",self.change_physics)
self.bind("<Right>",self.change_physics)
for i in xrange(10):
self.bind("<KeyPress-%d>"%i,self.easy_label)
buttons = []
buttons.append('file')
buttons.append({'name':'new','image':"new.gif",'command':self.new})
buttons.append({'name':'open','image':"open.gif",'command':self.open})
buttons.append({'name':'save','image':"save.gif",'command':self.saveas})
buttons.append({'name':'print','image':"print.gif",'command':self.printcanv})
buttons.append('edit')
buttons.append({'name':'undo','image':"undo.gif",'command':self.undo})
buttons.append({'name':'redo','image':"redo.gif",'command':self.redo})
buttons.append({'name':'cut','image':"cut.gif",'command':self.cut})
buttons.append({'name':'copy','image':"copy.gif",'command':self.copy})
buttons.append({'name':'paste','image':"paste.gif",'command':self.paste})
buttons.append('edges')
buttons.append({'name':'curve','image':"curve.gif",'command':self.curve_selected})
buttons.append({'name':'connect','image':"connect.gif",'command':self.connect})
buttons.append({'name':'wrap','image':"wrap.gif",'command':self.wrap_selected})
buttons.append('physics')
buttons.append({'name':'start physics','image':"startphy.gif",'command':self.start_physics})
buttons.append({'name':'stop physics','image':"stopphy.gif",'command':self.stop_physics})
buttons.append('products')
## buttons.append(self.cartbutton)
buttons.append({'name':'Cartesian','image':"cartesian.gif",'command':lambda: self.graph_product('cartesian')})
buttons.append({'name':'Tensor','image':"tensor.gif",'command':lambda: self.graph_product('tensor')})
buttons.append({'name':'Strong','image':"strong.gif",'command':lambda: self.graph_product('strong')})
buttons.append('aesthetics')
buttons.append({'name':'ColorChooser','image':"colorchooser.gif",'command':self.choose_color})
buttons.append({'name':'SizePicker','image':"sizepicker.gif",'command':self.pick_size})
buttons.append({'name':'ShapeSelecter','image':"shapeselecter.gif",'command':self.select_shape})
self.fr(LEFT, width=70, expand=0)
self.menu_buttons(buttons)
#################################################################
self.fr(TOP, width=32, height=5, bd = 4, bg="grey", expand=0)
self.endfr()
#################################################################
self.endfr()
self.fr(LEFT, expand = 1)
self.canvas = self.ca(width=self.ca_width, height=self.ca_height, bg='white')
# # NOTE: resize works when the canvas is small--could start with this?
# # NOTE: try to find "minimum size" for resizing entire window, so we can't get any smaller at some me-defined point...keep menus/shit intact.
#self.canvas = self.ca(width=1, height=1, bg='white')
#self.canvas.configure(width=self.ca_width, height=self.ca_height)
self.canvas.bind("<Button-1>", self.clicked)
self.canvas.bind("<ButtonRelease-1>", self.released)
self.canvas.bind("<B1-Motion>", self.dragged)
self.canvas.bind("<Button-3>", self.right_clicked)
self.constraintstxt = StringVar()
self.number_per_circle = StringVar()
self.grid_size = StringVar()
self.holes_mode = StringVar()
self.snap_mode = StringVar()
self.constraintstxt.set("Labeling Constraints: L(2,1)")
self.number_per_circle.set("13")
self.grid_size.set("25")
self.holes_mode.set("allow")
self.snap_mode.set("none")
self.fr(TOP, expand = 0)
self.fr(LEFT, width=2, height=32, bd = 1, bg="grey", expand=0)
self.endfr()
self.fr(LEFT)
self.la(TOP,'both',0,'n',textvariable=self.constraintstxt)
self.bu(TOP,text="Change",command=self.constraints_message)
self.endfr()
self.fr(LEFT, width=2, height=32, bd = 1, bg="grey", expand=0)
self.endfr()
self.fr(LEFT)
self.fr()
self.endfr()
self.fr(TOP)
self.la(LEFT,'both',0,'n',text='Hole Algorithm')
#TODO: direct "help_holes" to help, with an argument for the section/tag in the help doc.
self.bu(side = TOP, anchor = W, text="?", command=self.help_holes)
self.endfr()
self.widget(Radiobutton,side = TOP, anchor = W, variable=self.holes_mode, text="Allow Holes", value="allow", state="active")
self.widget(Radiobutton,side = TOP, anchor = W, variable=self.holes_mode, text="Minimize Holes", value="minimize")
self.widget(Radiobutton,side = TOP, anchor = W, variable=self.holes_mode, text="No Holes", value="none")
self.endfr()
self.fr(LEFT, width=2, height=32, bd = 1, bg="grey", expand=0)
self.endfr()
self.fr(LEFT)
self.fr(TOP)
self.la(TOP,'both',0,'n',text='Snapping')
self.endfr()
self.fr(TOP)
self.fr(LEFT)
self.widget(Radiobutton,side = TOP, anchor = W, variable=self.snap_mode, text="None", value="none", state="active", command=self.redraw)
self.widget(Radiobutton,side = TOP, anchor = W, variable=self.snap_mode, text="Rectangular", value="rect", command=self.redraw)
self.widget(Radiobutton,side = TOP, anchor = W, variable=self.snap_mode, text="Polar", value="polar", command=self.redraw)
self.endfr()
self.fr(LEFT)
a = self.fr(TOP)
self.la(LEFT,'both',0,'n',text="Grid Size")
self.en(LEFT,anchor = N,width=4,textvariable=self.grid_size)
self.endfr()
# Again, unsure why the "pack forget/pack" lines ensure that the entry box acts right; without them, it doesn't (it expands fully)
a.pack_forget()
a.pack(side=TOP)
b = self.fr(TOP)
self.la(LEFT,'both',0,'n',text="Number of Axes")
self.en(LEFT,anchor = N,width=4,textvariable=self.number_per_circle)
self.endfr()
b.pack_forget()
b.pack(side=TOP)
self.bu(TOP,text='Update',command=self.redraw)
self.endfr()
self.endfr()
self.endfr()
self.fr(LEFT, width=2, height=32, bd = 1, bg="grey", expand=0)
self.endfr()
self.endfr()
self.endfr()
self.fr(LEFT, width=70, expand=0)
self.subgraph_menu()
self.endfr()
def help_holes(self):
helptxt = "Holes Allowed: The generated labelings are simply the smallest labelling; they have no regard for holes.\n\
Holes Minimized: The generated labeling is a labeling with the least number of holes in all samllest-span labelings.\n\
No Holes: The generated labelings contain no holes, at the possible expense of having a larger span."
tkMessageBox.showinfo("Help! I need somebody...", helptxt)
def menu_buttons(self,buttons):
i = 1
while i < len(buttons):
if i != 1: # Draw a grey bar between sections
self.fr(TOP, width=32, height=5, bd = 4, bg="grey", expand=0)
self.endfr()
self.fr(TOP, width=70, expand=0)
parity = False
while i < len(buttons) and type(buttons[i]) != type('str'):
button = buttons[i]
if parity == False:
self.fr(TOP, expand = 0)
try:
p = PhotoImage(file="icons/" + button['image'])
b = self.bu(text=button['name'], image=p, width=32, command=button['command'])
b.pack(side=LEFT,padx=2,pady=2)
b.image = p
except:
b = self.bu(text=button['name'], width=32, command=button['command'])
b.pack(side=LEFT,padx=2,pady=2)
if parity == True:
self.endfr()
i = i + 1
parity = not parity
if parity == True:
self.endfr()
self.endfr()
i = i + 1
def subgraph_menu(self):
self.la(TOP,'both',0,'n',text = 'Insert Subgraph')
subgraphs = []
subgraphs.append({'name':'petersen',
'command':lambda: self.select_subgraph('petersen'),
'options':[['vertices/layer',6],['layers',2]]})
subgraphs.append({'name':'cycle',
'command':lambda: self.select_subgraph('cycle'),
'options':[['vertices/cycle',5],['layers',1]]})
subgraphs.append({'name':'grid',
'command':lambda: self.select_subgraph('grid'),
'options':[['rows',5],['columns',4]]})
subgraphs.append({'name':'star',
'command':lambda: self.select_subgraph('star'),
'options':[['vertices/cycle',5],['skip',2]]})
subgraphs.append({'name':'mobius',
'command':lambda: self.select_subgraph('mobius'),
'options':[['n',5]]})
subgraphs.append({'name':'triangles',
'command':lambda: self.select_subgraph('triangles'),
'options':[['n',5],['m',5], ['sheet(1),\ncylinder(2),\ntoroid(3)',1]]})
subgraphs.append({'name':'hexagons',
'command':lambda: self.select_subgraph('hexagons'),
'options':[['n',5],['m',5], ['sheet(1),\ncylinder(2),\ntoroid(3)',1]]})
subgraphs.append({'name':'partite',
'command':lambda: self.select_subgraph('partite'),
'options':[['sizes','3,4,3']]})
subgraphs.append({'name':'file',
'command':lambda: self.select_subgraph('file'),
'options':[]})
self.subgraph_buttons = []
parity = False
self.fr(TOP, width=70, expand=0)
for subgraph in subgraphs:
if parity == False:
self.fr(TOP, expand = 0)
try:
p = PhotoImage(file="icons/subgraphs/" + subgraph['name'] + ".gif")
b = self.bu(text=subgraph['name'], width=64, image=p, command=subgraph['command'])
b.pack(side=LEFT,padx=2,pady=2)
b.image = p
except:
b=self.bu(text=subgraph['name'], width=64, command=subgraph['command'])
b.name = subgraph['name']
b.options = subgraph['options']
self.subgraph_buttons.append(b)
if parity == True:
self.endfr()
parity = not parity
if parity == True:
self.endfr()
self.subgraph_entries = []
for i in range(5):
this_frame = self.fr(side=TOP, anchor=W)
# ## NOTE: if the next two lines aren't added, the first box expands full width. Not sure exactly why...
this_frame.pack_forget()
this_frame.pack(side=TOP, anchor=W)
# ##
self.subgraph_entries.append((self.la(LEFT,text=""),
self.en(LEFT,width = 4),
this_frame))
self.endfr()
self.subgraph_button_frame = self.fr(TOP)
self.bu(text="Insert Subgraph", command=self.insert_subgraph)
self.endfr()
self.endfr()
self.selected_subgraph = None
self.select_subgraph(subgraphs[0]['name'])
def makemenus(self):
menu=Menu(self)
self.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="New (ctrl-n)", command=self.new)
filemenu.add_command(label="Save (ctrl-s)", command=self.saveas)
filemenu.add_command(label="Save Sequence", command=self.savesequence)
filemenu.add_command(label="Open (ctrl-o)", command=self.open)
filemenu.add_command(label="Open sequence", command=self.opensequence)
filemenu.add_command(label="Print (ctrl-p)", command=self.printcanv)
filemenu.add_separator()
filemenu.add_command(label="Import Regular Graph File (first graph)", command=self.import_graph)
filemenu.add_command(label="Import GPGs", command=self.import_GPGs)
filemenu.add_command(label="Enter Shortcode", command=self.enter_shortcode)
filemenu.add_command(label="Enter GPGPermutation", command=self.enter_GPGpermutation)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=self.exit)
editmenu = Menu(menu)
menu.add_cascade(label="Edit", menu=editmenu)
editmenu.add_command(label="Cut (ctrl-x)", command=self.cut)
editmenu.add_command(label="Copy (ctrl-c)", command=self.copy)
editmenu.add_command(label="Paste (ctrl-v)", command=self.paste)
editmenu.add_separator()
editmenu.add_command(label="Undo (ctrl-z)", command=self.undo)
editmenu.add_command(label="Redo (ctrl-y)", command=self.redo)
labelmenu = Menu(menu)
menu.add_cascade(label="Labeling", menu=labelmenu)
labelmenu.add_command(label="Label Selected Vertices", command=self.label_message)
#labelmenu.add_command(label="Label (with reals) Selected Vertices", command=self.label_real_message)
labelmenu.add_command(label="Unlabel Selected Vertices (ctrl-u)", command=self.unlabel_vertex)
labelmenu.add_command(label="Clear Labeling", command=self.clear_labeling)
labelmenu.add_separator()
labelmenu.add_command(label="Auto-Label/Finish Labeling Graph", command=self.autolabel_message)
#labelmenu.add_command(label="Find Lambda Number (clears current labeling)", command=self.lambda_label_message)
labelmenu.add_command(label="Check Labeling", command=self.check_labeling)
labelmenu.add_command(label="Count Holes", command=self.count_holes)
graphmenu = Menu(menu)
menu.add_cascade(label="Graphs", menu=graphmenu)
graphmenu.add_command(label="Graph Complement", command=self.complement)
graphmenu.add_command(label="Line Graph", command=self.line_graph)
graphmenu.add_command(label="Box Everything", command=self.box_all)
graphmenu.add_separator()
graphmenu.add_command(label="Process Regular Graph File", command=self.process_regular_graph)
graphmenu.add_separator()
graphmenu.add_command(label="Get Graph Representations", command=self.get_graph_representations)
# graphmenu.add_command(label="Check Isomorphism", command=self.check_isomorphic)
helpmenu = Menu(menu)
menu.add_cascade(label="Help", menu=helpmenu)
helpmenu.add_command(label="Help (F1)", command=self.helptext)
helpmenu.add_command(label="About", command=self.abouttext)
def helptext(self, event=None):
basics = "Creating Vertices and Edges:\n\
To create vertices, simply shift-click on an empty spot.\n\
To create edges, either select multiple vertices, and right click and select 'connect', or...\n\
Hold down CTRL and click and drag. Release the mouse, and you will create the edge. Note that \n\
none, one, or both of the endpoints may be existing vertices.\n\
\n\
Editing the Edges:\n\
To wrap edges, first select the edges. Then either click the 'wrap' button from the left side, or\n\
right click and select 'wrap'.\n\
To curve edges, just drag an edge, and it will curve along your cursor (try it!)\n\
For a different method for curving, first select the edges. Then either click the 'curve' button from\n\
the left side, or right click and select 'curve'.\n\
Note that edges cannot be both curved and wrapped, and curving win take over if both are selected.\n\
\n\
Selecting and Moving:\n\
Click on an edge or vertex to select it. Click and drag a vertex to move it.\n\
Also, there is an 'area select' mode, where you can drag and select everything inside a rectangle. After\n\
you make your selection, you can click and drag the entire box, or resize by dragging the handles.\n\
You can always press 'Escape' to unselect everything, including any area select box.\n\
\n\
Cut, Copy and Paste:\n\
To cut, copy, or paste, use either the keyboard shortcuts, right click, use the button on the left menu, or select\n\
from the 'edit' drop down menu.\n\
After you click to 'paste', you must then click somewhere on the drawing area. The pasted graph can then be \n\
or resized via the box methods.\n"
more_advanced = "Labeling:\n\
To label, either right click, or select 'label' from the top drop-down menu.\n\
You can label with either reals or integers using the same dialog.\n\
Note that real numbers are much slower in solving, due to more complex representation in the computer.\n\
\n\
Physics Mode:\n\
This can now be started and stopped via the buttons on the left menu or by pressing Ctrl-H.\n\
Press up and down to control vertex spacing (pushing away from each other) \n\
and left and right to control attraction along edges\n\
\n\
Key Shortcuts:\n\
Most key shortcuts are noted in the top drop down menus. For brevity, we only include the others here.\n\
\n\
Ctrl-A: Select All\n\
Ctrl-E: Select Edges\n\
Ctrl-B: Select Vertices\n\
\n\
Delete: Delete Selected\n\
Escape: Deselect All\n\
F1: Help\n\
Ctrl-<number>: complete L(2,1)-Labeling with minimum lambda <number> or find a k-conversion set with <number> vertices\n\
Ctrl-F: finish k-conversion with already labeled vertices\n\
Ctrl-0: step through one step of the k-conversion process\n\
\n\
Right Click:\n\
You can right click on the drawing area to access commonly used functions from a pop up menu.\n\
\n\
Auto-Update:\n\
You should always have the latest version!\n\
Each time the program starts, it tries to connect to the internet, and downloads the latest version of itself.\n\
This is meant to be very unobtrusive, but a useful way to provide quick updates and bug fixes.\n\
Although the delay shouldn't be noticeable, it this becomes an issue, there is a simple way to disable it.\n\
(Note: Is is not recommended to disable this!)\n\
\n\
Easy Install:\n\
As a side effect of the auto-update, the program is a snap to install. Just double click on the update file (start.py),\n\
and the entire program is downloaded to the folder containing start.py.\n"
about_the_menus = "Menus/Parts of the GUI:\n\
Simple Top Menu\n\
Key shortcuts are given in the drop down top menus.\n\
\n\
Buttons on the Left Menu\n\
File Commands (New, Open, Save, and Print)\n\
Edit Commands (Undo, Redo, Cut, Copy, and Paste)\n\
Edge Commands (Curve, Connect, Wrap)\n\
Physics Commands (Start, Stop)\n\
Product Commands (Cartesian, Tensor, Strong)\n\
-make graph, click product button to store first graph. alter or make a new, second graph, press product button to create the product of the first and second graph\n\
\n\
Insert Subgraph Menu\n\
You can insert subgraphs without clearing the existing graph.\n\
\n\
Bottom Bar\n\
Can change of labeling constraints. (single number - k conversion, list of numbers (2,1 or 1,0) L(n,m) labeling, M - majority conversion)\n\
Can change hole algorithm.\n\
Easy setup or change grid for snapping."
tkMessageBox.showinfo("Basic Help (P1/3)", basics)
tkMessageBox.showinfo("More Advanced Help (P2/3)", more_advanced)
tkMessageBox.showinfo("An overview of the Menus (P3/3)", about_the_menus)
def abouttext(self, event=None):
abouttxt = "Olin Graph Program\n\
\n\
Created by Jon Cass, Cody Wheeland, and Matthew Tesch\n\
\n\
Email iamtesch@gmail.com for feature requests, questions, or help."
tkMessageBox.showinfo("About", abouttxt)
# #####################################################################################################
# File operations (New, Open, Save, Import, Print, Exit):
# #####################################################################################################
def new(self, event=None):
self.querysave()
if not self.cancelled:
self.clear()
self.backups = []
self.redos = []
self.cancelled=False
self.control_up()
def open(self, event=None):
#self.querysave()
if not self.cancelled:
file = tkFileDialog.askopenfile(parent=self,mode='rb',title='Choose a file')
if file != None:
self.backups = []
self.redos = []
self.graph = pickle.load(file)
file.close()
self.redraw()
self.cancelled=False
self.control_up()
def opensequence(self, event=None):
#self.querysave()
if not self.cancelled:
file = tkFileDialog.askopenfile(parent=self,mode='rb',filetypes=[('Graph Sequence','*.graphs')],title='Choose a file')
if file != None:
self.backups = []
self.redos = pickle.load(file)
self.graph = self.redos[len(self.redos)-1]
file.close()
self.redraw()
self.cancelled=False
self.control_up()
def saveas(self, event=None, fileName=None):
if not self.cancelled:
if not fileName:
fileName = tkFileDialog.asksaveasfilename(parent=self,filetypes=myFormats,title="Save the graph as...")
if len(fileName ) > 0:
if ('.' in fileName and '.graph' not in fileName):
## try:
self.draw_to_file(fileName)
## except:
## tkMessageBox.showinfo("You need PIL!", "It looks like you don't have PIL.\nYou need the Python Imaging Library to save to an image!\nhttp://www.pythonware.com/products/pil/")
else:
if '.graph' not in fileName:
fileName += '.graph'
f=file(fileName, 'wb')
pickle.dump(self.graph,f)
f.close()
self.cancelled=False
self.control_up()
def savesequence(self, event=None, fileName=None):
if not self.cancelled:
if not fileName:
fileName = tkFileDialog.asksaveasfilename(parent=self,filetypes=[('Graph Sequence','*.graphs')],title="Save the graph sequence as...")
if len(fileName ) > 0:
if '.graphs' not in fileName:
fileName += '.graphs'
f=file(fileName, 'wb')
pickle.dump(self.redos,f)
f.close()
self.cancelled=False
self.control_up()
def querysave(self):
self.message("Save?", "Would you like to save?", self.saveas, "yesnocancel")
self.control_up()
def draw_to_file(self, filename):
width=float(self.canvas.winfo_width())
height=float(self.canvas.winfo_height())
image1 = Image.new("RGB", (width, height), (255,255,255))
draw = ImageDraw.Draw(image1)
draw=self.graph.draw_to_file(draw,width,height)
image1.save(filename)
def import_graph(self):
file = tkFileDialog.askopenfile(parent=self,mode='rb',title='Choose a file')
if file != None:
self.clear()
self.graph = Graph(labelingConstraints=self.graph.labelingConstraints)
if file.name.endswith('.scd'):
nums=self.readshortcode(file)
for graph in self.graph.loadshortcode(nums, all=False):
self.graph=graph
else:
adjlist = []
while file:
line = file.readline()
if line[0:5] == "Graph":
line = file.readline()
line = file.readline()
while line[0:5] != "Taill":
line = line.split()
line.remove(":")
for i in range(len(line)):
line[i] = int(line[i])
adjlist.append(line)
line = file.readline()
break
self.graph.loadadjlist(adjlist)
file.close()
self.redraw()
self.control_up()
def import_GPGs(self):
file = tkFileDialog.askopenfile(parent=self,mode='r',title='Choose a file')
if file !=None:
self.clear()
numgraphs=sum(1 for line in file)
file.seek(0)
graphcounter=0;
rows=5
cols=5
for i in xrange(1,5):
if i*i>numgraphs:
rows=cols=i
break
spacing=20
canvas_width=self.canvas.winfo_width()
canvas_height=self.canvas.winfo_height()
w=(canvas_width-spacing*(cols+1))/cols
h=(canvas_height-spacing*(rows+1))/rows
for line in file:
nums=list(line.strip())
for i in xrange(len(nums)):
nums[i]=int(nums[i])
g=Graph(labelingConstraints=self.graph.labelingConstraints)
g.loadGPG(nums)
labels=[]
verts=g.get_vertices()
edges=g.edges
constraints=g.labelingConstraints
if type(constraints)==type([]):
labels = graphmath.auto_label(verts, edges, constraints, 5, self.holes_mode.get())
else:
labels=graphmath.finishklabeling(verts,edges,constraints)
i=0
for vert in g.get_vertices():
vert.label=labels[i]
vert.x*=w/400.
vert.y*=h/400.
col=graphcounter%cols
row=(graphcounter%(rows*cols))/rows
x=col*w+w/2+spacing*(col+1)-canvas_width/2
y=row*h+h/2+spacing*(row+1)-canvas_height/2
vert.x+=x
vert.y+=y
self.graph.add_vertex(vert)
i+=1
for edge in g.edges:
self.graph.edges.append(edge)
graphcounter+=1
if graphcounter%(rows*cols)==0:
self.saveas(fileName=file.name[:-4]+'-'+str(graphcounter/(rows*cols))+'.png')
self.clear()
self.saveas(fileName=file.name[:-4]+'-'+str(graphcounter/(rows*cols)+1)+'.png')
file.close()
self.redraw()
def enter_shortcode(self):
res = tkSimpleDialog.askstring("Enter Shortcode", "Enter Shortcode to load:")
res=res.split(',')
if len(res)==1:
res=res[0].split()
if len(res)==1:
num=int(res[0])
res=[]
while num>0:
res.append(num%10)
num/=10
if res[0]=='0':
del res[0]
for i in xrange(len(res)):
res[i]=int(res[i])
res.insert(0,max(res)) #the number of vertices will be the highest number in the edge-list
res.insert(1,len(res)*2/res[0])
res.insert(2,0)
for graph in self.graph.loadshortcode(res, all=False):
self.graph=graph
self.redraw()
def enter_GPGpermutation(self):
res = tkSimpleDialog.askstring("Enter Permutation", "Enter permutation to load:")
res=res.split(',')
if len(res)==1:
res=res[0].split()
if len(res)==1:
num=res
res=[]
for i in xrange(len(num)):
res.append(int(num[i]))
for i in xrange(len(res)):
res[i]=int(res[i])
print res
self.graph.loadGPG(res)
self.redraw()
def process_regular_graph(self):
infile = tkFileDialog.askopenfile(parent=self,mode='rb',title='Choose a file')
outfilename = tkFileDialog.asksaveasfilename(parent=self,title="Save the output as...")
if len(outfilename) > 0:
outfile=file(outfilename, 'w')
else:
outfile=file('out.txt', 'w')
self.cancelled=False
if infile != None:
# self.holes_mode.set("minimize") # I really don't think this should be here, or else it resets every time we process. We want to process with the current settings.
tempgraph = deepcopy(self.graph)
self.clear()
self.graph = Graph(labelingConstraints=self.graph.labelingConstraints) # we want to keep the existing labeling constraints here
if infile.name.endswith('.scd'):
nums=self.readshortcode(infile)
for graph in self.graph.loadshortcode(nums, all=True):
self.graph=graph
self.clear_labeling()
lnum = self.autolabel(0,quiet=True)
outfile.write("Lambda: "+str(lnum)+"\r\n")
holes = self.count_holes(quiet=True)
outfile.write("Holes: "+str(holes)+"\r\n")
else:
line = 'beginning' # some value so the while loop goes at least once...
while line != '':
line = infile.readline()
if line[0:5] == "Graph":
line = infile.readline()
line = infile.readline()
adjlist = []
while line[0:5] != "Taill":
line = line.split()
line.remove(":")
for i in range(len(line)):
line[i] = int(line[i])
adjlist.append(line)
line = infile.readline()
self.graph.loadadjlist(adjlist)
self.clear_labeling()
lnum = self.autolabel(0,quiet=True)
outfile.write("Lambda: "+str(lnum)+"\r\n")
holes = self.count_holes(quiet=True)
outfile.write("Holes: "+str(holes)+"\r\n")
self.graph = tempgraph
infile.close()
outfile.close()
self.redraw()
def get_graph_representations(self):
adj=graphmath.adjacencymatrix(self.graph.get_vertices(),self.graph.edges)
adjmessage= "Adjacency Matrix\n---------------------\n"
for i in xrange(len(adj)):
adjmessage+=str(adj[i])+"\n"
spm=graphmath.shortestpathmatrix(self.graph.get_vertices(),self.graph.edges)
spmmessage= "Shortest Path Matrix\n------------------------\n"
for i in xrange(len(spm)):
spmmessage+=str(spm[i])+"\n"
scmessage="Shortcode\n------------\n"
if graphmath.is_regular(self.graph.get_vertices(),self.graph.edges):
scmessage+=str(graphmath.generate_shortcode(self.graph.get_vertices(),self.graph.edges))
else:
scmessage+="The graph is not regular.\nA shortcode doesn't make sense."
if len(self.graph.get_vertices())<10:
tkMessageBox.showinfo("Graph Representations:",adjmessage+"\n"+spmmessage+"\n"+scmessage)
else:
tkMessageBox.showinfo("Graph Representations (P1/3):",adjmessage)
tkMessageBox.showinfo("Graph Representations (P2/3):",spmmessage)
tkMessageBox.showinfo("Graph Representations (P3/3):",scmessage)
#reads a shortcode file, returns list with the numeric elements of the file
#first two elements are number of vertices and the regularity of the graph
#shortcode is for k-regular graphs on n-vertices, produced by genreg program
def readshortcode(self, f, full=True):
name=os.path.split(f.name)[-1]
name=name.split('_')
k=int(name[1])
n=int(name[0])
s=f.read(1)
nums=[n, k]
while s:
nums.append(ord(s))
s=f.read(1)
if not full and len(nums)==2+n*k/2:
break
return nums
def printcanv(self, event=None):
self.canvas.postscript(file="print.ps")
os.system("PrFile32.exe /q print.ps")
def cancel(self):
self.cancelled=True
def exit(self):
self.querysave()
if not self.cancelled:
sys.exit(0)
self.cancelled=False
# #####################################################################################################
# Edit Operations: Undo, Redo, Copy, Paste, Connect, Delete, etc.
# #####################################################################################################
def curve_selected(self, event=None):
for edge in self.graph.edges:
if edge.selected:
edge.curved = not edge.curved
self.redraw()
# def curve_height(self, event):
# step = 0
# if event.keysym == "Up":
# step = 1
# if event.keysym == "Down":
# step = -1
# for edge in self.graph.edges:
# if edge.selected:
# if not edge.curved:
# edge.curved = True
# edge.height = edge.height + step
# self.redraw()
def wrap_selected(self, event=None):
for edge in self.graph.edges:
if edge.selected:
edge.wrap = not edge.wrap
edge.curved = False
self.redraw()
# Call this function before any operation that you want to be "undone". It saves the state of the graph at that point.
# (For example, the start of all clicks, new vertices, deletes, etc.)
def registerwithundo(self):
self.redos = []
self.backups.append(deepcopy(self.graph))
if len(self.backups)>MAXUNDO:
self.backups.pop(1)
def undo(self, event=None):
if len(self.backups) == 0:
return
self.redos.append(deepcopy(self.graph))
self.graph = self.backups.pop()
self.redraw()
def redo(self, event=None):
if len(self.redos) == 0:
return
self.backups.append(deepcopy(self.graph))
self.graph = self.redos.pop()
self.redraw()
def selection(self):
sel = [o for o in self.graph.get_vertices() + self.graph.edges if o.selected]
if sel == []:
return None
return sel
def select_all(self, event=None):
self.select_edges(all=True)
self.select_vertices(all=True)
def select_edges(self, event=None, all=False):
self.registerwithundo()
if all:
for e in self.graph.edges:
e.selected=True
else:
for v in self.graph.get_vertices():
v.selected=False
self.redraw()
def select_vertices(self, event=None,all=False):
self.registerwithundo()
if all:
for v in self.graph.get_vertices():
v.selected=True
else:
for e in self.graph.edges:
e.selected=False
self.redraw()
def deselect_all(self, event=None):
self.registerwithundo()
self.box = None
self.deselect_edges()
self.deselect_vertices()
def deselect_edges(self, event=None):
self.registerwithundo()
for e in self.graph.edges:
e.selected=False
self.redraw()
def deselect_vertices(self, event=None):
self.registerwithundo()
for v in self.graph.get_vertices():
v.selected=False
self.redraw()
def invert_selected(self, event=None):
self.registerwithundo()
for v in self.graph.get_vertices():
v.selected=not v.selected
for e in self.graph.edges:
e.selected=not e.selected
self.redraw()
# Deprecated and unneeded. Delete this function?
# def delete_selected_vertices(self, event=None):
# self.registerwithundo()
# vr = []
# for v in self.graph.get_vertices():
# if v.selected:
# vr.append(v)
# for e in self.graph.edges:
# if v in e.vs:
# er.append(e)
# for e in er:
# try:
# self.graph.edges.remove(e)
# except:
# pass
# for v in vr:
# try:
# self.graph.remove_vertex(v)
# except:
# pass
# self.redraw()
def delete_selected(self, event=None):
self.registerwithundo()
er = []
vr = []
for e in self.graph.edges:
if e.selected:
er.append(e)
for v in self.graph.get_vertices():
if v.selected:
vr.append(v)
for e in self.graph.edges:
if v in e.vs:
er.append(e)
for e in er:
try:
self.graph.edges.remove(e)
except:
pass
for v in vr:
try:
self.graph.remove_vertex(v)
except:
pass
self.box = False
self.redraw()
def connect(self, event=None):
self.registerwithundo()
self.graph.connect()
self.redraw()
def copy(self, event=None, delete=False):
selectedverts = [v for v in self.graph.get_vertices() if v.selected]
self.copied_verts = []
self.copied_edges = []
for v in selectedverts:
self.copied_verts.append((v.x,v.y,v.label))
for e in self.graph.edges:
if e.vs[0] in selectedverts and e.vs[1] in selectedverts and e.selected:
self.copied_edges.append(((e.vs[0].x,e.vs[0].y),(e.vs[1].x,e.vs[1].y),[e.wrap,e.curved,e.height,e.direction]))
if delete==True:
self.delete_selected()
else:
self.deselect_all()
def cut(self, event=None):
self.registerwithundo()
self.copy(event=event, delete=True)
def paste(self, event=None):
self.registerwithundo()
self.pasting = True
def shift_down(self, event=None):
self.shift_pressed=True
def shift_up(self, event=None):
self.shift_pressed=False
def choose_color(self):
self.registerwithundo()
vert_selected=False
if len([v for v in self.graph.get_vertices() if v.selected])>0:
color=tkColorChooser.askcolor(color=self.graph.get_vertices()[0].color,title="Choose a Vertex Color")[1]
for v in [v for v in self.graph.get_vertices() if v.selected]:
if color!=None:
v.color=color
if v.label!="NULL":
vert_selected=True
self.redraw();
if len([edge for edge in self.graph.edges if edge.selected])>0:
color=tkColorChooser.askcolor(color=self.graph.edges[0].color,title="Choose an Edge Color")[1]
for edge in [edge for edge in self.graph.edges if edge.selected]:
edge.color=color
self.redraw();
if vert_selected:
color=tkColorChooser.askcolor(color=self.graph.get_vertices()[0].lcolor,title="Label Color")[1]
if color!=None:
for v in [v for v in self.graph.get_vertices() if v.selected]:
v.lcolor=color
self.redraw()
def pick_size(self, event=None):
vert_selected=False
if len([v for v in self.graph.get_vertices() if v.selected])>0:
size=int(tkSimpleDialog.askstring("Pick Size", "What's a good size for the selected vertices?"))
if size!=None:
size=int(size)
for v in [v for v in self.graph.get_vertices() if v.selected]:
if size!=None:
v.size=size
if v.label!="NULL":
vert_selected=True
self.redraw();
if len([edge for edge in self.graph.edges if edge.selected])>0:
size=tkSimpleDialog.askstring("Pick Size", "What's a good width for the selected edges?")
if size!=None:
size=int(size)
for edge in [edge for edge in self.graph.edges if edge.selected]:
edge.size=size
self.redraw();
if vert_selected:
size=tkSimpleDialog.askstring("Pick Size", "What's a good width for the labels?")
if size!=None:
size=int(size)
for v in [v for v in self.graph.get_vertices() if v.selected]:
v.lsize=size
self.redraw()
def select_shape(self, event=None):
shape=-1
for v in [v for v in self.graph.get_vertices() if v.selected]:
if shape==-1:
if type(v.shape)==type('A'):
shape=0
elif v.shape==8:
names=['Harold','Luke','Connor','Paul','Zachary','Dr. Adams','Dr. Troxell']
shape=random.choice(names)
else:
shape=(v.shape+1)
if shape==7:
shape+=1
v.shape=shape
self.redraw()
# #####################################################################################################
# Whole Graph Commands: Complement, Line Graph, etc. Anything that changes/affects the current graph. (In the spirit of complement, etc, but not "add new subgraph")
# #####################################################################################################
def complement(self):
self.registerwithundo()
comp = Graph()
vertices = self.graph.get_vertices()
comp.vertices = vertices
comp.edges = []
for v1 in vertices:
for v2 in vertices:
if v1 != v2:
found = 0
for e in self.graph.edges:
if v1 in e.vs and v2 in e.vs:
found = 1
break
if not found:
comp.edges.append(Edge(v1,v2))
self.graph.edges.append(Edge(v1,v2))
self.graph = comp
self.redraw()
def line_graph(self):
self.registerwithundo()
lg = Graph(edges = [])
i = 0
lgverts = []
for e1 in self.graph.edges:
v = Vertex((.5*e1.vs[0].x+.5*e1.vs[1].x, .5*e1.vs[0].y+.5*e1.vs[1].y))
lgverts.append(v)
lg.add_vertex(v)
for j in range(i):
e2 = self.graph.edges[j]
if e1 != e2:
if (e1.vs[0] in e2.vs) or (e1.vs[1] in e2.vs):
lg.edges.append(Edge(lgverts[i],lgverts[j]))
i = i + 1
self.graph = lg
self.redraw()
# #####################################################################################################
# Product Commands: Commands to create products of graphs
# #####################################################################################################
def graph_product(self, type, event=None):
self.registerwithundo()
if (len(self.product_verts)!=0):
product_adj=graphmath.adjacencymatrix(self.product_verts,self.product_edges)
verts = self.graph.get_vertices()
edges = self.graph.edges
product_adj2=graphmath.adjacencymatrix(verts,edges)
adjmat=[]
if (type=='cartesian'):
adjmat=graphmath.cartesian_product(product_adj,product_adj2)
elif(type=='tensor'):
adjmat=graphmath.tensor_product(product_adj,product_adj2)
elif(type=='strong'):
adjmat=graphmath.strong_product(product_adj,product_adj2)
else:
print "uh oh. that not a graph product type."
adjmat=graphmath.cartesian_product(product_adj,product_adj2)
self.graph = Graph(labelingConstraints =self.graph.labelingConstraints)
self.graph.loadadjmatrix(adjmat,len(self.product_verts), len(verts),self.product_verts, verts )
self.product_verts=[]
self.product_edges=[]
else:
self.product_verts=self.graph.get_vertices()[:]
self.product_edges=self.graph.edges[:]
self.redraw()
# #####################################################################################################
# Labeling Commands: Commands to label, change labeling constraints, etc.
# #####################################################################################################
def autolabel_easy(self, event=None):
if type(self.graph.labelingConstraints)==type([]):
if self.check_to_clear():
self.clear_labeling()
self.autolabel(int(event.keysym))
else:
if int(event.keysym)!=0:
self.autolabel(int(event.keysym))
else:
self.stepthrough()
self.control_up()
def check_to_clear(self):
for vertex in self.graph.vertices:
if vertex.label == 'NULL':
return False
self.control_up()
return True
# def label_message(self, event=None):
# self.message("Label Vertices", "What would you like to label these vertices?", self.label_vertex)
# Note: label_message now takes care of real and integers; integers are transformed to int type in label_vertex.
def label_message(self, event=None):
self.message("Label Vertices", "What would you like to label these vertices?", self.label_vertex, type="Decimal")
self.control_up()
def autolabel_message(self):
self.message("Auto-Label Graph", "What is the minimum lambda-number for this graph?", self.autolabel)
self.control_up()
# def lambda_label_message(self):
# self.clear_labeling()
# self.holes_mode.set("allow")
# lnum = self.autolabel(0,quiet=True)
# labeltxt = ""
# for labConst in self.graph.labelingConstraints:
# labeltxt += str(labConst) + ","
# labeltxt = labeltxt[:-1]
# tkMessageBox.showinfo("Labeling Span", "The L(" + labeltxt + ") lambda number for this graph is " + str(lnum) + ".")
def constraints_message(self):
res = ''
while res == '':
res = tkSimpleDialog.askstring("Change Labeling Constraints", \
"Please enter new labeling constraints.\n" \
+"Enter a single value for K conversion ('3' for K3).\n" \
+"M - majority, MS - strong majority.\n" \
+"comma deliminated list of values for L(m,n,...) labeling ('2,1' for L(2,1) labeling)")
self.change_constraints(res)
self.control_up()
def change_constraints(self, newconstraints):
backup = self.graph.labelingConstraints
if (len(newconstraints)>1 and newconstraints[0].isdigit()):
self.graph.labelingConstraints = []
try:
for label in newconstraints.split(','):
label = Decimal(label)
if label == int(label):
self.graph.labelingConstraints.append(int(label))
else:
self.graph.labelingConstraints.append(label)
except:
tkMessageBox.showinfo("Error", "The labeling constraints were input in a bad form! Using old constraints.")
self.graph.labelingConstraints = backup
labeltxt = "Labeling Constraints: L("
for labConst in self.graph.labelingConstraints:
labeltxt += str(labConst) + ","
labeltxt = labeltxt[:-1]
labeltxt += ")"
self.constraintstxt.set(labeltxt)
else:
self.graph.labelingConstraints = 0
try:
label=int(newconstraints[0])
self.graph.labelingConstraints=label
labeltxt = "Labeling Constraints: K"+ str(label)
except:
if newconstraints.upper()[0]=='M':
if (len(newconstraints)>1 and newconstraints.upper()[1]=='S'):
self.graph.labelingConstraints=-2
labeltxt = "Labeling Constraints: Strong Majority"
else:
self.graph.labelingConstraints=-1
labeltxt = "Labeling Constraints: Majority"
else:
tkMessageBox.showinfo("Error", "The labeling constraints were input in a bad form! Using old constraints.")
self.graph.labelingConstraints = backup
self.constraintstxt.set(labeltxt)
self.control_up()
def label_vertex(self, label):
self.registerwithundo()
if int(label) == label:
label = int(label)
for v in [v for v in self.graph.get_vertices() if v.selected]:
v.label=label
self.redraw()
def unlabel_vertex(self, event=None):
self.registerwithundo()
for v in [v for v in self.graph.get_vertices() if v.selected]:
v.label='NULL'
self.redraw()
def clear_labeling(self, event=None):
self.registerwithundo()
for v in self.graph.get_vertices():
v.label='NULL'
self.redraw()
def autolabel(self, minlambda, quiet = False):
self.registerwithundo()
verts = self.graph.get_vertices()
edges = self.graph.edges
constraints = self.graph.labelingConstraints
labels=[]
if type(constraints)==type([]):
labels = graphmath.auto_label(verts, edges, constraints, minlambda, self.holes_mode.get())
else:
if minlambda==-1:
labels=graphmath.finishklabeling(verts,edges,constraints)
else:
labels=graphmath.find_conversion_set(verts,edges,constraints, minlambda)
##put the control-2-3-4-5-etc code call here
if labels == "RealError":
tkMessageBox.showinfo("Holes and Reals don't mix!", "Don't select 'minimize' or 'no holes' with real labels or constraints; this doesn't make sense!")
self.control_up()
return
if labels == False:
tkMessageBox.showinfo("Bad Partial Labeling", "The partial labeling is incorrect. Please correct before auto-finishing the labeling.")
self.control_up()
return
for i in range(len(verts)):
verts[i].label = labels[i]
(lmin,lmax,complete)=graphmath.labeling_difference(verts)
self.redraw()
lnum = lmax - lmin
if (not quiet):
self.control_up()
if type(self.graph.labelingConstraints)==type([]):
tkMessageBox.showinfo("Labeling Span", "The labeling span for this coloring is " + str(lnum) + ".\n Largest label: " + str(lmax) + "\n Smallest label: " + str(lmin))
else:
s='The graph is completely covered!'
if not complete:
s='The graph is NOT completely covered.'
tkMessageBox.showinfo("Conversion Time", "The conversion time for this coloring is " + str(lnum) + ".\n Largest time: " + str(lmax) + "\n Smallest time: " + str(lmin)+"\n"+s)
return lnum
def check_labeling(self,quiet = False):
verts = self.graph.get_vertices()
edges = self.graph.edges
constraints = self.graph.labelingConstraints
res = graphmath.check_labeling(verts,edges,constraints)
if res == True:
if not quiet:
self.control_up()
tkMessageBox.showinfo("Correct Labeling", "The labeling is correct.")
return True
else: # res is (False,(i,j)), where 'i' and 'j' are the bad vertices
if not quiet:
self.control_up()
self.deselect_vertices()
verts[res[1][0]].selected = True
verts[res[1][1]].selected = True
tkMessageBox.showwarning("Bad labeling", "The selected vertices appears to be wrong.")
self.redraw()
return False
#shouldn't work with real labelings! TODO: check this! (doesn't break, but shouldn't let you)
def count_holes(self,quiet = False):
verts = self.graph.get_vertices()
lmax = 0
for v in verts:
if v.label > lmax:
lmax = v.label
numholes = 0
for i in range(lmax):
found = 0
for v in verts:
if v.label == i:
found = 1
break
if not found:
numholes += 1
if not quiet:
control_up()
tkMessageBox.showinfo("Number of Holes", "The number of holes in this labeling is " + str(numholes) + ".")
return numholes
def easy_label(self, event=None):
self.label_vertex(int(event.keysym))
#stepthrough one step in k conversion process
def stepthrough(self):
verts=self.graph.get_vertices()
changelist=graphmath.stepthrough(verts,graphmath.adjacencymatrix(verts,self.graph.edges), self.graph.labelingConstraints)
if len(changelist)!=0:
self.registerwithundo()
(lmin,lmax, complete)=graphmath.labeling_difference(verts)
for vertnum in changelist:
verts[vertnum].label=lmax+1
return complete
else:
return True
def finishklabeling(self,event=None):
if type(self.graph.labelingConstraints)!=type([]):
self.autolabel(-1)
# #####################################################################################################
# Gui Bindings: Mouse controlled-commands and helper functions
# #####################################################################################################
def find_clicked_on(self, event):
#TODO: ensure this returns a vertex or edge, not a selection circle or something!
# for v in self.graph.get_vertices():
# if x+10 > v.x > x-10 and y+10 > v.y > y-10:
# return v
#TODO: how about just finding anthing in "self.canvas.find_overlapping"???
self.closest=self.canvas.find_closest(event.x, event.y)
try:
self.closest=self.closest[0]
except:
return None
if self.closest in self.canvas.find_overlapping(event.x-10, event.y-10, event.x+10, event.y+10):
for h in self.handles.keys():
if self.closest == h:
return h
for v in self.graph.get_vertices():
if self.closest == v.circle:
return v
if self.shift_pressed and self.closest==v.text:
return v
for e in self.graph.edges:
if self.closest == e.line or (e.wrap and self.closest == e.altline):
return e
return None
def right_clicked(self, e):
# def rClick_Copy(e, apnd=0):
#e.widget.event_generate('<Control-c>')
# print "copy"
#event.widget.focus()
nclst=[
('Connect Selected', self.connect),
('----', None),
('Cut', self.cut),
('Copy', self.copy),
('Paste', self.paste),
('----', None),
('Label Selected', self.label_message),
('Unlabel Selected', self.unlabel_vertex),
('----', None),
('Wrap Edges', self.wrap_selected),
('Curve Edges', self.curve_selected),
('----', None),
('Change Cursor', self.change_cursor)
#('Copy', lambda e=e: rClick_Copy(e)),
#('Paste', lambda e=e: rClick_Paste(e)),
]
rmenu = Menu(None, tearoff=0, takefocus=0)
# cas = {}
# cascade = 0
for (txt, cmd) in nclst:
if txt == "----":
rmenu.add_separator()
else:
rmenu.add_command(label=txt, command=cmd)
# if txt.startswith('>>>>>>') or cascade:
# if txt.startswith('>>>>>>') and cascade and cmd == None:
# #done cascade
# cascade = 0
# rmenu.add_cascade( label=icmd, menu = cas[icmd] )
# elif cascade:
# if txt == ' ------ ':
# cas[icmd].add_separator()
# else: cas[icmd].add_command(label=txt, command=cmd)
# else: # start cascade
# cascade = 1
# icmd = cmd[:]
# cas[icmd] = Tk.Menu(rmenu, tearoff=0, takefocus=0)
# else:
# if txt == ' ------ ':
# rmenu.add_separator()
# else: rmenu.add_command(label=txt, command=cmd)
#rmenu.entryconfigure(0, label = "redemo", state = 'disabled')
rmenu.tk_popup(e.x_root+10, e.y_root+10,entry="0")
return "break"
def clicked(self, event):
#TODO: create "clicked flags" instead of individual variables?
self.registerwithundo()
self.clicked_time = time.time()
self.clicked_pos = (event.x, event.y)
self.dragging = False
self.clicked_on = self.find_clicked_on(event)
self.clicked_create_edge = self.control_pressed
self.clicked_in_box = False
self.resize = None
if self.box:
center = self.get_center()
b0 = self.box[0]+center[0]
b1 = self.box[1]+center[1]
b2 = self.box[2]+center[0]
b3 = self.box[3]+center[1]
xcoords = (b0,b2)
ycoords = (b1,b3)
if self.clicked_on in self.handles.keys():
self.resize = ['m','m']
if self.handles[self.clicked_on][0] == b0:
self.resize[0] = 'l'
elif self.handles[self.clicked_on][0] == b2:
self.resize[0] = 'r'
if self.handles[self.clicked_on][1] == b1:
self.resize[1] = 'l'
elif self.handles[self.clicked_on][1] == b3:
self.resize[1] = 'r'
center = self.get_center()
for v in self.surrounded_vertices:
try:
#v.xnorm = (v.x-self.box[0]+center[0])/(self.box[2]-self.box[0])
v.xnorm = (v.x-self.box[0])/(self.box[2]-self.box[0])
except:
v.xnorm = 0
try:
#v.ynorm = (v.y-self.box[1]+center[1])/(self.box[3]-self.box[1])
v.ynorm = (v.y-self.box[1])/(self.box[3]-self.box[1])
except:
v.ynorm = 0
elif min(xcoords) < event.x < max(xcoords) and min(ycoords) < event.y < max(ycoords):
self.clicked_in_box = (event.x, event.y)
else:
self.box = False
#self.redraw()
# if self.click_mode == "path":
# oldtime = self.clickedtime
# self.clickedtime = time.time()
# if self.clickedtime-oldtime < .25: # Double click!
# self.graph.lastvertex = None
# return
# single click...
# v = None
# for vert in self.graph.get_vertices():
# if x+10 > vert.x > x-10 and y+10 > vert.y > y-10:
# v = vert
# break
# if v == None:
# v = Vertex((x, y))
# self.graph.add_vertex(v)
# if self.graph.lastvertex != None:
# self.graph.connect((v, self.graph.lastvertex))
# self.graph.lastvertex = v
# self.redraw()
def move_box(self, event):
dx = event.x - self.clicked_in_box[0]
dy = event.y - self.clicked_in_box[1]
for v in self.surrounded_vertices:
v.x += dx
v.y += dy
self.box[0] += dx
self.box[1] += dy
self.box[2] += dx
self.box[3] += dy
self.clicked_in_box = (event.x, event.y)
def resize_box(self, event):
center = self.get_center()
if self.resize[0] == 'l':
self.box[0] = event.x - center[0]
elif self.resize[0] == 'r':
self.box[2] = event.x - center[0]
if self.resize[1] == 'l':
self.box[1] = event.y - center[1]
elif self.resize[1] == 'r':
self.box[3] = event.y - center[1]
for v in self.surrounded_vertices:
v.x = v.xnorm*(self.box[2]-self.box[0])+self.box[0]
v.y = v.ynorm*(self.box[3]-self.box[1])+self.box[1]
def dragged(self, event):
center = self.get_center()
x = event.x - center[0]
y = event.y - center[1]
if self.dragging or (time.time() - self.clicked_time > .15):
self.dragging = True
if self.clicked_create_edge:
if self.control_pressed:
try:
self.canvas.delete(self.drag_shape)
except:
pass
self.drag_shape = self.canvas.create_line(self.clicked_pos[0], self.clicked_pos[1], event.x, event.y, width=4, fill="blue")
return
elif self.box:
if self.resize:
self.resize_box(event)
if self.clicked_in_box:
self.move_box(event)
self.redraw()
else: #no box
if self.clicked_on in self.graph.edges: # If we clicked on an edge
#do "drag-curving" logic/trig here.
self.clicked_on.curve_through(x,y)
self.redraw()
elif self.clicked_on in self.graph.get_vertices(): #If we clicked and dragged a vertex...
if self.shift_pressed:
self.clicked_on.lx=x-self.clicked_on.x
self.clicked_on.ly=y-self.clicked_on.y
elif self.snap_mode.get() != 'none': #snap-move vertex
self.snap(event, self.clicked_on)
else: #move vertex
self.clicked_on.x = x
self.clicked_on.y = y
self.redraw()
else: #if we are drag-selecting
try:
self.canvas.delete(self.drag_shape)
except:
pass
self.drag_shape = self.canvas.create_rectangle(self.clicked_pos[0], self.clicked_pos[1], event.x, event.y, width=2, outline="blue", tags="bounding box")
# elif self.clickedon in self.graph.get_vertices():
# if self.drag_mode == "single" or self.drag_mode == "selected":
# if self.snap_on:
# dx = event.x - self.clickedon.x
# dy = event.y - self.clickedon.y
#
# else:
# dx = x - self.clickedon.x
# dy = y - self.clickedon.y
# self.redraw()
# if self.drag_mode == "selected":
# for v in self.graph.get_vertices():
# if v.selected and v != self.clickedon:
# if self.snap_on:
# e = FakeEvent(v.x + dx,v.y + dy)
# self.snap(e, v)
# else:
# v.x += dx
# v.y += dy
# self.redraw()
def released(self, event):
center = self.get_center()
x = event.x - center[0]
y = event.y - center[1]
if self.dragging: #We've been dragging.
if self.clicked_create_edge:
if self.control_pressed:
self.drag_to_create_edge(event) # create Edge
elif self.box:
pass #we've already done these steps in the "dragged" function...
else: #no box
if self.clicked_on in self.graph.edges: # If we clicked on an edge
pass
#do "drag-curving" logic/trig here.
#self. curve_through(edge, point)
elif self.clicked_on in self.graph.get_vertices(): #If we clicked and dragged a vertex...
pass #we've already moved it in the "dragged" function -- nothing more to do here!
else: #if we are drag-selecting
xcoords = [event.x,self.clicked_pos[0]]
ycoords = [event.y,self.clicked_pos[1]]
self.surrounded_vertices = []
for v in self.graph.get_vertices():
if min(xcoords) < v.x + center[0] < max(xcoords) and min(ycoords) < v.y + center[1] < max(ycoords):
self.surrounded_vertices.append(v)
v.selected = True
for e in self.graph.edges:
if e.vs[0] in self.surrounded_vertices and e.vs[1] in self.surrounded_vertices:
e.selected = True
self.box = [self.clicked_pos[0]-center[0],self.clicked_pos[1]-center[1],event.x-center[0],event.y-center[1]]
else: #We're not draggin!
if self.pasting: #if pasting/insert subgraph is true:
self.insert_copied(event)
self.pasting = False
#insert subgraph
elif self.clicked_on in self.graph.get_vertices() or self.clicked_on in self.graph.edges: # If we clicked on something
#Toggle its selection
self.clicked_on.toggle()
self.clicked_on.draw(self.canvas)
elif (self.selection() != None or self.box) and not self.shift_pressed: #elif something is selected (and clicked on nothing) and not pressing shift
self.deselect_all()
elif(self.shift_pressed): # If we clicked on nothing, and nothing is selected or pressing shift (to make a new vertex)
newVertex = Vertex((x, y))
if self.snap_mode.get() != 'none':
self.snap( event, newVertex )
self.graph.add_vertex( newVertex )
self.redraw()
def change_cursor(self, event=None):
self.config(cursor=random.choice(['bottom_tee', 'heart', 'double_arrow', 'top_left_arrow',
'top_side', 'top_left_corner', 'X_cursor', 'dotbox',
'lr_angle', 'sb_down_arrow', 'draft_small', 'gumby',
'bottom_right_corner', 'hand2', 'sb_right_arrow', 'diamond_cross',
'umbrella', 'mouse', 'trek', 'bottom_side', 'spraycan', 'll_angle',
'based_arrow_down', 'rightbutton', 'clock', 'right_ptr', 'sailboat', 'draft_large',
'cross', 'fleur', 'left_tee', 'boat', 'sb_left_arrow', 'shuttle', 'plus', 'bogosity',
'man', 'pirate', 'bottom_left_corner', 'pencil', 'star', 'arrow', 'exchange', 'gobbler',
'iron_cross', 'left_side', 'xterm', 'watch', 'leftbutton', 'spider', 'sizing', 'ul_angle',
'center_ptr', 'circle', 'icon', 'sb_up_arrow', 'draped_box', 'box_spiral', 'rtl_logo',
'target', 'middlebutton', 'question_arrow', 'cross_reverse', 'sb_v_double_arrow', 'right_side',
'top_right_corner', 'top_tee', 'ur_angle', 'sb_h_double_arrow', 'left_ptr', 'crosshair',
'coffee_mug', 'right_tee', 'based_arrow_up', 'tcross', 'dot', 'hand1']))
def insert_copied(self, event):
center = self.get_center()
x = event.x - center[0]
y = event.y - center[1]
vertdict = {}
leastx = 100000
mostx = -100000
leasty = 100000
mosty = -100000
for v in self.copied_verts:
if v[0] > mostx:
mostx = v[0]
if v[1] > mosty:
mosty = v[1]
if v[0] < leastx:
leastx = v[0]
if v[1] < leasty:
leasty = v[1]
avgx = (mostx + leastx) / 2
avgy = (mosty + leasty) / 2
self.deselect_all()
for v in self.copied_verts:
# In case we insert a graph with labels undefined
if len(v) < 3:
v = (v[0], v[1], "NULL")
vertdict[(v[0],v[1])] = Vertex((x+v[0]-avgx,y+v[1]-avgy),v[2])
self.graph.add_vertex( vertdict[(v[0],v[1])] )
for e in self.copied_edges:
if len(e) < 3:
# In case we insert a graph with edge curviness/wrapped-ness undefined
e = (e[0], e[1], None)
self.graph.connect((vertdict[e[0]],vertdict[e[1]]),e[2])
for v in vertdict.values():
v.toggle()
for e in self.graph.edges:
if e.vs[0] in vertdict.values() and e.vs[1] in vertdict.values():
e.toggle()
self.surrounded_vertices = vertdict.values()
self.box = [x-(mostx-leastx)/2, y-(mosty-leasty)/2, x+(mostx-leastx)/2, y+(mosty-leasty)/2]
def box_none(self,event=None):
self.box=False
self.surrounded_vertices=[]
self.redraw()
def box_all(self,event=None):
leastx = 100000
mostx = -100000
leasty = 100000
mosty = -100000
for v in self.graph.get_vertices():
if v.x > mostx:
mostx = v.x
if v.y > mosty:
mosty = v.y
if v.x < leastx:
leastx = v.x
if v.y < leasty:
leasty = v.y
self.box = [leastx-10, leasty-10,mostx+10, mosty+10]
self.surrounded_vertices=[v for v in self.graph.get_vertices()]
self.select_all()
def drag_to_create_edge(self, event):
center = self.get_center()
x = event.x - center[0]
y = event.y - center[1]
if self.clicked_on in self.graph.get_vertices():
v1 = self.clicked_on
else:
v1 = Vertex((self.clicked_pos[0]-center[0], self.clicked_pos[1]-center[1]))
if self.snap_mode.get() != 'none':
self.snap(FakeEvent(self.clicked_pos[0], self.clicked_pos[1]), v1)
self.graph.add_vertex(v1)
self.redraw()
released_on = self.find_clicked_on(event)
if released_on in self.graph.get_vertices():
v2 = released_on
else:
v2 = Vertex((x, y))
if self.snap_mode.get() != 'none':
self.snap(event, v2)
self.graph.add_vertex(v2)
self.graph.connect(vs = (v1,v2))
# #####################################################################################################
# Other Functions
# #####################################################################################################
def do_physics(self):
spacing = self.spacing
attraction = self.attraction
vertices = self.graph.get_vertices()
vertices2 = vertices[:]
for i in xrange(len(vertices)):
vertex=vertices2[random.randrange(0,len(vertices2))]
vertices2.remove(vertex)
for vertex2 in vertices2:
x_distance = vertex.x - vertex2.x
y_distance = vertex.y - vertex2.y
distance2 = (x_distance * x_distance) + (y_distance * y_distance)
if (vertex.x != vertex2.x or vertex.y != vertex2.y) and (distance2 < 10000 ):
if x_distance != 0:
delta_x = x_distance * spacing / distance2
if not vertex.selected:
vertex.x = vertex.x + delta_x
if not vertex2.selected:
vertex2.x = vertex2.x - delta_x
if y_distance != 0:
delta_y = y_distance * spacing / distance2
if not vertex.selected:
vertex.y = vertex.y + delta_y
if not vertex2.selected:
vertex2.y = vertex2.y - delta_y
for edge in self.graph.edges:
vertices = edge.vs
distance = math.sqrt( math.pow( vertices[0].x - vertices[1].x, 2 ) + math.pow( vertices[0].y - vertices[1].y, 2 ) )
direction = [ (vertices[0].x - vertices[1].x), (vertices[0].y - vertices[1].y) ]
if not vertices[0].selected:
vertices[0].x = vertices[0].x - direction[0] * distance * attraction
vertices[0].y = vertices[0].y - direction[1] * distance * attraction
if not vertices[1].selected:
vertices[1].x = vertices[1].x + direction[0] * distance * attraction
vertices[1].y = vertices[1].y + direction[1] * distance * attraction
self.redraw()
def start_physics(self, event=None):
if self.stop_physics:
self.stop_physics = False
while(1):
self.do_physics()
self.update()
self.redraw()
if self.stop_physics == True:
return
else:
self.stop_physics=True
def stop_physics(self):
self.stop_physics = True
def change_physics(self,event=None):
if event.keysym == "Up":
self.spacing+=.5
elif event.keysym == "Down":
self.spacing-=.5
elif event.keysym == "Right":
self.attraction+=.00001
elif event.keysym == "Left":
self.attraction-=.00001
def drawbox(self):
center = self.get_center()
if self.box:
b0 = self.box[0] + center[0]
b1 = self.box[1] + center[1]
b2 = self.box[2] + center[0]
b3 = self.box[3] + center[1]
self.canvas.create_rectangle(b0, b1, b2, b3, width=2, outline="blue", dash = (2,4), tags="selection box")
handles = ((b0,b1),
(b0,(b1+b3)/2),
(b0,b3),
(b2,b1),
(b2,(b1+b3)/2),
(b2,b3),
((b0+b2)/2,b1),
((b0+b2)/2,b3))
self.handles = {}
for handle in handles:
h = self.canvas.create_rectangle(handle[0]-3, handle[1]-3, handle[0]+3, handle[1]+3, fill="blue", outline="blue")
self.handles[h]=(handle[0],handle[1])
def drawgrid(self):
if self.snap_mode.get() == "rect":
width = float(self.canvas.winfo_width())
height = float(self.canvas.winfo_height())
try:
grid_size = float(self.grid_size.get())
except:
print "Error in snap parameters!"
return
x = ( (width / 2.0) % grid_size)
y = ( (height / 2.0) % grid_size)
while x < width: #vertical lines
self.canvas.create_line(x, 0, x, height, width = 1, fill = "grey", tags = "grid")
x = x + grid_size
while y < height: #horizontal lines
self.canvas.create_line(0, y, width, y, width = 1, fill = "grey", tags = "grid")
y = y + grid_size
self.canvas.create_line(0, height/2, width, height/2, width = 2, fill = "grey", tags = "grid")
self.canvas.create_line(width/2, 0, width/2, height, width = 2, fill = "grey", tags = "grid")
elif self.snap_mode.get() == "polar":
width = float(self.canvas.winfo_width())
height = float(self.canvas.winfo_height())
center = [width / 2, height / 2]
#grid_size = float(self.snap_grid_size)
#number_per_circle = float(self.snap_number_per_circle)
try:
grid_size = float(self.grid_size.get())
number_per_circle = float(self.number_per_circle.get())
except:
print "Error in snap parameters!"
return
theta = 2 * pi / number_per_circle
radius = grid_size
angle = 0
canvas_radius = sqrt( height * height + width * width ) / 2
while radius < canvas_radius:
self.canvas.create_oval(center[0] - radius, center[1] - radius, center[0] + radius, center[1] + radius, width = 1, outline = "grey", tags = "grid")
radius = radius + grid_size
while angle < 2*pi:
self.canvas.create_line(center[0], center[1], center[0] + canvas_radius * cos(angle), center[1] + canvas_radius * sin(angle), width = 1, fill = "grey", tags = "grid")
angle = angle + theta
def snap(self, event, vertex):
center = self.get_center()
x = event.x - center[0]
y = event.y - center[1]
#grid_size = float(self.snap_grid_size)
#number_per_circle = float(self.snap_number_per_circle)
try:
grid_size = float(self.grid_size.get())
except:
print "Error in snap parameters!"
return
if self.snap_mode.get() == "rect":
low = grid_size * floor( x / grid_size )
high = grid_size * ceil( x / grid_size )
if (x - low) < (high - x):
vertex.x = low
else:
vertex.x = high
low = grid_size * floor( y / grid_size )
high = grid_size * ceil( y / grid_size )
if (y - low) < (high - y):
vertex.y = low
else:
vertex.y = high
elif self.snap_mode.get() == "polar":
try:
number_per_circle = float(self.number_per_circle.get())
except:
print "Error in snap parameters!"
return
distance = sqrt( x*x + y*y )
angle = atan2( y, x )
angle = angle / (2*pi) * number_per_circle
low = grid_size * floor( distance / grid_size )
high = grid_size * ceil( distance / grid_size )
if (distance - low) < (high - distance):
distance = low
else:
distance = high
low = floor( angle )
high = ceil( angle )
if (angle - low) < (high - angle):
angle = low
else:
angle = high
angle = angle / number_per_circle * 2*pi
vertex.x = distance * cos( angle )
vertex.y = distance * sin( angle )
def select_subgraph(self, type):
# first, save the old state, and "pop up" the button
for subgraph in self.subgraph_buttons:
if subgraph.name == self.selected_subgraph:
subgraph.config(relief = RAISED)
for i in range(len(subgraph.options)):
subgraph.options[i][1] = self.subgraph_entries[i][1].get()
self.subgraph_entries[i][1].delete(0, END)
# TODO: should we have done int conversion here? Make sure we try/except later...(watch out for "file")
break
# update the selected subgraph
self.selected_subgraph = type
# update the subgraph entry boxes, and
for subgraph in self.subgraph_buttons:
if subgraph.name == type:
subgraph.config(relief = SUNKEN)
self.subgraph_button_frame.pack_forget()
for i in range(len(subgraph.options)):
self.subgraph_entries[i][0].config(text = subgraph.options[i][0])
self.subgraph_entries[i][1].config(state = NORMAL)
self.subgraph_entries[i][1].insert(END, subgraph.options[i][1])
self.subgraph_entries[i][2].pack(side = TOP, anchor = W)
i = i + 1
if len(subgraph.options) == 0:
i = 0
while i < len(self.subgraph_entries):
self.subgraph_entries[i][0].config(text = "")
self.subgraph_entries[i][1].config(state = DISABLED)
self.subgraph_entries[i][2].config(height = 0)
self.subgraph_entries[i][2].pack_forget()
i=i+1
self.subgraph_button_frame.pack(side = TOP)
break
def insert_subgraph(self):
for subgraph in self.subgraph_buttons:
if subgraph.name == self.selected_subgraph:
options = []
for i in range(len(subgraph.options)):
try:
option = int(self.subgraph_entries[i][1].get())
if option <= 0:
tkMessageBox.showwarning("Invalid Parameters", "All parameters should be positive!")
return
options.append(option)
except:
try:
option= [int(x) for x in self.subgraph_entries[i][1].get().split(',')]
options.append(option)
except:
tkMessageBox.showwarning("Invalid Parameters", "All parameters should be integers!")
return
break
if self.selected_subgraph == "file":
file = tkFileDialog.askopenfile(parent=self,mode='rb',title='Choose a file')
if file != None:
tempgraph = pickle.load(file)
file.close()
self.copied_verts = []
self.copied_edges = []
for v in tempgraph.vertices:
self.copied_verts.append((v.x,v.y,v.label))
for e in tempgraph.edges:
self.copied_edges.append(((e.vs[0].x,e.vs[0].y),(e.vs[1].x,e.vs[1].y),[e.wrap,e.curved,e.height,e.direction]))
center = self.get_center()
center = FakeEvent(center[0],center[1])
self.insert_copied(center)
self.redraw()
return
tkMessageBox.showwarning("Unable to Insert", "No File Chosen")
return
res = generate.generate(subgraph.name, options)
if res[0] == "ERROR":
tkMessageBox.showwarning("Invalid Parameters", res[1])
self.copied_verts = res[0]
self.copied_edges = res[1]
center = self.get_center()
center = FakeEvent(center[0],center[1])
self.insert_copied(center)
self.redraw()
def message(self, title, message, function, type="okcancel"):
if type=="passgraphokcancel":
res = tkSimpleDialog.askinteger(title, message)
if res != None:
function( self.graph, res )
if type=="okcancel":
res = tkSimpleDialog.askinteger(title, message)
if res != None:
function( res )
if type=="Decimal":
res = tkSimpleDialog.askstring(title, message)
if res != None:
function( Decimal(res) )
elif type=="yesnocancel":
if tkMessageBox._show(title,message,icon=tkMessageBox.QUESTION,type=tkMessageBox.YESNOCANCEL)=="yes":
function()
# def toggle_snap_mode(self, type=None):
# if type == "none":
# self.snap_on = False
# try:
# self.canvas.delete("grid")
# except:
# pass
# elif type == "rect":
# self.snap_on = True
# self.snap_mode = "rect"
# elif type == "circular":
# self.snap_on = True
# self.snap_mode = "circular"
# self.redraw()
# return
def clear(self, reset=True):
if reset:
self.registerwithundo()
self.graph.vertices=[]
self.graph.edges=[]
self.graph.tags=[]
self.canvas.delete("all")
# event is needed so that it can be called from the "Configure" binding that detects window size changes.
def redraw(self, event=None):
self.clear(False)
self.drawgrid()
self.graph.draw(self.canvas)
self.drawbox()
def get_center(self):
width = float(self.canvas.winfo_width())
height = float(self.canvas.winfo_height())
return [width / 2, height / 2]
def main(update = False):
warnings.filterwarnings("ignore")
# import cProfile
try:
psyco.full()
except:
print "Problem with your psyco. go install it for faster action."
if update:
#Update "start.py"
from shutil import move
move("start.py.new","start.py")
world = GraphInterface()
# cProfile.run('GraphInterface()')
#world.mainloop()
if __name__ == '__main__':
main() | [
[
1,
0,
0.0014,
0.0005,
0,
0.66,
0,
349,
0,
2,
0,
0,
349,
0,
0
],
[
14,
0,
0.0019,
0.0005,
0,
0.66,
0.0323,
365,
1,
0,
0,
0,
0,
1,
0
],
[
1,
0,
0.0028,
0.0005,
0,
0... | [
"from decimal import Decimal, getcontext",
"getcontext.prec = 10",
"from copy import copy",
"import os",
"import random",
"import time",
"import tkFileDialog",
"import tkMessageBox",
"import tkSimpleDialog",
"import pickle",
"import math",
"import generate",
"import graphmath",
"from copy ... |
#!/usr/bin/python
from decimal import Decimal, getcontext
getcontext.prec = 10
from copy import copy
import os
import random
import time
import tkFileDialog
import tkMessageBox
import tkSimpleDialog
import pickle
import math
import generate
import graphmath
from copy import deepcopy
from math import *
from Gui import *
from graph import *
import tkColorChooser
try:
import Image, ImageDraw
except:
pass
import warnings
try:
import psyco
except:
pass
#Graph Types (do we need this?)
PETERSEN = 0
CYCLE = 1
STAR = 2
PRISM = 3
#Graph Commands
CONNECT = 0
MAXUNDO = 100
myFormats = [('Graph','*.graph')]
class FakeEvent():
def __init__(self,x,y):
self.x = x
self.y = y
class GraphInterface(Gui):
def __init__(self):
Gui.__init__(self)
self.graph = Graph()
self.ca_width = 600
self.ca_height = 600
self.rectangle = ['','']
self.backups = []
self.cancelled = False
self.dragging = False
self.box = False
self.handles = {}
self.clicked_on = None
self.product_verts=[]
self.product_edges=[]
self.click_mode = "vertex"
#self.clicked_time = 0
self.copied_verts = []
self.copied_edges = []
self.pasting = False
self.shift_pressed=False
self.control_pressed = False
self.attraction=.0005
self.spacing=10.0
self.setup()
self.mainloop()
def control_up(self, event=None):
self.control_pressed = False
self.redraw()
def control_down(self, event=None):
self.control_pressed = True
def setup(self):
self.title("Olin Graph Program")
self.makemenus()
#TODO: put in "keybindings" function
self.bind("<KeyRelease-Control_L>", self.control_up)
self.bind("<Control_L>", self.control_down)
self.bind("<Control-c>", self.copy)
self.bind("<Control-x>", self.cut)
self.bind("<Control-v>", self.paste)
self.bind("<Control-n>", self.new)
self.bind("<Control-s>", self.saveas)
self.bind("<Control-o>", self.open)
self.bind("<Control-p>", self.printcanv)
self.bind("<Control-k>", self.connect)
self.bind("<Control-l>", self.label_message)
# self.bind("<Control-r>", self.label_real_message)
self.bind("<Control-q>", self.clear_labeling)
self.bind("<Control-u>", self.unlabel_vertex)
self.bind("<Control-a>", self.select_all)
self.bind("<Control-b>", self.select_vertices)
self.bind("<Control-e>", self.select_edges)
self.bind("<Control-d>", self.deselect_all)
self.bind("<Control-i>", self.invert_selected)
self.bind("<Control-z>", self.undo)
self.bind("<Control-y>", self.redo)
self.bind("<Control-h>", self.start_physics)
self.bind("<Control-f>", self.finishklabeling)
self.bind("<Control-minus>", self.finishklabeling)
self.bind("<Control-space>", self.change_cursor)
self.bind("<Control-[>",self.box_none)
self.bind("<Control-]>",self.box_all)
# self.bind("<Control-s>", self.snapping)
# self.bind("<Control-m>", self.curve_selected)
# self.bind("<Control-w>", self.wrap_selected)
self.bind("<Control-KeyPress-1>", self.autolabel_easy)
self.bind("<Control-KeyPress-2>", self.autolabel_easy)
self.bind("<Control-KeyPress-3>", self.autolabel_easy)
self.bind("<Control-KeyPress-4>", self.autolabel_easy)
self.bind("<Control-KeyPress-5>", self.autolabel_easy)
self.bind("<Control-6>", self.autolabel_easy)
self.bind("<Control-7>", self.autolabel_easy)
self.bind("<Control-8>", self.autolabel_easy)
self.bind("<Control-9>", self.autolabel_easy)
self.bind("<Control-0>", self.autolabel_easy)
self.bind("<Delete>", self.delete_selected)
self.bind("<Configure>", self.redraw)
# self.bind("<Up>", self.curve_height)
# self.bind("<Down>", self.curve_height)
self.bind("<KeyPress-F1>", self.helptext)
self.bind("<Escape>", self.deselect_all)
self.bind("<Shift_L>",self.shift_down)
self.bind("<Shift_R>",self.shift_down)
self.bind("<KeyRelease-Shift_L>", self.shift_up)
self.bind("<Up>",self.change_physics)
self.bind("<Down>",self.change_physics)
self.bind("<Left>",self.change_physics)
self.bind("<Right>",self.change_physics)
for i in xrange(10):
self.bind("<KeyPress-%d>"%i,self.easy_label)
buttons = []
buttons.append('file')
buttons.append({'name':'new','image':"new.gif",'command':self.new})
buttons.append({'name':'open','image':"open.gif",'command':self.open})
buttons.append({'name':'save','image':"save.gif",'command':self.saveas})
buttons.append({'name':'print','image':"print.gif",'command':self.printcanv})
buttons.append('edit')
buttons.append({'name':'undo','image':"undo.gif",'command':self.undo})
buttons.append({'name':'redo','image':"redo.gif",'command':self.redo})
buttons.append({'name':'cut','image':"cut.gif",'command':self.cut})
buttons.append({'name':'copy','image':"copy.gif",'command':self.copy})
buttons.append({'name':'paste','image':"paste.gif",'command':self.paste})
buttons.append('edges')
buttons.append({'name':'curve','image':"curve.gif",'command':self.curve_selected})
buttons.append({'name':'connect','image':"connect.gif",'command':self.connect})
buttons.append({'name':'wrap','image':"wrap.gif",'command':self.wrap_selected})
buttons.append('physics')
buttons.append({'name':'start physics','image':"startphy.gif",'command':self.start_physics})
buttons.append({'name':'stop physics','image':"stopphy.gif",'command':self.stop_physics})
buttons.append('products')
## buttons.append(self.cartbutton)
buttons.append({'name':'Cartesian','image':"cartesian.gif",'command':lambda: self.graph_product('cartesian')})
buttons.append({'name':'Tensor','image':"tensor.gif",'command':lambda: self.graph_product('tensor')})
buttons.append({'name':'Strong','image':"strong.gif",'command':lambda: self.graph_product('strong')})
buttons.append('aesthetics')
buttons.append({'name':'ColorChooser','image':"colorchooser.gif",'command':self.choose_color})
buttons.append({'name':'SizePicker','image':"sizepicker.gif",'command':self.pick_size})
buttons.append({'name':'ShapeSelecter','image':"shapeselecter.gif",'command':self.select_shape})
self.fr(LEFT, width=70, expand=0)
self.menu_buttons(buttons)
#################################################################
self.fr(TOP, width=32, height=5, bd = 4, bg="grey", expand=0)
self.endfr()
#################################################################
self.endfr()
self.fr(LEFT, expand = 1)
self.canvas = self.ca(width=self.ca_width, height=self.ca_height, bg='white')
# # NOTE: resize works when the canvas is small--could start with this?
# # NOTE: try to find "minimum size" for resizing entire window, so we can't get any smaller at some me-defined point...keep menus/shit intact.
#self.canvas = self.ca(width=1, height=1, bg='white')
#self.canvas.configure(width=self.ca_width, height=self.ca_height)
self.canvas.bind("<Button-1>", self.clicked)
self.canvas.bind("<ButtonRelease-1>", self.released)
self.canvas.bind("<B1-Motion>", self.dragged)
self.canvas.bind("<Button-3>", self.right_clicked)
self.constraintstxt = StringVar()
self.number_per_circle = StringVar()
self.grid_size = StringVar()
self.holes_mode = StringVar()
self.snap_mode = StringVar()
self.constraintstxt.set("Labeling Constraints: L(2,1)")
self.number_per_circle.set("13")
self.grid_size.set("25")
self.holes_mode.set("allow")
self.snap_mode.set("none")
self.fr(TOP, expand = 0)
self.fr(LEFT, width=2, height=32, bd = 1, bg="grey", expand=0)
self.endfr()
self.fr(LEFT)
self.la(TOP,'both',0,'n',textvariable=self.constraintstxt)
self.bu(TOP,text="Change",command=self.constraints_message)
self.endfr()
self.fr(LEFT, width=2, height=32, bd = 1, bg="grey", expand=0)
self.endfr()
self.fr(LEFT)
self.fr()
self.endfr()
self.fr(TOP)
self.la(LEFT,'both',0,'n',text='Hole Algorithm')
#TODO: direct "help_holes" to help, with an argument for the section/tag in the help doc.
self.bu(side = TOP, anchor = W, text="?", command=self.help_holes)
self.endfr()
self.widget(Radiobutton,side = TOP, anchor = W, variable=self.holes_mode, text="Allow Holes", value="allow", state="active")
self.widget(Radiobutton,side = TOP, anchor = W, variable=self.holes_mode, text="Minimize Holes", value="minimize")
self.widget(Radiobutton,side = TOP, anchor = W, variable=self.holes_mode, text="No Holes", value="none")
self.endfr()
self.fr(LEFT, width=2, height=32, bd = 1, bg="grey", expand=0)
self.endfr()
self.fr(LEFT)
self.fr(TOP)
self.la(TOP,'both',0,'n',text='Snapping')
self.endfr()
self.fr(TOP)
self.fr(LEFT)
self.widget(Radiobutton,side = TOP, anchor = W, variable=self.snap_mode, text="None", value="none", state="active", command=self.redraw)
self.widget(Radiobutton,side = TOP, anchor = W, variable=self.snap_mode, text="Rectangular", value="rect", command=self.redraw)
self.widget(Radiobutton,side = TOP, anchor = W, variable=self.snap_mode, text="Polar", value="polar", command=self.redraw)
self.endfr()
self.fr(LEFT)
a = self.fr(TOP)
self.la(LEFT,'both',0,'n',text="Grid Size")
self.en(LEFT,anchor = N,width=4,textvariable=self.grid_size)
self.endfr()
# Again, unsure why the "pack forget/pack" lines ensure that the entry box acts right; without them, it doesn't (it expands fully)
a.pack_forget()
a.pack(side=TOP)
b = self.fr(TOP)
self.la(LEFT,'both',0,'n',text="Number of Axes")
self.en(LEFT,anchor = N,width=4,textvariable=self.number_per_circle)
self.endfr()
b.pack_forget()
b.pack(side=TOP)
self.bu(TOP,text='Update',command=self.redraw)
self.endfr()
self.endfr()
self.endfr()
self.fr(LEFT, width=2, height=32, bd = 1, bg="grey", expand=0)
self.endfr()
self.endfr()
self.endfr()
self.fr(LEFT, width=70, expand=0)
self.subgraph_menu()
self.endfr()
def help_holes(self):
helptxt = "Holes Allowed: The generated labelings are simply the smallest labelling; they have no regard for holes.\n\
Holes Minimized: The generated labeling is a labeling with the least number of holes in all samllest-span labelings.\n\
No Holes: The generated labelings contain no holes, at the possible expense of having a larger span."
tkMessageBox.showinfo("Help! I need somebody...", helptxt)
def menu_buttons(self,buttons):
i = 1
while i < len(buttons):
if i != 1: # Draw a grey bar between sections
self.fr(TOP, width=32, height=5, bd = 4, bg="grey", expand=0)
self.endfr()
self.fr(TOP, width=70, expand=0)
parity = False
while i < len(buttons) and type(buttons[i]) != type('str'):
button = buttons[i]
if parity == False:
self.fr(TOP, expand = 0)
try:
p = PhotoImage(file="icons/" + button['image'])
b = self.bu(text=button['name'], image=p, width=32, command=button['command'])
b.pack(side=LEFT,padx=2,pady=2)
b.image = p
except:
b = self.bu(text=button['name'], width=32, command=button['command'])
b.pack(side=LEFT,padx=2,pady=2)
if parity == True:
self.endfr()
i = i + 1
parity = not parity
if parity == True:
self.endfr()
self.endfr()
i = i + 1
def subgraph_menu(self):
self.la(TOP,'both',0,'n',text = 'Insert Subgraph')
subgraphs = []
subgraphs.append({'name':'petersen',
'command':lambda: self.select_subgraph('petersen'),
'options':[['vertices/layer',6],['layers',2]]})
subgraphs.append({'name':'cycle',
'command':lambda: self.select_subgraph('cycle'),
'options':[['vertices/cycle',5],['layers',1]]})
subgraphs.append({'name':'grid',
'command':lambda: self.select_subgraph('grid'),
'options':[['rows',5],['columns',4]]})
subgraphs.append({'name':'star',
'command':lambda: self.select_subgraph('star'),
'options':[['vertices/cycle',5],['skip',2]]})
subgraphs.append({'name':'mobius',
'command':lambda: self.select_subgraph('mobius'),
'options':[['n',5]]})
subgraphs.append({'name':'triangles',
'command':lambda: self.select_subgraph('triangles'),
'options':[['n',5],['m',5], ['sheet(1),\ncylinder(2),\ntoroid(3)',1]]})
subgraphs.append({'name':'hexagons',
'command':lambda: self.select_subgraph('hexagons'),
'options':[['n',5],['m',5], ['sheet(1),\ncylinder(2),\ntoroid(3)',1]]})
subgraphs.append({'name':'partite',
'command':lambda: self.select_subgraph('partite'),
'options':[['sizes','3,4,3']]})
subgraphs.append({'name':'file',
'command':lambda: self.select_subgraph('file'),
'options':[]})
self.subgraph_buttons = []
parity = False
self.fr(TOP, width=70, expand=0)
for subgraph in subgraphs:
if parity == False:
self.fr(TOP, expand = 0)
try:
p = PhotoImage(file="icons/subgraphs/" + subgraph['name'] + ".gif")
b = self.bu(text=subgraph['name'], width=64, image=p, command=subgraph['command'])
b.pack(side=LEFT,padx=2,pady=2)
b.image = p
except:
b=self.bu(text=subgraph['name'], width=64, command=subgraph['command'])
b.name = subgraph['name']
b.options = subgraph['options']
self.subgraph_buttons.append(b)
if parity == True:
self.endfr()
parity = not parity
if parity == True:
self.endfr()
self.subgraph_entries = []
for i in range(5):
this_frame = self.fr(side=TOP, anchor=W)
# ## NOTE: if the next two lines aren't added, the first box expands full width. Not sure exactly why...
this_frame.pack_forget()
this_frame.pack(side=TOP, anchor=W)
# ##
self.subgraph_entries.append((self.la(LEFT,text=""),
self.en(LEFT,width = 4),
this_frame))
self.endfr()
self.subgraph_button_frame = self.fr(TOP)
self.bu(text="Insert Subgraph", command=self.insert_subgraph)
self.endfr()
self.endfr()
self.selected_subgraph = None
self.select_subgraph(subgraphs[0]['name'])
def makemenus(self):
menu=Menu(self)
self.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="New (ctrl-n)", command=self.new)
filemenu.add_command(label="Save (ctrl-s)", command=self.saveas)
filemenu.add_command(label="Save Sequence", command=self.savesequence)
filemenu.add_command(label="Open (ctrl-o)", command=self.open)
filemenu.add_command(label="Open sequence", command=self.opensequence)
filemenu.add_command(label="Print (ctrl-p)", command=self.printcanv)
filemenu.add_separator()
filemenu.add_command(label="Import Regular Graph File (first graph)", command=self.import_graph)
filemenu.add_command(label="Import GPGs", command=self.import_GPGs)
filemenu.add_command(label="Enter Shortcode", command=self.enter_shortcode)
filemenu.add_command(label="Enter GPGPermutation", command=self.enter_GPGpermutation)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=self.exit)
editmenu = Menu(menu)
menu.add_cascade(label="Edit", menu=editmenu)
editmenu.add_command(label="Cut (ctrl-x)", command=self.cut)
editmenu.add_command(label="Copy (ctrl-c)", command=self.copy)
editmenu.add_command(label="Paste (ctrl-v)", command=self.paste)
editmenu.add_separator()
editmenu.add_command(label="Undo (ctrl-z)", command=self.undo)
editmenu.add_command(label="Redo (ctrl-y)", command=self.redo)
labelmenu = Menu(menu)
menu.add_cascade(label="Labeling", menu=labelmenu)
labelmenu.add_command(label="Label Selected Vertices", command=self.label_message)
#labelmenu.add_command(label="Label (with reals) Selected Vertices", command=self.label_real_message)
labelmenu.add_command(label="Unlabel Selected Vertices (ctrl-u)", command=self.unlabel_vertex)
labelmenu.add_command(label="Clear Labeling", command=self.clear_labeling)
labelmenu.add_separator()
labelmenu.add_command(label="Auto-Label/Finish Labeling Graph", command=self.autolabel_message)
#labelmenu.add_command(label="Find Lambda Number (clears current labeling)", command=self.lambda_label_message)
labelmenu.add_command(label="Check Labeling", command=self.check_labeling)
labelmenu.add_command(label="Count Holes", command=self.count_holes)
graphmenu = Menu(menu)
menu.add_cascade(label="Graphs", menu=graphmenu)
graphmenu.add_command(label="Graph Complement", command=self.complement)
graphmenu.add_command(label="Line Graph", command=self.line_graph)
graphmenu.add_command(label="Box Everything", command=self.box_all)
graphmenu.add_separator()
graphmenu.add_command(label="Process Regular Graph File", command=self.process_regular_graph)
graphmenu.add_separator()
graphmenu.add_command(label="Get Graph Representations", command=self.get_graph_representations)
# graphmenu.add_command(label="Check Isomorphism", command=self.check_isomorphic)
helpmenu = Menu(menu)
menu.add_cascade(label="Help", menu=helpmenu)
helpmenu.add_command(label="Help (F1)", command=self.helptext)
helpmenu.add_command(label="About", command=self.abouttext)
def helptext(self, event=None):
basics = "Creating Vertices and Edges:\n\
To create vertices, simply shift-click on an empty spot.\n\
To create edges, either select multiple vertices, and right click and select 'connect', or...\n\
Hold down CTRL and click and drag. Release the mouse, and you will create the edge. Note that \n\
none, one, or both of the endpoints may be existing vertices.\n\
\n\
Editing the Edges:\n\
To wrap edges, first select the edges. Then either click the 'wrap' button from the left side, or\n\
right click and select 'wrap'.\n\
To curve edges, just drag an edge, and it will curve along your cursor (try it!)\n\
For a different method for curving, first select the edges. Then either click the 'curve' button from\n\
the left side, or right click and select 'curve'.\n\
Note that edges cannot be both curved and wrapped, and curving win take over if both are selected.\n\
\n\
Selecting and Moving:\n\
Click on an edge or vertex to select it. Click and drag a vertex to move it.\n\
Also, there is an 'area select' mode, where you can drag and select everything inside a rectangle. After\n\
you make your selection, you can click and drag the entire box, or resize by dragging the handles.\n\
You can always press 'Escape' to unselect everything, including any area select box.\n\
\n\
Cut, Copy and Paste:\n\
To cut, copy, or paste, use either the keyboard shortcuts, right click, use the button on the left menu, or select\n\
from the 'edit' drop down menu.\n\
After you click to 'paste', you must then click somewhere on the drawing area. The pasted graph can then be \n\
or resized via the box methods.\n"
more_advanced = "Labeling:\n\
To label, either right click, or select 'label' from the top drop-down menu.\n\
You can label with either reals or integers using the same dialog.\n\
Note that real numbers are much slower in solving, due to more complex representation in the computer.\n\
\n\
Physics Mode:\n\
This can now be started and stopped via the buttons on the left menu or by pressing Ctrl-H.\n\
Press up and down to control vertex spacing (pushing away from each other) \n\
and left and right to control attraction along edges\n\
\n\
Key Shortcuts:\n\
Most key shortcuts are noted in the top drop down menus. For brevity, we only include the others here.\n\
\n\
Ctrl-A: Select All\n\
Ctrl-E: Select Edges\n\
Ctrl-B: Select Vertices\n\
\n\
Delete: Delete Selected\n\
Escape: Deselect All\n\
F1: Help\n\
Ctrl-<number>: complete L(2,1)-Labeling with minimum lambda <number> or find a k-conversion set with <number> vertices\n\
Ctrl-F: finish k-conversion with already labeled vertices\n\
Ctrl-0: step through one step of the k-conversion process\n\
\n\
Right Click:\n\
You can right click on the drawing area to access commonly used functions from a pop up menu.\n\
\n\
Auto-Update:\n\
You should always have the latest version!\n\
Each time the program starts, it tries to connect to the internet, and downloads the latest version of itself.\n\
This is meant to be very unobtrusive, but a useful way to provide quick updates and bug fixes.\n\
Although the delay shouldn't be noticeable, it this becomes an issue, there is a simple way to disable it.\n\
(Note: Is is not recommended to disable this!)\n\
\n\
Easy Install:\n\
As a side effect of the auto-update, the program is a snap to install. Just double click on the update file (start.py),\n\
and the entire program is downloaded to the folder containing start.py.\n"
about_the_menus = "Menus/Parts of the GUI:\n\
Simple Top Menu\n\
Key shortcuts are given in the drop down top menus.\n\
\n\
Buttons on the Left Menu\n\
File Commands (New, Open, Save, and Print)\n\
Edit Commands (Undo, Redo, Cut, Copy, and Paste)\n\
Edge Commands (Curve, Connect, Wrap)\n\
Physics Commands (Start, Stop)\n\
Product Commands (Cartesian, Tensor, Strong)\n\
-make graph, click product button to store first graph. alter or make a new, second graph, press product button to create the product of the first and second graph\n\
\n\
Insert Subgraph Menu\n\
You can insert subgraphs without clearing the existing graph.\n\
\n\
Bottom Bar\n\
Can change of labeling constraints. (single number - k conversion, list of numbers (2,1 or 1,0) L(n,m) labeling, M - majority conversion)\n\
Can change hole algorithm.\n\
Easy setup or change grid for snapping."
tkMessageBox.showinfo("Basic Help (P1/3)", basics)
tkMessageBox.showinfo("More Advanced Help (P2/3)", more_advanced)
tkMessageBox.showinfo("An overview of the Menus (P3/3)", about_the_menus)
def abouttext(self, event=None):
abouttxt = "Olin Graph Program\n\
\n\
Created by Jon Cass, Cody Wheeland, and Matthew Tesch\n\
\n\
Email iamtesch@gmail.com for feature requests, questions, or help."
tkMessageBox.showinfo("About", abouttxt)
# #####################################################################################################
# File operations (New, Open, Save, Import, Print, Exit):
# #####################################################################################################
def new(self, event=None):
self.querysave()
if not self.cancelled:
self.clear()
self.backups = []
self.redos = []
self.cancelled=False
self.control_up()
def open(self, event=None):
#self.querysave()
if not self.cancelled:
file = tkFileDialog.askopenfile(parent=self,mode='rb',title='Choose a file')
if file != None:
self.backups = []
self.redos = []
self.graph = pickle.load(file)
file.close()
self.redraw()
self.cancelled=False
self.control_up()
def opensequence(self, event=None):
#self.querysave()
if not self.cancelled:
file = tkFileDialog.askopenfile(parent=self,mode='rb',filetypes=[('Graph Sequence','*.graphs')],title='Choose a file')
if file != None:
self.backups = []
self.redos = pickle.load(file)
self.graph = self.redos[len(self.redos)-1]
file.close()
self.redraw()
self.cancelled=False
self.control_up()
def saveas(self, event=None, fileName=None):
if not self.cancelled:
if not fileName:
fileName = tkFileDialog.asksaveasfilename(parent=self,filetypes=myFormats,title="Save the graph as...")
if len(fileName ) > 0:
if ('.' in fileName and '.graph' not in fileName):
## try:
self.draw_to_file(fileName)
## except:
## tkMessageBox.showinfo("You need PIL!", "It looks like you don't have PIL.\nYou need the Python Imaging Library to save to an image!\nhttp://www.pythonware.com/products/pil/")
else:
if '.graph' not in fileName:
fileName += '.graph'
f=file(fileName, 'wb')
pickle.dump(self.graph,f)
f.close()
self.cancelled=False
self.control_up()
def savesequence(self, event=None, fileName=None):
if not self.cancelled:
if not fileName:
fileName = tkFileDialog.asksaveasfilename(parent=self,filetypes=[('Graph Sequence','*.graphs')],title="Save the graph sequence as...")
if len(fileName ) > 0:
if '.graphs' not in fileName:
fileName += '.graphs'
f=file(fileName, 'wb')
pickle.dump(self.redos,f)
f.close()
self.cancelled=False
self.control_up()
def querysave(self):
self.message("Save?", "Would you like to save?", self.saveas, "yesnocancel")
self.control_up()
def draw_to_file(self, filename):
width=float(self.canvas.winfo_width())
height=float(self.canvas.winfo_height())
image1 = Image.new("RGB", (width, height), (255,255,255))
draw = ImageDraw.Draw(image1)
draw=self.graph.draw_to_file(draw,width,height)
image1.save(filename)
def import_graph(self):
file = tkFileDialog.askopenfile(parent=self,mode='rb',title='Choose a file')
if file != None:
self.clear()
self.graph = Graph(labelingConstraints=self.graph.labelingConstraints)
if file.name.endswith('.scd'):
nums=self.readshortcode(file)
for graph in self.graph.loadshortcode(nums, all=False):
self.graph=graph
else:
adjlist = []
while file:
line = file.readline()
if line[0:5] == "Graph":
line = file.readline()
line = file.readline()
while line[0:5] != "Taill":
line = line.split()
line.remove(":")
for i in range(len(line)):
line[i] = int(line[i])
adjlist.append(line)
line = file.readline()
break
self.graph.loadadjlist(adjlist)
file.close()
self.redraw()
self.control_up()
def import_GPGs(self):
file = tkFileDialog.askopenfile(parent=self,mode='r',title='Choose a file')
if file !=None:
self.clear()
numgraphs=sum(1 for line in file)
file.seek(0)
graphcounter=0;
rows=5
cols=5
for i in xrange(1,5):
if i*i>numgraphs:
rows=cols=i
break
spacing=20
canvas_width=self.canvas.winfo_width()
canvas_height=self.canvas.winfo_height()
w=(canvas_width-spacing*(cols+1))/cols
h=(canvas_height-spacing*(rows+1))/rows
for line in file:
nums=list(line.strip())
for i in xrange(len(nums)):
nums[i]=int(nums[i])
g=Graph(labelingConstraints=self.graph.labelingConstraints)
g.loadGPG(nums)
labels=[]
verts=g.get_vertices()
edges=g.edges
constraints=g.labelingConstraints
if type(constraints)==type([]):
labels = graphmath.auto_label(verts, edges, constraints, 5, self.holes_mode.get())
else:
labels=graphmath.finishklabeling(verts,edges,constraints)
i=0
for vert in g.get_vertices():
vert.label=labels[i]
vert.x*=w/400.
vert.y*=h/400.
col=graphcounter%cols
row=(graphcounter%(rows*cols))/rows
x=col*w+w/2+spacing*(col+1)-canvas_width/2
y=row*h+h/2+spacing*(row+1)-canvas_height/2
vert.x+=x
vert.y+=y
self.graph.add_vertex(vert)
i+=1
for edge in g.edges:
self.graph.edges.append(edge)
graphcounter+=1
if graphcounter%(rows*cols)==0:
self.saveas(fileName=file.name[:-4]+'-'+str(graphcounter/(rows*cols))+'.png')
self.clear()
self.saveas(fileName=file.name[:-4]+'-'+str(graphcounter/(rows*cols)+1)+'.png')
file.close()
self.redraw()
def enter_shortcode(self):
res = tkSimpleDialog.askstring("Enter Shortcode", "Enter Shortcode to load:")
res=res.split(',')
if len(res)==1:
res=res[0].split()
if len(res)==1:
num=int(res[0])
res=[]
while num>0:
res.append(num%10)
num/=10
if res[0]=='0':
del res[0]
for i in xrange(len(res)):
res[i]=int(res[i])
res.insert(0,max(res)) #the number of vertices will be the highest number in the edge-list
res.insert(1,len(res)*2/res[0])
res.insert(2,0)
for graph in self.graph.loadshortcode(res, all=False):
self.graph=graph
self.redraw()
def enter_GPGpermutation(self):
res = tkSimpleDialog.askstring("Enter Permutation", "Enter permutation to load:")
res=res.split(',')
if len(res)==1:
res=res[0].split()
if len(res)==1:
num=res
res=[]
for i in xrange(len(num)):
res.append(int(num[i]))
for i in xrange(len(res)):
res[i]=int(res[i])
print res
self.graph.loadGPG(res)
self.redraw()
def process_regular_graph(self):
infile = tkFileDialog.askopenfile(parent=self,mode='rb',title='Choose a file')
outfilename = tkFileDialog.asksaveasfilename(parent=self,title="Save the output as...")
if len(outfilename) > 0:
outfile=file(outfilename, 'w')
else:
outfile=file('out.txt', 'w')
self.cancelled=False
if infile != None:
# self.holes_mode.set("minimize") # I really don't think this should be here, or else it resets every time we process. We want to process with the current settings.
tempgraph = deepcopy(self.graph)
self.clear()
self.graph = Graph(labelingConstraints=self.graph.labelingConstraints) # we want to keep the existing labeling constraints here
if infile.name.endswith('.scd'):
nums=self.readshortcode(infile)
for graph in self.graph.loadshortcode(nums, all=True):
self.graph=graph
self.clear_labeling()
lnum = self.autolabel(0,quiet=True)
outfile.write("Lambda: "+str(lnum)+"\r\n")
holes = self.count_holes(quiet=True)
outfile.write("Holes: "+str(holes)+"\r\n")
else:
line = 'beginning' # some value so the while loop goes at least once...
while line != '':
line = infile.readline()
if line[0:5] == "Graph":
line = infile.readline()
line = infile.readline()
adjlist = []
while line[0:5] != "Taill":
line = line.split()
line.remove(":")
for i in range(len(line)):
line[i] = int(line[i])
adjlist.append(line)
line = infile.readline()
self.graph.loadadjlist(adjlist)
self.clear_labeling()
lnum = self.autolabel(0,quiet=True)
outfile.write("Lambda: "+str(lnum)+"\r\n")
holes = self.count_holes(quiet=True)
outfile.write("Holes: "+str(holes)+"\r\n")
self.graph = tempgraph
infile.close()
outfile.close()
self.redraw()
def get_graph_representations(self):
adj=graphmath.adjacencymatrix(self.graph.get_vertices(),self.graph.edges)
adjmessage= "Adjacency Matrix\n---------------------\n"
for i in xrange(len(adj)):
adjmessage+=str(adj[i])+"\n"
spm=graphmath.shortestpathmatrix(self.graph.get_vertices(),self.graph.edges)
spmmessage= "Shortest Path Matrix\n------------------------\n"
for i in xrange(len(spm)):
spmmessage+=str(spm[i])+"\n"
scmessage="Shortcode\n------------\n"
if graphmath.is_regular(self.graph.get_vertices(),self.graph.edges):
scmessage+=str(graphmath.generate_shortcode(self.graph.get_vertices(),self.graph.edges))
else:
scmessage+="The graph is not regular.\nA shortcode doesn't make sense."
if len(self.graph.get_vertices())<10:
tkMessageBox.showinfo("Graph Representations:",adjmessage+"\n"+spmmessage+"\n"+scmessage)
else:
tkMessageBox.showinfo("Graph Representations (P1/3):",adjmessage)
tkMessageBox.showinfo("Graph Representations (P2/3):",spmmessage)
tkMessageBox.showinfo("Graph Representations (P3/3):",scmessage)
#reads a shortcode file, returns list with the numeric elements of the file
#first two elements are number of vertices and the regularity of the graph
#shortcode is for k-regular graphs on n-vertices, produced by genreg program
def readshortcode(self, f, full=True):
name=os.path.split(f.name)[-1]
name=name.split('_')
k=int(name[1])
n=int(name[0])
s=f.read(1)
nums=[n, k]
while s:
nums.append(ord(s))
s=f.read(1)
if not full and len(nums)==2+n*k/2:
break
return nums
def printcanv(self, event=None):
self.canvas.postscript(file="print.ps")
os.system("PrFile32.exe /q print.ps")
def cancel(self):
self.cancelled=True
def exit(self):
self.querysave()
if not self.cancelled:
sys.exit(0)
self.cancelled=False
# #####################################################################################################
# Edit Operations: Undo, Redo, Copy, Paste, Connect, Delete, etc.
# #####################################################################################################
def curve_selected(self, event=None):
for edge in self.graph.edges:
if edge.selected:
edge.curved = not edge.curved
self.redraw()
# def curve_height(self, event):
# step = 0
# if event.keysym == "Up":
# step = 1
# if event.keysym == "Down":
# step = -1
# for edge in self.graph.edges:
# if edge.selected:
# if not edge.curved:
# edge.curved = True
# edge.height = edge.height + step
# self.redraw()
def wrap_selected(self, event=None):
for edge in self.graph.edges:
if edge.selected:
edge.wrap = not edge.wrap
edge.curved = False
self.redraw()
# Call this function before any operation that you want to be "undone". It saves the state of the graph at that point.
# (For example, the start of all clicks, new vertices, deletes, etc.)
def registerwithundo(self):
self.redos = []
self.backups.append(deepcopy(self.graph))
if len(self.backups)>MAXUNDO:
self.backups.pop(1)
def undo(self, event=None):
if len(self.backups) == 0:
return
self.redos.append(deepcopy(self.graph))
self.graph = self.backups.pop()
self.redraw()
def redo(self, event=None):
if len(self.redos) == 0:
return
self.backups.append(deepcopy(self.graph))
self.graph = self.redos.pop()
self.redraw()
def selection(self):
sel = [o for o in self.graph.get_vertices() + self.graph.edges if o.selected]
if sel == []:
return None
return sel
def select_all(self, event=None):
self.select_edges(all=True)
self.select_vertices(all=True)
def select_edges(self, event=None, all=False):
self.registerwithundo()
if all:
for e in self.graph.edges:
e.selected=True
else:
for v in self.graph.get_vertices():
v.selected=False
self.redraw()
def select_vertices(self, event=None,all=False):
self.registerwithundo()
if all:
for v in self.graph.get_vertices():
v.selected=True
else:
for e in self.graph.edges:
e.selected=False
self.redraw()
def deselect_all(self, event=None):
self.registerwithundo()
self.box = None
self.deselect_edges()
self.deselect_vertices()
def deselect_edges(self, event=None):
self.registerwithundo()
for e in self.graph.edges:
e.selected=False
self.redraw()
def deselect_vertices(self, event=None):
self.registerwithundo()
for v in self.graph.get_vertices():
v.selected=False
self.redraw()
def invert_selected(self, event=None):
self.registerwithundo()
for v in self.graph.get_vertices():
v.selected=not v.selected
for e in self.graph.edges:
e.selected=not e.selected
self.redraw()
# Deprecated and unneeded. Delete this function?
# def delete_selected_vertices(self, event=None):
# self.registerwithundo()
# vr = []
# for v in self.graph.get_vertices():
# if v.selected:
# vr.append(v)
# for e in self.graph.edges:
# if v in e.vs:
# er.append(e)
# for e in er:
# try:
# self.graph.edges.remove(e)
# except:
# pass
# for v in vr:
# try:
# self.graph.remove_vertex(v)
# except:
# pass
# self.redraw()
def delete_selected(self, event=None):
self.registerwithundo()
er = []
vr = []
for e in self.graph.edges:
if e.selected:
er.append(e)
for v in self.graph.get_vertices():
if v.selected:
vr.append(v)
for e in self.graph.edges:
if v in e.vs:
er.append(e)
for e in er:
try:
self.graph.edges.remove(e)
except:
pass
for v in vr:
try:
self.graph.remove_vertex(v)
except:
pass
self.box = False
self.redraw()
def connect(self, event=None):
self.registerwithundo()
self.graph.connect()
self.redraw()
def copy(self, event=None, delete=False):
selectedverts = [v for v in self.graph.get_vertices() if v.selected]
self.copied_verts = []
self.copied_edges = []
for v in selectedverts:
self.copied_verts.append((v.x,v.y,v.label))
for e in self.graph.edges:
if e.vs[0] in selectedverts and e.vs[1] in selectedverts and e.selected:
self.copied_edges.append(((e.vs[0].x,e.vs[0].y),(e.vs[1].x,e.vs[1].y),[e.wrap,e.curved,e.height,e.direction]))
if delete==True:
self.delete_selected()
else:
self.deselect_all()
def cut(self, event=None):
self.registerwithundo()
self.copy(event=event, delete=True)
def paste(self, event=None):
self.registerwithundo()
self.pasting = True
def shift_down(self, event=None):
self.shift_pressed=True
def shift_up(self, event=None):
self.shift_pressed=False
def choose_color(self):
self.registerwithundo()
vert_selected=False
if len([v for v in self.graph.get_vertices() if v.selected])>0:
color=tkColorChooser.askcolor(color=self.graph.get_vertices()[0].color,title="Choose a Vertex Color")[1]
for v in [v for v in self.graph.get_vertices() if v.selected]:
if color!=None:
v.color=color
if v.label!="NULL":
vert_selected=True
self.redraw();
if len([edge for edge in self.graph.edges if edge.selected])>0:
color=tkColorChooser.askcolor(color=self.graph.edges[0].color,title="Choose an Edge Color")[1]
for edge in [edge for edge in self.graph.edges if edge.selected]:
edge.color=color
self.redraw();
if vert_selected:
color=tkColorChooser.askcolor(color=self.graph.get_vertices()[0].lcolor,title="Label Color")[1]
if color!=None:
for v in [v for v in self.graph.get_vertices() if v.selected]:
v.lcolor=color
self.redraw()
def pick_size(self, event=None):
vert_selected=False
if len([v for v in self.graph.get_vertices() if v.selected])>0:
size=int(tkSimpleDialog.askstring("Pick Size", "What's a good size for the selected vertices?"))
if size!=None:
size=int(size)
for v in [v for v in self.graph.get_vertices() if v.selected]:
if size!=None:
v.size=size
if v.label!="NULL":
vert_selected=True
self.redraw();
if len([edge for edge in self.graph.edges if edge.selected])>0:
size=tkSimpleDialog.askstring("Pick Size", "What's a good width for the selected edges?")
if size!=None:
size=int(size)
for edge in [edge for edge in self.graph.edges if edge.selected]:
edge.size=size
self.redraw();
if vert_selected:
size=tkSimpleDialog.askstring("Pick Size", "What's a good width for the labels?")
if size!=None:
size=int(size)
for v in [v for v in self.graph.get_vertices() if v.selected]:
v.lsize=size
self.redraw()
def select_shape(self, event=None):
shape=-1
for v in [v for v in self.graph.get_vertices() if v.selected]:
if shape==-1:
if type(v.shape)==type('A'):
shape=0
elif v.shape==8:
names=['Harold','Luke','Connor','Paul','Zachary','Dr. Adams','Dr. Troxell']
shape=random.choice(names)
else:
shape=(v.shape+1)
if shape==7:
shape+=1
v.shape=shape
self.redraw()
# #####################################################################################################
# Whole Graph Commands: Complement, Line Graph, etc. Anything that changes/affects the current graph. (In the spirit of complement, etc, but not "add new subgraph")
# #####################################################################################################
def complement(self):
self.registerwithundo()
comp = Graph()
vertices = self.graph.get_vertices()
comp.vertices = vertices
comp.edges = []
for v1 in vertices:
for v2 in vertices:
if v1 != v2:
found = 0
for e in self.graph.edges:
if v1 in e.vs and v2 in e.vs:
found = 1
break
if not found:
comp.edges.append(Edge(v1,v2))
self.graph.edges.append(Edge(v1,v2))
self.graph = comp
self.redraw()
def line_graph(self):
self.registerwithundo()
lg = Graph(edges = [])
i = 0
lgverts = []
for e1 in self.graph.edges:
v = Vertex((.5*e1.vs[0].x+.5*e1.vs[1].x, .5*e1.vs[0].y+.5*e1.vs[1].y))
lgverts.append(v)
lg.add_vertex(v)
for j in range(i):
e2 = self.graph.edges[j]
if e1 != e2:
if (e1.vs[0] in e2.vs) or (e1.vs[1] in e2.vs):
lg.edges.append(Edge(lgverts[i],lgverts[j]))
i = i + 1
self.graph = lg
self.redraw()
# #####################################################################################################
# Product Commands: Commands to create products of graphs
# #####################################################################################################
def graph_product(self, type, event=None):
self.registerwithundo()
if (len(self.product_verts)!=0):
product_adj=graphmath.adjacencymatrix(self.product_verts,self.product_edges)
verts = self.graph.get_vertices()
edges = self.graph.edges
product_adj2=graphmath.adjacencymatrix(verts,edges)
adjmat=[]
if (type=='cartesian'):
adjmat=graphmath.cartesian_product(product_adj,product_adj2)
elif(type=='tensor'):
adjmat=graphmath.tensor_product(product_adj,product_adj2)
elif(type=='strong'):
adjmat=graphmath.strong_product(product_adj,product_adj2)
else:
print "uh oh. that not a graph product type."
adjmat=graphmath.cartesian_product(product_adj,product_adj2)
self.graph = Graph(labelingConstraints =self.graph.labelingConstraints)
self.graph.loadadjmatrix(adjmat,len(self.product_verts), len(verts),self.product_verts, verts )
self.product_verts=[]
self.product_edges=[]
else:
self.product_verts=self.graph.get_vertices()[:]
self.product_edges=self.graph.edges[:]
self.redraw()
# #####################################################################################################
# Labeling Commands: Commands to label, change labeling constraints, etc.
# #####################################################################################################
def autolabel_easy(self, event=None):
if type(self.graph.labelingConstraints)==type([]):
if self.check_to_clear():
self.clear_labeling()
self.autolabel(int(event.keysym))
else:
if int(event.keysym)!=0:
self.autolabel(int(event.keysym))
else:
self.stepthrough()
self.control_up()
def check_to_clear(self):
for vertex in self.graph.vertices:
if vertex.label == 'NULL':
return False
self.control_up()
return True
# def label_message(self, event=None):
# self.message("Label Vertices", "What would you like to label these vertices?", self.label_vertex)
# Note: label_message now takes care of real and integers; integers are transformed to int type in label_vertex.
def label_message(self, event=None):
self.message("Label Vertices", "What would you like to label these vertices?", self.label_vertex, type="Decimal")
self.control_up()
def autolabel_message(self):
self.message("Auto-Label Graph", "What is the minimum lambda-number for this graph?", self.autolabel)
self.control_up()
# def lambda_label_message(self):
# self.clear_labeling()
# self.holes_mode.set("allow")
# lnum = self.autolabel(0,quiet=True)
# labeltxt = ""
# for labConst in self.graph.labelingConstraints:
# labeltxt += str(labConst) + ","
# labeltxt = labeltxt[:-1]
# tkMessageBox.showinfo("Labeling Span", "The L(" + labeltxt + ") lambda number for this graph is " + str(lnum) + ".")
def constraints_message(self):
res = ''
while res == '':
res = tkSimpleDialog.askstring("Change Labeling Constraints", \
"Please enter new labeling constraints.\n" \
+"Enter a single value for K conversion ('3' for K3).\n" \
+"M - majority, MS - strong majority.\n" \
+"comma deliminated list of values for L(m,n,...) labeling ('2,1' for L(2,1) labeling)")
self.change_constraints(res)
self.control_up()
def change_constraints(self, newconstraints):
backup = self.graph.labelingConstraints
if (len(newconstraints)>1 and newconstraints[0].isdigit()):
self.graph.labelingConstraints = []
try:
for label in newconstraints.split(','):
label = Decimal(label)
if label == int(label):
self.graph.labelingConstraints.append(int(label))
else:
self.graph.labelingConstraints.append(label)
except:
tkMessageBox.showinfo("Error", "The labeling constraints were input in a bad form! Using old constraints.")
self.graph.labelingConstraints = backup
labeltxt = "Labeling Constraints: L("
for labConst in self.graph.labelingConstraints:
labeltxt += str(labConst) + ","
labeltxt = labeltxt[:-1]
labeltxt += ")"
self.constraintstxt.set(labeltxt)
else:
self.graph.labelingConstraints = 0
try:
label=int(newconstraints[0])
self.graph.labelingConstraints=label
labeltxt = "Labeling Constraints: K"+ str(label)
except:
if newconstraints.upper()[0]=='M':
if (len(newconstraints)>1 and newconstraints.upper()[1]=='S'):
self.graph.labelingConstraints=-2
labeltxt = "Labeling Constraints: Strong Majority"
else:
self.graph.labelingConstraints=-1
labeltxt = "Labeling Constraints: Majority"
else:
tkMessageBox.showinfo("Error", "The labeling constraints were input in a bad form! Using old constraints.")
self.graph.labelingConstraints = backup
self.constraintstxt.set(labeltxt)
self.control_up()
def label_vertex(self, label):
self.registerwithundo()
if int(label) == label:
label = int(label)
for v in [v for v in self.graph.get_vertices() if v.selected]:
v.label=label
self.redraw()
def unlabel_vertex(self, event=None):
self.registerwithundo()
for v in [v for v in self.graph.get_vertices() if v.selected]:
v.label='NULL'
self.redraw()
def clear_labeling(self, event=None):
self.registerwithundo()
for v in self.graph.get_vertices():
v.label='NULL'
self.redraw()
def autolabel(self, minlambda, quiet = False):
self.registerwithundo()
verts = self.graph.get_vertices()
edges = self.graph.edges
constraints = self.graph.labelingConstraints
labels=[]
if type(constraints)==type([]):
labels = graphmath.auto_label(verts, edges, constraints, minlambda, self.holes_mode.get())
else:
if minlambda==-1:
labels=graphmath.finishklabeling(verts,edges,constraints)
else:
labels=graphmath.find_conversion_set(verts,edges,constraints, minlambda)
##put the control-2-3-4-5-etc code call here
if labels == "RealError":
tkMessageBox.showinfo("Holes and Reals don't mix!", "Don't select 'minimize' or 'no holes' with real labels or constraints; this doesn't make sense!")
self.control_up()
return
if labels == False:
tkMessageBox.showinfo("Bad Partial Labeling", "The partial labeling is incorrect. Please correct before auto-finishing the labeling.")
self.control_up()
return
for i in range(len(verts)):
verts[i].label = labels[i]
(lmin,lmax,complete)=graphmath.labeling_difference(verts)
self.redraw()
lnum = lmax - lmin
if (not quiet):
self.control_up()
if type(self.graph.labelingConstraints)==type([]):
tkMessageBox.showinfo("Labeling Span", "The labeling span for this coloring is " + str(lnum) + ".\n Largest label: " + str(lmax) + "\n Smallest label: " + str(lmin))
else:
s='The graph is completely covered!'
if not complete:
s='The graph is NOT completely covered.'
tkMessageBox.showinfo("Conversion Time", "The conversion time for this coloring is " + str(lnum) + ".\n Largest time: " + str(lmax) + "\n Smallest time: " + str(lmin)+"\n"+s)
return lnum
def check_labeling(self,quiet = False):
verts = self.graph.get_vertices()
edges = self.graph.edges
constraints = self.graph.labelingConstraints
res = graphmath.check_labeling(verts,edges,constraints)
if res == True:
if not quiet:
self.control_up()
tkMessageBox.showinfo("Correct Labeling", "The labeling is correct.")
return True
else: # res is (False,(i,j)), where 'i' and 'j' are the bad vertices
if not quiet:
self.control_up()
self.deselect_vertices()
verts[res[1][0]].selected = True
verts[res[1][1]].selected = True
tkMessageBox.showwarning("Bad labeling", "The selected vertices appears to be wrong.")
self.redraw()
return False
#shouldn't work with real labelings! TODO: check this! (doesn't break, but shouldn't let you)
def count_holes(self,quiet = False):
verts = self.graph.get_vertices()
lmax = 0
for v in verts:
if v.label > lmax:
lmax = v.label
numholes = 0
for i in range(lmax):
found = 0
for v in verts:
if v.label == i:
found = 1
break
if not found:
numholes += 1
if not quiet:
control_up()
tkMessageBox.showinfo("Number of Holes", "The number of holes in this labeling is " + str(numholes) + ".")
return numholes
def easy_label(self, event=None):
self.label_vertex(int(event.keysym))
#stepthrough one step in k conversion process
def stepthrough(self):
verts=self.graph.get_vertices()
changelist=graphmath.stepthrough(verts,graphmath.adjacencymatrix(verts,self.graph.edges), self.graph.labelingConstraints)
if len(changelist)!=0:
self.registerwithundo()
(lmin,lmax, complete)=graphmath.labeling_difference(verts)
for vertnum in changelist:
verts[vertnum].label=lmax+1
return complete
else:
return True
def finishklabeling(self,event=None):
if type(self.graph.labelingConstraints)!=type([]):
self.autolabel(-1)
# #####################################################################################################
# Gui Bindings: Mouse controlled-commands and helper functions
# #####################################################################################################
def find_clicked_on(self, event):
#TODO: ensure this returns a vertex or edge, not a selection circle or something!
# for v in self.graph.get_vertices():
# if x+10 > v.x > x-10 and y+10 > v.y > y-10:
# return v
#TODO: how about just finding anthing in "self.canvas.find_overlapping"???
self.closest=self.canvas.find_closest(event.x, event.y)
try:
self.closest=self.closest[0]
except:
return None
if self.closest in self.canvas.find_overlapping(event.x-10, event.y-10, event.x+10, event.y+10):
for h in self.handles.keys():
if self.closest == h:
return h
for v in self.graph.get_vertices():
if self.closest == v.circle:
return v
if self.shift_pressed and self.closest==v.text:
return v
for e in self.graph.edges:
if self.closest == e.line or (e.wrap and self.closest == e.altline):
return e
return None
def right_clicked(self, e):
# def rClick_Copy(e, apnd=0):
#e.widget.event_generate('<Control-c>')
# print "copy"
#event.widget.focus()
nclst=[
('Connect Selected', self.connect),
('----', None),
('Cut', self.cut),
('Copy', self.copy),
('Paste', self.paste),
('----', None),
('Label Selected', self.label_message),
('Unlabel Selected', self.unlabel_vertex),
('----', None),
('Wrap Edges', self.wrap_selected),
('Curve Edges', self.curve_selected),
('----', None),
('Change Cursor', self.change_cursor)
#('Copy', lambda e=e: rClick_Copy(e)),
#('Paste', lambda e=e: rClick_Paste(e)),
]
rmenu = Menu(None, tearoff=0, takefocus=0)
# cas = {}
# cascade = 0
for (txt, cmd) in nclst:
if txt == "----":
rmenu.add_separator()
else:
rmenu.add_command(label=txt, command=cmd)
# if txt.startswith('>>>>>>') or cascade:
# if txt.startswith('>>>>>>') and cascade and cmd == None:
# #done cascade
# cascade = 0
# rmenu.add_cascade( label=icmd, menu = cas[icmd] )
# elif cascade:
# if txt == ' ------ ':
# cas[icmd].add_separator()
# else: cas[icmd].add_command(label=txt, command=cmd)
# else: # start cascade
# cascade = 1
# icmd = cmd[:]
# cas[icmd] = Tk.Menu(rmenu, tearoff=0, takefocus=0)
# else:
# if txt == ' ------ ':
# rmenu.add_separator()
# else: rmenu.add_command(label=txt, command=cmd)
#rmenu.entryconfigure(0, label = "redemo", state = 'disabled')
rmenu.tk_popup(e.x_root+10, e.y_root+10,entry="0")
return "break"
def clicked(self, event):
#TODO: create "clicked flags" instead of individual variables?
self.registerwithundo()
self.clicked_time = time.time()
self.clicked_pos = (event.x, event.y)
self.dragging = False
self.clicked_on = self.find_clicked_on(event)
self.clicked_create_edge = self.control_pressed
self.clicked_in_box = False
self.resize = None
if self.box:
center = self.get_center()
b0 = self.box[0]+center[0]
b1 = self.box[1]+center[1]
b2 = self.box[2]+center[0]
b3 = self.box[3]+center[1]
xcoords = (b0,b2)
ycoords = (b1,b3)
if self.clicked_on in self.handles.keys():
self.resize = ['m','m']
if self.handles[self.clicked_on][0] == b0:
self.resize[0] = 'l'
elif self.handles[self.clicked_on][0] == b2:
self.resize[0] = 'r'
if self.handles[self.clicked_on][1] == b1:
self.resize[1] = 'l'
elif self.handles[self.clicked_on][1] == b3:
self.resize[1] = 'r'
center = self.get_center()
for v in self.surrounded_vertices:
try:
#v.xnorm = (v.x-self.box[0]+center[0])/(self.box[2]-self.box[0])
v.xnorm = (v.x-self.box[0])/(self.box[2]-self.box[0])
except:
v.xnorm = 0
try:
#v.ynorm = (v.y-self.box[1]+center[1])/(self.box[3]-self.box[1])
v.ynorm = (v.y-self.box[1])/(self.box[3]-self.box[1])
except:
v.ynorm = 0
elif min(xcoords) < event.x < max(xcoords) and min(ycoords) < event.y < max(ycoords):
self.clicked_in_box = (event.x, event.y)
else:
self.box = False
#self.redraw()
# if self.click_mode == "path":
# oldtime = self.clickedtime
# self.clickedtime = time.time()
# if self.clickedtime-oldtime < .25: # Double click!
# self.graph.lastvertex = None
# return
# single click...
# v = None
# for vert in self.graph.get_vertices():
# if x+10 > vert.x > x-10 and y+10 > vert.y > y-10:
# v = vert
# break
# if v == None:
# v = Vertex((x, y))
# self.graph.add_vertex(v)
# if self.graph.lastvertex != None:
# self.graph.connect((v, self.graph.lastvertex))
# self.graph.lastvertex = v
# self.redraw()
def move_box(self, event):
dx = event.x - self.clicked_in_box[0]
dy = event.y - self.clicked_in_box[1]
for v in self.surrounded_vertices:
v.x += dx
v.y += dy
self.box[0] += dx
self.box[1] += dy
self.box[2] += dx
self.box[3] += dy
self.clicked_in_box = (event.x, event.y)
def resize_box(self, event):
center = self.get_center()
if self.resize[0] == 'l':
self.box[0] = event.x - center[0]
elif self.resize[0] == 'r':
self.box[2] = event.x - center[0]
if self.resize[1] == 'l':
self.box[1] = event.y - center[1]
elif self.resize[1] == 'r':
self.box[3] = event.y - center[1]
for v in self.surrounded_vertices:
v.x = v.xnorm*(self.box[2]-self.box[0])+self.box[0]
v.y = v.ynorm*(self.box[3]-self.box[1])+self.box[1]
def dragged(self, event):
center = self.get_center()
x = event.x - center[0]
y = event.y - center[1]
if self.dragging or (time.time() - self.clicked_time > .15):
self.dragging = True
if self.clicked_create_edge:
if self.control_pressed:
try:
self.canvas.delete(self.drag_shape)
except:
pass
self.drag_shape = self.canvas.create_line(self.clicked_pos[0], self.clicked_pos[1], event.x, event.y, width=4, fill="blue")
return
elif self.box:
if self.resize:
self.resize_box(event)
if self.clicked_in_box:
self.move_box(event)
self.redraw()
else: #no box
if self.clicked_on in self.graph.edges: # If we clicked on an edge
#do "drag-curving" logic/trig here.
self.clicked_on.curve_through(x,y)
self.redraw()
elif self.clicked_on in self.graph.get_vertices(): #If we clicked and dragged a vertex...
if self.shift_pressed:
self.clicked_on.lx=x-self.clicked_on.x
self.clicked_on.ly=y-self.clicked_on.y
elif self.snap_mode.get() != 'none': #snap-move vertex
self.snap(event, self.clicked_on)
else: #move vertex
self.clicked_on.x = x
self.clicked_on.y = y
self.redraw()
else: #if we are drag-selecting
try:
self.canvas.delete(self.drag_shape)
except:
pass
self.drag_shape = self.canvas.create_rectangle(self.clicked_pos[0], self.clicked_pos[1], event.x, event.y, width=2, outline="blue", tags="bounding box")
# elif self.clickedon in self.graph.get_vertices():
# if self.drag_mode == "single" or self.drag_mode == "selected":
# if self.snap_on:
# dx = event.x - self.clickedon.x
# dy = event.y - self.clickedon.y
#
# else:
# dx = x - self.clickedon.x
# dy = y - self.clickedon.y
# self.redraw()
# if self.drag_mode == "selected":
# for v in self.graph.get_vertices():
# if v.selected and v != self.clickedon:
# if self.snap_on:
# e = FakeEvent(v.x + dx,v.y + dy)
# self.snap(e, v)
# else:
# v.x += dx
# v.y += dy
# self.redraw()
def released(self, event):
center = self.get_center()
x = event.x - center[0]
y = event.y - center[1]
if self.dragging: #We've been dragging.
if self.clicked_create_edge:
if self.control_pressed:
self.drag_to_create_edge(event) # create Edge
elif self.box:
pass #we've already done these steps in the "dragged" function...
else: #no box
if self.clicked_on in self.graph.edges: # If we clicked on an edge
pass
#do "drag-curving" logic/trig here.
#self. curve_through(edge, point)
elif self.clicked_on in self.graph.get_vertices(): #If we clicked and dragged a vertex...
pass #we've already moved it in the "dragged" function -- nothing more to do here!
else: #if we are drag-selecting
xcoords = [event.x,self.clicked_pos[0]]
ycoords = [event.y,self.clicked_pos[1]]
self.surrounded_vertices = []
for v in self.graph.get_vertices():
if min(xcoords) < v.x + center[0] < max(xcoords) and min(ycoords) < v.y + center[1] < max(ycoords):
self.surrounded_vertices.append(v)
v.selected = True
for e in self.graph.edges:
if e.vs[0] in self.surrounded_vertices and e.vs[1] in self.surrounded_vertices:
e.selected = True
self.box = [self.clicked_pos[0]-center[0],self.clicked_pos[1]-center[1],event.x-center[0],event.y-center[1]]
else: #We're not draggin!
if self.pasting: #if pasting/insert subgraph is true:
self.insert_copied(event)
self.pasting = False
#insert subgraph
elif self.clicked_on in self.graph.get_vertices() or self.clicked_on in self.graph.edges: # If we clicked on something
#Toggle its selection
self.clicked_on.toggle()
self.clicked_on.draw(self.canvas)
elif (self.selection() != None or self.box) and not self.shift_pressed: #elif something is selected (and clicked on nothing) and not pressing shift
self.deselect_all()
elif(self.shift_pressed): # If we clicked on nothing, and nothing is selected or pressing shift (to make a new vertex)
newVertex = Vertex((x, y))
if self.snap_mode.get() != 'none':
self.snap( event, newVertex )
self.graph.add_vertex( newVertex )
self.redraw()
def change_cursor(self, event=None):
self.config(cursor=random.choice(['bottom_tee', 'heart', 'double_arrow', 'top_left_arrow',
'top_side', 'top_left_corner', 'X_cursor', 'dotbox',
'lr_angle', 'sb_down_arrow', 'draft_small', 'gumby',
'bottom_right_corner', 'hand2', 'sb_right_arrow', 'diamond_cross',
'umbrella', 'mouse', 'trek', 'bottom_side', 'spraycan', 'll_angle',
'based_arrow_down', 'rightbutton', 'clock', 'right_ptr', 'sailboat', 'draft_large',
'cross', 'fleur', 'left_tee', 'boat', 'sb_left_arrow', 'shuttle', 'plus', 'bogosity',
'man', 'pirate', 'bottom_left_corner', 'pencil', 'star', 'arrow', 'exchange', 'gobbler',
'iron_cross', 'left_side', 'xterm', 'watch', 'leftbutton', 'spider', 'sizing', 'ul_angle',
'center_ptr', 'circle', 'icon', 'sb_up_arrow', 'draped_box', 'box_spiral', 'rtl_logo',
'target', 'middlebutton', 'question_arrow', 'cross_reverse', 'sb_v_double_arrow', 'right_side',
'top_right_corner', 'top_tee', 'ur_angle', 'sb_h_double_arrow', 'left_ptr', 'crosshair',
'coffee_mug', 'right_tee', 'based_arrow_up', 'tcross', 'dot', 'hand1']))
def insert_copied(self, event):
center = self.get_center()
x = event.x - center[0]
y = event.y - center[1]
vertdict = {}
leastx = 100000
mostx = -100000
leasty = 100000
mosty = -100000
for v in self.copied_verts:
if v[0] > mostx:
mostx = v[0]
if v[1] > mosty:
mosty = v[1]
if v[0] < leastx:
leastx = v[0]
if v[1] < leasty:
leasty = v[1]
avgx = (mostx + leastx) / 2
avgy = (mosty + leasty) / 2
self.deselect_all()
for v in self.copied_verts:
# In case we insert a graph with labels undefined
if len(v) < 3:
v = (v[0], v[1], "NULL")
vertdict[(v[0],v[1])] = Vertex((x+v[0]-avgx,y+v[1]-avgy),v[2])
self.graph.add_vertex( vertdict[(v[0],v[1])] )
for e in self.copied_edges:
if len(e) < 3:
# In case we insert a graph with edge curviness/wrapped-ness undefined
e = (e[0], e[1], None)
self.graph.connect((vertdict[e[0]],vertdict[e[1]]),e[2])
for v in vertdict.values():
v.toggle()
for e in self.graph.edges:
if e.vs[0] in vertdict.values() and e.vs[1] in vertdict.values():
e.toggle()
self.surrounded_vertices = vertdict.values()
self.box = [x-(mostx-leastx)/2, y-(mosty-leasty)/2, x+(mostx-leastx)/2, y+(mosty-leasty)/2]
def box_none(self,event=None):
self.box=False
self.surrounded_vertices=[]
self.redraw()
def box_all(self,event=None):
leastx = 100000
mostx = -100000
leasty = 100000
mosty = -100000
for v in self.graph.get_vertices():
if v.x > mostx:
mostx = v.x
if v.y > mosty:
mosty = v.y
if v.x < leastx:
leastx = v.x
if v.y < leasty:
leasty = v.y
self.box = [leastx-10, leasty-10,mostx+10, mosty+10]
self.surrounded_vertices=[v for v in self.graph.get_vertices()]
self.select_all()
def drag_to_create_edge(self, event):
center = self.get_center()
x = event.x - center[0]
y = event.y - center[1]
if self.clicked_on in self.graph.get_vertices():
v1 = self.clicked_on
else:
v1 = Vertex((self.clicked_pos[0]-center[0], self.clicked_pos[1]-center[1]))
if self.snap_mode.get() != 'none':
self.snap(FakeEvent(self.clicked_pos[0], self.clicked_pos[1]), v1)
self.graph.add_vertex(v1)
self.redraw()
released_on = self.find_clicked_on(event)
if released_on in self.graph.get_vertices():
v2 = released_on
else:
v2 = Vertex((x, y))
if self.snap_mode.get() != 'none':
self.snap(event, v2)
self.graph.add_vertex(v2)
self.graph.connect(vs = (v1,v2))
# #####################################################################################################
# Other Functions
# #####################################################################################################
def do_physics(self):
spacing = self.spacing
attraction = self.attraction
vertices = self.graph.get_vertices()
vertices2 = vertices[:]
for i in xrange(len(vertices)):
vertex=vertices2[random.randrange(0,len(vertices2))]
vertices2.remove(vertex)
for vertex2 in vertices2:
x_distance = vertex.x - vertex2.x
y_distance = vertex.y - vertex2.y
distance2 = (x_distance * x_distance) + (y_distance * y_distance)
if (vertex.x != vertex2.x or vertex.y != vertex2.y) and (distance2 < 10000 ):
if x_distance != 0:
delta_x = x_distance * spacing / distance2
if not vertex.selected:
vertex.x = vertex.x + delta_x
if not vertex2.selected:
vertex2.x = vertex2.x - delta_x
if y_distance != 0:
delta_y = y_distance * spacing / distance2
if not vertex.selected:
vertex.y = vertex.y + delta_y
if not vertex2.selected:
vertex2.y = vertex2.y - delta_y
for edge in self.graph.edges:
vertices = edge.vs
distance = math.sqrt( math.pow( vertices[0].x - vertices[1].x, 2 ) + math.pow( vertices[0].y - vertices[1].y, 2 ) )
direction = [ (vertices[0].x - vertices[1].x), (vertices[0].y - vertices[1].y) ]
if not vertices[0].selected:
vertices[0].x = vertices[0].x - direction[0] * distance * attraction
vertices[0].y = vertices[0].y - direction[1] * distance * attraction
if not vertices[1].selected:
vertices[1].x = vertices[1].x + direction[0] * distance * attraction
vertices[1].y = vertices[1].y + direction[1] * distance * attraction
self.redraw()
def start_physics(self, event=None):
if self.stop_physics:
self.stop_physics = False
while(1):
self.do_physics()
self.update()
self.redraw()
if self.stop_physics == True:
return
else:
self.stop_physics=True
def stop_physics(self):
self.stop_physics = True
def change_physics(self,event=None):
if event.keysym == "Up":
self.spacing+=.5
elif event.keysym == "Down":
self.spacing-=.5
elif event.keysym == "Right":
self.attraction+=.00001
elif event.keysym == "Left":
self.attraction-=.00001
def drawbox(self):
center = self.get_center()
if self.box:
b0 = self.box[0] + center[0]
b1 = self.box[1] + center[1]
b2 = self.box[2] + center[0]
b3 = self.box[3] + center[1]
self.canvas.create_rectangle(b0, b1, b2, b3, width=2, outline="blue", dash = (2,4), tags="selection box")
handles = ((b0,b1),
(b0,(b1+b3)/2),
(b0,b3),
(b2,b1),
(b2,(b1+b3)/2),
(b2,b3),
((b0+b2)/2,b1),
((b0+b2)/2,b3))
self.handles = {}
for handle in handles:
h = self.canvas.create_rectangle(handle[0]-3, handle[1]-3, handle[0]+3, handle[1]+3, fill="blue", outline="blue")
self.handles[h]=(handle[0],handle[1])
def drawgrid(self):
if self.snap_mode.get() == "rect":
width = float(self.canvas.winfo_width())
height = float(self.canvas.winfo_height())
try:
grid_size = float(self.grid_size.get())
except:
print "Error in snap parameters!"
return
x = ( (width / 2.0) % grid_size)
y = ( (height / 2.0) % grid_size)
while x < width: #vertical lines
self.canvas.create_line(x, 0, x, height, width = 1, fill = "grey", tags = "grid")
x = x + grid_size
while y < height: #horizontal lines
self.canvas.create_line(0, y, width, y, width = 1, fill = "grey", tags = "grid")
y = y + grid_size
self.canvas.create_line(0, height/2, width, height/2, width = 2, fill = "grey", tags = "grid")
self.canvas.create_line(width/2, 0, width/2, height, width = 2, fill = "grey", tags = "grid")
elif self.snap_mode.get() == "polar":
width = float(self.canvas.winfo_width())
height = float(self.canvas.winfo_height())
center = [width / 2, height / 2]
#grid_size = float(self.snap_grid_size)
#number_per_circle = float(self.snap_number_per_circle)
try:
grid_size = float(self.grid_size.get())
number_per_circle = float(self.number_per_circle.get())
except:
print "Error in snap parameters!"
return
theta = 2 * pi / number_per_circle
radius = grid_size
angle = 0
canvas_radius = sqrt( height * height + width * width ) / 2
while radius < canvas_radius:
self.canvas.create_oval(center[0] - radius, center[1] - radius, center[0] + radius, center[1] + radius, width = 1, outline = "grey", tags = "grid")
radius = radius + grid_size
while angle < 2*pi:
self.canvas.create_line(center[0], center[1], center[0] + canvas_radius * cos(angle), center[1] + canvas_radius * sin(angle), width = 1, fill = "grey", tags = "grid")
angle = angle + theta
def snap(self, event, vertex):
center = self.get_center()
x = event.x - center[0]
y = event.y - center[1]
#grid_size = float(self.snap_grid_size)
#number_per_circle = float(self.snap_number_per_circle)
try:
grid_size = float(self.grid_size.get())
except:
print "Error in snap parameters!"
return
if self.snap_mode.get() == "rect":
low = grid_size * floor( x / grid_size )
high = grid_size * ceil( x / grid_size )
if (x - low) < (high - x):
vertex.x = low
else:
vertex.x = high
low = grid_size * floor( y / grid_size )
high = grid_size * ceil( y / grid_size )
if (y - low) < (high - y):
vertex.y = low
else:
vertex.y = high
elif self.snap_mode.get() == "polar":
try:
number_per_circle = float(self.number_per_circle.get())
except:
print "Error in snap parameters!"
return
distance = sqrt( x*x + y*y )
angle = atan2( y, x )
angle = angle / (2*pi) * number_per_circle
low = grid_size * floor( distance / grid_size )
high = grid_size * ceil( distance / grid_size )
if (distance - low) < (high - distance):
distance = low
else:
distance = high
low = floor( angle )
high = ceil( angle )
if (angle - low) < (high - angle):
angle = low
else:
angle = high
angle = angle / number_per_circle * 2*pi
vertex.x = distance * cos( angle )
vertex.y = distance * sin( angle )
def select_subgraph(self, type):
# first, save the old state, and "pop up" the button
for subgraph in self.subgraph_buttons:
if subgraph.name == self.selected_subgraph:
subgraph.config(relief = RAISED)
for i in range(len(subgraph.options)):
subgraph.options[i][1] = self.subgraph_entries[i][1].get()
self.subgraph_entries[i][1].delete(0, END)
# TODO: should we have done int conversion here? Make sure we try/except later...(watch out for "file")
break
# update the selected subgraph
self.selected_subgraph = type
# update the subgraph entry boxes, and
for subgraph in self.subgraph_buttons:
if subgraph.name == type:
subgraph.config(relief = SUNKEN)
self.subgraph_button_frame.pack_forget()
for i in range(len(subgraph.options)):
self.subgraph_entries[i][0].config(text = subgraph.options[i][0])
self.subgraph_entries[i][1].config(state = NORMAL)
self.subgraph_entries[i][1].insert(END, subgraph.options[i][1])
self.subgraph_entries[i][2].pack(side = TOP, anchor = W)
i = i + 1
if len(subgraph.options) == 0:
i = 0
while i < len(self.subgraph_entries):
self.subgraph_entries[i][0].config(text = "")
self.subgraph_entries[i][1].config(state = DISABLED)
self.subgraph_entries[i][2].config(height = 0)
self.subgraph_entries[i][2].pack_forget()
i=i+1
self.subgraph_button_frame.pack(side = TOP)
break
def insert_subgraph(self):
for subgraph in self.subgraph_buttons:
if subgraph.name == self.selected_subgraph:
options = []
for i in range(len(subgraph.options)):
try:
option = int(self.subgraph_entries[i][1].get())
if option <= 0:
tkMessageBox.showwarning("Invalid Parameters", "All parameters should be positive!")
return
options.append(option)
except:
try:
option= [int(x) for x in self.subgraph_entries[i][1].get().split(',')]
options.append(option)
except:
tkMessageBox.showwarning("Invalid Parameters", "All parameters should be integers!")
return
break
if self.selected_subgraph == "file":
file = tkFileDialog.askopenfile(parent=self,mode='rb',title='Choose a file')
if file != None:
tempgraph = pickle.load(file)
file.close()
self.copied_verts = []
self.copied_edges = []
for v in tempgraph.vertices:
self.copied_verts.append((v.x,v.y,v.label))
for e in tempgraph.edges:
self.copied_edges.append(((e.vs[0].x,e.vs[0].y),(e.vs[1].x,e.vs[1].y),[e.wrap,e.curved,e.height,e.direction]))
center = self.get_center()
center = FakeEvent(center[0],center[1])
self.insert_copied(center)
self.redraw()
return
tkMessageBox.showwarning("Unable to Insert", "No File Chosen")
return
res = generate.generate(subgraph.name, options)
if res[0] == "ERROR":
tkMessageBox.showwarning("Invalid Parameters", res[1])
self.copied_verts = res[0]
self.copied_edges = res[1]
center = self.get_center()
center = FakeEvent(center[0],center[1])
self.insert_copied(center)
self.redraw()
def message(self, title, message, function, type="okcancel"):
if type=="passgraphokcancel":
res = tkSimpleDialog.askinteger(title, message)
if res != None:
function( self.graph, res )
if type=="okcancel":
res = tkSimpleDialog.askinteger(title, message)
if res != None:
function( res )
if type=="Decimal":
res = tkSimpleDialog.askstring(title, message)
if res != None:
function( Decimal(res) )
elif type=="yesnocancel":
if tkMessageBox._show(title,message,icon=tkMessageBox.QUESTION,type=tkMessageBox.YESNOCANCEL)=="yes":
function()
# def toggle_snap_mode(self, type=None):
# if type == "none":
# self.snap_on = False
# try:
# self.canvas.delete("grid")
# except:
# pass
# elif type == "rect":
# self.snap_on = True
# self.snap_mode = "rect"
# elif type == "circular":
# self.snap_on = True
# self.snap_mode = "circular"
# self.redraw()
# return
def clear(self, reset=True):
if reset:
self.registerwithundo()
self.graph.vertices=[]
self.graph.edges=[]
self.graph.tags=[]
self.canvas.delete("all")
# event is needed so that it can be called from the "Configure" binding that detects window size changes.
def redraw(self, event=None):
self.clear(False)
self.drawgrid()
self.graph.draw(self.canvas)
self.drawbox()
def get_center(self):
width = float(self.canvas.winfo_width())
height = float(self.canvas.winfo_height())
return [width / 2, height / 2]
def main(update = False):
warnings.filterwarnings("ignore")
# import cProfile
try:
psyco.full()
except:
print "Problem with your psyco. go install it for faster action."
if update:
#Update "start.py"
from shutil import move
move("start.py.new","start.py")
world = GraphInterface()
# cProfile.run('GraphInterface()')
#world.mainloop()
if __name__ == '__main__':
main() | [
[
1,
0,
0.0014,
0.0005,
0,
0.66,
0,
349,
0,
2,
0,
0,
349,
0,
0
],
[
14,
0,
0.0019,
0.0005,
0,
0.66,
0.0323,
365,
1,
0,
0,
0,
0,
1,
0
],
[
1,
0,
0.0028,
0.0005,
0,
0... | [
"from decimal import Decimal, getcontext",
"getcontext.prec = 10",
"from copy import copy",
"import os",
"import random",
"import time",
"import tkFileDialog",
"import tkMessageBox",
"import tkSimpleDialog",
"import pickle",
"import math",
"import generate",
"import graphmath",
"from copy ... |
"""Wrapper classes for use with tkinter.
This module provides the following classes:
Gui: a sublass of Tk that provides wrappers for most
of the widget-creating methods from Tk. The advantages of
these wrappers is that they use Python's optional argument capability
to provide appropriate default values, and that they combine widget
creation and packing into a single step. They also eliminate the need
to name the parent widget explicitly by keeping track of a current
frame and packing new objects into it.
GuiCanvas: a subclass of Canvas that provides wrappers for most of the
item-creating methods from Canvas. The advantages of the wrappers
are, again, that they use optional arguments to provide appropriate
defaults, and that they perform coordinate transformations.
Transform: an abstract class that provides basic methods inherited
by CanvasTransform and the other transforms.
CanvasTransform: a transformation that maps standard Cartesian
coordinates onto the 'graphics' coordinates used by Canvas objects.
Callable: the standard recipe from Python Cookbook for encapsulating
a funcation and its arguments in an object that can be used as a
callback.
Thread: a wrapper class for threading.Thread that improves the
interface.
Watcher: a workaround for the problem multithreaded programs have
handling signals, especially the SIGINT generated by a
KeyboardInterrupt.
The most important idea about this module is the idea of using
a stack of frames to avoid keeping track of parent widgets explicitly.
Copyright 2005 Allen B. Downey
This file contains wrapper classes I use with tkinter. It is
mostly for my own use; I don't support it, and it is not very
well documented.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see
http://www.gnu.org/licenses/gpl.html or write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA
"""
from math import *
from Tkinter import *
import threading, time, os, signal, sys, operator
class Thread(threading.Thread):
"""this is a wrapper for threading.Thread that improves
the syntax for creating and starting threads. See Appendix A
of The Little Book of Semaphores, http://greenteapress.com/semaphores/
"""
def __init__(self, target, *args):
threading.Thread.__init__(self, target=target, args=args)
self.start()
class Semaphore(threading._Semaphore):
"""this is a wrapper class that makes signal and wait
synonyms for acquire and release, and also makes signal
take an optional argument.
"""
wait = threading._Semaphore.acquire
def signal(self, n=1):
for i in range(n): self.release()
def value(self):
return self._Semaphore__value
def pairiter(seq):
"""return an iterator that yields consecutive pairs from seq"""
it = iter(seq)
while True:
yield [it.next(), it.next()]
def pair(seq):
"""return a list of consecutive pairs from seq"""
return [x for x in pairiter(seq)]
def flatten(seq):
return sum(seq, [])
# Gui provides wrappers for many of the methods in the Tk
# class; also, it keeps track of the current frame so that
# you can create new widgets without naming the parent frame
# explicitly.
def underride(d, **kwds):
"""Add kwds to the dictionary only if they are not already set"""
for key, val in kwds.iteritems():
if key not in d:
d[key] = val
def override(d, **kwds):
"""Add kwds to the dictionary even if they are already set"""
d.update(kwds)
class Gui(Tk):
def __init__(self, debug=False):
"""initialize the gui.
turning on debugging changes the behavior of Gui.fr so
that the nested frame structure is apparent
"""
Tk.__init__(self)
self.debug = debug
self.frames = [self] # the stack of nested frames
frame = property(lambda self: self.frames[-1])
def endfr(self):
"""end the current frame (and return it)"""
return self.frames.pop()
popfr = endfr
endgr = endfr
def pushfr(self, frame):
"""push a frame onto the frame stack"""
self.frames.append(frame)
def tl(self, **options):
"""make a return a top level window."""
return Toplevel(**options)
"""The following widget wrappers all invoke widget to
create and pack the new widget. The first four positional
arguments determine how the widget is packed. Some widgets
take additional positional arguments. In most cases, the
keyword arguments are passed as options to the widget
constructor.
The default pack arguments are
side=TOP, fill=NONE, expand=0, anchor=CENTER
Widgets that use these defaults can just pass along
args and options unmolested. Widgets (like fr and en)
that want different defaults have to roll the arguments
in with the other options and then underride them.
"""
argnames = ['side', 'fill', 'expand', 'anchor']
def fr(self, *args, **options):
"""make a return a frame.
As a side effect, the new frame becomes the current frame
"""
options.update(dict(zip(Gui.argnames,args)))
underride(options, fill=BOTH, expand=1)
if self.debug:
override(options, bd=5, relief=RIDGE)
# create the new frame and push it onto the stack
frame = self.widget(Frame, **options)
self.pushfr(frame)
return frame
def gr(self, cols, cweights=[1], rweights=[1], **options):
"""create a frame and switch to grid mode.
cols is the number of columns in the grid (no need to
specify the number of rows). cweight and rweight control
how the widgets expand if the frame expands (see colweights
and rowweights below). options are passed along to the frame
"""
fr = self.fr(**options)
fr.gridding = True
fr.cols = cols
fr.i = 0
fr.j = 0
self.colweights(cweights)
self.rowweights(rweights)
return fr
def colweights(self, weights):
"""attach weights to the columns of the current grid.
These weights control how the columns in the grid expand
when the grid expands. The default weight is 0, which
means that the column doesn't expand. If only one
column has a value, it gets all the extra space.
"""
for i, weight in enumerate(weights):
self.frame.columnconfigure(i, weight=weight)
def rowweights(self, weights):
"""attach weights to the rows of the current grid.
These weights control how the rows in the grid expand
when the grid expands. The default weight is 0, which
means that the row doesn't expand. If only one
row has a value, it gets all the extra space.
"""
for i, weight in enumerate(weights):
self.frame.rowconfigure(i, weight=weight)
def grid(self, widget, i=None, j=None, **options):
"""pack the given widget in the current grid.
By default, the widget is packed in the next available
space, but i and j can override.
"""
if i == None: i = self.frame.i
if j == None: j = self.frame.j
widget.grid(row=i, column=j, **options)
# increment j by 1, or by columnspan
# if the widget spans more than one column.
try:
incr = options['columnspan']
except KeyError:
incr = 1
self.frame.j += 1
if self.frame.j == self.frame.cols:
self.frame.j = 0
self.frame.i += 1
# entry
def en(self, *args, **options):
options.update(dict(zip(Gui.argnames,args)))
underride(options, fill=BOTH, expand=1)
text = options.pop('text', '')
en = self.widget(Entry, **options)
en.insert(0, text)
return en
# canvas
def ca(self, *args, **options):
underride(options, fill=BOTH, expand=1)
return self.widget(GuiCanvas, *args, **options)
# label
def la(self, *args, **options):
return self.widget(Label, *args, **options)
# button
def bu(self, *args, **options):
return self.widget(Button, *args, **options)
# menu button
def mb(self, *args, **options):
mb = self.widget(Menubutton, *args, **options)
mb.menu = Menu(mb, relief=SUNKEN)
mb['menu'] = mb.menu
return mb
# menu item
def mi(self, mb, label='', **options):
mb.menu.add_command(label=label, **options)
# text entry
def te(self, *args, **options):
return self.widget(Text, *args, **options)
# scrollbar
def sb(self, *args, **options):
return self.widget(Scrollbar, *args, **options)
class ScrollableText:
def __init__(self, gui,
*args, **options):
self.frame = gui.fr(*args, **options)
self.scrollbar = gui.sb(RIGHT, fill=Y)
self.text = gui.te(LEFT, wrap=WORD,
yscrollcommand=self.scrollbar.set)
self.scrollbar.config(command=self.text.yview)
gui.endfr()
# scrollable text
# returns a ScrollableText object that contains a frame, a
# text entry and a scrollbar.
# note: the options provided to st apply to the frame only;
# if you want to configure the other widgets, you have to do
# it after invoking st
def st(self, *args, **options):
return self.ScrollableText(self, *args, **options)
class ScrollableCanvas:
def __init__(self, gui, width=500, height=500, **options):
self.grid = gui.gr(2, **options)
self.canvas = gui.ca(width=width, height=height, bg='white')
self.yb = self.sb(command=self.canvas.yview, sticky=N+S)
self.xb = self.sb(command=self.canvas.xview, orient=HORIZONTAL,
sticky=E+W)
self.canvas.configure(xscrollcommand=self.xb.set,
yscrollcommand=self.yb.set)
gui.endgr()
def sc(self, *args, **options):
return self.ScrollableCanvas(self, *args, **options)
def widget(self, constructor, *args, **options):
"""this is the mother of all widget constructors.
the constructor argument is the function that will
be called to build the new widget. args is rolled
into options, and then options is split into widget
option, pack options and grid options
"""
options.update(dict(zip(Gui.argnames,args)))
widopt, packopt, gridopt = split_options(options)
# make the widget and either pack or grid it
widget = constructor(self.frame, **widopt)
if hasattr(self.frame, 'gridding'):
self.grid(widget, **gridopt)
else:
widget.pack(**packopt)
return widget
def pop_options(options, names):
"""remove names from options and return a new dictionary
that contains the names and values from options
"""
new = {}
for name in names:
if name in options:
new[name] = options.pop(name)
return new
def split_options(options):
"""take a dictionary of options and split it into pack
options, grid options, and anything left is assumed to
be a widget option
"""
packnames = ['side', 'fill', 'expand', 'anchor']
gridnames = ['column', 'columnspan', 'row', 'rowspan',
'padx', 'pady', 'ipadx', 'ipady', 'sticky']
packopts = pop_options(options, packnames)
gridopts = pop_options(options, gridnames)
return options, packopts, gridopts
class BBox(list):
__slots__ = ()
"""a bounding box is a list of coordinates, where each
coordinate is a list of numbers.
Creating a new bounding box makes a _shallow_ copy of
the list of coordinates. For a deep copy, use copy().
"""
def copy(self):
t = [Pos(coord) for coord in bbox]
return BBox(t)
# top, bottom, left, and right can be accessed as attributes
def setleft(bbox, val): bbox[0][0] = val
def settop(bbox, val): bbox[0][1] = val
def setright(bbox, val): bbox[1][0] = val
def setbottom(bbox, val): bbox[1][1] = val
left = property(lambda bbox: bbox[0][0], setleft)
top = property(lambda bbox: bbox[0][1], settop)
right = property(lambda bbox: bbox[1][0], setright)
bottom = property(lambda bbox: bbox[1][1], setbottom)
def width(bbox): return bbox.right - bbox.left
def height(bbox): return bbox.bottom - bbox.top
def upperleft(bbox): return Pos(bbox[0])
def lowerright(bbox): return Pos(bbox[1])
def midright(bbox):
x = bbox.right
y = (bbox.top + bbox.bottom) / 2.0
return Pos([x, y])
def midleft(bbox):
x = bbox.left
y = (bbox.top + bbox.bottom) / 2.0
return Pos([x, y])
def offset(bbox, pos):
"""return the vector between the upper-left corner of bbox and pos"""
return Pos([pos[0]-bbox.left, pos[1]-bbox.top])
def pos(bbox, offset):
"""return the position at the given offset from bbox upper-left"""
return Pos([offset[0]+bbox.left, offset[1]+bbox.top])
def flatten(bbox):
"""return a list of four coordinates"""
return bbox[0] + bbox[1]
class Pos(list):
__slots__ = ()
"""a position is a list of coordinates.
Because Pos inherits __init__ from list, it makes a copy
of the argument to the constructor.
"""
copy = lambda pos: Pos(pos)
# x and y can be accessed as attributes
def setx(pos, val): pos[0] = val
def sety(pos, val): pos[1] = val
x = property(lambda pos: pos[0], setx)
y = property(lambda pos: pos[1], sety)
class GuiCanvas(Canvas):
"""this is a wrapper for the Canvas provided by tkinter.
The primary difference is that it supports coordinate
transformations, the most common of which is the CanvasTranform,
which make canvas coordinates Cartesian (origin in the middle,
positive y axis going up).
It also provides methods like circle that provide a
nice interface to the underlying canvas methods.
"""
def __init__(self, w, transforms=None, **options):
Canvas.__init__(self, w, **options)
# the default transform is a standard CanvasTransform
if transforms == None:
self.transforms = [CanvasTransform(self)]
else:
self.transforms = transforms
# the following properties make it possbile to access
# the width and height of the canvas as if they were attributes
width = property(lambda self: int(self['width']))
height = property(lambda self: int(self['height']))
def add_transform(self, transform, pos=None):
if pos == None:
self.transforms.append(transform)
else:
self.transforms.insert(pos, transform)
def trans(self, coords):
"""apply each of the transforms for this canvas, in order"""
for trans in self.transforms:
coords = trans.trans_list(coords)
return coords
def invert(self, coords):
t = self.transforms[:]
t.reverse()
for trans in t:
coords = trans.invert_list(coords)
return coords
def bbox(self, item):
if isinstance(item, list):
item = item[0]
bbox = Canvas.bbox(self, item)
if bbox == None: return bbox
bbox = pair(bbox)
bbox = self.invert(bbox)
return BBox(bbox)
def coords(self, item, coords=None):
if coords:
coords = self.trans(coords)
coords = flatten(coords)
Canvas.coords(self, item, *coords)
else:
"have to get the coordinates and invert them"
def move(self, item, dx=0, dy=0):
coords = self.trans([[dx, dy]])
pos = coords[0]
Canvas.move(self, item, pos[0], pos[1])
def flipx(self, item):
coords = Canvas.coords(self, item)
for i in range(0, len(coords), 2):
coords[i] *= -1
Canvas.coords(self, item, *coords)
def circle(self, x, y, r, fill='', **options):
options['fill'] = fill
coords = self.trans([[x-r, y-r], [x+r, y+r]])
tag = self.create_oval(coords, options)
return tag
def oval(self, coords, fill='', **options):
options['fill'] = fill
return self.create_oval(self.trans(coords), options)
def rectangle(self, coords, fill='', **options):
options['fill'] = fill
return self.create_rectangle(self.trans(coords), options)
def line(self, coords, fill='black', **options):
options['fill'] = fill
tag = self.create_line(self.trans(coords), options)
return tag
def polygon(self, coords, fill='', **options):
options['fill'] = fill
return self.create_polygon(self.trans(coords), options)
def text(self, coord, text='', fill='black', **options):
options['text'] = text
options['fill'] = fill
return self.create_text(self.trans([coord]), options)
def image(self, coord, image, **options):
options['image'] = image
return self.create_image(self.trans([coord]), options)
def dump(self, filename='canvas.eps'):
bbox = Canvas.bbox(self, ALL)
x, y, width, height = bbox
width -= x
height -= y
ps = self.postscript(x=x, y=y, width=width, height=height)
fp = open(filename, 'w')
fp.write(ps)
fp.close()
class Transform:
"""the parent class of transforms, Transform provides methods
for transforming lists of coordinates. Subclasses of Transform
are supposed to implement trans() and invert()
"""
def trans_list(self, points, func=None):
# the default func is trans; invert_list overrides this
# with invert
if func == None:
func = self.trans
if isinstance(points[0], (list, tuple)):
return [Pos(func(p)) for p in points]
else:
return Pos(func(points))
def invert_list(self, points):
return self.trans_list(points, self.invert)
class CanvasTransform(Transform):
"""under a CanvasTransform, the origin is in the middle of
the canvas, the positive y-axis is up, and the coordinate
[1, 1] maps to the point specified by scale.
"""
def __init__(self, ca, scale=[1, 1]):
self.ca = ca
self.scale = scale
def trans(self, p):
x = p[0] * self.scale[0] + self.ca.width/2
y = -p[1] * self.scale[1] + self.ca.height/2
return [x, y]
class ScaleTransform(Transform):
"""scale the coordinate system by the given factors.
The origin is half a unit from the upper-left corner.
"""
def __init__(self, scale=[1, 1]):
self.scale = scale
def trans(self, p):
x = p[0] * self.scale[0]
y = p[1] * self.scale[1]
return [x, y]
def invert(self, p):
x = p[0] / self.scale[0]
y = p[1] / self.scale[1]
return [x, y]
class RotateTransform(Transform):
"""rotate the coordinate system theta degrees clockwise
"""
def __init__(self, theta):
self.theta = theta
def rotate(self, p, theta):
s = sin(theta)
c = cos(theta)
x = c * p[0] + s * p[1]
y = -s * p[0] + c * p[1]
return [x, y]
def trans(self, p):
return self.rotate(p, self.theta)
def invert(self, p):
return self.rotate(p, -self.theta)
class SwirlTransform(RotateTransform):
def trans(self, p):
d = sqrt(p[0]*p[0] + p[1]*p[1])
return self.rotate(p, self.theta*d)
def invert(self, p):
d = sqrt(p[0]*p[0] + p[1]*p[1])
return self.rotate(p, -self.theta*d)
class Callable:
"""this class is used to wrap a function and its arguments
into an object that can be passed as a callback parameter
and invoked later. It is from the Python Cookbook 9.1, page 302
"""
def __init__(self, func, *args, **kwds):
self.func = func
self.args = args
self.kwds = kwds
def __call__(self):
return apply(self.func, self.args, self.kwds)
def __str__(self):
return self.func.__name__
class Watcher:
"""this class solves two problems with multithreaded
programs in Python, (1) a signal might be delivered
to any thread (which is just a malfeature) and (2) if
the thread that gets the signal is waiting, the signal
is ignored (which is a bug).
The watcher is a concurrent process (not thread) that
waits for a signal and the process that contains the
threads. See Appendix A of The Little Book of Semaphores.
I have only tested this on Linux. I would expect it to
work on the Macintosh and not work on Windows.
"""
def __init__(self):
""" Creates a child thread, which returns. The parent
thread waits for a KeyboardInterrupt and then kills
the child thread.
"""
self.child = os.fork()
if self.child == 0:
return
else:
self.watch()
def watch(self):
try:
os.wait()
except KeyboardInterrupt:
# I put the capital B in KeyBoardInterrupt so I can
# tell when the Watcher gets the SIGINT
print 'KeyBoardInterrupt'
self.kill()
sys.exit()
def kill(self):
try:
os.kill(self.child, signal.SIGKILL)
except OSError: pass
def tk_example():
tk = Tk()
def hello():
ca.create_text(100, 100, text='hello', fill='blue')
ca = Canvas(tk, bg='white')
ca.pack(side=LEFT)
fr = Frame(tk)
fr.pack(side=LEFT)
bu1 = Button(fr, text='Hello', command=hello)
bu1.pack()
bu2 = Button(fr, text='Quit', command=tk.quit)
bu2.pack()
tk.mainloop()
def gui_example():
gui = Gui()
ca = gui.ca(LEFT, bg='white')
def hello():
ca.text([0,0], 'hello', 'blue')
gui.fr(LEFT)
gui.bu(text='Hello', command=hello)
gui.bu(text='Quit', command=gui.quit)
gui.endfr()
gui.mainloop()
def main(script, n=0, *args):
if n == 0:
tk_example()
else:
gui_example()
if __name__ == '__main__':
main(*sys.argv)
| [
[
8,
0,
0.0433,
0.0852,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0907,
0.0014,
0,
0.66,
0.037,
526,
0,
1,
0,
0,
526,
0,
0
],
[
1,
0,
0.092,
0.0014,
0,
0.66,
... | [
"\"\"\"Wrapper classes for use with tkinter.\n\nThis module provides the following classes:\n\nGui: a sublass of Tk that provides wrappers for most\nof the widget-creating methods from Tk. The advantages of\nthese wrappers is that they use Python's optional argument capability\nto provide appropriate default value... |
import math
def delimeters(gear_pos):
g1 = gear_pos[-1]
g2 = gear_pos[0]
dist = 0
d = []
for i in range(len(gear_pos)):
gear = gear_pos[i-1]
to_gear = gear_pos[i]
from_gear = gear_pos[i-2]
(t1,t2) = cctangent(from_gear, gear)
(t3, t4) = cctangent(gear, to_gear)
if i == 0:
th_from = math.atan2( (t1[0] - from_gear[0]) , (t1[1] - from_gear[1]) )
d.append((0,t1[0],t1[1], th_from, from_gear[2]))
dist += math.sqrt((t1[1] - t2[1])**2 + (t1[0] - t2[0])**2)
th_ini = math.atan2( (t2[0] - gear[0]) , (t2[1] - gear[1]) )
d.append((dist,t2[0],t2[1],th_ini,gear[2]))
th1 = math.atan2( (t2[0] - gear[0]) , (t2[1] - gear[1]) )
th2 = math.atan2( (t3[0] - gear[0]) , (t3[1] - gear[1]) )
arc = gear[2]*(th1 - th2)
dist += abs(arc)
d.append((dist, t3[0], t3[1], th1, gear[2]))
#total distance, x, y, initial angle, radius
length = math.sqrt((t4[1] - t3[1])**2 + (t4[0] - t3[0])**2)
dist += abs(length)
d.append((dist, t4[0], t4[1], 0, 0, 0))
#total distance, x, y
delimeters = d
for delim in d:
print delim[0], '(', delim[1], ',', delim[2], ')'
return d
def cctangent(c1, c2):
c1x=c1[0]
c1y=c1[1]
c1r=c1[2]
c2x=c2[0]
c2y=c2[1]
c2r=c2[2]
th_ini = math.atan2(c2y-c1y,c2x-c1x)
l = math.sqrt((c2y-c1y)**2 + (c2x-c1x)**2)
th = math.acos((c1r-c2r)/l)
t1x = c1x + c1r * math.cos(th+th_ini)
t1y = c1y + c1r * math.sin(th+th_ini)
t2x = c2x + c2r * math.cos(th+th_ini)
t2y = c2y + c2r * math.sin(th+th_ini)
return ((t1x, t1y), (t2x, t2y))
def get_xy_pos(d, dlist):
# d = self.rate*time - dist_behind
for i in range(len(dlist)-1):
#delimeters in the form [(d1, x1, y1, th_ini, r), (d2, x2, y2)]
p1 = dlist[i]
p2 = dlist[i+1]
if d >= dlist[-2][0]: #The front creep has done a lap
return x, y
if p1[0] <= d < p2[0]:
print p1[0], '(', p1[1], ',', p1[2], ')'
if i % 2 == 0: #even sections are linear
x = p1[1] + (d - p1[0]) / (p2[0] - p1[0]) * (p2[1] - p1[1])
y = p1[2] + (d - p1[0]) / (p2[0] - p1[0]) * (p2[2] - p1[2])
else: #odd sections are turns
x = p1[1] + math.cos(p1[3] + (d - p1[0])/p1[4])
y = p1[1] + math.sin(p1[3] + (d - p1[0])/p1[4])
return x, y
print get_xy_pos (5, delimeters([(2,2,-1), (-2,2, -1), (-2,-2,-1), (2,-2,-1)]) )
| [
[
1,
0,
0.0125,
0.0125,
0,
0.66,
0,
526,
0,
1,
0,
0,
526,
0,
0
],
[
2,
0,
0.275,
0.4875,
0,
0.66,
0.25,
288,
0,
1,
1,
0,
0,
0,
17
],
[
14,
1,
0.05,
0.0125,
1,
0.7,
... | [
"import math",
"def delimeters(gear_pos):\n g1 = gear_pos[-1]\n g2 = gear_pos[0]\n \n dist = 0\n d = []\n \n for i in range(len(gear_pos)):",
" g1 = gear_pos[-1]",
" g2 = gear_pos[0]",
" dist = 0",
" d = []",
" for i in range(len(gear_pos)):\n gear = gear_pos[i... |
from Tkinter import *
import ctypes
SET_SERVO = 1
##CLR_RA1 = 2
##GET_RA2 = 3
##SET_DUTY = 4
global servospot
servospot=0
print "set servospot"
usb = ctypes.cdll.LoadLibrary('usb.dll')
usb.initialize()
print "hey o"
buffer = ctypes.c_buffer(8)
##def set_ra1_callback():
## usb.control_transfer(dev, 0x40, SET_RA1, 0, 0, 0, buffer)
##
##def clr_ra1_callback():
## usb.control_transfer(dev, 0x40, CLR_RA1, 0, 0, 0, buffer)
# def get_ra2_callback():
# usb.control_transfer(dev, 0xC0, GET_RA2, 0, 0, 1, buffer)
# status.configure(text = 'RA2 is currently %d.' % ord(buffer[0]))
##def set_duty_callback(value):
## usb.control_transfer(dev, 0x40, SET_DUTY, int(value), 0, 0, buffer)
def set_servo_callback(value):
global servospot
servospot=int(value)
usb.control_transfer(dev, 0x40, SET_SERVO, int(value), 0, 0, buffer)
##
##def set_callback(pin):
## global player
## if not (pin in opponentpin or pin in playerpin):
## usb.control_transfer(dev, 0x40, pin, 0, 0, 0, buffer)
## img=PhotoImage(file=['X','O'][int(player)]+'.gif')
## buttons[pin].configure(image=img)
## buttons[pin].image=img
## if player:
## opponentpin.append(pin)
## else:
## playerpin.append(pin)
## player = not player
##def make_callback(pin):
## return lambda: set_callback(pin)
def update_status():
global servospot
#usb.control_transfer(dev, 0xC0, servospot, 0, 0, 1, buffer)
## usb.control_transfer(dev, 0xC0, SET_SERVO, servospot, 0, 1, buffer)
status.configure(text = 'Servo at %d' % servospot)
## servospot+=1
## if servospot>255:
## servospot=0
root.after(50, update_status)
root = Tk()
root.title('Tower GUI')
##buttons=[]
##img=PhotoImage(file='blank.GIF')
##for i in xrange(9):
##
#### print img
## b=Button(root, width=64,height=64, text=' ', image=img,command = make_callback(i))
## b.image=img
## b.grid(row=i/3, column=i%3)
## buttons.append(b)
#b.pack(side = LEFT, padx=2, pady=2)
#Button(fm, text = ' ', command = clr_ra1_callback).pack(side = LEFT)
# Button(fm, text = 'GET_RA2', command = get_ra2_callback).pack(side = LEFT)
#fm.pack(side = TOP)
#dutyslider = Scale(root, from_ = 0, to = 255, orient = HORIZONTAL, showvalue = FALSE, command = set_duty_callback)
#dutyslider.set(128)
#dutyslider.pack(side = TOP)
dutyslider = Scale(root, from_ = 0, to = 255, orient = HORIZONTAL, showvalue = FALSE, command = set_servo_callback)
dutyslider.set(128)
dutyslider.pack(side = TOP)
status = Label(root, text = 'Get Ready for FUN.')
#status.grid(row=3,column=0,columnspan=3)
status.pack(side = TOP)
#Button(fm, text='kill/unkill',command = toggle_kill).pack(side = LEFT)
dev = usb.open_device(0x6666, 0x0003, 0)
if dev<0:
print "No matching device found...\n"
else:
ret = usb.control_transfer(dev, 0x00, 0x09, 1, 0, 0, buffer)
if ret<0:
print "Unable to send SET_CONFIGURATION standard request.\n"
root.after(30, update_status)
root.mainloop()
usb.close_device(dev)
##global killed=False
##def toggle_kill():
## global killed
## value=0;
## if
## servospot=int(value)
## usb.control_transfer(dev, 0x40, SET_SERVO, int(value), 0, 0, buffer)
##
| [
[
1,
0,
0.018,
0.009,
0,
0.66,
0,
368,
0,
1,
0,
0,
368,
0,
0
],
[
1,
0,
0.027,
0.009,
0,
0.66,
0.0526,
182,
0,
1,
0,
0,
182,
0,
0
],
[
14,
0,
0.045,
0.009,
0,
0.66,... | [
"from Tkinter import *",
"import ctypes",
"SET_SERVO = 1",
"servospot=0",
"print(\"set servospot\")",
"usb = ctypes.cdll.LoadLibrary('usb.dll')",
"usb.initialize()",
"print(\"hey o\")",
"buffer = ctypes.c_buffer(8)",
"def set_servo_callback(value):\n global servospot\n servospot=int(value)\n... |
# explore the mouse wheel with the Tkinter GUI toolkit
# Windows and Linux generate different events
# tested with Python25
import Tkinter as tk
def mouse_wheel(event):
global count
# respond to Linux or Windows wheel event
if event.num == 5 or event.delta == -120:
count -= 1
if event.num == 4 or event.delta == 120:
count += 1
label['text'] = count
count = 0
root = tk.Tk()
root.title('turn mouse wheel')
root['bg'] = 'darkgreen'
# with Windows OS
root.bind("<MouseWheel>", mouse_wheel)
# with Linux OS
root.bind("<Button-4>", mouse_wheel)
root.bind("<Button-5>", mouse_wheel)
label = tk.Label(root, font=('courier', 18, 'bold'), width=10)
label.pack(padx=40, pady=40)
root.mainloop()
# http://www.daniweb.com/code/snippet217059.html
| [
[
1,
0,
0.1515,
0.0303,
0,
0.66,
0,
368,
0,
1,
0,
0,
368,
0,
0
],
[
2,
0,
0.3182,
0.2424,
0,
0.66,
0.0909,
419,
0,
1,
0,
0,
0,
0,
0
],
[
4,
1,
0.3182,
0.0606,
1,
0.... | [
"import Tkinter as tk",
"def mouse_wheel(event):\n global count\n # respond to Linux or Windows wheel event\n if event.num == 5 or event.delta == -120:\n count -= 1\n if event.num == 4 or event.delta == 120:\n count += 1\n label['text'] = count",
" if event.num == 5 or event.delt... |
from visual import *
from Blokus import *
from PieceTest import *
def draw_piece(piece,n):
color_index = [color.red,color.blue,color.green,color.yellow]
for (x,y) in piece.geometry:
box (pos = (-100 + x+n,y,0),size = (2,2,1), color = color_index[piece.color])
selected = display(title = 'Selected piece', x = 0, y = 10**6, width = 200,
height = 200, center = (0,0,0), background = (1,1,1),
userzoom = False)
board = display(width = 1000, height = 1000, center = (0, 0, 0),
userzoom = False, background = (0, 0, 1))
hand = display(x = 100, y = 10**6, width = 1000, height = 200,
background = (0,1,1), userzoom = False)
board.visible = True
selected.visible = True
hand.visible = True
p = Piece(3,2)
draw_piece(p, 10)
while True:
if hand.mouse.getclick():
obj = hand.mouse.pick #each piece needs to be printed as a single object
selected.select()
draw_piece(obj,0)
| [
[
1,
0,
0.0303,
0.0303,
0,
0.66,
0,
548,
0,
1,
0,
0,
548,
0,
0
],
[
1,
0,
0.0606,
0.0303,
0,
0.66,
0.0833,
535,
0,
1,
0,
0,
535,
0,
0
],
[
1,
0,
0.0909,
0.0303,
0,
... | [
"from visual import *",
"from Blokus import *",
"from PieceTest import *",
"def draw_piece(piece,n):\n color_index = [color.red,color.blue,color.green,color.yellow]\n for (x,y) in piece.geometry:\n box (pos = (-100 + x+n,y,0),size = (2,2,1), color = color_index[piece.color])",
" color_index ... |
from Gui import *
import ctypes
import threading
import math
import time
##usb = ctypes.cdll.LoadLibrary('usb.dll')
##usb.initialize()
##buffer = ctypes.c_buffer(8)
##def set_ra1_callback():
## usb.control_transfer(dev, 0x40, SET_RA1, 0, 0, 0, buffer)
##
##def clr_ra1_callback():
## usb.control_transfer(dev, 0x40, CLR_RA1, 0, 0, 0, buffer)
# def get_ra2_callback():
# usb.control_transfer(dev, 0xC0, GET_RA2, 0, 0, 1, buffer)
# status.configure(text = 'RA2 is currently %d.' % ord(buffer[0]))
##def set_duty_callback(value):
## usb.control_transfer(dev, 0x40, SET_DUTY, int(value), 0, 0, buffer)
##
##def set_callback(pin):
## global player
## if not (pin in opponentpin or pin in playerpin):
## usb.control_transfer(dev, 0x40, pin, 0, 0, 0, buffer)
## img=PhotoImage(file=['X','O'][int(player)]+'.gif')
## buttons[pin].configure(image=img)
## buttons[pin].image=img
## if player:
## opponentpin.append(pin)
## else:
## playerpin.append(pin)
## player = not player
##
##def make_callback(pin):
## return lambda: set_callback(pin)
##def update_status():
## for pos in opponentpin:
## usb.control_transfer(dev, 0xC0, pos, 0, 0, 1, buffer)
## status.configure(text = 'It is %s''s turn.' % ['X', 'O'][int(player)])
## root.after(50, update_status)
##
####def clear_board():
#### usb.control_transfer(dev, 0x40, 9, 0, 0, 0, buffer)
##
##root = Tk()
##root.title('Lab 3 GUI')
####fm = Frame(root)
####b=Button(root, width=20,text="First").grid(row=0)
####b=Button(root, width=20,text="Second").grid(row=1)
####b=Button(root, width=18,text="PAUL BOOTH").grid(row=0, column=1)
####b=Button(root, width=19,text="Blair's hair").grid(row=7, column=8)
##buttons=[]
##img=PhotoImage(file='blank.GIF')
##for i in xrange(9):
##
#### print img
## b=Button(root, width=64,height=64, text=' ', image=img,command = make_callback(i))
## b.image=img
## b.grid(row=i/3, column=i%3)
## buttons.append(b)
## #b.pack(side = LEFT, padx=2, pady=2)
##
##
###Button(fm, text = ' ', command = clr_ra1_callback).pack(side = LEFT)
### Button(fm, text = 'GET_RA2', command = get_ra2_callback).pack(side = LEFT)
###fm.pack(side = TOP)
###dutyslider = Scale(root, from_ = 0, to = 255, orient = HORIZONTAL, showvalue = FALSE, command = set_duty_callback)
###dutyslider.set(128)
###dutyslider.pack(side = TOP)
##status = Label(root, text = 'Get Ready for FUN.')
##status.grid(row=3,column=0,columnspan=3)
##b=Button(root, text = 'clear board', command = clear_board);
##b.grid(row=4,column=0,columnspan=3)
###status.pack(side = TOP)
##
##dev = usb.open_device(0x6666, 0x0003, 0)
##if dev<0:
## print "No matching device found...\n"
##else:
## ret = usb.control_transfer(dev, 0x00, 0x09, 1, 0, 0, buffer)
## if ret<0:
## print "Unable to send SET_CONFIGURATION standard request.\n"
## clear_board()
## root.after(30, update_status)
## root.mainloop()
## usb.close_device(dev)
class TowerGUI(Gui):
def __init__(self):
Gui.__init__(self)
self.title('Creep Path GUI')
self.ca_width = 1000
self.ca_height = 800
self.fr(LEFT, expand = 1)
self.canvas = self.ca(width=self.ca_width, height=self.ca_height, bg='white')
self.canvas.configure(width=self.ca_width, height=self.ca_height)
self.canvas.bind("<Button-1>", self.clicked)
self.canvas.pack()
self.endfr()
self.clicked_pos = None
self.board=Board()
#self.x=self.y=self.x2=self.y2=100
self.redraw()
thread1=threading.Thread(target=self.mainloop)
thread1.start()
self.infiniteloop()
def redraw(self, event=None):
#self.clear(False)
#self.canvas.create_line(self.x,self.y,self.x2,self.y2, width=4, fill="blue")
self.canvas.delete("all")
self.board.draw(self.canvas)
#print self.board.theta
def clicked(self, event):
self.clicked_pos = (event.x, event.y)
print self.clicked_pos
self.redraw()
def infiniteloop(self):
while 1:
self.board.update()
self.redraw()
#time.sleep(.0001)
class Board:
def __init__(self):
self.creeps=[Creep(i) for i in xrange(1)]
self.creepPath = CreepPath(rate = 0.01)
self.towers = []
self.theta = 0
self.time = 0 #jankity timer solution
self.creep_pos = []
self.towerlist = []
def update(self):
self.time += 1
for tower in self.towers:
tower.update()
self.towerlist.sort()
for tower in self.towerlist:
usb.control_transfer(dev, 0x40, AIM_TOWER, tower[0], tower[1], 0, buffer)
self.creep_pos = []
for creep in self.creeps:
(x,y) = self.creepPath.get_xy_pos(self.time, creep.num) #How does the timer work?
creep.x = 500+10*x
creep.y = 500+10*y
self.creep_pos.append((creep.x,creep.y))
#c = towergui.canvas.create_oval((creep.x, creep.y),fill='black', width = 3)
#I added self.towerlist, lengthened self.update and messed around with towers.
def draw(self, canvas):
for tower in self.creepPath.hardgears:
x = 500+10*tower[0]
y = 500+10*tower[1]
canvas.create_oval(x, y, x + tower[2], y + tower[2], fill = 'red', width = 5)
for creep in self.creep_pos:
canvas.create_oval((creep[0], creep[1], creep[0]+2, creep[1]+2), fill = 'red', width = 5)
## self.oval=canvas.create_oval(500-25, 500-25,
## 525, 525,
## fill="black", activefill="red")
## self.line=canvas.create_line(500,500, 500+100*math.cos(self.theta),500+100*math.sin(self.theta), width=4, fill="blue")
class CreepPath:
def __init__(self, rate = 0.01):
self.rate = rate
self.delimiters=[]
self.gears = []
## self.hardgears = [(34.125,4.75,-1.125),(33.875,18.625,-1.125),(21.125,21.125,1.125),
## (35.25,33.125,-1.5),(4.6,34.875,-1.75),(14.25,14.25,2.375),
## (5.125,4.25,-1.25)]
self.hardgears = [(0,0,1), (0,10,1), (10,10,1), (10,0,1)]
self.setup_path()
def __str__(self):
print "I am a creep path."
## def setup_path(self):
## #each gear is x,y,r
## #x,y position
## #r is radius of the gear
##
## i = 0
## for gear in self.hardgears:
## self.gears.append(Gear(gear))
##
## cumdist = 0
## for i in range(len(self.gears)):
##
## #delimiters in the form [(d1, x1, y1, th_ini, gear)]
## from_gear = self.gears[i-2]
## gear = self.gears[i-1]
## to_gear = self.gears[i]
##
## (t1, t2) = self.cctangent(from_gear, gear)
## (t3, t4) = self.cctangent(gear, to_gear)
## th1 = math.atan2( (t1[1] - from_gear.y) , (t1[0] - from_gear.x) )
## th2 = math.atan2( (t2[1] - gear.y) , (t2[0] - gear.x) )
## th3 = math.atan2( (t3[1] - gear.y) , (t3[0] - gear.x) )
## print "th1 is (%f) , th2 is (%f) , th3 is (%f)" %(th1, th2, th3)
##
## self.delimiters.append((cumdist, t1[0], t1[1], th1, from_gear))
## cumdist += math.sqrt((t2[1] - t1[1])**2 + (t2[0] - t1[0])**2)
## self.delimiters.append((cumdist, t2[0], t2[1], th2, gear))
## cumdist += gear.r*(th3 - th2)
## from_gear = self.gears[i-1]
## gear = self.gears[i]
## try: to_gear = self.gears[i+1]
## except: to_gear = self.gears[1]
## (t1, t2) = self.cctangent(from_gear, gear)
## (t3, t4) = self.cctangent(gear, to_gear)
##
## if i == 0:
## self.delimiters.append((0, t1[0], t1[1], 0, from_gear.r))
## length = math.sqrt((t2[1] - t1[1])**2 + (t2[0] - t1[0])**2)
## self.delimiters.append((length, t2[0], t2[1], 0, 0, gear.x, gear.y))
## cumdist += length
##
## th1 = math.atan2( (t3[0] - gear.x) , (t3[1] - gear.y) )
## th2 = math.atan2( (t2[0] - gear.x) , (t2[1] - gear.y) )
## arc = gear.r*(th1 - th2)
##
## cumdist += abs(arc)
##
## self.delimiters.append((cumdist, t3[0], t3[1], th1, gear.r))
## #total distance, x, y, initial angle, radius
##
## length = math.sqrt((t4[1] - t3[1])**2 + (t4[0] - t3[0])**2)
## cumdist += abs(length)
## self.delimiters.append((cumdist, t4[0], t4[1], 0, 0, to_gear.x, to_gear.y))
## #This is wrong. I'm'a fix this.
## #total distance, x, y
def setup_path(self):
#each gear is x,y,r
#x,y position
#r is radius of the gear
i = 0
for gear in self.hardgears:
self.gears.append(Gear(gear))
cumdist = 0
for i in range(len(self.gears)):
#delimiters in the form [(d1, x1, y1, th_ini, gear)]
from_gear = self.gears[i-2]
gear = self.gears[i-1]
to_gear = self.gears[i]
(t1, t2) = self.cctangent(from_gear, gear)
(t3, t4) = self.cctangent(gear, to_gear)
th1 = math.atan2( (t1[1] - from_gear.y) , (t1[0] - from_gear.x) )
th2 = math.atan2( (t2[1] - gear.y) , (t2[0] - gear.x) )
th3 = math.atan2( (t3[1] - gear.y) , (t3[0] - gear.x) )
self.delimiters.append((cumdist, t1[0], t1[1], th1, from_gear))
cumdist += math.sqrt((t2[1] - t1[1])**2 + (t2[0] - t1[0])**2)
for delim in self.delimiters:
print "d is (%f) , (x,y) is (%f), %f) , th_ini is (%f)" %(delim[0], delim[1], delim[2], delim[3])
return self.delimiters
def cctangent(self, c1, c2):
cen_len = math.sqrt((c2.y-c1.y)**2 + (c2.x-c1.x)**2)
try: cen_angle = math.atan2(c2.y-c1.y,c2.x-c1.x)
except: cen_angle = math.pi/2
tan_len = sqrt(cen_len**2 + (c1.r - c2.r)**2)
tan_angle = math.atan2( (c1.r - c2.r) , cen_len )
th = cen_angle + tan_angle
print th
t2x = c2.x + c2.r * cos(th+math.pi/2)
t2y = c2.y + c2.r * sin(th+math.pi/2)
t1x = t2x + tan_len * cos(th)
t1y = t2y + tan_len * sin(th)
return ((t1x, t1y), (t2x, t2y))
def get_xy_pos(self, t, dist_behind):
d = self.rate * t - dist_behind
if d >= self.delimiters[-1][0]: #The front creep has done a lap
d-=self.delimiters[-1][0]
for i in range(len(self.delimiters)):
#delimiters in the form [(d1, x1, y1, th_ini, gear)]
pfrom = self.delimiters[i-1]
pto = self.delimiters[i]
if pfrom[0] <= d and d < pto[0]:
if i % 1 == 0: #even -> odd sections are linear
x = pfrom[1] + (d - pfrom[0]) / (pto[0] - pfrom[0]) * (pto[1] - pfrom[1])
y = pfrom[2] + (d - pfrom[0]) / (pto[0] - pfrom[0]) * (pto[2] - pfrom[2])
else: #odd -> even sections are turns
x = pfrom[4].x + pto[4].r * math.cos(pto[3] + (d - pfrom[0])/pto[4].r)
y = pfrom[4].y + pto[4].r * math.sin(pto[3] + (d - pfrom[0])/pto[4].r)
return x, y
return 0,0
class Gear:
def __init__(self, (x,y,r), start_theta=0, end_theta=0):
self.x = x
self.y = y
self.r = r
self.start_theta=start_theta
self.end_theta=end_theta
class Creep:
def __init__(self, num=0, HP=10):
self.num=num
self.HP = HP
self.x=0
self.y=0
def hurt(HPloss):
self.HP-=HPloss
return self.HP>0
class Tower:
ttypes = ['Normal','Fire','Water','Earth','Wind']
def __init__ (self, ttype = 0, trange = 10, damage = 5):
self.x = 0
self.y = 0
self.type = ttype
self.delay = 2
self.firetime = time.time() + self.delay
if ttype == 0:
self.range = 15
self.damage = 10
elif ttype == 1:
self.range = 20
self.damage = 8
elif ttype == 2:
self.range = 10
self.damage = 10
elif ttype == 3:
self.range = 15
self.damage = 10
elif ttype == 4:
self.range = 10
self.damage = 30
self.target = None #but don't shoot at it til it's in range!
def __str__(self):
print 'This', ttypes[self.ttype], 'tower is located at (', self.x, ',', self.y, ').'
def update(self):
if self.target == None:
self.target = selecttarget()
#is the current creep dead?
if self.target.HP <= 0:
#if so, find a new creep
self.selecttarget()
self.aim()
if time.time() - self.firetime > self.delay:
self.shoot
def shoot(self):
self.target.hurt(self.damage)
self.firetime = time.time()
def selecttarget(self):
#Choose the first living creep in range
for creep in board.creeps:
if creep.HP > 0:
if math.sqrt( (creep.x - self.x)**2 + (creep.y - self.y)**2) <= self.range:
theta = atan2(self.target.x - self.x, self.target.y - self.y)
if -math.pi/2 < theta < math.pi/2:
self.target = creep
return
self.target = None
return None #We need to deal with the end of the game.
def aim(self):
theta = atan2(self.target.x - self.x, self.target.y - self.y)
SERVO_PLACEMENT = 135-(theta * 110) / 255.0;
board.towerlist.append(SERVO_PLACEMENT, self.address)
#convert to duty cycle and write it to the list for the pic
pass
## class Fire(Tower):
## def __init__(self):
## self.range =
## self.damage =
##
## class Water(Tower):
## def __init__(self):
## self.range =
## self.damage =
##
## class Wind(Tower):
## def __init__(self):
## self.range =
## self.damage =
##
## class Earth(Tower):
## def __init__(self):
## self.range =
## self.damage =
towergui=TowerGUI()
| [
[
1,
0,
0.0023,
0.0023,
0,
0.66,
0,
55,
0,
1,
0,
0,
55,
0,
0
],
[
1,
0,
0.0047,
0.0023,
0,
0.66,
0.0909,
182,
0,
1,
0,
0,
182,
0,
0
],
[
1,
0,
0.007,
0.0023,
0,
0.6... | [
"from Gui import *",
"import ctypes",
"import threading",
"import math",
"import time",
"class TowerGUI(Gui):\n def __init__(self):\n Gui.__init__(self)\n self.title('Creep Path GUI')\n self.ca_width = 1000\n self.ca_height = 800\n self.fr(LEFT, expand = 1)\n s... |
# -*- coding: utf-8 -*-
#
# jQuery File Upload Plugin GAE Python Example 2.1.0
# https://github.com/blueimp/jQuery-File-Upload
#
# Copyright 2011, Sebastian Tschan
# https://blueimp.net
#
# Licensed under the MIT license:
# http://www.opensource.org/licenses/MIT
#
from __future__ import with_statement
from google.appengine.api import files, images
from google.appengine.ext import blobstore, deferred
from google.appengine.ext.webapp import blobstore_handlers
import json
import re
import urllib
import webapp2
WEBSITE = 'http://blueimp.github.io/jQuery-File-Upload/'
MIN_FILE_SIZE = 1 # bytes
MAX_FILE_SIZE = 5000000 # bytes
IMAGE_TYPES = re.compile('image/(gif|p?jpeg|(x-)?png)')
ACCEPT_FILE_TYPES = IMAGE_TYPES
THUMBNAIL_MODIFICATOR = '=s80' # max width / height
EXPIRATION_TIME = 300 # seconds
def cleanup(blob_keys):
blobstore.delete(blob_keys)
class UploadHandler(webapp2.RequestHandler):
def initialize(self, request, response):
super(UploadHandler, self).initialize(request, response)
self.response.headers['Access-Control-Allow-Origin'] = '*'
self.response.headers[
'Access-Control-Allow-Methods'
] = 'OPTIONS, HEAD, GET, POST, PUT, DELETE'
self.response.headers[
'Access-Control-Allow-Headers'
] = 'Content-Type, Content-Range, Content-Disposition'
def validate(self, file):
if file['size'] < MIN_FILE_SIZE:
file['error'] = 'File is too small'
elif file['size'] > MAX_FILE_SIZE:
file['error'] = 'File is too big'
elif not ACCEPT_FILE_TYPES.match(file['type']):
file['error'] = 'Filetype not allowed'
else:
return True
return False
def get_file_size(self, file):
file.seek(0, 2) # Seek to the end of the file
size = file.tell() # Get the position of EOF
file.seek(0) # Reset the file position to the beginning
return size
def write_blob(self, data, info):
blob = files.blobstore.create(
mime_type=info['type'],
_blobinfo_uploaded_filename=info['name']
)
with files.open(blob, 'a') as f:
f.write(data)
files.finalize(blob)
return files.blobstore.get_blob_key(blob)
def handle_upload(self):
results = []
blob_keys = []
for name, fieldStorage in self.request.POST.items():
if type(fieldStorage) is unicode:
continue
result = {}
result['name'] = re.sub(
r'^.*\\',
'',
fieldStorage.filename
)
result['type'] = fieldStorage.type
result['size'] = self.get_file_size(fieldStorage.file)
if self.validate(result):
blob_key = str(
self.write_blob(fieldStorage.value, result)
)
blob_keys.append(blob_key)
result['deleteType'] = 'DELETE'
result['deleteUrl'] = self.request.host_url +\
'/?key=' + urllib.quote(blob_key, '')
if (IMAGE_TYPES.match(result['type'])):
try:
result['url'] = images.get_serving_url(
blob_key,
secure_url=self.request.host_url.startswith(
'https'
)
)
result['thumbnailUrl'] = result['url'] +\
THUMBNAIL_MODIFICATOR
except: # Could not get an image serving url
pass
if not 'url' in result:
result['url'] = self.request.host_url +\
'/' + blob_key + '/' + urllib.quote(
result['name'].encode('utf-8'), '')
results.append(result)
deferred.defer(
cleanup,
blob_keys,
_countdown=EXPIRATION_TIME
)
return results
def options(self):
pass
def head(self):
pass
def get(self):
self.redirect(WEBSITE)
def post(self):
if (self.request.get('_method') == 'DELETE'):
return self.delete()
result = {'files': self.handle_upload()}
s = json.dumps(result, separators=(',', ':'))
redirect = self.request.get('redirect')
if redirect:
return self.redirect(str(
redirect.replace('%s', urllib.quote(s, ''), 1)
))
if 'application/json' in self.request.headers.get('Accept'):
self.response.headers['Content-Type'] = 'application/json'
self.response.write(s)
def delete(self):
blobstore.delete(self.request.get('key') or '')
class DownloadHandler(blobstore_handlers.BlobstoreDownloadHandler):
def get(self, key, filename):
if not blobstore.get(key):
self.error(404)
else:
# Prevent browsers from MIME-sniffing the content-type:
self.response.headers['X-Content-Type-Options'] = 'nosniff'
# Cache for the expiration time:
self.response.headers['Cache-Control'] = 'public,max-age=%d' % EXPIRATION_TIME
# Send the file forcing a download dialog:
self.send_blob(key, save_as=filename, content_type='application/octet-stream')
app = webapp2.WSGIApplication(
[
('/', UploadHandler),
('/([^/]+)/([^/]+)', DownloadHandler)
],
debug=True
)
| [
[
1,
0,
0.0788,
0.0061,
0,
0.66,
0,
777,
0,
1,
0,
0,
777,
0,
0
],
[
1,
0,
0.0848,
0.0061,
0,
0.66,
0.0556,
279,
0,
2,
0,
0,
279,
0,
0
],
[
1,
0,
0.0909,
0.0061,
0,
... | [
"from __future__ import with_statement",
"from google.appengine.api import files, images",
"from google.appengine.ext import blobstore, deferred",
"from google.appengine.ext.webapp import blobstore_handlers",
"import json",
"import re",
"import urllib",
"import webapp2",
"WEBSITE = 'http://blueimp.g... |
# -*- coding: utf-8 -*-
#
# jQuery File Upload Plugin GAE Python Example 2.1.0
# https://github.com/blueimp/jQuery-File-Upload
#
# Copyright 2011, Sebastian Tschan
# https://blueimp.net
#
# Licensed under the MIT license:
# http://www.opensource.org/licenses/MIT
#
from __future__ import with_statement
from google.appengine.api import files, images
from google.appengine.ext import blobstore, deferred
from google.appengine.ext.webapp import blobstore_handlers
import json
import re
import urllib
import webapp2
WEBSITE = 'http://blueimp.github.io/jQuery-File-Upload/'
MIN_FILE_SIZE = 1 # bytes
MAX_FILE_SIZE = 5000000 # bytes
IMAGE_TYPES = re.compile('image/(gif|p?jpeg|(x-)?png)')
ACCEPT_FILE_TYPES = IMAGE_TYPES
THUMBNAIL_MODIFICATOR = '=s80' # max width / height
EXPIRATION_TIME = 300 # seconds
def cleanup(blob_keys):
blobstore.delete(blob_keys)
class UploadHandler(webapp2.RequestHandler):
def initialize(self, request, response):
super(UploadHandler, self).initialize(request, response)
self.response.headers['Access-Control-Allow-Origin'] = '*'
self.response.headers[
'Access-Control-Allow-Methods'
] = 'OPTIONS, HEAD, GET, POST, PUT, DELETE'
self.response.headers[
'Access-Control-Allow-Headers'
] = 'Content-Type, Content-Range, Content-Disposition'
def validate(self, file):
if file['size'] < MIN_FILE_SIZE:
file['error'] = 'File is too small'
elif file['size'] > MAX_FILE_SIZE:
file['error'] = 'File is too big'
elif not ACCEPT_FILE_TYPES.match(file['type']):
file['error'] = 'Filetype not allowed'
else:
return True
return False
def get_file_size(self, file):
file.seek(0, 2) # Seek to the end of the file
size = file.tell() # Get the position of EOF
file.seek(0) # Reset the file position to the beginning
return size
def write_blob(self, data, info):
blob = files.blobstore.create(
mime_type=info['type'],
_blobinfo_uploaded_filename=info['name']
)
with files.open(blob, 'a') as f:
f.write(data)
files.finalize(blob)
return files.blobstore.get_blob_key(blob)
def handle_upload(self):
results = []
blob_keys = []
for name, fieldStorage in self.request.POST.items():
if type(fieldStorage) is unicode:
continue
result = {}
result['name'] = re.sub(
r'^.*\\',
'',
fieldStorage.filename
)
result['type'] = fieldStorage.type
result['size'] = self.get_file_size(fieldStorage.file)
if self.validate(result):
blob_key = str(
self.write_blob(fieldStorage.value, result)
)
blob_keys.append(blob_key)
result['deleteType'] = 'DELETE'
result['deleteUrl'] = self.request.host_url +\
'/?key=' + urllib.quote(blob_key, '')
if (IMAGE_TYPES.match(result['type'])):
try:
result['url'] = images.get_serving_url(
blob_key,
secure_url=self.request.host_url.startswith(
'https'
)
)
result['thumbnailUrl'] = result['url'] +\
THUMBNAIL_MODIFICATOR
except: # Could not get an image serving url
pass
if not 'url' in result:
result['url'] = self.request.host_url +\
'/' + blob_key + '/' + urllib.quote(
result['name'].encode('utf-8'), '')
results.append(result)
deferred.defer(
cleanup,
blob_keys,
_countdown=EXPIRATION_TIME
)
return results
def options(self):
pass
def head(self):
pass
def get(self):
self.redirect(WEBSITE)
def post(self):
if (self.request.get('_method') == 'DELETE'):
return self.delete()
result = {'files': self.handle_upload()}
s = json.dumps(result, separators=(',', ':'))
redirect = self.request.get('redirect')
if redirect:
return self.redirect(str(
redirect.replace('%s', urllib.quote(s, ''), 1)
))
if 'application/json' in self.request.headers.get('Accept'):
self.response.headers['Content-Type'] = 'application/json'
self.response.write(s)
def delete(self):
blobstore.delete(self.request.get('key') or '')
class DownloadHandler(blobstore_handlers.BlobstoreDownloadHandler):
def get(self, key, filename):
if not blobstore.get(key):
self.error(404)
else:
# Prevent browsers from MIME-sniffing the content-type:
self.response.headers['X-Content-Type-Options'] = 'nosniff'
# Cache for the expiration time:
self.response.headers['Cache-Control'] = 'public,max-age=%d' % EXPIRATION_TIME
# Send the file forcing a download dialog:
self.send_blob(key, save_as=filename, content_type='application/octet-stream')
app = webapp2.WSGIApplication(
[
('/', UploadHandler),
('/([^/]+)/([^/]+)', DownloadHandler)
],
debug=True
)
| [
[
1,
0,
0.0788,
0.0061,
0,
0.66,
0,
777,
0,
1,
0,
0,
777,
0,
0
],
[
1,
0,
0.0848,
0.0061,
0,
0.66,
0.0556,
279,
0,
2,
0,
0,
279,
0,
0
],
[
1,
0,
0.0909,
0.0061,
0,
... | [
"from __future__ import with_statement",
"from google.appengine.api import files, images",
"from google.appengine.ext import blobstore, deferred",
"from google.appengine.ext.webapp import blobstore_handlers",
"import json",
"import re",
"import urllib",
"import webapp2",
"WEBSITE = 'http://blueimp.g... |
from sys import stdin
a, b, c = map(int, stdin.readline().strip().split())
print "%.3lf" % ((a+b+c)/3.0)
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.6667,
0.3333,
0,
0.66,
0.5,
256,
3,
2,
0,
0,
53,
10,
4
],
[
8,
0,
1,
0.3333,
0,
0.66,
... | [
"from sys import stdin",
"a, b, c = map(int, stdin.readline().strip().split())",
"print(\"%.3lf\" % ((a+b+c)/3.0))"
] |
from sys import stdin
from math import *
r, h = map(float, stdin.readline().strip().split())
print "Area = %.3lf" % (pi*r*r*2 + 2*pi*r*h)
| [
[
1,
0,
0.25,
0.25,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.5,
0.25,
0,
0.66,
0.3333,
526,
0,
1,
0,
0,
526,
0,
0
],
[
14,
0,
0.75,
0.25,
0,
0.66,
0.... | [
"from sys import stdin",
"from math import *",
"r, h = map(float, stdin.readline().strip().split())",
"print(\"Area = %.3lf\" % (pi*r*r*2 + 2*pi*r*h))"
] |
from sys import stdin
from math import *
n, = map(int, stdin.readline().strip().split())
rad = radians(n)
print "%.3lf %.3lf" % (sin(rad), cos(rad))
| [
[
1,
0,
0.2,
0.2,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.4,
0.2,
0,
0.66,
0.25,
526,
0,
1,
0,
0,
526,
0,
0
],
[
14,
0,
0.6,
0.2,
0,
0.66,
0.5,
... | [
"from sys import stdin",
"from math import *",
"n, = map(int, stdin.readline().strip().split())",
"rad = radians(n)",
"print(\"%.3lf %.3lf\" % (sin(rad), cos(rad)))"
] |
from sys import stdin
n, = map(int, stdin.readline().strip().split())
print n*(n+1)/2
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.6667,
0.3333,
0,
0.66,
0.5,
773,
3,
2,
0,
0,
53,
10,
4
],
[
8,
0,
1,
0.3333,
0,
0.66,
... | [
"from sys import stdin",
"n, = map(int, stdin.readline().strip().split())",
"print(n*(n+1)/2)"
] |
from sys import stdin
a, b = map(int, stdin.readline().strip().split())
print b, a
| [
[
1,
0,
0.25,
0.25,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.5,
0.25,
0,
0.66,
0.5,
127,
3,
2,
0,
0,
53,
10,
4
],
[
8,
0,
0.75,
0.25,
0,
0.66,
1,
... | [
"from sys import stdin",
"a, b = map(int, stdin.readline().strip().split())",
"print(b, a)"
] |
from sys import stdin
n, m = map(int, stdin.readline().strip().split())
a = (4*n-m)/2
b = n-a
if m % 2 == 1 or a < 0 or b < 0: print "No answer"
else: print a, b
| [
[
1,
0,
0.2,
0.2,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.4,
0.2,
0,
0.66,
0.3333,
51,
3,
2,
0,
0,
53,
10,
4
],
[
14,
0,
0.6,
0.2,
0,
0.66,
0.6667,... | [
"from sys import stdin",
"n, m = map(int, stdin.readline().strip().split())",
"a = (4*n-m)/2",
"b = n-a"
] |
from sys import stdin
n, = map(int, stdin.readline().strip().split())
money = n * 95
if money >= 300: money *= 0.85
print "%.2lf" % money
| [
[
1,
0,
0.2,
0.2,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.4,
0.2,
0,
0.66,
0.25,
773,
3,
2,
0,
0,
53,
10,
4
],
[
14,
0,
0.6,
0.2,
0,
0.66,
0.5,
... | [
"from sys import stdin",
"n, = map(int, stdin.readline().strip().split())",
"money = n * 95",
"if money >= 300: money *= 0.85",
"print(\"%.2lf\" % money)"
] |
from sys import stdin
n, = map(int, stdin.readline().strip().split())
print ["yes", "no"][n % 2]
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.6667,
0.3333,
0,
0.66,
0.5,
773,
3,
2,
0,
0,
53,
10,
4
],
[
8,
0,
1,
0.3333,
0,
0.66,
... | [
"from sys import stdin",
"n, = map(int, stdin.readline().strip().split())",
"print [\"yes\", \"no\"][n % 2]"
] |
from sys import stdin
from math import *
x1, y1, x2, y2 = map(float, stdin.readline().strip().split())
print "%.3lf" % hypot((x1-x2), (y1-y2))
| [
[
1,
0,
0.25,
0.25,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.5,
0.25,
0,
0.66,
0.3333,
526,
0,
1,
0,
0,
526,
0,
0
],
[
14,
0,
0.75,
0.25,
0,
0.66,
0.... | [
"from sys import stdin",
"from math import *",
"x1, y1, x2, y2 = map(float, stdin.readline().strip().split())",
"print(\"%.3lf\" % hypot((x1-x2), (y1-y2)))"
] |
from sys import stdin
n = stdin.readline().strip().split()[0]
print '%c%c%c' % (n[2], n[1], n[0])
| [
[
1,
0,
0.25,
0.25,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.5,
0.25,
0,
0.66,
0.5,
773,
6,
0,
0,
0,
0,
0,
3
],
[
8,
0,
0.75,
0.25,
0,
0.66,
1,
... | [
"from sys import stdin",
"n = stdin.readline().strip().split()[0]",
"print('%c%c%c' % (n[2], n[1], n[0]))"
] |
from sys import stdin
x, = map(float, stdin.readline().strip().split())
print abs(x)
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.6667,
0.3333,
0,
0.66,
0.5,
190,
3,
2,
0,
0,
53,
10,
4
],
[
8,
0,
1,
0.3333,
0,
0.66,
... | [
"from sys import stdin",
"x, = map(float, stdin.readline().strip().split())",
"print(abs(x))"
] |
from sys import stdin
from calendar import isleap
year, = map(int, stdin.readline().strip().split())
if isleap(year): print "yes"
else: print "no"
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.6667,
0.3333,
0,
0.66,
0.5,
917,
0,
1,
0,
0,
917,
0,
0
],
[
14,
0,
1,
0.3333,
0,
0.66,
... | [
"from sys import stdin",
"from calendar import isleap",
"year, = map(int, stdin.readline().strip().split())"
] |
from sys import stdin
f, = map(float, stdin.readline().strip().split())
print "%.3lf" % (5*(f-32)/9)
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.6667,
0.3333,
0,
0.66,
0.5,
899,
3,
2,
0,
0,
53,
10,
4
],
[
8,
0,
1,
0.3333,
0,
0.66,
... | [
"from sys import stdin",
"f, = map(float, stdin.readline().strip().split())",
"print(\"%.3lf\" % (5*(f-32)/9))"
] |
from sys import stdin
a, b, c = map(int, stdin.readline().strip().split())
if a*a + b*b == c*c or a*a + c*c == b*b or b*b + c*c == a*a: print "yes"
elif a + b <= c or a + c <= b or b + c <= a: print "not a triangle"
else: print "no"
| [
[
1,
0,
1,
1,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
]
] | [
"from sys import stdin"
] |
from sys import stdin
a = map(int, stdin.readline().strip().split())
a.sort()
print a[0], a[1], a[2]
| [
[
1,
0,
0.2,
0.2,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.4,
0.2,
0,
0.66,
0.3333,
475,
3,
2,
0,
0,
53,
10,
4
],
[
8,
0,
0.6,
0.2,
0,
0.66,
0.6667,... | [
"from sys import stdin",
"a = map(int, stdin.readline().strip().split())",
"a.sort()",
"print(a[0], a[1], a[2])"
] |
s = i = 0
while True:
term = 1.0 / (i*2+1)
s += term * ((-1)**i)
if term < 1e-6: break
i += 1
print "%.6lf" % s
| [
[
14,
0,
0.1429,
0.1429,
0,
0.66,
0,
553,
1,
0,
0,
0,
0,
1,
0
],
[
5,
0,
0.5714,
0.7143,
0,
0.66,
0.5,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
1,
0.4286,
0.1429,
1,
0.87,
... | [
"s = i = 0",
"while True:\n term = 1.0 / (i*2+1)\n s += term * ((-1)**i)\n if term < 1e-6: break\n i += 1",
" term = 1.0 / (i*2+1)",
" if term < 1e-6: break",
"print(\"%.6lf\" % s)"
] |
from sys import stdin
from decimal import *
a, b, c = map(int, stdin.readline().strip().split())
getcontext().prec = c
print Decimal(a) / Decimal(b)
| [
[
1,
0,
0.2,
0.2,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.4,
0.2,
0,
0.66,
0.25,
349,
0,
1,
0,
0,
349,
0,
0
],
[
14,
0,
0.6,
0.2,
0,
0.66,
0.5,
... | [
"from sys import stdin",
"from decimal import *",
"a, b, c = map(int, stdin.readline().strip().split())",
"getcontext().prec = c",
"print(Decimal(a) / Decimal(b))"
] |
from sys import stdin
n = int(stdin.readline().strip())
print "%.3lf" % sum([1.0/x for x in range(1,n+1)])
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.6667,
0.3333,
0,
0.66,
0.5,
773,
3,
1,
0,
0,
901,
10,
3
],
[
8,
0,
1,
0.3333,
0,
0.66,
... | [
"from sys import stdin",
"n = int(stdin.readline().strip())",
"print(\"%.3lf\" % sum([1.0/x for x in range(1,n+1)]))"
] |
from sys import stdin
print len(stdin.readline().strip())
| [
[
1,
0,
0.5,
0.5,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
8,
0,
1,
0.5,
0,
0.66,
1,
535,
3,
1,
0,
0,
0,
0,
4
]
] | [
"from sys import stdin",
"print(len(stdin.readline().strip()))"
] |
from itertools import product
from math import *
def issqrt(n):
s = int(floor(sqrt(n)))
return s*s == n
aabb = [a*1100+b*11 for a,b in product(range(1,10),range(10))]
print ' '.join(map(str, filter(issqrt, aabb)))
| [
[
1,
0,
0.1111,
0.1111,
0,
0.66,
0,
808,
0,
1,
0,
0,
808,
0,
0
],
[
1,
0,
0.2222,
0.1111,
0,
0.66,
0.25,
526,
0,
1,
0,
0,
526,
0,
0
],
[
2,
0,
0.5556,
0.3333,
0,
0.... | [
"from itertools import product",
"from math import *",
"def issqrt(n):\n s = int(floor(sqrt(n)))\n return s*s == n",
" s = int(floor(sqrt(n)))",
" return s*s == n",
"aabb = [a*1100+b*11 for a,b in product(range(1,10),range(10))]",
"print(' '.join(map(str, filter(issqrt, aabb))))"
] |
from sys import stdin
a = map(int, stdin.readline().strip().split())
print "%d %d %.3lf" % (min(a), max(a), float(sum(a)) / len(a))
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.6667,
0.3333,
0,
0.66,
0.5,
475,
3,
2,
0,
0,
53,
10,
4
],
[
8,
0,
1,
0.3333,
0,
0.66,
... | [
"from sys import stdin",
"a = map(int, stdin.readline().strip().split())",
"print(\"%d %d %.3lf\" % (min(a), max(a), float(sum(a)) / len(a)))"
] |
from sys import stdin
def cycle(n):
if n == 1: return 0
elif n % 2 == 1: return cycle(n*3+1) + 1
else: return cycle(n/2) + 1
n = int(stdin.readline().strip())
print cycle(n)
| [
[
1,
0,
0.1111,
0.1111,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
2,
0,
0.5,
0.4444,
0,
0.66,
0.3333,
276,
0,
1,
1,
0,
0,
0,
2
],
[
4,
1,
0.5556,
0.3333,
1,
0.93,... | [
"from sys import stdin",
"def cycle(n):\n if n == 1: return 0\n elif n % 2 == 1: return cycle(n*3+1) + 1\n else: return cycle(n/2) + 1",
" if n == 1: return 0\n elif n % 2 == 1: return cycle(n*3+1) + 1\n else: return cycle(n/2) + 1",
" if n == 1: return 0",
" elif n % 2 == 1: return cycle(n*3+1) + 1... |
from sys import stdin
n = int(stdin.readline().strip())
count = n*2-1
for i in range(n):
print ' '*i + '#'*count
count -= 2
| [
[
1,
0,
0.1667,
0.1667,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.3333,
0.1667,
0,
0.66,
0.3333,
773,
3,
1,
0,
0,
901,
10,
3
],
[
14,
0,
0.5,
0.1667,
0,
... | [
"from sys import stdin",
"n = int(stdin.readline().strip())",
"count = n*2-1",
"for i in range(n):\n print(' '*i + '#'*count)\n count -= 2",
" print(' '*i + '#'*count)"
] |
for abc in range(123, 329):
big = str(abc) + str(abc*2) + str(abc*3)
if(''.join(sorted(big)) == '123456789'): print abc, abc*2, abc*3
| [
[
6,
0,
0.75,
1,
0,
0.66,
0,
38,
3,
0,
0,
0,
0,
0,
4
],
[
14,
1,
1,
0.5,
1,
0.36,
0,
235,
4,
0,
0,
0,
0,
0,
3
]
] | [
"for abc in range(123, 329):\n big = str(abc) + str(abc*2) + str(abc*3)",
" big = str(abc) + str(abc*2) + str(abc*3)"
] |
from sys import stdin
n, m = map(int, stdin.readline().strip().split())
print "%.5lf" % sum([1.0/i/i for i in range(n,m+1)])
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.6667,
0.3333,
0,
0.66,
0.5,
51,
3,
2,
0,
0,
53,
10,
4
],
[
8,
0,
1,
0.3333,
0,
0.66,
... | [
"from sys import stdin",
"n, m = map(int, stdin.readline().strip().split())",
"print(\"%.5lf\" % sum([1.0/i/i for i in range(n,m+1)]))"
] |
from sys import stdin
data = map(int, stdin.readline().strip().split())
n, m = data[0], data[-1]
data = data[1:-1]
print len(filter(lambda x: x < m, data))
| [
[
1,
0,
0.2,
0.2,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.4,
0.2,
0,
0.66,
0.25,
929,
3,
2,
0,
0,
53,
10,
4
],
[
14,
0,
0.6,
0.2,
0,
0.66,
0.5,
... | [
"from sys import stdin",
"data = map(int, stdin.readline().strip().split())",
"n, m = data[0], data[-1]",
"data = data[1:-1]",
"print(len(filter(lambda x: x < m, data)))"
] |
from sys import stdin
def solve(a, b, c):
for i in range(10, 101):
if i % 3 == a and i % 5 == b and i % 7 == c:
print i
return
print 'No answer'
a, b, c = map(int, stdin.readline().strip().split())
solve(a, b, c)
| [
[
1,
0,
0.0909,
0.0909,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
2,
0,
0.5,
0.5455,
0,
0.66,
0.3333,
599,
0,
3,
0,
0,
0,
0,
3
],
[
6,
1,
0.5,
0.3636,
1,
0.59,
... | [
"from sys import stdin",
"def solve(a, b, c):\n for i in range(10, 101):\n if i % 3 == a and i % 5 == b and i % 7 == c:\n print(i)\n return\n print('No answer')",
" for i in range(10, 101):\n if i % 3 == a and i % 5 == b and i % 7 == c:\n print(i)\n return",
" if i % 3 == a and... |
from itertools import product
sol = [a*100+b*10+c for a,b,c in product(range(1,10), range(10), range(10)) if a**3+b**3+c**3 == a*100+b*10+c]
print '\n'.join(map(str, sol))
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
808,
0,
1,
0,
0,
808,
0,
0
],
[
14,
0,
0.6667,
0.3333,
0,
0.66,
0.5,
723,
5,
0,
0,
0,
0,
0,
4
],
[
8,
0,
1,
0.3333,
0,
0.66,
... | [
"from itertools import product",
"sol = [a*100+b*10+c for a,b,c in product(range(1,10), range(10), range(10)) if a**3+b**3+c**3 == a*100+b*10+c]",
"print('\\n'.join(map(str, sol)))"
] |
from sys import stdin
from math import *
n = int(stdin.readline().strip())
print sum(map(factorial, range(1,n+1))) % (10**6)
| [
[
1,
0,
0.2,
0.2,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.4,
0.2,
0,
0.66,
0.3333,
526,
0,
1,
0,
0,
526,
0,
0
],
[
14,
0,
0.6,
0.2,
0,
0.66,
0.6667,... | [
"from sys import stdin",
"from math import *",
"n = int(stdin.readline().strip())",
"print(sum(map(factorial, range(1,n+1))) % (10**6))"
] |
#!/usr/bin/python2.6
#
# Simple http server to emulate api.playfoursquare.com
import logging
import shutil
import sys
import urlparse
import SimpleHTTPServer
import BaseHTTPServer
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""Handle playfoursquare.com requests, for testing."""
def do_GET(self):
logging.warn('do_GET: %s, %s', self.command, self.path)
url = urlparse.urlparse(self.path)
logging.warn('do_GET: %s', url)
query = urlparse.parse_qs(url.query)
query_keys = [pair[0] for pair in query]
response = self.handle_url(url)
if response != None:
self.send_200()
shutil.copyfileobj(response, self.wfile)
self.wfile.close()
do_POST = do_GET
def handle_url(self, url):
path = None
if url.path == '/v1/venue':
path = '../captures/api/v1/venue.xml'
elif url.path == '/v1/addvenue':
path = '../captures/api/v1/venue.xml'
elif url.path == '/v1/venues':
path = '../captures/api/v1/venues.xml'
elif url.path == '/v1/user':
path = '../captures/api/v1/user.xml'
elif url.path == '/v1/checkcity':
path = '../captures/api/v1/checkcity.xml'
elif url.path == '/v1/checkins':
path = '../captures/api/v1/checkins.xml'
elif url.path == '/v1/cities':
path = '../captures/api/v1/cities.xml'
elif url.path == '/v1/switchcity':
path = '../captures/api/v1/switchcity.xml'
elif url.path == '/v1/tips':
path = '../captures/api/v1/tips.xml'
elif url.path == '/v1/checkin':
path = '../captures/api/v1/checkin.xml'
elif url.path == '/history/12345.rss':
path = '../captures/api/v1/feed.xml'
if path is None:
self.send_error(404)
else:
logging.warn('Using: %s' % path)
return open(path)
def send_200(self):
self.send_response(200)
self.send_header('Content-type', 'text/xml')
self.end_headers()
def main():
if len(sys.argv) > 1:
port = int(sys.argv[1])
else:
port = 8080
server_address = ('0.0.0.0', port)
httpd = BaseHTTPServer.HTTPServer(server_address, RequestHandler)
sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
if __name__ == '__main__':
main()
| [
[
1,
0,
0.0588,
0.0118,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0706,
0.0118,
0,
0.66,
0.125,
614,
0,
1,
0,
0,
614,
0,
0
],
[
1,
0,
0.0824,
0.0118,
0,
0... | [
"import logging",
"import shutil",
"import sys",
"import urlparse",
"import SimpleHTTPServer",
"import BaseHTTPServer",
"class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):\n \"\"\"Handle playfoursquare.com requests, for testing.\"\"\"\n\n def do_GET(self):\n logging.warn('do_GET: %s, %s',... |
#!/usr/bin/python
import datetime
import sys
import textwrap
import common
from xml.dom import pulldom
PARSER = """\
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.parsers;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareError;
import com.joelapenna.foursquare.error.FoursquareParseException;
import com.joelapenna.foursquare.types.%(type_name)s;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Auto-generated: %(timestamp)s
*
* @author Joe LaPenna (joe@joelapenna.com)
* @param <T>
*/
public class %(type_name)sParser extends AbstractParser<%(type_name)s> {
private static final Logger LOG = Logger.getLogger(%(type_name)sParser.class.getCanonicalName());
private static final boolean DEBUG = Foursquare.PARSER_DEBUG;
@Override
public %(type_name)s parseInner(XmlPullParser parser) throws XmlPullParserException, IOException,
FoursquareError, FoursquareParseException {
parser.require(XmlPullParser.START_TAG, null, null);
%(type_name)s %(top_node_name)s = new %(type_name)s();
while (parser.nextTag() == XmlPullParser.START_TAG) {
String name = parser.getName();
%(stanzas)s
} else {
// Consume something we don't understand.
if (DEBUG) LOG.log(Level.FINE, "Found tag that we don't recognize: " + name);
skipSubTree(parser);
}
}
return %(top_node_name)s;
}
}"""
BOOLEAN_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(Boolean.valueOf(parser.nextText()));
"""
GROUP_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(new GroupParser(new %(sub_parser_camel_case)s()).parse(parser));
"""
COMPLEX_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(new %(parser_name)s().parse(parser));
"""
STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(parser.nextText());
"""
def main():
type_name, top_node_name, attributes = common.WalkNodesForAttributes(
sys.argv[1])
GenerateClass(type_name, top_node_name, attributes)
def GenerateClass(type_name, top_node_name, attributes):
"""generate it.
type_name: the type of object the parser returns
top_node_name: the name of the object the parser returns.
per common.WalkNodsForAttributes
"""
stanzas = []
for name in sorted(attributes):
typ, children = attributes[name]
replacements = Replacements(top_node_name, name, typ, children)
if typ == common.BOOLEAN:
stanzas.append(BOOLEAN_STANZA % replacements)
elif typ == common.GROUP:
stanzas.append(GROUP_STANZA % replacements)
elif typ in common.COMPLEX:
stanzas.append(COMPLEX_STANZA % replacements)
else:
stanzas.append(STANZA % replacements)
if stanzas:
# pop off the extranious } else for the first conditional stanza.
stanzas[0] = stanzas[0].replace('} else ', '', 1)
replacements = Replacements(top_node_name, name, typ, [None])
replacements['stanzas'] = '\n'.join(stanzas).strip()
print PARSER % replacements
def Replacements(top_node_name, name, typ, children):
# CameCaseClassName
type_name = ''.join([word.capitalize() for word in top_node_name.split('_')])
# CamelCaseClassName
camel_name = ''.join([word.capitalize() for word in name.split('_')])
# camelCaseLocalName
attribute_name = camel_name.lower().capitalize()
# mFieldName
field_name = 'm' + camel_name
if children[0]:
sub_parser_camel_case = children[0] + 'Parser'
else:
sub_parser_camel_case = (camel_name[:-1] + 'Parser')
return {
'type_name': type_name,
'name': name,
'top_node_name': top_node_name,
'camel_name': camel_name,
'parser_name': typ + 'Parser',
'attribute_name': attribute_name,
'field_name': field_name,
'typ': typ,
'timestamp': datetime.datetime.now(),
'sub_parser_camel_case': sub_parser_camel_case,
'sub_type': children[0]
}
if __name__ == '__main__':
main()
| [
[
1,
0,
0.0201,
0.0067,
0,
0.66,
0,
426,
0,
1,
0,
0,
426,
0,
0
],
[
1,
0,
0.0268,
0.0067,
0,
0.66,
0.0769,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0336,
0.0067,
0,
... | [
"import datetime",
"import sys",
"import textwrap",
"import common",
"from xml.dom import pulldom",
"PARSER = \"\"\"\\\n/**\n * Copyright 2009 Joe LaPenna\n */\n\npackage com.joelapenna.foursquare.parsers;\n\nimport com.joelapenna.foursquare.Foursquare;",
"BOOLEAN_STANZA = \"\"\"\\\n } else i... |
#!/usr/bin/python
"""
Pull a oAuth protected page from foursquare.
Expects ~/.oget to contain (one on each line):
CONSUMER_KEY
CONSUMER_KEY_SECRET
USERNAME
PASSWORD
Don't forget to chmod 600 the file!
"""
import httplib
import os
import re
import sys
import urllib
import urllib2
import urlparse
import user
from xml.dom import pulldom
from xml.dom import minidom
import oauth
"""From: http://groups.google.com/group/foursquare-api/web/oauth
@consumer = OAuth::Consumer.new("consumer_token","consumer_secret", {
:site => "http://foursquare.com",
:scheme => :header,
:http_method => :post,
:request_token_path => "/oauth/request_token",
:access_token_path => "/oauth/access_token",
:authorize_path => "/oauth/authorize"
})
"""
SERVER = 'api.foursquare.com:80'
CONTENT_TYPE_HEADER = {'Content-Type' :'application/x-www-form-urlencoded'}
SIGNATURE_METHOD = oauth.OAuthSignatureMethod_HMAC_SHA1()
AUTHEXCHANGE_URL = 'http://api.foursquare.com/v1/authexchange'
def parse_auth_response(auth_response):
return (
re.search('<oauth_token>(.*)</oauth_token>', auth_response).groups()[0],
re.search('<oauth_token_secret>(.*)</oauth_token_secret>',
auth_response).groups()[0]
)
def create_signed_oauth_request(username, password, consumer):
oauth_request = oauth.OAuthRequest.from_consumer_and_token(
consumer, http_method='POST', http_url=AUTHEXCHANGE_URL,
parameters=dict(fs_username=username, fs_password=password))
oauth_request.sign_request(SIGNATURE_METHOD, consumer, None)
return oauth_request
def main():
url = urlparse.urlparse(sys.argv[1])
# Nevermind that the query can have repeated keys.
parameters = dict(urlparse.parse_qsl(url.query))
password_file = open(os.path.join(user.home, '.oget'))
lines = [line.strip() for line in password_file.readlines()]
if len(lines) == 4:
cons_key, cons_key_secret, username, password = lines
access_token = None
else:
cons_key, cons_key_secret, username, password, token, secret = lines
access_token = oauth.OAuthToken(token, secret)
consumer = oauth.OAuthConsumer(cons_key, cons_key_secret)
if not access_token:
oauth_request = create_signed_oauth_request(username, password, consumer)
connection = httplib.HTTPConnection(SERVER)
headers = {'Content-Type' :'application/x-www-form-urlencoded'}
connection.request(oauth_request.http_method, AUTHEXCHANGE_URL,
body=oauth_request.to_postdata(), headers=headers)
auth_response = connection.getresponse().read()
token = parse_auth_response(auth_response)
access_token = oauth.OAuthToken(*token)
open(os.path.join(user.home, '.oget'), 'w').write('\n'.join((
cons_key, cons_key_secret, username, password, token[0], token[1])))
oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer,
access_token, http_method='POST', http_url=url.geturl(),
parameters=parameters)
oauth_request.sign_request(SIGNATURE_METHOD, consumer, access_token)
connection = httplib.HTTPConnection(SERVER)
connection.request(oauth_request.http_method, oauth_request.to_url(),
body=oauth_request.to_postdata(), headers=CONTENT_TYPE_HEADER)
print connection.getresponse().read()
#print minidom.parse(connection.getresponse()).toprettyxml(indent=' ')
if __name__ == '__main__':
main()
| [
[
8,
0,
0.0631,
0.0991,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1261,
0.009,
0,
0.66,
0.05,
2,
0,
1,
0,
0,
2,
0,
0
],
[
1,
0,
0.1351,
0.009,
0,
0.66,
0.... | [
"\"\"\"\nPull a oAuth protected page from foursquare.\n\nExpects ~/.oget to contain (one on each line):\nCONSUMER_KEY\nCONSUMER_KEY_SECRET\nUSERNAME\nPASSWORD",
"import httplib",
"import os",
"import re",
"import sys",
"import urllib",
"import urllib2",
"import urlparse",
"import user",
"from xml.... |
#!/usr/bin/python
import os
import subprocess
import sys
BASEDIR = '../main/src/com/joelapenna/foursquare'
TYPESDIR = '../captures/types/v1'
captures = sys.argv[1:]
if not captures:
captures = os.listdir(TYPESDIR)
for f in captures:
basename = f.split('.')[0]
javaname = ''.join([c.capitalize() for c in basename.split('_')])
fullpath = os.path.join(TYPESDIR, f)
typepath = os.path.join(BASEDIR, 'types', javaname + '.java')
parserpath = os.path.join(BASEDIR, 'parsers', javaname + 'Parser.java')
cmd = 'python gen_class.py %s > %s' % (fullpath, typepath)
print cmd
subprocess.call(cmd, stdout=sys.stdout, shell=True)
cmd = 'python gen_parser.py %s > %s' % (fullpath, parserpath)
print cmd
subprocess.call(cmd, stdout=sys.stdout, shell=True)
| [
[
1,
0,
0.1111,
0.037,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.1481,
0.037,
0,
0.66,
0.1429,
394,
0,
1,
0,
0,
394,
0,
0
],
[
1,
0,
0.1852,
0.037,
0,
0.6... | [
"import os",
"import subprocess",
"import sys",
"BASEDIR = '../main/src/com/joelapenna/foursquare'",
"TYPESDIR = '../captures/types/v1'",
"captures = sys.argv[1:]",
"if not captures:\n captures = os.listdir(TYPESDIR)",
" captures = os.listdir(TYPESDIR)",
"for f in captures:\n basename = f.split('... |
#!/usr/bin/python
import logging
from xml.dom import minidom
from xml.dom import pulldom
BOOLEAN = "boolean"
STRING = "String"
GROUP = "Group"
# Interfaces that all FoursquareTypes implement.
DEFAULT_INTERFACES = ['FoursquareType']
# Interfaces that specific FoursqureTypes implement.
INTERFACES = {
}
DEFAULT_CLASS_IMPORTS = [
]
CLASS_IMPORTS = {
# 'Checkin': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
# 'Venue': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
# 'Tip': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
}
COMPLEX = [
'Group',
'Badge',
'Beenhere',
'Checkin',
'CheckinResponse',
'City',
'Credentials',
'Data',
'Mayor',
'Rank',
'Score',
'Scoring',
'Settings',
'Stats',
'Tags',
'Tip',
'User',
'Venue',
]
TYPES = COMPLEX + ['boolean']
def WalkNodesForAttributes(path):
"""Parse the xml file getting all attributes.
<venue>
<attribute>value</attribute>
</venue>
Returns:
type_name - The java-style name the top node will have. "Venue"
top_node_name - unadultured name of the xml stanza, probably the type of
java class we're creating. "venue"
attributes - {'attribute': 'value'}
"""
doc = pulldom.parse(path)
type_name = None
top_node_name = None
attributes = {}
level = 0
for event, node in doc:
# For skipping parts of a tree.
if level > 0:
if event == pulldom.END_ELEMENT:
level-=1
logging.warn('(%s) Skip end: %s' % (str(level), node))
continue
elif event == pulldom.START_ELEMENT:
logging.warn('(%s) Skipping: %s' % (str(level), node))
level+=1
continue
if event == pulldom.START_ELEMENT:
logging.warn('Parsing: ' + node.tagName)
# Get the type name to use.
if type_name is None:
type_name = ''.join([word.capitalize()
for word in node.tagName.split('_')])
top_node_name = node.tagName
logging.warn('Found Top Node Name: ' + top_node_name)
continue
typ = node.getAttribute('type')
child = node.getAttribute('child')
# We don't want to walk complex types.
if typ in COMPLEX:
logging.warn('Found Complex: ' + node.tagName)
level = 1
elif typ not in TYPES:
logging.warn('Found String: ' + typ)
typ = STRING
else:
logging.warn('Found Type: ' + typ)
logging.warn('Adding: ' + str((node, typ)))
attributes.setdefault(node.tagName, (typ, [child]))
logging.warn('Attr: ' + str((type_name, top_node_name, attributes)))
return type_name, top_node_name, attributes
| [
[
1,
0,
0.0263,
0.0088,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0439,
0.0088,
0,
0.66,
0.0833,
290,
0,
1,
0,
0,
290,
0,
0
],
[
1,
0,
0.0526,
0.0088,
0,
... | [
"import logging",
"from xml.dom import minidom",
"from xml.dom import pulldom",
"BOOLEAN = \"boolean\"",
"STRING = \"String\"",
"GROUP = \"Group\"",
"DEFAULT_INTERFACES = ['FoursquareType']",
"INTERFACES = {\n}",
"DEFAULT_CLASS_IMPORTS = [\n]",
"CLASS_IMPORTS = {\n# 'Checkin': DEFAULT_CLASS_IMP... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 by Alessandro Presta
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE
'''
======
tagger
======
Module for extracting tags from text documents.
Copyright (C) 2011 by Alessandro Presta
Configuration
=============
Dependencies:
python2.7, stemming, nltk (optional), lxml (optional), tkinter (optional)
You can install the stemming package with::
$ easy_install stemming
Usage
=====
Tagging a text document from Python::
import tagger
weights = pickle.load(open('data/dict.pkl', 'rb')) # or your own dictionary
myreader = tagger.Reader() # or your own reader class
mystemmer = tagger.Stemmer() # or your own stemmer class
myrater = tagger.Rater(weights) # or your own... (you got the idea)
mytagger = Tagger(myreader, mystemmer, myrater)
best_3_tags = mytagger(text_string, 3)
Running the module as a script::
$ ./tagger.py <text document(s) to tag>
Example::
$ ./tagger.py tests/*
Loading dictionary...
Tags for tests/bbc1.txt :
['bin laden', 'obama', 'pakistan', 'killed', 'raid']
Tags for tests/bbc2.txt :
['jo yeates', 'bristol', 'vincent tabak', 'murder', 'strangled']
Tags for tests/bbc3.txt :
['snp', 'party', 'election', 'scottish', 'labour']
Tags for tests/guardian1.txt :
['bin laden', 'al-qaida', 'killed', 'pakistan', 'al-fawwaz']
Tags for tests/guardian2.txt :
['clegg', 'tory', 'lib dem', 'party', 'coalition']
Tags for tests/post1.txt :
['sony', 'stolen', 'playstation network', 'hacker attack', 'lawsuit']
Tags for tests/wikipedia1.txt :
['universe', 'anthropic principle', 'observed', 'cosmological', 'theory']
Tags for tests/wikipedia2.txt :
['beetroot', 'beet', 'betaine', 'blood pressure', 'dietary nitrate']
Tags for tests/wikipedia3.txt :
['the lounge lizards', 'jazz', 'john lurie', 'musical', 'albums']
'''
from __future__ import division
import collections
import re
class Tag:
'''
General class for tags (small units of text)
'''
def __init__(self, string, stem=None, rating=1.0, proper=False,
terminal=False):
'''
@param string: the actual representation of the tag
@param stem: the internal (usually stemmed) representation;
tags with the same stem are regarded as equal
@param rating: a measure of the tag's relevance in the interval [0,1]
@param proper: whether the tag is a proper noun
@param terminal: set to True if the tag is at the end of a phrase
(or anyway it cannot be logically merged to the
following one)
@returns: a new L{Tag} object
'''
self.string = string
self.stem = stem or string
self.rating = rating
self.proper = proper
self.terminal = terminal
def __eq__(self, other):
return self.stem == other.stem
def __repr__(self):
return repr(self.string)
def __lt__(self, other):
return self.rating > other.rating
def __hash__(self):
return hash(self.stem)
class MultiTag(Tag):
'''
Class for aggregates of tags (usually next to each other in the document)
'''
def __init__(self, tail, head=None):
'''
@param tail: the L{Tag} object to add to the first part (head)
@param head: the (eventually absent) L{MultiTag} to be extended
@returns: a new L{MultiTag} object
'''
if not head:
Tag.__init__(self, tail.string, tail.stem, tail.rating,
tail.proper, tail.terminal)
self.size = 1
self.subratings = [self.rating]
else:
self.string = ' '.join([head.string, tail.string])
self.stem = ' '.join([head.stem, tail.stem])
self.size = head.size + 1
self.proper = (head.proper and tail.proper)
self.terminal = tail.terminal
self.subratings = head.subratings + [tail.rating]
self.rating = self.combined_rating()
def combined_rating(self):
'''
Method that computes the multitag's rating from the ratings of unit
subtags
(the default implementation uses the geometric mean - with a special
treatment for proper nouns - but this method can be overridden)
@returns: the rating of the multitag
'''
# by default, the rating of a multitag is the geometric mean of its
# unit subtags' ratings
product = reduce(lambda x, y: x * y, self.subratings, 1.0)
root = self.size
# but proper nouns shouldn't be penalized by stopwords
if product == 0.0 and self.proper:
nonzero = [r for r in self.subratings if r > 0.0]
if len(nonzero) == 0:
return 0.0
product = reduce(lambda x, y: x * y, nonzero, 1.0)
root = len(nonzero)
return product ** (1.0 / root)
class Reader:
'''
Class for parsing a string of text to obtain tags
(it just turns the string to lowercase and splits it according to
whitespaces and punctuation, identifying proper nouns and terminal words;
different rules and formats other than plain text could be used)
'''
match_apostrophes = re.compile(r'`|’')
match_paragraphs = re.compile(r'[\.\?!\t\n\r\f\v]+')
match_phrases = re.compile(r'[,;:\(\)\[\]\{\}<>]+')
match_words = re.compile(r'[\w\-\'_/&]+')
def __call__(self, text):
'''
@param text: the string of text to be tagged
@returns: a list of tags respecting the order in the text
'''
text = self.preprocess(text)
# split by full stops, newlines, question marks...
paragraphs = self.match_paragraphs.split(text)
tags = []
for par in paragraphs:
# split by commas, colons, parentheses...
phrases = self.match_phrases.split(par)
if len(phrases) > 0:
# first phrase of a paragraph
words = self.match_words.findall(phrases[0])
if len(words) > 1:
tags.append(Tag(words[0].lower()))
for w in words[1:-1]:
tags.append(Tag(w.lower(), proper=w[0].isupper()))
tags.append(Tag(words[-1].lower(),
proper=words[-1][0].isupper(),
terminal=True))
elif len(words) == 1:
tags.append(Tag(words[0].lower(), terminal=True))
# following phrases
for phr in phrases[1:]:
words = self.match_words.findall(phr)
if len(words) > 1:
for w in words[:-1]:
tags.append(Tag(w.lower(), proper=w[0].isupper()))
if len(words) > 0:
tags.append(Tag(words[-1].lower(),
proper=words[-1][0].isupper(),
terminal=True))
return tags
def preprocess(self, text):
'''
@param text: a string containing the text document to perform any
required transformation before splitting
@returns: the processed text
'''
text = self.match_apostrophes.sub('\'', text)
return text
class Stemmer:
'''
Class for extracting the stem of a word
(by default it uses a simple open-source implementation of Porter's
algorithm; this can be improved a lot, so experimenting with different ones
is advisable; nltk.stem provides different algorithms for many languages)
'''
match_contractions = re.compile(r'(\w+)\'(m|re|d|ve|s|ll|t)?')
match_hyphens = re.compile(r'\b[\-_]\b')
def __init__(self, stemmer=None):
'''
@param stemmer: an object or module with a 'stem' method (defaults to
stemming.porter2)
@returns: a new L{Stemmer} object
'''
if not stemmer:
from stemming import porter2
stemmer = porter2
self.stemmer = stemmer
def __call__(self, tag):
'''
@param tag: the tag to be stemmed
@returns: the stemmed tag
'''
string = self.preprocess(tag.string)
tag.stem = self.stemmer.stem(string)
return tag
def preprocess(self, string):
'''
@param string: a string to be treated before passing it to the stemmer
@returns: the processed string
'''
# delete hyphens and underscores
string = self.match_hyphens.sub('', string)
# get rid of contractions and possessive forms
match = self.match_contractions.match(string)
if match: string = match.group(1)
return string
class Rater:
'''
Class for estimating the relevance of tags
(the default implementation uses TF (term frequency) multiplied by weight,
but any other reasonable measure is fine; a quite rudimental heuristic
tries to discard redundant tags)
'''
def __init__(self, weights, multitag_size=3):
'''
@param weights: a dictionary of weights normalized in the
interval [0,1]
@param multitag_size: maximum size of tags formed by multiple unit
tags
@returns: a new L{Rater} object
'''
self.weights = weights
self.multitag_size = multitag_size
def __call__(self, tags):
'''
@param tags: a list of (preferably stemmed) tags
@returns: a list of unique (multi)tags sorted by relevance
'''
self.rate_tags(tags)
multitags = self.create_multitags(tags)
# keep most frequent version of each tag
clusters = collections.defaultdict(collections.Counter)
proper = collections.defaultdict(int)
ratings = collections.defaultdict(float)
for t in multitags:
clusters[t][t.string] += 1
if t.proper:
proper[t] += 1
ratings[t] = max(ratings[t], t.rating)
term_count = collections.Counter(multitags)
for t, cnt in term_count.iteritems():
t.string = clusters[t].most_common(1)[0][0]
proper_freq = proper[t] / cnt
if proper_freq >= 0.5:
t.proper = True
t.rating = ratings[t]
# purge duplicates, one-character tags and stopwords
unique_tags = set(t for t in term_count
if len(t.string) > 1 and t.rating > 0.0)
# remove redundant tags
for t, cnt in term_count.iteritems():
words = t.stem.split()
for l in xrange(1, len(words)):
for i in xrange(len(words) - l + 1):
s = Tag(' '.join(words[i:i + l]))
relative_freq = cnt / term_count[s]
if ((relative_freq == 1.0 and t.proper) or
(relative_freq >= 0.5 and t.rating > 0.0)):
unique_tags.discard(s)
else:
unique_tags.discard(t)
return sorted(unique_tags)
def rate_tags(self, tags):
'''
@param tags: a list of tags to be assigned a rating
'''
term_count = collections.Counter(tags)
for t in tags:
# rating of a single tag is term frequency * weight
t.rating = term_count[t] / len(tags) * self.weights.get(t.stem, 1.0)
def create_multitags(self, tags):
'''
@param tags: a list of tags (respecting the order in the text)
@returns: a list of multitags
'''
multitags = []
for i in xrange(len(tags)):
t = MultiTag(tags[i])
multitags.append(t)
for j in xrange(1, self.multitag_size):
if t.terminal or i + j >= len(tags):
break
else:
t = MultiTag(tags[i + j], t)
multitags.append(t)
return multitags
class Tagger:
'''
Master class for tagging text documents
(this is a simple interface that should allow convenient experimentation
by using different classes as building blocks)
'''
def __init__(self, reader, stemmer, rater):
'''
@param reader: a L{Reader} object
@param stemmer: a L{Stemmer} object
@param rater: a L{Rater} object
@returns: a new L{Tagger} object
'''
self.reader = reader
self.stemmer = stemmer
self.rater = rater
def __call__(self, text, tags_number=5):
'''
@param text: the string of text to be tagged
@param tags_number: number of best tags to be returned
Returns: a list of (hopefully) relevant tags
'''
tags = self.reader(text)
tags = map(self.stemmer, tags)
tags = self.rater(tags)
return tags[:tags_number]
if __name__ == '__main__':
import glob
import pickle
import sys
if len(sys.argv) < 2:
print 'No arguments given, running tests: '
documents = glob.glob('tests/*')
else:
documents = sys.argv[1:]
print 'Loading dictionary... '
weights = pickle.load(open('data/dict.pkl', 'rb'))
tagger = Tagger(Reader(), Stemmer(), Rater(weights))
for doc in documents:
with open(doc, 'r') as file:
print 'Tags for ', doc, ':'
print tagger(file.read())
| [
[
8,
0,
0.1149,
0.1255,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1809,
0.0021,
0,
0.66,
0.1,
777,
0,
1,
0,
0,
777,
0,
0
],
[
1,
0,
0.1851,
0.0021,
0,
0.66,
... | [
"'''\n======\ntagger\n======\n\nModule for extracting tags from text documents.\n \nCopyright (C) 2011 by Alessandro Presta",
"from __future__ import division",
"import collections",
"import re",
"class Tag:\n '''\n General class for tags (small units of text)\n '''\n \n def... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 by Alessandro Presta
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE
'''
======
tagger
======
Module for extracting tags from text documents.
Copyright (C) 2011 by Alessandro Presta
Configuration
=============
Dependencies:
python2.7, stemming, nltk (optional), lxml (optional), tkinter (optional)
You can install the stemming package with::
$ easy_install stemming
Usage
=====
Tagging a text document from Python::
import tagger
weights = pickle.load(open('data/dict.pkl', 'rb')) # or your own dictionary
myreader = tagger.Reader() # or your own reader class
mystemmer = tagger.Stemmer() # or your own stemmer class
myrater = tagger.Rater(weights) # or your own... (you got the idea)
mytagger = Tagger(myreader, mystemmer, myrater)
best_3_tags = mytagger(text_string, 3)
Running the module as a script::
$ ./tagger.py <text document(s) to tag>
Example::
$ ./tagger.py tests/*
Loading dictionary...
Tags for tests/bbc1.txt :
['bin laden', 'obama', 'pakistan', 'killed', 'raid']
Tags for tests/bbc2.txt :
['jo yeates', 'bristol', 'vincent tabak', 'murder', 'strangled']
Tags for tests/bbc3.txt :
['snp', 'party', 'election', 'scottish', 'labour']
Tags for tests/guardian1.txt :
['bin laden', 'al-qaida', 'killed', 'pakistan', 'al-fawwaz']
Tags for tests/guardian2.txt :
['clegg', 'tory', 'lib dem', 'party', 'coalition']
Tags for tests/post1.txt :
['sony', 'stolen', 'playstation network', 'hacker attack', 'lawsuit']
Tags for tests/wikipedia1.txt :
['universe', 'anthropic principle', 'observed', 'cosmological', 'theory']
Tags for tests/wikipedia2.txt :
['beetroot', 'beet', 'betaine', 'blood pressure', 'dietary nitrate']
Tags for tests/wikipedia3.txt :
['the lounge lizards', 'jazz', 'john lurie', 'musical', 'albums']
'''
from __future__ import division
import collections
import re
class Tag:
'''
General class for tags (small units of text)
'''
def __init__(self, string, stem=None, rating=1.0, proper=False,
terminal=False):
'''
@param string: the actual representation of the tag
@param stem: the internal (usually stemmed) representation;
tags with the same stem are regarded as equal
@param rating: a measure of the tag's relevance in the interval [0,1]
@param proper: whether the tag is a proper noun
@param terminal: set to True if the tag is at the end of a phrase
(or anyway it cannot be logically merged to the
following one)
@returns: a new L{Tag} object
'''
self.string = string
self.stem = stem or string
self.rating = rating
self.proper = proper
self.terminal = terminal
def __eq__(self, other):
return self.stem == other.stem
def __repr__(self):
return repr(self.string)
def __lt__(self, other):
return self.rating > other.rating
def __hash__(self):
return hash(self.stem)
class MultiTag(Tag):
'''
Class for aggregates of tags (usually next to each other in the document)
'''
def __init__(self, tail, head=None):
'''
@param tail: the L{Tag} object to add to the first part (head)
@param head: the (eventually absent) L{MultiTag} to be extended
@returns: a new L{MultiTag} object
'''
if not head:
Tag.__init__(self, tail.string, tail.stem, tail.rating,
tail.proper, tail.terminal)
self.size = 1
self.subratings = [self.rating]
else:
self.string = ' '.join([head.string, tail.string])
self.stem = ' '.join([head.stem, tail.stem])
self.size = head.size + 1
self.proper = (head.proper and tail.proper)
self.terminal = tail.terminal
self.subratings = head.subratings + [tail.rating]
self.rating = self.combined_rating()
def combined_rating(self):
'''
Method that computes the multitag's rating from the ratings of unit
subtags
(the default implementation uses the geometric mean - with a special
treatment for proper nouns - but this method can be overridden)
@returns: the rating of the multitag
'''
# by default, the rating of a multitag is the geometric mean of its
# unit subtags' ratings
product = reduce(lambda x, y: x * y, self.subratings, 1.0)
root = self.size
# but proper nouns shouldn't be penalized by stopwords
if product == 0.0 and self.proper:
nonzero = [r for r in self.subratings if r > 0.0]
if len(nonzero) == 0:
return 0.0
product = reduce(lambda x, y: x * y, nonzero, 1.0)
root = len(nonzero)
return product ** (1.0 / root)
class Reader:
'''
Class for parsing a string of text to obtain tags
(it just turns the string to lowercase and splits it according to
whitespaces and punctuation, identifying proper nouns and terminal words;
different rules and formats other than plain text could be used)
'''
match_apostrophes = re.compile(r'`|’')
match_paragraphs = re.compile(r'[\.\?!\t\n\r\f\v]+')
match_phrases = re.compile(r'[,;:\(\)\[\]\{\}<>]+')
match_words = re.compile(r'[\w\-\'_/&]+')
def __call__(self, text):
'''
@param text: the string of text to be tagged
@returns: a list of tags respecting the order in the text
'''
text = self.preprocess(text)
# split by full stops, newlines, question marks...
paragraphs = self.match_paragraphs.split(text)
tags = []
for par in paragraphs:
# split by commas, colons, parentheses...
phrases = self.match_phrases.split(par)
if len(phrases) > 0:
# first phrase of a paragraph
words = self.match_words.findall(phrases[0])
if len(words) > 1:
tags.append(Tag(words[0].lower()))
for w in words[1:-1]:
tags.append(Tag(w.lower(), proper=w[0].isupper()))
tags.append(Tag(words[-1].lower(),
proper=words[-1][0].isupper(),
terminal=True))
elif len(words) == 1:
tags.append(Tag(words[0].lower(), terminal=True))
# following phrases
for phr in phrases[1:]:
words = self.match_words.findall(phr)
if len(words) > 1:
for w in words[:-1]:
tags.append(Tag(w.lower(), proper=w[0].isupper()))
if len(words) > 0:
tags.append(Tag(words[-1].lower(),
proper=words[-1][0].isupper(),
terminal=True))
return tags
def preprocess(self, text):
'''
@param text: a string containing the text document to perform any
required transformation before splitting
@returns: the processed text
'''
text = self.match_apostrophes.sub('\'', text)
return text
class Stemmer:
'''
Class for extracting the stem of a word
(by default it uses a simple open-source implementation of Porter's
algorithm; this can be improved a lot, so experimenting with different ones
is advisable; nltk.stem provides different algorithms for many languages)
'''
match_contractions = re.compile(r'(\w+)\'(m|re|d|ve|s|ll|t)?')
match_hyphens = re.compile(r'\b[\-_]\b')
def __init__(self, stemmer=None):
'''
@param stemmer: an object or module with a 'stem' method (defaults to
stemming.porter2)
@returns: a new L{Stemmer} object
'''
if not stemmer:
from stemming import porter2
stemmer = porter2
self.stemmer = stemmer
def __call__(self, tag):
'''
@param tag: the tag to be stemmed
@returns: the stemmed tag
'''
string = self.preprocess(tag.string)
tag.stem = self.stemmer.stem(string)
return tag
def preprocess(self, string):
'''
@param string: a string to be treated before passing it to the stemmer
@returns: the processed string
'''
# delete hyphens and underscores
string = self.match_hyphens.sub('', string)
# get rid of contractions and possessive forms
match = self.match_contractions.match(string)
if match: string = match.group(1)
return string
class Rater:
'''
Class for estimating the relevance of tags
(the default implementation uses TF (term frequency) multiplied by weight,
but any other reasonable measure is fine; a quite rudimental heuristic
tries to discard redundant tags)
'''
def __init__(self, weights, multitag_size=3):
'''
@param weights: a dictionary of weights normalized in the
interval [0,1]
@param multitag_size: maximum size of tags formed by multiple unit
tags
@returns: a new L{Rater} object
'''
self.weights = weights
self.multitag_size = multitag_size
def __call__(self, tags):
'''
@param tags: a list of (preferably stemmed) tags
@returns: a list of unique (multi)tags sorted by relevance
'''
self.rate_tags(tags)
multitags = self.create_multitags(tags)
# keep most frequent version of each tag
clusters = collections.defaultdict(collections.Counter)
proper = collections.defaultdict(int)
ratings = collections.defaultdict(float)
for t in multitags:
clusters[t][t.string] += 1
if t.proper:
proper[t] += 1
ratings[t] = max(ratings[t], t.rating)
term_count = collections.Counter(multitags)
for t, cnt in term_count.iteritems():
t.string = clusters[t].most_common(1)[0][0]
proper_freq = proper[t] / cnt
if proper_freq >= 0.5:
t.proper = True
t.rating = ratings[t]
# purge duplicates, one-character tags and stopwords
unique_tags = set(t for t in term_count
if len(t.string) > 1 and t.rating > 0.0)
# remove redundant tags
for t, cnt in term_count.iteritems():
words = t.stem.split()
for l in xrange(1, len(words)):
for i in xrange(len(words) - l + 1):
s = Tag(' '.join(words[i:i + l]))
relative_freq = cnt / term_count[s]
if ((relative_freq == 1.0 and t.proper) or
(relative_freq >= 0.5 and t.rating > 0.0)):
unique_tags.discard(s)
else:
unique_tags.discard(t)
return sorted(unique_tags)
def rate_tags(self, tags):
'''
@param tags: a list of tags to be assigned a rating
'''
term_count = collections.Counter(tags)
for t in tags:
# rating of a single tag is term frequency * weight
t.rating = term_count[t] / len(tags) * self.weights.get(t.stem, 1.0)
def create_multitags(self, tags):
'''
@param tags: a list of tags (respecting the order in the text)
@returns: a list of multitags
'''
multitags = []
for i in xrange(len(tags)):
t = MultiTag(tags[i])
multitags.append(t)
for j in xrange(1, self.multitag_size):
if t.terminal or i + j >= len(tags):
break
else:
t = MultiTag(tags[i + j], t)
multitags.append(t)
return multitags
class Tagger:
'''
Master class for tagging text documents
(this is a simple interface that should allow convenient experimentation
by using different classes as building blocks)
'''
def __init__(self, reader, stemmer, rater):
'''
@param reader: a L{Reader} object
@param stemmer: a L{Stemmer} object
@param rater: a L{Rater} object
@returns: a new L{Tagger} object
'''
self.reader = reader
self.stemmer = stemmer
self.rater = rater
def __call__(self, text, tags_number=5):
'''
@param text: the string of text to be tagged
@param tags_number: number of best tags to be returned
Returns: a list of (hopefully) relevant tags
'''
tags = self.reader(text)
tags = map(self.stemmer, tags)
tags = self.rater(tags)
return tags[:tags_number]
if __name__ == '__main__':
import glob
import pickle
import sys
if len(sys.argv) < 2:
print 'No arguments given, running tests: '
documents = glob.glob('tests/*')
else:
documents = sys.argv[1:]
print 'Loading dictionary... '
weights = pickle.load(open('data/dict.pkl', 'rb'))
tagger = Tagger(Reader(), Stemmer(), Rater(weights))
for doc in documents:
with open(doc, 'r') as file:
print 'Tags for ', doc, ':'
print tagger(file.read())
| [
[
8,
0,
0.1149,
0.1255,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1809,
0.0021,
0,
0.66,
0.1,
777,
0,
1,
0,
0,
777,
0,
0
],
[
1,
0,
0.1851,
0.0021,
0,
0.66,
... | [
"'''\n======\ntagger\n======\n\nModule for extracting tags from text documents.\n \nCopyright (C) 2011 by Alessandro Presta",
"from __future__ import division",
"import collections",
"import re",
"class Tag:\n '''\n General class for tags (small units of text)\n '''\n \n def... |
# -*- coding: utf8 -*-
from fuzzywuzzy import fuzz
from fuzzywuzzy import process
from fuzzywuzzy import utils
import itertools
import unittest
class UtilsTest(unittest.TestCase):
def setUp(self):
self.s1 = "new york mets"
self.s1a = "new york mets"
self.s2 = "new YORK mets"
self.s3 = "the wonderful new york mets"
self.s4 = "new york mets vs atlanta braves"
self.s5 = "atlanta braves vs new york mets"
self.s6 = "new york mets - atlanta braves"
self.mixed_strings = [
"Lorem Ipsum is simply dummy text of the printing and typesetting industry.",
"C'est la vie",
"Ça va?",
"Cães danados",
u"\xacCamarões assados",
u"a\xac\u1234\u20ac\U00008000",
u"\u00C1"
]
def tearDown(self):
pass
def test_asciidammit(self):
for s in self.mixed_strings:
utils.asciidammit(s)
def test_asciionly(self):
for s in self.mixed_strings:
# ascii only only runs on strings
s = utils.asciidammit(s)
utils.asciionly(s)
def test_fullProcess(self):
for s in self.mixed_strings:
utils.full_process(s)
class RatioTest(unittest.TestCase):
def setUp(self):
self.s1 = "new york mets"
self.s1a = "new york mets"
self.s2 = "new YORK mets"
self.s3 = "the wonderful new york mets"
self.s4 = "new york mets vs atlanta braves"
self.s5 = "atlanta braves vs new york mets"
self.s6 = "new york mets - atlanta braves"
self.cirque_strings = [
"cirque du soleil - zarkana - las vegas",
"cirque du soleil ",
"cirque du soleil las vegas",
"zarkana las vegas",
"las vegas cirque du soleil at the bellagio",
"zarakana - cirque du soleil - bellagio"
]
self.baseball_strings = [
"new york mets vs chicago cubs",
"chicago cubs vs chicago white sox",
"philladelphia phillies vs atlanta braves",
"braves vs mets",
]
def tearDown(self):
pass
def testEqual(self):
self.assertEqual(fuzz.ratio(self.s1, self.s1a),100)
def testCaseInsensitive(self):
self.assertNotEqual(fuzz.ratio(self.s1, self.s2),100)
self.assertEqual(fuzz.ratio(utils.full_process(self.s1), utils.full_process(self.s2)),100)
def testPartialRatio(self):
self.assertEqual(fuzz.partial_ratio(self.s1, self.s3),100)
def testTokenSortRatio(self):
self.assertEqual(fuzz.token_sort_ratio(self.s1, self.s1a),100)
def testPartialTokenSortRatio(self):
self.assertEqual(fuzz.partial_token_sort_ratio(self.s1, self.s1a),100)
self.assertEqual(fuzz.partial_token_sort_ratio(self.s4, self.s5),100)
def testTokenSetRatio(self):
self.assertEqual(fuzz.token_set_ratio(self.s4, self.s5),100)
def testPartialTokenSetRatio(self):
self.assertEqual(fuzz.token_set_ratio(self.s4, self.s5),100)
def testQuickRatioEqual(self):
self.assertEqual(fuzz.QRatio(self.s1, self.s1a), 100)
def testQuickRatioCaseInsensitive(self):
self.assertEqual(fuzz.QRatio(self.s1, self.s2), 100)
def testQuickRatioNotEqual(self):
self.assertNotEqual(fuzz.QRatio(self.s1, self.s3), 100)
def testWRatioEqual(self):
self.assertEqual(fuzz.WRatio(self.s1, self.s1a), 100)
def testWRatioCaseInsensitive(self):
self.assertEqual(fuzz.WRatio(self.s1, self.s2), 100)
def testWRatioPartialMatch(self):
# a partial match is scaled by .9
self.assertEqual(fuzz.WRatio(self.s1, self.s3), 90)
def testWRatioMisorderedMatch(self):
# misordered full matches are scaled by .95
self.assertEqual(fuzz.WRatio(self.s4, self.s5), 95)
def testWRatioUnicode(self):
self.assertEqual(fuzz.WRatio(unicode(self.s1), unicode(self.s1a)), 100)
def testQRatioUnicode(self):
self.assertEqual(fuzz.WRatio(unicode(self.s1), unicode(self.s1a)), 100)
def testIssueSeven(self):
s1 = "HSINCHUANG"
s2 = "SINJHUAN"
s3 = "LSINJHUANG DISTRIC"
s4 = "SINJHUANG DISTRICT"
self.assertTrue(fuzz.partial_ratio(s1, s2) > 75)
self.assertTrue(fuzz.partial_ratio(s1, s3) > 75)
self.assertTrue(fuzz.partial_ratio(s1, s4) > 75)
def testWRatioUnicodeString(self):
s1 = u"\u00C1"
s2 = "ABCD"
score = fuzz.WRatio(s1, s2)
self.assertEqual(0, score)
def testQRatioUnicodeString(self):
s1 = u"\u00C1"
s2 = "ABCD"
score = fuzz.QRatio(s1, s2)
self.assertEqual(0, score)
# test processing methods
def testGetBestChoice1(self):
query = "new york mets at atlanta braves"
best = process.extractOne(query, self.baseball_strings)
self.assertEqual(best[0], "braves vs mets")
def testGetBestChoice2(self):
query = "philadelphia phillies at atlanta braves"
best = process.extractOne(query, self.baseball_strings)
self.assertEqual(best[0], self.baseball_strings[2])
def testGetBestChoice3(self):
query = "atlanta braves at philadelphia phillies"
best = process.extractOne(query, self.baseball_strings)
self.assertEqual(best[0], self.baseball_strings[2])
def testGetBestChoice4(self):
query = "chicago cubs vs new york mets"
best = process.extractOne(query, self.baseball_strings)
self.assertEqual(best[0], self.baseball_strings[0])
class ProcessTest(unittest.TestCase):
def setUp(self):
self.s1 = "new york mets"
self.s1a = "new york mets"
self.s2 = "new YORK mets"
self.s3 = "the wonderful new york mets"
self.s4 = "new york mets vs atlanta braves"
self.s5 = "atlanta braves vs new york mets"
self.s6 = "new york mets - atlanta braves"
self.cirque_strings = [
"cirque du soleil - zarkana - las vegas",
"cirque du soleil ",
"cirque du soleil las vegas",
"zarkana las vegas",
"las vegas cirque du soleil at the bellagio",
"zarakana - cirque du soleil - bellagio"
]
self.baseball_strings = [
"new york mets vs chicago cubs",
"chicago cubs vs chicago white sox",
"philladelphia phillies vs atlanta braves",
"braves vs mets",
]
def testWithProcessor(self):
events = [
["chicago cubs vs new york mets", "CitiField", "2011-05-11", "8pm"],
["new york yankees vs boston red sox", "Fenway Park", "2011-05-11", "8pm"],
["atlanta braves vs pittsburgh pirates", "PNC Park", "2011-05-11", "8pm"],
]
query = "new york mets vs chicago cubs"
processor = lambda event: event[0]
best = process.extractOne(query, events, processor=processor)
self.assertEqual(best[0], events[0])
def testWithScorer(self):
choices = [
"new york mets vs chicago cubs",
"chicago cubs at new york mets",
"atlanta braves vs pittsbugh pirates",
"new york yankees vs boston red sox"
]
# in this hypothetical example we care about ordering, so we use quick ratio
query = "new york mets at chicago cubs"
scorer = fuzz.QRatio
# first, as an example, the normal way would select the "more 'complete' match of choices[1]"
best = process.extractOne(query, choices)
self.assertEqual(best[0], choices[1])
# now, use the custom scorer
best = process.extractOne(query, choices, scorer=scorer)
self.assertEqual(best[0], choices[0])
def testWithCutoff(self):
choices = [
"new york mets vs chicago cubs",
"chicago cubs at new york mets",
"atlanta braves vs pittsbugh pirates",
"new york yankees vs boston red sox"
]
query = "los angeles dodgers vs san francisco giants"
# in this situation, this is an event that does not exist in the list
# we don't want to randomly match to something, so we use a reasonable cutoff
best = process.extractOne(query, choices, score_cutoff=50)
self.assertTrue(best is None)
#self.assertIsNone(best) # unittest.TestCase did not have assertIsNone until Python 2.7
# however if we had no cutoff, something would get returned
#best = process.extractOne(query, choices)
#self.assertIsNotNone(best)
def testEmptyStrings(self):
choices = [
"",
"new york mets vs chicago cubs",
"new york yankees vs boston red sox",
"",
""
]
query = "new york mets at chicago cubs"
best = process.extractOne(query, choices)
self.assertEqual(best[0], choices[1])
def testNullStrings(self):
choices = [
None,
"new york mets vs chicago cubs",
"new york yankees vs boston red sox",
None,
None
]
query = "new york mets at chicago cubs"
best = process.extractOne(query, choices)
self.assertEqual(best[0], choices[1])
if __name__ == '__main__':
unittest.main() # run all tests | [
[
1,
0,
0.0105,
0.0035,
0,
0.66,
0,
720,
0,
1,
0,
0,
720,
0,
0
],
[
1,
0,
0.014,
0.0035,
0,
0.66,
0.125,
720,
0,
1,
0,
0,
720,
0,
0
],
[
1,
0,
0.0175,
0.0035,
0,
0.... | [
"from fuzzywuzzy import fuzz",
"from fuzzywuzzy import process",
"from fuzzywuzzy import utils",
"import itertools",
"import unittest",
"class UtilsTest(unittest.TestCase):\n def setUp(self):\n self.s1 = \"new york mets\"\n self.s1a = \"new york mets\"\n self.s2 = \"new YORK mets\"... |
import string
bad_chars=''
for i in range(128,256):
bad_chars+=chr(i)
table_from=string.punctuation+string.ascii_uppercase
table_to=' '*len(string.punctuation)+string.ascii_lowercase
trans_table=string.maketrans(table_from, table_to)
def asciionly(s):
return s.translate(None, bad_chars)
# remove non-ASCII characters from strings
def asciidammit(s):
if type(s) is str:
return asciionly(s)
elif type(s) is unicode:
return asciionly(s.encode('ascii', 'ignore'))
else:
return asciidammit(unicode(s))
def validate_string(s):
try:
if len(s)>0:
return True
else:
return False
except:
return False
def full_process(s):
s = asciidammit(s)
return s.translate(trans_table, bad_chars).strip()
def intr(n):
'''Returns a correctly rounded integer'''
return int(round(n))
| [
[
1,
0,
0.025,
0.025,
0,
0.66,
0,
890,
0,
1,
0,
0,
890,
0,
0
],
[
14,
0,
0.075,
0.025,
0,
0.66,
0.1,
74,
1,
0,
0,
0,
0,
3,
0
],
[
6,
0,
0.1125,
0.05,
0,
0.66,
0... | [
"import string",
"bad_chars=''",
"for i in range(128,256):\n bad_chars+=chr(i)",
"table_from=string.punctuation+string.ascii_uppercase",
"table_to=' '*len(string.punctuation)+string.ascii_lowercase",
"trans_table=string.maketrans(table_from, table_to)",
"def asciionly(s):\n return s.translate(None... |
#!/usr/bin/env python
# encoding: utf-8
"""
process.py
Copyright (c) 2011 Adam Cohen
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from fuzz import *
import sys, os
import utils
#######################################
# Find Best Matchs In List Of Choices #
#######################################
def extract(query, choices, processor=None, scorer=None, limit=5):
# choices = a list of objects we are attempting to extract values from
# query = an object representing the thing we want to find
# scorer f(OBJ, QUERY) --> INT. We will return the objects with the highest score
# by default, we use score.WRatio() and both OBJ and QUERY should be strings
# processor f(OBJ_A) --> OBJ_B, where the output is an input to scorer
# for example, "processor = lambda x: x[0]" would return the first element in a collection x (of, say, strings)
# this would then be used in the scoring collection
if choices is None or len(choices) == 0:
return []
# default, turn whatever the choice is into a string
if processor is None:
processor = lambda x: utils.asciidammit(x)
# default: wratio
if scorer is None:
scorer = WRatio
sl = list()
for choice in choices:
processed = processor(choice)
score = scorer(query, processed)
tuple = (choice, score)
sl.append(tuple)
sl.sort(key=lambda i: -1*i[1])
return sl[:limit]
##########################
# Find Single Best Match #
##########################
def extractOne(query, choices, processor=None, scorer=None, score_cutoff=0):
# convenience method which returns the single best choice
# optional parameter: score_cutoff.
# If the best choice has a score of less than score_cutoff
# we will return none (intuition: not a good enough match)
best_list = extract(query, choices, processor, scorer, limit=1)
if len(best_list) > 0:
best = best_list[0]
if best[1] > score_cutoff:
return best
else:
return None
else:
return None
| [
[
8,
0,
0.1667,
0.2759,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.3103,
0.0115,
0,
0.66,
0.2,
390,
0,
1,
0,
0,
390,
0,
0
],
[
1,
0,
0.3333,
0.0115,
0,
0.66,
... | [
"\"\"\"\nprocess.py\n\nCopyright (c) 2011 Adam Cohen\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including",
"from fuzz import *",
"import sys, os",
"impor... |
#!/usr/bin/env python
# encoding: utf-8
"""
score.py
Copyright (c) 2011 Adam Cohen
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import sys
import os
import re
from utils import *
try:
from StringMatcher import StringMatcher as SequenceMatcher
except:
from difflib import SequenceMatcher
REG_TOKEN = re.compile("[\w\d]+")
###########################
# Basic Scoring Functions #
###########################
def ratio(s1, s2):
if s1 is None: raise TypeError("s1 is None")
if s2 is None: raise TypeError("s2 is None")
m = SequenceMatcher(None, s1, s2)
return intr(100 * m.ratio())
# todo: skip duplicate indexes for a little more speed
def partial_ratio(s1, s2):
if s1 is None: raise TypeError("s1 is None")
if s2 is None: raise TypeError("s2 is None")
if len(s1) <= len(s2):
shorter = s1; longer = s2;
else:
shorter = s2; longer = s1
m = SequenceMatcher(None, shorter, longer)
blocks = m.get_matching_blocks()
# each block represents a sequence of matching characters in a string
# of the form (idx_1, idx_2, len)
# the best partial match will block align with at least one of those blocks
# e.g. shorter = "abcd", longer = XXXbcdeEEE
# block = (1,3,3)
# best score === ratio("abcd", "Xbcd")
scores = []
for block in blocks:
long_start = block[1] - block[0] if (block[1] - block[0]) > 0 else 0
long_end = long_start + len(shorter)
long_substr = longer[long_start:long_end]
m2 = SequenceMatcher(None, shorter, long_substr)
r = m2.ratio()
if r > .995: return 100
else: scores.append(r)
return int(100 * max(scores))
##############################
# Advanced Scoring Functions #
##############################
# Sorted Token
# find all alphanumeric tokens in the string
# sort those tokens and take ratio of resulting joined strings
# controls for unordered string elements
def _token_sort(s1, s2, partial=True):
if s1 is None: raise TypeError("s1 is None")
if s2 is None: raise TypeError("s2 is None")
# pull tokens
tokens1 = REG_TOKEN.findall(s1)
tokens2 = REG_TOKEN.findall(s2)
# sort tokens and join
sorted1 = u" ".join(sorted(tokens1))
sorted2 = u" ".join(sorted(tokens2))
sorted1 = sorted1.strip()
sorted2 = sorted2.strip()
if partial:
return partial_ratio(sorted1, sorted2)
else:
return ratio(sorted1, sorted2)
def token_sort_ratio(s1, s2):
return _token_sort(s1, s2, False)
def partial_token_sort_ratio(s1, s2):
return _token_sort(s1, s2, True)
# Token Set
# find all alphanumeric tokens in each string...treat them as a set
# construct two strings of the form
# <sorted_intersection><sorted_remainder>
# take ratios of those two strings
# controls for unordered partial matches
def _token_set(s1, s2, partial=True):
if s1 is None: raise TypeError("s1 is None")
if s2 is None: raise TypeError("s2 is None")
# pull tokens
tokens1 = set(REG_TOKEN.findall(s1))
tokens2 = set(REG_TOKEN.findall(s2))
intersection = tokens1.intersection(tokens2)
diff1to2 = tokens1.difference(tokens2)
diff2to1 = tokens2.difference(tokens1)
sorted_sect = u" ".join(sorted(intersection))
sorted_1to2 = u" ".join(sorted(diff1to2))
sorted_2to1 = u" ".join(sorted(diff2to1))
combined_1to2 = sorted_sect + " " + sorted_1to2
combined_2to1 = sorted_sect + " " + sorted_2to1
# strip
sorted_sect = sorted_sect.strip()
combined_1to2 = combined_1to2.strip()
combined_2to1 = combined_2to1.strip()
pairwise = [
ratio(sorted_sect, combined_1to2),
ratio(sorted_sect, combined_2to1),
ratio(combined_1to2, combined_2to1)
]
return max(pairwise)
# if partial:
# # partial_token_set_ratio
#
# else:
# # token_set_ratio
# tsr = ratio(combined_1to2, combined_2to1)
# return tsr
def token_set_ratio(s1, s2):
return _token_set(s1, s2, False)
def partial_token_set_ratio(s1, s2):
return _token_set(s1, s2, True)
# TODO: numerics
###################
# Combination API #
###################
# q is for quick
def QRatio(s1, s2):
if not validate_string(s1): return 0
if not validate_string(s2): return 0
p1 = full_process(s1)
p2 = full_process(s2)
return ratio(p1, p2)
# w is for weighted
def WRatio(s1, s2):
p1 = full_process(s1)
p2 = full_process(s2)
if not validate_string(p1): return 0
if not validate_string(p2): return 0
# should we look at partials?
try_partial = True
unbase_scale = .95
partial_scale = .90
base = ratio(p1, p2)
len_ratio = float(max(len(p1),len(p2)))/min(len(p1),len(p2))
# if strings are similar length, don't use partials
if len_ratio < 1.5: try_partial = False
# if one string is much much shorter than the other
if len_ratio > 8: partial_scale = .6
if try_partial:
partial = partial_ratio(p1, p2) * partial_scale
ptsor = partial_token_sort_ratio(p1, p2) * unbase_scale * partial_scale
ptser = partial_token_set_ratio(p1, p2) * unbase_scale * partial_scale
return int(max(base, partial, ptsor, ptser))
else:
tsor = token_sort_ratio(p1, p2) * unbase_scale
tser = token_set_ratio(p1, p2) * unbase_scale
return int(max(base, tsor, tser))
| [
[
8,
0,
0.0659,
0.1091,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1273,
0.0045,
0,
0.66,
0.0625,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.1318,
0.0045,
0,
0.66... | [
"\"\"\"\nscore.py\n\nCopyright (c) 2011 Adam Cohen\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including",
"import sys",
"import os",
"import re",
"from ... |
#!/usr/bin/env python
# encoding: utf-8
"""
StringMatcher.py
ported from python-Levenshtein
[https://github.com/miohtama/python-Levenshtein]
"""
from Levenshtein import *
from warnings import warn
class StringMatcher:
"""A SequenceMatcher-like class built on the top of Levenshtein"""
def _reset_cache(self):
self._ratio = self._distance = None
self._opcodes = self._editops = self._matching_blocks = None
def __init__(self, isjunk=None, seq1='', seq2=''):
if isjunk:
warn("isjunk not NOT implemented, it will be ignored")
self._str1, self._str2 = seq1, seq2
self._reset_cache()
def set_seqs(self, seq1, seq2):
self._str1, self._str2 = seq1, seq2
self._reset_cache()
def set_seq1(self, seq1):
self._str1 = seq1
self._reset_cache()
def set_seq2(self, seq2):
self._str2 = seq2
self._reset_cache()
def get_opcodes(self):
if not self._opcodes:
if self._editops:
self._opcodes = opcodes(self._editops, self._str1, self._str2)
else:
self._opcodes = opcodes(self._str1, self._str2)
return self._opcodes
def get_editops(self):
if not self._editops:
if self._opcodes:
self._editops = editops(self._opcodes, self._str1, self._str2)
else:
self._editops = editops(self._str1, self._str2)
return self._editops
def get_matching_blocks(self):
if not self._matching_blocks:
self._matching_blocks = matching_blocks(self.get_opcodes(),
self._str1, self._str2)
return self._matching_blocks
def ratio(self):
if not self._ratio:
self._ratio = ratio(self._str1, self._str2)
return self._ratio
def quick_ratio(self):
# This is usually quick enough :o)
if not self._ratio:
self._ratio = ratio(self._str1, self._str2)
return self._ratio
def real_quick_ratio(self):
len1, len2 = len(self._str1), len(self._str2)
return 2.0 * min(len1, len2) / (len1 + len2)
def distance(self):
if not self._distance:
self._distance = distance(self._str1, self._str2)
return self._distance | [
[
8,
0,
0.0705,
0.0769,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1282,
0.0128,
0,
0.66,
0.3333,
920,
0,
1,
0,
0,
920,
0,
0
],
[
1,
0,
0.141,
0.0128,
0,
0.66,... | [
"\"\"\"\nStringMatcher.py\n\nported from python-Levenshtein\n[https://github.com/miohtama/python-Levenshtein]\n\"\"\"",
"from Levenshtein import *",
"from warnings import warn",
"class StringMatcher:\n \"\"\"A SequenceMatcher-like class built on the top of Levenshtein\"\"\"\n\n def _reset_cache(self):\n... |
#!/usr/bin/env python
# encoding: utf-8
"""
process.py
Copyright (c) 2011 Adam Cohen
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from fuzz import *
import sys, os
import utils
#######################################
# Find Best Matchs In List Of Choices #
#######################################
def extract(query, choices, processor=None, scorer=None, limit=5):
# choices = a list of objects we are attempting to extract values from
# query = an object representing the thing we want to find
# scorer f(OBJ, QUERY) --> INT. We will return the objects with the highest score
# by default, we use score.WRatio() and both OBJ and QUERY should be strings
# processor f(OBJ_A) --> OBJ_B, where the output is an input to scorer
# for example, "processor = lambda x: x[0]" would return the first element in a collection x (of, say, strings)
# this would then be used in the scoring collection
if choices is None or len(choices) == 0:
return []
# default, turn whatever the choice is into a string
if processor is None:
processor = lambda x: utils.asciidammit(x)
# default: wratio
if scorer is None:
scorer = WRatio
sl = list()
for choice in choices:
processed = processor(choice)
score = scorer(query, processed)
tuple = (choice, score)
sl.append(tuple)
sl.sort(key=lambda i: -1*i[1])
return sl[:limit]
##########################
# Find Single Best Match #
##########################
def extractOne(query, choices, processor=None, scorer=None, score_cutoff=0):
# convenience method which returns the single best choice
# optional parameter: score_cutoff.
# If the best choice has a score of less than score_cutoff
# we will return none (intuition: not a good enough match)
best_list = extract(query, choices, processor, scorer, limit=1)
if len(best_list) > 0:
best = best_list[0]
if best[1] > score_cutoff:
return best
else:
return None
else:
return None
| [
[
8,
0,
0.1667,
0.2759,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.3103,
0.0115,
0,
0.66,
0.2,
390,
0,
1,
0,
0,
390,
0,
0
],
[
1,
0,
0.3333,
0.0115,
0,
0.66,
... | [
"\"\"\"\nprocess.py\n\nCopyright (c) 2011 Adam Cohen\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including",
"from fuzz import *",
"import sys, os",
"impor... |
#!/usr/bin/env python
# encoding: utf-8
"""
StringMatcher.py
ported from python-Levenshtein
[https://github.com/miohtama/python-Levenshtein]
"""
from Levenshtein import *
from warnings import warn
class StringMatcher:
"""A SequenceMatcher-like class built on the top of Levenshtein"""
def _reset_cache(self):
self._ratio = self._distance = None
self._opcodes = self._editops = self._matching_blocks = None
def __init__(self, isjunk=None, seq1='', seq2=''):
if isjunk:
warn("isjunk not NOT implemented, it will be ignored")
self._str1, self._str2 = seq1, seq2
self._reset_cache()
def set_seqs(self, seq1, seq2):
self._str1, self._str2 = seq1, seq2
self._reset_cache()
def set_seq1(self, seq1):
self._str1 = seq1
self._reset_cache()
def set_seq2(self, seq2):
self._str2 = seq2
self._reset_cache()
def get_opcodes(self):
if not self._opcodes:
if self._editops:
self._opcodes = opcodes(self._editops, self._str1, self._str2)
else:
self._opcodes = opcodes(self._str1, self._str2)
return self._opcodes
def get_editops(self):
if not self._editops:
if self._opcodes:
self._editops = editops(self._opcodes, self._str1, self._str2)
else:
self._editops = editops(self._str1, self._str2)
return self._editops
def get_matching_blocks(self):
if not self._matching_blocks:
self._matching_blocks = matching_blocks(self.get_opcodes(),
self._str1, self._str2)
return self._matching_blocks
def ratio(self):
if not self._ratio:
self._ratio = ratio(self._str1, self._str2)
return self._ratio
def quick_ratio(self):
# This is usually quick enough :o)
if not self._ratio:
self._ratio = ratio(self._str1, self._str2)
return self._ratio
def real_quick_ratio(self):
len1, len2 = len(self._str1), len(self._str2)
return 2.0 * min(len1, len2) / (len1 + len2)
def distance(self):
if not self._distance:
self._distance = distance(self._str1, self._str2)
return self._distance | [
[
8,
0,
0.0705,
0.0769,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1282,
0.0128,
0,
0.66,
0.3333,
920,
0,
1,
0,
0,
920,
0,
0
],
[
1,
0,
0.141,
0.0128,
0,
0.66,... | [
"\"\"\"\nStringMatcher.py\n\nported from python-Levenshtein\n[https://github.com/miohtama/python-Levenshtein]\n\"\"\"",
"from Levenshtein import *",
"from warnings import warn",
"class StringMatcher:\n \"\"\"A SequenceMatcher-like class built on the top of Levenshtein\"\"\"\n\n def _reset_cache(self):\n... |
#!/usr/bin/env python
# encoding: utf-8
"""
score.py
Copyright (c) 2011 Adam Cohen
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import sys
import os
import re
from utils import *
try:
from StringMatcher import StringMatcher as SequenceMatcher
except:
from difflib import SequenceMatcher
REG_TOKEN = re.compile("[\w\d]+")
###########################
# Basic Scoring Functions #
###########################
def ratio(s1, s2):
if s1 is None: raise TypeError("s1 is None")
if s2 is None: raise TypeError("s2 is None")
m = SequenceMatcher(None, s1, s2)
return intr(100 * m.ratio())
# todo: skip duplicate indexes for a little more speed
def partial_ratio(s1, s2):
if s1 is None: raise TypeError("s1 is None")
if s2 is None: raise TypeError("s2 is None")
if len(s1) <= len(s2):
shorter = s1; longer = s2;
else:
shorter = s2; longer = s1
m = SequenceMatcher(None, shorter, longer)
blocks = m.get_matching_blocks()
# each block represents a sequence of matching characters in a string
# of the form (idx_1, idx_2, len)
# the best partial match will block align with at least one of those blocks
# e.g. shorter = "abcd", longer = XXXbcdeEEE
# block = (1,3,3)
# best score === ratio("abcd", "Xbcd")
scores = []
for block in blocks:
long_start = block[1] - block[0] if (block[1] - block[0]) > 0 else 0
long_end = long_start + len(shorter)
long_substr = longer[long_start:long_end]
m2 = SequenceMatcher(None, shorter, long_substr)
r = m2.ratio()
if r > .995: return 100
else: scores.append(r)
return int(100 * max(scores))
##############################
# Advanced Scoring Functions #
##############################
# Sorted Token
# find all alphanumeric tokens in the string
# sort those tokens and take ratio of resulting joined strings
# controls for unordered string elements
def _token_sort(s1, s2, partial=True):
if s1 is None: raise TypeError("s1 is None")
if s2 is None: raise TypeError("s2 is None")
# pull tokens
tokens1 = REG_TOKEN.findall(s1)
tokens2 = REG_TOKEN.findall(s2)
# sort tokens and join
sorted1 = u" ".join(sorted(tokens1))
sorted2 = u" ".join(sorted(tokens2))
sorted1 = sorted1.strip()
sorted2 = sorted2.strip()
if partial:
return partial_ratio(sorted1, sorted2)
else:
return ratio(sorted1, sorted2)
def token_sort_ratio(s1, s2):
return _token_sort(s1, s2, False)
def partial_token_sort_ratio(s1, s2):
return _token_sort(s1, s2, True)
# Token Set
# find all alphanumeric tokens in each string...treat them as a set
# construct two strings of the form
# <sorted_intersection><sorted_remainder>
# take ratios of those two strings
# controls for unordered partial matches
def _token_set(s1, s2, partial=True):
if s1 is None: raise TypeError("s1 is None")
if s2 is None: raise TypeError("s2 is None")
# pull tokens
tokens1 = set(REG_TOKEN.findall(s1))
tokens2 = set(REG_TOKEN.findall(s2))
intersection = tokens1.intersection(tokens2)
diff1to2 = tokens1.difference(tokens2)
diff2to1 = tokens2.difference(tokens1)
sorted_sect = u" ".join(sorted(intersection))
sorted_1to2 = u" ".join(sorted(diff1to2))
sorted_2to1 = u" ".join(sorted(diff2to1))
combined_1to2 = sorted_sect + " " + sorted_1to2
combined_2to1 = sorted_sect + " " + sorted_2to1
# strip
sorted_sect = sorted_sect.strip()
combined_1to2 = combined_1to2.strip()
combined_2to1 = combined_2to1.strip()
pairwise = [
ratio(sorted_sect, combined_1to2),
ratio(sorted_sect, combined_2to1),
ratio(combined_1to2, combined_2to1)
]
return max(pairwise)
# if partial:
# # partial_token_set_ratio
#
# else:
# # token_set_ratio
# tsr = ratio(combined_1to2, combined_2to1)
# return tsr
def token_set_ratio(s1, s2):
return _token_set(s1, s2, False)
def partial_token_set_ratio(s1, s2):
return _token_set(s1, s2, True)
# TODO: numerics
###################
# Combination API #
###################
# q is for quick
def QRatio(s1, s2):
if not validate_string(s1): return 0
if not validate_string(s2): return 0
p1 = full_process(s1)
p2 = full_process(s2)
return ratio(p1, p2)
# w is for weighted
def WRatio(s1, s2):
p1 = full_process(s1)
p2 = full_process(s2)
if not validate_string(p1): return 0
if not validate_string(p2): return 0
# should we look at partials?
try_partial = True
unbase_scale = .95
partial_scale = .90
base = ratio(p1, p2)
len_ratio = float(max(len(p1),len(p2)))/min(len(p1),len(p2))
# if strings are similar length, don't use partials
if len_ratio < 1.5: try_partial = False
# if one string is much much shorter than the other
if len_ratio > 8: partial_scale = .6
if try_partial:
partial = partial_ratio(p1, p2) * partial_scale
ptsor = partial_token_sort_ratio(p1, p2) * unbase_scale * partial_scale
ptser = partial_token_set_ratio(p1, p2) * unbase_scale * partial_scale
return int(max(base, partial, ptsor, ptser))
else:
tsor = token_sort_ratio(p1, p2) * unbase_scale
tser = token_set_ratio(p1, p2) * unbase_scale
return int(max(base, tsor, tser))
| [
[
8,
0,
0.0659,
0.1091,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1273,
0.0045,
0,
0.66,
0.0625,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.1318,
0.0045,
0,
0.66... | [
"\"\"\"\nscore.py\n\nCopyright (c) 2011 Adam Cohen\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including",
"import sys",
"import os",
"import re",
"from ... |
from distutils.core import setup
setup(name='fuzzywuzzy',
version='0.1',
description='Fuzzy string matching in python',
author='Adam Cohen',
author_email='adam@seatgeek.com',
url='https://github.com/seatgeek/fuzzywuzzy/',
packages=['fuzzywuzzy']) | [
[
1,
0,
0.1111,
0.1111,
0,
0.66,
0,
152,
0,
1,
0,
0,
152,
0,
0
],
[
8,
0,
0.6667,
0.7778,
0,
0.66,
1,
234,
3,
7,
0,
0,
0,
0,
1
]
] | [
"from distutils.core import setup",
"setup(name='fuzzywuzzy',\n version='0.1',\n description='Fuzzy string matching in python',\n author='Adam Cohen',\n author_email='adam@seatgeek.com',\n url='https://github.com/seatgeek/fuzzywuzzy/',\n packages=['fuzzywuzzy'])"
] |
# -*- coding: utf8 -*-
from timeit import timeit
from fuzzywuzzy import utils
iterations=100000
cirque_strings = [
"cirque du soleil - zarkana - las vegas",
"cirque du soleil ",
"cirque du soleil las vegas",
"zarkana las vegas",
"las vegas cirque du soleil at the bellagio",
"zarakana - cirque du soleil - bellagio"
]
choices = [
"",
"new york yankees vs boston red sox",
"",
"zarakana - cirque du soleil - bellagio",
None,
"cirque du soleil las vegas",
None
]
mixed_strings = [
"Lorem Ipsum is simply dummy text of the printing and typesetting industry.",
"C\\'est la vie",
"Ça va?",
"Cães danados",
u"\xacCamarões assados",
u"a\xac\u1234\u20ac\U00008000"
]
for s in choices:
print 'Test for string: "%s"' % s
# print 'Old: %f' % round(timeit('utils.validate_stringold(\'%s\')' % s, "from fuzzywuzzy import utils",number=iterations),4)
print 'New: %f' % round(timeit('utils.validate_string(\'%s\')' % s, "from fuzzywuzzy import utils",number=iterations),4)
print
for s in mixed_strings:
print 'Test for string: "%s"' % s
#print 'Old: %f' % round(timeit('utils.asciidammitold(\'%s\')' % s, "from fuzzywuzzy import utils",number=iterations),4)
print 'New: %f' % round(timeit('utils.asciidammit(\'%s\')' % s, "from fuzzywuzzy import utils",number=iterations),4)
print
for s in mixed_strings+cirque_strings+choices:
print 'Test for string: "%s"' % s
#print 'Old: %f' % round(timeit('utils.full_processold(\'%s\')' % s, "from fuzzywuzzy import utils",number=iterations),4)
print 'New: %f' % round(timeit('utils.full_process(\'%s\')' % s, "from fuzzywuzzy import utils",number=iterations),4)
### benchmarking the core matching methods...
for s in cirque_strings:
print 'Test fuzz.ratio for string: "%s"' % s
print '-------------------------------'
print 'New: %f' % round(timeit('fuzz.ratio(\'cirque du soleil\', \'%s\')' % s, "from fuzzywuzzy import fuzz",number=iterations/100),4)
for s in cirque_strings:
print 'Test fuzz.partial_ratio for string: "%s"' % s
print '-------------------------------'
print 'New: %f' % round(timeit('fuzz.partial_ratio(\'cirque du soleil\', \'%s\')' % s, "from fuzzywuzzy import fuzz",number=iterations/100),4)
for s in cirque_strings:
print 'Test fuzz.WRatio for string: "%s"' % s
print '-------------------------------'
print 'New: %f' % round(timeit('fuzz.WRatio(\'cirque du soleil\', \'%s\')' % s, "from fuzzywuzzy import fuzz",number=iterations/100),4)
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
200,
0,
1,
0,
0,
200,
0,
0
],
[
1,
0,
0.6667,
0.3333,
0,
0.66,
1,
720,
0,
1,
0,
0,
720,
0,
0
]
] | [
"from timeit import timeit",
"from fuzzywuzzy import utils"
] |
#!/opt/ActivePython-2.7/bin/python
#####################################################################################################
# Nicholas Harner
# CSE411
# Homework 7
# 11/19/2012
# This program is an exact mimic of Coelacanth: a simple password generator. It is a very simple
# application for creating passwords that can be used securely. Coelacanth was originally written
# in C#. My version is written in python, using Tkinter for the GUI. This program allows the user
# to designate if he/she would like a password containing any combination of uppercase letters,
# lowercase letters, or digits. The user can also request that the password be copied to the clipboard
# in windows following password generation. In addition, the user can specify the length of the
# password to be generated. Upon clicking generate, the password is created using the user
# specifications. Upon clicking clear, the text box containing the generated password is cleared.
# This clear does not clear the clipboard however.
#To Run on Suns, type:
# python NickHarnerHW7.py
# Coelacanth can be found at:
# http://code.google.com/p/coelacanth/
#####################################################################################################
import os,sys
import math
import random #need this to create random password
from Tkinter import *
def fatal():
sys.exit()
class Application(Frame):
""" GUI application that creates a new random password based on user specs """
def __init__(self, master):
Frame.__init__(self, master)
self.grid(ipadx = 5, ipady = 2) #add some padding to make the GUI look nice
self.create_widgets() #create all those buttons and other things you see in GUI
def create_widgets(self):
""" Create widgets to get new password user specs and to display the password. """
# create uppercase check button
self.is_uppercase = BooleanVar()
Checkbutton(self,
text = "Uppercase",
variable = self.is_uppercase
).grid(row = 0, column = 0, columnspan = 2, sticky = W)
# create lowercase check button
self.is_lowercase = BooleanVar()
Checkbutton(self,
text = "Lowercase",
variable = self.is_lowercase
).grid(row = 1, column = 0, columnspan = 2, sticky = W)
# create clipboard check button
self.is_clipboard = BooleanVar()
Checkbutton(self,
text = "Clipboard",
variable = self.is_clipboard
).grid(row = 0, column = 2, columnspan = 2, sticky = W)
# create digit check button
self.is_digit = BooleanVar()
Checkbutton(self,
text = "Digits",
variable = self.is_digit
).grid(row = 2, column = 0, columnspan = 2, sticky = W)
# create password label for spinbox
self.pass_length = StringVar()
self.previous_pass_length = StringVar()
Label(self,
text = "Length"
).grid(row = 2, column = 2, sticky = W)
# create password length spinbox
vcmd = (self.register(self.validate_float), '%s', '%P') #create validation command for spinbox monitoring
self.spinbox = Spinbox(self,
textvariable = self.pass_length, from_=1, to=20, width = 6,
validate="key", validatecommand = vcmd) #checks for validation upon key entry
self.spinbox.grid(row = 2, column = 2, columnspan = 1, sticky = E)
# create a generate button
Button(self,
text = "Generate", height = 1, width = 10,
command = self.get_password
).grid(row = 3, column = 0, columnspan = 2, sticky = N, pady = 2, padx = 5)
# create a clear button for password text box
Button(self,
text = "Clear", height = 1, width = 10,
command = self.clear_password
).grid(row = 3, column = 2, columnspan = 2, sticky = W, pady = 2, padx = 5)
# create a text box label for generated password
Label(self,
text = "Password"
).grid(row = 4, column = 0, columnspan = 1, sticky = E, pady = 5)
# create a text box for generated password
self.password_txt = Text(self,
width = 21, height = 1, wrap = NONE)
self.password_txt.grid(row = 4, column = 2, columnspan = 2,sticky = S, pady = 5)
# set all check buttons to checked initially
# also set default password length to 8
self.is_digit.set(True)
self.is_clipboard.set(True)
self.is_uppercase.set(True)
self.is_lowercase.set(True)
self.pass_length.set('8')
# validate spinbox entries
def validate_float(self, previous, new):
""" Validate the spinbox entry for only float values. """
if new == "" or new == "-":
return True
#check to see if the input is a float
try:
float(new)
self.previous_pass_length.set(new) #record most up-to-date valid input
return True
except ValueError:
return False
# clear password text box
def clear_password(self):
""" Clear text box with generated password. """
self.password_txt.delete(0.0, END)
# get password from entered specifications
def get_password(self):
""" Fill password text box with new password based on user specs. """
#convert all entered decimal numbers into the next integer
passwordLength = int(math.ceil(float(self.previous_pass_length.get())))
# get values from the GUI
digit = self.is_digit.get()
uppercase = self.is_uppercase.get()
lowercase = self.is_lowercase.get()
clipboard = self.is_clipboard.get()
# reset value in GUI to converted passwordLength
self.pass_length.set(passwordLength)
# If the user overrides the spinbox and enters a number manually, set values to closest option
if passwordLength > 20:
passwordLength = 20
self.pass_length.set('20')
if passwordLength < 1:
passwordLength = 1
self.pass_length.set('1')
# generate password
g = passwordGenerator(passwordLength,digit,uppercase,lowercase,clipboard)
password = g.createPassword()
# print password to text box
self.clear_password()
self.password_txt.insert(END, g.printPassword(password))
#####################################################################################################
class passwordGenerator:
"""A class for generating a password"""
def __init__(self,passwordLength,digit,uppercase,lowercase,clipboard):
self.pwdLength = int(passwordLength) #convert all these boolean and string vars to integers for use
self.dig = int(digit)
self.upper = int(uppercase)
self.lower = int(lowercase)
self.clip = int(clipboard)
self.noChoices = 0
# this function chooses random characters based on user input and returns them as a list
def createPassword(self):
""" Create password based on user specs. """
#initialize list
passwordCharList = []
pwd = []
#define letters and digits
lowercaseLetters = 'abcdefghijklmnopqrstuvwxyz'
uppercaseLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
digits = '0123456789'
# make digits an option when randomly selecting a char (user must specify)
if self.dig:
passwordCharList.extend(list(digits))
# make uppercase letters an option when randomly selecting a char (user must specify)
if self.upper:
passwordCharList.extend(list(uppercaseLetters))
# make lowercase letters an option when randomly selecting a char (user must specify)
if self.lower:
passwordCharList.extend(list(lowercaseLetters))
# choose random characters from option above (number of choices depends on password length)
if self.dig or self.upper or self.lower:
pwd = self.sample_with_replacement(passwordCharList,self.pwdLength)
else:
self.noChoices = 1 #record when no options are selected
return pwd
#This function a random sample list from a given list and the number of choices requested
#NOTE: This is sampling with replacement, so digits and letters can repeat in a password
def sample_with_replacement(self, popList, numChoices):
""" Sample a list with replacement. """
passwordList = []
# select random characters for password
for x in range(0,numChoices):
passwordList.extend(random.sample(popList,1))
return passwordList
#This function returns the string form of a given password character list
def printPassword(self,pwd):
""" Convert list to string and copy to clipboard if required. """
#set generic empty password
stringPassword = ""
#only create new password if there are characters to choose from
if self.noChoices != 1:
# add characters in password list to password string
for x in range(0,self.pwdLength):
stringPassword += pwd[x]
# add password to clipboard if user specified to do that
if self.clip:
c = Tk()
c.withdraw()
c.clipboard_clear()
c.clipboard_append(stringPassword)
c.destroy()
return stringPassword
#####################################################################################################
# the main program
root = Tk()
root.title("Coelacanth")
app = Application(root)
root.mainloop()
| [
[
1,
0,
0.1094,
0.0039,
0,
0.66,
0,
688,
0,
2,
0,
0,
688,
0,
0
],
[
1,
0,
0.1133,
0.0039,
0,
0.66,
0.1,
526,
0,
1,
0,
0,
526,
0,
0
],
[
1,
0,
0.1172,
0.0039,
0,
0.6... | [
"import os,sys",
"import math",
"import random #need this to create random password",
"from Tkinter import *",
"def fatal():\n sys.exit()",
" sys.exit()",
"class Application(Frame):\n \"\"\" GUI application that creates a new random password based on user specs \"\"\"\n def __init__(self, m... |
#!/usr/bin/python
# Sean Hill
# Fall 2012
# CSE 411
# Homework 7
#
# Description: Translates the image segmentation code from the following website from C++ to Python:
# http://www.cs.brown.edu/~pff/segment/
#
# Instructions: The command-line usage is as follows, where "sigma" and "k" and "min" are
# algorithm parameters, "input" is the .ppm file to be segmented, and "output" is a .ppm
# file for storing the output:
# H7.py sigma k min input output
# The output file doesn't need to exist, and the input file must be in a special ppm format
# that starts with P6. See http://orion.math.iastate.edu/burkardt/data/ppm/ppm.html for more
# information and http://www.cs.cornell.edu/courses/cs664/2003fa/images/ for more sample
# input files. Here's an example to run the program using the files I provided:
# H7.py .5 500 50 sign_1.ppm output.ppm
import sys, math, random, struct
MAXVAL = 255 # maximum allowed third value in P6 ppm file
WIDTH = 4.0 # used in filter calculations
# -------------------------------------------------------
# pnmfile.h
# -------------------------------------------------------
def error(message):
""" Report pnm_error and exit. """
sys.stderr.write("ERROR: " + message + " Exiting.\n")
sys.exit()
def pnm_read(f):
""" Read a line of the PNM field, skipping comments. """
c = f.read(1)
while c == '#':
f.readline()
c = f.read(1)
f.seek(-1, 1)
ret = f.readline()
return ret
def loadPPM(filename):
""" Load a PPM image from the specified input file into an Image class instance and rturn it. """
# read header:
try:
f = open(filename, "rb")
except IOError:
error("Failed to open file " + filename + ".")
buf = pnm_read(f)
if (buf[0:2] != "P6"):
error("P6 not found in header of file " + filename + ".")
buf = pnm_read(f).strip().split()
width = int(buf[0])
height = int(buf[1])
buf = pnm_read(f)
if (int(buf) > MAXVAL):
error("Max value (third number after P6) in file " + filename + " exceeds maximum allowed value of " + str(MAXVAL) + ".")
im = Image(width, height, 3)
# read in pixel values, convert from single bytes to rgb string lists:
for y in range(height):
for x in range(width):
rgb = []
for i in range(3):
rgb.append(f.read(1))
im.set_binary_data(x, y, rgb)
f.close()
return im
def savePPM(im, filename):
width = im.width
height = im.height
try:
f = open(filename, "wb")
except IOError:
error("Failed to open file " + filename + ".")
f.write("P6\n" + str(width) + ' ' + str(height) + '\n' + str(MAXVAL) + '\n')
for y in range(height):
for x in range(width):
rgb = im.get_binary_data(x, y)
f.write(rgb[0] + rgb[1] + rgb[2])
f.close()
# -------------------------------------------------------
# image.h
# -------------------------------------------------------
class Image:
def __init__(self, width, height, depth):
self.width = width
self.height = height
self.depth = depth # 3 for full image, 1 for segment
self.data = [[0.0 for value in range(depth)] for value in range(width * height)]
def set_binary_data(self, x, y, input_data):
""" Set data at (x, y) from binary-form input of a single element or a list of size self.depth. """
loc = y * self.width + x
if self.depth == 1:
self.data[loc] = struct.unpack('B', input_data)[0]
else:
self.data[loc] = [struct.unpack('B', input_data[i])[0] for i in range(self.depth)]
def set_decimal_data(self, x, y, input_data):
""" Set data at (x, y) from decimal-form input of a single element or a list of size self.depth. """
loc = y * self.width + x
self.data[loc] = input_data
def get_binary_data(self, x, y):
""" Return data at (x, y) in binary form as a single element or a list of size self.depth. """
loc = y * self.width + x
if self.depth == 1:
return struct.pack('B', int(self.data[loc]))
else:
return [struct.pack('B', int(self.data[loc][i])) for i in range(self.depth)]
def get_decimal_data(self, x, y):
""" Return data at (x, y) in decimal form as a single element or a list of size self.depth. """
loc = y * self.width + x
if self.depth == 1:
return self.data[loc]
else:
return [self.data[loc][i] for i in range(self.depth)]
# -------------------------------------------------------
# segment-image.h
# -------------------------------------------------------
def random_rgb():
rgb = []
for i in range(3):
rgb.append(random.randrange(0, 256))
return rgb
def diff(r, g, b, x1, y1, x2, y2):
return math.sqrt(pow(r.get_decimal_data(x1, y1) - r.get_decimal_data(x2, y2), 2) + \
pow(g.get_decimal_data(x1, y1) - g.get_decimal_data(x2, y2), 2) + \
pow(b.get_decimal_data(x1, y1) - b.get_decimal_data(x2, y2), 2))
def segment_image(im, sigma, c, min_size):
""" Segment an image. Returns a color image representing the segmentation and the number of components in the segmentation.
img: image to segment
sigma: to smooth the image
c: constant for threshold function
min_size: minimum component size (enforced by post-processing stage)"""
width = im.width
height = im.height
# separate colors into three channels:
r = Image(width, height, 1)
g = Image(width, height, 1)
b = Image(width, height, 1)
for y in range(height):
for x in range(width):
rgb = im.get_decimal_data(x, y)
r.set_decimal_data(x, y, rgb[0])
g.set_decimal_data(x, y, rgb[1])
b.set_decimal_data(x, y, rgb[2])
# smooth each color channel:
smooth_r = smooth(r, sigma)
smooth_g = smooth(g, sigma)
smooth_b = smooth(b, sigma)
# build graph:
edges = []
num = 0
for y in range(height):
for x in range(width):
if x < width - 1:
edges.append(Edge(y * width + x, \
y * width + (x + 1), \
diff(smooth_r, smooth_g, smooth_b, x, y, x + 1, y)))
if y < height - 1:
edges.append(Edge(y * width + x, \
(y + 1) * width + x, \
diff(smooth_r, smooth_g, smooth_b, x, y, x, y + 1)))
if x < width - 1 and y < height - 1:
edges.append(Edge(y * width + x, \
(y + 1) * width + (x + 1), \
diff(smooth_r, smooth_g, smooth_b, x, y, x + 1, y + 1)))
if x < width - 1 and y > 0:
edges.append(Edge(y * width + x, \
(y - 1) * width + (x + 1), \
diff(smooth_r, smooth_g, smooth_b, x, y, x + 1, y - 1)))
while len(edges) < width * height * 4:
edges.append(Edge(0, 0, 0))
# segment:
u = segment_graph(width * height, edges, c)
# post-process small components:
for i in range(len(edges)):
a = u.find(edges[i].a)
b = u.find(edges[i].b)
if a != b and (u.size(a) < min_size or u.size(b) < min_size):
u.join(a, b)
num_ccs = u.num_sets()
output = Image(width, height, 3)
# pick random colors for each component:
colors = [random_rgb() for value in range(width * height)]
for y in range(height):
for x in range(height):
comp = u.find(y * width + x)
output.set_decimal_data(x, y, colors[comp])
return output, num_ccs
# -------------------------------------------------------
# filter.h
# -------------------------------------------------------
def normalize(mask):
""" Normalize mask so it integrates to one. """
length = len(mask)
sum = 0.0
for i in range(1, length):
sum = sum + math.fabs(mask[i])
sum = 2 * sum + math.fabs(mask[0])
for i in range(length):
mask[i] = mask[i] / sum
return mask
def make_fgauss(sigma):
sigma = max((sigma, 0.01))
length = int(math.ceil(sigma * WIDTH) + 1)
mask = [0.0 for value in range(length)]
for i in range(length):
mask[i] = math.exp(-0.5 * math.pow(i/sigma, 2))
return mask
def smooth(src, sigma):
""" Convolve image with gaussian filter. """
mask = make_fgauss(sigma)
mask = normalize(mask)
tmp = convolve_even(src, mask)
dst = convolve_even(tmp, mask)
return dst
# -------------------------------------------------------
# convolve.h
# -------------------------------------------------------
def convolve_even(src, mask):
""" Convolve src with mask. ret is flipped! """
width = src.width
height = src.height
length = len(mask)
ret = Image(src.height, src.width, 1)
for y in range(height):
for x in range(width):
sum = mask[0] * src.get_decimal_data(x, y)
for i in range(1, length):
sum = sum + mask[i] \
* (src.get_decimal_data(max((x - i, 0)), y) \
+ src.get_decimal_data(min((x + i, width - 1)), y))
ret.set_decimal_data(y, x, sum)
return ret
# -------------------------------------------------------
# segment-graph.h
# -------------------------------------------------------
def segment_graph(num_vertices, edges, c):
""" Segment a graph. Returns a disjoint-set forest representing the segmentation.
num_vertices: number of vertices in graph
edges: array of edges
c: constant for treshold function"""
# sort edges by weight:
edges = sorted(edges)
# make a disjoint-set forest:
u = Universe(num_vertices)
# initiate thresholds:
threshold = [c for value in range(num_vertices)]
# for each edge, in non-decreasing weight order:
for i in range(len(edges)):
# components connected by this edge:
a = u.find(edges[i].a)
b = u.find(edges[i].b)
if a != b:
if edges[i].w <= threshold[a] and edges[i].w <= threshold[b]:
u.join(a, b)
a = u.find(a)
threshold[a] = edges[i].w + (c / u.size(a))
return u
class Edge:
def __init__(self, a, b, w):
self.a = a
self.b = b
self.w = w
# -------------------------------------------------------
# disjoint-set.h
# -------------------------------------------------------
class Uni_elt:
""" Universe element. """
def __init__(self, rank, size, p):
self.rank = rank
self.size = size
self.p = p
class Universe:
def __init__(self, elements):
self.elts = [Uni_elt(0, 1, i) for i in range(elements)]
self.num = elements
def find(self, x):
y = x
while y != self.elts[y].p:
y = self.elts[y].p
self.elts[x].p = y
return y
def join(self, x, y):
if self.elts[x].rank > self.elts[y].rank:
self.elts[y].p = x
self.elts[x].size = self.elts[x].size + self.elts[y].size
else:
self.elts[x].p = y
self.elts[y].size = self.elts[y].size + self.elts[x].size
if self.elts[x].rank == self.elts[y].rank:
self.elts[y].rank = self.elts[y].rank + 1
self.num = self.num - 1
def size(self, x):
return self.elts[x].size
def num_sets(self):
return self.num
# -------------------------------------------------------
# segment.cpp (main method)
# -------------------------------------------------------
if (len(sys.argv) != 6):
sys.stderr.write("usage: " + sys.argv[0] + " sigma k min input(ppm) output(ppm)\n")
sys.exit()
sigma = float(sys.argv[1])
k = float(sys.argv[2])
min_size = int(sys.argv[3])
print("loading input image.")
input_image = loadPPM(sys.argv[4])
print("processing")
seg, num_ccs = segment_image(input_image, sigma, k, min_size) # return two values
savePPM(seg, sys.argv[5])
print "got", num_ccs, "components"
print "done! uff...thats hard work."
| [
[
1,
0,
0.0556,
0.0026,
0,
0.66,
0,
509,
0,
4,
0,
0,
509,
0,
0
],
[
14,
0,
0.0608,
0.0026,
0,
0.66,
0.0345,
943,
1,
0,
0,
0,
0,
1,
0
],
[
14,
0,
0.0635,
0.0026,
0,
... | [
"import sys, math, random, struct",
"MAXVAL = 255 # maximum allowed third value in P6 ppm file",
"WIDTH = 4.0 # used in filter calculations",
"def error(message):\n \"\"\" Report pnm_error and exit. \"\"\"\n sys.stderr.write(\"ERROR: \" + message + \" Exiting.\\n\")\n sys.exit()",
" \"\"\" Repor... |
#! /usr/bin/python
from optparse import OptionParser
import os.path
import sys
parser = OptionParser()
parser.add_option("-L", "--line", dest="stripLine",
action="store_true", default=False,
help="strip single-line comments //...\\n")
parser.add_option("-C", "--cstyle", dest="stripCStyle",
action="store_true", default=False,
help="strip C-style comments /*...*/")
parser.add_option("-J", "--javadoc", dest="stripJavadoc",
action="store_true", default=False,
help="strip Javadoc comments /**...*/")
parser.add_option("-H", "--headerdoc", dest="stripHeaderDoc",
action="store_true", default=False,
help="strip HeaderDoc comments /*!...*/")
parser.add_option("--input", dest="inputFile", default="",
help="file from which to read input")
(options, args) = parser.parse_args()
error = False
if len(args) != 0:
print "ERROR: Invalid non-option arguments:"
for arg in args:
print " "+arg
error = True
if not options.stripLine and not options.stripCStyle and \
not options.stripJavadoc and not options.stripHeaderDoc:
print "ERROR: Please specify at least one comment style to strip."
error = True
if options.inputFile == "":
print "ERROR: Must specify input file to process using '--input'."
error = True
elif os.path.exists(options.inputFile) == False:
print "ERROR: Specified input file does not exist!"
error = True
else:
file = open(options.inputFile, "r")
if error == True:
sys.exit()
(SOURCE, STRING_LITERAL, CHAR_LITERAL, SLASH, SLASH_STAR, COMMENT_LINE,
COMMENT_CSTYLE, COMMENT_JAVADOC, COMMENT_HEADERDOC) = range(9) #state constants
state = SOURCE
thisChar = ''
while (1):
prevChar = thisChar
thisChar = file.read(1)
if not thisChar:
break
if state == SOURCE:
if thisChar == '/':
state = SLASH
else:
if thisChar == '"':
state = STRING_LITERAL
elif thisChar == '\'':
state = CHAR_LITERAL
sys.stdout.write(thisChar)
elif state == STRING_LITERAL:
if thisChar == '"' and prevChar != '\\':
state = SOURCE
sys.stdout.write(thisChar)
elif state == CHAR_LITERAL:
if thisChar == '\'' and prevChar != '\\':
state = SOURCE
sys.stdout.write(thisChar)
elif state == SLASH:
if thisChar == '*':
state = SLASH_STAR
elif thisChar == '/':
if not options.stripLine:
sys.stdout.write("//")
state = COMMENT_LINE
else:
sys.stdout.write("/")
sys.stdout.write(thisChar)
state = SOURCE
elif state == SLASH_STAR:
if thisChar == '*':
if not options.stripJavadoc:
sys.stdout.write("/**")
state = COMMENT_JAVADOC
elif thisChar == '!':
if not options.stripHeaderDoc:
sys.stdout.write("/*!")
state = COMMENT_HEADERDOC
else:
if not options.stripCStyle:
sys.stdout.write("/*")
sys.stdout.write(thisChar)
state = COMMENT_CSTYLE
thisChar = 0
# Don't treat "/*/" as a valid block comment
elif state == COMMENT_LINE:
if thisChar == '\n':
sys.stdout.write("\n")
state = SOURCE
if not options.stripLine:
sys.stdout.write(thisChar)
elif state == COMMENT_CSTYLE:
if not options.stripCStyle:
sys.stdout.write(thisChar)
if prevChar == '*' and thisChar == '/':
state = SOURCE
elif state == COMMENT_JAVADOC:
if not options.stripJavadoc:
sys.stdout.write(thisChar)
if prevChar == '*' and thisChar == '/':
state = SOURCE
elif state == COMMENT_HEADERDOC:
if not options.stripHeaderDoc:
sys.stdout.write(thisChar)
if prevChar == '*' and thisChar == '/':
state = SOURCE
file.close() | [
[
1,
0,
0.0231,
0.0077,
0,
0.66,
0,
323,
0,
1,
0,
0,
323,
0,
0
],
[
1,
0,
0.0308,
0.0077,
0,
0.66,
0.0526,
79,
0,
1,
0,
0,
79,
0,
0
],
[
1,
0,
0.0385,
0.0077,
0,
0.... | [
"from optparse import OptionParser",
"import os.path",
"import sys",
"parser = OptionParser()",
"parser.add_option(\"-L\", \"--line\", dest=\"stripLine\",\n action=\"store_true\", default=False,\n help=\"strip single-line comments //...\\\\n\")",
"parser.add_option(\"-C... |
#!/opt/ActivePython-2.7/bin/python
#####################################################################################################
# Nicholas Harner
# CSE411
# Homework 7
# 11/19/2012
# This program is an exact mimic of Coelacanth: a simple password generator. It is a very simple
# application for creating passwords that can be used securely. Coelacanth was originally written
# in C#. My version is written in python, using Tkinter for the GUI. This program allows the user
# to designate if he/she would like a password containing any combination of uppercase letters,
# lowercase letters, or digits. The user can also request that the password be copied to the clipboard
# in windows following password generation. In addition, the user can specify the length of the
# password to be generated. Upon clicking generate, the password is created using the user
# specifications. Upon clicking clear, the text box containing the generated password is cleared.
# This clear does not clear the clipboard however.
#To Run on Suns, type:
# python NickHarnerHW7.py
# Coelacanth can be found at:
# http://code.google.com/p/coelacanth/
#####################################################################################################
import os,sys
import math
import random #need this to create random password
from Tkinter import *
def fatal():
sys.exit()
class Application(Frame):
""" GUI application that creates a new random password based on user specs """
def __init__(self, master):
Frame.__init__(self, master)
self.grid(ipadx = 5, ipady = 2) #add some padding to make the GUI look nice
self.create_widgets() #create all those buttons and other things you see in GUI
def create_widgets(self):
""" Create widgets to get new password user specs and to display the password. """
# create uppercase check button
self.is_uppercase = BooleanVar()
Checkbutton(self,
text = "Uppercase",
variable = self.is_uppercase
).grid(row = 0, column = 0, columnspan = 2, sticky = W)
# create lowercase check button
self.is_lowercase = BooleanVar()
Checkbutton(self,
text = "Lowercase",
variable = self.is_lowercase
).grid(row = 1, column = 0, columnspan = 2, sticky = W)
# create clipboard check button
self.is_clipboard = BooleanVar()
Checkbutton(self,
text = "Clipboard",
variable = self.is_clipboard
).grid(row = 0, column = 2, columnspan = 2, sticky = W)
# create digit check button
self.is_digit = BooleanVar()
Checkbutton(self,
text = "Digits",
variable = self.is_digit
).grid(row = 2, column = 0, columnspan = 2, sticky = W)
# create password label for spinbox
self.pass_length = StringVar()
self.previous_pass_length = StringVar()
Label(self,
text = "Length"
).grid(row = 2, column = 2, sticky = W)
# create password length spinbox
vcmd = (self.register(self.validate_float), '%s', '%P') #create validation command for spinbox monitoring
self.spinbox = Spinbox(self,
textvariable = self.pass_length, from_=1, to=20, width = 6,
validate="key", validatecommand = vcmd) #checks for validation upon key entry
self.spinbox.grid(row = 2, column = 2, columnspan = 1, sticky = E)
# create a generate button
Button(self,
text = "Generate", height = 1, width = 10,
command = self.get_password
).grid(row = 3, column = 0, columnspan = 2, sticky = N, pady = 2, padx = 5)
# create a clear button for password text box
Button(self,
text = "Clear", height = 1, width = 10,
command = self.clear_password
).grid(row = 3, column = 2, columnspan = 2, sticky = W, pady = 2, padx = 5)
# create a text box label for generated password
Label(self,
text = "Password"
).grid(row = 4, column = 0, columnspan = 1, sticky = E, pady = 5)
# create a text box for generated password
self.password_txt = Text(self,
width = 21, height = 1, wrap = NONE)
self.password_txt.grid(row = 4, column = 2, columnspan = 2,sticky = S, pady = 5)
# set all check buttons to checked initially
# also set default password length to 8
self.is_digit.set(True)
self.is_clipboard.set(True)
self.is_uppercase.set(True)
self.is_lowercase.set(True)
self.pass_length.set('8')
# validate spinbox entries
def validate_float(self, previous, new):
""" Validate the spinbox entry for only float values. """
if new == "" or new == "-":
return True
#check to see if the input is a float
try:
float(new)
self.previous_pass_length.set(new) #record most up-to-date valid input
return True
except ValueError:
return False
# clear password text box
def clear_password(self):
""" Clear text box with generated password. """
self.password_txt.delete(0.0, END)
# get password from entered specifications
def get_password(self):
""" Fill password text box with new password based on user specs. """
#convert all entered decimal numbers into the next integer
passwordLength = int(math.ceil(float(self.previous_pass_length.get())))
# get values from the GUI
digit = self.is_digit.get()
uppercase = self.is_uppercase.get()
lowercase = self.is_lowercase.get()
clipboard = self.is_clipboard.get()
# reset value in GUI to converted passwordLength
self.pass_length.set(passwordLength)
# If the user overrides the spinbox and enters a number manually, set values to closest option
if passwordLength > 20:
passwordLength = 20
self.pass_length.set('20')
if passwordLength < 1:
passwordLength = 1
self.pass_length.set('1')
# generate password
g = passwordGenerator(passwordLength,digit,uppercase,lowercase,clipboard)
password = g.createPassword()
# print password to text box
self.clear_password()
self.password_txt.insert(END, g.printPassword(password))
#####################################################################################################
class passwordGenerator:
"""A class for generating a password"""
def __init__(self,passwordLength,digit,uppercase,lowercase,clipboard):
self.pwdLength = int(passwordLength) #convert all these boolean and string vars to integers for use
self.dig = int(digit)
self.upper = int(uppercase)
self.lower = int(lowercase)
self.clip = int(clipboard)
self.noChoices = 0
# this function chooses random characters based on user input and returns them as a list
def createPassword(self):
""" Create password based on user specs. """
#initialize list
passwordCharList = []
pwd = []
#define letters and digits
lowercaseLetters = 'abcdefghijklmnopqrstuvwxyz'
uppercaseLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
digits = '0123456789'
# make digits an option when randomly selecting a char (user must specify)
if self.dig:
passwordCharList.extend(list(digits))
# make uppercase letters an option when randomly selecting a char (user must specify)
if self.upper:
passwordCharList.extend(list(uppercaseLetters))
# make lowercase letters an option when randomly selecting a char (user must specify)
if self.lower:
passwordCharList.extend(list(lowercaseLetters))
# choose random characters from option above (number of choices depends on password length)
if self.dig or self.upper or self.lower:
pwd = self.sample_with_replacement(passwordCharList,self.pwdLength)
else:
self.noChoices = 1 #record when no options are selected
return pwd
#This function a random sample list from a given list and the number of choices requested
#NOTE: This is sampling with replacement, so digits and letters can repeat in a password
def sample_with_replacement(self, popList, numChoices):
""" Sample a list with replacement. """
passwordList = []
# select random characters for password
for x in range(0,numChoices):
passwordList.extend(random.sample(popList,1))
return passwordList
#This function returns the string form of a given password character list
def printPassword(self,pwd):
""" Convert list to string and copy to clipboard if required. """
#set generic empty password
stringPassword = ""
#only create new password if there are characters to choose from
if self.noChoices != 1:
# add characters in password list to password string
for x in range(0,self.pwdLength):
stringPassword += pwd[x]
# add password to clipboard if user specified to do that
if self.clip:
c = Tk()
c.withdraw()
c.clipboard_clear()
c.clipboard_append(stringPassword)
c.destroy()
return stringPassword
#####################################################################################################
# the main program
root = Tk()
root.title("Coelacanth")
app = Application(root)
root.mainloop()
| [
[
1,
0,
0.1094,
0.0039,
0,
0.66,
0,
688,
0,
2,
0,
0,
688,
0,
0
],
[
1,
0,
0.1133,
0.0039,
0,
0.66,
0.1,
526,
0,
1,
0,
0,
526,
0,
0
],
[
1,
0,
0.1172,
0.0039,
0,
0.6... | [
"import os,sys",
"import math",
"import random #need this to create random password",
"from Tkinter import *",
"def fatal():\n sys.exit()",
" sys.exit()",
"class Application(Frame):\n \"\"\" GUI application that creates a new random password based on user specs \"\"\"\n def __init__(self, m... |
#!/usr/bin/python
# Sean Hill
# Fall 2012
# CSE 411
# Homework 7
#
# Description: Translates the image segmentation code from the following website from C++ to Python:
# http://www.cs.brown.edu/~pff/segment/
#
# Instructions: The command-line usage is as follows, where "sigma" and "k" and "min" are
# algorithm parameters, "input" is the .ppm file to be segmented, and "output" is a .ppm
# file for storing the output:
# H7.py sigma k min input output
# The output file doesn't need to exist, and the input file must be in a special ppm format
# that starts with P6. See http://orion.math.iastate.edu/burkardt/data/ppm/ppm.html for more
# information and http://www.cs.cornell.edu/courses/cs664/2003fa/images/ for more sample
# input files. Here's an example to run the program using the files I provided:
# H7.py .5 500 50 sign_1.ppm output.ppm
import sys, math, random, struct
MAXVAL = 255 # maximum allowed third value in P6 ppm file
WIDTH = 4.0 # used in filter calculations
# -------------------------------------------------------
# pnmfile.h
# -------------------------------------------------------
def error(message):
""" Report pnm_error and exit. """
sys.stderr.write("ERROR: " + message + " Exiting.\n")
sys.exit()
def pnm_read(f):
""" Read a line of the PNM field, skipping comments. """
c = f.read(1)
while c == '#':
f.readline()
c = f.read(1)
f.seek(-1, 1)
ret = f.readline()
return ret
def loadPPM(filename):
""" Load a PPM image from the specified input file into an Image class instance and rturn it. """
# read header:
try:
f = open(filename, "rb")
except IOError:
error("Failed to open file " + filename + ".")
buf = pnm_read(f)
if (buf[0:2] != "P6"):
error("P6 not found in header of file " + filename + ".")
buf = pnm_read(f).strip().split()
width = int(buf[0])
height = int(buf[1])
buf = pnm_read(f)
if (int(buf) > MAXVAL):
error("Max value (third number after P6) in file " + filename + " exceeds maximum allowed value of " + str(MAXVAL) + ".")
im = Image(width, height, 3)
# read in pixel values, convert from single bytes to rgb string lists:
for y in range(height):
for x in range(width):
rgb = []
for i in range(3):
rgb.append(f.read(1))
im.set_binary_data(x, y, rgb)
f.close()
return im
def savePPM(im, filename):
width = im.width
height = im.height
try:
f = open(filename, "wb")
except IOError:
error("Failed to open file " + filename + ".")
f.write("P6\n" + str(width) + ' ' + str(height) + '\n' + str(MAXVAL) + '\n')
for y in range(height):
for x in range(width):
rgb = im.get_binary_data(x, y)
f.write(rgb[0] + rgb[1] + rgb[2])
f.close()
# -------------------------------------------------------
# image.h
# -------------------------------------------------------
class Image:
def __init__(self, width, height, depth):
self.width = width
self.height = height
self.depth = depth # 3 for full image, 1 for segment
self.data = [[0.0 for value in range(depth)] for value in range(width * height)]
def set_binary_data(self, x, y, input_data):
""" Set data at (x, y) from binary-form input of a single element or a list of size self.depth. """
loc = y * self.width + x
if self.depth == 1:
self.data[loc] = struct.unpack('B', input_data)[0]
else:
self.data[loc] = [struct.unpack('B', input_data[i])[0] for i in range(self.depth)]
def set_decimal_data(self, x, y, input_data):
""" Set data at (x, y) from decimal-form input of a single element or a list of size self.depth. """
loc = y * self.width + x
self.data[loc] = input_data
def get_binary_data(self, x, y):
""" Return data at (x, y) in binary form as a single element or a list of size self.depth. """
loc = y * self.width + x
if self.depth == 1:
return struct.pack('B', int(self.data[loc]))
else:
return [struct.pack('B', int(self.data[loc][i])) for i in range(self.depth)]
def get_decimal_data(self, x, y):
""" Return data at (x, y) in decimal form as a single element or a list of size self.depth. """
loc = y * self.width + x
if self.depth == 1:
return self.data[loc]
else:
return [self.data[loc][i] for i in range(self.depth)]
# -------------------------------------------------------
# segment-image.h
# -------------------------------------------------------
def random_rgb():
rgb = []
for i in range(3):
rgb.append(random.randrange(0, 256))
return rgb
def diff(r, g, b, x1, y1, x2, y2):
return math.sqrt(pow(r.get_decimal_data(x1, y1) - r.get_decimal_data(x2, y2), 2) + \
pow(g.get_decimal_data(x1, y1) - g.get_decimal_data(x2, y2), 2) + \
pow(b.get_decimal_data(x1, y1) - b.get_decimal_data(x2, y2), 2))
def segment_image(im, sigma, c, min_size):
""" Segment an image. Returns a color image representing the segmentation and the number of components in the segmentation.
img: image to segment
sigma: to smooth the image
c: constant for threshold function
min_size: minimum component size (enforced by post-processing stage)"""
width = im.width
height = im.height
# separate colors into three channels:
r = Image(width, height, 1)
g = Image(width, height, 1)
b = Image(width, height, 1)
for y in range(height):
for x in range(width):
rgb = im.get_decimal_data(x, y)
r.set_decimal_data(x, y, rgb[0])
g.set_decimal_data(x, y, rgb[1])
b.set_decimal_data(x, y, rgb[2])
# smooth each color channel:
smooth_r = smooth(r, sigma)
smooth_g = smooth(g, sigma)
smooth_b = smooth(b, sigma)
# build graph:
edges = []
num = 0
for y in range(height):
for x in range(width):
if x < width - 1:
edges.append(Edge(y * width + x, \
y * width + (x + 1), \
diff(smooth_r, smooth_g, smooth_b, x, y, x + 1, y)))
if y < height - 1:
edges.append(Edge(y * width + x, \
(y + 1) * width + x, \
diff(smooth_r, smooth_g, smooth_b, x, y, x, y + 1)))
if x < width - 1 and y < height - 1:
edges.append(Edge(y * width + x, \
(y + 1) * width + (x + 1), \
diff(smooth_r, smooth_g, smooth_b, x, y, x + 1, y + 1)))
if x < width - 1 and y > 0:
edges.append(Edge(y * width + x, \
(y - 1) * width + (x + 1), \
diff(smooth_r, smooth_g, smooth_b, x, y, x + 1, y - 1)))
while len(edges) < width * height * 4:
edges.append(Edge(0, 0, 0))
# segment:
u = segment_graph(width * height, edges, c)
# post-process small components:
for i in range(len(edges)):
a = u.find(edges[i].a)
b = u.find(edges[i].b)
if a != b and (u.size(a) < min_size or u.size(b) < min_size):
u.join(a, b)
num_ccs = u.num_sets()
output = Image(width, height, 3)
# pick random colors for each component:
colors = [random_rgb() for value in range(width * height)]
for y in range(height):
for x in range(height):
comp = u.find(y * width + x)
output.set_decimal_data(x, y, colors[comp])
return output, num_ccs
# -------------------------------------------------------
# filter.h
# -------------------------------------------------------
def normalize(mask):
""" Normalize mask so it integrates to one. """
length = len(mask)
sum = 0.0
for i in range(1, length):
sum = sum + math.fabs(mask[i])
sum = 2 * sum + math.fabs(mask[0])
for i in range(length):
mask[i] = mask[i] / sum
return mask
def make_fgauss(sigma):
sigma = max((sigma, 0.01))
length = int(math.ceil(sigma * WIDTH) + 1)
mask = [0.0 for value in range(length)]
for i in range(length):
mask[i] = math.exp(-0.5 * math.pow(i/sigma, 2))
return mask
def smooth(src, sigma):
""" Convolve image with gaussian filter. """
mask = make_fgauss(sigma)
mask = normalize(mask)
tmp = convolve_even(src, mask)
dst = convolve_even(tmp, mask)
return dst
# -------------------------------------------------------
# convolve.h
# -------------------------------------------------------
def convolve_even(src, mask):
""" Convolve src with mask. ret is flipped! """
width = src.width
height = src.height
length = len(mask)
ret = Image(src.height, src.width, 1)
for y in range(height):
for x in range(width):
sum = mask[0] * src.get_decimal_data(x, y)
for i in range(1, length):
sum = sum + mask[i] \
* (src.get_decimal_data(max((x - i, 0)), y) \
+ src.get_decimal_data(min((x + i, width - 1)), y))
ret.set_decimal_data(y, x, sum)
return ret
# -------------------------------------------------------
# segment-graph.h
# -------------------------------------------------------
def segment_graph(num_vertices, edges, c):
""" Segment a graph. Returns a disjoint-set forest representing the segmentation.
num_vertices: number of vertices in graph
edges: array of edges
c: constant for treshold function"""
# sort edges by weight:
edges = sorted(edges)
# make a disjoint-set forest:
u = Universe(num_vertices)
# initiate thresholds:
threshold = [c for value in range(num_vertices)]
# for each edge, in non-decreasing weight order:
for i in range(len(edges)):
# components connected by this edge:
a = u.find(edges[i].a)
b = u.find(edges[i].b)
if a != b:
if edges[i].w <= threshold[a] and edges[i].w <= threshold[b]:
u.join(a, b)
a = u.find(a)
threshold[a] = edges[i].w + (c / u.size(a))
return u
class Edge:
def __init__(self, a, b, w):
self.a = a
self.b = b
self.w = w
# -------------------------------------------------------
# disjoint-set.h
# -------------------------------------------------------
class Uni_elt:
""" Universe element. """
def __init__(self, rank, size, p):
self.rank = rank
self.size = size
self.p = p
class Universe:
def __init__(self, elements):
self.elts = [Uni_elt(0, 1, i) for i in range(elements)]
self.num = elements
def find(self, x):
y = x
while y != self.elts[y].p:
y = self.elts[y].p
self.elts[x].p = y
return y
def join(self, x, y):
if self.elts[x].rank > self.elts[y].rank:
self.elts[y].p = x
self.elts[x].size = self.elts[x].size + self.elts[y].size
else:
self.elts[x].p = y
self.elts[y].size = self.elts[y].size + self.elts[x].size
if self.elts[x].rank == self.elts[y].rank:
self.elts[y].rank = self.elts[y].rank + 1
self.num = self.num - 1
def size(self, x):
return self.elts[x].size
def num_sets(self):
return self.num
# -------------------------------------------------------
# segment.cpp (main method)
# -------------------------------------------------------
if (len(sys.argv) != 6):
sys.stderr.write("usage: " + sys.argv[0] + " sigma k min input(ppm) output(ppm)\n")
sys.exit()
sigma = float(sys.argv[1])
k = float(sys.argv[2])
min_size = int(sys.argv[3])
print("loading input image.")
input_image = loadPPM(sys.argv[4])
print("processing")
seg, num_ccs = segment_image(input_image, sigma, k, min_size) # return two values
savePPM(seg, sys.argv[5])
print "got", num_ccs, "components"
print "done! uff...thats hard work."
| [
[
1,
0,
0.0556,
0.0026,
0,
0.66,
0,
509,
0,
4,
0,
0,
509,
0,
0
],
[
14,
0,
0.0608,
0.0026,
0,
0.66,
0.0345,
943,
1,
0,
0,
0,
0,
1,
0
],
[
14,
0,
0.0635,
0.0026,
0,
... | [
"import sys, math, random, struct",
"MAXVAL = 255 # maximum allowed third value in P6 ppm file",
"WIDTH = 4.0 # used in filter calculations",
"def error(message):\n \"\"\" Report pnm_error and exit. \"\"\"\n sys.stderr.write(\"ERROR: \" + message + \" Exiting.\\n\")\n sys.exit()",
" \"\"\" Repor... |
#! /usr/bin/python
from optparse import OptionParser
import os.path
import sys
parser = OptionParser()
parser.add_option("-L", "--line", dest="stripLine",
action="store_true", default=False,
help="strip single-line comments //...\\n")
parser.add_option("-C", "--cstyle", dest="stripCStyle",
action="store_true", default=False,
help="strip C-style comments /*...*/")
parser.add_option("-J", "--javadoc", dest="stripJavadoc",
action="store_true", default=False,
help="strip Javadoc comments /**...*/")
parser.add_option("-H", "--headerdoc", dest="stripHeaderDoc",
action="store_true", default=False,
help="strip HeaderDoc comments /*!...*/")
parser.add_option("--input", dest="inputFile", default="",
help="file from which to read input")
(options, args) = parser.parse_args()
error = False
if len(args) != 0:
print "ERROR: Invalid non-option arguments:"
for arg in args:
print " "+arg
error = True
if not options.stripLine and not options.stripCStyle and \
not options.stripJavadoc and not options.stripHeaderDoc:
print "ERROR: Please specify at least one comment style to strip."
error = True
if options.inputFile == "":
print "ERROR: Must specify input file to process using '--input'."
error = True
elif os.path.exists(options.inputFile) == False:
print "ERROR: Specified input file does not exist!"
error = True
else:
file = open(options.inputFile, "r")
if error == True:
sys.exit()
(SOURCE, STRING_LITERAL, CHAR_LITERAL, SLASH, SLASH_STAR, COMMENT_LINE,
COMMENT_CSTYLE, COMMENT_JAVADOC, COMMENT_HEADERDOC) = range(9) #state constants
state = SOURCE
thisChar = ''
while (1):
prevChar = thisChar
thisChar = file.read(1)
if not thisChar:
break
if state == SOURCE:
if thisChar == '/':
state = SLASH
else:
if thisChar == '"':
state = STRING_LITERAL
elif thisChar == '\'':
state = CHAR_LITERAL
sys.stdout.write(thisChar)
elif state == STRING_LITERAL:
if thisChar == '"' and prevChar != '\\':
state = SOURCE
sys.stdout.write(thisChar)
elif state == CHAR_LITERAL:
if thisChar == '\'' and prevChar != '\\':
state = SOURCE
sys.stdout.write(thisChar)
elif state == SLASH:
if thisChar == '*':
state = SLASH_STAR
elif thisChar == '/':
if not options.stripLine:
sys.stdout.write("//")
state = COMMENT_LINE
else:
sys.stdout.write("/")
sys.stdout.write(thisChar)
state = SOURCE
elif state == SLASH_STAR:
if thisChar == '*':
if not options.stripJavadoc:
sys.stdout.write("/**")
state = COMMENT_JAVADOC
elif thisChar == '!':
if not options.stripHeaderDoc:
sys.stdout.write("/*!")
state = COMMENT_HEADERDOC
else:
if not options.stripCStyle:
sys.stdout.write("/*")
sys.stdout.write(thisChar)
state = COMMENT_CSTYLE
thisChar = 0
# Don't treat "/*/" as a valid block comment
elif state == COMMENT_LINE:
if thisChar == '\n':
sys.stdout.write("\n")
state = SOURCE
if not options.stripLine:
sys.stdout.write(thisChar)
elif state == COMMENT_CSTYLE:
if not options.stripCStyle:
sys.stdout.write(thisChar)
if prevChar == '*' and thisChar == '/':
state = SOURCE
elif state == COMMENT_JAVADOC:
if not options.stripJavadoc:
sys.stdout.write(thisChar)
if prevChar == '*' and thisChar == '/':
state = SOURCE
elif state == COMMENT_HEADERDOC:
if not options.stripHeaderDoc:
sys.stdout.write(thisChar)
if prevChar == '*' and thisChar == '/':
state = SOURCE
file.close() | [
[
1,
0,
0.0231,
0.0077,
0,
0.66,
0,
323,
0,
1,
0,
0,
323,
0,
0
],
[
1,
0,
0.0308,
0.0077,
0,
0.66,
0.0526,
79,
0,
1,
0,
0,
79,
0,
0
],
[
1,
0,
0.0385,
0.0077,
0,
0.... | [
"from optparse import OptionParser",
"import os.path",
"import sys",
"parser = OptionParser()",
"parser.add_option(\"-L\", \"--line\", dest=\"stripLine\",\n action=\"store_true\", default=False,\n help=\"strip single-line comments //...\\\\n\")",
"parser.add_option(\"-C... |
#!/opt/ActivePython-2.7/bin/python
# Mad Lib
# Create a story based on user input
from Tkinter import *
class Application(Frame):
""" GUI application that creates a story based on user input. """
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.create_widgets()
def create_widgets(self):
""" Create widgets to get story information and to display story. """
# create instruction label
Label(self,
text = "Enter information for a new story"
).grid(row = 0, column = 0, columnspan = 2, sticky = W)
# create a label and text entry for the name of a person
Label(self,
text = "Person: "
).grid(row = 1, column = 0, sticky = W)
self.person_ent = Entry(self)
self.person_ent.grid(row = 1, column = 1, sticky = W)
# create a label and text entry for a plural noun
Label(self,
text = "Plural Noun:"
).grid(row = 2, column = 0, sticky = W)
self.noun_ent = Entry(self)
self.noun_ent.grid(row = 2, column = 1, sticky = W)
# create a label and text entry for a verb
Label(self,
text = "Verb:"
).grid(row = 3, column = 0, sticky = W)
self.verb_ent = Entry(self)
self.verb_ent.grid(row = 3, column = 1, sticky = W)
# create a label for adjectives check buttons
Label(self,
text = "Adjective(s):"
).grid(row = 4, column = 0, sticky = W)
# create itchy check button
self.is_itchy = BooleanVar()
Checkbutton(self,
text = "itchy",
variable = self.is_itchy
).grid(row = 4, column = 1, sticky = W)
# create joyous check button
self.is_joyous = BooleanVar()
Checkbutton(self,
text = "joyous",
variable = self.is_joyous
).grid(row = 4, column = 2, sticky = W)
# create electric check button
self.is_electric = BooleanVar()
Checkbutton(self,
text = "electric",
variable = self.is_electric
).grid(row = 4, column = 3, sticky = W)
# create a label for body parts radio buttons
Label(self,
text = "Body Part:"
).grid(row = 5, column = 0, sticky = W)
# create variable for single, body part
self.body_part = StringVar()
self.body_part.set(None)
# create body part radio buttons
body_parts = ["bellybutton", "big toe", "medulla oblongata"]
column = 1
for part in body_parts:
Radiobutton(self,
text = part,
variable = self.body_part,
value = part
).grid(row = 5, column = column, sticky = W)
column += 1
# create a submit button
Button(self,
text = "Click for story",
command = self.tell_story
).grid(row = 6, column = 0, sticky = W)
self.story_txt = Text(self, width = 75, height = 10, wrap = WORD)
self.story_txt.grid(row = 7, column = 0, columnspan = 4)
def tell_story(self):
""" Fill text box with new story based on user input. """
# get values from the GUI
person = self.person_ent.get()
noun = self.noun_ent.get()
verb = self.verb_ent.get()
adjectives = ""
if self.is_itchy.get():
adjectives += "itchy, "
if self.is_joyous.get():
adjectives += "joyous, "
if self.is_electric.get():
adjectives += "electric, "
body_part = self.body_part.get()
# create the story
story = "The famous explorer "
story += person
story += " had nearly given up a life-long quest to find The Lost City of "
story += noun.title()
story += " when one day, the "
story += noun
story += " found "
story += person + ". "
story += "A strong, "
story += adjectives
story += "peculiar feeling overwhelmed the explorer. "
story += "After all this time, the quest was finally over. A tear came to "
story += person + "'s "
story += body_part + ". "
story += "And then, the "
story += noun
story += " promptly devoured "
story += person + ". "
story += "The moral of the story? Be careful what you "
story += verb
story += " for."
# display the story
self.story_txt.delete(0.0, END)
self.story_txt.insert(0.0, story)
# main
root = Tk()
root.title("Mad Lib")
app = Application(root)
root.mainloop()
| [
[
1,
0,
0.0414,
0.0069,
0,
0.66,
0,
368,
0,
1,
0,
0,
368,
0,
0
],
[
3,
0,
0.5034,
0.9034,
0,
0.66,
0.2,
979,
0,
3,
0,
0,
342,
0,
48
],
[
8,
1,
0.0621,
0.0069,
1,
0.... | [
"from Tkinter import *",
"class Application(Frame):\n \"\"\" GUI application that creates a story based on user input. \"\"\"\n def __init__(self, master):\n Frame.__init__(self, master)\n self.grid()\n self.create_widgets()\n\n def create_widgets(self):",
" \"\"\" GUI applicati... |
#!/opt/ActivePython-2.7/bin/python
# labeler.py
from Tkinter import *
root = Tk()
root.title("Labeler")
# root.geometry("200x100")
app = Frame(root)
app.grid()
lbl = Label(app, text = "I'm a label!")
lbl.grid()
root.mainloop()
| [
[
1,
0,
0.2941,
0.0588,
0,
0.66,
0,
368,
0,
1,
0,
0,
368,
0,
0
],
[
14,
0,
0.4118,
0.0588,
0,
0.66,
0.1429,
696,
3,
0,
0,
0,
309,
10,
1
],
[
8,
0,
0.4706,
0.0588,
0,
... | [
"from Tkinter import *",
"root = Tk()",
"root.title(\"Labeler\")",
"app = Frame(root)",
"app.grid()",
"lbl = Label(app, text = \"I'm a label!\")",
"lbl.grid()",
"root.mainloop()"
] |
#!/opt/ActivePython-2.7/bin/python
# Mad Lib
# Create a story based on user input
from Tkinter import *
class Application(Frame):
""" GUI application that creates a story based on user input. """
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.create_widgets()
def create_widgets(self):
""" Create widgets to get story information and to display story. """
# create instruction label
Label(self,
text = "Enter information for a new story"
).grid(row = 0, column = 0, columnspan = 2, sticky = W)
# create a label and text entry for the name of a person
Label(self,
text = "Person: "
).grid(row = 1, column = 0, sticky = W)
self.person_ent = Entry(self)
self.person_ent.grid(row = 1, column = 1, sticky = W)
# create a label and text entry for a plural noun
Label(self,
text = "Plural Noun:"
).grid(row = 2, column = 0, sticky = W)
self.noun_ent = Entry(self)
self.noun_ent.grid(row = 2, column = 1, sticky = W)
# create a label and text entry for a verb
Label(self,
text = "Verb:"
).grid(row = 3, column = 0, sticky = W)
self.verb_ent = Entry(self)
self.verb_ent.grid(row = 3, column = 1, sticky = W)
# create a label for adjectives check buttons
Label(self,
text = "Adjective(s):"
).grid(row = 4, column = 0, sticky = W)
# create itchy check button
self.is_itchy = BooleanVar()
Checkbutton(self,
text = "itchy",
variable = self.is_itchy
).grid(row = 4, column = 1, sticky = W)
# create joyous check button
self.is_joyous = BooleanVar()
Checkbutton(self,
text = "joyous",
variable = self.is_joyous
).grid(row = 4, column = 2, sticky = W)
# create electric check button
self.is_electric = BooleanVar()
Checkbutton(self,
text = "electric",
variable = self.is_electric
).grid(row = 4, column = 3, sticky = W)
# create a label for body parts radio buttons
Label(self,
text = "Body Part:"
).grid(row = 5, column = 0, sticky = W)
# create variable for single, body part
self.body_part = StringVar()
self.body_part.set(None)
# create body part radio buttons
body_parts = ["bellybutton", "big toe", "medulla oblongata"]
column = 1
for part in body_parts:
Radiobutton(self,
text = part,
variable = self.body_part,
value = part
).grid(row = 5, column = column, sticky = W)
column += 1
# create a submit button
Button(self,
text = "Click for story",
command = self.tell_story
).grid(row = 6, column = 0, sticky = W)
self.story_txt = Text(self, width = 75, height = 10, wrap = WORD)
self.story_txt.grid(row = 7, column = 0, columnspan = 4)
def tell_story(self):
""" Fill text box with new story based on user input. """
# get values from the GUI
person = self.person_ent.get()
noun = self.noun_ent.get()
verb = self.verb_ent.get()
adjectives = ""
if self.is_itchy.get():
adjectives += "itchy, "
if self.is_joyous.get():
adjectives += "joyous, "
if self.is_electric.get():
adjectives += "electric, "
body_part = self.body_part.get()
# create the story
story = "The famous explorer "
story += person
story += " had nearly given up a life-long quest to find The Lost City of "
story += noun.title()
story += " when one day, the "
story += noun
story += " found "
story += person + ". "
story += "A strong, "
story += adjectives
story += "peculiar feeling overwhelmed the explorer. "
story += "After all this time, the quest was finally over. A tear came to "
story += person + "'s "
story += body_part + ". "
story += "And then, the "
story += noun
story += " promptly devoured "
story += person + ". "
story += "The moral of the story? Be careful what you "
story += verb
story += " for."
# display the story
self.story_txt.delete(0.0, END)
self.story_txt.insert(0.0, story)
# main
root = Tk()
root.title("Mad Lib")
app = Application(root)
root.mainloop()
| [
[
1,
0,
0.0414,
0.0069,
0,
0.66,
0,
368,
0,
1,
0,
0,
368,
0,
0
],
[
3,
0,
0.5034,
0.9034,
0,
0.66,
0.2,
979,
0,
3,
0,
0,
342,
0,
48
],
[
8,
1,
0.0621,
0.0069,
1,
0.... | [
"from Tkinter import *",
"class Application(Frame):\n \"\"\" GUI application that creates a story based on user input. \"\"\"\n def __init__(self, master):\n Frame.__init__(self, master)\n self.grid()\n self.create_widgets()\n\n def create_widgets(self):",
" \"\"\" GUI applicati... |
#!/opt/ActivePython-2.7/bin/python
# lazy_buttons.py
from Tkinter import *
root = Tk()
root.title("Lazy Buttons")
root.geometry("200x100")
app = Frame(root)
app.grid()
bttn1 = Button(app, text = "I do nothing!")
bttn1.grid()
bttn2 = Button(app)
bttn2.grid()
bttn2.configure(text = "Me too!")
bttn3 = Button(app)
bttn3.grid()
bttn3["text"] = "Same here!"
root.mainloop()
| [
[
1,
0,
0.2,
0.04,
0,
0.66,
0,
368,
0,
1,
0,
0,
368,
0,
0
],
[
14,
0,
0.28,
0.04,
0,
0.66,
0.0714,
696,
3,
0,
0,
0,
309,
10,
1
],
[
8,
0,
0.32,
0.04,
0,
0.66,
0... | [
"from Tkinter import *",
"root = Tk()",
"root.title(\"Lazy Buttons\")",
"root.geometry(\"200x100\")",
"app = Frame(root)",
"app.grid()",
"bttn1 = Button(app, text = \"I do nothing!\")",
"bttn1.grid()",
"bttn2 = Button(app)",
"bttn2.grid()",
"bttn2.configure(text = \"Me too!\")",
"bttn3 = Butto... |
#!/opt/ActivePython-2.7/bin/python
# click_counter.py
from Tkinter import *
class Application(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.bttn_clicks = 0 # number clicks
self.create_widget()
def create_widget(self):
self.bttn = Button(self)
self.bttn["text"]= "Total Clicks: 0"
self.bttn["command"] = self.update_count
self.bttn.grid()
def update_count(self):
self.bttn_clicks += 1
self.bttn["text"] = "Total Clicks: " + str(self.bttn_clicks)
# main
root = Tk()
root.title("Click Counter")
root.geometry("200x85")
app = Application(root)
root.mainloop()
| [
[
1,
0,
0.1724,
0.0345,
0,
0.66,
0,
368,
0,
1,
0,
0,
368,
0,
0
],
[
3,
0,
0.5,
0.5517,
0,
0.66,
0.1667,
979,
0,
3,
0,
0,
342,
0,
6
],
[
2,
1,
0.3448,
0.1724,
1,
0.7... | [
"from Tkinter import *",
"class Application(Frame):\n def __init__(self, master):\n Frame.__init__(self, master)\n self.grid()\n self.bttn_clicks = 0 # number clicks\n self.create_widget()\n\n def create_widget(self):",
" def __init__(self, master):\n Frame.__init_... |
#!/opt/ActivePython-2.7/bin/python
# simple_gui.py
from Tkinter import *
root = Tk()
root.title("Simple GUI")
root.geometry("200x100")
root.mainloop()
| [
[
1,
0,
0.4545,
0.0909,
0,
0.66,
0,
368,
0,
1,
0,
0,
368,
0,
0
],
[
14,
0,
0.6364,
0.0909,
0,
0.66,
0.25,
696,
3,
0,
0,
0,
309,
10,
1
],
[
8,
0,
0.7273,
0.0909,
0,
... | [
"from Tkinter import *",
"root = Tk()",
"root.title(\"Simple GUI\")",
"root.geometry(\"200x100\")",
"root.mainloop()"
] |
#!/opt/ActivePython-2.7/bin/python
# labeler.py
from Tkinter import *
root = Tk()
root.title("Labeler")
# root.geometry("200x100")
app = Frame(root)
app.grid()
lbl = Label(app, text = "I'm a label!")
lbl.grid()
root.mainloop()
| [
[
1,
0,
0.2941,
0.0588,
0,
0.66,
0,
368,
0,
1,
0,
0,
368,
0,
0
],
[
14,
0,
0.4118,
0.0588,
0,
0.66,
0.1429,
696,
3,
0,
0,
0,
309,
10,
1
],
[
8,
0,
0.4706,
0.0588,
0,
... | [
"from Tkinter import *",
"root = Tk()",
"root.title(\"Labeler\")",
"app = Frame(root)",
"app.grid()",
"lbl = Label(app, text = \"I'm a label!\")",
"lbl.grid()",
"root.mainloop()"
] |
#!/opt/ActivePython-2.7/bin/python
# simple_gui.py
from Tkinter import *
root = Tk()
root.title("Simple GUI")
root.geometry("200x100")
root.mainloop()
| [
[
1,
0,
0.4545,
0.0909,
0,
0.66,
0,
368,
0,
1,
0,
0,
368,
0,
0
],
[
14,
0,
0.6364,
0.0909,
0,
0.66,
0.25,
696,
3,
0,
0,
0,
309,
10,
1
],
[
8,
0,
0.7273,
0.0909,
0,
... | [
"from Tkinter import *",
"root = Tk()",
"root.title(\"Simple GUI\")",
"root.geometry(\"200x100\")",
"root.mainloop()"
] |
#!/opt/ActivePython-2.7/bin/python
# lazy_buttons.py
from Tkinter import *
root = Tk()
root.title("Lazy Buttons")
root.geometry("200x100")
app = Frame(root)
app.grid()
bttn1 = Button(app, text = "I do nothing!")
bttn1.grid()
bttn2 = Button(app)
bttn2.grid()
bttn2.configure(text = "Me too!")
bttn3 = Button(app)
bttn3.grid()
bttn3["text"] = "Same here!"
root.mainloop()
| [
[
1,
0,
0.2,
0.04,
0,
0.66,
0,
368,
0,
1,
0,
0,
368,
0,
0
],
[
14,
0,
0.28,
0.04,
0,
0.66,
0.0714,
696,
3,
0,
0,
0,
309,
10,
1
],
[
8,
0,
0.32,
0.04,
0,
0.66,
0... | [
"from Tkinter import *",
"root = Tk()",
"root.title(\"Lazy Buttons\")",
"root.geometry(\"200x100\")",
"app = Frame(root)",
"app.grid()",
"bttn1 = Button(app, text = \"I do nothing!\")",
"bttn1.grid()",
"bttn2 = Button(app)",
"bttn2.grid()",
"bttn2.configure(text = \"Me too!\")",
"bttn3 = Butto... |
#!/opt/ActivePython-2.7/bin/python
# click_counter.py
from Tkinter import *
class Application(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.bttn_clicks = 0 # number clicks
self.create_widget()
def create_widget(self):
self.bttn = Button(self)
self.bttn["text"]= "Total Clicks: 0"
self.bttn["command"] = self.update_count
self.bttn.grid()
def update_count(self):
self.bttn_clicks += 1
self.bttn["text"] = "Total Clicks: " + str(self.bttn_clicks)
# main
root = Tk()
root.title("Click Counter")
root.geometry("200x85")
app = Application(root)
root.mainloop()
| [
[
1,
0,
0.1724,
0.0345,
0,
0.66,
0,
368,
0,
1,
0,
0,
368,
0,
0
],
[
3,
0,
0.5,
0.5517,
0,
0.66,
0.1667,
979,
0,
3,
0,
0,
342,
0,
6
],
[
2,
1,
0.3448,
0.1724,
1,
0.5... | [
"from Tkinter import *",
"class Application(Frame):\n def __init__(self, master):\n Frame.__init__(self, master)\n self.grid()\n self.bttn_clicks = 0 # number clicks\n self.create_widget()\n\n def create_widget(self):",
" def __init__(self, master):\n Frame.__init_... |
# graphics.py
"""Simple object oriented graphics library
The library is designed to make it very easy for novice programmers to
experiment with computer graphics in an object oriented fashion. It is
written by John Zelle for use with the book "Python Programming: An
Introduction to Computer Science" (Franklin, Beedle & Associates).
LICENSE: This is open-source software released under the terms of the
GPL (http://www.gnu.org/licenses/gpl.html).
PLATFORMS: The package is a wrapper around Tkinter and should run on
any platform where Tkinter is available.
INSTALLATION: Put this file somewhere where Python can see it.
OVERVIEW: There are two kinds of objects in the library. The GraphWin
class implements a window where drawing can be done and various
GraphicsObjects are provided that can be drawn into a GraphWin. As a
simple example, here is a complete program to draw a circle of radius
10 centered in a 100x100 window:
--------------------------------------------------------------------
from graphics import *
def main():
win = GraphWin("My Circle", 100, 100)
c = Circle(Point(50,50), 10)
c.draw(win)
win.getMouse() # Pause to view result
win.close() # Close window when done
main()
--------------------------------------------------------------------
GraphWin objects support coordinate transformation through the
setCoords method and pointer-based input through getMouse.
The library provides the following graphical objects:
Point
Line
Circle
Oval
Rectangle
Polygon
Text
Entry (for text-based input)
Image
Various attributes of graphical objects can be set such as
outline-color, fill-color and line-width. Graphical objects also
support moving and hiding for animation effects.
The library also provides a very simple class for pixel-based image
manipulation, Pixmap. A pixmap can be loaded from a file and displayed
using an Image object. Both getPixel and setPixel methods are provided
for manipulating the image.
DOCUMENTATION: For complete documentation, see Chapter 4 of "Python
Programming: An Introduction to Computer Science" by John Zelle,
published by Franklin, Beedle & Associates. Also see
http://mcsp.wartburg.edu/zelle/python for a quick reference"""
# Version 4.2 5/26/2011
# * Modified Image to allow multiple undraws like other GraphicsObjects
# Version 4.1 12/29/2009
# * Merged Pixmap and Image class. Old Pixmap removed, use Image.
# Version 4.0.1 10/08/2009
# * Modified the autoflush on GraphWin to default to True
# * Autoflush check on close, setBackground
# * Fixed getMouse to flush pending clicks at entry
# Version 4.0 08/2009
# * Reverted to non-threaded version. The advantages (robustness,
# efficiency, ability to use with other Tk code, etc.) outweigh
# the disadvantage that interactive use with IDLE is slightly more
# cumbersome.
# * Modified to run in either Python 2.x or 3.x (same file).
# * Added Image.getPixmap()
# * Added update() -- stand alone function to cause any pending
# graphics changes to display.
#
# Version 3.4 10/16/07
# Fixed GraphicsError to avoid "exploded" error messages.
# Version 3.3 8/8/06
# Added checkMouse method to GraphWin
# Version 3.2.3
# Fixed error in Polygon init spotted by Andrew Harrington
# Fixed improper threading in Image constructor
# Version 3.2.2 5/30/05
# Cleaned up handling of exceptions in Tk thread. The graphics package
# now raises an exception if attempt is made to communicate with
# a dead Tk thread.
# Version 3.2.1 5/22/05
# Added shutdown function for tk thread to eliminate race-condition
# error "chatter" when main thread terminates
# Renamed various private globals with _
# Version 3.2 5/4/05
# Added Pixmap object for simple image manipulation.
# Version 3.1 4/13/05
# Improved the Tk thread communication so that most Tk calls
# do not have to wait for synchonization with the Tk thread.
# (see _tkCall and _tkExec)
# Version 3.0 12/30/04
# Implemented Tk event loop in separate thread. Should now work
# interactively with IDLE. Undocumented autoflush feature is
# no longer necessary. Its default is now False (off). It may
# be removed in a future version.
# Better handling of errors regarding operations on windows that
# have been closed.
# Addition of an isClosed method to GraphWindow class.
# Version 2.2 8/26/04
# Fixed cloning bug reported by Joseph Oldham.
# Now implements deep copy of config info.
# Version 2.1 1/15/04
# Added autoflush option to GraphWin. When True (default) updates on
# the window are done after each action. This makes some graphics
# intensive programs sluggish. Turning off autoflush causes updates
# to happen during idle periods or when flush is called.
# Version 2.0
# Updated Documentation
# Made Polygon accept a list of Points in constructor
# Made all drawing functions call TK update for easier animations
# and to make the overall package work better with
# Python 2.3 and IDLE 1.0 under Windows (still some issues).
# Removed vestigial turtle graphics.
# Added ability to configure font for Entry objects (analogous to Text)
# Added setTextColor for Text as an alias of setFill
# Changed to class-style exceptions
# Fixed cloning of Text objects
# Version 1.6
# Fixed Entry so StringVar uses _root as master, solves weird
# interaction with shell in Idle
# Fixed bug in setCoords. X and Y coordinates can increase in
# "non-intuitive" direction.
# Tweaked wm_protocol so window is not resizable and kill box closes.
# Version 1.5
# Fixed bug in Entry. Can now define entry before creating a
# GraphWin. All GraphWins are now toplevel windows and share
# a fixed root (called _root).
# Version 1.4
# Fixed Garbage collection of Tkinter images bug.
# Added ability to set text atttributes.
# Added Entry boxes.
import time, os, sys
try: # import as appropriate for 2.x vs. 3.x
import tkinter as tk
except:
import Tkinter as tk
##########################################################################
# Module Exceptions
class GraphicsError(Exception):
"""Generic error class for graphics module exceptions."""
pass
OBJ_ALREADY_DRAWN = "Object currently drawn"
UNSUPPORTED_METHOD = "Object doesn't support operation"
BAD_OPTION = "Illegal option value"
DEAD_THREAD = "Graphics thread quit unexpectedly"
_root = tk.Tk()
_root.withdraw()
def update():
_root.update()
############################################################################
# Graphics classes start here
class GraphWin(tk.Canvas):
"""A GraphWin is a toplevel window for displaying graphics."""
def __init__(self, title="Graphics Window",
width=200, height=200, autoflush=True):
master = tk.Toplevel(_root)
master.protocol("WM_DELETE_WINDOW", self.close)
tk.Canvas.__init__(self, master, width=width, height=height)
self.master.title(title)
self.pack()
master.resizable(0,0)
self.foreground = "black"
self.items = []
self.mouseX = None
self.mouseY = None
self.bind("<Button-1>", self._onClick)
self.height = height
self.width = width
self.autoflush = autoflush
self._mouseCallback = None
self.trans = None
self.closed = False
master.lift()
if autoflush: _root.update()
def __checkOpen(self):
if self.closed:
raise GraphicsError("window is closed")
def setBackground(self, color):
"""Set background color of the window"""
self.__checkOpen()
self.config(bg=color)
self.__autoflush()
def setCoords(self, x1, y1, x2, y2):
"""Set coordinates of window to run from (x1,y1) in the
lower-left corner to (x2,y2) in the upper-right corner."""
self.trans = Transform(self.width, self.height, x1, y1, x2, y2)
def close(self):
"""Close the window"""
if self.closed: return
self.closed = True
self.master.destroy()
self.__autoflush()
def isClosed(self):
return self.closed
def isOpen(self):
return not self.closed
def __autoflush(self):
if self.autoflush:
_root.update()
def plot(self, x, y, color="black"):
"""Set pixel (x,y) to the given color"""
self.__checkOpen()
xs,ys = self.toScreen(x,y)
self.create_line(xs,ys,xs+1,ys, fill=color)
self.__autoflush()
def plotPixel(self, x, y, color="black"):
"""Set pixel raw (independent of window coordinates) pixel
(x,y) to color"""
self.__checkOpen()
self.create_line(x,y,x+1,y, fill=color)
self.__autoflush()
def flush(self):
"""Update drawing to the window"""
self.__checkOpen()
self.update_idletasks()
def getMouse(self):
"""Wait for mouse click and return Point object representing
the click"""
self.update() # flush any prior clicks
self.mouseX = None
self.mouseY = None
while self.mouseX == None or self.mouseY == None:
self.update()
if self.isClosed(): raise GraphicsError("getMouse in closed window")
time.sleep(.1) # give up thread
x,y = self.toWorld(self.mouseX, self.mouseY)
self.mouseX = None
self.mouseY = None
return Point(x,y)
def checkMouse(self):
"""Return last mouse click or None if mouse has
not been clicked since last call"""
if self.isClosed():
raise GraphicsError("checkMouse in closed window")
self.update()
if self.mouseX != None and self.mouseY != None:
x,y = self.toWorld(self.mouseX, self.mouseY)
self.mouseX = None
self.mouseY = None
return Point(x,y)
else:
return None
def getHeight(self):
"""Return the height of the window"""
return self.height
def getWidth(self):
"""Return the width of the window"""
return self.width
def toScreen(self, x, y):
trans = self.trans
if trans:
return self.trans.screen(x,y)
else:
return x,y
def toWorld(self, x, y):
trans = self.trans
if trans:
return self.trans.world(x,y)
else:
return x,y
def setMouseHandler(self, func):
self._mouseCallback = func
def _onClick(self, e):
self.mouseX = e.x
self.mouseY = e.y
if self._mouseCallback:
self._mouseCallback(Point(e.x, e.y))
class Transform:
"""Internal class for 2-D coordinate transformations"""
def __init__(self, w, h, xlow, ylow, xhigh, yhigh):
# w, h are width and height of window
# (xlow,ylow) coordinates of lower-left [raw (0,h-1)]
# (xhigh,yhigh) coordinates of upper-right [raw (w-1,0)]
xspan = (xhigh-xlow)
yspan = (yhigh-ylow)
self.xbase = xlow
self.ybase = yhigh
self.xscale = xspan/float(w-1)
self.yscale = yspan/float(h-1)
def screen(self,x,y):
# Returns x,y in screen (actually window) coordinates
xs = (x-self.xbase) / self.xscale
ys = (self.ybase-y) / self.yscale
return int(xs+0.5),int(ys+0.5)
def world(self,xs,ys):
# Returns xs,ys in world coordinates
x = xs*self.xscale + self.xbase
y = self.ybase - ys*self.yscale
return x,y
# Default values for various item configuration options. Only a subset of
# keys may be present in the configuration dictionary for a given item
DEFAULT_CONFIG = {"fill":"",
"outline":"black",
"width":"1",
"arrow":"none",
"text":"",
"justify":"center",
"font": ("helvetica", 12, "normal")}
class GraphicsObject:
"""Generic base class for all of the drawable objects"""
# A subclass of GraphicsObject should override _draw and
# and _move methods.
def __init__(self, options):
# options is a list of strings indicating which options are
# legal for this object.
# When an object is drawn, canvas is set to the GraphWin(canvas)
# object where it is drawn and id is the TK identifier of the
# drawn shape.
self.canvas = None
self.id = None
# config is the dictionary of configuration options for the widget.
config = {}
for option in options:
config[option] = DEFAULT_CONFIG[option]
self.config = config
def setFill(self, color):
"""Set interior color to color"""
self._reconfig("fill", color)
def setOutline(self, color):
"""Set outline color to color"""
self._reconfig("outline", color)
def setWidth(self, width):
"""Set line weight to width"""
self._reconfig("width", width)
def draw(self, graphwin):
"""Draw the object in graphwin, which should be a GraphWin
object. A GraphicsObject may only be drawn into one
window. Raises an error if attempt made to draw an object that
is already visible."""
if self.canvas and not self.canvas.isClosed(): raise GraphicsError(OBJ_ALREADY_DRAWN)
if graphwin.isClosed(): raise GraphicsError("Can't draw to closed window")
self.canvas = graphwin
self.id = self._draw(graphwin, self.config)
if graphwin.autoflush:
_root.update()
def undraw(self):
"""Undraw the object (i.e. hide it). Returns silently if the
object is not currently drawn."""
if not self.canvas: return
if not self.canvas.isClosed():
self.canvas.delete(self.id)
if self.canvas.autoflush:
_root.update()
self.canvas = None
self.id = None
def move(self, dx, dy):
"""move object dx units in x direction and dy units in y
direction"""
self._move(dx,dy)
canvas = self.canvas
if canvas and not canvas.isClosed():
trans = canvas.trans
if trans:
x = dx/ trans.xscale
y = -dy / trans.yscale
else:
x = dx
y = dy
self.canvas.move(self.id, x, y)
if canvas.autoflush:
_root.update()
def _reconfig(self, option, setting):
# Internal method for changing configuration of the object
# Raises an error if the option does not exist in the config
# dictionary for this object
if option not in self.config:
raise GraphicsError(UNSUPPORTED_METHOD)
options = self.config
options[option] = setting
if self.canvas and not self.canvas.isClosed():
self.canvas.itemconfig(self.id, options)
if self.canvas.autoflush:
_root.update()
def _draw(self, canvas, options):
"""draws appropriate figure on canvas with options provided
Returns Tk id of item drawn"""
pass # must override in subclass
def _move(self, dx, dy):
"""updates internal state of object to move it dx,dy units"""
pass # must override in subclass
class Point(GraphicsObject):
def __init__(self, x, y):
GraphicsObject.__init__(self, ["outline", "fill"])
self.setFill = self.setOutline
self.x = x
self.y = y
def _draw(self, canvas, options):
x,y = canvas.toScreen(self.x,self.y)
return canvas.create_rectangle(x,y,x+1,y+1,options)
def _move(self, dx, dy):
self.x = self.x + dx
self.y = self.y + dy
def clone(self):
other = Point(self.x,self.y)
other.config = self.config.copy()
return other
def getX(self): return self.x
def getY(self): return self.y
class _BBox(GraphicsObject):
# Internal base class for objects represented by bounding box
# (opposite corners) Line segment is a degenerate case.
def __init__(self, p1, p2, options=["outline","width","fill"]):
GraphicsObject.__init__(self, options)
self.p1 = p1.clone()
self.p2 = p2.clone()
def _move(self, dx, dy):
self.p1.x = self.p1.x + dx
self.p1.y = self.p1.y + dy
self.p2.x = self.p2.x + dx
self.p2.y = self.p2.y + dy
def getP1(self): return self.p1.clone()
def getP2(self): return self.p2.clone()
def getCenter(self):
p1 = self.p1
p2 = self.p2
return Point((p1.x+p2.x)/2.0, (p1.y+p2.y)/2.0)
class Rectangle(_BBox):
def __init__(self, p1, p2):
_BBox.__init__(self, p1, p2)
def _draw(self, canvas, options):
p1 = self.p1
p2 = self.p2
x1,y1 = canvas.toScreen(p1.x,p1.y)
x2,y2 = canvas.toScreen(p2.x,p2.y)
return canvas.create_rectangle(x1,y1,x2,y2,options)
def clone(self):
other = Rectangle(self.p1, self.p2)
other.config = self.config.copy()
return other
class Oval(_BBox):
def __init__(self, p1, p2):
_BBox.__init__(self, p1, p2)
def clone(self):
other = Oval(self.p1, self.p2)
other.config = self.config.copy()
return other
def _draw(self, canvas, options):
p1 = self.p1
p2 = self.p2
x1,y1 = canvas.toScreen(p1.x,p1.y)
x2,y2 = canvas.toScreen(p2.x,p2.y)
return canvas.create_oval(x1,y1,x2,y2,options)
class Circle(Oval):
def __init__(self, center, radius):
p1 = Point(center.x-radius, center.y-radius)
p2 = Point(center.x+radius, center.y+radius)
Oval.__init__(self, p1, p2)
self.radius = radius
def clone(self):
other = Circle(self.getCenter(), self.radius)
other.config = self.config.copy()
return other
def getRadius(self):
return self.radius
class Line(_BBox):
def __init__(self, p1, p2):
_BBox.__init__(self, p1, p2, ["arrow","fill","width"])
self.setFill(DEFAULT_CONFIG['outline'])
self.setOutline = self.setFill
def clone(self):
other = Line(self.p1, self.p2)
other.config = self.config.copy()
return other
def _draw(self, canvas, options):
p1 = self.p1
p2 = self.p2
x1,y1 = canvas.toScreen(p1.x,p1.y)
x2,y2 = canvas.toScreen(p2.x,p2.y)
return canvas.create_line(x1,y1,x2,y2,options)
def setArrow(self, option):
if not option in ["first","last","both","none"]:
raise GraphicsError(BAD_OPTION)
self._reconfig("arrow", option)
class Polygon(GraphicsObject):
def __init__(self, *points):
# if points passed as a list, extract it
if len(points) == 1 and type(points[0]) == type([]):
points = points[0]
self.points = list(map(Point.clone, points))
GraphicsObject.__init__(self, ["outline", "width", "fill"])
def clone(self):
other = Polygon(*self.points)
other.config = self.config.copy()
return other
def getPoints(self):
return list(map(Point.clone, self.points))
def _move(self, dx, dy):
for p in self.points:
p.move(dx,dy)
def _draw(self, canvas, options):
args = [canvas]
for p in self.points:
x,y = canvas.toScreen(p.x,p.y)
args.append(x)
args.append(y)
args.append(options)
return GraphWin.create_polygon(*args)
class Text(GraphicsObject):
def __init__(self, p, text):
GraphicsObject.__init__(self, ["justify","fill","text","font"])
self.setText(text)
self.anchor = p.clone()
self.setFill(DEFAULT_CONFIG['outline'])
self.setOutline = self.setFill
def _draw(self, canvas, options):
p = self.anchor
x,y = canvas.toScreen(p.x,p.y)
return canvas.create_text(x,y,options)
def _move(self, dx, dy):
self.anchor.move(dx,dy)
def clone(self):
other = Text(self.anchor, self.config['text'])
other.config = self.config.copy()
return other
def setText(self,text):
self._reconfig("text", text)
def getText(self):
return self.config["text"]
def getAnchor(self):
return self.anchor.clone()
def setFace(self, face):
if face in ['helvetica','arial','courier','times roman']:
f,s,b = self.config['font']
self._reconfig("font",(face,s,b))
else:
raise GraphicsError(BAD_OPTION)
def setSize(self, size):
if 5 <= size <= 36:
f,s,b = self.config['font']
self._reconfig("font", (f,size,b))
else:
raise GraphicsError(BAD_OPTION)
def setStyle(self, style):
if style in ['bold','normal','italic', 'bold italic']:
f,s,b = self.config['font']
self._reconfig("font", (f,s,style))
else:
raise GraphicsError(BAD_OPTION)
def setTextColor(self, color):
self.setFill(color)
class Entry(GraphicsObject):
def __init__(self, p, width):
GraphicsObject.__init__(self, [])
self.anchor = p.clone()
#print self.anchor
self.width = width
self.text = tk.StringVar(_root)
self.text.set("")
self.fill = "gray"
self.color = "black"
self.font = DEFAULT_CONFIG['font']
self.entry = None
def _draw(self, canvas, options):
p = self.anchor
x,y = canvas.toScreen(p.x,p.y)
frm = tk.Frame(canvas.master)
self.entry = tk.Entry(frm,
width=self.width,
textvariable=self.text,
bg = self.fill,
fg = self.color,
font=self.font)
self.entry.pack()
#self.setFill(self.fill)
return canvas.create_window(x,y,window=frm)
def getText(self):
return self.text.get()
def _move(self, dx, dy):
self.anchor.move(dx,dy)
def getAnchor(self):
return self.anchor.clone()
def clone(self):
other = Entry(self.anchor, self.width)
other.config = self.config.copy()
other.text = tk.StringVar()
other.text.set(self.text.get())
other.fill = self.fill
return other
def setText(self, t):
self.text.set(t)
def setFill(self, color):
self.fill = color
if self.entry:
self.entry.config(bg=color)
def _setFontComponent(self, which, value):
font = list(self.font)
font[which] = value
self.font = tuple(font)
if self.entry:
self.entry.config(font=self.font)
def setFace(self, face):
if face in ['helvetica','arial','courier','times roman']:
self._setFontComponent(0, face)
else:
raise GraphicsError(BAD_OPTION)
def setSize(self, size):
if 5 <= size <= 36:
self._setFontComponent(1,size)
else:
raise GraphicsError(BAD_OPTION)
def setStyle(self, style):
if style in ['bold','normal','italic', 'bold italic']:
self._setFontComponent(2,style)
else:
raise GraphicsError(BAD_OPTION)
def setTextColor(self, color):
self.color=color
if self.entry:
self.entry.config(fg=color)
class Image(GraphicsObject):
idCount = 0
imageCache = {} # tk photoimages go here to avoid GC while drawn
def __init__(self, p, *pixmap):
GraphicsObject.__init__(self, [])
self.anchor = p.clone()
self.imageId = Image.idCount
Image.idCount = Image.idCount + 1
if len(pixmap) == 1: # file name provided
self.img = tk.PhotoImage(file=pixmap[0], master=_root)
else: # width and height provided
width, height = pixmap
self.img = tk.PhotoImage(master=_root, width=width, height=height)
def _draw(self, canvas, options):
p = self.anchor
x,y = canvas.toScreen(p.x,p.y)
self.imageCache[self.imageId] = self.img # save a reference
return canvas.create_image(x,y,image=self.img)
def _move(self, dx, dy):
self.anchor.move(dx,dy)
def undraw(self):
try:
del self.imageCache[self.imageId] # allow gc of tk photoimage
except KeyError:
pass
GraphicsObject.undraw(self)
def getAnchor(self):
return self.anchor.clone()
def clone(self):
other = Image(Point(0,0), 0, 0)
other.img = self.img.copy()
other.anchor = self.anchor.clone()
other.config = self.config.copy()
return other
def getWidth(self):
"""Returns the width of the image in pixels"""
return self.img.width()
def getHeight(self):
"""Returns the height of the image in pixels"""
return self.img.height()
def getPixel(self, x, y):
"""Returns a list [r,g,b] with the RGB color values for pixel (x,y)
r,g,b are in range(256)
"""
value = self.img.get(x,y)
if type(value) == type(0):
return [value, value, value]
else:
return list(map(int, value.split()))
def setPixel(self, x, y, color):
"""Sets pixel (x,y) to the given color
"""
self.img.put("{" + color +"}", (x, y))
def save(self, filename):
"""Saves the pixmap image to filename.
The format for the save image is determined from the filname extension.
"""
path, name = os.path.split(filename)
ext = name.split(".")[-1]
self.img.write( filename, format=ext)
def color_rgb(r,g,b):
"""r,g,b are intensities of red, green, and blue in range(256)
Returns color specifier string for the resulting color"""
return "#%02x%02x%02x" % (r,g,b)
def test():
win = GraphWin()
win.setCoords(0,0,10,10)
t = Text(Point(5,5), "Centered Text")
t.draw(win)
p = Polygon(Point(1,1), Point(5,3), Point(2,7))
p.draw(win)
e = Entry(Point(5,6), 10)
e.draw(win)
win.getMouse()
p.setFill("red")
p.setOutline("blue")
p.setWidth(2)
s = ""
for pt in p.getPoints():
s = s + "(%0.1f,%0.1f) " % (pt.getX(), pt.getY())
t.setText(e.getText())
e.setFill("green")
e.setText("Spam!")
e.move(2,0)
win.getMouse()
p.move(2,3)
s = ""
for pt in p.getPoints():
s = s + "(%0.1f,%0.1f) " % (pt.getX(), pt.getY())
t.setText(s)
win.getMouse()
p.undraw()
e.undraw()
t.setStyle("bold")
win.getMouse()
t.setStyle("normal")
win.getMouse()
t.setStyle("italic")
win.getMouse()
t.setStyle("bold italic")
win.getMouse()
t.setSize(14)
win.getMouse()
t.setFace("arial")
t.setSize(20)
win.getMouse()
win.close()
if __name__ == "__main__":
test()
| [
[
8,
0,
0.0354,
0.0675,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1665,
0.0011,
0,
0.66,
0.037,
654,
0,
3,
0,
0,
654,
0,
0
],
[
7,
0,
0.1704,
0.0045,
0,
0.66,... | [
"\"\"\"Simple object oriented graphics library \n\nThe library is designed to make it very easy for novice programmers to\nexperiment with computer graphics in an object oriented fashion. It is\nwritten by John Zelle for use with the book \"Python Programming: An\nIntroduction to Computer Science\" (Franklin, Beed... |
'''
Created on 2012-10-15
@author: wangxin
'''
import sys
import os
import re
import time
import md5
import random
import thread
from sets import Set
import socket
import traceback
from Tkinter import *
#record the path
#action:
# DELETE=0
# INSERT=1
# SUBSTITUTION=2
# SAMEVALUE=3
class Path:
def __init__(self, i, j, action):
self.i=i
self.j=j
self.action=action
def get_i_index(self):
return self.i
def get_j_index(self):
return self.j
def get_action_value(self):
return self.action
class Edit_Distance:
def __init__(self,strA,strB,cdel,cins,csub,CHAR_WIDTH):
self.strA=strA
self.strB=strB
self.cdel=cdel
self.cins=cins
self.csub=csub
self.CHAR_WIDTH=CHAR_WIDTH
self.is_eidted=False
#comput the distance of two strings
#cdel: the cost of deleting
#cins: the cost of inserting
#csub: the cost of substitution
def edit_distance(self,strA,strB,cdel,cins,csub):
m=len(strA)
n=len(strB)
self.dist= [[0 for col in range(n+1)] for row in range(m+1)]
self.backtrack_dist=[[0 for col in range(n+1)] for row in range(m+1)] #for backtrack matrix
#initial the array
self.dist[0][0]=0
self.backtrack_dist[0][0]='0'
i=1
while i<=n:
self.dist[0][i]=self.dist[0][i-1]+cins
self.backtrack_dist[0][i]='-'
i=i+1
i=1
while i<=m:
self.dist[i][0]=self.dist[i-1][0]+cdel
self.backtrack_dist[i][0]='|'
i=i+1
j=1
i=1
while j<=n:
while i<=m:
if strA[i-1]==strB[j-1]: #D[i][j]=min(D[i-1][j-1],D[i-1][j]+1,D[i][j-1]+1);
self.dist[i][j]=min(self.dist[i-1][j-1],self.dist[i-1][j]+cdel,self.dist[i][j-1]+cins)
#compute backtrack matrix
if self.dist[i][j] == self.dist[i-1][j-1] :
self.backtrack_dist[i][j]='\\'
elif self.dist[i][j] == self.dist[i-1][j]+cdel :
self.backtrack_dist[i][j]='|'
else:
self.backtrack_dist[i][j]='-'
#print self.dist[i][j]
else:
self.dist[i][j]=min(self.dist[i-1][j-1]+csub,self.dist[i-1][j]+cdel,self.dist[i][j-1]+cins)
#compute backtrack matrix
if self.dist[i][j] == self.dist[i-1][j-1]+csub :
self.backtrack_dist[i][j]='\\'
elif self.dist[i][j] == self.dist[i-1][j]+cdel :
self.backtrack_dist[i][j]='|'
else:
self.backtrack_dist[i][j]='-'
#print self.dist[i][j]
i=i+1
i=1
j=j+1
#return self.dist
#return the fixed width string
def fiexed_width(self,onestr):
tmplen=len(str(onestr))
nullstr=""
while tmplen<=self.CHAR_WIDTH:
nullstr=nullstr+" "
tmplen=tmplen+1
onestr=nullstr+str(onestr)
# if len(onestr)>self.CHAR_WIDTH:
# onestr=onestr[0:self.CHAR_WIDTH-1]
return onestr
def get_matrix_strvalue(self,ary_matrix,strA,strB):
m=len(strA)
n=len(strB)
#print "valuse:"+str(ary_matrix[2][3])
#get the first line value
tmpstr=""
tmpstr=tmpstr+self.fiexed_width("")+self.fiexed_width("")
i=0
while i<n:
tmpstr=tmpstr+self.fiexed_width(strB[i])
i=i+1
tmpstr=tmpstr+"\n"
print "m="+str(m)
print "n="+str(n)
print "tmpstr="+str(tmpstr)
j=0
i=0
while j<=m:
if j==0: #second line
tmpstr=tmpstr+self.fiexed_width("")
else:
tmpstr=tmpstr+self.fiexed_width(strA[j-1])
print strA[j-1]
i=0
while i<=n:
tmpstr=tmpstr+self.fiexed_width(str(ary_matrix[j][i]))
i=i+1
tmpstr=tmpstr+"\n"
j=j+1
return tmpstr
#compute the alignment of two strings
def get_alignment_value(self,ary_matrix,strA,strB):
m=len(strA)
n=len(strB)
#action value
DELETE=0
INSERT=1
SUBSTITUTION=2
SAMEVALUE=3
#declare one array to store the actions
self.action_ary=[]
i=m
j=n
#self.action_ary[0]=Path(0,0,SAMEVALUE)
print "dist[m][n]:"+str(self.dist[m][n])
while i!=0 and j!=0:
tmp1=tmp2=tmp3=1234567 #set big value
if i-1>=0 and j-1>=0:
tmp1=self.dist[i-1][j-1]
if i-1>=0:
tmp2=self.dist[i-1][j]
if j-1>=0:
tmp3=self.dist[i][j-1]
minv=min(tmp1,tmp2,tmp3)
curv=self.dist[i][j]
if minv==tmp1:
if curv==minv:
self.action_ary.append(Path(i,j,SAMEVALUE))
print "same:"+str(i)+" "+str(j)
elif curv==minv+2:
self.action_ary.append(Path(i,j,SUBSTITUTION))
print "sub:"+str(i)+" "+str(j)
i=i-1
j=j-1
elif minv==tmp2:
self.action_ary.append(Path(i,j,DELETE))
print "delete:"+str(i)+" "+str(j)
i=i-1
elif minv==tmp3:
self.action_ary.append(Path(i,j,INSERT))
print "insert:"+str(i)+" "+str(j)
j=j-1
#compute the alignment string result
tmpstr=""
oriStr=""
destStr=""
sameStr=""
tmpstr=tmpstr+self.fiexed_width("")
i=len(self.action_ary)-1
print "len:"+str(i)
is_append=False
while i>=0:
onePath=self.action_ary[i]
print "i:"+str(i)
print "onePath:"+str(onePath.get_i_index())+" "+str(onePath.get_j_index())+" "+str(onePath.get_action_value())
if onePath.get_action_value()==DELETE:
print "delete"
if onePath.get_i_index()==len(strA):
oriStr=oriStr+self.fiexed_width(strA[onePath.get_i_index()-1])
else:
oriStr=oriStr+self.fiexed_width("-")
sameStr=sameStr+self.fiexed_width(" ")
elif onePath.get_action_value()==INSERT:
print "insert"
oriStr=oriStr+self.fiexed_width("-")
#destStr=destStr+self.fiexed_width(strB[onePath.get_j_index()-1])
sameStr=sameStr+self.fiexed_width(" ")
elif onePath.get_action_value()==SUBSTITUTION:
print "sub"
oriStr=oriStr+self.fiexed_width(strA[onePath.get_i_index()-1])
#destStr=destStr+self.fiexed_width(strB[onePath.get_j_index()-1])
sameStr=sameStr+self.fiexed_width(" ")
elif onePath.get_action_value()==SAMEVALUE:
print "same"
oriStr=oriStr+self.fiexed_width(str(strA[onePath.get_i_index()-1]))
#destStr=destStr+self.fiexed_width(str(strB[onePath.get_j_index()-1]))
sameStr=sameStr+self.fiexed_width("|")
if onePath.get_j_index()==len(strB) and is_append==False:
destStr=destStr+self.fiexed_width(strB[onePath.get_j_index()-1])
is_append=True
elif is_append==False:
destStr=destStr+self.fiexed_width(strB[onePath.get_j_index()-1])
else:
destStr=destStr+self.fiexed_width("-")
i=i-1
print "oristr:"+oriStr
print "destStr:"+destStr
print "same:"+sameStr
tmpstr=tmpstr+oriStr+"\n"
tmpstr=tmpstr+self.fiexed_width("")+sameStr+"\n"
tmpstr=tmpstr+self.fiexed_width("")+destStr+"\n"
return tmpstr
#return full edit distance matrix valuse
def get_full_edit_distance_matrix_result(self):
if self.is_eidted==False:
self.edit_distance(self.strA,self.strB,self.cdel,self.cins,self.csub)
self.is_eidted=True
return "full edit distance matrix:\n"+self.get_matrix_strvalue(self.dist,self.strA,self.strB)+"\n"
#return full edit distance matrix valuse
def get_backtrack_matrix_result(self):
if self.is_eidted==False:
self.edit_distance(self.strA,self.strB,self.cdel,self.cins,self.csub)
self.is_eidted=True
return "backtrack matrix:\n"+self.get_matrix_strvalue(self.backtrack_dist,self.strA,self.strB)+"\n"
#return full edit distance matrix valuse
def get_alignment_result(self):
if self.is_eidted==False:
self.edit_distance(self.strA,self.strB,self.cdel,self.cins,self.csub)
self.is_eidted=True
return "alignment:\n"+self.get_alignment_value(self.dist,self.strA,self.strB)+"\n"
def get_edit_distance(self):
return "\n edit distance:"+str(self.dist[len(self.strA)][len(self.strB)])+"\n"
#global variable
def btn_compute(strA,strB,cdel,cins,csub,CheckVar1,CheckVar2,CheckVar3,text):
print "strA:"+strA.get()
print "strB:"+strB.get()
print "cdel:"+str(cdel.get())
print "cins:"+str(cins.get())
print "csub:"+str(csub.get())
print "CheckVar1:"+str(CheckVar1.get())
print "CheckVar2:"+str(CheckVar2.get())
print "CheckVar3:"+str(CheckVar3.get())
edit_dist=Edit_Distance(strA.get(),strB.get(),cdel.get(),cins.get(),csub.get(),5)
#matrix_strvalue=edit_dist.get_backtrack_matrix_result()
if CheckVar1.get()==1:
full_matrix_strvalue=edit_dist.get_full_edit_distance_matrix_result()
text.insert(INSERT, full_matrix_strvalue)
if CheckVar2.get()==1:
backtrack_matrix_strvalue=edit_dist.get_backtrack_matrix_result()
text.insert(INSERT, backtrack_matrix_strvalue)
if CheckVar3.get()==1:
alignment_matrix_strvalue=edit_dist.get_alignment_result()
text.insert(INSERT, alignment_matrix_strvalue)
edit_distance=edit_dist.get_edit_distance()
text.insert(INSERT,edit_distance)
if __name__ == '__main__':
#ary= [[0 for col in range(5)] for row in range(3)]
# strA="compare"
# strB="computer"
#
#
# m=len(strA)
# n=len(strB)
# edit_dist=Edit_Distance(strA,strB,1,1,2,5)
# #matrix_strvalue=edit_dist.get_backtrack_matrix_result()
# matrix_strvalue=edit_dist.get_alignment_result()
# print len(matrix_strvalue)
matrix_strvalue=""
root = Tk()
# w = Label(root, text="Hello, world!")
# t = Text(root,width=20,height=10)
# t.insert(1.0,'56789\n')
# t.insert(3.2,'56789')
# t.pack() ,width=m+2,height=(n+2)*5
frame= Frame(height = 2000,width = 600,bg = 'red')
scrollbar = Scrollbar(frame)
scrollbar.pack( side = RIGHT, fill=Y )
text = Text(frame,yscrollcommand = scrollbar.set)
text.insert(INSERT, matrix_strvalue)
#text.insert(END, "Bye Bye.....")
text.pack(side = LEFT, fill = BOTH )
scrollbar.config( command = text.yview )
frame.pack()
fm = []
#fram 1
fm.append(Frame(height = 20,width = 400,bg = 'red'))
Label(fm[0], text=" first string:").pack(side = LEFT)
strA= StringVar()
Entry(fm[0] ,textvariable =strA).pack(side = RIGHT)
#fram 2
fm.append(Frame(height = 20,width = 400,bg = 'red'))
Label(fm[1], text="second string:").pack(side = LEFT)
strB= StringVar()
Entry(fm[1] ,textvariable =strB).pack(side = RIGHT)
#fram 3
fm.append(Frame(height = 20,width = 400))
cdel=IntVar()
cins=IntVar()
csub=IntVar()
Label(fm[2], text="cdel:").pack(side = LEFT)
Scale(fm[2],from_ = 0, to = 50, resolution = 1, orient = HORIZONTAL,variable = cdel).pack(side = RIGHT)
#fram 4
fm.append(Frame(height = 20,width = 400))
Label(fm[3], text="cins:").pack(side = LEFT)
Scale(fm[3],from_ = 0, to = 50, resolution = 1, orient = HORIZONTAL,variable = cins).pack(side = RIGHT)
#fram 5
fm.append(Frame(height = 20,width = 400))
Label(fm[4], text="csub:").pack(side = LEFT)
Scale(fm[4],from_ = 0, to = 50, resolution = 1, orient = HORIZONTAL,variable = csub).pack(side = RIGHT)
#fram 6
fm.append(Frame(height = 20,width = 400))
CheckVar1 = IntVar()
CheckVar2 = IntVar()
CheckVar3 =IntVar()
C1 = Checkbutton(fm[5], text = "distance matrix", variable = CheckVar1, \
onvalue = 1, offvalue = 0, height=5, \
width = 20)
C2 = Checkbutton(fm[5], text = "backtrack matrix", variable = CheckVar2, \
onvalue = 1, offvalue = 0, height=5, \
width = 20)
C3 = Checkbutton(fm[5], text = "alignment", variable = CheckVar3, \
onvalue = 1, offvalue = 0, height=5, \
width = 20)
C1.pack(side = LEFT)
C2.pack(side = LEFT)
C3.pack(side = LEFT)
#fram 7
fm.append(Frame(height = 20,width = 400))
Button(fm[6],text = 'Calculate ',command =lambda : btn_compute(strA,strB,cdel,cins,csub,CheckVar1,CheckVar2,CheckVar3,text)).pack()
#pack the frame
fm[0].pack()
fm[1].pack()
fm[2].pack()
fm[3].pack()
fm[4].pack()
fm[5].pack()
fm[6].pack()
root.mainloop()
| [
[
8,
0,
0.008,
0.0134,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0187,
0.0027,
0,
0.66,
0.0667,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0214,
0.0027,
0,
0.66,... | [
"'''\nCreated on 2012-10-15\n\n@author: wangxin\n'''",
"import sys",
"import os",
"import re",
"import time",
"import md5",
"import random",
"import thread",
"from sets import Set",
"import socket",
"import traceback",
"from Tkinter import *",
"class Path:\n def __init__(self, i, j, actio... |
import sys
import os
import re
import time
import md5
import random
import thread
from sets import Set
import socket
import traceback
from Tkinter import *
#record the path
#action:
# DELETE=0
# INSERT=1
# SUBSTITUTION=2
# SAMEVALUE=3
class Path:
def __init__(self, i, j, action):
self.i=i
self.j=j
self.action=action
def get_i_index(self):
return self.i
def get_j_index(self):
return self.j
def get_action_value(self):
return self.action
class Edit_Distance:
def __init__(self,strA,strB,cdel,cins,csub,CHAR_WIDTH):
self.strA=strA
self.strB=strB
self.cdel=cdel
self.cins=cins
self.csub=csub
self.CHAR_WIDTH=CHAR_WIDTH
self.is_eidted=False
#comput the distance of two strings
#cdel: the cost of deleting
#cins: the cost of inserting
#csub: the cost of substitution
def edit_distance(self,strA,strB,cdel,cins,csub):
m=len(strA)
n=len(strB)
self.dist= [[0 for col in range(n+1)] for row in range(m+1)]
self.backtrack_dist=[[0 for col in range(n+1)] for row in range(m+1)] #for backtrack matrix
#initial the array
self.dist[0][0]=0
self.backtrack_dist[0][0]='0'
i=1
while i<=n:
self.dist[0][i]=self.dist[0][i-1]+cins
self.backtrack_dist[0][i]='-'
i=i+1
i=1
while i<=m:
self.dist[i][0]=self.dist[i-1][0]+cdel
self.backtrack_dist[i][0]='|'
i=i+1
j=1
i=1
while j<=n:
while i<=m:
if strA[i-1]==strB[j-1]: #D[i][j]=min(D[i-1][j-1],D[i-1][j]+1,D[i][j-1]+1);
self.dist[i][j]=min(self.dist[i-1][j-1],self.dist[i-1][j]+cdel,self.dist[i][j-1]+cins)
#compute backtrack matrix
if self.dist[i][j] == self.dist[i-1][j-1] :
self.backtrack_dist[i][j]='\\'
elif self.dist[i][j] == self.dist[i-1][j]+cdel :
self.backtrack_dist[i][j]='|'
else:
self.backtrack_dist[i][j]='-'
#print self.dist[i][j]
else:
self.dist[i][j]=min(self.dist[i-1][j-1]+csub,self.dist[i-1][j]+cdel,self.dist[i][j-1]+cins)
#compute backtrack matrix
if self.dist[i][j] == self.dist[i-1][j-1]+csub :
self.backtrack_dist[i][j]='\\'
elif self.dist[i][j] == self.dist[i-1][j]+cdel :
self.backtrack_dist[i][j]='|'
else:
self.backtrack_dist[i][j]='-'
#print self.dist[i][j]
i=i+1
i=1
j=j+1
#return self.dist
#return the fixed width string
def fiexed_width(self,onestr):
tmplen=len(str(onestr))
nullstr=""
while tmplen<=self.CHAR_WIDTH:
nullstr=nullstr+" "
tmplen=tmplen+1
onestr=nullstr+str(onestr)
# if len(onestr)>self.CHAR_WIDTH:
# onestr=onestr[0:self.CHAR_WIDTH-1]
return onestr
def get_matrix_strvalue(self,ary_matrix,strA,strB):
m=len(strA)
n=len(strB)
#print "valuse:"+str(ary_matrix[2][3])
#get the first line value
tmpstr=""
tmpstr=tmpstr+self.fiexed_width("")+self.fiexed_width("")
i=0
while i<n:
tmpstr=tmpstr+self.fiexed_width(strB[i])
i=i+1
tmpstr=tmpstr+"\n"
# print "m="+str(m)
# print "n="+str(n)
# print "tmpstr="+str(tmpstr)
j=0
i=0
while j<=m:
if j==0: #second line
tmpstr=tmpstr+self.fiexed_width("")
else:
tmpstr=tmpstr+self.fiexed_width(strA[j-1])
print strA[j-1]
i=0
while i<=n:
tmpstr=tmpstr+self.fiexed_width(str(ary_matrix[j][i]))
i=i+1
tmpstr=tmpstr+"\n"
j=j+1
return tmpstr
#compute the alignment of two strings
def get_alignment_value(self,ary_matrix,strA,strB):
m=len(strA)
n=len(strB)
#action value
DELETE=0
INSERT=1
SUBSTITUTION=2
SAMEVALUE=3
#declare one array to store the actions
self.action_ary=[]
i=m
j=n
#self.action_ary[0]=Path(0,0,SAMEVALUE)
print "dist[m][n]:"+str(self.dist[m][n])
while i!=0 and j!=0:
tmp1=tmp2=tmp3=999999999 #set big value
if i-1>=0 and j-1>=0:
tmp1=self.dist[i-1][j-1]
if i-1>=0:
tmp2=self.dist[i-1][j]
if j-1>=0:
tmp3=self.dist[i][j-1]
minv=min(tmp1,tmp2,tmp3)
curv=self.dist[i][j]
if minv==tmp1:
if curv==minv:
self.action_ary.append(Path(i,j,SAMEVALUE))
# print "same:"+str(i)+" "+str(j)
elif curv==minv+2:
self.action_ary.append(Path(i,j,SUBSTITUTION))
# print "sub:"+str(i)+" "+str(j)
i=i-1
j=j-1
elif minv==tmp2:
self.action_ary.append(Path(i,j,DELETE))
# print "delete:"+str(i)+" "+str(j)
i=i-1
elif minv==tmp3:
self.action_ary.append(Path(i,j,INSERT))
# print "insert:"+str(i)+" "+str(j)
j=j-1
#compute the alignment string result
tmpstr=""
oriStr=""
destStr=""
sameStr=""
tmpstr=tmpstr+self.fiexed_width("")
i=len(self.action_ary)-1
# print "len:"+str(i)
is_append=False
while i>=0:
onePath=self.action_ary[i]
# print "i:"+str(i)
# print "onePath:"+str(onePath.get_i_index())+" "+str(onePath.get_j_index())+" "+str(onePath.get_action_value())
if onePath.get_action_value()==DELETE:
# print "delete"
if onePath.get_i_index()==len(strA):
oriStr=oriStr+self.fiexed_width(strA[onePath.get_i_index()-1])
else:
oriStr=oriStr+self.fiexed_width("-")
sameStr=sameStr+self.fiexed_width(" ")
elif onePath.get_action_value()==INSERT:
# print "insert"
oriStr=oriStr+self.fiexed_width("-")
#destStr=destStr+self.fiexed_width(strB[onePath.get_j_index()-1])
sameStr=sameStr+self.fiexed_width(" ")
elif onePath.get_action_value()==SUBSTITUTION:
# print "sub"
oriStr=oriStr+self.fiexed_width(strA[onePath.get_i_index()-1])
#destStr=destStr+self.fiexed_width(strB[onePath.get_j_index()-1])
sameStr=sameStr+self.fiexed_width(" ")
elif onePath.get_action_value()==SAMEVALUE:
# print "same"
oriStr=oriStr+self.fiexed_width(str(strA[onePath.get_i_index()-1]))
#destStr=destStr+self.fiexed_width(str(strB[onePath.get_j_index()-1]))
sameStr=sameStr+self.fiexed_width("|")
if onePath.get_j_index()==len(strB) and is_append==False:
destStr=destStr+self.fiexed_width(strB[onePath.get_j_index()-1])
is_append=True
elif is_append==False:
destStr=destStr+self.fiexed_width(strB[onePath.get_j_index()-1])
else:
destStr=destStr+self.fiexed_width("-")
i=i-1
# print "oristr:"+oriStr
# print "destStr:"+destStr
# print "same:"+sameStr
tmpstr=tmpstr+oriStr+"\n"
tmpstr=tmpstr+self.fiexed_width("")+sameStr+"\n"
tmpstr=tmpstr+self.fiexed_width("")+destStr+"\n"
return tmpstr
#return full edit distance matrix valuse
def get_full_edit_distance_matrix_result(self):
if self.is_eidted==False:
self.edit_distance(self.strA,self.strB,self.cdel,self.cins,self.csub)
self.is_eidted=True
return "full edit distance matrix:\n"+self.get_matrix_strvalue(self.dist,self.strA,self.strB)+"\n"
#return full edit distance matrix valuse
def get_backtrack_matrix_result(self):
if self.is_eidted==False:
self.edit_distance(self.strA,self.strB,self.cdel,self.cins,self.csub)
self.is_eidted=True
return "backtrack matrix:\n"+self.get_matrix_strvalue(self.backtrack_dist,self.strA,self.strB)+"\n"
#return full edit distance matrix valuse
def get_alignment_result(self):
if self.is_eidted==False:
self.edit_distance(self.strA,self.strB,self.cdel,self.cins,self.csub)
self.is_eidted=True
return "alignment:\n"+self.get_alignment_value(self.dist,self.strA,self.strB)+"\n"
def get_edit_distance(self):
return "\n edit distance:"+str(self.dist[len(self.strA)][len(self.strB)])+"\n"
#global variable
def btn_compute(strA,strB,cdel,cins,csub,CheckVar1,CheckVar2,CheckVar3,text):
# print "strA:"+strA.get()
# print "strB:"+strB.get()
# print "cdel:"+str(cdel.get())
# print "cins:"+str(cins.get())
# print "csub:"+str(csub.get())
# print "CheckVar1:"+str(CheckVar1.get())
# print "CheckVar2:"+str(CheckVar2.get())
# print "CheckVar3:"+str(CheckVar3.get())
edit_dist=Edit_Distance(strA.get(),strB.get(),cdel.get(),cins.get(),csub.get(),5)
#matrix_strvalue=edit_dist.get_backtrack_matrix_result()
if CheckVar1.get()==1:
full_matrix_strvalue=edit_dist.get_full_edit_distance_matrix_result()
text.insert(INSERT, full_matrix_strvalue)
if CheckVar2.get()==1:
backtrack_matrix_strvalue=edit_dist.get_backtrack_matrix_result()
text.insert(INSERT, backtrack_matrix_strvalue)
if CheckVar3.get()==1:
alignment_matrix_strvalue=edit_dist.get_alignment_result()
text.insert(INSERT, alignment_matrix_strvalue)
edit_distance=edit_dist.get_edit_distance()
text.insert(INSERT,edit_distance)
if __name__ == '__main__':
#ary= [[0 for col in range(5)] for row in range(3)]
# strA="compare"
# strB="computer"
#
#
# m=len(strA)
# n=len(strB)
# edit_dist=Edit_Distance(strA,strB,1,1,2,5)
# #matrix_strvalue=edit_dist.get_backtrack_matrix_result()
# matrix_strvalue=edit_dist.get_alignment_result()
# print len(matrix_strvalue)
matrix_strvalue=""
root = Tk()
# w = Label(root, text="Hello, world!")
# t = Text(root,width=20,height=10)
# t.insert(1.0,'56789\n')
# t.insert(3.2,'56789')
# t.pack() ,width=m+2,height=(n+2)*5
frame= Frame(height = 2000,width = 600,bg = 'red')
scrollbar = Scrollbar(frame)
scrollbar.pack( side = RIGHT, fill=Y )
text = Text(frame,yscrollcommand = scrollbar.set)
text.insert(INSERT, matrix_strvalue)
text.pack(side = LEFT, fill = BOTH )
scrollbar.config( command = text.yview )
frame.pack()
fm = []
#fram 1
fm.append(Frame(height = 20,width = 400,bg = 'red'))
Label(fm[0], text=" first string:").pack(side = LEFT)
strA= StringVar()
Entry(fm[0] ,textvariable =strA).pack(side = RIGHT)
#fram 2
fm.append(Frame(height = 20,width = 400,bg = 'red'))
Label(fm[1], text="second string:").pack(side = LEFT)
strB= StringVar()
Entry(fm[1] ,textvariable =strB).pack(side = RIGHT)
#fram 3
fm.append(Frame(height = 20,width = 400))
cdel=IntVar()
cins=IntVar()
csub=IntVar()
Label(fm[2], text="cdel:").pack(side = LEFT)
Scale(fm[2],from_ = 0, to = 50, resolution = 1, orient = HORIZONTAL,variable = cdel).pack(side = RIGHT)
#fram 4
fm.append(Frame(height = 20,width = 400))
Label(fm[3], text="cins:").pack(side = LEFT)
Scale(fm[3],from_ = 0, to = 50, resolution = 1, orient = HORIZONTAL,variable = cins).pack(side = RIGHT)
#fram 5
fm.append(Frame(height = 20,width = 400))
Label(fm[4], text="csub:").pack(side = LEFT)
Scale(fm[4],from_ = 0, to = 50, resolution = 1, orient = HORIZONTAL,variable = csub).pack(side = RIGHT)
#fram 6
fm.append(Frame(height = 20,width = 400))
CheckVar1 = IntVar()
CheckVar2 = IntVar()
CheckVar3 =IntVar()
C1 = Checkbutton(fm[5], text = "distance matrix", variable = CheckVar1, \
onvalue = 1, offvalue = 0, height=5, \
width = 20)
C2 = Checkbutton(fm[5], text = "backtrack matrix", variable = CheckVar2, \
onvalue = 1, offvalue = 0, height=5, \
width = 20)
C3 = Checkbutton(fm[5], text = "alignment", variable = CheckVar3, \
onvalue = 1, offvalue = 0, height=5, \
width = 20)
C1.pack(side = LEFT)
C2.pack(side = LEFT)
C3.pack(side = LEFT)
#fram 7
fm.append(Frame(height = 20,width = 400))
Button(fm[6],text = 'Calculate ',command =lambda : btn_compute(strA,strB,cdel,cins,csub,CheckVar1,CheckVar2,CheckVar3,text)).pack()
#pack the frame
fm[0].pack()
fm[1].pack()
fm[2].pack()
fm[3].pack()
fm[4].pack()
fm[5].pack()
fm[6].pack()
root.mainloop()
| [
[
1,
0,
0.0027,
0.0027,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0054,
0.0027,
0,
0.66,
0.0714,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.0082,
0.0027,
0,
... | [
"import sys",
"import os",
"import re",
"import time",
"import md5",
"import random",
"import thread",
"from sets import Set",
"import socket",
"import traceback",
"from Tkinter import *",
"class Path:\n def __init__(self, i, j, action):\n self.i=i\n self.j=j\n self.act... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.