code
stringlengths
1
1.72M
language
stringclasses
1 value
#!/usr/bin/env python # -*- coding: UTF-8 -*- from django.db import models from django.contrib.auth.models import User # Create your models here. class Music(models.Model): """音乐 """ title = models.CharField(max_length=50) artist = models.CharField(max_length=50) counting = models.IntegerField() song = models.FileField(upload_to="song/%Y/%m") join_time = models.DateTimeField(auto_now=True) class Meta: pass class Admin: pass def __unicode__(self): return self.title class Comment(models.Model): """用户评论 """ user = models.ForeignKey(User) music = models.ForeignKey(Music) rank = models.IntegerField() content = models.TextField(null=True, blank=True) send_time = models.DateTimeField(auto_now=True) class Meta: pass class Admin: pass def __unicode__(self): return "%s-%s" % (self.user.username, self.music.title, ) class UserMusic(models.Model): """用户播放列表 """ user = models.ForeignKey(User) music = models.ForeignKey(Music) counting = models.IntegerField() active = models.BooleanField(default=True) class Meta: pass class Admin: pass def __unicode__(self): return "%s: %s" % (self.user.username, self.music.title, ) class Category(models.Model): """音乐分类 """ title = models.CharField(max_length=50) description = models.CharField(max_length=500) class Meta: pass class Admin: pass def __unicode__(self): return self.title class CategoryMusic(models.Model): """分类音乐列表 """ category = models.ForeignKey(Category) music = models.ForeignKey(Music) counting = models.IntegerField(default=0) class Meta: pass class Admin: pass def __unicode__(self): return "%s:%s" % (self.category.title, self.music.title, )
Python
#!/usr/bin/env python # -*- coding: UTF-8 -*- from django.db import models from django.contrib.auth.models import User # Create your models here. class Music(models.Model): """音乐 """ title = models.CharField(max_length=50) artist = models.CharField(max_length=50) counting = models.IntegerField() song = models.FileField(upload_to="song/%Y/%m") join_time = models.DateTimeField(auto_now=True) class Meta: pass class Admin: pass def __unicode__(self): return self.title class Comment(models.Model): """用户评论 """ user = models.ForeignKey(User) music = models.ForeignKey(Music) rank = models.IntegerField() content = models.TextField(null=True, blank=True) send_time = models.DateTimeField(auto_now=True) class Meta: pass class Admin: pass def __unicode__(self): return "%s-%s" % (self.user.username, self.music.title, ) class UserMusic(models.Model): """用户播放列表 """ user = models.ForeignKey(User) music = models.ForeignKey(Music) counting = models.IntegerField() active = models.BooleanField(default=True) class Meta: pass class Admin: pass def __unicode__(self): return "%s: %s" % (self.user.username, self.music.title, ) class Category(models.Model): """音乐分类 """ title = models.CharField(max_length=50) description = models.CharField(max_length=500) class Meta: pass class Admin: pass def __unicode__(self): return self.title class CategoryMusic(models.Model): """分类音乐列表 """ category = models.ForeignKey(Category) music = models.ForeignKey(Music) counting = models.IntegerField(default=0) class Meta: pass class Admin: pass def __unicode__(self): return "%s:%s" % (self.category.title, self.music.title, )
Python
# Create your views here.
Python
# # 3DStudyMaze is a Panda3D application for building and # running an education course in virtual environment. # # It will feature: # - Simple maze definition language # - Connectivity between mazes # - Auto-adjusting room and tunnel sizes # - Support-ticket instructor locks # - LaTeX-editable walls # # It is based on the idea, published on Halfbakery: # http://www.halfbakery.com/idea/3D_20Study_20Maze # # Panda3D game engine is available at: # http://www.panda3d.org # # Inyuki < Made in The Internet > # Contact: mindey@gmail.com # # The initial commit is based on Panda3D sample program named "Bump-Mapping": # http://www.panda3d.org/manual/index.php/Sample_Programs:_Normal_Mapping # Licensed, probably, under http://www.panda3d.org/license.php # import direct.directbase.DirectStart from panda3d.core import WindowProperties from panda3d.core import TextNode from panda3d.core import Point2, Point3, Vec3, Vec4 from direct.task.Task import Task from direct.gui.OnscreenText import OnscreenText from direct.showbase.DirectObject import DirectObject from pandac.PandaModules import CardMaker import sys, os from pandac.PandaModules import Texture from PIL import Image, ImageDraw from pandac.PandaModules import TransparencyAttrib from copy import copy from direct.gui.DirectEntry import DirectEntry from panda3d.core import TextureStage rootNode = render.attachNewNode( 'rootNode' ) # We need a starting point for drawing either a room or a tunnel. class Entrance: def __init__(self, WallTopLeft=Point3(), offset=Point2(), dim=Point2(0,0), direction='back', kind='entrance' ): self.dim = dim self.direction = direction self.offset = offset if direction == 'left': ExitLeftTop = Point3(WallTopLeft + Point3( 0, offset.x, -offset.y) ) ExitRightTop = Point3(ExitLeftTop + Point3( 0, dim.x , 0) ) ExitLeftBottom = Point3(ExitLeftTop + Point3( 0, 0 , -dim.y) ) ExitRightBottom = Point3(ExitLeftTop + Point3( 0, dim.x , -dim.y) ) if direction == 'right': ExitLeftTop = Point3(WallTopLeft + Point3( 0, -offset.x, -offset.y) ) ExitRightTop = Point3(ExitLeftTop + Point3( 0, -dim.x , 0) ) ExitLeftBottom = Point3(ExitLeftTop + Point3( 0, 0 , -dim.y) ) ExitRightBottom = Point3(ExitLeftTop + Point3( 0, -dim.x , -dim.y) ) if direction == 'back': ExitLeftTop = Point3(WallTopLeft + Point3( -offset.x, 0, -offset.y) ) ExitRightTop = Point3(ExitLeftTop + Point3( -dim.x , 0, 0) ) ExitLeftBottom = Point3(ExitLeftTop + Point3( 0 , 0, -dim.y) ) ExitRightBottom = Point3(ExitLeftTop + Point3( -dim.x , 0, -dim.y) ) if direction == 'front': ExitLeftTop = Point3(WallTopLeft + Point3( offset.x, 0, -offset.y) ) ExitRightTop = Point3(ExitLeftTop + Point3( dim.x , 0, 0) ) ExitLeftBottom = Point3(ExitLeftTop + Point3( 0 , 0, -dim.y) ) ExitRightBottom = Point3(ExitLeftTop + Point3( dim.x , 0, -dim.y) ) if direction == 'bottom': ExitLeftTop = Point3(WallTopLeft + Point3( offset.x, -offset.y, 0) ) ExitRightTop = Point3(ExitLeftTop + Point3( dim.x , 0, 0) ) ExitLeftBottom = Point3(ExitLeftTop + Point3( 0 , -dim.y, 0) ) ExitRightBottom = Point3(ExitLeftTop + Point3( dim.x , -dim.y, 0) ) if direction == 'top': ExitLeftTop = Point3(WallTopLeft + Point3( offset.x, offset.y, 0) ) ExitRightTop = Point3(ExitLeftTop + Point3( dim.x , 0, 0) ) ExitLeftBottom = Point3(ExitLeftTop + Point3( 0 , dim.y, 0) ) ExitRightBottom = Point3(ExitLeftTop + Point3( dim.x , dim.y, 0) ) if kind == 'entrance': self.ExitLeftTop = ExitLeftTop self.ExitRightTop = ExitRightTop self.ExitLeftBottom = ExitLeftBottom self.ExitRightBottom = ExitRightBottom if kind == 'exit': if direction in ['left', 'right', 'back', 'front']: self.ExitLeftTop = ExitRightTop self.ExitRightTop = ExitLeftTop self.ExitLeftBottom = ExitRightBottom self.ExitRightBottom = ExitLeftBottom if direction in ['bottom', 'top']: self.ExitLeftTop = ExitLeftBottom self.ExitRightTop = ExitRightBottom self.ExitLeftBottom = ExitLeftTop self.ExitRightBottom = ExitRightTop if direction == 'left': self.direction = 'right' if direction == 'right': self.direction = 'left' if direction == 'back': self.direction = 'front' if direction == 'front': self.direction = 'back' if direction == 'bottom': self.direction = 'top' if direction == 'top': self.direction = 'bottom' class Wall: def __init__(self, LeftBottom=Point3( -15, 50, -10), RightBottom=Point3( 15, 50, -10), \ LeftTop=Point3( -15, 50, 10), RightTop=Point3( 15, 50, 10) ): self.cm = CardMaker('card') self.cm.setUvRange( Point2( 0, 0 ), Point2( 1, 1) ) self.cm.setFrame( LeftBottom, RightBottom, RightTop, LeftTop ) self.card = rootNode.attachNewNode(self.cm.generate()) class Room: def __init__(self, RightFrontTop, RightFrontBottom, RightBackTop, RightBackBottom, \ LeftFrontTop, LeftFrontBottom, LeftBackTop, LeftBackBottom): self.left_wall = Wall( LeftBackBottom, LeftFrontBottom, LeftBackTop, LeftFrontTop, Tile='left.png') self.right_wall = Wall( RightFrontBottom, RightBackBottom, RightFrontTop, RightBackTop, Tile='right.png') self.back_wall = Wall( RightBackBottom, LeftBackBottom, RightBackTop, LeftBackTop, Tile='back.png') self.front_wall = Wall( LeftFrontBottom, RightFrontBottom, LeftFrontTop, RightFrontTop, Tile='front.png') self.bottom_wall = Wall( LeftBackBottom, RightBackBottom, LeftFrontBottom, RightFrontBottom, Tile='bottom.png') self.top_wall = Wall( LeftFrontTop, RightFrontTop, LeftBackTop, RightBackTop, Tile='top.png') class Tunnel: def __init__(self, RightFrontTop, RightFrontBottom, RightBackTop, RightBackBottom, \ LeftFrontTop, LeftFrontBottom, LeftBackTop, LeftBackBottom): self.left_wall = Wall( LeftBackBottom, LeftFrontBottom, LeftBackTop, LeftFrontTop, Tile='left.png') self.right_wall = Wall( RightFrontBottom, RightBackBottom, RightFrontTop, RightBackTop, Tile='right.png') self.bottom_wall = Wall( LeftBackBottom, RightBackBottom, LeftFrontBottom, RightFrontBottom, Tile='bottom.png') self.top_wall = Wall( LeftFrontTop, RightFrontTop, LeftBackTop, RightBackTop, Tile='top.png') class Poster(Wall): def __init__(self, WallTopLeft=Point3(), PosterLeftTop=Point2(), directions=('y+','z+'), document='hi-res.png', scale=1.0, aspect='3:4' ): # Here, just needs to determine the positions of the 'LeftTop', 'RightTop', 'LeftBottom', 'RightBottom' points. # They all will depend on the coordinate of the maze wall's point of reference (e.g., LeftTop corner of the wall), # and the position, and the directions, along which to add the position.x and position.y coordinates. # Determine dimensions of the document: if document.split('.')[-1] in [ 'avi', 'mp4' ]: # If the document is video: if aspect == '9:16': img_h, img_w = 9*200*scale, 16*200*scale else: img_h, img_w = 3*500*scale, 4*500*scale else: # If the document is image: img=Image.open(document,'r') img_w, img_h = img.size document_x, document_y = scale*img_w/100, scale*img_h/100 # Save filename for later use in activating videos. self.document = document # Margin from the wall m = 0.01 # Margin for activation area (it could later be a function of img_h, img_w): a = 5. # The coordinates depend on the orientation of the wall, here specified by 'directions' instead of 'face'. # Maybe I should just have rotation matrices for each case, and write it more compactly, but for now: if directions == ('y+','z+'): # Poster on left wall margin = Point3(m,0,0) active = Point3(a,0,0) PosterLeftTop = Point3(WallTopLeft + Point3( 0, PosterLeftTop.x, -PosterLeftTop.y) + margin) PosterRightTop = Point3(PosterLeftTop + Point3( 0, document_x , 0) ) PosterLeftBottom = Point3(PosterLeftTop + Point3( 0, 0 , -document_y) ) PosterRightBottom = Point3(PosterLeftTop + Point3( 0, document_x , -document_y) ) if directions == ('y-','z+'): # Poster on right wall margin = Point3(-m,0,0) active = Point3(-a,0,0) PosterLeftTop = Point3(WallTopLeft + Point3( 0, -PosterLeftTop.x, -PosterLeftTop.y) + margin) PosterRightTop = Point3(PosterLeftTop + Point3( 0, -document_x , 0) ) PosterLeftBottom = Point3(PosterLeftTop + Point3( 0, 0 , -document_y) ) PosterRightBottom = Point3(PosterLeftTop + Point3( 0, -document_x , -document_y) ) if directions == ('x-','z+'): # Poster on back wall margin = Point3(0,m,0) active = Point3(0,a,0) PosterLeftTop = Point3(WallTopLeft + Point3( -PosterLeftTop.x, 0, -PosterLeftTop.y) + margin) PosterRightTop = Point3(PosterLeftTop + Point3( -document_x , 0, 0) ) PosterLeftBottom = Point3(PosterLeftTop + Point3( 0 , 0, -document_y) ) PosterRightBottom = Point3(PosterLeftTop + Point3( -document_x , 0, -document_y) ) if directions == ('x+','z+'): # Poster on front wall margin = Point3(0,-m,0) active = Point3(0,-a,0) PosterLeftTop = Point3(WallTopLeft + Point3( PosterLeftTop.x, 0, -PosterLeftTop.y) + margin) PosterRightTop = Point3(PosterLeftTop + Point3( document_x , 0, 0) ) PosterLeftBottom = Point3(PosterLeftTop + Point3( 0 , 0, -document_y) ) PosterRightBottom = Point3(PosterLeftTop + Point3( document_x , 0, -document_y) ) if directions == ('x+','y+'): # Poster on bottom wall margin = Point3(0,0,m) active = Point3(0,0,a) PosterLeftTop = Point3(WallTopLeft + Point3( PosterLeftTop.x, -PosterLeftTop.y, 0) + margin) PosterRightTop = Point3(PosterLeftTop + Point3( document_x , 0, 0) ) PosterLeftBottom = Point3(PosterLeftTop + Point3( 0 , -document_y, 0) ) PosterRightBottom = Point3(PosterLeftTop + Point3( document_x , -document_y, 0) ) if directions == ('x+','y-'): # Poster on top wall margin = Point3(0,0,-m) active = Point3(0,0,-a) PosterLeftTop = Point3(WallTopLeft + Point3( PosterLeftTop.x, PosterLeftTop.y, 0) + margin) PosterRightTop = Point3(PosterLeftTop + Point3( document_x , 0, 0) ) PosterLeftBottom = Point3(PosterLeftTop + Point3( 0 , document_y, 0) ) PosterRightBottom = Point3(PosterLeftTop + Point3( document_x , document_y, 0) ) Wall.__init__(self, LeftBottom=PosterLeftBottom, RightBottom=PosterRightBottom, \ LeftTop=PosterLeftTop, RightTop=PosterRightTop ) self.tex = loader.loadTexture(document) self.card.setTexture(self.tex) if document.split('.')[-1] in [ 'avi', 'mp4' ]: self.card.setTexScale(TextureStage.getDefault(), self.tex.getTexScale()) self.media = loader.loadSfx(document) self.tex.synchronizeTo(self.media) else: self.tex.setMinfilter(Texture.FTLinearMipmapLinear) # Poster activation area (used for starting the playing of a movie) # For activation area FurtherLeftTop = Point3(PosterLeftTop + active) FurtherRightTop = Point3(PosterRightTop + active) FurtherLeftBottom = Point3(PosterLeftBottom + active) FurtherRightBottom= Point3(PosterRightBottom + active) PointList = [PosterLeftTop, PosterRightTop, PosterLeftBottom, PosterRightBottom, \ FurtherLeftTop, FurtherRightTop, FurtherLeftBottom, FurtherRightBottom] self.x_minus = min([item.x for item in PointList]) self.x_plus = max([item.x for item in PointList]) self.y_minus = min([item.y for item in PointList]) self.y_plus = max([item.y for item in PointList]) self.z_minus = min([item.z for item in PointList]) self.z_plus = max([item.z for item in PointList]) def addPage(): pass def addFrame(): pass def flipPage(): pass class MazeWall: def __init__(self, origin=Point3(0,50,0), dim=Point2(120,120), orientation='front', reference='center' ): self.exits = [] # Possible references of the wall: center and corners references = [(0, ( 0., 0.), 'xy', 'center' ), (1, ( 1., 1.), 'x+y+', 'LeftBottom' ), (2, ( 1.,-1.), 'x+y-', 'LeftTop' ), (3, ( -1., 1.), 'x-y+', 'RightBottom'), (4, ( -1, -1.), 'x-y-', 'RightTop' )] # Finding index of the reference for item in references: if reference in item: reference = item[0] # Possible orientations of the wall: corresponding to the walls they are used to draw for a room. orientations = [(0, 'x-', 'left' ), (1, 'x+', 'right' ), (2, 'y-', 'back' ), (3, 'y+', 'front' ), (4, 'z-', 'bottom'), (5, 'z+', 'top' )] # Finding index of the orientation for item in orientations: if orientation in item: orientation = item[0] # Delta is half the distance from center D = Point2( dim.x/2., dim.y/2.) d = Point2( references[reference][1] ) delta2d = Point2(D.x*d.x, D.y*d.y) # Possible four corners in 2d: LeftBottom2d = Point2(0,0) + Point2(-dim.x/2., -dim.y/2.) + delta2d RightBottom2d = Point2(0,0) + Point2( dim.x/2., -dim.y/2.) + delta2d LeftTop2d = Point2(0,0) + Point2(-dim.x/2., dim.y/2.) + delta2d RightTop2d = Point2(0,0) + Point2( dim.x/2., dim.y/2.) + delta2d corners2d = [LeftBottom2d, RightBottom2d, LeftTop2d, RightTop2d] # What 3D coordinates these delta has to be applied to, depends on card's orientation: if orientation == 0: x = 'y+'; y = 'z+' if orientation == 1: x = 'y-'; y = 'z+' if orientation == 2: x = 'x-'; y = 'z+' if orientation == 3: x = 'x+'; y = 'z+' if orientation == 4: x = 'x+'; y = 'y+' if orientation == 5: x = 'x+'; y = 'y-' # Saving for use in method hangPoster self.x = x; self.y = y # Saving for use in method hangExit self.orientation = orientations[orientation][2] # Saving for use in method cutWindow self.dim = dim # Possible four corners in 3d: corners3d = [Point3(0,0,0)+origin, Point3(0,0,0)+origin, Point3(0,0,0)+origin, Point3(0,0,0)+origin] if x == 'x+': for i in range(4): corners3d[i] += Point3(corners2d[i].x, 0., 0.) if x == 'x-': for i in range(4): corners3d[i] -= Point3(corners2d[i].x, 0., 0.) if x == 'y+': for i in range(4): corners3d[i] += Point3(0., corners2d[i].x, 0.) if x == 'y-': for i in range(4): corners3d[i] -= Point3(0., corners2d[i].x, 0.) if y == 'y+': for i in range(4): corners3d[i] += Point3(0., corners2d[i].y, 0.) if y == 'y-': for i in range(4): corners3d[i] -= Point3(0., corners2d[i].y, 0.) if y == 'z+': for i in range(4): corners3d[i] += Point3(0., 0., corners2d[i].y) self.LeftBottom = Point3(corners3d[0]) self.RightBottom = Point3(corners3d[1]) self.LeftTop = Point3(corners3d[2]) self.RightTop = Point3(corners3d[3]) self.wall = Wall( self.LeftBottom, self.RightBottom, self.LeftTop, self.RightTop ) self.posters = {} # Store texture filename as a variable self.texture = os.path.join('temp', str(id(self))+'_tiled.png') self.alpha = os.path.join('temp', str(id(self))+'_alpha.png') self.addTexture( Tile=orientations[orientation][2]+'.png', repeat=(10,10), bg_dim = (dim.x*10,dim.y*10) ) self.addAlpha() self.updateTexture() def addTexture(self, Tile='default.png', repeat=(10,10), bg_dim=(0,0)): Tile = os.path.join('textures', Tile) # In case the Tile file does not exist, create and use default.png, so that it could be changed later. if not os.path.isfile(os.path.join(os.getcwd(),Tile)): im = Image.new('RGB', (150,150)); draw = ImageDraw.Draw(im) draw.rectangle([(0, 0), (150, 150)], outline='white'); draw.text((55, 70), "Default") im.save(os.path.join('textures', 'default.png'), 'PNG'); Tile = os.path.join('textures', 'default.png') # Reading the tile img=Image.open(Tile,'r') img_w, img_h = img.size # If the wall's dimensions in pixelsaren't specified if bg_dim[0] == 0 or bg_dim[1] == 0: # We tile by creating the image of the size it would take if you repeat the tiles that many times. background = Image.new("RGB", ( img_w*repeat[0], img_h*repeat[1]), (255,255,255)) for i in range(repeat[0]): for j in range(repeat[1]): background.paste(img,(i*img_w, j*img_h)) else: # We tile into the dimensions: background = Image.new("RGB", (int(bg_dim[0]), int(bg_dim[1])), (255,255,255)) for i in range(int(bg_dim[0]/img_w+1)): for j in range(int(bg_dim[1]/img_h+1)): background.paste(img,(i*img_w,j*img_h)) # We add a one-pixel white corner: draw = ImageDraw.Draw(background) draw.rectangle([(0, 0), (img_w*repeat[0], img_h*repeat[1])], outline='white') background.save(self.texture, 'PNG') def addAlpha(self): # Making transparency mapping file im = Image.new("RGB", (int(self.dim.x)*10, int(self.dim.y)*10), (255,255,255)); draw = ImageDraw.Draw(im) im.save(self.alpha) def cutWindow(self, window=(Point2(25,20),Point2(100,100))): # Reading the alpha tile im = Image.open(self.alpha,'r') img_w, img_h = im.size # How many pixels per 'blender unit' ratio_x, ratio_y = img_w/self.dim.x, img_h/self.dim.y draw = ImageDraw.Draw(im) draw.rectangle([(int(ratio_x*window[0].x), int(ratio_y*window[0].y)), \ (int(ratio_x*window[1].x-1), int(ratio_y*window[1].y-1))], fill="#000000") im.save(self.alpha, "PNG") self.updateTexture() def updateTexture(self): # Try to add default textures depending on the orientation of the wall try: self.wall.tex = loader.loadTexture(self.texture, self.alpha) self.wall.tex.reload() self.wall.card.setTexture(self.wall.tex) self.wall.card.setTransparency(True) self.wall.card.setTransparency(TransparencyAttrib.MBinary) except: pass def newTexture(self, Tile='default.png', repeat=(10,10), bg_dim=(0,0)): if not os.path.isfile('textures/%s' % Tile.split('/')[-1]): os.system('cp %s textures/' % Tile) else: if not os.stat('textures/%s' % Tile.split('/')[-1]).st_size == os.stat(Tile).st_size: os.system('cp %s textures/' % Tile) Tile = Tile.split('/')[-1] self.addTexture(Tile=Tile, repeat=repeat, bg_dim=bg_dim) self.updateTexture() def hangPoster(self, document='hi-res.png', offset=Point2(1,1), scale=1.0, aspect='3:4'): self.posters[document] = Poster( self.LeftTop, offset, (self.x, self.y), document, scale, aspect ) def hangPosters(self, folder='.', starting=1, rows=3, cols=4, scale=1.0, spacing=0.25, offset=Point2(0,0)): # ( With an assumption that all the pages of the book are equal rectangles ) # Get the pixel size of one page img=Image.open(os.path.join(folder,str(starting)+'.png'),'r') img_w, img_h = img.size # Get the dimensions of a single page in blender units doc_x, doc_y = scale*img_w/100, scale*img_h/100 # Compute the dimensions of the resulting mat, with spacing rez_x = doc_x * cols + spacing * (cols + 1) rez_y = doc_y * rows + spacing * (rows + 1) # Return an informative error if the size exceeds dimensions of the wall if self.dim.x < rez_x or self.dim.y < rez_y: print 'Either height or width exceed the corresponding dimension of the wall.' print 'Dimensions of the wall: x=%s, y=%s' % (self.dim.x, self.dim.y) print 'Dimensions of the mat: x=%s, y=%s' % (rez_x, rez_y) else: # Compute the upper limits for coordinates within which this point can be: max_x = self.dim.x - rez_x max_y = self.dim.y - rez_y # IF LeftTop corner of the mat is not outside the limits: if 0.0 <= offset.x < max_x and 0.0 <= offset.y < max_y: print 'Adding the pages to a wall.' I = offset + Point2(spacing, spacing) D = Point2(doc_x+spacing, doc_y+spacing) i = 0 for row in range(rows): for col in range(cols): fn = os.path.join(folder,str(starting+i)+'.png') pos = I + Point2(col*D.x,0) + Point2(0,row*D.y) if os.path.isfile(fn): self.hangPoster(fn, pos, scale) i += 1 else: print 'Although dimensions are right, your offset point is out of range.' print 'Range allows for offset: 0.0 < x < %s, 0.0 < y < %s' % (max_x, max_y) print 'The actual dimensions of the offset: x=%s, y=%s' % (offset.x, offset.y) def hangExit(self, offset=Point2(1,1), dim=Point2(5,8)): self.cutWindow((offset, Point2(offset+dim))) e = Entrance( self.LeftTop, offset, dim, self.orientation, kind='exit') self.exits.append( e ) return e def hangTunnel(self, offset=Point2(1,1), dim=Point2(5,8), questions = [('problem1.png', 'answer1'), \ ('problem2.png', 'answer2'), \ ('problem3.png', 'answer3'), \ ]): exit = self.hangExit(offset, dim) self.exits.append(exit) tunnel = MazeTunnel(exit, questions) return tunnel class MazeTunnel: def __init__(self, entrance, questions=[('problem1.png', 'answer1')]): # Since tunnel is a container of questions, it is appropriate to start estimating the length # depending on the questions answered, and only add the margin 'epsilon' at the end of tunnel # once all the questions had been answered. # At this moment, the questions will have to be passed to constructor function. However, it is preferable to have flexible 'addQuestion' method. # The problem is that all the later rooms' coordinates will depend on the tunnel's length, so the part of maze that follows that tunnel would have # to be all updated. # Here, I added 'invisible question', as it is not actually appearing, after all: in this implementation, # we let the user thrugh the tunnel when the current answer is equal to the number of questions. questions += [('invisible', 'question')] self.questions = questions self.length = len(questions)*10 self.epsilon = 5 self.which = Point3(0,0,0) # LEFT RIGHT BOTTOM TOP if entrance.direction == 'left': # x+ self.directions = ['front','back','bottom','top'] self.left = MazeWall(entrance.ExitRightTop, Point2(self.length, entrance.dim.y), orientation='front', reference='LeftTop') self.right = MazeWall(entrance.ExitLeftTop, Point2(self.length, entrance.dim.y), orientation='back', reference='RightTop') self.bottom = MazeWall(entrance.ExitRightBottom, Point2(self.length, entrance.dim.x), orientation='bottom', reference='LeftTop') self.top = MazeWall(entrance.ExitRightTop, Point2(self.length, entrance.dim.x), orientation='top', reference='LeftBottom') self.exit = Entrance(entrance.ExitLeftTop+Point3(self.length,0,0), offset=Point2(), dim=entrance.dim, direction=entrance.direction, kind='entrance') self.dim = Point3(self.length, entrance.dim.x, entrance.dim.y) self.which.x = 1 if entrance.direction == 'right': # x- self.directions = ['back','front','bottom','top'] self.left = MazeWall(entrance.ExitRightTop, Point2(self.length,entrance.dim.y), orientation='back', reference='LeftTop') self.right = MazeWall(entrance.ExitLeftTop, Point2(self.length,entrance.dim.y), orientation='front', reference='RightTop') self.bottom = MazeWall(entrance.ExitRightBottom, Point2(self.length, entrance.dim.x), orientation='bottom', reference='RightBottom') self.top = MazeWall(entrance.ExitRightTop, Point2(self.length, entrance.dim.x), orientation='top', reference='RightTop') self.exit = Entrance(entrance.ExitLeftTop+Point3(-self.length,0,0), offset=Point2(), dim=entrance.dim, direction=entrance.direction, kind='entrance') self.dim = Point3(self.length, entrance.dim.x, entrance.dim.y) self.which.x = -1 if entrance.direction == 'back': # y+ self.directions = ['left','right','bottom','top'] self.left = MazeWall(entrance.ExitRightTop, Point2(self.length,entrance.dim.y), orientation='left', reference='LeftTop') self.right = MazeWall(entrance.ExitLeftTop, Point2(self.length,entrance.dim.y), orientation='right', reference='RightTop') self.bottom = MazeWall(entrance.ExitRightBottom, Point2(entrance.dim.x, self.length), orientation='bottom', reference='LeftBottom') self.top = MazeWall(entrance.ExitLeftTop, Point2(entrance.dim.x, self.length), orientation='top', reference='RightTop') self.exit = Entrance(entrance.ExitLeftTop+Point3(0,self.length,0), offset=Point2(), dim=entrance.dim, direction=entrance.direction, kind='entrance') self.dim = Point3(entrance.dim.x, self.length, entrance.dim.y) self.which.y = 1 if entrance.direction == 'front': # y- self.directions = ['right','left','bottom','top'] self.left = MazeWall(entrance.ExitRightTop, Point2(self.length,entrance.dim.y), orientation='right', reference='LeftTop') self.right = MazeWall(entrance.ExitLeftTop, Point2(self.length,entrance.dim.y), orientation='left', reference='RightTop') self.bottom = MazeWall(entrance.ExitRightBottom, Point2(entrance.dim.x,self.length), orientation='bottom', reference='RightTop') self.top = MazeWall(entrance.ExitLeftTop, Point2(entrance.dim.x,self.length), orientation='top', reference='LeftBottom') self.exit = Entrance(entrance.ExitLeftTop+Point3(0,-self.length,0), offset=Point2(), dim=entrance.dim, direction=entrance.direction, kind='entrance') self.dim = Point3(entrance.dim.x, self.length, entrance.dim.y) self.which.y = -1 if entrance.direction == 'bottom': # z+ self.directions = ['left','right','front','back'] self.left = MazeWall(entrance.ExitLeftBottom, Point2(entrance.dim.y,self.length), orientation='left', reference='LeftBottom') self.right = MazeWall(entrance.ExitRightTop, Point2(entrance.dim.y,self.length), orientation='right', reference='LeftBottom') self.bottom = MazeWall(entrance.ExitRightTop, Point2(entrance.dim.x,self.length), orientation='front', reference='RightBottom') self.top = MazeWall(entrance.ExitRightBottom, Point2(entrance.dim.x, self.length), orientation='back', reference='LeftBottom') self.exit = Entrance(entrance.ExitLeftTop+Point3(0,0,self.length), offset=Point2(), dim=entrance.dim, direction=entrance.direction, kind='entrance') self.dim = Point3(entrance.dim.x, entrance.dim.y, self.length) self.which.z = 1 if entrance.direction == 'top': self.directions = ['left','right','back','front'] self.left = MazeWall(entrance.ExitLeftTop, Point2(entrance.dim.y,self.length), orientation='left', reference='LeftTop') self.right = MazeWall(entrance.ExitRightTop, Point2(entrance.dim.y,self.length), orientation='right', reference='RightTop') self.bottom = MazeWall(entrance.ExitLeftTop, Point2(entrance.dim.x,self.length), orientation='back', reference='RightTop') self.top = MazeWall(entrance.ExitLeftBottom, Point2(entrance.dim.x, self.length), orientation='front', reference='LeftTop') self.exit = Entrance(entrance.ExitLeftTop+Point3(0,0,-self.length), offset=Point2(), dim=entrance.dim, direction=entrance.direction, kind='entrance') self.dim = Point3(entrance.dim.x, entrance.dim.y, self.length) self.which.z = -1 # Find the center of the area: total = entrance.ExitLeftTop + self.exit.ExitRightBottom self.center = Point3(total.x/2, total.y/2, total.z/2) self.update_limits() def update_limits(self, current=1): # Update the number of problems solved in this tunnel. try: self.current_problem += 1 except: self.current_problem = current self.answer = self.questions[self.current_problem-1][1] remaining_problems = len(self.questions) - self.current_problem # Add epsilon only to the nearer end of the tunnel: self.x_minus = self.center.x - self.dim.x/2 if self.which.x == 1: self.x_minus -= abs(self.which.x)*self.epsilon self.x_plus = self.center.x + self.dim.x/2 if self.which.x ==-1: self.x_plus += abs(self.which.x)*self.epsilon self.y_minus = self.center.y - self.dim.y/2 if self.which.y == 1: self.y_minus -= abs(self.which.y)*self.epsilon self.y_plus = self.center.y + self.dim.y/2 if self.which.y ==-1: self.y_plus += abs(self.which.y)*self.epsilon self.z_minus = self.center.z - self.dim.z/2 if self.which.z == 1: self.z_minus -= abs(self.which.z)*self.epsilon self.z_plus = self.center.z + self.dim.z/2 if self.which.z ==-1: self.z_plus += abs(self.which.z)*self.epsilon # Correction depending on questions answered: if self.which.x == 1: self.x_plus -= remaining_problems*10. if self.which.x ==-1: self.x_minus += remaining_problems*10. if self.which.y == 1: self.y_plus -= remaining_problems*10. if self.which.y ==-1: self.y_minus += remaining_problems*10. if self.which.z == 1: self.z_plus -= remaining_problems*10. if self.which.z ==-1: self.z_minus += remaining_problems*10. # If all of the poroblems had been solved, add epsilon to the further end of the tunnel: if self.current_problem == len(self.questions): if self.which.x ==-1: self.x_minus -= abs(self.which.x)*self.epsilon if self.which.x == 1: self.x_plus += abs(self.which.x)*self.epsilon if self.which.y ==-1: self.y_minus -= abs(self.which.y)*self.epsilon if self.which.y == 1: self.y_plus += abs(self.which.y)*self.epsilon if self.which.z ==-1: self.z_minus -= abs(self.which.z)*self.epsilon if self.which.z == 1: self.z_plus += abs(self.which.z)*self.epsilon # For active zone (zone in which the question is activated) # Start with copying the coordinates of the tunnel zone: self.active_x_minus = copy(self.x_minus) self.active_x_plus = copy(self.x_plus) self.active_y_minus = copy(self.y_minus) self.active_y_plus = copy(self.y_plus) self.active_z_minus = copy(self.z_minus) self.active_z_plus = copy(self.z_plus) # If not all problems of the tunnel are solved, then, depending on the direction of the tunnel, modify if self.current_problem < len(self.questions): # the limits along that axis by either adding or subtracting from either positive or negative tunnel limit. if self.which == Point3(-1, 0, 0): # x- self.active_x_minus = copy(self.x_minus) self.active_x_plus = self.active_x_minus + 10 if self.which == Point3( 1, 0, 0): # x+ self.active_x_plus = copy(self.x_plus) self.active_x_minus = self.active_x_plus - 10 if self.which == Point3( 0,-1, 0): # y- self.active_y_minus = copy(self.y_minus) self.active_y_plus = self.active_y_minus + 10 if self.which == Point3( 0, 1, 0): # y+ self.active_y_plus = copy(self.y_plus) self.active_y_minus = self.active_y_plus - 10 if self.which == Point3( 0, 0,-1): # z- self.active_z_minus = copy(self.z_minus) self.active_z_plus = self.active_z_minus + 10 if self.which == Point3( 0, 0, 1): # z+ self.active_z_plus = copy(self.z_plus) self.active_z_minus = self.active_z_plus - 10 else: # Make arbitrary non-zero (cause zero very popular starting point), zero-volume point self.active_x_minus = self.active_x_plus self.active_y_minus = self.active_y_plus self.active_z_minus = self.active_z_plus def setTextures(self, Tile='default.png', repeat=(10,10), bg_dim=(0,0)): self.left.newTexture(Tile=Tile, repeat=repeat, bg_dim=bg_dim) self.right.newTexture(Tile=Tile, repeat=repeat, bg_dim=bg_dim) self.bottom.newTexture(Tile=Tile, repeat=repeat, bg_dim=bg_dim) self.top.newTexture(Tile=Tile, repeat=repeat, bg_dim=bg_dim) def __repr__(self): return str((self.x_minus, self.x_plus, self.y_minus, self.y_plus, self.z_minus, self.z_plus)) class MazeRoom: def __init__(self, entrance, dim=Point3(100,100,100), offset=Point2(2,2), music='basic.ogg'): self.music_file = music if isinstance(entrance,MazeTunnel): entrance = entrance.exit origin = entrance.ExitLeftTop if entrance.direction == 'left': reference = 'LeftBackTop' origin -= Point3(0, offset.x, -offset.y) if entrance.direction == 'right': reference = 'RightFrontTop' origin -= Point3(0, -offset.x, -offset.y) if entrance.direction == 'back': reference = 'RightBackTop' origin -= Point3(-offset.x, 0, -offset.y) if entrance.direction == 'front': reference = 'LeftFrontTop' origin -= Point3(offset.x, 0, -offset.y) if entrance.direction == 'bottom': reference = 'LeftFrontBottom' origin -= Point3(offset.x, -offset.y, 0) if entrance.direction == 'top': reference = 'LeftBackTop' origin -= Point3(offset.x, offset.y, 0) # Possible references of the room: center and corners # \/ Diametrically opposite to: \/ references = [(0, ( 0., 0., 0.), 'xyz', 'center' ), (1, ( 1., 1., 1.), 'x+y+z+', 'LeftBackBottom' ), # 'RightFrontTop' (2, ( 1., 1.,-1.), 'x+y+z-', 'LeftBackTop' ), # 'RightFrontBottom' (3, ( 1.,-1., 1.), 'x+y-z+', 'LeftFrontBottom' ), # 'RightBackTop' (4, ( 1.,-1.,-1.), 'x+y-z-', 'LeftFrontTop' ), # 'RightBackBottom' (5, (-1., 1., 1.), 'x-y+z+', 'RightBackBottom' ), # 'LeftFrontTop' (6, (-1., 1.,-1.), 'x-y+z-', 'RightBackTop' ), # 'LeftFrontBottom' (7, (-1.,-1., 1.), 'x-y-z+', 'RightFrontBottom'), # 'LeftBackTop' (8, (-1.,-1.,-1.), 'x-y-z-', 'RightFrontTop' )] # 'LeftBackBottom' # Finding index of the reference for item in references: if reference in item: reference = item[0] # if reference == 6: origin += Point3( offset.x, 0, offset.y ) # Delta is half the distance from center D = Point3( dim.x/2., dim.y/2., dim.z/2.) d = Point3( references[reference][1] ) delta = Point3(D.x*d.x, D.y*d.y, D.z*d.z) position = Point3(origin + delta) # Drawing six sides: self.left = MazeWall(position - Point3(dim.x/2.,0,0), Point2(dim.y,dim.z), 'left') self.right = MazeWall(position + Point3(dim.x/2.,0,0), Point2(dim.y,dim.z), 'right') self.back = MazeWall(position - Point3(0,dim.y/2.,0), Point2(dim.x,dim.z), 'back') self.front = MazeWall(position + Point3(0,dim.y/2.,0), Point2(dim.x,dim.z), 'front') self.bottom = MazeWall(position - Point3(0,0,dim.z/2.), Point2(dim.x,dim.y), 'bottom') self.top = MazeWall(position + Point3(0,0,dim.z/2.), Point2(dim.x,dim.y), 'top') # Define limits for the MazeRoom: since walls are parallel to axes, it's easy: self.x_minus = position.x - dim.x/2 self.x_plus = position.x + dim.x/2 self.y_minus = position.y - dim.y/2 self.y_plus = position.y + dim.y/2 self.z_minus = position.z - dim.z/2. self.z_plus = position.z + dim.z/2. # Cuting window on the appropriate created wall, to coincide with the entrance. if entrance.direction == 'left': self.left.cutWindow((offset, Point2(offset+entrance.dim))) if entrance.direction == 'right': self.right.cutWindow((offset, Point2(offset+entrance.dim))) if entrance.direction == 'back': self.back.cutWindow((offset, Point2(offset+entrance.dim))) if entrance.direction == 'front': self.front.cutWindow((offset, Point2(offset+entrance.dim))) if entrance.direction == 'bottom': self.bottom.cutWindow((offset, Point2(offset+entrance.dim))) if entrance.direction == 'top': self.top.cutWindow((offset, Point2(offset+entrance.dim))) def __repr__(self): return str((self.x_minus, self.x_plus, self.y_minus, self.y_plus, self.z_minus, self.z_plus)) def setTextures(self, Tile='default.png', repeat=(10,10), bg_dim=(0,0)): self.left.newTexture(Tile=Tile, repeat=repeat, bg_dim=bg_dim) self.right.newTexture(Tile=Tile, repeat=repeat, bg_dim=bg_dim) self.back.newTexture(Tile=Tile, repeat=repeat, bg_dim=bg_dim) self.front.newTexture(Tile=Tile, repeat=repeat, bg_dim=bg_dim) self.bottom.newTexture(Tile=Tile, repeat=repeat, bg_dim=bg_dim) self.top.newTexture(Tile=Tile, repeat=repeat, bg_dim=bg_dim) class StudyMaze(DirectObject): def __init__(self): # Cleanup the temporary directory before execution os.system('rm -rf %s*' % os.path.join(os.getcwd(), 'temp/') ) # List of all the areas (MazeRooms, MazeTunnels) in the maze. self.mazeAreas = [] self.margin = 2.0 # (Minimum distance to a wall.) # Saving the current state self.question_displayed = False # Load the 'empty room' model. self.room = loader.loadModel("models/emptyroom") self.room.reparentTo(rootNode) # Load background music. self.music_file = '' self.active_video = '' # ======================================================== # >>>>>>>>>>>>>>>>> MAZE WALLS IMAGES >>>>>>>>>>>>>>>>>>>> execfile('mazes/root.py') # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< # ======================================================== # Show framerate base.setFrameRateMeter(True) # Make the mouse invisible, turn off normal mouse controls base.disableMouse() props = WindowProperties() props.setCursorHidden(True) base.win.requestProperties(props) # Set the current viewing target: facing y+, from (0,0,0) self.focus = Vec3(0,0,0) self.heading = 0 self.pitch = 0 self.mousex = 0 self.mousey = 0 self.last = 0 self.mousebtn = [0,0,0] # Start the camera control task: taskMgr.add(self.controlCamera, "camera-task") self.accept("escape", sys.exit, [0]) self.accept("mouse1", self.setMouseBtn, [0, 1]) self.accept("mouse1-up", self.setMouseBtn, [0, 0]) self.accept("mouse2", self.setMouseBtn, [1, 1]) self.accept("mouse2-up", self.setMouseBtn, [1, 0]) self.accept("mouse3", self.setMouseBtn, [2, 1]) self.accept("mouse3-up", self.setMouseBtn, [2, 0]) def setMouseBtn(self, btn, value): self.mousebtn[btn] = value def whichAreas(self, point3): results = [] for area in self.mazeAreas: if area.x_minus < point3.x < area.x_plus and \ area.y_minus < point3.y < area.y_plus and \ area.z_minus < point3.z < area.z_plus: results.append(area) return results def display_question(self, source=('problem1.png', 'answer1')): cmi = CardMaker("Problem") cmi.setFrame(-0.9,0.2,-0.9,0.9) self.card = render2d.attachNewNode(cmi.generate()) tex = loader.loadTexture( source[0] ) self.answer = source[1] self.card.setTexture(tex) def hide_question(self): try: if self.card: self.card.removeNode() self.question_displayed = False if self.q: self.q.destroy() except: pass def controlCamera(self, task): # figure out how much the mouse has moved (in pixels) md = base.win.getPointer(0) x = md.getX() y = md.getY() # clearly: necessary for mouse movement if base.win.movePointer(0, 100, 100): self.heading = self.heading - (x - 100) * 0.2 self.pitch = self.pitch - (y - 100) * 0.2 # limits up/down movement of the camera if (self.pitch < -60): self.pitch = -60 if (self.pitch > 60): self.pitch = 60 # clearly: necessary for direction movement base.camera.setHpr(self.heading,self.pitch,0) dir = base.camera.getMat().getRow3(1) # clearly: necessary for forth/back movement elapsed = task.time - self.last if (self.last == 0): elapsed = 0 if (self.mousebtn[0]): self.focus = self.focus + dir * elapsed*30 if (self.mousebtn[1]) or (self.mousebtn[2]): self.focus = self.focus - dir * elapsed*30 base.camera.setPos(self.focus - (dir*5)) # >>>>>>>>>>>>>>>>> MAZE AREAS' LIMITS >>>>>>>>>>>>>>>>>>> # Get current camera position point = Point3(base.camera.getX(), base.camera.getY(), base.camera.getZ()) #print point # Check which area we are in, assuming single-area-presence for now: # // Later we will set priorities, in the cases of overlapping limits of # a MazeRoom and limits of a MazeTunnel. // # Function that checks for answer, used to update tunnel limits. def setText(textEntered): if textEntered == self.tunnel.answer: # i.e., if answer is correct: try: self.tunnel.update_limits() self.hide_question() except: pass textObject.setText(textEntered) # Function that clears the answer field. def clearText(): self.q.enterText('') # Set the limits of that room: try: AL = self.whichAreas(point) # Logically, if we are in more than 1 area, we should let the movement along the axis of the tunnel. # Determining the axis: if len(AL) > 1: pass elif len(AL) == 1: for item in AL: if isinstance(item, MazeTunnel): free = item.which if (item.active_x_minus < point.x < item.active_x_plus) and \ (item.active_y_minus < point.y < item.active_y_plus) and \ (item.active_z_minus < point.z < item.active_z_plus): if not self.question_displayed: # Display question self.tunnel = item self.q = DirectEntry(width=12, text = "" ,scale=.05, pos=(-0.4, 0, -0.7), \ command=setText, initialText="Step away, and type answer!", numLines = 3,focus=1,focusInCommand=clearText) self.display_question( item.questions[item.current_problem-1] ) self.question_displayed = True else: # Either not in active zone anymore self.hide_question() else: # Or not in MazeTunnel anymore. self.hide_question() # Change music: if self.music_file == '': self.music_file = item.music_file self.music = base.loader.loadSfx(self.music_file) self.music.play() self.music.setVolume(0.5) if item.music_file != self.music_file: self.music.stop() self.music_file = item.music_file if os.path.isfile(self.music_file): self.music = base.loader.loadSfx(item.music_file) self.music.play() self.music.setVolume(0.5) # Check if we are not in any Poster's activation area, # and activate the poster, in which's are we are in. WallList = [item.left, item.right, item.back, item.front, item.bottom, item.top] for wall in WallList: if len(wall.posters): for poster in wall.posters.values(): if poster.document.split('.')[-1] in [ 'avi', 'mp4' ]: if (poster.x_minus < point.x < poster.x_plus) and \ (poster.y_minus < point.y < poster.y_plus) and \ (poster.z_minus < point.z < poster.z_plus): if self.active_video == '': self.active_video = poster.media if id(self.active_video) != id(poster.media): self.active_video.stop() self.active_video = poster.media if self.active_video.getTime() > 0.0: self.active_video.setTime(0.0) self.active_video.play() free = Point3(0,0,0) AL = AL[0] if self.music_file != '': self.accept("z", self.music.stop) # z - for 'sleep zzz' if self.active_video != '': self.accept("x", self.active_video.stop) # x - for 'cross-out' self.accept("c", self.active_video.play) # c - for 'continue' left_lim = AL.x_minus + self.margin right_lim = AL.x_plus - self.margin back_lim = AL.y_minus + self.margin front_lim = AL.y_plus - self.margin bottom_lim = AL.z_minus + self.margin top_lim = AL.z_plus - self.margin if ( point.x < left_lim ) and not free.x: base.camera.setX(left_lim ) if ( point.x > right_lim ) and not free.x: base.camera.setX(right_lim ) if ( point.y < back_lim ) and not free.y: base.camera.setY(back_lim ) if ( point.y > front_lim ) and not free.y: base.camera.setY(front_lim ) if ( point.z < bottom_lim ) and not free.z: base.camera.setZ(bottom_lim ) if ( point.z > top_lim ) and not free.z: base.camera.setZ(top_lim ) except: pass # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< self.focus = base.camera.getPos() + (dir*5) self.last = task.time return Task.cont Maze = StudyMaze() rootNode.clearModelNodes() rootNode.flattenStrong() # Some text for entry field. bk_text = "" textObject = OnscreenText(text = bk_text, pos = (0.95,-0.95), scale = 0.07,fg=(1,0.5,0.5,1),align=TextNode.ACenter,mayChange=1) run()
Python
# Maze Root root = Entrance(Point3(0,-10,0), dim=Point2(0,0), direction='back') for directory in sorted([d for d in os.listdir('mazes') if os.path.isdir(os.path.join('mazes',d))]): guess = os.path.join(os.getcwd(),os.path.join(os.path.join('mazes',directory),'maze.py')) if os.path.exists(guess): # Todo: Read file, and replace all 'abc/def/ghi.xxx' into os.path.join(os.getcwd(), 'abc/def/ghi.xxx') before execution: execfile(guess)
Python
XXX101_r1 = MazeRoom(root, dim=Point3(50,50,50), offset=Point2(25,25), music='mazes/XXX101/basic.ogg') self.mazeAreas.append(XXX101_r1)
Python
""" FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == This is the integration file for Python. """ import cgi import os import re import string def escape(text, replace=string.replace): """Converts the special characters '<', '>', and '&'. RFC 1866 specifies that these characters be represented in HTML as &lt; &gt; and &amp; respectively. In Python 1.5 we use the new string.replace() function for speed. """ text = replace(text, '&', '&amp;') # must be done 1st text = replace(text, '<', '&lt;') text = replace(text, '>', '&gt;') text = replace(text, '"', '&quot;') text = replace(text, "'", '&#39;') return text # The FCKeditor class class FCKeditor(object): def __init__(self, instanceName): self.InstanceName = instanceName self.BasePath = '/fckeditor/' self.Width = '100%' self.Height = '200' self.ToolbarSet = 'Default' self.Value = ''; self.Config = {} def Create(self): return self.CreateHtml() def CreateHtml(self): HtmlValue = escape(self.Value) Html = "" if (self.IsCompatible()): File = "fckeditor.html" Link = "%seditor/%s?InstanceName=%s" % ( self.BasePath, File, self.InstanceName ) if (self.ToolbarSet is not None): Link += "&amp;Toolbar=%s" % self.ToolbarSet # Render the linked hidden field Html += "<input type=\"hidden\" id=\"%s\" name=\"%s\" value=\"%s\" style=\"display:none\" />" % ( self.InstanceName, self.InstanceName, HtmlValue ) # Render the configurations hidden field Html += "<input type=\"hidden\" id=\"%s___Config\" value=\"%s\" style=\"display:none\" />" % ( self.InstanceName, self.GetConfigFieldString() ) # Render the editor iframe Html += "<iframe id=\"%s\__Frame\" src=\"%s\" width=\"%s\" height=\"%s\" frameborder=\"0\" scrolling=\"no\"></iframe>" % ( self.InstanceName, Link, self.Width, self.Height ) else: if (self.Width.find("%%") < 0): WidthCSS = "%spx" % self.Width else: WidthCSS = self.Width if (self.Height.find("%%") < 0): HeightCSS = "%spx" % self.Height else: HeightCSS = self.Height Html += "<textarea name=\"%s\" rows=\"4\" cols=\"40\" style=\"width: %s; height: %s;\" wrap=\"virtual\">%s</textarea>" % ( self.InstanceName, WidthCSS, HeightCSS, HtmlValue ) return Html def IsCompatible(self): if (os.environ.has_key("HTTP_USER_AGENT")): sAgent = os.environ.get("HTTP_USER_AGENT", "") else: sAgent = "" if (sAgent.find("MSIE") >= 0) and (sAgent.find("mac") < 0) and (sAgent.find("Opera") < 0): i = sAgent.find("MSIE") iVersion = float(sAgent[i+5:i+5+3]) if (iVersion >= 5.5): return True return False elif (sAgent.find("Gecko/") >= 0): i = sAgent.find("Gecko/") iVersion = int(sAgent[i+6:i+6+8]) if (iVersion >= 20030210): return True return False elif (sAgent.find("Opera/") >= 0): i = sAgent.find("Opera/") iVersion = float(sAgent[i+6:i+6+4]) if (iVersion >= 9.5): return True return False elif (sAgent.find("AppleWebKit/") >= 0): p = re.compile('AppleWebKit\/(\d+)', re.IGNORECASE) m = p.search(sAgent) if (m.group(1) >= 522): return True return False else: return False def GetConfigFieldString(self): sParams = "" bFirst = True for sKey in self.Config.keys(): sValue = self.Config[sKey] if (not bFirst): sParams += "&amp;" else: bFirst = False if (sValue): k = escape(sKey) v = escape(sValue) if (sValue == "true"): sParams += "%s=true" % k elif (sValue == "false"): sParams += "%s=false" % k else: sParams += "%s=%s" % (k, v) return sParams
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector for Python (CGI and WSGI). """ import os try: # Windows needs stdio set for binary mode for file upload to work. import msvcrt msvcrt.setmode (0, os.O_BINARY) # stdin = 0 msvcrt.setmode (1, os.O_BINARY) # stdout = 1 except ImportError: pass from fckutil import * from fckoutput import * import config as Config class GetFoldersCommandMixin (object): def getFolders(self, resourceType, currentFolder): """ Purpose: command to recieve a list of folders """ # Map the virtual path to our local server serverPath = mapServerFolder(self.userFilesFolder,currentFolder) s = """<Folders>""" # Open the folders node for someObject in os.listdir(serverPath): someObjectPath = mapServerFolder(serverPath, someObject) if os.path.isdir(someObjectPath): s += """<Folder name="%s" />""" % ( convertToXmlAttribute(someObject) ) s += """</Folders>""" # Close the folders node return s class GetFoldersAndFilesCommandMixin (object): def getFoldersAndFiles(self, resourceType, currentFolder): """ Purpose: command to recieve a list of folders and files """ # Map the virtual path to our local server serverPath = mapServerFolder(self.userFilesFolder,currentFolder) # Open the folders / files node folders = """<Folders>""" files = """<Files>""" for someObject in os.listdir(serverPath): someObjectPath = mapServerFolder(serverPath, someObject) if os.path.isdir(someObjectPath): folders += """<Folder name="%s" />""" % ( convertToXmlAttribute(someObject) ) elif os.path.isfile(someObjectPath): size = os.path.getsize(someObjectPath) if size > 0: size = round(size/1024) if size < 1: size = 1 files += """<File name="%s" size="%d" />""" % ( convertToXmlAttribute(someObject), size ) # Close the folders / files node folders += """</Folders>""" files += """</Files>""" return folders + files class CreateFolderCommandMixin (object): def createFolder(self, resourceType, currentFolder): """ Purpose: command to create a new folder """ errorNo = 0; errorMsg =''; if self.request.has_key("NewFolderName"): newFolder = self.request.get("NewFolderName", None) newFolder = sanitizeFolderName (newFolder) try: newFolderPath = mapServerFolder(self.userFilesFolder, combinePaths(currentFolder, newFolder)) self.createServerFolder(newFolderPath) except Exception, e: errorMsg = str(e).decode('iso-8859-1').encode('utf-8') # warning with encodigns!!! if hasattr(e,'errno'): if e.errno==17: #file already exists errorNo=0 elif e.errno==13: # permission denied errorNo = 103 elif e.errno==36 or e.errno==2 or e.errno==22: # filename too long / no such file / invalid name errorNo = 102 else: errorNo = 110 else: errorNo = 102 return self.sendErrorNode ( errorNo, errorMsg ) def createServerFolder(self, folderPath): "Purpose: physically creates a folder on the server" # No need to check if the parent exists, just create all hierachy try: permissions = Config.ChmodOnFolderCreate if not permissions: os.makedirs(folderPath) except AttributeError: #ChmodOnFolderCreate undefined permissions = 0755 if permissions: oldumask = os.umask(0) os.makedirs(folderPath,mode=0755) os.umask( oldumask ) class UploadFileCommandMixin (object): def uploadFile(self, resourceType, currentFolder): """ Purpose: command to upload files to server (same as FileUpload) """ errorNo = 0 if self.request.has_key("NewFile"): # newFile has all the contents we need newFile = self.request.get("NewFile", "") # Get the file name newFileName = newFile.filename newFileName = sanitizeFileName( newFileName ) newFileNameOnly = removeExtension(newFileName) newFileExtension = getExtension(newFileName).lower() allowedExtensions = Config.AllowedExtensions[resourceType] deniedExtensions = Config.DeniedExtensions[resourceType] if (allowedExtensions): # Check for allowed isAllowed = False if (newFileExtension in allowedExtensions): isAllowed = True elif (deniedExtensions): # Check for denied isAllowed = True if (newFileExtension in deniedExtensions): isAllowed = False else: # No extension limitations isAllowed = True if (isAllowed): # Upload to operating system # Map the virtual path to the local server path currentFolderPath = mapServerFolder(self.userFilesFolder, currentFolder) i = 0 while (True): newFilePath = os.path.join (currentFolderPath,newFileName) if os.path.exists(newFilePath): i += 1 newFileName = "%s(%d).%s" % ( newFileNameOnly, i, newFileExtension ) errorNo= 201 # file renamed else: # Read file contents and write to the desired path (similar to php's move_uploaded_file) fout = file(newFilePath, 'wb') while (True): chunk = newFile.file.read(100000) if not chunk: break fout.write (chunk) fout.close() if os.path.exists ( newFilePath ): doChmod = False try: doChmod = Config.ChmodOnUpload permissions = Config.ChmodOnUpload except AttributeError: #ChmodOnUpload undefined doChmod = True permissions = 0755 if ( doChmod ): oldumask = os.umask(0) os.chmod( newFilePath, permissions ) os.umask( oldumask ) newFileUrl = combinePaths(self.webUserFilesFolder, currentFolder) + newFileName return self.sendUploadResults( errorNo , newFileUrl, newFileName ) else: return self.sendUploadResults( errorNo = 202, customMsg = "" ) else: return self.sendUploadResults( errorNo = 202, customMsg = "No File" )
Python
#!/usr/bin/env python """ * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Configuration file for the File Manager Connector for Python """ # INSTALLATION NOTE: You must set up your server environment accordingly to run # python scripts. This connector requires Python 2.4 or greater. # # Supported operation modes: # * WSGI (recommended): You'll need apache + mod_python + modpython_gateway # or any web server capable of the WSGI python standard # * Plain Old CGI: Any server capable of running standard python scripts # (although mod_python is recommended for performance) # This was the previous connector version operation mode # # If you're using Apache web server, replace the htaccess.txt to to .htaccess, # and set the proper options and paths. # For WSGI and mod_python, you may need to download modpython_gateway from: # http://projects.amor.org/misc/svn/modpython_gateway.py and copy it in this # directory. # SECURITY: You must explicitly enable this "connector". (Set it to "True"). # WARNING: don't just set "ConfigIsEnabled = True", you must be sure that only # authenticated users can access this file or use some kind of session checking. Enabled = False # Path to user files relative to the document root. UserFilesPath = '/userfiles/' # Fill the following value it you prefer to specify the absolute path for the # user files directory. Useful if you are using a virtual directory, symbolic # link or alias. Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'. # Attention: The above 'UserFilesPath' must point to the same directory. # WARNING: GetRootPath may not work in virtual or mod_python configurations, and # may not be thread safe. Use this configuration parameter instead. UserFilesAbsolutePath = '' # Due to security issues with Apache modules, it is recommended to leave the # following setting enabled. ForceSingleExtension = True # What the user can do with this connector ConfigAllowedCommands = [ 'QuickUpload', 'FileUpload', 'GetFolders', 'GetFoldersAndFiles', 'CreateFolder' ] # Allowed Resource Types ConfigAllowedTypes = ['File', 'Image', 'Flash', 'Media'] # After file is uploaded, sometimes it is required to change its permissions # so that it was possible to access it at the later time. # If possible, it is recommended to set more restrictive permissions, like 0755. # Set to 0 to disable this feature. # Note: not needed on Windows-based servers. ChmodOnUpload = 0755 # See comments above. # Used when creating folders that does not exist. ChmodOnFolderCreate = 0755 # Do not touch this 3 lines, see "Configuration settings for each Resource Type" AllowedExtensions = {}; DeniedExtensions = {}; FileTypesPath = {}; FileTypesAbsolutePath = {}; QuickUploadPath = {}; QuickUploadAbsolutePath = {}; # Configuration settings for each Resource Type # # - AllowedExtensions: the possible extensions that can be allowed. # If it is empty then any file type can be uploaded. # - DeniedExtensions: The extensions that won't be allowed. # If it is empty then no restrictions are done here. # # For a file to be uploaded it has to fulfill both the AllowedExtensions # and DeniedExtensions (that's it: not being denied) conditions. # # - FileTypesPath: the virtual folder relative to the document root where # these resources will be located. # Attention: It must start and end with a slash: '/' # # - FileTypesAbsolutePath: the physical path to the above folder. It must be # an absolute path. # If it's an empty string then it will be autocalculated. # Useful if you are using a virtual directory, symbolic link or alias. # Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'. # Attention: The above 'FileTypesPath' must point to the same directory. # Attention: It must end with a slash: '/' # # # - QuickUploadPath: the virtual folder relative to the document root where # these resources will be uploaded using the Upload tab in the resources # dialogs. # Attention: It must start and end with a slash: '/' # # - QuickUploadAbsolutePath: the physical path to the above folder. It must be # an absolute path. # If it's an empty string then it will be autocalculated. # Useful if you are using a virtual directory, symbolic link or alias. # Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'. # Attention: The above 'QuickUploadPath' must point to the same directory. # Attention: It must end with a slash: '/' AllowedExtensions['File'] = ['7z','aiff','asf','avi','bmp','csv','doc','fla','flv','gif','gz','gzip','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','ods','odt','pdf','png','ppt','pxd','qt','ram','rar','rm','rmi','rmvb','rtf','sdc','sitd','swf','sxc','sxw','tar','tgz','tif','tiff','txt','vsd','wav','wma','wmv','xls','xml','zip'] DeniedExtensions['File'] = [] FileTypesPath['File'] = UserFilesPath + 'file/' FileTypesAbsolutePath['File'] = (not UserFilesAbsolutePath == '') and (UserFilesAbsolutePath + 'file/') or '' QuickUploadPath['File'] = FileTypesPath['File'] QuickUploadAbsolutePath['File'] = FileTypesAbsolutePath['File'] AllowedExtensions['Image'] = ['bmp','gif','jpeg','jpg','png'] DeniedExtensions['Image'] = [] FileTypesPath['Image'] = UserFilesPath + 'image/' FileTypesAbsolutePath['Image'] = (not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'image/' or '' QuickUploadPath['Image'] = FileTypesPath['Image'] QuickUploadAbsolutePath['Image']= FileTypesAbsolutePath['Image'] AllowedExtensions['Flash'] = ['swf','flv'] DeniedExtensions['Flash'] = [] FileTypesPath['Flash'] = UserFilesPath + 'flash/' FileTypesAbsolutePath['Flash'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'flash/' or '' QuickUploadPath['Flash'] = FileTypesPath['Flash'] QuickUploadAbsolutePath['Flash']= FileTypesAbsolutePath['Flash'] AllowedExtensions['Media'] = ['aiff','asf','avi','bmp','fla', 'flv','gif','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','png','qt','ram','rm','rmi','rmvb','swf','tif','tiff','wav','wma','wmv'] DeniedExtensions['Media'] = [] FileTypesPath['Media'] = UserFilesPath + 'media/' FileTypesAbsolutePath['Media'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'media/' or '' QuickUploadPath['Media'] = FileTypesPath['Media'] QuickUploadAbsolutePath['Media']= FileTypesAbsolutePath['Media']
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Utility functions for the File Manager Connector for Python """ import string, re import os import config as Config # Generic manipulation functions def removeExtension(fileName): index = fileName.rindex(".") newFileName = fileName[0:index] return newFileName def getExtension(fileName): index = fileName.rindex(".") + 1 fileExtension = fileName[index:] return fileExtension def removeFromStart(string, char): return string.lstrip(char) def removeFromEnd(string, char): return string.rstrip(char) # Path functions def combinePaths( basePath, folder ): return removeFromEnd( basePath, '/' ) + '/' + removeFromStart( folder, '/' ) def getFileName(filename): " Purpose: helper function to extrapolate the filename " for splitChar in ["/", "\\"]: array = filename.split(splitChar) if (len(array) > 1): filename = array[-1] return filename def sanitizeFolderName( newFolderName ): "Do a cleanup of the folder name to avoid possible problems" # Remove . \ / | : ? * " < > and control characters return re.sub( '\\.|\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[\x00-\x1f\x7f-\x9f]', '_', newFolderName ) def sanitizeFileName( newFileName ): "Do a cleanup of the file name to avoid possible problems" # Replace dots in the name with underscores (only one dot can be there... security issue). if ( Config.ForceSingleExtension ): # remove dots newFileName = re.sub ( '\\.(?![^.]*$)', '_', newFileName ) ; newFileName = newFileName.replace('\\','/') # convert windows to unix path newFileName = os.path.basename (newFileName) # strip directories # Remove \ / | : ? * return re.sub ( '\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[\x00-\x1f\x7f-\x9f]/', '_', newFileName ) def getCurrentFolder(currentFolder): if not currentFolder: currentFolder = '/' # Check the current folder syntax (must begin and end with a slash). if (currentFolder[-1] <> "/"): currentFolder += "/" if (currentFolder[0] <> "/"): currentFolder = "/" + currentFolder # Ensure the folder path has no double-slashes while '//' in currentFolder: currentFolder = currentFolder.replace('//','/') # Check for invalid folder paths (..) if '..' in currentFolder or '\\' in currentFolder: return None # Check for invalid folder paths (..) if re.search( '(/\\.)|(//)|([\\\\:\\*\\?\\""\\<\\>\\|]|[\x00-\x1F]|[\x7f-\x9f])', currentFolder ): return None return currentFolder def mapServerPath( environ, url): " Emulate the asp Server.mapPath function. Given an url path return the physical directory that it corresponds to " # This isn't correct but for the moment there's no other solution # If this script is under a virtual directory or symlink it will detect the problem and stop return combinePaths( getRootPath(environ), url ) def mapServerFolder(resourceTypePath, folderPath): return combinePaths ( resourceTypePath , folderPath ) def getRootPath(environ): "Purpose: returns the root path on the server" # WARNING: this may not be thread safe, and doesn't work w/ VirtualServer/mod_python # Use Config.UserFilesAbsolutePath instead if environ.has_key('DOCUMENT_ROOT'): return environ['DOCUMENT_ROOT'] else: realPath = os.path.realpath( './' ) selfPath = environ['SCRIPT_FILENAME'] selfPath = selfPath [ : selfPath.rfind( '/' ) ] selfPath = selfPath.replace( '/', os.path.sep) position = realPath.find(selfPath) # This can check only that this script isn't run from a virtual dir # But it avoids the problems that arise if it isn't checked raise realPath if ( position < 0 or position <> len(realPath) - len(selfPath) or realPath[ : position ]==''): raise Exception('Sorry, can\'t map "UserFilesPath" to a physical path. You must set the "UserFilesAbsolutePath" value in "editor/filemanager/connectors/py/config.py".') return realPath[ : position ]
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector/QuickUpload for Python (WSGI wrapper). See config.py for configuration settings """ from connector import FCKeditorConnector from upload import FCKeditorQuickUpload import cgitb from cStringIO import StringIO # Running from WSGI capable server (recomended) def App(environ, start_response): "WSGI entry point. Run the connector" if environ['SCRIPT_NAME'].endswith("connector.py"): conn = FCKeditorConnector(environ) elif environ['SCRIPT_NAME'].endswith("upload.py"): conn = FCKeditorQuickUpload(environ) else: start_response ("200 Ok", [('Content-Type','text/html')]) yield "Unknown page requested: " yield environ['SCRIPT_NAME'] return try: # run the connector data = conn.doResponse() # Start WSGI response: start_response ("200 Ok", conn.headers) # Send response text yield data except: start_response("500 Internal Server Error",[("Content-type","text/html")]) file = StringIO() cgitb.Hook(file = file).handle() yield file.getvalue()
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector for Python (CGI and WSGI). """ import os try: # Windows needs stdio set for binary mode for file upload to work. import msvcrt msvcrt.setmode (0, os.O_BINARY) # stdin = 0 msvcrt.setmode (1, os.O_BINARY) # stdout = 1 except ImportError: pass from fckutil import * from fckoutput import * import config as Config class GetFoldersCommandMixin (object): def getFolders(self, resourceType, currentFolder): """ Purpose: command to recieve a list of folders """ # Map the virtual path to our local server serverPath = mapServerFolder(self.userFilesFolder,currentFolder) s = """<Folders>""" # Open the folders node for someObject in os.listdir(serverPath): someObjectPath = mapServerFolder(serverPath, someObject) if os.path.isdir(someObjectPath): s += """<Folder name="%s" />""" % ( convertToXmlAttribute(someObject) ) s += """</Folders>""" # Close the folders node return s class GetFoldersAndFilesCommandMixin (object): def getFoldersAndFiles(self, resourceType, currentFolder): """ Purpose: command to recieve a list of folders and files """ # Map the virtual path to our local server serverPath = mapServerFolder(self.userFilesFolder,currentFolder) # Open the folders / files node folders = """<Folders>""" files = """<Files>""" for someObject in os.listdir(serverPath): someObjectPath = mapServerFolder(serverPath, someObject) if os.path.isdir(someObjectPath): folders += """<Folder name="%s" />""" % ( convertToXmlAttribute(someObject) ) elif os.path.isfile(someObjectPath): size = os.path.getsize(someObjectPath) if size > 0: size = round(size/1024) if size < 1: size = 1 files += """<File name="%s" size="%d" />""" % ( convertToXmlAttribute(someObject), size ) # Close the folders / files node folders += """</Folders>""" files += """</Files>""" return folders + files class CreateFolderCommandMixin (object): def createFolder(self, resourceType, currentFolder): """ Purpose: command to create a new folder """ errorNo = 0; errorMsg =''; if self.request.has_key("NewFolderName"): newFolder = self.request.get("NewFolderName", None) newFolder = sanitizeFolderName (newFolder) try: newFolderPath = mapServerFolder(self.userFilesFolder, combinePaths(currentFolder, newFolder)) self.createServerFolder(newFolderPath) except Exception, e: errorMsg = str(e).decode('iso-8859-1').encode('utf-8') # warning with encodigns!!! if hasattr(e,'errno'): if e.errno==17: #file already exists errorNo=0 elif e.errno==13: # permission denied errorNo = 103 elif e.errno==36 or e.errno==2 or e.errno==22: # filename too long / no such file / invalid name errorNo = 102 else: errorNo = 110 else: errorNo = 102 return self.sendErrorNode ( errorNo, errorMsg ) def createServerFolder(self, folderPath): "Purpose: physically creates a folder on the server" # No need to check if the parent exists, just create all hierachy try: permissions = Config.ChmodOnFolderCreate if not permissions: os.makedirs(folderPath) except AttributeError: #ChmodOnFolderCreate undefined permissions = 0755 if permissions: oldumask = os.umask(0) os.makedirs(folderPath,mode=0755) os.umask( oldumask ) class UploadFileCommandMixin (object): def uploadFile(self, resourceType, currentFolder): """ Purpose: command to upload files to server (same as FileUpload) """ errorNo = 0 if self.request.has_key("NewFile"): # newFile has all the contents we need newFile = self.request.get("NewFile", "") # Get the file name newFileName = newFile.filename newFileName = sanitizeFileName( newFileName ) newFileNameOnly = removeExtension(newFileName) newFileExtension = getExtension(newFileName).lower() allowedExtensions = Config.AllowedExtensions[resourceType] deniedExtensions = Config.DeniedExtensions[resourceType] if (allowedExtensions): # Check for allowed isAllowed = False if (newFileExtension in allowedExtensions): isAllowed = True elif (deniedExtensions): # Check for denied isAllowed = True if (newFileExtension in deniedExtensions): isAllowed = False else: # No extension limitations isAllowed = True if (isAllowed): # Upload to operating system # Map the virtual path to the local server path currentFolderPath = mapServerFolder(self.userFilesFolder, currentFolder) i = 0 while (True): newFilePath = os.path.join (currentFolderPath,newFileName) if os.path.exists(newFilePath): i += 1 newFileName = "%s(%d).%s" % ( newFileNameOnly, i, newFileExtension ) errorNo= 201 # file renamed else: # Read file contents and write to the desired path (similar to php's move_uploaded_file) fout = file(newFilePath, 'wb') while (True): chunk = newFile.file.read(100000) if not chunk: break fout.write (chunk) fout.close() if os.path.exists ( newFilePath ): doChmod = False try: doChmod = Config.ChmodOnUpload permissions = Config.ChmodOnUpload except AttributeError: #ChmodOnUpload undefined doChmod = True permissions = 0755 if ( doChmod ): oldumask = os.umask(0) os.chmod( newFilePath, permissions ) os.umask( oldumask ) newFileUrl = combinePaths(self.webUserFilesFolder, currentFolder) + newFileName return self.sendUploadResults( errorNo , newFileUrl, newFileName ) else: return self.sendUploadResults( errorNo = 202, customMsg = "" ) else: return self.sendUploadResults( errorNo = 202, customMsg = "No File" )
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == This is the "File Uploader" for Python """ import os from fckutil import * from fckcommands import * # default command's implementation from fckconnector import FCKeditorConnectorBase # import base connector import config as Config class FCKeditorQuickUpload( FCKeditorConnectorBase, UploadFileCommandMixin, BaseHttpMixin, BaseHtmlMixin): def doResponse(self): "Main function. Process the request, set headers and return a string as response." # Check if this connector is disabled if not(Config.Enabled): return self.sendUploadResults(1, "This file uploader is disabled. Please check the \"editor/filemanager/connectors/py/config.py\"") command = 'QuickUpload' # The file type (from the QueryString, by default 'File'). resourceType = self.request.get('Type','File') currentFolder = "/" # Check for invalid paths if currentFolder is None: return self.sendUploadResults(102, '', '', "") # Check if it is an allowed command if ( not command in Config.ConfigAllowedCommands ): return self.sendUploadResults( 1, '', '', 'The %s command isn\'t allowed' % command ) if ( not resourceType in Config.ConfigAllowedTypes ): return self.sendUploadResults( 1, '', '', 'Invalid type specified' ) # Setup paths self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType] self.webUserFilesFolder = Config.QuickUploadPath[resourceType] if not self.userFilesFolder: # no absolute path given (dangerous...) self.userFilesFolder = mapServerPath(self.environ, self.webUserFilesFolder) # Ensure that the directory exists. if not os.path.exists(self.userFilesFolder): try: self.createServerFoldercreateServerFolder( self.userFilesFolder ) except: return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ") # File upload doesn't have to return XML, so intercept here return self.uploadFile(resourceType, currentFolder) # Running from command line (plain old CGI) if __name__ == '__main__': try: # Create a Connector Instance conn = FCKeditorQuickUpload() data = conn.doResponse() for header in conn.headers: if not header is None: print '%s: %s' % header print print data except: print "Content-Type: text/plain" print import cgi cgi.print_exception()
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Base Connector for Python (CGI and WSGI). See config.py for configuration settings """ import cgi, os from fckutil import * from fckcommands import * # default command's implementation from fckoutput import * # base http, xml and html output mixins import config as Config class FCKeditorConnectorBase( object ): "The base connector class. Subclass it to extend functionality (see Zope example)" def __init__(self, environ=None): "Constructor: Here you should parse request fields, initialize variables, etc." self.request = FCKeditorRequest(environ) # Parse request self.headers = [] # Clean Headers if environ: self.environ = environ else: self.environ = os.environ # local functions def setHeader(self, key, value): self.headers.append ((key, value)) return class FCKeditorRequest(object): "A wrapper around the request object" def __init__(self, environ): if environ: # WSGI self.request = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ, keep_blank_values=1) self.environ = environ else: # plain old cgi self.environ = os.environ self.request = cgi.FieldStorage() if 'REQUEST_METHOD' in self.environ and 'QUERY_STRING' in self.environ: if self.environ['REQUEST_METHOD'].upper()=='POST': # we are in a POST, but GET query_string exists # cgi parses by default POST data, so parse GET QUERY_STRING too self.get_request = cgi.FieldStorage(fp=None, environ={ 'REQUEST_METHOD':'GET', 'QUERY_STRING':self.environ['QUERY_STRING'], }, ) else: self.get_request={} def has_key(self, key): return self.request.has_key(key) or self.get_request.has_key(key) def get(self, key, default=None): if key in self.request.keys(): field = self.request[key] elif key in self.get_request.keys(): field = self.get_request[key] else: return default if hasattr(field,"filename") and field.filename: #file upload, do not convert return value return field else: return field.value
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector for Python (CGI and WSGI). See config.py for configuration settings """ import os from fckutil import * from fckcommands import * # default command's implementation from fckoutput import * # base http, xml and html output mixins from fckconnector import FCKeditorConnectorBase # import base connector import config as Config class FCKeditorConnector( FCKeditorConnectorBase, GetFoldersCommandMixin, GetFoldersAndFilesCommandMixin, CreateFolderCommandMixin, UploadFileCommandMixin, BaseHttpMixin, BaseXmlMixin, BaseHtmlMixin ): "The Standard connector class." def doResponse(self): "Main function. Process the request, set headers and return a string as response." s = "" # Check if this connector is disabled if not(Config.Enabled): return self.sendError(1, "This connector is disabled. Please check the connector configurations in \"editor/filemanager/connectors/py/config.py\" and try again.") # Make sure we have valid inputs for key in ("Command","Type","CurrentFolder"): if not self.request.has_key (key): return # Get command, resource type and current folder command = self.request.get("Command") resourceType = self.request.get("Type") currentFolder = getCurrentFolder(self.request.get("CurrentFolder")) # Check for invalid paths if currentFolder is None: if (command == "FileUpload"): return self.sendUploadResults( errorNo = 102, customMsg = "" ) else: return self.sendError(102, "") # Check if it is an allowed command if ( not command in Config.ConfigAllowedCommands ): return self.sendError( 1, 'The %s command isn\'t allowed' % command ) if ( not resourceType in Config.ConfigAllowedTypes ): return self.sendError( 1, 'Invalid type specified' ) # Setup paths if command == "QuickUpload": self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType] self.webUserFilesFolder = Config.QuickUploadPath[resourceType] else: self.userFilesFolder = Config.FileTypesAbsolutePath[resourceType] self.webUserFilesFolder = Config.FileTypesPath[resourceType] if not self.userFilesFolder: # no absolute path given (dangerous...) self.userFilesFolder = mapServerPath(self.environ, self.webUserFilesFolder) # Ensure that the directory exists. if not os.path.exists(self.userFilesFolder): try: self.createServerFolder( self.userFilesFolder ) except: return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ") # File upload doesn't have to return XML, so intercept here if (command == "FileUpload"): return self.uploadFile(resourceType, currentFolder) # Create Url url = combinePaths( self.webUserFilesFolder, currentFolder ) # Begin XML s += self.createXmlHeader(command, resourceType, currentFolder, url) # Execute the command selector = {"GetFolders": self.getFolders, "GetFoldersAndFiles": self.getFoldersAndFiles, "CreateFolder": self.createFolder, } s += selector[command](resourceType, currentFolder) s += self.createXmlFooter() return s # Running from command line (plain old CGI) if __name__ == '__main__': try: # Create a Connector Instance conn = FCKeditorConnector() data = conn.doResponse() for header in conn.headers: print '%s: %s' % header print print data except: print "Content-Type: text/plain" print import cgi cgi.print_exception()
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector for Python and Zope. This code was not tested at all. It just was ported from pre 2.5 release, so for further reference see \editor\filemanager\browser\default\connectors\py\connector.py in previous releases. """ from fckutil import * from connector import * import config as Config class FCKeditorConnectorZope(FCKeditorConnector): """ Zope versiof FCKeditorConnector """ # Allow access (Zope) __allow_access_to_unprotected_subobjects__ = 1 def __init__(self, context=None): """ Constructor """ FCKeditorConnector.__init__(self, environ=None) # call superclass constructor # Instance Attributes self.context = context self.request = FCKeditorRequest(context) def getZopeRootContext(self): if self.zopeRootContext is None: self.zopeRootContext = self.context.getPhysicalRoot() return self.zopeRootContext def getZopeUploadContext(self): if self.zopeUploadContext is None: folderNames = self.userFilesFolder.split("/") c = self.getZopeRootContext() for folderName in folderNames: if (folderName <> ""): c = c[folderName] self.zopeUploadContext = c return self.zopeUploadContext def setHeader(self, key, value): self.context.REQUEST.RESPONSE.setHeader(key, value) def getFolders(self, resourceType, currentFolder): # Open the folders node s = "" s += """<Folders>""" zopeFolder = self.findZopeFolder(resourceType, currentFolder) for (name, o) in zopeFolder.objectItems(["Folder"]): s += """<Folder name="%s" />""" % ( convertToXmlAttribute(name) ) # Close the folders node s += """</Folders>""" return s def getZopeFoldersAndFiles(self, resourceType, currentFolder): folders = self.getZopeFolders(resourceType, currentFolder) files = self.getZopeFiles(resourceType, currentFolder) s = folders + files return s def getZopeFiles(self, resourceType, currentFolder): # Open the files node s = "" s += """<Files>""" zopeFolder = self.findZopeFolder(resourceType, currentFolder) for (name, o) in zopeFolder.objectItems(["File","Image"]): s += """<File name="%s" size="%s" />""" % ( convertToXmlAttribute(name), ((o.get_size() / 1024) + 1) ) # Close the files node s += """</Files>""" return s def findZopeFolder(self, resourceType, folderName): # returns the context of the resource / folder zopeFolder = self.getZopeUploadContext() folderName = self.removeFromStart(folderName, "/") folderName = self.removeFromEnd(folderName, "/") if (resourceType <> ""): try: zopeFolder = zopeFolder[resourceType] except: zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=resourceType, title=resourceType) zopeFolder = zopeFolder[resourceType] if (folderName <> ""): folderNames = folderName.split("/") for folderName in folderNames: zopeFolder = zopeFolder[folderName] return zopeFolder def createFolder(self, resourceType, currentFolder): # Find out where we are zopeFolder = self.findZopeFolder(resourceType, currentFolder) errorNo = 0 errorMsg = "" if self.request.has_key("NewFolderName"): newFolder = self.request.get("NewFolderName", None) zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=newFolder, title=newFolder) else: errorNo = 102 return self.sendErrorNode ( errorNo, errorMsg ) def uploadFile(self, resourceType, currentFolder, count=None): zopeFolder = self.findZopeFolder(resourceType, currentFolder) file = self.request.get("NewFile", None) fileName = self.getFileName(file.filename) fileNameOnly = self.removeExtension(fileName) fileExtension = self.getExtension(fileName).lower() if (count): nid = "%s.%s.%s" % (fileNameOnly, count, fileExtension) else: nid = fileName title = nid try: zopeFolder.manage_addProduct['OFSP'].manage_addFile( id=nid, title=title, file=file.read() ) except: if (count): count += 1 else: count = 1 return self.zopeFileUpload(resourceType, currentFolder, count) return self.sendUploadResults( 0 ) class FCKeditorRequest(object): "A wrapper around the request object" def __init__(self, context=None): r = context.REQUEST self.request = r def has_key(self, key): return self.request.has_key(key) def get(self, key, default=None): return self.request.get(key, default) """ Running from zope, you will need to modify this connector. If you have uploaded the FCKeditor into Zope (like me), you need to move this connector out of Zope, and replace the "connector" with an alias as below. The key to it is to pass the Zope context in, as we then have a like to the Zope context. ## Script (Python) "connector.py" ##bind container=container ##bind context=context ##bind namespace= ##bind script=script ##bind subpath=traverse_subpath ##parameters=*args, **kws ##title=ALIAS ## import Products.zope as connector return connector.FCKeditorConnectorZope(context=context).doResponse() """
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector for Python (CGI and WSGI). """ from time import gmtime, strftime import string def escape(text, replace=string.replace): """ Converts the special characters '<', '>', and '&'. RFC 1866 specifies that these characters be represented in HTML as &lt; &gt; and &amp; respectively. In Python 1.5 we use the new string.replace() function for speed. """ text = replace(text, '&', '&amp;') # must be done 1st text = replace(text, '<', '&lt;') text = replace(text, '>', '&gt;') text = replace(text, '"', '&quot;') return text def convertToXmlAttribute(value): if (value is None): value = "" return escape(value) class BaseHttpMixin(object): def setHttpHeaders(self, content_type='text/xml'): "Purpose: to prepare the headers for the xml to return" # Prevent the browser from caching the result. # Date in the past self.setHeader('Expires','Mon, 26 Jul 1997 05:00:00 GMT') # always modified self.setHeader('Last-Modified',strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime())) # HTTP/1.1 self.setHeader('Cache-Control','no-store, no-cache, must-revalidate') self.setHeader('Cache-Control','post-check=0, pre-check=0') # HTTP/1.0 self.setHeader('Pragma','no-cache') # Set the response format. self.setHeader( 'Content-Type', content_type + '; charset=utf-8' ) return class BaseXmlMixin(object): def createXmlHeader(self, command, resourceType, currentFolder, url): "Purpose: returns the xml header" self.setHttpHeaders() # Create the XML document header s = """<?xml version="1.0" encoding="utf-8" ?>""" # Create the main connector node s += """<Connector command="%s" resourceType="%s">""" % ( command, resourceType ) # Add the current folder node s += """<CurrentFolder path="%s" url="%s" />""" % ( convertToXmlAttribute(currentFolder), convertToXmlAttribute(url), ) return s def createXmlFooter(self): "Purpose: returns the xml footer" return """</Connector>""" def sendError(self, number, text): "Purpose: in the event of an error, return an xml based error" self.setHttpHeaders() return ("""<?xml version="1.0" encoding="utf-8" ?>""" + """<Connector>""" + self.sendErrorNode (number, text) + """</Connector>""" ) def sendErrorNode(self, number, text): if number != 1: return """<Error number="%s" />""" % (number) else: return """<Error number="%s" text="%s" />""" % (number, convertToXmlAttribute(text)) class BaseHtmlMixin(object): def sendUploadResults( self, errorNo = 0, fileUrl = '', fileName = '', customMsg = '' ): self.setHttpHeaders("text/html") "This is the function that sends the results of the uploading process" "Minified version of the document.domain automatic fix script (#1919)." "The original script can be found at _dev/domain_fix_template.js" return """<script type="text/javascript"> (function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})(); window.parent.OnUploadCompleted(%(errorNumber)s,"%(fileUrl)s","%(fileName)s","%(customMsg)s"); </script>""" % { 'errorNumber': errorNo, 'fileUrl': fileUrl.replace ('"', '\\"'), 'fileName': fileName.replace ( '"', '\\"' ) , 'customMsg': customMsg.replace ( '"', '\\"' ), }
Python
#!/usr/bin/env python """ * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Configuration file for the File Manager Connector for Python """ # INSTALLATION NOTE: You must set up your server environment accordingly to run # python scripts. This connector requires Python 2.4 or greater. # # Supported operation modes: # * WSGI (recommended): You'll need apache + mod_python + modpython_gateway # or any web server capable of the WSGI python standard # * Plain Old CGI: Any server capable of running standard python scripts # (although mod_python is recommended for performance) # This was the previous connector version operation mode # # If you're using Apache web server, replace the htaccess.txt to to .htaccess, # and set the proper options and paths. # For WSGI and mod_python, you may need to download modpython_gateway from: # http://projects.amor.org/misc/svn/modpython_gateway.py and copy it in this # directory. # SECURITY: You must explicitly enable this "connector". (Set it to "True"). # WARNING: don't just set "ConfigIsEnabled = True", you must be sure that only # authenticated users can access this file or use some kind of session checking. Enabled = False # Path to user files relative to the document root. UserFilesPath = '/userfiles/' # Fill the following value it you prefer to specify the absolute path for the # user files directory. Useful if you are using a virtual directory, symbolic # link or alias. Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'. # Attention: The above 'UserFilesPath' must point to the same directory. # WARNING: GetRootPath may not work in virtual or mod_python configurations, and # may not be thread safe. Use this configuration parameter instead. UserFilesAbsolutePath = '' # Due to security issues with Apache modules, it is recommended to leave the # following setting enabled. ForceSingleExtension = True # What the user can do with this connector ConfigAllowedCommands = [ 'QuickUpload', 'FileUpload', 'GetFolders', 'GetFoldersAndFiles', 'CreateFolder' ] # Allowed Resource Types ConfigAllowedTypes = ['File', 'Image', 'Flash', 'Media'] # After file is uploaded, sometimes it is required to change its permissions # so that it was possible to access it at the later time. # If possible, it is recommended to set more restrictive permissions, like 0755. # Set to 0 to disable this feature. # Note: not needed on Windows-based servers. ChmodOnUpload = 0755 # See comments above. # Used when creating folders that does not exist. ChmodOnFolderCreate = 0755 # Do not touch this 3 lines, see "Configuration settings for each Resource Type" AllowedExtensions = {}; DeniedExtensions = {}; FileTypesPath = {}; FileTypesAbsolutePath = {}; QuickUploadPath = {}; QuickUploadAbsolutePath = {}; # Configuration settings for each Resource Type # # - AllowedExtensions: the possible extensions that can be allowed. # If it is empty then any file type can be uploaded. # - DeniedExtensions: The extensions that won't be allowed. # If it is empty then no restrictions are done here. # # For a file to be uploaded it has to fulfill both the AllowedExtensions # and DeniedExtensions (that's it: not being denied) conditions. # # - FileTypesPath: the virtual folder relative to the document root where # these resources will be located. # Attention: It must start and end with a slash: '/' # # - FileTypesAbsolutePath: the physical path to the above folder. It must be # an absolute path. # If it's an empty string then it will be autocalculated. # Useful if you are using a virtual directory, symbolic link or alias. # Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'. # Attention: The above 'FileTypesPath' must point to the same directory. # Attention: It must end with a slash: '/' # # # - QuickUploadPath: the virtual folder relative to the document root where # these resources will be uploaded using the Upload tab in the resources # dialogs. # Attention: It must start and end with a slash: '/' # # - QuickUploadAbsolutePath: the physical path to the above folder. It must be # an absolute path. # If it's an empty string then it will be autocalculated. # Useful if you are using a virtual directory, symbolic link or alias. # Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'. # Attention: The above 'QuickUploadPath' must point to the same directory. # Attention: It must end with a slash: '/' AllowedExtensions['File'] = ['7z','aiff','asf','avi','bmp','csv','doc','fla','flv','gif','gz','gzip','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','ods','odt','pdf','png','ppt','pxd','qt','ram','rar','rm','rmi','rmvb','rtf','sdc','sitd','swf','sxc','sxw','tar','tgz','tif','tiff','txt','vsd','wav','wma','wmv','xls','xml','zip'] DeniedExtensions['File'] = [] FileTypesPath['File'] = UserFilesPath + 'file/' FileTypesAbsolutePath['File'] = (not UserFilesAbsolutePath == '') and (UserFilesAbsolutePath + 'file/') or '' QuickUploadPath['File'] = FileTypesPath['File'] QuickUploadAbsolutePath['File'] = FileTypesAbsolutePath['File'] AllowedExtensions['Image'] = ['bmp','gif','jpeg','jpg','png'] DeniedExtensions['Image'] = [] FileTypesPath['Image'] = UserFilesPath + 'image/' FileTypesAbsolutePath['Image'] = (not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'image/' or '' QuickUploadPath['Image'] = FileTypesPath['Image'] QuickUploadAbsolutePath['Image']= FileTypesAbsolutePath['Image'] AllowedExtensions['Flash'] = ['swf','flv'] DeniedExtensions['Flash'] = [] FileTypesPath['Flash'] = UserFilesPath + 'flash/' FileTypesAbsolutePath['Flash'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'flash/' or '' QuickUploadPath['Flash'] = FileTypesPath['Flash'] QuickUploadAbsolutePath['Flash']= FileTypesAbsolutePath['Flash'] AllowedExtensions['Media'] = ['aiff','asf','avi','bmp','fla', 'flv','gif','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','png','qt','ram','rm','rmi','rmvb','swf','tif','tiff','wav','wma','wmv'] DeniedExtensions['Media'] = [] FileTypesPath['Media'] = UserFilesPath + 'media/' FileTypesAbsolutePath['Media'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'media/' or '' QuickUploadPath['Media'] = FileTypesPath['Media'] QuickUploadAbsolutePath['Media']= FileTypesAbsolutePath['Media']
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Base Connector for Python (CGI and WSGI). See config.py for configuration settings """ import cgi, os from fckutil import * from fckcommands import * # default command's implementation from fckoutput import * # base http, xml and html output mixins import config as Config class FCKeditorConnectorBase( object ): "The base connector class. Subclass it to extend functionality (see Zope example)" def __init__(self, environ=None): "Constructor: Here you should parse request fields, initialize variables, etc." self.request = FCKeditorRequest(environ) # Parse request self.headers = [] # Clean Headers if environ: self.environ = environ else: self.environ = os.environ # local functions def setHeader(self, key, value): self.headers.append ((key, value)) return class FCKeditorRequest(object): "A wrapper around the request object" def __init__(self, environ): if environ: # WSGI self.request = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ, keep_blank_values=1) self.environ = environ else: # plain old cgi self.environ = os.environ self.request = cgi.FieldStorage() if 'REQUEST_METHOD' in self.environ and 'QUERY_STRING' in self.environ: if self.environ['REQUEST_METHOD'].upper()=='POST': # we are in a POST, but GET query_string exists # cgi parses by default POST data, so parse GET QUERY_STRING too self.get_request = cgi.FieldStorage(fp=None, environ={ 'REQUEST_METHOD':'GET', 'QUERY_STRING':self.environ['QUERY_STRING'], }, ) else: self.get_request={} def has_key(self, key): return self.request.has_key(key) or self.get_request.has_key(key) def get(self, key, default=None): if key in self.request.keys(): field = self.request[key] elif key in self.get_request.keys(): field = self.get_request[key] else: return default if hasattr(field,"filename") and field.filename: #file upload, do not convert return value return field else: return field.value
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector for Python (CGI and WSGI). See config.py for configuration settings """ import os from fckutil import * from fckcommands import * # default command's implementation from fckoutput import * # base http, xml and html output mixins from fckconnector import FCKeditorConnectorBase # import base connector import config as Config class FCKeditorConnector( FCKeditorConnectorBase, GetFoldersCommandMixin, GetFoldersAndFilesCommandMixin, CreateFolderCommandMixin, UploadFileCommandMixin, BaseHttpMixin, BaseXmlMixin, BaseHtmlMixin ): "The Standard connector class." def doResponse(self): "Main function. Process the request, set headers and return a string as response." s = "" # Check if this connector is disabled if not(Config.Enabled): return self.sendError(1, "This connector is disabled. Please check the connector configurations in \"editor/filemanager/connectors/py/config.py\" and try again.") # Make sure we have valid inputs for key in ("Command","Type","CurrentFolder"): if not self.request.has_key (key): return # Get command, resource type and current folder command = self.request.get("Command") resourceType = self.request.get("Type") currentFolder = getCurrentFolder(self.request.get("CurrentFolder")) # Check for invalid paths if currentFolder is None: if (command == "FileUpload"): return self.sendUploadResults( errorNo = 102, customMsg = "" ) else: return self.sendError(102, "") # Check if it is an allowed command if ( not command in Config.ConfigAllowedCommands ): return self.sendError( 1, 'The %s command isn\'t allowed' % command ) if ( not resourceType in Config.ConfigAllowedTypes ): return self.sendError( 1, 'Invalid type specified' ) # Setup paths if command == "QuickUpload": self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType] self.webUserFilesFolder = Config.QuickUploadPath[resourceType] else: self.userFilesFolder = Config.FileTypesAbsolutePath[resourceType] self.webUserFilesFolder = Config.FileTypesPath[resourceType] if not self.userFilesFolder: # no absolute path given (dangerous...) self.userFilesFolder = mapServerPath(self.environ, self.webUserFilesFolder) # Ensure that the directory exists. if not os.path.exists(self.userFilesFolder): try: self.createServerFolder( self.userFilesFolder ) except: return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ") # File upload doesn't have to return XML, so intercept here if (command == "FileUpload"): return self.uploadFile(resourceType, currentFolder) # Create Url url = combinePaths( self.webUserFilesFolder, currentFolder ) # Begin XML s += self.createXmlHeader(command, resourceType, currentFolder, url) # Execute the command selector = {"GetFolders": self.getFolders, "GetFoldersAndFiles": self.getFoldersAndFiles, "CreateFolder": self.createFolder, } s += selector[command](resourceType, currentFolder) s += self.createXmlFooter() return s # Running from command line (plain old CGI) if __name__ == '__main__': try: # Create a Connector Instance conn = FCKeditorConnector() data = conn.doResponse() for header in conn.headers: print '%s: %s' % header print print data except: print "Content-Type: text/plain" print import cgi cgi.print_exception()
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Utility functions for the File Manager Connector for Python """ import string, re import os import config as Config # Generic manipulation functions def removeExtension(fileName): index = fileName.rindex(".") newFileName = fileName[0:index] return newFileName def getExtension(fileName): index = fileName.rindex(".") + 1 fileExtension = fileName[index:] return fileExtension def removeFromStart(string, char): return string.lstrip(char) def removeFromEnd(string, char): return string.rstrip(char) # Path functions def combinePaths( basePath, folder ): return removeFromEnd( basePath, '/' ) + '/' + removeFromStart( folder, '/' ) def getFileName(filename): " Purpose: helper function to extrapolate the filename " for splitChar in ["/", "\\"]: array = filename.split(splitChar) if (len(array) > 1): filename = array[-1] return filename def sanitizeFolderName( newFolderName ): "Do a cleanup of the folder name to avoid possible problems" # Remove . \ / | : ? * " < > and control characters return re.sub( '\\.|\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[\x00-\x1f\x7f-\x9f]', '_', newFolderName ) def sanitizeFileName( newFileName ): "Do a cleanup of the file name to avoid possible problems" # Replace dots in the name with underscores (only one dot can be there... security issue). if ( Config.ForceSingleExtension ): # remove dots newFileName = re.sub ( '\\.(?![^.]*$)', '_', newFileName ) ; newFileName = newFileName.replace('\\','/') # convert windows to unix path newFileName = os.path.basename (newFileName) # strip directories # Remove \ / | : ? * return re.sub ( '\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[\x00-\x1f\x7f-\x9f]/', '_', newFileName ) def getCurrentFolder(currentFolder): if not currentFolder: currentFolder = '/' # Check the current folder syntax (must begin and end with a slash). if (currentFolder[-1] <> "/"): currentFolder += "/" if (currentFolder[0] <> "/"): currentFolder = "/" + currentFolder # Ensure the folder path has no double-slashes while '//' in currentFolder: currentFolder = currentFolder.replace('//','/') # Check for invalid folder paths (..) if '..' in currentFolder or '\\' in currentFolder: return None # Check for invalid folder paths (..) if re.search( '(/\\.)|(//)|([\\\\:\\*\\?\\""\\<\\>\\|]|[\x00-\x1F]|[\x7f-\x9f])', currentFolder ): return None return currentFolder def mapServerPath( environ, url): " Emulate the asp Server.mapPath function. Given an url path return the physical directory that it corresponds to " # This isn't correct but for the moment there's no other solution # If this script is under a virtual directory or symlink it will detect the problem and stop return combinePaths( getRootPath(environ), url ) def mapServerFolder(resourceTypePath, folderPath): return combinePaths ( resourceTypePath , folderPath ) def getRootPath(environ): "Purpose: returns the root path on the server" # WARNING: this may not be thread safe, and doesn't work w/ VirtualServer/mod_python # Use Config.UserFilesAbsolutePath instead if environ.has_key('DOCUMENT_ROOT'): return environ['DOCUMENT_ROOT'] else: realPath = os.path.realpath( './' ) selfPath = environ['SCRIPT_FILENAME'] selfPath = selfPath [ : selfPath.rfind( '/' ) ] selfPath = selfPath.replace( '/', os.path.sep) position = realPath.find(selfPath) # This can check only that this script isn't run from a virtual dir # But it avoids the problems that arise if it isn't checked raise realPath if ( position < 0 or position <> len(realPath) - len(selfPath) or realPath[ : position ]==''): raise Exception('Sorry, can\'t map "UserFilesPath" to a physical path. You must set the "UserFilesAbsolutePath" value in "editor/filemanager/connectors/py/config.py".') return realPath[ : position ]
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector for Python (CGI and WSGI). """ from time import gmtime, strftime import string def escape(text, replace=string.replace): """ Converts the special characters '<', '>', and '&'. RFC 1866 specifies that these characters be represented in HTML as &lt; &gt; and &amp; respectively. In Python 1.5 we use the new string.replace() function for speed. """ text = replace(text, '&', '&amp;') # must be done 1st text = replace(text, '<', '&lt;') text = replace(text, '>', '&gt;') text = replace(text, '"', '&quot;') return text def convertToXmlAttribute(value): if (value is None): value = "" return escape(value) class BaseHttpMixin(object): def setHttpHeaders(self, content_type='text/xml'): "Purpose: to prepare the headers for the xml to return" # Prevent the browser from caching the result. # Date in the past self.setHeader('Expires','Mon, 26 Jul 1997 05:00:00 GMT') # always modified self.setHeader('Last-Modified',strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime())) # HTTP/1.1 self.setHeader('Cache-Control','no-store, no-cache, must-revalidate') self.setHeader('Cache-Control','post-check=0, pre-check=0') # HTTP/1.0 self.setHeader('Pragma','no-cache') # Set the response format. self.setHeader( 'Content-Type', content_type + '; charset=utf-8' ) return class BaseXmlMixin(object): def createXmlHeader(self, command, resourceType, currentFolder, url): "Purpose: returns the xml header" self.setHttpHeaders() # Create the XML document header s = """<?xml version="1.0" encoding="utf-8" ?>""" # Create the main connector node s += """<Connector command="%s" resourceType="%s">""" % ( command, resourceType ) # Add the current folder node s += """<CurrentFolder path="%s" url="%s" />""" % ( convertToXmlAttribute(currentFolder), convertToXmlAttribute(url), ) return s def createXmlFooter(self): "Purpose: returns the xml footer" return """</Connector>""" def sendError(self, number, text): "Purpose: in the event of an error, return an xml based error" self.setHttpHeaders() return ("""<?xml version="1.0" encoding="utf-8" ?>""" + """<Connector>""" + self.sendErrorNode (number, text) + """</Connector>""" ) def sendErrorNode(self, number, text): if number != 1: return """<Error number="%s" />""" % (number) else: return """<Error number="%s" text="%s" />""" % (number, convertToXmlAttribute(text)) class BaseHtmlMixin(object): def sendUploadResults( self, errorNo = 0, fileUrl = '', fileName = '', customMsg = '' ): self.setHttpHeaders("text/html") "This is the function that sends the results of the uploading process" "Minified version of the document.domain automatic fix script (#1919)." "The original script can be found at _dev/domain_fix_template.js" return """<script type="text/javascript"> (function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})(); window.parent.OnUploadCompleted(%(errorNumber)s,"%(fileUrl)s","%(fileName)s","%(customMsg)s"); </script>""" % { 'errorNumber': errorNo, 'fileUrl': fileUrl.replace ('"', '\\"'), 'fileName': fileName.replace ( '"', '\\"' ) , 'customMsg': customMsg.replace ( '"', '\\"' ), }
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector/QuickUpload for Python (WSGI wrapper). See config.py for configuration settings """ from connector import FCKeditorConnector from upload import FCKeditorQuickUpload import cgitb from cStringIO import StringIO # Running from WSGI capable server (recomended) def App(environ, start_response): "WSGI entry point. Run the connector" if environ['SCRIPT_NAME'].endswith("connector.py"): conn = FCKeditorConnector(environ) elif environ['SCRIPT_NAME'].endswith("upload.py"): conn = FCKeditorQuickUpload(environ) else: start_response ("200 Ok", [('Content-Type','text/html')]) yield "Unknown page requested: " yield environ['SCRIPT_NAME'] return try: # run the connector data = conn.doResponse() # Start WSGI response: start_response ("200 Ok", conn.headers) # Send response text yield data except: start_response("500 Internal Server Error",[("Content-type","text/html")]) file = StringIO() cgitb.Hook(file = file).handle() yield file.getvalue()
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == This is the "File Uploader" for Python """ import os from fckutil import * from fckcommands import * # default command's implementation from fckconnector import FCKeditorConnectorBase # import base connector import config as Config class FCKeditorQuickUpload( FCKeditorConnectorBase, UploadFileCommandMixin, BaseHttpMixin, BaseHtmlMixin): def doResponse(self): "Main function. Process the request, set headers and return a string as response." # Check if this connector is disabled if not(Config.Enabled): return self.sendUploadResults(1, "This file uploader is disabled. Please check the \"editor/filemanager/connectors/py/config.py\"") command = 'QuickUpload' # The file type (from the QueryString, by default 'File'). resourceType = self.request.get('Type','File') currentFolder = "/" # Check for invalid paths if currentFolder is None: return self.sendUploadResults(102, '', '', "") # Check if it is an allowed command if ( not command in Config.ConfigAllowedCommands ): return self.sendUploadResults( 1, '', '', 'The %s command isn\'t allowed' % command ) if ( not resourceType in Config.ConfigAllowedTypes ): return self.sendUploadResults( 1, '', '', 'Invalid type specified' ) # Setup paths self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType] self.webUserFilesFolder = Config.QuickUploadPath[resourceType] if not self.userFilesFolder: # no absolute path given (dangerous...) self.userFilesFolder = mapServerPath(self.environ, self.webUserFilesFolder) # Ensure that the directory exists. if not os.path.exists(self.userFilesFolder): try: self.createServerFoldercreateServerFolder( self.userFilesFolder ) except: return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ") # File upload doesn't have to return XML, so intercept here return self.uploadFile(resourceType, currentFolder) # Running from command line (plain old CGI) if __name__ == '__main__': try: # Create a Connector Instance conn = FCKeditorQuickUpload() data = conn.doResponse() for header in conn.headers: if not header is None: print '%s: %s' % header print print data except: print "Content-Type: text/plain" print import cgi cgi.print_exception()
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector for Python and Zope. This code was not tested at all. It just was ported from pre 2.5 release, so for further reference see \editor\filemanager\browser\default\connectors\py\connector.py in previous releases. """ from fckutil import * from connector import * import config as Config class FCKeditorConnectorZope(FCKeditorConnector): """ Zope versiof FCKeditorConnector """ # Allow access (Zope) __allow_access_to_unprotected_subobjects__ = 1 def __init__(self, context=None): """ Constructor """ FCKeditorConnector.__init__(self, environ=None) # call superclass constructor # Instance Attributes self.context = context self.request = FCKeditorRequest(context) def getZopeRootContext(self): if self.zopeRootContext is None: self.zopeRootContext = self.context.getPhysicalRoot() return self.zopeRootContext def getZopeUploadContext(self): if self.zopeUploadContext is None: folderNames = self.userFilesFolder.split("/") c = self.getZopeRootContext() for folderName in folderNames: if (folderName <> ""): c = c[folderName] self.zopeUploadContext = c return self.zopeUploadContext def setHeader(self, key, value): self.context.REQUEST.RESPONSE.setHeader(key, value) def getFolders(self, resourceType, currentFolder): # Open the folders node s = "" s += """<Folders>""" zopeFolder = self.findZopeFolder(resourceType, currentFolder) for (name, o) in zopeFolder.objectItems(["Folder"]): s += """<Folder name="%s" />""" % ( convertToXmlAttribute(name) ) # Close the folders node s += """</Folders>""" return s def getZopeFoldersAndFiles(self, resourceType, currentFolder): folders = self.getZopeFolders(resourceType, currentFolder) files = self.getZopeFiles(resourceType, currentFolder) s = folders + files return s def getZopeFiles(self, resourceType, currentFolder): # Open the files node s = "" s += """<Files>""" zopeFolder = self.findZopeFolder(resourceType, currentFolder) for (name, o) in zopeFolder.objectItems(["File","Image"]): s += """<File name="%s" size="%s" />""" % ( convertToXmlAttribute(name), ((o.get_size() / 1024) + 1) ) # Close the files node s += """</Files>""" return s def findZopeFolder(self, resourceType, folderName): # returns the context of the resource / folder zopeFolder = self.getZopeUploadContext() folderName = self.removeFromStart(folderName, "/") folderName = self.removeFromEnd(folderName, "/") if (resourceType <> ""): try: zopeFolder = zopeFolder[resourceType] except: zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=resourceType, title=resourceType) zopeFolder = zopeFolder[resourceType] if (folderName <> ""): folderNames = folderName.split("/") for folderName in folderNames: zopeFolder = zopeFolder[folderName] return zopeFolder def createFolder(self, resourceType, currentFolder): # Find out where we are zopeFolder = self.findZopeFolder(resourceType, currentFolder) errorNo = 0 errorMsg = "" if self.request.has_key("NewFolderName"): newFolder = self.request.get("NewFolderName", None) zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=newFolder, title=newFolder) else: errorNo = 102 return self.sendErrorNode ( errorNo, errorMsg ) def uploadFile(self, resourceType, currentFolder, count=None): zopeFolder = self.findZopeFolder(resourceType, currentFolder) file = self.request.get("NewFile", None) fileName = self.getFileName(file.filename) fileNameOnly = self.removeExtension(fileName) fileExtension = self.getExtension(fileName).lower() if (count): nid = "%s.%s.%s" % (fileNameOnly, count, fileExtension) else: nid = fileName title = nid try: zopeFolder.manage_addProduct['OFSP'].manage_addFile( id=nid, title=title, file=file.read() ) except: if (count): count += 1 else: count = 1 return self.zopeFileUpload(resourceType, currentFolder, count) return self.sendUploadResults( 0 ) class FCKeditorRequest(object): "A wrapper around the request object" def __init__(self, context=None): r = context.REQUEST self.request = r def has_key(self, key): return self.request.has_key(key) def get(self, key, default=None): return self.request.get(key, default) """ Running from zope, you will need to modify this connector. If you have uploaded the FCKeditor into Zope (like me), you need to move this connector out of Zope, and replace the "connector" with an alias as below. The key to it is to pass the Zope context in, as we then have a like to the Zope context. ## Script (Python) "connector.py" ##bind container=container ##bind context=context ##bind namespace= ##bind script=script ##bind subpath=traverse_subpath ##parameters=*args, **kws ##title=ALIAS ## import Products.zope as connector return connector.FCKeditorConnectorZope(context=context).doResponse() """
Python
#!/usr/bin/env python # encoding: utf-8 import random """ ' Author: Jonathan Potter ' ' Name: parameters ' ' Description: The simulation parameters, or knobs. These can be changed by the user to tailor the ' simulation to his needs. These are described more in depth in the User's Manual of the documentation. ' ' Notes: ' Encryption time found using time command to show ' system time used to encrypt 68byte (worst-case size) ' file using GPG. ' ' Hop time found using traceroute with 68byte (worst-case size) packets. ' ' Both measurements were repeated and mins and maxes were used ' as parameters in random number generation. ' """ parameters = { 'iterations' : 5, # number of times to run each step (these will be averaged) 'numberOfNodesRange' : (5, 1000, 5), # start, stop, step 'encryptionTimeRange' : (.1, 1), # range in milliseconds 'hopTimeRange' : (.1, 1), # hop time range in ms 'bandwidthRange' : (1, 10), # range 'packetSize' : 68, # bytes 'defaultDataNumberOfPackets' : 10, # use this many packets when calculating the bandwidth of a path 'snapshot' : [10, 20, 100, 200] }
Python
#!/usr/bin/env python # encoding: utf-8 import sys import os from parameters import * from driver import Driver """ ' ' Author: Jonathan Potter ' ' Name: Simulation ' ' Description: The main simulation entry point. This is the file you run, and it simply ' passes off control to the driver. ' ' Return: None. ' """ def main(): d = Driver(parameters) d.simulate() if __name__ == '__main__': main()
Python
#!/usr/bin/env python # encoding: utf-8 import sys import os import random import networkx as nx """ ' ' Author: Jonathan Potter ' ' Name: Utilities ' ' Description: Defines methods used by all protocols ' ' Parameters: None ' """ class Utilities: """ ' ' Name: pairs ' ' Description: Pairs up items of a list ' ' Parameters: a A list ' ' Returns: A list of pairs ' """ @staticmethod def pairs(a): return zip(*[a[x:] + a[:x] for x in range(2)]) """ ' ' Name: pathTime ' ' Description: Calculates and return time data will take to traverse given path ' ' Parameters: parameters, network, path, nodeDelay ' ' Returns: Time in milliseconds ' """ # Returns the total time in milliseconds. nodeDelay must be given in milliseconds! @staticmethod def pathTime(parameters, network, path, nodeDelay): numberOfPackets = parameters['defaultDataNumberOfPackets'] packetSize = parameters['packetSize'] pairs = Utilities.pairs(path)[:-1] # 125000 = (10 ** 3) / 8 to convert Mb/s to B/ms #print "PathA: ", path extractNormilizedBW = lambda (u, v): Utilities.getBandwidth(parameters, network, u, v) * 125000 bandwidths = map(extractNormilizedBW, pairs) wireTimes = map(lambda bw: float(packetSize)/bw, bandwidths) onePacket = nodeDelay * len(path) + sum(wireTimes) bottleNeck = max(nodeDelay, *wireTimes) # In ms totalTime = onePacket + (bottleNeck * (numberOfPackets - 1)) # In ms return totalTime """ ' ' Name: getBandwidth ' ' Description: Calculates and return total bandwidth along given path ' ' Parameters: parameters, network, node1, node2 ' ' Returns: Bandwidth in bits/second ' """ @staticmethod def getBandwidth(parameters, network, u, v): (minWeight, maxWeight) = parameters['bandwidthRange'] weight = network[u][v]['weight'] bandwidth = (maxWeight - weight) + minWeight return bandwidth """ ' ' Author: Jonathan Potter ' ' Name: Simple ' ' Description: Implements Simple Protocol ' ' Parameters: None ' """ class Simple: """ ' ' Name: Constructor ' """ def __init__(self): pass """ ' ' Name: getPath ' ' Description: Finds shortest path thru network using dijkstra's algorithm ' ' Parameters: self, network, parameters, source, destination ' ' Returns: path ' """ def getPath(self, network, parameters, source, destination): return nx.dijkstra_path(network, source, destination) """ ' ' Name: runSimulation ' ' Description: Runs simulation of protocol ' ' Parameters: self, network, parameters, path ' ' Returns: runtime of protocol on given path ' """ def runSimulation(self, network, parameters, path): hopTime = random.uniform(*parameters['hopTimeRange']) return Utilities.pathTime(parameters, network, path, hopTime) """ ' ' Author: Doug ' ' Name: Crowds ' ' Description: Implements Crowds Protocol ' ' Parameters: None ' """ class Crowds: """ ' ' Name: Constructor ' """ def __init__(self): pass """ ' ' Name: getPath ' ' Description: Using crowds to find the path. Uses Dijkstra's shortest path to find the path from the last jondo to the destination. ' ' Parameters: self, network, parameter, src ' ' Returns: The path. ' """ def getPath(self, network, parameters, src): myNetwork = network.copy() temp = network.copy() temp.remove_node(src) u = random.choice(temp.nodes()) dest = myNetwork.number_of_nodes() next = src crowdsPath = [next] while True: next = self.getNext(myNetwork, next) crowdsPath.append(next) if self.flipBiasedCoin() == 1: break dest = myNetwork.number_of_nodes() myNetwork.add_node(dest) myNetwork.add_edge(u, dest, weight = random.randint(*parameters['bandwidthRange'])) shortestPath = nx.dijkstra_path(myNetwork, next, dest) return (crowdsPath, shortestPath, myNetwork) """ ' ' Name: getNext ' ' Description: Gets the next random jondo. ' ' Parameters: self, network, src ' ' Returns: The next hop. ' """ def getNext(self, network, src): neighbors = network.neighbors(src) next = neighbors[random.randint(0, len(neighbors) - 1)] return next """ ' ' Name: flipBiasedCoin ' ' Description: Flips a coin that is biased torwards heads. ' ' Parameters: self ' ' Returns: True if heads, false if tails. ' """ def flipBiasedCoin(self): heads = 0.6 tails = 1 - heads flip = random.random() if flip > tails: return 1 else: return 0 """ ' ' Name: runSimulation ' ' Description: Runs simulation of the protocol. ' ' Parameters: self, network, parameters, crowdsPath, shortestPath ' ' Returns: Runtime of protocol on given path. ' """ def runSimulation(self, network, parameters, crowdsPath, shortestPath): encryptTime = 2 * random.uniform(*parameters['encryptionTimeRange']) hopTime = random.uniform(*parameters['hopTimeRange']) t1 = Utilities.pathTime(parameters, network, crowdsPath, encryptTime + hopTime) t2 = Utilities.pathTime(parameters, network, shortestPath, hopTime) return t1 + t2 """ ' ' Name: merge ' ' Description: Merges two lists. ' ' Parameters: self, l1, l2 ' ' Returns: N/A ' """ def merge(self, l1, l2): l2.pop(0) l1.extend(l2) """ ' ' Author: Erin ' ' Name: OnionRouting ' ' Description: Implements Onion Routing Protocol ' ' Parameters: None ' """ class OnionRouting: """ " Using Original instead of RTT for initial tests to choose path """ #constructor """ ' ' Name: Constructor ' """ def __init__(self): pass """ ' ' Name: runSimulation ' ' Description: Runs simulation of protocol ' ' Parameters: self, network, parameters, path ' ' Returns: runtime of protocol on given path ' """ def runSimulation(self, network, parameters, path): nodeDelay = random.uniform(*parameters['hopTimeRange']) runTime = self.returnOverhead(parameters, network, path, nodeDelay) return runTime """ ' ' Name: getPath ' ' Description: Chooses a random path through graph ' based on the way Tor uses the OR protocol ' random nodes are chosen, and then connected in an ' efficient manner ' ' Parameters: self, parameters, ORgraph, source, destination ' ' Returns: path ' """ def getPath(self, parameters, ORgraph, source, destination): # Get a random path, within a reasonable length myLength = 3 #this is the path length used by Tor next = source path = [] nodes = ORgraph.nodes() nodes.remove(source) for i in range(0 , myLength - 1): #choose a random node nextTemp = random.choice(nodes) #now remove it from the list of nodes so it won't come up again nodes.remove(nextTemp) #node must not be destination if nextTemp != destination: #add shortest path from random node to next random node using dijkstra's alg path = path + nx.dijkstra_path(ORgraph, next, nextTemp) #pop off last element so there won't be repeats path.pop() next = nextTemp else: i+=1 #otherwise do another loop in graph #add final dijkstra's path from last random node to dest path = path + nx.dijkstra_path(ORgraph, next, destination) return path """ " return parameters " Return measurements for final statistics """ """ ' ' Name: returnOverhead ' ' Description: Calculates and returns runtime of protocol thru path ' ' Parameters:self, parameters, network, path, nodeDelay ' ' Returns: runtime ' """ def returnOverhead(self, parameters, network, path, nodeDelay): #calculate and return overhead, incl. encryption time encryptPerPacket = random.uniform(*parameters['encryptionTimeRange']) transmitTime = Utilities.pathTime(parameters, network, path, nodeDelay) encryptTime = Utilities.pathTime(parameters, network, path, encryptPerPacket) #double encrypt time to account for encrypt and decrypt myTime = 2*encryptTime + transmitTime return myTime
Python
#!/usr/bin/env python # encoding: utf-8 import networkx as nx import matplotlib.pyplot as plt import sys import os import random import math from protocols import Simple from protocols import Crowds from protocols import OnionRouting from protocols import Utilities """ ' ' Author: Jonathan Potter ' ' Name: Driver ' ' Description: Drives the simulation, including reading in simulation parameters, ' generating a network, running each protocol on the generated network, and ' graphing statistics. ' """ class Driver: # The simulation input parameters (knobs) parameters = None # The list of protocols to run the simulation with protocols = None """ ' Name: __init__ ' ' Description: Constructor for class Driver. Sets up protocols and parameters. ' ' Parameters: parameters The simulation wide parameters (knobs) ' ' Return: An instance of class Driver. ' """ def __init__(self, parameters): self.parameters = parameters self.protocols = { 'Simple': Simple(), 'Crowds': Crowds(), 'OnionRouting': OnionRouting() } """ ' Name: generateNetwork ' ' Description: Generates a random network to use in the simulation. ' ' Parameters: numberOfNodes The number of nodes, or network size of the generated network. ' ' Return: A network of size numberOfNodes ' """ def generateNetwork(self, numberOfNodes): network = nx.connected_watts_strogatz_graph(numberOfNodes, int(round(math.log(numberOfNodes))), .8) # add a random weight between 1 and 10 for each edge for (u,v) in network.edges(): weight = random.randint(*self.parameters['bandwidthRange']) network[u][v] = {'weight': weight} network[v][u] = {'weight': weight} return network """ ' Name: displayNetwork ' ' Description: Saves a visual representation of the network to a file. This includes a highlighted path. ' ' Parameters: network The network to display. ' path The path to highlight on the network. ' filename The filename to save the image to. ' ' Return: None. ' """ def displayNetwork(self, network, path, filename): (nodeColors, edgeColors) = self.highlightPath(network, path) # Do widths edgeWidths = [] for (u, v) in network.edges(): edgeWidths.append(Utilities.getBandwidth(self.parameters, network, u, v)) pos = nx.graphviz_layout(network, prog = 'dot') nx.draw_networkx_edges( network, pos, alpha = .3, width = edgeWidths, edge_color = edgeColors) nx.draw_networkx_edges( network, pos, alpha = .4, width = 1, edge_color = 'k') nx.draw_networkx_nodes( network, pos, node_size = 80, alpha = 1, node_color = nodeColors, with_labels = False) plt.axis('off') # draw it plt.savefig(filename) plt.close() """ ' Name: getRandomEndpoints ' ' Description: Gets a random source and destination node in the network to use for routing data ' in the simulation. ' ' Parameters: network The network to get source and destination from. ' ' Return: (u, v) U is the source node, and V is the destination node. ' """ def getRandomEndpoints(self, network): u = random.choice(network.nodes()) withoutU = network.nodes()[:] withoutU.remove(u) v = random.choice(withoutU) return (u, v) """ ' Name: highlightPath ' ' Description: Visually highlights a path in our network. This function is used when saving ' a snapshot to a file. ' ' Parameters: network The network to use. ' path The path to highlight on the network. ' ' Return: (node_colors, edge_colors) Where node_colors and edge_colors are lists of color information to ' be used when saving a snapshot of the graph. These have the path highlighted. ' """ def highlightPath(self, network, path): node_colors = [255 for i in range(network.number_of_nodes())] edge_colors = ['black' for i in range(network.number_of_edges())] pairs = Utilities.pairs(path)[:-1] for (a, b) in pairs: if b < a: edge = (b, a) else: edge = (a, b) try: aIndex = network.nodes().index(a) bIndex = network.nodes().index(b) node_colors[aIndex] = 0 node_colors[bIndex] = 0 except: pass try: edgeIndex = network.edges().index(edge) edge_colors[edgeIndex] = 'magenta' except: pass return (node_colors, edge_colors) """ ' Name: initPlot ' ' Description: Initialize gnuplot to plot a certain dataset. This function opens a pipe to gnuplot and ' sets up basic axes and titles, etc. ' ' Parameters: name The name of this plot. This will be used as the filename to store the raw data in. ' title The title of this plot. This is used as the title of the graph. ' xLabel The label for the x axis of the plot. ' yLabel The label for the y axis of the plot. ' ' Return: (plotFile, gnuplot) Handles to the data file, and the gnuplot pipe respectively. ' """ def initPlot(self, name, title, xLabel, yLabel): # initialize plot file plotFile = open(name, "w") gnuplot = os.popen("gnuplot -persist 2> gnuplot.log", "w") # initialize gnuplot # gnuplot.write("set terminal x11\n") gnuplot.write("set title '%s'\n" % title) gnuplot.write("set xlabel '%s'\n" % xLabel) gnuplot.write("set ylabel '%s'\n" % yLabel) gnuplot.write("plot '%s' using 1:2 title 'Simple' with lines, '%s' using 1:3 title 'Crowds' with lines, '%s' using 1:4 title 'Onion Routing' with lines\n" % (name, name, name)) return (plotFile, gnuplot) """ ' Name: plotSlice ' ' Description: Plots one datapoint of the graph. This function is called each time through a loop ' to get live real time plotting. ' ' Parameters: plot The plot returned by the initPlot function. ' data The datapoint to plot. ' ' Return: None. ' """ def plotSlice(self, plot, data): (plotFile, gnuplot) = plot plotFile.write(' '.join(map(lambda x: str(x), data)) + "\n") plotFile.flush() gnuplot.write("replot\n") try: gnuplot.flush() except: pass """ ' Name: closePlot ' ' Description: Cleans up all plot variables, and closes file and pipe handles. ' ' Parameters: plot The plot returned by initPlot. ' ' Return: None. ' """ def closePlot(self, plot): (plotFile, gnuplot) = plot plotFile.close() gnuplot.close() """ ' Name: simulate ' ' Description: Main simulation funciton. Drives each of the protocols, generates the networks, and plots ' statistics from the simulation. ' ' Parameters: None ' ' Return: None. ' """ def simulate(self): bandwidthPlot = self.initPlot("bandwidth", "Bandwidth Comparison", "Number of nodes", "Bandwidth (Mbps)") overheadPlot = self.initPlot("overhead", "Overhead Comparison", "Number of nodes", "Overhead (milliseconds)") # data in bits amountOfData = self.parameters['defaultDataNumberOfPackets'] * self.parameters['packetSize'] * 8 for n in range(*self.parameters['numberOfNodesRange']): iterationTimes = [[], [], []] for i in range(self.parameters['iterations']): network = self.generateNetwork(n) (source, destination) = self.getRandomEndpoints(network) # Simple protocol simplePath = self.protocols['Simple'].getPath(network, self.parameters, source, destination) iterationTimes[0].append(self.protocols['Simple'].runSimulation(network, self.parameters, simplePath)) # Crowds protocol (crowdsPath, shortestPath, crowdsNetwork) = self.protocols['Crowds'].getPath(network, self.parameters, source) iterationTimes[1].append(self.protocols['Crowds'].runSimulation(crowdsNetwork, self.parameters, crowdsPath, shortestPath)) self.protocols['Crowds'].merge(crowdsPath, shortestPath) # Onion Routing protocol orPath = self.protocols['OnionRouting'].getPath(self.parameters, network, source, destination) iterationTimes[2].append(self.protocols['OnionRouting'].runSimulation(network, self.parameters, orPath)) if n in self.parameters['snapshot'] and i is 1: self.displayNetwork(network, simplePath, 'nodes_%s_protocol_%s' % (n, 'simple')) self.displayNetwork(crowdsNetwork, crowdsPath, 'nodes_%s_protocol_%s' % (n, 'crowds')) self.displayNetwork(network, orPath, 'nodes_%s_protocol_%s' % (n, 'onionrouting')) # In ms averageTimes = map(lambda p: float(sum(p)) / len(p), iterationTimes) # In Mbps bandwidths = map(lambda x: (float(amountOfData) / x) / 10 ** 3, averageTimes) # In ms overheads = averageTimes self.plotSlice(bandwidthPlot, [n] + bandwidths) self.plotSlice(overheadPlot, [n] + overheads) self.closePlot(bandwidthPlot) self.closePlot(overheadPlot)
Python
#!/opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin/python import codecs import re import jinja2 import markdown def process_slides(): with codecs.open('../presentation.html', 'w', encoding='utf8') as outfile: md = codecs.open('slides.md', encoding='utf8').read() md_slides = md.split('\n---\n') print len(md_slides) slides = [] # Process each slide separately. for md_slide in md_slides: slide = {} sections = md_slide.split('\n\n') # Extract metadata at the beginning of the slide (look for key: value) # pairs. metadata_section = sections[0] metadata = parse_metadata(metadata_section) slide.update(metadata) remainder_index = metadata and 1 or 0 # Get the content from the rest of the slide. content_section = '\n\n'.join(sections[remainder_index:]) html = markdown.markdown(content_section) slide['content'] = postprocess_html(html, markdown) slides.append(slide) template = jinja2.Template(open('base.html').read()) outfile.write(template.render(locals())) def parse_metadata(section): """Given the first part of a slide, returns metadata associated with it.""" metadata = {} metadata_lines = section.split('\n') for line in metadata_lines: colon_index = line.find(':') if colon_index != -1: key = line[:colon_index].strip() val = line[colon_index + 1:].strip() metadata[key] = val return metadata def postprocess_html(html, metadata): """Returns processed HTML to fit into the slide template format.""" return html if __name__ == '__main__': process_slides()
Python
#!/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()
Python
#!/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()
Python
#!/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()
Python
#!/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)
Python
#!/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
Python
#coding=utf-8 from django.db import models from django.contrib.auth.models import User #记录订单的表,请根据自己需求完成 class Transaction(models.Model): out_trade_no=models.CharField(max_length=32) user=models.ForeignKey(User)
Python
#encoding=utf-8 from django.conf.urls.defaults import patterns,include,url from views import * urlpatterns=patterns('alipay.views', url(r'checkout$',alipayTo), url(r'alipay_notify$',alipay_notify), url(r'alipay_return$',alipay_return), )
Python
#!/usr/bin/env python #coding=utf-8 ''' #============================================================================= # FileName: views.py # Desc: 支付宝接口调用类 # Author: GitFree # Email: pengzhao.lh@gmail.com # LastChange: 2011-11-21 13:52:52 #============================================================================= ''' from django.http import HttpResponseRedirect,HttpResponse from django.shortcuts import render_to_response,RequestContext from lib.AlipayService import Service from lib.AlipayNotify import Notify import hashlib import time from cart import Cart from django.contrib.auth.decorators import login_required @login_required def alipayTo(request): #/////////////////////////////////////////请求参数//////////////////////////////////////// #//////////必填参数////////////////////////////////////////// #请与贵网站订单系统中的唯一订单号匹配 hash=hashlib.md5() hash.update(str(time.time())) out_trade_no=hash.hexdigest() cart=Cart(request) #订单名称,显示在支付宝收银台里的“商品名称”里,显示在支付宝的交易管理的“商品名称”的列表里 subject = u"" #订单描述、订单详细、订单备注,显示在支付宝收银台里的“商品描述”里 body = "" for item in cart: body="%s%sx%d+" % (body,item.product.name,item.quantity) body=body[:-1] #订单总金额,显示在支付宝收银台里的“应付总额”里 total_fee = cart.total_fee #////////// end of 必填参数///////////////////////////////////// #扩展功能参数——默认支付方式// #默认支付方式,代码见“即时到帐接口”技术文档 paymethod = "" #默认网银代号,代号列表见“即时到帐接口”技术文档“附录”→“银行列表” defaultbank = "" #扩展功能参数——防钓鱼// #防钓鱼时间戳 anti_phishing_key = "" #获取客户端的IP地址,建议:编写获取客户端IP地址的程序 exter_invoke_ip = "" #注意: #请慎重选择是否开启防钓鱼功能 #exter_invoke_ip、anti_phishing_key一旦被设置过,那么它们就会成为必填参数 #建议使用POST方式请求数据 #示例: #exter_invoke_ip = "" #Service aliQuery_timestamp = new Service() #anti_phishing_key = aliQuery_timestamp.Query_timestamp() #扩展功能参数——其他// #商品展示地址,要用http:// 格式的完整路径,不允许加?id=123这类自定义参数 show_url = "" #自定义参数,可存放任何内容(除=、&等特殊字符外),不会显示在页面上 ##这里保存当前用户ID extra_common_param = str(request.user.id) #默认买家支付宝账号 buyer_email = "" #扩展功能参数——分润(若要使用,请按照注释要求的格式赋值)// #提成类型,该值为固定值:10,不需要修改 royalty_type = "" #提成信息集 royalty_parameters = "" #注意: #与需要结合商户网站自身情况动态获取每笔交易的各分润收款账号、各分润金额、各分润说明。最多只能设置10条 #各分润金额的总和须小于等于total_fee #提成信息集格式为:收款方Email_1^金额1^备注1|收款方Email_2^金额2^备注2 #示例: #royalty_type = "10" #royalty_parameters = "111@126.com^0.01^分润备注一|222@126.com^0.01^分润备注二" #///////////////////////////////////end of 请求参数////////////////////////////////////// #把请求参数打包成数组 sParaTemp = {} sParaTemp["payment_type"]= "1" sParaTemp["show_url"]= show_url sParaTemp["out_trade_no"]= out_trade_no sParaTemp["subject"]= subject sParaTemp["body"]= body sParaTemp["total_fee"]= total_fee sParaTemp["paymethod"]= paymethod sParaTemp["defaultbank"]= defaultbank sParaTemp["anti_phishing_key"]= anti_phishing_key sParaTemp["exter_invoke_ip"]= exter_invoke_ip sParaTemp["extra_common_param"]= extra_common_param sParaTemp["buyer_email"]= buyer_email sParaTemp["royalty_type"]= royalty_type sParaTemp["royalty_parameters"]= royalty_parameters #构造即时到帐接口表单提交HTML数据,无需修改 alipay = Service() strHtml = alipay.Create_direct_pay_by_user(sParaTemp) return render_to_response("empty.html",{'content':strHtml}) def alipay_notify(request): if request.POST: notify = Notify() verifyResult = aliNotify.Verify(request.POST, request.POST["notify_id"], request.POST["sign"]) if verifyResult:#验证成功 #/////////////////////////////////////////////////////////////////////////////////// #请在这里加上商户的业务逻辑程序代码 #——请根据您的业务逻辑来编写程序(以下代码仅作参考)—— #获取支付宝的通知返回参数,可参考技术文档中服务器异步通知参数列表 order_no = request.POST["out_trade_no"] #获取订单号 total_fee = request.POST["total_fee"] #获取总金额 subject = request.POST["subject"] #商品名称、订单名称 body = request.POST["body"] #商品描述、订单备注、描述 if request.POST["trade_status"] == "TRADE_FINISHED"\ or request.POST["trade_status"] =="TRADE_SUCCESS": #判断该笔订单是否在商户网站中已经做过处理 #如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序 #如果有做过处理,不执行商户的业务程序 return HttpResponse("success") #请不要修改或删除 else: return HttpResponse("success") #其他状态判断。普通即时到帐中,其他状态不用判断,直接打印success。 #——请根据您的业务逻辑来编写程序(以上代码仅作参考)—— #///////////////////////////////////////////////////////////////////////////////////// else: #验证失败 return HttpResponse("fail") else: return HttpResponse("无通知参数") @login_required def alipay_return(request): if request.GET: notify = Notify() verifyResult = aliNotify.Verify(request.GET, request.GET["notify_id"], request.GET["sign"]) if verifyResult:#验证成功 #/////////////////////////////////////////////////////////////////////////////////// #请在这里加上商户的业务逻辑程序代码 #——请根据您的业务逻辑来编写程序(以下代码仅作参考)—— #获取支付宝的通知返回参数,可参考技术文档中服务器异步通知参数列表 order_no = request.GET["out_trade_no"] #获取订单号 total_fee = request.GET["total_fee"] #获取总金额 subject = request.GET["subject"] #商品名称、订单名称 body = request.GET["body"] #商品描述、订单备注、描述 if request.GET["trade_status"] == "TRADE_FINISHED"\ or request.GET["trade_status"] =="TRADE_SUCCESS": #判断该笔订单是否在商户网站中已经做过处理 #如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序 #如果有做过处理,不执行商户的业务程序 return HttpResponse("支付成功!") else: return HttpResponse("支付成功!") #其他状态判断。普通即时到帐中,其他状态不用判断,直接打印success。 #——请根据您的业务逻辑来编写程序(以上代码仅作参考)—— #///////////////////////////////////////////////////////////////////////////////////// else: #验证失败 return HttpResponse("fail") else: return HttpResponse("无通知参数")
Python
#!/usr/bin/env python #coding=utf-8 ''' #============================================================================= # FileName: AlipayConfig.py # Desc: 基础配置类 # Author: GitFree # Email: pengzhao.lh@gmail.com # LastChange: 2011-11-21 13:53:39 #============================================================================= ''' class Config: def __init__(self): #↓↓↓↓↓↓↓↓↓↓请在这里配置您的基本信息↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ #合作身份者ID,以2088开头由16位纯数字组成的字符串 self.partner = "" #交易安全检验码,由数字和字母组成的32位字符串 self.key = "" #签约支付宝账号或卖家支付宝帐户 self.seller_email = "" #页面跳转同步返回页面文件路径 要用 http://格式的完整路径,不允许加?id=123这类自定义参数 self.return_url = "" #服务器通知的页面文件路径 要用 http://格式的完整路径,不允许加?id=123这类自定义参数 self.notify_url = "" #↑↑↑↑↑↑↑↑↑↑请在这里配置您的基本信息↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ #字符编码格式 目前支持 gbk 或 utf-8 self.input_charset = "utf-8" #签名方式 不需修改 self.sign_type = "MD5" #访问模式,根据自己的服务器是否支持ssl访问,若支持请选择https;若不支持请选择http self.transport = "http"
Python
#!/usr/bin/env python #coding=utf-8 ''' #============================================================================= # FileName: AlipayNotify.py # Desc: 支付宝通知处理类 # Author: GitFree # Email: pengzhao.lh@gmail.com # LastChange: 2011-09-27 00:52:09 #============================================================================= ''' from AlipayConfig import Config from AlipayCore import Core import urllib2 # #///////////////////注意///////////////////////////// # 调试通知返回时,可查看或改写log日志的写入TXT里的数据,来检查通知返回是否正常 # </summary> class Notify : #HTTPS支付宝通知路径 Https_veryfy_url = "https://www.alipay.com/cooperate/gateway.do?service=notify_verify&" #HTTP支付宝通知路径 Http_veryfy_url = "http://notify.alipay.com/trade/notify_query.do?" # 从配置文件中初始化变量 # <param name="inputPara">通知返回参数数组</param> # <param name="notify_id">通知验证ID</param> def __init__(self): config=Config() #合作身份者ID self.partner = config.partner #交易安全校验码 self.key = config.key self.input_charset = config.input_charset #签名方式 self.sign_type = config.sign_type #访问模式 self.transport = config.transport # <summary> # 验证消息是否是支付宝发出的合法消息 # </summary> # <param name="inputPara">通知返回参数数组</param> # <param name="notify_id">通知验证ID</param> # <param name="sign">支付宝生成的签名结果</param> # <returns>验证结果</returns> def Verify(self,inputPara,notify_id, sign): #获取返回回来的待签名数组签名后结果 mysign = self.GetResponseMysign(inputPara) #获取是否是支付宝服务器发来的请求的验证结果 responseTxt = "true" if notify_id != "" : responseTxt = self.GetResponseTxt(notify_id) #写日志记录(若要调试,请取消下面两行注释) #sWord = "responseTxt=" + responseTxt + "\n sign=" + sign + "&mysign=" + mysign + "\n 返回回来的参数:" + GetPreSignStr(inputPara) + "\n " #Core.LogResult(sWord) #验证 #responsetTxt的结果不是true,与服务器设置问题、合作身份者ID、notify_id一分钟失效有关 #mysign与sign不等,与安全校验码、请求时的参数格式(如:带自定义参数等)、编码格式有关 if responseTxt == "true" and sign == mysign:#验证成功 return True else:#验证失败 return False # <summary> # 获取待签名字符串(调试用) # </summary> # <param name="inputPara">通知返回参数数组</param> # <returns>待签名字符串</returns> def GetPreSignStr(self,inputPara): sPara = {} #过滤空值、sign与sign_type参数 sPara = Core.FilterPara(inputPara) #获取待签名字符串 preSignStr = Core.CreateLinkString(sPara) return preSignStr # <summary> # 获取返回回来的待签名数组签名后结果 # </summary> # <param name="inputPara">通知返回参数数组</param> # <returns>签名结果字符串</returns> def GetResponseMysign(self,inputPara): sPara ={} #过滤空值、sign与sign_type参数 sPara = Core.FilterPara(inputPara) #获得签名结果 mysign = Core.BuildMysign(sPara, self.key, self.sign_type, self.input_charset) return mysign # <summary> # 获取是否是支付宝服务器发来的请求的验证结果 # </summary> # <param name="notify_id">通知验证ID</param> # <returns>验证结果</returns> def GetResponseTxt(self,notify_id,timeout=120000): veryfy_url = self.transport == "https" and self.Https_veryfy_url or self.Http_veryfy_url veryfy_url += "partner=" + self.partner + "&notify_id=" + notify_id #获取远程服务器ATN结果,验证是否是支付宝服务器发来的请求 open = urllib2.urlopen(veryfy_url, timeout=timeout) return open.read()
Python
#!/usr/bin/env python #coding=utf-8 ''' #============================================================================= # FileName: AlipaySubmit.py # Desc: 支付宝各接口请求提交类 # Author: GitFree # Email: pengzhao.lh@gmail.com # LastChange: 2011-09-24 14:20:35 #============================================================================= ''' from AlipayConfig import Config from AlipayCore import Core class Submit: def __init__(self): config=Config() #交易安全校验码 self.key = config.key #编码格式 self.input_charset = config.input_charset #签名方式 self.sign_type = config.sign_type # 生成要请求给支付宝的参数数组 # <param name="sParaTemp">请求前的参数List</param> # <returns>要请求的参数List</returns> def BuildRequestPara(self,sParaTemp): #待签名请求参数数组 sPara={} #签名结果 mysign = "" #过滤签名参数数组 sPara = Core.FilterPara(sParaTemp) #获得签名结果 ########################################################################################## mysign = Core.BuildMysign(sPara, self.key, self.sign_type, self.input_charset) #签名结果与签名方式加入请求提交参数组中 sPara["sign"]=mysign sPara["sign_type"]= self.sign_type return sPara # 生成要请求给支付宝的参数数组 # <param name="sParaTemp">请求前的参数数组</param> # <returns>要请求的参数数组字符串</returns> def BuildRequestParaToString(self,sParaTemp): #待签名请求参数数组 sPara ={} sPara = BuildRequestPara(sParaTemp) #把参数组中所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串 strRequestData = Core.CreateLinkString(sPara) return strRequestData # <summary> # 构造提交表单HTML数据 # </summary> # <param name="sParaTemp">请求参数数组</param> # <param name="gateway">网关地址</param> # <param name="strMethod">提交方式。两个值可选:post、get</param> # <param name="strButtonValue">确认按钮显示文字</param> # <returns>提交表单HTML文本</returns> def BuildFormHtml(self,sParaTemp,gateway,strMethod,strButtonValue): #待请求参数数组 dicPara ={} dicPara = self.BuildRequestPara(sParaTemp) sbHtml =[] sbHtml.append("<form id='alipaysubmit' name='alipaysubmit' action='" + gateway + "_input_charset=" + self.input_charset + "' method='" + strMethod.lower() + "'>") for key in dicPara: sbHtml.append("<input type='hidden' name='%s' value='%s' />" %(key,dicPara[key])) #submit按钮控件请不要含有name属性 sbHtml.append("<input type='submit' value='" + strButtonValue + "' style='display:none'></form>") sbHtml.append("<script>document.forms['alipaysubmit'].submit()</script>") return ''.join(sbHtml) ####################未完成####################################### ''' # <summary> # 构造模拟远程HTTP的POST请求,获取支付宝的返回XML处理结果 # </summary> # <param name="sParaTemp">请求参数数组</param> # <param name="gateway">网关地址</param> # <returns>支付宝返回XML处理结果</returns> def SendPostInfo(sParaTemp,gateway): #待请求参数数组字符串 strRequestData = BuildRequestParaToString(sParaTemp) #把数组转换成流中所需字节数组类型 Encoding code = Encoding.GetEncoding(self.input_charset) byte[] bytesRequestData = code.GetBytes(strRequestData) #构造请求地址 strUrl = gateway + "_input_charset=" + self.input_charset #请求远程HTTP XmlDocument xmlDoc = new XmlDocument() try: #设置HttpWebRequest基本信息 HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(strUrl) myReq.Method = "post" myReq.ContentType = "application/x-www-form-urlencoded" #填充POST数据 myReq.ContentLength = bytesRequestData.Length Stream requestStream = myReq.GetRequestStream() requestStream.Write(bytesRequestData, 0, bytesRequestData.Length) requestStream.Close() #发送POST数据请求服务器 HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse() Stream myStream = HttpWResp.GetResponseStream() #获取服务器返回信息 XmlTextReader Reader = new XmlTextReader(myStream) xmlDoc.Load(Reader) except Exception as exp: strXmlError = "<error>" + exp + "</error>" xmlDoc.LoadXml(strXmlError) return xmlDoc } # <summary> # 构造模拟远程HTTP的GET请求,获取支付宝的返回XML处理结果 # </summary> # <param name="sParaTemp">请求参数数组</param> # <param name="gateway">网关地址</param> # <returns>支付宝返回XML处理结果</returns> public static XmlDocument SendGetInfo(SortedDictionary<string, string> sParaTemp, string gateway) { #待请求参数数组字符串 string strRequestData = BuildRequestParaToString(sParaTemp) #构造请求地址 string strUrl = gateway + strRequestData #请求远程HTTP XmlDocument xmlDoc = new XmlDocument() try { #设置HttpWebRequest基本信息 HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(strUrl) myReq.Method = "get" #发送POST数据请求服务器 HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse() Stream myStream = HttpWResp.GetResponseStream() #获取服务器返回信息 XmlTextReader Reader = new XmlTextReader(myStream) xmlDoc.Load(Reader) } catch (Exception exp) { string strXmlError = "<error>" + exp.Message + "</error>" xmlDoc.LoadXml(strXmlError) } return xmlDoc } } '''
Python
#!/usr/bin/env python #coding=utf-8 ''' #============================================================================= # FileName: AlipayService.py # Desc: 支付宝接口构造类 # Author: GitFree # Email: pengzhao.lh@gmail.com # LastChange: 2011-09-24 01:47:10 #============================================================================= ''' from AlipayConfig import Config from AlipaySubmit import Submit # 要传递的参数要么不允许为空,要么就不要出现在数组与隐藏控件或URL链接里。 class Service: # 构造函数 def __init__(self): # 从配置文件及入口文件中初始化变量 config=Config() #合作者身份ID self.partner = config.partner #字符编码格式 self.input_charset = config.input_charset #签约支付宝账号或卖家支付宝帐户 self.seller_email = config.seller_email #页面跳转同步返回页面文件路径 self.return_url = config.return_url #服务器通知的页面文件路径 self.notify_url =config.notify_url #支付宝网关地址(新) self.GATEWAY_NEW = "https://mapi.alipay.com/gateway.do?" # 构造即时到帐接口 # <param name="sParaTemp">请求参数集合</param> # <returns>表单提交HTML信息</returns> def Create_direct_pay_by_user(self,sParaTemp): #增加基本配置 sParaTemp["service"]="create_direct_pay_by_user" sParaTemp["partner"]=self.partner sParaTemp["_input_charset"]= self.input_charset sParaTemp["seller_email"]= self.seller_email sParaTemp["return_url"]=self.return_url sParaTemp["notify_url"]= self.notify_url #确认按钮显示文字 strButtonValue = u"确认" #表单提交HTML数据 strHtml = "" #构造表单提交HTML数据 submit=Submit() strHtml = submit.BuildFormHtml(sParaTemp, self.GATEWAY_NEW, "get", strButtonValue) return strHtml #未完成 # 用于防钓鱼,调用接口query_timestamp来获取时间戳的处理函数 # <returns>时间戳字符串</returns> def Query_timestamp(self): url = self.GATEWAY_NEW + "service=query_timestamp&partner=" + Config.partner encrypt_key = "" #从网络读取xml,未完成 #XmlTextReader Reader = new XmlTextReader(url) #XmlDocument xmlDoc = new XmlDocument() #xmlDoc.Load(Reader) #encrypt_key = xmlDoc.SelectSingleNode("/alipay/response/timestamp/encrypt_key").InnerText return encrypt_key #******************若要增加其他支付宝接口,可以按照下面的格式定义******************// # <summary> # 构造(支付宝接口名称)接口 # </summary> # <param name="sParaTemp">请求参数集合List</param> # <returns>表单提交HTML文本或者支付宝返回XML处理结果</returns> def AlipayInterface(self,sParaTemp): #增加基本配置 #表单提交HTML数据变量 strHtml = "" #构造请求参数数组 #构造给支付宝处理的请求 #请求方式有以下三种: #1.构造表单提交HTML数据:Submit.BuildFormHtml() #2.构造模拟远程HTTP的POST请求,获取支付宝的返回XML处理结果:Submit.SendPostInfo() #3.构造模拟远程HTTP的GET请求,获取支付宝的返回XML处理结果:Submit.SendGetInfo() #请根据不同的接口特性三选一 return strHtml
Python
#!/usr/bin/env python #coding=utf-8 ''' #============================================================================= # FileName: AlipayCore.py # Desc: 支付宝接口共用函数类 # Author: GitFree # Email: pengzhao.lh@gmail.com # LastChange: 2011-09-24 03:32:13 #============================================================================= ''' import hashlib import os.path class Core: def __init__(self): pass # 生成签名结果 # <param name="sArray">要签名的数组</param> # <param name="key">安全校验码</param> # <param name="sign_type">签名类型</param> # <param name="input_charset">编码格式</param> # <returns>签名结果字符串</returns> @staticmethod def BuildMysign(paramDic,key,sign_type,input_charset): prestr = Core.CreateLinkString(paramDic) #把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串 prestr = prestr + key #把拼接后的字符串再与安全校验码直接连接起来 mysign = Core.Sign(prestr, sign_type, input_charset) #把最终的字符串签名,获得签名结果 return mysign # <summary> # 除去数组中的空值和签名参数 # </summary> # <param name="dicArrayPre">过滤前的参数组</param> # <returns>过滤后的参数组</returns> @staticmethod def FilterPara(paramDicPre): paramDic ={} for key in paramDicPre: if key.lower() != "sign" and key.lower() != "sign_type" and paramDicPre[key] != "" and paramDicPre[key]!= None: paramDic[key]=paramDicPre[key] return paramDic # <summary> # 把数组所有元素排序,按照“参数=参数值”的模式用“&”字符拼接成字符串 # </summary> # <param name="sArray">需要拼接的数组</param> # <returns>拼接完成以后的字符串</returns> @staticmethod def CreateLinkString(paramDic): paramKeys=paramDic.keys() #排序 paramKeys.sort() preList=[] for key in paramKeys: preList.append('%s=%s'% (key,paramDic[key])) joined_string='&'.join(preList) return joined_string # <summary> # 签名字符串 # </summary> # <param name="prestr">需要签名的字符串</param> # <param name="sign_type">签名类型,这里支持只MD5</param> # <param name="input_charset">编码格式</param> # <returns>签名结果</returns> @staticmethod def Sign(prestr,sign_type,input_charset): prestr=prestr.encode(input_charset) if (sign_type.upper() == "MD5"): hash=hashlib.md5() hash.update(prestr) result=hash.hexdigest() else: result=sign_type+u'方式签名尚未开发,清自行添加' return result # <summary> # 写日志,方便测试(网站需求,可以改成把记录存入数据库) # </summary> # <param name="sWord">要写入日志里的文本内容</param> @staticmethod def LogResult(sWord): strPath = os.path.dirname(__file__) strPath = os.path.join(strPath, "log.txt") f=file(strPath,'a') f.write(time.strftime("%y-%m-%d-%H:%M:%S ")+sWord) f.close()
Python
import os numInput = 0 numOutput = 0 folderName = raw_input("Enter the folder containing the data files to convert ... ") files = os.listdir(folderName) for each in files: if(os.path.isdir(each)): files.remove(each) fileStr = "" for eachFile in files: fileStr += eachFile + ", " print("Converting "+fileStr) if(os.path.isdir(folderName+"/Converted/") == False): os.mkdir(folderName+"/Converted/") for FileName in files: FileObj = open(folderName+"/"+FileName, "r") rawData = FileObj.readlines() FileObj.close() data = [] dataPairs = 0 for eachLine in rawData: data.append(eachLine.strip(" \n\t").split(",")) dataPairs += 1 numOutput = 1 for each in data: numInput = len(each) - 1 newFile = open(folderName+"/Converted/fann_"+FileName, "w") newFile.write(str(dataPairs)+" "+str(numInput)+" "+str(numOutput)+"\n") lineCount = 0 for each in data: output = each[-1] del each[-1] inputStr = " ".join(each) newFile.write(inputStr+"\n") newFile.write(output +"\n") lineCount+=1 print("Converting line "+str(lineCount)+" of file "+FileName) newFile.close()
Python
#!/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()
Python
#!/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()
Python
#!/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()
Python
#!/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()
Python
#!/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()
Python
#!/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()
Python
#!/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()
Python
#!/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)))
Python
#!/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()
Python
#!/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()
Python
#!/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()
Python
#!/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()
Python
#!/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()
Python
#!/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" )
Python
# -*- 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)
Python
# 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'
Python
# Author: Hui ZHENG # Lisence: MIT import uno import unohelper from com.sun.star.task import XJobExecutor RegExp_3gpp_Ref = r'\[[:digit:]+\]' RegExp_3gpp_Ref_Definition = r'^[:space:]*\[[:digit:]+\]' RegExp_Numbering = r'[:digit:]+([. ][:digit:]+)+[:alpha:]?(-[:alnum:]+)?|[:digit:]+(-[:alnum:]+)' RegExp_Figure_Prefix = r'Figure' RegExp_Table_Prefix = r'Table' def make3gppRefBookmarkName(index): return '3gpp_ref_%d' % index def makeHeadingBookmarkName(numbering): return 'Heading_%s' % numbering.replace('.', '_').replace(' ', '_').strip() def makeFigureBookmarkName(prefix, numbering): return '%s_%s' % (prefix, numbering.replace('.', '_').replace('-', '__').strip()) def connect(port): localContext = uno.getComponentContext() # create the UnoUrlResolver resolver = localContext.ServiceManager.createInstanceWithContext( "com.sun.star.bridge.UnoUrlResolver", localContext ) # connect to the running office ctxt = resolver.resolve( "uno:socket,host=localhost,port=%d;urp;StarOffice.ComponentContext" % port) smgr = ctxt.ServiceManager # get the central desktop object desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop", ctxt) return (ctxt, desktop) def tryToSyncData(ctxt): ctxt.ServiceManager def fixHeadingOutlineLevel(document): para_styles = document.StyleFamilies.getByName("ParagraphStyles") for i in range(1, 9): heading = para_styles.getByName('Heading %d' % i) if heading.OutlineLevel != i: heading.OutlineLevel = i def fixTableTextWrapMode(document): frames = document.TextFrames for i in range(0, frames.Count): frame = frames.getByIndex(i) try: frame.Start # would raise exception if the frame contains a table except: frame.TextWrap = 'NONE' def findAllByRegularExpression(document, keyword): search = document.createSearchDescriptor() search.SearchRegularExpression = True search.SearchString = keyword return document.findAll(search) def findAllByStyle(document, style_name): search = document.createSearchDescriptor() search.SearchStyles = True search.SearchString = style_name return document.findAll(search) def replaceBookmark(document, text_range, bookmark_name, replace_old=True): bookmark = document.createInstance("com.sun.star.text.Bookmark") bookmark.Name = bookmark_name if document.Bookmarks.hasByName(bookmark_name) and replace_old: old_bookmark = document.Bookmarks.getByName(bookmark_name) document.Text.removeTextContent(old_bookmark) text_range.Text.insertTextContent(text_range, bookmark, True) def insertHyperLink(document, text_range, bookmark_name): if document.Bookmarks.hasByName(bookmark_name): text_range.HyperLinkURL = '#' + bookmark_name return True else: return False def addBookmarksTo3gppRefs(document): keyword = RegExp_3gpp_Ref_Definition found_refs = findAllByRegularExpression(document, keyword) for i in range(0, found_refs.Count): text_range = found_refs.getByIndex(i) bookmark_name = make3gppRefBookmarkName(i+1) replaceBookmark(document, text_range, bookmark_name) def addBookmarksToHeadings(document): def __do_heading(heading_level): found_headings = findAllByStyle(document, 'Heading %d' % heading_level) for i in range(0, found_headings.Count): text_range = found_headings.getByIndex(i) heading = text_range.String heading = heading.strip() if len(heading) == 0: continue numbering = heading.split()[0] bookmark_name = makeHeadingBookmarkName(numbering) replaceBookmark(document, text_range, bookmark_name) min_heading_level = 2 max_heading_level = 9 for i in range(min_heading_level, max_heading_level+1): __do_heading(i) def addBookmarksToFigures(document): def __do_bookmark(figure_prefix): keyword = figure_prefix + '[:space:]+' + '(' + RegExp_Numbering + ')' found_figures = findAllByRegularExpression(document, keyword) for i in range(0, found_figures.Count): text_range = found_figures.getByIndex(i) if text_range.CharWeight > 100.0: # do bold text only bookmark_numbering = text_range.String[len(RegExp_Figure_Prefix):] bookmark_name = makeFigureBookmarkName(figure_prefix, bookmark_numbering) replaceBookmark(document, text_range, bookmark_name, replace_old=False) for prefix in (RegExp_Figure_Prefix, RegExp_Table_Prefix): __do_bookmark(prefix) def addHyperLinksTo3gppRefs(document): keyword = RegExp_3gpp_Ref found_refs = findAllByRegularExpression(document, keyword) for i in range(0, found_refs.Count): text_range = found_refs.getByIndex(i) ref_str = text_range.String ref_str = ref_str.lstrip('[') ref_str = ref_str.rstrip(']') try: ref_index = int(ref_str) except ValueError: continue bookmark_name = make3gppRefBookmarkName(ref_index) insertHyperLink(document, text_range, bookmark_name) def addHyperLniksToNumberings(document): keyword = RegExp_Numbering found_numberings = findAllByRegularExpression(document, keyword) for i in range(0, found_numberings.Count): text_range = found_numberings.getByIndex(i) if 'Heading' in text_range.ParaStyleName: # skip heading text continue if text_range.CharWeight > 100.0: # skip bold text continue bookmark_name = makeHeadingBookmarkName(text_range.String) if insertHyperLink(document, text_range, bookmark_name) is False: for prefix in (RegExp_Figure_Prefix, RegExp_Table_Prefix): bookmark_name = makeFigureBookmarkName(prefix, text_range.String) if insertHyperLink(document, text_range, bookmark_name) is True: break def process(document): fixHeadingOutlineLevel(document) fixTableTextWrapMode(document) addBookmarksTo3gppRefs(document) addBookmarksToHeadings(document) addBookmarksToFigures(document) addHyperLinksTo3gppRefs(document) addHyperLniksToNumberings(document) def saveAsPdf(document, target_url): from com.sun.star.beans import PropertyValue property = ( PropertyValue("Overwrite",0,True,0), PropertyValue( "FilterName" , 0, "writer_pdf_Export" , 0 ), ) document.storeToURL(target_url, property) def convertToPdf(desktop, source_path): print 'start pdf conversion for', source_path from urllib import pathname2url from os.path import splitdrive, abspath, splitext drive, pathname = splitdrive(abspath(source_path)) source_url = "file:///" + drive + pathname2url(pathname) target_url = "file:///" + drive + pathname2url((splitext(pathname)[0] + ".pdf")) print 'processing', source_url document = None try: document = desktop.loadComponentFromURL(source_url, "_blank", 0, ()) process(document) saveAsPdf(document, target_url) print 'saved pdf to', target_url except Exception, e: print "Exception [%s] caught, while processing %s " % (str(e), source_url) if document is not None: document.dispose() # entry point for to call on command line def main(): import sys ctxt, desktop = connect(port=2002) if len(sys.argv) > 1: for arg in sys.argv[1:]: convertToPdf(desktop, arg) return None else: document = desktop.getCurrentComponent() process(document) tryToSyncData(ctxt) return document # return document for interactive inspection # entry point for to call as a macro within OOo def runMacro(): document = XSCRIPTCONTEXT.getDocument() process(document) # implement as a uno component so that it can be installed as an extension class Hyper3GPPLinks(unohelper.Base, XJobExecutor): def __init__(self, ctxt): self.ctxt = ctxt # entry point for to call as a uno component def trigger(self, args): desktop = self.ctxt.ServiceManager.createInstanceWithContext( "com.sun.star.frame.Desktop", self.ctxt ) document = desktop.getCurrentComponent() process(document) if __name__ == '__main__': doc = main() # for to run on command line else: g_exportedScripts = runMacro, # for to run as a macro in openoffice g_ImplementationHelper = unohelper.ImplementationHelper() # for to run as an extension g_ImplementationHelper.addImplementation(Hyper3GPPLinks, "zh.Hyper3GPPLinks", ("com.sun.star.task.Job",),)
Python
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()
Python
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)
Python
#from Gui import * import ctypes import threading import math import time import os import pygame from pygame.locals import * import ctypes from Tkinter import * 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 UNKILL_CREEPA = 10 UNKILL_CREEPB = 11 #[(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 update_clock(): usb.control_transfer(dev, 0xC0, GET_TICK, 0, 0, 1, buffer) tick = ord(buffer[0]) return tick #update_clock() def update_creep(): usb.control_transfer(dev, 0xC0, GET_CREEP, 0, 0, 1, buffer) creep = ord(buffer[0]) return creep def bits(i,n): return tuple((0,1)[i>>j & 1] for j in xrange(n-1,-1,-1)) def get_towerpos(): usb.control_transfer(dev, 0xC0, GET_TOWERPOS, 0, 0, 1, buffer) towertype = ord(buffer.raw[0]) return (bits(towertype,8), towertype) #root.after(50, update_status) 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) def unkill(value): print "kill_spot is %s" %value if value < 8: usb.control_transfer(dev, 0x40, UNKILL_CREEPA, int(value), 0, 0, buffer) else: usb.control_transfer(dev, 0x40, UNKILL_CREEPB, int(value-8), 0, 0, buffer) tower_delays = ctypes.c_buffer(64) 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) def distance(p1, p2): return math.sqrt(math.pow((p1[0] -p2[0]),2)+math.pow((p1[1] -p2[1]),2)) def determine_tangent(c1, c2): """ c1 and c2 are two circles, each represented by triple (x,y,r) where x,y are center coordinates and r is the radius. Assuming c1 is the circle with smaller radius, this function returns all possible tangents (0-4) between these two circles. """ x1,y1,r1 = c1 x2,y2,r2 = c2 assert(r1<=r2) d = math.sqrt((x1-x2)**2 + (y1-y2)**2) assert(d>0) direction_from_c1_to_c2 = ((x2-x1),(y2-y1)) outer_tangent = [] inner_tangent = [] if r2 - r1 > d: print "case 0: c1 is inside c2, hence no tangent" return outer_tangent, inner_tangent if r2 - r1 == d: print """case 1: c1 is inscribed in c2 return only 1 tangent line determined by the touching point and direction""" touch_point = (x1 - r1*(x2-x1)/d, \ y1 - r1*(y2-y1)/d) direction = (y2-y1, x2-x1) point_1 = (touch_point[0] + r2*direction[0]/d, \ touch_point[1] + r2*direction[1]/d) point_2 = (touch_point[0] - r2*direction[0]/d, \ touch_point[1] - r2*direction[1]/d) #outer_tangent = (touch_point,direction) outer_tangent.append((point_1, point_2)) return outer_tangent, inner_tangent cos_theta = (r1-r2)/d # rotation_angle >= pi/2 sin_theta = math.sqrt(1 - (cos_theta)**2) for i in (-1,+1): direction = (cos_theta*(x2-x1) + i*sin_theta*(y2-y1), \ -i*sin_theta*(x2-x1)+cos_theta*(y2-y1)) tangent_point_1 = (x1 + r1*direction[0]/d, \ y1 + r1*direction[1]/d) tangent_point_2 = (x2 + r2*direction[0]/d, \ y2 + r2*direction[1]/d) outer_tangent.append((tangent_point_1, tangent_point_2)) if r1 + r2 > d: print """case 2: the two circles intersect, hence no inner tangent return the two outer tangent lines determined by tangent points""" return outer_tangent, inner_tangent if r1 + r2 == d: print """ case 3: the two circles touch each other return the two outer tangent lines plus one additional inner tangent line determined by the touching point and direction """ touch_point = (x1 + r1*(x2-x1)/d, \ y1 + r1*(y2-y1)/d) direction = (y2-y1,x2-x1) direction = (y2-y1, x2-x1) point_1 = (touch_point[0] + r2*direction[0]/d, \ touch_point[1] + r2*direction[1]/d) point_2 = (touch_point[0] - r2*direction[0]/d, \ touch_point[1] - r2*direction[1]/d) #inner_tangent = (touch_point, direction) inner_tangent.append((point_1, point_2)) return outer_tangent, inner_tangent ## print """case 4: the two circles are separated ## return the two outer and two inner tangent lines ## all determined by the tangent points""" cos_theta = (r1+r2)/d # rotation_angle <= pi/2 sin_theta = math.sqrt(1 - (cos_theta)**2) for i in (-1,+1): direction = (cos_theta*(x2-x1) + i*sin_theta*(y2-y1), \ -i*sin_theta*(x2-x1)+cos_theta*(y2-y1)) tangent_point_1 = (x1 + r1*direction[0]/d, \ y1 + r1*direction[1]/d) tangent_point_2 = (x2 - r2*direction[0]/d, \ y2 - r2*direction[1]/d) inner_tangent.append((tangent_point_1, tangent_point_2)) return outer_tangent, inner_tangent def load_image(name, colorkey=None): fullname = os.path.join('data', name) try: image = pygame.image.load(fullname) except pygame.error, message: print 'Cannot load image:', fullname raise SystemExit, message image = image.convert() if colorkey is not None: if colorkey is -1: colorkey = image.get_at((0,0)) image.set_colorkey(colorkey, RLEACCEL) return image, image.get_rect() class Board: oldtime=0; newtime=0; creepkilltime=2; ## hardgears = [(34.25,4.75,1.25),(34.,18.75,1.75),(21.25,21.,1.5), ## (34.25,35.75,1.5),(4.75,35.,1.25),(14.25,14.75,1.25), ## (5.,4.5,2.5)] hardgears = [(5.5,4.5,1.25),(34.125,5,1.25),(33.75,18.75,1.25),(21,21.25,1.5),(35.25,33.25,1.5),(4.75,34.75,2),(14,14.75,2.5)] gear_tangents = [1,1,3,2,1,3,2] gear_directions = [-2,1,1,0,1,-1,1] hardkillerdistances = [ 3200/16*(i+1) for i in xrange(16)] display_size=(800,800) numcreeps=16 numtowers=6 numkillers=16 creep_path = [] cum_dist = [] gearscale=20 currentkilling=[] first_pos=0 creep_sep = 6.75 def __init__(self): for i in xrange(Board.numkillers): unkill(i) gearscale=Board.gearscale #window position #must be before initialise pygame window_x = 0 window_y = 10 self.tick_list = [] self.rate= 50 os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (window_x,window_y) #end window position setting pygame.init() self.screen = pygame.display.set_mode(Board.display_size) pygame.display.set_caption('POE TIME') pygame.mouse.set_visible(0) self.background = pygame.Surface(self.screen.get_size()) self.background = self.background.convert() self.creeps=[Creep(i) for i in xrange(Board.numcreeps)] self.creepsprites = pygame.sprite.RenderPlain(self.creeps) self.towers = [Tower(i) for i in xrange(Board.numtowers)] self.towersprites = pygame.sprite.RenderPlain(self.towers) #self.allsprites = pygame.sprite.RenderPlain( (Gear((100,50,10), 0,90), Gear((200,100,50), 0,90), Creep() ) ) Board.hardgears = [(Board.gearscale*g[0],Board.gearscale*g[1],Board.gearscale*g[2]) for g in Board.hardgears] self.setup_path() self.gearsprites=pygame.sprite.RenderPlain(self.gears) self.background.fill((255, 255, 255)) if pygame.font: font = pygame.font.Font(None, 36) text = font.render("POE: GET SUM", 1, (10, 10, 10)) textpos = text.get_rect(centerx=self.background.get_width()/2) self.background.blit(text, textpos) #print Board.creep_path #[[p[0]*gearscale, p[1]*gearscale] for p in Board.creep_path] self.gearsprites.draw(self.background) for i in xrange(len(Board.gear_tangents)): pygame.draw.line(self.background,(255*Board.gear_tangents[i]/3,255-Board.gear_tangents[i]/3,0),Board.creep_path[2*i],Board.creep_path[2*i+1], 2) self.screen.blit(self.background, (0, 0)) pygame.display.flip() self.clock = pygame.time.Clock() self.infiniteloop() def infiniteloop(self): while 1: #self.clock.tick(30) for event in pygame.event.get(): if event.type == QUIT: return elif event.type == KEYDOWN and event.key == K_ESCAPE: return self.update(); self.draw(); pygame.display.flip() #mainupdate def update(self): Board.newtime=time.clock() #self.gears[0].update() #Board.gear_tangents=[int(Board.newtime)%4]*7 #self.setup_path() #Board.first_pos=(Board.first_pos+1)%Board.cum_dist[-1] Board.first_pos = self.get_time() #for creep in self.creeps: # creep.update() #self.gearsprites.update() #self.towersprites.update() self.towerpos,towerposint = get_towerpos() #print "towerpos:",self.towerpos," inty:", towerposint self.towerpos=[1,1,1,1,1,1] for i in range(Board.numtowers): self.towers[i].activated=self.towerpos[i] #self.towers[i] = Tower( delay_array = [] firing_array = [] for creep in self.creeps: if creep.beenKilled == False: self.updateCreepXY(creep) if creep.isDead(): self.kill_creep(creep) for creep, i in self.currentkilling: if creep.distance<Board.hardkillerdistances[i]+6.75/2: unkill(i) self.currentkilling.remove((creep,i)) creep.beenKilled=True if creep in self.creeps: self.creeps.remove(creep) self.creepsprites.remove(creep) for i in range(Board.numtowers): firing = 0 if self.towerpos[i]: delay, firing = self.towers[i].update(self.creeps) delay_array.append(delay) else: delay_array.append( self.towers[i].angle) firing_array.append( 1)#replaced 1 for firing firing_array.append(0) firing_array.append(0) delay_array.append(80) delay_array.append(80) update_towers(delay_array, firing_array) #creep.moveTo(Board.creep_path[-1][0],Board.creep_path[-1][1]) #self.creeps[0].moveTo(self.gears[0].start_point[0], self.gears[0].start_point[1]) #print self.gears[0].end_theta*180/math.pi #self.creepsprites.update() Board.oldtime=Board.newtime #self.allsprites.update() ## for tower in self.towers: ## tower.update() ## ## self.creep_pos = [] ## for creep in self.creeps: ## (x,y) = self.creepPath.get_xy_pos(time.clock(), creep.num) ## creep.x = 100+10*x ## creep.y = 600-10*y ## self.creep_pos.append((creep.x,creep.y)) #c = towergui.canvas.create_oval((creep.x, creep.y),fill='black', width = 3) def draw(self): #print [(creep.distance) for creep in self.creeps] #print Board.cum_dist #self.screen.blit(self.background, (0, 0)) #self.gearsprites.clear(self.screen, self.background) self.towersprites=pygame.sprite.RenderPlain([tower for tower in self.towers if tower.activated]) self.towersprites.clear(self.screen, self.background) self.creepsprites.clear(self.screen, self.background) #self.gearsprites.draw(self.screen) self.towersprites.draw(self.screen) ## for tower in self.towers: ## if tower.activated: ## tower.draw(self.screen) self.creepsprites.draw(self.screen) def get_time(self): if update_clock(): t=time.clock() self.tick_list.append(t) print len(self.tick_list) if len(self.tick_list)>1: self.rate = len(self.tick_list)*6.75/(self.tick_list[-1]-self.tick_list[0]) if len(self.tick_list)>0: self.dist = len(self.tick_list)*6.75 + (time.clock()-self.tick_list[-1])*self.rate else: self.dist = self.rate * time.clock() return self.dist def setup_path(self): #each gear is x,y,r #x,y position #r is radius of the gear Board.creep_path=[] next_pos = (Board.hardgears[0][0],Board.hardgears[0][1]) for i in range(len(Board.hardgears)-1)+[-1]: c1= Board.hardgears[i] c2 = Board.hardgears[i+1] if (c2[2]<c1[2]): c3=c2 c2=c1 c1=c3 outer_tangent, inner_tangent = determine_tangent(c1, c2) outer_tangent+=inner_tangent; nextpos_choices = outer_tangent[Board.gear_tangents[i]] if (math.pow((nextpos_choices[0][0] -next_pos[0]),2)+math.pow((nextpos_choices[0][1] -next_pos[1]),2)<math.pow((nextpos_choices[1][0] -next_pos[0]),2)+math.pow((nextpos_choices[1][1] -next_pos[1]),2)): Board.creep_path.append(nextpos_choices[0]) next_pos = nextpos_choices[1] Board.creep_path.append(next_pos) else: Board.creep_path.append(nextpos_choices[1]) next_pos = nextpos_choices[0] Board.creep_path.append(next_pos) self.gears = []#[Gear((Board.hardgears[i][0],Board.hardgears[i][1],Board.hardgears[i][2]), 0,90) for i in xrange(len(Board.hardgears))] #print Board.creep_path sum = 0 numgears=len(Board.hardgears) for i in xrange(numgears): point_end=Board.creep_path[i*2] point_start=Board.creep_path[i*2-1] point_next_start=Board.creep_path[i*2+1] g=Gear(Board.hardgears[i],point_start, point_end, Board.gear_directions[i]) self.gears.append(g) if Board.gear_directions[i]==1 : sum+=g.r*abs(g.start_theta-g.end_theta) elif (Board.gear_directions[i]==0 or Board.gear_directions[i]==-1 or Board.gear_directions[i]==-2): ## print "YOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO",i ## print g.r*abs(g.start_theta-g.end_theta) ## print g.r*(2*math.pi-abs(g.start_theta-g.end_theta)) sum+=g.r*(2*math.pi-abs(g.start_theta-g.end_theta)) Board.cum_dist.append(sum) sum+=distance( point_end, point_next_start) Board.cum_dist.append(sum) print Board.cum_dist def updateCreepXY(self,creep): creep.distance=(Board.first_pos-Board.creep_sep*creep.num*Board.gearscale)%Board.cum_dist[-1] i=0 for j in xrange(len(Board.cum_dist)): if (creep.distance<Board.cum_dist[j]): break; i+=1 diff=(creep.distance-Board.cum_dist[i-1])/(Board.cum_dist[i]-Board.cum_dist[i-1]) if i==0: #print self.gears[0].start_theta*180/math.pi, self.gears[0].end_theta*180/math.pi diff= (creep.distance/Board.cum_dist[0]) if (i%2==0): g=self.gears[i/2] theta=g.start_theta+diff*(g.end_theta-g.start_theta) if (g.direction==-1): theta=g.start_theta+diff*(2*math.pi-(g.start_theta-g.end_theta)) elif (g.direction == 0): theta=g.start_theta-diff*(2*math.pi-abs(g.start_theta-g.end_theta)) elif(g.direction == -2): theta=g.start_theta+diff*((math.pi*2-g.start_theta+g.end_theta)) creep.moveTo(g.x+g.r*math.cos(theta), g.y+g.r*math.sin(theta)) else: g=self.gears[i/2] g2=self.gears[(i/2+1)%len(self.gears)] creep.moveTo(g.end_point[0]+diff*(g2.start_point[0]-g.end_point[0]),g.end_point[1]+diff*(g2.start_point[1]-g.end_point[1])) def kill_creep(self, creep): dist = creep.distance for i in xrange(Board.numkillers): if ( Board.hardkillerdistances[i]> dist and Board.hardkillerdistances[i] < dist+6.75*Board.gearscale): #creep.beenKilled=True ## threadkill=threading.Thread(target=self.kill_creep_thread, args=(i, creep)) ## threadkill.start() kill(i) self.currentkilling.append((creep,i)) def kill_creep_thread(self,num, creep): kill(num) killtime=time.clock()+Board.creepkilltime while (time.clock()<killtime): pass kill(num) class Gear(pygame.sprite.Sprite): def __init__(self, (x,y,r), point_start=[0,0], point_end=[0,0], direction=True): pygame.sprite.Sprite.__init__(self) #self.image, self.rect = load_image('O.GIF', -1) self.x = x self.y = y self.r = r self.start_point = point_start self.end_point = point_end self.start_theta=math.atan2((point_start[1]-y),(point_start[0]-x)) self.end_theta=math.atan2((point_end[1]-y),(point_end[0]-x)) self.direction=direction self.rect = pygame.Rect(x-r,y-r,r*2,2*r) self.image = pygame.Surface(self.rect.size) self.image.fill((255, 255, 255)) #self.image = pygame.transform.smoothscale(self.image, self.rect.size ) pygame.draw.circle(self.image, (0, 0, 0), (self.rect.width/2, self.rect.height/2), r, 3) #pygame.draw.circle(self.image, (0, 0, 0), (self.rect.width/2, self.rect.height/2), 2) #print self.rect ## self.dx=1 ## ## def update(self): ## #print self.rect.centerx ## #self.rect.centerx += (Board.newtime-Board.oldtime)*10 ## #print self.rect.move(((Board.newtime-Board.oldtime)*10, 0)).center ## #self.rect = self.rect.move(((Board.newtime-Board.oldtime)*10, 0)) ## self.rect.centerx += self.dx; ## if (self.rect.right> 800) or (self.rect.left <0): ## self.dx*=-1 ## #print "new:",self.rect.center def getRadius(): return self.r class Creep(pygame.sprite.Sprite): size=20 def __init__(self, num=0, HP=10): pygame.sprite.Sprite.__init__(self) self.image, self.rect = load_image('creep.jpg', -1) self.num=num self.HP = HP self.x=250 self.y=50 self.distance=0; self.rect.center = (self.x, self.y) self.beenKilled = False self.rect = pygame.Rect(self.x,self.y,Creep.size,Creep.size) self.image = pygame.transform.smoothscale(self.image, self.rect.size ) def hurt(self,HPloss): self.HP-=HPloss self.image = pygame.transform.flip(self.image, False, True) return self.HP>0 # def update(): def isDead(self): return self.HP<=0 def moveTo(self, x,y): self.x=x self.y=y self.rect.centerx = x self.rect.centery = y class Tower(pygame.sprite.Sprite): numtowerspots=6; numtowers=0; hardtowers = [(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)] tower_type_names = ['Water', 'Wind', 'Fire', 'Power', 'Awesrome', 'NoahtyestolemyPoEproject'] tower_ranges = [5000]*numtowerspots tower_damges = [5]*numtowers tower_size = 50; neutral = 80 def __init__ (self, num =0, ttype = 0): #towersetup #tsu pygame.sprite.Sprite.__init__(self) self.num = num self.activated = False self.x = Tower.hardtowers[num][0]*Board.gearscale self.y = Tower.hardtowers[num][1]*Board.gearscale self.default_angle = Tower.hardtowers[num][2] self.angle = 80 self.type = ttype self.range = 70#tower_ranges[self.type] self.damage = 10#tower_damages[self.type] self.target = None#but don't shoot at it till it's in range! self.lastfired = time.clock() self.firing = False self.delay = 2 self.image, self.rect = load_image('tower.png', -1) self.rect.center = (self.x, self.y) #self.image, self.rect = load_image('O.GIF', -1) self.rect = pygame.Rect(self.x,self.y,Tower.tower_size,Tower.tower_size) #self.image = pygame.Surface(self.rect.size) #self.image.fill((255, 255, 255)) self.image = pygame.transform.smoothscale(self.image, self.rect.size ) #pygame.draw.circle(self.image, (0, 0, 0), (self.rect.width/2, self.rect.height/2), r/2, 3) #pygame.draw.circle(self.image, (0, 0, 0), (self.rect.width/2, self.rect.height/2), 2) def __str__(self): print 'This', tower_type_names[self.type], 'tower is located at (', self.rect.centerx, ',', self.rect.centery, ').' def update(self, creeps): #is the current creep dead? #if not self.target or self.target.isDead(): #if so, find a new creep self.target=self.selecttarget( creeps ) if self.target: self.aim(self.target) timesincelastfire = time.clock() - self.lastfired if self.target and not self.target.isDead() and ( timesincelastfire> self.delay): self.firing = True self.target.hurt(self.damage) print "HIIIITTTTT!!!" self.image = pygame.transform.flip(self.image, False, True) self.lastfired=time.clock() else: self.firing = False print timesincelastfire #self.image.fill((255,0,0, 0), [0,0,timesincelastfire/self.delay*self.image.get_width(),timesincelastfire/self.delay*self.image.get_height()]) return self.angle, self.firing def selecttarget(self, creeps): #Choose the first living creep in range for creep in creeps: if not creep.isDead(): if math.sqrt( (creep.x - self.x)**2 + (creep.y - self.y)**2) <= self.range: return creep #else: # print math.sqrt( (creep.x - self.x)**2 + (creep.y - self.y)**2), self.range return None def aim(self, creep): self.angle = rad_to_delay(math.atan2(creep.x - self.x, creep.y - self.y) - self.default_angle) #print "aimed ",self.num," at:",self.angle #convert to duty cycle and send a vendor request to the pic 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-2*math.pi/3) + 25 if __name__ == '__main__': 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" Board() usb.close_device(dev)
Python
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)
Python
"""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)
Python
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)
Python
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)
Python
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)
Python
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)
Python
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)
Python
#!/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()
Python
#!/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()
Python
"""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)
Python
class Creep: def __init__(self, alive = 1, HP = 10, instance): self.life = alive #1 is alive, 0 is dead self.health = HP self.instance = instance self.x = x.Path(instance) #has something to do with where self.y = y.Path(instance) #the front creep is on the path. def __str__(self): print 'Who are you?', instance, ". Alive?", life, "HP:" health, '. Where are you? (', positionx, position y, ').' def update(self, instance): self.x = x.Path(instance) #has something to do with where self.y = y.Path(instance) #the front creep is on the path. def losehealth(self, damage): self.health = self.health - damage if self.health <= 0: self.die() def die(self): self.life = 0 class Tower: __init__(self, s, y, towertype): position angle upgrade def targetcreep(self): class LaserTower: class WindTower: class BombTower: etc. class Killswitch: __init__(self, x, y): self.state = 0 #Not sure if this is necessary. self.x = x self.y = y __str__(self): print "I am here: (", self.x, self.y ") and I am ", self.state def kill(self): self.state = 1 #vendor request goes here. self.state = 0 class CreepPath: def __init__(self): gear_pos = [(c1x, c1y, r1), (c2x, c2y, r2), etc) delimeters(gear_pos) def delimeters(self, gear_pos): d=[(0, 0, 0)] dist = 0 (tlast, tfirst, garbage) = cctangent(gear_pos[-1], gear_pos[0]) for ngear in range(len(gear_pos)-1): (t1, t2, ini_angle) = cctangent(ngear, ngear+1) arc = tfirst[1] dist += arc d[2*ngear-1] = (dist, t1[0], t1[1], ini_angle, ngear[2]) dist += math.sqrt((t2[1] - t1[1])**2 + (t2[0] - t1[0])**2) d[2*ngear] = (dist, t2[0], t2[1]) #total distance, x, y, angle for gears, radius self.delimeters = d def cctangent(c1, c2): th_ini = math.atan2(c2.y-c1.y,c2.x-c1.x) l = math.sqrt((c2.y-c1.y)**2 + (c2x-c1.x)**2) th = math.acos((c1.r-c2.r)/l) t1x = c1x + r1 * math.cos(th+th_ini) t1y = c1y + r1 * math.sin(th+th_ini) t2x = c2x + r2 * math.cos(th+th_ini) t2y = c2y + r2 * math.sin(th+th_ini) return (t1x, t1y, t2x, t2y) def get_xy_pos(self, time, dist_behind): # d = self.rate*time - dist_behind d = 1 for i in range(len(self.delimters)): #delimeters in the form [(d1, x1, y1, th_ini, r), (d2, x2, y2)] #bool = 1: theta increasing; -1: theta decreasing p1 = delimeters[i] p2 = delimeters[i+1] if d >= delimeters[-1][0]: #The front creep has done a lap return(x, y) self.y = if delimeters[i][0] < d < delimeters[i+1][0]: if i % 2 == 0: #Even sections are linear x = d / (p2[0] - p1[0]) * (p2[1] - p1[1]) y = d / (p2[0] - p1[0]) * (p2[2] - p1[2]) else: #Odd sections are turns x = p1[1] + math.cos(p1[3] + p1[5]*(d - p1[0])/p1[4]) y = p1[1] + math.sin(p1[3] + p1[5]*(d - p1[0])/p1[4]) def updatecreeps(creeps, time): for creep in creeps: creep.setxy( get_xy_pos(time, creep[1]) ) rate front creep position function describing path class Board: all tower positions list of creeps def update(self): update how long since last update? where was the creep last time? what is the new position on the path
Python
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)]) )
Python
from Gui import * import ctypes import threading import math ##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('Noah Tye stole my project!!!!') 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() class CreepPath: def __init__(self): self.setup_path() def get_first_position(self, time): pass def setup_path(self): #each gear is x,y,r, direction #x,y position #r is radius of the gear self.gears=[(1,2,1/2.), (3,4,2./2), (-6,8,0.5] def delimeters(self): self.delimiters=[] cumdist = 0 for i in range(len(self.gears)): ngear = self.gears[i-1] n2gear = self.gears[i] (t1, t2) = cctangent(ngear, n2gear) th1 = math.atan2( (t2[0] - ngear[0]) , (t2[1] - ngear[1]) ) th2 = math.atan2( (t1[0] - ngear[0]) , (t1[1] - ngear[1]) ) if i > 1: arc = ngear[2]*(th1 - th2) tfirst = t2 cumdist += abs(arc) self.delimiters.append((cumdist, t1[0], t1[1], th1, ngear[2], ngear[3])) #total distance, x, y, initial angle, radius length = math.sqrt((t2[1] - t1[1])**2 + (t2[0] - t1[0])**2) cumdist += abs(length) self.delimiters.append((cumdist, t2[0], t2[1], 0, 0, 0)) #total distance, x, y for delim in self.delimiters: print delim[0], '(', delim[1], ',', delim[2], ')' return self.delimiters def cctangent(self, c1, c2):u th_ini = math.atan2(c2.y-c1.y,c2.x-c1.x) l = math.sqrt((c2.y-c1.y)**2 + (c2x-c1.x)**2) th = math.acos((c1.r-c2.r)/l) t1x = c1x + r1 * math.cos(th+th_ini) t1y = c1y + r1 * math.sin(th+th_ini) t2x = c2x + r2 * math.cos(th+th_ini) t2y = c2y + r2 * math.sin(th+th_ini) return (t1x, t1y, t2x, t2y) def get_xy_pos(self, 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, bool), (d2, x2, y2)] #bool = 1: theta increasing; -1: theta decreasing p1 = dlist[i] p2 = dlist[i+1] # print p1[0], p2[0], 'i =', i, p2[0] - p1[0] if d >= dlist[-1][0]: #The front creep has done a lap return x, y if dlist[i][0] <= d < dlist[i+1][0]: print p1[0] #if i % 2 == 1: #Even sections are linear x = p1[1] + d / (p2[0] - p1[0]) * (p2[1] - p1[1]) y = p1[2] + d / (p2[0] - p1[0]) * (p2[2] - p1[2]) ## else: #Odd sections are turns ## x = p1[1] + math.cos(p1[3] + p1[5]*(d - p1[0])/p1[4]) ## y = p1[1] + math.sin(p1[3] + p1[5]*(d - p1[0])/p1[4]) return x, y 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 Board: def __init__(self): self.creeps=[Creep(i) for i in xrange(10)] self.creepPath=CreepPath() self.towers=[] self.theta=0 def update(self): for tower in self.towers: tower.update() self.theta=(self.theta+.001)%(2*math.pi) def draw(self, canvas): 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 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 towergui=TowerGUI()
Python
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) ##
Python
# 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
Python
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)
Python
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()
Python
# -*- 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 )
Python
# -*- 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 )
Python
from sys import stdin a, b, c = map(int, stdin.readline().strip().split()) print "%.3lf" % ((a+b+c)/3.0)
Python
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)
Python
from sys import stdin from math import * n, = map(int, stdin.readline().strip().split()) rad = radians(n) print "%.3lf %.3lf" % (sin(rad), cos(rad))
Python
from sys import stdin n, = map(int, stdin.readline().strip().split()) print n*(n+1)/2
Python
from sys import stdin a, b = map(int, stdin.readline().strip().split()) print b, a
Python
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
Python
from sys import stdin n, = map(int, stdin.readline().strip().split()) money = n * 95 if money >= 300: money *= 0.85 print "%.2lf" % money
Python
from sys import stdin n, = map(int, stdin.readline().strip().split()) print ["yes", "no"][n % 2]
Python
from sys import stdin from math import * x1, y1, x2, y2 = map(float, stdin.readline().strip().split()) print "%.3lf" % hypot((x1-x2), (y1-y2))
Python
from sys import stdin n = stdin.readline().strip().split()[0] print '%c%c%c' % (n[2], n[1], n[0])
Python
from sys import stdin x, = map(float, stdin.readline().strip().split()) print abs(x)
Python
from sys import stdin from calendar import isleap year, = map(int, stdin.readline().strip().split()) if isleap(year): print "yes" else: print "no"
Python
from sys import stdin f, = map(float, stdin.readline().strip().split()) print "%.3lf" % (5*(f-32)/9)
Python
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"
Python
from sys import stdin a = map(int, stdin.readline().strip().split()) a.sort() print a[0], a[1], a[2]
Python
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
Python
from sys import stdin from decimal import * a, b, c = map(int, stdin.readline().strip().split()) getcontext().prec = c print Decimal(a) / Decimal(b)
Python