Пример #1
0
class GUI(Frame):
    def __init__(self, master=None, **kw):
        Frame.__init__(self, master, **kw)
        self.initialize()

    def initialize(self):
        self.master.title(settings.APP_TITLE)

        self.pack(fill=Tkinter.BOTH, expand=1)

        self.columnconfigure(1, weight=1)
        self.columnconfigure(3, pad=7)
        self.rowconfigure(3, weight=1)
        self.rowconfigure(5, pad=7)

        lbl = Label(self, text="Журнал")
        lbl.grid(sticky=Tkinter.W, pady=4, padx=5)

        self.area = Tkinter.Text(self)
        self.area.grid(row=1,
                       column=0,
                       columnspan=2,
                       rowspan=4,
                       padx=5,
                       sticky=Tkinter.E + Tkinter.W + Tkinter.S + Tkinter.N)

        self.widgetLogger = WidgetLogger(self.area)

        lbl = Label(self, text="Адрес репозитория: ")
        lbl.grid(row=6)

        self.repo_addr_str = Tkinter.StringVar()
        self.repo_addr = Tkinter.Entry(self, textvariable=self.repo_addr_str)
        self.repo_addr.grid(row=7)

        lbl = Label(self, text="FTP для размещения: ")
        lbl.grid(row=6, column=1)

        self.ftp_addr_str = Tkinter.StringVar()
        self.ftp_addr = Tkinter.Entry(self, textvariable=self.ftp_addr_str)
        self.ftp_addr.grid(row=7, column=1, pady=1)

        self.deploybtn = Button(self,
                                text="Начать обновление",
                                command=self.start_update_thread)
        self.deploybtn.grid(row=10)

    def start_update_thread(self):
        # resetting vars
        settings.DEFAULT_FTP_HOST = self.ftp_addr_str.get()
        settings.DEFAULT_GIT_REPO = self.repo_addr_str.get()

        self.deploybtn.config(text="Идет обновление...",
                              state=Tkinter.DISABLED)

        tr = Thread(target=lambda: full_cycle(self))
        tr.start()
	def button_component(self, button_txt, init_txt, r, c, help_txt='', mode=NORMAL):
		'''adds a button component associated with an entry (the label only activates when help_txt != '')'''
		b = Button(self, text=button_txt)
		b.grid(row=r, column=c, sticky=W+E)
		b.config(state=mode)
		dir_var = StringVar()
		dir_var.set(init_txt)
		Entry(self, textvariable=dir_var).grid(row=r, column=c+1)
		Label(self, text=help_txt).grid(row=r, column=c+2, sticky=W)
		b.configure(command=lambda: self.browse_dir(dir_var, b))
		return dir_var
Пример #3
0
class IPSettingsDialog(object, Dialog):
    def __init__(self, parent, settings, title):
        self.settings = settings
        Dialog.__init__(self, parent, title)

    def body(self, parent):
        self.tkVar = IntVar()
        self.tkVar.set(-1)
        tkRb1 = Radiobutton(parent,
                            text="QT Console",
                            variable=self.tkVar,
                            value=0,
                            command=self.radio_select)
        tkRb1.grid(row=0)
        tkRb2 = Radiobutton(parent,
                            text="Notebook",
                            variable=self.tkVar,
                            value=1,
                            command=self.radio_select)
        tkRb2.grid(row=1)

        self.tkDir = StringVar()
        self.tkDir.set(self.settings.notebook_dir)
        self.tkDirEntry = Entry(parent,
                                textvariable=self.tkDir,
                                state="disabled")
        self.tkDirEntry.grid(row=2, column=0)
        self.tkBrowseButton = Button(parent,
                                     text="Browse",
                                     state="disabled",
                                     command=self.get_directory)
        self.tkBrowseButton.grid(row=2, column=1)

    def apply(self):
        rad = int(self.tkVar.get())
        note_dir = str(self.tkDir.get())
        self.result = rad, note_dir

    def radio_select(self):
        if self.tkVar.get() == 1:
            self.tkDirEntry.config(state="normal")
            self.tkBrowseButton.config(state="normal")
        else:
            self.tkDirEntry.config(state="disabled")
            self.tkBrowseButton.config(state="disabled")

    def get_directory(self):
        options = {
            'mustexist': True,
            'title': 'Please select a directory for IPython notebooks'
        }
        folder_path = tkFileDialog.askdirectory(**options)
        self.tkDir.set(folder_path)
Пример #4
0
class GUI(Frame):
    def __init__(self, master=None, **kw):
        Frame.__init__(self, master, **kw)
        self.initialize()

    def initialize(self):
        self.master.title(settings.APP_TITLE)

        self.pack(fill=Tkinter.BOTH, expand=1)

        self.columnconfigure(1, weight=1)
        self.columnconfigure(3, pad=7)
        self.rowconfigure(3, weight=1)
        self.rowconfigure(5, pad=7)

        lbl = Label(self, text="Журнал")
        lbl.grid(sticky=Tkinter.W, pady=4, padx=5)

        self.area = Tkinter.Text(self)
        self.area.grid(row=1, column=0, columnspan=2, rowspan=4,
                       padx=5, sticky=Tkinter.E + Tkinter.W + Tkinter.S + Tkinter.N)

        self.widgetLogger = WidgetLogger(self.area)

        lbl = Label(self, text="Адрес репозитория: ")
        lbl.grid(row=6)

        self.repo_addr_str = Tkinter.StringVar()
        self.repo_addr = Tkinter.Entry(self, textvariable=self.repo_addr_str)
        self.repo_addr.grid(row=7)

        lbl = Label(self, text="FTP для размещения: ")
        lbl.grid(row=6, column=1)

        self.ftp_addr_str = Tkinter.StringVar()
        self.ftp_addr = Tkinter.Entry(self, textvariable=self.ftp_addr_str)
        self.ftp_addr.grid(row=7, column=1, pady=1)

        self.deploybtn = Button(self, text="Начать обновление", command=self.start_update_thread)
        self.deploybtn.grid(row=10)

    def start_update_thread(self):
        # resetting vars
        settings.DEFAULT_FTP_HOST = self.ftp_addr_str.get()
        settings.DEFAULT_GIT_REPO = self.repo_addr_str.get()

        self.deploybtn.config(text="Идет обновление...", state=Tkinter.DISABLED)

        tr = Thread(target=lambda: full_cycle(self))
        tr.start()
Пример #5
0
    def nuevoPais(self):
        t = Toplevel(self)
        t.wm_title("Pais")

        Label(t, text="Nombre").grid(row=0, column=1)
        E2 = Entry(t)
        E2.grid(row=1, column=1)

        button1 = Button(t, text="Cancelar", command=lambda: t.destroy())
        button2 = Button(t, text="Guardar", command=lambda: self.nuevaEntradaPais(E2.get(), t))
        button3 = Button(t, text="Borrar", command=lambda: self.BorrarPais(E2.get(), t))
        button3.config(state="disabled")

        button1.grid(row=2, column=0)
        button2.grid(row=2, column=1)
        button3.grid(row=2, column=2)
Пример #6
0
 def button_component(self,
                      button_txt,
                      init_txt,
                      r,
                      c,
                      help_txt='',
                      mode=NORMAL):
     '''adds a button component associated with an entry (the label only activates when help_txt != '')'''
     b = Button(self, text=button_txt)
     b.grid(row=r, column=c, sticky=W + E)
     b.config(state=mode)
     dir_var = StringVar()
     dir_var.set(init_txt)
     Entry(self, textvariable=dir_var).grid(row=r, column=c + 1)
     Label(self, text=help_txt).grid(row=r, column=c + 2, sticky=W)
     b.configure(command=lambda: self.browse_dir(dir_var, b))
     return dir_var
Пример #7
0
class NGA_Window_LowMag(Frame):


    #homePos = [-10,0,2]
    homePos = [0,0,0]
    
    scanMirror = [2.3,-20,0] #for Dry

    options = [
        "NSF AIR - 90nm",
        "NV16 - 30nm",
        "NV10 - 90nm",
        "NV10B - 60nm",
        "NV16B - 60nm",
        "NV16B (dry) - 60nm"
    ]
    # Chip Modes: (*** note: ask Dave to make cooler chip names ***)
    #   1. NSF AIR - 90nm
    #   2. NV16 - 30nm
    #   3. NV10 - 90nm
    #   4. NV10B - 60nm
    #   5. NV16B - 60nm

    zoff = 0 #when stages are misaligned
    scanNSFAIR_1 = [-0.5,-18.1,-1+zoff]
    scanNSFAIR_2 = [-0.5,-18.1,-1+zoff]
    scanNV16_1 = [1.1,-18.1,-1+zoff] 
    scanNV16_2 = [1.1,-18.1,-1+zoff]
    scanNV10_1 = [2.3,-20,0+zoff] 
    scanNV10_2 = [2.3,-20,0+zoff] 
    scanNV10B_1 = [2.3,-20,0+zoff] 
    scanNV10B_2 = [2.3,-20,0+zoff] 
    scanNV16B_1 = [4.5,-20,0+zoff] 
    scanNV16B_2 = [4.5,-20,0+zoff]

    # Old modes commented out rather than deleted, for sanity.
    #scan90_1 = [1.0,-13.6,-1.4-1.8] #for Dry
    #scan90_2 = [1.0,-13.6,-1.85-1.8] #for Dry
    #scan60_1 = [1.0,-13.6,-1.2-1.8] #for Dry
    #scan60_2 = [1.0,-13.6,-1.85-1.8] #for Dry
    #scan30_1 = [2.6,-13.6,-1.4-1.8] #for Liquid
    #scan30_2 = [2.6,-13.6,-1.85-1.8] #for Liquid
    #scan60Long_1 = [4.0,-13.6,-1.2-1.8] #for Dry Long
    #scan60Long_2 = [4.0,-13.6,-1.85-1.8] #for Dry Long
     

    def __init__(self,parent,sys):
        Frame.__init__(self,parent)

        self.parent = parent
        self.sys = sys

        self.sys.c_lowmag = self

        self.parent.geometry(self.sys.win_cfg.wLowMag)
        self.parent.title(self.sys.win_cfg.sLowMag)
        
        self.sys.c_cam.setup_camera()
        self.sys.c_led.led_serial_status()
        if(self.sys.c_led.status == ":0"):
                self.sys.c_stage.home_stages()
                        
        self.longchip = 0
        
        self.initUI()

    def initUI(self):

        self.style = Style().configure("TFrame", background=self.sys.win_cfg.cBackground)
        self.pack(fill=BOTH, expand=1)

        titleLabel = Label(self, text=self.sys.win_cfg.sLowMag,
                            background="light blue",
                            width=15, height=1)
        titleLabel.place(x=5, y=5)

        prefixLabel= Label(self, text="File Prefix",
                                   background = self.sys.win_cfg.cBackground,width=9, height=1)
        prefixLabel.place(x=5, y=60)

        self.prefixEntry = Entry(self, width=30,background=self.sys.win_cfg.cTextBackground)
        self.prefixEntry.place(x=10, y=85)

        self.prefixEntry.insert(0,"CHIP")

        numberLabel= Label(self, text="Chip #",
                                   background = self.sys.win_cfg.cBackground,width=9, height=1)
        numberLabel.place(x=5, y=110)

        self.numberEntry = Entry(self, width=10,
                                         justify="center",background=self.sys.win_cfg.cTextBackground)
        self.numberEntry.place(x=10, y=135)

        self.numberEntry.insert(0,"1")
        
        if (self.checkIm(str(1)) == True):
            self.numberEntry.config(background="green")
        else:
            self.numberEntry.config(background="red")

        self.numDownButton = Button(self, text="prev",command=self.numDown, width=5)
        self.numDownButton.place(x=80, y=120)

        self.numUpButton = Button(self, text="next",command=self.numUp, width=5)
        self.numUpButton.place(x=80, y=145)

        self.deleteButton = Button(self, text="Delete",command=self.deleteIm, width = 10)
        self.deleteButton.place(x=125, y = 130)

        #self.stitchButton = Button(self, text="Stitch",command=self.stitch, width = 10)
        #self.stitchButton.place(x=125, y = 5)

        

        

        self.acquireButton = Button(self, text="Acquire",command=self.acquire, width = 20)
        self.acquireButton.place(x=5,y=180)

        self.mirrorButton = Button(self, text="Mirror",command=self.mirrorBtn, width = 5)
        self.mirrorButton.place(x=150,y=180)

        self.loadButton = Button(self, text="Unload",command=self.unload, width = 8)
        self.loadButton.place(x=130, y=30)   
        self.autoUnload = IntVar()
        self.autoUnload.set(1)

        self.autoUnloadCheck = Checkbutton(self, text = "Auto-Unload", variable = self.autoUnload, \
                                            onvalue = 1, offvalue = 0, height=1, \
                                            width = 10)
        self.autoUnloadCheck.place(x=90, y=60)

        self.v = IntVar()

        self.v.set(0)

        # Setting up the option box for the chip version
        self.chipMode = StringVar()
        self.chipMode.set(self.options[3]) # Default value
        self.chipSelect = OptionMenu(self,self.chipMode,*self.options)
        self.chipSelect.place(x=5, y=30)
        
        #self.modeDryV2 = Radiobutton(self, text="60", variable=self.v, value=0)
        #self.modeDryV2.place(x=5, y=30)
        #self.modeDry = Radiobutton(self, text="90", variable=self.v, value=1)
        #self.modeDry.place(x=45, y=30)
        #self.modeWet = Radiobutton(self, text="30", variable=self.v, value=2)
        #self.modeWet.place(x=85, y=30)

        #self.longCheck = Radiobutton(self, text="60-Long", variable=self.v, value=3)
        #self.longCheck.place(x=125, y = 5)

    def numUp(self):
        num = self.numberEntry.get()
        num = str(int(num)+1);
        self.numberEntry.delete(0, END)
        self.numberEntry.insert(0,str(int(num)))
        if (self.checkIm(num) == True):
            self.numberEntry.config(background="green")
        else:
            self.numberEntry.config(background="red")


    def numDown(self):
        num = self.numberEntry.get()
        if(int(num) > 1):
            num = str(int(num)-1);
            self.numberEntry.delete(0, END)
            self.numberEntry.insert(0,str(int(num)))
            if (self.checkIm(num) == True):
                self.numberEntry.config(background="green")
            else:
                self.numberEntry.config(background="red")


    def deleteIm(self):
            today = date.today()
            todaystr = str(today.year) +"-"+str(today.month) +"-"+str(today.day) +"/"
            todaystr = time.strftime("%Y-%m-%d") + "/"
            prefix = self.prefixEntry.get() + "_"
            num = self.numberEntry.get()
            os.remove("../data/" + todaystr + prefix + num.zfill(3)+"_1.png") 
            os.remove("../data/" + todaystr + prefix + num.zfill(3)+"_2.png")
            if (self.checkIm(num) == True):
                    self.numberEntry.config(background="green")
            else:
                    self.numberEntry.config(background="red")

    def mirrorBtn(self):
        self.mirror()
        #self.focus()
        
    def dataMirrorFiles(self):
        runMore = 0
        mirror_exists = self.mirror_exists()
        if (mirror_exists == False ):
            proceed = self.checkMirrorFiles()
            if (proceed == 0): #mirror is not old
                self.mirror_copy()
                runMore = 1
            elif (proceed == 1): # take new mirror
                runMore = 0
            elif (proceed == 2): #use old mirror
                self.mirror_copy()
                runMore = 1
        else:
            runMore = 1
        return runMore
            
    def checkMirrorFiles(self):
        proceed = 0
        mirror_fn1 = "../data/mirror/MIRROR_01.png"
        mirror_fn2 = "../data/mirror/MIRROR_02.png"
        
        mir_fold = "../data/mirror/"

        
        mirror_date = time.strftime("%Y-%m-%d",time.gmtime(os.path.getmtime(mirror_fn1)))
        days_since = self.days_between(mirror_date,time.strftime("%Y-%m-%d",time.gmtime()))
        if (days_since > 6):
            result = tkMessageBox.askyesno("Mirror File","It has been %d days since you took a mirror, would you like to take a new mirror before scanning?" % days_since)
            if (result == True):
                proceed = 1 #"Take new mirror"
            else:
                proceed = 2 #"Use existing mirror"
            
        return proceed
    
    def days_between(self,d1, d2):
        d1b = datetime.strptime(d1, "%Y-%m-%d")
        d2b = datetime.strptime(d2, "%Y-%m-%d") 
        return abs((d2b - d1b).days)
    
    def focus(self, focus_point = 1, led_color = 1):
            '''
            mode = self.v.get() 
            if(mode == 2): #30 nm
                if (led_color == 1):
                    scanPos = self.scan30_1
                elif (led_color == 2):
                    scanPos = self.scan30_2
            elif(mode == 1): #90 nm
                if (led_color == 1):
                    scanPos = self.scan90_1
                elif (led_color == 2):
                    scanPos = self.scan90_2
            elif(mode == 0): #30 nm
                if (led_color == 1):
                    scanPos = self.scan60_1
                elif (led_color == 2):
                    scanPos = self.scan60_2        
            elif(mode == 3): #60 long
                if (led_color == 1):
                    scanPos = self.scan60Long_1
                elif (led_color == 2):
                    scanPos = self.scan60Long_2             
            '''
            mode = self.chipMode.get()
            if(mode == self.options[0]):
                if(led_color == 1):
                    scanPos = self.scanNSFAIR_1
                elif(led_color == 2):
                    scanPos = self.scanNSFAIR_2
            elif(mode == self.options[1]):
                if(led_color == 1):
                    scanPos = self.scanNV16_1
                elif(led_color == 2):
                    scanPos = self.scanNV16_2
            elif(mode == self.options[2]):
                if(led_color == 1):
                    scanPos = self.scanNV10_1
                elif(led_color == 2):
                    scanPos = self.scanNV10_2
            elif(mode == self.options[3]):
                if(led_color == 1):
                    scanPos = self.scanNV10B_1
                elif(led_color == 2):
                    scanPos = self.scanNV10B_2
            elif(mode == self.options[4]):
                if(led_color == 1):
                    scanPos = self.scanNV16B_1
                elif(led_color == 2):
                    scanPos = self.scanNV16B_2
            elif(mode == self.options[5]):
                if(led_color == 1):
                    scanPos = self.scanNV16B_1
                elif(led_color == 2):
                    scanPos = self.scanNV16B_2
            
            
            self.sys.c_cam.close_realtime()
            oldfrms = self.sys.hw.cam.frms
            self.sys.hw.cam.frms = str(1)
            scores = []
            zpos = []
            for x in range(-50, 30, 5):
                offsetval = x/100
                self.sys.hw.stg.move_z(scanPos[2]+offsetval)
                z_status = self.sys.hw.stg.status_z()
                while ( (z_status['axis_moving'] == True)):
                    time.sleep(0.05)
                    z_status = self.sys.hw.stg.status_z()
                self.sys.hw.cam.dog_image(1)
                scores.append(float(self.sys.hw.cam.dog_score))
                #print scanPos[2]+offsetval
                zpos.append(scanPos[2]+offsetval)
            
            self.sys.hw.cam.frms = oldfrms
            
            # set focus to max change of slope
            y = numpy.gradient(scores)
            zs = numpy.argmax(y)
            zs2 = numpy.argmax(scores)
            zsmin = numpy.argmin(scores)
            
            if (focus_point == 0): # middle of slope
                focus_z = zs
            elif (focus_point == 1): #max of score
                focus_z = zs2
            elif (focus_point == 2): #min of score
                focus_z = zsmin
                    
            if (0):
                plt.interactive(True) #need to add this or program freezes while plotting
                plt.plot(zpos,scores)
                plt.show()               
                fig2 = plt.figure()
                zero_crossings = numpy.where(numpy.diff(numpy.sign(y)))[0]
                #print zero_crossings
                plt.plot(zpos,y)
                plt.plot(zpos[focus_z],y[focus_z],'gx')
                plt.show()
            
            ## move to z
            print(zpos[focus_z])
            print "Focus: " + str(focus_point)  + " - " + str(zpos[focus_z])
            self.sys.hw.stg.move_z(zpos[focus_z])
            z_status = self.sys.hw.stg.status_z()
            while ( (z_status['axis_moving'] == True)):
                time.sleep(0.05)
                z_status = self.sys.hw.stg.status_z()
            
            
    def moveAndCheck(self, x, y):
        self.sys.hw.stg.move_x(x)
        self.sys.hw.stg.move_y(y)
        x_status = self.sys.hw.stg.status_x()
        while ( (x_status['axis_moving'] == True)):
                time.sleep(0.05)
                x_status = self.sys.hw.stg.status_x()
        
        y_status = self.sys.hw.stg.status_y()
        while ( (y_status['axis_moving'] == True)):
                time.sleep(0.05)
                y_status = self.sys.hw.stg.status_y()
                
    def read_pgm(self, filename, byteorder='>'):
        #"""Return image data from a raw PGM file as numpy array.
    #
     #   Format specification: http://netpbm.sourceforge.net/doc/pgm.html
    

        with open(filename, 'rb') as f:
            buffer = f.read()
        try:
            header, width, height, maxval = re.search(
                b"(^P5\s(?:\s*#.*[\r\n])*"
                b"(\d+)\s(?:\s*#.*[\r\n])*"
                b"(\d+)\s(?:\s*#.*[\r\n])*"
                b"(\d+)\s(?:\s*#.*[\r\n]\s)*)", buffer).groups()
        except AttributeError:
            raise ValueError("Not a raw PGM file: '%s'" % filename)
        return numpy.frombuffer(buffer,
                                dtype='u1' if int(maxval) < 256 else byteorder+'u2',
                                count=int(width)*int(height),
                                offset=len(header)
                                ).reshape((int(height), int(width)))
                                       
    def mirror(self):
        start_time = time.time()
        self.mirror1()
        self.mirror2()
        self.mirror_copy()
        elapsed_time = time.time() - start_time
        str_cap = "Mirror Time: {0:.2f} s.".format(elapsed_time)
        print str_cap
    
    def mirror2(self):
            self.disableButtons()
            
            #self.backup_mirror() #make copy of mirror before replacing
            
            today = date.today()
            #todaystr = str(today.year) +"-"+str(today.month) +"-"+str(today.day) +"\\"
            folder = "../data/mirror/" # + todaystr
            image = []
            for i in range(0,9):
                fn1 = folder + "MIRROR_01_" + str(i) + ".pgm"
                image.append(self.read_pgm(fn1, byteorder='>'))
                os.remove(fn1)
                #plt.imshow(image)
                #plt.show()
                
            #d = numpy.array([image[0],image[1],image[2],image[3],image[4],image[5],image[6],image[7],image[8]])
            e = numpy.median(image, axis=0)
   
            fn1 = folder + "MIRROR_01" + ".png"
            f = open(fn1, 'wb')      # binary mode is important
            w = png.Writer(len(e[0]), len(e), greyscale=True, bitdepth=16)
            w.write(f, e)
            f.close()
            
            image = []
            for i in range(0,9):
                fn2 = folder + "MIRROR_02_" + str(i) + ".pgm"
                image.append(self.read_pgm(fn2, byteorder='>'))
                os.remove(fn2)
                #plt.imshow(image)
                #plt.show()
                
            #d = numpy.array([image[0],image[1],image[2],image[3],image[4],image[5],image[6],image[7],image[8]])
            e = numpy.median(image, axis=0)
   
            fn2 = folder + "MIRROR_02" + ".png"
            f = open(fn2, 'wb')      # binary mode is important
            w = png.Writer(len(e[0]), len(e), greyscale=True, bitdepth=16)
            w.write(f, e)
            f.close()
            self.enableButtons()
#             if (len(filename2) > 0):
#                 imgA = mpimg.imread(filename2,cv2.IMREAD_GRAYSCALE)
#                 img2A = cv2.resize(imgA, (0,0), fx=0.5, fy=0.5)
#                 heightA, width1A, channelsA = img2A.shape
#                 
#                 blue_image = img2A[:,:,1]
#                 red_image = img2[:,:,1]
#                     
#                 blank_image = 255*numpy.ones((height,width1,3), numpy.uint8)
#                 blank_image[:,:,0] = blank_image[:,:,0]-red_image
#                 blank_image[:,:,2] = blank_image[:,:,2]-blue_image
# 
#                 plt.imshow(blank_image)

    def backup_mirror(self):
        mir_fold = "../data/mirror/"
        
        og_fn1 = mir_fold + "MIRROR_01" + ".png"
        og_fn2 = mir_fold + "MIRROR_02" + ".png"
        
        mirror_date = time.strftime("%Y-%m-%d",time.gmtime(os.path.getmtime(og_fn1)))

        folder = "../data/mirror/" + mirror_date + "/"
        fn1 = folder + "MIRROR_01" + ".png"
        fn2 = folder + "MIRROR_02" + ".png"
        
        if(os.path.isdir(folder) == False):
                os.mkdir(folder)
        
        copyfile(og_fn1, fn1)
        copyfile(og_fn2, fn2)
        os.remove(og_fn1)
        os.remove(og_fn2)
        
    def mirror_exists(self):
        today = date.today()        
        todaystr = str(today.year) +"-"+str(today.month) +"-"+str(today.day) +"/"
        todaystr = time.strftime("%Y-%m-%d") + "/"
        folder = "../data/" + todaystr
        fn1 = folder + "MIRROR_01" + ".png"
        fn2 = folder + "MIRROR_02" + ".png"
        
        file1 = os.path.isfile(fn1)
        file2 = os.path.isfile(fn2) 
        
        return (file1 and file2)
        
    def mirror_copy(self): #copy mirror to data folder
        today = date.today()
        todaystr = str(today.year) +"-"+str(today.month) +"-"+str(today.day) +"/"

        todaystr = time.strftime("%Y-%m-%d") + "/"
        folder = "../data/" + todaystr
        fn1 = folder + "MIRROR_01" + ".png"
        fn2 = folder + "MIRROR_02" + ".png"
        
        mir_fold = "../data/mirror/"
        
        if(os.path.isdir(folder) == False):
                os.mkdir(folder)
        
        og_fn1 = mir_fold + "MIRROR_01" + ".png"
        og_fn2 = mir_fold + "MIRROR_02" + ".png"
        
        copyfile(og_fn1, fn1)
        copyfile(og_fn2, fn2)
        
    def mirror1(self):
            
            self.load()
            self.disableButtons()
            today = date.today()
            #todaystr = str(today.year) +"-"+str(today.month) +"-"+str(today.day) +"\\"
            folder = "../data/mirror/" # + todaystr
            if(os.path.isdir(folder) == False):
                os.mkdir(folder)
            #self.sys.c_cam.close_realtime()

            xoffsets = [-0.512, -0.512, -0.512, 0, 0, 0, 0.512, 0.512, 0.512]
            yoffsets = [-0.512, 0, 0.512, -0.512, 0, 0.5, -0.512, 0, 0.512]
            
            self.sys.hw.led.command(NGA_Interface_LED.LED_OFF)
            self.sys.hw.led.command(NGA_Interface_LED.LED1_ON)
            self.focus(1) #max peak
            
            for i in range(0,9):
                xpos = self.scanMirror[0] + xoffsets[i]
                ypos = self.scanMirror[1] + yoffsets[i]
                self.moveAndCheck(xpos, ypos)
                fn1 = folder + "MIRROR_01_" + str(i)
                self.sys.hw.cam.fn = fn1
                self.sys.hw.cam.imagePGM()
                
            self.sys.hw.led.command(NGA_Interface_LED.LED_OFF)
            self.sys.hw.led.command(NGA_Interface_LED.LED2_ON)
            self.focus(1) #max peak
            
            for i in range(0,9):
                xpos = self.scanMirror[0] + xoffsets[i]
                ypos = self.scanMirror[1] + yoffsets[i]
                self.moveAndCheck(xpos, ypos)
                fn2 = folder + "MIRROR_02_" + str(i)
                self.sys.hw.cam.fn = fn2
                self.sys.hw.cam.imagePGM()
            
    
            self.enableButtons()
            
            aunload = self.autoUnload.get()

            if (aunload > 0):
                self.unload()  
            
            
    def acquire(self):
        run = self.dataMirrorFiles() #check for mirror first
        if (run == 1):
            self.acquire_data() #acquire data
        
    def acquire_data(self):
            #mode = self.v.get()
            mode = self.chipMode.get()
            start_time = time.time()
            self.load()
            self.disableButtons()
            today = date.today()
            todaystr = str(today.year) +"-"+str(today.month) +"-"+str(today.day) +"/"
            todaystr = time.strftime("%Y-%m-%d") + "/"
            folder = "../data/" + todaystr
            if(os.path.isdir(folder) == False):
                os.mkdir(folder)
            #self.sys.c_cam.close_realtime()
            
            num = self.numberEntry.get().zfill(3)
            
            ## LED1
            ledn = 1
            fn1 = folder + self.prefixEntry.get()+"_"+num + "_1"
            self.sys.hw.cam.fn = fn1
            self.sys.hw.led.command(NGA_Interface_LED.LED_OFF)
            self.sys.hw.led.command(NGA_Interface_LED.LED1_ON)

            print("before focus 1. mode = " + mode)

            '''
            if (mode == 2): #30
                self.focus(1,ledn) #min score
            elif (mode == 1): #90
                self.focus(0,ledn) #max slope
            elif (mode == 0): #60
                self.focus(1,ledn) #max score
            '''
            if(mode == self.options[0]):
                self.focus(0,ledn)
            elif(mode == self.options[1]):
                self.focus(1,ledn)
            elif(mode == self.options[2]):
                self.focus(0,ledn)
            elif(mode == self.options[3]):
                self.focus(1,ledn)
            elif(mode == self.options[4]):
                self.focus(1,ledn)
            elif(mode == self.options[5]):
                self.focus(1,ledn)
            print('done with first focus')
            self.sys.hw.cam.image()
            print('done with first image')
            ## LED 2
            ledn = 2
            fn2 = folder + self.prefixEntry.get()+"_"+num + "_2"
            self.sys.hw.cam.fn = fn2
            self.sys.hw.led.command(NGA_Interface_LED.LED_OFF)
            self.sys.hw.led.command(NGA_Interface_LED.LED2_ON)
            '''
            if (mode == 2): #30
                self.focus(2,ledn) #min score
            elif (mode == 1): #90
                self.focus(1,ledn) #max score
            elif (mode == 0): #60
                self.focus(1,ledn) #max score
            '''
            print('before focus 2')
            if(mode == self.options[0]):
                self.focus(0,ledn)
            elif(mode == self.options[1]):
                self.focus(1,ledn)
            elif(mode == self.options[2]):
                self.focus(0,ledn)
            elif(mode == self.options[3]):
                self.focus(1,ledn)
            elif(mode == self.options[4]):
                self.focus(1,ledn)
            elif(mode == self.options[5]):
                self.focus(1,ledn)                
            print('second focus complete')
            
            self.sys.hw.cam.image()
            self.sys.hw.led.command(NGA_Interface_LED.LED_OFF)
            self.sys.hw.led.command(NGA_Interface_LED.LED1_ON)
            if (self.checkIm(num) == True):
                    self.numberEntry.config(background="green")
            else:
                    self.numberEntry.config(background="red")
            self.showimhist(fn1+".png", fn2+".png")
            self.enableButtons()
            
            aunload = self.autoUnload.get()

            if (aunload > 0):
                self.unload()
                
            self.numUp()    
            
            elapsed_time = time.time() - start_time
            str_cap = "Capture Time: {0:.2f} s.".format(elapsed_time)
            print str_cap

            # Editing the first pixel
            print('about to edit pixel...')
            point = (0,0)

            reader = png.Reader(filename=fn1+'.png')
            w, h, pixels, metadata = reader.read_flat()

            ## set chip version in first pixel
            if(mode == self.options[0]):
                pixels[0] = 1
            elif(mode == self.options[1]):
                pixels[0] = 2
            elif(mode == self.options[2]):
                pixels[0] = 3
            elif(mode == self.options[3]):
                pixels[0] = 4
            elif(mode == self.options[4]):
                pixels[0] = 5
            elif(mode == self.options[5]):
                pixels[0] = 6
                
            output = open(fn1+'.png', 'wb')
            writer = png.Writer(w, h, **metadata)
            writer.write_array(output, pixels)
            output.close()
            print('done')
            
            #self.sys.c_cam.real_time()

    def stitch(self):
            # preserve old values
            old90_1 = self.scan90_1
            old90_2 = self.scan90_2
            old60_1 = self.scan60_1
            old60_2 = self.scan60_2
            old30_1 = self.scan30_1
            old30_2 = self.scan30_2

            # Offset the x
            self.scan90_1[0] -= 3
            self.scan90_2[0] -= 3
            self.scan60_1[0] -= 3
            self.scan60_2[0] -= 3
            self.scan30_1[0] -= 3
            self.scan30_2[0] -= 3
        
            mode = self.v.get()
            start_time = time.time()
            self.load()
            self.disableButtons()
            today = date.today()
            todaystr = str(today.year) +"-"+str(today.month) +"-"+str(today.day) +"/"
            todaystr = time.strftime("%Y-%m-%d") + "/"
            folder = "../data/" + todaystr
            if(os.path.isdir(folder) == False):
                os.mkdir(folder)
            #self.sys.c_cam.close_realtime()
            
            num = self.numberEntry.get().zfill(3)
            
            ## LED1
            ledn = 1
            fn1 = folder + self.prefixEntry.get()+"_"+num + "_1a"
            self.sys.hw.cam.fn = fn1
            self.sys.hw.led.command(NGA_Interface_LED.LED_OFF)
            self.sys.hw.led.command(NGA_Interface_LED.LED1_ON)
            
            if (mode == 2): #30
                self.focus(1,ledn) #min score
            elif (mode == 1): #90
                self.focus(0,ledn) #max slope
            elif (mode == 0): #60
                self.focus(1,ledn) #max score
            self.sys.hw.cam.image()
            
            ## LED 2
            ledn = 2
            fn2 = folder + self.prefixEntry.get()+"_"+num + "_2a"
            self.sys.hw.cam.fn = fn2
            self.sys.hw.led.command(NGA_Interface_LED.LED_OFF)
            self.sys.hw.led.command(NGA_Interface_LED.LED2_ON)
            if (mode == 2): #30
                self.focus(2,ledn) #min score
            elif (mode == 1): #90
                self.focus(1,ledn) #max score
            elif (mode == 0): #60
                self.focus(1,ledn) #max score
            self.sys.hw.cam.image()
            self.sys.hw.led.command(NGA_Interface_LED.LED_OFF)
            self.sys.hw.led.command(NGA_Interface_LED.LED1_ON)
            if (self.checkIm(num) == True):
                    self.numberEntry.config(background="green")
            else:
                    self.numberEntry.config(background="red")
            self.showimhist(fn1+".png", fn2+".png")
            self.enableButtons()
            


            ### MOVE THE STAGE
                        # Offset the x
            self.scan90_1[0] += 6
            self.scan90_2[0] += 6
            self.scan60_1[0] += 6
            self.scan60_2[0] += 6
            self.scan30_1[0] += 6
            self.scan30_2[0] += 6

            self.load()
            
            ## LED1
            ledn = 1
            fn1 = folder + self.prefixEntry.get()+"_"+num + "_1b"
            self.sys.hw.cam.fn = fn1
            self.sys.hw.led.command(NGA_Interface_LED.LED_OFF)
            self.sys.hw.led.command(NGA_Interface_LED.LED1_ON)
            
            if (mode == 2): #30
                self.focus(1,ledn) #min score
            elif (mode == 1): #90
                self.focus(0,ledn) #max slope
            elif (mode == 0): #60
                self.focus(1,ledn) #max score
            self.sys.hw.cam.image()
            
            ## LED 2
            ledn = 2
            fn2 = folder + self.prefixEntry.get()+"_"+num + "_2b"
            self.sys.hw.cam.fn = fn2
            self.sys.hw.led.command(NGA_Interface_LED.LED_OFF)
            self.sys.hw.led.command(NGA_Interface_LED.LED2_ON)
            if (mode == 2): #30
                self.focus(2,ledn) #min score
            elif (mode == 1): #90
                self.focus(1,ledn) #max score
            elif (mode == 0): #60
                self.focus(1,ledn) #max score
            self.sys.hw.cam.image()
            self.sys.hw.led.command(NGA_Interface_LED.LED_OFF)
            self.sys.hw.led.command(NGA_Interface_LED.LED1_ON)
            if (self.checkIm(num) == True):
                    self.numberEntry.config(background="green")
            else:
                    self.numberEntry.config(background="red")
            self.showimhist(fn1+".png", fn2+".png")
            self.enableButtons()
            
            aunload = self.autoUnload.get()

            if (aunload > 0):
                self.unload()
                
            self.numUp()    
            
            elapsed_time = time.time() - start_time
            str_cap = "Capture Time: {0:.2f} s.".format(elapsed_time)
            print str_cap
            #self.sys.c_cam.real_time()

            # preserve old values
            #self.scan90_1 = old90_1
            #self.scan90_2 = old90_2
            #self.scan60_1 = old60_1
            #self.scan60_2 = old60_2
            #self.scan30_1 = old30_1
            #self.scan30_2 = old30_2
            self.scan90_1[0] -= 3
            self.scan90_2[0] -= 3
            self.scan60_1[0] -= 3
            self.scan60_2[0] -= 3
            self.scan30_1[0] -= 3
            self.scan30_2[0] -= 3


            

    def disableButtons(self):
            self.setButtons(DISABLED)

    def enableButtons(self):
            self.setButtons('normal')
    
    def setButtons(self,btnState):
            self.prefixEntry.config(state=btnState)
            self.numberEntry.config(state=btnState)
            self.numDownButton.config(state=btnState)
            self.numUpButton.config(state=btnState)
            self.deleteButton.config(state=btnState)
            self.acquireButton.config(state=btnState)
            self.loadButton.config(state=btnState)
            #self.modeDry.config(state=btnState)
            #self.modeWet.config(state=btnState)
            self.autoUnloadCheck.config(state=btnState)
            self.mirrorButton.config(state=btnState)
            
            
            #self.focusButton.config(state=DISABLED)
            self.parent.update()
        
    def checkIm(self, num):
        today = date.today()
        todaystr = str(today.year) +"-"+str(today.month) +"-"+str(today.day) +"/"
        todaystr = time.strftime("%Y-%m-%d") + "/"
        prefix = self.prefixEntry.get() + "_"
        return (os.path.isfile("../data/" + todaystr + prefix + num.zfill(3)+"_1.png") 
            & os.path.isfile("../data/" + todaystr + prefix + num.zfill(3)+"_2.png"))

    def load(self):
            self.disableButtons()
            self.loadButton["text"] = "Loading..."

            '''
                mode = self.v.get()
                if(mode == 2):
                    scanPos = self.scan30_1
                    #print str(scanPos[0])+" "+str(scanPos[1])+" "+str(scanPos[2])
                elif(mode == 1):
                    scanPos = self.scan90_1
                elif(mode == 0):
                    scanPos = self.scan60_1
                    #print str(scanPos[0])+" "+str(scanPos[1])+" "+str(scanPos[2])
                elif(mode==3):
                    scanPos = self.scan60Long_1
            '''
            
            mode = self.chipMode.get()
            print("Mode: " + mode)
            scanPos = [0, 0, 0]
            if(mode == self.options[0]):
               scanPos = self.scanNSFAIR_1
            elif(mode == self.options[1]):
               scanPos = self.scanNV16_1
            elif(mode == self.options[2]):
               scanPos = self.scanNV10_1
            elif(mode == self.options[3]):
               scanPos = self.scanNV10B_1
            elif(mode == self.options[4]):
               scanPos = self.scanNV16B_1
            elif(mode == self.options[5]):
               scanPos = self.scanNV16B_1
               
            print(scanPos)
            self.sys.hw.stg.move_z(scanPos[2])
            self.sys.c_stage.update_pos_x_y_z()
            self.sys.hw.stg.move_x(scanPos[0])
            self.sys.hw.stg.move_y(scanPos[1])
            self.sys.c_stage.update_pos_x_y_z()
            self.loadButton["text"] = "Unload"
            self.loadButton["command"] = self.unload
            self.enableButtons()

    def unload(self): 
            self.disableButtons()
            self.loadButton["text"] = "Unloading..."
            if self.sys.hw.led.led_on[0] == False:
                    self.sys.c_led.led_on()
            #self.sys.c_cam.real_time()
            self.sys.hw.stg.move_x(self.homePos[0])
            self.sys.hw.stg.move_y(self.homePos[1])
            self.sys.c_stage.update_pos_x_y_z()
            self.sys.hw.stg.move_z(self.homePos[2])
            self.sys.c_stage.update_pos_x_y_z()
            self.loadButton["text"] = "Load"
            self.loadButton["command"] = self.load
            self.enableButtons()

    def showimhist(self, filename, filename2 = ""):
            plt.interactive(True) #need to add this or program freezes while plotting
            #print filename
            img = mpimg.imread(filename,cv2.IMREAD_GRAYSCALE)
            img2 = cv2.resize(img, (0,0), fx=0.5, fy=0.5)
            height, width1, channels = img2.shape
            try:
                plt.close(0)
            except:
                pass #this will error out if window hasn't loaded yet, that's ok
            plt.figure(0)
            plt.imshow(img2)
            
