ÿØÿà JFIF    ÿÛ „ ( %!1!%*+...983,7(-.- PK%L]nЈ tkinter/matt/dialog-box.pynu[from Tkinter import * from Dialog import Dialog # this shows how to create a new window with a button in it # that can create new windows class Test(Frame): def printit(self): print "hi" def makeWindow(self): """Create a top-level dialog with some buttons. This uses the Dialog class, which is a wrapper around the Tcl/Tk tk_dialog script. The function returns 0 if the user clicks 'yes' or 1 if the user clicks 'no'. """ # the parameters to this call are as follows: d = Dialog( self, ## name of a toplevel window title="fred the dialog box",## title on the window text="click on a choice", ## message to appear in window bitmap="info", ## bitmap (if any) to appear; ## if none, use "" # legal values here are: # string what it looks like # ---------------------------------------------- # error a circle with a slash through it # grey25 grey square # grey50 darker grey square # hourglass use for "wait.." # info a large, lower case "i" # questhead a human head with a "?" in it # question a large "?" # warning a large "!" # @fname X bitmap where fname is the path to the file # default=0, # the index of the default button choice. # hitting return selects this strings=("yes", "no")) # values of the 'strings' key are the labels for the # buttons that appear left to right in the dialog box return d.num def createWidgets(self): self.QUIT = Button(self, text='QUIT', foreground='red', command=self.quit) self.QUIT.pack(side=LEFT, fill=BOTH) # a hello button self.hi_there = Button(self, text='Make a New Window', command=self.makeWindow) self.hi_there.pack(side=LEFT) def __init__(self, master=None): Frame.__init__(self, master) Pack.config(self) self.windownum = 0 self.createWidgets() test = Test() test.mainloop() PK%L]t44tkinter/matt/entry-simple.pyonu[ ^c@sSddlTddlZdefdYZeZejjdejdS(i(t*NtAppcBseZddZdZRS(cCsMtj|||jt|_|jj|jjd|jdS(Ns (tFramet__init__tpacktEntryt entrythingytbindtprint_contents(tselftmaster((s6/usr/lib64/python2.7/Demo/tkinter/matt/entry-simple.pyRs    cCsdG|jjGHdS(Ns"hi. contents of entry is now ---->(Rtget(R tevent((s6/usr/lib64/python2.7/Demo/tkinter/matt/entry-simple.pyRsN(t__name__t __module__tNoneRR(((s6/usr/lib64/python2.7/Demo/tkinter/matt/entry-simple.pyRs tFoo(tTkintertstringRRtrootR ttitletmainloop(((s6/usr/lib64/python2.7/Demo/tkinter/matt/entry-simple.pyts   PK%L];mDD(tkinter/matt/canvas-reading-tag-info.pycnu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBs&eZdZdZddZRS(cCs dGHdS(Nthi((tself((sA/usr/lib64/python2.7/Demo/tkinter/matt/canvas-reading-tag-info.pytprintitscCs!t|ddddd|j|_|jjdtdtt|dd d d |_|jjd d d d d d d d ddd d}|jj |d}dG|dGdGH|jj |d}dG|dGdGHdG|dGdGH|jj |d }dG|dGH|jjdt dS(NttexttQUITt foregroundtredtcommandtsidetfilltwidtht5itheighti inttagstweeetfootgrootstipples#pgon's current stipple value is -->is<--s pgon's current fill value is -->s when he is usually colored -->ispgon's tags are(RRR( tButtontquitRtpacktBOTTOMtBOTHtCanvastdrawingtcreate_polygont itemconfigtLEFT(Rtpgont option_value((sA/usr/lib64/python2.7/Demo/tkinter/matt/canvas-reading-tag-info.pyt createWidgetss   cCs+tj||tj||jdS(N(tFramet__init__tPacktconfigR (Rtmaster((sA/usr/lib64/python2.7/Demo/tkinter/matt/canvas-reading-tag-info.pyR"*s N(t__name__t __module__RR tNoneR"(((sA/usr/lib64/python2.7/Demo/tkinter/matt/canvas-reading-tag-info.pyRs  "N(tTkinterR!Rttesttmainloop(((sA/usr/lib64/python2.7/Demo/tkinter/matt/canvas-reading-tag-info.pyts + PK%L]`MY)tkinter/matt/subclass-existing-widgets.pynu[from Tkinter import * # This is a program that makes a simple two button application class New_Button(Button): def callback(self): print self.counter self.counter = self.counter + 1 def createWidgets(top): f = Frame(top) f.pack() f.QUIT = Button(f, text='QUIT', foreground='red', command=top.quit) f.QUIT.pack(side=LEFT, fill=BOTH) # a hello button f.hi_there = New_Button(f, text='Hello') # we do this on a different line because we need to reference f.hi_there f.hi_there.config(command=f.hi_there.callback) f.hi_there.pack(side=LEFT) f.hi_there.counter = 43 root = Tk() createWidgets(root) root.mainloop() PK%L] NN%tkinter/matt/canvas-moving-w-mouse.pynu[from Tkinter import * # this file demonstrates the movement of a single canvas item under mouse control class Test(Frame): ################################################################### ###### Event callbacks for THE CANVAS (not the stuff drawn on it) ################################################################### def mouseDown(self, event): # remember where the mouse went down self.lastx = event.x self.lasty = event.y def mouseMove(self, event): # whatever the mouse is over gets tagged as CURRENT for free by tk. self.draw.move(CURRENT, event.x - self.lastx, event.y - self.lasty) self.lastx = event.x self.lasty = event.y ################################################################### ###### Event callbacks for canvas ITEMS (stuff drawn on the canvas) ################################################################### def mouseEnter(self, event): # the CURRENT tag is applied to the object the cursor is over. # this happens automatically. self.draw.itemconfig(CURRENT, fill="red") def mouseLeave(self, event): # the CURRENT tag is applied to the object the cursor is over. # this happens automatically. self.draw.itemconfig(CURRENT, fill="blue") def createWidgets(self): self.QUIT = Button(self, text='QUIT', foreground='red', command=self.quit) self.QUIT.pack(side=LEFT, fill=BOTH) self.draw = Canvas(self, width="5i", height="5i") self.draw.pack(side=LEFT) fred = self.draw.create_oval(0, 0, 20, 20, fill="green", tags="selected") self.draw.tag_bind(fred, "", self.mouseEnter) self.draw.tag_bind(fred, "", self.mouseLeave) Widget.bind(self.draw, "<1>", self.mouseDown) Widget.bind(self.draw, "", self.mouseMove) def __init__(self, master=None): Frame.__init__(self, master) Pack.config(self) self.createWidgets() test = Test() test.mainloop() PK%L] tkinter/matt/slider-demo-1.pyonu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBs/eZdZdZdZddZRS(cCs dG|GHdS(Ns slider now at((tselftval((s7/usr/lib64/python2.7/Demo/tkinter/matt/slider-demo-1.pyt print_valuescCs|jjddS(Ni(tslidertset(R((s7/usr/lib64/python2.7/Demo/tkinter/matt/slider-demo-1.pytreset scCst|dddddtdddd d |j|_t|d d d |j|_t|d d ddd |j|_|jjdt |jjdt |jjdt dt dS(Ntfrom_ittoidtorienttlengtht3itlabels happy slidertcommandttexts reset slidertQUITt foregroundtredtsidetfill( tScalet HORIZONTALRRtButtonRtquitRtpacktLEFTtBOTH(R((s7/usr/lib64/python2.7/Demo/tkinter/matt/slider-demo-1.pyt createWidgets scCs+tj||tj||jdS(N(tFramet__init__tPacktconfigR(Rtmaster((s7/usr/lib64/python2.7/Demo/tkinter/matt/slider-demo-1.pyRs N(t__name__t __module__RRRtNoneR(((s7/usr/lib64/python2.7/Demo/tkinter/matt/slider-demo-1.pyRs   N(tTkinterRRttesttmainloop(((s7/usr/lib64/python2.7/Demo/tkinter/matt/slider-demo-1.pyts  PK%L]ktkinter/matt/dialog-box.pycnu[ ^c@sGddlTddlmZdefdYZeZejdS(i(t*(tDialogtTestcBs/eZdZdZdZddZRS(cCs dGHdS(Nthi((tself((s4/usr/lib64/python2.7/Demo/tkinter/matt/dialog-box.pytprintitsc Cs1t|ddddddddd d }|jS( sCreate a top-level dialog with some buttons. This uses the Dialog class, which is a wrapper around the Tcl/Tk tk_dialog script. The function returns 0 if the user clicks 'yes' or 1 if the user clicks 'no'. ttitlesfred the dialog boxttextsclick on a choicetbitmaptinfotdefaultitstringstyestno(R R (Rtnum(Rtd((s4/usr/lib64/python2.7/Demo/tkinter/matt/dialog-box.pyt makeWindow s cCsrt|ddddd|j|_|jjdtdtt|ddd|j|_|jjdtdS( NRtQUITt foregroundtredtcommandtsidetfillsMake a New Window(tButtontquitRtpacktLEFTtBOTHRthi_there(R((s4/usr/lib64/python2.7/Demo/tkinter/matt/dialog-box.pyt createWidgets.s cCs4tj||tj|d|_|jdS(Ni(tFramet__init__tPacktconfigt windownumR(Rtmaster((s4/usr/lib64/python2.7/Demo/tkinter/matt/dialog-box.pyR9s  N(t__name__t __module__RRRtNoneR(((s4/usr/lib64/python2.7/Demo/tkinter/matt/dialog-box.pyRs  # N(tTkinterRRRttesttmainloop(((s4/usr/lib64/python2.7/Demo/tkinter/matt/dialog-box.pyts 8 PK%L]v 'tkinter/matt/rubber-band-box-demo-1.pyonu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBsAeZdZdZdZdZdZddZRS(cCs dGHdS(Nthi((tself((s@/usr/lib64/python2.7/Demo/tkinter/matt/rubber-band-box-demo-1.pytprintitsc Cs{t|ddddddddd |j|_|jjd td tt|d d dd |_|jjd tdS(NttexttQUITt backgroundtredt foregroundtwhitetheightitcommandtsidetfilltwidtht5i( tButtontquitRtpacktBOTTOMtBOTHtCanvast canvasObjecttLEFT(R((s@/usr/lib64/python2.7/Demo/tkinter/matt/rubber-band-box-demo-1.pyt createWidgetsscCs4|jj|j|_|jj|j|_dS(N(Rtcanvasxtxtstartxtcanvasytytstarty(Rtevent((s@/usr/lib64/python2.7/Demo/tkinter/matt/rubber-band-box-demo-1.pyt mouseDownscCs|jj|j}|jj|j}|j|jkr|j|jkr|jj|j|jj |j|j|||_|j ndS(N( RRRRRRRtdeletet rubberbandBoxtcreate_rectangletupdate_idletasks(RR RR((s@/usr/lib64/python2.7/Demo/tkinter/matt/rubber-band-box-demo-1.pyt mouseMotions$ cCs|jj|jdS(N(RR"R#(RR ((s@/usr/lib64/python2.7/Demo/tkinter/matt/rubber-band-box-demo-1.pytmouseUp'scCstj||tj||jd|_tj|j d|j tj|j d|j tj|j d|j dS(Ns ss( tFramet__init__tPacktconfigRtNoneR#tWidgettbindRR!R&R'(Rtmaster((s@/usr/lib64/python2.7/Demo/tkinter/matt/rubber-band-box-demo-1.pyR)*s   N( t__name__t __module__RRR!R&R'R,R)(((s@/usr/lib64/python2.7/Demo/tkinter/matt/rubber-band-box-demo-1.pyRs     N(tTkinterR(Rttesttmainloop(((s@/usr/lib64/python2.7/Demo/tkinter/matt/rubber-band-box-demo-1.pyts 5 PK%L]Q"tkinter/matt/rubber-line-demo-1.pynu[from Tkinter import * class Test(Frame): def printit(self): print "hi" def createWidgets(self): self.QUIT = Button(self, text='QUIT', background='red', foreground='white', height=3, command=self.quit) self.QUIT.pack(side=BOTTOM, fill=BOTH) self.canvasObject = Canvas(self, width="5i", height="5i") self.canvasObject.pack(side=LEFT) def mouseDown(self, event): # canvas x and y take the screen coords from the event and translate # them into the coordinate system of the canvas object self.startx = self.canvasObject.canvasx(event.x) self.starty = self.canvasObject.canvasy(event.y) def mouseMotion(self, event): # canvas x and y take the screen coords from the event and translate # them into the coordinate system of the canvas object x = self.canvasObject.canvasx(event.x) y = self.canvasObject.canvasy(event.y) if (self.startx != event.x) and (self.starty != event.y) : self.canvasObject.delete(self.rubberbandLine) self.rubberbandLine = self.canvasObject.create_line( self.startx, self.starty, x, y) # this flushes the output, making sure that # the rectangle makes it to the screen # before the next event is handled self.update_idletasks() def __init__(self, master=None): Frame.__init__(self, master) Pack.config(self) self.createWidgets() # this is a "tagOrId" for the rectangle we draw on the canvas self.rubberbandLine = None Widget.bind(self.canvasObject, "", self.mouseDown) Widget.bind(self.canvasObject, "", self.mouseMotion) test = Test() test.mainloop() PK%L];$tkinter/matt/window-creation-more.pynu[from Tkinter import * # this shows how to create a new window with a button in it # that can create new windows class Test(Frame): def printit(self): print "hi" def makeWindow(self): fred = Toplevel() fred.label = Button(fred, text="This is window number %d." % self.windownum, command=self.makeWindow) fred.label.pack() self.windownum = self.windownum + 1 def createWidgets(self): self.QUIT = Button(self, text='QUIT', foreground='red', command=self.quit) self.QUIT.pack(side=LEFT, fill=BOTH) # a hello button self.hi_there = Button(self, text='Make a New Window', command=self.makeWindow) self.hi_there.pack(side=LEFT) def __init__(self, master=None): Frame.__init__(self, master) Pack.config(self) self.windownum = 0 self.createWidgets() test = Test() test.mainloop() PK%L]Ca33tkinter/matt/packer-simple.pynu[from Tkinter import * class Test(Frame): def printit(self): print self.hi_there["command"] def createWidgets(self): # a hello button self.QUIT = Button(self, text='QUIT', foreground='red', command=self.quit) self.QUIT.pack(side=LEFT, fill=BOTH) self.hi_there = Button(self, text='Hello', command=self.printit) self.hi_there.pack(side=LEFT) # note how Packer defaults to side=TOP self.guy2 = Button(self, text='button 2') self.guy2.pack() self.guy3 = Button(self, text='button 3') self.guy3.pack() def __init__(self, master=None): Frame.__init__(self, master) Pack.config(self) self.createWidgets() test = Test() test.mainloop() PK%L](  $tkinter/matt/canvas-mult-item-sel.pynu[from Tkinter import * # allows moving dots with multiple selection. SELECTED_COLOR = "red" UNSELECTED_COLOR = "blue" class Test(Frame): ################################################################### ###### Event callbacks for THE CANVAS (not the stuff drawn on it) ################################################################### def mouseDown(self, event): # see if we're inside a dot. If we are, it # gets tagged as CURRENT for free by tk. if not event.widget.find_withtag(CURRENT): # we clicked outside of all dots on the canvas. unselect all. # re-color everything back to an unselected color self.draw.itemconfig("selected", fill=UNSELECTED_COLOR) # unselect everything self.draw.dtag("selected") else: # mark as "selected" the thing the cursor is under self.draw.addtag("selected", "withtag", CURRENT) # color it as selected self.draw.itemconfig("selected", fill=SELECTED_COLOR) self.lastx = event.x self.lasty = event.y def mouseMove(self, event): self.draw.move("selected", event.x - self.lastx, event.y - self.lasty) self.lastx = event.x self.lasty = event.y def makeNewDot(self): # create a dot, and mark it as current fred = self.draw.create_oval(0, 0, 20, 20, fill=SELECTED_COLOR, tags=CURRENT) # and make it selected self.draw.addtag("selected", "withtag", CURRENT) def createWidgets(self): self.QUIT = Button(self, text='QUIT', foreground='red', command=self.quit) ################ # make the canvas and bind some behavior to it ################ self.draw = Canvas(self, width="5i", height="5i") Widget.bind(self.draw, "<1>", self.mouseDown) Widget.bind(self.draw, "", self.mouseMove) # and other things..... self.button = Button(self, text="make a new dot", foreground="blue", command=self.makeNewDot) message = ("%s dots are selected and can be dragged.\n" "%s are not selected.\n" "Click in a dot to select it.\n" "Click on empty space to deselect all dots." ) % (SELECTED_COLOR, UNSELECTED_COLOR) self.label = Message(self, width="5i", text=message) self.QUIT.pack(side=BOTTOM, fill=BOTH) self.label.pack(side=BOTTOM, fill=X, expand=1) self.button.pack(side=BOTTOM, fill=X) self.draw.pack(side=LEFT) def __init__(self, master=None): Frame.__init__(self, master) Pack.config(self) self.createWidgets() test = Test() test.mainloop() PK%L]*hh+tkinter/matt/entry-with-shared-variable.pycnu[ ^c@sSddlTddlZdefdYZeZejjdejdS(i(t*NtAppcBs&eZddZdZdZRS(cCstj|||jt||_|jjt|ddd|j|_|jjt|_ |j j d|jj d|j |jj d|j dS(NttextsUppercase The Entrytcommandsthis is a variablet textvariables (tFramet__init__tpacktEntryt entrythingytButtontuppertbuttont StringVartcontentstsettconfigtbindtprint_contents(tselftmaster((sD/usr/lib64/python2.7/Demo/tkinter/matt/entry-with-shared-variable.pyRs    cCs,tj|jj}|jj|dS(N(tstringR RtgetR(Rtstr((sD/usr/lib64/python2.7/Demo/tkinter/matt/entry-with-shared-variable.pyR scCsdG|jjGHdS(Ns"hi. contents of entry is now ---->(RR(Rtevent((sD/usr/lib64/python2.7/Demo/tkinter/matt/entry-with-shared-variable.pyR)sN(t__name__t __module__tNoneRR R(((sD/usr/lib64/python2.7/Demo/tkinter/matt/entry-with-shared-variable.pyRs  tFoo(tTkinterRRRtrootRttitletmainloop(((sD/usr/lib64/python2.7/Demo/tkinter/matt/entry-with-shared-variable.pyts  & PK%L]̆^+tkinter/matt/not-what-you-might-think-1.pycnu[ ^c@sWddlTdefdYZeZejjdejjdejdS(i(t*tTestcBseZdZddZRS(cCsxt|dddddd|_|jjdtt|jddd d d |j|j_|jjjdtdS( Ntwidtht1itheightt backgroundtgreentsidettexttQUITt foregroundtredtcommand(tFrametGpaneltpacktLEFTtButtontquitR (tself((sD/usr/lib64/python2.7/Demo/tkinter/matt/not-what-you-might-think-1.pyt createWidgetss cCs+tj||tj||jdS(N(R t__init__tPacktconfigR(Rtmaster((sD/usr/lib64/python2.7/Demo/tkinter/matt/not-what-you-might-think-1.pyRs N(t__name__t __module__RtNoneR(((sD/usr/lib64/python2.7/Demo/tkinter/matt/not-what-you-might-think-1.pyRs s packer demotpackerN(tTkinterR RttestRttitleticonnametmainloop(((sD/usr/lib64/python2.7/Demo/tkinter/matt/not-what-you-might-think-1.pyts  PK%L]ll+tkinter/matt/packer-and-placer-together.pycnu[ ^c@seddlTdZdZdZeZeeZejdejddej dS(i(t*cCs#tjjd|jd|jdS(Ntxty(tapptbuttontplaceRR(tevent((sD/usr/lib64/python2.7/Demo/tkinter/matt/packer-and-placer-together.pyt do_motionscCs dGHdS(Ns calling me!((((sD/usr/lib64/python2.7/Demo/tkinter/matt/packer-and-placer-together.pytdothis scCst|dddddd}|jdtddt|d d d d d t|_|jjdddddt|jdt |S(Ntwidthitheightt backgroundtgreentfilltexpandit foregroundtredttexttamazingtcommandtrelxg?trelygtanchors( tFrametpacktBOTHtButtonRRRtNWtbindR(ttoptf((sD/usr/lib64/python2.7/Demo/tkinter/matt/packer-and-placer-together.pyt createWidgets s !t400x400iN( tTkinterRRRtTktrootRtgeometrytmaxsizetmainloop(((sD/usr/lib64/python2.7/Demo/tkinter/matt/packer-and-placer-together.pyts       PK%L]jHH#tkinter/matt/radiobutton-simple.pycnu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBs&eZdZdZddZRS(cCs dGHdS(Nthi((tself((s</usr/lib64/python2.7/Demo/tkinter/matt/radiobutton-simple.pytprintitsc Csvt|_|jjdt||_|jjt|jddd|jdddt|j_|jjjdt t|jddd|jdd dt|j_ |jj jdt t|jdd d|jdd dt|j_ |jj jdt t |d |j|_ |j jdt t|dd ddd|j|_|jjdtdtdS(Nt chocolatettextsChocolate FlavortvariabletvaluetanchortfillsStrawberry Flavort strawberrys Lemon Flavortlemont textvariabletQUITt foregroundtredtcommandtside(t StringVartflavortsettFramet radioframetpackt RadiobuttontWtchoctXtstrawR tEntrytentrytButtontquitRtBOTTOMtBOTH(R((s</usr/lib64/python2.7/Demo/tkinter/matt/radiobutton-simple.pyt createWidgetss0  cCs+tj||tj||jdS(N(Rt__init__tPacktconfigR$(Rtmaster((s</usr/lib64/python2.7/Demo/tkinter/matt/radiobutton-simple.pyR%7s N(t__name__t __module__RR$tNoneR%(((s</usr/lib64/python2.7/Demo/tkinter/matt/radiobutton-simple.pyR s  &N(tTkinterRRttesttmainloop(((s</usr/lib64/python2.7/Demo/tkinter/matt/radiobutton-simple.pyts / PK%L]oVV&tkinter/matt/rubber-band-box-demo-1.pynu[from Tkinter import * class Test(Frame): def printit(self): print "hi" def createWidgets(self): self.QUIT = Button(self, text='QUIT', background='red', foreground='white', height=3, command=self.quit) self.QUIT.pack(side=BOTTOM, fill=BOTH) self.canvasObject = Canvas(self, width="5i", height="5i") self.canvasObject.pack(side=LEFT) def mouseDown(self, event): # canvas x and y take the screen coords from the event and translate # them into the coordinate system of the canvas object self.startx = self.canvasObject.canvasx(event.x) self.starty = self.canvasObject.canvasy(event.y) def mouseMotion(self, event): # canvas x and y take the screen coords from the event and translate # them into the coordinate system of the canvas object x = self.canvasObject.canvasx(event.x) y = self.canvasObject.canvasy(event.y) if (self.startx != event.x) and (self.starty != event.y) : self.canvasObject.delete(self.rubberbandBox) self.rubberbandBox = self.canvasObject.create_rectangle( self.startx, self.starty, x, y) # this flushes the output, making sure that # the rectangle makes it to the screen # before the next event is handled self.update_idletasks() def mouseUp(self, event): self.canvasObject.delete(self.rubberbandBox) def __init__(self, master=None): Frame.__init__(self, master) Pack.config(self) self.createWidgets() # this is a "tagOrId" for the rectangle we draw on the canvas self.rubberbandBox = None # and the bindings that make it work.. Widget.bind(self.canvasObject, "", self.mouseDown) Widget.bind(self.canvasObject, "", self.mouseMotion) Widget.bind(self.canvasObject, "", self.mouseUp) test = Test() test.mainloop() PK%L]ZZ%tkinter/matt/window-creation-more.pycnu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBs/eZdZdZdZddZRS(cCs dGHdS(Nthi((tself((s>/usr/lib64/python2.7/Demo/tkinter/matt/window-creation-more.pytprintitscCsOt}t|dd|jd|j|_|jj|jd|_dS(NttextsThis is window number %d.tcommandi(tTopleveltButtont windownumt makeWindowtlabeltpack(Rtfred((s>/usr/lib64/python2.7/Demo/tkinter/matt/window-creation-more.pyR s     cCsrt|ddddd|j|_|jjdtdtt|ddd|j|_|jjdtdS( NRtQUITt foregroundtredRtsidetfillsMake a New Window(RtquitRR tLEFTtBOTHR thi_there(R((s>/usr/lib64/python2.7/Demo/tkinter/matt/window-creation-more.pyt createWidgetss cCs4tj||tj|d|_|jdS(Ni(tFramet__init__tPacktconfigR R(Rtmaster((s>/usr/lib64/python2.7/Demo/tkinter/matt/window-creation-more.pyRs  N(t__name__t __module__RR RtNoneR(((s>/usr/lib64/python2.7/Demo/tkinter/matt/window-creation-more.pyRs   N(tTkinterRRttesttmainloop(((s>/usr/lib64/python2.7/Demo/tkinter/matt/window-creation-more.pyts  PK%L]MhΩ &tkinter/matt/canvas-moving-w-mouse.pyonu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBsAeZdZdZdZdZdZddZRS(cCs|j|_|j|_dS(N(txtlastxtytlasty(tselftevent((s?/usr/lib64/python2.7/Demo/tkinter/matt/canvas-moving-w-mouse.pyt mouseDown s cCsF|jjt|j|j|j|j|j|_|j|_dS(N(tdrawtmovetCURRENTRRRR(RR((s?/usr/lib64/python2.7/Demo/tkinter/matt/canvas-moving-w-mouse.pyt mouseMoves* cCs|jjtdddS(Ntfilltred(R t itemconfigR (RR((s?/usr/lib64/python2.7/Demo/tkinter/matt/canvas-moving-w-mouse.pyt mouseEnterscCs|jjtdddS(NR tblue(R RR (RR((s?/usr/lib64/python2.7/Demo/tkinter/matt/canvas-moving-w-mouse.pyt mouseLeavesc Cst|ddddd|j|_|jjdtdtt|dd d d |_|jjdt|jjd d d d dd dd}|jj |d|j |jj |d|j t j |jd|jt j |jd|jdS(NttexttQUITt foregroundRtcommandtsideR twidtht5itheightiitgreenttagstselecteds s s<1>s (tButtontquitRtpacktLEFTtBOTHtCanvasR t create_ovalttag_bindRRtWidgettbindRR (Rtfred((s?/usr/lib64/python2.7/Demo/tkinter/matt/canvas-moving-w-mouse.pyt createWidgets!scCs+tj||tj||jdS(N(tFramet__init__tPacktconfigR)(Rtmaster((s?/usr/lib64/python2.7/Demo/tkinter/matt/canvas-moving-w-mouse.pyR+1s N( t__name__t __module__RR RRR)tNoneR+(((s?/usr/lib64/python2.7/Demo/tkinter/matt/canvas-moving-w-mouse.pyRs     N(tTkinterR*Rttesttmainloop(((s?/usr/lib64/python2.7/Demo/tkinter/matt/canvas-moving-w-mouse.pyts 1 PK%L]~ tkinter/matt/00-HELLO-WORLD.pynu[from Tkinter import * # note that there is no explicit call to start Tk. # Tkinter is smart enough to start the system if it's not already going. class Test(Frame): def printit(self): print "hi" def createWidgets(self): self.QUIT = Button(self, text='QUIT', foreground='red', command=self.quit) self.QUIT.pack(side=LEFT, fill=BOTH) # a hello button self.hi_there = Button(self, text='Hello', command=self.printit) self.hi_there.pack(side=LEFT) def __init__(self, master=None): Frame.__init__(self, master) Pack.config(self) self.createWidgets() test = Test() test.mainloop() PK%L]Fֳ tkinter/matt/menu-simple.pynu[from Tkinter import * # some vocabulary to keep from getting confused. This terminology # is something I cooked up for this file, but follows the man pages # pretty closely # # # # This is a MENUBUTTON # V # +-------------+ # | | # # +------------++------------++------------+ # | || || | # | File || Edit || Options | <-------- the MENUBAR # | || || | # +------------++------------++------------+ # | New... | # | Open... | # | Print | # | | <------ This is a MENU. The lines of text in the menu are # | | MENU ENTRIES # | +---------------+ # | Open Files > | file1 | # | | file2 | # | | another file | <------ this cascading part is also a MENU # +----------------| | # | | # | | # | | # +---------------+ def new_file(): print "opening new file" def open_file(): print "opening OLD file" def makeFileMenu(): # make menu button : "File" File_button = Menubutton(mBar, text='File', underline=0) File_button.pack(side=LEFT, padx="1m") File_button.menu = Menu(File_button) # add an item. The first param is a menu entry type, # must be one of: "cascade", "checkbutton", "command", "radiobutton", "separator" # see menu-demo-2.py for examples of use File_button.menu.add_command(label='New...', underline=0, command=new_file) File_button.menu.add_command(label='Open...', underline=0, command=open_file) File_button.menu.add_command(label='Quit', underline=0, command='exit') # set up a pointer from the file menubutton back to the file menu File_button['menu'] = File_button.menu return File_button def makeEditMenu(): Edit_button = Menubutton(mBar, text='Edit', underline=0) Edit_button.pack(side=LEFT, padx="1m") Edit_button.menu = Menu(Edit_button) # just to be cute, let's disable the undo option: Edit_button.menu.add('command', label="Undo") # Since the tear-off bar is the 0th entry, # undo is the 1st entry... Edit_button.menu.entryconfig(1, state=DISABLED) # and these are just for show. No "command" callbacks attached. Edit_button.menu.add_command(label="Cut") Edit_button.menu.add_command(label="Copy") Edit_button.menu.add_command(label="Paste") # set up a pointer from the file menubutton back to the file menu Edit_button['menu'] = Edit_button.menu return Edit_button ################################################# #### Main starts here ... root = Tk() # make a menu bar mBar = Frame(root, relief=RAISED, borderwidth=2) mBar.pack(fill=X) File_button = makeFileMenu() Edit_button = makeEditMenu() # finally, install the buttons in the menu bar. # This allows for scanning from one menubutton to the next. mBar.tk_menuBar(File_button, Edit_button) root.title('menu demo') root.iconname('packer') root.mainloop() PK%L]!tkinter/matt/READMEnu[This directory contains some ad-hoc examples of Tkinter widget creation. The files named *-simple.py are the ones to start with if you're looking for a bare-bones usage of a widget. The other files are meant to show common usage patters that are a tad more involved. If you have a suggestion for an example program, please send mail to conway@virginia.edu and I'll include it. matt TODO ------- The X selection Dialog Boxes More canvas examples Message widgets Text Editors Scrollbars Listboxes PK%L]'tkinter/matt/canvas-gridding.pynu[from Tkinter import * # this is the same as simple-demo-1.py, but uses # subclassing. # note that there is no explicit call to start Tk. # Tkinter is smart enough to start the system if it's not already going. class Test(Frame): def printit(self): print "hi" def createWidgets(self): self.QUIT = Button(self, text='QUIT', background='red', foreground='white', height=3, command=self.quit) self.QUIT.pack(side=BOTTOM, fill=BOTH) self.canvasObject = Canvas(self, width="5i", height="5i") self.canvasObject.pack(side=LEFT) def mouseDown(self, event): # canvas x and y take the screen coords from the event and translate # them into the coordinate system of the canvas object self.startx = self.canvasObject.canvasx(event.x, self.griddingSize) self.starty = self.canvasObject.canvasy(event.y, self.griddingSize) def mouseMotion(self, event): # canvas x and y take the screen coords from the event and translate # them into the coordinate system of the canvas object x = self.canvasObject.canvasx(event.x, self.griddingSize) y = self.canvasObject.canvasy(event.y, self.griddingSize) if (self.startx != event.x) and (self.starty != event.y) : self.canvasObject.delete(self.rubberbandBox) self.rubberbandBox = self.canvasObject.create_rectangle( self.startx, self.starty, x, y) # this flushes the output, making sure that # the rectangle makes it to the screen # before the next event is handled self.update_idletasks() def __init__(self, master=None): Frame.__init__(self, master) Pack.config(self) self.createWidgets() # this is a "tagOrId" for the rectangle we draw on the canvas self.rubberbandBox = None # this is the size of the gridding squares self.griddingSize = 50 Widget.bind(self.canvasObject, "", self.mouseDown) Widget.bind(self.canvasObject, "", self.mouseMotion) test = Test() test.mainloop() PK%L]L  )tkinter/matt/printing-coords-of-items.pycnu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBsAeZdZdZdZdZdZddZRS(cCs|jjts|jj|jd|jd|jd|jddd}|jj|d|j|jj|d|j n|j|_ |j|_ dS(Ni tfilltgreenss( twidgett find_withtagtCURRENTtdrawt create_ovaltxtyttag_bindt mouseEntert mouseLeavetlastxtlasty(tselfteventtfred((sB/usr/lib64/python2.7/Demo/tkinter/matt/printing-coords-of-items.pyt mouseDown s +  cCsF|jjt|j|j|j|j|j|_|j|_dS(N(RtmoveRR RR R(RR((sB/usr/lib64/python2.7/Demo/tkinter/matt/printing-coords-of-items.pyt mouseMoves* cCs+|jjtdd|jjtGHdS(NRtred(Rt itemconfigRtcoords(RR((sB/usr/lib64/python2.7/Demo/tkinter/matt/printing-coords-of-items.pyR "scCs|jjtdddS(NRtblue(RRR(RR((sB/usr/lib64/python2.7/Demo/tkinter/matt/printing-coords-of-items.pyR (scCst|ddddd|j|_|jjdtdtt|dd d d |_|jjdttj |jd |j tj |jd |j dS( NttexttQUITt foregroundRtcommandtsideRtwidtht5itheights<1>s ( tButtontquitRtpacktLEFTtBOTHtCanvasRtWidgettbindRR(R((sB/usr/lib64/python2.7/Demo/tkinter/matt/printing-coords-of-items.pyt createWidgets-scCs+tj||tj||jdS(N(tFramet__init__tPacktconfigR*(Rtmaster((sB/usr/lib64/python2.7/Demo/tkinter/matt/printing-coords-of-items.pyR,7s N( t__name__t __module__RRR R R*tNoneR,(((sB/usr/lib64/python2.7/Demo/tkinter/matt/printing-coords-of-items.pyRs      N(tTkinterR+Rttesttmainloop(((sB/usr/lib64/python2.7/Demo/tkinter/matt/printing-coords-of-items.pyts 7 PK%L]*hh+tkinter/matt/entry-with-shared-variable.pyonu[ ^c@sSddlTddlZdefdYZeZejjdejdS(i(t*NtAppcBs&eZddZdZdZRS(cCstj|||jt||_|jjt|ddd|j|_|jjt|_ |j j d|jj d|j |jj d|j dS(NttextsUppercase The Entrytcommandsthis is a variablet textvariables (tFramet__init__tpacktEntryt entrythingytButtontuppertbuttont StringVartcontentstsettconfigtbindtprint_contents(tselftmaster((sD/usr/lib64/python2.7/Demo/tkinter/matt/entry-with-shared-variable.pyRs    cCs,tj|jj}|jj|dS(N(tstringR RtgetR(Rtstr((sD/usr/lib64/python2.7/Demo/tkinter/matt/entry-with-shared-variable.pyR scCsdG|jjGHdS(Ns"hi. contents of entry is now ---->(RR(Rtevent((sD/usr/lib64/python2.7/Demo/tkinter/matt/entry-with-shared-variable.pyR)sN(t__name__t __module__tNoneRR R(((sD/usr/lib64/python2.7/Demo/tkinter/matt/entry-with-shared-variable.pyRs  tFoo(tTkinterRRRtrootRttitletmainloop(((sD/usr/lib64/python2.7/Demo/tkinter/matt/entry-with-shared-variable.pyts  & PK%L]PPtkinter/matt/pong-demo-1.pycnu[ ^c@sCddlTddlZdefdYZeZejdS(i(t*NtPongcBs&eZdZdZddZRS(c Cst|ddddd|j|_|jjdtdtt|dd d d |_t|d t d d dddd|_ |j jdt dt |jj dddddd|_d|_d|_d|_d|_|jjdtdS(NttexttQUITt foregroundtredtcommandtsidetfilltwidtht5itheighttorienttlabels ball speedtfrom_ittoidt0is0.10ig?g333333?g?(tButtontquitRtpacktLEFTtBOTHtCanvastdrawtScalet HORIZONTALtspeedtBOTTOMtXt create_ovaltballtxtyt velocity_xt velocity_y(tself((s5/usr/lib64/python2.7/Demo/tkinter/matt/pong-demo-1.pyt createWidgetss     cGs|jdks|jdkr1d|j|_n|jdksO|jdkrbd|j|_n|j|jjd}|j|jjd}|j||_|j||_|jj|jd|d||j d|j dS(Ng@gggY@s%rii ( RR!R R"RtgetRtmoveRtaftertmoveBall(R#targstdeltaxtdeltay((s5/usr/lib64/python2.7/Demo/tkinter/matt/pong-demo-1.pyR(s!cCs>tj||tj||j|jd|jdS(Ni (tFramet__init__tPacktconfigR$R'R((R#tmaster((s5/usr/lib64/python2.7/Demo/tkinter/matt/pong-demo-1.pyR--s  N(t__name__t __module__R$R(tNoneR-(((s5/usr/lib64/python2.7/Demo/tkinter/matt/pong-demo-1.pyRs  (tTkintertstringR,Rtgametmainloop(((s5/usr/lib64/python2.7/Demo/tkinter/matt/pong-demo-1.pyts  . PK%L]|=4>>&tkinter/matt/canvas-with-scrollbars.pynu[from Tkinter import * # This example program creates a scrolling canvas, and demonstrates # how to tie scrollbars and canvases together. The mechanism # is analogus for listboxes and other widgets with # "xscroll" and "yscroll" configuration options. class Test(Frame): def printit(self): print "hi" def createWidgets(self): self.question = Label(self, text="Can Find The BLUE Square??????") self.question.pack() self.QUIT = Button(self, text='QUIT', background='red', height=3, command=self.quit) self.QUIT.pack(side=BOTTOM, fill=BOTH) spacer = Frame(self, height="0.25i") spacer.pack(side=BOTTOM) # notice that the scroll region (20" x 20") is larger than # displayed size of the widget (5" x 5") self.draw = Canvas(self, width="5i", height="5i", background="white", scrollregion=(0, 0, "20i", "20i")) self.draw.scrollX = Scrollbar(self, orient=HORIZONTAL) self.draw.scrollY = Scrollbar(self, orient=VERTICAL) # now tie the three together. This is standard boilerplate text self.draw['xscrollcommand'] = self.draw.scrollX.set self.draw['yscrollcommand'] = self.draw.scrollY.set self.draw.scrollX['command'] = self.draw.xview self.draw.scrollY['command'] = self.draw.yview # draw something. Note that the first square # is visible, but you need to scroll to see the second one. self.draw.create_rectangle(0, 0, "3.5i", "3.5i", fill="black") self.draw.create_rectangle("10i", "10i", "13.5i", "13.5i", fill="blue") # pack 'em up self.draw.scrollX.pack(side=BOTTOM, fill=X) self.draw.scrollY.pack(side=RIGHT, fill=Y) self.draw.pack(side=LEFT) def scrollCanvasX(self, *args): print "scrolling", args print self.draw.scrollX.get() def __init__(self, master=None): Frame.__init__(self, master) Pack.config(self) self.createWidgets() test = Test() test.mainloop() PK%L]uk/ tkinter/matt/animation-simple.pynu[from Tkinter import * # This program shows how to use the "after" function to make animation. class Test(Frame): def printit(self): print "hi" def createWidgets(self): self.QUIT = Button(self, text='QUIT', foreground='red', command=self.quit) self.QUIT.pack(side=LEFT, fill=BOTH) self.draw = Canvas(self, width="5i", height="5i") # all of these work.. self.draw.create_rectangle(0, 0, 10, 10, tags="thing", fill="blue") self.draw.pack(side=LEFT) def moveThing(self, *args): # move 1/10 of an inch every 1/10 sec (1" per second, smoothly) self.draw.move("thing", "0.01i", "0.01i") self.after(10, self.moveThing) def __init__(self, master=None): Frame.__init__(self, master) Pack.config(self) self.createWidgets() self.after(10, self.moveThing) test = Test() test.mainloop() PK%L]3--*tkinter/matt/window-creation-w-location.pynu[from Tkinter import * import sys ##sys.path.append("/users/mjc4y/projects/python/tkinter/utils") ##from TkinterUtils import * # this shows how to create a new window with a button in it that # can create new windows class QuitButton(Button): def __init__(self, master, *args, **kwargs): if not kwargs.has_key("text"): kwargs["text"] = "QUIT" if not kwargs.has_key("command"): kwargs["command"] = master.quit apply(Button.__init__, (self, master) + args, kwargs) class Test(Frame): def makeWindow(self, *args): fred = Toplevel() fred.label = Canvas (fred, width="2i", height="2i") fred.label.create_line("0", "0", "2i", "2i") fred.label.create_line("0", "2i", "2i", "0") fred.label.pack() ##centerWindow(fred, self.master) def createWidgets(self): self.QUIT = QuitButton(self) self.QUIT.pack(side=LEFT, fill=BOTH) self.makeWindow = Button(self, text='Make a New Window', width=50, height=20, command=self.makeWindow) self.makeWindow.pack(side=LEFT) def __init__(self, master=None): Frame.__init__(self, master) Pack.config(self) self.createWidgets() test = Test() test.mainloop() PK%L]R۩tkinter/matt/menu-simple.pycnu[ ^c@sddlTdZdZdZdZeZeededdZ e j d e eZ eZ e je e ejd ejd ejd S( i(t*cCs dGHdS(Nsopening new file((((s5/usr/lib64/python2.7/Demo/tkinter/matt/menu-simple.pytnew_file$scCs dGHdS(Nsopening OLD file((((s5/usr/lib64/python2.7/Demo/tkinter/matt/menu-simple.pyt open_file(scCsttdddd}|jdtddt||_|jjdd ddd t|jjdd ddd t|jjdd ddd d |j|d<|S(NttexttFilet underlineitsidetpadxt1mtlabelsNew...tcommandsOpen...tQuittexittmenu( t MenubuttontmBartpacktLEFTtMenuR t add_commandRR(t File_button((s5/usr/lib64/python2.7/Demo/tkinter/matt/menu-simple.pyt makeFileMenu,s cCsttdddd}|jdtddt||_|jjdd d |jjd d t|jj d d |jj d d|jj d d|j|d<|S(NRtEditRiRRRR R tUndoitstatetCuttCopytPasteR ( RRRRRR taddt entryconfigtDISABLEDR(t Edit_button((s5/usr/lib64/python2.7/Demo/tkinter/matt/menu-simple.pyt makeEditMenuFs trelieft borderwidthitfills menu demotpackerN(tTkinterRRRR tTktroottFrametRAISEDRRtXRRt tk_menuBarttitleticonnametmainloop(((s5/usr/lib64/python2.7/Demo/tkinter/matt/menu-simple.pyts #         PK%L]#tkinter/matt/rubber-line-demo-1.pycnu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBs8eZdZdZdZdZddZRS(cCs dGHdS(Nthi((tself((s</usr/lib64/python2.7/Demo/tkinter/matt/rubber-line-demo-1.pytprintitsc Cs{t|ddddddddd |j|_|jjd td tt|d d dd |_|jjd tdS(NttexttQUITt backgroundtredt foregroundtwhitetheightitcommandtsidetfilltwidtht5i( tButtontquitRtpacktBOTTOMtBOTHtCanvast canvasObjecttLEFT(R((s</usr/lib64/python2.7/Demo/tkinter/matt/rubber-line-demo-1.pyt createWidgetsscCs4|jj|j|_|jj|j|_dS(N(Rtcanvasxtxtstartxtcanvasytytstarty(Rtevent((s</usr/lib64/python2.7/Demo/tkinter/matt/rubber-line-demo-1.pyt mouseDownscCs|jj|j}|jj|j}|j|jkr|j|jkr|jj|j|jj |j|j|||_|j ndS(N( RRRRRRRtdeletetrubberbandLinet create_linetupdate_idletasks(RR RR((s</usr/lib64/python2.7/Demo/tkinter/matt/rubber-line-demo-1.pyt mouseMotions$ cCsftj||tj||jd|_tj|j d|j tj|j d|j dS(Ns s( tFramet__init__tPacktconfigRtNoneR#tWidgettbindRR!R&(Rtmaster((s</usr/lib64/python2.7/Demo/tkinter/matt/rubber-line-demo-1.pyR('s    N(t__name__t __module__RRR!R&R+R((((s</usr/lib64/python2.7/Demo/tkinter/matt/rubber-line-demo-1.pyRs    N(tTkinterR'Rttesttmainloop(((s</usr/lib64/python2.7/Demo/tkinter/matt/rubber-line-demo-1.pyts . PK%L]ZZ%tkinter/matt/window-creation-more.pyonu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBs/eZdZdZdZddZRS(cCs dGHdS(Nthi((tself((s>/usr/lib64/python2.7/Demo/tkinter/matt/window-creation-more.pytprintitscCsOt}t|dd|jd|j|_|jj|jd|_dS(NttextsThis is window number %d.tcommandi(tTopleveltButtont windownumt makeWindowtlabeltpack(Rtfred((s>/usr/lib64/python2.7/Demo/tkinter/matt/window-creation-more.pyR s     cCsrt|ddddd|j|_|jjdtdtt|ddd|j|_|jjdtdS( NRtQUITt foregroundtredRtsidetfillsMake a New Window(RtquitRR tLEFTtBOTHR thi_there(R((s>/usr/lib64/python2.7/Demo/tkinter/matt/window-creation-more.pyt createWidgetss cCs4tj||tj|d|_|jdS(Ni(tFramet__init__tPacktconfigR R(Rtmaster((s>/usr/lib64/python2.7/Demo/tkinter/matt/window-creation-more.pyRs  N(t__name__t __module__RR RtNoneR(((s>/usr/lib64/python2.7/Demo/tkinter/matt/window-creation-more.pyRs   N(tTkinterRRttesttmainloop(((s>/usr/lib64/python2.7/Demo/tkinter/matt/window-creation-more.pyts  PK%L]>;tkinter/matt/packer-simple.pyonu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBs&eZdZdZddZRS(cCs|jdGHdS(Ntcommand(thi_there(tself((s7/usr/lib64/python2.7/Demo/tkinter/matt/packer-simple.pytprintitscCst|ddddd|j|_|jjdtdtt|ddd|j|_|jjdtt|dd |_|jjt|dd |_ |j jdS( NttexttQUITt foregroundtredRtsidetfilltHellosbutton 2sbutton 3( tButtontquitRtpacktLEFTtBOTHRRtguy2tguy3(R((s7/usr/lib64/python2.7/Demo/tkinter/matt/packer-simple.pyt createWidgetss cCs+tj||tj||jdS(N(tFramet__init__tPacktconfigR(Rtmaster((s7/usr/lib64/python2.7/Demo/tkinter/matt/packer-simple.pyRs N(t__name__t __module__RRtNoneR(((s7/usr/lib64/python2.7/Demo/tkinter/matt/packer-simple.pyRs  N(tTkinterRRttesttmainloop(((s7/usr/lib64/python2.7/Demo/tkinter/matt/packer-simple.pyts  PK%L]f 44+tkinter/matt/window-creation-w-location.pycnu[ ^c@sYddlTddlZdefdYZdefdYZeZejdS(i(t*Nt QuitButtoncBseZdZRS(cOs\|jdsd|ds   PK%L]F77+tkinter/matt/not-what-you-might-think-2.pyonu[ ^c@sWddlTdefdYZeZejjdejjdejdS(i(t*tTestcBseZdZddZRS(cCst|dddddd|_|jjd|jjdtt|jdd d d d |j|j_|jjjdtdS( Ntwidtht1itheightt backgroundtgreenitsidettexttQUITt foregroundtredtcommand(tFrametGpanelt propagatetpacktLEFTtButtontquitR (tself((sD/usr/lib64/python2.7/Demo/tkinter/matt/not-what-you-might-think-2.pyt createWidgetss cCs+tj||tj||jdS(N(R t__init__tPacktconfigR(Rtmaster((sD/usr/lib64/python2.7/Demo/tkinter/matt/not-what-you-might-think-2.pyRs N(t__name__t __module__RtNoneR(((sD/usr/lib64/python2.7/Demo/tkinter/matt/not-what-you-might-think-2.pyRs s packer demotpackerN(tTkinterR RttestRttitleticonnametmainloop(((sD/usr/lib64/python2.7/Demo/tkinter/matt/not-what-you-might-think-2.pyts  PK%L]: %tkinter/matt/canvas-mult-item-sel.pycnu[ ^c@sCddlTdZdZdefdYZeZejdS(i(t*tredtbluetTestcBs8eZdZdZdZdZddZRS(cCs|jjts;|jjddt|jjdn,|jjddt|jjddt|j |_ |j |_ dS(Ntselectedtfilltwithtag( twidgett find_withtagtCURRENTtdrawt itemconfigtUNSELECTED_COLORtdtagtaddtagtSELECTED_COLORtxtlastxtytlasty(tselftevent((s>/usr/lib64/python2.7/Demo/tkinter/matt/canvas-mult-item-sel.pyt mouseDown s cCsF|jjd|j|j|j|j|j|_|j|_dS(NR(R tmoveRRRR(RR((s>/usr/lib64/python2.7/Demo/tkinter/matt/canvas-mult-item-sel.pyt mouseMove!s* c CsA|jjdddddtdt}|jjddtdS(NiiRttagsRR(R t create_ovalRR R(Rtfred((s>/usr/lib64/python2.7/Demo/tkinter/matt/canvas-mult-item-sel.pyt makeNewDot&scCs(t|ddddd|j|_t|dddd|_tj|jd |jtj|jd |jt|dd dd d|j |_ d t t f}t |ddd||_|jjdtdt|jjdtdtdd|j jdtdt|jjdtdS(NttexttQUITt foregroundRtcommandtwidtht5itheights<1>s smake a new dotRs%s dots are selected and can be dragged. %s are not selected. Click in a dot to select it. Click on empty space to deselect all dots.tsideRtexpandi(tButtontquitRtCanvasR tWidgettbindRRRtbuttonRR tMessagetlabeltpacktBOTTOMtBOTHtXtLEFT(Rtmessage((s>/usr/lib64/python2.7/Demo/tkinter/matt/canvas-mult-item-sel.pyt createWidgets-s cCs+tj||tj||jdS(N(tFramet__init__tPacktconfigR4(Rtmaster((s>/usr/lib64/python2.7/Demo/tkinter/matt/canvas-mult-item-sel.pyR6Hs N(t__name__t __module__RRRR4tNoneR6(((s>/usr/lib64/python2.7/Demo/tkinter/matt/canvas-mult-item-sel.pyRs     N(tTkinterRR R5Rttesttmainloop(((s>/usr/lib64/python2.7/Demo/tkinter/matt/canvas-mult-item-sel.pyts E PK%L]_ "tkinter/matt/canvas-demo-simple.pynu[from Tkinter import * # this program creates a canvas and puts a single polygon on the canvas class Test(Frame): def printit(self): print "hi" def createWidgets(self): self.QUIT = Button(self, text='QUIT', foreground='red', command=self.quit) self.QUIT.pack(side=BOTTOM, fill=BOTH) self.draw = Canvas(self, width="5i", height="5i") # see the other demos for other ways of specifying coords for a polygon self.draw.create_rectangle(0, 0, "3i", "3i", fill="black") self.draw.pack(side=LEFT) def __init__(self, master=None): Frame.__init__(self, master) Pack.config(self) self.createWidgets() test = Test() test.mainloop() PK%L]L  )tkinter/matt/printing-coords-of-items.pyonu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBsAeZdZdZdZdZdZddZRS(cCs|jjts|jj|jd|jd|jd|jddd}|jj|d|j|jj|d|j n|j|_ |j|_ dS(Ni tfilltgreenss( twidgett find_withtagtCURRENTtdrawt create_ovaltxtyttag_bindt mouseEntert mouseLeavetlastxtlasty(tselfteventtfred((sB/usr/lib64/python2.7/Demo/tkinter/matt/printing-coords-of-items.pyt mouseDown s +  cCsF|jjt|j|j|j|j|j|_|j|_dS(N(RtmoveRR RR R(RR((sB/usr/lib64/python2.7/Demo/tkinter/matt/printing-coords-of-items.pyt mouseMoves* cCs+|jjtdd|jjtGHdS(NRtred(Rt itemconfigRtcoords(RR((sB/usr/lib64/python2.7/Demo/tkinter/matt/printing-coords-of-items.pyR "scCs|jjtdddS(NRtblue(RRR(RR((sB/usr/lib64/python2.7/Demo/tkinter/matt/printing-coords-of-items.pyR (scCst|ddddd|j|_|jjdtdtt|dd d d |_|jjdttj |jd |j tj |jd |j dS( NttexttQUITt foregroundRtcommandtsideRtwidtht5itheights<1>s ( tButtontquitRtpacktLEFTtBOTHtCanvasRtWidgettbindRR(R((sB/usr/lib64/python2.7/Demo/tkinter/matt/printing-coords-of-items.pyt createWidgets-scCs+tj||tj||jdS(N(tFramet__init__tPacktconfigR*(Rtmaster((sB/usr/lib64/python2.7/Demo/tkinter/matt/printing-coords-of-items.pyR,7s N( t__name__t __module__RRR R R*tNoneR,(((sB/usr/lib64/python2.7/Demo/tkinter/matt/printing-coords-of-items.pyRs      N(tTkinterR+Rttesttmainloop(((sB/usr/lib64/python2.7/Demo/tkinter/matt/printing-coords-of-items.pyts 7 PK%L]w(tkinter/matt/bind-w-mult-calls-p-type.pynu[from Tkinter import * import string # This program shows how to use a simple type-in box class App(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.entrythingy = Entry() self.entrythingy.pack() # and here we get a callback when the user hits return. we could # make the key that triggers the callback anything we wanted to. # other typical options might be or (for anything) self.entrythingy.bind('', self.print_contents) # Note that here is where we bind a completely different callback to # the same event. We pass "+" here to indicate that we wish to ADD # this callback to the list associated with this event type. # Not specifying "+" would simply override whatever callback was # defined on this event. self.entrythingy.bind('', self.print_something_else, "+") def print_contents(self, event): print "hi. contents of entry is now ---->", self.entrythingy.get() def print_something_else(self, event): print "hi. Now doing something completely different" root = App() root.master.title("Foo") root.mainloop() # secret tip for experts: if you pass *any* non-false value as # the third parameter to bind(), Tkinter.py will accumulate # callbacks instead of overwriting. I use "+" here because that's # the Tk notation for getting this sort of behavior. The perfect GUI # interface would use a less obscure notation. PK%L]  tkinter/matt/canvas-gridding.pyonu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBs8eZdZdZdZdZddZRS(cCs dGHdS(Nthi((tself((s9/usr/lib64/python2.7/Demo/tkinter/matt/canvas-gridding.pytprintit sc Cs{t|ddddddddd |j|_|jjd td tt|d d dd |_|jjd tdS(NttexttQUITt backgroundtredt foregroundtwhitetheightitcommandtsidetfilltwidtht5i( tButtontquitRtpacktBOTTOMtBOTHtCanvast canvasObjecttLEFT(R((s9/usr/lib64/python2.7/Demo/tkinter/matt/canvas-gridding.pyt createWidgets scCs@|jj|j|j|_|jj|j|j|_dS(N(Rtcanvasxtxt griddingSizetstartxtcanvasytytstarty(Rtevent((s9/usr/lib64/python2.7/Demo/tkinter/matt/canvas-gridding.pyt mouseDownscCs|jj|j|j}|jj|j|j}|j|jkr|j|jkr|jj|j |jj |j|j|||_ |j ndS(N( RRRRRRRR tdeletet rubberbandBoxtcreate_rectangletupdate_idletasks(RR!RR((s9/usr/lib64/python2.7/Demo/tkinter/matt/canvas-gridding.pyt mouseMotions$ cCsotj||tj||jd|_d|_tj |j d|j tj |j d|j dS(Ni2s s( tFramet__init__tPacktconfigRtNoneR$RtWidgettbindRR"R'(Rtmaster((s9/usr/lib64/python2.7/Demo/tkinter/matt/canvas-gridding.pyR),s    N(t__name__t __module__RRR"R'R,R)(((s9/usr/lib64/python2.7/Demo/tkinter/matt/canvas-gridding.pyRs    N(tTkinterR(Rttesttmainloop(((s9/usr/lib64/python2.7/Demo/tkinter/matt/canvas-gridding.pyts 3 PK%L]}N  tkinter/matt/pong-demo-1.pynu[from Tkinter import * import string class Pong(Frame): def createWidgets(self): self.QUIT = Button(self, text='QUIT', foreground='red', command=self.quit) self.QUIT.pack(side=LEFT, fill=BOTH) ## The playing field self.draw = Canvas(self, width="5i", height="5i") ## The speed control for the ball self.speed = Scale(self, orient=HORIZONTAL, label="ball speed", from_=-100, to=100) self.speed.pack(side=BOTTOM, fill=X) # The ball self.ball = self.draw.create_oval("0i", "0i", "0.10i", "0.10i", fill="red") self.x = 0.05 self.y = 0.05 self.velocity_x = 0.3 self.velocity_y = 0.5 self.draw.pack(side=LEFT) def moveBall(self, *args): if (self.x > 5.0) or (self.x < 0.0): self.velocity_x = -1.0 * self.velocity_x if (self.y > 5.0) or (self.y < 0.0): self.velocity_y = -1.0 * self.velocity_y deltax = (self.velocity_x * self.speed.get() / 100.0) deltay = (self.velocity_y * self.speed.get() / 100.0) self.x = self.x + deltax self.y = self.y + deltay self.draw.move(self.ball, "%ri" % deltax, "%ri" % deltay) self.after(10, self.moveBall) def __init__(self, master=None): Frame.__init__(self, master) Pack.config(self) self.createWidgets() self.after(10, self.moveBall) game = Pong() game.mainloop() PK%L]aI  *tkinter/matt/canvas-moving-or-creating.pyonu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBsAeZdZdZdZdZdZddZRS(c Cs|jjts|jj|jd|jd|jd|jddddt}|jj|d|j|jj|d|j n|j|_ |j|_ dS(Ni tfilltgreenttagss s ( twidgett find_withtagtCURRENTtdrawt create_ovaltxtyttag_bindt mouseEntert mouseLeavetlastxtlasty(tselfteventtfred((sC/usr/lib64/python2.7/Demo/tkinter/matt/canvas-moving-or-creating.pyt mouseDown s + cCsF|jjt|j|j|j|j|j|_|j|_dS(N(RtmoveRR RR R(RR((sC/usr/lib64/python2.7/Demo/tkinter/matt/canvas-moving-or-creating.pyt mouseMoves* cCs|jjtdddS(NRtred(Rt itemconfigR(RR((sC/usr/lib64/python2.7/Demo/tkinter/matt/canvas-moving-or-creating.pyR $scCs|jjtdddS(NRtblue(RRR(RR((sC/usr/lib64/python2.7/Demo/tkinter/matt/canvas-moving-or-creating.pyR)scCst|ddddd|j|_|jjdtdtt|dd d d |_|jjdttj |jd |j tj |jd |j dS( NttexttQUITt foregroundRtcommandtsideRtwidtht5itheights<1>s ( tButtontquitRtpacktLEFTtBOTHtCanvasRtWidgettbindRR(R((sC/usr/lib64/python2.7/Demo/tkinter/matt/canvas-moving-or-creating.pyt createWidgets.scCs+tj||tj||jdS(N(tFramet__init__tPacktconfigR*(Rtmaster((sC/usr/lib64/python2.7/Demo/tkinter/matt/canvas-moving-or-creating.pyR,8s N( t__name__t __module__RRR RR*tNoneR,(((sC/usr/lib64/python2.7/Demo/tkinter/matt/canvas-moving-or-creating.pyRs      N(tTkinterR+Rttesttmainloop(((sC/usr/lib64/python2.7/Demo/tkinter/matt/canvas-moving-or-creating.pyts 7 PK%L]'tkinter/matt/canvas-w-widget-draw-el.pynu[from Tkinter import * # this file demonstrates the creation of widgets as part of a canvas object class Test(Frame): def printhi(self): print "hi" def createWidgets(self): self.QUIT = Button(self, text='QUIT', foreground='red', command=self.quit) self.QUIT.pack(side=BOTTOM, fill=BOTH) self.draw = Canvas(self, width="5i", height="5i") self.button = Button(self, text="this is a button", command=self.printhi) # note here the coords are given in pixels (form the # upper right and corner of the window, as usual for X) # but might just have well been given in inches or points or # whatever...use the "anchor" option to control what point of the # widget (in this case the button) gets mapped to the given x, y. # you can specify corners, edges, center, etc... self.draw.create_window(300, 300, window=self.button) self.draw.pack(side=LEFT) def __init__(self, master=None): Frame.__init__(self, master) Pack.config(self) self.createWidgets() test = Test() test.mainloop() PK%L]3(jj'tkinter/matt/window-creation-simple.pyonu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBs/eZdZdZdZddZRS(cCs dGHdS(Nthi((tself((s@/usr/lib64/python2.7/Demo/tkinter/matt/window-creation-simple.pytprintitscCs/t}t|dd|_|jjdS(NttextsHere's a new window(tTopleveltLabeltlabeltpack(Rtfred((s@/usr/lib64/python2.7/Demo/tkinter/matt/window-creation-simple.pyt makeWindow s cCsrt|ddddd|j|_|jjdtdtt|ddd|j|_|jjdtdS( NRtQUITt foregroundtredtcommandtsidetfillsMake a New Window(tButtontquitR R tLEFTtBOTHR thi_there(R((s@/usr/lib64/python2.7/Demo/tkinter/matt/window-creation-simple.pyt createWidgetss cCs+tj||tj||jdS(N(tFramet__init__tPacktconfigR(Rtmaster((s@/usr/lib64/python2.7/Demo/tkinter/matt/window-creation-simple.pyRs N(t__name__t __module__RR RtNoneR(((s@/usr/lib64/python2.7/Demo/tkinter/matt/window-creation-simple.pyRs   N(tTkinterRRttesttmainloop(((s@/usr/lib64/python2.7/Demo/tkinter/matt/window-creation-simple.pyts  PK%L]aI  *tkinter/matt/canvas-moving-or-creating.pycnu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBsAeZdZdZdZdZdZddZRS(c Cs|jjts|jj|jd|jd|jd|jddddt}|jj|d|j|jj|d|j n|j|_ |j|_ dS(Ni tfilltgreenttagss s ( twidgett find_withtagtCURRENTtdrawt create_ovaltxtyttag_bindt mouseEntert mouseLeavetlastxtlasty(tselfteventtfred((sC/usr/lib64/python2.7/Demo/tkinter/matt/canvas-moving-or-creating.pyt mouseDown s + cCsF|jjt|j|j|j|j|j|_|j|_dS(N(RtmoveRR RR R(RR((sC/usr/lib64/python2.7/Demo/tkinter/matt/canvas-moving-or-creating.pyt mouseMoves* cCs|jjtdddS(NRtred(Rt itemconfigR(RR((sC/usr/lib64/python2.7/Demo/tkinter/matt/canvas-moving-or-creating.pyR $scCs|jjtdddS(NRtblue(RRR(RR((sC/usr/lib64/python2.7/Demo/tkinter/matt/canvas-moving-or-creating.pyR)scCst|ddddd|j|_|jjdtdtt|dd d d |_|jjdttj |jd |j tj |jd |j dS( NttexttQUITt foregroundRtcommandtsideRtwidtht5itheights<1>s ( tButtontquitRtpacktLEFTtBOTHtCanvasRtWidgettbindRR(R((sC/usr/lib64/python2.7/Demo/tkinter/matt/canvas-moving-or-creating.pyt createWidgets.scCs+tj||tj||jdS(N(tFramet__init__tPacktconfigR*(Rtmaster((sC/usr/lib64/python2.7/Demo/tkinter/matt/canvas-moving-or-creating.pyR,8s N( t__name__t __module__RRR RR*tNoneR,(((sC/usr/lib64/python2.7/Demo/tkinter/matt/canvas-moving-or-creating.pyRs      N(tTkinterR+Rttesttmainloop(((sC/usr/lib64/python2.7/Demo/tkinter/matt/canvas-moving-or-creating.pyts 7 PK%L]>;tkinter/matt/packer-simple.pycnu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBs&eZdZdZddZRS(cCs|jdGHdS(Ntcommand(thi_there(tself((s7/usr/lib64/python2.7/Demo/tkinter/matt/packer-simple.pytprintitscCst|ddddd|j|_|jjdtdtt|ddd|j|_|jjdtt|dd |_|jjt|dd |_ |j jdS( NttexttQUITt foregroundtredRtsidetfilltHellosbutton 2sbutton 3( tButtontquitRtpacktLEFTtBOTHRRtguy2tguy3(R((s7/usr/lib64/python2.7/Demo/tkinter/matt/packer-simple.pyt createWidgetss cCs+tj||tj||jdS(N(tFramet__init__tPacktconfigR(Rtmaster((s7/usr/lib64/python2.7/Demo/tkinter/matt/packer-simple.pyRs N(t__name__t __module__RRtNoneR(((s7/usr/lib64/python2.7/Demo/tkinter/matt/packer-simple.pyRs  N(tTkinterRRttesttmainloop(((s7/usr/lib64/python2.7/Demo/tkinter/matt/packer-simple.pyts  PK%L]F77+tkinter/matt/not-what-you-might-think-2.pycnu[ ^c@sWddlTdefdYZeZejjdejjdejdS(i(t*tTestcBseZdZddZRS(cCst|dddddd|_|jjd|jjdtt|jdd d d d |j|j_|jjjdtdS( Ntwidtht1itheightt backgroundtgreenitsidettexttQUITt foregroundtredtcommand(tFrametGpanelt propagatetpacktLEFTtButtontquitR (tself((sD/usr/lib64/python2.7/Demo/tkinter/matt/not-what-you-might-think-2.pyt createWidgetss cCs+tj||tj||jdS(N(R t__init__tPacktconfigR(Rtmaster((sD/usr/lib64/python2.7/Demo/tkinter/matt/not-what-you-might-think-2.pyRs N(t__name__t __module__RtNoneR(((sD/usr/lib64/python2.7/Demo/tkinter/matt/not-what-you-might-think-2.pyRs s packer demotpackerN(tTkinterR RttestRttitleticonnametmainloop(((sD/usr/lib64/python2.7/Demo/tkinter/matt/not-what-you-might-think-2.pyts  PK%L] yy)tkinter/matt/bind-w-mult-calls-p-type.pyonu[ ^c@sSddlTddlZdefdYZeZejjdejdS(i(t*NtAppcBs&eZddZdZdZRS(cCsftj|||jt|_|jj|jjd|j|jjd|jddS(Ns t+(tFramet__init__tpacktEntryt entrythingytbindtprint_contentstprint_something_else(tselftmaster((sB/usr/lib64/python2.7/Demo/tkinter/matt/bind-w-mult-calls-p-type.pyRs    cCsdG|jjGHdS(Ns"hi. contents of entry is now ---->(Rtget(R tevent((sB/usr/lib64/python2.7/Demo/tkinter/matt/bind-w-mult-calls-p-type.pyR scCs dGHdS(Ns,hi. Now doing something completely different((R R((sB/usr/lib64/python2.7/Demo/tkinter/matt/bind-w-mult-calls-p-type.pyR sN(t__name__t __module__tNoneRR R (((sB/usr/lib64/python2.7/Demo/tkinter/matt/bind-w-mult-calls-p-type.pyRs  tFoo(tTkintertstringRRtrootR ttitletmainloop(((sB/usr/lib64/python2.7/Demo/tkinter/matt/bind-w-mult-calls-p-type.pyts   PK%L] yy)tkinter/matt/bind-w-mult-calls-p-type.pycnu[ ^c@sSddlTddlZdefdYZeZejjdejdS(i(t*NtAppcBs&eZddZdZdZRS(cCsftj|||jt|_|jj|jjd|j|jjd|jddS(Ns t+(tFramet__init__tpacktEntryt entrythingytbindtprint_contentstprint_something_else(tselftmaster((sB/usr/lib64/python2.7/Demo/tkinter/matt/bind-w-mult-calls-p-type.pyRs    cCsdG|jjGHdS(Ns"hi. contents of entry is now ---->(Rtget(R tevent((sB/usr/lib64/python2.7/Demo/tkinter/matt/bind-w-mult-calls-p-type.pyR scCs dGHdS(Ns,hi. Now doing something completely different((R R((sB/usr/lib64/python2.7/Demo/tkinter/matt/bind-w-mult-calls-p-type.pyR sN(t__name__t __module__tNoneRR R (((sB/usr/lib64/python2.7/Demo/tkinter/matt/bind-w-mult-calls-p-type.pyRs  tFoo(tTkintertstringRRtrootR ttitletmainloop(((sB/usr/lib64/python2.7/Demo/tkinter/matt/bind-w-mult-calls-p-type.pyts   PK%L]̆^+tkinter/matt/not-what-you-might-think-1.pyonu[ ^c@sWddlTdefdYZeZejjdejjdejdS(i(t*tTestcBseZdZddZRS(cCsxt|dddddd|_|jjdtt|jddd d d |j|j_|jjjdtdS( Ntwidtht1itheightt backgroundtgreentsidettexttQUITt foregroundtredtcommand(tFrametGpaneltpacktLEFTtButtontquitR (tself((sD/usr/lib64/python2.7/Demo/tkinter/matt/not-what-you-might-think-1.pyt createWidgetss cCs+tj||tj||jdS(N(R t__init__tPacktconfigR(Rtmaster((sD/usr/lib64/python2.7/Demo/tkinter/matt/not-what-you-might-think-1.pyRs N(t__name__t __module__RtNoneR(((sD/usr/lib64/python2.7/Demo/tkinter/matt/not-what-you-might-think-1.pyRs s packer demotpackerN(tTkinterR RttestRttitleticonnametmainloop(((sD/usr/lib64/python2.7/Demo/tkinter/matt/not-what-you-might-think-1.pyts  PK%L]#tkinter/matt/rubber-line-demo-1.pyonu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBs8eZdZdZdZdZddZRS(cCs dGHdS(Nthi((tself((s</usr/lib64/python2.7/Demo/tkinter/matt/rubber-line-demo-1.pytprintitsc Cs{t|ddddddddd |j|_|jjd td tt|d d dd |_|jjd tdS(NttexttQUITt backgroundtredt foregroundtwhitetheightitcommandtsidetfilltwidtht5i( tButtontquitRtpacktBOTTOMtBOTHtCanvast canvasObjecttLEFT(R((s</usr/lib64/python2.7/Demo/tkinter/matt/rubber-line-demo-1.pyt createWidgetsscCs4|jj|j|_|jj|j|_dS(N(Rtcanvasxtxtstartxtcanvasytytstarty(Rtevent((s</usr/lib64/python2.7/Demo/tkinter/matt/rubber-line-demo-1.pyt mouseDownscCs|jj|j}|jj|j}|j|jkr|j|jkr|jj|j|jj |j|j|||_|j ndS(N( RRRRRRRtdeletetrubberbandLinet create_linetupdate_idletasks(RR RR((s</usr/lib64/python2.7/Demo/tkinter/matt/rubber-line-demo-1.pyt mouseMotions$ cCsftj||tj||jd|_tj|j d|j tj|j d|j dS(Ns s( tFramet__init__tPacktconfigRtNoneR#tWidgettbindRR!R&(Rtmaster((s</usr/lib64/python2.7/Demo/tkinter/matt/rubber-line-demo-1.pyR('s    N(t__name__t __module__RRR!R&R+R((((s</usr/lib64/python2.7/Demo/tkinter/matt/rubber-line-demo-1.pyRs    N(tTkinterR'Rttesttmainloop(((s</usr/lib64/python2.7/Demo/tkinter/matt/rubber-line-demo-1.pyts . PK%L]br; ; 'tkinter/matt/canvas-with-scrollbars.pyonu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBs/eZdZdZdZddZRS(cCs dGHdS(Nthi((tself((s@/usr/lib64/python2.7/Demo/tkinter/matt/canvas-with-scrollbars.pytprintit sc Cst|dd|_|jjt|ddddddd|j|_|jjd td tt|dd }|jd tt |d d dd dddd|_ t |dt |j _ t |dt|j _|j j j|j d<|j jj|j d<|j j|j j d<|j j|j jd<|j jddddd d|j jddddd d|j j jd td t|j jjd td t|j jd tdS(NttextsCan Find The BLUE Square??????tQUITt backgroundtredtheightitcommandtsidetfills0.25itwidtht5itwhitet scrollregionit20itorienttxscrollcommandtyscrollcommands3.5itblackt10is13.5itblue(iiRR(tLabeltquestiontpacktButtontquitRtBOTTOMtBOTHtFrametCanvastdrawt Scrollbart HORIZONTALtscrollXtVERTICALtscrollYtsettxviewtyviewtcreate_rectangletXtRIGHTtYtLEFT(Rtspacer((s@/usr/lib64/python2.7/Demo/tkinter/matt/canvas-with-scrollbars.pyt createWidgets s*  cGsdG|GH|jjjGHdS(Nt scrolling(R!R$tget(Rtargs((s@/usr/lib64/python2.7/Demo/tkinter/matt/canvas-with-scrollbars.pyt scrollCanvasX0s cCs+tj||tj||jdS(N(Rt__init__tPacktconfigR0(Rtmaster((s@/usr/lib64/python2.7/Demo/tkinter/matt/canvas-with-scrollbars.pyR55s N(t__name__t __module__RR0R4tNoneR5(((s@/usr/lib64/python2.7/Demo/tkinter/matt/canvas-with-scrollbars.pyRs  $ N(tTkinterRRttesttmainloop(((s@/usr/lib64/python2.7/Demo/tkinter/matt/canvas-with-scrollbars.pyts 2 PK%L]> tkinter/matt/two-radio-groups.pynu[from Tkinter import * # The way to think about this is that each radio button menu # controls a different variable -- clicking on one of the # mutually exclusive choices in a radiobutton assigns some value # to an application variable you provide. When you define a # radiobutton menu choice, you have the option of specifying the # name of a varaible and value to assign to that variable when # that choice is selected. This clever mechanism relieves you, # the programmer, from having to write a dumb callback that # probably wouldn't have done anything more than an assignment # anyway. The Tkinter options for this follow their Tk # counterparts: # {"variable" : my_flavor_variable, "value" : "strawberry"} # where my_flavor_variable is an instance of one of the # subclasses of Variable, provided in Tkinter.py (there is # StringVar(), IntVar(), DoubleVar() and BooleanVar() to choose # from) def makePoliticalParties(var): # make menu button Radiobutton_button = Menubutton(mBar, text='Political Party', underline=0) Radiobutton_button.pack(side=LEFT, padx='2m') # the primary pulldown Radiobutton_button.menu = Menu(Radiobutton_button) Radiobutton_button.menu.add_radiobutton(label='Republican', variable=var, value=1) Radiobutton_button.menu.add('radiobutton', {'label': 'Democrat', 'variable' : var, 'value' : 2}) Radiobutton_button.menu.add('radiobutton', {'label': 'Libertarian', 'variable' : var, 'value' : 3}) var.set(2) # set up a pointer from the file menubutton back to the file menu Radiobutton_button['menu'] = Radiobutton_button.menu return Radiobutton_button def makeFlavors(var): # make menu button Radiobutton_button = Menubutton(mBar, text='Flavors', underline=0) Radiobutton_button.pack(side=LEFT, padx='2m') # the primary pulldown Radiobutton_button.menu = Menu(Radiobutton_button) Radiobutton_button.menu.add_radiobutton(label='Strawberry', variable=var, value='Strawberry') Radiobutton_button.menu.add_radiobutton(label='Chocolate', variable=var, value='Chocolate') Radiobutton_button.menu.add_radiobutton(label='Rocky Road', variable=var, value='Rocky Road') # choose a default var.set("Chocolate") # set up a pointer from the file menubutton back to the file menu Radiobutton_button['menu'] = Radiobutton_button.menu return Radiobutton_button def printStuff(): print "party is", party.get() print "flavor is", flavor.get() print ################################################# #### Main starts here ... root = Tk() # make a menu bar mBar = Frame(root, relief=RAISED, borderwidth=2) mBar.pack(fill=X) # make two application variables, # one to control each radio button set party = IntVar() flavor = StringVar() Radiobutton_button = makePoliticalParties(party) Radiobutton_button2 = makeFlavors(flavor) # finally, install the buttons in the menu bar. # This allows for scanning from one menubutton to the next. mBar.tk_menuBar(Radiobutton_button, Radiobutton_button2) b = Button(root, text="print party and flavor", foreground="red", command=printStuff) b.pack(side=TOP) root.title('menu demo') root.iconname('menu demo') root.mainloop() PK%L]>kv v )tkinter/matt/canvas-moving-or-creating.pynu[from Tkinter import * # this file demonstrates a more sophisticated movement -- # move dots or create new ones if you click outside the dots class Test(Frame): ################################################################### ###### Event callbacks for THE CANVAS (not the stuff drawn on it) ################################################################### def mouseDown(self, event): # see if we're inside a dot. If we are, it # gets tagged as CURRENT for free by tk. if not event.widget.find_withtag(CURRENT): # there is no dot here, so we can make one, # and bind some interesting behavior to it. # ------ # create a dot, and mark it as CURRENT fred = self.draw.create_oval( event.x - 10, event.y -10, event.x +10, event.y + 10, fill="green", tags=CURRENT) self.draw.tag_bind(fred, "", self.mouseEnter) self.draw.tag_bind(fred, "", self.mouseLeave) self.lastx = event.x self.lasty = event.y def mouseMove(self, event): self.draw.move(CURRENT, event.x - self.lastx, event.y - self.lasty) self.lastx = event.x self.lasty = event.y ################################################################### ###### Event callbacks for canvas ITEMS (stuff drawn on the canvas) ################################################################### def mouseEnter(self, event): # the CURRENT tag is applied to the object the cursor is over. # this happens automatically. self.draw.itemconfig(CURRENT, fill="red") def mouseLeave(self, event): # the CURRENT tag is applied to the object the cursor is over. # this happens automatically. self.draw.itemconfig(CURRENT, fill="blue") def createWidgets(self): self.QUIT = Button(self, text='QUIT', foreground='red', command=self.quit) self.QUIT.pack(side=LEFT, fill=BOTH) self.draw = Canvas(self, width="5i", height="5i") self.draw.pack(side=LEFT) Widget.bind(self.draw, "<1>", self.mouseDown) Widget.bind(self.draw, "", self.mouseMove) def __init__(self, master=None): Frame.__init__(self, master) Pack.config(self) self.createWidgets() test = Test() test.mainloop() PK%L]3(jj'tkinter/matt/window-creation-simple.pycnu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBs/eZdZdZdZddZRS(cCs dGHdS(Nthi((tself((s@/usr/lib64/python2.7/Demo/tkinter/matt/window-creation-simple.pytprintitscCs/t}t|dd|_|jjdS(NttextsHere's a new window(tTopleveltLabeltlabeltpack(Rtfred((s@/usr/lib64/python2.7/Demo/tkinter/matt/window-creation-simple.pyt makeWindow s cCsrt|ddddd|j|_|jjdtdtt|ddd|j|_|jjdtdS( NRtQUITt foregroundtredtcommandtsidetfillsMake a New Window(tButtontquitR R tLEFTtBOTHR thi_there(R((s@/usr/lib64/python2.7/Demo/tkinter/matt/window-creation-simple.pyt createWidgetss cCs+tj||tj||jdS(N(tFramet__init__tPacktconfigR(Rtmaster((s@/usr/lib64/python2.7/Demo/tkinter/matt/window-creation-simple.pyRs N(t__name__t __module__RR RtNoneR(((s@/usr/lib64/python2.7/Demo/tkinter/matt/window-creation-simple.pyRs   N(tTkinterRRttesttmainloop(((s@/usr/lib64/python2.7/Demo/tkinter/matt/window-creation-simple.pyts  PK%L]ll+tkinter/matt/packer-and-placer-together.pyonu[ ^c@seddlTdZdZdZeZeeZejdejddej dS(i(t*cCs#tjjd|jd|jdS(Ntxty(tapptbuttontplaceRR(tevent((sD/usr/lib64/python2.7/Demo/tkinter/matt/packer-and-placer-together.pyt do_motionscCs dGHdS(Ns calling me!((((sD/usr/lib64/python2.7/Demo/tkinter/matt/packer-and-placer-together.pytdothis scCst|dddddd}|jdtddt|d d d d d t|_|jjdddddt|jdt |S(Ntwidthitheightt backgroundtgreentfilltexpandit foregroundtredttexttamazingtcommandtrelxg?trelygtanchors( tFrametpacktBOTHtButtonRRRtNWtbindR(ttoptf((sD/usr/lib64/python2.7/Demo/tkinter/matt/packer-and-placer-together.pyt createWidgets s !t400x400iN( tTkinterRRRtTktrootRtgeometrytmaxsizetmainloop(((sD/usr/lib64/python2.7/Demo/tkinter/matt/packer-and-placer-together.pyts       PK%L]t44tkinter/matt/entry-simple.pycnu[ ^c@sSddlTddlZdefdYZeZejjdejdS(i(t*NtAppcBseZddZdZRS(cCsMtj|||jt|_|jj|jjd|jdS(Ns (tFramet__init__tpacktEntryt entrythingytbindtprint_contents(tselftmaster((s6/usr/lib64/python2.7/Demo/tkinter/matt/entry-simple.pyRs    cCsdG|jjGHdS(Ns"hi. contents of entry is now ---->(Rtget(R tevent((s6/usr/lib64/python2.7/Demo/tkinter/matt/entry-simple.pyRsN(t__name__t __module__tNoneRR(((s6/usr/lib64/python2.7/Demo/tkinter/matt/entry-simple.pyRs tFoo(tTkintertstringRRtrootR ttitletmainloop(((s6/usr/lib64/python2.7/Demo/tkinter/matt/entry-simple.pyts   PK%L]: %tkinter/matt/canvas-mult-item-sel.pyonu[ ^c@sCddlTdZdZdefdYZeZejdS(i(t*tredtbluetTestcBs8eZdZdZdZdZddZRS(cCs|jjts;|jjddt|jjdn,|jjddt|jjddt|j |_ |j |_ dS(Ntselectedtfilltwithtag( twidgett find_withtagtCURRENTtdrawt itemconfigtUNSELECTED_COLORtdtagtaddtagtSELECTED_COLORtxtlastxtytlasty(tselftevent((s>/usr/lib64/python2.7/Demo/tkinter/matt/canvas-mult-item-sel.pyt mouseDown s cCsF|jjd|j|j|j|j|j|_|j|_dS(NR(R tmoveRRRR(RR((s>/usr/lib64/python2.7/Demo/tkinter/matt/canvas-mult-item-sel.pyt mouseMove!s* c CsA|jjdddddtdt}|jjddtdS(NiiRttagsRR(R t create_ovalRR R(Rtfred((s>/usr/lib64/python2.7/Demo/tkinter/matt/canvas-mult-item-sel.pyt makeNewDot&scCs(t|ddddd|j|_t|dddd|_tj|jd |jtj|jd |jt|dd dd d|j |_ d t t f}t |ddd||_|jjdtdt|jjdtdtdd|j jdtdt|jjdtdS(NttexttQUITt foregroundRtcommandtwidtht5itheights<1>s smake a new dotRs%s dots are selected and can be dragged. %s are not selected. Click in a dot to select it. Click on empty space to deselect all dots.tsideRtexpandi(tButtontquitRtCanvasR tWidgettbindRRRtbuttonRR tMessagetlabeltpacktBOTTOMtBOTHtXtLEFT(Rtmessage((s>/usr/lib64/python2.7/Demo/tkinter/matt/canvas-mult-item-sel.pyt createWidgets-s cCs+tj||tj||jdS(N(tFramet__init__tPacktconfigR4(Rtmaster((s>/usr/lib64/python2.7/Demo/tkinter/matt/canvas-mult-item-sel.pyR6Hs N(t__name__t __module__RRRR4tNoneR6(((s>/usr/lib64/python2.7/Demo/tkinter/matt/canvas-mult-item-sel.pyRs     N(tTkinterRR R5Rttesttmainloop(((s>/usr/lib64/python2.7/Demo/tkinter/matt/canvas-mult-item-sel.pyts E PK%L]gtkinter/matt/00-HELLO-WORLD.pyonu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBs&eZdZdZddZRS(cCs dGHdS(Nthi((tself((s8/usr/lib64/python2.7/Demo/tkinter/matt/00-HELLO-WORLD.pytprintitscCsrt|ddddd|j|_|jjdtdtt|ddd|j|_|jjdtdS( NttexttQUITt foregroundtredtcommandtsidetfilltHello(tButtontquitRtpacktLEFTtBOTHRthi_there(R((s8/usr/lib64/python2.7/Demo/tkinter/matt/00-HELLO-WORLD.pyt createWidgets s cCs+tj||tj||jdS(N(tFramet__init__tPacktconfigR(Rtmaster((s8/usr/lib64/python2.7/Demo/tkinter/matt/00-HELLO-WORLD.pyRs N(t__name__t __module__RRtNoneR(((s8/usr/lib64/python2.7/Demo/tkinter/matt/00-HELLO-WORLD.pyRs  N(tTkinterRRttesttmainloop(((s8/usr/lib64/python2.7/Demo/tkinter/matt/00-HELLO-WORLD.pyts  PK%L]b*//&tkinter/matt/window-creation-simple.pynu[from Tkinter import * # this shows how to spawn off new windows at a button press class Test(Frame): def printit(self): print "hi" def makeWindow(self): fred = Toplevel() fred.label = Label(fred, text="Here's a new window") fred.label.pack() def createWidgets(self): self.QUIT = Button(self, text='QUIT', foreground='red', command=self.quit) self.QUIT.pack(side=LEFT, fill=BOTH) # a hello button self.hi_there = Button(self, text='Make a New Window', command=self.makeWindow) self.hi_there.pack(side=LEFT) def __init__(self, master=None): Frame.__init__(self, master) Pack.config(self) self.createWidgets() test = Test() test.mainloop() PK%L]v 'tkinter/matt/rubber-band-box-demo-1.pycnu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBsAeZdZdZdZdZdZddZRS(cCs dGHdS(Nthi((tself((s@/usr/lib64/python2.7/Demo/tkinter/matt/rubber-band-box-demo-1.pytprintitsc Cs{t|ddddddddd |j|_|jjd td tt|d d dd |_|jjd tdS(NttexttQUITt backgroundtredt foregroundtwhitetheightitcommandtsidetfilltwidtht5i( tButtontquitRtpacktBOTTOMtBOTHtCanvast canvasObjecttLEFT(R((s@/usr/lib64/python2.7/Demo/tkinter/matt/rubber-band-box-demo-1.pyt createWidgetsscCs4|jj|j|_|jj|j|_dS(N(Rtcanvasxtxtstartxtcanvasytytstarty(Rtevent((s@/usr/lib64/python2.7/Demo/tkinter/matt/rubber-band-box-demo-1.pyt mouseDownscCs|jj|j}|jj|j}|j|jkr|j|jkr|jj|j|jj |j|j|||_|j ndS(N( RRRRRRRtdeletet rubberbandBoxtcreate_rectangletupdate_idletasks(RR RR((s@/usr/lib64/python2.7/Demo/tkinter/matt/rubber-band-box-demo-1.pyt mouseMotions$ cCs|jj|jdS(N(RR"R#(RR ((s@/usr/lib64/python2.7/Demo/tkinter/matt/rubber-band-box-demo-1.pytmouseUp'scCstj||tj||jd|_tj|j d|j tj|j d|j tj|j d|j dS(Ns ss( tFramet__init__tPacktconfigRtNoneR#tWidgettbindRR!R&R'(Rtmaster((s@/usr/lib64/python2.7/Demo/tkinter/matt/rubber-band-box-demo-1.pyR)*s   N( t__name__t __module__RRR!R&R'R,R)(((s@/usr/lib64/python2.7/Demo/tkinter/matt/rubber-band-box-demo-1.pyRs     N(tTkinterR(Rttesttmainloop(((s@/usr/lib64/python2.7/Demo/tkinter/matt/rubber-band-box-demo-1.pyts 5 PK%L]f 44+tkinter/matt/window-creation-w-location.pyonu[ ^c@sYddlTddlZdefdYZdefdYZeZejdS(i(t*Nt QuitButtoncBseZdZRS(cOs\|jdsd|ds   PK%L]gtkinter/matt/00-HELLO-WORLD.pycnu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBs&eZdZdZddZRS(cCs dGHdS(Nthi((tself((s8/usr/lib64/python2.7/Demo/tkinter/matt/00-HELLO-WORLD.pytprintitscCsrt|ddddd|j|_|jjdtdtt|ddd|j|_|jjdtdS( NttexttQUITt foregroundtredtcommandtsidetfilltHello(tButtontquitRtpacktLEFTtBOTHRthi_there(R((s8/usr/lib64/python2.7/Demo/tkinter/matt/00-HELLO-WORLD.pyt createWidgets s cCs+tj||tj||jdS(N(tFramet__init__tPacktconfigR(Rtmaster((s8/usr/lib64/python2.7/Demo/tkinter/matt/00-HELLO-WORLD.pyRs N(t__name__t __module__RRtNoneR(((s8/usr/lib64/python2.7/Demo/tkinter/matt/00-HELLO-WORLD.pyRs  N(tTkinterRRttesttmainloop(((s8/usr/lib64/python2.7/Demo/tkinter/matt/00-HELLO-WORLD.pyts  PK%L]a>oQ*tkinter/matt/animation-w-velocity-ctrl.pyonu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBs/eZdZdZdZddZRS(cCs dGHdS(Nthi((tself((sC/usr/lib64/python2.7/Demo/tkinter/matt/animation-w-velocity-ctrl.pytprintit sc Cst|ddddd|j|_|jjdtdtt|dd d d |_t|d t d d dd|_ |j jdtdt |jj dddddddd|jjdt dS(NttexttQUITt foregroundtredtcommandtsidetfilltwidtht5itheighttorienttfrom_ittoidii ttagstthingtblue(tButtontquitRtpacktBOTTOMtBOTHtCanvastdrawtScalet HORIZONTALtspeedtXtcreate_rectangletLEFT(R((sC/usr/lib64/python2.7/Demo/tkinter/matt/animation-w-velocity-ctrl.pyt createWidgets s!%cGsY|jj}t|d}d|f}|jjd|||jd|jdS(Ng@@s%riRi (RtgettfloatRtmovetaftert moveThing(Rtargstvelocitytstr((sC/usr/lib64/python2.7/Demo/tkinter/matt/animation-w-velocity-ctrl.pyR's  cCs>tj||tj||j|jd|jdS(Ni (tFramet__init__tPacktconfigR"R&R'(Rtmaster((sC/usr/lib64/python2.7/Demo/tkinter/matt/animation-w-velocity-ctrl.pyR,#s  N(t__name__t __module__RR"R'tNoneR,(((sC/usr/lib64/python2.7/Demo/tkinter/matt/animation-w-velocity-ctrl.pyR s   N(tTkinterR+Rttesttmainloop(((sC/usr/lib64/python2.7/Demo/tkinter/matt/animation-w-velocity-ctrl.pyts ! PK%L]  tkinter/matt/canvas-gridding.pycnu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBs8eZdZdZdZdZddZRS(cCs dGHdS(Nthi((tself((s9/usr/lib64/python2.7/Demo/tkinter/matt/canvas-gridding.pytprintit sc Cs{t|ddddddddd |j|_|jjd td tt|d d dd |_|jjd tdS(NttexttQUITt backgroundtredt foregroundtwhitetheightitcommandtsidetfilltwidtht5i( tButtontquitRtpacktBOTTOMtBOTHtCanvast canvasObjecttLEFT(R((s9/usr/lib64/python2.7/Demo/tkinter/matt/canvas-gridding.pyt createWidgets scCs@|jj|j|j|_|jj|j|j|_dS(N(Rtcanvasxtxt griddingSizetstartxtcanvasytytstarty(Rtevent((s9/usr/lib64/python2.7/Demo/tkinter/matt/canvas-gridding.pyt mouseDownscCs|jj|j|j}|jj|j|j}|j|jkr|j|jkr|jj|j |jj |j|j|||_ |j ndS(N( RRRRRRRR tdeletet rubberbandBoxtcreate_rectangletupdate_idletasks(RR!RR((s9/usr/lib64/python2.7/Demo/tkinter/matt/canvas-gridding.pyt mouseMotions$ cCsotj||tj||jd|_d|_tj |j d|j tj |j d|j dS(Ni2s s( tFramet__init__tPacktconfigRtNoneR$RtWidgettbindRR"R'(Rtmaster((s9/usr/lib64/python2.7/Demo/tkinter/matt/canvas-gridding.pyR),s    N(t__name__t __module__RRR"R'R,R)(((s9/usr/lib64/python2.7/Demo/tkinter/matt/canvas-gridding.pyRs    N(tTkinterR(Rttesttmainloop(((s9/usr/lib64/python2.7/Demo/tkinter/matt/canvas-gridding.pyts 3 PK%L])'tkinter/matt/canvas-reading-tag-info.pynu[from Tkinter import * class Test(Frame): def printit(self): print "hi" def createWidgets(self): self.QUIT = Button(self, text='QUIT', foreground='red', command=self.quit) self.QUIT.pack(side=BOTTOM, fill=BOTH) self.drawing = Canvas(self, width="5i", height="5i") # make a shape pgon = self.drawing.create_polygon( 10, 10, 110, 10, 110, 110, 10 , 110, fill="red", tags=("weee", "foo", "groo")) # this is how you query an object for its attributes # config options FOR CANVAS ITEMS always come back in tuples of length 5. # 0 attribute name # 1 BLANK # 2 BLANK # 3 default value # 4 current value # the blank spots are for consistency with the config command that # is used for widgets. (remember, this is for ITEMS drawn # on a canvas widget, not widgets) option_value = self.drawing.itemconfig(pgon, "stipple") print "pgon's current stipple value is -->", option_value[4], "<--" option_value = self.drawing.itemconfig(pgon, "fill") print "pgon's current fill value is -->", option_value[4], "<--" print " when he is usually colored -->", option_value[3], "<--" ## here we print out all the tags associated with this object option_value = self.drawing.itemconfig(pgon, "tags") print "pgon's tags are", option_value[4] self.drawing.pack(side=LEFT) def __init__(self, master=None): Frame.__init__(self, master) Pack.config(self) self.createWidgets() test = Test() test.mainloop() PK%L]#Utkinter/matt/entry-simple.pynu[from Tkinter import * import string # This program shows how to use a simple type-in box class App(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.entrythingy = Entry() self.entrythingy.pack() # and here we get a callback when the user hits return. we could # make the key that triggers the callback anything we wanted to. # other typical options might be or (for anything) self.entrythingy.bind('', self.print_contents) def print_contents(self, event): print "hi. contents of entry is now ---->", self.entrythingy.get() root = App() root.master.title("Foo") root.mainloop() PK%L]Q.#tkinter/matt/killing-window-w-wm.pynu[from Tkinter import * # This file shows how to trap the killing of a window # when the user uses window manager menus (typ. upper left hand corner # menu in the decoration border). ### ******* this isn't really called -- read the comments def my_delete_callback(): print "whoops -- tried to delete me!" class Test(Frame): def deathHandler(self, event): print self, "is now getting nuked. performing some save here...." def createWidgets(self): # a hello button self.hi_there = Button(self, text='Hello') self.hi_there.pack(side=LEFT) def __init__(self, master=None): Frame.__init__(self, master) Pack.config(self) self.createWidgets() ### ### PREVENT WM kills from happening ### # the docs would have you do this: # self.master.protocol("WM_DELETE_WINDOW", my_delete_callback) # unfortunately, some window managers will not send this request to a window. # the "protocol" function seems incapable of trapping these "aggressive" window kills. # this line of code catches everything, tho. The window is deleted, but you have a chance # of cleaning up first. self.bind_all("", self.deathHandler) test = Test() test.mainloop() PK%L]D66tkinter/matt/placer-simple.pynu[from Tkinter import * # This is a program that tests the placer geom manager def do_motion(event): app.button.place(x=event.x, y=event.y) def dothis(): print 'calling me!' def createWidgets(top): # make a frame. Note that the widget is 200 x 200 # and the window containing is 400x400. We do this # simply to show that this is possible. The rest of the # area is inaccesssible. f = Frame(top, width=200, height=200, background='green') # place it so the upper left hand corner of # the frame is in the upper left corner of # the parent f.place(relx=0.0, rely=0.0) # now make a button f.button = Button(f, foreground='red', text='amazing', command=dothis) # and place it so that the nw corner is # 1/2 way along the top X edge of its' parent f.button.place(relx=0.5, rely=0.0, anchor=NW) # allow the user to move the button SUIT-style. f.bind('', do_motion) return f root = Tk() app = createWidgets(root) root.geometry("400x400") root.maxsize(1000, 1000) root.mainloop() PK%L]}` ` (tkinter/matt/printing-coords-of-items.pynu[from Tkinter import * # this file demonstrates the creation of widgets as part of a canvas object class Test(Frame): ################################################################### ###### Event callbacks for THE CANVAS (not the stuff drawn on it) ################################################################### def mouseDown(self, event): # see if we're inside a dot. If we are, it # gets tagged as CURRENT for free by tk. if not event.widget.find_withtag(CURRENT): # there is no dot here, so we can make one, # and bind some interesting behavior to it. # ------ # create a dot, and mark it as current fred = self.draw.create_oval( event.x - 10, event.y -10, event.x +10, event.y + 10, fill="green") self.draw.tag_bind(fred, "", self.mouseEnter) self.draw.tag_bind(fred, "", self.mouseLeave) self.lastx = event.x self.lasty = event.y def mouseMove(self, event): self.draw.move(CURRENT, event.x - self.lastx, event.y - self.lasty) self.lastx = event.x self.lasty = event.y ################################################################### ###### Event callbacks for canvas ITEMS (stuff drawn on the canvas) ################################################################### def mouseEnter(self, event): # the "current" tag is applied to the object the cursor is over. # this happens automatically. self.draw.itemconfig(CURRENT, fill="red") print self.draw.coords(CURRENT) def mouseLeave(self, event): # the "current" tag is applied to the object the cursor is over. # this happens automatically. self.draw.itemconfig(CURRENT, fill="blue") def createWidgets(self): self.QUIT = Button(self, text='QUIT', foreground='red', command=self.quit) self.QUIT.pack(side=LEFT, fill=BOTH) self.draw = Canvas(self, width="5i", height="5i") self.draw.pack(side=LEFT) Widget.bind(self.draw, "<1>", self.mouseDown) Widget.bind(self.draw, "", self.mouseMove) def __init__(self, master=None): Frame.__init__(self, master) Pack.config(self) self.createWidgets() test = Test() test.mainloop() PK%L]PPtkinter/matt/pong-demo-1.pyonu[ ^c@sCddlTddlZdefdYZeZejdS(i(t*NtPongcBs&eZdZdZddZRS(c Cst|ddddd|j|_|jjdtdtt|dd d d |_t|d t d d dddd|_ |j jdt dt |jj dddddd|_d|_d|_d|_d|_|jjdtdS(NttexttQUITt foregroundtredtcommandtsidetfilltwidtht5itheighttorienttlabels ball speedtfrom_ittoidt0is0.10ig?g333333?g?(tButtontquitRtpacktLEFTtBOTHtCanvastdrawtScalet HORIZONTALtspeedtBOTTOMtXt create_ovaltballtxtyt velocity_xt velocity_y(tself((s5/usr/lib64/python2.7/Demo/tkinter/matt/pong-demo-1.pyt createWidgetss     cGs|jdks|jdkr1d|j|_n|jdksO|jdkrbd|j|_n|j|jjd}|j|jjd}|j||_|j||_|jj|jd|d||j d|j dS(Ng@gggY@s%rii ( RR!R R"RtgetRtmoveRtaftertmoveBall(R#targstdeltaxtdeltay((s5/usr/lib64/python2.7/Demo/tkinter/matt/pong-demo-1.pyR(s!cCs>tj||tj||j|jd|jdS(Ni (tFramet__init__tPacktconfigR$R'R((R#tmaster((s5/usr/lib64/python2.7/Demo/tkinter/matt/pong-demo-1.pyR--s  N(t__name__t __module__R$R(tNoneR-(((s5/usr/lib64/python2.7/Demo/tkinter/matt/pong-demo-1.pyRs  (tTkintertstringR,Rtgametmainloop(((s5/usr/lib64/python2.7/Demo/tkinter/matt/pong-demo-1.pyts  . PK%L] 4+!tkinter/matt/two-radio-groups.pyonu[ ^c@sddlTdZdZdZeZeededdZej de e Z e Zee ZeeZejeeeed d d d d eZej deejdejdejdS(i(t*cCsttdddd}|jdtddt||_|jjdd d |d d |jjd idd6|d 6dd 6|jjd idd6|d 6dd 6|jd|j|d<|S(NttextsPolitical Partyt underlineitsidetpadxt2mtlabelt Republicantvariabletvalueit radiobuttontDemocratit Libertarianitmenu( t MenubuttontmBartpacktLEFTtMenuR tadd_radiobuttontaddtset(tvartRadiobutton_button((s:/usr/lib64/python2.7/Demo/tkinter/matt/two-radio-groups.pytmakePoliticalPartiess      cCsttdddd}|jdtddt||_|jjdd d |d d |jjdd d |d d |jjdd d |d d |jd |j|d<|S(NRtFlavorsRiRRRRt StrawberryRR t Chocolates Rocky RoadR (RRRRRR RR(RR((s:/usr/lib64/python2.7/Demo/tkinter/matt/two-radio-groups.pyt makeFlavors2s      cCs#dGtjGHdGtjGHHdS(Nsparty iss flavor is(tpartytgettflavor(((s:/usr/lib64/python2.7/Demo/tkinter/matt/two-radio-groups.pyt printStuffMstrelieft borderwidthitfillRsprint party and flavort foregroundtredtcommandRs menu demoN(tTkinterRRR tTktroottFrametRAISEDRRtXtIntVarRt StringVarRRtRadiobutton_button2t tk_menuBartButtontbtTOPttitleticonnametmainloop(((s:/usr/lib64/python2.7/Demo/tkinter/matt/two-radio-groups.pyts"            PK%L]br; ; 'tkinter/matt/canvas-with-scrollbars.pycnu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBs/eZdZdZdZddZRS(cCs dGHdS(Nthi((tself((s@/usr/lib64/python2.7/Demo/tkinter/matt/canvas-with-scrollbars.pytprintit sc Cst|dd|_|jjt|ddddddd|j|_|jjd td tt|dd }|jd tt |d d dd dddd|_ t |dt |j _ t |dt|j _|j j j|j d<|j jj|j d<|j j|j j d<|j j|j jd<|j jddddd d|j jddddd d|j j jd td t|j jjd td t|j jd tdS(NttextsCan Find The BLUE Square??????tQUITt backgroundtredtheightitcommandtsidetfills0.25itwidtht5itwhitet scrollregionit20itorienttxscrollcommandtyscrollcommands3.5itblackt10is13.5itblue(iiRR(tLabeltquestiontpacktButtontquitRtBOTTOMtBOTHtFrametCanvastdrawt Scrollbart HORIZONTALtscrollXtVERTICALtscrollYtsettxviewtyviewtcreate_rectangletXtRIGHTtYtLEFT(Rtspacer((s@/usr/lib64/python2.7/Demo/tkinter/matt/canvas-with-scrollbars.pyt createWidgets s*  cGsdG|GH|jjjGHdS(Nt scrolling(R!R$tget(Rtargs((s@/usr/lib64/python2.7/Demo/tkinter/matt/canvas-with-scrollbars.pyt scrollCanvasX0s cCs+tj||tj||jdS(N(Rt__init__tPacktconfigR0(Rtmaster((s@/usr/lib64/python2.7/Demo/tkinter/matt/canvas-with-scrollbars.pyR55s N(t__name__t __module__RR0R4tNoneR5(((s@/usr/lib64/python2.7/Demo/tkinter/matt/canvas-with-scrollbars.pyRs  $ N(tTkinterRRttesttmainloop(((s@/usr/lib64/python2.7/Demo/tkinter/matt/canvas-with-scrollbars.pyts 2 PK%L]Vkk*tkinter/matt/menu-all-types-of-entries.pycnu[ ^c@sddlTdZdZdZdadZdZdZd Zd Z d Z e Z e e d ed dZejdeeZeZeZe Ze Zejeeeeee jde jde jdS(i(t*cCs dGHdS(Nsopening new file((((sC/usr/lib64/python2.7/Demo/tkinter/matt/menu-all-types-of-entries.pytnew_file%scCs dGHdS(Nsopening OLD file((((sC/usr/lib64/python2.7/Demo/tkinter/matt/menu-all-types-of-entries.pyt open_file(scCs dGHdS(Nspicked a menu item((((sC/usr/lib64/python2.7/Demo/tkinter/matt/menu-all-types-of-entries.pytprint_something+sicCst adGtGHdS(Ns anchovies?(t anchovies(((sC/usr/lib64/python2.7/Demo/tkinter/matt/menu-all-types-of-entries.pytprint_anchovies2sc Cs+ttdddd}|jdtddt||_|jjdd |jjdd t|jjdd ddd t |jjdd ddd t |jjddddddd t |jjdd|jj d|jjddddddddd |j |j|d<|S(NttextsSimple Button Commandst underlineitsidetpadxt2mtlabeltUndotstatesNew...tcommandsOpen...sDifferent Fonttfonts&-*-helvetica-*-r-*-*-*-180-*-*-*-*-*-*tbitmaptinfot separatortQuitt backgroundtredtactivebackgroundtgreentmenu(t MenubuttontmBartpacktLEFTtMenuRt add_commandt entryconfigtDISABLEDRRRtaddtquit(tCommand_button((sC/usr/lib64/python2.7/Demo/tkinter/matt/menu-all-types-of-entries.pytmakeCommandMenu7s,    cCsttdddd}|jdtddt||_t|j|j_t|jj|jj_|jjjjdd |jjjjdd |jjjjdd |jjjdd |jjjdd |jjjdd|jjjdd|jjjdd|jjjdd|jjj ddd|jjj|jj ddd|jj|j|d<|S(NRsCascading MenusRiRR R R tavacadosbelgian endivet beefaronit ChocolatetVanillat TuttiFruititWopBopaLoopBapABopBamBooms Rocky Roadt BubbleGums Weird FlavorsRs more choices( RRRRRRtchoicest weirdonesRt add_cascade(tCascade_button((sC/usr/lib64/python2.7/Demo/tkinter/matt/menu-all-types-of-entries.pytmakeCascadeMenues*  cCsttdddd}|jdtddt||_|jjdd |jjdd |jjdd |jjdd d t|jj|jj d |j|d<|S(NRsCheckbutton MenusRiRR R R t PepperonitSausages Extra CheesetAnchovyRR( RRRRRRtadd_checkbuttonRtinvoketindex(tCheckbutton_button((sC/usr/lib64/python2.7/Demo/tkinter/matt/menu-all-types-of-entries.pytmakeCheckbuttonMenus  cCs ttdddd}|jdtddt||_|jjdd |jjdd |jjdd |jjdd |jjdd |jjdd|jjdd|jjdd|jjdd|jjdd|j|d<|S(NRsRadiobutton MenusRiRR R R t RepublicantDemocratt LibertariantCommietFacists Labor PartytToriet Independentt Anarchists No OpinionR(RRRRRRtadd_radiobutton(tRadiobutton_button((sC/usr/lib64/python2.7/Demo/tkinter/matt/menu-all-types-of-entries.pytmakeRadiobuttonMenus   cCs<ttdddd}|jdtddt|d<|S( NRs Dead MenuRiRR R R (RRRRR (t Dummy_button((sC/usr/lib64/python2.7/Demo/tkinter/matt/menu-all-types-of-entries.pytmakeDisabledMenus trelieft borderwidthitfills menu demoN(tTkinterRRRRRR$R0R8RCREtTktroottFrametRAISEDRRtXR#R/R7RBtNoMenut tk_menuBarttitleticonnametmainloop(((sC/usr/lib64/python2.7/Demo/tkinter/matt/menu-all-types-of-entries.pyts, $     . & ,         PK%L]0L$tkinter/matt/killing-window-w-wm.pyonu[ ^c@s@ddlTdZdefdYZeZejdS(i(t*cCs dGHdS(Nswhoops -- tried to delete me!((((s=/usr/lib64/python2.7/Demo/tkinter/matt/killing-window-w-wm.pytmy_delete_callback stTestcBs&eZdZdZddZRS(cCs |GdGHdS(Ns3is now getting nuked. performing some save here....((tselftevent((s=/usr/lib64/python2.7/Demo/tkinter/matt/killing-window-w-wm.pyt deathHandler scCs,t|dd|_|jjdtdS(NttexttHellotside(tButtonthi_theretpacktLEFT(R((s=/usr/lib64/python2.7/Demo/tkinter/matt/killing-window-w-wm.pyt createWidgetsscCs>tj||tj||j|jd|jdS(Ns (tFramet__init__tPacktconfigR tbind_allR(Rtmaster((s=/usr/lib64/python2.7/Demo/tkinter/matt/killing-window-w-wm.pyRs  N(t__name__t __module__RR tNoneR(((s=/usr/lib64/python2.7/Demo/tkinter/matt/killing-window-w-wm.pyR s  N(tTkinterRRRttesttmainloop(((s=/usr/lib64/python2.7/Demo/tkinter/matt/killing-window-w-wm.pyts   PK%L]ktkinter/matt/dialog-box.pyonu[ ^c@sGddlTddlmZdefdYZeZejdS(i(t*(tDialogtTestcBs/eZdZdZdZddZRS(cCs dGHdS(Nthi((tself((s4/usr/lib64/python2.7/Demo/tkinter/matt/dialog-box.pytprintitsc Cs1t|ddddddddd d }|jS( sCreate a top-level dialog with some buttons. This uses the Dialog class, which is a wrapper around the Tcl/Tk tk_dialog script. The function returns 0 if the user clicks 'yes' or 1 if the user clicks 'no'. ttitlesfred the dialog boxttextsclick on a choicetbitmaptinfotdefaultitstringstyestno(R R (Rtnum(Rtd((s4/usr/lib64/python2.7/Demo/tkinter/matt/dialog-box.pyt makeWindow s cCsrt|ddddd|j|_|jjdtdtt|ddd|j|_|jjdtdS( NRtQUITt foregroundtredtcommandtsidetfillsMake a New Window(tButtontquitRtpacktLEFTtBOTHRthi_there(R((s4/usr/lib64/python2.7/Demo/tkinter/matt/dialog-box.pyt createWidgets.s cCs4tj||tj|d|_|jdS(Ni(tFramet__init__tPacktconfigt windownumR(Rtmaster((s4/usr/lib64/python2.7/Demo/tkinter/matt/dialog-box.pyR9s  N(t__name__t __module__RRRtNoneR(((s4/usr/lib64/python2.7/Demo/tkinter/matt/dialog-box.pyRs  # N(tTkinterRRRttesttmainloop(((s4/usr/lib64/python2.7/Demo/tkinter/matt/dialog-box.pyts 8 PK%L];mDD(tkinter/matt/canvas-reading-tag-info.pyonu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBs&eZdZdZddZRS(cCs dGHdS(Nthi((tself((sA/usr/lib64/python2.7/Demo/tkinter/matt/canvas-reading-tag-info.pytprintitscCs!t|ddddd|j|_|jjdtdtt|dd d d |_|jjd d d d d d d d ddd d}|jj |d}dG|dGdGH|jj |d}dG|dGdGHdG|dGdGH|jj |d }dG|dGH|jjdt dS(NttexttQUITt foregroundtredtcommandtsidetfilltwidtht5itheighti inttagstweeetfootgrootstipples#pgon's current stipple value is -->is<--s pgon's current fill value is -->s when he is usually colored -->ispgon's tags are(RRR( tButtontquitRtpacktBOTTOMtBOTHtCanvastdrawingtcreate_polygont itemconfigtLEFT(Rtpgont option_value((sA/usr/lib64/python2.7/Demo/tkinter/matt/canvas-reading-tag-info.pyt createWidgetss   cCs+tj||tj||jdS(N(tFramet__init__tPacktconfigR (Rtmaster((sA/usr/lib64/python2.7/Demo/tkinter/matt/canvas-reading-tag-info.pyR"*s N(t__name__t __module__RR tNoneR"(((sA/usr/lib64/python2.7/Demo/tkinter/matt/canvas-reading-tag-info.pyRs  "N(tTkinterR!Rttesttmainloop(((sA/usr/lib64/python2.7/Demo/tkinter/matt/canvas-reading-tag-info.pyts + PK%L]0L$tkinter/matt/killing-window-w-wm.pycnu[ ^c@s@ddlTdZdefdYZeZejdS(i(t*cCs dGHdS(Nswhoops -- tried to delete me!((((s=/usr/lib64/python2.7/Demo/tkinter/matt/killing-window-w-wm.pytmy_delete_callback stTestcBs&eZdZdZddZRS(cCs |GdGHdS(Ns3is now getting nuked. performing some save here....((tselftevent((s=/usr/lib64/python2.7/Demo/tkinter/matt/killing-window-w-wm.pyt deathHandler scCs,t|dd|_|jjdtdS(NttexttHellotside(tButtonthi_theretpacktLEFT(R((s=/usr/lib64/python2.7/Demo/tkinter/matt/killing-window-w-wm.pyt createWidgetsscCs>tj||tj||j|jd|jdS(Ns (tFramet__init__tPacktconfigR tbind_allR(Rtmaster((s=/usr/lib64/python2.7/Demo/tkinter/matt/killing-window-w-wm.pyRs  N(t__name__t __module__RR tNoneR(((s=/usr/lib64/python2.7/Demo/tkinter/matt/killing-window-w-wm.pyR s  N(tTkinterRRRttesttmainloop(((s=/usr/lib64/python2.7/Demo/tkinter/matt/killing-window-w-wm.pyts   PK%L]d(tkinter/matt/canvas-w-widget-draw-el.pycnu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBs&eZdZdZddZRS(cCs dGHdS(Nthi((tself((sA/usr/lib64/python2.7/Demo/tkinter/matt/canvas-w-widget-draw-el.pytprinthiscCst|ddddd|j|_|jjdtdtt|dd d d |_t|dd d|j|_ |jj d d d |j |jjdt dS(NttexttQUITt foregroundtredtcommandtsidetfilltwidtht5itheightsthis is a buttoni,twindow( tButtontquitRtpacktBOTTOMtBOTHtCanvastdrawRtbuttont create_windowtLEFT(R((sA/usr/lib64/python2.7/Demo/tkinter/matt/canvas-w-widget-draw-el.pyt createWidgets scCs+tj||tj||jdS(N(tFramet__init__tPacktconfigR(Rtmaster((sA/usr/lib64/python2.7/Demo/tkinter/matt/canvas-w-widget-draw-el.pyRs N(t__name__t __module__RRtNoneR(((sA/usr/lib64/python2.7/Demo/tkinter/matt/canvas-w-widget-draw-el.pyRs  N(tTkinterRRttesttmainloop(((sA/usr/lib64/python2.7/Demo/tkinter/matt/canvas-w-widget-draw-el.pyts  PK%L]S"  tkinter/matt/placer-simple.pyonu[ ^c@seddlTdZdZdZeZeeZejdejddej dS(i(t*cCs#tjjd|jd|jdS(Ntxty(tapptbuttontplaceRR(tevent((s7/usr/lib64/python2.7/Demo/tkinter/matt/placer-simple.pyt do_motionscCs dGHdS(Ns calling me!((((s7/usr/lib64/python2.7/Demo/tkinter/matt/placer-simple.pytdothisscCst|dddddd}|jddddt|d d d d d t|_|jjdddddt|jdt|S(Ntwidthitheightt backgroundtgreentrelxgtrelyt foregroundtredttexttamazingtcommandg?tanchors(tFrameRtButtonRRtNWtbindR(ttoptf((s7/usr/lib64/python2.7/Demo/tkinter/matt/placer-simple.pyt createWidgets s !t400x400iN( tTkinterRRRtTktrootRtgeometrytmaxsizetmainloop(((s7/usr/lib64/python2.7/Demo/tkinter/matt/placer-simple.pyts       PK%L]jHH#tkinter/matt/radiobutton-simple.pyonu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBs&eZdZdZddZRS(cCs dGHdS(Nthi((tself((s</usr/lib64/python2.7/Demo/tkinter/matt/radiobutton-simple.pytprintitsc Csvt|_|jjdt||_|jjt|jddd|jdddt|j_|jjjdt t|jddd|jdd dt|j_ |jj jdt t|jdd d|jdd dt|j_ |jj jdt t |d |j|_ |j jdt t|dd ddd|j|_|jjdtdtdS(Nt chocolatettextsChocolate FlavortvariabletvaluetanchortfillsStrawberry Flavort strawberrys Lemon Flavortlemont textvariabletQUITt foregroundtredtcommandtside(t StringVartflavortsettFramet radioframetpackt RadiobuttontWtchoctXtstrawR tEntrytentrytButtontquitRtBOTTOMtBOTH(R((s</usr/lib64/python2.7/Demo/tkinter/matt/radiobutton-simple.pyt createWidgetss0  cCs+tj||tj||jdS(N(Rt__init__tPacktconfigR$(Rtmaster((s</usr/lib64/python2.7/Demo/tkinter/matt/radiobutton-simple.pyR%7s N(t__name__t __module__RR$tNoneR%(((s</usr/lib64/python2.7/Demo/tkinter/matt/radiobutton-simple.pyR s  &N(tTkinterRRttesttmainloop(((s</usr/lib64/python2.7/Demo/tkinter/matt/radiobutton-simple.pyts / PK%L]e̍#tkinter/matt/canvas-demo-simple.pycnu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBs&eZdZdZddZRS(cCs dGHdS(Nthi((tself((s</usr/lib64/python2.7/Demo/tkinter/matt/canvas-demo-simple.pytprintitscCst|ddddd|j|_|jjdtdtt|dd d d |_|jjd d d d dd |jjdt dS(NttexttQUITt foregroundtredtcommandtsidetfilltwidtht5itheightit3itblack( tButtontquitRtpacktBOTTOMtBOTHtCanvastdrawtcreate_rectangletLEFT(R((s</usr/lib64/python2.7/Demo/tkinter/matt/canvas-demo-simple.pyt createWidgets s cCs+tj||tj||jdS(N(tFramet__init__tPacktconfigR(Rtmaster((s</usr/lib64/python2.7/Demo/tkinter/matt/canvas-demo-simple.pyRs N(t__name__t __module__RRtNoneR(((s</usr/lib64/python2.7/Demo/tkinter/matt/canvas-demo-simple.pyRs  N(tTkinterRRttesttmainloop(((s</usr/lib64/python2.7/Demo/tkinter/matt/canvas-demo-simple.pyts  PK%L]MhΩ &tkinter/matt/canvas-moving-w-mouse.pycnu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBsAeZdZdZdZdZdZddZRS(cCs|j|_|j|_dS(N(txtlastxtytlasty(tselftevent((s?/usr/lib64/python2.7/Demo/tkinter/matt/canvas-moving-w-mouse.pyt mouseDown s cCsF|jjt|j|j|j|j|j|_|j|_dS(N(tdrawtmovetCURRENTRRRR(RR((s?/usr/lib64/python2.7/Demo/tkinter/matt/canvas-moving-w-mouse.pyt mouseMoves* cCs|jjtdddS(Ntfilltred(R t itemconfigR (RR((s?/usr/lib64/python2.7/Demo/tkinter/matt/canvas-moving-w-mouse.pyt mouseEnterscCs|jjtdddS(NR tblue(R RR (RR((s?/usr/lib64/python2.7/Demo/tkinter/matt/canvas-moving-w-mouse.pyt mouseLeavesc Cst|ddddd|j|_|jjdtdtt|dd d d |_|jjdt|jjd d d d dd dd}|jj |d|j |jj |d|j t j |jd|jt j |jd|jdS(NttexttQUITt foregroundRtcommandtsideR twidtht5itheightiitgreenttagstselecteds s s<1>s (tButtontquitRtpacktLEFTtBOTHtCanvasR t create_ovalttag_bindRRtWidgettbindRR (Rtfred((s?/usr/lib64/python2.7/Demo/tkinter/matt/canvas-moving-w-mouse.pyt createWidgets!scCs+tj||tj||jdS(N(tFramet__init__tPacktconfigR)(Rtmaster((s?/usr/lib64/python2.7/Demo/tkinter/matt/canvas-moving-w-mouse.pyR+1s N( t__name__t __module__RR RRR)tNoneR+(((s?/usr/lib64/python2.7/Demo/tkinter/matt/canvas-moving-w-mouse.pyRs     N(tTkinterR*Rttesttmainloop(((s?/usr/lib64/python2.7/Demo/tkinter/matt/canvas-moving-w-mouse.pyts 1 PK%L] tkinter/matt/slider-demo-1.pycnu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBs/eZdZdZdZddZRS(cCs dG|GHdS(Ns slider now at((tselftval((s7/usr/lib64/python2.7/Demo/tkinter/matt/slider-demo-1.pyt print_valuescCs|jjddS(Ni(tslidertset(R((s7/usr/lib64/python2.7/Demo/tkinter/matt/slider-demo-1.pytreset scCst|dddddtdddd d |j|_t|d d d |j|_t|d d ddd |j|_|jjdt |jjdt |jjdt dt dS(Ntfrom_ittoidtorienttlengtht3itlabels happy slidertcommandttexts reset slidertQUITt foregroundtredtsidetfill( tScalet HORIZONTALRRtButtonRtquitRtpacktLEFTtBOTH(R((s7/usr/lib64/python2.7/Demo/tkinter/matt/slider-demo-1.pyt createWidgets scCs+tj||tj||jdS(N(tFramet__init__tPacktconfigR(Rtmaster((s7/usr/lib64/python2.7/Demo/tkinter/matt/slider-demo-1.pyRs N(t__name__t __module__RRRtNoneR(((s7/usr/lib64/python2.7/Demo/tkinter/matt/slider-demo-1.pyRs   N(tTkinterRRttesttmainloop(((s7/usr/lib64/python2.7/Demo/tkinter/matt/slider-demo-1.pyts  PK%L]R۩tkinter/matt/menu-simple.pyonu[ ^c@sddlTdZdZdZdZeZeededdZ e j d e eZ eZ e je e ejd ejd ejd S( i(t*cCs dGHdS(Nsopening new file((((s5/usr/lib64/python2.7/Demo/tkinter/matt/menu-simple.pytnew_file$scCs dGHdS(Nsopening OLD file((((s5/usr/lib64/python2.7/Demo/tkinter/matt/menu-simple.pyt open_file(scCsttdddd}|jdtddt||_|jjdd ddd t|jjdd ddd t|jjdd ddd d |j|d<|S(NttexttFilet underlineitsidetpadxt1mtlabelsNew...tcommandsOpen...tQuittexittmenu( t MenubuttontmBartpacktLEFTtMenuR t add_commandRR(t File_button((s5/usr/lib64/python2.7/Demo/tkinter/matt/menu-simple.pyt makeFileMenu,s cCsttdddd}|jdtddt||_|jjdd d |jjd d t|jj d d |jj d d|jj d d|j|d<|S(NRtEditRiRRRR R tUndoitstatetCuttCopytPasteR ( RRRRRR taddt entryconfigtDISABLEDR(t Edit_button((s5/usr/lib64/python2.7/Demo/tkinter/matt/menu-simple.pyt makeEditMenuFs trelieft borderwidthitfills menu demotpackerN(tTkinterRRRR tTktroottFrametRAISEDRRtXRRt tk_menuBarttitleticonnametmainloop(((s5/usr/lib64/python2.7/Demo/tkinter/matt/menu-simple.pyts #         PK%L]J"tkinter/matt/radiobutton-simple.pynu[from Tkinter import * # This is a demo program that shows how to # create radio buttons and how to get other widgets to # share the information in a radio button. # # There are other ways of doing this too, but # the "variable" option of radiobuttons seems to be the easiest. # # note how each button has a value it sets the variable to as it gets hit. class Test(Frame): def printit(self): print "hi" def createWidgets(self): self.flavor = StringVar() self.flavor.set("chocolate") self.radioframe = Frame(self) self.radioframe.pack() # 'text' is the label # 'variable' is the name of the variable that all these radio buttons share # 'value' is the value this variable takes on when the radio button is selected # 'anchor' makes the text appear left justified (default is centered. ick) self.radioframe.choc = Radiobutton( self.radioframe, text="Chocolate Flavor", variable=self.flavor, value="chocolate", anchor=W) self.radioframe.choc.pack(fill=X) self.radioframe.straw = Radiobutton( self.radioframe, text="Strawberry Flavor", variable=self.flavor, value="strawberry", anchor=W) self.radioframe.straw.pack(fill=X) self.radioframe.lemon = Radiobutton( self.radioframe, text="Lemon Flavor", variable=self.flavor, value="lemon", anchor=W) self.radioframe.lemon.pack(fill=X) # this is a text entry that lets you type in the name of a flavor too. self.entry = Entry(self, textvariable=self.flavor) self.entry.pack(fill=X) self.QUIT = Button(self, text='QUIT', foreground='red', command=self.quit) self.QUIT.pack(side=BOTTOM, fill=BOTH) def __init__(self, master=None): Frame.__init__(self, master) Pack.config(self) self.createWidgets() test = Test() test.mainloop() PK%L]~ǁ*tkinter/matt/not-what-you-might-think-2.pynu[from Tkinter import * class Test(Frame): def createWidgets(self): self.Gpanel = Frame(self, width='1i', height='1i', background='green') # this line turns off the recalculation of geometry by masters. self.Gpanel.propagate(0) self.Gpanel.pack(side=LEFT) # a QUIT button self.Gpanel.QUIT = Button(self.Gpanel, text='QUIT', foreground='red', command=self.quit) self.Gpanel.QUIT.pack(side=LEFT) def __init__(self, master=None): Frame.__init__(self, master) Pack.config(self) self.createWidgets() test = Test() test.master.title('packer demo') test.master.iconname('packer') test.mainloop() PK%L]!tkinter/matt/animation-simple.pycnu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBs/eZdZdZdZddZRS(cCs dGHdS(Nthi((tself((s:/usr/lib64/python2.7/Demo/tkinter/matt/animation-simple.pytprintitsc Cst|ddddd|j|_|jjdtdtt|dd d d |_|jjd d d d d ddd|jjdtdS(NttexttQUITt foregroundtredtcommandtsidetfilltwidtht5itheightii ttagstthingtblue( tButtontquitRtpacktLEFTtBOTHtCanvastdrawtcreate_rectangle(R((s:/usr/lib64/python2.7/Demo/tkinter/matt/animation-simple.pyt createWidgets s %cGs-|jjddd|jd|jdS(NRs0.01ii (Rtmovetaftert moveThing(Rtargs((s:/usr/lib64/python2.7/Demo/tkinter/matt/animation-simple.pyRscCs>tj||tj||j|jd|jdS(Ni (tFramet__init__tPacktconfigRRR(Rtmaster((s:/usr/lib64/python2.7/Demo/tkinter/matt/animation-simple.pyR s  N(t__name__t __module__RRRtNoneR (((s:/usr/lib64/python2.7/Demo/tkinter/matt/animation-simple.pyRs  N(tTkinterRRttesttmainloop(((s:/usr/lib64/python2.7/Demo/tkinter/matt/animation-simple.pyts  PK%L]X *tkinter/matt/packer-and-placer-together.pynu[from Tkinter import * # This is a program that tests the placer geom manager in conjunction with # the packer. The background (green) is packed, while the widget inside is placed def do_motion(event): app.button.place(x=event.x, y=event.y) def dothis(): print 'calling me!' def createWidgets(top): # make a frame. Note that the widget is 200 x 200 # and the window containing is 400x400. We do this # simply to show that this is possible. The rest of the # area is inaccesssible. f = Frame(top, width=200, height=200, background='green') # note that we use a different manager here. # This way, the top level frame widget resizes when the # application window does. f.pack(fill=BOTH, expand=1) # now make a button f.button = Button(f, foreground='red', text='amazing', command=dothis) # and place it so that the nw corner is # 1/2 way along the top X edge of its' parent f.button.place(relx=0.5, rely=0.0, anchor=NW) # allow the user to move the button SUIT-style. f.bind('', do_motion) return f root = Tk() app = createWidgets(root) root.geometry("400x400") root.maxsize(1000, 1000) root.mainloop() PK%L]S"  tkinter/matt/placer-simple.pycnu[ ^c@seddlTdZdZdZeZeeZejdejddej dS(i(t*cCs#tjjd|jd|jdS(Ntxty(tapptbuttontplaceRR(tevent((s7/usr/lib64/python2.7/Demo/tkinter/matt/placer-simple.pyt do_motionscCs dGHdS(Ns calling me!((((s7/usr/lib64/python2.7/Demo/tkinter/matt/placer-simple.pytdothisscCst|dddddd}|jddddt|d d d d d t|_|jjdddddt|jdt|S(Ntwidthitheightt backgroundtgreentrelxgtrelyt foregroundtredttexttamazingtcommandg?tanchors(tFrameRtButtonRRtNWtbindR(ttoptf((s7/usr/lib64/python2.7/Demo/tkinter/matt/placer-simple.pyt createWidgets s !t400x400iN( tTkinterRRRtTktrootRtgeometrytmaxsizetmainloop(((s7/usr/lib64/python2.7/Demo/tkinter/matt/placer-simple.pyts       PK%L]#~*tkinter/matt/entry-with-shared-variable.pynu[from Tkinter import * import string # This program shows how to make a typein box shadow a program variable. class App(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.entrythingy = Entry(self) self.entrythingy.pack() self.button = Button(self, text="Uppercase The Entry", command=self.upper) self.button.pack() # here we have the text in the entry widget tied to a variable. # changes in the variable are echoed in the widget and vice versa. # Very handy. # there are other Variable types. See Tkinter.py for all # the other variable types that can be shadowed self.contents = StringVar() self.contents.set("this is a variable") self.entrythingy.config(textvariable=self.contents) # and here we get a callback when the user hits return. we could # make the key that triggers the callback anything we wanted to. # other typical options might be or (for anything) self.entrythingy.bind('', self.print_contents) def upper(self): # notice here, we don't actually refer to the entry box. # we just operate on the string variable and we # because it's being looked at by the entry widget, changing # the variable changes the entry widget display automatically. # the strange get/set operators are clunky, true... str = string.upper(self.contents.get()) self.contents.set(str) def print_contents(self, event): print "hi. contents of entry is now ---->", self.contents.get() root = App() root.master.title("Foo") root.mainloop() PK%L]x##)tkinter/matt/menu-all-types-of-entries.pynu[from Tkinter import * # some vocabulary to keep from getting confused. This terminology # is something I cooked up for this file, but follows the man pages # pretty closely # # # # This is a MENUBUTTON # V # +-------------+ # | | # # +------------++------------++------------+ # | || || | # | File || Edit || Options | <-------- the MENUBAR # | || || | # +------------++------------++------------+ # | New... | # | Open... | # | Print | # | | <-------- This is a MENU. The lines of text in the menu are # | | MENU ENTRIES # | +---------------+ # | Open Files > | file1 | # | | file2 | # | | another file | <------ this cascading part is also a MENU # +----------------| | # | | # | | # | | # +---------------+ # some miscellaneous callbacks def new_file(): print "opening new file" def open_file(): print "opening OLD file" def print_something(): print "picked a menu item" anchovies = 0 def print_anchovies(): global anchovies anchovies = not anchovies print "anchovies?", anchovies def makeCommandMenu(): # make menu button Command_button = Menubutton(mBar, text='Simple Button Commands', underline=0) Command_button.pack(side=LEFT, padx="2m") # make the pulldown part of the File menu. The parameter passed is the master. # we attach it to the button as a python attribute called "menu" by convention. # hopefully this isn't too confusing... Command_button.menu = Menu(Command_button) # just to be cute, let's disable the undo option: Command_button.menu.add_command(label="Undo") # undo is the 0th entry... Command_button.menu.entryconfig(0, state=DISABLED) Command_button.menu.add_command(label='New...', underline=0, command=new_file) Command_button.menu.add_command(label='Open...', underline=0, command=open_file) Command_button.menu.add_command(label='Different Font', underline=0, font='-*-helvetica-*-r-*-*-*-180-*-*-*-*-*-*', command=print_something) # we can make bitmaps be menu entries too. File format is X11 bitmap. # if you use XV, save it under X11 bitmap format. duh-uh.,.. Command_button.menu.add_command( bitmap="info") #bitmap='@/home/mjc4y/dilbert/project.status.is.doomed.last.panel.bm') # this is just a line Command_button.menu.add('separator') # change the color Command_button.menu.add_command(label='Quit', underline=0, background='red', activebackground='green', command=Command_button.quit) # set up a pointer from the file menubutton back to the file menu Command_button['menu'] = Command_button.menu return Command_button def makeCascadeMenu(): # make menu button Cascade_button = Menubutton(mBar, text='Cascading Menus', underline=0) Cascade_button.pack(side=LEFT, padx="2m") # the primary pulldown Cascade_button.menu = Menu(Cascade_button) # this is the menu that cascades from the primary pulldown.... Cascade_button.menu.choices = Menu(Cascade_button.menu) # ...and this is a menu that cascades from that. Cascade_button.menu.choices.weirdones = Menu(Cascade_button.menu.choices) # then you define the menus from the deepest level on up. Cascade_button.menu.choices.weirdones.add_command(label='avacado') Cascade_button.menu.choices.weirdones.add_command(label='belgian endive') Cascade_button.menu.choices.weirdones.add_command(label='beefaroni') # definition of the menu one level up... Cascade_button.menu.choices.add_command(label='Chocolate') Cascade_button.menu.choices.add_command(label='Vanilla') Cascade_button.menu.choices.add_command(label='TuttiFruiti') Cascade_button.menu.choices.add_command(label='WopBopaLoopBapABopBamBoom') Cascade_button.menu.choices.add_command(label='Rocky Road') Cascade_button.menu.choices.add_command(label='BubbleGum') Cascade_button.menu.choices.add_cascade( label='Weird Flavors', menu=Cascade_button.menu.choices.weirdones) # and finally, the definition for the top level Cascade_button.menu.add_cascade(label='more choices', menu=Cascade_button.menu.choices) Cascade_button['menu'] = Cascade_button.menu return Cascade_button def makeCheckbuttonMenu(): global fred # make menu button Checkbutton_button = Menubutton(mBar, text='Checkbutton Menus', underline=0) Checkbutton_button.pack(side=LEFT, padx='2m') # the primary pulldown Checkbutton_button.menu = Menu(Checkbutton_button) # and all the check buttons. Note that the "variable" "onvalue" and "offvalue" options # are not supported correctly at present. You have to do all your application # work through the calback. Checkbutton_button.menu.add_checkbutton(label='Pepperoni') Checkbutton_button.menu.add_checkbutton(label='Sausage') Checkbutton_button.menu.add_checkbutton(label='Extra Cheese') # so here's a callback Checkbutton_button.menu.add_checkbutton(label='Anchovy', command=print_anchovies) # and start with anchovies selected to be on. Do this by # calling invoke on this menu option. To refer to the "anchovy" menu # entry we need to know it's index. To do this, we use the index method # which takes arguments of several forms: # # argument what it does # ----------------------------------- # a number -- this is useless. # "last" -- last option in the menu # "none" -- used with the activate command. see the man page on menus # "active" -- the currently active menu option. A menu option is made active # with the 'activate' method # "@number" -- where 'number' is an integer and is treated like a y coordinate in pixels # string pattern -- this is the option used below, and attempts to match "labels" using the # rules of Tcl_StringMatch Checkbutton_button.menu.invoke(Checkbutton_button.menu.index('Anchovy')) # set up a pointer from the file menubutton back to the file menu Checkbutton_button['menu'] = Checkbutton_button.menu return Checkbutton_button def makeRadiobuttonMenu(): # make menu button Radiobutton_button = Menubutton(mBar, text='Radiobutton Menus', underline=0) Radiobutton_button.pack(side=LEFT, padx='2m') # the primary pulldown Radiobutton_button.menu = Menu(Radiobutton_button) # and all the Radio buttons. Note that the "variable" "onvalue" and "offvalue" options # are not supported correctly at present. You have to do all your application # work through the calback. Radiobutton_button.menu.add_radiobutton(label='Republican') Radiobutton_button.menu.add_radiobutton(label='Democrat') Radiobutton_button.menu.add_radiobutton(label='Libertarian') Radiobutton_button.menu.add_radiobutton(label='Commie') Radiobutton_button.menu.add_radiobutton(label='Facist') Radiobutton_button.menu.add_radiobutton(label='Labor Party') Radiobutton_button.menu.add_radiobutton(label='Torie') Radiobutton_button.menu.add_radiobutton(label='Independent') Radiobutton_button.menu.add_radiobutton(label='Anarchist') Radiobutton_button.menu.add_radiobutton(label='No Opinion') # set up a pointer from the file menubutton back to the file menu Radiobutton_button['menu'] = Radiobutton_button.menu return Radiobutton_button def makeDisabledMenu(): Dummy_button = Menubutton(mBar, text='Dead Menu', underline=0) Dummy_button.pack(side=LEFT, padx='2m') # this is the standard way of turning off a whole menu Dummy_button["state"] = DISABLED return Dummy_button ################################################# #### Main starts here ... root = Tk() # make a menu bar mBar = Frame(root, relief=RAISED, borderwidth=2) mBar.pack(fill=X) Command_button = makeCommandMenu() Cascade_button = makeCascadeMenu() Checkbutton_button = makeCheckbuttonMenu() Radiobutton_button = makeRadiobuttonMenu() NoMenu = makeDisabledMenu() # finally, install the buttons in the menu bar. # This allows for scanning from one menubutton to the next. mBar.tk_menuBar(Command_button, Cascade_button, Checkbutton_button, Radiobutton_button, NoMenu) root.title('menu demo') root.iconname('menu demo') root.mainloop() PK%L]d(tkinter/matt/canvas-w-widget-draw-el.pyonu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBs&eZdZdZddZRS(cCs dGHdS(Nthi((tself((sA/usr/lib64/python2.7/Demo/tkinter/matt/canvas-w-widget-draw-el.pytprinthiscCst|ddddd|j|_|jjdtdtt|dd d d |_t|dd d|j|_ |jj d d d |j |jjdt dS(NttexttQUITt foregroundtredtcommandtsidetfilltwidtht5itheightsthis is a buttoni,twindow( tButtontquitRtpacktBOTTOMtBOTHtCanvastdrawRtbuttont create_windowtLEFT(R((sA/usr/lib64/python2.7/Demo/tkinter/matt/canvas-w-widget-draw-el.pyt createWidgets scCs+tj||tj||jdS(N(tFramet__init__tPacktconfigR(Rtmaster((sA/usr/lib64/python2.7/Demo/tkinter/matt/canvas-w-widget-draw-el.pyRs N(t__name__t __module__RRtNoneR(((sA/usr/lib64/python2.7/Demo/tkinter/matt/canvas-w-widget-draw-el.pyRs  N(tTkinterRRttesttmainloop(((sA/usr/lib64/python2.7/Demo/tkinter/matt/canvas-w-widget-draw-el.pyts  PK%L] 4+!tkinter/matt/two-radio-groups.pycnu[ ^c@sddlTdZdZdZeZeededdZej de e Z e Zee ZeeZejeeeed d d d d eZej deejdejdejdS(i(t*cCsttdddd}|jdtddt||_|jjdd d |d d |jjd idd6|d 6dd 6|jjd idd6|d 6dd 6|jd|j|d<|S(NttextsPolitical Partyt underlineitsidetpadxt2mtlabelt Republicantvariabletvalueit radiobuttontDemocratit Libertarianitmenu( t MenubuttontmBartpacktLEFTtMenuR tadd_radiobuttontaddtset(tvartRadiobutton_button((s:/usr/lib64/python2.7/Demo/tkinter/matt/two-radio-groups.pytmakePoliticalPartiess      cCsttdddd}|jdtddt||_|jjdd d |d d |jjdd d |d d |jjdd d |d d |jd |j|d<|S(NRtFlavorsRiRRRRt StrawberryRR t Chocolates Rocky RoadR (RRRRRR RR(RR((s:/usr/lib64/python2.7/Demo/tkinter/matt/two-radio-groups.pyt makeFlavors2s      cCs#dGtjGHdGtjGHHdS(Nsparty iss flavor is(tpartytgettflavor(((s:/usr/lib64/python2.7/Demo/tkinter/matt/two-radio-groups.pyt printStuffMstrelieft borderwidthitfillRsprint party and flavort foregroundtredtcommandRs menu demoN(tTkinterRRR tTktroottFrametRAISEDRRtXtIntVarRt StringVarRRtRadiobutton_button2t tk_menuBartButtontbtTOPttitleticonnametmainloop(((s:/usr/lib64/python2.7/Demo/tkinter/matt/two-radio-groups.pyts"            PK%L]ʥE*tkinter/matt/not-what-you-might-think-1.pynu[from Tkinter import * class Test(Frame): def createWidgets(self): self.Gpanel = Frame(self, width='1i', height='1i', background='green') self.Gpanel.pack(side=LEFT) # a QUIT button self.Gpanel.QUIT = Button(self.Gpanel, text='QUIT', foreground='red', command=self.quit) self.Gpanel.QUIT.pack(side=LEFT) def __init__(self, master=None): Frame.__init__(self, master) Pack.config(self) self.createWidgets() test = Test() test.master.title('packer demo') test.master.iconname('packer') test.mainloop() PK%L]e̍#tkinter/matt/canvas-demo-simple.pyonu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBs&eZdZdZddZRS(cCs dGHdS(Nthi((tself((s</usr/lib64/python2.7/Demo/tkinter/matt/canvas-demo-simple.pytprintitscCst|ddddd|j|_|jjdtdtt|dd d d |_|jjd d d d dd |jjdt dS(NttexttQUITt foregroundtredtcommandtsidetfilltwidtht5itheightit3itblack( tButtontquitRtpacktBOTTOMtBOTHtCanvastdrawtcreate_rectangletLEFT(R((s</usr/lib64/python2.7/Demo/tkinter/matt/canvas-demo-simple.pyt createWidgets s cCs+tj||tj||jdS(N(tFramet__init__tPacktconfigR(Rtmaster((s</usr/lib64/python2.7/Demo/tkinter/matt/canvas-demo-simple.pyRs N(t__name__t __module__RRtNoneR(((s</usr/lib64/python2.7/Demo/tkinter/matt/canvas-demo-simple.pyRs  N(tTkinterRRttesttmainloop(((s</usr/lib64/python2.7/Demo/tkinter/matt/canvas-demo-simple.pyts  PK%L]a>oQ*tkinter/matt/animation-w-velocity-ctrl.pycnu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBs/eZdZdZdZddZRS(cCs dGHdS(Nthi((tself((sC/usr/lib64/python2.7/Demo/tkinter/matt/animation-w-velocity-ctrl.pytprintit sc Cst|ddddd|j|_|jjdtdtt|dd d d |_t|d t d d dd|_ |j jdtdt |jj dddddddd|jjdt dS(NttexttQUITt foregroundtredtcommandtsidetfilltwidtht5itheighttorienttfrom_ittoidii ttagstthingtblue(tButtontquitRtpacktBOTTOMtBOTHtCanvastdrawtScalet HORIZONTALtspeedtXtcreate_rectangletLEFT(R((sC/usr/lib64/python2.7/Demo/tkinter/matt/animation-w-velocity-ctrl.pyt createWidgets s!%cGsY|jj}t|d}d|f}|jjd|||jd|jdS(Ng@@s%riRi (RtgettfloatRtmovetaftert moveThing(Rtargstvelocitytstr((sC/usr/lib64/python2.7/Demo/tkinter/matt/animation-w-velocity-ctrl.pyR's  cCs>tj||tj||j|jd|jdS(Ni (tFramet__init__tPacktconfigR"R&R'(Rtmaster((sC/usr/lib64/python2.7/Demo/tkinter/matt/animation-w-velocity-ctrl.pyR,#s  N(t__name__t __module__RR"R'tNoneR,(((sC/usr/lib64/python2.7/Demo/tkinter/matt/animation-w-velocity-ctrl.pyR s   N(tTkinterR+Rttesttmainloop(((sC/usr/lib64/python2.7/Demo/tkinter/matt/animation-w-velocity-ctrl.pyts ! PK%L]])tkinter/matt/animation-w-velocity-ctrl.pynu[from Tkinter import * # this is the same as simple-demo-1.py, but uses # subclassing. # note that there is no explicit call to start Tk. # Tkinter is smart enough to start the system if it's not already going. class Test(Frame): def printit(self): print "hi" def createWidgets(self): self.QUIT = Button(self, text='QUIT', foreground='red', command=self.quit) self.QUIT.pack(side=BOTTOM, fill=BOTH) self.draw = Canvas(self, width="5i", height="5i") self.speed = Scale(self, orient=HORIZONTAL, from_=-100, to=100) self.speed.pack(side=BOTTOM, fill=X) # all of these work.. self.draw.create_rectangle(0, 0, 10, 10, tags="thing", fill="blue") self.draw.pack(side=LEFT) def moveThing(self, *args): velocity = self.speed.get() str = float(velocity) / 1000.0 str = "%ri" % (str,) self.draw.move("thing", str, str) self.after(10, self.moveThing) def __init__(self, master=None): Frame.__init__(self, master) Pack.config(self) self.createWidgets() self.after(10, self.moveThing) test = Test() test.mainloop() PK%L];U<*tkinter/matt/subclass-existing-widgets.pyonu[ ^c@sJddlTdefdYZdZeZeeejdS(i(t*t New_ButtoncBseZdZRS(cCs|jGH|jd|_dS(Ni(tcounter(tself((sC/usr/lib64/python2.7/Demo/tkinter/matt/subclass-existing-widgets.pytcallbacks(t__name__t __module__R(((sC/usr/lib64/python2.7/Demo/tkinter/matt/subclass-existing-widgets.pyRscCst|}|jt|ddddd|j|_|jjdtdtt|dd|_|jj d|jj |jjdtd |j_ dS( NttexttQUITt foregroundtredtcommandtsidetfilltHelloi+( tFrametpacktButtontquitRtLEFTtBOTHRthi_theretconfigRR(ttoptf((sC/usr/lib64/python2.7/Demo/tkinter/matt/subclass-existing-widgets.pyt createWidgets s  $N(tTkinterRRRtTktroottmainloop(((sC/usr/lib64/python2.7/Demo/tkinter/matt/subclass-existing-widgets.pyts    PK%L]P6tkinter/matt/slider-demo-1.pynu[from Tkinter import * # shows how to make a slider, set and get its value under program control class Test(Frame): def print_value(self, val): print "slider now at", val def reset(self): self.slider.set(0) def createWidgets(self): self.slider = Scale(self, from_=0, to=100, orient=HORIZONTAL, length="3i", label="happy slider", command=self.print_value) self.reset = Button(self, text='reset slider', command=self.reset) self.QUIT = Button(self, text='QUIT', foreground='red', command=self.quit) self.slider.pack(side=LEFT) self.reset.pack(side=LEFT) self.QUIT.pack(side=LEFT, fill=BOTH) def __init__(self, master=None): Frame.__init__(self, master) Pack.config(self) self.createWidgets() test = Test() test.mainloop() PK%L];U<*tkinter/matt/subclass-existing-widgets.pycnu[ ^c@sJddlTdefdYZdZeZeeejdS(i(t*t New_ButtoncBseZdZRS(cCs|jGH|jd|_dS(Ni(tcounter(tself((sC/usr/lib64/python2.7/Demo/tkinter/matt/subclass-existing-widgets.pytcallbacks(t__name__t __module__R(((sC/usr/lib64/python2.7/Demo/tkinter/matt/subclass-existing-widgets.pyRscCst|}|jt|ddddd|j|_|jjdtdtt|dd|_|jj d|jj |jjdtd |j_ dS( NttexttQUITt foregroundtredtcommandtsidetfilltHelloi+( tFrametpacktButtontquitRtLEFTtBOTHRthi_theretconfigRR(ttoptf((sC/usr/lib64/python2.7/Demo/tkinter/matt/subclass-existing-widgets.pyt createWidgets s  $N(tTkinterRRRtTktroottmainloop(((sC/usr/lib64/python2.7/Demo/tkinter/matt/subclass-existing-widgets.pyts    PK%L]!tkinter/matt/animation-simple.pyonu[ ^c@s7ddlTdefdYZeZejdS(i(t*tTestcBs/eZdZdZdZddZRS(cCs dGHdS(Nthi((tself((s:/usr/lib64/python2.7/Demo/tkinter/matt/animation-simple.pytprintitsc Cst|ddddd|j|_|jjdtdtt|dd d d |_|jjd d d d d ddd|jjdtdS(NttexttQUITt foregroundtredtcommandtsidetfilltwidtht5itheightii ttagstthingtblue( tButtontquitRtpacktLEFTtBOTHtCanvastdrawtcreate_rectangle(R((s:/usr/lib64/python2.7/Demo/tkinter/matt/animation-simple.pyt createWidgets s %cGs-|jjddd|jd|jdS(NRs0.01ii (Rtmovetaftert moveThing(Rtargs((s:/usr/lib64/python2.7/Demo/tkinter/matt/animation-simple.pyRscCs>tj||tj||j|jd|jdS(Ni (tFramet__init__tPacktconfigRRR(Rtmaster((s:/usr/lib64/python2.7/Demo/tkinter/matt/animation-simple.pyR s  N(t__name__t __module__RRRtNoneR (((s:/usr/lib64/python2.7/Demo/tkinter/matt/animation-simple.pyRs  N(tTkinterRRttesttmainloop(((s:/usr/lib64/python2.7/Demo/tkinter/matt/animation-simple.pyts  PK%L]Vkk*tkinter/matt/menu-all-types-of-entries.pyonu[ ^c@sddlTdZdZdZdadZdZdZd Zd Z d Z e Z e e d ed dZejdeeZeZeZe Ze Zejeeeeee jde jde jdS(i(t*cCs dGHdS(Nsopening new file((((sC/usr/lib64/python2.7/Demo/tkinter/matt/menu-all-types-of-entries.pytnew_file%scCs dGHdS(Nsopening OLD file((((sC/usr/lib64/python2.7/Demo/tkinter/matt/menu-all-types-of-entries.pyt open_file(scCs dGHdS(Nspicked a menu item((((sC/usr/lib64/python2.7/Demo/tkinter/matt/menu-all-types-of-entries.pytprint_something+sicCst adGtGHdS(Ns anchovies?(t anchovies(((sC/usr/lib64/python2.7/Demo/tkinter/matt/menu-all-types-of-entries.pytprint_anchovies2sc Cs+ttdddd}|jdtddt||_|jjdd |jjdd t|jjdd ddd t |jjdd ddd t |jjddddddd t |jjdd|jj d|jjddddddddd |j |j|d<|S(NttextsSimple Button Commandst underlineitsidetpadxt2mtlabeltUndotstatesNew...tcommandsOpen...sDifferent Fonttfonts&-*-helvetica-*-r-*-*-*-180-*-*-*-*-*-*tbitmaptinfot separatortQuitt backgroundtredtactivebackgroundtgreentmenu(t MenubuttontmBartpacktLEFTtMenuRt add_commandt entryconfigtDISABLEDRRRtaddtquit(tCommand_button((sC/usr/lib64/python2.7/Demo/tkinter/matt/menu-all-types-of-entries.pytmakeCommandMenu7s,    cCsttdddd}|jdtddt||_t|j|j_t|jj|jj_|jjjjdd |jjjjdd |jjjjdd |jjjdd |jjjdd |jjjdd|jjjdd|jjjdd|jjjdd|jjj ddd|jjj|jj ddd|jj|j|d<|S(NRsCascading MenusRiRR R R tavacadosbelgian endivet beefaronit ChocolatetVanillat TuttiFruititWopBopaLoopBapABopBamBooms Rocky Roadt BubbleGums Weird FlavorsRs more choices( RRRRRRtchoicest weirdonesRt add_cascade(tCascade_button((sC/usr/lib64/python2.7/Demo/tkinter/matt/menu-all-types-of-entries.pytmakeCascadeMenues*  cCsttdddd}|jdtddt||_|jjdd |jjdd |jjdd |jjdd d t|jj|jj d |j|d<|S(NRsCheckbutton MenusRiRR R R t PepperonitSausages Extra CheesetAnchovyRR( RRRRRRtadd_checkbuttonRtinvoketindex(tCheckbutton_button((sC/usr/lib64/python2.7/Demo/tkinter/matt/menu-all-types-of-entries.pytmakeCheckbuttonMenus  cCs ttdddd}|jdtddt||_|jjdd |jjdd |jjdd |jjdd |jjdd |jjdd|jjdd|jjdd|jjdd|jjdd|j|d<|S(NRsRadiobutton MenusRiRR R R t RepublicantDemocratt LibertariantCommietFacists Labor PartytToriet Independentt Anarchists No OpinionR(RRRRRRtadd_radiobutton(tRadiobutton_button((sC/usr/lib64/python2.7/Demo/tkinter/matt/menu-all-types-of-entries.pytmakeRadiobuttonMenus   cCs<ttdddd}|jdtddt|d<|S( NRs Dead MenuRiRR R R (RRRRR (t Dummy_button((sC/usr/lib64/python2.7/Demo/tkinter/matt/menu-all-types-of-entries.pytmakeDisabledMenus trelieft borderwidthitfills menu demoN(tTkinterRRRRRR$R0R8RCREtTktroottFrametRAISEDRRtXR#R/R7RBtNoMenut tk_menuBarttitleticonnametmainloop(((sC/usr/lib64/python2.7/Demo/tkinter/matt/menu-all-types-of-entries.pyts, $     . & ,         PK%L]m.,,tkinter/guido/kill.pynuȯ#! /usr/bin/python2.7 # Tkinter interface to Linux `kill' command. from Tkinter import * from string import splitfields from string import split import commands import os class BarButton(Menubutton): def __init__(self, master=None, **cnf): apply(Menubutton.__init__, (self, master), cnf) self.pack(side=LEFT) self.menu = Menu(self, name='menu') self['menu'] = self.menu class Kill(Frame): # List of (name, option, pid_column) format_list = [('Default', '', 0), ('Long', '-l', 2), ('User', '-u', 1), ('Jobs', '-j', 1), ('Signal', '-s', 1), ('Memory', '-m', 0), ('VM', '-v', 0), ('Hex', '-X', 0)] def kill(self, selected): c = self.format_list[self.format.get()][2] pid = split(selected)[c] os.system('kill -9 ' + pid) self.do_update() def do_update(self): name, option, column = self.format_list[self.format.get()] s = commands.getoutput('ps -w ' + option) list = splitfields(s, '\n') self.header.set(list[0]) del list[0] y = self.frame.vscroll.get()[0] self.frame.list.delete(0, AtEnd()) for line in list: self.frame.list.insert(0, line) self.frame.list.yview(int(y)) def do_motion(self, e): e.widget.select_clear(0, END) e.widget.select_set(e.widget.nearest(e.y)) def do_leave(self, e): e.widget.select_clear(0, END) def do_1(self, e): self.kill(e.widget.get(e.widget.nearest(e.y))) def __init__(self, master=None, **cnf): Frame.__init__(self, master, cnf) self.pack(expand=1, fill=BOTH) self.bar = Frame(self, name='bar', relief=RAISED, borderwidth=2) self.bar.pack(fill=X) self.bar.file = BarButton(self.bar, text='File') self.bar.file.menu.add_command( label='Quit', command=self.quit) self.bar.view = BarButton(self.bar, text='View') self.format = IntVar(self) self.format.set(2) for num in range(len(self.format_list)): self.bar.view.menu.add_radiobutton( label=self.format_list[num][0], command=self.do_update, variable=self.format, value=num) #self.bar.view.menu.add_separator() #XXX ... self.bar.tk_menuBar(self.bar.file, self.bar.view) self.frame = Frame(self, relief=RAISED, borderwidth=2) self.frame.pack(expand=1, fill=BOTH) self.header = StringVar(self) self.frame.label = Label(self.frame, relief=FLAT, anchor=NW, borderwidth=0, textvariable=self.header) self.frame.label.pack(fill=X) self.frame.vscroll = Scrollbar(self.frame, orient=VERTICAL) self.frame.list = Listbox(self.frame, relief=SUNKEN, selectbackground='#eed5b7', selectborderwidth=0, yscroll=self.frame.vscroll.set) self.frame.vscroll['command'] = self.frame.list.yview self.frame.vscroll.pack(side=RIGHT, fill=Y) self.frame.list.pack(expand=1, fill=BOTH) self.update = Button(self, text="Update", command=self.do_update) self.update.pack(expand=1, fill=X) self.frame.list.bind('', self.do_motion) self.frame.list.bind('', self.do_leave) self.frame.list.bind('<1>', self.do_1) self.do_update() if __name__ == '__main__': kill = Kill(None, borderwidth=5) kill.winfo_toplevel().title('Tkinter Process Killer') kill.winfo_toplevel().minsize(1, 1) kill.mainloop() PK%L]1tkinter/guido/switch.pynu[# Show how to do switchable panels. from Tkinter import * class App: def __init__(self, top=None, master=None): if top is None: if master is None: top = Tk() else: top = Toplevel(master) self.top = top self.buttonframe = Frame(top) self.buttonframe.pack() self.panelframe = Frame(top, borderwidth=2, relief=GROOVE) self.panelframe.pack(expand=1, fill=BOTH) self.panels = {} self.curpanel = None def addpanel(self, name, klass): button = Button(self.buttonframe, text=name, command=lambda self=self, name=name: self.show(name)) button.pack(side=LEFT) frame = Frame(self.panelframe) instance = klass(frame) self.panels[name] = (button, frame, instance) if self.curpanel is None: self.show(name) def show(self, name): (button, frame, instance) = self.panels[name] if self.curpanel: self.curpanel.pack_forget() self.curpanel = frame frame.pack(expand=1, fill="both") class LabelPanel: def __init__(self, frame): self.label = Label(frame, text="Hello world") self.label.pack() class ButtonPanel: def __init__(self, frame): self.button = Button(frame, text="Press me") self.button.pack() def main(): app = App() app.addpanel("label", LabelPanel) app.addpanel("button", ButtonPanel) app.top.mainloop() if __name__ == '__main__': main() PK%L]| tkinter/guido/MimeViewer.pynuȯ#! /usr/bin/python2.7 # View a single MIME multipart message. # Display each part as a box. import string from types import * from Tkinter import * from ScrolledText import ScrolledText class MimeViewer: def __init__(self, parent, title, msg): self.title = title self.msg = msg self.frame = Frame(parent, {'relief': 'raised', 'bd': 2}) self.frame.packing = {'expand': 0, 'fill': 'both'} self.button = Checkbutton(self.frame, {'text': title, 'command': self.toggle}) self.button.pack({'anchor': 'w'}) headertext = msg.getheadertext( lambda x: x != 'received' and x[:5] != 'x400-') height = countlines(headertext, 4) if height: self.htext = ScrolledText(self.frame, {'height': height, 'width': 80, 'wrap': 'none', 'relief': 'raised', 'bd': 2}) self.htext.packing = {'expand': 1, 'fill': 'both', 'after': self.button} self.htext.insert('end', headertext) else: self.htext = Frame(self.frame, {'relief': 'raised', 'bd': 2}) self.htext.packing = {'side': 'top', 'ipady': 2, 'fill': 'x', 'after': self.button} body = msg.getbody() if type(body) == StringType: self.pad = None height = countlines(body, 10) if height: self.btext = ScrolledText(self.frame, {'height': height, 'width': 80, 'wrap': 'none', 'relief': 'raised', 'bd': 2}) self.btext.packing = {'expand': 1, 'fill': 'both'} self.btext.insert('end', body) else: self.btext = None self.parts = None else: self.pad = Frame(self.frame, {'relief': 'flat', 'bd': 2}) self.pad.packing = {'side': 'left', 'ipadx': 10, 'fill': 'y', 'after': self.htext} self.parts = [] for i in range(len(body)): p = MimeViewer(self.frame, '%s.%d' % (title, i+1), body[i]) self.parts.append(p) self.btext = None self.collapsed = 1 def pack(self): self.frame.pack(self.frame.packing) def destroy(self): self.frame.destroy() def show(self): if self.collapsed: self.button.invoke() def toggle(self): if self.collapsed: self.explode() else: self.collapse() def collapse(self): self.collapsed = 1 for comp in self.htext, self.btext, self.pad: if comp: comp.forget() if self.parts: for part in self.parts: part.frame.forget() self.frame.pack({'expand': 0}) def explode(self): self.collapsed = 0 for comp in self.htext, self.btext, self.pad: if comp: comp.pack(comp.packing) if self.parts: for part in self.parts: part.pack() self.frame.pack({'expand': 1}) def countlines(str, limit): i = 0 n = 0 while n < limit: i = string.find(str, '\n', i) if i < 0: break n = n+1 i = i+1 return n def main(): import sys import getopt import mhlib opts, args = getopt.getopt(sys.argv[1:], '') for o, a in opts: pass message = None folder = 'inbox' for arg in args: if arg[:1] == '+': folder = arg[1:] else: message = string.atoi(arg) mh = mhlib.MH() f = mh.openfolder(folder) if not message: message = f.getcurrent() m = f.openmessage(message) root = Tk() tk = root.tk top = MimeViewer(root, '+%s/%d' % (folder, message), m) top.pack() top.show() root.minsize(1, 1) tk.mainloop() if __name__ == '__main__': main() PK%L]GfGftkinter/guido/ss1.pynu["""SS1 -- a spreadsheet.""" import os import re import sys import cgi import rexec from xml.parsers import expat LEFT, CENTER, RIGHT = "LEFT", "CENTER", "RIGHT" def ljust(x, n): return x.ljust(n) def center(x, n): return x.center(n) def rjust(x, n): return x.rjust(n) align2action = {LEFT: ljust, CENTER: center, RIGHT: rjust} align2xml = {LEFT: "left", CENTER: "center", RIGHT: "right"} xml2align = {"left": LEFT, "center": CENTER, "right": RIGHT} align2anchor = {LEFT: "w", CENTER: "center", RIGHT: "e"} def sum(seq): total = 0 for x in seq: if x is not None: total += x return total class Sheet: def __init__(self): self.cells = {} # {(x, y): cell, ...} self.rexec = rexec.RExec() m = self.rexec.add_module('__main__') m.cell = self.cellvalue m.cells = self.multicellvalue m.sum = sum def cellvalue(self, x, y): cell = self.getcell(x, y) if hasattr(cell, 'recalc'): return cell.recalc(self.rexec) else: return cell def multicellvalue(self, x1, y1, x2, y2): if x1 > x2: x1, x2 = x2, x1 if y1 > y2: y1, y2 = y2, y1 seq = [] for y in range(y1, y2+1): for x in range(x1, x2+1): seq.append(self.cellvalue(x, y)) return seq def getcell(self, x, y): return self.cells.get((x, y)) def setcell(self, x, y, cell): assert x > 0 and y > 0 assert isinstance(cell, BaseCell) self.cells[x, y] = cell def clearcell(self, x, y): try: del self.cells[x, y] except KeyError: pass def clearcells(self, x1, y1, x2, y2): for xy in self.selectcells(x1, y1, x2, y2): del self.cells[xy] def clearrows(self, y1, y2): self.clearcells(0, y1, sys.maxint, y2) def clearcolumns(self, x1, x2): self.clearcells(x1, 0, x2, sys.maxint) def selectcells(self, x1, y1, x2, y2): if x1 > x2: x1, x2 = x2, x1 if y1 > y2: y1, y2 = y2, y1 return [(x, y) for x, y in self.cells if x1 <= x <= x2 and y1 <= y <= y2] def movecells(self, x1, y1, x2, y2, dx, dy): if dx == 0 and dy == 0: return if x1 > x2: x1, x2 = x2, x1 if y1 > y2: y1, y2 = y2, y1 assert x1+dx > 0 and y1+dy > 0 new = {} for x, y in self.cells: cell = self.cells[x, y] if hasattr(cell, 'renumber'): cell = cell.renumber(x1, y1, x2, y2, dx, dy) if x1 <= x <= x2 and y1 <= y <= y2: x += dx y += dy new[x, y] = cell self.cells = new def insertrows(self, y, n): assert n > 0 self.movecells(0, y, sys.maxint, sys.maxint, 0, n) def deleterows(self, y1, y2): if y1 > y2: y1, y2 = y2, y1 self.clearrows(y1, y2) self.movecells(0, y2+1, sys.maxint, sys.maxint, 0, y1-y2-1) def insertcolumns(self, x, n): assert n > 0 self.movecells(x, 0, sys.maxint, sys.maxint, n, 0) def deletecolumns(self, x1, x2): if x1 > x2: x1, x2 = x2, x1 self.clearcells(x1, x2) self.movecells(x2+1, 0, sys.maxint, sys.maxint, x1-x2-1, 0) def getsize(self): maxx = maxy = 0 for x, y in self.cells: maxx = max(maxx, x) maxy = max(maxy, y) return maxx, maxy def reset(self): for cell in self.cells.itervalues(): if hasattr(cell, 'reset'): cell.reset() def recalc(self): self.reset() for cell in self.cells.itervalues(): if hasattr(cell, 'recalc'): cell.recalc(self.rexec) def display(self): maxx, maxy = self.getsize() width, height = maxx+1, maxy+1 colwidth = [1] * width full = {} # Add column heading labels in row 0 for x in range(1, width): full[x, 0] = text, alignment = colnum2name(x), RIGHT colwidth[x] = max(colwidth[x], len(text)) # Add row labels in column 0 for y in range(1, height): full[0, y] = text, alignment = str(y), RIGHT colwidth[0] = max(colwidth[0], len(text)) # Add sheet cells in columns with x>0 and y>0 for (x, y), cell in self.cells.iteritems(): if x <= 0 or y <= 0: continue if hasattr(cell, 'recalc'): cell.recalc(self.rexec) if hasattr(cell, 'format'): text, alignment = cell.format() assert isinstance(text, str) assert alignment in (LEFT, CENTER, RIGHT) else: text = str(cell) if isinstance(cell, str): alignment = LEFT else: alignment = RIGHT full[x, y] = (text, alignment) colwidth[x] = max(colwidth[x], len(text)) # Calculate the horizontal separator line (dashes and dots) sep = "" for x in range(width): if sep: sep += "+" sep += "-"*colwidth[x] # Now print The full grid for y in range(height): line = "" for x in range(width): text, alignment = full.get((x, y)) or ("", LEFT) text = align2action[alignment](text, colwidth[x]) if line: line += '|' line += text print line if y == 0: print sep def xml(self): out = [''] for (x, y), cell in self.cells.iteritems(): if hasattr(cell, 'xml'): cellxml = cell.xml() else: cellxml = '%s' % cgi.escape(cell) out.append('\n %s\n' % (y, x, cellxml)) out.append('') return '\n'.join(out) def save(self, filename): text = self.xml() f = open(filename, "w") f.write(text) if text and not text.endswith('\n'): f.write('\n') f.close() def load(self, filename): f = open(filename, 'r') SheetParser(self).parsefile(f) f.close() class SheetParser: def __init__(self, sheet): self.sheet = sheet def parsefile(self, f): parser = expat.ParserCreate() parser.StartElementHandler = self.startelement parser.EndElementHandler = self.endelement parser.CharacterDataHandler = self.data parser.ParseFile(f) def startelement(self, tag, attrs): method = getattr(self, 'start_'+tag, None) if method: for key, value in attrs.iteritems(): attrs[key] = str(value) # XXX Convert Unicode to 8-bit method(attrs) self.texts = [] def data(self, text): text = str(text) # XXX Convert Unicode to 8-bit self.texts.append(text) def endelement(self, tag): method = getattr(self, 'end_'+tag, None) if method: method("".join(self.texts)) def start_cell(self, attrs): self.y = int(attrs.get("row")) self.x = int(attrs.get("col")) def start_value(self, attrs): self.fmt = attrs.get('format') self.alignment = xml2align.get(attrs.get('align')) start_formula = start_value def end_int(self, text): try: self.value = int(text) except: self.value = None def end_long(self, text): try: self.value = long(text) except: self.value = None def end_double(self, text): try: self.value = float(text) except: self.value = None def end_complex(self, text): try: self.value = complex(text) except: self.value = None def end_string(self, text): try: self.value = text except: self.value = None def end_value(self, text): if isinstance(self.value, BaseCell): self.cell = self.value elif isinstance(self.value, str): self.cell = StringCell(self.value, self.fmt or "%s", self.alignment or LEFT) else: self.cell = NumericCell(self.value, self.fmt or "%s", self.alignment or RIGHT) def end_formula(self, text): self.cell = FormulaCell(text, self.fmt or "%s", self.alignment or RIGHT) def end_cell(self, text): self.sheet.setcell(self.x, self.y, self.cell) class BaseCell: __init__ = None # Must provide """Abstract base class for sheet cells. Subclasses may but needn't provide the following APIs: cell.reset() -- prepare for recalculation cell.recalc(rexec) -> value -- recalculate formula cell.format() -> (value, alignment) -- return formatted value cell.xml() -> string -- return XML """ class NumericCell(BaseCell): def __init__(self, value, fmt="%s", alignment=RIGHT): assert isinstance(value, (int, long, float, complex)) assert alignment in (LEFT, CENTER, RIGHT) self.value = value self.fmt = fmt self.alignment = alignment def recalc(self, rexec): return self.value def format(self): try: text = self.fmt % self.value except: text = str(self.value) return text, self.alignment def xml(self): method = getattr(self, '_xml_' + type(self.value).__name__) return '%s' % ( align2xml[self.alignment], self.fmt, method()) def _xml_int(self): if -2**31 <= self.value < 2**31: return '%s' % self.value else: return self._xml_long() def _xml_long(self): return '%s' % self.value def _xml_float(self): return '%s' % repr(self.value) def _xml_complex(self): return '%s' % repr(self.value) class StringCell(BaseCell): def __init__(self, text, fmt="%s", alignment=LEFT): assert isinstance(text, (str, unicode)) assert alignment in (LEFT, CENTER, RIGHT) self.text = text self.fmt = fmt self.alignment = alignment def recalc(self, rexec): return self.text def format(self): return self.text, self.alignment def xml(self): s = '%s' return s % ( align2xml[self.alignment], self.fmt, cgi.escape(self.text)) class FormulaCell(BaseCell): def __init__(self, formula, fmt="%s", alignment=RIGHT): assert alignment in (LEFT, CENTER, RIGHT) self.formula = formula self.translated = translate(self.formula) self.fmt = fmt self.alignment = alignment self.reset() def reset(self): self.value = None def recalc(self, rexec): if self.value is None: try: # A hack to evaluate expressions using true division rexec.r_exec("from __future__ import division\n" + "__value__ = eval(%s)" % repr(self.translated)) self.value = rexec.r_eval("__value__") except: exc = sys.exc_info()[0] if hasattr(exc, "__name__"): self.value = exc.__name__ else: self.value = str(exc) return self.value def format(self): try: text = self.fmt % self.value except: text = str(self.value) return text, self.alignment def xml(self): return '%s' % ( align2xml[self.alignment], self.fmt, self.formula) def renumber(self, x1, y1, x2, y2, dx, dy): out = [] for part in re.split('(\w+)', self.formula): m = re.match('^([A-Z]+)([1-9][0-9]*)$', part) if m is not None: sx, sy = m.groups() x = colname2num(sx) y = int(sy) if x1 <= x <= x2 and y1 <= y <= y2: part = cellname(x+dx, y+dy) out.append(part) return FormulaCell("".join(out), self.fmt, self.alignment) def translate(formula): """Translate a formula containing fancy cell names to valid Python code. Examples: B4 -> cell(2, 4) B4:Z100 -> cells(2, 4, 26, 100) """ out = [] for part in re.split(r"(\w+(?::\w+)?)", formula): m = re.match(r"^([A-Z]+)([1-9][0-9]*)(?::([A-Z]+)([1-9][0-9]*))?$", part) if m is None: out.append(part) else: x1, y1, x2, y2 = m.groups() x1 = colname2num(x1) if x2 is None: s = "cell(%s, %s)" % (x1, y1) else: x2 = colname2num(x2) s = "cells(%s, %s, %s, %s)" % (x1, y1, x2, y2) out.append(s) return "".join(out) def cellname(x, y): "Translate a cell coordinate to a fancy cell name (e.g. (1, 1)->'A1')." assert x > 0 # Column 0 has an empty name, so can't use that return colnum2name(x) + str(y) def colname2num(s): "Translate a column name to number (e.g. 'A'->1, 'Z'->26, 'AA'->27)." s = s.upper() n = 0 for c in s: assert 'A' <= c <= 'Z' n = n*26 + ord(c) - ord('A') + 1 return n def colnum2name(n): "Translate a column number to name (e.g. 1->'A', etc.)." assert n > 0 s = "" while n: n, m = divmod(n-1, 26) s = chr(m+ord('A')) + s return s import Tkinter as Tk class SheetGUI: """Beginnings of a GUI for a spreadsheet. TO DO: - clear multiple cells - Insert, clear, remove rows or columns - Show new contents while typing - Scroll bars - Grow grid when window is grown - Proper menus - Undo, redo - Cut, copy and paste - Formatting and alignment """ def __init__(self, filename="sheet1.xml", rows=10, columns=5): """Constructor. Load the sheet from the filename argument. Set up the Tk widget tree. """ # Create and load the sheet self.filename = filename self.sheet = Sheet() if os.path.isfile(filename): self.sheet.load(filename) # Calculate the needed grid size maxx, maxy = self.sheet.getsize() rows = max(rows, maxy) columns = max(columns, maxx) # Create the widgets self.root = Tk.Tk() self.root.wm_title("Spreadsheet: %s" % self.filename) self.beacon = Tk.Label(self.root, text="A1", font=('helvetica', 16, 'bold')) self.entry = Tk.Entry(self.root) self.savebutton = Tk.Button(self.root, text="Save", command=self.save) self.cellgrid = Tk.Frame(self.root) # Configure the widget lay-out self.cellgrid.pack(side="bottom", expand=1, fill="both") self.beacon.pack(side="left") self.savebutton.pack(side="right") self.entry.pack(side="left", expand=1, fill="x") # Bind some events self.entry.bind("", self.return_event) self.entry.bind("", self.shift_return_event) self.entry.bind("", self.tab_event) self.entry.bind("", self.shift_tab_event) self.entry.bind("", self.delete_event) self.entry.bind("", self.escape_event) # Now create the cell grid self.makegrid(rows, columns) # Select the top-left cell self.currentxy = None self.cornerxy = None self.setcurrent(1, 1) # Copy the sheet cells to the GUI cells self.sync() def delete_event(self, event): if self.cornerxy != self.currentxy and self.cornerxy is not None: self.sheet.clearcells(*(self.currentxy + self.cornerxy)) else: self.sheet.clearcell(*self.currentxy) self.sync() self.entry.delete(0, 'end') return "break" def escape_event(self, event): x, y = self.currentxy self.load_entry(x, y) def load_entry(self, x, y): cell = self.sheet.getcell(x, y) if cell is None: text = "" elif isinstance(cell, FormulaCell): text = '=' + cell.formula else: text, alignment = cell.format() self.entry.delete(0, 'end') self.entry.insert(0, text) self.entry.selection_range(0, 'end') def makegrid(self, rows, columns): """Helper to create the grid of GUI cells. The edge (x==0 or y==0) is filled with labels; the rest is real cells. """ self.rows = rows self.columns = columns self.gridcells = {} # Create the top left corner cell (which selects all) cell = Tk.Label(self.cellgrid, relief='raised') cell.grid_configure(column=0, row=0, sticky='NSWE') cell.bind("", self.selectall) # Create the top row of labels, and confiure the grid columns for x in range(1, columns+1): self.cellgrid.grid_columnconfigure(x, minsize=64) cell = Tk.Label(self.cellgrid, text=colnum2name(x), relief='raised') cell.grid_configure(column=x, row=0, sticky='WE') self.gridcells[x, 0] = cell cell.__x = x cell.__y = 0 cell.bind("", self.selectcolumn) cell.bind("", self.extendcolumn) cell.bind("", self.extendcolumn) cell.bind("", self.extendcolumn) # Create the leftmost column of labels for y in range(1, rows+1): cell = Tk.Label(self.cellgrid, text=str(y), relief='raised') cell.grid_configure(column=0, row=y, sticky='WE') self.gridcells[0, y] = cell cell.__x = 0 cell.__y = y cell.bind("", self.selectrow) cell.bind("", self.extendrow) cell.bind("", self.extendrow) cell.bind("", self.extendrow) # Create the real cells for x in range(1, columns+1): for y in range(1, rows+1): cell = Tk.Label(self.cellgrid, relief='sunken', bg='white', fg='black') cell.grid_configure(column=x, row=y, sticky='NSWE') self.gridcells[x, y] = cell cell.__x = x cell.__y = y # Bind mouse events cell.bind("", self.press) cell.bind("", self.motion) cell.bind("", self.release) cell.bind("", self.release) def selectall(self, event): self.setcurrent(1, 1) self.setcorner(sys.maxint, sys.maxint) def selectcolumn(self, event): x, y = self.whichxy(event) self.setcurrent(x, 1) self.setcorner(x, sys.maxint) def extendcolumn(self, event): x, y = self.whichxy(event) if x > 0: self.setcurrent(self.currentxy[0], 1) self.setcorner(x, sys.maxint) def selectrow(self, event): x, y = self.whichxy(event) self.setcurrent(1, y) self.setcorner(sys.maxint, y) def extendrow(self, event): x, y = self.whichxy(event) if y > 0: self.setcurrent(1, self.currentxy[1]) self.setcorner(sys.maxint, y) def press(self, event): x, y = self.whichxy(event) if x > 0 and y > 0: self.setcurrent(x, y) def motion(self, event): x, y = self.whichxy(event) if x > 0 and y > 0: self.setcorner(x, y) release = motion def whichxy(self, event): w = self.cellgrid.winfo_containing(event.x_root, event.y_root) if w is not None and isinstance(w, Tk.Label): try: return w.__x, w.__y except AttributeError: pass return 0, 0 def save(self): self.sheet.save(self.filename) def setcurrent(self, x, y): "Make (x, y) the current cell." if self.currentxy is not None: self.change_cell() self.clearfocus() self.beacon['text'] = cellname(x, y) self.load_entry(x, y) self.entry.focus_set() self.currentxy = x, y self.cornerxy = None gridcell = self.gridcells.get(self.currentxy) if gridcell is not None: gridcell['bg'] = 'yellow' def setcorner(self, x, y): if self.currentxy is None or self.currentxy == (x, y): self.setcurrent(x, y) return self.clearfocus() self.cornerxy = x, y x1, y1 = self.currentxy x2, y2 = self.cornerxy or self.currentxy if x1 > x2: x1, x2 = x2, x1 if y1 > y2: y1, y2 = y2, y1 for (x, y), cell in self.gridcells.iteritems(): if x1 <= x <= x2 and y1 <= y <= y2: cell['bg'] = 'lightBlue' gridcell = self.gridcells.get(self.currentxy) if gridcell is not None: gridcell['bg'] = 'yellow' self.setbeacon(x1, y1, x2, y2) def setbeacon(self, x1, y1, x2, y2): if x1 == y1 == 1 and x2 == y2 == sys.maxint: name = ":" elif (x1, x2) == (1, sys.maxint): if y1 == y2: name = "%d" % y1 else: name = "%d:%d" % (y1, y2) elif (y1, y2) == (1, sys.maxint): if x1 == x2: name = "%s" % colnum2name(x1) else: name = "%s:%s" % (colnum2name(x1), colnum2name(x2)) else: name1 = cellname(*self.currentxy) name2 = cellname(*self.cornerxy) name = "%s:%s" % (name1, name2) self.beacon['text'] = name def clearfocus(self): if self.currentxy is not None: x1, y1 = self.currentxy x2, y2 = self.cornerxy or self.currentxy if x1 > x2: x1, x2 = x2, x1 if y1 > y2: y1, y2 = y2, y1 for (x, y), cell in self.gridcells.iteritems(): if x1 <= x <= x2 and y1 <= y <= y2: cell['bg'] = 'white' def return_event(self, event): "Callback for the Return key." self.change_cell() x, y = self.currentxy self.setcurrent(x, y+1) return "break" def shift_return_event(self, event): "Callback for the Return key with Shift modifier." self.change_cell() x, y = self.currentxy self.setcurrent(x, max(1, y-1)) return "break" def tab_event(self, event): "Callback for the Tab key." self.change_cell() x, y = self.currentxy self.setcurrent(x+1, y) return "break" def shift_tab_event(self, event): "Callback for the Tab key with Shift modifier." self.change_cell() x, y = self.currentxy self.setcurrent(max(1, x-1), y) return "break" def change_cell(self): "Set the current cell from the entry widget." x, y = self.currentxy text = self.entry.get() cell = None if text.startswith('='): cell = FormulaCell(text[1:]) else: for cls in int, long, float, complex: try: value = cls(text) except: continue else: cell = NumericCell(value) break if cell is None and text: cell = StringCell(text) if cell is None: self.sheet.clearcell(x, y) else: self.sheet.setcell(x, y, cell) self.sync() def sync(self): "Fill the GUI cells from the sheet cells." self.sheet.recalc() for (x, y), gridcell in self.gridcells.iteritems(): if x == 0 or y == 0: continue cell = self.sheet.getcell(x, y) if cell is None: gridcell['text'] = "" else: if hasattr(cell, 'format'): text, alignment = cell.format() else: text, alignment = str(cell), LEFT gridcell['text'] = text gridcell['anchor'] = align2anchor[alignment] def test_basic(): "Basic non-gui self-test." import os a = Sheet() for x in range(1, 11): for y in range(1, 11): if x == 1: cell = NumericCell(y) elif y == 1: cell = NumericCell(x) else: c1 = cellname(x, 1) c2 = cellname(1, y) formula = "%s*%s" % (c1, c2) cell = FormulaCell(formula) a.setcell(x, y, cell) ## if os.path.isfile("sheet1.xml"): ## print "Loading from sheet1.xml" ## a.load("sheet1.xml") a.display() a.save("sheet1.xml") def test_gui(): "GUI test." if sys.argv[1:]: filename = sys.argv[1] else: filename = "sheet1.xml" g = SheetGUI(filename) g.root.mainloop() if __name__ == '__main__': #test_basic() test_gui() PK%L]Ṁ tkinter/guido/dialog.pynuȯ#! /usr/bin/python2.7 # A Python function that generates dialog boxes with a text message, # optional bitmap, and any number of buttons. # Cf. Ousterhout, Tcl and the Tk Toolkit, Figs. 27.2-3, pp. 269-270. from Tkinter import * import sys def dialog(master, title, text, bitmap, default, *args): # 1. Create the top-level window and divide it into top # and bottom parts. w = Toplevel(master, class_='Dialog') w.title(title) w.iconname('Dialog') top = Frame(w, relief=RAISED, borderwidth=1) top.pack(side=TOP, fill=BOTH) bot = Frame(w, relief=RAISED, borderwidth=1) bot.pack(side=BOTTOM, fill=BOTH) # 2. Fill the top part with the bitmap and message. msg = Message(top, width='3i', text=text, font='-Adobe-Times-Medium-R-Normal-*-180-*') msg.pack(side=RIGHT, expand=1, fill=BOTH, padx='3m', pady='3m') if bitmap: bm = Label(top, bitmap=bitmap) bm.pack(side=LEFT, padx='3m', pady='3m') # 3. Create a row of buttons at the bottom of the dialog. var = IntVar() buttons = [] i = 0 for but in args: b = Button(bot, text=but, command=lambda v=var,i=i: v.set(i)) buttons.append(b) if i == default: bd = Frame(bot, relief=SUNKEN, borderwidth=1) bd.pack(side=LEFT, expand=1, padx='3m', pady='2m') b.lift() b.pack (in_=bd, side=LEFT, padx='2m', pady='2m', ipadx='2m', ipady='1m') else: b.pack (side=LEFT, expand=1, padx='3m', pady='3m', ipadx='2m', ipady='1m') i = i+1 # 4. Set up a binding for , if there's a default, # set a grab, and claim the focus too. if default >= 0: w.bind('', lambda e, b=buttons[default], v=var, i=default: (b.flash(), v.set(i))) oldFocus = w.focus_get() w.grab_set() w.focus_set() # 5. Wait for the user to respond, then restore the focus # and return the index of the selected button. w.waitvar(var) w.destroy() if oldFocus: oldFocus.focus_set() return var.get() # The rest is the test program. def go(): i = dialog(mainWidget, 'Not Responding', "The file server isn't responding right now; " "I'll keep trying.", '', -1, 'OK') print 'pressed button', i i = dialog(mainWidget, 'File Modified', 'File "tcl.h" has been modified since ' 'the last time it was saved. ' 'Do you want to save it before exiting the application?', 'warning', 0, 'Save File', 'Discard Changes', 'Return To Editor') print 'pressed button', i def test(): import sys global mainWidget mainWidget = Frame() Pack.config(mainWidget) start = Button(mainWidget, text='Press Here To Start', command=go) start.pack() endit = Button(mainWidget, text="Exit", command=sys.exit) endit.pack(fill=BOTH) mainWidget.mainloop() if __name__ == '__main__': test() PK%L]^tkinter/guido/wish.pyonu[ ^c@sddlZddlZejejddddZejddZxer\dZndZyeeZ Wne k rPnXee d Zej ejd d erMej e yejd eZ Wnejk rZd GeGHnXe re GHndZqMqMWdS(iNtDISPLAYtwishtTkitupdatets% s tinfotcompletetevals TclError:(t_tkintertostcreatetenvironttktcalltcmdtpromptt raw_inputtlinetEOFErrort getbooleantrecordtresulttTclErrortmsg(((s//usr/lib64/python2.7/Demo/tkinter/guido/wish.pyts,       PK%L](Vtkinter/guido/ManPage.pynu[# Widget to display a man page import re from Tkinter import * from Tkinter import _tkinter from ScrolledText import ScrolledText # XXX These fonts may have to be changed to match your system BOLDFONT = '*-Courier-Bold-R-Normal-*-120-*' ITALICFONT = '*-Courier-Medium-O-Normal-*-120-*' # XXX Recognizing footers is system dependent # (This one works for IRIX 5.2 and Solaris 2.2) footerprog = re.compile( '^ Page [1-9][0-9]*[ \t]+\|^.*Last change:.*[1-9][0-9]*\n') emptyprog = re.compile('^[ \t]*\n') ulprog = re.compile('^[ \t]*[Xv!_][Xv!_ \t]*\n') # Basic Man Page class -- does not disable editing class EditableManPage(ScrolledText): # Initialize instance def __init__(self, master=None, **cnf): # Initialize base class apply(ScrolledText.__init__, (self, master), cnf) # Define tags for formatting styles self.tag_config('X', underline=1) self.tag_config('!', font=BOLDFONT) self.tag_config('_', font=ITALICFONT) # Set state to idle self.fp = None self.lineno = 0 # Test whether we are busy parsing a file def busy(self): return self.fp != None # Ensure we're not busy def kill(self): if self.busy(): self._endparser() # Parse a file, in the background def asyncparsefile(self, fp): self._startparser(fp) self.tk.createfilehandler(fp, _tkinter.READABLE, self._filehandler) parsefile = asyncparsefile # Alias # I/O handler used by background parsing def _filehandler(self, fp, mask): nextline = self.fp.readline() if not nextline: self._endparser() return self._parseline(nextline) # Parse a file, now (cannot be aborted) def syncparsefile(self, fp): from select import select def avail(fp=fp, tout=0.0, select=select): return select([fp], [], [], tout)[0] height = self.getint(self['height']) self._startparser(fp) while 1: nextline = fp.readline() if not nextline: break self._parseline(nextline) self._endparser() # Initialize parsing from a particular file -- must not be busy def _startparser(self, fp): if self.busy(): raise RuntimeError, 'startparser: still busy' fp.fileno() # Test for file-ness self.fp = fp self.lineno = 0 self.ok = 0 self.empty = 0 self.buffer = None savestate = self['state'] self['state'] = NORMAL self.delete('1.0', END) self['state'] = savestate # End parsing -- must be busy, need not be at EOF def _endparser(self): if not self.busy(): raise RuntimeError, 'endparser: not busy' if self.buffer: self._parseline('') try: self.tk.deletefilehandler(self.fp) except TclError, msg: pass self.fp.close() self.fp = None del self.ok, self.empty, self.buffer # Parse a single line def _parseline(self, nextline): if not self.buffer: # Save this line -- we need one line read-ahead self.buffer = nextline return if emptyprog.match(self.buffer) >= 0: # Buffered line was empty -- set a flag self.empty = 1 self.buffer = nextline return textline = self.buffer if ulprog.match(nextline) >= 0: # Next line is properties for buffered line propline = nextline self.buffer = None else: # Next line is read-ahead propline = None self.buffer = nextline if not self.ok: # First non blank line after footer must be header # -- skip that too self.ok = 1 self.empty = 0 return if footerprog.match(textline) >= 0: # Footer -- start skipping until next non-blank line self.ok = 0 self.empty = 0 return savestate = self['state'] self['state'] = NORMAL if TkVersion >= 4.0: self.mark_set('insert', 'end-1c') else: self.mark_set('insert', END) if self.empty: # One or more previous lines were empty # -- insert one blank line in the text self._insert_prop('\n') self.lineno = self.lineno + 1 self.empty = 0 if not propline: # No properties self._insert_prop(textline) else: # Search for properties p = '' j = 0 for i in range(min(len(propline), len(textline))): if propline[i] != p: if j < i: self._insert_prop(textline[j:i], p) j = i p = propline[i] self._insert_prop(textline[j:]) self.lineno = self.lineno + 1 self['state'] = savestate # Insert a string at the end, with at most one property (tag) def _insert_prop(self, str, prop = ' '): here = self.index(AtInsert()) self.insert(AtInsert(), str) if TkVersion <= 4.0: tags = self.tag_names(here) for tag in tags: self.tag_remove(tag, here, AtInsert()) if prop != ' ': self.tag_add(prop, here, AtInsert()) # Readonly Man Page class -- disables editing, otherwise the same class ReadonlyManPage(EditableManPage): # Initialize instance def __init__(self, master=None, **cnf): cnf['state'] = DISABLED apply(EditableManPage.__init__, (self, master), cnf) # Alias ManPage = ReadonlyManPage # Test program. # usage: ManPage [manpage]; or ManPage [-f] file # -f means that the file is nroff -man output run through ul -i def test(): import os import sys # XXX This directory may be different on your system MANDIR = '/usr/local/man/mann' DEFAULTPAGE = 'Tcl' formatted = 0 if sys.argv[1:] and sys.argv[1] == '-f': formatted = 1 del sys.argv[1] if sys.argv[1:]: name = sys.argv[1] else: name = DEFAULTPAGE if not formatted: if name[-2:-1] != '.': name = name + '.n' name = os.path.join(MANDIR, name) root = Tk() root.minsize(1, 1) manpage = ManPage(root, relief=SUNKEN, borderwidth=2) manpage.pack(expand=1, fill=BOTH) if formatted: fp = open(name, 'r') else: fp = os.popen('nroff -man %s | ul -i' % name, 'r') manpage.parsefile(fp) root.mainloop() # Run the test program when called as a script if __name__ == '__main__': test() PK%L].,#,#tkinter/guido/tkman.pynuȯ#! /usr/bin/python2.7 # Tk man page browser -- currently only shows the Tcl/Tk man pages import sys import os import string import re from Tkinter import * from ManPage import ManPage MANNDIRLIST = ['/depot/sundry/man/mann','/usr/local/man/mann'] MAN3DIRLIST = ['/depot/sundry/man/man3','/usr/local/man/man3'] foundmanndir = 0 for dir in MANNDIRLIST: if os.path.exists(dir): MANNDIR = dir foundmanndir = 1 foundman3dir = 0 for dir in MAN3DIRLIST: if os.path.exists(dir): MAN3DIR = dir foundman3dir = 1 if not foundmanndir or not foundman3dir: sys.stderr.write('\n') if not foundmanndir: msg = """\ Failed to find mann directory. Please add the correct entry to the MANNDIRLIST at the top of %s script.""" % \ sys.argv[0] sys.stderr.write("%s\n\n" % msg) if not foundman3dir: msg = """\ Failed to find man3 directory. Please add the correct entry to the MAN3DIRLIST at the top of %s script.""" % \ sys.argv[0] sys.stderr.write("%s\n\n" % msg) sys.exit(1) del foundmanndir del foundman3dir def listmanpages(mandir): files = os.listdir(mandir) names = [] for file in files: if file[-2:-1] == '.' and (file[-1] in 'ln123456789'): names.append(file[:-2]) names.sort() return names class SelectionBox: def __init__(self, master=None): self.choices = [] self.frame = Frame(master, name="frame") self.frame.pack(expand=1, fill=BOTH) self.master = self.frame.master self.subframe = Frame(self.frame, name="subframe") self.subframe.pack(expand=0, fill=BOTH) self.leftsubframe = Frame(self.subframe, name='leftsubframe') self.leftsubframe.pack(side=LEFT, expand=1, fill=BOTH) self.rightsubframe = Frame(self.subframe, name='rightsubframe') self.rightsubframe.pack(side=RIGHT, expand=1, fill=BOTH) self.chaptervar = StringVar(master) self.chapter = Menubutton(self.rightsubframe, name='chapter', text='Directory', relief=RAISED, borderwidth=2) self.chapter.pack(side=TOP) self.chaptermenu = Menu(self.chapter, name='chaptermenu') self.chaptermenu.add_radiobutton(label='C functions', value=MAN3DIR, variable=self.chaptervar, command=self.newchapter) self.chaptermenu.add_radiobutton(label='Tcl/Tk functions', value=MANNDIR, variable=self.chaptervar, command=self.newchapter) self.chapter['menu'] = self.chaptermenu self.listbox = Listbox(self.rightsubframe, name='listbox', relief=SUNKEN, borderwidth=2, width=20, height=5) self.listbox.pack(expand=1, fill=BOTH) self.l1 = Button(self.leftsubframe, name='l1', text='Display manual page named:', command=self.entry_cb) self.l1.pack(side=TOP) self.entry = Entry(self.leftsubframe, name='entry', relief=SUNKEN, borderwidth=2, width=20) self.entry.pack(expand=0, fill=X) self.l2frame = Frame(self.leftsubframe, name='l2frame') self.l2frame.pack(expand=0, fill=NONE) self.l2 = Button(self.l2frame, name='l2', text='Search regexp:', command=self.search_cb) self.l2.pack(side=LEFT) self.casevar = BooleanVar() self.casesense = Checkbutton(self.l2frame, name='casesense', text='Case sensitive', variable=self.casevar, relief=FLAT) self.casesense.pack(side=LEFT) self.search = Entry(self.leftsubframe, name='search', relief=SUNKEN, borderwidth=2, width=20) self.search.pack(expand=0, fill=X) self.title = Label(self.leftsubframe, name='title', text='(none)') self.title.pack(side=BOTTOM) self.text = ManPage(self.frame, name='text', relief=SUNKEN, borderwidth=2, wrap=NONE, width=72, selectbackground='pink') self.text.pack(expand=1, fill=BOTH) self.entry.bind('', self.entry_cb) self.search.bind('', self.search_cb) self.listbox.bind('', self.listbox_cb) self.entry.bind('', self.entry_tab) self.search.bind('', self.search_tab) self.text.bind('', self.text_tab) self.entry.focus_set() self.chaptervar.set(MANNDIR) self.newchapter() def newchapter(self): mandir = self.chaptervar.get() self.choices = [] self.addlist(listmanpages(mandir)) def addchoice(self, choice): if choice not in self.choices: self.choices.append(choice) self.choices.sort() self.update() def addlist(self, list): self.choices[len(self.choices):] = list self.choices.sort() self.update() def entry_cb(self, *e): self.update() def listbox_cb(self, e): selection = self.listbox.curselection() if selection and len(selection) == 1: name = self.listbox.get(selection[0]) self.show_page(name) def search_cb(self, *e): self.search_string(self.search.get()) def entry_tab(self, e): self.search.focus_set() def search_tab(self, e): self.entry.focus_set() def text_tab(self, e): self.entry.focus_set() def updatelist(self): key = self.entry.get() ok = filter(lambda name, key=key, n=len(key): name[:n]==key, self.choices) if not ok: self.frame.bell() self.listbox.delete(0, AtEnd()) exactmatch = 0 for item in ok: if item == key: exactmatch = 1 self.listbox.insert(AtEnd(), item) if exactmatch: return key n = self.listbox.size() if n == 1: return self.listbox.get(0) # Else return None, meaning not a unique selection def update(self): name = self.updatelist() if name: self.show_page(name) self.entry.delete(0, AtEnd()) self.updatelist() def show_page(self, name): file = '%s/%s.?' % (self.chaptervar.get(), name) fp = os.popen('nroff -man %s | ul -i' % file, 'r') self.text.kill() self.title['text'] = name self.text.parsefile(fp) def search_string(self, search): if not search: self.frame.bell() print 'Empty search string' return if not self.casevar.get(): map = re.IGNORECASE else: map = None try: if map: prog = re.compile(search, map) else: prog = re.compile(search) except re.error, msg: self.frame.bell() print 'Regex error:', msg return here = self.text.index(AtInsert()) lineno = string.atoi(here[:string.find(here, '.')]) end = self.text.index(AtEnd()) endlineno = string.atoi(end[:string.find(end, '.')]) wraplineno = lineno found = 0 while 1: lineno = lineno + 1 if lineno > endlineno: if wraplineno <= 0: break endlineno = wraplineno lineno = 0 wraplineno = 0 line = self.text.get('%d.0 linestart' % lineno, '%d.0 lineend' % lineno) i = prog.search(line) if i >= 0: found = 1 n = max(1, len(prog.group(0))) try: self.text.tag_remove('sel', AtSelFirst(), AtSelLast()) except TclError: pass self.text.tag_add('sel', '%d.%d' % (lineno, i), '%d.%d' % (lineno, i+n)) self.text.mark_set(AtInsert(), '%d.%d' % (lineno, i)) self.text.yview_pickplace(AtInsert()) break if not found: self.frame.bell() def main(): root = Tk() sb = SelectionBox(root) if sys.argv[1:]: sb.show_page(sys.argv[1]) root.minsize(1, 1) root.mainloop() main() PK%L]MdUUtkinter/guido/MimeViewer.pycnu[ Afc@soddlZddlTddlTddlmZdd dYZdZdZedkrkendS( iN(t*(t ScrolledTextt MimeViewercBsGeZdZdZdZdZdZdZdZRS(c Cs||_||_t|idd6dd6|_idd6dd6|j_t|ji|d 6|jd 6|_|jjid d 6|j d }t |d}|r"t |ji|d6dd6dd6dd6dd6|_ idd6dd6|jd6|j _|j j d|nNt|jidd6dd6|_ idd6dd6dd6|jd6|j _|j}t|tkr)d|_t |d}|rt |ji|d6dd6dd6dd6dd6|_idd6dd6|j_|jj d|n d|_d|_nt|jidd6dd6|_idd6dd6dd6|j d6|j_g|_xQtt|D]=}t|jd ||df||}|jj|qWd|_d|_dS(!NtraisedtreliefitbditexpandtbothtfillttexttcommandtwtanchorcSs|dko|d dkS(Ntreceivedisx400-((tx((s5/usr/lib64/python2.7/Demo/tkinter/guido/MimeViewer.pyttitheightiPtwidthtnonetwrapitaftertendttoptsidetipadyRi tflattlefttipadxtys%s.%d(ttitletmsgtFrametframetpackingt Checkbuttonttoggletbuttontpackt getheadertextt countlinesRthtexttinserttgetbodyttypet StringTypetNonetpadtbtexttpartstrangetlenRtappendt collapsed( tselftparentRRt headertextRtbodytitp((s5/usr/lib64/python2.7/Demo/tkinter/guido/MimeViewer.pyt__init__ sn                      cCs|jj|jjdS(N(R!R&R"(R6((s5/usr/lib64/python2.7/Demo/tkinter/guido/MimeViewer.pyR&GscCs|jjdS(N(R!tdestroy(R6((s5/usr/lib64/python2.7/Demo/tkinter/guido/MimeViewer.pyR=IscCs|jr|jjndS(N(R5R%tinvoke(R6((s5/usr/lib64/python2.7/Demo/tkinter/guido/MimeViewer.pytshowKs cCs$|jr|jn |jdS(N(R5texplodetcollapse(R6((s5/usr/lib64/python2.7/Demo/tkinter/guido/MimeViewer.pyR$Ns  cCsd|_x3|j|j|jfD]}|r"|jq"q"W|jrlx!|jD]}|jjqRWn|jjidd6dS(NiiR(R5R)R0R/tforgetR1R!R&(R6tcomptpart((s5/usr/lib64/python2.7/Demo/tkinter/guido/MimeViewer.pyRASs  cCsd|_x9|j|j|jfD]}|r"|j|jq"q"W|jrox|jD]}|jqXWn|jjidd6dS(NiiR(R5R)R0R/R&R"R1R!(R6RCRD((s5/usr/lib64/python2.7/Demo/tkinter/guido/MimeViewer.pyR@\s  ( t__name__t __module__R<R&R=R?R$RAR@(((s5/usr/lib64/python2.7/Demo/tkinter/guido/MimeViewer.pyR s ;     cCs\d}d}xI||krWtj|d|}|dkr@Pn|d}|d}qW|S(Nis i(tstringtfind(tstrtlimitR:tn((s5/usr/lib64/python2.7/Demo/tkinter/guido/MimeViewer.pyR(es  cCsBddl}ddl}ddl}|j|jdd\}}x|D] \}}qJWd}d}x:|D]2} | d dkr| d}qmtj| }qmW|j} | j|} |s| j }n| j |} t } | j }t | d||f| }|j|j| jdd|jdS(NiiRtinboxt+s+%s/%d(tsystgetopttmhlibtargvR.RGtatoitMHt openfoldert getcurrentt openmessagetTkttkRR&R?tminsizetmainloop(RNRORPtoptstargstotatmessagetfoldertargtmhtftmtrootRXR((s5/usr/lib64/python2.7/Demo/tkinter/guido/MimeViewer.pytmainos0          t__main__((RGttypestTkinterRRR(RfRE(((s5/usr/lib64/python2.7/Demo/tkinter/guido/MimeViewer.pyts   Z PK%L]Dtkinter/guido/optionmenu.pynu[# option menu sample (Fredrik Lundh, September 1997) from Tkinter import * root = Tk() # # standard usage var1 = StringVar() var1.set("One") # default selection menu1 = OptionMenu(root, var1, "One", "Two", "Three") menu1.pack() # # initialize from a sequence CHOICES = "Aah", "Bee", "Cee", "Dee", "Eff" var2 = StringVar() var2.set(CHOICES[0]) menu2 = apply(OptionMenu, (root, var2) + tuple(CHOICES)) menu2.pack() root.mainloop() PK%L]ե))tkinter/guido/hanoi.pynu[# Animated Towers of Hanoi using Tk with optional bitmap file in # background. # # Usage: tkhanoi [n [bitmapfile]] # # n is the number of pieces to animate; default is 4, maximum 15. # # The bitmap file can be any X11 bitmap file (look in # /usr/include/X11/bitmaps for samples); it is displayed as the # background of the animation. Default is no bitmap. # This uses Steen Lumholt's Tk interface from Tkinter import * # Basic Towers-of-Hanoi algorithm: move n pieces from a to b, using c # as temporary. For each move, call report() def hanoi(n, a, b, c, report): if n <= 0: return hanoi(n-1, a, c, b, report) report(n, a, b) hanoi(n-1, c, b, a, report) # The graphical interface class Tkhanoi: # Create our objects def __init__(self, n, bitmap = None): self.n = n self.tk = tk = Tk() self.canvas = c = Canvas(tk) c.pack() width, height = tk.getint(c['width']), tk.getint(c['height']) # Add background bitmap if bitmap: self.bitmap = c.create_bitmap(width//2, height//2, bitmap=bitmap, foreground='blue') # Generate pegs pegwidth = 10 pegheight = height//2 pegdist = width//3 x1, y1 = (pegdist-pegwidth)//2, height*1//3 x2, y2 = x1+pegwidth, y1+pegheight self.pegs = [] p = c.create_rectangle(x1, y1, x2, y2, fill='black') self.pegs.append(p) x1, x2 = x1+pegdist, x2+pegdist p = c.create_rectangle(x1, y1, x2, y2, fill='black') self.pegs.append(p) x1, x2 = x1+pegdist, x2+pegdist p = c.create_rectangle(x1, y1, x2, y2, fill='black') self.pegs.append(p) self.tk.update() # Generate pieces pieceheight = pegheight//16 maxpiecewidth = pegdist*2//3 minpiecewidth = 2*pegwidth self.pegstate = [[], [], []] self.pieces = {} x1, y1 = (pegdist-maxpiecewidth)//2, y2-pieceheight-2 x2, y2 = x1+maxpiecewidth, y1+pieceheight dx = (maxpiecewidth-minpiecewidth) // (2*max(1, n-1)) for i in range(n, 0, -1): p = c.create_rectangle(x1, y1, x2, y2, fill='red') self.pieces[i] = p self.pegstate[0].append(i) x1, x2 = x1 + dx, x2-dx y1, y2 = y1 - pieceheight-2, y2-pieceheight-2 self.tk.update() self.tk.after(25) # Run -- never returns def run(self): while 1: hanoi(self.n, 0, 1, 2, self.report) hanoi(self.n, 1, 2, 0, self.report) hanoi(self.n, 2, 0, 1, self.report) hanoi(self.n, 0, 2, 1, self.report) hanoi(self.n, 2, 1, 0, self.report) hanoi(self.n, 1, 0, 2, self.report) # Reporting callback for the actual hanoi function def report(self, i, a, b): if self.pegstate[a][-1] != i: raise RuntimeError # Assertion del self.pegstate[a][-1] p = self.pieces[i] c = self.canvas # Lift the piece above peg a ax1, ay1, ax2, ay2 = c.bbox(self.pegs[a]) while 1: x1, y1, x2, y2 = c.bbox(p) if y2 < ay1: break c.move(p, 0, -1) self.tk.update() # Move it towards peg b bx1, by1, bx2, by2 = c.bbox(self.pegs[b]) newcenter = (bx1+bx2)//2 while 1: x1, y1, x2, y2 = c.bbox(p) center = (x1+x2)//2 if center == newcenter: break if center > newcenter: c.move(p, -1, 0) else: c.move(p, 1, 0) self.tk.update() # Move it down on top of the previous piece pieceheight = y2-y1 newbottom = by2 - pieceheight*len(self.pegstate[b]) - 2 while 1: x1, y1, x2, y2 = c.bbox(p) if y2 >= newbottom: break c.move(p, 0, 1) self.tk.update() # Update peg state self.pegstate[b].append(i) # Main program def main(): import sys, string # First argument is number of pegs, default 4 if sys.argv[1:]: n = string.atoi(sys.argv[1]) else: n = 4 # Second argument is bitmap file, default none if sys.argv[2:]: bitmap = sys.argv[2] # Reverse meaning of leading '@' compared to Tk if bitmap[0] == '@': bitmap = bitmap[1:] else: bitmap = '@' + bitmap else: bitmap = None # Create the graphical objects... h = Tkhanoi(n, bitmap) # ...and run! h.run() # Call main when run as script if __name__ == '__main__': main() PK%L]^ui i tkinter/guido/switch.pycnu[ ^c@sfddlTdd dYZdd dYZdd dYZdZed krbend S(i(t*tAppcBs)eZdddZdZdZRS(cCs|dkr3|dkr$t}q3t|}n||_t||_|jjt|dddt|_|jjdddt i|_ d|_ dS(Nt borderwidthitrelieftexpanditfill( tNonetTktToplevelttoptFramet buttonframetpacktGROOVEt panelframetBOTHtpanelstcurpanel(tselfR tmaster((s1/usr/lib64/python2.7/Demo/tkinter/guido/switch.pyt__init__s      cCst|jd|d||d}|jdtt|j}||}|||f|j|<|jdkr|j |ndS(NttexttcommandcSs |j|S(N(tshow(Rtname((s1/usr/lib64/python2.7/Demo/tkinter/guido/switch.pytttside( tButtonR R tLEFTR RRRRR(RRtklasstbuttontframetinstance((s1/usr/lib64/python2.7/Demo/tkinter/guido/switch.pytaddpanels cCsR|j|\}}}|jr/|jjn||_|jdddddS(NRiRtboth(RRt pack_forgetR (RRRR R!((s1/usr/lib64/python2.7/Demo/tkinter/guido/switch.pyRs   N(t__name__t __module__RRR"R(((s1/usr/lib64/python2.7/Demo/tkinter/guido/switch.pyRs t LabelPanelcBseZdZRS(cCs&t|dd|_|jjdS(NRs Hello world(tLabeltlabelR (RR ((s1/usr/lib64/python2.7/Demo/tkinter/guido/switch.pyR's(R%R&R(((s1/usr/lib64/python2.7/Demo/tkinter/guido/switch.pyR'&st ButtonPanelcBseZdZRS(cCs&t|dd|_|jjdS(NRsPress me(RRR (RR ((s1/usr/lib64/python2.7/Demo/tkinter/guido/switch.pyR,s(R%R&R(((s1/usr/lib64/python2.7/Demo/tkinter/guido/switch.pyR*+scCs:t}|jdt|jdt|jjdS(NR)R(RR"R'R*R tmainloop(tapp((s1/usr/lib64/python2.7/Demo/tkinter/guido/switch.pytmain0s t__main__N((((tTkinterRR'R*R-R%(((s1/usr/lib64/python2.7/Demo/tkinter/guido/switch.pyts !  PK%L]htkinter/guido/imagedraw.pycnu[ ^c@s9dZddlTddlZdZdZedS(sDraw on top of an imagei(t*NcCstjd}t}td|}|j|j}}t|d|d|}|jdddtd||j |j dt |j dS( Nitfiletwidththeightitanchortimages ( tsystargvtTkt PhotoImageRRtCanvast create_imagetNWtpacktbindtblobtmainloop(tfilenametroottimgtwthtcanv((s4/usr/lib64/python2.7/Demo/tkinter/guido/imagedraw.pytmains   c CsX|j|j}}|j}d}|j||||||||dddddS(Nitfilltredtoutlinet(txtytwidgett create_oval(teventRRRtr((s4/usr/lib64/python2.7/Demo/tkinter/guido/imagedraw.pyRs (t__doc__tTkinterRRR(((s4/usr/lib64/python2.7/Demo/tkinter/guido/imagedraw.pyts    PK%L]MdUUtkinter/guido/MimeViewer.pyonu[ Afc@soddlZddlTddlTddlmZdd dYZdZdZedkrkendS( iN(t*(t ScrolledTextt MimeViewercBsGeZdZdZdZdZdZdZdZRS(c Cs||_||_t|idd6dd6|_idd6dd6|j_t|ji|d 6|jd 6|_|jjid d 6|j d }t |d}|r"t |ji|d6dd6dd6dd6dd6|_ idd6dd6|jd6|j _|j j d|nNt|jidd6dd6|_ idd6dd6dd6|jd6|j _|j}t|tkr)d|_t |d}|rt |ji|d6dd6dd6dd6dd6|_idd6dd6|j_|jj d|n d|_d|_nt|jidd6dd6|_idd6dd6dd6|j d6|j_g|_xQtt|D]=}t|jd ||df||}|jj|qWd|_d|_dS(!NtraisedtreliefitbditexpandtbothtfillttexttcommandtwtanchorcSs|dko|d dkS(Ntreceivedisx400-((tx((s5/usr/lib64/python2.7/Demo/tkinter/guido/MimeViewer.pyttitheightiPtwidthtnonetwrapitaftertendttoptsidetipadyRi tflattlefttipadxtys%s.%d(ttitletmsgtFrametframetpackingt Checkbuttonttoggletbuttontpackt getheadertextt countlinesRthtexttinserttgetbodyttypet StringTypetNonetpadtbtexttpartstrangetlenRtappendt collapsed( tselftparentRRt headertextRtbodytitp((s5/usr/lib64/python2.7/Demo/tkinter/guido/MimeViewer.pyt__init__ sn                      cCs|jj|jjdS(N(R!R&R"(R6((s5/usr/lib64/python2.7/Demo/tkinter/guido/MimeViewer.pyR&GscCs|jjdS(N(R!tdestroy(R6((s5/usr/lib64/python2.7/Demo/tkinter/guido/MimeViewer.pyR=IscCs|jr|jjndS(N(R5R%tinvoke(R6((s5/usr/lib64/python2.7/Demo/tkinter/guido/MimeViewer.pytshowKs cCs$|jr|jn |jdS(N(R5texplodetcollapse(R6((s5/usr/lib64/python2.7/Demo/tkinter/guido/MimeViewer.pyR$Ns  cCsd|_x3|j|j|jfD]}|r"|jq"q"W|jrlx!|jD]}|jjqRWn|jjidd6dS(NiiR(R5R)R0R/tforgetR1R!R&(R6tcomptpart((s5/usr/lib64/python2.7/Demo/tkinter/guido/MimeViewer.pyRASs  cCsd|_x9|j|j|jfD]}|r"|j|jq"q"W|jrox|jD]}|jqXWn|jjidd6dS(NiiR(R5R)R0R/R&R"R1R!(R6RCRD((s5/usr/lib64/python2.7/Demo/tkinter/guido/MimeViewer.pyR@\s  ( t__name__t __module__R<R&R=R?R$RAR@(((s5/usr/lib64/python2.7/Demo/tkinter/guido/MimeViewer.pyR s ;     cCs\d}d}xI||krWtj|d|}|dkr@Pn|d}|d}qW|S(Nis i(tstringtfind(tstrtlimitR:tn((s5/usr/lib64/python2.7/Demo/tkinter/guido/MimeViewer.pyR(es  cCsBddl}ddl}ddl}|j|jdd\}}x|D] \}}qJWd}d}x:|D]2} | d dkr| d}qmtj| }qmW|j} | j|} |s| j }n| j |} t } | j }t | d||f| }|j|j| jdd|jdS(NiiRtinboxt+s+%s/%d(tsystgetopttmhlibtargvR.RGtatoitMHt openfoldert getcurrentt openmessagetTkttkRR&R?tminsizetmainloop(RNRORPtoptstargstotatmessagetfoldertargtmhtftmtrootRXR((s5/usr/lib64/python2.7/Demo/tkinter/guido/MimeViewer.pytmainos0          t__main__((RGttypestTkinterRRR(RfRE(((s5/usr/lib64/python2.7/Demo/tkinter/guido/MimeViewer.pyts   Z PK%L]kK\\tkinter/guido/sortvisu.pycnu[ Afc@sdZddlTddlmZmZddlZdZdZdZdddYZ d dd YZ d Z d Z d Z dZdZdZdZdZdZdZdddYZdZedkrendS(sjSorting algorithms visualizer using Tkinter. This module is comprised of three ``components'': - an array visualizer with methods that implement basic sorting operations (compare, swap) as well as methods for ``annotating'' the sorting algorithm (e.g. to show the pivot element); - a number of sorting algorithms (currently quicksort, insertion sort, selection sort and bubble sort, as well as a randomization function), all using the array visualizer for its basic operations and with calls to its annotation methods; - and a ``driver'' class which can be used as a Grail applet or as a stand-alone application. i(t*(tLinet RectangleNi itArraycBseZddZdZdZdZdZdZdZ dZ dZ dZ d Z d Zd Zd Zd ZdZdZdZdZdZdZdZdZdZdZdZdZdZRS(cCs||_t|j|_|jjdtt|j|_|jjt|j|_|jjt|j|_ |j jt |jdddd|_ t |jdddd|_ t |jdddd|_ g|_d|_|_|r|j|ndS(Ntfilli(tmastertFrametframetpacktXtLabeltlabeltCanvastcanvastreportRtlefttrighttpivottitemstsizetmaxvaluetsetdata(tselfRtdata((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyt__init__"s      cCs|j}g|_x|D]}|jqWt||_t||_|jjd|jdtd|jdt x7t |jD]&}|jj t ||||qW|j d|jdS(NtwidthitheightsSort demo, size %d(RtdeletetlenRtmaxRR tconfigtXGRIDtYGRIDtrangetappendt ArrayItemtreset(RRtolditemstitemti((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyR4s   $tnormalcCs ||_dS(N(tspeed(RR)((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pytsetspeedCscCs|jjdS(N(Rtdestroy(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyR+FsicCs&d|_|jr"|jjndS(Ni(t stop_mainloopt in_mainloopRtquit(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pytcancelLs  cCs|jr|jjndS(N(R-RR.(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pytstepQs sArray.CancelledcCs|jdkrd}n4|jdkr4|d}n|jdkrLd}n|js|jj|jj||jj}d|_|jj|jj|d|_n|jrd|_|j dt j ndS( Ntfastestitfasti s single-stepiʚ;it Cancelled( R)R,RtupdatetafterR.R-tmainloopt after_canceltmessageRR3(Rtmsecstid((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pytwaitWs"           cCs|jS(N(R(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pytgetsizejscCszxit|jD]X}|j|}||ko:|knrU|jjddq|jjddqW|jdS(NRtredtorange(R!RRR&Rthide_left_right_pivot(RtfirsttlastR'R&((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pytshow_partitionms  cCsHx7t|jD]&}|j|}|jjddqW|jdS(NRR=(R!RRR&RR?(RR'R&((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pythide_partitionvs cCsd|ko|jkns-|jdS|j|j\}}}}|jj|ddf|ddfg|jjdS(Niii'(Rt hide_leftRtpositionRtcoordsRR4(RRtx1ty1tx2ty2((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyt show_left|s  *cCsd|ko|jkns-|jdS|j|j\}}}}|jj|ddf|ddff|jjdS(Niii'(Rt hide_rightRRERRFRR4(RRRGRHRIRJ((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyt show_rights  *cCs"|j|j|jdS(N(RDRLt hide_pivot(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyR?s  cCs|jjddfdS(Ni(ii(ii(RRF(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRDscCs|jjddfdS(Ni(ii(ii(RRF(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRLscCsM|j|j\}}}}|jjd|dfd|dffdS(Niii'(RRERRF(RRRGRHRIRJ((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyt show_pivotscCs|jjddfdS(Ni(ii(ii(RRF(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRNscCs`||krdS|j|j|}|j|}|||j|<|j|<|j|dS(N(t countswapRtswapwith(RR'tjR&tother((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pytswaps    cCs1|j|j|}|j|}|j|S(N(t countcompareRt compareto(RR'RRR&RS((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pytcompares   cCs7d|_d|_|j||j|jdS(Ni(t ncomparestnswapsR8t updatereportRC(Rtmsg((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyR$s     cCs|jjd|dS(Nttext(R R(RR[((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyR8scCs|jd|_|jdS(Ni(RYRZ(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRPscCs|jd|_|jdS(Ni(RXRZ(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRUscCs-d|j|jf}|jjd|dS(Ns%d cmps, %d swapsR\(RXRYRR(RR\((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRZsN(t__name__t __module__tNoneRRR)R*R+R-R,R/R0R3R;R<RBRCRKRMR?RDRLRORNRTRWR$R8RPRURZ(((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyR s8                     R#cBsbeZdZdZdZdZdZdZdZdZ dZ d Z RS( c Cs||_||_||_|j\}}}}t|j||||dddddd|_|jjd|j|jjd|j |jjd |j dS( NRR=toutlinetblackRis ss( tarraytindextvalueRERR R&tbindt mouse_downt mouse_movetmouse_up(RRbRcRdRGRHRIRJ((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRs   cCs)|j}d|_d|_|jdS(N(R&R_RbR(RR&((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRs   cCsA|j|_|j|_|j|_|j|_|jjdS(N(txtlastxtytlastytorigxtorigyR&ttkraise(Rtevent((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRfs     cCsC|jj|j|j|j|j|j|_|j|_dS(N(R&tmoveRiRjRkRl(RRp((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRgs' c Cs|j|j}||jjkr=|jjd}n|dkrRd}n|jj|}|j}|||jj|<|jj|<||_|j\}}}}|jj||f||ff|j |dS(Nii( t nearestindexRiRbR<RRcRER&RFtsetindex( RRpR'RSthereRGRHRIRJ((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRhs   ! "cCst|j|}|sdS|jjdkr7d}n|j}||_|j}t|||}|jjx<|D]4}|jj|d |df|jj dq~WdS(NR1iii2( tstepsRcRbR)REt interpolateR&RoRFR;(RRctnstepstoldptstnewptst trajectorytpts((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRss      cCst|j|j}|sdS|jjdkr:d}n|j}|j}|j|j|_|_|j}|j}|jd}|jd}|jjdd|jjdd|jjj|jjdkrk|jj |d |df|jj |d |df|jjj|jjd||jjd||jj ddSt |||} t |||} |j |j kr|jj |jj n|jj |jj zxztt| D]f} | | } | | } |jj | d | df|jj | d | df|jj dqWWd| d } | d } |jj | d | df|jj | d | df|jjd||jjd|XdS( NR1iRtgreentyellows single-stepii2i(RuRcRbR)RER&RRR4RFR;RvRdRoR!R(RRSRwtmyoldptst otheroldptstmynewptst othernewptstmyfillt otherfillt mytrajectorytothertrajectoryR'tmyptstotherpts((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRQsV              cCs|jd}|jd}t|j|j}|dkrJd}d}n%|dkred}d}n d}}z:|jjd||jjd||jjdWd|jjd||jjd|X|S(NRitwhiteRatgreyi(R&tcmpRdRRbR;(RRSRRtoutcometmyflasht otherflash((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRV-s"       cCsX|jdttd}|t}|jjdt}||jt}||||fS(Nii(RcRtWIDTHRbRR Rd(RRGRIRJRH((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyREBs  cCsttt|tdS(Ni(tinttroundtfloatR(RRi((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRrIs( R]R^RRRfRgRhRsRQRVRERr(((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyR#s      .  cCs[t||}|dkr)|d}n.|dkrB|d}n|dkrWd}n|S(Niiii (tabs(RttthereRw((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRuOs      cCst|t|kr$tdndgt|}t|g}xmtd|D]\}x@tt|D],}|||||||||||j || fn| dkr.|j | |fq.q.W|jdWd|j XdS(Nt QuicksortiiisInsertion sortisChoosing pivotisPivot at left of partitionisSweep right pointersSweep left pointersEnd of partitions Swap itemssSwap pivot backR( R<R$RBR8R!RWRTROR;RMRKR"RC( RbRtstackR@RAR'RRRRRRtn1tn2((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyt quicksortsx             '    '         cCs<x5x.ttttgD]}t|||qWqWdS(N(RRRRR(Rbtalg((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pytdemosorts tSortDemocBseZddZdZdZdZdZdZdZdZ d Z d Z d Z d Z d ZdZRS(icCs||_||_d|_t|j|_t||_|jjdtt|j|_ |j jdt dt t|j|_ |j jdt dt t|j ddd|j|_|jjdtt|j ddd|j|_|jjdtt|j ddd|j|_|jjdtt|j dd d|j|_|jjdtd tfd Y}||j||_|jj|d d ddgtddd}|j|kr|j|j|jntt|j |jft ||_!|j!jdtt"|j|_#|j#jdt|j |j#dddd|_$|j$jdtt|j ddd|j%|_&|j&jdtt|j ddd|j'|_(|j(jdtt|j ddd|j)|_*|j*jdtt|j ddd|j+|_,|j,jdtt|j ddd|j-|_.|j.jdtt|j ddd|j/|_0|j0jdt|j0j1dt2t|j ddd|j3|_4|j4jdtdS(NitsideRR\RtcommandsInsertion sortsSelection sorts Bubble sorttMyIntVarcBseZdZdZRS(cSs||_tj||dS(N(tdemotIntVarR(RRR((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRs cSs9tj||t|dkr5|jj|ndS(Nt0(RtsettstrRtresize(RRd((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRs(R]R^RR(((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRs iiiiii7R(s single-stepR2R1tStept RandomizetUniformtDistincttDemotCanceltstatetQuit(5RRtbusyRRbRtbotframeRtBOTTOMt botleftframetLEFTtYt botrightframetRIGHTtButtontc_qsorttb_qsortR tc_isorttb_isorttc_ssorttb_ssorttc_bsorttb_bsortRtv_sizeRR!R"tsorttapplyt OptionMenuRtm_sizet StringVartv_speedtm_speedtc_steptb_stept c_randomizet b_randomizet c_uniformt b_uniformt c_distinctt b_distincttc_demotb_demotc_canceltb_cancelRtDISABLEDtc_quittb_quit(RRRRtsizes((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRsv        " "       cCsG|jr|jjdS||_|jjtd|jddS(Ni(RRtbellRRbRR!(Rtnewsize((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyR0s    cCs|jtdS(N(trunR(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyR7scCs|jtdS(N(RR(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyR:scCs|jtdS(N(RR(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyR=scCs|jtdS(N(RR(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyR@scCs|jtdS(N(RR(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRCscCs|jtdS(N(RR(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRFscCs|jtdS(N(RR(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRIscCs|jtdS(N(RR(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRLscCs|jr|jjdSd|_|jj|jj|jjdt y||jWnt j k rvnX|jjdt d|_dS(NiRi( RRRRbR*RtgetRRtNORMALRR3R(Rtfunc((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyROs   cCs+|js|jjdS|jjdS(N(RRRRbR/(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyR]s  cCsK|js|jjdS|jjd|jjd|jjdS(Ns single-step(RRRRRRbR*R0(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRcs   cCs3|jr|jjn|jj|jjdS(N(RRbR/Rt after_idleR.(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRks (R]R^RRRRRRRRRRRRRR(((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRs L            cCs6t}t|}|jd|j|jdS(NtWM_DELETE_WINDOW(tTkRtprotocolRR6(trootR((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pytmainss  t__main__((((t__doc__tTkinterR RRRRR RRR#RuRvRRRRRRRRRRR](((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyts,       =   PK%L]X##tkinter/guido/tkman.pyonu[ Afc@sddlZddlZddlZddlZddlTddlmZddgZddgZdZx/eD]'Z ej j e roe Z d ZqoqoWdZ x/eD]'Z ej j e re Zd Z qqWe se r\ejjd esd ejdZejjd ene sLd ejdZejjd enejd n[[ dZdddYZdZedS(iN(t*(tManPages/depot/sundry/man/manns/usr/local/man/manns/depot/sundry/man/man3s/usr/local/man/man3iis sgFailed to find mann directory. Please add the correct entry to the MANNDIRLIST at the top of %s script.s%s sgFailed to find man3 directory. Please add the correct entry to the MAN3DIRLIST at the top of %s script.cCsktj|}g}xE|D]=}|dd!dkr|ddkr|j|d qqW|j|S(Niit.t ln123456789(tostlistdirtappendtsort(tmandirtfilestnamestfile((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pyt listmanpages0s # t SelectionBoxcBseZddZdZdZdZdZdZdZ dZ dZ d Z d Z d Zd Zd ZRS(cCsg|_t|dd|_|jjdddt|jj|_t|jdd|_|jjdddtt|jdd|_|jjd tdddtt|jdd |_ |j jd t dddtt ||_ t |j dd d d dtdd|_|jjd tt|jdd|_|jjdddtd|j d|j|jjdddtd|j d|j|j|jds s(6tchoicestFrameRtpacktBOTHtmasterRRtLEFTRtRIGHTt StringVart chaptervart MenubuttontRAISEDRtTOPtMenuRtadd_radiobuttontMAN3DIRt newchaptertMANNDIRtListboxtSUNKENR!tButtontentry_cbR$tEntryR%tXR&tNONEt search_cbR't BooleanVartcasevart CheckbuttontFLATR(R)tLabelR*tBOTTOMRRtbindt listbox_cbt entry_tabt search_tabttext_tabt focus_settset(tselfR2((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pyt__init__;s                    cCs/|jj}g|_|jt|dS(N(R6tgetR.taddlistR (RTR((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pyR=s cCs=||jkr/|jj||jjn|jdS(N(R.RRtupdate(RTtchoice((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pyt addchoicescCs1||jt|j)|jj|jdS(N(R.tlenRRX(RTtlist((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pyRWs cGs|jdS(N(RX(RTte((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pyRBscCsQ|jj}|rMt|dkrM|jj|d}|j|ndS(Nii(R!t curselectionR[RVt show_page(RTR]t selectionR((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pyRNscGs|j|jjdS(N(t search_stringR)RV(RTR]((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pyRFscCs|jjdS(N(R)RR(RTR]((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pyROscCs|jjdS(N(R%RR(RTR]((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pyRPscCs|jjdS(N(R%RR(RTR]((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pyRQscCs|jj}t|t|d|j}|sF|jjn|jjdt d}x9|D]1}||krd}n|jj t |qiW|r|S|jj }|dkr|jjdSdS(NcSs|| |kS(N((Rtkeytn((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pyttii( R%RVtfilterR[R.RtbellR!tdeletetAtEndtinserttsize(RTRbtokt exactmatchtitemRc((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pyt updatelists     cCsF|j}|rB|j||jjdt|jndS(Ni(RoR_R%RhRi(RTR((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pyRXs   cCs]d|jj|f}tjd|d}|jj||jd<|jj|dS(Ns%s/%s.?snroff -man %s | ul -itrR(R6RVRtpopenRtkillR*t parsefile(RTRR tfp((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pyR_s   cCs`|s|jjdGHdS|jjs7tj}nd}y.|r[tj||}ntj|}Wn-tjk r}|jjdG|GHdSX|j j t }t j |t j|d }|j j t}t j |t j|d }|} d} x4|d}||krM| dkr8Pn| }d}d} n|j jd|d|} |j| } | dkrd} tdt|jd} y |j jdttWntk rnX|j jdd || fd || | f|j jt d || f|j jt PqqW| s\|jjndS( NsEmpty search strings Regex error:Riis%d.0 linestarts %d.0 lineendtsels%d.%d(RRgRHRVtret IGNORECASEtNonetcompileterrorRtindextAtInserttstringtatoitfindRiR)tmaxR[tgroupt tag_removet AtSelFirstt AtSelLasttTclErrorttag_addtmark_settyview_pickplace(RTR)tmaptprogtmsgtheretlinenotendt endlinenot wraplinenotfoundtlinetiRc((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pyRasd              N(t__name__t __module__RxRUR=RZRWRBRNRFRORPRQRoRXR_Ra(((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pyR 9s M            cCsWt}t|}tjdr9|jtjdn|jdd|jdS(Ni(tTkR tsystargvR_tminsizetmainloop(troottsb((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pytmains    ((RRR}RvtTkinterRt MANNDIRLISTt MAN3DIRLISTt foundmanndirtdirtpathtexistsR>t foundman3dirR<tstderrtwriteRRtexitR R R(((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pytsD             PK%L]kK\\tkinter/guido/sortvisu.pyonu[ Afc@sdZddlTddlmZmZddlZdZdZdZdddYZ d dd YZ d Z d Z d Z dZdZdZdZdZdZdZdddYZdZedkrendS(sjSorting algorithms visualizer using Tkinter. This module is comprised of three ``components'': - an array visualizer with methods that implement basic sorting operations (compare, swap) as well as methods for ``annotating'' the sorting algorithm (e.g. to show the pivot element); - a number of sorting algorithms (currently quicksort, insertion sort, selection sort and bubble sort, as well as a randomization function), all using the array visualizer for its basic operations and with calls to its annotation methods; - and a ``driver'' class which can be used as a Grail applet or as a stand-alone application. i(t*(tLinet RectangleNi itArraycBseZddZdZdZdZdZdZdZ dZ dZ dZ d Z d Zd Zd Zd ZdZdZdZdZdZdZdZdZdZdZdZdZdZRS(cCs||_t|j|_|jjdtt|j|_|jjt|j|_|jjt|j|_ |j jt |jdddd|_ t |jdddd|_ t |jdddd|_ g|_d|_|_|r|j|ndS(Ntfilli(tmastertFrametframetpacktXtLabeltlabeltCanvastcanvastreportRtlefttrighttpivottitemstsizetmaxvaluetsetdata(tselfRtdata((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyt__init__"s      cCs|j}g|_x|D]}|jqWt||_t||_|jjd|jdtd|jdt x7t |jD]&}|jj t ||||qW|j d|jdS(NtwidthitheightsSort demo, size %d(RtdeletetlenRtmaxRR tconfigtXGRIDtYGRIDtrangetappendt ArrayItemtreset(RRtolditemstitemti((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyR4s   $tnormalcCs ||_dS(N(tspeed(RR)((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pytsetspeedCscCs|jjdS(N(Rtdestroy(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyR+FsicCs&d|_|jr"|jjndS(Ni(t stop_mainloopt in_mainloopRtquit(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pytcancelLs  cCs|jr|jjndS(N(R-RR.(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pytstepQs sArray.CancelledcCs|jdkrd}n4|jdkr4|d}n|jdkrLd}n|js|jj|jj||jj}d|_|jj|jj|d|_n|jrd|_|j dt j ndS( Ntfastestitfasti s single-stepiʚ;it Cancelled( R)R,RtupdatetafterR.R-tmainloopt after_canceltmessageRR3(Rtmsecstid((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pytwaitWs"           cCs|jS(N(R(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pytgetsizejscCszxit|jD]X}|j|}||ko:|knrU|jjddq|jjddqW|jdS(NRtredtorange(R!RRR&Rthide_left_right_pivot(RtfirsttlastR'R&((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pytshow_partitionms  cCsHx7t|jD]&}|j|}|jjddqW|jdS(NRR=(R!RRR&RR?(RR'R&((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pythide_partitionvs cCsd|ko|jkns-|jdS|j|j\}}}}|jj|ddf|ddfg|jjdS(Niii'(Rt hide_leftRtpositionRtcoordsRR4(RRtx1ty1tx2ty2((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyt show_left|s  *cCsd|ko|jkns-|jdS|j|j\}}}}|jj|ddf|ddff|jjdS(Niii'(Rt hide_rightRRERRFRR4(RRRGRHRIRJ((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyt show_rights  *cCs"|j|j|jdS(N(RDRLt hide_pivot(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyR?s  cCs|jjddfdS(Ni(ii(ii(RRF(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRDscCs|jjddfdS(Ni(ii(ii(RRF(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRLscCsM|j|j\}}}}|jjd|dfd|dffdS(Niii'(RRERRF(RRRGRHRIRJ((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyt show_pivotscCs|jjddfdS(Ni(ii(ii(RRF(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRNscCs`||krdS|j|j|}|j|}|||j|<|j|<|j|dS(N(t countswapRtswapwith(RR'tjR&tother((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pytswaps    cCs1|j|j|}|j|}|j|S(N(t countcompareRt compareto(RR'RRR&RS((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pytcompares   cCs7d|_d|_|j||j|jdS(Ni(t ncomparestnswapsR8t updatereportRC(Rtmsg((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyR$s     cCs|jjd|dS(Nttext(R R(RR[((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyR8scCs|jd|_|jdS(Ni(RYRZ(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRPscCs|jd|_|jdS(Ni(RXRZ(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRUscCs-d|j|jf}|jjd|dS(Ns%d cmps, %d swapsR\(RXRYRR(RR\((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRZsN(t__name__t __module__tNoneRRR)R*R+R-R,R/R0R3R;R<RBRCRKRMR?RDRLRORNRTRWR$R8RPRURZ(((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyR s8                     R#cBsbeZdZdZdZdZdZdZdZdZ dZ d Z RS( c Cs||_||_||_|j\}}}}t|j||||dddddd|_|jjd|j|jjd|j |jjd |j dS( NRR=toutlinetblackRis ss( tarraytindextvalueRERR R&tbindt mouse_downt mouse_movetmouse_up(RRbRcRdRGRHRIRJ((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRs   cCs)|j}d|_d|_|jdS(N(R&R_RbR(RR&((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRs   cCsA|j|_|j|_|j|_|j|_|jjdS(N(txtlastxtytlastytorigxtorigyR&ttkraise(Rtevent((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRfs     cCsC|jj|j|j|j|j|j|_|j|_dS(N(R&tmoveRiRjRkRl(RRp((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRgs' c Cs|j|j}||jjkr=|jjd}n|dkrRd}n|jj|}|j}|||jj|<|jj|<||_|j\}}}}|jj||f||ff|j |dS(Nii( t nearestindexRiRbR<RRcRER&RFtsetindex( RRpR'RSthereRGRHRIRJ((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRhs   ! "cCst|j|}|sdS|jjdkr7d}n|j}||_|j}t|||}|jjx<|D]4}|jj|d |df|jj dq~WdS(NR1iii2( tstepsRcRbR)REt interpolateR&RoRFR;(RRctnstepstoldptstnewptst trajectorytpts((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRss      cCst|j|j}|sdS|jjdkr:d}n|j}|j}|j|j|_|_|j}|j}|jd}|jd}|jjdd|jjdd|jjj|jjdkrk|jj |d |df|jj |d |df|jjj|jjd||jjd||jj ddSt |||} t |||} |j |j kr|jj |jj n|jj |jj zxztt| D]f} | | } | | } |jj | d | df|jj | d | df|jj dqWWd| d } | d } |jj | d | df|jj | d | df|jjd||jjd|XdS( NR1iRtgreentyellows single-stepii2i(RuRcRbR)RER&RRR4RFR;RvRdRoR!R(RRSRwtmyoldptst otheroldptstmynewptst othernewptstmyfillt otherfillt mytrajectorytothertrajectoryR'tmyptstotherpts((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRQsV              cCs|jd}|jd}t|j|j}|dkrJd}d}n%|dkred}d}n d}}z:|jjd||jjd||jjdWd|jjd||jjd|X|S(NRitwhiteRatgreyi(R&tcmpRdRRbR;(RRSRRtoutcometmyflasht otherflash((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRV-s"       cCsX|jdttd}|t}|jjdt}||jt}||||fS(Nii(RcRtWIDTHRbRR Rd(RRGRIRJRH((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyREBs  cCsttt|tdS(Ni(tinttroundtfloatR(RRi((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRrIs( R]R^RRRfRgRhRsRQRVRERr(((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyR#s      .  cCs[t||}|dkr)|d}n.|dkrB|d}n|dkrWd}n|S(Niiii (tabs(RttthereRw((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRuOs      cCst|t|kr$tdndgt|}t|g}xmtd|D]\}x@tt|D],}|||||||||||j || fn| dkr.|j | |fq.q.W|jdWd|j XdS(Nt QuicksortiiisInsertion sortisChoosing pivotisPivot at left of partitionisSweep right pointersSweep left pointersEnd of partitions Swap itemssSwap pivot backR( R<R$RBR8R!RWRTROR;RMRKR"RC( RbRtstackR@RAR'RRRRRRtn1tn2((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyt quicksortsx             '    '         cCs<x5x.ttttgD]}t|||qWqWdS(N(RRRRR(Rbtalg((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pytdemosorts tSortDemocBseZddZdZdZdZdZdZdZdZ d Z d Z d Z d Z d ZdZRS(icCs||_||_d|_t|j|_t||_|jjdtt|j|_ |j jdt dt t|j|_ |j jdt dt t|j ddd|j|_|jjdtt|j ddd|j|_|jjdtt|j ddd|j|_|jjdtt|j dd d|j|_|jjdtd tfd Y}||j||_|jj|d d ddgtddd}|j|kr|j|j|jntt|j |jft ||_!|j!jdtt"|j|_#|j#jdt|j |j#dddd|_$|j$jdtt|j ddd|j%|_&|j&jdtt|j ddd|j'|_(|j(jdtt|j ddd|j)|_*|j*jdtt|j ddd|j+|_,|j,jdtt|j ddd|j-|_.|j.jdtt|j ddd|j/|_0|j0jdt|j0j1dt2t|j ddd|j3|_4|j4jdtdS(NitsideRR\RtcommandsInsertion sortsSelection sorts Bubble sorttMyIntVarcBseZdZdZRS(cSs||_tj||dS(N(tdemotIntVarR(RRR((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRs cSs9tj||t|dkr5|jj|ndS(Nt0(RtsettstrRtresize(RRd((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRs(R]R^RR(((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRs iiiiii7R(s single-stepR2R1tStept RandomizetUniformtDistincttDemotCanceltstatetQuit(5RRtbusyRRbRtbotframeRtBOTTOMt botleftframetLEFTtYt botrightframetRIGHTtButtontc_qsorttb_qsortR tc_isorttb_isorttc_ssorttb_ssorttc_bsorttb_bsortRtv_sizeRR!R"tsorttapplyt OptionMenuRtm_sizet StringVartv_speedtm_speedtc_steptb_stept c_randomizet b_randomizet c_uniformt b_uniformt c_distinctt b_distincttc_demotb_demotc_canceltb_cancelRtDISABLEDtc_quittb_quit(RRRRtsizes((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRsv        " "       cCsG|jr|jjdS||_|jjtd|jddS(Ni(RRtbellRRbRR!(Rtnewsize((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyR0s    cCs|jtdS(N(trunR(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyR7scCs|jtdS(N(RR(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyR:scCs|jtdS(N(RR(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyR=scCs|jtdS(N(RR(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyR@scCs|jtdS(N(RR(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRCscCs|jtdS(N(RR(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRFscCs|jtdS(N(RR(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRIscCs|jtdS(N(RR(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRLscCs|jr|jjdSd|_|jj|jj|jjdt y||jWnt j k rvnX|jjdt d|_dS(NiRi( RRRRbR*RtgetRRtNORMALRR3R(Rtfunc((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyROs   cCs+|js|jjdS|jjdS(N(RRRRbR/(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyR]s  cCsK|js|jjdS|jjd|jjd|jjdS(Ns single-step(RRRRRRbR*R0(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRcs   cCs3|jr|jjn|jj|jjdS(N(RRbR/Rt after_idleR.(R((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRks (R]R^RRRRRRRRRRRRRR(((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyRs L            cCs6t}t|}|jd|j|jdS(NtWM_DELETE_WINDOW(tTkRtprotocolRR6(trootR((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pytmainss  t__main__((((t__doc__tTkinterR RRRRR RRR#RuRvRRRRRRRRRRR](((s3/usr/lib64/python2.7/Demo/tkinter/guido/sortvisu.pyts,       =   PK%L],))tkinter/guido/canvasevents.pyonu[ Afc@sddlTddlmZmZmZdefdYZdddYZdefdYZd dd YZd efd YZd efdYZ de fdYZ dddYZ dZ e dkre ndS(i(t*(tOvaltGroupt CanvasTextRcBseZdddZRS(cCs|jj|j||S(N(tcanvasttag_bindtid(tselftsequencetcommand((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pytbind sN(t__name__t __module__tNoneR (((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR stObjectcBsYeZdZdddddZdZdZdZdZd Zd Z RS( sBase class for composite graphical objects. Objects belong to a canvas, and can be moved around on the canvas. They also belong to at most one ``pile'' of objects, and can be transferred between piles (or removed from their pile). Objects have a canonical ``x, y'' position which is moved when the object is moved. Where the object is relative to this position depends on the object; for simple objects, it may be their center. Objects have mouse sensitivity. They can be clicked, dragged and double-clicked. The behavior may actually be determined by the pile they are in. All instance attributes are public since the derived class may need them. itredtobjectcCsJ||_||_||_d|_t|j|_|j||dS(N(RtxtyR tpileRtgroupt createitems(RRRRtfillttext((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyt__init__#s     cCs t|jS(N(tstrR(R((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyt__str__+sc Cst|j|jd|jd|jd|jdd|dd|_|jj|jt|j|j|jd||_|jj|jdS(Nii RtwidthiR( RRRRt _Object__ovalRtaddtag_withtagRt _Object__text(RRR((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR.s + cCsW||kodknr dS|jj|||j||_|j||_dS(Ni(RtmoveRR(Rtdxtdy((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pytmoveby7s cCs"|j||j||jdS(N(R"RR(RRR((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pytmoveto>scCsN|jr%|jj|d|_n||_|jrJ|jj|ndS(N(RtdeleteR tadd(RR((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyttransferAs     cCs|jjdS(N(Rttkraise(R((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR'Is( R R t__doc__RRRR"R#R&R'(((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyRs    tBottomcBseZdZdZRS(s+An object to serve as the bottom of a pile.c Gs]t|j|jd|jd|jd|jddddd|_|jj|jdS(Nii Rtgraytoutlinet(RRRRt _Bottom__ovalRR(Rtargs((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyRQs +(R R R(R(((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR)MstPilecBsPeZdZddZdZdZdZdZdZ dZ RS( sA group of graphical objects.cCs~||_||_||_g|_t|j|j|j|_t|jd||_|jj|jj|j dS(Nttag( RRRtobjectsR)tbottomRRRt bindhandlers(RRRRR0((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR\s    cCs0|jjd|j|jjd|jdS(Ns<1>s (RR t clickhandlertdoubleclickhandler(R((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR3fscCs4|jj||jj|j|j|dS(N(R1tappendRRtposition(RR((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR%jscCs'|jj|j|jj|dS(N(RtdtagR1tremove(RR((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR$oscCsF|j|jj|}|j|j|d|j|ddS(Nii(R'R1tindexR#RR(RRti((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR7ss cCsdS(N((Rtevent((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR4xscCsdS(N((RR<((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR5{sN( R R R(R RR3R%R$R7R4R5(((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR/Xs     t MovingPilecBsAeZdZdZdZeZdZdZdZ RS(cCs=tj||jjd|j|jjd|jdS(Ns s(R/R3RR t motionhandlertreleasehandler(R((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR3s cCs|jjd}xMtt|jD])}|j|}|jj|kr(Pq(q(Wd|_dS|j||_x|jD]}|j q|W|j |_ |j |_ dS(Ntcurrent(RtgettagstrangetlenR1RR0R tmovethisR'RtlastxRtlasty(RR<ttagsR;to((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR4s   cCsm|js dS|j|j}|j|j}|j|_|j|_x!|jD]}|j||qOWdS(N(RDRRERRFR"(RR<R R!RH((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR>s   cCs-|j}|sdSd|_|j|dS(N(RDR t finishmove(RR<R1((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR?s   cCs"x|D]}|j|qWdS(N(R7(RR1RH((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyRIs N( R R R3R RDR4R5R>R?RI(((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR=s   tPile1cBs>eZdZdZdZdZdZdZdZRS(i2tp1cCs5||_tj||jj|j|j|jdS(N(tdemoR=RRRRR0(RRL((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyRs cCsMy|jd}Wntk r%dSX|j|jtj||dS(Ni(R1t IndexErrorR&totherR=R5(RR<RH((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR5s  cCs |jjS(N(RLtp2(R((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyRNscCs|d}|j}|j|j}}||jd||jd||jd||jdkrx.|D]}|j|qpWntj||dS(Nii(RNRRR&R=RI(RR1RHtpRR((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyRIs  @ ( R R RRR0RR5RNRI(((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyRJs   tPile2cBs#eZdZdZdZdZRS(ii2ROcCs |jjS(N(RLRK(R((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyRNs(R R RRR0RN(((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyRQstDemocBseZdZRS(c Cs||_t|dddddddtdd|_|jjd d d tt||_t||_ t |jd d d d}t |jd dd d}t |jd dd d}|j |j|j |j|j |j dS(NRitheightt backgroundtyellowtrelieft borderwidthitexpandiRRRto1tgreento2s light blueto3( tmastertCanvastSUNKENRtpacktBOTHRJRKRQRORR&(RR]RYR[R\((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyRs   (R R R(((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyRRscCs6t}t|}|jd|j|jdS(NtWM_DELETE_WINDOW(tTkRRtprotocoltquittmainloop(trootRL((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pytmains  t__main__N((((tTkinterR^RRRRR)R/R=RJRQRRRhR (((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyts ? '0   PK%L].55tkinter/guido/svkill.pyonu[ Afc@sddlTedkr"ednddlmZddlmZddlZddlZejdZ de fd YZ d e fd YZ ed kre dd dZejjdejjddejndS(i(t*g@s/This version of svkill requires Tk 4.0 or later(t splitfields(tsplitNtLOGNAMEt BarButtoncBseZddZRS(cKsOttj||f||jdtt|dd|_|j|dss<1>(0RtFrameR R tBOTHtRAISEDR;tXRtfileRt add_commandtquitR"RtIntVarR&trangetlenR!tadd_radiobuttonRRt tk_menuBarR't StringVarR%tLabeltFLATtNWR@tYtWt ScrollbartVERTICALtvscrolltListboxtSUNKENtBROWSER(tyviewtRIGHTtButtontupdatetbindR6R7R8(RRRtnumR@toptiontcol((s1/usr/lib64/python2.7/Demo/tkinter/guido/svkill.pyR ?sv           (RR(s Every (-e)s-e(sNon process group leaders (-d)s-d(sNon leaders with tty (-a)s-a(RRi(s Long (-l)s-li(s Full (-f)s-fi(sFull Long (-f -l)s-l -fi(sSession and group ID (-j)s-ji(sScheduler properties (-c)s-ciN( RRtuserR!RR RR6R7R8RR (((s1/usr/lib64/python2.7/Demo/tkinter/guido/svkill.pyRs"     t__main__R=isTkinter Process Killer (SYSV)i(tTkintert TkVersiont ImportErrortstringRRR#RtenvironRrR RRRRRRR twinfo_toplevelttitletminsizetmainloop(((s1/usr/lib64/python2.7/Demo/tkinter/guido/svkill.pyts      d PK%L]k>'tkinter/guido/hello.pyonu[ ^c@s3ddlZddlTdZdZedS(iN(t*cCsAt}t|}d|ds    PK%L],))tkinter/guido/canvasevents.pycnu[ Afc@sddlTddlmZmZmZdefdYZdddYZdefdYZd dd YZd efd YZd efdYZ de fdYZ dddYZ dZ e dkre ndS(i(t*(tOvaltGroupt CanvasTextRcBseZdddZRS(cCs|jj|j||S(N(tcanvasttag_bindtid(tselftsequencetcommand((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pytbind sN(t__name__t __module__tNoneR (((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR stObjectcBsYeZdZdddddZdZdZdZdZd Zd Z RS( sBase class for composite graphical objects. Objects belong to a canvas, and can be moved around on the canvas. They also belong to at most one ``pile'' of objects, and can be transferred between piles (or removed from their pile). Objects have a canonical ``x, y'' position which is moved when the object is moved. Where the object is relative to this position depends on the object; for simple objects, it may be their center. Objects have mouse sensitivity. They can be clicked, dragged and double-clicked. The behavior may actually be determined by the pile they are in. All instance attributes are public since the derived class may need them. itredtobjectcCsJ||_||_||_d|_t|j|_|j||dS(N(RtxtyR tpileRtgroupt createitems(RRRRtfillttext((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyt__init__#s     cCs t|jS(N(tstrR(R((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyt__str__+sc Cst|j|jd|jd|jd|jdd|dd|_|jj|jt|j|j|jd||_|jj|jdS(Nii RtwidthiR( RRRRt _Object__ovalRtaddtag_withtagRt _Object__text(RRR((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR.s + cCsW||kodknr dS|jj|||j||_|j||_dS(Ni(RtmoveRR(Rtdxtdy((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pytmoveby7s cCs"|j||j||jdS(N(R"RR(RRR((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pytmoveto>scCsN|jr%|jj|d|_n||_|jrJ|jj|ndS(N(RtdeleteR tadd(RR((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyttransferAs     cCs|jjdS(N(Rttkraise(R((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR'Is( R R t__doc__RRRR"R#R&R'(((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyRs    tBottomcBseZdZdZRS(s+An object to serve as the bottom of a pile.c Gs]t|j|jd|jd|jd|jddddd|_|jj|jdS(Nii Rtgraytoutlinet(RRRRt _Bottom__ovalRR(Rtargs((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyRQs +(R R R(R(((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR)MstPilecBsPeZdZddZdZdZdZdZdZ dZ RS( sA group of graphical objects.cCs~||_||_||_g|_t|j|j|j|_t|jd||_|jj|jj|j dS(Nttag( RRRtobjectsR)tbottomRRRt bindhandlers(RRRRR0((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR\s    cCs0|jjd|j|jjd|jdS(Ns<1>s (RR t clickhandlertdoubleclickhandler(R((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR3fscCs4|jj||jj|j|j|dS(N(R1tappendRRtposition(RR((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR%jscCs'|jj|j|jj|dS(N(RtdtagR1tremove(RR((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR$oscCsF|j|jj|}|j|j|d|j|ddS(Nii(R'R1tindexR#RR(RRti((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR7ss cCsdS(N((Rtevent((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR4xscCsdS(N((RR<((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR5{sN( R R R(R RR3R%R$R7R4R5(((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR/Xs     t MovingPilecBsAeZdZdZdZeZdZdZdZ RS(cCs=tj||jjd|j|jjd|jdS(Ns s(R/R3RR t motionhandlertreleasehandler(R((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR3s cCs|jjd}xMtt|jD])}|j|}|jj|kr(Pq(q(Wd|_dS|j||_x|jD]}|j q|W|j |_ |j |_ dS(Ntcurrent(RtgettagstrangetlenR1RR0R tmovethisR'RtlastxRtlasty(RR<ttagsR;to((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR4s   cCsm|js dS|j|j}|j|j}|j|_|j|_x!|jD]}|j||qOWdS(N(RDRRERRFR"(RR<R R!RH((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR>s   cCs-|j}|sdSd|_|j|dS(N(RDR t finishmove(RR<R1((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR?s   cCs"x|D]}|j|qWdS(N(R7(RR1RH((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyRIs N( R R R3R RDR4R5R>R?RI(((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR=s   tPile1cBs>eZdZdZdZdZdZdZdZRS(i2tp1cCs5||_tj||jj|j|j|jdS(N(tdemoR=RRRRR0(RRL((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyRs cCsMy|jd}Wntk r%dSX|j|jtj||dS(Ni(R1t IndexErrorR&totherR=R5(RR<RH((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyR5s  cCs |jjS(N(RLtp2(R((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyRNscCs|d}|j}|j|j}}||jd||jd||jd||jdkrx.|D]}|j|qpWntj||dS(Nii(RNRRR&R=RI(RR1RHtpRR((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyRIs  @ ( R R RRR0RR5RNRI(((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyRJs   tPile2cBs#eZdZdZdZdZRS(ii2ROcCs |jjS(N(RLRK(R((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyRNs(R R RRR0RN(((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyRQstDemocBseZdZRS(c Cs||_t|dddddddtdd|_|jjd d d tt||_t||_ t |jd d d d}t |jd dd d}t |jd dd d}|j |j|j |j|j |j dS(NRitheightt backgroundtyellowtrelieft borderwidthitexpandiRRRto1tgreento2s light blueto3( tmastertCanvastSUNKENRtpacktBOTHRJRKRQRORR&(RR]RYR[R\((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyRs   (R R R(((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyRRscCs6t}t|}|jd|j|jdS(NtWM_DELETE_WINDOW(tTkRRtprotocoltquittmainloop(trootRL((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pytmains  t__main__N((((tTkinterR^RRRRR)R/R=RJRQRRRhR (((s7/usr/lib64/python2.7/Demo/tkinter/guido/canvasevents.pyts ? '0   PK%L]Itkinter/guido/rmt.pynuȯ#! /usr/bin/python2.7 # A Python program implementing rmt, an application for remotely # controlling other Tk applications. # Cf. Ousterhout, Tcl and the Tk Toolkit, Figs. 27.5-8, pp. 273-276. # Note that because of forward references in the original, we # sometimes delay bindings until after the corresponding procedure is # defined. We also introduce names for some unnamed code blocks in # the original because of restrictions on lambda forms in Python. # XXX This should be written in a more Python-like style!!! from Tkinter import * import sys # 1. Create basic application structure: menu bar on top of # text widget, scrollbar on right. root = Tk() tk = root.tk mBar = Frame(root, relief=RAISED, borderwidth=2) mBar.pack(fill=X) f = Frame(root) f.pack(expand=1, fill=BOTH) s = Scrollbar(f, relief=FLAT) s.pack(side=RIGHT, fill=Y) t = Text(f, relief=RAISED, borderwidth=2, yscrollcommand=s.set, setgrid=1) t.pack(side=LEFT, fill=BOTH, expand=1) t.tag_config('bold', font='-Adobe-Courier-Bold-R-Normal-*-120-*') s['command'] = t.yview root.title('Tk Remote Controller') root.iconname('Tk Remote') # 2. Create menu button and menus. file = Menubutton(mBar, text='File', underline=0) file.pack(side=LEFT) file_m = Menu(file) file['menu'] = file_m file_m_apps = Menu(file_m, tearoff=0) file_m.add_cascade(label='Select Application', underline=0, menu=file_m_apps) file_m.add_command(label='Quit', underline=0, command=sys.exit) # 3. Create bindings for text widget to allow commands to be # entered and information to be selected. New characters # can only be added at the end of the text (can't ever move # insertion point). def single1(e): x = e.x y = e.y t.setvar('tk_priv(selectMode)', 'char') t.mark_set('anchor', At(x, y)) # Should focus W t.bind('<1>', single1) def double1(e): x = e.x y = e.y t.setvar('tk_priv(selectMode)', 'word') t.tk_textSelectTo(At(x, y)) t.bind('', double1) def triple1(e): x = e.x y = e.y t.setvar('tk_priv(selectMode)', 'line') t.tk_textSelectTo(At(x, y)) t.bind('', triple1) def returnkey(e): t.insert(AtInsert(), '\n') invoke() t.bind('', returnkey) def controlv(e): t.insert(AtInsert(), t.selection_get()) t.yview_pickplace(AtInsert()) if t.index(AtInsert())[-2:] == '.0': invoke() t.bind('', controlv) # 4. Procedure to backspace over one character, as long as # the character isn't part of the prompt. def backspace(e): if t.index('promptEnd') != t.index('insert - 1 char'): t.delete('insert - 1 char', AtInsert()) t.yview_pickplace(AtInsert()) t.bind('', backspace) t.bind('', backspace) t.bind('', backspace) # 5. Procedure that's invoked when return is typed: if # there's not yet a complete command (e.g. braces are open) # then do nothing. Otherwise, execute command (locally or # remotely), output the result or error message, and issue # a new prompt. def invoke(): cmd = t.get('promptEnd + 1 char', AtInsert()) if t.getboolean(tk.call('info', 'complete', cmd)): # XXX if app == root.winfo_name(): msg = tk.call('eval', cmd) # XXX else: msg = t.send(app, cmd) if msg: t.insert(AtInsert(), msg + '\n') prompt() t.yview_pickplace(AtInsert()) def prompt(): t.insert(AtInsert(), app + ': ') t.mark_set('promptEnd', 'insert - 1 char') t.tag_add('bold', 'insert linestart', 'promptEnd') # 6. Procedure to select a new application. Also changes # the prompt on the current command line to reflect the new # name. def newApp(appName): global app app = appName t.delete('promptEnd linestart', 'promptEnd') t.insert('promptEnd', appName + ':') t.tag_add('bold', 'promptEnd linestart', 'promptEnd') def fillAppsMenu(): file_m_apps.add('command') file_m_apps.delete(0, 'last') names = root.winfo_interps() names = list(names) names.sort() for name in names: try: root.send(name, 'winfo name .') except TclError: # Inoperative window -- ignore it pass else: file_m_apps.add_command( label=name, command=lambda name=name: newApp(name)) file_m_apps['postcommand'] = fillAppsMenu mBar.tk_menuBar(file) # 7. Miscellaneous initialization. app = root.winfo_name() prompt() t.focus() root.mainloop() PK%L]Vtkinter/guido/rmt.pyonu[ Afc @sddlTddlZeZejZeededdZejde eeZ e jddde e e de Zejd edeee deddd ejd dZejd ede ddejd d dejedcCs<|j}|j}tjddtjt||dS(Nstk_priv(selectMode)tword(RRRRttk_textSelectToR(RRR((s./usr/lib64/python2.7/Demo/tkinter/guido/rmt.pytdouble1=s  s cCs<|j}|j}tjddtjt||dS(Nstk_priv(selectMode)tline(RRRRRR(RRR((s./usr/lib64/python2.7/Demo/tkinter/guido/rmt.pyttriple1Ds  s cCstjtdtdS(Ns (RtinserttAtInserttinvoke(R((s./usr/lib64/python2.7/Demo/tkinter/guido/rmt.pyt returnkeyKsscCsStjttjtjttjtddkrOtndS(Nis.0(RR!R"t selection_gettyview_pickplacetindexR#(R((s./usr/lib64/python2.7/Demo/tkinter/guido/rmt.pytcontrolvPss cCsHtjdtjdkrDtjdttjtndS(Nt promptEndsinsert - 1 char(RR'tdeleteR"R&(R((s./usr/lib64/python2.7/Demo/tkinter/guido/rmt.pyt backspaceZss s scCstjdt}tjtjdd|rttjkrZtjd|}ntj t|}|rtj t|dnt ntj tdS(NspromptEnd + 1 chartinfotcompletetevals ( RtgetR"t getbooleanttktcalltapptroott winfo_nametsendR!tpromptR&(tcmdtmsg((s./usr/lib64/python2.7/Demo/tkinter/guido/rmt.pyR#is cCs>tjttdtjddtjddddS(Ns: R)sinsert - 1 charRsinsert linestart(RR!R"R3Rttag_add(((s./usr/lib64/python2.7/Demo/tkinter/guido/rmt.pyR7uscCsA|atjddtjd|dtjddddS(NspromptEnd linestartR)t:R(R3RR*R!R:(tappName((s./usr/lib64/python2.7/Demo/tkinter/guido/rmt.pytnewApp~scCstjdtjddtj}t|}|jxR|D]J}ytj|dWntk rsqFXtj d|d|dqFWdS(NR itlasts winfo name .RcSs t|S(N(R=(tname((s./usr/lib64/python2.7/Demo/tkinter/guido/rmt.pytt( t file_m_appstaddR*R4t winfo_interpstlisttsortR6tTclErrort add_command(tnamesR?((s./usr/lib64/python2.7/Demo/tkinter/guido/rmt.pyt fillAppsMenus       t postcommand(1tTkintertsystTkR4R1tFrametRAISEDtmBartpacktXtftBOTHt ScrollbartFLATtstRIGHTtYtTexttsetRtLEFTt tag_configtyviewttitleticonnamet MenubuttontfiletMenutfile_mRBt add_cascadeRHtexitRtbindRR R$R(R+R#R7R=RJt tk_menuBarR5R3tfocustmainloop(((s./usr/lib64/python2.7/Demo/tkinter/guido/rmt.pyts^     '                 PK%L]', self.do_motion) self.frame.list.bind('', self.do_leave) self.frame.list.bind('<1>', self.do_1) self.do_update() if __name__ == '__main__': kill = Kill(None, borderwidth=5) kill.winfo_toplevel().title('Tkinter Process Killer (SYSV)') kill.winfo_toplevel().minsize(1, 1) kill.mainloop() PK%L]|Dtkinter/guido/paint.pyonu[ ^c@s`dZddlTdad \aadZdZdZdZ e dkr\end S( sA"Paint program by Dave Michell. Subject: tkinter "paint" example From: Dave Mitchell To: python-list@cwi.nl Date: Fri, 23 Jan 1998 12:18:05 -0500 (EST) Not too long ago (last week maybe?) someone posted a request for an example of a paint program using Tkinter. Try as I might I can't seem to find it in the archive, so i'll just post mine here and hope that the person who requested it sees this! All this does is put up a canvas and draw a smooth black line whenever you have the mouse button down, but hopefully it will be enough to start with.. It would be easy enough to add some options like other shapes or colors... yours, dave mitchell davem@magnet.com i(t*tupcCs]t}t|}|j|jdt|jdt|jdt|jdS(Nsss(tTktCanvastpacktbindtmotiontb1downtb1uptmainloop(troott drawing_area((s0/usr/lib64/python2.7/Demo/tkinter/guido/paint.pytmains   cCs dadS(Ntdown(tb1(tevent((s0/usr/lib64/python2.7/Demo/tkinter/guido/paint.pyR'scCsdadadadS(NR(RtNonetxoldtyold(R((s0/usr/lib64/python2.7/Demo/tkinter/guido/paint.pyR,scCsetdkratdk rLtdk rL|jjtt|j|jdtn|ja|jandS(NR tsmooth( RRRRtwidgett create_linetxtytTRUE(R((s0/usr/lib64/python2.7/Demo/tkinter/guido/paint.pyR2s  ( t__main__N(NN( t__doc__tTkinterRRRRR RRRt__name__(((s0/usr/lib64/python2.7/Demo/tkinter/guido/paint.pyts     PK%L]X##tkinter/guido/tkman.pycnu[ Afc@sddlZddlZddlZddlZddlTddlmZddgZddgZdZx/eD]'Z ej j e roe Z d ZqoqoWdZ x/eD]'Z ej j e re Zd Z qqWe se r\ejjd esd ejdZejjd ene sLd ejdZejjd enejd n[[ dZdddYZdZedS(iN(t*(tManPages/depot/sundry/man/manns/usr/local/man/manns/depot/sundry/man/man3s/usr/local/man/man3iis sgFailed to find mann directory. Please add the correct entry to the MANNDIRLIST at the top of %s script.s%s sgFailed to find man3 directory. Please add the correct entry to the MAN3DIRLIST at the top of %s script.cCsktj|}g}xE|D]=}|dd!dkr|ddkr|j|d qqW|j|S(Niit.t ln123456789(tostlistdirtappendtsort(tmandirtfilestnamestfile((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pyt listmanpages0s # t SelectionBoxcBseZddZdZdZdZdZdZdZ dZ dZ d Z d Z d Zd Zd ZRS(cCsg|_t|dd|_|jjdddt|jj|_t|jdd|_|jjdddtt|jdd|_|jjd tdddtt|jdd |_ |j jd t dddtt ||_ t |j dd d d dtdd|_|jjd tt|jdd|_|jjdddtd|j d|j|jjdddtd|j d|j|j|jds s(6tchoicestFrameRtpacktBOTHtmasterRRtLEFTRtRIGHTt StringVart chaptervart MenubuttontRAISEDRtTOPtMenuRtadd_radiobuttontMAN3DIRt newchaptertMANNDIRtListboxtSUNKENR!tButtontentry_cbR$tEntryR%tXR&tNONEt search_cbR't BooleanVartcasevart CheckbuttontFLATR(R)tLabelR*tBOTTOMRRtbindt listbox_cbt entry_tabt search_tabttext_tabt focus_settset(tselfR2((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pyt__init__;s                    cCs/|jj}g|_|jt|dS(N(R6tgetR.taddlistR (RTR((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pyR=s cCs=||jkr/|jj||jjn|jdS(N(R.RRtupdate(RTtchoice((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pyt addchoicescCs1||jt|j)|jj|jdS(N(R.tlenRRX(RTtlist((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pyRWs cGs|jdS(N(RX(RTte((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pyRBscCsQ|jj}|rMt|dkrM|jj|d}|j|ndS(Nii(R!t curselectionR[RVt show_page(RTR]t selectionR((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pyRNscGs|j|jjdS(N(t search_stringR)RV(RTR]((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pyRFscCs|jjdS(N(R)RR(RTR]((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pyROscCs|jjdS(N(R%RR(RTR]((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pyRPscCs|jjdS(N(R%RR(RTR]((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pyRQscCs|jj}t|t|d|j}|sF|jjn|jjdt d}x9|D]1}||krd}n|jj t |qiW|r|S|jj }|dkr|jjdSdS(NcSs|| |kS(N((Rtkeytn((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pyttii( R%RVtfilterR[R.RtbellR!tdeletetAtEndtinserttsize(RTRbtokt exactmatchtitemRc((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pyt updatelists     cCsF|j}|rB|j||jjdt|jndS(Ni(RoR_R%RhRi(RTR((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pyRXs   cCs]d|jj|f}tjd|d}|jj||jd<|jj|dS(Ns%s/%s.?snroff -man %s | ul -itrR(R6RVRtpopenRtkillR*t parsefile(RTRR tfp((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pyR_s   cCs`|s|jjdGHdS|jjs7tj}nd}y.|r[tj||}ntj|}Wn-tjk r}|jjdG|GHdSX|j j t }t j |t j|d }|j j t}t j |t j|d }|} d} x4|d}||krM| dkr8Pn| }d}d} n|j jd|d|} |j| } | dkrd} tdt|jd} y |j jdttWntk rnX|j jdd || fd || | f|j jt d || f|j jt PqqW| s\|jjndS( NsEmpty search strings Regex error:Riis%d.0 linestarts %d.0 lineendtsels%d.%d(RRgRHRVtret IGNORECASEtNonetcompileterrorRtindextAtInserttstringtatoitfindRiR)tmaxR[tgroupt tag_removet AtSelFirstt AtSelLasttTclErrorttag_addtmark_settyview_pickplace(RTR)tmaptprogtmsgtheretlinenotendt endlinenot wraplinenotfoundtlinetiRc((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pyRasd              N(t__name__t __module__RxRUR=RZRWRBRNRFRORPRQRoRXR_Ra(((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pyR 9s M            cCsWt}t|}tjdr9|jtjdn|jdd|jdS(Ni(tTkR tsystargvR_tminsizetmainloop(troottsb((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pytmains    ((RRR}RvtTkinterRt MANNDIRLISTt MAN3DIRLISTt foundmanndirtdirtpathtexistsR>t foundman3dirR<tstderrtwriteRRtexitR R R(((s0/usr/lib64/python2.7/Demo/tkinter/guido/tkman.pytsD             PK%L]YYtkinter/guido/brownian.pyonu[ ^c@sddlTddlZddlZddlZddlZdZdZdZdZdZ dZ dZ da d Z d ZedS( i(t*Nii,i itredicCst}tjtdt}tjtdt}|j||||||||dt}xvtstjdt }tjdt }tj t }y|j |||Wnt k rPnXtj|qcWdS(Ng@tfilli(tRADIUStrandomtgausstWIDTHtSIGMAtHEIGHTt create_ovaltFILLtstoptBUZZt expovariatetLAMBDAtmovetTclErrorttimetsleep(tcanvastrtxtytptdxtdytdt((s3/usr/lib64/python2.7/Demo/tkinter/guido/brownian.pytparticles.  cCst}t|dtdt}|jddddd}tjdr`ttjd}nx9t|D]+}t j dt d |f}|j qmWz|j WddaXdS( NtwidththeightRtbothtexpandiittargettargs(tTktCanvasRRtpacktsystargvtinttranget threadingtThreadRtstarttmainloopR (trootRtnptitt((s3/usr/lib64/python2.7/Demo/tkinter/guido/brownian.pytmain"s  (tTkinterRR)RR%RRRR RRR R RR1(((s3/usr/lib64/python2.7/Demo/tkinter/guido/brownian.pyts       PK%L]"@@tkinter/guido/kill.pycnu[ Afc@sddlTddlmZddlmZddlZddlZdefdYZdefdYZ e d kre dd d Z e j jd e j jd d e jndS(i(t*(t splitfields(tsplitNt BarButtoncBseZddZRS(cKsOttj||f||jdtt|dd|_|j|dss<1>(,tFrameR R tBOTHtRAISEDRCtXRtfileRt add_commandtquittviewtIntVarRR*trangetlenRtadd_radiobuttonR"t tk_menuBarR+t StringVarR)tLabeltFLATtNWRHt ScrollbartVERTICALR,tListboxtSUNKENR-R1tRIGHTtYtButtontupdatetbindR>R?R@(R RRtnum((s//usr/lib64/python2.7/Demo/tkinter/guido/kill.pyR 2sP    (RRi(Rs-li(Rs-ui(Rs-ji(Rs-si(Rs-mi(Rs-vi(Rs-XiN( RRRR&R"R>R?R@RR (((s//usr/lib64/python2.7/Demo/tkinter/guido/kill.pyRs     t__main__REisTkinter Process Killeri(tTkintertstringRRR'R RRRURRRR&twinfo_toplevelttitletminsizetmainloop(((s//usr/lib64/python2.7/Demo/tkinter/guido/kill.pyts   M PK%L] Cxjjtkinter/guido/paint.pynu[""""Paint program by Dave Michell. Subject: tkinter "paint" example From: Dave Mitchell To: python-list@cwi.nl Date: Fri, 23 Jan 1998 12:18:05 -0500 (EST) Not too long ago (last week maybe?) someone posted a request for an example of a paint program using Tkinter. Try as I might I can't seem to find it in the archive, so i'll just post mine here and hope that the person who requested it sees this! All this does is put up a canvas and draw a smooth black line whenever you have the mouse button down, but hopefully it will be enough to start with.. It would be easy enough to add some options like other shapes or colors... yours, dave mitchell davem@magnet.com """ from Tkinter import * """paint.py: not exactly a paint program.. just a smooth line drawing demo.""" b1 = "up" xold, yold = None, None def main(): root = Tk() drawing_area = Canvas(root) drawing_area.pack() drawing_area.bind("", motion) drawing_area.bind("", b1down) drawing_area.bind("", b1up) root.mainloop() def b1down(event): global b1 b1 = "down" # you only want to draw when the button is down # because "Motion" events happen -all the time- def b1up(event): global b1, xold, yold b1 = "up" xold = None # reset the line when you let go of the button yold = None def motion(event): if b1 == "down": global xold, yold if xold is not None and yold is not None: event.widget.create_line(xold,yold,event.x,event.y,smooth=TRUE) # here's where you draw it. smooth. neat. xold = event.x yold = event.y if __name__ == "__main__": main() PK%L].55tkinter/guido/svkill.pycnu[ Afc@sddlTedkr"ednddlmZddlmZddlZddlZejdZ de fd YZ d e fd YZ ed kre dd dZejjdejjddejndS(i(t*g@s/This version of svkill requires Tk 4.0 or later(t splitfields(tsplitNtLOGNAMEt BarButtoncBseZddZRS(cKsOttj||f||jdtt|dd|_|j|dss<1>(0RtFrameR R tBOTHtRAISEDR;tXRtfileRt add_commandtquitR"RtIntVarR&trangetlenR!tadd_radiobuttonRRt tk_menuBarR't StringVarR%tLabeltFLATtNWR@tYtWt ScrollbartVERTICALtvscrolltListboxtSUNKENtBROWSER(tyviewtRIGHTtButtontupdatetbindR6R7R8(RRRtnumR@toptiontcol((s1/usr/lib64/python2.7/Demo/tkinter/guido/svkill.pyR ?sv           (RR(s Every (-e)s-e(sNon process group leaders (-d)s-d(sNon leaders with tty (-a)s-a(RRi(s Long (-l)s-li(s Full (-f)s-fi(sFull Long (-f -l)s-l -fi(sSession and group ID (-j)s-ji(sScheduler properties (-c)s-ciN( RRtuserR!RR RR6R7R8RR (((s1/usr/lib64/python2.7/Demo/tkinter/guido/svkill.pyRs"     t__main__R=isTkinter Process Killer (SYSV)i(tTkintert TkVersiont ImportErrortstringRRR#RtenvironRrR RRRRRRR twinfo_toplevelttitletminsizetmainloop(((s1/usr/lib64/python2.7/Demo/tkinter/guido/svkill.pyts      d PK%L]%Ltkinter/guido/brownian2.pycnu[ ^c@sddlTddlZddlZdZdZdZdZdZdZdZ da da d Z d Zd Zed krendS( i(t*Nii,i itrediccst}tjtdt}tjtdt}|j||||||||dt}x_tstjdt }tjdt }y|j |||Wnt k rPqcXdVqcWdS(Ng@tfilli( tRADIUStrandomtgausstWIDTHtSIGMAtHEIGHTt create_ovaltFILLtstoptBUZZtmovetTclErrortNone(tcanvastrtxtytptdxtdy((s4/usr/lib64/python2.7/Demo/tkinter/guido/brownian2.pytparticles.  cCs:|jtjt}tjt|dt|dS(Ni(tnextRt expovariatetLAMBDAtroottaftertintR (Rtdt((s4/usr/lib64/python2.7/Demo/tkinter/guido/brownian2.pyR "s cCstattdtdt}|jddddd}tjdr`ttjd}nx$t |D]}t t |qmWztj Wdda XdS(NtwidththeightRtbothtexpandii(tTkRtCanvasRRtpacktsystargvRtrangeR RtmainloopR (Rtnpti((s4/usr/lib64/python2.7/Demo/tkinter/guido/brownian2.pytmain's  t__main__(tTkinterRR&RRRR RRR R RRRR R,t__name__(((s4/usr/lib64/python2.7/Demo/tkinter/guido/brownian2.pyts       PK%L]`xIItkinter/guido/hanoi.pycnu[ ^c@sIddlTdZdddYZdZedkrEendS( i(t*cCsX|dkrdSt|d||||||||t|d||||dS(Nii(thanoi(tntatbtctreport((s0/usr/lib64/python2.7/Demo/tkinter/guido/hanoi.pyRs  tTkhanoicBs&eZddZdZdZRS(cCs||_t|_}t||_}|j|j|d|j|d}}|r|j|d|dd|dd|_nd}|d}|d} | |d|d d} } | || |} } g|_ |j | | | | d d }|j j || | | | } } |j | | | | d d }|j j || | | | } } |j | | | | d d }|j j ||jj |d }| dd}d|}gggg|_ i|_| |d| |d} } | || |} } ||dtd |d }xt|d dD]}|j | | | | d d}||j|<|j d j || || |} } | |d| |d} } |jj |jjdqFWdS(Ntwidththeightitbitmapt foregroundtbluei iitfilltblackiiitredi(RtTkttktCanvastcanvastpacktgetintt create_bitmapR tpegstcreate_rectangletappendtupdatetpegstatetpiecestmaxtrangetafter(tselfRR RRRR tpegwidtht pegheighttpegdisttx1ty1tx2ty2tpt pieceheightt maxpiecewidtht minpiecewidthtdxti((s0/usr/lib64/python2.7/Demo/tkinter/guido/hanoi.pyt__init__sP  '         cCsxt|jddd|jt|jddd|jt|jddd|jt|jddd|jt|jddd|jt|jddd|jqWdS(Niii(RRR(R ((s0/usr/lib64/python2.7/Demo/tkinter/guido/hanoi.pytrunNscCs|j|d|kr tn|j|d=|j|}|j}|j|j|\}}}} xO|j|\} } } } | |krPn|j|dd|jjqiW|j|j|\}}}}||d}x|j|\} } } } | | d}||kr$Pn||krF|j|ddn|j|dd|jjqW| | }||t |j|d}xO|j|\} } } } | |krPn|j|dd|jjqW|j|j |dS(Niiii( Rt RuntimeErrorRRtbboxRtmoveRRtlenR(R R-RRR(Rtax1tay1tax2tay2R$R%R&R'tbx1tby1tbx2tby2t newcentertcenterR)t newbottom((s0/usr/lib64/python2.7/Demo/tkinter/guido/hanoi.pyRXs@   " "    N(t__name__t __module__tNoneR.R/R(((s0/usr/lib64/python2.7/Demo/tkinter/guido/hanoi.pyRs 1 cCsddl}ddl}|jdr>|j|jd}nd}|jdr|jd}|ddkr{|d}qd|}nd}t||}|jdS(Niiiiit@(tsyststringtargvtatoiRARR/(RCRDRR th((s0/usr/lib64/python2.7/Demo/tkinter/guido/hanoi.pytmains     t__main__N((tTkinterRRRHR?(((s0/usr/lib64/python2.7/Demo/tkinter/guido/hanoi.pyt s  e  PK%L]^ui i tkinter/guido/switch.pyonu[ ^c@sfddlTdd dYZdd dYZdd dYZdZed krbend S(i(t*tAppcBs)eZdddZdZdZRS(cCs|dkr3|dkr$t}q3t|}n||_t||_|jjt|dddt|_|jjdddt i|_ d|_ dS(Nt borderwidthitrelieftexpanditfill( tNonetTktToplevelttoptFramet buttonframetpacktGROOVEt panelframetBOTHtpanelstcurpanel(tselfR tmaster((s1/usr/lib64/python2.7/Demo/tkinter/guido/switch.pyt__init__s      cCst|jd|d||d}|jdtt|j}||}|||f|j|<|jdkr|j |ndS(NttexttcommandcSs |j|S(N(tshow(Rtname((s1/usr/lib64/python2.7/Demo/tkinter/guido/switch.pytttside( tButtonR R tLEFTR RRRRR(RRtklasstbuttontframetinstance((s1/usr/lib64/python2.7/Demo/tkinter/guido/switch.pytaddpanels cCsR|j|\}}}|jr/|jjn||_|jdddddS(NRiRtboth(RRt pack_forgetR (RRRR R!((s1/usr/lib64/python2.7/Demo/tkinter/guido/switch.pyRs   N(t__name__t __module__RRR"R(((s1/usr/lib64/python2.7/Demo/tkinter/guido/switch.pyRs t LabelPanelcBseZdZRS(cCs&t|dd|_|jjdS(NRs Hello world(tLabeltlabelR (RR ((s1/usr/lib64/python2.7/Demo/tkinter/guido/switch.pyR's(R%R&R(((s1/usr/lib64/python2.7/Demo/tkinter/guido/switch.pyR'&st ButtonPanelcBseZdZRS(cCs&t|dd|_|jjdS(NRsPress me(RRR (RR ((s1/usr/lib64/python2.7/Demo/tkinter/guido/switch.pyR,s(R%R&R(((s1/usr/lib64/python2.7/Demo/tkinter/guido/switch.pyR*+scCs:t}|jdt|jdt|jjdS(NR)R(RR"R'R*R tmainloop(tapp((s1/usr/lib64/python2.7/Demo/tkinter/guido/switch.pytmain0s t__main__N((((tTkinterRR'R*R-R%(((s1/usr/lib64/python2.7/Demo/tkinter/guido/switch.pyts !  PK%L]#tkinter/guido/imageview.pynu[from Tkinter import * import sys def main(): filename = sys.argv[1] root = Tk() img = PhotoImage(file=filename) label = Label(root, image=img) label.pack() root.mainloop() main() PK%L].Vootkinter/guido/wish.pynu[# This is about all it requires to write a wish shell in Python! import _tkinter import os tk = _tkinter.create(os.environ['DISPLAY'], 'wish', 'Tk', 1) tk.call('update') cmd = '' while 1: if cmd: prompt = '' else: prompt = '% ' try: line = raw_input(prompt) except EOFError: break cmd = cmd + (line + '\n') if tk.getboolean(tk.call('info', 'complete', cmd)): tk.record(line) try: result = tk.call('eval', cmd) except _tkinter.TclError, msg: print 'TclError:', msg else: if result: print result cmd = '' PK%L]27O::tkinter/guido/imageview.pyonu[ ^c@s*ddlTddlZdZedS(i(t*NcCsOtjd}t}td|}t|d|}|j|jdS(Nitfiletimage(tsystargvtTkt PhotoImagetLabeltpacktmainloop(tfilenametroottimgtlabel((s4/usr/lib64/python2.7/Demo/tkinter/guido/imageview.pytmains    (tTkinterRR(((s4/usr/lib64/python2.7/Demo/tkinter/guido/imageview.pyts   PK%L]˗*KKtkinter/guido/hello.pynu[# Display hello, world in a button; clicking it quits the program import sys from Tkinter import * def main(): root = Tk() button = Button(root) button['text'] = 'Hello, world' button['command'] = quit_callback # See below button.pack() root.mainloop() def quit_callback(): sys.exit(0) main() PK%L]E`}eR R tkinter/guido/electrons.pyonu[ Afc@sLddlTddlZdddYZdZedkrHendS(i(t*Nt ElectronscBs&eZddZdZdZRS(c Cs||_t|_}t||_}|j|j|d|j|d}}|r|j|d|dd|dd|_ng|_ d \}}} } xWt |D]I} |j ||| | d d } |j j | |d| d}} qW|jj dS(Ntwidththeightitbitmapt foregroundtbluei iFiiJtfilltred(i iFiiJ(tntTkttktCanvastcanvastpacktgetintt create_bitmapRtpiecestranget create_ovaltappendtupdate( tselfR RR tcRRtx1ty1tx2ty2titp((s4/usr/lib64/python2.7/Demo/tkinter/guido/electrons.pyt__init__s   ' cCsq|j}xT|jD]I}tjtdd}tjtdd}|j|||qW|jjdS(Niii(R RtrandomtchoiceRtmoveR R(RR RRtxty((s4/usr/lib64/python2.7/Demo/tkinter/guido/electrons.pyt random_move+s  cCshy+x$tdD]}|j|jqWWn6tk rcy|jjWqdtk r_qdXnXdS(Ni(RR$R tTclErrorR tdestroy(RR((s4/usr/lib64/python2.7/Demo/tkinter/guido/electrons.pytrun4s  N(t__name__t __module__tNoneRR$R'(((s4/usr/lib64/python2.7/Demo/tkinter/guido/electrons.pyRs  cCsddl}ddl}|jdr>|j|jd}nd}|jdr|jd}|ddkr{|d}qd|}nd}t||}|jdS(Niiiiit@(tsyststringtargvtatoiR*RR'(R,R-R Rth((s4/usr/lib64/python2.7/Demo/tkinter/guido/electrons.pytmain@s     t__main__((tTkinterRRR1R((((s4/usr/lib64/python2.7/Demo/tkinter/guido/electrons.pyts  -  PK%L])tMIMItkinter/guido/AttrDialog.pycnu[ ^c@sddlTdddYZdefdYZdefdYZdefd YZd efd YZd dd YZdefdYZdefdYZdefdYZ de fdYZ dZ dZ dZ e dS(i(t*tOptioncBs5eZeZdZdZdZddZRS(cCs||_||_|j|_|j|\|_|_|j|j|_t |j|_ |j j dt t |j d|d|_|jj dt|j|jdS(Ntfillttextt:tside(tdialogtoptionttoptmastertoptionstdefaulttklasstvarclasstvartFrametframetpacktXtLabeltlabeltLEFTtupdatet addoption(tselfRR((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyt__init__s    cCs|jj|jdS(N(RtrefreshR(R((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyR"s cCsQy|jj|j|_Wntk r9|j|_nX|jj|jdS(N(RtcurrentRtKeyErrorR Rtset(R((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyR&s  cCsdS(N((Rte((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyR-sN( t__name__t __module__t StringVarR RRRtNoneR(((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyRs   t BooleanOptioncBseZeZdZRS(cCsYt|jddddddd|jdtd d d |j|_|jjd tdS( NRson/offtonvalueitoffvalueitvariabletrelieft borderwidthitcommandR(t CheckbuttonRRtRAISEDRtbuttonRtRIGHT(R((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyR4s  (RR t BooleanVarR R(((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyR#0st EnumOptioncBseZdZRS(c Cst|jd|jdtdd|_|jjdtt|j|_|j|jd( tEntryRRtSUNKENtentryRR-RtbindR(R((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyRQs   (RR R(((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyR8OstReadonlyOptioncBseZdZRS(cCs8t|jd|jdt|_|jjdtdS(NR0tanchorR(RRRtERRR-(R((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyR\s (RR R(((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyR?ZstDialogcBsPeZdZdZdZdZiZiZeZ e Z e Z eZRS(cCsf||_|j|jt|j|_|jj|jj|jjdd|j dS(Ni( R t fixclassesRtToplevelRttitlet __class__Rtminsizet addchoices(RR ((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyRcs   cCsdS(N((R((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyRltcCsdS(N((R((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyRCnRIcCsi|_g}x0|jjD]\}}|j||fqW|jx|D]\}\}}y|j|}Wntk rd}nXt|tkr|j }n9|dkr|j }n!|dkr|j }n |j }||||j|    "tRemotePackDialogcBseZdZdZdd dYZdeefdYZdeefdYZdee fd YZ d ee fd YZ RS( cCso||_||_||_|jt|j|_|jj|jd|jjdd|jdS(Ns PackDialogi( R tappR^RRDRRERGRH(RR RR^((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyRs    cCsy4|jjj|jj|jdd|j}Wntk rO}|GHdSXi}xFtdt|dD],}||d}||d}|||6dd?6dd@6ddA6ddB6d.dC6ddD6ddE6dFdG6dHdI6d.dJ6ddK6e!e"e#fdL6Z$ie%e&e'fdM6Z(ie%e'fdM6Z)ie(dN6e(dO6e(dP6e)dQ6e)dC6e(dR6e)dS6Z*RS(UcCs,||_|j|_tj||dS(N(R^R`R RBR(RR^((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyRs cCst|jj|jrpi}xF|j|j|jfD]+}x"|jD]}||||(RR>t opendialogsR(RRRRW((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyRscCsddl}|j}|j}x|D]}|j|}|j|d}t||j||dkruq(nyt||j|Wq(tk r}|GHq(Xq(WdS(Niit.( RR^t curselectionRctsplitRRRRe(RRRWtselRRR^Rf((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyRs     N(((tTkinterRR#R/R8R?RBR]RRRRRR(((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyts  .67m2   PK%L]27O::tkinter/guido/imageview.pycnu[ ^c@s*ddlTddlZdZedS(i(t*NcCsOtjd}t}td|}t|d|}|j|jdS(Nitfiletimage(tsystargvtTkt PhotoImagetLabeltpacktmainloop(tfilenametroottimgtlabel((s4/usr/lib64/python2.7/Demo/tkinter/guido/imageview.pytmains    (tTkinterRR(((s4/usr/lib64/python2.7/Demo/tkinter/guido/imageview.pyts   PK%L]E7tkinter/guido/listtree.pynu[# List a remote app's widget tree (names and classes only) import sys import string from Tkinter import * def listtree(master, app): list = Listbox(master, name='list') list.pack(expand=1, fill=BOTH) listnodes(list, app, '.', 0) return list def listnodes(list, app, widget, level): klass = list.send(app, 'winfo', 'class', widget) ## i = string.rindex(widget, '.') ## list.insert(END, '%s%s (%s)' % ((level-1)*'. ', widget[i:], klass)) list.insert(END, '%s (%s)' % (widget, klass)) children = list.tk.splitlist( list.send(app, 'winfo', 'children', widget)) for c in children: listnodes(list, app, c, level+1) def main(): if not sys.argv[1:]: sys.stderr.write('Usage: listtree appname\n') sys.exit(2) app = sys.argv[1] tk = Tk() tk.minsize(1, 1) f = Frame(tk, name='f') f.pack(expand=1, fill=BOTH) list = listtree(f, app) tk.mainloop() if __name__ == '__main__': main() PK%L]+$RRtkinter/guido/optionmenu.pycnu[ ^c@sddlTeZeZejdeeedddZejd Z eZ e je d e eee fe e Z e jejd S( i(t*tOnetTwotThreetAahtBeetCeetDeetEffiN(RRRRR(tTkintertTktroott StringVartvar1tsett OptionMenutmenu1tpacktCHOICEStvar2tapplyttupletmenu2tmainloop(((s5/usr/lib64/python2.7/Demo/tkinter/guido/optionmenu.pyts       PK%L]j'tkinter/guido/imagedraw.pynu["""Draw on top of an image""" from Tkinter import * import sys def main(): filename = sys.argv[1] root = Tk() img = PhotoImage(file=filename) w, h = img.width(), img.height() canv = Canvas(root, width=w, height=h) canv.create_image(0, 0, anchor=NW, image=img) canv.pack() canv.bind('', blob) root.mainloop() def blob(event): x, y = event.x, event.y canv = event.widget r = 5 canv.create_oval(x-r, y-r, x+r, y+r, fill='red', outline="") main() PK%L]"@@tkinter/guido/kill.pyonu[ Afc@sddlTddlmZddlmZddlZddlZdefdYZdefdYZ e d kre dd d Z e j jd e j jd d e jndS(i(t*(t splitfields(tsplitNt BarButtoncBseZddZRS(cKsOttj||f||jdtt|dd|_|j|dss<1>(,tFrameR R tBOTHtRAISEDRCtXRtfileRt add_commandtquittviewtIntVarRR*trangetlenRtadd_radiobuttonR"t tk_menuBarR+t StringVarR)tLabeltFLATtNWRHt ScrollbartVERTICALR,tListboxtSUNKENR-R1tRIGHTtYtButtontupdatetbindR>R?R@(R RRtnum((s//usr/lib64/python2.7/Demo/tkinter/guido/kill.pyR 2sP    (RRi(Rs-li(Rs-ui(Rs-ji(Rs-si(Rs-mi(Rs-vi(Rs-XiN( RRRR&R"R>R?R@RR (((s//usr/lib64/python2.7/Demo/tkinter/guido/kill.pyRs     t__main__REisTkinter Process Killeri(tTkintertstringRRR'R RRRURRRR&twinfo_toplevelttitletminsizetmainloop(((s//usr/lib64/python2.7/Demo/tkinter/guido/kill.pyts   M PK%L]KѴQQtkinter/guido/solitaire.pyonu[ Afc@sCdZddlZddlZddlTddlmZmZmZmZdefdYZdZ dZ d Z e d e Z e d e Z d Zd ZdZdZdZdZdZdZiZxeefD]Zeees s sN( R&R'tgametcardsRRR(R t clickhandlertdoubleclickhandlert motionhandlertreleasehandlert makebottom(RR&R'R>((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyR2s    cCsdS(N((R((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRDscCsd|jj|j|jfS(s+Return a string for debug print statements.s %s(%d, %d)(t __class__R R&R'(R((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyR3scCs>|jj||j|j||jj|jdS(N(R?tappendR9tpositionR(R-(Rtcard((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pytadd%s  cCs'|jj||jj|jdS(N(R?tremoveR(tdtag(RRH((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pytdelete+scCs!|jr|jdjndS(Ni(R?R:(R((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pytshowtop/s cCs+|js dS|jd}|j||S(Ni(R?RRL(RRH((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pytdeal3s    cCs|j|j|jdS(N(R5R&R'(RRH((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRG<scCs|jdS(N(RM(R((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pytuserclickhandler?scCs|jdS(N(RO(R((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pytuserdoubleclickhandlerBscCs"x|D]}|j|qWdS(N(RG(RR?RH((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pytusermovehandlerEs cCs%|j|j|j|dS(N(t finishmovingROt startmoving(Rtevent((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyR@Ks  cCs|j|dS(N(t keepmoving(RRT((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRBPscCs|j||jdS(N(RURR(RRT((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRCSs cCs%|j|j|j|dS(N(RRRPRS(RRT((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRAWs  cCsd|_|jjjd}xDtt|jD])}|j|}|jj |kr4Pq4q4WdS|j srdS|j||_|j |_ |j |_x|jD]}|jqWdS(Ntcurrent(RtmovingR>RtgettagstrangetlenR?R(ttagR%R&tlastxR'tlastyR9(RRTttagstiRH((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRS`s     cCs||js dS|j|j}|j|j}|j|_|j|_|sQ|rxx$|jD]}|j||q[WndS(N(RWR&R\R'R]R4(RRTR7R8RH((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRUqs    cCs,|j}d|_|r(|j|ndS(N(RWRRQ(RR?((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRR|s  N(R R R<RR2RDR3RIRLRMRNRGRORPRQR@RBRCRARWRSRURR(((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyR=s(-                tDeckcBs2eZdZdZdZdZdZRS(s7The deck is a stack with support for shuffling. New methods: fill() -- create the playing cards shuffle() -- shuffle the playing cards A single click moves the top card to the game's open deck and moves it face up; if we're out of cards, it moves the open deck back to the deck. c CsRt|jj|j|j|jt|jtdddt}|jj |dS(NRRR( RR>RR&R'R*R.t BACKGROUNDR(R-(Rtbottom((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRDs   cCsEx>tD]6}x-tD]%}|jt|||jjqWqWdS(N(tALLSUITSt ALLVALUESRIRR>R(RR!R"((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRs  cCsMt|j}g}x(t|D]}|j|j|q"W||_dS(N(RZR?trandpermRF(RtntnewcardsR_((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pytshuffles cCsv|jj}|j}|sUxQ|j}|s7Pn|j||jq!Wn|jjj||jdS(N(R>topendeckRNRIR;R:(RRiRH((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyROs    (R R R<RDRRhRO(((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyR`s     cCsLt|}g}x3|rGtj|}|j||j|qW|S(s4Function returning a random permutation of range(n).(RYtrandomtchoiceRFRJ(RftrR&R_((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRes   t OpenStackcBs#eZdZdZdZRS(cCsdS(Ni((RR?((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyt acceptablescCs|d}|jj|}| s?||ks?|j| rRtj||n8x(|D] }|j||j|qYW|jjdS(Ni(R>t closeststackRnR=RQRLRItwincheck(RR?RHtstack((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRQs #  cCs|js dS|jd}|js1|jdSxQ|jjD]C}|j|gr>|j||j||jjPq>q>WdS(Ni( R?R%ROR>tsuitsRnRLRIRp(RRHts((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRPs       (R R RnRQRP(((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRms  t SuitStackcBs,eZdZdZdZdZRS(c CsBt|jj|j|j|jt|jtdddd}dS(NRRRR(RR>RR&R'R*R.(RRb((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRDs  cCsdS(N((R((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyROscCsdS(N((R((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRPscCsit|dkrdS|d}|js6|jtkS|jd}|j|jkoh|j|jdkS(Niii(RZR?R"tACER!(RR?RHttopcard((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRns    (R R RDRORPRn(((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRts   tRowStackcBseZdZdZRS(cCs`|d}|js |jtkS|jd}|js:dS|j|jko_|j|jdkS(Niii(R?R"tKINGR%R$(RR?RHRv((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRns     cCsh|j}xE|jD]:}||kr)Pn|jrC|dt}q|t}qW|j|j|dS(Ni(R'R?R%R0tOFFSETR5R&(RRHR'tc((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRGs   (R R RnRG(((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRws t SolitairecBsGeZdZdZdZdZdZdZdZRS(c Cs||_t|jdtdddttddtdt|_|jjdt d t t |jd d dddtd d d|j |_ t|jtdtdd|j dtt}t}t||||_|t}t||||_|t}g|_x:ttD],}|t}|jjt|||qWt}|t}g|_x:ttD],}|jjt||||t}qoW|jg|j|j|_|jj|j dS(Nt backgroundthighlightthicknessitwidththeightiiRtexpandRtDealtactivebackgroundtgreenR twindowR(tmastertCanvasRatNROWStXSPACINGtYSPACINGR0RtpacktBOTHtTRUEtButtonRNt dealbuttonRtSWR`tdeckRmRiRrRYtNSUITSRFRttrowsRwt openstacksR(RRR&R'R_((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyR2sD            cCsEx*|jD]}t|jtkr dSq W|j|jdS(N(RrRZR?tNVALUEStwinRN(RRs((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRp=s  cCsgg}x|jD]}||j}qWx9|rbtj|}|j||j||jq*WdS(sStupid animation when you win.N(RR?RjRkRJtanimatedmovetoR(RR?RsRH((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRDs  cCsgx`tdddD]L}|j|j||j|j|}}|j|||jjqWdS(Ni ii(RYR&R'R4Rtupdate_idletasks(RRHtdestR_R7R8((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRNs)cCsed}d}xR|jD]G}|j|jd|j|jd}||kr|}|}qqW|S(Niɚ;i(RRR&R'(RRHtclosesttcdistRqtdist((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRoTs&  cCs|j|jjxHttD]:}x1|j|D]"}|jj}|j|q8Wq$Wx|jD]}|jqlWdS(N( tresetRRhRYRRRNRIRM(RR_RlRH((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRN`s  cCsOxH|jD]=}x4|j}|s)Pn|jj||jqWq WdS(N(RRNRRIR;(RRqRH((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRjs ( R R R2RpRRRoRNR(((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyR{ s .   cCs6t}t|}|jd|j|jdS(NtWM_DELETE_WINDOW(tTkR{tprotocoltquittmainloop(trootR>((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pytmainvs  t__main__((((1R<tmathRjtTkinterRRRRRR*R.R0RRRyRatHEARTStDIAMONDStCLUBStSPADEStREDtBLACKR#RstkeysRcRZRRutJACKtQUEENRxRYRdRtmaptstrR)RRR=R`ReRmRtRwR{RR (((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pytsX   "     /f1 i  PK%L]o o tkinter/guido/dialog.pycnu[ Afc@sKddlTddlZdZdZdZedkrGendS(i(t*NcGst|dd}|j||jdt|dtdd}|jdtdtt|dtdd}|jdtdtt |dd d |d d } | jdt d ddtdddd|rt |d|} | jdt ddddnt } g} d} x|D]}t|d |d| | d}| j|| |krt|dtdd}|jdt d ddddd|j|jd|dt ddddddddn.|jdt d ddddddddd| d} q!W|dkrA|jd| || |dn|j}|j|j|j| |j|r|jn| jS(Ntclass_tDialogtrelieft borderwidthitsidetfilltwidtht3ittexttfonts$-Adobe-Times-Medium-R-Normal-*-180-*texpandtpadxt3mtpadytbitmapitcommandcSs |j|S(N(tset(tvti((s1/usr/lib64/python2.7/Demo/tkinter/guido/dialog.pyt(tt2mtin_tipadxtipadyt1mscSs|j|j|fS(N(tflashR(tetbRR((s1/usr/lib64/python2.7/Demo/tkinter/guido/dialog.pyR:s (tToplevelttitleticonnametFrametRAISEDtpacktTOPtBOTHtBOTTOMtMessagetRIGHTtLabeltLEFTtIntVartButtontappendtSUNKENtlifttbindt focus_gettgrab_sett focus_settwaitvartdestroytget(tmasterRR RtdefaulttargstwttoptbottmsgtbmtvartbuttonsRtbutRtbdtoldFocus((s1/usr/lib64/python2.7/Demo/tkinter/guido/dialog.pytdialog sN   (  !  "         c CsRttddddd}dG|GHttddd d d d d }dG|GHdS(NsNot Respondings=The file server isn't responding right now; I'll keep trying.RitOKspressed buttons File ModifiedswFile "tcl.h" has been modified since the last time it was saved. Do you want to save it before exiting the application?twarningis Save FilesDiscard ChangessReturn To Editor(RDt mainWidget(R((s1/usr/lib64/python2.7/Demo/tkinter/guido/dialog.pytgoLs    cCs}ddl}tatjtttdddt}|jttddd|j}|jdt tj dS(NiR sPress Here To StartRtExitR( tsysR!RGtPacktconfigR,RHR#texitR%tmainloop(RJtstarttendit((s1/usr/lib64/python2.7/Demo/tkinter/guido/dialog.pyttestas    t__main__(tTkinterRJRDRHRQt__name__(((s1/usr/lib64/python2.7/Demo/tkinter/guido/dialog.pyts   A  PK%L]`xIItkinter/guido/hanoi.pyonu[ ^c@sIddlTdZdddYZdZedkrEendS( i(t*cCsX|dkrdSt|d||||||||t|d||||dS(Nii(thanoi(tntatbtctreport((s0/usr/lib64/python2.7/Demo/tkinter/guido/hanoi.pyRs  tTkhanoicBs&eZddZdZdZRS(cCs||_t|_}t||_}|j|j|d|j|d}}|r|j|d|dd|dd|_nd}|d}|d} | |d|d d} } | || |} } g|_ |j | | | | d d }|j j || | | | } } |j | | | | d d }|j j || | | | } } |j | | | | d d }|j j ||jj |d }| dd}d|}gggg|_ i|_| |d| |d} } | || |} } ||dtd |d }xt|d dD]}|j | | | | d d}||j|<|j d j || || |} } | |d| |d} } |jj |jjdqFWdS(Ntwidththeightitbitmapt foregroundtbluei iitfilltblackiiitredi(RtTkttktCanvastcanvastpacktgetintt create_bitmapR tpegstcreate_rectangletappendtupdatetpegstatetpiecestmaxtrangetafter(tselfRR RRRR tpegwidtht pegheighttpegdisttx1ty1tx2ty2tpt pieceheightt maxpiecewidtht minpiecewidthtdxti((s0/usr/lib64/python2.7/Demo/tkinter/guido/hanoi.pyt__init__sP  '         cCsxt|jddd|jt|jddd|jt|jddd|jt|jddd|jt|jddd|jt|jddd|jqWdS(Niii(RRR(R ((s0/usr/lib64/python2.7/Demo/tkinter/guido/hanoi.pytrunNscCs|j|d|kr tn|j|d=|j|}|j}|j|j|\}}}} xO|j|\} } } } | |krPn|j|dd|jjqiW|j|j|\}}}}||d}x|j|\} } } } | | d}||kr$Pn||krF|j|ddn|j|dd|jjqW| | }||t |j|d}xO|j|\} } } } | |krPn|j|dd|jjqW|j|j |dS(Niiii( Rt RuntimeErrorRRtbboxRtmoveRRtlenR(R R-RRR(Rtax1tay1tax2tay2R$R%R&R'tbx1tby1tbx2tby2t newcentertcenterR)t newbottom((s0/usr/lib64/python2.7/Demo/tkinter/guido/hanoi.pyRXs@   " "    N(t__name__t __module__tNoneR.R/R(((s0/usr/lib64/python2.7/Demo/tkinter/guido/hanoi.pyRs 1 cCsddl}ddl}|jdr>|j|jd}nd}|jdr|jd}|ddkr{|d}qd|}nd}t||}|jdS(Niiiiit@(tsyststringtargvtatoiRARR/(RCRDRR th((s0/usr/lib64/python2.7/Demo/tkinter/guido/hanoi.pytmains     t__main__N((tTkinterRRRHR?(((s0/usr/lib64/python2.7/Demo/tkinter/guido/hanoi.pyt s  e  PK%L] 7E tkinter/guido/mbox.pycnu[ Afc@s)ddlZddlZddlZddlZddlZddlZddlTddlmZejddZ dZ dZ dZ d Z d Zejd Zdd Zdd ZdZddZdadaddZdZdZdZdddZe dS(iN(t*(tdialogtHOMEs/Mailc Cs#daday#tjtjdd\}}Wn(tjk rY}|GHtjdnXx1|D])}|d dkr|daqa|aqaWtja t j ta t a t jatt atjidd6dd 6tt}|jid d 6d d 6t|id d6dd6}|jid d 6d d 6t|idd6atjidd6dd 6dd 6tt atjdidd6td6tjdtjdidd6dd6tjdt|dftdtsettyscrollcommandtyviews s<3>tfixedtfonts Open MessagesRemove MessagesRefile Messagetblacktbgtxi (*tfoldertseqtgetopttsystargvterrorRtmhlibtMHtmht openfoldertmhftTktrootttktFramettoptpackt ScrollbartListboxt folderboxtMenut foldermenutaddt open_foldertbindt folder_unpostt folder_posttscanboxtscanmenut open_messagetremove_messagetrefile_messaget scan_unpostt scan_posttbottNonetviewertminsizet setfolderstrescantmainloop( toptstargstmsgtargR t folderbarRtscanbartrule2((s//usr/lib64/python2.7/Demo/tkinter/guido/mbox.pytmains#        "         ""               cCs9|j|j}}tj|d|dtjdS(Ni (tx_rootty_rootR4tposttgrab_set(teRR ((s//usr/lib64/python2.7/Demo/tkinter/guido/mbox.pyR9scCs5tjddtjtjtjddS(Ntupdatet idletaskstactive(R,tcallR4t grab_releasetunposttinvoke(RT((s//usr/lib64/python2.7/Demo/tkinter/guido/mbox.pyR8s  cCs9|j|j}}tj|d|dtjdS(Ni (RPRQR;RRRS(RTRR ((s//usr/lib64/python2.7/Demo/tkinter/guido/mbox.pyR@scCs5tjddtjtjtjddS(NRURVRW(R,RXR;RYRZR[(RT((s//usr/lib64/python2.7/Demo/tkinter/guido/mbox.pyR?s  s ^ *([0-9]+)cCstj}t|dkr\t|dkr9d}nd}ttd|ddddS|d}tj|atjta t dS(Nis Please open one folder at a timesPlease select a folder to opensCan't Open FolderRitOK( R2t curselectiontlenRR+tgetRR'R(R)RF(RTtselRJti((s//usr/lib64/python2.7/Demo/tkinter/guido/mbox.pyR6s   c Cs9tj}t|dkr\t|dkr9d}nd}ttd|ddddStd}d tdttddddddSg}xT|D]L}tj|}tj|dkrK|jt j tj dqKqKWt j |ttt||dS(NisNo Message To Removes!Please select a message to removeRR\i(R:tnearestR]RR+R_ReRftappendRgRhRiR)tremovemessagesRFtfixfocustmin(RTtitopR`ttodoRaRm((s//usr/lib64/python2.7/Demo/tkinter/guido/mbox.pyR=s   & Rc Cs]tjd}tj}|s>ttddddddStj}t|dkr|skd}nd}ttd |ddddStj|d}g}xT|D]L}tj|}tj |dkr|j t j tj dqqWt|kst r/|adatjtantj|tttt||dS( NisNo Message To Refiles!Please select a message to refileRR\is#Please select a folder to refile tos-Please select exactly one folder to refile tosNo Folder To Refile(R:RsR]RR+R2R^R_ReRfRtRgRhRit lastrefilettofolderRBR'R(R)trefilemessagesRFRvRw( RTRxR`t folderselRJtrefiletoRyRaRm((s//usr/lib64/python2.7/Demo/tkinter/guido/mbox.pyR>s4     &cCstj}xot|D][}tjt|}tj|dkrtjtj d}||krtPqtqqWd}tj |tj |dS(Niitend( R:tsizetrangeR_treprReRfRgRhRit select_fromR(tnearRxtnRaRmRn((s//usr/lib64/python2.7/Demo/tkinter/guido/mbox.pyRvs    cCs;tjddx$tjD]}tjd|qWdS(NiR(R2tdeleteR'tlistallfolderstinsert(tfn((s//usr/lib64/python2.7/Demo/tkinter/guido/mbox.pyRE scCsWtrtjdantjddx'tttD]}tjd|q9WdS(NiR( RCRkRBR:Rt scanfolderRR R(Rm((s//usr/lib64/python2.7/Demo/tkinter/guido/mbox.pyRFs   RRcCs,tdtjd||fdjS(NcSs|d S(Ni((Rm((s//usr/lib64/python2.7/Demo/tkinter/guido/mbox.pytRs scan +%s %str(tmaptostpopent readlines(Rtsequence((s//usr/lib64/python2.7/Demo/tkinter/guido/mbox.pyRs(RR"treR!RgR%tTkinterRtenvirontmailboxROR9R8R@R?tcompileReRBR6R<RrR=RzR{R>RvRERFR(((s//usr/lib64/python2.7/Demo/tkinter/guido/mbox.pyts4        x           PK%L]vtkinter/guido/canvasevents.pynuȯ#! /usr/bin/python2.7 from Tkinter import * from Canvas import Oval, Group, CanvasText # Fix a bug in Canvas.Group as distributed in Python 1.4. The # distributed bind() method is broken. This is what should be used: class Group(Group): def bind(self, sequence=None, command=None): return self.canvas.tag_bind(self.id, sequence, command) class Object: """Base class for composite graphical objects. Objects belong to a canvas, and can be moved around on the canvas. They also belong to at most one ``pile'' of objects, and can be transferred between piles (or removed from their pile). Objects have a canonical ``x, y'' position which is moved when the object is moved. Where the object is relative to this position depends on the object; for simple objects, it may be their center. Objects have mouse sensitivity. They can be clicked, dragged and double-clicked. The behavior may actually be determined by the pile they are in. All instance attributes are public since the derived class may need them. """ def __init__(self, canvas, x=0, y=0, fill='red', text='object'): self.canvas = canvas self.x = x self.y = y self.pile = None self.group = Group(self.canvas) self.createitems(fill, text) def __str__(self): return str(self.group) def createitems(self, fill, text): self.__oval = Oval(self.canvas, self.x-20, self.y-10, self.x+20, self.y+10, fill=fill, width=3) self.group.addtag_withtag(self.__oval) self.__text = CanvasText(self.canvas, self.x, self.y, text=text) self.group.addtag_withtag(self.__text) def moveby(self, dx, dy): if dx == dy == 0: return self.group.move(dx, dy) self.x = self.x + dx self.y = self.y + dy def moveto(self, x, y): self.moveby(x - self.x, y - self.y) def transfer(self, pile): if self.pile: self.pile.delete(self) self.pile = None self.pile = pile if self.pile: self.pile.add(self) def tkraise(self): self.group.tkraise() class Bottom(Object): """An object to serve as the bottom of a pile.""" def createitems(self, *args): self.__oval = Oval(self.canvas, self.x-20, self.y-10, self.x+20, self.y+10, fill='gray', outline='') self.group.addtag_withtag(self.__oval) class Pile: """A group of graphical objects.""" def __init__(self, canvas, x, y, tag=None): self.canvas = canvas self.x = x self.y = y self.objects = [] self.bottom = Bottom(self.canvas, self.x, self.y) self.group = Group(self.canvas, tag=tag) self.group.addtag_withtag(self.bottom.group) self.bindhandlers() def bindhandlers(self): self.group.bind('<1>', self.clickhandler) self.group.bind('', self.doubleclickhandler) def add(self, object): self.objects.append(object) self.group.addtag_withtag(object.group) self.position(object) def delete(self, object): object.group.dtag(self.group) self.objects.remove(object) def position(self, object): object.tkraise() i = self.objects.index(object) object.moveto(self.x + i*4, self.y + i*8) def clickhandler(self, event): pass def doubleclickhandler(self, event): pass class MovingPile(Pile): def bindhandlers(self): Pile.bindhandlers(self) self.group.bind('', self.motionhandler) self.group.bind('', self.releasehandler) movethis = None def clickhandler(self, event): tags = self.canvas.gettags('current') for i in range(len(self.objects)): o = self.objects[i] if o.group.tag in tags: break else: self.movethis = None return self.movethis = self.objects[i:] for o in self.movethis: o.tkraise() self.lastx = event.x self.lasty = event.y doubleclickhandler = clickhandler def motionhandler(self, event): if not self.movethis: return dx = event.x - self.lastx dy = event.y - self.lasty self.lastx = event.x self.lasty = event.y for o in self.movethis: o.moveby(dx, dy) def releasehandler(self, event): objects = self.movethis if not objects: return self.movethis = None self.finishmove(objects) def finishmove(self, objects): for o in objects: self.position(o) class Pile1(MovingPile): x = 50 y = 50 tag = 'p1' def __init__(self, demo): self.demo = demo MovingPile.__init__(self, self.demo.canvas, self.x, self.y, self.tag) def doubleclickhandler(self, event): try: o = self.objects[-1] except IndexError: return o.transfer(self.other()) MovingPile.doubleclickhandler(self, event) def other(self): return self.demo.p2 def finishmove(self, objects): o = objects[0] p = self.other() x, y = o.x, o.y if (x-p.x)**2 + (y-p.y)**2 < (x-self.x)**2 + (y-self.y)**2: for o in objects: o.transfer(p) else: MovingPile.finishmove(self, objects) class Pile2(Pile1): x = 150 y = 50 tag = 'p2' def other(self): return self.demo.p1 class Demo: def __init__(self, master): self.master = master self.canvas = Canvas(master, width=200, height=200, background='yellow', relief=SUNKEN, borderwidth=2) self.canvas.pack(expand=1, fill=BOTH) self.p1 = Pile1(self) self.p2 = Pile2(self) o1 = Object(self.canvas, fill='red', text='o1') o2 = Object(self.canvas, fill='green', text='o2') o3 = Object(self.canvas, fill='light blue', text='o3') o1.transfer(self.p1) o2.transfer(self.p1) o3.transfer(self.p2) # Main function, run when invoked as a stand-alone Python program. def main(): root = Tk() demo = Demo(root) root.protocol('WM_DELETE_WINDOW', root.quit) root.mainloop() if __name__ == '__main__': main() PK%L]Xj|0J|J|tkinter/guido/ss1.pyonu[ ^c@sdZddlZddlZddlZddlZddlZddlmZdddf\ZZ Z dZ dZ d Z ie e6e e 6e e 6Zid e6d e 6d e 6Zied 6e d 6e d 6Zid e6d e 6de 6ZdZdfdYZdfdYZdfdYZdefdYZdefdYZdefdYZdZdZdZdZddlZd fd!YZd"Z d#Z!e"d$kre!ndS(%sSS1 -- a spreadsheet.iN(texpattLEFTtCENTERtRIGHTcCs |j|S(N(tljust(txtn((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyR scCs |j|S(N(tcenter(RR((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRscCs |j|S(N(trjust(RR((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRstleftRtrighttwtecCs4d}x'|D]}|dk r ||7}q q W|S(Ni(tNone(tseqttotalR((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pytsums   tSheetcBseZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZdZdZdZRS(cCsOi|_tj|_|jjd}|j|_|j|_t|_dS(Nt__main__(tcellstrexectRExect add_modulet cellvaluetcelltmulticellvalueR(tselftm((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyt__init__"s    cCs9|j||}t|dr1|j|jS|SdS(Ntrecalc(tgetcellthasattrRR(RRtyR((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyR*scCs||kr||}}n||kr8||}}ng}xRt||dD]=}x4t||dD]}|j|j||qlWqRW|S(Ni(trangetappendR(Rtx1ty1tx2ty2RR R((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyR1s  !cCs|jj||fS(N(Rtget(RRR ((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyR<scCs||j||fR!t colnum2nameRR;tlentstrRt iteritemsRRRRAt isinstanceRR't align2action(RR<R=twidththeighttcolwidthtfullRttextt alignmentR Rtseptline((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pytdisplaysP &!&!"  ! '  cCsdg}xn|jjD]]\\}}}t|drI|j}ndtj|}|jd|||fqW|jddj|S(Ns txmls%ss% %s ss (RRIRRUtcgitescapeR"tjoin(RtoutRR Rtcellxml((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRUs "  cCs\|j}t|d}|j||rN|jd rN|jdn|jdS(NR s (RUtopentwritetendswithtclose(RtfilenameRPtf((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pytsaves   cCs0t|d}t|j||jdS(Ntr(R[t SheetParsert parsefileR^(RR_R`((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pytloads(t__name__t __module__RRRRR(R*R-R0R1R+R6R7R8R9R:R>R?RRTRURaRe(((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyR s,                  2 RccBseZdZdZdZdZdZdZdZeZ dZ dZ d Z d Z d Zd Zd ZdZRS(cCs ||_dS(N(tsheet(RRh((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRscCsAtj}|j|_|j|_|j|_|j|dS(N( Rt ParserCreatet startelementtStartElementHandlert endelementtEndElementHandlertdatatCharacterDataHandlert ParseFile(RR`tparser((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRds     cCsct|d|d}|rVx*|jD]\}}t|||%s(RsttypeRyRft align2xmlRQR(RRw((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRUXs  cCs8d|jkodknr*d|jS|jSdS(Niis %sIiI(Ryt _xml_long(R((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyt_xml_int_s cCs d|jS(Ns%s(Ry(R((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRescCsdt|jS(Ns%s(treprRy(R((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyt _xml_floathscCsdt|jS(Ns%s(RRy(R((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyt _xml_complexks( RfRgRRRRARURRRR(((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyREs      RcBs2eZdedZdZdZdZRS(s%scCs||_||_||_dS(N(RPRRQ(RRPRRQ((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRps  cCs|jS(N(RP(RR((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRwscCs|j|jfS(N(RPRQ(R((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRAzscCs-d}|t|j|jtj|jfS(Ns9%s(RRQRRVRWRP(Rts((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRU}s  (RfRgRRRRARU(((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRns  RcBsDeZdedZdZdZdZdZdZRS(s%scCs;||_t|j|_||_||_|jdS(N(tformulat translatet translatedRRQR?(RRRRQ((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRs    cCs d|_dS(N(R Ry(R((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyR?scCs|jdkry4|jddt|j|jd|_Wqtjd}t|drw|j |_qt ||_qXn|jS(Ns from __future__ import division s__value__ = eval(%s)t __value__iRf( RyR tr_execRRtr_evalR.texc_infoRRfRH(RRtexc((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRs cCs:y|j|j}Wnt|j}nX||jfS(N(RRyRHRQ(RRP((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRAs cCsdt|j|j|jfS(Ns,%s(RRQRR(R((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRUs cCsg}xtjd|jD]}tjd|} | dk r| j\} } t| } t| } || ko|knr|| ko|knrt| || |}qn|j |qWt dj ||j |j S(Ns(\w+)s^([A-Z]+)([1-9][0-9]*)$RB(tretsplitRtmatchR tgroupst colname2numR}tcellnameR"RRXRRQ(RR#R$R%R&R3R4RYtpartRtsxtsyRR ((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyR2s   8( RfRgRRR?RRARUR2(((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRs     c Csg}xtjd|D]}tjd|}|dkrM|j|q|j\}}}}t|}|dkrd||f}n"t|}d||||f}|j|qWdj|S(sTranslate a formula containing fancy cell names to valid Python code. Examples: B4 -> cell(2, 4) B4:Z100 -> cells(2, 4, 26, 100) s(\w+(?::\w+)?)s2^([A-Z]+)([1-9][0-9]*)(?::([A-Z]+)([1-9][0-9]*))?$s cell(%s, %s)scells(%s, %s, %s, %s)RBN(RRRR R"RRRX( RRYRRR#R$R%R&R((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRs    cCst|t|S(sETranslate a cell coordinate to a fancy cell name (e.g. (1, 1)->'A1').(RFRH(RR ((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRscCsI|j}d}x0|D](}|dt|tdd}qW|S(sCTranslate a column name to number (e.g. 'A'->1, 'Z'->26, 'AA'->27).iitAi(tuppertord(RRtc((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRs   &cCsJd}x=|rEt|dd\}}t|td|}q W|S(s6Translate a column number to name (e.g. 1->'A', etc.).RBiiR(tdivmodtchrR(RRR((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRFs  tSheetGUIcBseZdZddddZdZdZdZdZd Zd Z d Z d Z d Z dZ dZeZdZdZdZdZdZdZdZdZdZdZdZdZRS(s7Beginnings of a GUI for a spreadsheet. TO DO: - clear multiple cells - Insert, clear, remove rows or columns - Show new contents while typing - Scroll bars - Grow grid when window is grown - Proper menus - Undo, redo - Cut, copy and paste - Formatting and alignment s sheet1.xmli icCs*||_t|_tjj|r:|jj|n|jj\}}t||}t||}t j |_ |j j d|jt j |j dddd|_ t j|j |_t j|j ddd |j|_t j|j |_|jjd d d d dd|j jd d|jjd d|jjd dd d dd|jjd|j|jjd|j|jjd|j|jjd|j|jjd|j|jjd|j|j||d|_d|_ |j!d d |j"dS(slConstructor. Load the sheet from the filename argument. Set up the Tk widget tree. sSpreadsheet: %sRPtA1tfontt helveticaitboldtSavetcommandtsidetbottomtexpanditfilltbothR R Rssss ssN(RiR(#R_RRhtostpathtisfileReR>R;tTktroottwm_titletLabeltbeacontEntrytentrytButtonRat savebuttontFrametcellgridtpacktbindt return_eventtshift_return_eventt tab_eventtshift_tab_eventt delete_eventt escape_eventtmakegridR t currentxytcornerxyt setcurrenttsync(RR_trowstcolumnsR<R=((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRs<     cCsr|j|jkr>|jdk r>|jj|j|jn|jj|j|j|jjdddS(Nitendtbreak( RRR RhR-R*RRtdelete(Rtevent((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyR's ! cCs#|j\}}|j||dS(N(Rt load_entry(RRRR ((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyR0scCs|jj||}|dkr*d}n1t|trId|j}n|j\}}|jjdd|jj d||jj dddS(NRBt=iR( RhRR RJRRRARRtinserttselection_range(RRR RRPRQ((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyR4s  c Cs||_||_i|_tj|jdd}|jdddddd|jd|jxt d |d D]}|jj |d d tj|jd t |dd}|jd|dddd ||j|df<||_ d|_ |jd|j|jd|j|jd|j|jd|jqvWxt d |d D]}tj|jd t|dd}|jddd|dd ||jd|fitminsizei@RPtWEs sstsunkentbgtwhitetfgtblackN(RRt gridcellsRRRtgrid_configureRt selectallR!tgrid_columnconfigureRFt _SheetGUI__xt _SheetGUI__yt selectcolumnt extendcolumnRHt selectrowt extendrowtpresstmotiontrelease(RRRRRR ((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyR@sN   $  $    cCs*|jdd|jtjtjdS(Ni(Rt setcornerR.R/(RR((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRrscCs<|j|\}}|j|d|j|tjdS(Ni(twhichxyRRR.R/(RRRR ((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRvscCsR|j|\}}|dkrN|j|jdd|j|tjndS(Nii(RRRRR.R/(RRRR ((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyR{s cCs<|j|\}}|jd||jtj|dS(Ni(RRRR.R/(RRRR ((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRscCsR|j|\}}|dkrN|jd|jd|jtj|ndS(Nii(RRRRR.R/(RRRR ((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRs cCsD|j|\}}|dkr@|dkr@|j||ndS(Ni(RR(RRRR ((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRscCsD|j|\}}|dkr@|dkr@|j||ndS(Ni(RR(RRRR ((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRscCsh|jj|j|j}|dk rdt|tjrdy|j|j fSWqdt k r`qdXndS(Ni(ii( Rtwinfo_containingtx_rootty_rootR RJRRRRtAttributeError(RRR ((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRs cCs|jj|jdS(N(RhRaR_(R((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRascCs|jdk r|jn|jt|||jd<|j|||jj||f|_d|_ |j j |j}|dk rd|ds@         Y )6   C  PK%L]/ Ŕcctkinter/guido/brownian2.pynu[# Brownian motion -- an example of a NON multi-threaded Tkinter program ;) # By Michele Simoniato, inspired by brownian.py from Tkinter import * import random import sys WIDTH = 400 HEIGHT = 300 SIGMA = 10 BUZZ = 2 RADIUS = 2 LAMBDA = 10 FILL = 'red' stop = 0 # Set when main loop exits root = None # main window def particle(canvas): # particle = iterator over the moves r = RADIUS x = random.gauss(WIDTH/2.0, SIGMA) y = random.gauss(HEIGHT/2.0, SIGMA) p = canvas.create_oval(x-r, y-r, x+r, y+r, fill=FILL) while not stop: dx = random.gauss(0, BUZZ) dy = random.gauss(0, BUZZ) try: canvas.move(p, dx, dy) except TclError: break else: yield None def move(particle): # move the particle at random time particle.next() dt = random.expovariate(LAMBDA) root.after(int(dt*1000), move, particle) def main(): global root, stop root = Tk() canvas = Canvas(root, width=WIDTH, height=HEIGHT) canvas.pack(fill='both', expand=1) np = 30 if sys.argv[1:]: np = int(sys.argv[1]) for i in range(np): # start the dance move(particle(canvas)) try: root.mainloop() finally: stop = 1 if __name__ == '__main__': main() PK%L]&S}E}Etkinter/guido/solitaire.pynuȯ#! /usr/bin/python2.7 """Solitaire game, much like the one that comes with MS Windows. Limitations: - No cute graphical images for the playing cards faces or backs. - No scoring or timer. - No undo. - No option to turn 3 cards at a time. - No keyboard shortcuts. - Less fancy animation when you win. - The determination of which stack you drag to is more relaxed. Apology: I'm not much of a card player, so my terminology in these comments may at times be a little unusual. If you have suggestions, please let me know! """ # Imports import math import random from Tkinter import * from Canvas import Rectangle, CanvasText, Group, Window # Fix a bug in Canvas.Group as distributed in Python 1.4. The # distributed bind() method is broken. Rather than asking you to fix # the source, we fix it here by deriving a subclass: class Group(Group): def bind(self, sequence=None, command=None): return self.canvas.tag_bind(self.id, sequence, command) # Constants determining the size and lay-out of cards and stacks. We # work in a "grid" where each card/stack is surrounded by MARGIN # pixels of space on each side, so adjacent stacks are separated by # 2*MARGIN pixels. OFFSET is the offset used for displaying the # face down cards in the row stacks. CARDWIDTH = 100 CARDHEIGHT = 150 MARGIN = 10 XSPACING = CARDWIDTH + 2*MARGIN YSPACING = CARDHEIGHT + 4*MARGIN OFFSET = 5 # The background color, green to look like a playing table. The # standard green is way too bright, and dark green is way to dark, so # we use something in between. (There are a few more colors that # could be customized, but they are less controversial.) BACKGROUND = '#070' # Suits and colors. The values of the symbolic suit names are the # strings used to display them (you change these and VALNAMES to # internationalize the game). The COLOR dictionary maps suit names to # colors (red and black) which must be Tk color names. The keys() of # the COLOR dictionary conveniently provides us with a list of all # suits (in arbitrary order). HEARTS = 'Heart' DIAMONDS = 'Diamond' CLUBS = 'Club' SPADES = 'Spade' RED = 'red' BLACK = 'black' COLOR = {} for s in (HEARTS, DIAMONDS): COLOR[s] = RED for s in (CLUBS, SPADES): COLOR[s] = BLACK ALLSUITS = COLOR.keys() NSUITS = len(ALLSUITS) # Card values are 1-13. We also define symbolic names for the picture # cards. ALLVALUES is a list of all card values. ACE = 1 JACK = 11 QUEEN = 12 KING = 13 ALLVALUES = range(1, 14) # (one more than the highest value) NVALUES = len(ALLVALUES) # VALNAMES is a list that maps a card value to string. It contains a # dummy element at index 0 so it can be indexed directly with the card # value. VALNAMES = ["", "A"] + map(str, range(2, 11)) + ["J", "Q", "K"] # Solitaire constants. The only one I can think of is the number of # row stacks. NROWS = 7 # The rest of the program consists of class definitions. These are # further described in their documentation strings. class Card: """A playing card. A card doesn't record to which stack it belongs; only the stack records this (it turns out that we always know this from the context, and this saves a ``double update'' with potential for inconsistencies). Public methods: moveto(x, y) -- move the card to an absolute position moveby(dx, dy) -- move the card by a relative offset tkraise() -- raise the card to the top of its stack showface(), showback() -- turn the card face up or down & raise it Public read-only instance variables: suit, value, color -- the card's suit, value and color face_shown -- true when the card is shown face up, else false Semi-public read-only instance variables (XXX should be made private): group -- the Canvas.Group representing the card x, y -- the position of the card's top left corner Private instance variables: __back, __rect, __text -- the canvas items making up the card (To show the card face up, the text item is placed in front of rect and the back is placed behind it. To show it face down, this is reversed. The card is created face down.) """ def __init__(self, suit, value, canvas): """Card constructor. Arguments are the card's suit and value, and the canvas widget. The card is created at position (0, 0), with its face down (adding it to a stack will position it according to that stack's rules). """ self.suit = suit self.value = value self.color = COLOR[suit] self.face_shown = 0 self.x = self.y = 0 self.group = Group(canvas) text = "%s %s" % (VALNAMES[value], suit) self.__text = CanvasText(canvas, CARDWIDTH//2, 0, anchor=N, fill=self.color, text=text) self.group.addtag_withtag(self.__text) self.__rect = Rectangle(canvas, 0, 0, CARDWIDTH, CARDHEIGHT, outline='black', fill='white') self.group.addtag_withtag(self.__rect) self.__back = Rectangle(canvas, MARGIN, MARGIN, CARDWIDTH-MARGIN, CARDHEIGHT-MARGIN, outline='black', fill='blue') self.group.addtag_withtag(self.__back) def __repr__(self): """Return a string for debug print statements.""" return "Card(%r, %r)" % (self.suit, self.value) def moveto(self, x, y): """Move the card to absolute position (x, y).""" self.moveby(x - self.x, y - self.y) def moveby(self, dx, dy): """Move the card by (dx, dy).""" self.x = self.x + dx self.y = self.y + dy self.group.move(dx, dy) def tkraise(self): """Raise the card above all other objects in its canvas.""" self.group.tkraise() def showface(self): """Turn the card's face up.""" self.tkraise() self.__rect.tkraise() self.__text.tkraise() self.face_shown = 1 def showback(self): """Turn the card's face down.""" self.tkraise() self.__rect.tkraise() self.__back.tkraise() self.face_shown = 0 class Stack: """A generic stack of cards. This is used as a base class for all other stacks (e.g. the deck, the suit stacks, and the row stacks). Public methods: add(card) -- add a card to the stack delete(card) -- delete a card from the stack showtop() -- show the top card (if any) face up deal() -- delete and return the top card, or None if empty Method that subclasses may override: position(card) -- move the card to its proper (x, y) position The default position() method places all cards at the stack's own (x, y) position. userclickhandler(), userdoubleclickhandler() -- called to do subclass specific things on single and double clicks The default user (single) click handler shows the top card face up. The default user double click handler calls the user single click handler. usermovehandler(cards) -- called to complete a subpile move The default user move handler moves all moved cards back to their original position (by calling the position() method). Private methods: clickhandler(event), doubleclickhandler(event), motionhandler(event), releasehandler(event) -- event handlers The default event handlers turn the top card of the stack with its face up on a (single or double) click, and also support moving a subpile around. startmoving(event) -- begin a move operation finishmoving() -- finish a move operation """ def __init__(self, x, y, game=None): """Stack constructor. Arguments are the stack's nominal x and y position (the top left corner of the first card placed in the stack), and the game object (which is used to get the canvas; subclasses use the game object to find other stacks). """ self.x = x self.y = y self.game = game self.cards = [] self.group = Group(self.game.canvas) self.group.bind('<1>', self.clickhandler) self.group.bind('', self.doubleclickhandler) self.group.bind('', self.motionhandler) self.group.bind('', self.releasehandler) self.makebottom() def makebottom(self): pass def __repr__(self): """Return a string for debug print statements.""" return "%s(%d, %d)" % (self.__class__.__name__, self.x, self.y) # Public methods def add(self, card): self.cards.append(card) card.tkraise() self.position(card) self.group.addtag_withtag(card.group) def delete(self, card): self.cards.remove(card) card.group.dtag(self.group) def showtop(self): if self.cards: self.cards[-1].showface() def deal(self): if not self.cards: return None card = self.cards[-1] self.delete(card) return card # Subclass overridable methods def position(self, card): card.moveto(self.x, self.y) def userclickhandler(self): self.showtop() def userdoubleclickhandler(self): self.userclickhandler() def usermovehandler(self, cards): for card in cards: self.position(card) # Event handlers def clickhandler(self, event): self.finishmoving() # In case we lost an event self.userclickhandler() self.startmoving(event) def motionhandler(self, event): self.keepmoving(event) def releasehandler(self, event): self.keepmoving(event) self.finishmoving() def doubleclickhandler(self, event): self.finishmoving() # In case we lost an event self.userdoubleclickhandler() self.startmoving(event) # Move internals moving = None def startmoving(self, event): self.moving = None tags = self.game.canvas.gettags('current') for i in range(len(self.cards)): card = self.cards[i] if card.group.tag in tags: break else: return if not card.face_shown: return self.moving = self.cards[i:] self.lastx = event.x self.lasty = event.y for card in self.moving: card.tkraise() def keepmoving(self, event): if not self.moving: return dx = event.x - self.lastx dy = event.y - self.lasty self.lastx = event.x self.lasty = event.y if dx or dy: for card in self.moving: card.moveby(dx, dy) def finishmoving(self): cards = self.moving self.moving = None if cards: self.usermovehandler(cards) class Deck(Stack): """The deck is a stack with support for shuffling. New methods: fill() -- create the playing cards shuffle() -- shuffle the playing cards A single click moves the top card to the game's open deck and moves it face up; if we're out of cards, it moves the open deck back to the deck. """ def makebottom(self): bottom = Rectangle(self.game.canvas, self.x, self.y, self.x+CARDWIDTH, self.y+CARDHEIGHT, outline='black', fill=BACKGROUND) self.group.addtag_withtag(bottom) def fill(self): for suit in ALLSUITS: for value in ALLVALUES: self.add(Card(suit, value, self.game.canvas)) def shuffle(self): n = len(self.cards) newcards = [] for i in randperm(n): newcards.append(self.cards[i]) self.cards = newcards def userclickhandler(self): opendeck = self.game.opendeck card = self.deal() if not card: while 1: card = opendeck.deal() if not card: break self.add(card) card.showback() else: self.game.opendeck.add(card) card.showface() def randperm(n): """Function returning a random permutation of range(n).""" r = range(n) x = [] while r: i = random.choice(r) x.append(i) r.remove(i) return x class OpenStack(Stack): def acceptable(self, cards): return 0 def usermovehandler(self, cards): card = cards[0] stack = self.game.closeststack(card) if not stack or stack is self or not stack.acceptable(cards): Stack.usermovehandler(self, cards) else: for card in cards: self.delete(card) stack.add(card) self.game.wincheck() def userdoubleclickhandler(self): if not self.cards: return card = self.cards[-1] if not card.face_shown: self.userclickhandler() return for s in self.game.suits: if s.acceptable([card]): self.delete(card) s.add(card) self.game.wincheck() break class SuitStack(OpenStack): def makebottom(self): bottom = Rectangle(self.game.canvas, self.x, self.y, self.x+CARDWIDTH, self.y+CARDHEIGHT, outline='black', fill='') def userclickhandler(self): pass def userdoubleclickhandler(self): pass def acceptable(self, cards): if len(cards) != 1: return 0 card = cards[0] if not self.cards: return card.value == ACE topcard = self.cards[-1] return card.suit == topcard.suit and card.value == topcard.value + 1 class RowStack(OpenStack): def acceptable(self, cards): card = cards[0] if not self.cards: return card.value == KING topcard = self.cards[-1] if not topcard.face_shown: return 0 return card.color != topcard.color and card.value == topcard.value - 1 def position(self, card): y = self.y for c in self.cards: if c == card: break if c.face_shown: y = y + 2*MARGIN else: y = y + OFFSET card.moveto(self.x, y) class Solitaire: def __init__(self, master): self.master = master self.canvas = Canvas(self.master, background=BACKGROUND, highlightthickness=0, width=NROWS*XSPACING, height=3*YSPACING + 20 + MARGIN) self.canvas.pack(fill=BOTH, expand=TRUE) self.dealbutton = Button(self.canvas, text="Deal", highlightthickness=0, background=BACKGROUND, activebackground="green", command=self.deal) Window(self.canvas, MARGIN, 3*YSPACING + 20, window=self.dealbutton, anchor=SW) x = MARGIN y = MARGIN self.deck = Deck(x, y, self) x = x + XSPACING self.opendeck = OpenStack(x, y, self) x = x + XSPACING self.suits = [] for i in range(NSUITS): x = x + XSPACING self.suits.append(SuitStack(x, y, self)) x = MARGIN y = y + YSPACING self.rows = [] for i in range(NROWS): self.rows.append(RowStack(x, y, self)) x = x + XSPACING self.openstacks = [self.opendeck] + self.suits + self.rows self.deck.fill() self.deal() def wincheck(self): for s in self.suits: if len(s.cards) != NVALUES: return self.win() self.deal() def win(self): """Stupid animation when you win.""" cards = [] for s in self.openstacks: cards = cards + s.cards while cards: card = random.choice(cards) cards.remove(card) self.animatedmoveto(card, self.deck) def animatedmoveto(self, card, dest): for i in range(10, 0, -1): dx, dy = (dest.x-card.x)//i, (dest.y-card.y)//i card.moveby(dx, dy) self.master.update_idletasks() def closeststack(self, card): closest = None cdist = 999999999 # Since we only compare distances, # we don't bother to take the square root. for stack in self.openstacks: dist = (stack.x - card.x)**2 + (stack.y - card.y)**2 if dist < cdist: closest = stack cdist = dist return closest def deal(self): self.reset() self.deck.shuffle() for i in range(NROWS): for r in self.rows[i:]: card = self.deck.deal() r.add(card) for r in self.rows: r.showtop() def reset(self): for stack in self.openstacks: while 1: card = stack.deal() if not card: break self.deck.add(card) card.showback() # Main function, run when invoked as a stand-alone Python program. def main(): root = Tk() game = Solitaire(root) root.protocol('WM_DELETE_WINDOW', root.quit) root.mainloop() if __name__ == '__main__': main() PK%L]-88tkinter/guido/AttrDialog.pynu[ # The options of a widget are described by the following attributes # of the Pack and Widget dialogs: # # Dialog.current: {name: value} # -- changes during Widget's lifetime # # Dialog.options: {name: (default, klass)} # -- depends on widget class only # # Dialog.classes: {klass: (v0, v1, v2, ...) | 'boolean' | 'other'} # -- totally static, though different between PackDialog and WidgetDialog # (but even that could be unified) from Tkinter import * class Option: varclass = StringVar # May be overridden def __init__(self, dialog, option): self.dialog = dialog self.option = option self.master = dialog.top self.default, self.klass = dialog.options[option] self.var = self.varclass(self.master) self.frame = Frame(self.master) self.frame.pack(fill=X) self.label = Label(self.frame, text=(option + ":")) self.label.pack(side=LEFT) self.update() self.addoption() def refresh(self): self.dialog.refresh() self.update() def update(self): try: self.current = self.dialog.current[self.option] except KeyError: self.current = self.default self.var.set(self.current) def set(self, e=None): # Should be overridden pass class BooleanOption(Option): varclass = BooleanVar def addoption(self): self.button = Checkbutton(self.frame, text='on/off', onvalue=1, offvalue=0, variable=self.var, relief=RAISED, borderwidth=2, command=self.set) self.button.pack(side=RIGHT) class EnumOption(Option): def addoption(self): self.button = Menubutton(self.frame, textvariable=self.var, relief=RAISED, borderwidth=2) self.button.pack(side=RIGHT) self.menu = Menu(self.button) self.button['menu'] = self.menu for v in self.dialog.classes[self.klass]: self.menu.add_radiobutton( label=v, variable=self.var, value=v, command=self.set) class StringOption(Option): def addoption(self): self.entry = Entry(self.frame, textvariable=self.var, width=10, relief=SUNKEN, borderwidth=2) self.entry.pack(side=RIGHT, fill=X, expand=1) self.entry.bind('', self.set) class ReadonlyOption(Option): def addoption(self): self.label = Label(self.frame, textvariable=self.var, anchor=E) self.label.pack(side=RIGHT) class Dialog: def __init__(self, master): self.master = master self.fixclasses() self.refresh() self.top = Toplevel(self.master) self.top.title(self.__class__.__name__) self.top.minsize(1, 1) self.addchoices() def refresh(self): pass # Must override def fixclasses(self): pass # May override def addchoices(self): self.choices = {} list = [] for k, dc in self.options.items(): list.append((k, dc)) list.sort() for k, (d, c) in list: try: cl = self.classes[c] except KeyError: cl = 'unknown' if type(cl) == TupleType: cl = self.enumoption elif cl == 'boolean': cl = self.booleanoption elif cl == 'readonly': cl = self.readonlyoption else: cl = self.stringoption self.choices[k] = cl(self, k) # Must override: options = {} classes = {} # May override: booleanoption = BooleanOption stringoption = StringOption enumoption = EnumOption readonlyoption = ReadonlyOption class PackDialog(Dialog): def __init__(self, widget): self.widget = widget Dialog.__init__(self, widget) def refresh(self): self.current = self.widget.info() self.current['.class'] = self.widget.winfo_class() self.current['.name'] = self.widget._w class packoption: # Mix-in class def set(self, e=None): self.current = self.var.get() try: apply(self.dialog.widget.pack, (), {self.option: self.current}) except TclError, msg: print msg self.refresh() class booleanoption(packoption, BooleanOption): pass class enumoption(packoption, EnumOption): pass class stringoption(packoption, StringOption): pass class readonlyoption(packoption, ReadonlyOption): pass options = { '.class': (None, 'Class'), '.name': (None, 'Name'), 'after': (None, 'Widget'), 'anchor': ('center', 'Anchor'), 'before': (None, 'Widget'), 'expand': ('no', 'Boolean'), 'fill': ('none', 'Fill'), 'in': (None, 'Widget'), 'ipadx': (0, 'Pad'), 'ipady': (0, 'Pad'), 'padx': (0, 'Pad'), 'pady': (0, 'Pad'), 'side': ('top', 'Side'), } classes = { 'Anchor': (N, NE, E, SE, S, SW, W, NW, CENTER), 'Boolean': 'boolean', 'Class': 'readonly', 'Expand': 'boolean', 'Fill': (NONE, X, Y, BOTH), 'Name': 'readonly', 'Pad': 'pixel', 'Side': (TOP, RIGHT, BOTTOM, LEFT), 'Widget': 'readonly', } class RemotePackDialog(PackDialog): def __init__(self, master, app, widget): self.master = master self.app = app self.widget = widget self.refresh() self.top = Toplevel(self.master) self.top.title(self.app + ' PackDialog') self.top.minsize(1, 1) self.addchoices() def refresh(self): try: words = self.master.tk.splitlist( self.master.send(self.app, 'pack', 'info', self.widget)) except TclError, msg: print msg return dict = {} for i in range(0, len(words), 2): key = words[i][1:] value = words[i+1] dict[key] = value dict['.class'] = self.master.send(self.app, 'winfo', 'class', self.widget) dict['.name'] = self.widget self.current = dict class remotepackoption: # Mix-in class def set(self, e=None): self.current = self.var.get() try: self.dialog.master.send( self.dialog.app, 'pack', 'config', self.dialog.widget, '-'+self.option, self.dialog.master.tk.merge( self.current)) except TclError, msg: print msg self.refresh() class booleanoption(remotepackoption, BooleanOption): pass class enumoption(remotepackoption, EnumOption): pass class stringoption(remotepackoption, StringOption): pass class readonlyoption(remotepackoption, ReadonlyOption): pass class WidgetDialog(Dialog): def __init__(self, widget): self.widget = widget self.klass = widget.winfo_class() Dialog.__init__(self, widget) def fixclasses(self): if self.addclasses.has_key(self.klass): classes = {} for c in (self.classes, self.addclasses[self.klass]): for k in c.keys(): classes[k] = c[k] self.classes = classes def refresh(self): self.configuration = self.widget.config() self.update() self.current['.class'] = self.widget.winfo_class() self.current['.name'] = self.widget._w def update(self): self.current = {} self.options = {} for k, v in self.configuration.items(): if len(v) > 4: self.current[k] = v[4] self.options[k] = v[3], v[2] # default, klass self.options['.class'] = (None, 'Class') self.options['.name'] = (None, 'Name') class widgetoption: # Mix-in class def set(self, e=None): self.current = self.var.get() try: self.dialog.widget[self.option] = self.current except TclError, msg: print msg self.refresh() class booleanoption(widgetoption, BooleanOption): pass class enumoption(widgetoption, EnumOption): pass class stringoption(widgetoption, StringOption): pass class readonlyoption(widgetoption, ReadonlyOption): pass # Universal classes classes = { 'Anchor': (N, NE, E, SE, S, SW, W, NW, CENTER), 'Aspect': 'integer', 'Background': 'color', 'Bitmap': 'bitmap', 'BorderWidth': 'pixel', 'Class': 'readonly', 'CloseEnough': 'double', 'Command': 'command', 'Confine': 'boolean', 'Cursor': 'cursor', 'CursorWidth': 'pixel', 'DisabledForeground': 'color', 'ExportSelection': 'boolean', 'Font': 'font', 'Foreground': 'color', 'From': 'integer', 'Geometry': 'geometry', 'Height': 'pixel', 'InsertWidth': 'time', 'Justify': (LEFT, CENTER, RIGHT), 'Label': 'string', 'Length': 'pixel', 'MenuName': 'widget', 'Name': 'readonly', 'OffTime': 'time', 'OnTime': 'time', 'Orient': (HORIZONTAL, VERTICAL), 'Pad': 'pixel', 'Relief': (RAISED, SUNKEN, FLAT, RIDGE, GROOVE), 'RepeatDelay': 'time', 'RepeatInterval': 'time', 'ScrollCommand': 'command', 'ScrollIncrement': 'pixel', 'ScrollRegion': 'rectangle', 'ShowValue': 'boolean', 'SetGrid': 'boolean', 'Sliderforeground': 'color', 'SliderLength': 'pixel', 'Text': 'string', 'TickInterval': 'integer', 'To': 'integer', 'Underline': 'index', 'Variable': 'variable', 'Value': 'string', 'Width': 'pixel', 'Wrap': (NONE, CHAR, WORD), } # Classes that (may) differ per widget type _tristate = {'State': (NORMAL, ACTIVE, DISABLED)} _bistate = {'State': (NORMAL, DISABLED)} addclasses = { 'Button': _tristate, 'Radiobutton': _tristate, 'Checkbutton': _tristate, 'Entry': _bistate, 'Text': _bistate, 'Menubutton': _tristate, 'Slider': _bistate, } class RemoteWidgetDialog(WidgetDialog): def __init__(self, master, app, widget): self.app = app self.widget = widget self.klass = master.send(self.app, 'winfo', 'class', self.widget) Dialog.__init__(self, master) def refresh(self): try: items = self.master.tk.splitlist( self.master.send(self.app, self.widget, 'config')) except TclError, msg: print msg return dict = {} for item in items: words = self.master.tk.splitlist(item) key = words[0][1:] value = (key,) + words[1:] dict[key] = value self.configuration = dict self.update() self.current['.class'] = self.klass self.current['.name'] = self.widget class remotewidgetoption: # Mix-in class def set(self, e=None): self.current = self.var.get() try: self.dialog.master.send( self.dialog.app, self.dialog.widget, 'config', '-'+self.option, self.current) except TclError, msg: print msg self.refresh() class booleanoption(remotewidgetoption, BooleanOption): pass class enumoption(remotewidgetoption, EnumOption): pass class stringoption(remotewidgetoption, StringOption): pass class readonlyoption(remotewidgetoption, ReadonlyOption): pass def test(): import sys root = Tk() root.minsize(1, 1) if sys.argv[1:]: remotetest(root, sys.argv[1]) else: frame = Frame(root, name='frame') frame.pack(expand=1, fill=BOTH) button = Button(frame, name='button', text='button') button.pack(expand=1) canvas = Canvas(frame, name='canvas') canvas.pack() fpd = PackDialog(frame) fwd = WidgetDialog(frame) bpd = PackDialog(button) bwd = WidgetDialog(button) cpd = PackDialog(canvas) cwd = WidgetDialog(canvas) root.mainloop() def remotetest(root, app): from listtree import listtree list = listtree(root, app) list.bind('', opendialogs) list.app = app # Pass it on to handler def opendialogs(e): import string list = e.widget sel = list.curselection() for i in sel: item = list.get(i) widget = string.split(item)[0] RemoteWidgetDialog(list, list.app, widget) if widget == '.': continue try: RemotePackDialog(list, list.app, widget) except TclError, msg: print msg test() PK%L]-ɖ55tkinter/guido/mbox.pynuȯ#! /usr/bin/python2.7 # Scan MH folder, display results in window import os import sys import re import getopt import string import mhlib from Tkinter import * from dialog import dialog mailbox = os.environ['HOME'] + '/Mail' def main(): global root, tk, top, mid, bot global folderbox, foldermenu, scanbox, scanmenu, viewer global folder, seq global mh, mhf # Parse command line options folder = 'inbox' seq = 'all' try: opts, args = getopt.getopt(sys.argv[1:], '') except getopt.error, msg: print msg sys.exit(2) for arg in args: if arg[:1] == '+': folder = arg[1:] else: seq = arg # Initialize MH mh = mhlib.MH() mhf = mh.openfolder(folder) # Build widget hierarchy root = Tk() tk = root.tk top = Frame(root) top.pack({'expand': 1, 'fill': 'both'}) # Build right part: folder list right = Frame(top) right.pack({'fill': 'y', 'side': 'right'}) folderbar = Scrollbar(right, {'relief': 'sunken', 'bd': 2}) folderbar.pack({'fill': 'y', 'side': 'right'}) folderbox = Listbox(right, {'exportselection': 0}) folderbox.pack({'expand': 1, 'fill': 'both', 'side': 'left'}) foldermenu = Menu(root) foldermenu.add('command', {'label': 'Open Folder', 'command': open_folder}) foldermenu.add('separator') foldermenu.add('command', {'label': 'Quit', 'command': 'exit'}) foldermenu.bind('', folder_unpost) folderbox['yscrollcommand'] = (folderbar, 'set') folderbar['command'] = (folderbox, 'yview') folderbox.bind('', open_folder, 1) folderbox.bind('<3>', folder_post) # Build left part: scan list left = Frame(top) left.pack({'expand': 1, 'fill': 'both', 'side': 'left'}) scanbar = Scrollbar(left, {'relief': 'sunken', 'bd': 2}) scanbar.pack({'fill': 'y', 'side': 'right'}) scanbox = Listbox(left, {'font': 'fixed'}) scanbox.pack({'expand': 1, 'fill': 'both', 'side': 'left'}) scanmenu = Menu(root) scanmenu.add('command', {'label': 'Open Message', 'command': open_message}) scanmenu.add('command', {'label': 'Remove Message', 'command': remove_message}) scanmenu.add('command', {'label': 'Refile Message', 'command': refile_message}) scanmenu.add('separator') scanmenu.add('command', {'label': 'Quit', 'command': 'exit'}) scanmenu.bind('', scan_unpost) scanbox['yscrollcommand'] = (scanbar, 'set') scanbar['command'] = (scanbox, 'yview') scanbox.bind('', open_message) scanbox.bind('<3>', scan_post) # Separator between middle and bottom part rule2 = Frame(root, {'bg': 'black'}) rule2.pack({'fill': 'x'}) # Build bottom part: current message bot = Frame(root) bot.pack({'expand': 1, 'fill': 'both'}) # viewer = None # Window manager commands root.minsize(800, 1) # Make window resizable # Fill folderbox with text setfolders() # Fill scanbox with text rescan() # Enter mainloop root.mainloop() def folder_post(e): x, y = e.x_root, e.y_root foldermenu.post(x - 10, y - 10) foldermenu.grab_set() def folder_unpost(e): tk.call('update', 'idletasks') foldermenu.grab_release() foldermenu.unpost() foldermenu.invoke('active') def scan_post(e): x, y = e.x_root, e.y_root scanmenu.post(x - 10, y - 10) scanmenu.grab_set() def scan_unpost(e): tk.call('update', 'idletasks') scanmenu.grab_release() scanmenu.unpost() scanmenu.invoke('active') scanparser = re.compile('^ *([0-9]+)') def open_folder(e=None): global folder, mhf sel = folderbox.curselection() if len(sel) != 1: if len(sel) > 1: msg = "Please open one folder at a time" else: msg = "Please select a folder to open" dialog(root, "Can't Open Folder", msg, "", 0, "OK") return i = sel[0] folder = folderbox.get(i) mhf = mh.openfolder(folder) rescan() def open_message(e=None): global viewer sel = scanbox.curselection() if len(sel) != 1: if len(sel) > 1: msg = "Please open one message at a time" else: msg = "Please select a message to open" dialog(root, "Can't Open Message", msg, "", 0, "OK") return cursor = scanbox['cursor'] scanbox['cursor'] = 'watch' tk.call('update', 'idletasks') i = sel[0] line = scanbox.get(i) if scanparser.match(line) >= 0: num = string.atoi(scanparser.group(1)) m = mhf.openmessage(num) if viewer: viewer.destroy() from MimeViewer import MimeViewer viewer = MimeViewer(bot, '+%s/%d' % (folder, num), m) viewer.pack() viewer.show() scanbox['cursor'] = cursor def interestingheader(header): return header != 'received' def remove_message(e=None): itop = scanbox.nearest(0) sel = scanbox.curselection() if not sel: dialog(root, "No Message To Remove", "Please select a message to remove", "", 0, "OK") return todo = [] for i in sel: line = scanbox.get(i) if scanparser.match(line) >= 0: todo.append(string.atoi(scanparser.group(1))) mhf.removemessages(todo) rescan() fixfocus(min(todo), itop) lastrefile = '' tofolder = None def refile_message(e=None): global lastrefile, tofolder itop = scanbox.nearest(0) sel = scanbox.curselection() if not sel: dialog(root, "No Message To Refile", "Please select a message to refile", "", 0, "OK") return foldersel = folderbox.curselection() if len(foldersel) != 1: if not foldersel: msg = "Please select a folder to refile to" else: msg = "Please select exactly one folder to refile to" dialog(root, "No Folder To Refile", msg, "", 0, "OK") return refileto = folderbox.get(foldersel[0]) todo = [] for i in sel: line = scanbox.get(i) if scanparser.match(line) >= 0: todo.append(string.atoi(scanparser.group(1))) if lastrefile != refileto or not tofolder: lastrefile = refileto tofolder = None tofolder = mh.openfolder(lastrefile) mhf.refilemessages(todo, tofolder) rescan() fixfocus(min(todo), itop) def fixfocus(near, itop): n = scanbox.size() for i in range(n): line = scanbox.get(repr(i)) if scanparser.match(line) >= 0: num = string.atoi(scanparser.group(1)) if num >= near: break else: i = 'end' scanbox.select_from(i) scanbox.yview(itop) def setfolders(): folderbox.delete(0, 'end') for fn in mh.listallfolders(): folderbox.insert('end', fn) def rescan(): global viewer if viewer: viewer.destroy() viewer = None scanbox.delete(0, 'end') for line in scanfolder(folder, seq): scanbox.insert('end', line) def scanfolder(folder = 'inbox', sequence = 'all'): return map( lambda line: line[:-1], os.popen('scan +%s %s' % (folder, sequence), 'r').readlines()) main() PK%L]%Ltkinter/guido/brownian2.pyonu[ ^c@sddlTddlZddlZdZdZdZdZdZdZdZ da da d Z d Zd Zed krendS( i(t*Nii,i itrediccst}tjtdt}tjtdt}|j||||||||dt}x_tstjdt }tjdt }y|j |||Wnt k rPqcXdVqcWdS(Ng@tfilli( tRADIUStrandomtgausstWIDTHtSIGMAtHEIGHTt create_ovaltFILLtstoptBUZZtmovetTclErrortNone(tcanvastrtxtytptdxtdy((s4/usr/lib64/python2.7/Demo/tkinter/guido/brownian2.pytparticles.  cCs:|jtjt}tjt|dt|dS(Ni(tnextRt expovariatetLAMBDAtroottaftertintR (Rtdt((s4/usr/lib64/python2.7/Demo/tkinter/guido/brownian2.pyR "s cCstattdtdt}|jddddd}tjdr`ttjd}nx$t |D]}t t |qmWztj Wdda XdS(NtwidththeightRtbothtexpandii(tTkRtCanvasRRtpacktsystargvRtrangeR RtmainloopR (Rtnpti((s4/usr/lib64/python2.7/Demo/tkinter/guido/brownian2.pytmain's  t__main__(tTkinterRR&RRRR RRR R RRRR R,t__name__(((s4/usr/lib64/python2.7/Demo/tkinter/guido/brownian2.pyts       PK%L]o o tkinter/guido/dialog.pyonu[ Afc@sKddlTddlZdZdZdZedkrGendS(i(t*NcGst|dd}|j||jdt|dtdd}|jdtdtt|dtdd}|jdtdtt |dd d |d d } | jdt d ddtdddd|rt |d|} | jdt ddddnt } g} d} x|D]}t|d |d| | d}| j|| |krt|dtdd}|jdt d ddddd|j|jd|dt ddddddddn.|jdt d ddddddddd| d} q!W|dkrA|jd| || |dn|j}|j|j|j| |j|r|jn| jS(Ntclass_tDialogtrelieft borderwidthitsidetfilltwidtht3ittexttfonts$-Adobe-Times-Medium-R-Normal-*-180-*texpandtpadxt3mtpadytbitmapitcommandcSs |j|S(N(tset(tvti((s1/usr/lib64/python2.7/Demo/tkinter/guido/dialog.pyt(tt2mtin_tipadxtipadyt1mscSs|j|j|fS(N(tflashR(tetbRR((s1/usr/lib64/python2.7/Demo/tkinter/guido/dialog.pyR:s (tToplevelttitleticonnametFrametRAISEDtpacktTOPtBOTHtBOTTOMtMessagetRIGHTtLabeltLEFTtIntVartButtontappendtSUNKENtlifttbindt focus_gettgrab_sett focus_settwaitvartdestroytget(tmasterRR RtdefaulttargstwttoptbottmsgtbmtvartbuttonsRtbutRtbdtoldFocus((s1/usr/lib64/python2.7/Demo/tkinter/guido/dialog.pytdialog sN   (  !  "         c CsRttddddd}dG|GHttddd d d d d }dG|GHdS(NsNot Respondings=The file server isn't responding right now; I'll keep trying.RitOKspressed buttons File ModifiedswFile "tcl.h" has been modified since the last time it was saved. Do you want to save it before exiting the application?twarningis Save FilesDiscard ChangessReturn To Editor(RDt mainWidget(R((s1/usr/lib64/python2.7/Demo/tkinter/guido/dialog.pytgoLs    cCs}ddl}tatjtttdddt}|jttddd|j}|jdt tj dS(NiR sPress Here To StartRtExitR( tsysR!RGtPacktconfigR,RHR#texitR%tmainloop(RJtstarttendit((s1/usr/lib64/python2.7/Demo/tkinter/guido/dialog.pyttestas    t__main__(tTkinterRJRDRHRQt__name__(((s1/usr/lib64/python2.7/Demo/tkinter/guido/dialog.pyts   A  PK%L]~H+tkinter/guido/ShellWindow.pyonu[ ^c@sddlZddlZddlZddlTddlmZddlmZddlZdZdefdYZdZ d Z d Z e d kre ndS( iN(t*(t ScrolledText(tDialogit ShellWindowcBsheZd d dZdZdZdZdZdZdZ dZ dZ d Z RS( cKs|s>ytjd}Wntk r0d}nX|d}ntj|}|d}ttj||f|d|_|j d|j |j d|j |j d|j |j d |j |j d |jt||\|_|_|_|jj|jt|jdS( NtSHELLs/bin/shs -iis1.0ss s s s (tostenvirontKeyErrortstringtsplittapplyRt__init__tpostbindt inputhandlertsiginttsigtermtsigkilltsendeoftspawntpidt fromchildttochildttktcreatefilehandlertREADABLEt outputhandler(tselftmastertshelltcnftargs((s6/usr/lib64/python2.7/Demo/tkinter/guido/ShellWindow.pyR s$     !c Cstj|t}|s|jj|tj|jd\}}dG|GdG|GHd|_|d?}|d@}|dkrd|}n%d|d@}|d @r|d }nt|j d |d d dddddddS|j t ||j d|_ |jt dS(NiRtstatusiisexit status %dskilled by signal %diis -- core dumpedttextttitles Exit statustbitmaptwarningtdefaulttstringstOKs end - 1 char(R'(RtreadtBUFSIZERtdeletefilehandlertwaitpidRtNoneRRtinserttENDtindexR tyview_pickplace( RtfiletmasktdataRtststdetailtcausetmsg((s6/usr/lib64/python2.7/Demo/tkinter/guido/ShellWindow.pyR#s.        cGse|js|jdS|jtd|j|jd}|jt|_tj|j |dS(Ntbreaks s end - 1 char( Rt no_processR-R.tgetR R/RtwriteR(RRtline((s6/usr/lib64/python2.7/Demo/tkinter/guido/ShellWindow.pyR=s  cGs+|js|jdStj|jdS(NR8(RR9RtcloseR(RR((s6/usr/lib64/python2.7/Demo/tkinter/guido/ShellWindow.pyRGs   cCs.|js|jdStj|j|dS(NR8(RR9Rtkill(Rtsig((s6/usr/lib64/python2.7/Demo/tkinter/guido/ShellWindow.pytsendsigNs   cGs|jtjS(N(R@tsignaltSIGINT(RR((s6/usr/lib64/python2.7/Demo/tkinter/guido/ShellWindow.pyRUscGs|jtjS(N(R@RAtSIGQUIT(RR((s6/usr/lib64/python2.7/Demo/tkinter/guido/ShellWindow.pytsigquitXscGs|jtjS(N(R@RAtSIGTERM(RR((s6/usr/lib64/python2.7/Demo/tkinter/guido/ShellWindow.pyR[scGs|jtjS(N(R@RAtSIGKILL(RR((s6/usr/lib64/python2.7/Demo/tkinter/guido/ShellWindow.pyR^sc Cs/t|jddddddddd d dS( NR!sNo active processR"s No processR#terrorR%iR&R'(R'(RR(R((s6/usr/lib64/python2.7/Demo/tkinter/guido/ShellWindow.pyR9as  N( t__name__t __module__R,R RRRR@RRDRRR9(((s6/usr/lib64/python2.7/Demo/tkinter/guido/ShellWindow.pyR s       idcCs\tj\}}tj\}}tj}|dkr5x6dD].}ytj|WqCtjk rpqCXqCWtj|dkrtjjdntj|dkrtjjdntj|dkrtjjdntj dt ztj ||Wdtjjdtj dXntj|tj||||fS( Niiispopen2: bad read dup spopen2: bad write dup isexecvp failed (iii( RtpipetforkR=RGtduptsyststderrR;t closerangetMAXFDtexecvpt_exit(tprogRtp2creadtp2cwritetc2preadtc2pwriteRti((s6/usr/lib64/python2.7/Demo/tkinter/guido/ShellWindow.pyRks.     cCstjtjd}t}|jdd|rJt|d|}n t|}|jdddt|j |j j dS(NiRtexpandtfill( RtjoinRMtargvtTktminsizeRtpacktBOTHt focus_setRtmainloop(Rtroottw((s6/usr/lib64/python2.7/Demo/tkinter/guido/ShellWindow.pyttests   t__main__( RRMRtTkinterRRRAR)RRPRReRH(((s6/usr/lib64/python2.7/Demo/tkinter/guido/ShellWindow.pyts     ^  PK%L])tMIMItkinter/guido/AttrDialog.pyonu[ ^c@sddlTdddYZdefdYZdefdYZdefd YZd efd YZd dd YZdefdYZdefdYZdefdYZ de fdYZ dZ dZ dZ e dS(i(t*tOptioncBs5eZeZdZdZdZddZRS(cCs||_||_|j|_|j|\|_|_|j|j|_t |j|_ |j j dt t |j d|d|_|jj dt|j|jdS(Ntfillttextt:tside(tdialogtoptionttoptmastertoptionstdefaulttklasstvarclasstvartFrametframetpacktXtLabeltlabeltLEFTtupdatet addoption(tselfRR((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyt__init__s    cCs|jj|jdS(N(RtrefreshR(R((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyR"s cCsQy|jj|j|_Wntk r9|j|_nX|jj|jdS(N(RtcurrentRtKeyErrorR Rtset(R((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyR&s  cCsdS(N((Rte((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyR-sN( t__name__t __module__t StringVarR RRRtNoneR(((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyRs   t BooleanOptioncBseZeZdZRS(cCsYt|jddddddd|jdtd d d |j|_|jjd tdS( NRson/offtonvalueitoffvalueitvariabletrelieft borderwidthitcommandR(t CheckbuttonRRtRAISEDRtbuttonRtRIGHT(R((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyR4s  (RR t BooleanVarR R(((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyR#0st EnumOptioncBseZdZRS(c Cst|jd|jdtdd|_|jjdtt|j|_|j|jd( tEntryRRtSUNKENtentryRR-RtbindR(R((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyRQs   (RR R(((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyR8OstReadonlyOptioncBseZdZRS(cCs8t|jd|jdt|_|jjdtdS(NR0tanchorR(RRRtERRR-(R((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyR\s (RR R(((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyR?ZstDialogcBsPeZdZdZdZdZiZiZeZ e Z e Z eZRS(cCsf||_|j|jt|j|_|jj|jj|jjdd|j dS(Ni( R t fixclassesRtToplevelRttitlet __class__Rtminsizet addchoices(RR ((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyRcs   cCsdS(N((R((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyRltcCsdS(N((R((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyRCnRIcCsi|_g}x0|jjD]\}}|j||fqW|jx|D]\}\}}y|j|}Wntk rd}nXt|tkr|j }n9|dkr|j }n!|dkr|j }n |j }||||j|    "tRemotePackDialogcBseZdZdZdd dYZdeefdYZdeefdYZdee fd YZ d ee fd YZ RS( cCso||_||_||_|jt|j|_|jj|jd|jjdd|jdS(Ns PackDialogi( R tappR^RRDRRERGRH(RR RR^((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyRs    cCsy4|jjj|jj|jdd|j}Wntk rO}|GHdSXi}xFtdt|dD],}||d}||d}|||6dd?6dd@6ddA6ddB6d.dC6ddD6ddE6dFdG6dHdI6d.dJ6ddK6e!e"e#fdL6Z$ie%e&e'fdM6Z(ie%e'fdM6Z)ie(dN6e(dO6e(dP6e)dQ6e)dC6e(dR6e)dS6Z*RS(UcCs,||_|j|_tj||dS(N(R^R`R RBR(RR^((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyRs cCst|jj|jrpi}xF|j|j|jfD]+}x"|jD]}||||(RR>t opendialogsR(RRRRW((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyRscCsddl}|j}|j}x|D]}|j|}|j|d}t||j||dkruq(nyt||j|Wq(tk r}|GHq(Xq(WdS(Niit.( RR^t curselectionRctsplitRRRRe(RRRWtselRRR^Rf((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyRs     N(((tTkinterRR#R/R8R?RBR]RRRRRR(((s5/usr/lib64/python2.7/Demo/tkinter/guido/AttrDialog.pyts  .67m2   PK%L]`&CCtkinter/guido/brownian.pynu[# Brownian motion -- an example of a multi-threaded Tkinter program. from Tkinter import * import random import threading import time import sys WIDTH = 400 HEIGHT = 300 SIGMA = 10 BUZZ = 2 RADIUS = 2 LAMBDA = 10 FILL = 'red' stop = 0 # Set when main loop exits def particle(canvas): r = RADIUS x = random.gauss(WIDTH/2.0, SIGMA) y = random.gauss(HEIGHT/2.0, SIGMA) p = canvas.create_oval(x-r, y-r, x+r, y+r, fill=FILL) while not stop: dx = random.gauss(0, BUZZ) dy = random.gauss(0, BUZZ) dt = random.expovariate(LAMBDA) try: canvas.move(p, dx, dy) except TclError: break time.sleep(dt) def main(): global stop root = Tk() canvas = Canvas(root, width=WIDTH, height=HEIGHT) canvas.pack(fill='both', expand=1) np = 30 if sys.argv[1:]: np = int(sys.argv[1]) for i in range(np): t = threading.Thread(target=particle, args=(canvas,)) t.start() try: root.mainloop() finally: stop = 1 main() PK%L] 7E tkinter/guido/mbox.pyonu[ Afc@s)ddlZddlZddlZddlZddlZddlZddlTddlmZejddZ dZ dZ dZ d Z d Zejd Zdd Zdd ZdZddZdadaddZdZdZdZdddZe dS(iN(t*(tdialogtHOMEs/Mailc Cs#daday#tjtjdd\}}Wn(tjk rY}|GHtjdnXx1|D])}|d dkr|daqa|aqaWtja t j ta t a t jatt atjidd6dd 6tt}|jid d 6d d 6t|id d6dd6}|jid d 6d d 6t|idd6atjidd6dd 6dd 6tt atjdidd6td6tjdtjdidd6dd6tjdt|dftdtsettyscrollcommandtyviews s<3>tfixedtfonts Open MessagesRemove MessagesRefile Messagetblacktbgtxi (*tfoldertseqtgetopttsystargvterrorRtmhlibtMHtmht openfoldertmhftTktrootttktFramettoptpackt ScrollbartListboxt folderboxtMenut foldermenutaddt open_foldertbindt folder_unpostt folder_posttscanboxtscanmenut open_messagetremove_messagetrefile_messaget scan_unpostt scan_posttbottNonetviewertminsizet setfolderstrescantmainloop( toptstargstmsgtargR t folderbarRtscanbartrule2((s//usr/lib64/python2.7/Demo/tkinter/guido/mbox.pytmains#        "         ""               cCs9|j|j}}tj|d|dtjdS(Ni (tx_rootty_rootR4tposttgrab_set(teRR ((s//usr/lib64/python2.7/Demo/tkinter/guido/mbox.pyR9scCs5tjddtjtjtjddS(Ntupdatet idletaskstactive(R,tcallR4t grab_releasetunposttinvoke(RT((s//usr/lib64/python2.7/Demo/tkinter/guido/mbox.pyR8s  cCs9|j|j}}tj|d|dtjdS(Ni (RPRQR;RRRS(RTRR ((s//usr/lib64/python2.7/Demo/tkinter/guido/mbox.pyR@scCs5tjddtjtjtjddS(NRURVRW(R,RXR;RYRZR[(RT((s//usr/lib64/python2.7/Demo/tkinter/guido/mbox.pyR?s  s ^ *([0-9]+)cCstj}t|dkr\t|dkr9d}nd}ttd|ddddS|d}tj|atjta t dS(Nis Please open one folder at a timesPlease select a folder to opensCan't Open FolderRitOK( R2t curselectiontlenRR+tgetRR'R(R)RF(RTtselRJti((s//usr/lib64/python2.7/Demo/tkinter/guido/mbox.pyR6s   c Cs9tj}t|dkr\t|dkr9d}nd}ttd|ddddStd}d tdttddddddSg}xT|D]L}tj|}tj|dkrK|jt j tj dqKqKWt j |ttt||dS(NisNo Message To Removes!Please select a message to removeRR\i(R:tnearestR]RR+R_ReRftappendRgRhRiR)tremovemessagesRFtfixfocustmin(RTtitopR`ttodoRaRm((s//usr/lib64/python2.7/Demo/tkinter/guido/mbox.pyR=s   & Rc Cs]tjd}tj}|s>ttddddddStj}t|dkr|skd}nd}ttd |ddddStj|d}g}xT|D]L}tj|}tj |dkr|j t j tj dqqWt|kst r/|adatjtantj|tttt||dS( NisNo Message To Refiles!Please select a message to refileRR\is#Please select a folder to refile tos-Please select exactly one folder to refile tosNo Folder To Refile(R:RsR]RR+R2R^R_ReRfRtRgRhRit lastrefilettofolderRBR'R(R)trefilemessagesRFRvRw( RTRxR`t folderselRJtrefiletoRyRaRm((s//usr/lib64/python2.7/Demo/tkinter/guido/mbox.pyR>s4     &cCstj}xot|D][}tjt|}tj|dkrtjtj d}||krtPqtqqWd}tj |tj |dS(Niitend( R:tsizetrangeR_treprReRfRgRhRit select_fromR(tnearRxtnRaRmRn((s//usr/lib64/python2.7/Demo/tkinter/guido/mbox.pyRvs    cCs;tjddx$tjD]}tjd|qWdS(NiR(R2tdeleteR'tlistallfolderstinsert(tfn((s//usr/lib64/python2.7/Demo/tkinter/guido/mbox.pyRE scCsWtrtjdantjddx'tttD]}tjd|q9WdS(NiR( RCRkRBR:Rt scanfolderRR R(Rm((s//usr/lib64/python2.7/Demo/tkinter/guido/mbox.pyRFs   RRcCs,tdtjd||fdjS(NcSs|d S(Ni((Rm((s//usr/lib64/python2.7/Demo/tkinter/guido/mbox.pytRs scan +%s %str(tmaptostpopent readlines(Rtsequence((s//usr/lib64/python2.7/Demo/tkinter/guido/mbox.pyRs(RR"treR!RgR%tTkinterRtenvirontmailboxROR9R8R@R?tcompileReRBR6R<RrR=RzR{R>RvRERFR(((s//usr/lib64/python2.7/Demo/tkinter/guido/mbox.pyts4        x           PK%L]LLtkinter/guido/ShellWindow.pynu[import os import sys import string from Tkinter import * from ScrolledText import ScrolledText from Dialog import Dialog import signal BUFSIZE = 512 class ShellWindow(ScrolledText): def __init__(self, master=None, shell=None, **cnf): if not shell: try: shell = os.environ['SHELL'] except KeyError: shell = '/bin/sh' shell = shell + ' -i' args = string.split(shell) shell = args[0] apply(ScrolledText.__init__, (self, master), cnf) self.pos = '1.0' self.bind('', self.inputhandler) self.bind('', self.sigint) self.bind('', self.sigterm) self.bind('', self.sigkill) self.bind('', self.sendeof) self.pid, self.fromchild, self.tochild = spawn(shell, args) self.tk.createfilehandler(self.fromchild, READABLE, self.outputhandler) def outputhandler(self, file, mask): data = os.read(file, BUFSIZE) if not data: self.tk.deletefilehandler(file) pid, sts = os.waitpid(self.pid, 0) print 'pid', pid, 'status', sts self.pid = None detail = sts>>8 cause = sts & 0xff if cause == 0: msg = "exit status %d" % detail else: msg = "killed by signal %d" % (cause & 0x7f) if cause & 0x80: msg = msg + " -- core dumped" Dialog(self.master, text=msg, title="Exit status", bitmap='warning', default=0, strings=('OK',)) return self.insert(END, data) self.pos = self.index("end - 1 char") self.yview_pickplace(END) def inputhandler(self, *args): if not self.pid: self.no_process() return "break" self.insert(END, "\n") line = self.get(self.pos, "end - 1 char") self.pos = self.index(END) os.write(self.tochild, line) return "break" def sendeof(self, *args): if not self.pid: self.no_process() return "break" os.close(self.tochild) return "break" def sendsig(self, sig): if not self.pid: self.no_process() return "break" os.kill(self.pid, sig) return "break" def sigint(self, *args): return self.sendsig(signal.SIGINT) def sigquit(self, *args): return self.sendsig(signal.SIGQUIT) def sigterm(self, *args): return self.sendsig(signal.SIGTERM) def sigkill(self, *args): return self.sendsig(signal.SIGKILL) def no_process(self): Dialog(self.master, text="No active process", title="No process", bitmap='error', default=0, strings=('OK',)) MAXFD = 100 # Max number of file descriptors (os.getdtablesize()???) def spawn(prog, args): p2cread, p2cwrite = os.pipe() c2pread, c2pwrite = os.pipe() pid = os.fork() if pid == 0: # Child for i in 0, 1, 2: try: os.close(i) except os.error: pass if os.dup(p2cread) <> 0: sys.stderr.write('popen2: bad read dup\n') if os.dup(c2pwrite) <> 1: sys.stderr.write('popen2: bad write dup\n') if os.dup(c2pwrite) <> 2: sys.stderr.write('popen2: bad write dup\n') os.closerange(3, MAXFD) try: os.execvp(prog, args) finally: sys.stderr.write('execvp failed\n') os._exit(1) os.close(p2cread) os.close(c2pwrite) return pid, c2pread, p2cwrite def test(): shell = string.join(sys.argv[1:]) root = Tk() root.minsize(1, 1) if shell: w = ShellWindow(root, shell=shell) else: w = ShellWindow(root) w.pack(expand=1, fill=BOTH) w.focus_set() w.tk.mainloop() if __name__ == '__main__': test() PK%L]&Ytkinter/guido/listtree.pyonu[ ^c@sWddlZddlZddlTdZdZdZedkrSendS(iN(t*cCs?t|dd}|jdddtt||dd|S(Ntnametlisttexpanditfillt.i(tListboxtpacktBOTHt listnodes(tmastertappR((s3/usr/lib64/python2.7/Demo/tkinter/guido/listtree.pytlisttreescCs|j|dd|}|jtd||f|jj|j|dd|}x%|D]}t||||dq]WdS(Ntwinfotclasss%s (%s)tchildreni(tsendtinserttENDttkt splitlistR (RR twidgettleveltklassRtc((s3/usr/lib64/python2.7/Demo/tkinter/guido/listtree.pyR s   cCstjds-tjjdtjdntjd}t}|jddt|dd}|jdddt t ||}|j dS(NisUsage: listtree appname iRtfRR( tsystargvtstderrtwritetexittTktminsizetFrameRRR tmainloop(R RRR((s3/usr/lib64/python2.7/Demo/tkinter/guido/listtree.pytmains   t__main__(RtstringtTkinterR R R#t__name__(((s3/usr/lib64/python2.7/Demo/tkinter/guido/listtree.pyts     PK%L]~H+tkinter/guido/ShellWindow.pycnu[ ^c@sddlZddlZddlZddlTddlmZddlmZddlZdZdefdYZdZ d Z d Z e d kre ndS( iN(t*(t ScrolledText(tDialogit ShellWindowcBsheZd d dZdZdZdZdZdZdZ dZ dZ d Z RS( cKs|s>ytjd}Wntk r0d}nX|d}ntj|}|d}ttj||f|d|_|j d|j |j d|j |j d|j |j d |j |j d |jt||\|_|_|_|jj|jt|jdS( NtSHELLs/bin/shs -iis1.0ss s s s (tostenvirontKeyErrortstringtsplittapplyRt__init__tpostbindt inputhandlertsiginttsigtermtsigkilltsendeoftspawntpidt fromchildttochildttktcreatefilehandlertREADABLEt outputhandler(tselftmastertshelltcnftargs((s6/usr/lib64/python2.7/Demo/tkinter/guido/ShellWindow.pyR s$     !c Cstj|t}|s|jj|tj|jd\}}dG|GdG|GHd|_|d?}|d@}|dkrd|}n%d|d@}|d @r|d }nt|j d |d d dddddddS|j t ||j d|_ |jt dS(NiRtstatusiisexit status %dskilled by signal %diis -- core dumpedttextttitles Exit statustbitmaptwarningtdefaulttstringstOKs end - 1 char(R'(RtreadtBUFSIZERtdeletefilehandlertwaitpidRtNoneRRtinserttENDtindexR tyview_pickplace( RtfiletmasktdataRtststdetailtcausetmsg((s6/usr/lib64/python2.7/Demo/tkinter/guido/ShellWindow.pyR#s.        cGse|js|jdS|jtd|j|jd}|jt|_tj|j |dS(Ntbreaks s end - 1 char( Rt no_processR-R.tgetR R/RtwriteR(RRtline((s6/usr/lib64/python2.7/Demo/tkinter/guido/ShellWindow.pyR=s  cGs+|js|jdStj|jdS(NR8(RR9RtcloseR(RR((s6/usr/lib64/python2.7/Demo/tkinter/guido/ShellWindow.pyRGs   cCs.|js|jdStj|j|dS(NR8(RR9Rtkill(Rtsig((s6/usr/lib64/python2.7/Demo/tkinter/guido/ShellWindow.pytsendsigNs   cGs|jtjS(N(R@tsignaltSIGINT(RR((s6/usr/lib64/python2.7/Demo/tkinter/guido/ShellWindow.pyRUscGs|jtjS(N(R@RAtSIGQUIT(RR((s6/usr/lib64/python2.7/Demo/tkinter/guido/ShellWindow.pytsigquitXscGs|jtjS(N(R@RAtSIGTERM(RR((s6/usr/lib64/python2.7/Demo/tkinter/guido/ShellWindow.pyR[scGs|jtjS(N(R@RAtSIGKILL(RR((s6/usr/lib64/python2.7/Demo/tkinter/guido/ShellWindow.pyR^sc Cs/t|jddddddddd d dS( NR!sNo active processR"s No processR#terrorR%iR&R'(R'(RR(R((s6/usr/lib64/python2.7/Demo/tkinter/guido/ShellWindow.pyR9as  N( t__name__t __module__R,R RRRR@RRDRRR9(((s6/usr/lib64/python2.7/Demo/tkinter/guido/ShellWindow.pyR s       idcCs\tj\}}tj\}}tj}|dkr5x6dD].}ytj|WqCtjk rpqCXqCWtj|dkrtjjdntj|dkrtjjdntj|dkrtjjdntj dt ztj ||Wdtjjdtj dXntj|tj||||fS( Niiispopen2: bad read dup spopen2: bad write dup isexecvp failed (iii( RtpipetforkR=RGtduptsyststderrR;t closerangetMAXFDtexecvpt_exit(tprogRtp2creadtp2cwritetc2preadtc2pwriteRti((s6/usr/lib64/python2.7/Demo/tkinter/guido/ShellWindow.pyRks.     cCstjtjd}t}|jdd|rJt|d|}n t|}|jdddt|j |j j dS(NiRtexpandtfill( RtjoinRMtargvtTktminsizeRtpacktBOTHt focus_setRtmainloop(Rtroottw((s6/usr/lib64/python2.7/Demo/tkinter/guido/ShellWindow.pyttests   t__main__( RRMRtTkinterRRRAR)RRPRReRH(((s6/usr/lib64/python2.7/Demo/tkinter/guido/ShellWindow.pyts     ^  PK%L]htkinter/guido/imagedraw.pyonu[ ^c@s9dZddlTddlZdZdZedS(sDraw on top of an imagei(t*NcCstjd}t}td|}|j|j}}t|d|d|}|jdddtd||j |j dt |j dS( Nitfiletwidththeightitanchortimages ( tsystargvtTkt PhotoImageRRtCanvast create_imagetNWtpacktbindtblobtmainloop(tfilenametroottimgtwthtcanv((s4/usr/lib64/python2.7/Demo/tkinter/guido/imagedraw.pytmains   c CsX|j|j}}|j}d}|j||||||||dddddS(Nitfilltredtoutlinet(txtytwidgett create_oval(teventRRRtr((s4/usr/lib64/python2.7/Demo/tkinter/guido/imagedraw.pyRs (t__doc__tTkinterRRR(((s4/usr/lib64/python2.7/Demo/tkinter/guido/imagedraw.pyts    PK%L]+$RRtkinter/guido/optionmenu.pyonu[ ^c@sddlTeZeZejdeeedddZejd Z eZ e je d e eee fe e Z e jejd S( i(t*tOnetTwotThreetAahtBeetCeetDeetEffiN(RRRRR(tTkintertTktroott StringVartvar1tsett OptionMenutmenu1tpacktCHOICEStvar2tapplyttupletmenu2tmainloop(((s5/usr/lib64/python2.7/Demo/tkinter/guido/optionmenu.pyts       PK%L]sl~~tkinter/guido/ss1.pycnu[ ^c@sdZddlZddlZddlZddlZddlZddlmZdddf\ZZ Z dZ dZ d Z ie e6e e 6e e 6Zid e6d e 6d e 6Zied 6e d 6e d 6Zid e6d e 6de 6ZdZdfdYZdfdYZdfdYZdefdYZdefdYZdefdYZdZdZdZdZddlZd fd!YZd"Z d#Z!e"d$kre!ndS(%sSS1 -- a spreadsheet.iN(texpattLEFTtCENTERtRIGHTcCs |j|S(N(tljust(txtn((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyR scCs |j|S(N(tcenter(RR((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRscCs |j|S(N(trjust(RR((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRstleftRtrighttwtecCs4d}x'|D]}|dk r ||7}q q W|S(Ni(tNone(tseqttotalR((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pytsums   tSheetcBseZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZdZdZdZRS(cCsOi|_tj|_|jjd}|j|_|j|_t|_dS(Nt__main__(tcellstrexectRExect add_modulet cellvaluetcelltmulticellvalueR(tselftm((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyt__init__"s    cCs9|j||}t|dr1|j|jS|SdS(Ntrecalc(tgetcellthasattrRR(RRtyR((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyR*scCs||kr||}}n||kr8||}}ng}xRt||dD]=}x4t||dD]}|j|j||qlWqRW|S(Ni(trangetappendR(Rtx1ty1tx2ty2RR R((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyR1s  !cCs|jj||fS(N(Rtget(RRR ((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyR<scCsJ|dkr|dkstt|ts3t||j||ftlentstrRt iteritemsRRRRDR)R(RRR't align2action(RR?R@twidththeighttcolwidthtfullRttextt alignmentR Rtseptline((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pytdisplaysR &!&!"  ! '  cCsdg}xn|jjD]]\\}}}t|drI|j}ndtj|}|jd|||fqW|jddj|S(Ns txmls%ss% %s ss (RRLRRWtcgitescapeR"tjoin(RtoutRR Rtcellxml((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRWs "  cCs\|j}t|d}|j||rN|jd rN|jdn|jdS(NR s (RWtopentwritetendswithtclose(RtfilenameRRtf((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pytsaves   cCs0t|d}t|j||jdS(Ntr(R]t SheetParsert parsefileR`(RRaRb((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pytloads(t__name__t __module__RRRRR+R-R0R3R4R.R9R:R;R<R=RARBRRVRWRcRg(((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyR s,                  2 RecBseZdZdZdZdZdZdZdZeZ dZ dZ d Z d Z d Zd Zd ZdZRS(cCs ||_dS(N(tsheet(RRj((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRscCsAtj}|j|_|j|_|j|_|j|dS(N( Rt ParserCreatet startelementtStartElementHandlert endelementtEndElementHandlertdatatCharacterDataHandlert ParseFile(RRbtparser((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRfs     cCsct|d|d}|rVx*|jD]\}}t|||%s(RuttypeR{Rht align2xmlRSR(RRy((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRWXs  cCs8d|jkodknr*d|jS|jSdS(Niis %sIiI(R{t _xml_long(R((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyt_xml_int_s cCs d|jS(Ns%s(R{(R((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRescCsdt|jS(Ns%s(treprR{(R((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyt _xml_floathscCsdt|jS(Ns%s(RR{(R((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyt _xml_complexks( RhRiRRRRDRWRRRR(((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyREs      RcBs2eZdedZdZdZdZRS(s%scCsUt|ttfst|tttfks6t||_||_||_ dS(N( R)RKtunicodeR(RRRRRRRS(RRRRRS((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRps   cCs|jS(N(RR(RR((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRwscCs|j|jfS(N(RRRS(R((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRDzscCs-d}|t|j|jtj|jfS(Ns9%s(RRSRRXRYRR(Rts((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRW}s  (RhRiRRRRDRW(((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRns  RcBsDeZdedZdZdZdZdZdZRS(s%scCsV|tttfkst||_t|j|_||_||_|j dS(N( RRRR(tformulat translatet translatedRRSRB(RRRRS((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRs    cCs d|_dS(N(R R{(R((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRBscCs|jdkry4|jddt|j|jd|_Wqtjd}t|drw|j |_qt ||_qXn|jS(Ns from __future__ import division s__value__ = eval(%s)t __value__iRh( R{R tr_execRRtr_evalR1texc_infoRRhRK(RRtexc((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRs cCs:y|j|j}Wnt|j}nX||jfS(N(RR{RKRS(RRR((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRDs cCsdt|j|j|jfS(Ns,%s(RRSRR(R((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRWs cCsg}xtjd|jD]}tjd|} | dk r| j\} } t| } t| } || ko|knr|| ko|knrt| || |}qn|j |qWt dj ||j |j S(Ns(\w+)s^([A-Z]+)([1-9][0-9]*)$RE(tretsplitRtmatchR tgroupst colname2numRtcellnameR"RRZRRS(RR#R$R%R&R6R7R[tpartRtsxtsyRR ((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyR5s   8( RhRiRRRBRRDRWR5(((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRs     c Csg}xtjd|D]}tjd|}|dkrM|j|q|j\}}}}t|}|dkrd||f}n"t|}d||||f}|j|qWdj|S(sTranslate a formula containing fancy cell names to valid Python code. Examples: B4 -> cell(2, 4) B4:Z100 -> cells(2, 4, 26, 100) s(\w+(?::\w+)?)s2^([A-Z]+)([1-9][0-9]*)(?::([A-Z]+)([1-9][0-9]*))?$s cell(%s, %s)scells(%s, %s, %s, %s)REN(RRRR R"RRRZ( RR[RRR#R$R%R&R((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRs    cCs&|dkstt|t|S(sETranslate a cell coordinate to a fancy cell name (e.g. (1, 1)->'A1').i(R(RIRK(RR ((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRscCsk|j}d}xR|D]J}d|ko6dknsAt|dt|tdd}qW|S(sCTranslate a column name to number (e.g. 'A'->1, 'Z'->26, 'AA'->27).itAtZii(tupperR(tord(RRtc((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRs   "&cCs\|dkstd}x=|rWt|dd\}}t|td|}qW|S(s6Translate a column number to name (e.g. 1->'A', etc.).iREiiR(R(tdivmodtchrR(RRR((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRIs  tSheetGUIcBseZdZddddZdZdZdZdZd Zd Z d Z d Z d Z dZ dZeZdZdZdZdZdZdZdZdZdZdZdZdZRS(s7Beginnings of a GUI for a spreadsheet. TO DO: - clear multiple cells - Insert, clear, remove rows or columns - Show new contents while typing - Scroll bars - Grow grid when window is grown - Proper menus - Undo, redo - Cut, copy and paste - Formatting and alignment s sheet1.xmli icCs*||_t|_tjj|r:|jj|n|jj\}}t||}t||}t j |_ |j j d|jt j |j dddd|_ t j|j |_t j|j ddd |j|_t j|j |_|jjd d d d dd|j jd d|jjd d|jjd dd d dd|jjd|j|jjd|j|jjd|j|jjd|j|jjd|j|jjd|j|j||d|_d|_ |j!d d |j"dS(slConstructor. Load the sheet from the filename argument. Set up the Tk widget tree. sSpreadsheet: %sRRtA1tfontt helveticaitboldtSavetcommandtsidetbottomtexpanditfilltbothR R Rssss ssN(RiR(#RaRRjtostpathtisfileRgRAR>tTktroottwm_titletLabeltbeacontEntrytentrytButtonRct savebuttontFrametcellgridtpacktbindt return_eventtshift_return_eventt tab_eventtshift_tab_eventt delete_eventt escape_eventtmakegridR t currentxytcornerxyt setcurrenttsync(RRatrowstcolumnsR?R@((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRs<     cCsr|j|jkr>|jdk r>|jj|j|jn|jj|j|j|jjdddS(Nitendtbreak( RRR RjR0R-RRtdelete(Rtevent((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyR's ! cCs#|j\}}|j||dS(N(Rt load_entry(RRRR ((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyR0scCs|jj||}|dkr*d}n1t|trId|j}n|j\}}|jjdd|jj d||jj dddS(NREt=iR( RjRR R)RRRDRRtinserttselection_range(RRR RRRRS((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyR4s  c Cs||_||_i|_tj|jdd}|jdddddd|jd|jxt d |d D]}|jj |d d tj|jd t |dd}|jd|dddd ||j|df<||_ d|_ |jd|j|jd|j|jd|j|jd|jqvWxt d |d D]}tj|jd t|dd}|jddd|dd ||jd|fitminsizei@RRtWEs sstsunkentbgtwhitetfgtblackN(RRt gridcellsRRRtgrid_configureRt selectallR!tgrid_columnconfigureRIt _SheetGUI__xt _SheetGUI__yt selectcolumnt extendcolumnRKt selectrowt extendrowtpresstmotiontrelease(RRRRRR ((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyR@sN   $  $    cCs*|jdd|jtjtjdS(Ni(Rt setcornerR1R2(RR((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRrscCs<|j|\}}|j|d|j|tjdS(Ni(twhichxyRRR1R2(RRRR ((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRvscCsR|j|\}}|dkrN|j|jdd|j|tjndS(Nii(RRRRR1R2(RRRR ((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyR{s cCs<|j|\}}|jd||jtj|dS(Ni(RRRR1R2(RRRR ((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRscCsR|j|\}}|dkrN|jd|jd|jtj|ndS(Nii(RRRRR1R2(RRRR ((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRs cCsD|j|\}}|dkr@|dkr@|j||ndS(Ni(RR(RRRR ((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRscCsD|j|\}}|dkr@|dkr@|j||ndS(Ni(RR(RRRR ((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRscCsh|jj|j|j}|dk rdt|tjrdy|j|j fSWqdt k r`qdXndS(Ni(ii( Rtwinfo_containingtx_rootty_rootR R)RRRRtAttributeError(RRR ((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRs cCs|jj|jdS(N(RjRcRa(R((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRcscCs|jdk r|jn|jt|||jd<|j|||jj||f|_d|_ |j j |j}|dk rd|d(RRRR ((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRs cCs1|j|j\}}|j|d|dS(sCallback for the Tab key.iR(RRR(RRRR ((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRs cCs:|j|j\}}|jtd|d|dS(s-Callback for the Tab key with Shift modifier.iR(RRRR>(RRRR ((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRs cCs|j\}}|jj}d}|jdrFt|d}nGxDtttt fD]0}y||}Wn qYqYXt |}PqYW|dkr|rt |}n|dkr|j j ||n|j j||||jdS(s+Set the current cell from the entry widget.RiN(RRR'R t startswithRRRRRRRRjR-R+R(RRR RRRtclsR{((s./usr/lib64/python2.7/Demo/tkinter/guido/ss1.pyRs$  cCs|jjx|jjD]\\}}}|dks|dkrMqn|jj||}|dkr{d|ds@         Y )6   C  PK%L]E`}eR R tkinter/guido/electrons.pycnu[ Afc@sLddlTddlZdddYZdZedkrHendS(i(t*Nt ElectronscBs&eZddZdZdZRS(c Cs||_t|_}t||_}|j|j|d|j|d}}|r|j|d|dd|dd|_ng|_ d \}}} } xWt |D]I} |j ||| | d d } |j j | |d| d}} qW|jj dS(Ntwidththeightitbitmapt foregroundtbluei iFiiJtfilltred(i iFiiJ(tntTkttktCanvastcanvastpacktgetintt create_bitmapRtpiecestranget create_ovaltappendtupdate( tselfR RR tcRRtx1ty1tx2ty2titp((s4/usr/lib64/python2.7/Demo/tkinter/guido/electrons.pyt__init__s   ' cCsq|j}xT|jD]I}tjtdd}tjtdd}|j|||qW|jjdS(Niii(R RtrandomtchoiceRtmoveR R(RR RRtxty((s4/usr/lib64/python2.7/Demo/tkinter/guido/electrons.pyt random_move+s  cCshy+x$tdD]}|j|jqWWn6tk rcy|jjWqdtk r_qdXnXdS(Ni(RR$R tTclErrorR tdestroy(RR((s4/usr/lib64/python2.7/Demo/tkinter/guido/electrons.pytrun4s  N(t__name__t __module__tNoneRR$R'(((s4/usr/lib64/python2.7/Demo/tkinter/guido/electrons.pyRs  cCsddl}ddl}|jdr>|j|jd}nd}|jdr|jd}|ddkr{|d}qd|}nd}t||}|jdS(Niiiiit@(tsyststringtargvtatoiR*RR'(R,R-R Rth((s4/usr/lib64/python2.7/Demo/tkinter/guido/electrons.pytmain@s     t__main__((tTkinterRRR1R((((s4/usr/lib64/python2.7/Demo/tkinter/guido/electrons.pyts  -  PK%L]KѴQQtkinter/guido/solitaire.pycnu[ Afc@sCdZddlZddlZddlTddlmZmZmZmZdefdYZdZ dZ d Z e d e Z e d e Z d Zd ZdZdZdZdZdZdZiZxeefD]Zeees s sN( R&R'tgametcardsRRR(R t clickhandlertdoubleclickhandlert motionhandlertreleasehandlert makebottom(RR&R'R>((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyR2s    cCsdS(N((R((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRDscCsd|jj|j|jfS(s+Return a string for debug print statements.s %s(%d, %d)(t __class__R R&R'(R((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyR3scCs>|jj||j|j||jj|jdS(N(R?tappendR9tpositionR(R-(Rtcard((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pytadd%s  cCs'|jj||jj|jdS(N(R?tremoveR(tdtag(RRH((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pytdelete+scCs!|jr|jdjndS(Ni(R?R:(R((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pytshowtop/s cCs+|js dS|jd}|j||S(Ni(R?RRL(RRH((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pytdeal3s    cCs|j|j|jdS(N(R5R&R'(RRH((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRG<scCs|jdS(N(RM(R((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pytuserclickhandler?scCs|jdS(N(RO(R((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pytuserdoubleclickhandlerBscCs"x|D]}|j|qWdS(N(RG(RR?RH((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pytusermovehandlerEs cCs%|j|j|j|dS(N(t finishmovingROt startmoving(Rtevent((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyR@Ks  cCs|j|dS(N(t keepmoving(RRT((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRBPscCs|j||jdS(N(RURR(RRT((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRCSs cCs%|j|j|j|dS(N(RRRPRS(RRT((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRAWs  cCsd|_|jjjd}xDtt|jD])}|j|}|jj |kr4Pq4q4WdS|j srdS|j||_|j |_ |j |_x|jD]}|jqWdS(Ntcurrent(RtmovingR>RtgettagstrangetlenR?R(ttagR%R&tlastxR'tlastyR9(RRTttagstiRH((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRS`s     cCs||js dS|j|j}|j|j}|j|_|j|_|sQ|rxx$|jD]}|j||q[WndS(N(RWR&R\R'R]R4(RRTR7R8RH((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRUqs    cCs,|j}d|_|r(|j|ndS(N(RWRRQ(RR?((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRR|s  N(R R R<RR2RDR3RIRLRMRNRGRORPRQR@RBRCRARWRSRURR(((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyR=s(-                tDeckcBs2eZdZdZdZdZdZRS(s7The deck is a stack with support for shuffling. New methods: fill() -- create the playing cards shuffle() -- shuffle the playing cards A single click moves the top card to the game's open deck and moves it face up; if we're out of cards, it moves the open deck back to the deck. c CsRt|jj|j|j|jt|jtdddt}|jj |dS(NRRR( RR>RR&R'R*R.t BACKGROUNDR(R-(Rtbottom((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRDs   cCsEx>tD]6}x-tD]%}|jt|||jjqWqWdS(N(tALLSUITSt ALLVALUESRIRR>R(RR!R"((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRs  cCsMt|j}g}x(t|D]}|j|j|q"W||_dS(N(RZR?trandpermRF(RtntnewcardsR_((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pytshuffles cCsv|jj}|j}|sUxQ|j}|s7Pn|j||jq!Wn|jjj||jdS(N(R>topendeckRNRIR;R:(RRiRH((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyROs    (R R R<RDRRhRO(((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyR`s     cCsLt|}g}x3|rGtj|}|j||j|qW|S(s4Function returning a random permutation of range(n).(RYtrandomtchoiceRFRJ(RftrR&R_((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRes   t OpenStackcBs#eZdZdZdZRS(cCsdS(Ni((RR?((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyt acceptablescCs|d}|jj|}| s?||ks?|j| rRtj||n8x(|D] }|j||j|qYW|jjdS(Ni(R>t closeststackRnR=RQRLRItwincheck(RR?RHtstack((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRQs #  cCs|js dS|jd}|js1|jdSxQ|jjD]C}|j|gr>|j||j||jjPq>q>WdS(Ni( R?R%ROR>tsuitsRnRLRIRp(RRHts((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRPs       (R R RnRQRP(((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRms  t SuitStackcBs,eZdZdZdZdZRS(c CsBt|jj|j|j|jt|jtdddd}dS(NRRRR(RR>RR&R'R*R.(RRb((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRDs  cCsdS(N((R((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyROscCsdS(N((R((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRPscCsit|dkrdS|d}|js6|jtkS|jd}|j|jkoh|j|jdkS(Niii(RZR?R"tACER!(RR?RHttopcard((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRns    (R R RDRORPRn(((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRts   tRowStackcBseZdZdZRS(cCs`|d}|js |jtkS|jd}|js:dS|j|jko_|j|jdkS(Niii(R?R"tKINGR%R$(RR?RHRv((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRns     cCsh|j}xE|jD]:}||kr)Pn|jrC|dt}q|t}qW|j|j|dS(Ni(R'R?R%R0tOFFSETR5R&(RRHR'tc((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRGs   (R R RnRG(((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRws t SolitairecBsGeZdZdZdZdZdZdZdZRS(c Cs||_t|jdtdddttddtdt|_|jjdt d t t |jd d dddtd d d|j |_ t|jtdtdd|j dtt}t}t||||_|t}t||||_|t}g|_x:ttD],}|t}|jjt|||qWt}|t}g|_x:ttD],}|jjt||||t}qoW|jg|j|j|_|jj|j dS(Nt backgroundthighlightthicknessitwidththeightiiRtexpandRtDealtactivebackgroundtgreenR twindowR(tmastertCanvasRatNROWStXSPACINGtYSPACINGR0RtpacktBOTHtTRUEtButtonRNt dealbuttonRtSWR`tdeckRmRiRrRYtNSUITSRFRttrowsRwt openstacksR(RRR&R'R_((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyR2sD            cCsEx*|jD]}t|jtkr dSq W|j|jdS(N(RrRZR?tNVALUEStwinRN(RRs((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRp=s  cCsgg}x|jD]}||j}qWx9|rbtj|}|j||j||jq*WdS(sStupid animation when you win.N(RR?RjRkRJtanimatedmovetoR(RR?RsRH((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRDs  cCsgx`tdddD]L}|j|j||j|j|}}|j|||jjqWdS(Ni ii(RYR&R'R4Rtupdate_idletasks(RRHtdestR_R7R8((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRNs)cCsed}d}xR|jD]G}|j|jd|j|jd}||kr|}|}qqW|S(Niɚ;i(RRR&R'(RRHtclosesttcdistRqtdist((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRoTs&  cCs|j|jjxHttD]:}x1|j|D]"}|jj}|j|q8Wq$Wx|jD]}|jqlWdS(N( tresetRRhRYRRRNRIRM(RR_RlRH((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRN`s  cCsOxH|jD]=}x4|j}|s)Pn|jj||jqWq WdS(N(RRNRRIR;(RRqRH((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyRjs ( R R R2RpRRRoRNR(((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pyR{ s .   cCs6t}t|}|jd|j|jdS(NtWM_DELETE_WINDOW(tTkR{tprotocoltquittmainloop(trootR>((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pytmainvs  t__main__((((1R<tmathRjtTkinterRRRRRR*R.R0RRRyRatHEARTStDIAMONDStCLUBStSPADEStREDtBLACKR#RstkeysRcRZRRutJACKtQUEENRxRYRdRtmaptstrR)RRR=R`ReRmRtRwR{RR (((s4/usr/lib64/python2.7/Demo/tkinter/guido/solitaire.pytsX   "     /f1 i  PK%L]k>'tkinter/guido/hello.pycnu[ ^c@s3ddlZddlTdZdZedS(iN(t*cCsAt}t|}d|ds    PK%L]YYtkinter/guido/brownian.pycnu[ ^c@sddlTddlZddlZddlZddlZdZdZdZdZdZ dZ dZ da d Z d ZedS( i(t*Nii,i itredicCst}tjtdt}tjtdt}|j||||||||dt}xvtstjdt }tjdt }tj t }y|j |||Wnt k rPnXtj|qcWdS(Ng@tfilli(tRADIUStrandomtgausstWIDTHtSIGMAtHEIGHTt create_ovaltFILLtstoptBUZZt expovariatetLAMBDAtmovetTclErrorttimetsleep(tcanvastrtxtytptdxtdytdt((s3/usr/lib64/python2.7/Demo/tkinter/guido/brownian.pytparticles.  cCst}t|dtdt}|jddddd}tjdr`ttjd}nx9t|D]+}t j dt d |f}|j qmWz|j WddaXdS( NtwidththeightRtbothtexpandiittargettargs(tTktCanvasRRtpacktsystargvtinttranget threadingtThreadRtstarttmainloopR (trootRtnptitt((s3/usr/lib64/python2.7/Demo/tkinter/guido/brownian.pytmain"s  (tTkinterRR)RR%RRRR RRR R RR1(((s3/usr/lib64/python2.7/Demo/tkinter/guido/brownian.pyts       PK%L]qfXX tkinter/guido/newmenubardemo.pyonu[ Afc@sFdZddlTdddYZdZedkrBendS( s.Play with the new Tk 8.0 toplevel menu option.i(t*tAppcBseZdZRS(cCsu||_t|j|_t|j|_|jjdd|jjdd|jjdd|jj|jjddd|jjt|j|_|jjdd|jjdd|jjdd t|jd d |_|jjdd |jj dd d|j|jj ddd|j|jj ddd|jt d|j|_ dS(NtlabeltNewsOpen...tClosetQuittcommandtCuttCopytPastetnamethelpsAbout...tFiletmenutEdittHelp( tmastertMenutmenubartfilemenut add_commandt add_separatortquitteditmenuthelpmenut add_cascadetToplevelttop(tselfR((s9/usr/lib64/python2.7/Demo/tkinter/guido/newmenubardemo.pyt__init__ s$  (t__name__t __module__R(((s9/usr/lib64/python2.7/Demo/tkinter/guido/newmenubardemo.pyRscCs-t}|jt|}|jdS(N(tTktwithdrawRtmainloop(troottapp((s9/usr/lib64/python2.7/Demo/tkinter/guido/newmenubardemo.pytmain(s   t__main__N((t__doc__tTkinterRR%R(((s9/usr/lib64/python2.7/Demo/tkinter/guido/newmenubardemo.pyts  !  PK%L]qfXX tkinter/guido/newmenubardemo.pycnu[ Afc@sFdZddlTdddYZdZedkrBendS( s.Play with the new Tk 8.0 toplevel menu option.i(t*tAppcBseZdZRS(cCsu||_t|j|_t|j|_|jjdd|jjdd|jjdd|jj|jjddd|jjt|j|_|jjdd|jjdd|jjdd t|jd d |_|jjdd |jj dd d|j|jj ddd|j|jj ddd|jt d|j|_ dS(NtlabeltNewsOpen...tClosetQuittcommandtCuttCopytPastetnamethelpsAbout...tFiletmenutEdittHelp( tmastertMenutmenubartfilemenut add_commandt add_separatortquitteditmenuthelpmenut add_cascadetToplevelttop(tselfR((s9/usr/lib64/python2.7/Demo/tkinter/guido/newmenubardemo.pyt__init__ s$  (t__name__t __module__R(((s9/usr/lib64/python2.7/Demo/tkinter/guido/newmenubardemo.pyRscCs-t}|jt|}|jdS(N(tTktwithdrawRtmainloop(troottapp((s9/usr/lib64/python2.7/Demo/tkinter/guido/newmenubardemo.pytmain(s   t__main__N((t__doc__tTkinterRR%R(((s9/usr/lib64/python2.7/Demo/tkinter/guido/newmenubardemo.pyts  !  PK%L]&Ytkinter/guido/listtree.pycnu[ ^c@sWddlZddlZddlTdZdZdZedkrSendS(iN(t*cCs?t|dd}|jdddtt||dd|S(Ntnametlisttexpanditfillt.i(tListboxtpacktBOTHt listnodes(tmastertappR((s3/usr/lib64/python2.7/Demo/tkinter/guido/listtree.pytlisttreescCs|j|dd|}|jtd||f|jj|j|dd|}x%|D]}t||||dq]WdS(Ntwinfotclasss%s (%s)tchildreni(tsendtinserttENDttkt splitlistR (RR twidgettleveltklassRtc((s3/usr/lib64/python2.7/Demo/tkinter/guido/listtree.pyR s   cCstjds-tjjdtjdntjd}t}|jddt|dd}|jdddt t ||}|j dS(NisUsage: listtree appname iRtfRR( tsystargvtstderrtwritetexittTktminsizetFrameRRR tmainloop(R RRR((s3/usr/lib64/python2.7/Demo/tkinter/guido/listtree.pytmains   t__main__(RtstringtTkinterR R R#t__name__(((s3/usr/lib64/python2.7/Demo/tkinter/guido/listtree.pyts     PK%L]X\tkinter/guido/ManPage.pyonu[ ^c@sddlZddlTddlmZddlmZdZdZejdZejdZejd Z d efd YZ d e fd YZ e Z dZ edkre ndS(iN(t*(t_tkinter(t ScrolledTexts*-Courier-Bold-R-Normal-*-120-*s!*-Courier-Medium-O-Normal-*-120-*s:^ Page [1-9][0-9]*[ ]+\|^.*Last change:.*[1-9][0-9]* s^[ ]* s^[ ]*[Xv!_][Xv!_ ]* tEditableManPagecBsneZd dZdZdZdZeZdZdZ dZ dZ dZ d d Z RS( cKshttj||f||jddd|jddt|jddtd|_d|_dS(NtXt underlineit!tfontt_i( tapplyRt__init__t tag_configtBOLDFONTt ITALICFONTtNonetfptlineno(tselftmastertcnf((s2/usr/lib64/python2.7/Demo/tkinter/guido/ManPage.pyR s  cCs |jdkS(N(RR(R((s2/usr/lib64/python2.7/Demo/tkinter/guido/ManPage.pytbusy%scCs|jr|jndS(N(Rt _endparser(R((s2/usr/lib64/python2.7/Demo/tkinter/guido/ManPage.pytkill)s cCs-|j||jj|tj|jdS(N(t _startparserttktcreatefilehandlerRtREADABLEt _filehandler(RR((s2/usr/lib64/python2.7/Demo/tkinter/guido/ManPage.pytasyncparsefile.s cCs4|jj}|s#|jdS|j|dS(N(RtreadlineRt _parseline(RRtmasktnextline((s2/usr/lib64/python2.7/Demo/tkinter/guido/ManPage.pyR6s  cCszddlm}|d|d}|j|d}|j|x'|j}|s[Pn|j|qEW|jdS(Ni(tselectgcSs||ggg|dS(Ni((RttoutR!((s2/usr/lib64/python2.7/Demo/tkinter/guido/ManPage.pytavail@stheight(R!tgetintRRRR(RRR!R#R$R ((s2/usr/lib64/python2.7/Demo/tkinter/guido/ManPage.pyt syncparsefile>s  cCs|jrtdn|j||_d|_d|_d|_d|_|d}t |d<|j dt ||ds     PK%L]^tkinter/guido/wish.pycnu[ ^c@sddlZddlZejejddddZejddZxer\dZndZyeeZ Wne k rPnXee d Zej ejd d erMej e yejd eZ Wnejk rZd GeGHnXe re GHndZqMqMWdS(iNtDISPLAYtwishtTkitupdatets% s tinfotcompletetevals TclError:(t_tkintertostcreatetenvironttktcalltcmdtpromptt raw_inputtlinetEOFErrort getbooleantrecordtresulttTclErrortmsg(((s//usr/lib64/python2.7/Demo/tkinter/guido/wish.pyts,       PK%L])YzKKtkinter/guido/sortvisu.pynuȯ#! /usr/bin/python2.7 """Sorting algorithms visualizer using Tkinter. This module is comprised of three ``components'': - an array visualizer with methods that implement basic sorting operations (compare, swap) as well as methods for ``annotating'' the sorting algorithm (e.g. to show the pivot element); - a number of sorting algorithms (currently quicksort, insertion sort, selection sort and bubble sort, as well as a randomization function), all using the array visualizer for its basic operations and with calls to its annotation methods; - and a ``driver'' class which can be used as a Grail applet or as a stand-alone application. """ from Tkinter import * from Canvas import Line, Rectangle import random XGRID = 10 YGRID = 10 WIDTH = 6 class Array: def __init__(self, master, data=None): self.master = master self.frame = Frame(self.master) self.frame.pack(fill=X) self.label = Label(self.frame) self.label.pack() self.canvas = Canvas(self.frame) self.canvas.pack() self.report = Label(self.frame) self.report.pack() self.left = Line(self.canvas, 0, 0, 0, 0) self.right = Line(self.canvas, 0, 0, 0, 0) self.pivot = Line(self.canvas, 0, 0, 0, 0) self.items = [] self.size = self.maxvalue = 0 if data: self.setdata(data) def setdata(self, data): olditems = self.items self.items = [] for item in olditems: item.delete() self.size = len(data) self.maxvalue = max(data) self.canvas.config(width=(self.size+1)*XGRID, height=(self.maxvalue+1)*YGRID) for i in range(self.size): self.items.append(ArrayItem(self, i, data[i])) self.reset("Sort demo, size %d" % self.size) speed = "normal" def setspeed(self, speed): self.speed = speed def destroy(self): self.frame.destroy() in_mainloop = 0 stop_mainloop = 0 def cancel(self): self.stop_mainloop = 1 if self.in_mainloop: self.master.quit() def step(self): if self.in_mainloop: self.master.quit() Cancelled = "Array.Cancelled" # Exception def wait(self, msecs): if self.speed == "fastest": msecs = 0 elif self.speed == "fast": msecs = msecs//10 elif self.speed == "single-step": msecs = 1000000000 if not self.stop_mainloop: self.master.update() id = self.master.after(msecs, self.master.quit) self.in_mainloop = 1 self.master.mainloop() self.master.after_cancel(id) self.in_mainloop = 0 if self.stop_mainloop: self.stop_mainloop = 0 self.message("Cancelled") raise Array.Cancelled def getsize(self): return self.size def show_partition(self, first, last): for i in range(self.size): item = self.items[i] if first <= i < last: item.item.config(fill='red') else: item.item.config(fill='orange') self.hide_left_right_pivot() def hide_partition(self): for i in range(self.size): item = self.items[i] item.item.config(fill='red') self.hide_left_right_pivot() def show_left(self, left): if not 0 <= left < self.size: self.hide_left() return x1, y1, x2, y2 = self.items[left].position() ## top, bot = HIRO self.left.coords([(x1-2, 0), (x1-2, 9999)]) self.master.update() def show_right(self, right): if not 0 <= right < self.size: self.hide_right() return x1, y1, x2, y2 = self.items[right].position() self.right.coords(((x2+2, 0), (x2+2, 9999))) self.master.update() def hide_left_right_pivot(self): self.hide_left() self.hide_right() self.hide_pivot() def hide_left(self): self.left.coords(((0, 0), (0, 0))) def hide_right(self): self.right.coords(((0, 0), (0, 0))) def show_pivot(self, pivot): x1, y1, x2, y2 = self.items[pivot].position() self.pivot.coords(((0, y1-2), (9999, y1-2))) def hide_pivot(self): self.pivot.coords(((0, 0), (0, 0))) def swap(self, i, j): if i == j: return self.countswap() item = self.items[i] other = self.items[j] self.items[i], self.items[j] = other, item item.swapwith(other) def compare(self, i, j): self.countcompare() item = self.items[i] other = self.items[j] return item.compareto(other) def reset(self, msg): self.ncompares = 0 self.nswaps = 0 self.message(msg) self.updatereport() self.hide_partition() def message(self, msg): self.label.config(text=msg) def countswap(self): self.nswaps = self.nswaps + 1 self.updatereport() def countcompare(self): self.ncompares = self.ncompares + 1 self.updatereport() def updatereport(self): text = "%d cmps, %d swaps" % (self.ncompares, self.nswaps) self.report.config(text=text) class ArrayItem: def __init__(self, array, index, value): self.array = array self.index = index self.value = value x1, y1, x2, y2 = self.position() self.item = Rectangle(array.canvas, x1, y1, x2, y2, fill='red', outline='black', width=1) self.item.bind('', self.mouse_down) self.item.bind('', self.mouse_move) self.item.bind('', self.mouse_up) def delete(self): item = self.item self.array = None self.item = None item.delete() def mouse_down(self, event): self.lastx = event.x self.lasty = event.y self.origx = event.x self.origy = event.y self.item.tkraise() def mouse_move(self, event): self.item.move(event.x - self.lastx, event.y - self.lasty) self.lastx = event.x self.lasty = event.y def mouse_up(self, event): i = self.nearestindex(event.x) if i >= self.array.getsize(): i = self.array.getsize() - 1 if i < 0: i = 0 other = self.array.items[i] here = self.index self.array.items[here], self.array.items[i] = other, self self.index = i x1, y1, x2, y2 = self.position() self.item.coords(((x1, y1), (x2, y2))) other.setindex(here) def setindex(self, index): nsteps = steps(self.index, index) if not nsteps: return if self.array.speed == "fastest": nsteps = 0 oldpts = self.position() self.index = index newpts = self.position() trajectory = interpolate(oldpts, newpts, nsteps) self.item.tkraise() for pts in trajectory: self.item.coords((pts[:2], pts[2:])) self.array.wait(50) def swapwith(self, other): nsteps = steps(self.index, other.index) if not nsteps: return if self.array.speed == "fastest": nsteps = 0 myoldpts = self.position() otheroldpts = other.position() self.index, other.index = other.index, self.index mynewpts = self.position() othernewpts = other.position() myfill = self.item['fill'] otherfill = other.item['fill'] self.item.config(fill='green') other.item.config(fill='yellow') self.array.master.update() if self.array.speed == "single-step": self.item.coords((mynewpts[:2], mynewpts[2:])) other.item.coords((othernewpts[:2], othernewpts[2:])) self.array.master.update() self.item.config(fill=myfill) other.item.config(fill=otherfill) self.array.wait(0) return mytrajectory = interpolate(myoldpts, mynewpts, nsteps) othertrajectory = interpolate(otheroldpts, othernewpts, nsteps) if self.value > other.value: self.item.tkraise() other.item.tkraise() else: other.item.tkraise() self.item.tkraise() try: for i in range(len(mytrajectory)): mypts = mytrajectory[i] otherpts = othertrajectory[i] self.item.coords((mypts[:2], mypts[2:])) other.item.coords((otherpts[:2], otherpts[2:])) self.array.wait(50) finally: mypts = mytrajectory[-1] otherpts = othertrajectory[-1] self.item.coords((mypts[:2], mypts[2:])) other.item.coords((otherpts[:2], otherpts[2:])) self.item.config(fill=myfill) other.item.config(fill=otherfill) def compareto(self, other): myfill = self.item['fill'] otherfill = other.item['fill'] outcome = cmp(self.value, other.value) if outcome < 0: myflash = 'white' otherflash = 'black' elif outcome > 0: myflash = 'black' otherflash = 'white' else: myflash = otherflash = 'grey' try: self.item.config(fill=myflash) other.item.config(fill=otherflash) self.array.wait(500) finally: self.item.config(fill=myfill) other.item.config(fill=otherfill) return outcome def position(self): x1 = (self.index+1)*XGRID - WIDTH//2 x2 = x1+WIDTH y2 = (self.array.maxvalue+1)*YGRID y1 = y2 - (self.value)*YGRID return x1, y1, x2, y2 def nearestindex(self, x): return int(round(float(x)/XGRID)) - 1 # Subroutines that don't need an object def steps(here, there): nsteps = abs(here - there) if nsteps <= 3: nsteps = nsteps * 3 elif nsteps <= 5: nsteps = nsteps * 2 elif nsteps > 10: nsteps = 10 return nsteps def interpolate(oldpts, newpts, n): if len(oldpts) != len(newpts): raise ValueError, "can't interpolate arrays of different length" pts = [0]*len(oldpts) res = [tuple(oldpts)] for i in range(1, n): for k in range(len(pts)): pts[k] = oldpts[k] + (newpts[k] - oldpts[k])*i//n res.append(tuple(pts)) res.append(tuple(newpts)) return res # Various (un)sorting algorithms def uniform(array): size = array.getsize() array.setdata([(size+1)//2] * size) array.reset("Uniform data, size %d" % size) def distinct(array): size = array.getsize() array.setdata(range(1, size+1)) array.reset("Distinct data, size %d" % size) def randomize(array): array.reset("Randomizing") n = array.getsize() for i in range(n): j = random.randint(0, n-1) array.swap(i, j) array.message("Randomized") def insertionsort(array): size = array.getsize() array.reset("Insertion sort") for i in range(1, size): j = i-1 while j >= 0: if array.compare(j, j+1) <= 0: break array.swap(j, j+1) j = j-1 array.message("Sorted") def selectionsort(array): size = array.getsize() array.reset("Selection sort") try: for i in range(size): array.show_partition(i, size) for j in range(i+1, size): if array.compare(i, j) > 0: array.swap(i, j) array.message("Sorted") finally: array.hide_partition() def bubblesort(array): size = array.getsize() array.reset("Bubble sort") for i in range(size): for j in range(1, size): if array.compare(j-1, j) > 0: array.swap(j-1, j) array.message("Sorted") def quicksort(array): size = array.getsize() array.reset("Quicksort") try: stack = [(0, size)] while stack: first, last = stack[-1] del stack[-1] array.show_partition(first, last) if last-first < 5: array.message("Insertion sort") for i in range(first+1, last): j = i-1 while j >= first: if array.compare(j, j+1) <= 0: break array.swap(j, j+1) j = j-1 continue array.message("Choosing pivot") j, i, k = first, (first+last)//2, last-1 if array.compare(k, i) < 0: array.swap(k, i) if array.compare(k, j) < 0: array.swap(k, j) if array.compare(j, i) < 0: array.swap(j, i) pivot = j array.show_pivot(pivot) array.message("Pivot at left of partition") array.wait(1000) left = first right = last while 1: array.message("Sweep right pointer") right = right-1 array.show_right(right) while right > first and array.compare(right, pivot) >= 0: right = right-1 array.show_right(right) array.message("Sweep left pointer") left = left+1 array.show_left(left) while left < last and array.compare(left, pivot) <= 0: left = left+1 array.show_left(left) if left > right: array.message("End of partition") break array.message("Swap items") array.swap(left, right) array.message("Swap pivot back") array.swap(pivot, right) n1 = right-first n2 = last-left if n1 > 1: stack.append((first, right)) if n2 > 1: stack.append((left, last)) array.message("Sorted") finally: array.hide_partition() def demosort(array): while 1: for alg in [quicksort, insertionsort, selectionsort, bubblesort]: randomize(array) alg(array) # Sort demo class -- usable as a Grail applet class SortDemo: def __init__(self, master, size=15): self.master = master self.size = size self.busy = 0 self.array = Array(self.master) self.botframe = Frame(master) self.botframe.pack(side=BOTTOM) self.botleftframe = Frame(self.botframe) self.botleftframe.pack(side=LEFT, fill=Y) self.botrightframe = Frame(self.botframe) self.botrightframe.pack(side=RIGHT, fill=Y) self.b_qsort = Button(self.botleftframe, text="Quicksort", command=self.c_qsort) self.b_qsort.pack(fill=X) self.b_isort = Button(self.botleftframe, text="Insertion sort", command=self.c_isort) self.b_isort.pack(fill=X) self.b_ssort = Button(self.botleftframe, text="Selection sort", command=self.c_ssort) self.b_ssort.pack(fill=X) self.b_bsort = Button(self.botleftframe, text="Bubble sort", command=self.c_bsort) self.b_bsort.pack(fill=X) # Terrible hack to overcome limitation of OptionMenu... class MyIntVar(IntVar): def __init__(self, master, demo): self.demo = demo IntVar.__init__(self, master) def set(self, value): IntVar.set(self, value) if str(value) != '0': self.demo.resize(value) self.v_size = MyIntVar(self.master, self) self.v_size.set(size) sizes = [1, 2, 3, 4] + range(5, 55, 5) if self.size not in sizes: sizes.append(self.size) sizes.sort() self.m_size = apply(OptionMenu, (self.botleftframe, self.v_size) + tuple(sizes)) self.m_size.pack(fill=X) self.v_speed = StringVar(self.master) self.v_speed.set("normal") self.m_speed = OptionMenu(self.botleftframe, self.v_speed, "single-step", "normal", "fast", "fastest") self.m_speed.pack(fill=X) self.b_step = Button(self.botleftframe, text="Step", command=self.c_step) self.b_step.pack(fill=X) self.b_randomize = Button(self.botrightframe, text="Randomize", command=self.c_randomize) self.b_randomize.pack(fill=X) self.b_uniform = Button(self.botrightframe, text="Uniform", command=self.c_uniform) self.b_uniform.pack(fill=X) self.b_distinct = Button(self.botrightframe, text="Distinct", command=self.c_distinct) self.b_distinct.pack(fill=X) self.b_demo = Button(self.botrightframe, text="Demo", command=self.c_demo) self.b_demo.pack(fill=X) self.b_cancel = Button(self.botrightframe, text="Cancel", command=self.c_cancel) self.b_cancel.pack(fill=X) self.b_cancel.config(state=DISABLED) self.b_quit = Button(self.botrightframe, text="Quit", command=self.c_quit) self.b_quit.pack(fill=X) def resize(self, newsize): if self.busy: self.master.bell() return self.size = newsize self.array.setdata(range(1, self.size+1)) def c_qsort(self): self.run(quicksort) def c_isort(self): self.run(insertionsort) def c_ssort(self): self.run(selectionsort) def c_bsort(self): self.run(bubblesort) def c_demo(self): self.run(demosort) def c_randomize(self): self.run(randomize) def c_uniform(self): self.run(uniform) def c_distinct(self): self.run(distinct) def run(self, func): if self.busy: self.master.bell() return self.busy = 1 self.array.setspeed(self.v_speed.get()) self.b_cancel.config(state=NORMAL) try: func(self.array) except Array.Cancelled: pass self.b_cancel.config(state=DISABLED) self.busy = 0 def c_cancel(self): if not self.busy: self.master.bell() return self.array.cancel() def c_step(self): if not self.busy: self.master.bell() return self.v_speed.set("single-step") self.array.setspeed("single-step") self.array.step() def c_quit(self): if self.busy: self.array.cancel() self.master.after_idle(self.master.quit) # Main program -- for stand-alone operation outside Grail def main(): root = Tk() demo = SortDemo(root) root.protocol('WM_DELETE_WINDOW', demo.c_quit) root.mainloop() if __name__ == '__main__': main() PK%L]X\tkinter/guido/ManPage.pycnu[ ^c@sddlZddlTddlmZddlmZdZdZejdZejdZejd Z d efd YZ d e fd YZ e Z dZ edkre ndS(iN(t*(t_tkinter(t ScrolledTexts*-Courier-Bold-R-Normal-*-120-*s!*-Courier-Medium-O-Normal-*-120-*s:^ Page [1-9][0-9]*[ ]+\|^.*Last change:.*[1-9][0-9]* s^[ ]* s^[ ]*[Xv!_][Xv!_ ]* tEditableManPagecBsneZd dZdZdZdZeZdZdZ dZ dZ dZ d d Z RS( cKshttj||f||jddd|jddt|jddtd|_d|_dS(NtXt underlineit!tfontt_i( tapplyRt__init__t tag_configtBOLDFONTt ITALICFONTtNonetfptlineno(tselftmastertcnf((s2/usr/lib64/python2.7/Demo/tkinter/guido/ManPage.pyR s  cCs |jdkS(N(RR(R((s2/usr/lib64/python2.7/Demo/tkinter/guido/ManPage.pytbusy%scCs|jr|jndS(N(Rt _endparser(R((s2/usr/lib64/python2.7/Demo/tkinter/guido/ManPage.pytkill)s cCs-|j||jj|tj|jdS(N(t _startparserttktcreatefilehandlerRtREADABLEt _filehandler(RR((s2/usr/lib64/python2.7/Demo/tkinter/guido/ManPage.pytasyncparsefile.s cCs4|jj}|s#|jdS|j|dS(N(RtreadlineRt _parseline(RRtmasktnextline((s2/usr/lib64/python2.7/Demo/tkinter/guido/ManPage.pyR6s  cCszddlm}|d|d}|j|d}|j|x'|j}|s[Pn|j|qEW|jdS(Ni(tselectgcSs||ggg|dS(Ni((RttoutR!((s2/usr/lib64/python2.7/Demo/tkinter/guido/ManPage.pytavail@stheight(R!tgetintRRRR(RRR!R#R$R ((s2/usr/lib64/python2.7/Demo/tkinter/guido/ManPage.pyt syncparsefile>s  cCs|jrtdn|j||_d|_d|_d|_d|_|d}t |d<|j dt ||ds     PK%L]n`  tkinter/guido/electrons.pynuȯ#! /usr/bin/python2.7 # Simulate "electrons" migrating across the screen. # An optional bitmap file in can be in the background. # # Usage: electrons [n [bitmapfile]] # # n is the number of electrons to animate; default is 30. # # The bitmap file can be any X11 bitmap file (look in # /usr/include/X11/bitmaps for samples); it is displayed as the # background of the animation. Default is no bitmap. from Tkinter import * import random # The graphical interface class Electrons: # Create our objects def __init__(self, n, bitmap = None): self.n = n self.tk = tk = Tk() self.canvas = c = Canvas(tk) c.pack() width, height = tk.getint(c['width']), tk.getint(c['height']) # Add background bitmap if bitmap: self.bitmap = c.create_bitmap(width/2, height/2, bitmap=bitmap, foreground='blue') self.pieces = [] x1, y1, x2, y2 = 10,70,14,74 for i in range(n): p = c.create_oval(x1, y1, x2, y2, fill='red') self.pieces.append(p) y1, y2 = y1 +2, y2 + 2 self.tk.update() def random_move(self, n): c = self.canvas for p in self.pieces: x = random.choice(range(-2,4)) y = random.choice(range(-3,4)) c.move(p, x, y) self.tk.update() # Run -- allow 500 movemens def run(self): try: for i in range(500): self.random_move(self.n) except TclError: try: self.tk.destroy() except TclError: pass # Main program def main(): import sys, string # First argument is number of electrons, default 30 if sys.argv[1:]: n = string.atoi(sys.argv[1]) else: n = 30 # Second argument is bitmap file, default none if sys.argv[2:]: bitmap = sys.argv[2] # Reverse meaning of leading '@' compared to Tk if bitmap[0] == '@': bitmap = bitmap[1:] else: bitmap = '@' + bitmap else: bitmap = None # Create the graphical objects... h = Electrons(n, bitmap) # ...and run! h.run() # Call main when run as script if __name__ == '__main__': main() PK%L]aAtkinter/guido/newmenubardemo.pynuȯ#! /usr/bin/python2.7 """Play with the new Tk 8.0 toplevel menu option.""" from Tkinter import * class App: def __init__(self, master): self.master = master self.menubar = Menu(self.master) self.filemenu = Menu(self.menubar) self.filemenu.add_command(label="New") self.filemenu.add_command(label="Open...") self.filemenu.add_command(label="Close") self.filemenu.add_separator() self.filemenu.add_command(label="Quit", command=self.master.quit) self.editmenu = Menu(self.menubar) self.editmenu.add_command(label="Cut") self.editmenu.add_command(label="Copy") self.editmenu.add_command(label="Paste") self.helpmenu = Menu(self.menubar, name='help') self.helpmenu.add_command(label="About...") self.menubar.add_cascade(label="File", menu=self.filemenu) self.menubar.add_cascade(label="Edit", menu=self.editmenu) self.menubar.add_cascade(label="Help", menu=self.helpmenu) self.top = Toplevel(menu=self.menubar) # Rest of app goes here... def main(): root = Tk() root.withdraw() app = App(root) root.mainloop() if __name__ == '__main__': main() PK%L]|Dtkinter/guido/paint.pycnu[ ^c@s`dZddlTdad \aadZdZdZdZ e dkr\end S( sA"Paint program by Dave Michell. Subject: tkinter "paint" example From: Dave Mitchell To: python-list@cwi.nl Date: Fri, 23 Jan 1998 12:18:05 -0500 (EST) Not too long ago (last week maybe?) someone posted a request for an example of a paint program using Tkinter. Try as I might I can't seem to find it in the archive, so i'll just post mine here and hope that the person who requested it sees this! All this does is put up a canvas and draw a smooth black line whenever you have the mouse button down, but hopefully it will be enough to start with.. It would be easy enough to add some options like other shapes or colors... yours, dave mitchell davem@magnet.com i(t*tupcCs]t}t|}|j|jdt|jdt|jdt|jdS(Nsss(tTktCanvastpacktbindtmotiontb1downtb1uptmainloop(troott drawing_area((s0/usr/lib64/python2.7/Demo/tkinter/guido/paint.pytmains   cCs dadS(Ntdown(tb1(tevent((s0/usr/lib64/python2.7/Demo/tkinter/guido/paint.pyR'scCsdadadadS(NR(RtNonetxoldtyold(R((s0/usr/lib64/python2.7/Demo/tkinter/guido/paint.pyR,scCsetdkratdk rLtdk rL|jjtt|j|jdtn|ja|jandS(NR tsmooth( RRRRtwidgett create_linetxtytTRUE(R((s0/usr/lib64/python2.7/Demo/tkinter/guido/paint.pyR2s  ( t__main__N(NN( t__doc__tTkinterRRRRR RRRt__name__(((s0/usr/lib64/python2.7/Demo/tkinter/guido/paint.pyts     PK%L]Vtkinter/guido/rmt.pycnu[ Afc @sddlTddlZeZejZeededdZejde eeZ e jddde e e de Zejd edeee deddd ejd dZejd ede ddejd d dejedcCs<|j}|j}tjddtjt||dS(Nstk_priv(selectMode)tword(RRRRttk_textSelectToR(RRR((s./usr/lib64/python2.7/Demo/tkinter/guido/rmt.pytdouble1=s  s cCs<|j}|j}tjddtjt||dS(Nstk_priv(selectMode)tline(RRRRRR(RRR((s./usr/lib64/python2.7/Demo/tkinter/guido/rmt.pyttriple1Ds  s cCstjtdtdS(Ns (RtinserttAtInserttinvoke(R((s./usr/lib64/python2.7/Demo/tkinter/guido/rmt.pyt returnkeyKsscCsStjttjtjttjtddkrOtndS(Nis.0(RR!R"t selection_gettyview_pickplacetindexR#(R((s./usr/lib64/python2.7/Demo/tkinter/guido/rmt.pytcontrolvPss cCsHtjdtjdkrDtjdttjtndS(Nt promptEndsinsert - 1 char(RR'tdeleteR"R&(R((s./usr/lib64/python2.7/Demo/tkinter/guido/rmt.pyt backspaceZss s scCstjdt}tjtjdd|rttjkrZtjd|}ntj t|}|rtj t|dnt ntj tdS(NspromptEnd + 1 chartinfotcompletetevals ( RtgetR"t getbooleanttktcalltapptroott winfo_nametsendR!tpromptR&(tcmdtmsg((s./usr/lib64/python2.7/Demo/tkinter/guido/rmt.pyR#is cCs>tjttdtjddtjddddS(Ns: R)sinsert - 1 charRsinsert linestart(RR!R"R3Rttag_add(((s./usr/lib64/python2.7/Demo/tkinter/guido/rmt.pyR7uscCsA|atjddtjd|dtjddddS(NspromptEnd linestartR)t:R(R3RR*R!R:(tappName((s./usr/lib64/python2.7/Demo/tkinter/guido/rmt.pytnewApp~scCstjdtjddtj}t|}|jxR|D]J}ytj|dWntk rsqFXtj d|d|dqFWdS(NR itlasts winfo name .RcSs t|S(N(R=(tname((s./usr/lib64/python2.7/Demo/tkinter/guido/rmt.pytt( t file_m_appstaddR*R4t winfo_interpstlisttsortR6tTclErrort add_command(tnamesR?((s./usr/lib64/python2.7/Demo/tkinter/guido/rmt.pyt fillAppsMenus       t postcommand(1tTkintertsystTkR4R1tFrametRAISEDtmBartpacktXtftBOTHt ScrollbartFLATtstRIGHTtYtTexttsetRtLEFTt tag_configtyviewttitleticonnamet MenubuttontfiletMenutfile_mRBt add_cascadeRHtexitRtbindRR R$R(R+R#R7R=RJt tk_menuBarR5R3tfocustmainloop(((s./usr/lib64/python2.7/Demo/tkinter/guido/rmt.pyts^     '                 PK%L]Ծtkinter/READMEnu[Several collections of example code for Tkinter. See the toplevel README for an explanation of the difference between Tkinter and _tkinter, how to enable the Python Tk interface, and where to get Matt Conway's lifesaver document. Subdirectories: guido my original example set (fairly random collection) matt Matt Conway's examples, to go with his lifesaver document ttk Examples using the ttk module PK%L]Rh|@@!tkinter/ttk/listbox_scrollcmd.pycnu[ ^c@sWdZddlZddlZejZejddZejdddddd ejd ej d d Z e j ed s"     PK%L]"P P tkinter/ttk/widget_state.pycnu[ ^c @sdZddlZddddddd d d g Zx eD]Zejd eq;Wd ZdejfdYZdZe dkrendS(s8Sample demo showing widget states and some font styling.iNtactivetdisabledtfocustpressedtselectedt backgroundtreadonlyt alternatetinvalidt!cCs%tttd}|j|dS(Ni(tstatestlentstate(twidgettnostate((s5/usr/lib64/python2.7/Demo/tkinter/ttk/widget_state.pyt reset_state stAppcBs2eZddZddZdZdZRS(cCstjj|dd|jj|tj|_|jjdd}t|j j d|}|j j d||_ d|j krd|j |_ n|d d kr|d nd |_ t ||d d krd nd |_g|_|jdS( Nt borderwidthitTButtontfontsfont configure %s -sizesfont configure %s -familyt s{%s}it-ti(tttktFramet__init__tmasterttitletStyletstyletlookuptstrttktevalt font_familyt fsize_prefixtintt base_fsizetupdate_widgetst_setup_widgets(tselfRtbtn_fonttfsize((s5/usr/lib64/python2.7/Demo/tkinter/ttk/widget_state.pyRs#) icCs4|jjddd|j|j|j|fdS(NRRs%s %s%d(Rt configureR"R#R%(R(textra((s5/usr/lib64/python2.7/Demo/tkinter/ttk/widget_state.pyt _set_font#scCs|j|}|s'dg}d}nGt|j}g|D]}|tkr@|^q@}dt|}x(|jD]}t||j|qxW|j|dS(NRiii( t nametowidgettsettsplitR R R&RR R-(R(R tnewtextt goodstatest font_extrat newstatesR ((s5/usr/lib64/python2.7/Demo/tkinter/ttk/widget_state.pyt _new_state's  %  c Cstj|dd}tj|dddd}|j|jddf|d <|j|jj||j|j d d d d |j dddd d d dd|j d ddddS(NttextsEnter states and watchtcursortxtermtvalidatetkeys%Ws%Ptvalidatecommandtfilltxtpadxitsidetlefttpadytanchortntbothtexpandi( RtButtontEntrytregisterR5RR&tappendR9tpack(R(tbtntentry((s5/usr/lib64/python2.7/Demo/tkinter/ttk/widget_state.pyR'?s  "N(t__name__t __module__tNoneRR-R5R'(((s5/usr/lib64/python2.7/Demo/tkinter/ttk/widget_state.pyRs   cCstd}|jdS(NsWidget State Tester(Rtmainloop(tapp((s5/usr/lib64/python2.7/Demo/tkinter/ttk/widget_state.pytmainNs t__main__( t__doc__RR R RIRRRRRRM(((s5/usr/lib64/python2.7/Demo/tkinter/ttk/widget_state.pyts  @  PK%L]J"_ !tkinter/ttk/notebook_closebtn.pycnu[ ^c @sdZddlZddlZddlZejZejjejje dZ ej ddejje dZ ej ddejje dZ ej d dejje d ZejZejd d dd8d9ddddejddidd6fgejddidd6didd6dd6didd6dd6didd6dd6fdidd6dd6fgd 6fgd 6fgd 6fgd!Zd"Zejd#d$eeejd#d%eejd&d'd(d'd)dZde_ejed*d+Zejed*d,Zejed*d-Zejed.d/d0d1ejed.d2d0d1ejed.d3d0d1ej d4d5d6d7ej!dS(:saA Ttk Notebook with close buttons. Based on an example by patthoyts, http://paste.tclers.tk/896 iNtimgt img_closetfiles close.giftimg_closeactivesclose_active.giftimg_closepressedsclose_pressed.giftclosetimagetactivetpresseds !disabledtborderitstickyttButtonNotebooksButtonNotebook.clienttnswesButtonNotebook.TabsButtonNotebook.tabsButtonNotebook.paddingttoptsidesButtonNotebook.focussButtonNotebook.labeltleftsButtonNotebook.closetchildrencCst|j|j|j}}}|j||}|jd||f}d|krp|jdg||_ndS(Ns@%d,%dRR(txtytwidgettidentifytindextstatet pressed_index(teventRRRtelemR((s:/usr/lib64/python2.7/Demo/tkinter/ttk/notebook_closebtn.pyt btn_press&s  cCs|j|j|j}}}|jdgs3dS|j||}|jd||f}d|kr|j|kr|j||jdn|j dgd|_dS(NRs@%d,%dRs<>s!pressed( RRRtinstateRRRtforgettevent_generateRtNone(RRRRRR((s:/usr/lib64/python2.7/Demo/tkinter/ttk/notebook_closebtn.pyt btn_release/s t TNotebooksstwidthitheighttstylet backgroundtredtgreentbluettexttRedtpaddingitGreentBluetexpanditfilltboth(RRs !disabledR(Rs !disabledR("t__doc__tostTkintertttktTktroottpathtjointdirnamet__file__timgdirt PhotoImageti1ti2ti3tStyleR$telement_createtlayoutRR t bind_classtTruetNotebooktnbRRtFrametf1tf2tf3taddtpacktmainloop(((s:/usr/lib64/python2.7/Demo/tkinter/ttk/notebook_closebtn.pytsF    !$      <  PK%L]J"_ !tkinter/ttk/notebook_closebtn.pyonu[ ^c @sdZddlZddlZddlZejZejjejje dZ ej ddejje dZ ej ddejje dZ ej d dejje d ZejZejd d dd8d9ddddejddidd6fgejddidd6didd6dd6didd6dd6didd6dd6fdidd6dd6fgd 6fgd 6fgd 6fgd!Zd"Zejd#d$eeejd#d%eejd&d'd(d'd)dZde_ejed*d+Zejed*d,Zejed*d-Zejed.d/d0d1ejed.d2d0d1ejed.d3d0d1ej d4d5d6d7ej!dS(:saA Ttk Notebook with close buttons. Based on an example by patthoyts, http://paste.tclers.tk/896 iNtimgt img_closetfiles close.giftimg_closeactivesclose_active.giftimg_closepressedsclose_pressed.giftclosetimagetactivetpresseds !disabledtborderitstickyttButtonNotebooksButtonNotebook.clienttnswesButtonNotebook.TabsButtonNotebook.tabsButtonNotebook.paddingttoptsidesButtonNotebook.focussButtonNotebook.labeltleftsButtonNotebook.closetchildrencCst|j|j|j}}}|j||}|jd||f}d|krp|jdg||_ndS(Ns@%d,%dRR(txtytwidgettidentifytindextstatet pressed_index(teventRRRtelemR((s:/usr/lib64/python2.7/Demo/tkinter/ttk/notebook_closebtn.pyt btn_press&s  cCs|j|j|j}}}|jdgs3dS|j||}|jd||f}d|kr|j|kr|j||jdn|j dgd|_dS(NRs@%d,%dRs<>s!pressed( RRRtinstateRRRtforgettevent_generateRtNone(RRRRRR((s:/usr/lib64/python2.7/Demo/tkinter/ttk/notebook_closebtn.pyt btn_release/s t TNotebooksstwidthitheighttstylet backgroundtredtgreentbluettexttRedtpaddingitGreentBluetexpanditfilltboth(RRs !disabledR(Rs !disabledR("t__doc__tostTkintertttktTktroottpathtjointdirnamet__file__timgdirt PhotoImageti1ti2ti3tStyleR$telement_createtlayoutRR t bind_classtTruetNotebooktnbRRtFrametf1tf2tf3taddtpacktmainloop(((s:/usr/lib64/python2.7/Demo/tkinter/ttk/notebook_closebtn.pytsF    !$      <  PK%L]#gg$tkinter/ttk/treeview_multicolumn.pycnu[ ^c@sdZddlZddlZddlZd6Zd7d8d9d:d;d<d=d>d?d@dAdBdCdDdEgZd1Zd2efd3YZd4Z e d5kre ndS(FsCDemo based on the demo mclist included with tk source distribution.iNtcountrytcapitaltcurrencyt Argentinas Buenos AirestARSt AustraliatCanberratAUDtBraziltBraziliatBRLtCanadatOttawatCADtChinatBeijingtCNYtFrancetParistEURtGermanytBerlintIndias New DelhitINRtItalytRometJapantTokyotJPYtMexicos Mexico CitytMXNtRussiatMoscowtRUBs South AfricatPretoriatZARsUnited KingdomtLondontGBPs United StatessWashington, D.C.tUSDcsgjdD]}j|||f^q}|jdx1t|D]#\}}j|dd|qQWj|d|fddS(s/Sort tree contents when a column is clicked on.ttreverseitcommandcst|t S(N(tsortbytint(tcol(t descendingttree(s=/usr/lib64/python2.7/Demo/tkinter/ttk/treeview_multicolumn.pyt%R'N(t get_childrentsettsortt enumeratetmovetheading(R.R,R-tchildtdatatindxtitem((R-R.s=/usr/lib64/python2.7/Demo/tkinter/ttk/treeview_multicolumn.pyR*s 4 tAppcBs#eZdZdZdZRS(cCs!d|_|j|jdS(N(tNoneR.t_setup_widgetst _build_tree(tself((s=/usr/lib64/python2.7/Demo/tkinter/ttk/treeview_multicolumn.pyt__init__(s  c Csetjdddddddd$d d }|jd dtj}|jd ddttjdtdd|_tjddd|jj }tjddd|jj }|jj d|j d|j |jj ddddddd||j dd dddd!d||j dddd dd"d||jdd#d |jdd#d dS(%Nt wraplengtht4itjustifytlefttanchortntpaddingi iittextsTtk is the new Tk themed widget set. One of the widgets it includes is a tree widget, which can be configured to display multiple columns of informational data without displaying the tree itself. This is a simple way to build a listbox that has multiple columns. Clicking on the heading for a column will sort the data by that column. You can also change the width of the columns by dragging the boundary between them.tfilltxtbothtexpandtcolumnstshowtheadingstorienttverticalR)t horizontaltyscrollcommandtxscrollcommandtcolumnitrowtstickytnsewtin_itnstewtweight(i ii i(tttktLabeltpacktFrametTruetTreeviewt tree_columnsR.t Scrollbartyviewtxviewt configureR1tgridtgrid_columnconfiguretgrid_rowconfigure(R>tmsgt containertvsbthsb((s=/usr/lib64/python2.7/Demo/tkinter/ttk/treeview_multicolumn.pyR<-s  %""c s xgtD]_}jj|d|jd|fdjj|dtjj|jqWxtD]}jj ddd|xnt |D]`\}}tjj|}jjt|dd|krjjt|d|qqWqqWdS(NRGR)cstj|dS(Ni(R*R.(tc(R>(s=/usr/lib64/python2.7/Demo/tkinter/ttk/treeview_multicolumn.pyR/MR'twidthR'tendtvalues( RbR.R5ttitleRTttkFonttFonttmeasuret tree_datatinsertR3R;(R>R,R9R8tvaltilen((R>s=/usr/lib64/python2.7/Demo/tkinter/ttk/treeview_multicolumn.pyR=Js / "(t__name__t __module__R?R<R=(((s=/usr/lib64/python2.7/Demo/tkinter/ttk/treeview_multicolumn.pyR:'s  cCstj}|jd|jdddl}y|jdWn*tk roddl}|jdnXt }|j dS(NsMulti-Column Listtmclistis~/tile-themes/plastik/plastiks'plastik theme being used without images( tTkintertTktwm_titlet wm_iconnamet plastik_themetinstallt ExceptiontwarningstwarnR:tmainloop(trootRRtapp((s=/usr/lib64/python2.7/Demo/tkinter/ttk/treeview_multicolumn.pytmain[s       t__main__(RRR(Rs Buenos AiresR(RRR(RR R (R R R (RRR(RRR(RRR(Rs New DelhiR(RRR(RRR(Rs Mexico CityR(RR R!(s South AfricaR"R#(sUnited KingdomR$R%(s United StatessWashington, D.C.R&( t__doc__R}RsR\RbRvR*tobjectR:RRz(((s=/usr/lib64/python2.7/Demo/tkinter/ttk/treeview_multicolumn.pyts0     4  PK%L] w%> > tkinter/ttk/theme_selector.pycnu[ ^c@sZdZddlZddlZdejfdYZdZedkrVendS(sTtk Theme Selector v2. This is an improvement from the other theme selector (themes_combo.py) since now you can notice theme changes in Ttk Combobox, Ttk Frame, Ttk Label and Ttk Button. iNtAppcBs,eZdZdZdZdZRS(cCsHtjj|ddtj|_tj|d|_|jdS(Nt borderwidthii( tttktFramet__init__tStyletstyletTkintertIntVarttheme_autochanget_setup_widgets(tself((s7/usr/lib64/python2.7/Demo/tkinter/ttk/theme_selector.pyR scCs|jj|jjdS(N(Rt theme_uset themes_combotget(R ((s7/usr/lib64/python2.7/Demo/tkinter/ttk/theme_selector.pyt _change_themescCs |jjr|jndS(N(R RR(R twidget((s7/usr/lib64/python2.7/Demo/tkinter/ttk/theme_selector.pyt_theme_sel_changedsc Cstj|dd}|jj}tj|d|dd|_|jj|d|jjd|jtj |ddd |j }tj |dd d |j }|j d d dd|jj dddddd dd|j dddddd dd|j dddddddd |j}|jddd|jddd|jddd|j dddddddddddS(NttexttThemestvalueststatetreadonlyis<>s Change Themetcommands-Change themes when combobox item is activatedtvariabletipadxitstickytwtrowtcolumnitpadxtewitet columnspanitpadytweighttnsewtrowspan(RtLabelRt theme_namestComboboxR tsettbindRtButtonRt CheckbuttonR tgridtwinfo_toplevelt rowconfiguretcolumnconfigure(R t themes_lbltthemest change_btnttheme_change_checkbtnttop((s7/usr/lib64/python2.7/Demo/tkinter/ttk/theme_selector.pyR s&   %"" (t__name__t __module__RRRR (((s7/usr/lib64/python2.7/Demo/tkinter/ttk/theme_selector.pyR s  cCs't}|jjd|jdS(NsTheme Selector(Rtmasterttitletmainloop(tapp((s7/usr/lib64/python2.7/Demo/tkinter/ttk/theme_selector.pytmain7s t__main__(t__doc__RRRRR<R6(((s7/usr/lib64/python2.7/Demo/tkinter/ttk/theme_selector.pyts   -  PK%L]y5Ltkinter/ttk/roundframe.pynu["""Ttk Frame with rounded corners. Based on an example by Bryan Oakley, found at: http://wiki.tcl.tk/20152""" import Tkinter import ttk root = Tkinter.Tk() img1 = Tkinter.PhotoImage("frameFocusBorder", data=""" R0lGODlhQABAAPcAAHx+fMTCxKSipOTi5JSSlNTS1LSytPTy9IyKjMzKzKyq rOzq7JyanNza3Ly6vPz6/ISChMTGxKSmpOTm5JSWlNTW1LS2tPT29IyOjMzO zKyurOzu7JyenNze3Ly+vPz+/OkAKOUA5IEAEnwAAACuQACUAAFBAAB+AFYd QAC0AABBAAB+AIjMAuEEABINAAAAAHMgAQAAAAAAAAAAAKjSxOIEJBIIpQAA sRgBMO4AAJAAAHwCAHAAAAUAAJEAAHwAAP+eEP8CZ/8Aif8AAG0BDAUAAJEA AHwAAIXYAOfxAIESAHwAAABAMQAbMBZGMAAAIEggJQMAIAAAAAAAfqgaXESI 5BdBEgB+AGgALGEAABYAAAAAAACsNwAEAAAMLwAAAH61MQBIAABCM8B+AAAU AAAAAAAApQAAsf8Brv8AlP8AQf8Afv8AzP8A1P8AQf8AfgAArAAABAAADAAA AACQDADjAAASAAAAAACAAADVABZBAAB+ALjMwOIEhxINUAAAANIgAOYAAIEA AHwAAGjSAGEEABYIAAAAAEoBB+MAAIEAAHwCACABAJsAAFAAAAAAAGjJAGGL AAFBFgB+AGmIAAAQAABHAAB+APQoAOE/ABIAAAAAAADQAADjAAASAAAAAPiF APcrABKDAAB8ABgAGO4AAJAAqXwAAHAAAAUAAJEAAHwAAP8AAP8AAP8AAP8A AG0pIwW3AJGSAHx8AEocI/QAAICpAHwAAAA0SABk6xaDEgB8AAD//wD//wD/ /wD//2gAAGEAABYAAAAAAAC0/AHj5AASEgAAAAA01gBkWACDTAB8AFf43PT3 5IASEnwAAOAYd+PuMBKQTwB8AGgAEGG35RaSEgB8AOj/NOL/ZBL/gwD/fMkc q4sA5UGpEn4AAIg02xBk/0eD/358fx/4iADk5QASEgAAAALnHABkAACDqQB8 AMyINARkZA2DgwB8fBABHL0AAEUAqQAAAIAxKOMAPxIwAAAAAIScAOPxABIS AAAAAIIAnQwA/0IAR3cAACwAAAAAQABAAAAI/wA/CBxIsKDBgwgTKlzIsKFD gxceNnxAsaLFixgzUrzAsWPFCw8kDgy5EeQDkBxPolypsmXKlx1hXnS48UEH CwooMCDAgIJOCjx99gz6k+jQnkWR9lRgYYDJkAk/DlAgIMICZlizat3KtatX rAsiCNDgtCJClQkoFMgqsu3ArBkoZDgA8uDJAwk4bGDmtm9BZgcYzK078m4D Cgf4+l0skNkGCg3oUhR4d4GCDIoZM2ZWQMECyZQvLMggIbPmzQIyfCZ5YcME AwFMn/bLLIKBCRtMHljQQcDV2ZqZTRDQYfWFAwMqUJANvC8zBhUWbDi5YUAB Bsybt2VGoUKH3AcmdP+Im127xOcJih+oXsEDdvOLuQfIMGBD9QwBlsOnzcBD hfrsuVfefgzJR599A+CnH4Hb9fcfgu29x6BIBgKYYH4DTojQc/5ZGGGGGhpU IYIKghgiQRw+GKCEJxZIwXwWlthiQyl6KOCMLsJIIoY4LlQjhDf2mNCI9/Eo 5IYO2sjikX+9eGCRCzL5V5JALillY07GaOSVb1G5ookzEnlhlFx+8OOXZb6V 5Y5kcnlmckGmKaaMaZrpJZxWXjnnlmW++WGdZq5ZXQEetKmnlxPgl6eUYhJq KKOI0imnoNbF2ScFHQJJwW99TsBAAAVYWEAAHEQAZoi1cQDqAAeEV0EACpT/ JqcACgRQAW6uNWCbYKcyyEwGDBgQwa2tTlBBAhYIQMFejC5AgQAWJNDABK3y loEDEjCgV6/aOcYBAwp4kIF6rVkXgAEc8IQZVifCBRQHGqya23HGIpsTBgSU OsFX/PbrVVjpYsCABA4kQCxHu11ogAQUIOAwATpBLDFQFE9sccUYS0wAxD5h 4DACFEggbAHk3jVBA/gtTIHHEADg8sswxyzzzDQDAAEECGAQsgHiTisZResN gLIHBijwLQEYePzx0kw37fTSSjuMr7ZMzfcgYZUZi58DGsTKwbdgayt22GSP bXbYY3MggQIaONDzAJ8R9kFlQheQQAAOWGCAARrwdt23Bn8H7vfggBMueOEG WOBBAAkU0EB9oBGUdXIFZJBABAEEsPjmmnfO+eeeh/55BBEk0Ph/E8Q9meQq bbDABAN00EADFRRQ++2254777rr3jrvjFTTQwQCpz7u6QRut5/oEzA/g/PPQ Ry/99NIz//oGrZpUUEAAOw==""") img2 = Tkinter.PhotoImage("frameBorder", data=""" R0lGODlhQABAAPcAAHx+fMTCxKSipOTi5JSSlNTS1LSytPTy9IyKjMzKzKyq rOzq7JyanNza3Ly6vPz6/ISChMTGxKSmpOTm5JSWlNTW1LS2tPT29IyOjMzO zKyurOzu7JyenNze3Ly+vPz+/OkAKOUA5IEAEnwAAACuQACUAAFBAAB+AFYd QAC0AABBAAB+AIjMAuEEABINAAAAAHMgAQAAAAAAAAAAAKjSxOIEJBIIpQAA sRgBMO4AAJAAAHwCAHAAAAUAAJEAAHwAAP+eEP8CZ/8Aif8AAG0BDAUAAJEA AHwAAIXYAOfxAIESAHwAAABAMQAbMBZGMAAAIEggJQMAIAAAAAAAfqgaXESI 5BdBEgB+AGgALGEAABYAAAAAAACsNwAEAAAMLwAAAH61MQBIAABCM8B+AAAU AAAAAAAApQAAsf8Brv8AlP8AQf8Afv8AzP8A1P8AQf8AfgAArAAABAAADAAA AACQDADjAAASAAAAAACAAADVABZBAAB+ALjMwOIEhxINUAAAANIgAOYAAIEA AHwAAGjSAGEEABYIAAAAAEoBB+MAAIEAAHwCACABAJsAAFAAAAAAAGjJAGGL AAFBFgB+AGmIAAAQAABHAAB+APQoAOE/ABIAAAAAAADQAADjAAASAAAAAPiF APcrABKDAAB8ABgAGO4AAJAAqXwAAHAAAAUAAJEAAHwAAP8AAP8AAP8AAP8A AG0pIwW3AJGSAHx8AEocI/QAAICpAHwAAAA0SABk6xaDEgB8AAD//wD//wD/ /wD//2gAAGEAABYAAAAAAAC0/AHj5AASEgAAAAA01gBkWACDTAB8AFf43PT3 5IASEnwAAOAYd+PuMBKQTwB8AGgAEGG35RaSEgB8AOj/NOL/ZBL/gwD/fMkc q4sA5UGpEn4AAIg02xBk/0eD/358fx/4iADk5QASEgAAAALnHABkAACDqQB8 AMyINARkZA2DgwB8fBABHL0AAEUAqQAAAIAxKOMAPxIwAAAAAIScAOPxABIS AAAAAIIAnQwA/0IAR3cAACwAAAAAQABAAAAI/wA/CBxIsKDBgwgTKlzIsKFD gxceNnxAsaLFixgzUrzAsWPFCw8kDgy5EeQDkBxPolypsmXKlx1hXnS48UEH CwooMCDAgIJOCjx99gz6k+jQnkWR9lRgYYDJkAk/DlAgIMICkVgHLoggQIPT ighVJqBQIKvZghkoZDgA8uDJAwk4bDhLd+ABBmvbjnzbgMKBuoA/bKDQgC1F gW8XKMgQOHABBQsMI76wIIOExo0FZIhM8sKGCQYCYA4cwcCEDSYPLOgg4Oro uhMEdOB84cCAChReB2ZQYcGGkxsGFGCgGzCFCh1QH5jQIW3xugwSzD4QvIIH 4s/PUgiQYcCG4BkC5P/ObpaBhwreq18nb3Z79+8Dwo9nL9I8evjWsdOX6D59 fPH71Xeef/kFyB93/sln4EP2Ebjegg31B5+CEDLUIH4PVqiQhOABqKFCF6qn 34cHcfjffCQaFOJtGaZYkIkUuljQigXK+CKCE3po40A0trgjjDru+EGPI/6I Y4co7kikkAMBmaSNSzL5gZNSDjkghkXaaGIBHjwpY4gThJeljFt2WSWYMQpZ 5pguUnClehS4tuMEDARQgH8FBMBBBExGwIGdAxywXAUBKHCZkAIoEEAFp33W QGl47ZgBAwZEwKigE1SQgAUCUDCXiwtQIIAFCTQwgaCrZeCABAzIleIGHDD/ oIAHGUznmXABGMABT4xpmBYBHGgAKGq1ZbppThgAG8EEAW61KwYMSOBAApdy pNp/BkhAAQLcEqCTt+ACJW645I5rLrgEeOsTBtwiQIEElRZg61sTNBBethSw CwEA/Pbr778ABywwABBAgAAG7xpAq6mGUUTdAPZ6YIACsRKAAbvtZqzxxhxn jDG3ybbKFHf36ZVYpuE5oIGhHMTqcqswvyxzzDS/HDMHEiiggQMLDxCZXh8k BnEBCQTggAUGGKCB0ktr0PTTTEfttNRQT22ABR4EkEABDXgnGUEn31ZABglE EEAAWaeN9tpqt832221HEEECW6M3wc+Hga3SBgtMODBABw00UEEBgxdO+OGG J4744oZzXUEDHQxwN7F5G7QRdXxPoPkAnHfu+eeghw665n1vIKhJBQUEADs=""") style = ttk.Style() style.element_create("RoundedFrame", "image", "frameBorder", ("focus", "frameFocusBorder"), border=16, sticky="nsew") style.layout("RoundedFrame", [("RoundedFrame", {"sticky": "nsew"})]) style.configure("TEntry", borderwidth=0) frame = ttk.Frame(style="RoundedFrame", padding=10) frame.pack(fill='x') frame2 = ttk.Frame(style="RoundedFrame", padding=10) frame2.pack(fill='both', expand=1) entry = ttk.Entry(frame, text='Test') entry.pack(fill='x') entry.bind("", lambda evt: frame.state(["focus"])) entry.bind("", lambda evt: frame.state(["!focus"])) text = Tkinter.Text(frame2, borderwidth=0, bg="white", highlightthickness=0) text.pack(fill='both', expand=1) text.bind("", lambda evt: frame2.state(["focus"])) text.bind("", lambda evt: frame2.state(["!focus"])) root.mainloop() PK%L]yTt%t%tkinter/ttk/plastik_theme.pynu["""This demonstrates good part of the syntax accepted by theme_create. This is a translation of plastik.tcl to python. You will need the images used by the plastik theme to test this. The images (and other tile themes) can be retrived by doing: $ cvs -z3 -d:pserver:anonymous@tktable.cvs.sourceforge.net:/cvsroot/tktable \ co tile-themes To test this module you should do, for example: import Tkinter import plastik_theme root = Tkinter.Tk() plastik_theme.install(plastik_image_dir) ... Where plastik_image_dir contains the path to the images directory used by the plastik theme, something like: tile-themes/plastik/plastik """ import os import glob import ttk from Tkinter import PhotoImage __all__ = ['install'] colors = { "frame": "#efefef", "disabledfg": "#aaaaaa", "selectbg": "#657a9e", "selectfg": "#ffffff" } imgs = {} def _load_imgs(imgdir): imgdir = os.path.expanduser(imgdir) if not os.path.isdir(imgdir): raise Exception("%r is not a directory, can't load images" % imgdir) for f in glob.glob("%s/*.gif" % imgdir): img = os.path.split(f)[1] name = img[:-4] imgs[name] = PhotoImage(name, file=f, format="gif89") def install(imgdir): _load_imgs(imgdir) style = ttk.Style() style.theme_create("plastik", "default", settings={ ".": { "configure": {"background": colors['frame'], "troughcolor": colors['frame'], "selectbackground": colors['selectbg'], "selectforeground": colors['selectfg'], "fieldbackground": colors['frame'], "font": "TkDefaultFont", "borderwidth": 1}, "map": {"foreground": [("disabled", colors['disabledfg'])]} }, "Vertical.TScrollbar": {"layout": [ ("Vertical.Scrollbar.uparrow", {"side": "top", "sticky": ''}), ("Vertical.Scrollbar.downarrow", {"side": "bottom", "sticky": ''}), ("Vertical.Scrollbar.uparrow", {"side": "bottom", "sticky": ''}), ("Vertical.Scrollbar.trough", {"sticky": "ns", "children": [("Vertical.Scrollbar.thumb", {"expand": 1, "unit": 1, "children": [("Vertical.Scrollbar.grip", {"sticky": ''})] })] })] }, "Horizontal.TScrollbar": {"layout": [ ("Horizontal.Scrollbar.leftarrow", {"side": "left", "sticky": ''}), ("Horizontal.Scrollbar.rightarrow", {"side": "right", "sticky": ''}), ("Horizontal.Scrollbar.leftarrow", {"side": "right", "sticky": ''}), ("Horizontal.Scrollbar.trough", {"sticky": "ew", "children": [("Horizontal.Scrollbar.thumb", {"expand": 1, "unit": 1, "children": [("Horizontal.Scrollbar.grip", {"sticky": ''})] })] })] }, "TButton": { "configure": {"width": 10, "anchor": "center"}, "layout": [ ("Button.button", {"children": [("Button.focus", {"children": [("Button.padding", {"children": [("Button.label", {"side": "left", "expand": 1})] })] })] }) ] }, "Toolbutton": { "configure": {"anchor": "center"}, "layout": [ ("Toolbutton.border", {"children": [("Toolbutton.button", {"children": [("Toolbutton.padding", {"children": [("Toolbutton.label", {"side":"left", "expand":1})] })] })] }) ] }, "TMenubutton": {"layout": [ ("Menubutton.button", {"children": [("Menubutton.indicator", {"side": "right"}), ("Menubutton.focus", {"children": [("Menubutton.padding", {"children": [("Menubutton.label", {"side": "left", "expand": 1})] })] })] })] }, "TNotebook": {"configure": {"tabmargins": [0, 2, 0, 0]}}, "TNotebook.tab": { "configure": {"padding": [6, 2, 6, 2], "expand": [0, 0, 2]}, "map": {"expand": [("selected", [1, 2, 4, 2])]} }, "Treeview": {"configure": {"padding": 0}}, # elements "Button.button": {"element create": ("image", 'button-n', ("pressed", 'button-p'), ("active", 'button-h'), {"border": [4, 10], "padding": 4, "sticky":"ewns"} ) }, "Toolbutton.button": {"element create": ("image", 'tbutton-n', ("selected", 'tbutton-p'), ("pressed", 'tbutton-p'), ("active", 'tbutton-h'), {"border": [4, 9], "padding": 3, "sticky": "news"} ) }, "Checkbutton.indicator": {"element create": ("image", 'check-nu', ('active', 'selected', 'check-hc'), ('pressed', 'selected', 'check-pc'), ('active', 'check-hu'), ("selected", 'check-nc'), {"sticky": ''} ) }, "Radiobutton.indicator": {"element create": ("image", 'radio-nu', ('active', 'selected', 'radio-hc'), ('pressed', 'selected', 'radio-pc'), ('active', 'radio-hu'), ('selected', 'radio-nc'), {"sticky": ''} ) }, "Horizontal.Scrollbar.thumb": {"element create": ("image", 'hsb-n', {"border": 3, "sticky": "ew"}) }, "Horizontal.Scrollbar.grip": {"element create": ("image", 'hsb-g')}, "Horizontal.Scrollbar.trough": {"element create": ("image", 'hsb-t')}, "Vertical.Scrollbar.thumb": {"element create": ("image", 'vsb-n', {"border": 3, "sticky": "ns"}) }, "Vertical.Scrollbar.grip": {"element create": ("image", 'vsb-g')}, "Vertical.Scrollbar.trough": {"element create": ("image", 'vsb-t')}, "Scrollbar.uparrow": {"element create": ("image", 'arrowup-n', ("pressed", 'arrowup-p'), {"sticky": ''}) }, "Scrollbar.downarrow": {"element create": ("image", 'arrowdown-n', ("pressed", 'arrowdown-p'), {'sticky': ''}) }, "Scrollbar.leftarrow": {"element create": ("image", 'arrowleft-n', ("pressed", 'arrowleft-p'), {'sticky': ''}) }, "Scrollbar.rightarrow": {"element create": ("image", 'arrowright-n', ("pressed", 'arrowright-p'), {'sticky': ''}) }, "Horizontal.Scale.slider": {"element create": ("image", 'hslider-n', {'sticky': ''}) }, "Horizontal.Scale.trough": {"element create": ("image", 'hslider-t', {'border': 1, 'padding': 0}) }, "Vertical.Scale.slider": {"element create": ("image", 'vslider-n', {'sticky': ''}) }, "Vertical.Scale.trough": {"element create": ("image", 'vslider-t', {'border': 1, 'padding': 0}) }, "Entry.field": {"element create": ("image", 'entry-n', ("focus", 'entry-f'), {'border': 2, 'padding': [3, 4], 'sticky': 'news'} ) }, "Labelframe.border": {"element create": ("image", 'border', {'border': 4, 'padding': 4, 'sticky': 'news'}) }, "Menubutton.button": {"element create": ("image", 'combo-r', ('active', 'combo-ra'), {'sticky': 'news', 'border': [4, 6, 24, 15], 'padding': [4, 4, 5]} ) }, "Menubutton.indicator": {"element create": ("image", 'arrow-d', {"sticky": "e", "border": [15, 0, 0, 0]}) }, "Combobox.field": {"element create": ("image", 'combo-n', ('readonly', 'active', 'combo-ra'), ('focus', 'active', 'combo-fa'), ('active', 'combo-a'), ('!readonly', 'focus', 'combo-f'), ('readonly', 'combo-r'), {'border': [4, 6, 24, 15], 'padding': [4, 4, 5], 'sticky': 'news'} ) }, "Combobox.downarrow": {"element create": ("image", 'arrow-d', {'sticky': 'e', 'border': [15, 0, 0, 0]}) }, "Notebook.client": {"element create": ("image", 'notebook-c', {'border': 4}) }, "Notebook.tab": {"element create": ("image", 'notebook-tn', ("selected", 'notebook-ts'), ("active", 'notebook-ta'), {'padding': [0, 2, 0, 0], 'border': [4, 10, 4, 10]} ) }, "Progressbar.trough": {"element create": ("image", 'hprogress-t', {'border': 2}) }, "Horizontal.Progressbar.pbar": {"element create": ("image", 'hprogress-b', {'border': [2, 9]}) }, "Vertical.Progressbar.pbar": {"element create": ("image", 'vprogress-b', {'border': [9, 2]}) }, "Treeheading.cell": {"element create": ("image", 'tree-n', ("pressed", 'tree-p'), {'border': [4, 10], 'padding': 4, 'sticky': 'news'} ) } }) style.theme_use("plastik") PK%L]$&$&tkinter/ttk/ttkcalendar.pycnu[ ^c@s{dZddlZddlZddlZddlZdZdejfdYZdZe dkrwendS(sQ Simple calendar using ttk Treeview together with calendar and datetime classes. iNcCs-|dkrtj|Stj||SdS(N(tNonetcalendart TextCalendartLocaleTextCalendar(tlocaletfwday((s4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyt get_calendar s  tCalendarcBseZejjZejjZddZdZdZdZ dZ dZ dZ dZ dZd Zd Zd Zd Zed ZRS(c KsY|jdtj}|jd|jjj}|jd|jjj}|jdd}|jdd}|jdd}|j||d |_d|_ t j j |||t |||_|j|j|j|j||gtd D]!} |jjd d d d ^q |_|j|jjd|jdS(s WIDGET-SPECIFIC OPTIONS locale, firstweekday, year, month, selectbackground, selectforeground t firstweekdaytyeartmonthRtselectbackgrounds#ecffc4tselectforegrounds#05640eiittendtvaluessN(tpopRtMONDAYtdatetimetnowR R Rt_datet _selectiontttktFramet__init__Rt_calt_Calendar__setup_stylest_Calendar__place_widgetst_Calendar__config_calendart_Calendar__setup_selectiontranget _calendartinsertt_itemst_build_calendartbindt_Calendar__minsize( tselftmastertkwRR R Rtsel_bgtsel_fgt_((s4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyRs$    4 cCs|dkrtd|n]|dkr;||jdTss L.TButtontlefts R.TButtontright(RtStyleR&tlayout(R%tstylet arrow_layout((s4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyt__setup_stylesQs c Cs&tj|}tj|ddd|j}tj|ddd|j}tj|dddd|_tjd d d d d d|_|j d|dddddd|j d||jj d|dddddd|j d|dddd|jj d|dddddddS(NR@s L.TButtontcommands R.TButtontwidthitanchortcentertshowR t selectmodetnonetheightitin_tsidettoptpadyitcolumnitrowitpadxi itexpandR3tbothtbottom( RRtButtont _prev_montht _next_monthtLabelt_headertTreeviewRtpacktgrid(R%thframetlbtntrbtn((s4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyt__place_widgetsZs!"%c s|jjdj}||jd<|jjddd|jjddd|d dtjtfd |D}x0|D](}|jj |d |d |d dqWdS(NitcolumnstheaderR+tgrey90R RRttagc3s|]}j|VqdS(N(tmeasure(t.0tcol(tfont(s4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pys qsRDtminwidthREte( RtformatweekheadertsplitRt tag_configureR ttkFonttFonttmaxRO(R%tcolstmaxwidthRg((Rhs4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyt__config_calendarjs   cstj|_tj|jd|dddd|_jddd|dd_j dfd |jj d fd |jj d|j dS( NR+t borderwidthithighlightthicknessR3REtwscs jS(N(t place_forget(tevt(tcanvas(s4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyR;|R s cs jS(N(Rw(Rx(Ry(s4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyR;}R ( RnRot_fonttTkintertCanvasRR.t create_textR0R#t_pressed(R%R(R)((Rys4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyt__setup_selectionvs!cCsN|jjjjd\}}||jd }|jjj||dS(Ntxt+(RR&tgeometryRltindextminsize(R%RxRDRJ((s4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyt __minsizes!c Cs|jj|jj}}|jj||d}|j|jd<|jj||}x~t|j D]m\}}|t |kr||ng}g|D]}|rd|nd^q} |j j |d| qiWdS(NiR0s%02dR R( RR R RtformatmonthnamettitleRYtmonthdayscalendart enumerateR!tlenRR,( R%R R RbtcaltindxR,tweektdaytfmt_week((s4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyR"s")c Cs|\}}}}|jj|}|j}|jd|d||j|j|||dd|j|jd||jd|jd|d|d S( s%Configure canvas for a new selection.RDRJiiR0RKRtyN( RzReR.t configuretcoordsR0R/tplaceR( R%R0tbboxRRRDRJttextwRy((s4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyt_show_selections "c Cs|j|j|j}}}|j|}|j|}| sQ||jkrUdS|j|d}t|sxdS|t|dd}|sdS|j ||} | sdSd|}|||f|_ |j || dS(s"Clicked somewhere in the calendar.NRis%02d( RRtwidgett identify_rowtidentify_columnR!R,RtintRRR( R%RxRRRR,ROt item_valuesR0R((s4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyR~s"  cCs[|jj|j|jdd|_|j|jj|jjd|_|jdS(s,Updated calendar to show the previous month.tdaysiN(R.RwRt timedeltaRR R R"(R%((s4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyRVs $cCs|jj|jj|jj}}|j|jdtj||dd|_|j|jj|jjd|_|j dS(s'Update calendar to show the next month.RiN( R.RwRR R RRt monthrangeRR"(R%R R ((s4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyRWs  !$cCsF|js dS|jj|jj}}|j||t|jdS(s9Return a datetime representing the current selected date.iN(RRRR R RR(R%R R ((s4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyt selections N(t__name__t __module__RRRRRR1R7RRRRR$R"RR~RVRWtpropertyR(((s4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyRs    %       cCsddl}tj}|jdtdtj}|jddddd|jkrxt j }|j d n|j dS( Nis Ttk CalendarRRRiR3RStwintclam( tsysR{tTkRRRtSUNDAYR[tplatformRR>t theme_usetmainloop(RtroottttkcalR@((s4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyttests    t__main__( t__doc__RR{RnRRRRRR(((s4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyts      PK%L]Otkinter/ttk/dirbrowser.pyonu[ ^c @sdZddlZddlZddlZddlZdZdZdZdZdZ ej Z ej dd Z ej dd Zejd d)ddddddZeje d|dkr>|jn |j|j||dS(s"Hide and show scrollbar as needed.iiN(tfloatt grid_removetgridR (tsbartfirsttlast((s3/usr/lib64/python2.7/Demo/tkinter/ttk/dirbrowser.pyt autoscroll9s   torienttverticalt horizontaltcolumnsRRR tdisplaycolumnstyscrollcommandcCstt||S(N(R5tvsb(tftl((s3/usr/lib64/python2.7/Demo/tkinter/ttk/dirbrowser.pytHR%txscrollcommandcCstt||S(N(R5thsb(R=R>((s3/usr/lib64/python2.7/Demo/tkinter/ttk/dirbrowser.pyR?IR%tcommands#0RsDirectory Structuretanchortws File Sizetstretchitwidthids<>stcolumntrowtstickytnsweitnstewtweight(RRR (t__doc__RRtTkintertttkR$R(R,R.R5tTktroott ScrollbarR<RAtTreeviewRtyviewtxviewtheadingRGtbindR1tgrid_columnconfiguretgrid_rowconfiguretmainloop(((s3/usr/lib64/python2.7/Demo/tkinter/ttk/dirbrowser.pyts:            PK%L]#gg$tkinter/ttk/treeview_multicolumn.pyonu[ ^c@sdZddlZddlZddlZd6Zd7d8d9d:d;d<d=d>d?d@dAdBdCdDdEgZd1Zd2efd3YZd4Z e d5kre ndS(FsCDemo based on the demo mclist included with tk source distribution.iNtcountrytcapitaltcurrencyt Argentinas Buenos AirestARSt AustraliatCanberratAUDtBraziltBraziliatBRLtCanadatOttawatCADtChinatBeijingtCNYtFrancetParistEURtGermanytBerlintIndias New DelhitINRtItalytRometJapantTokyotJPYtMexicos Mexico CitytMXNtRussiatMoscowtRUBs South AfricatPretoriatZARsUnited KingdomtLondontGBPs United StatessWashington, D.C.tUSDcsgjdD]}j|||f^q}|jdx1t|D]#\}}j|dd|qQWj|d|fddS(s/Sort tree contents when a column is clicked on.ttreverseitcommandcst|t S(N(tsortbytint(tcol(t descendingttree(s=/usr/lib64/python2.7/Demo/tkinter/ttk/treeview_multicolumn.pyt%R'N(t get_childrentsettsortt enumeratetmovetheading(R.R,R-tchildtdatatindxtitem((R-R.s=/usr/lib64/python2.7/Demo/tkinter/ttk/treeview_multicolumn.pyR*s 4 tAppcBs#eZdZdZdZRS(cCs!d|_|j|jdS(N(tNoneR.t_setup_widgetst _build_tree(tself((s=/usr/lib64/python2.7/Demo/tkinter/ttk/treeview_multicolumn.pyt__init__(s  c Csetjdddddddd$d d }|jd dtj}|jd ddttjdtdd|_tjddd|jj }tjddd|jj }|jj d|j d|j |jj ddddddd||j dd dddd!d||j dddd dd"d||jdd#d |jdd#d dS(%Nt wraplengtht4itjustifytlefttanchortntpaddingi iittextsTtk is the new Tk themed widget set. One of the widgets it includes is a tree widget, which can be configured to display multiple columns of informational data without displaying the tree itself. This is a simple way to build a listbox that has multiple columns. Clicking on the heading for a column will sort the data by that column. You can also change the width of the columns by dragging the boundary between them.tfilltxtbothtexpandtcolumnstshowtheadingstorienttverticalR)t horizontaltyscrollcommandtxscrollcommandtcolumnitrowtstickytnsewtin_itnstewtweight(i ii i(tttktLabeltpacktFrametTruetTreeviewt tree_columnsR.t Scrollbartyviewtxviewt configureR1tgridtgrid_columnconfiguretgrid_rowconfigure(R>tmsgt containertvsbthsb((s=/usr/lib64/python2.7/Demo/tkinter/ttk/treeview_multicolumn.pyR<-s  %""c s xgtD]_}jj|d|jd|fdjj|dtjj|jqWxtD]}jj ddd|xnt |D]`\}}tjj|}jjt|dd|krjjt|d|qqWqqWdS(NRGR)cstj|dS(Ni(R*R.(tc(R>(s=/usr/lib64/python2.7/Demo/tkinter/ttk/treeview_multicolumn.pyR/MR'twidthR'tendtvalues( RbR.R5ttitleRTttkFonttFonttmeasuret tree_datatinsertR3R;(R>R,R9R8tvaltilen((R>s=/usr/lib64/python2.7/Demo/tkinter/ttk/treeview_multicolumn.pyR=Js / "(t__name__t __module__R?R<R=(((s=/usr/lib64/python2.7/Demo/tkinter/ttk/treeview_multicolumn.pyR:'s  cCstj}|jd|jdddl}y|jdWn*tk roddl}|jdnXt }|j dS(NsMulti-Column Listtmclistis~/tile-themes/plastik/plastiks'plastik theme being used without images( tTkintertTktwm_titlet wm_iconnamet plastik_themetinstallt ExceptiontwarningstwarnR:tmainloop(trootRRtapp((s=/usr/lib64/python2.7/Demo/tkinter/ttk/treeview_multicolumn.pytmain[s       t__main__(RRR(Rs Buenos AiresR(RRR(RR R (R R R (RRR(RRR(RRR(Rs New DelhiR(RRR(RRR(Rs Mexico CityR(RR R!(s South AfricaR"R#(sUnited KingdomR$R%(s United StatessWashington, D.C.R&( t__doc__R}RsR\RbRvR*tobjectR:RRz(((s=/usr/lib64/python2.7/Demo/tkinter/ttk/treeview_multicolumn.pyts0     4  PK%L]xa##tkinter/ttk/roundframe.pycnu[ ^c @sdZddlZddlZejZejdddZejdddZejZ e j dd dd%d d d de j ddidd 6fge j dddej ddddZejddej ddddZejddddejeddZejddejddejddejeddd d!d"dZejddddejdd#ejdd$ejdS(&shTtk Frame with rounded corners. Based on an example by Bryan Oakley, found at: http://wiki.tcl.tk/20152iNtframeFocusBordertdatas R0lGODlhQABAAPcAAHx+fMTCxKSipOTi5JSSlNTS1LSytPTy9IyKjMzKzKyq rOzq7JyanNza3Ly6vPz6/ISChMTGxKSmpOTm5JSWlNTW1LS2tPT29IyOjMzO zKyurOzu7JyenNze3Ly+vPz+/OkAKOUA5IEAEnwAAACuQACUAAFBAAB+AFYd QAC0AABBAAB+AIjMAuEEABINAAAAAHMgAQAAAAAAAAAAAKjSxOIEJBIIpQAA sRgBMO4AAJAAAHwCAHAAAAUAAJEAAHwAAP+eEP8CZ/8Aif8AAG0BDAUAAJEA AHwAAIXYAOfxAIESAHwAAABAMQAbMBZGMAAAIEggJQMAIAAAAAAAfqgaXESI 5BdBEgB+AGgALGEAABYAAAAAAACsNwAEAAAMLwAAAH61MQBIAABCM8B+AAAU AAAAAAAApQAAsf8Brv8AlP8AQf8Afv8AzP8A1P8AQf8AfgAArAAABAAADAAA AACQDADjAAASAAAAAACAAADVABZBAAB+ALjMwOIEhxINUAAAANIgAOYAAIEA AHwAAGjSAGEEABYIAAAAAEoBB+MAAIEAAHwCACABAJsAAFAAAAAAAGjJAGGL AAFBFgB+AGmIAAAQAABHAAB+APQoAOE/ABIAAAAAAADQAADjAAASAAAAAPiF APcrABKDAAB8ABgAGO4AAJAAqXwAAHAAAAUAAJEAAHwAAP8AAP8AAP8AAP8A AG0pIwW3AJGSAHx8AEocI/QAAICpAHwAAAA0SABk6xaDEgB8AAD//wD//wD/ /wD//2gAAGEAABYAAAAAAAC0/AHj5AASEgAAAAA01gBkWACDTAB8AFf43PT3 5IASEnwAAOAYd+PuMBKQTwB8AGgAEGG35RaSEgB8AOj/NOL/ZBL/gwD/fMkc q4sA5UGpEn4AAIg02xBk/0eD/358fx/4iADk5QASEgAAAALnHABkAACDqQB8 AMyINARkZA2DgwB8fBABHL0AAEUAqQAAAIAxKOMAPxIwAAAAAIScAOPxABIS AAAAAIIAnQwA/0IAR3cAACwAAAAAQABAAAAI/wA/CBxIsKDBgwgTKlzIsKFD gxceNnxAsaLFixgzUrzAsWPFCw8kDgy5EeQDkBxPolypsmXKlx1hXnS48UEH CwooMCDAgIJOCjx99gz6k+jQnkWR9lRgYYDJkAk/DlAgIMICZlizat3KtatX rAsiCNDgtCJClQkoFMgqsu3ArBkoZDgA8uDJAwk4bGDmtm9BZgcYzK078m4D Cgf4+l0skNkGCg3oUhR4d4GCDIoZM2ZWQMECyZQvLMggIbPmzQIyfCZ5YcME AwFMn/bLLIKBCRtMHljQQcDV2ZqZTRDQYfWFAwMqUJANvC8zBhUWbDi5YUAB Bsybt2VGoUKH3AcmdP+Im127xOcJih+oXsEDdvOLuQfIMGBD9QwBlsOnzcBD hfrsuVfefgzJR599A+CnH4Hb9fcfgu29x6BIBgKYYH4DTojQc/5ZGGGGGhpU IYIKghgiQRw+GKCEJxZIwXwWlthiQyl6KOCMLsJIIoY4LlQjhDf2mNCI9/Eo 5IYO2sjikX+9eGCRCzL5V5JALillY07GaOSVb1G5ookzEnlhlFx+8OOXZb6V 5Y5kcnlmckGmKaaMaZrpJZxWXjnnlmW++WGdZq5ZXQEetKmnlxPgl6eUYhJq KKOI0imnoNbF2ScFHQJJwW99TsBAAAVYWEAAHEQAZoi1cQDqAAeEV0EACpT/ JqcACgRQAW6uNWCbYKcyyEwGDBgQwa2tTlBBAhYIQMFejC5AgQAWJNDABK3y loEDEjCgV6/aOcYBAwp4kIF6rVkXgAEc8IQZVifCBRQHGqya23HGIpsTBgSU OsFX/PbrVVjpYsCABA4kQCxHu11ogAQUIOAwATpBLDFQFE9sccUYS0wAxD5h 4DACFEggbAHk3jVBA/gtTIHHEADg8sswxyzzzDQDAAEECGAQsgHiTisZResN gLIHBijwLQEYePzx0kw37fTSSjuMr7ZMzfcgYZUZi58DGsTKwbdgayt22GSP bXbYY3MggQIaONDzAJ8R9kFlQheQQAAOWGCAARrwdt23Bn8H7vfggBMueOEG WOBBAAkU0EB9oBGUdXIFZJBABAEEsPjmmnfO+eeeh/55BBEk0Ph/E8Q9meQq bbDABAN00EADFRRQ++2254777rr3jrvjFTTQwQCpz7u6QRut5/oEzA/g/PPQ Ry/99NIz//oGrZpUUEAAOw==t frameBorders R0lGODlhQABAAPcAAHx+fMTCxKSipOTi5JSSlNTS1LSytPTy9IyKjMzKzKyq rOzq7JyanNza3Ly6vPz6/ISChMTGxKSmpOTm5JSWlNTW1LS2tPT29IyOjMzO zKyurOzu7JyenNze3Ly+vPz+/OkAKOUA5IEAEnwAAACuQACUAAFBAAB+AFYd QAC0AABBAAB+AIjMAuEEABINAAAAAHMgAQAAAAAAAAAAAKjSxOIEJBIIpQAA sRgBMO4AAJAAAHwCAHAAAAUAAJEAAHwAAP+eEP8CZ/8Aif8AAG0BDAUAAJEA AHwAAIXYAOfxAIESAHwAAABAMQAbMBZGMAAAIEggJQMAIAAAAAAAfqgaXESI 5BdBEgB+AGgALGEAABYAAAAAAACsNwAEAAAMLwAAAH61MQBIAABCM8B+AAAU AAAAAAAApQAAsf8Brv8AlP8AQf8Afv8AzP8A1P8AQf8AfgAArAAABAAADAAA AACQDADjAAASAAAAAACAAADVABZBAAB+ALjMwOIEhxINUAAAANIgAOYAAIEA AHwAAGjSAGEEABYIAAAAAEoBB+MAAIEAAHwCACABAJsAAFAAAAAAAGjJAGGL AAFBFgB+AGmIAAAQAABHAAB+APQoAOE/ABIAAAAAAADQAADjAAASAAAAAPiF APcrABKDAAB8ABgAGO4AAJAAqXwAAHAAAAUAAJEAAHwAAP8AAP8AAP8AAP8A AG0pIwW3AJGSAHx8AEocI/QAAICpAHwAAAA0SABk6xaDEgB8AAD//wD//wD/ /wD//2gAAGEAABYAAAAAAAC0/AHj5AASEgAAAAA01gBkWACDTAB8AFf43PT3 5IASEnwAAOAYd+PuMBKQTwB8AGgAEGG35RaSEgB8AOj/NOL/ZBL/gwD/fMkc q4sA5UGpEn4AAIg02xBk/0eD/358fx/4iADk5QASEgAAAALnHABkAACDqQB8 AMyINARkZA2DgwB8fBABHL0AAEUAqQAAAIAxKOMAPxIwAAAAAIScAOPxABIS AAAAAIIAnQwA/0IAR3cAACwAAAAAQABAAAAI/wA/CBxIsKDBgwgTKlzIsKFD gxceNnxAsaLFixgzUrzAsWPFCw8kDgy5EeQDkBxPolypsmXKlx1hXnS48UEH CwooMCDAgIJOCjx99gz6k+jQnkWR9lRgYYDJkAk/DlAgIMICkVgHLoggQIPT ighVJqBQIKvZghkoZDgA8uDJAwk4bDhLd+ABBmvbjnzbgMKBuoA/bKDQgC1F gW8XKMgQOHABBQsMI76wIIOExo0FZIhM8sKGCQYCYA4cwcCEDSYPLOgg4Oro uhMEdOB84cCAChReB2ZQYcGGkxsGFGCgGzCFCh1QH5jQIW3xugwSzD4QvIIH 4s/PUgiQYcCG4BkC5P/ObpaBhwreq18nb3Z79+8Dwo9nL9I8evjWsdOX6D59 fPH71Xeef/kFyB93/sln4EP2Ebjegg31B5+CEDLUIH4PVqiQhOABqKFCF6qn 34cHcfjffCQaFOJtGaZYkIkUuljQigXK+CKCE3po40A0trgjjDru+EGPI/6I Y4co7kikkAMBmaSNSzL5gZNSDjkghkXaaGIBHjwpY4gThJeljFt2WSWYMQpZ 5pguUnClehS4tuMEDARQgH8FBMBBBExGwIGdAxywXAUBKHCZkAIoEEAFp33W QGl47ZgBAwZEwKigE1SQgAUCUDCXiwtQIIAFCTQwgaCrZeCABAzIleIGHDD/ oIAHGUznmXABGMABT4xpmBYBHGgAKGq1ZbppThgAG8EEAW61KwYMSOBAApdy pNp/BkhAAQLcEqCTt+ACJW645I5rLrgEeOsTBtwiQIEElRZg61sTNBBethSw CwEA/Pbr778ABywwABBAgAAG7xpAq6mGUUTdAPZ6YIACsRKAAbvtZqzxxhxn jDG3ybbKFHf36ZVYpuE5oIGhHMTqcqswvyxzzDS/HDMHEiiggQMLDxCZXh8k BnEBCQTggAUGGKCB0ktr0PTTTEfttNRQT22ABR4EkEABDXgnGUEn31ZABglE EEAAWaeN9tpqt832221HEEECW6M3wc+Hga3SBgtMODBABw00UEEBgxdO+OGG J4744oZzXUEDHQxwN7F5G7QRdXxPoPkAnHfu+eeghw665n1vIKhJBQUEADs=t RoundedFrametimagetfocustborderitstickytnsewtTEntryt borderwidthitstyletpaddingi tfilltxtbothtexpandittexttTests cCstjdgS(NR(tframetstate(tevt((s3/usr/lib64/python2.7/Demo/tkinter/ttk/roundframe.pytgts cCstjdgS(Ns!focus(RR(R((s3/usr/lib64/python2.7/Demo/tkinter/ttk/roundframe.pyRhRtbgtwhitethighlightthicknesscCstjdgS(NR(tframe2R(R((s3/usr/lib64/python2.7/Demo/tkinter/ttk/roundframe.pyRlRcCstjdgS(Ns!focus(RR(R((s3/usr/lib64/python2.7/Demo/tkinter/ttk/roundframe.pyRmR(RR(t__doc__tTkintertttktTktroott PhotoImagetimg1timg2tStyleR telement_createtlayoutt configuretFrameRtpackRtEntrytentrytbindtTextRtmainloop(((s3/usr/lib64/python2.7/Demo/tkinter/ttk/roundframe.pyts2    &  $   !PK%L]j:^^tkinter/ttk/plastik_theme.pyonu[ ^c@sdZddlZddlZddlZddlmZdgZidd6dd6d d 6d d 6ZiZd Z dZ dS(ssThis demonstrates good part of the syntax accepted by theme_create. This is a translation of plastik.tcl to python. You will need the images used by the plastik theme to test this. The images (and other tile themes) can be retrived by doing: $ cvs -z3 -d:pserver:anonymous@tktable.cvs.sourceforge.net:/cvsroot/tktable co tile-themes To test this module you should do, for example: import Tkinter import plastik_theme root = Tkinter.Tk() plastik_theme.install(plastik_image_dir) ... Where plastik_image_dir contains the path to the images directory used by the plastik theme, something like: tile-themes/plastik/plastik iN(t PhotoImagetinstalls#efefeftframes#aaaaaat disabledfgs#657a9etselectbgs#fffffftselectfgcCstjj|}tjj|s7td|nxWtjd|D]B}tjj|d}|d }t|d|ddt|id)d6fd?id@idAid'd6dd 6fgd#6fgd#6fgd#6fgd$6dB6iidCdDdCdCgdE6d6dF6iidGdDdGdDgdH6dCdCdDgd 6d6idIddDdJdDgfgd 6d6dK6iidCdH6d6dL6idMdNddidJd/gdS6dJdH6dTd6fdU6d36idMdVdddidJdYgdS6dZdH6d[d6fdU6d96idMd\ddddidd6fdU6da6idMdbddddidd6fdU6dg6idMdhidZdS6d+d6fdU6d,6iddU6d-6iddU6d*6idMdkidZdS6dd6fdU6d6iddU6d"6iddU6d6idMdndidd6fdU6dp6idMdqdidd6fdU6ds6idMdtdidd6fdU6dv6idMdwdidd6fdU6dy6idMdzidd6fdU6d{6idMd|iddS6dCdH6fdU6d}6idMd~idd6fdU6d6idMdiddS6dCdH6fdU6d6idMddidDdS6dZdJgdH6d[d6fdU6d6idMdSidJdS6dJdH6d[d6fdU6d6idMddid[d6dJdGddgdS6dJdJdgdH6fdU6d=6idMdidd6ddCdCdCgdS6fdU6d>6idMddddddidJdGddgdS6dJdJdgdH6d[d6fdU6d6idMdidd6ddCdCdCgdS6fdU6d6idMdidJdS6fdU6d6idMdddidCdDdCdCgdH6dJd/dJd/gdS6fdU6d6idMdidDdS6fdU6d6idMdidDdYgdS6fdU6d6idMdidYdDgdS6fdU6d6idMddidJd/gdS6dJdH6d[d6fdU6d6|jddS(NtplastiktdefaulttsettingsRt backgroundt troughcolorRtselectbackgroundRtselectforegroundtfieldbackgroundt TkDefaultFonttfontit borderwidtht configuretdisabledRt foregroundtmapt.sVertical.Scrollbar.uparrowttoptsidettstickysVertical.Scrollbar.downarrowtbottomsVertical.Scrollbar.troughtnssVertical.Scrollbar.thumbtexpandtunitsVertical.Scrollbar.griptchildrentlayoutsVertical.TScrollbarsHorizontal.Scrollbar.leftarrowtleftsHorizontal.Scrollbar.rightarrowtrightsHorizontal.Scrollbar.troughtewsHorizontal.Scrollbar.thumbsHorizontal.Scrollbar.gripsHorizontal.TScrollbari twidthtcentertanchors Button.buttons Button.focussButton.paddings Button.labeltTButtonsToolbutton.bordersToolbutton.buttonsToolbutton.paddingsToolbutton.labelt ToolbuttonsMenubutton.buttonsMenubutton.indicatorsMenubutton.focussMenubutton.paddingsMenubutton.labelt TMenubuttoniit tabmarginst TNotebookitpaddingtselectedis TNotebook.tabtTreeviewtimagesbutton-ntpressedsbutton-ptactivesbutton-htbordertewnsselement creates tbutton-ns tbutton-ps tbutton-hi itnewsscheck-nuscheck-hcscheck-pcscheck-huscheck-ncsCheckbutton.indicatorsradio-nusradio-hcsradio-pcsradio-husradio-ncsRadiobutton.indicatorshsb-nshsb-gshsb-tsvsb-nsvsb-gsvsb-ts arrowup-ns arrowup-psScrollbar.uparrows arrowdown-ns arrowdown-psScrollbar.downarrows arrowleft-ns arrowleft-psScrollbar.leftarrows arrowright-ns arrowright-psScrollbar.rightarrows hslider-nsHorizontal.Scale.sliders hslider-tsHorizontal.Scale.troughs vslider-nsVertical.Scale.sliders vslider-tsVertical.Scale.troughsentry-ntfocussentry-fs Entry.fieldsLabelframe.borderscombo-rscombo-raiiisarrow-dtescombo-ntreadonlyscombo-fascombo-as !readonlyscombo-fsCombobox.fieldsCombobox.downarrows notebook-csNotebook.clients notebook-tns notebook-tss notebook-tas Notebook.tabs hprogress-tsProgressbar.troughs hprogress-bsHorizontal.Progressbar.pbars vprogress-bsVertical.Progressbar.pbarstree-nstree-psTreeheading.cell(R?sbutton-p(R@sbutton-h(R<s tbutton-p(R?s tbutton-p(R@s tbutton-h(R@R<scheck-hc(R?R<scheck-pc(R@scheck-hu(R<scheck-nc(R@R<sradio-hc(R?R<sradio-pc(R@sradio-hu(R<sradio-nc(R>shsb-g(R>shsb-t(R>svsb-g(R>svsb-t(R?s arrowup-p(R?s arrowdown-p(R?s arrowleft-p(R?s arrowright-p(RDsentry-f(R@scombo-ra(RFR@scombo-ra(RDR@scombo-fa(R@scombo-a(s !readonlyRDscombo-f(RFscombo-r(R<s notebook-ts(R@s notebook-ta(R?stree-p(RtttktStylet theme_createtcolorst theme_use(Rtstyle((s6/usr/lib64/python2.7/Demo/tkinter/ttk/plastik_theme.pyR.s        / /@@@!*'))"" "")).&.4!!-( t__doc__R RRGtTkinterRt__all__RJRRR(((s6/usr/lib64/python2.7/Demo/tkinter/ttk/plastik_theme.pyts      PK%L]xa##tkinter/ttk/roundframe.pyonu[ ^c @sdZddlZddlZejZejdddZejdddZejZ e j dd dd%d d d de j ddidd 6fge j dddej ddddZejddej ddddZejddddejeddZejddejddejddejeddd d!d"dZejddddejdd#ejdd$ejdS(&shTtk Frame with rounded corners. Based on an example by Bryan Oakley, found at: http://wiki.tcl.tk/20152iNtframeFocusBordertdatas R0lGODlhQABAAPcAAHx+fMTCxKSipOTi5JSSlNTS1LSytPTy9IyKjMzKzKyq rOzq7JyanNza3Ly6vPz6/ISChMTGxKSmpOTm5JSWlNTW1LS2tPT29IyOjMzO zKyurOzu7JyenNze3Ly+vPz+/OkAKOUA5IEAEnwAAACuQACUAAFBAAB+AFYd QAC0AABBAAB+AIjMAuEEABINAAAAAHMgAQAAAAAAAAAAAKjSxOIEJBIIpQAA sRgBMO4AAJAAAHwCAHAAAAUAAJEAAHwAAP+eEP8CZ/8Aif8AAG0BDAUAAJEA AHwAAIXYAOfxAIESAHwAAABAMQAbMBZGMAAAIEggJQMAIAAAAAAAfqgaXESI 5BdBEgB+AGgALGEAABYAAAAAAACsNwAEAAAMLwAAAH61MQBIAABCM8B+AAAU AAAAAAAApQAAsf8Brv8AlP8AQf8Afv8AzP8A1P8AQf8AfgAArAAABAAADAAA AACQDADjAAASAAAAAACAAADVABZBAAB+ALjMwOIEhxINUAAAANIgAOYAAIEA AHwAAGjSAGEEABYIAAAAAEoBB+MAAIEAAHwCACABAJsAAFAAAAAAAGjJAGGL AAFBFgB+AGmIAAAQAABHAAB+APQoAOE/ABIAAAAAAADQAADjAAASAAAAAPiF APcrABKDAAB8ABgAGO4AAJAAqXwAAHAAAAUAAJEAAHwAAP8AAP8AAP8AAP8A AG0pIwW3AJGSAHx8AEocI/QAAICpAHwAAAA0SABk6xaDEgB8AAD//wD//wD/ /wD//2gAAGEAABYAAAAAAAC0/AHj5AASEgAAAAA01gBkWACDTAB8AFf43PT3 5IASEnwAAOAYd+PuMBKQTwB8AGgAEGG35RaSEgB8AOj/NOL/ZBL/gwD/fMkc q4sA5UGpEn4AAIg02xBk/0eD/358fx/4iADk5QASEgAAAALnHABkAACDqQB8 AMyINARkZA2DgwB8fBABHL0AAEUAqQAAAIAxKOMAPxIwAAAAAIScAOPxABIS AAAAAIIAnQwA/0IAR3cAACwAAAAAQABAAAAI/wA/CBxIsKDBgwgTKlzIsKFD gxceNnxAsaLFixgzUrzAsWPFCw8kDgy5EeQDkBxPolypsmXKlx1hXnS48UEH CwooMCDAgIJOCjx99gz6k+jQnkWR9lRgYYDJkAk/DlAgIMICZlizat3KtatX rAsiCNDgtCJClQkoFMgqsu3ArBkoZDgA8uDJAwk4bGDmtm9BZgcYzK078m4D Cgf4+l0skNkGCg3oUhR4d4GCDIoZM2ZWQMECyZQvLMggIbPmzQIyfCZ5YcME AwFMn/bLLIKBCRtMHljQQcDV2ZqZTRDQYfWFAwMqUJANvC8zBhUWbDi5YUAB Bsybt2VGoUKH3AcmdP+Im127xOcJih+oXsEDdvOLuQfIMGBD9QwBlsOnzcBD hfrsuVfefgzJR599A+CnH4Hb9fcfgu29x6BIBgKYYH4DTojQc/5ZGGGGGhpU IYIKghgiQRw+GKCEJxZIwXwWlthiQyl6KOCMLsJIIoY4LlQjhDf2mNCI9/Eo 5IYO2sjikX+9eGCRCzL5V5JALillY07GaOSVb1G5ookzEnlhlFx+8OOXZb6V 5Y5kcnlmckGmKaaMaZrpJZxWXjnnlmW++WGdZq5ZXQEetKmnlxPgl6eUYhJq KKOI0imnoNbF2ScFHQJJwW99TsBAAAVYWEAAHEQAZoi1cQDqAAeEV0EACpT/ JqcACgRQAW6uNWCbYKcyyEwGDBgQwa2tTlBBAhYIQMFejC5AgQAWJNDABK3y loEDEjCgV6/aOcYBAwp4kIF6rVkXgAEc8IQZVifCBRQHGqya23HGIpsTBgSU OsFX/PbrVVjpYsCABA4kQCxHu11ogAQUIOAwATpBLDFQFE9sccUYS0wAxD5h 4DACFEggbAHk3jVBA/gtTIHHEADg8sswxyzzzDQDAAEECGAQsgHiTisZResN gLIHBijwLQEYePzx0kw37fTSSjuMr7ZMzfcgYZUZi58DGsTKwbdgayt22GSP bXbYY3MggQIaONDzAJ8R9kFlQheQQAAOWGCAARrwdt23Bn8H7vfggBMueOEG WOBBAAkU0EB9oBGUdXIFZJBABAEEsPjmmnfO+eeeh/55BBEk0Ph/E8Q9meQq bbDABAN00EADFRRQ++2254777rr3jrvjFTTQwQCpz7u6QRut5/oEzA/g/PPQ Ry/99NIz//oGrZpUUEAAOw==t frameBorders R0lGODlhQABAAPcAAHx+fMTCxKSipOTi5JSSlNTS1LSytPTy9IyKjMzKzKyq rOzq7JyanNza3Ly6vPz6/ISChMTGxKSmpOTm5JSWlNTW1LS2tPT29IyOjMzO zKyurOzu7JyenNze3Ly+vPz+/OkAKOUA5IEAEnwAAACuQACUAAFBAAB+AFYd QAC0AABBAAB+AIjMAuEEABINAAAAAHMgAQAAAAAAAAAAAKjSxOIEJBIIpQAA sRgBMO4AAJAAAHwCAHAAAAUAAJEAAHwAAP+eEP8CZ/8Aif8AAG0BDAUAAJEA AHwAAIXYAOfxAIESAHwAAABAMQAbMBZGMAAAIEggJQMAIAAAAAAAfqgaXESI 5BdBEgB+AGgALGEAABYAAAAAAACsNwAEAAAMLwAAAH61MQBIAABCM8B+AAAU AAAAAAAApQAAsf8Brv8AlP8AQf8Afv8AzP8A1P8AQf8AfgAArAAABAAADAAA AACQDADjAAASAAAAAACAAADVABZBAAB+ALjMwOIEhxINUAAAANIgAOYAAIEA AHwAAGjSAGEEABYIAAAAAEoBB+MAAIEAAHwCACABAJsAAFAAAAAAAGjJAGGL AAFBFgB+AGmIAAAQAABHAAB+APQoAOE/ABIAAAAAAADQAADjAAASAAAAAPiF APcrABKDAAB8ABgAGO4AAJAAqXwAAHAAAAUAAJEAAHwAAP8AAP8AAP8AAP8A AG0pIwW3AJGSAHx8AEocI/QAAICpAHwAAAA0SABk6xaDEgB8AAD//wD//wD/ /wD//2gAAGEAABYAAAAAAAC0/AHj5AASEgAAAAA01gBkWACDTAB8AFf43PT3 5IASEnwAAOAYd+PuMBKQTwB8AGgAEGG35RaSEgB8AOj/NOL/ZBL/gwD/fMkc q4sA5UGpEn4AAIg02xBk/0eD/358fx/4iADk5QASEgAAAALnHABkAACDqQB8 AMyINARkZA2DgwB8fBABHL0AAEUAqQAAAIAxKOMAPxIwAAAAAIScAOPxABIS AAAAAIIAnQwA/0IAR3cAACwAAAAAQABAAAAI/wA/CBxIsKDBgwgTKlzIsKFD gxceNnxAsaLFixgzUrzAsWPFCw8kDgy5EeQDkBxPolypsmXKlx1hXnS48UEH CwooMCDAgIJOCjx99gz6k+jQnkWR9lRgYYDJkAk/DlAgIMICkVgHLoggQIPT ighVJqBQIKvZghkoZDgA8uDJAwk4bDhLd+ABBmvbjnzbgMKBuoA/bKDQgC1F gW8XKMgQOHABBQsMI76wIIOExo0FZIhM8sKGCQYCYA4cwcCEDSYPLOgg4Oro uhMEdOB84cCAChReB2ZQYcGGkxsGFGCgGzCFCh1QH5jQIW3xugwSzD4QvIIH 4s/PUgiQYcCG4BkC5P/ObpaBhwreq18nb3Z79+8Dwo9nL9I8evjWsdOX6D59 fPH71Xeef/kFyB93/sln4EP2Ebjegg31B5+CEDLUIH4PVqiQhOABqKFCF6qn 34cHcfjffCQaFOJtGaZYkIkUuljQigXK+CKCE3po40A0trgjjDru+EGPI/6I Y4co7kikkAMBmaSNSzL5gZNSDjkghkXaaGIBHjwpY4gThJeljFt2WSWYMQpZ 5pguUnClehS4tuMEDARQgH8FBMBBBExGwIGdAxywXAUBKHCZkAIoEEAFp33W QGl47ZgBAwZEwKigE1SQgAUCUDCXiwtQIIAFCTQwgaCrZeCABAzIleIGHDD/ oIAHGUznmXABGMABT4xpmBYBHGgAKGq1ZbppThgAG8EEAW61KwYMSOBAApdy pNp/BkhAAQLcEqCTt+ACJW645I5rLrgEeOsTBtwiQIEElRZg61sTNBBethSw CwEA/Pbr778ABywwABBAgAAG7xpAq6mGUUTdAPZ6YIACsRKAAbvtZqzxxhxn jDG3ybbKFHf36ZVYpuE5oIGhHMTqcqswvyxzzDS/HDMHEiiggQMLDxCZXh8k BnEBCQTggAUGGKCB0ktr0PTTTEfttNRQT22ABR4EkEABDXgnGUEn31ZABglE EEAAWaeN9tpqt832221HEEECW6M3wc+Hga3SBgtMODBABw00UEEBgxdO+OGG J4744oZzXUEDHQxwN7F5G7QRdXxPoPkAnHfu+eeghw665n1vIKhJBQUEADs=t RoundedFrametimagetfocustborderitstickytnsewtTEntryt borderwidthitstyletpaddingi tfilltxtbothtexpandittexttTests cCstjdgS(NR(tframetstate(tevt((s3/usr/lib64/python2.7/Demo/tkinter/ttk/roundframe.pytgts cCstjdgS(Ns!focus(RR(R((s3/usr/lib64/python2.7/Demo/tkinter/ttk/roundframe.pyRhRtbgtwhitethighlightthicknesscCstjdgS(NR(tframe2R(R((s3/usr/lib64/python2.7/Demo/tkinter/ttk/roundframe.pyRlRcCstjdgS(Ns!focus(RR(R((s3/usr/lib64/python2.7/Demo/tkinter/ttk/roundframe.pyRmR(RR(t__doc__tTkintertttktTktroott PhotoImagetimg1timg2tStyleR telement_createtlayoutt configuretFrameRtpackRtEntrytentrytbindtTextRtmainloop(((s3/usr/lib64/python2.7/Demo/tkinter/ttk/roundframe.pyts2    &  $   !PK%L][tkinter/ttk/mac_searchentry.pynu["""Mac style search widget Translated from Tcl code by Schelte Bron, http://wiki.tcl.tk/18188 """ import Tkinter import ttk root = Tkinter.Tk() data = """ R0lGODlhKgAaAOfnAFdZVllbWFpcWVtdWlxeW11fXF9hXmBiX2ZnZWhpZ2lraGxua25wbXJ0 cXR2c3V3dHZ4dXh6d3x+e31/fH6AfYSGg4eJhoiKh4qMiYuNio2PjHmUqnqVq3yXrZGTkJKU kX+asJSWk32cuJWXlIGcs5aYlX6euZeZloOetZial4SftpqbmIWgt4GhvYahuIKivpudmYei uYOjv5yem4ijuoSkwIWlwYmlu56gnYamwp+hnoenw4unvaCin4ioxJCnuZykrImpxZmlsoaq zI2pv6KkoZGouoqqxpqms4erzaOloo6qwYurx5Kqu5untIiszqSmo5CrwoysyJeqtpOrvJyo tZGsw42typSsvaaopZKtxJWtvp6qt4+uy6epppOuxZCvzKiqp5quuZSvxoyx06mrqJWwx42y 1JKxzpmwwaqsqZaxyI6z1ZqxwqutqpOzz4+01qyuq56yvpizypS00Jm0y5W10Zq1zJa20rCy rpu3zqizwbGzr6C3yZy4z7K0saG4yp250LO1sqK5y5660Z+70qO7zKy4xaC806S8zba4taG9 1KW9zq66x6+7yLi6t6S/1rC8yrm7uLO8xLG9y7q8ubS9xabB2anB07K+zLW+xrO/za7CzrTA zrjAyLXBz77BvbbC0K/G2LjD0bnE0rLK28TGw8bIxcLL07vP28HN28rMycvOyr/T38DU4cnR 2s/RztHT0NLU0cTY5MrW5MvX5dHX2c3Z59bY1dPb5Nbb3dLe7Nvd2t3f3NXh797g3d3j5dnl 9OPl4eTm4+Ln6tzo9uXn5Obo5eDp8efp5uHq8uXq7ejq5+nr6OPs9Ovu6unu8O3v6+vw8+7w 7ezx9O/x7vDy7/Hz8O/19/P18vT38/L3+fb49Pf59vX6/fj69/b7/vn7+Pr8+ff9//v9+vz/ +/7//P////////////////////////////////////////////////////////////////// /////////////////////////////////yH/C05FVFNDQVBFMi4wAwEAAAAh+QQJZAD/ACwC AAIAKAAWAAAI/gD/CRz4bwUGCg8eQFjIsGHDBw4iTLAQgqBFgisuePCiyJOpUyBDihRpypMi Lx8qaLhIMIyGFZ5sAUsmjZrNmzhzWpO2DJgtTysqfGDpxoMbW8ekeQsXzty4p1CjRjUXrps3 asJsuclQ4uKKSbamMR3n1JzZs2jRkh1HzuxVXX8y4CDYAwqua+DInVrRwMGJU2kDp31KThy1 XGWGDlxhi1rTPAUICBBAoEAesoIzn6Vm68MKgVAUHftmzhOCBCtQwQKSoABgzZnJdSMmyIPA FbCotdUQAIhNa9B6DPCAGbZac+SowVIMRVe4pwkA4GpqDlwuAAmMZx4nTtfnf1mO5JEDNy46 MHJkxQEDgKC49rPjwC0bqGaZuOoZAKjBPE4NgAzUvYcWOc0QZF91imAnCDHJ5JFAAJN0I2Ba 4iRDUC/gOEVNDwIUcEABCAgAAATUTIgWOMBYRFp80ghiAQIIVAAEAwJIYI2JZnUji0XSYAYO NcsQA8wy0hCTwAASXGOiONFcxAtpTokTHznfiLMNMAkcAMuE43jDC0vLeGOWe2R5o4sn1LgH GzkWsvTPMgEOaA433Ag4TjjMuDkQMNi0tZ12sqWoJ0HATMPNffAZZ6U0wLAyqJ62RGoLLrhI aqmlpzwaEAAh+QQJZAD/ACwAAAAAKgAaAAAI/gD/CRw40JEhQoEC+fGjcOHCMRAjRkxDsKLF f5YcAcID582ZjyBDJhmZZIjJIUySEDHiBMhFghrtdNnRAgSHmzhz6sTZQcSLITx+CHn5bxSk Nz5MCMGy55CjTVCjbuJEtSrVQ3uwqDBRQwrFi476SHHxow8qXcemVbPGtm21t3CnTaP27Jgu VHtuiIjBsuImQkRiiEEFTNo2cOTMKV7MuLE5cN68QUOGSgwKG1EqJqJDY8+rZt8UjxtNunTj cY3DgZOWS46KIFgGjiI0ZIsqaqNNjWjgYMUpx8Adc3v2aosNMAI1DbqyI9WycOb4IAggQEAB A3lQBxet/TG4cMpI/tHwYeSfIzxM0uTKNs7UgAQrYL1akaDA7+3bueVqY4NJlUhIcQLNYx8E AIQ01mwjTQ8DeNAdfouNA8440GBCQxJY3MEGD6p4Y844CQCAizcSgpMLAAlAuJ03qOyQRBR3 nEHEK+BMGKIui4kDDAAIPKiiYuSYSMQQRCDCxhiziPMYBgDkEaEaAGQA3Y+MjUPOLFoMoUUh cKxRC4ngeILiH8Qkk0cCAUzSDZWpzbLEE1EwggcYqWCj2DNADFDAAQUgIAAAEFDDJmPYqNJF F1s4cscTmCDjDTjdSPOHBQggUAEQDAgggTWDPoYMJkFoUdRmddyyjWLeULMMMcAsIw0x4wkM IME1g25zyxpHxFYUHmyIggw4H4ojITnfiLMNMAkcAAub4BQjihRdDGTJHmvc4Qo1wD6Imje6 eILbj+BQ4wqu5Q3ECSJ0FOKKMtv4mBg33Pw4zjbKuBIIE1xYpIkhdQQiyi7OtAucj6dt48wu otQhBRa6VvSJIRwhIkotvgRTzMUYZ6xxMcj4QkspeKDxxRhEmUfIHWjAgQcijEDissuXvCyz zH7Q8YQURxDhUsn/bCInR3AELfTQZBRt9BBJkCGFFVhMwTNBlnBCSCGEIJQQIAklZMXWRBAR RRRWENHwRQEBADs=""" s1 = Tkinter.PhotoImage("search1", data=data, format="gif -index 0") s2 = Tkinter.PhotoImage("search2", data=data, format="gif -index 1") style = ttk.Style() style.element_create("Search.field", "image", "search1", ("focus", "search2"), border=[22, 7, 14], sticky="ew") style.layout("Search.entry", [ ("Search.field", {"sticky": "nswe", "border": 1, "children": [("Entry.padding", {"sticky": "nswe", "children": [("Entry.textarea", {"sticky": "nswe"})] })] })] ) style.configure("Search.entry", background="#b2b2b2") root.configure(background="#b2b2b2") e1 = ttk.Entry(style="Search.entry", width=20) e2 = ttk.Entry(style="Search.entry", width=20) e1.grid(padx=10, pady=10) e2.grid(padx=10, pady=10) root.mainloop() PK%L]^#tkinter/ttk/treeview_multicolumn.pynu["""Demo based on the demo mclist included with tk source distribution.""" import Tkinter import tkFont import ttk tree_columns = ("country", "capital", "currency") tree_data = [ ("Argentina", "Buenos Aires", "ARS"), ("Australia", "Canberra", "AUD"), ("Brazil", "Brazilia", "BRL"), ("Canada", "Ottawa", "CAD"), ("China", "Beijing", "CNY"), ("France", "Paris", "EUR"), ("Germany", "Berlin", "EUR"), ("India", "New Delhi", "INR"), ("Italy", "Rome", "EUR"), ("Japan", "Tokyo", "JPY"), ("Mexico", "Mexico City", "MXN"), ("Russia", "Moscow", "RUB"), ("South Africa", "Pretoria", "ZAR"), ("United Kingdom", "London", "GBP"), ("United States", "Washington, D.C.", "USD") ] def sortby(tree, col, descending): """Sort tree contents when a column is clicked on.""" # grab values to sort data = [(tree.set(child, col), child) for child in tree.get_children('')] # reorder data data.sort(reverse=descending) for indx, item in enumerate(data): tree.move(item[1], '', indx) # switch the heading so that it will sort in the opposite direction tree.heading(col, command=lambda col=col: sortby(tree, col, int(not descending))) class App(object): def __init__(self): self.tree = None self._setup_widgets() self._build_tree() def _setup_widgets(self): msg = ttk.Label(wraplength="4i", justify="left", anchor="n", padding=(10, 2, 10, 6), text=("Ttk is the new Tk themed widget set. One of the widgets it " "includes is a tree widget, which can be configured to " "display multiple columns of informational data without " "displaying the tree itself. This is a simple way to build " "a listbox that has multiple columns. Clicking on the " "heading for a column will sort the data by that column. " "You can also change the width of the columns by dragging " "the boundary between them.")) msg.pack(fill='x') container = ttk.Frame() container.pack(fill='both', expand=True) # XXX Sounds like a good support class would be one for constructing # a treeview with scrollbars. self.tree = ttk.Treeview(columns=tree_columns, show="headings") vsb = ttk.Scrollbar(orient="vertical", command=self.tree.yview) hsb = ttk.Scrollbar(orient="horizontal", command=self.tree.xview) self.tree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set) self.tree.grid(column=0, row=0, sticky='nsew', in_=container) vsb.grid(column=1, row=0, sticky='ns', in_=container) hsb.grid(column=0, row=1, sticky='ew', in_=container) container.grid_columnconfigure(0, weight=1) container.grid_rowconfigure(0, weight=1) def _build_tree(self): for col in tree_columns: self.tree.heading(col, text=col.title(), command=lambda c=col: sortby(self.tree, c, 0)) # XXX tkFont.Font().measure expected args are incorrect according # to the Tk docs self.tree.column(col, width=tkFont.Font().measure(col.title())) for item in tree_data: self.tree.insert('', 'end', values=item) # adjust columns lenghts if necessary for indx, val in enumerate(item): ilen = tkFont.Font().measure(val) if self.tree.column(tree_columns[indx], width=None) < ilen: self.tree.column(tree_columns[indx], width=ilen) def main(): root = Tkinter.Tk() root.wm_title("Multi-Column List") root.wm_iconname("mclist") import plastik_theme try: plastik_theme.install('~/tile-themes/plastik/plastik') except Exception: import warnings warnings.warn("plastik theme being used without images") app = App() root.mainloop() if __name__ == "__main__": main() PK%L]Rh|@@!tkinter/ttk/listbox_scrollcmd.pyonu[ ^c@sWdZddlZddlZejZejddZejdddddd ejd ej d d Z e j ed s"     PK%L] w%> > tkinter/ttk/theme_selector.pyonu[ ^c@sZdZddlZddlZdejfdYZdZedkrVendS(sTtk Theme Selector v2. This is an improvement from the other theme selector (themes_combo.py) since now you can notice theme changes in Ttk Combobox, Ttk Frame, Ttk Label and Ttk Button. iNtAppcBs,eZdZdZdZdZRS(cCsHtjj|ddtj|_tj|d|_|jdS(Nt borderwidthii( tttktFramet__init__tStyletstyletTkintertIntVarttheme_autochanget_setup_widgets(tself((s7/usr/lib64/python2.7/Demo/tkinter/ttk/theme_selector.pyR scCs|jj|jjdS(N(Rt theme_uset themes_combotget(R ((s7/usr/lib64/python2.7/Demo/tkinter/ttk/theme_selector.pyt _change_themescCs |jjr|jndS(N(R RR(R twidget((s7/usr/lib64/python2.7/Demo/tkinter/ttk/theme_selector.pyt_theme_sel_changedsc Cstj|dd}|jj}tj|d|dd|_|jj|d|jjd|jtj |ddd |j }tj |dd d |j }|j d d dd|jj dddddd dd|j dddddd dd|j dddddddd |j}|jddd|jddd|jddd|j dddddddddddS(NttexttThemestvalueststatetreadonlyis<>s Change Themetcommands-Change themes when combobox item is activatedtvariabletipadxitstickytwtrowtcolumnitpadxtewitet columnspanitpadytweighttnsewtrowspan(RtLabelRt theme_namestComboboxR tsettbindRtButtonRt CheckbuttonR tgridtwinfo_toplevelt rowconfiguretcolumnconfigure(R t themes_lbltthemest change_btnttheme_change_checkbtnttop((s7/usr/lib64/python2.7/Demo/tkinter/ttk/theme_selector.pyR s&   %"" (t__name__t __module__RRRR (((s7/usr/lib64/python2.7/Demo/tkinter/ttk/theme_selector.pyR s  cCs't}|jjd|jdS(NsTheme Selector(Rtmasterttitletmainloop(tapp((s7/usr/lib64/python2.7/Demo/tkinter/ttk/theme_selector.pytmain7s t__main__(t__doc__RRRRR<R6(((s7/usr/lib64/python2.7/Demo/tkinter/ttk/theme_selector.pyts   -  PK%L]>tkinter/ttk/mac_searchentry.pyonu[ ^c @sdZddlZddlZejZdZejddeddZejddedd Zej Z e j d d dd!d dddgdde j dd idd6dd 6didd6didd6fgd6fgd6fge j dddej ddejddddZejddddZejddd dejddd dejdS("s\Mac style search widget Translated from Tcl code by Schelte Bron, http://wiki.tcl.tk/18188 iNs R0lGODlhKgAaAOfnAFdZVllbWFpcWVtdWlxeW11fXF9hXmBiX2ZnZWhpZ2lraGxua25wbXJ0 cXR2c3V3dHZ4dXh6d3x+e31/fH6AfYSGg4eJhoiKh4qMiYuNio2PjHmUqnqVq3yXrZGTkJKU kX+asJSWk32cuJWXlIGcs5aYlX6euZeZloOetZial4SftpqbmIWgt4GhvYahuIKivpudmYei uYOjv5yem4ijuoSkwIWlwYmlu56gnYamwp+hnoenw4unvaCin4ioxJCnuZykrImpxZmlsoaq zI2pv6KkoZGouoqqxpqms4erzaOloo6qwYurx5Kqu5untIiszqSmo5CrwoysyJeqtpOrvJyo tZGsw42typSsvaaopZKtxJWtvp6qt4+uy6epppOuxZCvzKiqp5quuZSvxoyx06mrqJWwx42y 1JKxzpmwwaqsqZaxyI6z1ZqxwqutqpOzz4+01qyuq56yvpizypS00Jm0y5W10Zq1zJa20rCy rpu3zqizwbGzr6C3yZy4z7K0saG4yp250LO1sqK5y5660Z+70qO7zKy4xaC806S8zba4taG9 1KW9zq66x6+7yLi6t6S/1rC8yrm7uLO8xLG9y7q8ubS9xabB2anB07K+zLW+xrO/za7CzrTA zrjAyLXBz77BvbbC0K/G2LjD0bnE0rLK28TGw8bIxcLL07vP28HN28rMycvOyr/T38DU4cnR 2s/RztHT0NLU0cTY5MrW5MvX5dHX2c3Z59bY1dPb5Nbb3dLe7Nvd2t3f3NXh797g3d3j5dnl 9OPl4eTm4+Ln6tzo9uXn5Obo5eDp8efp5uHq8uXq7ejq5+nr6OPs9Ovu6unu8O3v6+vw8+7w 7ezx9O/x7vDy7/Hz8O/19/P18vT38/L3+fb49Pf59vX6/fj69/b7/vn7+Pr8+ff9//v9+vz/ +/7//P////////////////////////////////////////////////////////////////// /////////////////////////////////yH/C05FVFNDQVBFMi4wAwEAAAAh+QQJZAD/ACwC AAIAKAAWAAAI/gD/CRz4bwUGCg8eQFjIsGHDBw4iTLAQgqBFgisuePCiyJOpUyBDihRpypMi Lx8qaLhIMIyGFZ5sAUsmjZrNmzhzWpO2DJgtTysqfGDpxoMbW8ekeQsXzty4p1CjRjUXrps3 asJsuclQ4uKKSbamMR3n1JzZs2jRkh1HzuxVXX8y4CDYAwqua+DInVrRwMGJU2kDp31KThy1 XGWGDlxhi1rTPAUICBBAoEAesoIzn6Vm68MKgVAUHftmzhOCBCtQwQKSoABgzZnJdSMmyIPA FbCotdUQAIhNa9B6DPCAGbZac+SowVIMRVe4pwkA4GpqDlwuAAmMZx4nTtfnf1mO5JEDNy46 MHJkxQEDgKC49rPjwC0bqGaZuOoZAKjBPE4NgAzUvYcWOc0QZF91imAnCDHJ5JFAAJN0I2Ba 4iRDUC/gOEVNDwIUcEABCAgAAATUTIgWOMBYRFp80ghiAQIIVAAEAwJIYI2JZnUji0XSYAYO NcsQA8wy0hCTwAASXGOiONFcxAtpTokTHznfiLMNMAkcAMuE43jDC0vLeGOWe2R5o4sn1LgH GzkWsvTPMgEOaA433Ag4TjjMuDkQMNi0tZ12sqWoJ0HATMPNffAZZ6U0wLAyqJ62RGoLLrhI aqmlpzwaEAAh+QQJZAD/ACwAAAAAKgAaAAAI/gD/CRw40JEhQoEC+fGjcOHCMRAjRkxDsKLF f5YcAcID582ZjyBDJhmZZIjJIUySEDHiBMhFghrtdNnRAgSHmzhz6sTZQcSLITx+CHn5bxSk Nz5MCMGy55CjTVCjbuJEtSrVQ3uwqDBRQwrFi476SHHxow8qXcemVbPGtm21t3CnTaP27Jgu VHtuiIjBsuImQkRiiEEFTNo2cOTMKV7MuLE5cN68QUOGSgwKG1EqJqJDY8+rZt8UjxtNunTj cY3DgZOWS46KIFgGjiI0ZIsqaqNNjWjgYMUpx8Adc3v2aosNMAI1DbqyI9WycOb4IAggQEAB A3lQBxet/TG4cMpI/tHwYeSfIzxM0uTKNs7UgAQrYL1akaDA7+3bueVqY4NJlUhIcQLNYx8E AIQ01mwjTQ8DeNAdfouNA8440GBCQxJY3MEGD6p4Y844CQCAizcSgpMLAAlAuJ03qOyQRBR3 nEHEK+BMGKIui4kDDAAIPKiiYuSYSMQQRCDCxhiziPMYBgDkEaEaAGQA3Y+MjUPOLFoMoUUh cKxRC4ngeILiH8Qkk0cCAUzSDZWpzbLEE1EwggcYqWCj2DNADFDAAQUgIAAAEFDDJmPYqNJF F1s4cscTmCDjDTjdSPOHBQggUAEQDAgggTWDPoYMJkFoUdRmddyyjWLeULMMMcAsIw0x4wkM IME1g25zyxpHxFYUHmyIggw4H4ojITnfiLMNMAkcAAub4BQjihRdDGTJHmvc4Qo1wD6Imje6 eILbj+BQ4wqu5Q3ECSJ0FOKKMtv4mBg33Pw4zjbKuBIIE1xYpIkhdQQiyi7OtAucj6dt48wu otQhBRa6VvSJIRwhIkotvgRTzMUYZ6xxMcj4QkspeKDxxRhEmUfIHWjAgQcijEDissuXvCyz zH7Q8YQURxDhUsn/bCInR3AELfTQZBRt9BBJkCGFFVhMwTNBlnBCSCGEIJQQIAklZMXWRBAR RRRWENHwRQEBADs=tsearch1tdatatformats gif -index 0tsearch2s gif -index 1s Search.fieldtimagetfocustborderiiitstickytews Search.entrytnsweis Entry.paddingsEntry.textareatchildrent backgrounds#b2b2b2tstyletwidthitpadxi tpady(RR(t__doc__tTkintertttktTktrootRt PhotoImagets1ts2tStyleR telement_createtlayoutt configuretEntryte1te2tgridtmainloop(((s8/usr/lib64/python2.7/Demo/tkinter/ttk/mac_searchentry.pyts(   )   +PK%L]|&C]tkinter/ttk/combo_themes.pycnu[ ^c@sNdZddlZdejfdYZdZedkrJendS(sTtk Theme Selector. Although it is a theme selector, you won't notice many changes since there is only a combobox and a frame around. iNtAppcBs#eZdZdZdZRS(cCs-tjj|tj|_|jdS(N(tttktFramet__init__tStyletstylet_setup_widgets(tself((s5/usr/lib64/python2.7/Demo/tkinter/ttk/combo_themes.pyR scCs5|jjr1|jj}|jj|ndS(N(twidgettcurrenttgetRt theme_use(Rteventtnewtheme((s5/usr/lib64/python2.7/Demo/tkinter/ttk/combo_themes.pyt _change_themescCst|jj}|jddtj|d|dddd}|j|d|jd|j|j d d |j d d d d dS(Nis Pick a themetvalueststatetreadonlytheightis<>tfilltxtbothtexpandi( tlistRt theme_namestinsertRtComboboxtsettbindRtpack(Rtthemest themes_combo((s5/usr/lib64/python2.7/Demo/tkinter/ttk/combo_themes.pyRs (t__name__t __module__RRR(((s5/usr/lib64/python2.7/Demo/tkinter/ttk/combo_themes.pyRs  cCs't}|jjd|jdS(Ns Ttk Combobox(Rtmasterttitletmainloop(tapp((s5/usr/lib64/python2.7/Demo/tkinter/ttk/combo_themes.pytmain(s t__main__(t__doc__RRRR&R (((s5/usr/lib64/python2.7/Demo/tkinter/ttk/combo_themes.pyts    PK%L]Otkinter/ttk/dirbrowser.pycnu[ ^c @sdZddlZddlZddlZddlZdZdZdZdZdZ ej Z ej dd Z ej dd Zejd d)ddddddZeje d|dkr>|jn |j|j||dS(s"Hide and show scrollbar as needed.iiN(tfloatt grid_removetgridR (tsbartfirsttlast((s3/usr/lib64/python2.7/Demo/tkinter/ttk/dirbrowser.pyt autoscroll9s   torienttverticalt horizontaltcolumnsRRR tdisplaycolumnstyscrollcommandcCstt||S(N(R5tvsb(tftl((s3/usr/lib64/python2.7/Demo/tkinter/ttk/dirbrowser.pytHR%txscrollcommandcCstt||S(N(R5thsb(R=R>((s3/usr/lib64/python2.7/Demo/tkinter/ttk/dirbrowser.pyR?IR%tcommands#0RsDirectory Structuretanchortws File Sizetstretchitwidthids<>stcolumntrowtstickytnsweitnstewtweight(RRR (t__doc__RRtTkintertttkR$R(R,R.R5tTktroott ScrollbarR<RAtTreeviewRtyviewtxviewtheadingRGtbindR1tgrid_columnconfiguretgrid_rowconfiguretmainloop(((s3/usr/lib64/python2.7/Demo/tkinter/ttk/dirbrowser.pyts:            PK%L]"P P tkinter/ttk/widget_state.pyonu[ ^c @sdZddlZddddddd d d g Zx eD]Zejd eq;Wd ZdejfdYZdZe dkrendS(s8Sample demo showing widget states and some font styling.iNtactivetdisabledtfocustpressedtselectedt backgroundtreadonlyt alternatetinvalidt!cCs%tttd}|j|dS(Ni(tstatestlentstate(twidgettnostate((s5/usr/lib64/python2.7/Demo/tkinter/ttk/widget_state.pyt reset_state stAppcBs2eZddZddZdZdZRS(cCstjj|dd|jj|tj|_|jjdd}t|j j d|}|j j d||_ d|j krd|j |_ n|d d kr|d nd |_ t ||d d krd nd |_g|_|jdS( Nt borderwidthitTButtontfontsfont configure %s -sizesfont configure %s -familyt s{%s}it-ti(tttktFramet__init__tmasterttitletStyletstyletlookuptstrttktevalt font_familyt fsize_prefixtintt base_fsizetupdate_widgetst_setup_widgets(tselfRtbtn_fonttfsize((s5/usr/lib64/python2.7/Demo/tkinter/ttk/widget_state.pyRs#) icCs4|jjddd|j|j|j|fdS(NRRs%s %s%d(Rt configureR"R#R%(R(textra((s5/usr/lib64/python2.7/Demo/tkinter/ttk/widget_state.pyt _set_font#scCs|j|}|s'dg}d}nGt|j}g|D]}|tkr@|^q@}dt|}x(|jD]}t||j|qxW|j|dS(NRiii( t nametowidgettsettsplitR R R&RR R-(R(R tnewtextt goodstatest font_extrat newstatesR ((s5/usr/lib64/python2.7/Demo/tkinter/ttk/widget_state.pyt _new_state's  %  c Cstj|dd}tj|dddd}|j|jddf|d <|j|jj||j|j d d d d |j dddd d d dd|j d ddddS(NttextsEnter states and watchtcursortxtermtvalidatetkeys%Ws%Ptvalidatecommandtfilltxtpadxitsidetlefttpadytanchortntbothtexpandi( RtButtontEntrytregisterR5RR&tappendR9tpack(R(tbtntentry((s5/usr/lib64/python2.7/Demo/tkinter/ttk/widget_state.pyR'?s  "N(t__name__t __module__tNoneRR-R5R'(((s5/usr/lib64/python2.7/Demo/tkinter/ttk/widget_state.pyRs   cCstd}|jdS(NsWidget State Tester(Rtmainloop(tapp((s5/usr/lib64/python2.7/Demo/tkinter/ttk/widget_state.pytmainNs t__main__( t__doc__RR R RIRRRRRRM(((s5/usr/lib64/python2.7/Demo/tkinter/ttk/widget_state.pyts  @  PK%L]8~ ~ tkinter/ttk/ttkcalendar.pynu[""" Simple calendar using ttk Treeview together with calendar and datetime classes. """ import calendar import Tkinter import tkFont import ttk def get_calendar(locale, fwday): # instantiate proper calendar class if locale is None: return calendar.TextCalendar(fwday) else: return calendar.LocaleTextCalendar(fwday, locale) class Calendar(ttk.Frame): # XXX ToDo: cget and configure datetime = calendar.datetime.datetime timedelta = calendar.datetime.timedelta def __init__(self, master=None, **kw): """ WIDGET-SPECIFIC OPTIONS locale, firstweekday, year, month, selectbackground, selectforeground """ # remove custom options from kw before initializating ttk.Frame fwday = kw.pop('firstweekday', calendar.MONDAY) year = kw.pop('year', self.datetime.now().year) month = kw.pop('month', self.datetime.now().month) locale = kw.pop('locale', None) sel_bg = kw.pop('selectbackground', '#ecffc4') sel_fg = kw.pop('selectforeground', '#05640e') self._date = self.datetime(year, month, 1) self._selection = None # no date selected ttk.Frame.__init__(self, master, **kw) self._cal = get_calendar(locale, fwday) self.__setup_styles() # creates custom styles self.__place_widgets() # pack/grid used widgets self.__config_calendar() # adjust calendar columns and setup tags # configure a canvas, and proper bindings, for selecting dates self.__setup_selection(sel_bg, sel_fg) # store items ids, used for insertion later self._items = [self._calendar.insert('', 'end', values='') for _ in range(6)] # insert dates in the currently empty calendar self._build_calendar() # set the minimal size for the widget self._calendar.bind('', self.__minsize) def __setitem__(self, item, value): if item in ('year', 'month'): raise AttributeError("attribute '%s' is not writeable" % item) elif item == 'selectbackground': self._canvas['background'] = value elif item == 'selectforeground': self._canvas.itemconfigure(self._canvas.text, item=value) else: ttk.Frame.__setitem__(self, item, value) def __getitem__(self, item): if item in ('year', 'month'): return getattr(self._date, item) elif item == 'selectbackground': return self._canvas['background'] elif item == 'selectforeground': return self._canvas.itemcget(self._canvas.text, 'fill') else: r = ttk.tclobjs_to_py({item: ttk.Frame.__getitem__(self, item)}) return r[item] def __setup_styles(self): # custom ttk styles style = ttk.Style(self.master) arrow_layout = lambda dir: ( [('Button.focus', {'children': [('Button.%sarrow' % dir, None)]})] ) style.layout('L.TButton', arrow_layout('left')) style.layout('R.TButton', arrow_layout('right')) def __place_widgets(self): # header frame and its widgets hframe = ttk.Frame(self) lbtn = ttk.Button(hframe, style='L.TButton', command=self._prev_month) rbtn = ttk.Button(hframe, style='R.TButton', command=self._next_month) self._header = ttk.Label(hframe, width=15, anchor='center') # the calendar self._calendar = ttk.Treeview(show='', selectmode='none', height=7) # pack the widgets hframe.pack(in_=self, side='top', pady=4, anchor='center') lbtn.grid(in_=hframe) self._header.grid(in_=hframe, column=1, row=0, padx=12) rbtn.grid(in_=hframe, column=2, row=0) self._calendar.pack(in_=self, expand=1, fill='both', side='bottom') def __config_calendar(self): cols = self._cal.formatweekheader(3).split() self._calendar['columns'] = cols self._calendar.tag_configure('header', background='grey90') self._calendar.insert('', 'end', values=cols, tag='header') # adjust its columns width font = tkFont.Font() maxwidth = max(font.measure(col) for col in cols) for col in cols: self._calendar.column(col, width=maxwidth, minwidth=maxwidth, anchor='e') def __setup_selection(self, sel_bg, sel_fg): self._font = tkFont.Font() self._canvas = canvas = Tkinter.Canvas(self._calendar, background=sel_bg, borderwidth=0, highlightthickness=0) canvas.text = canvas.create_text(0, 0, fill=sel_fg, anchor='w') canvas.bind('', lambda evt: canvas.place_forget()) self._calendar.bind('', lambda evt: canvas.place_forget()) self._calendar.bind('', self._pressed) def __minsize(self, evt): width, height = self._calendar.master.geometry().split('x') height = height[:height.index('+')] self._calendar.master.minsize(width, height) def _build_calendar(self): year, month = self._date.year, self._date.month # update header text (Month, YEAR) header = self._cal.formatmonthname(year, month, 0) self._header['text'] = header.title() # update calendar shown dates cal = self._cal.monthdayscalendar(year, month) for indx, item in enumerate(self._items): week = cal[indx] if indx < len(cal) else [] fmt_week = [('%02d' % day) if day else '' for day in week] self._calendar.item(item, values=fmt_week) def _show_selection(self, text, bbox): """Configure canvas for a new selection.""" x, y, width, height = bbox textw = self._font.measure(text) canvas = self._canvas canvas.configure(width=width, height=height) canvas.coords(canvas.text, width - textw, height / 2 - 1) canvas.itemconfigure(canvas.text, text=text) canvas.place(in_=self._calendar, x=x, y=y) # Callbacks def _pressed(self, evt): """Clicked somewhere in the calendar.""" x, y, widget = evt.x, evt.y, evt.widget item = widget.identify_row(y) column = widget.identify_column(x) if not column or not item in self._items: # clicked in the weekdays row or just outside the columns return item_values = widget.item(item)['values'] if not len(item_values): # row is empty for this month return text = item_values[int(column[1]) - 1] if not text: # date is empty return bbox = widget.bbox(item, column) if not bbox: # calendar not visible yet return # update and then show selection text = '%02d' % text self._selection = (text, item, column) self._show_selection(text, bbox) def _prev_month(self): """Updated calendar to show the previous month.""" self._canvas.place_forget() self._date = self._date - self.timedelta(days=1) self._date = self.datetime(self._date.year, self._date.month, 1) self._build_calendar() # reconstruct calendar def _next_month(self): """Update calendar to show the next month.""" self._canvas.place_forget() year, month = self._date.year, self._date.month self._date = self._date + self.timedelta( days=calendar.monthrange(year, month)[1] + 1) self._date = self.datetime(self._date.year, self._date.month, 1) self._build_calendar() # reconstruct calendar # Properties @property def selection(self): """Return a datetime representing the current selected date.""" if not self._selection: return None year, month = self._date.year, self._date.month return self.datetime(year, month, int(self._selection[0])) def test(): import sys root = Tkinter.Tk() root.title('Ttk Calendar') ttkcal = Calendar(firstweekday=calendar.SUNDAY) ttkcal.pack(expand=1, fill='both') if 'win' not in sys.platform: style = ttk.Style() style.theme_use('clam') root.mainloop() if __name__ == '__main__': test() PK%L]$&$&tkinter/ttk/ttkcalendar.pyonu[ ^c@s{dZddlZddlZddlZddlZdZdejfdYZdZe dkrwendS(sQ Simple calendar using ttk Treeview together with calendar and datetime classes. iNcCs-|dkrtj|Stj||SdS(N(tNonetcalendart TextCalendartLocaleTextCalendar(tlocaletfwday((s4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyt get_calendar s  tCalendarcBseZejjZejjZddZdZdZdZ dZ dZ dZ dZ dZd Zd Zd Zd Zed ZRS(c KsY|jdtj}|jd|jjj}|jd|jjj}|jdd}|jdd}|jdd}|j||d |_d|_ t j j |||t |||_|j|j|j|j||gtd D]!} |jjd d d d ^q |_|j|jjd|jdS(s WIDGET-SPECIFIC OPTIONS locale, firstweekday, year, month, selectbackground, selectforeground t firstweekdaytyeartmonthRtselectbackgrounds#ecffc4tselectforegrounds#05640eiittendtvaluessN(tpopRtMONDAYtdatetimetnowR R Rt_datet _selectiontttktFramet__init__Rt_calt_Calendar__setup_stylest_Calendar__place_widgetst_Calendar__config_calendart_Calendar__setup_selectiontranget _calendartinsertt_itemst_build_calendartbindt_Calendar__minsize( tselftmastertkwRR R Rtsel_bgtsel_fgt_((s4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyRs$    4 cCs|dkrtd|n]|dkr;||jdTss L.TButtontlefts R.TButtontright(RtStyleR&tlayout(R%tstylet arrow_layout((s4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyt__setup_stylesQs c Cs&tj|}tj|ddd|j}tj|ddd|j}tj|dddd|_tjd d d d d d|_|j d|dddddd|j d||jj d|dddddd|j d|dddd|jj d|dddddddS(NR@s L.TButtontcommands R.TButtontwidthitanchortcentertshowR t selectmodetnonetheightitin_tsidettoptpadyitcolumnitrowitpadxi itexpandR3tbothtbottom( RRtButtont _prev_montht _next_monthtLabelt_headertTreeviewRtpacktgrid(R%thframetlbtntrbtn((s4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyt__place_widgetsZs!"%c s|jjdj}||jd<|jjddd|jjddd|d dtjtfd |D}x0|D](}|jj |d |d |d dqWdS(NitcolumnstheaderR+tgrey90R RRttagc3s|]}j|VqdS(N(tmeasure(t.0tcol(tfont(s4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pys qsRDtminwidthREte( RtformatweekheadertsplitRt tag_configureR ttkFonttFonttmaxRO(R%tcolstmaxwidthRg((Rhs4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyt__config_calendarjs   cstj|_tj|jd|dddd|_jddd|dd_j dfd |jj d fd |jj d|j dS( NR+t borderwidthithighlightthicknessR3REtwscs jS(N(t place_forget(tevt(tcanvas(s4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyR;|R s cs jS(N(Rw(Rx(Ry(s4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyR;}R ( RnRot_fonttTkintertCanvasRR.t create_textR0R#t_pressed(R%R(R)((Rys4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyt__setup_selectionvs!cCsN|jjjjd\}}||jd }|jjj||dS(Ntxt+(RR&tgeometryRltindextminsize(R%RxRDRJ((s4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyt __minsizes!c Cs|jj|jj}}|jj||d}|j|jd<|jj||}x~t|j D]m\}}|t |kr||ng}g|D]}|rd|nd^q} |j j |d| qiWdS(NiR0s%02dR R( RR R RtformatmonthnamettitleRYtmonthdayscalendart enumerateR!tlenRR,( R%R R RbtcaltindxR,tweektdaytfmt_week((s4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyR"s")c Cs|\}}}}|jj|}|j}|jd|d||j|j|||dd|j|jd||jd|jd|d|d S( s%Configure canvas for a new selection.RDRJiiR0RKRtyN( RzReR.t configuretcoordsR0R/tplaceR( R%R0tbboxRRRDRJttextwRy((s4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyt_show_selections "c Cs|j|j|j}}}|j|}|j|}| sQ||jkrUdS|j|d}t|sxdS|t|dd}|sdS|j ||} | sdSd|}|||f|_ |j || dS(s"Clicked somewhere in the calendar.NRis%02d( RRtwidgett identify_rowtidentify_columnR!R,RtintRRR( R%RxRRRR,ROt item_valuesR0R((s4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyR~s"  cCs[|jj|j|jdd|_|j|jj|jjd|_|jdS(s,Updated calendar to show the previous month.tdaysiN(R.RwRt timedeltaRR R R"(R%((s4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyRVs $cCs|jj|jj|jj}}|j|jdtj||dd|_|j|jj|jjd|_|j dS(s'Update calendar to show the next month.RiN( R.RwRR R RRt monthrangeRR"(R%R R ((s4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyRWs  !$cCsF|js dS|jj|jj}}|j||t|jdS(s9Return a datetime representing the current selected date.iN(RRRR R RR(R%R R ((s4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyt selections N(t__name__t __module__RRRRRR1R7RRRRR$R"RR~RVRWtpropertyR(((s4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyRs    %       cCsddl}tj}|jdtdtj}|jddddd|jkrxt j }|j d n|j dS( Nis Ttk CalendarRRRiR3RStwintclam( tsysR{tTkRRRtSUNDAYR[tplatformRR>t theme_usetmainloop(RtroottttkcalR@((s4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyttests    t__main__( t__doc__RR{RnRRRRRR(((s4/usr/lib64/python2.7/Demo/tkinter/ttk/ttkcalendar.pyts      PK%L]aOtkinter/ttk/theme_selector.pynu["""Ttk Theme Selector v2. This is an improvement from the other theme selector (themes_combo.py) since now you can notice theme changes in Ttk Combobox, Ttk Frame, Ttk Label and Ttk Button. """ import Tkinter import ttk class App(ttk.Frame): def __init__(self): ttk.Frame.__init__(self, borderwidth=3) self.style = ttk.Style() # XXX Ideally I wouldn't want to create a Tkinter.IntVar to make # it works with Checkbutton variable option. self.theme_autochange = Tkinter.IntVar(self, 0) self._setup_widgets() def _change_theme(self): self.style.theme_use(self.themes_combo.get()) def _theme_sel_changed(self, widget): if self.theme_autochange.get(): self._change_theme() def _setup_widgets(self): themes_lbl = ttk.Label(self, text="Themes") themes = self.style.theme_names() self.themes_combo = ttk.Combobox(self, values=themes, state="readonly") self.themes_combo.set(themes[0]) self.themes_combo.bind("<>", self._theme_sel_changed) change_btn = ttk.Button(self, text='Change Theme', command=self._change_theme) theme_change_checkbtn = ttk.Checkbutton(self, text="Change themes when combobox item is activated", variable=self.theme_autochange) themes_lbl.grid(ipadx=6, sticky="w") self.themes_combo.grid(row=0, column=1, padx=6, sticky="ew") change_btn.grid(row=0, column=2, padx=6, sticky="e") theme_change_checkbtn.grid(row=1, columnspan=3, sticky="w", pady=6) top = self.winfo_toplevel() top.rowconfigure(0, weight=1) top.columnconfigure(0, weight=1) self.columnconfigure(1, weight=1) self.grid(row=0, column=0, sticky="nsew", columnspan=3, rowspan=2) def main(): app = App() app.master.title("Theme Selector") app.mainloop() if __name__ == "__main__": main() PK%L]qP tkinter/ttk/dirbrowser.pynu["""A directory browser using Ttk Treeview. Based on the demo found in Tk 8.5 library/demos/browse """ import os import glob import Tkinter import ttk def populate_tree(tree, node): if tree.set(node, "type") != 'directory': return path = tree.set(node, "fullpath") tree.delete(*tree.get_children(node)) parent = tree.parent(node) special_dirs = [] if parent else glob.glob('.') + glob.glob('..') for p in special_dirs + os.listdir(path): ptype = None p = os.path.join(path, p).replace('\\', '/') if os.path.isdir(p): ptype = "directory" elif os.path.isfile(p): ptype = "file" fname = os.path.split(p)[1] id = tree.insert(node, "end", text=fname, values=[p, ptype]) if ptype == 'directory': if fname not in ('.', '..'): tree.insert(id, 0, text="dummy") tree.item(id, text=fname) elif ptype == 'file': size = os.stat(p).st_size tree.set(id, "size", "%d bytes" % size) def populate_roots(tree): dir = os.path.abspath('.').replace('\\', '/') node = tree.insert('', 'end', text=dir, values=[dir, "directory"]) populate_tree(tree, node) def update_tree(event): tree = event.widget populate_tree(tree, tree.focus()) def change_dir(event): tree = event.widget node = tree.focus() if tree.parent(node): path = os.path.abspath(tree.set(node, "fullpath")) if os.path.isdir(path): os.chdir(path) tree.delete(tree.get_children('')) populate_roots(tree) def autoscroll(sbar, first, last): """Hide and show scrollbar as needed.""" first, last = float(first), float(last) if first <= 0 and last >= 1: sbar.grid_remove() else: sbar.grid() sbar.set(first, last) root = Tkinter.Tk() vsb = ttk.Scrollbar(orient="vertical") hsb = ttk.Scrollbar(orient="horizontal") tree = ttk.Treeview(columns=("fullpath", "type", "size"), displaycolumns="size", yscrollcommand=lambda f, l: autoscroll(vsb, f, l), xscrollcommand=lambda f, l:autoscroll(hsb, f, l)) vsb['command'] = tree.yview hsb['command'] = tree.xview tree.heading("#0", text="Directory Structure", anchor='w') tree.heading("size", text="File Size", anchor='w') tree.column("size", stretch=0, width=100) populate_roots(tree) tree.bind('<>', update_tree) tree.bind('', change_dir) # Arrange the tree and its scrollbars in the toplevel tree.grid(column=0, row=0, sticky='nswe') vsb.grid(column=1, row=0, sticky='ns') hsb.grid(column=0, row=1, sticky='ew') root.grid_columnconfigure(0, weight=1) root.grid_rowconfigure(0, weight=1) root.mainloop() PK%L]akJ tkinter/ttk/widget_state.pynu["""Sample demo showing widget states and some font styling.""" import ttk states = ['active', 'disabled', 'focus', 'pressed', 'selected', 'background', 'readonly', 'alternate', 'invalid'] for state in states[:]: states.append("!" + state) def reset_state(widget): nostate = states[len(states) // 2:] widget.state(nostate) class App(ttk.Frame): def __init__(self, title=None): ttk.Frame.__init__(self, borderwidth=6) self.master.title(title) self.style = ttk.Style() # get default font size and family btn_font = self.style.lookup("TButton", "font") fsize = str(self.tk.eval("font configure %s -size" % btn_font)) self.font_family = self.tk.eval("font configure %s -family" % btn_font) if ' ' in self.font_family: self.font_family = '{%s}' % self.font_family self.fsize_prefix = fsize[0] if fsize[0] == '-' else '' self.base_fsize = int(fsize[1 if fsize[0] == '-' else 0:]) # a list to hold all the widgets that will have their states changed self.update_widgets = [] self._setup_widgets() def _set_font(self, extra=0): self.style.configure("TButton", font="%s %s%d" % (self.font_family, self.fsize_prefix, self.base_fsize + extra)) def _new_state(self, widget, newtext): widget = self.nametowidget(widget) if not newtext: goodstates = ["disabled"] font_extra = 0 else: # set widget state according to what has been entered in the entry newstates = set(newtext.split()) # eliminate duplicates # keep only the valid states goodstates = [state for state in newstates if state in states] # define a new font size based on amount of states font_extra = 2 * len(goodstates) # set new widget state for widget in self.update_widgets: reset_state(widget) # remove any previous state from the widget widget.state(goodstates) # update Ttk Button font size self._set_font(font_extra) return 1 def _setup_widgets(self): btn = ttk.Button(self, text='Enter states and watch') entry = ttk.Entry(self, cursor='xterm', validate="key") entry['validatecommand'] = (self.register(self._new_state), '%W', '%P') entry.focus() self.update_widgets.append(btn) entry.validate() entry.pack(fill='x', padx=6) btn.pack(side='left', pady=6, padx=6, anchor='n') self.pack(fill='both', expand=1) def main(): app = App("Widget State Tester") app.mainloop() if __name__ == "__main__": main() PK%L]j:^^tkinter/ttk/plastik_theme.pycnu[ ^c@sdZddlZddlZddlZddlmZdgZidd6dd6d d 6d d 6ZiZd Z dZ dS(ssThis demonstrates good part of the syntax accepted by theme_create. This is a translation of plastik.tcl to python. You will need the images used by the plastik theme to test this. The images (and other tile themes) can be retrived by doing: $ cvs -z3 -d:pserver:anonymous@tktable.cvs.sourceforge.net:/cvsroot/tktable co tile-themes To test this module you should do, for example: import Tkinter import plastik_theme root = Tkinter.Tk() plastik_theme.install(plastik_image_dir) ... Where plastik_image_dir contains the path to the images directory used by the plastik theme, something like: tile-themes/plastik/plastik iN(t PhotoImagetinstalls#efefeftframes#aaaaaat disabledfgs#657a9etselectbgs#fffffftselectfgcCstjj|}tjj|s7td|nxWtjd|D]B}tjj|d}|d }t|d|ddt|id)d6fd?id@idAid'd6dd 6fgd#6fgd#6fgd#6fgd$6dB6iidCdDdCdCgdE6d6dF6iidGdDdGdDgdH6dCdCdDgd 6d6idIddDdJdDgfgd 6d6dK6iidCdH6d6dL6idMdNddidJd/gdS6dJdH6dTd6fdU6d36idMdVdddidJdYgdS6dZdH6d[d6fdU6d96idMd\ddddidd6fdU6da6idMdbddddidd6fdU6dg6idMdhidZdS6d+d6fdU6d,6iddU6d-6iddU6d*6idMdkidZdS6dd6fdU6d6iddU6d"6iddU6d6idMdndidd6fdU6dp6idMdqdidd6fdU6ds6idMdtdidd6fdU6dv6idMdwdidd6fdU6dy6idMdzidd6fdU6d{6idMd|iddS6dCdH6fdU6d}6idMd~idd6fdU6d6idMdiddS6dCdH6fdU6d6idMddidDdS6dZdJgdH6d[d6fdU6d6idMdSidJdS6dJdH6d[d6fdU6d6idMddid[d6dJdGddgdS6dJdJdgdH6fdU6d=6idMdidd6ddCdCdCgdS6fdU6d>6idMddddddidJdGddgdS6dJdJdgdH6d[d6fdU6d6idMdidd6ddCdCdCgdS6fdU6d6idMdidJdS6fdU6d6idMdddidCdDdCdCgdH6dJd/dJd/gdS6fdU6d6idMdidDdS6fdU6d6idMdidDdYgdS6fdU6d6idMdidYdDgdS6fdU6d6idMddidJd/gdS6dJdH6d[d6fdU6d6|jddS(NtplastiktdefaulttsettingsRt backgroundt troughcolorRtselectbackgroundRtselectforegroundtfieldbackgroundt TkDefaultFonttfontit borderwidtht configuretdisabledRt foregroundtmapt.sVertical.Scrollbar.uparrowttoptsidettstickysVertical.Scrollbar.downarrowtbottomsVertical.Scrollbar.troughtnssVertical.Scrollbar.thumbtexpandtunitsVertical.Scrollbar.griptchildrentlayoutsVertical.TScrollbarsHorizontal.Scrollbar.leftarrowtleftsHorizontal.Scrollbar.rightarrowtrightsHorizontal.Scrollbar.troughtewsHorizontal.Scrollbar.thumbsHorizontal.Scrollbar.gripsHorizontal.TScrollbari twidthtcentertanchors Button.buttons Button.focussButton.paddings Button.labeltTButtonsToolbutton.bordersToolbutton.buttonsToolbutton.paddingsToolbutton.labelt ToolbuttonsMenubutton.buttonsMenubutton.indicatorsMenubutton.focussMenubutton.paddingsMenubutton.labelt TMenubuttoniit tabmarginst TNotebookitpaddingtselectedis TNotebook.tabtTreeviewtimagesbutton-ntpressedsbutton-ptactivesbutton-htbordertewnsselement creates tbutton-ns tbutton-ps tbutton-hi itnewsscheck-nuscheck-hcscheck-pcscheck-huscheck-ncsCheckbutton.indicatorsradio-nusradio-hcsradio-pcsradio-husradio-ncsRadiobutton.indicatorshsb-nshsb-gshsb-tsvsb-nsvsb-gsvsb-ts arrowup-ns arrowup-psScrollbar.uparrows arrowdown-ns arrowdown-psScrollbar.downarrows arrowleft-ns arrowleft-psScrollbar.leftarrows arrowright-ns arrowright-psScrollbar.rightarrows hslider-nsHorizontal.Scale.sliders hslider-tsHorizontal.Scale.troughs vslider-nsVertical.Scale.sliders vslider-tsVertical.Scale.troughsentry-ntfocussentry-fs Entry.fieldsLabelframe.borderscombo-rscombo-raiiisarrow-dtescombo-ntreadonlyscombo-fascombo-as !readonlyscombo-fsCombobox.fieldsCombobox.downarrows notebook-csNotebook.clients notebook-tns notebook-tss notebook-tas Notebook.tabs hprogress-tsProgressbar.troughs hprogress-bsHorizontal.Progressbar.pbars vprogress-bsVertical.Progressbar.pbarstree-nstree-psTreeheading.cell(R?sbutton-p(R@sbutton-h(R<s tbutton-p(R?s tbutton-p(R@s tbutton-h(R@R<scheck-hc(R?R<scheck-pc(R@scheck-hu(R<scheck-nc(R@R<sradio-hc(R?R<sradio-pc(R@sradio-hu(R<sradio-nc(R>shsb-g(R>shsb-t(R>svsb-g(R>svsb-t(R?s arrowup-p(R?s arrowdown-p(R?s arrowleft-p(R?s arrowright-p(RDsentry-f(R@scombo-ra(RFR@scombo-ra(RDR@scombo-fa(R@scombo-a(s !readonlyRDscombo-f(RFscombo-r(R<s notebook-ts(R@s notebook-ta(R?stree-p(RtttktStylet theme_createtcolorst theme_use(Rtstyle((s6/usr/lib64/python2.7/Demo/tkinter/ttk/plastik_theme.pyR.s        / /@@@!*'))"" "")).&.4!!-( t__doc__R RRGtTkinterRt__all__RJRRR(((s6/usr/lib64/python2.7/Demo/tkinter/ttk/plastik_theme.pyts      PK%L]xUeetkinter/ttk/img/close.gifnu[GIF89a;;;;;;;;;;;;;;;!Created with GIMP! ,0DJ'! 晅aA ;PK%L]|!ee!tkinter/ttk/img/close_pressed.gifnu[GIF89a**ff;;;;;;;;;;;;!Created with GIMP! ,0DJ'! 晅aA ;PK%L].PP tkinter/ttk/img/close_active.gifnu[GIF89a4! ,0DJ'! 晅aA ;PK%L]- tkinter/ttk/listbox_scrollcmd.pynu["""Sample taken from: http://www.tkdocs.com/tutorial/morewidgets.html and converted to Python, mainly to demonstrate xscrollcommand option. grid [tk::listbox .l -yscrollcommand ".s set" -height 5] -column 0 -row 0 -sticky nwes grid [ttk::scrollbar .s -command ".l yview" -orient vertical] -column 1 -row 0 -sticky ns grid [ttk::label .stat -text "Status message here" -anchor w] -column 0 -row 1 -sticky we grid [ttk::sizegrip .sz] -column 1 -row 1 -sticky se grid columnconfigure . 0 -weight 1; grid rowconfigure . 0 -weight 1 for {set i 0} {$i<100} {incr i} { .l insert end "Line $i of 100" } """ import Tkinter import ttk root = Tkinter.Tk() l = Tkinter.Listbox(height=5) l.grid(column=0, row=0, sticky='nwes') s = ttk.Scrollbar(command=l.yview, orient='vertical') l['yscrollcommand'] = s.set s.grid(column=1, row=0, sticky="ns") stat = ttk.Label(text="Status message here", anchor='w') stat.grid(column=0, row=1, sticky='we') sz = ttk.Sizegrip() sz.grid(column=1, row=1, sticky='se') root.grid_columnconfigure(0, weight=1) root.grid_rowconfigure(0, weight=1) for i in range(100): l.insert('end', "Line %d of 100" % i) root.mainloop() PK%L]|&C]tkinter/ttk/combo_themes.pyonu[ ^c@sNdZddlZdejfdYZdZedkrJendS(sTtk Theme Selector. Although it is a theme selector, you won't notice many changes since there is only a combobox and a frame around. iNtAppcBs#eZdZdZdZRS(cCs-tjj|tj|_|jdS(N(tttktFramet__init__tStyletstylet_setup_widgets(tself((s5/usr/lib64/python2.7/Demo/tkinter/ttk/combo_themes.pyR scCs5|jjr1|jj}|jj|ndS(N(twidgettcurrenttgetRt theme_use(Rteventtnewtheme((s5/usr/lib64/python2.7/Demo/tkinter/ttk/combo_themes.pyt _change_themescCst|jj}|jddtj|d|dddd}|j|d|jd|j|j d d |j d d d d dS(Nis Pick a themetvalueststatetreadonlytheightis<>tfilltxtbothtexpandi( tlistRt theme_namestinsertRtComboboxtsettbindRtpack(Rtthemest themes_combo((s5/usr/lib64/python2.7/Demo/tkinter/ttk/combo_themes.pyRs (t__name__t __module__RRR(((s5/usr/lib64/python2.7/Demo/tkinter/ttk/combo_themes.pyRs  cCs't}|jjd|jdS(Ns Ttk Combobox(Rtmasterttitletmainloop(tapp((s5/usr/lib64/python2.7/Demo/tkinter/ttk/combo_themes.pytmain(s t__main__(t__doc__RRRR&R (((s5/usr/lib64/python2.7/Demo/tkinter/ttk/combo_themes.pyts    PK%L]>tkinter/ttk/mac_searchentry.pycnu[ ^c @sdZddlZddlZejZdZejddeddZejddedd Zej Z e j d d dd!d dddgdde j dd idd6dd 6didd6didd6fgd6fgd6fge j dddej ddejddddZejddddZejddd dejddd dejdS("s\Mac style search widget Translated from Tcl code by Schelte Bron, http://wiki.tcl.tk/18188 iNs R0lGODlhKgAaAOfnAFdZVllbWFpcWVtdWlxeW11fXF9hXmBiX2ZnZWhpZ2lraGxua25wbXJ0 cXR2c3V3dHZ4dXh6d3x+e31/fH6AfYSGg4eJhoiKh4qMiYuNio2PjHmUqnqVq3yXrZGTkJKU kX+asJSWk32cuJWXlIGcs5aYlX6euZeZloOetZial4SftpqbmIWgt4GhvYahuIKivpudmYei uYOjv5yem4ijuoSkwIWlwYmlu56gnYamwp+hnoenw4unvaCin4ioxJCnuZykrImpxZmlsoaq zI2pv6KkoZGouoqqxpqms4erzaOloo6qwYurx5Kqu5untIiszqSmo5CrwoysyJeqtpOrvJyo tZGsw42typSsvaaopZKtxJWtvp6qt4+uy6epppOuxZCvzKiqp5quuZSvxoyx06mrqJWwx42y 1JKxzpmwwaqsqZaxyI6z1ZqxwqutqpOzz4+01qyuq56yvpizypS00Jm0y5W10Zq1zJa20rCy rpu3zqizwbGzr6C3yZy4z7K0saG4yp250LO1sqK5y5660Z+70qO7zKy4xaC806S8zba4taG9 1KW9zq66x6+7yLi6t6S/1rC8yrm7uLO8xLG9y7q8ubS9xabB2anB07K+zLW+xrO/za7CzrTA zrjAyLXBz77BvbbC0K/G2LjD0bnE0rLK28TGw8bIxcLL07vP28HN28rMycvOyr/T38DU4cnR 2s/RztHT0NLU0cTY5MrW5MvX5dHX2c3Z59bY1dPb5Nbb3dLe7Nvd2t3f3NXh797g3d3j5dnl 9OPl4eTm4+Ln6tzo9uXn5Obo5eDp8efp5uHq8uXq7ejq5+nr6OPs9Ovu6unu8O3v6+vw8+7w 7ezx9O/x7vDy7/Hz8O/19/P18vT38/L3+fb49Pf59vX6/fj69/b7/vn7+Pr8+ff9//v9+vz/ +/7//P////////////////////////////////////////////////////////////////// /////////////////////////////////yH/C05FVFNDQVBFMi4wAwEAAAAh+QQJZAD/ACwC AAIAKAAWAAAI/gD/CRz4bwUGCg8eQFjIsGHDBw4iTLAQgqBFgisuePCiyJOpUyBDihRpypMi Lx8qaLhIMIyGFZ5sAUsmjZrNmzhzWpO2DJgtTysqfGDpxoMbW8ekeQsXzty4p1CjRjUXrps3 asJsuclQ4uKKSbamMR3n1JzZs2jRkh1HzuxVXX8y4CDYAwqua+DInVrRwMGJU2kDp31KThy1 XGWGDlxhi1rTPAUICBBAoEAesoIzn6Vm68MKgVAUHftmzhOCBCtQwQKSoABgzZnJdSMmyIPA FbCotdUQAIhNa9B6DPCAGbZac+SowVIMRVe4pwkA4GpqDlwuAAmMZx4nTtfnf1mO5JEDNy46 MHJkxQEDgKC49rPjwC0bqGaZuOoZAKjBPE4NgAzUvYcWOc0QZF91imAnCDHJ5JFAAJN0I2Ba 4iRDUC/gOEVNDwIUcEABCAgAAATUTIgWOMBYRFp80ghiAQIIVAAEAwJIYI2JZnUji0XSYAYO NcsQA8wy0hCTwAASXGOiONFcxAtpTokTHznfiLMNMAkcAMuE43jDC0vLeGOWe2R5o4sn1LgH GzkWsvTPMgEOaA433Ag4TjjMuDkQMNi0tZ12sqWoJ0HATMPNffAZZ6U0wLAyqJ62RGoLLrhI aqmlpzwaEAAh+QQJZAD/ACwAAAAAKgAaAAAI/gD/CRw40JEhQoEC+fGjcOHCMRAjRkxDsKLF f5YcAcID582ZjyBDJhmZZIjJIUySEDHiBMhFghrtdNnRAgSHmzhz6sTZQcSLITx+CHn5bxSk Nz5MCMGy55CjTVCjbuJEtSrVQ3uwqDBRQwrFi476SHHxow8qXcemVbPGtm21t3CnTaP27Jgu VHtuiIjBsuImQkRiiEEFTNo2cOTMKV7MuLE5cN68QUOGSgwKG1EqJqJDY8+rZt8UjxtNunTj cY3DgZOWS46KIFgGjiI0ZIsqaqNNjWjgYMUpx8Adc3v2aosNMAI1DbqyI9WycOb4IAggQEAB A3lQBxet/TG4cMpI/tHwYeSfIzxM0uTKNs7UgAQrYL1akaDA7+3bueVqY4NJlUhIcQLNYx8E AIQ01mwjTQ8DeNAdfouNA8440GBCQxJY3MEGD6p4Y844CQCAizcSgpMLAAlAuJ03qOyQRBR3 nEHEK+BMGKIui4kDDAAIPKiiYuSYSMQQRCDCxhiziPMYBgDkEaEaAGQA3Y+MjUPOLFoMoUUh cKxRC4ngeILiH8Qkk0cCAUzSDZWpzbLEE1EwggcYqWCj2DNADFDAAQUgIAAAEFDDJmPYqNJF F1s4cscTmCDjDTjdSPOHBQggUAEQDAgggTWDPoYMJkFoUdRmddyyjWLeULMMMcAsIw0x4wkM IME1g25zyxpHxFYUHmyIggw4H4ojITnfiLMNMAkcAAub4BQjihRdDGTJHmvc4Qo1wD6Imje6 eILbj+BQ4wqu5Q3ECSJ0FOKKMtv4mBg33Pw4zjbKuBIIE1xYpIkhdQQiyi7OtAucj6dt48wu otQhBRa6VvSJIRwhIkotvgRTzMUYZ6xxMcj4QkspeKDxxRhEmUfIHWjAgQcijEDissuXvCyz zH7Q8YQURxDhUsn/bCInR3AELfTQZBRt9BBJkCGFFVhMwTNBlnBCSCGEIJQQIAklZMXWRBAR RRRWENHwRQEBADs=tsearch1tdatatformats gif -index 0tsearch2s gif -index 1s Search.fieldtimagetfocustborderiiitstickytews Search.entrytnsweis Entry.paddingsEntry.textareatchildrent backgrounds#b2b2b2tstyletwidthitpadxi tpady(RR(t__doc__tTkintertttktTktrootRt PhotoImagets1ts2tStyleR telement_createtlayoutt configuretEntryte1te2tgridtmainloop(((s8/usr/lib64/python2.7/Demo/tkinter/ttk/mac_searchentry.pyts(   )   +PK%L]nnF tkinter/ttk/notebook_closebtn.pynu["""A Ttk Notebook with close buttons. Based on an example by patthoyts, http://paste.tclers.tk/896 """ import os import Tkinter import ttk root = Tkinter.Tk() imgdir = os.path.join(os.path.dirname(__file__), 'img') i1 = Tkinter.PhotoImage("img_close", file=os.path.join(imgdir, 'close.gif')) i2 = Tkinter.PhotoImage("img_closeactive", file=os.path.join(imgdir, 'close_active.gif')) i3 = Tkinter.PhotoImage("img_closepressed", file=os.path.join(imgdir, 'close_pressed.gif')) style = ttk.Style() style.element_create("close", "image", "img_close", ("active", "pressed", "!disabled", "img_closepressed"), ("active", "!disabled", "img_closeactive"), border=8, sticky='') style.layout("ButtonNotebook", [("ButtonNotebook.client", {"sticky": "nswe"})]) style.layout("ButtonNotebook.Tab", [ ("ButtonNotebook.tab", {"sticky": "nswe", "children": [("ButtonNotebook.padding", {"side": "top", "sticky": "nswe", "children": [("ButtonNotebook.focus", {"side": "top", "sticky": "nswe", "children": [("ButtonNotebook.label", {"side": "left", "sticky": ''}), ("ButtonNotebook.close", {"side": "left", "sticky": ''})] })] })] })] ) def btn_press(event): x, y, widget = event.x, event.y, event.widget elem = widget.identify(x, y) index = widget.index("@%d,%d" % (x, y)) if "close" in elem: widget.state(['pressed']) widget.pressed_index = index def btn_release(event): x, y, widget = event.x, event.y, event.widget if not widget.instate(['pressed']): return elem = widget.identify(x, y) index = widget.index("@%d,%d" % (x, y)) if "close" in elem and widget.pressed_index == index: widget.forget(index) widget.event_generate("<>") widget.state(["!pressed"]) widget.pressed_index = None root.bind_class("TNotebook", "", btn_press, True) root.bind_class("TNotebook", "", btn_release) # create a ttk notebook with our custom style, and add some tabs to it nb = ttk.Notebook(width=200, height=200, style="ButtonNotebook") nb.pressed_index = None f1 = Tkinter.Frame(nb, background="red") f2 = Tkinter.Frame(nb, background="green") f3 = Tkinter.Frame(nb, background="blue") nb.add(f1, text='Red', padding=3) nb.add(f2, text='Green', padding=3) nb.add(f3, text='Blue', padding=3) nb.pack(expand=1, fill='both') root.mainloop() PK%L]/ QQtkinter/ttk/combo_themes.pynu["""Ttk Theme Selector. Although it is a theme selector, you won't notice many changes since there is only a combobox and a frame around. """ import ttk class App(ttk.Frame): def __init__(self): ttk.Frame.__init__(self) self.style = ttk.Style() self._setup_widgets() def _change_theme(self, event): if event.widget.current(): # value #0 is not a theme newtheme = event.widget.get() # change to the new theme and refresh all the widgets self.style.theme_use(newtheme) def _setup_widgets(self): themes = list(self.style.theme_names()) themes.insert(0, "Pick a theme") # Create a readonly Combobox which will display 4 values at max, # which will cause it to create a scrollbar if there are more # than 4 values in total. themes_combo = ttk.Combobox(self, values=themes, state="readonly", height=4) themes_combo.set(themes[0]) # sets the combobox value to "Pick a theme" # Combobox widget generates a <> virtual event # when the user selects an element. This event is generated after # the listbox is unposted (after you select an item, the combobox's # listbox disappears, then it is said that listbox is now unposted). themes_combo.bind("<>", self._change_theme) themes_combo.pack(fill='x') self.pack(fill='both', expand=1) def main(): app = App() app.master.title("Ttk Combobox") app.mainloop() if __name__ == "__main__": main() PK%L]UWp turtle/tdemo_planet_and_moon.pycnu[ Afc@sdZddlmZmZmZmZddlmZdZ de fdYZ defdYZ d Z ed kre end S( s turtle-example-suite: tdemo_planets_and_moon.py Gravitational system simulation using the approximation method from Feynman-lectures, p.9-8, using turtlegraphics. Example: heavy central body, light planet, very light moon! Planet has a circular orbit, moon a stable orbit around the planet. You can hold the movement temporarily by pressing the left mouse button with the mouse over the scrollbar of the canvas. i(tShapetTurtletmainlooptVec2D(tsleepitGravSyscBs#eZdZdZdZRS(cCsg|_d|_d|_dS(Nig{Gz?(tplanetstttdt(tself((s9/usr/lib64/python2.7/Demo/turtle/tdemo_planet_and_moon.pyt__init__s  cCs"x|jD]}|jq WdS(N(Rtinit(R tp((s9/usr/lib64/python2.7/Demo/turtle/tdemo_planet_and_moon.pyR scCsKxDtdD]6}|j|j7_x|jD]}|jq/Wq WdS(Ni'(trangeRRRtstep(R tiR ((s9/usr/lib64/python2.7/Demo/turtle/tdemo_planet_and_moon.pytstart!s(t__name__t __module__R R R(((s9/usr/lib64/python2.7/Demo/turtle/tdemo_planet_and_moon.pyRs  tStarcBs,eZdZdZdZdZRS(cCsptj|d||j||_|j|||_|jj|||_|j d|j dS(Ntshapetuser( RR tpenuptmtsetpostvRtappendtgravSyst resizemodetpendown(R RtxRRR((s9/usr/lib64/python2.7/Demo/turtle/tdemo_planet_and_moon.pyR (s      cCs:|jj}|j|_|jd||j|_dS(Ng?(RRtacctaR(R R((s9/usr/lib64/python2.7/Demo/turtle/tdemo_planet_and_moon.pyR 2s cCsrtdd}x\|jjD]N}||kr|j|j}|t|jt|d|7}qqW|S(Nii(tVecRRtpostGRtabs(R R tplanetR((s9/usr/lib64/python2.7/Demo/turtle/tdemo_planet_and_moon.pyR6s  *cCs|jj}|j|j||j|jjj|dkrh|j|j|jjdn|j |_ |j||j |_dS(Ni( RRRR"RRtindext setheadingttowardsRR (R R((s9/usr/lib64/python2.7/Demo/turtle/tdemo_planet_and_moon.pyR=s  #(RRR R RR(((s9/usr/lib64/python2.7/Demo/turtle/tdemo_planet_and_moon.pyR's  cCst}|j|jdd|j|j|jd|jd|j|jdd|j |j }|j|jdd|j |j }t d}|j |d|j |d|j jd||jd dt}td tddtdd |d }|jd |jd|jtdtddtdd|d}|jd|jdtd tddtdd|d}|jd|jd|j|jdS(NiiiZitcompoundtorangetblueR%ii@Bgtcircletyellowg?i0iitgreeng?ii'g?sDone!(Rtresetttracerthttputfdtltt begin_polyR,tend_polytget_polyRt addcomponentt getscreentregister_shapeRRR!tcolort shapesizetpencolorR R(tstm1tm2t planetshapetgstsuntearthtmoon((s9/usr/lib64/python2.7/Demo/turtle/tdemo_planet_and_moon.pytmainGsD              *   *  *    t__main__N(t__doc__tturtleRRRRR!ttimeRR#tobjectRRRFR(((s9/usr/lib64/python2.7/Demo/turtle/tdemo_planet_and_moon.pyts" ' PK%L]PX''turtle/tdemo_minimal_hanoi.pycnu[ Afc@sdZddlTdefdYZdefdYZdZdZd Ze d kr{eZ e GHe nd S( s turtle-example-suite: tdemo_minimal_hanoi.py A minimal 'Towers of Hanoi' animation: A tower of 6 discs is transferred from the left to the right peg. An imho quite elegant and concise implementation using a tower class, which is derived from the built-in type list. Discs are turtles with shape "square", but stretched to rectangles by shapesize() --------------------------------------- To exit press STOP button --------------------------------------- i(t*tDisccBseZdZRS(cCsgtj|dddt|j|jd|dd|j|ddd|d|jdS( Ntshapetsquaretvisibleg?ig@ii(tTurtlet__init__tFalsetput shapesizet fillcolortst(tselftn((s7/usr/lib64/python2.7/Demo/turtle/tdemo_minimal_hanoi.pyRs  (t__name__t __module__R(((s7/usr/lib64/python2.7/Demo/turtle/tdemo_minimal_hanoi.pyRstTowercBs)eZdZdZdZdZRS(s-Hanoi tower, a subclass of built-in type listcCs ||_dS(s-create an empty tower. x is x-position of pegN(tx(R R((s7/usr/lib64/python2.7/Demo/turtle/tdemo_minimal_hanoi.pyR scCs<|j|j|jddt||j|dS(Niji"(tsetxRtsetytlentappend(R td((s7/usr/lib64/python2.7/Demo/turtle/tdemo_minimal_hanoi.pytpush#scCs tj|}|jd|S(Ni(tlisttpopR(R R((s7/usr/lib64/python2.7/Demo/turtle/tdemo_minimal_hanoi.pyR's (RRt__doc__RRR(((s7/usr/lib64/python2.7/Demo/turtle/tdemo_minimal_hanoi.pyRs  cCsT|dkrPt|d||||j|jt|d|||ndS(Nii(thanoiRR(R tfrom_twith_tto_((s7/usr/lib64/python2.7/Demo/turtle/tdemo_minimal_hanoi.pyR,s cCsYtddty-tdttttddddd Wntk rTnXdS( Ntspaceispress STOP button to exittaligntcentertfonttCourieritbold(R#iR$( tonkeytNonetclearRtt1tt2tt3twritet Terminator(((s7/usr/lib64/python2.7/Demo/turtle/tdemo_minimal_hanoi.pytplay2s   cCstttddtdatdatdax-tdddD]}tjt |qRWt ddd d dt t dt dS(Niiiiiispress spacebar to start gameR R!R"R#iR$Rt EVENTLOOP(R#iR$(thttpenuptgotoRR(R)R*trangeRRR+R%R-tlisten(ti((s7/usr/lib64/python2.7/Demo/turtle/tdemo_minimal_hanoi.pytmain<s       t__main__N( RtturtleRRRRRR-R5Rtmsgtmainloop(((s7/usr/lib64/python2.7/Demo/turtle/tdemo_minimal_hanoi.pyts     PK%L]tn*ܷturtle/tdemo_chaos.pynu[# File: tdemo_chaos.py # Author: Gregor Lingl # Date: 2009-06-24 # A demonstration of chaos from turtle import * N = 80 def f(x): return 3.9*x*(1-x) def g(x): return 3.9*(x-x**2) def h(x): return 3.9*x-3.9*x*x def jumpto(x, y): penup(); goto(x,y) def line(x1, y1, x2, y2): jumpto(x1, y1) pendown() goto(x2, y2) def coosys(): line(-1, 0, N+1, 0) line(0, -0.1, 0, 1.1) def plot(fun, start, color): pencolor(color) x = start jumpto(0, x) pendown() dot(5) for i in range(N): x=fun(x) goto(i+1,x) dot(5) def main(): reset() setworldcoordinates(-1.0,-0.1, N+1, 1.1) speed(0) hideturtle() coosys() plot(f, 0.35, "blue") plot(g, 0.35, "green") plot(h, 0.35, "red") # Now zoom in: for s in range(100): setworldcoordinates(0.5*s,-0.1, N+1, 1.1) return "Done!" if __name__ == "__main__": main() mainloop() PK%L]w[turtle/tdemo_wikipedia.pyonu[ ^c@srdZddlmZmZmZddlmZmZdZdZ e dkrne Z e GHendS(sF turtle-example-suite: tdemo_wikipedia3.py This example is inspired by the Wikipedia article on turtle graphics. (See example wikipedia1 for URLs) First we create (ne-1) (i.e. 35 in this example) copies of our first turtle p. Then we let them perform their steps in parallel. Followed by a complete undo(). i(tScreentTurtletmainloop(tclocktsleepcCs|g}xGtd|D]6}|j}|jd||j||}qWxvt|D]h}t|d||d}xC|D];}|jd||jd|d||j|qWq`WdS(Nigv@g@gffffff?i(trangetclonetrttappendtabstpencolortfd(tptnetszt turtlelisttitqtctt((s3/usr/lib64/python2.7/Demo/turtle/tdemo_wikipedia.pytmn_ecks     cCs t}|jdt}|jd|j|jd|jd|jddt}t |ddt}||}t dt}xPt g|j D]}|j ^qrx|j D]}|jqWqWt}d|||S( Ntblackitredii$iisLaufzeit: %.3f sec(RtbgcolorRtspeedt hideturtleR tpensizettracerRRRtanytturtlestundobufferentriestundo(tsR tattettz1R((s3/usr/lib64/python2.7/Demo/turtle/tdemo_wikipedia.pytmain$s&            . t__main__N( t__doc__tturtleRRRttimeRRRR$t__name__tmsg(((s3/usr/lib64/python2.7/Demo/turtle/tdemo_wikipedia.pyts    PK%L] turtle/tdemo_clock.pynuȯ#! /usr/bin/python2.7 # -*- coding: cp1252 -*- """ turtle-example-suite: tdemo_clock.py Enhanced clock-program, showing date and time ------------------------------------ Press STOP to exit the program! ------------------------------------ """ from turtle import * from datetime import datetime def jump(distanz, winkel=0): penup() right(winkel) forward(distanz) left(winkel) pendown() def hand(laenge, spitze): fd(laenge*1.15) rt(90) fd(spitze/2.0) lt(120) fd(spitze) lt(120) fd(spitze) lt(120) fd(spitze/2.0) def make_hand_shape(name, laenge, spitze): reset() jump(-laenge*0.15) begin_poly() hand(laenge, spitze) end_poly() hand_form = get_poly() register_shape(name, hand_form) def clockface(radius): reset() pensize(7) for i in range(60): jump(radius) if i % 5 == 0: fd(25) jump(-radius-25) else: dot(3) jump(-radius) rt(6) def setup(): global second_hand, minute_hand, hour_hand, writer mode("logo") make_hand_shape("second_hand", 125, 25) make_hand_shape("minute_hand", 130, 25) make_hand_shape("hour_hand", 90, 25) clockface(160) second_hand = Turtle() second_hand.shape("second_hand") second_hand.color("gray20", "gray80") minute_hand = Turtle() minute_hand.shape("minute_hand") minute_hand.color("blue1", "red1") hour_hand = Turtle() hour_hand.shape("hour_hand") hour_hand.color("blue3", "red3") for hand in second_hand, minute_hand, hour_hand: hand.resizemode("user") hand.shapesize(1, 1, 3) hand.speed(0) ht() writer = Turtle() #writer.mode("logo") writer.ht() writer.pu() writer.bk(85) def wochentag(t): wochentag = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] return wochentag[t.weekday()] def datum(z): monat = ["Jan.", "Feb.", "Mar.", "Apr.", "May", "June", "July", "Aug.", "Sep.", "Oct.", "Nov.", "Dec."] j = z.year m = monat[z.month - 1] t = z.day return "%s %d %d" % (m, t, j) def tick(): t = datetime.today() sekunde = t.second + t.microsecond*0.000001 minute = t.minute + sekunde/60.0 stunde = t.hour + minute/60.0 try: tracer(False) # Terminator can occur here writer.clear() writer.home() writer.forward(65) writer.write(wochentag(t), align="center", font=("Courier", 14, "bold")) writer.back(150) writer.write(datum(t), align="center", font=("Courier", 14, "bold")) writer.forward(85) tracer(True) second_hand.setheading(6*sekunde) # or here minute_hand.setheading(6*minute) hour_hand.setheading(30*stunde) tracer(True) ontimer(tick, 100) except Terminator: pass # turtledemo user pressed STOP def main(): tracer(False) setup() tracer(True) tick() return "EVENTLOOP" if __name__ == "__main__": mode("logo") msg = main() print msg mainloop() # keep window open PK%L]PX''turtle/tdemo_minimal_hanoi.pyonu[ Afc@sdZddlTdefdYZdefdYZdZdZd Ze d kr{eZ e GHe nd S( s turtle-example-suite: tdemo_minimal_hanoi.py A minimal 'Towers of Hanoi' animation: A tower of 6 discs is transferred from the left to the right peg. An imho quite elegant and concise implementation using a tower class, which is derived from the built-in type list. Discs are turtles with shape "square", but stretched to rectangles by shapesize() --------------------------------------- To exit press STOP button --------------------------------------- i(t*tDisccBseZdZRS(cCsgtj|dddt|j|jd|dd|j|ddd|d|jdS( Ntshapetsquaretvisibleg?ig@ii(tTurtlet__init__tFalsetput shapesizet fillcolortst(tselftn((s7/usr/lib64/python2.7/Demo/turtle/tdemo_minimal_hanoi.pyRs  (t__name__t __module__R(((s7/usr/lib64/python2.7/Demo/turtle/tdemo_minimal_hanoi.pyRstTowercBs)eZdZdZdZdZRS(s-Hanoi tower, a subclass of built-in type listcCs ||_dS(s-create an empty tower. x is x-position of pegN(tx(R R((s7/usr/lib64/python2.7/Demo/turtle/tdemo_minimal_hanoi.pyR scCs<|j|j|jddt||j|dS(Niji"(tsetxRtsetytlentappend(R td((s7/usr/lib64/python2.7/Demo/turtle/tdemo_minimal_hanoi.pytpush#scCs tj|}|jd|S(Ni(tlisttpopR(R R((s7/usr/lib64/python2.7/Demo/turtle/tdemo_minimal_hanoi.pyR's (RRt__doc__RRR(((s7/usr/lib64/python2.7/Demo/turtle/tdemo_minimal_hanoi.pyRs  cCsT|dkrPt|d||||j|jt|d|||ndS(Nii(thanoiRR(R tfrom_twith_tto_((s7/usr/lib64/python2.7/Demo/turtle/tdemo_minimal_hanoi.pyR,s cCsYtddty-tdttttddddd Wntk rTnXdS( Ntspaceispress STOP button to exittaligntcentertfonttCourieritbold(R#iR$( tonkeytNonetclearRtt1tt2tt3twritet Terminator(((s7/usr/lib64/python2.7/Demo/turtle/tdemo_minimal_hanoi.pytplay2s   cCstttddtdatdatdax-tdddD]}tjt |qRWt ddd d dt t dt dS(Niiiiiispress spacebar to start gameR R!R"R#iR$Rt EVENTLOOP(R#iR$(thttpenuptgotoRR(R)R*trangeRRR+R%R-tlisten(ti((s7/usr/lib64/python2.7/Demo/turtle/tdemo_minimal_hanoi.pytmain<s       t__main__N( RtturtleRRRRRR-R5Rtmsgtmainloop(((s7/usr/lib64/python2.7/Demo/turtle/tdemo_minimal_hanoi.pyts     PK%L]UWp turtle/tdemo_planet_and_moon.pyonu[ Afc@sdZddlmZmZmZmZddlmZdZ de fdYZ defdYZ d Z ed kre end S( s turtle-example-suite: tdemo_planets_and_moon.py Gravitational system simulation using the approximation method from Feynman-lectures, p.9-8, using turtlegraphics. Example: heavy central body, light planet, very light moon! Planet has a circular orbit, moon a stable orbit around the planet. You can hold the movement temporarily by pressing the left mouse button with the mouse over the scrollbar of the canvas. i(tShapetTurtletmainlooptVec2D(tsleepitGravSyscBs#eZdZdZdZRS(cCsg|_d|_d|_dS(Nig{Gz?(tplanetstttdt(tself((s9/usr/lib64/python2.7/Demo/turtle/tdemo_planet_and_moon.pyt__init__s  cCs"x|jD]}|jq WdS(N(Rtinit(R tp((s9/usr/lib64/python2.7/Demo/turtle/tdemo_planet_and_moon.pyR scCsKxDtdD]6}|j|j7_x|jD]}|jq/Wq WdS(Ni'(trangeRRRtstep(R tiR ((s9/usr/lib64/python2.7/Demo/turtle/tdemo_planet_and_moon.pytstart!s(t__name__t __module__R R R(((s9/usr/lib64/python2.7/Demo/turtle/tdemo_planet_and_moon.pyRs  tStarcBs,eZdZdZdZdZRS(cCsptj|d||j||_|j|||_|jj|||_|j d|j dS(Ntshapetuser( RR tpenuptmtsetpostvRtappendtgravSyst resizemodetpendown(R RtxRRR((s9/usr/lib64/python2.7/Demo/turtle/tdemo_planet_and_moon.pyR (s      cCs:|jj}|j|_|jd||j|_dS(Ng?(RRtacctaR(R R((s9/usr/lib64/python2.7/Demo/turtle/tdemo_planet_and_moon.pyR 2s cCsrtdd}x\|jjD]N}||kr|j|j}|t|jt|d|7}qqW|S(Nii(tVecRRtpostGRtabs(R R tplanetR((s9/usr/lib64/python2.7/Demo/turtle/tdemo_planet_and_moon.pyR6s  *cCs|jj}|j|j||j|jjj|dkrh|j|j|jjdn|j |_ |j||j |_dS(Ni( RRRR"RRtindext setheadingttowardsRR (R R((s9/usr/lib64/python2.7/Demo/turtle/tdemo_planet_and_moon.pyR=s  #(RRR R RR(((s9/usr/lib64/python2.7/Demo/turtle/tdemo_planet_and_moon.pyR's  cCst}|j|jdd|j|j|jd|jd|j|jdd|j |j }|j|jdd|j |j }t d}|j |d|j |d|j jd||jd dt}td tddtdd |d }|jd |jd|jtdtddtdd|d}|jd|jdtd tddtdd|d}|jd|jd|j|jdS(NiiiZitcompoundtorangetblueR%ii@Bgtcircletyellowg?i0iitgreeng?ii'g?sDone!(Rtresetttracerthttputfdtltt begin_polyR,tend_polytget_polyRt addcomponentt getscreentregister_shapeRRR!tcolort shapesizetpencolorR R(tstm1tm2t planetshapetgstsuntearthtmoon((s9/usr/lib64/python2.7/Demo/turtle/tdemo_planet_and_moon.pytmainGsD              *   *  *    t__main__N(t__doc__tturtleRRRRR!ttimeRR#tobjectRRRFR(((s9/usr/lib64/python2.7/Demo/turtle/tdemo_planet_and_moon.pyts" ' PK%L]CCturtle/tdemo_wikipedia.pynu[""" turtle-example-suite: tdemo_wikipedia3.py This example is inspired by the Wikipedia article on turtle graphics. (See example wikipedia1 for URLs) First we create (ne-1) (i.e. 35 in this example) copies of our first turtle p. Then we let them perform their steps in parallel. Followed by a complete undo(). """ from turtle import Screen, Turtle, mainloop from time import clock, sleep def mn_eck(p, ne,sz): turtlelist = [p] #create ne-1 additional turtles for i in range(1,ne): q = p.clone() q.rt(360.0/ne) turtlelist.append(q) p = q for i in range(ne): c = abs(ne/2.0-i)/(ne*.7) # let those ne turtles make a step # in parallel: for t in turtlelist: t.rt(360./ne) t.pencolor(1-c,0,c) t.fd(sz) def main(): s = Screen() s.bgcolor("black") p=Turtle() p.speed(0) p.hideturtle() p.pencolor("red") p.pensize(3) s.tracer(36,0) at = clock() mn_eck(p, 36, 19) et = clock() z1 = et-at sleep(1) at = clock() while any([t.undobufferentries() for t in s.turtles()]): for t in s.turtles(): t.undo() et = clock() return "Laufzeit: %.3f sec" % (z1+et-at) if __name__ == '__main__': msg = main() print msg mainloop() PK%L]jN= = turtle/tdemo_colormixer.pycnu[ ^c@slddlmZmZmZdefdYZdZdZedkrheZeGHendS(i(tScreentTurtletmainloopt ColorTurtlecBseZdZdZRS(cCstj||jd|jd|jddd|jddddg|_||_||j|<|j|j|j d|j d|j |j |d|j |jd|j |j||jd |j|jdS( Ntturtletuseriii iiZitgray25(Rt__init__tshapet resizemodet shapesizetpensizet_colortxtcolortspeedtlefttputgototpdtsetytpencolortondragtshift(tselfR ty((s4/usr/lib64/python2.7/Demo/turtle/tdemo_colormixer.pyRs&              cCsP|jtdt|d|j|j|j<|j|jtdS(Nii(RtmaxtmintycorR R t fillcolort setbgcolor(RR R((s4/usr/lib64/python2.7/Demo/turtle/tdemo_colormixer.pyRs(t__name__t __module__RR(((s4/usr/lib64/python2.7/Demo/turtle/tdemo_colormixer.pyRs cCs)tjtjtjtjdS(N(tscreentbgcolortredRtgreentblue(((s4/usr/lib64/python2.7/Demo/turtle/tdemo_colormixer.pyR"sc Cstatjdtjddddtddatddatddatt }|j |j |j dd |j d d d d dddfdS(Niig333333ӿig?g?iigffffff?sDRAG!taligntcentertfonttArialitboldtitalict EVENTLOOP(R*R+(RR!tdelaytsetworldcoordinatesRR#R$R%RRthtRRtwrite(twriter((s4/usr/lib64/python2.7/Demo/turtle/tdemo_colormixer.pytmain%s     "t__main__N( RRRRRRR2Rtmsg(((s4/usr/lib64/python2.7/Demo/turtle/tdemo_colormixer.pyts    PK%L]Hllturtle/tdemo_peace.pyonu[ Afc@s:dZddlTdZedkr6eendS(s turtle-example-suite: tdemo_peace.py A simple drawing suitable as a beginner's programming example. Aside from the peacecolors assignment and the for loop, it only uses turtle commands. i(t*cCsMd}ttttdd td xX|D]P}t|ttd ttd t d td t d q9Wtdtdtddtt dt d tdtt dtdt dttdttdt d ttdttdddS(Ntred3torangetyellowt seagreen4torchid4t royalblue1t dodgerblue4ii=iFiiZiBitwhiteiiViiTii-i,sDone!(RRRRRRR( tresettScreentuptgototwidthtcolortdowntforwardtbackwardtlefttrighttcircle(t peacecolorstpcolor((s//usr/lib64/python2.7/Demo/turtle/tdemo_peace.pytmainsL                      t__main__N(t__doc__tturtleRt__name__tmainloop(((s//usr/lib64/python2.7/Demo/turtle/tdemo_peace.pyt s   - PK%L]}W$$turtle/tdemo_nim.pyonu[ ^c@s5dZddlZddlZddlZdZdZdZdZedZeedd edd Z dZ dZ dZ dZ dZdZdefdYZdejfdYZdefdYZdefdYZdefdYZdZedkr1eejndS( s turtle-example-suite: tdemo_nim.py Play nim against the computer. The player who takes the last stick is the winner. Implements the model-view-controller design pattern. iNiiiii ii ii?iicCstjttS(N(trandomtrandintt MINSTICKSt MAXSTICKS(((s-/usr/lib64/python2.7/Demo/turtle/tdemo_nim.pyt randomrowscCsy|d|dA|dA}|dkr0t|SxBtdD]4}|||A}|||kr=||f}|Sq=WdS(Niiii(t randommovetrange(tstatetxoredtztstmove((s-/usr/lib64/python2.7/Demo/turtle/tdemo_nim.pyt computerzug!s   cCsot|}x6trDtjdd}|||dkkrPqqWtj|dk||d}||fS(Niii(tmaxtTrueRR(RtmR trand((s-/usr/lib64/python2.7/Demo/turtle/tdemo_nim.pyR+s   tNimModelcBs5eZdZdZdZdZdZRS(cCs ||_dS(N(tgame(tselfR((s-/usr/lib64/python2.7/Demo/turtle/tdemo_nim.pyt__init__6scCsr|jjtjtjgkr"dStttg|_d|_d|_ |jj j tj |j_dS(Ni( RRtNimtCREATEDtOVERRtstickstplayertNonetwinnertviewtsetuptRUNNING(R((s-/usr/lib64/python2.7/Demo/turtle/tdemo_nim.pyR9s  cCs|j|}||j|<|jjj||||j|jrstj|j_|j|_ |jjj nI|jdkrd|_t |j\}}|j ||d|_ndS(Nii( RRRt notify_moveRt game_overRRRRt notify_overR R (Rtrowtcolt maxspalte((s-/usr/lib64/python2.7/Demo/turtle/tdemo_nim.pyR Bs     cCs|jdddgkS(Ni(R(R((s-/usr/lib64/python2.7/Demo/turtle/tdemo_nim.pyR PscCs+|j||krdS|j||dS(N(RR (RR"R#((s-/usr/lib64/python2.7/Demo/turtle/tdemo_nim.pyRSs(t__name__t __module__RRR R R(((s-/usr/lib64/python2.7/Demo/turtle/tdemo_nim.pyR5s    tStickcBs#eZdZdZdZRS(cCstjj|dt||_||_||_|j||\}}|jd|j t dt d|j d|j |j|||jd|jdS(Ntvisibletsquareg$@g4@itwhite(tturtletTurtleRtFalseR"R#Rtcoordstshapet shapesizetHUNITtWUNITtspeedtputgototcolort showturtle(RR"R#Rtxty((s-/usr/lib64/python2.7/Demo/turtle/tdemo_nim.pyRZs       cCskt|d\}}dd|d|t}dd|t}|tdtdtd|tdfS(Niii i(tdivmodR2R1t SCREENWIDTHt SCREENHEIGHT(RR"R#tpackett remainderR8R9((s-/usr/lib64/python2.7/Demo/turtle/tdemo_nim.pyR.hscCs9|jjtjkrdS|jjj|j|jdS(N(RRRRt controllerRR"R#(RR8R9((s-/usr/lib64/python2.7/Demo/turtle/tdemo_nim.pytmakemovens(R%R&RR.R@(((s-/usr/lib64/python2.7/Demo/turtle/tdemo_nim.pyR'Ys  tNimViewcBsAeZdZddZdZdZdZdZRS(cCs||_|j|_|j|_|jjd|jjt|jjdtjdt|_ |j j |j j di|_ xJt dD]<}x3t tD]%}t||||j ||f s0      $E  PK%L]!KKturtle/tdemo_tree.pyonu[ Afc@sodZddlmZmZddlmZdZdZdZe dkrkeZ e GHendS( s turtle-example-suite: tdemo_tree.py Displays a 'breadth-first-tree' - in contrast to the classical Logo tree drawing programs, which use a depth-first-algorithm. Uses: (1) a tree-generator, where the drawing is quasi the side-effect, whereas the generator always yields None. (2) Turtle-cloning: At each branching point the current pen is cloned. So in the end there are 1024 turtles. i(tTurtletmainloop(tclockccs|dkrg}x[|D]S}|j||j}|j||j||j||j|qWx)t|||||D] }dVqWndS(s plist is list of pens l is length of branch a is half of the angle between 2 branches f is factor by which branch is shortened from level to level.iN(tforwardtclonetlefttrighttappendttreetNone(tplisttltatftlsttptqtx((s./usr/lib64/python2.7/Demo/turtle/tdemo_tree.pyRs        cCst}|jd|j|jd|jdd|jd|j|jd|j t |gddd}x|D]}qWt |j j GHdS(NiiiZi.iiAgffffff?(Rt setundobufferR t hideturtletspeedttracerRtpenupRtpendownRtlent getscreentturtles(RttR((s./usr/lib64/python2.7/Demo/turtle/tdemo_tree.pytmaketree's         cCs%t}tt}d||S(Nsdone: %.2f sec.(RR(R tb((s./usr/lib64/python2.7/Demo/turtle/tdemo_tree.pytmain6s  t__main__N( t__doc__tturtleRRttimeRRRRt__name__tmsg(((s./usr/lib64/python2.7/Demo/turtle/tdemo_tree.pyts     PK%L]Hllturtle/tdemo_peace.pycnu[ Afc@s:dZddlTdZedkr6eendS(s turtle-example-suite: tdemo_peace.py A simple drawing suitable as a beginner's programming example. Aside from the peacecolors assignment and the for loop, it only uses turtle commands. i(t*cCsMd}ttttdd td xX|D]P}t|ttd ttd t d td t d q9Wtdtdtddtt dt d tdtt dtdt dttdttdt d ttdttdddS(Ntred3torangetyellowt seagreen4torchid4t royalblue1t dodgerblue4ii=iFiiZiBitwhiteiiViiTii-i,sDone!(RRRRRRR( tresettScreentuptgototwidthtcolortdowntforwardtbackwardtlefttrighttcircle(t peacecolorstpcolor((s//usr/lib64/python2.7/Demo/turtle/tdemo_peace.pytmainsL                      t__main__N(t__doc__tturtleRt__name__tmainloop(((s//usr/lib64/python2.7/Demo/turtle/tdemo_peace.pyt s   - PK%L]:Bmmturtle/tdemo_paint.pycnu[ Afc@s_dZddlTdddZdddZdZedkr[eZeGHendS( sp turtle-example-suite: tdemo_paint.py A simple event-driven paint program - left mouse button moves turtle - middle mouse button changes color - right mouse button toogles betweem pen up (no line drawn when the turtle moves) and pen down (line is drawn). If pen up follows at least two pen-down moves, the polygon that includes the starting point is filled. ------------------------------------------- Play around by clicking into the canvas using all three mouse buttons. ------------------------------------------- To exit press STOP button ------------------------------------------- i(t*icCs0tdrttnttdS(Ntpendown(tpentend_filltuptdownt begin_fill(txty((s//usr/lib64/python2.7/Demo/turtle/tdemo_paint.pyt switchupdowns   cCs$tdtd attddS(Nii(tcolorstcolor(RR((s//usr/lib64/python2.7/Demo/turtle/tdemo_paint.pyt changecolor scCsztdtdtdtdddddgattd tttd tt d ttdd S( Ntcircletuserg?itredtgreentbluetyellowiiit EVENTLOOP( tshapet resizemodet shapesizetwidthR R R t onscreenclicktgotoR (((s//usr/lib64/python2.7/Demo/turtle/tdemo_paint.pytmain%s       t__main__N(t__doc__tturtleR R Rt__name__tmsgtmainloop(((s//usr/lib64/python2.7/Demo/turtle/tdemo_paint.pyts    PK%L] p||$turtle/tdemo_I_dontlike_tiltdemo.pycnu[ Afc@sMdZddlTddlZdZedkrIeZeGHendS(s turtle-example-suite: tdemo-I_dont_like_tiltdemo.py Demonstrates (a) use of a tilted ellipse as turtle shape (b) stamping that shape We can remove it, if you don't like it. Without using reset() ;-) --------------------------------------- i(t*NcCsttdtdttddtdttdttdd d t d d x/t dD]!}t dt d t q|Wt d dx/t dD]!}t dt d t qWtdtdddt ddxBt dD]4}t dt d |ddkrt qqWtjdxtrotq\Wttddddd dS(!Ntcircletuseriigo!@iZi-ii itredtvioletitiiiitbluetyellowiiis OK, OVER!taligntcentertfonttCouriertboldsDone!i(R iR (tresettshapet resizemodetputbktrttpdttiltt turtlesizetcolortrangetfdtlttstampttimetsleeptundobufferentriestundothttwrite(ti((s=/usr/lib64/python2.7/Demo/turtle/tdemo_I_dontlike_tiltdemo.pytmainsD                   t__main__(t__doc__tturtleRR"t__name__tmsgtmainloop(((s=/usr/lib64/python2.7/Demo/turtle/tdemo_I_dontlike_tiltdemo.pyts   %  PK%L]3 turtle/tdemo_tree.pynuȯ#! /usr/bin/python2.7 """ turtle-example-suite: tdemo_tree.py Displays a 'breadth-first-tree' - in contrast to the classical Logo tree drawing programs, which use a depth-first-algorithm. Uses: (1) a tree-generator, where the drawing is quasi the side-effect, whereas the generator always yields None. (2) Turtle-cloning: At each branching point the current pen is cloned. So in the end there are 1024 turtles. """ from turtle import Turtle, mainloop from time import clock def tree(plist, l, a, f): """ plist is list of pens l is length of branch a is half of the angle between 2 branches f is factor by which branch is shortened from level to level.""" if l > 3: lst = [] for p in plist: p.forward(l) q = p.clone() p.left(a) q.right(a) lst.append(p) lst.append(q) for x in tree(lst, l*f, a, f): yield None def maketree(): p = Turtle() p.setundobuffer(None) p.hideturtle() p.speed(0) p.tracer(30,0) p.left(90) p.penup() p.forward(-210) p.pendown() t = tree([p], 200, 65, 0.6375) for x in t: pass print len(p.getscreen().turtles()) def main(): a=clock() maketree() b=clock() return "done: %.2f sec." % (b-a) if __name__ == "__main__": msg = main() print msg mainloop() PK%L]JȤturtle/turtle.cfgnu[width = 800 height = 600 canvwidth = 1200 canvheight = 900 shape = arrow mode = standard resizemode = auto fillcolor = "" title = Python turtle graphics demo. PK%L]g#turtle/tdemo_lindenmayer_indian.pycnu[ Afc@sSdZddlTdZdZdZedkrOeZeGHendS(s turtle-example-suite: xtx_lindenmayer_indian.py Each morning women in Tamil Nadu, in southern India, place designs, created by using rice flour and known as kolam on the thresholds of their homes. These can be described by Lindenmayer systems, which can easily be implemented with turtle graphics and Python. Two examples are shown here: (1) the snake kolam (2) anklets of Krishna Taken from Marcia Ascher: Mathematics Elsewhere, An Exploration of Ideas Across Cultures i(t*cCsNxGt|D]9}d}x$|D]}||j||}q W|}q W|S(Nt(trangetget(tseqtreplacementRulestntitnewseqtelement((s</usr/lib64/python2.7/Demo/turtle/tdemo_lindenmayer_indian.pytreplaces   cCsWxP|D]H}y||Wqtk rNyt|||WqOqOXqXqWdS(N(t TypeErrortdraw(tcommandstrulestb((s</usr/lib64/python2.7/Demo/turtle/tdemo_lindenmayer_indian.pyR &s  cCsrd}d}d}i|d6|d6|d6dd6}id d6}d }t||d }ttd td d tttdtt||ddl m }|d d}d} d} i|d6| d6| d6} idd6dd6} d} ttd td d tt dt| | d }t|| td dS(NcSstddS(Ni-(tright(((s</usr/lib64/python2.7/Demo/turtle/tdemo_lindenmayer_indian.pytr7scSstddS(Ni-(tleft(((s</usr/lib64/python2.7/Demo/turtle/tdemo_lindenmayer_indian.pytl:scSstddS(Ng@(tforward(((s</usr/lib64/python2.7/Demo/turtle/tdemo_lindenmayer_indian.pytf=st-t+Rsf+f+f--f--f+f+fRsb+f+b--f--b+f+bs b--f--b--fiiiii(tsleepcSstdtdddS(Ntredi iZ(tcolortcircle(((s</usr/lib64/python2.7/Demo/turtle/tdemo_lindenmayer_indian.pytAVs cSsOddlm}tdd|d}t|t|dt|dS(Ni(tsqrttblackiii(tmathRRRR(RR((s</usr/lib64/python2.7/Demo/turtle/tdemo_lindenmayer_indian.pytBZs    cSstdtddS(Ntgreeni (RR(((s</usr/lib64/python2.7/Demo/turtle/tdemo_lindenmayer_indian.pytFbs tatafbfat afbfbfbfatfbfbfbfbi-sDone!( R tresettspeedttracerthttuptbackwardtdownR ttimeRR(RRRt snake_rulestsnake_replacementRulest snake_starttdrawingRRR R"t krishna_rulestkrishna_replacementRulest krishna_start((s</usr/lib64/python2.7/Demo/turtle/tdemo_lindenmayer_indian.pytmain1s@   "              t__main__N(t__doc__tturtleR R R6t__name__tmsgtmainloop(((s</usr/lib64/python2.7/Demo/turtle/tdemo_lindenmayer_indian.pyts   C  PK%L]^turtle/tdemo_chaos.pyonu[ ^c@syddlTdZdZdZdZdZdZdZd Zd Z e d krue e nd S( i(t*iPcCsd|d|S(Ng333333@i((tx((s//usr/lib64/python2.7/Demo/turtle/tdemo_chaos.pytf scCsd||dS(Ng333333@i((R((s//usr/lib64/python2.7/Demo/turtle/tdemo_chaos.pytgscCsd|d||S(Ng333333@((R((s//usr/lib64/python2.7/Demo/turtle/tdemo_chaos.pythscCstt||dS(N(tpenuptgoto(Rty((s//usr/lib64/python2.7/Demo/turtle/tdemo_chaos.pytjumptoscCs%t||tt||dS(N(RtpendownR(tx1ty1tx2ty2((s//usr/lib64/python2.7/Demo/turtle/tdemo_chaos.pytlines cCs.tddtddtdddddS(Niiigg?(RtN(((s//usr/lib64/python2.7/Demo/turtle/tdemo_chaos.pytcoosysscCspt||}td|ttdx;ttD]-}||}t|d|tdq;WdS(Niii(tpencolorRR tdottrangeRR(tfuntstarttcolorRti((s//usr/lib64/python2.7/Demo/turtle/tdemo_chaos.pytplot s    cCsttddtddtdttttddttddtt dd x/t d D]!}td |dtddqsWd S( Nggig?igffffff?tbluetgreentredidg?sDone!( tresettsetworldcoordinatesRtspeedt hideturtleRRRRRR(ts((s//usr/lib64/python2.7/Demo/turtle/tdemo_chaos.pytmain+s t__main__N( tturtleRRRRRRRRR!t__name__tmainloop(((s//usr/lib64/python2.7/Demo/turtle/tdemo_chaos.pyts         PK%L]!KKturtle/tdemo_tree.pycnu[ Afc@sodZddlmZmZddlmZdZdZdZe dkrkeZ e GHendS( s turtle-example-suite: tdemo_tree.py Displays a 'breadth-first-tree' - in contrast to the classical Logo tree drawing programs, which use a depth-first-algorithm. Uses: (1) a tree-generator, where the drawing is quasi the side-effect, whereas the generator always yields None. (2) Turtle-cloning: At each branching point the current pen is cloned. So in the end there are 1024 turtles. i(tTurtletmainloop(tclockccs|dkrg}x[|D]S}|j||j}|j||j||j||j|qWx)t|||||D] }dVqWndS(s plist is list of pens l is length of branch a is half of the angle between 2 branches f is factor by which branch is shortened from level to level.iN(tforwardtclonetlefttrighttappendttreetNone(tplisttltatftlsttptqtx((s./usr/lib64/python2.7/Demo/turtle/tdemo_tree.pyRs        cCst}|jd|j|jd|jdd|jd|j|jd|j t |gddd}x|D]}qWt |j j GHdS(NiiiZi.iiAgffffff?(Rt setundobufferR t hideturtletspeedttracerRtpenupRtpendownRtlent getscreentturtles(RttR((s./usr/lib64/python2.7/Demo/turtle/tdemo_tree.pytmaketree's         cCs%t}tt}d||S(Nsdone: %.2f sec.(RR(R tb((s./usr/lib64/python2.7/Demo/turtle/tdemo_tree.pytmain6s  t__main__N( t__doc__tturtleRRttimeRRRRt__name__tmsg(((s./usr/lib64/python2.7/Demo/turtle/tdemo_tree.pyts     PK%L]ʭ turtle/tdemo_fractalcurves.pycnu[ Afc@smdZddlTddlmZmZdefdYZdZedkrieZ e GHe ndS( s& turtle-example-suite: tdemo_fractalCurves.py This program draws two fractal-curve-designs: (1) A hilbert curve (in a box) (2) A combination of Koch-curves. The CurvesTurtle class and the fractal-curve- methods are taken from the PythonCard example scripts for turtle-graphics. i(t*(tsleeptclockt CurvesTurtlecBs#eZdZdZdZRS(cCs|dkrdS|j|d|j||d| |j||j|d|j||d||j||j||d||j|d|j||j||d| |j|ddS(NiiZi(tleftthilberttforwardtright(tselftsizetleveltparity((s7/usr/lib64/python2.7/Demo/turtle/tdemo_fractalcurves.pyRs    cCsddl}d||j|j|}|j|j||j|jdd|d|x8t|D]*}|j||||jd|quW|j dd|d||j|j ||jdS(NiiiiZih( tmathtsintpitputfdtpdtrttrangetfractaltlttbk(RtntradtlevtdirR tedgeti((s7/usr/lib64/python2.7/Demo/turtle/tdemo_fractalcurves.pyt fractalgon/s      cCs|dkr|j|dS|j|d|d||jd||j|d|d||jd||j|d|d||jd||j|d|d|dS(Niii<ix(RRRR(RtdisttdepthR((s7/usr/lib64/python2.7/Demo/turtle/tdemo_fractalcurves.pyRBs  (t__name__t __module__RRR(((s7/usr/lib64/python2.7/Demo/turtle/tdemo_fractalcurves.pyRs  cCsrt}|j|jd|j|jdd|jd}|jd|d||jt}|j d|j t |j ||j |dd|j |x:tdD],}|jd|j |d |d qW|jx.td D] }|j ||jdqW|jx:td D],}|j |d |d |jdqKW|j tt}d ||}td|j|jd|j|jddt}|jdd|j t |jddd d|j t |jd|jddd d|j tt}|d||7}|S(NiiiiitrediiZi@iiiBsHilbert: %.2fsec. tblacktblueiiisKoch: %.2fsec.(RtresettspeedthtttracerRtsetposRRt fillcolortfilltTrueRRRRRtFalseRtcolorR(tftR ttaRttbtres((s7/usr/lib64/python2.7/Demo/turtle/tdemo_fractalcurves.pytmainNsZ                           t__main__N( t__doc__tturtlettimeRRtPenRR3R tmsgtmainloop(((s7/usr/lib64/python2.7/Demo/turtle/tdemo_fractalcurves.pyt s = 8  PK%L]rTzturtle/tdemo_clock.pycnu[ Afc@sdZddlTddlmZddZdZdZdZd Zd Zd Z d Z d Z e dkre de ZeGHendS(s turtle-example-suite: tdemo_clock.py Enhanced clock-program, showing date and time ------------------------------------ Press STOP to exit the program! ------------------------------------ i(t*(tdatetimeicCs0tt|t|t|tdS(N(tpenuptrighttforwardtlefttpendown(tdistanztwinkel((s//usr/lib64/python2.7/Demo/turtle/tdemo_clock.pytjumps    cCsjt|dtdt|dtdt|tdt|tdt|ddS(Ngffffff?iZg@ix(tfdtrttlt(tlaengetspitze((s//usr/lib64/python2.7/Demo/turtle/tdemo_clock.pythands      cCsKtt| dtt||tt}t||dS(Ng333333?(tresetR t begin_polyRtend_polytget_polytregister_shape(tnameR Rt hand_form((s//usr/lib64/python2.7/Demo/turtle/tdemo_clock.pytmake_hand_shape"s  cCsttdxitdD][}t||ddkrZtdt| dntdt| tdqWdS(Nii<iiiii(RtpensizetrangeR R tdotR (tradiusti((s//usr/lib64/python2.7/Demo/turtle/tdemo_clock.pyt clockface+s     cCs2tdtdddtdddtdddtd tatjdtjd d tatjdtjd d tatjdtjddxDtttfD]3}|j d|j ddd|j dqWt ta t j t jt jddS(Ntlogot second_handi}it minute_handit hour_handiZitgray20tgray80tblue1tred1tblue3tred3tuseriiiiU(tmodeRRtTurtleRtshapetcolorR R!t resizemodet shapesizetspeedthttwritertputbk(R((s//usr/lib64/python2.7/Demo/turtle/tdemo_clock.pytsetup8s.            cCs)dddddddg}||jS(NtMondaytTuesdayt WednesdaytThursdaytFridaytSaturdaytSunday(tweekday(ttt wochentag((s//usr/lib64/python2.7/Demo/turtle/tdemo_clock.pyR>Ss c Cs^ddddddddd d d d g }|j}||jd }|j}d|||fS(NsJan.sFeb.sMar.sApr.tMaytJunetJulysAug.sSep.sOct.sNov.sDec.is%s %d %d(tyeartmonthtday(tztmonattjtmR=((s//usr/lib64/python2.7/Demo/turtle/tdemo_clock.pytdatumXs   cCs5tj}|j|jd}|j|d}|j|d}ytttj tj tj dtj t |ddddtjd tj t|ddddtj d tttjd |tjd |tjd |ttttdWntk r0nXdS(Ngư>gN@iAtaligntcentertfonttCourieritboldiiUiiid(RMiRN(RMiRN(Rttodaytsecondt microsecondtminutethourttracertFalseR1tclearthomeRtwriteR>tbackRItTrueRt setheadingR R!tontimerttickt Terminator(R=tsekundeRRtstunde((s//usr/lib64/python2.7/Demo/turtle/tdemo_clock.pyR]`s.            cCs&ttttttdS(Nt EVENTLOOP(RTRUR4RZR](((s//usr/lib64/python2.7/Demo/turtle/tdemo_clock.pytmainys   t__main__RN(t__doc__tturtleRR RRRR4R>RIR]Rbt__name__R)tmsgtmainloop(((s//usr/lib64/python2.7/Demo/turtle/tdemo_clock.pyt s           PK%L] p||$turtle/tdemo_I_dontlike_tiltdemo.pyonu[ Afc@sMdZddlTddlZdZedkrIeZeGHendS(s turtle-example-suite: tdemo-I_dont_like_tiltdemo.py Demonstrates (a) use of a tilted ellipse as turtle shape (b) stamping that shape We can remove it, if you don't like it. Without using reset() ;-) --------------------------------------- i(t*NcCsttdtdttddtdttdttdd d t d d x/t dD]!}t dt d t q|Wt d dx/t dD]!}t dt d t qWtdtdddt ddxBt dD]4}t dt d |ddkrt qqWtjdxtrotq\Wttddddd dS(!Ntcircletuseriigo!@iZi-ii itredtvioletitiiiitbluetyellowiiis OK, OVER!taligntcentertfonttCouriertboldsDone!i(R iR (tresettshapet resizemodetputbktrttpdttiltt turtlesizetcolortrangetfdtlttstampttimetsleeptundobufferentriestundothttwrite(ti((s=/usr/lib64/python2.7/Demo/turtle/tdemo_I_dontlike_tiltdemo.pytmainsD                   t__main__(t__doc__tturtleRR"t__name__tmsgtmainloop(((s=/usr/lib64/python2.7/Demo/turtle/tdemo_I_dontlike_tiltdemo.pyts   %  PK%L]%i((turtle/tdemo_yinyang.pyonu[ Afc@sCdZddlTdZdZedkr?eendS(s turtle-example-suite: tdemo_yinyang.py Another drawing suitable as a beginner's programming example. The small circles are drawn by the circle command. i(t*cCstdtdttt|ddt|dtdt| ddt|ttt|tdtt|dtdt t|dtdtt tt |dt tddS(Nitblackg@iiZg?g?( twidthtcolortfilltTruetcircletlefttuptforwardtrighttdowntFalsetbackward(tradiustcolor1tcolor2((s1/usr/lib64/python2.7/Demo/turtle/tdemo_yinyang.pytyins,            cCs2ttdddtdddtdS(NitwhiteRsDone!(tresetRtht(((s1/usr/lib64/python2.7/Demo/turtle/tdemo_yinyang.pytmain(s t__main__N(t__doc__tturtleRRt__name__tmainloop(((s1/usr/lib64/python2.7/Demo/turtle/tdemo_yinyang.pyt s     PK%L]^turtle/tdemo_chaos.pycnu[ ^c@syddlTdZdZdZdZdZdZdZd Zd Z e d krue e nd S( i(t*iPcCsd|d|S(Ng333333@i((tx((s//usr/lib64/python2.7/Demo/turtle/tdemo_chaos.pytf scCsd||dS(Ng333333@i((R((s//usr/lib64/python2.7/Demo/turtle/tdemo_chaos.pytgscCsd|d||S(Ng333333@((R((s//usr/lib64/python2.7/Demo/turtle/tdemo_chaos.pythscCstt||dS(N(tpenuptgoto(Rty((s//usr/lib64/python2.7/Demo/turtle/tdemo_chaos.pytjumptoscCs%t||tt||dS(N(RtpendownR(tx1ty1tx2ty2((s//usr/lib64/python2.7/Demo/turtle/tdemo_chaos.pytlines cCs.tddtddtdddddS(Niiigg?(RtN(((s//usr/lib64/python2.7/Demo/turtle/tdemo_chaos.pytcoosysscCspt||}td|ttdx;ttD]-}||}t|d|tdq;WdS(Niii(tpencolorRR tdottrangeRR(tfuntstarttcolorRti((s//usr/lib64/python2.7/Demo/turtle/tdemo_chaos.pytplot s    cCsttddtddtdttttddttddtt dd x/t d D]!}td |dtddqsWd S( Nggig?igffffff?tbluetgreentredidg?sDone!( tresettsetworldcoordinatesRtspeedt hideturtleRRRRRR(ts((s//usr/lib64/python2.7/Demo/turtle/tdemo_chaos.pytmain+s t__main__N( tturtleRRRRRRRRR!t__name__tmainloop(((s//usr/lib64/python2.7/Demo/turtle/tdemo_chaos.pyts         PK%L]z turtle/demohelp.txtnu[ ---------------------------------------------- turtleDemo - Help ---------------------------------------------- This document has two sections: (1) How to use the demo viewer (2) How to add your own demos to the demo repository (1) How to use the demo viewer. Select a demoscript from the example menu. The (syntax colored) source code appears in the left source code window. IT CANNOT BE EDITED, but ONLY VIEWED! - Press START button to start the demo. - Stop execution by pressing the STOP button. - Clear screen by pressing the CLEAR button. - Restart by pressing the START button again. SPECIAL demos are those which run EVENTDRIVEN. (For example clock.py - or oldTurtleDemo.py which in the end expects a mouse click.): Press START button to start the demo. - Until the EVENTLOOP is entered everything works as in an ordinary demo script. - When the EVENTLOOP is entered, you control the application by using the mouse and/or keys (or it's controlled by some timer events) To stop it you can and must press the STOP button. While the EVENTLOOP is running, the examples menu is disabled. - Only after having pressed the STOP button, you may restart it or choose another example script. * * * * * * * * In some rare situations there may occur interferences/conflicts between events concerning the demo script and those concerning the demo-viewer. (They run in the same process.) Strange behaviour may be the consequence and in the worst case you must close and restart the viewer. * * * * * * * * (2) How to add your own demos to the demo repository IMPORTANT! When imported, the demo should not modify the system by calling functions in other modules, such as sys, tkinter, or turtle. Global variables should be initialized in main(). - The script name must begin with tdemo_ , so it must have the form tdemo_.py - The code must contain a main() function which will be executed by the viewer (see provided example scripts). It may return a string which will be displayed in the Label below the source code window (when execution has finished.) - In order to run mydemo.py by itself, such as during development, add the following at the end of the file: if __name__ == '__main__': main() mainloop() # keep window python -m turtledemo.mydemo # will then run it - If the demo is EVENT DRIVEN, main must return the string "EVENTLOOP". This informs the demo viewer that the script is still running and must be stopped by the user! If an "EVENTLOOP" demo runs by itself, as with clock, which uses ontimer, or minimal_hanoi, which loops by recursion, then the code should catch the turtle.Terminator exception that will be raised when the user presses the STOP button. (Paint is not such a demo; it only acts in response to mouse clicks and movements.) PK%L]g#turtle/tdemo_lindenmayer_indian.pyonu[ Afc@sSdZddlTdZdZdZedkrOeZeGHendS(s turtle-example-suite: xtx_lindenmayer_indian.py Each morning women in Tamil Nadu, in southern India, place designs, created by using rice flour and known as kolam on the thresholds of their homes. These can be described by Lindenmayer systems, which can easily be implemented with turtle graphics and Python. Two examples are shown here: (1) the snake kolam (2) anklets of Krishna Taken from Marcia Ascher: Mathematics Elsewhere, An Exploration of Ideas Across Cultures i(t*cCsNxGt|D]9}d}x$|D]}||j||}q W|}q W|S(Nt(trangetget(tseqtreplacementRulestntitnewseqtelement((s</usr/lib64/python2.7/Demo/turtle/tdemo_lindenmayer_indian.pytreplaces   cCsWxP|D]H}y||Wqtk rNyt|||WqOqOXqXqWdS(N(t TypeErrortdraw(tcommandstrulestb((s</usr/lib64/python2.7/Demo/turtle/tdemo_lindenmayer_indian.pyR &s  cCsrd}d}d}i|d6|d6|d6dd6}id d6}d }t||d }ttd td d tttdtt||ddl m }|d d}d} d} i|d6| d6| d6} idd6dd6} d} ttd td d tt dt| | d }t|| td dS(NcSstddS(Ni-(tright(((s</usr/lib64/python2.7/Demo/turtle/tdemo_lindenmayer_indian.pytr7scSstddS(Ni-(tleft(((s</usr/lib64/python2.7/Demo/turtle/tdemo_lindenmayer_indian.pytl:scSstddS(Ng@(tforward(((s</usr/lib64/python2.7/Demo/turtle/tdemo_lindenmayer_indian.pytf=st-t+Rsf+f+f--f--f+f+fRsb+f+b--f--b+f+bs b--f--b--fiiiii(tsleepcSstdtdddS(Ntredi iZ(tcolortcircle(((s</usr/lib64/python2.7/Demo/turtle/tdemo_lindenmayer_indian.pytAVs cSsOddlm}tdd|d}t|t|dt|dS(Ni(tsqrttblackiii(tmathRRRR(RR((s</usr/lib64/python2.7/Demo/turtle/tdemo_lindenmayer_indian.pytBZs    cSstdtddS(Ntgreeni (RR(((s</usr/lib64/python2.7/Demo/turtle/tdemo_lindenmayer_indian.pytFbs tatafbfat afbfbfbfatfbfbfbfbi-sDone!( R tresettspeedttracerthttuptbackwardtdownR ttimeRR(RRRt snake_rulestsnake_replacementRulest snake_starttdrawingRRR R"t krishna_rulestkrishna_replacementRulest krishna_start((s</usr/lib64/python2.7/Demo/turtle/tdemo_lindenmayer_indian.pytmain1s@   "              t__main__N(t__doc__tturtleR R R6t__name__tmsgtmainloop(((s</usr/lib64/python2.7/Demo/turtle/tdemo_lindenmayer_indian.pyts   C  PK%L]/..turtle/about_turtledemo.txtnu[ -------------------------------------- About xturtleDemo.py -------------------------------------- Tiny demo Viewer to view turtle graphics example scripts. Quickly and dirtyly assembled by Gregor Lingl. June, 2006 For more information see: xturtleDemo - Help Have fun! PK%L]w[turtle/tdemo_wikipedia.pycnu[ ^c@srdZddlmZmZmZddlmZmZdZdZ e dkrne Z e GHendS(sF turtle-example-suite: tdemo_wikipedia3.py This example is inspired by the Wikipedia article on turtle graphics. (See example wikipedia1 for URLs) First we create (ne-1) (i.e. 35 in this example) copies of our first turtle p. Then we let them perform their steps in parallel. Followed by a complete undo(). i(tScreentTurtletmainloop(tclocktsleepcCs|g}xGtd|D]6}|j}|jd||j||}qWxvt|D]h}t|d||d}xC|D];}|jd||jd|d||j|qWq`WdS(Nigv@g@gffffff?i(trangetclonetrttappendtabstpencolortfd(tptnetszt turtlelisttitqtctt((s3/usr/lib64/python2.7/Demo/turtle/tdemo_wikipedia.pytmn_ecks     cCs t}|jdt}|jd|j|jd|jd|jddt}t |ddt}||}t dt}xPt g|j D]}|j ^qrx|j D]}|jqWqWt}d|||S( Ntblackitredii$iisLaufzeit: %.3f sec(RtbgcolorRtspeedt hideturtleR tpensizettracerRRRtanytturtlestundobufferentriestundo(tsR tattettz1R((s3/usr/lib64/python2.7/Demo/turtle/tdemo_wikipedia.pytmain$s&            . t__main__N( t__doc__tturtleRRRttimeRRRR$t__name__tmsg(((s3/usr/lib64/python2.7/Demo/turtle/tdemo_wikipedia.pyts    PK%L]uUccturtle/tdemo_two_canvases.pyonu[ ^c@sOdZddlmZmZmZdZedkrKeejndS(sturtledemo.two_canvases Use TurtleScreen and RawTurtle to draw on two distinct canvases in a separate windows. The new window must be separately closed in addition to pressing the STOP button. i(t TurtleScreent RawTurtletTKc Cstj}tj|dddddd}tj|dddddd}|j|jt|}|jddd t|}|jd ddt|}t|}|jd d|jd |jd d|jd x.||fD] }|j d |j dqW|j dx||fD]}|j q=WxEt dD]7}x.||fD] }|j d|j dqqWq^WxB||fD]4}|j|j d|j|jdqWdS(Ntwidthi,theightitbgs#ddffffs#ffeeeeg333333?itreditbluetturtlei$iii2iHi6t EVENTLOOP(ig333333?g333333?(g333333?g333333?i(RtTktCanvastpackRtbgcolorRtcolorRtshapetltt begin_filltrangetfdtend_filltputbk( troottcv1tcv2ts1ts2tptqttti((s6/usr/lib64/python2.7/Demo/turtle/tdemo_two_canvases.pytmain s> !!              t__main__N(t__doc__RRRRR t__name__tmainloop(((s6/usr/lib64/python2.7/Demo/turtle/tdemo_two_canvases.pyts  ) PK%L]F\turtle/tdemo_bytedesign.pycnu[ Afc@sdZddlZddlmZmZddlmZdefdYZdZe dkr{eZ e GHendS( s turtle-example-suite: tdemo_bytedesign.py An example adapted from the example-suite of PythonCard's turtle graphcis. It's based on an article in BYTE magazine Problem Solving with Logo: Using Turtle Graphics to Redraw a Design November 1982, p. 118 - 134 ------------------------------------------- Due to the statement t.delay(0) in line 152, which sets the animation delay to 0, this animation runs in "line per line" mode as fast as possible. iN(tTurtletmainloop(tclocktDesignercBsYeZdZdZdZdZdZdZdZdZ dZ RS( cCs|jxmtdD]_}|jd||j|j|j||j|jd||jdqW|j|j||jd|jd||jd|j|j d|d||j t dS( Nig)P@iHi$g8@ii.ga@( tuptrangetforwardtdowntwheeltpositiontbackwardtrighttgotot centerpiecettracertTrue(tselfthomePostscaleti((s4/usr/lib64/python2.7/Demo/turtle/tdemo_bytedesign.pytdesign!s         cCs|jdx$tdD]}|j||qW|j|jdx$tdD]}|j||qXW|jdxWtdD]I}|j|jd|jd||j|jd|qW|jd|j j dS(Ni6ii$iiHi( R Rt pentpieceRtleftttripieceRRR t getscreentupdate(RtinitposRR((s4/usr/lib64/python2.7/Demo/turtle/tdemo_bytedesign.pyR3s         cCs|j}|j|jd||jd|||j|j||j||j|jd||jd|||j|j||j||jd|j j dS(Ng@g?@iH( theadingRR ttripolyrRR t setheadingttripolylRRR(RRRtoldh((s4/usr/lib64/python2.7/Demo/turtle/tdemo_bytedesign.pyREs          cCsM|j}|j|jd||jx2tdD]$}|jd||jdq>W|jd|d||j|j||j||jd||jx2tdD]$}|jd||jdqW|j d|d||j|j||j||j d|j j dS(NiiiiHiK( RRRRRR tpentrR RtpentlRRR(RRRRR((s4/usr/lib64/python2.7/Demo/turtle/tdemo_bytedesign.pyRVs,           cCsM|d|krdS|j||j||j|d|||dS(NigRQ?(RRR!(RtsidetangR((s4/usr/lib64/python2.7/Demo/turtle/tdemo_bytedesign.pyR!ns   cCsM|d|krdS|j||j||j|d|||dS(NigRQ?(RR R (RR"R#R((s4/usr/lib64/python2.7/Demo/turtle/tdemo_bytedesign.pyR ts   cCs|d|krdS|j||jd|j|d|jd|j|d|jd|j|d|dS(Niiog{Gz?g?ig?(RR R(RR"R((s4/usr/lib64/python2.7/Demo/turtle/tdemo_bytedesign.pyRzs    cCs|d|krdS|j||jd|j|d|jd|j|d|jd|j|d|dS(Niiog{Gz?g?ig?(RRR(RR"R((s4/usr/lib64/python2.7/Demo/turtle/tdemo_bytedesign.pyRs    cCsM|j||j||d|kr.dS|j|d|||dS(Ng@g333333?(RRR (RtstaR((s4/usr/lib64/python2.7/Demo/turtle/tdemo_bytedesign.pyR s  ( t__name__t __module__RRRRR!R RRR (((s4/usr/lib64/python2.7/Demo/turtle/tdemo_bytedesign.pyRs       cCstt}|jd|j|jjd|jdt}|j|jdt}d||S(Niisruntime: %.2f sec.( Rtspeedt hideturtleRtdelayRRRR (tttattet((s4/usr/lib64/python2.7/Demo/turtle/tdemo_bytedesign.pytmains      t__main__( t__doc__tmathtturtleRRttimeRRR.R&tmsg(((s4/usr/lib64/python2.7/Demo/turtle/tdemo_bytedesign.pyts u  PK%L]3'vuuturtle/tdemo_penrose.pycnu[ Afc@sdZddlTddlmZmZddlmZmZddZd ed ed Z d Z d Z dZ dZ d dZdZdZdZdZddedd dZedZdZedkreZendS( s xturtle-example-suite: xtx_kites_and_darts.py Constructs two aperiodic penrose-tilings, consisting of kites and darts, by the method of inflation in six steps. Starting points are the patterns "sun" consisting of five kites and "star" consisting of five darts. For more information see: http://en.wikipedia.org/wiki/Penrose_tiling ------------------------------------------- i(t*(tcostpi(tclocktsleepig?ig@iii cCsht|}tdt|tdt|tdt|tdt|tddS(Ni$ili(tftlttfdtrt(tltfl((s1/usr/lib64/python2.7/Demo/turtle/tdemo_penrose.pytkites         cCsht|}tdt|tdt|tdt|tdt|tddS(Ni$i(RRRR(R R ((s1/usr/lib64/python2.7/Demo/turtle/tdemo_penrose.pytdart%s         cCs|dkrat\}}ttt|dt|d}}}tt|||fs(           PK%L]H}``turtle/tdemo_two_canvases.pynu["""turtledemo.two_canvases Use TurtleScreen and RawTurtle to draw on two distinct canvases in a separate windows. The new window must be separately closed in addition to pressing the STOP button. """ from turtle import TurtleScreen, RawTurtle, TK def main(): root = TK.Tk() cv1 = TK.Canvas(root, width=300, height=200, bg="#ddffff") cv2 = TK.Canvas(root, width=300, height=200, bg="#ffeeee") cv1.pack() cv2.pack() s1 = TurtleScreen(cv1) s1.bgcolor(0.85, 0.85, 1) s2 = TurtleScreen(cv2) s2.bgcolor(1, 0.85, 0.85) p = RawTurtle(s1) q = RawTurtle(s2) p.color("red", (1, 0.85, 0.85)) p.width(3) q.color("blue", (0.85, 0.85, 1)) q.width(3) for t in p,q: t.shape("turtle") t.lt(36) q.lt(180) for t in p, q: t.begin_fill() for i in range(5): for t in p, q: t.fd(50) t.lt(72) for t in p,q: t.end_fill() t.lt(54) t.pu() t.bk(50) return "EVENTLOOP" if __name__ == '__main__': main() TK.mainloop() # keep window open until user closes it PK%L]v 11#turtle/tdemo_I_dontlike_tiltdemo.pynuȯ#! /usr/bin/python2.7 """ turtle-example-suite: tdemo-I_dont_like_tiltdemo.py Demonstrates (a) use of a tilted ellipse as turtle shape (b) stamping that shape We can remove it, if you don't like it. Without using reset() ;-) --------------------------------------- """ from turtle import * import time def main(): reset() shape("circle") resizemode("user") pu(); bk(24*18/6.283); rt(90); pd() tilt(45) pu() turtlesize(16,10,5) color("red", "violet") for i in range(18): fd(24) lt(20) stamp() color("red", "") for i in range(18): fd(24) lt(20) stamp() tilt(-15) turtlesize(3, 1, 4) color("blue", "yellow") for i in range(17): fd(24) lt(20) if i%2 == 0: stamp() time.sleep(1) while undobufferentries(): undo() ht() write("OK, OVER!", align="center", font=("Courier", 18, "bold")) return "Done!" if __name__=="__main__": msg = main() print msg mainloop() PK%L]::turtle/tdemo_colormixer.pynu[# colormixer from turtle import Screen, Turtle, mainloop class ColorTurtle(Turtle): def __init__(self, x, y): Turtle.__init__(self) self.shape("turtle") self.resizemode("user") self.shapesize(3,3,5) self.pensize(10) self._color = [0,0,0] self.x = x self._color[x] = y self.color(self._color) self.speed(0) self.left(90) self.pu() self.goto(x,0) self.pd() self.sety(1) self.pu() self.sety(y) self.pencolor("gray25") self.ondrag(self.shift) def shift(self, x, y): self.sety(max(0,min(y,1))) self._color[self.x] = self.ycor() self.fillcolor(self._color) setbgcolor() def setbgcolor(): screen.bgcolor(red.ycor(), green.ycor(), blue.ycor()) def main(): global screen, red, green, blue screen = Screen() screen.delay(0) screen.setworldcoordinates(-1, -0.3, 3, 1.3) red = ColorTurtle(0, .5) green = ColorTurtle(1, .5) blue = ColorTurtle(2, .5) setbgcolor() writer = Turtle() writer.ht() writer.pu() writer.goto(1,1.15) writer.write("DRAG!",align="center",font=("Arial",30,("bold","italic"))) return "EVENTLOOP" if __name__ == "__main__": msg = main() print msg mainloop() PK%L]{Pturtle/tdemo_minimal_hanoi.pynuȯ#! /usr/bin/python2.7 """ turtle-example-suite: tdemo_minimal_hanoi.py A minimal 'Towers of Hanoi' animation: A tower of 6 discs is transferred from the left to the right peg. An imho quite elegant and concise implementation using a tower class, which is derived from the built-in type list. Discs are turtles with shape "square", but stretched to rectangles by shapesize() --------------------------------------- To exit press STOP button --------------------------------------- """ from turtle import * class Disc(Turtle): def __init__(self, n): Turtle.__init__(self, shape="square", visible=False) self.pu() self.shapesize(1.5, n*1.5, 2) # square-->rectangle self.fillcolor(n/6., 0, 1-n/6.) self.st() class Tower(list): "Hanoi tower, a subclass of built-in type list" def __init__(self, x): "create an empty tower. x is x-position of peg" self.x = x def push(self, d): d.setx(self.x) d.sety(-150+34*len(self)) self.append(d) def pop(self): d = list.pop(self) d.sety(150) return d def hanoi(n, from_, with_, to_): if n > 0: hanoi(n-1, from_, to_, with_) to_.push(from_.pop()) hanoi(n-1, with_, from_, to_) def play(): onkey(None,"space") clear() try: hanoi(6, t1, t2, t3) write("press STOP button to exit", align="center", font=("Courier", 16, "bold")) except Terminator: pass # turtledemo user pressed STOP def main(): global t1, t2, t3 ht(); penup(); goto(0, -225) # writer turtle t1 = Tower(-250) t2 = Tower(0) t3 = Tower(250) # make tower of 6 discs for i in range(6,0,-1): t1.push(Disc(i)) # prepare spartanic user interface ;-) write("press spacebar to start game", align="center", font=("Courier", 16, "bold")) onkey(play, "space") listen() return "EVENTLOOP" if __name__=="__main__": msg = main() print msg mainloop() PK%L]HB  turtle/tdemo_paint.pynuȯ#! /usr/bin/python2.7 """ turtle-example-suite: tdemo_paint.py A simple event-driven paint program - left mouse button moves turtle - middle mouse button changes color - right mouse button toogles betweem pen up (no line drawn when the turtle moves) and pen down (line is drawn). If pen up follows at least two pen-down moves, the polygon that includes the starting point is filled. ------------------------------------------- Play around by clicking into the canvas using all three mouse buttons. ------------------------------------------- To exit press STOP button ------------------------------------------- """ from turtle import * def switchupdown(x=0, y=0): if pen()["pendown"]: end_fill() up() else: down() begin_fill() def changecolor(x=0, y=0): global colors colors = colors[1:]+colors[:1] color(colors[0]) def main(): global colors shape("circle") resizemode("user") shapesize(.5) width(3) colors=["red", "green", "blue", "yellow"] color(colors[0]) switchupdown() onscreenclick(goto,1) onscreenclick(changecolor,2) onscreenclick(switchupdown,3) return "EVENTLOOP" if __name__ == "__main__": msg = main() print msg mainloop() PK%L]F\turtle/tdemo_bytedesign.pyonu[ Afc@sdZddlZddlmZmZddlmZdefdYZdZe dkr{eZ e GHendS( s turtle-example-suite: tdemo_bytedesign.py An example adapted from the example-suite of PythonCard's turtle graphcis. It's based on an article in BYTE magazine Problem Solving with Logo: Using Turtle Graphics to Redraw a Design November 1982, p. 118 - 134 ------------------------------------------- Due to the statement t.delay(0) in line 152, which sets the animation delay to 0, this animation runs in "line per line" mode as fast as possible. iN(tTurtletmainloop(tclocktDesignercBsYeZdZdZdZdZdZdZdZdZ dZ RS( cCs|jxmtdD]_}|jd||j|j|j||j|jd||jdqW|j|j||jd|jd||jd|j|j d|d||j t dS( Nig)P@iHi$g8@ii.ga@( tuptrangetforwardtdowntwheeltpositiontbackwardtrighttgotot centerpiecettracertTrue(tselfthomePostscaleti((s4/usr/lib64/python2.7/Demo/turtle/tdemo_bytedesign.pytdesign!s         cCs|jdx$tdD]}|j||qW|j|jdx$tdD]}|j||qXW|jdxWtdD]I}|j|jd|jd||j|jd|qW|jd|j j dS(Ni6ii$iiHi( R Rt pentpieceRtleftttripieceRRR t getscreentupdate(RtinitposRR((s4/usr/lib64/python2.7/Demo/turtle/tdemo_bytedesign.pyR3s         cCs|j}|j|jd||jd|||j|j||j||j|jd||jd|||j|j||j||jd|j j dS(Ng@g?@iH( theadingRR ttripolyrRR t setheadingttripolylRRR(RRRtoldh((s4/usr/lib64/python2.7/Demo/turtle/tdemo_bytedesign.pyREs          cCsM|j}|j|jd||jx2tdD]$}|jd||jdq>W|jd|d||j|j||j||jd||jx2tdD]$}|jd||jdqW|j d|d||j|j||j||j d|j j dS(NiiiiHiK( RRRRRR tpentrR RtpentlRRR(RRRRR((s4/usr/lib64/python2.7/Demo/turtle/tdemo_bytedesign.pyRVs,           cCsM|d|krdS|j||j||j|d|||dS(NigRQ?(RRR!(RtsidetangR((s4/usr/lib64/python2.7/Demo/turtle/tdemo_bytedesign.pyR!ns   cCsM|d|krdS|j||j||j|d|||dS(NigRQ?(RR R (RR"R#R((s4/usr/lib64/python2.7/Demo/turtle/tdemo_bytedesign.pyR ts   cCs|d|krdS|j||jd|j|d|jd|j|d|jd|j|d|dS(Niiog{Gz?g?ig?(RR R(RR"R((s4/usr/lib64/python2.7/Demo/turtle/tdemo_bytedesign.pyRzs    cCs|d|krdS|j||jd|j|d|jd|j|d|jd|j|d|dS(Niiog{Gz?g?ig?(RRR(RR"R((s4/usr/lib64/python2.7/Demo/turtle/tdemo_bytedesign.pyRs    cCsM|j||j||d|kr.dS|j|d|||dS(Ng@g333333?(RRR (RtstaR((s4/usr/lib64/python2.7/Demo/turtle/tdemo_bytedesign.pyR s  ( t__name__t __module__RRRRR!R RRR (((s4/usr/lib64/python2.7/Demo/turtle/tdemo_bytedesign.pyRs       cCstt}|jd|j|jjd|jdt}|j|jdt}d||S(Niisruntime: %.2f sec.( Rtspeedt hideturtleRtdelayRRRR (tttattet((s4/usr/lib64/python2.7/Demo/turtle/tdemo_bytedesign.pytmains      t__main__( t__doc__tmathtturtleRRttimeRRR.R&tmsg(((s4/usr/lib64/python2.7/Demo/turtle/tdemo_bytedesign.pyts u  PK%L]3'vuuturtle/tdemo_penrose.pyonu[ Afc@sdZddlTddlmZmZddlmZmZddZd ed ed Z d Z d Z dZ dZ d dZdZdZdZdZddedd dZedZdZedkreZendS( s xturtle-example-suite: xtx_kites_and_darts.py Constructs two aperiodic penrose-tilings, consisting of kites and darts, by the method of inflation in six steps. Starting points are the patterns "sun" consisting of five kites and "star" consisting of five darts. For more information see: http://en.wikipedia.org/wiki/Penrose_tiling ------------------------------------------- i(t*(tcostpi(tclocktsleepig?ig@iii cCsht|}tdt|tdt|tdt|tdt|tddS(Ni$ili(tftlttfdtrt(tltfl((s1/usr/lib64/python2.7/Demo/turtle/tdemo_penrose.pytkites         cCsht|}tdt|tdt|tdt|tdt|tddS(Ni$i(RRRR(R R ((s1/usr/lib64/python2.7/Demo/turtle/tdemo_penrose.pytdart%s         cCs|dkrat\}}ttt|dt|d}}}tt|||fs(           PK%L]:Bmmturtle/tdemo_paint.pyonu[ Afc@s_dZddlTdddZdddZdZedkr[eZeGHendS( sp turtle-example-suite: tdemo_paint.py A simple event-driven paint program - left mouse button moves turtle - middle mouse button changes color - right mouse button toogles betweem pen up (no line drawn when the turtle moves) and pen down (line is drawn). If pen up follows at least two pen-down moves, the polygon that includes the starting point is filled. ------------------------------------------- Play around by clicking into the canvas using all three mouse buttons. ------------------------------------------- To exit press STOP button ------------------------------------------- i(t*icCs0tdrttnttdS(Ntpendown(tpentend_filltuptdownt begin_fill(txty((s//usr/lib64/python2.7/Demo/turtle/tdemo_paint.pyt switchupdowns   cCs$tdtd attddS(Nii(tcolorstcolor(RR((s//usr/lib64/python2.7/Demo/turtle/tdemo_paint.pyt changecolor scCsztdtdtdtdddddgattd tttd tt d ttdd S( Ntcircletuserg?itredtgreentbluetyellowiiit EVENTLOOP( tshapet resizemodet shapesizetwidthR R R t onscreenclicktgotoR (((s//usr/lib64/python2.7/Demo/turtle/tdemo_paint.pytmain%s       t__main__N(t__doc__tturtleR R Rt__name__tmsgtmainloop(((s//usr/lib64/python2.7/Demo/turtle/tdemo_paint.pyts    PK%L]jN= = turtle/tdemo_colormixer.pyonu[ ^c@slddlmZmZmZdefdYZdZdZedkrheZeGHendS(i(tScreentTurtletmainloopt ColorTurtlecBseZdZdZRS(cCstj||jd|jd|jddd|jddddg|_||_||j|<|j|j|j d|j d|j |j |d|j |jd|j |j||jd |j|jdS( Ntturtletuseriii iiZitgray25(Rt__init__tshapet resizemodet shapesizetpensizet_colortxtcolortspeedtlefttputgototpdtsetytpencolortondragtshift(tselfR ty((s4/usr/lib64/python2.7/Demo/turtle/tdemo_colormixer.pyRs&              cCsP|jtdt|d|j|j|j<|j|jtdS(Nii(RtmaxtmintycorR R t fillcolort setbgcolor(RR R((s4/usr/lib64/python2.7/Demo/turtle/tdemo_colormixer.pyRs(t__name__t __module__RR(((s4/usr/lib64/python2.7/Demo/turtle/tdemo_colormixer.pyRs cCs)tjtjtjtjdS(N(tscreentbgcolortredRtgreentblue(((s4/usr/lib64/python2.7/Demo/turtle/tdemo_colormixer.pyR"sc Cstatjdtjddddtddatddatddatt }|j |j |j dd |j d d d d dddfdS(Niig333333ӿig?g?iigffffff?sDRAG!taligntcentertfonttArialitboldtitalict EVENTLOOP(R*R+(RR!tdelaytsetworldcoordinatesRR#R$R%RRthtRRtwrite(twriter((s4/usr/lib64/python2.7/Demo/turtle/tdemo_colormixer.pytmain%s     "t__main__N( RRRRRRR2Rtmsg(((s4/usr/lib64/python2.7/Demo/turtle/tdemo_colormixer.pyts    PK%L]uUccturtle/tdemo_two_canvases.pycnu[ ^c@sOdZddlmZmZmZdZedkrKeejndS(sturtledemo.two_canvases Use TurtleScreen and RawTurtle to draw on two distinct canvases in a separate windows. The new window must be separately closed in addition to pressing the STOP button. i(t TurtleScreent RawTurtletTKc Cstj}tj|dddddd}tj|dddddd}|j|jt|}|jddd t|}|jd ddt|}t|}|jd d|jd |jd d|jd x.||fD] }|j d |j dqW|j dx||fD]}|j q=WxEt dD]7}x.||fD] }|j d|j dqqWq^WxB||fD]4}|j|j d|j|jdqWdS(Ntwidthi,theightitbgs#ddffffs#ffeeeeg333333?itreditbluetturtlei$iii2iHi6t EVENTLOOP(ig333333?g333333?(g333333?g333333?i(RtTktCanvastpackRtbgcolorRtcolorRtshapetltt begin_filltrangetfdtend_filltputbk( troottcv1tcv2ts1ts2tptqttti((s6/usr/lib64/python2.7/Demo/turtle/tdemo_two_canvases.pytmain s> !!              t__main__N(t__doc__RRRRR t__name__tmainloop(((s6/usr/lib64/python2.7/Demo/turtle/tdemo_two_canvases.pyts  ) PK%L]iʈk'k'turtle/turtleDemo.pynuȯ#! /usr/bin/python2.7 import sys import os from Tkinter import * from idlelib.Percolator import Percolator from idlelib.ColorDelegator import ColorDelegator from idlelib.textView import view_file import turtle import time demo_dir = os.getcwd() if "turtleDemo.py" not in os.listdir(demo_dir): print "Directory of turtleDemo must be current working directory!" print "But in your case this is", demo_dir sys.exit() STARTUP = 1 READY = 2 RUNNING = 3 DONE = 4 EVENTDRIVEN = 5 menufont = ("Arial", 12, NORMAL) btnfont = ("Arial", 12, 'bold') txtfont = ('Lucida Console', 8, 'normal') def getExampleEntries(): entries1 = [entry for entry in os.listdir(demo_dir) if entry.startswith("tdemo_") and not entry.endswith(".pyc")] entries2 = [] for entry in entries1: if entry.endswith(".py"): entries2.append(entry) else: path = os.path.join(demo_dir, entry) sys.path.append(path) subdir = [entry] scripts = [script for script in os.listdir(path) if script.startswith("tdemo_") and script.endswith(".py")] entries2.append(subdir+scripts) return entries2 help_entries = ( # (help_label, help_file) ('Turtledemo help', "demohelp.txt"), ('About turtledemo', "about_turtledemo.txt"), ('About turtle module', "about_turtle.txt"), ) class DemoWindow(object): def __init__(self, filename=None): self.root = root = turtle._root = Tk() root.title('Python turtle-graphics examples') root.wm_protocol("WM_DELETE_WINDOW", self._destroy) root.grid_rowconfigure(1, weight=1) root.grid_columnconfigure(0, weight=1) root.grid_columnconfigure(1, minsize=90, weight=1) root.grid_columnconfigure(2, minsize=90, weight=1) root.grid_columnconfigure(3, minsize=90, weight=1) self.mBar = Frame(root, relief=RAISED, borderwidth=2) self.ExamplesBtn = self.makeLoadDemoMenu() self.OptionsBtn = self.makeHelpMenu() self.mBar.grid(row=0, columnspan=4, sticky='news') pane = PanedWindow(orient=HORIZONTAL, sashwidth=5, sashrelief=SOLID, bg='#ddd') pane.add(self.makeTextFrame(pane)) pane.add(self.makeGraphFrame(pane)) pane.grid(row=1, columnspan=4, sticky='news') self.output_lbl = Label(root, height= 1, text=" --- ", bg="#ddf", font=("Arial", 16, 'normal'), borderwidth=2, relief=RIDGE) self.start_btn = Button(root, text=" START ", font=btnfont, fg="white", disabledforeground = "#fed", command=self.startDemo) self.stop_btn = Button(root, text=" STOP ", font=btnfont, fg="white", disabledforeground = "#fed", command=self.stopIt) self.clear_btn = Button(root, text=" CLEAR ", font=btnfont, fg="white", disabledforeground="#fed", command = self.clearCanvas) self.output_lbl.grid(row=2, column=0, sticky='news', padx=(0,5)) self.start_btn.grid(row=2, column=1, sticky='ew') self.stop_btn.grid(row=2, column=2, sticky='ew') self.clear_btn.grid(row=2, column=3, sticky='ew') Percolator(self.text).insertfilter(ColorDelegator()) self.dirty = False self.exitflag = False if filename: self.loadfile(filename) self.configGUI(NORMAL, DISABLED, DISABLED, DISABLED, "Choose example from menu", "black") self.state = STARTUP def onResize(self, event): cwidth = self._canvas.winfo_width() cheight = self._canvas.winfo_height() self._canvas.xview_moveto(0.5*(self.canvwidth-cwidth)/self.canvwidth) self._canvas.yview_moveto(0.5*(self.canvheight-cheight)/self.canvheight) def makeTextFrame(self, root): self.text_frame = text_frame = Frame(root) self.text = text = Text(text_frame, name='text', padx=5, wrap='none', width=45) self.vbar = vbar = Scrollbar(text_frame, name='vbar') vbar['command'] = text.yview vbar.pack(side=LEFT, fill=Y) self.hbar = hbar = Scrollbar(text_frame, name='hbar', orient=HORIZONTAL) hbar['command'] = text.xview hbar.pack(side=BOTTOM, fill=X) text['font'] = txtfont text['yscrollcommand'] = vbar.set text['xscrollcommand'] = hbar.set text.pack(side=LEFT, fill=BOTH, expand=1) return text_frame def makeGraphFrame(self, root): turtle._Screen._root = root self.canvwidth = 1000 self.canvheight = 800 turtle._Screen._canvas = self._canvas = canvas = turtle.ScrolledCanvas( root, 800, 600, self.canvwidth, self.canvheight) canvas.adjustScrolls() canvas._rootwindow.bind('', self.onResize) canvas._canvas['borderwidth'] = 0 self.screen = _s_ = turtle.Screen() turtle.TurtleScreen.__init__(_s_, _s_._canvas) self.scanvas = _s_._canvas turtle.RawTurtle.screens = [_s_] return canvas def configGUI(self, menu, start, stop, clear, txt="", color="blue"): self.ExamplesBtn.config(state=menu) self.start_btn.config(state=start, bg="#d00" if start == NORMAL else "#fca") self.stop_btn.config(state=stop, bg="#d00" if stop == NORMAL else "#fca") self.clear_btn.config(state=clear, bg="#d00" if clear == NORMAL else"#fca") self.output_lbl.config(text=txt, fg=color) def makeLoadDemoMenu(self): CmdBtn = Menubutton(self.mBar, text='Examples', underline=0, font=menufont) CmdBtn.pack(side=LEFT, padx="2m") CmdBtn.menu = Menu(CmdBtn) for entry in getExampleEntries(): def loadexample(x): def emit(): self.loadfile(x) return emit if isinstance(entry,str): CmdBtn.menu.add_command(label=entry[6:-3], underline=0, font=menufont, command=loadexample(entry)) else: _dir, entries = entry[0], entry[1:] CmdBtn.menu.choices = Menu(CmdBtn.menu) for e in entries: CmdBtn.menu.choices.add_command( label=e[6:-3], underline=0, font=menufont, command = loadexample(os.path.join(_dir,e))) CmdBtn.menu.add_cascade( label=_dir[6:], menu = CmdBtn.menu.choices, font=menufont) CmdBtn['menu'] = CmdBtn.menu return CmdBtn def makeHelpMenu(self): CmdBtn = Menubutton(self.mBar, text='Help', underline=0, font = menufont) CmdBtn.pack(side=LEFT, padx='2m') CmdBtn.menu = Menu(CmdBtn) for help_label, help_file in help_entries: def show(help_label=help_label, help_file=help_file): view_file(self.root, help_label, os.path.join(demo_dir, help_file)) CmdBtn.menu.add_command(label=help_label, font=menufont, command=show) CmdBtn['menu'] = CmdBtn.menu return CmdBtn def refreshCanvas(self): if not self.dirty: return self.screen.clear() self.dirty=False def loadfile(self,filename): self.refreshCanvas() if os.path.exists(filename) and not os.path.isdir(filename): # load and display file text f = open(filename,'r') chars = f.read() f.close() self.text.delete("1.0", "end") self.text.insert("1.0",chars) direc, fname = os.path.split(filename) self.root.title(fname[6:-3]+" - a Python turtle graphics example") self.module = __import__(fname[:-3]) self.configGUI(NORMAL, NORMAL, DISABLED, DISABLED, "Press start button", "red") self.state = READY def startDemo(self): self.refreshCanvas() self.dirty = True turtle.TurtleScreen._RUNNING = True self.configGUI(DISABLED, DISABLED, NORMAL, DISABLED, "demo running...", "black") self.screen.clear() self.screen.mode("standard") self.state = RUNNING try: result = self.module.main() if result == "EVENTLOOP": self.state = EVENTDRIVEN else: self.state = DONE except turtle.Terminator: if self.root is None: return self.state = DONE result = "stopped!" if self.state == DONE: self.configGUI(NORMAL, NORMAL, DISABLED, NORMAL, result) elif self.state == EVENTDRIVEN: self.exitflag = True self.configGUI(DISABLED, DISABLED, NORMAL, DISABLED, "use mouse/keys or STOP", "red") def clearCanvas(self): self.refreshCanvas() self.scanvas.config(cursor="") self.configGUI(NORMAL, NORMAL, DISABLED, DISABLED) def stopIt(self): if self.exitflag: self.clearCanvas() self.exitflag = False self.configGUI(NORMAL, NORMAL, DISABLED, DISABLED, "STOPPED!", "red") turtle.TurtleScreen._RUNNING = False else: turtle.TurtleScreen._RUNNING = False def _destroy(self): turtle.TurtleScreen._RUNNING = False self.root.destroy() self.root = None #sys.exit() def main(): demo = DemoWindow() demo.root.mainloop() if __name__ == '__main__': main() PK%L]ʏ turtle/tdemo_penrose.pynuȯ#! /usr/bin/python2.7 """ xturtle-example-suite: xtx_kites_and_darts.py Constructs two aperiodic penrose-tilings, consisting of kites and darts, by the method of inflation in six steps. Starting points are the patterns "sun" consisting of five kites and "star" consisting of five darts. For more information see: http://en.wikipedia.org/wiki/Penrose_tiling ------------------------------------------- """ from turtle import * from math import cos, pi from time import clock, sleep f = (5**0.5-1)/2.0 # (sqrt(5)-1)/2 -- golden ratio d = 2 * cos(3*pi/10) def kite(l): fl = f * l lt(36) fd(l) rt(108) fd(fl) rt(36) fd(fl) rt(108) fd(l) rt(144) def dart(l): fl = f * l lt(36) fd(l) rt(144) fd(fl) lt(36) fd(fl) rt(144) fd(l) rt(144) def inflatekite(l, n): if n == 0: px, py = pos() h, x, y = int(heading()), round(px,3), round(py,3) tiledict[(h,x,y)] = True return fl = f * l lt(36) inflatedart(fl, n-1) fd(l) rt(144) inflatekite(fl, n-1) lt(18) fd(l*d) rt(162) inflatekite(fl, n-1) lt(36) fd(l) rt(180) inflatedart(fl, n-1) lt(36) def inflatedart(l, n): if n == 0: px, py = pos() h, x, y = int(heading()), round(px,3), round(py,3) tiledict[(h,x,y)] = False return fl = f * l inflatekite(fl, n-1) lt(36) fd(l) rt(180) inflatedart(fl, n-1) lt(54) fd(l*d) rt(126) inflatedart(fl, n-1) fd(l) rt(144) def draw(l, n, th=2): clear() l = l * f**n shapesize(l/100.0, l/100.0, th) for k in tiledict: h, x, y = k setpos(x, y) setheading(h) if tiledict[k]: shape("kite") color("black", (0, 0.75, 0)) else: shape("dart") color("black", (0.75, 0, 0)) stamp() def sun(l, n): for i in range(5): inflatekite(l, n) lt(72) def star(l,n): for i in range(5): inflatedart(l, n) lt(72) def makeshapes(): tracer(0) begin_poly() kite(100) end_poly() register_shape("kite", get_poly()) begin_poly() dart(100) end_poly() register_shape("dart", get_poly()) tracer(1) def start(): reset() ht() pu() makeshapes() resizemode("user") def test(l=200, n=4, fun=sun, startpos=(0,0), th=2): global tiledict goto(startpos) setheading(0) tiledict = {} a = clock() tracer(0) fun(l, n) b = clock() draw(l, n, th) tracer(1) c = clock() print "Calculation: %7.4f s" % (b - a) print "Drawing: %7.4f s" % (c - b) print "Together: %7.4f s" % (c - a) nk = len([x for x in tiledict if tiledict[x]]) nd = len([x for x in tiledict if not tiledict[x]]) print "%d kites and %d darts = %d pieces." % (nk, nd, nk+nd) def demo(fun=sun): start() for i in range(8): a = clock() test(300, i, fun) b = clock() t = b - a if t < 2: sleep(2 - t) def main(): #title("Penrose-tiling with kites and darts.") mode("logo") bgcolor(0.3, 0.3, 0) demo(sun) sleep(2) demo(star) pencolor("black") goto(0,-200) pencolor(0.7,0.7,1) write("Please wait...", align="center", font=('Arial Black', 36, 'bold')) test(600, 8, startpos=(70, 117)) return "Done" if __name__ == "__main__": msg = main() mainloop() PK%L]ؿy turtle/about_turtle.txtnu[ ======================================================== A new turtle module for Python ======================================================== Turtle graphics is a popular way for introducing programming to kids. It was part of the original Logo programming language developed by Wally Feurzig and Seymour Papert in 1966. Imagine a robotic turtle starting at (0, 0) in the x-y plane. After an ``import turtle``, give it the command turtle.forward(15), and it moves (on-screen!) 15 pixels in the direction it is facing, drawing a line as it moves. Give it the command turtle.right(25), and it rotates in-place 25 degrees clockwise. By combining together these and similar commands, intricate shapes and pictures can easily be drawn. ----- turtle.py This module is an extended reimplementation of turtle.py from the Python standard distribution up to Python 2.5. (See: http:\\www.python.org) It tries to keep the merits of turtle.py and to be (nearly) 100% compatible with it. This means in the first place to enable the learning programmer to use all the commands, classes and methods interactively when using the module from within IDLE run with the -n switch. Roughly it has the following features added: - Better animation of the turtle movements, especially of turning the turtle. So the turtles can more easily be used as a visual feedback instrument by the (beginning) programmer. - Different turtle shapes, gif-images as turtle shapes, user defined and user controllable turtle shapes, among them compound (multicolored) shapes. Turtle shapes can be stgretched and tilted, which makes turtles zu very versatile geometrical objects. - Fine control over turtle movement and screen updates via delay(), and enhanced tracer() and speed() methods. - Aliases for the most commonly used commands, like fd for forward etc., following the early Logo traditions. This reduces the boring work of typing long sequences of commands, which often occur in a natural way when kids try to program fancy pictures on their first encounter with turtle graphcis. - Turtles now have an undo()-method with configurable undo-buffer. - Some simple commands/methods for creating event driven programs (mouse-, key-, timer-events). Especially useful for programming games. - A scrollable Canvas class. The default scrollable Canvas can be extended interactively as needed while playing around with the turtle(s). - A TurtleScreen class with methods controlling background color or background image, window and canvas size and other properties of the TurtleScreen. - There is a method, setworldcoordinates(), to install a user defined coordinate-system for the TurtleScreen. - The implementation uses a 2-vector class named Vec2D, derived from tuple. This class is public, so it can be imported by the application programmer, which makes certain types of computations very natural and compact. - Appearance of the TurtleScreen and the Turtles at startup/import can be configured by means of a turtle.cfg configuration file. The default configuration mimics the appearance of the old turtle module. - If configured appropriately the module reads in docstrings from a docstring dictionary in some different language, supplied separately and replaces the english ones by those read in. There is a utility function write_docstringdict() to write a dictionary with the original (english) docstrings to disc, so it can serve as a template for translations. PK%L]}W$$turtle/tdemo_nim.pycnu[ ^c@s5dZddlZddlZddlZdZdZdZdZedZeedd edd Z dZ dZ dZ dZ dZdZdefdYZdejfdYZdefdYZdefdYZdefdYZdZedkr1eejndS( s turtle-example-suite: tdemo_nim.py Play nim against the computer. The player who takes the last stick is the winner. Implements the model-view-controller design pattern. iNiiiii ii ii?iicCstjttS(N(trandomtrandintt MINSTICKSt MAXSTICKS(((s-/usr/lib64/python2.7/Demo/turtle/tdemo_nim.pyt randomrowscCsy|d|dA|dA}|dkr0t|SxBtdD]4}|||A}|||kr=||f}|Sq=WdS(Niiii(t randommovetrange(tstatetxoredtztstmove((s-/usr/lib64/python2.7/Demo/turtle/tdemo_nim.pyt computerzug!s   cCsot|}x6trDtjdd}|||dkkrPqqWtj|dk||d}||fS(Niii(tmaxtTrueRR(RtmR trand((s-/usr/lib64/python2.7/Demo/turtle/tdemo_nim.pyR+s   tNimModelcBs5eZdZdZdZdZdZRS(cCs ||_dS(N(tgame(tselfR((s-/usr/lib64/python2.7/Demo/turtle/tdemo_nim.pyt__init__6scCsr|jjtjtjgkr"dStttg|_d|_d|_ |jj j tj |j_dS(Ni( RRtNimtCREATEDtOVERRtstickstplayertNonetwinnertviewtsetuptRUNNING(R((s-/usr/lib64/python2.7/Demo/turtle/tdemo_nim.pyR9s  cCs|j|}||j|<|jjj||||j|jrstj|j_|j|_ |jjj nI|jdkrd|_t |j\}}|j ||d|_ndS(Nii( RRRt notify_moveRt game_overRRRRt notify_overR R (Rtrowtcolt maxspalte((s-/usr/lib64/python2.7/Demo/turtle/tdemo_nim.pyR Bs     cCs|jdddgkS(Ni(R(R((s-/usr/lib64/python2.7/Demo/turtle/tdemo_nim.pyR PscCs+|j||krdS|j||dS(N(RR (RR"R#((s-/usr/lib64/python2.7/Demo/turtle/tdemo_nim.pyRSs(t__name__t __module__RRR R R(((s-/usr/lib64/python2.7/Demo/turtle/tdemo_nim.pyR5s    tStickcBs#eZdZdZdZRS(cCstjj|dt||_||_||_|j||\}}|jd|j t dt d|j d|j |j|||jd|jdS(Ntvisibletsquareg$@g4@itwhite(tturtletTurtleRtFalseR"R#Rtcoordstshapet shapesizetHUNITtWUNITtspeedtputgototcolort showturtle(RR"R#Rtxty((s-/usr/lib64/python2.7/Demo/turtle/tdemo_nim.pyRZs       cCskt|d\}}dd|d|t}dd|t}|tdtdtd|tdfS(Niii i(tdivmodR2R1t SCREENWIDTHt SCREENHEIGHT(RR"R#tpackett remainderR8R9((s-/usr/lib64/python2.7/Demo/turtle/tdemo_nim.pyR.hscCs9|jjtjkrdS|jjj|j|jdS(N(RRRRt controllerRR"R#(RR8R9((s-/usr/lib64/python2.7/Demo/turtle/tdemo_nim.pytmakemovens(R%R&RR.R@(((s-/usr/lib64/python2.7/Demo/turtle/tdemo_nim.pyR'Ys  tNimViewcBsAeZdZddZdZdZdZdZRS(cCs||_|j|_|j|_|jjd|jjt|jjdtjdt|_ |j j |j j di|_ xJt dD]<}x3t tD]%}t||||j ||f s0      $E  PK%L]:8''turtle/tdemo_yinyang.pynuȯ#! /usr/bin/python2.7 """ turtle-example-suite: tdemo_yinyang.py Another drawing suitable as a beginner's programming example. The small circles are drawn by the circle command. """ from turtle import * def yin(radius, color1, color2): width(3) color("black") fill(True) circle(radius/2., 180) circle(radius, 180) left(180) circle(-radius/2., 180) color(color1) fill(True) color(color2) left(90) up() forward(radius*0.375) right(90) down() circle(radius*0.125) left(90) fill(False) up() backward(radius*0.375) down() left(90) def main(): reset() yin(200, "white", "black") yin(200, "black", "white") ht() return "Done!" if __name__ == '__main__': main() mainloop() PK%L]8Hw**turtle/turtleDemo.pycnu[ Afc@s0ddlZddlZddlTddlmZddlmZddlmZddl Z ddl Z ej Z dej e krdGHdGe GHejnd Zd Zd Zd Zd ZddefZdZd ZdZd!d"d#fZdefdYZdZedkr,endS($iN(t*(t Percolator(tColorDelegator(t view_files turtleDemo.pys:Directory of turtleDemo must be current working directory!sBut in your case this isiiiiitAriali tboldsLucida ConsoleitnormalcCsgtjtD]+}|jdr|jd r|^q}g}x|D]}|jdrs|j|qNtjjt|}tjj||g}gtj|D]*}|jdr|jdr|^q}|j||qNW|S(Nttdemo_s.pycs.py( tostlistdirtdemo_dirt startswithtendswithtappendtpathtjointsys(tentrytentries1tentries2Rtsubdirtscripttscripts((s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pytgetExampleEntriess  sTurtledemo helps demohelp.txtsAbout turtledemosabout_turtledemo.txtsAbout turtle modulesabout_turtle.txtt DemoWindowcBseZddZdZdZdZdddZdZdZ d Z d Z d Z d Z d ZdZRS(cCst|_}t_|jd|jd|j|jddd|jddd|jddddd|jddddd|jd ddddt |d t d d|_ |j |_ |j|_|j jd dd dddtdtdddtdd}|j|j||j|j||jd dd dddt|dddddddd,d dd t|_t|dddtd d!d"d#d$|j|_t|dd%dtd d!d"d#d$|j|_t|dd&dtd d!d"d#d$|j |_!|jjd dd'dddd(d-|jjd dd'ddd)|jjd dd'ddd)|j!jd dd'd dd)t"|j#j$t%t&|_'t&|_(|r|j)|n|j*t+t,t,t,d*d+t-|_.dS(.NsPython turtle-graphics examplestWM_DELETE_WINDOWitweightitminsizeiZiitrelieft borderwidthtrowt columnspanitstickytnewstorientt sashwidthit sashrelieftbgs#dddtheightttexts --- s#ddftfontRiRs START tfgtwhitetdisabledforegrounds#fedtcommands STOP s CLEAR tcolumntpadxtewsChoose example from menutblack(RiR(ii(/tTktroottturtlet_rootttitlet wm_protocolt_destroytgrid_rowconfiguretgrid_columnconfiguretFrametRAISEDtmBartmakeLoadDemoMenut ExamplesBtnt makeHelpMenut OptionsBtntgridt PanedWindowt HORIZONTALtSOLIDtaddt makeTextFrametmakeGraphFrametLabeltRIDGEt output_lbltButtontbtnfontt startDemot start_btntstopIttstop_btnt clearCanvast clear_btnRR't insertfilterRtFalsetdirtytexitflagtloadfilet configGUItNORMALtDISABLEDtSTARTUPtstate(tselftfilenameR2tpane((s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pyt__init__7sR      %   cCsf|jj}|jj}|jjd|j||j|jjd|j||jdS(Ng?(t_canvast winfo_widtht winfo_heightt xview_movetot canvwidtht yview_movetot canvheight(R]teventtcwidthtcheight((s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pytonResizehs"c Cst||_}t|dddddddd|_}t|dd |_}|j|d <|jd td t t|dd dt |_ }|j |d <|jd t d tt|d<|j|d<|j|d<|jd td tdd|S(NtnameR'R.itwraptnonetwidthi-tvbarR,tsidetfillthbarR"R(tyscrollcommandtxscrollcommandtexpandi(R:t text_frametTextR't ScrollbarRptyviewtpacktLEFTtYRCRstxviewtBOTTOMtXttxtfonttsettBOTH(R]R2RwR'RpRs((s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pyRFns     cCs|tj_d|_d|_tj|dd|j|jtj_|_}|j|jj d|j d|jdiR(R3t_ScreenR4ReRgtScrolledCanvasRat adjustScrollst _rootwindowtbindRktScreentscreent TurtleScreenR`tscanvast RawTurtletscreens(R]R2tcanvast_s_((s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pyRGs   ,   ttbluecCs|jjd||jjd|d|tkr7dnd|jjd|d|tkrbdnd|jjd|d|tkrdnd|jjd|d|dS(NR\R%s#d00s#fcaR'R)(R>tconfigRNRYRPRRRJ(R]tmenutstarttstoptclearttxttcolor((s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pyRXscsftjdddddt}|jdtddt||_x tD]}fd }t|t r|jj d |d d !dddtd ||qP|d|d}}t|j|j_ xR|D]J}|jj j d |d d !dddtd |t j j||qW|jjd |d d|jj dtqPW|j|d<|S(NR'tExamplest underlineiR(RqR.t2mcsfd}|S(NcsjdS(N(RW((R]tx(s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pytemits((RR(R](Rs./usr/lib64/python2.7/Demo/turtle/turtleDemo.pyt loadexamplestlabeliiR,iR(t MenubuttonR<tmenufontR{R|tMenuRRt isinstancetstrt add_commandtchoicesRRRt add_cascade(R]tCmdBtnRRt_dirtentrieste((R]s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pyR=s(   ! cstjdddddt}|jdtddt||_xHtD]@\}}||fd }|jjd |dtd |qMW|j|d <|S( NR'tHelpRiR(RqR.Rcs&tj|tjjt|dS(N(RR2RRRR (t help_labelt help_file(R](s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pytshowsRR,R( RR<RR{R|RRt help_entriesR(R]RRRR((R]s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pyR?s!# cCs'|js dS|jjt|_dS(N(RURRRT(R]((s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pyt refreshCanvass  cCs|jtjj|rtjj| rt|d}|j}|j|jj dd|jj d|tjj |\}}|j j |dd!dt|d |_|jttttddt|_ndS( Ntrs1.0tendiis# - a Python turtle graphics examplesPress start buttontred(RRRtexiststisdirtopentreadtcloseR'tdeletetinserttsplitR2R5t __import__tmoduleRXRYRZtREADYR\(R]R^tftcharstdirectfname((s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pyRWs %   cCs4|jt|_ttj_|jttttdd|j j |j j dt |_ y4|jj}|dkrt|_ n t|_ Wn6tjk r|jdkrdSt|_ d}nX|j tkr|jtttt|n7|j tkr0t|_|jttttddndS(Nsdemo running...R0tstandardt EVENTLOOPsstopped!suse mouse/keys or STOPR(RtTrueRUR3Rt_RUNNINGRXRZRYRRtmodetRUNNINGR\Rtmaint EVENTDRIVENtDONEt TerminatorR2tNoneRV(R]tresult((s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pyRMs2             cCs7|j|jjdd|jttttdS(NtcursorR(RRRRXRYRZ(R]((s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pyRQs cCsW|jrG|jt|_|jttttddttj_n ttj_dS(NsSTOPPED!R( RVRQRTRXRYRZR3RR(R]((s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pyROs    cCs&ttj_|jjd|_dS(N(RTR3RRR2tdestroyR(R]((s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pyR7s  N(t__name__t __module__RR`RkRFRGRXR=R?RRWRMRQROR7(((s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pyR5s 1         cCst}|jjdS(N(RR2tmainloop(tdemo((s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pyR s t__main__(Ri R(sLucida ConsoleiR(sTurtledemo helps demohelp.txt(sAbout turtledemosabout_turtledemo.txt(sAbout turtle modulesabout_turtle.txt(RRtTkintertidlelib.PercolatorRtidlelib.ColorDelegatorRtidlelib.textViewRR3ttimetgetcwdR R texitR[RRRRRYRRLRRRtobjectRRR(((s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pyts8            PK%L]Mkrrturtle/tdemo_nim.pynu[""" turtle-example-suite: tdemo_nim.py Play nim against the computer. The player who takes the last stick is the winner. Implements the model-view-controller design pattern. """ import turtle import random import time SCREENWIDTH = 640 SCREENHEIGHT = 480 MINSTICKS = 7 MAXSTICKS = 31 HUNIT = SCREENHEIGHT // 12 WUNIT = SCREENWIDTH // ((MAXSTICKS // 5) * 11 + (MAXSTICKS % 5) * 2) SCOLOR = (63, 63, 31) HCOLOR = (255, 204, 204) COLOR = (204, 204, 255) def randomrow(): return random.randint(MINSTICKS, MAXSTICKS) def computerzug(state): xored = state[0] ^ state[1] ^ state[2] if xored == 0: return randommove(state) for z in range(3): s = state[z] ^ xored if s <= state[z]: move = (z, s) return move def randommove(state): m = max(state) while True: z = random.randint(0,2) if state[z] > (m > 1): break rand = random.randint(m > 1, state[z]-1) return z, rand class NimModel(object): def __init__(self, game): self.game = game def setup(self): if self.game.state not in [Nim.CREATED, Nim.OVER]: return self.sticks = [randomrow(), randomrow(), randomrow()] self.player = 0 self.winner = None self.game.view.setup() self.game.state = Nim.RUNNING def move(self, row, col): maxspalte = self.sticks[row] self.sticks[row] = col self.game.view.notify_move(row, col, maxspalte, self.player) if self.game_over(): self.game.state = Nim.OVER self.winner = self.player self.game.view.notify_over() elif self.player == 0: self.player = 1 row, col = computerzug(self.sticks) self.move(row, col) self.player = 0 def game_over(self): return self.sticks == [0, 0, 0] def notify_move(self, row, col): if self.sticks[row] <= col: return self.move(row, col) class Stick(turtle.Turtle): def __init__(self, row, col, game): turtle.Turtle.__init__(self, visible=False) self.row = row self.col = col self.game = game x, y = self.coords(row, col) self.shape("square") self.shapesize(HUNIT/10.0, WUNIT/20.0) self.speed(0) self.pu() self.goto(x,y) self.color("white") self.showturtle() def coords(self, row, col): packet, remainder = divmod(col, 5) x = (3 + 11 * packet + 2 * remainder) * WUNIT y = (2 + 3 * row) * HUNIT return x - SCREENWIDTH // 2 + WUNIT // 2, SCREENHEIGHT // 2 - y - HUNIT // 2 def makemove(self, x, y): if self.game.state != Nim.RUNNING: return self.game.controller.notify_move(self.row, self.col) class NimView(object): def __init__(self, game): self.game = game self.screen = game.screen self.model = game.model self.screen.colormode(255) self.screen.tracer(False) self.screen.bgcolor((240, 240, 255)) self.writer = turtle.Turtle(visible=False) self.writer.pu() self.writer.speed(0) self.sticks = {} for row in range(3): for col in range(MAXSTICKS): self.sticks[(row, col)] = Stick(row, col, game) self.display("... a moment please ...") self.screen.tracer(True) def display(self, msg1, msg2=None): self.screen.tracer(False) self.writer.clear() if msg2 is not None: self.writer.goto(0, - SCREENHEIGHT // 2 + 48) self.writer.pencolor("red") self.writer.write(msg2, align="center", font=("Courier",18,"bold")) self.writer.goto(0, - SCREENHEIGHT // 2 + 20) self.writer.pencolor("black") self.writer.write(msg1, align="center", font=("Courier",14,"bold")) self.screen.tracer(True) def setup(self): self.screen.tracer(False) for row in range(3): for col in range(self.model.sticks[row]): self.sticks[(row, col)].color(SCOLOR) for row in range(3): for col in range(self.model.sticks[row], MAXSTICKS): self.sticks[(row, col)].color("white") self.display("Your turn! Click leftmost stick to remove.") self.screen.tracer(True) def notify_move(self, row, col, maxspalte, player): if player == 0: farbe = HCOLOR for s in range(col, maxspalte): self.sticks[(row, s)].color(farbe) else: self.display(" ... thinking ... ") time.sleep(0.5) self.display(" ... thinking ... aaah ...") farbe = COLOR for s in range(maxspalte-1, col-1, -1): time.sleep(0.2) self.sticks[(row, s)].color(farbe) self.display("Your turn! Click leftmost stick to remove.") def notify_over(self): if self.game.model.winner == 0: msg2 = "Congrats. You're the winner!!!" else: msg2 = "Sorry, the computer is the winner." self.display("To play again press space bar. To leave press ESC.", msg2) def clear(self): if self.game.state == Nim.OVER: self.screen.clear() class NimController(object): def __init__(self, game): self.game = game self.sticks = game.view.sticks self.BUSY = False for stick in self.sticks.values(): stick.onclick(stick.makemove) self.game.screen.onkey(self.game.model.setup, "space") self.game.screen.onkey(self.game.view.clear, "Escape") self.game.view.display("Press space bar to start game") self.game.screen.listen() def notify_move(self, row, col): if self.BUSY: return self.BUSY = True self.game.model.notify_move(row, col) self.BUSY = False class Nim(object): CREATED = 0 RUNNING = 1 OVER = 2 def __init__(self, screen): self.state = Nim.CREATED self.screen = screen self.model = NimModel(self) self.view = NimView(self) self.controller = NimController(self) def main(): mainscreen = turtle.Screen() mainscreen.mode("standard") mainscreen.setup(SCREENWIDTH, SCREENHEIGHT) nim = Nim(mainscreen) return "EVENTLOOP!" if __name__ == "__main__": main() turtle.mainloop() PK%L]pzzturtle/tdemo_bytedesign.pynuȯ#! /usr/bin/python2.7 """ turtle-example-suite: tdemo_bytedesign.py An example adapted from the example-suite of PythonCard's turtle graphcis. It's based on an article in BYTE magazine Problem Solving with Logo: Using Turtle Graphics to Redraw a Design November 1982, p. 118 - 134 ------------------------------------------- Due to the statement t.delay(0) in line 152, which sets the animation delay to 0, this animation runs in "line per line" mode as fast as possible. """ import math from turtle import Turtle, mainloop from time import clock # wrapper for any additional drawing routines # that need to know about each other class Designer(Turtle): def design(self, homePos, scale): self.up() for i in range(5): self.forward(64.65 * scale) self.down() self.wheel(self.position(), scale) self.up() self.backward(64.65 * scale) self.right(72) self.up() self.goto(homePos) self.right(36) self.forward(24.5 * scale) self.right(198) self.down() self.centerpiece(46 * scale, 143.4, scale) self.tracer(True) def wheel(self, initpos, scale): self.right(54) for i in range(4): self.pentpiece(initpos, scale) self.down() self.left(36) for i in range(5): self.tripiece(initpos, scale) self.left(36) for i in range(5): self.down() self.right(72) self.forward(28 * scale) self.up() self.backward(28 * scale) self.left(54) self.getscreen().update() def tripiece(self, initpos, scale): oldh = self.heading() self.down() self.backward(2.5 * scale) self.tripolyr(31.5 * scale, scale) self.up() self.goto(initpos) self.setheading(oldh) self.down() self.backward(2.5 * scale) self.tripolyl(31.5 * scale, scale) self.up() self.goto(initpos) self.setheading(oldh) self.left(72) self.getscreen().update() def pentpiece(self, initpos, scale): oldh = self.heading() self.up() self.forward(29 * scale) self.down() for i in range(5): self.forward(18 * scale) self.right(72) self.pentr(18 * scale, 75, scale) self.up() self.goto(initpos) self.setheading(oldh) self.forward(29 * scale) self.down() for i in range(5): self.forward(18 * scale) self.right(72) self.pentl(18 * scale, 75, scale) self.up() self.goto(initpos) self.setheading(oldh) self.left(72) self.getscreen().update() def pentl(self, side, ang, scale): if side < (2 * scale): return self.forward(side) self.left(ang) self.pentl(side - (.38 * scale), ang, scale) def pentr(self, side, ang, scale): if side < (2 * scale): return self.forward(side) self.right(ang) self.pentr(side - (.38 * scale), ang, scale) def tripolyr(self, side, scale): if side < (4 * scale): return self.forward(side) self.right(111) self.forward(side / 1.78) self.right(111) self.forward(side / 1.3) self.right(146) self.tripolyr(side * .75, scale) def tripolyl(self, side, scale): if side < (4 * scale): return self.forward(side) self.left(111) self.forward(side / 1.78) self.left(111) self.forward(side / 1.3) self.left(146) self.tripolyl(side * .75, scale) def centerpiece(self, s, a, scale): self.forward(s); self.left(a) if s < (7.5 * scale): return self.centerpiece(s - (1.2 * scale), a, scale) def main(): t = Designer() t.speed(0) t.hideturtle() t.getscreen().delay(0) t.tracer(0) at = clock() t.design(t.position(), 2) et = clock() return "runtime: %.2f sec." % (et-at) if __name__ == '__main__': msg = main() print msg mainloop() PK%L]%i((turtle/tdemo_yinyang.pycnu[ Afc@sCdZddlTdZdZedkr?eendS(s turtle-example-suite: tdemo_yinyang.py Another drawing suitable as a beginner's programming example. The small circles are drawn by the circle command. i(t*cCstdtdttt|ddt|dtdt| ddt|ttt|tdtt|dtdt t|dtdtt tt |dt tddS(Nitblackg@iiZg?g?( twidthtcolortfilltTruetcircletlefttuptforwardtrighttdowntFalsetbackward(tradiustcolor1tcolor2((s1/usr/lib64/python2.7/Demo/turtle/tdemo_yinyang.pytyins,            cCs2ttdddtdddtdS(NitwhiteRsDone!(tresetRtht(((s1/usr/lib64/python2.7/Demo/turtle/tdemo_yinyang.pytmain(s t__main__N(t__doc__tturtleRRt__name__tmainloop(((s1/usr/lib64/python2.7/Demo/turtle/tdemo_yinyang.pyt s     PK%L]ʭ turtle/tdemo_fractalcurves.pyonu[ Afc@smdZddlTddlmZmZdefdYZdZedkrieZ e GHe ndS( s& turtle-example-suite: tdemo_fractalCurves.py This program draws two fractal-curve-designs: (1) A hilbert curve (in a box) (2) A combination of Koch-curves. The CurvesTurtle class and the fractal-curve- methods are taken from the PythonCard example scripts for turtle-graphics. i(t*(tsleeptclockt CurvesTurtlecBs#eZdZdZdZRS(cCs|dkrdS|j|d|j||d| |j||j|d|j||d||j||j||d||j|d|j||j||d| |j|ddS(NiiZi(tleftthilberttforwardtright(tselftsizetleveltparity((s7/usr/lib64/python2.7/Demo/turtle/tdemo_fractalcurves.pyRs    cCsddl}d||j|j|}|j|j||j|jdd|d|x8t|D]*}|j||||jd|quW|j dd|d||j|j ||jdS(NiiiiZih( tmathtsintpitputfdtpdtrttrangetfractaltlttbk(RtntradtlevtdirR tedgeti((s7/usr/lib64/python2.7/Demo/turtle/tdemo_fractalcurves.pyt fractalgon/s      cCs|dkr|j|dS|j|d|d||jd||j|d|d||jd||j|d|d||jd||j|d|d|dS(Niii<ix(RRRR(RtdisttdepthR((s7/usr/lib64/python2.7/Demo/turtle/tdemo_fractalcurves.pyRBs  (t__name__t __module__RRR(((s7/usr/lib64/python2.7/Demo/turtle/tdemo_fractalcurves.pyRs  cCsrt}|j|jd|j|jdd|jd}|jd|d||jt}|j d|j t |j ||j |dd|j |x:tdD],}|jd|j |d |d qW|jx.td D] }|j ||jdqW|jx:td D],}|j |d |d |jdqKW|j tt}d ||}td|j|jd|j|jddt}|jdd|j t |jddd d|j t |jd|jddd d|j tt}|d||7}|S(NiiiiitrediiZi@iiiBsHilbert: %.2fsec. tblacktblueiiisKoch: %.2fsec.(RtresettspeedthtttracerRtsetposRRt fillcolortfilltTrueRRRRRtFalseRtcolorR(tftR ttaRttbtres((s7/usr/lib64/python2.7/Demo/turtle/tdemo_fractalcurves.pytmainNsZ                           t__main__N( t__doc__tturtlettimeRRtPenRR3R tmsgtmainloop(((s7/usr/lib64/python2.7/Demo/turtle/tdemo_fractalcurves.pyt s = 8  PK%L]S;Q Q turtle/tdemo_fractalcurves.pynuȯ#! /usr/bin/python2.7 """ turtle-example-suite: tdemo_fractalCurves.py This program draws two fractal-curve-designs: (1) A hilbert curve (in a box) (2) A combination of Koch-curves. The CurvesTurtle class and the fractal-curve- methods are taken from the PythonCard example scripts for turtle-graphics. """ from turtle import * from time import sleep, clock class CurvesTurtle(Pen): # example derived from # Turtle Geometry: The Computer as a Medium for Exploring Mathematics # by Harold Abelson and Andrea diSessa # p. 96-98 def hilbert(self, size, level, parity): if level == 0: return # rotate and draw first subcurve with opposite parity to big curve self.left(parity * 90) self.hilbert(size, level - 1, -parity) # interface to and draw second subcurve with same parity as big curve self.forward(size) self.right(parity * 90) self.hilbert(size, level - 1, parity) # third subcurve self.forward(size) self.hilbert(size, level - 1, parity) # fourth subcurve self.right(parity * 90) self.forward(size) self.hilbert(size, level - 1, -parity) # a final turn is needed to make the turtle # end up facing outward from the large square self.left(parity * 90) # Visual Modeling with Logo: A Structural Approach to Seeing # by James Clayson # Koch curve, after Helge von Koch who introduced this geometric figure in 1904 # p. 146 def fractalgon(self, n, rad, lev, dir): import math # if dir = 1 turn outward # if dir = -1 turn inward edge = 2 * rad * math.sin(math.pi / n) self.pu() self.fd(rad) self.pd() self.rt(180 - (90 * (n - 2) / n)) for i in range(n): self.fractal(edge, lev, dir) self.rt(360 / n) self.lt(180 - (90 * (n - 2) / n)) self.pu() self.bk(rad) self.pd() # p. 146 def fractal(self, dist, depth, dir): if depth < 1: self.fd(dist) return self.fractal(dist / 3, depth - 1, dir) self.lt(60 * dir) self.fractal(dist / 3, depth - 1, dir) self.rt(120 * dir) self.fractal(dist / 3, depth - 1, dir) self.lt(60 * dir) self.fractal(dist / 3, depth - 1, dir) def main(): ft = CurvesTurtle() ft.reset() ft.speed(0) ft.ht() ft.tracer(1,0) ft.pu() size = 6 ft.setpos(-33*size, -32*size) ft.pd() ta=clock() ft.fillcolor("red") ft.fill(True) ft.fd(size) ft.hilbert(size, 6, 1) # frame ft.fd(size) for i in range(3): ft.lt(90) ft.fd(size*(64+i%2)) ft.pu() for i in range(2): ft.fd(size) ft.rt(90) ft.pd() for i in range(4): ft.fd(size*(66+i%2)) ft.rt(90) ft.fill(False) tb=clock() res = "Hilbert: %.2fsec. " % (tb-ta) sleep(3) ft.reset() ft.speed(0) ft.ht() ft.tracer(1,0) ta=clock() ft.color("black", "blue") ft.fill(True) ft.fractalgon(3, 250, 4, 1) ft.fill(True) ft.color("red") ft.fractalgon(3, 200, 4, -1) ft.fill(False) tb=clock() res += "Koch: %.2fsec." % (tb-ta) return res if __name__ == '__main__': msg = main() print msg mainloop() PK%L]px  turtle/tdemo_planet_and_moon.pynuȯ#! /usr/bin/python2.7 """ turtle-example-suite: tdemo_planets_and_moon.py Gravitational system simulation using the approximation method from Feynman-lectures, p.9-8, using turtlegraphics. Example: heavy central body, light planet, very light moon! Planet has a circular orbit, moon a stable orbit around the planet. You can hold the movement temporarily by pressing the left mouse button with the mouse over the scrollbar of the canvas. """ from turtle import Shape, Turtle, mainloop, Vec2D as Vec from time import sleep G = 8 class GravSys(object): def __init__(self): self.planets = [] self.t = 0 self.dt = 0.01 def init(self): for p in self.planets: p.init() def start(self): for i in range(10000): self.t += self.dt for p in self.planets: p.step() class Star(Turtle): def __init__(self, m, x, v, gravSys, shape): Turtle.__init__(self, shape=shape) self.penup() self.m = m self.setpos(x) self.v = v gravSys.planets.append(self) self.gravSys = gravSys self.resizemode("user") self.pendown() def init(self): dt = self.gravSys.dt self.a = self.acc() self.v = self.v + 0.5*dt*self.a def acc(self): a = Vec(0,0) for planet in self.gravSys.planets: if planet != self: v = planet.pos()-self.pos() a += (G*planet.m/abs(v)**3)*v return a def step(self): dt = self.gravSys.dt self.setpos(self.pos() + dt*self.v) if self.gravSys.planets.index(self) != 0: self.setheading(self.towards(self.gravSys.planets[0])) self.a = self.acc() self.v = self.v + dt*self.a ## create compound yellow/blue turtleshape for planets def main(): s = Turtle() s.reset() s.tracer(0,0) s.ht() s.pu() s.fd(6) s.lt(90) s.begin_poly() s.circle(6, 180) s.end_poly() m1 = s.get_poly() s.begin_poly() s.circle(6,180) s.end_poly() m2 = s.get_poly() planetshape = Shape("compound") planetshape.addcomponent(m1,"orange") planetshape.addcomponent(m2,"blue") s.getscreen().register_shape("planet", planetshape) s.tracer(1,0) ## setup gravitational system gs = GravSys() sun = Star(1000000, Vec(0,0), Vec(0,-2.5), gs, "circle") sun.color("yellow") sun.shapesize(1.8) sun.pu() earth = Star(12500, Vec(210,0), Vec(0,195), gs, "planet") earth.pencolor("green") earth.shapesize(0.8) moon = Star(1, Vec(220,0), Vec(0,295), gs, "planet") moon.pencolor("blue") moon.shapesize(0.5) gs.init() gs.start() return "Done!" if __name__ == '__main__': main() mainloop() PK%L]Ag: "turtle/tdemo_lindenmayer_indian.pynuȯ#! /usr/bin/python2.7 """ turtle-example-suite: xtx_lindenmayer_indian.py Each morning women in Tamil Nadu, in southern India, place designs, created by using rice flour and known as kolam on the thresholds of their homes. These can be described by Lindenmayer systems, which can easily be implemented with turtle graphics and Python. Two examples are shown here: (1) the snake kolam (2) anklets of Krishna Taken from Marcia Ascher: Mathematics Elsewhere, An Exploration of Ideas Across Cultures """ ################################ # Mini Lindenmayer tool ############################### from turtle import * def replace( seq, replacementRules, n ): for i in range(n): newseq = "" for element in seq: newseq = newseq + replacementRules.get(element,element) seq = newseq return seq def draw( commands, rules ): for b in commands: try: rules[b]() except TypeError: try: draw(rules[b], rules) except: pass def main(): ################################ # Example 1: Snake kolam ################################ def r(): right(45) def l(): left(45) def f(): forward(7.5) snake_rules = {"-":r, "+":l, "f":f, "b":"f+f+f--f--f+f+f"} snake_replacementRules = {"b": "b+f+b--f--b+f+b"} snake_start = "b--f--b--f" drawing = replace(snake_start, snake_replacementRules, 3) reset() speed(3) tracer(1,0) ht() up() backward(195) down() draw(drawing, snake_rules) from time import sleep sleep(3) ################################ # Example 2: Anklets of Krishna ################################ def A(): color("red") circle(10,90) def B(): from math import sqrt color("black") l = 5/sqrt(2) forward(l) circle(l, 270) forward(l) def F(): color("green") forward(10) krishna_rules = {"a":A, "b":B, "f":F} krishna_replacementRules = {"a" : "afbfa", "b" : "afbfbfbfa" } krishna_start = "fbfbfbfb" reset() speed(0) tracer(3,0) ht() left(45) drawing = replace(krishna_start, krishna_replacementRules, 3) draw(drawing, krishna_rules) tracer(1) return "Done!" if __name__=='__main__': msg = main() print msg mainloop() PK%L]rTzturtle/tdemo_clock.pyonu[ Afc@sdZddlTddlmZddZdZdZdZd Zd Zd Z d Z d Z e dkre de ZeGHendS(s turtle-example-suite: tdemo_clock.py Enhanced clock-program, showing date and time ------------------------------------ Press STOP to exit the program! ------------------------------------ i(t*(tdatetimeicCs0tt|t|t|tdS(N(tpenuptrighttforwardtlefttpendown(tdistanztwinkel((s//usr/lib64/python2.7/Demo/turtle/tdemo_clock.pytjumps    cCsjt|dtdt|dtdt|tdt|tdt|ddS(Ngffffff?iZg@ix(tfdtrttlt(tlaengetspitze((s//usr/lib64/python2.7/Demo/turtle/tdemo_clock.pythands      cCsKtt| dtt||tt}t||dS(Ng333333?(tresetR t begin_polyRtend_polytget_polytregister_shape(tnameR Rt hand_form((s//usr/lib64/python2.7/Demo/turtle/tdemo_clock.pytmake_hand_shape"s  cCsttdxitdD][}t||ddkrZtdt| dntdt| tdqWdS(Nii<iiiii(RtpensizetrangeR R tdotR (tradiusti((s//usr/lib64/python2.7/Demo/turtle/tdemo_clock.pyt clockface+s     cCs2tdtdddtdddtdddtd tatjdtjd d tatjdtjd d tatjdtjddxDtttfD]3}|j d|j ddd|j dqWt ta t j t jt jddS(Ntlogot second_handi}it minute_handit hour_handiZitgray20tgray80tblue1tred1tblue3tred3tuseriiiiU(tmodeRRtTurtleRtshapetcolorR R!t resizemodet shapesizetspeedthttwritertputbk(R((s//usr/lib64/python2.7/Demo/turtle/tdemo_clock.pytsetup8s.            cCs)dddddddg}||jS(NtMondaytTuesdayt WednesdaytThursdaytFridaytSaturdaytSunday(tweekday(ttt wochentag((s//usr/lib64/python2.7/Demo/turtle/tdemo_clock.pyR>Ss c Cs^ddddddddd d d d g }|j}||jd }|j}d|||fS(NsJan.sFeb.sMar.sApr.tMaytJunetJulysAug.sSep.sOct.sNov.sDec.is%s %d %d(tyeartmonthtday(tztmonattjtmR=((s//usr/lib64/python2.7/Demo/turtle/tdemo_clock.pytdatumXs   cCs5tj}|j|jd}|j|d}|j|d}ytttj tj tj dtj t |ddddtjd tj t|ddddtj d tttjd |tjd |tjd |ttttdWntk r0nXdS(Ngư>gN@iAtaligntcentertfonttCourieritboldiiUiiid(RMiRN(RMiRN(Rttodaytsecondt microsecondtminutethourttracertFalseR1tclearthomeRtwriteR>tbackRItTrueRt setheadingR R!tontimerttickt Terminator(R=tsekundeRRtstunde((s//usr/lib64/python2.7/Demo/turtle/tdemo_clock.pyR]`s.            cCs&ttttttdS(Nt EVENTLOOP(RTRUR4RZR](((s//usr/lib64/python2.7/Demo/turtle/tdemo_clock.pytmainys   t__main__RN(t__doc__tturtleRR RRRR4R>RIR]Rbt__name__R)tmsgtmainloop(((s//usr/lib64/python2.7/Demo/turtle/tdemo_clock.pyt s           PK%L]j%))turtle/tdemo_peace.pynuȯ#! /usr/bin/python2.7 """ turtle-example-suite: tdemo_peace.py A simple drawing suitable as a beginner's programming example. Aside from the peacecolors assignment and the for loop, it only uses turtle commands. """ from turtle import * def main(): peacecolors = ("red3", "orange", "yellow", "seagreen4", "orchid4", "royalblue1", "dodgerblue4") reset() Screen() up() goto(-320,-195) width(70) for pcolor in peacecolors: color(pcolor) down() forward(640) up() backward(640) left(90) forward(66) right(90) width(25) color("white") goto(0,-170) down() circle(170) left(90) forward(340) up() left(180) forward(170) right(45) down() forward(170) up() backward(170) left(90) down() forward(170) up() goto(0,300) # vanish if hideturtle() is not available ;-) return "Done!" if __name__ == "__main__": main() mainloop() PK%L]8Hw**turtle/turtleDemo.pyonu[ Afc@s0ddlZddlZddlTddlmZddlmZddlmZddl Z ddl Z ej Z dej e krdGHdGe GHejnd Zd Zd Zd Zd ZddefZdZd ZdZd!d"d#fZdefdYZdZedkr,endS($iN(t*(t Percolator(tColorDelegator(t view_files turtleDemo.pys:Directory of turtleDemo must be current working directory!sBut in your case this isiiiiitAriali tboldsLucida ConsoleitnormalcCsgtjtD]+}|jdr|jd r|^q}g}x|D]}|jdrs|j|qNtjjt|}tjj||g}gtj|D]*}|jdr|jdr|^q}|j||qNW|S(Nttdemo_s.pycs.py( tostlistdirtdemo_dirt startswithtendswithtappendtpathtjointsys(tentrytentries1tentries2Rtsubdirtscripttscripts((s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pytgetExampleEntriess  sTurtledemo helps demohelp.txtsAbout turtledemosabout_turtledemo.txtsAbout turtle modulesabout_turtle.txtt DemoWindowcBseZddZdZdZdZdddZdZdZ d Z d Z d Z d Z d ZdZRS(cCst|_}t_|jd|jd|j|jddd|jddd|jddddd|jddddd|jd ddddt |d t d d|_ |j |_ |j|_|j jd dd dddtdtdddtdd}|j|j||j|j||jd dd dddt|dddddddd,d dd t|_t|dddtd d!d"d#d$|j|_t|dd%dtd d!d"d#d$|j|_t|dd&dtd d!d"d#d$|j |_!|jjd dd'dddd(d-|jjd dd'ddd)|jjd dd'ddd)|j!jd dd'd dd)t"|j#j$t%t&|_'t&|_(|r|j)|n|j*t+t,t,t,d*d+t-|_.dS(.NsPython turtle-graphics examplestWM_DELETE_WINDOWitweightitminsizeiZiitrelieft borderwidthtrowt columnspanitstickytnewstorientt sashwidthit sashrelieftbgs#dddtheightttexts --- s#ddftfontRiRs START tfgtwhitetdisabledforegrounds#fedtcommands STOP s CLEAR tcolumntpadxtewsChoose example from menutblack(RiR(ii(/tTktroottturtlet_rootttitlet wm_protocolt_destroytgrid_rowconfiguretgrid_columnconfiguretFrametRAISEDtmBartmakeLoadDemoMenut ExamplesBtnt makeHelpMenut OptionsBtntgridt PanedWindowt HORIZONTALtSOLIDtaddt makeTextFrametmakeGraphFrametLabeltRIDGEt output_lbltButtontbtnfontt startDemot start_btntstopIttstop_btnt clearCanvast clear_btnRR't insertfilterRtFalsetdirtytexitflagtloadfilet configGUItNORMALtDISABLEDtSTARTUPtstate(tselftfilenameR2tpane((s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pyt__init__7sR      %   cCsf|jj}|jj}|jjd|j||j|jjd|j||jdS(Ng?(t_canvast winfo_widtht winfo_heightt xview_movetot canvwidtht yview_movetot canvheight(R]teventtcwidthtcheight((s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pytonResizehs"c Cst||_}t|dddddddd|_}t|dd |_}|j|d <|jd td t t|dd dt |_ }|j |d <|jd t d tt|d<|j|d<|j|d<|jd td tdd|S(NtnameR'R.itwraptnonetwidthi-tvbarR,tsidetfillthbarR"R(tyscrollcommandtxscrollcommandtexpandi(R:t text_frametTextR't ScrollbarRptyviewtpacktLEFTtYRCRstxviewtBOTTOMtXttxtfonttsettBOTH(R]R2RwR'RpRs((s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pyRFns     cCs|tj_d|_d|_tj|dd|j|jtj_|_}|j|jj d|j d|jdiR(R3t_ScreenR4ReRgtScrolledCanvasRat adjustScrollst _rootwindowtbindRktScreentscreent TurtleScreenR`tscanvast RawTurtletscreens(R]R2tcanvast_s_((s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pyRGs   ,   ttbluecCs|jjd||jjd|d|tkr7dnd|jjd|d|tkrbdnd|jjd|d|tkrdnd|jjd|d|dS(NR\R%s#d00s#fcaR'R)(R>tconfigRNRYRPRRRJ(R]tmenutstarttstoptclearttxttcolor((s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pyRXscsftjdddddt}|jdtddt||_x tD]}fd }t|t r|jj d |d d !dddtd ||qP|d|d}}t|j|j_ xR|D]J}|jj j d |d d !dddtd |t j j||qW|jjd |d d|jj dtqPW|j|d<|S(NR'tExamplest underlineiR(RqR.t2mcsfd}|S(NcsjdS(N(RW((R]tx(s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pytemits((RR(R](Rs./usr/lib64/python2.7/Demo/turtle/turtleDemo.pyt loadexamplestlabeliiR,iR(t MenubuttonR<tmenufontR{R|tMenuRRt isinstancetstrt add_commandtchoicesRRRt add_cascade(R]tCmdBtnRRt_dirtentrieste((R]s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pyR=s(   ! cstjdddddt}|jdtddt||_xHtD]@\}}||fd }|jjd |dtd |qMW|j|d <|S( NR'tHelpRiR(RqR.Rcs&tj|tjjt|dS(N(RR2RRRR (t help_labelt help_file(R](s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pytshowsRR,R( RR<RR{R|RRt help_entriesR(R]RRRR((R]s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pyR?s!# cCs'|js dS|jjt|_dS(N(RURRRT(R]((s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pyt refreshCanvass  cCs|jtjj|rtjj| rt|d}|j}|j|jj dd|jj d|tjj |\}}|j j |dd!dt|d |_|jttttddt|_ndS( Ntrs1.0tendiis# - a Python turtle graphics examplesPress start buttontred(RRRtexiststisdirtopentreadtcloseR'tdeletetinserttsplitR2R5t __import__tmoduleRXRYRZtREADYR\(R]R^tftcharstdirectfname((s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pyRWs %   cCs4|jt|_ttj_|jttttdd|j j |j j dt |_ y4|jj}|dkrt|_ n t|_ Wn6tjk r|jdkrdSt|_ d}nX|j tkr|jtttt|n7|j tkr0t|_|jttttddndS(Nsdemo running...R0tstandardt EVENTLOOPsstopped!suse mouse/keys or STOPR(RtTrueRUR3Rt_RUNNINGRXRZRYRRtmodetRUNNINGR\Rtmaint EVENTDRIVENtDONEt TerminatorR2tNoneRV(R]tresult((s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pyRMs2             cCs7|j|jjdd|jttttdS(NtcursorR(RRRRXRYRZ(R]((s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pyRQs cCsW|jrG|jt|_|jttttddttj_n ttj_dS(NsSTOPPED!R( RVRQRTRXRYRZR3RR(R]((s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pyROs    cCs&ttj_|jjd|_dS(N(RTR3RRR2tdestroyR(R]((s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pyR7s  N(t__name__t __module__RR`RkRFRGRXR=R?RRWRMRQROR7(((s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pyR5s 1         cCst}|jjdS(N(RR2tmainloop(tdemo((s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pyR s t__main__(Ri R(sLucida ConsoleiR(sTurtledemo helps demohelp.txt(sAbout turtledemosabout_turtledemo.txt(sAbout turtle modulesabout_turtle.txt(RRtTkintertidlelib.PercolatorRtidlelib.ColorDelegatorRtidlelib.textViewRR3ttimetgetcwdR R texitR[RRRRRYRRLRRRtobjectRRR(((s./usr/lib64/python2.7/Demo/turtle/turtleDemo.pyts8            PK%L]Ĩkk rpc/rpc.pynu[# Sun RPC version 2 -- RFC1057. # XXX There should be separate exceptions for the various reasons why # XXX an RPC can fail, rather than using RuntimeError for everything # XXX Need to use class based exceptions rather than string exceptions # XXX The UDP version of the protocol resends requests when it does # XXX not receive a timely reply -- use only for idempotent calls! # XXX There is no provision for call timeout on TCP connections import xdr import socket import os RPCVERSION = 2 CALL = 0 REPLY = 1 AUTH_NULL = 0 AUTH_UNIX = 1 AUTH_SHORT = 2 AUTH_DES = 3 MSG_ACCEPTED = 0 MSG_DENIED = 1 SUCCESS = 0 # RPC executed successfully PROG_UNAVAIL = 1 # remote hasn't exported program PROG_MISMATCH = 2 # remote can't support version # PROC_UNAVAIL = 3 # program can't support procedure GARBAGE_ARGS = 4 # procedure can't decode params RPC_MISMATCH = 0 # RPC version number != 2 AUTH_ERROR = 1 # remote can't authenticate caller AUTH_BADCRED = 1 # bad credentials (seal broken) AUTH_REJECTEDCRED = 2 # client must begin new session AUTH_BADVERF = 3 # bad verifier (seal broken) AUTH_REJECTEDVERF = 4 # verifier expired or replayed AUTH_TOOWEAK = 5 # rejected for security reasons class Packer(xdr.Packer): def pack_auth(self, auth): flavor, stuff = auth self.pack_enum(flavor) self.pack_opaque(stuff) def pack_auth_unix(self, stamp, machinename, uid, gid, gids): self.pack_uint(stamp) self.pack_string(machinename) self.pack_uint(uid) self.pack_uint(gid) self.pack_uint(len(gids)) for i in gids: self.pack_uint(i) def pack_callheader(self, xid, prog, vers, proc, cred, verf): self.pack_uint(xid) self.pack_enum(CALL) self.pack_uint(RPCVERSION) self.pack_uint(prog) self.pack_uint(vers) self.pack_uint(proc) self.pack_auth(cred) self.pack_auth(verf) # Caller must add procedure-specific part of call def pack_replyheader(self, xid, verf): self.pack_uint(xid) self.pack_enum(REPLY) self.pack_uint(MSG_ACCEPTED) self.pack_auth(verf) self.pack_enum(SUCCESS) # Caller must add procedure-specific part of reply # Exceptions class BadRPCFormat(Exception): pass class BadRPCVersion(Exception): pass class GarbageArgs(Exception): pass class Unpacker(xdr.Unpacker): def unpack_auth(self): flavor = self.unpack_enum() stuff = self.unpack_opaque() return (flavor, stuff) def unpack_callheader(self): xid = self.unpack_uint() temp = self.unpack_enum() if temp != CALL: raise BadRPCFormat, 'no CALL but %r' % (temp,) temp = self.unpack_uint() if temp != RPCVERSION: raise BadRPCVersion, 'bad RPC version %r' % (temp,) prog = self.unpack_uint() vers = self.unpack_uint() proc = self.unpack_uint() cred = self.unpack_auth() verf = self.unpack_auth() return xid, prog, vers, proc, cred, verf # Caller must add procedure-specific part of call def unpack_replyheader(self): xid = self.unpack_uint() mtype = self.unpack_enum() if mtype != REPLY: raise RuntimeError, 'no REPLY but %r' % (mtype,) stat = self.unpack_enum() if stat == MSG_DENIED: stat = self.unpack_enum() if stat == RPC_MISMATCH: low = self.unpack_uint() high = self.unpack_uint() raise RuntimeError, \ 'MSG_DENIED: RPC_MISMATCH: %r' % ((low, high),) if stat == AUTH_ERROR: stat = self.unpack_uint() raise RuntimeError, \ 'MSG_DENIED: AUTH_ERROR: %r' % (stat,) raise RuntimeError, 'MSG_DENIED: %r' % (stat,) if stat != MSG_ACCEPTED: raise RuntimeError, \ 'Neither MSG_DENIED nor MSG_ACCEPTED: %r' % (stat,) verf = self.unpack_auth() stat = self.unpack_enum() if stat == PROG_UNAVAIL: raise RuntimeError, 'call failed: PROG_UNAVAIL' if stat == PROG_MISMATCH: low = self.unpack_uint() high = self.unpack_uint() raise RuntimeError, \ 'call failed: PROG_MISMATCH: %r' % ((low, high),) if stat == PROC_UNAVAIL: raise RuntimeError, 'call failed: PROC_UNAVAIL' if stat == GARBAGE_ARGS: raise RuntimeError, 'call failed: GARBAGE_ARGS' if stat != SUCCESS: raise RuntimeError, 'call failed: %r' % (stat,) return xid, verf # Caller must get procedure-specific part of reply # Subroutines to create opaque authentication objects def make_auth_null(): return '' def make_auth_unix(seed, host, uid, gid, groups): p = Packer() p.pack_auth_unix(seed, host, uid, gid, groups) return p.get_buf() def make_auth_unix_default(): try: from os import getuid, getgid uid = getuid() gid = getgid() except ImportError: uid = gid = 0 import time return make_auth_unix(int(time.time()-unix_epoch()), \ socket.gethostname(), uid, gid, []) _unix_epoch = -1 def unix_epoch(): """Very painful calculation of when the Unix Epoch is. This is defined as the return value of time.time() on Jan 1st, 1970, 00:00:00 GMT. On a Unix system, this should always return 0.0. On a Mac, the calculations are needed -- and hard because of integer overflow and other limitations. """ global _unix_epoch if _unix_epoch >= 0: return _unix_epoch import time now = time.time() localt = time.localtime(now) # (y, m, d, hh, mm, ss, ..., ..., ...) gmt = time.gmtime(now) offset = time.mktime(localt) - time.mktime(gmt) y, m, d, hh, mm, ss = 1970, 1, 1, 0, 0, 0 offset, ss = divmod(ss + offset, 60) offset, mm = divmod(mm + offset, 60) offset, hh = divmod(hh + offset, 24) d = d + offset _unix_epoch = time.mktime((y, m, d, hh, mm, ss, 0, 0, 0)) print "Unix epoch:", time.ctime(_unix_epoch) return _unix_epoch # Common base class for clients class Client: def __init__(self, host, prog, vers, port): self.host = host self.prog = prog self.vers = vers self.port = port self.makesocket() # Assigns to self.sock self.bindsocket() self.connsocket() self.lastxid = 0 # XXX should be more random? self.addpackers() self.cred = None self.verf = None def close(self): self.sock.close() def makesocket(self): # This MUST be overridden raise RuntimeError, 'makesocket not defined' def connsocket(self): # Override this if you don't want/need a connection self.sock.connect((self.host, self.port)) def bindsocket(self): # Override this to bind to a different port (e.g. reserved) self.sock.bind(('', 0)) def addpackers(self): # Override this to use derived classes from Packer/Unpacker self.packer = Packer() self.unpacker = Unpacker('') def make_call(self, proc, args, pack_func, unpack_func): # Don't normally override this (but see Broadcast) if pack_func is None and args is not None: raise TypeError, 'non-null args with null pack_func' self.start_call(proc) if pack_func: pack_func(args) self.do_call() if unpack_func: result = unpack_func() else: result = None self.unpacker.done() return result def start_call(self, proc): # Don't override this self.lastxid = xid = self.lastxid + 1 cred = self.mkcred() verf = self.mkverf() p = self.packer p.reset() p.pack_callheader(xid, self.prog, self.vers, proc, cred, verf) def do_call(self): # This MUST be overridden raise RuntimeError, 'do_call not defined' def mkcred(self): # Override this to use more powerful credentials if self.cred is None: self.cred = (AUTH_NULL, make_auth_null()) return self.cred def mkverf(self): # Override this to use a more powerful verifier if self.verf is None: self.verf = (AUTH_NULL, make_auth_null()) return self.verf def call_0(self): # Procedure 0 is always like this return self.make_call(0, None, None, None) # Record-Marking standard support def sendfrag(sock, last, frag): x = len(frag) if last: x = x | 0x80000000L header = (chr(int(x>>24 & 0xff)) + chr(int(x>>16 & 0xff)) + \ chr(int(x>>8 & 0xff)) + chr(int(x & 0xff))) sock.send(header + frag) def sendrecord(sock, record): sendfrag(sock, 1, record) def recvfrag(sock): header = sock.recv(4) if len(header) < 4: raise EOFError x = long(ord(header[0]))<<24 | ord(header[1])<<16 | \ ord(header[2])<<8 | ord(header[3]) last = ((x & 0x80000000) != 0) n = int(x & 0x7fffffff) frag = '' while n > 0: buf = sock.recv(n) if not buf: raise EOFError n = n - len(buf) frag = frag + buf return last, frag def recvrecord(sock): record = '' last = 0 while not last: last, frag = recvfrag(sock) record = record + frag return record # Try to bind to a reserved port (must be root) last_resv_port_tried = None def bindresvport(sock, host): global last_resv_port_tried FIRST, LAST = 600, 1024 # Range of ports to try if last_resv_port_tried is None: import os last_resv_port_tried = FIRST + os.getpid() % (LAST-FIRST) for i in range(last_resv_port_tried, LAST) + \ range(FIRST, last_resv_port_tried): last_resv_port_tried = i try: sock.bind((host, i)) return last_resv_port_tried except socket.error, (errno, msg): if errno != 114: raise socket.error, (errno, msg) raise RuntimeError, 'can\'t assign reserved port' # Client using TCP to a specific port class RawTCPClient(Client): def makesocket(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def do_call(self): call = self.packer.get_buf() sendrecord(self.sock, call) reply = recvrecord(self.sock) u = self.unpacker u.reset(reply) xid, verf = u.unpack_replyheader() if xid != self.lastxid: # Can't really happen since this is TCP... raise RuntimeError, 'wrong xid in reply %r instead of %r' % ( xid, self.lastxid) # Client using UDP to a specific port class RawUDPClient(Client): def makesocket(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) def do_call(self): call = self.packer.get_buf() self.sock.send(call) try: from select import select except ImportError: print 'WARNING: select not found, RPC may hang' select = None BUFSIZE = 8192 # Max UDP buffer size timeout = 1 count = 5 while 1: r, w, x = [self.sock], [], [] if select: r, w, x = select(r, w, x, timeout) if self.sock not in r: count = count - 1 if count < 0: raise RuntimeError, 'timeout' if timeout < 25: timeout = timeout *2 ## print 'RESEND', timeout, count self.sock.send(call) continue reply = self.sock.recv(BUFSIZE) u = self.unpacker u.reset(reply) xid, verf = u.unpack_replyheader() if xid != self.lastxid: ## print 'BAD xid' continue break # Client using UDP broadcast to a specific port class RawBroadcastUDPClient(RawUDPClient): def __init__(self, bcastaddr, prog, vers, port): RawUDPClient.__init__(self, bcastaddr, prog, vers, port) self.reply_handler = None self.timeout = 30 def connsocket(self): # Don't connect -- use sendto self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) def set_reply_handler(self, reply_handler): self.reply_handler = reply_handler def set_timeout(self, timeout): self.timeout = timeout # Use None for infinite timeout def make_call(self, proc, args, pack_func, unpack_func): if pack_func is None and args is not None: raise TypeError, 'non-null args with null pack_func' self.start_call(proc) if pack_func: pack_func(args) call = self.packer.get_buf() self.sock.sendto(call, (self.host, self.port)) try: from select import select except ImportError: print 'WARNING: select not found, broadcast will hang' select = None BUFSIZE = 8192 # Max UDP buffer size (for reply) replies = [] if unpack_func is None: def dummy(): pass unpack_func = dummy while 1: r, w, x = [self.sock], [], [] if select: if self.timeout is None: r, w, x = select(r, w, x) else: r, w, x = select(r, w, x, self.timeout) if self.sock not in r: break reply, fromaddr = self.sock.recvfrom(BUFSIZE) u = self.unpacker u.reset(reply) xid, verf = u.unpack_replyheader() if xid != self.lastxid: ## print 'BAD xid' continue reply = unpack_func() self.unpacker.done() replies.append((reply, fromaddr)) if self.reply_handler: self.reply_handler(reply, fromaddr) return replies # Port mapper interface # Program number, version and (fixed!) port number PMAP_PROG = 100000 PMAP_VERS = 2 PMAP_PORT = 111 # Procedure numbers PMAPPROC_NULL = 0 # (void) -> void PMAPPROC_SET = 1 # (mapping) -> bool PMAPPROC_UNSET = 2 # (mapping) -> bool PMAPPROC_GETPORT = 3 # (mapping) -> unsigned int PMAPPROC_DUMP = 4 # (void) -> pmaplist PMAPPROC_CALLIT = 5 # (call_args) -> call_result # A mapping is (prog, vers, prot, port) and prot is one of: IPPROTO_TCP = 6 IPPROTO_UDP = 17 # A pmaplist is a variable-length list of mappings, as follows: # either (1, mapping, pmaplist) or (0). # A call_args is (prog, vers, proc, args) where args is opaque; # a call_result is (port, res) where res is opaque. class PortMapperPacker(Packer): def pack_mapping(self, mapping): prog, vers, prot, port = mapping self.pack_uint(prog) self.pack_uint(vers) self.pack_uint(prot) self.pack_uint(port) def pack_pmaplist(self, list): self.pack_list(list, self.pack_mapping) def pack_call_args(self, ca): prog, vers, proc, args = ca self.pack_uint(prog) self.pack_uint(vers) self.pack_uint(proc) self.pack_opaque(args) class PortMapperUnpacker(Unpacker): def unpack_mapping(self): prog = self.unpack_uint() vers = self.unpack_uint() prot = self.unpack_uint() port = self.unpack_uint() return prog, vers, prot, port def unpack_pmaplist(self): return self.unpack_list(self.unpack_mapping) def unpack_call_result(self): port = self.unpack_uint() res = self.unpack_opaque() return port, res class PartialPortMapperClient: def addpackers(self): self.packer = PortMapperPacker() self.unpacker = PortMapperUnpacker('') def Set(self, mapping): return self.make_call(PMAPPROC_SET, mapping, \ self.packer.pack_mapping, \ self.unpacker.unpack_uint) def Unset(self, mapping): return self.make_call(PMAPPROC_UNSET, mapping, \ self.packer.pack_mapping, \ self.unpacker.unpack_uint) def Getport(self, mapping): return self.make_call(PMAPPROC_GETPORT, mapping, \ self.packer.pack_mapping, \ self.unpacker.unpack_uint) def Dump(self): return self.make_call(PMAPPROC_DUMP, None, \ None, \ self.unpacker.unpack_pmaplist) def Callit(self, ca): return self.make_call(PMAPPROC_CALLIT, ca, \ self.packer.pack_call_args, \ self.unpacker.unpack_call_result) class TCPPortMapperClient(PartialPortMapperClient, RawTCPClient): def __init__(self, host): RawTCPClient.__init__(self, \ host, PMAP_PROG, PMAP_VERS, PMAP_PORT) class UDPPortMapperClient(PartialPortMapperClient, RawUDPClient): def __init__(self, host): RawUDPClient.__init__(self, \ host, PMAP_PROG, PMAP_VERS, PMAP_PORT) class BroadcastUDPPortMapperClient(PartialPortMapperClient, \ RawBroadcastUDPClient): def __init__(self, bcastaddr): RawBroadcastUDPClient.__init__(self, \ bcastaddr, PMAP_PROG, PMAP_VERS, PMAP_PORT) # Generic clients that find their server through the Port mapper class TCPClient(RawTCPClient): def __init__(self, host, prog, vers): pmap = TCPPortMapperClient(host) port = pmap.Getport((prog, vers, IPPROTO_TCP, 0)) pmap.close() if port == 0: raise RuntimeError, 'program not registered' RawTCPClient.__init__(self, host, prog, vers, port) class UDPClient(RawUDPClient): def __init__(self, host, prog, vers): pmap = UDPPortMapperClient(host) port = pmap.Getport((prog, vers, IPPROTO_UDP, 0)) pmap.close() if port == 0: raise RuntimeError, 'program not registered' RawUDPClient.__init__(self, host, prog, vers, port) class BroadcastUDPClient(Client): def __init__(self, bcastaddr, prog, vers): self.pmap = BroadcastUDPPortMapperClient(bcastaddr) self.pmap.set_reply_handler(self.my_reply_handler) self.prog = prog self.vers = vers self.user_reply_handler = None self.addpackers() def close(self): self.pmap.close() def set_reply_handler(self, reply_handler): self.user_reply_handler = reply_handler def set_timeout(self, timeout): self.pmap.set_timeout(timeout) def my_reply_handler(self, reply, fromaddr): port, res = reply self.unpacker.reset(res) result = self.unpack_func() self.unpacker.done() self.replies.append((result, fromaddr)) if self.user_reply_handler is not None: self.user_reply_handler(result, fromaddr) def make_call(self, proc, args, pack_func, unpack_func): self.packer.reset() if pack_func: pack_func(args) if unpack_func is None: def dummy(): pass self.unpack_func = dummy else: self.unpack_func = unpack_func self.replies = [] packed_args = self.packer.get_buf() dummy_replies = self.pmap.Callit( \ (self.prog, self.vers, proc, packed_args)) return self.replies # Server classes # These are not symmetric to the Client classes # XXX No attempt is made to provide authorization hooks yet class Server: def __init__(self, host, prog, vers, port): self.host = host # Should normally be '' for default interface self.prog = prog self.vers = vers self.port = port # Should normally be 0 for random port self.makesocket() # Assigns to self.sock and self.prot self.bindsocket() self.host, self.port = self.sock.getsockname() self.addpackers() def register(self): mapping = self.prog, self.vers, self.prot, self.port p = TCPPortMapperClient(self.host) if not p.Set(mapping): raise RuntimeError, 'register failed' def unregister(self): mapping = self.prog, self.vers, self.prot, self.port p = TCPPortMapperClient(self.host) if not p.Unset(mapping): raise RuntimeError, 'unregister failed' def handle(self, call): # Don't use unpack_header but parse the header piecewise # XXX I have no idea if I am using the right error responses! self.unpacker.reset(call) self.packer.reset() xid = self.unpacker.unpack_uint() self.packer.pack_uint(xid) temp = self.unpacker.unpack_enum() if temp != CALL: return None # Not worthy of a reply self.packer.pack_uint(REPLY) temp = self.unpacker.unpack_uint() if temp != RPCVERSION: self.packer.pack_uint(MSG_DENIED) self.packer.pack_uint(RPC_MISMATCH) self.packer.pack_uint(RPCVERSION) self.packer.pack_uint(RPCVERSION) return self.packer.get_buf() self.packer.pack_uint(MSG_ACCEPTED) self.packer.pack_auth((AUTH_NULL, make_auth_null())) prog = self.unpacker.unpack_uint() if prog != self.prog: self.packer.pack_uint(PROG_UNAVAIL) return self.packer.get_buf() vers = self.unpacker.unpack_uint() if vers != self.vers: self.packer.pack_uint(PROG_MISMATCH) self.packer.pack_uint(self.vers) self.packer.pack_uint(self.vers) return self.packer.get_buf() proc = self.unpacker.unpack_uint() methname = 'handle_' + repr(proc) try: meth = getattr(self, methname) except AttributeError: self.packer.pack_uint(PROC_UNAVAIL) return self.packer.get_buf() cred = self.unpacker.unpack_auth() verf = self.unpacker.unpack_auth() try: meth() # Unpack args, call turn_around(), pack reply except (EOFError, GarbageArgs): # Too few or too many arguments self.packer.reset() self.packer.pack_uint(xid) self.packer.pack_uint(REPLY) self.packer.pack_uint(MSG_ACCEPTED) self.packer.pack_auth((AUTH_NULL, make_auth_null())) self.packer.pack_uint(GARBAGE_ARGS) return self.packer.get_buf() def turn_around(self): try: self.unpacker.done() except RuntimeError: raise GarbageArgs self.packer.pack_uint(SUCCESS) def handle_0(self): # Handle NULL message self.turn_around() def makesocket(self): # This MUST be overridden raise RuntimeError, 'makesocket not defined' def bindsocket(self): # Override this to bind to a different port (e.g. reserved) self.sock.bind((self.host, self.port)) def addpackers(self): # Override this to use derived classes from Packer/Unpacker self.packer = Packer() self.unpacker = Unpacker('') class TCPServer(Server): def makesocket(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.prot = IPPROTO_TCP def loop(self): self.sock.listen(0) while 1: self.session(self.sock.accept()) def session(self, connection): sock, (host, port) = connection while 1: try: call = recvrecord(sock) except EOFError: break except socket.error, msg: print 'socket error:', msg break reply = self.handle(call) if reply is not None: sendrecord(sock, reply) def forkingloop(self): # Like loop but uses forksession() self.sock.listen(0) while 1: self.forksession(self.sock.accept()) def forksession(self, connection): # Like session but forks off a subprocess import os # Wait for deceased children try: while 1: pid, sts = os.waitpid(0, 1) except os.error: pass pid = None try: pid = os.fork() if pid: # Parent connection[0].close() return # Child self.session(connection) finally: # Make sure we don't fall through in the parent if pid == 0: os._exit(0) class UDPServer(Server): def makesocket(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.prot = IPPROTO_UDP def loop(self): while 1: self.session() def session(self): call, host_port = self.sock.recvfrom(8192) reply = self.handle(call) if reply is not None: self.sock.sendto(reply, host_port) # Simple test program -- dump local portmapper status def test(): pmap = UDPPortMapperClient('') list = pmap.Dump() list.sort() for prog, vers, prot, port in list: print prog, vers, if prot == IPPROTO_TCP: print 'tcp', elif prot == IPPROTO_UDP: print 'udp', else: print prot, print port # Test program for broadcast operation -- dump everybody's portmapper status def testbcast(): import sys if sys.argv[1:]: bcastaddr = sys.argv[1] else: bcastaddr = '' def rh(reply, fromaddr): host, port = fromaddr print host + '\t' + repr(reply) pmap = BroadcastUDPPortMapperClient(bcastaddr) pmap.set_reply_handler(rh) pmap.set_timeout(5) replies = pmap.Getport((100002, 1, IPPROTO_UDP, 0)) # Test program for server, with corresponding client # On machine A: python -c 'import rpc; rpc.testsvr()' # On machine B: python -c 'import rpc; rpc.testclt()' A # (A may be == B) def testsvr(): # Simple test class -- proc 1 doubles its string argument as reply class S(UDPServer): def handle_1(self): arg = self.unpacker.unpack_string() self.turn_around() print 'RPC function 1 called, arg', repr(arg) self.packer.pack_string(arg + arg) # s = S('', 0x20000000, 1, 0) try: s.unregister() except RuntimeError, msg: print 'RuntimeError:', msg, '(ignored)' s.register() print 'Service started...' try: s.loop() finally: s.unregister() print 'Service interrupted.' def testclt(): import sys if sys.argv[1:]: host = sys.argv[1] else: host = '' # Client for above server class C(UDPClient): def call_1(self, arg): return self.make_call(1, arg, \ self.packer.pack_string, \ self.unpacker.unpack_string) c = C(host, 0x20000000, 1) print 'making call...' reply = c.call_1('hello, world, ') print 'call returned', repr(reply) PK%L]rrpc/nfsclient.pycnu[ ^c@sddlZddlmZmZddlmZmZmZdZdZdZ dZ dZ dZ dZ d Zd Zd efd YZd efdYZdefdYZdZdS(iN(t UDPClientt TCPClient(tFHSIZEt MountPackert MountUnpackeriiiiiiit NFSPackercBs5eZdZdZdZdZdZRS(cCs*|\}}|j||j|dS(N(t pack_fhandlet pack_sattr(tselftsatfilet attributes((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pytpack_sattrargss  cCsj|\}}}}}}|j||j||j||j||j||j|dS(N(t pack_uintt pack_timeval(RR tmodetuidtgidtsizetatimetmtime((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pyR$s     cCs*|\}}|j||j|dS(N(Rt pack_string(Rtdatdirtname((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pytpack_diropargs-s  cCs:|\}}}|j||j||j|dS(N(RR (RtraRtcookietcount((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pytpack_readdirargs2s  cCs*|\}}|j||j|dS(N(R (Rttvtsecstusecs((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pyR8s  (t__name__t __module__R RRRR(((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pyRs    t NFSUnpackercBs>eZdZdZdZdZdZdZRS(cCsU|j}|tkrE|j|j}|j}||f}nd}||fS(N(t unpack_enumtNFS_OKt unpack_listt unpack_entryt unpack_booltNone(Rtstatustentriesteoftrest((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pytunpack_readdirres@s   cCs1|j}|j}|j}|||fS(N(t unpack_uintt unpack_string(RtfileidRR((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pyR'Js   cCsO|j}|tkr?|j}|j}||f}nd}||fS(N(R$R%tunpack_fhandlet unpack_fattrR)(RR*tfhtfaR-((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pytunpack_diropresPs    cCs7|j}|tkr'|j}nd}||fS(N(R$R%R3R)(RR*R ((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pytunpack_attrstatZs   cCs|j}|j}|j}|j}|j}|j}|j}|j}|j} |j} |j} |j} |j} |j}||||||||| | | | | |fS(N(R$R/tunpack_timeval(RttypeRtnlinkRRRt blocksizetrdevtblockstfsidR1RRtctime((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pyR3bs               cCs"|j}|j}||fS(N(R/(RRR ((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pyR8ts  (R!R"R.R'R6R7R3R8(((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pyR#>s    t NFSClientcBsPeZdZdZdZdZdZdZdZdZ RS(cCstj||ttdS(N(Rt__init__t NFS_PROGRAMt NFS_VERSION(Rthost((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pyRA|scCst|_td|_dS(Nt(RtpackerR#tunpacker(R((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pyt addpackerss cCs1|jdkr*tjtjf|_n|jS(N(tcredR)trpct AUTH_UNIXtmake_auth_unix_default(R((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pytmkcredscCs"|jd||jj|jjS(Ni(t make_callRFRRGR7(RR4((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pytGetattrs  cCs"|jd||jj|jjS(Ni(RNRFR RGR7(RR ((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pytSetattrs  cCs"|jd||jj|jjS(Ni(RNRFRRGR6(RR((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pytLookups  cCs"|jd||jj|jjS(Ni(RNRFRRGR.(RR((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pytReaddirs  c Csg}|ddf}x|j|\}}|tkr=Pn|\}}d}x0|D](\} } } |j| | f| }qVW|s|dkrPn|d||df}qW|S(Niii(RRR%R)tappend( RRtlistRR*R-R+R,t last_cookieR1RR((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pytListdirs   ( R!R"RARHRMRORPRQRRRV(((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pyR@zs       c Cs#ddl}|jdr)|jd}nd}|jdrL|jd}nd}ddlm}m}||}|dkr|j}x|D] }|GHqWdS|j|}|GH|d} | rt|} | j | } | GH| j | }x|D] }|GHqW|j |ndS(NiiREi(tUDPMountClienttTCPMountClient( tsystargvR)t mountclientRWRXtExporttMntR@RORVtUmnt( RYRDtfilesysRWRXtmclRTtitemtsfR4tncltattrstat((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pyttests2           (RJRRR[RRRRBRCR%tNFNONtNFREGtNFDIRtNFBLKtNFCHRtNFLNKRR#R@Re(((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pyt s !<9PK%L]'Cj??rpc/T.pynu[# Simple interface to report execution times of program fragments. # Call TSTART() to reset the timer, TSTOP(...) to report times. import sys, os, time def TSTART(): global t0, t1 u, s, cu, cs = os.times() t0 = u+cu, s+cs, time.time() def TSTOP(*label): global t0, t1 u, s, cu, cs = os.times() t1 = u+cu, s+cs, time.time() tt = [] for i in range(3): tt.append(t1[i] - t0[i]) [u, s, r] = tt msg = '' for x in label: msg = msg + (x + ' ') msg = msg + '%r user, %r sys, %r real\n' % (u, s, r) sys.stderr.write(msg) PK%L]•rpc/mountclient.pynu[# Mount RPC client -- RFC 1094 (NFS), Appendix A # This module demonstrates how to write your own RPC client in Python. # When this example was written, there was no RPC compiler for # Python. Without such a compiler, you must first create classes # derived from Packer and Unpacker to handle the data types for the # server you want to interface to. You then write the client class. # If you want to support both the TCP and the UDP version of a # protocol, use multiple inheritance as shown below. import rpc from rpc import Packer, Unpacker, TCPClient, UDPClient # Program number and version for the mount protocol MOUNTPROG = 100005 MOUNTVERS = 1 # Size of the 'fhandle' opaque structure FHSIZE = 32 # Packer derived class for Mount protocol clients. # The only thing we need to pack beyond basic types is an 'fhandle' class MountPacker(Packer): def pack_fhandle(self, fhandle): self.pack_fopaque(FHSIZE, fhandle) # Unpacker derived class for Mount protocol clients. # The important types we need to unpack are fhandle, fhstatus, # mountlist and exportlist; mountstruct, exportstruct and groups are # used to unpack components of mountlist and exportlist and the # corresponding functions are passed as function argument to the # generic unpack_list function. class MountUnpacker(Unpacker): def unpack_fhandle(self): return self.unpack_fopaque(FHSIZE) def unpack_fhstatus(self): status = self.unpack_uint() if status == 0: fh = self.unpack_fhandle() else: fh = None return status, fh def unpack_mountlist(self): return self.unpack_list(self.unpack_mountstruct) def unpack_mountstruct(self): hostname = self.unpack_string() directory = self.unpack_string() return (hostname, directory) def unpack_exportlist(self): return self.unpack_list(self.unpack_exportstruct) def unpack_exportstruct(self): filesys = self.unpack_string() groups = self.unpack_groups() return (filesys, groups) def unpack_groups(self): return self.unpack_list(self.unpack_string) # These are the procedures specific to the Mount client class. # Think of this as a derived class of either TCPClient or UDPClient. class PartialMountClient: # This method is called by Client.__init__ to initialize # self.packer and self.unpacker def addpackers(self): self.packer = MountPacker() self.unpacker = MountUnpacker('') # This method is called by Client.__init__ to bind the socket # to a particular network interface and port. We use the # default network interface, but if we're running as root, # we want to bind to a reserved port def bindsocket(self): import os try: uid = os.getuid() except AttributeError: uid = 1 if uid == 0: port = rpc.bindresvport(self.sock, '') # 'port' is not used else: self.sock.bind(('', 0)) # This function is called to cough up a suitable # authentication object for a call to procedure 'proc'. def mkcred(self): if self.cred is None: self.cred = rpc.AUTH_UNIX, rpc.make_auth_unix_default() return self.cred # The methods Mnt, Dump etc. each implement one Remote # Procedure Call. This is done by calling self.make_call() # with as arguments: # # - the procedure number # - the arguments (or None) # - the "packer" function for the arguments (or None) # - the "unpacker" function for the return value (or None) # # The packer and unpacker function, if not None, *must* be # methods of self.packer and self.unpacker, respectively. # A value of None means that there are no arguments or is no # return value, respectively. # # The return value from make_call() is the return value from # the remote procedure call, as unpacked by the "unpacker" # function, or None if the unpacker function is None. # # (Even if you expect a result of None, you should still # return the return value from make_call(), since this may be # needed by a broadcasting version of the class.) # # If the call fails, make_call() raises an exception # (this includes time-outs and invalid results). # # Note that (at least with the UDP protocol) there is no # guarantee that a call is executed at most once. When you do # get a reply, you know it has been executed at least once; # when you don't get a reply, you know nothing. def Mnt(self, directory): return self.make_call(1, directory, \ self.packer.pack_string, \ self.unpacker.unpack_fhstatus) def Dump(self): return self.make_call(2, None, \ None, self.unpacker.unpack_mountlist) def Umnt(self, directory): return self.make_call(3, directory, \ self.packer.pack_string, None) def Umntall(self): return self.make_call(4, None, None, None) def Export(self): return self.make_call(5, None, \ None, self.unpacker.unpack_exportlist) # We turn the partial Mount client into a full one for either protocol # by use of multiple inheritance. (In general, when class C has base # classes B1...Bn, if x is an instance of class C, methods of x are # searched first in C, then in B1, then in B2, ..., finally in Bn.) class TCPMountClient(PartialMountClient, TCPClient): def __init__(self, host): TCPClient.__init__(self, host, MOUNTPROG, MOUNTVERS) class UDPMountClient(PartialMountClient, UDPClient): def __init__(self, host): UDPClient.__init__(self, host, MOUNTPROG, MOUNTVERS) # A little test program for the Mount client. This takes a host as # command line argument (default the local machine), prints its export # list, and attempts to mount and unmount each exported files system. # An optional first argument of -t or -u specifies the protocol to use # (TCP or UDP), default is UDP. def test(): import sys if sys.argv[1:] and sys.argv[1] == '-t': C = TCPMountClient del sys.argv[1] elif sys.argv[1:] and sys.argv[1] == '-u': C = UDPMountClient del sys.argv[1] else: C = UDPMountClient if sys.argv[1:]: host = sys.argv[1] else: host = '' mcl = C(host) list = mcl.Export() for item in list: print item try: mcl.Mnt(item[0]) except: print 'Sorry' continue mcl.Umnt(item[0]) PK%L] x}vv rpc/rpc.pycnu[ ^c@s=ddlZddlZddlZdZdZdZdZdZdZdZ dZ dZ dZ dZ dZdZdZdZdZdZdZdZdZdZdejfd YZd efd YZd efd YZdefdYZdejfdYZdZdZdZ da!dZ"ddCdYZ#dZ$dZ%dZ&dZ'da)dZ*de#fdYZ+de#fd YZ,d!e,fd"YZ-d#Z.dZ/d$Z0dZ1dZ2dZ3dZ4dZ5dZ6d%Z7d&Z8d'efd(YZ9d)efd*YZ:d+dDd,YZ;d-e;e+fd.YZ<d/e;e,fd0YZ=d1e;e-fd2YZ>d3e+fd4YZ?d5e,fd6YZ@d7e#fd8YZAd9dEd:YZBd;eBfd<YZCd=eBfd>YZDd?ZEd@ZFdAZGdBZHdS(FiNiiiiiitPackercBs,eZdZdZdZdZRS(cCs*|\}}|j||j|dS(N(t pack_enumt pack_opaque(tselftauthtflavortstuff((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyt pack_auth0s  cCsi|j||j||j||j||jt|x|D]}|j|qNWdS(N(t pack_uintt pack_stringtlen(Rtstampt machinenametuidtgidtgidsti((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytpack_auth_unix5s     cCsl|j||jt|jt|j||j||j||j||j|dS(N(RRtCALLt RPCVERSIONR(Rtxidtprogtverstproctcredtverf((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytpack_callheader>s       cCsE|j||jt|jt|j||jtdS(N(RRtREPLYt MSG_ACCEPTEDRtSUCCESS(RRR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytpack_replyheaderIs     (t__name__t __module__RRRR(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR.s  t BadRPCFormatcBseZRS((RR (((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR!Sst BadRPCVersioncBseZRS((RR (((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR"Tst GarbageArgscBseZRS((RR (((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR#UstUnpackercBs#eZdZdZdZRS(cCs"|j}|j}||fS(N(t unpack_enumt unpack_opaque(RRR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyt unpack_authYs  cCs|j}|j}|tkr7td|fn|j}|tkrbtd|fn|j}|j}|j}|j}|j}||||||fS(Nsno CALL but %rsbad RPC version %r(t unpack_uintR%RR!RR"R'(RRttempRRRRR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytunpack_callheader^s          cCs|j}|j}|tkr7td|fn|j}|tkr|j}|tkr|j}|j}td||ffn|tkr|j}td|fntd|fn|tkrtd|fn|j}|j}|t kr%tdn|t krb|j}|j}td||ffn|t krztdn|t krtd n|t krtd |fn||fS( Nsno REPLY but %rsMSG_DENIED: RPC_MISMATCH: %rsMSG_DENIED: AUTH_ERROR: %rsMSG_DENIED: %rs'Neither MSG_DENIED nor MSG_ACCEPTED: %rscall failed: PROG_UNAVAILscall failed: PROG_MISMATCH: %rscall failed: PROC_UNAVAILscall failed: GARBAGE_ARGSscall failed: %r(R(R%Rt RuntimeErrort MSG_DENIEDt RPC_MISMATCHt AUTH_ERRORRR't PROG_UNAVAILt PROG_MISMATCHt PROC_UNAVAILt GARBAGE_ARGSR(RRtmtypetstattlowthighR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytunpack_replyheadernsH                        (RR R'R*R7(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR$Ws  cCsdS(Nt((((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytmake_auth_nullscCs,t}|j||||||jS(N(RRtget_buf(tseedthostR Rtgroupstp((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytmake_auth_unixs cCsy,ddlm}m}|}|}Wntk rId}}nXddl}tt|jttj ||gS(Ni(tgetuidtgetgidi( tosR@RAt ImportErrorttimeR?tintt unix_epochtsockett gethostname(R@RAR RRD((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytmake_auth_unix_defaults    c CstdkrtSddl}|j}|j|}|j|}|j||j|}d \}}}}} } t| |d\}} t| |d\}} t||d\}}||}|j||||| | dddf adG|jtGHtS( s9Very painful calculation of when the Unix Epoch is. This is defined as the return value of time.time() on Jan 1st, 1970, 00:00:00 GMT. On a Unix system, this should always return 0.0. On a Mac, the calculations are needed -- and hard because of integer overflow and other limitations. iiNiii<is Unix epoch:(iiiiii(t _unix_epochRDt localtimetgmtimetmktimetdivmodtctime( RDtnowtlocalttgmttoffsettytmtdthhtmmtss((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRFs    *tClientcBsteZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z RS( cCsk||_||_||_||_|j|j|jd|_|jd|_ d|_ dS(Ni( R<RRtportt makesockett bindsockett connsockettlastxidt addpackerstNoneRR(RR<RRR[((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyt__init__s          cCs|jjdS(N(tsocktclose(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRdscCs tddS(Nsmakesocket not defined(R+(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR\scCs |jj|j|jfdS(N(RctconnectR<R[(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR^scCs|jjddS(NR8i(R8i(Rctbind(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR]scCst|_td|_dS(NR8(RtpackerR$tunpacker(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR`s cCsw|dkr$|dk r$tdn|j||rD||n|j|r`|}nd}|jj|S(Ns!non-null args with null pack_func(Rat TypeErrort start_calltdo_callRhtdone(RRtargst pack_funct unpack_functresult((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyt make_calls      cCse|jd|_}|j}|j}|j}|j|j||j|j|||dS(Ni(R_tmkcredtmkverfRgtresetRRR(RRRRRR>((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRjs     cCs tddS(Nsdo_call not defined(R+(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRkscCs+|jdkr$ttf|_n|jS(N(RRat AUTH_NULLR9(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRr scCs+|jdkr$ttf|_n|jS(N(RRaRuR9(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRsscCs|jddddS(Ni(RqRa(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytcall_0s(RR RbRdR\R^R]R`RqRjRkRrRsRv(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRZs         cCst|}|r|dB}ntt|d?d@tt|d?d@tt|d?d@tt|d@}|j||dS(Nliiii(R tchrREtsend(Rctlasttfragtxtheader((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytsendfrags   ^cCst|d|dS(Ni(R}(Rctrecord((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyt sendrecord"scCs|jd}t|dkr*tntt|dd>t|dd>Bt|dd>Bt|dB}|d @dk}t|d @}d }xH|dkr|j|}|stn|t|}||}qW||fS( NiiiiiiiiIiR8(trecvR tEOFErrortlongtordRE(RcR|R{RytnRztbuf((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytrecvfrag%s L cCs9d}d}x&|s4t|\}}||}qW|S(NR8i(R(RcR~RyRz((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyt recvrecord5s  cCsd\}}tdkr?ddl}||j||anxtt|t|tD]g}|ay|j||ftSWq\tjk r\}}|dkrtj||fqq\Xq\WtddS(NiXiiirscan't assign reserved port(iXi( tlast_resv_port_triedRaRBtgetpidtrangeRfRGterrorR+(RcR<tFIRSTtLASTRBRterrnotmsg((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyt bindresvportAs    t RawTCPClientcBseZdZdZRS(cCstjtjtj|_dS(N(RGtAF_INETt SOCK_STREAMRc(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR\WscCs|jj}t|j|t|j}|j}|j||j\}}||jkr~t d||jfndS(Ns#wrong xid in reply %r instead of %r( RgR:RRcRRhRtR7R_R+(RtcalltreplytuRR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRkZs  (RR R\Rk(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRUs t RawUDPClientcBseZdZdZRS(cCstjtjtj|_dS(N(RGRt SOCK_DGRAMRc(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR\ksc Cs`|jj}|jj|yddlm}Wntk rQdGHd}nXd}d}d}x|jggg}}}|r|||||\}}}n|j|kr|d}|dkrtdn|d kr|d }n|jj|qgn|jj|} |j } | j | | j \} } | |j krWqgnPqgWdS( Ni(tselects'WARNING: select not found, RPC may hangi iiittimeoutii( RgR:RcRxRRCRaR+RRhRtR7R_( RRRtBUFSIZERtcounttrtwR{RRRR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRkns:  !     (RR R\Rk(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRis tRawBroadcastUDPClientcBs5eZdZdZdZdZdZRS(cCs/tj|||||d|_d|_dS(Ni(RRbRat reply_handlerR(Rt bcastaddrRRR[((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRbs cCs |jjtjtjddS(Ni(Rct setsockoptRGt SOL_SOCKETt SO_BROADCAST(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR^scCs ||_dS(N(R(RR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytset_reply_handlerscCs ||_dS(N(R(RR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyt set_timeoutscCs|dkr$|dk r$tdn|j||rD||n|jj}|jj||j|jfyddl m }Wnt k rdGHd}nXd}g}|dkrd} | }nx"|jggg} } } |rC|j dkr|| | | \} } } qC|| | | |j \} } } n|j| krVPn|jj |\} }|j }|j| |j\}}||jkrqn|} |j j|j| |f|jr|j| |qqW|S(Ns!non-null args with null pack_funci(Rs.WARNING: select not found, broadcast will hangi cSsdS(N((((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytdummyR8(RaRiRjRgR:RctsendtoR<R[RRCRtrecvfromRhRtR7R_RltappendR(RRRmRnRoRRRtrepliesRRRR{RtfromaddrRRR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRqsJ        $     (RR RbR^RRRq(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRs     iioiitPortMapperPackercBs#eZdZdZdZRS(cCsJ|\}}}}|j||j||j||j|dS(N(R(RtmappingRRtprotR[((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyt pack_mappings    cCs|j||jdS(N(t pack_listR(Rtlist((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyt pack_pmaplistscCsJ|\}}}}|j||j||j||j|dS(N(RR(RtcaRRRRm((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytpack_call_argss    (RR RRR(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRs  tPortMapperUnpackercBs#eZdZdZdZRS(cCs@|j}|j}|j}|j}||||fS(N(R((RRRRR[((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytunpack_mappings     cCs|j|jS(N(t unpack_listR(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytunpack_pmaplistscCs"|j}|j}||fS(N(R(R&(RR[tres((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytunpack_call_results  (RR RRR(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRs  tPartialPortMapperClientcBs>eZdZdZdZdZdZdZRS(cCst|_td|_dS(NR8(RRgRRh(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR`s cCs"|jt||jj|jjS(N(Rqt PMAPPROC_SETRgRRhR((RR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytSets  cCs"|jt||jj|jjS(N(RqtPMAPPROC_UNSETRgRRhR((RR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytUnsets  cCs"|jt||jj|jjS(N(RqtPMAPPROC_GETPORTRgRRhR((RR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytGetports  cCs|jtdd|jjS(N(Rqt PMAPPROC_DUMPRaRhR(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytDump!s cCs"|jt||jj|jjS(N(RqtPMAPPROC_CALLITRgRRhR(RR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytCallit&s  (RR R`RRRRR(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR s      tTCPPortMapperClientcBseZdZRS(cCstj||tttdS(N(RRbt PMAP_PROGt PMAP_VERSt PMAP_PORT(RR<((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRb.s (RR Rb(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR,stUDPPortMapperClientcBseZdZRS(cCstj||tttdS(N(RRbRRR(RR<((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRb5s (RR Rb(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR3stBroadcastUDPPortMapperClientcBseZdZRS(cCstj||tttdS(N(RRbRRR(RR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRb=s (RR Rb(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR:st TCPClientcBseZdZRS(cCsft|}|j||tdf}|j|dkrItdntj|||||dS(Nisprogram not registered(RRt IPPROTO_TCPRdR+RRb(RR<RRtpmapR[((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRbFs     (RR Rb(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRDst UDPClientcBseZdZRS(cCsft|}|j||tdf}|j|dkrItdntj|||||dS(Nisprogram not registered(RRt IPPROTO_UDPRdR+RRb(RR<RRRR[((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRbQs     (RR Rb(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyROstBroadcastUDPClientcBs>eZdZdZdZdZdZdZRS(cCsKt||_|jj|j||_||_d|_|jdS(N( RRRtmy_reply_handlerRRRatuser_reply_handlerR`(RRRR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRb\s    cCs|jjdS(N(RRd(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRddscCs ||_dS(N(R(RR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRgscCs|jj|dS(N(RR(RR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRjscCsq|\}}|jj||j}|jj|jj||f|jdk rm|j||ndS(N(RhRtRoRlRRRRa(RRRR[RRp((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRms   cCs|jj|r ||n|dkrAd}||_n ||_g|_|jj}|jj|j|j ||f}|jS(NcSsdS(N((((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR{R8( RgRtRaRoRR:RRRR(RRRmRnRoRt packed_argst dummy_replies((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRqvs        (RR RbRdRRRRq(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRZs      tServercBsYeZdZdZdZdZdZdZdZdZ dZ RS( cCsa||_||_||_||_|j|j|jj\|_|_|jdS(N( R<RRR[R\R]Rct getsocknameR`(RR<RRR[((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRbs      cCsL|j|j|j|jf}t|j}|j|sHtdndS(Nsregister failed(RRRR[RR<RR+(RRR>((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytregisterscCsL|j|j|j|jf}t|j}|j|sHtdndS(Nsunregister failed(RRRR[RR<RR+(RRR>((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyt unregistersc Cs|jj||jj|jj}|jj||jj}|tkr[dS|jjt|jj}|t kr|jjt |jjt |jjt |jjt |jj S|jjt |jjttf|jj}||jkr7|jjt|jj S|jj}||jkr|jjt|jj|j|jj|j|jj S|jj}dt|}yt||}Wn+tk r|jjt|jj SX|jj} |jj} y |Wn}ttfk r|jj|jj||jjt|jjt |jjttf|jjtnX|jj S(Nthandle_(RhRtRgR(RR%RRaRRR,R-R:RRRuR9RR/RR0treprtgetattrtAttributeErrorR1R'RR#R2( RRRR)RRRtmethnametmethRR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pythandles\         cCs?y|jjWntk r*tnX|jjtdS(N(RhRlR+R#RgRR(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyt turn_arounds   cCs|jdS(N(R(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pythandle_0scCs tddS(Nsmakesocket not defined(R+(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR\scCs |jj|j|jfdS(N(RcRfR<R[(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR]scCst|_td|_dS(NR8(RRgR$Rh(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR`s ( RR RbRRRRRR\R]R`(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRs   3    t TCPServercBs5eZdZdZdZdZdZRS(cCs(tjtjtj|_t|_dS(N(RGRRRcRR(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR\scCs1|jjdx|j|jjqWdS(Ni(Rctlistentsessiontaccept(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytloopscCs|\}\}}xsyt|}Wn1tk r9Pn tjk rX}dG|GHPnX|j|}|dk rt||qqWdS(Ns socket error:(RRRGRRRaR(Rt connectionRcR<R[RRR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRs   cCs1|jjdx|j|jjqWdS(Ni(RcRt forksessionR(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyt forkingloopscCsddl}y#x|jdd\}}qWWn|jk rEnXd}z5|j}|rs|djdS|j|Wd|dkr|jdnXdS(Niii(RBtwaitpidRRatforkRdRt_exit(RRRBtpidtsts((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR s    (RR R\RRRR(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRs     t UDPServercBs#eZdZdZdZRS(cCs(tjtjtj|_t|_dS(N(RGRRRcRR(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR\&scCsx|jqWdS(N(R(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR*scCsM|jjd\}}|j|}|dk rI|jj||ndS(Ni (RcRRRaR(RRt host_portR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR.s (RR R\RR(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR$s  cCsztd}|j}|jxQ|D]I\}}}}|G|G|tkrVdGn|tkridGn|G|GHq)WdS(NR8ttcptudp(RRtsortRR(RRRRRR[((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyttest7s     cCs}ddl}|jdr)|jd}nd}d}t|}|j||jd|jddtdf}dS(Niis cSs#|\}}|dt|GHdS(Ns (R(RRR<R[((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytrhKs iii(tsystargvRRRRR(RRRRR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyt testbcastEs      cCsdtfdY}|dddd}y|jWn tk r[}dG|GdGHnX|jd GHz|jWd|jd GHXdS( NtScBseZdZRS(cSs@|jj}|jdGt|GH|jj||dS(NsRPC function 1 called, arg(Rht unpack_stringRRRgR (Rtarg((s$/usr/lib64/python2.7/Demo/rpc/rpc.pythandle_1\s (RR R(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR[sR8i iis RuntimeError:s (ignored)sService started...sService interrupted.(RRR+RR(RtsR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyttestsvrYs  cCs~ddl}|jdr)|jd}nd}dtfdY}||dd}dGH|jd}d Gt|GHdS( NiiR8tCcBseZdZRS(cSs"|jd||jj|jjS(Ni(RqRgR RhR(RR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytcall_1vs  (RR R(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRusi smaking call...shello, world, s call returned(RRRRR(RR<RtcR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyttestcltps  ((((ItxdrRGRBRRRRut AUTH_UNIXt AUTH_SHORTtAUTH_DESRR,RR/R0R1R2R-R.t AUTH_BADCREDtAUTH_REJECTEDCREDt AUTH_BADVERFtAUTH_REJECTEDVERFt AUTH_TOOWEAKRt ExceptionR!R"R#R$R9R?RIRJRFRZR}RRRRaRRRRRRRRt PMAPPROC_NULLRRRRRRRRRRRRRRRRRRRRRRR(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyt s   %A    Q     '>     1c6   PK%L] rpc/xdr.pycnu[ ^c@s`yddlZWnek r)dZnXedZdddYZdddYZdS( iNltPackercBseZdZdZdZdZerTejdddkrTdZneZeZ dZ d Z e Z d Z d Zd ZeZd ZeZdZdZdZRS(cCs|jdS(N(treset(tself((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt__init__scCs d|_dS(Nt(tbuf(R((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyRscCs|jS(N(R(R((s$/usr/lib64/python2.7/Demo/rpc/xdr.pytget_bufscCsl|jtt|d?d@tt|d?d@tt|d?d@tt|d@|_dS(Niiii(Rtchrtint(Rtx((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt pack_uintstliscCsMt|tkr-t|ddd}n|jtjd||_dS(NllR (ttypetLongRRtstructtpack(RR ((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyR s cCs-|r|jd|_n|jd|_dS(Nss(R(RR ((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt pack_bool'scCs6|jt|d?d@|jt|d@dS(Ni I(R R(RR ((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt pack_uhyper+scCs |jtjd||_dS(Ntf(RRR(RR ((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt pack_float1scCs |jtjd||_dS(Ntd(RRR(RR ((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt pack_double5scCs`|dkrtdn|ddd}|| }||t|d}|j||_dS(Nis fstring size must be nonnegativeiis(t ValueErrortlenR(Rtntstdata((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt pack_fstring9s    cCs-t|}|j||j||dS(N(RR R(RRR((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt pack_stringCs  cCs9x%|D]}|jd||qW|jddS(Nii(R (Rtlistt pack_itemtitem((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt pack_listJs  cCs=t||krtdnx|D]}||q%WdS(Nswrong array size(RR(RRRRR((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt pack_farrayPs  cCs0t|}|j||j|||dS(N(RR R!(RRRR((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt pack_arrayVs  (t__name__t __module__RRRR RRtpack_intt pack_enumRRt pack_hyperRRRt pack_fopaqueRt pack_opaqueR R!R"(((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyR s(             tUnpackercBseZdZdZdZdZerTejdddkrTdZndZeZ eZ d Z d Z d Z d Zd ZeZdZeZdZdZdZRS(cCs|j|dS(N(R(RR((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyR^scCs||_d|_dS(Ni(Rtpos(RR((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyRas cCs(|jt|jkr$tdndS(Nsunextracted data remains(R+RRt RuntimeError(R((s$/usr/lib64/python2.7/Demo/rpc/xdr.pytdoneescCs|j}|d|_}|j||!}t|dkrEtntt|dd>t|dd>Bt|dd>Bt|dB}|d krt|}n|S( Niiiiiiiil(R+RRtEOFErrortlongtordR(RtitjRR ((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt unpack_uintis  L R sicCsU|j}|d|_}|j||!}t|dkrEtntjd|S(NiR (R+RRR.Rtunpack(RR1R2R((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyR3vs   cCs/|j}|dkr%|d}nt|S(Nll(R3R(RR ((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt unpack_int~s  cCs*|j}|j}t|d>|BS(Ni (R3R/(Rthitlo((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt unpack_uhypers  cCs)|j}|dkr%|d}n|S(Nll(R8(RR ((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt unpack_hypers  cCsY|j}|d|_}|j||!}t|dkrEtntjd|dS(NiRi(R+RRR.RR4(RR1R2R((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt unpack_floats   cCsY|j}|d|_}|j||!}t|dkrEtntjd|dS(NiRi(R+RRR.RR4(RR1R2R((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt unpack_doubles   cCsp|dkrtdn|j}||ddd}|t|jkrUtn||_|j|||!S(Nis fstring size must be nonnegativeii(RR+RRR.(RRR1R2((s$/usr/lib64/python2.7/Demo/rpc/xdr.pytunpack_fstrings     cCs|j}|j|S(N(R3R<(RR((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt unpack_strings cCsbg}xU|j}|dkr%Pn|dkrDtd|fn|}|j|q W|S(Niis0 or 1 expected, got %r(R3R,tappend(Rt unpack_itemRR R((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt unpack_lists    cCs1g}x$t|D]}|j|qW|S(N(trangeR>(RRR?RR1((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt unpack_farrayscCs|j}|j||S(N(R3RB(RR?R((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt unpack_arrays (R#R$RRR-R3RR4R5t unpack_enumt unpack_boolR8R9R:R;R<tunpack_fopaqueR=t unpack_opaqueR@RBRC(((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyR*\s(           (((Rt ImportErrortNoneR R RR*(((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyts    OPK%L]A)E E rpc/rnusersclient.pynu[# Remote nusers client interface import rpc from rpc import Packer, Unpacker, UDPClient, BroadcastUDPClient class RnusersPacker(Packer): def pack_utmp(self, ui): ut_line, ut_name, ut_host, ut_time = utmp self.pack_string(ut_line) self.pack_string(ut_name) self.pack_string(ut_host) self.pack_int(ut_time) def pack_utmpidle(self, ui): ui_itmp, ui_idle = ui self.pack_utmp(ui_utmp) self.pack_uint(ui_idle) def pack_utmpidlearr(self, list): self.pack_array(list, self.pack_itmpidle) class RnusersUnpacker(Unpacker): def unpack_utmp(self): ut_line = self.unpack_string() ut_name = self.unpack_string() ut_host = self.unpack_string() ut_time = self.unpack_int() return ut_line, ut_name, ut_host, ut_time def unpack_utmpidle(self): ui_utmp = self.unpack_utmp() ui_idle = self.unpack_uint() return ui_utmp, ui_idle def unpack_utmpidlearr(self): return self.unpack_array(self.unpack_utmpidle) class PartialRnusersClient: def addpackers(self): self.packer = RnusersPacker() self.unpacker = RnusersUnpacker('') def Num(self): return self.make_call(1, None, None, self.unpacker.unpack_int) def Names(self): return self.make_call(2, None, \ None, self.unpacker.unpack_utmpidlearr) def Allnames(self): return self.make_call(3, None, \ None, self.unpacker.unpack_utmpidlearr) class RnusersClient(PartialRnusersClient, UDPClient): def __init__(self, host): UDPClient.__init__(self, host, 100002, 2) class BroadcastRnusersClient(PartialRnusersClient, BroadcastUDPClient): def __init__(self, bcastaddr): BroadcastUDPClient.__init__(self, bcastaddr, 100002, 2) def test(): import sys if not sys.argv[1:]: testbcast() return else: host = sys.argv[1] c = RnusersClient(host) list = c.Names() for (line, name, host, time), idle in list: line = strip0(line) name = strip0(name) host = strip0(host) print "%r %r %r %s %s" % (name, host, line, time, idle) def testbcast(): c = BroadcastRnusersClient('') def listit(list, fromaddr): host, port = fromaddr print host + '\t:', for (line, name, host, time), idle in list: print strip0(name), print c.set_reply_handler(listit) all = c.Names() print 'Total Count:', len(all) def strip0(s): while s and s[-1] == '\0': s = s[:-1] return s test() PK%L]Wj rpc/READMEnu[This is a Python interface to Sun RPC, designed and implemented mostly by reading the Internet RFCs about the subject. *** NOTE: xdr.py has evolved into the standard module xdrlib.py *** There are two library modules, xdr.py and rpc.py, and several example clients: mountclient.py, nfsclient.py, and rnusersclient.py, implementing the NFS Mount protocol, (part of) the NFS protocol, and the "rnusers" protocol (used by rusers(1)), respectively. The latter demonstrates the use of broadcast via the Port mapper's CALLIT procedure. There is also a way to create servers in Python. To test the nfs client, run it from the shell with something like this: python -c 'import nfsclient; nfsclient.test()' [hostname [filesystemname]] When called without a filesystemname, it lists the filesystems at the host; default host is the local machine. Other clients are tested similarly. For hostname, use e.g. wuarchive.wustl.edu or gatekeeper.dec.com (two hosts that are known to export NFS filesystems with little restrictions). There are now two different RPC compilers: 1) Wim Lewis rpcgen.py found on http://www.omnigroup.com/~wiml/soft/stale-index.html#python. 2) Peter strands rpcgen.py, which is part of "pynfs" (http://www.cendio.se/~peter/pynfs/). PK%L]yOGii rpc/MANIFESTnu[ File Name Archive # Description ----------------------------------------------------------- MANIFEST 1 This shipping list README 1 T.py 1 mountclient.py 1 nfsclient.py 1 rpc.py 1 test 1 xdr.py 1 PK%L]}, rpc/xdr.pynu[# Implement (a subset of) Sun XDR -- RFC1014. try: import struct except ImportError: struct = None Long = type(0L) class Packer: def __init__(self): self.reset() def reset(self): self.buf = '' def get_buf(self): return self.buf def pack_uint(self, x): self.buf = self.buf + \ (chr(int(x>>24 & 0xff)) + chr(int(x>>16 & 0xff)) + \ chr(int(x>>8 & 0xff)) + chr(int(x & 0xff))) if struct and struct.pack('l', 1) == '\0\0\0\1': def pack_uint(self, x): if type(x) == Long: x = int((x + 0x80000000L) % 0x100000000L \ - 0x80000000L) self.buf = self.buf + struct.pack('l', x) pack_int = pack_uint pack_enum = pack_int def pack_bool(self, x): if x: self.buf = self.buf + '\0\0\0\1' else: self.buf = self.buf + '\0\0\0\0' def pack_uhyper(self, x): self.pack_uint(int(x>>32 & 0xffffffff)) self.pack_uint(int(x & 0xffffffff)) pack_hyper = pack_uhyper def pack_float(self, x): # XXX self.buf = self.buf + struct.pack('f', x) def pack_double(self, x): # XXX self.buf = self.buf + struct.pack('d', x) def pack_fstring(self, n, s): if n < 0: raise ValueError, 'fstring size must be nonnegative' n = ((n + 3)//4)*4 data = s[:n] data = data + (n - len(data)) * '\0' self.buf = self.buf + data pack_fopaque = pack_fstring def pack_string(self, s): n = len(s) self.pack_uint(n) self.pack_fstring(n, s) pack_opaque = pack_string def pack_list(self, list, pack_item): for item in list: self.pack_uint(1) pack_item(item) self.pack_uint(0) def pack_farray(self, n, list, pack_item): if len(list) <> n: raise ValueError, 'wrong array size' for item in list: pack_item(item) def pack_array(self, list, pack_item): n = len(list) self.pack_uint(n) self.pack_farray(n, list, pack_item) class Unpacker: def __init__(self, data): self.reset(data) def reset(self, data): self.buf = data self.pos = 0 def done(self): if self.pos < len(self.buf): raise RuntimeError, 'unextracted data remains' def unpack_uint(self): i = self.pos self.pos = j = i+4 data = self.buf[i:j] if len(data) < 4: raise EOFError x = long(ord(data[0]))<<24 | ord(data[1])<<16 | \ ord(data[2])<<8 | ord(data[3]) # Return a Python long only if the value is not representable # as a nonnegative Python int if x < 0x80000000L: x = int(x) return x if struct and struct.unpack('l', '\0\0\0\1') == 1: def unpack_uint(self): i = self.pos self.pos = j = i+4 data = self.buf[i:j] if len(data) < 4: raise EOFError return struct.unpack('l', data) def unpack_int(self): x = self.unpack_uint() if x >= 0x80000000L: x = x - 0x100000000L return int(x) unpack_enum = unpack_int unpack_bool = unpack_int def unpack_uhyper(self): hi = self.unpack_uint() lo = self.unpack_uint() return long(hi)<<32 | lo def unpack_hyper(self): x = self.unpack_uhyper() if x >= 0x8000000000000000L: x = x - 0x10000000000000000L return x def unpack_float(self): # XXX i = self.pos self.pos = j = i+4 data = self.buf[i:j] if len(data) < 4: raise EOFError return struct.unpack('f', data)[0] def unpack_double(self): # XXX i = self.pos self.pos = j = i+8 data = self.buf[i:j] if len(data) < 8: raise EOFError return struct.unpack('d', data)[0] def unpack_fstring(self, n): if n < 0: raise ValueError, 'fstring size must be nonnegative' i = self.pos j = i + (n+3)//4*4 if j > len(self.buf): raise EOFError self.pos = j return self.buf[i:i+n] unpack_fopaque = unpack_fstring def unpack_string(self): n = self.unpack_uint() return self.unpack_fstring(n) unpack_opaque = unpack_string def unpack_list(self, unpack_item): list = [] while 1: x = self.unpack_uint() if x == 0: break if x <> 1: raise RuntimeError, '0 or 1 expected, got %r' % (x, ) item = unpack_item() list.append(item) return list def unpack_farray(self, n, unpack_item): list = [] for i in range(n): list.append(unpack_item()) return list def unpack_array(self, unpack_item): n = self.unpack_uint() return self.unpack_farray(n, unpack_item) PK%L]: rpc/T.pyonu[ ^c@s:ddlZddlZddlZdZdZdS(iNcCs9tj\}}}}||||tjfadS(N(tosttimesttimett0(tutstcutcs((s"/usr/lib64/python2.7/Demo/rpc/T.pytTSTARTsc Gstj\}}}}||||tjfag}x-tdD]}|jt|t|qHW|\}}}d}x|D]} || d}qW|d|||f}tjj |dS(Nitt s%r user, %r sys, %r real ( RRRtt1trangetappendRtsyststderrtwrite( tlabelRRRRttttitrtmsgtx((s"/usr/lib64/python2.7/Demo/rpc/T.pytTSTOP s (RRRRR(((s"/usr/lib64/python2.7/Demo/rpc/T.pyts$ PK%L]?rpc/testnu[: ${PYTHON=python} : ${SERVER=charon.cwi.nl} set -xe $PYTHON -c 'from rpc import test; test()' $PYTHON -c 'from rpc import test; test()' ${SERVER} $PYTHON -c 'from rpc import testsvr; testsvr()' & PID=$! sleep 2 $PYTHON -c 'from rpc import testclt; testclt()' kill -2 $PID $PYTHON -c 'from mountclient import test; test()' $PYTHON -c 'from mountclient import test; test()' gatekeeper.dec.com $PYTHON -c 'from nfsclient import test; test()' $PYTHON -c 'from nfsclient import test; test()' gatekeeper.dec.com $PYTHON -c 'from nfsclient import test; test()' gatekeeper.dec.com /archive $PYTHON -c 'from rnusersclient import test; test()' '' $PYTHON -c 'from rpc import testbcast; testbcast()' PK%L] 6O<  rpc/rnusersclient.pyonu[ ^c@sddlZddlmZmZmZmZdefdYZdefdYZdddYZd eefd YZd eefd YZ d Z dZ dZ e dS(iN(tPackertUnpackert UDPClienttBroadcastUDPClientt RnusersPackercBs#eZdZdZdZRS(cCsJt\}}}}|j||j||j||j|dS(N(tutmpt pack_stringtpack_int(tselftuitut_linetut_nametut_hosttut_time((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pyt pack_utmps    cCs*|\}}|jt|j|dS(N(Rtui_utmpt pack_uint(RR tui_itmptui_idle((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pyt pack_utmpidles  cCs|j||jdS(N(t pack_arrayt pack_itmpidle(Rtlist((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pytpack_utmpidlearrs(t__name__t __module__RRR(((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pyRs  tRnusersUnpackercBs#eZdZdZdZRS(cCs@|j}|j}|j}|j}||||fS(N(t unpack_stringt unpack_int(RR R R R ((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pyt unpack_utmps     cCs"|j}|j}||fS(N(Rt unpack_uint(RRR((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pytunpack_utmpidles  cCs|j|jS(N(t unpack_arrayR(R((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pytunpack_utmpidlearr!s(RRRRR!(((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pyRs  tPartialRnusersClientcBs,eZdZdZdZdZRS(cCst|_td|_dS(Nt(RtpackerRtunpacker(R((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pyt addpackers's cCs|jddd|jjS(Ni(t make_calltNoneR%R(R((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pytNum+scCs|jddd|jjS(Ni(R'R(R%R!(R((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pytNames.s cCs|jddd|jjS(Ni(R'R(R%R!(R((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pytAllnames2s (RRR&R)R*R+(((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pyR"%s   t RnusersClientcBseZdZRS(cCstj||dddS(Nii(Rt__init__(Rthost((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pyR-9s(RRR-(((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pyR,7stBroadcastRnusersClientcBseZdZRS(cCstj||dddS(Nii(RR-(Rt bcastaddr((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pyR-?s(RRR-(((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pyR/=scCsddl}|jds$tdS|jd}t|}|j}x\|D]T\\}}}}}t|}t|}t|}d|||||fGHqPWdS(Niis%r %r %r %s %s(tsystargvt testbcastR,R*tstrip0(R1R.tcRtlinetnamettimetidle((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pyttestCs        cCsAtd}d}|j||j}dGt|GHdS(Ns cSsF|\}}|dGx*|D]"\\}}}}}t|GqWHdS(Ns :(R4(RtfromaddrR.tportR6R7R8R9((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pytlistitTs  s Total Count:(R/tset_reply_handlerR*tlen(R5R=tall((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pyR3Rs     cCs+x$|r&|ddkr&|d }qW|S(Nis((ts((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pyR4^s(( trpcRRRRRRR"R,R/R:R3R4(((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pyts "  PK%L]: rpc/T.pycnu[ ^c@s:ddlZddlZddlZdZdZdS(iNcCs9tj\}}}}||||tjfadS(N(tosttimesttimett0(tutstcutcs((s"/usr/lib64/python2.7/Demo/rpc/T.pytTSTARTsc Gstj\}}}}||||tjfag}x-tdD]}|jt|t|qHW|\}}}d}x|D]} || d}qW|d|||f}tjj |dS(Nitt s%r user, %r sys, %r real ( RRRtt1trangetappendRtsyststderrtwrite( tlabelRRRRttttitrtmsgtx((s"/usr/lib64/python2.7/Demo/rpc/T.pytTSTOP s (RRRRR(((s"/usr/lib64/python2.7/Demo/rpc/T.pyts$ PK%L]XPPrpc/mountclient.pycnu[ ^c@sddlZddlmZmZmZmZdZdZdZdefdYZdefd YZ d dd YZ d e efd YZ de efdYZ dZ dS(iN(tPackertUnpackert TCPClientt UDPClientiii t MountPackercBseZdZRS(cCs|jt|dS(N(t pack_fopaquetFHSIZE(tselftfhandle((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pyt pack_fhandles(t__name__t __module__R (((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pyRst MountUnpackercBsGeZdZdZdZdZdZdZdZRS(cCs |jtS(N(tunpack_fopaqueR(R((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pytunpack_fhandle*scCs7|j}|dkr'|j}nd}||fS(Ni(t unpack_uintRtNone(Rtstatustfh((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pytunpack_fhstatus-s   cCs|j|jS(N(t unpack_listtunpack_mountstruct(R((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pytunpack_mountlist5scCs"|j}|j}||fS(N(t unpack_string(Rthostnamet directory((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pyR8s  cCs|j|jS(N(Rtunpack_exportstruct(R((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pytunpack_exportlist=scCs"|j}|j}||fS(N(Rt unpack_groups(Rtfilesystgroups((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pyR@s  cCs|j|jS(N(RR(R((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pyREs( R R RRRRRRR(((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pyR (s      tPartialMountClientcBsPeZdZdZdZdZdZdZdZdZ RS(cCst|_td|_dS(Nt(RtpackerR tunpacker(R((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pyt addpackersPs cCsnddl}y|j}Wntk r5d}nX|dkrZtj|jd}n|jjddS(NiiiR (R i(tostgetuidtAttributeErrortrpct bindresvporttsocktbind(RR$tuidtport((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pyt bindsocketXs    cCs1|jdkr*tjtjf|_n|jS(N(tcredRR't AUTH_UNIXtmake_auth_unix_default(R((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pytmkcredfscCs"|jd||jj|jjS(Ni(t make_callR!t pack_stringR"R(RR((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pytMnts  cCs|jddd|jjS(Ni(R2RR"R(R((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pytDumps cCs|jd||jjdS(Ni(R2R!R3R(RR((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pytUmnts cCs|jddddS(Ni(R2R(R((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pytUmntallscCs|jddd|jjS(Ni(R2RR"R(R((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pytExports ( R R R#R-R1R4R5R6R7R8(((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pyRLs   #    tTCPMountClientcBseZdZRS(cCstj||ttdS(N(Rt__init__t MOUNTPROGt MOUNTVERS(Rthost((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pyR:s(R R R:(((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pyR9stUDPMountClientcBseZdZRS(cCstj||ttdS(N(RR:R;R<(RR=((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pyR:s(R R R:(((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pyR>scCsddl}|jdr?|jddkr?t}|jd=n9|jdrr|jddkrrt}|jd=nt}|jdr|jd}nd}||}|j}xK|D]C}|GHy|j|dWndGHqnX|j|dqWdS(Niis-ts-uR itSorry(tsystargvR9R>R8R4R6(R@tCR=tmcltlisttitem((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pyttests*         ((R'RRRRR;R<RRR RR9R>RF(((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pyt s " $W PK%L] 6O<  rpc/rnusersclient.pycnu[ ^c@sddlZddlmZmZmZmZdefdYZdefdYZdddYZd eefd YZd eefd YZ d Z dZ dZ e dS(iN(tPackertUnpackert UDPClienttBroadcastUDPClientt RnusersPackercBs#eZdZdZdZRS(cCsJt\}}}}|j||j||j||j|dS(N(tutmpt pack_stringtpack_int(tselftuitut_linetut_nametut_hosttut_time((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pyt pack_utmps    cCs*|\}}|jt|j|dS(N(Rtui_utmpt pack_uint(RR tui_itmptui_idle((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pyt pack_utmpidles  cCs|j||jdS(N(t pack_arrayt pack_itmpidle(Rtlist((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pytpack_utmpidlearrs(t__name__t __module__RRR(((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pyRs  tRnusersUnpackercBs#eZdZdZdZRS(cCs@|j}|j}|j}|j}||||fS(N(t unpack_stringt unpack_int(RR R R R ((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pyt unpack_utmps     cCs"|j}|j}||fS(N(Rt unpack_uint(RRR((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pytunpack_utmpidles  cCs|j|jS(N(t unpack_arrayR(R((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pytunpack_utmpidlearr!s(RRRRR!(((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pyRs  tPartialRnusersClientcBs,eZdZdZdZdZRS(cCst|_td|_dS(Nt(RtpackerRtunpacker(R((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pyt addpackers's cCs|jddd|jjS(Ni(t make_calltNoneR%R(R((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pytNum+scCs|jddd|jjS(Ni(R'R(R%R!(R((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pytNames.s cCs|jddd|jjS(Ni(R'R(R%R!(R((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pytAllnames2s (RRR&R)R*R+(((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pyR"%s   t RnusersClientcBseZdZRS(cCstj||dddS(Nii(Rt__init__(Rthost((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pyR-9s(RRR-(((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pyR,7stBroadcastRnusersClientcBseZdZRS(cCstj||dddS(Nii(RR-(Rt bcastaddr((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pyR-?s(RRR-(((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pyR/=scCsddl}|jds$tdS|jd}t|}|j}x\|D]T\\}}}}}t|}t|}t|}d|||||fGHqPWdS(Niis%r %r %r %s %s(tsystargvt testbcastR,R*tstrip0(R1R.tcRtlinetnamettimetidle((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pyttestCs        cCsAtd}d}|j||j}dGt|GHdS(Ns cSsF|\}}|dGx*|D]"\\}}}}}t|GqWHdS(Ns :(R4(RtfromaddrR.tportR6R7R8R9((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pytlistitTs  s Total Count:(R/tset_reply_handlerR*tlen(R5R=tall((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pyR3Rs     cCs+x$|r&|ddkr&|d }qW|S(Nis((ts((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pyR4^s(( trpcRRRRRRR"R,R/R:R3R4(((s./usr/lib64/python2.7/Demo/rpc/rnusersclient.pyts "  PK%L]"zrpc/nfsclient.pynu[# NFS RPC client -- RFC 1094 # XXX This is not yet complete. # XXX Only GETATTR, SETTTR, LOOKUP and READDIR are supported. # (See mountclient.py for some hints on how to write RPC clients in # Python in general) import rpc from rpc import UDPClient, TCPClient from mountclient import FHSIZE, MountPacker, MountUnpacker NFS_PROGRAM = 100003 NFS_VERSION = 2 # enum stat NFS_OK = 0 # (...many error values...) # enum ftype NFNON = 0 NFREG = 1 NFDIR = 2 NFBLK = 3 NFCHR = 4 NFLNK = 5 class NFSPacker(MountPacker): def pack_sattrargs(self, sa): file, attributes = sa self.pack_fhandle(file) self.pack_sattr(attributes) def pack_sattr(self, sa): mode, uid, gid, size, atime, mtime = sa self.pack_uint(mode) self.pack_uint(uid) self.pack_uint(gid) self.pack_uint(size) self.pack_timeval(atime) self.pack_timeval(mtime) def pack_diropargs(self, da): dir, name = da self.pack_fhandle(dir) self.pack_string(name) def pack_readdirargs(self, ra): dir, cookie, count = ra self.pack_fhandle(dir) self.pack_uint(cookie) self.pack_uint(count) def pack_timeval(self, tv): secs, usecs = tv self.pack_uint(secs) self.pack_uint(usecs) class NFSUnpacker(MountUnpacker): def unpack_readdirres(self): status = self.unpack_enum() if status == NFS_OK: entries = self.unpack_list(self.unpack_entry) eof = self.unpack_bool() rest = (entries, eof) else: rest = None return (status, rest) def unpack_entry(self): fileid = self.unpack_uint() name = self.unpack_string() cookie = self.unpack_uint() return (fileid, name, cookie) def unpack_diropres(self): status = self.unpack_enum() if status == NFS_OK: fh = self.unpack_fhandle() fa = self.unpack_fattr() rest = (fh, fa) else: rest = None return (status, rest) def unpack_attrstat(self): status = self.unpack_enum() if status == NFS_OK: attributes = self.unpack_fattr() else: attributes = None return status, attributes def unpack_fattr(self): type = self.unpack_enum() mode = self.unpack_uint() nlink = self.unpack_uint() uid = self.unpack_uint() gid = self.unpack_uint() size = self.unpack_uint() blocksize = self.unpack_uint() rdev = self.unpack_uint() blocks = self.unpack_uint() fsid = self.unpack_uint() fileid = self.unpack_uint() atime = self.unpack_timeval() mtime = self.unpack_timeval() ctime = self.unpack_timeval() return (type, mode, nlink, uid, gid, size, blocksize, \ rdev, blocks, fsid, fileid, atime, mtime, ctime) def unpack_timeval(self): secs = self.unpack_uint() usecs = self.unpack_uint() return (secs, usecs) class NFSClient(UDPClient): def __init__(self, host): UDPClient.__init__(self, host, NFS_PROGRAM, NFS_VERSION) def addpackers(self): self.packer = NFSPacker() self.unpacker = NFSUnpacker('') def mkcred(self): if self.cred is None: self.cred = rpc.AUTH_UNIX, rpc.make_auth_unix_default() return self.cred def Getattr(self, fh): return self.make_call(1, fh, \ self.packer.pack_fhandle, \ self.unpacker.unpack_attrstat) def Setattr(self, sa): return self.make_call(2, sa, \ self.packer.pack_sattrargs, \ self.unpacker.unpack_attrstat) # Root() is obsolete def Lookup(self, da): return self.make_call(4, da, \ self.packer.pack_diropargs, \ self.unpacker.unpack_diropres) # ... def Readdir(self, ra): return self.make_call(16, ra, \ self.packer.pack_readdirargs, \ self.unpacker.unpack_readdirres) # Shorthand to get the entire contents of a directory def Listdir(self, dir): list = [] ra = (dir, 0, 2000) while 1: (status, rest) = self.Readdir(ra) if status <> NFS_OK: break entries, eof = rest last_cookie = None for fileid, name, cookie in entries: list.append((fileid, name)) last_cookie = cookie if eof or last_cookie is None: break ra = (ra[0], last_cookie, ra[2]) return list def test(): import sys if sys.argv[1:]: host = sys.argv[1] else: host = '' if sys.argv[2:]: filesys = sys.argv[2] else: filesys = None from mountclient import UDPMountClient, TCPMountClient mcl = TCPMountClient(host) if filesys is None: list = mcl.Export() for item in list: print item return sf = mcl.Mnt(filesys) print sf fh = sf[1] if fh: ncl = NFSClient(host) attrstat = ncl.Getattr(fh) print attrstat list = ncl.Listdir(fh) for item in list: print item mcl.Umnt(filesys) PK%L] x}vv rpc/rpc.pyonu[ ^c@s=ddlZddlZddlZdZdZdZdZdZdZdZ dZ dZ dZ dZ dZdZdZdZdZdZdZdZdZdZdejfd YZd efd YZd efd YZdefdYZdejfdYZdZdZdZ da!dZ"ddCdYZ#dZ$dZ%dZ&dZ'da)dZ*de#fdYZ+de#fd YZ,d!e,fd"YZ-d#Z.dZ/d$Z0dZ1dZ2dZ3dZ4dZ5dZ6d%Z7d&Z8d'efd(YZ9d)efd*YZ:d+dDd,YZ;d-e;e+fd.YZ<d/e;e,fd0YZ=d1e;e-fd2YZ>d3e+fd4YZ?d5e,fd6YZ@d7e#fd8YZAd9dEd:YZBd;eBfd<YZCd=eBfd>YZDd?ZEd@ZFdAZGdBZHdS(FiNiiiiiitPackercBs,eZdZdZdZdZRS(cCs*|\}}|j||j|dS(N(t pack_enumt pack_opaque(tselftauthtflavortstuff((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyt pack_auth0s  cCsi|j||j||j||j||jt|x|D]}|j|qNWdS(N(t pack_uintt pack_stringtlen(Rtstampt machinenametuidtgidtgidsti((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytpack_auth_unix5s     cCsl|j||jt|jt|j||j||j||j||j|dS(N(RRtCALLt RPCVERSIONR(Rtxidtprogtverstproctcredtverf((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytpack_callheader>s       cCsE|j||jt|jt|j||jtdS(N(RRtREPLYt MSG_ACCEPTEDRtSUCCESS(RRR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytpack_replyheaderIs     (t__name__t __module__RRRR(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR.s  t BadRPCFormatcBseZRS((RR (((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR!Sst BadRPCVersioncBseZRS((RR (((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR"Tst GarbageArgscBseZRS((RR (((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR#UstUnpackercBs#eZdZdZdZRS(cCs"|j}|j}||fS(N(t unpack_enumt unpack_opaque(RRR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyt unpack_authYs  cCs|j}|j}|tkr7td|fn|j}|tkrbtd|fn|j}|j}|j}|j}|j}||||||fS(Nsno CALL but %rsbad RPC version %r(t unpack_uintR%RR!RR"R'(RRttempRRRRR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytunpack_callheader^s          cCs|j}|j}|tkr7td|fn|j}|tkr|j}|tkr|j}|j}td||ffn|tkr|j}td|fntd|fn|tkrtd|fn|j}|j}|t kr%tdn|t krb|j}|j}td||ffn|t krztdn|t krtd n|t krtd |fn||fS( Nsno REPLY but %rsMSG_DENIED: RPC_MISMATCH: %rsMSG_DENIED: AUTH_ERROR: %rsMSG_DENIED: %rs'Neither MSG_DENIED nor MSG_ACCEPTED: %rscall failed: PROG_UNAVAILscall failed: PROG_MISMATCH: %rscall failed: PROC_UNAVAILscall failed: GARBAGE_ARGSscall failed: %r(R(R%Rt RuntimeErrort MSG_DENIEDt RPC_MISMATCHt AUTH_ERRORRR't PROG_UNAVAILt PROG_MISMATCHt PROC_UNAVAILt GARBAGE_ARGSR(RRtmtypetstattlowthighR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytunpack_replyheadernsH                        (RR R'R*R7(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR$Ws  cCsdS(Nt((((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytmake_auth_nullscCs,t}|j||||||jS(N(RRtget_buf(tseedthostR Rtgroupstp((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytmake_auth_unixs cCsy,ddlm}m}|}|}Wntk rId}}nXddl}tt|jttj ||gS(Ni(tgetuidtgetgidi( tosR@RAt ImportErrorttimeR?tintt unix_epochtsockett gethostname(R@RAR RRD((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytmake_auth_unix_defaults    c CstdkrtSddl}|j}|j|}|j|}|j||j|}d \}}}}} } t| |d\}} t| |d\}} t||d\}}||}|j||||| | dddf adG|jtGHtS( s9Very painful calculation of when the Unix Epoch is. This is defined as the return value of time.time() on Jan 1st, 1970, 00:00:00 GMT. On a Unix system, this should always return 0.0. On a Mac, the calculations are needed -- and hard because of integer overflow and other limitations. iiNiii<is Unix epoch:(iiiiii(t _unix_epochRDt localtimetgmtimetmktimetdivmodtctime( RDtnowtlocalttgmttoffsettytmtdthhtmmtss((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRFs    *tClientcBsteZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z RS( cCsk||_||_||_||_|j|j|jd|_|jd|_ d|_ dS(Ni( R<RRtportt makesockett bindsockett connsockettlastxidt addpackerstNoneRR(RR<RRR[((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyt__init__s          cCs|jjdS(N(tsocktclose(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRdscCs tddS(Nsmakesocket not defined(R+(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR\scCs |jj|j|jfdS(N(RctconnectR<R[(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR^scCs|jjddS(NR8i(R8i(Rctbind(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR]scCst|_td|_dS(NR8(RtpackerR$tunpacker(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR`s cCsw|dkr$|dk r$tdn|j||rD||n|j|r`|}nd}|jj|S(Ns!non-null args with null pack_func(Rat TypeErrort start_calltdo_callRhtdone(RRtargst pack_funct unpack_functresult((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyt make_calls      cCse|jd|_}|j}|j}|j}|j|j||j|j|||dS(Ni(R_tmkcredtmkverfRgtresetRRR(RRRRRR>((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRjs     cCs tddS(Nsdo_call not defined(R+(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRkscCs+|jdkr$ttf|_n|jS(N(RRat AUTH_NULLR9(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRr scCs+|jdkr$ttf|_n|jS(N(RRaRuR9(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRsscCs|jddddS(Ni(RqRa(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytcall_0s(RR RbRdR\R^R]R`RqRjRkRrRsRv(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRZs         cCst|}|r|dB}ntt|d?d@tt|d?d@tt|d?d@tt|d@}|j||dS(Nliiii(R tchrREtsend(Rctlasttfragtxtheader((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytsendfrags   ^cCst|d|dS(Ni(R}(Rctrecord((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyt sendrecord"scCs|jd}t|dkr*tntt|dd>t|dd>Bt|dd>Bt|dB}|d @dk}t|d @}d }xH|dkr|j|}|stn|t|}||}qW||fS( NiiiiiiiiIiR8(trecvR tEOFErrortlongtordRE(RcR|R{RytnRztbuf((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytrecvfrag%s L cCs9d}d}x&|s4t|\}}||}qW|S(NR8i(R(RcR~RyRz((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyt recvrecord5s  cCsd\}}tdkr?ddl}||j||anxtt|t|tD]g}|ay|j||ftSWq\tjk r\}}|dkrtj||fqq\Xq\WtddS(NiXiiirscan't assign reserved port(iXi( tlast_resv_port_triedRaRBtgetpidtrangeRfRGterrorR+(RcR<tFIRSTtLASTRBRterrnotmsg((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyt bindresvportAs    t RawTCPClientcBseZdZdZRS(cCstjtjtj|_dS(N(RGtAF_INETt SOCK_STREAMRc(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR\WscCs|jj}t|j|t|j}|j}|j||j\}}||jkr~t d||jfndS(Ns#wrong xid in reply %r instead of %r( RgR:RRcRRhRtR7R_R+(RtcalltreplytuRR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRkZs  (RR R\Rk(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRUs t RawUDPClientcBseZdZdZRS(cCstjtjtj|_dS(N(RGRt SOCK_DGRAMRc(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR\ksc Cs`|jj}|jj|yddlm}Wntk rQdGHd}nXd}d}d}x|jggg}}}|r|||||\}}}n|j|kr|d}|dkrtdn|d kr|d }n|jj|qgn|jj|} |j } | j | | j \} } | |j krWqgnPqgWdS( Ni(tselects'WARNING: select not found, RPC may hangi iiittimeoutii( RgR:RcRxRRCRaR+RRhRtR7R_( RRRtBUFSIZERtcounttrtwR{RRRR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRkns:  !     (RR R\Rk(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRis tRawBroadcastUDPClientcBs5eZdZdZdZdZdZRS(cCs/tj|||||d|_d|_dS(Ni(RRbRat reply_handlerR(Rt bcastaddrRRR[((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRbs cCs |jjtjtjddS(Ni(Rct setsockoptRGt SOL_SOCKETt SO_BROADCAST(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR^scCs ||_dS(N(R(RR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytset_reply_handlerscCs ||_dS(N(R(RR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyt set_timeoutscCs|dkr$|dk r$tdn|j||rD||n|jj}|jj||j|jfyddl m }Wnt k rdGHd}nXd}g}|dkrd} | }nx"|jggg} } } |rC|j dkr|| | | \} } } qC|| | | |j \} } } n|j| krVPn|jj |\} }|j }|j| |j\}}||jkrqn|} |j j|j| |f|jr|j| |qqW|S(Ns!non-null args with null pack_funci(Rs.WARNING: select not found, broadcast will hangi cSsdS(N((((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytdummyR8(RaRiRjRgR:RctsendtoR<R[RRCRtrecvfromRhRtR7R_RltappendR(RRRmRnRoRRRtrepliesRRRR{RtfromaddrRRR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRqsJ        $     (RR RbR^RRRq(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRs     iioiitPortMapperPackercBs#eZdZdZdZRS(cCsJ|\}}}}|j||j||j||j|dS(N(R(RtmappingRRtprotR[((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyt pack_mappings    cCs|j||jdS(N(t pack_listR(Rtlist((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyt pack_pmaplistscCsJ|\}}}}|j||j||j||j|dS(N(RR(RtcaRRRRm((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytpack_call_argss    (RR RRR(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRs  tPortMapperUnpackercBs#eZdZdZdZRS(cCs@|j}|j}|j}|j}||||fS(N(R((RRRRR[((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytunpack_mappings     cCs|j|jS(N(t unpack_listR(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytunpack_pmaplistscCs"|j}|j}||fS(N(R(R&(RR[tres((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytunpack_call_results  (RR RRR(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRs  tPartialPortMapperClientcBs>eZdZdZdZdZdZdZRS(cCst|_td|_dS(NR8(RRgRRh(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR`s cCs"|jt||jj|jjS(N(Rqt PMAPPROC_SETRgRRhR((RR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytSets  cCs"|jt||jj|jjS(N(RqtPMAPPROC_UNSETRgRRhR((RR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytUnsets  cCs"|jt||jj|jjS(N(RqtPMAPPROC_GETPORTRgRRhR((RR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytGetports  cCs|jtdd|jjS(N(Rqt PMAPPROC_DUMPRaRhR(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytDump!s cCs"|jt||jj|jjS(N(RqtPMAPPROC_CALLITRgRRhR(RR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytCallit&s  (RR R`RRRRR(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR s      tTCPPortMapperClientcBseZdZRS(cCstj||tttdS(N(RRbt PMAP_PROGt PMAP_VERSt PMAP_PORT(RR<((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRb.s (RR Rb(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR,stUDPPortMapperClientcBseZdZRS(cCstj||tttdS(N(RRbRRR(RR<((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRb5s (RR Rb(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR3stBroadcastUDPPortMapperClientcBseZdZRS(cCstj||tttdS(N(RRbRRR(RR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRb=s (RR Rb(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR:st TCPClientcBseZdZRS(cCsft|}|j||tdf}|j|dkrItdntj|||||dS(Nisprogram not registered(RRt IPPROTO_TCPRdR+RRb(RR<RRtpmapR[((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRbFs     (RR Rb(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRDst UDPClientcBseZdZRS(cCsft|}|j||tdf}|j|dkrItdntj|||||dS(Nisprogram not registered(RRt IPPROTO_UDPRdR+RRb(RR<RRRR[((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRbQs     (RR Rb(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyROstBroadcastUDPClientcBs>eZdZdZdZdZdZdZRS(cCsKt||_|jj|j||_||_d|_|jdS(N( RRRtmy_reply_handlerRRRatuser_reply_handlerR`(RRRR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRb\s    cCs|jjdS(N(RRd(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRddscCs ||_dS(N(R(RR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRgscCs|jj|dS(N(RR(RR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRjscCsq|\}}|jj||j}|jj|jj||f|jdk rm|j||ndS(N(RhRtRoRlRRRRa(RRRR[RRp((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRms   cCs|jj|r ||n|dkrAd}||_n ||_g|_|jj}|jj|j|j ||f}|jS(NcSsdS(N((((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR{R8( RgRtRaRoRR:RRRR(RRRmRnRoRt packed_argst dummy_replies((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRqvs        (RR RbRdRRRRq(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRZs      tServercBsYeZdZdZdZdZdZdZdZdZ dZ RS( cCsa||_||_||_||_|j|j|jj\|_|_|jdS(N( R<RRR[R\R]Rct getsocknameR`(RR<RRR[((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRbs      cCsL|j|j|j|jf}t|j}|j|sHtdndS(Nsregister failed(RRRR[RR<RR+(RRR>((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytregisterscCsL|j|j|j|jf}t|j}|j|sHtdndS(Nsunregister failed(RRRR[RR<RR+(RRR>((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyt unregistersc Cs|jj||jj|jj}|jj||jj}|tkr[dS|jjt|jj}|t kr|jjt |jjt |jjt |jjt |jj S|jjt |jjttf|jj}||jkr7|jjt|jj S|jj}||jkr|jjt|jj|j|jj|j|jj S|jj}dt|}yt||}Wn+tk r|jjt|jj SX|jj} |jj} y |Wn}ttfk r|jj|jj||jjt|jjt |jjttf|jjtnX|jj S(Nthandle_(RhRtRgR(RR%RRaRRR,R-R:RRRuR9RR/RR0treprtgetattrtAttributeErrorR1R'RR#R2( RRRR)RRRtmethnametmethRR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pythandles\         cCs?y|jjWntk r*tnX|jjtdS(N(RhRlR+R#RgRR(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyt turn_arounds   cCs|jdS(N(R(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pythandle_0scCs tddS(Nsmakesocket not defined(R+(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR\scCs |jj|j|jfdS(N(RcRfR<R[(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR]scCst|_td|_dS(NR8(RRgR$Rh(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR`s ( RR RbRRRRRR\R]R`(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRs   3    t TCPServercBs5eZdZdZdZdZdZRS(cCs(tjtjtj|_t|_dS(N(RGRRRcRR(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR\scCs1|jjdx|j|jjqWdS(Ni(Rctlistentsessiontaccept(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytloopscCs|\}\}}xsyt|}Wn1tk r9Pn tjk rX}dG|GHPnX|j|}|dk rt||qqWdS(Ns socket error:(RRRGRRRaR(Rt connectionRcR<R[RRR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRs   cCs1|jjdx|j|jjqWdS(Ni(RcRt forksessionR(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyt forkingloopscCsddl}y#x|jdd\}}qWWn|jk rEnXd}z5|j}|rs|djdS|j|Wd|dkr|jdnXdS(Niii(RBtwaitpidRRatforkRdRt_exit(RRRBtpidtsts((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR s    (RR R\RRRR(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRs     t UDPServercBs#eZdZdZdZRS(cCs(tjtjtj|_t|_dS(N(RGRRRcRR(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR\&scCsx|jqWdS(N(R(R((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR*scCsM|jjd\}}|j|}|dk rI|jj||ndS(Ni (RcRRRaR(RRt host_portR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR.s (RR R\RR(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR$s  cCsztd}|j}|jxQ|D]I\}}}}|G|G|tkrVdGn|tkridGn|G|GHq)WdS(NR8ttcptudp(RRtsortRR(RRRRRR[((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyttest7s     cCs}ddl}|jdr)|jd}nd}d}t|}|j||jd|jddtdf}dS(Niis cSs#|\}}|dt|GHdS(Ns (R(RRR<R[((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytrhKs iii(tsystargvRRRRR(RRRRR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyt testbcastEs      cCsdtfdY}|dddd}y|jWn tk r[}dG|GdGHnX|jd GHz|jWd|jd GHXdS( NtScBseZdZRS(cSs@|jj}|jdGt|GH|jj||dS(NsRPC function 1 called, arg(Rht unpack_stringRRRgR (Rtarg((s$/usr/lib64/python2.7/Demo/rpc/rpc.pythandle_1\s (RR R(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyR[sR8i iis RuntimeError:s (ignored)sService started...sService interrupted.(RRR+RR(RtsR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyttestsvrYs  cCs~ddl}|jdr)|jd}nd}dtfdY}||dd}dGH|jd}d Gt|GHdS( NiiR8tCcBseZdZRS(cSs"|jd||jj|jjS(Ni(RqRgR RhR(RR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pytcall_1vs  (RR R(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyRusi smaking call...shello, world, s call returned(RRRRR(RR<RtcR((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyttestcltps  ((((ItxdrRGRBRRRRut AUTH_UNIXt AUTH_SHORTtAUTH_DESRR,RR/R0R1R2R-R.t AUTH_BADCREDtAUTH_REJECTEDCREDt AUTH_BADVERFtAUTH_REJECTEDVERFt AUTH_TOOWEAKRt ExceptionR!R"R#R$R9R?RIRJRFRZR}RRRRaRRRRRRRRt PMAPPROC_NULLRRRRRRRRRRRRRRRRRRRRRRR(((s$/usr/lib64/python2.7/Demo/rpc/rpc.pyt s   %A    Q     '>     1c6   PK%L] rpc/xdr.pyonu[ ^c@s`yddlZWnek r)dZnXedZdddYZdddYZdS( iNltPackercBseZdZdZdZdZerTejdddkrTdZneZeZ dZ d Z e Z d Z d Zd ZeZd ZeZdZdZdZRS(cCs|jdS(N(treset(tself((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt__init__scCs d|_dS(Nt(tbuf(R((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyRscCs|jS(N(R(R((s$/usr/lib64/python2.7/Demo/rpc/xdr.pytget_bufscCsl|jtt|d?d@tt|d?d@tt|d?d@tt|d@|_dS(Niiii(Rtchrtint(Rtx((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt pack_uintstliscCsMt|tkr-t|ddd}n|jtjd||_dS(NllR (ttypetLongRRtstructtpack(RR ((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyR s cCs-|r|jd|_n|jd|_dS(Nss(R(RR ((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt pack_bool'scCs6|jt|d?d@|jt|d@dS(Ni I(R R(RR ((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt pack_uhyper+scCs |jtjd||_dS(Ntf(RRR(RR ((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt pack_float1scCs |jtjd||_dS(Ntd(RRR(RR ((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt pack_double5scCs`|dkrtdn|ddd}|| }||t|d}|j||_dS(Nis fstring size must be nonnegativeiis(t ValueErrortlenR(Rtntstdata((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt pack_fstring9s    cCs-t|}|j||j||dS(N(RR R(RRR((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt pack_stringCs  cCs9x%|D]}|jd||qW|jddS(Nii(R (Rtlistt pack_itemtitem((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt pack_listJs  cCs=t||krtdnx|D]}||q%WdS(Nswrong array size(RR(RRRRR((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt pack_farrayPs  cCs0t|}|j||j|||dS(N(RR R!(RRRR((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt pack_arrayVs  (t__name__t __module__RRRR RRtpack_intt pack_enumRRt pack_hyperRRRt pack_fopaqueRt pack_opaqueR R!R"(((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyR s(             tUnpackercBseZdZdZdZdZerTejdddkrTdZndZeZ eZ d Z d Z d Z d Zd ZeZdZeZdZdZdZRS(cCs|j|dS(N(R(RR((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyR^scCs||_d|_dS(Ni(Rtpos(RR((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyRas cCs(|jt|jkr$tdndS(Nsunextracted data remains(R+RRt RuntimeError(R((s$/usr/lib64/python2.7/Demo/rpc/xdr.pytdoneescCs|j}|d|_}|j||!}t|dkrEtntt|dd>t|dd>Bt|dd>Bt|dB}|d krt|}n|S( Niiiiiiiil(R+RRtEOFErrortlongtordR(RtitjRR ((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt unpack_uintis  L R sicCsU|j}|d|_}|j||!}t|dkrEtntjd|S(NiR (R+RRR.Rtunpack(RR1R2R((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyR3vs   cCs/|j}|dkr%|d}nt|S(Nll(R3R(RR ((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt unpack_int~s  cCs*|j}|j}t|d>|BS(Ni (R3R/(Rthitlo((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt unpack_uhypers  cCs)|j}|dkr%|d}n|S(Nll(R8(RR ((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt unpack_hypers  cCsY|j}|d|_}|j||!}t|dkrEtntjd|dS(NiRi(R+RRR.RR4(RR1R2R((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt unpack_floats   cCsY|j}|d|_}|j||!}t|dkrEtntjd|dS(NiRi(R+RRR.RR4(RR1R2R((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt unpack_doubles   cCsp|dkrtdn|j}||ddd}|t|jkrUtn||_|j|||!S(Nis fstring size must be nonnegativeii(RR+RRR.(RRR1R2((s$/usr/lib64/python2.7/Demo/rpc/xdr.pytunpack_fstrings     cCs|j}|j|S(N(R3R<(RR((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt unpack_strings cCsbg}xU|j}|dkr%Pn|dkrDtd|fn|}|j|q W|S(Niis0 or 1 expected, got %r(R3R,tappend(Rt unpack_itemRR R((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt unpack_lists    cCs1g}x$t|D]}|j|qW|S(N(trangeR>(RRR?RR1((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt unpack_farrayscCs|j}|j||S(N(R3RB(RR?R((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyt unpack_arrays (R#R$RRR-R3RR4R5t unpack_enumt unpack_boolR8R9R:R;R<tunpack_fopaqueR=t unpack_opaqueR@RBRC(((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyR*\s(           (((Rt ImportErrortNoneR R RR*(((s$/usr/lib64/python2.7/Demo/rpc/xdr.pyts    OPK%L]rrpc/nfsclient.pyonu[ ^c@sddlZddlmZmZddlmZmZmZdZdZdZ dZ dZ dZ dZ d Zd Zd efd YZd efdYZdefdYZdZdS(iN(t UDPClientt TCPClient(tFHSIZEt MountPackert MountUnpackeriiiiiiit NFSPackercBs5eZdZdZdZdZdZRS(cCs*|\}}|j||j|dS(N(t pack_fhandlet pack_sattr(tselftsatfilet attributes((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pytpack_sattrargss  cCsj|\}}}}}}|j||j||j||j||j||j|dS(N(t pack_uintt pack_timeval(RR tmodetuidtgidtsizetatimetmtime((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pyR$s     cCs*|\}}|j||j|dS(N(Rt pack_string(Rtdatdirtname((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pytpack_diropargs-s  cCs:|\}}}|j||j||j|dS(N(RR (RtraRtcookietcount((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pytpack_readdirargs2s  cCs*|\}}|j||j|dS(N(R (Rttvtsecstusecs((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pyR8s  (t__name__t __module__R RRRR(((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pyRs    t NFSUnpackercBs>eZdZdZdZdZdZdZRS(cCsU|j}|tkrE|j|j}|j}||f}nd}||fS(N(t unpack_enumtNFS_OKt unpack_listt unpack_entryt unpack_booltNone(Rtstatustentriesteoftrest((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pytunpack_readdirres@s   cCs1|j}|j}|j}|||fS(N(t unpack_uintt unpack_string(RtfileidRR((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pyR'Js   cCsO|j}|tkr?|j}|j}||f}nd}||fS(N(R$R%tunpack_fhandlet unpack_fattrR)(RR*tfhtfaR-((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pytunpack_diropresPs    cCs7|j}|tkr'|j}nd}||fS(N(R$R%R3R)(RR*R ((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pytunpack_attrstatZs   cCs|j}|j}|j}|j}|j}|j}|j}|j}|j} |j} |j} |j} |j} |j}||||||||| | | | | |fS(N(R$R/tunpack_timeval(RttypeRtnlinkRRRt blocksizetrdevtblockstfsidR1RRtctime((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pyR3bs               cCs"|j}|j}||fS(N(R/(RRR ((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pyR8ts  (R!R"R.R'R6R7R3R8(((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pyR#>s    t NFSClientcBsPeZdZdZdZdZdZdZdZdZ RS(cCstj||ttdS(N(Rt__init__t NFS_PROGRAMt NFS_VERSION(Rthost((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pyRA|scCst|_td|_dS(Nt(RtpackerR#tunpacker(R((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pyt addpackerss cCs1|jdkr*tjtjf|_n|jS(N(tcredR)trpct AUTH_UNIXtmake_auth_unix_default(R((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pytmkcredscCs"|jd||jj|jjS(Ni(t make_callRFRRGR7(RR4((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pytGetattrs  cCs"|jd||jj|jjS(Ni(RNRFR RGR7(RR ((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pytSetattrs  cCs"|jd||jj|jjS(Ni(RNRFRRGR6(RR((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pytLookups  cCs"|jd||jj|jjS(Ni(RNRFRRGR.(RR((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pytReaddirs  c Csg}|ddf}x|j|\}}|tkr=Pn|\}}d}x0|D](\} } } |j| | f| }qVW|s|dkrPn|d||df}qW|S(Niii(RRR%R)tappend( RRtlistRR*R-R+R,t last_cookieR1RR((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pytListdirs   ( R!R"RARHRMRORPRQRRRV(((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pyR@zs       c Cs#ddl}|jdr)|jd}nd}|jdrL|jd}nd}ddlm}m}||}|dkr|j}x|D] }|GHqWdS|j|}|GH|d} | rt|} | j | } | GH| j | }x|D] }|GHqW|j |ndS(NiiREi(tUDPMountClienttTCPMountClient( tsystargvR)t mountclientRWRXtExporttMntR@RORVtUmnt( RYRDtfilesysRWRXtmclRTtitemtsfR4tncltattrstat((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pyttests2           (RJRRR[RRRRBRCR%tNFNONtNFREGtNFDIRtNFBLKtNFCHRtNFLNKRR#R@Re(((s*/usr/lib64/python2.7/Demo/rpc/nfsclient.pyt s !<9PK%L]XPPrpc/mountclient.pyonu[ ^c@sddlZddlmZmZmZmZdZdZdZdefdYZdefd YZ d dd YZ d e efd YZ de efdYZ dZ dS(iN(tPackertUnpackert TCPClientt UDPClientiii t MountPackercBseZdZRS(cCs|jt|dS(N(t pack_fopaquetFHSIZE(tselftfhandle((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pyt pack_fhandles(t__name__t __module__R (((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pyRst MountUnpackercBsGeZdZdZdZdZdZdZdZRS(cCs |jtS(N(tunpack_fopaqueR(R((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pytunpack_fhandle*scCs7|j}|dkr'|j}nd}||fS(Ni(t unpack_uintRtNone(Rtstatustfh((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pytunpack_fhstatus-s   cCs|j|jS(N(t unpack_listtunpack_mountstruct(R((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pytunpack_mountlist5scCs"|j}|j}||fS(N(t unpack_string(Rthostnamet directory((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pyR8s  cCs|j|jS(N(Rtunpack_exportstruct(R((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pytunpack_exportlist=scCs"|j}|j}||fS(N(Rt unpack_groups(Rtfilesystgroups((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pyR@s  cCs|j|jS(N(RR(R((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pyREs( R R RRRRRRR(((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pyR (s      tPartialMountClientcBsPeZdZdZdZdZdZdZdZdZ RS(cCst|_td|_dS(Nt(RtpackerR tunpacker(R((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pyt addpackersPs cCsnddl}y|j}Wntk r5d}nX|dkrZtj|jd}n|jjddS(NiiiR (R i(tostgetuidtAttributeErrortrpct bindresvporttsocktbind(RR$tuidtport((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pyt bindsocketXs    cCs1|jdkr*tjtjf|_n|jS(N(tcredRR't AUTH_UNIXtmake_auth_unix_default(R((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pytmkcredfscCs"|jd||jj|jjS(Ni(t make_callR!t pack_stringR"R(RR((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pytMnts  cCs|jddd|jjS(Ni(R2RR"R(R((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pytDumps cCs|jd||jjdS(Ni(R2R!R3R(RR((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pytUmnts cCs|jddddS(Ni(R2R(R((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pytUmntallscCs|jddd|jjS(Ni(R2RR"R(R((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pytExports ( R R R#R-R1R4R5R6R7R8(((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pyRLs   #    tTCPMountClientcBseZdZRS(cCstj||ttdS(N(Rt__init__t MOUNTPROGt MOUNTVERS(Rthost((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pyR:s(R R R:(((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pyR9stUDPMountClientcBseZdZRS(cCstj||ttdS(N(RR:R;R<(RR=((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pyR:s(R R R:(((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pyR>scCsddl}|jdr?|jddkr?t}|jd=n9|jdrr|jddkrrt}|jd=nt}|jdr|jd}nd}||}|j}xK|D]C}|GHy|j|dWndGHqnX|j|dqWdS(Niis-ts-uR itSorry(tsystargvR9R>R8R4R6(R@tCR=tmcltlisttitem((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pyttests*         ((R'RRRRR;R<RRR RR9R>RF(((s,/usr/lib64/python2.7/Demo/rpc/mountclient.pyt s " $W PK%L]CCmetaclasses/Enum.pynu["""Enumeration metaclass. XXX This is very much a work in progress. """ import string class EnumMetaClass: """Metaclass for enumeration. To define your own enumeration, do something like class Color(Enum): red = 1 green = 2 blue = 3 Now, Color.red, Color.green and Color.blue behave totally different: they are enumerated values, not integers. Enumerations cannot be instantiated; however they can be subclassed. """ def __init__(self, name, bases, dict): """Constructor -- create an enumeration. Called at the end of the class statement. The arguments are the name of the new class, a tuple containing the base classes, and a dictionary containing everything that was entered in the class' namespace during execution of the class statement. In the above example, it would be {'red': 1, 'green': 2, 'blue': 3}. """ for base in bases: if base.__class__ is not EnumMetaClass: raise TypeError, "Enumeration base class must be enumeration" bases = filter(lambda x: x is not Enum, bases) self.__name__ = name self.__bases__ = bases self.__dict = {} for key, value in dict.items(): self.__dict[key] = EnumInstance(name, key, value) def __getattr__(self, name): """Return an enumeration value. For example, Color.red returns the value corresponding to red. XXX Perhaps the values should be created in the constructor? This looks in the class dictionary and if it is not found there asks the base classes. The special attribute __members__ returns the list of names defined in this class (it does not merge in the names defined in base classes). """ if name == '__members__': return self.__dict.keys() try: return self.__dict[name] except KeyError: for base in self.__bases__: try: return getattr(base, name) except AttributeError: continue raise AttributeError, name def __repr__(self): s = self.__name__ if self.__bases__: s = s + '(' + string.join(map(lambda x: x.__name__, self.__bases__), ", ") + ')' if self.__dict: list = [] for key, value in self.__dict.items(): list.append("%s: %s" % (key, int(value))) s = "%s: {%s}" % (s, string.join(list, ", ")) return s class EnumInstance: """Class to represent an enumeration value. EnumInstance('Color', 'red', 12) prints as 'Color.red' and behaves like the integer 12 when compared, but doesn't support arithmetic. XXX Should it record the actual enumeration rather than just its name? """ def __init__(self, classname, enumname, value): self.__classname = classname self.__enumname = enumname self.__value = value def __int__(self): return self.__value def __repr__(self): return "EnumInstance(%r, %r, %r)" % (self.__classname, self.__enumname, self.__value) def __str__(self): return "%s.%s" % (self.__classname, self.__enumname) def __cmp__(self, other): return cmp(self.__value, int(other)) # Create the base class for enumerations. # It is an empty enumeration. Enum = EnumMetaClass("Enum", (), {}) def _test(): class Color(Enum): red = 1 green = 2 blue = 3 print Color.red print dir(Color) print Color.red == Color.red print Color.red == Color.blue print Color.red == 1 print Color.red == 2 class ExtendedColor(Color): white = 0 orange = 4 yellow = 5 purple = 6 black = 7 print ExtendedColor.orange print ExtendedColor.red print Color.red == ExtendedColor.red class OtherColor(Enum): white = 4 blue = 5 class MergedColor(Color, OtherColor): pass print MergedColor.red print MergedColor.white print Color print ExtendedColor print OtherColor print MergedColor if __name__ == '__main__': _test() PK%L]yHmetaclasses/Eiffel.pyonu[ ^c@sdZddlmZmZmZdefdYZdefdYZdefdYZed d iZd Z e d kre nd S(sSupport Eiffel-style preconditions and postconditions. For example, class C: def m1(self, arg): require arg > 0 return whatever ensure Result > arg can be written (clumsily, I agree) as: class C(Eiffel): def m1(self, arg): return whatever def m1_pre(self, arg): assert arg > 0 def m1_post(self, Result, arg): assert Result > arg Pre- and post-conditions for a method, being implemented as methods themselves, are inherited independently from the method. This gives much of the same effect of Eiffel, where pre- and post-conditions are inherited when a method is overridden by a derived class. However, when a derived class in Python needs to extend a pre- or post-condition, it must manually merge the base class' pre- or post-condition with that defined in the derived class', for example: class D(C): def m1(self, arg): return arg**2 def m1_post(self, Result, arg): C.m1_post(self, Result, arg) assert Result < 100 This gives derived classes more freedom but also more responsibility than in Eiffel, where the compiler automatically takes care of this. In Eiffel, pre-conditions combine using contravariance, meaning a derived class can only make a pre-condition weaker; in Python, this is up to the derived class. For example, a derived class that takes away the requirement that arg > 0 could write: def m1_pre(self, arg): pass but one could equally write a derived class that makes a stronger requirement: def m1_pre(self, arg): require arg > 50 It would be easy to modify the classes shown here so that pre- and post-conditions can be disabled (separately, on a per-class basis). A different design would have the pre- or post-condition testing functions return true for success and false for failure. This would make it possible to implement automatic combination of inherited and new pre-/post-conditions. All this is left as an exercise to the reader. i(t MetaClasst MetaHelpertMetaMethodWrappertEiffelMethodWrappercBseZdZdZRS(cCstj|||yt||jd|_Wntk rLd|_nXyt||jd|_Wntk rd|_nXdS(Nt_pret_post(Rt__init__tgetattrt__name__tpretAttributeErrortNonetpost(tselftfunctinst((s//usr/lib64/python2.7/Demo/metaclasses/Eiffel.pyRDs   cOsh|jrt|j||nt|j|jf||}|jrdt|j|f||n|S(N(R tapplyRRR (R targstkwtResult((s//usr/lib64/python2.7/Demo/metaclasses/Eiffel.pyt__call__Ss   (Rt __module__RR(((s//usr/lib64/python2.7/Demo/metaclasses/Eiffel.pyRBs t EiffelHelpercBseZeZRS((RRRt__methodwrapper__(((s//usr/lib64/python2.7/Demo/metaclasses/Eiffel.pyR[stEiffelMetaClasscBseZeZRS((RRRt __helper__(((s//usr/lib64/python2.7/Demo/metaclasses/Eiffel.pyR^stEiffelcCs0dtfdY}|}|jddS(NtCcBs#eZdZdZdZRS(cSs|dS(Ni((R targ((s//usr/lib64/python2.7/Demo/metaclasses/Eiffel.pytm1fscSsdS(N((R R((s//usr/lib64/python2.7/Demo/metaclasses/Eiffel.pytm1_prehscSsdS(N((R RR((s//usr/lib64/python2.7/Demo/metaclasses/Eiffel.pytm1_postjs(RRRRR(((s//usr/lib64/python2.7/Demo/metaclasses/Eiffel.pyRes  i (RR(Rtx((s//usr/lib64/python2.7/Demo/metaclasses/Eiffel.pyt_testds t__main__N(( t__doc__tMetaRRRRRRRR!R(((s//usr/lib64/python2.7/Demo/metaclasses/Eiffel.pyt>s PK%L]]P]Pmetaclasses/index.htmlnu[ Metaclasses in Python 1.5

Metaclasses in Python 1.5

(A.k.a. The Killer Joke :-)


(Postscript: reading this essay is probably not the best way to understand the metaclass hook described here. See a message posted by Vladimir Marangozov which may give a gentler introduction to the matter. You may also want to search Deja News for messages with "metaclass" in the subject posted to comp.lang.python in July and August 1998.)

In previous Python releases (and still in 1.5), there is something called the ``Don Beaudry hook'', after its inventor and champion. This allows C extensions to provide alternate class behavior, thereby allowing the Python class syntax to be used to define other class-like entities. Don Beaudry has used this in his infamous MESS package; Jim Fulton has used it in his Extension Classes package. (It has also been referred to as the ``Don Beaudry hack,'' but that's a misnomer. There's nothing hackish about it -- in fact, it is rather elegant and deep, even though there's something dark to it.)

(On first reading, you may want to skip directly to the examples in the section "Writing Metaclasses in Python" below, unless you want your head to explode.)


Documentation of the Don Beaudry hook has purposefully been kept minimal, since it is a feature of incredible power, and is easily abused. Basically, it checks whether the type of the base class is callable, and if so, it is called to create the new class.

Note the two indirection levels. Take a simple example:

class B:
    pass

class C(B):
    pass
Take a look at the second class definition, and try to fathom ``the type of the base class is callable.''

(Types are not classes, by the way. See questions 4.2, 4.19 and in particular 6.22 in the Python FAQ for more on this topic.)

  • The base class is B; this one's easy.

  • Since B is a class, its type is ``class''; so the type of the base class is the type ``class''. This is also known as types.ClassType, assuming the standard module types has been imported.

  • Now is the type ``class'' callable? No, because types (in core Python) are never callable. Classes are callable (calling a class creates a new instance) but types aren't.

So our conclusion is that in our example, the type of the base class (of C) is not callable. So the Don Beaudry hook does not apply, and the default class creation mechanism is used (which is also used when there is no base class). In fact, the Don Beaudry hook never applies when using only core Python, since the type of a core object is never callable.

So what do Don and Jim do in order to use Don's hook? Write an extension that defines at least two new Python object types. The first would be the type for ``class-like'' objects usable as a base class, to trigger Don's hook. This type must be made callable. That's why we need a second type. Whether an object is callable depends on its type. So whether a type object is callable depends on its type, which is a meta-type. (In core Python there is only one meta-type, the type ``type'' (types.TypeType), which is the type of all type objects, even itself.) A new meta-type must be defined that makes the type of the class-like objects callable. (Normally, a third type would also be needed, the new ``instance'' type, but this is not an absolute requirement -- the new class type could return an object of some existing type when invoked to create an instance.)

Still confused? Here's a simple device due to Don himself to explain metaclasses. Take a simple class definition; assume B is a special class that triggers Don's hook:

class C(B):
    a = 1
    b = 2
This can be though of as equivalent to:
C = type(B)('C', (B,), {'a': 1, 'b': 2})
If that's too dense for you, here's the same thing written out using temporary variables:
creator = type(B)               # The type of the base class
name = 'C'                      # The name of the new class
bases = (B,)                    # A tuple containing the base class(es)
namespace = {'a': 1, 'b': 2}    # The namespace of the class statement
C = creator(name, bases, namespace)
This is analogous to what happens without the Don Beaudry hook, except that in that case the creator function is set to the default class creator.

In either case, the creator is called with three arguments. The first one, name, is the name of the new class (as given at the top of the class statement). The bases argument is a tuple of base classes (a singleton tuple if there's only one base class, like the example). Finally, namespace is a dictionary containing the local variables collected during execution of the class statement.

Note that the contents of the namespace dictionary is simply whatever names were defined in the class statement. A little-known fact is that when Python executes a class statement, it enters a new local namespace, and all assignments and function definitions take place in this namespace. Thus, after executing the following class statement:

class C:
    a = 1
    def f(s): pass
the class namespace's contents would be {'a': 1, 'f': <function f ...>}.

But enough already about writing Python metaclasses in C; read the documentation of MESS or Extension Classes for more information.


Writing Metaclasses in Python

In Python 1.5, the requirement to write a C extension in order to write metaclasses has been dropped (though you can still do it, of course). In addition to the check ``is the type of the base class callable,'' there's a check ``does the base class have a __class__ attribute.'' If so, it is assumed that the __class__ attribute refers to a class.

Let's repeat our simple example from above:

class C(B):
    a = 1
    b = 2
Assuming B has a __class__ attribute, this translates into:
C = B.__class__('C', (B,), {'a': 1, 'b': 2})
This is exactly the same as before except that instead of type(B), B.__class__ is invoked. If you have read FAQ question 6.22 you will understand that while there is a big technical difference between type(B) and B.__class__, they play the same role at different abstraction levels. And perhaps at some point in the future they will really be the same thing (at which point you would be able to derive subclasses from built-in types).

At this point it may be worth mentioning that C.__class__ is the same object as B.__class__, i.e., C's metaclass is the same as B's metaclass. In other words, subclassing an existing class creates a new (meta)inststance of the base class's metaclass.

Going back to the example, the class B.__class__ is instantiated, passing its constructor the same three arguments that are passed to the default class constructor or to an extension's metaclass: name, bases, and namespace.

It is easy to be confused by what exactly happens when using a metaclass, because we lose the absolute distinction between classes and instances: a class is an instance of a metaclass (a ``metainstance''), but technically (i.e. in the eyes of the python runtime system), the metaclass is just a class, and the metainstance is just an instance. At the end of the class statement, the metaclass whose metainstance is used as a base class is instantiated, yielding a second metainstance (of the same metaclass). This metainstance is then used as a (normal, non-meta) class; instantiation of the class means calling the metainstance, and this will return a real instance. And what class is that an instance of? Conceptually, it is of course an instance of our metainstance; but in most cases the Python runtime system will see it as an instance of a helper class used by the metaclass to implement its (non-meta) instances...

Hopefully an example will make things clearer. Let's presume we have a metaclass MetaClass1. It's helper class (for non-meta instances) is callled HelperClass1. We now (manually) instantiate MetaClass1 once to get an empty special base class:

BaseClass1 = MetaClass1("BaseClass1", (), {})
We can now use BaseClass1 as a base class in a class statement:
class MySpecialClass(BaseClass1):
    i = 1
    def f(s): pass
At this point, MySpecialClass is defined; it is a metainstance of MetaClass1 just like BaseClass1, and in fact the expression ``BaseClass1.__class__ == MySpecialClass.__class__ == MetaClass1'' yields true.

We are now ready to create instances of MySpecialClass. Let's assume that no constructor arguments are required:

x = MySpecialClass()
y = MySpecialClass()
print x.__class__, y.__class__
The print statement shows that x and y are instances of HelperClass1. How did this happen? MySpecialClass is an instance of MetaClass1 (``meta'' is irrelevant here); when an instance is called, its __call__ method is invoked, and presumably the __call__ method defined by MetaClass1 returns an instance of HelperClass1.

Now let's see how we could use metaclasses -- what can we do with metaclasses that we can't easily do without them? Here's one idea: a metaclass could automatically insert trace calls for all method calls. Let's first develop a simplified example, without support for inheritance or other ``advanced'' Python features (we'll add those later).

import types

class Tracing:
    def __init__(self, name, bases, namespace):
        """Create a new class."""
        self.__name__ = name
        self.__bases__ = bases
        self.__namespace__ = namespace
    def __call__(self):
        """Create a new instance."""
        return Instance(self)

class Instance:
    def __init__(self, klass):
        self.__klass__ = klass
    def __getattr__(self, name):
        try:
            value = self.__klass__.__namespace__[name]
        except KeyError:
            raise AttributeError, name
        if type(value) is not types.FunctionType:
            return value
        return BoundMethod(value, self)

class BoundMethod:
    def __init__(self, function, instance):
        self.function = function
        self.instance = instance
    def __call__(self, *args):
        print "calling", self.function, "for", self.instance, "with", args
        return apply(self.function, (self.instance,) + args)

Trace = Tracing('Trace', (), {})

class MyTracedClass(Trace):
    def method1(self, a):
        self.a = a
    def method2(self):
        return self.a

aninstance = MyTracedClass()

aninstance.method1(10)

print "the answer is %d" % aninstance.method2()
Confused already? The intention is to read this from top down. The Tracing class is the metaclass we're defining. Its structure is really simple.

  • The __init__ method is invoked when a new Tracing instance is created, e.g. the definition of class MyTracedClass later in the example. It simply saves the class name, base classes and namespace as instance variables.

  • The __call__ method is invoked when a Tracing instance is called, e.g. the creation of aninstance later in the example. It returns an instance of the class Instance, which is defined next.

The class Instance is the class used for all instances of classes built using the Tracing metaclass, e.g. aninstance. It has two methods:

  • The __init__ method is invoked from the Tracing.__call__ method above to initialize a new instance. It saves the class reference as an instance variable. It uses a funny name because the user's instance variables (e.g. self.a later in the example) live in the same namespace.

  • The __getattr__ method is invoked whenever the user code references an attribute of the instance that is not an instance variable (nor a class variable; but except for __init__ and __getattr__ there are no class variables). It will be called, for example, when aninstance.method1 is referenced in the example, with self set to aninstance and name set to the string "method1".

The __getattr__ method looks the name up in the __namespace__ dictionary. If it isn't found, it raises an AttributeError exception. (In a more realistic example, it would first have to look through the base classes as well.) If it is found, there are two possibilities: it's either a function or it isn't. If it's not a function, it is assumed to be a class variable, and its value is returned. If it's a function, we have to ``wrap'' it in instance of yet another helper class, BoundMethod.

The BoundMethod class is needed to implement a familiar feature: when a method is defined, it has an initial argument, self, which is automatically bound to the relevant instance when it is called. For example, aninstance.method1(10) is equivalent to method1(aninstance, 10). In the example if this call, first a temporary BoundMethod instance is created with the following constructor call: temp = BoundMethod(method1, aninstance); then this instance is called as temp(10). After the call, the temporary instance is discarded.

  • The __init__ method is invoked for the constructor call BoundMethod(method1, aninstance). It simply saves away its arguments.

  • The __call__ method is invoked when the bound method instance is called, as in temp(10). It needs to call method1(aninstance, 10). However, even though self.function is now method1 and self.instance is aninstance, it can't call self.function(self.instance, args) directly, because it should work regardless of the number of arguments passed. (For simplicity, support for keyword arguments has been omitted.)

In order to be able to support arbitrary argument lists, the __call__ method first constructs a new argument tuple. Conveniently, because of the notation *args in __call__'s own argument list, the arguments to __call__ (except for self) are placed in the tuple args. To construct the desired argument list, we concatenate a singleton tuple containing the instance with the args tuple: (self.instance,) + args. (Note the trailing comma used to construct the singleton tuple.) In our example, the resulting argument tuple is (aninstance, 10).

The intrinsic function apply() takes a function and an argument tuple and calls the function for it. In our example, we are calling apply(method1, (aninstance, 10)) which is equivalent to calling method(aninstance, 10).

From here on, things should come together quite easily. The output of the example code is something like this:

calling <function method1 at ae8d8> for <Instance instance at 95ab0> with (10,)
calling <function method2 at ae900> for <Instance instance at 95ab0> with ()
the answer is 10

That was about the shortest meaningful example that I could come up with. A real tracing metaclass (for example, Trace.py discussed below) needs to be more complicated in two dimensions.

First, it needs to support more advanced Python features such as class variables, inheritance, __init__ methods, and keyword arguments.

Second, it needs to provide a more flexible way to handle the actual tracing information; perhaps it should be possible to write your own tracing function that gets called, perhaps it should be possible to enable and disable tracing on a per-class or per-instance basis, and perhaps a filter so that only interesting calls are traced; it should also be able to trace the return value of the call (or the exception it raised if an error occurs). Even the Trace.py example doesn't support all these features yet.


Real-life Examples

Have a look at some very preliminary examples that I coded up to teach myself how to write metaclasses:

Enum.py
This (ab)uses the class syntax as an elegant way to define enumerated types. The resulting classes are never instantiated -- rather, their class attributes are the enumerated values. For example:
class Color(Enum):
    red = 1
    green = 2
    blue = 3
print Color.red
will print the string ``Color.red'', while ``Color.red==1'' is true, and ``Color.red + 1'' raise a TypeError exception.

Trace.py
The resulting classes work much like standard classes, but by setting a special class or instance attribute __trace_output__ to point to a file, all calls to the class's methods are traced. It was a bit of a struggle to get this right. This should probably redone using the generic metaclass below.

Meta.py
A generic metaclass. This is an attempt at finding out how much standard class behavior can be mimicked by a metaclass. The preliminary answer appears to be that everything's fine as long as the class (or its clients) don't look at the instance's __class__ attribute, nor at the class's __dict__ attribute. The use of __getattr__ internally makes the classic implementation of __getattr__ hooks tough; we provide a similar hook _getattr_ instead. (__setattr__ and __delattr__ are not affected.) (XXX Hm. Could detect presence of __getattr__ and rename it.)

Eiffel.py
Uses the above generic metaclass to implement Eiffel style pre-conditions and post-conditions.

Synch.py
Uses the above generic metaclass to implement synchronized methods.

Simple.py
The example module used above.

A pattern seems to be emerging: almost all these uses of metaclasses (except for Enum, which is probably more cute than useful) mostly work by placing wrappers around method calls. An obvious problem with that is that it's not easy to combine the features of different metaclasses, while this would actually be quite useful: for example, I wouldn't mind getting a trace from the test run of the Synch module, and it would be interesting to add preconditions to it as well. This needs more research. Perhaps a metaclass could be provided that allows stackable wrappers...


Things You Could Do With Metaclasses

There are lots of things you could do with metaclasses. Most of these can also be done with creative use of __getattr__, but metaclasses make it easier to modify the attribute lookup behavior of classes. Here's a partial list.

  • Enforce different inheritance semantics, e.g. automatically call base class methods when a derived class overrides

  • Implement class methods (e.g. if the first argument is not named 'self')

  • Implement that each instance is initialized with copies of all class variables

  • Implement a different way to store instance variables (e.g. in a list kept outside the instance but indexed by the instance's id())

  • Automatically wrap or trap all or certain methods
    • for tracing
    • for precondition and postcondition checking
    • for synchronized methods
    • for automatic value caching

  • When an attribute is a parameterless function, call it on reference (to mimic it being an instance variable); same on assignment

  • Instrumentation: see how many times various attributes are used

  • Different semantics for __setattr__ and __getattr__ (e.g. disable them when they are being used recursively)

  • Abuse class syntax for other things

  • Experiment with automatic type checking

  • Delegation (or acquisition)

  • Dynamic inheritance patterns

  • Automatic caching of methods


Credits

Many thanks to David Ascher and Donald Beaudry for their comments on earlier draft of this paper. Also thanks to Matt Conway and Tommy Burnette for putting a seed for the idea of metaclasses in my mind, nearly three years ago, even though at the time my response was ``you can do that with __getattr__ hooks...'' :-)


PK%L]á> metaclasses/Simple.pycnu[ ^c@sddlZdd dYZdd dYZdddYZeddiZd efd YZeZejd ejGHdS(iNtTracingcBseZdZdZRS(cCs||_||_||_dS(sCreate a new class.N(t__name__t __bases__t __namespace__(tselftnametbasest namespace((s//usr/lib64/python2.7/Demo/metaclasses/Simple.pyt__init__s  cCs t|S(sCreate a new instance.(tInstance(R((s//usr/lib64/python2.7/Demo/metaclasses/Simple.pyt__call__ s(Rt __module__RR (((s//usr/lib64/python2.7/Demo/metaclasses/Simple.pyRs R cBseZdZdZRS(cCs ||_dS(N(t __klass__(Rtklass((s//usr/lib64/python2.7/Demo/metaclasses/Simple.pyRscCsWy|jj|}Wntk r0t|nXt|tjk rJ|St||S(N(R RtKeyErrortAttributeErrorttypettypest FunctionTypet BoundMethod(RRtvalue((s//usr/lib64/python2.7/Demo/metaclasses/Simple.pyt __getattr__s  (RR RR(((s//usr/lib64/python2.7/Demo/metaclasses/Simple.pyR s RcBseZdZdZRS(cCs||_||_dS(N(tfunctiontinstance(RRR((s//usr/lib64/python2.7/Demo/metaclasses/Simple.pyRs cGs9dG|jGdG|jGdG|GHt|j|jf|S(Ntcallingtfortwith(RRtapply(Rtargs((s//usr/lib64/python2.7/Demo/metaclasses/Simple.pyR s(RR RR (((s//usr/lib64/python2.7/Demo/metaclasses/Simple.pyRs tTracet MyTracedClasscBseZdZdZRS(cCs ||_dS(N(ta(RR((s//usr/lib64/python2.7/Demo/metaclasses/Simple.pytmethod1$scCs|jS(N(R(R((s//usr/lib64/python2.7/Demo/metaclasses/Simple.pytmethod2&s(RR R R!(((s//usr/lib64/python2.7/Demo/metaclasses/Simple.pyR#s i ((((( RRR RRRt aninstanceR R!(((s//usr/lib64/python2.7/Demo/metaclasses/Simple.pyts     PK%L],.K metaclasses/Eiffel.pynu["""Support Eiffel-style preconditions and postconditions. For example, class C: def m1(self, arg): require arg > 0 return whatever ensure Result > arg can be written (clumsily, I agree) as: class C(Eiffel): def m1(self, arg): return whatever def m1_pre(self, arg): assert arg > 0 def m1_post(self, Result, arg): assert Result > arg Pre- and post-conditions for a method, being implemented as methods themselves, are inherited independently from the method. This gives much of the same effect of Eiffel, where pre- and post-conditions are inherited when a method is overridden by a derived class. However, when a derived class in Python needs to extend a pre- or post-condition, it must manually merge the base class' pre- or post-condition with that defined in the derived class', for example: class D(C): def m1(self, arg): return arg**2 def m1_post(self, Result, arg): C.m1_post(self, Result, arg) assert Result < 100 This gives derived classes more freedom but also more responsibility than in Eiffel, where the compiler automatically takes care of this. In Eiffel, pre-conditions combine using contravariance, meaning a derived class can only make a pre-condition weaker; in Python, this is up to the derived class. For example, a derived class that takes away the requirement that arg > 0 could write: def m1_pre(self, arg): pass but one could equally write a derived class that makes a stronger requirement: def m1_pre(self, arg): require arg > 50 It would be easy to modify the classes shown here so that pre- and post-conditions can be disabled (separately, on a per-class basis). A different design would have the pre- or post-condition testing functions return true for success and false for failure. This would make it possible to implement automatic combination of inherited and new pre-/post-conditions. All this is left as an exercise to the reader. """ from Meta import MetaClass, MetaHelper, MetaMethodWrapper class EiffelMethodWrapper(MetaMethodWrapper): def __init__(self, func, inst): MetaMethodWrapper.__init__(self, func, inst) # Note that the following causes recursive wrappers around # the pre-/post-condition testing methods. These are harmless # but inefficient; to avoid them, the lookup must be done # using the class. try: self.pre = getattr(inst, self.__name__ + "_pre") except AttributeError: self.pre = None try: self.post = getattr(inst, self.__name__ + "_post") except AttributeError: self.post = None def __call__(self, *args, **kw): if self.pre: apply(self.pre, args, kw) Result = apply(self.func, (self.inst,) + args, kw) if self.post: apply(self.post, (Result,) + args, kw) return Result class EiffelHelper(MetaHelper): __methodwrapper__ = EiffelMethodWrapper class EiffelMetaClass(MetaClass): __helper__ = EiffelHelper Eiffel = EiffelMetaClass('Eiffel', (), {}) def _test(): class C(Eiffel): def m1(self, arg): return arg+1 def m1_pre(self, arg): assert arg > 0, "precondition for m1 failed" def m1_post(self, Result, arg): assert Result > arg x = C() x.m1(12) ## x.m1(-1) if __name__ == '__main__': _test() PK%L]VAmetaclasses/Meta.pycnu[ ^c@sdZddlZdd dYZdd dYZdddYZed diZd Zed kr|endS(s?Generic metaclass. XXX This is very much a work in progress. iNtMetaMethodWrappercBseZdZdZRS(cCs%||_||_|jj|_dS(N(tfunctinstt__name__(tselfRR((s-/usr/lib64/python2.7/Demo/metaclasses/Meta.pyt__init__ s  cOst|j|jf||S(N(tapplyRR(Rtargstkw((s-/usr/lib64/python2.7/Demo/metaclasses/Meta.pyt__call__s(Rt __module__RR (((s-/usr/lib64/python2.7/Demo/metaclasses/Meta.pyR s t MetaHelpercBs eZeZdZdZRS(cCs ||_dS(N(t__formalclass__(Rt formalclass((s-/usr/lib64/python2.7/Demo/metaclasses/Meta.pyt__helperinit__scCsy|jj|}WnTtk rly|jjd}Wn ttfk r^t|nX|||SXt|tjkr|S|j||S(Nt__usergetattr__(R t __getattr__tAttributeErrortKeyErrorttypettypest FunctionTypet__methodwrapper__(Rtnametrawtga((s-/usr/lib64/python2.7/Demo/metaclasses/Meta.pyRs  (RR RRRR(((s-/usr/lib64/python2.7/Demo/metaclasses/Meta.pyR s t MetaClasscBs>eZdZeZdZdZdZdZdZ RS(scA generic metaclass. This can be subclassed to implement various kinds of meta-behavior. icCs[y|d}Wntk r!nX||d<|d=||_||_||_d|_dS(NRRi(RRt __bases__t __realdict__t_MetaClass__inited(RRtbasestdictR((s-/usr/lib64/python2.7/Demo/metaclasses/Meta.pyR4s     cCsiy|j|SWnStk rdx6|jD]+}y|j|SWq)tk rSq)Xq)Wt|nXdS(N(RRRRR(RRtbase((s-/usr/lib64/python2.7/Demo/metaclasses/Meta.pyRAs  cCs*|js||j|Xt(t __helper__RRRR(RRRRtinit((s-/usr/lib64/python2.7/Demo/metaclasses/Meta.pyR Rs    ( RR t__doc__R R'RRRR#R (((s-/usr/lib64/python2.7/Demo/metaclasses/Meta.pyR(s tMetacCsidtfdY}|GH|}|GH|jdd|fdY}|}|jGH|jGHdS(NtCcBseZdZdZRS(cWs dG|GHdS(Ns__init__, args =((RR((s-/usr/lib64/python2.7/Demo/metaclasses/Meta.pyRbscSsd|fGHdS(Nsm1(x=%r)((Rtx((s-/usr/lib64/python2.7/Demo/metaclasses/Meta.pytm1ds(RR RR-(((s-/usr/lib64/python2.7/Demo/metaclasses/Meta.pyR+as i tDcBseZdZRS(cSs$|d dkrt|nd|S(Nit__s getattr:%s(R(RR((s-/usr/lib64/python2.7/Demo/metaclasses/Meta.pyRks (RR R(((s-/usr/lib64/python2.7/Demo/metaclasses/Meta.pyR.js(R*R-tfoot_foo(R+R,R.((s-/usr/lib64/python2.7/Demo/metaclasses/Meta.pyt_test`s   t__main__(((((R)RRR RR*R2R(((s-/usr/lib64/python2.7/Demo/metaclasses/Meta.pyts  5  PK%L]LԯC##metaclasses/Enum.pyonu[ ^c@smdZddlZdd dYZdd dYZedd iZdZed kriendS( sCEnumeration metaclass. XXX This is very much a work in progress. iNt EnumMetaClasscBs)eZdZdZdZdZRS(shMetaclass for enumeration. To define your own enumeration, do something like class Color(Enum): red = 1 green = 2 blue = 3 Now, Color.red, Color.green and Color.blue behave totally different: they are enumerated values, not integers. Enumerations cannot be instantiated; however they can be subclassed. cCsx)|D]!}|jtk rtdqqWtd|}||_||_i|_x3|jD]%\}}t||||j|)tN( t __class__Rt TypeErrortfiltert__name__t __bases__t_EnumMetaClass__dicttitemst EnumInstance(tselftnametbasestdicttbasetkeytvalue((s-/usr/lib64/python2.7/Demo/metaclasses/Enum.pyt__init__s    cCs|dkr|jjSy|j|SWnMtk rwx=|jD].}yt||SWqBtk roqBqBXqBWnXt|dS(sReturn an enumeration value. For example, Color.red returns the value corresponding to red. XXX Perhaps the values should be created in the constructor? This looks in the class dictionary and if it is not found there asks the base classes. The special attribute __members__ returns the list of names defined in this class (it does not merge in the names defined in base classes). t __members__N(R tkeystKeyErrorR tgetattrtAttributeError(R RR((s-/usr/lib64/python2.7/Demo/metaclasses/Enum.pyt __getattr__0s    cCs|j}|jrB|dtjtd|jdd}n|jrg}x:|jjD])\}}|jd|t|fqaWd|tj|df}n|S(Nt(cSs|jS(N(R(R((s-/usr/lib64/python2.7/Demo/metaclasses/Enum.pyRPRs, t)s%s: %ss%s: {%s}( RR tstringtjointmapR R tappendtint(R tstlistRR((s-/usr/lib64/python2.7/Demo/metaclasses/Enum.pyt__repr__Ms  0 !(Rt __module__t__doc__RRR$(((s-/usr/lib64/python2.7/Demo/metaclasses/Enum.pyR s  R cBs;eZdZdZdZdZdZdZRS(s Class to represent an enumeration value. EnumInstance('Color', 'red', 12) prints as 'Color.red' and behaves like the integer 12 when compared, but doesn't support arithmetic. XXX Should it record the actual enumeration rather than just its name? cCs||_||_||_dS(N(t_EnumInstance__classnamet_EnumInstance__enumnamet_EnumInstance__value(R t classnametenumnameR((s-/usr/lib64/python2.7/Demo/metaclasses/Enum.pyRes  cCs|jS(N(R)(R ((s-/usr/lib64/python2.7/Demo/metaclasses/Enum.pyt__int__jscCsd|j|j|jfS(NsEnumInstance(%r, %r, %r)(R'R(R)(R ((s-/usr/lib64/python2.7/Demo/metaclasses/Enum.pyR$ms cCsd|j|jfS(Ns%s.%s(R'R((R ((s-/usr/lib64/python2.7/Demo/metaclasses/Enum.pyt__str__rscCst|jt|S(N(tcmpR)R!(R tother((s-/usr/lib64/python2.7/Demo/metaclasses/Enum.pyt__cmp__us(RR%R&RR,R$R-R0(((s-/usr/lib64/python2.7/Demo/metaclasses/Enum.pyR Zs      RcCsdtfdY}|jGHt|GH|j|jkGH|j|jkGH|jdkGH|jdkGHd|fdY}|jGH|jGH|j|jkGHdtfdY}d ||fd Y}|jGH|jGH|GH|GH|GH|GHdS( NtColorcBseZdZdZdZRS(iii(RR%tredtgreentblue(((s-/usr/lib64/python2.7/Demo/metaclasses/Enum.pyR1siit ExtendedColorcBs&eZdZdZdZdZdZRS(iiiii(RR%twhitetorangetyellowtpurpletblack(((s-/usr/lib64/python2.7/Demo/metaclasses/Enum.pyR5s t OtherColorcBseZdZdZRS(ii(RR%R6R4(((s-/usr/lib64/python2.7/Demo/metaclasses/Enum.pyR;st MergedColorcBseZRS((RR%(((s-/usr/lib64/python2.7/Demo/metaclasses/Enum.pyR<s(RR2tdirR4R7R6(R1R5R;R<((s-/usr/lib64/python2.7/Demo/metaclasses/Enum.pyt_test~s& t__main__((((R&RRR RR>R(((s-/usr/lib64/python2.7/Demo/metaclasses/Enum.pyts Q! * PK%L]Ymetaclasses/Trace.pycnu[ ^c@sdZddlZddlZdddYZdddYZdddYZd efd YZed didd 6Zd Z e dkre ndS(s?Tracing metaclass. XXX This is very much a work in progress. iNtTraceMetaClasscBs>eZdZdZdZdZdZdZdZ RS(sUMetaclass for tracing. Classes defined using this metaclass have an automatic tracing feature -- by setting the __trace_output__ instance (or class) variable to a file object, trace messages about all calls are written to the file. The trace formatting can be changed by defining a suitable __trace_call__ method. icCs(||_||_||_d|_dS(Ni(t__name__t __bases__t_TraceMetaClass__dictt_TraceMetaClass__inited(tselftnametbasestdict((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyt__init__s   cCsiy|j|SWnStk rdx6|jD]+}y|j|SWq)tk rSq)Xq)Wt|nXdS(N(RtKeyErrorRt __getattr__tAttributeError(RRtbase((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyR s  cCs*|js||j|4t(tTracingInstancet __meta_init__R R tapply(Rtargstkwtinsttinit((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyt__call__.s    N( Rt __module__t__doc__RR R RRRt__trace_output__(((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyR s    RcBs)eZdZdZdZdZRS(s9Helper class to represent an instance of a tracing class.cGs|j|d|dS(Ns (twrite(RtfptfmtR((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyt__trace_call__=scCs ||_dS(N(t_TracingInstance__class(Rtklass((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyR@scCsy|jj|}Wntk r2t|nXt|tjkrL|S|jjd|}|j sv|dkrt|||St |||SdS(Nt.R"( R#R R ttypettypest FunctionTypeRRtNotTracingWrappertTracingWrapper(RRtrawtfullname((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyR Cs  (RRRR"RR (((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyR:s  R)cBseZdZdZRS(cCs||_||_||_dS(N(RtfuncR(RRR-R((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyR Ss  cOst|j|jf||S(N(RR-R(RRR((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyRWs(RRR R(((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyR)Rs R*cBseZdZRS(cOs|jj|jjd|j|j||y#t|j|jf||}WnMtj\}}}|jj|jjd|j|||||n'X|jj|jjd|j||SdS(Ns#calling %s, inst=%s, args=%s, kw=%ss'returning from %s with exception %s: %ssreturning from %s with value %s(RR"RRRR-tsystexc_info(RRRtrvtttvttb((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyR# (RRR(((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyR*ZstTracedRcCsdtfdYadtfdYatd}|GH|jGH|jdGH|jdGH|jdGH|jd GH|jd GH|jGHtjGHtjGHtjGHtjGHt}|GH|jdGH|jdGH|jGHdS( NtCcBs/eZddZdZdZejZRS(icSs ||_dS(N(tx(RR6((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyR sRcSs ||_dS(N(R6(RR6((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pytm1tRcSs |j|S(N(R6(Rty((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pytm2uR(RRR R7R9R.tstdoutR(((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyR5rs   tDcBseZdZdZRS(cSsd|fGHtj||S(NsD.m2(%r)(R5R9(RR8((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyR9xs N(RRR9RR(((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyR;ws iidi i!ii(R4R5R;R6R7R9R (R6R8((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyt_testps(  t__main__((((( RR'R.RRR)R*RR4R<R(((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyts1  PK%L]Ymetaclasses/Trace.pyonu[ ^c@sdZddlZddlZdddYZdddYZdddYZd efd YZed didd 6Zd Z e dkre ndS(s?Tracing metaclass. XXX This is very much a work in progress. iNtTraceMetaClasscBs>eZdZdZdZdZdZdZdZ RS(sUMetaclass for tracing. Classes defined using this metaclass have an automatic tracing feature -- by setting the __trace_output__ instance (or class) variable to a file object, trace messages about all calls are written to the file. The trace formatting can be changed by defining a suitable __trace_call__ method. icCs(||_||_||_d|_dS(Ni(t__name__t __bases__t_TraceMetaClass__dictt_TraceMetaClass__inited(tselftnametbasestdict((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyt__init__s   cCsiy|j|SWnStk rdx6|jD]+}y|j|SWq)tk rSq)Xq)Wt|nXdS(N(RtKeyErrorRt __getattr__tAttributeError(RRtbase((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyR s  cCs*|js||j|4t(tTracingInstancet __meta_init__R R tapply(Rtargstkwtinsttinit((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyt__call__.s    N( Rt __module__t__doc__RR R RRRt__trace_output__(((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyR s    RcBs)eZdZdZdZdZRS(s9Helper class to represent an instance of a tracing class.cGs|j|d|dS(Ns (twrite(RtfptfmtR((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyt__trace_call__=scCs ||_dS(N(t_TracingInstance__class(Rtklass((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyR@scCsy|jj|}Wntk r2t|nXt|tjkrL|S|jjd|}|j sv|dkrt|||St |||SdS(Nt.R"( R#R R ttypettypest FunctionTypeRRtNotTracingWrappertTracingWrapper(RRtrawtfullname((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyR Cs  (RRRR"RR (((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyR:s  R)cBseZdZdZRS(cCs||_||_||_dS(N(RtfuncR(RRR-R((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyR Ss  cOst|j|jf||S(N(RR-R(RRR((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyRWs(RRR R(((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyR)Rs R*cBseZdZRS(cOs|jj|jjd|j|j||y#t|j|jf||}WnMtj\}}}|jj|jjd|j|||||n'X|jj|jjd|j||SdS(Ns#calling %s, inst=%s, args=%s, kw=%ss'returning from %s with exception %s: %ssreturning from %s with value %s(RR"RRRR-tsystexc_info(RRRtrvtttvttb((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyR# (RRR(((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyR*ZstTracedRcCsdtfdYadtfdYatd}|GH|jGH|jdGH|jdGH|jdGH|jd GH|jd GH|jGHtjGHtjGHtjGHtjGHt}|GH|jdGH|jdGH|jGHdS( NtCcBs/eZddZdZdZejZRS(icSs ||_dS(N(tx(RR6((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyR sRcSs ||_dS(N(R6(RR6((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pytm1tRcSs |j|S(N(R6(Rty((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pytm2uR(RRR R7R9R.tstdoutR(((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyR5rs   tDcBseZdZdZRS(cSsd|fGHtj||S(NsD.m2(%r)(R5R9(RR8((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyR9xs N(RRR9RR(((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyR;ws iidi i!ii(R4R5R;R6R7R9R (R6R8((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyt_testps(  t__main__((((( RR'R.RRR)R*RR4R<R(((s./usr/lib64/python2.7/Demo/metaclasses/Trace.pyts1  PK%L]metaclasses/Simple.pynu[import types class Tracing: def __init__(self, name, bases, namespace): """Create a new class.""" self.__name__ = name self.__bases__ = bases self.__namespace__ = namespace def __call__(self): """Create a new instance.""" return Instance(self) class Instance: def __init__(self, klass): self.__klass__ = klass def __getattr__(self, name): try: value = self.__klass__.__namespace__[name] except KeyError: raise AttributeError, name if type(value) is not types.FunctionType: return value return BoundMethod(value, self) class BoundMethod: def __init__(self, function, instance): self.function = function self.instance = instance def __call__(self, *args): print "calling", self.function, "for", self.instance, "with", args return apply(self.function, (self.instance,) + args) Trace = Tracing('Trace', (), {}) class MyTracedClass(Trace): def method1(self, a): self.a = a def method2(self): return self.a aninstance = MyTracedClass() aninstance.method1(10) print aninstance.method2() PK%L]VAmetaclasses/Meta.pyonu[ ^c@sdZddlZdd dYZdd dYZdddYZed diZd Zed kr|endS(s?Generic metaclass. XXX This is very much a work in progress. iNtMetaMethodWrappercBseZdZdZRS(cCs%||_||_|jj|_dS(N(tfunctinstt__name__(tselfRR((s-/usr/lib64/python2.7/Demo/metaclasses/Meta.pyt__init__ s  cOst|j|jf||S(N(tapplyRR(Rtargstkw((s-/usr/lib64/python2.7/Demo/metaclasses/Meta.pyt__call__s(Rt __module__RR (((s-/usr/lib64/python2.7/Demo/metaclasses/Meta.pyR s t MetaHelpercBs eZeZdZdZRS(cCs ||_dS(N(t__formalclass__(Rt formalclass((s-/usr/lib64/python2.7/Demo/metaclasses/Meta.pyt__helperinit__scCsy|jj|}WnTtk rly|jjd}Wn ttfk r^t|nX|||SXt|tjkr|S|j||S(Nt__usergetattr__(R t __getattr__tAttributeErrortKeyErrorttypettypest FunctionTypet__methodwrapper__(Rtnametrawtga((s-/usr/lib64/python2.7/Demo/metaclasses/Meta.pyRs  (RR RRRR(((s-/usr/lib64/python2.7/Demo/metaclasses/Meta.pyR s t MetaClasscBs>eZdZeZdZdZdZdZdZ RS(scA generic metaclass. This can be subclassed to implement various kinds of meta-behavior. icCs[y|d}Wntk r!nX||d<|d=||_||_||_d|_dS(NRRi(RRt __bases__t __realdict__t_MetaClass__inited(RRtbasestdictR((s-/usr/lib64/python2.7/Demo/metaclasses/Meta.pyR4s     cCsiy|j|SWnStk rdx6|jD]+}y|j|SWq)tk rSq)Xq)Wt|nXdS(N(RRRRR(RRtbase((s-/usr/lib64/python2.7/Demo/metaclasses/Meta.pyRAs  cCs*|js||j|Xt(t __helper__RRRR(RRRRtinit((s-/usr/lib64/python2.7/Demo/metaclasses/Meta.pyR Rs    ( RR t__doc__R R'RRRR#R (((s-/usr/lib64/python2.7/Demo/metaclasses/Meta.pyR(s tMetacCsidtfdY}|GH|}|GH|jdd|fdY}|}|jGH|jGHdS(NtCcBseZdZdZRS(cWs dG|GHdS(Ns__init__, args =((RR((s-/usr/lib64/python2.7/Demo/metaclasses/Meta.pyRbscSsd|fGHdS(Nsm1(x=%r)((Rtx((s-/usr/lib64/python2.7/Demo/metaclasses/Meta.pytm1ds(RR RR-(((s-/usr/lib64/python2.7/Demo/metaclasses/Meta.pyR+as i tDcBseZdZRS(cSs$|d dkrt|nd|S(Nit__s getattr:%s(R(RR((s-/usr/lib64/python2.7/Demo/metaclasses/Meta.pyRks (RR R(((s-/usr/lib64/python2.7/Demo/metaclasses/Meta.pyR.js(R*R-tfoot_foo(R+R,R.((s-/usr/lib64/python2.7/Demo/metaclasses/Meta.pyt_test`s   t__main__(((((R)RRR RR*R2R(((s-/usr/lib64/python2.7/Demo/metaclasses/Meta.pyts  5  PK%L]LԯC##metaclasses/Enum.pycnu[ ^c@smdZddlZdd dYZdd dYZedd iZdZed kriendS( sCEnumeration metaclass. XXX This is very much a work in progress. iNt EnumMetaClasscBs)eZdZdZdZdZRS(shMetaclass for enumeration. To define your own enumeration, do something like class Color(Enum): red = 1 green = 2 blue = 3 Now, Color.red, Color.green and Color.blue behave totally different: they are enumerated values, not integers. Enumerations cannot be instantiated; however they can be subclassed. cCsx)|D]!}|jtk rtdqqWtd|}||_||_i|_x3|jD]%\}}t||||j|)tN( t __class__Rt TypeErrortfiltert__name__t __bases__t_EnumMetaClass__dicttitemst EnumInstance(tselftnametbasestdicttbasetkeytvalue((s-/usr/lib64/python2.7/Demo/metaclasses/Enum.pyt__init__s    cCs|dkr|jjSy|j|SWnMtk rwx=|jD].}yt||SWqBtk roqBqBXqBWnXt|dS(sReturn an enumeration value. For example, Color.red returns the value corresponding to red. XXX Perhaps the values should be created in the constructor? This looks in the class dictionary and if it is not found there asks the base classes. The special attribute __members__ returns the list of names defined in this class (it does not merge in the names defined in base classes). t __members__N(R tkeystKeyErrorR tgetattrtAttributeError(R RR((s-/usr/lib64/python2.7/Demo/metaclasses/Enum.pyt __getattr__0s    cCs|j}|jrB|dtjtd|jdd}n|jrg}x:|jjD])\}}|jd|t|fqaWd|tj|df}n|S(Nt(cSs|jS(N(R(R((s-/usr/lib64/python2.7/Demo/metaclasses/Enum.pyRPRs, t)s%s: %ss%s: {%s}( RR tstringtjointmapR R tappendtint(R tstlistRR((s-/usr/lib64/python2.7/Demo/metaclasses/Enum.pyt__repr__Ms  0 !(Rt __module__t__doc__RRR$(((s-/usr/lib64/python2.7/Demo/metaclasses/Enum.pyR s  R cBs;eZdZdZdZdZdZdZRS(s Class to represent an enumeration value. EnumInstance('Color', 'red', 12) prints as 'Color.red' and behaves like the integer 12 when compared, but doesn't support arithmetic. XXX Should it record the actual enumeration rather than just its name? cCs||_||_||_dS(N(t_EnumInstance__classnamet_EnumInstance__enumnamet_EnumInstance__value(R t classnametenumnameR((s-/usr/lib64/python2.7/Demo/metaclasses/Enum.pyRes  cCs|jS(N(R)(R ((s-/usr/lib64/python2.7/Demo/metaclasses/Enum.pyt__int__jscCsd|j|j|jfS(NsEnumInstance(%r, %r, %r)(R'R(R)(R ((s-/usr/lib64/python2.7/Demo/metaclasses/Enum.pyR$ms cCsd|j|jfS(Ns%s.%s(R'R((R ((s-/usr/lib64/python2.7/Demo/metaclasses/Enum.pyt__str__rscCst|jt|S(N(tcmpR)R!(R tother((s-/usr/lib64/python2.7/Demo/metaclasses/Enum.pyt__cmp__us(RR%R&RR,R$R-R0(((s-/usr/lib64/python2.7/Demo/metaclasses/Enum.pyR Zs      RcCsdtfdY}|jGHt|GH|j|jkGH|j|jkGH|jdkGH|jdkGHd|fdY}|jGH|jGH|j|jkGHdtfdY}d ||fd Y}|jGH|jGH|GH|GH|GH|GHdS( NtColorcBseZdZdZdZRS(iii(RR%tredtgreentblue(((s-/usr/lib64/python2.7/Demo/metaclasses/Enum.pyR1siit ExtendedColorcBs&eZdZdZdZdZdZRS(iiiii(RR%twhitetorangetyellowtpurpletblack(((s-/usr/lib64/python2.7/Demo/metaclasses/Enum.pyR5s t OtherColorcBseZdZdZRS(ii(RR%R6R4(((s-/usr/lib64/python2.7/Demo/metaclasses/Enum.pyR;st MergedColorcBseZRS((RR%(((s-/usr/lib64/python2.7/Demo/metaclasses/Enum.pyR<s(RR2tdirR4R7R6(R1R5R;R<((s-/usr/lib64/python2.7/Demo/metaclasses/Enum.pyt_test~s& t__main__((((R&RRR RR>R(((s-/usr/lib64/python2.7/Demo/metaclasses/Enum.pyts Q! * PK%L]zmetaclasses/Eiffel.pycnu[ ^c@sdZddlmZmZmZdefdYZdefdYZdefdYZed d iZd Z e d kre nd S(sSupport Eiffel-style preconditions and postconditions. For example, class C: def m1(self, arg): require arg > 0 return whatever ensure Result > arg can be written (clumsily, I agree) as: class C(Eiffel): def m1(self, arg): return whatever def m1_pre(self, arg): assert arg > 0 def m1_post(self, Result, arg): assert Result > arg Pre- and post-conditions for a method, being implemented as methods themselves, are inherited independently from the method. This gives much of the same effect of Eiffel, where pre- and post-conditions are inherited when a method is overridden by a derived class. However, when a derived class in Python needs to extend a pre- or post-condition, it must manually merge the base class' pre- or post-condition with that defined in the derived class', for example: class D(C): def m1(self, arg): return arg**2 def m1_post(self, Result, arg): C.m1_post(self, Result, arg) assert Result < 100 This gives derived classes more freedom but also more responsibility than in Eiffel, where the compiler automatically takes care of this. In Eiffel, pre-conditions combine using contravariance, meaning a derived class can only make a pre-condition weaker; in Python, this is up to the derived class. For example, a derived class that takes away the requirement that arg > 0 could write: def m1_pre(self, arg): pass but one could equally write a derived class that makes a stronger requirement: def m1_pre(self, arg): require arg > 50 It would be easy to modify the classes shown here so that pre- and post-conditions can be disabled (separately, on a per-class basis). A different design would have the pre- or post-condition testing functions return true for success and false for failure. This would make it possible to implement automatic combination of inherited and new pre-/post-conditions. All this is left as an exercise to the reader. i(t MetaClasst MetaHelpertMetaMethodWrappertEiffelMethodWrappercBseZdZdZRS(cCstj|||yt||jd|_Wntk rLd|_nXyt||jd|_Wntk rd|_nXdS(Nt_pret_post(Rt__init__tgetattrt__name__tpretAttributeErrortNonetpost(tselftfunctinst((s//usr/lib64/python2.7/Demo/metaclasses/Eiffel.pyRDs   cOsh|jrt|j||nt|j|jf||}|jrdt|j|f||n|S(N(R tapplyRRR (R targstkwtResult((s//usr/lib64/python2.7/Demo/metaclasses/Eiffel.pyt__call__Ss   (Rt __module__RR(((s//usr/lib64/python2.7/Demo/metaclasses/Eiffel.pyRBs t EiffelHelpercBseZeZRS((RRRt__methodwrapper__(((s//usr/lib64/python2.7/Demo/metaclasses/Eiffel.pyR[stEiffelMetaClasscBseZeZRS((RRRt __helper__(((s//usr/lib64/python2.7/Demo/metaclasses/Eiffel.pyR^stEiffelcCs0dtfdY}|}|jddS(NtCcBs#eZdZdZdZRS(cSs|dS(Ni((R targ((s//usr/lib64/python2.7/Demo/metaclasses/Eiffel.pytm1fscSs|dkstddS(Nisprecondition for m1 failed(tAssertionError(R R((s//usr/lib64/python2.7/Demo/metaclasses/Eiffel.pytm1_prehscSs||kstdS(N(R(R RR((s//usr/lib64/python2.7/Demo/metaclasses/Eiffel.pytm1_postjs(RRRRR (((s//usr/lib64/python2.7/Demo/metaclasses/Eiffel.pyRes  i (RR(Rtx((s//usr/lib64/python2.7/Demo/metaclasses/Eiffel.pyt_testds t__main__N(( t__doc__tMetaRRRRRRRR"R(((s//usr/lib64/python2.7/Demo/metaclasses/Eiffel.pyt>s PK%L]L!!metaclasses/Synch.pycnu[ ^c@sdZddlZdddYZdZddlmZmZmZdefdYZd efd YZ d efd YZ e d diZ dZ e dkree ndS(s`Synchronization metaclass. This metaclass makes it possible to declare synchronized methods. iNtLockcBs,eZdZdZddZdZRS(sReentrant lock. This is a mutex-like object which can be acquired by the same thread more than once. It keeps a reference count of the number of times it has been acquired by the same thread. Each acquire() call must be matched by a release() call and only the last release() call actually releases the lock for acquisition by another thread. The implementation uses two locks internally: __mutex is a short term lock used to protect the instance variables __wait is the lock for which other threads wait A thread intending to acquire both locks should acquire __wait first. The implementation uses two other instance variables, protected by locking __mutex: __tid is the thread ID of the thread that currently has the lock __count is the number of times the current thread has acquired it When the lock is released, __tid is None and __count is zero. cCs4tj|_tj|_d|_d|_dS(s0Constructor. Initialize all instance variables.iN(tthreadt allocate_lockt _Lock__mutext _Lock__waittNonet _Lock__tidt _Lock__count(tself((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pyt__init__*s icCs|jjz-|jtjkr9|jd|_dSWd|jjX|jj|}| ro| rodSzW|jj|jdkst |jdkst tj|_d|_dSWd|jjXdS(s}Acquire the lock. If the optional flag argument is false, returns immediately when it cannot acquire the __wait lock without blocking (it may still block for a little while in order to acquire the __mutex lock). The return value is only relevant when the flag argument is false; it is 1 if the lock is acquired, 0 if not. iNi( RtacquireRRt get_identRtreleaseRRtAssertionError(Rtflagtlocked((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pyR 1s"   cCs|jjzl|jtjks+t|jdks@t|jd|_|jdkrxd|_|jj nWd|jj XdS(sRelease the lock. If this thread doesn't currently have the lock, an assertion error is raised. Only allow another thread to acquire the lock when the count reaches zero after decrementing it. iiN( RR RRR R RRRR (R((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pyR Qs  (t__name__t __module__t__doc__R R R (((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pyR s  cCsg}|d}||d}t}|j|||j|jtj||ftj|||ftj||ftj||f|jddl}x.t|dkrt|GH|jdqWt|GHdS(NcSs3|jdtjG|j|jddS(Nsf2 running in thread %d i(R RR R tappend(tlocktdone((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pytf2ks  cSsE|jdtjGz||Wd|jX|jddS(Nsf1 running in thread %d i(R RR R R(RRR((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pytf1qs   ii gMbP?(RR R Rtstart_new_threadttimetlentsleep(RRRRR((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pyt _testLockgs$         (t MetaClasst MetaHelpertMetaMethodWrappertLockingMethodWrappercBseZdZRS(cOs|jd dkrC|jddkrCt|j|jf||S|jjjz!t|j|jf||SWd|jjjXdS(Nit_(Rtapplytfunctinstt__lock__R R (Rtargstkw((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pyt__call__s &!(RRR((((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pyR st LockingHelpercBseZeZdZRS(cCs tj||t|_dS(N(Rt__helperinit__RR%(Rt formalclass((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pyR*s(RRR t__methodwrapper__R*(((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pyR)stLockingMetaClasscBseZeZRS((RRR)t __helper__(((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pyR-stLockingcCsdtfdY}dd}dd}tj}|jtj}|j|d}d}tj||||ftj||||f|jdGH|jdGHd Gt|jGHdS( NtBuffercBs#eZdZdZdZRS(cSsB|dkst||_dg|j|_d|_|_dS(Ni(R tsizeRtbuffertfirsttlast(Rt initialsize((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pyR s cSsI|jd|j|jkrH||j|j<|jd|j|_dSdG|jGHd|j|j|jfGH|j|jkr|j|j|j!}n|j|j|j|j }dG|GH|dg|jd|_d|_|jd|_|jd|_dG|jGHdG|jGHd|j|j|jfGH|j|dS( Nisbuffer =s first = %d, last = %d, size = %dstemp =iisBuffer size doubled tos new buffer =(R4R1R3R2Rtput(Rtitemttemp((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pyR6s(     cSsF|j|jkrtn|j|j}|jd|j|_|S(Ni(R3R4tEOFErrorR2R1(RR7((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pytgets  (RRR R6R:(((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pyR0s  icSs`ddl}d}x0||krDdG|GH|j||d}qWdG|GdGH|jdS(NiiR6isProducer: done producingtitems(RR6R (R2twaittnRti((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pytproducers    cSsddl}d}d}x||kryK|j}||krXtd||fndG|GH|d}d}Wqtk r|j||d}qXqWdG|Gd GH|jdS( NiigMbP?sget() returned %s, expected %stgotiisConsumer: done consumingR;(RR:R R9RR (R2R<R=RR>ttouttx((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pytconsumers"         is Producer donesAll donesbuffer size ==(R/RRR RRR2(R0R?RCtpwaittcwaitR2R=((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pyt_tests (        t__main__(((RRRRtMetaRRRR R)R-R/RFR(((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pyts Z +  U PK%L]>Ͼo%%metaclasses/Trace.pynu["""Tracing metaclass. XXX This is very much a work in progress. """ import types, sys class TraceMetaClass: """Metaclass for tracing. Classes defined using this metaclass have an automatic tracing feature -- by setting the __trace_output__ instance (or class) variable to a file object, trace messages about all calls are written to the file. The trace formatting can be changed by defining a suitable __trace_call__ method. """ __inited = 0 def __init__(self, name, bases, dict): self.__name__ = name self.__bases__ = bases self.__dict = dict # XXX Can't define __dict__, alas self.__inited = 1 def __getattr__(self, name): try: return self.__dict[name] except KeyError: for base in self.__bases__: try: return base.__getattr__(name) except AttributeError: pass raise AttributeError, name def __setattr__(self, name, value): if not self.__inited: self.__dict__[name] = value else: self.__dict[name] = value def __call__(self, *args, **kw): inst = TracingInstance() inst.__meta_init__(self) try: init = inst.__getattr__('__init__') except AttributeError: init = lambda: None apply(init, args, kw) return inst __trace_output__ = None class TracingInstance: """Helper class to represent an instance of a tracing class.""" def __trace_call__(self, fp, fmt, *args): fp.write((fmt+'\n') % args) def __meta_init__(self, klass): self.__class = klass def __getattr__(self, name): # Invoked for any attr not in the instance's __dict__ try: raw = self.__class.__getattr__(name) except AttributeError: raise AttributeError, name if type(raw) != types.FunctionType: return raw # It's a function fullname = self.__class.__name__ + "." + name if not self.__trace_output__ or name == '__trace_call__': return NotTracingWrapper(fullname, raw, self) else: return TracingWrapper(fullname, raw, self) class NotTracingWrapper: def __init__(self, name, func, inst): self.__name__ = name self.func = func self.inst = inst def __call__(self, *args, **kw): return apply(self.func, (self.inst,) + args, kw) class TracingWrapper(NotTracingWrapper): def __call__(self, *args, **kw): self.inst.__trace_call__(self.inst.__trace_output__, "calling %s, inst=%s, args=%s, kw=%s", self.__name__, self.inst, args, kw) try: rv = apply(self.func, (self.inst,) + args, kw) except: t, v, tb = sys.exc_info() self.inst.__trace_call__(self.inst.__trace_output__, "returning from %s with exception %s: %s", self.__name__, t, v) raise t, v, tb else: self.inst.__trace_call__(self.inst.__trace_output__, "returning from %s with value %s", self.__name__, rv) return rv Traced = TraceMetaClass('Traced', (), {'__trace_output__': None}) def _test(): global C, D class C(Traced): def __init__(self, x=0): self.x = x def m1(self, x): self.x = x def m2(self, y): return self.x + y __trace_output__ = sys.stdout class D(C): def m2(self, y): print "D.m2(%r)" % (y,); return C.m2(self, y) __trace_output__ = None x = C(4321) print x print x.x print x.m1(100) print x.m1(10) print x.m2(33) print x.m1(5) print x.m2(4000) print x.x print C.__init__ print C.m2 print D.__init__ print D.m2 y = D() print y print y.m1(10) print y.m2(100) print y.x if __name__ == '__main__': _test() PK%L]Ǫ>z z metaclasses/Synch.pyonu[ ^c@sdZddlZdddYZdZddlmZmZmZdefdYZd efd YZ d efd YZ e d diZ dZ e dkree ndS(s`Synchronization metaclass. This metaclass makes it possible to declare synchronized methods. iNtLockcBs,eZdZdZddZdZRS(sReentrant lock. This is a mutex-like object which can be acquired by the same thread more than once. It keeps a reference count of the number of times it has been acquired by the same thread. Each acquire() call must be matched by a release() call and only the last release() call actually releases the lock for acquisition by another thread. The implementation uses two locks internally: __mutex is a short term lock used to protect the instance variables __wait is the lock for which other threads wait A thread intending to acquire both locks should acquire __wait first. The implementation uses two other instance variables, protected by locking __mutex: __tid is the thread ID of the thread that currently has the lock __count is the number of times the current thread has acquired it When the lock is released, __tid is None and __count is zero. cCs4tj|_tj|_d|_d|_dS(s0Constructor. Initialize all instance variables.iN(tthreadt allocate_lockt _Lock__mutext _Lock__waittNonet _Lock__tidt _Lock__count(tself((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pyt__init__*s icCs|jjz-|jtjkr9|jd|_dSWd|jjX|jj|}| ro| rodSz-|jjtj|_d|_dSWd|jjXdS(s}Acquire the lock. If the optional flag argument is false, returns immediately when it cannot acquire the __wait lock without blocking (it may still block for a little while in order to acquire the __mutex lock). The return value is only relevant when the flag argument is false; it is 1 if the lock is acquired, 0 if not. iNi(RtacquireRRt get_identRtreleaseR(Rtflagtlocked((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pyR 1s   cCs^|jjz<|jd|_|jdkrHd|_|jjnWd|jjXdS(sRelease the lock. If this thread doesn't currently have the lock, an assertion error is raised. Only allow another thread to acquire the lock when the count reaches zero after decrementing it. iiN(RR RRRRR (R((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pyR Qs  (t__name__t __module__t__doc__R R R (((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pyR s  cCsg}|d}||d}t}|j|||j|jtj||ftj|||ftj||ftj||f|jddl}x.t|dkrt|GH|jdqWt|GHdS(NcSs3|jdtjG|j|jddS(Nsf2 running in thread %d i(R RR R tappend(tlocktdone((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pytf2ks  cSsE|jdtjGz||Wd|jX|jddS(Nsf1 running in thread %d i(R RR R R(RRR((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pytf1qs   ii gMbP?(RR R Rtstart_new_threadttimetlentsleep(RRRRR((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pyt _testLockgs$         (t MetaClasst MetaHelpertMetaMethodWrappertLockingMethodWrappercBseZdZRS(cOs|jd dkrC|jddkrCt|j|jf||S|jjjz!t|j|jf||SWd|jjjXdS(Nit_(Rtapplytfunctinstt__lock__R R (Rtargstkw((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pyt__call__s &!(RRR'(((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pyRst LockingHelpercBseZeZdZRS(cCs tj||t|_dS(N(Rt__helperinit__RR$(Rt formalclass((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pyR)s(RRRt__methodwrapper__R)(((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pyR(stLockingMetaClasscBseZeZRS((RRR(t __helper__(((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pyR,stLockingcCsdtfdY}dd}dd}tj}|jtj}|j|d}d}tj||||ftj||||f|jdGH|jdGHd Gt|jGHdS( NtBuffercBs#eZdZdZdZRS(cSs0||_dg|j|_d|_|_dS(Ni(tsizeRtbuffertfirsttlast(Rt initialsize((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pyR s cSsI|jd|j|jkrH||j|j<|jd|j|_dSdG|jGHd|j|j|jfGH|j|jkr|j|j|j!}n|j|j|j|j }dG|GH|dg|jd|_d|_|jd|_|jd|_dG|jGHdG|jGHd|j|j|jfGH|j|dS( Nisbuffer =s first = %d, last = %d, size = %dstemp =iisBuffer size doubled tos new buffer =(R3R0R2R1Rtput(Rtitemttemp((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pyR5s(     cSsF|j|jkrtn|j|j}|jd|j|_|S(Ni(R2R3tEOFErrorR1R0(RR6((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pytgets  (RRR R5R9(((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pyR/s  icSs`ddl}d}x0||krDdG|GH|j||d}qWdG|GdGH|jdS(NiiR5isProducer: done producingtitems(RR5R (R1twaittnRti((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pytproducers    cSsddl}d}d}x||kryK|j}||krXtd||fndG|GH|d}d}Wqtk r|j||d}qXqWdG|Gd GH|jdS( NiigMbP?sget() returned %s, expected %stgotiisConsumer: done consumingR:(RR9tAssertionErrorR8RR (R1R;R<RR=ttouttx((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pytconsumers"         is Producer donesAll donesbuffer size ==(R.RRR RRR1(R/R>RCtpwaittcwaitR1R<((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pyt_tests (        t__main__(((RRRRtMetaRRRRR(R,R.RFR(((s./usr/lib64/python2.7/Demo/metaclasses/Synch.pyts Z +  U PK%L]6Q}metaclasses/Synch.pynu["""Synchronization metaclass. This metaclass makes it possible to declare synchronized methods. """ import thread # First we need to define a reentrant lock. # This is generally useful and should probably be in a standard Python # library module. For now, we in-line it. class Lock: """Reentrant lock. This is a mutex-like object which can be acquired by the same thread more than once. It keeps a reference count of the number of times it has been acquired by the same thread. Each acquire() call must be matched by a release() call and only the last release() call actually releases the lock for acquisition by another thread. The implementation uses two locks internally: __mutex is a short term lock used to protect the instance variables __wait is the lock for which other threads wait A thread intending to acquire both locks should acquire __wait first. The implementation uses two other instance variables, protected by locking __mutex: __tid is the thread ID of the thread that currently has the lock __count is the number of times the current thread has acquired it When the lock is released, __tid is None and __count is zero. """ def __init__(self): """Constructor. Initialize all instance variables.""" self.__mutex = thread.allocate_lock() self.__wait = thread.allocate_lock() self.__tid = None self.__count = 0 def acquire(self, flag=1): """Acquire the lock. If the optional flag argument is false, returns immediately when it cannot acquire the __wait lock without blocking (it may still block for a little while in order to acquire the __mutex lock). The return value is only relevant when the flag argument is false; it is 1 if the lock is acquired, 0 if not. """ self.__mutex.acquire() try: if self.__tid == thread.get_ident(): self.__count = self.__count + 1 return 1 finally: self.__mutex.release() locked = self.__wait.acquire(flag) if not flag and not locked: return 0 try: self.__mutex.acquire() assert self.__tid == None assert self.__count == 0 self.__tid = thread.get_ident() self.__count = 1 return 1 finally: self.__mutex.release() def release(self): """Release the lock. If this thread doesn't currently have the lock, an assertion error is raised. Only allow another thread to acquire the lock when the count reaches zero after decrementing it. """ self.__mutex.acquire() try: assert self.__tid == thread.get_ident() assert self.__count > 0 self.__count = self.__count - 1 if self.__count == 0: self.__tid = None self.__wait.release() finally: self.__mutex.release() def _testLock(): done = [] def f2(lock, done=done): lock.acquire() print "f2 running in thread %d\n" % thread.get_ident(), lock.release() done.append(1) def f1(lock, f2=f2, done=done): lock.acquire() print "f1 running in thread %d\n" % thread.get_ident(), try: f2(lock) finally: lock.release() done.append(1) lock = Lock() lock.acquire() f1(lock) # Adds 2 to done lock.release() lock.acquire() thread.start_new_thread(f1, (lock,)) # Adds 2 thread.start_new_thread(f1, (lock, f1)) # Adds 3 thread.start_new_thread(f2, (lock,)) # Adds 1 thread.start_new_thread(f2, (lock,)) # Adds 1 lock.release() import time while len(done) < 9: print len(done) time.sleep(0.001) print len(done) # Now, the Locking metaclass is a piece of cake. # As an example feature, methods whose name begins with exactly one # underscore are not synchronized. from Meta import MetaClass, MetaHelper, MetaMethodWrapper class LockingMethodWrapper(MetaMethodWrapper): def __call__(self, *args, **kw): if self.__name__[:1] == '_' and self.__name__[1:] != '_': return apply(self.func, (self.inst,) + args, kw) self.inst.__lock__.acquire() try: return apply(self.func, (self.inst,) + args, kw) finally: self.inst.__lock__.release() class LockingHelper(MetaHelper): __methodwrapper__ = LockingMethodWrapper def __helperinit__(self, formalclass): MetaHelper.__helperinit__(self, formalclass) self.__lock__ = Lock() class LockingMetaClass(MetaClass): __helper__ = LockingHelper Locking = LockingMetaClass('Locking', (), {}) def _test(): # For kicks, take away the Locking base class and see it die class Buffer(Locking): def __init__(self, initialsize): assert initialsize > 0 self.size = initialsize self.buffer = [None]*self.size self.first = self.last = 0 def put(self, item): # Do we need to grow the buffer? if (self.last+1) % self.size != self.first: # Insert the new item self.buffer[self.last] = item self.last = (self.last+1) % self.size return # Double the buffer size # First normalize it so that first==0 and last==size-1 print "buffer =", self.buffer print "first = %d, last = %d, size = %d" % ( self.first, self.last, self.size) if self.first <= self.last: temp = self.buffer[self.first:self.last] else: temp = self.buffer[self.first:] + self.buffer[:self.last] print "temp =", temp self.buffer = temp + [None]*(self.size+1) self.first = 0 self.last = self.size-1 self.size = self.size*2 print "Buffer size doubled to", self.size print "new buffer =", self.buffer print "first = %d, last = %d, size = %d" % ( self.first, self.last, self.size) self.put(item) # Recursive call to test the locking def get(self): # Is the buffer empty? if self.first == self.last: raise EOFError # Avoid defining a new exception item = self.buffer[self.first] self.first = (self.first+1) % self.size return item def producer(buffer, wait, n=1000): import time i = 0 while i < n: print "put", i buffer.put(i) i = i+1 print "Producer: done producing", n, "items" wait.release() def consumer(buffer, wait, n=1000): import time i = 0 tout = 0.001 while i < n: try: x = buffer.get() if x != i: raise AssertionError, \ "get() returned %s, expected %s" % (x, i) print "got", i i = i+1 tout = 0.001 except EOFError: time.sleep(tout) tout = tout*2 print "Consumer: done consuming", n, "items" wait.release() pwait = thread.allocate_lock() pwait.acquire() cwait = thread.allocate_lock() cwait.acquire() buffer = Buffer(1) n = 1000 thread.start_new_thread(consumer, (buffer, cwait, n)) thread.start_new_thread(producer, (buffer, pwait, n)) pwait.acquire() print "Producer done" cwait.acquire() print "All done" print "buffer size ==", len(buffer.buffer) if __name__ == '__main__': _testLock() _test() PK%L]á> metaclasses/Simple.pyonu[ ^c@sddlZdd dYZdd dYZdddYZeddiZd efd YZeZejd ejGHdS(iNtTracingcBseZdZdZRS(cCs||_||_||_dS(sCreate a new class.N(t__name__t __bases__t __namespace__(tselftnametbasest namespace((s//usr/lib64/python2.7/Demo/metaclasses/Simple.pyt__init__s  cCs t|S(sCreate a new instance.(tInstance(R((s//usr/lib64/python2.7/Demo/metaclasses/Simple.pyt__call__ s(Rt __module__RR (((s//usr/lib64/python2.7/Demo/metaclasses/Simple.pyRs R cBseZdZdZRS(cCs ||_dS(N(t __klass__(Rtklass((s//usr/lib64/python2.7/Demo/metaclasses/Simple.pyRscCsWy|jj|}Wntk r0t|nXt|tjk rJ|St||S(N(R RtKeyErrortAttributeErrorttypettypest FunctionTypet BoundMethod(RRtvalue((s//usr/lib64/python2.7/Demo/metaclasses/Simple.pyt __getattr__s  (RR RR(((s//usr/lib64/python2.7/Demo/metaclasses/Simple.pyR s RcBseZdZdZRS(cCs||_||_dS(N(tfunctiontinstance(RRR((s//usr/lib64/python2.7/Demo/metaclasses/Simple.pyRs cGs9dG|jGdG|jGdG|GHt|j|jf|S(Ntcallingtfortwith(RRtapply(Rtargs((s//usr/lib64/python2.7/Demo/metaclasses/Simple.pyR s(RR RR (((s//usr/lib64/python2.7/Demo/metaclasses/Simple.pyRs tTracet MyTracedClasscBseZdZdZRS(cCs ||_dS(N(ta(RR((s//usr/lib64/python2.7/Demo/metaclasses/Simple.pytmethod1$scCs|jS(N(R(R((s//usr/lib64/python2.7/Demo/metaclasses/Simple.pytmethod2&s(RR R R!(((s//usr/lib64/python2.7/Demo/metaclasses/Simple.pyR#s i ((((( RRR RRRt aninstanceR R!(((s//usr/lib64/python2.7/Demo/metaclasses/Simple.pyts     PK%L]BO--metaclasses/meta-vladimir.txtnu[Subject: Re: The metaclass saga using Python From: Vladimir Marangozov To: tim_one@email.msn.com (Tim Peters) Cc: python-list@cwi.nl Date: Wed, 5 Aug 1998 15:59:06 +0200 (DFT) [Tim] > > building-on-examples-tends-to-prevent-abstract-thrashing-ly y'rs - tim > OK, I stand corrected. I understand that anybody's interpretation of the meta-class concept is likely to be difficult to digest by others. Here's another try, expressing the same thing, but using the Python programming model, examples and, perhaps, more popular terms. 1. Classes. This is pure Python of today. Sorry about the tutorial, but it is meant to illustrate the second part, which is the one we're interested in and which will follow the same development scenario. Besides, newbies are likely to understand that the discussion is affordable even for them :-) a) Class definition A class is meant to define the common properties of a set of objects. A class is a "package" of properties. The assembly of properties in a class package is sometimes called a class structure (which isn't always appropriate). >>> class A: attr1 = "Hello" # an attribute of A def method1(self, *args): pass # method1 of A def method2(self, *args): pass # method2 of A >>> So far, we defined the structure of the class A. The class A is of type . We can check this by asking Python: "what is A?" >>> A # What is A? b) Class instantiation Creating an object with the properties defined in the class A is called instantiation of the class A. After an instantiation of A, we obtain a new object, called an instance, which has the properties packaged in the class A. >>> a = A() # 'a' is the 1st instance of A >>> a # What is 'a'? <__main__.A instance at 2022b9d0> >>> b = A() # 'b' is another instance of A >>> b # What is 'b'? <__main__.A instance at 2022b9c0> The objects, 'a' and 'b', are of type and they both have the same properties. Note, that 'a' and 'b' are different objects. (their adresses differ). This is a bit hard to see, so let's ask Python: >>> a == b # Is 'a' the same object as 'b'? 0 # No. Instance objects have one more special property, indicating the class they are an instance of. This property is named __class__. >>> a.__class__ # What is the class of 'a'? # 'a' is an instance of A >>> b.__class__ # What is the class of 'b'? # 'b' is an instance of A >>> a.__class__ == b.__class__ # Is it really the same class A? 1 # Yes. c) Class inheritance (class composition and specialization) Classes can be defined in terms of other existing classes (and only classes! -- don't bug me on this now). Thus, we can compose property packages and create new ones. We reuse the property set defined in a class by defining a new class, which "inherits" from the former. In other words, a class B which inherits from the class A, inherits the properties defined in A, or, B inherits the structure of A. In the same time, at the definition of the new class B, we can enrich the inherited set of properties by adding new ones and/or modify some of the inherited properties. >>> class B(A): # B inherits A's properties attr2 = "World" # additional attr2 def method2(self, arg1): pass # method2 is redefined def method3(self, *args): pass # additional method3 >>> B # What is B? >>> B == A # Is B the same class as A? 0 # No. Classes define one special property, indicating whether a class inherits the properties of another class. This property is called __bases__ and it contains a list (a tuple) of the classes the new class inherits from. The classes from which a class is inheriting the properties are called superclasses (in Python, we call them also -- base classes). >>> A.__bases__ # Does A have any superclasses? () # No. >>> B.__bases__ # Does B have any superclasses? (,) # Yes. It has one superclass. >>> B.__bases__[0] == A # Is it really the class A? 1 # Yes, it is. -------- Congratulations on getting this far! This was the hard part. Now, let's continue with the easy one. -------- 2. Meta-classes You have to admit, that an anonymous group of Python wizards are not satisfied with the property packaging facilities presented above. They say, that the Real-World bugs them with problems that cannot be modelled successfully with classes. Or, that the way classes are implemented in Python and the way classes and instances behave at runtime isn't always appropriate for reproducing the Real-World's behavior in a way that satisfies them. Hence, what they want is the following: a) leave objects as they are (instances of classes) b) leave classes as they are (property packages and object creators) BUT, at the same time: c) consider classes as being instances of mysterious objects. d) label mysterious objects "meta-classes". Easy, eh? You may ask: "Why on earth do they want to do that?". They answer: "Poor soul... Go and see how cruel the Real-World is!". You - fuzzy: "OK, will do!" And here we go for another round of what I said in section 1 -- Classes. However, be warned! The features we're going to talk about aren't fully implemented yet, because the Real-World don't let wizards to evaluate precisely how cruel it is, so the features are still highly-experimental. a) Meta-class definition A meta-class is meant to define the common properties of a set of classes. A meta-class is a "package" of properties. The assembly of properties in a meta-class package is sometimes called a meta-class structure (which isn't always appropriate). In Python, a meta-class definition would have looked like this: >>> metaclass M: attr1 = "Hello" # an attribute of M def method1(self, *args): pass # method1 of M def method2(self, *args): pass # method2 of M >>> So far, we defined the structure of the meta-class M. The meta-class M is of type . We cannot check this by asking Python, but if we could, it would have answered: >>> M # What is M? b) Meta-class instantiation Creating an object with the properties defined in the meta-class M is called instantiation of the meta-class M. After an instantiation of M, we obtain a new object, called an class, but now it is called also a meta-instance, which has the properties packaged in the meta-class M. In Python, instantiating a meta-class would have looked like this: >>> A = M() # 'A' is the 1st instance of M >>> A # What is 'A'? >>> B = M() # 'B' is another instance of M >>> B # What is 'B'? The metaclass-instances, A and B, are of type and they both have the same properties. Note, that A and B are different objects. (their adresses differ). This is a bit hard to see, but if it was possible to ask Python, it would have answered: >>> A == B # Is A the same class as B? 0 # No. Class objects have one more special property, indicating the meta-class they are an instance of. This property is named __metaclass__. >>> A.__metaclass__ # What is the meta-class of A? # A is an instance of M >>> A.__metaclass__ # What is the meta-class of B? # B is an instance of M >>> A.__metaclass__ == B.__metaclass__ # Is it the same meta-class M? 1 # Yes. c) Meta-class inheritance (meta-class composition and specialization) Meta-classes can be defined in terms of other existing meta-classes (and only meta-classes!). Thus, we can compose property packages and create new ones. We reuse the property set defined in a meta-class by defining a new meta-class, which "inherits" from the former. In other words, a meta-class N which inherits from the meta-class M, inherits the properties defined in M, or, N inherits the structure of M. In the same time, at the definition of the new meta-class N, we can enrich the inherited set of properties by adding new ones and/or modify some of the inherited properties. >>> metaclass N(M): # N inherits M's properties attr2 = "World" # additional attr2 def method2(self, arg1): pass # method2 is redefined def method3(self, *args): pass # additional method3 >>> N # What is N? >>> N == M # Is N the same meta-class as M? 0 # No. Meta-classes define one special property, indicating whether a meta-class inherits the properties of another meta-class. This property is called __metabases__ and it contains a list (a tuple) of the meta-classes the new meta-class inherits from. The meta-classes from which a meta-class is inheriting the properties are called super-meta-classes (in Python, we call them also -- super meta-bases). >>> M.__metabases__ # Does M have any supermetaclasses? () # No. >>> N.__metabases__ # Does N have any supermetaclasses? (,) # Yes. It has a supermetaclass. >>> N.__metabases__[0] == M # Is it really the meta-class M? 1 # Yes, it is. -------- Triple congratulations on getting this far! Now you know everything about meta-classes and the Real-World! -- Vladimir MARANGOZOV | Vladimir.Marangozov@inrialpes.fr http://sirac.inrialpes.fr/~marangoz | tel:(+33-4)76615277 fax:76615252 PK%L]Nιu u metaclasses/Meta.pynu["""Generic metaclass. XXX This is very much a work in progress. """ import types class MetaMethodWrapper: def __init__(self, func, inst): self.func = func self.inst = inst self.__name__ = self.func.__name__ def __call__(self, *args, **kw): return apply(self.func, (self.inst,) + args, kw) class MetaHelper: __methodwrapper__ = MetaMethodWrapper # For derived helpers to override def __helperinit__(self, formalclass): self.__formalclass__ = formalclass def __getattr__(self, name): # Invoked for any attr not in the instance's __dict__ try: raw = self.__formalclass__.__getattr__(name) except AttributeError: try: ga = self.__formalclass__.__getattr__('__usergetattr__') except (KeyError, AttributeError): raise AttributeError, name return ga(self, name) if type(raw) != types.FunctionType: return raw return self.__methodwrapper__(raw, self) class MetaClass: """A generic metaclass. This can be subclassed to implement various kinds of meta-behavior. """ __helper__ = MetaHelper # For derived metaclasses to override __inited = 0 def __init__(self, name, bases, dict): try: ga = dict['__getattr__'] except KeyError: pass else: dict['__usergetattr__'] = ga del dict['__getattr__'] self.__name__ = name self.__bases__ = bases self.__realdict__ = dict self.__inited = 1 def __getattr__(self, name): try: return self.__realdict__[name] except KeyError: for base in self.__bases__: try: return base.__getattr__(name) except AttributeError: pass raise AttributeError, name def __setattr__(self, name, value): if not self.__inited: self.__dict__[name] = value else: self.__realdict__[name] = value def __call__(self, *args, **kw): inst = self.__helper__() inst.__helperinit__(self) try: init = inst.__getattr__('__init__') except AttributeError: init = lambda: None apply(init, args, kw) return inst Meta = MetaClass('Meta', (), {}) def _test(): class C(Meta): def __init__(self, *args): print "__init__, args =", args def m1(self, x): print "m1(x=%r)" % (x,) print C x = C() print x x.m1(12) class D(C): def __getattr__(self, name): if name[:2] == '__': raise AttributeError, name return "getattr:%s" % name x = D() print x.foo print x._foo ## print x.__foo ## print x.__foo__ if __name__ == '__main__': _test() PK%L]DREADMEnu[This directory contains various demonstrations of what you can do with Python. They were all written by me except where explicitly stated otherwise -- in general, demos contributed by others ends up in the ../Contrib directory, unless I think they're of utmost general importance (like Matt Conway's Tk demos). A fair number of utilities that are useful when while developing Python code can be found in the ../Tools directory -- some of these can also be considered good examples of how to write Python code. Finally, in order to save disk space and net bandwidth, not all subdirectories listed here are distributed. They are listed just in case I change my mind about them. cgi CGI examples (see also ../Tools/faqwiz/.) classes Some examples of how to use classes. comparisons A set of responses to a really old language-comparison challenge. curses A set of curses demos. embed An example of embedding Python in another application (see also pysvr). imputil Demonstration subclasses of imputil.Importer. md5test Test program for the optional md5 module. metaclasses The code from the 1.5 metaclasses paper on the web. parser Example using the parser module. pdist Old, unfinished code messing with CVS, RCS and remote files. pysvr An example of embedding Python in a threaded application. rpc A set of classes for building clients and servers for Sun RPC. scripts Some useful Python scripts that I put in my bin directory. No optional built-in modules needed. sockets Examples for the new built-in module 'socket'. threads Demos that use the 'thread' module. (Currently these only run on SGIs, but this may change in the future.) tix Demos using the Tix widget set addition to Tkinter. tkinter Demos using the Tk interface (including Matt Conway's excellent set of demos). xml Some XML demos. zlib Some demos for the zlib module (see also the standard library module gzip.py). PK%L]/ classes/Dates.pynu[# Class Date supplies date objects that support date arithmetic. # # Date(month,day,year) returns a Date object. An instance prints as, # e.g., 'Mon 16 Aug 1993'. # # Addition, subtraction, comparison operators, min, max, and sorting # all work as expected for date objects: int+date or date+int returns # the date `int' days from `date'; date+date raises an exception; # date-int returns the date `int' days before `date'; date2-date1 returns # an integer, the number of days from date1 to date2; int-date raises an # exception; date1 < date2 is true iff date1 occurs before date2 (& # similarly for other comparisons); min(date1,date2) is the earlier of # the two dates and max(date1,date2) the later; and date objects can be # used as dictionary keys. # # Date objects support one visible method, date.weekday(). This returns # the day of the week the date falls on, as a string. # # Date objects also have 4 read-only data attributes: # .month in 1..12 # .day in 1..31 # .year int or long int # .ord the ordinal of the date relative to an arbitrary staring point # # The Dates module also supplies function today(), which returns the # current date as a date object. # # Those entranced by calendar trivia will be disappointed, as no attempt # has been made to accommodate the Julian (etc) system. On the other # hand, at least this package knows that 2000 is a leap year but 2100 # isn't, and works fine for years with a hundred decimal digits . # Tim Peters tim@ksr.com # not speaking for Kendall Square Research Corp # Adapted to Python 1.1 (where some hacks to overcome coercion are unnecessary) # by Guido van Rossum # Note that as of Python 2.3, a datetime module is included in the stardard # library. # vi:set tabsize=8: _MONTH_NAMES = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] _DAY_NAMES = [ 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday' ] _DAYS_IN_MONTH = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ] _DAYS_BEFORE_MONTH = [] dbm = 0 for dim in _DAYS_IN_MONTH: _DAYS_BEFORE_MONTH.append(dbm) dbm = dbm + dim del dbm, dim _INT_TYPES = type(1), type(1L) def _is_leap(year): # 1 if leap year, else 0 if year % 4 != 0: return 0 if year % 400 == 0: return 1 return year % 100 != 0 def _days_in_year(year): # number of days in year return 365 + _is_leap(year) def _days_before_year(year): # number of days before year return year*365L + (year+3)//4 - (year+99)//100 + (year+399)//400 def _days_in_month(month, year): # number of days in month of year if month == 2 and _is_leap(year): return 29 return _DAYS_IN_MONTH[month-1] def _days_before_month(month, year): # number of days in year before month return _DAYS_BEFORE_MONTH[month-1] + (month > 2 and _is_leap(year)) def _date2num(date): # compute ordinal of date.month,day,year return _days_before_year(date.year) + \ _days_before_month(date.month, date.year) + \ date.day _DI400Y = _days_before_year(400) # number of days in 400 years def _num2date(n): # return date with ordinal n if type(n) not in _INT_TYPES: raise TypeError, 'argument must be integer: %r' % type(n) ans = Date(1,1,1) # arguments irrelevant; just getting a Date obj del ans.ord, ans.month, ans.day, ans.year # un-initialize it ans.ord = n n400 = (n-1)//_DI400Y # # of 400-year blocks preceding year, n = 400 * n400, n - _DI400Y * n400 more = n // 365 dby = _days_before_year(more) if dby >= n: more = more - 1 dby = dby - _days_in_year(more) year, n = year + more, int(n - dby) try: year = int(year) # chop to int, if it fits except (ValueError, OverflowError): pass month = min(n//29 + 1, 12) dbm = _days_before_month(month, year) if dbm >= n: month = month - 1 dbm = dbm - _days_in_month(month, year) ans.month, ans.day, ans.year = month, n-dbm, year return ans def _num2day(n): # return weekday name of day with ordinal n return _DAY_NAMES[ int(n % 7) ] class Date: def __init__(self, month, day, year): if not 1 <= month <= 12: raise ValueError, 'month must be in 1..12: %r' % (month,) dim = _days_in_month(month, year) if not 1 <= day <= dim: raise ValueError, 'day must be in 1..%r: %r' % (dim, day) self.month, self.day, self.year = month, day, year self.ord = _date2num(self) # don't allow setting existing attributes def __setattr__(self, name, value): if self.__dict__.has_key(name): raise AttributeError, 'read-only attribute ' + name self.__dict__[name] = value def __cmp__(self, other): return cmp(self.ord, other.ord) # define a hash function so dates can be used as dictionary keys def __hash__(self): return hash(self.ord) # print as, e.g., Mon 16 Aug 1993 def __repr__(self): return '%.3s %2d %.3s %r' % ( self.weekday(), self.day, _MONTH_NAMES[self.month-1], self.year) # Python 1.1 coerces neither int+date nor date+int def __add__(self, n): if type(n) not in _INT_TYPES: raise TypeError, 'can\'t add %r to date' % type(n) return _num2date(self.ord + n) __radd__ = __add__ # handle int+date # Python 1.1 coerces neither date-int nor date-date def __sub__(self, other): if type(other) in _INT_TYPES: # date-int return _num2date(self.ord - other) else: return self.ord - other.ord # date-date # complain about int-date def __rsub__(self, other): raise TypeError, 'Can\'t subtract date from integer' def weekday(self): return _num2day(self.ord) def today(): import time local = time.localtime(time.time()) return Date(local[1], local[2], local[0]) class DateTestError(Exception): pass def test(firstyear, lastyear): a = Date(9,30,1913) b = Date(9,30,1914) if repr(a) != 'Tue 30 Sep 1913': raise DateTestError, '__repr__ failure' if (not a < b) or a == b or a > b or b != b: raise DateTestError, '__cmp__ failure' if a+365 != b or 365+a != b: raise DateTestError, '__add__ failure' if b-a != 365 or b-365 != a: raise DateTestError, '__sub__ failure' try: x = 1 - a raise DateTestError, 'int-date should have failed' except TypeError: pass try: x = a + b raise DateTestError, 'date+date should have failed' except TypeError: pass if a.weekday() != 'Tuesday': raise DateTestError, 'weekday() failure' if max(a,b) is not b or min(a,b) is not a: raise DateTestError, 'min/max failure' d = {a-1:b, b:a+1} if d[b-366] != b or d[a+(b-a)] != Date(10,1,1913): raise DateTestError, 'dictionary failure' # verify date<->number conversions for first and last days for # all years in firstyear .. lastyear lord = _days_before_year(firstyear) y = firstyear while y <= lastyear: ford = lord + 1 lord = ford + _days_in_year(y) - 1 fd, ld = Date(1,1,y), Date(12,31,y) if (fd.ord,ld.ord) != (ford,lord): raise DateTestError, ('date->num failed', y) fd, ld = _num2date(ford), _num2date(lord) if (1,1,y,12,31,y) != \ (fd.month,fd.day,fd.year,ld.month,ld.day,ld.year): raise DateTestError, ('num->date failed', y) y = y + 1 if __name__ == '__main__': test(1850, 2150) PK%L]ΎMMclasses/Vec.pynu[class Vec: """ A simple vector class Instances of the Vec class can be constructed from numbers >>> a = Vec(1, 2, 3) >>> b = Vec(3, 2, 1) added >>> a + b Vec(4, 4, 4) subtracted >>> a - b Vec(-2, 0, 2) and multiplied by a scalar on the left >>> 3.0 * a Vec(3.0, 6.0, 9.0) or on the right >>> a * 3.0 Vec(3.0, 6.0, 9.0) """ def __init__(self, *v): self.v = list(v) @classmethod def fromlist(cls, v): if not isinstance(v, list): raise TypeError inst = cls() inst.v = v return inst def __repr__(self): args = ', '.join(repr(x) for x in self.v) return 'Vec({0})'.format(args) def __len__(self): return len(self.v) def __getitem__(self, i): return self.v[i] def __add__(self, other): # Element-wise addition v = [x + y for x, y in zip(self.v, other.v)] return Vec.fromlist(v) def __sub__(self, other): # Element-wise subtraction v = [x - y for x, y in zip(self.v, other.v)] return Vec.fromlist(v) def __mul__(self, scalar): # Multiply by scalar v = [x * scalar for x in self.v] return Vec.fromlist(v) __rmul__ = __mul__ def test(): import doctest doctest.testmod() test() PK%L]j%&&classes/Dbm.pynu[# A wrapper around the (optional) built-in class dbm, supporting keys # and values of almost any type instead of just string. # (Actually, this works only for keys and values that can be read back # correctly after being converted to a string.) class Dbm: def __init__(self, filename, mode, perm): import dbm self.db = dbm.open(filename, mode, perm) def __repr__(self): s = '' for key in self.keys(): t = repr(key) + ': ' + repr(self[key]) if s: t = ', ' + t s = s + t return '{' + s + '}' def __len__(self): return len(self.db) def __getitem__(self, key): return eval(self.db[repr(key)]) def __setitem__(self, key, value): self.db[repr(key)] = repr(value) def __delitem__(self, key): del self.db[repr(key)] def keys(self): res = [] for key in self.db.keys(): res.append(eval(key)) return res def has_key(self, key): return self.db.has_key(repr(key)) def test(): d = Dbm('@dbm', 'rw', 0600) print d while 1: try: key = input('key: ') if d.has_key(key): value = d[key] print 'currently:', value value = input('value: ') if value is None: del d[key] else: d[key] = value except KeyboardInterrupt: print '' print d except EOFError: print '[eof]' break print d test() PK%L]Eclasses/Range.pyonu[ ^c@sNdZdZdZdddYZdZedkrJendS( s Example of a generator: re-implement the built-in range function without actually constructing the list of values. OldStyleRange is coded in the way required to work in a 'for' loop before iterators were introduced into the language; using __getitem__ and __len__ . cCsyt|dkr,dt|ddfSt|dkr_t|dt|ddfSt|dkr|ddkrtdntd|DStdt|Wntk rtdnXd S( sgTake list of arguments and extract/create proper start, stop, and step values and return in a tupleiiiisstep argument must not be zerocss|]}t|VqdS(N(tint(t.0tx((s*/usr/lib64/python2.7/Demo/classes/Range.pys ss$range() accepts 1-3 arguments, givensArange() arguments must be numbers or strings representing numbersN(tlenRt ValueErrorttuplet TypeError(targlist((s*/usr/lib64/python2.7/Demo/classes/Range.pyt handleargss! cgsAt|\}}}|}x||kr<|V||7}qWdS(s,Function to implement 'range' as a generatorN(R(tatstarttstoptsteptvalue((s*/usr/lib64/python2.7/Demo/classes/Range.pytgenranges toldrangecBs2eZdZdZdZdZdZRS(sClass implementing a range object. To the user the instances feel like immutable sequences (and you can't concatenate or slice them) Done using the old way (pre-iterators; __len__ and __getitem__) to have an object be used by a 'for' loop. cGsEt|\|_|_|_td|j|j|j|_dS(s Initialize start, stop, and step values along with calculating the nubmer of values (what __len__ will return) in the rangeiN(RR R R tmaxR(tselfR ((s*/usr/lib64/python2.7/Demo/classes/Range.pyt__init__,scCsd|j|j|jfS(s-implement repr(x) which is also used by printsrange(%r, %r, %r)(R R R (R((s*/usr/lib64/python2.7/Demo/classes/Range.pyt__repr__2scCs|jS(simplement len(x)(R(R((s*/usr/lib64/python2.7/Demo/classes/Range.pyt__len__6scCs>d|ko|jknr1|j|j|StddS(simplement x[i]isrange[i] index out of rangeN(RR R t IndexError(Rti((s*/usr/lib64/python2.7/Demo/classes/Range.pyt __getitem__:s(t__name__t __module__t__doc__RRRR(((s*/usr/lib64/python2.7/Demo/classes/Range.pyR"s    c Cs9ddl}ddl}|jddd}ttddd}ttddd}||ksu||krtd|||fndGH|j}xtdD]}qW|j}xtdD]}qW|j}x|jdD]}qW|j} ||GdGH||Gd GH| |Gd GHdS( NiiidisEerror in implementation: correct = %s old-style = %s generator = %ssTimings for range(1000):issec (old-style class)ssec (generator)ssec (built-in)(ttimet __builtin__trangetlistRRt Exception( RRtcorrect_resulttoldrange_resulttgenrange_resulttt1Rtt2tt3tt4((s*/usr/lib64/python2.7/Demo/classes/Range.pyttestBs*      t__main__N((RRRRR'R(((s*/usr/lib64/python2.7/Demo/classes/Range.pyts     PK%L] classes/Dbm.pycnu[ ^c@s'dddYZdZedS(tDbmcBsPeZdZdZdZdZdZdZdZdZ RS(cCs(ddl}|j||||_dS(Ni(tdbmtopentdb(tselftfilenametmodetpermR((s(/usr/lib64/python2.7/Demo/classes/Dbm.pyt__init__ s cCsdd}xO|jD]A}t|dt||}|rJd|}n||}qWd|dS(Nts: s, t{t}(tkeystrepr(Rtstkeytt((s(/usr/lib64/python2.7/Demo/classes/Dbm.pyt__repr__ s cCs t|jS(N(tlenR(R((s(/usr/lib64/python2.7/Demo/classes/Dbm.pyt__len__scCst|jt|S(N(tevalRR (RR((s(/usr/lib64/python2.7/Demo/classes/Dbm.pyt __getitem__scCst||jt|s$ PK%L](  classes/READMEnu[Examples of classes that implement special operators (see reference manual): Complex.py Complex numbers Dates.py Date manipulation package by Tim Peters Dbm.py Wrapper around built-in dbm, supporting arbitrary values Range.py Example of a generator: re-implement built-in range() Rev.py Yield the reverse of a sequence Vec.py A simple vector class bitvec.py A bit-vector class by Jan-Hein B\"uhrman (For straightforward examples of basic class features, such as use of methods and inheritance, see the library code.) PK%L]u+&&classes/Complex.pynu[# Complex numbers # --------------- # [Now that Python has a complex data type built-in, this is not very # useful, but it's still a nice example class] # This module represents complex numbers as instances of the class Complex. # A Complex instance z has two data attribues, z.re (the real part) and z.im # (the imaginary part). In fact, z.re and z.im can have any value -- all # arithmetic operators work regardless of the type of z.re and z.im (as long # as they support numerical operations). # # The following functions exist (Complex is actually a class): # Complex([re [,im]) -> creates a complex number from a real and an imaginary part # IsComplex(z) -> true iff z is a complex number (== has .re and .im attributes) # ToComplex(z) -> a complex number equal to z; z itself if IsComplex(z) is true # if z is a tuple(re, im) it will also be converted # PolarToComplex([r [,phi [,fullcircle]]]) -> # the complex number z for which r == z.radius() and phi == z.angle(fullcircle) # (r and phi default to 0) # exp(z) -> returns the complex exponential of z. Equivalent to pow(math.e,z). # # Complex numbers have the following methods: # z.abs() -> absolute value of z # z.radius() == z.abs() # z.angle([fullcircle]) -> angle from positive X axis; fullcircle gives units # z.phi([fullcircle]) == z.angle(fullcircle) # # These standard functions and unary operators accept complex arguments: # abs(z) # -z # +z # not z # repr(z) == `z` # str(z) # hash(z) -> a combination of hash(z.re) and hash(z.im) such that if z.im is zero # the result equals hash(z.re) # Note that hex(z) and oct(z) are not defined. # # These conversions accept complex arguments only if their imaginary part is zero: # int(z) # long(z) # float(z) # # The following operators accept two complex numbers, or one complex number # and one real number (int, long or float): # z1 + z2 # z1 - z2 # z1 * z2 # z1 / z2 # pow(z1, z2) # cmp(z1, z2) # Note that z1 % z2 and divmod(z1, z2) are not defined, # nor are shift and mask operations. # # The standard module math does not support complex numbers. # The cmath modules should be used instead. # # Idea: # add a class Polar(r, phi) and mixed-mode arithmetic which # chooses the most appropriate type for the result: # Complex for +,-,cmp # Polar for *,/,pow import math import sys twopi = math.pi*2.0 halfpi = math.pi/2.0 def IsComplex(obj): return hasattr(obj, 're') and hasattr(obj, 'im') def ToComplex(obj): if IsComplex(obj): return obj elif isinstance(obj, tuple): return Complex(*obj) else: return Complex(obj) def PolarToComplex(r = 0, phi = 0, fullcircle = twopi): phi = phi * (twopi / fullcircle) return Complex(math.cos(phi)*r, math.sin(phi)*r) def Re(obj): if IsComplex(obj): return obj.re return obj def Im(obj): if IsComplex(obj): return obj.im return 0 class Complex: def __init__(self, re=0, im=0): _re = 0 _im = 0 if IsComplex(re): _re = re.re _im = re.im else: _re = re if IsComplex(im): _re = _re - im.im _im = _im + im.re else: _im = _im + im # this class is immutable, so setting self.re directly is # not possible. self.__dict__['re'] = _re self.__dict__['im'] = _im def __setattr__(self, name, value): raise TypeError, 'Complex numbers are immutable' def __hash__(self): if not self.im: return hash(self.re) return hash((self.re, self.im)) def __repr__(self): if not self.im: return 'Complex(%r)' % (self.re,) else: return 'Complex(%r, %r)' % (self.re, self.im) def __str__(self): if not self.im: return repr(self.re) else: return 'Complex(%r, %r)' % (self.re, self.im) def __neg__(self): return Complex(-self.re, -self.im) def __pos__(self): return self def __abs__(self): return math.hypot(self.re, self.im) def __int__(self): if self.im: raise ValueError, "can't convert Complex with nonzero im to int" return int(self.re) def __long__(self): if self.im: raise ValueError, "can't convert Complex with nonzero im to long" return long(self.re) def __float__(self): if self.im: raise ValueError, "can't convert Complex with nonzero im to float" return float(self.re) def __cmp__(self, other): other = ToComplex(other) return cmp((self.re, self.im), (other.re, other.im)) def __rcmp__(self, other): other = ToComplex(other) return cmp(other, self) def __nonzero__(self): return not (self.re == self.im == 0) abs = radius = __abs__ def angle(self, fullcircle = twopi): return (fullcircle/twopi) * ((halfpi - math.atan2(self.re, self.im)) % twopi) phi = angle def __add__(self, other): other = ToComplex(other) return Complex(self.re + other.re, self.im + other.im) __radd__ = __add__ def __sub__(self, other): other = ToComplex(other) return Complex(self.re - other.re, self.im - other.im) def __rsub__(self, other): other = ToComplex(other) return other - self def __mul__(self, other): other = ToComplex(other) return Complex(self.re*other.re - self.im*other.im, self.re*other.im + self.im*other.re) __rmul__ = __mul__ def __div__(self, other): other = ToComplex(other) d = float(other.re*other.re + other.im*other.im) if not d: raise ZeroDivisionError, 'Complex division' return Complex((self.re*other.re + self.im*other.im) / d, (self.im*other.re - self.re*other.im) / d) def __rdiv__(self, other): other = ToComplex(other) return other / self def __pow__(self, n, z=None): if z is not None: raise TypeError, 'Complex does not support ternary pow()' if IsComplex(n): if n.im: if self.im: raise TypeError, 'Complex to the Complex power' else: return exp(math.log(self.re)*n) n = n.re r = pow(self.abs(), n) phi = n*self.angle() return Complex(math.cos(phi)*r, math.sin(phi)*r) def __rpow__(self, base): base = ToComplex(base) return pow(base, self) def exp(z): r = math.exp(z.re) return Complex(math.cos(z.im)*r,math.sin(z.im)*r) def checkop(expr, a, b, value, fuzz = 1e-6): print ' ', a, 'and', b, try: result = eval(expr) except: result = sys.exc_type print '->', result if isinstance(result, str) or isinstance(value, str): ok = (result == value) else: ok = abs(result - value) <= fuzz if not ok: print '!!\t!!\t!! should be', value, 'diff', abs(result - value) def test(): print 'test constructors' constructor_test = ( # "expect" is an array [re,im] "got" the Complex. ( (0,0), Complex() ), ( (0,0), Complex() ), ( (1,0), Complex(1) ), ( (0,1), Complex(0,1) ), ( (1,2), Complex(Complex(1,2)) ), ( (1,3), Complex(Complex(1,2),1) ), ( (0,0), Complex(0,Complex(0,0)) ), ( (3,4), Complex(3,Complex(4)) ), ( (-1,3), Complex(1,Complex(3,2)) ), ( (-7,6), Complex(Complex(1,2),Complex(4,8)) ) ) cnt = [0,0] for t in constructor_test: cnt[0] += 1 if ((t[0][0]!=t[1].re)or(t[0][1]!=t[1].im)): print " expected", t[0], "got", t[1] cnt[1] += 1 print " ", cnt[1], "of", cnt[0], "tests failed" # test operators testsuite = { 'a+b': [ (1, 10, 11), (1, Complex(0,10), Complex(1,10)), (Complex(0,10), 1, Complex(1,10)), (Complex(0,10), Complex(1), Complex(1,10)), (Complex(1), Complex(0,10), Complex(1,10)), ], 'a-b': [ (1, 10, -9), (1, Complex(0,10), Complex(1,-10)), (Complex(0,10), 1, Complex(-1,10)), (Complex(0,10), Complex(1), Complex(-1,10)), (Complex(1), Complex(0,10), Complex(1,-10)), ], 'a*b': [ (1, 10, 10), (1, Complex(0,10), Complex(0, 10)), (Complex(0,10), 1, Complex(0,10)), (Complex(0,10), Complex(1), Complex(0,10)), (Complex(1), Complex(0,10), Complex(0,10)), ], 'a/b': [ (1., 10, 0.1), (1, Complex(0,10), Complex(0, -0.1)), (Complex(0, 10), 1, Complex(0, 10)), (Complex(0, 10), Complex(1), Complex(0, 10)), (Complex(1), Complex(0,10), Complex(0, -0.1)), ], 'pow(a,b)': [ (1, 10, 1), (1, Complex(0,10), 1), (Complex(0,10), 1, Complex(0,10)), (Complex(0,10), Complex(1), Complex(0,10)), (Complex(1), Complex(0,10), 1), (2, Complex(4,0), 16), ], 'cmp(a,b)': [ (1, 10, -1), (1, Complex(0,10), 1), (Complex(0,10), 1, -1), (Complex(0,10), Complex(1), -1), (Complex(1), Complex(0,10), 1), ], } for expr in sorted(testsuite): print expr + ':' t = (expr,) for item in testsuite[expr]: checkop(*(t+item)) if __name__ == '__main__': test() PK%L]1 1 classes/Rev.pycnu[ ^c@s<dZdddYZdZedkr8endS(s A class which presents the reverse of a sequence without duplicating it. From: "Steven D. Majewski" It works on mutable or inmutable sequences. >>> chars = list(Rev('Hello World!')) >>> print ''.join(chars) !dlroW olleH The .forw is so you can use anonymous sequences in __init__, and still keep a reference the forward sequence. ) If you give it a non-anonymous mutable sequence, the reverse sequence will track the updated values. ( but not reassignment! - another good reason to use anonymous values in creating the sequence to avoid confusion. Maybe it should be change to copy input sequence to break the connection completely ? ) >>> nnn = range(3) >>> rnn = Rev(nnn) >>> for n in rnn: print n ... 2 1 0 >>> for n in range(4, 6): nnn.append(n) # update nnn ... >>> for n in rnn: print n # prints reversed updated values ... 5 4 2 1 0 >>> nnn = nnn[1:-1] >>> nnn [1, 2, 4] >>> for n in rnn: print n # prints reversed values of old nnn ... 5 4 2 1 0 # >>> WH = Rev('Hello World!') >>> print WH.forw, WH.back Hello World! !dlroW olleH >>> nnn = Rev(range(1, 10)) >>> print nnn.forw [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> print nnn.back [9, 8, 7, 6, 5, 4, 3, 2, 1] >>> rrr = Rev(nnn) >>> rrr <1, 2, 3, 4, 5, 6, 7, 8, 9> tRevcBs,eZdZdZdZdZRS(cCs||_||_dS(N(tforwtback(tselftseq((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt__init__?s cCs t|jS(N(tlenR(R((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt__len__CscCs|j|d S(Ni(R(Rtj((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt __getitem__FscCs|j}t|tr'd}d}nHt|trEd}d}n*t|trcd}d}n d}d}g|jD]}t|^qy}|d |j||dS(Ns[]s, s()ts<>ii(Rt isinstancetlistttupletstrRtjoin(RRtwraptseptitemtoutstrs((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt__repr__Is    "(t__name__t __module__RRR R(((s(/usr/lib64/python2.7/Demo/classes/Rev.pyR>s   cCs%ddl}ddl}|j|S(Ni(tdoctestRttestmod(RR((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt_testZst__main__N((t__doc__RRR(((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt<s  PK%L]nL6 6 classes/Range.pynu["""Example of a generator: re-implement the built-in range function without actually constructing the list of values. OldStyleRange is coded in the way required to work in a 'for' loop before iterators were introduced into the language; using __getitem__ and __len__ . """ def handleargs(arglist): """Take list of arguments and extract/create proper start, stop, and step values and return in a tuple""" try: if len(arglist) == 1: return 0, int(arglist[0]), 1 elif len(arglist) == 2: return int(arglist[0]), int(arglist[1]), 1 elif len(arglist) == 3: if arglist[2] == 0: raise ValueError("step argument must not be zero") return tuple(int(x) for x in arglist) else: raise TypeError("range() accepts 1-3 arguments, given", len(arglist)) except TypeError: raise TypeError("range() arguments must be numbers or strings " "representing numbers") def genrange(*a): """Function to implement 'range' as a generator""" start, stop, step = handleargs(a) value = start while value < stop: yield value value += step class oldrange: """Class implementing a range object. To the user the instances feel like immutable sequences (and you can't concatenate or slice them) Done using the old way (pre-iterators; __len__ and __getitem__) to have an object be used by a 'for' loop. """ def __init__(self, *a): """ Initialize start, stop, and step values along with calculating the nubmer of values (what __len__ will return) in the range""" self.start, self.stop, self.step = handleargs(a) self.len = max(0, (self.stop - self.start) // self.step) def __repr__(self): """implement repr(x) which is also used by print""" return 'range(%r, %r, %r)' % (self.start, self.stop, self.step) def __len__(self): """implement len(x)""" return self.len def __getitem__(self, i): """implement x[i]""" if 0 <= i <= self.len: return self.start + self.step * i else: raise IndexError, 'range[i] index out of range' def test(): import time, __builtin__ #Just a quick sanity check correct_result = __builtin__.range(5, 100, 3) oldrange_result = list(oldrange(5, 100, 3)) genrange_result = list(genrange(5, 100, 3)) if genrange_result != correct_result or oldrange_result != correct_result: raise Exception("error in implementation:\ncorrect = %s" "\nold-style = %s\ngenerator = %s" % (correct_result, oldrange_result, genrange_result)) print "Timings for range(1000):" t1 = time.time() for i in oldrange(1000): pass t2 = time.time() for i in genrange(1000): pass t3 = time.time() for i in __builtin__.range(1000): pass t4 = time.time() print t2-t1, 'sec (old-style class)' print t3-t2, 'sec (generator)' print t4-t3, 'sec (built-in)' if __name__ == '__main__': test() PK%L]FI&'&'classes/Complex.pyonu[ ^c@sddlZddlZejdZejdZdZdZddedZdZdZ d dd YZ d Z d d Z dZ edkre ndS(iNg@cCst|dot|dS(Ntretim(thasattr(tobj((s,/usr/lib64/python2.7/Demo/classes/Complex.pyt IsComplexGscCs7t|r|St|tr)t|St|SdS(N(Rt isinstancettupletComplex(R((s,/usr/lib64/python2.7/Demo/classes/Complex.pyt ToComplexJs   icCs5|t|}ttj||tj||S(N(ttwopiRtmathtcostsin(trtphit fullcircle((s,/usr/lib64/python2.7/Demo/classes/Complex.pytPolarToComplexRscCst|r|jS|S(N(RR(R((s,/usr/lib64/python2.7/Demo/classes/Complex.pytReVs cCst|r|jSdS(Ni(RR(R((s,/usr/lib64/python2.7/Demo/classes/Complex.pytIm[s RcBseZdddZdZdZdZdZdZdZdZ d Z d Z d Z d Z d ZdZe ZZedZeZdZeZdZdZdZeZdZdZddZdZRS(icCsd}d}t|r-|j}|j}n|}t|r\||j}||j}n ||}||jd<||jdcCsdG|GdG|Gyt|}Wntj}nXdG|GHt|tsZt|tri||k}nt|||k}|sdG|GdGt||GHndS(Ns tands->s!! !! !! should betdiff(tevaltsystexc_typeRtstrR@(texprtatbRtfuzztresulttok((s,/usr/lib64/python2.7/Demo/classes/Complex.pytcheckops  cCsdGHdtfd tfd!tdfd"tddfd#ttddfd$ttdddfd%tdtddfd&tdtdfd'tdtddfd(ttddtdd ff }ddg}x|D]x}|dcd7<|dd|djksH|dd|djkrd G|dGd G|dGH|dcd7As           J PK%L]Eclasses/Range.pycnu[ ^c@sNdZdZdZdddYZdZedkrJendS( s Example of a generator: re-implement the built-in range function without actually constructing the list of values. OldStyleRange is coded in the way required to work in a 'for' loop before iterators were introduced into the language; using __getitem__ and __len__ . cCsyt|dkr,dt|ddfSt|dkr_t|dt|ddfSt|dkr|ddkrtdntd|DStdt|Wntk rtdnXd S( sgTake list of arguments and extract/create proper start, stop, and step values and return in a tupleiiiisstep argument must not be zerocss|]}t|VqdS(N(tint(t.0tx((s*/usr/lib64/python2.7/Demo/classes/Range.pys ss$range() accepts 1-3 arguments, givensArange() arguments must be numbers or strings representing numbersN(tlenRt ValueErrorttuplet TypeError(targlist((s*/usr/lib64/python2.7/Demo/classes/Range.pyt handleargss! cgsAt|\}}}|}x||kr<|V||7}qWdS(s,Function to implement 'range' as a generatorN(R(tatstarttstoptsteptvalue((s*/usr/lib64/python2.7/Demo/classes/Range.pytgenranges toldrangecBs2eZdZdZdZdZdZRS(sClass implementing a range object. To the user the instances feel like immutable sequences (and you can't concatenate or slice them) Done using the old way (pre-iterators; __len__ and __getitem__) to have an object be used by a 'for' loop. cGsEt|\|_|_|_td|j|j|j|_dS(s Initialize start, stop, and step values along with calculating the nubmer of values (what __len__ will return) in the rangeiN(RR R R tmaxR(tselfR ((s*/usr/lib64/python2.7/Demo/classes/Range.pyt__init__,scCsd|j|j|jfS(s-implement repr(x) which is also used by printsrange(%r, %r, %r)(R R R (R((s*/usr/lib64/python2.7/Demo/classes/Range.pyt__repr__2scCs|jS(simplement len(x)(R(R((s*/usr/lib64/python2.7/Demo/classes/Range.pyt__len__6scCs>d|ko|jknr1|j|j|StddS(simplement x[i]isrange[i] index out of rangeN(RR R t IndexError(Rti((s*/usr/lib64/python2.7/Demo/classes/Range.pyt __getitem__:s(t__name__t __module__t__doc__RRRR(((s*/usr/lib64/python2.7/Demo/classes/Range.pyR"s    c Cs9ddl}ddl}|jddd}ttddd}ttddd}||ksu||krtd|||fndGH|j}xtdD]}qW|j}xtdD]}qW|j}x|jdD]}qW|j} ||GdGH||Gd GH| |Gd GHdS( NiiidisEerror in implementation: correct = %s old-style = %s generator = %ssTimings for range(1000):issec (old-style class)ssec (generator)ssec (built-in)(ttimet __builtin__trangetlistRRt Exception( RRtcorrect_resulttoldrange_resulttgenrange_resulttt1Rtt2tt3tt4((s*/usr/lib64/python2.7/Demo/classes/Range.pyttestBs*      t__main__N((RRRRR'R(((s*/usr/lib64/python2.7/Demo/classes/Range.pyts     PK%L]:6  classes/Vec.pyonu[ ^c@s'dddYZdZedS(tVeccBsbeZdZdZedZdZdZdZdZ dZ dZ e Z RS( sx A simple vector class Instances of the Vec class can be constructed from numbers >>> a = Vec(1, 2, 3) >>> b = Vec(3, 2, 1) added >>> a + b Vec(4, 4, 4) subtracted >>> a - b Vec(-2, 0, 2) and multiplied by a scalar on the left >>> 3.0 * a Vec(3.0, 6.0, 9.0) or on the right >>> a * 3.0 Vec(3.0, 6.0, 9.0) cGst||_dS(N(tlisttv(tselfR((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__init__scCs.t|tstn|}||_|S(N(t isinstanceRt TypeErrorR(tclsRtinst((s(/usr/lib64/python2.7/Demo/classes/Vec.pytfromlists    cCs)djd|jD}dj|S(Ns, css|]}t|VqdS(N(trepr(t.0tx((s(/usr/lib64/python2.7/Demo/classes/Vec.pys %ssVec({0})(tjoinRtformat(Rtargs((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__repr__$scCs t|jS(N(tlenR(R((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__len__(scCs |j|S(N(R(Rti((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt __getitem__+scCs?gt|j|jD]\}}||^q}tj|S(N(tzipRRR (RtotherR tyR((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__add__.s2cCs?gt|j|jD]\}}||^q}tj|S(N(RRRR (RRR RR((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__sub__3s2cCs-g|jD]}||^q }tj|S(N(RRR (RtscalarR R((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__mul__8s ( t__name__t __module__t__doc__Rt classmethodR RRRRRRt__rmul__(((s(/usr/lib64/python2.7/Demo/classes/Vec.pyRs       cCsddl}|jdS(Ni(tdoctestttestmod(R!((s(/usr/lib64/python2.7/Demo/classes/Vec.pyttest@s N((RR#(((s(/usr/lib64/python2.7/Demo/classes/Vec.pyts? PK%L]FI&'&'classes/Complex.pycnu[ ^c@sddlZddlZejdZejdZdZdZddedZdZdZ d dd YZ d Z d d Z dZ edkre ndS(iNg@cCst|dot|dS(Ntretim(thasattr(tobj((s,/usr/lib64/python2.7/Demo/classes/Complex.pyt IsComplexGscCs7t|r|St|tr)t|St|SdS(N(Rt isinstancettupletComplex(R((s,/usr/lib64/python2.7/Demo/classes/Complex.pyt ToComplexJs   icCs5|t|}ttj||tj||S(N(ttwopiRtmathtcostsin(trtphit fullcircle((s,/usr/lib64/python2.7/Demo/classes/Complex.pytPolarToComplexRscCst|r|jS|S(N(RR(R((s,/usr/lib64/python2.7/Demo/classes/Complex.pytReVs cCst|r|jSdS(Ni(RR(R((s,/usr/lib64/python2.7/Demo/classes/Complex.pytIm[s RcBseZdddZdZdZdZdZdZdZdZ d Z d Z d Z d Z d ZdZe ZZedZeZdZeZdZdZdZeZdZdZddZdZRS(icCsd}d}t|r-|j}|j}n|}t|r\||j}||j}n ||}||jd<||jdcCsdG|GdG|Gyt|}Wntj}nXdG|GHt|tsZt|tri||k}nt|||k}|sdG|GdGt||GHndS(Ns tands->s!! !! !! should betdiff(tevaltsystexc_typeRtstrR@(texprtatbRtfuzztresulttok((s,/usr/lib64/python2.7/Demo/classes/Complex.pytcheckops  cCsdGHdtfd tfd!tdfd"tddfd#ttddfd$ttdddfd%tdtddfd&tdtdfd'tdtddfd(ttddtdd ff }ddg}x|D]x}|dcd7<|dd|djksH|dd|djkrd G|dGd G|dGH|dcd7As           J PK%L]cAC<5(5(classes/bitvec.pyonu[ ^c@s{ddlZejjZdefdYZdZddlZdZdZ dZ dfd YZ e Z dS( iNterrorcBseZRS((t__name__t __module__(((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyR scCsEt|tdks5d|ko/dkn rAtdndS(Niis)bitvec() items must have int value 0 or 1(ttypeR(tvalue((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt _check_value s5cCstjt|\}}d|>}||krMtd||ffnx,|r{|d?}||@rnPn|d}qPW|S(Nls(param, l) = %ri(tmathtfrexptfloatt RuntimeError(tparamtmanttltbitmask((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt _compute_lens     cCsit|tdkr$tdn|dkr=||}nd|koT|knsetdn|S(Nissequence subscript not intslist index out of range(Rt TypeErrort IndexError(tlentkey((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt _check_key!s    cCs>t|dt||}}||kr4|}n||fS(Ni(tmaxtmin(Rtitj((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt _check_slice*s  tBitVeccBs eZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZRS(cGsd|_d|_t|s!nt|dkr|\}t|tgkrd}d}x+|D]#}|r||B}n|d>}qgW||_t||_qt|tdkr|dkrtdn||_t||_qtdnt|dkr|\}}t|tdkr|dkrNtdn||_t|tdkr{td nt|}||krd GH|jd|>d@|_n||_qtdn td dS( Nliils$bitvec() can't handle negative longss)bitvec() requires array or long parameteriscan't handle negative longss$bitvec()'s 2nd parameter must be intsMwarning: bitvec() value is longer than the length indicates, truncating values%bitvec() requires 0 -- 2 parameter(s)(t_datat_lenRRRR(tselftparamsR Rtbit_masktitemtlengthtcomputed_length((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__init__4sL                    cCs(tt| d||j|j+dS(Ni(RtlongR(RR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytappendbscCsR|r|j}n |j}d}x)|rM|d?||d@dk}}q%W|S(Nii(R(RRtdatatcount((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyR&is   #cCs^|r|j}n |j}d}|s4tdnx#|d@sY|d?|d}}q7W|S(Nislist.index(x): x not in listi(Rt ValueError(RRR%tindex((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyR(us    cCs"tt| d|||+dS(Ni(RR#(RR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytinsertscCs||j|=dS(N(R((RR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytremovescCso|jd}}xOt|jD]>}|sA||j|>}Pn|d>|d@B|d?}}q W||_dS(Nli(RtrangeR(RR%tresultR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytreverses!cCs/|jd}d|>d|j|>|_dS(Nil(R&RR(Rtc((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytsortscCst|j|jS(N(RRR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytcopyscCs(g}x|D]}|j|q W|S(N(R$(RR,R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytseqs cCsd|j|jfS(Nsbitvec(%r, %r)(RR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__repr__scGs#t|t|kr1tt|f|}n|j}|dksU|jdkret||jS||jkrt||j}t|| || pt||||S|j|jkrdS|dkrt|d|dS|d?}t|| || pt||||SdS(Nii(RtapplytbitvecRtcmpRR(RtothertrestR t min_length((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__cmp__s    cCs|jS(N(R(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__len__scCs't|j|}|jd|>@dkS(Nli(RRR(RR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __getitem__scCsHt|j|}|r/|jd|>B|_n|jd|>@|_dS(Nl(RRR(RRR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __setitem__scCsIt|j|}|| j||dj|?B|_|jd|_dS(Ni(RRR(RR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __delitem__s#cCst|j||\}}||kr4tddS|rJ|j|?}n |j}||}||jkr|d|>d@}nt||S(Nlili(RRRR(RRRtndatatnlength((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __getslice__s    cGst|j||\}}t|t|krLtt|f|}n|| }||}|j|j|j|j>B|j>B|_|j|||j|_dS(N(RRRR3R4R(RRRtsequenceR7tls_parttms_part((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __setslice__s  cCst|j||\}}|dkrK||jkrKd\|_|_nB||kr|| j||j|?B|_|j|||_ndS(Nil(li(RRR(RRR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __delslice__s  cCs#|j}|||j|j+|S(N(R0R(RR6tretval((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__add__s cCst|tdkr$tdn|dkr=tddS|dkrS|jS|jdkrvtd|j|S|jdkrtd|j|Stdd}x|r|||d}}qW|S(Nissequence subscript not intli(RRRR0RR(Rt multiplierRF((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__mul__ s      cGsWt|t|kr1tt|f|}nt|j|j@t|j|jS(N(RR3R4RRRR(RtotherseqR7((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__and__scGsWt|t|kr1tt|f|}nt|j|jAt|j|jS(N(RR3R4RRRR(RRJR7((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__xor__%scGsWt|t|kr1tt|f|}nt|j|jBt|j|jS(N(RR3R4RRRR(RRJR7((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__or__.scCs#t|jd|j>d@|jS(Nli(RRR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __invert__7scGs;t|t|kr1tt|f|}n||fS(N(RR3R4(RRJR7((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __coerce__<scCs t|jS(N(tintR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__int__CscCs t|jS(N(R#R(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__long__FscCs t|jS(N(RR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __float__Is(RRR"R$R&R(R)R*R-R/R0R1R2R9R:R;R<R=R@RDRERGRIRKRLRMRNRORQRRRS(((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyR2s: .                   ( tsyststderrtwritetrprtt ExceptionRRRRRRRR4(((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyts    PK%L]((classes/bitvec.pynu[# # this is a rather strict implementation of a bit vector class # it is accessed the same way as an array of python-ints, except # the value must be 0 or 1 # import sys; rprt = sys.stderr.write #for debugging class error(Exception): pass def _check_value(value): if type(value) != type(0) or not 0 <= value < 2: raise error, 'bitvec() items must have int value 0 or 1' import math def _compute_len(param): mant, l = math.frexp(float(param)) bitmask = 1L << l if bitmask <= param: raise RuntimeError('(param, l) = %r' % ((param, l),)) while l: bitmask = bitmask >> 1 if param & bitmask: break l = l - 1 return l def _check_key(len, key): if type(key) != type(0): raise TypeError, 'sequence subscript not int' if key < 0: key = key + len if not 0 <= key < len: raise IndexError, 'list index out of range' return key def _check_slice(len, i, j): #the type is ok, Python already checked that i, j = max(i, 0), min(len, j) if i > j: i = j return i, j class BitVec: def __init__(self, *params): self._data = 0L self._len = 0 if not len(params): pass elif len(params) == 1: param, = params if type(param) == type([]): value = 0L bit_mask = 1L for item in param: # strict check #_check_value(item) if item: value = value | bit_mask bit_mask = bit_mask << 1 self._data = value self._len = len(param) elif type(param) == type(0L): if param < 0: raise error, 'bitvec() can\'t handle negative longs' self._data = param self._len = _compute_len(param) else: raise error, 'bitvec() requires array or long parameter' elif len(params) == 2: param, length = params if type(param) == type(0L): if param < 0: raise error, \ 'can\'t handle negative longs' self._data = param if type(length) != type(0): raise error, 'bitvec()\'s 2nd parameter must be int' computed_length = _compute_len(param) if computed_length > length: print 'warning: bitvec() value is longer than the length indicates, truncating value' self._data = self._data & \ ((1L << length) - 1) self._len = length else: raise error, 'bitvec() requires array or long parameter' else: raise error, 'bitvec() requires 0 -- 2 parameter(s)' def append(self, item): #_check_value(item) #self[self._len:self._len] = [item] self[self._len:self._len] = \ BitVec(long(not not item), 1) def count(self, value): #_check_value(value) if value: data = self._data else: data = (~self)._data count = 0 while data: data, count = data >> 1, count + (data & 1 != 0) return count def index(self, value): #_check_value(value): if value: data = self._data else: data = (~self)._data index = 0 if not data: raise ValueError, 'list.index(x): x not in list' while not (data & 1): data, index = data >> 1, index + 1 return index def insert(self, index, item): #_check_value(item) #self[index:index] = [item] self[index:index] = BitVec(long(not not item), 1) def remove(self, value): del self[self.index(value)] def reverse(self): #ouch, this one is expensive! #for i in self._len>>1: self[i], self[l-i] = self[l-i], self[i] data, result = self._data, 0L for i in range(self._len): if not data: result = result << (self._len - i) break result, data = (result << 1) | (data & 1), data >> 1 self._data = result def sort(self): c = self.count(1) self._data = ((1L << c) - 1) << (self._len - c) def copy(self): return BitVec(self._data, self._len) def seq(self): result = [] for i in self: result.append(i) return result def __repr__(self): ##rprt('.' + '__repr__()\n') return 'bitvec(%r, %r)' % (self._data, self._len) def __cmp__(self, other, *rest): #rprt('%r.__cmp__%r\n' % (self, (other,) + rest)) if type(other) != type(self): other = apply(bitvec, (other, ) + rest) #expensive solution... recursive binary, with slicing length = self._len if length == 0 or other._len == 0: return cmp(length, other._len) if length != other._len: min_length = min(length, other._len) return cmp(self[:min_length], other[:min_length]) or \ cmp(self[min_length:], other[min_length:]) #the lengths are the same now... if self._data == other._data: return 0 if length == 1: return cmp(self[0], other[0]) else: length = length >> 1 return cmp(self[:length], other[:length]) or \ cmp(self[length:], other[length:]) def __len__(self): #rprt('%r.__len__()\n' % (self,)) return self._len def __getitem__(self, key): #rprt('%r.__getitem__(%r)\n' % (self, key)) key = _check_key(self._len, key) return self._data & (1L << key) != 0 def __setitem__(self, key, value): #rprt('%r.__setitem__(%r, %r)\n' % (self, key, value)) key = _check_key(self._len, key) #_check_value(value) if value: self._data = self._data | (1L << key) else: self._data = self._data & ~(1L << key) def __delitem__(self, key): #rprt('%r.__delitem__(%r)\n' % (self, key)) key = _check_key(self._len, key) #el cheapo solution... self._data = self[:key]._data | self[key+1:]._data >> key self._len = self._len - 1 def __getslice__(self, i, j): #rprt('%r.__getslice__(%r, %r)\n' % (self, i, j)) i, j = _check_slice(self._len, i, j) if i >= j: return BitVec(0L, 0) if i: ndata = self._data >> i else: ndata = self._data nlength = j - i if j != self._len: #we'll have to invent faster variants here #e.g. mod_2exp ndata = ndata & ((1L << nlength) - 1) return BitVec(ndata, nlength) def __setslice__(self, i, j, sequence, *rest): #rprt('%s.__setslice__%r\n' % (self, (i, j, sequence) + rest)) i, j = _check_slice(self._len, i, j) if type(sequence) != type(self): sequence = apply(bitvec, (sequence, ) + rest) #sequence is now of our own type ls_part = self[:i] ms_part = self[j:] self._data = ls_part._data | \ ((sequence._data | \ (ms_part._data << sequence._len)) << ls_part._len) self._len = self._len - j + i + sequence._len def __delslice__(self, i, j): #rprt('%r.__delslice__(%r, %r)\n' % (self, i, j)) i, j = _check_slice(self._len, i, j) if i == 0 and j == self._len: self._data, self._len = 0L, 0 elif i < j: self._data = self[:i]._data | (self[j:]._data >> i) self._len = self._len - j + i def __add__(self, other): #rprt('%r.__add__(%r)\n' % (self, other)) retval = self.copy() retval[self._len:self._len] = other return retval def __mul__(self, multiplier): #rprt('%r.__mul__(%r)\n' % (self, multiplier)) if type(multiplier) != type(0): raise TypeError, 'sequence subscript not int' if multiplier <= 0: return BitVec(0L, 0) elif multiplier == 1: return self.copy() #handle special cases all 0 or all 1... if self._data == 0L: return BitVec(0L, self._len * multiplier) elif (~self)._data == 0L: return ~BitVec(0L, self._len * multiplier) #otherwise el cheapo again... retval = BitVec(0L, 0) while multiplier: retval, multiplier = retval + self, multiplier - 1 return retval def __and__(self, otherseq, *rest): #rprt('%r.__and__%r\n' % (self, (otherseq,) + rest)) if type(otherseq) != type(self): otherseq = apply(bitvec, (otherseq, ) + rest) #sequence is now of our own type return BitVec(self._data & otherseq._data, \ min(self._len, otherseq._len)) def __xor__(self, otherseq, *rest): #rprt('%r.__xor__%r\n' % (self, (otherseq,) + rest)) if type(otherseq) != type(self): otherseq = apply(bitvec, (otherseq, ) + rest) #sequence is now of our own type return BitVec(self._data ^ otherseq._data, \ max(self._len, otherseq._len)) def __or__(self, otherseq, *rest): #rprt('%r.__or__%r\n' % (self, (otherseq,) + rest)) if type(otherseq) != type(self): otherseq = apply(bitvec, (otherseq, ) + rest) #sequence is now of our own type return BitVec(self._data | otherseq._data, \ max(self._len, otherseq._len)) def __invert__(self): #rprt('%r.__invert__()\n' % (self,)) return BitVec(~self._data & ((1L << self._len) - 1), \ self._len) def __coerce__(self, otherseq, *rest): #needed for *some* of the arithmetic operations #rprt('%r.__coerce__%r\n' % (self, (otherseq,) + rest)) if type(otherseq) != type(self): otherseq = apply(bitvec, (otherseq, ) + rest) return self, otherseq def __int__(self): return int(self._data) def __long__(self): return long(self._data) def __float__(self): return float(self._data) bitvec = BitVec PK%L]cAC<5(5(classes/bitvec.pycnu[ ^c@s{ddlZejjZdefdYZdZddlZdZdZ dZ dfd YZ e Z dS( iNterrorcBseZRS((t__name__t __module__(((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyR scCsEt|tdks5d|ko/dkn rAtdndS(Niis)bitvec() items must have int value 0 or 1(ttypeR(tvalue((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt _check_value s5cCstjt|\}}d|>}||krMtd||ffnx,|r{|d?}||@rnPn|d}qPW|S(Nls(param, l) = %ri(tmathtfrexptfloatt RuntimeError(tparamtmanttltbitmask((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt _compute_lens     cCsit|tdkr$tdn|dkr=||}nd|koT|knsetdn|S(Nissequence subscript not intslist index out of range(Rt TypeErrort IndexError(tlentkey((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt _check_key!s    cCs>t|dt||}}||kr4|}n||fS(Ni(tmaxtmin(Rtitj((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt _check_slice*s  tBitVeccBs eZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZRS(cGsd|_d|_t|s!nt|dkr|\}t|tgkrd}d}x+|D]#}|r||B}n|d>}qgW||_t||_qt|tdkr|dkrtdn||_t||_qtdnt|dkr|\}}t|tdkr|dkrNtdn||_t|tdkr{td nt|}||krd GH|jd|>d@|_n||_qtdn td dS( Nliils$bitvec() can't handle negative longss)bitvec() requires array or long parameteriscan't handle negative longss$bitvec()'s 2nd parameter must be intsMwarning: bitvec() value is longer than the length indicates, truncating values%bitvec() requires 0 -- 2 parameter(s)(t_datat_lenRRRR(tselftparamsR Rtbit_masktitemtlengthtcomputed_length((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__init__4sL                    cCs(tt| d||j|j+dS(Ni(RtlongR(RR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytappendbscCsR|r|j}n |j}d}x)|rM|d?||d@dk}}q%W|S(Nii(R(RRtdatatcount((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyR&is   #cCs^|r|j}n |j}d}|s4tdnx#|d@sY|d?|d}}q7W|S(Nislist.index(x): x not in listi(Rt ValueError(RRR%tindex((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyR(us    cCs"tt| d|||+dS(Ni(RR#(RR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytinsertscCs||j|=dS(N(R((RR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytremovescCso|jd}}xOt|jD]>}|sA||j|>}Pn|d>|d@B|d?}}q W||_dS(Nli(RtrangeR(RR%tresultR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytreverses!cCs/|jd}d|>d|j|>|_dS(Nil(R&RR(Rtc((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytsortscCst|j|jS(N(RRR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytcopyscCs(g}x|D]}|j|q W|S(N(R$(RR,R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytseqs cCsd|j|jfS(Nsbitvec(%r, %r)(RR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__repr__scGs#t|t|kr1tt|f|}n|j}|dksU|jdkret||jS||jkrt||j}t|| || pt||||S|j|jkrdS|dkrt|d|dS|d?}t|| || pt||||SdS(Nii(RtapplytbitvecRtcmpRR(RtothertrestR t min_length((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__cmp__s    cCs|jS(N(R(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__len__scCs't|j|}|jd|>@dkS(Nli(RRR(RR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __getitem__scCsHt|j|}|r/|jd|>B|_n|jd|>@|_dS(Nl(RRR(RRR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __setitem__scCsIt|j|}|| j||dj|?B|_|jd|_dS(Ni(RRR(RR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __delitem__s#cCst|j||\}}||kr4tddS|rJ|j|?}n |j}||}||jkr|d|>d@}nt||S(Nlili(RRRR(RRRtndatatnlength((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __getslice__s    cGst|j||\}}t|t|krLtt|f|}n|| }||}|j|j|j|j>B|j>B|_|j|||j|_dS(N(RRRR3R4R(RRRtsequenceR7tls_parttms_part((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __setslice__s  cCst|j||\}}|dkrK||jkrKd\|_|_nB||kr|| j||j|?B|_|j|||_ndS(Nil(li(RRR(RRR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __delslice__s  cCs#|j}|||j|j+|S(N(R0R(RR6tretval((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__add__s cCst|tdkr$tdn|dkr=tddS|dkrS|jS|jdkrvtd|j|S|jdkrtd|j|Stdd}x|r|||d}}qW|S(Nissequence subscript not intli(RRRR0RR(Rt multiplierRF((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__mul__ s      cGsWt|t|kr1tt|f|}nt|j|j@t|j|jS(N(RR3R4RRRR(RtotherseqR7((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__and__scGsWt|t|kr1tt|f|}nt|j|jAt|j|jS(N(RR3R4RRRR(RRJR7((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__xor__%scGsWt|t|kr1tt|f|}nt|j|jBt|j|jS(N(RR3R4RRRR(RRJR7((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__or__.scCs#t|jd|j>d@|jS(Nli(RRR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __invert__7scGs;t|t|kr1tt|f|}n||fS(N(RR3R4(RRJR7((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __coerce__<scCs t|jS(N(tintR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__int__CscCs t|jS(N(R#R(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__long__FscCs t|jS(N(RR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __float__Is(RRR"R$R&R(R)R*R-R/R0R1R2R9R:R;R<R=R@RDRERGRIRKRLRMRNRORQRRRS(((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyR2s: .                   ( tsyststderrtwritetrprtt ExceptionRRRRRRRR4(((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyts    PK%L]wclasses/Dates.pycnu[ ^c @spdddddddddd d d g Zd d dddddgZddddddddddddg ZgZdZx%eD]ZejeeeZqW[[ededfZdZ dZ dZ dZ dZ dZe dZd Zd!Zd"d,d#YZd$Zd%efd&YZd'Zed(krled)d*nd+S(-tJanuarytFebruarytMarchtApriltMaytJunetJulytAugustt SeptembertOctobertNovembertDecembertFridaytSaturdaytSundaytMondaytTuesdayt WednesdaytThursdayiiiiilcCs6|ddkrdS|ddkr(dS|ddkS(Niiiiid((tyear((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt_is_leap>s cCsdt|S(Nim(R(R((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt _days_in_yearCscCs,|d|dd|dd|ddS(Nlmiiicidii((R((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt_days_before_yearFscCs(|dkrt|rdSt|dS(Niii(Rt_DAYS_IN_MONTH(tmonthR((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt_days_in_monthIscCs"t|d|dko t|S(Nii(t_DAYS_BEFORE_MONTHR(RR((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt_days_before_monthMscCs't|jt|j|j|jS(N(RRRRtday(tdate((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt _date2numPsicCs}t|tkr(tdt|ntddd}|`|`|`|`||_|dt}d||t|}}|d}t |}||kr|d}|t |}n||t ||}}yt |}Wnt t fk rnXt|ddd}t||}||krX|d}|t||}n|||||_|_|_|S(Nsargument must be integer: %riiimii (ttypet _INT_TYPESt TypeErrortDatetordRRRt_DI400YRRtintt ValueErrort OverflowErrortminRR(tntanstn400RtmoretdbyRtdbm((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt _num2dateWs0       !cCstt|dS(Ni(t _DAY_NAMESR%(R)((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt_num2daytsR"cBs_eZdZdZdZdZdZdZeZdZ dZ dZ RS( cCsd|kodkns/td|fnt||}d|koU|knsptd||fn||||_|_|_t||_dS(Nii smonth must be in 1..12: %rsday must be in 1..%r: %r(R&RRRRRR#(tselfRRRtdim((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt__init__yscCs3|jj|r"td|n||j|num failedsnum->date failed(R"treprRMR!R@tmaxR(RRR#R/RRR( t firstyeartlastyeartatbtxtdtlordtytfordtfdtld((s*/usr/lib64/python2.7/Demo/classes/Dates.pyttestsP 1            * 8   %-t__main__i:ifN((RAR0RRR.R3tappendRR RRRRRRR$R/R1R"RLt ExceptionRMR[RF(((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt,s6  *           4  . PK%L]wclasses/Dates.pyonu[ ^c @spdddddddddd d d g Zd d dddddgZddddddddddddg ZgZdZx%eD]ZejeeeZqW[[ededfZdZ dZ dZ dZ dZ dZe dZd Zd!Zd"d,d#YZd$Zd%efd&YZd'Zed(krled)d*nd+S(-tJanuarytFebruarytMarchtApriltMaytJunetJulytAugustt SeptembertOctobertNovembertDecembertFridaytSaturdaytSundaytMondaytTuesdayt WednesdaytThursdayiiiiilcCs6|ddkrdS|ddkr(dS|ddkS(Niiiiid((tyear((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt_is_leap>s cCsdt|S(Nim(R(R((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt _days_in_yearCscCs,|d|dd|dd|ddS(Nlmiiicidii((R((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt_days_before_yearFscCs(|dkrt|rdSt|dS(Niii(Rt_DAYS_IN_MONTH(tmonthR((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt_days_in_monthIscCs"t|d|dko t|S(Nii(t_DAYS_BEFORE_MONTHR(RR((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt_days_before_monthMscCs't|jt|j|j|jS(N(RRRRtday(tdate((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt _date2numPsicCs}t|tkr(tdt|ntddd}|`|`|`|`||_|dt}d||t|}}|d}t |}||kr|d}|t |}n||t ||}}yt |}Wnt t fk rnXt|ddd}t||}||krX|d}|t||}n|||||_|_|_|S(Nsargument must be integer: %riiimii (ttypet _INT_TYPESt TypeErrortDatetordRRRt_DI400YRRtintt ValueErrort OverflowErrortminRR(tntanstn400RtmoretdbyRtdbm((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt _num2dateWs0       !cCstt|dS(Ni(t _DAY_NAMESR%(R)((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt_num2daytsR"cBs_eZdZdZdZdZdZdZeZdZ dZ dZ RS( cCsd|kodkns/td|fnt||}d|koU|knsptd||fn||||_|_|_t||_dS(Nii smonth must be in 1..12: %rsday must be in 1..%r: %r(R&RRRRRR#(tselfRRRtdim((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt__init__yscCs3|jj|r"td|n||j|num failedsnum->date failed(R"treprRMR!R@tmaxR(RRR#R/RRR( t firstyeartlastyeartatbtxtdtlordtytfordtfdtld((s*/usr/lib64/python2.7/Demo/classes/Dates.pyttestsP 1            * 8   %-t__main__i:ifN((RAR0RRR.R3tappendRR RRRRRRR$R/R1R"RLt ExceptionRMR[RF(((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt,s6  *           4  . PK%L]:6  classes/Vec.pycnu[ ^c@s'dddYZdZedS(tVeccBsbeZdZdZedZdZdZdZdZ dZ dZ e Z RS( sx A simple vector class Instances of the Vec class can be constructed from numbers >>> a = Vec(1, 2, 3) >>> b = Vec(3, 2, 1) added >>> a + b Vec(4, 4, 4) subtracted >>> a - b Vec(-2, 0, 2) and multiplied by a scalar on the left >>> 3.0 * a Vec(3.0, 6.0, 9.0) or on the right >>> a * 3.0 Vec(3.0, 6.0, 9.0) cGst||_dS(N(tlisttv(tselfR((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__init__scCs.t|tstn|}||_|S(N(t isinstanceRt TypeErrorR(tclsRtinst((s(/usr/lib64/python2.7/Demo/classes/Vec.pytfromlists    cCs)djd|jD}dj|S(Ns, css|]}t|VqdS(N(trepr(t.0tx((s(/usr/lib64/python2.7/Demo/classes/Vec.pys %ssVec({0})(tjoinRtformat(Rtargs((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__repr__$scCs t|jS(N(tlenR(R((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__len__(scCs |j|S(N(R(Rti((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt __getitem__+scCs?gt|j|jD]\}}||^q}tj|S(N(tzipRRR (RtotherR tyR((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__add__.s2cCs?gt|j|jD]\}}||^q}tj|S(N(RRRR (RRR RR((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__sub__3s2cCs-g|jD]}||^q }tj|S(N(RRR (RtscalarR R((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__mul__8s ( t__name__t __module__t__doc__Rt classmethodR RRRRRRt__rmul__(((s(/usr/lib64/python2.7/Demo/classes/Vec.pyRs       cCsddl}|jdS(Ni(tdoctestttestmod(R!((s(/usr/lib64/python2.7/Demo/classes/Vec.pyttest@s N((RR#(((s(/usr/lib64/python2.7/Demo/classes/Vec.pyts? PK%L]Iclasses/Rev.pynu[''' A class which presents the reverse of a sequence without duplicating it. From: "Steven D. Majewski" It works on mutable or inmutable sequences. >>> chars = list(Rev('Hello World!')) >>> print ''.join(chars) !dlroW olleH The .forw is so you can use anonymous sequences in __init__, and still keep a reference the forward sequence. ) If you give it a non-anonymous mutable sequence, the reverse sequence will track the updated values. ( but not reassignment! - another good reason to use anonymous values in creating the sequence to avoid confusion. Maybe it should be change to copy input sequence to break the connection completely ? ) >>> nnn = range(3) >>> rnn = Rev(nnn) >>> for n in rnn: print n ... 2 1 0 >>> for n in range(4, 6): nnn.append(n) # update nnn ... >>> for n in rnn: print n # prints reversed updated values ... 5 4 2 1 0 >>> nnn = nnn[1:-1] >>> nnn [1, 2, 4] >>> for n in rnn: print n # prints reversed values of old nnn ... 5 4 2 1 0 # >>> WH = Rev('Hello World!') >>> print WH.forw, WH.back Hello World! !dlroW olleH >>> nnn = Rev(range(1, 10)) >>> print nnn.forw [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> print nnn.back [9, 8, 7, 6, 5, 4, 3, 2, 1] >>> rrr = Rev(nnn) >>> rrr <1, 2, 3, 4, 5, 6, 7, 8, 9> ''' class Rev: def __init__(self, seq): self.forw = seq self.back = self def __len__(self): return len(self.forw) def __getitem__(self, j): return self.forw[-(j + 1)] def __repr__(self): seq = self.forw if isinstance(seq, list): wrap = '[]' sep = ', ' elif isinstance(seq, tuple): wrap = '()' sep = ', ' elif isinstance(seq, str): wrap = '' sep = '' else: wrap = '<>' sep = ', ' outstrs = [str(item) for item in self.back] return wrap[:1] + sep.join(outstrs) + wrap[-1:] def _test(): import doctest, Rev return doctest.testmod(Rev) if __name__ == "__main__": _test() PK%L] classes/Dbm.pyonu[ ^c@s'dddYZdZedS(tDbmcBsPeZdZdZdZdZdZdZdZdZ RS(cCs(ddl}|j||||_dS(Ni(tdbmtopentdb(tselftfilenametmodetpermR((s(/usr/lib64/python2.7/Demo/classes/Dbm.pyt__init__ s cCsdd}xO|jD]A}t|dt||}|rJd|}n||}qWd|dS(Nts: s, t{t}(tkeystrepr(Rtstkeytt((s(/usr/lib64/python2.7/Demo/classes/Dbm.pyt__repr__ s cCs t|jS(N(tlenR(R((s(/usr/lib64/python2.7/Demo/classes/Dbm.pyt__len__scCst|jt|S(N(tevalRR (RR((s(/usr/lib64/python2.7/Demo/classes/Dbm.pyt __getitem__scCst||jt|s$ PK%L]1 1 classes/Rev.pyonu[ ^c@s<dZdddYZdZedkr8endS(s A class which presents the reverse of a sequence without duplicating it. From: "Steven D. Majewski" It works on mutable or inmutable sequences. >>> chars = list(Rev('Hello World!')) >>> print ''.join(chars) !dlroW olleH The .forw is so you can use anonymous sequences in __init__, and still keep a reference the forward sequence. ) If you give it a non-anonymous mutable sequence, the reverse sequence will track the updated values. ( but not reassignment! - another good reason to use anonymous values in creating the sequence to avoid confusion. Maybe it should be change to copy input sequence to break the connection completely ? ) >>> nnn = range(3) >>> rnn = Rev(nnn) >>> for n in rnn: print n ... 2 1 0 >>> for n in range(4, 6): nnn.append(n) # update nnn ... >>> for n in rnn: print n # prints reversed updated values ... 5 4 2 1 0 >>> nnn = nnn[1:-1] >>> nnn [1, 2, 4] >>> for n in rnn: print n # prints reversed values of old nnn ... 5 4 2 1 0 # >>> WH = Rev('Hello World!') >>> print WH.forw, WH.back Hello World! !dlroW olleH >>> nnn = Rev(range(1, 10)) >>> print nnn.forw [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> print nnn.back [9, 8, 7, 6, 5, 4, 3, 2, 1] >>> rrr = Rev(nnn) >>> rrr <1, 2, 3, 4, 5, 6, 7, 8, 9> tRevcBs,eZdZdZdZdZRS(cCs||_||_dS(N(tforwtback(tselftseq((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt__init__?s cCs t|jS(N(tlenR(R((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt__len__CscCs|j|d S(Ni(R(Rtj((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt __getitem__FscCs|j}t|tr'd}d}nHt|trEd}d}n*t|trcd}d}n d}d}g|jD]}t|^qy}|d |j||dS(Ns[]s, s()ts<>ii(Rt isinstancetlistttupletstrRtjoin(RRtwraptseptitemtoutstrs((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt__repr__Is    "(t__name__t __module__RRR R(((s(/usr/lib64/python2.7/Demo/classes/Rev.pyR>s   cCs%ddl}ddl}|j|S(Ni(tdoctestRttestmod(RR((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt_testZst__main__N((t__doc__RRR(((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt<s  PK%L]Y md5test/md5driver.pyonu[ ^c@sddlZddlZddlmZdZddlmZdZdZdZdZ ddlZd Z d Z d Z e dS( iN(targvcCsSd}xB|D]:}t|}|tj|d?d@tj|d@}q W|GdS(Ntii(tordtstringt hexdigits(tstrtoutstrtito((s./usr/lib64/python2.7/Demo/md5test/md5driver.pytMDPrints   ,(ttimecCs8d}x+t||dD]}|t|}qW|S(NRi(trangetchr(tstarttendtresultR((s./usr/lib64/python2.7/Demo/md5test/md5driver.pytmakestrsc Csd}d}||}d }td|d}|||}|||| }~~dG|GdGHt}tj}x!t|D]}|j|qW|j} t} t| dGHd G| |GHd G|| |GHdS( Nii'iiisMD5 time trial. Processings characters...sis digest of test input.sSeconds to process test input:s Characters processed per second:i(RR tmd5tnewR tupdatetdigestR ( tTEST_BLOCK_SIZEt TEST_BLOCKSt TEST_BYTEStfilsiztfillertdatatt1t mdContextRRtt2((s./usr/lib64/python2.7/Demo/md5test/md5driver.pyt MDTimeTrials&        cCs*ttj|jd|dGHdS(Nt"(R RRR(R((s./usr/lib64/python2.7/Demo/md5test/md5driver.pytMDString;scCsat|d}tj}x*|jd}|s7Pn|j|qWt|j|GHdS(Ntrbi(topenRRtreadRR R(tfilenametfRR((s./usr/lib64/python2.7/Demo/md5test/md5driver.pytMDFile@s cCsQtj}x-tjjd}|s+Pn|j|qWt|jHdS(Ni(RRtsyststdinR#RR R(RR((s./usr/lib64/python2.7/Demo/md5test/md5driver.pytMDFilterPs cCsdGHtdtdtdtdtttdtdtttdtdttdtdttd td tttd td d d td dS(NsMD5 test suite results:Rtatabcsmessage digesttztAtZt0t9t1itfoo(R RRR&(((s./usr/lib64/python2.7/Demo/md5test/md5driver.pyt MDTestSuite]s    N'cCsttdkrtnxitdD]]}|d dkrNt|dq'|dkrdtq'|dkrztq't|q'WdS(Niis-ss-ts-x(tlenRR)R RR3R&(targ((s./usr/lib64/python2.7/Demo/md5test/md5driver.pytmainns     ( RRR'RR R RRR R&R)R3R6(((s./usr/lib64/python2.7/Demo/md5test/md5driver.pyts     "     PK%L]md5test/READMEnu[This is the Python version of the MD5 test program from the MD5 Internet Draft (Rivest and Dusse, The MD5 Message-Digest Algorithm, 10 July 1991). The file "foo" contains the string "abc" with no trailing newline. When called without arguments, it acts as a filter. When called with "-x", it executes a self-test, and the output should literally match the output given in the RFC. Code by Jan-Hein B\"uhrman after the original in C. PK%L]A$5 md5test/foonu[abcPK%L]Y md5test/md5driver.pycnu[ ^c@sddlZddlZddlmZdZddlmZdZdZdZdZ ddlZd Z d Z d Z e dS( iN(targvcCsSd}xB|D]:}t|}|tj|d?d@tj|d@}q W|GdS(Ntii(tordtstringt hexdigits(tstrtoutstrtito((s./usr/lib64/python2.7/Demo/md5test/md5driver.pytMDPrints   ,(ttimecCs8d}x+t||dD]}|t|}qW|S(NRi(trangetchr(tstarttendtresultR((s./usr/lib64/python2.7/Demo/md5test/md5driver.pytmakestrsc Csd}d}||}d }td|d}|||}|||| }~~dG|GdGHt}tj}x!t|D]}|j|qW|j} t} t| dGHd G| |GHd G|| |GHdS( Nii'iiisMD5 time trial. Processings characters...sis digest of test input.sSeconds to process test input:s Characters processed per second:i(RR tmd5tnewR tupdatetdigestR ( tTEST_BLOCK_SIZEt TEST_BLOCKSt TEST_BYTEStfilsiztfillertdatatt1t mdContextRRtt2((s./usr/lib64/python2.7/Demo/md5test/md5driver.pyt MDTimeTrials&        cCs*ttj|jd|dGHdS(Nt"(R RRR(R((s./usr/lib64/python2.7/Demo/md5test/md5driver.pytMDString;scCsat|d}tj}x*|jd}|s7Pn|j|qWt|j|GHdS(Ntrbi(topenRRtreadRR R(tfilenametfRR((s./usr/lib64/python2.7/Demo/md5test/md5driver.pytMDFile@s cCsQtj}x-tjjd}|s+Pn|j|qWt|jHdS(Ni(RRtsyststdinR#RR R(RR((s./usr/lib64/python2.7/Demo/md5test/md5driver.pytMDFilterPs cCsdGHtdtdtdtdtttdtdtttdtdttdtdttd td tttd td d d td dS(NsMD5 test suite results:Rtatabcsmessage digesttztAtZt0t9t1itfoo(R RRR&(((s./usr/lib64/python2.7/Demo/md5test/md5driver.pyt MDTestSuite]s    N'cCsttdkrtnxitdD]]}|d dkrNt|dq'|dkrdtq'|dkrztq't|q'WdS(Niis-ss-ts-x(tlenRR)R RR3R&(targ((s./usr/lib64/python2.7/Demo/md5test/md5driver.pytmainns     ( RRR'RR R RRR R&R)R3R6(((s./usr/lib64/python2.7/Demo/md5test/md5driver.pyts     "     PK%L]< md5test/md5driver.pynu[import string import md5 from sys import argv def MDPrint(str): outstr = '' for i in str: o = ord(i) outstr = (outstr + string.hexdigits[(o >> 4) & 0xF] + string.hexdigits[o & 0xF]) print outstr, from time import time def makestr(start, end): result = '' for i in range(start, end + 1): result = result + chr(i) return result def MDTimeTrial(): TEST_BLOCK_SIZE = 1000 TEST_BLOCKS = 10000 TEST_BYTES = TEST_BLOCK_SIZE * TEST_BLOCKS # initialize test data, need temporary string filler filsiz = 1 << 8 filler = makestr(0, filsiz-1) data = filler * (TEST_BLOCK_SIZE // filsiz) data = data + filler[:(TEST_BLOCK_SIZE % filsiz)] del filsiz, filler # start timer print 'MD5 time trial. Processing', TEST_BYTES, 'characters...' t1 = time() mdContext = md5.new() for i in range(TEST_BLOCKS): mdContext.update(data) str = mdContext.digest() t2 = time() MDPrint(str) print 'is digest of test input.' print 'Seconds to process test input:', t2 - t1 print 'Characters processed per second:', TEST_BYTES / (t2 - t1) def MDString(str): MDPrint(md5.new(str).digest()) print '"' + str + '"' def MDFile(filename): f = open(filename, 'rb') mdContext = md5.new() while 1: data = f.read(1024) if not data: break mdContext.update(data) MDPrint(mdContext.digest()) print filename import sys def MDFilter(): mdContext = md5.new() while 1: data = sys.stdin.read(16) if not data: break mdContext.update(data) MDPrint(mdContext.digest()) print def MDTestSuite(): print 'MD5 test suite results:' MDString('') MDString('a') MDString('abc') MDString('message digest') MDString(makestr(ord('a'), ord('z'))) MDString(makestr(ord('A'), ord('Z')) + makestr(ord('a'), ord('z')) + makestr(ord('0'), ord('9'))) MDString((makestr(ord('1'), ord('9')) + '0') * 8) # Contents of file foo are "abc" MDFile('foo') # I don't wanna use getopt(), since I want to use the same i/f... def main(): if len(argv) == 1: MDFilter() for arg in argv[1:]: if arg[:2] == '-s': MDString(arg[2:]) elif arg == '-t': MDTimeTrial() elif arg == '-x': MDTestSuite() else: MDFile(arg) main() PK%L]J==zlib/minigzip.pycnu[ Afc@sddlZddlZddlZd \ZZZZZdZdZ d Z d Z d Z e d kr|e ndS(iNiiiiicCs~|jt|d@|d}|jt|d@|d}|jt|d@|d}|jt|d@dS(Nii(twritetchr(toutputtvalue((s*/usr/lib64/python2.7/Demo/zlib/minigzip.pytwrite32 s   cCspt|jd}|t|jdd>7}|t|jdd>7}|t|jdd>7}|S(Niiii(tordtread(tinputtv((s*/usr/lib64/python2.7/Demo/zlib/minigzip.pytread32s cCs.|jd|jtttj|}|d}t|||jd|jd|j|dtjd}tjdtj tj tj d}xQt r|j d }|dkrPntj||}|j|j|qW|j|jt||t||d dS( Nsisssti iii(RRtFNAMEtoststatRtzlibtcrc32t compressobjtDEFLATEDt MAX_WBITSt DEF_MEM_LEVELtTrueRtcompresstflush(tfilenameRRtstatvaltmtimetcrcvaltcompobjtdata((s*/usr/lib64/python2.7/Demo/zlib/minigzip.pyRs(        c Cs{|jd}|dkr0dGHtjdnt|jddkr`dGHtjdnt|jd}|jd|t@rt|jd}|d t|jd7}|j|n|t@rx,tr|jd}|d krPqqWn|t@r@x,tr<|jd}|d krPqqWn|t@rZ|jdnt j t j }t j d }d}xgtr|jd } | d krPn|j | } |j| |t| 7}t j | |}qW|j} |j| |t| 7}t j | |}|jd dt|} t|} | |krcdGHn| |krwdGHndS(NissNot a gzipped fileiiisUnknown compression methodiisR iisCRC check failed.s!Incorrect length of data producedii(RtsystexitRtFEXTRAR RtFCOMMENTtFHCRCRt decompressobjRRt decompressRtlenRtseekR ( RRtmagictflagtxlentst decompobjRtlengthRt decompdataRtisize((s*/usr/lib64/python2.7/Demo/zlib/minigzip.pyR#1s^                   cCsttjdkr/dGHdGHtjdntjd}|jdr^t}|d }nt}|d}t|d}t|d }|rt|||n t |||j |j dS( NisUsage: minigzip.py s. The file will be compressed or decompressed.iis.gzitrbtwb( R$RtargvRtendswithtFalseRtopenRR#tclose(Rt compressingt outputnameRR((s*/usr/lib64/python2.7/Demo/zlib/minigzip.pytmainks"     t__main__(iiiii(RRR tFTEXTR!RR R RR RR#R7t__name__(((s*/usr/lib64/python2.7/Demo/zlib/minigzip.pyts$    :  PK%L]zlib/minigzip.pynuȯ#! /usr/bin/python2.7 # Demo program for zlib; it compresses or decompresses files, but *doesn't* # delete the original. This doesn't support all of gzip's options. # # The 'gzip' module in the standard library provides a more complete # implementation of gzip-format files. import zlib, sys, os FTEXT, FHCRC, FEXTRA, FNAME, FCOMMENT = 1, 2, 4, 8, 16 def write32(output, value): output.write(chr(value & 255)) ; value=value // 256 output.write(chr(value & 255)) ; value=value // 256 output.write(chr(value & 255)) ; value=value // 256 output.write(chr(value & 255)) def read32(input): v = ord(input.read(1)) v += (ord(input.read(1)) << 8 ) v += (ord(input.read(1)) << 16) v += (ord(input.read(1)) << 24) return v def compress (filename, input, output): output.write('\037\213\010') # Write the header, ... output.write(chr(FNAME)) # ... flag byte ... statval = os.stat(filename) # ... modification time ... mtime = statval[8] write32(output, mtime) output.write('\002') # ... slowest compression alg. ... output.write('\377') # ... OS (=unknown) ... output.write(filename+'\000') # ... original filename ... crcval = zlib.crc32("") compobj = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS, zlib.DEF_MEM_LEVEL, 0) while True: data = input.read(1024) if data == "": break crcval = zlib.crc32(data, crcval) output.write(compobj.compress(data)) output.write(compobj.flush()) write32(output, crcval) # ... the CRC ... write32(output, statval[6]) # and the file size. def decompress (input, output): magic = input.read(2) if magic != '\037\213': print 'Not a gzipped file' sys.exit(0) if ord(input.read(1)) != 8: print 'Unknown compression method' sys.exit(0) flag = ord(input.read(1)) input.read(4+1+1) # Discard modification time, # extra flags, and OS byte. if flag & FEXTRA: # Read & discard the extra field, if present xlen = ord(input.read(1)) xlen += 256*ord(input.read(1)) input.read(xlen) if flag & FNAME: # Read and discard a null-terminated string containing the filename while True: s = input.read(1) if s == '\0': break if flag & FCOMMENT: # Read and discard a null-terminated string containing a comment while True: s=input.read(1) if s=='\0': break if flag & FHCRC: input.read(2) # Read & discard the 16-bit header CRC decompobj = zlib.decompressobj(-zlib.MAX_WBITS) crcval = zlib.crc32("") length = 0 while True: data=input.read(1024) if data == "": break decompdata = decompobj.decompress(data) output.write(decompdata) length += len(decompdata) crcval = zlib.crc32(decompdata, crcval) decompdata = decompobj.flush() output.write(decompdata) length += len(decompdata) crcval = zlib.crc32(decompdata, crcval) # We've read to the end of the file, so we have to rewind in order # to reread the 8 bytes containing the CRC and the file size. The # decompressor is smart and knows when to stop, so feeding it # extra data is harmless. input.seek(-8, 2) crc32 = read32(input) isize = read32(input) if crc32 != crcval: print 'CRC check failed.' if isize != length: print 'Incorrect length of data produced' def main(): if len(sys.argv)!=2: print 'Usage: minigzip.py ' print ' The file will be compressed or decompressed.' sys.exit(0) filename = sys.argv[1] if filename.endswith('.gz'): compressing = False outputname = filename[:-3] else: compressing = True outputname = filename + '.gz' input = open(filename, 'rb') output = open(outputname, 'wb') if compressing: compress(filename, input, output) else: decompress(input, output) input.close() output.close() if __name__ == '__main__': main() PK%L]J==zlib/minigzip.pyonu[ Afc@sddlZddlZddlZd \ZZZZZdZdZ d Z d Z d Z e d kr|e ndS(iNiiiiicCs~|jt|d@|d}|jt|d@|d}|jt|d@|d}|jt|d@dS(Nii(twritetchr(toutputtvalue((s*/usr/lib64/python2.7/Demo/zlib/minigzip.pytwrite32 s   cCspt|jd}|t|jdd>7}|t|jdd>7}|t|jdd>7}|S(Niiii(tordtread(tinputtv((s*/usr/lib64/python2.7/Demo/zlib/minigzip.pytread32s cCs.|jd|jtttj|}|d}t|||jd|jd|j|dtjd}tjdtj tj tj d}xQt r|j d }|dkrPntj||}|j|j|qW|j|jt||t||d dS( Nsisssti iii(RRtFNAMEtoststatRtzlibtcrc32t compressobjtDEFLATEDt MAX_WBITSt DEF_MEM_LEVELtTrueRtcompresstflush(tfilenameRRtstatvaltmtimetcrcvaltcompobjtdata((s*/usr/lib64/python2.7/Demo/zlib/minigzip.pyRs(        c Cs{|jd}|dkr0dGHtjdnt|jddkr`dGHtjdnt|jd}|jd|t@rt|jd}|d t|jd7}|j|n|t@rx,tr|jd}|d krPqqWn|t@r@x,tr<|jd}|d krPqqWn|t@rZ|jdnt j t j }t j d }d}xgtr|jd } | d krPn|j | } |j| |t| 7}t j | |}qW|j} |j| |t| 7}t j | |}|jd dt|} t|} | |krcdGHn| |krwdGHndS(NissNot a gzipped fileiiisUnknown compression methodiisR iisCRC check failed.s!Incorrect length of data producedii(RtsystexitRtFEXTRAR RtFCOMMENTtFHCRCRt decompressobjRRt decompressRtlenRtseekR ( RRtmagictflagtxlentst decompobjRtlengthRt decompdataRtisize((s*/usr/lib64/python2.7/Demo/zlib/minigzip.pyR#1s^                   cCsttjdkr/dGHdGHtjdntjd}|jdr^t}|d }nt}|d}t|d}t|d }|rt|||n t |||j |j dS( NisUsage: minigzip.py s. The file will be compressed or decompressed.iis.gzitrbtwb( R$RtargvRtendswithtFalseRtopenRR#tclose(Rt compressingt outputnameRR((s*/usr/lib64/python2.7/Demo/zlib/minigzip.pytmainks"     t__main__(iiiii(RRR tFTEXTR!RR R RR RR#R7t__name__(((s*/usr/lib64/python2.7/Demo/zlib/minigzip.pyts$    :  PK%L]mzlib/zlibdemo.pynuȯ#! /usr/bin/python2.7 # Takes an optional filename, defaulting to this file itself. # Reads the file and compresses the content using level 1 and level 9 # compression, printing a summary of the results. import zlib, sys def main(): if len(sys.argv) > 1: filename = sys.argv[1] else: filename = sys.argv[0] print 'Reading', filename f = open(filename, 'rb') # Get the data to compress s = f.read() f.close() # First, we'll compress the string in one step comptext = zlib.compress(s, 1) decomp = zlib.decompress(comptext) print '1-step compression: (level 1)' print ' Original:', len(s), 'Compressed:', len(comptext), print 'Uncompressed:', len(decomp) # Now, let's compress the string in stages; set chunk to work in smaller steps chunk = 256 compressor = zlib.compressobj(9) decompressor = zlib.decompressobj() comptext = decomp = '' for i in range(0, len(s), chunk): comptext = comptext+compressor.compress(s[i:i+chunk]) # Don't forget to call flush()!! comptext = comptext + compressor.flush() for i in range(0, len(comptext), chunk): decomp = decomp + decompressor.decompress(comptext[i:i+chunk]) decomp=decomp+decompressor.flush() print 'Progressive compression (level 9):' print ' Original:', len(s), 'Compressed:', len(comptext), print 'Uncompressed:', len(decomp) if __name__ == '__main__': main() PK%L]tHzlib/zlibdemo.pycnu[ Afc@s;ddlZddlZdZedkr7endS(iNc Csttjdkr%tjd}n tjd}dG|GHt|d}|j}|jtj|d}tj|}dGHdGt|GdGt|GdGt|GHd }tj d }tj }d }}x>t dt||D]$}||j||||!}qW||j }x>t dt||D]$}||j||||!}qFW||j }d GHdGt|GdGt|GdGt|GHdS( NiitReadingtrbs1-step compression: (level 1)s Original:s Compressed:s Uncompressed:ii ts"Progressive compression (level 9):( tlentsystargvtopentreadtclosetzlibtcompresst decompresst compressobjt decompressobjtrangetflush( tfilenametftstcomptexttdecomptchunkt compressort decompressorti((s*/usr/lib64/python2.7/Demo/zlib/zlibdemo.pytmain s2      ""t__main__(R RRt__name__(((s*/usr/lib64/python2.7/Demo/zlib/zlibdemo.pyts & PK%L]tHzlib/zlibdemo.pyonu[ Afc@s;ddlZddlZdZedkr7endS(iNc Csttjdkr%tjd}n tjd}dG|GHt|d}|j}|jtj|d}tj|}dGHdGt|GdGt|GdGt|GHd }tj d }tj }d }}x>t dt||D]$}||j||||!}qW||j }x>t dt||D]$}||j||||!}qFW||j }d GHdGt|GdGt|GdGt|GHdS( NiitReadingtrbs1-step compression: (level 1)s Original:s Compressed:s Uncompressed:ii ts"Progressive compression (level 9):( tlentsystargvtopentreadtclosetzlibtcompresst decompresst compressobjt decompressobjtrangetflush( tfilenametftstcomptexttdecomptchunkt compressort decompressorti((s*/usr/lib64/python2.7/Demo/zlib/zlibdemo.pytmain s2      ""t__main__(R RRt__name__(((s*/usr/lib64/python2.7/Demo/zlib/zlibdemo.pyts & PK%L]threads/Coroutine.pycnu[ ^c@snddlZddlZdd dYZdefdYZdefdYZdd d YZdS( iNt_CoEventcBs>eZdZdZdZdZdZdZRS(cCs||_tj|_dS(N(tftsyncteventte(tselftfunc((s./usr/lib64/python2.7/Demo/threads/Coroutine.pyt__init__Is cCs%|jdkrdSd|jjSdS(Nsmain coroutinescoroutine for func (RtNonet func_name(R((s./usr/lib64/python2.7/Demo/threads/Coroutine.pyt__repr__MscCs t|S(N(tid(R((s./usr/lib64/python2.7/Demo/threads/Coroutine.pyt__hash__SscCstt|t|S(N(tcmpR (txty((s./usr/lib64/python2.7/Demo/threads/Coroutine.pyt__cmp__VscCs|jjdS(N(Rtpost(R((s./usr/lib64/python2.7/Demo/threads/Coroutine.pytresumeYscCs|jj|jjdS(N(Rtwaittclear(R((s./usr/lib64/python2.7/Demo/threads/Coroutine.pyR\s (t__name__t __module__RR R RRR(((s./usr/lib64/python2.7/Demo/threads/Coroutine.pyRHs      tKilledcBseZRS((RR(((s./usr/lib64/python2.7/Demo/threads/Coroutine.pyR`st EarlyExitcBseZRS((RR(((s./usr/lib64/python2.7/Demo/threads/Coroutine.pyRast CoroutinecBsPeZdZdZdZdZddZddZddZ RS(cCsHtd|_|_id|j6|_d|_d|_d|_dS(Ni(RRtactivetmaint invokedbytkilledtvaluet terminated_by(R((s./usr/lib64/python2.7/Demo/threads/Coroutine.pyRds   cGs7t|}d|j|Es  PK%L]3h!!threads/find.pyonu[ ^c@sddlZddlZddlZddlZddlZddlTddlZdddYZdZdZ dZ edS( iN(t*tWorkQcBs>eZdZdZdZdZdZdZRS(cCsAtj|_tj|_|jjg|_d|_dS(Ni(tthreadtallocatetmutexttodotacquiretworktbusy(tself((s)/usr/lib64/python2.7/Demo/threads/find.pyt__init__,s   cCs_||f}|jj|jj||jjt|jdkr[|jjndS(Ni(RRRtappendtreleasetlenR(R tfunctargstjob((s)/usr/lib64/python2.7/Demo/threads/find.pytaddwork3s    cCs|jj|jj|jdkr\t|jdkr\|jj|jjdS|jd}|jd=|jd|_|jjt|jdkr|jjn|S(Nii(RRRRR RR tNone(R R((s)/usr/lib64/python2.7/Demo/threads/find.pyt_getwork;s  $     cCsb|jj|jd|_|jdkrQt|jdkrQ|jjn|jjdS(Nii(RRRR RRR (R ((s)/usr/lib64/python2.7/Demo/threads/find.pyt _doneworkJs  $cCsQtjdx=|j}|s&Pn|\}}t|||jqWdS(Ngh㈵>(ttimetsleepRtapplyR(R RRR((s)/usr/lib64/python2.7/Demo/threads/find.pyt_workerQs    cCsV|js dSx+t|dD]}tj|jdqW|j|jjdS(Ni((RtrangeRt start_newRRR(R tnworkersti((s)/usr/lib64/python2.7/Demo/threads/find.pytrun[s   (t__name__t __module__R RRRRR(((s)/usr/lib64/python2.7/Demo/threads/find.pyR#s      c Csd}tjtjdd\}}x2|D]*\}}|dkr,tj|}q,q,W|sotjg}nt}x'|D]}|jt |t |fqWt j }|j |t j }tj jd||dS(Niis-w:s-wsTotal time %r sec. (tgetopttsystargvtstringtatoitostcurdirRRtfindtselectorRRtstderrtwrite( RtoptsRtopttargtwqtdirtt1tt2((s)/usr/lib64/python2.7/Demo/threads/find.pytmainfs      cCs#|td@dko"t|t S(Nii(tST_MODEtS_ISLNK(R/tnametfullnametstat((s)/usr/lib64/python2.7/Demo/threads/find.pyR(}scCs%ytj|}Wn*tjk r?}t|GdG|GHdSXx|D]}|tjtjfkrGtjj||}ytj|}Wn,tjk r}t|GdG|GHqGnX|||||r|GHnt |t rtjj |s|j t |||fqqqGqGWdS(Nt:(R%tlistdirterrortreprR&tpardirtpathtjointlstattS_ISDIRR3tismountRR'(R/tpredR.tnamestmsgR5R6R7((s)/usr/lib64/python2.7/Demo/threads/find.pyR's$ (( R!R R#RR%R7RRR2R(R'(((s)/usr/lib64/python2.7/Demo/threads/find.pyts       C   PK%L]threads/Coroutine.pyonu[ ^c@snddlZddlZdd dYZdefdYZdefdYZdd d YZdS( iNt_CoEventcBs>eZdZdZdZdZdZdZRS(cCs||_tj|_dS(N(tftsyncteventte(tselftfunc((s./usr/lib64/python2.7/Demo/threads/Coroutine.pyt__init__Is cCs%|jdkrdSd|jjSdS(Nsmain coroutinescoroutine for func (RtNonet func_name(R((s./usr/lib64/python2.7/Demo/threads/Coroutine.pyt__repr__MscCs t|S(N(tid(R((s./usr/lib64/python2.7/Demo/threads/Coroutine.pyt__hash__SscCstt|t|S(N(tcmpR (txty((s./usr/lib64/python2.7/Demo/threads/Coroutine.pyt__cmp__VscCs|jjdS(N(Rtpost(R((s./usr/lib64/python2.7/Demo/threads/Coroutine.pytresumeYscCs|jj|jjdS(N(Rtwaittclear(R((s./usr/lib64/python2.7/Demo/threads/Coroutine.pyR\s (t__name__t __module__RR R RRR(((s./usr/lib64/python2.7/Demo/threads/Coroutine.pyRHs      tKilledcBseZRS((RR(((s./usr/lib64/python2.7/Demo/threads/Coroutine.pyR`st EarlyExitcBseZRS((RR(((s./usr/lib64/python2.7/Demo/threads/Coroutine.pyRast CoroutinecBsPeZdZdZdZdZddZddZddZ RS(cCsHtd|_|_id|j6|_d|_d|_d|_dS(Ni(RRtactivetmaint invokedbytkilledtvaluet terminated_by(R((s./usr/lib64/python2.7/Demo/threads/Coroutine.pyRds   cGs7t|}d|j|Es  PK%L]}c threads/telnet.pycnu[ ^c@sddlZddlZddlZddlTddlZd ZedZedZedZ edZ ed Z d Z d Z d Ze dS(iN(t*iiiiiiicCsttjdkr5tjjdtjdntjd}yt|}Wn9tk rtjjtjddtjdnXttjdkrtjd}nd}d|d kodknrt|}nHyt |d}Wn2tk r/tjj|d tjdnXt t t }y|j ||fWn7tk r}tjjd |ftjdnXtjt|ft|dS( Nisusage: telnet hostname [port] is: bad host name ttelnett0t9ttcps: bad tcp service name sconnect failed: %r (tlentsystargvtstderrtwritetexitt gethostbynameterrortevalt getservbynametsockettAF_INETt SOCK_STREAMtconnecttthreadt start_newtchildtparent(thostthostaddrtservnametporttstmsg((s+/usr/lib64/python2.7/Demo/threads/telnet.pytmains6    cCswd}d}xd|jt\}}|sJtjjdtjdnd}x|D]}|rt|GH|j||d}qW|r+d}|tkr||}qN|t t fkr|t krdGndGtt }qN|t t fkr|t krdGndGtt }qNd Gt|GHqW|tkrDd}d GqW||}qWWtj j|tj jqWdS( Nits(Closed by remote host) is(DO)s(DONT)s(WILL)s(WONT)s (command)s(IAC)(trecvfromtBUFSIZERRR R tordtsendtIACtDOtDONTtWONTtWILLtstdouttflush(Rtiactopttdatatdummyt cleandatatc((s+/usr/lib64/python2.7/Demo/threads/telnet.pyRBsD          cCs1x*tjj}|sPn|j|qWdS(N(RtstdintreadlineR"(Rtline((s+/usr/lib64/python2.7/Demo/threads/telnet.pyRjs i (RtosttimeRRR tchrR#R%R$R&R'RRR(((s+/usr/lib64/python2.7/Demo/threads/telnet.pyts$        $ ( PK%L]Q, threads/Generator.pyonu[ ^c@s^ddlZddlZdefdYZdddYZdZdZedS( iNtKilledcBseZRS((t__name__t __module__(((s./usr/lib64/python2.7/Demo/threads/Generator.pyRst GeneratorcBs>eZdZdZdZdZdZdZRS(cCsstj|_tj|_|jj|jj||_||_d|_d|_tj |j ddS(Ni(( tthreadt allocate_locktgetlocktputlocktacquiretfunctargstdonetkilledtstart_new_threadt_start(tselfR R ((s./usr/lib64/python2.7/Demo/threads/Generator.pyt__init__ s      cCsyzO|jj|jsNyt|j|f|jWqNtk rJqNXnWd|jstd|_|jj nXdS(Ni( RRR tapplyR R RR Rtrelease(R((s./usr/lib64/python2.7/Demo/threads/Generator.pyRs      cCsN|jrtdn||_|jj|jj|jrJtndS(Ns put() called on killed generator(R t TypeErrortvalueRRRRR(RR((s./usr/lib64/python2.7/Demo/threads/Generator.pytput%s      cCsH|jrtdn|jj|jj|jrAtn|jS(Ns get() called on killed generator( R RRRRRR tEOFErrorR(R((s./usr/lib64/python2.7/Demo/threads/Generator.pytget/s      cCs/|jrtdnd|_|jjdS(Ns!kill() called on killed generatori(R RRR(R((s./usr/lib64/python2.7/Demo/threads/Generator.pytkill9s   cCst|j|jS(N(RR R (R((s./usr/lib64/python2.7/Demo/threads/Generator.pytclone@s(RRRRRRRR(((s./usr/lib64/python2.7/Demo/threads/Generator.pyR s   c Csd\}}}}}x||d|d|d}}}||||||||||f\}}}}||||}} xU|| kr|jt|d||d||}}||||}} qWqWdS(Nllll l (llll l(Rtint( tgtktatbta1tb1tptqtdtd1((s./usr/lib64/python2.7/Demo/threads/Generator.pytpiCs$6cCsttd}|jttd}xtdD]}|jGq5WH|j}|jx|jGtjjqcWdS(Ni ((( RR%RtrangeRRtsyststdouttflush(Rtith((s./usr/lib64/python2.7/Demo/threads/Generator.pyttestPs    ((R'Rt ExceptionRRR%R,(((s./usr/lib64/python2.7/Demo/threads/Generator.pyts  : PK%L]; threads/squasher.pynu[# Coroutine example: general coroutine transfers # # The program is a variation of a Simula 67 program due to Dahl & Hoare, # (Dahl/Dijkstra/Hoare, Structured Programming; Academic Press, 1972) # who in turn credit the original example to Conway. # # We have a number of input lines, terminated by a 0 byte. The problem # is to squash them together into output lines containing 72 characters # each. A semicolon must be added between input lines. Runs of blanks # and tabs in input lines must be squashed into single blanks. # Occurrences of "**" in input lines must be replaced by "^". # # Here's a test case: test = """\ d = sqrt(b**2 - 4*a*c) twoa = 2*a L = -b/twoa R = d/twoa A1 = L + R A2 = L - R\0 """ # The program should print: # d = sqrt(b^2 - 4*a*c);twoa = 2*a; L = -b/twoa; R = d/twoa; A1 = L + R; #A2 = L - R #done # getline: delivers the next input line to its invoker # disassembler: grabs input lines from getline, and delivers them one # character at a time to squasher, also inserting a semicolon into # the stream between lines # squasher: grabs characters from disassembler and passes them on to # assembler, first replacing "**" with "^" and squashing runs of # whitespace # assembler: grabs characters from squasher and packs them into lines # with 72 character each, delivering each such line to putline; # when it sees a null byte, passes the last line to putline and # then kills all the coroutines # putline: grabs lines from assembler, and just prints them from Coroutine import * def getline(text): for line in string.splitfields(text, '\n'): co.tran(codisassembler, line) def disassembler(): while 1: card = co.tran(cogetline) for i in range(len(card)): co.tran(cosquasher, card[i]) co.tran(cosquasher, ';') def squasher(): while 1: ch = co.tran(codisassembler) if ch == '*': ch2 = co.tran(codisassembler) if ch2 == '*': ch = '^' else: co.tran(coassembler, ch) ch = ch2 if ch in ' \t': while 1: ch2 = co.tran(codisassembler) if ch2 not in ' \t': break co.tran(coassembler, ' ') ch = ch2 co.tran(coassembler, ch) def assembler(): line = '' while 1: ch = co.tran(cosquasher) if ch == '\0': break if len(line) == 72: co.tran(coputline, line) line = '' line = line + ch line = line + ' ' * (72 - len(line)) co.tran(coputline, line) co.kill() def putline(): while 1: line = co.tran(coassembler) print line import string co = Coroutine() cogetline = co.create(getline, test) coputline = co.create(putline) coassembler = co.create(assembler) codisassembler = co.create(disassembler) cosquasher = co.create(squasher) co.tran(coputline) print 'done' # end of example PK%L]B} 6AAthreads/squasher.pyonu[ ^c@sdZddlTdZdZdZdZdZddlZeZej eeZ ej eZ ej eZ ej eZ ej eZeje d GHdS( s} d = sqrt(b**2 - 4*a*c) twoa = 2*a L = -b/twoa R = d/twoa A1 = L + R A2 = L - R i(t*cCs1x*tj|dD]}tjt|qWdS(Ns (tstringt splitfieldstcottrantcodisassembler(ttexttline((s-/usr/lib64/python2.7/Demo/threads/squasher.pytgetline-scCs[xTtjt}x.tt|D]}tjt||q%WtjtdqWdS(Nt;(RRt cogetlinetrangetlent cosquasher(tcardti((s-/usr/lib64/python2.7/Demo/threads/squasher.pyt disassembler1s cCsxtjt}|dkr[tjt}|dkrBd}q[tjt||}n|dkrx#tjt}|dkrjPqjqjWtjtd|}ntjt|qWdS(NRt^s t (RRRt coassembler(tchtch2((s-/usr/lib64/python2.7/Demo/threads/squasher.pytsquasher8s        cCsd}xXtjt}|dkr(Pnt|dkrStjt|d}n||}q W|ddt|}tjt|tjdS(NtsiHR(RRR R t coputlinetkill(RR((s-/usr/lib64/python2.7/Demo/threads/squasher.pyt assemblerKs  cCsxtjt}|GHqWdS(N(RRR(R((s-/usr/lib64/python2.7/Demo/threads/squasher.pytputlineYsNtdone(ttestt CoroutineRRRRRRRtcreateR RRRR R(((s-/usr/lib64/python2.7/Demo/threads/squasher.pyts         PK%L]__  threads/telnet.pynu[# Minimal interface to the Internet telnet protocol. # # *** modified to use threads *** # # It refuses all telnet options and does not recognize any of the other # telnet commands, but can still be used to connect in line-by-line mode. # It's also useful to play with a number of other services, # like time, finger, smtp and even ftp. # # Usage: telnet host [port] # # The port may be a service name or a decimal port number; # it defaults to 'telnet'. import sys, os, time from socket import * import thread BUFSIZE = 8*1024 # Telnet protocol characters IAC = chr(255) # Interpret as command DONT = chr(254) DO = chr(253) WONT = chr(252) WILL = chr(251) def main(): if len(sys.argv) < 2: sys.stderr.write('usage: telnet hostname [port]\n') sys.exit(2) host = sys.argv[1] try: hostaddr = gethostbyname(host) except error: sys.stderr.write(sys.argv[1] + ': bad host name\n') sys.exit(2) # if len(sys.argv) > 2: servname = sys.argv[2] else: servname = 'telnet' # if '0' <= servname[:1] <= '9': port = eval(servname) else: try: port = getservbyname(servname, 'tcp') except error: sys.stderr.write(servname + ': bad tcp service name\n') sys.exit(2) # s = socket(AF_INET, SOCK_STREAM) # try: s.connect((host, port)) except error, msg: sys.stderr.write('connect failed: %r\n' % (msg,)) sys.exit(1) # thread.start_new(child, (s,)) parent(s) def parent(s): # read socket, write stdout iac = 0 # Interpret next char as command opt = '' # Interpret next char as option while 1: data, dummy = s.recvfrom(BUFSIZE) if not data: # EOF -- exit sys.stderr.write( '(Closed by remote host)\n') sys.exit(1) cleandata = '' for c in data: if opt: print ord(c) ## print '(replying: %r)' % (opt+c,) s.send(opt + c) opt = '' elif iac: iac = 0 if c == IAC: cleandata = cleandata + c elif c in (DO, DONT): if c == DO: print '(DO)', else: print '(DONT)', opt = IAC + WONT elif c in (WILL, WONT): if c == WILL: print '(WILL)', else: print '(WONT)', opt = IAC + DONT else: print '(command)', ord(c) elif c == IAC: iac = 1 print '(IAC)', else: cleandata = cleandata + c sys.stdout.write(cleandata) sys.stdout.flush() ## print 'Out:', repr(cleandata) def child(s): # read stdin, write socket while 1: line = sys.stdin.readline() ## print 'Got:', repr(line) if not line: break s.send(line) main() PK%L]Ithreads/READMEnu[This directory contains some demonstrations of the thread module. These are mostly "proof of concept" type applications: Generator.py Generator class implemented with threads. sync.py Condition variables primitives by Tim Peters. telnet.py Version of ../sockets/telnet.py using threads. Coroutine.py Coroutines using threads, by Tim Peters (22 May 94) fcmp.py Example of above, by Tim squasher.py Another example of above, also by Tim PK%L]}c threads/telnet.pyonu[ ^c@sddlZddlZddlZddlTddlZd ZedZedZedZ edZ ed Z d Z d Z d Ze dS(iN(t*iiiiiiicCsttjdkr5tjjdtjdntjd}yt|}Wn9tk rtjjtjddtjdnXttjdkrtjd}nd}d|d kodknrt|}nHyt |d}Wn2tk r/tjj|d tjdnXt t t }y|j ||fWn7tk r}tjjd |ftjdnXtjt|ft|dS( Nisusage: telnet hostname [port] is: bad host name ttelnett0t9ttcps: bad tcp service name sconnect failed: %r (tlentsystargvtstderrtwritetexitt gethostbynameterrortevalt getservbynametsockettAF_INETt SOCK_STREAMtconnecttthreadt start_newtchildtparent(thostthostaddrtservnametporttstmsg((s+/usr/lib64/python2.7/Demo/threads/telnet.pytmains6    cCswd}d}xd|jt\}}|sJtjjdtjdnd}x|D]}|rt|GH|j||d}qW|r+d}|tkr||}qN|t t fkr|t krdGndGtt }qN|t t fkr|t krdGndGtt }qNd Gt|GHqW|tkrDd}d GqW||}qWWtj j|tj jqWdS( Nits(Closed by remote host) is(DO)s(DONT)s(WILL)s(WONT)s (command)s(IAC)(trecvfromtBUFSIZERRR R tordtsendtIACtDOtDONTtWONTtWILLtstdouttflush(Rtiactopttdatatdummyt cleandatatc((s+/usr/lib64/python2.7/Demo/threads/telnet.pyRBsD          cCs1x*tjj}|sPn|j|qWdS(N(RtstdintreadlineR"(Rtline((s+/usr/lib64/python2.7/Demo/threads/telnet.pyRjs i (RtosttimeRRR tchrR#R%R$R&R'RRR(((s+/usr/lib64/python2.7/Demo/threads/telnet.pyts$        $ ( PK%L]8threads/Coroutine.pynu[# Coroutine implementation using Python threads. # # Combines ideas from Guido's Generator module, and from the coroutine # features of Icon and Simula 67. # # To run a collection of functions as coroutines, you need to create # a Coroutine object to control them: # co = Coroutine() # and then 'create' a subsidiary object for each function in the # collection: # cof1 = co.create(f1 [, arg1, arg2, ...]) # [] means optional, # cof2 = co.create(f2 [, arg1, arg2, ...]) #... not list # cof3 = co.create(f3 [, arg1, arg2, ...]) # etc. The functions need not be distinct; 'create'ing the same # function multiple times gives you independent instances of the # function. # # To start the coroutines running, use co.tran on one of the create'd # functions; e.g., co.tran(cof2). The routine that first executes # co.tran is called the "main coroutine". It's special in several # respects: it existed before you created the Coroutine object; if any of # the create'd coroutines exits (does a return, or suffers an unhandled # exception), EarlyExit error is raised in the main coroutine; and the # co.detach() method transfers control directly to the main coroutine # (you can't use co.tran() for this because the main coroutine doesn't # have a name ...). # # Coroutine objects support these methods: # # handle = .create(func [, arg1, arg2, ...]) # Creates a coroutine for an invocation of func(arg1, arg2, ...), # and returns a handle ("name") for the coroutine so created. The # handle can be used as the target in a subsequent .tran(). # # .tran(target, data=None) # Transfer control to the create'd coroutine "target", optionally # passing it an arbitrary piece of data. To the coroutine A that does # the .tran, .tran acts like an ordinary function call: another # coroutine B can .tran back to it later, and if it does A's .tran # returns the 'data' argument passed to B's tran. E.g., # # in coroutine coA in coroutine coC in coroutine coB # x = co.tran(coC) co.tran(coB) co.tran(coA,12) # print x # 12 # # The data-passing feature is taken from Icon, and greatly cuts # the need to use global variables for inter-coroutine communication. # # .back( data=None ) # The same as .tran(invoker, data=None), where 'invoker' is the # coroutine that most recently .tran'ed control to the coroutine # doing the .back. This is akin to Icon's "&source". # # .detach( data=None ) # The same as .tran(main, data=None), where 'main' is the # (unnameable!) coroutine that started it all. 'main' has all the # rights of any other coroutine: upon receiving control, it can # .tran to an arbitrary coroutine of its choosing, go .back to # the .detach'er, or .kill the whole thing. # # .kill() # Destroy all the coroutines, and return control to the main # coroutine. None of the create'ed coroutines can be resumed after a # .kill(). An EarlyExit exception does a .kill() automatically. It's # a good idea to .kill() coroutines you're done with, since the # current implementation consumes a thread for each coroutine that # may be resumed. import thread import sync class _CoEvent: def __init__(self, func): self.f = func self.e = sync.event() def __repr__(self): if self.f is None: return 'main coroutine' else: return 'coroutine for func ' + self.f.func_name def __hash__(self): return id(self) def __cmp__(x,y): return cmp(id(x), id(y)) def resume(self): self.e.post() def wait(self): self.e.wait() self.e.clear() class Killed(Exception): pass class EarlyExit(Exception): pass class Coroutine: def __init__(self): self.active = self.main = _CoEvent(None) self.invokedby = {self.main: None} self.killed = 0 self.value = None self.terminated_by = None def create(self, func, *args): me = _CoEvent(func) self.invokedby[me] = None thread.start_new_thread(self._start, (me,) + args) return me def _start(self, me, *args): me.wait() if not self.killed: try: try: apply(me.f, args) except Killed: pass finally: if not self.killed: self.terminated_by = me self.kill() def kill(self): if self.killed: raise TypeError, 'kill() called on dead coroutines' self.killed = 1 for coroutine in self.invokedby.keys(): coroutine.resume() def back(self, data=None): return self.tran( self.invokedby[self.active], data ) def detach(self, data=None): return self.tran( self.main, data ) def tran(self, target, data=None): if not self.invokedby.has_key(target): raise TypeError, '.tran target %r is not an active coroutine' % (target,) if self.killed: raise TypeError, '.tran target %r is killed' % (target,) self.value = data me = self.active self.invokedby[target] = me self.active = target target.resume() me.wait() if self.killed: if self.main is not me: raise Killed if self.terminated_by is not None: raise EarlyExit, '%r terminated early' % (self.terminated_by,) return self.value # end of module PK%L]3h!!threads/find.pycnu[ ^c@sddlZddlZddlZddlZddlZddlTddlZdddYZdZdZ dZ edS( iN(t*tWorkQcBs>eZdZdZdZdZdZdZRS(cCsAtj|_tj|_|jjg|_d|_dS(Ni(tthreadtallocatetmutexttodotacquiretworktbusy(tself((s)/usr/lib64/python2.7/Demo/threads/find.pyt__init__,s   cCs_||f}|jj|jj||jjt|jdkr[|jjndS(Ni(RRRtappendtreleasetlenR(R tfunctargstjob((s)/usr/lib64/python2.7/Demo/threads/find.pytaddwork3s    cCs|jj|jj|jdkr\t|jdkr\|jj|jjdS|jd}|jd=|jd|_|jjt|jdkr|jjn|S(Nii(RRRRR RR tNone(R R((s)/usr/lib64/python2.7/Demo/threads/find.pyt_getwork;s  $     cCsb|jj|jd|_|jdkrQt|jdkrQ|jjn|jjdS(Nii(RRRR RRR (R ((s)/usr/lib64/python2.7/Demo/threads/find.pyt _doneworkJs  $cCsQtjdx=|j}|s&Pn|\}}t|||jqWdS(Ngh㈵>(ttimetsleepRtapplyR(R RRR((s)/usr/lib64/python2.7/Demo/threads/find.pyt_workerQs    cCsV|js dSx+t|dD]}tj|jdqW|j|jjdS(Ni((RtrangeRt start_newRRR(R tnworkersti((s)/usr/lib64/python2.7/Demo/threads/find.pytrun[s   (t__name__t __module__R RRRRR(((s)/usr/lib64/python2.7/Demo/threads/find.pyR#s      c Csd}tjtjdd\}}x2|D]*\}}|dkr,tj|}q,q,W|sotjg}nt}x'|D]}|jt |t |fqWt j }|j |t j }tj jd||dS(Niis-w:s-wsTotal time %r sec. (tgetopttsystargvtstringtatoitostcurdirRRtfindtselectorRRtstderrtwrite( RtoptsRtopttargtwqtdirtt1tt2((s)/usr/lib64/python2.7/Demo/threads/find.pytmainfs      cCs#|td@dko"t|t S(Nii(tST_MODEtS_ISLNK(R/tnametfullnametstat((s)/usr/lib64/python2.7/Demo/threads/find.pyR(}scCs%ytj|}Wn*tjk r?}t|GdG|GHdSXx|D]}|tjtjfkrGtjj||}ytj|}Wn,tjk r}t|GdG|GHqGnX|||||r|GHnt |t rtjj |s|j t |||fqqqGqGWdS(Nt:(R%tlistdirterrortreprR&tpardirtpathtjointlstattS_ISDIRR3tismountRR'(R/tpredR.tnamestmsgR5R6R7((s)/usr/lib64/python2.7/Demo/threads/find.pyR's$ (( R!R R#RR%R7RRR2R(R'(((s)/usr/lib64/python2.7/Demo/threads/find.pyts       C   PK%L]Q, threads/Generator.pycnu[ ^c@s^ddlZddlZdefdYZdddYZdZdZedS( iNtKilledcBseZRS((t__name__t __module__(((s./usr/lib64/python2.7/Demo/threads/Generator.pyRst GeneratorcBs>eZdZdZdZdZdZdZRS(cCsstj|_tj|_|jj|jj||_||_d|_d|_tj |j ddS(Ni(( tthreadt allocate_locktgetlocktputlocktacquiretfunctargstdonetkilledtstart_new_threadt_start(tselfR R ((s./usr/lib64/python2.7/Demo/threads/Generator.pyt__init__ s      cCsyzO|jj|jsNyt|j|f|jWqNtk rJqNXnWd|jstd|_|jj nXdS(Ni( RRR tapplyR R RR Rtrelease(R((s./usr/lib64/python2.7/Demo/threads/Generator.pyRs      cCsN|jrtdn||_|jj|jj|jrJtndS(Ns put() called on killed generator(R t TypeErrortvalueRRRRR(RR((s./usr/lib64/python2.7/Demo/threads/Generator.pytput%s      cCsH|jrtdn|jj|jj|jrAtn|jS(Ns get() called on killed generator( R RRRRRR tEOFErrorR(R((s./usr/lib64/python2.7/Demo/threads/Generator.pytget/s      cCs/|jrtdnd|_|jjdS(Ns!kill() called on killed generatori(R RRR(R((s./usr/lib64/python2.7/Demo/threads/Generator.pytkill9s   cCst|j|jS(N(RR R (R((s./usr/lib64/python2.7/Demo/threads/Generator.pytclone@s(RRRRRRRR(((s./usr/lib64/python2.7/Demo/threads/Generator.pyR s   c Csd\}}}}}x||d|d|d}}}||||||||||f\}}}}||||}} xU|| kr|jt|d||d||}}||||}} qWqWdS(Nllll l (llll l(Rtint( tgtktatbta1tb1tptqtdtd1((s./usr/lib64/python2.7/Demo/threads/Generator.pytpiCs$6cCsttd}|jttd}xtdD]}|jGq5WH|j}|jx|jGtjjqcWdS(Ni ((( RR%RtrangeRRtsyststdouttflush(Rtith((s./usr/lib64/python2.7/Demo/threads/Generator.pyttestPs    ((R'Rt ExceptionRRR%R,(((s./usr/lib64/python2.7/Demo/threads/Generator.pyts  : PK%L] ,threads/fcmp.pyonu[ ^c@szddlTdZdZedddgeddgggdggddddggdd gd ggggZeed Zeed eGHeed eGHeeed GHeed eGHeeed GHeddgd ggdgdgd gGHeddgd ggdgdgd gGHeddgd ggdgdgdgGHdS(i(t*cCsJxC|D];}t|tgkr5t||q|j|qWdS(N(ttypetfringetback(tcotlisttx((s)/usr/lib64/python2.7/Demo/threads/fcmp.pyRs cCsOt}|jt||}yx|j|Gq$WWntk rInXHdS(N(t CoroutinetcreateRttrant EarlyExit(RRtf((s)/usr/lib64/python2.7/Demo/threads/fcmp.pyt printinorders  iiiiiiicCst}|jt||}t}|jt||}xy|j|}WnDtk ry|j|}Wntk rdSX|jdSXy|j|}Wntk r|jdSX||kr?|j|jt||Sq?WdS(Niii(RRRR R tkilltcmp(tl1tl2tco1tf1tco2tf2tv1tv2((s)/usr/lib64/python2.7/Demo/threads/fcmp.pytfcmps.         iii N(RRR RRtrange(((s)/usr/lib64/python2.7/Demo/threads/fcmp.pyts$   -  PK%L]Vm threads/Generator.pynu[# Generator implementation using threads import sys import thread class Killed(Exception): pass class Generator: # Constructor def __init__(self, func, args): self.getlock = thread.allocate_lock() self.putlock = thread.allocate_lock() self.getlock.acquire() self.putlock.acquire() self.func = func self.args = args self.done = 0 self.killed = 0 thread.start_new_thread(self._start, ()) # Internal routine def _start(self): try: self.putlock.acquire() if not self.killed: try: apply(self.func, (self,) + self.args) except Killed: pass finally: if not self.killed: self.done = 1 self.getlock.release() # Called by producer for each value; raise Killed if no more needed def put(self, value): if self.killed: raise TypeError, 'put() called on killed generator' self.value = value self.getlock.release() # Resume consumer thread self.putlock.acquire() # Wait for next get() call if self.killed: raise Killed # Called by producer to get next value; raise EOFError if no more def get(self): if self.killed: raise TypeError, 'get() called on killed generator' self.putlock.release() # Resume producer thread self.getlock.acquire() # Wait for value to appear if self.done: raise EOFError # Say there are no more values return self.value # Called by consumer if no more values wanted def kill(self): if self.killed: raise TypeError, 'kill() called on killed generator' self.killed = 1 self.putlock.release() # Clone constructor def clone(self): return Generator(self.func, self.args) def pi(g): k, a, b, a1, b1 = 2L, 4L, 1L, 12L, 4L while 1: # Next approximation p, q, k = k*k, 2L*k+1L, k+1L a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1 # Print common digits d, d1 = a//b, a1//b1 while d == d1: g.put(int(d)) a, a1 = 10L*(a%b), 10L*(a1%b1) d, d1 = a//b, a1//b1 def test(): g = Generator(pi, ()) g.kill() g = Generator(pi, ()) for i in range(10): print g.get(), print h = g.clone() g.kill() while 1: print h.get(), sys.stdout.flush() test() PK%L]j+j+threads/sync.pyonu[ ^c@sddlZdddYZdddYZdddYZddd YZd dd YZd Zd ZdZdZ dZ dZ e dkre ndS(iNt conditioncBsDeZddZdZdZdZdZddZRS(cCs|dkrtj|_n3t|drHt|drH||_n tdtj|_|jjtj|_d|_ d|_ d|_ d|_ d|_ dS(Ntacquiretreleases.condition constructor requires a lock argumenti(tNonetthreadt allocate_locktmutexthasattrt TypeErrortcheckoutRtidlocktidtwaitingtpendingt toreleaset releasing(tselftlock((s)/usr/lib64/python2.7/Demo/threads/sync.pyt__init__s        cCs|jjdS(N(RR(R((s)/usr/lib64/python2.7/Demo/threads/sync.pyR*scCs|jjdS(N(RR(R((s)/usr/lib64/python2.7/Demo/threads/sync.pyR-scCs3|j|j|j}}}|js5tdn|j|j}|jd|_|j|jx?|j|j||jkrPn|j|jqoW|j d|_ |j d|_ |j r|jn7d|_ |j |jko dknrd|_n|j|jdS(Ns1condition must be .acquire'd when .wait() invokedii( RR R tlockedt ValueErrorRR R RR RR(RRR R tmyid((s)/usr/lib64/python2.7/Demo/threads/sync.pytwait0s2           "  cCs|jddS(Ni(t broadcast(R((s)/usr/lib64/python2.7/Demo/threads/sync.pytsignalNsicCs|dkrtd|fn|dkr/dS|jj|jrt|j|j|_d|_|jd|_n|dkr|j|_nt|j|j||_|jr|j rd|_|j j n|jj dS(Nis.broadcast called with num %rii( RR RR R R RtminRR R(Rtnum((s)/usr/lib64/python2.7/Demo/threads/sync.pyRQs"        N( t__name__t __module__RRRRRRR(((s)/usr/lib64/python2.7/Demo/threads/sync.pyRs      tbarriercBseZdZdZRS(cCs"||_||_t|_dS(N(tnttogoRtfull(RR((s)/usr/lib64/python2.7/Demo/threads/sync.pyRfs  cCs]|j}|j|jd|_|jr9|jn|j|_|j|jdS(Ni(R RRRRRR(RR ((s)/usr/lib64/python2.7/Demo/threads/sync.pytenterks      (RRRR!(((s)/usr/lib64/python2.7/Demo/threads/sync.pyRes teventcBs5eZdZdZdZdZdZRS(cCsd|_t|_dS(Ni(tstateRtposted(R((s)/usr/lib64/python2.7/Demo/threads/sync.pyRws cCs4|jjd|_|jj|jjdS(Ni(R$RR#RR(R((s)/usr/lib64/python2.7/Demo/threads/sync.pytpost{s   cCs'|jjd|_|jjdS(Ni(R$RR#R(R((s)/usr/lib64/python2.7/Demo/threads/sync.pytclears  cCs'|jj|j}|jj|S(N(R$RR#R(Rtanswer((s)/usr/lib64/python2.7/Demo/threads/sync.pyt is_posteds   cCs7|jj|js&|jjn|jjdS(N(R$RR#RR(R((s)/usr/lib64/python2.7/Demo/threads/sync.pyRs  (RRRR%R&R(R(((s)/usr/lib64/python2.7/Demo/threads/sync.pyR"vs     t semaphorecBs&eZddZdZdZRS(icCs>|dkrtd|n||_||_t|_dS(Nis semaphore count %d; must be >= 1(RtcounttmaxcountRtnonzero(RR*((s)/usr/lib64/python2.7/Demo/threads/sync.pyRs    cCsQ|jjx |jdkr/|jjqW|jd|_|jjdS(Nii(R,RR*RR(R((s)/usr/lib64/python2.7/Demo/threads/sync.pytps  cCs`|jj|j|jkr2td|jn|jd|_|jj|jjdS(Ns:.v() tried to raise semaphore count above initial value %ri(R,RR*R+RRR(R((s)/usr/lib64/python2.7/Demo/threads/sync.pytvs   (RRRR-R.(((s)/usr/lib64/python2.7/Demo/threads/sync.pyR)s  tmrswcBs>eZdZdZdZdZdZdZRS(cCsRtj|_d|_d|_d|_t|j|_t|j|_dS(Ni( RRtrwOKtnrtnwtwritingRtreadOKtwriteOK(R((s)/usr/lib64/python2.7/Demo/threads/sync.pyRs    cCsK|jjx|jr)|jjqW|jd|_|jjdS(Ni(R0RR2R4RR1R(R((s)/usr/lib64/python2.7/Demo/threads/sync.pytread_ins   cCsh|jj|jdkr(tdn|jd|_|jdkrW|jjn|jjdS(Nis,.read_out() invoked without an active readeri(R0RR1RR5RR(R((s)/usr/lib64/python2.7/Demo/threads/sync.pytread_outs  cCs]|jj|jd|_x#|js2|jrB|jjq Wd|_|jjdS(Ni(R0RR2R3R1R5RR(R((s)/usr/lib64/python2.7/Demo/threads/sync.pytwrite_ins   cCsr|jj|js"tdnd|_|jd|_|jrT|jjn |jj|jj dS(Ns-.write_out() invoked without an active writerii( R0RR3RR2R5RR4RR(R((s)/usr/lib64/python2.7/Demo/threads/sync.pyt write_outs      cCsu|jj|js"tdnd|_|jd|_|jd|_|jsd|jjn|jjdS(Ns1.write_to_read() invoked without an active writerii( R0RR3RR2R1R4RR(R((s)/usr/lib64/python2.7/Demo/threads/sync.pyt write_to_reads     (RRRR6R7R8R9R:(((s)/usr/lib64/python2.7/Demo/threads/sync.pyR/s    cGsytjtd}atjtjtj|dG|GdGttGdGHtjtj ||f|dS(Nisstarting threads--talive( ttidRtTIDRtioR;tappendtlenRtstart_new_thread(tfunctargsR ((s)/usr/lib64/python2.7/Demo/threads/sync.pyt _new_threads    c CsWtjdG|GdG|G|GHtj||dkr||}|d}xQt||D]@}|||kr]||||||<||<|d}q]q]W||d|||<||dRRtrangeR"RDt_qsortRR;tremoveR%( R<tatltrtfinishedtpivottjtitl_subarray_sortedtr_subarray_sorted((s)/usr/lib64/python2.7/Demo/threads/sync.pyRGs,    !      cCstjdG|GdGHtjx]tdt|D]F}tjtd|}tj||||||<||RRRFR@twhtrandintR;RHR%(R<RIRLRORN((s)/usr/lib64/python2.7/Demo/threads/sync.pyt _randarrays    !  cCs.|tt|kr*td|fndS(Ns a not sorted(RFR@R(RI((s)/usr/lib64/python2.7/Demo/threads/sync.pyt _check_sortscCs6tjdG|GdG|GHtjt}tt|||jtjdG|GdG|GHtj|jtt|dt |||jt |tjdG|GdGHtj|j tjdG|GdGHtjtjt j |tj|j |j |jdS(NRt randomizingtsortingisentering barriersleaving barrier(R>RRR"RDRTRR&RGR@RUR!R;RHR%(R<RItbartdoneRL((s)/usr/lib64/python2.7/Demo/threads/sync.pyt _run_one_sorts4                 cCsXddl}|jadatjatjatjagad}g}x/t |D]!}|j t |ddq^Wt |}t }x+t |D]}t t||||qW|jdGHtrtdtfnxWt |D]I}||}t||ddkr9td|d fnt|qWd GtGd GHdS( Niiiii s*all threads done, and checking results ...sthreads still alive at endslength of arrays screwed ups test passed!sthreads created in all(trandomRSR=RRR<R>RRR;RFR?RR"RDRZRRR@RU(R[tNSORTStarraysRORXRLRI((s)/usr/lib64/python2.7/Demo/threads/sync.pyttest7s2         t__main__(((((( RRRR"R)R/RDRGRTRURZR^R(((s)/usr/lib64/python2.7/Demo/threads/sync.pyts TE     ! PK%L] ,threads/fcmp.pycnu[ ^c@szddlTdZdZedddgeddgggdggddddggdd gd ggggZeed Zeed eGHeed eGHeeed GHeed eGHeeed GHeddgd ggdgdgd gGHeddgd ggdgdgd gGHeddgd ggdgdgdgGHdS(i(t*cCsJxC|D];}t|tgkr5t||q|j|qWdS(N(ttypetfringetback(tcotlisttx((s)/usr/lib64/python2.7/Demo/threads/fcmp.pyRs cCsOt}|jt||}yx|j|Gq$WWntk rInXHdS(N(t CoroutinetcreateRttrant EarlyExit(RRtf((s)/usr/lib64/python2.7/Demo/threads/fcmp.pyt printinorders  iiiiiiicCst}|jt||}t}|jt||}xy|j|}WnDtk ry|j|}Wntk rdSX|jdSXy|j|}Wntk r|jdSX||kr?|j|jt||Sq?WdS(Niii(RRRR R tkilltcmp(tl1tl2tco1tf1tco2tf2tv1tv2((s)/usr/lib64/python2.7/Demo/threads/fcmp.pytfcmps.         iii N(RRR RRtrange(((s)/usr/lib64/python2.7/Demo/threads/fcmp.pyts$   -  PK%L]j+j+threads/sync.pycnu[ ^c@sddlZdddYZdddYZdddYZddd YZd dd YZd Zd ZdZdZ dZ dZ e dkre ndS(iNt conditioncBsDeZddZdZdZdZdZddZRS(cCs|dkrtj|_n3t|drHt|drH||_n tdtj|_|jjtj|_d|_ d|_ d|_ d|_ d|_ dS(Ntacquiretreleases.condition constructor requires a lock argumenti(tNonetthreadt allocate_locktmutexthasattrt TypeErrortcheckoutRtidlocktidtwaitingtpendingt toreleaset releasing(tselftlock((s)/usr/lib64/python2.7/Demo/threads/sync.pyt__init__s        cCs|jjdS(N(RR(R((s)/usr/lib64/python2.7/Demo/threads/sync.pyR*scCs|jjdS(N(RR(R((s)/usr/lib64/python2.7/Demo/threads/sync.pyR-scCs3|j|j|j}}}|js5tdn|j|j}|jd|_|j|jx?|j|j||jkrPn|j|jqoW|j d|_ |j d|_ |j r|jn7d|_ |j |jko dknrd|_n|j|jdS(Ns1condition must be .acquire'd when .wait() invokedii( RR R tlockedt ValueErrorRR R RR RR(RRR R tmyid((s)/usr/lib64/python2.7/Demo/threads/sync.pytwait0s2           "  cCs|jddS(Ni(t broadcast(R((s)/usr/lib64/python2.7/Demo/threads/sync.pytsignalNsicCs|dkrtd|fn|dkr/dS|jj|jrt|j|j|_d|_|jd|_n|dkr|j|_nt|j|j||_|jr|j rd|_|j j n|jj dS(Nis.broadcast called with num %rii( RR RR R R RtminRR R(Rtnum((s)/usr/lib64/python2.7/Demo/threads/sync.pyRQs"        N( t__name__t __module__RRRRRRR(((s)/usr/lib64/python2.7/Demo/threads/sync.pyRs      tbarriercBseZdZdZRS(cCs"||_||_t|_dS(N(tnttogoRtfull(RR((s)/usr/lib64/python2.7/Demo/threads/sync.pyRfs  cCs]|j}|j|jd|_|jr9|jn|j|_|j|jdS(Ni(R RRRRRR(RR ((s)/usr/lib64/python2.7/Demo/threads/sync.pytenterks      (RRRR!(((s)/usr/lib64/python2.7/Demo/threads/sync.pyRes teventcBs5eZdZdZdZdZdZRS(cCsd|_t|_dS(Ni(tstateRtposted(R((s)/usr/lib64/python2.7/Demo/threads/sync.pyRws cCs4|jjd|_|jj|jjdS(Ni(R$RR#RR(R((s)/usr/lib64/python2.7/Demo/threads/sync.pytpost{s   cCs'|jjd|_|jjdS(Ni(R$RR#R(R((s)/usr/lib64/python2.7/Demo/threads/sync.pytclears  cCs'|jj|j}|jj|S(N(R$RR#R(Rtanswer((s)/usr/lib64/python2.7/Demo/threads/sync.pyt is_posteds   cCs7|jj|js&|jjn|jjdS(N(R$RR#RR(R((s)/usr/lib64/python2.7/Demo/threads/sync.pyRs  (RRRR%R&R(R(((s)/usr/lib64/python2.7/Demo/threads/sync.pyR"vs     t semaphorecBs&eZddZdZdZRS(icCs>|dkrtd|n||_||_t|_dS(Nis semaphore count %d; must be >= 1(RtcounttmaxcountRtnonzero(RR*((s)/usr/lib64/python2.7/Demo/threads/sync.pyRs    cCsQ|jjx |jdkr/|jjqW|jd|_|jjdS(Nii(R,RR*RR(R((s)/usr/lib64/python2.7/Demo/threads/sync.pytps  cCs`|jj|j|jkr2td|jn|jd|_|jj|jjdS(Ns:.v() tried to raise semaphore count above initial value %ri(R,RR*R+RRR(R((s)/usr/lib64/python2.7/Demo/threads/sync.pytvs   (RRRR-R.(((s)/usr/lib64/python2.7/Demo/threads/sync.pyR)s  tmrswcBs>eZdZdZdZdZdZdZRS(cCsRtj|_d|_d|_d|_t|j|_t|j|_dS(Ni( RRtrwOKtnrtnwtwritingRtreadOKtwriteOK(R((s)/usr/lib64/python2.7/Demo/threads/sync.pyRs    cCsK|jjx|jr)|jjqW|jd|_|jjdS(Ni(R0RR2R4RR1R(R((s)/usr/lib64/python2.7/Demo/threads/sync.pytread_ins   cCsh|jj|jdkr(tdn|jd|_|jdkrW|jjn|jjdS(Nis,.read_out() invoked without an active readeri(R0RR1RR5RR(R((s)/usr/lib64/python2.7/Demo/threads/sync.pytread_outs  cCs]|jj|jd|_x#|js2|jrB|jjq Wd|_|jjdS(Ni(R0RR2R3R1R5RR(R((s)/usr/lib64/python2.7/Demo/threads/sync.pytwrite_ins   cCsr|jj|js"tdnd|_|jd|_|jrT|jjn |jj|jj dS(Ns-.write_out() invoked without an active writerii( R0RR3RR2R5RR4RR(R((s)/usr/lib64/python2.7/Demo/threads/sync.pyt write_outs      cCsu|jj|js"tdnd|_|jd|_|jd|_|jsd|jjn|jjdS(Ns1.write_to_read() invoked without an active writerii( R0RR3RR2R1R4RR(R((s)/usr/lib64/python2.7/Demo/threads/sync.pyt write_to_reads     (RRRR6R7R8R9R:(((s)/usr/lib64/python2.7/Demo/threads/sync.pyR/s    cGsytjtd}atjtjtj|dG|GdGttGdGHtjtj ||f|dS(Nisstarting threads--talive( ttidRtTIDRtioR;tappendtlenRtstart_new_thread(tfunctargsR ((s)/usr/lib64/python2.7/Demo/threads/sync.pyt _new_threads    c CsWtjdG|GdG|G|GHtj||dkr||}|d}xQt||D]@}|||kr]||||||<||<|d}q]q]W||d|||<||dRRtrangeR"RDt_qsortRR;tremoveR%( R<tatltrtfinishedtpivottjtitl_subarray_sortedtr_subarray_sorted((s)/usr/lib64/python2.7/Demo/threads/sync.pyRGs,    !      cCstjdG|GdGHtjx]tdt|D]F}tjtd|}tj||||||<||RRRFR@twhtrandintR;RHR%(R<RIRLRORN((s)/usr/lib64/python2.7/Demo/threads/sync.pyt _randarrays    !  cCs.|tt|kr*td|fndS(Ns a not sorted(RFR@R(RI((s)/usr/lib64/python2.7/Demo/threads/sync.pyt _check_sortscCs6tjdG|GdG|GHtjt}tt|||jtjdG|GdG|GHtj|jtt|dt |||jt |tjdG|GdGHtj|j tjdG|GdGHtjtjt j |tj|j |j |jdS(NRt randomizingtsortingisentering barriersleaving barrier(R>RRR"RDRTRR&RGR@RUR!R;RHR%(R<RItbartdoneRL((s)/usr/lib64/python2.7/Demo/threads/sync.pyt _run_one_sorts4                 cCsXddl}|jadatjatjatjagad}g}x/t |D]!}|j t |ddq^Wt |}t }x+t |D]}t t||||qW|jdGHtrtdtfnxWt |D]I}||}t||ddkr9td|d fnt|qWd GtGd GHdS( Niiiii s*all threads done, and checking results ...sthreads still alive at endslength of arrays screwed ups test passed!sthreads created in all(trandomRSR=RRR<R>RRR;RFR?RR"RDRZRRR@RU(R[tNSORTStarraysRORXRLRI((s)/usr/lib64/python2.7/Demo/threads/sync.pyttest7s2         t__main__(((((( RRRR"R)R/RDRGRTRURZR^R(((s)/usr/lib64/python2.7/Demo/threads/sync.pyts TE     ! PK%L]eITTthreads/sync.pynu[# Defines classes that provide synchronization objects. Note that use of # this module requires that your Python support threads. # # condition(lock=None) # a POSIX-like condition-variable object # barrier(n) # an n-thread barrier # event() # an event object # semaphore(n=1) # a semaphore object, with initial count n # mrsw() # a multiple-reader single-writer lock # # CONDITIONS # # A condition object is created via # import this_module # your_condition_object = this_module.condition(lock=None) # # As explained below, a condition object has a lock associated with it, # used in the protocol to protect condition data. You can specify a # lock to use in the constructor, else the constructor will allocate # an anonymous lock for you. Specifying a lock explicitly can be useful # when more than one condition keys off the same set of shared data. # # Methods: # .acquire() # acquire the lock associated with the condition # .release() # release the lock associated with the condition # .wait() # block the thread until such time as some other thread does a # .signal or .broadcast on the same condition, and release the # lock associated with the condition. The lock associated with # the condition MUST be in the acquired state at the time # .wait is invoked. # .signal() # wake up exactly one thread (if any) that previously did a .wait # on the condition; that thread will awaken with the lock associated # with the condition in the acquired state. If no threads are # .wait'ing, this is a nop. If more than one thread is .wait'ing on # the condition, any of them may be awakened. # .broadcast() # wake up all threads (if any) that are .wait'ing on the condition; # the threads are woken up serially, each with the lock in the # acquired state, so should .release() as soon as possible. If no # threads are .wait'ing, this is a nop. # # Note that if a thread does a .wait *while* a signal/broadcast is # in progress, it's guaranteeed to block until a subsequent # signal/broadcast. # # Secret feature: `broadcast' actually takes an integer argument, # and will wake up exactly that many waiting threads (or the total # number waiting, if that's less). Use of this is dubious, though, # and probably won't be supported if this form of condition is # reimplemented in C. # # DIFFERENCES FROM POSIX # # + A separate mutex is not needed to guard condition data. Instead, a # condition object can (must) be .acquire'ed and .release'ed directly. # This eliminates a common error in using POSIX conditions. # # + Because of implementation difficulties, a POSIX `signal' wakes up # _at least_ one .wait'ing thread. Race conditions make it difficult # to stop that. This implementation guarantees to wake up only one, # but you probably shouldn't rely on that. # # PROTOCOL # # Condition objects are used to block threads until "some condition" is # true. E.g., a thread may wish to wait until a producer pumps out data # for it to consume, or a server may wish to wait until someone requests # its services, or perhaps a whole bunch of threads want to wait until a # preceding pass over the data is complete. Early models for conditions # relied on some other thread figuring out when a blocked thread's # condition was true, and made the other thread responsible both for # waking up the blocked thread and guaranteeing that it woke up with all # data in a correct state. This proved to be very delicate in practice, # and gave conditions a bad name in some circles. # # The POSIX model addresses these problems by making a thread responsible # for ensuring that its own state is correct when it wakes, and relies # on a rigid protocol to make this easy; so long as you stick to the # protocol, POSIX conditions are easy to "get right": # # A) The thread that's waiting for some arbitrarily-complex condition # (ACC) to become true does: # # condition.acquire() # while not (code to evaluate the ACC): # condition.wait() # # That blocks the thread, *and* releases the lock. When a # # condition.signal() happens, it will wake up some thread that # # did a .wait, *and* acquire the lock again before .wait # # returns. # # # # Because the lock is acquired at this point, the state used # # in evaluating the ACC is frozen, so it's safe to go back & # # reevaluate the ACC. # # # At this point, ACC is true, and the thread has the condition # # locked. # # So code here can safely muck with the shared state that # # went into evaluating the ACC -- if it wants to. # # When done mucking with the shared state, do # condition.release() # # B) Threads that are mucking with shared state that may affect the # ACC do: # # condition.acquire() # # muck with shared state # condition.release() # if it's possible that ACC is true now: # condition.signal() # or .broadcast() # # Note: You may prefer to put the "if" clause before the release(). # That's fine, but do note that anyone waiting on the signal will # stay blocked until the release() is done (since acquiring the # condition is part of what .wait() does before it returns). # # TRICK OF THE TRADE # # With simpler forms of conditions, it can be impossible to know when # a thread that's supposed to do a .wait has actually done it. But # because this form of condition releases a lock as _part_ of doing a # wait, the state of that lock can be used to guarantee it. # # E.g., suppose thread A spawns thread B and later wants to wait for B to # complete: # # In A: In B: # # B_done = condition() ... do work ... # B_done.acquire() B_done.acquire(); B_done.release() # spawn B B_done.signal() # ... some time later ... ... and B exits ... # B_done.wait() # # Because B_done was in the acquire'd state at the time B was spawned, # B's attempt to acquire B_done can't succeed until A has done its # B_done.wait() (which releases B_done). So B's B_done.signal() is # guaranteed to be seen by the .wait(). Without the lock trick, B # may signal before A .waits, and then A would wait forever. # # BARRIERS # # A barrier object is created via # import this_module # your_barrier = this_module.barrier(num_threads) # # Methods: # .enter() # the thread blocks until num_threads threads in all have done # .enter(). Then the num_threads threads that .enter'ed resume, # and the barrier resets to capture the next num_threads threads # that .enter it. # # EVENTS # # An event object is created via # import this_module # your_event = this_module.event() # # An event has two states, `posted' and `cleared'. An event is # created in the cleared state. # # Methods: # # .post() # Put the event in the posted state, and resume all threads # .wait'ing on the event (if any). # # .clear() # Put the event in the cleared state. # # .is_posted() # Returns 0 if the event is in the cleared state, or 1 if the event # is in the posted state. # # .wait() # If the event is in the posted state, returns immediately. # If the event is in the cleared state, blocks the calling thread # until the event is .post'ed by another thread. # # Note that an event, once posted, remains posted until explicitly # cleared. Relative to conditions, this is both the strength & weakness # of events. It's a strength because the .post'ing thread doesn't have to # worry about whether the threads it's trying to communicate with have # already done a .wait (a condition .signal is seen only by threads that # do a .wait _prior_ to the .signal; a .signal does not persist). But # it's a weakness because .clear'ing an event is error-prone: it's easy # to mistakenly .clear an event before all the threads you intended to # see the event get around to .wait'ing on it. But so long as you don't # need to .clear an event, events are easy to use safely. # # SEMAPHORES # # A semaphore object is created via # import this_module # your_semaphore = this_module.semaphore(count=1) # # A semaphore has an integer count associated with it. The initial value # of the count is specified by the optional argument (which defaults to # 1) passed to the semaphore constructor. # # Methods: # # .p() # If the semaphore's count is greater than 0, decrements the count # by 1 and returns. # Else if the semaphore's count is 0, blocks the calling thread # until a subsequent .v() increases the count. When that happens, # the count will be decremented by 1 and the calling thread resumed. # # .v() # Increments the semaphore's count by 1, and wakes up a thread (if # any) blocked by a .p(). It's an (detected) error for a .v() to # increase the semaphore's count to a value larger than the initial # count. # # MULTIPLE-READER SINGLE-WRITER LOCKS # # A mrsw lock is created via # import this_module # your_mrsw_lock = this_module.mrsw() # # This kind of lock is often useful with complex shared data structures. # The object lets any number of "readers" proceed, so long as no thread # wishes to "write". When a (one or more) thread declares its intention # to "write" (e.g., to update a shared structure), all current readers # are allowed to finish, and then a writer gets exclusive access; all # other readers & writers are blocked until the current writer completes. # Finally, if some thread is waiting to write and another is waiting to # read, the writer takes precedence. # # Methods: # # .read_in() # If no thread is writing or waiting to write, returns immediately. # Else blocks until no thread is writing or waiting to write. So # long as some thread has completed a .read_in but not a .read_out, # writers are blocked. # # .read_out() # Use sometime after a .read_in to declare that the thread is done # reading. When all threads complete reading, a writer can proceed. # # .write_in() # If no thread is writing (has completed a .write_in, but hasn't yet # done a .write_out) or reading (similarly), returns immediately. # Else blocks the calling thread, and threads waiting to read, until # the current writer completes writing or all the current readers # complete reading; if then more than one thread is waiting to # write, one of them is allowed to proceed, but which one is not # specified. # # .write_out() # Use sometime after a .write_in to declare that the thread is done # writing. Then if some other thread is waiting to write, it's # allowed to proceed. Else all threads (if any) waiting to read are # allowed to proceed. # # .write_to_read() # Use instead of a .write_in to declare that the thread is done # writing but wants to continue reading without other writers # intervening. If there are other threads waiting to write, they # are allowed to proceed only if the current thread calls # .read_out; threads waiting to read are only allowed to proceed # if there are no threads waiting to write. (This is a # weakness of the interface!) import thread class condition: def __init__(self, lock=None): # the lock actually used by .acquire() and .release() if lock is None: self.mutex = thread.allocate_lock() else: if hasattr(lock, 'acquire') and \ hasattr(lock, 'release'): self.mutex = lock else: raise TypeError, 'condition constructor requires ' \ 'a lock argument' # lock used to block threads until a signal self.checkout = thread.allocate_lock() self.checkout.acquire() # internal critical-section lock, & the data it protects self.idlock = thread.allocate_lock() self.id = 0 self.waiting = 0 # num waiters subject to current release self.pending = 0 # num waiters awaiting next signal self.torelease = 0 # num waiters to release self.releasing = 0 # 1 iff release is in progress def acquire(self): self.mutex.acquire() def release(self): self.mutex.release() def wait(self): mutex, checkout, idlock = self.mutex, self.checkout, self.idlock if not mutex.locked(): raise ValueError, \ "condition must be .acquire'd when .wait() invoked" idlock.acquire() myid = self.id self.pending = self.pending + 1 idlock.release() mutex.release() while 1: checkout.acquire(); idlock.acquire() if myid < self.id: break checkout.release(); idlock.release() self.waiting = self.waiting - 1 self.torelease = self.torelease - 1 if self.torelease: checkout.release() else: self.releasing = 0 if self.waiting == self.pending == 0: self.id = 0 idlock.release() mutex.acquire() def signal(self): self.broadcast(1) def broadcast(self, num = -1): if num < -1: raise ValueError, '.broadcast called with num %r' % (num,) if num == 0: return self.idlock.acquire() if self.pending: self.waiting = self.waiting + self.pending self.pending = 0 self.id = self.id + 1 if num == -1: self.torelease = self.waiting else: self.torelease = min( self.waiting, self.torelease + num ) if self.torelease and not self.releasing: self.releasing = 1 self.checkout.release() self.idlock.release() class barrier: def __init__(self, n): self.n = n self.togo = n self.full = condition() def enter(self): full = self.full full.acquire() self.togo = self.togo - 1 if self.togo: full.wait() else: self.togo = self.n full.broadcast() full.release() class event: def __init__(self): self.state = 0 self.posted = condition() def post(self): self.posted.acquire() self.state = 1 self.posted.broadcast() self.posted.release() def clear(self): self.posted.acquire() self.state = 0 self.posted.release() def is_posted(self): self.posted.acquire() answer = self.state self.posted.release() return answer def wait(self): self.posted.acquire() if not self.state: self.posted.wait() self.posted.release() class semaphore: def __init__(self, count=1): if count <= 0: raise ValueError, 'semaphore count %d; must be >= 1' % count self.count = count self.maxcount = count self.nonzero = condition() def p(self): self.nonzero.acquire() while self.count == 0: self.nonzero.wait() self.count = self.count - 1 self.nonzero.release() def v(self): self.nonzero.acquire() if self.count == self.maxcount: raise ValueError, '.v() tried to raise semaphore count above ' \ 'initial value %r' % self.maxcount self.count = self.count + 1 self.nonzero.signal() self.nonzero.release() class mrsw: def __init__(self): # critical-section lock & the data it protects self.rwOK = thread.allocate_lock() self.nr = 0 # number readers actively reading (not just waiting) self.nw = 0 # number writers either waiting to write or writing self.writing = 0 # 1 iff some thread is writing # conditions self.readOK = condition(self.rwOK) # OK to unblock readers self.writeOK = condition(self.rwOK) # OK to unblock writers def read_in(self): self.rwOK.acquire() while self.nw: self.readOK.wait() self.nr = self.nr + 1 self.rwOK.release() def read_out(self): self.rwOK.acquire() if self.nr <= 0: raise ValueError, \ '.read_out() invoked without an active reader' self.nr = self.nr - 1 if self.nr == 0: self.writeOK.signal() self.rwOK.release() def write_in(self): self.rwOK.acquire() self.nw = self.nw + 1 while self.writing or self.nr: self.writeOK.wait() self.writing = 1 self.rwOK.release() def write_out(self): self.rwOK.acquire() if not self.writing: raise ValueError, \ '.write_out() invoked without an active writer' self.writing = 0 self.nw = self.nw - 1 if self.nw: self.writeOK.signal() else: self.readOK.broadcast() self.rwOK.release() def write_to_read(self): self.rwOK.acquire() if not self.writing: raise ValueError, \ '.write_to_read() invoked without an active writer' self.writing = 0 self.nw = self.nw - 1 self.nr = self.nr + 1 if not self.nw: self.readOK.broadcast() self.rwOK.release() # The rest of the file is a test case, that runs a number of parallelized # quicksorts in parallel. If it works, you'll get about 600 lines of # tracing output, with a line like # test passed! 209 threads created in all # as the last line. The content and order of preceding lines will # vary across runs. def _new_thread(func, *args): global TID tid.acquire(); id = TID = TID+1; tid.release() io.acquire(); alive.append(id); \ print 'starting thread', id, '--', len(alive), 'alive'; \ io.release() thread.start_new_thread( func, (id,) + args ) def _qsort(tid, a, l, r, finished): # sort a[l:r]; post finished when done io.acquire(); print 'thread', tid, 'qsort', l, r; io.release() if r-l > 1: pivot = a[l] j = l+1 # make a[l:j] <= pivot, and a[j:r] > pivot for i in range(j, r): if a[i] <= pivot: a[j], a[i] = a[i], a[j] j = j + 1 a[l], a[j-1] = a[j-1], pivot l_subarray_sorted = event() r_subarray_sorted = event() _new_thread(_qsort, a, l, j-1, l_subarray_sorted) _new_thread(_qsort, a, j, r, r_subarray_sorted) l_subarray_sorted.wait() r_subarray_sorted.wait() io.acquire(); print 'thread', tid, 'qsort done'; \ alive.remove(tid); io.release() finished.post() def _randarray(tid, a, finished): io.acquire(); print 'thread', tid, 'randomizing array'; \ io.release() for i in range(1, len(a)): wh.acquire(); j = randint(0,i); wh.release() a[i], a[j] = a[j], a[i] io.acquire(); print 'thread', tid, 'randomizing done'; \ alive.remove(tid); io.release() finished.post() def _check_sort(a): if a != range(len(a)): raise ValueError, ('a not sorted', a) def _run_one_sort(tid, a, bar, done): # randomize a, and quicksort it # for variety, all the threads running this enter a barrier # at the end, and post `done' after the barrier exits io.acquire(); print 'thread', tid, 'randomizing', a; \ io.release() finished = event() _new_thread(_randarray, a, finished) finished.wait() io.acquire(); print 'thread', tid, 'sorting', a; io.release() finished.clear() _new_thread(_qsort, a, 0, len(a), finished) finished.wait() _check_sort(a) io.acquire(); print 'thread', tid, 'entering barrier'; \ io.release() bar.enter() io.acquire(); print 'thread', tid, 'leaving barrier'; \ io.release() io.acquire(); alive.remove(tid); io.release() bar.enter() # make sure they've all removed themselves from alive ## before 'done' is posted bar.enter() # just to be cruel done.post() def test(): global TID, tid, io, wh, randint, alive import random randint = random.randint TID = 0 # thread ID (1, 2, ...) tid = thread.allocate_lock() # for changing TID io = thread.allocate_lock() # for printing, and 'alive' wh = thread.allocate_lock() # for calls to random alive = [] # IDs of active threads NSORTS = 5 arrays = [] for i in range(NSORTS): arrays.append( range( (i+1)*10 ) ) bar = barrier(NSORTS) finished = event() for i in range(NSORTS): _new_thread(_run_one_sort, arrays[i], bar, finished) finished.wait() print 'all threads done, and checking results ...' if alive: raise ValueError, ('threads still alive at end', alive) for i in range(NSORTS): a = arrays[i] if len(a) != (i+1)*10: raise ValueError, ('length of array', i, 'screwed up') _check_sort(a) print 'test passed!', TID, 'threads created in all' if __name__ == '__main__': test() # end of module PK%L]B} 6AAthreads/squasher.pycnu[ ^c@sdZddlTdZdZdZdZdZddlZeZej eeZ ej eZ ej eZ ej eZ ej eZeje d GHdS( s} d = sqrt(b**2 - 4*a*c) twoa = 2*a L = -b/twoa R = d/twoa A1 = L + R A2 = L - R i(t*cCs1x*tj|dD]}tjt|qWdS(Ns (tstringt splitfieldstcottrantcodisassembler(ttexttline((s-/usr/lib64/python2.7/Demo/threads/squasher.pytgetline-scCs[xTtjt}x.tt|D]}tjt||q%WtjtdqWdS(Nt;(RRt cogetlinetrangetlent cosquasher(tcardti((s-/usr/lib64/python2.7/Demo/threads/squasher.pyt disassembler1s cCsxtjt}|dkr[tjt}|dkrBd}q[tjt||}n|dkrx#tjt}|dkrjPqjqjWtjtd|}ntjt|qWdS(NRt^s t (RRRt coassembler(tchtch2((s-/usr/lib64/python2.7/Demo/threads/squasher.pytsquasher8s        cCsd}xXtjt}|dkr(Pnt|dkrStjt|d}n||}q W|ddt|}tjt|tjdS(NtsiHR(RRR R t coputlinetkill(RR((s-/usr/lib64/python2.7/Demo/threads/squasher.pyt assemblerKs  cCsxtjt}|GHqWdS(N(RRR(R((s-/usr/lib64/python2.7/Demo/threads/squasher.pytputlineYsNtdone(ttestt CoroutineRRRRRRRtcreateR RRRR R(((s-/usr/lib64/python2.7/Demo/threads/squasher.pyts         PK%L]+wwthreads/find.pynu[# A parallelized "find(1)" using the thread module. # This demonstrates the use of a work queue and worker threads. # It really does do more stats/sec when using multiple threads, # although the improvement is only about 20-30 percent. # (That was 8 years ago. In 2002, on Linux, I can't measure # a speedup. :-( ) # I'm too lazy to write a command line parser for the full find(1) # command line syntax, so the predicate it searches for is wired-in, # see function selector() below. (It currently searches for files with # world write permission.) # Usage: parfind.py [-w nworkers] [directory] ... # Default nworkers is 4 import sys import getopt import string import time import os from stat import * import thread # Work queue class. Usage: # wq = WorkQ() # wq.addwork(func, (arg1, arg2, ...)) # one or more calls # wq.run(nworkers) # The work is done when wq.run() completes. # The function calls executed by the workers may add more work. # Don't use keyboard interrupts! class WorkQ: # Invariants: # - busy and work are only modified when mutex is locked # - len(work) is the number of jobs ready to be taken # - busy is the number of jobs being done # - todo is locked iff there is no work and somebody is busy def __init__(self): self.mutex = thread.allocate() self.todo = thread.allocate() self.todo.acquire() self.work = [] self.busy = 0 def addwork(self, func, args): job = (func, args) self.mutex.acquire() self.work.append(job) self.mutex.release() if len(self.work) == 1: self.todo.release() def _getwork(self): self.todo.acquire() self.mutex.acquire() if self.busy == 0 and len(self.work) == 0: self.mutex.release() self.todo.release() return None job = self.work[0] del self.work[0] self.busy = self.busy + 1 self.mutex.release() if len(self.work) > 0: self.todo.release() return job def _donework(self): self.mutex.acquire() self.busy = self.busy - 1 if self.busy == 0 and len(self.work) == 0: self.todo.release() self.mutex.release() def _worker(self): time.sleep(0.00001) # Let other threads run while 1: job = self._getwork() if not job: break func, args = job apply(func, args) self._donework() def run(self, nworkers): if not self.work: return # Nothing to do for i in range(nworkers-1): thread.start_new(self._worker, ()) self._worker() self.todo.acquire() # Main program def main(): nworkers = 4 opts, args = getopt.getopt(sys.argv[1:], '-w:') for opt, arg in opts: if opt == '-w': nworkers = string.atoi(arg) if not args: args = [os.curdir] wq = WorkQ() for dir in args: wq.addwork(find, (dir, selector, wq)) t1 = time.time() wq.run(nworkers) t2 = time.time() sys.stderr.write('Total time %r sec.\n' % (t2-t1)) # The predicate -- defines what files we look for. # Feel free to change this to suit your purpose def selector(dir, name, fullname, stat): # Look for world writable files that are not symlinks return (stat[ST_MODE] & 0002) != 0 and not S_ISLNK(stat[ST_MODE]) # The find procedure -- calls wq.addwork() for subdirectories def find(dir, pred, wq): try: names = os.listdir(dir) except os.error, msg: print repr(dir), ':', msg return for name in names: if name not in (os.curdir, os.pardir): fullname = os.path.join(dir, name) try: stat = os.lstat(fullname) except os.error, msg: print repr(fullname), ':', msg continue if pred(dir, name, fullname, stat): print fullname if S_ISDIR(stat[ST_MODE]): if not os.path.ismount(fullname): wq.addwork(find, (fullname, pred, wq)) # Call the main program main() PK%L]7\threads/fcmp.pynu[# Coroutine example: controlling multiple instances of a single function from Coroutine import * # fringe visits a nested list in inorder, and detaches for each non-list # element; raises EarlyExit after the list is exhausted def fringe(co, list): for x in list: if type(x) is type([]): fringe(co, x) else: co.back(x) def printinorder(list): co = Coroutine() f = co.create(fringe, co, list) try: while 1: print co.tran(f), except EarlyExit: pass print printinorder([1,2,3]) # 1 2 3 printinorder([[[[1,[2]]],3]]) # ditto x = [0, 1, [2, [3]], [4,5], [[[6]]] ] printinorder(x) # 0 1 2 3 4 5 6 # fcmp lexicographically compares the fringes of two nested lists def fcmp(l1, l2): co1 = Coroutine(); f1 = co1.create(fringe, co1, l1) co2 = Coroutine(); f2 = co2.create(fringe, co2, l2) while 1: try: v1 = co1.tran(f1) except EarlyExit: try: v2 = co2.tran(f2) except EarlyExit: return 0 co2.kill() return -1 try: v2 = co2.tran(f2) except EarlyExit: co1.kill() return 1 if v1 != v2: co1.kill(); co2.kill() return cmp(v1,v2) print fcmp(range(7), x) # 0; fringes are equal print fcmp(range(6), x) # -1; 1st list ends early print fcmp(x, range(6)) # 1; 2nd list ends early print fcmp(range(8), x) # 1; 2nd list ends early print fcmp(x, range(8)) # -1; 1st list ends early print fcmp([1,[[2],8]], [[[1],2],8]) # 0 print fcmp([1,[[3],8]], [[[1],2],8]) # 1 print fcmp([1,[[2],8]], [[[1],2],9]) # -1 # end of example PK%L]Stix/tixwidgets.pynu[# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- # # $Id$ # # tixwidgets.py -- # # For Tix, see http://tix.sourceforge.net # # This is a demo program of some of the Tix widgets available in Python. # If you have installed Python & Tix properly, you can execute this as # # % python tixwidgets.py # import os, os.path, sys, Tix from Tkconstants import * import traceback, tkMessageBox TCL_DONT_WAIT = 1<<1 TCL_WINDOW_EVENTS = 1<<2 TCL_FILE_EVENTS = 1<<3 TCL_TIMER_EVENTS = 1<<4 TCL_IDLE_EVENTS = 1<<5 TCL_ALL_EVENTS = 0 class Demo: def __init__(self, top): self.root = top self.exit = -1 self.dir = None # script directory self.balloon = None # balloon widget self.useBalloons = Tix.StringVar() self.useBalloons.set('0') self.statusbar = None # status bar widget self.welmsg = None # Msg widget self.welfont = '' # font name self.welsize = '' # font size progname = sys.argv[0] dirname = os.path.dirname(progname) if dirname and dirname != os.curdir: self.dir = dirname index = -1 for i in range(len(sys.path)): p = sys.path[i] if p in ("", os.curdir): index = i if index >= 0: sys.path[index] = dirname else: sys.path.insert(0, dirname) else: self.dir = os.getcwd() sys.path.insert(0, self.dir+'/samples') def MkMainMenu(self): top = self.root w = Tix.Frame(top, bd=2, relief=RAISED) file = Tix.Menubutton(w, text='File', underline=0, takefocus=0) help = Tix.Menubutton(w, text='Help', underline=0, takefocus=0) file.pack(side=LEFT) help.pack(side=RIGHT) fm = Tix.Menu(file, tearoff=0) file['menu'] = fm hm = Tix.Menu(help, tearoff=0) help['menu'] = hm fm.add_command(label='Exit', underline=1, command = lambda self=self: self.quitcmd () ) hm.add_checkbutton(label='BalloonHelp', underline=0, command=ToggleHelp, variable=self.useBalloons) # The trace variable option doesn't seem to work, instead I use 'command' #apply(w.tk.call, ('trace', 'variable', self.useBalloons, 'w', # ToggleHelp)) return w def MkMainNotebook(self): top = self.root w = Tix.NoteBook(top, ipadx=5, ipady=5, options=""" tagPadX 6 tagPadY 4 borderWidth 2 """) # This may be required if there is no *Background option top['bg'] = w['bg'] w.add('wel', label='Welcome', underline=0, createcmd=lambda w=w, name='wel': MkWelcome(w, name)) w.add('cho', label='Choosers', underline=0, createcmd=lambda w=w, name='cho': MkChoosers(w, name)) w.add('scr', label='Scrolled Widgets', underline=0, createcmd=lambda w=w, name='scr': MkScroll(w, name)) w.add('mgr', label='Manager Widgets', underline=0, createcmd=lambda w=w, name='mgr': MkManager(w, name)) w.add('dir', label='Directory List', underline=0, createcmd=lambda w=w, name='dir': MkDirList(w, name)) w.add('exp', label='Run Sample Programs', underline=0, createcmd=lambda w=w, name='exp': MkSample(w, name)) return w def MkMainStatus(self): global demo top = self.root w = Tix.Frame(top, relief=Tix.RAISED, bd=1) demo.statusbar = Tix.Label(w, relief=Tix.SUNKEN, bd=1) demo.statusbar.form(padx=3, pady=3, left=0, right='%70') return w def build(self): root = self.root z = root.winfo_toplevel() z.wm_title('Tix Widget Demonstration') if z.winfo_screenwidth() <= 800: z.geometry('790x590+10+10') else: z.geometry('890x640+10+10') demo.balloon = Tix.Balloon(root) frame1 = self.MkMainMenu() frame2 = self.MkMainNotebook() frame3 = self.MkMainStatus() frame1.pack(side=TOP, fill=X) frame3.pack(side=BOTTOM, fill=X) frame2.pack(side=TOP, expand=1, fill=BOTH, padx=4, pady=4) demo.balloon['statusbar'] = demo.statusbar z.wm_protocol("WM_DELETE_WINDOW", lambda self=self: self.quitcmd()) # To show Tcl errors - uncomment this to see the listbox bug. # Tkinter defines a Tcl tkerror procedure that in effect # silences all background Tcl error reporting. # root.tk.eval('if {[info commands tkerror] != ""} {rename tkerror pytkerror}') def quitcmd (self): """Quit our mainloop. It is up to you to call root.destroy() after.""" self.exit = 0 def loop(self): """This is an explict replacement for _tkinter mainloop() It lets you catch keyboard interrupts easier, and avoids the 20 msec. dead sleep() which burns a constant CPU.""" while self.exit < 0: # There are 2 whiles here. The outer one lets you continue # after a ^C interrupt. try: # This is the replacement for _tkinter mainloop() # It blocks waiting for the next Tcl event using select. while self.exit < 0: self.root.tk.dooneevent(TCL_ALL_EVENTS) except SystemExit: # Tkinter uses SystemExit to exit #print 'Exit' self.exit = 1 return except KeyboardInterrupt: if tkMessageBox.askquestion ('Interrupt', 'Really Quit?') == 'yes': # self.tk.eval('exit') self.exit = 1 return continue except: # Otherwise it's some other error - be nice and say why t, v, tb = sys.exc_info() text = "" for line in traceback.format_exception(t,v,tb): text += line + '\n' try: tkMessageBox.showerror ('Error', text) except: pass self.exit = 1 raise SystemExit, 1 def destroy (self): self.root.destroy() def RunMain(root): global demo demo = Demo(root) demo.build() demo.loop() demo.destroy() # Tabs def MkWelcome(nb, name): w = nb.page(name) bar = MkWelcomeBar(w) text = MkWelcomeText(w) bar.pack(side=TOP, fill=X, padx=2, pady=2) text.pack(side=TOP, fill=BOTH, expand=1) def MkWelcomeBar(top): global demo w = Tix.Frame(top, bd=2, relief=Tix.GROOVE) b1 = Tix.ComboBox(w, command=lambda w=top: MainTextFont(w)) b2 = Tix.ComboBox(w, command=lambda w=top: MainTextFont(w)) b1.entry['width'] = 15 b1.slistbox.listbox['height'] = 3 b2.entry['width'] = 4 b2.slistbox.listbox['height'] = 3 demo.welfont = b1 demo.welsize = b2 b1.insert(Tix.END, 'Courier') b1.insert(Tix.END, 'Helvetica') b1.insert(Tix.END, 'Lucida') b1.insert(Tix.END, 'Times Roman') b2.insert(Tix.END, '8') b2.insert(Tix.END, '10') b2.insert(Tix.END, '12') b2.insert(Tix.END, '14') b2.insert(Tix.END, '18') b1.pick(1) b2.pick(3) b1.pack(side=Tix.LEFT, padx=4, pady=4) b2.pack(side=Tix.LEFT, padx=4, pady=4) demo.balloon.bind_widget(b1, msg='Choose\na font', statusmsg='Choose a font for this page') demo.balloon.bind_widget(b2, msg='Point size', statusmsg='Choose the font size for this page') return w def MkWelcomeText(top): global demo w = Tix.ScrolledWindow(top, scrollbar='auto') win = w.window text = 'Welcome to TIX in Python' title = Tix.Label(win, bd=0, width=30, anchor=Tix.N, text=text) msg = Tix.Message(win, bd=0, width=400, anchor=Tix.N, text='Tix is a set of mega-widgets based on TK. This program \ demonstrates the widgets in the Tix widget set. You can choose the pages \ in this window to look at the corresponding widgets. \n\n\ To quit this program, choose the "File | Exit" command.\n\n\ For more information, see http://tix.sourceforge.net.') title.pack(expand=1, fill=Tix.BOTH, padx=10, pady=10) msg.pack(expand=1, fill=Tix.BOTH, padx=10, pady=10) demo.welmsg = msg return w def MainTextFont(w): global demo if not demo.welmsg: return font = demo.welfont['value'] point = demo.welsize['value'] if font == 'Times Roman': font = 'times' fontstr = '%s %s' % (font, point) demo.welmsg['font'] = fontstr def ToggleHelp(): if demo.useBalloons.get() == '1': demo.balloon['state'] = 'both' else: demo.balloon['state'] = 'none' def MkChoosers(nb, name): w = nb.page(name) options = "label.padX 4" til = Tix.LabelFrame(w, label='Chooser Widgets', options=options) cbx = Tix.LabelFrame(w, label='tixComboBox', options=options) ctl = Tix.LabelFrame(w, label='tixControl', options=options) sel = Tix.LabelFrame(w, label='tixSelect', options=options) opt = Tix.LabelFrame(w, label='tixOptionMenu', options=options) fil = Tix.LabelFrame(w, label='tixFileEntry', options=options) fbx = Tix.LabelFrame(w, label='tixFileSelectBox', options=options) tbr = Tix.LabelFrame(w, label='Tool Bar', options=options) MkTitle(til.frame) MkCombo(cbx.frame) MkControl(ctl.frame) MkSelect(sel.frame) MkOptMenu(opt.frame) MkFileEnt(fil.frame) MkFileBox(fbx.frame) MkToolBar(tbr.frame) # First column: comBox and selector cbx.form(top=0, left=0, right='%33') sel.form(left=0, right='&'+str(cbx), top=cbx) opt.form(left=0, right='&'+str(cbx), top=sel, bottom=-1) # Second column: title .. etc til.form(left=cbx, top=0,right='%66') ctl.form(left=cbx, right='&'+str(til), top=til) fil.form(left=cbx, right='&'+str(til), top=ctl) tbr.form(left=cbx, right='&'+str(til), top=fil, bottom=-1) # # Third column: file selection fbx.form(right=-1, top=0, left='%66') def MkCombo(w): options="label.width %d label.anchor %s entry.width %d" % (10, Tix.E, 14) static = Tix.ComboBox(w, label='Static', editable=0, options=options) editable = Tix.ComboBox(w, label='Editable', editable=1, options=options) history = Tix.ComboBox(w, label='History', editable=1, history=1, anchor=Tix.E, options=options) static.insert(Tix.END, 'January') static.insert(Tix.END, 'February') static.insert(Tix.END, 'March') static.insert(Tix.END, 'April') static.insert(Tix.END, 'May') static.insert(Tix.END, 'June') static.insert(Tix.END, 'July') static.insert(Tix.END, 'August') static.insert(Tix.END, 'September') static.insert(Tix.END, 'October') static.insert(Tix.END, 'November') static.insert(Tix.END, 'December') editable.insert(Tix.END, 'Angola') editable.insert(Tix.END, 'Bangladesh') editable.insert(Tix.END, 'China') editable.insert(Tix.END, 'Denmark') editable.insert(Tix.END, 'Ecuador') history.insert(Tix.END, '/usr/bin/ksh') history.insert(Tix.END, '/usr/local/lib/python') history.insert(Tix.END, '/var/adm') static.pack(side=Tix.TOP, padx=5, pady=3) editable.pack(side=Tix.TOP, padx=5, pady=3) history.pack(side=Tix.TOP, padx=5, pady=3) states = ['Bengal', 'Delhi', 'Karnataka', 'Tamil Nadu'] def spin_cmd(w, inc): idx = states.index(demo_spintxt.get()) + inc if idx < 0: idx = len(states) - 1 elif idx >= len(states): idx = 0 # following doesn't work. # return states[idx] demo_spintxt.set(states[idx]) # this works def spin_validate(w): global states, demo_spintxt try: i = states.index(demo_spintxt.get()) except ValueError: return states[0] return states[i] # why this procedure works as opposed to the previous one beats me. def MkControl(w): global demo_spintxt options="label.width %d label.anchor %s entry.width %d" % (10, Tix.E, 13) demo_spintxt = Tix.StringVar() demo_spintxt.set(states[0]) simple = Tix.Control(w, label='Numbers', options=options) spintxt = Tix.Control(w, label='States', variable=demo_spintxt, options=options) spintxt['incrcmd'] = lambda w=spintxt: spin_cmd(w, 1) spintxt['decrcmd'] = lambda w=spintxt: spin_cmd(w, -1) spintxt['validatecmd'] = lambda w=spintxt: spin_validate(w) simple.pack(side=Tix.TOP, padx=5, pady=3) spintxt.pack(side=Tix.TOP, padx=5, pady=3) def MkSelect(w): options = "label.anchor %s" % Tix.CENTER sel1 = Tix.Select(w, label='Mere Mortals', allowzero=1, radio=1, orientation=Tix.VERTICAL, labelside=Tix.TOP, options=options) sel2 = Tix.Select(w, label='Geeks', allowzero=1, radio=0, orientation=Tix.VERTICAL, labelside= Tix.TOP, options=options) sel1.add('eat', text='Eat') sel1.add('work', text='Work') sel1.add('play', text='Play') sel1.add('party', text='Party') sel1.add('sleep', text='Sleep') sel2.add('eat', text='Eat') sel2.add('prog1', text='Program') sel2.add('prog2', text='Program') sel2.add('prog3', text='Program') sel2.add('sleep', text='Sleep') sel1.pack(side=Tix.LEFT, padx=5, pady=3, fill=Tix.X) sel2.pack(side=Tix.LEFT, padx=5, pady=3, fill=Tix.X) def MkOptMenu(w): options='menubutton.width 15 label.anchor %s' % Tix.E m = Tix.OptionMenu(w, label='File Format : ', options=options) m.add_command('text', label='Plain Text') m.add_command('post', label='PostScript') m.add_command('format', label='Formatted Text') m.add_command('html', label='HTML') m.add_command('sep') m.add_command('tex', label='LaTeX') m.add_command('rtf', label='Rich Text Format') m.pack(fill=Tix.X, padx=5, pady=3) def MkFileEnt(w): msg = Tix.Message(w, relief=Tix.FLAT, width=240, anchor=Tix.N, text='Press the "open file" icon button and a TixFileSelectDialog will popup.') ent = Tix.FileEntry(w, label='Select a file : ') msg.pack(side=Tix.TOP, expand=1, fill=Tix.BOTH, padx=3, pady=3) ent.pack(side=Tix.TOP, fill=Tix.X, padx=3, pady=3) def MkFileBox(w): """The FileSelectBox is a Motif-style box with various enhancements. For example, you can adjust the size of the two listboxes and your past selections are recorded. """ msg = Tix.Message(w, relief=Tix.FLAT, width=240, anchor=Tix.N, text='The Tix FileSelectBox is a Motif-style box with various enhancements. For example, you can adjust the size of the two listboxes and your past selections are recorded.') box = Tix.FileSelectBox(w) msg.pack(side=Tix.TOP, expand=1, fill=Tix.BOTH, padx=3, pady=3) box.pack(side=Tix.TOP, fill=Tix.X, padx=3, pady=3) def MkToolBar(w): """The Select widget is also good for arranging buttons in a tool bar. """ global demo options='frame.borderWidth 1' msg = Tix.Message(w, relief=Tix.FLAT, width=240, anchor=Tix.N, text='The Select widget is also good for arranging buttons in a tool bar.') bar = Tix.Frame(w, bd=2, relief=Tix.RAISED) font = Tix.Select(w, allowzero=1, radio=0, label='', options=options) para = Tix.Select(w, allowzero=0, radio=1, label='', options=options) font.add('bold', bitmap='@' + demo.dir + '/bitmaps/bold.xbm') font.add('italic', bitmap='@' + demo.dir + '/bitmaps/italic.xbm') font.add('underline', bitmap='@' + demo.dir + '/bitmaps/underline.xbm') font.add('capital', bitmap='@' + demo.dir + '/bitmaps/capital.xbm') para.add('left', bitmap='@' + demo.dir + '/bitmaps/leftj.xbm') para.add('right', bitmap='@' + demo.dir + '/bitmaps/rightj.xbm') para.add('center', bitmap='@' + demo.dir + '/bitmaps/centerj.xbm') para.add('justify', bitmap='@' + demo.dir + '/bitmaps/justify.xbm') msg.pack(side=Tix.TOP, expand=1, fill=Tix.BOTH, padx=3, pady=3) bar.pack(side=Tix.TOP, fill=Tix.X, padx=3, pady=3) font.pack({'in':bar}, side=Tix.LEFT, padx=3, pady=3) para.pack({'in':bar}, side=Tix.LEFT, padx=3, pady=3) def MkTitle(w): msg = Tix.Message(w, relief=Tix.FLAT, width=240, anchor=Tix.N, text='There are many types of "chooser" widgets that allow the user to input different types of information') msg.pack(side=Tix.TOP, expand=1, fill=Tix.BOTH, padx=3, pady=3) def MkScroll(nb, name): w = nb.page(name) options='label.padX 4' sls = Tix.LabelFrame(w, label='Tix.ScrolledListBox', options=options) swn = Tix.LabelFrame(w, label='Tix.ScrolledWindow', options=options) stx = Tix.LabelFrame(w, label='Tix.ScrolledText', options=options) MkSList(sls.frame) MkSWindow(swn.frame) MkSText(stx.frame) sls.form(top=0, left=0, right='%33', bottom=-1) swn.form(top=0, left=sls, right='%66', bottom=-1) stx.form(top=0, left=swn, right=-1, bottom=-1) def MkSList(w): """This TixScrolledListBox is configured so that it uses scrollbars only when it is necessary. Use the handles to resize the listbox and watch the scrollbars automatically appear and disappear. """ top = Tix.Frame(w, width=300, height=330) bot = Tix.Frame(w) msg = Tix.Message(top, relief=Tix.FLAT, width=200, anchor=Tix.N, text='This TixScrolledListBox is configured so that it uses scrollbars only when it is necessary. Use the handles to resize the listbox and watch the scrollbars automatically appear and disappear.') list = Tix.ScrolledListBox(top, scrollbar='auto') list.place(x=50, y=150, width=120, height=80) list.listbox.insert(Tix.END, 'Alabama') list.listbox.insert(Tix.END, 'California') list.listbox.insert(Tix.END, 'Montana') list.listbox.insert(Tix.END, 'New Jersey') list.listbox.insert(Tix.END, 'New York') list.listbox.insert(Tix.END, 'Pennsylvania') list.listbox.insert(Tix.END, 'Washington') rh = Tix.ResizeHandle(top, bg='black', relief=Tix.RAISED, handlesize=8, gridded=1, minwidth=50, minheight=30) btn = Tix.Button(bot, text='Reset', command=lambda w=rh, x=list: SList_reset(w,x)) top.propagate(0) msg.pack(fill=Tix.X) btn.pack(anchor=Tix.CENTER) top.pack(expand=1, fill=Tix.BOTH) bot.pack(fill=Tix.BOTH) list.bind('', func=lambda arg=0, rh=rh, list=list: list.tk.call('tixDoWhenIdle', str(rh), 'attachwidget', str(list))) def SList_reset(rh, list): list.place(x=50, y=150, width=120, height=80) list.update() rh.attach_widget(list) def MkSWindow(w): """The ScrolledWindow widget allows you to scroll any kind of Tk widget. It is more versatile than a scrolled canvas widget. """ global demo text = 'The Tix ScrolledWindow widget allows you to scroll any kind of Tk widget. It is more versatile than a scrolled canvas widget.' file = os.path.join(demo.dir, 'bitmaps', 'tix.gif') if not os.path.isfile(file): text += ' (Image missing)' top = Tix.Frame(w, width=330, height=330) bot = Tix.Frame(w) msg = Tix.Message(top, relief=Tix.FLAT, width=200, anchor=Tix.N, text=text) win = Tix.ScrolledWindow(top, scrollbar='auto') image1 = win.window.image_create('photo', file=file) lbl = Tix.Label(win.window, image=image1) lbl.pack(expand=1, fill=Tix.BOTH) win.place(x=30, y=150, width=190, height=120) rh = Tix.ResizeHandle(top, bg='black', relief=Tix.RAISED, handlesize=8, gridded=1, minwidth=50, minheight=30) btn = Tix.Button(bot, text='Reset', command=lambda w=rh, x=win: SWindow_reset(w,x)) top.propagate(0) msg.pack(fill=Tix.X) btn.pack(anchor=Tix.CENTER) top.pack(expand=1, fill=Tix.BOTH) bot.pack(fill=Tix.BOTH) win.bind('', func=lambda arg=0, rh=rh, win=win: win.tk.call('tixDoWhenIdle', str(rh), 'attachwidget', str(win))) def SWindow_reset(rh, win): win.place(x=30, y=150, width=190, height=120) win.update() rh.attach_widget(win) def MkSText(w): """The TixScrolledWindow widget allows you to scroll any kind of Tk widget. It is more versatile than a scrolled canvas widget.""" top = Tix.Frame(w, width=330, height=330) bot = Tix.Frame(w) msg = Tix.Message(top, relief=Tix.FLAT, width=200, anchor=Tix.N, text='The Tix ScrolledWindow widget allows you to scroll any kind of Tk widget. It is more versatile than a scrolled canvas widget.') win = Tix.ScrolledText(top, scrollbar='auto') win.text['wrap'] = 'none' win.text.insert(Tix.END, '''When -scrollbar is set to "auto", the scrollbars are shown only when needed. Additional modifiers can be used to force a scrollbar to be shown or hidden. For example, "auto -y" means the horizontal scrollbar should be shown when needed but the vertical scrollbar should always be hidden; "auto +x" means the vertical scrollbar should be shown when needed but the horizontal scrollbar should always be shown, and so on.''' ) win.place(x=30, y=150, width=190, height=100) rh = Tix.ResizeHandle(top, bg='black', relief=Tix.RAISED, handlesize=8, gridded=1, minwidth=50, minheight=30) btn = Tix.Button(bot, text='Reset', command=lambda w=rh, x=win: SText_reset(w,x)) top.propagate(0) msg.pack(fill=Tix.X) btn.pack(anchor=Tix.CENTER) top.pack(expand=1, fill=Tix.BOTH) bot.pack(fill=Tix.BOTH) win.bind('', func=lambda arg=0, rh=rh, win=win: win.tk.call('tixDoWhenIdle', str(rh), 'attachwidget', str(win))) def SText_reset(rh, win): win.place(x=30, y=150, width=190, height=120) win.update() rh.attach_widget(win) def MkManager(nb, name): w = nb.page(name) options='label.padX 4' pane = Tix.LabelFrame(w, label='Tix.PanedWindow', options=options) note = Tix.LabelFrame(w, label='Tix.NoteBook', options=options) MkPanedWindow(pane.frame) MkNoteBook(note.frame) pane.form(top=0, left=0, right=note, bottom=-1) note.form(top=0, right=-1, bottom=-1) def MkPanedWindow(w): """The PanedWindow widget allows the user to interactively manipulate the sizes of several panes. The panes can be arranged either vertically or horizontally. """ msg = Tix.Message(w, relief=Tix.FLAT, width=240, anchor=Tix.N, text='The PanedWindow widget allows the user to interactively manipulate the sizes of several panes. The panes can be arranged either vertically or horizontally.') group = Tix.LabelEntry(w, label='Newsgroup:', options='entry.width 25') group.entry.insert(0,'comp.lang.python') pane = Tix.PanedWindow(w, orientation='vertical') p1 = pane.add('list', min=70, size=100) p2 = pane.add('text', min=70) list = Tix.ScrolledListBox(p1) text = Tix.ScrolledText(p2) list.listbox.insert(Tix.END, " 12324 Re: Tkinter is good for your health") list.listbox.insert(Tix.END, "+ 12325 Re: Tkinter is good for your health") list.listbox.insert(Tix.END, "+ 12326 Re: Tix is even better for your health (Was: Tkinter is good...)") list.listbox.insert(Tix.END, " 12327 Re: Tix is even better for your health (Was: Tkinter is good...)") list.listbox.insert(Tix.END, "+ 12328 Re: Tix is even better for your health (Was: Tkinter is good...)") list.listbox.insert(Tix.END, " 12329 Re: Tix is even better for your health (Was: Tkinter is good...)") list.listbox.insert(Tix.END, "+ 12330 Re: Tix is even better for your health (Was: Tkinter is good...)") text.text['bg'] = list.listbox['bg'] text.text['wrap'] = 'none' text.text.insert(Tix.END, """ Mon, 19 Jun 1995 11:39:52 comp.lang.python Thread 34 of 220 Lines 353 A new way to put text and bitmaps together iNo responses ioi@blue.seas.upenn.edu Ioi K. Lam at University of Pennsylvania Hi, I have implemented a new image type called "compound". It allows you to glue together a bunch of bitmaps, images and text strings together to form a bigger image. Then you can use this image with widgets that support the -image option. For example, you can display a text string together with a bitmap, at the same time, inside a TK button widget. """) list.pack(expand=1, fill=Tix.BOTH, padx=4, pady=6) text.pack(expand=1, fill=Tix.BOTH, padx=4, pady=6) msg.pack(side=Tix.TOP, padx=3, pady=3, fill=Tix.BOTH) group.pack(side=Tix.TOP, padx=3, pady=3, fill=Tix.BOTH) pane.pack(side=Tix.TOP, padx=3, pady=3, fill=Tix.BOTH, expand=1) def MkNoteBook(w): msg = Tix.Message(w, relief=Tix.FLAT, width=240, anchor=Tix.N, text='The NoteBook widget allows you to layout a complex interface into individual pages.') # prefix = Tix.OptionName(w) # if not prefix: prefix = '' # w.option_add('*' + prefix + '*TixNoteBook*tagPadX', 8) options = "entry.width %d label.width %d label.anchor %s" % (10, 18, Tix.E) nb = Tix.NoteBook(w, ipadx=6, ipady=6, options=options) nb.add('hard_disk', label="Hard Disk", underline=0) nb.add('network', label="Network", underline=0) # Frame for the buttons that are present on all pages common = Tix.Frame(nb.hard_disk) common.pack(side=Tix.RIGHT, padx=2, pady=2, fill=Tix.Y) CreateCommonButtons(common) # Widgets belonging only to this page a = Tix.Control(nb.hard_disk, value=12, label='Access Time: ') w = Tix.Control(nb.hard_disk, value=400, label='Write Throughput: ') r = Tix.Control(nb.hard_disk, value=400, label='Read Throughput: ') c = Tix.Control(nb.hard_disk, value=1021, label='Capacity: ') a.pack(side=Tix.TOP, padx=20, pady=2) w.pack(side=Tix.TOP, padx=20, pady=2) r.pack(side=Tix.TOP, padx=20, pady=2) c.pack(side=Tix.TOP, padx=20, pady=2) common = Tix.Frame(nb.network) common.pack(side=Tix.RIGHT, padx=2, pady=2, fill=Tix.Y) CreateCommonButtons(common) a = Tix.Control(nb.network, value=12, label='Access Time: ') w = Tix.Control(nb.network, value=400, label='Write Throughput: ') r = Tix.Control(nb.network, value=400, label='Read Throughput: ') c = Tix.Control(nb.network, value=1021, label='Capacity: ') u = Tix.Control(nb.network, value=10, label='Users: ') a.pack(side=Tix.TOP, padx=20, pady=2) w.pack(side=Tix.TOP, padx=20, pady=2) r.pack(side=Tix.TOP, padx=20, pady=2) c.pack(side=Tix.TOP, padx=20, pady=2) u.pack(side=Tix.TOP, padx=20, pady=2) msg.pack(side=Tix.TOP, padx=3, pady=3, fill=Tix.BOTH) nb.pack(side=Tix.TOP, padx=5, pady=5, fill=Tix.BOTH, expand=1) def CreateCommonButtons(f): ok = Tix.Button(f, text='OK', width = 6) cancel = Tix.Button(f, text='Cancel', width = 6) ok.pack(side=Tix.TOP, padx=2, pady=2) cancel.pack(side=Tix.TOP, padx=2, pady=2) def MkDirList(nb, name): w = nb.page(name) options = "label.padX 4" dir = Tix.LabelFrame(w, label='Tix.DirList', options=options) fsbox = Tix.LabelFrame(w, label='Tix.ExFileSelectBox', options=options) MkDirListWidget(dir.frame) MkExFileWidget(fsbox.frame) dir.form(top=0, left=0, right='%40', bottom=-1) fsbox.form(top=0, left='%40', right=-1, bottom=-1) def MkDirListWidget(w): """The TixDirList widget gives a graphical representation of the file system directory and makes it easy for the user to choose and access directories. """ msg = Tix.Message(w, relief=Tix.FLAT, width=240, anchor=Tix.N, text='The Tix DirList widget gives a graphical representation of the file system directory and makes it easy for the user to choose and access directories.') dirlist = Tix.DirList(w, options='hlist.padY 1 hlist.width 25 hlist.height 16') msg.pack(side=Tix.TOP, expand=1, fill=Tix.BOTH, padx=3, pady=3) dirlist.pack(side=Tix.TOP, padx=3, pady=3) def MkExFileWidget(w): """The TixExFileSelectBox widget is more user friendly than the Motif style FileSelectBox. """ msg = Tix.Message(w, relief=Tix.FLAT, width=240, anchor=Tix.N, text='The Tix ExFileSelectBox widget is more user friendly than the Motif style FileSelectBox.') # There's a bug in the ComboBoxes - the scrolledlistbox is destroyed box = Tix.ExFileSelectBox(w, bd=2, relief=Tix.RAISED) msg.pack(side=Tix.TOP, expand=1, fill=Tix.BOTH, padx=3, pady=3) box.pack(side=Tix.TOP, padx=3, pady=3) ### ### List of all the demos we want to show off comments = {'widget' : 'Widget Demos', 'image' : 'Image Demos'} samples = {'Balloon' : 'Balloon', 'Button Box' : 'BtnBox', 'Combo Box' : 'ComboBox', 'Compound Image' : 'CmpImg', 'Directory List' : 'DirList', 'Directory Tree' : 'DirTree', 'Control' : 'Control', 'Notebook' : 'NoteBook', 'Option Menu' : 'OptMenu', 'Paned Window' : 'PanedWin', 'Popup Menu' : 'PopMenu', 'ScrolledHList (1)' : 'SHList1', 'ScrolledHList (2)' : 'SHList2', 'Tree (dynamic)' : 'Tree' } # There are still a lot of demos to be translated: ## set root { ## {d "File Selectors" file } ## {d "Hierachical ListBox" hlist } ## {d "Tabular ListBox" tlist {c tixTList}} ## {d "Grid Widget" grid {c tixGrid}} ## {d "Manager Widgets" manager } ## {d "Scrolled Widgets" scroll } ## {d "Miscellaneous Widgets" misc } ## {d "Image Types" image } ## } ## ## set image { ## {d "Compound Image" cmpimg } ## {d "XPM Image" xpm {i pixmap}} ## } ## ## set cmpimg { ##done {f "In Buttons" CmpImg.tcl } ## {f "In NoteBook" CmpImg2.tcl } ## {f "Notebook Color Tabs" CmpImg4.tcl } ## {f "Icons" CmpImg3.tcl } ## } ## ## set xpm { ## {f "In Button" Xpm.tcl {i pixmap}} ## {f "In Menu" Xpm1.tcl {i pixmap}} ## } ## ## set file { ##added {f DirList DirList.tcl } ##added {f DirTree DirTree.tcl } ## {f DirSelectDialog DirDlg.tcl } ## {f ExFileSelectDialog EFileDlg.tcl } ## {f FileSelectDialog FileDlg.tcl } ## {f FileEntry FileEnt.tcl } ## } ## ## set hlist { ## {f HList HList1.tcl } ## {f CheckList ChkList.tcl {c tixCheckList}} ##done {f "ScrolledHList (1)" SHList.tcl } ##done {f "ScrolledHList (2)" SHList2.tcl } ##done {f Tree Tree.tcl } ##done {f "Tree (Dynamic)" DynTree.tcl {v win}} ## } ## ## set tlist { ## {f "ScrolledTList (1)" STList1.tcl {c tixTList}} ## {f "ScrolledTList (2)" STList2.tcl {c tixTList}} ## } ## global tcl_platform ## # This demo hangs windows ## if {$tcl_platform(platform) != "windows"} { ##na lappend tlist {f "TList File Viewer" STList3.tcl {c tixTList}} ## } ## ## set grid { ##na {f "Simple Grid" SGrid0.tcl {c tixGrid}} ##na {f "ScrolledGrid" SGrid1.tcl {c tixGrid}} ##na {f "Editable Grid" EditGrid.tcl {c tixGrid}} ## } ## ## set scroll { ## {f ScrolledListBox SListBox.tcl } ## {f ScrolledText SText.tcl } ## {f ScrolledWindow SWindow.tcl } ##na {f "Canvas Object View" CObjView.tcl {c tixCObjView}} ## } ## ## set manager { ## {f ListNoteBook ListNBK.tcl } ##done {f NoteBook NoteBook.tcl } ##done {f PanedWindow PanedWin.tcl } ## } ## ## set misc { ##done {f Balloon Balloon.tcl } ##done {f ButtonBox BtnBox.tcl } ##done {f ComboBox ComboBox.tcl } ##done {f Control Control.tcl } ## {f LabelEntry LabEntry.tcl } ## {f LabelFrame LabFrame.tcl } ## {f Meter Meter.tcl {c tixMeter}} ##done {f OptionMenu OptMenu.tcl } ##done {f PopupMenu PopMenu.tcl } ## {f Select Select.tcl } ## {f StdButtonBox StdBBox.tcl } ## } ## stypes = {} stypes['widget'] = ['Balloon', 'Button Box', 'Combo Box', 'Control', 'Directory List', 'Directory Tree', 'Notebook', 'Option Menu', 'Popup Menu', 'Paned Window', 'ScrolledHList (1)', 'ScrolledHList (2)', 'Tree (dynamic)'] stypes['image'] = ['Compound Image'] def MkSample(nb, name): w = nb.page(name) options = "label.padX 4" pane = Tix.PanedWindow(w, orientation='horizontal') pane.pack(side=Tix.TOP, expand=1, fill=Tix.BOTH) f1 = pane.add('list', expand='1') f2 = pane.add('text', expand='5') f1['relief'] = 'flat' f2['relief'] = 'flat' lab = Tix.LabelFrame(f1, label='Select a sample program:') lab.pack(side=Tix.TOP, expand=1, fill=Tix.BOTH, padx=5, pady=5) lab1 = Tix.LabelFrame(f2, label='Source:') lab1.pack(side=Tix.TOP, expand=1, fill=Tix.BOTH, padx=5, pady=5) slb = Tix.Tree(lab.frame, options='hlist.width 20') slb.pack(side=Tix.TOP, expand=1, fill=Tix.BOTH, padx=5) stext = Tix.ScrolledText(lab1.frame, name='stext') font = root.tk.eval('tix option get fixed_font') stext.text.config(font=font) frame = Tix.Frame(lab1.frame, name='frame') run = Tix.Button(frame, text='Run ...', name='run') view = Tix.Button(frame, text='View Source ...', name='view') run.pack(side=Tix.LEFT, expand=0, fill=Tix.NONE) view.pack(side=Tix.LEFT, expand=0, fill=Tix.NONE) stext.text['bg'] = slb.hlist['bg'] stext.text['state'] = 'disabled' stext.text['wrap'] = 'none' stext.text['width'] = 80 frame.pack(side=Tix.BOTTOM, expand=0, fill=Tix.X, padx=7) stext.pack(side=Tix.TOP, expand=0, fill=Tix.BOTH, padx=7) slb.hlist['separator'] = '.' slb.hlist['width'] = 25 slb.hlist['drawbranch'] = 0 slb.hlist['indent'] = 10 slb.hlist['wideselect'] = 1 slb.hlist['command'] = lambda args=0, w=w,slb=slb,stext=stext,run=run,view=view: Sample_Action(w, slb, stext, run, view, 'run') slb.hlist['browsecmd'] = lambda args=0, w=w,slb=slb,stext=stext,run=run,view=view: Sample_Action(w, slb, stext, run, view, 'browse') run['command'] = lambda args=0, w=w,slb=slb,stext=stext,run=run,view=view: Sample_Action(w, slb, stext, run, view, 'run') view['command'] = lambda args=0, w=w,slb=slb,stext=stext,run=run,view=view: Sample_Action(w, slb, stext, run, view, 'view') for type in ['widget', 'image']: if type != 'widget': x = Tix.Frame(slb.hlist, bd=2, height=2, width=150, relief=Tix.SUNKEN, bg=slb.hlist['bg']) slb.hlist.add_child(itemtype=Tix.WINDOW, window=x, state='disabled') x = slb.hlist.add_child(itemtype=Tix.TEXT, state='disabled', text=comments[type]) for key in stypes[type]: slb.hlist.add_child(x, itemtype=Tix.TEXT, data=key, text=key) slb.hlist.selection_clear() run['state'] = 'disabled' view['state'] = 'disabled' def Sample_Action(w, slb, stext, run, view, action): global demo hlist = slb.hlist anchor = hlist.info_anchor() if not anchor: run['state'] = 'disabled' view['state'] = 'disabled' elif not hlist.info_parent(anchor): # a comment return run['state'] = 'normal' view['state'] = 'normal' key = hlist.info_data(anchor) title = key prog = samples[key] if action == 'run': exec('import ' + prog) w = Tix.Toplevel() w.title(title) rtn = eval(prog + '.RunSample') rtn(w) elif action == 'view': w = Tix.Toplevel() w.title('Source view: ' + title) LoadFile(w, demo.dir + '/samples/' + prog + '.py') elif action == 'browse': ReadFile(stext.text, demo.dir + '/samples/' + prog + '.py') def LoadFile(w, fname): global root b = Tix.Button(w, text='Close', command=w.destroy) t = Tix.ScrolledText(w) # b.form(left=0, bottom=0, padx=4, pady=4) # t.form(left=0, bottom=b, right='-0', top=0) t.pack() b.pack() font = root.tk.eval('tix option get fixed_font') t.text.config(font=font) t.text['bd'] = 2 t.text['wrap'] = 'none' ReadFile(t.text, fname) def ReadFile(w, fname): old_state = w['state'] w['state'] = 'normal' w.delete('0.0', Tix.END) try: f = open(fname) lines = f.readlines() for s in lines: w.insert(Tix.END, s) f.close() finally: # w.see('1.0') w['state'] = old_state if __name__ == '__main__': root = Tix.Tk() RunMain(root) PK%L]gˆ tix/grid.pycnu[ ^c @sddlZddlmZejZejdejeddZejdej fdYZ e eddd d Z e jd ej xMe d D]?Zx6e d D](Ze jeed eeefqWqWejed ddejZejejdS(iN(tpprintttesttnameta_labeltMyGridcBseZdZdZRS(cOs'|j|ds     * PK%L]{̖̖tix/tixwidgets.pyonu[ ^c @sddlZddlZddlZddlZddlTddlZddlZdQZdRZdSZ dTZ dUZ dZ d dVd YZ d Zd Zd ZdZdZdZdZdZddddgadZdZdZdZdZdZdZdZdZd Z d!Z!d"Z"d#Z#d$Z$d%Z%d&Z&d'Z'd(Z(d)Z)d*Z*d+Z+d,Z,d-Z-id.d/6d0d16Z.id2d26d3d46d5d66d7d86d9d:6d;d<6d=d=6d>d?6d@dA6dBdC6dDdE6dFdG6dHdI6dJdK6Z/iZ0d2d4d6d=d:d<d?dAdEdCdGdIdKg e0d/FRt BalloonHelptvariable( RR tFrametRAISEDt MenubuttontpacktLEFTtRIGHTtMenut add_commandtadd_checkbuttont ToggleHelpR (RRtwtfilethelptfmthm((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyt MkMainMenu9s !!    c Cs,|j}tj|dddddd}|d|d<|jddd d d d |dd |jdddd d d |dd|jdddd d d |dd|jdddd d d |dd|jdddd d d |dd|jdddd d d |dd|S(NtipadxitipadytoptionssC tagPadX 6 tagPadY 4 borderWidth 2 tbgtwelR,tWelcomeR&it createcmdcSs t||S(N(t MkWelcome(R=tname((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR0ZRtchotChooserscSs t||S(N(t MkChoosers(R=RK((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR0\RtscrsScrolled WidgetscSs t||S(N(tMkScroll(R=RK((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR0^RtmgrsManager WidgetscSs t||S(N(t MkManager(R=RK((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR0`RRsDirectory ListcSs t||S(N(t MkDirList(R=RK((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR0bRtexpsRun Sample ProgramscSs t||S(N(tMkSample(R=RK((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR0dR(RR tNoteBooktadd(RRR=((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pytMkMainNotebookOs"  c Csq|j}tj|dtjdd}tj|dtjddt_tjjddddddd d |S( NR#R"itpadxitpadytleftitrights%70( RR R3R4tLabeltSUNKENtdemoR tform(RRR=((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyt MkMainStatusgs  !%c Cs|j}|j}|jd|jdkrD|jdn |jdtj|t_|j }|j }|j }|j dt dt|j dtdt|j dt dddtd d d d tjtjd <|jd |ddS(NsTix Widget Demonstrationi s 790x590+10+10s 890x640+10+10R)tfilltexpandiRYiRZR tWM_DELETE_WINDOWcSs |jS(N(R/(R((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR0R(Rtwinfo_topleveltwm_titletwinfo_screenwidthtgeometryR tBalloonR_RRBRXRaR6tTOPtXtBOTTOMtBOTHR t wm_protocol(RRtztframe1tframe2tframe3((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pytbuildps       (cCs d|_dS(s@Quit our mainloop. It is up to you to call root.destroy() after.iN(R(R((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR/scCsx|jdkry-x&|jdkr=|jjjtqWWqtk r\d|_dStk rtjdddkrd|_dSqqt j \}}}d}x+t j |||D]}||d7}qWytj d |WnnXd|_tdqXqWdS( sThis is an explict replacement for _tkinter mainloop() It lets you catch keyboard interrupts easier, and avoids the 20 msec. dead sleep() which burns a constant CPU.iiNt Interrupts Really Quit?tyesRs tError(RRttkt dooneeventtTCL_ALL_EVENTSt SystemExittKeyboardInterruptt tkMessageBoxt askquestionRtexc_infot tracebacktformat_exceptiont showerror(RtttvttbR$tline((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pytloops.     cCs|jjdS(N(Rtdestroy(R((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyRs( t__name__t __module__R!RBRXRaRsR/RR(((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyRs      "cCs.t|atjtjtjdS(N(RR_RsRR(R((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pytRunMains   c Csi|j|}t|}t|}|jdtdtdddd|jdtdtdddS(NR)RbRYiRZRci(tpaget MkWelcomeBart MkWelcomeTextR6RjRkRm(tnbRKR=tbarR$((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyRJs   "cCstj|dddtj}tj|d|d}tj|d|d}d|jdtfunccSs%|jjdt|dt|S(Nt tixDoWhenIdlet attachwidget(RwtcallR(targtrhtlist((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR0sN(R R3RR"RtScrolledListBoxtplaceRRRt ResizeHandleR4tButtont propagateR6RkRRmtbind(R=RtbotRRJRItbtn((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR0s0  " $ c Cs=|jdddddddd|j|j|dS( NR6i2R7iRixRiP(RLtupdatet attach_widget(RIRJ((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyRC s" c Csd}tjjtjdd}tjj|s@|d7}ntj|dddd}tj|}tj|dtj dd d tj d |}tj |d d }|j j dd|}tj|j d|}|jdddtj|jddddddddtj|dddtjdddddd d!d} tj|d d"d#| |d$} |jd%|jdtj| jd tj|jdddtj|jdtj|jd&d'd%| |d(d)S(*sThe ScrolledWindow widget allows you to scroll any kind of Tk widget. It is more versatile than a scrolled canvas widget. s}The Tix ScrolledWindow widget allows you to scroll any kind of Tk widget. It is more versatile than a scrolled canvas widget.tbitmapsstix.gifs (Image missing)RiJRR#iRR$RRtphotoR>timageRciRbR6iR7iiixRFR=R>iR?R@i2RARBR.cSs t||S(N(t SWindow_reset(R=R6((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR0,RisRDcSs%|jjdt|dt|S(NRERF(RwRGR(RHRIR((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR03sN(RRtjoinR_RtisfileR R3RR"RRRt image_createR]R6RmRLRMR4RNRORkRRP( R=R$R>RRQRRtimage1tlblRIRR((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR1s0   " $ c Cs=|jdddddddd|j|j|dS( NR6iR7iRiRix(RLRSRT(RIR((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyRX6s" cCstj|dddd}tj|}tj|dtjdddtjdd}tj|d d }d |jd <|jjtjd |j ddddddddtj |dddtj dddddddd}tj |ddd||d}|j d |jd!tj|jdtj|jd"dd!tj|jd!tj|jd#d$d ||d%d&S('sThe TixScrolledWindow widget allows you to scroll any kind of Tk widget. It is more versatile than a scrolled canvas widget.RiJRR#iRR$s}The Tix ScrolledWindow widget allows you to scroll any kind of Tk widget. It is more versatile than a scrolled canvas widget.RRRtwrapsWhen -scrollbar is set to "auto", the scrollbars are shown only when needed. Additional modifiers can be used to force a scrollbar to be shown or hidden. For example, "auto -y" means the horizontal scrollbar should be shown when needed but the vertical scrollbar should always be hidden; "auto +x" means the vertical scrollbar should be shown when needed but the horizontal scrollbar should always be shown, and so on.R6iR7iiidRFR=R>iR?iR@i2RARBR.cSs t||S(N(t SText_reset(R=R6((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR0VRiRbRcsRDcSs%|jjdt|dt|S(NRERF(RwRGR(RHRIR((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR0\sN(R R3RR"Rt ScrolledTextR$RRRLRMR4RNROR6RkRRmRP(R=RRQRRRIRR((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR2;s(    " $ c Cs=|jdddddddd|j|j|dS( NR6iR7iRiRix(RLRSRT(RIR((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR__s" c Cs|j|}d}tj|ddd|}tj|ddd|}t|jt|j|jddddd |d d |jddd d d d dS( Ns label.padX 4R,sTix.PanedWindowREs Tix.NoteBookRiR[R\Ri(RR Rt MkPanedWindowRt MkNoteBookR`(RRKR=REtpanetnote((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyRRds  "c Cs[tj|dtjdddtjdd}tj|ddd d }|jjd d tj|d d}|jddddd}|jddd}tj |}tj |}|j jtj d|j jtj d|j jtj d|j jtj d|j jtj d|j jtj d|j jtj d|j d|j dNs label.padX 4Rt horizontalR)RciRbRJRR$t5tflatR#R,sSelect a sample program:RYiRZsSource:REshlist.width 20RKtstextstix option get fixed_fontRRsRun ...trunsView Source ...tviewiRFtdisabledRRR^iPRit.t separatorit drawbranchi tindentt wideselectcSst|||||dS(NR(t Sample_Action(targsR=tslbRRR((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR0RR.cSst|||||dS(Ntbrowse(R(RR=RRRR((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR0Rt browsecmdcSst|||||dS(NR(R(RR=RRRR((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR0RcSst|||||dS(NR(R(RR=RRRR((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR0RRRWR"iRititemtypeRtdata(RR RiR6RjRmRWRRRR`RRwtevalR$tconfigR3RNR7tNONEthlistRlRkR^t add_childtWINDOWtTEXTtcommentststypestselection_clear(RRKR=RERctf1tf2tlabtlab1RRRRRRttypeR6tkey((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyRUksd"  ..(""   ((     "" !%   c Bs@|j}|j}|s2d|ds0   %   % "         '  $  / .    ^    @     PK%L]b&UUtix/samples/PopMenu.pyonu[ ^c@sHddlZdZedkrDejZeeejndS(iNc Cstj|dtjdd}tj|dd}|jdddtjdd d d tj|d d }|j||j||jj d ddd|jj d ddd|jj d ddd|jj d ddd|jj d dddtj |j}|j d d|jj d dd||jdtj ddd d tj |dtj}|jdddddddd|d |jd!dd"ddddd|d#|jdtjdtj|jdtj dtjdddS($NtrelieftbdittextsEPress the right mouse button over this button or its surrounding areatexpandtfilltpadxi2tpadyttitles Popup TesttlabeltDesktopt underlineitSelecttFindtSystemtHelptHellotMoretmenutsidei(t orientationtoktOktwidthitcommandcSs |jS(N(tdestroy(tw((s0/usr/lib64/python2.7/Demo/tix/samples/PopMenu.pyt0ttcanceltCancelcSs |jS(N(R(R((s0/usr/lib64/python2.7/Demo/tix/samples/PopMenu.pyR2R(tTixtFrametRAISEDtButtontpacktBOTHt PopupMenut bind_widgetRt add_commandtMenut add_cascadetTOPt ButtonBoxt HORIZONTALtaddtBOTTOMtX(Rttoptbuttptm1tbox((s0/usr/lib64/python2.7/Demo/tix/samples/PopMenu.pyt RunSamples,%    t__main__(RR4t__name__tTktroottmainloop(((s0/usr/lib64/python2.7/Demo/tix/samples/PopMenu.pyts  %   PK%L]3U tix/samples/DirList.pyonu[ ^c@sddlZddlZddlZddlTdZdZdd dYZedkrddlZddl Z yej Z ee Wqe j \ZZZdZxAe jeeeD]&Zeed Zejd eZqWqXndS( iN(t*icCs$t|}|j|jdS(N(t DemoDirListtmainlooptdestroy(troottdirlist((s0/usr/lib64/python2.7/Demo/tix/samples/DirList.pyt RunSamples  RcBs>eZdZdZdZdZdZdZRS(c Csc||_d|_|j}|jd|dtj|dtdd}tj||_d|jj d#ttrelieftbdii(twidthttexts >> tpadyitlabelsInstallation Directory:t labelsidettoptoptionss entry.width 40 label.anchor w stix option get fixed_fonttfontt textvariablecSs|j||S(N(t copy_name(tdirtentR ((s0/usr/lib64/python2.7/Demo/tix/samples/DirList.pyR KstcommandscSs |jS(N(tokcmd(R ((s0/usr/lib64/python2.7/Demo/tix/samples/DirList.pyR OR texpandtyestfilltbothtsidetpadxitanchortst orientationt horizontaltoktOkt underlineicSs |jS(N(R(R ((s0/usr/lib64/python2.7/Demo/tix/samples/DirList.pyR ZR tcanceltCancelcSs |jS(N(R(R ((s0/usr/lib64/python2.7/Demo/tix/samples/DirList.pyR \R tx(Rtexittwinfo_toplevelt wm_protocoltTixtFrametRAISEDtDirListRthlisttButtontbtnt LabelEntryRttktevaltentrytcopytostcurdirt dlist_dirtbindtpacktTOPtBOTHtLEFTtXt ButtonBoxtaddtBOTTOM(R twtzRRtbox((s0/usr/lib64/python2.7/Demo/tix/samples/DirList.pyt__init__s6    +%1  cCs?|jd|_|jjdd|jjd|jdS(Ntvalueitend(tcgetR=R9tdeletetinsert(R RR((s0/usr/lib64/python2.7/Demo/tix/samples/DirList.pyR`scCs|jdS(N(R(R ((s0/usr/lib64/python2.7/Demo/tix/samples/DirList.pyRgscCs d|_dS(Ni(R,(R ((s0/usr/lib64/python2.7/Demo/tix/samples/DirList.pyRkscCs-x&|jdkr(|jjjtqWdS(Ni(R,RR7t dooneeventtTCL_ALL_EVENTS(R ((s0/usr/lib64/python2.7/Demo/tix/samples/DirList.pyRnscCs|jjdS(N(RR(R ((s0/usr/lib64/python2.7/Demo/tix/samples/DirList.pyRrs(t__name__t __module__RJRRRRR(((s0/usr/lib64/python2.7/Demo/tix/samples/DirList.pyRs  B    t__main__sError running the demo script: s sTix Demo Error((R/R;R:t TkconstantsRQRRRRt tkMessageBoxt tracebacktTkRtsystexc_infotttvttbRtformat_exceptiontlinet showerrortd(((s0/usr/lib64/python2.7/Demo/tix/samples/DirList.pyts$  [  PK%L]aatix/samples/SHList1.pyonu[ ^c@sWddlZdZdZdddYZedkrSejZeendS(iNicCs$t|}|j|jdS(N(t DemoSHListtmainlooptdestroy(troottshlist((s0/usr/lib64/python2.7/Demo/tix/samples/SHList1.pyt RunSamples  RcBs5eZdZdZdZdZdZRS(c Cst||_d|_|j}|jd|dtj|dtjdd}tj||_|jj dddtj d d d d d tj d9d:d;g}d<d=d>d?d@dAdBg}|jj }|j d!d"d#d$d%d&d'd d&}x|D]\}} |retj|d(d)|d*d+d#d,dd+dtj} |jd-tjd.| d/tjn|j|d-tjd0| |d}qWx8|D]0\} }} |d"| } |j| d0| qWtj|d1tj} | jd2d0d3d4d&d#d5d6|j| jd7d0d8d4d&d#d5d6|j| j d tjdtj|j d tj dtj dddS(CNitWM_DELETE_WINDOWcSs |jS(N(tquitcmd(tself((s0/usr/lib64/python2.7/Demo/tix/samples/SHList1.pytttrelieftbditexpandtfilltpadxi tpadytsidetjeffs Jeff WaxmantjohnsJohn Leetpeters Peter Kensontalexs Alex Kellmantalans Alan AdamstandysAndreas Crawfordtdougs Douglas Bloomtjons Jon BarakitchrissChris Geoffreytchucks Chuck McLeant separatort.twidthit drawbranchitindenttnamessep%dtheightiititemtypetwindowtstatettextt orientationtoktOkt underlineitcommandtcanceltCancel(Rs Jeff Waxman(RsJohn Lee(Rs Peter Kenson(RRs Alex Kellman(RRs Alan Adams(RRsAndreas Crawford(RRs Douglas Bloom(RRs Jon Baraki(RRsChris Geoffrey(RRs Chuck McLean(Rtexittwinfo_toplevelt wm_protocoltTixtFrametRAISEDt ScrolledHListtatpacktBOTHtTOPthlisttconfigtSUNKENt add_childtWINDOWtDISABLEDtaddtTEXTt ButtonBoxt HORIZONTALtokcmdRtBOTTOMtX(Rtwtzttoptbossest employeesR9tcounttbossR!tftpersontkeytbox((s0/usr/lib64/python2.7/Demo/tix/samples/SHList1.pyt__init__sL   1   ""  cCs|jdS(N(R(R((s0/usr/lib64/python2.7/Demo/tix/samples/SHList1.pyRCpscCs d|_dS(Ni(R.(R((s0/usr/lib64/python2.7/Demo/tix/samples/SHList1.pyRsscCs-x&|jdkr(|jjjtqWdS(Ni(R.Rttkt dooneeventtTCL_ALL_EVENTS(R((s0/usr/lib64/python2.7/Demo/tix/samples/SHList1.pyRvscCs|jjdS(N(RR(R((s0/usr/lib64/python2.7/Demo/tix/samples/SHList1.pyRzs(t__name__t __module__RQRCRRR(((s0/usr/lib64/python2.7/Demo/tix/samples/SHList1.pyRs  V   t__main__((R1RTRRRUtTkR(((s0/usr/lib64/python2.7/Demo/tix/samples/SHList1.pyts  h  PK%L]nb!tix/samples/PanedWin.pycnu[ ^c@sWddlZdZdZdddYZedkrSejZeendS(iNicCs$t|}|j|jdS(N(t DemoPanedwintmainlooptdestroy(troottpanedwin((s1/usr/lib64/python2.7/Demo/tix/samples/PanedWin.pyt RunSamples  RcBs,eZdZdZdZdZRS(c Cs||_d|_|j}|jd|dtj|dddd}|jjdd tj|d d }|j d d ddd}|j dd d}tj |}d|j d!ttlabels Newsgroup:toptionssentry.width 25iscomp.lang.pythont orientationtverticaltlisttminiFtsizeidttextiPtwidthitheightis+ 12324 Re: Tkinter is good for your healths++ 12325 Re: Tkinter is good for your healthsH+ 12326 Re: Tix is even better for your health (Was: Tkinter is good...)sH 12327 Re: Tix is even better for your health (Was: Tkinter is good...)sH+ 12328 Re: Tix is even better for your health (Was: Tkinter is good...)sH 12329 Re: Tix is even better for your health (Was: Tkinter is good...)sH+ 12330 Re: Tix is even better for your health (Was: Tkinter is good...)tbgtnonetwraps~ Mon, 19 Jun 1995 11:39:52 comp.lang.python Thread 34 of 220 Lines 353 A new way to put text and bitmaps together iNo responses ioi@blue.seas.upenn.edu Ioi K. Lam at University of Pennsylvania Hi, I have implemented a new image type called "compound". It allows you to glue together a bunch of bitmaps, images and text strings together to form a bigger image. Then you can use this image with widgets that support the -image option. For example, you can display a text string string together with a bitmap, at the same time, inside a TK button widget. tdisabledtstatetexpanditfilltpadxitpadyitsideitoktOkt underlinetcommandtcanceltCancel(Rtexittwinfo_toplevelt wm_protocoltTixt LabelEntrytentrytinsertt PanedWindowtaddtScrolledListBoxtlistboxt ScrolledTextRtENDtpacktBOTHtTOPt ButtonBoxt HORIZONTALRtBOTTOMtX( Rtwtztgrouptpanetp1tp2RRtbox((s1/usr/lib64/python2.7/Demo/tix/samples/PanedWin.pyt__init__sJ          %%(.  cCs d|_dS(Ni(R%(R((s1/usr/lib64/python2.7/Demo/tix/samples/PanedWin.pyRVscCs-x&|jdkr(|jjjtqWdS(Ni(R%Rttkt dooneeventtTCL_ALL_EVENTS(R((s1/usr/lib64/python2.7/Demo/tix/samples/PanedWin.pyRYscCs|jjdS(N(RR(R((s1/usr/lib64/python2.7/Demo/tix/samples/PanedWin.pyR]s(t__name__t __module__R@RRR(((s1/usr/lib64/python2.7/Demo/tix/samples/PanedWin.pyRs :  t__main__((R(RCRRRDtTkR(((s1/usr/lib64/python2.7/Demo/tix/samples/PanedWin.pyts  E  PK%L]3U tix/samples/DirList.pycnu[ ^c@sddlZddlZddlZddlTdZdZdd dYZedkrddlZddl Z yej Z ee Wqe j \ZZZdZxAe jeeeD]&Zeed Zejd eZqWqXndS( iN(t*icCs$t|}|j|jdS(N(t DemoDirListtmainlooptdestroy(troottdirlist((s0/usr/lib64/python2.7/Demo/tix/samples/DirList.pyt RunSamples  RcBs>eZdZdZdZdZdZdZRS(c Csc||_d|_|j}|jd|dtj|dtdd}tj||_d|jj d#ttrelieftbdii(twidthttexts >> tpadyitlabelsInstallation Directory:t labelsidettoptoptionss entry.width 40 label.anchor w stix option get fixed_fonttfontt textvariablecSs|j||S(N(t copy_name(tdirtentR ((s0/usr/lib64/python2.7/Demo/tix/samples/DirList.pyR KstcommandscSs |jS(N(tokcmd(R ((s0/usr/lib64/python2.7/Demo/tix/samples/DirList.pyR OR texpandtyestfilltbothtsidetpadxitanchortst orientationt horizontaltoktOkt underlineicSs |jS(N(R(R ((s0/usr/lib64/python2.7/Demo/tix/samples/DirList.pyR ZR tcanceltCancelcSs |jS(N(R(R ((s0/usr/lib64/python2.7/Demo/tix/samples/DirList.pyR \R tx(Rtexittwinfo_toplevelt wm_protocoltTixtFrametRAISEDtDirListRthlisttButtontbtnt LabelEntryRttktevaltentrytcopytostcurdirt dlist_dirtbindtpacktTOPtBOTHtLEFTtXt ButtonBoxtaddtBOTTOM(R twtzRRtbox((s0/usr/lib64/python2.7/Demo/tix/samples/DirList.pyt__init__s6    +%1  cCs?|jd|_|jjdd|jjd|jdS(Ntvalueitend(tcgetR=R9tdeletetinsert(R RR((s0/usr/lib64/python2.7/Demo/tix/samples/DirList.pyR`scCs|jdS(N(R(R ((s0/usr/lib64/python2.7/Demo/tix/samples/DirList.pyRgscCs d|_dS(Ni(R,(R ((s0/usr/lib64/python2.7/Demo/tix/samples/DirList.pyRkscCs-x&|jdkr(|jjjtqWdS(Ni(R,RR7t dooneeventtTCL_ALL_EVENTS(R ((s0/usr/lib64/python2.7/Demo/tix/samples/DirList.pyRnscCs|jjdS(N(RR(R ((s0/usr/lib64/python2.7/Demo/tix/samples/DirList.pyRrs(t__name__t __module__RJRRRRR(((s0/usr/lib64/python2.7/Demo/tix/samples/DirList.pyRs  B    t__main__sError running the demo script: s sTix Demo Error((R/R;R:t TkconstantsRQRRRRt tkMessageBoxt tracebacktTkRtsystexc_infotttvttbRtformat_exceptiontlinet showerrortd(((s0/usr/lib64/python2.7/Demo/tix/samples/DirList.pyts$  [  PK%L]ûT T tix/samples/ComboBox.pynu[# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- # # $Id$ # # Tix Demonstration Program # # This sample program is structured in such a way so that it can be # executed from the Tix demo program "tixwidgets.py": it must have a # procedure called "RunSample". It should also have the "if" statment # at the end of this file so that it can be run as a standalone # program. # This file demonstrates the use of the tixComboBox widget, which is close # to the MS Window Combo Box control. # import Tix def RunSample(w): global demo_month, demo_year top = Tix.Frame(w, bd=1, relief=Tix.RAISED) demo_month = Tix.StringVar() demo_year = Tix.StringVar() # $w.top.a is a drop-down combo box. It is not editable -- who wants # to invent new months? # # [Hint] The -options switch sets the options of the subwidgets. # [Hint] We set the label.width subwidget option of both comboboxes to # be 10 so that their labels appear to be aligned. # a = Tix.ComboBox(top, label="Month: ", dropdown=1, command=select_month, editable=0, variable=demo_month, options='listbox.height 6 label.width 10 label.anchor e') # $w.top.b is a non-drop-down combo box. It is not editable: we provide # four choices for the user, but he can enter an alternative year if he # wants to. # # [Hint] Use the padY and anchor options of the label subwidget to # align the label with the entry subwidget. # [Hint] Notice that you should use padY (the NAME of the option) and not # pady (the SWITCH of the option). # b = Tix.ComboBox(top, label="Year: ", dropdown=0, command=select_year, editable=1, variable=demo_year, options='listbox.height 4 label.padY 5 label.width 10 label.anchor ne') a.pack(side=Tix.TOP, anchor=Tix.W) b.pack(side=Tix.TOP, anchor=Tix.W) a.insert(Tix.END, 'January') a.insert(Tix.END, 'February') a.insert(Tix.END, 'March') a.insert(Tix.END, 'April') a.insert(Tix.END, 'May') a.insert(Tix.END, 'June') a.insert(Tix.END, 'July') a.insert(Tix.END, 'August') a.insert(Tix.END, 'September') a.insert(Tix.END, 'October') a.insert(Tix.END, 'November') a.insert(Tix.END, 'December') b.insert(Tix.END, '1992') b.insert(Tix.END, '1993') b.insert(Tix.END, '1994') b.insert(Tix.END, '1995') b.insert(Tix.END, '1996') # Use "tixSetSilent" to set the values of the combo box if you # don't want your -command procedures (cbx:select_month and # cbx:select_year) to be called. # a.set_silent('January') b.set_silent('1995') box = Tix.ButtonBox(w, orientation=Tix.HORIZONTAL) box.add('ok', text='Ok', underline=0, width=6, command=lambda w=w: ok_command(w)) box.add('cancel', text='Cancel', underline=0, width=6, command=lambda w=w: w.destroy()) box.pack(side=Tix.BOTTOM, fill=Tix.X) top.pack(side=Tix.TOP, fill=Tix.BOTH, expand=1) def select_month(event=None): # tixDemo:Status "Month = %s" % demo_month.get() pass def select_year(event=None): # tixDemo:Status "Year = %s" % demo_year.get() pass def ok_command(w): # tixDemo:Status "Month = %s, Year= %s" % (demo_month.get(), demo_year.get()) w.destroy() if __name__ == '__main__': root = Tix.Tk() RunSample(root) root.mainloop() PK%L]N tix/samples/OptMenu.pynu[# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- # # $Id$ # # Tix Demonstration Program # # This sample program is structured in such a way so that it can be # executed from the Tix demo program "tixwidgets.py": it must have a # procedure called "RunSample". It should also have the "if" statment # at the end of this file so that it can be run as a standalone # program. # This file demonstrates the use of the tixOptionMenu widget -- you can # use it for the user to choose from a fixed set of options # import Tix options = {'text':'Plain Text', 'post':'PostScript', 'html':'HTML', 'tex':'LaTeX', 'rtf':'Rich Text Format'} def RunSample(w): global demo_opt_from, demo_opt_to demo_opt_from = Tix.StringVar() demo_opt_to = Tix.StringVar() top = Tix.Frame(w, bd=1, relief=Tix.RAISED) from_file = Tix.OptionMenu(top, label="From File Format : ", variable=demo_opt_from, options = 'label.width 19 label.anchor e menubutton.width 15') to_file = Tix.OptionMenu(top, label="To File Format : ", variable=demo_opt_to, options='label.width 19 label.anchor e menubutton.width 15') # Add the available options to the two OptionMenu widgets # # [Hint] You have to add the options first before you set the # global variables "demo_opt_from" and "demo_opt_to". Otherwise # the OptionMenu widget will complain about "unknown options"! # for opt in options.keys(): from_file.add_command(opt, label=options[opt]) to_file.add_command(opt, label=options[opt]) demo_opt_from.set('html') demo_opt_to.set('post') from_file.pack(side=Tix.TOP, anchor=Tix.W, pady=3, padx=6) to_file.pack(side=Tix.TOP, anchor=Tix.W, pady=3, padx=6) box = Tix.ButtonBox(w, orientation=Tix.HORIZONTAL) box.add('ok', text='Ok', underline=0, width=6, command=lambda w=w: ok_command(w)) box.add('cancel', text='Cancel', underline=0, width=6, command=lambda w=w: w.destroy()) box.pack(side=Tix.BOTTOM, fill=Tix.X) top.pack(side=Tix.TOP, fill=Tix.BOTH, expand=1) def ok_command(w): # tixDemo:Status "Convert file from %s to %s" % ( demo_opt_from.get(), demo_opt_to.get()) w.destroy() if __name__ == '__main__': root = Tix.Tk() RunSample(root) root.mainloop() PK%L]qtix/samples/Control.pyonu[ ^c@sxddlZdZdZdd dYZdddgZd Zd Zed krtejZ ee ndS( iNicCs$t|}|j|jdS(N(t DemoControltmainlooptdestroy(troottcontrol((s0/usr/lib64/python2.7/Demo/tix/samples/Control.pyt RunSamples  RcBs5eZdZdZdZdZdZRS(cCs<||_d|_tjatjatjatj dtj dtj dtj |dddtj }tj |dd d dd td dd ddd}tj |ddd dd dd dddd tdd}tj |ddddd tdd}|d|d<|d|d<|d|d<|j dtjd tj|j dtjd tj|j dtjd tjtj|d!tj}|jd"d#d$d%dd&d'd(|j|jd)d#d*d%dd&d'd(|j|j dtjd+tj|j dtjd+tjd,ddS(-NisP&Wg@itbditrelieftlabelsNumber of Engines: tintegertvariabletmintmaxitoptionss,entry.width 10 label.width 20 label.anchor esThrust: is10000.0s60000.0tstepisEngine Maker: tvaluecSs t|dS(Ni(t adjust_maker(tw((s0/usr/lib64/python2.7/Demo/tix/samples/Control.pytCttincrcmdcSs t|dS(Ni(R(R((s0/usr/lib64/python2.7/Demo/tix/samples/Control.pyRDRtdecrcmdcSs t|S(N(tvalidate_maker(R((s0/usr/lib64/python2.7/Demo/tix/samples/Control.pyRERt validatecmdtsidetanchort orientationtokttexttOkt underlinetwidthitcommandtcanceltCanceltfilltexpand(RtexittTixt StringVart demo_makert DoubleVart demo_thrusttIntVartdemo_num_enginestsettFrametRAISEDtControltpacktTOPtWt ButtonBoxt HORIZONTALtaddtokcmdtquitcmdtBOTTOMtXtBOTH(tselfRttoptatbtctbox((s0/usr/lib64/python2.7/Demo/tix/samples/Control.pyt__init__s@             cCs|jdS(N(R8(R<((s0/usr/lib64/python2.7/Demo/tix/samples/Control.pyR7SscCs d|_dS(Ni(R%(R<((s0/usr/lib64/python2.7/Demo/tix/samples/Control.pyR8WscCs-x&|jdkr(|jjjtqWdS(Ni(R%Rttkt dooneeventtTCL_ALL_EVENTS(R<((s0/usr/lib64/python2.7/Demo/tix/samples/Control.pyRZscCs|jjdS(N(RR(R<((s0/usr/lib64/python2.7/Demo/tix/samples/Control.pyR^s(t__name__t __module__RBR7R8RR(((s0/usr/lib64/python2.7/Demo/tix/samples/Control.pyRs  4   sP&WtGEs Rolls RoycecCsntjtj}||}|ttkr:d}n|dkrYttd}ntjt|dS(Nii(t maker_listtindexR(tgettlenR-(Rtincti((s0/usr/lib64/python2.7/Demo/tix/samples/Control.pyRcs   cCs:ytjtj}Wntk r1tdSXt|S(Ni(RIRJR(RKt ValueError(RRN((s0/usr/lib64/python2.7/Demo/tix/samples/Control.pyRos   t__main__(( R&RERRRIRRRFtTkR(((s0/usr/lib64/python2.7/Demo/tix/samples/Control.pyts  C  PK%L]tܙyytix/samples/NoteBook.pynu[# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- # # $Id$ # # Tix Demonstration Program # # This sample program is structured in such a way so that it can be # executed from the Tix demo program "tixwidgets.py": it must have a # procedure called "RunSample". It should also have the "if" statment # at the end of this file so that it can be run as a standalone # program. # This file demonstrates the use of the tixNoteBook widget, which allows # you to lay out your interface using a "notebook" metaphore # import Tix def RunSample(w): global root root = w # We use these options to set the sizes of the subwidgets inside the # notebook, so that they are well-aligned on the screen. prefix = Tix.OptionName(w) if prefix: prefix = '*'+prefix else: prefix = '' w.option_add(prefix+'*TixControl*entry.width', 10) w.option_add(prefix+'*TixControl*label.width', 18) w.option_add(prefix+'*TixControl*label.anchor', Tix.E) w.option_add(prefix+'*TixNoteBook*tagPadX', 8) # Create the notebook widget and set its backpagecolor to gray. # Note that the -backpagecolor option belongs to the "nbframe" # subwidget. nb = Tix.NoteBook(w, name='nb', ipadx=6, ipady=6) nb['bg'] = 'gray' nb.nbframe['backpagecolor'] = 'gray' # Create the two tabs on the notebook. The -underline option # puts a underline on the first character of the labels of the tabs. # Keyboard accelerators will be defined automatically according # to the underlined character. nb.add('hard_disk', label="Hard Disk", underline=0) nb.add('network', label="Network", underline=0) nb.pack(expand=1, fill=Tix.BOTH, padx=5, pady=5 ,side=Tix.TOP) #---------------------------------------- # Create the first page #---------------------------------------- # Create two frames: one for the common buttons, one for the # other widgets # tab=nb.hard_disk f = Tix.Frame(tab) common = Tix.Frame(tab) f.pack(side=Tix.LEFT, padx=2, pady=2, fill=Tix.BOTH, expand=1) common.pack(side=Tix.RIGHT, padx=2, fill=Tix.Y) a = Tix.Control(f, value=12, label='Access time: ') w = Tix.Control(f, value=400, label='Write Throughput: ') r = Tix.Control(f, value=400, label='Read Throughput: ') c = Tix.Control(f, value=1021, label='Capacity: ') a.pack(side=Tix.TOP, padx=20, pady=2) w.pack(side=Tix.TOP, padx=20, pady=2) r.pack(side=Tix.TOP, padx=20, pady=2) c.pack(side=Tix.TOP, padx=20, pady=2) # Create the common buttons createCommonButtons(common) #---------------------------------------- # Create the second page #---------------------------------------- tab = nb.network f = Tix.Frame(tab) common = Tix.Frame(tab) f.pack(side=Tix.LEFT, padx=2, pady=2, fill=Tix.BOTH, expand=1) common.pack(side=Tix.RIGHT, padx=2, fill=Tix.Y) a = Tix.Control(f, value=12, label='Access time: ') w = Tix.Control(f, value=400, label='Write Throughput: ') r = Tix.Control(f, value=400, label='Read Throughput: ') c = Tix.Control(f, value=1021, label='Capacity: ') u = Tix.Control(f, value=10, label='Users: ') a.pack(side=Tix.TOP, padx=20, pady=2) w.pack(side=Tix.TOP, padx=20, pady=2) r.pack(side=Tix.TOP, padx=20, pady=2) c.pack(side=Tix.TOP, padx=20, pady=2) u.pack(side=Tix.TOP, padx=20, pady=2) createCommonButtons(common) def doDestroy(): global root root.destroy() def createCommonButtons(master): ok = Tix.Button(master, name='ok', text='OK', width=6, command=doDestroy) cancel = Tix.Button(master, name='cancel', text='Cancel', width=6, command=doDestroy) ok.pack(side=Tix.TOP, padx=2, pady=2) cancel.pack(side=Tix.TOP, padx=2, pady=2) if __name__ == '__main__': root = Tix.Tk() RunSample(root) root.mainloop() PK%L]l/ / tix/samples/Tree.pynu[# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- # # $Id$ # # Tix Demonstration Program # # This sample program is structured in such a way so that it can be # executed from the Tix demo program "tixwidgets.py": it must have a # procedure called "RunSample". It should also have the "if" statment # at the end of this file so that it can be run as a standalone # program. # This file demonstrates how to use the TixTree widget to display # dynamic hierachical data (the files in the Unix file system) # import Tix, os def RunSample(w): top = Tix.Frame(w, relief=Tix.RAISED, bd=1) tree = Tix.Tree(top, options='separator "/"') tree.pack(expand=1, fill=Tix.BOTH, padx=10, pady=10, side=Tix.LEFT) tree['opencmd'] = lambda dir=None, w=tree: opendir(w, dir) # The / directory is added in the "open" mode. The user can open it # and then browse its subdirectories ... adddir(tree, "/") box = Tix.ButtonBox(w, orientation=Tix.HORIZONTAL) box.add('ok', text='Ok', underline=0, command=w.destroy, width=6) box.add('cancel', text='Cancel', underline=0, command=w.destroy, width=6) box.pack(side=Tix.BOTTOM, fill=Tix.X) top.pack(side=Tix.TOP, fill=Tix.BOTH, expand=1) def adddir(tree, dir): if dir == '/': text = '/' else: text = os.path.basename(dir) tree.hlist.add(dir, itemtype=Tix.IMAGETEXT, text=text, image=tree.tk.call('tix', 'getimage', 'folder')) try: os.listdir(dir) tree.setmode(dir, 'open') except os.error: # No read permission ? pass # This function is called whenever the user presses the (+) indicator or # double clicks on a directory whose mode is "open". It loads the files # inside that directory into the Tree widget. # # Note we didn't specify the closecmd option for the Tree widget, so it # performs the default action when the user presses the (-) indicator or # double clicks on a directory whose mode is "close": hide all of its child # entries def opendir(tree, dir): entries = tree.hlist.info_children(dir) if entries: # We have already loaded this directory. Let's just # show all the child entries # # Note: since we load the directory only once, it will not be # refreshed if the you add or remove files from this # directory. # for entry in entries: tree.hlist.show_entry(entry) files = os.listdir(dir) for file in files: if os.path.isdir(dir + '/' + file): adddir(tree, dir + '/' + file) else: tree.hlist.add(dir + '/' + file, itemtype=Tix.IMAGETEXT, text=file, image=tree.tk.call('tix', 'getimage', 'file')) if __name__ == '__main__': root = Tix.Tk() RunSample(root) root.mainloop() PK%L]7:BBtix/samples/BtnBox.pycnu[ ^c@sHddlZdZedkrDejZeeejndS(iNcCstj|dddddddtjdtjd d }tj|d tj}|jd d d ddddd|d|jdd dddddd|d|jdtjdtj |jdtj dtj dddS(Ntpadxitpadyi tbditrelieftanchorttexts?This dialog box is a demonstration of the tixButtonBox widgett orientationtoktOKt underlineitwidthitcommandcSs |jS(N(tdestroy(tw((s//usr/lib64/python2.7/Demo/tix/samples/BtnBox.pyt#ttclosetCancelcSs |jS(N(R (R ((s//usr/lib64/python2.7/Demo/tix/samples/BtnBox.pyR%Rtsidetfilltexpand( tTixtLabeltRAISEDtCENTERt ButtonBoxt HORIZONTALtaddtpacktBOTTOMtXtTOPtBOTH(R ttoptbox((s//usr/lib64/python2.7/Demo/tix/samples/BtnBox.pyt RunSamples'   t__main__(RR#t__name__tTktroottmainloop(((s//usr/lib64/python2.7/Demo/tix/samples/BtnBox.pyts     PK%L]VGtix/samples/Balloon.pynu[# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- # # $Id$ # # Tix Demonstration Program # # This sample program is structured in such a way so that it can be # executed from the Tix demo program "tixwidgets.py": it must have a # procedure called "RunSample". It should also have the "if" statment # at the end of this file so that it can be run as a standalone # program. # This file demonstrates the use of the tixBalloon widget, which provides # an interesting way to give help tips about elements in your user interface. # Your can display the help message in a "balloon" and a status bar widget. # import Tix TCL_ALL_EVENTS = 0 def RunSample (root): balloon = DemoBalloon(root) balloon.mainloop() balloon.destroy() class DemoBalloon: def __init__(self, w): self.root = w self.exit = -1 z = w.winfo_toplevel() z.wm_protocol("WM_DELETE_WINDOW", lambda self=self: self.quitcmd()) status = Tix.Label(w, width=40, relief=Tix.SUNKEN, bd=1) status.pack(side=Tix.BOTTOM, fill=Tix.Y, padx=2, pady=1) # Create two mysterious widgets that need balloon help button1 = Tix.Button(w, text='Something Unexpected', command=self.quitcmd) button2 = Tix.Button(w, text='Something Else Unexpected') button2['command'] = lambda w=button2: w.destroy() button1.pack(side=Tix.TOP, expand=1) button2.pack(side=Tix.TOP, expand=1) # Create the balloon widget and associate it with the widgets that we want # to provide tips for: b = Tix.Balloon(w, statusbar=status) b.bind_widget(button1, balloonmsg='Close Window', statusmsg='Press this button to close this window') b.bind_widget(button2, balloonmsg='Self-destruct button', statusmsg='Press this button and it will destroy itself') def quitcmd (self): self.exit = 0 def mainloop(self): foundEvent = 1 while self.exit < 0 and foundEvent > 0: foundEvent = self.root.tk.dooneevent(TCL_ALL_EVENTS) def destroy (self): self.root.destroy() if __name__ == '__main__': root = Tix.Tk() RunSample(root) PK%L]nb!tix/samples/PanedWin.pyonu[ ^c@sWddlZdZdZdddYZedkrSejZeendS(iNicCs$t|}|j|jdS(N(t DemoPanedwintmainlooptdestroy(troottpanedwin((s1/usr/lib64/python2.7/Demo/tix/samples/PanedWin.pyt RunSamples  RcBs,eZdZdZdZdZRS(c Cs||_d|_|j}|jd|dtj|dddd}|jjdd tj|d d }|j d d ddd}|j dd d}tj |}d|j d!ttlabels Newsgroup:toptionssentry.width 25iscomp.lang.pythont orientationtverticaltlisttminiFtsizeidttextiPtwidthitheightis+ 12324 Re: Tkinter is good for your healths++ 12325 Re: Tkinter is good for your healthsH+ 12326 Re: Tix is even better for your health (Was: Tkinter is good...)sH 12327 Re: Tix is even better for your health (Was: Tkinter is good...)sH+ 12328 Re: Tix is even better for your health (Was: Tkinter is good...)sH 12329 Re: Tix is even better for your health (Was: Tkinter is good...)sH+ 12330 Re: Tix is even better for your health (Was: Tkinter is good...)tbgtnonetwraps~ Mon, 19 Jun 1995 11:39:52 comp.lang.python Thread 34 of 220 Lines 353 A new way to put text and bitmaps together iNo responses ioi@blue.seas.upenn.edu Ioi K. Lam at University of Pennsylvania Hi, I have implemented a new image type called "compound". It allows you to glue together a bunch of bitmaps, images and text strings together to form a bigger image. Then you can use this image with widgets that support the -image option. For example, you can display a text string string together with a bitmap, at the same time, inside a TK button widget. tdisabledtstatetexpanditfilltpadxitpadyitsideitoktOkt underlinetcommandtcanceltCancel(Rtexittwinfo_toplevelt wm_protocoltTixt LabelEntrytentrytinsertt PanedWindowtaddtScrolledListBoxtlistboxt ScrolledTextRtENDtpacktBOTHtTOPt ButtonBoxt HORIZONTALRtBOTTOMtX( Rtwtztgrouptpanetp1tp2RRtbox((s1/usr/lib64/python2.7/Demo/tix/samples/PanedWin.pyt__init__sJ          %%(.  cCs d|_dS(Ni(R%(R((s1/usr/lib64/python2.7/Demo/tix/samples/PanedWin.pyRVscCs-x&|jdkr(|jjjtqWdS(Ni(R%Rttkt dooneeventtTCL_ALL_EVENTS(R((s1/usr/lib64/python2.7/Demo/tix/samples/PanedWin.pyRYscCs|jjdS(N(RR(R((s1/usr/lib64/python2.7/Demo/tix/samples/PanedWin.pyR]s(t__name__t __module__R@RRR(((s1/usr/lib64/python2.7/Demo/tix/samples/PanedWin.pyRs :  t__main__((R(RCRRRDtTkR(((s1/usr/lib64/python2.7/Demo/tix/samples/PanedWin.pyts  E  PK%L]Dl11tix/samples/CmpImg.pynu[# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- # # $Id$ # # Tix Demonstration Program # # This sample program is structured in such a way so that it can be # executed from the Tix demo program "tixwidgets.py": it must have a # procedure called "RunSample". It should also have the "if" statment # at the end of this file so that it can be run as a standalone # program. # This file demonstrates the use of the compound images: it uses compound # images to display a text string together with a pixmap inside # buttons # import Tix network_pixmap = """/* XPM */ static char * netw_xpm[] = { /* width height ncolors chars_per_pixel */ "32 32 7 1", /* colors */ " s None c None", ". c #000000000000", "X c white", "o c #c000c000c000", "O c #404040", "+ c blue", "@ c red", /* pixels */ " ", " .............. ", " .XXXXXXXXXXXX. ", " .XooooooooooO. ", " .Xo.......XoO. ", " .Xo.++++o+XoO. ", " .Xo.++++o+XoO. ", " .Xo.++oo++XoO. ", " .Xo.++++++XoO. ", " .Xo.+o++++XoO. ", " .Xo.++++++XoO. ", " .Xo.XXXXXXXoO. ", " .XooooooooooO. ", " .Xo@ooo....oO. ", " .............. .XooooooooooO. ", " .XXXXXXXXXXXX. .XooooooooooO. ", " .XooooooooooO. .OOOOOOOOOOOO. ", " .Xo.......XoO. .............. ", " .Xo.++++o+XoO. @ ", " .Xo.++++o+XoO. @ ", " .Xo.++oo++XoO. @ ", " .Xo.++++++XoO. @ ", " .Xo.+o++++XoO. @ ", " .Xo.++++++XoO. ..... ", " .Xo.XXXXXXXoO. .XXX. ", " .XooooooooooO.@@@@@@.X O. ", " .Xo@ooo....oO. .OOO. ", " .XooooooooooO. ..... ", " .XooooooooooO. ", " .OOOOOOOOOOOO. ", " .............. ", " "}; """ hard_disk_pixmap = """/* XPM */ static char * drivea_xpm[] = { /* width height ncolors chars_per_pixel */ "32 32 5 1", /* colors */ " s None c None", ". c #000000000000", "X c white", "o c #c000c000c000", "O c #800080008000", /* pixels */ " ", " ", " ", " ", " ", " ", " ", " ", " ", " .......................... ", " .XXXXXXXXXXXXXXXXXXXXXXXo. ", " .XooooooooooooooooooooooO. ", " .Xooooooooooooooooo..oooO. ", " .Xooooooooooooooooo..oooO. ", " .XooooooooooooooooooooooO. ", " .Xoooooooo.......oooooooO. ", " .Xoo...................oO. ", " .Xoooooooo.......oooooooO. ", " .XooooooooooooooooooooooO. ", " .XooooooooooooooooooooooO. ", " .XooooooooooooooooooooooO. ", " .XooooooooooooooooooooooO. ", " .oOOOOOOOOOOOOOOOOOOOOOOO. ", " .......................... ", " ", " ", " ", " ", " ", " ", " ", " "}; """ network_bitmap = """ #define netw_width 32 #define netw_height 32 static unsigned char netw_bits[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x7f, 0x00, 0x00, 0x02, 0x40, 0x00, 0x00, 0xfa, 0x5f, 0x00, 0x00, 0x0a, 0x50, 0x00, 0x00, 0x0a, 0x52, 0x00, 0x00, 0x0a, 0x52, 0x00, 0x00, 0x8a, 0x51, 0x00, 0x00, 0x0a, 0x50, 0x00, 0x00, 0x4a, 0x50, 0x00, 0x00, 0x0a, 0x50, 0x00, 0x00, 0x0a, 0x50, 0x00, 0x00, 0xfa, 0x5f, 0x00, 0x00, 0x02, 0x40, 0xfe, 0x7f, 0x52, 0x55, 0x02, 0x40, 0xaa, 0x6a, 0xfa, 0x5f, 0xfe, 0x7f, 0x0a, 0x50, 0xfe, 0x7f, 0x0a, 0x52, 0x80, 0x00, 0x0a, 0x52, 0x80, 0x00, 0x8a, 0x51, 0x80, 0x00, 0x0a, 0x50, 0x80, 0x00, 0x4a, 0x50, 0x80, 0x00, 0x0a, 0x50, 0xe0, 0x03, 0x0a, 0x50, 0x20, 0x02, 0xfa, 0xdf, 0x3f, 0x03, 0x02, 0x40, 0xa0, 0x02, 0x52, 0x55, 0xe0, 0x03, 0xaa, 0x6a, 0x00, 0x00, 0xfe, 0x7f, 0x00, 0x00, 0xfe, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; """ hard_disk_bitmap = """ #define drivea_width 32 #define drivea_height 32 static unsigned char drivea_bits[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0xff, 0x1f, 0x08, 0x00, 0x00, 0x18, 0xa8, 0xaa, 0xaa, 0x1a, 0x48, 0x55, 0xd5, 0x1d, 0xa8, 0xaa, 0xaa, 0x1b, 0x48, 0x55, 0x55, 0x1d, 0xa8, 0xfa, 0xaf, 0x1a, 0xc8, 0xff, 0xff, 0x1d, 0xa8, 0xfa, 0xaf, 0x1a, 0x48, 0x55, 0x55, 0x1d, 0xa8, 0xaa, 0xaa, 0x1a, 0x48, 0x55, 0x55, 0x1d, 0xa8, 0xaa, 0xaa, 0x1a, 0xf8, 0xff, 0xff, 0x1f, 0xf8, 0xff, 0xff, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; """ def RunSample(w): w.img0 = Tix.Image('pixmap', data=network_pixmap) if not w.img0: w.img0 = Tix.Image('bitmap', data=network_bitmap) w.img1 = Tix.Image('pixmap', data=hard_disk_pixmap) if not w.img0: w.img1 = Tix.Image('bitmap', data=hard_disk_bitmap) hdd = Tix.Button(w, padx=4, pady=1, width=120) net = Tix.Button(w, padx=4, pady=1, width=120) # Create the first image: we create a line, then put a string, # a space and an image into this line, from left to right. # The result: we have a one-line image that consists of three # individual items # # The tk.calls should be methods in Tix ... w.hdd_img = Tix.Image('compound', window=hdd) w.hdd_img.tk.call(str(w.hdd_img), 'add', 'line') w.hdd_img.tk.call(str(w.hdd_img), 'add', 'text', '-text', 'Hard Disk', '-underline', '0') w.hdd_img.tk.call(str(w.hdd_img), 'add', 'space', '-width', '7') w.hdd_img.tk.call(str(w.hdd_img), 'add', 'image', '-image', w.img1) # Put this image into the first button # hdd['image'] = w.hdd_img # Next button w.net_img = Tix.Image('compound', window=net) w.net_img.tk.call(str(w.net_img), 'add', 'line') w.net_img.tk.call(str(w.net_img), 'add', 'text', '-text', 'Network', '-underline', '0') w.net_img.tk.call(str(w.net_img), 'add', 'space', '-width', '7') w.net_img.tk.call(str(w.net_img), 'add', 'image', '-image', w.img0) # Put this image into the first button # net['image'] = w.net_img close = Tix.Button(w, pady=1, text='Close', command=lambda w=w: w.destroy()) hdd.pack(side=Tix.LEFT, padx=10, pady=10, fill=Tix.Y, expand=1) net.pack(side=Tix.LEFT, padx=10, pady=10, fill=Tix.Y, expand=1) close.pack(side=Tix.LEFT, padx=10, pady=10, fill=Tix.Y, expand=1) if __name__ == '__main__': root = Tix.Tk() RunSample(root) root.mainloop() PK%L]qtix/samples/Control.pycnu[ ^c@sxddlZdZdZdd dYZdddgZd Zd Zed krtejZ ee ndS( iNicCs$t|}|j|jdS(N(t DemoControltmainlooptdestroy(troottcontrol((s0/usr/lib64/python2.7/Demo/tix/samples/Control.pyt RunSamples  RcBs5eZdZdZdZdZdZRS(cCs<||_d|_tjatjatjatj dtj dtj dtj |dddtj }tj |dd d dd td dd ddd}tj |ddd dd dd dddd tdd}tj |ddddd tdd}|d|d<|d|d<|d|d<|j dtjd tj|j dtjd tj|j dtjd tjtj|d!tj}|jd"d#d$d%dd&d'd(|j|jd)d#d*d%dd&d'd(|j|j dtjd+tj|j dtjd+tjd,ddS(-NisP&Wg@itbditrelieftlabelsNumber of Engines: tintegertvariabletmintmaxitoptionss,entry.width 10 label.width 20 label.anchor esThrust: is10000.0s60000.0tstepisEngine Maker: tvaluecSs t|dS(Ni(t adjust_maker(tw((s0/usr/lib64/python2.7/Demo/tix/samples/Control.pytCttincrcmdcSs t|dS(Ni(R(R((s0/usr/lib64/python2.7/Demo/tix/samples/Control.pyRDRtdecrcmdcSs t|S(N(tvalidate_maker(R((s0/usr/lib64/python2.7/Demo/tix/samples/Control.pyRERt validatecmdtsidetanchort orientationtokttexttOkt underlinetwidthitcommandtcanceltCanceltfilltexpand(RtexittTixt StringVart demo_makert DoubleVart demo_thrusttIntVartdemo_num_enginestsettFrametRAISEDtControltpacktTOPtWt ButtonBoxt HORIZONTALtaddtokcmdtquitcmdtBOTTOMtXtBOTH(tselfRttoptatbtctbox((s0/usr/lib64/python2.7/Demo/tix/samples/Control.pyt__init__s@             cCs|jdS(N(R8(R<((s0/usr/lib64/python2.7/Demo/tix/samples/Control.pyR7SscCs d|_dS(Ni(R%(R<((s0/usr/lib64/python2.7/Demo/tix/samples/Control.pyR8WscCs-x&|jdkr(|jjjtqWdS(Ni(R%Rttkt dooneeventtTCL_ALL_EVENTS(R<((s0/usr/lib64/python2.7/Demo/tix/samples/Control.pyRZscCs|jjdS(N(RR(R<((s0/usr/lib64/python2.7/Demo/tix/samples/Control.pyR^s(t__name__t __module__RBR7R8RR(((s0/usr/lib64/python2.7/Demo/tix/samples/Control.pyRs  4   sP&WtGEs Rolls RoycecCsntjtj}||}|ttkr:d}n|dkrYttd}ntjt|dS(Nii(t maker_listtindexR(tgettlenR-(Rtincti((s0/usr/lib64/python2.7/Demo/tix/samples/Control.pyRcs   cCs:ytjtj}Wntk r1tdSXt|S(Ni(RIRJR(RKt ValueError(RRN((s0/usr/lib64/python2.7/Demo/tix/samples/Control.pyRos   t__main__(( R&RERRRIRRRFtTkR(((s0/usr/lib64/python2.7/Demo/tix/samples/Control.pyts  C  PK%L] ttix/samples/DirTree.pycnu[ ^c@syddlZddlZddlZddlTdZdZdddYZedkruejZ ee ndS( iN(t*icCs$t|}|j|jdS(N(t DemoDirTreetmainlooptdestroy(troottdirtree((s0/usr/lib64/python2.7/Demo/tix/samples/DirTree.pyt RunSamples  RcBs>eZdZdZdZdZdZdZRS(c Cs>||_d|_|j}|jd|dtj|dtdd}tj||_d|jj d#ttrelieftbdii(twidthttexts >> tpadyitlabelsInstallation Directory:t labelsidettoptoptionss entry.width 40 label.anchor w t textvariablecSs|j||S(N(t copy_name(tdirtentR ((s0/usr/lib64/python2.7/Demo/tix/samples/DirTree.pyR FstcommandscSs |jS(N(tokcmd(R ((s0/usr/lib64/python2.7/Demo/tix/samples/DirTree.pyR IR texpandtyestfilltbothtsidetpadxitanchortst orientationt horizontaltoktOkt underlineicSs |jS(N(R(R ((s0/usr/lib64/python2.7/Demo/tix/samples/DirTree.pyR TR tcanceltCancelcSs |jS(N(R(R ((s0/usr/lib64/python2.7/Demo/tix/samples/DirTree.pyR VR tx(Rtexittwinfo_toplevelt wm_protocoltTixtFrametRAISEDtDirTreeRthlisttButtontbtnt LabelEntryRtcopytostcurdirt dlist_dirtentrytbindtpacktTOPtBOTHtLEFTtXt ButtonBoxtaddtBOTTOM(R twtzRtbox((s0/usr/lib64/python2.7/Demo/tix/samples/DirTree.pyt__init__s2    +%1  cCs?|jd|_|jjdd|jjd|jdS(Ntvalueitend(tcgetR9R:tdeletetinsert(R RR((s0/usr/lib64/python2.7/Demo/tix/samples/DirTree.pyRZscCs|jdS(N(R(R ((s0/usr/lib64/python2.7/Demo/tix/samples/DirTree.pyRascCs d|_dS(Ni(R+(R ((s0/usr/lib64/python2.7/Demo/tix/samples/DirTree.pyRescCs-x&|jdkr(|jjjtqWdS(Ni(R+Rttkt dooneeventtTCL_ALL_EVENTS(R ((s0/usr/lib64/python2.7/Demo/tix/samples/DirTree.pyRiscCs|jjdS(N(RR(R ((s0/usr/lib64/python2.7/Demo/tix/samples/DirTree.pyRms(t__name__t __module__RGRRRRR(((s0/usr/lib64/python2.7/Demo/tix/samples/DirTree.pyRs  <    t__main__(( R.R7R6t TkconstantsRORRRPtTkR(((s0/usr/lib64/python2.7/Demo/tix/samples/DirTree.pyts$  V  PK%L]*MB tix/samples/ComboBox.pycnu[ ^c@siddlZdZddZddZdZedkreejZeeej ndS(iNcCstj|dddtj}tjatjatj|dddddtdd d td d }tj|dd dd dtddd td d}|j dtj dtj |j dtj dtj |j tj d|j tj d|j tj d|j tj d|j tj d|j tj d|j tj d|j tj d|j tj d|j tj d|j tj d|j tj d|j tj d|j tj d|j tj d|j tj d |j tj d!|jd|jd tj|d"tj}|jd#d$d%d&d d'd(d|d)|jd*d$d+d&d d'd(d|d,|j dtjd-tj|j dtj d-tjd.ddS(/NtbditrelieftlabelsMonth: tdropdowntcommandteditableitvariabletoptionss.listbox.height 6 label.width 10 label.anchor esYear: s<listbox.height 4 label.padY 5 label.width 10 label.anchor netsidetanchortJanuarytFebruarytMarchtApriltMaytJunetJulytAugustt SeptembertOctobertNovembertDecembert1992t1993t1994t1995t1996t orientationtokttexttOkt underlinetwidthicSs t|S(N(t ok_command(tw((s1/usr/lib64/python2.7/Demo/tix/samples/ComboBox.pytQttcanceltCancelcSs |jS(N(tdestroy(R"((s1/usr/lib64/python2.7/Demo/tix/samples/ComboBox.pyR#SR$tfilltexpand(tTixtFrametRAISEDt StringVart demo_montht demo_yeartComboBoxt select_montht select_yeartpacktTOPtWtinserttENDt set_silentt ButtonBoxt HORIZONTALtaddtBOTTOMtXtBOTH(R"ttoptatbtbox((s1/usr/lib64/python2.7/Demo/tix/samples/ComboBox.pyt RunSamplesJ        cCsdS(N((tevent((s1/usr/lib64/python2.7/Demo/tix/samples/ComboBox.pyR1WscCsdS(N((RD((s1/usr/lib64/python2.7/Demo/tix/samples/ComboBox.pyR2[scCs|jdS(N(R'(R"((s1/usr/lib64/python2.7/Demo/tix/samples/ComboBox.pyR!_st__main__( R*RCtNoneR1R2R!t__name__tTktroottmainloop(((s1/usr/lib64/python2.7/Demo/tix/samples/ComboBox.pyts  E      PK%L] \ \ tix/samples/Balloon.pycnu[ ^c@sWddlZdZdZdddYZedkrSejZeendS(iNicCs$t|}|j|jdS(N(t DemoBalloontmainlooptdestroy(troottballoon((s0/usr/lib64/python2.7/Demo/tix/samples/Balloon.pyt RunSamples  RcBs,eZdZdZdZdZRS(c Cs@||_d|_|j}|jd|dtj|dddtjdd}|jd tjd tj d d d dtj |ddd|j }tj |dd}|d|d<|jd tj dd|jd tj ddtj |d|}|j|dddd|j|dddddS(NitWM_DELETE_WINDOWcSs |jS(N(tquitcmd(tself((s0/usr/lib64/python2.7/Demo/tix/samples/Balloon.pyt!ttwidthi(trelieftbditsidetfilltpadxitpadyttextsSomething UnexpectedtcommandsSomething Else UnexpectedcSs |jS(N(R(tw((s0/usr/lib64/python2.7/Demo/tix/samples/Balloon.pyR *R texpandt statusbart balloonmsgs Close Windowt statusmsgs&Press this button to close this windowsSelf-destruct buttons,Press this button and it will destroy itself(Rtexittwinfo_toplevelt wm_protocoltTixtLabeltSUNKENtpacktBOTTOMtYtButtonRtTOPtBalloont bind_widget(RRtztstatustbutton1tbutton2tb((s0/usr/lib64/python2.7/Demo/tix/samples/Balloon.pyt__init__s"   $( cCs d|_dS(Ni(R(R((s0/usr/lib64/python2.7/Demo/tix/samples/Balloon.pyR7scCsAd}x4|jdkr<|dkr<|jjjt}q WdS(Nii(RRttkt dooneeventtTCL_ALL_EVENTS(Rt foundEvent((s0/usr/lib64/python2.7/Demo/tix/samples/Balloon.pyR:scCs|jjdS(N(RR(R((s0/usr/lib64/python2.7/Demo/tix/samples/Balloon.pyR?s(t__name__t __module__R+RRR(((s0/usr/lib64/python2.7/Demo/tix/samples/Balloon.pyRs   t__main__((RR.RRR0tTkR(((s0/usr/lib64/python2.7/Demo/tix/samples/Balloon.pyts  '  PK%L]88tix/samples/PopMenu.pynu[# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- # # $Id$ # # Tix Demonstration Program # # This sample program is structured in such a way so that it can be # executed from the Tix demo program "tixwidgets.py": it must have a # procedure called "RunSample". It should also have the "if" statment # at the end of this file so that it can be run as a standalone # program using tixwish. # This file demonstrates the use of the tixPopupMenu widget. # import Tix def RunSample(w): # We create the frame and the button, then we'll bind the PopupMenu # to both widgets. The result is, when you press the right mouse # button over $w.top or $w.top.but, the PopupMenu will come up. # top = Tix.Frame(w, relief=Tix.RAISED, bd=1) but = Tix.Button(top, text='Press the right mouse button over this button or its surrounding area') but.pack(expand=1, fill=Tix.BOTH, padx=50, pady=50) p = Tix.PopupMenu(top, title='Popup Test') p.bind_widget(top) p.bind_widget(but) # Set the entries inside the PopupMenu widget. # [Hint] You have to manipulate the "menu" subwidget. # $w.top.p itself is NOT a menu widget. # [Hint] Watch carefully how the sub-menu is created # p.menu.add_command(label='Desktop', underline=0) p.menu.add_command(label='Select', underline=0) p.menu.add_command(label='Find', underline=0) p.menu.add_command(label='System', underline=1) p.menu.add_command(label='Help', underline=0) m1 = Tix.Menu(p.menu) m1.add_command(label='Hello') p.menu.add_cascade(label='More', menu=m1) but.pack(side=Tix.TOP, padx=40, pady=50) box = Tix.ButtonBox(w, orientation=Tix.HORIZONTAL) box.add('ok', text='Ok', underline=0, width=6, command=lambda w=w: w.destroy()) box.add('cancel', text='Cancel', underline=0, width=6, command=lambda w=w: w.destroy()) box.pack(side=Tix.BOTTOM, fill=Tix.X) top.pack(side=Tix.TOP, fill=Tix.BOTH, expand=1) if __name__ == '__main__': root = Tix.Tk() RunSample(root) root.mainloop() PK%L]B~ gtix/samples/SHList2.pycnu[ ^c@sWddlZdZdZdddYZedkrSejZeendS(iNicCs$t|}|j|jdS(N(t DemoSHListtmainlooptdestroy(troottshlist((s0/usr/lib64/python2.7/Demo/tix/samples/SHList2.pyt RunSamples  RcBs5eZdZdZdZdZdZRS(c Cs%||_d|_|j}|jd|dtj|dtjdd}tj|dd|_|jj d dd tj d d d d dtj |jj }|j jdddd}i}tjtjd|dtjd dd dd||d<|jddtjddd|d|jddtjddd|d|jdddN}dOdPdQg}dRdSdTdUdVdWdXg} tjtjd||d:d?d@dAdBddCd |jddDdE|jd?dtjd|dd|d:|jd?ddtjd|dd|d;xp|D]h\} } } d?| } |j| dtjd| d|d:|j| ddtjd| d|d;qWxr| D]j\} }} } d?|d?| }|j|d| d|d<|j|ddtjd| d|d=q Wtj|dFtj}|jdGddHdIdd@dJdK|j|jdLddMdIdd@dJdK|j|j dtjd tj|j dtj d tj d ddS(YNitWM_DELETE_WINDOWcSs |jS(N(tquitcmd(tself((s0/usr/lib64/python2.7/Demo/tix/samples/SHList2.pyt"ttrelieftbditoptionsshlist.columns 3 hlist.header 1texpandtfilltpadxi tpadytsidettixtoptiontgett bold_fontt refwindowtanchoriitfonttheaderititemtypettexttNametstyletPositiontdoesJohn DoetDirectortjeffs Jeff WaxmantManagertjohnsJohn Leetpeters Peter Kensontalexs Alex KellmantClerktalans Alan AdamstandysAndreas CrawfordtSalesmantdougs Douglas Bloomtjons Jon BarakitchrissChris Geoffreytchucks Chuck McLeantCleanertmgr_nametmgr_posnt empl_namet empl_posnt separatort.twidthit drawbranchtindenttcharsit orientationtoktOkt underlineitcommandtcanceltCancel(R sJohn DoeR!(R"s Jeff WaxmanR#(R$sJohn LeeR#(R%s Peter KensonR#(R&R$s Alex KellmanR'(R(R$s Alan AdamsR'(R)R%sAndreas CrawfordR*(R+R"s Douglas BloomR'(R,R%s Jon BarakiR*(R-R"sChris GeoffreyR'(R.R"s Chuck McLeanR/(Rtexittwinfo_toplevelt wm_protocoltTixtFrametRAISEDt ScrolledHListtatpacktBOTHtTOPthlistttktcallt DisplayStyletTEXTtCENTERt header_createt column_widthtconfigtaddt item_createt ButtonBoxt HORIZONTALtokcmdRtBOTTOMtX(RtwtzttopRLtboldfontRtbosstmanagerst employeestkeytnametposntetmgrt entrypathtbox((s0/usr/lib64/python2.7/Demo/tix/samples/SHList2.pyt__init__sp   1 "    """ "     cCs|jdS(N(R(R((s0/usr/lib64/python2.7/Demo/tix/samples/SHList2.pyRYscCs d|_dS(Ni(RA(R((s0/usr/lib64/python2.7/Demo/tix/samples/SHList2.pyRscCs-x&|jdkr(|jjjtqWdS(Ni(RARRMt dooneeventtTCL_ALL_EVENTS(R((s0/usr/lib64/python2.7/Demo/tix/samples/SHList2.pyRscCs|jjdS(N(RR(R((s0/usr/lib64/python2.7/Demo/tix/samples/SHList2.pyRs(t__name__t __module__RjRYRRR(((s0/usr/lib64/python2.7/Demo/tix/samples/SHList2.pyRs  x   t__main__((RDRlRRRmtTkR(((s0/usr/lib64/python2.7/Demo/tix/samples/SHList2.pyts    PK%L]07bbtix/samples/OptMenu.pyonu[ ^c@szddlZidd6dd6dd6dd 6d d 6Zd Zd ZedkrvejZeeejndS(iNs Plain Textttextt PostScripttposttHTMLthtmltLaTeXttexsRich Text Formattrtfc Cstjatjatj|dddtj}tj|dddtdd}tj|dd dtdd}xBtjD]4}|j |dt||j |dt|qWtj d tj d |j d tj d tj dddd|j d tj d tj ddddtj|dtj}|jdddddddd|d|jdddddddd|d|j d tjdtj|j d tj dtjdddS( NtbditrelieftlabelsFrom File Format : tvariabletoptionss2label.width 19 label.anchor e menubutton.width 15sTo File Format : RRtsidetanchortpadyitpadxit orientationtokRtOkt underlineitwidthtcommandcSs t|S(N(t ok_command(tw((s0/usr/lib64/python2.7/Demo/tix/samples/OptMenu.pyt7ttcanceltCancelcSs |jS(N(tdestroy(R((s0/usr/lib64/python2.7/Demo/tix/samples/OptMenu.pyR9Rtfilltexpand(tTixt StringVart demo_opt_fromt demo_opt_totFrametRAISEDt OptionMenuR tkeyst add_commandtsettpacktTOPtWt ButtonBoxt HORIZONTALtaddtBOTTOMtXtBOTH(Rttopt from_filetto_filetopttbox((s0/usr/lib64/python2.7/Demo/tix/samples/OptMenu.pyt RunSamples.      ((  cCs|jdS(N(R(R((s0/usr/lib64/python2.7/Demo/tix/samples/OptMenu.pyR=st__main__(R R R8Rt__name__tTktroottmainloop(((s0/usr/lib64/python2.7/Demo/tix/samples/OptMenu.pyts  (    PK%L]-tix/samples/PanedWin.pynu[# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- # # $Id$ # # Tix Demonstration Program # # This sample program is structured in such a way so that it can be # executed from the Tix demo program "tixwidgets.py": it must have a # procedure called "RunSample". It should also have the "if" statment # at the end of this file so that it can be run as a standalone # program. # This file demonstrates the use of the tixPanedWindow widget. This program # is a dummy news reader: the user can adjust the sizes of the list # of artical names and the size of the text widget that shows the body # of the article. import Tix TCL_ALL_EVENTS = 0 def RunSample (root): panedwin = DemoPanedwin(root) panedwin.mainloop() panedwin.destroy() class DemoPanedwin: def __init__(self, w): self.root = w self.exit = -1 z = w.winfo_toplevel() z.wm_protocol("WM_DELETE_WINDOW", lambda self=self: self.quitcmd()) group = Tix.LabelEntry(w, label='Newsgroup:', options='entry.width 25') group.entry.insert(0,'comp.lang.python') pane = Tix.PanedWindow(w, orientation='vertical') p1 = pane.add('list', min=70, size=100) p2 = pane.add('text', min=70) list = Tix.ScrolledListBox(p1) list.listbox['width'] = 80 list.listbox['height'] = 5 text = Tix.ScrolledText(p2) text.text['width'] = 80 text.text['height'] = 20 list.listbox.insert(Tix.END, " 12324 Re: Tkinter is good for your health") list.listbox.insert(Tix.END, "+ 12325 Re: Tkinter is good for your health") list.listbox.insert(Tix.END, "+ 12326 Re: Tix is even better for your health (Was: Tkinter is good...)") list.listbox.insert(Tix.END, " 12327 Re: Tix is even better for your health (Was: Tkinter is good...)") list.listbox.insert(Tix.END, "+ 12328 Re: Tix is even better for your health (Was: Tkinter is good...)") list.listbox.insert(Tix.END, " 12329 Re: Tix is even better for your health (Was: Tkinter is good...)") list.listbox.insert(Tix.END, "+ 12330 Re: Tix is even better for your health (Was: Tkinter is good...)") text.text['bg'] = list.listbox['bg'] text.text['wrap'] = 'none' text.text.insert(Tix.END, """ Mon, 19 Jun 1995 11:39:52 comp.lang.python Thread 34 of 220 Lines 353 A new way to put text and bitmaps together iNo responses ioi@blue.seas.upenn.edu Ioi K. Lam at University of Pennsylvania Hi, I have implemented a new image type called "compound". It allows you to glue together a bunch of bitmaps, images and text strings together to form a bigger image. Then you can use this image with widgets that support the -image option. For example, you can display a text string string together with a bitmap, at the same time, inside a TK button widget. """) text.text['state'] = 'disabled' list.pack(expand=1, fill=Tix.BOTH, padx=4, pady=6) text.pack(expand=1, fill=Tix.BOTH, padx=4, pady=6) group.pack(side=Tix.TOP, padx=3, pady=3, fill=Tix.BOTH) pane.pack(side=Tix.TOP, padx=3, pady=3, fill=Tix.BOTH, expand=1) box = Tix.ButtonBox(w, orientation=Tix.HORIZONTAL) box.add('ok', text='Ok', underline=0, width=6, command=self.quitcmd) box.add('cancel', text='Cancel', underline=0, width=6, command=self.quitcmd) box.pack(side=Tix.BOTTOM, fill=Tix.X) def quitcmd (self): self.exit = 0 def mainloop(self): while self.exit < 0: self.root.tk.dooneevent(TCL_ALL_EVENTS) def destroy (self): self.root.destroy() if __name__ == '__main__': root = Tix.Tk() RunSample(root) PK%L]!tix/samples/BtnBox.pynu[# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- # # $Id$ # # Tix Demonstration Program # # This sample program is structured in such a way so that it can be # executed from the Tix demo program "tixwidgets.py": it must have a # procedure called "RunSample". It should also have the "if" statment # at the end of this file so that it can be run as a standalone # program. # This file demonstrates the use of the tixButtonBox widget, which is a # group of TK buttons. You can use it to manage the buttons in a dialog box, # for example. # import Tix def RunSample(w): # Create the label on the top of the dialog box # top = Tix.Label(w, padx=20, pady=10, bd=1, relief=Tix.RAISED, anchor=Tix.CENTER, text='This dialog box is\n a demonstration of the\n tixButtonBox widget') # Create the button box and add a few buttons in it. Set the # -width of all the buttons to the same value so that they # appear in the same size. # # Note that the -text, -underline, -command and -width options are all # standard options of the button widgets. # box = Tix.ButtonBox(w, orientation=Tix.HORIZONTAL) box.add('ok', text='OK', underline=0, width=5, command=lambda w=w: w.destroy()) box.add('close', text='Cancel', underline=0, width=5, command=lambda w=w: w.destroy()) box.pack(side=Tix.BOTTOM, fill=Tix.X) top.pack(side=Tix.TOP, fill=Tix.BOTH, expand=1) if __name__ == '__main__': root = Tix.Tk() RunSample(root) root.mainloop() PK%L]D*_ _ tix/samples/NoteBook.pyonu[ ^c@sZddlZdZdZdZedkrVejaettjndS(iNc Cs)|atj|}|r(d|}nd}|j|dd|j|dd|j|dtj|j|dd tj|d d d d dd }d|ds  T    PK%L]B~ gtix/samples/SHList2.pyonu[ ^c@sWddlZdZdZdddYZedkrSejZeendS(iNicCs$t|}|j|jdS(N(t DemoSHListtmainlooptdestroy(troottshlist((s0/usr/lib64/python2.7/Demo/tix/samples/SHList2.pyt RunSamples  RcBs5eZdZdZdZdZdZRS(c Cs%||_d|_|j}|jd|dtj|dtjdd}tj|dd|_|jj d dd tj d d d d dtj |jj }|j jdddd}i}tjtjd|dtjd dd dd||d<|jddtjddd|d|jddtjddd|d|jdddN}dOdPdQg}dRdSdTdUdVdWdXg} tjtjd||d:d?d@dAdBddCd |jddDdE|jd?dtjd|dd|d:|jd?ddtjd|dd|d;xp|D]h\} } } d?| } |j| dtjd| d|d:|j| ddtjd| d|d;qWxr| D]j\} }} } d?|d?| }|j|d| d|d<|j|ddtjd| d|d=q Wtj|dFtj}|jdGddHdIdd@dJdK|j|jdLddMdIdd@dJdK|j|j dtjd tj|j dtj d tj d ddS(YNitWM_DELETE_WINDOWcSs |jS(N(tquitcmd(tself((s0/usr/lib64/python2.7/Demo/tix/samples/SHList2.pyt"ttrelieftbditoptionsshlist.columns 3 hlist.header 1texpandtfilltpadxi tpadytsidettixtoptiontgett bold_fontt refwindowtanchoriitfonttheaderititemtypettexttNametstyletPositiontdoesJohn DoetDirectortjeffs Jeff WaxmantManagertjohnsJohn Leetpeters Peter Kensontalexs Alex KellmantClerktalans Alan AdamstandysAndreas CrawfordtSalesmantdougs Douglas Bloomtjons Jon BarakitchrissChris Geoffreytchucks Chuck McLeantCleanertmgr_nametmgr_posnt empl_namet empl_posnt separatort.twidthit drawbranchtindenttcharsit orientationtoktOkt underlineitcommandtcanceltCancel(R sJohn DoeR!(R"s Jeff WaxmanR#(R$sJohn LeeR#(R%s Peter KensonR#(R&R$s Alex KellmanR'(R(R$s Alan AdamsR'(R)R%sAndreas CrawfordR*(R+R"s Douglas BloomR'(R,R%s Jon BarakiR*(R-R"sChris GeoffreyR'(R.R"s Chuck McLeanR/(Rtexittwinfo_toplevelt wm_protocoltTixtFrametRAISEDt ScrolledHListtatpacktBOTHtTOPthlistttktcallt DisplayStyletTEXTtCENTERt header_createt column_widthtconfigtaddt item_createt ButtonBoxt HORIZONTALtokcmdRtBOTTOMtX(RtwtzttopRLtboldfontRtbosstmanagerst employeestkeytnametposntetmgrt entrypathtbox((s0/usr/lib64/python2.7/Demo/tix/samples/SHList2.pyt__init__sp   1 "    """ "     cCs|jdS(N(R(R((s0/usr/lib64/python2.7/Demo/tix/samples/SHList2.pyRYscCs d|_dS(Ni(RA(R((s0/usr/lib64/python2.7/Demo/tix/samples/SHList2.pyRscCs-x&|jdkr(|jjjtqWdS(Ni(RARRMt dooneeventtTCL_ALL_EVENTS(R((s0/usr/lib64/python2.7/Demo/tix/samples/SHList2.pyRscCs|jjdS(N(RR(R((s0/usr/lib64/python2.7/Demo/tix/samples/SHList2.pyRs(t__name__t __module__RjRYRRR(((s0/usr/lib64/python2.7/Demo/tix/samples/SHList2.pyRs  x   t__main__((RDRlRRRmtTkR(((s0/usr/lib64/python2.7/Demo/tix/samples/SHList2.pyts    PK%L]aatix/samples/SHList1.pycnu[ ^c@sWddlZdZdZdddYZedkrSejZeendS(iNicCs$t|}|j|jdS(N(t DemoSHListtmainlooptdestroy(troottshlist((s0/usr/lib64/python2.7/Demo/tix/samples/SHList1.pyt RunSamples  RcBs5eZdZdZdZdZdZRS(c Cst||_d|_|j}|jd|dtj|dtjdd}tj||_|jj dddtj d d d d d tj d9d:d;g}d<d=d>d?d@dAdBg}|jj }|j d!d"d#d$d%d&d'd d&}x|D]\}} |retj|d(d)|d*d+d#d,dd+dtj} |jd-tjd.| d/tjn|j|d-tjd0| |d}qWx8|D]0\} }} |d"| } |j| d0| qWtj|d1tj} | jd2d0d3d4d&d#d5d6|j| jd7d0d8d4d&d#d5d6|j| j d tjdtj|j d tj dtj dddS(CNitWM_DELETE_WINDOWcSs |jS(N(tquitcmd(tself((s0/usr/lib64/python2.7/Demo/tix/samples/SHList1.pytttrelieftbditexpandtfilltpadxi tpadytsidetjeffs Jeff WaxmantjohnsJohn Leetpeters Peter Kensontalexs Alex Kellmantalans Alan AdamstandysAndreas Crawfordtdougs Douglas Bloomtjons Jon BarakitchrissChris Geoffreytchucks Chuck McLeant separatort.twidthit drawbranchitindenttnamessep%dtheightiititemtypetwindowtstatettextt orientationtoktOkt underlineitcommandtcanceltCancel(Rs Jeff Waxman(RsJohn Lee(Rs Peter Kenson(RRs Alex Kellman(RRs Alan Adams(RRsAndreas Crawford(RRs Douglas Bloom(RRs Jon Baraki(RRsChris Geoffrey(RRs Chuck McLean(Rtexittwinfo_toplevelt wm_protocoltTixtFrametRAISEDt ScrolledHListtatpacktBOTHtTOPthlisttconfigtSUNKENt add_childtWINDOWtDISABLEDtaddtTEXTt ButtonBoxt HORIZONTALtokcmdRtBOTTOMtX(Rtwtzttoptbossest employeesR9tcounttbossR!tftpersontkeytbox((s0/usr/lib64/python2.7/Demo/tix/samples/SHList1.pyt__init__sL   1   ""  cCs|jdS(N(R(R((s0/usr/lib64/python2.7/Demo/tix/samples/SHList1.pyRCpscCs d|_dS(Ni(R.(R((s0/usr/lib64/python2.7/Demo/tix/samples/SHList1.pyRsscCs-x&|jdkr(|jjjtqWdS(Ni(R.Rttkt dooneeventtTCL_ALL_EVENTS(R((s0/usr/lib64/python2.7/Demo/tix/samples/SHList1.pyRvscCs|jjdS(N(RR(R((s0/usr/lib64/python2.7/Demo/tix/samples/SHList1.pyRzs(t__name__t __module__RQRCRRR(((s0/usr/lib64/python2.7/Demo/tix/samples/SHList1.pyRs  V   t__main__((R1RTRRRUtTkR(((s0/usr/lib64/python2.7/Demo/tix/samples/SHList1.pyts  h  PK%L]m7&~~tix/samples/SHList1.pynu[# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- # # $Id$ # # Tix Demonstration Program # # This sample program is structured in such a way so that it can be # executed from the Tix demo program "tixwidgets.py": it must have a # procedure called "RunSample". It should also have the "if" statment # at the end of this file so that it can be run as a standalone # program using tixwish. # This file demonstrates the use of the tixScrolledHList widget. # import Tix TCL_ALL_EVENTS = 0 def RunSample (root): shlist = DemoSHList(root) shlist.mainloop() shlist.destroy() class DemoSHList: def __init__(self, w): self.root = w self.exit = -1 z = w.winfo_toplevel() z.wm_protocol("WM_DELETE_WINDOW", lambda self=self: self.quitcmd()) # We create the frame and the ScrolledHList widget # at the top of the dialog box # top = Tix.Frame( w, relief=Tix.RAISED, bd=1) # Put a simple hierachy into the HList (two levels). Use colors and # separator widgets (frames) to make the list look fancy # top.a = Tix.ScrolledHList(top) top.a.pack( expand=1, fill=Tix.BOTH, padx=10, pady=10, side=Tix.TOP) # This is our little relational database # bosses = [ ('jeff', 'Jeff Waxman'), ('john', 'John Lee'), ('peter', 'Peter Kenson') ] employees = [ ('alex', 'john', 'Alex Kellman'), ('alan', 'john', 'Alan Adams'), ('andy', 'peter', 'Andreas Crawford'), ('doug', 'jeff', 'Douglas Bloom'), ('jon', 'peter', 'Jon Baraki'), ('chris', 'jeff', 'Chris Geoffrey'), ('chuck', 'jeff', 'Chuck McLean') ] hlist=top.a.hlist # Let configure the appearance of the HList subwidget # hlist.config( separator='.', width=25, drawbranch=0, indent=10) count=0 for boss,name in bosses : if count : f=Tix.Frame(hlist, name='sep%d' % count, height=2, width=150, bd=2, relief=Tix.SUNKEN ) hlist.add_child( itemtype=Tix.WINDOW, window=f, state=Tix.DISABLED ) hlist.add(boss, itemtype=Tix.TEXT, text=name) count = count+1 for person,boss,name in employees : # '.' is the separator character we chose above # key= boss + '.' + person # ^^^^ ^^^^^^ # parent entryPath / child's name hlist.add( key, text=name ) # [Hint] Make sure the keys (e.g. 'boss.person') you choose # are unique names. If you cannot be sure of this (because of # the structure of your database, e.g.) you can use the # "add_child" command instead: # # hlist.addchild( boss, text=name) # ^^^^ # parent entryPath # Use a ButtonBox to hold the buttons. # box= Tix.ButtonBox(top, orientation=Tix.HORIZONTAL ) box.add( 'ok', text='Ok', underline=0, width=6, command = self.okcmd) box.add( 'cancel', text='Cancel', underline=0, width=6, command = self.quitcmd) box.pack( side=Tix.BOTTOM, fill=Tix.X) top.pack( side=Tix.TOP, fill=Tix.BOTH, expand=1 ) def okcmd (self): self.quitcmd() def quitcmd (self): self.exit = 0 def mainloop(self): while self.exit < 0: self.root.tk.dooneevent(TCL_ALL_EVENTS) def destroy (self): self.root.destroy() # This "if" statement makes it possible to run this script file inside or # outside of the main demo program "tixwidgets.py". # if __name__== '__main__' : root=Tix.Tk() RunSample(root) PK%L]7:BBtix/samples/BtnBox.pyonu[ ^c@sHddlZdZedkrDejZeeejndS(iNcCstj|dddddddtjdtjd d }tj|d tj}|jd d d ddddd|d|jdd dddddd|d|jdtjdtj |jdtj dtj dddS(Ntpadxitpadyi tbditrelieftanchorttexts?This dialog box is a demonstration of the tixButtonBox widgett orientationtoktOKt underlineitwidthitcommandcSs |jS(N(tdestroy(tw((s//usr/lib64/python2.7/Demo/tix/samples/BtnBox.pyt#ttclosetCancelcSs |jS(N(R (R ((s//usr/lib64/python2.7/Demo/tix/samples/BtnBox.pyR%Rtsidetfilltexpand( tTixtLabeltRAISEDtCENTERt ButtonBoxt HORIZONTALtaddtpacktBOTTOMtXtTOPtBOTH(R ttoptbox((s//usr/lib64/python2.7/Demo/tix/samples/BtnBox.pyt RunSamples'   t__main__(RR#t__name__tTktroottmainloop(((s//usr/lib64/python2.7/Demo/tix/samples/BtnBox.pyts     PK%L]?Þtix/samples/CmpImg.pyonu[ ^c@s`ddlZdZdZdZdZdZedkr\ejZeeej ndS(iNs/* XPM */ static char * netw_xpm[] = { /* width height ncolors chars_per_pixel */ "32 32 7 1", /* colors */ " s None c None", ". c #000000000000", "X c white", "o c #c000c000c000", "O c #404040", "+ c blue", "@ c red", /* pixels */ " ", " .............. ", " .XXXXXXXXXXXX. ", " .XooooooooooO. ", " .Xo.......XoO. ", " .Xo.++++o+XoO. ", " .Xo.++++o+XoO. ", " .Xo.++oo++XoO. ", " .Xo.++++++XoO. ", " .Xo.+o++++XoO. ", " .Xo.++++++XoO. ", " .Xo.XXXXXXXoO. ", " .XooooooooooO. ", " .Xo@ooo....oO. ", " .............. .XooooooooooO. ", " .XXXXXXXXXXXX. .XooooooooooO. ", " .XooooooooooO. .OOOOOOOOOOOO. ", " .Xo.......XoO. .............. ", " .Xo.++++o+XoO. @ ", " .Xo.++++o+XoO. @ ", " .Xo.++oo++XoO. @ ", " .Xo.++++++XoO. @ ", " .Xo.+o++++XoO. @ ", " .Xo.++++++XoO. ..... ", " .Xo.XXXXXXXoO. .XXX. ", " .XooooooooooO.@@@@@@.X O. ", " .Xo@ooo....oO. .OOO. ", " .XooooooooooO. ..... ", " .XooooooooooO. ", " .OOOOOOOOOOOO. ", " .............. ", " "}; su/* XPM */ static char * drivea_xpm[] = { /* width height ncolors chars_per_pixel */ "32 32 5 1", /* colors */ " s None c None", ". c #000000000000", "X c white", "o c #c000c000c000", "O c #800080008000", /* pixels */ " ", " ", " ", " ", " ", " ", " ", " ", " ", " .......................... ", " .XXXXXXXXXXXXXXXXXXXXXXXo. ", " .XooooooooooooooooooooooO. ", " .Xooooooooooooooooo..oooO. ", " .Xooooooooooooooooo..oooO. ", " .XooooooooooooooooooooooO. ", " .Xoooooooo.......oooooooO. ", " .Xoo...................oO. ", " .Xoooooooo.......oooooooO. ", " .XooooooooooooooooooooooO. ", " .XooooooooooooooooooooooO. ", " .XooooooooooooooooooooooO. ", " .XooooooooooooooooooooooO. ", " .oOOOOOOOOOOOOOOOOOOOOOOO. ", " .......................... ", " ", " ", " ", " ", " ", " ", " ", " "}; su #define netw_width 32 #define netw_height 32 static unsigned char netw_bits[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x7f, 0x00, 0x00, 0x02, 0x40, 0x00, 0x00, 0xfa, 0x5f, 0x00, 0x00, 0x0a, 0x50, 0x00, 0x00, 0x0a, 0x52, 0x00, 0x00, 0x0a, 0x52, 0x00, 0x00, 0x8a, 0x51, 0x00, 0x00, 0x0a, 0x50, 0x00, 0x00, 0x4a, 0x50, 0x00, 0x00, 0x0a, 0x50, 0x00, 0x00, 0x0a, 0x50, 0x00, 0x00, 0xfa, 0x5f, 0x00, 0x00, 0x02, 0x40, 0xfe, 0x7f, 0x52, 0x55, 0x02, 0x40, 0xaa, 0x6a, 0xfa, 0x5f, 0xfe, 0x7f, 0x0a, 0x50, 0xfe, 0x7f, 0x0a, 0x52, 0x80, 0x00, 0x0a, 0x52, 0x80, 0x00, 0x8a, 0x51, 0x80, 0x00, 0x0a, 0x50, 0x80, 0x00, 0x4a, 0x50, 0x80, 0x00, 0x0a, 0x50, 0xe0, 0x03, 0x0a, 0x50, 0x20, 0x02, 0xfa, 0xdf, 0x3f, 0x03, 0x02, 0x40, 0xa0, 0x02, 0x52, 0x55, 0xe0, 0x03, 0xaa, 0x6a, 0x00, 0x00, 0xfe, 0x7f, 0x00, 0x00, 0xfe, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; s{ #define drivea_width 32 #define drivea_height 32 static unsigned char drivea_bits[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0xff, 0x1f, 0x08, 0x00, 0x00, 0x18, 0xa8, 0xaa, 0xaa, 0x1a, 0x48, 0x55, 0xd5, 0x1d, 0xa8, 0xaa, 0xaa, 0x1b, 0x48, 0x55, 0x55, 0x1d, 0xa8, 0xfa, 0xaf, 0x1a, 0xc8, 0xff, 0xff, 0x1d, 0xa8, 0xfa, 0xaf, 0x1a, 0x48, 0x55, 0x55, 0x1d, 0xa8, 0xaa, 0xaa, 0x1a, 0x48, 0x55, 0x55, 0x1d, 0xa8, 0xaa, 0xaa, 0x1a, 0xf8, 0xff, 0xff, 0x1f, 0xf8, 0xff, 0xff, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; c Cstjddt|_|js<tjddt|_ntjddt|_|jsxtjddt|_ntj|dddddd }tj|dddddd }tjd d ||_ |j j j t |j d d |j j j t |j d ddddd|j j j t |j d ddd|j j j t |j d dd|j|j |dttsidei tfilltexpand(tTixtImagetnetwork_pixmaptimg0tnetwork_bitmapthard_disk_pixmaptimg1thard_disk_bitmaptButtonthdd_imgttktcalltstrtnet_imgtpacktLEFTtY(Rthddtnettclose((s//usr/lib64/python2.7/Demo/tix/samples/CmpImg.pyt RunSamples6  !!"$ (+ "$ (+ ..t__main__( RRRRR R-t__name__tTktroottmainloop(((s//usr/lib64/python2.7/Demo/tix/samples/CmpImg.pyts /- /   PK%L] ttix/samples/DirTree.pyonu[ ^c@syddlZddlZddlZddlTdZdZdddYZedkruejZ ee ndS( iN(t*icCs$t|}|j|jdS(N(t DemoDirTreetmainlooptdestroy(troottdirtree((s0/usr/lib64/python2.7/Demo/tix/samples/DirTree.pyt RunSamples  RcBs>eZdZdZdZdZdZdZRS(c Cs>||_d|_|j}|jd|dtj|dtdd}tj||_d|jj d#ttrelieftbdii(twidthttexts >> tpadyitlabelsInstallation Directory:t labelsidettoptoptionss entry.width 40 label.anchor w t textvariablecSs|j||S(N(t copy_name(tdirtentR ((s0/usr/lib64/python2.7/Demo/tix/samples/DirTree.pyR FstcommandscSs |jS(N(tokcmd(R ((s0/usr/lib64/python2.7/Demo/tix/samples/DirTree.pyR IR texpandtyestfilltbothtsidetpadxitanchortst orientationt horizontaltoktOkt underlineicSs |jS(N(R(R ((s0/usr/lib64/python2.7/Demo/tix/samples/DirTree.pyR TR tcanceltCancelcSs |jS(N(R(R ((s0/usr/lib64/python2.7/Demo/tix/samples/DirTree.pyR VR tx(Rtexittwinfo_toplevelt wm_protocoltTixtFrametRAISEDtDirTreeRthlisttButtontbtnt LabelEntryRtcopytostcurdirt dlist_dirtentrytbindtpacktTOPtBOTHtLEFTtXt ButtonBoxtaddtBOTTOM(R twtzRtbox((s0/usr/lib64/python2.7/Demo/tix/samples/DirTree.pyt__init__s2    +%1  cCs?|jd|_|jjdd|jjd|jdS(Ntvalueitend(tcgetR9R:tdeletetinsert(R RR((s0/usr/lib64/python2.7/Demo/tix/samples/DirTree.pyRZscCs|jdS(N(R(R ((s0/usr/lib64/python2.7/Demo/tix/samples/DirTree.pyRascCs d|_dS(Ni(R+(R ((s0/usr/lib64/python2.7/Demo/tix/samples/DirTree.pyRescCs-x&|jdkr(|jjjtqWdS(Ni(R+Rttkt dooneeventtTCL_ALL_EVENTS(R ((s0/usr/lib64/python2.7/Demo/tix/samples/DirTree.pyRiscCs|jjdS(N(RR(R ((s0/usr/lib64/python2.7/Demo/tix/samples/DirTree.pyRms(t__name__t __module__RGRRRRR(((s0/usr/lib64/python2.7/Demo/tix/samples/DirTree.pyRs  <    t__main__(( R.R7R6t TkconstantsRORRRPtTkR(((s0/usr/lib64/python2.7/Demo/tix/samples/DirTree.pyts$  V  PK%L]zd3 3 tix/samples/Tree.pyonu[ ^c@sfddlZddlZdZdZdZedkrbejZeeejndS(iNc Cs+tj|dtjdd}tj|dd}|jdddtjdd d d d tjd|d |d ttopencmdt/t orientationtokttexttOkt underlineitcommandtwidthitcanceltCancel(tTixtFrametRAISEDtTreetpacktBOTHtLEFTtNonetadddirt ButtonBoxt HORIZONTALtaddtdestroytBOTTOMtXtTOP(R ttopttreetbox((s-/usr/lib64/python2.7/Demo/tix/samples/Tree.pyt RunSamples. ((c Cs|dkrd}ntjj|}|jj|dtjd|d|jjdddy!tj ||j |dWntj k rnXdS( NRtitemtypeRtimagettixtgetimagetfoldertopen( tostpathtbasenamethlistR#Rt IMAGETEXTttktcalltlistdirtsetmodeterror(R)R R((s-/usr/lib64/python2.7/Demo/tix/samples/Tree.pyR #s   c Cs|jj|}|r<x!|D]}|jj|qWntj|}x|D]w}tjj|d|rt||d|qR|jj|d|dt j d|d|j j dddqRWdS(NRR,RR-R.R/tfile( R5t info_childrent show_entryR2R9R3tisdirR R#RR6R7R8(R)R tentriestentrytfilesR<((s-/usr/lib64/python2.7/Demo/tix/samples/Tree.pyR9s  &t__main__( RR2R+R Rt__name__tTktroottmainloop(((s-/usr/lib64/python2.7/Demo/tix/samples/Tree.pyts      PK%L]sRgtix/samples/SHList2.pynu[# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- # # $Id$ # # Tix Demonstration Program # # This sample program is structured in such a way so that it can be # executed from the Tix demo program "tixwidget": it must have a # procedure called "RunSample". It should also have the "if" statment # at the end of this file so that it can be run as a standalone # program using tixwish. # This file demonstrates how to use multiple columns and multiple styles # in the tixHList widget # # In a tixHList widget, you can have one ore more columns. # import Tix TCL_ALL_EVENTS = 0 def RunSample (root): shlist = DemoSHList(root) shlist.mainloop() shlist.destroy() class DemoSHList: def __init__(self, w): self.root = w self.exit = -1 z = w.winfo_toplevel() z.wm_protocol("WM_DELETE_WINDOW", lambda self=self: self.quitcmd()) # We create the frame and the ScrolledHList widget # at the top of the dialog box # top = Tix.Frame( w, relief=Tix.RAISED, bd=1) # Put a simple hierachy into the HList (two levels). Use colors and # separator widgets (frames) to make the list look fancy # top.a = Tix.ScrolledHList(top, options='hlist.columns 3 hlist.header 1' ) top.a.pack( expand=1, fill=Tix.BOTH, padx=10, pady=10, side=Tix.TOP) hlist=top.a.hlist # Create the title for the HList widget # >> Notice that we have set the hlist.header subwidget option to true # so that the header is displayed # boldfont=hlist.tk.call('tix','option','get','bold_font') # First some styles for the headers style={} style['header'] = Tix.DisplayStyle(Tix.TEXT, refwindow=hlist, anchor=Tix.CENTER, padx=8, pady=2, font = boldfont ) hlist.header_create(0, itemtype=Tix.TEXT, text='Name', style=style['header']) hlist.header_create(1, itemtype=Tix.TEXT, text='Position', style=style['header']) # Notice that we use 3 columns in the hlist widget. This way when the user # expands the windows wide, the right side of the header doesn't look # chopped off. The following line ensures that the 3 column header is # not shown unless the hlist window is wider than its contents. # hlist.column_width(2,0) # This is our little relational database # boss = ('doe', 'John Doe', 'Director') managers = [ ('jeff', 'Jeff Waxman', 'Manager'), ('john', 'John Lee', 'Manager'), ('peter', 'Peter Kenson', 'Manager') ] employees = [ ('alex', 'john', 'Alex Kellman', 'Clerk'), ('alan', 'john', 'Alan Adams', 'Clerk'), ('andy', 'peter', 'Andreas Crawford', 'Salesman'), ('doug', 'jeff', 'Douglas Bloom', 'Clerk'), ('jon', 'peter', 'Jon Baraki', 'Salesman'), ('chris', 'jeff', 'Chris Geoffrey', 'Clerk'), ('chuck', 'jeff', 'Chuck McLean', 'Cleaner') ] style['mgr_name'] = Tix.DisplayStyle(Tix.TEXT, refwindow=hlist) style['mgr_posn'] = Tix.DisplayStyle(Tix.TEXT, padx=8, refwindow=hlist) style['empl_name'] = Tix.DisplayStyle(Tix.TEXT, refwindow=hlist) style['empl_posn'] = Tix.DisplayStyle(Tix.TEXT, padx=8, refwindow=hlist) # Let configure the appearance of the HList subwidget # hlist.config(separator='.', width=25, drawbranch=0, indent=10) hlist.column_width(0, chars=20) # Create the boss # hlist.add ('.', itemtype=Tix.TEXT, text=boss[1], style=style['mgr_name']) hlist.item_create('.', 1, itemtype=Tix.TEXT, text=boss[2], style=style['mgr_posn']) # Create the managers # for key,name,posn in managers : e= '.'+ key hlist.add(e, itemtype=Tix.TEXT, text=name, style=style['mgr_name']) hlist.item_create(e, 1, itemtype=Tix.TEXT, text=posn, style=style['mgr_posn']) for key,mgr,name,posn in employees : # "." is the separator character we chose above entrypath = '.' + mgr + '.' + key # ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ # parent entryPath / child's name hlist.add(entrypath, text=name, style=style['empl_name']) hlist.item_create(entrypath, 1, itemtype=Tix.TEXT, text = posn, style = style['empl_posn'] ) # Use a ButtonBox to hold the buttons. # box= Tix.ButtonBox(top, orientation=Tix.HORIZONTAL ) box.add( 'ok', text='Ok', underline=0, width=6, command = self.okcmd ) box.add( 'cancel', text='Cancel', underline=0, width=6, command = self.quitcmd ) box.pack( side=Tix.BOTTOM, fill=Tix.X) top.pack( side=Tix.TOP, fill=Tix.BOTH, expand=1 ) def okcmd (self): self.quitcmd() def quitcmd (self): self.exit = 0 def mainloop(self): while self.exit < 0: self.root.tk.dooneevent(TCL_ALL_EVENTS) def destroy (self): self.root.destroy() # This "if" statement makes it possible to run this script file inside or # outside of the main demo program "tixwidgets.py". # if __name__== '__main__' : root=Tix.Tk() RunSample(root) PK%L]zd3 3 tix/samples/Tree.pycnu[ ^c@sfddlZddlZdZdZdZedkrbejZeeejndS(iNc Cs+tj|dtjdd}tj|dd}|jdddtjdd d d d tjd|d |d ttopencmdt/t orientationtokttexttOkt underlineitcommandtwidthitcanceltCancel(tTixtFrametRAISEDtTreetpacktBOTHtLEFTtNonetadddirt ButtonBoxt HORIZONTALtaddtdestroytBOTTOMtXtTOP(R ttopttreetbox((s-/usr/lib64/python2.7/Demo/tix/samples/Tree.pyt RunSamples. ((c Cs|dkrd}ntjj|}|jj|dtjd|d|jjdddy!tj ||j |dWntj k rnXdS( NRtitemtypeRtimagettixtgetimagetfoldertopen( tostpathtbasenamethlistR#Rt IMAGETEXTttktcalltlistdirtsetmodeterror(R)R R((s-/usr/lib64/python2.7/Demo/tix/samples/Tree.pyR #s   c Cs|jj|}|r<x!|D]}|jj|qWntj|}x|D]w}tjj|d|rt||d|qR|jj|d|dt j d|d|j j dddqRWdS(NRR,RR-R.R/tfile( R5t info_childrent show_entryR2R9R3tisdirR R#RR6R7R8(R)R tentriestentrytfilesR<((s-/usr/lib64/python2.7/Demo/tix/samples/Tree.pyR9s  &t__main__( RR2R+R Rt__name__tTktroottmainloop(((s-/usr/lib64/python2.7/Demo/tix/samples/Tree.pyts      PK%L]Satix/samples/DirList.pynu[# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- # # $Id$ # # Tix Demonstration Program # # This sample program is structured in such a way so that it can be # executed from the Tix demo program "tixwidgets.py": it must have a # procedure called "RunSample". It should also have the "if" statment # at the end of this file so that it can be run as a standalone # program using tixwish. # This file demonstrates the use of the tixDirList widget -- you can # use it for the user to select a directory. For example, an installation # program can use the tixDirList widget to ask the user to select the # installation directory for an application. # import Tix, os, copy from Tkconstants import * TCL_ALL_EVENTS = 0 def RunSample (root): dirlist = DemoDirList(root) dirlist.mainloop() dirlist.destroy() class DemoDirList: def __init__(self, w): self.root = w self.exit = -1 z = w.winfo_toplevel() z.wm_protocol("WM_DELETE_WINDOW", lambda self=self: self.quitcmd()) # Create the tixDirList and the tixLabelEntry widgets on the on the top # of the dialog box # bg = root.tk.eval('tix option get bg') # adding bg=bg crashes Windows pythonw tk8.3.3 Python 2.1.0 top = Tix.Frame( w, relief=RAISED, bd=1) # Create the DirList widget. By default it will show the current # directory # # top.dir = Tix.DirList(top) top.dir.hlist['width'] = 40 # When the user presses the ".." button, the selected directory # is "transferred" into the entry widget # top.btn = Tix.Button(top, text = " >> ", pady = 0) # We use a LabelEntry to hold the installation directory. The user # can choose from the DirList widget, or he can type in the directory # manually # top.ent = Tix.LabelEntry(top, label="Installation Directory:", labelside = 'top', options = ''' entry.width 40 label.anchor w ''') font = self.root.tk.eval('tix option get fixed_font') # font = self.root.master.tix_option_get('fixed_font') top.ent.entry['font'] = font self.dlist_dir = copy.copy(os.curdir) # This should work setting the entry's textvariable top.ent.entry['textvariable'] = self.dlist_dir top.btn['command'] = lambda dir=top.dir, ent=top.ent, self=self: \ self.copy_name(dir,ent) # top.ent.entry.insert(0,'tix'+repr(self)) top.ent.entry.bind('', lambda self=self: self.okcmd () ) top.pack( expand='yes', fill='both', side=TOP) top.dir.pack( expand=1, fill=BOTH, padx=4, pady=4, side=LEFT) top.btn.pack( anchor='s', padx=4, pady=4, side=LEFT) top.ent.pack( expand=1, fill=X, anchor='s', padx=4, pady=4, side=LEFT) # Use a ButtonBox to hold the buttons. # box = Tix.ButtonBox (w, orientation='horizontal') box.add ('ok', text='Ok', underline=0, width=6, command = lambda self=self: self.okcmd () ) box.add ('cancel', text='Cancel', underline=0, width=6, command = lambda self=self: self.quitcmd () ) box.pack( anchor='s', fill='x', side=BOTTOM) def copy_name (self, dir, ent): # This should work as it is the entry's textvariable self.dlist_dir = dir.cget('value') # but it isn't so I'll do it manually ent.entry.delete(0,'end') ent.entry.insert(0, self.dlist_dir) def okcmd (self): # tixDemo:Status "You have selected the directory" + self.dlist_dir self.quitcmd() def quitcmd (self): self.exit = 0 def mainloop(self): while self.exit < 0: self.root.tk.dooneevent(TCL_ALL_EVENTS) def destroy (self): self.root.destroy() # This "if" statement makes it possible to run this script file inside or # outside of the main demo program "tixwidgets.py". # if __name__== '__main__' : import tkMessageBox, traceback try: root=Tix.Tk() RunSample(root) except: t, v, tb = sys.exc_info() text = "Error running the demo script:\n" for line in traceback.format_exception(t,v,tb): text = text + line + '\n' d = tkMessageBox.showerror ( 'Tix Demo Error', text) PK%L]?Þtix/samples/CmpImg.pycnu[ ^c@s`ddlZdZdZdZdZdZedkr\ejZeeej ndS(iNs/* XPM */ static char * netw_xpm[] = { /* width height ncolors chars_per_pixel */ "32 32 7 1", /* colors */ " s None c None", ". c #000000000000", "X c white", "o c #c000c000c000", "O c #404040", "+ c blue", "@ c red", /* pixels */ " ", " .............. ", " .XXXXXXXXXXXX. ", " .XooooooooooO. ", " .Xo.......XoO. ", " .Xo.++++o+XoO. ", " .Xo.++++o+XoO. ", " .Xo.++oo++XoO. ", " .Xo.++++++XoO. ", " .Xo.+o++++XoO. ", " .Xo.++++++XoO. ", " .Xo.XXXXXXXoO. ", " .XooooooooooO. ", " .Xo@ooo....oO. ", " .............. .XooooooooooO. ", " .XXXXXXXXXXXX. .XooooooooooO. ", " .XooooooooooO. .OOOOOOOOOOOO. ", " .Xo.......XoO. .............. ", " .Xo.++++o+XoO. @ ", " .Xo.++++o+XoO. @ ", " .Xo.++oo++XoO. @ ", " .Xo.++++++XoO. @ ", " .Xo.+o++++XoO. @ ", " .Xo.++++++XoO. ..... ", " .Xo.XXXXXXXoO. .XXX. ", " .XooooooooooO.@@@@@@.X O. ", " .Xo@ooo....oO. .OOO. ", " .XooooooooooO. ..... ", " .XooooooooooO. ", " .OOOOOOOOOOOO. ", " .............. ", " "}; su/* XPM */ static char * drivea_xpm[] = { /* width height ncolors chars_per_pixel */ "32 32 5 1", /* colors */ " s None c None", ". c #000000000000", "X c white", "o c #c000c000c000", "O c #800080008000", /* pixels */ " ", " ", " ", " ", " ", " ", " ", " ", " ", " .......................... ", " .XXXXXXXXXXXXXXXXXXXXXXXo. ", " .XooooooooooooooooooooooO. ", " .Xooooooooooooooooo..oooO. ", " .Xooooooooooooooooo..oooO. ", " .XooooooooooooooooooooooO. ", " .Xoooooooo.......oooooooO. ", " .Xoo...................oO. ", " .Xoooooooo.......oooooooO. ", " .XooooooooooooooooooooooO. ", " .XooooooooooooooooooooooO. ", " .XooooooooooooooooooooooO. ", " .XooooooooooooooooooooooO. ", " .oOOOOOOOOOOOOOOOOOOOOOOO. ", " .......................... ", " ", " ", " ", " ", " ", " ", " ", " "}; su #define netw_width 32 #define netw_height 32 static unsigned char netw_bits[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x7f, 0x00, 0x00, 0x02, 0x40, 0x00, 0x00, 0xfa, 0x5f, 0x00, 0x00, 0x0a, 0x50, 0x00, 0x00, 0x0a, 0x52, 0x00, 0x00, 0x0a, 0x52, 0x00, 0x00, 0x8a, 0x51, 0x00, 0x00, 0x0a, 0x50, 0x00, 0x00, 0x4a, 0x50, 0x00, 0x00, 0x0a, 0x50, 0x00, 0x00, 0x0a, 0x50, 0x00, 0x00, 0xfa, 0x5f, 0x00, 0x00, 0x02, 0x40, 0xfe, 0x7f, 0x52, 0x55, 0x02, 0x40, 0xaa, 0x6a, 0xfa, 0x5f, 0xfe, 0x7f, 0x0a, 0x50, 0xfe, 0x7f, 0x0a, 0x52, 0x80, 0x00, 0x0a, 0x52, 0x80, 0x00, 0x8a, 0x51, 0x80, 0x00, 0x0a, 0x50, 0x80, 0x00, 0x4a, 0x50, 0x80, 0x00, 0x0a, 0x50, 0xe0, 0x03, 0x0a, 0x50, 0x20, 0x02, 0xfa, 0xdf, 0x3f, 0x03, 0x02, 0x40, 0xa0, 0x02, 0x52, 0x55, 0xe0, 0x03, 0xaa, 0x6a, 0x00, 0x00, 0xfe, 0x7f, 0x00, 0x00, 0xfe, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; s{ #define drivea_width 32 #define drivea_height 32 static unsigned char drivea_bits[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0xff, 0x1f, 0x08, 0x00, 0x00, 0x18, 0xa8, 0xaa, 0xaa, 0x1a, 0x48, 0x55, 0xd5, 0x1d, 0xa8, 0xaa, 0xaa, 0x1b, 0x48, 0x55, 0x55, 0x1d, 0xa8, 0xfa, 0xaf, 0x1a, 0xc8, 0xff, 0xff, 0x1d, 0xa8, 0xfa, 0xaf, 0x1a, 0x48, 0x55, 0x55, 0x1d, 0xa8, 0xaa, 0xaa, 0x1a, 0x48, 0x55, 0x55, 0x1d, 0xa8, 0xaa, 0xaa, 0x1a, 0xf8, 0xff, 0xff, 0x1f, 0xf8, 0xff, 0xff, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; c Cstjddt|_|js<tjddt|_ntjddt|_|jsxtjddt|_ntj|dddddd }tj|dddddd }tjd d ||_ |j j j t |j d d |j j j t |j d ddddd|j j j t |j d ddd|j j j t |j d dd|j|j |dttsidei tfilltexpand(tTixtImagetnetwork_pixmaptimg0tnetwork_bitmapthard_disk_pixmaptimg1thard_disk_bitmaptButtonthdd_imgttktcalltstrtnet_imgtpacktLEFTtY(Rthddtnettclose((s//usr/lib64/python2.7/Demo/tix/samples/CmpImg.pyt RunSamples6  !!"$ (+ "$ (+ ..t__main__( RRRRR R-t__name__tTktroottmainloop(((s//usr/lib64/python2.7/Demo/tix/samples/CmpImg.pyts /- /   PK%L] \ \ tix/samples/Balloon.pyonu[ ^c@sWddlZdZdZdddYZedkrSejZeendS(iNicCs$t|}|j|jdS(N(t DemoBalloontmainlooptdestroy(troottballoon((s0/usr/lib64/python2.7/Demo/tix/samples/Balloon.pyt RunSamples  RcBs,eZdZdZdZdZRS(c Cs@||_d|_|j}|jd|dtj|dddtjdd}|jd tjd tj d d d dtj |ddd|j }tj |dd}|d|d<|jd tj dd|jd tj ddtj |d|}|j|dddd|j|dddddS(NitWM_DELETE_WINDOWcSs |jS(N(tquitcmd(tself((s0/usr/lib64/python2.7/Demo/tix/samples/Balloon.pyt!ttwidthi(trelieftbditsidetfilltpadxitpadyttextsSomething UnexpectedtcommandsSomething Else UnexpectedcSs |jS(N(R(tw((s0/usr/lib64/python2.7/Demo/tix/samples/Balloon.pyR *R texpandt statusbart balloonmsgs Close Windowt statusmsgs&Press this button to close this windowsSelf-destruct buttons,Press this button and it will destroy itself(Rtexittwinfo_toplevelt wm_protocoltTixtLabeltSUNKENtpacktBOTTOMtYtButtonRtTOPtBalloont bind_widget(RRtztstatustbutton1tbutton2tb((s0/usr/lib64/python2.7/Demo/tix/samples/Balloon.pyt__init__s"   $( cCs d|_dS(Ni(R(R((s0/usr/lib64/python2.7/Demo/tix/samples/Balloon.pyR7scCsAd}x4|jdkr<|dkr<|jjjt}q WdS(Nii(RRttkt dooneeventtTCL_ALL_EVENTS(Rt foundEvent((s0/usr/lib64/python2.7/Demo/tix/samples/Balloon.pyR:scCs|jjdS(N(RR(R((s0/usr/lib64/python2.7/Demo/tix/samples/Balloon.pyR?s(t__name__t __module__R+RRR(((s0/usr/lib64/python2.7/Demo/tix/samples/Balloon.pyRs   t__main__((RR.RRR0tTkR(((s0/usr/lib64/python2.7/Demo/tix/samples/Balloon.pyts  '  PK%L]*MB tix/samples/ComboBox.pyonu[ ^c@siddlZdZddZddZdZedkreejZeeej ndS(iNcCstj|dddtj}tjatjatj|dddddtdd d td d }tj|dd dd dtddd td d}|j dtj dtj |j dtj dtj |j tj d|j tj d|j tj d|j tj d|j tj d|j tj d|j tj d|j tj d|j tj d|j tj d|j tj d|j tj d|j tj d|j tj d|j tj d|j tj d |j tj d!|jd|jd tj|d"tj}|jd#d$d%d&d d'd(d|d)|jd*d$d+d&d d'd(d|d,|j dtjd-tj|j dtj d-tjd.ddS(/NtbditrelieftlabelsMonth: tdropdowntcommandteditableitvariabletoptionss.listbox.height 6 label.width 10 label.anchor esYear: s<listbox.height 4 label.padY 5 label.width 10 label.anchor netsidetanchortJanuarytFebruarytMarchtApriltMaytJunetJulytAugustt SeptembertOctobertNovembertDecembert1992t1993t1994t1995t1996t orientationtokttexttOkt underlinetwidthicSs t|S(N(t ok_command(tw((s1/usr/lib64/python2.7/Demo/tix/samples/ComboBox.pytQttcanceltCancelcSs |jS(N(tdestroy(R"((s1/usr/lib64/python2.7/Demo/tix/samples/ComboBox.pyR#SR$tfilltexpand(tTixtFrametRAISEDt StringVart demo_montht demo_yeartComboBoxt select_montht select_yeartpacktTOPtWtinserttENDt set_silentt ButtonBoxt HORIZONTALtaddtBOTTOMtXtBOTH(R"ttoptatbtbox((s1/usr/lib64/python2.7/Demo/tix/samples/ComboBox.pyt RunSamplesJ        cCsdS(N((tevent((s1/usr/lib64/python2.7/Demo/tix/samples/ComboBox.pyR1WscCsdS(N((RD((s1/usr/lib64/python2.7/Demo/tix/samples/ComboBox.pyR2[scCs|jdS(N(R'(R"((s1/usr/lib64/python2.7/Demo/tix/samples/ComboBox.pyR!_st__main__( R*RCtNoneR1R2R!t__name__tTktroottmainloop(((s1/usr/lib64/python2.7/Demo/tix/samples/ComboBox.pyts  E      PK%L]i|##tix/samples/Control.pynu[# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- # # $Id$ # # Tix Demonstration Program # # This sample program is structured in such a way so that it can be # executed from the Tix demo program "tixwidgets.py": it must have a # procedure called "RunSample". It should also have the "if" statment # at the end of this file so that it can be run as a standalone # program. # This file demonstrates the use of the tixControl widget -- it is an # entry widget with up/down arrow buttons. You can use the arrow buttons # to adjust the value inside the entry widget. # # This example program uses three Control widgets. One lets you select # integer values; one lets you select floating point values and the last # one lets you select a few names. import Tix TCL_ALL_EVENTS = 0 def RunSample (root): control = DemoControl(root) control.mainloop() control.destroy() class DemoControl: def __init__(self, w): self.root = w self.exit = -1 global demo_maker, demo_thrust, demo_num_engines demo_maker = Tix.StringVar() demo_thrust = Tix.DoubleVar() demo_num_engines = Tix.IntVar() demo_maker.set('P&W') demo_thrust.set(20000.0) demo_num_engines.set(2) top = Tix.Frame(w, bd=1, relief=Tix.RAISED) # $w.top.a allows only integer values # # [Hint] The -options switch sets the options of the subwidgets. # [Hint] We set the label.width subwidget option of the Controls to # be 16 so that their labels appear to be aligned. # a = Tix.Control(top, label='Number of Engines: ', integer=1, variable=demo_num_engines, min=1, max=4, options='entry.width 10 label.width 20 label.anchor e') b = Tix.Control(top, label='Thrust: ', integer=0, min='10000.0', max='60000.0', step=500, variable=demo_thrust, options='entry.width 10 label.width 20 label.anchor e') c = Tix.Control(top, label='Engine Maker: ', value='P&W', variable=demo_maker, options='entry.width 10 label.width 20 label.anchor e') # We can't define these in the init because the widget 'c' doesn't # exist yet and we need to reference it c['incrcmd'] = lambda w=c: adjust_maker(w, 1) c['decrcmd'] = lambda w=c: adjust_maker(w, -1) c['validatecmd'] = lambda w=c: validate_maker(w) a.pack(side=Tix.TOP, anchor=Tix.W) b.pack(side=Tix.TOP, anchor=Tix.W) c.pack(side=Tix.TOP, anchor=Tix.W) box = Tix.ButtonBox(w, orientation=Tix.HORIZONTAL) box.add('ok', text='Ok', underline=0, width=6, command=self.okcmd) box.add('cancel', text='Cancel', underline=0, width=6, command=self.quitcmd) box.pack(side=Tix.BOTTOM, fill=Tix.X) top.pack(side=Tix.TOP, fill=Tix.BOTH, expand=1) def okcmd (self): # tixDemo:Status "Selected %d of %s engines each of thrust %d", (demo_num_engines.get(), demo_maker.get(), demo_thrust.get()) self.quitcmd() def quitcmd (self): self.exit = 0 def mainloop(self): while self.exit < 0: self.root.tk.dooneevent(TCL_ALL_EVENTS) def destroy (self): self.root.destroy() maker_list = ['P&W', 'GE', 'Rolls Royce'] def adjust_maker(w, inc): i = maker_list.index(demo_maker.get()) i = i + inc if i >= len(maker_list): i = 0 elif i < 0: i = len(maker_list) - 1 # In Tcl/Tix we should return the string maker_list[i]. We can't # do that in Tkinter so we set the global variable. (This works). demo_maker.set(maker_list[i]) def validate_maker(w): try: i = maker_list.index(demo_maker.get()) except ValueError: # Works here though. Why ? Beats me. return maker_list[0] # Works here though. Why ? Beats me. return maker_list[i] if __name__ == '__main__': root = Tix.Tk() RunSample(root) PK%L]b&UUtix/samples/PopMenu.pycnu[ ^c@sHddlZdZedkrDejZeeejndS(iNc Cstj|dtjdd}tj|dd}|jdddtjdd d d tj|d d }|j||j||jj d ddd|jj d ddd|jj d ddd|jj d ddd|jj d dddtj |j}|j d d|jj d dd||jdtj ddd d tj |dtj}|jdddddddd|d |jd!dd"ddddd|d#|jdtjdtj|jdtj dtjdddS($NtrelieftbdittextsEPress the right mouse button over this button or its surrounding areatexpandtfilltpadxi2tpadyttitles Popup TesttlabeltDesktopt underlineitSelecttFindtSystemtHelptHellotMoretmenutsidei(t orientationtoktOktwidthitcommandcSs |jS(N(tdestroy(tw((s0/usr/lib64/python2.7/Demo/tix/samples/PopMenu.pyt0ttcanceltCancelcSs |jS(N(R(R((s0/usr/lib64/python2.7/Demo/tix/samples/PopMenu.pyR2R(tTixtFrametRAISEDtButtontpacktBOTHt PopupMenut bind_widgetRt add_commandtMenut add_cascadetTOPt ButtonBoxt HORIZONTALtaddtBOTTOMtX(Rttoptbuttptm1tbox((s0/usr/lib64/python2.7/Demo/tix/samples/PopMenu.pyt RunSamples,%    t__main__(RR4t__name__tTktroottmainloop(((s0/usr/lib64/python2.7/Demo/tix/samples/PopMenu.pyts  %   PK%L]07bbtix/samples/OptMenu.pycnu[ ^c@szddlZidd6dd6dd6dd 6d d 6Zd Zd ZedkrvejZeeejndS(iNs Plain Textttextt PostScripttposttHTMLthtmltLaTeXttexsRich Text Formattrtfc Cstjatjatj|dddtj}tj|dddtdd}tj|dd dtdd}xBtjD]4}|j |dt||j |dt|qWtj d tj d |j d tj d tj dddd|j d tj d tj ddddtj|dtj}|jdddddddd|d|jdddddddd|d|j d tjdtj|j d tj dtjdddS( NtbditrelieftlabelsFrom File Format : tvariabletoptionss2label.width 19 label.anchor e menubutton.width 15sTo File Format : RRtsidetanchortpadyitpadxit orientationtokRtOkt underlineitwidthtcommandcSs t|S(N(t ok_command(tw((s0/usr/lib64/python2.7/Demo/tix/samples/OptMenu.pyt7ttcanceltCancelcSs |jS(N(tdestroy(R((s0/usr/lib64/python2.7/Demo/tix/samples/OptMenu.pyR9Rtfilltexpand(tTixt StringVart demo_opt_fromt demo_opt_totFrametRAISEDt OptionMenuR tkeyst add_commandtsettpacktTOPtWt ButtonBoxt HORIZONTALtaddtBOTTOMtXtBOTH(Rttopt from_filetto_filetopttbox((s0/usr/lib64/python2.7/Demo/tix/samples/OptMenu.pyt RunSamples.      ((  cCs|jdS(N(R(R((s0/usr/lib64/python2.7/Demo/tix/samples/OptMenu.pyR=st__main__(R R R8Rt__name__tTktroottmainloop(((s0/usr/lib64/python2.7/Demo/tix/samples/OptMenu.pyts  (    PK%L]Jtix/samples/DirTree.pynu[# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- # # $Id$ # # Tix Demonstration Program # # This sample program is structured in such a way so that it can be # executed from the Tix demo program "tixwidgets.py": it must have a # procedure called "RunSample". It should also have the "if" statment # at the end of this file so that it can be run as a standalone # program using tixwish. # This file demonstrates the use of the tixDirTree widget -- you can # use it for the user to select a directory. For example, an installation # program can use the tixDirTree widget to ask the user to select the # installation directory for an application. # import Tix, os, copy from Tkconstants import * TCL_ALL_EVENTS = 0 def RunSample (root): dirtree = DemoDirTree(root) dirtree.mainloop() dirtree.destroy() class DemoDirTree: def __init__(self, w): self.root = w self.exit = -1 z = w.winfo_toplevel() z.wm_protocol("WM_DELETE_WINDOW", lambda self=self: self.quitcmd()) # Create the tixDirTree and the tixLabelEntry widgets on the on the top # of the dialog box # bg = root.tk.eval('tix option get bg') # adding bg=bg crashes Windows pythonw tk8.3.3 Python 2.1.0 top = Tix.Frame( w, relief=RAISED, bd=1) # Create the DirTree widget. By default it will show the current # directory # # top.dir = Tix.DirTree(top) top.dir.hlist['width'] = 40 # When the user presses the ".." button, the selected directory # is "transferred" into the entry widget # top.btn = Tix.Button(top, text = " >> ", pady = 0) # We use a LabelEntry to hold the installation directory. The user # can choose from the DirTree widget, or he can type in the directory # manually # top.ent = Tix.LabelEntry(top, label="Installation Directory:", labelside = 'top', options = ''' entry.width 40 label.anchor w ''') self.dlist_dir = copy.copy(os.curdir) top.ent.entry['textvariable'] = self.dlist_dir top.btn['command'] = lambda dir=top.dir, ent=top.ent, self=self: \ self.copy_name(dir,ent) top.ent.entry.bind('', lambda self=self: self.okcmd () ) top.pack( expand='yes', fill='both', side=TOP) top.dir.pack( expand=1, fill=BOTH, padx=4, pady=4, side=LEFT) top.btn.pack( anchor='s', padx=4, pady=4, side=LEFT) top.ent.pack( expand=1, fill=X, anchor='s', padx=4, pady=4, side=LEFT) # Use a ButtonBox to hold the buttons. # box = Tix.ButtonBox (w, orientation='horizontal') box.add ('ok', text='Ok', underline=0, width=6, command = lambda self=self: self.okcmd () ) box.add ('cancel', text='Cancel', underline=0, width=6, command = lambda self=self: self.quitcmd () ) box.pack( anchor='s', fill='x', side=BOTTOM) def copy_name (self, dir, ent): # This should work as it is the entry's textvariable self.dlist_dir = dir.cget('value') # but it isn't so I'll do it manually ent.entry.delete(0,'end') ent.entry.insert(0, self.dlist_dir) def okcmd (self): # tixDemo:Status "You have selected the directory" + self.dlist_dir self.quitcmd() def quitcmd (self): # tixDemo:Status "You have selected the directory" + self.dlist_dir self.exit = 0 def mainloop(self): while self.exit < 0: self.root.tk.dooneevent(TCL_ALL_EVENTS) def destroy (self): self.root.destroy() # This "if" statement makes it possible to run this script file inside or # outside of the main demo program "tixwidgets.py". # if __name__== '__main__' : root=Tix.Tk() RunSample(root) PK%L]D*_ _ tix/samples/NoteBook.pycnu[ ^c@sZddlZdZdZdZedkrVejaettjndS(iNc Cs)|atj|}|r(d|}nd}|j|dd|j|dd|j|dtj|j|dd tj|d d d d dd }d|ds  T    PK%L]{̖̖tix/tixwidgets.pycnu[ ^c @sddlZddlZddlZddlZddlTddlZddlZdQZdRZdSZ dTZ dUZ dZ d dVd YZ d Zd Zd ZdZdZdZdZdZddddgadZdZdZdZdZdZdZdZdZd Z d!Z!d"Z"d#Z#d$Z$d%Z%d&Z&d'Z'd(Z(d)Z)d*Z*d+Z+d,Z,d-Z-id.d/6d0d16Z.id2d26d3d46d5d66d7d86d9d:6d;d<6d=d=6d>d?6d@dA6dBdC6dDdE6dFdG6dHdI6dJdK6Z/iZ0d2d4d6d=d:d<d?dAdEdCdGdIdKg e0d/FRt BalloonHelptvariable( RR tFrametRAISEDt MenubuttontpacktLEFTtRIGHTtMenut add_commandtadd_checkbuttont ToggleHelpR (RRtwtfilethelptfmthm((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyt MkMainMenu9s !!    c Cs,|j}tj|dddddd}|d|d<|jddd d d d |dd |jdddd d d |dd|jdddd d d |dd|jdddd d d |dd|jdddd d d |dd|jdddd d d |dd|S(NtipadxitipadytoptionssC tagPadX 6 tagPadY 4 borderWidth 2 tbgtwelR,tWelcomeR&it createcmdcSs t||S(N(t MkWelcome(R=tname((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR0ZRtchotChooserscSs t||S(N(t MkChoosers(R=RK((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR0\RtscrsScrolled WidgetscSs t||S(N(tMkScroll(R=RK((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR0^RtmgrsManager WidgetscSs t||S(N(t MkManager(R=RK((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR0`RRsDirectory ListcSs t||S(N(t MkDirList(R=RK((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR0bRtexpsRun Sample ProgramscSs t||S(N(tMkSample(R=RK((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR0dR(RR tNoteBooktadd(RRR=((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pytMkMainNotebookOs"  c Csq|j}tj|dtjdd}tj|dtjddt_tjjddddddd d |S( NR#R"itpadxitpadytleftitrights%70( RR R3R4tLabeltSUNKENtdemoR tform(RRR=((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyt MkMainStatusgs  !%c Cs|j}|j}|jd|jdkrD|jdn |jdtj|t_|j }|j }|j }|j dt dt|j dtdt|j dt dddtd d d d tjtjd <|jd |ddS(NsTix Widget Demonstrationi s 790x590+10+10s 890x640+10+10R)tfilltexpandiRYiRZR tWM_DELETE_WINDOWcSs |jS(N(R/(R((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR0R(Rtwinfo_topleveltwm_titletwinfo_screenwidthtgeometryR tBalloonR_RRBRXRaR6tTOPtXtBOTTOMtBOTHR t wm_protocol(RRtztframe1tframe2tframe3((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pytbuildps       (cCs d|_dS(s@Quit our mainloop. It is up to you to call root.destroy() after.iN(R(R((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR/scCsx|jdkry-x&|jdkr=|jjjtqWWqtk r\d|_dStk rtjdddkrd|_dSqqt j \}}}d}x+t j |||D]}||d7}qWytj d |WnnXd|_tdqXqWdS( sThis is an explict replacement for _tkinter mainloop() It lets you catch keyboard interrupts easier, and avoids the 20 msec. dead sleep() which burns a constant CPU.iiNt Interrupts Really Quit?tyesRs tError(RRttkt dooneeventtTCL_ALL_EVENTSt SystemExittKeyboardInterruptt tkMessageBoxt askquestionRtexc_infot tracebacktformat_exceptiont showerror(RtttvttbR$tline((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pytloops.     cCs|jjdS(N(Rtdestroy(R((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyRs( t__name__t __module__R!RBRXRaRsR/RR(((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyRs      "cCs.t|atjtjtjdS(N(RR_RsRR(R((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pytRunMains   c Csi|j|}t|}t|}|jdtdtdddd|jdtdtdddS(NR)RbRYiRZRci(tpaget MkWelcomeBart MkWelcomeTextR6RjRkRm(tnbRKR=tbarR$((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyRJs   "cCstj|dddtj}tj|d|d}tj|d|d}d|jdtfunccSs%|jjdt|dt|S(Nt tixDoWhenIdlet attachwidget(RwtcallR(targtrhtlist((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR0sN(R R3RR"RtScrolledListBoxtplaceRRRt ResizeHandleR4tButtont propagateR6RkRRmtbind(R=RtbotRRJRItbtn((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR0s0  " $ c Cs=|jdddddddd|j|j|dS( NR6i2R7iRixRiP(RLtupdatet attach_widget(RIRJ((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyRC s" c Csd}tjjtjdd}tjj|s@|d7}ntj|dddd}tj|}tj|dtj dd d tj d |}tj |d d }|j j dd|}tj|j d|}|jdddtj|jddddddddtj|dddtjdddddd d!d} tj|d d"d#| |d$} |jd%|jdtj| jd tj|jdddtj|jdtj|jd&d'd%| |d(d)S(*sThe ScrolledWindow widget allows you to scroll any kind of Tk widget. It is more versatile than a scrolled canvas widget. s}The Tix ScrolledWindow widget allows you to scroll any kind of Tk widget. It is more versatile than a scrolled canvas widget.tbitmapsstix.gifs (Image missing)RiJRR#iRR$RRtphotoR>timageRciRbR6iR7iiixRFR=R>iR?R@i2RARBR.cSs t||S(N(t SWindow_reset(R=R6((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR0,RisRDcSs%|jjdt|dt|S(NRERF(RwRGR(RHRIR((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR03sN(RRtjoinR_RtisfileR R3RR"RRRt image_createR]R6RmRLRMR4RNRORkRRP( R=R$R>RRQRRtimage1tlblRIRR((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR1s0   " $ c Cs=|jdddddddd|j|j|dS( NR6iR7iRiRix(RLRSRT(RIR((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyRX6s" cCstj|dddd}tj|}tj|dtjdddtjdd}tj|d d }d |jd <|jjtjd |j ddddddddtj |dddtj dddddddd}tj |ddd||d}|j d |jd!tj|jdtj|jd"dd!tj|jd!tj|jd#d$d ||d%d&S('sThe TixScrolledWindow widget allows you to scroll any kind of Tk widget. It is more versatile than a scrolled canvas widget.RiJRR#iRR$s}The Tix ScrolledWindow widget allows you to scroll any kind of Tk widget. It is more versatile than a scrolled canvas widget.RRRtwrapsWhen -scrollbar is set to "auto", the scrollbars are shown only when needed. Additional modifiers can be used to force a scrollbar to be shown or hidden. For example, "auto -y" means the horizontal scrollbar should be shown when needed but the vertical scrollbar should always be hidden; "auto +x" means the vertical scrollbar should be shown when needed but the horizontal scrollbar should always be shown, and so on.R6iR7iiidRFR=R>iR?iR@i2RARBR.cSs t||S(N(t SText_reset(R=R6((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR0VRiRbRcsRDcSs%|jjdt|dt|S(NRERF(RwRGR(RHRIR((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR0\sN(R R3RR"Rt ScrolledTextR$RRRLRMR4RNROR6RkRRmRP(R=RRQRRRIRR((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR2;s(    " $ c Cs=|jdddddddd|j|j|dS( NR6iR7iRiRix(RLRSRT(RIR((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR__s" c Cs|j|}d}tj|ddd|}tj|ddd|}t|jt|j|jddddd |d d |jddd d d d dS( Ns label.padX 4R,sTix.PanedWindowREs Tix.NoteBookRiR[R\Ri(RR Rt MkPanedWindowRt MkNoteBookR`(RRKR=REtpanetnote((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyRRds  "c Cs[tj|dtjdddtjdd}tj|ddd d }|jjd d tj|d d}|jddddd}|jddd}tj |}tj |}|j jtj d|j jtj d|j jtj d|j jtj d|j jtj d|j jtj d|j jtj d|j d|j dNs label.padX 4Rt horizontalR)RciRbRJRR$t5tflatR#R,sSelect a sample program:RYiRZsSource:REshlist.width 20RKtstextstix option get fixed_fontRRsRun ...trunsView Source ...tviewiRFtdisabledRRR^iPRit.t separatorit drawbranchi tindentt wideselectcSst|||||dS(NR(t Sample_Action(targsR=tslbRRR((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR0RR.cSst|||||dS(Ntbrowse(R(RR=RRRR((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR0Rt browsecmdcSst|||||dS(NR(R(RR=RRRR((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR0RcSst|||||dS(NR(R(RR=RRRR((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyR0RRRWR"iRititemtypeRtdata(RR RiR6RjRmRWRRRR`RRwtevalR$tconfigR3RNR7tNONEthlistRlRkR^t add_childtWINDOWtTEXTtcommentststypestselection_clear(RRKR=RERctf1tf2tlabtlab1RRRRRRttypeR6tkey((s+/usr/lib64/python2.7/Demo/tix/tixwidgets.pyRUksd"  ..(""   ((     "" !%   c Bs@|j}|j}|s2d|ds0   %   % "         '  $  / .    ^    @     PK%L]F_ajjtix/bitmaps/netw.xpmnu[/* XPM */ static char * netw_xpm[] = { /* width height ncolors chars_per_pixel */ "32 32 7 1", /* colors */ " s None c None", ". c #000000000000", "X c white", "o c #c000c000c000", "O c #404040", "+ c blue", "@ c red", /* pixels */ " ", " .............. ", " .XXXXXXXXXXXX. ", " .XooooooooooO. ", " .Xo.......XoO. ", " .Xo.++++o+XoO. ", " .Xo.++++o+XoO. ", " .Xo.++oo++XoO. ", " .Xo.++++++XoO. ", " .Xo.+o++++XoO. ", " .Xo.++++++XoO. ", " .Xo.XXXXXXXoO. ", " .XooooooooooO. ", " .Xo@ooo....oO. ", " .............. .XooooooooooO. ", " .XXXXXXXXXXXX. .XooooooooooO. ", " .XooooooooooO. .OOOOOOOOOOOO. ", " .Xo.......XoO. .............. ", " .Xo.++++o+XoO. @ ", " .Xo.++++o+XoO. @ ", " .Xo.++oo++XoO. @ ", " .Xo.++++++XoO. @ ", " .Xo.+o++++XoO. @ ", " .Xo.++++++XoO. ..... ", " .Xo.XXXXXXXoO. .XXX. ", " .XooooooooooO.@@@@@@.X O. ", " .Xo@ooo....oO. .OOO. ", " .XooooooooooO. ..... ", " .XooooooooooO. ", " .OOOOOOOOOOOO. ", " .............. ", " "}; PK%L]٦pt"+"+tix/bitmaps/tix.gifnuȯGIF87a,@I8ͻ`(dih qlϸӃpHt }͘<L\q\R5vIμg,S*IrFRh|fNcG@h?K_vg^TuWSkampor*,|iVjiQuyl~O~^DLO)/(Z6Ư`ҁU֕[zJ۝_w[lMσUZdjce3HL`ᆀ!h" +8pㄎ@ HAQ88+cY* 10rpBhSBRd PpT`ӲfHiզ\:`Yk˖d^-3$6eT0=Pkz6W][tmutuچ@LvfW xAߍrFnc<@e˵}mjb-PQ_ש ; k=jfPaXVfZk)_W(vU5J4^aNL e0Irɔ@G+Wyu`W1.#cAk A|~3bA*%Tp:Q>5@ 98V0䘫1vc }cʷ n0g߂KgV% 1cO*'Uc"8lFqCkv4<7ufFk[ۏT2h۵"owNx 1F$e)D%x$q!H@D|x8" 8@䏅tca U#E.9DbD0 (s%tBkl(Uh<~O,#'?AF]c _dX'U@@ 5 ,<92_˕ m4f pRHccgRsC9Fͳ:g=͹@LqIP={ru VGM:jvL`Y@=hfQOa=ԝog|b,1 j,'df%ɶ׈hGMLf90FDZbjiМ7Ȟ5vf/ZƟ^ '(v@2E)ƘJm=9ZSFiȪd2j]L+.ՇU8=Va)'RcڽsElD]awE 6ꡫUq 5y&," @r}\Ac*lfo"K,œ͌sPՅL: EW"6>܍R(=[\;_֖d+q;F11h$@!E3큵ؾ NlEFK-f'1ÌD|N-f\qw Sh{ 51͎ U}Sc]9/Ԍ5\[[|Ќzܶ-F|D-d>}m2Xϻ.٘g~tP,FP$6LN #n\㙴Y*MZ>&՝)DP-ebe}4238"쨡ʰ6#_]#İ$ܯօgdq=;e FedH!9eոtOYm<Ϫ!UtpS+Dr9lns_ꆏ7Rm)M2ܱ%qԾeaOSjէPPQjlu* )^q>8ġX؀v-3+\C>s4d 3$r? {G*z6oG.6z.րCXpV3DI3&74bb*.E)Gbq't+B8TrOQVhDhS@"67DaG @zut#FDFH(7GY YpxT[Z^M$kgM5N VF (=:10U: ;"My d&% Tc5CްVIP/~QJuV 8zK~}JMlm)%Y;!. ʁ2tPIa8Xxؘ"Sȍ׍pdP84aA%R5 ☋VŽ~P#SeQt UZ]UxPYs@ER^j xZ~CȎ uRE[WT"u`JS(V Lx-zEPwkOQo~%Vx0K 2e3w4%,Z.WxU+}HFH$p5 hIv(hyMOx2&JzXHYYe"#78TבwId"+IU'CIWDILATU;wneUwz( %r[axZM'XGt%Kt95ɋzWQPMj=R" &aVVjw{U^hY %I䚕rmg:dxT*1;|\D@#TELY01 9$~tH2`FVWgx;HH؝-pZ5u\ q\;Hw%] E^ʠ`!#wG;I}ofg0 \js1hi y!yK1i2\)ϥEv/ ^$Q^W0i X mV_&!4&a1֣'-U`HJ?SAScMo5i vq\Eril !{r`rYitQɧT ޥ02p{-@!Bc;BFfD{ '&*_dW!xyzd^<fO9nɚ="_ 3Rg2>A@A=M8 {-;f'[[7#m'ݷ]xgFPW]<2e,> q:|4(01SŅܿ9iƯ Ao.?bg*E< ~Za u4w͕ W;qw[aC6?| 6j]ada8-zF)a3-臹!`͡OXI 攅'0R mǦ1Һi*k!(A]| L.,%&}u8)kAD<ʒW0_];oKt$&h. !D&g}86ӼjibB3whB~T.&tTL8z:Y5H CK>/#_nQg]7&V:4D:@^j gsLu.$'}J<k N Kݚb:{#ǚ\X߶w͔D3&3޼]sd!4{,4}])ە5%WM Дfc=' 9Baz5 _. |D(Ee}td %v%Q>`U]Q!qG0`̂f~TNYPޜMЅCGpDvwdGa(d0IpGȤI0I $c ;X})[`(J^֎M fx[ [N2(uṷɓ܀*wOgc 餕؏cT|x |ִPXqCY!YOGɱPS~e˜N|N*JӾJ,`oID/@ZUvy'q9X~M)Ԑt!OO@k s2:=~ HˍO/uPAxZ/bsW?_eOSXNhdz%a&QR &|;4ORSy5QiԲR%#S(,&Ucc}:ߍ#Y ~^4b+h .oiWə?=@ukyi0z}[M:,G A^5 fN]@8$10X~O)͝@WkU>4 :ƃXˍ+ѧiTI#&./:E 3/˶H28*ß>")BԵЫ9O,Zbϵ]`+YTU"V"WINagĭ^ڔ F37uxyi!kỊۺpƩ,3tr(4b<\% {4IE.N")g1LJa}B+`K]%١`ƑI㘕8jNG ~Y˜c Ŝk0ċfj`AzUz-1,p.RX.XwTy[ pq1u &6fw]M2xsbK&hH$%ԶNCPD.elQĿm =G /ȑo8.h$ɶ:-qګ͔">"B)<'Ɇ2O,Ѓ '00mqWbJ&~*pA(8fYQh$G z챼4 4hbFzb,èC9KKN(ɨ Ӱdaxq M({$l#;1d 6$k #, M !M M?[;bIm+`\UJ"V F% `k QBm3Y%aQG{` -PB 43KV0CW*u9t_DeVH=UI%7XE -dGхW҆NDLNPr W ]NHu!n whځc)bbyB Z%f`cuU`{afgvh`pK Z b}ȼ x^-evZ괿%"m#Xhmjj<.4_}^Z |sh" H[eUI=`%Zg]vӋ-_taf}r) ]tF|s !}ZZ=ҨؿW?iN_7^rUR*43\ F0y~#B57Ov@>+{2[@ ek>yǮBhEw`xGb[~0X;onIWC~ȃB]ҀB&T4Rqa T ᇳ%Q.##h;4}>ĝ5"z}Tu!)vL Pj[h4Kbm(Y\c8}l@ŽeZTI rW3c(4s !; 5.r؈VSp4|T mP׻q IѰ@C4 2ݠt8;h:l~h"7wIv][r, U8*e`w#5(<ᅱwc$.h~Uc- fS/dhY,E>:P SRR ˤE=O]ZX26<:a7B,mQ'Mniz). :qWF->Td$HJur-V u#xG nt5UYw^6[?/EȣD!cBE똏z 'K;KL8"`Kfqei1Vd`idyˊOA,m:\1[2IQY5}S\S9@R{Md)3-[ĺ=TL<`-QDmL5,t*!DlLA.+C=ŴD= 4H3D[<:ϩTQpBpGE~I|JYE#JyGeTʻ{=8(@9tI&C { ʭҁ9sǙ,Y)$Bɪd|;|.ls˖\룵XaKaKL"b貗3YAK*,-PLg!BK&2 MtD=ilc +|z1 #;Aj~t[dX_p᭯= 9`ψi 1b5l:E0ЕٮKРdдQ[OP#x!PO!X⡺=;)L[#N)vDJ[? {R6D猣Ǔ B;ж>@ D@ʑbc<BDi3+BC+ yϰ n3#0,ҒܽI,IiRQV/"ۛ1U=DN41 s|Ӡ lųS̃?w!F .R;ŒxCeEғH(q=q* ԿE=Fc1,UQDڄL-=־6ɋQc>W;)l23+4м6AZ|KI8h|.$:kQNݼim:J{ UcsYx%U0SGNDiAbU:vK/zi|c>6(<̩}KU%B=C"4Vmeɸ. ˡöSU sj<%WI tHa#6U5|C7( <ۻKSp*ZTMkt,ƳڪdmKz,1>guŁ;u5]5@Kj]S]Q2 VsIl$ˤZj< ;ƲW 8\峾Y%[@pS~}CڤGB]\kݚ@]TTZ].bPB" I?1XH=I2dA}>U`kGD (e_O%Bb+C;,w=r-R>*Q[\Uy<׾Q¥AuW\KLŲ͝04nRYtWeD[?G'42JٜR:n;* a޺ԙܢ4Ք̱bM|2ݛ__f_R2֐|F@"cQ0ᵈZsu؉ E&j˝bLz´!"VŸe(\cX)NU,;O*kMEU],E]wR6^8cNdcTȫ3:kGZiZ$ 1[xME99kQB~x;8\ b9SfēB6^mg^Fyx=Ͱ6S mmLrHkv  2mL<߆[B`&Lq#a*rLG`h;nFfd[^o? m8(%%tix/bitmaps/justify.xbmnu[#define justify_width 16 #define justify_height 16 static unsigned char justify_bits[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xec, 0xdb, 0x00, 0x00, 0x7c, 0xdb, 0x00, 0x00, 0xbc, 0xf7, 0x00, 0x00, 0xdc, 0xde, 0x00, 0x00, 0x6c, 0xdf, 0x00, 0x00, 0x6c, 0xef, 0x00, 0x00, 0xdc, 0xdf}; PK%L]tix/bitmaps/combobox.xbmnu[#define combobox_width 32 #define combobox_height 32 static unsigned char combobox_bits[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0xff, 0xff, 0x3e, 0x04, 0x00, 0x80, 0x2a, 0x04, 0x00, 0x80, 0x2a, 0x04, 0x00, 0x80, 0x2a, 0x04, 0x00, 0x80, 0x2b, 0xfc, 0xff, 0xff, 0x3e, 0x08, 0x00, 0x00, 0x20, 0x08, 0x00, 0x00, 0x3e, 0x08, 0x00, 0x00, 0x2a, 0x28, 0x49, 0x00, 0x2a, 0x08, 0x00, 0x00, 0x3e, 0x08, 0x00, 0x00, 0x22, 0x08, 0x00, 0x00, 0x22, 0x28, 0x49, 0x12, 0x22, 0x08, 0x00, 0x00, 0x22, 0x08, 0x00, 0x00, 0x22, 0x08, 0x00, 0x00, 0x22, 0x28, 0x49, 0x02, 0x22, 0x08, 0x00, 0x00, 0x3e, 0x08, 0x00, 0x00, 0x2a, 0x08, 0x00, 0x00, 0x2a, 0xf8, 0xff, 0xff, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; PK%L]{J _tix/bitmaps/optmenu.xpmnu[/* XPM */ static char * optmenu_xpm[] = { "50 40 5 1", " s None c None", ". c white", "X c gray80", "o c gray50", "O c black", " ", " ", " .............................. ", " .XXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", " .XXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", " .XXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", " .XXXOXOXXOXXOXXXXOOXXXXXXXXXXo ", " .XXXOXOXXOXOXXXOXXOXXXXXXXXXXo ", " .XXXXOXXOXXOXXXOXXXOXXXXXXXXXo ", " .XXXXOXXXOXXOOXXOXOXXXXXXXXXXo ", " .XXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", " .XXXXXXXXXXXXXXXXXXXXXXXXXXXXo.............o ", " .............................o o ", " ..XXXOXXXXXOXXXXXXXXOXXXXXXXOo o ", " ..XXOXOXOXXOXOXXXOXXOXXXXXXXOo ...... o ", " ..XXXOXXXOXXOXXXOXXXOXXXXXXXOo . o o ", " ..XXOXXXOXXXOXOXXOXXOXXXXXXXOo . o o ", " ..XXXXXXXXXXXXXXXXXXXXXXXXXXOo .ooooo o ", " .OOOOOOOOOOOOOOOOOOOOOOOOOOOOo o ", " .XXXXXXXXXXXXXXXXXXXXXXXXXXXXo o ", " .XXXXXXXXXXXXXXXXXXXXXXXXXXXXooooooooooooooo ", " .XXXXOXXXXXOXXXXXXXXXXXXXXXXXo ", " .XXXOXXXXXXXXXOXXXXXXXXXXXXXXo ", " .XXXXOXXOXXOXOXOXXXXXXXXXXXXXo ", " .XXXXXOXXOXOXXXXXXXXXXXXXXXXXo ", " .XXXXXXXXXXXXXOXXXXXXXXXXXXXXo ", " .XXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", " .XXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", " .XXXOXOXXXXXXXOXOXXXXXOXXXXXXo ", " .XXXXXOXOXOXXOXXXXXOXXOXXXXXXo ", " .XXXXOXXOXOXOXXXOXOXOXXOXXXXXo ", " .XXXOXXXXOXXOXXXOXXOXXXXOXXXXo ", " .XXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", " .XXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", " .XXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", " oooooooooooooooooooooooooooooo ", " ", " ", " ", " "}; PK%L]TZye%%tix/bitmaps/centerj.xbmnu[#define centerj_width 16 #define centerj_height 16 static unsigned char centerj_bits[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x3e, 0x00, 0x00, 0xc0, 0x0d, 0x00, 0x00, 0x58, 0x77, 0x00, 0x00, 0xb0, 0x3b, 0x00, 0x00, 0xdc, 0xf7, 0x00, 0x00, 0xf0, 0x3e, 0x00, 0x00, 0xd8, 0x7e}; PK%L]4 4 tix/bitmaps/select.xpmnu[/* XPM */ static char * select_xpm[] = { "50 40 9 1", " s None c None", ". c black", "X c gray95", "o c gray50", "O c gray70", "+ c navy", "@ c #000080800000", "# c #808000000000", "$ c white", " ", " ", " ", " ", " ", " ", " ", " ", " ", " .............................................. ", " .XXXXXXXXXXooooooooooooXXXXXXXXXXXoXXXXXXXXXX. ", " .X ooOOOOOOOOOOXX oX o. ", " .X ooOOOOOOOOOOXX oX o. ", " .X ++++ ooOOOOOOOOOOXX ... oX @ o. ", " .X +++++ ooOOOOOOOOOOXX . . oX @@@ o. ", " .X +++ + ooOOOOOOOOOOXX . . oX @ @ o. ", " .X + + ooOO#####OOOXX . . oX @ @ o. ", " .X + + ooOO#OOO##OOXX . oX @ @ o. ", " .X + + ooO##OOOO##OXX . oX @ @ o. ", " .X ++ ++ ooO###OOO#OOXX . oX @ @ o. ", " .X +++++++ ooO#######OOXX . oX @ @ o. ", " .X + + ooO##O#OO#OOXX . oX @ @ o. ", " .X + ++ ooO##OOOOO#OXX . . oX @ @ o. ", " .X + + ooOO#OOOOO#OXX . . oX @ @@ o. ", " .X + ++ ooOO#OOOOO#OXX .... oX @@@@@ o. ", " .X ooOO######OOXX oX o. ", " .X ooOOOOOOOOOOXX $oX o. ", " .XoooooooooooXXXXXXXXXXXoooooooooooXooooooooo. ", " .............................................. ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " "}; PK%L]0tix/bitmaps/bold.xbmnu[#define bold_width 16 #define bold_height 16 static unsigned char bold_bits[] = { 0x00, 0x00, 0x00, 0x00, 0xfc, 0x07, 0xfc, 0x0f, 0x18, 0x1c, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1c, 0xf8, 0x0f, 0xf8, 0x0f, 0x18, 0x18, 0x18, 0x30, 0x18, 0x30, 0x18, 0x38, 0xfc, 0x3f, 0xfc, 0x1f}; PK%L]Ǐtix/bitmaps/leftj.xbmnu[#define leftj_width 16 #define leftj_height 16 static unsigned char leftj_bits[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xcc, 0x6d, 0x00, 0x00, 0xdc, 0x01, 0x00, 0x00, 0xec, 0x0e, 0x00, 0x00, 0xfc, 0x7e, 0x00, 0x00, 0xdc, 0x03, 0x00, 0x00, 0x6c, 0x3b, 0x00, 0x00, 0x6c, 0x1f}; PK%L]Hj"  tix/bitmaps/combobox.xpmnu[/* XPM */ static char * combobox_xpm[] = { "50 40 6 1", " s None c None", ". c black", "X c white", "o c #FFFF80808080", "O c gray70", "+ c #808000008080", " ", " ", " ", " .................................... XXXXXXX ", " .ooooooooooooooooooooooooooooooooooX X . . ", " .ooooooooooooooooooooooooooooooooooX X . . ", " .oooo.oooooooooooooooooooooooooooooX X . . ", " .oo.o..oo.o.oo.o.ooooooooooooooooooX X . . ", " .o..o.o.o.oo.oo.oo.ooooooooooooooooX X ... . ", " .oo.oo.oo.o.oo.ooo.ooooooooooooooooX X . . ", " .ooooooooooooooooooooooooooooooooooX X . ", " .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX X...... ", " ", " ", " ", " XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ", " X............................................ ", " X.OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOX.OOOOX. ", " X.O+OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOX.OX OX. ", " X.O++OOO+OO+++OOOOOOOOOOOOOOOOOOOOOOOX.X ..X. ", " X.O+O+O+OOO+O+OOOOOOOOOOOOOOOOOOOOOOOX.OOOOX. ", " X.O++OOO+OO+++OOOOOOOOOOOOOOOOOOOOOOOX.OOOOX. ", " X.OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOX.XXXXX. ", " X.O.....X..........................OOX.X .X. ", " X.OX...XXX.X.XX.XX.................OOX.X .X. ", " X.OX.X..X..X.XX..XX.X..............OOX.X .X. ", " X.O.X...X..X.X...X..X..............OOX.X .X. ", " X.OOOOOOOOOOOOOOOOOOOOOOOO+OOOOOOOOOOX.X .X. ", " X.OOOOOOOOO+OOO+OOOOO+OOOO+OOOOOOOOOOX.X .X. ", " X.O+++OO+OO+O+OO++O++OO+OO+OOOOOOOOOOX.X...X. ", " X.OO+OO++OO+O+OO+OOO+OO+O++OOOOOOOOOOX.OOOOX. ", " X.OOOOOOOO+OOOOO++OO+OOOOOOOOOOOOOOOOX.OOOOX. ", " X.OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOX.X .X. ", " X.OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOX.O .OX. ", " X.OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOX.OOOOX. ", " X.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.XXXXX. ", " X............................................ ", " ", " ", " "}; PK%L]{++tix/bitmaps/underline.xbmnu[#define underline_width 16 #define underline_height 16 static unsigned char underline_bits[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x1c, 0x38, 0x1c, 0x30, 0x0c, 0x30, 0x0c, 0x30, 0x0c, 0x30, 0x0c, 0x30, 0x0c, 0x70, 0x0e, 0xf0, 0x0f, 0xe0, 0x07, 0x00, 0x00, 0xf8, 0x1f}; PK%L]#1}}tix/bitmaps/filebox.xbmnu[#define filebox_width 32 #define filebox_height 32 static unsigned char filebox_bits[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0xff, 0xff, 0x3f, 0x04, 0x00, 0x00, 0x20, 0xe4, 0xff, 0xff, 0x27, 0x24, 0x00, 0x00, 0x24, 0x24, 0x00, 0x00, 0x24, 0xe4, 0xff, 0xff, 0x27, 0x04, 0x00, 0x00, 0x20, 0xe4, 0x7f, 0xfe, 0x27, 0x24, 0x50, 0x02, 0x25, 0x24, 0x40, 0x02, 0x24, 0x24, 0x50, 0x02, 0x25, 0x24, 0x40, 0x02, 0x24, 0x24, 0x50, 0x02, 0x25, 0x24, 0x40, 0x02, 0x24, 0x24, 0x50, 0x02, 0x25, 0xe4, 0x7f, 0xfe, 0x27, 0x04, 0x00, 0x00, 0x20, 0xe4, 0xff, 0xff, 0x27, 0x24, 0x00, 0x00, 0x24, 0x24, 0x00, 0x00, 0x24, 0xe4, 0xff, 0xff, 0x27, 0x04, 0x00, 0x00, 0x20, 0xfc, 0xff, 0xff, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; PK%L]W=""tix/bitmaps/rightj.xbmnu[#define rightj_width 16 #define rightj_height 16 static unsigned char rightj_bits[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0xdb, 0x00, 0x00, 0x70, 0xdb, 0x00, 0x00, 0x00, 0xef, 0x00, 0x00, 0xd8, 0xde, 0x00, 0x00, 0xc0, 0xdd, 0x00, 0x00, 0xa0, 0xef, 0x00, 0x00, 0xd8, 0xde}; PK%L]5(=[[tix/bitmaps/drivea.xpmnu[/* XPM */ static char * drivea_xpm[] = { /* width height ncolors chars_per_pixel */ "32 32 5 1", /* colors */ " s None c None", ". c #000000000000", "X c white", "o c #c000c000c000", "O c #800080008000", /* pixels */ " ", " ", " ", " ", " ", " ", " ", " ", " ", " .......................... ", " .XXXXXXXXXXXXXXXXXXXXXXXo. ", " .XooooooooooooooooooooooO. ", " .Xooooooooooooooooo..oooO. ", " .Xooooooooooooooooo..oooO. ", " .XooooooooooooooooooooooO. ", " .Xoooooooo.......oooooooO. ", " .Xoo...................oO. ", " .Xoooooooo.......oooooooO. ", " .XooooooooooooooooooooooO. ", " .XooooooooooooooooooooooO. ", " .XooooooooooooooooooooooO. ", " .XooooooooooooooooooooooO. ", " .oOOOOOOOOOOOOOOOOOOOOOOO. ", " .......................... ", " ", " ", " ", " ", " ", " ", " ", " "}; PK%L]7o  tix/bitmaps/filebox.xpmnu[/* XPM */ static char * filebox_xpm[] = { "50 40 6 1", " s None c None", ". c white", "X c gray80", "o c black", "O c #FFFF80808080", "+ c gray70", " ", " ", " ", " ............................................ ", " .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", " .XXooXooXoXooXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", " .XXooXooXoXooXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", " .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", " .XXooooooooooooooooooooooooooooooooooooo.XXo ", " .XXoOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO.XXo ", " .XXoOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO.XXo ", " .XX......................................XXo ", " .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", " .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", " .XXoooooooooooooooo.XXXXoooooooooooooooo.XXo ", " .XXo+++++++++++++++.XXXXo+++++++++++++++.XXo ", " .XXo+++++++++++++++.XXXXo+++++++++++++++.XXo ", " .XXo+++++++++++++++.XXXXo+++++++++++++++.XXo ", " .XXo+++++++++++++++.XXXXo+++++++++++++++.XXo ", " .XXo+++++++++++++++.XXXXo+++++++++++++++.XXo ", " .XXo+++++++++++++++.XXXXo+++++++++++++++.XXo ", " .XXo+++++++++++++++.XXXXo+++++++++++++++.XXo ", " .XXo+++++++++++++++.XXXXo+++++++++++++++.XXo ", " .XXo+++++++++++++++.XXXXo+++++++++++++++.XXo ", " .XXo+++++++++++++++.XXXXo+++++++++++++++.XXo ", " .XXo+++++++++++++++.XXXXo+++++++++++++++.XXo ", " .XX.................XXXX.................XXo ", " .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", " .XXooXooXoXooXoXXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", " .XXooXooXoXooXoXooXXXXXXXXXXXXXXXXXXXXXXXXXo ", " .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", " .XXoooooooooooooooooooooooooooooooooooooo.Xo ", " .XXoOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO.Xo ", " .XXoOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO.Xo ", " .XX.......................................Xo ", " .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", " .ooooooooooooooooooooooooooooooooooooooooooo ", " ", " ", " "}; PK%L]*GS%%tix/bitmaps/capital.xbmnu[#define capital_width 16 #define capital_height 16 static unsigned char capital_bits[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x08, 0x30, 0x0c, 0x30, 0x06, 0x30, 0x03, 0xb0, 0x01, 0xf0, 0x00, 0xf0, 0x00, 0xf0, 0x01, 0xb0, 0x03, 0x30, 0x07, 0x30, 0x0e, 0x30, 0x1c, 0x00, 0x00}; PK%L]gˆ tix/grid.pyonu[ ^c @sddlZddlmZejZejdejeddZejdej fdYZ e eddd d Z e jd ej xMe d D]?Zx6e d D](Ze jeed eeefqWqWejed ddejZejejdS(iN(tpprintttesttnameta_labeltMyGridcBseZdZdZRS(cOs'|j|ds     * PK%L]Ftix/README.txtnu[About Tix.py ----------- Tix.py is based on an idea of Jean-Marc Lugrin (lugrin@ms.com) who wrote pytix (another Python-Tix marriage). Tix widgets are an attractive and useful extension to Tk. See http://tix.sourceforge.net for more details about Tix and how to get it. Features: 1) It is almost complete. 2) Tix widgets are represented by classes in Python. Sub-widgets are members of the mega-widget class. For example, if a particular TixWidget (e.g. ScrolledText) has an embedded widget (Text in this case), it is possible to call the methods of the child directly. 3) The members of the class are created automatically. In the case of widgets like ButtonBox, the members are added dynamically. PK%L]䠵&& tix/grid.pynu[### import Tix as tk from pprint import pprint r= tk.Tk() r.title("test") l=tk.Label(r, name="a_label") l.pack() class MyGrid(tk.Grid): def __init__(self, *args, **kwargs): kwargs['editnotify']= self.editnotify tk.Grid.__init__(self, *args, **kwargs) def editnotify(self, x, y): return True g = MyGrid(r, name="a_grid", selectunit="cell") g.pack(fill=tk.BOTH) for x in xrange(5): for y in xrange(5): g.set(x,y,text=str((x,y))) c = tk.Button(r, text="Close", command=r.destroy) c.pack() tk.mainloop() PK%L]*ϰtix/INSTALL.txtnu[$Id$ Installing Tix.py ---------------- 0) To use Tix.py, you need Tcl/Tk (V8.3.3), Tix (V8.1.1) and Python (V2.1.1). Tix.py has been written and tested on an Intel Pentium running RH Linux 5.2 and Mandrake Linux 7.0 and Windows with the above mentioned packages. Older versions, e.g. Tix 4.1 and Tk 8.0, might also work. There is nothing OS-specific in Tix.py itself so it should work on any machine with Tix and Python installed. You can get Tcl and Tk from http://dev.scriptics.com and Tix from http://tix.sourceforge.net. 1) Build and install Tcl/Tk 8.3. Build and install Tix 8.1. Ensure that Tix is properly installed by running tixwish and executing the demo programs. Under Unix, use the --enable-shared configure option for all three. We recommend tcl8.3.3 for this release of Tix.py. 2a) If you have a distribution like ActiveState with a tcl subdirectory of $PYTHONHOME, which contains the directories tcl8.3 and tk8.3, make a directory tix8.1 as well. Recursively copy the files from /library to $PYTHONHOME/lib/tix8.1, and copy the dynamic library (tix8183.dll or libtix8.1.8.3.so) to the same place as the tcl dynamic libraries ($PYTHONHOME/Dlls or lib/python-2.1/lib-dynload). In this case you are all installed, and you can skip to the end. 2b) Modify Modules/Setup.dist and setup.py to change the version of the tix library from tix4.1.8.0 to tix8.1.8.3 These modified files can be used for Tkinter with or without Tix. 3) The default is to build dynamically, and use the Tcl 'package require'. To build statically, modify the Modules/Setup file to link in the Tix library according to the comments in the file. On Linux this looks like: # *** Always uncomment this (leave the leading underscore in!): _tkinter _tkinter.c tkappinit.c -DWITH_APPINIT \ # *** Uncomment and edit to reflect where your Tcl/Tk libraries are: -L/usr/local/lib \ # *** Uncomment and edit to reflect where your Tcl/Tk headers are: -I/usr/local/include \ # *** Uncomment and edit to reflect where your X11 header files are: -I/usr/X11R6/include \ # *** Or uncomment this for Solaris: # -I/usr/openwin/include \ # *** Uncomment and edit for BLT extension only: # -DWITH_BLT -I/usr/local/blt/blt8.0-unoff/include -lBLT8.0 \ # *** Uncomment and edit for PIL (TkImaging) extension only: # (See http://www.pythonware.com/products/pil/ for more info) # -DWITH_PIL -I../Extensions/Imaging/libImaging tkImaging.c \ # *** Uncomment and edit for TOGL extension only: # -DWITH_TOGL togl.c \ # *** Uncomment and edit for Tix extension only: -DWITH_TIX -ltix8.1.8.3 \ # *** Uncomment and edit to reflect your Tcl/Tk versions: -ltk8.3 -ltcl8.3 \ # *** Uncomment and edit to reflect where your X11 libraries are: -L/usr/X11R6/lib \ # *** Or uncomment this for Solaris: # -L/usr/openwin/lib \ # *** Uncomment these for TOGL extension only: # -lGL -lGLU -lXext -lXmu \ # *** Uncomment for AIX: # -lld \ # *** Always uncomment this; X11 libraries to link with: -lX11 4) Rebuild Python and reinstall. You should now have a working Tix implementation in Python. To see if all is as it should be, run the 'tixwidgets.py' script in the Demo/tix directory. Under X windows, do /usr/local/bin/python Demo/tix/tixwidgets.py If this does not work, you may need to tell python where to find the Tcl, Tk and Tix library files. This is done by setting the TCL_LIBRARY, TK_LIBRARY and TIX_LIBRARY environment variables. Try this: env TCL_LIBRARY=/usr/local/lib/tcl8.3 \ TK_LIBRARY=/usr/local/lib/tk8.3 \ TIX_LIBRARY=/usr/local/lib/tix8.1 \ /usr/local/bin/python Demo/tix/tixwidgets.py If you find any bugs or have suggestions for improvement, please report them via http://tix.sourceforge.net PK%L]Irscripts/makedir.pynuȯ#! /usr/bin/python2.7 # Like mkdir, but also make intermediate directories if necessary. # It is not an error if the given directory already exists (as long # as it is a directory). # Errors are not treated specially -- you just get a Python exception. import sys, os def main(): for p in sys.argv[1:]: makedirs(p) def makedirs(p): if p and not os.path.isdir(p): head, tail = os.path.split(p) makedirs(head) os.mkdir(p, 0777) if __name__ == "__main__": main() PK%L]u=iiscripts/from.pynuȯ#! /usr/bin/python2.7 # Print From and Subject of messages in $MAIL. # Extension to multiple mailboxes and other bells & whistles are left # as exercises for the reader. import sys, os # Open mailbox file. Exits with exception when this fails. try: mailbox = os.environ['MAIL'] except (AttributeError, KeyError): sys.stderr.write('No environment variable $MAIL\n') sys.exit(2) try: mail = open(mailbox) except IOError: sys.exit('Cannot open mailbox file: ' + mailbox) while 1: line = mail.readline() if not line: break # EOF if line.startswith('From '): # Start of message found print line[:-1], while 1: line = mail.readline() if not line or line == '\n': break if line.startswith('Subject: '): print repr(line[9:-1]), print PK%L]hq scripts/update.pyonu[ Afc@soddlZddlZddlZdZejeZdddYZdZedkrkendS(iNs^([^: ]+):([1-9][0-9]*):tFileObjcBs#eZdZdZdZRS(cCsk||_d|_yt|dj|_Wn*tk rZ}d|G|GHd|_dSXdG|jGHdS(Nitrs*** Can't open "%s":tdiffing(tfilenametchangedtopent readlinestlinestIOErrortNone(tselfRtmsg((s+/usr/lib64/python2.7/Demo/scripts/update.pyt__init__s    cCs|jsdG|jGHdSy0tj|j|jdt|jd}Wn-tjtfk rx}d|jG|GHdSXdG|jGHx|jD]}|j|qW|j d|_dS(Ns no changes tot~tws*** Can't rewrite "%s":twritingi( RRtostrenameRterrorRRtwritetclose(R tfpR tline((s+/usr/lib64/python2.7/Demo/scripts/update.pytfinishs    cCs|jdkr'd|j||fGdSt|d}d|koWt|jknstd|j||fGdS|j||krd|j||fGdS|jsd|_nd||fGHdG|j|GdGH||j|(RR RtevaltlenR(R tlinenotrestti((s+/usr/lib64/python2.7/Demo/scripts/update.pytprocess,s(%   (t__name__t __module__R RR(((s+/usr/lib64/python2.7/Demo/scripts/update.pyRs cCs1tjdrayttjdd}Wqjtk r]}dtjdG|GHtjdqjXn tj}d}x|j}|s|r|jnPnt j |}|dkrdG|Gqsnt j dd\}}| s||j kr|r|jnt |}n|j|||qsWdS(NiRsCan't open "%s":is Funny line:i(tsystargvRRtexittstdinR treadlineRtprogtmatchtgroupRRR(RR tcurfileRtnRR((s+/usr/lib64/python2.7/Demo/scripts/update.pytmainBs0      t__main__(( RR"tretpattcompileR'RR,R (((s+/usr/lib64/python2.7/Demo/scripts/update.pyt s   2  PK%L]8 scripts/pp.pynuȯ#! /usr/bin/python2.7 # Emulate some Perl command line options. # Usage: pp [-a] [-c] [-d] [-e scriptline] [-F fieldsep] [-n] [-p] [file] ... # Where the options mean the following: # -a : together with -n or -p, splits each line into list F # -c : check syntax only, do not execute any code # -d : run the script under the debugger, pdb # -e scriptline : gives one line of the Python script; may be repeated # -F fieldsep : sets the field separator for the -a option [not in Perl] # -n : runs the script for each line of input # -p : prints the line after the script has run # When no script lines have been passed, the first file argument # contains the script. With -n or -p, the remaining arguments are # read as input to the script, line by line. If a file is '-' # or missing, standard input is read. # XXX To do: # - add -i extension option (change files in place) # - make a single loop over the files and lines (changes effect of 'break')? # - add an option to specify the record separator # - except for -n/-p, run directly from the file if at all possible import sys import getopt FS = '' SCRIPT = [] AFLAG = 0 CFLAG = 0 DFLAG = 0 NFLAG = 0 PFLAG = 0 try: optlist, ARGS = getopt.getopt(sys.argv[1:], 'acde:F:np') except getopt.error, msg: sys.stderr.write('%s: %s\n' % (sys.argv[0], msg)) sys.exit(2) for option, optarg in optlist: if option == '-a': AFLAG = 1 elif option == '-c': CFLAG = 1 elif option == '-d': DFLAG = 1 elif option == '-e': for line in optarg.split('\n'): SCRIPT.append(line) elif option == '-F': FS = optarg elif option == '-n': NFLAG = 1 PFLAG = 0 elif option == '-p': NFLAG = 1 PFLAG = 1 else: print option, 'not recognized???' if not ARGS: ARGS.append('-') if not SCRIPT: if ARGS[0] == '-': fp = sys.stdin else: fp = open(ARGS[0], 'r') while 1: line = fp.readline() if not line: break SCRIPT.append(line[:-1]) del fp del ARGS[0] if not ARGS: ARGS.append('-') if CFLAG: prologue = ['if 0:'] epilogue = [] elif NFLAG: # Note that it is on purpose that AFLAG and PFLAG are # tested dynamically each time through the loop prologue = [ 'LINECOUNT = 0', 'for FILE in ARGS:', ' \tif FILE == \'-\':', ' \t \tFP = sys.stdin', ' \telse:', ' \t \tFP = open(FILE, \'r\')', ' \tLINENO = 0', ' \twhile 1:', ' \t \tLINE = FP.readline()', ' \t \tif not LINE: break', ' \t \tLINENO = LINENO + 1', ' \t \tLINECOUNT = LINECOUNT + 1', ' \t \tL = LINE[:-1]', ' \t \taflag = AFLAG', ' \t \tif aflag:', ' \t \t \tif FS: F = L.split(FS)', ' \t \t \telse: F = L.split()' ] epilogue = [ ' \t \tif not PFLAG: continue', ' \t \tif aflag:', ' \t \t \tif FS: print FS.join(F)', ' \t \t \telse: print \' \'.join(F)', ' \t \telse: print L', ] else: prologue = ['if 1:'] epilogue = [] # Note that we indent using tabs only, so that any indentation style # used in 'command' will come out right after re-indentation. program = '\n'.join(prologue) + '\n' for line in SCRIPT: program += ' \t \t' + line + '\n' program += '\n'.join(epilogue) + '\n' import tempfile fp = tempfile.NamedTemporaryFile() fp.write(program) fp.flush() if DFLAG: import pdb pdb.run('execfile(%r)' % (fp.name,)) else: execfile(fp.name) PK%L]Gx#scripts/makedir.pyonu[ Afc@sDddlZddlZdZdZedkr@endS(iNcCs&xtjdD]}t|qWdS(Ni(tsystargvtmakedirs(tp((s,/usr/lib64/python2.7/Demo/scripts/makedir.pytmain scCsR|rNtjj| rNtjj|\}}t|tj|dndS(Ni(tostpathtisdirtsplitRtmkdir(Rtheadttail((s,/usr/lib64/python2.7/Demo/scripts/makedir.pyRs t__main__(RRRRt__name__(((s,/usr/lib64/python2.7/Demo/scripts/makedir.pyts   PK%L]#scripts/primes.pyonu[ Afc@s,dZdZedkr(endS(cCs|dko|knr$dGHndg}d}x||krx2|D]*}||dkso|||krIPqIqIW||dkr|j|||kr|GHqn|d7}q6WdS(Niii(tappend(tmintmaxtprimestitp((s+/usr/lib64/python2.7/Demo/scripts/primes.pyRs      cCsoddl}d\}}|jdr^t|jd}|jdr^t|jd}q^nt||dS(Niiii(ii(tsystargvtintR(RRR((s+/usr/lib64/python2.7/Demo/scripts/primes.pytmains    t__main__N(RR t__name__(((s+/usr/lib64/python2.7/Demo/scripts/primes.pyts  PK%L]aPOOscripts/morse.pyonu[ Afc@sddlZddlZddlZdZdeZdZiJdd6dd6dd 6dd 6d d 6d d 6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6d d!6d d"6d#d$6d#d%6d&d'6d&d(6d)d*6d)d+6d,d-6d,d.6d/d06d/d16d2d36d2d46d5d66d5d76d8d96d8d:6d;d<6d;d=6d>d?6d>d@6dAdB6dAdC6dDdE6dDdF6dGdH6dGdI6dJdK6dJdL6dMdN6dMdO6dPdQ6dPdR6dSdT6dUdV6dWdX6dYd6dZd[6d\d]6d^d_6d`da6dbdc6ddde6dfdg6dhdi6djdk6dld>6dmdn6dodp6dqdr6dsdt6dudv6dsdw6dxdx6dydz6Zd{d|Zd}ZeeZ d~Z dZ dZ dZ dZedkre ndS(iNiiis.-tAtas-...tBtbs-.-.tCtcs-..tDtdt.tEtes..-.tFtfs--.tGtgs....tHths..tItis.---tJtjs-.-tKtks.-..tLtls--tMtms-.tNtns---tOtos.--.tPtps--.-tQtqs.-.tRtrs...tStst-tTtts..-tUtus...-tVtvs.--tWtws-..-tXtxs-.--tYtys--..tZtzs-----t0s--..--t,s.----t1s.-.-.-s..---t2s..--..t?s...--t3s-.-.-.t;s....-t4s---...t:s.....t5s.----.t's-....t6s-....-s--...t7s-..-.t/s---..t8s-.--.-t(s----.t9t)t s..--.-t_sicCsod}xbtdD]T}ttjtj||dd}|t|d?d@t|d@7}qW|S(NtidgI@i0uii(trangetinttmathtsintpitchr(toctavetsinewaveRtval((s*/usr/lib64/python2.7/Demo/scripts/morse.pytmkwave<s (*c Csddl}y#|jtjdd\}}Wn@|jk rqtjjdtjddtjdnXd}t}x|D]\}}|dkrddl }|j |d}|j d |j d |j dn|d krtt|}qqW|sjddl}|j}|jd |j d |j d|j|_|j|_n|rd j|g} nttjjd } xF| D]>} t| } t| ||t|dr|jqqW|jdS(Niiso:p:sUsage is, [ -o outfile ] [ -p octave ] [ words ] ... s-oR/iDis-pRHRJtwait(tgetopttsystargvterrortstderrtwritetexittNonet defaultwavetaifctopent setframeratet setsampwidtht setnchannelsRTRLtaudiodevtAudioDevt setoutratetstoptcloset writeframestwriteframesrawtjointitertstdintreadlinetmorsetplaythasattrRU( RVtoptstargstdevtwaveRRR_Rdtsourcetlinetmline((s*/usr/lib64/python2.7/Demo/scripts/morse.pytmainEsF #             cCsEd}x8|D]0}y|t|d7}Wq tk r<q Xq W|S(NRJs(tmorsetabtKeyError(RwtresR((s*/usr/lib64/python2.7/Demo/scripts/morse.pyRoms  cCsqxj|D]b}|dkr,t|t|n0|dkrKt|t|nt|ttt|tqWdS(NRR'(tsinetDOTtDAHtpause(RwRtRuR((s*/usr/lib64/python2.7/Demo/scripts/morse.pyRpws   cCs(x!t|D]}|j|q WdS(N(RKRj(RttlengthRuR((s*/usr/lib64/python2.7/Demo/scripts/morse.pyR}scCs(x!t|D]}|jtq WdS(N(RKRjtnowave(RtRR((s*/usr/lib64/python2.7/Demo/scripts/morse.pyRst__main__(RWRMRdR~RtOCTAVERzRRTR^RyRoRpR}Rt__name__(((s*/usr/lib64/python2.7/Demo/scripts/morse.pytsf$     (   PK%L]Kscripts/markov.pynuȯ#! /usr/bin/python2.7 class Markov: def __init__(self, histsize, choice): self.histsize = histsize self.choice = choice self.trans = {} def add(self, state, next): self.trans.setdefault(state, []).append(next) def put(self, seq): n = self.histsize add = self.add add(None, seq[:0]) for i in range(len(seq)): add(seq[max(0, i-n):i], seq[i:i+1]) add(seq[len(seq)-n:], None) def get(self): choice = self.choice trans = self.trans n = self.histsize seq = choice(trans[None]) while True: subseq = seq[max(0, len(seq)-n):] options = trans[subseq] next = choice(options) if not next: break seq += next return seq def test(): import sys, random, getopt args = sys.argv[1:] try: opts, args = getopt.getopt(args, '0123456789cdwq') except getopt.error: print 'Usage: %s [-#] [-cddqw] [file] ...' % sys.argv[0] print 'Options:' print '-#: 1-digit history size (default 2)' print '-c: characters (default)' print '-w: words' print '-d: more debugging output' print '-q: no debugging output' print 'Input files (default stdin) are split in paragraphs' print 'separated blank lines and each paragraph is split' print 'in words by whitespace, then reconcatenated with' print 'exactly one space separating words.' print 'Output consists of paragraphs separated by blank' print 'lines, where lines are no longer than 72 characters.' sys.exit(2) histsize = 2 do_words = False debug = 1 for o, a in opts: if '-0' <= o <= '-9': histsize = int(o[1:]) if o == '-c': do_words = False if o == '-d': debug += 1 if o == '-q': debug = 0 if o == '-w': do_words = True if not args: args = ['-'] m = Markov(histsize, random.choice) try: for filename in args: if filename == '-': f = sys.stdin if f.isatty(): print 'Sorry, need stdin from file' continue else: f = open(filename, 'r') if debug: print 'processing', filename, '...' text = f.read() f.close() paralist = text.split('\n\n') for para in paralist: if debug > 1: print 'feeding ...' words = para.split() if words: if do_words: data = tuple(words) else: data = ' '.join(words) m.put(data) except KeyboardInterrupt: print 'Interrupted -- continue with data read so far' if not m.trans: print 'No valid input files' return if debug: print 'done.' if debug > 1: for key in m.trans.keys(): if key is None or len(key) < histsize: print repr(key), m.trans[key] if histsize == 0: print repr(''), m.trans[''] print while True: data = m.get() if do_words: words = data else: words = data.split() n = 0 limit = 72 for w in words: if n + len(w) > limit: print n = 0 print w, n += len(w) + 1 print print if __name__ == "__main__": test() PK%L]T`scripts/morse.pynuȯ#! /usr/bin/python2.7 # DAH should be three DOTs. # Space between DOTs and DAHs should be one DOT. # Space between two letters should be one DAH. # Space between two words should be DOT DAH DAH. import sys, math, audiodev DOT = 30 DAH = 3 * DOT OCTAVE = 2 # 1 == 441 Hz, 2 == 882 Hz, ... morsetab = { 'A': '.-', 'a': '.-', 'B': '-...', 'b': '-...', 'C': '-.-.', 'c': '-.-.', 'D': '-..', 'd': '-..', 'E': '.', 'e': '.', 'F': '..-.', 'f': '..-.', 'G': '--.', 'g': '--.', 'H': '....', 'h': '....', 'I': '..', 'i': '..', 'J': '.---', 'j': '.---', 'K': '-.-', 'k': '-.-', 'L': '.-..', 'l': '.-..', 'M': '--', 'm': '--', 'N': '-.', 'n': '-.', 'O': '---', 'o': '---', 'P': '.--.', 'p': '.--.', 'Q': '--.-', 'q': '--.-', 'R': '.-.', 'r': '.-.', 'S': '...', 's': '...', 'T': '-', 't': '-', 'U': '..-', 'u': '..-', 'V': '...-', 'v': '...-', 'W': '.--', 'w': '.--', 'X': '-..-', 'x': '-..-', 'Y': '-.--', 'y': '-.--', 'Z': '--..', 'z': '--..', '0': '-----', ',': '--..--', '1': '.----', '.': '.-.-.-', '2': '..---', '?': '..--..', '3': '...--', ';': '-.-.-.', '4': '....-', ':': '---...', '5': '.....', "'": '.----.', '6': '-....', '-': '-....-', '7': '--...', '/': '-..-.', '8': '---..', '(': '-.--.-', '9': '----.', ')': '-.--.-', ' ': ' ', '_': '..--.-', } nowave = '\0' * 200 # If we play at 44.1 kHz (which we do), then if we produce one sine # wave in 100 samples, we get a tone of 441 Hz. If we produce two # sine waves in these 100 samples, we get a tone of 882 Hz. 882 Hz # appears to be a nice one for playing morse code. def mkwave(octave): sinewave = '' for i in range(100): val = int(math.sin(math.pi * i * octave / 50.0) * 30000) sinewave += chr((val >> 8) & 255) + chr(val & 255) return sinewave defaultwave = mkwave(OCTAVE) def main(): import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'o:p:') except getopt.error: sys.stderr.write('Usage ' + sys.argv[0] + ' [ -o outfile ] [ -p octave ] [ words ] ...\n') sys.exit(1) dev = None wave = defaultwave for o, a in opts: if o == '-o': import aifc dev = aifc.open(a, 'w') dev.setframerate(44100) dev.setsampwidth(2) dev.setnchannels(1) if o == '-p': wave = mkwave(int(a)) if not dev: import audiodev dev = audiodev.AudioDev() dev.setoutrate(44100) dev.setsampwidth(2) dev.setnchannels(1) dev.close = dev.stop dev.writeframesraw = dev.writeframes if args: source = [' '.join(args)] else: source = iter(sys.stdin.readline, '') for line in source: mline = morse(line) play(mline, dev, wave) if hasattr(dev, 'wait'): dev.wait() dev.close() # Convert a string to morse code with \001 between the characters in # the string. def morse(line): res = '' for c in line: try: res += morsetab[c] + '\001' except KeyError: pass return res # Play a line of morse code. def play(line, dev, wave): for c in line: if c == '.': sine(dev, DOT, wave) elif c == '-': sine(dev, DAH, wave) else: # space pause(dev, DAH + DOT) pause(dev, DOT) def sine(dev, length, wave): for i in range(length): dev.writeframesraw(wave) def pause(dev, length): for i in range(length): dev.writeframesraw(nowave) if __name__ == '__main__': main() PK%L]@Iww scripts/pi.pynuȯ#! /usr/bin/python2.7 # Print digits of pi forever. # # The algorithm, using Python's 'long' integers ("bignums"), works # with continued fractions, and was conceived by Lambert Meertens. # # See also the ABC Programmer's Handbook, by Geurts, Meertens & Pemberton, # published by Prentice-Hall (UK) Ltd., 1990. import sys def main(): k, a, b, a1, b1 = 2, 4, 1, 12, 4 while True: # Next approximation p, q, k = k*k, 2*k+1, k+1 a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1 # Print common digits d, d1 = a//b, a1//b1 while d == d1: output(d) a, a1 = 10*(a%b), 10*(a1%b1) d, d1 = a//b, a1//b1 def output(d): # Use write() to avoid spaces between the digits sys.stdout.write(str(d)) # Flush so the output is seen immediately sys.stdout.flush() if __name__ == "__main__": main() PK%L]Lscripts/beer.pyonu[ Afc@sddlZdZejdr5eejdZndZxPeeddD]<ZeeGdGHeedGHdGHeedGd GHqQWdS( iNidicCs.|dkrdS|dkr dSt|dS(Nisno more bottles of beerisone bottle of beers bottles of beer(tstr(tn((s)/usr/lib64/python2.7/Demo/scripts/beer.pytbottle s   is on the wall,t.sTake one down, pass it around,s on the wall.(tsysRtargvtintRtrangeti(((s)/usr/lib64/python2.7/Demo/scripts/beer.pyts   PK%L]`(scripts/fact.pyonu[ Afc@sHddlZddlmZdZdZedkrDendS(iN(tsqrtcCs|dkrtdn|dkr+gSg}x+|ddkr^|jd|d}q4Wt|d}d}xT||kr||dkr|j|||}t|d}qx|d7}qxW|dkr|j|n|S(Nisfact() argument should be >= 1iii(t ValueErrortappendR(tntrestlimitti((s)/usr/lib64/python2.7/Demo/scripts/fact.pytfact s&      cCsttjdkr%tjd}nttd}xJ|D]B}yt|}Wntk rm|GdGHq;X|Gt|GHq;WdS(Nitsis not an integer(tlentsystargvtitert raw_inputtintRR(tsourcetargR((s)/usr/lib64/python2.7/Demo/scripts/fact.pytmain#s   t__main__(R tmathRRRt__name__(((s)/usr/lib64/python2.7/Demo/scripts/fact.pyts   PK%L]йscripts/markov.pycnu[ Afc@s6dddYZdZedkr2endS(tMarkovcBs,eZdZdZdZdZRS(cCs||_||_i|_dS(N(thistsizetchoicettrans(tselfRR((s+/usr/lib64/python2.7/Demo/scripts/markov.pyt__init__s  cCs |jj|gj|dS(N(Rt setdefaulttappend(Rtstatetnext((s+/usr/lib64/python2.7/Demo/scripts/markov.pytadd scCs|j}|j}|d|d xFtt|D]2}||td|||!|||d!q6W||t||ddS(Nii(RR tNonetrangetlentmax(RtseqtnR ti((s+/usr/lib64/python2.7/Demo/scripts/markov.pytput s   0cCs|j}|j}|j}||d}xQtr~|tdt||}||}||}|sqPn||7}q.W|S(Ni(RRRR tTrueRR (RRRRRtsubseqtoptionsR ((s+/usr/lib64/python2.7/Demo/scripts/markov.pytgets      (t__name__t __module__RR RR(((s+/usr/lib64/python2.7/Demo/scripts/markov.pyRs   cCsddl}ddl}ddl}|jd}y|j|d\}}Wnm|jk rd|jdGHdGHdGHdGHd GHd GHd GHd GHd GHdGHdGHdGHdGH|jdnXd}t}d}x|D]\}} d|kodknrt|d}n|dkr&t}n|dkr?|d7}n|dkrTd}n|dkrt}qqW|sdg}nt ||j } yx|D]} | dkr|j } | j rdGHqqnt | d} |rdG| GdGHn| j} | j| jd}xh|D]`}|dkr;dGHn|j}|r!|rbt|}nd j|}| j|q!q!WqWWntk rd!GHnX| jsd"GHdS|rd#GHn|dkrIxN| jjD]=}|dkst||krt|G| j|GHqqW|dkrEtd$G| jd$GHnHnxtr| j}|rm|}n |j}d}d%}xF|D]>}|t||krHd}n|G|t|d7}qWHHqLWdS(&Niit0123456789cdwqs"Usage: %s [-#] [-cddqw] [file] ...isOptions:s$-#: 1-digit history size (default 2)s-c: characters (default)s -w: wordss-d: more debugging outputs-q: no debugging outputs3Input files (default stdin) are split in paragraphss1separated blank lines and each paragraph is splits0in words by whitespace, then reconcatenated withs#exactly one space separating words.s0Output consists of paragraphs separated by blanks4lines, where lines are no longer than 72 characters.is-0s-9s-cs-ds-qs-wt-sSorry, need stdin from filetrt processings...s s feeding ...t s-Interrupted -- continue with data read so farsNo valid input filessdone.tiH(tsystrandomtgetopttargvterrortexittFalsetintRRRtstdintisattytopentreadtclosetsplitttupletjoinRtKeyboardInterruptRtkeysR R treprR(RR R!targstoptsRtdo_wordstdebugtotatmtfilenametfttexttparalisttparatwordstdatatkeyRtlimittw((s+/usr/lib64/python2.7/Demo/scripts/markov.pyttest#s$                           t__main__N((RRCR(((s+/usr/lib64/python2.7/Demo/scripts/markov.pyts U PK%L]scripts/eqfix.pynuȯ#! /usr/bin/python2.7 # Fix Python source files to use the new equality test operator, i.e., # if x = y: ... # is changed to # if x == y: ... # The script correctly tokenizes the Python program to reliably # distinguish between assignments and equality tests. # # Command line arguments are files or directories to be processed. # Directories are searched recursively for files whose name looks # like a python module. # Symbolic links are always ignored (except as explicit directory # arguments). Of course, the original file is kept as a back-up # (with a "~" attached to its name). # It complains about binaries (files containing null bytes) # and about files that are ostensibly not Python files: if the first # line starts with '#!' and does not contain the string 'python'. # # Changes made are reported to stdout in a diff-like format. # # Undoubtedly you can do this using find and sed or perl, but this is # a nice example of Python code that recurses down a directory tree # and uses regular expressions. Also note several subtleties like # preserving the file's mode and avoiding to even write a temp file # when no changes are needed for a file. # # NB: by changing only the function fixline() you can turn this # into a program for a different change to Python programs... import sys import re import os from stat import * import string err = sys.stderr.write dbg = err rep = sys.stdout.write def main(): bad = 0 if not sys.argv[1:]: # No arguments err('usage: ' + sys.argv[0] + ' file-or-directory ...\n') sys.exit(2) for arg in sys.argv[1:]: if os.path.isdir(arg): if recursedown(arg): bad = 1 elif os.path.islink(arg): err(arg + ': will not process symbolic links\n') bad = 1 else: if fix(arg): bad = 1 sys.exit(bad) ispythonprog = re.compile('^[a-zA-Z0-9_]+\.py$') def ispython(name): return ispythonprog.match(name) >= 0 def recursedown(dirname): dbg('recursedown(%r)\n' % (dirname,)) bad = 0 try: names = os.listdir(dirname) except os.error, msg: err('%s: cannot list directory: %r\n' % (dirname, msg)) return 1 names.sort() subdirs = [] for name in names: if name in (os.curdir, os.pardir): continue fullname = os.path.join(dirname, name) if os.path.islink(fullname): pass elif os.path.isdir(fullname): subdirs.append(fullname) elif ispython(name): if fix(fullname): bad = 1 for fullname in subdirs: if recursedown(fullname): bad = 1 return bad def fix(filename): ## dbg('fix(%r)\n' % (dirname,)) try: f = open(filename, 'r') except IOError, msg: err('%s: cannot open: %r\n' % (filename, msg)) return 1 head, tail = os.path.split(filename) tempname = os.path.join(head, '@' + tail) g = None # If we find a match, we rewind the file and start over but # now copy everything to a temp file. lineno = 0 while 1: line = f.readline() if not line: break lineno = lineno + 1 if g is None and '\0' in line: # Check for binary files err(filename + ': contains null bytes; not fixed\n') f.close() return 1 if lineno == 1 and g is None and line[:2] == '#!': # Check for non-Python scripts words = string.split(line[2:]) if words and re.search('[pP]ython', words[0]) < 0: msg = filename + ': ' + words[0] msg = msg + ' script; not fixed\n' err(msg) f.close() return 1 while line[-2:] == '\\\n': nextline = f.readline() if not nextline: break line = line + nextline lineno = lineno + 1 newline = fixline(line) if newline != line: if g is None: try: g = open(tempname, 'w') except IOError, msg: f.close() err('%s: cannot create: %r\n' % (tempname, msg)) return 1 f.seek(0) lineno = 0 rep(filename + ':\n') continue # restart from the beginning rep(repr(lineno) + '\n') rep('< ' + line) rep('> ' + newline) if g is not None: g.write(newline) # End of file f.close() if not g: return 0 # No changes # Finishing touch -- move files # First copy the file's mode to the temp file try: statbuf = os.stat(filename) os.chmod(tempname, statbuf[ST_MODE] & 07777) except os.error, msg: err('%s: warning: chmod failed (%r)\n' % (tempname, msg)) # Then make a backup of the original file as filename~ try: os.rename(filename, filename + '~') except os.error, msg: err('%s: warning: backup failed (%r)\n' % (filename, msg)) # Now move the temp file to the original file try: os.rename(tempname, filename) except os.error, msg: err('%s: rename failed (%r)\n' % (filename, msg)) return 1 # Return succes return 0 from tokenize import tokenprog match = {'if':':', 'elif':':', 'while':':', 'return':'\n', \ '(':')', '[':']', '{':'}', '`':'`'} def fixline(line): # Quick check for easy case if '=' not in line: return line i, n = 0, len(line) stack = [] while i < n: j = tokenprog.match(line, i) if j < 0: # A bad token; forget about the rest of this line print '(Syntax error:)' print line, return line a, b = tokenprog.regs[3] # Location of the token proper token = line[a:b] i = i+j if stack and token == stack[-1]: del stack[-1] elif match.has_key(token): stack.append(match[token]) elif token == '=' and stack: line = line[:a] + '==' + line[b:] i, n = a + len('=='), len(line) elif token == '==' and not stack: print '(Warning: \'==\' at top level:)' print line, return line if __name__ == "__main__": main() PK%L]Xiscripts/queens.pynuȯ#! /usr/bin/python2.7 """N queens problem. The (well-known) problem is due to Niklaus Wirth. This solution is inspired by Dijkstra (Structured Programming). It is a classic recursive backtracking approach. """ N = 8 # Default; command line overrides class Queens: def __init__(self, n=N): self.n = n self.reset() def reset(self): n = self.n self.y = [None] * n # Where is the queen in column x self.row = [0] * n # Is row[y] safe? self.up = [0] * (2*n-1) # Is upward diagonal[x-y] safe? self.down = [0] * (2*n-1) # Is downward diagonal[x+y] safe? self.nfound = 0 # Instrumentation def solve(self, x=0): # Recursive solver for y in range(self.n): if self.safe(x, y): self.place(x, y) if x+1 == self.n: self.display() else: self.solve(x+1) self.remove(x, y) def safe(self, x, y): return not self.row[y] and not self.up[x-y] and not self.down[x+y] def place(self, x, y): self.y[x] = y self.row[y] = 1 self.up[x-y] = 1 self.down[x+y] = 1 def remove(self, x, y): self.y[x] = None self.row[y] = 0 self.up[x-y] = 0 self.down[x+y] = 0 silent = 0 # If true, count solutions only def display(self): self.nfound = self.nfound + 1 if self.silent: return print '+-' + '--'*self.n + '+' for y in range(self.n-1, -1, -1): print '|', for x in range(self.n): if self.y[x] == y: print "Q", else: print ".", print '|' print '+-' + '--'*self.n + '+' def main(): import sys silent = 0 n = N if sys.argv[1:2] == ['-n']: silent = 1 del sys.argv[1] if sys.argv[1:]: n = int(sys.argv[1]) q = Queens(n) q.silent = silent q.solve() print "Found", q.nfound, "solutions." if __name__ == "__main__": main() PK%L]0yܺ scripts/unbirthday.pycnu[ Afc@sbddlZddlZddlZdZdZdZdZedkr^endS(iNc Cstjdr#ttjd}nttd}d|koLdknrsdG|G|d}dG|GdGHn3d |kotjdknsd G|GHdStjd rttjd }nttd }d|kod knsdG|GHdStjdr'ttjd}nttd}|d kr]tj|r]d}n tj|}d|ko|knsdG|GdGHdS|||f}t |}dGt |GHtjd }t |}dGt |GH||krdGHdS||krdGHdS||}dG|GdGHd} xQt ||ddD]8} || ||fkoq|knrK| d} qKqKWdG| GdGH|d|dkrdGt | GdGHdGndGt || Gd GHdS(!NisIn which year were you born? iidsI'll assume that byilsyou meansand not the early Christian erai:s%It's hard to believe you were born inisAnd in which month? (1-12) i sThere is no month numberedis&And on what day of that month? (1-31) is There are nosdays in that month!sYou were born onsToday iss0You are a time traveler. Go back to the future!s'You were born today. Have a nice life!sYou have livedtdayssYou ares years oldsCongratulations! Today is yourtbirthdaysYesterday was yours Today is yourt unbirthday( tsystargvtintt raw_inputttimet localtimetcalendartisleaptmdaystmkdatetformattrangetnth( tyeartmonthtdaytmaxdayt bdaytupletbdaydatet todaytuplet todaydateRtagety((s//usr/lib64/python2.7/Demo/scripts/unbirthday.pytmain sb  &             % cCs'|\}}}d|tj||fS(Ns%d %s %d(R t month_name(t.0RRR((s//usr/lib64/python2.7/Demo/scripts/unbirthday.pyR Ns cCs8|dkrdS|dkr dS|dkr0dSd|S(Nit1stit2ndit3rds%dth((tn((s//usr/lib64/python2.7/Demo/scripts/unbirthday.pyRQs   cCs|\}}}|d}||dd}||dd}||dd}xPtd|D]?}|d krtj|r|d }q_|tj|}q_W||}|S( Nimiiicidiiiii(RR R R (RRRRRti((s//usr/lib64/python2.7/Demo/scripts/unbirthday.pyR Ws    t__main__(RRR RR RR t__name__(((s//usr/lib64/python2.7/Demo/scripts/unbirthday.pyts    B    PK%L]    scripts/lpwatch.pynuȯ#! /usr/bin/python2.7 # Watch line printer queue(s). # Intended for BSD 4.3 lpq. import os import sys import time DEF_PRINTER = 'psc' DEF_DELAY = 10 def main(): delay = DEF_DELAY # XXX Use getopt() later try: thisuser = os.environ['LOGNAME'] except: thisuser = os.environ['USER'] printers = sys.argv[1:] if printers: # Strip '-P' from printer names just in case # the user specified it... for i, name in enumerate(printers): if name[:2] == '-P': printers[i] = name[2:] else: if os.environ.has_key('PRINTER'): printers = [os.environ['PRINTER']] else: printers = [DEF_PRINTER] clearhome = os.popen('clear', 'r').read() while True: text = clearhome for name in printers: text += makestatus(name, thisuser) + '\n' print text time.sleep(delay) def makestatus(name, thisuser): pipe = os.popen('lpq -P' + name + ' 2>&1', 'r') lines = [] users = {} aheadbytes = 0 aheadjobs = 0 userseen = False totalbytes = 0 totaljobs = 0 for line in pipe: fields = line.split() n = len(fields) if len(fields) >= 6 and fields[n-1] == 'bytes': rank, user, job = fields[0:3] files = fields[3:-2] bytes = int(fields[n-2]) if user == thisuser: userseen = True elif not userseen: aheadbytes += bytes aheadjobs += 1 totalbytes += bytes totaljobs += 1 ujobs, ubytes = users.get(user, (0, 0)) ujobs += 1 ubytes += bytes users[user] = ujobs, ubytes else: if fields and fields[0] != 'Rank': line = line.strip() if line == 'no entries': line = name + ': idle' elif line[-22:] == ' is ready and printing': line = name lines.append(line) if totaljobs: line = '%d K' % ((totalbytes+1023) // 1024) if totaljobs != len(users): line += ' (%d jobs)' % totaljobs if len(users) == 1: line += ' for %s' % (users.keys()[0],) else: line += ' for %d users' % len(users) if userseen: if aheadjobs == 0: line += ' (%s first)' % thisuser else: line += ' (%d K before %s)' % ( (aheadbytes+1023) // 1024, thisuser) lines.append(line) sts = pipe.close() if sts: lines.append('lpq exit status %r' % (sts,)) return ': '.join(lines) if __name__ == "__main__": try: main() except KeyboardInterrupt: pass PK%L]1:t t scripts/mboxconvert.pynuȯ#! /usr/bin/python2.7 # Convert MH directories (1 message per file) or MMDF mailboxes (4x^A # delimited) to unix mailbox (From ... delimited) on stdout. # If -f is given, files contain one message per file (e.g. MH messages) import rfc822 import sys import time import os import stat import getopt import re def main(): dofile = mmdf try: opts, args = getopt.getopt(sys.argv[1:], 'f') except getopt.error, msg: sys.stderr.write('%s\n' % msg) sys.exit(2) for o, a in opts: if o == '-f': dofile = message if not args: args = ['-'] sts = 0 for arg in args: if arg == '-' or arg == '': sts = dofile(sys.stdin) or sts elif os.path.isdir(arg): sts = mh(arg) or sts elif os.path.isfile(arg): try: f = open(arg) except IOError, msg: sys.stderr.write('%s: %s\n' % (arg, msg)) sts = 1 continue sts = dofile(f) or sts f.close() else: sys.stderr.write('%s: not found\n' % arg) sts = 1 if sts: sys.exit(sts) numeric = re.compile('[1-9][0-9]*') def mh(dir): sts = 0 msgs = os.listdir(dir) for msg in msgs: if numeric.match(msg) != len(msg): continue fn = os.path.join(dir, msg) try: f = open(fn) except IOError, msg: sys.stderr.write('%s: %s\n' % (fn, msg)) sts = 1 continue sts = message(f) or sts return sts def mmdf(f): sts = 0 while 1: line = f.readline() if not line: break if line == '\1\1\1\1\n': sts = message(f, line) or sts else: sys.stderr.write( 'Bad line in MMFD mailbox: %r\n' % (line,)) return sts counter = 0 # for generating unique Message-ID headers def message(f, delimiter = ''): sts = 0 # Parse RFC822 header m = rfc822.Message(f) # Write unix header line fullname, email = m.getaddr('From') tt = m.getdate('Date') if tt: t = time.mktime(tt) else: sys.stderr.write( 'Unparseable date: %r\n' % (m.getheader('Date'),)) t = os.fstat(f.fileno())[stat.ST_MTIME] print 'From', email, time.ctime(t) # Copy RFC822 header for line in m.headers: print line, # Invent Message-ID header if none is present if not m.has_key('message-id'): global counter counter = counter + 1 msgid = "<%s.%d>" % (hex(t), counter) sys.stderr.write("Adding Message-ID %s (From %s)\n" % (msgid, email)) print "Message-ID:", msgid print # Copy body while 1: line = f.readline() if line == delimiter: break if not line: sys.stderr.write('Unexpected EOF in message\n') sts = 1 break if line[:5] == 'From ': line = '>' + line print line, # Print trailing newline print return sts if __name__ == "__main__": main() PK%L]scripts/from.pyonu[ Afc@sddlZddlZyejdZWn4eefk r_ejjdejdnXye eZ Wn"e k rejdenXxe j Z e sPne jdre d GxJe j Z e se dkrPne jdree d d!GqqWHqqWdS( iNtMAILsNo environment variable $MAIL isCannot open mailbox file: sFrom s s Subject: i (tsystostenvirontmailboxtAttributeErrortKeyErrortstderrtwritetexittopentmailtIOErrortreadlinetlinet startswithtrepr(((s)/usr/lib64/python2.7/Demo/scripts/from.pyts,   PK%L]scripts/from.pycnu[ Afc@sddlZddlZyejdZWn4eefk r_ejjdejdnXye eZ Wn"e k rejdenXxe j Z e sPne jdre d GxJe j Z e se dkrPne jdree d d!GqqWHqqWdS( iNtMAILsNo environment variable $MAIL isCannot open mailbox file: sFrom s s Subject: i (tsystostenvirontmailboxtAttributeErrortKeyErrortstderrtwritetexittopentmailtIOErrortreadlinetlinet startswithtrepr(((s)/usr/lib64/python2.7/Demo/scripts/from.pyts,   PK%L]zvscripts/READMEnu[This directory contains a collection of executable Python scripts. See also the Tools/scripts directory! beer.py Print the classic 'bottles of beer' list eqfix.py Fix .py files to use the correct equality test operator fact.py Factorize numbers find-uname.py Search for Unicode characters using regexps from.py Summarize mailbox lpwatch.py Watch BSD line printer queues makedir.py Like mkdir -p markov.py Markov chain simulation of words or characters mboxconvert.py Convert MH or MMDF mailboxes to unix mailbox format morse.py Produce morse code (audible or on AIFF file) newslist.py List all newsgroups on a NNTP server as HTML pages pi.py Print all digits of pi -- given enough time and memory pp.py Emulate some Perl command line options primes.py Print prime numbers queens.py Dijkstra's solution to Wirth's "N Queens problem" script.py Equivalent to BSD script(1) -- by Steen Lumholt unbirthday.py Print unbirthday count update.py Update a bunch of files according to a script. PK%L]qDscripts/eqfix.pyonu[ Afc@sddlZddlZddlZddlTddlZejjZeZej jZ dZ ej dZ dZdZdZddlmZid d 6d d 6d d 6d d6dd6dd6dd6dd6ZdZedkre ndS(iN(t*cCsd}tjds<tdtjddtjdnx}tjdD]n}tjj|rzt|rd}qqJtjj|rt|dd}qJt |rJd}qJqJWtj|dS(Niisusage: s file-or-directory ... is": will not process symbolic links ( tsystargvterrtexittostpathtisdirt recursedowntislinktfix(tbadtarg((s*/usr/lib64/python2.7/Demo/scripts/eqfix.pytmain)s    s^[a-zA-Z0-9_]+\.py$cCstj|dkS(Ni(t ispythonprogtmatch(tname((s*/usr/lib64/python2.7/Demo/scripts/eqfix.pytispython9scCs1td|fd}ytj|}Wn+tjk rW}td||fdSX|jg}x|D]}|tjtjfkrqontjj ||}tjj |rqotjj |r|j |qot |rot|rd}qqoqoWx#|D]}t|rd}qqW|S(Nsrecursedown(%r) is%s: cannot list directory: %r i(tdbgRtlistdirterrorRtsorttcurdirtpardirRtjoinR RtappendRR R(tdirnameR tnamestmsgtsubdirsRtfullname((s*/usr/lib64/python2.7/Demo/scripts/eqfix.pyR<s0      c Csyt|d}Wn(tk r=}td||fdSXtjj|\}}tjj|d|}d}d}x|j}|sPn|d}|dkrd|krt|d|j dS|dkrf|dkrf|d d krft j|d} | rft j d | ddkrf|d | d}|d }t||j dSnx>|d dkr|j} | sPn|| }|d}qiWt |} | |krm|dkr:yt|d}Wn2tk r}|j td||fdSX|jdd}t|dq~ntt|dtd|td| n|dk r~|j| q~q~W|j |sdSy+tj|} tj|| td@Wn*tjk r}td||fnXytj||dWn*tjk r=}td||fnXytj||Wn+tjk r}td||fdSXdS(Ntrs%s: cannot open: %r it@iss!: contains null bytes; not fixed is#!s [pP]ythons: s script; not fixed is\ tws%s: cannot create: %r s: s s< s> is%s: warning: chmod failed (%r) t~s %s: warning: backup failed (%r) s%s: rename failed (%r) (topentIOErrorRRRtsplitRtNonetreadlinetclosetstringtretsearchtfixlinetseektreptreprtwritetstattchmodtST_MODERtrename( tfilenametfRtheadttailttempnametgtlinenotlinetwordstnextlinetnewlinetstatbuf((s*/usr/lib64/python2.7/Demo/scripts/eqfix.pyR Rs   ("            (t tokenprogt:tifteliftwhiles treturnt)t(t]t[t}t{t`cCs?d|kr|Sdt|}}g}x||kr:tj||}|dkrcdGH|G|Stjd\}}|||!}||}|r||dkr|d=q,tj|r|jt|q,|dkr|r|| d||}|tdt|}}q,|dkr,| r,dGH|Gq,q,W|S(Nt=is(Syntax error:)iis==s(Warning: '==' at top level:)(tlenRARtregsthas_keyR(R<titntstacktjtatbttoken((s*/usr/lib64/python2.7/Demo/scripts/eqfix.pyR,s0       t__main__(RR*RR1R)tstderrR0RRtstdoutR.R tcompileRRRR ttokenizeRARR,t__name__(((s*/usr/lib64/python2.7/Demo/scripts/eqfix.pyts$           R  PK%L]Lscripts/beer.pycnu[ Afc@sddlZdZejdr5eejdZndZxPeeddD]<ZeeGdGHeedGHdGHeedGd GHqQWdS( iNidicCs.|dkrdS|dkr dSt|dS(Nisno more bottles of beerisone bottle of beers bottles of beer(tstr(tn((s)/usr/lib64/python2.7/Demo/scripts/beer.pytbottle s   is on the wall,t.sTake one down, pass it around,s on the wall.(tsysRtargvtintRtrangeti(((s)/usr/lib64/python2.7/Demo/scripts/beer.pyts   PK%L]Gx#scripts/makedir.pycnu[ Afc@sDddlZddlZdZdZedkr@endS(iNcCs&xtjdD]}t|qWdS(Ni(tsystargvtmakedirs(tp((s,/usr/lib64/python2.7/Demo/scripts/makedir.pytmain scCsR|rNtjj| rNtjj|\}}t|tj|dndS(Ni(tostpathtisdirtsplitRtmkdir(Rtheadttail((s,/usr/lib64/python2.7/Demo/scripts/makedir.pyRs t__main__(RRRRt__name__(((s,/usr/lib64/python2.7/Demo/scripts/makedir.pyts   PK%L]VB scripts/queens.pyonu[ Afc@sBdZdZdddYZdZedkr>endS(sN queens problem. The (well-known) problem is due to Niklaus Wirth. This solution is inspired by Dijkstra (Structured Programming). It is a classic recursive backtracking approach. itQueenscBsSeZedZdZddZdZdZdZdZ dZ RS(cCs||_|jdS(N(tntreset(tselfR((s+/usr/lib64/python2.7/Demo/scripts/queens.pyt__init__s cCsf|j}dg||_dg||_dgd|d|_dgd|d|_d|_dS(Niii(RtNonetytrowtuptdowntnfound(RR((s+/usr/lib64/python2.7/Demo/scripts/queens.pyRs  icCsx}t|jD]l}|j||r|j|||d|jkrX|jn|j|d|j||qqWdS(Ni(trangeRtsafetplacetdisplaytsolvetremove(RtxR((s+/usr/lib64/python2.7/Demo/scripts/queens.pyRs cCs0|j| o/|j|| o/|j|| S(N(RRR (RRR((s+/usr/lib64/python2.7/Demo/scripts/queens.pyR &scCs@||j| s 8  PK%L]LC C scripts/unbirthday.pynuȯ#! /usr/bin/python2.7 # Calculate your unbirthday count (see Alice in Wonderland). # This is defined as the number of days from your birth until today # that weren't your birthday. (The day you were born is not counted). # Leap years make it interesting. import sys import time import calendar def main(): if sys.argv[1:]: year = int(sys.argv[1]) else: year = int(raw_input('In which year were you born? ')) if 0 <= year < 100: print "I'll assume that by", year, year = year + 1900 print 'you mean', year, 'and not the early Christian era' elif not (1850 <= year <= time.localtime()[0]): print "It's hard to believe you were born in", year return if sys.argv[2:]: month = int(sys.argv[2]) else: month = int(raw_input('And in which month? (1-12) ')) if not (1 <= month <= 12): print 'There is no month numbered', month return if sys.argv[3:]: day = int(sys.argv[3]) else: day = int(raw_input('And on what day of that month? (1-31) ')) if month == 2 and calendar.isleap(year): maxday = 29 else: maxday = calendar.mdays[month] if not (1 <= day <= maxday): print 'There are no', day, 'days in that month!' return bdaytuple = (year, month, day) bdaydate = mkdate(bdaytuple) print 'You were born on', format(bdaytuple) todaytuple = time.localtime()[:3] todaydate = mkdate(todaytuple) print 'Today is', format(todaytuple) if bdaytuple > todaytuple: print 'You are a time traveler. Go back to the future!' return if bdaytuple == todaytuple: print 'You were born today. Have a nice life!' return days = todaydate - bdaydate print 'You have lived', days, 'days' age = 0 for y in range(year, todaytuple[0] + 1): if bdaytuple < (y, month, day) <= todaytuple: age = age + 1 print 'You are', age, 'years old' if todaytuple[1:] == bdaytuple[1:]: print 'Congratulations! Today is your', nth(age), 'birthday' print 'Yesterday was your', else: print 'Today is your', print nth(days - age), 'unbirthday' def format((year, month, day)): return '%d %s %d' % (day, calendar.month_name[month], year) def nth(n): if n == 1: return '1st' if n == 2: return '2nd' if n == 3: return '3rd' return '%dth' % n def mkdate((year, month, day)): # January 1st, in 0 A.D. is arbitrarily defined to be day 1, # even though that day never actually existed and the calendar # was different then... days = year*365 # years, roughly days = days + (year+3)//4 # plus leap years, roughly days = days - (year+99)//100 # minus non-leap years every century days = days + (year+399)//400 # plus leap years every 4 centirues for i in range(1, month): if i == 2 and calendar.isleap(year): days = days + 29 else: days = days + calendar.mdays[i] days = days + day return days if __name__ == "__main__": main() PK%L]#scripts/primes.pycnu[ Afc@s,dZdZedkr(endS(cCs|dko|knr$dGHndg}d}x||krx2|D]*}||dkso|||krIPqIqIW||dkr|j|||kr|GHqn|d7}q6WdS(Niii(tappend(tmintmaxtprimestitp((s+/usr/lib64/python2.7/Demo/scripts/primes.pyRs      cCsoddl}d\}}|jdr^t|jd}|jdr^t|jd}q^nt||dS(Niiii(ii(tsystargvtintR(RRR((s+/usr/lib64/python2.7/Demo/scripts/primes.pytmains    t__main__N(RR t__name__(((s+/usr/lib64/python2.7/Demo/scripts/primes.pyts  PK%L]aPOOscripts/morse.pycnu[ Afc@sddlZddlZddlZdZdeZdZiJdd6dd6dd 6dd 6d d 6d d 6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6d d!6d d"6d#d$6d#d%6d&d'6d&d(6d)d*6d)d+6d,d-6d,d.6d/d06d/d16d2d36d2d46d5d66d5d76d8d96d8d:6d;d<6d;d=6d>d?6d>d@6dAdB6dAdC6dDdE6dDdF6dGdH6dGdI6dJdK6dJdL6dMdN6dMdO6dPdQ6dPdR6dSdT6dUdV6dWdX6dYd6dZd[6d\d]6d^d_6d`da6dbdc6ddde6dfdg6dhdi6djdk6dld>6dmdn6dodp6dqdr6dsdt6dudv6dsdw6dxdx6dydz6Zd{d|Zd}ZeeZ d~Z dZ dZ dZ dZedkre ndS(iNiiis.-tAtas-...tBtbs-.-.tCtcs-..tDtdt.tEtes..-.tFtfs--.tGtgs....tHths..tItis.---tJtjs-.-tKtks.-..tLtls--tMtms-.tNtns---tOtos.--.tPtps--.-tQtqs.-.tRtrs...tStst-tTtts..-tUtus...-tVtvs.--tWtws-..-tXtxs-.--tYtys--..tZtzs-----t0s--..--t,s.----t1s.-.-.-s..---t2s..--..t?s...--t3s-.-.-.t;s....-t4s---...t:s.....t5s.----.t's-....t6s-....-s--...t7s-..-.t/s---..t8s-.--.-t(s----.t9t)t s..--.-t_sicCsod}xbtdD]T}ttjtj||dd}|t|d?d@t|d@7}qW|S(NtidgI@i0uii(trangetinttmathtsintpitchr(toctavetsinewaveRtval((s*/usr/lib64/python2.7/Demo/scripts/morse.pytmkwave<s (*c Csddl}y#|jtjdd\}}Wn@|jk rqtjjdtjddtjdnXd}t}x|D]\}}|dkrddl }|j |d}|j d |j d |j dn|d krtt|}qqW|sjddl}|j}|jd |j d |j d|j|_|j|_n|rd j|g} nttjjd } xF| D]>} t| } t| ||t|dr|jqqW|jdS(Niiso:p:sUsage is, [ -o outfile ] [ -p octave ] [ words ] ... s-oR/iDis-pRHRJtwait(tgetopttsystargvterrortstderrtwritetexittNonet defaultwavetaifctopent setframeratet setsampwidtht setnchannelsRTRLtaudiodevtAudioDevt setoutratetstoptcloset writeframestwriteframesrawtjointitertstdintreadlinetmorsetplaythasattrRU( RVtoptstargstdevtwaveRRR_Rdtsourcetlinetmline((s*/usr/lib64/python2.7/Demo/scripts/morse.pytmainEsF #             cCsEd}x8|D]0}y|t|d7}Wq tk r<q Xq W|S(NRJs(tmorsetabtKeyError(RwtresR((s*/usr/lib64/python2.7/Demo/scripts/morse.pyRoms  cCsqxj|D]b}|dkr,t|t|n0|dkrKt|t|nt|ttt|tqWdS(NRR'(tsinetDOTtDAHtpause(RwRtRuR((s*/usr/lib64/python2.7/Demo/scripts/morse.pyRpws   cCs(x!t|D]}|j|q WdS(N(RKRj(RttlengthRuR((s*/usr/lib64/python2.7/Demo/scripts/morse.pyR}scCs(x!t|D]}|jtq WdS(N(RKRjtnowave(RtRR((s*/usr/lib64/python2.7/Demo/scripts/morse.pyRst__main__(RWRMRdR~RtOCTAVERzRRTR^RyRoRpR}Rt__name__(((s*/usr/lib64/python2.7/Demo/scripts/morse.pytsf$     (   PK%L]]">scripts/find-uname.pynuȯ#! /usr/bin/python2.7 """ For each argument on the command line, look for it in the set of all Unicode names. Arguments are treated as case-insensitive regular expressions, e.g.: % find-uname 'small letter a$' 'horizontal line' *** small letter a$ matches *** LATIN SMALL LETTER A (97) COMBINING LATIN SMALL LETTER A (867) CYRILLIC SMALL LETTER A (1072) PARENTHESIZED LATIN SMALL LETTER A (9372) CIRCLED LATIN SMALL LETTER A (9424) FULLWIDTH LATIN SMALL LETTER A (65345) *** horizontal line matches *** HORIZONTAL LINE EXTENSION (9135) """ import unicodedata import sys import re def main(args): unicode_names = [] for ix in range(sys.maxunicode+1): try: unicode_names.append((ix, unicodedata.name(unichr(ix)))) except ValueError: # no name for the character pass for arg in args: pat = re.compile(arg, re.I) matches = [(y,x) for (x,y) in unicode_names if pat.search(y) is not None] if matches: print "***", arg, "matches", "***" for match in matches: print "%s (%d)" % match if __name__ == "__main__": main(sys.argv[1:]) PK%L]qDscripts/eqfix.pycnu[ Afc@sddlZddlZddlZddlTddlZejjZeZej jZ dZ ej dZ dZdZdZddlmZid d 6d d 6d d 6d d6dd6dd6dd6dd6ZdZedkre ndS(iN(t*cCsd}tjds<tdtjddtjdnx}tjdD]n}tjj|rzt|rd}qqJtjj|rt|dd}qJt |rJd}qJqJWtj|dS(Niisusage: s file-or-directory ... is": will not process symbolic links ( tsystargvterrtexittostpathtisdirt recursedowntislinktfix(tbadtarg((s*/usr/lib64/python2.7/Demo/scripts/eqfix.pytmain)s    s^[a-zA-Z0-9_]+\.py$cCstj|dkS(Ni(t ispythonprogtmatch(tname((s*/usr/lib64/python2.7/Demo/scripts/eqfix.pytispython9scCs1td|fd}ytj|}Wn+tjk rW}td||fdSX|jg}x|D]}|tjtjfkrqontjj ||}tjj |rqotjj |r|j |qot |rot|rd}qqoqoWx#|D]}t|rd}qqW|S(Nsrecursedown(%r) is%s: cannot list directory: %r i(tdbgRtlistdirterrorRtsorttcurdirtpardirRtjoinR RtappendRR R(tdirnameR tnamestmsgtsubdirsRtfullname((s*/usr/lib64/python2.7/Demo/scripts/eqfix.pyR<s0      c Csyt|d}Wn(tk r=}td||fdSXtjj|\}}tjj|d|}d}d}x|j}|sPn|d}|dkrd|krt|d|j dS|dkrf|dkrf|d d krft j|d} | rft j d | ddkrf|d | d}|d }t||j dSnx>|d dkr|j} | sPn|| }|d}qiWt |} | |krm|dkr:yt|d}Wn2tk r}|j td||fdSX|jdd}t|dq~ntt|dtd|td| n|dk r~|j| q~q~W|j |sdSy+tj|} tj|| td@Wn*tjk r}td||fnXytj||dWn*tjk r=}td||fnXytj||Wn+tjk r}td||fdSXdS(Ntrs%s: cannot open: %r it@iss!: contains null bytes; not fixed is#!s [pP]ythons: s script; not fixed is\ tws%s: cannot create: %r s: s s< s> is%s: warning: chmod failed (%r) t~s %s: warning: backup failed (%r) s%s: rename failed (%r) (topentIOErrorRRRtsplitRtNonetreadlinetclosetstringtretsearchtfixlinetseektreptreprtwritetstattchmodtST_MODERtrename( tfilenametfRtheadttailttempnametgtlinenotlinetwordstnextlinetnewlinetstatbuf((s*/usr/lib64/python2.7/Demo/scripts/eqfix.pyR Rs   ("            (t tokenprogt:tifteliftwhiles treturnt)t(t]t[t}t{t`cCs?d|kr|Sdt|}}g}x||kr:tj||}|dkrcdGH|G|Stjd\}}|||!}||}|r||dkr|d=q,tj|r|jt|q,|dkr|r|| d||}|tdt|}}q,|dkr,| r,dGH|Gq,q,W|S(Nt=is(Syntax error:)iis==s(Warning: '==' at top level:)(tlenRARtregsthas_keyR(R<titntstacktjtatbttoken((s*/usr/lib64/python2.7/Demo/scripts/eqfix.pyR,s0       t__main__(RR*RR1R)tstderrR0RRtstdoutR.R tcompileRRRR ttokenizeRARR,t__name__(((s*/usr/lib64/python2.7/Demo/scripts/eqfix.pyts$           R  PK%L]ټgllscripts/fact.pynuȯ#! /usr/bin/python2.7 # Factorize numbers. # The algorithm is not efficient, but easy to understand. # If there are large factors, it will take forever to find them, # because we try all odd numbers between 3 and sqrt(n)... import sys from math import sqrt def fact(n): if n < 1: raise ValueError('fact() argument should be >= 1') if n == 1: return [] # special case res = [] # Treat even factors special, so we can use i += 2 later while n % 2 == 0: res.append(2) n //= 2 # Try odd numbers up to sqrt(n) limit = sqrt(n+1) i = 3 while i <= limit: if n % i == 0: res.append(i) n //= i limit = sqrt(n+1) else: i += 2 if n != 1: res.append(n) return res def main(): if len(sys.argv) > 1: source = sys.argv[1:] else: source = iter(raw_input, '') for arg in source: try: n = int(arg) except ValueError: print arg, 'is not an integer' else: print n, fact(n) if __name__ == "__main__": main() PK%L]hq scripts/update.pycnu[ Afc@soddlZddlZddlZdZejeZdddYZdZedkrkendS(iNs^([^: ]+):([1-9][0-9]*):tFileObjcBs#eZdZdZdZRS(cCsk||_d|_yt|dj|_Wn*tk rZ}d|G|GHd|_dSXdG|jGHdS(Nitrs*** Can't open "%s":tdiffing(tfilenametchangedtopent readlinestlinestIOErrortNone(tselfRtmsg((s+/usr/lib64/python2.7/Demo/scripts/update.pyt__init__s    cCs|jsdG|jGHdSy0tj|j|jdt|jd}Wn-tjtfk rx}d|jG|GHdSXdG|jGHx|jD]}|j|qW|j d|_dS(Ns no changes tot~tws*** Can't rewrite "%s":twritingi( RRtostrenameRterrorRRtwritetclose(R tfpR tline((s+/usr/lib64/python2.7/Demo/scripts/update.pytfinishs    cCs|jdkr'd|j||fGdSt|d}d|koWt|jknstd|j||fGdS|j||krd|j||fGdS|jsd|_nd||fGHdG|j|GdGH||j|(RR RtevaltlenR(R tlinenotrestti((s+/usr/lib64/python2.7/Demo/scripts/update.pytprocess,s(%   (t__name__t __module__R RR(((s+/usr/lib64/python2.7/Demo/scripts/update.pyRs cCs1tjdrayttjdd}Wqjtk r]}dtjdG|GHtjdqjXn tj}d}x|j}|s|r|jnPnt j |}|dkrdG|Gqsnt j dd\}}| s||j kr|r|jnt |}n|j|||qsWdS(NiRsCan't open "%s":is Funny line:i(tsystargvRRtexittstdinR treadlineRtprogtmatchtgroupRRR(RR tcurfileRtnRR((s+/usr/lib64/python2.7/Demo/scripts/update.pytmainBs0      t__main__(( RR"tretpattcompileR'RR,R (((s+/usr/lib64/python2.7/Demo/scripts/update.pyt s   2  PK%L]`(scripts/fact.pycnu[ Afc@sHddlZddlmZdZdZedkrDendS(iN(tsqrtcCs|dkrtdn|dkr+gSg}x+|ddkr^|jd|d}q4Wt|d}d}xT||kr||dkr|j|||}t|d}qx|d7}qxW|dkr|j|n|S(Nisfact() argument should be >= 1iii(t ValueErrortappendR(tntrestlimitti((s)/usr/lib64/python2.7/Demo/scripts/fact.pytfact s&      cCsttjdkr%tjd}nttd}xJ|D]B}yt|}Wntk rm|GdGHq;X|Gt|GHq;WdS(Nitsis not an integer(tlentsystargvtitert raw_inputtintRR(tsourcetargR((s)/usr/lib64/python2.7/Demo/scripts/fact.pytmain#s   t__main__(R tmathRRRt__name__(((s)/usr/lib64/python2.7/Demo/scripts/fact.pyts   PK%L](N scripts/update.pynuȯ#! /usr/bin/python2.7 # Update a bunch of files according to a script. # The input file contains lines of the form ::, # meaning that the given line of the given file is to be replaced # by the given text. This is useful for performing global substitutions # on grep output: import os import sys import re pat = '^([^: \t\n]+):([1-9][0-9]*):' prog = re.compile(pat) class FileObj: def __init__(self, filename): self.filename = filename self.changed = 0 try: self.lines = open(filename, 'r').readlines() except IOError, msg: print '*** Can\'t open "%s":' % filename, msg self.lines = None return print 'diffing', self.filename def finish(self): if not self.changed: print 'no changes to', self.filename return try: os.rename(self.filename, self.filename + '~') fp = open(self.filename, 'w') except (os.error, IOError), msg: print '*** Can\'t rewrite "%s":' % self.filename, msg return print 'writing', self.filename for line in self.lines: fp.write(line) fp.close() self.changed = 0 def process(self, lineno, rest): if self.lines is None: print '(not processed): %s:%s:%s' % ( self.filename, lineno, rest), return i = eval(lineno) - 1 if not 0 <= i < len(self.lines): print '*** Line number out of range: %s:%s:%s' % ( self.filename, lineno, rest), return if self.lines[i] == rest: print '(no change): %s:%s:%s' % ( self.filename, lineno, rest), return if not self.changed: self.changed = 1 print '%sc%s' % (lineno, lineno) print '<', self.lines[i], print '---' self.lines[i] = rest print '>', self.lines[i], def main(): if sys.argv[1:]: try: fp = open(sys.argv[1], 'r') except IOError, msg: print 'Can\'t open "%s":' % sys.argv[1], msg sys.exit(1) else: fp = sys.stdin curfile = None while 1: line = fp.readline() if not line: if curfile: curfile.finish() break n = prog.match(line) if n < 0: print 'Funny line:', line, continue filename, lineno = prog.group(1, 2) if not curfile or filename <> curfile.filename: if curfile: curfile.finish() curfile = FileObj(filename) curfile.process(lineno, line[n:]) if __name__ == "__main__": main() PK%L]) - - scripts/lpwatch.pycnu[ Afc@stddlZddlZddlZdZdZdZdZedkrpy eWqpek rlqpXndS(iNtpsci cCst}ytjd}Wntjd}nXtjd}|rxlt|D]-\}}|d dkrN|d||&1RiiitbytesiiitRanks no entriess: idleis is ready and printings%d Kiis (%d jobs)s for %ss for %d userss (%s first)s (%d K before %s)slpq exit status %rs: (ii( RRtFalsetsplittlentintRtgettstriptappendtkeystclosetjoin(RRtpipetlinestuserst aheadbytest aheadjobstuserseent totalbytest totaljobstlinetfieldstntranktusertjobtfilesRtujobstubyteststs((s,/usr/lib64/python2.7/Demo/scripts/lpwatch.pyR)sd   &               t__main__( RR RR RRRt__name__tKeyboardInterrupt(((s,/usr/lib64/python2.7/Demo/scripts/lpwatch.pyts     9   PK%L] Bscripts/find-uname.pyonu[ Afc@sWdZddlZddlZddlZdZedkrSeejdndS(s) For each argument on the command line, look for it in the set of all Unicode names. Arguments are treated as case-insensitive regular expressions, e.g.: % find-uname 'small letter a$' 'horizontal line' *** small letter a$ matches *** LATIN SMALL LETTER A (97) COMBINING LATIN SMALL LETTER A (867) CYRILLIC SMALL LETTER A (1072) PARENTHESIZED LATIN SMALL LETTER A (9372) CIRCLED LATIN SMALL LETTER A (9424) FULLWIDTH LATIN SMALL LETTER A (65345) *** horizontal line matches *** HORIZONTAL LINE EXTENSION (9135) iNc Csg}xUttjdD]@}y&|j|tjt|fWqtk rYqXqWx|D]}tj |tj }g|D]-\}}|j |dk r||f^q}|redG|GdGdGHx|D]}d|GHqWqeqeWdS(Nis***tmatchess%s (%d)( trangetsyst maxunicodetappendt unicodedatatnametunichrt ValueErrortretcompiletItsearchtNone( targst unicode_namestixtargtpattxtyRtmatch((s//usr/lib64/python2.7/Demo/scripts/find-uname.pytmains&  ' t__main__i(t__doc__RRR Rt__name__targv(((s//usr/lib64/python2.7/Demo/scripts/find-uname.pyts      PK%L]0yܺ scripts/unbirthday.pyonu[ Afc@sbddlZddlZddlZdZdZdZdZedkr^endS(iNc Cstjdr#ttjd}nttd}d|koLdknrsdG|G|d}dG|GdGHn3d |kotjdknsd G|GHdStjd rttjd }nttd }d|kod knsdG|GHdStjdr'ttjd}nttd}|d kr]tj|r]d}n tj|}d|ko|knsdG|GdGHdS|||f}t |}dGt |GHtjd }t |}dGt |GH||krdGHdS||krdGHdS||}dG|GdGHd} xQt ||ddD]8} || ||fkoq|knrK| d} qKqKWdG| GdGH|d|dkrdGt | GdGHdGndGt || Gd GHdS(!NisIn which year were you born? iidsI'll assume that byilsyou meansand not the early Christian erai:s%It's hard to believe you were born inisAnd in which month? (1-12) i sThere is no month numberedis&And on what day of that month? (1-31) is There are nosdays in that month!sYou were born onsToday iss0You are a time traveler. Go back to the future!s'You were born today. Have a nice life!sYou have livedtdayssYou ares years oldsCongratulations! Today is yourtbirthdaysYesterday was yours Today is yourt unbirthday( tsystargvtintt raw_inputttimet localtimetcalendartisleaptmdaystmkdatetformattrangetnth( tyeartmonthtdaytmaxdayt bdaytupletbdaydatet todaytuplet todaydateRtagety((s//usr/lib64/python2.7/Demo/scripts/unbirthday.pytmain sb  &             % cCs'|\}}}d|tj||fS(Ns%d %s %d(R t month_name(t.0RRR((s//usr/lib64/python2.7/Demo/scripts/unbirthday.pyR Ns cCs8|dkrdS|dkr dS|dkr0dSd|S(Nit1stit2ndit3rds%dth((tn((s//usr/lib64/python2.7/Demo/scripts/unbirthday.pyRQs   cCs|\}}}|d}||dd}||dd}||dd}xPtd|D]?}|d krtj|r|d }q_|tj|}q_W||}|S( Nimiiicidiiiii(RR R R (RRRRRti((s//usr/lib64/python2.7/Demo/scripts/unbirthday.pyR Ws    t__main__(RRR RR RR t__name__(((s//usr/lib64/python2.7/Demo/scripts/unbirthday.pyts    B    PK%L]R~scripts/pi.pyonu[ Afc@s8ddlZdZdZedkr4endS(iNc Csd\}}}}}xtr||d|d|d}}}||||||||||f\}}}}||||}}xL||krt|d||d||}}||||}}qWqWdS(Niiii i (iiii i(tTruetoutput( tktatbta1tb1tptqtdtd1((s'/usr/lib64/python2.7/Demo/scripts/pi.pytmain s $6 cCs'tjjt|tjjdS(N(tsyststdouttwritetstrtflush(R ((s'/usr/lib64/python2.7/Demo/scripts/pi.pyRst__main__(R R Rt__name__(((s'/usr/lib64/python2.7/Demo/scripts/pi.pyt s   PK%L]) - - scripts/lpwatch.pyonu[ Afc@stddlZddlZddlZdZdZdZdZedkrpy eWqpek rlqpXndS(iNtpsci cCst}ytjd}Wntjd}nXtjd}|rxlt|D]-\}}|d dkrN|d||&1RiiitbytesiiitRanks no entriess: idleis is ready and printings%d Kiis (%d jobs)s for %ss for %d userss (%s first)s (%d K before %s)slpq exit status %rs: (ii( RRtFalsetsplittlentintRtgettstriptappendtkeystclosetjoin(RRtpipetlinestuserst aheadbytest aheadjobstuserseent totalbytest totaljobstlinetfieldstntranktusertjobtfilesRtujobstubyteststs((s,/usr/lib64/python2.7/Demo/scripts/lpwatch.pyR)sd   &               t__main__( RR RR RRRt__name__tKeyboardInterrupt(((s,/usr/lib64/python2.7/Demo/scripts/lpwatch.pyts     9   PK%L] Bscripts/find-uname.pycnu[ Afc@sWdZddlZddlZddlZdZedkrSeejdndS(s) For each argument on the command line, look for it in the set of all Unicode names. Arguments are treated as case-insensitive regular expressions, e.g.: % find-uname 'small letter a$' 'horizontal line' *** small letter a$ matches *** LATIN SMALL LETTER A (97) COMBINING LATIN SMALL LETTER A (867) CYRILLIC SMALL LETTER A (1072) PARENTHESIZED LATIN SMALL LETTER A (9372) CIRCLED LATIN SMALL LETTER A (9424) FULLWIDTH LATIN SMALL LETTER A (65345) *** horizontal line matches *** HORIZONTAL LINE EXTENSION (9135) iNc Csg}xUttjdD]@}y&|j|tjt|fWqtk rYqXqWx|D]}tj |tj }g|D]-\}}|j |dk r||f^q}|redG|GdGdGHx|D]}d|GHqWqeqeWdS(Nis***tmatchess%s (%d)( trangetsyst maxunicodetappendt unicodedatatnametunichrt ValueErrortretcompiletItsearchtNone( targst unicode_namestixtargtpattxtyRtmatch((s//usr/lib64/python2.7/Demo/scripts/find-uname.pytmains&  ' t__main__i(t__doc__RRR Rt__name__targv(((s//usr/lib64/python2.7/Demo/scripts/find-uname.pyts      PK%L]*R  scripts/pp.pycnu[ Afc@s_ddlZddlZdZgZdZdZdZdZdZy#ejej dd\Z Z WnDej k rZ ejjdej de fejdnXxe D]\ZZedkrdZqed krdZqed krdZqed kr4x{ejd D]ZejeqWqed krIeZqedkrddZdZqedkrdZdZqeGdGHqWe se jdnes(e ddkrejZnee ddZx+ejZesPnejed qW[e d=e s(e jdq(ner@dgZgZnferddddddddddddd d!d"d#d$gZd%d"d&d'd(gZnd)gZgZd jed Zx eD]Zed*ed 7ZqWed jed 7ZddlZejZejeej erNddl!Z!e!j"d+ej#fn e$ej#dS(,iNtiis acde:F:nps%s: %s is-as-cs-ds-es s-Fs-ns-psnot recognized???t-trsif 0:s LINECOUNT = 0sfor FILE in ARGS:s if FILE == '-':s FP = sys.stdins else:s FP = open(FILE, 'r')s LINENO = 0s while 1:s LINE = FP.readline()s if not LINE: breaks LINENO = LINENO + 1s! LINECOUNT = LINECOUNT + 1s L = LINE[:-1]s aflag = AFLAGs if aflag:s" if FS: F = L.split(FS)s else: F = L.split()s if not PFLAG: continues# if FS: print FS.join(F)s# else: print ' '.join(F)s else: print Lsif 1:s s execfile(%r)(%tsystgetopttFStSCRIPTtAFLAGtCFLAGtDFLAGtNFLAGtPFLAGtargvtoptlisttARGSterrortmsgtstderrtwritetexittoptiontoptargtsplittlinetappendtstdintfptopentreadlinetprologuetepiloguetjointprogramttempfiletNamedTemporaryFiletflushtpdbtruntnametexecfile(((s'/usr/lib64/python2.7/Demo/scripts/pp.pyts  #!                           PK%L]MHYZZscripts/primes.pynuȯ#! /usr/bin/python2.7 # Print prime numbers in a given range def primes(min, max): if max >= 2 >= min: print 2 primes = [2] i = 3 while i <= max: for p in primes: if i % p == 0 or p*p > i: break if i % p != 0: primes.append(i) if i >= min: print i i += 2 def main(): import sys min, max = 2, 0x7fffffff if sys.argv[1:]: min = int(sys.argv[1]) if sys.argv[2:]: max = int(sys.argv[2]) primes(min, max) if __name__ == "__main__": main() PK%L]йscripts/markov.pyonu[ Afc@s6dddYZdZedkr2endS(tMarkovcBs,eZdZdZdZdZRS(cCs||_||_i|_dS(N(thistsizetchoicettrans(tselfRR((s+/usr/lib64/python2.7/Demo/scripts/markov.pyt__init__s  cCs |jj|gj|dS(N(Rt setdefaulttappend(Rtstatetnext((s+/usr/lib64/python2.7/Demo/scripts/markov.pytadd scCs|j}|j}|d|d xFtt|D]2}||td|||!|||d!q6W||t||ddS(Nii(RR tNonetrangetlentmax(RtseqtnR ti((s+/usr/lib64/python2.7/Demo/scripts/markov.pytput s   0cCs|j}|j}|j}||d}xQtr~|tdt||}||}||}|sqPn||7}q.W|S(Ni(RRRR tTrueRR (RRRRRtsubseqtoptionsR ((s+/usr/lib64/python2.7/Demo/scripts/markov.pytgets      (t__name__t __module__RR RR(((s+/usr/lib64/python2.7/Demo/scripts/markov.pyRs   cCsddl}ddl}ddl}|jd}y|j|d\}}Wnm|jk rd|jdGHdGHdGHdGHd GHd GHd GHd GHd GHdGHdGHdGHdGH|jdnXd}t}d}x|D]\}} d|kodknrt|d}n|dkr&t}n|dkr?|d7}n|dkrTd}n|dkrt}qqW|sdg}nt ||j } yx|D]} | dkr|j } | j rdGHqqnt | d} |rdG| GdGHn| j} | j| jd}xh|D]`}|dkr;dGHn|j}|r!|rbt|}nd j|}| j|q!q!WqWWntk rd!GHnX| jsd"GHdS|rd#GHn|dkrIxN| jjD]=}|dkst||krt|G| j|GHqqW|dkrEtd$G| jd$GHnHnxtr| j}|rm|}n |j}d}d%}xF|D]>}|t||krHd}n|G|t|d7}qWHHqLWdS(&Niit0123456789cdwqs"Usage: %s [-#] [-cddqw] [file] ...isOptions:s$-#: 1-digit history size (default 2)s-c: characters (default)s -w: wordss-d: more debugging outputs-q: no debugging outputs3Input files (default stdin) are split in paragraphss1separated blank lines and each paragraph is splits0in words by whitespace, then reconcatenated withs#exactly one space separating words.s0Output consists of paragraphs separated by blanks4lines, where lines are no longer than 72 characters.is-0s-9s-cs-ds-qs-wt-sSorry, need stdin from filetrt processings...s s feeding ...t s-Interrupted -- continue with data read so farsNo valid input filessdone.tiH(tsystrandomtgetopttargvterrortexittFalsetintRRRtstdintisattytopentreadtclosetsplitttupletjoinRtKeyboardInterruptRtkeysR R treprR(RR R!targstoptsRtdo_wordstdebugtotatmtfilenametfttexttparalisttparatwordstdatatkeyRtlimittw((s+/usr/lib64/python2.7/Demo/scripts/markov.pyttest#s$                           t__main__N((RRCR(((s+/usr/lib64/python2.7/Demo/scripts/markov.pyts U PK%L];scripts/script.pynuȯ#! /usr/bin/python2.7 # script.py -- Make typescript of terminal session. # Usage: # -a Append to typescript. # -p Use Python as shell. # Author: Steen Lumholt. import os, time, sys, getopt import pty def read(fd): data = os.read(fd, 1024) script.write(data) return data shell = 'sh' filename = 'typescript' mode = 'w' if os.environ.has_key('SHELL'): shell = os.environ['SHELL'] try: opts, args = getopt.getopt(sys.argv[1:], 'ap') except getopt.error, msg: print '%s: %s' % (sys.argv[0], msg) sys.exit(2) for o, a in opts: if o == '-a': mode = 'a' elif o == '-p': shell = 'python' script = open(filename, mode) sys.stdout.write('Script started, file is %s\n' % filename) script.write('Script started on %s\n' % time.ctime(time.time())) pty.spawn(shell, read) script.write('Script done on %s\n' % time.ctime(time.time())) sys.stdout.write('Script done, file is %s\n' % filename) PK%L]R~scripts/pi.pycnu[ Afc@s8ddlZdZdZedkr4endS(iNc Csd\}}}}}xtr||d|d|d}}}||||||||||f\}}}}||||}}xL||krt|d||d||}}||||}}qWqWdS(Niiii i (iiii i(tTruetoutput( tktatbta1tb1tptqtdtd1((s'/usr/lib64/python2.7/Demo/scripts/pi.pytmain s $6 cCs'tjjt|tjjdS(N(tsyststdouttwritetstrtflush(R ((s'/usr/lib64/python2.7/Demo/scripts/pi.pyRst__main__(R R Rt__name__(((s'/usr/lib64/python2.7/Demo/scripts/pi.pyt s   PK%L]*R  scripts/pp.pyonu[ Afc@s_ddlZddlZdZgZdZdZdZdZdZy#ejej dd\Z Z WnDej k rZ ejjdej de fejdnXxe D]\ZZedkrdZqed krdZqed krdZqed kr4x{ejd D]ZejeqWqed krIeZqedkrddZdZqedkrdZdZqeGdGHqWe se jdnes(e ddkrejZnee ddZx+ejZesPnejed qW[e d=e s(e jdq(ner@dgZgZnferddddddddddddd d!d"d#d$gZd%d"d&d'd(gZnd)gZgZd jed Zx eD]Zed*ed 7ZqWed jed 7ZddlZejZejeej erNddl!Z!e!j"d+ej#fn e$ej#dS(,iNtiis acde:F:nps%s: %s is-as-cs-ds-es s-Fs-ns-psnot recognized???t-trsif 0:s LINECOUNT = 0sfor FILE in ARGS:s if FILE == '-':s FP = sys.stdins else:s FP = open(FILE, 'r')s LINENO = 0s while 1:s LINE = FP.readline()s if not LINE: breaks LINENO = LINENO + 1s! LINECOUNT = LINECOUNT + 1s L = LINE[:-1]s aflag = AFLAGs if aflag:s" if FS: F = L.split(FS)s else: F = L.split()s if not PFLAG: continues# if FS: print FS.join(F)s# else: print ' '.join(F)s else: print Lsif 1:s s execfile(%r)(%tsystgetopttFStSCRIPTtAFLAGtCFLAGtDFLAGtNFLAGtPFLAGtargvtoptlisttARGSterrortmsgtstderrtwritetexittoptiontoptargtsplittlinetappendtstdintfptopentreadlinetprologuetepiloguetjointprogramttempfiletNamedTemporaryFiletflushtpdbtruntnametexecfile(((s'/usr/lib64/python2.7/Demo/scripts/pp.pyts  #!                           PK%L]cA-Dscripts/script.pycnu[ Afc@sddlZddlZddlZddlZddlZdZdZdZdZej j dryej dZny#ejej dd\Z Z Wn9ejk rZd ej d efGHejd nXx>e D]6\ZZed krd ZqedkrdZqqWeeeZejjdeejdejejejeeejdejejejjdedS(iNcCs#tj|d}tj||S(Ni(tostreadtscripttwrite(tfdtdata((s+/usr/lib64/python2.7/Demo/scripts/script.pyR s tsht typescripttwtSHELLitaps%s: %siis-atas-ptpythonsScript started, file is %s sScript started on %s sScript done on %s sScript done, file is %s (RttimetsystgetopttptyRtshelltfilenametmodetenvironthas_keytargvtoptstargsterrortmsgtexittoR topenRtstdoutRtctimetspawn(((s+/usr/lib64/python2.7/Demo/scripts/script.pyt s.0  #      PK%L]C-scripts/beer.pynuȯ#! /usr/bin/python2.7 # By GvR, demystified after a version by Fredrik Lundh. import sys n = 100 if sys.argv[1:]: n = int(sys.argv[1]) def bottle(n): if n == 0: return "no more bottles of beer" if n == 1: return "one bottle of beer" return str(n) + " bottles of beer" for i in range(n, 0, -1): print bottle(i), "on the wall," print bottle(i) + "." print "Take one down, pass it around," print bottle(i-1), "on the wall." PK%L]VB scripts/queens.pycnu[ Afc@sBdZdZdddYZdZedkr>endS(sN queens problem. The (well-known) problem is due to Niklaus Wirth. This solution is inspired by Dijkstra (Structured Programming). It is a classic recursive backtracking approach. itQueenscBsSeZedZdZddZdZdZdZdZ dZ RS(cCs||_|jdS(N(tntreset(tselfR((s+/usr/lib64/python2.7/Demo/scripts/queens.pyt__init__s cCsf|j}dg||_dg||_dgd|d|_dgd|d|_d|_dS(Niii(RtNonetytrowtuptdowntnfound(RR((s+/usr/lib64/python2.7/Demo/scripts/queens.pyRs  icCsx}t|jD]l}|j||r|j|||d|jkrX|jn|j|d|j||qqWdS(Ni(trangeRtsafetplacetdisplaytsolvetremove(RtxR((s+/usr/lib64/python2.7/Demo/scripts/queens.pyRs cCs0|j| o/|j|| o/|j|| S(N(RRR (RRR((s+/usr/lib64/python2.7/Demo/scripts/queens.pyR &scCs@||j| s 8  PK%L]G scripts/mboxconvert.pycnu[ Afc@sddlZddlZddlZddlZddlZddlZddlZdZejdZ dZ dZ da ddZ ed krendS( iNc Cst}y#tjtjdd\}}Wn7tjk rb}tjjd|tjdnXx)|D]!\}}|dkrjt}qjqjW|sdg}nd}x|D]}|dks|dkr|tj p|}qt j j |r t |p|}qt j j|ryt|}Wn6tk re}tjjd ||fd}qnX||pu|}|jqtjjd |d}qW|rtj|ndS( Nitfs%s is-ft-its%s: %s s%s: not found (tmmdftgetopttsystargvterrortstderrtwritetexittmessagetstdintostpathtisdirtmhtisfiletopentIOErrortclose( tdofiletoptstargstmsgtotatststargR((s0/usr/lib64/python2.7/Demo/scripts/mboxconvert.pytmains<#      s [1-9][0-9]*cCsd}tj|}x|D]}tj|t|krCqntjj||}yt|}Wn6tk r}t j j d||fd}qnXt |p|}qW|S(Nis%s: %s i( R tlistdirtnumerictmatchtlenRtjoinRRRRR R (tdirRtmsgsRtfnR((s0/usr/lib64/python2.7/Demo/scripts/mboxconvert.pyR2s cCsbd}xU|j}|sPn|dkrCt||p=|}q tjjd|fq W|S(Nis sBad line in MMFD mailbox: %r (treadlineR RRR (RRtline((s0/usr/lib64/python2.7/Demo/scripts/mboxconvert.pyRBs   iRc Cszd}tj|}|jd\}}|jd}|rQtj|}n<tjjd|j dft j |j t j}dG|Gtj|GHx|jD] }|GqW|jdstdadt|tf} tjjd| |fd G| GHnHxa|j}||kr0Pn|sPtjjd d}Pn|d d krmd |}n|GqWH|S(NitFromtDatesUnparseable date: %r s message-idis<%s.%d>sAdding Message-ID %s (From %s) s Message-ID:sUnexpected EOF in message isFrom t>(trfc822tMessagetgetaddrtgetdatettimetmktimeRRR t getheaderR tfstattfilenotstattST_MTIMEtctimetheadersthas_keytcounterthexR&( Rt delimiterRtmtfullnametemailtttttR'tmsgid((s0/usr/lib64/python2.7/Demo/scripts/mboxconvert.pyR Qs@       t__main__(R+RR/R R4RtreRtcompileRRRR9R t__name__(((s0/usr/lib64/python2.7/Demo/scripts/mboxconvert.pyts        !   * PK%L]G scripts/mboxconvert.pyonu[ Afc@sddlZddlZddlZddlZddlZddlZddlZdZejdZ dZ dZ da ddZ ed krendS( iNc Cst}y#tjtjdd\}}Wn7tjk rb}tjjd|tjdnXx)|D]!\}}|dkrjt}qjqjW|sdg}nd}x|D]}|dks|dkr|tj p|}qt j j |r t |p|}qt j j|ryt|}Wn6tk re}tjjd ||fd}qnX||pu|}|jqtjjd |d}qW|rtj|ndS( Nitfs%s is-ft-its%s: %s s%s: not found (tmmdftgetopttsystargvterrortstderrtwritetexittmessagetstdintostpathtisdirtmhtisfiletopentIOErrortclose( tdofiletoptstargstmsgtotatststargR((s0/usr/lib64/python2.7/Demo/scripts/mboxconvert.pytmains<#      s [1-9][0-9]*cCsd}tj|}x|D]}tj|t|krCqntjj||}yt|}Wn6tk r}t j j d||fd}qnXt |p|}qW|S(Nis%s: %s i( R tlistdirtnumerictmatchtlenRtjoinRRRRR R (tdirRtmsgsRtfnR((s0/usr/lib64/python2.7/Demo/scripts/mboxconvert.pyR2s cCsbd}xU|j}|sPn|dkrCt||p=|}q tjjd|fq W|S(Nis sBad line in MMFD mailbox: %r (treadlineR RRR (RRtline((s0/usr/lib64/python2.7/Demo/scripts/mboxconvert.pyRBs   iRc Cszd}tj|}|jd\}}|jd}|rQtj|}n<tjjd|j dft j |j t j}dG|Gtj|GHx|jD] }|GqW|jdstdadt|tf} tjjd| |fd G| GHnHxa|j}||kr0Pn|sPtjjd d}Pn|d d krmd |}n|GqWH|S(NitFromtDatesUnparseable date: %r s message-idis<%s.%d>sAdding Message-ID %s (From %s) s Message-ID:sUnexpected EOF in message isFrom t>(trfc822tMessagetgetaddrtgetdatettimetmktimeRRR t getheaderR tfstattfilenotstattST_MTIMEtctimetheadersthas_keytcounterthexR&( Rt delimiterRtmtfullnametemailtttttR'tmsgid((s0/usr/lib64/python2.7/Demo/scripts/mboxconvert.pyR Qs@       t__main__(R+RR/R R4RtreRtcompileRRRR9R t__name__(((s0/usr/lib64/python2.7/Demo/scripts/mboxconvert.pyts        !   * PK%L]cA-Dscripts/script.pyonu[ Afc@sddlZddlZddlZddlZddlZdZdZdZdZej j dryej dZny#ejej dd\Z Z Wn9ejk rZd ej d efGHejd nXx>e D]6\ZZed krd ZqedkrdZqqWeeeZejjdeejdejejejeeejdejejejjdedS(iNcCs#tj|d}tj||S(Ni(tostreadtscripttwrite(tfdtdata((s+/usr/lib64/python2.7/Demo/scripts/script.pyR s tsht typescripttwtSHELLitaps%s: %siis-atas-ptpythonsScript started, file is %s sScript started on %s sScript done on %s sScript done, file is %s (RttimetsystgetopttptyRtshelltfilenametmodetenvironthas_keytargvtoptstargsterrortmsgtexittoR topenRtstdoutRtctimetspawn(((s+/usr/lib64/python2.7/Demo/scripts/script.pyt s.0  #      PK%L]-; cgi/wiki.pyonu[ ^c@skdZddlZddlZddlZddlZddlZejZdZdddYZdS(s0Wiki main program. Imported and run by cgi3.py.iNcCsotj}dGHH|jdd}|jdd}t|}t|d|dp^|j}||dS(NsContent-type: text/htmltcmdtviewtpaget FrontPagetcmd_(tcgit FieldStoragetgetvaluetWikiPagetgetattrtNonetcmd_view(tformRRtwikitmethod((s%/usr/lib64/python2.7/Demo/cgi/wiki.pytmains  RcBseZejZejjej dZ dZ dZ dZ ddZdZdZdZd Zdd Zd Zd Zd ZRS(icCs2|j|stdn||_|jdS(Nspage name is not a wiki word(t iswikiwordt ValueErrortnametload(tselfR((s%/usr/lib64/python2.7/Demo/cgi/wiki.pyt__init__s  cCsdGt|j|jGdGHdGHx?|jjD].}|j}|sTdGHq4|j|GHq4WdGHdG|jd|jddGH|jdd d d GHdS( Ns

s

s

s


teditsEdit this paget;RRsgo to front paget.(tescapet splitwikiwordRtdatat splitlinestrstript formatlinetmklink(RR tline((s%/usr/lib64/python2.7/Demo/cgi/wiki.pyR s cCsg}xtjd|D]}}|j|r}tjj|j|ra|jd||}q|jd||d}n t|}|j |qWdj |S(Ns(\W+)Rtnewt*t( tretsplitRtostpathtisfiletmkfileRRtappendtjoin(RR twordstword((s%/usr/lib64/python2.7/Demo/cgi/wiki.pyR(s tChangecCsZdG|G|jGdGHd|jGHd}||jGHdGHd|jGHdGHd|GHd GHdS( Ns

s

s
s7s/s,s
s%s
(Rt scripturlR(RR tlabelts((s%/usr/lib64/python2.7/Demo/cgi/wiki.pytcmd_edit5s    cCs|jddj|_|j}|rIdGHdGHdGt|GHnJdGHd}||jd|jGHdGHd GHd G|jd |j|jGHdS( NttextR#s%

I'm sorry. That didn't work

s8

An error occurred while attempting to write the file:s

ss/s?cmd=view&page=s

OK

s)

If nothing happens, please click here:R(RtstripRtstoreRR/RR(RR terrorR1((s%/usr/lib64/python2.7/Demo/cgi/wiki.pyt cmd_create@s cCs|j|dddS(NR0tCreate(R2(RR ((s%/usr/lib64/python2.7/Demo/cgi/wiki.pytcmd_newQscCstjd|S(Ns[A-Z][a-z]+([A-Z][a-z]*)+(R$tmatch(RR-((s%/usr/lib64/python2.7/Demo/cgi/wiki.pyRTscCsSg}x=|D]5}|r5|jr5|jdn|j|q Wdj|S(Nt R#(tisupperR*R+(RR-tcharstc((s%/usr/lib64/python2.7/Demo/cgi/wiki.pyRWs  cCs2|dkr|j}ntjj|j|dS(Ns.txt(R RR&R'R+thomedir(RR((s%/usr/lib64/python2.7/Demo/cgi/wiki.pyR)_s  cCs'|jd|d|}d||fS(Ns?cmd=s&page=s%s(R/(RRRR3tlink((s%/usr/lib64/python2.7/Demo/cgi/wiki.pyRdscCsYy2t|j}|jj}|jWntk rKd}nX||_dS(NR#(topenR)treadR4tclosetIOErrorR(RtfR((s%/usr/lib64/python2.7/Demo/cgi/wiki.pyRhs  cCs|j}yZt|jd}|j||rT|jd rT|jdn|jdSWntk r}dt|SXdS(Ntws R#s IOError: %s(RRAR)twritetendswithRCRDtstr(RRREterr((s%/usr/lib64/python2.7/Demo/cgi/wiki.pyR5qs   N(t__name__t __module__ttempfilet gettempdirR?R&R'tbasenametsystargvR/RR RR2R7R9RRR R)RRR5(((s%/usr/lib64/python2.7/Demo/cgi/wiki.pyRs         (( t__doc__R&R$RRPRMRRR(((s%/usr/lib64/python2.7/Demo/cgi/wiki.pyts<  PK%L]. cgi/cgi2.pyonu[ Afc@sKdZddlZejddlZdZedkrGendS(s%CGI test 2 - basic use of cgi module.iNcCsptj}dGHH|s dGHnLdGHxD|jD]6}||j}dGtj|GdGtj|GHq2WdS(NsContent-type: text/htmls

No Form Keys

s

Form Keys

s

t:(tcgit FieldStoragetkeystvaluetescape(tformtkeyR((s%/usr/lib64/python2.7/Demo/cgi/cgi2.pytmain s  t__main__(t__doc__tcgitbtenableRRt__name__(((s%/usr/lib64/python2.7/Demo/cgi/cgi2.pyts    PK%L]6f cgi/cgi3.pynuȯ#! /usr/bin/python2.7 """CGI test 3 (persistent data).""" import cgitb; cgitb.enable() from wiki import main if __name__ == "__main__": main() PK%L]``M cgi/cgi0.shnuȯ#! /bin/sh # If you can't get this to work, your web server isn't set up right echo Content-type: text/plain echo echo Hello world echo This is cgi0.sh PK%L]Rq cgi/READMEnu[CGI Examples ------------ Here are some example CGI programs. For a larger example, see ../../Tools/faqwiz/. cgi0.sh -- A shell script to test your server is configured for CGI cgi1.py -- A Python script to test your server is configured for CGI cgi2.py -- A Python script showing how to parse a form cgi3.py -- A Python script for driving an arbitrary CGI application wiki.py -- Sample CGI application: a minimal Wiki implementation PK%L]4 cgi/cgi2.pynuȯ#! /usr/bin/python2.7 """CGI test 2 - basic use of cgi module.""" import cgitb; cgitb.enable() import cgi def main(): form = cgi.FieldStorage() print "Content-type: text/html" print if not form: print "

No Form Keys

" else: print "

Form Keys

" for key in form.keys(): value = form[key].value print "

", cgi.escape(key), ":", cgi.escape(value) if __name__ == "__main__": main() PK%L]_ cgi/cgi1.pynuȯ#! /usr/bin/python2.7 """CGI test 1 - check server setup.""" # Until you get this to work, your web server isn't set up right or # your Python isn't set up right. # If cgi0.sh works but cgi1.py doesn't, check the #! line and the file # permissions. The docs for the cgi.py module have debugging tips. print "Content-type: text/html" print print "

Hello world

" print "

This is cgi1.py" PK%L]-hFF cgi/cgi3.pyonu[ Afc@sFdZddlZejddlmZedkrBendS(sCGI test 3 (persistent data).iN(tmaint__main__(t__doc__tcgitbtenabletwikiRt__name__(((s%/usr/lib64/python2.7/Demo/cgi/cgi3.pyts   PK%L] cgi/cgi1.pyonu[ Afc@sdZdGHHdGHdGHdS(s CGI test 1 - check server setup.sContent-type: text/htmls

Hello world

s

This is cgi1.pyN(t__doc__(((s%/usr/lib64/python2.7/Demo/cgi/cgi1.pytsPK%L]. cgi/cgi2.pycnu[ Afc@sKdZddlZejddlZdZedkrGendS(s%CGI test 2 - basic use of cgi module.iNcCsptj}dGHH|s dGHnLdGHxD|jD]6}||j}dGtj|GdGtj|GHq2WdS(NsContent-type: text/htmls

No Form Keys

s

Form Keys

s

t:(tcgit FieldStoragetkeystvaluetescape(tformtkeyR((s%/usr/lib64/python2.7/Demo/cgi/cgi2.pytmain s  t__main__(t__doc__tcgitbtenableRRt__name__(((s%/usr/lib64/python2.7/Demo/cgi/cgi2.pyts    PK%L]-; cgi/wiki.pycnu[ ^c@skdZddlZddlZddlZddlZddlZejZdZdddYZdS(s0Wiki main program. Imported and run by cgi3.py.iNcCsotj}dGHH|jdd}|jdd}t|}t|d|dp^|j}||dS(NsContent-type: text/htmltcmdtviewtpaget FrontPagetcmd_(tcgit FieldStoragetgetvaluetWikiPagetgetattrtNonetcmd_view(tformRRtwikitmethod((s%/usr/lib64/python2.7/Demo/cgi/wiki.pytmains  RcBseZejZejjej dZ dZ dZ dZ ddZdZdZdZd Zdd Zd Zd Zd ZRS(icCs2|j|stdn||_|jdS(Nspage name is not a wiki word(t iswikiwordt ValueErrortnametload(tselfR((s%/usr/lib64/python2.7/Demo/cgi/wiki.pyt__init__s  cCsdGt|j|jGdGHdGHx?|jjD].}|j}|sTdGHq4|j|GHq4WdGHdG|jd|jddGH|jdd d d GHdS( Ns

s

s

s


teditsEdit this paget;RRsgo to front paget.(tescapet splitwikiwordRtdatat splitlinestrstript formatlinetmklink(RR tline((s%/usr/lib64/python2.7/Demo/cgi/wiki.pyR s cCsg}xtjd|D]}}|j|r}tjj|j|ra|jd||}q|jd||d}n t|}|j |qWdj |S(Ns(\W+)Rtnewt*t( tretsplitRtostpathtisfiletmkfileRRtappendtjoin(RR twordstword((s%/usr/lib64/python2.7/Demo/cgi/wiki.pyR(s tChangecCsZdG|G|jGdGHd|jGHd}||jGHdGHd|jGHdGHd|GHd GHdS( Ns

s

s
s7s/s,s
s%s
(Rt scripturlR(RR tlabelts((s%/usr/lib64/python2.7/Demo/cgi/wiki.pytcmd_edit5s    cCs|jddj|_|j}|rIdGHdGHdGt|GHnJdGHd}||jd|jGHdGHd GHd G|jd |j|jGHdS( NttextR#s%

I'm sorry. That didn't work

s8

An error occurred while attempting to write the file:s

ss/s?cmd=view&page=s

OK

s)

If nothing happens, please click here:R(RtstripRtstoreRR/RR(RR terrorR1((s%/usr/lib64/python2.7/Demo/cgi/wiki.pyt cmd_create@s cCs|j|dddS(NR0tCreate(R2(RR ((s%/usr/lib64/python2.7/Demo/cgi/wiki.pytcmd_newQscCstjd|S(Ns[A-Z][a-z]+([A-Z][a-z]*)+(R$tmatch(RR-((s%/usr/lib64/python2.7/Demo/cgi/wiki.pyRTscCsSg}x=|D]5}|r5|jr5|jdn|j|q Wdj|S(Nt R#(tisupperR*R+(RR-tcharstc((s%/usr/lib64/python2.7/Demo/cgi/wiki.pyRWs  cCs2|dkr|j}ntjj|j|dS(Ns.txt(R RR&R'R+thomedir(RR((s%/usr/lib64/python2.7/Demo/cgi/wiki.pyR)_s  cCs'|jd|d|}d||fS(Ns?cmd=s&page=s%s(R/(RRRR3tlink((s%/usr/lib64/python2.7/Demo/cgi/wiki.pyRdscCsYy2t|j}|jj}|jWntk rKd}nX||_dS(NR#(topenR)treadR4tclosetIOErrorR(RtfR((s%/usr/lib64/python2.7/Demo/cgi/wiki.pyRhs  cCs|j}yZt|jd}|j||rT|jd rT|jdn|jdSWntk r}dt|SXdS(Ntws R#s IOError: %s(RRAR)twritetendswithRCRDtstr(RRREterr((s%/usr/lib64/python2.7/Demo/cgi/wiki.pyR5qs   N(t__name__t __module__ttempfilet gettempdirR?R&R'tbasenametsystargvR/RR RR2R7R9RRR R)RRR5(((s%/usr/lib64/python2.7/Demo/cgi/wiki.pyRs         (( t__doc__R&R$RRPRMRRR(((s%/usr/lib64/python2.7/Demo/cgi/wiki.pyts<  PK%L]-hFF cgi/cgi3.pycnu[ Afc@sFdZddlZejddlmZedkrBendS(sCGI test 3 (persistent data).iN(tmaint__main__(t__doc__tcgitbtenabletwikiRt__name__(((s%/usr/lib64/python2.7/Demo/cgi/cgi3.pyts   PK%L] cgi/cgi1.pycnu[ Afc@sdZdGHHdGHdGHdS(s CGI test 1 - check server setup.sContent-type: text/htmls

Hello world

s

This is cgi1.pyN(t__doc__(((s%/usr/lib64/python2.7/Demo/cgi/cgi1.pytsPK%L]7 cgi/wiki.pynu["""Wiki main program. Imported and run by cgi3.py.""" import os, re, cgi, sys, tempfile escape = cgi.escape def main(): form = cgi.FieldStorage() print "Content-type: text/html" print cmd = form.getvalue("cmd", "view") page = form.getvalue("page", "FrontPage") wiki = WikiPage(page) method = getattr(wiki, 'cmd_' + cmd, None) or wiki.cmd_view method(form) class WikiPage: homedir = tempfile.gettempdir() scripturl = os.path.basename(sys.argv[0]) def __init__(self, name): if not self.iswikiword(name): raise ValueError, "page name is not a wiki word" self.name = name self.load() def cmd_view(self, form): print "

", escape(self.splitwikiword(self.name)), "

" print "

" for line in self.data.splitlines(): line = line.rstrip() if not line: print "

" else: print self.formatline(line) print "


" print "

", self.mklink("edit", self.name, "Edit this page") + ";" print self.mklink("view", "FrontPage", "go to front page") + "." def formatline(self, line): words = [] for word in re.split('(\W+)', line): if self.iswikiword(word): if os.path.isfile(self.mkfile(word)): word = self.mklink("view", word, word) else: word = self.mklink("new", word, word + "*") else: word = escape(word) words.append(word) return "".join(words) def cmd_edit(self, form, label="Change"): print "

", label, self.name, "

" print '
' % self.scripturl s = '' print s % self.data print '' print '' % self.name print '
' print '' % label print "
" def cmd_create(self, form): self.data = form.getvalue("text", "").strip() error = self.store() if error: print "

I'm sorry. That didn't work

" print "

An error occurred while attempting to write the file:" print "

", escape(error) else: # Use a redirect directive, to avoid "reload page" problems print "" s = '' print s % (self.scripturl + "?cmd=view&page=" + self.name) print "" print "

OK

" print "

If nothing happens, please click here:", print self.mklink("view", self.name, self.name) def cmd_new(self, form): self.cmd_edit(form, label="Create") def iswikiword(self, word): return re.match("[A-Z][a-z]+([A-Z][a-z]*)+", word) def splitwikiword(self, word): chars = [] for c in word: if chars and c.isupper(): chars.append(' ') chars.append(c) return "".join(chars) def mkfile(self, name=None): if name is None: name = self.name return os.path.join(self.homedir, name + ".txt") def mklink(self, cmd, page, text): link = self.scripturl + "?cmd=" + cmd + "&page=" + page return '%s' % (link, text) def load(self): try: f = open(self.mkfile()) data = f.read().strip() f.close() except IOError: data = "" self.data = data def store(self): data = self.data try: f = open(self.mkfile(), "w") f.write(data) if data and not data.endswith('\n'): f.write('\n') f.close() return "" except IOError, err: return "IOError: %s" % str(err) PK%L]}*EE pysvr/READMEnu[This is an example of a multi-threaded C application embedding a Python interpreter. The particular application is a multi-threaded telnet-like server that provides you with a Python prompt (instead of a shell prompt). The file pysvr.py is a prototype in Python. THIS APPLICATION IS NOT SECURE -- ONLY USE IT FOR TESTING! PK%L]J~^5e e pysvr/pysvr.pynuȯ#! /usr/bin/python2.7 """A multi-threaded telnet-like server that gives a Python prompt. This is really a prototype for the same thing in C. Usage: pysvr.py [port] For security reasons, it only accepts requests from the current host. This can still be insecure, but restricts violations from people who can log in on your machine. Use with caution! """ import sys, os, string, getopt, thread, socket, traceback PORT = 4000 # Default port def main(): try: opts, args = getopt.getopt(sys.argv[1:], "") if len(args) > 1: raise getopt.error, "Too many arguments." except getopt.error, msg: usage(msg) for o, a in opts: pass if args: try: port = string.atoi(args[0]) except ValueError, msg: usage(msg) else: port = PORT main_thread(port) def usage(msg=None): sys.stdout = sys.stderr if msg: print msg print "\n", __doc__, sys.exit(2) def main_thread(port): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(("", port)) sock.listen(5) print "Listening on port", port, "..." while 1: (conn, addr) = sock.accept() if addr[0] != conn.getsockname()[0]: conn.close() print "Refusing connection from non-local host", addr[0], "." continue thread.start_new_thread(service_thread, (conn, addr)) del conn, addr def service_thread(conn, addr): (caddr, cport) = addr print "Thread %s has connection from %s.\n" % (str(thread.get_ident()), caddr), stdin = conn.makefile("r") stdout = conn.makefile("w", 0) run_interpreter(stdin, stdout) print "Thread %s is done.\n" % str(thread.get_ident()), def run_interpreter(stdin, stdout): globals = {} try: str(sys.ps1) except: sys.ps1 = ">>> " source = "" while 1: stdout.write(sys.ps1) line = stdin.readline() if line[:2] == '\377\354': line = "" if not line and not source: break if line[-2:] == '\r\n': line = line[:-2] + '\n' source = source + line try: code = compile_command(source) except SyntaxError, err: source = "" traceback.print_exception(SyntaxError, err, None, file=stdout) continue if not code: continue source = "" try: run_command(code, stdin, stdout, globals) except SystemExit, how: if how: try: how = str(how) except: how = "" stdout.write("Exit %s\n" % how) break stdout.write("\nGoodbye.\n") def run_command(code, stdin, stdout, globals): save = sys.stdin, sys.stdout, sys.stderr try: sys.stdout = sys.stderr = stdout sys.stdin = stdin try: exec code in globals except SystemExit, how: raise SystemExit, how, sys.exc_info()[2] except: type, value, tb = sys.exc_info() if tb: tb = tb.tb_next traceback.print_exception(type, value, tb) del tb finally: sys.stdin, sys.stdout, sys.stderr = save from code import compile_command main() PK%L]ryk pysvr/pysvr.cnu[/* A multi-threaded telnet-like server that gives a Python prompt. Usage: pysvr [port] For security reasons, it only accepts requests from the current host. This can still be insecure, but restricts violations from people who can log in on your machine. Use with caution! */ #include #include #include #include #include #include #include #include #include #include /* XXX Umpfh. Python.h defines a typedef destructor, which conflicts with pthread.h. So Python.h must be included after pthread.h. */ #include "Python.h" extern int Py_VerboseFlag; #ifndef PORT #define PORT 4000 #endif struct workorder { int conn; struct sockaddr_in addr; }; /* Forward */ static void init_python(void); static void usage(void); static void oprogname(void); static void main_thread(int); static void create_thread(int, struct sockaddr_in *); static void *service_thread(struct workorder *); static void run_interpreter(FILE *, FILE *); static int run_command(char *, PyObject *); static void ps(void); static char *progname = "pysvr"; static PyThreadState *gtstate; main(int argc, char **argv) { int port = PORT; int c; if (argc > 0 && argv[0] != NULL && argv[0][0] != '\0') progname = argv[0]; while ((c = getopt(argc, argv, "v")) != EOF) { switch (c) { case 'v': Py_VerboseFlag++; break; default: usage(); } } if (optind < argc) { if (optind+1 < argc) { oprogname(); fprintf(stderr, "too many arguments\n"); usage(); } port = atoi(argv[optind]); if (port <= 0) { fprintf(stderr, "bad port (%s)\n", argv[optind]); usage(); } } main_thread(port); fprintf(stderr, "Bye.\n"); exit(0); } static char usage_line[] = "usage: %s [port]\n"; static void usage(void) { fprintf(stderr, usage_line, progname); exit(2); } static void main_thread(int port) { int sock, conn, size, i; struct sockaddr_in addr, clientaddr; sock = socket(PF_INET, SOCK_STREAM, 0); if (sock < 0) { oprogname(); perror("can't create socket"); exit(1); } #ifdef SO_REUSEADDR i = 1; setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &i, sizeof i); #endif memset((char *)&addr, '\0', sizeof addr); addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr.s_addr = 0L; if (bind(sock, (struct sockaddr *)&addr, sizeof addr) < 0) { oprogname(); perror("can't bind socket to address"); exit(1); } if (listen(sock, 5) < 0) { oprogname(); perror("can't listen on socket"); exit(1); } fprintf(stderr, "Listening on port %d...\n", port); for (i = 0; ; i++) { size = sizeof clientaddr; memset((char *) &clientaddr, '\0', size); conn = accept(sock, (struct sockaddr *) &clientaddr, &size); if (conn < 0) { oprogname(); perror("can't accept connection from socket"); exit(1); } size = sizeof addr; memset((char *) &addr, '\0', size); if (getsockname(conn, (struct sockaddr *)&addr, &size) < 0) { oprogname(); perror("can't get socket name of connection"); exit(1); } if (clientaddr.sin_addr.s_addr != addr.sin_addr.s_addr) { oprogname(); perror("connection from non-local host refused"); fprintf(stderr, "(addr=%lx, clientaddr=%lx)\n", ntohl(addr.sin_addr.s_addr), ntohl(clientaddr.sin_addr.s_addr)); close(conn); continue; } if (i == 4) { close(conn); break; } create_thread(conn, &clientaddr); } close(sock); if (gtstate) { PyEval_AcquireThread(gtstate); gtstate = NULL; Py_Finalize(); /* And a second time, just because we can. */ Py_Finalize(); /* This should be harmless. */ } exit(0); } static void create_thread(int conn, struct sockaddr_in *addr) { struct workorder *work; pthread_t tdata; work = malloc(sizeof(struct workorder)); if (work == NULL) { oprogname(); fprintf(stderr, "out of memory for thread.\n"); close(conn); return; } work->conn = conn; work->addr = *addr; init_python(); if (pthread_create(&tdata, NULL, (void *)service_thread, work) < 0) { oprogname(); perror("can't create new thread"); close(conn); return; } if (pthread_detach(tdata) < 0) { oprogname(); perror("can't detach from thread"); } } static PyThreadState *the_tstate; static PyInterpreterState *the_interp; static PyObject *the_builtins; static void init_python(void) { if (gtstate) return; Py_Initialize(); /* Initialize the interpreter */ PyEval_InitThreads(); /* Create (and acquire) the interpreter lock */ gtstate = PyEval_SaveThread(); /* Release the thread state */ } static void * service_thread(struct workorder *work) { FILE *input, *output; fprintf(stderr, "Start thread for connection %d.\n", work->conn); ps(); input = fdopen(work->conn, "r"); if (input == NULL) { oprogname(); perror("can't create input stream"); goto done; } output = fdopen(work->conn, "w"); if (output == NULL) { oprogname(); perror("can't create output stream"); fclose(input); goto done; } setvbuf(input, NULL, _IONBF, 0); setvbuf(output, NULL, _IONBF, 0); run_interpreter(input, output); fclose(input); fclose(output); done: fprintf(stderr, "End thread for connection %d.\n", work->conn); close(work->conn); free(work); } static void oprogname(void) { int save = errno; fprintf(stderr, "%s: ", progname); errno = save; } static void run_interpreter(FILE *input, FILE *output) { PyThreadState *tstate; PyObject *new_stdin, *new_stdout; PyObject *mainmod, *globals; char buffer[1000]; char *p, *q; int n, end; PyEval_AcquireLock(); tstate = Py_NewInterpreter(); if (tstate == NULL) { fprintf(output, "Sorry -- can't create an interpreter\n"); return; } mainmod = PyImport_AddModule("__main__"); globals = PyModule_GetDict(mainmod); Py_INCREF(globals); new_stdin = PyFile_FromFile(input, "", "r", NULL); new_stdout = PyFile_FromFile(output, "", "w", NULL); PySys_SetObject("stdin", new_stdin); PySys_SetObject("stdout", new_stdout); PySys_SetObject("stderr", new_stdout); for (n = 1; !PyErr_Occurred(); n++) { Py_BEGIN_ALLOW_THREADS fprintf(output, "%d> ", n); p = fgets(buffer, sizeof buffer, input); Py_END_ALLOW_THREADS if (p == NULL) break; if (p[0] == '\377' && p[1] == '\354') break; q = strrchr(p, '\r'); if (q && q[1] == '\n' && q[2] == '\0') { *q++ = '\n'; *q++ = '\0'; } while (*p && isspace(*p)) p++; if (p[0] == '#' || p[0] == '\0') continue; end = run_command(buffer, globals); if (end < 0) PyErr_Print(); if (end) break; } Py_XDECREF(globals); Py_XDECREF(new_stdin); Py_XDECREF(new_stdout); Py_EndInterpreter(tstate); PyEval_ReleaseLock(); fprintf(output, "Goodbye!\n"); } static int run_command(char *buffer, PyObject *globals) { PyObject *m, *d, *v; fprintf(stderr, "run_command: %s", buffer); if (strchr(buffer, '\n') == NULL) fprintf(stderr, "\n"); v = PyRun_String(buffer, Py_single_input, globals, globals); if (v == NULL) { if (PyErr_Occurred() == PyExc_SystemExit) { PyErr_Clear(); return 1; } PyErr_Print(); return 0; } Py_DECREF(v); return 0; } static void ps(void) { char buffer[100]; PyOS_snprintf(buffer, sizeof(buffer), "ps -l -p %d >> Risis s tfilesExit %s s Goodbye. ( R(Rtps1twritetreadlinetcompile_commandt SyntaxErrort tracebacktprint_exceptiontNonet run_commandt SystemExit(R.Rtglobalstsourcetlinetcodeterrthow((s(/usr/lib64/python2.7/Demo/pysvr/pysvr.pyR+CsH      c Bsejejejf}z|e_e_|e_y ||UWnlek rk}e|ejdnDej\}}}|r|j}nej|||~nXWd|\e_e_e_XdS(Ni( RR.RRR9texc_infottb_nextR5R6( R=R.RR:tsaveR?ttypetvaluettb((s(/usr/lib64/python2.7/Demo/pysvr/pysvr.pyR8is    (R3(RRtosRRR RR5R RR7RR R"R+R8R=R3(((s(/usr/lib64/python2.7/Demo/pysvr/pysvr.pyt sT    & PK%L]W..pysvr/pysvr.pyonu[ Afc@sdZddlZddlZddlZddlZddlZddlZddlZdZdZ ddZ dZ dZ dZd Zdd lmZe dS( sIA multi-threaded telnet-like server that gives a Python prompt. This is really a prototype for the same thing in C. Usage: pysvr.py [port] For security reasons, it only accepts requests from the current host. This can still be insecure, but restricts violations from people who can log in on your machine. Use with caution! iNicCsyDtjtjdd\}}t|dkrCtjdnWn tjk rf}t|nXx|D] \}}qnW|rytj|d}Wqtk r}t|qXnt }t |dS(NitsToo many arguments.i( tgetopttsystargvtlenterrortusagetstringtatoit ValueErrortPORTt main_thread(toptstargstmsgtotatport((s(/usr/lib64/python2.7/Demo/pysvr/pysvr.pytmainscCs3tjt_|r|GHndGtGtjddS(Ns i(Rtstderrtstdoutt__doc__texit(R((s(/usr/lib64/python2.7/Demo/pysvr/pysvr.pyR%s  cCstjtjtj}|jd|f|jddG|GdGHxm|j\}}|d|jdkr|jdG|dGdGHqHntj t ||f~~qHWdS(NRisListening on ports...is'Refusing connection from non-local hostt.( tsockettAF_INETt SOCK_STREAMtbindtlistentacceptt getsocknametclosetthreadtstart_new_threadtservice_thread(Rtsocktconntaddr((s(/usr/lib64/python2.7/Demo/pysvr/pysvr.pyR ,s   cCsl|\}}dttj|fG|jd}|jdd}t||dttjGdS(Ns"Thread %s has connection from %s. trtwisThread %s is done. (tstrR t get_identtmakefiletrun_interpreter(R$R%tcaddrtcporttstdinR((s(/usr/lib64/python2.7/Demo/pysvr/pysvr.pyR":s  cCs|i}yttjWndt_nXd}x8|jtj|j}|d dkrhd}n| rz| rzPn|ddkr|d d}n||}yt|}Wn5tk r}d}tjt|dd|q3nX|sq3nd}yt ||||Wq3t k rf}|rbyt|}Wn d}nX|jd |nPq3Xq3W|jd dS( Ns>>> Risis s tfilesExit %s s Goodbye. ( R(Rtps1twritetreadlinetcompile_commandt SyntaxErrort tracebacktprint_exceptiontNonet run_commandt SystemExit(R.Rtglobalstsourcetlinetcodeterrthow((s(/usr/lib64/python2.7/Demo/pysvr/pysvr.pyR+CsH      c Bsejejejf}z|e_e_|e_y ||UWnlek rk}e|ejdnDej\}}}|r|j}nej|||~nXWd|\e_e_e_XdS(Ni( RR.RRR9texc_infottb_nextR5R6( R=R.RR:tsaveR?ttypetvaluettb((s(/usr/lib64/python2.7/Demo/pysvr/pysvr.pyR8is    (R3(RRtosRRR RR5R RR7RR R"R+R8R=R3(((s(/usr/lib64/python2.7/Demo/pysvr/pysvr.pyt sT    & PK%L]mznewmetaclasses/Enum.pynu["""Enumeration metaclass.""" class EnumMetaclass(type): """Metaclass for enumeration. To define your own enumeration, do something like class Color(Enum): red = 1 green = 2 blue = 3 Now, Color.red, Color.green and Color.blue behave totally different: they are enumerated values, not integers. Enumerations cannot be instantiated; however they can be subclassed. """ def __init__(cls, name, bases, dict): super(EnumMetaclass, cls).__init__(name, bases, dict) cls._members = [] for attr in dict.keys(): if not (attr.startswith('__') and attr.endswith('__')): enumval = EnumInstance(name, attr, dict[attr]) setattr(cls, attr, enumval) cls._members.append(attr) def __getattr__(cls, name): if name == "__members__": return cls._members raise AttributeError, name def __repr__(cls): s1 = s2 = "" enumbases = [base.__name__ for base in cls.__bases__ if isinstance(base, EnumMetaclass) and not base is Enum] if enumbases: s1 = "(%s)" % ", ".join(enumbases) enumvalues = ["%s: %d" % (val, getattr(cls, val)) for val in cls._members] if enumvalues: s2 = ": {%s}" % ", ".join(enumvalues) return "%s%s%s" % (cls.__name__, s1, s2) class FullEnumMetaclass(EnumMetaclass): """Metaclass for full enumerations. A full enumeration displays all the values defined in base classes. """ def __init__(cls, name, bases, dict): super(FullEnumMetaclass, cls).__init__(name, bases, dict) for obj in cls.__mro__: if isinstance(obj, EnumMetaclass): for attr in obj._members: # XXX inefficient if not attr in cls._members: cls._members.append(attr) class EnumInstance(int): """Class to represent an enumeration value. EnumInstance('Color', 'red', 12) prints as 'Color.red' and behaves like the integer 12 when compared, but doesn't support arithmetic. XXX Should it record the actual enumeration rather than just its name? """ def __new__(cls, classname, enumname, value): return int.__new__(cls, value) def __init__(self, classname, enumname, value): self.__classname = classname self.__enumname = enumname def __repr__(self): return "EnumInstance(%s, %s, %d)" % (self.__classname, self.__enumname, self) def __str__(self): return "%s.%s" % (self.__classname, self.__enumname) class Enum: __metaclass__ = EnumMetaclass class FullEnum: __metaclass__ = FullEnumMetaclass def _test(): class Color(Enum): red = 1 green = 2 blue = 3 print Color.red print repr(Color.red) print Color.red == Color.red print Color.red == Color.blue print Color.red == 1 print Color.red == 2 class ExtendedColor(Color): white = 0 orange = 4 yellow = 5 purple = 6 black = 7 print ExtendedColor.orange print ExtendedColor.red print Color.red == ExtendedColor.red class OtherColor(Enum): white = 4 blue = 5 class MergedColor(Color, OtherColor): pass print MergedColor.red print MergedColor.white print Color print ExtendedColor print OtherColor print MergedColor def _test2(): class Color(FullEnum): red = 1 green = 2 blue = 3 print Color.red print repr(Color.red) print Color.red == Color.red print Color.red == Color.blue print Color.red == 1 print Color.red == 2 class ExtendedColor(Color): white = 0 orange = 4 yellow = 5 purple = 6 black = 7 print ExtendedColor.orange print ExtendedColor.red print Color.red == ExtendedColor.red class OtherColor(FullEnum): white = 4 blue = 5 class MergedColor(Color, OtherColor): pass print MergedColor.red print MergedColor.white print Color print ExtendedColor print OtherColor print MergedColor if __name__ == '__main__': _test() _test2() PK%L]aQnewmetaclasses/Eiffel.pyonu[ ^c@sdZddlmZdefdYZdefdYZdddYZd efd YZ d efd YZ d Z e dkre ee e ndS(s6Support Eiffel-style preconditions and postconditions.i(t FunctionTypetEiffelBaseMetaClasscBs eZdZedZRS(cCs,|j|tt|j||||S(N(tconvert_methodstsuperRt__new__(tmetatnametbasestdict((s2/usr/lib64/python2.7/Demo/newmetaclasses/Eiffel.pyRs cCsg}xZ|jD]L\}}|jds_|jdr@qt|tr|j|qqWx`|D]X}|jd|}|jd|}|s|rj|j||||||s  4  PK%L]e@Pnewmetaclasses/Eiffel.pynu["""Support Eiffel-style preconditions and postconditions.""" from types import FunctionType as function class EiffelBaseMetaClass(type): def __new__(meta, name, bases, dict): meta.convert_methods(dict) return super(EiffelBaseMetaClass, meta).__new__(meta, name, bases, dict) @classmethod def convert_methods(cls, dict): """Replace functions in dict with EiffelMethod wrappers. The dict is modified in place. If a method ends in _pre or _post, it is removed from the dict regardless of whether there is a corresponding method. """ # find methods with pre or post conditions methods = [] for k, v in dict.iteritems(): if k.endswith('_pre') or k.endswith('_post'): assert isinstance(v, function) elif isinstance(v, function): methods.append(k) for m in methods: pre = dict.get("%s_pre" % m) post = dict.get("%s_post" % m) if pre or post: dict[m] = cls.make_eiffel_method(dict[m], pre, post) class EiffelMetaClass1(EiffelBaseMetaClass): # an implementation of the "eiffel" meta class that uses nested functions @staticmethod def make_eiffel_method(func, pre, post): def method(self, *args, **kwargs): if pre: pre(self, *args, **kwargs) x = func(self, *args, **kwargs) if post: post(self, x, *args, **kwargs) return x if func.__doc__: method.__doc__ = func.__doc__ return method class EiffelMethodWrapper: def __init__(self, inst, descr): self._inst = inst self._descr = descr def __call__(self, *args, **kwargs): return self._descr.callmethod(self._inst, args, kwargs) class EiffelDescriptor(object): def __init__(self, func, pre, post): self._func = func self._pre = pre self._post = post self.__name__ = func.__name__ self.__doc__ = func.__doc__ def __get__(self, obj, cls): return EiffelMethodWrapper(obj, self) def callmethod(self, inst, args, kwargs): if self._pre: self._pre(inst, *args, **kwargs) x = self._func(inst, *args, **kwargs) if self._post: self._post(inst, x, *args, **kwargs) return x class EiffelMetaClass2(EiffelBaseMetaClass): # an implementation of the "eiffel" meta class that uses descriptors make_eiffel_method = EiffelDescriptor def _test(metaclass): class Eiffel: __metaclass__ = metaclass class Test(Eiffel): def m(self, arg): """Make it a little larger""" return arg + 1 def m2(self, arg): """Make it a little larger""" return arg + 1 def m2_pre(self, arg): assert arg > 0 def m2_post(self, result, arg): assert result > arg class Sub(Test): def m2(self, arg): return arg**2 def m2_post(self, Result, arg): super(Sub, self).m2_post(Result, arg) assert Result < 100 t = Test() t.m(1) t.m2(1) try: t.m2(0) except AssertionError: pass else: assert False s = Sub() try: s.m2(1) except AssertionError: pass # result == arg else: assert False try: s.m2(10) except AssertionError: pass # result == 100 else: assert False s.m2(5) if __name__ == "__main__": _test(EiffelMetaClass1) _test(EiffelMetaClass2) PK%L];onewmetaclasses/Enum.pyonu[ ^c@sdZdefdYZdefdYZdefdYZdddYZd dd YZd Zd Z e d kree ndS(sEnumeration metaclass.t EnumMetaclasscBs)eZdZdZdZdZRS(sgMetaclass for enumeration. To define your own enumeration, do something like class Color(Enum): red = 1 green = 2 blue = 3 Now, Color.red, Color.green and Color.blue behave totally different: they are enumerated values, not integers. Enumerations cannot be instantiated; however they can be subclassed. cCstt|j|||g|_xk|jD]]}|jdoS|jds2t||||}t||||jj |q2q2WdS(Nt__( tsuperRt__init__t_memberstkeyst startswithtendswitht EnumInstancetsetattrtappend(tclstnametbasestdicttattrtenumval((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyRs cCs |dkr|jSt|dS(Nt __members__(RtAttributeError(R R ((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyt __getattr__s cCsd}}g|jD]*}t|tr|tk r|j^q}|r`ddj|}ng|jD]}d|t||f^qj}|rddj|}nd|j||fS(Nts(%s)s, s%s: %ds: {%s}s%s%s%s(t __bases__t isinstanceRtEnumt__name__tjoinRtgetattr(R ts1ts2tbaset enumbasestvalt enumvalues((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyt__repr__"s *,(Rt __module__t__doc__RRR!(((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyRs tFullEnumMetaclasscBseZdZdZRS(snMetaclass for full enumerations. A full enumeration displays all the values defined in base classes. cCs|tt|j|||xY|jD]N}t|tr&x6|jD](}||jkrE|jj|qEqEWq&q&WdS(N(RR$Rt__mro__RRRR (R R R RtobjR((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyR4s (RR"R#R(((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyR$.sRcBs2eZdZdZdZdZdZRS(s Class to represent an enumeration value. EnumInstance('Color', 'red', 12) prints as 'Color.red' and behaves like the integer 12 when compared, but doesn't support arithmetic. XXX Should it record the actual enumeration rather than just its name? cCstj||S(N(tintt__new__(R t classnametenumnametvalue((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyR(GscCs||_||_dS(N(t_EnumInstance__classnamet_EnumInstance__enumname(tselfR)R*R+((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyRJs cCsd|j|j|fS(NsEnumInstance(%s, %s, %d)(R,R-(R.((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyR!NscCsd|j|jfS(Ns%s.%s(R,R-(R.((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyt__str__Rs(RR"R#R(RR!R/(((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyR=s    RcBseZeZRS((RR"Rt __metaclass__(((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyRUstFullEnumcBseZeZRS((RR"R$R0(((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyR1XscCsdtfdY}|jGHt|jGH|j|jkGH|j|jkGH|jdkGH|jdkGHd|fdY}|jGH|jGH|j|jkGHdtfdY}d ||fd Y}|jGH|jGH|GH|GH|GH|GHdS( NtColorcBseZdZdZdZRS(iii(RR"tredtgreentblue(((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyR2]siit ExtendedColorcBs&eZdZdZdZdZdZRS(iiiii(RR"twhitetorangetyellowtpurpletblack(((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyR6js t OtherColorcBseZdZdZRS(ii(RR"R7R5(((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyR<vst MergedColorcBseZRS((RR"(((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyR=zs(RR3treprR5R8R7(R2R6R<R=((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyt_test[s&cCsdtfdY}|jGHt|jGH|j|jkGH|j|jkGH|jdkGH|jdkGHd|fdY}|jGH|jGH|j|jkGHdtfdY}d ||fd Y}|jGH|jGH|GH|GH|GH|GHdS( NR2cBseZdZdZdZRS(iii(RR"R3R4R5(((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyR2siiR6cBs&eZdZdZdZdZdZRS(iiiii(RR"R7R8R9R:R;(((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyR6s R<cBseZdZdZRS(ii(RR"R7R5(((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyR<sR=cBseZRS((RR"(((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyR=s(R1R3R>R5R8R7(R2R6R<R=((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyt_test2s&t__main__N((( R#ttypeRR$R'RRR1R?R@R(((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyts+ * * PK%L];onewmetaclasses/Enum.pycnu[ ^c@sdZdefdYZdefdYZdefdYZdddYZd dd YZd Zd Z e d kree ndS(sEnumeration metaclass.t EnumMetaclasscBs)eZdZdZdZdZRS(sgMetaclass for enumeration. To define your own enumeration, do something like class Color(Enum): red = 1 green = 2 blue = 3 Now, Color.red, Color.green and Color.blue behave totally different: they are enumerated values, not integers. Enumerations cannot be instantiated; however they can be subclassed. cCstt|j|||g|_xk|jD]]}|jdoS|jds2t||||}t||||jj |q2q2WdS(Nt__( tsuperRt__init__t_memberstkeyst startswithtendswitht EnumInstancetsetattrtappend(tclstnametbasestdicttattrtenumval((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyRs cCs |dkr|jSt|dS(Nt __members__(RtAttributeError(R R ((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyt __getattr__s cCsd}}g|jD]*}t|tr|tk r|j^q}|r`ddj|}ng|jD]}d|t||f^qj}|rddj|}nd|j||fS(Nts(%s)s, s%s: %ds: {%s}s%s%s%s(t __bases__t isinstanceRtEnumt__name__tjoinRtgetattr(R ts1ts2tbaset enumbasestvalt enumvalues((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyt__repr__"s *,(Rt __module__t__doc__RRR!(((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyRs tFullEnumMetaclasscBseZdZdZRS(snMetaclass for full enumerations. A full enumeration displays all the values defined in base classes. cCs|tt|j|||xY|jD]N}t|tr&x6|jD](}||jkrE|jj|qEqEWq&q&WdS(N(RR$Rt__mro__RRRR (R R R RtobjR((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyR4s (RR"R#R(((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyR$.sRcBs2eZdZdZdZdZdZRS(s Class to represent an enumeration value. EnumInstance('Color', 'red', 12) prints as 'Color.red' and behaves like the integer 12 when compared, but doesn't support arithmetic. XXX Should it record the actual enumeration rather than just its name? cCstj||S(N(tintt__new__(R t classnametenumnametvalue((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyR(GscCs||_||_dS(N(t_EnumInstance__classnamet_EnumInstance__enumname(tselfR)R*R+((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyRJs cCsd|j|j|fS(NsEnumInstance(%s, %s, %d)(R,R-(R.((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyR!NscCsd|j|jfS(Ns%s.%s(R,R-(R.((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyt__str__Rs(RR"R#R(RR!R/(((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyR=s    RcBseZeZRS((RR"Rt __metaclass__(((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyRUstFullEnumcBseZeZRS((RR"R$R0(((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyR1XscCsdtfdY}|jGHt|jGH|j|jkGH|j|jkGH|jdkGH|jdkGHd|fdY}|jGH|jGH|j|jkGHdtfdY}d ||fd Y}|jGH|jGH|GH|GH|GH|GHdS( NtColorcBseZdZdZdZRS(iii(RR"tredtgreentblue(((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyR2]siit ExtendedColorcBs&eZdZdZdZdZdZRS(iiiii(RR"twhitetorangetyellowtpurpletblack(((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyR6js t OtherColorcBseZdZdZRS(ii(RR"R7R5(((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyR<vst MergedColorcBseZRS((RR"(((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyR=zs(RR3treprR5R8R7(R2R6R<R=((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyt_test[s&cCsdtfdY}|jGHt|jGH|j|jkGH|j|jkGH|jdkGH|jdkGHd|fdY}|jGH|jGH|j|jkGHdtfdY}d ||fd Y}|jGH|jGH|GH|GH|GH|GHdS( NR2cBseZdZdZdZRS(iii(RR"R3R4R5(((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyR2siiR6cBs&eZdZdZdZdZdZRS(iiiii(RR"R7R8R9R:R;(((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyR6s R<cBseZdZdZRS(ii(RR"R7R5(((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyR<sR=cBseZRS((RR"(((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyR=s(R1R3R>R5R8R7(R2R6R<R=((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyt_test2s&t__main__N((( R#ttypeRR$R'RRR1R?R@R(((s0/usr/lib64/python2.7/Demo/newmetaclasses/Enum.pyts+ * * PK%L]|rrnewmetaclasses/Eiffel.pycnu[ ^c@sdZddlmZdefdYZdefdYZdddYZd efd YZ d efd YZ d Z e dkre ee e ndS(s6Support Eiffel-style preconditions and postconditions.i(t FunctionTypetEiffelBaseMetaClasscBs eZdZedZRS(cCs,|j|tt|j||||S(N(tconvert_methodstsuperRt__new__(tmetatnametbasestdict((s2/usr/lib64/python2.7/Demo/newmetaclasses/Eiffel.pyRs cCsg}xo|jD]a\}}|jds=|jdrUt|tsttqt|tr|j|qqWx`|D]X}|jd|}|jd|}|s|r|j||||||s  4  PK%L]I8 xml/rss2html.pycnu[ ^c@sdZddlZddlZddlmZmZdZdZdejfdYZ e dkreZ e j e e j ejd ndS( sx A demo that reads in an RSS XML document and emits an HTML file containing a list of the individual items in the feed. iN(t make_parserthandlers %s

%s

sU
Converted to HTML by rss2html.py.
t RSSHandlercBs2eZejdZdZdZdZRS(cCsbtjj|tjd||_d|_d|_t |_ d|_ d|_ d|_ dS(Nsutf-8t(RtContentHandlert__init__tcodecst getwritert_outt_texttNonet_parenttFalset _list_startedt_titlet_linkt_descr(tselftout((s)/usr/lib64/python2.7/Demo/xml/rss2html.pyR)s     cCs=|dks$|dks$|dkr0||_nd|_dS(NtchanneltimagetitemR(R R (Rtnametattrs((s)/usr/lib64/python2.7/Demo/xml/rss2html.pyt startElement6s$ cCsb|jdkrg|dkr>|jjt|j|jfq?|dkr?|jjd|jq?n|jdkr?|dkr|j|_q?|dkr|j|_q?|dkr|j|_q?|dkr?|js|jjdt |_n|jjd|j|j|jfd|_d|_d |_q?n|d kr^|jjt ndS( NRttitlet descriptions

%s

Rtlinks
    s
  • %s %s Rtrss( R RtwritettopR RRRR tTrueR tbottom(RR((s)/usr/lib64/python2.7/Demo/xml/rss2html.pyt endElement<s. #           cCs|j||_dS(N(R (Rtcontent((s)/usr/lib64/python2.7/Demo/xml/rss2html.pyt charactersYs(t__name__t __module__tsyststdoutRRR!R#(((s)/usr/lib64/python2.7/Demo/xml/rss2html.pyR's  t__main__i(t__doc__R&Rtxml.saxRRRR RRR$tparsertsetContentHandlertparsetargv(((s)/usr/lib64/python2.7/Demo/xml/rss2html.pyts   7  PK%L]I&&xml/elem_count.pyonu[ ^c@sdZddlZddlmZddlmZmZdejfdYZe dkreZ e j ee j ej dndS( s A simple demo that reads in an XML document and displays the number of elements and attributes as well as a tally of elements and attributes by name. iN(t defaultdict(t make_parserthandlert FancyCountercBs#eZdZdZdZRS(cCs4d|_d|_tt|_tt|_dS(Ni(t_elemst_attrsRtintt _elem_typest _attr_types(tself((s+/usr/lib64/python2.7/Demo/xml/elem_count.pyt__init__ s  cCse|jd7_|jt|7_|j|cd7s   PK%L]I&&xml/elem_count.pycnu[ ^c@sdZddlZddlmZddlmZmZdejfdYZe dkreZ e j ee j ej dndS( s A simple demo that reads in an XML document and displays the number of elements and attributes as well as a tally of elements and attributes by name. iN(t defaultdict(t make_parserthandlert FancyCountercBs#eZdZdZdZRS(cCs4d|_d|_tt|_tt|_dS(Ni(t_elemst_attrsRtintt _elem_typest _attr_types(tself((s+/usr/lib64/python2.7/Demo/xml/elem_count.pyt__init__ s  cCse|jd7_|jt|7_|j|cd7s   PK%L]dxml/roundtrip.pynu[""" A simple demo that reads in an XML document and spits out an equivalent, but not necessarily identical, document. """ import sys from xml.sax import saxutils, handler, make_parser # --- The ContentHandler class ContentGenerator(handler.ContentHandler): def __init__(self, out=sys.stdout): handler.ContentHandler.__init__(self) self._out = out # ContentHandler methods def startDocument(self): self._out.write('\n') def startElement(self, name, attrs): self._out.write('<' + name) for (name, value) in attrs.items(): self._out.write(' %s="%s"' % (name, saxutils.escape(value))) self._out.write('>') def endElement(self, name): self._out.write('' % name) def characters(self, content): self._out.write(saxutils.escape(content)) def ignorableWhitespace(self, content): self._out.write(content) def processingInstruction(self, target, data): self._out.write('' % (target, data)) # --- The main program if __name__ == '__main__': parser = make_parser() parser.setContentHandler(ContentGenerator()) parser.parse(sys.argv[1]) PK%L]I8 xml/rss2html.pyonu[ ^c@sdZddlZddlZddlmZmZdZdZdejfdYZ e dkreZ e j e e j ejd ndS( sx A demo that reads in an RSS XML document and emits an HTML file containing a list of the individual items in the feed. iN(t make_parserthandlers %s

    %s

    sU

Converted to HTML by rss2html.py.
t RSSHandlercBs2eZejdZdZdZdZRS(cCsbtjj|tjd||_d|_d|_t |_ d|_ d|_ d|_ dS(Nsutf-8t(RtContentHandlert__init__tcodecst getwritert_outt_texttNonet_parenttFalset _list_startedt_titlet_linkt_descr(tselftout((s)/usr/lib64/python2.7/Demo/xml/rss2html.pyR)s     cCs=|dks$|dks$|dkr0||_nd|_dS(NtchanneltimagetitemR(R R (Rtnametattrs((s)/usr/lib64/python2.7/Demo/xml/rss2html.pyt startElement6s$ cCsb|jdkrg|dkr>|jjt|j|jfq?|dkr?|jjd|jq?n|jdkr?|dkr|j|_q?|dkr|j|_q?|dkr|j|_q?|dkr?|js|jjdt |_n|jjd|j|j|jfd|_d|_d |_q?n|d kr^|jjt ndS( NRttitlet descriptions

%s

Rtlinks
    s
  • %s %s Rtrss( R RtwritettopR RRRR tTrueR tbottom(RR((s)/usr/lib64/python2.7/Demo/xml/rss2html.pyt endElement<s. #           cCs|j||_dS(N(R (Rtcontent((s)/usr/lib64/python2.7/Demo/xml/rss2html.pyt charactersYs(t__name__t __module__tsyststdoutRRR!R#(((s)/usr/lib64/python2.7/Demo/xml/rss2html.pyR's  t__main__i(t__doc__R&Rtxml.saxRRRR RRR$tparsertsetContentHandlertparsetargv(((s)/usr/lib64/python2.7/Demo/xml/rss2html.pyts   7  PK%L]3W  xml/rss2html.pynu[""" A demo that reads in an RSS XML document and emits an HTML file containing a list of the individual items in the feed. """ import sys import codecs from xml.sax import make_parser, handler # --- Templates top = """\ %s

    %s

    """ bottom = """

Converted to HTML by rss2html.py.
""" # --- The ContentHandler class RSSHandler(handler.ContentHandler): def __init__(self, out=sys.stdout): handler.ContentHandler.__init__(self) self._out = codecs.getwriter('utf-8')(out) self._text = "" self._parent = None self._list_started = False self._title = None self._link = None self._descr = "" # ContentHandler methods def startElement(self, name, attrs): if name == "channel" or name == "image" or name == "item": self._parent = name self._text = "" def endElement(self, name): if self._parent == "channel": if name == "title": self._out.write(top % (self._text, self._text)) elif name == "description": self._out.write("

%s

\n" % self._text) elif self._parent == "item": if name == "title": self._title = self._text elif name == "link": self._link = self._text elif name == "description": self._descr = self._text elif name == "item": if not self._list_started: self._out.write("
    \n") self._list_started = True self._out.write('
  • %s %s\n' % (self._link, self._title, self._descr)) self._title = None self._link = None self._descr = "" if name == "rss": self._out.write(bottom) def characters(self, content): self._text = self._text + content # --- Main program if __name__ == '__main__': parser = make_parser() parser.setContentHandler(RSSHandler()) parser.parse(sys.argv[1]) PK%L]‘߀xml/elem_count.pynu[""" A simple demo that reads in an XML document and displays the number of elements and attributes as well as a tally of elements and attributes by name. """ import sys from collections import defaultdict from xml.sax import make_parser, handler class FancyCounter(handler.ContentHandler): def __init__(self): self._elems = 0 self._attrs = 0 self._elem_types = defaultdict(int) self._attr_types = defaultdict(int) def startElement(self, name, attrs): self._elems += 1 self._attrs += len(attrs) self._elem_types[name] += 1 for name in attrs.keys(): self._attr_types[name] += 1 def endDocument(self): print "There were", self._elems, "elements." print "There were", self._attrs, "attributes." print "---ELEMENT TYPES" for pair in self._elem_types.items(): print "%20s %d" % pair print "---ATTRIBUTE TYPES" for pair in self._attr_types.items(): print "%20s %d" % pair if __name__ == '__main__': parser = make_parser() parser.setContentHandler(FancyCounter()) parser.parse(sys.argv[1]) PK%L]@= = xml/roundtrip.pycnu[ ^c@sdZddlZddlmZmZmZdejfdYZedkreZ e j ee j ej dndS(ss A simple demo that reads in an XML document and spits out an equivalent, but not necessarily identical, document. iN(tsaxutilsthandlert make_parsertContentGeneratorcBsMeZejdZdZdZdZdZdZ dZ RS(cCstjj|||_dS(N(RtContentHandlert__init__t_out(tselftout((s*/usr/lib64/python2.7/Demo/xml/roundtrip.pyRscCs|jjddS(Ns, (Rtwrite(R((s*/usr/lib64/python2.7/Demo/xml/roundtrip.pyt startDocumentscCsh|jjd|x=|jD]/\}}|jjd|tj|fq!W|jjddS(Nt(RR titemsRtescape(Rtnametattrstvalue((s*/usr/lib64/python2.7/Demo/xml/roundtrip.pyt startElements'cCs|jjd|dS(Ns(RR (RR((s*/usr/lib64/python2.7/Demo/xml/roundtrip.pyt endElementscCs|jjtj|dS(N(RR RR(Rtcontent((s*/usr/lib64/python2.7/Demo/xml/roundtrip.pyt characters scCs|jj|dS(N(RR (RR((s*/usr/lib64/python2.7/Demo/xml/roundtrip.pytignorableWhitespace#scCs|jjd||fdS(Ns (RR (Rttargettdata((s*/usr/lib64/python2.7/Demo/xml/roundtrip.pytprocessingInstruction&s( t__name__t __module__tsyststdoutRR RRRRR(((s*/usr/lib64/python2.7/Demo/xml/roundtrip.pyR s     t__main__i( t__doc__Rtxml.saxRRRRRRtparsertsetContentHandlertparsetargv(((s*/usr/lib64/python2.7/Demo/xml/roundtrip.pyts   PK%L]@= = xml/roundtrip.pyonu[ ^c@sdZddlZddlmZmZmZdejfdYZedkreZ e j ee j ej dndS(ss A simple demo that reads in an XML document and spits out an equivalent, but not necessarily identical, document. iN(tsaxutilsthandlert make_parsertContentGeneratorcBsMeZejdZdZdZdZdZdZ dZ RS(cCstjj|||_dS(N(RtContentHandlert__init__t_out(tselftout((s*/usr/lib64/python2.7/Demo/xml/roundtrip.pyRscCs|jjddS(Ns, (Rtwrite(R((s*/usr/lib64/python2.7/Demo/xml/roundtrip.pyt startDocumentscCsh|jjd|x=|jD]/\}}|jjd|tj|fq!W|jjddS(Nt(RR titemsRtescape(Rtnametattrstvalue((s*/usr/lib64/python2.7/Demo/xml/roundtrip.pyt startElements'cCs|jjd|dS(Ns(RR (RR((s*/usr/lib64/python2.7/Demo/xml/roundtrip.pyt endElementscCs|jjtj|dS(N(RR RR(Rtcontent((s*/usr/lib64/python2.7/Demo/xml/roundtrip.pyt characters scCs|jj|dS(N(RR (RR((s*/usr/lib64/python2.7/Demo/xml/roundtrip.pytignorableWhitespace#scCs|jjd||fdS(Ns (RR (Rttargettdata((s*/usr/lib64/python2.7/Demo/xml/roundtrip.pytprocessingInstruction&s( t__name__t __module__tsyststdoutRR RRRRR(((s*/usr/lib64/python2.7/Demo/xml/roundtrip.pyR s     t__main__i( t__doc__Rtxml.saxRRRRRRtparsertsetContentHandlertparsetargv(((s*/usr/lib64/python2.7/Demo/xml/roundtrip.pyts   PK%L]Dcomparisons/systemtest.pynuȯ#! /usr/bin/python2.7 # 3) System Test # # Given a list of directories, report any bogus symbolic links contained # anywhere in those subtrees. A bogus symbolic link is one that cannot # be resolved because it points to a nonexistent or otherwise # unresolvable file. Do *not* use an external find executable. # Directories may be very very deep. Print a warning immediately if the # system you're running on doesn't support symbolic links. # This implementation: # - takes one optional argument, using the current directory as default # - uses chdir to increase performance # - sorts the names per directory # - prints output lines of the form "path1 -> path2" as it goes # - prints error messages about directories it can't list or chdir into import os import sys from stat import * def main(): try: # Note: can't test for presence of lstat -- it's always there dummy = os.readlink except AttributeError: print "This system doesn't have symbolic links" sys.exit(0) if sys.argv[1:]: prefix = sys.argv[1] else: prefix = '' if prefix: os.chdir(prefix) if prefix[-1:] != '/': prefix = prefix + '/' reportboguslinks(prefix) else: reportboguslinks('') def reportboguslinks(prefix): try: names = os.listdir('.') except os.error, msg: print "%s%s: can't list: %s" % (prefix, '.', msg) return names.sort() for name in names: if name == os.curdir or name == os.pardir: continue try: mode = os.lstat(name)[ST_MODE] except os.error: print "%s%s: can't stat: %s" % (prefix, name, msg) continue if S_ISLNK(mode): try: os.stat(name) except os.error: print "%s%s -> %s" % \ (prefix, name, os.readlink(name)) elif S_ISDIR(mode): try: os.chdir(name) except os.error, msg: print "%s%s: can't chdir: %s" % \ (prefix, name, msg) continue try: reportboguslinks(prefix + name + '/') finally: os.chdir('..') main() PK%L]&bcomparisons/sortingtest.pyonu[ Afc@s,ddlZddlZdZedS(iNcs{tjd}|dxYtjD]N}tfd|jD}x"|D]\}}d||fGqTWHq%WdS(Ns^(.*)=([-+]?[0-9]+)cSsE|j|}|r7|j\}}t||fSd|fSdS(Ni(tmatchtgroupstint(titemtprogRtvartnum((s4/usr/lib64/python2.7/Demo/comparisons/sortingtest.pytmakekeys c3s|]}|VqdS(N((t.0R(R(s4/usr/lib64/python2.7/Demo/comparisons/sortingtest.pys (ss%s=%s(tretcompiletsyststdintsortedtsplit(RtlinetitemsRR((Rs4/usr/lib64/python2.7/Demo/comparisons/sortingtest.pytmains "(R R R(((s4/usr/lib64/python2.7/Demo/comparisons/sortingtest.pyts   PK%L]]|I comparisons/READMEnu[Subject: Re: What language would you use? From: Tom Christiansen Date: 6 Nov 1994 15:14:51 GMT Newsgroups: comp.lang.python,comp.lang.tcl,comp.lang.scheme,comp.lang.misc,comp.lang.perl Message-Id: <39irtb$3t4@csnews.cs.Colorado.EDU> References: <39b7ha$j9v@zeno.nscf.org> <39hhjp$lgn@csnews.cs.Colorado.EDU> <39hvsu$dus@mathserv.mps.ohio-state.edu> [...] If you're really into benchmarks, I'd love it if someone were to code up the following problems in tcl, python, and scheme (and whatever else you'd like). Separate versions (one optimized for speed, one for beauty :-) are ok. Post your code so we can time it on our own systems. 0) Factorial Test (numerics and function calls) (we did this already) 1) Regular Expressions Test Read a file of (extended per egrep) regular expressions (one per line), and apply those to all files whose names are listed on the command line. Basically, an 'egrep -f' simulator. Test it with 20 "vt100" patterns against a five /etc/termcap files. Tests using more elaborate patters would also be interesting. Your code should not break if given hundreds of regular expressions or binary files to scan. 2) Sorting Test Sort an input file that consists of lines like this var1=23 other=14 ditto=23 fred=2 such that each output line is sorted WRT to the number. Order of output lines does not change. Resolve collisions using the variable name. e.g. fred=2 other=14 ditto=23 var1=23 Lines may be up to several kilobytes in length and contain zillions of variables. 3) System Test Given a list of directories, report any bogus symbolic links contained anywhere in those subtrees. A bogus symbolic link is one that cannot be resolved because it points to a nonexistent or otherwise unresolvable file. Do *not* use an external find executable. Directories may be very very deep. Print a warning immediately if the system you're running on doesn't support symbolic links. I'll post perl solutions if people post the others. --tom -- Tom Christiansen Perl Consultant, Gamer, Hiker tchrist@mox.perl.com "But Billy! A *small* allowance prepares you for a lifetime of small salaries and for your Social Security payments." --Family Circus PK%L]k4zcomparisons/regextest.pynuȯ#! /usr/bin/python2.7 # 1) Regular Expressions Test # # Read a file of (extended per egrep) regular expressions (one per line), # and apply those to all files whose names are listed on the command line. # Basically, an 'egrep -f' simulator. Test it with 20 "vt100" patterns # against a five /etc/termcap files. Tests using more elaborate patters # would also be interesting. Your code should not break if given hundreds # of regular expressions or binary files to scan. # This implementation: # - combines all patterns into a single one using ( ... | ... | ... ) # - reads patterns from stdin, scans files given as command line arguments # - produces output in the format :: # - is only about 2.5 times as slow as egrep (though I couldn't run # Tom's test -- this system, a vanilla SGI, only has /etc/terminfo) import string import sys import re def main(): pats = map(chomp, sys.stdin.readlines()) bigpat = '(' + '|'.join(pats) + ')' prog = re.compile(bigpat) for file in sys.argv[1:]: try: fp = open(file, 'r') except IOError, msg: print "%s: %s" % (file, msg) continue lineno = 0 while 1: line = fp.readline() if not line: break lineno = lineno + 1 if prog.search(line): print "%s:%s:%s" % (file, lineno, line), def chomp(s): return s.rstrip('\n') if __name__ == '__main__': main() PK%L], >>comparisons/systemtest.pycnu[ Afc@s?ddlZddlZddlTdZdZedS(iN(t*cCsy tj}Wn#tk r2dGHtjdnXtjdrPtjd}nd}|rtj||ddkr|d}nt|n tddS(Ns'This system doesn't have symbolic linksiitit/(tostreadlinktAttributeErrortsystexittargvtchdirtreportboguslinks(tdummytprefix((s3/usr/lib64/python2.7/Demo/comparisons/systemtest.pytmains      cCsytjd}Wn)tjk r>}d|d|fGHdSX|jx<|D]4}|tjksP|tjkrzqPnytj|t}Wn)tjk rd|||fGHqPnXt|rytj |Wqtjk r d||tj |fGHqXqPt |rPytj |Wn+tjk rY}d|||fGHqPnXzt ||dWdtj dXqPqPWdS(Nt.s%s%s: can't list: %ss%s%s: can't stat: %ss %s%s -> %ss%s%s: can't chdir: %sRs..(RtlistdirterrortsorttcurdirtpardirtlstattST_MODEtS_ISLNKtstatRtS_ISDIRR R (R tnamestmsgtnametmode((s3/usr/lib64/python2.7/Demo/comparisons/systemtest.pyR )s<    (RRRR R (((s3/usr/lib64/python2.7/Demo/comparisons/systemtest.pyts     !PK%L]'2ӎcomparisons/sortingtest.pynuȯ#! /usr/bin/python2.7 # 2) Sorting Test # # Sort an input file that consists of lines like this # # var1=23 other=14 ditto=23 fred=2 # # such that each output line is sorted WRT to the number. Order # of output lines does not change. Resolve collisions using the # variable name. e.g. # # fred=2 other=14 ditto=23 var1=23 # # Lines may be up to several kilobytes in length and contain # zillions of variables. # This implementation: # - Reads stdin, writes stdout # - Uses any amount of whitespace to separate fields # - Allows signed numbers # - Treats illegally formatted fields as field=0 # - Outputs the sorted fields with exactly one space between them # - Handles blank input lines correctly import re import sys def main(): prog = re.compile('^(.*)=([-+]?[0-9]+)') def makekey(item, prog=prog): match = prog.match(item) if match: var, num = match.groups() return int(num), var else: # Bad input -- pretend it's a var with value 0 return 0, item for line in sys.stdin: items = sorted(makekey(item) for item in line.split()) for num, var in items: print "%s=%s" % (var, num), print main() PK%L]7\AAcomparisons/regextest.pycnu[ Afc@sPddlZddlZddlZdZdZedkrLendS(iNcCstttjj}ddj|d}tj|}xtjdD]}yt |d}Wn%t k r}d||fGHqLnXd}xG|j }|sPn|d}|j |rd|||fGqqWqLWdS( Nt(t|t)itrs%s: %sis%s:%s:%s( tmaptchomptsyststdint readlinestjointretcompiletargvtopentIOErrortreadlinetsearch(tpatstbigpattprogtfiletfptmsgtlinenotline((s2/usr/lib64/python2.7/Demo/comparisons/regextest.pytmains"  cCs |jdS(Ns (trstrip(ts((s2/usr/lib64/python2.7/Demo/comparisons/regextest.pyR+st__main__(tstringRR RRt__name__(((s2/usr/lib64/python2.7/Demo/comparisons/regextest.pyts      PK%L]%.comparisons/patternsnu[^def ^class ^import ^from PK%L], >>comparisons/systemtest.pyonu[ Afc@s?ddlZddlZddlTdZdZedS(iN(t*cCsy tj}Wn#tk r2dGHtjdnXtjdrPtjd}nd}|rtj||ddkr|d}nt|n tddS(Ns'This system doesn't have symbolic linksiitit/(tostreadlinktAttributeErrortsystexittargvtchdirtreportboguslinks(tdummytprefix((s3/usr/lib64/python2.7/Demo/comparisons/systemtest.pytmains      cCsytjd}Wn)tjk r>}d|d|fGHdSX|jx<|D]4}|tjksP|tjkrzqPnytj|t}Wn)tjk rd|||fGHqPnXt|rytj |Wqtjk r d||tj |fGHqXqPt |rPytj |Wn+tjk rY}d|||fGHqPnXzt ||dWdtj dXqPqPWdS(Nt.s%s%s: can't list: %ss%s%s: can't stat: %ss %s%s -> %ss%s%s: can't chdir: %sRs..(RtlistdirterrortsorttcurdirtpardirtlstattST_MODEtS_ISLNKtstatRtS_ISDIRR R (R tnamestmsgtnametmode((s3/usr/lib64/python2.7/Demo/comparisons/systemtest.pyR )s<    (RRRR R (((s3/usr/lib64/python2.7/Demo/comparisons/systemtest.pyts     !PK%L]7\AAcomparisons/regextest.pyonu[ Afc@sPddlZddlZddlZdZdZedkrLendS(iNcCstttjj}ddj|d}tj|}xtjdD]}yt |d}Wn%t k r}d||fGHqLnXd}xG|j }|sPn|d}|j |rd|||fGqqWqLWdS( Nt(t|t)itrs%s: %sis%s:%s:%s( tmaptchomptsyststdint readlinestjointretcompiletargvtopentIOErrortreadlinetsearch(tpatstbigpattprogtfiletfptmsgtlinenotline((s2/usr/lib64/python2.7/Demo/comparisons/regextest.pytmains"  cCs |jdS(Ns (trstrip(ts((s2/usr/lib64/python2.7/Demo/comparisons/regextest.pyR+st__main__(tstringRR RRt__name__(((s2/usr/lib64/python2.7/Demo/comparisons/regextest.pyts      PK%L]&bcomparisons/sortingtest.pycnu[ Afc@s,ddlZddlZdZedS(iNcs{tjd}|dxYtjD]N}tfd|jD}x"|D]\}}d||fGqTWHq%WdS(Ns^(.*)=([-+]?[0-9]+)cSsE|j|}|r7|j\}}t||fSd|fSdS(Ni(tmatchtgroupstint(titemtprogRtvartnum((s4/usr/lib64/python2.7/Demo/comparisons/sortingtest.pytmakekeys c3s|]}|VqdS(N((t.0R(R(s4/usr/lib64/python2.7/Demo/comparisons/sortingtest.pys (ss%s=%s(tretcompiletsyststdintsortedtsplit(RtlinetitemsRR((Rs4/usr/lib64/python2.7/Demo/comparisons/sortingtest.pytmains "(R R R(((s4/usr/lib64/python2.7/Demo/comparisons/sortingtest.pyts   PK%L]F"pdist/rrcs.pycnu[ Afc@sdZddlZddlZddlZddlZddlZddlZddlmZdZ dZ dZ dZ dZ d Zd Zd Zd Zd ZddZdZdZi de fd6de fd6de fd6de fd6defd6defd6defd6de fd6de fd6defd6defd6Zedkre ndS( s$Remote RCS -- command line interfaceiN(t openrcsclientc Csntjt_ytjtjdd\}}|s=d}n|d|d}}tj|sptjdnt|\}}tj||\}}WnZtjk r}|GHdGHdGHdGHd GHd GHd GHd GHd GHdGHdGHtjdnXt |}|s|j }nxP|D]H} y|||| Wqt t jfk re}d| |fGHqXqWdS(Nis h:p:d:qvLtheadisunknown commands2usage: rrcs [options] command [options] [file] ...swhere command can be:s+ ci|put # checkin the given filess co|get # checkouts% info # print header infos1 head # print revision of head branchs* list # list filename if valids" log # print full logs/ diff # diff rcs file and work files7if no files are given, all remote rcs files are assumedis%s: %s( tsyststderrtstdouttgetopttargvtcommandsthas_keyterrortexitRt listfilestIOErrortos( toptstresttcmdtcoptsettfunctcoptstfilestmsgtxtfn((s'/usr/lib64/python2.7/Demo/pdist/rrcs.pytmain s>    cCst|}|j}|j|j| }| r[t||||r[d|GHdSdG|GdGHt|}|j|||}|r|GHndS(Ns %s: unchanged since last checkins Checking ins...(topentreadtclosetisvalidtsamet asklogmessagetput(RRRtftdatatnewtmessagetmessages((s'/usr/lib64/python2.7/Demo/pdist/rrcs.pytcheckin/s      cCs9|j|}t|d}|j||jdS(Ntw(tgetRtwriteR(RRRR!R ((s'/usr/lib64/python2.7/Demo/pdist/rrcs.pytcheckout=s cCs|j|dS(N(tlock(RRR((s'/usr/lib64/python2.7/Demo/pdist/rrcs.pyR*CscCs|j|dS(N(tunlock(RRR((s'/usr/lib64/python2.7/Demo/pdist/rrcs.pyR+FscCsT|j|}|j}|jx|D]}|dG||GHq,WddGHdS(Nt:t=iF(tinfotkeystsort(RRRtdictR/tkey((s'/usr/lib64/python2.7/Demo/pdist/rrcs.pyR.Is    cCs|j|}|G|GHdS(N(R(RRRR((s'/usr/lib64/python2.7/Demo/pdist/rrcs.pyRQscCs|j|r|GHndS(N(R(RRR((s'/usr/lib64/python2.7/Demo/pdist/rrcs.pytlistUscCsTd}x&|D]\}}|d||}q W|d}|j||}|GHdS(Ntt i(tlog(RRRtflagstotaR$((s'/usr/lib64/python2.7/Demo/pdist/rrcs.pyR6Ys  c Cst|||rdSd}x&|D]\}}|d||}q#W|d}|j|}tj}|j||jd||j||fGHtjd||j |f}|rddGHndS(NR4R5isdiff %s -r%s %ss diff %s %s %sR-iF( RR'ttempfiletNamedTemporaryFileR(tflushRR tsystemtname( RRRR7R8R9R!ttftsts((s'/usr/lib64/python2.7/Demo/pdist/rrcs.pytdiffas    cCs_|dkr1t|}|j}|jntj|j}|j|}||kS(N(tNoneRRRtmd5R"tdigesttsum(RRRR!R tlsumtrsum((s'/usr/lib64/python2.7/Demo/pdist/rrcs.pyRqs    cCs|r dGndGdGH|r$dGHnd}xQtjjdtjjtjj}| sl|dkrpPn||}q-W|S(Nsenter description,senter log message,s)terminate with single '.' or end of file:s"NOTE: This is NOT the log message!R4s>> s. (RRR(R<tstdintreadline(R"R#tline((s'/usr/lib64/python2.7/Demo/pdist/rrcs.pyRzs cCs,ytj|Wntjk r'nXdS(N(R tunlinkR (R((s'/usr/lib64/python2.7/Demo/pdist/rrcs.pytremovesR4tciRtcoR'R.RR3R*R+sbhLRtd:l:r:s:w:V:R6tcRAt__main__(t__doc__RR RtstringRCR:t rcsclientRRR%R)R*R+R.RR3R6RARBRRRLRt__name__(((s'/usr/lib64/python2.7/Demo/pdist/rrcs.pytsD       "                      PK%L]%{Ș pdist/rrcs.pynuȯ#! /usr/bin/python2.7 "Remote RCS -- command line interface" import sys import os import getopt import string import md5 import tempfile from rcsclient import openrcsclient def main(): sys.stdout = sys.stderr try: opts, rest = getopt.getopt(sys.argv[1:], 'h:p:d:qvL') if not rest: cmd = 'head' else: cmd, rest = rest[0], rest[1:] if not commands.has_key(cmd): raise getopt.error, "unknown command" coptset, func = commands[cmd] copts, files = getopt.getopt(rest, coptset) except getopt.error, msg: print msg print "usage: rrcs [options] command [options] [file] ..." print "where command can be:" print " ci|put # checkin the given files" print " co|get # checkout" print " info # print header info" print " head # print revision of head branch" print " list # list filename if valid" print " log # print full log" print " diff # diff rcs file and work file" print "if no files are given, all remote rcs files are assumed" sys.exit(2) x = openrcsclient(opts) if not files: files = x.listfiles() for fn in files: try: func(x, copts, fn) except (IOError, os.error), msg: print "%s: %s" % (fn, msg) def checkin(x, copts, fn): f = open(fn) data = f.read() f.close() new = not x.isvalid(fn) if not new and same(x, copts, fn, data): print "%s: unchanged since last checkin" % fn return print "Checking in", fn, "..." message = asklogmessage(new) messages = x.put(fn, data, message) if messages: print messages def checkout(x, copts, fn): data = x.get(fn) f = open(fn, 'w') f.write(data) f.close() def lock(x, copts, fn): x.lock(fn) def unlock(x, copts, fn): x.unlock(fn) def info(x, copts, fn): dict = x.info(fn) keys = dict.keys() keys.sort() for key in keys: print key + ':', dict[key] print '='*70 def head(x, copts, fn): head = x.head(fn) print fn, head def list(x, copts, fn): if x.isvalid(fn): print fn def log(x, copts, fn): flags = '' for o, a in copts: flags = flags + ' ' + o + a flags = flags[1:] messages = x.log(fn, flags) print messages def diff(x, copts, fn): if same(x, copts, fn): return flags = '' for o, a in copts: flags = flags + ' ' + o + a flags = flags[1:] data = x.get(fn) tf = tempfile.NamedTemporaryFile() tf.write(data) tf.flush() print 'diff %s -r%s %s' % (flags, x.head(fn), fn) sts = os.system('diff %s %s %s' % (flags, tf.name, fn)) if sts: print '='*70 def same(x, copts, fn, data = None): if data is None: f = open(fn) data = f.read() f.close() lsum = md5.new(data).digest() rsum = x.sum(fn) return lsum == rsum def asklogmessage(new): if new: print "enter description,", else: print "enter log message,", print "terminate with single '.' or end of file:" if new: print "NOTE: This is NOT the log message!" message = "" while 1: sys.stderr.write(">> ") sys.stderr.flush() line = sys.stdin.readline() if not line or line == '.\n': break message = message + line return message def remove(fn): try: os.unlink(fn) except os.error: pass commands = { 'ci': ('', checkin), 'put': ('', checkin), 'co': ('', checkout), 'get': ('', checkout), 'info': ('', info), 'head': ('', head), 'list': ('', list), 'lock': ('', lock), 'unlock': ('', unlock), 'log': ('bhLRtd:l:r:s:w:V:', log), 'diff': ('c', diff), } if __name__ == '__main__': main() PK%L]Uddpdist/client.pynu["""RPC Client module.""" import sys import socket import pickle import __builtin__ import os # Default verbosity (0 = silent, 1 = print connections, 2 = print requests too) VERBOSE = 1 class Client: """RPC Client class. No need to derive a class -- it's fully generic.""" def __init__(self, address, verbose = VERBOSE): self._pre_init(address, verbose) self._post_init() def _pre_init(self, address, verbose = VERBOSE): if type(address) == type(0): address = ('', address) self._address = address self._verbose = verbose if self._verbose: print "Connecting to %s ..." % repr(address) self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._socket.connect(address) if self._verbose: print "Connected." self._lastid = 0 # Last id for which a reply has been received self._nextid = 1 # Id of next request self._replies = {} # Unprocessed replies self._rf = self._socket.makefile('r') self._wf = self._socket.makefile('w') def _post_init(self): self._methods = self._call('.methods') def __del__(self): self._close() def _close(self): if self._rf: self._rf.close() self._rf = None if self._wf: self._wf.close() self._wf = None if self._socket: self._socket.close() self._socket = None def __getattr__(self, name): if name in self._methods: method = _stub(self, name) setattr(self, name, method) # XXX circular reference return method raise AttributeError, name def _setverbose(self, verbose): self._verbose = verbose def _call(self, name, *args): return self._vcall(name, args) def _vcall(self, name, args): return self._recv(self._vsend(name, args)) def _send(self, name, *args): return self._vsend(name, args) def _send_noreply(self, name, *args): return self._vsend(name, args, 0) def _vsend_noreply(self, name, args): return self._vsend(name, args, 0) def _vsend(self, name, args, wantreply = 1): id = self._nextid self._nextid = id+1 if not wantreply: id = -id request = (name, args, id) if self._verbose > 1: print "sending request: %s" % repr(request) wp = pickle.Pickler(self._wf) wp.dump(request) return id def _recv(self, id): exception, value, rid = self._vrecv(id) if rid != id: raise RuntimeError, "request/reply id mismatch: %d/%d" % (id, rid) if exception is None: return value x = exception if hasattr(__builtin__, exception): x = getattr(__builtin__, exception) elif exception in ('posix.error', 'mac.error'): x = os.error if x == exception: exception = x raise exception, value def _vrecv(self, id): self._flush() if self._replies.has_key(id): if self._verbose > 1: print "retrieving previous reply, id = %d" % id reply = self._replies[id] del self._replies[id] return reply aid = abs(id) while 1: if self._verbose > 1: print "waiting for reply, id = %d" % id rp = pickle.Unpickler(self._rf) reply = rp.load() del rp if self._verbose > 1: print "got reply: %s" % repr(reply) rid = reply[2] arid = abs(rid) if arid == aid: if self._verbose > 1: print "got it" return reply self._replies[rid] = reply if arid > aid: if self._verbose > 1: print "got higher id, assume all ok" return (None, None, id) def _flush(self): self._wf.flush() from security import Security class SecureClient(Client, Security): def __init__(self, *args): import string apply(self._pre_init, args) Security.__init__(self) self._wf.flush() line = self._rf.readline() challenge = string.atoi(string.strip(line)) response = self._encode_challenge(challenge) line = repr(long(response)) if line[-1] in 'Ll': line = line[:-1] self._wf.write(line + '\n') self._wf.flush() self._post_init() class _stub: """Helper class for Client -- each instance serves as a method of the client.""" def __init__(self, client, name): self._client = client self._name = name def __call__(self, *args): return self._client._vcall(self._name, args) PK%L]Zuu pdist/rrcsnuȯ#! /usr/bin/python2.7 import addpack addpack.addpack('/home/guido/src/python/Demo/pdist') import rrcs rrcs.main() PK%L] >L5L5 pdist/rcvs.pynuȯ#! /usr/bin/python2.7 """Remote CVS -- command line interface""" # XXX To do: # # Bugs: # - if the remote file is deleted, "rcvs update" will fail # # Functionality: # - cvs rm # - descend into directories (alraedy done for update) # - conflict resolution # - other relevant commands? # - branches # # - Finesses: # - retain file mode's x bits # - complain when "nothing known about filename" # - edit log message the way CVS lets you edit it # - cvs diff -rREVA -rREVB # - send mail the way CVS sends it # # Performance: # - cache remote checksums (for every revision ever seen!) # - translate symbolic revisions to numeric revisions # # Reliability: # - remote locking # # Security: # - Authenticated RPC? from cvslib import CVS, File import md5 import os import string import sys from cmdfw import CommandFrameWork DEF_LOCAL = 1 # Default -l class MyFile(File): def action(self): """Return a code indicating the update status of this file. The possible return values are: '=' -- everything's fine '0' -- file doesn't exist anywhere '?' -- exists locally only 'A' -- new locally 'R' -- deleted locally 'U' -- changed remotely, no changes locally (includes new remotely or deleted remotely) 'M' -- changed locally, no changes remotely 'C' -- conflict: changed locally as well as remotely (includes cases where the file has been added or removed locally and remotely) 'D' -- deleted remotely 'N' -- new remotely 'r' -- get rid of entry 'c' -- create entry 'u' -- update entry (and probably others :-) """ if not self.lseen: self.getlocal() if not self.rseen: self.getremote() if not self.eseen: if not self.lsum: if not self.rsum: return '0' # Never heard of else: return 'N' # New remotely else: # self.lsum if not self.rsum: return '?' # Local only # Local and remote, but no entry if self.lsum == self.rsum: return 'c' # Restore entry only else: return 'C' # Real conflict else: # self.eseen if not self.lsum: if self.edeleted: if self.rsum: return 'R' # Removed else: return 'r' # Get rid of entry else: # not self.edeleted if self.rsum: print "warning:", print self.file, print "was lost" return 'U' else: return 'r' # Get rid of entry else: # self.lsum if not self.rsum: if self.enew: return 'A' # New locally else: return 'D' # Deleted remotely else: # self.rsum if self.enew: if self.lsum == self.rsum: return 'u' else: return 'C' if self.lsum == self.esum: if self.esum == self.rsum: return '=' else: return 'U' elif self.esum == self.rsum: return 'M' elif self.lsum == self.rsum: return 'u' else: return 'C' def update(self): code = self.action() if code == '=': return print code, self.file if code in ('U', 'N'): self.get() elif code == 'C': print "%s: conflict resolution not yet implemented" % \ self.file elif code == 'D': remove(self.file) self.eseen = 0 elif code == 'r': self.eseen = 0 elif code in ('c', 'u'): self.eseen = 1 self.erev = self.rrev self.enew = 0 self.edeleted = 0 self.esum = self.rsum self.emtime, self.ectime = os.stat(self.file)[-2:] self.extra = '' def commit(self, message = ""): code = self.action() if code in ('A', 'M'): self.put(message) return 1 elif code == 'R': print "%s: committing removes not yet implemented" % \ self.file elif code == 'C': print "%s: conflict resolution not yet implemented" % \ self.file def diff(self, opts = []): self.action() # To update lseen, rseen flags = '' rev = self.rrev # XXX should support two rev options too! for o, a in opts: if o == '-r': rev = a else: flags = flags + ' ' + o + a if rev == self.rrev and self.lsum == self.rsum: return flags = flags[1:] fn = self.file data = self.proxy.get((fn, rev)) sum = md5.new(data).digest() if self.lsum == sum: return import tempfile tf = tempfile.NamedTemporaryFile() tf.write(data) tf.flush() print 'diff %s -r%s %s' % (flags, rev, fn) sts = os.system('diff %s %s %s' % (flags, tf.name, fn)) if sts: print '='*70 def commitcheck(self): return self.action() != 'C' def put(self, message = ""): print "Checking in", self.file, "..." data = open(self.file).read() if not self.enew: self.proxy.lock(self.file) messages = self.proxy.put(self.file, data, message) if messages: print messages self.setentry(self.proxy.head(self.file), self.lsum) def get(self): data = self.proxy.get(self.file) f = open(self.file, 'w') f.write(data) f.close() self.setentry(self.rrev, self.rsum) def log(self, otherflags): print self.proxy.log(self.file, otherflags) def add(self): self.eseen = 0 # While we're hacking... self.esum = self.lsum self.emtime, self.ectime = 0, 0 self.erev = '' self.enew = 1 self.edeleted = 0 self.eseen = 1 # Done self.extra = '' def setentry(self, erev, esum): self.eseen = 0 # While we're hacking... self.esum = esum self.emtime, self.ectime = os.stat(self.file)[-2:] self.erev = erev self.enew = 0 self.edeleted = 0 self.eseen = 1 # Done self.extra = '' SENDMAIL = "/usr/lib/sendmail -t" MAILFORM = """To: %s Subject: CVS changes: %s ...Message from rcvs... Committed files: %s Log message: %s """ class RCVS(CVS): FileClass = MyFile def __init__(self): CVS.__init__(self) def update(self, files): for e in self.whichentries(files, 1): e.update() def commit(self, files, message = ""): list = self.whichentries(files) if not list: return ok = 1 for e in list: if not e.commitcheck(): ok = 0 if not ok: print "correct above errors first" return if not message: message = raw_input("One-liner: ") committed = [] for e in list: if e.commit(message): committed.append(e.file) self.mailinfo(committed, message) def mailinfo(self, files, message = ""): towhom = "sjoerd@cwi.nl, jack@cwi.nl" # XXX mailtext = MAILFORM % (towhom, string.join(files), string.join(files), message) print '-'*70 print mailtext print '-'*70 ok = raw_input("OK to mail to %s? " % towhom) if string.lower(string.strip(ok)) in ('y', 'ye', 'yes'): p = os.popen(SENDMAIL, "w") p.write(mailtext) sts = p.close() if sts: print "Sendmail exit status %s" % str(sts) else: print "Mail sent." else: print "No mail sent." def report(self, files): for e in self.whichentries(files): e.report() def diff(self, files, opts): for e in self.whichentries(files): e.diff(opts) def add(self, files): if not files: raise RuntimeError, "'cvs add' needs at least one file" list = [] for e in self.whichentries(files, 1): e.add() def rm(self, files): if not files: raise RuntimeError, "'cvs rm' needs at least one file" raise RuntimeError, "'cvs rm' not yet imlemented" def log(self, files, opts): flags = '' for o, a in opts: flags = flags + ' ' + o + a for e in self.whichentries(files): e.log(flags) def whichentries(self, files, localfilestoo = 0): if files: list = [] for file in files: if self.entries.has_key(file): e = self.entries[file] else: e = self.FileClass(file) self.entries[file] = e list.append(e) else: list = self.entries.values() for file in self.proxy.listfiles(): if self.entries.has_key(file): continue e = self.FileClass(file) self.entries[file] = e list.append(e) if localfilestoo: for file in os.listdir(os.curdir): if not self.entries.has_key(file) \ and not self.ignored(file): e = self.FileClass(file) self.entries[file] = e list.append(e) list.sort() if self.proxy: for e in list: if e.proxy is None: e.proxy = self.proxy return list class rcvs(CommandFrameWork): GlobalFlags = 'd:h:p:qvL' UsageMessage = \ "usage: rcvs [-d directory] [-h host] [-p port] [-q] [-v] [subcommand arg ...]" PostUsageMessage = \ "If no subcommand is given, the status of all files is listed" def __init__(self): """Constructor.""" CommandFrameWork.__init__(self) self.proxy = None self.cvs = RCVS() def close(self): if self.proxy: self.proxy._close() self.proxy = None def recurse(self): self.close() names = os.listdir(os.curdir) for name in names: if name == os.curdir or name == os.pardir: continue if name == "CVS": continue if not os.path.isdir(name): continue if os.path.islink(name): continue print "--- entering subdirectory", name, "---" os.chdir(name) try: if os.path.isdir("CVS"): self.__class__().run() else: self.recurse() finally: os.chdir(os.pardir) print "--- left subdirectory", name, "---" def options(self, opts): self.opts = opts def ready(self): import rcsclient self.proxy = rcsclient.openrcsclient(self.opts) self.cvs.setproxy(self.proxy) self.cvs.getentries() def default(self): self.cvs.report([]) def do_report(self, opts, files): self.cvs.report(files) def do_update(self, opts, files): """update [-l] [-R] [file] ...""" local = DEF_LOCAL for o, a in opts: if o == '-l': local = 1 if o == '-R': local = 0 self.cvs.update(files) self.cvs.putentries() if not local and not files: self.recurse() flags_update = '-lR' do_up = do_update flags_up = flags_update def do_commit(self, opts, files): """commit [-m message] [file] ...""" message = "" for o, a in opts: if o == '-m': message = a self.cvs.commit(files, message) self.cvs.putentries() flags_commit = 'm:' do_com = do_commit flags_com = flags_commit def do_diff(self, opts, files): """diff [difflags] [file] ...""" self.cvs.diff(files, opts) flags_diff = 'cbitwcefhnlr:sD:S:' do_dif = do_diff flags_dif = flags_diff def do_add(self, opts, files): """add file ...""" if not files: print "'rcvs add' requires at least one file" return self.cvs.add(files) self.cvs.putentries() def do_remove(self, opts, files): """remove file ...""" if not files: print "'rcvs remove' requires at least one file" return self.cvs.remove(files) self.cvs.putentries() do_rm = do_remove def do_log(self, opts, files): """log [rlog-options] [file] ...""" self.cvs.log(files, opts) flags_log = 'bhLNRtd:s:V:r:' def remove(fn): try: os.unlink(fn) except os.error: pass def main(): r = rcvs() try: r.run() finally: r.close() if __name__ == "__main__": main() PK%L];DDpdist/client.pycnu[ ^c@sdZddlZddlZddlZddlZddlZdZdd dYZddlm Z dee fdYZ d d d YZ dS( sRPC Client module.iNitClientcBseZdZedZedZdZdZdZdZ dZ dZ d Z d Z d Zd Zd dZdZdZdZRS(sCRPC Client class. No need to derive a class -- it's fully generic.cCs|j|||jdS(N(t _pre_initt _post_init(tselftaddresstverbose((s)/usr/lib64/python2.7/Demo/pdist/client.pyt__init__scCst|tdkr'd|f}n||_||_|jrTdt|GHntjtjtj|_|jj||jrdGHnd|_ d|_ i|_ |jj d|_ |jj d|_dS(NitsConnecting to %s ...s Connected.itrtw(ttypet_addresst_verbosetreprtsockettAF_INETt SOCK_STREAMt_sockettconnectt_lastidt_nextidt_repliestmakefilet_rft_wf(RRR((s)/usr/lib64/python2.7/Demo/pdist/client.pyRs       cCs|jd|_dS(Ns.methods(t_callt_methods(R((s)/usr/lib64/python2.7/Demo/pdist/client.pyR%scCs|jdS(N(t_close(R((s)/usr/lib64/python2.7/Demo/pdist/client.pyt__del__(scCsj|jr|jjnd|_|jr;|jjnd|_|jr]|jjnd|_dS(N(RtclosetNoneRR(R((s)/usr/lib64/python2.7/Demo/pdist/client.pyR+s     cCs?||jkr2t||}t||||St|dS(N(Rt_stubtsetattrtAttributeError(Rtnametmethod((s)/usr/lib64/python2.7/Demo/pdist/client.pyt __getattr__3s cCs ||_dS(N(R (RR((s)/usr/lib64/python2.7/Demo/pdist/client.pyt _setverbose:scGs|j||S(N(t_vcall(RR"targs((s)/usr/lib64/python2.7/Demo/pdist/client.pyR=scCs|j|j||S(N(t_recvt_vsend(RR"R'((s)/usr/lib64/python2.7/Demo/pdist/client.pyR&@scGs|j||S(N(R)(RR"R'((s)/usr/lib64/python2.7/Demo/pdist/client.pyt_sendCscGs|j||dS(Ni(R)(RR"R'((s)/usr/lib64/python2.7/Demo/pdist/client.pyt _send_noreplyFscCs|j||dS(Ni(R)(RR"R'((s)/usr/lib64/python2.7/Demo/pdist/client.pyt_vsend_noreplyIsicCsy|j}|d|_|s&| }n|||f}|jdkrVdt|GHntj|j}|j||S(Nissending request: %s(RR R tpickletPicklerRtdump(RR"R't wantreplytidtrequesttwp((s)/usr/lib64/python2.7/Demo/pdist/client.pyR)Ls    cCs|j|\}}}||kr:td||fn|dkrJ|S|}tt|rqtt|}n|dkrtj}n||kr|}n||dS(Ns request/reply id mismatch: %d/%ds posix.errors mac.error(s posix.errors mac.error(t_vrecvt RuntimeErrorRthasattrt __builtin__tgetattrtosterror(RR1t exceptiontvaluetridtx((s)/usr/lib64/python2.7/Demo/pdist/client.pyR(Vs      cCs@|j|jj|rR|jdkr7d|GHn|j|}|j|=|St|}x|jdkr|d|GHntj|j}|j}~|jdkrdt |GHn|d}t|}||kr|jdkrdGHn|S||j|<||kra|jdkr+dGHndd|fSqaWdS(Nis"retrieving previous reply, id = %dswaiting for reply, id = %ds got reply: %sisgot itsgot higher id, assume all ok( t_flushRthas_keyR tabsR-t UnpicklerRtloadR R(RR1treplytaidtrpR=tarid((s)/usr/lib64/python2.7/Demo/pdist/client.pyR4es6            cCs|jjdS(N(Rtflush(R((s)/usr/lib64/python2.7/Demo/pdist/client.pyR?}s(t__name__t __module__t__doc__tVERBOSERRRRRR$R%RR&R*R+R,R)R(R4R?(((s)/usr/lib64/python2.7/Demo/pdist/client.pyRs"              (tSecurityt SecureClientcBseZdZRS(cGsddl}t|j|tj||jj|jj}|j |j |}|j |}t t |}|ddkr|d }n|jj|d|jj|jdS(NitLls (tstringtapplyRRMRRRHRtreadlinetatoitstript_encode_challengeR tlongtwriteR(RR'RPtlinet challengetresponse((s)/usr/lib64/python2.7/Demo/pdist/client.pyRs     (RIRJR(((s)/usr/lib64/python2.7/Demo/pdist/client.pyRNsRcBs eZdZdZdZRS(sJHelper class for Client -- each instance serves as a method of the client.cCs||_||_dS(N(t_clientt_name(RtclientR"((s)/usr/lib64/python2.7/Demo/pdist/client.pyRs cGs|jj|j|S(N(R[R&R\(RR'((s)/usr/lib64/python2.7/Demo/pdist/client.pyt__call__s(RIRJRKRR^(((s)/usr/lib64/python2.7/Demo/pdist/client.pyRs ((( RKtsysRR-R7R9RLRtsecurityRMRNR(((s)/usr/lib64/python2.7/Demo/pdist/client.pyts     sPK%L]2"&pdist/FSProxy.pynu["""File System Proxy. Provide an OS-neutral view on a file system, locally or remotely. The functionality is geared towards implementing some sort of rdist-like utility between a Mac and a UNIX system. The module defines three classes: FSProxyLocal -- used for local access FSProxyServer -- used on the server side of remote access FSProxyClient -- used on the client side of remote access The remote classes are instantiated with an IP address and an optional verbosity flag. """ import server import client import md5 import os import fnmatch from stat import * import time import fnmatch maxnamelen = 255 skipnames = (os.curdir, os.pardir) class FSProxyLocal: def __init__(self): self._dirstack = [] self._ignore = ['*.pyc'] + self._readignore() def _close(self): while self._dirstack: self.back() def _readignore(self): file = self._hide('ignore') try: f = open(file) except IOError: file = self._hide('synctree.ignorefiles') try: f = open(file) except IOError: return [] ignore = [] while 1: line = f.readline() if not line: break if line[-1] == '\n': line = line[:-1] ignore.append(line) f.close() return ignore def _hidden(self, name): return name[0] == '.' def _hide(self, name): return '.%s' % name def visible(self, name): if len(name) > maxnamelen: return 0 if name[-1] == '~': return 0 if name in skipnames: return 0 if self._hidden(name): return 0 head, tail = os.path.split(name) if head or not tail: return 0 if os.path.islink(name): return 0 if '\0' in open(name, 'rb').read(512): return 0 for ign in self._ignore: if fnmatch.fnmatch(name, ign): return 0 return 1 def check(self, name): if not self.visible(name): raise os.error, "protected name %s" % repr(name) def checkfile(self, name): self.check(name) if not os.path.isfile(name): raise os.error, "not a plain file %s" % repr(name) def pwd(self): return os.getcwd() def cd(self, name): self.check(name) save = os.getcwd(), self._ignore os.chdir(name) self._dirstack.append(save) self._ignore = self._ignore + self._readignore() def back(self): if not self._dirstack: raise os.error, "empty directory stack" dir, ignore = self._dirstack[-1] os.chdir(dir) del self._dirstack[-1] self._ignore = ignore def _filter(self, files, pat = None): if pat: def keep(name, pat = pat): return fnmatch.fnmatch(name, pat) files = filter(keep, files) files = filter(self.visible, files) files.sort() return files def list(self, pat = None): files = os.listdir(os.curdir) return self._filter(files, pat) def listfiles(self, pat = None): files = os.listdir(os.curdir) files = filter(os.path.isfile, files) return self._filter(files, pat) def listsubdirs(self, pat = None): files = os.listdir(os.curdir) files = filter(os.path.isdir, files) return self._filter(files, pat) def exists(self, name): return self.visible(name) and os.path.exists(name) def isdir(self, name): return self.visible(name) and os.path.isdir(name) def islink(self, name): return self.visible(name) and os.path.islink(name) def isfile(self, name): return self.visible(name) and os.path.isfile(name) def sum(self, name): self.checkfile(name) BUFFERSIZE = 1024*8 f = open(name) sum = md5.new() while 1: buffer = f.read(BUFFERSIZE) if not buffer: break sum.update(buffer) return sum.digest() def size(self, name): self.checkfile(name) return os.stat(name)[ST_SIZE] def mtime(self, name): self.checkfile(name) return time.localtime(os.stat(name)[ST_MTIME]) def stat(self, name): self.checkfile(name) size = os.stat(name)[ST_SIZE] mtime = time.localtime(os.stat(name)[ST_MTIME]) return size, mtime def info(self, name): sum = self.sum(name) size = os.stat(name)[ST_SIZE] mtime = time.localtime(os.stat(name)[ST_MTIME]) return sum, size, mtime def _list(self, function, list): if list is None: list = self.listfiles() res = [] for name in list: try: res.append((name, function(name))) except (os.error, IOError): res.append((name, None)) return res def sumlist(self, list = None): return self._list(self.sum, list) def statlist(self, list = None): return self._list(self.stat, list) def mtimelist(self, list = None): return self._list(self.mtime, list) def sizelist(self, list = None): return self._list(self.size, list) def infolist(self, list = None): return self._list(self.info, list) def _dict(self, function, list): if list is None: list = self.listfiles() dict = {} for name in list: try: dict[name] = function(name) except (os.error, IOError): pass return dict def sumdict(self, list = None): return self.dict(self.sum, list) def sizedict(self, list = None): return self.dict(self.size, list) def mtimedict(self, list = None): return self.dict(self.mtime, list) def statdict(self, list = None): return self.dict(self.stat, list) def infodict(self, list = None): return self._dict(self.info, list) def read(self, name, offset = 0, length = -1): self.checkfile(name) f = open(name) f.seek(offset) if length == 0: data = '' elif length < 0: data = f.read() else: data = f.read(length) f.close() return data def create(self, name): self.check(name) if os.path.exists(name): self.checkfile(name) bname = name + '~' try: os.unlink(bname) except os.error: pass os.rename(name, bname) f = open(name, 'w') f.close() def write(self, name, data, offset = 0): self.checkfile(name) f = open(name, 'r+') f.seek(offset) f.write(data) f.close() def mkdir(self, name): self.check(name) os.mkdir(name, 0777) def rmdir(self, name): self.check(name) os.rmdir(name) class FSProxyServer(FSProxyLocal, server.Server): def __init__(self, address, verbose = server.VERBOSE): FSProxyLocal.__init__(self) server.Server.__init__(self, address, verbose) def _close(self): server.Server._close(self) FSProxyLocal._close(self) def _serve(self): server.Server._serve(self) # Retreat into start directory while self._dirstack: self.back() class FSProxyClient(client.Client): def __init__(self, address, verbose = client.VERBOSE): client.Client.__init__(self, address, verbose) def test(): import string import sys if sys.argv[1:]: port = string.atoi(sys.argv[1]) else: port = 4127 proxy = FSProxyServer(('', port)) proxy._serverloop() if __name__ == '__main__': test() PK%L]roQ8Q8pdist/rcvs.pyonu[ Afc@sdZddlmZmZddlZddlZddlZddlZddlm Z dZ defdYZ dZ d Z d efd YZd e fd YZdZdZedkrendS(s$Remote CVS -- command line interfacei(tCVStFileN(tCommandFrameWorkitMyFilecBskeZdZdZddZgdZdZddZdZdZ d Z d Z RS( cCsl|js|jn|js,|jn|js||jsR|jsKdSdSqh|js_dS|j|jkrudSdSn|js|jr|jrdSdSqh|jrdG|jGd GHd SdSn|js|j rd Sd Sn|j r |j|jkrd SdSn|j|j kr8|j |jkr1dSd Sn0|j |jkrNdS|j|jkrdd SdSdS(sReturn a code indicating the update status of this file. The possible return values are: '=' -- everything's fine '0' -- file doesn't exist anywhere '?' -- exists locally only 'A' -- new locally 'R' -- deleted locally 'U' -- changed remotely, no changes locally (includes new remotely or deleted remotely) 'M' -- changed locally, no changes remotely 'C' -- conflict: changed locally as well as remotely (includes cases where the file has been added or removed locally and remotely) 'D' -- deleted remotely 'N' -- new remotely 'r' -- get rid of entry 'c' -- create entry 'u' -- update entry (and probably others :-) t0tNt?tctCtRtrswarning:swas losttUtAtDtut=tMN( tlseentgetlocaltrseent getremoteteseentlsumtrsumtedeletedtfiletenewtesum(tself((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pytaction0sT               cCs |j}|dkrdS|G|jGH|dkrA|jn|dkr\d|jGHn|dkrt|jd|_n|dkrd|_nm|dkrd |_|j|_d|_d|_|j |_ t j |jd \|_ |_d |_ndS(NRR RRs+%s: conflict resolution not yet implementedR iR RRiit(R R(RR(RRtgettremoveRtrrevterevRRRRtoststattemtimetectimetextra(Rtcode((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pytupdateys,                  "RcCsc|j}|dkr)|j|dS|dkrDd|jGHn|dkr_d|jGHndS( NR RiR s*%s: committing removes not yet implementedRs+%s: conflict resolution not yet implemented(R R(RtputR(RtmessageR(((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pytcommits      c CsE|jd}|j}x;|D]3\}}|dkrA|}q |d||}q W||jkr||j|jkr|dS|d}|j}|jj||f}tj|j }|j|krdSddl } | j } | j || j d|||fGHtjd|| j|f} | rAdd GHndS( NRs-rt iisdiff %s -r%s %ss diff %s %s %sRiF(RR!RRRtproxyRtmd5tnewtdigestttempfiletNamedTemporaryFiletwritetflushR#tsystemtname( RtoptstflagstrevtotatfntdatatsumR2ttftsts((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pytdiffs.    !      cCs|jdkS(NR(R(R((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyt commitcheckscCsdG|jGdGHt|jj}|jsD|jj|jn|jj|j||}|rm|GHn|j|jj|j|j dS(Ns Checking ins...( RtopentreadRR.tlockR*tsetentrytheadR(RR+R>tmessages((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyR*s cCsX|jj|j}t|jd}|j||j|j|j|jdS(Ntw( R.RRRDR4tcloseRGR!R(RR>tf((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyRs   cCs|jj|j|GHdS(N(R.tlogR(Rt otherflags((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyRMscCsXd|_|j|_d\|_|_d|_d|_d|_d|_d|_dS(NiRi(ii( RRRR%R&R"RRR'(R((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pytadds      cCsed|_||_tj|jd\|_|_||_d|_d|_ d|_d|_ dS(NiiiR( RRR#R$RR%R&R"RRR'(RR"R((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyRGs  "    ( t__name__t __module__RR)R,RBRCR*RRMRORG(((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyR.s I      s/usr/lib/sendmail -tsoTo: %s Subject: CVS changes: %s ...Message from rcvs... Committed files: %s Log message: %s tRCVScBsqeZeZdZdZddZddZdZdZ dZ dZ d Z d d Z RS( cCstj|dS(N(Rt__init__(R((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyRSscCs+x$|j|dD]}|jqWdS(Ni(t whichentriesR)(Rtfileste((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyR)sRcCs|j|}|sdSd}x#|D]}|js&d}q&q&W|sTdGHdS|sitd}ng}x0|D](}|j|rv|j|jqvqvW|j||dS(Niiscorrect above errors firsts One-liner: (RTRCt raw_inputR,tappendRtmailinfo(RRUR+tlisttokRVt committed((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyR,s"    cCsd}t|tj|tj||f}ddGH|GHddGHtd|}tjtj|d krtjtd}|j ||j }|rd t |GHqd GHnd GHdS( Nssjoerd@cwi.nl, jack@cwi.nlt-iFsOK to mail to %s? tytyetyesRJsSendmail exit status %ss Mail sent.s No mail sent.(R^R_R`( tMAILFORMtstringtjoinRWtlowertstripR#tpopentSENDMAILR4RKtstr(RRUR+ttowhomtmailtextR[tpRA((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyRYs    cCs(x!|j|D]}|jqWdS(N(RTtreport(RRURV((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyRl!scCs+x$|j|D]}|j|qWdS(N(RTRB(RRUR8RV((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyRB%scCsC|stdng}x$|j|dD]}|jq+WdS(Ns!'cvs add' needs at least one filei(t RuntimeErrorRTRO(RRURZRV((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyRO)s  cCs|stdntddS(Ns 'cvs rm' needs at least one files'cvs rm' not yet imlemented(Rm(RRU((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pytrm0s cCsZd}x&|D]\}}|d||}q Wx$|j|D]}|j|q?WdS(NRR-(RTRM(RRUR8R9R;R<RV((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyRM5s icCs|rkg}xE|D]Q}|jj|r;|j|}n|j|}||j|<|j|qWn|jj}xX|jjD]G}|jj|rqn|j|}||j|<|j|qW|rJxltjtj D]U}|jj| r|j | r|j|}||j|<|j|qqWn|j |jrx/|D]$}|jdkrd|j|_qdqdWn|S(N( tentriesthas_keyt FileClassRXtvaluesR.t listfilesR#tlistdirtcurdirtignoredtsorttNone(RRUt localfilestooRZRRV((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyRT<s8       (RPRQRRqRSR)R,RYRlRBRORnRMRT(((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyRRs         trcvscBseZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z e Ze Zd Zd ZeZeZdZdZeZeZdZdZeZdZdZRS(s d:h:p:qvLsMusage: rcvs [-d directory] [-h host] [-p port] [-q] [-v] [subcommand arg ...]s<If no subcommand is given, the status of all files is listedcCs&tj|d|_t|_dS(s Constructor.N(RRSRxR.RRtcvs(R((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyRSes  cCs&|jr|jjnd|_dS(N(R.t_closeRx(R((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyRKks cCs|jtjtj}x|D]}|tjks#|tjkrMq#n|dkr_q#ntjj|swq#ntjj|rq#ndG|GdGHtj|z3tjjdr|j j n |j WdtjtjdG|GdGHXq#WdS(NRs--- entering subdirectorys---s--- left subdirectory( RKR#RtRutpardirtpathtisdirtislinktchdirt __class__truntrecurse(RtnamesR7((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyRps&     cCs ||_dS(N(R8(RR8((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pytoptionsscCsEddl}|j|j|_|jj|j|jjdS(Ni(t rcsclientt openrcsclientR8R.R{tsetproxyt getentries(RR((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pytreadys cCs|jjgdS(N(R{Rl(R((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pytdefaultscCs|jj|dS(N(R{Rl(RR8RU((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyt do_reportscCst}x>|D]6\}}|dkr.d}n|dkr d}q q W|jj||jj| r| r|jndS(supdate [-l] [-R] [file] ...s-lis-RiN(t DEF_LOCALR{R)t putentriesR(RR8RUtlocalR;R<((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyt do_updates   s-lRcCsVd}x)|D]!\}}|dkr |}q q W|jj|||jjdS(scommit [-m message] [file] ...Rs-mN(R{R,R(RR8RUR+R;R<((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyt do_commits  sm:cCs|jj||dS(sdiff [difflags] [file] ...N(R{RB(RR8RU((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pytdo_diffsscbitwcefhnlr:sD:S:cCs0|sdGHdS|jj||jjdS(s add file ...s%'rcvs add' requires at least one fileN(R{ROR(RR8RU((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pytdo_adds cCs0|sdGHdS|jj||jjdS(sremove file ...s('rcvs remove' requires at least one fileN(R{R R(RR8RU((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyt do_removes cCs|jj||dS(slog [rlog-options] [file] ...N(R{RM(RR8RU((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pytdo_logssbhLNRtd:s:V:r:(RPRQt GlobalFlagst UsageMessagetPostUsageMessageRSRKRRRRRRt flags_updatetdo_uptflags_upRt flags_committdo_comt flags_comRt flags_difftdo_dift flags_difRRtdo_rmRt flags_log(((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyRz]s6             cCs,ytj|Wntjk r'nXdS(N(R#tunlinkterror(R=((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyR scCs)t}z|jWd|jXdS(N(RzRRK(R ((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pytmains t__main__(t__doc__tcvslibRRR/R#RbtsystcmdfwRRRRgRaRRRzR RRP(((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyts       lp   PK%L] , pdist/READMEnu[Filesystem, RCS and CVS client and server classes ================================================= *** See the security warning at the end of this file! *** This directory contains various modules and classes that support remote file system operations. CVS stuff --------- rcvs Script to put in your bin directory rcvs.py Remote CVS client command line interface cvslib.py CVS admin files classes (used by rrcs) cvslock.py CVS locking algorithms RCS stuff --------- rrcs Script to put in your bin directory rrcs.py Remote RCS client command line interface rcsclient.py Return an RCSProxyClient instance (has reasonable default server/port/directory) RCSProxy.py RCS proxy and server classes (on top of rcslib.py) rcslib.py Local-only RCS base class (affects stdout & local work files) FSProxy stuff ------------- sumtree.py Old demo for FSProxy cmptree.py First FSProxy client (used to sync from the Mac) FSProxy.py Filesystem interface classes Generic client/server stuff --------------------------- client.py Client class server.py Server class security.py Security mix-in class (not very secure I think) Other generic stuff ------------------- cmdfw.py CommandFrameWork class (used by rcvs, should be used by rrcs as well) Client/Server operation ----------------------- The Client and Server classes implement a simple-minded RPC protocol, using Python's pickle module to transfer arguments, return values and exceptions with the most generality. The Server class is instantiated with a port number on which it should listen for requests; the Client class is instantiated with a host name and a port number where it should connect to. Once a client is connected, a TCP connection is maintained between client and server. The Server class currently handles only one connection at a time; however it could be rewritten to allow various modes of operations, using multiple threads or processes or the select() system call as desired to serve multiple clients simultaneously (when using select(), still handling one request at a time). This would not require rewriting of the Client class. It may also be possible to adapt the code to use UDP instead of TCP, but then both classes will have to be rewritten (and unless extensive acknowlegements and request serial numbers are used, the server should handle duplicate requests, so its semantics should be idempotent -- shrudder). Even though the FSProxy and RCSProxy modules define client classes, the client class is fully generic -- what methods it supports is determined entirely by the server. The server class, however, must be derived from. This is generally done as follows: from server import Server from client import Client # Define a class that performs the operations locally class MyClassLocal: def __init__(self): ... def _close(self): ... # Derive a server class using multiple inheritance class MyClassServer(MyClassLocal, Server): def __init__(self, address): # Must initialize MyClassLocal as well as Server MyClassLocal.__init__(self) Server.__init__(self, address) def _close(self): Server._close() MyClassLocal._close() # A dummy client class class MyClassClient(Client): pass Note that because MyClassLocal isn't used in the definition of MyClassClient, it would actually be better to place it in a separate module so the definition of MyClassLocal isn't executed when we only instantiate a client. The modules client and server should probably be renamed to Client and Server in order to match the class names. *** Security warning: this version requires that you have a file $HOME/.python_keyfile at the server and client side containing two comma- separated numbers. The security system at the moment makes no guarantees of actuallng being secure -- however it requires that the key file exists and contains the same numbers at both ends for this to work. (You can specify an alternative keyfile in $PYTHON_KEYFILE). Have a look at the Security class in security.py for details; basically, if the key file contains (x, y), then the security server class chooses a random number z (the challenge) in the range 10..100000 and the client must be able to produce pow(z, x, y) (i.e. z**x mod y). PK%L]l  pdist/rcsclient.pynu["""Customize this file to change the default client etc. (In general, it is probably be better to make local operation the default and to require something like an RCSSERVER environment variable to enable remote operation.) """ import string import os # These defaults don't belong here -- they should be taken from the # environment or from a hidden file in the current directory HOST = 'voorn.cwi.nl' PORT = 4127 VERBOSE = 1 LOCAL = 0 import client class RCSProxyClient(client.SecureClient): def __init__(self, address, verbose = client.VERBOSE): client.SecureClient.__init__(self, address, verbose) def openrcsclient(opts = []): "open an RCSProxy client based on a list of options returned by getopt" import RCSProxy host = HOST port = PORT verbose = VERBOSE local = LOCAL directory = None for o, a in opts: if o == '-h': host = a if ':' in host: i = string.find(host, ':') host, p = host[:i], host[i+1:] if p: port = string.atoi(p) if o == '-p': port = string.atoi(a) if o == '-d': directory = a if o == '-v': verbose = verbose + 1 if o == '-q': verbose = 0 if o == '-L': local = 1 if local: import RCSProxy x = RCSProxy.RCSProxyLocal() else: address = (host, port) x = RCSProxyClient(address, verbose) if not directory: try: directory = open(os.path.join("CVS", "Repository")).readline() except IOError: pass else: if directory[-1] == '\n': directory = directory[:-1] if directory: x.cd(directory) return x PK%L]GGpdist/RCSProxy.pyonu[ Afc@sdZddlZddlZddlZddlZddlZddlZddlZdd dYZdej efdYZ de ej fdYZ d Z d Zed krendS( sRCS Proxy. Provide a simplified interface on RCS files, locally or remotely. The functionality is geared towards implementing some sort of remote CVS like utility. It is modeled after the similar module FSProxy. The module defines two classes: RCSProxyLocal -- used for local access RCSProxyServer -- used on the server side of remote access The corresponding client class, RCSProxyClient, is defined in module rcsclient. The remote classes are instantiated with an IP address and an optional verbosity flag. iNt DirSupportcBseeZdZdZdZdZdZdZd dZ dZ dZ d Z RS( cCs g|_dS(N(t _dirstack(tself((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyt__init__!scCs|jdS(N(t_close(R((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyt__del__$scCsx|jr|jqWdS(N(Rtback(R((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyR's cCs tjS(N(tostgetcwd(R((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pytpwd+scCs-tj}tj||jj|dS(N(RRtchdirRtappend(Rtnametsave((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pytcd.s  cCs@|jstjdn|jd}tj||jd=dS(Nsempty directory stacki(RRterrorR (Rtdir((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyR3s    cCs7tjtj}ttjj|}|j||S(N(Rtlistdirtcurdirtfiltertpathtisdirt_filter(Rtpattfiles((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyt listsubdirs:scCstjj|S(N(RRR(RR ((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyR?scCstj|ddS(Ni(Rtmkdir(RR ((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyRBscCstj|dS(N(Rtrmdir(RR ((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyREsN( t__name__t __module__RRRR RRtNoneRRRR(((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyRs         t RCSProxyLocalcBsheZdZdZd dZd dZdZdZd dZ d dZ d dZ RS( cCs!tjj|tj|dS(N(trcslibtRCSRR(R((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyRKscCs!tj|tjj|dS(N(RRR R!(R((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyROs cCs|j|j|S(N(t_listtsum(Rtlist((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pytsumlistSscCs|j|j|S(N(t_dictR#(RR$((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pytsumdictVscCse|j|}d}tj}x*|j|}|s=Pn|j|q$W|j||jS(Niii (t_opentmd5tnewtreadtupdatet _closepipetdigest(Rtname_revtft BUFFERSIZER#tbuffer((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyR#Ys  cCs,|j|}|j}|j||S(N(R(R+R-(RR/R0tdata((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pytgetes  cCs\|j|\}}t|d}|j||j|j|||j|dS(Ntw(t _unmangletopentwritetclosetcheckint_remove(RR/R3tmessageR trevR0((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pytputks   cCs|dkr|j}ng}x[|D]S}y|j|||fWq(tjtfk rz|j|dfq(Xq(W|S(sINTERNAL: apply FUNCTION to all files in LIST. Return a list of the results. The list defaults to all files in the directory if None. N(Rt listfilesR RRtIOError(RtfunctionR$tresR ((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyR"ss  cCsg|dkr|j}ni}x?|D]7}y||||R"R&(((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyRIs       tRCSProxyServercBs)eZejdZdZdZRS(cCs'tj|tjj|||dS(N(RRtservert SecureServer(Rtaddresstverbose((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyRs cCs!tjj|tj|dS(N(RERFRR(R((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyRscCs.tjj|x|jr)|jqWdS(N(RERFt_serveRR(R((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyRIs (RRREtVERBOSERRRI(((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyRDs cCsdddl}ddl}|jdr>|j|jd}nd}td|f}|jdS(Niiit(tstringtsystargvtatoiRDt _serverloop(RLRMtporttproxy((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyt test_servers   cCsddl}|jd s>|jdrU|jdddkrUt|jdnt}|jd}t||rt||}t|rt|t |jdGHqt |GHnd|GH|jddS(Niiit 0123456789is%s: no such attribute( RMRNRStexitRthasattrtgetattrtcallabletapplyttupletrepr(RMRRtwhattattr((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyttests 2    t__main__((t__doc__RER)RtfnmatchRLttempfileR RR!RRFRDRSR^R(((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyts       *O  PK%L]Op!p!pdist/cvslock.pyonu[ ^c@sdZddlZddlZddlZddlZdZdZdZdZdZ ddd YZ d e fd YZ d dd YZ dZ de fdYZde fdYZedZdZedkrendS(sCVS locking algorithm. CVS locking strategy ==================== As reverse engineered from the CVS 1.3 sources (file lock.c): - Locking is done on a per repository basis (but a process can hold write locks for multiple directories); all lock files are placed in the repository and have names beginning with "#cvs.". - Before even attempting to lock, a file "#cvs.tfl." is created (and removed again), to test that we can write the repository. [The algorithm can still be fooled (1) if the repository's mode is changed while attempting to lock; (2) if this file exists and is writable but the directory is not.] - While creating the actual read/write lock files (which may exist for a long time), a "meta-lock" is held. The meta-lock is a directory named "#cvs.lock" in the repository. The meta-lock is also held while a write lock is held. - To set a read lock: - acquire the meta-lock - create the file "#cvs.rfl." - release the meta-lock - To set a write lock: - acquire the meta-lock - check that there are no files called "#cvs.rfl.*" - if there are, release the meta-lock, sleep, try again - create the file "#cvs.wfl." - To release a write lock: - remove the file "#cvs.wfl." - rmdir the meta-lock - To release a read lock: - remove the file "#cvs.rfl." Additional notes ---------------- - A process should read-lock at most one repository at a time. - A process may write-lock as many repositories as it wishes (to avoid deadlocks, I presume it should always lock them top-down in the directory hierarchy). - A process should make sure it removes all its lock files and directories when it crashes. - Limitation: one user id should not be committing files into the same repository at the same time. Turn this into Python code -------------------------- rl = ReadLock(repository, waittime) wl = WriteLock(repository, waittime) list = MultipleWriteLock([repository1, repository2, ...], waittime) iNi is#cvs.lcks #cvs.rfl.s #cvs.wfl.tErrorcBs#eZdZdZdZRS(cCs ||_dS(N(tmsg(tselfR((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyt__init__`scCs t|jS(N(treprR(R((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyt__repr__cscCs t|jS(N(tstrR(R((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyt__str__fs(t__name__t __module__RRR(((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyR^s  tLockedcBseZRS((RR (((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyR jstLockcBsVeZdedZdZdZdZdZdZdZ dZ RS( t.cCsx||_||_d|_d|_ttj}|jt |_ |jt ||_ |jt ||_dS(N(t repositorytdelaytNonetlockdirtlockfileRtostgetpidtjointCVSLCKtcvslcktCVSRFLtcvsrfltCVSWFLtcvswfl(RR Rtpid((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyRps    cCsdGH|jdS(Nt__del__(tunlock(R((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyRzscCsxy'|j|_tj|jddSWqtjk r}d|_|dtkrytj|j}Wntjk rqnX|j|qnt d|j |fqXqWdS(Niisfailed to lock %s: %s( RRRtmkdirterrorRtEEXISTtstattsleepRR (RRtst((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyt setlockdir~s    cCs|j|jdS(N(t unlockfilet unlockdir(R((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyRs cCsP|jrLdG|jGHytj|jWntjk r?nXd|_ndS(Ntunlink(RRR'RR(R((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyR%s  cCsP|jrLdG|jGHytj|jWntjk r?nXd|_ndS(Ntrmdir(RRR(RR(R((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyR&s  cCst||j|jdS(N(R"R R(RR#((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyR"scCstjj|j|S(N(RtpathRR (Rtname((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyRs( RR tDELAYRRR$RR%R&R"R(((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyR ns    cCs|dkrt|n|tj}ytj|}|d}Wntk rbd|}nXdtjtjdd!Gd|G|GHtj|dS(Nisuid %ds[%s]i isWaiting for %s's lock in( R R!tST_UIDtpwdtgetpwuidtKeyErrorttimetctimeR"(R#R Rtuidtpwenttuser((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyR"s    tReadLockcBseZedZRS(cCsztj|||d}z<|j|j|_t|jd}|jd}Wd|sk|jn|jXdS(Nitwi( R RR$RRtopentcloseR%R&(RR Rtoktfp((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyRs     (RR R+R(((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyR5st WriteLockcBseZedZdZRS(cCs}tj||||jx1|j}|s6Pn|j|j|q W|j|_t|jd}|j dS(NR6( R RR$t readers_existR&R"RRR7R8(RR RR2R:((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyRs    cCswtt}xdtj|jD]P}|| tkrytj|j|}Wntjk rjqnX|SqWdS(N( tlenRRtlistdirR R!RRR(RtnR*R#((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyR<s (RR R+RR<(((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyR;s cCsjxcg}xC|D]:}y|jt|dWqtk rI}~PqXqWPt|j||qWtS(Ni(tappendR;R R"Rtlist(t repositoriesRtlockstrtinstance((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pytMultipleWriteLocks  cCsddl}|jdr)|jd}nd}d}d}zDdGHt|}dGH|jdGHt|}dGH|jWddgGHd|_dgGH|r|jndgGH|r|jnd gGHd}d gGHd}d gGHXdS( NiiR sattempting write lock ...sgot it.sattempting read lock ...iiiii(tsystargvRR;RR5t exc_traceback(RGR trltwl((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyttests8        t__main__(((t__doc__RR0R!R-R+R RRRRR R R"R5R;RFRLR(((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pytGs&     ?   ! PK%L]Șypdist/cmptree.pynu["""Compare local and remote dictionaries and transfer differing files -- like rdist.""" import sys from repr import repr import FSProxy import time import os def main(): pwd = os.getcwd() s = raw_input("chdir [%s] " % pwd) if s: os.chdir(s) pwd = os.getcwd() host = ask("host", 'voorn.cwi.nl') port = 4127 verbose = 1 mode = '' print """\ Mode should be a string of characters, indicating what to do with differences. r - read different files to local file system w - write different files to remote file system c - create new files, either remote or local d - delete disappearing files, either remote or local """ s = raw_input("mode [%s] " % mode) if s: mode = s address = (host, port) t1 = time.time() local = FSProxy.FSProxyLocal() remote = FSProxy.FSProxyClient(address, verbose) compare(local, remote, mode) remote._close() local._close() t2 = time.time() dt = t2-t1 mins, secs = divmod(dt, 60) print mins, "minutes and", round(secs), "seconds" raw_input("[Return to exit] ") def ask(prompt, default): s = raw_input("%s [%s] " % (prompt, default)) return s or default def askint(prompt, default): s = raw_input("%s [%s] " % (prompt, str(default))) if s: return string.atoi(s) return default def compare(local, remote, mode): print print "PWD =", repr(os.getcwd()) sums_id = remote._send('sumlist') subdirs_id = remote._send('listsubdirs') remote._flush() print "calculating local sums ..." lsumdict = {} for name, info in local.sumlist(): lsumdict[name] = info print "getting remote sums ..." sums = remote._recv(sums_id) print "got", len(sums) rsumdict = {} for name, rsum in sums: rsumdict[name] = rsum if not lsumdict.has_key(name): print repr(name), "only remote" if 'r' in mode and 'c' in mode: recvfile(local, remote, name) else: lsum = lsumdict[name] if lsum != rsum: print repr(name), rmtime = remote.mtime(name) lmtime = local.mtime(name) if rmtime > lmtime: print "remote newer", if 'r' in mode: recvfile(local, remote, name) elif lmtime > rmtime: print "local newer", if 'w' in mode: sendfile(local, remote, name) else: print "same mtime but different sum?!?!", print for name in lsumdict.keys(): if not rsumdict.keys(): print repr(name), "only locally", fl() if 'w' in mode and 'c' in mode: sendfile(local, remote, name) elif 'r' in mode and 'd' in mode: os.unlink(name) print "removed." print print "gettin subdirs ..." subdirs = remote._recv(subdirs_id) common = [] for name in subdirs: if local.isdir(name): print "Common subdirectory", repr(name) common.append(name) else: print "Remote subdirectory", repr(name), "not found locally" if 'r' in mode and 'c' in mode: pr = "Create local subdirectory %s? [y] " % \ repr(name) if 'y' in mode: ok = 'y' else: ok = ask(pr, "y") if ok[:1] in ('y', 'Y'): local.mkdir(name) print "Subdirectory %s made" % \ repr(name) common.append(name) lsubdirs = local.listsubdirs() for name in lsubdirs: if name not in subdirs: print "Local subdirectory", repr(name), "not found remotely" for name in common: print "Entering subdirectory", repr(name) local.cd(name) remote.cd(name) compare(local, remote, mode) remote.back() local.back() def sendfile(local, remote, name): try: remote.create(name) except (IOError, os.error), msg: print "cannot create:", msg return print "sending ...", fl() data = open(name).read() t1 = time.time() remote._send_noreply('write', name, data) remote._flush() t2 = time.time() dt = t2-t1 print len(data), "bytes in", round(dt), "seconds", if dt: print "i.e.", round(len(data)/dt), "bytes/sec", print def recvfile(local, remote, name): ok = 0 try: rv = recvfile_real(local, remote, name) ok = 1 return rv finally: if not ok: print "*** recvfile of %r failed, deleting" % (name,) local.delete(name) def recvfile_real(local, remote, name): try: local.create(name) except (IOError, os.error), msg: print "cannot create:", msg return print "receiving ...", fl() f = open(name, 'w') t1 = time.time() length = 4*1024 offset = 0 id = remote._send('read', name, offset, length) remote._flush() while 1: newoffset = offset + length newid = remote._send('read', name, newoffset, length) data = remote._recv(id) id = newid if not data: break f.seek(offset) f.write(data) offset = newoffset size = f.tell() t2 = time.time() f.close() dt = t2-t1 print size, "bytes in", round(dt), "seconds", if dt: print "i.e.", size//dt, "bytes/sec", print remote._recv(id) # ignored def fl(): sys.stdout.flush() if __name__ == '__main__': main() PK%L]Cpdist/sumtree.pyonu[ ^c@s5ddlZddlZdZdZedS(iNcCsStj}tj}t||jtj}||GdGHtddS(Ntsecondss[Return to exit] (ttimetFSProxyt FSProxyLocaltsumtreet_closet raw_input(tt1tproxytt2((s*/usr/lib64/python2.7/Demo/pdist/sumtree.pytmains      cCsjdG|jGH|j}|j||j}x/|D]'}|j|t||jq;WdS(NsPWD =(tpwdt listfilestinfolistt listsubdirstcdRtback(Rtfilestsubdirstname((s*/usr/lib64/python2.7/Demo/pdist/sumtree.pyRs      (RRR R(((s*/usr/lib64/python2.7/Demo/pdist/sumtree.pyts   PK%L]e'wwpdist/cmdfw.pyonu[ ^c@s<dZdddYZdZedkr8endS(sHFramework for command line interfaces like CVS. See class CmdFrameWork.tCommandFrameWorkcBs\eZdZdZd ZdZdZd dZdZ dZ d dZ dZ RS( sFramework class for command line interfaces like CVS. The general command line structure is command [flags] subcommand [subflags] [argument] ... There's a class variable GlobalFlags which specifies the global flags options. Subcommands are defined by defining methods named do_. Flags for the subcommand are defined by defining class or instance variables named flags_. If there's no command, method default() is called. The __doc__ strings for the do_ methods are used for the usage message, printed after the general usage message which is the class variable UsageMessage. The class variable PostUsageMessage is printed after all the do_ methods' __doc__ strings. The method's return value can be a suggested exit status. [XXX Need to rewrite this to clarify it.] Common usage is to derive a class, instantiate it, and then call its run() method; by default this takes its arguments from sys.argv[1:]. s;usage: (name)s [flags] subcommand [subflags] [argument] ...tcCsdS(s&Constructor, present for completeness.N((tself((s(/usr/lib64/python2.7/Demo/pdist/cmdfw.pyt__init__#sc Csddl}ddl}|dkr4|jd}ny|j||j\}}Wn |jk ru}|j|SX|j||s|j|j S|d}d|}d|}yt ||} Wn"t k r|jd|fSXyt ||} Wnt k rd} nXy |j|d| \}}Wn.|jk rp}|jd |t |SX|j| ||SdS( s3Process flags, subcommand and options, then run it.iNiitdo_tflags_scommand %r unknownRssubcommand %s: ( tgetopttsystNonetargvt GlobalFlagsterrortusagetoptionstreadytdefaulttgetattrtAttributeErrortstr( RtargsRRtoptstmsgtcmdtmnametfnametmethodtflags((s(/usr/lib64/python2.7/Demo/pdist/cmdfw.pytrun's:            cCsR|rNddGHdGHx+|D]#\}}dG|GdGt|GHqWddGHndS(sWProcess the options retrieved by getopt. Override this if you have any options.t-i(sOptions:toptiontvalueN(trepr(RRtota((s(/usr/lib64/python2.7/Demo/pdist/cmdfw.pyR Gs  cCsdS(s*Called just before calling the subcommand.N((R((s(/usr/lib64/python2.7/Demo/pdist/cmdfw.pyRQscCs%|r|GHn|ji|jjd6GHi}|j}xxut|D]g}|d dkrF|j|rqqFnyt||j}Wn d}nX|r|||su  PK%L]#)--pdist/rcslib.pyonu[ ^c@sYdZddlZddlZddlZddlZddlZdddYZdS(sRCS interface module. Defines the class RCS, which represents a directory with rcs version files and (possibly) corresponding work files. iNtRCScBseZdZejejdZdZdZddZ dZ dZ dZ d Z d dd Zddd Zdd ZdZdZdZdZdZdddZdZdZdZddZdZdZRS(s7RCS interface class (local filesystem version). An instance of this class represents a directory with rcs version files and (possible) corresponding work files. Methods provide access to most rcs operations such as checkin/checkout, access to the rcs metadata (revisions, logs, branches etc.) as well as some filesystem operations such as listing all rcs version files. XXX BUGS / PROBLEMS - The instance always represents the current directory so it's not very useful to have more than one instance around simultaneously s-_=+cCsdS(s Constructor.N((tself((s)/usr/lib64/python2.7/Demo/pdist/rcslib.pyt__init__&scCsdS(s Destructor.N((R((s)/usr/lib64/python2.7/Demo/pdist/rcslib.pyt__del__*stcCsi|j|d|}|j}|j|}|rH|d|}n|ddkre|d }n|S(smReturn the full log text for NAME_REV as a string. Optional OTHERFLAGS are passed to rlog. srlog s%s: %sis (t_opentreadt _closepipe(Rtname_revt otherflagstftdatatstatus((s)/usr/lib64/python2.7/Demo/pdist/rcslib.pytlog0s  cCs|j|}|dS(s%Return the head revision for NAME_REVthead(tinfo(RRtdict((s)/usr/lib64/python2.7/Demo/pdist/rcslib.pyR?sc Cs|j|d}i}x}|j}|s1Pn|ddkrGqntj|d}|dkr|| tj||d}}|||" if None); or the file description if this is a new file. The optional OTHERFLAGS argument is passed to ci without interpretation. Any output from ci goes to directly to stdout. sis s-usci %s%s -t%s %s %ss([\"$`])s\\\1sci %s%s -m"%s" %s %s( t _unmangletisvalidttempfiletNamedTemporaryFiletwritetflushRtretsubR( RRtmessageR RRtnewR#R R((s)/usr/lib64/python2.7/Demo/pdist/rcslib.pytcheckins"      cCstjtj}t|j|}tjjdrdtjd}t|j|}||}nt|j|}|j ||S(s=Return a list of all version files matching optional PATTERN.R( tostlistdirtcurdirtfiltert_isrcstpathtisdirtmaptrealnamet_filter(Rtpattfilestfiles2((s)/usr/lib64/python2.7/Demo/pdist/rcslib.pyt listfiless cCs@|j|}tjj|p?tjjtjjd|S(s0Test whether NAME has a version file associated.R(trcsnameR0R5tisfiletjoin(RRtnamev((s)/usr/lib64/python2.7/Demo/pdist/rcslib.pyR&scCs|j|r|}n |d}tjj|r8|Stjjdtjj|}tjj|ro|Stjjdrtjjd|S|SdS(sReturn the pathname of the version file for NAME. The argument can be a work file name or a version file name. If the version file does not exist, the name of the version file that would be created by "ci" is returned. s,vRN(R4R0R5R?R@tbasenameR6(RRRA((s)/usr/lib64/python2.7/Demo/pdist/rcslib.pyR>s  !cCsN|j|r|d }n|}tjj|r8|Stjj|}|S(sReturn the pathname of the work file for NAME. The argument can be a work file name or a version file name. If the work file does not exist, the name of the work file that would be created by "co" is returned. i(R4R0R5R?RB(RRAR((s)/usr/lib64/python2.7/Demo/pdist/rcslib.pyR8s cCs|j|d}|j}|j|}|r?t|n|sIdS|ddkrf|d }n|j||j|kS(sTest whether FILE (which must have a version file) is locked. XXX This does not tell you which revision number is locked and ignores any revision you may pass in (by virtue of using rlog -L -R). s rlog -L -Ris N(RRRRtNoneR8(RRR RR ((s)/usr/lib64/python2.7/Demo/pdist/rcslib.pytislockeds   cCsD|j|\}}|j|s:tjd|fn||fS(s}Normalize NAME_REV into a (NAME, REV) tuple. Raise an exception if there is no corresponding version file. snot an rcs file %r(R%R&R0terror(RRRR((s)/usr/lib64/python2.7/Demo/pdist/rcslib.pyRssco -ps-rcCsV|j|\}}|j|}|r?|d||}ntjd||fS(sINTERNAL: open a read pipe to NAME_REV using optional COMMAND. Optional FLAG is used to indicate the revision (default -r). Default COMMAND is "co -p". Return a file object connected by a pipe to the command's output. t s%s %r(RR>R0tpopen(RRRtrflagRRRA((s)/usr/lib64/python2.7/Demo/pdist/rcslib.pyRs cCsmt|tdkr1|df}\}}n |\}}x)|D]!}||jkrDtdqDqDW|S(sINTERNAL: Normalize NAME_REV argument to (NAME, REV) tuple. Raise an exception if NAME contains invalid characters. A NAME_REV argument is either NAME string (implying REV='') or a tuple of the form (NAME, REV). Rsbad char in rev(ttypetokcharst ValueError(RRRRtc((s)/usr/lib64/python2.7/Demo/pdist/rcslib.pyR%s   cCs|j}|sd St|d\}}|dkrAd|fS|d@}|dkrfd}|}nd}|d@r|d}n||fS( s:INTERNAL: Close PIPE and print its exit status if nonzero.iitexititstoppedtkilledis (coredump)N(tcloseRCtdivmod(RR tststdetailtreasontsignaltcode((s)/usr/lib64/python2.7/Demo/pdist/rcslib.pyRs       cCs3|d}tj|}|r/td|ndS(s{INTERNAL: run COMMAND in a subshell. Standard input for the command is taken from /dev/null. Raise IOError when the exit status is not zero. Return whatever the calling method should return; normally None. A derived class may override this method and redefine it to capture stdout/stderr of the command and return it. s R8RDRRR%RRR9R]R4(((s)/usr/lib64/python2.7/Demo/pdist/rcslib.pyRs0       !          ((R`RXR0R+RR'R(((s)/usr/lib64/python2.7/Demo/pdist/rcslib.pyts      PK%L]F"pdist/rrcs.pyonu[ Afc@sdZddlZddlZddlZddlZddlZddlZddlmZdZ dZ dZ dZ dZ d Zd Zd Zd Zd ZddZdZdZi de fd6de fd6de fd6de fd6defd6defd6defd6de fd6de fd6defd6defd6Zedkre ndS( s$Remote RCS -- command line interfaceiN(t openrcsclientc Csntjt_ytjtjdd\}}|s=d}n|d|d}}tj|sptjdnt|\}}tj||\}}WnZtjk r}|GHdGHdGHdGHd GHd GHd GHd GHd GHdGHdGHtjdnXt |}|s|j }nxP|D]H} y|||| Wqt t jfk re}d| |fGHqXqWdS(Nis h:p:d:qvLtheadisunknown commands2usage: rrcs [options] command [options] [file] ...swhere command can be:s+ ci|put # checkin the given filess co|get # checkouts% info # print header infos1 head # print revision of head branchs* list # list filename if valids" log # print full logs/ diff # diff rcs file and work files7if no files are given, all remote rcs files are assumedis%s: %s( tsyststderrtstdouttgetopttargvtcommandsthas_keyterrortexitRt listfilestIOErrortos( toptstresttcmdtcoptsettfunctcoptstfilestmsgtxtfn((s'/usr/lib64/python2.7/Demo/pdist/rrcs.pytmain s>    cCst|}|j}|j|j| }| r[t||||r[d|GHdSdG|GdGHt|}|j|||}|r|GHndS(Ns %s: unchanged since last checkins Checking ins...(topentreadtclosetisvalidtsamet asklogmessagetput(RRRtftdatatnewtmessagetmessages((s'/usr/lib64/python2.7/Demo/pdist/rrcs.pytcheckin/s      cCs9|j|}t|d}|j||jdS(Ntw(tgetRtwriteR(RRRR!R ((s'/usr/lib64/python2.7/Demo/pdist/rrcs.pytcheckout=s cCs|j|dS(N(tlock(RRR((s'/usr/lib64/python2.7/Demo/pdist/rrcs.pyR*CscCs|j|dS(N(tunlock(RRR((s'/usr/lib64/python2.7/Demo/pdist/rrcs.pyR+FscCsT|j|}|j}|jx|D]}|dG||GHq,WddGHdS(Nt:t=iF(tinfotkeystsort(RRRtdictR/tkey((s'/usr/lib64/python2.7/Demo/pdist/rrcs.pyR.Is    cCs|j|}|G|GHdS(N(R(RRRR((s'/usr/lib64/python2.7/Demo/pdist/rrcs.pyRQscCs|j|r|GHndS(N(R(RRR((s'/usr/lib64/python2.7/Demo/pdist/rrcs.pytlistUscCsTd}x&|D]\}}|d||}q W|d}|j||}|GHdS(Ntt i(tlog(RRRtflagstotaR$((s'/usr/lib64/python2.7/Demo/pdist/rrcs.pyR6Ys  c Cst|||rdSd}x&|D]\}}|d||}q#W|d}|j|}tj}|j||jd||j||fGHtjd||j |f}|rddGHndS(NR4R5isdiff %s -r%s %ss diff %s %s %sR-iF( RR'ttempfiletNamedTemporaryFileR(tflushRR tsystemtname( RRRR7R8R9R!ttftsts((s'/usr/lib64/python2.7/Demo/pdist/rrcs.pytdiffas    cCs_|dkr1t|}|j}|jntj|j}|j|}||kS(N(tNoneRRRtmd5R"tdigesttsum(RRRR!R tlsumtrsum((s'/usr/lib64/python2.7/Demo/pdist/rrcs.pyRqs    cCs|r dGndGdGH|r$dGHnd}xQtjjdtjjtjj}| sl|dkrpPn||}q-W|S(Nsenter description,senter log message,s)terminate with single '.' or end of file:s"NOTE: This is NOT the log message!R4s>> s. (RRR(R<tstdintreadline(R"R#tline((s'/usr/lib64/python2.7/Demo/pdist/rrcs.pyRzs cCs,ytj|Wntjk r'nXdS(N(R tunlinkR (R((s'/usr/lib64/python2.7/Demo/pdist/rrcs.pytremovesR4tciRtcoR'R.RR3R*R+sbhLRtd:l:r:s:w:V:R6tcRAt__main__(t__doc__RR RtstringRCR:t rcsclientRRR%R)R*R+R.RR3R6RARBRRRLRt__name__(((s'/usr/lib64/python2.7/Demo/pdist/rrcs.pytsD       "                      PK%L]5tVV pdist/mac.pycnu[ ^c@s8ddlZddlZddlZdZedS(iNcCsxzytd}Wntk r'PnXtj|}|sCqn|ddkrf|jddn|t_tjqWdS(Ns$ itrcvs( t raw_inputtEOFErrortstringtsplittinserttsystargvRtmain(tlinetwords((s&/usr/lib64/python2.7/Demo/pdist/mac.pyRs  (RRRR(((s&/usr/lib64/python2.7/Demo/pdist/mac.pyts    PK%L]''pdist/cvslib.pynu["""Utilities for CVS administration.""" import string import os import time import md5 import fnmatch if not hasattr(time, 'timezone'): time.timezone = 0 class File: """Represent a file's status. Instance variables: file -- the filename (no slashes), None if uninitialized lseen -- true if the data for the local file is up to date eseen -- true if the data from the CVS/Entries entry is up to date (this implies that the entry must be written back) rseen -- true if the data for the remote file is up to date proxy -- RCSProxy instance used to contact the server, or None Note that lseen and rseen don't necessary mean that a local or remote file *exists* -- they indicate that we've checked it. However, eseen means that this instance corresponds to an entry in the CVS/Entries file. If lseen is true: lsum -- checksum of the local file, None if no local file lctime -- ctime of the local file, None if no local file lmtime -- mtime of the local file, None if no local file If eseen is true: erev -- revision, None if this is a no revision (not '0') enew -- true if this is an uncommitted added file edeleted -- true if this is an uncommitted removed file ectime -- ctime of last local file corresponding to erev emtime -- mtime of last local file corresponding to erev extra -- 5th string from CVS/Entries file If rseen is true: rrev -- revision of head, None if non-existent rsum -- checksum of that revision, Non if non-existent If eseen and rseen are both true: esum -- checksum of revision erev, None if no revision Note """ def __init__(self, file = None): if file and '/' in file: raise ValueError, "no slash allowed in file" self.file = file self.lseen = self.eseen = self.rseen = 0 self.proxy = None def __cmp__(self, other): return cmp(self.file, other.file) def getlocal(self): try: self.lmtime, self.lctime = os.stat(self.file)[-2:] except os.error: self.lmtime = self.lctime = self.lsum = None else: self.lsum = md5.new(open(self.file).read()).digest() self.lseen = 1 def getentry(self, line): words = string.splitfields(line, '/') if self.file and words[1] != self.file: raise ValueError, "file name mismatch" self.file = words[1] self.erev = words[2] self.edeleted = 0 self.enew = 0 self.ectime = self.emtime = None if self.erev[:1] == '-': self.edeleted = 1 self.erev = self.erev[1:] if self.erev == '0': self.erev = None self.enew = 1 else: dates = words[3] self.ectime = unctime(dates[:24]) self.emtime = unctime(dates[25:]) self.extra = words[4] if self.rseen: self.getesum() self.eseen = 1 def getremote(self, proxy = None): if proxy: self.proxy = proxy try: self.rrev = self.proxy.head(self.file) except (os.error, IOError): self.rrev = None if self.rrev: self.rsum = self.proxy.sum(self.file) else: self.rsum = None if self.eseen: self.getesum() self.rseen = 1 def getesum(self): if self.erev == self.rrev: self.esum = self.rsum elif self.erev: name = (self.file, self.erev) self.esum = self.proxy.sum(name) else: self.esum = None def putentry(self): """Return a line suitable for inclusion in CVS/Entries. The returned line is terminated by a newline. If no entry should be written for this file, return "". """ if not self.eseen: return "" rev = self.erev or '0' if self.edeleted: rev = '-' + rev if self.enew: dates = 'Initial ' + self.file else: dates = gmctime(self.ectime) + ' ' + \ gmctime(self.emtime) return "/%s/%s/%s/%s/\n" % ( self.file, rev, dates, self.extra) def report(self): print '-'*50 def r(key, repr=repr, self=self): try: value = repr(getattr(self, key)) except AttributeError: value = "?" print "%-15s:" % key, value r("file") if self.lseen: r("lsum", hexify) r("lctime", gmctime) r("lmtime", gmctime) if self.eseen: r("erev") r("enew") r("edeleted") r("ectime", gmctime) r("emtime", gmctime) if self.rseen: r("rrev") r("rsum", hexify) if self.eseen: r("esum", hexify) class CVS: """Represent the contents of a CVS admin file (and more). Class variables: FileClass -- the class to be instantiated for entries (this should be derived from class File above) IgnoreList -- shell patterns for local files to be ignored Instance variables: entries -- a dictionary containing File instances keyed by their file name proxy -- an RCSProxy instance, or None """ FileClass = File IgnoreList = ['.*', '@*', ',*', '*~', '*.o', '*.a', '*.so', '*.pyc'] def __init__(self): self.entries = {} self.proxy = None def setproxy(self, proxy): if proxy is self.proxy: return self.proxy = proxy for e in self.entries.values(): e.rseen = 0 def getentries(self): """Read the contents of CVS/Entries""" self.entries = {} f = self.cvsopen("Entries") while 1: line = f.readline() if not line: break e = self.FileClass() e.getentry(line) self.entries[e.file] = e f.close() def putentries(self): """Write CVS/Entries back""" f = self.cvsopen("Entries", 'w') for e in self.values(): f.write(e.putentry()) f.close() def getlocalfiles(self): list = self.entries.keys() addlist = os.listdir(os.curdir) for name in addlist: if name in list: continue if not self.ignored(name): list.append(name) list.sort() for file in list: try: e = self.entries[file] except KeyError: e = self.entries[file] = self.FileClass(file) e.getlocal() def getremotefiles(self, proxy = None): if proxy: self.proxy = proxy if not self.proxy: raise RuntimeError, "no RCS proxy" addlist = self.proxy.listfiles() for file in addlist: try: e = self.entries[file] except KeyError: e = self.entries[file] = self.FileClass(file) e.getremote(self.proxy) def report(self): for e in self.values(): e.report() print '-'*50 def keys(self): keys = self.entries.keys() keys.sort() return keys def values(self): def value(key, self=self): return self.entries[key] return map(value, self.keys()) def items(self): def item(key, self=self): return (key, self.entries[key]) return map(item, self.keys()) def cvsexists(self, file): file = os.path.join("CVS", file) return os.path.exists(file) def cvsopen(self, file, mode = 'r'): file = os.path.join("CVS", file) if 'r' not in mode: self.backup(file) return open(file, mode) def backup(self, file): if os.path.isfile(file): bfile = file + '~' try: os.unlink(bfile) except os.error: pass os.rename(file, bfile) def ignored(self, file): if os.path.isdir(file): return True for pat in self.IgnoreList: if fnmatch.fnmatch(file, pat): return True return False # hexify and unhexify are useful to print MD5 checksums in hex format hexify_format = '%02x' * 16 def hexify(sum): "Return a hex representation of a 16-byte string (e.g. an MD5 digest)" if sum is None: return "None" return hexify_format % tuple(map(ord, sum)) def unhexify(hexsum): "Return the original from a hexified string" if hexsum == "None": return None sum = '' for i in range(0, len(hexsum), 2): sum = sum + chr(string.atoi(hexsum[i:i+2], 16)) return sum unctime_monthmap = {} def unctime(date): if date == "None": return None if not unctime_monthmap: months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] i = 0 for m in months: i = i+1 unctime_monthmap[m] = i words = string.split(date) # Day Mon DD HH:MM:SS YEAR year = string.atoi(words[4]) month = unctime_monthmap[words[1]] day = string.atoi(words[2]) [hh, mm, ss] = map(string.atoi, string.splitfields(words[3], ':')) ss = ss - time.timezone return time.mktime((year, month, day, hh, mm, ss, 0, 0, 0)) def gmctime(t): if t is None: return "None" return time.asctime(time.gmtime(t)) def test_unctime(): now = int(time.time()) t = time.gmtime(now) at = time.asctime(t) print 'GMT', now, at print 'timezone', time.timezone print 'local', time.ctime(now) u = unctime(at) print 'unctime()', u gu = time.gmtime(u) print '->', gu print time.asctime(gu) def test(): x = CVS() x.getentries() x.getlocalfiles() ## x.report() import rcsclient proxy = rcsclient.openrcsclient() x.getremotefiles(proxy) x.report() if __name__ == "__main__": test() PK%L]l!!pdist/cmdfw.pynu["Framework for command line interfaces like CVS. See class CmdFrameWork." class CommandFrameWork: """Framework class for command line interfaces like CVS. The general command line structure is command [flags] subcommand [subflags] [argument] ... There's a class variable GlobalFlags which specifies the global flags options. Subcommands are defined by defining methods named do_. Flags for the subcommand are defined by defining class or instance variables named flags_. If there's no command, method default() is called. The __doc__ strings for the do_ methods are used for the usage message, printed after the general usage message which is the class variable UsageMessage. The class variable PostUsageMessage is printed after all the do_ methods' __doc__ strings. The method's return value can be a suggested exit status. [XXX Need to rewrite this to clarify it.] Common usage is to derive a class, instantiate it, and then call its run() method; by default this takes its arguments from sys.argv[1:]. """ UsageMessage = \ "usage: (name)s [flags] subcommand [subflags] [argument] ..." PostUsageMessage = None GlobalFlags = '' def __init__(self): """Constructor, present for completeness.""" pass def run(self, args = None): """Process flags, subcommand and options, then run it.""" import getopt, sys if args is None: args = sys.argv[1:] try: opts, args = getopt.getopt(args, self.GlobalFlags) except getopt.error, msg: return self.usage(msg) self.options(opts) if not args: self.ready() return self.default() else: cmd = args[0] mname = 'do_' + cmd fname = 'flags_' + cmd try: method = getattr(self, mname) except AttributeError: return self.usage("command %r unknown" % (cmd,)) try: flags = getattr(self, fname) except AttributeError: flags = '' try: opts, args = getopt.getopt(args[1:], flags) except getopt.error, msg: return self.usage( "subcommand %s: " % cmd + str(msg)) self.ready() return method(opts, args) def options(self, opts): """Process the options retrieved by getopt. Override this if you have any options.""" if opts: print "-"*40 print "Options:" for o, a in opts: print 'option', o, 'value', repr(a) print "-"*40 def ready(self): """Called just before calling the subcommand.""" pass def usage(self, msg = None): """Print usage message. Return suitable exit code (2).""" if msg: print msg print self.UsageMessage % {'name': self.__class__.__name__} docstrings = {} c = self.__class__ while 1: for name in dir(c): if name[:3] == 'do_': if docstrings.has_key(name): continue try: doc = getattr(c, name).__doc__ except: doc = None if doc: docstrings[name] = doc if not c.__bases__: break c = c.__bases__[0] if docstrings: print "where subcommand can be:" names = docstrings.keys() names.sort() for name in names: print docstrings[name] if self.PostUsageMessage: print self.PostUsageMessage return 2 def default(self): """Default method, called when no subcommand is given. You should always override this.""" print "Nobody expects the Spanish Inquisition!" def test(): """Test script -- called when this module is run as a script.""" import sys class Hello(CommandFrameWork): def do_hello(self, opts, args): "hello -- print 'hello world', needs no arguments" print "Hello, world" x = Hello() tests = [ [], ['hello'], ['spam'], ['-x'], ['hello', '-x'], None, ] for t in tests: print '-'*10, t, '-'*10 sts = x.run(t) print "Exit status:", repr(sts) if __name__ == '__main__': test() PK%L]Z>N(N(pdist/rcslib.pynu["""RCS interface module. Defines the class RCS, which represents a directory with rcs version files and (possibly) corresponding work files. """ import fnmatch import os import re import string import tempfile class RCS: """RCS interface class (local filesystem version). An instance of this class represents a directory with rcs version files and (possible) corresponding work files. Methods provide access to most rcs operations such as checkin/checkout, access to the rcs metadata (revisions, logs, branches etc.) as well as some filesystem operations such as listing all rcs version files. XXX BUGS / PROBLEMS - The instance always represents the current directory so it's not very useful to have more than one instance around simultaneously """ # Characters allowed in work file names okchars = string.ascii_letters + string.digits + '-_=+' def __init__(self): """Constructor.""" pass def __del__(self): """Destructor.""" pass # --- Informational methods about a single file/revision --- def log(self, name_rev, otherflags = ''): """Return the full log text for NAME_REV as a string. Optional OTHERFLAGS are passed to rlog. """ f = self._open(name_rev, 'rlog ' + otherflags) data = f.read() status = self._closepipe(f) if status: data = data + "%s: %s" % status elif data[-1] == '\n': data = data[:-1] return data def head(self, name_rev): """Return the head revision for NAME_REV""" dict = self.info(name_rev) return dict['head'] def info(self, name_rev): """Return a dictionary of info (from rlog -h) for NAME_REV The dictionary's keys are the keywords that rlog prints (e.g. 'head' and its values are the corresponding data (e.g. '1.3'). XXX symbolic names and locks are not returned """ f = self._open(name_rev, 'rlog -h') dict = {} while 1: line = f.readline() if not line: break if line[0] == '\t': # XXX could be a lock or symbolic name # Anything else? continue i = string.find(line, ':') if i > 0: key, value = line[:i], string.strip(line[i+1:]) dict[key] = value status = self._closepipe(f) if status: raise IOError, status return dict # --- Methods that change files --- def lock(self, name_rev): """Set an rcs lock on NAME_REV.""" name, rev = self.checkfile(name_rev) cmd = "rcs -l%s %s" % (rev, name) return self._system(cmd) def unlock(self, name_rev): """Clear an rcs lock on NAME_REV.""" name, rev = self.checkfile(name_rev) cmd = "rcs -u%s %s" % (rev, name) return self._system(cmd) def checkout(self, name_rev, withlock=0, otherflags=""): """Check out NAME_REV to its work file. If optional WITHLOCK is set, check out locked, else unlocked. The optional OTHERFLAGS is passed to co without interpretation. Any output from co goes to directly to stdout. """ name, rev = self.checkfile(name_rev) if withlock: lockflag = "-l" else: lockflag = "-u" cmd = 'co %s%s %s %s' % (lockflag, rev, otherflags, name) return self._system(cmd) def checkin(self, name_rev, message=None, otherflags=""): """Check in NAME_REV from its work file. The optional MESSAGE argument becomes the checkin message (default "" if None); or the file description if this is a new file. The optional OTHERFLAGS argument is passed to ci without interpretation. Any output from ci goes to directly to stdout. """ name, rev = self._unmangle(name_rev) new = not self.isvalid(name) if not message: message = "" if message and message[-1] != '\n': message = message + '\n' lockflag = "-u" if new: f = tempfile.NamedTemporaryFile() f.write(message) f.flush() cmd = 'ci %s%s -t%s %s %s' % \ (lockflag, rev, f.name, otherflags, name) else: message = re.sub(r'([\"$`])', r'\\\1', message) cmd = 'ci %s%s -m"%s" %s %s' % \ (lockflag, rev, message, otherflags, name) return self._system(cmd) # --- Exported support methods --- def listfiles(self, pat = None): """Return a list of all version files matching optional PATTERN.""" files = os.listdir(os.curdir) files = filter(self._isrcs, files) if os.path.isdir('RCS'): files2 = os.listdir('RCS') files2 = filter(self._isrcs, files2) files = files + files2 files = map(self.realname, files) return self._filter(files, pat) def isvalid(self, name): """Test whether NAME has a version file associated.""" namev = self.rcsname(name) return (os.path.isfile(namev) or os.path.isfile(os.path.join('RCS', namev))) def rcsname(self, name): """Return the pathname of the version file for NAME. The argument can be a work file name or a version file name. If the version file does not exist, the name of the version file that would be created by "ci" is returned. """ if self._isrcs(name): namev = name else: namev = name + ',v' if os.path.isfile(namev): return namev namev = os.path.join('RCS', os.path.basename(namev)) if os.path.isfile(namev): return namev if os.path.isdir('RCS'): return os.path.join('RCS', namev) else: return namev def realname(self, namev): """Return the pathname of the work file for NAME. The argument can be a work file name or a version file name. If the work file does not exist, the name of the work file that would be created by "co" is returned. """ if self._isrcs(namev): name = namev[:-2] else: name = namev if os.path.isfile(name): return name name = os.path.basename(name) return name def islocked(self, name_rev): """Test whether FILE (which must have a version file) is locked. XXX This does not tell you which revision number is locked and ignores any revision you may pass in (by virtue of using rlog -L -R). """ f = self._open(name_rev, 'rlog -L -R') line = f.readline() status = self._closepipe(f) if status: raise IOError, status if not line: return None if line[-1] == '\n': line = line[:-1] return self.realname(name_rev) == self.realname(line) def checkfile(self, name_rev): """Normalize NAME_REV into a (NAME, REV) tuple. Raise an exception if there is no corresponding version file. """ name, rev = self._unmangle(name_rev) if not self.isvalid(name): raise os.error, 'not an rcs file %r' % (name,) return name, rev # --- Internal methods --- def _open(self, name_rev, cmd = 'co -p', rflag = '-r'): """INTERNAL: open a read pipe to NAME_REV using optional COMMAND. Optional FLAG is used to indicate the revision (default -r). Default COMMAND is "co -p". Return a file object connected by a pipe to the command's output. """ name, rev = self.checkfile(name_rev) namev = self.rcsname(name) if rev: cmd = cmd + ' ' + rflag + rev return os.popen("%s %r" % (cmd, namev)) def _unmangle(self, name_rev): """INTERNAL: Normalize NAME_REV argument to (NAME, REV) tuple. Raise an exception if NAME contains invalid characters. A NAME_REV argument is either NAME string (implying REV='') or a tuple of the form (NAME, REV). """ if type(name_rev) == type(''): name_rev = name, rev = name_rev, '' else: name, rev = name_rev for c in rev: if c not in self.okchars: raise ValueError, "bad char in rev" return name_rev def _closepipe(self, f): """INTERNAL: Close PIPE and print its exit status if nonzero.""" sts = f.close() if not sts: return None detail, reason = divmod(sts, 256) if reason == 0: return 'exit', detail # Exit status signal = reason&0x7F if signal == 0x7F: code = 'stopped' signal = detail else: code = 'killed' if reason&0x80: code = code + '(coredump)' return code, signal def _system(self, cmd): """INTERNAL: run COMMAND in a subshell. Standard input for the command is taken from /dev/null. Raise IOError when the exit status is not zero. Return whatever the calling method should return; normally None. A derived class may override this method and redefine it to capture stdout/stderr of the command and return it. """ cmd = cmd + " s   PK%L]" tpdist/server.pynu["""RPC Server module.""" import sys import socket import pickle from fnmatch import fnmatch from repr import repr # Default verbosity (0 = silent, 1 = print connections, 2 = print requests too) VERBOSE = 1 class Server: """RPC Server class. Derive a class to implement a particular service.""" def __init__(self, address, verbose = VERBOSE): if type(address) == type(0): address = ('', address) self._address = address self._verbose = verbose self._socket = None self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._socket.bind(address) self._socket.listen(1) self._listening = 1 def _setverbose(self, verbose): self._verbose = verbose def __del__(self): self._close() def _close(self): self._listening = 0 if self._socket: self._socket.close() self._socket = None def _serverloop(self): while self._listening: self._serve() def _serve(self): if self._verbose: print "Wait for connection ..." conn, address = self._socket.accept() if self._verbose: print "Accepted connection from %s" % repr(address) if not self._verify(conn, address): print "*** Connection from %s refused" % repr(address) conn.close() return rf = conn.makefile('r') wf = conn.makefile('w') ok = 1 while ok: wf.flush() if self._verbose > 1: print "Wait for next request ..." ok = self._dorequest(rf, wf) _valid = ['192.16.201.*', '192.16.197.*', '132.151.1.*', '129.6.64.*'] def _verify(self, conn, address): host, port = address for pat in self._valid: if fnmatch(host, pat): return 1 return 0 def _dorequest(self, rf, wf): rp = pickle.Unpickler(rf) try: request = rp.load() except EOFError: return 0 if self._verbose > 1: print "Got request: %s" % repr(request) try: methodname, args, id = request if '.' in methodname: reply = (None, self._special(methodname, args), id) elif methodname[0] == '_': raise NameError, "illegal method name %s" % repr(methodname) else: method = getattr(self, methodname) reply = (None, apply(method, args), id) except: reply = (sys.exc_type, sys.exc_value, id) if id < 0 and reply[:2] == (None, None): if self._verbose > 1: print "Suppress reply" return 1 if self._verbose > 1: print "Send reply: %s" % repr(reply) wp = pickle.Pickler(wf) wp.dump(reply) return 1 def _special(self, methodname, args): if methodname == '.methods': if not hasattr(self, '_methods'): self._methods = tuple(self._listmethods()) return self._methods raise NameError, "unrecognized special method name %s" % repr(methodname) def _listmethods(self, cl=None): if not cl: cl = self.__class__ names = cl.__dict__.keys() names = filter(lambda x: x[0] != '_', names) names.sort() for base in cl.__bases__: basenames = self._listmethods(base) basenames = filter(lambda x, names=names: x not in names, basenames) names[len(names):] = basenames return names from security import Security class SecureServer(Server, Security): def __init__(self, *args): apply(Server.__init__, (self,) + args) Security.__init__(self) def _verify(self, conn, address): import string challenge = self._generate_challenge() conn.send("%d\n" % challenge) response = "" while "\n" not in response and len(response) < 100: data = conn.recv(100) if not data: break response = response + data try: response = string.atol(string.strip(response)) except string.atol_error: if self._verbose > 0: print "Invalid response syntax", repr(response) return 0 if not self._compare_challenge_response(challenge, response): if self._verbose > 0: print "Invalid response value", repr(response) return 0 if self._verbose > 1: print "Response matches challenge. Go ahead!" return 1 PK%L]Gpdist/sumtree.pynu[import time import FSProxy def main(): t1 = time.time() #proxy = FSProxy.FSProxyClient(('voorn.cwi.nl', 4127)) proxy = FSProxy.FSProxyLocal() sumtree(proxy) proxy._close() t2 = time.time() print t2-t1, "seconds" raw_input("[Return to exit] ") def sumtree(proxy): print "PWD =", proxy.pwd() files = proxy.listfiles() proxy.infolist(files) subdirs = proxy.listsubdirs() for name in subdirs: proxy.cd(name) sumtree(proxy) proxy.back() main() PK%L]#44pdist/rcsclient.pycnu[ ^c@skdZddlZddlZdZdZdZdZddlZdejfdYZ gd Z dS( sCustomize this file to change the default client etc. (In general, it is probably be better to make local operation the default and to require something like an RCSSERVER environment variable to enable remote operation.) iNs voorn.cwi.nliiitRCSProxyClientcBseZejdZRS(cCstjj|||dS(N(tclientt SecureClientt__init__(tselftaddresstverbose((s,/usr/lib64/python2.7/Demo/pdist/rcsclient.pyRs(t__name__t __module__RtVERBOSER(((s,/usr/lib64/python2.7/Demo/pdist/rcsclient.pyRsc Csddl}t}t}t}t}d}x|D]\}}|dkr|}d|krtj|d} || || d}} | rtj| }qqn|dkrtj|}n|dkr|}n|dkr|d}n|d krd }n|d kr1d}q1q1W|r?ddl}|j } n||f} t | |} |sy%t t j jd d j}Wntk rqX|ddkr|d }qn|r| j|n| S(sEopen an RCSProxy client based on a list of options returned by getoptiNs-ht:is-ps-ds-vs-qis-LtCVSt Repositorys (tRCSProxytHOSTtPORTR tLOCALtNonetstringtfindtatoit RCSProxyLocalRtopentostpathtjointreadlinetIOErrortcd( toptsR thosttportRtlocalt directorytotatitptxR((s,/usr/lib64/python2.7/Demo/pdist/rcsclient.pyt openrcsclientsN              % ( t__doc__RRRRR RRRRR'(((s,/usr/lib64/python2.7/Demo/pdist/rcsclient.pyts   PK%L]F N2 2 pdist/makechangelog.pycnu[ Afc@sdZddlZddlZddlZddlZddlZdZejddZidd6dd 6d d 6Z d Z ejd Z dZ dZ edkrendS(s<Turn a pile of RCS log output into ChangeLog file entries. iNc Cstjd}tj|d\}}d}x)|D]!\}}tdkr2|}q2q2Wtj}g}xft|}|sPng}x*t||} | sPn|j| qW|ri||t|)qiqiW|j |j x|D]} t | |qWdS(Nisp:ts-p( tsystargvtgetopttptstdint getnextfilet getnextrevtappendtlentsorttreverset formatrev( targstoptstprefixtotatftallrevstfiletrevstrev((s0/usr/lib64/python2.7/Demo/pdist/makechangelog.pytmain s0       s"^date: ([0-9]+)/([0-9]+)/([0-9]+) s-([0-9]+):([0-9]+):([0-9]+); author: ([^ ;]+)s+Guido van Rossum tguidosJack Jansen tjacks!Sjoerd Mullender tsjoerdcCsh|\}}}}tj|dkrdtjdddddd}tjd}tj|rpt|}nttj|dddg}|dtj |ds&            PK%L]Mi$11pdist/FSProxy.pyonu[ ^c@sdZddlZddlZddlZddlZddlZddlTddlZddlZdZej ej fZ dd dYZ de ej fdYZd ejfd YZd Zed krendS(sFile System Proxy. Provide an OS-neutral view on a file system, locally or remotely. The functionality is geared towards implementing some sort of rdist-like utility between a Mac and a UNIX system. The module defines three classes: FSProxyLocal -- used for local access FSProxyServer -- used on the server side of remote access FSProxyClient -- used on the client side of remote access The remote classes are instantiated with an IP address and an optional verbosity flag. iN(t*it FSProxyLocalcBseZdZdZdZdZdZdZdZdZ dZ d Z d Z d+d Zd+d Zd+d Zd+dZdZdZdZdZdZdZdZdZdZdZd+dZd+dZd+dZd+dZd+dZ dZ!d+dZ"d+d Z#d+d!Z$d+d"Z%d+d#Z&d$d%d&Z'd'Z(d$d(Z)d)Z*d*Z+RS(,cCs#g|_dg|j|_dS(Ns*.pyc(t _dirstackt _readignoret_ignore(tself((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyt__init__!s cCsx|jr|jqWdS(N(Rtback(R((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyt_close%s cCs|jd}yt|}WnEtk rf|jd}yt|}Wqgtk rbgSXnXg}xD|j}|sPn|ddkr|d }n|j|qpW|j|S(Ntignoressynctree.ignorefilesis (t_hidetopentIOErrortreadlinetappendtclose(RtfiletfR tline((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyR)s&      cCs|ddkS(Nit.((Rtname((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyt_hidden<scCsd|S(Ns.%s((RR((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyR ?scCst|tkrdS|ddkr*dS|tkr:dS|j|rMdStjj|\}}|sr| rvdStjj|rdSdt|dj dkrdSx'|j D]}t j ||rdSqWdS(Niit~strbii( tlent maxnamelent skipnamesRtostpathtsplittislinkR treadRtfnmatch(RRtheadttailtign((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pytvisibleBs&  cCs,|j|s(tjdt|ndS(Nsprotected name %s(R$Rterrortrepr(RR((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pytcheckOscCs<|j|tjj|s8tjdt|ndS(Nsnot a plain file %s(R'RRtisfileR%R&(RR((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyt checkfileSs cCs tjS(N(Rtgetcwd(R((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pytpwdXscCsY|j|tj|jf}tj||jj||j|j|_dS(N(R'RR*RtchdirRRR(RRtsave((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pytcd[s   cCsO|jstjdn|jd\}}tj||jd=||_dS(Nsempty directory stacki(RRR%R,R(RtdirR ((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyRbs    cCsD|r$|d}t||}nt|j|}|j|S(NcSstj||S(N(R (Rtpat((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pytkeepls(tfilterR$tsort(RtfilesR0R1((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyt_filterjs   cCs"tjtj}|j||S(N(RtlistdirtcurdirR5(RR0R4((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pytlistsscCs7tjtj}ttjj|}|j||S(N(RR6R7R2RR(R5(RR0R4((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyt listfileswscCs7tjtj}ttjj|}|j||S(N(RR6R7R2RtisdirR5(RR0R4((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyt listsubdirs|scCs|j|otjj|S(N(R$RRtexists(RR((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyR<scCs|j|otjj|S(N(R$RRR:(RR((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyR:scCs|j|otjj|S(N(R$RRR(RR((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyRscCs|j|otjj|S(N(R$RRR((RR((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyR(scCsb|j|d}t|}tj}x*|j|}|sGPn|j|q.W|jS(Niii (R)R tmd5tnewRtupdatetdigest(RRt BUFFERSIZERtsumtbuffer((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyRBs   cCs|j|tj|tS(N(R)RtstattST_SIZE(RR((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pytsizes cCs'|j|tjtj|tS(N(R)ttimet localtimeRRDtST_MTIME(RR((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pytmtimes cCsF|j|tj|t}tjtj|t}||fS(N(R)RRDRERGRHRI(RRRFRJ((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyRDs cCsK|j|}tj|t}tjtj|t}|||fS(N(RBRRDRERGRHRI(RRRBRFRJ((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pytinfoscCs|dkr|j}ng}x[|D]S}y|j|||fWq(tjtfk rz|j|dfq(Xq(W|S(N(tNoneR9RRR%R (RtfunctionR8tresR((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyt_lists  cCs|j|j|S(N(RORB(RR8((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pytsumlistscCs|j|j|S(N(RORD(RR8((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pytstatlistscCs|j|j|S(N(RORJ(RR8((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyt mtimelistscCs|j|j|S(N(RORF(RR8((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pytsizelistscCs|j|j|S(N(RORK(RR8((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pytinfolistscCsg|dkr|j}ni}x?|D]7}y|||||j|jd}nd}td|f}|jdS(NiiiR\(tstringtsystargvtatoiRkt _serverloop(RuRvtporttproxy((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyttest!s   t__main__((t__doc__RlRsR=RR RDRGRR7tpardirRRRmRkRtRrR|Ri(((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyts          PK%L]roQ8Q8pdist/rcvs.pycnu[ Afc@sdZddlmZmZddlZddlZddlZddlZddlm Z dZ defdYZ dZ d Z d efd YZd e fd YZdZdZedkrendS(s$Remote CVS -- command line interfacei(tCVStFileN(tCommandFrameWorkitMyFilecBskeZdZdZddZgdZdZddZdZdZ d Z d Z RS( cCsl|js|jn|js,|jn|js||jsR|jsKdSdSqh|js_dS|j|jkrudSdSn|js|jr|jrdSdSqh|jrdG|jGd GHd SdSn|js|j rd Sd Sn|j r |j|jkrd SdSn|j|j kr8|j |jkr1dSd Sn0|j |jkrNdS|j|jkrdd SdSdS(sReturn a code indicating the update status of this file. The possible return values are: '=' -- everything's fine '0' -- file doesn't exist anywhere '?' -- exists locally only 'A' -- new locally 'R' -- deleted locally 'U' -- changed remotely, no changes locally (includes new remotely or deleted remotely) 'M' -- changed locally, no changes remotely 'C' -- conflict: changed locally as well as remotely (includes cases where the file has been added or removed locally and remotely) 'D' -- deleted remotely 'N' -- new remotely 'r' -- get rid of entry 'c' -- create entry 'u' -- update entry (and probably others :-) t0tNt?tctCtRtrswarning:swas losttUtAtDtut=tMN( tlseentgetlocaltrseent getremoteteseentlsumtrsumtedeletedtfiletenewtesum(tself((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pytaction0sT               cCs |j}|dkrdS|G|jGH|dkrA|jn|dkr\d|jGHn|dkrt|jd|_n|dkrd|_nm|dkrd |_|j|_d|_d|_|j |_ t j |jd \|_ |_d |_ndS(NRR RRs+%s: conflict resolution not yet implementedR iR RRiit(R R(RR(RRtgettremoveRtrrevterevRRRRtoststattemtimetectimetextra(Rtcode((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pytupdateys,                  "RcCsc|j}|dkr)|j|dS|dkrDd|jGHn|dkr_d|jGHndS( NR RiR s*%s: committing removes not yet implementedRs+%s: conflict resolution not yet implemented(R R(RtputR(RtmessageR(((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pytcommits      c CsE|jd}|j}x;|D]3\}}|dkrA|}q |d||}q W||jkr||j|jkr|dS|d}|j}|jj||f}tj|j }|j|krdSddl } | j } | j || j d|||fGHtjd|| j|f} | rAdd GHndS( NRs-rt iisdiff %s -r%s %ss diff %s %s %sRiF(RR!RRRtproxyRtmd5tnewtdigestttempfiletNamedTemporaryFiletwritetflushR#tsystemtname( RtoptstflagstrevtotatfntdatatsumR2ttftsts((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pytdiffs.    !      cCs|jdkS(NR(R(R((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyt commitcheckscCsdG|jGdGHt|jj}|jsD|jj|jn|jj|j||}|rm|GHn|j|jj|j|j dS(Ns Checking ins...( RtopentreadRR.tlockR*tsetentrytheadR(RR+R>tmessages((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyR*s cCsX|jj|j}t|jd}|j||j|j|j|jdS(Ntw( R.RRRDR4tcloseRGR!R(RR>tf((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyRs   cCs|jj|j|GHdS(N(R.tlogR(Rt otherflags((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyRMscCsXd|_|j|_d\|_|_d|_d|_d|_d|_d|_dS(NiRi(ii( RRRR%R&R"RRR'(R((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pytadds      cCsed|_||_tj|jd\|_|_||_d|_d|_ d|_d|_ dS(NiiiR( RRR#R$RR%R&R"RRR'(RR"R((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyRGs  "    ( t__name__t __module__RR)R,RBRCR*RRMRORG(((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyR.s I      s/usr/lib/sendmail -tsoTo: %s Subject: CVS changes: %s ...Message from rcvs... Committed files: %s Log message: %s tRCVScBsqeZeZdZdZddZddZdZdZ dZ dZ d Z d d Z RS( cCstj|dS(N(Rt__init__(R((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyRSscCs+x$|j|dD]}|jqWdS(Ni(t whichentriesR)(Rtfileste((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyR)sRcCs|j|}|sdSd}x#|D]}|js&d}q&q&W|sTdGHdS|sitd}ng}x0|D](}|j|rv|j|jqvqvW|j||dS(Niiscorrect above errors firsts One-liner: (RTRCt raw_inputR,tappendRtmailinfo(RRUR+tlisttokRVt committed((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyR,s"    cCsd}t|tj|tj||f}ddGH|GHddGHtd|}tjtj|d krtjtd}|j ||j }|rd t |GHqd GHnd GHdS( Nssjoerd@cwi.nl, jack@cwi.nlt-iFsOK to mail to %s? tytyetyesRJsSendmail exit status %ss Mail sent.s No mail sent.(R^R_R`( tMAILFORMtstringtjoinRWtlowertstripR#tpopentSENDMAILR4RKtstr(RRUR+ttowhomtmailtextR[tpRA((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyRYs    cCs(x!|j|D]}|jqWdS(N(RTtreport(RRURV((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyRl!scCs+x$|j|D]}|j|qWdS(N(RTRB(RRUR8RV((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyRB%scCsC|stdng}x$|j|dD]}|jq+WdS(Ns!'cvs add' needs at least one filei(t RuntimeErrorRTRO(RRURZRV((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyRO)s  cCs|stdntddS(Ns 'cvs rm' needs at least one files'cvs rm' not yet imlemented(Rm(RRU((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pytrm0s cCsZd}x&|D]\}}|d||}q Wx$|j|D]}|j|q?WdS(NRR-(RTRM(RRUR8R9R;R<RV((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyRM5s icCs|rkg}xE|D]Q}|jj|r;|j|}n|j|}||j|<|j|qWn|jj}xX|jjD]G}|jj|rqn|j|}||j|<|j|qW|rJxltjtj D]U}|jj| r|j | r|j|}||j|<|j|qqWn|j |jrx/|D]$}|jdkrd|j|_qdqdWn|S(N( tentriesthas_keyt FileClassRXtvaluesR.t listfilesR#tlistdirtcurdirtignoredtsorttNone(RRUt localfilestooRZRRV((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyRT<s8       (RPRQRRqRSR)R,RYRlRBRORnRMRT(((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyRRs         trcvscBseZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z e Ze Zd Zd ZeZeZdZdZeZeZdZdZeZdZdZRS(s d:h:p:qvLsMusage: rcvs [-d directory] [-h host] [-p port] [-q] [-v] [subcommand arg ...]s<If no subcommand is given, the status of all files is listedcCs&tj|d|_t|_dS(s Constructor.N(RRSRxR.RRtcvs(R((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyRSes  cCs&|jr|jjnd|_dS(N(R.t_closeRx(R((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyRKks cCs|jtjtj}x|D]}|tjks#|tjkrMq#n|dkr_q#ntjj|swq#ntjj|rq#ndG|GdGHtj|z3tjjdr|j j n |j WdtjtjdG|GdGHXq#WdS(NRs--- entering subdirectorys---s--- left subdirectory( RKR#RtRutpardirtpathtisdirtislinktchdirt __class__truntrecurse(RtnamesR7((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyRps&     cCs ||_dS(N(R8(RR8((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pytoptionsscCsEddl}|j|j|_|jj|j|jjdS(Ni(t rcsclientt openrcsclientR8R.R{tsetproxyt getentries(RR((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pytreadys cCs|jjgdS(N(R{Rl(R((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pytdefaultscCs|jj|dS(N(R{Rl(RR8RU((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyt do_reportscCst}x>|D]6\}}|dkr.d}n|dkr d}q q W|jj||jj| r| r|jndS(supdate [-l] [-R] [file] ...s-lis-RiN(t DEF_LOCALR{R)t putentriesR(RR8RUtlocalR;R<((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyt do_updates   s-lRcCsVd}x)|D]!\}}|dkr |}q q W|jj|||jjdS(scommit [-m message] [file] ...Rs-mN(R{R,R(RR8RUR+R;R<((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyt do_commits  sm:cCs|jj||dS(sdiff [difflags] [file] ...N(R{RB(RR8RU((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pytdo_diffsscbitwcefhnlr:sD:S:cCs0|sdGHdS|jj||jjdS(s add file ...s%'rcvs add' requires at least one fileN(R{ROR(RR8RU((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pytdo_adds cCs0|sdGHdS|jj||jjdS(sremove file ...s('rcvs remove' requires at least one fileN(R{R R(RR8RU((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyt do_removes cCs|jj||dS(slog [rlog-options] [file] ...N(R{RM(RR8RU((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pytdo_logssbhLNRtd:s:V:r:(RPRQt GlobalFlagst UsageMessagetPostUsageMessageRSRKRRRRRRt flags_updatetdo_uptflags_upRt flags_committdo_comt flags_comRt flags_difftdo_dift flags_difRRtdo_rmRt flags_log(((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyRz]s6             cCs,ytj|Wntjk r'nXdS(N(R#tunlinkterror(R=((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyR scCs)t}z|jWd|jXdS(N(RzRRK(R ((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pytmains t__main__(t__doc__tcvslibRRR/R#RbtsystcmdfwRRRRgRaRRRzR RRP(((s'/usr/lib64/python2.7/Demo/pdist/rcvs.pyts       lp   PK%L](q pdist/makechangelog.pynuȯ#! /usr/bin/python2.7 """Turn a pile of RCS log output into ChangeLog file entries. """ import sys import string import re import getopt import time def main(): args = sys.argv[1:] opts, args = getopt.getopt(args, 'p:') prefix = '' for o, a in opts: if p == '-p': prefix = a f = sys.stdin allrevs = [] while 1: file = getnextfile(f) if not file: break revs = [] while 1: rev = getnextrev(f, file) if not rev: break revs.append(rev) if revs: allrevs[len(allrevs):] = revs allrevs.sort() allrevs.reverse() for rev in allrevs: formatrev(rev, prefix) parsedateprog = re.compile( '^date: ([0-9]+)/([0-9]+)/([0-9]+) ' + '([0-9]+):([0-9]+):([0-9]+); author: ([^ ;]+)') authormap = { 'guido': 'Guido van Rossum ', 'jack': 'Jack Jansen ', 'sjoerd': 'Sjoerd Mullender ', } def formatrev(rev, prefix): dateline, file, revline, log = rev if parsedateprog.match(dateline) >= 0: fields = parsedateprog.group(1, 2, 3, 4, 5, 6) author = parsedateprog.group(7) if authormap.has_key(author): author = authormap[author] tfields = map(string.atoi, fields) + [0, 0, 0] tfields[5] = tfields[5] - time.timezone t = time.mktime(tuple(tfields)) print time.ctime(t), '', author words = string.split(log) words[:0] = ['*', prefix + file + ':'] maxcol = 72-8 col = maxcol for word in words: if col > 0 and col + len(word) >= maxcol: print print '\t' + word, col = -1 else: print word, col = col + 1 + len(word) print print startprog = re.compile("^Working file: (.*)$") def getnextfile(f): while 1: line = f.readline() if not line: return None if startprog.match(line) >= 0: file = startprog.group(1) # Skip until first revision while 1: line = f.readline() if not line: return None if line[:10] == '='*10: return None if line[:10] == '-'*10: break ## print "Skipped", line, return file ## else: ## print "Ignored", line, def getnextrev(f, file): # This is called when we are positioned just after a '---' separator revline = f.readline() dateline = f.readline() log = '' while 1: line = f.readline() if not line: break if line[:10] == '='*10: # Ignore the *last* log entry for each file since it # is the revision since which we are logging. return None if line[:10] == '-'*10: break log = log + line return dateline, file, revline, log if __name__ == '__main__': main() PK%L];DDpdist/client.pyonu[ ^c@sdZddlZddlZddlZddlZddlZdZdd dYZddlm Z dee fdYZ d d d YZ dS( sRPC Client module.iNitClientcBseZdZedZedZdZdZdZdZ dZ dZ d Z d Z d Zd Zd dZdZdZdZRS(sCRPC Client class. No need to derive a class -- it's fully generic.cCs|j|||jdS(N(t _pre_initt _post_init(tselftaddresstverbose((s)/usr/lib64/python2.7/Demo/pdist/client.pyt__init__scCst|tdkr'd|f}n||_||_|jrTdt|GHntjtjtj|_|jj||jrdGHnd|_ d|_ i|_ |jj d|_ |jj d|_dS(NitsConnecting to %s ...s Connected.itrtw(ttypet_addresst_verbosetreprtsockettAF_INETt SOCK_STREAMt_sockettconnectt_lastidt_nextidt_repliestmakefilet_rft_wf(RRR((s)/usr/lib64/python2.7/Demo/pdist/client.pyRs       cCs|jd|_dS(Ns.methods(t_callt_methods(R((s)/usr/lib64/python2.7/Demo/pdist/client.pyR%scCs|jdS(N(t_close(R((s)/usr/lib64/python2.7/Demo/pdist/client.pyt__del__(scCsj|jr|jjnd|_|jr;|jjnd|_|jr]|jjnd|_dS(N(RtclosetNoneRR(R((s)/usr/lib64/python2.7/Demo/pdist/client.pyR+s     cCs?||jkr2t||}t||||St|dS(N(Rt_stubtsetattrtAttributeError(Rtnametmethod((s)/usr/lib64/python2.7/Demo/pdist/client.pyt __getattr__3s cCs ||_dS(N(R (RR((s)/usr/lib64/python2.7/Demo/pdist/client.pyt _setverbose:scGs|j||S(N(t_vcall(RR"targs((s)/usr/lib64/python2.7/Demo/pdist/client.pyR=scCs|j|j||S(N(t_recvt_vsend(RR"R'((s)/usr/lib64/python2.7/Demo/pdist/client.pyR&@scGs|j||S(N(R)(RR"R'((s)/usr/lib64/python2.7/Demo/pdist/client.pyt_sendCscGs|j||dS(Ni(R)(RR"R'((s)/usr/lib64/python2.7/Demo/pdist/client.pyt _send_noreplyFscCs|j||dS(Ni(R)(RR"R'((s)/usr/lib64/python2.7/Demo/pdist/client.pyt_vsend_noreplyIsicCsy|j}|d|_|s&| }n|||f}|jdkrVdt|GHntj|j}|j||S(Nissending request: %s(RR R tpickletPicklerRtdump(RR"R't wantreplytidtrequesttwp((s)/usr/lib64/python2.7/Demo/pdist/client.pyR)Ls    cCs|j|\}}}||kr:td||fn|dkrJ|S|}tt|rqtt|}n|dkrtj}n||kr|}n||dS(Ns request/reply id mismatch: %d/%ds posix.errors mac.error(s posix.errors mac.error(t_vrecvt RuntimeErrorRthasattrt __builtin__tgetattrtosterror(RR1t exceptiontvaluetridtx((s)/usr/lib64/python2.7/Demo/pdist/client.pyR(Vs      cCs@|j|jj|rR|jdkr7d|GHn|j|}|j|=|St|}x|jdkr|d|GHntj|j}|j}~|jdkrdt |GHn|d}t|}||kr|jdkrdGHn|S||j|<||kra|jdkr+dGHndd|fSqaWdS(Nis"retrieving previous reply, id = %dswaiting for reply, id = %ds got reply: %sisgot itsgot higher id, assume all ok( t_flushRthas_keyR tabsR-t UnpicklerRtloadR R(RR1treplytaidtrpR=tarid((s)/usr/lib64/python2.7/Demo/pdist/client.pyR4es6            cCs|jjdS(N(Rtflush(R((s)/usr/lib64/python2.7/Demo/pdist/client.pyR?}s(t__name__t __module__t__doc__tVERBOSERRRRRR$R%RR&R*R+R,R)R(R4R?(((s)/usr/lib64/python2.7/Demo/pdist/client.pyRs"              (tSecurityt SecureClientcBseZdZRS(cGsddl}t|j|tj||jj|jj}|j |j |}|j |}t t |}|ddkr|d }n|jj|d|jj|jdS(NitLls (tstringtapplyRRMRRRHRtreadlinetatoitstript_encode_challengeR tlongtwriteR(RR'RPtlinet challengetresponse((s)/usr/lib64/python2.7/Demo/pdist/client.pyRs     (RIRJR(((s)/usr/lib64/python2.7/Demo/pdist/client.pyRNsRcBs eZdZdZdZRS(sJHelper class for Client -- each instance serves as a method of the client.cCs||_||_dS(N(t_clientt_name(RtclientR"((s)/usr/lib64/python2.7/Demo/pdist/client.pyRs cGs|jj|j|S(N(R[R&R\(RR'((s)/usr/lib64/python2.7/Demo/pdist/client.pyt__call__s(RIRJRKRR^(((s)/usr/lib64/python2.7/Demo/pdist/client.pyRs ((( RKtsysRR-R7R9RLRtsecurityRMRNR(((s)/usr/lib64/python2.7/Demo/pdist/client.pyts     sPK%L]osspdist/RCSProxy.pynuȯ#! /usr/bin/python2.7 """RCS Proxy. Provide a simplified interface on RCS files, locally or remotely. The functionality is geared towards implementing some sort of remote CVS like utility. It is modeled after the similar module FSProxy. The module defines two classes: RCSProxyLocal -- used for local access RCSProxyServer -- used on the server side of remote access The corresponding client class, RCSProxyClient, is defined in module rcsclient. The remote classes are instantiated with an IP address and an optional verbosity flag. """ import server import md5 import os import fnmatch import string import tempfile import rcslib class DirSupport: def __init__(self): self._dirstack = [] def __del__(self): self._close() def _close(self): while self._dirstack: self.back() def pwd(self): return os.getcwd() def cd(self, name): save = os.getcwd() os.chdir(name) self._dirstack.append(save) def back(self): if not self._dirstack: raise os.error, "empty directory stack" dir = self._dirstack[-1] os.chdir(dir) del self._dirstack[-1] def listsubdirs(self, pat = None): files = os.listdir(os.curdir) files = filter(os.path.isdir, files) return self._filter(files, pat) def isdir(self, name): return os.path.isdir(name) def mkdir(self, name): os.mkdir(name, 0777) def rmdir(self, name): os.rmdir(name) class RCSProxyLocal(rcslib.RCS, DirSupport): def __init__(self): rcslib.RCS.__init__(self) DirSupport.__init__(self) def __del__(self): DirSupport.__del__(self) rcslib.RCS.__del__(self) def sumlist(self, list = None): return self._list(self.sum, list) def sumdict(self, list = None): return self._dict(self.sum, list) def sum(self, name_rev): f = self._open(name_rev) BUFFERSIZE = 1024*8 sum = md5.new() while 1: buffer = f.read(BUFFERSIZE) if not buffer: break sum.update(buffer) self._closepipe(f) return sum.digest() def get(self, name_rev): f = self._open(name_rev) data = f.read() self._closepipe(f) return data def put(self, name_rev, data, message=None): name, rev = self._unmangle(name_rev) f = open(name, 'w') f.write(data) f.close() self.checkin(name_rev, message) self._remove(name) def _list(self, function, list = None): """INTERNAL: apply FUNCTION to all files in LIST. Return a list of the results. The list defaults to all files in the directory if None. """ if list is None: list = self.listfiles() res = [] for name in list: try: res.append((name, function(name))) except (os.error, IOError): res.append((name, None)) return res def _dict(self, function, list = None): """INTERNAL: apply FUNCTION to all files in LIST. Return a dictionary mapping files to results. The list defaults to all files in the directory if None. """ if list is None: list = self.listfiles() dict = {} for name in list: try: dict[name] = function(name) except (os.error, IOError): pass return dict class RCSProxyServer(RCSProxyLocal, server.SecureServer): def __init__(self, address, verbose = server.VERBOSE): RCSProxyLocal.__init__(self) server.SecureServer.__init__(self, address, verbose) def _close(self): server.SecureServer._close(self) RCSProxyLocal._close(self) def _serve(self): server.SecureServer._serve(self) # Retreat into start directory while self._dirstack: self.back() def test_server(): import string import sys if sys.argv[1:]: port = string.atoi(sys.argv[1]) else: port = 4127 proxy = RCSProxyServer(('', port)) proxy._serverloop() def test(): import sys if not sys.argv[1:] or sys.argv[1] and sys.argv[1][0] in '0123456789': test_server() sys.exit(0) proxy = RCSProxyLocal() what = sys.argv[1] if hasattr(proxy, what): attr = getattr(proxy, what) if callable(attr): print apply(attr, tuple(sys.argv[2:])) else: print repr(attr) else: print "%s: no such attribute" % what sys.exit(2) if __name__ == '__main__': test() PK%L]HxT3T3pdist/cvslib.pyonu[ ^c@sdZddlZddlZddlZddlZddlZeeds]de_ndddYZdddYZ d d Z d Z d Z iZ d ZdZdZdZedkrendS(s!Utilities for CVS administration.iNttimezoneitFilecBs\eZdZd dZdZdZdZd dZdZ dZ dZ RS( sRepresent a file's status. Instance variables: file -- the filename (no slashes), None if uninitialized lseen -- true if the data for the local file is up to date eseen -- true if the data from the CVS/Entries entry is up to date (this implies that the entry must be written back) rseen -- true if the data for the remote file is up to date proxy -- RCSProxy instance used to contact the server, or None Note that lseen and rseen don't necessary mean that a local or remote file *exists* -- they indicate that we've checked it. However, eseen means that this instance corresponds to an entry in the CVS/Entries file. If lseen is true: lsum -- checksum of the local file, None if no local file lctime -- ctime of the local file, None if no local file lmtime -- mtime of the local file, None if no local file If eseen is true: erev -- revision, None if this is a no revision (not '0') enew -- true if this is an uncommitted added file edeleted -- true if this is an uncommitted removed file ectime -- ctime of last local file corresponding to erev emtime -- mtime of last local file corresponding to erev extra -- 5th string from CVS/Entries file If rseen is true: rrev -- revision of head, None if non-existent rsum -- checksum of that revision, Non if non-existent If eseen and rseen are both true: esum -- checksum of revision erev, None if no revision Note cCsK|rd|krtdn||_d|_|_|_d|_dS(Nt/sno slash allowed in filei(t ValueErrortfiletlseenteseentrseentNonetproxy(tselfR((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pyt__init__9s   cCst|j|jS(N(tcmpR(R tother((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pyt__cmp__@scCsy&tj|jd\|_|_Wn+tjk rSd|_|_|_n(Xtj t |jj j |_d|_ dS(Nii(toststatRtlmtimetlctimeterrorRtlsumtmd5tnewtopentreadtdigestR(R ((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pytgetlocalCs &'cCs)tj|d}|jr:|d|jkr:tdn|d|_|d|_d|_d|_d|_|_ |jd dkrd|_|jd|_n|jdkrd|_d|_n0|d}t |d |_t |d |_ |d |_ |j r|j nd|_dS( NRisfile name mismatchiit-t0iiii(tstringt splitfieldsRRterevtedeletedtenewRtectimetemtimetunctimetextraRtgetesumR(R tlinetwordstdates((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pytgetentryLs*            cCs|r||_ny|jj|j|_Wn#tjtfk rSd|_nX|jrx|jj|j|_ n d|_ |j r|j nd|_ dS(Ni( R theadRtrrevRRtIOErrorRtsumtrsumRR&R(R R ((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pyt getremoteds      cCsa|j|jkr!|j|_n<|jrT|j|jf}|jj||_n d|_dS(N(RR,R/tesumRR R.R(R tname((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pyR&ss  cCs|js dS|jpd}|jr2d|}n|jrKd|j}n t|jdt|j}d|j|||jfS(sReturn a line suitable for inclusion in CVS/Entries. The returned line is terminated by a newline. If no entry should be written for this file, return "". tRRsInitial t s/%s/%s/%s/%s/ ( RRR R!RtgmctimeR"R#R%(R trevR)((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pytputentry|s    cCsddGHt|d}|d|jrU|dt|dt|dtn|jr|d|d |d |d t|d tn|jr|d |dt|jr|dtqndS(NRi2cSsDy|t||}Wntk r2d}nXd|G|GHdS(Nt?s%-15s:(tgetattrtAttributeError(tkeytreprR tvalue((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pytrs   RRRRRR!R R"R#R,R/R1(R<RthexifyR5RR(R R>((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pytreports$              N( t__name__t __module__t__doc__RR RRR*R0R&R7R@(((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pyR s+     tCVScBseZdZeZddddddddgZd Zd Zd Zd Z d Z ddZ dZ dZdZdZdZddZdZdZRS(sRepresent the contents of a CVS admin file (and more). Class variables: FileClass -- the class to be instantiated for entries (this should be derived from class File above) IgnoreList -- shell patterns for local files to be ignored Instance variables: entries -- a dictionary containing File instances keyed by their file name proxy -- an RCSProxy instance, or None s.*s@*s,*s*~s*.os*.as*.sos*.pyccCsi|_d|_dS(N(tentriesRR (R ((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pyR s cCsC||jkrdS||_x |jjD]}d|_q,WdS(Ni(R REtvaluesR(R R te((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pytsetproxys  cCsli|_|jd}xC|j}|s1Pn|j}|j|||j|jcCs>tjjd|}d|kr1|j|nt||S(NRDR>(RRcRdtbackupR(R Rtmode((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pyRJs cCs[tjj|rW|d}ytj|Wntjk rCnXtj||ndS(Nt~(RRctisfiletunlinkRtrename(R Rtbfile((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pyRgs cCsDtjj|rtSx'|jD]}tj||r tSq WtS(N(RRctisdirtTruet IgnoreListtfnmatchtFalse(R Rtpat((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pyRV#s N(RARBRCRRLRpR RHRORRR\RR_R@RSRFRbRfRJRgRV(((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pyRDs"           s%02xicCs'|dkrdStttt|S(sDReturn a hex representation of a 16-byte string (e.g. an MD5 digest)RN(Rt hexify_formatttupleR`tord(R.((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pyR?-s cCsd|dkrdSd}xGtdt|dD]-}|ttj|||d!d}q/W|S(s*Return the original from a hexified stringRR3iiiN(RtrangetlentchrRtatoi(thexsumR.ti((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pytunhexify3s  +c Cs|dkrdStsndddddddd d d d d g }d}x%|D]}|d}|t|s    + cCs&|dkrdStjtj|S(NR(RRtasctimetgmtime(tt((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pyR5Os cCsttj}tj|}tj|}dG|G|GHdGtjGHdGtj|GHt|}dG|GHtj|}dG|GHtj|GHdS(NtGMTRtlocals unctime()s->(tintRRRRtctimeR$(tnowRtattutgu((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pyt test_unctimeSs     cCsPt}|j|jddl}|j}|j||jdS(Ni(RDROR\t rcsclientt openrcsclientR_R@(txRR ((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pyttest`s      t__main__(((RCRRRRRqthasattrRRRDRtR?R}RR$R5RRRA(((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pyts&      ~      PK%L]e'wwpdist/cmdfw.pycnu[ ^c@s<dZdddYZdZedkr8endS(sHFramework for command line interfaces like CVS. See class CmdFrameWork.tCommandFrameWorkcBs\eZdZdZd ZdZdZd dZdZ dZ d dZ dZ RS( sFramework class for command line interfaces like CVS. The general command line structure is command [flags] subcommand [subflags] [argument] ... There's a class variable GlobalFlags which specifies the global flags options. Subcommands are defined by defining methods named do_. Flags for the subcommand are defined by defining class or instance variables named flags_. If there's no command, method default() is called. The __doc__ strings for the do_ methods are used for the usage message, printed after the general usage message which is the class variable UsageMessage. The class variable PostUsageMessage is printed after all the do_ methods' __doc__ strings. The method's return value can be a suggested exit status. [XXX Need to rewrite this to clarify it.] Common usage is to derive a class, instantiate it, and then call its run() method; by default this takes its arguments from sys.argv[1:]. s;usage: (name)s [flags] subcommand [subflags] [argument] ...tcCsdS(s&Constructor, present for completeness.N((tself((s(/usr/lib64/python2.7/Demo/pdist/cmdfw.pyt__init__#sc Csddl}ddl}|dkr4|jd}ny|j||j\}}Wn |jk ru}|j|SX|j||s|j|j S|d}d|}d|}yt ||} Wn"t k r|jd|fSXyt ||} Wnt k rd} nXy |j|d| \}}Wn.|jk rp}|jd |t |SX|j| ||SdS( s3Process flags, subcommand and options, then run it.iNiitdo_tflags_scommand %r unknownRssubcommand %s: ( tgetopttsystNonetargvt GlobalFlagsterrortusagetoptionstreadytdefaulttgetattrtAttributeErrortstr( RtargsRRtoptstmsgtcmdtmnametfnametmethodtflags((s(/usr/lib64/python2.7/Demo/pdist/cmdfw.pytrun's:            cCsR|rNddGHdGHx+|D]#\}}dG|GdGt|GHqWddGHndS(sWProcess the options retrieved by getopt. Override this if you have any options.t-i(sOptions:toptiontvalueN(trepr(RRtota((s(/usr/lib64/python2.7/Demo/pdist/cmdfw.pyR Gs  cCsdS(s*Called just before calling the subcommand.N((R((s(/usr/lib64/python2.7/Demo/pdist/cmdfw.pyRQscCs%|r|GHn|ji|jjd6GHi}|j}xxut|D]g}|d dkrF|j|rqqFnyt||j}Wn d}nX|r|||su  PK%L]XB pdist/cmptree.pycnu[ ^c@sdZddlZddlmZddlZddlZddlZdZdZdZdZ dZ d Z d Z d Z ed krendS( sQCompare local and remote dictionaries and transfer differing files -- like rdist.iN(treprcCs-tj}td|}|r>tj|tj}ntdd}d}d}d}dGHtd|}|r|}n||f}tj}tj}tj||} t || || j |j tj} | |} t | d \} } | Gd Gt | Gd GHtd dS( Ns chdir [%s] thosts voorn.cwi.nliitsMode should be a string of characters, indicating what to do with differences. r - read different files to local file system w - write different files to remote file system c - create new files, either remote or local d - delete disappearing files, either remote or local s mode [%s] i<s minutes andtsecondss[Return to exit] ( tostgetcwdt raw_inputtchdirtaskttimetFSProxyt FSProxyLocalt FSProxyClienttcomparet_closetdivmodtround(tpwdtsRtporttverbosetmodetaddresstt1tlocaltremotett2tdttminstsecs((s*/usr/lib64/python2.7/Demo/pdist/cmptree.pytmain s2          cCs td||f}|p|S(Ns%s [%s] (R(tprompttdefaultR((s*/usr/lib64/python2.7/Demo/pdist/cmptree.pyR)scCs3td|t|f}|r/tj|S|S(Ns%s [%s] (Rtstrtstringtatoi(RR R((s*/usr/lib64/python2.7/Demo/pdist/cmptree.pytaskint-s cCsHdGttjGH|jd}|jd}|jdGHi}x$|jD]\}}|||s       P  &  PK%L]GT[DDpdist/security.pynu[class Security: def __init__(self): import os env = os.environ if env.has_key('PYTHON_KEYFILE'): keyfile = env['PYTHON_KEYFILE'] else: keyfile = '.python_keyfile' if env.has_key('HOME'): keyfile = os.path.join(env['HOME'], keyfile) if not os.path.exists(keyfile): import sys for dir in sys.path: kf = os.path.join(dir, keyfile) if os.path.exists(kf): keyfile = kf break try: self._key = eval(open(keyfile).readline()) except IOError: raise IOError, "python keyfile %s: cannot open" % keyfile def _generate_challenge(self): import random return random.randint(100, 100000) def _compare_challenge_response(self, challenge, response): return self._encode_challenge(challenge) == response def _encode_challenge(self, challenge): p, m = self._key return pow(long(challenge), p, m) PK%L]Zr`` pdist/mac.pynu[import sys import string import rcvs def main(): while 1: try: line = raw_input('$ ') except EOFError: break words = string.split(line) if not words: continue if words[0] != 'rcvs': words.insert(0, 'rcvs') sys.argv = words rcvs.main() main() PK%L]Op!p!pdist/cvslock.pycnu[ ^c@sdZddlZddlZddlZddlZdZdZdZdZdZ ddd YZ d e fd YZ d dd YZ dZ de fdYZde fdYZedZdZedkrendS(sCVS locking algorithm. CVS locking strategy ==================== As reverse engineered from the CVS 1.3 sources (file lock.c): - Locking is done on a per repository basis (but a process can hold write locks for multiple directories); all lock files are placed in the repository and have names beginning with "#cvs.". - Before even attempting to lock, a file "#cvs.tfl." is created (and removed again), to test that we can write the repository. [The algorithm can still be fooled (1) if the repository's mode is changed while attempting to lock; (2) if this file exists and is writable but the directory is not.] - While creating the actual read/write lock files (which may exist for a long time), a "meta-lock" is held. The meta-lock is a directory named "#cvs.lock" in the repository. The meta-lock is also held while a write lock is held. - To set a read lock: - acquire the meta-lock - create the file "#cvs.rfl." - release the meta-lock - To set a write lock: - acquire the meta-lock - check that there are no files called "#cvs.rfl.*" - if there are, release the meta-lock, sleep, try again - create the file "#cvs.wfl." - To release a write lock: - remove the file "#cvs.wfl." - rmdir the meta-lock - To release a read lock: - remove the file "#cvs.rfl." Additional notes ---------------- - A process should read-lock at most one repository at a time. - A process may write-lock as many repositories as it wishes (to avoid deadlocks, I presume it should always lock them top-down in the directory hierarchy). - A process should make sure it removes all its lock files and directories when it crashes. - Limitation: one user id should not be committing files into the same repository at the same time. Turn this into Python code -------------------------- rl = ReadLock(repository, waittime) wl = WriteLock(repository, waittime) list = MultipleWriteLock([repository1, repository2, ...], waittime) iNi is#cvs.lcks #cvs.rfl.s #cvs.wfl.tErrorcBs#eZdZdZdZRS(cCs ||_dS(N(tmsg(tselfR((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyt__init__`scCs t|jS(N(treprR(R((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyt__repr__cscCs t|jS(N(tstrR(R((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyt__str__fs(t__name__t __module__RRR(((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyR^s  tLockedcBseZRS((RR (((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyR jstLockcBsVeZdedZdZdZdZdZdZdZ dZ RS( t.cCsx||_||_d|_d|_ttj}|jt |_ |jt ||_ |jt ||_dS(N(t repositorytdelaytNonetlockdirtlockfileRtostgetpidtjointCVSLCKtcvslcktCVSRFLtcvsrfltCVSWFLtcvswfl(RR Rtpid((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyRps    cCsdGH|jdS(Nt__del__(tunlock(R((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyRzscCsxy'|j|_tj|jddSWqtjk r}d|_|dtkrytj|j}Wntjk rqnX|j|qnt d|j |fqXqWdS(Niisfailed to lock %s: %s( RRRtmkdirterrorRtEEXISTtstattsleepRR (RRtst((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyt setlockdir~s    cCs|j|jdS(N(t unlockfilet unlockdir(R((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyRs cCsP|jrLdG|jGHytj|jWntjk r?nXd|_ndS(Ntunlink(RRR'RR(R((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyR%s  cCsP|jrLdG|jGHytj|jWntjk r?nXd|_ndS(Ntrmdir(RRR(RR(R((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyR&s  cCst||j|jdS(N(R"R R(RR#((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyR"scCstjj|j|S(N(RtpathRR (Rtname((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyRs( RR tDELAYRRR$RR%R&R"R(((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyR ns    cCs|dkrt|n|tj}ytj|}|d}Wntk rbd|}nXdtjtjdd!Gd|G|GHtj|dS(Nisuid %ds[%s]i isWaiting for %s's lock in( R R!tST_UIDtpwdtgetpwuidtKeyErrorttimetctimeR"(R#R Rtuidtpwenttuser((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyR"s    tReadLockcBseZedZRS(cCsztj|||d}z<|j|j|_t|jd}|jd}Wd|sk|jn|jXdS(Nitwi( R RR$RRtopentcloseR%R&(RR Rtoktfp((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyRs     (RR R+R(((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyR5st WriteLockcBseZedZdZRS(cCs}tj||||jx1|j}|s6Pn|j|j|q W|j|_t|jd}|j dS(NR6( R RR$t readers_existR&R"RRR7R8(RR RR2R:((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyRs    cCswtt}xdtj|jD]P}|| tkrytj|j|}Wntjk rjqnX|SqWdS(N( tlenRRtlistdirR R!RRR(RtnR*R#((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyR<s (RR R+RR<(((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyR;s cCsjxcg}xC|D]:}y|jt|dWqtk rI}~PqXqWPt|j||qWtS(Ni(tappendR;R R"Rtlist(t repositoriesRtlockstrtinstance((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pytMultipleWriteLocks  cCsddl}|jdr)|jd}nd}d}d}zDdGHt|}dGH|jdGHt|}dGH|jWddgGHd|_dgGH|r|jndgGH|r|jnd gGHd}d gGHd}d gGHXdS( NiiR sattempting write lock ...sgot it.sattempting read lock ...iiiii(tsystargvRR;RR5t exc_traceback(RGR trltwl((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pyttests8        t__main__(((t__doc__RR0R!R-R+R RRRRR R R"R5R;RFRLR(((s*/usr/lib64/python2.7/Demo/pdist/cvslock.pytGs&     ?   ! PK%L]Mi$11pdist/FSProxy.pycnu[ ^c@sdZddlZddlZddlZddlZddlZddlTddlZddlZdZej ej fZ dd dYZ de ej fdYZd ejfd YZd Zed krendS(sFile System Proxy. Provide an OS-neutral view on a file system, locally or remotely. The functionality is geared towards implementing some sort of rdist-like utility between a Mac and a UNIX system. The module defines three classes: FSProxyLocal -- used for local access FSProxyServer -- used on the server side of remote access FSProxyClient -- used on the client side of remote access The remote classes are instantiated with an IP address and an optional verbosity flag. iN(t*it FSProxyLocalcBseZdZdZdZdZdZdZdZdZ dZ d Z d Z d+d Zd+d Zd+d Zd+dZdZdZdZdZdZdZdZdZdZdZd+dZd+dZd+dZd+dZd+dZ dZ!d+dZ"d+d Z#d+d!Z$d+d"Z%d+d#Z&d$d%d&Z'd'Z(d$d(Z)d)Z*d*Z+RS(,cCs#g|_dg|j|_dS(Ns*.pyc(t _dirstackt _readignoret_ignore(tself((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyt__init__!s cCsx|jr|jqWdS(N(Rtback(R((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyt_close%s cCs|jd}yt|}WnEtk rf|jd}yt|}Wqgtk rbgSXnXg}xD|j}|sPn|ddkr|d }n|j|qpW|j|S(Ntignoressynctree.ignorefilesis (t_hidetopentIOErrortreadlinetappendtclose(RtfiletfR tline((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyR)s&      cCs|ddkS(Nit.((Rtname((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyt_hidden<scCsd|S(Ns.%s((RR((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyR ?scCst|tkrdS|ddkr*dS|tkr:dS|j|rMdStjj|\}}|sr| rvdStjj|rdSdt|dj dkrdSx'|j D]}t j ||rdSqWdS(Niit~strbii( tlent maxnamelent skipnamesRtostpathtsplittislinkR treadRtfnmatch(RRtheadttailtign((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pytvisibleBs&  cCs,|j|s(tjdt|ndS(Nsprotected name %s(R$Rterrortrepr(RR((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pytcheckOscCs<|j|tjj|s8tjdt|ndS(Nsnot a plain file %s(R'RRtisfileR%R&(RR((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyt checkfileSs cCs tjS(N(Rtgetcwd(R((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pytpwdXscCsY|j|tj|jf}tj||jj||j|j|_dS(N(R'RR*RtchdirRRR(RRtsave((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pytcd[s   cCsO|jstjdn|jd\}}tj||jd=||_dS(Nsempty directory stacki(RRR%R,R(RtdirR ((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyRbs    cCsD|r$|d}t||}nt|j|}|j|S(NcSstj||S(N(R (Rtpat((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pytkeepls(tfilterR$tsort(RtfilesR0R1((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyt_filterjs   cCs"tjtj}|j||S(N(RtlistdirtcurdirR5(RR0R4((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pytlistsscCs7tjtj}ttjj|}|j||S(N(RR6R7R2RR(R5(RR0R4((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyt listfileswscCs7tjtj}ttjj|}|j||S(N(RR6R7R2RtisdirR5(RR0R4((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyt listsubdirs|scCs|j|otjj|S(N(R$RRtexists(RR((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyR<scCs|j|otjj|S(N(R$RRR:(RR((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyR:scCs|j|otjj|S(N(R$RRR(RR((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyRscCs|j|otjj|S(N(R$RRR((RR((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyR(scCsb|j|d}t|}tj}x*|j|}|sGPn|j|q.W|jS(Niii (R)R tmd5tnewRtupdatetdigest(RRt BUFFERSIZERtsumtbuffer((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyRBs   cCs|j|tj|tS(N(R)RtstattST_SIZE(RR((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pytsizes cCs'|j|tjtj|tS(N(R)ttimet localtimeRRDtST_MTIME(RR((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pytmtimes cCsF|j|tj|t}tjtj|t}||fS(N(R)RRDRERGRHRI(RRRFRJ((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyRDs cCsK|j|}tj|t}tjtj|t}|||fS(N(RBRRDRERGRHRI(RRRBRFRJ((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pytinfoscCs|dkr|j}ng}x[|D]S}y|j|||fWq(tjtfk rz|j|dfq(Xq(W|S(N(tNoneR9RRR%R (RtfunctionR8tresR((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyt_lists  cCs|j|j|S(N(RORB(RR8((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pytsumlistscCs|j|j|S(N(RORD(RR8((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pytstatlistscCs|j|j|S(N(RORJ(RR8((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyt mtimelistscCs|j|j|S(N(RORF(RR8((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pytsizelistscCs|j|j|S(N(RORK(RR8((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pytinfolistscCsg|dkr|j}ni}x?|D]7}y|||||j|jd}nd}td|f}|jdS(NiiiR\(tstringtsystargvtatoiRkt _serverloop(RuRvtporttproxy((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyttest!s   t__main__((t__doc__RlRsR=RR RDRGRR7tpardirRRRmRkRtRrR|Ri(((s*/usr/lib64/python2.7/Demo/pdist/FSProxy.pyts          PK%L]HxT3T3pdist/cvslib.pycnu[ ^c@sdZddlZddlZddlZddlZddlZeeds]de_ndddYZdddYZ d d Z d Z d Z iZ d ZdZdZdZedkrendS(s!Utilities for CVS administration.iNttimezoneitFilecBs\eZdZd dZdZdZdZd dZdZ dZ dZ RS( sRepresent a file's status. Instance variables: file -- the filename (no slashes), None if uninitialized lseen -- true if the data for the local file is up to date eseen -- true if the data from the CVS/Entries entry is up to date (this implies that the entry must be written back) rseen -- true if the data for the remote file is up to date proxy -- RCSProxy instance used to contact the server, or None Note that lseen and rseen don't necessary mean that a local or remote file *exists* -- they indicate that we've checked it. However, eseen means that this instance corresponds to an entry in the CVS/Entries file. If lseen is true: lsum -- checksum of the local file, None if no local file lctime -- ctime of the local file, None if no local file lmtime -- mtime of the local file, None if no local file If eseen is true: erev -- revision, None if this is a no revision (not '0') enew -- true if this is an uncommitted added file edeleted -- true if this is an uncommitted removed file ectime -- ctime of last local file corresponding to erev emtime -- mtime of last local file corresponding to erev extra -- 5th string from CVS/Entries file If rseen is true: rrev -- revision of head, None if non-existent rsum -- checksum of that revision, Non if non-existent If eseen and rseen are both true: esum -- checksum of revision erev, None if no revision Note cCsK|rd|krtdn||_d|_|_|_d|_dS(Nt/sno slash allowed in filei(t ValueErrortfiletlseenteseentrseentNonetproxy(tselfR((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pyt__init__9s   cCst|j|jS(N(tcmpR(R tother((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pyt__cmp__@scCsy&tj|jd\|_|_Wn+tjk rSd|_|_|_n(Xtj t |jj j |_d|_ dS(Nii(toststatRtlmtimetlctimeterrorRtlsumtmd5tnewtopentreadtdigestR(R ((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pytgetlocalCs &'cCs)tj|d}|jr:|d|jkr:tdn|d|_|d|_d|_d|_d|_|_ |jd dkrd|_|jd|_n|jdkrd|_d|_n0|d}t |d |_t |d |_ |d |_ |j r|j nd|_dS( NRisfile name mismatchiit-t0iiii(tstringt splitfieldsRRterevtedeletedtenewRtectimetemtimetunctimetextraRtgetesumR(R tlinetwordstdates((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pytgetentryLs*            cCs|r||_ny|jj|j|_Wn#tjtfk rSd|_nX|jrx|jj|j|_ n d|_ |j r|j nd|_ dS(Ni( R theadRtrrevRRtIOErrorRtsumtrsumRR&R(R R ((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pyt getremoteds      cCsa|j|jkr!|j|_n<|jrT|j|jf}|jj||_n d|_dS(N(RR,R/tesumRR R.R(R tname((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pyR&ss  cCs|js dS|jpd}|jr2d|}n|jrKd|j}n t|jdt|j}d|j|||jfS(sReturn a line suitable for inclusion in CVS/Entries. The returned line is terminated by a newline. If no entry should be written for this file, return "". tRRsInitial t s/%s/%s/%s/%s/ ( RRR R!RtgmctimeR"R#R%(R trevR)((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pytputentry|s    cCsddGHt|d}|d|jrU|dt|dt|dtn|jr|d|d |d |d t|d tn|jr|d |dt|jr|dtqndS(NRi2cSsDy|t||}Wntk r2d}nXd|G|GHdS(Nt?s%-15s:(tgetattrtAttributeError(tkeytreprR tvalue((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pytrs   RRRRRR!R R"R#R,R/R1(R<RthexifyR5RR(R R>((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pytreports$              N( t__name__t __module__t__doc__RR RRR*R0R&R7R@(((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pyR s+     tCVScBseZdZeZddddddddgZd Zd Zd Zd Z d Z ddZ dZ dZdZdZdZddZdZdZRS(sRepresent the contents of a CVS admin file (and more). Class variables: FileClass -- the class to be instantiated for entries (this should be derived from class File above) IgnoreList -- shell patterns for local files to be ignored Instance variables: entries -- a dictionary containing File instances keyed by their file name proxy -- an RCSProxy instance, or None s.*s@*s,*s*~s*.os*.as*.sos*.pyccCsi|_d|_dS(N(tentriesRR (R ((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pyR s cCsC||jkrdS||_x |jjD]}d|_q,WdS(Ni(R REtvaluesR(R R te((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pytsetproxys  cCsli|_|jd}xC|j}|s1Pn|j}|j|||j|jcCs>tjjd|}d|kr1|j|nt||S(NRDR>(RRcRdtbackupR(R Rtmode((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pyRJs cCs[tjj|rW|d}ytj|Wntjk rCnXtj||ndS(Nt~(RRctisfiletunlinkRtrename(R Rtbfile((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pyRgs cCsDtjj|rtSx'|jD]}tj||r tSq WtS(N(RRctisdirtTruet IgnoreListtfnmatchtFalse(R Rtpat((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pyRV#s N(RARBRCRRLRpR RHRORRR\RR_R@RSRFRbRfRJRgRV(((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pyRDs"           s%02xicCs'|dkrdStttt|S(sDReturn a hex representation of a 16-byte string (e.g. an MD5 digest)RN(Rt hexify_formatttupleR`tord(R.((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pyR?-s cCsd|dkrdSd}xGtdt|dD]-}|ttj|||d!d}q/W|S(s*Return the original from a hexified stringRR3iiiN(RtrangetlentchrRtatoi(thexsumR.ti((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pytunhexify3s  +c Cs|dkrdStsndddddddd d d d d g }d}x%|D]}|d}|t|s    + cCs&|dkrdStjtj|S(NR(RRtasctimetgmtime(tt((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pyR5Os cCsttj}tj|}tj|}dG|G|GHdGtjGHdGtj|GHt|}dG|GHtj|}dG|GHtj|GHdS(NtGMTRtlocals unctime()s->(tintRRRRtctimeR$(tnowRtattutgu((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pyt test_unctimeSs     cCsPt}|j|jddl}|j}|j||jdS(Ni(RDROR\t rcsclientt openrcsclientR_R@(txRR ((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pyttest`s      t__main__(((RCRRRRRqthasattrRRRDRtR?R}RR$R5RRRA(((s)/usr/lib64/python2.7/Demo/pdist/cvslib.pyts&      ~      PK%L]Kouu pdist/rcvsnuȯ#! /usr/bin/python2.7 import addpack addpack.addpack('/home/guido/src/python/Demo/pdist') import rcvs rcvs.main() PK%L])SSpdist/server.pyonu[ ^c@sdZddlZddlZddlZddlmZddlmZdZdd dYZddlm Z d ee fd YZ dS( sRPC Server module.iN(tfnmatch(trepritServercBseZdZedZdZdZdZdZdZ ddd d gZ d Z d Z d Z ddZRS(sDRPC Server class. Derive a class to implement a particular service.cCst|tdkr'd|f}n||_||_d|_tjtjtj|_|jj||jj dd|_ dS(Niti( ttypet_addresst_verbosetNonet_sockettsockettAF_INETt SOCK_STREAMtbindtlistent _listening(tselftaddresstverbose((s)/usr/lib64/python2.7/Demo/pdist/server.pyt__init__s   cCs ||_dS(N(R(RR((s)/usr/lib64/python2.7/Demo/pdist/server.pyt _setverbosescCs|jdS(N(t_close(R((s)/usr/lib64/python2.7/Demo/pdist/server.pyt__del__ scCs/d|_|jr"|jjnd|_dS(Ni(RRtcloseR(R((s)/usr/lib64/python2.7/Demo/pdist/server.pyR#s  cCsx|jr|jqWdS(N(Rt_serve(R((s)/usr/lib64/python2.7/Demo/pdist/server.pyt _serverloop)s cCs|jrdGHn|jj\}}|jrAdt|GHn|j||spdt|GH|jdS|jd}|jd}d}x=|r|j|jdkrdGHn|j||}qWdS(NsWait for connection ...sAccepted connection from %ss*** Connection from %s refusedtrtwisWait for next request ...( RRtacceptRt_verifyRtmakefiletflusht _dorequest(RtconnRtrftwftok((s)/usr/lib64/python2.7/Demo/pdist/server.pyR-s"     s 192.16.201.*s 192.16.197.*s 132.151.1.*s 129.6.64.*cCs7|\}}x$|jD]}t||rdSqWdS(Nii(t_validR(RR Rthosttporttpat((s)/usr/lib64/python2.7/Demo/pdist/server.pyR?s  c Csvtj|}y|j}Wntk r3dSX|jdkrUdt|GHny|\}}}d|krd|j|||f}nM|ddkrtdt|n't ||} dt | ||f}Wnt j t j |f}nX|dkr5|d d kr5|jdkr1dGHndS|jdkrVd t|GHntj|} | j|dS( NiisGot request: %st.t_sillegal method name %sisSuppress replysSend reply: %s(NN(tpicklet UnpicklertloadtEOFErrorRRRt_specialt NameErrortgetattrtapplytsystexc_typet exc_valuetPicklertdump( RR!R"trptrequestt methodnametargstidtreplytmethodtwp((s)/usr/lib64/python2.7/Demo/pdist/server.pyREs4   cCsQ|dkr:t|ds3t|j|_n|jStdt|dS(Ns.methodst_methodss#unrecognized special method name %s(thasattrttuplet _listmethodsR?R/R(RR9R:((s)/usr/lib64/python2.7/Demo/pdist/server.pyR._s  cCs|s|j}n|jj}td|}|jxE|jD]:}|j|}t|d|}||t|)qGW|S(NcSs|ddkS(NiR)((tx((s)/usr/lib64/python2.7/Demo/pdist/server.pytiRcSs ||kS(N((RCtnames((s)/usr/lib64/python2.7/Demo/pdist/server.pyRDmR(t __class__t__dict__tkeystfiltertsortt __bases__RBtlen(RtclREtbaset basenames((s)/usr/lib64/python2.7/Demo/pdist/server.pyRBfs  N(t__name__t __module__t__doc__tVERBOSERRRRRRR$RRR.RRB(((s)/usr/lib64/python2.7/Demo/pdist/server.pyRs        (tSecurityt SecureServercBseZdZdZRS(cGs(ttj|f|tj|dS(N(R1RRRT(RR:((s)/usr/lib64/python2.7/Demo/pdist/server.pyRwscCsddl}|j}|jd|d}xEd|krvt|dkrv|jd}|siPn||}q2Wy|j|j|}Wn6|jk r|jdkrdGt |GHndSX|j ||s|jdkrdGt |GHndS|jd krd GHnd S( Nis%d Rs idisInvalid response syntaxsInvalid response valueis&Response matches challenge. Go ahead!( tstringt_generate_challengetsendRLtrecvtatoltstript atol_errorRRt_compare_challenge_response(RR RRVt challengetresponsetdata((s)/usr/lib64/python2.7/Demo/pdist/server.pyR{s,  !(RPRQRR(((s)/usr/lib64/python2.7/Demo/pdist/server.pyRUus (( RRR2R R*RRRSRtsecurityRTRU(((s)/usr/lib64/python2.7/Demo/pdist/server.pyts   dPK%L]F N2 2 pdist/makechangelog.pyonu[ Afc@sdZddlZddlZddlZddlZddlZdZejddZidd6dd 6d d 6Z d Z ejd Z dZ dZ edkrendS(s<Turn a pile of RCS log output into ChangeLog file entries. iNc Cstjd}tj|d\}}d}x)|D]!\}}tdkr2|}q2q2Wtj}g}xft|}|sPng}x*t||} | sPn|j| qW|ri||t|)qiqiW|j |j x|D]} t | |qWdS(Nisp:ts-p( tsystargvtgetopttptstdint getnextfilet getnextrevtappendtlentsorttreverset formatrev( targstoptstprefixtotatftallrevstfiletrevstrev((s0/usr/lib64/python2.7/Demo/pdist/makechangelog.pytmain s0       s"^date: ([0-9]+)/([0-9]+)/([0-9]+) s-([0-9]+):([0-9]+):([0-9]+); author: ([^ ;]+)s+Guido van Rossum tguidosJack Jansen tjacks!Sjoerd Mullender tsjoerdcCsh|\}}}}tj|dkrdtjdddddd}tjd}tj|rpt|}nttj|dddg}|dtj |ds&            PK%L]5tVV pdist/mac.pyonu[ ^c@s8ddlZddlZddlZdZedS(iNcCsxzytd}Wntk r'PnXtj|}|sCqn|ddkrf|jddn|t_tjqWdS(Ns$ itrcvs( t raw_inputtEOFErrortstringtsplittinserttsystargvRtmain(tlinetwords((s&/usr/lib64/python2.7/Demo/pdist/mac.pyRs  (RRRR(((s&/usr/lib64/python2.7/Demo/pdist/mac.pyts    PK%L]@GFpdist/security.pycnu[ ^c@sdddYZdS(tSecuritycBs,eZdZdZdZdZRS(cCs ddl}|j}|jdr1|d}nd}|jdrb|jj|d|}n|jj|sddl}xE|jD]7}|jj||}|jj|r|}PqqWnytt|j |_ Wnt k rt d|nXdS(NitPYTHON_KEYFILEs.python_keyfiletHOMEspython keyfile %s: cannot open( tostenvironthas_keytpathtjointexiststsystevaltopentreadlinet_keytIOError(tselfRtenvtkeyfileR tdirtkf((s+/usr/lib64/python2.7/Demo/pdist/security.pyt__init__s$      cCsddl}|jddS(Niidi(trandomtrandint(RR((s+/usr/lib64/python2.7/Demo/pdist/security.pyt_generate_challenges cCs|j||kS(N(t_encode_challenge(Rt challengetresponse((s+/usr/lib64/python2.7/Demo/pdist/security.pyt_compare_challenge_responsescCs%|j\}}tt|||S(N(R tpowtlong(RRtptm((s+/usr/lib64/python2.7/Demo/pdist/security.pyRs(t__name__t __module__RRRR(((s+/usr/lib64/python2.7/Demo/pdist/security.pyRs   N((R(((s+/usr/lib64/python2.7/Demo/pdist/security.pyttPK%L])SSpdist/server.pycnu[ ^c@sdZddlZddlZddlZddlmZddlmZdZdd dYZddlm Z d ee fd YZ dS( sRPC Server module.iN(tfnmatch(trepritServercBseZdZedZdZdZdZdZdZ ddd d gZ d Z d Z d Z ddZRS(sDRPC Server class. Derive a class to implement a particular service.cCst|tdkr'd|f}n||_||_d|_tjtjtj|_|jj||jj dd|_ dS(Niti( ttypet_addresst_verbosetNonet_sockettsockettAF_INETt SOCK_STREAMtbindtlistent _listening(tselftaddresstverbose((s)/usr/lib64/python2.7/Demo/pdist/server.pyt__init__s   cCs ||_dS(N(R(RR((s)/usr/lib64/python2.7/Demo/pdist/server.pyt _setverbosescCs|jdS(N(t_close(R((s)/usr/lib64/python2.7/Demo/pdist/server.pyt__del__ scCs/d|_|jr"|jjnd|_dS(Ni(RRtcloseR(R((s)/usr/lib64/python2.7/Demo/pdist/server.pyR#s  cCsx|jr|jqWdS(N(Rt_serve(R((s)/usr/lib64/python2.7/Demo/pdist/server.pyt _serverloop)s cCs|jrdGHn|jj\}}|jrAdt|GHn|j||spdt|GH|jdS|jd}|jd}d}x=|r|j|jdkrdGHn|j||}qWdS(NsWait for connection ...sAccepted connection from %ss*** Connection from %s refusedtrtwisWait for next request ...( RRtacceptRt_verifyRtmakefiletflusht _dorequest(RtconnRtrftwftok((s)/usr/lib64/python2.7/Demo/pdist/server.pyR-s"     s 192.16.201.*s 192.16.197.*s 132.151.1.*s 129.6.64.*cCs7|\}}x$|jD]}t||rdSqWdS(Nii(t_validR(RR Rthosttporttpat((s)/usr/lib64/python2.7/Demo/pdist/server.pyR?s  c Csvtj|}y|j}Wntk r3dSX|jdkrUdt|GHny|\}}}d|krd|j|||f}nM|ddkrtdt|n't ||} dt | ||f}Wnt j t j |f}nX|dkr5|d d kr5|jdkr1dGHndS|jdkrVd t|GHntj|} | j|dS( NiisGot request: %st.t_sillegal method name %sisSuppress replysSend reply: %s(NN(tpicklet UnpicklertloadtEOFErrorRRRt_specialt NameErrortgetattrtapplytsystexc_typet exc_valuetPicklertdump( RR!R"trptrequestt methodnametargstidtreplytmethodtwp((s)/usr/lib64/python2.7/Demo/pdist/server.pyREs4   cCsQ|dkr:t|ds3t|j|_n|jStdt|dS(Ns.methodst_methodss#unrecognized special method name %s(thasattrttuplet _listmethodsR?R/R(RR9R:((s)/usr/lib64/python2.7/Demo/pdist/server.pyR._s  cCs|s|j}n|jj}td|}|jxE|jD]:}|j|}t|d|}||t|)qGW|S(NcSs|ddkS(NiR)((tx((s)/usr/lib64/python2.7/Demo/pdist/server.pytiRcSs ||kS(N((RCtnames((s)/usr/lib64/python2.7/Demo/pdist/server.pyRDmR(t __class__t__dict__tkeystfiltertsortt __bases__RBtlen(RtclREtbaset basenames((s)/usr/lib64/python2.7/Demo/pdist/server.pyRBfs  N(t__name__t __module__t__doc__tVERBOSERRRRRRR$RRR.RRB(((s)/usr/lib64/python2.7/Demo/pdist/server.pyRs        (tSecurityt SecureServercBseZdZdZRS(cGs(ttj|f|tj|dS(N(R1RRRT(RR:((s)/usr/lib64/python2.7/Demo/pdist/server.pyRwscCsddl}|j}|jd|d}xEd|krvt|dkrv|jd}|siPn||}q2Wy|j|j|}Wn6|jk r|jdkrdGt |GHndSX|j ||s|jdkrdGt |GHndS|jd krd GHnd S( Nis%d Rs idisInvalid response syntaxsInvalid response valueis&Response matches challenge. Go ahead!( tstringt_generate_challengetsendRLtrecvtatoltstript atol_errorRRt_compare_challenge_response(RR RRVt challengetresponsetdata((s)/usr/lib64/python2.7/Demo/pdist/server.pyR{s,  !(RPRQRR(((s)/usr/lib64/python2.7/Demo/pdist/server.pyRUus (( RRR2R R*RRRSRtsecurityRTRU(((s)/usr/lib64/python2.7/Demo/pdist/server.pyts   dPK%L]XB pdist/cmptree.pyonu[ ^c@sdZddlZddlmZddlZddlZddlZdZdZdZdZ dZ d Z d Z d Z ed krendS( sQCompare local and remote dictionaries and transfer differing files -- like rdist.iN(treprcCs-tj}td|}|r>tj|tj}ntdd}d}d}d}dGHtd|}|r|}n||f}tj}tj}tj||} t || || j |j tj} | |} t | d \} } | Gd Gt | Gd GHtd dS( Ns chdir [%s] thosts voorn.cwi.nliitsMode should be a string of characters, indicating what to do with differences. r - read different files to local file system w - write different files to remote file system c - create new files, either remote or local d - delete disappearing files, either remote or local s mode [%s] i<s minutes andtsecondss[Return to exit] ( tostgetcwdt raw_inputtchdirtaskttimetFSProxyt FSProxyLocalt FSProxyClienttcomparet_closetdivmodtround(tpwdtsRtporttverbosetmodetaddresstt1tlocaltremotett2tdttminstsecs((s*/usr/lib64/python2.7/Demo/pdist/cmptree.pytmain s2          cCs td||f}|p|S(Ns%s [%s] (R(tprompttdefaultR((s*/usr/lib64/python2.7/Demo/pdist/cmptree.pyR)scCs3td|t|f}|r/tj|S|S(Ns%s [%s] (Rtstrtstringtatoi(RR R((s*/usr/lib64/python2.7/Demo/pdist/cmptree.pytaskint-s cCsHdGttjGH|jd}|jd}|jdGHi}x$|jD]\}}|||s       P  &  PK%L]#44pdist/rcsclient.pyonu[ ^c@skdZddlZddlZdZdZdZdZddlZdejfdYZ gd Z dS( sCustomize this file to change the default client etc. (In general, it is probably be better to make local operation the default and to require something like an RCSSERVER environment variable to enable remote operation.) iNs voorn.cwi.nliiitRCSProxyClientcBseZejdZRS(cCstjj|||dS(N(tclientt SecureClientt__init__(tselftaddresstverbose((s,/usr/lib64/python2.7/Demo/pdist/rcsclient.pyRs(t__name__t __module__RtVERBOSER(((s,/usr/lib64/python2.7/Demo/pdist/rcsclient.pyRsc Csddl}t}t}t}t}d}x|D]\}}|dkr|}d|krtj|d} || || d}} | rtj| }qqn|dkrtj|}n|dkr|}n|dkr|d}n|d krd }n|d kr1d}q1q1W|r?ddl}|j } n||f} t | |} |sy%t t j jd d j}Wntk rqX|ddkr|d }qn|r| j|n| S(sEopen an RCSProxy client based on a list of options returned by getoptiNs-ht:is-ps-ds-vs-qis-LtCVSt Repositorys (tRCSProxytHOSTtPORTR tLOCALtNonetstringtfindtatoit RCSProxyLocalRtopentostpathtjointreadlinetIOErrortcd( toptsR thosttportRtlocalt directorytotatitptxR((s,/usr/lib64/python2.7/Demo/pdist/rcsclient.pyt openrcsclientsN              % ( t__doc__RRRRR RRRRR'(((s,/usr/lib64/python2.7/Demo/pdist/rcsclient.pyts   PK%L]@GFpdist/security.pyonu[ ^c@sdddYZdS(tSecuritycBs,eZdZdZdZdZRS(cCs ddl}|j}|jdr1|d}nd}|jdrb|jj|d|}n|jj|sddl}xE|jD]7}|jj||}|jj|r|}PqqWnytt|j |_ Wnt k rt d|nXdS(NitPYTHON_KEYFILEs.python_keyfiletHOMEspython keyfile %s: cannot open( tostenvironthas_keytpathtjointexiststsystevaltopentreadlinet_keytIOError(tselfRtenvtkeyfileR tdirtkf((s+/usr/lib64/python2.7/Demo/pdist/security.pyt__init__s$      cCsddl}|jddS(Niidi(trandomtrandint(RR((s+/usr/lib64/python2.7/Demo/pdist/security.pyt_generate_challenges cCs|j||kS(N(t_encode_challenge(Rt challengetresponse((s+/usr/lib64/python2.7/Demo/pdist/security.pyt_compare_challenge_responsescCs%|j\}}tt|||S(N(R tpowtlong(RRtptm((s+/usr/lib64/python2.7/Demo/pdist/security.pyRs(t__name__t __module__RRRR(((s+/usr/lib64/python2.7/Demo/pdist/security.pyRs   N((R(((s+/usr/lib64/python2.7/Demo/pdist/security.pyttPK%L]#)--pdist/rcslib.pycnu[ ^c@sYdZddlZddlZddlZddlZddlZdddYZdS(sRCS interface module. Defines the class RCS, which represents a directory with rcs version files and (possibly) corresponding work files. iNtRCScBseZdZejejdZdZdZddZ dZ dZ dZ d Z d dd Zddd Zdd ZdZdZdZdZdZdddZdZdZdZddZdZdZRS(s7RCS interface class (local filesystem version). An instance of this class represents a directory with rcs version files and (possible) corresponding work files. Methods provide access to most rcs operations such as checkin/checkout, access to the rcs metadata (revisions, logs, branches etc.) as well as some filesystem operations such as listing all rcs version files. XXX BUGS / PROBLEMS - The instance always represents the current directory so it's not very useful to have more than one instance around simultaneously s-_=+cCsdS(s Constructor.N((tself((s)/usr/lib64/python2.7/Demo/pdist/rcslib.pyt__init__&scCsdS(s Destructor.N((R((s)/usr/lib64/python2.7/Demo/pdist/rcslib.pyt__del__*stcCsi|j|d|}|j}|j|}|rH|d|}n|ddkre|d }n|S(smReturn the full log text for NAME_REV as a string. Optional OTHERFLAGS are passed to rlog. srlog s%s: %sis (t_opentreadt _closepipe(Rtname_revt otherflagstftdatatstatus((s)/usr/lib64/python2.7/Demo/pdist/rcslib.pytlog0s  cCs|j|}|dS(s%Return the head revision for NAME_REVthead(tinfo(RRtdict((s)/usr/lib64/python2.7/Demo/pdist/rcslib.pyR?sc Cs|j|d}i}x}|j}|s1Pn|ddkrGqntj|d}|dkr|| tj||d}}|||" if None); or the file description if this is a new file. The optional OTHERFLAGS argument is passed to ci without interpretation. Any output from ci goes to directly to stdout. sis s-usci %s%s -t%s %s %ss([\"$`])s\\\1sci %s%s -m"%s" %s %s( t _unmangletisvalidttempfiletNamedTemporaryFiletwritetflushRtretsubR( RRtmessageR RRtnewR#R R((s)/usr/lib64/python2.7/Demo/pdist/rcslib.pytcheckins"      cCstjtj}t|j|}tjjdrdtjd}t|j|}||}nt|j|}|j ||S(s=Return a list of all version files matching optional PATTERN.R( tostlistdirtcurdirtfiltert_isrcstpathtisdirtmaptrealnamet_filter(Rtpattfilestfiles2((s)/usr/lib64/python2.7/Demo/pdist/rcslib.pyt listfiless cCs@|j|}tjj|p?tjjtjjd|S(s0Test whether NAME has a version file associated.R(trcsnameR0R5tisfiletjoin(RRtnamev((s)/usr/lib64/python2.7/Demo/pdist/rcslib.pyR&scCs|j|r|}n |d}tjj|r8|Stjjdtjj|}tjj|ro|Stjjdrtjjd|S|SdS(sReturn the pathname of the version file for NAME. The argument can be a work file name or a version file name. If the version file does not exist, the name of the version file that would be created by "ci" is returned. s,vRN(R4R0R5R?R@tbasenameR6(RRRA((s)/usr/lib64/python2.7/Demo/pdist/rcslib.pyR>s  !cCsN|j|r|d }n|}tjj|r8|Stjj|}|S(sReturn the pathname of the work file for NAME. The argument can be a work file name or a version file name. If the work file does not exist, the name of the work file that would be created by "co" is returned. i(R4R0R5R?RB(RRAR((s)/usr/lib64/python2.7/Demo/pdist/rcslib.pyR8s cCs|j|d}|j}|j|}|r?t|n|sIdS|ddkrf|d }n|j||j|kS(sTest whether FILE (which must have a version file) is locked. XXX This does not tell you which revision number is locked and ignores any revision you may pass in (by virtue of using rlog -L -R). s rlog -L -Ris N(RRRRtNoneR8(RRR RR ((s)/usr/lib64/python2.7/Demo/pdist/rcslib.pytislockeds   cCsD|j|\}}|j|s:tjd|fn||fS(s}Normalize NAME_REV into a (NAME, REV) tuple. Raise an exception if there is no corresponding version file. snot an rcs file %r(R%R&R0terror(RRRR((s)/usr/lib64/python2.7/Demo/pdist/rcslib.pyRssco -ps-rcCsV|j|\}}|j|}|r?|d||}ntjd||fS(sINTERNAL: open a read pipe to NAME_REV using optional COMMAND. Optional FLAG is used to indicate the revision (default -r). Default COMMAND is "co -p". Return a file object connected by a pipe to the command's output. t s%s %r(RR>R0tpopen(RRRtrflagRRRA((s)/usr/lib64/python2.7/Demo/pdist/rcslib.pyRs cCsmt|tdkr1|df}\}}n |\}}x)|D]!}||jkrDtdqDqDW|S(sINTERNAL: Normalize NAME_REV argument to (NAME, REV) tuple. Raise an exception if NAME contains invalid characters. A NAME_REV argument is either NAME string (implying REV='') or a tuple of the form (NAME, REV). Rsbad char in rev(ttypetokcharst ValueError(RRRRtc((s)/usr/lib64/python2.7/Demo/pdist/rcslib.pyR%s   cCs|j}|sd St|d\}}|dkrAd|fS|d@}|dkrfd}|}nd}|d@r|d}n||fS( s:INTERNAL: Close PIPE and print its exit status if nonzero.iitexititstoppedtkilledis (coredump)N(tcloseRCtdivmod(RR tststdetailtreasontsignaltcode((s)/usr/lib64/python2.7/Demo/pdist/rcslib.pyRs       cCs3|d}tj|}|r/td|ndS(s{INTERNAL: run COMMAND in a subshell. Standard input for the command is taken from /dev/null. Raise IOError when the exit status is not zero. Return whatever the calling method should return; normally None. A derived class may override this method and redefine it to capture stdout/stderr of the command and return it. s R8RDRRR%RRR9R]R4(((s)/usr/lib64/python2.7/Demo/pdist/rcslib.pyRs0       !          ((R`RXR0R+RR'R(((s)/usr/lib64/python2.7/Demo/pdist/rcslib.pyts      PK%L]Wsspdist/cvslock.pynu["""CVS locking algorithm. CVS locking strategy ==================== As reverse engineered from the CVS 1.3 sources (file lock.c): - Locking is done on a per repository basis (but a process can hold write locks for multiple directories); all lock files are placed in the repository and have names beginning with "#cvs.". - Before even attempting to lock, a file "#cvs.tfl." is created (and removed again), to test that we can write the repository. [The algorithm can still be fooled (1) if the repository's mode is changed while attempting to lock; (2) if this file exists and is writable but the directory is not.] - While creating the actual read/write lock files (which may exist for a long time), a "meta-lock" is held. The meta-lock is a directory named "#cvs.lock" in the repository. The meta-lock is also held while a write lock is held. - To set a read lock: - acquire the meta-lock - create the file "#cvs.rfl." - release the meta-lock - To set a write lock: - acquire the meta-lock - check that there are no files called "#cvs.rfl.*" - if there are, release the meta-lock, sleep, try again - create the file "#cvs.wfl." - To release a write lock: - remove the file "#cvs.wfl." - rmdir the meta-lock - To release a read lock: - remove the file "#cvs.rfl." Additional notes ---------------- - A process should read-lock at most one repository at a time. - A process may write-lock as many repositories as it wishes (to avoid deadlocks, I presume it should always lock them top-down in the directory hierarchy). - A process should make sure it removes all its lock files and directories when it crashes. - Limitation: one user id should not be committing files into the same repository at the same time. Turn this into Python code -------------------------- rl = ReadLock(repository, waittime) wl = WriteLock(repository, waittime) list = MultipleWriteLock([repository1, repository2, ...], waittime) """ import os import time import stat import pwd # Default wait time DELAY = 10 # XXX This should be the same on all Unix versions EEXIST = 17 # Files used for locking (must match cvs.h in the CVS sources) CVSLCK = "#cvs.lck" CVSRFL = "#cvs.rfl." CVSWFL = "#cvs.wfl." class Error: def __init__(self, msg): self.msg = msg def __repr__(self): return repr(self.msg) def __str__(self): return str(self.msg) class Locked(Error): pass class Lock: def __init__(self, repository = ".", delay = DELAY): self.repository = repository self.delay = delay self.lockdir = None self.lockfile = None pid = repr(os.getpid()) self.cvslck = self.join(CVSLCK) self.cvsrfl = self.join(CVSRFL + pid) self.cvswfl = self.join(CVSWFL + pid) def __del__(self): print "__del__" self.unlock() def setlockdir(self): while 1: try: self.lockdir = self.cvslck os.mkdir(self.cvslck, 0777) return except os.error, msg: self.lockdir = None if msg[0] == EEXIST: try: st = os.stat(self.cvslck) except os.error: continue self.sleep(st) continue raise Error("failed to lock %s: %s" % ( self.repository, msg)) def unlock(self): self.unlockfile() self.unlockdir() def unlockfile(self): if self.lockfile: print "unlink", self.lockfile try: os.unlink(self.lockfile) except os.error: pass self.lockfile = None def unlockdir(self): if self.lockdir: print "rmdir", self.lockdir try: os.rmdir(self.lockdir) except os.error: pass self.lockdir = None def sleep(self, st): sleep(st, self.repository, self.delay) def join(self, name): return os.path.join(self.repository, name) def sleep(st, repository, delay): if delay <= 0: raise Locked(st) uid = st[stat.ST_UID] try: pwent = pwd.getpwuid(uid) user = pwent[0] except KeyError: user = "uid %d" % uid print "[%s]" % time.ctime(time.time())[11:19], print "Waiting for %s's lock in" % user, repository time.sleep(delay) class ReadLock(Lock): def __init__(self, repository, delay = DELAY): Lock.__init__(self, repository, delay) ok = 0 try: self.setlockdir() self.lockfile = self.cvsrfl fp = open(self.lockfile, 'w') fp.close() ok = 1 finally: if not ok: self.unlockfile() self.unlockdir() class WriteLock(Lock): def __init__(self, repository, delay = DELAY): Lock.__init__(self, repository, delay) self.setlockdir() while 1: uid = self.readers_exist() if not uid: break self.unlockdir() self.sleep(uid) self.lockfile = self.cvswfl fp = open(self.lockfile, 'w') fp.close() def readers_exist(self): n = len(CVSRFL) for name in os.listdir(self.repository): if name[:n] == CVSRFL: try: st = os.stat(self.join(name)) except os.error: continue return st return None def MultipleWriteLock(repositories, delay = DELAY): while 1: locks = [] for r in repositories: try: locks.append(WriteLock(r, 0)) except Locked, instance: del locks break else: break sleep(instance.msg, r, delay) return list def test(): import sys if sys.argv[1:]: repository = sys.argv[1] else: repository = "." rl = None wl = None try: print "attempting write lock ..." wl = WriteLock(repository) print "got it." wl.unlock() print "attempting read lock ..." rl = ReadLock(repository) print "got it." rl.unlock() finally: print [1] sys.exc_traceback = None print [2] if rl: rl.unlock() print [3] if wl: wl.unlock() print [4] rl = None print [5] wl = None print [6] if __name__ == '__main__': test() PK%L]P] pdist/rcsbumpnuȯ#! /usr/bin/python2.7 # -*- python -*- # # guido's version, from rcsbump,v 1.2 1995/06/22 21:27:27 bwarsaw Exp # # Python script for bumping up an RCS major revision number. import sys import re import rcslib import string WITHLOCK = 1 majorrev_re = re.compile('^[0-9]+') dir = rcslib.RCS() if sys.argv[1:]: files = sys.argv[1:] else: files = dir.listfiles() for file in files: # get the major revnumber of the file headbranch = dir.info(file)['head'] majorrev_re.match(headbranch) majorrev = string.atoi(majorrev_re.group(0)) + 1 if not dir.islocked(file): dir.checkout(file, WITHLOCK) msg = "Bumping major revision number (to %d)" % majorrev dir.checkin((file, "%s.0" % majorrev), msg, "-f") PK%L]GGpdist/RCSProxy.pycnu[ Afc@sdZddlZddlZddlZddlZddlZddlZddlZdd dYZdej efdYZ de ej fdYZ d Z d Zed krendS( sRCS Proxy. Provide a simplified interface on RCS files, locally or remotely. The functionality is geared towards implementing some sort of remote CVS like utility. It is modeled after the similar module FSProxy. The module defines two classes: RCSProxyLocal -- used for local access RCSProxyServer -- used on the server side of remote access The corresponding client class, RCSProxyClient, is defined in module rcsclient. The remote classes are instantiated with an IP address and an optional verbosity flag. iNt DirSupportcBseeZdZdZdZdZdZdZd dZ dZ dZ d Z RS( cCs g|_dS(N(t _dirstack(tself((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyt__init__!scCs|jdS(N(t_close(R((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyt__del__$scCsx|jr|jqWdS(N(Rtback(R((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyR's cCs tjS(N(tostgetcwd(R((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pytpwd+scCs-tj}tj||jj|dS(N(RRtchdirRtappend(Rtnametsave((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pytcd.s  cCs@|jstjdn|jd}tj||jd=dS(Nsempty directory stacki(RRterrorR (Rtdir((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyR3s    cCs7tjtj}ttjj|}|j||S(N(Rtlistdirtcurdirtfiltertpathtisdirt_filter(Rtpattfiles((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyt listsubdirs:scCstjj|S(N(RRR(RR ((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyR?scCstj|ddS(Ni(Rtmkdir(RR ((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyRBscCstj|dS(N(Rtrmdir(RR ((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyREsN( t__name__t __module__RRRR RRtNoneRRRR(((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyRs         t RCSProxyLocalcBsheZdZdZd dZd dZdZdZd dZ d dZ d dZ RS( cCs!tjj|tj|dS(N(trcslibtRCSRR(R((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyRKscCs!tj|tjj|dS(N(RRR R!(R((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyROs cCs|j|j|S(N(t_listtsum(Rtlist((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pytsumlistSscCs|j|j|S(N(t_dictR#(RR$((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pytsumdictVscCse|j|}d}tj}x*|j|}|s=Pn|j|q$W|j||jS(Niii (t_opentmd5tnewtreadtupdatet _closepipetdigest(Rtname_revtft BUFFERSIZER#tbuffer((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyR#Ys  cCs,|j|}|j}|j||S(N(R(R+R-(RR/R0tdata((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pytgetes  cCs\|j|\}}t|d}|j||j|j|||j|dS(Ntw(t _unmangletopentwritetclosetcheckint_remove(RR/R3tmessageR trevR0((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pytputks   cCs|dkr|j}ng}x[|D]S}y|j|||fWq(tjtfk rz|j|dfq(Xq(W|S(sINTERNAL: apply FUNCTION to all files in LIST. Return a list of the results. The list defaults to all files in the directory if None. N(Rt listfilesR RRtIOError(RtfunctionR$tresR ((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyR"ss  cCsg|dkr|j}ni}x?|D]7}y||||R"R&(((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyRIs       tRCSProxyServercBs)eZejdZdZdZRS(cCs'tj|tjj|||dS(N(RRtservert SecureServer(Rtaddresstverbose((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyRs cCs!tjj|tj|dS(N(RERFRR(R((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyRscCs.tjj|x|jr)|jqWdS(N(RERFt_serveRR(R((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyRIs (RRREtVERBOSERRRI(((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyRDs cCsdddl}ddl}|jdr>|j|jd}nd}td|f}|jdS(Niiit(tstringtsystargvtatoiRDt _serverloop(RLRMtporttproxy((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyt test_servers   cCsddl}|jd s>|jdrU|jdddkrUt|jdnt}|jd}t||rt||}t|rt|t |jdGHqt |GHnd|GH|jddS(Niiit 0123456789is%s: no such attribute( RMRNRStexitRthasattrtgetattrtcallabletapplyttupletrepr(RMRRtwhattattr((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyttests 2    t__main__((t__doc__RER)RtfnmatchRLttempfileR RR!RRFRDRSR^R(((s+/usr/lib64/python2.7/Demo/pdist/RCSProxy.pyts       *O  PK%L].)S;;sockets/echosvr.pyonu[ Afc@s6ddlZddlTdZdZdZedS(iN(t*iPiicCsttjdkr1tttjd}nt}ttt}|j d|f|j d|j \}\}}dG|G|GHx*|j t }|sPn|j|qWdS(Nits connected by(tlentsystargvtinttevalt ECHO_PORTtsockettAF_INETt SOCK_STREAMtbindtlistentaccepttrecvtBUFSIZEtsend(tporttstconnt remotehostt remoteporttdata((s,/usr/lib64/python2.7/Demo/sockets/echosvr.pytmains  iW(RRRRR(((s,/usr/lib64/python2.7/Demo/sockets/echosvr.pyts   PK%L]~hD7&7&sockets/gopher.pynuȯ#! /usr/bin/python2.7 # A simple gopher client. # # Usage: gopher [ [selector] host [port] ] import string import sys import os import socket # Default selector, host and port DEF_SELECTOR = '' DEF_HOST = 'gopher.micro.umn.edu' DEF_PORT = 70 # Recognized file types T_TEXTFILE = '0' T_MENU = '1' T_CSO = '2' T_ERROR = '3' T_BINHEX = '4' T_DOS = '5' T_UUENCODE = '6' T_SEARCH = '7' T_TELNET = '8' T_BINARY = '9' T_REDUNDANT = '+' T_SOUND = 's' # Dictionary mapping types to strings typename = {'0': '', '1': '', '2': '', '3': '', \ '4': '', '5': '', '6': '', '7': '', \ '8': '', '9': '', '+': '', 's': ''} # Oft-used characters and strings CRLF = '\r\n' TAB = '\t' # Open a TCP connection to a given host and port def open_socket(host, port): if not port: port = DEF_PORT elif type(port) == type(''): port = string.atoi(port) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) return s # Send a selector to a given host and port, return a file with the reply def send_request(selector, host, port): s = open_socket(host, port) s.send(selector + CRLF) s.shutdown(1) return s.makefile('r') # Get a menu in the form of a list of entries def get_menu(selector, host, port): f = send_request(selector, host, port) list = [] while 1: line = f.readline() if not line: print '(Unexpected EOF from server)' break if line[-2:] == CRLF: line = line[:-2] elif line[-1:] in CRLF: line = line[:-1] if line == '.': break if not line: print '(Empty line from server)' continue typechar = line[0] parts = string.splitfields(line[1:], TAB) if len(parts) < 4: print '(Bad line from server: %r)' % (line,) continue if len(parts) > 4: print '(Extra info from server: %r)' % (parts[4:],) parts.insert(0, typechar) list.append(parts) f.close() return list # Get a text file as a list of lines, with trailing CRLF stripped def get_textfile(selector, host, port): list = [] get_alt_textfile(selector, host, port, list.append) return list # Get a text file and pass each line to a function, with trailing CRLF stripped def get_alt_textfile(selector, host, port, func): f = send_request(selector, host, port) while 1: line = f.readline() if not line: print '(Unexpected EOF from server)' break if line[-2:] == CRLF: line = line[:-2] elif line[-1:] in CRLF: line = line[:-1] if line == '.': break if line[:2] == '..': line = line[1:] func(line) f.close() # Get a binary file as one solid data block def get_binary(selector, host, port): f = send_request(selector, host, port) data = f.read() f.close() return data # Get a binary file and pass each block to a function def get_alt_binary(selector, host, port, func, blocksize): f = send_request(selector, host, port) while 1: data = f.read(blocksize) if not data: break func(data) # A *very* simple interactive browser # Browser main command, has default arguments def browser(*args): selector = DEF_SELECTOR host = DEF_HOST port = DEF_PORT n = len(args) if n > 0 and args[0]: selector = args[0] if n > 1 and args[1]: host = args[1] if n > 2 and args[2]: port = args[2] if n > 3: raise RuntimeError, 'too many args' try: browse_menu(selector, host, port) except socket.error, msg: print 'Socket error:', msg sys.exit(1) except KeyboardInterrupt: print '\n[Goodbye]' # Browse a menu def browse_menu(selector, host, port): list = get_menu(selector, host, port) while 1: print '----- MENU -----' print 'Selector:', repr(selector) print 'Host:', host, ' Port:', port print for i in range(len(list)): item = list[i] typechar, description = item[0], item[1] print string.rjust(repr(i+1), 3) + ':', description, if typename.has_key(typechar): print typename[typechar] else: print '' print while 1: try: str = raw_input('Choice [CR == up a level]: ') except EOFError: print return if not str: return try: choice = string.atoi(str) except string.atoi_error: print 'Choice must be a number; try again:' continue if not 0 < choice <= len(list): print 'Choice out of range; try again:' continue break item = list[choice-1] typechar = item[0] [i_selector, i_host, i_port] = item[2:5] if typebrowser.has_key(typechar): browserfunc = typebrowser[typechar] try: browserfunc(i_selector, i_host, i_port) except (IOError, socket.error): print '***', sys.exc_type, ':', sys.exc_value else: print 'Unsupported object type' # Browse a text file def browse_textfile(selector, host, port): x = None try: p = os.popen('${PAGER-more}', 'w') x = SaveLines(p) get_alt_textfile(selector, host, port, x.writeln) except IOError, msg: print 'IOError:', msg if x: x.close() f = open_savefile() if not f: return x = SaveLines(f) try: get_alt_textfile(selector, host, port, x.writeln) print 'Done.' except IOError, msg: print 'IOError:', msg x.close() # Browse a search index def browse_search(selector, host, port): while 1: print '----- SEARCH -----' print 'Selector:', repr(selector) print 'Host:', host, ' Port:', port print try: query = raw_input('Query [CR == up a level]: ') except EOFError: print break query = string.strip(query) if not query: break if '\t' in query: print 'Sorry, queries cannot contain tabs' continue browse_menu(selector + TAB + query, host, port) # "Browse" telnet-based information, i.e. open a telnet session def browse_telnet(selector, host, port): if selector: print 'Log in as', repr(selector) if type(port) <> type(''): port = repr(port) sts = os.system('set -x; exec telnet ' + host + ' ' + port) if sts: print 'Exit status:', sts # "Browse" a binary file, i.e. save it to a file def browse_binary(selector, host, port): f = open_savefile() if not f: return x = SaveWithProgress(f) get_alt_binary(selector, host, port, x.write, 8*1024) x.close() # "Browse" a sound file, i.e. play it or save it def browse_sound(selector, host, port): browse_binary(selector, host, port) # Dictionary mapping types to browser functions typebrowser = {'0': browse_textfile, '1': browse_menu, \ '4': browse_binary, '5': browse_binary, '6': browse_textfile, \ '7': browse_search, \ '8': browse_telnet, '9': browse_binary, 's': browse_sound} # Class used to save lines, appending a newline to each line class SaveLines: def __init__(self, f): self.f = f def writeln(self, line): self.f.write(line + '\n') def close(self): sts = self.f.close() if sts: print 'Exit status:', sts # Class used to save data while showing progress class SaveWithProgress: def __init__(self, f): self.f = f def write(self, data): sys.stdout.write('#') sys.stdout.flush() self.f.write(data) def close(self): print sts = self.f.close() if sts: print 'Exit status:', sts # Ask for and open a save file, or return None if not to save def open_savefile(): try: savefile = raw_input( \ 'Save as file [CR == don\'t save; |pipeline or ~user/... OK]: ') except EOFError: print return None savefile = string.strip(savefile) if not savefile: return None if savefile[0] == '|': cmd = string.strip(savefile[1:]) try: p = os.popen(cmd, 'w') except IOError, msg: print repr(cmd), ':', msg return None print 'Piping through', repr(cmd), '...' return p if savefile[0] == '~': savefile = os.path.expanduser(savefile) try: f = open(savefile, 'w') except IOError, msg: print repr(savefile), ':', msg return None print 'Saving to', repr(savefile), '...' return f # Test program def test(): if sys.argv[4:]: print 'usage: gopher [ [selector] host [port] ]' sys.exit(2) elif sys.argv[3:]: browser(sys.argv[1], sys.argv[2], sys.argv[3]) elif sys.argv[2:]: try: port = string.atoi(sys.argv[2]) selector = '' host = sys.argv[1] except string.atoi_error: selector = sys.argv[1] host = sys.argv[2] port = '' browser(selector, host, port) elif sys.argv[1:]: browser('', sys.argv[1]) else: browser() # Call the test program as a main program test() PK%L]Yڎeesockets/telnet.pycnu[ Afc@sddlZddlZddlZddlTdZedZedZedZedZ edZ d Z y e Wne k rnXdS( iN(t*iiiiiic Cs!tjd}yt|}Wn9tk rXtjjtjddtjdnXttjdkr~tjd}nd}d|d kodknrt|}nHyt |d}Wn2tk rtjj|dtjdnXt t t }y|j ||fWn>tk ra}tjjd t|d tjdnXtj}|d krxtjj}|j|q}Wn}d }d } xn|jt} | stjjd tj|dtjdnd } x| D]} | r2t| GH|j| | d } q|rd }| tkrW| | } q| ttfkr| tkr|dGndGtt} q| ttfkr| tkrdGndGtt} qdGt| GHq| tkrd}dGq| | } qWtjj| tjjqWdS(Nis: bad host name ittelnett0t9ttcps: bad tcp service name sconnect failed: s its(Closed by remote host) i s(DO)s(DONT)s(WILL)s(WONT)s (command)s(IAC)(tsystargvt gethostbynameterrortstderrtwritetexittlentevalt getservbynametsockettAF_INETt SOCK_STREAMtconnecttreprtposixtforktstdintreadlinetsendtrecvtBUFSIZEtkilltordtIACtDOtDONTtWONTtWILLtstdouttflush( thostthostaddrtservnametporttstmsgtpidtlinetiactopttdatat cleandatatc((s+/usr/lib64/python2.7/Demo/sockets/telnet.pytmains|                ( RRttimeRRtchrRR RR!R"R2tKeyboardInterrupt(((s+/usr/lib64/python2.7/Demo/sockets/telnet.pyts$       M  PK%L]\-sockets/unixclient.pyonu[ ^c@seddlTdZeeeZejeejdejdZej dGe eGHdS(i(t*s unix-sockets Hello, worlditReceivedN( tsockettFILEtAF_UNIXt SOCK_STREAMtstconnecttsendtrecvtdatatclosetrepr(((s//usr/lib64/python2.7/Demo/sockets/unixclient.pyts    PK%L]sockets/unicast.pyonu[ ^c@sdZddlZddlZddlTeeeZejdx=eejdZ ej e defej dqGWdS( iPiN(t*tis i(Ri( tMYPORTtsysttimetsockettAF_INETt SOCK_DGRAMtstbindtreprtdatatsendtotsleep(((s,/usr/lib64/python2.7/Demo/sockets/unicast.pyts  PK%L]S(S(sockets/gopher.pycnu[ Afc@sddlZddlZddlZddlZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZi dd6dd6dd6dd6dd 6dd 6dd 6dd 6dd 6dd6dd6dd6ZdZdZdZd Zd!Zd"Zd#Zd$Zd%Zd&Zd'Zd(Zd)Z d*Z!d+Z"d,Z#i ed6ed6e"d 6e"d 6ed 6e d 6e!d 6e"d6e#d6Z$d-d3d.YZ%d/d4d0YZ&d1Z'd2Z(e(dS(5iNtsgopher.micro.umn.eduiFt0t1t2t3t4t5t6t7t8t9t+tssssssss ssss ss s cCsh|st}n*t|tdkr9tj|}ntjtjtj}|j||f|S(NR(tDEF_PORTttypetstringtatoitsockettAF_INETt SOCK_STREAMtconnect(thosttportR ((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyt open_socket)s cCs:t||}|j|t|jd|jdS(Nitr(RtsendtCRLFtshutdowntmakefile(tselectorRRR ((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyt send_request3s cCs)t|||}g}x|j}|s6dGHPn|dtkrS|d }n|dtkrp|d }n|dkrPn|sdGHqn|d}tj|dt}t|dkrd |fGHqnt|dkrd |dfGHn|jd||j|qW|j |S( Ns(Unexpected EOF from server)iit.s(Empty line from server)iiis(Bad line from server: %r)s(Extra info from server: %r)( RtreadlineRRt splitfieldstTABtlentinserttappendtclose(RRRtftlisttlinettypechartparts((s+/usr/lib64/python2.7/Demo/sockets/gopher.pytget_menu:s6       cCs g}t||||j|S(N(tget_alt_textfileR%(RRRR(((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyt get_textfileXscCst|||}x|j}|s0dGHPn|dtkrM|d }n|dtkrj|d }n|dkrzPn|d dkr|d}n||qW|jdS(Ns(Unexpected EOF from server)iiRis..i(RR RR&(RRRtfuncR'R)((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyR-^s      cCs,t|||}|j}|j|S(N(RtreadR&(RRRR'tdata((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyt get_binaryqs  cCs@t|||}x'|j|}|s.Pn||qWdS(N(RR0(RRRR/t blocksizeR'R1((s+/usr/lib64/python2.7/Demo/sockets/gopher.pytget_alt_binaryxs cGst}t}t}t|}|dkrA|drA|d}n|dkrd|drd|d}n|dkr|dr|d}n|dkrtdnyt|||WnAtjk r}dG|GHtj dnt k rdGHnXdS(Niiiis too many argss Socket error:s [Goodbye]( t DEF_SELECTORtDEF_HOSTR R#t RuntimeErrort browse_menuRterrortsystexittKeyboardInterrupt(targsRRRtntmsg((s+/usr/lib64/python2.7/Demo/sockets/gopher.pytbrowsers&        cCst|||}xdGHdGt|GHdG|GdG|GHHxtt|D]u}||}|d|d}}tjt|dddG|Gtj|rt|GHqNd t|d GHqNWHxytd }Wnt k rHdSX|sdSytj |} Wntj k r,d GHqnXd| koJt|knsZd GHqnPqW|| d}|d}|dd!\} } } t j|rt |} y| | | | Wqt tjfk rdGtjGdGtjGHqXqdGHqWdS(Ns----- MENU -----s Selector:sHost:s Port:iiit:ssChoice [CR == up a level]: s#Choice must be a number; try again:sChoice out of range; try again:iis***sUnsupported object type(R,treprtrangeR#Rtrjustttypenamethas_keyt raw_inputtEOFErrorRt atoi_errort typebrowsertIOErrorRR9R:texc_typet exc_value(RRRR(tititemR*t descriptiontstrtchoicet i_selectorti_hostti_portt browserfunc((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyR8sR "  "  cCsd}y8tjdd}t|}t||||jWntk r\}dG|GHnX|rp|jnt}|sdSt|}yt||||jdGHWntk r}dG|GHnX|jdS(Ns ${PAGER-more}twsIOError:sDone.( tNonetostpopent SaveLinesR-twritelnRLR&t open_savefile(RRRtxtpR?R'((s+/usr/lib64/python2.7/Demo/sockets/gopher.pytbrowse_textfiles&       cCsxdGHdGt|GHdG|GdG|GHHytd}Wntk rNHPnXtj|}|shPnd|krdGHqnt|t|||qWdS(Ns----- SEARCH -----s Selector:sHost:s Port:sQuery [CR == up a level]: s s"Sorry, queries cannot contain tabs(RCRHRIRtstripR8R"(RRRtquery((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyt browse_searchs"  cCsp|rdGt|GHnt|tdkr?t|}ntjd|d|}|rldG|GHndS(Ns Log in asRsset -x; exec telnet t s Exit status:(RCRRZtsystem(RRRtsts((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyt browse_telnetscCsFt}|sdSt|}t||||jd|jdS(Niii (R^tSaveWithProgressR4twriteR&(RRRR'R_((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyt browse_binarys   cCst|||dS(N(Rk(RRR((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyt browse_soundsR\cBs#eZdZdZdZRS(cCs ||_dS(N(R'(tselfR'((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyt__init__scCs|jj|ddS(Ns (R'Rj(RmR)((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyR]scCs%|jj}|r!dG|GHndS(Ns Exit status:(R'R&(RmRg((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyR&s(t__name__t __module__RnR]R&(((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyR\s  RicBs#eZdZdZdZRS(cCs ||_dS(N(R'(RmR'((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyRnscCs1tjjdtjj|jj|dS(Nt#(R:tstdoutRjtflushR'(RmR1((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyRjs cCs&H|jj}|r"dG|GHndS(Ns Exit status:(R'R&(RmRg((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyR& s(RoRpRnRjR&(((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyRis  cCs2ytd}Wntk r%HdSXtj|}|s?dS|ddkrtj|d}ytj|d}Wn'tk r}t|GdG|GHdSXdGt|GdGH|S|dd krtj j |}nyt |d}Wn'tk r}t|GdG|GHdSXd Gt|GdGH|S( Ns<Save as file [CR == don't save; |pipeline or ~user/... OK]: it|iRXRAsPiping throughs...t~s Saving to( RHRIRYRRbRZR[RLRCtpatht expandusertopen(tsavefiletcmdR`R?R'((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyR^'s6  cCs tjdr"dGHtjdntjdrWttjdtjdtjdntjdry-tjtjd}d}tjd}Wn4tjk rtjd}tjd}d}nXt|||n+tjdrtdtjdntdS(Nis(usage: gopher [ [selector] host [port] ]iiiR(R:targvR;R@RRRJ(RRR((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyttestEs$  (     ((()RR:RZRR5R6R t T_TEXTFILEtT_MENUtT_CSOtT_ERRORtT_BINHEXtT_DOSt T_UUENCODEtT_SEARCHtT_TELNETtT_BINARYt T_REDUNDANTtT_SOUNDRFRR"RRR,R.R-R2R4R@R8RaRdRhRkRlRKR\RiR^R|(((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyts\           .      PK%L]S(S(sockets/gopher.pyonu[ Afc@sddlZddlZddlZddlZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZi dd6dd6dd6dd6dd 6dd 6dd 6dd 6dd 6dd6dd6dd6ZdZdZdZd Zd!Zd"Zd#Zd$Zd%Zd&Zd'Zd(Zd)Z d*Z!d+Z"d,Z#i ed6ed6e"d 6e"d 6ed 6e d 6e!d 6e"d6e#d6Z$d-d3d.YZ%d/d4d0YZ&d1Z'd2Z(e(dS(5iNtsgopher.micro.umn.eduiFt0t1t2t3t4t5t6t7t8t9t+tssssssss ssss ss s cCsh|st}n*t|tdkr9tj|}ntjtjtj}|j||f|S(NR(tDEF_PORTttypetstringtatoitsockettAF_INETt SOCK_STREAMtconnect(thosttportR ((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyt open_socket)s cCs:t||}|j|t|jd|jdS(Nitr(RtsendtCRLFtshutdowntmakefile(tselectorRRR ((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyt send_request3s cCs)t|||}g}x|j}|s6dGHPn|dtkrS|d }n|dtkrp|d }n|dkrPn|sdGHqn|d}tj|dt}t|dkrd |fGHqnt|dkrd |dfGHn|jd||j|qW|j |S( Ns(Unexpected EOF from server)iit.s(Empty line from server)iiis(Bad line from server: %r)s(Extra info from server: %r)( RtreadlineRRt splitfieldstTABtlentinserttappendtclose(RRRtftlisttlinettypechartparts((s+/usr/lib64/python2.7/Demo/sockets/gopher.pytget_menu:s6       cCs g}t||||j|S(N(tget_alt_textfileR%(RRRR(((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyt get_textfileXscCst|||}x|j}|s0dGHPn|dtkrM|d }n|dtkrj|d }n|dkrzPn|d dkr|d}n||qW|jdS(Ns(Unexpected EOF from server)iiRis..i(RR RR&(RRRtfuncR'R)((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyR-^s      cCs,t|||}|j}|j|S(N(RtreadR&(RRRR'tdata((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyt get_binaryqs  cCs@t|||}x'|j|}|s.Pn||qWdS(N(RR0(RRRR/t blocksizeR'R1((s+/usr/lib64/python2.7/Demo/sockets/gopher.pytget_alt_binaryxs cGst}t}t}t|}|dkrA|drA|d}n|dkrd|drd|d}n|dkr|dr|d}n|dkrtdnyt|||WnAtjk r}dG|GHtj dnt k rdGHnXdS(Niiiis too many argss Socket error:s [Goodbye]( t DEF_SELECTORtDEF_HOSTR R#t RuntimeErrort browse_menuRterrortsystexittKeyboardInterrupt(targsRRRtntmsg((s+/usr/lib64/python2.7/Demo/sockets/gopher.pytbrowsers&        cCst|||}xdGHdGt|GHdG|GdG|GHHxtt|D]u}||}|d|d}}tjt|dddG|Gtj|rt|GHqNd t|d GHqNWHxytd }Wnt k rHdSX|sdSytj |} Wntj k r,d GHqnXd| koJt|knsZd GHqnPqW|| d}|d}|dd!\} } } t j|rt |} y| | | | Wqt tjfk rdGtjGdGtjGHqXqdGHqWdS(Ns----- MENU -----s Selector:sHost:s Port:iiit:ssChoice [CR == up a level]: s#Choice must be a number; try again:sChoice out of range; try again:iis***sUnsupported object type(R,treprtrangeR#Rtrjustttypenamethas_keyt raw_inputtEOFErrorRt atoi_errort typebrowsertIOErrorRR9R:texc_typet exc_value(RRRR(tititemR*t descriptiontstrtchoicet i_selectorti_hostti_portt browserfunc((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyR8sR "  "  cCsd}y8tjdd}t|}t||||jWntk r\}dG|GHnX|rp|jnt}|sdSt|}yt||||jdGHWntk r}dG|GHnX|jdS(Ns ${PAGER-more}twsIOError:sDone.( tNonetostpopent SaveLinesR-twritelnRLR&t open_savefile(RRRtxtpR?R'((s+/usr/lib64/python2.7/Demo/sockets/gopher.pytbrowse_textfiles&       cCsxdGHdGt|GHdG|GdG|GHHytd}Wntk rNHPnXtj|}|shPnd|krdGHqnt|t|||qWdS(Ns----- SEARCH -----s Selector:sHost:s Port:sQuery [CR == up a level]: s s"Sorry, queries cannot contain tabs(RCRHRIRtstripR8R"(RRRtquery((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyt browse_searchs"  cCsp|rdGt|GHnt|tdkr?t|}ntjd|d|}|rldG|GHndS(Ns Log in asRsset -x; exec telnet t s Exit status:(RCRRZtsystem(RRRtsts((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyt browse_telnetscCsFt}|sdSt|}t||||jd|jdS(Niii (R^tSaveWithProgressR4twriteR&(RRRR'R_((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyt browse_binarys   cCst|||dS(N(Rk(RRR((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyt browse_soundsR\cBs#eZdZdZdZRS(cCs ||_dS(N(R'(tselfR'((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyt__init__scCs|jj|ddS(Ns (R'Rj(RmR)((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyR]scCs%|jj}|r!dG|GHndS(Ns Exit status:(R'R&(RmRg((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyR&s(t__name__t __module__RnR]R&(((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyR\s  RicBs#eZdZdZdZRS(cCs ||_dS(N(R'(RmR'((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyRnscCs1tjjdtjj|jj|dS(Nt#(R:tstdoutRjtflushR'(RmR1((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyRjs cCs&H|jj}|r"dG|GHndS(Ns Exit status:(R'R&(RmRg((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyR& s(RoRpRnRjR&(((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyRis  cCs2ytd}Wntk r%HdSXtj|}|s?dS|ddkrtj|d}ytj|d}Wn'tk r}t|GdG|GHdSXdGt|GdGH|S|dd krtj j |}nyt |d}Wn'tk r}t|GdG|GHdSXd Gt|GdGH|S( Ns<Save as file [CR == don't save; |pipeline or ~user/... OK]: it|iRXRAsPiping throughs...t~s Saving to( RHRIRYRRbRZR[RLRCtpatht expandusertopen(tsavefiletcmdR`R?R'((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyR^'s6  cCs tjdr"dGHtjdntjdrWttjdtjdtjdntjdry-tjtjd}d}tjd}Wn4tjk rtjd}tjd}d}nXt|||n+tjdrtdtjdntdS(Nis(usage: gopher [ [selector] host [port] ]iiiR(R:targvR;R@RRRJ(RRR((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyttestEs$  (     ((()RR:RZRR5R6R t T_TEXTFILEtT_MENUtT_CSOtT_ERRORtT_BINHEXtT_DOSt T_UUENCODEtT_SEARCHtT_TELNETtT_BINARYt T_REDUNDANTtT_SOUNDRFRR"RRR,R.R-R2R4R@R8RaRdRhRkRlRKR\RiR^R|(((s+/usr/lib64/python2.7/Demo/sockets/gopher.pyts\           .      PK%L]߼U sockets/telnet.pynuȯ#! /usr/bin/python2.7 # Minimal interface to the Internet telnet protocol. # # It refuses all telnet options and does not recognize any of the other # telnet commands, but can still be used to connect in line-by-line mode. # It's also useful to play with a number of other services, # like time, finger, smtp and even ftp. # # Usage: telnet host [port] # # The port may be a service name or a decimal port number; # it defaults to 'telnet'. import sys, posix, time from socket import * BUFSIZE = 1024 # Telnet protocol characters IAC = chr(255) # Interpret as command DONT = chr(254) DO = chr(253) WONT = chr(252) WILL = chr(251) def main(): host = sys.argv[1] try: hostaddr = gethostbyname(host) except error: sys.stderr.write(sys.argv[1] + ': bad host name\n') sys.exit(2) # if len(sys.argv) > 2: servname = sys.argv[2] else: servname = 'telnet' # if '0' <= servname[:1] <= '9': port = eval(servname) else: try: port = getservbyname(servname, 'tcp') except error: sys.stderr.write(servname + ': bad tcp service name\n') sys.exit(2) # s = socket(AF_INET, SOCK_STREAM) # try: s.connect((host, port)) except error, msg: sys.stderr.write('connect failed: ' + repr(msg) + '\n') sys.exit(1) # pid = posix.fork() # if pid == 0: # child -- read stdin, write socket while 1: line = sys.stdin.readline() s.send(line) else: # parent -- read socket, write stdout iac = 0 # Interpret next char as command opt = '' # Interpret next char as option while 1: data = s.recv(BUFSIZE) if not data: # EOF; kill child and exit sys.stderr.write( '(Closed by remote host)\n') posix.kill(pid, 9) sys.exit(1) cleandata = '' for c in data: if opt: print ord(c) s.send(opt + c) opt = '' elif iac: iac = 0 if c == IAC: cleandata = cleandata + c elif c in (DO, DONT): if c == DO: print '(DO)', else: print '(DONT)', opt = IAC + WONT elif c in (WILL, WONT): if c == WILL: print '(WILL)', else: print '(WONT)', opt = IAC + DONT else: print '(command)', ord(c) elif c == IAC: iac = 1 print '(IAC)', else: cleandata = cleandata + c sys.stdout.write(cleandata) sys.stdout.flush() try: main() except KeyboardInterrupt: pass PK%L]q<sockets/finger.pycnu[ Afc@sEddlZddlZddlTdZdZdZedS(iN(t*iOcCstttt}|j|tf|j|dx-|jd}|sOPntjj |q6Wtjj dS(Ns i( tsockettAF_INETt SOCK_STREAMtconnectt FINGER_PORTtsendtrecvtsyststdouttwritetflush(thosttargststbuf((s+/usr/lib64/python2.7/Demo/sockets/finger.pytfingerscCsd}d}xO|ttjkr]tj|d dkr]|tj|d}|d}qWtj|}|s}dg}nx^|D]V}d|krtj|d}||d}|| }nd}t|||qWdS(Ntit-t t@(tlenRtargvtstringtindexR(toptionstiR targtatR ((s+/usr/lib64/python2.7/Demo/sockets/finger.pytmain%s/     (RRRRRR(((s+/usr/lib64/python2.7/Demo/sockets/finger.pyt s   PK%L].)S;;sockets/echosvr.pycnu[ Afc@s6ddlZddlTdZdZdZedS(iN(t*iPiicCsttjdkr1tttjd}nt}ttt}|j d|f|j d|j \}\}}dG|G|GHx*|j t }|sPn|j|qWdS(Nits connected by(tlentsystargvtinttevalt ECHO_PORTtsockettAF_INETt SOCK_STREAMtbindtlistentaccepttrecvtBUFSIZEtsend(tporttstconnt remotehostt remoteporttdata((s,/usr/lib64/python2.7/Demo/sockets/echosvr.pytmains  iW(RRRRR(((s,/usr/lib64/python2.7/Demo/sockets/echosvr.pyts   PK%L]vttsockets/READMEnu[This directory contains some demonstrations of the socket module: broadcast.py Broadcast the time to radio.py. echosvr.py About the simplest TCP server possible. finger.py Client for the 'finger' protocol. ftp.py A very simple ftp client. gopher.py A simple gopher client. mcast.py IPv4/v6 multicast example radio.py Receive time broadcasts from broadcast.py. telnet.py Client for the 'telnet' protocol. throughput.py Client and server to measure TCP throughput. unixclient.py Unix socket example, client side unixserver.py Unix socket example, server side udpecho.py Client and server for the UDP echo protocol. PK%L]ⱈsockets/mcast.pynuȯ#! /usr/bin/python2.7 # # Send/receive UDP multicast packets. # Requires that your OS kernel supports IP multicast. # # Usage: # mcast -s (sender, IPv4) # mcast -s -6 (sender, IPv6) # mcast (receivers, IPv4) # mcast -6 (receivers, IPv6) MYPORT = 8123 MYGROUP_4 = '225.0.0.250' MYGROUP_6 = 'ff15:7079:7468:6f6e:6465:6d6f:6d63:6173' MYTTL = 1 # Increase to reach other networks import time import struct import socket import sys def main(): group = MYGROUP_6 if "-6" in sys.argv[1:] else MYGROUP_4 if "-s" in sys.argv[1:]: sender(group) else: receiver(group) def sender(group): addrinfo = socket.getaddrinfo(group, None)[0] s = socket.socket(addrinfo[0], socket.SOCK_DGRAM) # Set Time-to-live (optional) ttl_bin = struct.pack('@i', MYTTL) if addrinfo[0] == socket.AF_INET: # IPv4 s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl_bin) else: s.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_HOPS, ttl_bin) while True: data = repr(time.time()) s.sendto(data + '\0', (addrinfo[4][0], MYPORT)) time.sleep(1) def receiver(group): # Look up multicast group address in name server and find out IP version addrinfo = socket.getaddrinfo(group, None)[0] # Create a socket s = socket.socket(addrinfo[0], socket.SOCK_DGRAM) # Allow multiple copies of this program on one machine # (not strictly needed) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Bind it to the port s.bind(('', MYPORT)) group_bin = socket.inet_pton(addrinfo[0], addrinfo[4][0]) # Join group if addrinfo[0] == socket.AF_INET: # IPv4 mreq = group_bin + struct.pack('=I', socket.INADDR_ANY) s.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) else: mreq = group_bin + struct.pack('@I', 0) s.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, mreq) # Loop, printing any data we receive while True: data, sender = s.recvfrom(1500) while data[-1:] == '\0': data = data[:-1] # Strip trailing \0's print (str(sender) + ' ' + repr(data)) if __name__ == '__main__': main() PK%L]Z6qA sockets/throughput.pyonu[ Afc@s]ddlZddlZddlTd ZdZdZdZdZd ZedS( iN(t*iPi*icCsdttjdkrtntjddkr<tn$tjddkrYtntdS(Niis-ss-c(tlentsystargvtusagetservertclient(((s//usr/lib64/python2.7/Demo/sockets/throughput.pytmains   cCs'tjt_dGHdGHtjddS(Ns*Usage: (on host_A) throughput -s [port]s7and then: (on host_B) throughput -c count host_A [port]i(Rtstderrtstdouttexit(((s//usr/lib64/python2.7/Demo/sockets/throughput.pyR"s cCsttjdkr+ttjd}nt}ttt}|jd|f|j ddGHxg|j \}\}}x |j t }|sPn~qW|j d|jdG|GdG|GHqhWdS(NitisServer ready...sOK s Done withtport(RRRtevaltMY_PORTtsockettAF_INETt SOCK_STREAMtbindtlistentaccepttrecvtBUFSIZEtsendtclose(R tstconnthostt remoteporttdata((s//usr/lib64/python2.7/Demo/sockets/throughput.pyR)s"   c Csttjdkrtntttjd}tjd}ttjdkrpttjd}nt}dtdd}tj}t t t }tj}|j ||ftj}d}x'||kr|d}|j |qW|jdtj} |jt} tj} | GHdG|G|G|G| G| GHd G||G||G| |G| | GHd G| |GHd Gtt|d | |dGd GHdS(Niiitxis is Raw timers:s Intervals:sTotal:s Throughput:gMbP?sK/sec.(RRRRtintR RRttimeRRRtconnectRtshutdownRtround( tcountRR ttestdatatt1Rtt2tt3titt4Rtt5((s//usr/lib64/python2.7/Demo/sockets/throughput.pyR>s6         % !iz( RR RRRRRRR(((s//usr/lib64/python2.7/Demo/sockets/throughput.pyts    PK%L][gyysockets/mcast.pyonu[ Afc@s}dZdZdZdZddlZddlZddlZddlZdZdZ dZ e d kryendS( is 225.0.0.250s'ff15:7079:7468:6f6e:6465:6d6f:6d63:6173iiNcCsMdtjdkrtnt}dtjdkr?t|n t|dS(Ns-6is-s(tsystargvt MYGROUP_6t MYGROUP_4tsendertreceiver(tgroup((s*/usr/lib64/python2.7/Demo/sockets/mcast.pytmains cCstj|dd}tj|dtj}tjdt}|dtjkrp|jtj tj |n|jtj tj |xKt rttj}|j|d|ddtftjdqWdS(Nis@isii(tsockett getaddrinfotNonet SOCK_DGRAMtstructtpacktMYTTLtAF_INETt setsockoptt IPPROTO_IPtIP_MULTICAST_TTLt IPPROTO_IPV6tIPV6_MULTICAST_HOPStTruetreprttimetsendtotMYPORTtsleep(Rtaddrinfotstttl_bintdata((s*/usr/lib64/python2.7/Demo/sockets/mcast.pyRs "cCsPtj|dd}tj|dtj}|jtjtjd|jdtftj |d|dd}|dtj kr|t j dtj }|jtjtj|n/|t j dd}|jtjtj|xYtrK|jd\}}x|dd kr.|d }qWt|d t|GHqWdS( Niitis=Is@Iiiss (RR R R Rt SOL_SOCKETt SO_REUSEADDRtbindRt inet_ptonRR R t INADDR_ANYRtIP_ADD_MEMBERSHIPRtIPV6_JOIN_GROUPRtrecvfromtstrR(RRRt group_bintmreqRR((s*/usr/lib64/python2.7/Demo/sockets/mcast.pyR1s t__main__( RRRRRR RRRRRt__name__(((s*/usr/lib64/python2.7/Demo/sockets/mcast.pyt s       PK%L][gyysockets/mcast.pycnu[ Afc@s}dZdZdZdZddlZddlZddlZddlZdZdZ dZ e d kryendS( is 225.0.0.250s'ff15:7079:7468:6f6e:6465:6d6f:6d63:6173iiNcCsMdtjdkrtnt}dtjdkr?t|n t|dS(Ns-6is-s(tsystargvt MYGROUP_6t MYGROUP_4tsendertreceiver(tgroup((s*/usr/lib64/python2.7/Demo/sockets/mcast.pytmains cCstj|dd}tj|dtj}tjdt}|dtjkrp|jtj tj |n|jtj tj |xKt rttj}|j|d|ddtftjdqWdS(Nis@isii(tsockett getaddrinfotNonet SOCK_DGRAMtstructtpacktMYTTLtAF_INETt setsockoptt IPPROTO_IPtIP_MULTICAST_TTLt IPPROTO_IPV6tIPV6_MULTICAST_HOPStTruetreprttimetsendtotMYPORTtsleep(Rtaddrinfotstttl_bintdata((s*/usr/lib64/python2.7/Demo/sockets/mcast.pyRs "cCsPtj|dd}tj|dtj}|jtjtjd|jdtftj |d|dd}|dtj kr|t j dtj }|jtjtj|n/|t j dd}|jtjtj|xYtrK|jd\}}x|dd kr.|d }qWt|d t|GHqWdS( Niitis=Is@Iiiss (RR R R Rt SOL_SOCKETt SO_REUSEADDRtbindRt inet_ptonRR R t INADDR_ANYRtIP_ADD_MEMBERSHIPRtIPV6_JOIN_GROUPRtrecvfromtstrR(RRRt group_bintmreqRR((s*/usr/lib64/python2.7/Demo/sockets/mcast.pyR1s t__main__( RRRRRR RRRRRt__name__(((s*/usr/lib64/python2.7/Demo/sockets/mcast.pyt s       PK%L]Itsockets/unixserver.pynu[# Echo server demo using Unix sockets (handles one connection only) # Piet van Oostrum import os from socket import * FILE = 'unix-socket' s = socket(AF_UNIX, SOCK_STREAM) s.bind(FILE) print 'Sock name is: ['+s.getsockname()+']' # Wait for a connection s.listen(1) conn, addr = s.accept() while True: data = conn.recv(1024) if not data: break conn.send(data) conn.close() os.unlink(FILE) PK%L]Yڎeesockets/telnet.pyonu[ Afc@sddlZddlZddlZddlTdZedZedZedZedZ edZ d Z y e Wne k rnXdS( iN(t*iiiiiic Cs!tjd}yt|}Wn9tk rXtjjtjddtjdnXttjdkr~tjd}nd}d|d kodknrt|}nHyt |d}Wn2tk rtjj|dtjdnXt t t }y|j ||fWn>tk ra}tjjd t|d tjdnXtj}|d krxtjj}|j|q}Wn}d }d } xn|jt} | stjjd tj|dtjdnd } x| D]} | r2t| GH|j| | d } q|rd }| tkrW| | } q| ttfkr| tkr|dGndGtt} q| ttfkr| tkrdGndGtt} qdGt| GHq| tkrd}dGq| | } qWtjj| tjjqWdS(Nis: bad host name ittelnett0t9ttcps: bad tcp service name sconnect failed: s its(Closed by remote host) i s(DO)s(DONT)s(WILL)s(WONT)s (command)s(IAC)(tsystargvt gethostbynameterrortstderrtwritetexittlentevalt getservbynametsockettAF_INETt SOCK_STREAMtconnecttreprtposixtforktstdintreadlinetsendtrecvtBUFSIZEtkilltordtIACtDOtDONTtWONTtWILLtstdouttflush( thostthostaddrtservnametporttstmsgtpidtlinetiactopttdatat cleandatatc((s+/usr/lib64/python2.7/Demo/sockets/telnet.pytmains|                ( RRttimeRRtchrRR RR!R"R2tKeyboardInterrupt(((s+/usr/lib64/python2.7/Demo/sockets/telnet.pyts$       M  PK%L]`sockets/finger.pynuȯ#! /usr/bin/python2.7 # Python interface to the Internet finger daemon. # # Usage: finger [options] [user][@host] ... # # If no host is given, the finger daemon on the local host is contacted. # Options are passed uninterpreted to the finger daemon! import sys, string from socket import * # Hardcode the number of the finger port here. # It's not likely to change soon... # FINGER_PORT = 79 # Function to do one remote finger invocation. # Output goes directly to stdout (although this can be changed). # def finger(host, args): s = socket(AF_INET, SOCK_STREAM) s.connect((host, FINGER_PORT)) s.send(args + '\n') while 1: buf = s.recv(1024) if not buf: break sys.stdout.write(buf) sys.stdout.flush() # Main function: argument parsing. # def main(): options = '' i = 1 while i < len(sys.argv) and sys.argv[i][:1] == '-': options = options + sys.argv[i] + ' ' i = i+1 args = sys.argv[i:] if not args: args = [''] for arg in args: if '@' in arg: at = string.index(arg, '@') host = arg[at+1:] arg = arg[:at] else: host = '' finger(host, options + arg) # Call the main function. # main() PK%L]sockets/radio.pynu[# Receive UDP packets transmitted by a broadcasting service MYPORT = 50000 import sys from socket import * s = socket(AF_INET, SOCK_DGRAM) s.bind(('', MYPORT)) while 1: data, wherefrom = s.recvfrom(1500, 0) sys.stderr.write(repr(wherefrom) + '\n') sys.stdout.write(data) PK%L]FGsockets/udpecho.pyonu[ Afc@sQddlZddlTd ZdZdZdZdZd ZedS( iN(t*iPiicCsdttjdkrtntjddkr<tn$tjddkrYtntdS(Niis-ss-c(tlentsystargvtusagetservertclient(((s,/usr/lib64/python2.7/Demo/sockets/udpecho.pytmains   cCs'tjt_dGHdGHtjddS(Ns,Usage: udpecho -s [port] (server)s,or: udpecho -c host [port] s    PK%L]'sockets/rpython.pynuȯ#! /usr/bin/python2.7 # Remote python client. # Execute Python commands remotely and send output back. import sys import string from socket import * PORT = 4127 BUFSIZE = 1024 def main(): if len(sys.argv) < 3: print "usage: rpython host command" sys.exit(2) host = sys.argv[1] port = PORT i = string.find(host, ':') if i >= 0: port = string.atoi(port[i+1:]) host = host[:i] command = string.join(sys.argv[2:]) s = socket(AF_INET, SOCK_STREAM) s.connect((host, port)) s.send(command) s.shutdown(1) reply = '' while 1: data = s.recv(BUFSIZE) if not data: break reply = reply + data print reply, main() PK%L]'}&QQsockets/unixserver.pyonu[ ^c@sddlZddlTdZeeeZejedejdGHejdej \Z Z x0e re j dZesPne jeqmWe jejedS(iN(t*s unix-socketsSock name is: [t]ii(tostsockettFILEtAF_UNIXt SOCK_STREAMtstbindt getsocknametlistentaccepttconntaddrtTruetrecvtdatatsendtclosetunlink(((s//usr/lib64/python2.7/Demo/sockets/unixserver.pyts      PK%L]j{sockets/echosvr.pynuȯ#! /usr/bin/python2.7 # Python implementation of an 'echo' tcp server: echo all data it receives. # # This is the simplest possible server, servicing a single request only. import sys from socket import * # The standard echo port isn't very useful, it requires root permissions! # ECHO_PORT = 7 ECHO_PORT = 50000 + 7 BUFSIZE = 1024 def main(): if len(sys.argv) > 1: port = int(eval(sys.argv[1])) else: port = ECHO_PORT s = socket(AF_INET, SOCK_STREAM) s.bind(('', port)) s.listen(1) conn, (remotehost, remoteport) = s.accept() print 'connected by', remotehost, remoteport while 1: data = conn.recv(BUFSIZE) if not data: break conn.send(data) main() PK%L]Hz sockets/ftp.pycnu[ ^c@sddlZddlZddlZddlTdZdZedZedZdZdZd a d Z d Z d Z d Z dZedS(iN(t*iiiiPcCstjd}t|dS(Ni(tsystargvtcontrol(thostname((s(/usr/lib64/python2.7/Demo/sockets/ftp.pytmain's cCsttt}|j|tf|jd}d}xt|}|dkrVPn|dkrt|t|}d}n|st ||}nt }|sPn|j |dq:WdS(Ntrt221tEOFt150s (RR( tsockettAF_INETt SOCK_STREAMtconnecttFTP_PORTtmakefiletNonetgetreplytgetdatat newdataportt getcommandtsend(RtstfRtcodetcmd((s(/usr/lib64/python2.7/Demo/sockets/ftp.pyR.s$       icCsdtt}tddattt}|jtt|f|jdt ||||S(Nii( tnextportt FTP_DATA_PORTR R R tbindt gethostbynamet gethostnametlistent sendportcmd(RRtportR((s(/usr/lib64/python2.7/Demo/sockets/ftp.pyRMs  c Cst}t|}tj|d}t|dt|dg}||}dtj|d}|j|dt|} dS(Nt.isPORT t,s (RRtstringt splitfieldstreprt joinfieldsRR( RRR!RthostaddrthbytestpbytestbytesRR((s(/usr/lib64/python2.7/Demo/sockets/ftp.pyR Zs    cCs|j}|sdS|G|d }|dd!dkrxH|j}|sPPn|G|d |kr:|dd!dkr:Pq:q:Wn|S(NRiit-(treadline(RtlineR((s(/usr/lib64/python2.7/Demo/sockets/ftp.pyRks   # cCsUdGH|j\}}dGHx-|jt}|s8Pntjj|qWdGHdS(Ns(accepting data connection)s(data connection accepted)s(end of data connection)(taccepttrecvtBUFSIZERtstdouttwrite(Rtconnthosttdata((s(/usr/lib64/python2.7/Demo/sockets/ftp.pyR{scCs:y!xtd}|r|SqWWntk r5dSXdS(Nsftp.py> t(t raw_inputtEOFError(R.((s(/usr/lib64/python2.7/Demo/sockets/ftp.pyRs   (RtposixR$R R1RRRRRRR RRR(((s(/usr/lib64/python2.7/Demo/sockets/ftp.pyts$        PK%L])asockets/radio.pycnu[ ^c@sdZddlZddlTeeeZejdefxFejdd\ZZ ej j e e dej j eqAWdS(iPiN(t*tiis (tMYPORTtsystsockettAF_INETt SOCK_DGRAMtstbindtrecvfromtdatat wherefromtstderrtwritetreprtstdout(((s*/usr/lib64/python2.7/Demo/sockets/radio.pyts  PK%L]Sesockets/rpython.pycnu[ Afc@sBddlZddlZddlTdZdZdZedS(iN(t*iicCs ttjdkr*dGHtjdntjd}t}tj|d}|dkrtj||d}|| }ntjtjd}t t t }|j ||f|j ||jdd}x'|jt}|sPn||}qW|GdS(Nisusage: rpython host commandiit:it(tlentsystargvtexittPORTtstringtfindtatoitjointsockettAF_INETt SOCK_STREAMtconnecttsendtshutdowntrecvtBUFSIZE(thosttporttitcommandtstreplytdata((s,/usr/lib64/python2.7/Demo/sockets/rpython.pytmain s*     (RRR RRR(((s,/usr/lib64/python2.7/Demo/sockets/rpython.pyts    PK%L]uasockets/udpecho.pynuȯ#! /usr/bin/python2.7 # Client and server for udp (datagram) echo. # # Usage: udpecho -s [port] (to start a server) # or: udpecho -c host [port] 2: port = eval(sys.argv[2]) else: port = ECHO_PORT s = socket(AF_INET, SOCK_DGRAM) s.bind(('', port)) print 'udp echo server ready' while 1: data, addr = s.recvfrom(BUFSIZE) print 'server received %r from %r' % (data, addr) s.sendto(data, addr) def client(): if len(sys.argv) < 3: usage() host = sys.argv[2] if len(sys.argv) > 3: port = eval(sys.argv[3]) else: port = ECHO_PORT addr = host, port s = socket(AF_INET, SOCK_DGRAM) s.bind(('', 0)) print 'udp echo client ready, reading stdin' while 1: line = sys.stdin.readline() if not line: break s.sendto(line, addr) data, fromaddr = s.recvfrom(BUFSIZE) print 'client received %r from %r' % (data, fromaddr) main() PK%L]$$sockets/throughput.pynuȯ#! /usr/bin/python2.7 # Test network throughput. # # Usage: # 1) on host_A: throughput -s [port] # start a server # 2) on host_B: throughput -c count host_A [port] # start a client # # The server will service multiple clients until it is killed. # # The client performs one transfer of count*BUFSIZE bytes and # measures the time it takes (roundtrip!). import sys, time from socket import * MY_PORT = 50000 + 42 BUFSIZE = 1024 def main(): if len(sys.argv) < 2: usage() if sys.argv[1] == '-s': server() elif sys.argv[1] == '-c': client() else: usage() def usage(): sys.stdout = sys.stderr print 'Usage: (on host_A) throughput -s [port]' print 'and then: (on host_B) throughput -c count host_A [port]' sys.exit(2) def server(): if len(sys.argv) > 2: port = eval(sys.argv[2]) else: port = MY_PORT s = socket(AF_INET, SOCK_STREAM) s.bind(('', port)) s.listen(1) print 'Server ready...' while 1: conn, (host, remoteport) = s.accept() while 1: data = conn.recv(BUFSIZE) if not data: break del data conn.send('OK\n') conn.close() print 'Done with', host, 'port', remoteport def client(): if len(sys.argv) < 4: usage() count = int(eval(sys.argv[2])) host = sys.argv[3] if len(sys.argv) > 4: port = eval(sys.argv[4]) else: port = MY_PORT testdata = 'x' * (BUFSIZE-1) + '\n' t1 = time.time() s = socket(AF_INET, SOCK_STREAM) t2 = time.time() s.connect((host, port)) t3 = time.time() i = 0 while i < count: i = i+1 s.send(testdata) s.shutdown(1) # Send EOF t4 = time.time() data = s.recv(BUFSIZE) t5 = time.time() print data print 'Raw timers:', t1, t2, t3, t4, t5 print 'Intervals:', t2-t1, t3-t2, t4-t3, t5-t4 print 'Total:', t5-t1 print 'Throughput:', round((BUFSIZE*count*0.001) / (t5-t1), 3), print 'K/sec.' main() PK%L]q<sockets/finger.pyonu[ Afc@sEddlZddlZddlTdZdZdZedS(iN(t*iOcCstttt}|j|tf|j|dx-|jd}|sOPntjj |q6Wtjj dS(Ns i( tsockettAF_INETt SOCK_STREAMtconnectt FINGER_PORTtsendtrecvtsyststdouttwritetflush(thosttargststbuf((s+/usr/lib64/python2.7/Demo/sockets/finger.pytfingerscCsd}d}xO|ttjkr]tj|d dkr]|tj|d}|d}qWtj|}|s}dg}nx^|D]V}d|krtj|d}||d}|| }nd}t|||qWdS(Ntit-t t@(tlenRtargvtstringtindexR(toptionstiR targtatR ((s+/usr/lib64/python2.7/Demo/sockets/finger.pytmain%s/     (RRRRRR(((s+/usr/lib64/python2.7/Demo/sockets/finger.pyt s   PK%L]Csockets/broadcast.pynu[# Send UDP broadcast packets MYPORT = 50000 import sys, time from socket import * s = socket(AF_INET, SOCK_DGRAM) s.bind(('', 0)) s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) while 1: data = repr(time.time()) + '\n' s.sendto(data, ('', MYPORT)) time.sleep(2) PK%L]Z6qA sockets/throughput.pycnu[ Afc@s]ddlZddlZddlTd ZdZdZdZdZd ZedS( iN(t*iPi*icCsdttjdkrtntjddkr<tn$tjddkrYtntdS(Niis-ss-c(tlentsystargvtusagetservertclient(((s//usr/lib64/python2.7/Demo/sockets/throughput.pytmains   cCs'tjt_dGHdGHtjddS(Ns*Usage: (on host_A) throughput -s [port]s7and then: (on host_B) throughput -c count host_A [port]i(Rtstderrtstdouttexit(((s//usr/lib64/python2.7/Demo/sockets/throughput.pyR"s cCsttjdkr+ttjd}nt}ttt}|jd|f|j ddGHxg|j \}\}}x |j t }|sPn~qW|j d|jdG|GdG|GHqhWdS(NitisServer ready...sOK s Done withtport(RRRtevaltMY_PORTtsockettAF_INETt SOCK_STREAMtbindtlistentaccepttrecvtBUFSIZEtsendtclose(R tstconnthostt remoteporttdata((s//usr/lib64/python2.7/Demo/sockets/throughput.pyR)s"   c Csttjdkrtntttjd}tjd}ttjdkrpttjd}nt}dtdd}tj}t t t }tj}|j ||ftj}d}x'||kr|d}|j |qW|jdtj} |jt} tj} | GHdG|G|G|G| G| GHd G||G||G| |G| | GHd G| |GHd Gtt|d | |dGd GHdS(Niiitxis is Raw timers:s Intervals:sTotal:s Throughput:gMbP?sK/sec.(RRRRtintR RRttimeRRRtconnectRtshutdownRtround( tcountRR ttestdatatt1Rtt2tt3titt4Rtt5((s//usr/lib64/python2.7/Demo/sockets/throughput.pyR>s6         % !iz( RR RRRRRRR(((s//usr/lib64/python2.7/Demo/sockets/throughput.pyts    PK%L]dBT77sockets/rpythond.pyonu[ Afc@sWddlZddlTddlZddlZdZdZdZdZedS(iN(t*iicCsttjdkr1tttjd}nt}ttt}|j d|f|j dx||j \}\}}dG|G|GHd}x'|j t }|sPn||}qWt|}|j||jqiWdS(Nits connected by(tlentsystargvtinttevaltPORTtsockettAF_INETt SOCK_STREAMtbindtlistentaccepttrecvtBUFSIZEtexecutetsendtclose(tporttstconnt remotehostt remoteporttrequesttdatatreply((s-/usr/lib64/python2.7/Demo/sockets/rpythond.pytmains$    cBsvej}ej}eje_e_}z*y|iiUWnHejdnXWd|e_|e_X|jS(Nid(RtstdouttstderrtStringIOt tracebackt print_exctgetvalue(RRRtfakefile((s-/usr/lib64/python2.7/Demo/sockets/rpythond.pyR%s    (RRRRRRRR(((s-/usr/lib64/python2.7/Demo/sockets/rpythond.pyts      PK%L]csockets/rpythond.pynuȯ#! /usr/bin/python2.7 # Remote python server. # Execute Python commands remotely and send output back. # WARNING: This version has a gaping security hole -- it accepts requests # from any host on the Internet! import sys from socket import * import StringIO import traceback PORT = 4127 BUFSIZE = 1024 def main(): if len(sys.argv) > 1: port = int(eval(sys.argv[1])) else: port = PORT s = socket(AF_INET, SOCK_STREAM) s.bind(('', port)) s.listen(1) while 1: conn, (remotehost, remoteport) = s.accept() print 'connected by', remotehost, remoteport request = '' while 1: data = conn.recv(BUFSIZE) if not data: break request = request + data reply = execute(request) conn.send(reply) conn.close() def execute(request): stdout = sys.stdout stderr = sys.stderr sys.stdout = sys.stderr = fakefile = StringIO.StringIO() try: try: exec request in {}, {} except: print traceback.print_exc(100) finally: sys.stderr = stderr sys.stdout = stdout return fakefile.getvalue() main() PK%L]##sockets/broadcast.pyonu[ ^c@sdZddlZddlZddlTeeeZejd eje e dx=e ejdZ ej e defejd qZWdS( iPiN(t*tiis s i(Ri(tMYPORTtsysttimetsockettAF_INETt SOCK_DGRAMtstbindt setsockoptt SOL_SOCKETt SO_BROADCASTtreprtdatatsendtotsleep(((s./usr/lib64/python2.7/Demo/sockets/broadcast.pyts  PK%L]##sockets/broadcast.pycnu[ ^c@sdZddlZddlZddlTeeeZejd eje e dx=e ejdZ ej e defejd qZWdS( iPiN(t*tiis s i(Ri(tMYPORTtsysttimetsockettAF_INETt SOCK_DGRAMtstbindt setsockoptt SOL_SOCKETt SO_BROADCASTtreprtdatatsendtotsleep(((s./usr/lib64/python2.7/Demo/sockets/broadcast.pyts  PK%L]'}&QQsockets/unixserver.pycnu[ ^c@sddlZddlTdZeeeZejedejdGHejdej \Z Z x0e re j dZesPne jeqmWe jejedS(iN(t*s unix-socketsSock name is: [t]ii(tostsockettFILEtAF_UNIXt SOCK_STREAMtstbindt getsocknametlistentaccepttconntaddrtTruetrecvtdatatsendtclosetunlink(((s//usr/lib64/python2.7/Demo/sockets/unixserver.pyts      PK%L])asockets/radio.pyonu[ ^c@sdZddlZddlTeeeZejdefxFejdd\ZZ ej j e e dej j eqAWdS(iPiN(t*tiis (tMYPORTtsystsockettAF_INETt SOCK_DGRAMtstbindtrecvfromtdatat wherefromtstderrtwritetreprtstdout(((s*/usr/lib64/python2.7/Demo/sockets/radio.pyts  PK%L]\-sockets/unixclient.pycnu[ ^c@seddlTdZeeeZejeejdejdZej dGe eGHdS(i(t*s unix-sockets Hello, worlditReceivedN( tsockettFILEtAF_UNIXt SOCK_STREAMtstconnecttsendtrecvtdatatclosetrepr(((s//usr/lib64/python2.7/Demo/sockets/unixclient.pyts    PK%L]sockets/unicast.pycnu[ ^c@sdZddlZddlZddlTeeeZejdx=eejdZ ej e defej dqGWdS( iPiN(t*tis i(Ri( tMYPORTtsysttimetsockettAF_INETt SOCK_DGRAMtstbindtreprtdatatsendtotsleep(((s,/usr/lib64/python2.7/Demo/sockets/unicast.pyts  PK%L]Hz sockets/ftp.pyonu[ ^c@sddlZddlZddlZddlTdZdZedZedZdZdZd a d Z d Z d Z d Z dZedS(iN(t*iiiiPcCstjd}t|dS(Ni(tsystargvtcontrol(thostname((s(/usr/lib64/python2.7/Demo/sockets/ftp.pytmain's cCsttt}|j|tf|jd}d}xt|}|dkrVPn|dkrt|t|}d}n|st ||}nt }|sPn|j |dq:WdS(Ntrt221tEOFt150s (RR( tsockettAF_INETt SOCK_STREAMtconnecttFTP_PORTtmakefiletNonetgetreplytgetdatat newdataportt getcommandtsend(RtstfRtcodetcmd((s(/usr/lib64/python2.7/Demo/sockets/ftp.pyR.s$       icCsdtt}tddattt}|jtt|f|jdt ||||S(Nii( tnextportt FTP_DATA_PORTR R R tbindt gethostbynamet gethostnametlistent sendportcmd(RRtportR((s(/usr/lib64/python2.7/Demo/sockets/ftp.pyRMs  c Cst}t|}tj|d}t|dt|dg}||}dtj|d}|j|dt|} dS(Nt.isPORT t,s (RRtstringt splitfieldstreprt joinfieldsRR( RRR!RthostaddrthbytestpbytestbytesRR((s(/usr/lib64/python2.7/Demo/sockets/ftp.pyR Zs    cCs|j}|sdS|G|d }|dd!dkrxH|j}|sPPn|G|d |kr:|dd!dkr:Pq:q:Wn|S(NRiit-(treadline(RtlineR((s(/usr/lib64/python2.7/Demo/sockets/ftp.pyRks   # cCsUdGH|j\}}dGHx-|jt}|s8Pntjj|qWdGHdS(Ns(accepting data connection)s(data connection accepted)s(end of data connection)(taccepttrecvtBUFSIZERtstdouttwrite(Rtconnthosttdata((s(/usr/lib64/python2.7/Demo/sockets/ftp.pyR{scCs:y!xtd}|r|SqWWntk r5dSXdS(Nsftp.py> t(t raw_inputtEOFError(R.((s(/usr/lib64/python2.7/Demo/sockets/ftp.pyRs   (RtposixR$R R1RRRRRRR RRR(((s(/usr/lib64/python2.7/Demo/sockets/ftp.pyts$        PK%L]^XXsockets/ftp.pynu[# A simple FTP client. # # The information to write this program was gathered from RFC 959, # but this is not a complete implementation! Yet it shows how a simple # FTP client can be built, and you are welcome to extend it to suit # it to your needs... # # How it works (assuming you've read the RFC): # # User commands are passed uninterpreted to the server. However, the # user never needs to send a PORT command. Rather, the client opens a # port right away and sends the appropriate PORT command to the server. # When a response code 150 is received, this port is used to receive # the data (which is written to stdout in this version), and when the # data is exhausted, a new port is opened and a corresponding PORT # command sent. In order to avoid errors when reusing ports quickly # (and because there is no s.getsockname() method in Python yet) we # cycle through a number of ports in the 50000 range. import sys, posix, string from socket import * BUFSIZE = 1024 # Default port numbers used by the FTP protocol. # FTP_PORT = 21 FTP_DATA_PORT = FTP_PORT - 1 # Change the data port to something not needing root permissions. # FTP_DATA_PORT = FTP_DATA_PORT + 50000 # Main program (called at the end of this file). # def main(): hostname = sys.argv[1] control(hostname) # Control process (user interface and user protocol interpreter). # def control(hostname): # # Create control connection # s = socket(AF_INET, SOCK_STREAM) s.connect((hostname, FTP_PORT)) f = s.makefile('r') # Reading the replies is easier from a file... # # Control loop # r = None while 1: code = getreply(f) if code in ('221', 'EOF'): break if code == '150': getdata(r) code = getreply(f) r = None if not r: r = newdataport(s, f) cmd = getcommand() if not cmd: break s.send(cmd + '\r\n') # Create a new data port and send a PORT command to the server for it. # (Cycle through a number of ports to avoid problems with reusing # a port within a short time.) # nextport = 0 # def newdataport(s, f): global nextport port = nextport + FTP_DATA_PORT nextport = (nextport+1) % 16 r = socket(AF_INET, SOCK_STREAM) r.bind((gethostbyname(gethostname()), port)) r.listen(1) sendportcmd(s, f, port) return r # Send an appropriate port command. # def sendportcmd(s, f, port): hostname = gethostname() hostaddr = gethostbyname(hostname) hbytes = string.splitfields(hostaddr, '.') pbytes = [repr(port//256), repr(port%256)] bytes = hbytes + pbytes cmd = 'PORT ' + string.joinfields(bytes, ',') s.send(cmd + '\r\n') code = getreply(f) # Process an ftp reply and return the 3-digit reply code (as a string). # The reply should be a line of text starting with a 3-digit number. # If the 4th char is '-', it is a multi-line reply and is # terminate by a line starting with the same 3-digit number. # Any text while receiving the reply is echoed to the file. # def getreply(f): line = f.readline() if not line: return 'EOF' print line, code = line[:3] if line[3:4] == '-': while 1: line = f.readline() if not line: break # Really an error print line, if line[:3] == code and line[3:4] != '-': break return code # Get the data from the data connection. # def getdata(r): print '(accepting data connection)' conn, host = r.accept() print '(data connection accepted)' while 1: data = conn.recv(BUFSIZE) if not data: break sys.stdout.write(data) print '(end of data connection)' # Get a command from the user. # def getcommand(): try: while 1: line = raw_input('ftp.py> ') if line: return line except EOFError: return '' # Call the main program. # main() PK%L]IA}sockets/unixclient.pynu[# Echo client demo using Unix sockets # Piet van Oostrum from socket import * FILE = 'unix-socket' s = socket(AF_UNIX, SOCK_STREAM) s.connect(FILE) s.send('Hello, world') data = s.recv(1024) s.close() print 'Received', repr(data) PK%L]FGsockets/udpecho.pycnu[ Afc@sQddlZddlTd ZdZdZdZdZd ZedS( iN(t*iPiicCsdttjdkrtntjddkr<tn$tjddkrYtntdS(Niis-ss-c(tlentsystargvtusagetservertclient(((s,/usr/lib64/python2.7/Demo/sockets/udpecho.pytmains   cCs'tjt_dGHdGHtjddS(Ns,Usage: udpecho -s [port] (server)s,or: udpecho -c host [port] s    PK%L]Sesockets/rpython.pyonu[ Afc@sBddlZddlZddlTdZdZdZedS(iN(t*iicCs ttjdkr*dGHtjdntjd}t}tj|d}|dkrtj||d}|| }ntjtjd}t t t }|j ||f|j ||jdd}x'|jt}|sPn||}qW|GdS(Nisusage: rpython host commandiit:it(tlentsystargvtexittPORTtstringtfindtatoitjointsockettAF_INETt SOCK_STREAMtconnecttsendtshutdowntrecvtBUFSIZE(thosttporttitcommandtstreplytdata((s,/usr/lib64/python2.7/Demo/sockets/rpython.pytmain s*     (RRR RRR(((s,/usr/lib64/python2.7/Demo/sockets/rpython.pyts    PK%L]dBT77sockets/rpythond.pycnu[ Afc@sWddlZddlTddlZddlZdZdZdZdZedS(iN(t*iicCsttjdkr1tttjd}nt}ttt}|j d|f|j dx||j \}\}}dG|G|GHd}x'|j t }|sPn||}qWt|}|j||jqiWdS(Nits connected by(tlentsystargvtinttevaltPORTtsockettAF_INETt SOCK_STREAMtbindtlistentaccepttrecvtBUFSIZEtexecutetsendtclose(tporttstconnt remotehostt remoteporttrequesttdatatreply((s-/usr/lib64/python2.7/Demo/sockets/rpythond.pytmains$    cBsvej}ej}eje_e_}z*y|iiUWnHejdnXWd|e_|e_X|jS(Nid(RtstdouttstderrtStringIOt tracebackt print_exctgetvalue(RRRtfakefile((s-/usr/lib64/python2.7/Demo/sockets/rpythond.pyR%s    (RRRRRRRR(((s-/usr/lib64/python2.7/Demo/sockets/rpythond.pyts      PK%L]lsockets/unicast.pynu[# Send UDP broadcast packets MYPORT = 50000 import sys, time from socket import * s = socket(AF_INET, SOCK_DGRAM) s.bind(('', 0)) while 1: data = repr(time.time()) + '\n' s.sendto(data, ('', MYPORT)) time.sleep(2) PK%L]'njCjCparser/unparse.pynu["Usage: unparse.py " import sys import ast import cStringIO import os # Large float and imaginary literals get turned into infinities in the AST. # We unparse those infinities to INFSTR. INFSTR = "1e" + repr(sys.float_info.max_10_exp + 1) def interleave(inter, f, seq): """Call f on each item in seq, calling inter() in between. """ seq = iter(seq) try: f(next(seq)) except StopIteration: pass else: for x in seq: inter() f(x) class Unparser: """Methods in this class recursively traverse an AST and output source code for the abstract syntax; original formatting is disregarded. """ def __init__(self, tree, file = sys.stdout): """Unparser(tree, file=sys.stdout) -> None. Print the source for tree to file.""" self.f = file self.future_imports = [] self._indent = 0 self.dispatch(tree) self.f.write("") self.f.flush() def fill(self, text = ""): "Indent a piece of text, according to the current indentation level" self.f.write("\n"+" "*self._indent + text) def write(self, text): "Append a piece of text to the current line." self.f.write(text) def enter(self): "Print ':', and increase the indentation." self.write(":") self._indent += 1 def leave(self): "Decrease the indentation level." self._indent -= 1 def dispatch(self, tree): "Dispatcher function, dispatching tree type T to method _T." if isinstance(tree, list): for t in tree: self.dispatch(t) return meth = getattr(self, "_"+tree.__class__.__name__) meth(tree) ############### Unparsing methods ###################### # There should be one method per concrete grammar type # # Constructors should be grouped by sum type. Ideally, # # this would follow the order in the grammar, but # # currently doesn't. # ######################################################## def _Module(self, tree): for stmt in tree.body: self.dispatch(stmt) # stmt def _Expr(self, tree): self.fill() self.dispatch(tree.value) def _Import(self, t): self.fill("import ") interleave(lambda: self.write(", "), self.dispatch, t.names) def _ImportFrom(self, t): # A from __future__ import may affect unparsing, so record it. if t.module and t.module == '__future__': self.future_imports.extend(n.name for n in t.names) self.fill("from ") self.write("." * t.level) if t.module: self.write(t.module) self.write(" import ") interleave(lambda: self.write(", "), self.dispatch, t.names) def _Assign(self, t): self.fill() for target in t.targets: self.dispatch(target) self.write(" = ") self.dispatch(t.value) def _AugAssign(self, t): self.fill() self.dispatch(t.target) self.write(" "+self.binop[t.op.__class__.__name__]+"= ") self.dispatch(t.value) def _Return(self, t): self.fill("return") if t.value: self.write(" ") self.dispatch(t.value) def _Pass(self, t): self.fill("pass") def _Break(self, t): self.fill("break") def _Continue(self, t): self.fill("continue") def _Delete(self, t): self.fill("del ") interleave(lambda: self.write(", "), self.dispatch, t.targets) def _Assert(self, t): self.fill("assert ") self.dispatch(t.test) if t.msg: self.write(", ") self.dispatch(t.msg) def _Exec(self, t): self.fill("exec ") self.dispatch(t.body) if t.globals: self.write(" in ") self.dispatch(t.globals) if t.locals: self.write(", ") self.dispatch(t.locals) def _Print(self, t): self.fill("print ") do_comma = False if t.dest: self.write(">>") self.dispatch(t.dest) do_comma = True for e in t.values: if do_comma:self.write(", ") else:do_comma=True self.dispatch(e) if not t.nl: self.write(",") def _Global(self, t): self.fill("global ") interleave(lambda: self.write(", "), self.write, t.names) def _Yield(self, t): self.write("(") self.write("yield") if t.value: self.write(" ") self.dispatch(t.value) self.write(")") def _Raise(self, t): self.fill('raise ') if t.type: self.dispatch(t.type) if t.inst: self.write(", ") self.dispatch(t.inst) if t.tback: self.write(", ") self.dispatch(t.tback) def _TryExcept(self, t): self.fill("try") self.enter() self.dispatch(t.body) self.leave() for ex in t.handlers: self.dispatch(ex) if t.orelse: self.fill("else") self.enter() self.dispatch(t.orelse) self.leave() def _TryFinally(self, t): if len(t.body) == 1 and isinstance(t.body[0], ast.TryExcept): # try-except-finally self.dispatch(t.body) else: self.fill("try") self.enter() self.dispatch(t.body) self.leave() self.fill("finally") self.enter() self.dispatch(t.finalbody) self.leave() def _ExceptHandler(self, t): self.fill("except") if t.type: self.write(" ") self.dispatch(t.type) if t.name: self.write(" as ") self.dispatch(t.name) self.enter() self.dispatch(t.body) self.leave() def _ClassDef(self, t): self.write("\n") for deco in t.decorator_list: self.fill("@") self.dispatch(deco) self.fill("class "+t.name) if t.bases: self.write("(") for a in t.bases: self.dispatch(a) self.write(", ") self.write(")") self.enter() self.dispatch(t.body) self.leave() def _FunctionDef(self, t): self.write("\n") for deco in t.decorator_list: self.fill("@") self.dispatch(deco) self.fill("def "+t.name + "(") self.dispatch(t.args) self.write(")") self.enter() self.dispatch(t.body) self.leave() def _For(self, t): self.fill("for ") self.dispatch(t.target) self.write(" in ") self.dispatch(t.iter) self.enter() self.dispatch(t.body) self.leave() if t.orelse: self.fill("else") self.enter() self.dispatch(t.orelse) self.leave() def _If(self, t): self.fill("if ") self.dispatch(t.test) self.enter() self.dispatch(t.body) self.leave() # collapse nested ifs into equivalent elifs. while (t.orelse and len(t.orelse) == 1 and isinstance(t.orelse[0], ast.If)): t = t.orelse[0] self.fill("elif ") self.dispatch(t.test) self.enter() self.dispatch(t.body) self.leave() # final else if t.orelse: self.fill("else") self.enter() self.dispatch(t.orelse) self.leave() def _While(self, t): self.fill("while ") self.dispatch(t.test) self.enter() self.dispatch(t.body) self.leave() if t.orelse: self.fill("else") self.enter() self.dispatch(t.orelse) self.leave() def _With(self, t): self.fill("with ") self.dispatch(t.context_expr) if t.optional_vars: self.write(" as ") self.dispatch(t.optional_vars) self.enter() self.dispatch(t.body) self.leave() # expr def _Str(self, tree): # if from __future__ import unicode_literals is in effect, # then we want to output string literals using a 'b' prefix # and unicode literals with no prefix. if "unicode_literals" not in self.future_imports: self.write(repr(tree.s)) elif isinstance(tree.s, str): self.write("b" + repr(tree.s)) elif isinstance(tree.s, unicode): self.write(repr(tree.s).lstrip("u")) else: assert False, "shouldn't get here" def _Name(self, t): self.write(t.id) def _Repr(self, t): self.write("`") self.dispatch(t.value) self.write("`") def _Num(self, t): repr_n = repr(t.n) # Parenthesize negative numbers, to avoid turning (-1)**2 into -1**2. if repr_n.startswith("-"): self.write("(") # Substitute overflowing decimal literal for AST infinities. self.write(repr_n.replace("inf", INFSTR)) if repr_n.startswith("-"): self.write(")") def _List(self, t): self.write("[") interleave(lambda: self.write(", "), self.dispatch, t.elts) self.write("]") def _ListComp(self, t): self.write("[") self.dispatch(t.elt) for gen in t.generators: self.dispatch(gen) self.write("]") def _GeneratorExp(self, t): self.write("(") self.dispatch(t.elt) for gen in t.generators: self.dispatch(gen) self.write(")") def _SetComp(self, t): self.write("{") self.dispatch(t.elt) for gen in t.generators: self.dispatch(gen) self.write("}") def _DictComp(self, t): self.write("{") self.dispatch(t.key) self.write(": ") self.dispatch(t.value) for gen in t.generators: self.dispatch(gen) self.write("}") def _comprehension(self, t): self.write(" for ") self.dispatch(t.target) self.write(" in ") self.dispatch(t.iter) for if_clause in t.ifs: self.write(" if ") self.dispatch(if_clause) def _IfExp(self, t): self.write("(") self.dispatch(t.body) self.write(" if ") self.dispatch(t.test) self.write(" else ") self.dispatch(t.orelse) self.write(")") def _Set(self, t): assert(t.elts) # should be at least one element self.write("{") interleave(lambda: self.write(", "), self.dispatch, t.elts) self.write("}") def _Dict(self, t): self.write("{") def write_pair(pair): (k, v) = pair self.dispatch(k) self.write(": ") self.dispatch(v) interleave(lambda: self.write(", "), write_pair, zip(t.keys, t.values)) self.write("}") def _Tuple(self, t): self.write("(") if len(t.elts) == 1: (elt,) = t.elts self.dispatch(elt) self.write(",") else: interleave(lambda: self.write(", "), self.dispatch, t.elts) self.write(")") unop = {"Invert":"~", "Not": "not", "UAdd":"+", "USub":"-"} def _UnaryOp(self, t): self.write("(") self.write(self.unop[t.op.__class__.__name__]) self.write(" ") # If we're applying unary minus to a number, parenthesize the number. # This is necessary: -2147483648 is different from -(2147483648) on # a 32-bit machine (the first is an int, the second a long), and # -7j is different from -(7j). (The first has real part 0.0, the second # has real part -0.0.) if isinstance(t.op, ast.USub) and isinstance(t.operand, ast.Num): self.write("(") self.dispatch(t.operand) self.write(")") else: self.dispatch(t.operand) self.write(")") binop = { "Add":"+", "Sub":"-", "Mult":"*", "Div":"/", "Mod":"%", "LShift":"<<", "RShift":">>", "BitOr":"|", "BitXor":"^", "BitAnd":"&", "FloorDiv":"//", "Pow": "**"} def _BinOp(self, t): self.write("(") self.dispatch(t.left) self.write(" " + self.binop[t.op.__class__.__name__] + " ") self.dispatch(t.right) self.write(")") cmpops = {"Eq":"==", "NotEq":"!=", "Lt":"<", "LtE":"<=", "Gt":">", "GtE":">=", "Is":"is", "IsNot":"is not", "In":"in", "NotIn":"not in"} def _Compare(self, t): self.write("(") self.dispatch(t.left) for o, e in zip(t.ops, t.comparators): self.write(" " + self.cmpops[o.__class__.__name__] + " ") self.dispatch(e) self.write(")") boolops = {ast.And: 'and', ast.Or: 'or'} def _BoolOp(self, t): self.write("(") s = " %s " % self.boolops[t.op.__class__] interleave(lambda: self.write(s), self.dispatch, t.values) self.write(")") def _Attribute(self,t): self.dispatch(t.value) # Special case: 3.__abs__() is a syntax error, so if t.value # is an integer literal then we need to either parenthesize # it or add an extra space to get 3 .__abs__(). if isinstance(t.value, ast.Num) and isinstance(t.value.n, int): self.write(" ") self.write(".") self.write(t.attr) def _Call(self, t): self.dispatch(t.func) self.write("(") comma = False for e in t.args: if comma: self.write(", ") else: comma = True self.dispatch(e) for e in t.keywords: if comma: self.write(", ") else: comma = True self.dispatch(e) if t.starargs: if comma: self.write(", ") else: comma = True self.write("*") self.dispatch(t.starargs) if t.kwargs: if comma: self.write(", ") else: comma = True self.write("**") self.dispatch(t.kwargs) self.write(")") def _Subscript(self, t): self.dispatch(t.value) self.write("[") self.dispatch(t.slice) self.write("]") # slice def _Ellipsis(self, t): self.write("...") def _Index(self, t): self.dispatch(t.value) def _Slice(self, t): if t.lower: self.dispatch(t.lower) self.write(":") if t.upper: self.dispatch(t.upper) if t.step: self.write(":") self.dispatch(t.step) def _ExtSlice(self, t): interleave(lambda: self.write(', '), self.dispatch, t.dims) # others def _arguments(self, t): first = True # normal arguments defaults = [None] * (len(t.args) - len(t.defaults)) + t.defaults for a,d in zip(t.args, defaults): if first:first = False else: self.write(", ") self.dispatch(a), if d: self.write("=") self.dispatch(d) # varargs if t.vararg: if first:first = False else: self.write(", ") self.write("*") self.write(t.vararg) # kwargs if t.kwarg: if first:first = False else: self.write(", ") self.write("**"+t.kwarg) def _keyword(self, t): self.write(t.arg) self.write("=") self.dispatch(t.value) def _Lambda(self, t): self.write("(") self.write("lambda ") self.dispatch(t.args) self.write(": ") self.dispatch(t.body) self.write(")") def _alias(self, t): self.write(t.name) if t.asname: self.write(" as "+t.asname) def roundtrip(filename, output=sys.stdout): with open(filename, "r") as pyfile: source = pyfile.read() tree = compile(source, filename, "exec", ast.PyCF_ONLY_AST) Unparser(tree, output) def testdir(a): try: names = [n for n in os.listdir(a) if n.endswith('.py')] except OSError: sys.stderr.write("Directory not readable: %s" % a) else: for n in names: fullname = os.path.join(a, n) if os.path.isfile(fullname): output = cStringIO.StringIO() print 'Testing %s' % fullname try: roundtrip(fullname, output) except Exception as e: print ' Failed to compile, exception is %s' % repr(e) elif os.path.isdir(fullname): testdir(fullname) def main(args): if args[0] == '--testdir': for a in args[1:]: testdir(a) else: for a in args: roundtrip(a) if __name__=='__main__': main(sys.argv[1:]) PK%L]g$$parser/example.pyonu[ ^c@sdZddlZddlZddlZddlZddlZddlmZmZdZdddYZ dddYZ d e e fd YZ d e fd YZ d e e fdYZ ddZejejdgffZejejejejejejejejejejejejejejej ej!ej"ej#ej$dgfffffffffffffffffej%dfffZ&dS(sSimple code to extract class & function docstrings from a module. This code is used as an example in the library reference manual in the section on using the parser module. Refer to the manual for a thorough discussion of the operation of this code. iN(tListTypet TupleTypecCsVt|j}tjjtjj|d}tj|}t|j |S(sRetrieve information from the parse tree of a source file. fileName Name of the file to read Python source code from. i( topentreadtostpathtbasenametsplitexttparsertsuitet ModuleInfottotuple(tfileNametsourceRtast((s+/usr/lib64/python2.7/Demo/parser/example.pytget_docss"t SuiteInfoBasecBsVeZdZdZddZdZdZdZdZ dZ dZ RS( tcCs,i|_i|_|r(|j|ndS(N(t _class_infot_function_infot _extract_info(tselfttree((s+/usr/lib64/python2.7/Demo/parser/example.pyt__init__!s  cCst|dkr2ttd|d\}}ntt|d\}}|rgt|d|_nx|dD]}tt|\}}|rr|d}|dtjkr|dd}t||j |scCs |jjS(N(Rtkeys(R((s+/usr/lib64/python2.7/Demo/parser/example.pytget_class_namesAscCs |j|S(N(R(RR)((s+/usr/lib64/python2.7/Demo/parser/example.pytget_class_infoDscCs/y|j|SWntk r*|j|SXdS(N(RtKeyErrorR(RR)((s+/usr/lib64/python2.7/Demo/parser/example.pyt __getitem__Gs N( t__name__t __module__RR+tNoneRRR*R,R.R/R1(((s+/usr/lib64/python2.7/Demo/parser/example.pyRs      t SuiteFuncInfocBseZdZdZRS(cCs |jjS(N(RR-(R((s+/usr/lib64/python2.7/Demo/parser/example.pytget_function_namesQscCs |j|S(N(R(RR)((s+/usr/lib64/python2.7/Demo/parser/example.pytget_function_infoTs(R2R3R6R7(((s+/usr/lib64/python2.7/Demo/parser/example.pyR5Ns R"cBseZddZRS(cCs5|dd|_tj||r*|dp-ddS(Niii(R+RRR4(RR((s+/usr/lib64/python2.7/Demo/parser/example.pyRYsN(R2R3R4R(((s+/usr/lib64/python2.7/Demo/parser/example.pyR"XsR$cBs&eZddZdZdZRS(cCs5|dd|_tj||r*|dp-ddS(Niii(R+RRR4(RR((s+/usr/lib64/python2.7/Demo/parser/example.pyR_scCs |jjS(N(RR-(R((s+/usr/lib64/python2.7/Demo/parser/example.pytget_method_namescscCs |j|S(N(R(RR)((s+/usr/lib64/python2.7/Demo/parser/example.pytget_method_infofsN(R2R3R4RR8R9(((s+/usr/lib64/python2.7/Demo/parser/example.pyR$^s  R cBseZdddZRS(scCsU||_tj|||rQtt|d\}}|rQ|d|_qQndS(NiR(R+RRRRR(RRR)R%R&((s+/usr/lib64/python2.7/Demo/parser/example.pyRks  N(R2R3R4R(((s+/usr/lib64/python2.7/Demo/parser/example.pyR jscCs|dkri}nt|tkr?|||dsF      1   + ?PK%L]ɣ=]]parser/unparse.pycnu[ ^c@sdZddlZddlZddlZddlZdeejjdZdZ dfdYZ ej dZ d Z d Zed kreejdndS( s'Usage: unparse.py iNt1eicCsZt|}y|t|Wntk r3n#Xx|D]}|||q;WdS(s<Call f on each item in seq, calling inter() in between. N(titertnextt StopIteration(tintertftseqtx((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt interleave s   tUnparsercBseZdZejdZddZdZdZdZ dZ dZ d Z d Z d Zd Zd ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZ dZ!dZ"d Z#d!Z$d"Z%d#Z&d$Z'd%Z(d&Z)d'Z*d(Z+d)Z,d*Z-d+Z.d,Z/d-Z0d.Z1d/Z2id0d16d2d36d4d56d6d76Z3d8Z4i d4d96d6d:6d;d<6d=d>6d?d@6dAdB6dCdD6dEdF6dGdH6dIdJ6dKdL6dMdN6Z5dOZ6i dPdQ6dRdS6dTdU6dVdW6dXdY6dZd[6d\d]6d^d_6d`da6dbdc6Z7ddZ8idee9j:6dfe9j;6Z<dgZ=dhZ>diZ?djZ@dkZAdlZBdmZCdnZDdoZEdpZFdqZGdrZHRS(ssMethods in this class recursively traverse an AST and output source code for the abstract syntax; original formatting is disregarded. cCsI||_g|_d|_|j||jjd|jjdS(sTUnparser(tree, file=sys.stdout) -> None. Print the source for tree to file.itN(Rtfuture_importst_indenttdispatchtwritetflush(tselfttreetfile((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt__init__s     R cCs#|jjdd|j|dS(sBIndent a piece of text, according to the current indentation levels s N(RRR (Rttext((s+/usr/lib64/python2.7/Demo/parser/unparse.pytfill'scCs|jj|dS(s+Append a piece of text to the current line.N(RR(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyR+scCs |jd|jd7_dS(s(Print ':', and increase the indentation.t:iN(RR (R((s+/usr/lib64/python2.7/Demo/parser/unparse.pytenter/s cCs|jd8_dS(sDecrease the indentation level.iN(R (R((s+/usr/lib64/python2.7/Demo/parser/unparse.pytleave4scCsXt|tr1x|D]}|j|qWdSt|d|jj}||dS(s:Dispatcher function, dispatching tree type T to method _T.Nt_(t isinstancetlistR tgetattrt __class__t__name__(RRtttmeth((s+/usr/lib64/python2.7/Demo/parser/unparse.pyR 8s  cCs%x|jD]}|j|q WdS(N(tbodyR (RRtstmt((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_ModuleIscCs|j|j|jdS(N(RR tvalue(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_ExprNs cs0jdtfdj|jdS(Nsimport cs jdS(Ns, (R((R(s+/usr/lib64/python2.7/Demo/parser/unparse.pytTR (RRR tnames(RR((Rs+/usr/lib64/python2.7/Demo/parser/unparse.pyt_ImportRs cs|jr8|jdkr8jjd|jDnjdjd|j|jruj|jnjdtfdj|jdS(Nt __future__css|]}|jVqdS(N(tname(t.0tn((s+/usr/lib64/python2.7/Demo/parser/unparse.pys Yssfrom t.s import cs jdS(Ns, (R((R(s+/usr/lib64/python2.7/Demo/parser/unparse.pyR&`R ( tmoduleR textendR'RRtlevelRR (RR((Rs+/usr/lib64/python2.7/Demo/parser/unparse.pyt _ImportFromVs    cCsL|jx+|jD] }|j||jdqW|j|jdS(Ns = (RttargetsR RR$(RRttarget((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Assignbs   cCsS|j|j|j|jd|j|jjjd|j|jdS(Nt s= ( RR R3RtbinoptopRRR$(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt _AugAssignis %cCs:|jd|jr6|jd|j|jndS(NtreturnR5(RR$RR (RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Returnos   cCs|jddS(Ntpass(R(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_PassuscCs|jddS(Ntbreak(R(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_BreakxscCs|jddS(Ntcontinue(R(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt _Continue{scs0jdtfdj|jdS(Nsdel cs jdS(Ns, (R((R(s+/usr/lib64/python2.7/Demo/parser/unparse.pyR&R (RRR R2(RR((Rs+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Delete~s cCsJ|jd|j|j|jrF|jd|j|jndS(Nsassert s, (RR ttesttmsgR(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Asserts    cCss|jd|j|j|jrF|jd|j|jn|jro|jd|j|jndS(Nsexec s in s, (RR R!tglobalsRtlocals(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Execs     cCs|jdt}|jrB|jd|j|jt}nx:|jD]/}|rh|jdnt}|j|qLW|js|jdndS(Nsprint s>>s, t,(RtFalsetdestRR tTruetvaluestnl(RRtdo_commate((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Prints     cs0jdtfdj|jdS(Nsglobal cs jdS(Ns, (R((R(s+/usr/lib64/python2.7/Demo/parser/unparse.pyR&R (RRRR'(RR((Rs+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Globals cCsT|jd|jd|jrC|jd|j|jn|jddS(Nt(tyieldR5t)(RR$R (RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Yields     cCs|jd|jr)|j|jn|jrR|jd|j|jn|jr{|jd|j|jndS(Nsraise s, (RttypeR tinstRttback(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Raises      cCs|jd|j|j|j|jx|jD]}|j|q;W|jr|jd|j|j|j|jndS(Nttrytelse(RRR R!Rthandlerstorelse(RRtex((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt _TryExcepts      cCst|jdkrAt|jdtjrA|j|jn1|jd|j|j|j|j|jd|j|j|j |jdS(NiiRZtfinally( tlenR!Rtastt TryExceptR RRRt finalbody(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt _TryFinallys.     cCs|jd|jr6|jd|j|jn|jr_|jd|j|jn|j|j|j|jdS(NtexceptR5s as (RRVRR R*RR!R(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_ExceptHandlers      cCs|jdx+|jD] }|jd|j|qW|jd|j|jr|jdx+|jD] }|j||jdqoW|jdn|j|j|j|jdS(Ns t@sclass RRs, RT( Rtdecorator_listRR R*tbasesRR!R(RRtdecota((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt _ClassDefs      cCs|jdx+|jD] }|jd|j|qW|jd|jd|j|j|jd|j|j|j|jdS(Ns Rhsdef RRRT( RRiRR R*targsRR!R(RRRk((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt _FunctionDefs    cCs|jd|j|j|jd|j|j|j|j|j|j|jr|jd|j|j|j|jndS(Nsfor s in R[( RR R3RRRR!RR](RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Fors       cCs|jd|j|j|j|j|j|jx|jrt|jdkrt|jdt j r|jd}|jd|j|j|j|j|j|jqDW|jr |jd|j|j|j|jndS(Nsif iiselif R[( RR RBRR!RR]RaRRbtIf(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_If s$   !      cCs|jd|j|j|j|j|j|j|jr~|jd|j|j|j|jndS(Nswhile R[(RR RBRR!RR](RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_While!s      cCsn|jd|j|j|jrF|jd|j|jn|j|j|j|jdS(Nswith s as (RR t context_exprt optional_varsRRR!R(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_With-s    cCsd|jkr(|jt|jnut|jtrW|jdt|jnFt|jtr|jt|jjdntst ddS(Ntunicode_literalstbtusshouldn't get here( R RtreprtsRtstrtunicodetlstripRItAssertionError(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Str8s"cCs|j|jdS(N(Rtid(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_NameEscCs.|jd|j|j|jddS(Nt`(RR R$(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_ReprHs cCsjt|j}|jdr.|jdn|j|jdt|jdrf|jdndS(Nt-RRtinfRT(RzR,t startswithRtreplacetINFSTR(RRtrepr_n((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_NumMs cs=jdtfdj|jjddS(Nt[cs jdS(Ns, (R((R(s+/usr/lib64/python2.7/Demo/parser/unparse.pyR&YR t](RRR telts(RR((Rs+/usr/lib64/python2.7/Demo/parser/unparse.pyt_ListWs cCsO|jd|j|jx|jD]}|j|q'W|jddS(NRR(RR teltt generators(RRtgen((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt _ListComp\s  cCsO|jd|j|jx|jD]}|j|q'W|jddS(NRRRT(RR RR(RRR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt _GeneratorExpcs  cCsO|jd|j|jx|jD]}|j|q'W|jddS(Nt{t}(RR RR(RRR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_SetCompjs  cCsl|jd|j|j|jd|j|jx|jD]}|j|qDW|jddS(NRs: R(RR tkeyR$R(RRR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt _DictCompqs  cCsl|jd|j|j|jd|j|jx+|jD] }|jd|j|qDWdS(Ns for s in s if (RR R3Rtifs(RRt if_clause((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_comprehensionzs   cCsh|jd|j|j|jd|j|j|jd|j|j|jddS(NRRs if s else RT(RR R!RBR](RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_IfExps   csL|jstjdtfdj|jjddS(NRcs jdS(Ns, (R((R(s+/usr/lib64/python2.7/Demo/parser/unparse.pyR&R R(RRRRR (RR((Rs+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Sets csUjdfd}tfd|t|j|jjddS(NRcs7|\}}j|jdj|dS(Ns: (R R(tpairtktv(R(s+/usr/lib64/python2.7/Demo/parser/unparse.pyt write_pairs   cs jdS(Ns, (R((R(s+/usr/lib64/python2.7/Demo/parser/unparse.pyR&R R(RRtziptkeysRL(RRR((Rs+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Dicts (cs{jdt|jdkrK|j\}j|jdntfdj|jjddS(NRRiRHcs jdS(Ns, (R((R(s+/usr/lib64/python2.7/Demo/parser/unparse.pyR&R RT(RRaRR R(RRR((Rs+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Tuples   t~tInverttnottNott+tUAddRtUSubcCs|jd|j|j|jjj|jdt|jtjrt|jtj r|jd|j |j|jdn|j |j|jddS(NRRR5RT( RtunopR7RRRRbRtoperandtNumR (RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_UnaryOps  * tAddtSubt*tMultt/tDivt%tMods<>tRShiftt|tBitOrt^tBitXort&tBitAnds//tFloorDivs**tPowcCsc|jd|j|j|jd|j|jjjd|j|j|jddS(NRRR5RT(RR tleftR6R7RRtright(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_BinOps  %s==tEqs!=tNotEqttGts>=tGtEtistIssis nottIsNottintInsnot intNotIncCs|jd|j|jxRt|j|jD];\}}|jd|j|jjd|j|q3W|jddS(NRRR5RT( RR RRtopst comparatorstcmpopsRR(RRtoRO((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Compares  ""tandtorcsWjddj|jjtfdj|jjddS(NRRs %s cs jS(N(R((R{R(s+/usr/lib64/python2.7/Demo/parser/unparse.pyR&R RT(RtboolopsR7RRR RL(RR((R{Rs+/usr/lib64/python2.7/Demo/parser/unparse.pyt_BoolOps "cCsk|j|jt|jtjrJt|jjtrJ|jdn|jd|j|jdS(NR5R-( R R$RRbRR,tintRtattr(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt _Attributes * cCs8|j|j|jdt}x:|jD]/}|rI|jdnt}|j|q-Wx:|jD]/}|r|jdnt}|j|qjW|jr|r|jdnt}|jd|j|jn|jr'|r|jdnt}|jd|j|jn|jddS(NRRs, Rs**RT( R tfuncRRIRnRKtkeywordststarargstkwargs(RRtcommaRO((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Calls4     cCs>|j|j|jd|j|j|jddS(NRR(R R$Rtslice(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt _Subscripts cCs|jddS(Ns...(R(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt _EllipsisscCs|j|jdS(N(R R$(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_IndexscCsr|jr|j|jn|jd|jrE|j|jn|jrn|jd|j|jndS(NR(tlowerR Rtuppertstep(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Slices     cs#tfdj|jdS(Ncs jdS(Ns, (R((R(s+/usr/lib64/python2.7/Demo/parser/unparse.pyR& R (RR tdims(RR((Rs+/usr/lib64/python2.7/Demo/parser/unparse.pyt _ExtSlice scCs't}dgt|jt|j|j}xot|j|D][\}}|r^t}n |jd|j|f|rC|jd|j|qCqCW|j r|rt}n |jd|jd|j|j n|j r#|rt}n |jd|jd|j ndS(Ns, t=Rs**( RKtNoneRaRntdefaultsRRIRR tvarargtkwarg(RRtfirstRRltd((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt _argumentss**          cCs1|j|j|jd|j|jdS(NR(RtargR R$(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_keyword)s cCsX|jd|jd|j|j|jd|j|j|jddS(NRRslambda s: RT(RR RnR!(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Lambda.s    cCs4|j|j|jr0|jd|jndS(Ns as (RR*tasname(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_alias6s (IRt __module__t__doc__tsyststdoutRRRRRR R#R%R(R1R4R8R:R<R>R@RARDRGRPRQRURYR_ReRgRmRoRpRrRsRvRRRRRRRRRRRRRRRRR6RRRRbtAndtOrRRRRRRRRRRRRR(((s+/usr/lib64/python2.7/Demo/parser/unparse.pyR s                                " &# -          cCsMt|d}|j}WdQXt||dtj}t||dS(Ntrtexec(topentreadtcompileRbt PyCF_ONLY_ASTR (tfilenametoutputtpyfiletsourceR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt roundtrip;scCsy5gtj|D]}|jdr|^q}Wn%tk r\tjjd|nXx|D]}tjj||}tjj |rt j }d|GHyt ||Wqt k r}dt|GHqXqdtjj|rdt|qdqdWdS(Ns.pysDirectory not readable: %ss Testing %ss$ Failed to compile, exception is %s(tostlistdirtendswithtOSErrorRtstderrRtpathtjointisfilet cStringIOtStringIORt ExceptionRztisdirttestdir(RlR,R'tfullnameR RO((s+/usr/lib64/python2.7/Demo/parser/unparse.pyRCs5    cCsQ|ddkr2x:|dD]}t|qWnx|D]}t|q9WdS(Nis --testdiri(RR(RnRl((s+/usr/lib64/python2.7/Demo/parser/unparse.pytmainUs  t__main__(RRRbRRRzt float_infot max_10_expRRR RRRRRtargv(((s+/usr/lib64/python2.7/Demo/parser/unparse.pyts     %   PK%L]n6parser/test_parser.pynuȯ#! /usr/bin/python2.7 # (Force the script to use the latest build.) # # test_parser.py import parser, traceback _numFailed = 0 def testChunk(t, fileName): global _numFailed print '----', fileName, try: st = parser.suite(t) tup = parser.st2tuple(st) # this discards the first ST; a huge memory savings when running # against a large source file like Tkinter.py. st = None new = parser.tuple2st(tup) except parser.ParserError, err: print print 'parser module raised exception on input file', fileName + ':' traceback.print_exc() _numFailed = _numFailed + 1 else: if tup != parser.st2tuple(new): print print 'parser module failed on input file', fileName _numFailed = _numFailed + 1 else: print 'o.k.' def testFile(fileName): t = open(fileName).read() testChunk(t, fileName) def test(): import sys args = sys.argv[1:] if not args: import glob args = glob.glob("*.py") args.sort() map(testFile, args) sys.exit(_numFailed != 0) if __name__ == '__main__': test() PK%L]$00parser/source.pycnu[ ^c@s&dZdddYZdZdS(sExmaple file to be parsed for the parsermodule example. The classes and functions in this module exist only to exhibit the ability of the handling information extraction from nested definitions using parse trees. They shouldn't interest you otherwise! tSimplecBs*eZdZdZdddYZRS(sThis class does very little.cCsdS(s This method does almost nothing.i((tself((s*/usr/lib64/python2.7/Demo/parser/source.pytmethod stNestedcBseZdZdZRS(sThis is a nested class.cCs d}|S(sMethod of Nested class.cSsdS(s#Function in method of Nested class.N((((s*/usr/lib64/python2.7/Demo/parser/source.pytnested_functions((RR((s*/usr/lib64/python2.7/Demo/parser/source.pyt nested_methods (t__name__t __module__t__doc__R(((s*/usr/lib64/python2.7/Demo/parser/source.pyRs((RRRRR(((s*/usr/lib64/python2.7/Demo/parser/source.pyRs cCsdS(s(This function lives at the module level.i((((s*/usr/lib64/python2.7/Demo/parser/source.pytfunctionsN((RRR (((s*/usr/lib64/python2.7/Demo/parser/source.pytsPK%L]^ parser/READMEnu[These files are from the large example of using the `parser' module. Refer to the Python Library Reference for more information. It also contains examples for the AST parser. Files: ------ FILES -- list of files associated with the parser module. README -- this file. docstring.py -- sample source file containing only a module docstring. example.py -- module that uses the `parser' module to extract information from the parse tree of Python source code. simple.py -- sample source containing a "short form" definition. source.py -- sample source code used to demonstrate ability to handle nested constructs easily using the functions and classes in example.py. test_parser.py program to put the parser module through its paces. test_unparse.py tests for the unparse module unparse.py AST (2.7) based example to recreate source code from an AST. Enjoy! PK%L]y=ZZparser/example.pynu["""Simple code to extract class & function docstrings from a module. This code is used as an example in the library reference manual in the section on using the parser module. Refer to the manual for a thorough discussion of the operation of this code. """ import os import parser import symbol import token import types from types import ListType, TupleType def get_docs(fileName): """Retrieve information from the parse tree of a source file. fileName Name of the file to read Python source code from. """ source = open(fileName).read() basename = os.path.basename(os.path.splitext(fileName)[0]) ast = parser.suite(source) return ModuleInfo(ast.totuple(), basename) class SuiteInfoBase: _docstring = '' _name = '' def __init__(self, tree = None): self._class_info = {} self._function_info = {} if tree: self._extract_info(tree) def _extract_info(self, tree): # extract docstring if len(tree) == 2: found, vars = match(DOCSTRING_STMT_PATTERN[1], tree[1]) else: found, vars = match(DOCSTRING_STMT_PATTERN, tree[3]) if found: self._docstring = eval(vars['docstring']) # discover inner definitions for node in tree[1:]: found, vars = match(COMPOUND_STMT_PATTERN, node) if found: cstmt = vars['compound'] if cstmt[0] == symbol.funcdef: name = cstmt[2][1] self._function_info[name] = FunctionInfo(cstmt) elif cstmt[0] == symbol.classdef: name = cstmt[2][1] self._class_info[name] = ClassInfo(cstmt) def get_docstring(self): return self._docstring def get_name(self): return self._name def get_class_names(self): return self._class_info.keys() def get_class_info(self, name): return self._class_info[name] def __getitem__(self, name): try: return self._class_info[name] except KeyError: return self._function_info[name] class SuiteFuncInfo: # Mixin class providing access to function names and info. def get_function_names(self): return self._function_info.keys() def get_function_info(self, name): return self._function_info[name] class FunctionInfo(SuiteInfoBase, SuiteFuncInfo): def __init__(self, tree = None): self._name = tree[2][1] SuiteInfoBase.__init__(self, tree and tree[-1] or None) class ClassInfo(SuiteInfoBase): def __init__(self, tree = None): self._name = tree[2][1] SuiteInfoBase.__init__(self, tree and tree[-1] or None) def get_method_names(self): return self._function_info.keys() def get_method_info(self, name): return self._function_info[name] class ModuleInfo(SuiteInfoBase, SuiteFuncInfo): def __init__(self, tree = None, name = ""): self._name = name SuiteInfoBase.__init__(self, tree) if tree: found, vars = match(DOCSTRING_STMT_PATTERN, tree[1]) if found: self._docstring = vars["docstring"] def match(pattern, data, vars=None): """Match `data' to `pattern', with variable extraction. pattern Pattern to match against, possibly containing variables. data Data to be checked and against which variables are extracted. vars Dictionary of variables which have already been found. If not provided, an empty dictionary is created. The `pattern' value may contain variables of the form ['varname'] which are allowed to match anything. The value that is matched is returned as part of a dictionary which maps 'varname' to the matched value. 'varname' is not required to be a string object, but using strings makes patterns and the code which uses them more readable. This function returns two values: a boolean indicating whether a match was found and a dictionary mapping variable names to their associated values. """ if vars is None: vars = {} if type(pattern) is ListType: # 'variables' are ['varname'] vars[pattern[0]] = data return 1, vars if type(pattern) is not TupleType: return (pattern == data), vars if len(data) != len(pattern): return 0, vars for pattern, data in map(None, pattern, data): same, vars = match(pattern, data, vars) if not same: break return same, vars # This pattern identifies compound statements, allowing them to be readily # differentiated from simple statements. # COMPOUND_STMT_PATTERN = ( symbol.stmt, (symbol.compound_stmt, ['compound']) ) # This pattern will match a 'stmt' node which *might* represent a docstring; # docstrings require that the statement which provides the docstring be the # first statement in the class or function, which this pattern does not check. # DOCSTRING_STMT_PATTERN = ( symbol.stmt, (symbol.simple_stmt, (symbol.small_stmt, (symbol.expr_stmt, (symbol.testlist, (symbol.test, (symbol.and_test, (symbol.not_test, (symbol.comparison, (symbol.expr, (symbol.xor_expr, (symbol.and_expr, (symbol.shift_expr, (symbol.arith_expr, (symbol.term, (symbol.factor, (symbol.power, (symbol.atom, (token.STRING, ['docstring']) )))))))))))))))), (token.NEWLINE, '') )) PK%L]Nk[[ parser/FILESnu[Demo/parser Doc/libparser.tex Lib/AST.py Lib/symbol.py Lib/token.py Modules/parsermodule.c PK%L]rXparser/docstring.pycnu[ ^c@s dZdS(sSome documentation. N(t__doc__(((s-/usr/lib64/python2.7/Demo/parser/docstring.pyttPK%L]cparser/simple.pyonu[ ^c@s dZdS(cCsdS(smaybe a docstringN((((s*/usr/lib64/python2.7/Demo/parser/simple.pytftN(R(((s*/usr/lib64/python2.7/Demo/parser/simple.pytRPK%L]64?!!parser/test_unparse.pyonu[ ^c@sddlZddlmZddlZddlZddlZddlZddlZddlZdZ dZ dZ dZ dZ dZd Zd Zd ejfd YZd efdYZdefdYZdZedkrendS(iN(t test_supportcCs(t|d}|j}WdQX|S(snRead and return the contents of a Python source file (as a string), taking into account the file encoding.trN(topentread(tfilenametpyfiletsource((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyt read_pyfile ssQdef f(): for x in range(10): break else: y = 2 z = 3 sIdef g(): while True: break else: y = 2 z = 3 sQfrom . import fred from .. import barney from .australia import shrimp as prawns s@f1(arg) @f2 class Foo: pass s=if cond1: suite1 elif cond2: suite2 else: suite3 s,if cond1: suite1 elif cond2: suite2 sctry: suite1 except ex1: suite2 except ex2: suite3 else: suite4 finally: suite5 t ASTTestCasecBseZdZddZRS(cCsDtj|}tj|}|jtj|tj|dS(N(tasttdumpt assertEqual(tselftast1tast2tdump1tdump2((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pytassertASTEqualMstinternalcCslt||dtj}tj}tj|||j}t||dtj}|j||dS(Ntexec( tcompileR t PyCF_ONLY_ASTt cStringIOtStringIOtunparsetUnparsertgetvalueR(R tcode1RR tunparse_buffertcode2R((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pytcheck_roundtripRs   (t__name__t __module__RR(((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyRLs tUnparseTestCasecBseZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZdZdZRS(cCs|jddS(Ns del x, y, z(R(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyttest_del_statement]scCs|jd|jddS(Ns45 << 2s13 >> 7(R(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyt test_shifts`s cCs|jtdS(N(Rtfor_else(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyt test_for_elsedscCs|jtdS(N(Rt while_else(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyttest_while_elsegscCsE|jd|jd|jd|jd|jddS(Ns(-1)**7s(-1.)**8s(-1j)**6snot True or FalsesTrue or not False(R(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyttest_unary_parensjs     cCs|jddS(Ns 3 .__abs__()(R(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyttest_integer_parensqscCs8|jd|jd|jd|jddS(Nt1e1000s-1e1000t1e1000js-1e1000j(R(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyttest_huge_floatts   cCs7|jttj d|jdtjddS(Nis-(%s)(Rtstrtsystmaxint(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyt test_min_intzscCsR|jd|jd|jd|jd|jd|jddS(Nt7js-7js-(7j)t0js-0js-(0j)(R(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyttest_imaginary_literals~s      cCsl|jd|jd|jd|jd|jd|jd|jd|jddS( Ns-0s-(0)s-0b0s-(0b0)s-0o0s-(0o0)s-0x0s-(0x0)(R(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyttest_negative_zeros       cCs|jddS(Ns(lambda: int)()(R(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyttest_lambda_parenthesesscCs|jd|jddS(Ns 1 < 4 <= 5sa is b is c is not d(R(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyttest_chained_comparisonss cCs_|jd|jd|jd|jd|jd|jd|jddS(Ns def f(): passsdef f(a): passsdef f(b = 2): passsdef f(a, b): passsdef f(a, b = 2): passsdef f(a = 5, b = 2): passsdef f(*args, **kwargs): pass(R(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyttest_function_argumentss      cCs|jtdS(N(Rtrelative_import(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyttest_relative_importscCs|jddS(Nsb'123'(R(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyt test_bytesscCs|jddS(Ns{'a', 'b', 'c'}(R(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyttest_set_literalscCs|jddS(Ns{x for x in range(5)}(R(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyttest_set_comprehensionscCs|jddS(Ns{x: x*x for x in range(10)}(R(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyttest_dict_comprehensionscCs|jtdS(N(Rtclass_decorator(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyttest_class_decoratorsscCs|jt|jtdS(N(Rtelif1telif2(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyt test_elifss cCs|jtdS(N(Rttry_except_finally(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyttest_try_except_finallys(RR R"R#R%R'R(R)R,R0R3R4R5R6R7R9R:R;R<R=R?RBRD(((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyR!Zs*                  tDirectoryTestCasecBs2eZdZdejjddfZdZRS(s:Test roundtrip behaviour on all files in Lib and Lib/test.tLibttestcCstjjtjjttjtj}g}x~|jD]s}tjj||}xUtj|D]D}|jdre|j d re|j tjj||qeqeWq:Wx<|D]4}t j rd|GHnt |}|j|qWdS(Ns.pytbads Testing %s(tostpathtjointdirnamet__file__tpardirttest_directoriestlistdirtendswitht startswithtappendRtverboseRR(R tdist_dirtnamestdttest_dirtnRR((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyt test_filess*'    (RR t__doc__RIRJRKRORZ(((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyREscCstjttdS(N(Rt run_unittestR!RE(((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyt test_mainst__main__(tunittestRGRRR.RIttokenizeR RRR$R&R8R>R@RARCtTestCaseRR!RER]R(((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyts*           _  PK%L]0parser/test_parser.pycnu[ Afc@sSddlZddlZdadZdZdZedkrOendS(iNicCsdG|Gy7tj|}tj|}d}tj|}Wn8tjk ry}HdG|dGHtjtdan2X|tj|krHdG|GHtdandGHdS(Ns----s,parser module raised exception on input filet:is"parser module failed on input fileso.k.( tparsertsuitetst2tupletNonettuple2stt ParserErrort tracebackt print_exct _numFailed(tttfileNametstttuptnewterr((s//usr/lib64/python2.7/Demo/parser/test_parser.pyt testChunk s     cCs#t|j}t||dS(N(topentreadR(R R ((s//usr/lib64/python2.7/Demo/parser/test_parser.pyttestFile!scCskddl}|jd}|sGddl}|jd}|jntt||jtdkdS(Niis*.pyi(tsystargvtglobtsorttmapRtexitR (RtargsR((s//usr/lib64/python2.7/Demo/parser/test_parser.pyttest%s     t__main__(RRR RRRt__name__(((s//usr/lib64/python2.7/Demo/parser/test_parser.pyts    PK%L]9\n]n]parser/unparse.pyonu[ ^c@sdZddlZddlZddlZddlZdeejjdZdZ dfdYZ ej dZ d Z d Zed kreejdndS( s'Usage: unparse.py iNt1eicCsZt|}y|t|Wntk r3n#Xx|D]}|||q;WdS(s<Call f on each item in seq, calling inter() in between. N(titertnextt StopIteration(tintertftseqtx((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt interleave s   tUnparsercBseZdZejdZddZdZdZdZ dZ dZ d Z d Z d Zd Zd ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZ dZ!dZ"d Z#d!Z$d"Z%d#Z&d$Z'd%Z(d&Z)d'Z*d(Z+d)Z,d*Z-d+Z.d,Z/d-Z0d.Z1d/Z2id0d16d2d36d4d56d6d76Z3d8Z4i d4d96d6d:6d;d<6d=d>6d?d@6dAdB6dCdD6dEdF6dGdH6dIdJ6dKdL6dMdN6Z5dOZ6i dPdQ6dRdS6dTdU6dVdW6dXdY6dZd[6d\d]6d^d_6d`da6dbdc6Z7ddZ8idee9j:6dfe9j;6Z<dgZ=dhZ>diZ?djZ@dkZAdlZBdmZCdnZDdoZEdpZFdqZGdrZHRS(ssMethods in this class recursively traverse an AST and output source code for the abstract syntax; original formatting is disregarded. cCsI||_g|_d|_|j||jjd|jjdS(sTUnparser(tree, file=sys.stdout) -> None. Print the source for tree to file.itN(Rtfuture_importst_indenttdispatchtwritetflush(tselfttreetfile((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt__init__s     R cCs#|jjdd|j|dS(sBIndent a piece of text, according to the current indentation levels s N(RRR (Rttext((s+/usr/lib64/python2.7/Demo/parser/unparse.pytfill'scCs|jj|dS(s+Append a piece of text to the current line.N(RR(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyR+scCs |jd|jd7_dS(s(Print ':', and increase the indentation.t:iN(RR (R((s+/usr/lib64/python2.7/Demo/parser/unparse.pytenter/s cCs|jd8_dS(sDecrease the indentation level.iN(R (R((s+/usr/lib64/python2.7/Demo/parser/unparse.pytleave4scCsXt|tr1x|D]}|j|qWdSt|d|jj}||dS(s:Dispatcher function, dispatching tree type T to method _T.Nt_(t isinstancetlistR tgetattrt __class__t__name__(RRtttmeth((s+/usr/lib64/python2.7/Demo/parser/unparse.pyR 8s  cCs%x|jD]}|j|q WdS(N(tbodyR (RRtstmt((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_ModuleIscCs|j|j|jdS(N(RR tvalue(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_ExprNs cs0jdtfdj|jdS(Nsimport cs jdS(Ns, (R((R(s+/usr/lib64/python2.7/Demo/parser/unparse.pytTR (RRR tnames(RR((Rs+/usr/lib64/python2.7/Demo/parser/unparse.pyt_ImportRs cs|jr8|jdkr8jjd|jDnjdjd|j|jruj|jnjdtfdj|jdS(Nt __future__css|]}|jVqdS(N(tname(t.0tn((s+/usr/lib64/python2.7/Demo/parser/unparse.pys Yssfrom t.s import cs jdS(Ns, (R((R(s+/usr/lib64/python2.7/Demo/parser/unparse.pyR&`R ( tmoduleR textendR'RRtlevelRR (RR((Rs+/usr/lib64/python2.7/Demo/parser/unparse.pyt _ImportFromVs    cCsL|jx+|jD] }|j||jdqW|j|jdS(Ns = (RttargetsR RR$(RRttarget((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Assignbs   cCsS|j|j|j|jd|j|jjjd|j|jdS(Nt s= ( RR R3RtbinoptopRRR$(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt _AugAssignis %cCs:|jd|jr6|jd|j|jndS(NtreturnR5(RR$RR (RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Returnos   cCs|jddS(Ntpass(R(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_PassuscCs|jddS(Ntbreak(R(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_BreakxscCs|jddS(Ntcontinue(R(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt _Continue{scs0jdtfdj|jdS(Nsdel cs jdS(Ns, (R((R(s+/usr/lib64/python2.7/Demo/parser/unparse.pyR&R (RRR R2(RR((Rs+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Delete~s cCsJ|jd|j|j|jrF|jd|j|jndS(Nsassert s, (RR ttesttmsgR(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Asserts    cCss|jd|j|j|jrF|jd|j|jn|jro|jd|j|jndS(Nsexec s in s, (RR R!tglobalsRtlocals(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Execs     cCs|jdt}|jrB|jd|j|jt}nx:|jD]/}|rh|jdnt}|j|qLW|js|jdndS(Nsprint s>>s, t,(RtFalsetdestRR tTruetvaluestnl(RRtdo_commate((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Prints     cs0jdtfdj|jdS(Nsglobal cs jdS(Ns, (R((R(s+/usr/lib64/python2.7/Demo/parser/unparse.pyR&R (RRRR'(RR((Rs+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Globals cCsT|jd|jd|jrC|jd|j|jn|jddS(Nt(tyieldR5t)(RR$R (RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Yields     cCs|jd|jr)|j|jn|jrR|jd|j|jn|jr{|jd|j|jndS(Nsraise s, (RttypeR tinstRttback(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Raises      cCs|jd|j|j|j|jx|jD]}|j|q;W|jr|jd|j|j|j|jndS(Nttrytelse(RRR R!Rthandlerstorelse(RRtex((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt _TryExcepts      cCst|jdkrAt|jdtjrA|j|jn1|jd|j|j|j|j|jd|j|j|j |jdS(NiiRZtfinally( tlenR!Rtastt TryExceptR RRRt finalbody(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt _TryFinallys.     cCs|jd|jr6|jd|j|jn|jr_|jd|j|jn|j|j|j|jdS(NtexceptR5s as (RRVRR R*RR!R(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_ExceptHandlers      cCs|jdx+|jD] }|jd|j|qW|jd|j|jr|jdx+|jD] }|j||jdqoW|jdn|j|j|j|jdS(Ns t@sclass RRs, RT( Rtdecorator_listRR R*tbasesRR!R(RRtdecota((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt _ClassDefs      cCs|jdx+|jD] }|jd|j|qW|jd|jd|j|j|jd|j|j|j|jdS(Ns Rhsdef RRRT( RRiRR R*targsRR!R(RRRk((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt _FunctionDefs    cCs|jd|j|j|jd|j|j|j|j|j|j|jr|jd|j|j|j|jndS(Nsfor s in R[( RR R3RRRR!RR](RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Fors       cCs|jd|j|j|j|j|j|jx|jrt|jdkrt|jdt j r|jd}|jd|j|j|j|j|j|jqDW|jr |jd|j|j|j|jndS(Nsif iiselif R[( RR RBRR!RR]RaRRbtIf(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_If s$   !      cCs|jd|j|j|j|j|j|j|jr~|jd|j|j|j|jndS(Nswhile R[(RR RBRR!RR](RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_While!s      cCsn|jd|j|j|jrF|jd|j|jn|j|j|j|jdS(Nswith s as (RR t context_exprt optional_varsRRR!R(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_With-s    cCsd|jkr(|jt|jnct|jtrW|jdt|jn4t|jtr|jt|jjdndS(Ntunicode_literalstbtu(R RtreprtsRtstrtunicodetlstrip(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Str8s"cCs|j|jdS(N(Rtid(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_NameEscCs.|jd|j|j|jddS(Nt`(RR R$(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_ReprHs cCsjt|j}|jdr.|jdn|j|jdt|jdrf|jdndS(Nt-RRtinfRT(RzR,t startswithRtreplacetINFSTR(RRtrepr_n((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_NumMs cs=jdtfdj|jjddS(Nt[cs jdS(Ns, (R((R(s+/usr/lib64/python2.7/Demo/parser/unparse.pyR&YR t](RRR telts(RR((Rs+/usr/lib64/python2.7/Demo/parser/unparse.pyt_ListWs cCsO|jd|j|jx|jD]}|j|q'W|jddS(NRR(RR teltt generators(RRtgen((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt _ListComp\s  cCsO|jd|j|jx|jD]}|j|q'W|jddS(NRRRT(RR RR(RRR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt _GeneratorExpcs  cCsO|jd|j|jx|jD]}|j|q'W|jddS(Nt{t}(RR RR(RRR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_SetCompjs  cCsl|jd|j|j|jd|j|jx|jD]}|j|qDW|jddS(NRs: R(RR tkeyR$R(RRR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt _DictCompqs  cCsl|jd|j|j|jd|j|jx+|jD] }|jd|j|qDWdS(Ns for s in s if (RR R3Rtifs(RRt if_clause((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_comprehensionzs   cCsh|jd|j|j|jd|j|j|jd|j|j|jddS(NRRs if s else RT(RR R!RBR](RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_IfExps   cs=jdtfdj|jjddS(NRcs jdS(Ns, (R((R(s+/usr/lib64/python2.7/Demo/parser/unparse.pyR&R R(RRR R(RR((Rs+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Sets csUjdfd}tfd|t|j|jjddS(NRcs7|\}}j|jdj|dS(Ns: (R R(tpairtktv(R(s+/usr/lib64/python2.7/Demo/parser/unparse.pyt write_pairs   cs jdS(Ns, (R((R(s+/usr/lib64/python2.7/Demo/parser/unparse.pyR&R R(RRtziptkeysRL(RRR((Rs+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Dicts (cs{jdt|jdkrK|j\}j|jdntfdj|jjddS(NRRiRHcs jdS(Ns, (R((R(s+/usr/lib64/python2.7/Demo/parser/unparse.pyR&R RT(RRaRR R(RRR((Rs+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Tuples   t~tInverttnottNott+tUAddRtUSubcCs|jd|j|j|jjj|jdt|jtjrt|jtj r|jd|j |j|jdn|j |j|jddS(NRRR5RT( RtunopR7RRRRbRtoperandtNumR (RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_UnaryOps  * tAddtSubt*tMultt/tDivt%tMods<>tRShiftt|tBitOrt^tBitXort&tBitAnds//tFloorDivs**tPowcCsc|jd|j|j|jd|j|jjjd|j|j|jddS(NRRR5RT(RR tleftR6R7RRtright(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_BinOps  %s==tEqs!=tNotEqttGts>=tGtEtistIssis nottIsNottintInsnot intNotIncCs|jd|j|jxRt|j|jD];\}}|jd|j|jjd|j|q3W|jddS(NRRR5RT( RR RRtopst comparatorstcmpopsRR(RRtoRO((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Compares  ""tandtorcsWjddj|jjtfdj|jjddS(NRRs %s cs jS(N(R((R{R(s+/usr/lib64/python2.7/Demo/parser/unparse.pyR&R RT(RtboolopsR7RRR RL(RR((R{Rs+/usr/lib64/python2.7/Demo/parser/unparse.pyt_BoolOps "cCsk|j|jt|jtjrJt|jjtrJ|jdn|jd|j|jdS(NR5R-( R R$RRbRR,tintRtattr(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt _Attributes * cCs8|j|j|jdt}x:|jD]/}|rI|jdnt}|j|q-Wx:|jD]/}|r|jdnt}|j|qjW|jr|r|jdnt}|jd|j|jn|jr'|r|jdnt}|jd|j|jn|jddS(NRRs, Rs**RT( R tfuncRRIRnRKtkeywordststarargstkwargs(RRtcommaRO((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Calls4     cCs>|j|j|jd|j|j|jddS(NRR(R R$Rtslice(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt _Subscripts cCs|jddS(Ns...(R(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt _EllipsisscCs|j|jdS(N(R R$(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_IndexscCsr|jr|j|jn|jd|jrE|j|jn|jrn|jd|j|jndS(NR(tlowerR Rtuppertstep(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Slices     cs#tfdj|jdS(Ncs jdS(Ns, (R((R(s+/usr/lib64/python2.7/Demo/parser/unparse.pyR& R (RR tdims(RR((Rs+/usr/lib64/python2.7/Demo/parser/unparse.pyt _ExtSlice scCs't}dgt|jt|j|j}xot|j|D][\}}|r^t}n |jd|j|f|rC|jd|j|qCqCW|j r|rt}n |jd|jd|j|j n|j r#|rt}n |jd|jd|j ndS(Ns, t=Rs**( RKtNoneRaRntdefaultsRRIRR tvarargtkwarg(RRtfirstRRltd((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt _argumentss**          cCs1|j|j|jd|j|jdS(NR(RtargR R$(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_keyword)s cCsX|jd|jd|j|j|jd|j|j|jddS(NRRslambda s: RT(RR RnR!(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_Lambda.s    cCs4|j|j|jr0|jd|jndS(Ns as (RR*tasname(RR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt_alias6s (IRt __module__t__doc__tsyststdoutRRRRRR R#R%R(R1R4R8R:R<R>R@RARDRGRPRQRURYR_ReRgRmRoRpRrRsRvRRRRRRRRRRRRRRRRR6RRRRbtAndtOrRRRRRRRRRRRRR(((s+/usr/lib64/python2.7/Demo/parser/unparse.pyR s                                " &# -          cCsMt|d}|j}WdQXt||dtj}t||dS(Ntrtexec(topentreadtcompileRbt PyCF_ONLY_ASTR (tfilenametoutputtpyfiletsourceR((s+/usr/lib64/python2.7/Demo/parser/unparse.pyt roundtrip;scCsy5gtj|D]}|jdr|^q}Wn%tk r\tjjd|nXx|D]}tjj||}tjj |rt j }d|GHyt ||Wqt k r}dt|GHqXqdtjj|rdt|qdqdWdS(Ns.pysDirectory not readable: %ss Testing %ss$ Failed to compile, exception is %s(tostlistdirtendswithtOSErrorRtstderrRtpathtjointisfilet cStringIOtStringIOR t ExceptionRztisdirttestdir(RlR,R'tfullnameR RO((s+/usr/lib64/python2.7/Demo/parser/unparse.pyRCs5    cCsQ|ddkr2x:|dD]}t|qWnx|D]}t|q9WdS(Nis --testdiri(RR (RnRl((s+/usr/lib64/python2.7/Demo/parser/unparse.pytmainUs  t__main__(RRRbRRRzt float_infot max_10_expRRR RR RRRtargv(((s+/usr/lib64/python2.7/Demo/parser/unparse.pyts     %   PK%L]qϭparser/simple.pynu[def f(): "maybe a docstring" PK%L]parser/test_unparse.pynu[import unittest from test import test_support import cStringIO import sys import os import tokenize import ast import unparse def read_pyfile(filename): """Read and return the contents of a Python source file (as a string), taking into account the file encoding.""" with open(filename, "r") as pyfile: source = pyfile.read() return source for_else = """\ def f(): for x in range(10): break else: y = 2 z = 3 """ while_else = """\ def g(): while True: break else: y = 2 z = 3 """ relative_import = """\ from . import fred from .. import barney from .australia import shrimp as prawns """ class_decorator = """\ @f1(arg) @f2 class Foo: pass """ elif1 = """\ if cond1: suite1 elif cond2: suite2 else: suite3 """ elif2 = """\ if cond1: suite1 elif cond2: suite2 """ try_except_finally = """\ try: suite1 except ex1: suite2 except ex2: suite3 else: suite4 finally: suite5 """ class ASTTestCase(unittest.TestCase): def assertASTEqual(self, ast1, ast2): dump1 = ast.dump(ast1) dump2 = ast.dump(ast2) self.assertEqual(ast.dump(ast1), ast.dump(ast2)) def check_roundtrip(self, code1, filename="internal"): ast1 = compile(code1, filename, "exec", ast.PyCF_ONLY_AST) unparse_buffer = cStringIO.StringIO() unparse.Unparser(ast1, unparse_buffer) code2 = unparse_buffer.getvalue() ast2 = compile(code2, filename, "exec", ast.PyCF_ONLY_AST) self.assertASTEqual(ast1, ast2) class UnparseTestCase(ASTTestCase): # Tests for specific bugs found in earlier versions of unparse def test_del_statement(self): self.check_roundtrip("del x, y, z") def test_shifts(self): self.check_roundtrip("45 << 2") self.check_roundtrip("13 >> 7") def test_for_else(self): self.check_roundtrip(for_else) def test_while_else(self): self.check_roundtrip(while_else) def test_unary_parens(self): self.check_roundtrip("(-1)**7") self.check_roundtrip("(-1.)**8") self.check_roundtrip("(-1j)**6") self.check_roundtrip("not True or False") self.check_roundtrip("True or not False") def test_integer_parens(self): self.check_roundtrip("3 .__abs__()") def test_huge_float(self): self.check_roundtrip("1e1000") self.check_roundtrip("-1e1000") self.check_roundtrip("1e1000j") self.check_roundtrip("-1e1000j") def test_min_int(self): self.check_roundtrip(str(-sys.maxint-1)) self.check_roundtrip("-(%s)" % (sys.maxint + 1)) def test_imaginary_literals(self): self.check_roundtrip("7j") self.check_roundtrip("-7j") self.check_roundtrip("-(7j)") self.check_roundtrip("0j") self.check_roundtrip("-0j") self.check_roundtrip("-(0j)") def test_negative_zero(self): self.check_roundtrip("-0") self.check_roundtrip("-(0)") self.check_roundtrip("-0b0") self.check_roundtrip("-(0b0)") self.check_roundtrip("-0o0") self.check_roundtrip("-(0o0)") self.check_roundtrip("-0x0") self.check_roundtrip("-(0x0)") def test_lambda_parentheses(self): self.check_roundtrip("(lambda: int)()") def test_chained_comparisons(self): self.check_roundtrip("1 < 4 <= 5") self.check_roundtrip("a is b is c is not d") def test_function_arguments(self): self.check_roundtrip("def f(): pass") self.check_roundtrip("def f(a): pass") self.check_roundtrip("def f(b = 2): pass") self.check_roundtrip("def f(a, b): pass") self.check_roundtrip("def f(a, b = 2): pass") self.check_roundtrip("def f(a = 5, b = 2): pass") self.check_roundtrip("def f(*args, **kwargs): pass") def test_relative_import(self): self.check_roundtrip(relative_import) def test_bytes(self): self.check_roundtrip("b'123'") def test_set_literal(self): self.check_roundtrip("{'a', 'b', 'c'}") def test_set_comprehension(self): self.check_roundtrip("{x for x in range(5)}") def test_dict_comprehension(self): self.check_roundtrip("{x: x*x for x in range(10)}") def test_class_decorators(self): self.check_roundtrip(class_decorator) def test_elifs(self): self.check_roundtrip(elif1) self.check_roundtrip(elif2) def test_try_except_finally(self): self.check_roundtrip(try_except_finally) class DirectoryTestCase(ASTTestCase): """Test roundtrip behaviour on all files in Lib and Lib/test.""" # test directories, relative to the root of the distribution test_directories = 'Lib', os.path.join('Lib', 'test') def test_files(self): # get names of files to test dist_dir = os.path.join(os.path.dirname(__file__), os.pardir, os.pardir) names = [] for d in self.test_directories: test_dir = os.path.join(dist_dir, d) for n in os.listdir(test_dir): if n.endswith('.py') and not n.startswith('bad'): names.append(os.path.join(test_dir, n)) for filename in names: if test_support.verbose: print('Testing %s' % filename) source = read_pyfile(filename) self.check_roundtrip(source) def test_main(): test_support.run_unittest(UnparseTestCase, DirectoryTestCase) if __name__ == '__main__': test_main() PK%L]cparser/simple.pycnu[ ^c@s dZdS(cCsdS(smaybe a docstringN((((s*/usr/lib64/python2.7/Demo/parser/simple.pytftN(R(((s*/usr/lib64/python2.7/Demo/parser/simple.pytRPK%L]Gparser/docstring.pynu["""Some documentation. """ PK%L]g$$parser/example.pycnu[ ^c@sdZddlZddlZddlZddlZddlZddlmZmZdZdddYZ dddYZ d e e fd YZ d e fd YZ d e e fdYZ ddZejejdgffZejejejejejejejejejejejejejejej ej!ej"ej#ej$dgfffffffffffffffffej%dfffZ&dS(sSimple code to extract class & function docstrings from a module. This code is used as an example in the library reference manual in the section on using the parser module. Refer to the manual for a thorough discussion of the operation of this code. iN(tListTypet TupleTypecCsVt|j}tjjtjj|d}tj|}t|j |S(sRetrieve information from the parse tree of a source file. fileName Name of the file to read Python source code from. i( topentreadtostpathtbasenametsplitexttparsertsuitet ModuleInfottotuple(tfileNametsourceRtast((s+/usr/lib64/python2.7/Demo/parser/example.pytget_docss"t SuiteInfoBasecBsVeZdZdZddZdZdZdZdZ dZ dZ RS( tcCs,i|_i|_|r(|j|ndS(N(t _class_infot_function_infot _extract_info(tselfttree((s+/usr/lib64/python2.7/Demo/parser/example.pyt__init__!s  cCst|dkr2ttd|d\}}ntt|d\}}|rgt|d|_nx|dD]}tt|\}}|rr|d}|dtjkr|dd}t||j |scCs |jjS(N(Rtkeys(R((s+/usr/lib64/python2.7/Demo/parser/example.pytget_class_namesAscCs |j|S(N(R(RR)((s+/usr/lib64/python2.7/Demo/parser/example.pytget_class_infoDscCs/y|j|SWntk r*|j|SXdS(N(RtKeyErrorR(RR)((s+/usr/lib64/python2.7/Demo/parser/example.pyt __getitem__Gs N( t__name__t __module__RR+tNoneRRR*R,R.R/R1(((s+/usr/lib64/python2.7/Demo/parser/example.pyRs      t SuiteFuncInfocBseZdZdZRS(cCs |jjS(N(RR-(R((s+/usr/lib64/python2.7/Demo/parser/example.pytget_function_namesQscCs |j|S(N(R(RR)((s+/usr/lib64/python2.7/Demo/parser/example.pytget_function_infoTs(R2R3R6R7(((s+/usr/lib64/python2.7/Demo/parser/example.pyR5Ns R"cBseZddZRS(cCs5|dd|_tj||r*|dp-ddS(Niii(R+RRR4(RR((s+/usr/lib64/python2.7/Demo/parser/example.pyRYsN(R2R3R4R(((s+/usr/lib64/python2.7/Demo/parser/example.pyR"XsR$cBs&eZddZdZdZRS(cCs5|dd|_tj||r*|dp-ddS(Niii(R+RRR4(RR((s+/usr/lib64/python2.7/Demo/parser/example.pyR_scCs |jjS(N(RR-(R((s+/usr/lib64/python2.7/Demo/parser/example.pytget_method_namescscCs |j|S(N(R(RR)((s+/usr/lib64/python2.7/Demo/parser/example.pytget_method_infofsN(R2R3R4RR8R9(((s+/usr/lib64/python2.7/Demo/parser/example.pyR$^s  R cBseZdddZRS(scCsU||_tj|||rQtt|d\}}|rQ|d|_qQndS(NiR(R+RRRRR(RRR)R%R&((s+/usr/lib64/python2.7/Demo/parser/example.pyRks  N(R2R3R4R(((s+/usr/lib64/python2.7/Demo/parser/example.pyR jscCs|dkri}nt|tkr?|||dsF      1   + ?PK%L]$00parser/source.pyonu[ ^c@s&dZdddYZdZdS(sExmaple file to be parsed for the parsermodule example. The classes and functions in this module exist only to exhibit the ability of the handling information extraction from nested definitions using parse trees. They shouldn't interest you otherwise! tSimplecBs*eZdZdZdddYZRS(sThis class does very little.cCsdS(s This method does almost nothing.i((tself((s*/usr/lib64/python2.7/Demo/parser/source.pytmethod stNestedcBseZdZdZRS(sThis is a nested class.cCs d}|S(sMethod of Nested class.cSsdS(s#Function in method of Nested class.N((((s*/usr/lib64/python2.7/Demo/parser/source.pytnested_functions((RR((s*/usr/lib64/python2.7/Demo/parser/source.pyt nested_methods (t__name__t __module__t__doc__R(((s*/usr/lib64/python2.7/Demo/parser/source.pyRs((RRRRR(((s*/usr/lib64/python2.7/Demo/parser/source.pyRs cCsdS(s(This function lives at the module level.i((((s*/usr/lib64/python2.7/Demo/parser/source.pytfunctionsN((RRR (((s*/usr/lib64/python2.7/Demo/parser/source.pytsPK%L]rXparser/docstring.pyonu[ ^c@s dZdS(sSome documentation. N(t__doc__(((s-/usr/lib64/python2.7/Demo/parser/docstring.pyttPK%L]GjDparser/source.pynu["""Exmaple file to be parsed for the parsermodule example. The classes and functions in this module exist only to exhibit the ability of the handling information extraction from nested definitions using parse trees. They shouldn't interest you otherwise! """ class Simple: "This class does very little." def method(self): "This method does almost nothing." return 1 class Nested: "This is a nested class." def nested_method(self): "Method of Nested class." def nested_function(): "Function in method of Nested class." pass return nested_function def function(): "This function lives at the module level." return 0 PK%L]64?!!parser/test_unparse.pycnu[ ^c@sddlZddlmZddlZddlZddlZddlZddlZddlZdZ dZ dZ dZ dZ dZd Zd Zd ejfd YZd efdYZdefdYZdZedkrendS(iN(t test_supportcCs(t|d}|j}WdQX|S(snRead and return the contents of a Python source file (as a string), taking into account the file encoding.trN(topentread(tfilenametpyfiletsource((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyt read_pyfile ssQdef f(): for x in range(10): break else: y = 2 z = 3 sIdef g(): while True: break else: y = 2 z = 3 sQfrom . import fred from .. import barney from .australia import shrimp as prawns s@f1(arg) @f2 class Foo: pass s=if cond1: suite1 elif cond2: suite2 else: suite3 s,if cond1: suite1 elif cond2: suite2 sctry: suite1 except ex1: suite2 except ex2: suite3 else: suite4 finally: suite5 t ASTTestCasecBseZdZddZRS(cCsDtj|}tj|}|jtj|tj|dS(N(tasttdumpt assertEqual(tselftast1tast2tdump1tdump2((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pytassertASTEqualMstinternalcCslt||dtj}tj}tj|||j}t||dtj}|j||dS(Ntexec( tcompileR t PyCF_ONLY_ASTt cStringIOtStringIOtunparsetUnparsertgetvalueR(R tcode1RR tunparse_buffertcode2R((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pytcheck_roundtripRs   (t__name__t __module__RR(((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyRLs tUnparseTestCasecBseZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZdZdZRS(cCs|jddS(Ns del x, y, z(R(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyttest_del_statement]scCs|jd|jddS(Ns45 << 2s13 >> 7(R(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyt test_shifts`s cCs|jtdS(N(Rtfor_else(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyt test_for_elsedscCs|jtdS(N(Rt while_else(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyttest_while_elsegscCsE|jd|jd|jd|jd|jddS(Ns(-1)**7s(-1.)**8s(-1j)**6snot True or FalsesTrue or not False(R(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyttest_unary_parensjs     cCs|jddS(Ns 3 .__abs__()(R(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyttest_integer_parensqscCs8|jd|jd|jd|jddS(Nt1e1000s-1e1000t1e1000js-1e1000j(R(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyttest_huge_floatts   cCs7|jttj d|jdtjddS(Nis-(%s)(Rtstrtsystmaxint(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyt test_min_intzscCsR|jd|jd|jd|jd|jd|jddS(Nt7js-7js-(7j)t0js-0js-(0j)(R(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyttest_imaginary_literals~s      cCsl|jd|jd|jd|jd|jd|jd|jd|jddS( Ns-0s-(0)s-0b0s-(0b0)s-0o0s-(0o0)s-0x0s-(0x0)(R(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyttest_negative_zeros       cCs|jddS(Ns(lambda: int)()(R(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyttest_lambda_parenthesesscCs|jd|jddS(Ns 1 < 4 <= 5sa is b is c is not d(R(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyttest_chained_comparisonss cCs_|jd|jd|jd|jd|jd|jd|jddS(Ns def f(): passsdef f(a): passsdef f(b = 2): passsdef f(a, b): passsdef f(a, b = 2): passsdef f(a = 5, b = 2): passsdef f(*args, **kwargs): pass(R(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyttest_function_argumentss      cCs|jtdS(N(Rtrelative_import(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyttest_relative_importscCs|jddS(Nsb'123'(R(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyt test_bytesscCs|jddS(Ns{'a', 'b', 'c'}(R(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyttest_set_literalscCs|jddS(Ns{x for x in range(5)}(R(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyttest_set_comprehensionscCs|jddS(Ns{x: x*x for x in range(10)}(R(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyttest_dict_comprehensionscCs|jtdS(N(Rtclass_decorator(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyttest_class_decoratorsscCs|jt|jtdS(N(Rtelif1telif2(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyt test_elifss cCs|jtdS(N(Rttry_except_finally(R ((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyttest_try_except_finallys(RR R"R#R%R'R(R)R,R0R3R4R5R6R7R9R:R;R<R=R?RBRD(((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyR!Zs*                  tDirectoryTestCasecBs2eZdZdejjddfZdZRS(s:Test roundtrip behaviour on all files in Lib and Lib/test.tLibttestcCstjjtjjttjtj}g}x~|jD]s}tjj||}xUtj|D]D}|jdre|j d re|j tjj||qeqeWq:Wx<|D]4}t j rd|GHnt |}|j|qWdS(Ns.pytbads Testing %s(tostpathtjointdirnamet__file__tpardirttest_directoriestlistdirtendswitht startswithtappendRtverboseRR(R tdist_dirtnamestdttest_dirtnRR((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyt test_filess*'    (RR t__doc__RIRJRKRORZ(((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyREscCstjttdS(N(Rt run_unittestR!RE(((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyt test_mainst__main__(tunittestRGRRR.RIttokenizeR RRR$R&R8R>R@RARCtTestCaseRR!RER]R(((s0/usr/lib64/python2.7/Demo/parser/test_unparse.pyts*           _  PK%L]0parser/test_parser.pyonu[ Afc@sSddlZddlZdadZdZdZedkrOendS(iNicCsdG|Gy7tj|}tj|}d}tj|}Wn8tjk ry}HdG|dGHtjtdan2X|tj|krHdG|GHtdandGHdS(Ns----s,parser module raised exception on input filet:is"parser module failed on input fileso.k.( tparsertsuitetst2tupletNonettuple2stt ParserErrort tracebackt print_exct _numFailed(tttfileNametstttuptnewterr((s//usr/lib64/python2.7/Demo/parser/test_parser.pyt testChunk s     cCs#t|j}t||dS(N(topentreadR(R R ((s//usr/lib64/python2.7/Demo/parser/test_parser.pyttestFile!scCskddl}|jd}|sGddl}|jd}|jntt||jtdkdS(Niis*.pyi(tsystargvtglobtsorttmapRtexitR (RtargsR((s//usr/lib64/python2.7/Demo/parser/test_parser.pyttest%s     t__main__(RRR RRRt__name__(((s//usr/lib64/python2.7/Demo/parser/test_parser.pyts    PK%L] c c curses/rain.pynuȯ#! /usr/bin/python2.7 # # $Id$ # # somebody should probably check the randrange()s... import curses from random import randrange def next_j(j): if j == 0: j = 4 else: j -= 1 if curses.has_colors(): z = randrange(0, 3) color = curses.color_pair(z) if z: color = color | curses.A_BOLD stdscr.attrset(color) return j def main(win): # we know that the first argument from curses.wrapper() is stdscr. # Initialize it globally for convenience. global stdscr stdscr = win if curses.has_colors(): bg = curses.COLOR_BLACK curses.init_pair(1, curses.COLOR_BLUE, bg) curses.init_pair(2, curses.COLOR_CYAN, bg) curses.nl() curses.noecho() # XXX curs_set() always returns ERR # curses.curs_set(0) stdscr.timeout(0) c = curses.COLS - 4 r = curses.LINES - 4 xpos = [0] * c ypos = [0] * r for j in range(4, -1, -1): xpos[j] = randrange(0, c) + 2 ypos[j] = randrange(0, r) + 2 j = 0 while True: x = randrange(0, c) + 2 y = randrange(0, r) + 2 stdscr.addch(y, x, ord('.')) stdscr.addch(ypos[j], xpos[j], ord('o')) j = next_j(j) stdscr.addch(ypos[j], xpos[j], ord('O')) j = next_j(j) stdscr.addch( ypos[j] - 1, xpos[j], ord('-')) stdscr.addstr(ypos[j], xpos[j] - 1, "|.|") stdscr.addch( ypos[j] + 1, xpos[j], ord('-')) j = next_j(j) stdscr.addch( ypos[j] - 2, xpos[j], ord('-')) stdscr.addstr(ypos[j] - 1, xpos[j] - 1, "/ \\") stdscr.addstr(ypos[j], xpos[j] - 2, "| O |") stdscr.addstr(ypos[j] + 1, xpos[j] - 1, "\\ /") stdscr.addch( ypos[j] + 2, xpos[j], ord('-')) j = next_j(j) stdscr.addch( ypos[j] - 2, xpos[j], ord(' ')) stdscr.addstr(ypos[j] - 1, xpos[j] - 1, " ") stdscr.addstr(ypos[j], xpos[j] - 2, " ") stdscr.addstr(ypos[j] + 1, xpos[j] - 1, " ") stdscr.addch( ypos[j] + 2, xpos[j], ord(' ')) xpos[j] = x ypos[j] = y ch = stdscr.getch() if ch == ord('q') or ch == ord('Q'): return elif ch == ord('s'): stdscr.nodelay(0) elif ch == ord(' '): stdscr.nodelay(1) curses.napms(50) curses.wrapper(main) PK%L]@@curses/tclock.pycnu[ Afc@sfddlTddlZddlZdZdZdZdZdZdZej edS( i(t*Ng@cCs|dkrdSdS(Niii((t_x((s*/usr/lib64/python2.7/Demo/curses/tclock.pytsign s cCs:ttt|t|tt|t|fS(N(tinttroundtASPECTtsintcos(tangletradius((s*/usr/lib64/python2.7/Demo/curses/tclock.pytA2XYscCstj|||dS(N(tstdscrtaddch(txtytcol((s*/usr/lib64/python2.7/Demo/curses/tclock.pytplotscCsttjr%tjtj|n||}||}t|d}t|d} t|} t|} |} |} || kr| |d}xtrt| | || |krdS|dkr| | 7} ||8}n| | 7} || 7}qWnr|| d}xatrot| | || |kr5dS|dkrX| | 7} || 8}n| | 7} ||7}qWdS(Nii( tcursest has_colorsR tattrsett color_pairtabsRtTrueR(tpairtfrom_xtfrom_ytx2ty2tchtdxtdytaxtaytsxtsyR Rtd((s*/usr/lib64/python2.7/Demo/curses/tclock.pytdlines>                  cCs$|ad}tj}tjdtjdtjrtjdtj|tjdtj|tjdtj |ntj dd}tj d}t |dt |td}d|d}|d}d|d}xetdd D]T} | dd td } t| |\} } tj|| || d | dqWtjddd t|dd}xtrtjdtj} tj| }|d|dd}|d kr|d 8}n|ddtd}t||\}}|dtd }t||\}}|ddtd} t| |\} } td||||||tdtjtjtd||||||tdtjtjtjrtjtjdnt|| || tdtjr&tjtjdntjtj ddtj| tj |dddkr|d|kr|d}tj!ntj"}|tdkrdSt|| || tdtd||||||tdtd||||||tdqvWdS(Niiiiiiiii g@g(@s%ds5ASCII Clock by Howard Jones , 1994iigN@t#t.tOtqt (#R Rt COLOR_BLACKtnodelayttimeoutRt init_pairt COLOR_REDt COLOR_MAGENTAt COLOR_GREENtCOLStLINEStminRRtrangetpiR taddstrtmaxRtnapmsttimet localtimeR$tordRt A_REVERSEtattroffRRtctimetrefreshtbeeptgetch(twintlastbeeptmy_bgtcxtcyRtmradiusthradiustsradiustitsangletsdxtsdyttimttthourstmangletmdxtmdythanglethdxthdy((s*/usr/lib64/python2.7/Demo/curses/tclock.pytmainCsn     ! '      ''  # $   '( tmathRR9RRR RR$RWtwrapper(((s*/usr/lib64/python2.7/Demo/curses/tclock.pyts     + PPK%L]2Ocurses/life.pycnu[ Afc@sddlZddlZddlZddlZdd dYZdZdZdZdZe dkrej endS( iNt LifeBoardcBsPeZdZeddZdZdZdZedZ dZ RS(sEncapsulates a Life board Attributes: X,Y : horizontal and vertical size of the board state : dictionary mapping (x,y) to 0 or 1 Methods: display(update_board) -- If update_board is true, compute the next generation. Then display the state of the board and refresh the screen. erase() -- clear the entire board makeRandom() -- fill the board randomly set(y,x) -- set the given cell to Live; doesn't refresh the screen toggle(y,x) -- change the given cell from live to dead, or vice versa, and refresh the screen display t*cCs i|_||_|jj\}}|d|dd|_|_||_|jjd|jdd}|jjdd||jj|jdd|xUtd|jD]A}|jjd|dd|jjd||jddqW|jj dS(sCreate a new LifeBoard instance. scr -- curses screen object to use for display char -- character used to render live cells (default: '*') iit+t-it|N( tstatetscrtgetmaxyxtXtYtchartcleartaddstrtrangetrefresh(tselfRR R Rt border_linety((s(/usr/lib64/python2.7/Demo/curses/life.pyt__init__)s    %cCsc|dks6|j|ks6|dks6|j|krLtd||fnd|j||ftboardtxpostypostc((s(/usr/lib64/python2.7/Demo/curses/life.pytkeyloopsd                      "  " cCst|dS(N(RM(R4((s(/usr/lib64/python2.7/Demo/curses/life.pytmainst__main__(( R+tstringt tracebackRBRR6R7RMRNR-twrapper(((s(/usr/lib64/python2.7/Demo/curses/life.pyts$ n   ?  PK%L]ϐcurses/rain.pycnu[ Afc@s?ddlZddlmZdZdZejedS(iN(t randrangecCss|dkrd}n |d8}tjrotdd}tj|}|r_|tjB}ntj|n|S(Niiii(tcursest has_colorsRt color_pairtA_BOLDtstdscrtattrset(tjtztcolor((s(/usr/lib64/python2.7/Demo/curses/rain.pytnext_j s    c Cs|atjrJtj}tjdtj|tjdtj|ntjtjtj dtj d}tj d}dg|}dg|}xHt dddD]4}t d|d||s   EPK%L]̥TT curses/READMEnu[This is a collection of demos and tests for the curses module. ncurses demos ============= These demos are converted from the C versions in the ncurses distribution, and were contributed by Thomas Gellekum I didn't strive for a `pythonic' style, but bluntly copied the originals. I won't attempt to `beautify' the program anytime soon, but I wouldn't mind someone else making an effort in that direction, of course. ncurses.py -- currently only a panels demo rain.py -- raindrops keep falling on my desktop tclock.py -- ASCII clock, by Howard Jones xmas.py -- I'm dreaming of an ASCII christmas Please submit bugfixes and new contributions to the Python bug tracker. Other demos =========== life.py -- Simple game of Life repeat.py -- Repeatedly execute a shell command (like watch(1)) PK%L]r;5curses/life.pynuȯ#! /usr/bin/python2.7 # life.py -- A curses-based version of Conway's Game of Life. # Contributed by AMK # # An empty board will be displayed, and the following commands are available: # E : Erase the board # R : Fill the board randomly # S : Step for a single generation # C : Update continuously until a key is struck # Q : Quit # Cursor keys : Move the cursor around the board # Space or Enter : Toggle the contents of the cursor's position # # TODO : # Support the mouse # Use colour if available # Make board updates faster # import random, string, traceback import curses class LifeBoard: """Encapsulates a Life board Attributes: X,Y : horizontal and vertical size of the board state : dictionary mapping (x,y) to 0 or 1 Methods: display(update_board) -- If update_board is true, compute the next generation. Then display the state of the board and refresh the screen. erase() -- clear the entire board makeRandom() -- fill the board randomly set(y,x) -- set the given cell to Live; doesn't refresh the screen toggle(y,x) -- change the given cell from live to dead, or vice versa, and refresh the screen display """ def __init__(self, scr, char=ord('*')): """Create a new LifeBoard instance. scr -- curses screen object to use for display char -- character used to render live cells (default: '*') """ self.state = {} self.scr = scr Y, X = self.scr.getmaxyx() self.X, self.Y = X-2, Y-2-1 self.char = char self.scr.clear() # Draw a border around the board border_line = '+'+(self.X*'-')+'+' self.scr.addstr(0, 0, border_line) self.scr.addstr(self.Y+1,0, border_line) for y in range(0, self.Y): self.scr.addstr(1+y, 0, '|') self.scr.addstr(1+y, self.X+1, '|') self.scr.refresh() def set(self, y, x): """Set a cell to the live state""" if x<0 or self.X<=x or y<0 or self.Y<=y: raise ValueError, "Coordinates out of range %i,%i"% (y,x) self.state[x,y] = 1 def toggle(self, y, x): """Toggle a cell's state between live and dead""" if x<0 or self.X<=x or y<0 or self.Y<=y: raise ValueError, "Coordinates out of range %i,%i"% (y,x) if self.state.has_key( (x,y) ): del self.state[x,y] self.scr.addch(y+1, x+1, ' ') else: self.state[x,y] = 1 self.scr.addch(y+1, x+1, self.char) self.scr.refresh() def erase(self): """Clear the entire board and update the board display""" self.state = {} self.display(update_board=False) def display(self, update_board=True): """Display the whole board, optionally computing one generation""" M,N = self.X, self.Y if not update_board: for i in range(0, M): for j in range(0, N): if self.state.has_key( (i,j) ): self.scr.addch(j+1, i+1, self.char) else: self.scr.addch(j+1, i+1, ' ') self.scr.refresh() return d = {} self.boring = 1 for i in range(0, M): L = range( max(0, i-1), min(M, i+2) ) for j in range(0, N): s = 0 live = self.state.has_key( (i,j) ) for k in range( max(0, j-1), min(N, j+2) ): for l in L: if self.state.has_key( (l,k) ): s += 1 s -= live if s == 3: # Birth d[i,j] = 1 self.scr.addch(j+1, i+1, self.char) if not live: self.boring = 0 elif s == 2 and live: d[i,j] = 1 # Survival elif live: # Death self.scr.addch(j+1, i+1, ' ') self.boring = 0 self.state = d self.scr.refresh() def makeRandom(self): "Fill the board with a random pattern" self.state = {} for i in range(0, self.X): for j in range(0, self.Y): if random.random() > 0.5: self.set(j,i) def erase_menu(stdscr, menu_y): "Clear the space where the menu resides" stdscr.move(menu_y, 0) stdscr.clrtoeol() stdscr.move(menu_y+1, 0) stdscr.clrtoeol() def display_menu(stdscr, menu_y): "Display the menu of possible keystroke commands" erase_menu(stdscr, menu_y) stdscr.addstr(menu_y, 4, 'Use the cursor keys to move, and space or Enter to toggle a cell.') stdscr.addstr(menu_y+1, 4, 'E)rase the board, R)andom fill, S)tep once or C)ontinuously, Q)uit') def keyloop(stdscr): # Clear the screen and display the menu of keys stdscr.clear() stdscr_y, stdscr_x = stdscr.getmaxyx() menu_y = (stdscr_y-3)-1 display_menu(stdscr, menu_y) # Allocate a subwindow for the Life board and create the board object subwin = stdscr.subwin(stdscr_y-3, stdscr_x, 0, 0) board = LifeBoard(subwin, char=ord('*')) board.display(update_board=False) # xpos, ypos are the cursor's position xpos, ypos = board.X//2, board.Y//2 # Main loop: while (1): stdscr.move(1+ypos, 1+xpos) # Move the cursor c = stdscr.getch() # Get a keystroke if 00: ypos -= 1 elif c == curses.KEY_DOWN and ypos0: xpos -= 1 elif c == curses.KEY_RIGHT and xpos This simple program repeatedly (at 1-second intervals) executes the shell command given on the command line and displays the output (or as much of it as fits on the screen). It uses curses to paint each new output on top of the old output, so that if nothing changes, the screen doesn't change. This is handy to watch for changes in e.g. a directory or process listing. To end, hit Control-C. iNcCsVtjds"tGHtjdndjtjd}tj|d}|j}|j}|rtj dI|IJtj|nt j }zxt rB|j y|j|Wnt jk rnX|jtjdtj|d}|j}|j}|rtj dI|IJtj|qqWWdt jXdS(Niit trs Exit code:(tsystargvt__doc__texittjointostpopentreadtclosetstderrtcursestinitscrtTrueterasetaddstrterrortrefreshttimetsleeptendwin(tcmdtpttexttststw((s*/usr/lib64/python2.7/Demo/curses/repeat.pytmains6          (RRRRR R(((s*/usr/lib64/python2.7/Demo/curses/repeat.pyt s      PK%L]@@curses/tclock.pyonu[ Afc@sfddlTddlZddlZdZdZdZdZdZdZej edS( i(t*Ng@cCs|dkrdSdS(Niii((t_x((s*/usr/lib64/python2.7/Demo/curses/tclock.pytsign s cCs:ttt|t|tt|t|fS(N(tinttroundtASPECTtsintcos(tangletradius((s*/usr/lib64/python2.7/Demo/curses/tclock.pytA2XYscCstj|||dS(N(tstdscrtaddch(txtytcol((s*/usr/lib64/python2.7/Demo/curses/tclock.pytplotscCsttjr%tjtj|n||}||}t|d}t|d} t|} t|} |} |} || kr| |d}xtrt| | || |krdS|dkr| | 7} ||8}n| | 7} || 7}qWnr|| d}xatrot| | || |kr5dS|dkrX| | 7} || 8}n| | 7} ||7}qWdS(Nii( tcursest has_colorsR tattrsett color_pairtabsRtTrueR(tpairtfrom_xtfrom_ytx2ty2tchtdxtdytaxtaytsxtsyR Rtd((s*/usr/lib64/python2.7/Demo/curses/tclock.pytdlines>                  cCs$|ad}tj}tjdtjdtjrtjdtj|tjdtj|tjdtj |ntj dd}tj d}t |dt |td}d|d}|d}d|d}xetdd D]T} | dd td } t| |\} } tj|| || d | dqWtjddd t|dd}xtrtjdtj} tj| }|d|dd}|d kr|d 8}n|ddtd}t||\}}|dtd }t||\}}|ddtd} t| |\} } td||||||tdtjtjtd||||||tdtjtjtjrtjtjdnt|| || tdtjr&tjtjdntjtj ddtj| tj |dddkr|d|kr|d}tj!ntj"}|tdkrdSt|| || tdtd||||||tdtd||||||tdqvWdS(Niiiiiiiii g@g(@s%ds5ASCII Clock by Howard Jones , 1994iigN@t#t.tOtqt (#R Rt COLOR_BLACKtnodelayttimeoutRt init_pairt COLOR_REDt COLOR_MAGENTAt COLOR_GREENtCOLStLINEStminRRtrangetpiR taddstrtmaxRtnapmsttimet localtimeR$tordRt A_REVERSEtattroffRRtctimetrefreshtbeeptgetch(twintlastbeeptmy_bgtcxtcyRtmradiusthradiustsradiustitsangletsdxtsdyttimttthourstmangletmdxtmdythanglethdxthdy((s*/usr/lib64/python2.7/Demo/curses/tclock.pytmainCsn     ! '      ''  # $   '( tmathRR9RRR RR$RWtwrapper(((s*/usr/lib64/python2.7/Demo/curses/tclock.pyts     + PPK%L]cQcurses/ncurses.pycnu[ Afc@sxddlZddlmZddZdZdZdZdZdZd Z d Z ej e dS( iN(tpanelcCs|dkrt}n|jS(N(tNonetstdscrtgetch(twin((s+/usr/lib64/python2.7/Demo/curses/ncurses.pytwGetchar s cCs tdS(N(R(((s+/usr/lib64/python2.7/Demo/curses/ncurses.pytGetcharscCs'tdkrtn tjtdS(Ni(tnap_msecRtcursestnapms(((s+/usr/lib64/python2.7/Demo/curses/ncurses.pyt wait_a_whiles  cCs2tjtjddtjtj|dS(Nii(RtmoveRtLINEStclrtoeoltaddstr(ttext((s+/usr/lib64/python2.7/Demo/curses/ncurses.pytsaywhats c Cstj||||}tj|}tjr|tjkrNtj}n tj}|}tj||||j t dtj |n|j t dtj |S(Nt ( RtnewwinRt new_panelt has_colorst COLOR_BLUEt COLOR_WHITEt COLOR_BLACKt init_pairtbkgdsettordt color_pairtA_BOLD( tcolortrowstcolsttlyttlxRtpantfgtbg((s+/usr/lib64/python2.7/Demo/curses/ncurses.pytmkpanel s   "cCstjtjdS(N(Rt update_panelsRtdoupdate(((s+/usr/lib64/python2.7/Demo/curses/ncurses.pytpflush0s cCs|j}|jd}|jdd|jd||j|j|j\}}xVtd|dD]A}x8td|dD]#}|j|||j|qWqwWdS(Nis-pan%c-i( twindowtuserptrR RR tboxtgetmaxyxtrangetaddch(R"Rtnumtmaxytmaxxtytx((s+/usr/lib64/python2.7/Demo/curses/ncurses.pyt fill_panel4s   c Cs6|adaddddddgatjxTtdtjdD]<}x3tdtjD]}tjd ||d q^WqEWxtddD]}t tj tjd d tjd ddd}|j d t tj tjd dtjdtjdtjd }|j dt tj tjdtjd tjd tjd}|j dt tjtjd d tjd tjd d tjd}|j dt tjtjd d tjd tjd tjd d }|j dt|t|t|t|t||j|jttdttd|jdd|j|j|j|j|jtttd|jtttd|jtttd|jtjddtjd tttd|jtttd|jtjddtjdtttd|jtttd|jtttd |jtttd!|jtttd"|jtttd#|jtttd!|jtttd$|jttxDtdd%D]3}|j} |j} td&| jtjd d| jt||jtjd%|tjd | jtjd%d| jt|tttd'| jtjd%d| jt||jtjdd|d d%| jtjd d| jt|ttqWtd&|jtjd%|dtjd tttd(|jtttd#|jtttd"|jtttd)~tttd*|jtttd+~tttd,~tttd-~tttdkr(Pnd.aqWdS(/NittesttTESTs(**)s*()*s<-->tLASTis%di iitp1iitp2i tp3itp4tp5spress any key to continues(h3 s1 s2 s4 s5;press any key to continuess1; press any key to continuess2; press any key to continuesm2; press any key to continuess3; press any key to continuesm3; press any key to continueisb3; press any key to continuess4; press any key to continuess5; press any key to continuest3; press any key to continuest1; press any key to continuest2; press any key to continuest4; press any key to continueism4; press any key to continuesm5; press any key to continuest5; press any key to continuesd2; press any key to continuesh3; press any key to continuesd1; press any key to continuesd4; press any key to continuesd5; press any key to continueid(RRtmodtrefreshR-RR tCOLSRR%t COLOR_REDt set_userptrt COLOR_GREENt COLOR_YELLOWRt COLOR_MAGENTAR4thideR(RR R tshowtbottomttopR)( RR2R3R8R9R:R;R<titmptw4tw5((s+/usr/lib64/python2.7/Demo/curses/ncurses.pyt demo_panelsCsN !                                      "   "                   " #  &             ( RRRRRR RR%R(R4RLtwrapper(((s+/usr/lib64/python2.7/Demo/curses/ncurses.pyts         PK%L]lҗcurses/repeat.pynuȯ#! /usr/bin/python2.7 """repeat This simple program repeatedly (at 1-second intervals) executes the shell command given on the command line and displays the output (or as much of it as fits on the screen). It uses curses to paint each new output on top of the old output, so that if nothing changes, the screen doesn't change. This is handy to watch for changes in e.g. a directory or process listing. To end, hit Control-C. """ # Author: Guido van Rossum # Disclaimer: there's a Linux program named 'watch' that does the same # thing. Honestly, I didn't know of its existence when I wrote this! # To do: add features until it has the same functionality as watch(1); # then compare code size and development time. import os import sys import time import curses def main(): if not sys.argv[1:]: print __doc__ sys.exit(0) cmd = " ".join(sys.argv[1:]) p = os.popen(cmd, "r") text = p.read() sts = p.close() if sts: print >>sys.stderr, "Exit code:", sts sys.exit(sts) w = curses.initscr() try: while True: w.erase() try: w.addstr(text) except curses.error: pass w.refresh() time.sleep(1) p = os.popen(cmd, "r") text = p.read() sts = p.close() if sts: print >>sys.stderr, "Exit code:", sts sys.exit(sts) finally: curses.endwin() main() PK%L]cQcurses/ncurses.pyonu[ Afc@sxddlZddlmZddZdZdZdZdZdZd Z d Z ej e dS( iN(tpanelcCs|dkrt}n|jS(N(tNonetstdscrtgetch(twin((s+/usr/lib64/python2.7/Demo/curses/ncurses.pytwGetchar s cCs tdS(N(R(((s+/usr/lib64/python2.7/Demo/curses/ncurses.pytGetcharscCs'tdkrtn tjtdS(Ni(tnap_msecRtcursestnapms(((s+/usr/lib64/python2.7/Demo/curses/ncurses.pyt wait_a_whiles  cCs2tjtjddtjtj|dS(Nii(RtmoveRtLINEStclrtoeoltaddstr(ttext((s+/usr/lib64/python2.7/Demo/curses/ncurses.pytsaywhats c Cstj||||}tj|}tjr|tjkrNtj}n tj}|}tj||||j t dtj |n|j t dtj |S(Nt ( RtnewwinRt new_panelt has_colorst COLOR_BLUEt COLOR_WHITEt COLOR_BLACKt init_pairtbkgdsettordt color_pairtA_BOLD( tcolortrowstcolsttlyttlxRtpantfgtbg((s+/usr/lib64/python2.7/Demo/curses/ncurses.pytmkpanel s   "cCstjtjdS(N(Rt update_panelsRtdoupdate(((s+/usr/lib64/python2.7/Demo/curses/ncurses.pytpflush0s cCs|j}|jd}|jdd|jd||j|j|j\}}xVtd|dD]A}x8td|dD]#}|j|||j|qWqwWdS(Nis-pan%c-i( twindowtuserptrR RR tboxtgetmaxyxtrangetaddch(R"Rtnumtmaxytmaxxtytx((s+/usr/lib64/python2.7/Demo/curses/ncurses.pyt fill_panel4s   c Cs6|adaddddddgatjxTtdtjdD]<}x3tdtjD]}tjd ||d q^WqEWxtddD]}t tj tjd d tjd ddd}|j d t tj tjd dtjdtjdtjd }|j dt tj tjdtjd tjd tjd}|j dt tjtjd d tjd tjd d tjd}|j dt tjtjd d tjd tjd tjd d }|j dt|t|t|t|t||j|jttdttd|jdd|j|j|j|j|jtttd|jtttd|jtttd|jtjddtjd tttd|jtttd|jtjddtjdtttd|jtttd|jtttd |jtttd!|jtttd"|jtttd#|jtttd!|jtttd$|jttxDtdd%D]3}|j} |j} td&| jtjd d| jt||jtjd%|tjd | jtjd%d| jt|tttd'| jtjd%d| jt||jtjdd|d d%| jtjd d| jt|ttqWtd&|jtjd%|dtjd tttd(|jtttd#|jtttd"|jtttd)~tttd*|jtttd+~tttd,~tttd-~tttdkr(Pnd.aqWdS(/NittesttTESTs(**)s*()*s<-->tLASTis%di iitp1iitp2i tp3itp4tp5spress any key to continues(h3 s1 s2 s4 s5;press any key to continuess1; press any key to continuess2; press any key to continuesm2; press any key to continuess3; press any key to continuesm3; press any key to continueisb3; press any key to continuess4; press any key to continuess5; press any key to continuest3; press any key to continuest1; press any key to continuest2; press any key to continuest4; press any key to continueism4; press any key to continuesm5; press any key to continuest5; press any key to continuesd2; press any key to continuesh3; press any key to continuesd1; press any key to continuesd4; press any key to continuesd5; press any key to continueid(RRtmodtrefreshR-RR tCOLSRR%t COLOR_REDt set_userptrt COLOR_GREENt COLOR_YELLOWRt COLOR_MAGENTAR4thideR(RR R tshowtbottomttopR)( RR2R3R8R9R:R;R<titmptw4tw5((s+/usr/lib64/python2.7/Demo/curses/ncurses.pyt demo_panelsCsN !                                      "   "                   " #  &             ( RRRRRR RR%R(R4RLtwrapper(((s+/usr/lib64/python2.7/Demo/curses/ncurses.pyts         PK%L]٪  curses/tclock.pynuȯ#! /usr/bin/python2.7 # # $Id$ # # From tclock.c, Copyright Howard Jones , September 1994. from math import * import curses, time ASPECT = 2.2 def sign(_x): if _x < 0: return -1 return 1 def A2XY(angle, radius): return (int(round(ASPECT * radius * sin(angle))), int(round(radius * cos(angle)))) def plot(x, y, col): stdscr.addch(y, x, col) # draw a diagonal line using Bresenham's algorithm def dline(pair, from_x, from_y, x2, y2, ch): if curses.has_colors(): stdscr.attrset(curses.color_pair(pair)) dx = x2 - from_x dy = y2 - from_y ax = abs(dx * 2) ay = abs(dy * 2) sx = sign(dx) sy = sign(dy) x = from_x y = from_y if ax > ay: d = ay - ax // 2 while True: plot(x, y, ch) if x == x2: return if d >= 0: y += sy d -= ax x += sx d += ay else: d = ax - ay // 2 while True: plot(x, y, ch) if y == y2: return if d >= 0: x += sx d -= ay y += sy d += ax def main(win): global stdscr stdscr = win lastbeep = -1 my_bg = curses.COLOR_BLACK stdscr.nodelay(1) stdscr.timeout(0) # curses.curs_set(0) if curses.has_colors(): curses.init_pair(1, curses.COLOR_RED, my_bg) curses.init_pair(2, curses.COLOR_MAGENTA, my_bg) curses.init_pair(3, curses.COLOR_GREEN, my_bg) cx = (curses.COLS - 1) // 2 cy = curses.LINES // 2 ch = min( cy-1, int(cx // ASPECT) - 1) mradius = (3 * ch) // 4 hradius = ch // 2 sradius = 5 * ch // 6 for i in range(0, 12): sangle = (i + 1) * 2.0 * pi / 12.0 sdx, sdy = A2XY(sangle, sradius) stdscr.addstr(cy - sdy, cx + sdx, "%d" % (i + 1)) stdscr.addstr(0, 0, "ASCII Clock by Howard Jones , 1994") sradius = max(sradius-4, 8) while True: curses.napms(1000) tim = time.time() t = time.localtime(tim) hours = t[3] + t[4] / 60.0 if hours > 12.0: hours -= 12.0 mangle = t[4] * 2 * pi / 60.0 mdx, mdy = A2XY(mangle, mradius) hangle = hours * 2 * pi / 12.0 hdx, hdy = A2XY(hangle, hradius) sangle = t[5] * 2 * pi / 60.0 sdx, sdy = A2XY(sangle, sradius) dline(3, cx, cy, cx + mdx, cy - mdy, ord('#')) stdscr.attrset(curses.A_REVERSE) dline(2, cx, cy, cx + hdx, cy - hdy, ord('.')) stdscr.attroff(curses.A_REVERSE) if curses.has_colors(): stdscr.attrset(curses.color_pair(1)) plot(cx + sdx, cy - sdy, ord('O')) if curses.has_colors(): stdscr.attrset(curses.color_pair(0)) stdscr.addstr(curses.LINES - 2, 0, time.ctime(tim)) stdscr.refresh() if (t[5] % 5) == 0 and t[5] != lastbeep: lastbeep = t[5] curses.beep() ch = stdscr.getch() if ch == ord('q'): return 0 plot(cx + sdx, cy - sdy, ord(' ')) dline(0, cx, cy, cx + hdx, cy - hdy, ord(' ')) dline(0, cx, cy, cx + mdx, cy - mdy, ord(' ')) curses.wrapper(main) PK%L] fcfccurses/xmas.pynu[# asciixmas # December 1989 Larry Bartz Indianapolis, IN # # $Id$ # # I'm dreaming of an ascii character-based monochrome Christmas, # Just like the ones I used to know! # Via a full duplex communications channel, # At 9600 bits per second, # Even though it's kinda slow. # # I'm dreaming of an ascii character-based monochrome Christmas, # With ev'ry C program I write! # May your screen be merry and bright! # And may all your Christmases be amber or green, # (for reduced eyestrain and improved visibility)! # # # Notes on the Python version: # I used a couple of `try...except curses.error' to get around some functions # returning ERR. The errors come from using wrapping functions to fill # windows to the last character cell. The C version doesn't have this problem, # it simply ignores any return values. # import curses import sys FROMWHO = "Thomas Gellekum " def set_color(win, color): if curses.has_colors(): n = color + 1 curses.init_pair(n, color, my_bg) win.attroff(curses.A_COLOR) win.attron(curses.color_pair(n)) def unset_color(win): if curses.has_colors(): win.attrset(curses.color_pair(0)) def look_out(msecs): curses.napms(msecs) if stdscr.getch() != -1: curses.beep() sys.exit(0) def boxit(): for y in range(0, 20): stdscr.addch(y, 7, ord('|')) for x in range(8, 80): stdscr.addch(19, x, ord('_')) for x in range(0, 80): stdscr.addch(22, x, ord('_')) return def seas(): stdscr.addch(4, 1, ord('S')) stdscr.addch(6, 1, ord('E')) stdscr.addch(8, 1, ord('A')) stdscr.addch(10, 1, ord('S')) stdscr.addch(12, 1, ord('O')) stdscr.addch(14, 1, ord('N')) stdscr.addch(16, 1, ord("'")) stdscr.addch(18, 1, ord('S')) return def greet(): stdscr.addch(3, 5, ord('G')) stdscr.addch(5, 5, ord('R')) stdscr.addch(7, 5, ord('E')) stdscr.addch(9, 5, ord('E')) stdscr.addch(11, 5, ord('T')) stdscr.addch(13, 5, ord('I')) stdscr.addch(15, 5, ord('N')) stdscr.addch(17, 5, ord('G')) stdscr.addch(19, 5, ord('S')) return def fromwho(): stdscr.addstr(21, 13, FROMWHO) return def tree(): set_color(treescrn, curses.COLOR_GREEN) treescrn.addch(1, 11, ord('/')) treescrn.addch(2, 11, ord('/')) treescrn.addch(3, 10, ord('/')) treescrn.addch(4, 9, ord('/')) treescrn.addch(5, 9, ord('/')) treescrn.addch(6, 8, ord('/')) treescrn.addch(7, 7, ord('/')) treescrn.addch(8, 6, ord('/')) treescrn.addch(9, 6, ord('/')) treescrn.addch(10, 5, ord('/')) treescrn.addch(11, 3, ord('/')) treescrn.addch(12, 2, ord('/')) treescrn.addch(1, 13, ord('\\')) treescrn.addch(2, 13, ord('\\')) treescrn.addch(3, 14, ord('\\')) treescrn.addch(4, 15, ord('\\')) treescrn.addch(5, 15, ord('\\')) treescrn.addch(6, 16, ord('\\')) treescrn.addch(7, 17, ord('\\')) treescrn.addch(8, 18, ord('\\')) treescrn.addch(9, 18, ord('\\')) treescrn.addch(10, 19, ord('\\')) treescrn.addch(11, 21, ord('\\')) treescrn.addch(12, 22, ord('\\')) treescrn.addch(4, 10, ord('_')) treescrn.addch(4, 14, ord('_')) treescrn.addch(8, 7, ord('_')) treescrn.addch(8, 17, ord('_')) treescrn.addstr(13, 0, "//////////// \\\\\\\\\\\\\\\\\\\\\\\\") treescrn.addstr(14, 11, "| |") treescrn.addstr(15, 11, "|_|") unset_color(treescrn) treescrn.refresh() w_del_msg.refresh() return def balls(): treescrn.overlay(treescrn2) set_color(treescrn2, curses.COLOR_BLUE) treescrn2.addch(3, 9, ord('@')) treescrn2.addch(3, 15, ord('@')) treescrn2.addch(4, 8, ord('@')) treescrn2.addch(4, 16, ord('@')) treescrn2.addch(5, 7, ord('@')) treescrn2.addch(5, 17, ord('@')) treescrn2.addch(7, 6, ord('@')) treescrn2.addch(7, 18, ord('@')) treescrn2.addch(8, 5, ord('@')) treescrn2.addch(8, 19, ord('@')) treescrn2.addch(10, 4, ord('@')) treescrn2.addch(10, 20, ord('@')) treescrn2.addch(11, 2, ord('@')) treescrn2.addch(11, 22, ord('@')) treescrn2.addch(12, 1, ord('@')) treescrn2.addch(12, 23, ord('@')) unset_color(treescrn2) treescrn2.refresh() w_del_msg.refresh() return def star(): treescrn2.attrset(curses.A_BOLD | curses.A_BLINK) set_color(treescrn2, curses.COLOR_YELLOW) treescrn2.addch(0, 12, ord('*')) treescrn2.standend() unset_color(treescrn2) treescrn2.refresh() w_del_msg.refresh() return def strng1(): treescrn2.attrset(curses.A_BOLD | curses.A_BLINK) set_color(treescrn2, curses.COLOR_WHITE) treescrn2.addch(3, 13, ord('\'')) treescrn2.addch(3, 12, ord(':')) treescrn2.addch(3, 11, ord('.')) treescrn2.attroff(curses.A_BOLD | curses.A_BLINK) unset_color(treescrn2) treescrn2.refresh() w_del_msg.refresh() return def strng2(): treescrn2.attrset(curses.A_BOLD | curses.A_BLINK) set_color(treescrn2, curses.COLOR_WHITE) treescrn2.addch(5, 14, ord('\'')) treescrn2.addch(5, 13, ord(':')) treescrn2.addch(5, 12, ord('.')) treescrn2.addch(5, 11, ord(',')) treescrn2.addch(6, 10, ord('\'')) treescrn2.addch(6, 9, ord(':')) treescrn2.attroff(curses.A_BOLD | curses.A_BLINK) unset_color(treescrn2) treescrn2.refresh() w_del_msg.refresh() return def strng3(): treescrn2.attrset(curses.A_BOLD | curses.A_BLINK) set_color(treescrn2, curses.COLOR_WHITE) treescrn2.addch(7, 16, ord('\'')) treescrn2.addch(7, 15, ord(':')) treescrn2.addch(7, 14, ord('.')) treescrn2.addch(7, 13, ord(',')) treescrn2.addch(8, 12, ord('\'')) treescrn2.addch(8, 11, ord(':')) treescrn2.addch(8, 10, ord('.')) treescrn2.addch(8, 9, ord(',')) treescrn2.attroff(curses.A_BOLD | curses.A_BLINK) unset_color(treescrn2) treescrn2.refresh() w_del_msg.refresh() return def strng4(): treescrn2.attrset(curses.A_BOLD | curses.A_BLINK) set_color(treescrn2, curses.COLOR_WHITE) treescrn2.addch(9, 17, ord('\'')) treescrn2.addch(9, 16, ord(':')) treescrn2.addch(9, 15, ord('.')) treescrn2.addch(9, 14, ord(',')) treescrn2.addch(10, 13, ord('\'')) treescrn2.addch(10, 12, ord(':')) treescrn2.addch(10, 11, ord('.')) treescrn2.addch(10, 10, ord(',')) treescrn2.addch(11, 9, ord('\'')) treescrn2.addch(11, 8, ord(':')) treescrn2.addch(11, 7, ord('.')) treescrn2.addch(11, 6, ord(',')) treescrn2.addch(12, 5, ord('\'')) treescrn2.attroff(curses.A_BOLD | curses.A_BLINK) unset_color(treescrn2) treescrn2.refresh() w_del_msg.refresh() return def strng5(): treescrn2.attrset(curses.A_BOLD | curses.A_BLINK) set_color(treescrn2, curses.COLOR_WHITE) treescrn2.addch(11, 19, ord('\'')) treescrn2.addch(11, 18, ord(':')) treescrn2.addch(11, 17, ord('.')) treescrn2.addch(11, 16, ord(',')) treescrn2.addch(12, 15, ord('\'')) treescrn2.addch(12, 14, ord(':')) treescrn2.addch(12, 13, ord('.')) treescrn2.addch(12, 12, ord(',')) treescrn2.attroff(curses.A_BOLD | curses.A_BLINK) unset_color(treescrn2) # save a fully lit tree treescrn2.overlay(treescrn) treescrn2.refresh() w_del_msg.refresh() return def blinkit(): treescrn8.touchwin() for cycle in range(5): if cycle == 0: treescrn3.overlay(treescrn8) treescrn8.refresh() w_del_msg.refresh() break elif cycle == 1: treescrn4.overlay(treescrn8) treescrn8.refresh() w_del_msg.refresh() break elif cycle == 2: treescrn5.overlay(treescrn8) treescrn8.refresh() w_del_msg.refresh() break elif cycle == 3: treescrn6.overlay(treescrn8) treescrn8.refresh() w_del_msg.refresh() break elif cycle == 4: treescrn7.overlay(treescrn8) treescrn8.refresh() w_del_msg.refresh() break treescrn8.touchwin() # ALL ON treescrn.overlay(treescrn8) treescrn8.refresh() w_del_msg.refresh() return def deer_step(win, y, x): win.mvwin(y, x) win.refresh() w_del_msg.refresh() look_out(5) def reindeer(): y_pos = 0 for x_pos in range(70, 62, -1): if x_pos < 66: y_pos = 1 for looper in range(0, 4): dotdeer0.addch(y_pos, x_pos, ord('.')) dotdeer0.refresh() w_del_msg.refresh() dotdeer0.erase() dotdeer0.refresh() w_del_msg.refresh() look_out(50) y_pos = 2 for x_pos in range(x_pos - 1, 50, -1): for looper in range(0, 4): if x_pos < 56: y_pos = 3 try: stardeer0.addch(y_pos, x_pos, ord('*')) except curses.error: pass stardeer0.refresh() w_del_msg.refresh() stardeer0.erase() stardeer0.refresh() w_del_msg.refresh() else: dotdeer0.addch(y_pos, x_pos, ord('*')) dotdeer0.refresh() w_del_msg.refresh() dotdeer0.erase() dotdeer0.refresh() w_del_msg.refresh() x_pos = 58 for y_pos in range(2, 5): lildeer0.touchwin() lildeer0.refresh() w_del_msg.refresh() for looper in range(0, 4): deer_step(lildeer3, y_pos, x_pos) deer_step(lildeer2, y_pos, x_pos) deer_step(lildeer1, y_pos, x_pos) deer_step(lildeer2, y_pos, x_pos) deer_step(lildeer3, y_pos, x_pos) lildeer0.touchwin() lildeer0.refresh() w_del_msg.refresh() x_pos -= 2 x_pos = 35 for y_pos in range(5, 10): middeer0.touchwin() middeer0.refresh() w_del_msg.refresh() for looper in range(2): deer_step(middeer3, y_pos, x_pos) deer_step(middeer2, y_pos, x_pos) deer_step(middeer1, y_pos, x_pos) deer_step(middeer2, y_pos, x_pos) deer_step(middeer3, y_pos, x_pos) middeer0.touchwin() middeer0.refresh() w_del_msg.refresh() x_pos -= 3 look_out(300) y_pos = 1 for x_pos in range(8, 16): deer_step(bigdeer4, y_pos, x_pos) deer_step(bigdeer3, y_pos, x_pos) deer_step(bigdeer2, y_pos, x_pos) deer_step(bigdeer1, y_pos, x_pos) deer_step(bigdeer2, y_pos, x_pos) deer_step(bigdeer3, y_pos, x_pos) deer_step(bigdeer4, y_pos, x_pos) deer_step(bigdeer0, y_pos, x_pos) x_pos -= 1 for looper in range(0, 6): deer_step(lookdeer4, y_pos, x_pos) deer_step(lookdeer3, y_pos, x_pos) deer_step(lookdeer2, y_pos, x_pos) deer_step(lookdeer1, y_pos, x_pos) deer_step(lookdeer2, y_pos, x_pos) deer_step(lookdeer3, y_pos, x_pos) deer_step(lookdeer4, y_pos, x_pos) deer_step(lookdeer0, y_pos, x_pos) for y_pos in range(y_pos, 10): for looper in range(0, 2): deer_step(bigdeer4, y_pos, x_pos) deer_step(bigdeer3, y_pos, x_pos) deer_step(bigdeer2, y_pos, x_pos) deer_step(bigdeer1, y_pos, x_pos) deer_step(bigdeer2, y_pos, x_pos) deer_step(bigdeer3, y_pos, x_pos) deer_step(bigdeer4, y_pos, x_pos) deer_step(bigdeer0, y_pos, x_pos) y_pos -= 1 deer_step(lookdeer3, y_pos, x_pos) return def main(win): global stdscr stdscr = win global my_bg, y_pos, x_pos global treescrn, treescrn2, treescrn3, treescrn4 global treescrn5, treescrn6, treescrn7, treescrn8 global dotdeer0, stardeer0 global lildeer0, lildeer1, lildeer2, lildeer3 global middeer0, middeer1, middeer2, middeer3 global bigdeer0, bigdeer1, bigdeer2, bigdeer3, bigdeer4 global lookdeer0, lookdeer1, lookdeer2, lookdeer3, lookdeer4 global w_holiday, w_del_msg my_bg = curses.COLOR_BLACK # curses.curs_set(0) treescrn = curses.newwin(16, 27, 3, 53) treescrn2 = curses.newwin(16, 27, 3, 53) treescrn3 = curses.newwin(16, 27, 3, 53) treescrn4 = curses.newwin(16, 27, 3, 53) treescrn5 = curses.newwin(16, 27, 3, 53) treescrn6 = curses.newwin(16, 27, 3, 53) treescrn7 = curses.newwin(16, 27, 3, 53) treescrn8 = curses.newwin(16, 27, 3, 53) dotdeer0 = curses.newwin(3, 71, 0, 8) stardeer0 = curses.newwin(4, 56, 0, 8) lildeer0 = curses.newwin(7, 53, 0, 8) lildeer1 = curses.newwin(2, 4, 0, 0) lildeer2 = curses.newwin(2, 4, 0, 0) lildeer3 = curses.newwin(2, 4, 0, 0) middeer0 = curses.newwin(15, 42, 0, 8) middeer1 = curses.newwin(3, 7, 0, 0) middeer2 = curses.newwin(3, 7, 0, 0) middeer3 = curses.newwin(3, 7, 0, 0) bigdeer0 = curses.newwin(10, 23, 0, 0) bigdeer1 = curses.newwin(10, 23, 0, 0) bigdeer2 = curses.newwin(10, 23, 0, 0) bigdeer3 = curses.newwin(10, 23, 0, 0) bigdeer4 = curses.newwin(10, 23, 0, 0) lookdeer0 = curses.newwin(10, 25, 0, 0) lookdeer1 = curses.newwin(10, 25, 0, 0) lookdeer2 = curses.newwin(10, 25, 0, 0) lookdeer3 = curses.newwin(10, 25, 0, 0) lookdeer4 = curses.newwin(10, 25, 0, 0) w_holiday = curses.newwin(1, 27, 3, 27) w_del_msg = curses.newwin(1, 20, 23, 60) try: w_del_msg.addstr(0, 0, "Hit any key to quit") except curses.error: pass try: w_holiday.addstr(0, 0, "H A P P Y H O L I D A Y S") except curses.error: pass # set up the windows for our various reindeer lildeer1.addch(0, 0, ord('V')) lildeer1.addch(1, 0, ord('@')) lildeer1.addch(1, 1, ord('<')) lildeer1.addch(1, 2, ord('>')) try: lildeer1.addch(1, 3, ord('~')) except curses.error: pass lildeer2.addch(0, 0, ord('V')) lildeer2.addch(1, 0, ord('@')) lildeer2.addch(1, 1, ord('|')) lildeer2.addch(1, 2, ord('|')) try: lildeer2.addch(1, 3, ord('~')) except curses.error: pass lildeer3.addch(0, 0, ord('V')) lildeer3.addch(1, 0, ord('@')) lildeer3.addch(1, 1, ord('>')) lildeer3.addch(1, 2, ord('<')) try: lildeer2.addch(1, 3, ord('~')) # XXX except curses.error: pass middeer1.addch(0, 2, ord('y')) middeer1.addch(0, 3, ord('y')) middeer1.addch(1, 2, ord('0')) middeer1.addch(1, 3, ord('(')) middeer1.addch(1, 4, ord('=')) middeer1.addch(1, 5, ord(')')) middeer1.addch(1, 6, ord('~')) middeer1.addch(2, 3, ord('\\')) middeer1.addch(2, 5, ord('/')) middeer2.addch(0, 2, ord('y')) middeer2.addch(0, 3, ord('y')) middeer2.addch(1, 2, ord('0')) middeer2.addch(1, 3, ord('(')) middeer2.addch(1, 4, ord('=')) middeer2.addch(1, 5, ord(')')) middeer2.addch(1, 6, ord('~')) middeer2.addch(2, 3, ord('|')) middeer2.addch(2, 5, ord('|')) middeer3.addch(0, 2, ord('y')) middeer3.addch(0, 3, ord('y')) middeer3.addch(1, 2, ord('0')) middeer3.addch(1, 3, ord('(')) middeer3.addch(1, 4, ord('=')) middeer3.addch(1, 5, ord(')')) middeer3.addch(1, 6, ord('~')) middeer3.addch(2, 3, ord('/')) middeer3.addch(2, 5, ord('\\')) bigdeer1.addch(0, 17, ord('\\')) bigdeer1.addch(0, 18, ord('/')) bigdeer1.addch(0, 19, ord('\\')) bigdeer1.addch(0, 20, ord('/')) bigdeer1.addch(1, 18, ord('\\')) bigdeer1.addch(1, 20, ord('/')) bigdeer1.addch(2, 19, ord('|')) bigdeer1.addch(2, 20, ord('_')) bigdeer1.addch(3, 18, ord('/')) bigdeer1.addch(3, 19, ord('^')) bigdeer1.addch(3, 20, ord('0')) bigdeer1.addch(3, 21, ord('\\')) bigdeer1.addch(4, 17, ord('/')) bigdeer1.addch(4, 18, ord('/')) bigdeer1.addch(4, 19, ord('\\')) bigdeer1.addch(4, 22, ord('\\')) bigdeer1.addstr(5, 7, "^~~~~~~~~// ~~U") bigdeer1.addstr(6, 7, "( \\_____( /") # )) bigdeer1.addstr(7, 8, "( ) /") bigdeer1.addstr(8, 9, "\\\\ /") bigdeer1.addstr(9, 11, "\\>/>") bigdeer2.addch(0, 17, ord('\\')) bigdeer2.addch(0, 18, ord('/')) bigdeer2.addch(0, 19, ord('\\')) bigdeer2.addch(0, 20, ord('/')) bigdeer2.addch(1, 18, ord('\\')) bigdeer2.addch(1, 20, ord('/')) bigdeer2.addch(2, 19, ord('|')) bigdeer2.addch(2, 20, ord('_')) bigdeer2.addch(3, 18, ord('/')) bigdeer2.addch(3, 19, ord('^')) bigdeer2.addch(3, 20, ord('0')) bigdeer2.addch(3, 21, ord('\\')) bigdeer2.addch(4, 17, ord('/')) bigdeer2.addch(4, 18, ord('/')) bigdeer2.addch(4, 19, ord('\\')) bigdeer2.addch(4, 22, ord('\\')) bigdeer2.addstr(5, 7, "^~~~~~~~~// ~~U") bigdeer2.addstr(6, 7, "(( )____( /") # )) bigdeer2.addstr(7, 7, "( / |") bigdeer2.addstr(8, 8, "\\/ |") bigdeer2.addstr(9, 9, "|> |>") bigdeer3.addch(0, 17, ord('\\')) bigdeer3.addch(0, 18, ord('/')) bigdeer3.addch(0, 19, ord('\\')) bigdeer3.addch(0, 20, ord('/')) bigdeer3.addch(1, 18, ord('\\')) bigdeer3.addch(1, 20, ord('/')) bigdeer3.addch(2, 19, ord('|')) bigdeer3.addch(2, 20, ord('_')) bigdeer3.addch(3, 18, ord('/')) bigdeer3.addch(3, 19, ord('^')) bigdeer3.addch(3, 20, ord('0')) bigdeer3.addch(3, 21, ord('\\')) bigdeer3.addch(4, 17, ord('/')) bigdeer3.addch(4, 18, ord('/')) bigdeer3.addch(4, 19, ord('\\')) bigdeer3.addch(4, 22, ord('\\')) bigdeer3.addstr(5, 7, "^~~~~~~~~// ~~U") bigdeer3.addstr(6, 6, "( ()_____( /") # )) bigdeer3.addstr(7, 6, "/ / /") bigdeer3.addstr(8, 5, "|/ \\") bigdeer3.addstr(9, 5, "/> \\>") bigdeer4.addch(0, 17, ord('\\')) bigdeer4.addch(0, 18, ord('/')) bigdeer4.addch(0, 19, ord('\\')) bigdeer4.addch(0, 20, ord('/')) bigdeer4.addch(1, 18, ord('\\')) bigdeer4.addch(1, 20, ord('/')) bigdeer4.addch(2, 19, ord('|')) bigdeer4.addch(2, 20, ord('_')) bigdeer4.addch(3, 18, ord('/')) bigdeer4.addch(3, 19, ord('^')) bigdeer4.addch(3, 20, ord('0')) bigdeer4.addch(3, 21, ord('\\')) bigdeer4.addch(4, 17, ord('/')) bigdeer4.addch(4, 18, ord('/')) bigdeer4.addch(4, 19, ord('\\')) bigdeer4.addch(4, 22, ord('\\')) bigdeer4.addstr(5, 7, "^~~~~~~~~// ~~U") bigdeer4.addstr(6, 6, "( )______( /") # ) bigdeer4.addstr(7, 5, "(/ \\") # ) bigdeer4.addstr(8, 0, "v___= ----^") lookdeer1.addstr(0, 16, "\\/ \\/") lookdeer1.addstr(1, 17, "\\Y/ \\Y/") lookdeer1.addstr(2, 19, "\\=/") lookdeer1.addstr(3, 17, "^\\o o/^") lookdeer1.addstr(4, 17, "//( )") lookdeer1.addstr(5, 7, "^~~~~~~~~// \\O/") lookdeer1.addstr(6, 7, "( \\_____( /") # )) lookdeer1.addstr(7, 8, "( ) /") lookdeer1.addstr(8, 9, "\\\\ /") lookdeer1.addstr(9, 11, "\\>/>") lookdeer2.addstr(0, 16, "\\/ \\/") lookdeer2.addstr(1, 17, "\\Y/ \\Y/") lookdeer2.addstr(2, 19, "\\=/") lookdeer2.addstr(3, 17, "^\\o o/^") lookdeer2.addstr(4, 17, "//( )") lookdeer2.addstr(5, 7, "^~~~~~~~~// \\O/") lookdeer2.addstr(6, 7, "(( )____( /") # )) lookdeer2.addstr(7, 7, "( / |") lookdeer2.addstr(8, 8, "\\/ |") lookdeer2.addstr(9, 9, "|> |>") lookdeer3.addstr(0, 16, "\\/ \\/") lookdeer3.addstr(1, 17, "\\Y/ \\Y/") lookdeer3.addstr(2, 19, "\\=/") lookdeer3.addstr(3, 17, "^\\o o/^") lookdeer3.addstr(4, 17, "//( )") lookdeer3.addstr(5, 7, "^~~~~~~~~// \\O/") lookdeer3.addstr(6, 6, "( ()_____( /") # )) lookdeer3.addstr(7, 6, "/ / /") lookdeer3.addstr(8, 5, "|/ \\") lookdeer3.addstr(9, 5, "/> \\>") lookdeer4.addstr(0, 16, "\\/ \\/") lookdeer4.addstr(1, 17, "\\Y/ \\Y/") lookdeer4.addstr(2, 19, "\\=/") lookdeer4.addstr(3, 17, "^\\o o/^") lookdeer4.addstr(4, 17, "//( )") lookdeer4.addstr(5, 7, "^~~~~~~~~// \\O/") lookdeer4.addstr(6, 6, "( )______( /") # ) lookdeer4.addstr(7, 5, "(/ \\") # ) lookdeer4.addstr(8, 0, "v___= ----^") ############################################### curses.cbreak() stdscr.nodelay(1) while 1: stdscr.clear() treescrn.erase() w_del_msg.touchwin() treescrn.touchwin() treescrn2.erase() treescrn2.touchwin() treescrn8.erase() treescrn8.touchwin() stdscr.refresh() look_out(150) boxit() stdscr.refresh() look_out(150) seas() stdscr.refresh() greet() stdscr.refresh() look_out(150) fromwho() stdscr.refresh() look_out(150) tree() look_out(150) balls() look_out(150) star() look_out(150) strng1() strng2() strng3() strng4() strng5() # set up the windows for our blinking trees # # treescrn3 treescrn.overlay(treescrn3) # balls treescrn3.addch(4, 18, ord(' ')) treescrn3.addch(7, 6, ord(' ')) treescrn3.addch(8, 19, ord(' ')) treescrn3.addch(11, 22, ord(' ')) # star treescrn3.addch(0, 12, ord('*')) # strng1 treescrn3.addch(3, 11, ord(' ')) # strng2 treescrn3.addch(5, 13, ord(' ')) treescrn3.addch(6, 10, ord(' ')) # strng3 treescrn3.addch(7, 16, ord(' ')) treescrn3.addch(7, 14, ord(' ')) # strng4 treescrn3.addch(10, 13, ord(' ')) treescrn3.addch(10, 10, ord(' ')) treescrn3.addch(11, 8, ord(' ')) # strng5 treescrn3.addch(11, 18, ord(' ')) treescrn3.addch(12, 13, ord(' ')) # treescrn4 treescrn.overlay(treescrn4) # balls treescrn4.addch(3, 9, ord(' ')) treescrn4.addch(4, 16, ord(' ')) treescrn4.addch(7, 6, ord(' ')) treescrn4.addch(8, 19, ord(' ')) treescrn4.addch(11, 2, ord(' ')) treescrn4.addch(12, 23, ord(' ')) # star treescrn4.standout() treescrn4.addch(0, 12, ord('*')) treescrn4.standend() # strng1 treescrn4.addch(3, 13, ord(' ')) # strng2 # strng3 treescrn4.addch(7, 15, ord(' ')) treescrn4.addch(8, 11, ord(' ')) # strng4 treescrn4.addch(9, 16, ord(' ')) treescrn4.addch(10, 12, ord(' ')) treescrn4.addch(11, 8, ord(' ')) # strng5 treescrn4.addch(11, 18, ord(' ')) treescrn4.addch(12, 14, ord(' ')) # treescrn5 treescrn.overlay(treescrn5) # balls treescrn5.addch(3, 15, ord(' ')) treescrn5.addch(10, 20, ord(' ')) treescrn5.addch(12, 1, ord(' ')) # star treescrn5.addch(0, 12, ord(' ')) # strng1 treescrn5.addch(3, 11, ord(' ')) # strng2 treescrn5.addch(5, 12, ord(' ')) # strng3 treescrn5.addch(7, 14, ord(' ')) treescrn5.addch(8, 10, ord(' ')) # strng4 treescrn5.addch(9, 15, ord(' ')) treescrn5.addch(10, 11, ord(' ')) treescrn5.addch(11, 7, ord(' ')) # strng5 treescrn5.addch(11, 17, ord(' ')) treescrn5.addch(12, 13, ord(' ')) # treescrn6 treescrn.overlay(treescrn6) # balls treescrn6.addch(6, 7, ord(' ')) treescrn6.addch(7, 18, ord(' ')) treescrn6.addch(10, 4, ord(' ')) treescrn6.addch(11, 23, ord(' ')) # star treescrn6.standout() treescrn6.addch(0, 12, ord('*')) treescrn6.standend() # strng1 # strng2 treescrn6.addch(5, 11, ord(' ')) # strng3 treescrn6.addch(7, 13, ord(' ')) treescrn6.addch(8, 9, ord(' ')) # strng4 treescrn6.addch(9, 14, ord(' ')) treescrn6.addch(10, 10, ord(' ')) treescrn6.addch(11, 6, ord(' ')) # strng5 treescrn6.addch(11, 16, ord(' ')) treescrn6.addch(12, 12, ord(' ')) # treescrn7 treescrn.overlay(treescrn7) # balls treescrn7.addch(3, 15, ord(' ')) treescrn7.addch(6, 7, ord(' ')) treescrn7.addch(7, 18, ord(' ')) treescrn7.addch(10, 4, ord(' ')) treescrn7.addch(11, 22, ord(' ')) # star treescrn7.addch(0, 12, ord('*')) # strng1 treescrn7.addch(3, 12, ord(' ')) # strng2 treescrn7.addch(5, 13, ord(' ')) treescrn7.addch(6, 9, ord(' ')) # strng3 treescrn7.addch(7, 15, ord(' ')) treescrn7.addch(8, 11, ord(' ')) # strng4 treescrn7.addch(9, 16, ord(' ')) treescrn7.addch(10, 12, ord(' ')) treescrn7.addch(11, 8, ord(' ')) # strng5 treescrn7.addch(11, 18, ord(' ')) treescrn7.addch(12, 14, ord(' ')) look_out(150) reindeer() w_holiday.touchwin() w_holiday.refresh() w_del_msg.refresh() look_out(500) for i in range(0, 20): blinkit() curses.wrapper(main) PK%L]2Ocurses/life.pyonu[ Afc@sddlZddlZddlZddlZdd dYZdZdZdZdZe dkrej endS( iNt LifeBoardcBsPeZdZeddZdZdZdZedZ dZ RS(sEncapsulates a Life board Attributes: X,Y : horizontal and vertical size of the board state : dictionary mapping (x,y) to 0 or 1 Methods: display(update_board) -- If update_board is true, compute the next generation. Then display the state of the board and refresh the screen. erase() -- clear the entire board makeRandom() -- fill the board randomly set(y,x) -- set the given cell to Live; doesn't refresh the screen toggle(y,x) -- change the given cell from live to dead, or vice versa, and refresh the screen display t*cCs i|_||_|jj\}}|d|dd|_|_||_|jjd|jdd}|jjdd||jj|jdd|xUtd|jD]A}|jjd|dd|jjd||jddqW|jj dS(sCreate a new LifeBoard instance. scr -- curses screen object to use for display char -- character used to render live cells (default: '*') iit+t-it|N( tstatetscrtgetmaxyxtXtYtchartcleartaddstrtrangetrefresh(tselfRR R Rt border_linety((s(/usr/lib64/python2.7/Demo/curses/life.pyt__init__)s    %cCsc|dks6|j|ks6|dks6|j|krLtd||fnd|j||ftboardtxpostypostc((s(/usr/lib64/python2.7/Demo/curses/life.pytkeyloopsd                      "  " cCst|dS(N(RM(R4((s(/usr/lib64/python2.7/Demo/curses/life.pytmainst__main__(( R+tstringt tracebackRBRR6R7RMRNR-twrapper(((s(/usr/lib64/python2.7/Demo/curses/life.pyts$ n   ?  PK%L]ϐcurses/rain.pyonu[ Afc@s?ddlZddlmZdZdZejedS(iN(t randrangecCss|dkrd}n |d8}tjrotdd}tj|}|r_|tjB}ntj|n|S(Niiii(tcursest has_colorsRt color_pairtA_BOLDtstdscrtattrset(tjtztcolor((s(/usr/lib64/python2.7/Demo/curses/rain.pytnext_j s    c Cs|atjrJtj}tjdtj|tjdtj|ntjtjtj dtj d}tj d}dg|}dg|}xHt dddD]4}t d|d||s   EPK%L] XA?curses/ncurses.pynuȯ#! /usr/bin/python2.7 # # $Id$ # # (n)curses exerciser in Python, an interactive test for the curses # module. Currently, only the panel demos are ported. import curses from curses import panel def wGetchar(win = None): if win is None: win = stdscr return win.getch() def Getchar(): wGetchar() # # Panels tester # def wait_a_while(): if nap_msec == 1: Getchar() else: curses.napms(nap_msec) def saywhat(text): stdscr.move(curses.LINES - 1, 0) stdscr.clrtoeol() stdscr.addstr(text) def mkpanel(color, rows, cols, tly, tlx): win = curses.newwin(rows, cols, tly, tlx) pan = panel.new_panel(win) if curses.has_colors(): if color == curses.COLOR_BLUE: fg = curses.COLOR_WHITE else: fg = curses.COLOR_BLACK bg = color curses.init_pair(color, fg, bg) win.bkgdset(ord(' '), curses.color_pair(color)) else: win.bkgdset(ord(' '), curses.A_BOLD) return pan def pflush(): panel.update_panels() curses.doupdate() def fill_panel(pan): win = pan.window() num = pan.userptr()[1] win.move(1, 1) win.addstr("-pan%c-" % num) win.clrtoeol() win.box() maxy, maxx = win.getmaxyx() for y in range(2, maxy - 1): for x in range(1, maxx - 1): win.move(y, x) win.addch(num) def demo_panels(win): global stdscr, nap_msec, mod stdscr = win nap_msec = 1 mod = ["test", "TEST", "(**)", "*()*", "<-->", "LAST"] stdscr.refresh() for y in range(0, curses.LINES - 1): for x in range(0, curses.COLS): stdscr.addstr("%d" % ((y + x) % 10)) for y in range(0, 1): p1 = mkpanel(curses.COLOR_RED, curses.LINES // 2 - 2, curses.COLS // 8 + 1, 0, 0) p1.set_userptr("p1") p2 = mkpanel(curses.COLOR_GREEN, curses.LINES // 2 + 1, curses.COLS // 7, curses.LINES // 4, curses.COLS // 10) p2.set_userptr("p2") p3 = mkpanel(curses.COLOR_YELLOW, curses.LINES // 4, curses.COLS // 10, curses.LINES // 2, curses.COLS // 9) p3.set_userptr("p3") p4 = mkpanel(curses.COLOR_BLUE, curses.LINES // 2 - 2, curses.COLS // 8, curses.LINES // 2 - 2, curses.COLS // 3) p4.set_userptr("p4") p5 = mkpanel(curses.COLOR_MAGENTA, curses.LINES // 2 - 2, curses.COLS // 8, curses.LINES // 2, curses.COLS // 2 - 2) p5.set_userptr("p5") fill_panel(p1) fill_panel(p2) fill_panel(p3) fill_panel(p4) fill_panel(p5) p4.hide() p5.hide() pflush() saywhat("press any key to continue") wait_a_while() saywhat("h3 s1 s2 s4 s5;press any key to continue") p1.move(0, 0) p3.hide() p1.show() p2.show() p4.show() p5.show() pflush() wait_a_while() saywhat("s1; press any key to continue") p1.show() pflush() wait_a_while() saywhat("s2; press any key to continue") p2.show() pflush() wait_a_while() saywhat("m2; press any key to continue") p2.move(curses.LINES // 3 + 1, curses.COLS // 8) pflush() wait_a_while() saywhat("s3; press any key to continue") p3.show() pflush() wait_a_while() saywhat("m3; press any key to continue") p3.move(curses.LINES // 4 + 1, curses.COLS // 15) pflush() wait_a_while() saywhat("b3; press any key to continue") p3.bottom() pflush() wait_a_while() saywhat("s4; press any key to continue") p4.show() pflush() wait_a_while() saywhat("s5; press any key to continue") p5.show() pflush() wait_a_while() saywhat("t3; press any key to continue") p3.top() pflush() wait_a_while() saywhat("t1; press any key to continue") p1.show() pflush() wait_a_while() saywhat("t2; press any key to continue") p2.show() pflush() wait_a_while() saywhat("t3; press any key to continue") p3.show() pflush() wait_a_while() saywhat("t4; press any key to continue") p4.show() pflush() wait_a_while() for itmp in range(0, 6): w4 = p4.window() w5 = p5.window() saywhat("m4; press any key to continue") w4.move(curses.LINES // 8, 1) w4.addstr(mod[itmp]) p4.move(curses.LINES // 6, itmp * curses.COLS // 8) w5.move(curses.LINES // 6, 1) w5.addstr(mod[itmp]) pflush() wait_a_while() saywhat("m5; press any key to continue") w4.move(curses.LINES // 6, 1) w4.addstr(mod[itmp]) p5.move(curses.LINES // 3 - 1, itmp * 10 + 6) w5.move(curses.LINES // 8, 1) w5.addstr(mod[itmp]) pflush() wait_a_while() saywhat("m4; press any key to continue") p4.move(curses.LINES // 6, (itmp + 1) * curses.COLS // 8) pflush() wait_a_while() saywhat("t5; press any key to continue") p5.top() pflush() wait_a_while() saywhat("t2; press any key to continue") p2.top() pflush() wait_a_while() saywhat("t1; press any key to continue") p1.top() pflush() wait_a_while() saywhat("d2; press any key to continue") del p2 pflush() wait_a_while() saywhat("h3; press any key to continue") p3.hide() pflush() wait_a_while() saywhat("d1; press any key to continue") del p1 pflush() wait_a_while() saywhat("d4; press any key to continue") del p4 pflush() wait_a_while() saywhat("d5; press any key to continue") del p5 pflush() wait_a_while() if nap_msec == 1: break nap_msec = 100 # # one fine day there'll be the menu at this place # curses.wrapper(demo_panels) PK%L]`gjMMcurses/xmas.pyonu[ ^c@sddlZddlZdZdZdZdZdZdZdZd Z d Z d Z d Z d Z dZdZdZdZdZdZdZdZejedS(iNs Thomas Gellekum cCsVtjrR|d}tj||t|jtj|jtj|ndS(Ni(tcursest has_colorst init_pairtmy_bgtattrofftA_COLORtattront color_pair(twintcolortn((s(/usr/lib64/python2.7/Demo/curses/xmas.pyt set_colors   cCs)tjr%|jtjdndS(Ni(RRtattrsetR(R((s(/usr/lib64/python2.7/Demo/curses/xmas.pyt unset_color&s cCs=tj|tjdkr9tjtjdndS(Nii(Rtnapmststdscrtgetchtbeeptsystexit(tmsecs((s(/usr/lib64/python2.7/Demo/curses/xmas.pytlook_out*s  cCsx0tddD]}tj|dtdqWx0tddD]}tjd|tdqCWx0tddD]}tjd |tdqvWdS( Niiit|iiPit_i(trangeRtaddchtord(tytx((s(/usr/lib64/python2.7/Demo/curses/xmas.pytboxit0scCstjddtdtjddtdtjddtdtjddtdtjd dtd tjd dtd tjd dtdtjddtddS(NiitSitEitAi i tOitNit'i(RRR(((s(/usr/lib64/python2.7/Demo/curses/xmas.pytseas<scCstjddtdtjddtdtjddtdtjddtdtjddtd tjd dtd tjd dtd tjddtdtjddtddS(NiitGtRiRi i tTi tIiR"iiR(RRR(((s(/usr/lib64/python2.7/Demo/curses/xmas.pytgreetHscCstjddtdS(Nii (RtaddstrtFROMWHO(((s(/usr/lib64/python2.7/Demo/curses/xmas.pytfromwhoUscCs'tttjtjddtdtjddtdtjddtdtjddtdtjd dtdtjd d tdtjd d tdtjd d tdtjdd tdtjdd tdtjddtdtjd dtdtjddtdtjddtdtjddtdtjddtdtjd dtdtjd dtdtjd dtdtjd dtdtjddtdtjddtdtjddtdtjd dtdtjddtdtjddtdtjd d tdtjd dtdtjdddtjdddtjdddtttjt jdS(Nii t/iii ii iiiii i s\iiiiiiiiRis//////////// \\\\\\\\\\\\s| |s|_|( R ttreescrnRt COLOR_GREENRRR*R trefresht w_del_msg(((s(/usr/lib64/python2.7/Demo/curses/xmas.pyttreeYsH   cCstjttttjtjddtdtjddtdtjddtdtjddtdtjdd tdtjdd tdtjd d tdtjd d tdtjddtdtjdd tdtjddtdtjddtdtjddtdtjddtdtjddtdtjddtdtttj t j dS(Nii t@iiiiiiiiiii ii iii ii( R.toverlayt treescrn2R Rt COLOR_BLUERRR R0R1(((s(/usr/lib64/python2.7/Demo/curses/xmas.pytballss,    cCsltjtjtjBtttjtjddtdtj t ttj t j dS(Nii t*( R5R RtA_BOLDtA_BLINKR t COLOR_YELLOWRRtstandendR R0R1(((s(/usr/lib64/python2.7/Demo/curses/xmas.pytstars    cCstjtjtjBtttjtjddtdtjddtdtjddtdtj tjtjBt ttj t j dS(Nii s'i t:i t.( R5R RR9R:R t COLOR_WHITERRRR R0R1(((s(/usr/lib64/python2.7/Demo/curses/xmas.pytstrng1s   cCstjtjtjBtttjtjddtdtjddtdtjddtdtjddtd tjd d tdtjd d tdtj tjtjBt ttj t j dS( Niis'i R>i R?i t,ii i ( R5R RR9R:R R@RRRR R0R1(((s(/usr/lib64/python2.7/Demo/curses/xmas.pytstrng2s   cCs(tjtjtjBtttjtjddtdtjddtdtjddtdtjddtd tjd d tdtjd d tdtjd d tdtjd dtd tj tjtjBt ttj t j dS(Niis'iR>iR?i RBii i i i ( R5R RR9R:R R@RRRR R0R1(((s(/usr/lib64/python2.7/Demo/curses/xmas.pytstrng3s   cCstjtjtjBtttjtjddtdtjddtdtjddtdtjddtd tjd d tdtjd d tdtjd d tdtjd d td tjd dtdtjd dtdtjd dtdtjd dtd tjd dtdtj tjtjBt ttj t j dS(Ni is'iR>iR?iRBi i i i iiii( R5R RR9R:R R@RRRR R0R1(((s(/usr/lib64/python2.7/Demo/curses/xmas.pytstrng4s(   cCs5tjtjtjBtttjtjddtdtjddtdtjddtdtjddtd tjd d tdtjd d tdtjd d tdtjd d td tj tjtjBt ttj t tj tj dS(Ni is'iR>iR?iRBi iii (R5R RR9R:R R@RRRR R4R.R0R1(((s(/usr/lib64/python2.7/Demo/curses/xmas.pytstrng5s     cCsEtjxtdD]}|dkrNtjttjtjPn|dkrtjttjtjPn|dkrtjttjtjPnb|dkrt jttjtjPn1|dkrt jttjtjPntjqWt jttjtjdS(Niiiiii( t treescrn8ttouchwinRt treescrn3R4R0R1t treescrn4t treescrn5t treescrn6t treescrn7R.(tcycle((s(/usr/lib64/python2.7/Demo/curses/xmas.pytblinkits@                        cCs2|j|||jtjtddS(Ni(tmvwinR0R1R(RRR((s(/usr/lib64/python2.7/Demo/curses/xmas.pyt deer_step7s  cCskd}xtdddD]}|dkr4d}nxltddD][}tj||tdtjtjtjtjtjtd qDWqWd }xt|dd dD]}xtddD]}|d kr[d }ytj||td Wnt j k r%nXtjtjtjtjtjqtj||td tjtjtjtjtjqWqWd}xtd dD]}t j t jtjxtddD]~}t t||t t||t t||t t||t t||t j t jtj|d 8}qWqWd}xtddD]}tj tjtjxtd D]~}t t||t t||t t||t t||t t||tj tjtj|d 8}qWqWtdd}xtddD]}t t||t t||t t||t t||t t||t t||t t||t t||qkW|d8}xtddD]v}t t||t t||t t||t t||t t||t t||t t||qWt t||xt|dD]}xtdd D]v}t t||t t||t t||t t||t t||t t||t t||qWt t||qW|d8}t t||dS(NiiFi>iiBiiR?i2ii8iR8i:ii#i i,iii(Rtdotdeer0RRR0R1teraseRt stardeer0Rterrortlildeer0RHRQtlildeer3tlildeer2tlildeer1tmiddeer0tmiddeer3tmiddeer2tmiddeer1tbigdeer4tbigdeer3tbigdeer2tbigdeer1tbigdeer0t lookdeer4t lookdeer3t lookdeer2t lookdeer1t lookdeer0(ty_postx_postlooper((s(/usr/lib64/python2.7/Demo/curses/xmas.pytreindeer=s                               cCs=|atjatjddddatjddddatjddddatjddddatjdddda tjdddda tjdddda tjdddda tjdddda tjdd ddatjd dddatjd dddatjd dddatjd dddatjd d ddatjdd ddatjdd ddatjdd ddatjddddatjddddatjddddatjddddatjddddatjddddatjddddatjddddatjddddatjdddda tjdddda!tjdddda"yt"j#dddWntj$k r nXyt!j#dddWntj$k r:nXtj%ddt&dtj%ddt&dtj%ddt&dtj%dd t&dytj%ddt&dWntj$k rnXtj%ddt&dtj%ddt&dtj%ddt&dtj%dd t&dytj%ddt&dWntj$k rjnXtj%ddt&dtj%ddt&dtj%ddt&dtj%dd t&dytj%ddt&dWntj$k rnXtj%dd t&dtj%ddt&dtj%dd t&dtj%ddt&dtj%ddt&dtj%dd t&d!tj%dd"t&dtj%d dt&d#tj%d d t&d$tj%dd t&dtj%ddt&dtj%dd t&dtj%ddt&dtj%ddt&dtj%dd t&d!tj%dd"t&dtj%d dt&dtj%d d t&dtj%dd t&dtj%ddt&dtj%dd t&dtj%ddt&dtj%ddt&dtj%dd t&d!tj%dd"t&dtj%d dt&d$tj%d d t&d#tj%dd%t&d#tj%dd&t&d$tj%dd't&d#tj%ddt&d$tj%dd&t&d#tj%ddt&d$tj%d d't&dtj%d dt&d(tj%dd&t&d$tj%dd't&d)tj%ddt&dtj%dd*t&d#tj%dd%t&d$tj%dd&t&d$tj%dd't&d#tj%dd+t&d#tj#d d d,tj#d"d d-tj#d dd.tj#dd/d0tj#d/d1d2tj%dd%t&d#tj%dd&t&d$tj%dd't&d#tj%ddt&d$tj%dd&t&d#tj%ddt&d$tj%d d't&dtj%d dt&d(tj%dd&t&d$tj%dd't&d)tj%ddt&dtj%dd*t&d#tj%dd%t&d$tj%dd&t&d$tj%dd't&d#tj%dd+t&d#tj#d d d,tj#d"d d3tj#d d d4tj#ddd5tj#d/d/d6tj%dd%t&d#tj%dd&t&d$tj%dd't&d#tj%ddt&d$tj%dd&t&d#tj%ddt&d$tj%d d't&dtj%d dt&d(tj%dd&t&d$tj%dd't&d)tj%ddt&dtj%dd*t&d#tj%dd%t&d$tj%dd&t&d$tj%dd't&d#tj%dd+t&d#tj#d d d,tj#d"d"d7tj#d d"d8tj#dd d9tj#d/d d:tj%dd%t&d#tj%dd&t&d$tj%dd't&d#tj%ddt&d$tj%dd&t&d#tj%ddt&d$tj%d d't&dtj%d dt&d(tj%dd&t&d$tj%dd't&d)tj%ddt&dtj%dd*t&d#tj%dd%t&d$tj%dd&t&d$tj%dd't&d#tj%dd+t&d#tj#d d d,tj#d"d"d;tj#d d d<tj#ddd=tj#ddd>tj#dd%d?tj#d d'd@tj#dd%dAtj#dd%dBtj#d d dCtj#d"d d-tj#d dd.tj#dd/d0tj#d/d1d2tj#ddd>tj#dd%d?tj#d d'd@tj#dd%dAtj#dd%dBtj#d d dCtj#d"d d3tj#d d d4tj#ddd5tj#d/d/d6tj#ddd>tj#dd%d?tj#d d'd@tj#dd%dAtj#dd%dBtj#d d dCtj#d"d"d7tj#d d"d8tj#dd d9tj#d/d d:t j#ddd>t j#dd%d?t j#d d'd@t j#dd%dAt j#dd%dBt j#d d dCt j#d"d"d;t j#d d d<t j#ddd=tj'tj(dxtj)tj*t"j+tj+tj*tj+t j*t j+tj,t-dDt.tj,t-dDt/tj,t0tj,t-dDt1tj,t-dDt2t-dDt3t-dDt4t-dDt5t6t7t8t9tj:ttj%dd&t&dEtj%d d"t&dEtj%dd't&dEtj%d1d+t&dEtj%ddFt&dGtj%dd1t&dEtj%d dHt&dEtj%d"dt&dEtj%d dt&dEtj%d dIt&dEtj%ddHt&dEtj%ddt&dEtj%d1dt&dEtj%d1d&t&dEtj%dFdHt&dEtj:ttj%dd/t&dEtj%ddt&dEtj%d d"t&dEtj%dd't&dEtj%d1d t&dEtj%dFdt&dEtj;tj%ddFt&dGtj<tj%ddHt&dEtj%d d t&dEtj%dd1t&dEtj%d/dt&dEtj%ddFt&dEtj%d1dt&dEtj%d1d&t&dEtj%dFdIt&dEtj:t t j%dd t&dEt j%ddt&dEt j%dFdt&dEt j%ddFt&dEt j%dd1t&dEt j%d dFt&dEt j%d dIt&dEt j%ddt&dEt j%d/d t&dEt j%dd1t&dEt j%d1d t&dEt j%d1d%t&dEt j%dFdHt&dEtj:t t j%d"d t&dEt j%d d&t&dEt j%ddt&dEt j%d1dt&dEt j;t j%ddFt&dGt j<t j%d d1t&dEt j%d dHt&dEt j%dd/t&dEt j%d/dIt&dEt j%ddt&dEt j%d1d"t&dEt j%d1dt&dEt j%dFdFt&dEtj:t t j%dd t&dEt j%d"d t&dEt j%d d&t&dEt j%ddt&dEt j%d1d+t&dEt j%ddFt&dGt j%ddFt&dEt j%d dHt&dEt j%d"d/t&dEt j%d d t&dEt j%dd1t&dEt j%d/dt&dEt j%ddFt&dEt j%d1dt&dEt j%d1d&t&dEt j%dFdIt&dEt-dDt=t!j+t!j,t"j,t-dJxt>ddD] }t?q$WqNWdS(KNiiii5iGiiii8iiii*i iiiii<sHit any key to quitsH A P P Y H O L I D A Y StVR3tt~RRt0t(t=it)is\R-iiiRt^iis^~~~~~~~~// ~~Us ( \_____( /s( ) /i s\\ /i s\>/>s (( )____( /s( / |s\/ |s|> |>s ( ()_____( /s / / /s |/ \s/> \>s ( )______( /s (/ \sv___= ----^s \/ \/s\Y/ \Y/s\=/s^\o o/^s//( )s^~~~~~~~~// \O/it i R8i ii(@RRt COLOR_BLACKRtnewwinR.R5RIRJRKRLRMRGRRRTRVRYRXRWRZR]R\R[RbRaR`R_R^RgRfReRdRct w_holidayR1R*RURRtcbreaktnodelaytclearRSRHR0RRR$R)R,R2R7R=RARCRDRERFR4tstandoutR<RkRRO(Rti((s(/usr/lib64/python2.7/Demo/curses/xmas.pytmains                                     (RRR+R R RRR$R)R,R2R7R=RARCRDRERFRORQRkR~twrapper(((s(/usr/lib64/python2.7/Demo/curses/xmas.pyts.       ,       '  z PK%L]`gjMMcurses/xmas.pycnu[ ^c@sddlZddlZdZdZdZdZdZdZdZd Z d Z d Z d Z d Z dZdZdZdZdZdZdZdZejedS(iNs Thomas Gellekum cCsVtjrR|d}tj||t|jtj|jtj|ndS(Ni(tcursest has_colorst init_pairtmy_bgtattrofftA_COLORtattront color_pair(twintcolortn((s(/usr/lib64/python2.7/Demo/curses/xmas.pyt set_colors   cCs)tjr%|jtjdndS(Ni(RRtattrsetR(R((s(/usr/lib64/python2.7/Demo/curses/xmas.pyt unset_color&s cCs=tj|tjdkr9tjtjdndS(Nii(Rtnapmststdscrtgetchtbeeptsystexit(tmsecs((s(/usr/lib64/python2.7/Demo/curses/xmas.pytlook_out*s  cCsx0tddD]}tj|dtdqWx0tddD]}tjd|tdqCWx0tddD]}tjd |tdqvWdS( Niiit|iiPit_i(trangeRtaddchtord(tytx((s(/usr/lib64/python2.7/Demo/curses/xmas.pytboxit0scCstjddtdtjddtdtjddtdtjddtdtjd dtd tjd dtd tjd dtdtjddtddS(NiitSitEitAi i tOitNit'i(RRR(((s(/usr/lib64/python2.7/Demo/curses/xmas.pytseas<scCstjddtdtjddtdtjddtdtjddtdtjddtd tjd dtd tjd dtd tjddtdtjddtddS(NiitGtRiRi i tTi tIiR"iiR(RRR(((s(/usr/lib64/python2.7/Demo/curses/xmas.pytgreetHscCstjddtdS(Nii (RtaddstrtFROMWHO(((s(/usr/lib64/python2.7/Demo/curses/xmas.pytfromwhoUscCs'tttjtjddtdtjddtdtjddtdtjddtdtjd dtdtjd d tdtjd d tdtjd d tdtjdd tdtjdd tdtjddtdtjd dtdtjddtdtjddtdtjddtdtjddtdtjd dtdtjd dtdtjd dtdtjd dtdtjddtdtjddtdtjddtdtjd dtdtjddtdtjddtdtjd d tdtjd dtdtjdddtjdddtjdddtttjt jdS(Nii t/iii ii iiiii i s\iiiiiiiiRis//////////// \\\\\\\\\\\\s| |s|_|( R ttreescrnRt COLOR_GREENRRR*R trefresht w_del_msg(((s(/usr/lib64/python2.7/Demo/curses/xmas.pyttreeYsH   cCstjttttjtjddtdtjddtdtjddtdtjddtdtjdd tdtjdd tdtjd d tdtjd d tdtjddtdtjdd tdtjddtdtjddtdtjddtdtjddtdtjddtdtjddtdtttj t j dS(Nii t@iiiiiiiiiii ii iii ii( R.toverlayt treescrn2R Rt COLOR_BLUERRR R0R1(((s(/usr/lib64/python2.7/Demo/curses/xmas.pytballss,    cCsltjtjtjBtttjtjddtdtj t ttj t j dS(Nii t*( R5R RtA_BOLDtA_BLINKR t COLOR_YELLOWRRtstandendR R0R1(((s(/usr/lib64/python2.7/Demo/curses/xmas.pytstars    cCstjtjtjBtttjtjddtdtjddtdtjddtdtj tjtjBt ttj t j dS(Nii s'i t:i t.( R5R RR9R:R t COLOR_WHITERRRR R0R1(((s(/usr/lib64/python2.7/Demo/curses/xmas.pytstrng1s   cCstjtjtjBtttjtjddtdtjddtdtjddtdtjddtd tjd d tdtjd d tdtj tjtjBt ttj t j dS( Niis'i R>i R?i t,ii i ( R5R RR9R:R R@RRRR R0R1(((s(/usr/lib64/python2.7/Demo/curses/xmas.pytstrng2s   cCs(tjtjtjBtttjtjddtdtjddtdtjddtdtjddtd tjd d tdtjd d tdtjd d tdtjd dtd tj tjtjBt ttj t j dS(Niis'iR>iR?i RBii i i i ( R5R RR9R:R R@RRRR R0R1(((s(/usr/lib64/python2.7/Demo/curses/xmas.pytstrng3s   cCstjtjtjBtttjtjddtdtjddtdtjddtdtjddtd tjd d tdtjd d tdtjd d tdtjd d td tjd dtdtjd dtdtjd dtdtjd dtd tjd dtdtj tjtjBt ttj t j dS(Ni is'iR>iR?iRBi i i i iiii( R5R RR9R:R R@RRRR R0R1(((s(/usr/lib64/python2.7/Demo/curses/xmas.pytstrng4s(   cCs5tjtjtjBtttjtjddtdtjddtdtjddtdtjddtd tjd d tdtjd d tdtjd d tdtjd d td tj tjtjBt ttj t tj tj dS(Ni is'iR>iR?iRBi iii (R5R RR9R:R R@RRRR R4R.R0R1(((s(/usr/lib64/python2.7/Demo/curses/xmas.pytstrng5s     cCsEtjxtdD]}|dkrNtjttjtjPn|dkrtjttjtjPn|dkrtjttjtjPnb|dkrt jttjtjPn1|dkrt jttjtjPntjqWt jttjtjdS(Niiiiii( t treescrn8ttouchwinRt treescrn3R4R0R1t treescrn4t treescrn5t treescrn6t treescrn7R.(tcycle((s(/usr/lib64/python2.7/Demo/curses/xmas.pytblinkits@                        cCs2|j|||jtjtddS(Ni(tmvwinR0R1R(RRR((s(/usr/lib64/python2.7/Demo/curses/xmas.pyt deer_step7s  cCskd}xtdddD]}|dkr4d}nxltddD][}tj||tdtjtjtjtjtjtd qDWqWd }xt|dd dD]}xtddD]}|d kr[d }ytj||td Wnt j k r%nXtjtjtjtjtjqtj||td tjtjtjtjtjqWqWd}xtd dD]}t j t jtjxtddD]~}t t||t t||t t||t t||t t||t j t jtj|d 8}qWqWd}xtddD]}tj tjtjxtd D]~}t t||t t||t t||t t||t t||tj tjtj|d 8}qWqWtdd}xtddD]}t t||t t||t t||t t||t t||t t||t t||t t||qkW|d8}xtddD]v}t t||t t||t t||t t||t t||t t||t t||qWt t||xt|dD]}xtdd D]v}t t||t t||t t||t t||t t||t t||t t||qWt t||qW|d8}t t||dS(NiiFi>iiBiiR?i2ii8iR8i:ii#i i,iii(Rtdotdeer0RRR0R1teraseRt stardeer0Rterrortlildeer0RHRQtlildeer3tlildeer2tlildeer1tmiddeer0tmiddeer3tmiddeer2tmiddeer1tbigdeer4tbigdeer3tbigdeer2tbigdeer1tbigdeer0t lookdeer4t lookdeer3t lookdeer2t lookdeer1t lookdeer0(ty_postx_postlooper((s(/usr/lib64/python2.7/Demo/curses/xmas.pytreindeer=s                               cCs=|atjatjddddatjddddatjddddatjddddatjdddda tjdddda tjdddda tjdddda tjdddda tjdd ddatjd dddatjd dddatjd dddatjd dddatjd d ddatjdd ddatjdd ddatjdd ddatjddddatjddddatjddddatjddddatjddddatjddddatjddddatjddddatjddddatjdddda tjdddda!tjdddda"yt"j#dddWntj$k r nXyt!j#dddWntj$k r:nXtj%ddt&dtj%ddt&dtj%ddt&dtj%dd t&dytj%ddt&dWntj$k rnXtj%ddt&dtj%ddt&dtj%ddt&dtj%dd t&dytj%ddt&dWntj$k rjnXtj%ddt&dtj%ddt&dtj%ddt&dtj%dd t&dytj%ddt&dWntj$k rnXtj%dd t&dtj%ddt&dtj%dd t&dtj%ddt&dtj%ddt&dtj%dd t&d!tj%dd"t&dtj%d dt&d#tj%d d t&d$tj%dd t&dtj%ddt&dtj%dd t&dtj%ddt&dtj%ddt&dtj%dd t&d!tj%dd"t&dtj%d dt&dtj%d d t&dtj%dd t&dtj%ddt&dtj%dd t&dtj%ddt&dtj%ddt&dtj%dd t&d!tj%dd"t&dtj%d dt&d$tj%d d t&d#tj%dd%t&d#tj%dd&t&d$tj%dd't&d#tj%ddt&d$tj%dd&t&d#tj%ddt&d$tj%d d't&dtj%d dt&d(tj%dd&t&d$tj%dd't&d)tj%ddt&dtj%dd*t&d#tj%dd%t&d$tj%dd&t&d$tj%dd't&d#tj%dd+t&d#tj#d d d,tj#d"d d-tj#d dd.tj#dd/d0tj#d/d1d2tj%dd%t&d#tj%dd&t&d$tj%dd't&d#tj%ddt&d$tj%dd&t&d#tj%ddt&d$tj%d d't&dtj%d dt&d(tj%dd&t&d$tj%dd't&d)tj%ddt&dtj%dd*t&d#tj%dd%t&d$tj%dd&t&d$tj%dd't&d#tj%dd+t&d#tj#d d d,tj#d"d d3tj#d d d4tj#ddd5tj#d/d/d6tj%dd%t&d#tj%dd&t&d$tj%dd't&d#tj%ddt&d$tj%dd&t&d#tj%ddt&d$tj%d d't&dtj%d dt&d(tj%dd&t&d$tj%dd't&d)tj%ddt&dtj%dd*t&d#tj%dd%t&d$tj%dd&t&d$tj%dd't&d#tj%dd+t&d#tj#d d d,tj#d"d"d7tj#d d"d8tj#dd d9tj#d/d d:tj%dd%t&d#tj%dd&t&d$tj%dd't&d#tj%ddt&d$tj%dd&t&d#tj%ddt&d$tj%d d't&dtj%d dt&d(tj%dd&t&d$tj%dd't&d)tj%ddt&dtj%dd*t&d#tj%dd%t&d$tj%dd&t&d$tj%dd't&d#tj%dd+t&d#tj#d d d,tj#d"d"d;tj#d d d<tj#ddd=tj#ddd>tj#dd%d?tj#d d'd@tj#dd%dAtj#dd%dBtj#d d dCtj#d"d d-tj#d dd.tj#dd/d0tj#d/d1d2tj#ddd>tj#dd%d?tj#d d'd@tj#dd%dAtj#dd%dBtj#d d dCtj#d"d d3tj#d d d4tj#ddd5tj#d/d/d6tj#ddd>tj#dd%d?tj#d d'd@tj#dd%dAtj#dd%dBtj#d d dCtj#d"d"d7tj#d d"d8tj#dd d9tj#d/d d:t j#ddd>t j#dd%d?t j#d d'd@t j#dd%dAt j#dd%dBt j#d d dCt j#d"d"d;t j#d d d<t j#ddd=tj'tj(dxtj)tj*t"j+tj+tj*tj+t j*t j+tj,t-dDt.tj,t-dDt/tj,t0tj,t-dDt1tj,t-dDt2t-dDt3t-dDt4t-dDt5t6t7t8t9tj:ttj%dd&t&dEtj%d d"t&dEtj%dd't&dEtj%d1d+t&dEtj%ddFt&dGtj%dd1t&dEtj%d dHt&dEtj%d"dt&dEtj%d dt&dEtj%d dIt&dEtj%ddHt&dEtj%ddt&dEtj%d1dt&dEtj%d1d&t&dEtj%dFdHt&dEtj:ttj%dd/t&dEtj%ddt&dEtj%d d"t&dEtj%dd't&dEtj%d1d t&dEtj%dFdt&dEtj;tj%ddFt&dGtj<tj%ddHt&dEtj%d d t&dEtj%dd1t&dEtj%d/dt&dEtj%ddFt&dEtj%d1dt&dEtj%d1d&t&dEtj%dFdIt&dEtj:t t j%dd t&dEt j%ddt&dEt j%dFdt&dEt j%ddFt&dEt j%dd1t&dEt j%d dFt&dEt j%d dIt&dEt j%ddt&dEt j%d/d t&dEt j%dd1t&dEt j%d1d t&dEt j%d1d%t&dEt j%dFdHt&dEtj:t t j%d"d t&dEt j%d d&t&dEt j%ddt&dEt j%d1dt&dEt j;t j%ddFt&dGt j<t j%d d1t&dEt j%d dHt&dEt j%dd/t&dEt j%d/dIt&dEt j%ddt&dEt j%d1d"t&dEt j%d1dt&dEt j%dFdFt&dEtj:t t j%dd t&dEt j%d"d t&dEt j%d d&t&dEt j%ddt&dEt j%d1d+t&dEt j%ddFt&dGt j%ddFt&dEt j%d dHt&dEt j%d"d/t&dEt j%d d t&dEt j%dd1t&dEt j%d/dt&dEt j%ddFt&dEt j%d1dt&dEt j%d1d&t&dEt j%dFdIt&dEt-dDt=t!j+t!j,t"j,t-dJxt>ddD] }t?q$WqNWdS(KNiiii5iGiiii8iiii*i iiiii<sHit any key to quitsH A P P Y H O L I D A Y StVR3tt~RRt0t(t=it)is\R-iiiRt^iis^~~~~~~~~// ~~Us ( \_____( /s( ) /i s\\ /i s\>/>s (( )____( /s( / |s\/ |s|> |>s ( ()_____( /s / / /s |/ \s/> \>s ( )______( /s (/ \sv___= ----^s \/ \/s\Y/ \Y/s\=/s^\o o/^s//( )s^~~~~~~~~// \O/it i R8i ii(@RRt COLOR_BLACKRtnewwinR.R5RIRJRKRLRMRGRRRTRVRYRXRWRZR]R\R[RbRaR`R_R^RgRfReRdRct w_holidayR1R*RURRtcbreaktnodelaytclearRSRHR0RRR$R)R,R2R7R=RARCRDRERFR4tstandoutR<RkRRO(Rti((s(/usr/lib64/python2.7/Demo/curses/xmas.pytmains                                     (RRR+R R RRR$R)R,R2R7R=RARCRDRERFRORQRkR~twrapper(((s(/usr/lib64/python2.7/Demo/curses/xmas.pyts.       ,       '  z PK%L]%curses/repeat.pycnu[ Afc@sJdZddlZddlZddlZddlZdZedS(srepeat This simple program repeatedly (at 1-second intervals) executes the shell command given on the command line and displays the output (or as much of it as fits on the screen). It uses curses to paint each new output on top of the old output, so that if nothing changes, the screen doesn't change. This is handy to watch for changes in e.g. a directory or process listing. To end, hit Control-C. iNcCsVtjds"tGHtjdndjtjd}tj|d}|j}|j}|rtj dI|IJtj|nt j }zxt rB|j y|j|Wnt jk rnX|jtjdtj|d}|j}|j}|rtj dI|IJtj|qqWWdt jXdS(Niit trs Exit code:(tsystargvt__doc__texittjointostpopentreadtclosetstderrtcursestinitscrtTrueterasetaddstrterrortrefreshttimetsleeptendwin(tcmdtpttexttststw((s*/usr/lib64/python2.7/Demo/curses/repeat.pytmains6          (RRRRR R(((s*/usr/lib64/python2.7/Demo/curses/repeat.pyt s      PK%L]H embed/loop.cnu[/* Simple program that repeatedly calls Py_Initialize(), does something, and then calls Py_Finalize(). This should help finding leaks related to initialization. */ #include "Python.h" main(int argc, char **argv) { int count = -1; char *command; if (argc < 2 || argc > 3) { fprintf(stderr, "usage: loop [count]\n"); exit(2); } command = argv[1]; if (argc == 3) { count = atoi(argv[2]); } Py_SetProgramName(argv[0]); /* uncomment this if you don't want to load site.py */ /* Py_NoSiteFlag = 1; */ while (count == -1 || --count >= 0 ) { Py_Initialize(); PyRun_SimpleString(command); Py_Finalize(); } return 0; } PK%L]_66 embed/READMEnu[This directory show how to embed the Python interpreter in your own application. The file demo.c shows you all that is needed in your C code. To build it, you may have to edit the Makefile: 1) set blddir to the directory where you built Python, if it isn't in the source directory (../..) 2) change the variables that together define the list of libraries (MODLIBS, LIBS, SYSLIBS) to link with, to match their definitions in $(blddir)/Modules/Makefile An additional test program, loop.c, is used to experiment with memory leakage caused by repeated initialization and finalization of the interpreter. It can be build by saying "make loop" and tested with "make looptest". Command line usage is "./loop ", e.g. "./loop 'print 2+2'" should spit out an endless number of lines containing the number 4. PK%L]'\embed/importexc.cnu[#include char* cmd = "import exceptions"; int main() { Py_Initialize(); PyEval_InitThreads(); PyRun_SimpleString(cmd); Py_EndInterpreter(PyThreadState_Get()); Py_NewInterpreter(); PyRun_SimpleString(cmd); Py_Finalize(); return 0; } PK%L]9ʃembed/Makefilenu[# Makefile for embedded Python use demo. # (This version originally written on Red Hat Linux 6.1; # edit lines marked with XXX.) # XXX The compiler you are using CC= gcc # XXX Top of the build tree and source tree blddir= ../.. srcdir= ../.. # Python version VERSION= 2.7 # Compiler flags OPT= -g INCLUDES= -I$(srcdir)/Include -I$(blddir) CFLAGS= $(OPT) CPPFLAGS= $(INCLUDES) # The Python library LIBPYTHON= $(blddir)/libpython$(VERSION).a # XXX edit LIBS (in particular) to match $(blddir)/Makefile LIBS= -lnsl -ldl -lreadline -ltermcap -lieee -lpthread -lutil LDFLAGS= -Xlinker -export-dynamic SYSLIBS= -lm MODLIBS= ALLLIBS= $(LIBPYTHON) $(MODLIBS) $(LIBS) $(SYSLIBS) # Build the demo applications all: demo loop importexc demo: demo.o $(CC) $(LDFLAGS) demo.o $(ALLLIBS) -o demo loop: loop.o $(CC) $(LDFLAGS) loop.o $(ALLLIBS) -o loop importexc: importexc.o $(CC) $(LDFLAGS) importexc.o $(ALLLIBS) -o importexc # Administrative targets test: demo ./demo COMMAND="print 'hello world'" looptest: loop ./loop $(COMMAND) clean: -rm -f *.o core clobber: clean -rm -f *~ @* '#'* demo loop importexc realclean: clobber PK%L]& embed/demo.cnu[/* Example of embedding Python in another program */ #include "Python.h" void initxyzzy(void); /* Forward */ main(int argc, char **argv) { /* Pass argv[0] to the Python interpreter */ Py_SetProgramName(argv[0]); /* Initialize the Python interpreter. Required. */ Py_Initialize(); /* Add a static module */ initxyzzy(); /* Define sys.argv. It is up to the application if you want this; you can also leave it undefined (since the Python code is generally not a main program it has no business touching sys.argv...) If the third argument is true, sys.path is modified to include either the directory containing the script named by argv[0], or the current working directory. This can be risky; if you run an application embedding Python in a directory controlled by someone else, attackers could put a Trojan-horse module in the directory (say, a file named os.py) that your application would then import and run. */ PySys_SetArgvEx(argc, argv, 0); /* Do some application specific code */ printf("Hello, brave new world\n\n"); /* Execute some Python statements (in module __main__) */ PyRun_SimpleString("import sys\n"); PyRun_SimpleString("print sys.builtin_module_names\n"); PyRun_SimpleString("print sys.modules.keys()\n"); PyRun_SimpleString("print sys.executable\n"); PyRun_SimpleString("print sys.argv\n"); /* Note that you can call any public function of the Python interpreter here, e.g. call_object(). */ /* Some more application specific code */ printf("\nGoodbye, cruel world\n"); /* Exit, cleaning up the interpreter */ Py_Exit(0); /*NOTREACHED*/ } /* A static module */ /* 'self' is not used */ static PyObject * xyzzy_foo(PyObject *self, PyObject* args) { return PyInt_FromLong(42L); } static PyMethodDef xyzzy_methods[] = { {"foo", xyzzy_foo, METH_NOARGS, "Return the meaning of everything."}, {NULL, NULL} /* sentinel */ }; void initxyzzy(void) { PyImport_AddModule("xyzzy"); Py_InitModule("xyzzy", xyzzy_methods); } PK%L]nЈ tkinter/matt/dialog-box.pynu[PK%L]t44 tkinter/matt/entry-simple.pyonu[PK%L];mDD(Stkinter/matt/canvas-reading-tag-info.pycnu[PK%L]`MY)tkinter/matt/subclass-existing-widgets.pynu[PK%L] NN%tkinter/matt/canvas-moving-w-mouse.pynu[PK%L] !tkinter/matt/slider-demo-1.pyonu[PK%L]k(tkinter/matt/dialog-box.pycnu[PK%L]v '0tkinter/matt/rubber-band-box-demo-1.pyonu[PK%L]Q":tkinter/matt/rubber-line-demo-1.pynu[PK%L];$Btkinter/matt/window-creation-more.pynu[PK%L]Ca33Gtkinter/matt/packer-simple.pynu[PK%L](  $Jtkinter/matt/canvas-mult-item-sel.pynu[PK%L]*hh+Vtkinter/matt/entry-with-shared-variable.pycnu[PK%L]̆^+\tkinter/matt/not-what-you-might-think-1.pycnu[PK%L]ll+3btkinter/matt/packer-and-placer-together.pycnu[PK%L]jHH#gtkinter/matt/radiobutton-simple.pycnu[PK%L]oVV&otkinter/matt/rubber-band-box-demo-1.pynu[PK%L]ZZ%Axtkinter/matt/window-creation-more.pycnu[PK%L]MhΩ &Mtkinter/matt/canvas-moving-w-mouse.pyonu[PK%L]~ Ltkinter/matt/00-HELLO-WORLD.pynu[PK%L]Fֳ ntkinter/matt/menu-simple.pynu[PK%L]!ltkinter/matt/READMEnu[PK%L]'tkinter/matt/canvas-gridding.pynu[PK%L]L  )ޤtkinter/matt/printing-coords-of-items.pycnu[PK%L]*hh+Mtkinter/matt/entry-with-shared-variable.pyonu[PK%L]PPtkinter/matt/pong-demo-1.pycnu[PK%L]|=4>>&tkinter/matt/canvas-with-scrollbars.pynu[PK%L]uk/ @tkinter/matt/animation-simple.pynu[PK%L]3--*;tkinter/matt/window-creation-w-location.pynu[PK%L]R۩tkinter/matt/menu-simple.pycnu[PK%L]#tkinter/matt/rubber-line-demo-1.pycnu[PK%L]ZZ%tkinter/matt/window-creation-more.pyonu[PK%L]>;tkinter/matt/packer-simple.pyonu[PK%L]f 44+tkinter/matt/window-creation-w-location.pycnu[PK%L]F77+dtkinter/matt/not-what-you-might-think-2.pyonu[PK%L]: %tkinter/matt/canvas-mult-item-sel.pycnu[PK%L]_ "Atkinter/matt/canvas-demo-simple.pynu[PK%L]L  ) tkinter/matt/printing-coords-of-items.pyonu[PK%L]w(tkinter/matt/bind-w-mult-calls-p-type.pynu[PK%L]  Ttkinter/matt/canvas-gridding.pyonu[PK%L]}N  %tkinter/matt/pong-demo-1.pynu[PK%L]aI  *,tkinter/matt/canvas-moving-or-creating.pyonu[PK%L]'6tkinter/matt/canvas-w-widget-draw-el.pynu[PK%L]3(jj'q;tkinter/matt/window-creation-simple.pyonu[PK%L]aI  *2Btkinter/matt/canvas-moving-or-creating.pycnu[PK%L]>;Ltkinter/matt/packer-simple.pycnu[PK%L]F77+Rtkinter/matt/not-what-you-might-think-2.pycnu[PK%L] yy)Xtkinter/matt/bind-w-mult-calls-p-type.pyonu[PK%L] yy)]tkinter/matt/bind-w-mult-calls-p-type.pycnu[PK%L]̆^+ctkinter/matt/not-what-you-might-think-1.pyonu[PK%L]#&itkinter/matt/rubber-line-demo-1.pyonu[PK%L]br; ; 'Zrtkinter/matt/canvas-with-scrollbars.pyonu[PK%L]> {tkinter/matt/two-radio-groups.pynu[PK%L]>kv v )tkinter/matt/canvas-moving-or-creating.pynu[PK%L]3(jj'tkinter/matt/window-creation-simple.pycnu[PK%L]ll+ztkinter/matt/packer-and-placer-together.pyonu[PK%L]t44Atkinter/matt/entry-simple.pycnu[PK%L]: %¥tkinter/matt/canvas-mult-item-sel.pyonu[PK%L]g tkinter/matt/00-HELLO-WORLD.pyonu[PK%L]b*//&otkinter/matt/window-creation-simple.pynu[PK%L]v 'tkinter/matt/rubber-band-box-demo-1.pycnu[PK%L]f 44+Ttkinter/matt/window-creation-w-location.pyonu[PK%L]gtkinter/matt/00-HELLO-WORLD.pycnu[PK%L]a>oQ*Etkinter/matt/animation-w-velocity-ctrl.pyonu[PK%L]  tkinter/matt/canvas-gridding.pycnu[PK%L])'tkinter/matt/canvas-reading-tag-info.pynu[PK%L]#Utkinter/matt/entry-simple.pynu[PK%L]Q.#tkinter/matt/killing-window-w-wm.pynu[PK%L]D66Ytkinter/matt/placer-simple.pynu[PK%L]}` ` (tkinter/matt/printing-coords-of-items.pynu[PK%L]PPtkinter/matt/pong-demo-1.pyonu[PK%L] 4+!0 tkinter/matt/two-radio-groups.pyonu[PK%L]br; ; 'tkinter/matt/canvas-with-scrollbars.pycnu[PK%L]Vkk*tkinter/matt/menu-all-types-of-entries.pycnu[PK%L]0L$h0tkinter/matt/killing-window-w-wm.pyonu[PK%L]k6tkinter/matt/dialog-box.pyonu[PK%L];mDD(>tkinter/matt/canvas-reading-tag-info.pyonu[PK%L]0L$2Ftkinter/matt/killing-window-w-wm.pycnu[PK%L]d([Ltkinter/matt/canvas-w-widget-draw-el.pycnu[PK%L]S"  Rtkinter/matt/placer-simple.pyonu[PK%L]jHH#Wtkinter/matt/radiobutton-simple.pyonu[PK%L]e̍#_tkinter/matt/canvas-demo-simple.pycnu[PK%L]MhΩ &jetkinter/matt/canvas-moving-w-mouse.pycnu[PK%L] iotkinter/matt/slider-demo-1.pycnu[PK%L]R۩gvtkinter/matt/menu-simple.pyonu[PK%L]J"\~tkinter/matt/radiobutton-simple.pynu[PK%L]~ǁ*tkinter/matt/not-what-you-might-think-2.pynu[PK%L]!Ήtkinter/matt/animation-simple.pycnu[PK%L]X *אtkinter/matt/packer-and-placer-together.pynu[PK%L]S"  tkinter/matt/placer-simple.pycnu[PK%L]#~*Etkinter/matt/entry-with-shared-variable.pynu[PK%L]x##)rtkinter/matt/menu-all-types-of-entries.pynu[PK%L]d(atkinter/matt/canvas-w-widget-draw-el.pyonu[PK%L] 4+!tkinter/matt/two-radio-groups.pycnu[PK%L]ʥE*{tkinter/matt/not-what-you-might-think-1.pynu[PK%L]e̍#xtkinter/matt/canvas-demo-simple.pyonu[PK%L]a>oQ*Xtkinter/matt/animation-w-velocity-ctrl.pycnu[PK%L]])tkinter/matt/animation-w-velocity-ctrl.pynu[PK%L];U<*tkinter/matt/subclass-existing-widgets.pyonu[PK%L]P6tkinter/matt/slider-demo-1.pynu[PK%L];U<*tkinter/matt/subclass-existing-widgets.pycnu[PK%L]!4tkinter/matt/animation-simple.pyonu[PK%L]Vkk*=tkinter/matt/menu-all-types-of-entries.pyonu[PK%L]m.,,tkinter/guido/kill.pynuȯPK%L]1s$tkinter/guido/switch.pynu[PK%L]| *tkinter/guido/MimeViewer.pynuȯPK%L]GfGf<tkinter/guido/ss1.pynu[PK%L]Ṁ 8tkinter/guido/dialog.pynuȯPK%L]^tkinter/guido/wish.pyonu[PK%L](V'tkinter/guido/ManPage.pynu[PK%L].,#,#7tkinter/guido/tkman.pynuȯPK%L]MdUUtkinter/guido/MimeViewer.pycnu[PK%L]DJtkinter/guido/optionmenu.pynu[PK%L]ե))Ntkinter/guido/hanoi.pynu[PK%L]^ui i tkinter/guido/switch.pycnu[PK%L]hn%tkinter/guido/imagedraw.pycnu[PK%L]MdUU<*tkinter/guido/MimeViewer.pyonu[PK%L]kK\\=tkinter/guido/sortvisu.pycnu[PK%L]X##tkinter/guido/tkman.pyonu[PK%L]kK\\tkinter/guido/sortvisu.pyonu[PK%L],))tkinter/guido/canvasevents.pyonu[PK%L].55Etkinter/guido/svkill.pyonu[PK%L]k>'V]tkinter/guido/hello.pyonu[PK%L],))Z`tkinter/guido/canvasevents.pycnu[PK%L]Itkinter/guido/rmt.pynuȯPK%L]VStkinter/guido/rmt.pyonu[PK%L][ tkinter/guido/ss1.pycnu[PK%L]E`}eR R . tkinter/guido/electrons.pycnu[PK%L]KѴQQ tkinter/guido/solitaire.pycnu[PK%L]k>'5 tkinter/guido/hello.pycnu[PK%L]YY8 tkinter/guido/brownian.pycnu[PK%L]qfXX ^? tkinter/guido/newmenubardemo.pyonu[PK%L]qfXX F tkinter/guido/newmenubardemo.pycnu[PK%L]&YL tkinter/guido/listtree.pycnu[PK%L]X\R tkinter/guido/ManPage.pyonu[PK%L]^Ul tkinter/guido/wish.pycnu[PK%L])YzKK|o tkinter/guido/sortvisu.pynuȯPK%L]X\W tkinter/guido/ManPage.pycnu[PK%L]n`   tkinter/guido/electrons.pynuȯPK%L]aA tkinter/guido/newmenubardemo.pynuȯPK%L]|D2 tkinter/guido/paint.pycnu[PK%L]V< tkinter/guido/rmt.pycnu[PK%L]Ծ6 tkinter/READMEnu[PK%L]Rh|@@! tkinter/ttk/listbox_scrollcmd.pycnu[PK%L]"P P  tkinter/ttk/widget_state.pycnu[PK%L]J"_ !> tkinter/ttk/notebook_closebtn.pycnu[PK%L]J"_ !/" tkinter/ttk/notebook_closebtn.pyonu[PK%L]#gg$ . tkinter/ttk/treeview_multicolumn.pycnu[PK%L] w%> > C tkinter/ttk/theme_selector.pycnu[PK%L]y5LgO tkinter/ttk/roundframe.pynu[PK%L]yTt%t%e tkinter/ttk/plastik_theme.pynu[PK%L]$&$&Q tkinter/ttk/ttkcalendar.pycnu[PK%L]O tkinter/ttk/dirbrowser.pyonu[PK%L]#gg$ tkinter/ttk/treeview_multicolumn.pyonu[PK%L]xa##M tkinter/ttk/roundframe.pycnu[PK%L]j:^^ tkinter/ttk/plastik_theme.pyonu[PK%L]xa##e tkinter/ttk/roundframe.pyonu[PK%L][' tkinter/ttk/mac_searchentry.pynu[PK%L]^#6 tkinter/ttk/treeview_multicolumn.pynu[PK%L]Rh|@@!G tkinter/ttk/listbox_scrollcmd.pyonu[PK%L] w%> >  N tkinter/ttk/theme_selector.pyonu[PK%L]>Y tkinter/ttk/mac_searchentry.pyonu[PK%L]|&C]i tkinter/ttk/combo_themes.pycnu[PK%L]OWq tkinter/ttk/dirbrowser.pycnu[PK%L]"P P ) tkinter/ttk/widget_state.pyonu[PK%L]8~ ~ Ŏ tkinter/ttk/ttkcalendar.pynu[PK%L]$&$& tkinter/ttk/ttkcalendar.pyonu[PK%L]aO tkinter/ttk/theme_selector.pynu[PK%L]qP  tkinter/ttk/dirbrowser.pynu[PK%L]akJ  tkinter/ttk/widget_state.pynu[PK%L]j:^^ tkinter/ttk/plastik_theme.pycnu[PK%L]xUeey tkinter/ttk/img/close.gifnu[PK%L]|!ee!' tkinter/ttk/img/close_pressed.gifnu[PK%L].PP  tkinter/ttk/img/close_active.gifnu[PK%L]- } tkinter/ttk/listbox_scrollcmd.pynu[PK%L]|&C]R tkinter/ttk/combo_themes.pyonu[PK%L]>% tkinter/ttk/mac_searchentry.pycnu[PK%L]nnF / tkinter/ttk/notebook_closebtn.pynu[PK%L]/ QQ,: tkinter/ttk/combo_themes.pynu[PK%L]UWp @ turtle/tdemo_planet_and_moon.pycnu[PK%L]PX''R turtle/tdemo_minimal_hanoi.pycnu[PK%L]tn*ܷDa turtle/tdemo_chaos.pynu[PK%L]w[@e turtle/tdemo_wikipedia.pyonu[PK%L] -m turtle/tdemo_clock.pynuȯPK%L]PX''z turtle/tdemo_minimal_hanoi.pyonu[PK%L]UWp z turtle/tdemo_planet_and_moon.pyonu[PK%L]CC turtle/tdemo_wikipedia.pynu[PK%L]jN= =  turtle/tdemo_colormixer.pycnu[PK%L]Hll turtle/tdemo_peace.pyonu[PK%L]}W$$G turtle/tdemo_nim.pyonu[PK%L]!KK3 turtle/tdemo_tree.pyonu[PK%L]Hll turtle/tdemo_peace.pycnu[PK%L]:Bmmu turtle/tdemo_paint.pycnu[PK%L] p||$( turtle/tdemo_I_dontlike_tiltdemo.pycnu[PK%L]3  turtle/tdemo_tree.pynuȯPK%L]JȤ turtle/turtle.cfgnu[PK%L]g# turtle/tdemo_lindenmayer_indian.pycnu[PK%L]^turtle/tdemo_chaos.pyonu[PK%L]!KKBturtle/tdemo_tree.pycnu[PK%L]ʭ turtle/tdemo_fractalcurves.pycnu[PK%L]rTz%turtle/tdemo_clock.pycnu[PK%L] p||$7turtle/tdemo_I_dontlike_tiltdemo.pyonu[PK%L]%i((>turtle/tdemo_yinyang.pyonu[PK%L]^!Dturtle/tdemo_chaos.pycnu[PK%L]z _Mturtle/demohelp.txtnu[PK%L]g#|Yturtle/tdemo_lindenmayer_indian.pyonu[PK%L]/..gturtle/about_turtledemo.txtnu[PK%L]w[Ziturtle/tdemo_wikipedia.pycnu[PK%L]uUccGqturtle/tdemo_two_canvases.pyonu[PK%L]F\wturtle/tdemo_bytedesign.pycnu[PK%L]3'vuuturtle/tdemo_penrose.pycnu[PK%L]H}``turtle/tdemo_two_canvases.pynu[PK%L]v 11#lturtle/tdemo_I_dontlike_tiltdemo.pynuȯPK%L]::turtle/tdemo_colormixer.pynu[PK%L]{Ptturtle/tdemo_minimal_hanoi.pynuȯPK%L]HB  »turtle/tdemo_paint.pynuȯPK%L]F\turtle/tdemo_bytedesign.pyonu[PK%L]3'vuuturtle/tdemo_penrose.pyonu[PK%L]:Bmmturtle/tdemo_paint.pyonu[PK%L]jN= = turtle/tdemo_colormixer.pyonu[PK%L]uUccturtle/tdemo_two_canvases.pycnu[PK%L]iʈk'k'turtle/turtleDemo.pynuȯPK%L]ʏ s-turtle/tdemo_penrose.pynuȯPK%L]ؿy ;turtle/about_turtle.txtnu[PK%L]}W$$Iturtle/tdemo_nim.pycnu[PK%L]:8''nturtle/tdemo_yinyang.pynuȯPK%L]8Hw**qturtle/turtleDemo.pycnu[PK%L]Mkrrturtle/tdemo_nim.pynu[PK%L]pzzturtle/tdemo_bytedesign.pynuȯPK%L]%i((qturtle/tdemo_yinyang.pycnu[PK%L]ʭ turtle/tdemo_fractalcurves.pyonu[PK%L]S;Q Q turtle/tdemo_fractalcurves.pynuȯPK%L]px  turtle/tdemo_planet_and_moon.pynuȯPK%L]Ag: "turtle/tdemo_lindenmayer_indian.pynuȯPK%L]rTzturtle/tdemo_clock.pyonu[PK%L]j%))turtle/tdemo_peace.pynuȯPK%L]8Hw**$turtle/turtleDemo.pyonu[PK%L]Ĩkk -?rpc/rpc.pynu[PK%L]rVrpc/nfsclient.pycnu[PK%L]'Cj??rpc/T.pynu[PK%L]•rpc/mountclient.pynu[PK%L] x}vv /rpc/rpc.pycnu[PK%L] PZrpc/xdr.pycnu[PK%L]A)E E pyrpc/rnusersclient.pynu[PK%L]Wj rpc/READMEnu[PK%L]yOGii  rpc/MANIFESTnu[PK%L]}, Ŋrpc/xdr.pynu[PK%L]: rpc/T.pyonu[PK%L]?rpc/testnu[PK%L] 6O<  rpc/rnusersclient.pyonu[PK%L]: rpc/T.pycnu[PK%L]XPPٽrpc/mountclient.pycnu[PK%L] 6O<  lrpc/rnusersclient.pycnu[PK%L]"zrpc/nfsclient.pynu[PK%L] x}vv rpc/rpc.pyonu[PK%L] trpc/xdr.pyonu[PK%L]rrpc/nfsclient.pyonu[PK%L]XPP@rpc/mountclient.pyonu[PK%L]CCmetaclasses/Enum.pynu[PK%L]yHYmetaclasses/Eiffel.pyonu[PK%L]]P]PQmetaclasses/index.htmlnu[PK%L]á> 9metaclasses/Simple.pycnu[PK%L],.K Dmetaclasses/Eiffel.pynu[PK%L]VARmetaclasses/Meta.pycnu[PK%L]LԯC##dmetaclasses/Enum.pyonu[PK%L]YS}metaclasses/Trace.pycnu[PK%L]Ymetaclasses/Trace.pyonu[PK%L]metaclasses/Simple.pynu[PK%L]VAmetaclasses/Meta.pyonu[PK%L]LԯC##+metaclasses/Enum.pycnu[PK%L]zmetaclasses/Eiffel.pycnu[PK%L]L!!metaclasses/Synch.pycnu[PK%L]>Ͼo%%Cmetaclasses/Trace.pynu[PK%L]Ǫ>z z !metaclasses/Synch.pyonu[PK%L]6Q}kBmetaclasses/Synch.pynu[PK%L]á> ametaclasses/Simple.pyonu[PK%L]BO--lmetaclasses/meta-vladimir.txtnu[PK%L]Nιu u metaclasses/Meta.pynu[PK%L]DREADMEnu[PK%L]/ classes/Dates.pynu[PK%L]ΎMM`classes/Vec.pynu[PK%L]j%&&classes/Dbm.pynu[PK%L]EOclasses/Range.pyonu[PK%L] classes/Dbm.pycnu[PK%L](  classes/READMEnu[PK%L]u+&&classes/Complex.pynu[PK%L]1 1 classes/Rev.pycnu[PK%L]nL6 6 ~'classes/Range.pynu[PK%L]FI&'&'3classes/Complex.pyonu[PK%L]E][classes/Range.pycnu[PK%L]:6  kclasses/Vec.pyonu[PK%L]FI&'&'vclasses/Complex.pycnu[PK%L]cAC<5(5(Eclasses/bitvec.pyonu[PK%L]((classes/bitvec.pynu[PK%L]cAC<5(5(classes/bitvec.pycnu[PK%L]wsclasses/Dates.pycnu[PK%L]wZ5classes/Dates.pyonu[PK%L]:6  ARclasses/Vec.pycnu[PK%L]I]classes/Rev.pynu[PK%L] eclasses/Dbm.pyonu[PK%L]1 1 oclasses/Rev.pyonu[PK%L]Y M{md5test/md5driver.pyonu[PK%L]md5test/READMEnu[PK%L]A$5 md5test/foonu[PK%L]Y Šmd5test/md5driver.pycnu[PK%L]< md5test/md5driver.pynu[PK%L]J==zlib/minigzip.pycnu[PK%L]zlib/minigzip.pynuȯPK%L]J==zlib/minigzip.pyonu[PK%L]m(zlib/zlibdemo.pynuȯPK%L]tH%zlib/zlibdemo.pycnu[PK%L]tHAzlib/zlibdemo.pyonu[PK%L]]threads/Coroutine.pycnu[PK%L]3h!!9threads/find.pyonu[PK%L]threads/Coroutine.pyonu[PK%L]}c vthreads/telnet.pycnu[PK%L]Q, threads/Generator.pyonu[PK%L]; (threads/squasher.pynu[PK%L]B} 6AA4threads/squasher.pyonu[PK%L]__  }=threads/telnet.pynu[PK%L]IIthreads/READMEnu[PK%L]}c Kthreads/telnet.pyonu[PK%L]8Uthreads/Coroutine.pynu[PK%L]3h!!kthreads/find.pycnu[PK%L]Q, {threads/Generator.pycnu[PK%L] ,Sthreads/fcmp.pyonu[PK%L]Vm 0threads/Generator.pynu[PK%L]j+j+\threads/sync.pyonu[PK%L] ,threads/fcmp.pycnu[PK%L]j+j+threads/sync.pycnu[PK%L]eITTthreads/sync.pynu[PK%L]B} 6AAcLthreads/squasher.pycnu[PK%L]+wwTthreads/find.pynu[PK%L]7\ethreads/fcmp.pynu[PK%L]Sltix/tixwidgets.pynu[PK%L]gˆ tix/grid.pycnu[PK%L]{̖̖7tix/tixwidgets.pyonu[PK%L]b&UUEtix/samples/PopMenu.pyonu[PK%L]3U tix/samples/DirList.pyonu[PK%L]aaøtix/samples/SHList1.pyonu[PK%L]nb!ktix/samples/PanedWin.pycnu[PK%L]3U ;tix/samples/DirList.pycnu[PK%L]ûT T tix/samples/ComboBox.pynu[PK%L]N tix/samples/OptMenu.pynu[PK%L]qtix/samples/Control.pyonu[PK%L]tܙyytix/samples/NoteBook.pynu[PK%L]l/ / \!tix/samples/Tree.pynu[PK%L]7:BB,tix/samples/BtnBox.pycnu[PK%L]VGV2tix/samples/Balloon.pynu[PK%L]nb!t;tix/samples/PanedWin.pyonu[PK%L]Dl11DLtix/samples/CmpImg.pynu[PK%L]qhtix/samples/Control.pycnu[PK%L] txtix/samples/DirTree.pycnu[PK%L]*MB tix/samples/ComboBox.pycnu[PK%L] \ \ 4tix/samples/Balloon.pycnu[PK%L]88מtix/samples/PopMenu.pynu[PK%L]B~ gUtix/samples/SHList2.pycnu[PK%L]07bbvtix/samples/OptMenu.pyonu[PK%L]-tix/samples/PanedWin.pynu[PK%L]!_tix/samples/BtnBox.pynu[PK%L]D*_ _ tix/samples/NoteBook.pyonu[PK%L]B~ gitix/samples/SHList2.pyonu[PK%L]aatix/samples/SHList1.pycnu[PK%L]m7&~~2tix/samples/SHList1.pynu[PK%L]7:BBtix/samples/BtnBox.pyonu[PK%L]?Þ~tix/samples/CmpImg.pyonu[PK%L] tb3tix/samples/DirTree.pyonu[PK%L]zd3 3 Ctix/samples/Tree.pyonu[PK%L]sRg Mtix/samples/SHList2.pynu[PK%L]zd3 3 Tctix/samples/Tree.pycnu[PK%L]Saltix/samples/DirList.pynu[PK%L]?Þ~tix/samples/CmpImg.pycnu[PK%L] \ \ Θtix/samples/Balloon.pyonu[PK%L]*MB qtix/samples/ComboBox.pyonu[PK%L]i|##tix/samples/Control.pynu[PK%L]b&UUtix/samples/PopMenu.pycnu[PK%L]07bbtix/samples/OptMenu.pycnu[PK%L]JYtix/samples/DirTree.pynu[PK%L]D*_ _ ~tix/samples/NoteBook.pycnu[PK%L]{̖̖%tix/tixwidgets.pycnu[PK%L]F_ajj3tix/bitmaps/netw.xpmnu[PK%L]٦pt"+"+tix/bitmaps/tix.gifnuȯPK%L]LFtix/bitmaps/combobox.xpm.1nu[PK%L]r,5zz|tix/bitmaps/drivea.xbmnu[PK%L]rn(<tix/bitmaps/exit.xpmnu[PK%L]j  utix/bitmaps/about.xpmnu[PK%L]tttix/bitmaps/netw.xbmnu[PK%L]!""xtix/bitmaps/italic.xbmnu[PK%L]>(%%tix/bitmaps/justify.xbmnu[PK%L]Ltix/bitmaps/combobox.xbmnu[PK%L]{J _tix/bitmaps/optmenu.xpmnu[PK%L]TZye%%Ltix/bitmaps/centerj.xbmnu[PK%L]4 4 tix/bitmaps/select.xpmnu[PK%L]02tix/bitmaps/bold.xbmnu[PK%L]Ǐtix/bitmaps/leftj.xbmnu[PK%L]Hj"  tix/bitmaps/combobox.xpmnu[PK%L]{++Ltix/bitmaps/underline.xbmnu[PK%L]#1}}tix/bitmaps/filebox.xbmnu[PK%L]W=""tix/bitmaps/rightj.xbmnu[PK%L]5(=[[tix/bitmaps/drivea.xpmnu[PK%L]7o   tix/bitmaps/filebox.xpmnu[PK%L]*GS%%tix/bitmaps/capital.xbmnu[PK%L]gˆ Ftix/grid.pyonu[PK%L]Ftix/README.txtnu[PK%L]䠵&& tix/grid.pynu[PK%L]*ϰtix/INSTALL.txtnu[PK%L]Ir-scripts/makedir.pynuȯPK%L]u=ii%0scripts/from.pynuȯPK%L]hq 3scripts/update.pyonu[PK%L]8 >scripts/pp.pynuȯPK%L]Gx#Mscripts/makedir.pyonu[PK%L]#Qscripts/primes.pyonu[PK%L]aPOOTscripts/morse.pyonu[PK%L]Kfscripts/markov.pynuȯPK%L]T`tscripts/morse.pynuȯPK%L]@Iww scripts/pi.pynuȯPK%L]Lscripts/beer.pyonu[PK%L]`(scripts/fact.pyonu[PK%L]йescripts/markov.pycnu[PK%L]`scripts/eqfix.pynuȯPK%L]XiFscripts/queens.pynuȯPK%L]0yܺ Escripts/unbirthday.pycnu[PK%L]    Escripts/lpwatch.pynuȯPK%L]1:t t scripts/mboxconvert.pynuȯPK%L]Vscripts/from.pyonu[PK%L]scripts/from.pycnu[PK%L]zvscripts/READMEnu[PK%L]qDscripts/eqfix.pyonu[PK%L]L>scripts/beer.pycnu[PK%L]Gx#=scripts/makedir.pycnu[PK%L]VB \ scripts/queens.pyonu[PK%L]LC C nscripts/unbirthday.pynuȯPK%L]#"scripts/primes.pycnu[PK%L]aPOO&scripts/morse.pycnu[PK%L]]">a8scripts/find-uname.pynuȯPK%L]qD]=scripts/eqfix.pycnu[PK%L]ټgllOscripts/fact.pynuȯPK%L]hq cTscripts/update.pycnu[PK%L]`(l_scripts/fact.pycnu[PK%L](N ;dscripts/update.pynuȯPK%L]) - - 9oscripts/lpwatch.pycnu[PK%L] Byscripts/find-uname.pyonu[PK%L]0yܺ scripts/unbirthday.pyonu[PK%L]R~Ջscripts/pi.pyonu[PK%L]) - - scripts/lpwatch.pyonu[PK%L] Bscripts/find-uname.pycnu[PK%L]*R  Hscripts/pp.pycnu[PK%L]MHYZZscripts/primes.pynuȯPK%L]й?scripts/markov.pyonu[PK%L];:scripts/script.pynuȯPK%L]R~<scripts/pi.pycnu[PK%L]*R  scripts/pp.pyonu[PK%L]cA-Doscripts/script.pycnu[PK%L]C-scripts/beer.pynuȯPK%L]VB scripts/queens.pycnu[PK%L]G scripts/mboxconvert.pycnu[PK%L]G scripts/mboxconvert.pyonu[PK%L]cA-Dscripts/script.pyonu[PK%L]-; cgi/wiki.pyonu[PK%L]. cgi/cgi2.pyonu[PK%L]6f cgi/cgi3.pynuȯPK%L]``M cgi/cgi0.shnuȯPK%L]Rq cgi/READMEnu[PK%L]4 cgi/cgi2.pynuȯPK%L]_ cgi/cgi1.pynuȯPK%L]-hFF pcgi/cgi3.pyonu[PK%L]  cgi/cgi1.pyonu[PK%L]. E"cgi/cgi2.pycnu[PK%L]-; Z%cgi/wiki.pycnu[PK%L]-hFF :cgi/cgi3.pycnu[PK%L] <cgi/cgi1.pycnu[PK%L]7 l=cgi/wiki.pynu[PK%L]}*EE lMpysvr/READMEnu[PK%L]J~^5e e Npysvr/pysvr.pynuȯPK%L]ryk \pysvr/pysvr.cnu[PK%L]( ==}pysvr/Makefilenu[PK%L]W..3pysvr/pysvr.pycnu[PK%L]W..pysvr/pysvr.pyonu[PK%L]mz newmetaclasses/Enum.pynu[PK%L]aQYnewmetaclasses/Eiffel.pyonu[PK%L]e@Pwnewmetaclasses/Eiffel.pynu[PK%L];o@newmetaclasses/Enum.pyonu[PK%L];onewmetaclasses/Enum.pycnu[PK%L]|rr newmetaclasses/Eiffel.pycnu[PK%L]I8 ) xml/rss2html.pycnu[PK%L]I&&]4 xml/elem_count.pyonu[PK%L]I&&; xml/elem_count.pycnu[PK%L]d-C xml/roundtrip.pynu[PK%L]I8 ;H xml/rss2html.pyonu[PK%L]3W  S xml/rss2html.pynu[PK%L]‘߀V\ xml/elem_count.pynu[PK%L]@= = %a xml/roundtrip.pycnu[PK%L]@= = j xml/roundtrip.pyonu[PK%L]D!t comparisons/systemtest.pynuȯPK%L]&bY} comparisons/sortingtest.pyonu[PK%L]]|I  comparisons/READMEnu[PK%L]k4z comparisons/regextest.pynuȯPK%L], >>P comparisons/systemtest.pycnu[PK%L]'2ӎؗ comparisons/sortingtest.pynuȯPK%L]7\AA comparisons/regextest.pycnu[PK%L]%. comparisons/patternsnu[PK%L], >> comparisons/systemtest.pyonu[PK%L]7\AA comparisons/regextest.pyonu[PK%L]&b comparisons/sortingtest.pycnu[PK%L]F"s pdist/rrcs.pycnu[PK%L]%{Ș  pdist/rrcs.pynuȯPK%L]Udd pdist/client.pynu[PK%L]Zuu & pdist/rrcsnuȯPK%L] >L5L5  pdist/rcvs.pynuȯPK%L];DD^ !pdist/client.pycnu[PK%L]2"&:!pdist/FSProxy.pynu[PK%L]roQ8Q8Y!pdist/rcvs.pyonu[PK%L] , E!pdist/READMEnu[PK%L]l  )!pdist/rcsclient.pynu[PK%L]GGv!pdist/RCSProxy.pyonu[PK%L]Op!p!!pdist/cvslock.pyonu[PK%L]Șy!pdist/cmptree.pynu[PK%L]C"pdist/sumtree.pyonu[PK%L]e'wwJ"pdist/cmdfw.pyonu[PK%L]#)--"pdist/rcslib.pyonu[PK%L]F"\G"pdist/rrcs.pyonu[PK%L]5tVV ]"pdist/mac.pycnu[PK%L]''*`"pdist/cvslib.pynu[PK%L]l!!("pdist/cmdfw.pynu[PK%L]Z>N(N("pdist/rcslib.pynu[PK%L]C"pdist/sumtree.pycnu[PK%L]" t"pdist/server.pynu[PK%L]G"pdist/sumtree.pynu[PK%L]#44F"pdist/rcsclient.pycnu[PK%L]F N2 2 "pdist/makechangelog.pycnu[PK%L]Mi$116"pdist/FSProxy.pyonu[PK%L]roQ8Q8r"#pdist/rcvs.pycnu[PK%L](q [#pdist/makechangelog.pynuȯPK%L];DDf#pdist/client.pyonu[PK%L]ossw#pdist/RCSProxy.pynuȯPK%L]HxT3T3+#pdist/cvslib.pyonu[PK%L]e'ww#pdist/cmdfw.pycnu[PK%L]XB u#pdist/cmptree.pycnu[PK%L]GT[DD#pdist/security.pynu[PK%L]Zr`` &#pdist/mac.pynu[PK%L]Op!p!#pdist/cvslock.pycnu[PK%L]Mi$11s$pdist/FSProxy.pycnu[PK%L]HxT3T3N$pdist/cvslib.pycnu[PK%L]Kouu C$pdist/rcvsnuȯPK%L])SS$pdist/server.pyonu[PK%L]F N2 2 $pdist/makechangelog.pyonu[PK%L]5tVV $pdist/mac.pyonu[PK%L]@GF$pdist/security.pycnu[PK%L])SSd$pdist/server.pycnu[PK%L]XB $pdist/cmptree.pyonu[PK%L]#44#$pdist/rcsclient.pyonu[PK%L]@GF$pdist/security.pyonu[PK%L]#)--m$pdist/rcslib.pycnu[PK%L]Wss%pdist/cvslock.pynu[PK%L]P] |7%pdist/rcsbumpnuȯPK%L]GG:%pdist/RCSProxy.pycnu[PK%L].)S;;+Y%sockets/echosvr.pyonu[PK%L]~hD7&7&\%sockets/gopher.pynuȯPK%L]Yڎee!%sockets/telnet.pycnu[PK%L]\-ȋ%sockets/unixclient.pyonu[PK%L]%sockets/unicast.pyonu[PK%L]S(S(%sockets/gopher.pycnu[PK%L]S(S(V%sockets/gopher.pyonu[PK%L]߼U %sockets/telnet.pynuȯPK%L]q<%sockets/finger.pycnu[PK%L].)S;;%sockets/echosvr.pycnu[PK%L]vtt7%sockets/READMEnu[PK%L]ⱈ%sockets/mcast.pynuȯPK%L]Z6qA &sockets/throughput.pyonu[PK%L][gyy &sockets/mcast.pyonu[PK%L][gyyx&sockets/mcast.pycnu[PK%L]It2&sockets/unixserver.pynu[PK%L]Yڎee&sockets/telnet.pyonu[PK%L]`&&sockets/finger.pynuȯPK%L]+&sockets/radio.pynu[PK%L]FGG-&sockets/udpecho.pyonu[PK%L]'u5&sockets/rpython.pynuȯPK%L]'}&QQ8&sockets/unixserver.pyonu[PK%L]j{;&sockets/echosvr.pynuȯPK%L]Hz ;>&sockets/ftp.pycnu[PK%L])aJ&sockets/radio.pycnu[PK%L]SeL&sockets/rpython.pycnu[PK%L]ua5P&sockets/udpecho.pynuȯPK%L]$$2V&sockets/throughput.pynuȯPK%L]q<^&sockets/finger.pyonu[PK%L]Cgc&sockets/broadcast.pynu[PK%L]Z6qA d&sockets/throughput.pycnu[PK%L]dBT77n&sockets/rpythond.pyonu[PK%L]c0t&sockets/rpythond.pynuȯPK%L]##0y&sockets/broadcast.pyonu[PK%L]##{&sockets/broadcast.pycnu[PK%L]'}&QQ~&sockets/unixserver.pycnu[PK%L])a&sockets/radio.pyonu[PK%L]\-&sockets/unixclient.pycnu[PK%L]&sockets/unicast.pycnu[PK%L]Hz &sockets/ftp.pyonu[PK%L]^XXq&sockets/ftp.pynu[PK%L]IA}&sockets/unixclient.pynu[PK%L]FG4&sockets/udpecho.pycnu[PK%L]Seb&sockets/rpython.pyonu[PK%L]dBT77{&sockets/rpythond.pycnu[PK%L]l&sockets/unicast.pynu[PK%L]'njCjC&parser/unparse.pynu[PK%L]g$$&parser/example.pyonu[PK%L]ɣ=]]/'parser/unparse.pycnu[PK%L]n66t'parser/test_parser.pynuȯPK%L]$00y'parser/source.pycnu[PK%L]^ 'parser/READMEnu[PK%L]y=ZZЃ'parser/example.pynu[PK%L]Nk[[ k'parser/FILESnu[PK%L]rX'parser/docstring.pycnu[PK%L]c'parser/simple.pyonu[PK%L]64?!!M'parser/test_unparse.pyonu[PK%L]0b'parser/test_parser.pycnu[PK%L]9\n]n]K'parser/unparse.pyonu[PK%L]qϭ"(parser/simple.pynu[PK%L]X#(parser/test_unparse.pynu[PK%L]c_9(parser/simple.pycnu[PK%L]G:(parser/docstring.pynu[PK%L]g$$;(parser/example.pycnu[PK%L]$00{W(parser/source.pyonu[PK%L]rX](parser/docstring.pyonu[PK%L]GjD^(parser/source.pynu[PK%L]64?!!b(parser/test_unparse.pycnu[PK%L]0(parser/test_parser.pyonu[PK%L] c c (curses/rain.pynuȯPK%L]@@(curses/tclock.pycnu[PK%L]2O$(curses/life.pycnu[PK%L]ϐ(curses/rain.pycnu[PK%L]̥TT (curses/READMEnu[PK%L]r;5(curses/life.pynuȯPK%L]%(curses/repeat.pyonu[PK%L]@@(curses/tclock.pyonu[PK%L]cQ(curses/ncurses.pycnu[PK%L]lҗ&)curses/repeat.pynuȯPK%L]cQQ)curses/ncurses.pyonu[PK%L]٪  h/)curses/tclock.pynuȯPK%L] fcfc<)curses/xmas.pynu[PK%L]2OO)curses/life.pyonu[PK%L]ϐ)curses/rain.pyonu[PK%L] XA?G)curses/ncurses.pynuȯPK%L]`gjMM)curses/xmas.pyonu[PK%L]`gjMMW,*curses/xmas.pycnu[PK%L]%.z*curses/repeat.pycnu[PK%L]H *embed/loop.cnu[PK%L]_66 <*embed/READMEnu[PK%L]'\*embed/importexc.cnu[PK%L]9ʃ*embed/Makefilenu[PK%L]& *embed/demo.cnu[PK r*