#             if (len(filename2) > 0):
#                 imgA = mpimg.imread(filename2,cv2.IMREAD_GRAYSCALE)
#                 img2A = cv2.resize(imgA, (0,0), fx=0.5, fy=0.5)
#                 heightA, width1A, channelsA = img2A.shape
#                 
#                 blue_image = img2A[:,:,1]
#                 red_image = img2[:,:,1]
#                     
#                 blank_image = 255*numpy.ones((height,width1,3), numpy.uint8)
#                 blank_image[:,:,0] = blank_image[:,:,0]-red_image
#                 blank_image[:,:,2] = blank_image[:,:,2]-blue_image
# 
#                 plt.imshow(blank_image)
                
            hist = cv2.calcHist(img,[0],None,[256],[0,256])
            maxhist = max(hist)
            y = [((x/maxhist)*-1*height*.3) for x in hist]
            N = len(y)
            xold = range(N)
            x = [(x/(N-1))*width1 for x in xold]
            width = (1/N)*width1
            plt.bar(x, y, width, color="blue", bottom=height)
            plt.axis([0,width1,height,0])
            plt.title(filename)
            plt.show()
Пример #8
0
class Edit_save(object):

    def __init__(self):
        self.root = Tk()
        self.root.title('EditSave')
        self.root.geometry('+120+50')
        self.font_en = Font(self.root, size=12)
        self.font_text = Font(self.root,family="Helvetica",
                        size=12, weight='normal')

        self.menubar = Menu(self.root, bg='purple')
        self.filemenu = Menu(self.menubar)
        self.filemenu.add_command(label='Open', accelerator='Ctrl+o',
                command=self.__open, underline=0)
        self.filemenu.add_command(label='Save', accelerator='Ctrl+s',
                command=self.__save, underline=0)
        self.filemenu.add_command(label='Save As', accelerator='Ctrl+Shift+s',
                command=self.__save_as, underline=5)
        self.filemenu.add_separator()
        self.filemenu.add_command(label='Quit', accelerator='Alt+F4',
                command=self.root.destroy, underline=0)
        self.menubar.add_cascade(label='File', underline=0, menu=self.filemenu)
        self.helpmenu = Menu(self.menubar)
        self.helpmenu.add_command(label='About', underline=0,
                                  command=About_editsave)
        self.menubar.add_cascade(label='Help', underline=0, menu=self.helpmenu)
        self.editmenu = Menu(self.menubar, tearoff=False)
        self.editmenu.add_command(label='Refresh', accelerator='F5',
                command=self.root.update)
        self.editmenu.add_command(label='Copy', accelerator='Ctrl+C',
                command=lambda : self.text.event_generate('<<Copy>>'))
        self.editmenu.add_command(label='Paste', accelerator='Ctrl+V',
                command=lambda : self.text.event_generate('<<Paste>>'))
        self.editmenu.add_command(label='Cut', accelerator='Ctrl+X',
                command=lambda : self.text.event_generate('<<Cut>>'))
#       self.editmenu.add_command(label='Undo', accelerator='Ctrl+Z',
#               command=lambda : self.text.event_generate('<<Undo>>'))
#       self.editmenu.add_command(label='Redo', accelerator='Ctrl+Y',
#               command=lambda : self.text.event_generate('<<Redo>>'))
        self.editmenu.add_command(label='select_all', accelerator='Ctrl+A',
                command=lambda : self.text.tag_add('sel', '1.0', 'end'))

        self.fm_base = Frame(self.root)
        self.fm_up = Frame(self.fm_base)
        self.var = StringVar()
        self.en = Entry(self.fm_up, font=self.font_en,
                        textvariable=self.var, width=20)
        self.bt_open = Button(self.fm_up, text='Open',)
        self.bt_quit = Button(self.fm_up, text='Quit', underline=0)
        self.bt_quit.pack(side=RIGHT, padx=10)
        self.bt_open.pack(side=RIGHT, padx=5)
        self.en.pack(side=RIGHT, pady=5)
        self.bt_open.config(command=self.__open)
        self.bt_quit.config(command=self.root.destroy)
        self.fm_up.pack(fill=X)
        self.fm_base.pack(fill=X)

        self.fm_down =  Frame(self.root)
        self.text = Text(self.fm_down, font=self.font_text,
                        width=50, height=20)
        self.text.pack(side=LEFT, fill=BOTH, expand=True)
        self.scb = Scrollbar(self.fm_down)
        self.scb.pack(side=LEFT, fill=Y)
        self.text.config(yscrollcommand=self.scb.set)
        self.scb.config(command=self.text.yview)
        self.fm_down.pack(fill=BOTH, expand=True)

        self.root.bind('<Control-o>', self.__invoke_open)
        self.root.bind('<Control-O>', self.__invoke_open)
        self.root.bind('<Control-s>', self.__invoke_save)
        self.root.bind('<Control-S>', self.__invoke_save_as)
        self.root.bind('<Button-3>', self.__popupmenu)
        self.root.bind('Alt-F4', lambda event:  self.root.destroy)
        self.root.bind('<F5>', lambda event: self.root.update)
        self.root.bind('<Control-C>',
                        lambda event: self.text.event_generate('<<Copy>>'))
        self.root.bind('<Control-V>',
                        lambda event: self.text.event_generate('<<Paste>>'))
        self.root.bind('<Control-X>',
                        lambda event: self.text.event_generate('<<Cut>>'))
        for i in 'a', 'A':
            self.root.bind('<Control-%s>' % i,
                        lambda event: self.text.tag_add('sel', '1.0', 'end'))
#       for i in 'z', 'Z':
#           self.root.bind('<Control-%s>' % i,
#                       lambda event: self.text.event_generate('<<Undo>>'))
#       for i in 'y', 'Y':
#           self.root.bind('<Control-%s>' % i,
#                       lambda event: self.text.event_generate('<<Redo>>'))

        self.root.config(menu=self.menubar)
        self.root.mainloop()

    def __open(self):
        filetypes = [
                ("All Files", '*'),
                ("Python Files", '*.py', 'TEXT'),
                ("Text Files", '*.txt', 'TEXT'),
                ("Config Files", '*.conf', 'TEXT')]
        fobj = askopenfile(filetypes=filetypes)
        if fobj:
            self.text.delete('1.0', END)
            self.text.insert('1.0', fobj.read())
            self.en.delete(0, END)
            self.en.insert(0, fobj.name)

    def __save(self):
        value = self.var.get().strip()
        if value:
            f = open(value, 'w')
            f.write(self.text.get('1.0', END).strip() + '\n')
            f.close()
        else:
            self.__save_as()

    def __save_as(self):
        text_value = self.text.get('1.0', END).strip()
        if text_value:
            fobj = asksaveasfile()
            if fobj:
                fobj.write(text_value + '\n')

    def __invoke_open(self, event):
        self.__open()

    def __invoke_save(self, event):
        self.__save()

    def __invoke_save_as(self, event):
        self.__save_as()

    def __popupmenu(self, event):
        self.editmenu.post(event.x_root, event.y_root)
class MainWindow(Tk):
    def __init__(self):
        Tk.__init__(self)
        self.title(mainWindowTitle)
        self.resizable(width=0, height=0)
        self.__setStyles()
        self.__initializeComponents()
        self.__dataController = DataController();
        self.mainloop()
            
    def __initializeComponents(self):
        self.imageCanvas = Canvas(master=self, width=imageCanvasWidth,
                                  height=windowElementsHeight, bg="white")
        self.imageCanvas.pack(side=LEFT, padx=(windowPadding, 0),
                              pady=windowPadding, fill=BOTH)
        
        self.buttonsFrame = Frame(master=self, width=buttonsFrameWidth,
                                  height=windowElementsHeight)
        self.buttonsFrame.propagate(0)
        self.loadFileButton = Button(master=self.buttonsFrame,
                                     text=loadFileButtonText, command=self.loadFileButtonClick)
        self.loadFileButton.pack(fill=X, pady=buttonsPadding);
        
        self.colorByLabel = Label(self.buttonsFrame, text=colorByLabelText)
        self.colorByLabel.pack(fill=X)
        self.colorByCombobox = Combobox(self.buttonsFrame, state=DISABLED,
                                        values=colorByComboboxValues)
        self.colorByCombobox.set(colorByComboboxValues[0])
        self.colorByCombobox.bind("<<ComboboxSelected>>", self.__colorByComboboxChange)
        self.colorByCombobox.pack(fill=X, pady=buttonsPadding)
        self.rejectedValuesPercentLabel = Label(self.buttonsFrame, text=rejectedMarginLabelText)
        self.rejectedValuesPercentLabel.pack(fill=X)
        self.rejectedValuesPercentEntry = Entry(self.buttonsFrame)
        self.rejectedValuesPercentEntry.insert(0, defaultRejectedValuesPercent)
        self.rejectedValuesPercentEntry.config(state=DISABLED)
        self.rejectedValuesPercentEntry.pack(fill=X, pady=buttonsPadding)        
        
        self.colorsSettingsPanel = Labelframe(self.buttonsFrame, text=visualisationSettingsPanelText)
        self.colorsTableLengthLabel = Label(self.colorsSettingsPanel, text=colorsTableLengthLabelText)
        self.colorsTableLengthLabel.pack(fill=X)
        self.colorsTableLengthEntry = Entry(self.colorsSettingsPanel)
        self.colorsTableLengthEntry.insert(0, defaultColorsTableLength)
        self.colorsTableLengthEntry.config(state=DISABLED)
        self.colorsTableLengthEntry.pack(fill=X)
        self.scaleTypeLabel = Label(self.colorsSettingsPanel, text=scaleTypeLabelText)
        self.scaleTypeLabel.pack(fill=X)
        self.scaleTypeCombobox = Combobox(self.colorsSettingsPanel, state=DISABLED,
                                          values=scaleTypesComboboxValues)
        self.scaleTypeCombobox.set(scaleTypesComboboxValues[0])
        self.scaleTypeCombobox.bind("<<ComboboxSelected>>", self.__scaleTypeComboboxChange)
        self.scaleTypeCombobox.pack(fill=X)
        self.colorsTableMinLabel = Label(self.colorsSettingsPanel, text=colorsTableMinLabelText)
        self.colorsTableMinLabel.pack(fill=X)
        self.colorsTableMinEntry = Entry(self.colorsSettingsPanel)
        self.colorsTableMinEntry.insert(0, defaultColorsTableMin)
        self.colorsTableMinEntry.config(state=DISABLED)
        self.colorsTableMinEntry.pack(fill=X)
        self.colorsTableMaxLabel = Label(self.colorsSettingsPanel, text=colorsTableMaxLabelText)
        self.colorsTableMaxLabel.pack(fill=X)
        self.colorsTableMaxEntry = Entry(self.colorsSettingsPanel)
        self.colorsTableMaxEntry.insert(0, defaultColorsTableMax)
        self.colorsTableMaxEntry.config(state=DISABLED)
        self.colorsTableMaxEntry.pack(fill=X)
        self.colorsSettingsPanel.pack(fill=X, pady=buttonsPadding)
        
        self.redrawButton = Button(master=self.buttonsFrame, text=redrawButtonText,
                                   state=DISABLED, command=self.__redrawButtonClick)
        self.redrawButton.pack(fill=X, pady=buttonsPadding)
        self.buttonsFrame.pack(side=RIGHT, padx=windowPadding, pady=windowPadding, fill=BOTH)
        
    def __setStyles(self):
        Style().configure("TButton", padding=buttonsTextPadding, font=buttonsFont)
    
    def loadFileButtonClick(self):
        fileName = tkFileDialog.askopenfilename(filetypes=[('Tablet files', '*.mtb'), ('Tablet files', '*.htd')])
        if (fileName):
            if (not self.__getInputParams()):
                self.__showInvalidInputMessage()
                return
            
            self.lastFileName = fileName;
            self.title(mainWindowTitle + " " + fileName)
            self.__draw(fileName)
            tkMessageBox.showinfo(measureDialogTitle, 
                                  measureDialogText + str(self.__dataController.getMeasure(fileName)))
            
            self.redrawButton.config(state=NORMAL)
            self.colorByCombobox.config(state="readonly")
            self.colorsTableLengthEntry.config(state=NORMAL)
            self.scaleTypeCombobox.config(state="readonly")
            
    def __redrawButtonClick(self):
        if (not self.__getInputParams()):
            self.__showInvalidInputMessage()
            return
        
        self.__draw(self.lastFileName)

    def __scaleTypeComboboxChange(self, event):
        if (self.scaleTypeCombobox.get() == relativeScaleType):
            self.colorsTableMinEntry.config(state=DISABLED)
            self.colorsTableMaxEntry.config(state=DISABLED)
        else:
            self.colorsTableMinEntry.config(state=NORMAL)
            self.colorsTableMaxEntry.config(state=NORMAL)
        
    def __colorByComboboxChange(self, event):
        if (self.colorByCombobox.get() == colorByNoneOption):
            self.rejectedValuesPercentEntry.config(state=DISABLED)
        else:
            self.rejectedValuesPercentEntry.config(state=NORMAL)
        
    def __draw(self, fileName):
        self.imageCanvas.delete(ALL)

        dataForDrawing = self.__dataController.getDataForDrawing(
            fileName, self.colorByCombobox.get(), self.colorsTableLength,
            self.scaleTypeCombobox.get(), self.colorsTableMinValue,
            self.colorsTableMaxValue, self.rejectedValuesPercent)
        
        for package in dataForDrawing:
            x = package[0];
            y = package[1];
            color = package[2];
            self.imageCanvas.create_line(x, y, x + 1, y + 1, fill=color)
            
    def __drawColorBySpeed(self, dataPackages, minX, minY, ratio, hsv):   
        allSpeeds = self.__getAllSpeeds(dataPackages)
        minSpeed = min(allSpeeds)
        maxSpeed = max(allSpeeds)
        
        if (self.scaleTypeCombobox.get() == relativeScaleType):
            colorsTableMinValue = minSpeed
            colorsTableMaxValue = maxSpeed
        else:
            colorsTableMinValue = self.colorsTableMinValue
            colorsTableMaxValue = self.colorsTableMaxValue
        
        i = 0
        for package in dataPackages:
            x = (package[dataXNumber] - minX) * ratio
            y = (package[dataYNumber] - minY) * ratio
            
            color = hsv.getColorByValue(colorsTableMinValue,
                                        colorsTableMaxValue,
                                        allSpeeds[i])
                
            tk_rgb = "#%02x%02x%02x" % color
            self.imageCanvas.create_line(x, y, x + 1, y + 1, fill=tk_rgb)
            i += 1
            
    def __showInvalidInputMessage(self):
        tkMessageBox.showinfo(invalidInputMessageTitle, invalidInputMessageText)
    
    def __getInputParams(self):
        try:
            self.colorsTableLength = int(self.colorsTableLengthEntry.get())
            self.colorsTableMinValue = float(self.colorsTableMinEntry.get())
            self.colorsTableMaxValue = float(self.colorsTableMaxEntry.get())
            self.rejectedValuesPercent = float(self.rejectedValuesPercentEntry.get())
        
            if (self.colorsTableLength < 1 or
                self.colorsTableMinValue >= self.colorsTableMaxValue or
                self.rejectedValuesPercent < 0 or self.rejectedValuesPercent >= 100):
                raise
            return True
        except:
            return False
Пример #10
0
class Login(object):
    def __init__(self):
        self.root = Tk()
        self.root.title(u'用户登录')
        self.root.resizable(False, False)
        self.root.geometry('400x670-100+200')

        self.xmlpath = StringVar()
        dict = self.checkconf()
        dict['xml_path'] = str(self.checkxml())
        self.lb_user = Label(self.root, text=u'用户名:', padx=5)
        self.lb_passwd = Label(self.root, text=u'密码:', padx=5)
        self.checkDep_lab = Label(self.root, text=u'所属部门:', padx=5)
        self.checkRo_lab = Label(self.root, text=u'角色选择:', padx=5)
        self.checkRo_group = Label(self.root, text=u'小组选择:', padx=5)
        self.check_lab1 = Label(self.root, text=u' ', padx=1)
        self.check_lab2 = Label(self.root, text=u'', padx=1)

        self.deptset = StringVar()
        self.deptset.set(dict.get('[dept]'))
        self.roalset = StringVar()
        self.roalset.set(dict.get('[role]'))
        self.group = eval(dict.get('[group]'))

        self.checkfrom1 = Radiobutton(self.root,
                                      text="项目",
                                      variable=self.deptset,
                                      value="1")
        self.checkfrom2 = Radiobutton(self.root,
                                      text="研发",
                                      variable=self.deptset,
                                      value="2")
        self.checkfrom3 = Radiobutton(self.root,
                                      text="运维",
                                      variable=self.deptset,
                                      value="3")
        self.checkroal1 = Radiobutton(self.root,
                                      text="JAVA工程师",
                                      variable=self.roalset,
                                      value="1")
        self.checkroal2 = Radiobutton(self.root,
                                      text="UI设计师",
                                      variable=self.roalset,
                                      value="2")
        self.checkroal3 = Radiobutton(self.root,
                                      text="IOS工程师",
                                      variable=self.roalset,
                                      value="3")
        self.checkroal4 = Radiobutton(self.root,
                                      text="Andrior工程师",
                                      variable=self.roalset,
                                      value="4")
        self.checkroal5 = Radiobutton(self.root,
                                      text="测试工程师",
                                      variable=self.roalset,
                                      value="5")
        self.checkroal6 = Radiobutton(self.root,
                                      text="WEB前端",
                                      variable=self.roalset,
                                      value="6")
        self.checkroal7 = Radiobutton(self.root,
                                      text="JAVA设计师",
                                      variable=self.roalset,
                                      value="7")
        self.checkroal8 = Radiobutton(self.root,
                                      text="产品专员",
                                      variable=self.roalset,
                                      value="8")
        self.checkroal9 = Radiobutton(self.root,
                                      text="综合管理员",
                                      variable=self.roalset,
                                      value="9")
        self.checkroal0 = Radiobutton(self.root,
                                      text="技术总监",
                                      variable=self.roalset,
                                      value="0")
        self.lb_user.grid(row=0, column=0, sticky=W)
        self.lb_passwd.grid(row=1, column=0, sticky=W)
        self.checkDep_lab.grid(row=2, column=0, sticky=W)
        self.checkfrom1.grid(row=2, column=1, sticky=W)
        self.checkfrom2.grid(row=3, column=1, sticky=W)
        self.checkfrom3.grid(row=4, column=1, sticky=W)
        self.checkRo_lab.grid(row=5, column=0, sticky=W)
        self.checkRo_group.grid(row=16, column=0, sticky=W)
        self.checkroal1.grid(row=6, column=1, sticky=W)
        self.checkroal2.grid(row=7, column=1, sticky=W)
        self.checkroal3.grid(row=8, column=1, sticky=W)
        self.checkroal4.grid(row=9, column=1, sticky=W)
        self.checkroal5.grid(row=10, column=1, sticky=W)
        self.checkroal6.grid(row=11, column=1, sticky=W)
        self.checkroal7.grid(row=12, column=1, sticky=W)
        self.checkroal8.grid(row=13, column=1, sticky=W)
        self.checkroal9.grid(row=14, column=1, sticky=W)
        self.checkroal0.grid(row=15, column=1, sticky=W)

        self.choicegroup = StringVar()
        self.choicegroup.set('小组一')
        num = 0
        for i in self.group.keys():
            num = num + 1
            setattr(
                self, 'group_',
                Radiobutton(self.root,
                            text=self.group[i],
                            variable=self.choicegroup,
                            value=i).grid(row=16 + num, column=1, sticky=W))
        num = 0
        self.en_user = Entry(self.root, width=20)
        self.en_passwd = Entry(self.root, width=20, show='*')
        self.en_user.insert(0, dict.get('[ID]'))
        self.en_passwd.insert(0, dict.get('[code]'))
        self.check_lab1['text'] = ' 已获取: '
        self.check_lab2['text'] = dict.get('xml_path')
        self.en_user.grid(row=0, column=1, columnspan=1)
        self.en_passwd.grid(row=1, column=1, columnspan=1)
        self.check_lab1.grid(row=25)
        self.check_lab2.grid(row=26)
        self.var = IntVar()
        self.ckb = Checkbutton(self.root,
                               text=u'记住用户名和密码以及设置',
                               underline=0,
                               variable=self.var)
        self.ckb.grid(row=22, column=0)
        self.bt_print = Button(self.root, text=u'确定', width=20)
        self.bt_print.grid(row=23, column=1, sticky=E, pady=5)
        self.bt_print.config(command=self.print_info)
        self.root.mainloop()

        def validate_func(self, en):
            return False if eval(en).get().strip() != '' else True

        def checkfromclick1(self):

            return list

    def print_info(self):
        if self.var.get() != 0:
            print(self.var.get())
            self.saveconf()
        sendmes = {}
        sendmes['xml_path'] = self.check_lab2['text']
        if self.deptset.get() == '1':
            sendmes['send_dept'] = '268599543846224672-anchor'
        elif self.deptset.get() == '2':
            sendmes['send_dept'] = '6377311728366403805-anchor'
        else:
            sendmes['send_dept'] = '4218208322934425649-anchor'
        sendmes['send_role'] = self.roalset.get()
        sendmes['en_user'] = self.en_user.get().strip()
        sendmes['en_passwd'] = self.en_passwd.get().strip()
        sendmes['lastday'] = time.strftime('%Y-%m', time.localtime(time.time()))+'-'\
                           + str(calendar.monthrange(datetime.now().year, datetime.now().month)[1])\
                           + ' 17:30'
        sendmes['xml_lastday'] = time.strftime('%m', time.localtime(time.time()))+'月'\
                           + str(calendar.monthrange(datetime.now().year, datetime.now().month)[1])+'日'
        sendmes['group'] = self.choicegroup.get()
        #isok=runwork.test(sendmes)
        isok = runwork.doLoginSession(sendmes)

        #返回信息
        if isok == "ture":
            MG.showinfo(title="完成", message="已保存至待发事项,请注意及时发送")
            sys.exit(0)
        elif isok == "chromeerror":
            MG.showerror(title="失败",
                         message="浏览器驱动与版本不兼容,请尝试更新 \n "
                         "驱动与Chrome版本下载 请参照 目录下README帮助文件 \n "
                         "程序驱动位于bin目录下")
            sys.exit(0)
        else:
            MG.showerror(title="失败",
                         message="失败 可以再尝试下,或者 \n "
                         "目录下mylog日志文件解决问题,或者联系作者 \n"
                         "源码已公开")
            sys.exit(0)

    def saveconf(self):
        f = open("local.conf", 'r')
        result = list()
        for line in f.readlines():
            line = line.strip()
            if line.strip().find("=") and '[ID]' in line.strip():
                result.append(line.strip().split("=")[0] + '=' +
                              self.en_user.get())
            if line.strip().find("=") and '[code]' in line.strip():
                result.append(line.strip().split("=")[0] + '=' +
                              self.en_passwd.get())
            if line.strip().find("=") and '[dept]' in line.strip():
                result.append(line.strip().split("=")[0] + '=' +
                              self.deptset.get())
            if line.strip().find("=") and '[role]' in line.strip():
                result.append(line.strip().split("=")[0] + '=' +
                              self.roalset.get())
            if line.strip().find("=") and '[group]' in line.strip():
                result.append(line.strip().split("=")[0] + '=' +
                              line.strip().split("=")[1])
            if not len(line) or line.startswith('#'):
                continue
        f.close()  # 关闭文件
        with open('local.conf', 'w') as fw:  # with方式不需要再进行close
            fw.write('%s' % '\n'.join(result))

    def checkconf(self):
        if os.path.exists("local.conf") and os.path.getsize("local.conf") != 0:
            dict = {}
            with open('local.conf', 'r') as f:
                for line in f.readlines():
                    if line.strip().find("="):
                        dict[line.strip().split("=")[0]] = line.strip().split(
                            "=")[1]
            return dict
        else:
            dictDefault = {
                '[ID]': '输入用户名',
                '[code]': '密码',
                '[dept]': '1',
                '[role]': '1'
            }
            return dictDefault

    def checkxml(self):
        xmlpath = time.strftime('%Y-%m', time.localtime(
            time.time())) + '月份绩效填写用表.xlsx'
        print(xmlpath)
        print(os.path.exists(xmlpath))
        if os.path.exists(xmlpath):
            return xmlpath
        else:
            MG.showerror(title="失败", message="不存在" + xmlpath + "文件,停止进程")
            sys.exit(0)
            return '-1'  #多余
Пример #11
0
class Example(Frame):
#Initialise values
    ctrlpt1=[55,55]
    ctrlpt2=[150,120]
    ctrlpt3=[55,215]
    pt1=[50,50]
    pt2=[100,100]
    clickno=2
    toggle = 1
    div_num = 10

#initilise Frame then initialise this Example class using initUI() 
    def __init__(self, parent):
        Frame.__init__(self, parent)   
        
        self.parent = parent
        self.initUI()
        

        
    def initUI(self):
      
        self.parent.title("Grass")
#Configure parent for column layout       
        Style().configure("TButton", padding=(0, 5, 0, 5), 
            font='serif 10')
        
        self.columnconfigure(0, pad=3)
        self.columnconfigure(1, pad=3)
        self.columnconfigure(2, pad=3)
        self.columnconfigure(3, pad=3)
        
        self.rowconfigure(0, pad=3)
        self.rowconfigure(1, pad=3)
        self.rowconfigure(2, pad=3)
        self.rowconfigure(3, pad=3)
        self.rowconfigure(4, pad=3)
        self.rowconfigure(5, pad=3)
        self.rowconfigure(6, pad=3)
        self.rowconfigure(7, pad=3)
        self.rowconfigure(8, pad=3)


        frame1 = Frame(self)
        frame1.grid(row=0,columnspan=4)
        self.lbl1 = Label(frame1, text="")
        self.lbl1.pack(side=LEFT, padx=5, pady=5)

        frame2 = Frame(self)
        frame2.grid(row=1,columnspan=4)
        lbl2 = Label(frame2, text="Divisions", width=6)
        lbl2.pack(side=LEFT, padx=5, pady=5)
        self.entry1=Entry(frame2) 
        self.entry1.pack(fill=X, padx=5, expand=True)        
        
        frame3 = Frame(self)
        frame3.grid(row=2,columnspan=4)
        self.lbl3 = Label(frame3, text="Divisions =%r"%self.div_num)
        self.lbl3.pack(side=LEFT, expand=True)
    

        set_point = Button(self, text="Set divisions", command=self.get_div)
        set_point.grid(row=3, columnspan=2)
     
        self.stop_place = Button(self, text="Toggle delete",\
        command=self.change_toggle)
        self.stop_place.grid(row = 3, column = 2,columnspan=2) 
    
        clr_btn = Button(self, text="Clear Canvas", command=self.clear_canvas)
        clr_btn.grid(row = 4, column = 0,columnspan=2)

        drw_btn = Button(self, text="Draw lines", command=self.draw_ctrllines)
        drw_btn.grid(row = 4, column = 2,columnspan=2)

        div = Button(self, text="Divide", command=self.draw_divide)
        div.grid(row = 5, column = 0,columnspan=2)

        strart = Button(self, text="Strings", command=self.string_art)
        strart.grid(row = 5, column = 2,columnspan=2)

        plotpar = Button(self, text="Parabola", command=self.plot_para)
        plotpar.grid(row = 6, column = 0,columnspan=2)

        self.w = Canvas(self, width=200, height=900)
        self.w.grid(row=7, columnspan=4)


#Draw initial control points for user

        self.id1=self.w.create_oval(self.ctrlpt1[0] - 2, self.ctrlpt1[1] - 2,\
        self.ctrlpt1[0] + 2,self.ctrlpt1[1] + 2,fill="black",tags='maybe')
        self.w.tag_bind(self.id1,'<Button-1>',self.del_elem)


        id2=self.w.create_oval(
                            self.ctrlpt2[0] - 2, self.ctrlpt2[1] - 2,
                            self.ctrlpt2[0] + 2,self.ctrlpt2[1] + 2,fill="black"
                              )
        self.w.tag_bind(id2,'<Button-1>',self.del_elem)

        self.id3=self.w.create_oval(self.ctrlpt3[0] - 2, self.ctrlpt3[1] - 2,\
        self.ctrlpt3[0] + 2,self.ctrlpt3[1] + 2,fill="black")
        self.w.tag_bind(self.id3,'<Button-1>',self.del_elem)
        self.w.bind('<Motion>',self.motion)  
        print self.id1

        movebut = Button(self, text="Grass", command=self.grass_polygon)
        movebut.grid(row = 6, column = 2,columnspan=2)
        
        #self.w.bind('<Button-1>',self.clicky) 
 
        self.pack()    

    def get_div(self):
        try:
            self.div_num=int(self.entry1.get())
            self.lbl1.config(text="Division number set")
            self.lbl3.config(text="Divisions =%r"%self.div_num)
        except ValueError:
            self.lbl1.config(text="Incorrect entry type")

    def draw_divide(self):
        self.w.delete("all")
        list1=self.divide_line(self.ctrlpt1,self.ctrlpt2)
        for n in range(len(list1)):  
            id=self.w.create_oval(
                                list1[n][0] - 2, list1[n][1] - 2, 
                                list1[n][0] + 2,list1[n][1] + 2,fill="black"
                                  )
            self.w.tag_bind(id,'<Button-1>',self.del_elem)
        list2=self.divide_line(self.ctrlpt2,self.ctrlpt3)  
        for n in range(len(list2)):  
            id=self.w.create_oval(
                                list2[n][0] - 2, list2[n][1] - 2, 
                                list2[n][0] + 2,list2[n][1] + 2,fill="black"
                                  )
            self.w.tag_bind(id,'<Button-1>',self.del_elem)
    
    def grass_polygon(self):
        lst=self.intersect_list()
        for n in range(len(lst)-1):
            width=5+10*(1-abs(1-2*(n+1)/float(len(lst))))
            m1 = self.slope(lst[n],lst[n+1])
            m = -1/self.slope(lst[n],lst[n+1])
            print lst[n],m1,m
            dx = math.sqrt(width**2/(1+m**2))
            dy = math.sqrt(width**2/(1+1/m**2))
            x1=math.ceil(lst[n][0]-dx)
            y1=math.ceil(lst[n][1]-dy)
            x2=math.ceil(lst[n][0]+dx)
            y2=math.ceil(lst[n][1]+dy)
            x3=lst[n+1][0]+dx
            y3=lst[n+1][1]+dy
            x4=lst[n+1][0]-dx
            y4=lst[n+1][1]-dy
            if n==0:
                x2=x1=lst[n][0]
                y2=y1=lst[n][1]
                
            self.w.create_polygon(x1,y1,x2,y2,x3,y3,x4,y4,fill='green')
    

    def dist(self,point1,point2):
        x1,y1 = point1
        x2,y2 = point2
        distance = math.sqrt(float((x2-x1))**2+(y2-y1)**2)
        return distance
    
    def slope(self,point1,point2):
        x1,y1 = point1
        x2,y2 = point2
        if abs(x2-x1) > 0.00001:
            m1=(y2+y1)/float(x2-x1)
            return m1
        else:
            return none

    def intersect_list(self):
        list1 = self.divide_line(self.ctrlpt1,self.ctrlpt2)
        list2 = self.divide_line(self.ctrlpt2,self.ctrlpt3)
        zplst = zip(list1[0:len(list1)-1],list2[1:len(list1)])
        para_list=[0]*(len(zplst)+1)
        para_list[0]=self.ctrlpt1
        para_list[len(zplst)]=self.ctrlpt3
        for n in range(len(zplst)-1):
            para_list[n+1]=self.intersection(
                                        zplst[n][0],zplst[n][1],
                                        zplst[n+1][0],zplst[n+1][1]
                                        )
        return para_list
            
    def plot_para(self):
        plotlist=self.intersect_list()
        for n in range(len(plotlist)):  
            id=self.w.create_oval(
                                plotlist[n][0]-2, plotlist[n][1]-2, 
                                plotlist[n][0]+2, plotlist[n][1]+2,fill="black"
                                  )
            self.w.tag_bind(id,'<Button-1>',self.del_elem)
                    
    def string_art(self):
        list1 = self.divide_line(self.ctrlpt1,self.ctrlpt2)
        list2 = self.divide_line(self.ctrlpt2,self.ctrlpt3)
        zplst = zip(list1[0:len(list1)-1],list2[1:len(list1)])
        for n in range(len(zplst)):  
            id=self.w.create_line(
                                zplst[n][0][0], zplst[n][0][1], 
                                zplst[n][1][0], zplst[n][1][1],fill="black"
                                  )
            self.w.tag_bind(id,'<Button-1>',self.del_elem)

    def intersection(self,point1,point2,point3,point4):
        x1,y1 = point1
        x2,y2 = point2
        x3,y3 = point3
        x4,y4 = point4
        if abs(x2-x1) > 0.00001 and abs(x4-x3) > 0.00001:
            m1=(y2-y1)/float(x2-x1)
            c1=y1-float(m1)*x1
            m2=(y4-y3)/float(x4-x3)
            c2=y3-float(m2)*x3
            xint = (c2-c1)/float((m1-m2))
            yint = m1*((c2-c1)/float((m1-m2)))+c1
        else:
            if abs(x2-x1) < 0.00001:
                xint=x2
                yint=(y4-y3)*x2/float(x4-x3)+y3-float((y4-y3)/float(x4-x3))*x3
            else:
                xint=x3
                yint=(y2-y1)*x3/float(x2-x1)+y1-float((y2-y1)/float(x2-x1))*x1
            
        return [xint,yint]

    def draw_ctrllines(self):
        x1,y1=self.ctrlpt1
        x2,y2=self.ctrlpt2
        x3,y3=self.ctrlpt3
        line1 = self.w.create_line(x1, y1, x2, y2)
        self.w.tag_bind(line1,'<Button-1>',self.del_elem)
        line2 = self.w.create_line(x2, y2, x3, y3)
        self.w.tag_bind(line2,'<Button-1>',self.del_elem)

    def divide_line(self,point1,point2):
        x1,y1 = point1
        x2,y2 = point2
        list = [0]*(self.div_num+1)
        for n in range(self.div_num+1):
            list[n]=[x1+(n)*(x2-x1)/float(self.div_num),y1+(n)*(y2-y1)/float(self.div_num)]
        return list            

    def change_toggle(self):
        self.toggle=(self.toggle+1)%2
        if self.toggle == 1:
            self.stop_place.config(text="Delete mode off")
        else:
            self.stop_place.config(text="Delete mode on")
    
       
    def del_elem(self,event):
        if self.toggle==1:
            pass
        else:
            print "Hello"
            event.widget.delete("current")
            
    def midpoint(self,x1,x2,y1,y2):
        xmid=(x1+x2)/2
        ymid=(y1+y2)/2
        return xmid,ymid

    def motion(self,event):
        w=self.parent.winfo_screenwidth()
        h=self.parent.winfo_screenheight()
        x,y = self.w.winfo_pointerxy()
        print x-536,y-353
    
    def clear_canvas(self):
        self.w.delete("all") 
Пример #12
0
class FindServer(Frame):

    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        self.selected = "";
        self.controller = controller
        label = Label(self, text="Select server", font=TITLE_FONT, justify=CENTER, anchor=CENTER)
        label.pack(side="top", fill="x", pady=10)
        
        self.button1 = Button(self, text="Next",state="disabled", command=self.callback_choose)
        button2 = Button(self, text="Refresh", command=self.callback_refresh)        
        button3 = Button(self, text="Back", command=self.callback_start)
        
        scrollbar = Scrollbar(self)
        self.mylist = Listbox(self, width=100, yscrollcommand = scrollbar.set )
        self.mylist.bind("<Double-Button-1>", self.twoClick)

        self.button1.pack()
        button2.pack()
        button3.pack()
        # create list with a scroolbar
        scrollbar.pack( side = "right", fill="y" )
        self.mylist.pack( side = "top", fill = "x", ipadx=20, ipady=20, padx=20, pady=20 )
        scrollbar.config( command = self.mylist.yview )
        # create a progress bar
        label2 = Label(self, text="Refresh progress bar", justify='center', anchor='center')
        label2.pack(side="top", fill="x")
        
        self.bar_lenght = 200
        self.pb = Progressbar(self, length=self.bar_lenght, mode='determinate')
        self.pb.pack(side="top", anchor='center', ipadx=20, ipady=20, padx=10, pady=10)
        self.pb.config(value=0)

    # to select he server user must double-click on it
    def twoClick(self, event):
        widget = event.widget
        selection=widget.curselection()
        value = widget.get(selection[0])
        self.selected = value
        self.button1.config(state="normal")
        # save the selected server in a global variable
        SELECTED_SERV = SERVER_LIST[selection[0]]
        set_globvar(SELECTED_SERV)      
    
    # listen for broadcasts from port 8192
    def listen_broadcasts(self, port, timeout):
        # Set the progress bar to 0
        self.pb.config(value=0)
        step_size = ((self.bar_lenght/(MAX_NR_OF_SERVERS+1))/2)
        list_of_servers = []
        # Initialize the listener
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        s.bind(('', port))
        s.settimeout(LISTENING_TIMEOUT)
        # Listen for a number of times to get multiple servers
        for _ in range(MAX_NR_OF_SERVERS + 1):
            # Update the progress bar
            self.pb.step(step_size)
            self.pb.update_idletasks()
            try:
                message, address = s.recvfrom(8192) 
                m_split = message.split(';')
                if m_split[0] == '\HELLO':
                    server_id = (m_split[1], address)
                    # Check if the server has not yet broadcasted itself.
                    if server_id not in list_of_servers:
                        list_of_servers.append(server_id)              
            except:
                pass
        # Close the socket
        s.close()
        if not list_of_servers:
            # If no server found, pop a warning message.
            tkMessageBox.showwarning("Find Servers", "No servers found. Refresh or create a new game.")
        # Set the progress bar back to 0
        self.pb.config(value=0)
        # Return the whole list of available servers
        return list_of_servers
    
    # service the refresh button
    def callback_refresh(self):
        global SERVER_LIST
        self.mylist.delete(0,END)
        SERVER_LIST = self.listen_broadcasts(BROADCASTING_PORT, LISTENING_TIMEOUT)
        for server_el in SERVER_LIST:
            self.mylist.insert(END,(" "+str(server_el[0])+"  IP: "+str(server_el[1])+"  Time: "+str(time.asctime())))
    
    def callback_choose(self):
        self.mylist.delete(0,END)
        self.button1.config(state="disabled")
        self.controller.show_frame("ChooseType")
        
    def callback_start(self):
        self.mylist.delete(0,END)
        self.button1.config(state="disabled")
        self.controller.show_frame("StartPage")
Пример #13
0
class MainControlFrame(Frame):
    def __init__(self, master, sequencer):
        Frame.__init__(self, master)
        self.sequencer = sequencer

        self.control_label = Label(self, text="Control")

        self.start_button = Button(self, text="Start")
        self.stop_button = Button(self, text="Stop")

        self.start_button.config(command=self.sequencer.play)
        self.stop_button.config(command=self.sequencer.stop)

        self.control_label.pack()
        self.start_button.pack()
        self.stop_button.pack()

        Label(self, text='Tempo').pack()
        self.tempo_label = Label(self)
        self.tempo_label.pack()

        def set_tempo(v):
            tempo = float(v)
            self.sequencer.set_speed(tempo)
            self.tempo_label.config(text='%3.0f' % tempo)

        tempo_scale = Scale(self, from_=400, to=5, command=set_tempo, orient='vertical')
        tempo_scale.set(self.sequencer.speed)
        tempo_scale.pack()

        measure_control_frame = Frame(self)
        measure_control_frame.pack()

        self.measure_resolution = StringVar(measure_control_frame)
        self.measure_resolution.set(self.sequencer.measure_resolution)
        self.beats_per_measure = StringVar(measure_control_frame)
        self.beats_per_measure.set(self.sequencer.beats_per_measure)

        Label(measure_control_frame, text='Resolution').grid(row=0, column=0, sticky='E')
        measure_resolution_entry = Entry(measure_control_frame, textvariable=self.measure_resolution, width=3)
        measure_resolution_entry.grid(row=0, column=1)

        Label(measure_control_frame, text='Beats').grid(row=1, column=0, sticky='E')
        beats_per_measure_entry = Entry(measure_control_frame, textvariable=self.beats_per_measure, width=3)
        beats_per_measure_entry.grid(row=1, column=1)

        change_measure_update = Button(measure_control_frame, text='Update Measure', command=self.change_measures)
        change_measure_update.grid(row=2, columnspan=2)

        # master_fader = mixer_frame.AudioFader(self, sequencer.getVolume, sequencer.setVolume)
        # master_fader.pack()

    def start_stop(self, event=None):
        if self.sequencer.running:
            self.sequencer.play()
        else:
            self.sequencer.stop()

    def change_measures(self):

        old_measure_resolution = self.sequencer.measure_resolution
        old_beats_per_measure = self.sequencer.beats_per_measure

        try:
            measure_resolution = int(self.measure_resolution.get())
            beats_per_measure = int(self.beats_per_measure.get())

            self.sequencer.change_measures(beats_per_measure, measure_resolution)
            print "ready to reload seq"
            self.master.master._open_sequencer(self.sequencer)
        except Exception as e:
            print e
            self.measure_resolution.set(old_measure_resolution)
            self.beats_per_measure.set(old_beats_per_measure)
            pass
Пример #14
0
class Evolution(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        
        self.parent = parent

        self.initUI()
        

    def configure(self):
        self.conf = Toplevel(self)
        self.conf.wm_title("Configure Universe")

        self.wc.reconfigure(self)
    

    def initUI(self):
        #create initial Beings object (not instantiated until live is called)
        self.wc = WorldConfiguration()

        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)

        self.columnconfigure(2, weight=1)
        self.columnconfigure(4, pad=7)
        self.rowconfigure(3, weight=1)

        lbl = Label(self, text="PyLife")
        lbl.grid(sticky = W, padx=25, pady=5)

        self.world = Canvas(self, background="#7474DB")
        self.world.grid(row=1, column=0, columnspan=3, rowspan=8, padx=5, sticky=E+W+N+S)
        
        self.sbtn = Button(self, text="Stop")
        self.sbtn.grid(row=1, column=4, pady = 5, sticky=E)

        self.bbox = Text(self, height=20, width=36)
        self.bbox.grid(row=3, column = 4, padx=5, sticky=E+W+N+S)

        self.bbox1 = Text(self, height=11, width=36)
        self.bbox1.grid(row=4, column=4, padx=5, sticky=E+W+N+S)

        self.cbtn = Button(self, text="Close", command=self.parent.destroy)
        self.cbtn.grid(row=9, column=4, pady=5)

        self.cnfbtn = Button(self, text="Configure Universe")
        self.cnfbtn.grid(row=9, column=0, padx=5)

        self.timelbl = Text(self, height=1, width=10)
        self.timelbl.grid(row=2, column=4, pady=5 )
       

        b = Beings(self)
        abtn = Button(self, text="Start", command=b.live)  #Beings(cnfbtn, world, 4, 10, sbtn, bbox, bbox1, timelbl).live)
        abtn.grid(row=1, column=4, pady=5, sticky=W)

        self.cnfbtn.config(command=b.configure)

    def close(self):
        self.parent.destroy
Пример #15
0
class toolUI(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent
        
        self.initUI()        
        
    def initUI(self):
      
        self.parent.title("Sequence modification parser")          
        
        self.columnconfigure(0, pad=5)
        self.columnconfigure(1, pad=5, weight = 1)
        self.columnconfigure(2, pad=5)
        
        self.rowconfigure(0, pad=5, weight = 1)
        self.rowconfigure(1, pad=5, weight = 1)
        self.rowconfigure(2, pad=5, weight = 1)
        self.rowconfigure(3, pad=5, weight = 1)
        self.rowconfigure(4, pad=5, weight = 1)
        self.rowconfigure(5, pad=5, weight = 1)
        
        self.lInput = Label(self, text = "Input file")
        self.lInput.grid(row = 0, column = 0, sticky = W)
        self.lPRS = Label(self, text = "phospoRS Column Name")
        self.lPRS.grid(row = 1, column = 0, sticky = W)
        self.lScore = Label(self, text = "Min phosphoRS Score")
        self.lScore.grid(row = 2, column = 0, sticky = W)
        self.lDA = Label(self, text = "Check deamidation sites")
        self.lDA.grid(row = 3, column = 0, sticky = W)
        self.lLabFile = Label(self, text = "Label description file")
        self.lLabFile.grid(row = 4, column = 0, sticky = W)
        
        self.ifPathText = StringVar()
        self.prsScoreText = StringVar(value = '0')
        self.prsNameText = StringVar()
        self.doDAVar = IntVar()
        self.labFileText = StringVar(value = path.abspath('moddict.txt'))
        
        self.ifPath = Entry(self, textvariable = self.ifPathText)
        self.ifPath.grid(row = 0, column = 1, sticky = W+E)
        self.prsName = Entry(self, textvariable = self.prsNameText)
        self.prsName.grid(row = 1, column = 1, sticky = W+E)        
        self.prsScore = Entry(self, textvariable = self.prsScoreText, state = DISABLED)
        self.prsScore.grid(row = 2, column = 1, sticky = W+E)
        self.doDABox = Checkbutton(self, variable = self.doDAVar)
        self.doDABox.grid(row = 3, column = 1, sticky = W)
        self.labFile = Entry(self, textvariable = self.labFileText)
        self.labFile.grid(row = 4, column = 1, sticky = W+E)
        
        
        self.foButton = Button(self, text = "Select file", command = self.selectFileOpen)
        self.foButton.grid(row = 0, column = 2, sticky = E+W, padx = 3)
        self.prsButton = Button(self, text = "Select column", state = DISABLED, command = self.selectColumn)
        self.prsButton.grid(row = 1, column = 2, sticky = E+W, padx = 3)
        self.labFileButton = Button(self, text = "Select file", command = self.selectLabFileOpen)
        self.labFileButton.grid(row = 4, column = 2, sticky = E+W, padx = 3)
        self.startButton = Button(self, text = "Start", command = self.start, padx = 3, pady = 3)
        self.startButton.grid(row = 5, column = 1, sticky = E+W)
        
    
        self.pack(fill = BOTH, expand = True, padx = 5, pady = 5)
        
    def selectFileOpen(self):
        #Open file dialog
        dlg = tkFileDialog.Open(self, filetypes = [('Excel spreadsheet', '*.xlsx')])
        openName = dlg.show()
        if openName != "":
            self.ifPathText.set(openName)
            self.findPRS(openName)#find phosphRS column
    
    def selectLabFileOpen(self):
        #Open labels file dialog
        dlg = tkFileDialog.Open(self, filetypes = [('All files', '*.*')])
        openName = dlg.show()
        if openName != "":
            self.labFileText.set(openName)
    
    def findPRS(self, openName):
        #find phosphoRS column
        worksheet = load_workbook(openName, use_iterators = True).get_active_sheet() #open excel sheet
        
        self.headers = [unicode(worksheet.cell(get_column_letter(columnNr) + '1').value).lower()
            for columnNr in range(1, worksheet.get_highest_column() + 1)]
        
        self.prsButton.config(state = "normal")
        
        if 'phosphors site probabilities' in self.headers:
            self.prsNameText.set('phosphoRS Site Probabilities')
        elif 'phosphors: phospho_sty site probabilities' in self.headers:
            self.prsNameText.set('PhosphoRS: Phospho_STY Site Probabilities')
        elif 'phosphors: phospho site probabilities' in self.headers:
            self.prsNameText.set('PhosphoRS: Phospho Site Probabilities')
        else:
            self.prsNameText.set('PhosphoRS column not found')
            return
            
        self.prsScore.config(state = 'normal')
        if self.prsScoreText.get() == '0':
            self.prsScoreText.set('95')
    
    def selectColumn(self):
        column = ListBoxChoice(self.parent, "Select column",
                                    "Select the column that has phosphoRS or ptmRS data", self.headers).returnValue()
        
        if not column is None:
            self.prsNameText.set(column)
            self.prsScore.config(state = 'normal')
            if self.prsScoreText.get() == '0':
                self.prsScoreText.set('95')
    
    def start(self):
        if self.prsScoreText.get() == '':
            self.prsScoreText.set("0")
            
        process(self.ifPathText.get(), float(self.prsScoreText.get()), bool(self.doDAVar.get()),
                'PD', self.labFileText.get(), self.prsNameText.get())
Пример #16
0
    def initUI(self,cards):
      
        self.parent.title("Karuta")
        
        Style().configure("TButton")
        
        p1,p2 = assignCards(cards,order)
        for row in range(6):
            for col in range(NUM_COLS):
                if (NUM_COLS-col,row+1) in p1:
                    self.setCard(p1[(NUM_COLS-col,row+1)],row,col)
                elif (col+1,6-row) in p2:
                    self.setCard(p2[(col+1,6-row)],row,col)
                else:
                    self.setCard(-1,row,col)
        self.p1 = [i for i in p1.values()]
        self.p2 = [i for i in p2.values()]

        def move():
            if self.state == 'move-select-start' or self.state == 'move-select-stop':
                self.changeState('waiting')
                self.moveButton.config(text='Move')
                self.infoLabel.config(text='Move cancelled')
            elif self.state == 'waiting':
                self.changeState('move-select-start')
                self.infoLabel.config(text='Select card to move')
                self.moveButton.config(text='Cancel')
            self.update()
        b = Button(self,text='Move',command=move)
        b.grid(row=0,column=8)
        self.moveButton = b


        def playNextAudio():
            if self.state == 'taking':
                self.playNextAudio()
            else:
                self.client.sendMessage('play')
        b = Button(self,text='Play',command=playNextAudio)
        self.playButton = b
        b.grid(row=0, column=9)

        def reveal():
            self.reveal()

        b = Button(self,text='Reveal',command=reveal)
        b.grid(row=0, column=10)
        self.revealButton = b
        if self.multiplayer:
            b.config(state=DISABLED)

        def rerack():
            self.rerack()

        b = Button(self,text='Rerack',command=rerack)
        b.grid(row=0, column=11)
        self.rerackButton = b


        def ready():
            if self.startTime < time.time() - 11:
                if self.state == 'taking' and not self.activeCardRow == -1:
                    self.infoLabel.config(text="Card has not been found yet.")
                    self.update()
                else:
                    self.moveButton.config(text="Move")
                    self.client.sendMessage('ready')
                    self.update()

        b = Button(self,text='Ready',command=ready)
        b.grid(row=0, column=12)
        self.readyButton = b

        l = Label(self,text='')
        l.grid(row=0, column=0, columnspan=5)
        self.infoLabel = l
        self.pack()
Пример #17
0
class Login(object):
    def __init__(self):
        self.root = Tk()
        self.root.title(u'登录')
        self.root.resizable(False, False)
        self.root.geometry('+450+250')
        self.sysfont = Font(self.root, size=15)
        self.lb_user = Label(self.root,
                             text=u'用户名:',
                             width=20,
                             height=10,
                             font=("黑体", 15, "bold"))
        self.lb_passwd1 = Label(self.root, text=u'')
        self.lb_passwd = Label(self.root,
                               text=u'密码:',
                               width=20,
                               height=5,
                               font=("黑体", 15, "bold"))
        self.lb_user.grid(row=0, column=0, sticky=W)
        self.lb_passwd1.grid(row=1, column=0, sticky=W)
        self.lb_passwd.grid(row=2, column=0, sticky=W)

        self.en_user = Entry(self.root, font=self.sysfont, width=24)
        self.en_passwd = Entry(self.root, font=self.sysfont, width=24)
        self.en_user.grid(row=0, column=1, columnspan=1)
        self.en_passwd.grid(row=2, column=1, columnspan=1)
        self.en_user.insert(0, u'请输入用户名')
        self.en_passwd.insert(0, u'请输入密码')
        self.en_user.config(
            validate='focusin',
            validatecommand=lambda: self.validate_func('self.en_user'),
            invalidcommand=lambda: self.invalid_func('self.en_user'))
        self.en_passwd.config(
            validate='focusin',
            validatecommand=lambda: self.validate_func('self.en_passwd'),
            invalidcommand=lambda: self.invalid_func('self.en_passwd'))

        self.var = IntVar()
        self.ckb = Checkbutton(self.root,
                               text=u'记住用户名和密码',
                               underline=0,
                               variable=self.var,
                               font=(15))
        self.ckb.grid(row=3, column=0)
        self.bt_print = Button(self.root, text=u'登陆')
        self.bt_print.grid(row=3, column=1, sticky=E, pady=50, padx=10)
        self.bt_print.config(command=self.print_info)

        self.bt_http = Button(self.root, text=u'http登录')
        self.bt_http.grid(row=3, column=2, sticky=E, pady=50, padx=50)
        self.bt_http.config(command=self.http_info)

        self.bt_register = Button(self.root, text=u'注册')
        self.bt_register.grid(row=3, column=3, sticky=E, pady=50, padx=50)
        self.bt_register.config(command=self.register_info)
        self.root.mainloop()

    def validate_func(self, en):
        return False if eval(en).get().strip() != '' else True

    def invalid_func(self, en):
        value = eval(en).get().strip()
        if value == u'输入用户名' or value == u'输入密码':
            eval(en).delete(0, END)
        if en == 'self.en_passwd':
            eval(en).config(show='*')

    def print_info(self):
        en1_value = self.en_user.get().strip()
        en2_value = self.en_passwd.get().strip()
        txt = u'''用户名: %s \n密码  : %s ''' % (self.en_user.get(),
                                            self.en_passwd.get())
        if en1_value == '' or en1_value == u'输入用户名':
            showwarning(u'无用户名', u'请输入用户名')
        elif en2_value == '' or en2_value == u'输入密码':
            showwarning(u'无密码', u'请输入密码')
        else:
            a = 0

            ip_port = ('127.0.0.1', 9999)
            regInfo = [en1_value, en2_value]

            tcpCliSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            tcpCliSock.connect(ip_port)
            datastr = json.dumps(regInfo)
            tcpCliSock.send(datastr.encode('utf-8'))
            data_sign = tcpCliSock.recv(1024)
            tcpCliSock.close()

            if data_sign == '0':
                a = 1
                print "数据库连接及验证成功!!!".decode("utf-8").encode("gb2312")
                showinfo('登陆成功!!!', txt)
                self.Chat()
                # # 打印结果
            else:
                print "Error: unable to fecth data"

            if (a == 0):
                showinfo('用户名或密码错误!!!', txt)

    def Chat(self):
        self.rootC = Toplevel()
        ChatClient(self.rootC)
        self.root.withdraw()

    def http_info(self):
        webbrowser.open("http://localhost:3000/login", new=0, autoraise=True)

    def register_info(self):
        self.rootR = Toplevel()
        loginPage(self.rootR)
        #self.root.withdraw()

    def enter_print(self, event):
        self.print_info()
Пример #18
0
class Login(object):
    def __init__(self):
        self.root = Tk()
        self.root.title(u'登录')
        self.root.resizable(False, False)
        self.root.geometry('+450+250')
        # self.sysfont = font(self.root, size=15)
        self.lb_user = Label(self.root,
                             text=u'用户名:',
                             width=20,
                             height=10,
                             font=("黑体", 15, "bold"))
        self.lb_passwd1 = Label(self.root, text=u'')
        self.lb_passwd = Label(self.root,
                               text=u'密码:',
                               width=20,
                               height=5,
                               font=("黑体", 15, "bold"))
        self.lb_user.grid(row=0, column=0, sticky=W)
        self.lb_passwd1.grid(row=1, column=0, sticky=W)
        self.lb_passwd.grid(row=2, column=0, sticky=W)

        self.en_user = Entry(self.root, width=24)
        self.en_passwd = Entry(self.root, width=24)
        self.en_user.grid(row=0, column=1, columnspan=1)
        self.en_passwd.grid(row=2, column=1, columnspan=1)
        self.en_user.insert(0, u'请输入用户名')
        self.en_passwd.insert(0, u'请输入密码')
        self.en_user.config(
            validate='focusin',
            validatecommand=lambda: self.validate_func('self.en_user'),
            invalidcommand=lambda: self.invalid_func('self.en_user'))
        self.en_passwd.config(
            validate='focusin',
            validatecommand=lambda: self.validate_func('self.en_passwd'),
            invalidcommand=lambda: self.invalid_func('self.en_passwd'))

        self.var = IntVar()
        self.ckb = Checkbutton(self.root,
                               text=u'记住用户名和密码',
                               underline=0,
                               variable=self.var,
                               font=(15))
        self.ckb.grid(row=3, column=0)
        self.bt_print = Button(self.root, text=u'登陆')
        self.bt_print.grid(row=3, column=1, sticky=E, pady=50, padx=10)
        self.bt_print.config(command=self.print_info)

        self.bt_register = Button(self.root, text=u'注册')
        self.bt_register.grid(row=3, column=2, sticky=E, pady=50, padx=50)
        # self.bt_register.config(command=self.register_info)
        # self.root.bind('<Return>', self.enter_print)
        self.root.mainloop()

    def validate_func(self, en):
        return False if eval(en).get().strip() != '' else True

    def invalid_func(self, en):
        value = eval(en).get().strip()
        if value == u'输入用户名' or value == u'输入密码':
            eval(en).delete(0, END)
        if en == 'self.en_passwd':
            eval(en).config(show='*')

    def print_info(self):
        en1_value = self.en_user.get().strip()
        en2_value = self.en_passwd.get().strip()
        txt = u'''用户名: %s \n密码  : %s ''' % (self.en_user.get(),
                                            self.en_passwd.get())
        if en1_value == '' or en1_value == u'输入用户名':
            print(u'无用户名', u'请输入用户名')
        elif en2_value == '' or en2_value == u'输入密码':
            print(u'无密码', u'请输入密码')
        else:
            a = 0
            # 打开数据库连接
            db = pymysql.connect("62.234.41.135", "root", "root", "book")
            # 使用cursor()方法获取操作游标
            cursor = db.cursor()
            # SQL 查询语句
            sql = "select * from user"
            try:
                # 执行SQL语句
                cursor.execute(sql)
                # 获取所有记录列表
                results = cursor.fetchall()
                for row in results:
                    id = row[0]
                    name = row[1]
                    pwd = row[2]
                    if name == en1_value and pwd == en2_value:
                        a = 1
                        print("数据库连接及验证成功!!!")
                        print('登陆成功!!!', txt)
                    # # 打印结果
                    # print "id=%d,name=%s,pwd=%s" % \
                    #       (id, name, pwd)
            except:
                print("Error: unable b_while fecth data")

            # 关闭数据库连接
            db.close()
            if (a == 0):
                print('用户名或密码错误!!!', txt)

    def register_info(self):
        self.rootR = Tk()
        loginPage(self.rootR)
        self.root.withdraw()

    def enter_print(self, event):
        self.print_info()
Пример #19
0
class DronControll(Frame):

    #Botones Despegar aterrizar
    btnDespegar = 0
    btnAterrizar = 0
    #Botones controll
    btnGiroIzquierda = 0
    btnGiroDerecha = 0
    btnAdelante = 0
    btnAtras = 0
    btnIzquierda = 0
    btnDerecha = 0
    #Botones camera
    btnTiltDownCamera = 0
    btnTiltUpCamera = 0
    btnPanLeft = 0
    btnPanRight = 0
    btnEnableCamera = 0

    #TOPICS
    pubControllDron = 0
    pubControllTakeoff = 0
    pubControllLanding = 0

    #ETIQUETAS
    etqControlDron = 0
    etqControlCamera = 0

   
    def __init__(self,parent,pubControllDron,pubControllTakeoff,pubControllLanding,pubControllCamera):
        Frame.__init__(self, parent)

        self.parent = parent
        self.initUI()

        self.pubControllDron = pubControllDron
        self.pubControllTakeoff = pubControllTakeoff
        self.pubControllLanding = pubControllLanding
        self.pubControllCamera = pubControllCamera
    
        
    def initUI(self):

        self.parent.title("Quit button")
        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)
        self.initButtons()

        self.etqControlDron = Label(self,text="Dron Controll")
        self.etqControlDron.place(x=20,y=10)

        self.etqControlCamera = Label(self,text="Camera Controll")
        self.etqControlCamera.place(x=370,y=10)

    def initButtons(self):

        #Controll drone

        self.btnIzquierda = Button(self,text = "Go Left",command = self.GoLeft)
        self.btnIzquierda.place(x=60,y=60)

        self.btnDerecha = Button(self,text = "Go Right",command = self.GoRight)
        self.btnDerecha.place(x=260,y=60)

        self.btnGiroIzquierda = Button(self, text="Rotate Left",command=self.Izquierda)
        self.btnGiroIzquierda.place(x=50, y=100)

        self.btnGiroDerecha = Button(self,text = "Rotate Right",command=self.Derecha);
        self.btnGiroDerecha.place(x=250, y=100);

        self.btnAdelante = Button(self,text = "Forward",command=self.Delante);
        self.btnAdelante.place(x=160,y=50);

        self.btnAtras = Button(self,text = "Backwards",command=self.Atras);
        self.btnAtras.place(x=150,y=140);

        #takeoff & landing

        self.btnDespegar = Button(self,text = "Takeoff",command=self.Takeoff);
        self.btnDespegar.place(x=50,y=220);

        self.btnAterrizar = Button(self,text = "Landing",command=self.Land);
        self.btnAterrizar.place(x=250,y=220);
        self.btnAterrizar.config(state='disabled')

        #camera_controll
        self.btnTiltUpCamera = Button(self,text="Tilt Up Camera",command=self.tiltup)
        self.btnTiltUpCamera.place(x=450,y=60);

        self.btnTiltDownCamera = Button(self,text="Tilt Down Camera",command=self.tiltdown)
        self.btnTiltDownCamera.place(x=600,y=60);

        self.btnPanRight = Button(self,text="Pan Right Camera",command=self.panRight)
        self.btnPanRight.place(x=600,y=150);

        self.btnPanLeft = Button(self,text="Pan Left Camera",command=self.panLeft)
        self.btnPanLeft.place(x=450,y=150);

    #Camera controll
    def panLeft(self):
        print("pan left")
        self.pubControllCamera.publish(Twist(Vector3(0,0,0),Vector3(0,0,-10)))

    def panRight(self):
        print("pan right")
        self.pubControllCamera.publish(Twist(Vector3(0,0,0),Vector3(0,0,10)))

    def tiltup(self):
        print("tilt up")
        self.pubControllCamera.publish(Twist(Vector3(0,0,0),Vector3(0,10,0)))

    def tiltdown(self):
        print("tilt down")
        self.pubControllCamera.publish(Twist(Vector3(0,0,0),Vector3(0,-10,0)))

    #Dron controll
    def GoLeft(self):
        print("go left")
        self.pubControllDron.publish(Twist(Vector3(0,1,0),Vector3(0,0,0)))

    def GoRight(self):
        print("go right")
        self.pubControllDron.publish(Twist(Vector3(0,-1,0),Vector3(0,0,0)))

    def Delante(self):
        print("Adelante...")
        self.pubControllDron.publish(Twist(Vector3(2,0,0),Vector3(0,0,0)))

    def Atras(self):
        print("Atras")
        self.pubControllDron.publish(Twist(Vector3(-2,0,0),Vector3(0,0,0)))

    def Derecha(self):
        print("Derecha")
        self.pubControllDron.publish(Twist(Vector3(0,0,0),Vector3(0,0,-3)))

    def Izquierda(self):
        print("Izquierda")
        self.pubControllDron.publish(Twist(Vector3(0,0,0),Vector3(0,0,3)))

    #Dron landing and takeoff
    def Land(self):
        print("LANDING...")
        self.btnAterrizar.config(state='disabled')
        self.btnDespegar.config(state='normal')
        self.pubControllLanding.publish(Empty())
        

    def Takeoff(self):
        print("Takeoff...")
        self.btnDespegar.config(state='disabled')
        self.btnAterrizar.config(state='normal')
        self.pubControllTakeoff.publish(Empty())
Пример #20
0
class App(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent
        self.initUI()
        self.centerWindow()

    def initUI(self):
        self.parent.title("Champion Pool Builder")
        self.parent.iconbitmap("assets/icon.ico")
        self.style = Style()
        self.style.theme_use("default")

        self.pack(fill=BOTH, expand=1)

        self.buildMode = True
        self.allPools = "assets/pools/"

        self.champsLabel = Label(text="Champions")
        self.champBox = Listbox(self)
        self.champBoxScrollbar = Scrollbar(self.champBox, orient=VERTICAL)
        self.champBox.config(yscrollcommand=self.champBoxScrollbar.set)
        self.champBoxScrollbar.config(command=self.champBox.yview)

        self.addButton = Button(self, text=">>", command=self.addChampToPool)
        self.removeButton = Button(self, text="<<", command=self.removeChampFromPool)
        self.saveButton = Button(self, text="Save champion pool", width=18, command=self.saveChampPool)
        self.loadButton = Button(self, text="Load champion pool", width=18, command=lambda: self.loadChampPools(1))
        self.confirmLoadButton = Button(self, text="Load", width=6, command=self.choosePool)
        self.getStringButton = Button(self, text="Copy pool to clipboard", width=18, command=self.buildPoolString)

        self.poolLabel = Label(text="Champion Pool")
        self.poolBox = Listbox(self)
        self.poolBoxScrollbar = Scrollbar(self.poolBox, orient=VERTICAL)
        self.poolBox.config(yscrollcommand=self.poolBoxScrollbar.set)
        self.poolBoxScrollbar.config(command=self.poolBox.yview)

        self.champsLabel.place(x=5, y=5)
        self.champBox.place(x=5, y=30)

        self.addButton.place(x=150, y=60)
        self.removeButton.place(x=150, y=100)
        self.saveButton.place(x=350, y=30)
        self.loadButton.place(x=350, y=60)
        self.getStringButton.place(x=350, y=90)

        self.poolLabel.place(x=200, y=5)
        self.poolBox.place(x=200, y=30)

        self.champBox.focus_set()
        self.loadChampions()

    def centerWindow(self):
        w = 500
        h = 200
        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()
        x = (sw - w)/2
        y = (sh - h)/2
        self.parent.geometry("%dx%d+%d+%d" % (w, h, x, y))

    def loadChampions(self, pooled=None):
        if pooled:
            with open("assets/Champions.txt", "r") as file:
                champions = file.read().splitlines()
            for champ in pooled:
                champions.remove(champ)
            for champion in sorted(champions):
                self.champBox.insert(END, champion)
        else:
            with open("assets/Champions.txt", "r") as file:
                champions = file.read().splitlines()
            for champion in sorted(champions):
                self.champBox.insert(END, champion)

    def choosePool(self):
        idx = self.poolBox.curselection()
        chosenPool = self.poolBox.get(idx)
        self.confirmLoadButton.place_forget()
        self.loadChampPools(2, chosenPool)

    def loadChampPools(self, level, pool=None):
        if level == 1:
            self.buildMode = False
            self.champBox.delete(0, END)
            self.poolBox.delete(0, END)
            self.saveButton.config(state=DISABLED)
            self.loadButton.config(state=DISABLED)
            self.getStringButton.config(state=DISABLED)
            self.confirmLoadButton.place(x=350, y=120)

            with open("assets/champpools.txt", "r") as file:
                champPools = file.read().splitlines()
            for pool in champPools:
                self.poolBox.insert(END, pool)
        elif level == 2:
            self.poolBox.delete(0, END)
            self.buildMode = True
            self.loadButton.config(state=NORMAL)
            self.saveButton.config(state=NORMAL)
            self.getStringButton.config(state=NORMAL)

            fileName = pool + ".txt"
            with open(self.allPools + fileName, "r") as file:
                champPool = file.read().splitlines()
                for champion in sorted(champPool):
                    self.poolBox.insert(END, champion)

            self.loadChampions(champPool)

    def addChampToPool(self):
        idx = self.champBox.curselection()
        if idx and self.buildMode:
            name = self.champBox.get(idx)
            self.poolBox.insert(END, name)
            self.champBox.delete(idx)

    def removeChampFromPool(self):
        idx = self.poolBox.curselection()
        if idx and self.buildMode:
            name = self.poolBox.get(idx)
            self.champBox.insert(END, name)
            self.poolBox.delete(idx)

    def checkIfPoolExists(self, title):
        with open("assets/champpools.txt", "r") as poolFile:
            pools = poolFile.read().splitlines()
            for pool in pools:
                if pool == title:
                    return True
            return False

    def saveChampPool(self):
        championPool = self.poolBox.get(0, END)
        poolTitle = TitleDialog(self.parent)
        fileName = self.allPools + poolTitle.title + ".txt"
        checker = self.checkIfPoolExists(poolTitle.title)

        if not checker:
            with open("assets/champpools.txt", "a")as file:
                file.write(poolTitle.title + "\n")
        with open(fileName, "w+") as file:
            for champion in sorted(championPool):
                file.write(champion + "\n")



    def buildPoolString(self):
        clipper = Tk()
        clipper.withdraw()
        clipper.clipboard_clear()

        championPool = self.poolBox.get(0, END)

        if championPool:
            championPoolString = ""
            for champion in championPool:
                championPoolString += "^" + champion + "$|"

            clipper.clipboard_append(championPoolString)
            clipper.destroy()
Пример #21
0
class CreateServer(Frame):

    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        self.controller = controller
        CreateServer.local_world = None
        label_1 = Label(self, text="Create server\n\n\n\n", font=TITLE_FONT, justify=CENTER, anchor=CENTER)
        label_2 = Label(self, text="Server name:")
        label_3 = Label(self, text="Gamefield (MxN):")
        CreateServer.plx_name = 'none'
        CreateServer.game_dim = '10X10'
        self.entry_1 = Entry(self)
        self.entry_2 = Entry(self)
        self.entry_2.insert(0, '10x10')
        self.entry_1.bind("<Key>", self.checkString)

        self.button1 = Button(self, text="Create",state="disabled", command= self.callback_set)
        self.button2 = Button(self, text="Back", command=lambda: controller.show_frame("StartPage"))

        label_1.pack(side="top", fill="x", pady=10)
        label_2.pack()
        self.entry_1.pack()
        label_3.pack()
        self.entry_2.pack()
        self.button1.pack(pady=10)
        self.button2.pack(pady=20)
    
    
    def com(self, controller, next_frame):
        controller.show_frame(next_frame)
        
    def checkString(self, event):
        if self.entry_1:
            self.button1.config(state="normal")
    
    def callback_set(self):
        set_global_state(1)
        if self.get_name_field():
            self.controller.show_frame("ChooseType")
    
    # process user inputs
    def get_name_field(self):
        CreateServer.plx_name = self.entry_1.get()
        CreateServer.game_dim = self.entry_2.get().upper()
        
        flag2 = False
        
        flag1 = self.string_check(CreateServer.plx_name,"Invalid server name")
        if flag1:
            flag2 = self.string_check(CreateServer.game_dim,"Invalid game field parameters")
        
        if flag2:
            m_split=CreateServer.game_dim.split('X')
            if len(m_split)==2:
                try:
                    _ = int(m_split[0])
                except:
                    flag2 = False  
                try:
                    _ = int(m_split[1])
                except:
                    flag2 = False
            else:
                flag2 = False
                
            if flag2 == False:
                tkMessageBox.showwarning("Error message", "Invalid game field parameters!")
        return flag1 & flag2
    
    # check if the string is usable
    def string_check(self,s,msg):
        temp = False
        try:
            s.decode('ascii')
        except UnicodeEncodeError:
            print "it was not an ascii-encoded unicode string"
            tkMessageBox.showwarning("Error message", msg)
        except UnicodeDecodeError:
            print "it was not an ascii-encoded unicode string"
            tkMessageBox.showwarning("Error message", msg)
        else:
            if len(CreateServer.plx_name) < 11 and len(CreateServer.plx_name) >= 1:
                temp = True
            else:
                tkMessageBox.showwarning("Error message", "Please input 1-10 characters!")
        return temp
Пример #22
0
class Login(object):
    def __init__(self):
        self.root = Tk()
        self.root.title(u'用户登录')
        self.root.resizable(False, False)
        self.root.geometry('+500+500')
        self.lb_user = Label(self.root, text=u'用户名:', padx=5)
        self.lb_passwd = Label(self.root, text=u'密码:', padx=5)

        self.lb_stime = Label(self.root, text=u'日期: ', padx=5)
        self.lb_sexmp = Label(self.root, text=u'      (输入格式01,02,03)', padx=5)
        self.lb_mytext = Label(self.root, text=u'原因: ', padx=5)
        self.lb_user.grid(row=0, column=0, sticky=W)
        self.lb_passwd.grid(row=1, column=0, sticky=W)
        self.lb_stime.grid(row=2, column=0, sticky=W)
        self.lb_sexmp.grid(row=3, column=0, sticky=W)
        self.lb_mytext.grid(row=4, column=0, sticky=W)

        self.en_user = Entry(self.root, width=20)
        self.en_passwd = Entry(self.root, width=20)
        self.en_stime = Entry(self.root, width=20)
        self.en_reson = Entry(self.root, width=20)
        self.en_user.grid(row=0, column=1, columnspan=1)
        self.en_passwd.grid(row=1, column=1, columnspan=1)
        self.en_stime.grid(row=2, column=1, columnspan=1)
        self.en_reson.grid(row=4, column=1, columnspan=1, rowspan=3)

        self.var = IntVar()
        self.ckb = Checkbutton(self.root,
                               text=u'记住用户名和密码',
                               underline=0,
                               variable=self.var)
        self.ckb.grid(row=9, column=0)
        self.bt_print = Button(self.root, text=u'确定', width=20)
        self.bt_print.grid(row=9, column=1, sticky=E, pady=5)
        self.bt_print.config(command=self.print_info)
        self.checkconf()
        self.root.mainloop()

        def validate_func(self, en):
            return False if eval(en).get().strip() != '' else True

    def print_info(self):
        en1_value = self.en_user.get().strip()
        en2_value = self.en_passwd.get().strip()
        en3_value = self.en_stime.get().strip()
        nowtime = time.strftime('%Y-%m-', time.localtime(time.time()))
        real_en3_value = nowtime + en3_value + " 18:00"
        real_en4_value = nowtime + en3_value + " 20:00"
        en4_value = self.en_stime.get().strip()
        en5_value = self.en_reson.get().strip()
        #print(real_en3_value,real_en4_value)
        isok = job.test_search_in_python_org(en1_value, en2_value,
                                             real_en3_value, real_en4_value,
                                             en5_value)
        #print(isok)

    def checkconf(self):
        if os.path.exists("local.conf") and os.path.getsize("local.conf") != 0:
            list = []
            with open('local.conf', 'r') as f:
                for line in f.readlines():
                    list.append(line.strip())
                    print(line.strip())
            self.en_user.insert(0, list[0])
            self.en_passwd.insert(0, list[1])
            self.en_stime.insert(0, u'01')
            self.en_reson.insert(0, list[2])
        else:
            self.en_user.insert(0, u'input you name')
            self.en_passwd.insert(0, u'input you password')
            self.en_stime.insert(0, u'01')
            self.en_reson.insert(0, u'值班')
Пример #23
0
class GameWindow(Frame):

    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        self.parent = parent
        self.watchdog_socket = None
        self.is_first_time = True
        self.is_alive = True
        self.play_again = False
        self.controller = controller
        self.root = self
        self.keys = {}
        self.items = []
        self.extents = None # field size
        self.background = None
        # the following variables are needed for arrow key servicing
        # <<<<<
        self.amove = 'STAY'
        self.ajump = 0
        self.movereg = 0
        self.bup = 0
        self.bdown = 0
        self.bleft = 0
        self.bright = 0
        self.sprint = 1
        self.direction = None
        self.next_move = 'STAY'
        self.up_key = False
        self.down_key = False
        self.right_key = False
        self.left_key = False
        self.up_key_count = 0
        self.down_key_count = 0
        self.right_key_count = 0
        self.left_key_count = 0 
        self.local_class = "SPECTATOR"
        # >>>>>
       
        # Everything that is visible in the side bar
        # Info: Server, Nickname, Class, Score, Time
        # Buttons: try again, leave 
        # <<<<<<
        sidebar = Frame(self)
        sidebar.pack(side='left',fill='y')
        opts_frame = Frame(sidebar)
        GameWindow.vSer = StringVar()
        self.vN = StringVar()
        self.vC = StringVar()
        self.vS = StringVar()
        self.vT = StringVar()
        i = 0
        label00 = Label(opts_frame, text='Server: ')
        label00.grid(row=i,column=0)
        self.labe01 = Label(opts_frame, textvariable=GameWindow.vSer)
        self.labe01.grid(row=i,column=1)
        i=i+1
        if self.vC != "SPECTATOR":
            label1 = Label(opts_frame, text='Nickname: ')
            label1.grid(row=i,column=0)
        self.label2 = Label(opts_frame, textvariable=self.vN)
        self.label2.grid(row=i,column=1)
        i=i+1
        label3 = Label(opts_frame, text='Class: ')
        label3.grid(row=i,column=0)
        self.label4 = Label(opts_frame, textvariable=self.vC)
        self.label4.grid(row=i,column=1)
        i=i+1
        label5 = Label(opts_frame, text='Score: ')
        label5.grid(row=i,column=0)
        self.label6 = Label(opts_frame, textvariable=self.vS)
        self.label6.grid(row=i,column=1)
        i=i+1          
        label7 = Label(opts_frame, text="Time")
        label7.grid(row=i,column=0)
        self.label8 = Label(opts_frame, textvariable=self.vT)
        self.label8.grid(row=i,column=1)
        opts_frame.pack(side='top',fill='x', )
        self.leave_button = Button(sidebar, text="Try again!")
        self.leave_button.pack(side='top',fill='x')
        self.leave_button.config(command=self._again)
        self.leave_button = Button(sidebar, text="Leave")
        self.leave_button.pack(side='top',fill='x')
        self.leave_button.config(command=self._leave)
        # >>>>>>
        
        # bind arrow key events to the canvas which is used to show the game field
        self.canvas = Canvas(self)
        self.canvas.bind('<KeyPress>', self.kp)
        self.canvas.bind('<KeyRelease>', self.kr)
        self.canvas.bind("<1>", lambda event: self.canvas.focus_set())
        self.canvas.pack(expand=True,fill='both')
        # List info: players on the game field
        self.players_list = Text(sidebar, width=20, state=DISABLED)
        self.players_list.pack(side='top',expand=True, fill='both')
        # Start the scheduler
        self._tick()
    
    # key press
    def kp(self,event):
        if event.keysym == 'Up':
            self.direction = UP
            self.up_key = True
            self.up_key_count += 1
        elif event.keysym == 'Down':
            self.direction = DOWN
            self.down_key = True
            self.down_key_count += 1
        elif event.keysym == 'Left':
            self.direction = LEFT
            self.left_key = True
            self.left_key_count += 1 # 0 is do not move
        elif event.keysym == 'Right':
            self.direction = RIGHT
            self.right_key = True
            self.right_key_count += 1
        elif event.keysym == 'Shift_L' or event.keysym == 'Shift_R':
            if ChooseType.plx_type == "FROG":
                self.sprint = 2
    # key release
    def kr(self,event):
        if event.keysym == 'Up':
            self.up_key = False
        elif event.keysym == 'Down':
            self.down_key = False
        elif event.keysym == 'Left':
            self.left_key = False      
        elif event.keysym == 'Right':
            self.right_key = False
        elif event.keysym == 'Shift_L' or event.keysym == 'Shift_R':
            if ChooseType.plx_type == "FROG":
                self.sprint = 1
    
    def prepare_move(self):
        if ChooseType.plx_type != 'SPECTATOR':     
            # UP
            if self.direction == UP:
                if self.sprint == 1:
                    self.next_move = 'UP'
                elif self.sprint == 2:
                    self.next_move = '2UP'
                self.up_key_count = 0
            # DOWN
            elif self.direction == DOWN:
                if self.sprint == 1:
                    self.next_move = 'DOWN'
                elif self.sprint == 2:
                    self.next_move = '2DOWN'
                self.down_key_count = 0
            # LEFT
            elif self.direction == LEFT:
                if self.sprint == 1:
                    self.next_move = 'LEFT'
                elif self.sprint == 2:
                    self.next_move = '2LEFT'
                self.left_key_count = 0
            # RIGHT
            elif self.direction == RIGHT:
                if self.sprint == 1:
                    self.next_move = 'RIGHT'
                elif self.sprint == 2:
                    self.next_move = '2RIGHT'
                self.right_key_count = 0
            # no motion
            else:
                self.direction = 'none'
                self.next_move = 'STAY'                
            self._send_actions(self.next_move)
            self.next_move = 'STAY'
            self.direction = 'none'
    
    def update_field(self, extents):
        "Creates field background."
        if extents==self.extents:
            return
        # Delete the old background
        if self.background!=None:
            self.canvas.delete(self.background)
        self.extents = extents
        M,N = extents
        self.background = self.canvas.create_rectangle(0,0,WIDTH*M,WIDTH*N, fill=BACKGROUND_COLOR)

    def update_objects(self, objects):
        "Create canvas items from triples: (x,y,class)."
        oldItems = list(self.items)
        self.items = []
        # add new objects
        for (i,j,tp) in objects:
            if tp not in C_CODE:
                continue
            size = SIZES[tp]
            tx = int(j)*WIDTH+(WIDTH-size)/2
            ty = int(i)*WIDTH+(WIDTH-size)/2
            x = int(tx)
            y = int(ty)
 
            if tp in [RC_FROG]:
                # the cell is visible, so put background
                bItem = self.canvas.create_rectangle(x,y,x+WIDTH,y+WIDTH, fill='#ffc', width=0)
                item = self.canvas.create_oval(x,y,x+size-1,y+size-1, fill='green') # reduce by 1 for outline
                self.items.extend([bItem,item])
            elif tp in [RC_FLY]:
                # the cell is visible, so put background
                bItem = self.canvas.create_rectangle(x-S_WIDTH,y-S_WIDTH,x+S2_WIDTH,y+S2_WIDTH, fill='#ffc', width=0)
                item = self.canvas.create_oval(x,y,x+size-1,y+size-1, fill='black') # reduce by 1 for outline
                self.items.extend([bItem,item])
            elif tp in [RC_ZERO]:
                item = self.canvas.create_rectangle(x,y,x+size,y+size, fill='#ffc', width=0)
                self.items.append(item)
        # delete old objects
        for item in oldItems:
            self.canvas.delete(item)

    def _tick(self):
        # If the game has started:    
        if ChooseType.start_game:
            # Check if it's a client's entity
            if global_state == 0:
                # If the first time in a particular game, initialize the watch dog.
                # and start the listening thread.
                if self.is_first_time:
                    self.is_alive = True
                    self.watchdog_socket = self._init_watchdog(BROADCASTING_PORT, WATCHDOG_PING)
                    wdt = self.server_alive_watchdog_thread(self.watchdog_socket, SERVER_LIST)
                    wdt.start()
                    THREADS.append(wdt)
                    print "Watchdog thread started!"
                    # Wait for the server to be considered online by the watch dog for the first time
                    while not self.is_alive:
                        pass
                    self.is_first_time = False
                    # Check if the server is still running by using the watch dog.
                if self.is_alive:
                    self._recScope()
                    self.prepare_move()
                    self._recList()
                else:
                    # If server down - show a pop up message and leave the game.
                    tkMessageBox.showwarning("Game status", "Server down")
                    self._leave()
            else:
                if CreateServer.local_world.keep_alive:
                    self._recScope()
                    self.prepare_move()
                    self._recList()
        # If a player pressed the 'X' window button, leave and destroy the app.
        if shut_down_level == 2:
            if self.play_again:
                ChooseType.start_game = True
            self._leave()
            set_shut_down_level(0)                     
            self.parent.destroy()
            self.parent.quit()
        self.root.after(TICK_TIME, self._tick) # Must be larger than engine's sleep

    # receive message
    def _rec_msg(self):
        buf = ChooseType.socket.recv(100)
        message = buf.decode('utf-8')
        return message
    
    # play again
    def _again(self):
        if ChooseType.start_game == False:
            return
        self.play_again = True
        ChooseType.button4.config(state="disabled")
        if global_state == 0:
            self._send_one_word('LEAVE')
        else:
            CreateServer.local_world.set_player_attr(ChooseType.create_player, 1, 'character', "SPECTATOR")
        ChooseType.start_game = False
        self.controller.show_frame("ChooseType")
    
    def _leave(self):
        if ChooseType.start_game == False:
            return
        ChooseType.start_game = False
        self.play_again = False
        set_shut_down_level(0)
        ChooseType.button4.config(state="normal")
        if global_state == 0:
            print 'Client trying to leave'
            self._send_one_word('QUIT')
            ChooseType.socket.close() # Close the socket
            print 'Exited succesfully!'
            self.is_first_time = True
            # Signal the watchdog thread to end
            self.is_alive = False
        else:         
            CreateServer.local_world.keep_alive = False # Kill some threads   
            # Kill the server thread by sending the appropriate message
            s = socket.socket(AF_INET,SOCK_STREAM)
            host = globvar[0]
            s.connect((host,QUAD_AXE))
            msg = 'CLOSE_SOCKET'
            s.send(msg.encode())
            s.close()
            # Remove the client from the list.
            for client in CLIENTS:
                CLIENTS.remove(client)  # Remove all clients            
        set_global_state(0)
        self.controller.show_frame("StartPage")
    
    # receive the scope  
    def _recScope(self):
        if ChooseType.start_game == False:
            return
        try:
            if global_state == 0:
                    self._send_one_word("PRINT")
                    buf = ChooseType.socket.recv(BUF_SIZE)
                    scope = pickle.loads(buf)
            else:
                scope = CreateServer.local_world.gamefield_scope(ChooseType.create_player)
            if scope:
                self._recv_command2(scope)
        except Exception:
                        if not self.is_alive:
                            ChooseType.socket.close()
    # receive the player list        
    def _recList(self):
        if ChooseType.start_game == False:
            return
        try:
            if global_state == 0:
                self._send_one_word("SCORE")
                buf = ChooseType.socket.recv(BUF_SIZE)
                p_list = buf.decode('utf-8')
                self.process_list(p_list)
            else:
                p_list = CreateServer.local_world.get_player_info(ChooseType.create_player)
                self.process_list(p_list)
        except Exception:
            if not self.is_alive:
                ChooseType.socket.close()
    
    # decode the player list        
    def process_list(self,message):
        m_split = message.split(';')
        # get player type, if player has died, the serve switches player class to spectator
        fly_list = []
        frog_list = []
        player_stats = []
        # the lists are created by deciphering the received packet from server
        for i, c in enumerate(m_split):
            # code for player list: PL1
            if c == "PL1":
                # fly or forg player list key: PL1;PL2;
                if m_split[i] == "PL1" and m_split[i+1] == "PL2":
                    # fly list key: PL1;PL2;FLY;
                    if m_split[i+2] == "FLY": # full sequence: PL1;PL2;FLY;NAME;SCORE;TIME
                        for k in range(3,6):
                            fly_list.append(str(m_split[i+k]))
                    # frog list key: PL1;PL2;FROG;
                    if m_split[i+2] == "FROG": # full sequence: PL1;PL2;FROG;NAME;SCORE;TIME
                        for k in range(3,6):
                            frog_list.append(str(m_split[i+k]))
                # player info key: PL1;PL3;
                if m_split[i] == "PL1" and m_split[i+1] == "PL3": # full sequence: PL1;PL3;CLASS;NAME;SCORE;TIME
                    for k in range(2,6):
                        player_stats.append(str(m_split[i+k]))              
        if player_stats:
            self.vN.set(player_stats[1])
            self.vC.set(player_stats[0])
            self.vS.set(player_stats[2])
            self.vT.set(player_stats[3])
        else:
            self.vN.set("")
            self.vC.set("SPECTATOR")
            self.vS.set("")
            self.vT.set("")
        self._update_list(fly_list,frog_list)
    
    # send MOVE action to he server or directly ad it to the engine movement variables
    def _send_actions(self, actions):
        if global_state == 0:
            self._send_two_words('MOVE', actions)          
        else:
            CreateServer.local_world.set_player_attr(ChooseType.create_player, 1, 'nextmove', actions)
    
    # send two word command        
    def _send_one_word(self, com1):
        if ChooseType.socket==None:
            return
        try:
            if global_state == 0: 
                data = com1 + ";"
                ChooseType.socket.send(data.encode())
        except Exception:
            if not self.is_alive:
                ChooseType.socket.close()
    
    # send one word command
    def _send_two_words(self, com1, com2):
        if ChooseType.socket==None:
            return
        try:
            data = com1+";"+com2
            if global_state == 0: 
                ChooseType.socket.send(data.encode())
        except Exception:
            if not self.is_alive:
                ChooseType.socket.close()
    
    # prepare the received game scope for game field rendering
    def _recv_command2(self, args):
        objects = []
        numrows = len(args) 
        numcols = len(args[0])
        for i in range(numrows):
            for j in range(numcols):
                cell = args[i][j]
                objects.append((i,j,cell))
        self.update_field((numcols,numrows))
        self.update_objects(objects)
    
    # sidebar list info : list is divided in tow parts: fly list and frog list
    def _update_list(self,fly_list,frog_list):
        self.players_list.config(state=NORMAL)
        self.players_list.delete("1.0",END)
        flyc = len(fly_list)
        frogc = len(frog_list)
        if fly_list:
            self.players_list.insert(END,("FLYs<:>Score<:>Time\n"))        
            for i in range(0, flyc, 3):
                self.players_list.insert(END,(fly_list[i]+": "+fly_list[i+1]+" "+fly_list[i+2]+"\n"))
        if frog_list:
            self.players_list.insert(END,("FROGs<:>Score<:>Time\n"))   
            for i in range(0, frogc, 3):
                self.players_list.insert(END,(frog_list[i]+": "+frog_list[i+1]+" "+frog_list[i+2] +"\n"))
        self.players_list.config(state=DISABLED)
    
    def _init_watchdog(self, port, timeout):
        '''Initialize the listening watch dog.
        '''
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        s.bind(('', port))
        s.settimeout(timeout)
        return s

    def _server_alive_watchog(self, socket, list_of_servers):
        '''The watch dog listens if the server is still alive.
            If not - sets a particular flag.
        '''
        socket.settimeout(WATCHDOG_PING)
        try:
            while self.is_alive:
                message, address = socket.recvfrom(8192)
                if message == '\DIE':
                    if address == globvar[1]: # If the registered server is the one that broadcasted, then it's alive
                        self.is_alive = False
            print 'Watchdog thread ended!'
            socket.close()
        except Exception:
            socket.close()
            
    def server_alive_watchdog_thread(self, socket, list_of_servers): 
        args = { 'socket':socket, 'list_of_servers':list_of_servers}
        def server_wd(x,a):
            self._server_alive_watchog(args['socket'], args['list_of_servers'])
        name = "Server watchdog thread"
        t = Thread(target=server_wd, name=name, args=args)
        return t 
Пример #24
0
class Window(Frame):
	def __init__(self, parent):
		Frame.__init__(self, parent)
		self.parent = parent
		self.initUI()

	def initUI(self):
		self.style = Style()
		self.style.theme_use("clam")
		self.pack(fill=BOTH,expand=5)
		self.parent.title("Document Similarity Checker")
		self.dir = "Choose a directory"
		self.setupInputs()
		self.setButton()
	
	def setupInputs(self):
		self.chooseDir = Button(self, text="Choose",command=self.getDir)
		self.chooseDir.place(x=10, y=10)
		self.selpath = Label(self, text=self.dir, font=("Helvetica", 12))
		self.selpath.place(x=150, y=10)

		self.aLabel = Label(self, text="Alpha", font=("Helvetica", 12))
		self.aLabel.place(x=10, y=50)
		self.aEntry = Entry()
		self.aEntry.place(x=200,y=50,width=400,height=30)

		self.bLabel = Label(self, text="Beta", font=("Helvetica", 12))
		self.bLabel.place(x=10, y=100)
		self.bEntry = Entry()
		self.bEntry.place(x=200,y=100,width=400,height=30)

	def setButton(self):
		self.quitButton = Button(self, text="Close",command=self.quit)
		self.quitButton.place(x=520, y=250)

		self.browserButton = Button(self, text="Open Browser",command=self.browser)
		self.browserButton.place(x=400, y=250)
		self.browserButton.config(state=DISABLED)

		self.generate = Button(self, text="Generate Data",command=self.genData)
		self.generate.place(x=10, y=250)

	def browser(self):
		import webbrowser
		webbrowser.get('firefox').open('data/index.html')
		self.browserButton.config(state=DISABLED)

	def getDir(self):
		globals.dir = tkFileDialog.askdirectory(parent=self.parent,initialdir="/",title='Select a directory')
		self.selpath['text'] = globals.dir
		#print globals.dir

	#validate and process data
	def genData(self):
		valid = True
		try:
			globals.alpha = float(self.aEntry.get())
		except ValueError:
			globals.alpha = 0.0
			valid = False
		try:
			globals.beta = float(self.bEntry.get())
		except ValueError:
			globals.beta = 0.0
			valid = False

		if not os.path.isdir(globals.dir) or globals.alpha>=1.0 or globals.beta>=1.0:
			valid = False

		if valid:
			self.generate.config(state=DISABLED)
			from compute import main as computeMain
			computeMain()
			from jsonutil import main as jsonMain
			jsonMain()
			self.browserButton.config(state=NORMAL)
			self.generate.config(state=NORMAL)
Пример #25
0
class CHEWDDialog(ModelessDialog):
    name = "Energy Visualizer"
    buttons = ("Apply", "Close")
    help = ("Energy.html", CHEWD)
    title = "CHemical Energy Wise Decomposition"

    def fillInUI(self, parent):

        #parent.resizable(0, 0)
        frame4 = Frame(parent)
        frame4.grid(row=0, column=0, sticky="nsew")
        self.wat = IntVar()
        self.wat.set(1)
        self.waterswap = Checkbutton(frame4,
                                     text="Water Swap",
                                     command=self.optionws,
                                     variable=self.wat)
        self.waterswap.grid(row=0, column=0)
        self.lig = IntVar()
        self.lig.set(0)
        self.ligandswap = Checkbutton(frame4,
                                      text="Ligand Swap",
                                      command=self.optionls,
                                      variable=self.lig)
        self.ligandswap.grid(row=0, column=1)
        self.mm = IntVar()
        self.mm.set(0)
        self.mmpbsa = Checkbutton(frame4,
                                  text="MMPBSA",
                                  command=self.optionmm,
                                  variable=self.mm)
        self.mmpbsa.grid(row=0, column=2)

        frame1 = Frame(parent)
        frame1.grid(row=1, column=0, sticky="nsew")
        lbl1 = Label(frame1, text="Log file folder", width=12)
        lbl1.grid(row=0, column=0)
        self.entry1 = Entry(frame1)
        self.entry1.grid(row=0, column=1, columnspan=4, sticky=W + E)
        self.browserButton = Button(frame1,
                                    text="Browser",
                                    command=self.onOpen)
        self.browserButton.grid(row=0, column=5, sticky="e")

        lbl2 = Label(frame1, text="MMPBSA log file", width=12)
        lbl2.grid(row=1, column=0)
        self.entry2 = Entry(frame1, state=DISABLED)
        self.entry2.grid(row=1, column=1, columnspan=4, sticky=W + E)
        self.browserButtonMM = Button(frame1,
                                      text="Browser",
                                      command=self.onOpenMM,
                                      state=DISABLED)
        self.browserButtonMM.grid(row=1, column=5, sticky="e")

        lbl3 = Label(frame1, text="MMPBSA PDB file", width=12)
        lbl3.grid(row=2, column=0)
        self.entry3 = Entry(frame1, state=DISABLED)
        self.entry3.grid(row=2, column=1, columnspan=4, sticky=W + E)
        self.browserButtonPDB = Button(frame1,
                                       text="Browser",
                                       command=self.onOpenPDB,
                                       state=DISABLED)
        self.browserButtonPDB.grid(row=2, column=5, sticky="e")

        lbl4 = Label(frame1, text="Ligand Name", width=12)
        lbl4.grid(row=3, column=0)
        self.entry4 = Entry(frame1)
        self.entry4.grid(row=3, column=1)
        self.lblswap = Label(frame1,
                             text="Swap Ligand",
                             width=12,
                             state=DISABLED)
        self.lblswap.grid(row=3, column=2)
        self.swapentry = Entry(frame1, state=DISABLED)
        self.swapentry.grid(row=3, column=3)
        self.l1v = IntVar()
        self.l1v.set(1)
        self.lig1ck = Checkbutton(frame1,
                                  text="Ligand 1",
                                  command=self.changelig1,
                                  state=DISABLED,
                                  variable=self.l1v)
        self.lig1ck.grid(row=4, column=0)
        self.l2v = IntVar()
        self.l2v.set(0)
        self.lig2ck = Checkbutton(frame1,
                                  text="Ligand 2",
                                  command=self.changelig2,
                                  state=DISABLED,
                                  variable=self.l2v)
        self.lig2ck.grid(row=4, column=2)
        lbl5 = Label(frame1, text="Display Radius", width=12)
        lbl5.grid(row=5, column=0)
        self.entry5 = Entry(frame1)
        self.entry5.grid(row=5, column=1)
        self.entry5.insert(0, "5.0")
        self.sv = IntVar()
        self.sv.set(0)
        self.surface = Checkbutton(frame1,
                                   text="View Surface",
                                   command=self.viewsurface,
                                   variable=self.sv)
        self.surface.grid(row=5, column=2)
        self.vl = IntVar()
        self.vl.set(1)
        self.label = Checkbutton(frame1,
                                 text="View Label",
                                 command=self.viewlabel,
                                 variable=self.vl)
        self.label.grid(row=5, column=3)

        lbl6 = Label(frame1, text="Min Value", width=12)
        lbl6.grid(row=6, column=0)
        self.entry6 = Entry(frame1)
        self.entry6.grid(row=6, column=1)
        self.entry6.insert(0, "-5")
        lbl7 = Label(frame1, text="Max Value", width=12)
        lbl7.grid(row=6, column=2)
        self.entry7 = Entry(frame1)
        self.entry7.grid(row=6, column=3)
        self.entry7.insert(0, "+5")

        lbl8 = Label(frame1, text="Starting log file", width=12)
        lbl8.grid(row=7, column=0)
        self.entry8 = Entry(frame1)
        self.entry8.grid(row=7, column=1)
        self.entry8.insert(0, "400")
        lbl9 = Label(frame1, text="Ending log file", width=12)
        lbl9.grid(row=7, column=2)
        self.entry9 = Entry(frame1)
        self.entry9.grid(row=7, column=3)
        self.entry9.insert(0, "1000")

        frame2 = Frame(parent)
        frame2.grid(row=2, column=0, sticky="nsew")
        self.vsb = Scrollbar(frame2, orient="vertical", command=self.OnVsb)
        self.vsb.grid(row=1, column=3, sticky="ns")
        self.lb1 = Listbox(frame2, yscrollcommand=self.vsb.set)
        self.lb1.grid(row=1, column=0)
        self.lb2 = Listbox(frame2, yscrollcommand=self.vsb.set)
        self.lb2.grid(row=1, column=1)
        self.lb3 = Listbox(frame2, yscrollcommand=self.vsb.set)
        self.lb3.grid(row=1, column=2)

        self.b1 = Button(frame2,
                         text="Residue Number",
                         state=DISABLED,
                         command=lambda: self.sortdata(0))
        self.b1.grid(row=0, column=0, sticky=W + E)
        self.b2 = Button(frame2,
                         text="Residue Name",
                         state=DISABLED,
                         command=lambda: self.sortdata(1))
        self.b2.grid(row=0, column=1, sticky=W + E)
        self.b3 = Button(frame2,
                         text="Energy Value",
                         state=DISABLED,
                         command=lambda: self.sortdata(2))
        self.b3.grid(row=0, column=2, sticky=W + E)

        self.lb1.bind("<<ListboxSelect>>", self.OnSelect)
        self.lb1.bind("<MouseWheel>", self.OnMouseWheel)
        self.lb2.bind("<<ListboxSelect>>", self.OnSelect)
        self.lb2.bind("<MouseWheel>", self.OnMouseWheel)
        self.lb3.bind("<<ListboxSelect>>", self.OnSelect)
        self.lb3.bind("<MouseWheel>", self.OnMouseWheel)

        frame3 = Frame(parent)
        frame3.grid(row=3, column=0, sticky="nsew")

        self.previous = Button(frame3,
                               text="Previous Frame",
                               state=DISABLED,
                               command=self.prevframe)
        self.previous.grid(row=0, column=0, sticky=W + E)
        self.scale = Scale(frame3,
                           command=self.onScale,
                           state=DISABLED,
                           orient=HORIZONTAL,
                           length=320,
                           showvalue=0)
        self.scale.grid(row=0, column=1, sticky=W + E)
        self.next = Button(frame3,
                           text="Next Frame",
                           state=DISABLED,
                           command=self.nextframe)
        self.next.grid(row=0, column=2, sticky=W + E)

        self.var = IntVar()
        v = 000
        self.var.set(v)
        self.label = Label(frame3, text=0, textvariable=self.var)
        self.label.grid(row=0, column=3)

        ToolTip(lbl1, "Load the result directory of Sire Analysis")
        ToolTip(self.browserButton,
                "Load the result directory of Sire Analysis")
        ToolTip(lbl4, "Enter the name of the Ligand in your coordinate file")
        ToolTip(
            lbl5,
            "The radially distributed zone around ligand you want to be displayed"
        )
        ToolTip(
            lbl6,
            "Minimum scale value for the color distribution and it will be treated as blue"
        )
        ToolTip(
            lbl7,
            "Maximum scale value for the color distribution and it will be treated as red"
        )

    def viewlabel(self):
        if (load > 0):
            if (self.wat.get() == 1):
                CHEWD.togglelabelws(self.vl.get(), str(self.scale.get()),
                                    self.entry4.get(), self.entry5.get())
            elif (self.lig.get() == 1):
                if (self.l1v.get() == 1):
                    vl = self.entry4.get()
                    hl = self.swapentry.get()
                if (self.l2v.get() == 1):
                    vl = self.swapentry.get()
                    hl = self.entry4.get()
                CHEWD.togglelabells(self.vl.get(), str(self.scale.get()), vl,
                                    self.entry5.get(), hl)
            elif (self.mm.get() == 1):
                CHEWD.togglelabelws(self.vl.get(), "0", self.entry4.get(),
                                    self.entry5.get())

    def viewsurface(self):
        if (load > 0):
            CHEWD.togglesurface(self.sv.get())

    def optionws(self):
        if (self.wat.get() == 1):
            self.lig.set(0)
            self.mm.set(0)
            self.entry1.config(state="normal")
            self.browserButton.config(state="normal")
            self.swapentry.config(state=DISABLED)
            self.lig1ck.config(state=DISABLED)
            self.lig2ck.config(state=DISABLED)
            self.lblswap.config(state=DISABLED)
            self.entry2.config(state=DISABLED)
            self.entry3.config(state=DISABLED)
            self.browserButtonMM.config(state=DISABLED)
            self.browserButtonPDB.config(state=DISABLED)
        else:
            self.wat.set(0)
            self.lig.set(1)
            self.mm.set(0)
            self.swapentry.config(state="normal")
            self.lig1ck.config(state="normal")
            self.lig2ck.config(state="normal")
            self.lblswap.config(state="normal")
            self.entry1.config(state="normal")
            self.browserButton.config(state="normal")
            self.entry2.config(state=DISABLED)
            self.entry3.config(state=DISABLED)
            self.browserButtonMM.config(state=DISABLED)
            self.browserButtonPDB.config(state=DISABLED)

    def optionls(self):
        if (self.lig.get() == 1):
            self.wat.set(0)
            self.mm.set(0)
            self.swapentry.config(state="normal")
            self.lig1ck.config(state="normal")
            self.lig2ck.config(state="normal")
            self.lblswap.config(state="normal")
            self.entry1.config(state="normal")
            self.browserButton.config(state="normal")
            self.entry2.config(state=DISABLED)
            self.entry3.config(state=DISABLED)
            self.browserButtonMM.config(state=DISABLED)
            self.browserButtonPDB.config(state=DISABLED)
        else:
            self.lig.set(0)
            self.mm.set(0)
            self.wat.set(1)
            self.entry1.config(state="normal")
            self.browserButton.config(state="normal")
            self.swapentry.config(state=DISABLED)
            self.lig1ck.config(state=DISABLED)
            self.lig2ck.config(state=DISABLED)
            self.lblswap.config(state=DISABLED)
            self.entry2.config(state=DISABLED)
            self.entry3.config(state=DISABLED)
            self.browserButtonMM.config(state=DISABLED)
            self.browserButtonPDB.config(state=DISABLED)

    def optionmm(self):
        if (self.mm.get() == 1):
            self.lig.set(0)
            self.wat.set(0)
            self.swapentry.config(state=DISABLED)
            self.lig1ck.config(state=DISABLED)
            self.lig2ck.config(state=DISABLED)
            self.lblswap.config(state=DISABLED)
            self.entry8.config(state=DISABLED)
            self.entry9.config(state=DISABLED)
            self.entry1.config(state=DISABLED)
            self.browserButton.config(state=DISABLED)
            self.entry2.config(state="normal")
            self.entry3.config(state="normal")
            self.browserButtonMM.config(state="normal")
            self.browserButtonPDB.config(state="normal")
        else:
            self.wat.set(1)
            self.lig.set(0)
            self.mm.set(0)
            self.entry8.config(state="normal")
            self.entry9.config(state="normal")
            self.entry1.config(state="normal")
            self.browserButton.config(state="normal")
            self.entry2.config(state=DISABLED)
            self.entry3.config(state=DISABLED)
            self.browserButtonMM.config(state=DISABLED)
            self.browserButtonPDB.config(state=DISABLED)

    def changelig1(self):
        if (self.l1v.get() == 1):
            self.l2v.set(0)
        else:
            self.l2v.set(1)
        if (load > 0):
            if (self.l1v.get() == 1):
                vl = self.entry4.get()
                hl = self.swapentry.get()
            if (self.l2v.get() == 1):
                vl = self.swapentry.get()
                hl = self.entry4.get()
            CHEWD.lsupdateview(vl, self.entry5.get(), self.entry6.get(),
                               self.entry7.get(), prevz, str(self.scale.get()),
                               hl, self.vl.get())

    def changelig2(self):
        if (self.l2v.get() == 1):
            self.l1v.set(0)
        else:
            self.l1v.set(1)
        if (load > 0):
            if (self.l1v.get() == 1):
                vl = self.entry4.get()
                hl = self.swapentry.get()
            if (self.l2v.get() == 1):
                vl = self.swapentry.get()
                hl = self.entry4.get()
            CHEWD.lsupdateview(vl, self.entry5.get(), self.entry6.get(),
                               self.entry7.get(), prevz, str(self.scale.get()),
                               hl, self.vl.get())

    def loadmmpbsaresults(self):
        fp = open(self.entry2.get(), "r")
        resv = list()
        for line in fp:
            t = line.split(',')
            t2 = t[0].split()
            if (len(t) == 20 and len(t2) == 2 and t2[0] != self.entry4.get()):
                resv.append([int(t2[1]), float(t[17]), t2[0]])
            matchObj = re.match(r'Sidechain Energy Decomposition:', line,
                                re.M | re.I)
            if matchObj:
                break
        self.lb1.delete(0, END)
        self.lb2.delete(0, END)
        self.lb3.delete(0, END)
        x = len(resv)
        for i in range(x):
            self.lb1.insert(END, resv[i][0])
            self.lb2.insert(END, resv[i][2])
            self.lb3.insert(END, resv[i][1])
        fp = open(tempfile.gettempdir() + "/temp.txt", "w")
        fc = open(tempfile.gettempdir() + "/clear.txt", "w")
        fp.write("attribute: sireEnergy\n")
        fp.write("recipient: residues\n")
        fc.write("attribute: sireEnergy\n")
        fc.write("recipient: residues\n")
        for i in range(x):
            fp.write("\t:" + str(resv[i][0]) + "\t" + str(resv[i][1]) + "\n")
            fc.write("\t:" + str(resv[i][0]) + "\t0.0\n")
        fp.close()
        fc.close()
        self.b1.config(state="normal")
        self.b2.config(state="normal")
        self.b3.config(state="normal")

    def changestate(self):
        x = list()
        tempx = list()
        if (self.wat.get() == 1):
            base = os.listdir(self.entry1.get())
        else:
            base = os.listdir(self.entry1.get() + "/")
        for a in base:
            if a.endswith(".log"):
                tempx.append(a)
        tempx.sort()
        tlen = len(tempx)
        ia = int(self.entry8.get()) - 1
        while (ia <= int(self.entry9.get()) and ia < tlen):
            x.append(tempx[ia])
            ia += 1
        resv = list()
        c = 0
        i = 0
        for fn in x:
            if (self.wat.get() == 1):
                fp = open(self.entry1.get() + "/" + fn, "r")
            else:
                fp = open(self.entry1.get() + "/" + fn, "r")
            if (c == 0):
                for line in fp:
                    t = line.split()
                    if (len(t) == 8):
                        if (t[0] == "Residue("):
                            resv.append([int(t[3]), float(t[5]), t[1]])
                    if (line == "PROTEIN BOX WATER FREE ENERGY COMPONENTS\n"):
                        c = c + 1
                        i = 0
                        break
            else:
                for line in fp:
                    t = line.split()
                    if (len(t) == 8):
                        if (t[0] == "Residue("):
                            resv[i][1] = resv[i][1] + float(t[5])
                            i = i + 1
                    if (line == "PROTEIN BOX WATER FREE ENERGY COMPONENTS\n"):
                        c = c + 1
                        i = 0
                        break
            fp.close()
        x = len(resv)
        self.lb1.delete(0, END)
        self.lb2.delete(0, END)
        self.lb3.delete(0, END)
        for i in range(x):
            resv[i][1] = resv[i][1] / c
        for i in range(x):
            self.lb1.insert(END, resv[i][0])
            self.lb2.insert(END, resv[i][2])
            self.lb3.insert(END, round(resv[i][1], 3))

        fp = open(tempfile.gettempdir() + "/temp.txt", "w")
        fc = open(tempfile.gettempdir() + "/clear.txt", "w")
        fp.write("attribute: sireEnergy\n")
        fp.write("recipient: residues\n")
        fc.write("attribute: sireEnergy\n")
        fc.write("recipient: residues\n")
        for i in range(x):
            fp.write("\t:" + str(resv[i][0]) + "\t" + str(resv[i][1]) + "\n")
            fc.write("\t:" + str(resv[i][0]) + "\t0.0\n")
        fp.close()
        fc.close()
        self.b1.config(state="normal")
        self.b2.config(state="normal")
        self.b3.config(state="normal")

    def prevframe(self):
        global prevz, load
        if (load > 0):
            self.scale.set(self.scale.get() - 1)

    def nextframe(self):
        global prevz, load
        if (load > 0):
            self.scale.set(self.scale.get() + 1)

    def onScale(self, val):
        global prevz, load
        if (load > 0):
            v = self.lig1pdb[int(float(val))][14:19]
            self.var.set(v)
            if (self.scale.get() == 0):
                self.previous.config(state=DISABLED)
            if (self.scale.get() == len(self.lig1pdb) - 2):
                self.next.config(state="normal")
            if (self.scale.get() == 1):
                self.previous.config(state="normal")
            if (self.scale.get() == len(self.lig1pdb) - 1):
                self.next.config(state=DISABLED)
            if (self.wat.get() == 1):
                CHEWD.wsupdateview(self.entry4.get(), self.entry5.get(),
                                   self.entry6.get(), self.entry7.get(), prevz,
                                   str(self.scale.get()), self.vl.get())
            elif (self.lig.get() == 1):
                if (self.l1v.get() == 1):
                    vl = self.entry4.get()
                    hl = self.swapentry.get()
                if (self.l2v.get() == 1):
                    vl = self.swapentry.get()
                    hl = self.entry4.get()
                CHEWD.lsupdateview(vl, self.entry5.get(), self.entry6.get(),
                                   self.entry7.get(), prevz,
                                   str(self.scale.get()), hl, self.vl.get())

    def OnSelect(self, val):
        global prev
        sender = val.widget
        idx = sender.curselection()
        dis = self.lb1.get(idx)
        if (self.wat.get() == 1):
            CHEWD.wslistdisplay(self.entry4.get(), self.entry5.get(), prev,
                                dis, str(self.scale.get()), self.vl.get())
        elif (self.lig.get() == 1):
            if (self.l1v.get() == 1):
                vl = self.entry4.get()
                hl = self.swapentry.get()
            if (self.l2v.get() == 1):
                vl = self.swapentry.get()
                hl = self.entry4.get()
            CHEWD.lslistdisplay(vl, self.entry5.get(), prev, dis,
                                str(self.scale.get()), hl, self.vl.get())
        elif (self.mm.get() == 1):
            CHEWD.mmlistdisplay(self.entry4.get(), self.entry5.get(), prev,
                                dis, "0", self.vl.get())
        prev = dis

    def sortdata(self, sc):
        global dr1, dr2, dr3
        tableData1 = self.lb1.get(0, END)
        tableData2 = self.lb2.get(0, END)
        tableData3 = self.lb3.get(0, END)

        data = list()
        nv = len(tableData1)
        for x in range(nv):
            data.append([tableData1[x], tableData2[x], tableData3[x]])

        if (sc == 0):
            lab = self.b1.cget('text')
            if lab[0] == '[': self.b1.config(text=lab[4:])
            lab = self.b2.cget('text')
            if lab[0] == '[': self.b2.config(text=lab[4:])
            lab = self.b3.cget('text')
            if lab[0] == '[': self.b3.config(text=lab[4:])
            lab = self.b1.cget('text')
            if dr1 == 1: self.b1.config(text='[+] ' + lab)
            else: self.b1.config(text='[-] ' + lab)
            data.sort(key=lambda s: (s[sc]), reverse=dr1 == 1)
            dr1 = dr1 * -1
        if (sc == 1):
            lab = self.b1.cget('text')
            if lab[0] == '[': self.b1.config(text=lab[4:])
            lab = self.b2.cget('text')
            if lab[0] == '[': self.b2.config(text=lab[4:])
            lab = self.b3.cget('text')
            if lab[0] == '[': self.b3.config(text=lab[4:])
            lab = self.b2.cget('text')
            if dr2 == 1: self.b2.config(text='[+] ' + lab)
            else: self.b2.config(text='[-] ' + lab)
            data.sort(key=lambda s: (s[sc]), reverse=dr2 == 1)
            dr2 = dr2 * -1
        if (sc == 2):
            lab = self.b1.cget('text')
            if lab[0] == '[': self.b1.config(text=lab[4:])
            lab = self.b2.cget('text')
            if lab[0] == '[': self.b2.config(text=lab[4:])
            lab = self.b3.cget('text')
            if lab[0] == '[': self.b3.config(text=lab[4:])
            lab = self.b3.cget('text')
            if dr3 == 1: self.b3.config(text='[+] ' + lab)
            else: self.b3.config(text='[-] ' + lab)
            data.sort(key=lambda s: (s[sc]), reverse=dr3 == 1)
            dr3 = dr3 * -1
        nv = len(data)
        self.lb1.delete(0, 'end')
        self.lb2.delete(0, 'end')
        self.lb3.delete(0, 'end')
        for x in range(nv):
            self.lb1.insert(END, data[x][0])
            self.lb2.insert(END, data[x][1])
            self.lb3.insert(END, data[x][2])

    def onOpen(self):
        global load
        fold = tkFileDialog.askdirectory()
        self.entry1.delete(0, 'end')
        self.entry1.insert(0, fold)
        load = 0

    def onOpenMM(self):
        global load
        fold = tkFileDialog.askopenfilename()
        self.entry2.delete(0, 'end')
        self.entry2.insert(0, fold)
        load = 0

    def onOpenPDB(self):
        global load
        fold = tkFileDialog.askopenfilename()
        self.entry3.delete(0, 'end')
        self.entry3.insert(0, fold)
        load = 0

    def OnVsb(self, *args):
        self.lb1.yview(*args)
        self.lb2.yview(*args)
        self.lb3.yview(*args)

    def OnMouseWheel(self, event):
        self.lb1.yview("scroll", event.delta, "units")
        self.lb2.yview("scroll", event.delta, "units")
        self.lb3.yview("scroll", event.delta, "units")
        return "break"

    def Apply(self):
        global load, prevz
        if (load == 0):

            if (self.wat.get() == 1 or self.lig.get() == 1):
                self.changestate()
                self.base = os.listdir(self.entry1.get())
                pdb1 = list()
                for a in self.base:
                    matchObj = re.match(r'bound_mobile_\d{6}_0\.\d{5}\.pdb', a,
                                        re.M | re.I)
                    if matchObj:
                        pdb1.append(a)
                self.lig1pdb = list()
                self.lig2pdb = list()
                #print x
                x = pdb1[1][22:27]

                for a in pdb1:

                    matchObj = re.match(r'bound_mobile_\d{6}_0\.' + x + '.pdb',
                                        a, re.M | re.I)
                    if matchObj:
                        self.lig1pdb.append(a)
                    else:
                        self.lig2pdb.append(a)
                self.lig1pdb.sort()
                self.lig2pdb.sort()
                self.scale.configure(from_=0, to=len(self.lig1pdb) - 1)
                self.scale.config(state="normal")

            elif (self.mm.get() == 1):
                self.loadmmpbsaresults()
                CHEWD.mmloadpdb(self.entry3.get())
                CHEWD.mmvisualizer("0", tempfile.gettempdir(),
                                   self.entry4.get(), self.entry5.get(),
                                   self.entry6.get(), self.entry7.get(),
                                   self.vl.get())

            if (self.wat.get() == 1):
                CHEWD.wsloadallpdb(self.lig1pdb, self.entry1.get())
                self.next.config(state="normal")
                v = self.lig1pdb[0][14:19]
                self.var.set(v)
                CHEWD.wsvisualizer(str(self.scale.get()),
                                   tempfile.gettempdir(), self.entry4.get(),
                                   self.entry5.get(), self.entry6.get(),
                                   self.entry7.get(), self.vl.get())
            elif (self.lig.get() == 1):
                if (self.l1v.get() == 1):
                    vl = self.entry4.get()
                    hl = self.swapentry.get()
                if (self.l2v.get() == 1):
                    vl = self.swapentry.get()
                    hl = self.entry4.get()
                CHEWD.wsloadallpdb(self.lig1pdb, self.entry1.get())
                self.next.config(state="normal")
                v = self.lig1pdb[0][14:19]
                self.var.set(v)
                CHEWD.lsvisualizer(str(self.scale.get()),
                                   tempfile.gettempdir(), vl,
                                   self.entry5.get(), self.entry6.get(),
                                   self.entry7.get(), hl, self.vl.get())
            load = 1

        else:

            if (self.wat.get() == 1):
                self.changestate()
                CHEWD.clear(tempfile.gettempdir())
                CHEWD.loadresults(tempfile.gettempdir())
                CHEWD.wsupdateview(self.entry4.get(), self.entry5.get(),
                                   self.entry6.get(), self.entry7.get(), prevz,
                                   str(self.scale.get()), self.vl.get())
            elif (self.lig.get() == 1):
                self.changestate()
                if (self.l1v.get() == 1):
                    vl = self.entry4.get()
                    hl = self.swapentry.get()
                if (self.l2v.get() == 1):
                    vl = self.swapentry.get()
                    hl = self.entry4.get()

                CHEWD.clear(tempfile.gettempdir())
                CHEWD.loadresults(tempfile.gettempdir())
                CHEWD.lsupdateview(vl, self.entry5.get(), self.entry6.get(),
                                   self.entry7.get(), prevz,
                                   str(self.scale.get()), hl, self.vl.get())
            elif (self.mm.get() == 1):
                CHEWD.mmupdateview(self.entry4.get(), self.entry5.get(),
                                   self.entry6.get(), self.entry7.get(), prevz,
                                   "0", self.vl.get())
        prevz = self.entry5.get()
Пример #26
0
class Metadator(Tk):
    def __init__(self):
        u"""
        Main window constructor
        Creates 1 frame and 2 labeled subframes
        """
        # first: the log
        # see: http://sametmax.com/ecrire-des-logs-en-python/
        self.logger = logging.getLogger()
        self.logger.setLevel(logging.DEBUG)  # all errors will be get
        log_form = logging.Formatter('%(asctime)s || %(levelname)s || %(message)s')
        logfile = RotatingFileHandler('Metadator_LOG.log', 'a', 5000000, 1)
        logfile.setLevel(logging.DEBUG)
        logfile.setFormatter(log_form)
        self.logger.addHandler(logfile)
        self.logger.info('\n\t ======== Metadator ========')  # first messages
        self.logger.info('Starting the UI')

        # checking the path to GDAL in the path
        if "GDAL_DATA" not in env.keys():
            try:
                gdal.SetConfigOption(str('GDAL_DATA'),
                                     str(path.abspath(r'data/gdal')))
            except:
                print("Oups! Something has gone wrong...\
                      see: https://github.com/Guts/Metadator/issues/21")
        else:
            pass

        # basics settings
        Tk.__init__(self)           # constructor of parent graphic class
        self.title(u'Metadator {0}'.format(MetadatorVersion))
        self.style = Style()        # more friendly windows style
        if opersys == 'win32':
            self.logger.info('Op. system: {0}'.format(platform.platform()))
            self.iconbitmap('Metadator.ico')    # windows icon
            self.uzer = env.get(u'USERNAME')
        elif opersys == 'linux2':
            self.logger.info('Op. system: {0}'.format(platform.platform()))
            self.uzer = env.get(u'USER')
            icon = Image("photo", file=r'data/img/metadator.gif')
            self.call('wm', 'iconphoto', self._w, icon)
            self.minsize(580, 100)
            self.style.theme_use('clam')
        elif opersys == 'darwin':
            self.logger.info('Op. system: {0}'.format(platform.platform()))
            self.uzer = env.get(u'USER')
        else:
            self.logger.warning('Operating system not tested')
            self.logger.info('Op. system: {0}'.format(platform.platform()))
        self.resizable(width=False, height=False)
        self.focus_force()

        self.logger.info('GDAL version: {}'.format(gdal.__version__))

        # variables
        self.def_rep = ""       # folder to search for
        self.def_lang = 'FR'    # language to start
        self.def_doc = IntVar()     # to export into Word
        self.def_xls = IntVar()     # to export into Excel 2003
        self.def_xml = IntVar()     # to export into ISO 19139
        self.def_cat = IntVar()     # to merge all output Word files
        self.def_odt = IntVar()     # to export into OpenDocumentText
        self.def_dict = IntVar()    # to make a dictionnary of data
        self.def_kass = IntVar()    # to handle field name case sensitive
        self.def_stat = IntVar()    # to active/disable stats fields
        self.li_pro = []            # list for profiles in language selected
        self.li_shp = []            # list for shapefiles path
        self.li_tab = []            # list for MapInfo tables path
        self.num_folders = 0        # number of folders explored
        self.today = strftime("%Y-%m-%d")   # date of the day
        self.dico_layer = OD()      # dictionary about layer properties
        self.dico_profil = OD()     # dictionary from profile selected
        self.dico_fields = OD()     # dictionary for fields information
        self.dico_rekur = OD()      # dictionary of recurring attributes
        self.dico_err = OD()     # errors list
        self.dico_help = OD()                # dictionary of help texts
        li_lang = [lg for lg in listdir(r'locale')]   # available languages
        self.blabla = OD()      # texts dictionary

        # GUI fonts
        ft_tit = tkFont.Font(family="Times", size=10, weight=tkFont.BOLD)

        # fillfulling
        self.load_settings()
        self.load_texts(self.def_lang)
        self.li_profiles(self.def_lang)
        self.li_rekurs(self.def_lang)
        self.recup_help(self.def_lang)

        # Tabs
        self.nb = Notebook(self)
        self.tab_globals = Frame(self.nb)   # tab_id = 0
        self.tab_options = Frame(self.nb)   # tab_id = 1
        self.tab_attribs = Frame(self.nb)   # tab_id = 2
        self.nb.add(self.tab_globals,
                    text=self.blabla.get('gui_tab1'), padding=3)
        self.nb.add(self.tab_options,
                    text=self.blabla.get('gui_tab2'), padding=3)
        self.nb.add(self.tab_attribs,
                    text=self.blabla.get('gui_tab3'), padding=3)
        self.logger.info('UI created')

                ### Tab 1: global
        # Frames
        self.FrPath = Labelframe(self.tab_globals,
                                 name='main',
                                 text=self.blabla.get('tab1_fr1'))
        self.FrProg = Labelframe(self.tab_globals,
                                 name='progression',
                                 text=self.blabla.get('tab1_frprog'))
            ## Frame 1
        # target folder
        self.labtarg = Label(self.FrPath, text=self.blabla.get('tab1_path'))
        self.target = Entry(self.FrPath, width=25)
        self.browsetarg = Button(self.FrPath,       # browse button
                                 text=self.blabla.get('tab1_browse'),
                                 command=lambda: self.setpathtarg(),
                                 takefocus=True)
        self.browsetarg.focus_force()               # force the focus on
        self.profil = Label(self.FrPath, text=self.blabla.get('tab1_prof'))
        # profiles switcher
        self.ddl_profil = Combobox(self.FrPath, values=self.li_pro, width=5)
        self.ddl_profil.current(0)
        self.ddl_profil.bind("<<ComboboxSelected>>", self.select_profil)
        # widgets placement
        self.labtarg.grid(row=1, column=1, columnspan=1,
                          sticky=N + S + W + E, padx=2, pady=8)
        self.target.grid(row=1, column=2, columnspan=1,
                         sticky=N + S + W + E, padx=2, pady=8)
        self.browsetarg.grid(row=1, column=3,
                             sticky=N + S + W + E, padx=2, pady=8)
        self.profil.grid(row=2, column=1,
                         sticky=N + S + W + E, padx=2, pady=8)
        self.ddl_profil.grid(row=2, column=2, sticky=W + E + N + S,
                             columnspan=2, padx=2, pady=8)

        # tooltips
        InfoBulle(self.target, message=self.dico_help.get(30)[1])
        InfoBulle(self.browsetarg, message=self.dico_help.get(30)[1])
        InfoBulle(self.ddl_profil, message=self.dico_help.get(31)[1])

            ## Frame 2
        # variables
        self.status = StringVar(self.FrProg, '')
        # widgets
        self.prog_layers = Progressbar(self.FrProg, orient="horizontal")
        self.prog_fields = Progressbar(self.FrProg, orient="horizontal")
        # widgets placement
        Label(self.FrProg, textvariable=self.status,
                           foreground='DodgerBlue').pack(expand=1)
        self.prog_layers.pack(expand=1, fill=X)

        # Frames placement
        self.FrPath.pack(expand=1, fill='both')
        self.FrProg.pack(expand=1, fill='both')

                ### Tab 2: options
        # Export options
        caz_doc = Checkbutton(self.tab_options,
                              text=u'HTML / Word (.doc/.docx)',
                              variable=self.def_doc,
                              command=lambda: self.catalog_dependance())
        caz_xls = Checkbutton(self.tab_options,
                              text=u'Excel 2003 (.xls)',
                              variable=self.def_xls)
        caz_xml = Checkbutton(self.tab_options,
                              text=u'XML (ISO 19139)',
                              variable=self.def_xml)
        self.caz_cat = Checkbutton(self.tab_options,
                                   text=self.blabla.get('tab2_merge'),
                                   variable=self.def_cat)
        caz_odt = Checkbutton(self.tab_options,
                              text=u'Open Document Text (.odt)',
                              variable=self.def_odt)
        # widgets placement
        caz_doc.grid(row=1,
                     column=0,
                     sticky=N + S + W + E,
                     padx=2, pady=2)
        self.caz_cat.grid(row=2,
                          column=0,
                          sticky=N + S + W + E,
                          padx=2, pady=2)
        caz_xls.grid(row=1,
                     column=1,
                     sticky=N + S + W + E,
                     padx=2, pady=2)
        caz_xml.grid(row=2,
                     column=1,
                     sticky=N + S + W + E,
                     padx=2, pady=2)
        caz_odt.grid(row=3,
                     column=1,
                     sticky=N + S + W + E,
                     padx=2, pady=2)
        # disabling the widgets which work only on Windows OS
        if opersys != 'win32':
            self.logger.info('Disabling Windows reserved functions.')
            self.def_doc.set(0)
            self.def_cat.set(0)
            caz_doc.configure(state='disabled')
            self.caz_cat.configure(state='disabled')
        else:
            pass
        # make the catalog option depending on the Word option
        self.catalog_dependance()

        # tooltips
        InfoBulle(caz_doc,
                  message=self.dico_help.get(33)[1],
                  image=self.dico_help.get(33)[2])
        InfoBulle(caz_xls,
                  message=self.dico_help.get(34)[1],
                  image=self.dico_help.get(34)[2])
        InfoBulle(caz_xml,
                  message=self.dico_help.get(35)[1],
                  image=self.dico_help.get(35)[2])
        InfoBulle(caz_odt,
                  message=self.dico_help.get(36)[1],
                  image=self.dico_help.get(36)[2])
        InfoBulle(self.caz_cat,
                  message=self.dico_help.get(37)[1],
                  image=self.dico_help.get(37)[2])

                ### Tab 3: recurring attributes
        # Attribute selector
        self.lab_chps = Label(self.tab_attribs, text=self.blabla.get('tab3_sele'))
        self.ddl_attr = Combobox(self.tab_attribs, values=self.dico_rekur.keys())
        self.ddl_attr.bind("<<ComboboxSelected>>", self.edit_rekur)
        self.supr = Button(self.tab_attribs, text=self.blabla.get('tab3_supp'),
                           command=self.del_rekur)
        # frame
        self.FrRekur = Labelframe(self.tab_attribs,
                                  name='attributes',
                                  text=self.blabla.get('tab3_tit'))
        # attribute settings
        self.tab3_LBnom = Label(self.FrRekur,
                                text=self.blabla.get('tab3_nom'),
                                state=DISABLED)
        self.tab3_ENnom = Entry(self.FrRekur, state=DISABLED)
        self.tab3_LBdesc = Label(self.FrRekur,
                                 text=self.blabla.get('tab3_desc'),
                                 state=DISABLED)
        self.tab3_TXdesc = Text(self.FrRekur,
                                height=5, width=30,
                                wrap=WORD, state=DISABLED)
        self.tab3_CBcass = Checkbutton(self.FrRekur,
                                       text=self.blabla.get('tab3_cass'),
                                       variable=self.def_kass,
                                       state=DISABLED)
        self.tab3_CBstat = Checkbutton(self.FrRekur,
                                       text=self.blabla.get('tab3_stat'),
                                       variable=self.def_stat,
                                       state=DISABLED)
        # Validation button
        self.save = Button(self.FrRekur,
                           text=self.blabla.get('tab3_save'),
                           command=self.save_rekur,
                           state='disabled')

        # widgets placement
        self.lab_chps.grid(row=1, column=1, sticky=N + S + W,
                           padx=2, pady=2)
        self.ddl_attr.grid(row=1, column=2, sticky=N + S + W + E,
                           padx=2, pady=2)
        self.supr.grid(row=1, column=3, sticky=N + S + W + E,
                       padx=2, pady=2)
        self.tab3_LBnom.grid(row=1, column=0, columnspan=1,
                             sticky=N + S + W, padx=2, pady=2)
        self.tab3_ENnom.grid(row=1, column=1, columnspan=1,
                             sticky=N + S + W + E, padx=2, pady=2)
        self.tab3_LBdesc.grid(row=2, column=0, columnspan=1,
                              sticky=N + S + W + E, padx=2, pady=2)
        self.tab3_TXdesc.grid(row=2, column=1, columnspan=2,
                              sticky=N + S + W + E, padx=2, pady=2)
        self.tab3_CBcass.grid(row=3, column=0, columnspan=1,
                              sticky=N + S + W + E, padx=2, pady=2)
        self.tab3_CBstat.grid(row=3, column=1, columnspan=1,
                              sticky=N + S + W + E, padx=2, pady=2)
        self.save.grid(row=5, column=0, columnspan=4,
                       sticky=N + S + W + E, padx=2, pady=2)

        # Frame placement
        self.FrRekur.grid(row=2, column=1, columnspan=3,
                          sticky=N + S + W + E, padx=2, pady=2)

        # tooltips
        InfoBulle(self.lab_chps, message=self.dico_help.get(38)[1])
        InfoBulle(self.ddl_attr, message=self.dico_help.get(39)[1])
        InfoBulle(self.supr, message=self.dico_help.get(40)[1])
        InfoBulle(self.tab3_CBcass, message=self.dico_help.get(41)[1])
        InfoBulle(self.tab3_CBstat, message=self.dico_help.get(42)[1])

            ## Main frame
        # Hola
        self.welcome = Label(self,
                             text=self.blabla.get('hi') + self.uzer,
                             font=ft_tit,
                             foreground="red2")
        # Image
        self.icone = PhotoImage(master=self, file=r'data/img/metadator.gif')
        Label(self, image=self.icone).grid(row=2,
                                           column=0,
                                           padx=2,
                                           pady=2,
                                           sticky=N + S + W + E)
        # credits
        s = Style(self)
        s.configure('Kim.TButton', foreground='DodgerBlue',
                    borderwidth=0, relief="flat")
        Button(self,
               text='by Julien M. (2015)',
               style='Kim.TButton',
               command=lambda: open_new('https://github.com/Guts')).grid(row=3,
                                                                         padx=2,
                                                                         pady=2,
                                                                         sticky=W+E)
        # language switcher
        self.ddl_lang = Combobox(self, values=li_lang, width=5)
        self.ddl_lang.current(li_lang.index(self.def_lang))
        self.ddl_lang.bind("<<ComboboxSelected>>", self.change_lang)
        # Go go go button
        self.val = Button(self,
                          text=self.blabla.get('tab1_go'),
                          state='active',
                          command=lambda: self.process())
        # Cancel button
        self.can = Button(self,
                          text=self.blabla.get('gui_quit'),
                          command=self.destroy)
        # widgets placement
        self.welcome.grid(row=0, column=0, columnspan=1, sticky=N + S + W + E,
                          padx=2, pady=2)
        self.ddl_lang.grid(row=1, column=0, sticky=N, padx=2, pady=0)
        self.can.grid(row=4, column=0, sticky=N + S + W + E, padx=2, pady=2)
        self.val.grid(row=4, column=1, sticky=N + S + W + E, padx=2, pady=2)

        # tooltips
        InfoBulle(self.ddl_lang, message=self.dico_help.get(32)[1])

                ### Notebook placement
        self.nb.grid(row=0, rowspan=4, column=1, sticky=N + S + W + E)
        # keep updated list of profiles
        self.maj()

    def maj(self):
        """
        update the profiles dropdown list every second
        """
        try:
            self.li_profiles(self.ddl_lang.get())
            self.ddl_profil['values'] = self.li_pro
            self.after(1000, self.maj)
        except WindowsError:    # avoid an error occuring with browse button
            self.after(1000, self.maj)
            pass

    def alter_state(self, parent, new_state):
        """
        just a function to change easily  the state of  all children widgets
        of a parent class

        parent=Tkinter class with children (Frame, Labelframe, Tk, etc.)
        new_state=Tkinter keyword for widget state (ACTIVE, NORMAL, DISABLED)
        """
        for child in parent.winfo_children():
            child.configure(state=new_state)
        # end of function
        return parent, new_state

    def catalog_dependance(self):
        """ unselect the catalog option if the word option is unselected """
        if self.def_doc.get() == 0:
            self.def_cat.set(0)
            self.caz_cat.config(state='disabled')
        elif self.def_doc.get() == 1:
            self.caz_cat.config(state='normal')
        # end of function
        return

    def load_settings(self):
        u""" load settings from last execution """
        confile = 'options.ini'
        config = ConfigParser.RawConfigParser()
        config.read(confile)
        # basics
        self.def_lang = config.get('basics', 'def_codelang')
        self.def_rep = config.get('basics', 'def_rep')
        # export preferences
        self.def_doc.set(config.get('export_preferences', 'def_word'))
        self.def_cat.set(config.get('export_preferences', 'def_cat'))
        self.def_xls.set(config.get('export_preferences', 'def_xls'))
        self.def_xml.set(config.get('export_preferences', 'def_xml'))
        self.def_dict.set(config.get('export_preferences', 'def_dict'))
        self.def_odt.set(config.get('export_preferences', 'def_odt'))
        # log
        self.logger.info('Last options loaded')
        # End of function
        return config, self.def_rep, self.def_lang, self.def_doc

    def save_settings(self):
        u""" save options in order to make the next execution easier """
        confile = 'options.ini'
        config = ConfigParser.RawConfigParser()
        # add sections
        config.add_section('basics')
        config.add_section('export_preferences')
        # basics
        config.set('basics', 'def_codelang', self.ddl_lang.get())
        config.set('basics', 'def_rep', self.target.get())
        # export preferences
        config.set('export_preferences', 'def_word', self.def_doc.get())
        config.set('export_preferences', 'def_cat', self.def_cat.get())
        config.set('export_preferences', 'def_xls', self.def_xls.get())
        config.set('export_preferences', 'def_xml', self.def_xml.get())
        config.set('export_preferences', 'def_dict', self.def_dict.get())
        config.set('export_preferences', 'def_odt', self.def_odt.get())
        # Writing the configuration file
        with open(confile, 'wb') as configfile:
            config.write(configfile)
        # End of function
        return config

    def change_lang(self, event):
        u""" update the texts dictionary with the language selected """
        new_lang = event.widget.get()
        # change to the new language selected
        self.load_texts(new_lang)
        self.li_profiles(new_lang)
        self.li_rekurs(new_lang)
        self.ddl_profil.delete(0, END)
        self.ddl_profil.config(values=self.li_pro)
        self.ddl_profil.update()
        self.ddl_attr.config(values=self.dico_rekur.keys())
        self.recup_help(new_lang)
        # update widgets text
          # tab1
        self.nb.tab(0, text=self.blabla.get('gui_tab1'))
        self.welcome.config(text=self.blabla.get('hi') + self.uzer)
        self.can.config(text=self.blabla.get('gui_quit'))
        self.FrPath.config(text=self.blabla.get('tab1_fr1'))
        self.FrProg.config(text=self.blabla.get('tab1_frprog'))
        self.labtarg.config(text=self.blabla.get('tab1_path'))
        self.browsetarg.config(text=self.blabla.get('tab1_browse'))
        self.val.config(text=self.blabla.get('tab1_go'))
        self.profil.config(text=self.blabla.get('tab1_prof'))
          # tab2
        self.nb.tab(1, text=self.blabla.get('gui_tab2'))
        self.caz_cat.config(text=self.blabla.get('tab2_merge'))
          # tab3
        self.nb.tab(2, text=self.blabla.get('gui_tab3'))
        self.lab_chps.config(text=self.blabla.get('tab3_sele'))
        self.supr.config(text=self.blabla.get('tab3_supp'))
        self.FrRekur.config(text=self.blabla.get('tab3_tit'))
        self.tab3_LBnom.config(text=self.blabla.get('tab3_nom'))
        self.tab3_LBdesc.config(text=self.blabla.get('tab3_desc'))
        self.tab3_CBcass.config(text=self.blabla.get('tab3_cass'))
        self.tab3_CBstat.config(text=self.blabla.get('tab3_stat'))
        self.save.config(text=self.blabla.get('tab3_save'))

        # End of function
        return self.blabla

    def load_texts(self, lang='FR'):
        u"""
        Load texts according to the selected language
        """
        # clearing the text dictionary
        self.blabla.clear()
        # open xml cursor
        xml = ET.parse('locale/{0}/lang_{0}.xml'.format(lang))
        # Looping and gathering texts from the xml file
        for elem in xml.getroot().getiterator():
            self.blabla[elem.tag] = elem.text
        # updating the GUI
        self.update()
        # en of function
        return self.blabla

    def setpathtarg(self):
        """ ...browse and insert the path of target folder """
        foldername = askdirectory(parent=self,
                                  initialdir=self.def_rep,
                                  mustexist=True,
                                  title=self.blabla.get('gui_cible'))
        # check if a folder has been choosen
        if foldername:
            try:
                self.target.delete(0, END)
                self.target.insert(0, foldername)
            except:
                info(title=self.blabla.get('nofolder'),
                     message=self.blabla.get('nofolder'))
                return

        # count shapefiles and MapInfo files in a separated thread
        proc = threading.Thread(target=self.li_geofiles,
                                args=(foldername, ))
        proc.daemon = True
        proc.start()

        # end of function
        return foldername

    def li_geofiles(self, foldertarget):
        u""" List shapefiles and MapInfo files (.tab, not .mid/mif) contained
        in the folders structure """
        # reseting global variables
        self.li_shp = []
        self.li_tab = []
        self.browsetarg.config(state=DISABLED)
        # Looping in folders structure
        self.status.set(self.blabla.get('tab1_prog1'))
        self.prog_layers.start()
        for root, dirs, files in walk(unicode(foldertarget)):
            self.num_folders = self.num_folders + len(dirs)
            for f in files:
                """ looking for files with geographic data """
                try:
                    unicode(path.join(root, f))
                    full_path = path.join(root, f)
                except UnicodeDecodeError:
                    full_path = path.join(root, f.decode('latin1'))
                # Looping on files contained
                if path.splitext(full_path.lower())[1].lower() == '.shp'\
                   and (path.isfile('{0}.dbf'.format(full_path[:-4]))
                        or path.isfile('{0}.DBF'.format(full_path[:-4])))\
                   and (path.isfile('{0}.shx'.format(full_path[:-4]))
                        or path.isfile('{0}.SHX'.format(full_path[:-4]))):
                    """ listing compatible shapefiles """
                    # add complete path of shapefile
                    self.li_shp.append(full_path)
                elif path.splitext(full_path.lower())[1] == '.tab'\
                    and (path.isfile(full_path[:-4] + '.dat')
                         or path.isfile(full_path[:-4] + '.DAT'))\
                    and (path.isfile(full_path[:-4] + '.map')
                         or path.isfile(full_path[:-4] + '.MAP'))\
                    and (path.isfile(full_path[:-4] + '.id')
                         or path.isfile(full_path[:-4] + '.ID')):
                    """ listing MapInfo tables """
                    # add complete path of MapInfo file
                    self.li_tab.append(full_path)
        # stopping the progress bar
        self.prog_layers.stop()
        # Lists ordering and tupling
        self.li_shp.sort()
        self.li_shp = tuple(self.li_shp)
        self.li_tab.sort()
        self.li_tab = tuple(self.li_tab)
        # setting the label text and activing the buttons
        self.status.set(unicode(len(self.li_shp)) + u' shapefiles - '
                        + unicode(len(self.li_tab)) + u' tables (MapInfo) - '
                        + unicode(self.num_folders) + self.blabla.get('log_numfold'))
        self.browsetarg.config(state=ACTIVE)
        self.val.config(state=ACTIVE)
        # End of function
        return foldertarget, self.li_shp, self.li_tab

    def li_profiles(self, lang):
        u"""
        list profiles already existing
        """
        # reseting global variable
        self.li_pro = []
        # Looping in folders structure
        folder_profiles = path.join('locale/', lang + '/profiles/')
        self.li_pro = [lg[:-4] for lg in listdir(folder_profiles)]
        self.li_pro.append(self.blabla.get('tab1_new'))
        # End of function
        return folder_profiles, self.li_pro

    def li_rekurs(self, lang):
        u"""
        List recurring attributes that already exist in the selected language
        """
        # clearing the text dictionary
        self.dico_rekur.clear()
        champis = path.abspath(r'locale/{0}/champignons_{0}.xml'.format(lang))
        xml = ET.parse(champis)
        # Looping and gathering texts from the xml file
        for elem in xml.findall('champ'):
            rek_name = elem.find('intitule').text
            rek_desc = elem.find('description').text
            rek_kass = elem.find('case').text
            rek_stat = elem.find('stats').text
            self.dico_rekur[rek_name] = rek_desc, rek_kass, rek_stat
        self.dico_rekur[self.blabla.get('tab3_new')] = '', 0, 0
        # updating the GUI
        self.update()
        # End of function
        return self.dico_rekur

    def edit_rekur(self, event):
        u"""
        preparing the form to edit a recurring attribute
        """
        rekur = event.widget.get()
        # deactivate the selector
        self.ddl_attr.config(state=DISABLED)
        # activate the form
        self.alter_state(self.FrRekur, NORMAL)
        # change to the new language selected
        self.tab3_ENnom.insert(0, rekur)
        self.tab3_TXdesc.insert(1.0, self.dico_rekur.get(rekur)[0])
        self.def_kass.set(self.dico_rekur.get(rekur)[1])
        self.def_stat.set(self.dico_rekur.get(rekur)[2])
        # End of function
        return self.dico_rekur

    def save_rekur(self):
        u""" save the recurring attribute edited """
        # check if the attribute already exists
        if self.tab3_ENnom.get() in self.dico_rekur:
            if not askyesno(title=self.blabla.get('tab3_alert_exist1'),
                            message=self.blabla.get('tab3_alert_exist2')):
                return
            else:
                pass
        else:
            pass

        # save
        self.dico_rekur[self.tab3_ENnom.get()] = self.tab3_TXdesc.get(1.0, END).rstrip(),\
                                                 self.def_kass.get(),\
                                                 self.def_stat.get()
        # reset the form
        self.tab3_ENnom.delete(0, END)
        self.tab3_TXdesc.delete(1.0, END)
        self.def_kass.set(0)
        self.def_stat.set(0)
        # deactivate the form
        self.alter_state(self.FrRekur, DISABLED)
        # updating the dropdown list
        self.ddl_attr.config(state=NORMAL)
        self.ddl_attr.delete(0, END)
        self.ddl_attr['values'] = self.dico_rekur.keys()

        # End of function
        return self.dico_rekur

    def del_rekur(self):
        u""" delete the selected recurring attribute """
        # reactivate the selector
        self.ddl_attr.config(state=ACTIVE)
        self.dico_rekur.pop(self.ddl_attr.get())

        self.ddl_attr.delete(0, END)
        self.ddl_attr['values'] = self.dico_rekur.keys()
        # reset the form
        self.tab3_ENnom.delete(0, END)
        self.tab3_TXdesc.delete(1.0, END)
        self.def_kass.set(0)
        self.def_stat.set(0)
        # deactivate the form
        self.alter_state(self.FrRekur, DISABLED)

        # End of function
        return self.dico_rekur

    def saveas_rekurs(self, lang):
        u""" save the recurring fields into the file dedicated """
        rekur = ET.Element(u'champs')
        xml_path = r'locale/{0}/champignons_{0}.xml'.format(lang)
        self.dico_rekur.pop(self.blabla.get('tab3_new'))
        with open(xml_path, 'w') as champis:
            for elem in self.dico_rekur.keys():
                rek = ET.SubElement(rekur, u'champ')
                # name of recurring attribute
                rek_name = ET.SubElement(rek, u'intitule')
                rek_name.text = elem
                # description of recurring attribute
                rek_desc = ET.SubElement(rek, u'description')
                rek_desc.text = self.dico_rekur.get(elem)[0]
                # stats option of recurring attribute
                rek_stats = ET.SubElement(rek, u'stats')
                rek_stats.text = unicode(self.dico_rekur.get(elem)[1])
                # case sensitive option of recurring attribute
                rek_case = ET.SubElement(rek, u'case')
                rek_case.text = unicode(self.dico_rekur.get(elem)[2])

        # creating the xml tree
        out_rekurs = ET.ElementTree(rekur)
        # saving it
        out_rekurs.write(xml_path,
                         encoding='utf-8',
                         xml_declaration='version="1.0"',
                         method='xml')

        # End of function
        return self.dico_rekur

    def select_profil(self, event):
        """ when a profile is selected... """
        profsel = event.widget.get()
        # if user wants to use an existing profile or create a new one
        if profsel == self.blabla.get('tab1_new'):
            self.val.config(text=self.blabla.get('tab1_crprofil'))
        else:
            self.val.config(text=self.blabla.get('tab1_go'))

        # end of function
        return self.val

    def recup_profil(self, lang):
        """ get the information from the profile selected """
        # clearing the profile dictionary
        self.dico_profil.clear()
        # specific path to profile file
        path_profile = path.join('locale/{0}/profiles/{1}.xml'.format(lang,
                                                                      self.ddl_profil.get()))
        with open(path_profile, 'r') as profile:
            # open xml parser
            xml = ET.parse(profile)
            # basic informations
            self.dico_profil['description'] = xml.find('description').text
            self.dico_profil['sources'] = xml.find('sources').text
            self.dico_profil['url'] = xml.find('url').text
            self.dico_profil['url_label'] = xml.find('url_label').text
            self.dico_profil[u'diffusion'] = xml.find('diffusion').text
            # data language
            lang_data = xml.find(u'lang_data')
            self.dico_profil[u"lang_data"] = lang_data.find(u'name').text
            # metadata language
            lang_metad = xml.find(u'lang_metad')
            self.dico_profil[u"lang_md"] = lang_metad.find(u'name').text
            # diffusion constraints
            diff = xml.find(u'diffusion')
            self.dico_profil['diffusion'] = diff.find(u'name').text
            # update rythm
            rythm = xml.find(u'rythm')
            self.dico_profil['rythm'] = rythm.find(u'name').text
            # INSPIRE themes
            themes = xml.find('themesinspire')
            li_themesinspire = [theme.find('name').text for theme in themes.findall('theme')]
            self.dico_profil['themesinspire'] = li_themesinspire
            # custom keywords
            keywords = xml.find('keywords')
            li_keywords = [keyword.find('name').text for keyword in keywords.findall('keyword')]
            self.dico_profil['keywords'] = li_keywords
            # places keywords
            geokeywords = xml.find('geokeywords')
            li_geokeywords = [geokeyword.find('name').text for geokeyword in geokeywords.findall('geokeyword')]
            self.dico_profil['geokeywords'] = li_geokeywords
            # contacts
            contacts = xml.find(u'contacts')
            # point of contact
            cont = contacts.find(u'pointdecontact')
            self.dico_profil[u'cont_name'] = cont.find(u'name').text
            self.dico_profil[u'cont_orga'] = cont.find(u'org').text
            self.dico_profil[u'cont_mail'] = cont.find(u'mail').text
            self.dico_profil[u'cont_role'] = cont.find(u'role').text
            self.dico_profil[u'cont_func'] = cont.find(u'func')[0].text
            self.dico_profil[u'cont_street'] = cont.find(u'street').text
            self.dico_profil[u'cont_city'] = cont.find(u'city').text
            self.dico_profil[u'cont_cp'] = cont.find(u'cp').text
            self.dico_profil[u'cont_country'] = cont.find(u'country').text
            self.dico_profil[u'cont_phone'] = cont.find(u'tel').text
            # second contact (responsable, etc.)
            resp = contacts.find(u'second_contact')
            self.dico_profil[u'resp_name'] = resp.find(u'name').text
            self.dico_profil[u'resp_orga'] = resp.find(u'org').text
            self.dico_profil[u'resp_mail'] = resp.find(u'mail').text
            self.dico_profil[u'resp_role'] = resp.find(u'role').text
            self.dico_profil[u'resp_func'] = resp.find(u'func')[0].text
            self.dico_profil[u'resp_street'] = resp.find(u'street').text
            self.dico_profil[u'resp_city'] = resp.find(u'city').text
            self.dico_profil[u'resp_cp'] = resp.find(u'cp').text
            self.dico_profil[u'resp_country'] = resp.find(u'country').text
            self.dico_profil[u'resp_phone'] = resp.find(u'tel').text
        # End of function
        return self.dico_profil

    def recup_help(self, lang):
        """ get the help texts """
        # specific path to xml file
        path_help = 'locale/%s/help_%s.xml' % (lang, lang)
        # reading and parsing the xml
        with open(path_help, 'r') as source:
            xml = ET.parse(source)                  # xml cursor
            for tooltip in xml.findall('tooltip'):
                idu = tooltip.find('id').text
                ref = tooltip.find('ref').text
                txt = tooltip.find('txt').text
                img = tooltip.find('image').text
                doc = tooltip.find('doc').text
                # fillfulling the INSPIRE dictionary
                self.dico_help[int(idu)] = ref, txt, img, doc
        # End of function
        return self.dico_help

    def process(self):
        u""" launch the different processes """
        # display the main tab
        self.nb.select(0)
        # check option selected: process or create a new profile
        if self.ddl_profil.get() == self.blabla.get('tab1_new'):
            # launching the profile form
            self.logger.info('Creation of a new profile')
            tr_profile = threading.Thread(target=NewProfile,
                                          args=(self.blabla,
                                                self.ddl_lang.get(),
                                                self.dico_help,
                                                self.li_pro))
            tr_profile.daemon = True
            tr_profile.run()
            # NewProfile(self.blabla, self.ddl_lang.get(), self.li_pro)
            self.li_profiles(self.ddl_lang.get())   # updating the dropdow list
            self.ddl_profil['values'] = self.li_pro
            return
        # check if the target folder has been selected
        if self.target.get() == "":
            info(title=self.blabla.get('info_blanktarget1'),
                 message=self.blabla.get('info_blanktarget2'))
            return
        # check if a profile has been selected
        if self.ddl_profil.get() == "":
            info(title=self.blabla.get('info_blankprofile1'),
                 message=self.blabla.get('info_blankprofile2'))
            return
        # disabling others GUI parts
        self.tab_globals.focus_force()
        self.alter_state(self.FrPath, DISABLED)

        # check if there are some layers into the folder structure
        if len(self.li_shp) + len(self.li_tab) == 0:
            self.logger.warning("No geofiles found in the folder structure")
            self.status.set(self.blabla.get('log_nodata'))
            return
        # specific variables
        dest = path.join(self.target.get(), 'metadator')
        if not path.isdir(dest):    # test if folder already exists
            mkdir(dest, 0777)       # if not, we create it
        # getting profile informations
        self.recup_profil(self.ddl_lang.get())
        # saving options in a separated thread
        tr_options = threading.Thread(target=self.save_settings)
        tr_options.daemon = True
        tr_options.start()
        self.logger.info('Current options saved')
        # saving recurring fiels in a separated thread
        tr_rekurs = threading.Thread(target=self.saveas_rekurs,
                                     args=(self.ddl_lang.get(), ))
        tr_rekurs.daemon = True
        tr_rekurs.start()
        # configuring the progression bar
        self.prog_layers["maximum"] = len(self.li_shp) + len(self.li_tab)
        self.prog_layers["value"]
        # Processing the shapefiles
        self.logger.info('\tStart processing the files')
        for shp in self.li_shp:
            """ looping on shapefiles list """
            self.logger.info('Processing: %s' % path.basename(shp))
            self.status.set(path.basename(shp))
            # reset recipient data
            self.dico_layer.clear()
            self.dico_fields.clear()
            # getting separated process threads
            Read_SHP(shp,
                     self.dico_layer,
                     self.dico_fields,
                     'shape',
                     self.blabla)
            # checking layer error
            if self.dico_layer.get('error'):
                # increment the progress bar
                self.prog_layers["value"] = self.prog_layers["value"] + 1
                self.update()
                self.logger.warning('This shape has an issue: %s' % shp)
                continue
            # getting fields statistics only if needed
            if self.def_doc.get() == 1 or self.def_xls.get() == 1 or self.def_odt.get() == 1:
                StatsFields(shp, self.dico_fields, self.dico_rekur, self.blabla)
            # export according to options selected
            if self.def_doc.get() == 1:
                ExportToHTML(dest,
                             self.dico_layer,
                             self.dico_fields,
                             self.dico_profil,
                             self.dico_rekur,
                             self.blabla)
                html_path = path.join(dest,
                                      "{0}_MD.html".format(self.dico_layer['name'][:-4]))
                ExportToDocX(html_path, dest)
            if self.def_xls.get() == 1:
                ExportToXLS(dest,
                            self.dico_layer,
                            self.dico_fields,
                            self.dico_profil,
                            self.dico_rekur,
                            self.blabla)
            if self.def_xml.get() == 1:
                ExportToXML(dest,
                            self.dico_layer,
                            self.dico_profil,
                            '',
                            self.blabla,
                            1,
                            0)
            if self.def_odt.get() == 1:
                ExportToODT(dest,
                            self.dico_layer,
                            self.dico_fields,
                            self.dico_profil,
                            self.dico_rekur,
                            self.blabla)
            # increment the progress bar
            self.prog_layers["value"] = self.prog_layers["value"] + 1
            self.update()

        # Processing the MapInfo tables
        for tab in self.li_tab:
            """ looping on MapInfo tables list """
            self.logger.info('Processing: %s' % path.basename(tab))
            self.status.set(path.basename(tab))
            # reset recipient data
            self.dico_layer.clear()
            self.dico_fields.clear()
            # getting the informations
            Read_TAB(tab,
                     self.dico_layer,
                     self.dico_fields,
                     'table',
                     self.blabla)
            # checking layer error
            if self.dico_layer.get('error'):
                self.logger.warning('This MapInfo table has an issue: %s' % tab)
                # increment the progress bar
                self.prog_layers["value"] = self.prog_layers["value"] +1
                self.update()
                continue
            # getting fields statistics only if needed
            if self.def_doc.get() == 1 \
               or self.def_xls.get() == 1 \
               or self.def_odt.get() == 1:
                StatsFields(tab, self.dico_fields, self.dico_rekur, self.blabla)
            # export according to options selected
            if self.def_doc.get() == 1:
                ExportToHTML(dest,
                             self.dico_layer,
                             self.dico_fields,
                             self.dico_profil,
                             self.dico_rekur,
                             self.blabla)
                html_path = path.join(dest,
                                      "{0}_MD.html".format(self.dico_layer['name'][:-4]))
                ExportToDocX(html_path, dest)
            if self.def_xls.get() == 1:
                ExportToXLS(dest,
                            self.dico_layer,
                            self.dico_fields,
                            self.dico_profil,
                            self.dico_rekur,
                            self.blabla)
            if self.def_xml.get() == 1:
                ExportToXML(dest,
                            self.dico_layer,
                            self.dico_profil,
                            '',
                            self.blabla,
                            1,
                            0)
            if self.def_odt.get() == 1:
                ExportToODT(dest,
                            self.dico_layer,
                            self.dico_fields,
                            self.dico_profil,
                            self.dico_rekur,
                            self.blabla)
            # increment the progress bar
            self.prog_layers["value"] = self.prog_layers["value"] + 1
            self.update()

        # Word catalog export
        if self.def_doc.get() == 1 and self.def_cat.get() == 1:
            self.status.set(self.blabla.get('info_cat'))
            self.update()
            DocxMerger(dest, '00_Metadator_Catalog', 'metadator_')
        else:
            pass

        # final message
        # msg = self.blabla.get('info_end2') + self.blabla.get('info_end3')
        # info(title=self.blabla.get('info_end'), message=msg)
        # opening the destination folder
        self.open_dir_file(dest)
        # cleaning up
        logging.info('Hurray! It worked! All seem to have been fine!')
        self.destroy()
        # end of function
        return

    def open_dir_file(self, target):
        """
        Open a file or a directory in the explorer of the operating system
        http://sametmax.com/ouvrir-un-fichier-avec-le-bon-programme-en-python
        """
        # check if the file or the directory exists
        if not path.exists(target):
            raise IOError('No such file: {0}'.format(target))

        # check the read permission
        if not access(target, R_OK):
            raise IOError('Cannot access file: {0}'.format(target))

        # open the directory or the file according to the os
        if opersys == 'win32':  # Windows
            proc = startfile(target)

        elif opersys.startswith('linux'):  # Linux:
            proc = subprocess.Popen(['xdg-open', target],
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)

        elif opersys == 'darwin':  # Mac:
            proc = subprocess.Popen(['open', '--', target],
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)

        else:
            raise NotImplementedError(
                "Your `%s` isn't a supported operating system`." % opersys)

        # end of function
        return proc
Пример #27
0
class Cyantific(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
        self.master = master
        self.master.title("Cyantific")

        #self.GUIFrame = Frame(self)
        #Load image related elements
        #self.loadFrame = Frame(self)
        self.loadButton = Button(self)

        #Cropping related GUI elements
        #self.cropFrame = Frame(self)
        self.cropButton = Button(self)
        self.OCRButton = Button(self)
        self.BWSlider = tk.Scale(self)
        self.BWButton = Button(self)
        self.RButton = Button(self)
        self.RSlider = tk.Scale(self)
        #self.XScroll = tk.Scrollbar(self)
        #self.YScroll = tk.Scrollbar(self)
        self.TextField = tk.Text(self)
        self.SaveButton = Button(self)
        self.SkewButton = Button(self)

        self.canvas = None
        self.cropRect = None
        self.startX = self.startY = None
        self.currX = self.currY = None
        self.cropping = False
        self.rotating = False

        self.skewRects = None
        self.skewPoints = np.zeros(shape=(4, 2), dtype=np.float)
        self.newPoints = np.zeros(shape=(4, 2), dtype=np.float)

        self.imageHandler = IH.ImageHandler()

        self.initUI()
        self.filename = None
        self.image_dims = None

        self.converting_bw = False
        self.skewing = False
        self.skewdex = 0

        self.master_text = None

    def initUI(self):
        self.pack(fill=tk.BOTH, expand=True)

        self.columnconfigure(1, weight=1)
        self.columnconfigure(3, pad=7)
        self.rowconfigure(3, weight=1)
        self.rowconfigure(5, pad=7)

        label = Label(self, text="Image")
        label.grid(sticky=tk.W + tk.S, pady=4, padx=5)

        self.canvas = tk.Canvas(self)
        self.canvas.config(
            cursor="cross"
        )  #, xscrollcommand=self.XScroll.set, yscrollcommand=self.YScroll.set)
        self.canvas.grid(row=1,
                         column=1,
                         columnspan=2,
                         rowspan=4,
                         sticky=tk.N + tk.S + tk.E + tk.W)
        #self.canvas.pack(side="top", fill="both", expand=True)
        self.canvas.bind("<ButtonPress-1>", self.on_button_press)
        self.canvas.bind("<B1-Motion>", self.on_move_press)
        self.canvas.bind("<ButtonRelease-1>", self.on_button_release)

        #self.XScroll.config(orient=tk.HORIZONTAL, command=self.canvas.xview, width=20)
        #self.YScroll.config(orient=tk.VERTICAL, command=self.canvas.yview, width=20)
        #self.XScroll.grid(row=0, column=1, columnspan=2)
        #self.YScroll.grid(row=2, column=0, rowspan=4)

        #self.GUIFrame.grid(row=0, column=1)

        #Loading elements
        #self.loadFrame.grid(row=1, column=1)
        self.loadButton.config(text="Load Image", command=self.load_image)
        self.loadButton.grid(row=1, column=4)

        #Cropping elements
        #self.cropFrame.grid(row=0, column=1)
        self.cropButton.config(text="Start Cropping",
                               command=self.set_cropping,
                               state=tk.DISABLED)
        self.cropButton.grid(row=6, column=4, pady=4)

        self.OCRButton.config(text="OCR Image",
                              command=self.OCR_image,
                              state=tk.DISABLED)
        self.OCRButton.grid(row=6, column=5, padx=5)

        self.BWSlider.config(from_=0,
                             to=255,
                             orient=tk.HORIZONTAL,
                             label="B&W Threshold",
                             command=self.slider_update_bw,
                             state=tk.DISABLED)
        self.BWSlider.set(128)
        self.BWSlider.grid(row=5, column=4)
        self.BWButton.config(text="Convert to B&W",
                             command=self.toggle_bw,
                             state=tk.DISABLED)
        self.BWButton.grid(row=5, column=5)

        self.RSlider.config(from_=-180,
                            to=180,
                            orien=tk.HORIZONTAL,
                            label="Rotation Deg.",
                            command=self.slider_update_rot,
                            state=tk.DISABLED)
        self.RSlider.grid(row=4, column=4, sticky=tk.N)
        self.RButton.config(text="Rotate Image",
                            command=self.toggle_rot,
                            state=tk.DISABLED)
        self.RButton.grid(row=4, column=5)

        self.SkewButton.config(text="Fix Skew",
                               command=self.set_skewing,
                               state=tk.DISABLED)
        self.SkewButton.grid(row=3, column=4)

        self.TextField.grid(row=2, column=6, rowspan=3, columnspan=4)
        self.SaveButton.config(text="Save to File",
                               command=self.write_to_file,
                               state=tk.DISABLED)
        self.SaveButton.grid(row=5, column=7)

    def slider_update_bw(self, event):
        thresh = self.BWSlider.get()
        if (self.converting_bw):
            self.black_and_white(thresh)

    def slider_update_rot(self, event):
        degrees = self.RSlider.get()
        if (self.rotating):
            self.rotate_image(degrees)

    def draw_image(self, path=None):
        fpath = None
        if path == None:
            fpath = self.filename
        else:
            fpath = path

        self.imageHandler.init_image(fpath)

        self.im = Image.open(fpath)
        dimX, dimY = self.im.size
        self.canvas.config(scrollregion=(0, 0, dimX, dimY))
        self.image_dims = (dimY, dimX)
        self.tk_im = ImageTk.PhotoImage(self.im)
        self.canvas.create_image(0, 0, anchor="nw", image=self.tk_im)
        self.canvas.config(width=dimX, height=dimY)

    def draw_from_array(self, image):
        self.canvas.delete(tk.ALL)
        self.im = Image.fromarray(image)
        dimX, dimY = self.im.size
        self.image_dims = (dimY, dimX)
        self.tk_im = ImageTk.PhotoImage(self.im)
        self.canvas.create_image(0, 0, anchor="nw", image=self.tk_im)
        self.canvas.config(width=dimX, height=dimY)

    def on_button_press(self, event):
        if self.cropping:
            self.startX = event.x
            self.startY = event.y

            if not self.cropRect:
                self.cropRect = self.canvas.create_rectangle(0,
                                                             0,
                                                             1,
                                                             1,
                                                             fill="",
                                                             outline="red",
                                                             width=3)
        elif self.skewing:
            self.px = event.x
            self.py = event.y

            if not self.skewRects:
                self.skewRects = []
                for x in range(0, 4):
                    self.skewRects.append(
                        self.canvas.create_rectangle(0, 0, 1, 1, fill="green"))

    def on_move_press(self, event):
        if self.cropping:
            self.currX, self.currY = (event.x, event.y)
            self.canvas.coords(self.cropRect, self.startX, self.startY,
                               self.currX, self.currY)

    def load_image(self):
        self.canvas.delete(tk.ALL)
        self.cropRect = None
        self.filename = None
        self.filename = askopenfilename(filetypes=([("Image files",
                                                     ("*.png", "*.jpg",
                                                      "*.jpeg", "*.gif",
                                                      "*.tiff"))]))
        if self.filename:
            self.draw_image(self.filename)
            self.cropButton.config(state=tk.NORMAL)
            self.OCRButton.config(state=tk.NORMAL)
            self.BWButton.config(state=tk.NORMAL)
            self.RButton.config(state=tk.NORMAL)
            self.SkewButton.config(state=tk.NORMAL)

    def on_button_release(self, event):
        if self.cropping:
            pass
        elif self.skewing and self.skewdex <= 3:
            self.canvas.coords(self.skewRects[self.skewdex], self.px - 5,
                               self.py - 5, self.px + 5, self.py + 5)
            self.skewPoints[self.skewdex] = (self.px, self.py)
            self.skewdex += 1
        if self.skewdex == 4:
            self.SkewButton.config(state=tk.NORMAL)
            x1, y1 = self.skewPoints[0]
            x2, y2 = self.skewPoints[1]
            x3, y3 = self.skewPoints[2]
            self.dx = int(round(sqrt((x2 - x1)**2 + (y2 - y1)**2)))
            self.dy = int(round(sqrt((x1 - x3)**2 + (y1 - y3)**2)))

            self.newPoints[0] = (0, 0)
            self.newPoints[1] = (self.dx, 0)
            self.newPoints[2] = (0, self.dy)
            self.newPoints[3] = (self.dx, self.dy)

    def set_skewing(self):
        if not self.skewing:
            self.skewing = True
            self.SkewButton.config(text="Skew")
            self.BWButton.config(state=tk.DISABLED)
            self.RButton.config(state=tk.DISABLED)
            self.cropButton.config(state=tk.DISABLED)
        else:
            self.BWButton.config(state=tk.NORMAL)
            self.RButton.config(state=tk.NORMAL)
            self.cropButton.config(state=tk.NORMAL)
            self.skew_image()
            self.skewdex = 0
            self.skewing = False
            self.skewRects = None

    def set_cropping(self):
        if not self.cropping:
            self.cropping = True
            self.cropButton.config(text="Save Crop")
            self.BWButton.config(state=tk.DISABLED)
            self.RButton.config(state=tk.DISABLED)
        else:
            self.cropTop = tk.Toplevel(width=200, height=100)
            self.cropTop.title("Confirm crop")
            self.cropTop.resizable(width=None, height=None)
            label = Label(self.cropTop, text="Crop the image?", pad=5)
            label.pack()
            confirm = Button(self.cropTop,
                             text="Confirm",
                             pad=5,
                             command=self.crop_image)
            confirm.pack(pady=5, padx=5)
            cancel = Button(self.cropTop,
                            text="Cancel",
                            pad=5,
                            command=self.cancel_crop_top)
            cancel.pack(pady=5, padx=5)
            self.BWButton.config(state=tk.NORMAL)
            self.RButton.config(state=tk.NORMAL)

    def cancel_crop_top(self):
        self.cropTop.destroy()
        self.cropButton.config(text="Save Crop")
        self.cropping = True

    def crop_image(self):
        self.cropTop.destroy()
        self.cropButton.config(text="Start Cropping")
        self.cropping = False
        c1, r1, c2, r2 = self.startX, self.startY, self.currX, self.currY
        if c1 > c2:
            c1 = self.currX
            c2 = self.startX
        if r1 > r2:
            r1 = self.currY
            r2 = self.startY

        cols = self.image_dims[1]
        rows = self.image_dims[0]
        c1 = 0 if (c1 < 0) else c1
        r1 = 0 if (r1 < 0) else r1
        c2 = cols - 1 if (c2 >= cols) else c2
        r2 = rows - 1 if (r2 >= rows) else r2

        image = self.imageHandler.crop_image(r1, c1, r2, c2)
        self.cropRect = None
        self.draw_from_array(image)

    def toggle_bw(self):
        if not self.converting_bw:
            self.BWSlider.config(state=tk.NORMAL)
            self.BWButton.config(text="Save Change")
            self.cropButton.config(state=tk.DISABLED)
            self.OCRButton.config(state=tk.DISABLED)
        else:
            self.BWSlider.config(state=tk.DISABLED)
            self.BWButton.config(text="Convert to B&W")
            self.cropButton.config(state=tk.NORMAL)
            self.OCRButton.config(state=tk.NORMAL)
            self.imageHandler.converted = True
            self.imageHandler.write_curr_image()
        self.converting_bw = (not self.converting_bw)

    def toggle_rot(self):
        if not self.rotating:
            self.RSlider.config(state=tk.NORMAL)
            self.RButton.config(text="Save Change")
            self.cropButton.config(state=tk.DISABLED)
            self.OCRButton.config(state=tk.DISABLED)
        else:
            self.RSlider.config(state=tk.DISABLED)
            self.RButton.config(text="Rotate Image")
            self.cropButton.config(state=tk.NORMAL)
            self.OCRButton.config(state=tk.NORMAL)
            self.rotate_image(degrees=self.RSlider.get(), save=True)
        self.rotating = (not self.rotating)

    def black_and_white(self, thresh=128):
        image = self.imageHandler.black_and_white(thresh)
        self.draw_from_array(image)

    def rotate_image(self, degrees=0, save=False):
        image = self.imageHandler.rotate_image(degrees, save)
        self.draw_from_array(image)

    def skew_image(self):
        self.imageHandler.converted = True
        image = self.imageHandler.skew_image(self.skewPoints, self.newPoints,
                                             self.dx, self.dy)
        self.draw_from_array(image)

    def OCR_image(self):
        self.SaveButton.config(state=tk.NORMAL)
        self.TextField.delete("1.0", 'end')
        words, defins, kanji = self.imageHandler.OCR()
        index = 0
        kindex = 0
        for word in words:
            defin = defins[index]
            kan = kanji[kindex:(kindex + len(word))]
            self.TextField.insert('end', word)
            self.TextField.insert('end', "\n")
            self.TextField.insert('end', "Kanji Breakdown: \n")
            for k in kan:
                self.TextField.insert('end', k[0])
                self.TextField.insert('end', "\nMeaning: ")
                self.TextField.insert('end', k[1])
                self.TextField.insert('end', "\nOnyomi: ")
                self.TextField.insert('end', k[2])
                self.TextField.insert('end', "\nKunyomi: ")
                self.TextField.insert('end', k[3])
                self.TextField.insert('end', "\nRadicals: ")
                self.TextField.insert('end', k[4])
                self.TextField.insert('end', "\n\n")
            self.TextField.insert('end', "Words and Definitions:\n")
            for d in defin:
                self.TextField.insert('end', "Possible Word: ")
                self.TextField.insert('end', d[1])
                self.TextField.insert('end', "\nReading: ")
                self.TextField.insert('end', d[2])
                self.TextField.insert('end', "\nDefinition: ")
                self.TextField.insert('end', d[3])
                self.TextField.insert('end', "\n\n")
            index += 1
            kindex += len(word)
            more_info = "For more detailed kanji information for\'" + word + "\', see jisho.org/search/" + word + " %23kanji\n\n"
            self.TextField.insert('end', more_info)
        self.master_text = self.TextField.get('1.0', 'end')

    def write_to_file(self):
        out_file = open('output.txt', 'w')
        out_file.write(self.master_text.encode("utf-8"))
        out_file.close()
Пример #28
0
class CHEWD(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()
        self.selection = ""
        self.pdb = ""

    def initUI(self):
        self.parent.title("CHemical Energy Wise Decomposition")
        frame4 = Frame(self.parent)
        frame4.grid(row=0, column=0, sticky="nsew")
        self.wat = IntVar()
        self.wat.set(1)
        self.waterswap = Checkbutton(frame4,
                                     text="Water Swap",
                                     command=self.optionws,
                                     variable=self.wat)
        self.waterswap.grid(row=0, column=0)
        self.lig = IntVar()
        self.lig.set(0)
        self.ligandswap = Checkbutton(frame4,
                                      text="Ligand Swap",
                                      command=self.optionls,
                                      variable=self.lig)
        self.ligandswap.grid(row=0, column=1)
        self.mm = IntVar()
        self.mm.set(0)
        self.mmpbsa = Checkbutton(frame4,
                                  text="MMPBSA",
                                  command=self.optionmm,
                                  variable=self.mm)
        self.mmpbsa.grid(row=0, column=2)

        frame1 = Frame(self.parent)
        frame1.grid(row=1, column=0, sticky="nsew")
        lbl1 = Label(frame1, text="Log file folder", width=12)
        lbl1.grid(row=0, column=0)
        self.entry1 = Entry(frame1)
        self.entry1.grid(row=0, column=1, columnspan=4, sticky=W + E)
        self.browserButton = Button(frame1,
                                    text="Browser",
                                    command=self.onOpen)
        self.browserButton.grid(row=0, column=5, sticky="e")

        lbl2 = Label(frame1, text="MMPBSA log file", width=12)
        lbl2.grid(row=1, column=0)
        self.entry2 = Entry(frame1, state=DISABLED)
        self.entry2.grid(row=1, column=1, columnspan=4, sticky=W + E)
        self.browserButtonMM = Button(frame1,
                                      text="Browser",
                                      command=self.onOpenMM,
                                      state=DISABLED)
        self.browserButtonMM.grid(row=1, column=5, sticky="e")

        lbl3 = Label(frame1, text="MMPBSA PDB file", width=12)
        lbl3.grid(row=2, column=0)
        self.entry3 = Entry(frame1, state=DISABLED)
        self.entry3.grid(row=2, column=1, columnspan=4, sticky=W + E)
        self.browserButtonPDB = Button(frame1,
                                       text="Browser",
                                       command=self.onOpenPDB,
                                       state=DISABLED)
        self.browserButtonPDB.grid(row=2, column=5, sticky="e")

        lbl4 = Label(frame1, text="Ligand Name", width=12)
        lbl4.grid(row=3, column=0)
        self.entry4 = Entry(frame1)
        self.entry4.grid(row=3, column=1)
        self.lblswap = Label(frame1,
                             text="Swap Ligand",
                             width=12,
                             state=DISABLED)
        self.lblswap.grid(row=3, column=2)
        self.swapentry = Entry(frame1, state=DISABLED)
        self.swapentry.grid(row=3, column=3)
        self.l1v = IntVar()
        self.l1v.set(1)
        self.lig1ck = Checkbutton(frame1,
                                  text="Ligand 1",
                                  command=self.changelig1,
                                  state=DISABLED,
                                  variable=self.l1v)
        self.lig1ck.grid(row=4, column=0)
        self.l2v = IntVar()
        self.l2v.set(0)
        self.lig2ck = Checkbutton(frame1,
                                  text="Ligand 2",
                                  command=self.changelig2,
                                  state=DISABLED,
                                  variable=self.l2v)
        self.lig2ck.grid(row=4, column=2)
        lbl5 = Label(frame1, text="Display Radius", width=12)
        lbl5.grid(row=5, column=0)
        self.entry5 = Entry(frame1)
        self.entry5.grid(row=5, column=1)
        self.entry5.insert(0, "5.0")
        self.sv = IntVar()
        self.sv.set(0)
        self.surface = Checkbutton(frame1,
                                   text="View Surface",
                                   command=self.viewsurface,
                                   variable=self.sv)
        self.surface.grid(row=5, column=2)
        self.vl = IntVar()
        self.vl.set(1)
        self.label = Checkbutton(frame1,
                                 text="View Label",
                                 command=self.viewlabel,
                                 variable=self.vl)
        self.label.grid(row=5, column=3)

        lbl6 = Label(frame1, text="Min Value", width=12)
        lbl6.grid(row=6, column=0)
        self.entry6 = Entry(frame1)
        self.entry6.grid(row=6, column=1)
        self.entry6.insert(0, "-5")
        lbl7 = Label(frame1, text="Max Value", width=12)
        lbl7.grid(row=6, column=2)
        self.entry7 = Entry(frame1)
        self.entry7.grid(row=6, column=3)
        self.entry7.insert(0, "+5")

        lbl8 = Label(frame1, text="Starting log file", width=12)
        lbl8.grid(row=7, column=0)
        self.entry8 = Entry(frame1)
        self.entry8.grid(row=7, column=1)
        self.entry8.insert(0, "400")
        lbl9 = Label(frame1, text="Ending log file", width=12)
        lbl9.grid(row=7, column=2)
        self.entry9 = Entry(frame1)
        self.entry9.grid(row=7, column=3)
        self.entry9.insert(0, "1000")

        frame2 = Frame(self.parent)
        frame2.grid(row=2, column=0, sticky="nsew")
        self.vsb = Scrollbar(frame2, orient="vertical", command=self.OnVsb)
        self.vsb.grid(row=1, column=3, sticky="ns")
        self.lb1 = Listbox(frame2, yscrollcommand=self.vsb.set)
        self.lb1.grid(row=1, column=0)
        self.lb2 = Listbox(frame2, yscrollcommand=self.vsb.set)
        self.lb2.grid(row=1, column=1)
        self.lb3 = Listbox(frame2, yscrollcommand=self.vsb.set)
        self.lb3.grid(row=1, column=2)

        self.b1 = Button(frame2,
                         text="Residue Number",
                         state=DISABLED,
                         command=lambda: self.sortdata(0))
        self.b1.grid(row=0, column=0, sticky=W + E)
        self.b2 = Button(frame2,
                         text="Residue Name",
                         state=DISABLED,
                         command=lambda: self.sortdata(1))
        self.b2.grid(row=0, column=1, sticky=W + E)
        self.b3 = Button(frame2,
                         text="Energy Value",
                         state=DISABLED,
                         command=lambda: self.sortdata(2))
        self.b3.grid(row=0, column=2, sticky=W + E)

        OS = platform.system()
        if (OS == "Linux"):
            self.lb1.bind("<<ListboxSelect>>", self.OnSelect)
            self.lb1.bind("<4>", self.OnMouseWheel)
            self.lb1.bind("<5>", self.OnMouseWheel)
            self.lb2.bind("<<ListboxSelect>>", self.OnSelect)
            self.lb2.bind("<4>", self.OnMouseWheel)
            self.lb2.bind("<5>", self.OnMouseWheel)
            self.lb3.bind("<<ListboxSelect>>", self.OnSelect)
            self.lb3.bind("<4>", self.OnMouseWheel)
            self.lb3.bind("<5>", self.OnMouseWheel)
        else:
            self.lb1.bind("<<ListboxSelect>>", self.OnSelect)
            self.lb1.bind("<MouseWheel>", self.OnMouseWheel)
            self.lb2.bind("<<ListboxSelect>>", self.OnSelect)
            self.lb2.bind("<MouseWheel>", self.OnMouseWheel)
            self.lb3.bind("<<ListboxSelect>>", self.OnSelect)
            self.lb3.bind("<MouseWheel>", self.OnMouseWheel)

        frame3 = Frame(self.parent)
        frame3.grid(row=3, column=0, sticky="nsew")

        self.previous = Button(frame3,
                               text="Previous Frame",
                               state=DISABLED,
                               command=self.prevframe)
        self.previous.grid(row=0, column=0, sticky=W + E)
        self.scale = Scale(frame3,
                           command=self.onScale,
                           state=DISABLED,
                           orient=HORIZONTAL,
                           length=320,
                           showvalue=0)
        self.scale.grid(row=0, column=1, sticky=W + E)
        self.next = Button(frame3,
                           text="Next Frame",
                           state=DISABLED,
                           command=self.nextframe)
        self.next.grid(row=0, column=2, sticky=W + E)

        self.var = IntVar()
        v = 000
        self.var.set(v)
        self.label = Label(frame3, text=0, textvariable=self.var)
        self.label.grid(row=0, column=3)
        self.ApplyButton = Button(frame3, text="Apply", command=self.Apply)
        self.ApplyButton.grid(row=1, column=3, sticky="e")

        ToolTip(lbl1, "Load the result directory of Sire Analysis")
        ToolTip(self.browserButton,
                "Load the result directory of Sire Analysis")
        ToolTip(lbl4, "Enter the name of the Ligand in your coordinate file")
        ToolTip(
            lbl5,
            "The radially distributed zone around ligand you want to be displayed"
        )
        ToolTip(
            lbl6,
            "Minimum scale value for the color distribution and it will be treated as blue"
        )
        ToolTip(
            lbl7,
            "Maximum scale value for the color distribution and it will be treated as red"
        )

    def wsvisualizer(self, index, lig, zone, min, max, label):
        cmd.hide("all")
        x = cmd.get_names("all")
        cmd.show("cartoon", "bo. " + x[index])
        cmd.show("sticks", x[index] + " and r. " + lig)
        cmd.color("white", x[index] + " and pol.")
        fp = open(tempfile.gettempdir() + "/temp.txt", "r")
        #tt=0
        stored.bfact = []
        for line in fp:
            stored.bfact.append(line)
            #print(stored.bfact[tt]+"\t"+line+"\t"+str(tt))
            #tt=tt+1
        #print(tt)
        fp.close()
        cmd.alter(x[index], "b=stored.bfact.pop(0)")
        cmd.spectrum("b", "blue_white_red", x[index], minimum=min, maximum=max)
        cmd.ramp_new("ramp_obj",
                     x[index],
                     range=[min, 0, max],
                     color="[blue, white, red ]")
        cmd.util.cbaw(x[index] + " and r. " + lig)
        cmd.show(
            "licorice", "( " + x[index] + " and (r. " + lig + " a. " + zone +
            ") ) and (not (" + x[index] +
            " and (r. SWT or r. BWT or r. SWP))) ")
        self.togglelabelws(label, index, lig, zone)

    def lsvisualizer(self, index, lig, zone, min, max, hlig, label):
        cmd.hide("all")
        x = cmd.get_names("all")
        cmd.show("cartoon", "bo. " + x[index])
        cmd.show("sticks", x[index] + " and r. " + lig)
        cmd.color("white", x[index] + " and pol.")
        fp = open(tempfile.gettempdir() + "/temp.txt", "r")
        stored.bfact = []
        for line in fp:
            stored.bfact.append(line)
        fp.close()
        cmd.alter(x[index], "b=stored.bfact.pop(0)")
        cmd.spectrum("b", "blue_white_red", x[index], minimum=min, maximum=max)
        cmd.ramp_new("ramp_obj",
                     x[index],
                     range=[min, 0, max],
                     color="[blue, white, red ]")
        cmd.util.cbaw(x[index] + " and r. " + lig)
        cmd.show(
            "licorice", "( " + x[index] + " and (r. " + lig + " a. " + zone +
            ") ) and (not (" + x[index] +
            " and (r. SWT or r. BWT or r. SWP))) ")
        cmd.hide("licorice", x[index] + " and r. " + hlig)
        self.togglelabells(label, index, lig, zone, hlig)

    def wsupdateview(self, lig, zone, min, max, prev, index, label):
        cmd.hide("all")
        x = cmd.get_names("all")
        cmd.label(
            "( " + x[index] + " and (r. " + lig + " a. " + prev +
            ") ) and (not (" + x[index] +
            " and (r. SWT or r. BWT or r. SWP))) " + " and name CA", "\" \"")
        cmd.show("cartoon", "bo. " + x[index])
        cmd.show("sticks", x[index] + " and r. " + lig)
        cmd.color("white", x[index] + " and pol.")
        fp = open(tempfile.gettempdir() + "/temp.txt", "r")
        #tt=0
        stored.bfact = []
        for line in fp:
            stored.bfact.append(line)
            #print(stored.bfact[tt]+"\t"+line+"\t"+str(tt))
            #tt=tt+1
        #print(tt)
        fp.close()
        cmd.alter(x[index], "b=stored.bfact.pop(0)")
        cmd.spectrum("b", "blue_white_red", x[index], minimum=min, maximum=max)
        cmd.ramp_new("ramp_obj",
                     x[index],
                     range=[min, 0, max],
                     color="[blue, white, red ]")
        cmd.util.cbaw(x[index] + " and r. " + lig)
        cmd.show(
            "licorice", "( " + x[index] + " and (r. " + lig + " a. " + zone +
            ") ) and (not (" + x[index] +
            " and (r. SWT or r. BWT or r. SWP))) ")
        self.togglelabelws(label, index, lig, zone)

    def lsupdateview(self, lig, zone, min, max, prev, index, hlig, label):
        cmd.hide("all")
        x = cmd.get_names("all")
        cmd.label(
            "( " + x[index] + " and (r. " + lig + " a. " + prev +
            ") ) and (not (" + x[index] +
            " and (r. SWT or r. BWT or r. SWP))) " + " and name CA", "\" \"")
        cmd.show("cartoon", "bo. " + x[index])
        cmd.show("sticks", x[index] + " and r. " + lig)
        cmd.color("white", x[index] + " and pol.")
        fp = open(tempfile.gettempdir() + "/temp.txt", "r")

        stored.bfact = []
        for line in fp:
            stored.bfact.append(line)

        fp.close()
        cmd.alter(x[index], "b=stored.bfact.pop(0)")
        cmd.spectrum("b", "blue_white_red", x[index], minimum=min, maximum=max)
        cmd.ramp_new("ramp_obj",
                     x[index],
                     range=[min, 0, max],
                     color="[blue, white, red ]")
        cmd.util.cbaw(x[index] + " and r. " + lig)
        cmd.show(
            "licorice", "( " + x[index] + " and (r. " + lig + " a. " + zone +
            ") ) and (not (" + x[index] +
            " and (r. SWT or r. BWT or r. SWP))) ")
        cmd.hide("licorice", x[index] + " and r. " + hlig)
        self.togglelabells(label, index, lig, zone, hlig)

    def wsloadallpdb(self, pdblist, path):
        for x in pdblist:
            cmd.load(path + "/" + x)
            #print(path +"/"+ x)
        cmd.hide("all")

    def mmloadpdb(self, path):
        cmd.load(path)

    def togglesurface(self, sur):
        x = cmd.get_names("all")
        if (sur):
            cmd.show("surf", x[int(self.scale.get())])
            cmd.set("transparency", "0.7")
        else:
            cmd.hide("surf", x[int(self.scale.get())])

    def wslistdisplay(self, prev, cur, index):
        x = cmd.get_names("all")
        cmd.hide("sticks", x[index] + " and i. " + prev)
        cmd.label(x[index] + " and i. " + prev + " and name CA", "\" \"")
        cmd.show("sticks", x[index] + " and i. " + cur)
        cmd.label(x[index] + " and i. " + cur + " and name CA",
                  "\"%s %s\"%(resn,resi)")

    def togglelabelws(self, label, index, lig, zone):
        global prevz
        x = cmd.get_names("all")
        if (label):
            cmd.label(
                "( " + x[index] + " and (r. " + lig + " a. " + zone +
                ") ) and (not (" + x[index] +
                " and (r. SWT or r. BWT or r. SWP))) " + " and name CA",
                "\"%s %s\"%(resn,resi)")
            prevz = self.entry5.get()
        else:
            cmd.label(
                "( " + x[index] + " and (r. " + lig + " a. " + prevz +
                ") ) and (not (" + x[index] +
                " and (r. SWT or r. BWT or r. SWP))) " + " and name CA",
                "\" \"")

    def togglelabells(self, label, index, lig, zone, hlig):
        global prevz
        x = cmd.get_names("all")
        if (label):
            cmd.label(
                "( " + x[index] + " and (r. " + lig + " a. " + zone +
                ") ) and (not (" + x[index] +
                " and (r. SWT or r. BWT or r. SWP))) " + " and name CA",
                "\"%s %s\"%(resn,resi)")
            cmd.label(x[index] + " and r. " + hlig + " and name CA", "\" \"")
            prevz = self.entry5.get()
        else:
            cmd.label(
                "( " + x[index] + " and (r. " + lig + " a. " + prevz +
                ") ) and (not (" + x[index] +
                " and (r. SWT or r. BWT or r. SWP))) " + " and name CA",
                "\" \"")

    def viewlabel(self):
        if (load > 0):
            if (self.wat.get() == 1):
                self.togglelabelws(self.vl.get(), int(self.scale.get()),
                                   self.entry4.get(), self.entry5.get())
            elif (self.lig.get() == 1):
                if (self.l1v.get() == 1):
                    vl = self.entry4.get()
                    hl = self.swapentry.get()
                if (self.l2v.get() == 1):
                    vl = self.swapentry.get()
                    hl = self.entry4.get()
                self.togglelabells(self.vl.get(), int(self.scale.get()), vl,
                                   self.entry5.get(), hl)
            elif (self.mm.get() == 1):
                self.togglelabelws(self.vl.get(), 0, self.entry4.get(),
                                   self.entry5.get())

    def viewsurface(self):  ##
        if (load > 0):
            self.togglesurface(self.sv.get())

    def optionws(self):
        if (self.wat.get() == 1):
            self.lig.set(0)
            self.mm.set(0)
            self.entry1.config(state="normal")
            self.browserButton.config(state="normal")
            self.swapentry.config(state=DISABLED)
            self.lig1ck.config(state=DISABLED)
            self.lig2ck.config(state=DISABLED)
            self.lblswap.config(state=DISABLED)
            self.entry2.config(state=DISABLED)
            self.entry3.config(state=DISABLED)
            self.browserButtonMM.config(state=DISABLED)
            self.browserButtonPDB.config(state=DISABLED)
        else:
            self.wat.set(0)
            self.lig.set(1)
            self.mm.set(0)
            self.swapentry.config(state="normal")
            self.lig1ck.config(state="normal")
            self.lig2ck.config(state="normal")
            self.lblswap.config(state="normal")
            self.entry1.config(state="normal")
            self.browserButton.config(state="normal")
            self.entry2.config(state=DISABLED)
            self.entry3.config(state=DISABLED)
            self.browserButtonMM.config(state=DISABLED)
            self.browserButtonPDB.config(state=DISABLED)

    def optionls(self):
        if (self.lig.get() == 1):
            self.wat.set(0)
            self.mm.set(0)
            self.swapentry.config(state="normal")
            self.lig1ck.config(state="normal")
            self.lig2ck.config(state="normal")
            self.lblswap.config(state="normal")
            self.entry1.config(state="normal")
            self.browserButton.config(state="normal")
            self.entry2.config(state=DISABLED)
            self.entry3.config(state=DISABLED)
            self.browserButtonMM.config(state=DISABLED)
            self.browserButtonPDB.config(state=DISABLED)
        else:
            self.lig.set(0)
            self.mm.set(0)
            self.wat.set(1)
            self.entry1.config(state="normal")
            self.browserButton.config(state="normal")
            self.swapentry.config(state=DISABLED)
            self.lig1ck.config(state=DISABLED)
            self.lig2ck.config(state=DISABLED)
            self.lblswap.config(state=DISABLED)
            self.entry2.config(state=DISABLED)
            self.entry3.config(state=DISABLED)
            self.browserButtonMM.config(state=DISABLED)
            self.browserButtonPDB.config(state=DISABLED)

    def optionmm(self):
        if (self.mm.get() == 1):
            self.lig.set(0)
            self.wat.set(0)
            self.swapentry.config(state=DISABLED)
            self.lig1ck.config(state=DISABLED)
            self.lig2ck.config(state=DISABLED)
            self.lblswap.config(state=DISABLED)
            self.entry8.config(state=DISABLED)
            self.entry9.config(state=DISABLED)
            self.entry1.config(state=DISABLED)
            self.browserButton.config(state=DISABLED)
            self.entry2.config(state="normal")
            self.entry3.config(state="normal")
            self.browserButtonMM.config(state="normal")
            self.browserButtonPDB.config(state="normal")
        else:
            self.wat.set(1)
            self.lig.set(0)
            self.mm.set(0)
            self.entry8.config(state="normal")
            self.entry9.config(state="normal")
            self.entry1.config(state="normal")
            self.browserButton.config(state="normal")
            self.entry2.config(state=DISABLED)
            self.entry3.config(state=DISABLED)
            self.browserButtonMM.config(state=DISABLED)
            self.browserButtonPDB.config(state=DISABLED)

    def changelig1(self):  ##
        if (self.l1v.get() == 1):
            self.l2v.set(0)
        else:
            self.l2v.set(1)
        if (load > 0):
            if (self.l1v.get() == 1):
                vl = self.entry4.get()
                hl = self.swapentry.get()
            if (self.l2v.get() == 1):
                vl = self.swapentry.get()
                hl = self.entry4.get()
            self.lsupdateview(vl, self.entry5.get(), self.entry6.get(),
                              self.entry7.get(), prevz, int(self.scale.get()),
                              hl, self.vl.get())

    def changelig2(self):  ##
        if (self.l2v.get() == 1):
            self.l1v.set(0)
        else:
            self.l1v.set(1)
        if (load > 0):
            if (self.l1v.get() == 1):
                vl = self.entry4.get()
                hl = self.swapentry.get()
            if (self.l2v.get() == 1):
                vl = self.swapentry.get()
                hl = self.entry4.get()
            self.lsupdateview(vl, self.entry5.get(), self.entry6.get(),
                              self.entry7.get(), prevz, int(self.scale.get()),
                              hl, self.vl.get())

    def loadmmpbsaresults(self):
        fp = open(self.entry3.get(), "r")
        e = 0
        atomcount = 0
        resnew = 0
        rescount = 0
        resnum = list()
        residuename = list()
        resv = list()
        atomnum = list()
        atomnums = list()
        score = list()
        r = ""
        rn = ""
        for line in fp:
            if e == 2:
                atomnum.append(atomnums)
                break
            t = line.split()
            if line.find('TER') != -1:
                e = e + 1
            if line.find('ATOM') != -1:
                if (resnew == 0):
                    r = t[4]
                    rn = t[3]
                    resnew = 1
                    resnum.append(r)
                    residuename.append(rn)
                    score.append(0)
                elif (r != t[4]):
                    r = t[4]
                    rn = t[3]
                    atomnum.append(atomnums)
                    resnum.append(r)
                    residuename.append(rn)
                    score.append(0)
                    atomnums = list()
                atomnums.append(atomcount)
                atomcount = atomcount + 1
        fp.close()
        ll = len(score)
        print(ll)
        resv = list()
        fp = open(self.entry2.get(), "r")
        for line in fp:
            t = line.split(',')
            t2 = t[0].split()
            if (len(t) == 20 and len(t2) == 2 and t2[0] != "LIG"):
                for xx in range(ll):
                    if (int(resnum[xx]) == int(t2[1])):
                        #print(str(ll)+"\t"+str(len(t)))
                        score[xx] = float(t[17])
            matchObj = re.match(r'Sidechain Energy Decomposition:', line,
                                re.M | re.I)
            if matchObj:
                break
        fp.close()
        x = len(score)
        data = list()
        for i in range(x):
            data.append([resnum[i], score[i], residuename[i], atomnum[i]])
        data.sort(key=lambda s: (int(s[0])))
        scores = list()
        for i in range(len(data)):
            for j in range(len(data[i][3])):
                scores.append("{0:.3f}".format(data[i][1]))
        fp = open(tempfile.gettempdir() + "/temp.txt", "w")
        xs = len(scores)
        for i in range(xs):
            fp.write(str(scores[i]) + "\n")
        fp.close()
        self.lb1.delete(0, END)
        self.lb2.delete(0, END)
        self.lb3.delete(0, END)

        for i in range(x):
            self.lb1.insert(END, data[i][0])
            self.lb2.insert(END, data[i][2])
            self.lb3.insert(END, round(data[i][1], 3))

        self.b1.config(state="normal")
        self.b2.config(state="normal")
        self.b3.config(state="normal")

    def changestate(self):  ##
        fp = open(self.entry1.get() + "/bound_mobile_000100_0.00500.pdb")
        lend = 0
        if (self.wat.get() == 1):
            lend = 2
        elif (self.lig.get() == 1):
            lend = 4
        e = 0
        atomcount = 0
        resnew = 0
        rescount = 0
        resnum = list()
        residuename = list()
        resv = list()
        atomnum = list()
        atomnums = list()
        score = list()
        r = ""
        rn = ""
        for line in fp:
            if e == lend:
                atomnum.append(atomnums)
                break
            t = line.split()
            if line.find('TER') != -1:
                e = e + 1
            if line.find('ATOM') != -1:
                if (resnew == 0):
                    r = t[4]
                    rn = t[3]
                    resnew = 1
                    resnum.append(r)
                    residuename.append(rn)
                    score.append(0)
                elif (r != t[4]):
                    r = t[4]
                    rn = t[3]
                    atomnum.append(atomnums)
                    resnum.append(r)
                    residuename.append(rn)
                    score.append(0)
                    atomnums = list()
                atomnums.append(atomcount)
                atomcount = atomcount + 1
        fp.close()
        x = list()
        tempx = list()
        ll = len(score)
        base = os.listdir(self.entry1.get())
        for a in base:
            if a.endswith(".log"):
                tempx.append(a)
        tempx.sort()
        tlen = len(tempx)
        ia = int(self.entry8.get())
        while (ia <= int(self.entry9.get()) and ia < tlen):
            x.append(tempx[ia])
            ia += 1
        c = 0
        i = 0
        for fn in x:
            fp = open(self.entry1.get() + "/" + fn, "r")
            if (c == 0):
                for line in fp:
                    t = line.split()
                    if (len(t) == 8):
                        if (t[0] == "Residue("):
                            for xx in range(ll):
                                if (int(resnum[xx]) == int(t[3])):
                                    score[xx] = float(t[5])
                    if (line == "PROTEIN BOX WATER FREE ENERGY COMPONENTS\n"):
                        c = c + 1
                        i = 0
                        break
            else:
                for line in fp:
                    t = line.split()
                    if (len(t) == 8):
                        if (t[0] == "Residue("):
                            for xx in range(ll):
                                if (int(t[3]) == int(resnum[xx])):
                                    score[xx] = score[xx] + float(t[5])
                                i = i + 1
                    if (line == "PROTEIN BOX WATER FREE ENERGY COMPONENTS\n"):
                        c = c + 1
                        i = 0
                        break
            fp.close()
        x = len(score)
        data = list()
        for i in range(x):
            data.append([resnum[i], score[i], residuename[i], atomnum[i]])
        data.sort(key=lambda s: (int(s[0])))
        for i in range(x):
            data[i][1] = data[i][1] / c
        scores = list()
        for i in range(len(data)):
            for j in range(len(data[i][3])):
                scores.append("{0:.3f}".format(data[i][1]))
        self.lb1.delete(0, END)
        self.lb2.delete(0, END)
        self.lb3.delete(0, END)

        for i in range(x):
            self.lb1.insert(END, data[i][0])
            self.lb2.insert(END, data[i][2])
            self.lb3.insert(END, round(data[i][1], 3))

        fp = open(tempfile.gettempdir() + "/temp.txt", "w")
        lx = len(scores)
        for i in range(lx):
            fp.write(str(scores[i]) + "\n")
        fp.close()
        self.b1.config(state="normal")
        self.b2.config(state="normal")
        self.b3.config(state="normal")

    def prevframe(self):
        global prevz, load
        if (load > 0):
            self.scale.set(self.scale.get() - 1)

    def nextframe(self):
        global prevz, load
        if (load > 0):
            self.scale.set(self.scale.get() + 1)

    def onScale(self, val):
        global prevz, load
        if (load > 0):
            v = self.lig1pdb[int(float(val))][14:19]
            self.var.set(v)
            if (self.scale.get() == 0):
                self.previous.config(state=DISABLED)
            if (self.scale.get() == len(self.lig1pdb) - 2):
                self.next.config(state="normal")
            if (self.scale.get() == 1):
                self.previous.config(state="normal")
            if (self.scale.get() == len(self.lig1pdb) - 1):
                self.next.config(state=DISABLED)
            if (self.wat.get() == 1):
                self.wsupdateview(self.entry4.get(), self.entry5.get(),
                                  self.entry6.get(), self.entry7.get(), prevz,
                                  int(self.scale.get()), self.vl.get())
            elif (self.lig.get() == 1):
                if (self.l1v.get() == 1):
                    vl = self.entry4.get()
                    hl = self.swapentry.get()
                if (self.l2v.get() == 1):
                    vl = self.swapentry.get()
                    hl = self.entry4.get()
                self.lsupdateview(vl, self.entry5.get(), self.entry6.get(),
                                  self.entry7.get(), prevz,
                                  int(self.scale.get()), hl, self.vl.get())

    def OnSelect(self, val):
        global prev
        sender = val.widget
        idx = sender.curselection()
        if (idx != ()):
            dis = self.lb1.get(idx)
            if (self.wat.get() == 1 or self.lig.get() == 1):
                self.wslistdisplay(prev, dis, int(self.scale.get()))
            elif (self.mm.get() == 1):
                self.wslistdisplay(prev, dis, 0)
            prev = dis

    def sortdata(self, sc):
        global dr1, dr2, dr3
        tableData1 = self.lb1.get(0, END)
        tableData2 = self.lb2.get(0, END)
        tableData3 = self.lb3.get(0, END)

        data = list()
        nv = len(tableData1)
        for x in range(nv):
            data.append([tableData1[x], tableData2[x], tableData3[x]])

        if (sc == 0):
            lab = self.b1.cget('text')
            if lab[0] == '[': self.b1.config(text=lab[4:])
            lab = self.b2.cget('text')
            if lab[0] == '[': self.b2.config(text=lab[4:])
            lab = self.b3.cget('text')
            if lab[0] == '[': self.b3.config(text=lab[4:])
            lab = self.b1.cget('text')
            if dr1 == 1: self.b1.config(text='[+] ' + lab)
            else: self.b1.config(text='[-] ' + lab)
            data.sort(key=lambda s: (int(s[sc])), reverse=dr1 == 1)
            dr1 = dr1 * -1
        if (sc == 1):
            lab = self.b1.cget('text')
            if lab[0] == '[': self.b1.config(text=lab[4:])
            lab = self.b2.cget('text')
            if lab[0] == '[': self.b2.config(text=lab[4:])
            lab = self.b3.cget('text')
            if lab[0] == '[': self.b3.config(text=lab[4:])
            lab = self.b2.cget('text')
            if dr2 == 1: self.b2.config(text='[+] ' + lab)
            else: self.b2.config(text='[-] ' + lab)
            data.sort(key=lambda s: (s[sc]), reverse=dr2 == 1)
            dr2 = dr2 * -1
        if (sc == 2):
            lab = self.b1.cget('text')
            if lab[0] == '[': self.b1.config(text=lab[4:])
            lab = self.b2.cget('text')
            if lab[0] == '[': self.b2.config(text=lab[4:])
            lab = self.b3.cget('text')
            if lab[0] == '[': self.b3.config(text=lab[4:])
            lab = self.b3.cget('text')
            if dr3 == 1: self.b3.config(text='[+] ' + lab)
            else: self.b3.config(text='[-] ' + lab)
            data.sort(key=lambda s: (float(s[sc])), reverse=dr3 == 1)
            dr3 = dr3 * -1
        nv = len(data)
        self.lb1.delete(0, 'end')
        self.lb2.delete(0, 'end')
        self.lb3.delete(0, 'end')
        for x in range(nv):
            self.lb1.insert(END, data[x][0])
            self.lb2.insert(END, data[x][1])
            self.lb3.insert(END, data[x][2])

    def onOpen(self):
        global load
        fold = tkFileDialog.askdirectory()
        self.entry1.delete(0, 'end')
        self.entry1.insert(0, fold)
        load = 0

    def onOpenMM(self):
        global load
        fold = tkFileDialog.askopenfilename()
        self.entry2.delete(0, 'end')
        self.entry2.insert(0, fold)
        load = 0

    def onOpenPDB(self):
        global load
        fold = tkFileDialog.askopenfilename()
        self.entry3.delete(0, 'end')
        self.entry3.insert(0, fold)
        load = 0

    def OnVsb(self, *args):
        self.lb1.yview(*args)
        self.lb2.yview(*args)
        self.lb3.yview(*args)

    def OnMouseWheel(self, event):
        self.lb1.yview("scroll", event.delta, "units")
        self.lb2.yview("scroll", event.delta, "units")
        self.lb3.yview("scroll", event.delta, "units")
        return "break"

    def Apply(self):
        global load, prevz
        if (load == 0):

            if (self.wat.get() == 1 or self.lig.get() == 1):
                self.changestate()
                self.base = os.listdir(self.entry1.get())
                pdb1 = list()
                for a in self.base:
                    matchObj = re.match(r'bound_mobile_\d{6}_0\.\d{5}\.pdb', a,
                                        re.M | re.I)
                    if matchObj:
                        pdb1.append(a)
                self.lig1pdb = list()
                self.lig2pdb = list()
                x = pdb1[1][22:27]

                for a in pdb1:

                    matchObj = re.match(r'bound_mobile_\d{6}_0\.' + x + '.pdb',
                                        a, re.M | re.I)
                    if matchObj:
                        self.lig1pdb.append(a)
                    else:
                        self.lig2pdb.append(a)
                self.lig1pdb.sort()
                self.lig2pdb.sort()
                self.scale.configure(from_=0, to=len(self.lig1pdb) - 1)
                self.scale.config(state="normal")

            elif (self.mm.get() == 1):
                self.loadmmpbsaresults()
                self.mmloadpdb(self.entry3.get())
                self.wsvisualizer(0, self.entry4.get(), self.entry5.get(),
                                  self.entry6.get(), self.entry7.get(),
                                  self.vl.get())

            if (self.wat.get() == 1):
                self.wsloadallpdb(self.lig1pdb, self.entry1.get())
                self.next.config(state="normal")
                v = self.lig1pdb[0][14:19]
                self.var.set(v)
                self.wsvisualizer(int(self.scale.get()), self.entry4.get(),
                                  self.entry5.get(), self.entry6.get(),
                                  self.entry7.get(), self.vl.get())
            elif (self.lig.get() == 1):
                if (self.l1v.get() == 1):
                    vl = self.entry4.get()
                    hl = self.swapentry.get()
                if (self.l2v.get() == 1):
                    vl = self.swapentry.get()
                    hl = self.entry4.get()
                self.wsloadallpdb(self.lig1pdb, self.entry1.get())
                self.next.config(state="normal")
                v = self.lig1pdb[0][14:19]
                self.var.set(v)
                self.lsvisualizer(int(self.scale.get()), vl, self.entry5.get(),
                                  self.entry6.get(), self.entry7.get(), hl,
                                  self.vl.get())
            load = 1

        else:  #old code "else:"

            if (self.wat.get() == 1):
                self.wsupdateview(self.entry4.get(), self.entry5.get(),
                                  self.entry6.get(), self.entry7.get(), prevz,
                                  int(self.scale.get()), self.vl.get())
            elif (self.lig.get() == 1):
                if (self.l1v.get() == 1):
                    vl = self.entry4.get()
                    hl = self.swapentry.get()
                if (self.l2v.get() == 1):
                    vl = self.swapentry.get()
                    hl = self.entry4.get()

                self.lsupdateview(vl, self.entry5.get(), self.entry6.get(),
                                  self.entry7.get(), prevz,
                                  int(self.scale.get()), hl, self.vl.get())
            elif (self.mm.get() == 1):
                self.wsupdateview(self.entry4.get(), self.entry5.get(),
                                  self.entry6.get(), self.entry7.get(), prevz,
                                  0, self.vl.get())
        prevz = self.entry5.get()
class StartPage(Frame):
	_title = "Bus Terminal Demo App"
	def __init__(self, parent, controller):
		Frame.__init__(self, parent)
		self.controller = controller
		self.parent = parent

		Style().configure("TButton", padding=(0, 5, 0, 5), font='serif 10')

		self.columnconfigure(0, pad=10)
		self.columnconfigure(1, pad=10)

		self.rowconfigure(0, pad=10)
		self.rowconfigure(1, pad=10)
		self.rowconfigure(2, pad=10)

		self.btn_wifi = Button(self,
			text="Wifi Connection Demo",
			command=lambda: controller.show_frame("Test_Wifi"), width=BTN_WIDTH)
		self.btn_wifi.grid(row=1, column=0)

		self.btn_gps_3g = Button(self,
			text="3G + GPS Demo",
			command=lambda: controller.show_frame("Test_GPS3G"), width=BTN_WIDTH)
		self.btn_gps_3g.grid(row=1, column=1)

		self.btn_cepas = Button(self,
			text="Cepas Reader Demo",
			command=lambda: controller.show_frame("Test_Cepas"), width=BTN_WIDTH)
		self.btn_cepas.grid(row=2, column=0)

		self.btn_zebra_scanner = Button(self,
			text="Zebra Scanner Demo",
			command=lambda: controller.show_frame("Test_ZebraScanner"), width=BTN_WIDTH)
		self.btn_zebra_scanner.grid(row=2, column=1)

		self.pack()

	def _enable_test(self):
		self.btn_wifi.config(state="normal")
		self.btn_gps_3g.config(state="normal")
		self.btn_cepas.config(state="normal")
		self.btn_zebra_scanner.config(state="normal")

	def _disable_test(self):
		self.btn_wifi.config(state=tk.DISABLED)
		self.btn_gps_3g.config(state=tk.DISABLED)
		self.btn_cepas.config(state=tk.DISABLED)
		self.btn_zebra_scanner.config(state=tk.DISABLED)
Пример #30
0
class App(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent
        self.initUI()
        self.centerWindow()

    def initUI(self):
        self.parent.title("Champion Pool Builder")
        self.parent.iconbitmap("assets/icon.ico")
        self.style = Style()
        self.style.theme_use("default")

        self.pack(fill=BOTH, expand=1)

        self.buildMode = True
        self.allPools = "assets/pools/"

        self.champsLabel = Label(text="Champions")
        self.champBox = Listbox(self)
        self.champBoxScrollbar = Scrollbar(self.champBox, orient=VERTICAL)
        self.champBox.config(yscrollcommand=self.champBoxScrollbar.set)
        self.champBoxScrollbar.config(command=self.champBox.yview)

        self.addButton = Button(self, text=">>", command=self.addChampToPool)
        self.removeButton = Button(self,
                                   text="<<",
                                   command=self.removeChampFromPool)
        self.saveButton = Button(self,
                                 text="Save champion pool",
                                 width=18,
                                 command=self.saveChampPool)
        self.loadButton = Button(self,
                                 text="Load champion pool",
                                 width=18,
                                 command=lambda: self.loadChampPools(1))
        self.confirmLoadButton = Button(self,
                                        text="Load",
                                        width=6,
                                        command=self.choosePool)
        self.getStringButton = Button(self,
                                      text="Copy pool to clipboard",
                                      width=18,
                                      command=self.buildPoolString)

        self.poolLabel = Label(text="Champion Pool")
        self.poolBox = Listbox(self)
        self.poolBoxScrollbar = Scrollbar(self.poolBox, orient=VERTICAL)
        self.poolBox.config(yscrollcommand=self.poolBoxScrollbar.set)
        self.poolBoxScrollbar.config(command=self.poolBox.yview)

        self.champsLabel.place(x=5, y=5)
        self.champBox.place(x=5, y=30)

        self.addButton.place(x=150, y=60)
        self.removeButton.place(x=150, y=100)
        self.saveButton.place(x=350, y=30)
        self.loadButton.place(x=350, y=60)
        self.getStringButton.place(x=350, y=90)

        self.poolLabel.place(x=200, y=5)
        self.poolBox.place(x=200, y=30)

        self.champBox.focus_set()
        self.loadChampions()

    def centerWindow(self):
        w = 500
        h = 200
        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()
        x = (sw - w) / 2
        y = (sh - h) / 2
        self.parent.geometry("%dx%d+%d+%d" % (w, h, x, y))

    def loadChampions(self, pooled=None):
        if pooled:
            with open("assets/Champions.txt", "r") as file:
                champions = file.read().splitlines()
            for champ in pooled:
                champions.remove(champ)
            for champion in sorted(champions):
                self.champBox.insert(END, champion)
        else:
            with open("assets/Champions.txt", "r") as file:
                champions = file.read().splitlines()
            for champion in sorted(champions):
                self.champBox.insert(END, champion)

    def choosePool(self):
        idx = self.poolBox.curselection()
        chosenPool = self.poolBox.get(idx)
        self.confirmLoadButton.place_forget()
        self.loadChampPools(2, chosenPool)

    def loadChampPools(self, level, pool=None):
        if level == 1:
            self.buildMode = False
            self.champBox.delete(0, END)
            self.poolBox.delete(0, END)
            self.saveButton.config(state=DISABLED)
            self.loadButton.config(state=DISABLED)
            self.getStringButton.config(state=DISABLED)
            self.confirmLoadButton.place(x=350, y=120)

            with open("assets/champpools.txt", "r") as file:
                champPools = file.read().splitlines()
            for pool in champPools:
                self.poolBox.insert(END, pool)
        elif level == 2:
            self.poolBox.delete(0, END)
            self.buildMode = True
            self.loadButton.config(state=NORMAL)
            self.saveButton.config(state=NORMAL)
            self.getStringButton.config(state=NORMAL)

            fileName = pool + ".txt"
            with open(self.allPools + fileName, "r") as file:
                champPool = file.read().splitlines()
                for champion in sorted(champPool):
                    self.poolBox.insert(END, champion)

            self.loadChampions(champPool)

    def addChampToPool(self):
        idx = self.champBox.curselection()
        if idx and self.buildMode:
            name = self.champBox.get(idx)
            self.poolBox.insert(END, name)
            self.champBox.delete(idx)

    def removeChampFromPool(self):
        idx = self.poolBox.curselection()
        if idx and self.buildMode:
            name = self.poolBox.get(idx)
            self.champBox.insert(END, name)
            self.poolBox.delete(idx)

    def checkIfPoolExists(self, title):
        with open("assets/champpools.txt", "r") as poolFile:
            pools = poolFile.read().splitlines()
            for pool in pools:
                if pool == title:
                    return True
            return False

    def saveChampPool(self):
        championPool = self.poolBox.get(0, END)
        poolTitle = TitleDialog(self.parent)
        fileName = self.allPools + poolTitle.title + ".txt"
        checker = self.checkIfPoolExists(poolTitle.title)

        if not checker:
            with open("assets/champpools.txt", "a") as file:
                file.write(poolTitle.title + "\n")
        with open(fileName, "w+") as file:
            for champion in sorted(championPool):
                file.write(champion + "\n")

    def buildPoolString(self):
        clipper = Tk()
        clipper.withdraw()
        clipper.clipboard_clear()

        championPool = self.poolBox.get(0, END)

        if championPool:
            championPoolString = ""
            for champion in championPool:
                championPoolString += "^" + champion + "$|"

            clipper.clipboard_append(championPoolString)
            clipper.destroy()
Пример #31
0
class CreationContainer(Frame):
    def __init__(self, parent, concF):
        Frame.__init__(self, master=parent)
        self.parent = parent
        self.type = StringVar(self)
        self.connection = StringVar(self)
        self.concF = concF
        self.load = concF.load
        self.initUI()
        self.grid(row=0, column=2, rowspan=2, columnspan=10)

    def initUI(self):
        self.actions = self.parent.link.getIDs()
        self.actions.append("New element")
        types = ["Info", "Speak", "Camera Change", "Movement"]
        self.type.set("Info")
        self.connection.set("New element")
        Style().configure("TButton",
                          padding=(0, 5, 0, 5),
                          background='WhiteSmoke')

        self.save = Button(self, text="Save")
        self.save.grid(row=2, column=0)

        self.existing_connections = Listbox(self)
        self.populateExistingConnections()
        self.existing_connections.grid(row=1, rowspan=2, column=5)

        self.next = OptionMenu(self, self.connection, *self.actions)
        self.next.grid(row=3, column=2)

        self.window = None
        if self.load != 0:
            self.connection.set(self.concF.index.get())
        self.connect(True)
        self.connection.set("New element")

        actOM = OptionMenu(self, self.type, *types, command=self.changeFrame)
        actOM.config(width=25)
        actOM.grid(row=0, column=0, columnspan=2, sticky="ew")

        self.backB = Button(self, text="Back", command=self.back)
        self.backB.grid(row=3, column=4)

        self.lead = Label(self, text="Leads to:")
        self.lead.grid(row=3, column=1)

        self.connectB = Button(self, text="Connect", command=self.lightConnect)
        self.connectB.grid(row=3, column=3)

        self.delete = Button(self, text="Delete", command=self.removeElement)
        self.delete.grid(row=3, column=0)

        self.follow_path = Button(self,
                                  text="Enter linked element",
                                  command=self.follow)
        self.follow_path.grid(row=0, column=6, rowspan=2)

        self.rmvRel = Button(self,
                             text="Remove this connection",
                             command=self.removeRelation)
        self.rmvRel.grid(row=1, column=6, rowspan=2)

        self.conLab = Label(self, text="This action connects to:")
        self.conLab.grid(row=0, column=5)

    def removeRelation(self):
        if not popup(
                "Are you sure you want to remove this relation?\n\nWARNING: ANY ACTIONS SOLELY DEPENDANT ON THIS RELATION WILL BE DELETED RECURSIVELY (TREE WILL BE PRUNED)"
                +
                "\n\ne.g.\nAction 1 => Action 2 => Action 3\nAction 1 =/> Action 2 => Action 3\nAction 1 => Nothing\n\nHowever:\nAction 1 => Action 2\nAction 5 => Action 2\n\n"
                +
                "Action 1 =/> Action 2\nAction 5 => Action 2\n\nAction 1 => Nothing\nAction 5 => Action 2",
                "Warning"):
            return
        self.parent.link.delRelation(
            self.parent.i,
            self.actions.index(self.existing_connections.get(ANCHOR)))
        self.populateExistingConnections()
        self.updateElementList()

    def removeElement(self):
        if not popup(
                "Are you sure you want to remove this relation?\n\nWARNING: ANY ACTIONS SOLELY DEPENDANT ON THIS ACTION AND ITS RELATIONS WILL BE DELETED RECURSIVELY (TREE WILL BE PRUNED)",
                "Warning"):
            return
        print "Deleting " + str(self.parent.i)
        self.parent.link.delItem(self.parent.i)
        self.back()

    def populateExistingConnections(self):
        self.existing_connections.delete(0, END)
        for relation in self.parent.link.getRelations(self.parent.i):
            self.existing_connections.insert(
                END,
                self.parent.link.getOneID(self.parent.link.getItem(relation)))

    def back(self):
        print "Back"
        self.destroy()
        SLBase(self.parent)

    def follow(self):
        if not self.existing_connections.get(ANCHOR):
            return
        self.connection.set(self.existing_connections.get(ANCHOR))
        self.connect(True)
        self.connection.set("New element")

    def lightConnect(self):
        if self.connection.get() == "New element":
            self.parent.link.addRelation(self.parent.i,
                                         self.parent.link.size())
            print "Linked to index " + str(self.parent.link.size())
            self.parent.i = self.parent.link.size()
            self.load = 0
            self.changeFrame(0)
            self.populateExistingConnections()
            self.updateElementList()
        else:
            self.parent.link.addRelation(
                self.parent.i, self.actions.index(self.connection.get()))
            print "Linked to index " + str(
                self.actions.index(self.connection.get()))
            self.window.save()
            self.populateExistingConnections()

    def connect(self, spawn):
        if self.connection.get() == "New element":
            if not spawn:
                self.parent.link.addRelation(self.parent.i,
                                             self.parent.link.size())
                print "Linked to index " + str(self.parent.link.size())
            self.parent.i = self.parent.link.size()
            self.load = 0
            self.changeFrame(0)
        else:
            if not spawn:
                self.parent.link.addRelation(
                    self.parent.i, self.actions.index(self.connection.get()))
                print "Linked to index " + str(
                    self.actions.index(self.connection.get()))
            self.parent.i = self.actions.index(self.connection.get())
            if isinstance(
                    self.parent.link.getItem(
                        self.actions.index(self.connection.get())), Info):
                self.type.set("Info")
            elif isinstance(
                    self.parent.link.getItem(
                        self.actions.index(self.connection.get())), Speak):
                self.type.set("Speak")
            elif isinstance(
                    self.parent.link.getItem(
                        self.actions.index(self.connection.get())), Camera):
                self.type.set("Camera Change")
            elif isinstance(
                    self.parent.link.getItem(
                        self.actions.index(self.connection.get())), Movement):
                self.type.set("Movement")
            self.load = self.parent.link.getItem(
                self.actions.index(self.connection.get()))
            self.changeFrame(0)

    def updateElementList(self):
        self.next["menu"].delete(0, "end")
        self.actions = self.parent.link.getIDs()
        for action in self.actions:
            self.next["menu"].add_command(label=action,
                                          command=Tkinter._setit(
                                              self.connection, action))
        self.next["menu"].add_command(label="New element",
                                      command=Tkinter._setit(
                                          self.connection, "New element"))

    def changeFrame(self, something):
        print "Changed to " + self.type.get()
        try:
            self.window.destroy()
        except AttributeError:
            pass
        if self.type.get() == "Speak":
            self.window = SpeakFrame(self, self.load)
        elif self.type.get() == "Camera Change":
            self.window = CameraFrame(self, self.load)
        elif self.type.get() == "Movement":
            self.window = MoveFrame(self, self.load)
        else:  # self.type.get() == "Info":
            self.window = InfoFrame(self, self.load)
        self.save.config(command=self.window.save)
        self.populateExistingConnections()
        self.updateElementList()
Пример #32
0
class Evolution(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent

        self.initUI()

    def configure(self):
        self.conf = Toplevel(self)
        self.conf.wm_title("Configure Universe")

        self.wc.reconfigure(self)

    def initUI(self):
        #create initial Beings object (not instantiated until live is called)
        self.wc = WorldConfiguration()

        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)

        self.columnconfigure(2, weight=1)
        self.columnconfigure(4, pad=7)
        self.rowconfigure(3, weight=1)

        lbl = Label(self, text="PyLife")
        lbl.grid(sticky=W, padx=25, pady=5)

        self.world = Canvas(self, background="#7474DB")
        self.world.grid(row=1,
                        column=0,
                        columnspan=3,
                        rowspan=8,
                        padx=5,
                        sticky=E + W + N + S)

        self.sbtn = Button(self, text="Stop")
        self.sbtn.grid(row=1, column=4, pady=5, sticky=E)

        self.bbox = Text(self, height=20, width=36)
        self.bbox.grid(row=3, column=4, padx=5, sticky=E + W + N + S)

        self.bbox1 = Text(self, height=11, width=36)
        self.bbox1.grid(row=4, column=4, padx=5, sticky=E + W + N + S)

        self.cbtn = Button(self, text="Close", command=self.parent.destroy)
        self.cbtn.grid(row=9, column=4, pady=5)

        self.cnfbtn = Button(self, text="Configure Universe")
        self.cnfbtn.grid(row=9, column=0, padx=5)

        self.timelbl = Text(self, height=1, width=10)
        self.timelbl.grid(row=2, column=4, pady=5)

        b = Beings(self)
        abtn = Button(
            self, text="Start", command=b.live
        )  #Beings(cnfbtn, world, 4, 10, sbtn, bbox, bbox1, timelbl).live)
        abtn.grid(row=1, column=4, pady=5, sticky=W)

        self.cnfbtn.config(command=b.configure)

    def close(self):
        self.parent.destroy