Ejemplo n.º 1
0
class cp_config_win(Toplevel):
    def __init__(self, parent):
        Toplevel.__init__(self)

        img = ImageTk.PhotoImage(file=os.path.join(os.path.dirname(__file__),
                                                   'Icons/LMS8001_PLLSim.png'))
        self.tk.call('wm', 'iconphoto', self._w, img)

        self.resizable(0, 0)
        self.parent = parent
        self.initUI()
        center_Window(self)
        self.protocol("WM_DELETE_WINDOW", self.on_Quit)

    def on_OK(self):
        self.on_Apply()
        self.on_Quit()

    def on_Apply(self):
        self.parent.cp_fc.set(float(self.entry_fc.get()) * 1.0e3)
        self.parent.cp_slope.set(float(self.entry_slope.get()))
        self.parent.pll.cp = lms8001_cp(fc=float(self.parent.cp_fc.get()),
                                        slope=float(
                                            self.parent.cp_slope.get()))
        self.parent.def_cp()

    def on_Quit(self):
        self.parent.cp_config_win = None
        self.destroy()

    def initUI(self):
        self.title('CP Noise Parameters')
        self.columnconfigure(0, pad=1)
        self.columnconfigure(1, pad=1)
        self.columnconfigure(2, pad=1)
        self.rowconfigure(0, pad=10)
        self.rowconfigure(1, pad=1)
        self.rowconfigure(2, pad=6)

        label1 = Label(self, text='Corner Frequency [kHz]')
        self.entry_fc = Entry(self, width=8)
        self.entry_fc.insert(END, str(self.parent.cp_fc.get() / 1.0e3))
        label1.grid(row=0, column=0, sticky=W)
        self.entry_fc.grid(row=0, column=1, sticky=W)

        label2 = Label(self, text='Noise slope [dB/dec]')
        self.entry_slope = Entry(self, width=8)
        self.entry_slope.insert(END, str(self.parent.cp_slope.get()))
        label2.grid(row=1, column=0, sticky=W)
        self.entry_slope.grid(row=1, column=1, sticky=W)

        button_OK = Button(self, text='OK', command=self.on_OK, width=10)
        button_Apply = Button(self,
                              text='Apply',
                              command=self.on_Apply,
                              width=10)
        button_Quit = Button(self, text='Quit', command=self.on_Quit, width=10)
        button_OK.grid(row=2, column=0, sticky=W + E + S)
        button_Apply.grid(row=2, column=1, sticky=W + E + S)
        button_Quit.grid(row=2, column=2, sticky=W + E + S)
    def initUI(self):
        self.parent.title("Test the Gauss point")
        self.pack(fill=BOTH, expand=True)
        self.fields = \
                'bulk_modulus', \
                'scale_hardening', \
                'max_stress_in', \
                'increment_strain', \
                'Nloop', \
                'initial_confinement', \
                'reference_pressure', \
                'modulus_n', \
                'cohesion', \
                'RMC_shape_k', \
                'dilation_angle_eta', \
                'diletion_scale'

        default_values = \
                        '1E7', \
                        '1E3', \
                        '3E4', \
                        '1E-4', \
                        '2', \
                        '1E5', \
                        '1E5', \
                        '0.7', \
                        '0.0', \
                        '1.0', \
                        '1.0', \
                        '1.0'
        # ==================
        # Entries for User input:
        self.entries = []
        for idx, field in enumerate(self.fields):
            row = Frame(self)
            row.pack(fill=X)
            labl = Label(row, text=field, width=30)
            labl.pack(side=LEFT, padx=5, pady=5)
            entry = Entry(row)
            entry.insert(END, default_values[idx])
            entry.pack(fill=X, padx=5, expand=True)
            self.entries.append((field, entry))
            # print field

        # ==================
        # Button for calculation
        frameButtonCalc = Frame(self)
        frameButtonCalc.pack(fill=X)
        calcButton = Button(frameButtonCalc,
                            text="calculate",
                            command=self.calculate)
        calcButton.pack(side=LEFT, padx=5, pady=5)

        # ==================
        # Raw Frame for plot
        self.canvasFrame = Frame(self)
        self.canvasFrame.pack(fill=BOTH, expand=True)
Ejemplo n.º 3
0
	def initUI(self, parameterDict, callback, validate, undoCallback):

		self.parent.title("Choose parameters for fit")

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

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

		count = 0
		entries = {}
		for key, value in parameterDict.iteritems():
			self.rowconfigure(count, pad=3)
			label = Label(self, text=key)
			label.grid(row=count, column=0)
			entry = Entry(self)
			entry.grid(row=count, column=1)
			entry.insert(0, value)
			entries[key] = entry
			count = count + 1

		def buttonCallback(*args): #the *args here is needed because the Button needs a function without an argument and the callback for function takes an event as argument
			try:
				newParameterDict = {}
				for key, value in entries.iteritems():
					newParameterDict[key] = value.get()
				self.parent.withdraw() #hide window
				feedback = callback(newParameterDict)
				if validate:
					if(askyesno("Validate", feedback,  default=YES)):
						self.parent.destroy() #clean up window
					else:
						undoCallback() #rollback changes done by callback
						self.parent.deiconify() #show the window again
				else:
					self.parent.withdraw()
					self.parent.destroy()
			except Exception as e:
				import traceback
				traceback.print_exc()
				self.parent.destroy()

		self.parent.bind("<Return>", buttonCallback)
		self.parent.bind("<KP_Enter>", buttonCallback)
		run = Button(self, text="Run fit", command=buttonCallback)
		run.grid(row=count, column=0)
		count = count + 1
		self.pack()
Ejemplo n.º 4
0
    def editarParroquia(self):
        t = Toplevel(self)
        t.wm_title("Estudio")

        Label(t, text="Nombre").grid(row=0, column=1)
        E2 = Entry(t)
        E2.insert(END, self.selectorParroquial.get())
        E2.grid(row=1, column=1)

        nombreOld = self.selectorParroquial.get()

        button1 = Button(t, text="Cancelar", command=lambda: t.destroy())
        button2 = Button(t, text="Guardar", command=lambda: self.actualizarParroquia(nombreOld, E2.get(), t))
        button3 = Button(t, text="Borrar", command=lambda: self.BorrarParroquial(E2.get(), t))

        button1.grid(row=2, column=0)
        button2.grid(row=2, column=1)
        button3.grid(row=2, column=2)
    def initUI(self):
        self.parent.title("Test the Gauss point")
        self.pack(fill=BOTH, expand=True)
        self.fields = \
                'bulk_modulus', \
                'Scale_Hardening', \
                'max_strain_in', \
                'increment_strain', \
                'Nloop'
        default_values = \
                        '16750', \
                        '1', \
                        '1E-2', \
                        '1E-4', \
                        '0'
        # ==================
        # Entries for User input:
        self.entries = []
        for idx, field in enumerate(self.fields):
            row = Frame(self)
            row.pack(fill=X)
            labl = Label(row, text=field, width=30)
            labl.pack(side=LEFT, padx=5, pady=5)
            entry = Entry(row)
            entry.insert(END, default_values[idx])
            entry.pack(fill=X, padx=5, expand=True)
            self.entries.append((field, entry))
            # print field

        # ==================
        # Button for calculation
        frameButtonCalc = Frame(self)
        frameButtonCalc.pack(fill=X)
        calcButton = Button(frameButtonCalc,
                            text="calculate",
                            command=self.calculate)
        calcButton.pack(side=LEFT, padx=5, pady=5)

        # ==================
        # Raw Frame for plot
        self.canvasFrame = Frame(self)
        self.canvasFrame.pack(fill=BOTH, expand=True)
Ejemplo n.º 6
0
class MyEntry:
#Класс для уменьшений объёма кода однотипных элементов для ввода параметров.
    def __init__(self, place_class, string_class, DefaultValue, choise_class = False, button_add = False):
#При создании принимается место прикрепления виджета и строковое значение для надписи.
# A string value to add a combobox or a button could be also inputed.

        def button_finfo():
            messagebox.showinfo(locale(u"ui_iftxt", Settingz["str_langu"]), button_add)
# Here it is a function to show information window.

        self.frame_class = Frame(place_class)
        self.frame_class.pack(side = TOP, fill = BOTH)
#Внутри – рамка для виджетов, растягивается по ширине окна.
        self.label_class = Label(self.frame_class, text = string_class)
        self.label_class.pack(side = LEFT)
#В ней – надписи для описания вводимых значений выровнены по левому краю.
        self.entry_class = Entry(self.frame_class, width = 15)
        self.entry_class.pack(side = RIGHT)
        self.entry_class.insert(0, DefaultValue)
#И элементы для ввода значений шириной в 15 знаков выровнены по правому краю.
        if choise_class:
            self.box_class = Combobox(self.frame_class, values = choise_class, width = 2)
            self.box_class.set(choise_class[0])
            self.box_class.pack(side = RIGHT)
        elif button_add:
            self.button_class = Button(self.frame_class, text = u"?", command = button_finfo, width = -1)
            self.button_class.pack(side = RIGHT)
# The combobox widget or the button will be created if it is set.

    def get(self):
        return(self.entry_class.get())
#Метод .get() передаётся от элемента для ввода объекту описываемого класса.
    def getbox(self):
        if self.box_class.get() in ["+", "~"]:
            return(True)
        else:
            return(False)
Ejemplo n.º 7
0
    def initUI(self):
        self.parent.title("Software Activation")
        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)

        if(self.needsActivated()):
            idEntry = Entry(self, width=36)
            idEntry.place(x=175, y=20)
            idEntry.delete(0, END)
            idEntry.insert(0, "Enter a product id")
            
            keyEntry = Entry(self, width=36)
            keyEntry.place(x=175, y=40)
            keyEntry.delete(0, END)
            keyEntry.insert(0, "Enter your license key")
            
            activateButton = Button(self, text="Activate",
                                    command=lambda:self.activate(
                                        idEntry.get(), keyEntry.get()))
            activateButton.place(x=250, y=65)
        else:
            label = Label(self, text="Product has already been activated")
            label.pack()
Ejemplo n.º 8
0
class Window(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()
        
    def initUI(self):
        self.parent.title("Network/Port Scan")
        self.style = Style()
        self.style.configure("TFrame", background = "#000000")
        self.style.configure("TCheckbutton", background = "#000000")
        self.style.configure("TButton", background = "#000000") 
        self.pack(fill=BOTH, expand=1)
        
        # Configure layout
        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=1)
        self.columnconfigure(2, weight=1)
        self.rowconfigure(5, weight = 1)
        self.rowconfigure(6, weight = 1)
        
        # Title of program
        lbl = Label(self, text="Network/Port Scan")
        lbl.grid(sticky = W, pady=5, padx=5)

        # Text Box
        area = ScrolledText(self, height = 20)
        area.grid(row=1, column=0, columnspan=3, rowspan=4, padx=3, sticky = N+S+E+W)
        self.area = area

        # IP Address Button
        self.ip = BooleanVar()
        ip_add_button = Checkbutton(self, text="IP Address",variable=self.ip, width=10)
        ip_add_button.grid(row = 1, column = 3, sticky = N)
        ip_add_button.config(anchor = W, activebackground = "red")

        # Port Button
        self.port = BooleanVar()
        port_button = Checkbutton(self, text="Ports", variable=self.port, width=10)
        port_button.grid(row = 1, column = 3)
        port_button.config(anchor = W, activebackground = "orange")
        
        # Host Name Button
        self.host = BooleanVar()
        host_name_button = Checkbutton(self, text="Host Name",variable=self.host, width=10)
        host_name_button.grid(row = 1, column = 3, sticky = S)
        host_name_button.config(anchor = W, activebackground = "yellow")
        
        # Gateway Button
        self.gateway = BooleanVar()
        gateway_btn = Checkbutton(self, text="Gateway", variable=self.gateway, width=10)
        gateway_btn.grid(row = 2, column = 3, sticky = N)
        gateway_btn.config(anchor = W, activebackground = "green")

        # Services Button
        self.service = BooleanVar()
        service_btn = Checkbutton(self, text="Services", variable = self.service, width=10)
        service_btn.grid(row = 2, column = 3)
        service_btn.config(anchor = W, activebackground = "blue")

        # Starting IP label
        ip_label = Label(self, text = "Starting IP:  ")
        ip_label.grid(row = 5, column = 0, pady = 1, padx = 3, sticky = W)
        self.ip_from = Entry(self, width = 15)
        self.ip_from.insert(0, start_ip)
        self.ip_from.grid(row = 5 , column = 0, pady = 1, padx = 3, sticky = E)

        # Ending IP label
        ip_label_two = Label(self, text = "Ending IP:  ")
        ip_label_two.grid(row = 5, column = 1, pady = 1, padx = 5, sticky = W)
        self.ip_to = Entry(self, width = 15)
        self.ip_to.insert(0, end_ip)
        self.ip_to.grid(row = 5 , column = 1, pady = 1, padx = 5, sticky = E)
        
        # Starting Port Label
        port_label = Label(self, text = "Starting Port:  ")
        port_label.grid(row = 5, column = 0, pady = 3, padx = 5, sticky = S+W)
        self.port_from = Entry(self, width = 15)
        self.port_from.insert(0, 0)
        self.port_from.grid(row = 5 , column = 0, pady = 1, padx = 5, sticky = S+E)

        # Ending Port Label
        port_label_two = Label(self, text = "Ending Port:  ")
        port_label_two.grid(row = 5, column = 1, pady = 3, padx = 5, sticky = S+W)
        self.port_to = Entry(self, width = 15)
        self.port_to.insert(0, 1025)
        self.port_to.grid(row = 5 , column = 1, pady = 1, padx = 5, sticky = S+E)

        # Scan Me 
        self_scan_button = Button(self, text="Scan Me", command = lambda : self.onClick(1), width = 33)
        self_scan_button.grid(row = 6, column = 1, sticky = N)

        # Scan near me Button
        scan_other_button = Button(self, text="Scan Near Me", width = 33, command = lambda : self.onClick(2))
        scan_other_button.grid(row = 6, column = 0, pady=1, sticky = N)
        
        # Clear button
        clear_button = Button(self, text="Clear text", command = self.clear_text, width = 12)
        clear_button.grid(row = 6, column = 3, pady=1, sticky = N)

        # Progress Bar
        self.label_scanning = Progressbar(self, orient = HORIZONTAL, length = 175)
        self.label_scanning.grid(row = 6, column = 0, columnspan = 4, padx = 7, pady = 7, sticky = E+S+W)
        self.label_scanning.config(mode = "determinate")

     
    # Clear what is in the text box.   
    def clear_text(self):
        self.area.delete(0.0, 'end')
        # empty my lists.
        my_ports[:] = []
        ip_address_up[:] = []
        target_host_name[:] = []
        target_port_up[:] = []
        
    # On click methods for scan me and scan others.
    def onClick(self, button_id):
        
        if button_id == 1:
            
            # Check to see if host button is marked
            if self.host.get() == 1:
                message = my_host_name()
                self.area.insert(0.0, message, ("warning"))
                self.area.tag_configure("warning", foreground = "blue")    
                
            # Check to see if ports button is marked   
            if self.port.get() == 1:
                # Check port entry widgets. 
                if self.port_from:
                    if self.port_to:
                        # Get the user input
                        starting_port = self.port_from.get()
                        ending_port = self.port_to.get()                
                        message, total = scan_my_ports(int(starting_port), int(ending_port))
                        for i in message:
                            new_message = "My TCP " + i + "\n"
                            self.area.insert(0.0, new_message, ("ports"))
                            #self.area.tag_configure("ports", foreground = "green")
                    
                    time = "The TCP port scan completed in: " + str(total) + "\n"
                    self.area.insert(0.0, time, ("timing"))
                    self.area.tag_configure("timing", foreground = "red")
                else:
                    self.area.insert(0.0, "No valid ports specified.")
                
            # Check to see if IP button is marked     
            if self.ip.get() == 1:
                message = my_ip()
                self.area.insert(0.0, message)
            
            # Check if gateway button is marked.
            if self.gateway.get() == 1:
                message = my_gateway()
                self.area.insert(0.0, message)

            # Check if service button is marked.
            if self.service.get() == 1:
                message, time = scan_my_services()
                for i in message:
                    new_message = i + "\n"
                    self.area.insert(0.0, new_message)
                new_time = "The local scan completed in: " + str(time) + "\n"
                self.area.insert(0.0. new_time, ("timing"))
                self.area.tag_configure("timing", foreground = "red")
                
        # If Scan other button is clicked. 
        elif button_id == 2:
            
            # Check other IP's 
            if self.ip.get() == 1:
                # Check the entry widgets.
                if self.ip_from:
                    if self.ip_to:
                        # Get the ranges from the entry widgets
                        starting_ipv4_address = self.ip_from.get()
                        ending_ipv4_address = self.ip_to.get()
                        
                        # Pass the values from the entry widgets into the function to scan nearby IP addresses.
                        message, time = ping_ip_other(starting_ipv4_address, ending_ipv4_address)
                        if message:
                            for i in message:
                                new_message = "The address:     {:>15} {:>15}".format(i,"is UP\n")
                                self.area.insert(0.0, new_message)
                        
                        total_time =  "Range scanned: " + str(starting_ipv4_address) +" to " + str(ending_ipv4_address) + "\n" + "The IP scan completed in:  " + str(time) + "\n"
                        self.area.insert(0.0, total_time, ("timing"))
                        self.area.tag_configure("timing", foreground = "red")

                else:
                    self.area.insert(0.0, "No Ip range is specified.")
                
                
            # Check others Ports
            if self.port.get() == 1:
                # Check port entry widgets. 
                if self.port_from:
                    if self.port_to:
                        # Get the user input
                        starting_port = self.port_from.get()
                        ending_port = self.port_to.get()
                        
                        
                        message, time = scan_ports_other(int(starting_port), int(ending_port))
                        if message:
                            for i in message:
                                new_msg = "The " + i +"\n"
                                self.area.insert(0.0, new_msg)
                        else:
                            new_msg = "Must scan nearby IP addresses first.\n"
                    
                    total_time = "TCP Port scan completed in: " + str(time) + "\n"
                    self.area.insert(0.0, total_time, ("timing"))
                    self.area.tag_configure("timing", foreground = "red")
                    
                else:
                    self.area.insert(0.0, "No Port range specified.")
            
            # Check other host names. Based on IP's scanned.
            if self.host.get() == 1:
                message, time = scan_host_other(ip_address_up)
                # Check that IP's of other computers were collected 
                if message:
                    for i in message:
                        new_message = "Host name: "+ str(i) + "\n"
                        self.area.insert(0.0, new_message)

                else:
                    new_msg = "Must scan nearby IP addresses first. \n"
                    self.area.insert(0.0, new_msg)
                    
                total = "The host scan completed in: " + str(time) + "\n"
                self.area.insert(0.0, total, ("timing"))
                self.area.tag_configure("timing", foreground = "red")
                
            # Check gateway return the gateway of the host machine again.
            if self.gateway.get() == 1:
                message = "\n" + str(my_gateway())
                self.area.insert(0.0, message)

            # Check what services are running on which IP and port.
            if self.service.get() == 1:
                message, time = services_other()
                if message:
                    for i in message:
                        new_message = i + "\n"
                        self.area.insert(0.0, new_message)
                    
                else:
                    new_msg = "The IP addresses and ports must be scanned first."
                    self.area.insert(0.0, new_msg)
                    
                new_time = "The service scan completed in: " + str(time) + "\n"
                self.area.insert(0.0, new_time, ("timing"))
                self.area.tag_configure("timing", foreground = "red")
                
        else:
            pass
Ejemplo n.º 9
0
class Open(Frame):

    def __init__(self, parent, **kw):
        Frame.__init__(self, **kw)
        self.parent = parent
        self.initUI()
        return

    def initUI(self):
        config = ConfigParser.ConfigParser()
        config.read('settings.ini')
        default_sheet = config.get('USER', 'default_spreadsheet')
        self.pack(fill=BOTH, expand=True)
        self.columnconfigure(1, weight=1)
        self.columnconfigure(3, pad=7)

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

        self.lblTsv = Label(self, text="Enter TSV Export:")
        self.lblTsv.grid(sticky=W, pady=4, padx=5)

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

        self.btnSubmit = Button(self, text="Submit", command=self.submit_text)
        self.btnSubmit.grid(row=6, column=4, padx=5)

        self.btnUpload = Button(self, text="Upload to GS", command = self.upload_db)
        self.btnUpload.grid(row=6, column=3, padx=5)

        self.btnCancel = Button(self, command=sys.exit, text="Quit")
        self.btnCancel.grid(row=6, column=2, padx=5)

        self.lblSheet = Label(self, text="Enter google sheets URL:")
        self.lblSheet.grid(row=5, sticky=W, pady=4, padx=4)

        self.sheetUrl = Entry(self)
        self.sheetUrl.grid(row=6, columnspan=2, sticky=W+E, padx=5, pady=5)
        self.sheetUrl.insert(0, default_sheet)
        return


    def submit_text(self):
        text = self.txtTsv.get("1.0", END)
        reader = RCLCReader()
        session = Session()
        try:
            db_objects, failed_lines = reader.read_tsv_text(text, session)
            session.commit()
            if len(failed_lines) > 0:
                errormsg = "{0} lines raised an error when reading data:\n".format(len(failed_lines))
                for line in failed_lines:
                    errormsg += line
                tkMessageBox.showerror("Error", errormsg)
            else:
                tkMessageBox.showinfo("Data Submission Complete", "All data has been submitted to DB successfully.")
        except Exception as e:
            ex_type, ex, tb = sys.exc_info()
            tkMessageBox.showerror("Error", "An error occured in reading the data: {0} {1}.\nTraceback: {2}.".format(e.message, str(e), traceback.format_tb(tb)))
        return


    def upload_db(self):
        session = Session()
        id_regex = "/spreadsheets/d/([a-zA-Z0-9-_]+)"
        id = re.search(id_regex, self.sheetUrl.get())
        if len(id.groups()) == 0:
            tkMessageBox.showerror("Error", "A valid google sheet ID could not be determined.")
        else:
            config = ConfigParser.ConfigParser()
            config.read('settings.ini')
            config.set('USER', 'default_spreadsheet', self.sheetUrl.get())
            fp = open('settings.ini', 'w+')
            config.write(fp)
            fp.close()
            try:
                writer = GSheetsWriter(spreadsheet_id=id.group(1))
                writer.update_loot_spreadsheet(session)
            except Exception as e:
                fp = open("delete_error.txt", "w+")
                ex_type, ex, tb = sys.exc_info()
                fp.write(str(ex_type))
                traceback.print_tb(tb, file=fp)
                fp.write(str(e.args) + "\n")
                fp.write(str(e) + "\n")
                fp.write(e.message + "\n")
                fp.flush()
                fp.close()
                tkMessageBox.showerror("Error", "An error occurred in uploading to google sheets: {0}".format(e.message))
            tkMessageBox.showinfo("", "Loot data has been uploaded to google spreadsheet.")
        return
Ejemplo n.º 10
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'值班')
Ejemplo n.º 11
0
class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent
        self.date = (time.strftime("%m_%d_%Y"))
        self.initUI()


    def initUI(self):
        self.parent.title("Experiment")
        self.pack(fill=BOTH, expand=True)

        self.frame1 = Frame(self)
        self.frame1.pack(fill=X)

        self.lbl1 = Label(self.frame1, text="Participant", width=10)
        self.lbl1.pack(side=LEFT, padx=5, pady=5)

        self.entry1 = Entry(self.frame1)
        self.entry1.pack(fill=X, padx=5, expand=True)

        self.frame2 = Frame(self)
        self.frame2.pack(fill=X)

        self.lbl2 = Label(self.frame2, text="Date", width=10)
        self.lbl2.pack(side=LEFT, padx=5, pady=5)

        self.entry2 = Entry(self.frame2)
        self.entry2.insert(0, self.date)
        self.entry2.state()
        self.entry2.pack(fill=X, padx=5, expand=True)

        self.frame3 = Frame(self)
        self.frame3.pack(fill=X)

        self.lbl3 = Label(self.frame3, text="COM Port", width=10)
        self.lbl3.pack(side=LEFT, padx=5, pady=5)

        self.entry3 = Entry(self.frame3)
        self.entry3.pack(fill=X, padx=5, expand=True)

        self.frame4 = Frame(self)
        self.frame4.pack(fill=X)

        self.accept = Button(self.frame4, text="Ok", command=self.makeVariables)
        self.accept.pack(fill=X, padx=5)


    def makeVariables(self):
        self.participant = self.entry1.get()
        self.port = self.entry3.get()
        self.verify()
        Frame.quit(self)


    def verify(self):
        mbox.showwarning('Check', 'Have you set the markers on Emotiv Toolbox?')


    def getName(self):
        return self.participant


    def getDate(self):
        return self.date

    def get_port(self):
        return self.port
Ejemplo n.º 12
0
class ChooseType(Frame):

    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        self.controller = controller
        ChooseType.socket = None
        ChooseType.create_player = None
        
        self.plx_name = "PLAYER"
        ChooseType.plx_type = "SPECTATOR"
        ChooseType.start_game = None
        label_1 = Label(self, text="Create character", font=TITLE_FONT, justify=CENTER, anchor=CENTER)
        label_2 = Label(self, text="Name: ")
        self.entry_1 = Entry(self)
        self.entry_1.insert(0, 'Player_')

        label_3 = Label(self, text="Join as: ")
        button1 = Button(self, text="FROG", command=self.callback_frog)
        button2 = Button(self, text="FLY", command=self.callback_fly)
        button3 = Button(self, text="SPECTATOR", command=self.callback_spec)
        ChooseType.button4 = 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()
        button1.pack()
        button2.pack()
        button3.pack()
        ChooseType.button4.pack(pady=20)
    
    def check_name(self,s):
        temp = False
        try:
            s.decode('ascii')
        except UnicodeEncodeError:
            print "it was not a ascii-encoded unicode string"
            tkMessageBox.showwarning("Error message", "Invalid player name")
        except UnicodeDecodeError:
            print "it was not a ascii-encoded unicode string"
            tkMessageBox.showwarning("Error message", "Invalid player name")
        else:
            if len(s) < 10 and len(s) >= 1:
                temp = True
            else:
                tkMessageBox.showwarning("Error message", "String lenght must be 1-10 characters")
        return temp
    
    # this frame works on callbacks so each button is processed separately
    # 1. get name
    # 2. check if the name is valid
    # 3. set player type
    # 4. **create server localy if the user comes from create server frame
    # 5. add player to the game (parameters: name, type)
    def callback_frog(self):
        self.plx_name = self.entry_1.get()
        if self.check_name(self.plx_name):
            ChooseType.plx_type = "FROG"
            self.create_server(CreateServer.plx_name,CreateServer.game_dim)
            self.callback_add_player()

    def callback_fly(self):
        self.plx_name = self.entry_1.get()
        if self.check_name(self.plx_name):
            ChooseType.plx_type = "FLY"
            self.create_server(CreateServer.plx_name,CreateServer.game_dim)
            self.callback_add_player()

    def callback_spec(self):
        self.plx_name = self.entry_1.get()
        if self.check_name(self.plx_name):
            ChooseType.plx_type = "SPECTATOR"
            self.create_server(CreateServer.plx_name,CreateServer.game_dim)
            self.callback_add_player()
        
    
    # join the game
    def callback_add_player(self):
        set_shut_down_level(1)
        data = "JOIN;"+ChooseType.plx_type
        if global_state==1:
            # directly (locally) access the game engine
            ChooseType.create_player = CreateServer.local_world.add_player(self.plx_name)
            CLIENTS.append((ChooseType.create_player, 'Local Player'))
            CreateServer.local_world.set_player_attr(ChooseType.create_player, 1, 'character', data)
            ChooseType.start_game = True
        else:
            GameWindow.vSer.set(globvar[0]) 
            host,_ = globvar[1]
            try:
                ChooseType.socket = s = socket.socket(AF_INET,SOCK_STREAM)
                s.connect((host,QUAD_AXE))
                # ping-pong communication:  
                # 1. client: ADD_ME;Player1 -> server: ADDED -> client
                # 2. client: JOIN;FROG -> server
                data2 = 'ADD_ME;'+self.plx_name
                self.socket.send(data2.encode())
                buf = ChooseType.socket.recv(100)
                message = buf.decode('utf-8')
                if message == "ADDED":
                    print 'Added player!'
                    ChooseType.start_game = True
                    ChooseType.socket.send(data.encode())
            except Exception as e:
                print e
                ChooseType.start_game = False
                print 'Cannot connect to server!'
        self.controller.show_frame("GameWindow")
    
    # this is the function that initiates: engine, server and broadcast
    def create_server(self,s_name,field_xy):
        if global_state == 0 or shut_down_level != 0:
            return
        ChooseType.button4.config(state="disabled")
        # addition game field size check
        GameWindow.vSer.set(s_name)
        m_split=field_xy.split('X')
        try:
            x_size = int(m_split[0])
        except:
            x_size = 10  
        try:
            y_size = int(m_split[1])
        except:
            y_size = 10                    
        if (x_size < 2 or x_size > MAX_GF_SIZE):
            print 'The gamefield\'s dimensions size should be between 3 and '+str(MAX_GF_SIZE)+' !'
            x_size = 10             
        if (y_size < 2 or y_size > MAX_GF_SIZE):
            print 'The gamefield\'s dimensions size should be between 3 and '+str(MAX_GF_SIZE)+' !'
            y_size = 10
        # Start the world
        CreateServer.local_world = engine.World(x_size,y_size)
        et = engine.engine_thread(ENGINE_SLEEP, CreateServer.local_world)
        et.start()
        THREADS.append(et)       
        # Initialize the server
        server_sock = server.init_server()
        set_globvar(server_sock.getsockname())
        st = server.server_thread(s_name, server_sock, CreateServer.local_world)        
        st.start() # Start the server thread
        THREADS.append(st)     
        # Initialize the broadcaster
        bc_sock = server.init_broadcaster()
        # Start broadcasting thread
        bt = server.announce_bc_thread(bc_sock, BROADCASTING_PORT, s_name, CreateServer.local_world)
        bt.start()
        THREADS.append(bt)
Ejemplo n.º 13
0
class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent

        self.initUI()

    def initUI(self):

        self.parent.title("Append Data")
        self.pack(fill=BOTH, expand=True)
        labelfont20 = ('Roboto', 15, 'bold')
        labelfont10 = ('Roboto', 10, 'bold')
        labelfont8 = ('Roboto', 8, 'bold')

        frame0 = Frame(self)
        frame0.pack()

        lbl0 = Label(frame0, text="Hi Nakul")
        lbl0.config(font=labelfont20)
        lbl0.pack(padx=5, pady=5)
        lbl00 = Label(frame0, text="Fill the data here")
        lbl00.config(font=labelfont10)
        lbl00.pack(padx=5, pady=5)

        ####################################
        frame1 = Frame(self)
        frame1.pack()
        frame1.place(x=50, y=100)

        lbl1 = Label(frame1, text="Name", width=15)
        lbl1.pack(side=LEFT, padx=7, pady=5)

        self.entry1 = Entry(frame1, width=20)
        self.entry1.pack(padx=5, expand=True)

        ####################################
        frame2 = Frame(self)
        frame2.pack()
        frame2.place(x=50, y=130)

        lbl2 = Label(frame2, text="F Name", width=15)
        lbl2.pack(side=LEFT, padx=7, pady=5)

        self.entry2 = Entry(frame2)
        self.entry2.pack(fill=X, padx=5, expand=True)

        ######################################
        frame3 = Frame(self)
        frame3.pack()
        frame3.place(x=50, y=160)

        lbl3 = Label(frame3, text="DOB(D/M/Y)", width=15)
        lbl3.pack(side=LEFT, padx=7, pady=5)

        self.entry3 = Entry(frame3)
        self.entry3.pack(fill=X, padx=5, expand=True)

        #######################################
        frame4 = Frame(self)
        frame4.pack()
        frame4.place(x=50, y=190)

        lbl4 = Label(frame4, text="Medium(H/E)", width=15)
        lbl4.pack(side=LEFT, padx=7, pady=5)

        self.entry4 = Entry(frame4)
        self.entry4.pack(fill=X, padx=5, expand=True)

        ##########################################
        frame5 = Frame(self)
        frame5.pack()
        frame5.place(x=50, y=225)
        MODES = [
            ("M", "Male"),
            ("F", "Female"),
        ]
        lbl5 = Label(frame5, text="Gender", width=15)
        lbl5.pack(side=LEFT, padx=7, pady=5)

        global v
        v = StringVar()
        v.set("Male")  # initialize

        for text, mode in MODES:
            b = Radiobutton(frame5, text=text, variable=v, value=mode)
            b.pack(side=LEFT, padx=10)

        ############################################
        #####printing line
        lbl5a = Label(
            text="___________________________________________________")
        lbl5a.pack()
        lbl5a.place(x=45, y=255)

        ############################################
        frame6 = Frame(self)
        frame6.pack()
        frame6.place(x=50, y=290)

        lbl6 = Label(frame6, text="Phone No:", width=15)
        lbl6.pack(side=LEFT, padx=7, pady=5)

        self.entry6 = Entry(frame6)
        self.entry6.pack(fill=X, padx=5, expand=True)

        ################################################

        frame7 = Frame(self)
        frame7.pack()
        frame7.place(x=50, y=320)

        lbl7 = Label(frame7, text="Landline No:", width=15)
        lbl7.pack(side=LEFT, padx=7, pady=5)

        self.entry7 = Entry(frame7)
        self.entry7.pack(fill=X, padx=5, expand=True)

        ###############################################
        frame8 = Frame(self)
        frame8.pack()
        frame8.place(x=50, y=350)

        lbl8 = Label(frame8, text="Email:", width=15)
        lbl8.pack(side=LEFT, padx=7, pady=5)

        self.entry8 = Entry(frame8)
        self.entry8.pack(fill=X, padx=5, expand=True)

        #############################################
        frame9 = Frame(self)
        frame9.pack()
        frame9.place(x=50, y=380)

        lbl9 = Label(frame9, text="HomeTown:", width=15)
        lbl9.pack(side=LEFT, padx=7, pady=5)

        self.entry9 = Entry(frame9)
        self.entry9.pack(fill=X, padx=5, expand=True)

        ###############################################
        frame10 = Frame(self)
        frame10.pack()
        frame10.place(x=60, y=415)

        lbl10 = Label(frame10, text="Address:")
        lbl10.pack(padx=5, pady=5)

        self.entry10 = Text(frame10, height=5, width=28)
        self.entry10.pack(padx=5, expand=True)

        ##############################################

        #############################################

        frame11 = Frame(self)
        frame11.pack()
        frame11.place(x=350, y=100)

        lbl11x = Label(frame11, text="_______Class 10th Data_______")
        lbl11x.pack(padx=0, pady=0)

        lbl11 = Label(text="%", width=15)
        lbl11.pack(side=LEFT, padx=0, pady=0)
        lbl11.place(x=350, y=130)

        self.entry11 = Entry(width=12)
        self.entry11.pack(padx=1, expand=True)
        self.entry11.place(x=420, y=130)

        lbl11a = Label(text="Passing Year", width=15)
        lbl11a.pack(padx=0, pady=2)
        lbl11a.place(x=350, y=160)

        self.entry11a = Entry(width=12)
        self.entry11a.pack(padx=1, expand=True)
        self.entry11a.place(x=420, y=160)

        lbl11b = Label(text="Board Name", width=15)
        lbl11b.pack(padx=0, pady=2)
        lbl11b.place(x=350, y=190)

        self.entry11b = Entry(width=12)
        self.entry11b.pack(padx=1, expand=True)
        self.entry11b.place(x=420, y=190)

        ####################################################
        frame12 = Frame(self)
        frame12.pack()
        frame12.place(x=510, y=100)

        lbl12x = Label(frame12, text="_______Class 12th Data_______")
        lbl12x.pack(padx=0, pady=0)

        lbl12 = Label(text="%", width=15)
        lbl12.pack(side=LEFT, padx=0, pady=0)
        lbl12.place(x=510, y=130)

        self.entry12 = Entry(width=12)
        self.entry12.pack(padx=1, expand=True)
        self.entry12.place(x=580, y=130)

        lbl12a = Label(text="Passing Year", width=15)
        lbl12a.pack(padx=0, pady=2)
        lbl12a.place(x=510, y=160)

        self.entry12a = Entry(width=12)
        self.entry12a.pack(padx=1, expand=True)
        self.entry12a.place(x=580, y=160)

        lbl12b = Label(text="Board Name", width=15)
        lbl12b.pack(padx=0, pady=2)
        lbl12b.place(x=510, y=190)

        self.entry12b = Entry(width=12)
        self.entry12b.pack(padx=1, expand=True)
        self.entry12b.place(x=580, y=190)

        #####################################################
        frame13 = Frame(self)
        frame13.pack()
        frame13.place(x=670, y=100)

        lbl13x = Label(frame13, text="________B.Tech Data_________")
        lbl13x.pack(padx=0, pady=0)

        lbl13 = Label(text="%", width=15)
        lbl13.pack(side=LEFT, padx=0, pady=0)
        lbl13.place(x=670, y=130)

        self.entry13 = Entry(width=12)
        self.entry13.pack(padx=1, expand=True)
        self.entry13.place(x=740, y=130)

        lbl13a = Label(text="Passing Year", width=15)
        lbl13a.pack(padx=0, pady=2)
        lbl13a.place(x=670, y=160)

        self.entry13a = Entry(width=12)
        self.entry13a.pack(padx=1, expand=True)
        self.entry13a.place(x=740, y=160)

        lbl13b = Label(text="College", width=15)
        lbl13b.pack(padx=0, pady=2)
        lbl13b.place(x=670, y=190)

        self.entry13b = Entry(width=12)
        self.entry13b.pack(padx=1, expand=True)
        self.entry13b.place(x=740, y=190)

        ####################################################

        frame14 = Frame(self)
        frame14.pack()
        frame14.place(x=380, y=255)

        lbl14 = Label(frame14, text="Any Other Info:")
        lbl14.pack(padx=5, pady=5)

        self.entry14 = Text(frame14, height=5, width=28)
        self.entry14.pack(padx=5, expand=True)

        frame15 = Frame(self)
        frame15.pack()
        frame15.place(x=650, y=290)

        openButton = Button(frame15,
                            text="Attatch Resume",
                            width=15,
                            command=self.openResume)
        openButton.pack(padx=5, pady=5)
        self.entry15 = Entry(frame15)
        self.entry15.pack(fill=X, padx=4, expand=True)
        #############################################################
        frame16 = Frame(self)
        frame16.pack()
        frame16.place(x=450, y=500)

        closeButton = Button(frame16,
                             text="SUBMIT",
                             width=35,
                             command=self.getDatax)
        closeButton.pack(padx=5, pady=5)

        #######################################
        framexxx = Frame(self)
        framexxx.pack()
        framexxx.place(x=700, y=600)
        self.xxx = Label(framexxx, text="Recent Changes Will Appear Here")
        self.xxx.config(font=labelfont8)
        self.xxx.pack()

        #######################################

        frame000 = Frame(self)
        frame000.pack()
        frame000.place(x=50, y=600)

        self.lbl000 = Label(frame000,
                            text="Beta/Sample2.0 | (c) Nakul Rathore")
        self.lbl000.config(font=labelfont8)
        self.lbl000.pack(padx=5, pady=5)

    def openResume(self):
        ftypes = [('All files', '*')]
        dlg = tkFileDialog.Open(self, filetypes=ftypes, initialdir='C:/Users/')
        global x15
        fl = dlg.show()
        #file name
        x15 = fl
        temp1 = os.path.basename(fl)
        global temp2
        temp2 = os.path.splitext(temp1)[0]

        self.entry15.delete(0, 'end')
        self.entry15.insert(0, temp2)

        #####################

    def getDatax(self):
        x1 = self.entry1.get()
        x2 = self.entry2.get()
        x3 = self.entry3.get()
        x4 = self.entry4.get()

        x5 = v.get()

        x6 = int(self.entry6.get())
        x7 = int(self.entry7.get())
        x8 = self.entry8.get()
        x9 = self.entry9.get()

        x10 = self.entry10.get('1.0', 'end')

        x11 = int(self.entry11.get())
        x11a = int(self.entry11a.get())
        x11b = self.entry11b.get()

        x12 = int(self.entry12.get())
        x12a = int(self.entry12a.get())
        x12b = self.entry12b.get()

        x13 = int(self.entry13.get())
        x13a = int(self.entry13a.get())
        x13b = self.entry13b.get()

        x14 = self.entry14.get('1.0', 'end')

        list1 = [
            x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x11a, x11b, x12,
            x12a, x12b, x13, x13a, x13b, x14,
            "=HYPERLINK(" + "\"" + x15 + "\"" + "," + "\"" + temp2 + "\"" + ")"
        ]

        wb = openpyxl.load_workbook('..\database\database.xlsx')
        ws = wb.active
        print(wb.get_sheet_names())
        max_row = ws.get_highest_row()
        #max_col = ws.get_highest_column()
        max_col = 21
        print max_row

        for i in xrange(1, max_col + 1):
            #print list1[i]
            ws.cell(row=max_row + 1, column=i).value = list1[i - 1]
        ws.cell(row=max_row + 1,
                column=max_col).font = Font(color="0000FF", underline='single')
        ws.cell(row=max_row + 1,
                column=max_col).alignment = Alignment(horizontal='center')
        wb.save('..\database\database.xlsx')

        self.entry1.delete(0, 'end')
        self.entry2.delete(0, 'end')
        self.entry3.delete(0, 'end')
        self.entry4.delete(0, 'end')

        self.entry6.delete(0, 'end')
        self.entry7.delete(0, 'end')
        self.entry8.delete(0, 'end')
        self.entry9.delete(0, 'end')
        self.entry10.delete('1.0', '2.0')
        self.entry11.delete(0, 'end')
        self.entry11a.delete(0, 'end')
        self.entry11b.delete(0, 'end')
        self.entry12.delete(0, 'end')
        self.entry12a.delete(0, 'end')
        self.entry12b.delete(0, 'end')
        self.entry13.delete(0, 'end')
        self.entry13a.delete(0, 'end')
        self.entry13b.delete(0, 'end')

        self.entry14.delete('1.0', '2.0')

        self.xxx.config(text="Recent Changes Made For : " + x1)
Ejemplo n.º 14
0
class IniGenGui(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUIGlobals()

    def initUIGlobals(self):

        self.parent.title("Ini Generator")

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

        f1 = Frame(self)
        f1.grid(row=0, column=0, padx=10, sticky=N + S + E + W)

        f11 = LabelFrame(f1, text="Algorithms to Run")
        f11.grid(row=0, column=0)
        row = 0

        self.check_algs_value_list = []
        self.check_algs_map = {}
        for alg in algorithms:
            if alg == 'clean':
                continue
            check_alg_value = IntVar()
            check_alg = Checkbutton(f11,
                                    text=alg,
                                    variable=check_alg_value,
                                    justify=LEFT,
                                    width=25)
            check_alg.grid(row=row, column=0, sticky=W + E)
            self.check_algs_value_list.append(check_alg_value)
            self.check_algs_map[alg] = check_alg_value
            row += 1

        f111 = Frame(f11)
        f111.grid(row=row, column=0)

        button_checkall = Button(f111, text="All", command=self.checkall)
        button_checkall.grid(row=0, column=0, sticky=W + E)
        button_uncheckall = Button(f111, text="None", command=self.uncheckall)
        button_uncheckall.grid(row=0, column=1, sticky=W + E)

        row = 0

        f12 = Frame(f1)
        f12.grid(row=1, column=0, pady=20, sticky=S + W + E)

        f121 = LabelFrame(f12, text='Location of uPMU')
        f121.grid(row=0, column=0)

        self.radio_loc_string = StringVar()
        locations.append('Other Location')
        for loc in locations:
            radio_loc = Radiobutton(f121,
                                    text=loc,
                                    variable=self.radio_loc_string,
                                    value=loc,
                                    command=self.set_loc,
                                    justify=LEFT,
                                    width=25)
            radio_loc.grid(row=row, column=0, sticky=W + E)
            row += 1

        self.entry_otherloc = Entry(f121)

        f2 = Frame(self)
        f2.grid(row=0, column=1, padx=10, sticky=N + S + E + W)

        f21 = LabelFrame(f2, text='Name of uPMU (raw)')
        f21.grid(row=0)
        row = 0

        f211 = Frame(f21)
        f211.grid(row=row)
        row += 1

        self.entry_namesearch = Entry(f211)
        self.entry_namesearch.grid(row=0, column=0, sticky=E + W)

        button_namesearch = Button(f211,
                                   text="Search",
                                   command=self.namesearch)
        button_namesearch.grid(row=0, column=1, sticky=W + E)

        self.lstbx_namelist = Listbox(f21)
        self.lstbx_namelist.bind("<Double-Button-1>", self.namelist_select)
        self.lstbx_namelist.grid(row=row, sticky=W + E)
        row += 1

        f212 = Frame(f21)
        f212.grid(row=row)
        row += 1

        label_nameselected = Label(f212, text="Selected:")
        label_nameselected.grid(row=0, column=0)

        self.entry_nameselected = Entry(f212, state=DISABLED)
        self.entry_nameselected.grid(row=0, column=1, sticky=W + E)

        f22 = LabelFrame(f2, text="Name of uPMU (abbr)")
        f22.grid(row=1, sticky=W + E, pady=10)
        self.entry_name = Entry(f22, width=30)
        self.entry_name.grid(row=0, column=0, sticky=E + W)

        f23 = LabelFrame(f2, text="Name of Reference uPMU (clean)")
        f23.grid(row=2, pady=10)
        row = 0

        f231 = Frame(f23)
        f231.grid(row=row)
        row += 1

        self.entry_refnamesearch = Entry(f231)
        self.entry_refnamesearch.grid(row=0, column=0, sticky=E + W)

        button_refnamesearch = Button(f231,
                                      text="Search",
                                      command=self.refnamesearch)
        button_refnamesearch.grid(row=0, column=1, sticky=W + E)

        self.lstbx_refnamelist = Listbox(f23)
        self.lstbx_refnamelist.bind("<Double-Button-1>",
                                    self.refnamelist_select)
        self.lstbx_refnamelist.grid(row=row, sticky=W + E)
        row += 1

        f232 = Frame(f23)
        f232.grid(row=row)
        row += 1

        label_refnameselected = Label(f232, text="Selected:")
        label_refnameselected.grid(row=0, column=0)

        self.entry_refnameselected = Entry(f232, state=DISABLED)
        self.entry_refnameselected.grid(row=0, column=1, sticky=W + E)

        button_gen = Button(self,
                            text="Generate Files",
                            command=self.generate_files)
        button_gen.grid(row=1, column=0, columnspan=2, sticky=W + E)

        self.pack()

    def generate_files(self):
        algs = []
        for alg in self.check_algs_map:
            if self.check_algs_map[alg].get() == 1:
                algs.append(alg)

        if self.radio_loc_string.get() == "Other Location":
            location = self.entry_otherloc.get()
        else:
            location = self.radio_loc_string.get()

        name_raw = self.entry_nameselected.get()
        name = self.entry_name.get()
        ref_name = self.entry_refnameselected.get()

        uuid_map = self.get_uuid_map(name_raw)
        reference_uuid_map = self.get_ref_uuid_map(ref_name)

        IniGenAutomation(location, name_raw, name, uuid_map, ref_name,
                         reference_uuid_map, algs)

    def namesearch(self):
        searchterm = self.entry_namesearch.get()
        if searchterm.contains("/"):
            loc = searchterm.split('/')
            searchphrase = '/upmu/%{0}%/%{1}%/%'.format(loc[0], loc[1])
        else:
            searchphrase = '/upmu/%{0}%/%'.format(searchterm)
        search_results = self.search(searchterm, searchphrase)
        self.lstbx_namelist.delete(0, END)
        if len(search_results) == 0:
            tkMessageBox.showwarning(
                'Search Error',
                'No matches from search for \'{0}\''.format(searchterm))
        else:
            for result in search_results:
                self.lstbx_namelist.insert(END, result)

    def refnamesearch(self):
        searchterm = self.entry_refnamesearch.get()
        searchphrase = '/Clean/%{0}%/%'.format(searchterm)
        search_results = self.search(searchterm, searchphrase)
        self.lstbx_refnamelist.delete(0, END)
        if len(search_results) == 0:
            tkMessageBox.showwarning(
                'Search Error',
                'No matches from search for \'{0}\''.format(searchterm))
        else:
            for result in search_results:
                self.lstbx_refnamelist.insert(END, result)

    def search(self, searchterm, searchphrase):
        connection = _mysql.connect(host="128.32.37.231",
                                    port=3306,
                                    user="******",
                                    passwd="moresecuredataftw",
                                    db='upmu')
        connection.query(
            "SELECT * FROM uuidpathmap WHERE path LIKE '{0}'".format(
                searchphrase))
        results = connection.store_result()
        queried_data = {}
        result = results.fetch_row()
        while result != tuple():
            queried_data[result[0][0]] = result[0][1]
            result = results.fetch_row()
        search_results = set()
        for path in queried_data:
            dirs = path.split('/')
            if searchterm in dirs[2]:
                search_results.add(dirs[2])
        return search_results

    def set_loc(self):
        if self.radio_loc_string.get() == "Other Location":
            self.entry_otherloc.grid(sticky=W + E)
        else:
            self.entry_otherloc.grid_forget()

    def checkall(self):
        for check in self.check_algs_value_list:
            check.set(1)

    def uncheckall(self):
        for check in self.check_algs_value_list:
            check.set(0)

    def namelist_select(self, event):
        selected_index = self.lstbx_namelist.curselection()
        selected = self.lstbx_namelist.get(selected_index)
        self.entry_nameselected.configure(state=NORMAL)
        self.entry_nameselected.delete(0, END)
        self.entry_nameselected.insert(0, selected)
        self.entry_nameselected.configure(state=DISABLED)

    def refnamelist_select(self, event):
        selected_index = self.lstbx_refnamelist.curselection()
        selected = self.lstbx_refnamelist.get(selected_index)
        self.entry_refnameselected.configure(state=NORMAL)
        self.entry_refnameselected.delete(0, END)
        self.entry_refnameselected.insert(0, selected)
        self.entry_refnameselected.configure(state=DISABLED)

    def get_uuid_map(self, name):
        uuid_map = {}
        connection = _mysql.connect(host="128.32.37.231",
                                    port=3306,
                                    user="******",
                                    passwd="moresecuredataftw",
                                    db='upmu')
        connection.query(
            "SELECT * FROM uuidpathmap WHERE path LIKE '/upmu/{0}/%'".format(
                name))
        results = connection.store_result()
        result = results.fetch_row()
        while result != tuple():
            path = result[0][0].split('/')
            uuid_map[path[-1]] = result[0][1]
            result = results.fetch_row()
        return uuid_map

    def get_ref_uuid_map(self, name):
        uuid_map = {}
        connection = _mysql.connect(host="128.32.37.231",
                                    port=3306,
                                    user="******",
                                    passwd="moresecuredataftw",
                                    db='upmu')
        connection.query(
            "SELECT * FROM uuidpathmap WHERE path LIKE '/Clean/{0}/%'".format(
                name))
        results = connection.store_result()
        result = results.fetch_row()
        while result != tuple():
            path = result[0][0].split('/')
            uuid_map[path[-2]] = result[0][1]
            result = results.fetch_row()
        return uuid_map
Ejemplo n.º 15
0
class Window(Frame):
    def __init__(self, parent, window_type):
        Frame.__init__(self, parent, msg=None)

        self.parent = parent
        if window_type == "main":
            self.initUI_main()
        if window_type == "err":
            self.initUI_err()

    def initUI_main(self):
        self.parent.title("Personal Helper")
        self.pack(fill=BOTH, expand=True)

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

        lbl = Label(self, text="Windows")
        lbl.grid(sticky=W + N, pady=4, padx=5)

        check_box = {"work": IntVar(), "boost": IntVar()}

        check1 = Checkbutton(self,
                             text="work-Mode",
                             variable=check_box["work"])
        check1.grid(row=7, column=0)

        check2 = Checkbutton(self,
                             text="boost games",
                             variable=check_box["boost"])
        check2.grid(row=7, column=1)

        ### old version, may be used again later
        area = Treeview(self)
        area['show'] = 'headings'
        area["columns"] = ("one", "two", "three", "four")
        area.column("one", width=10)
        area.column("two", width=10)
        area.column("three", width=10)
        area.column("four", width=10)
        area.heading("one", text="process name")
        area.heading("two", text="Priority")
        area.heading("three", text="PID")
        area.heading("four", text="Usage")
        ###about this part
        #area.grid(row=1, column=0, columnspan=2, rowspan=4, padx=5, sticky=E + W + S + N)
        #######

        #comboboxes and relevant buttons

        self.block_drop = Combobox(self, postcommand=self.update_blocked)
        self.block_drop['values'] = working_bans
        self.block_drop.current(0)
        self.block_drop.grid(row=1, column=1, pady=1)
        self.entry = Entry(self)
        self.entry.insert(0, "enter to block")
        self.entry.grid(row=1, column=4)

        block_btn_remv = Button(self,
                                text="Remove",
                                command=lambda: remove_from_list(
                                    working_bans, self.block_drop.get()))
        block_btn_remv.grid(row=1, column=2)

        block_btn_add = Button(
            self,
            text="Add",
            command=lambda: add_to_list(working_bans, self.entry.get(), self.
                                        entry, defults["block"]))
        block_btn_add.grid(row=1, column=3)

        ############
        #boosted combo
        self.boost_drop = Combobox(self, postcommand=self.update_boosted)
        self.boost_drop['values'] = boosted
        self.boost_drop.current(0)
        self.boost_drop.grid(row=2, column=1, pady=1)
        self.entry2 = Entry(self)
        self.entry2.insert(0, "enter to buff priority")
        self.entry2.grid(row=2, column=4, pady=4)

        boost_btn_remv = Button(
            self,
            text="Remove",
            command=lambda: remove_from_list(boosted, self.boost_drop.get()))
        boost_btn_remv.grid(row=2, column=2)

        boost_btn_add = Button(
            self,
            text="Add",
            command=lambda: add_to_list(boosted, self.entry2.get(), self.
                                        entry2, defults["boost"]))
        boost_btn_add.grid(row=2, column=3)

        #########################################

        #degraded combo
        self.deg_drop = Combobox(self, postcommand=self.update_degraded)
        self.deg_drop['values'] = degraded
        self.deg_drop.current(0)
        self.deg_drop.grid(row=3, column=1, pady=1)
        self.entry3 = Entry(self)
        self.entry3.insert(0, "enter to lower priority")
        self.entry3.grid(row=3, column=4, pady=4)

        deg_btn_remv = Button(
            self,
            text="Remove",
            command=lambda: remove_from_list(degraded, self.deg_drop.get()))
        deg_btn_remv.grid(row=3, column=2)

        deg_btn_add = Button(
            self,
            text="Add",
            command=lambda: add_to_list(degraded, self.entry3.get(), self.
                                        entry3, defults["degrade"]))
        deg_btn_add.grid(row=3, column=3)

        ####
        #music combo

        self.music_drop = Combobox(self, postcommand=self.update_music)
        self.music_drop['values'] = music_list.keys()
        self.music_drop.current(0)
        self.music_drop.grid(row=4, column=1, pady=1)
        self.entry4 = Entry(self)
        self.entry4.insert(0, "enter url")
        self.entry4.grid(row=4, column=5)
        self.entry5 = Entry(self)
        self.entry5.insert(0, "enter song's name")
        self.entry5.grid(row=4, column=4)

        music_btn_remv = Button(self,
                                text="Remove",
                                command=lambda: remove_from_list(
                                    music_list, self.music_drop.get()))
        music_btn_remv.grid(row=4, column=2)

        music_btn_add = Button(
            self,
            text="Add",
            command=lambda: add_music(music_list, self.entry5.get(
            ), self.entry4.get(), self.entry5, defults["music"]))
        music_btn_add.grid(row=4, column=3)

        abtn = Button(self, text="Activate", command=scan_computer_programs)
        abtn.grid(row=1, column=5, sticky=E)

        sbtn = Button(self, text="Stop", command=lambda: stop_running())
        sbtn.grid(row=2, column=5, pady=6, sticky=E)

        cbtn = Button(self, text="Close", command=quit)
        cbtn.grid(row=3, column=5, pady=4, sticky=E)

        hbtn = Button(self, text="Save", command=save_lists)
        hbtn.grid(row=6, column=0, sticky=W)

        tsbtn = Button(self,
                       text="TaskManager",
                       command=lambda: os.system("TaskManager\pyProcMon.py"))
        tsbtn.grid(row=3, column=5, sticky=E)

        obtn = Button(
            self,
            text="start",
            command=lambda: call_running(area, threads["procs"], check_box))
        obtn.grid(row=6, column=5, sticky=E)

    def initUI_err(self):
        self.parent.title("Personal Helper")
        self.pack(fill=BOTH, expand=True)

    def update_boosted(self):
        self.boost_drop['values'] = boosted
        try:
            self.boost_drop.current(0)
        except:
            self.boost_drop.set("empty")

    def update_blocked(self):
        self.block_drop['values'] = working_bans
        try:
            self.block_drop.current(0)
        except:
            self.block_drop.set("empty")

    def update_degraded(self):
        self.deg_drop['values'] = degraded
        try:
            self.block_drop.current(0)
        except:
            self.block_drop.set("empty")

    def update_music(self):
        self.music_drop['values'] = music_list.keys()
        try:
            self.block_drop.current(0)
        except:
            self.block_drop.set("empty")
Ejemplo n.º 16
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 IniGenGui(Frame):

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

  def initUIGlobals(self):
   
    self.parent.title("Ini Generator")

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

    f1 = Frame(self)
    f1.grid(row=0, column=0, padx=10, sticky=N+S+E+W)

    f11 = LabelFrame(f1, text="Algorithms to Run")
    f11.grid(row=0, column=0)
    row = 0

    self.check_algs_value_list = []
    self.check_algs_map = {}
    for alg in algorithms:
      if alg == 'clean':
        continue
      check_alg_value = IntVar()
      check_alg = Checkbutton(f11, text=alg, variable=check_alg_value, justify=LEFT, width=25)
      check_alg.grid(row=row, column=0, sticky=W+E)
      self.check_algs_value_list.append(check_alg_value)
      self.check_algs_map[alg] = check_alg_value
      row += 1

    f111 = Frame(f11)
    f111.grid(row=row, column=0)

    button_checkall = Button(f111, text="All", command=self.checkall)
    button_checkall.grid(row=0, column=0, sticky=W+E)
    button_uncheckall = Button(f111, text="None", command=self.uncheckall)
    button_uncheckall.grid(row=0, column=1, sticky=W+E)

    row = 0

    f12 = Frame(f1)
    f12.grid(row=1, column=0, pady=20, sticky=S+W+E)

    f121 = LabelFrame(f12, text='Location of uPMU')
    f121.grid(row=0, column=0)

    self.radio_loc_string = StringVar()
    locations.append('Other Location')
    for loc in locations:
      radio_loc = Radiobutton(f121, text=loc, variable=self.radio_loc_string, value=loc, command=self.set_loc, justify=LEFT, width=25)
      radio_loc.grid(row=row, column=0, sticky=W+E)
      row += 1

    self.entry_otherloc = Entry(f121)

    f2 = Frame(self)
    f2.grid(row=0, column=1, padx=10, sticky=N+S+E+W)

    f21 = LabelFrame(f2, text='Name of uPMU (raw)')
    f21.grid(row=0)
    row = 0

    f211 = Frame(f21)
    f211.grid(row=row)
    row += 1

    self.entry_namesearch = Entry(f211)
    self.entry_namesearch.grid(row=0, column=0, sticky=E+W)

    button_namesearch = Button(f211, text="Search", command=self.namesearch)
    button_namesearch.grid(row=0, column=1, sticky=W+E)

    self.lstbx_namelist = Listbox(f21)
    self.lstbx_namelist.bind("<Double-Button-1>", self.namelist_select)
    self.lstbx_namelist.grid(row=row, sticky=W+E)
    row += 1

    f212 = Frame(f21)
    f212.grid(row=row)
    row += 1

    label_nameselected = Label(f212, text="Selected:")
    label_nameselected.grid(row=0, column=0)

    self.entry_nameselected = Entry(f212, state=DISABLED)
    self.entry_nameselected.grid(row=0, column=1, sticky=W+E)

    f22 = LabelFrame(f2, text="Name of uPMU (abbr)")
    f22.grid(row=1, sticky=W+E, pady=10)
    self.entry_name = Entry(f22, width=30)
    self.entry_name.grid(row=0, column=0, sticky=E+W)

    f23 = LabelFrame(f2, text="Name of Reference uPMU (clean)")
    f23.grid(row=2, pady=10)
    row = 0

    f231 = Frame(f23)
    f231.grid(row=row)
    row += 1

    self.entry_refnamesearch = Entry(f231)
    self.entry_refnamesearch.grid(row=0, column=0, sticky=E+W)

    button_refnamesearch = Button(f231, text="Search", command=self.refnamesearch)
    button_refnamesearch.grid(row=0, column=1, sticky=W+E)

    self.lstbx_refnamelist = Listbox(f23)
    self.lstbx_refnamelist.bind("<Double-Button-1>", self.refnamelist_select)
    self.lstbx_refnamelist.grid(row=row, sticky=W+E)
    row += 1

    f232 = Frame(f23)
    f232.grid(row=row)
    row += 1

    label_refnameselected = Label(f232, text="Selected:")
    label_refnameselected.grid(row=0, column=0)

    self.entry_refnameselected = Entry(f232, state=DISABLED)
    self.entry_refnameselected.grid(row=0, column=1, sticky=W+E)

    button_gen = Button(self, text="Generate Files", command=self.generate_files)
    button_gen.grid(row=1, column=0, columnspan=2, sticky=W+E)

    self.pack()

  def generate_files(self):
    algs = []
    for alg in self.check_algs_map:
      if self.check_algs_map[alg].get() == 1:
        algs.append(alg)

    if self.radio_loc_string.get() == "Other Location":
      location = self.entry_otherloc.get()
    else:
      location = self.radio_loc_string.get()

    name_raw = self.entry_nameselected.get()
    name = self.entry_name.get()
    ref_name = self.entry_refnameselected.get()

    uuid_map = self.get_uuid_map(name_raw)
    reference_uuid_map = self.get_ref_uuid_map(ref_name)

    IniGenAutomation(location, name_raw, name, uuid_map, ref_name, reference_uuid_map, algs)

  def namesearch(self):
    searchterm = self.entry_namesearch.get()
    searchphrase = '/upmu/%{0}%/%'.format(searchterm)
    search_results = self.search(searchterm, searchphrase)
    self.lstbx_namelist.delete(0, END)
    if len(search_results) == 0:
      tkMessageBox.showwarning('Search Error', 'No matches from search for \'{0}\''.format(searchterm))
    else:
      for result in search_results:
        self.lstbx_namelist.insert(END, result)
        
  def refnamesearch(self):
    searchterm = self.entry_refnamesearch.get()
    searchphrase = '/Clean/%{0}%/%'.format(searchterm)
    search_results = self.search(searchterm, searchphrase, ref=True)
    self.lstbx_refnamelist.delete(0, END)
    if len(search_results) == 0:
      tkMessageBox.showwarning('Search Error', 'No matches from search for \'{0}\''.format(searchterm))
    else:
      for result in search_results:
        self.lstbx_refnamelist.insert(END, result)
  
  def search(self, searchterm, searchphrase, ref=False):
    connection = _mysql.connect(host="128.32.37.231", port=3306, user="******",
                                passwd="moresecuredataftw", db='upmu')
    connection.query("SELECT * FROM uuidpathmap WHERE path LIKE '{0}'".format(searchphrase))
    results = connection.store_result()
    queried_data = {}
    result = results.fetch_row()
    while result != tuple():
      queried_data[result[0][0]] = result[0][1]
      result = results.fetch_row()
    search_results = set()
    for path in queried_data:
      dirs = path.split('/')
      if ref:
        if searchterm in '/'.join(dirs[2:-2]):
          search_results.add('/'.join(dirs[2:-2]))
      else:
        if searchterm in '/'.join(dirs[2:-1]):
          search_results.add('/'.join(dirs[2:-1]))
    return search_results

  def set_loc(self):
    if self.radio_loc_string.get() == "Other Location":
      self.entry_otherloc.grid(sticky=W+E)
    else:
      self.entry_otherloc.grid_forget()

  def checkall(self):
    for check in self.check_algs_value_list:
      check.set(1)
  
  def uncheckall(self):
    for check in self.check_algs_value_list:
      check.set(0)

  def namelist_select(self, event):
    selected_index = self.lstbx_namelist.curselection()
    selected = self.lstbx_namelist.get(selected_index)
    self.entry_nameselected.configure(state=NORMAL)
    self.entry_nameselected.delete(0, END)
    self.entry_nameselected.insert(0, selected)
    self.entry_nameselected.configure(state=DISABLED)

  def refnamelist_select(self, event):
    selected_index = self.lstbx_refnamelist.curselection()
    selected = self.lstbx_refnamelist.get(selected_index)
    self.entry_refnameselected.configure(state=NORMAL)
    self.entry_refnameselected.delete(0, END)
    self.entry_refnameselected.insert(0, selected)
    self.entry_refnameselected.configure(state=DISABLED)

  def get_uuid_map(self, name):
    uuid_map = {}
    connection = _mysql.connect(host="128.32.37.231", port=3306, user="******",
                                passwd="moresecuredataftw", db='upmu')
    connection.query("SELECT * FROM uuidpathmap WHERE path LIKE '/upmu/{0}/%'".format(name))
    results = connection.store_result()
    result = results.fetch_row()
    while result != tuple():
      path = result[0][0].split('/')
      uuid_map[path[-1]] = result[0][1]
      result = results.fetch_row()
    return uuid_map
    
  def get_ref_uuid_map(self, name):
    uuid_map = {}
    connection = _mysql.connect(host="128.32.37.231", port=3306, user="******",
                                passwd="moresecuredataftw", db='upmu')
    connection.query("SELECT * FROM uuidpathmap WHERE path LIKE '/Clean/{0}/%'".format(name))
    results = connection.store_result()
    result = results.fetch_row()
    while result != tuple():
      path = result[0][0].split('/')
      uuid_map[path[-2]] = result[0][1]
      result = results.fetch_row()
    return uuid_map
Ejemplo n.º 18
0
    'log': 'np.log10',
    'sqrt': 'np.sqrt',
    '^': '**',
    'factorial': 'np.factorial',
    'ln': 'np.log',
    'DtoR': 'np.radians',
    'RtoD': 'np.degrees'
}

root.title("Calculator for Mathematics")

Style().configure("TButton", padding=(0, 5, 0, 5), font='cambria 15')

border1 = Entry(calc, justify=RIGHT)
border1.grid(row=0, column=0, columnspan=9, pady=5, sticky=W + E)
border1.insert(0, "0")

sinButton = Button(calc, text="sin(x)")
sinButton["command"] = lambda val="sin(": input.numPressed(val)
sinButton.grid(row=1, column=4, pady=5, sticky=W + E)

cosButton = Button(calc, text="cos(x)")
cosButton["command"] = lambda val="cos(": input.numPressed(val)
cosButton.grid(row=1, column=5, pady=5, sticky=W + E)

tanButton = Button(calc, text="tan(x)")
tanButton["command"] = lambda val="tan(": input.numPressed(val)
tanButton.grid(row=1, column=6, pady=5)

clearButton = Button(calc, text="Clear")
clearButton["command"] = input.clearResult
Ejemplo n.º 19
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()
Ejemplo n.º 20
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
Ejemplo n.º 21
0
class Window(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("Network/Port Scan")
        self.style = Style()
        self.style.configure("TFrame", background="#000000")
        self.style.configure("TCheckbutton", background="#000000")
        self.style.configure("TButton", background="#000000")
        self.pack(fill=BOTH, expand=1)

        # Configure layout
        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=1)
        self.columnconfigure(2, weight=1)
        self.rowconfigure(5, weight=1)
        self.rowconfigure(6, weight=1)

        # Title of program
        lbl = Label(self, text="Network/Port Scan")
        lbl.grid(sticky=W, pady=5, padx=5)

        # Text Box
        area = ScrolledText(self, height=20)
        area.grid(row=1,
                  column=0,
                  columnspan=3,
                  rowspan=4,
                  padx=3,
                  sticky=N + S + E + W)
        self.area = area

        # IP Address Button
        self.ip = BooleanVar()
        ip_add_button = Checkbutton(self,
                                    text="IP Address",
                                    variable=self.ip,
                                    width=10)
        ip_add_button.grid(row=1, column=3, sticky=N)
        ip_add_button.config(anchor=W, activebackground="red")

        # Port Button
        self.port = BooleanVar()
        port_button = Checkbutton(self,
                                  text="Ports",
                                  variable=self.port,
                                  width=10)
        port_button.grid(row=1, column=3)
        port_button.config(anchor=W, activebackground="orange")

        # Host Name Button
        self.host = BooleanVar()
        host_name_button = Checkbutton(self,
                                       text="Host Name",
                                       variable=self.host,
                                       width=10)
        host_name_button.grid(row=1, column=3, sticky=S)
        host_name_button.config(anchor=W, activebackground="yellow")

        # Gateway Button
        self.gateway = BooleanVar()
        gateway_btn = Checkbutton(self,
                                  text="Gateway",
                                  variable=self.gateway,
                                  width=10)
        gateway_btn.grid(row=2, column=3, sticky=N)
        gateway_btn.config(anchor=W, activebackground="green")

        # Services Button
        self.service = BooleanVar()
        service_btn = Checkbutton(self,
                                  text="Services",
                                  variable=self.service,
                                  width=10)
        service_btn.grid(row=2, column=3)
        service_btn.config(anchor=W, activebackground="blue")

        # Starting IP label
        ip_label = Label(self, text="Starting IP:  ")
        ip_label.grid(row=5, column=0, pady=1, padx=3, sticky=W)
        self.ip_from = Entry(self, width=15)
        self.ip_from.insert(0, start_ip)
        self.ip_from.grid(row=5, column=0, pady=1, padx=3, sticky=E)

        # Ending IP label
        ip_label_two = Label(self, text="Ending IP:  ")
        ip_label_two.grid(row=5, column=1, pady=1, padx=5, sticky=W)
        self.ip_to = Entry(self, width=15)
        self.ip_to.insert(0, end_ip)
        self.ip_to.grid(row=5, column=1, pady=1, padx=5, sticky=E)

        # Starting Port Label
        port_label = Label(self, text="Starting Port:  ")
        port_label.grid(row=5, column=0, pady=3, padx=5, sticky=S + W)
        self.port_from = Entry(self, width=15)
        self.port_from.insert(0, 0)
        self.port_from.grid(row=5, column=0, pady=1, padx=5, sticky=S + E)

        # Ending Port Label
        port_label_two = Label(self, text="Ending Port:  ")
        port_label_two.grid(row=5, column=1, pady=3, padx=5, sticky=S + W)
        self.port_to = Entry(self, width=15)
        self.port_to.insert(0, 1025)
        self.port_to.grid(row=5, column=1, pady=1, padx=5, sticky=S + E)

        # Scan Me
        self_scan_button = Button(self,
                                  text="Scan Me",
                                  command=lambda: self.onClick(1),
                                  width=33)
        self_scan_button.grid(row=6, column=1, sticky=N)

        # Scan near me Button
        scan_other_button = Button(self,
                                   text="Scan Near Me",
                                   width=33,
                                   command=lambda: self.onClick(2))
        scan_other_button.grid(row=6, column=0, pady=1, sticky=N)

        # Clear button
        clear_button = Button(self,
                              text="Clear text",
                              command=self.clear_text,
                              width=12)
        clear_button.grid(row=6, column=3, pady=1, sticky=N)

        # Progress Bar
        self.label_scanning = Progressbar(self, orient=HORIZONTAL, length=175)
        self.label_scanning.grid(row=6,
                                 column=0,
                                 columnspan=4,
                                 padx=7,
                                 pady=7,
                                 sticky=E + S + W)
        self.label_scanning.config(mode="determinate")

    # Clear what is in the text box.
    def clear_text(self):
        self.area.delete(0.0, 'end')
        # empty my lists.
        my_ports[:] = []
        ip_address_up[:] = []
        target_host_name[:] = []
        target_port_up[:] = []

    # On click methods for scan me and scan others.
    def onClick(self, button_id):

        if button_id == 1:

            # Check to see if host button is marked
            if self.host.get() == 1:
                message = my_host_name()
                self.area.insert(0.0, message, ("warning"))
                self.area.tag_configure("warning", foreground="blue")

            # Check to see if ports button is marked
            if self.port.get() == 1:
                # Check port entry widgets.
                if self.port_from:
                    if self.port_to:
                        # Get the user input
                        starting_port = self.port_from.get()
                        ending_port = self.port_to.get()
                        message, total = scan_my_ports(int(starting_port),
                                                       int(ending_port))
                        for i in message:
                            new_message = "My TCP " + i + "\n"
                            self.area.insert(0.0, new_message, ("ports"))
                            #self.area.tag_configure("ports", foreground = "green")

                    time = "The TCP port scan completed in: " + str(
                        total) + "\n"
                    self.area.insert(0.0, time, ("timing"))
                    self.area.tag_configure("timing", foreground="red")
                else:
                    self.area.insert(0.0, "No valid ports specified.")

            # Check to see if IP button is marked
            if self.ip.get() == 1:
                message = my_ip()
                self.area.insert(0.0, message)

            # Check if gateway button is marked.
            if self.gateway.get() == 1:
                message = my_gateway()
                self.area.insert(0.0, message)

            # Check if service button is marked.
            if self.service.get() == 1:
                message, time = scan_my_services()
                for i in message:
                    new_message = i + "\n"
                    self.area.insert(0.0, new_message)
                new_time = "The local scan completed in: " + str(time) + "\n"
                self.area.insert(0.0.new_time, ("timing"))
                self.area.tag_configure("timing", foreground="red")

        # If Scan other button is clicked.
        elif button_id == 2:

            # Check other IP's
            if self.ip.get() == 1:
                # Check the entry widgets.
                if self.ip_from:
                    if self.ip_to:
                        # Get the ranges from the entry widgets
                        starting_ipv4_address = self.ip_from.get()
                        ending_ipv4_address = self.ip_to.get()

                        # Pass the values from the entry widgets into the function to scan nearby IP addresses.
                        message, time = ping_ip_other(starting_ipv4_address,
                                                      ending_ipv4_address)
                        if message:
                            for i in message:
                                new_message = "The address:     {:>15} {:>15}".format(
                                    i, "is UP\n")
                                self.area.insert(0.0, new_message)

                        total_time = "Range scanned: " + str(
                            starting_ipv4_address) + " to " + str(
                                ending_ipv4_address
                            ) + "\n" + "The IP scan completed in:  " + str(
                                time) + "\n"
                        self.area.insert(0.0, total_time, ("timing"))
                        self.area.tag_configure("timing", foreground="red")

                else:
                    self.area.insert(0.0, "No Ip range is specified.")

            # Check others Ports
            if self.port.get() == 1:
                # Check port entry widgets.
                if self.port_from:
                    if self.port_to:
                        # Get the user input
                        starting_port = self.port_from.get()
                        ending_port = self.port_to.get()

                        message, time = scan_ports_other(
                            int(starting_port), int(ending_port))
                        if message:
                            for i in message:
                                new_msg = "The " + i + "\n"
                                self.area.insert(0.0, new_msg)
                        else:
                            new_msg = "Must scan nearby IP addresses first.\n"

                    total_time = "TCP Port scan completed in: " + str(
                        time) + "\n"
                    self.area.insert(0.0, total_time, ("timing"))
                    self.area.tag_configure("timing", foreground="red")

                else:
                    self.area.insert(0.0, "No Port range specified.")

            # Check other host names. Based on IP's scanned.
            if self.host.get() == 1:
                message, time = scan_host_other(ip_address_up)
                # Check that IP's of other computers were collected
                if message:
                    for i in message:
                        new_message = "Host name: " + str(i) + "\n"
                        self.area.insert(0.0, new_message)

                else:
                    new_msg = "Must scan nearby IP addresses first. \n"
                    self.area.insert(0.0, new_msg)

                total = "The host scan completed in: " + str(time) + "\n"
                self.area.insert(0.0, total, ("timing"))
                self.area.tag_configure("timing", foreground="red")

            # Check gateway return the gateway of the host machine again.
            if self.gateway.get() == 1:
                message = "\n" + str(my_gateway())
                self.area.insert(0.0, message)

            # Check what services are running on which IP and port.
            if self.service.get() == 1:
                message, time = services_other()
                if message:
                    for i in message:
                        new_message = i + "\n"
                        self.area.insert(0.0, new_message)

                else:
                    new_msg = "The IP addresses and ports must be scanned first."
                    self.area.insert(0.0, new_msg)

                new_time = "The service scan completed in: " + str(time) + "\n"
                self.area.insert(0.0, new_time, ("timing"))
                self.area.tag_configure("timing", foreground="red")

        else:
            pass
Ejemplo n.º 22
0
class MainForm(Frame):
    """
    If method is handling some GUI shit, its written in camelCase style
    """
    def __init__(self, parent, caller_instance):
        Frame.__init__(self, parent)
        self.caller_instance = caller_instance
        self.running_on = "%s:%s" % (get_local_addr(),
                                     getattr(self.caller_instance, 'port',
                                             None) or "8888")
        self.parent = parent
        caller_instance.messangers.append(self)
        self.initUI()

    def initUI(self):
        self.__centerWindow()
        self.parent.title("epyks %s" % self.running_on)
        #
        # Addr textbox
        #
        addr_validate = (self.parent.register(self.addrValidation), '%S', '%d')
        self.EntryAddress = Entry(self,
                                  validate='key',
                                  validatecommand=addr_validate,
                                  width=17)
        self.EntryAddress.grid(row=0,
                               column=0,
                               padx=10,
                               pady=5,
                               columnspan=2,
                               sticky=W)
        self.EntryAddress.delete(0, END)
        self.EntryAddress.insert(0, "192.168.0.102:8889")
        #
        # Call button
        #
        self.ButtonCall = Button(self,
                                 text="Call",
                                 command=self.onButtonCallClick)
        self.ButtonCall.grid(row=0, column=1, pady=5)
        #
        #   Callmode status canvas
        #
        self.CanvasCallmode = Canvas(self,
                                     width=20,
                                     height=20,
                                     bg="light grey")
        self.CanvasCallmode.create_oval(1,
                                        1,
                                        20,
                                        20,
                                        fill="red",
                                        outline="light grey")
        self.CanvasCallmode.grid(row=1,
                                 column=0,
                                 pady=0,
                                 padx=10,
                                 sticky=W,
                                 columnspan=2)
        #
        #   Callmode status label
        #
        self.LabelCallmode = Label(self, text="Not connected")
        self.LabelCallmode.grid(row=1, column=0, padx=35)
        #
        #   End call button
        #
        self.ButtonEndCall = Button(self,
                                    text="End call",
                                    command=self.onButtonEndCallClick)
        self.ButtonEndCall.grid(row=1, column=1)

        #
        #   Message listbox
        #
        self.MessagesListBox = Listbox(self)
        self.MessagesListBox.grid(row=2,
                                  column=0,
                                  columnspan=2,
                                  padx=2,
                                  pady=2,
                                  sticky="EW")
        #
        # Message entry
        #
        self.EntryMessage = Entry(self)
        self.EntryMessage.grid(row=3, column=0, padx=2)
        #
        # Send message
        #
        self.ButtonSendMessage = Button(self,
                                        text="Send",
                                        command=self.onButtonSendMessageClick)
        self.ButtonSendMessage.grid(row=3, column=1)

        # Testing

        # Pack all
        self.pack(fill=BOTH, expand=1)

    def onGetAnswerMessageBox(self, interlocutor):
        return tkMessageBox.askyesno(
            title="Incoming call",
            message="A call from {}, wanna answer?".format(interlocutor))

    def addrValidation(self, string, action):
        print string
        if action != 1:
            # 0 - delete, 1 - insert, -1 - focus in/out
            return True
        print "addrValidation: %s" % string
        if len(string) > 1:
            return full_ipv4_check(fulladdr=string)
        return string in ACCEPTABLE_CHARS

    def onTextBoxChange(self, *args, **kwargs):
        print 'lol ' + str(args) + str(kwargs)

    def onButtonCallClick(self):
        address = (self.EntryAddress.get())
        if not full_ipv4_check(fulladdr=address):
            tkMessageBox.showerror(message="Incorrect address")
        ip, port = address.split(':')
        self.caller_instance.call((ip, int(port)))

    def onButtonSendMessageClick(self):
        message = self.EntryMessage.get()
        self.MessagesListBox.insert(
            END, "{author}> {message}".format(author="self", message=message))
        ip, port = self.EntryAddress.get().split(':')
        self.caller_instance.send(message=message, address=(ip, int(port)))

    def onButtonEndCallClick(self):
        self.caller_instance.hang_up()

    def onMessageRecieved(self, author, message):
        """
        :param author: Address of author, tuple (ip, port)
        :param message: Content
        """
        author = ''.join([author[0], ':', str(author[1])])
        self.MessagesListBox.insert(
            END, "{author}> {message}".format(author=author, message=message))

    def checkStatus(self):
        status = self.caller_instance.status
        if status.startswith('On'):
            self.CanvasCallmode.create_oval(1,
                                            1,
                                            20,
                                            20,
                                            fill="green",
                                            outline="light grey")
            self.EntryAddress.delete(0, END)
            self.EntryAddress.insert(
                0, "{}:{}".format(self.caller_instance.interlocutor[0],
                                  self.caller_instance.interlocutor[1]))
            self.EntryAddress.configure(state='readonly')

        elif status.startswith('Not'):
            self.CanvasCallmode.create_oval(1,
                                            1,
                                            20,
                                            20,
                                            fill="red",
                                            outline="light grey")
            self.EntryAddress.configure(state='')
        else:
            self.CanvasCallmode.create_oval(1,
                                            1,
                                            20,
                                            20,
                                            fill="yellow",
                                            outline="light grey")
            self.EntryAddress.configure(state='readonly')
        self.LabelCallmode['text'] = status
        self.parent.after(ms=100, func=self.checkStatus)

    def __centerWindow(self):
        w = 260
        h = 270
        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))
Ejemplo n.º 23
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'  #多余
    def initUI(self):
      
        self.parent.title("Resistor Calculator")
        
        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.columnconfigure(4, pad=3)        
        self.columnconfigure(5, 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)
        self.rowconfigure(9, pad=3)
        self.rowconfigure(10, pad=3)
        self.rowconfigure(11, pad=3)
        self.rowconfigure(12, pad=3)


        entry = Entry(self)
        entry.grid(row=0, columnspan=4, sticky=W+E)
        global resistance
        resistance=""
        def ringOne(number):
            entry.delete(0, END)
            entry.insert(0, str(number))
            global resistance
            resistance = resistance + str(number)
        def ringTwo(number):
            ent=str(number)
            entry.insert(END, str(number))
            global resistance
            resistance = resistance + str(number)
        def ringThree(number): 
            ent=str(number)
            entry.insert(END, str(number))
            global resistance
            resistance = resistance + str(number)
        def ringFour(number):
            global resistance
            entry.delete(0, END)
            for x in range (0, number):
               resistance = resistance + "0"
            ent = "Resistance is: " + resistance
            entry.insert(END,ent)
            resistance = ""
        def cls():
            global resistance
            resistance = ""
            entry.delete(0, END)
            entry.insert(0,"Please Select ring colors")
               
        entry.insert(0,"Please Select ring colors")
        entry.config(justify=RIGHT)

        black = Button(self, text="Black", command=lambda: ringOne(0))
        black.grid(row=2, column=0)
        brown = Button(self, text="Brown", command=lambda: ringOne(1))
        brown.grid(row=3, column=0)
        red = Button(self, text = "Red", command=lambda: ringOne(2))
        red.grid(row=4, column=0)    
        orange = Button(self, text="Orange", command=lambda: ringOne(3))
        orange.grid(row=5, column=0)        
        yellow = Button(self, text="Yellow", command=lambda: ringOne(4))
        yellow.grid(row=6, column=0)        
        green = Button(self, text="Green", command=lambda: ringOne(5))
        green.grid(row=7, column=0)         
        blue = Button(self, text="Blue", command=lambda: ringOne(6))
        blue.grid(row=8, column=0) 
        violet = Button(self, text="Violet", command=lambda: ringOne(7))
        violet.grid(row=9, column=0) 
        grey = Button(self, text = "Grey", command=lambda: ringOne(8))
        grey.grid(row=10, column = 0)
        white = Button(self, text="White", command=lambda: ringOne(9))
        white.grid(row=11,column = 0)

        black2 = Button(self, text="Black", command=lambda: ringTwo(0))
        black2.grid(row=2, column=1)
        brown2 = Button(self, text="Brown", command=lambda: ringTwo(1))
        brown2.grid(row=3, column=1)
        red2 = Button(self, text = "Red", command=lambda: ringTwo(2))
        red2.grid(row=4, column=1)    
        orange2 = Button(self, text="Orange", command=lambda: ringTwo(3))
        orange2.grid(row=5, column=1)        
        yellow2 = Button(self, text="Yellow", command=lambda: ringTwo(4))
        yellow2.grid(row=6, column=1)        
        green2 = Button(self, text="Green", command=lambda: ringTwo(5))
        green2.grid(row=7, column=1)         
        blue2 = Button(self, text="Blue", command=lambda: ringTwo(6))
        blue2.grid(row=8, column=1) 
        violet2 = Button(self, text="Violet", command=lambda: ringTwo(7))
        violet2.grid(row=9, column=1) 
        grey2 = Button(self, text = "Grey", command=lambda: ringTwo(8))
        grey2.grid(row=10, column = 1)
        white2 = Button(self, text="White", command=lambda: ringTwo(9))
        white2.grid(row=11,column = 1)

        
        black3 = Button(self, text="Black", command=lambda: ringThree(0))
        black3.grid(row=2, column=2)
        brown3 = Button(self, text="Brown", command=lambda: ringThree(1))
        brown3.grid(row=3, column=2)
        red3 = Button(self, text = "Red", command=lambda: ringThree(2))
        red3.grid(row=4, column=2)    
        orange3 = Button(self, text="Orange", command=lambda: ringThree(3))
        orange3.grid(row=5, column=2)        
        yellow3 = Button(self, text="Yellow", command=lambda: ringThree(4))
        yellow3.grid(row=6, column=2)        
        green3 = Button(self, text="Green", command=lambda: ringThree(5))
        green3.grid(row=7, column=2)         
        blue3 = Button(self, text="Blue", command=lambda: ringThree(6))
        blue3.grid(row=8, column=2) 
        violet3 = Button(self, text="Violet", command=lambda: ringThree(7))
        violet3.grid(row=9, column=2) 
        grey3 = Button(self, text = "Grey", command=lambda: ringThree(8))
        grey3.grid(row=10, column = 2)
        white3 = Button(self, text="White", command=lambda: ringThree(9))
        white3.grid(row=11,column = 2)

        black4 = Button(self, text="Black", command=lambda: ringFour(0))
        black4.grid(row=2, column=3)
        brown4 = Button(self, text="Brown", command=lambda: ringFour(1))
        brown4.grid(row=3, column=3)
        red4 = Button(self, text = "Red", command=lambda: ringFour(2))
        red4.grid(row=4, column=3)    
        orange4 = Button(self, text="Orange", command=lambda: ringFour(3))
        orange4.grid(row=5, column=3)        
        yellow4 = Button(self, text="Yellow", command=lambda: ringFour(4))
        yellow4.grid(row=6, column=3)        
        green4 = Button(self, text="Green", command=lambda: ringFour(5))
        green4.grid(row=7, column=3)         
        blue4 = Button(self, text="Blue", command=lambda: ringFour(6))
        blue4.grid(row=8, column=3) 
        violet4 = Button(self, text="Violet", command=lambda: ringFour(7))
        violet4.grid(row=9, column=3) 
        grey4 = Button(self, text = "Grey", command=lambda: ringFour(8))
        grey4.grid(row=10, column = 3)
        white4 = Button(self, text="White", command=lambda: ringFour(9))
        white4.grid(row=11,column = 3)
        
        i=0
        labels = "Ring 1", "Ring 2", "Ring 3", "Multiplier"
        for label in labels:
          label1 = Label(self, text=label)
          label1.grid(row=1, column = i)
          i+=1
          
        clear = Button(self, text = "Clear", command = lambda: cls())
        clear.grid(row=12, columnspan=4, sticky=W+E)

        self.pack()
Ejemplo n.º 25
0
class MainFrame(Frame):

    TOP_FRAME_BACKGROUND_COLOR = 'gray75'

    w_ = 500
    h_ = 400

    a_ = 5.
    b_ = 5.

    pad_l = 10

    def __init__(self, parent):
        Frame.__init__(self, parent, background='white')

        self.parent_ = parent

        # this is the main frame we are working on
        self.img_frame = Frame(self, background='navy')
        self.entry1 = None
        self.entry2 = None
        self.cb = None

        #
        self.init_ui()
        self.centering()

        # broken TV app))
        # while True:
        self.state = 0
        self.init_random_image()
        # time.sleep(0.05)

    def centering(self):
        pos_x = (self.parent_.winfo_screenwidth() - self.w_) / 2
        pos_y = (self.parent_.winfo_screenheight() - self.h_) / 2

        self.parent_.geometry('{}x{}+{}+{}'.format(self.w_, self.h_, pos_x, pos_y))

    def init_ui(self):
        self.parent_.title('Rough surface generator')
        self.pack(fill=BOTH, expand=True)

        # top panel with controls
        frame_top = Frame(self, background=self.TOP_FRAME_BACKGROUND_COLOR)
        frame_top.pack(fill=X)

        self.cb = Combobox(frame_top, values=('Gaussian', 'Laplace'))
        self.cb.current(0)
        self.cb.pack(side=LEFT, padx=5, expand=True)

        l1 = Label(frame_top, text=r'Cx', background=self.TOP_FRAME_BACKGROUND_COLOR, width=4)
        l1.pack(side=LEFT, padx=5, expand=True)

        self.entry1 = Entry(frame_top,
                            validate='key',
                            validatecommand=(self.register(self.on_validate),
                                             '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W'),
                            width=10)
        self.entry1.pack(side=LEFT, padx=5, expand=True)
        self.entry1.insert(0, str(self.a_))

        l1 = Label(frame_top, text=r'Cy', width=4, background=self.TOP_FRAME_BACKGROUND_COLOR)
        l1.pack(side=LEFT, padx=5)

        self.entry2 = Entry(frame_top,
                            validate='key',
                            validatecommand=(self.register(self.on_validate),
                                             '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W'),
                            width=10)
        self.entry2.pack(side=LEFT, padx=5, expand=True)
        self.entry2.insert(0, str(self.b_))

        but1 = Button(frame_top, text='RUN', command=self.button_action)
        but1.pack(side=RIGHT, padx=5, pady=5)

        # central panel. It will have a label with an image. Image may have a random noise state, or
        # transformed image state
        self.img_frame.pack(fill=BOTH, expand=True)
        img_label = Label(self.img_frame, background=None)
        img_label.pack(expand=True, fill=BOTH, padx=5, pady=5)

    def on_validate(self, d, i, P, s, S, v, V, W):
        """
        :param d: type of action: 1 - insert, 0 - delete, -1 - other
        :param i: index of char string to be inserted/deleted, or -1
        :param P: value of the entry if the edit is allowed
        :param s: value of entry prior to editing
        :param S: the text string being inserted or deleted, if any
        :param v: the type of validation that is currently set
        :param V: the type of validation that triggered the callback
                    (key, focusin, focusout, forced)
        :param W: the tk name of the widget
        :return: True/False -> Valid / Invalid

        Found it here:
            https://stackoverflow.com/questions/4140437/interactively-validating-entry-widget-content-in-tkinter
        Very good answer!
        """

        if d == '1':
            if W == str(self.entry1):
                try:
                    float(s + S)
                    return True
                except ValueError:
                    self.entry1.delete(0, 'end')
                    self.entry1.insert(0, s)

                    print("Not a number, entry 1")
                    return False
            if W == str(self.entry2):
                try:
                    float(s + S)
                    return True
                except ValueError:
                    self.entry2.delete(0, 'end')
                    self.entry2.insert(0, s)

                    print("Not a number, entry 2")
                    return False
        return True

    def init_random_image(self):
        """
            Create a rough surface image from a random noise
        """
        self.update()

        # set a colormap
        c_map = cm.get_cmap('bwr')

        # width and height of the image
        w_ = self.img_frame.winfo_width()-self.pad_l
        h_ = self.img_frame.winfo_height()-self.pad_l

        # generate random noise
        random_map = np.random.random((h_, w_))

        # generate a meshgrid for the filter
        xv, yv = np.meshgrid(np.linspace(-int(w_ / 2.), int(w_ / 2.), w_),
                             np.linspace(-int(h_ / 2.), int(h_ / 2.), h_))

        # define correlation length and width
        if len(self.entry1.get()) > 0:
            clx = float(self.entry1.get())
        else:
            return

        if len(self.entry2.get()) > 0:
            cly = float(self.entry2.get())
        else:
            return

        #
        if self.cb.get().startswith('G'):
            # Gaussian filter
            filter_ = np.exp(-np.power(xv, 2) / clx - np.power(yv, 2) / cly)
        else:
            # Laplace filter
            filter_ = np.exp(-np.abs(xv) / clx - np.abs(yv) / cly)

        # this is a resulting map
        random_map = np.fft.ifft2(np.multiply(np.fft.fft2(random_map), np.fft.fft2(filter_)))
        random_map = np.real(random_map)

        # normalize to [0, 1]
        random_map -= np.min(random_map)
        random_map /= np.max(random_map)

        # create PhotoImage object to add on the panel
        img = ImageTk.PhotoImage(
            Image.fromarray(
                # image really likes unsigned ints))
                np.uint8(
                    # convert to colormap you like
                    c_map(
                        # give a random image to color map with values between 0 and 1
                        # np.random.random(
                        #     (self.img_frame.winfo_height()-self.pad_l, self.img_frame.winfo_width()-self.pad_l)
                        # )
                        random_map
                    )*255
                )
            )
        )

        # Gray colormap
        # img = ImageTk.PhotoImage(
        #     Image.fromarray(np.random.random_integers(0, 255,
        #                                   (self.img_frame.winfo_height()-self.pad_l,
        #                                    self.img_frame.winfo_width()-self.pad_l)).astype(np.int8)
        #                     ).convert('L')
        # )

        keys = self.img_frame.children.keys()
        for key in keys:
            self.img_frame.children[key].configure(image=img)
            self.img_frame.children[key].image = img

    def button_action(self):
        """
        """
        self.init_random_image()
Ejemplo n.º 26
0
class Example(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent
        
        self.initUI()
        
        
    def initUI(self):
   
      
        self.parent.title("Append Data")
        self.pack(fill=BOTH, expand=True)
        labelfont20 = ('Roboto', 15, 'bold')
        labelfont10 = ('Roboto', 10, 'bold')
        labelfont8 = ('Roboto', 8, 'bold')
        
        frame0 = Frame(self)
        frame0.pack()
        
        lbl0 = Label(frame0, text="Hi Nakul")
        lbl0.config(font=labelfont20)    
        lbl0.pack( padx=5, pady=5)
        lbl00 = Label(frame0, text="Fill the data here")
        lbl00.config(font=labelfont10)
        lbl00.pack( padx=5, pady=5)
        
        ####################################
        frame1 = Frame(self)
        frame1.pack()
        frame1.place(x=50, y=100)        
        
        lbl1 = Label(frame1, text="Name", width=15)
        lbl1.pack(side=LEFT,padx=7, pady=5) 
             
        self.entry1 = Entry(frame1,width=20)
        self.entry1.pack(padx=5, expand=True)
    
        ####################################
        frame2 = Frame(self)
        frame2.pack()
        frame2.place(x=50, y=130)
        
        lbl2 = Label(frame2, text="F Name", width=15)
        lbl2.pack(side=LEFT, padx=7, pady=5)

        self.entry2 = Entry(frame2)
        self.entry2.pack(fill=X, padx=5, expand=True)
        
        ######################################
        frame3 = Frame(self)
        frame3.pack()
        frame3.place(x=50, y=160)
        
        lbl3 = Label(frame3, text="DOB(D/M/Y)", width=15)
        lbl3.pack(side=LEFT, padx=7, pady=5)        

        self.entry3 = Entry(frame3)
        self.entry3.pack(fill=X, padx=5, expand=True) 
        
        #######################################
        frame4 = Frame(self)
        frame4.pack()
        frame4.place(x=50, y=190)
        
        lbl4 = Label(frame4, text="Medium(H/E)", width=15)
        lbl4.pack(side=LEFT, padx=7, pady=5)        

        self.entry4 = Entry(frame4)
        self.entry4.pack(fill=X, padx=5, expand=True)
        
        ##########################################
        frame5 = Frame(self)
        frame5.pack()
        frame5.place(x=50, y=225)  
        MODES = [
            ("M", "Male"),
            ("F", "Female"),
            ]
        lbl5 = Label(frame5, text="Gender", width=15)
        lbl5.pack(side=LEFT, padx=7, pady=5)

        global v
        v = StringVar()
        v.set("Male") # initialize

        for text, mode in MODES:
            b = Radiobutton(frame5, text=text,variable=v, value=mode)
            b.pack(side=LEFT,padx=10)
        
        ############################################
        #####printing line
        lbl5a = Label(text="___________________________________________________")
        lbl5a.pack()
        lbl5a.place(x=45, y=255)  
        
        ############################################
        frame6 = Frame(self)
        frame6.pack()
        frame6.place(x=50, y=290)
        
        lbl6 = Label(frame6, text="Phone No:", width=15)
        lbl6.pack(side=LEFT, padx=7, pady=5)        

        self.entry6 = Entry(frame6)
        self.entry6.pack(fill=X, padx=5, expand=True)
        
        ################################################
        
        frame7 = Frame(self)
        frame7.pack()
        frame7.place(x=50, y=320)
        
        lbl7 = Label(frame7, text="Landline No:", width=15)
        lbl7.pack(side=LEFT, padx=7, pady=5)        

        self.entry7 = Entry(frame7)
        self.entry7.pack(fill=X, padx=5, expand=True)
        
        ###############################################
        frame8 = Frame(self)
        frame8.pack()
        frame8.place(x=50, y=350)
        
        lbl8 = Label(frame8, text="Email:", width=15)
        lbl8.pack(side=LEFT, padx=7, pady=5)        

        self.entry8 = Entry(frame8)
        self.entry8.pack(fill=X, padx=5, expand=True)
        
        #############################################
        frame9 = Frame(self)
        frame9.pack()
        frame9.place(x=50, y=380)
        
        lbl9 = Label(frame9, text="HomeTown:", width=15)
        lbl9.pack(side=LEFT, padx=7, pady=5)        

        self.entry9 = Entry(frame9)
        self.entry9.pack(fill=X, padx=5, expand=True)
        
        ###############################################
        frame10 = Frame(self)
        frame10.pack()
        frame10.place(x=60, y=415)
        
        lbl10 = Label(frame10, text="Address:")
        lbl10.pack( padx=5, pady=5)        

        self.entry10 = Text(frame10,height=5, width=28)
        self.entry10.pack(padx=5, expand=True)
        
        ##############################################
        
        #############################################
        
        frame11 = Frame(self)
        frame11.pack()
        frame11.place(x=350, y=100)
        
        lbl11x = Label(frame11,text="_______Class 10th Data_______")
        lbl11x.pack(padx=0, pady=0)
        
        lbl11 = Label(text="%",width=15)
        lbl11.pack(side=LEFT,padx=0, pady=0)
        lbl11.place(x=350, y=130)        

        self.entry11 = Entry(width=12)
        self.entry11.pack(padx=1, expand=True)
        self.entry11.place(x=420, y=130) 
        
        lbl11a = Label(text="Passing Year",width=15)
        lbl11a.pack(padx=0, pady=2)   
        lbl11a.place(x=350, y=160)   

        self.entry11a = Entry(width=12)
        self.entry11a.pack(padx=1, expand=True)
        self.entry11a.place(x=420, y=160) 
        
        lbl11b = Label(text="Board Name",width=15)
        lbl11b.pack(padx=0, pady=2)   
        lbl11b.place(x=350, y=190)   

        self.entry11b = Entry(width=12)
        self.entry11b.pack(padx=1, expand=True)
        self.entry11b.place(x=420, y=190)
        
        
        ####################################################
        frame12 = Frame(self)
        frame12.pack()
        frame12.place(x=510, y=100)
        
        lbl12x = Label(frame12,text="_______Class 12th Data_______")
        lbl12x.pack(padx=0, pady=0)
        
        lbl12 = Label(text="%",width=15)
        lbl12.pack(side=LEFT,padx=0, pady=0)
        lbl12.place(x=510, y=130)        

        self.entry12 = Entry(width=12)
        self.entry12.pack(padx=1, expand=True)
        self.entry12.place(x=580, y=130) 
        
        lbl12a = Label(text="Passing Year",width=15)
        lbl12a.pack(padx=0, pady=2)   
        lbl12a.place(x=510, y=160)   

        self.entry12a = Entry(width=12)
        self.entry12a.pack(padx=1, expand=True)
        self.entry12a.place(x=580, y=160) 
        
        lbl12b = Label(text="Board Name",width=15)
        lbl12b.pack(padx=0, pady=2)   
        lbl12b.place(x=510, y=190)   

        self.entry12b = Entry(width=12)
        self.entry12b.pack(padx=1, expand=True)
        self.entry12b.place(x=580, y=190)

        #####################################################
        frame13 = Frame(self)
        frame13.pack()
        frame13.place(x=670, y=100)
        
        lbl13x = Label(frame13,text="________B.Tech Data_________")
        lbl13x.pack(padx=0, pady=0)
        
        lbl13 = Label(text="%",width=15)
        lbl13.pack(side=LEFT,padx=0, pady=0)
        lbl13.place(x=670, y=130)        

        self.entry13 = Entry(width=12)
        self.entry13.pack(padx=1, expand=True)
        self.entry13.place(x=740, y=130) 
        
        lbl13a = Label(text="Passing Year",width=15)
        lbl13a.pack(padx=0, pady=2)   
        lbl13a.place(x=670, y=160)   

        self.entry13a = Entry(width=12)
        self.entry13a.pack(padx=1, expand=True)
        self.entry13a.place(x=740, y=160) 
        
        lbl13b = Label(text="College",width=15)
        lbl13b.pack(padx=0, pady=2)   
        lbl13b.place(x=670, y=190)   

        self.entry13b = Entry(width=12)
        self.entry13b.pack(padx=1, expand=True)
        self.entry13b.place(x=740, y=190)
        
        ####################################################
        
        frame14 = Frame(self)
        frame14.pack()
        frame14.place(x=380, y=255)
        
        lbl14 = Label(frame14, text="Any Other Info:")
        lbl14.pack( padx=5, pady=5)        

        self.entry14 = Text(frame14,height=5, width=28)
        self.entry14.pack(padx=5, expand=True)
             
         
        
        frame15 = Frame(self)
        frame15.pack()
        frame15.place(x=650, y=290)
        
        openButton = Button(frame15, text="Attatch Resume",width=15,command=self.openResume)
        openButton.pack(padx=5, pady=5)
        self.entry15 = Entry(frame15)
        self.entry15.pack(fill=X, padx=4, expand=True)
        #############################################################
        frame16 = Frame(self)
        frame16.pack()
        frame16.place(x=450, y=500)
        
        closeButton = Button(frame16, text="SUBMIT",width=35,command=self.getDatax)
        closeButton.pack(padx=5, pady=5)
        
        #######################################
        framexxx = Frame(self)
        framexxx.pack()
        framexxx.place(x=700, y=600)
        self.xxx = Label(framexxx,text="Recent Changes Will Appear Here")
        self.xxx.config(font=labelfont8) 
        self.xxx.pack()
        
        #######################################
        
        frame000 = Frame(self)
        frame000.pack()
        frame000.place(x=50, y=600)
        
        self.lbl000= Label(frame000, text="Beta/Sample2.0 | (c) Nakul Rathore")
        self.lbl000.config(font=labelfont8)    
        self.lbl000.pack( padx=5, pady=5)
        
        
           

    def openResume(self):
        ftypes = [('All files', '*')]
        dlg = tkFileDialog.Open(self, filetypes = ftypes,initialdir='C:/Users/')
        global x15
        fl = dlg.show()
        #file name
        x15 = fl
        temp1 = os.path.basename(fl)
        global temp2
        temp2 = os.path.splitext(temp1)[0]
        
        self.entry15.delete(0, 'end')
        self.entry15.insert(0,temp2)
        
      
        
        
        
        #####################
        
        
        
        
        
    def getDatax(self):
        x1 = self.entry1.get()
        x2 = self.entry2.get()
        x3 = self.entry3.get()
        x4 = self.entry4.get()
        
        x5 = v.get()
        
        x6 = int(self.entry6.get())
        x7 = int(self.entry7.get())
        x8 = self.entry8.get()
        x9 = self.entry9.get()
        
        x10 = self.entry10.get('1.0', 'end')
        
        x11 = int(self.entry11.get())
        x11a = int(self.entry11a.get())
        x11b = self.entry11b.get()
        
        x12 = int(self.entry12.get())
        x12a = int(self.entry12a.get())
        x12b = self.entry12b.get()
        
        x13 = int(self.entry13.get())
        x13a = int(self.entry13a.get())
        x13b = self.entry13b.get()
        
        x14 = self.entry14.get('1.0', 'end')
        
        
        
        
        
        list1=[x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x11a,x11b,x12,x12a,x12b,x13,x13a,x13b,x14,"=HYPERLINK("+"\""+x15+"\""+","+"\""+temp2+"\""+")"]
        
        
        wb = openpyxl.load_workbook('..\database\database.xlsx')
        ws = wb.active
        print(wb.get_sheet_names())
        max_row = ws.get_highest_row()
        #max_col = ws.get_highest_column()
        max_col = 21
        print max_row
        
        for i in xrange(1,max_col+1):
            #print list1[i]
            ws.cell(row = max_row+1, column = i).value = list1[i-1]
        ws.cell(row = max_row+1, column = max_col).font = Font(color="0000FF", underline='single')
        ws.cell(row = max_row+1, column = max_col).alignment = Alignment(horizontal='center')
        wb.save('..\database\database.xlsx')
        
        
        self.entry1.delete(0, 'end')
        self.entry2.delete(0, 'end')
        self.entry3.delete(0, 'end')
        self.entry4.delete(0, 'end')
        
        self.entry6.delete(0, 'end')
        self.entry7.delete(0, 'end')
        self.entry8.delete(0, 'end')
        self.entry9.delete(0, 'end')
        self.entry10.delete('1.0', '2.0')
        self.entry11.delete(0, 'end')
        self.entry11a.delete(0, 'end')
        self.entry11b.delete(0, 'end')
        self.entry12.delete(0, 'end')
        self.entry12a.delete(0, 'end')
        self.entry12b.delete(0, 'end')
        self.entry13.delete(0, 'end')
        self.entry13a.delete(0, 'end')
        self.entry13b.delete(0, 'end')
        
        self.entry14.delete('1.0', '2.0')
        
        
        self.xxx.config(text="Recent Changes Made For : "+x1)
Ejemplo n.º 27
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
Ejemplo n.º 28
0
class topFrame(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.setUI()

    def setUI(self):
        self.parent.title("ServoGui")
        self.pack(fill=BOTH, expand=1)
        self.comPort = StringVar(self)
        self.laststrm = StringVar(self)

        settingFrame = Frame(self, borderwidth=1, relief=RAISED)
        settingFrame.pack(fill=Y, side=LEFT)

        Label(settingFrame, width=50, text="Port Settings", bg="green", fg="black").pack(fill=X)

        ports = self.getComPorts()
        w = apply(OptionMenu, (settingFrame, self.comPort) + tuple(ports))
        w.pack(fill=X)

        BaudFrame = Frame(settingFrame)
        BaudFrame.pack(fill=X)
        Label(BaudFrame, text="Baud:").pack(side=LEFT)
        self.baud_entry = Entry(BaudFrame,
                                width=15,
                                validate="focusout",
                                validatecommand=self.baudValidate)
        self.baud_entry.pack(side=LEFT, expand = True)
        self.baud_entry.insert(0,"115200")

        Button(settingFrame, text="Open Port", command=self.openPort). pack(fill=X)
        Button(settingFrame, text="Close Port", command=self.closePort). pack(fill=X)

        StreamFrame = Frame(settingFrame)
        StreamFrame.pack()
        self.btnStartStream = Button(StreamFrame,
                                text="Start Stream",
                                command=self.startStream,
                                state=DISABLED)
        self.btnStopStream = Button(StreamFrame,
                                text="Stop Stream",
                                command=self.stopStream,
                                state=DISABLED)
        self.btnGetConfig = Button(StreamFrame,
                                text="Get Config",
                                command=self.getConfig,
                                state=DISABLED)
        self.btnStartStream.pack(side=LEFT)
        self.btnStopStream.pack(side=LEFT)
        self.btnGetConfig.pack(side=LEFT)
        self.queue = Queue.Queue()
        self.writequeue = Queue.Queue()

        Label(settingFrame, width=50, text="Drive Settings", bg="green", fg="black").pack(fill=X)
        DriveSettingsFrame = Frame(settingFrame, relief=SUNKEN)
        DriveSettingsFrame.pack(fill=X)

        driveSettingsFrames = []
        self.driveSettingsEntries = []
        for drivesetting in drivesettings:
            driveSettingsFrames.append(Frame(DriveSettingsFrame))
            driveSettingsFrames[-1].pack(fill=X)
            Label(driveSettingsFrames[-1], text=drivesetting).pack(side=LEFT)
            self.driveSettingsEntries.append(Entry(driveSettingsFrames[-1]))
            self.driveSettingsEntries[-1].pack(side=RIGHT)
        Button(DriveSettingsFrame, text="Send to drive", command=self.sendConfig).pack(fill=X)
        Button(DriveSettingsFrame, text="Save config in drive", command=self.saveConfig).pack(fill=X)

        Label(settingFrame, width=50, textvariable=self.laststrm, bg="green", fg="black").pack(fill=X)

        #MatplotLib stuff

        f = Figure(figsize=(5, 4), dpi=100)
        self.a = f.add_subplot(311)
        self.a.set_title("Requested and actual position")
        self.b = f.add_subplot(312)
        self.b.set_title("Error")
        self.c = f.add_subplot(313)
        self.c.set_title("Current meas ADC value")

        self.canvas = FigureCanvasTkAgg(f, master=self)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)

        toolbar = NavigationToolbar2TkAgg(self.canvas, self)
        toolbar.update()
        self.canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1)

        self.hall=[]
        self.encoder_count=[]
        self.pos_error=[]
        self.requested_position=[]
        self.requested_delta=[]
        self.adc_value=[]
        self.pid_output=[]
        self.a.set_autoscaley_on(True)


        self.encoder_line, = self.a.plot([],[])
        self.error_line, = self.b.plot([],[])
        self.reqpos_line, = self.a.plot([],[])
        self.ADC_line, = self.c.plot([],[])
        self.updateCanvas()


    def baudValidate(self):
        sVal = self.baud_entry.get()
        try:
            iVal = int(sVal)
        except ValueError:
            print "Illegal baud value"
            self.baud_entry.delete(0, END)
            self.baud_entry.insert(0, "115200")
            return False
        return True

    def openPort(self):
        try:
            self.ser = serial.Serial(self.comPort.get(), int(self.baud_entry.get()), timeout=0)
        except serial.SerialException:
            print "unable to open"
            return
        self.btnStartStream['state'] = NORMAL
        self.btnStopStream['state'] = NORMAL
        self.btnGetConfig['state'] = NORMAL

        self.thread = SerialThread(self.queue, self.writequeue, self.ser)
        self.thread.daemon = True
        self.thread.start()
        self.process_serial()

    def closePort(self):
        self.thread.stop()
        self.thread.join()
        self.ser.closePort()

        self.btnStartStream['state'] = DISABLED
        self.btnStopStream['state'] = DISABLED
        self.btnGetConfig['state'] = DISABLED

    def process_serial(self):
        while self.queue.qsize():
            try:
                line = self.queue.get()
                self.handleLine(line)
            except Queue.Empty:
                pass
        self.after(100, self.process_serial)

    def startStream(self):
        self.writequeue.put(b"STREAM START \r")

    def stopStream(self):
        self.writequeue.put(b"STREAM DIE \r")
    def getConfig(self):
        self.writequeue.put(b"GET\r")
    def saveConfig(self):
        self.writequeue.put(b"SAVE \r")
    def sendConfig(self):
        for setting in drivesettings:
            dataToSend = b"SET "+setting+" "+self.driveSettingsEntries[drivesettings.index(setting)].get()+"\r"
            print dataToSend
            self.writequeue.put(dataToSend)
            time.sleep(0.2)


    def getComPorts(self):
        ports = serial.tools.list_ports.comports()
        portNames = []
        for port in ports:
            portNames.append(port[0])
        return portNames
    def handleLine(self,line):
        line = line.replace(" ", "")
        line = line.replace("/n", "")
        line = line.replace("/r", "")
        parts = line.split(":")
        if len(parts)>1:
            if parts[0] == "STR":
                self.handleStr(parts[1])
                return
            if parts[0] in drivesettings:
                self.driveSettingsEntries[drivesettings.index(parts[0])].delete(0, END)
                self.driveSettingsEntries[drivesettings.index(parts[0])].insert(0, parts[1])
    def handleStr(self,strm):
        #format of the stream line: STR:hall;count;requestedPosition;requestedDelta;error
        parts = strm.split(";")

        self.laststrm.set(strm)
        self.hall.append(int(parts[0]))
        if len(self.hall) > 5000:
            self.hall.pop(0)

        self.encoder_count.append(parts[1])
        if len(self.encoder_count) > 5000:
            self.encoder_count.pop(0)

        self.requested_position.append(parts[2])
        if len(self.requested_position) > 5000:
            self.requested_position.pop(0)

        self.requested_delta.append(parts[3])
        if len(self.requested_delta) > 5000:
            self.requested_delta.pop(0)

        self.pos_error.append(parts[4])
        if len(self.pos_error) > 5000:
            self.pos_error.pop(0)

        self.adc_value.append(parts[5])
        if len(self.adc_value) > 5000:
            self.adc_value.pop(0)

        self.pid_output.append(parts[5])
        if len(self.pid_output) > 5000:
            self.pid_output.pop(0)

    def updateCanvas(self):

        self.encoder_line.set_xdata(range(len(self.encoder_count)))
        self.encoder_line.set_ydata(self.encoder_count)
        self.error_line.set_xdata(range(len(self.pos_error)))
        self.error_line.set_ydata(self.pos_error)
        self.reqpos_line.set_xdata(range(len(self.requested_position)))
        self.reqpos_line.set_ydata(self.requested_position)
        self.ADC_line.set_xdata(range(len(self.adc_value)))
        self.ADC_line.set_ydata(self.adc_value)
        self.a.relim()
        self.a.autoscale_view()
        self.b.relim()
        self.b.autoscale_view()
        self.c.relim()
        self.c.autoscale_view()
        self.canvas.draw()
        self.after(100, self.updateCanvas)
class mSim(Frame):
  
    def __init__(self, parent):
        
        self.serialStatus = False

        #create variables
        self.startmotor = BooleanVar()
        self.logstate = BooleanVar()
        self.loggedData = []
        self.throttlevar = StringVar()
        self.throttleval = IntVar()

        #default values
        self.throttlevar.set("0%")
        self.throttleval.set(0)

        #base frame init
        Frame.__init__(self, parent)   
        self.parent = parent
        self.initUI()
        self.centerWindow()

        self.PERIOD_LENGTH_Log = 100 #milliseconds
        self.PERIOD_LENGTH_Scan = 1000 #milliseconds
        self.PERIOD_LENGTH_Refresh = 300 #milliseconds

        self.parent.after(0, self.runScan)
        self.parent.after(0, self.runLog)
        self.parent.after(0, self.runRefresh)

    def runScan(self):
        #serial port scanning function
        """ Lists serial port names

            :raises EnvironmentError:
                On unsupported or unknown platforms
            :returns:
                A list of the serial ports available on the system
        """
        if sys.platform.startswith('win'):
            ports = ['COM%s' % (i + 1) for i in range(256)]
        elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
            # this excludes your current terminal "/dev/tty"
            ports = glob.glob('/dev/tty[A-Za-z]*')
        elif sys.platform.startswith('darwin'):
            ports = glob.glob('/dev/tty.*')
        else:
            raise EnvironmentError('Unsupported platform')

        result = []
        for port in ports:
            try:
                s = serial.Serial(port)
                s.close()
                result.append(port)
            except (OSError, serial.SerialException):
                pass
        menu = self.drop["menu"]
        menu.delete(0, "end")
        menu.add_command(label="None", command=lambda value="None": self.selected_s_Port.set(value))
        for string in result:
            menu.add_command(label=string, command=lambda value=string: self.selected_s_Port.set(value))
                
        self.parent.after(self.PERIOD_LENGTH_Scan, self.runScan)

    def runLog(self):
        #this will probably not work since you're not appending to 
        if (self.logstate.get() == True) and (self.serialStatus == True): #logging data                                        
                    data = dict(zip(*[self.SC.dict.keys(), zip(*self.SC.dict.values())[-1]])) 
                    if 'l' not in locals():         # a dictionary with a deque of the recent data for each message type -Austin
                        l = []
                    if self.loggedData == []: #if empty add titles
                        l=[data.keys()]
                    data = data.values()
                    
                    self.loggedData.append(data)
                    
        self.parent.after(self.PERIOD_LENGTH_Log, self.runLog)

    def runRefresh(self):
        
        #Refresh figures function
        self.a.clear()
        self.b.clear()
        self.c.clear()
        self.d.clear()
        
        if not self.serialStatus:
            #TODO: Put SerialComm data buffer here v . Timestamps (from python?) on x axis, values on y-axis
            #Helpful Info: plot([xvals],[yvals])
            self.a.plot([0],[0])
            self.b.plot([0],[0])
            self.c.plot([0],[0])
            self.d.plot([0],[0])
        else:
            self.SC.processData(5) # This param is the number of bytes to try for a message -Austin
            timestamps = [val / 1000.0  if val != None else val for val in self.SC.dict['Timestamp']]
            self.a.plot(timestamps, self.SC.dict['Thrust'])
            self.b.plot(timestamps, self.SC.dict['Rot Speed'])
            self.c.plot(timestamps, self.SC.dict['Current'])
            self.d.plot(timestamps, self.SC.dict['Voltage'])

        #set labels for graphs (could make automatic later)
        self.a.set_xlabel('time (s)')
        self.a.set_ylabel('Thrust (N)')
        self.b.set_xlabel('time (s)')
        self.b.set_ylabel('RPM')
        self.c.set_xlabel('time (s)')
        self.c.set_ylabel('Current (A)')
        self.d.set_xlabel('time (s)')
        self.d.set_ylabel('Voltage (V)')

        #try drawing the canvas
        try:
            self.canvas.draw()
        except:
            pass #just ignore it, you'll do better next time
        
        self.parent.after(self.PERIOD_LENGTH_Refresh, self.runRefresh)

    def centerWindow(self):
      
        w = 900 #eh, who needs scaling anyways
        h = 600

        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 initUI(self):

        #Parent Frame
        self.parent.title("Test Stand Control Panel")
        self.style = Style()
        self.style.theme_use("default")

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


        # Frame 1 (top)
        frame1 = Frame(self)
        frame1.pack(fill=X, expand=1)

            #Start motor button
        startButton = Button(frame1, text="Start Motor",
            command=self.startMotor)
        startButton.pack(side=LEFT, padx=5, pady=5)     


            #Throttle slider
        lbl1 = Label(frame1, text="Throttle (0-100):", width=14)
        lbl1.pack(side=LEFT, padx=5, pady=5)
        
        self.scale = Scale(frame1, from_=0, to=100, 
            command=self.onScaleThrottle)
        self.scale.pack(side=LEFT, padx=15)
        
        self.label = Label(frame1, text="throttle", textvariable=self.throttlevar, width=5)        
        self.label.pack(side=LEFT)

            #Throttlesweep checkbutton
        self.autovar = BooleanVar()
        cb = Checkbutton(frame1, text="Throttle Sweep",
            variable=self.autovar, command=self.onClickAuto)
        cb.pack(side=LEFT, padx=15)

            #Com port selection field
        droplbl = Label(frame1, text="Serial Port:", width=10)
        droplbl.pack(side=LEFT, padx=5, pady=5)
        self.selected_s_Port = StringVar()
        self.s_Ports = []
        self.drop = OptionMenu(frame1,self.selected_s_Port,"None",*self.s_Ports)
        self.drop.pack(side=LEFT, padx=5)

            #baudrate selection field (disabled)
##       drop2lbl = Label(frame1, text="Baudrate:", width=9)
##        drop2lbl.pack(side=LEFT, padx=5, pady=5)
##        self.baudrate = StringVar()
##        baudrates = [9600, 19200, 38400, 57600, 115200]
##        drop2 = OptionMenu(frame1,self.baudrate,*baudrates)
##        drop2.pack(side=LEFT, padx=5)

            #Start serial button
        comsButton = Button(frame1, text="Start Serial",
            command=self.startSerial)
        comsButton.pack(side=LEFT, padx=5, pady=5)

            #Stop serial button
        comsStopButton = Button(frame1, text="Stop Serial",
            command=self.stopSerial)
        comsStopButton.pack(side=LEFT, padx=5, pady=5)

        # Frame 2 (second line)
        frame2 = Frame(self)
        frame2.pack(fill=X, expand=1)

            #Amperage entry
        lbl2 = Label(frame2, text="Max Motor Current (A):", width=21)
        lbl2.pack(side=LEFT, padx=5, pady=5)
        
        self.MaxA_Entry = Entry(frame2)
        self.MaxA_Entry.pack(side="left", fill=X, padx=5, expand=False)
        self.MaxA_Entry.insert(0, 10)

            #Voltage entry
        lbl3 = Label(frame2, text="Max Motor Voltage (V):", width=20)
        lbl3.pack(side=LEFT, padx=5, pady=5)
        
        self.MaxV_Entry = Entry(frame2)
        self.MaxV_Entry.pack(side="left", fill=X, padx=5, expand=False)
        self.MaxV_Entry.insert(0, 14)

            #Update button
        updateButton = Button(frame2, text="Update Values",
            command=self.updateValues)
        updateButton.pack(side=LEFT, padx=5, pady=5)
        
        # Graph Frame
        framegraph = Frame(self)
        framegraph.pack(fill=X, expand=1)

            #Init figures
        f = Figure(figsize=(4,4), dpi=100)
        self.a = f.add_subplot(2, 2, 1)
        self.d = f.add_subplot(2, 2, 4)
        self.c = f.add_subplot(2, 2, 3)
        self.b = f.add_subplot(2, 2, 2)
        
        f.set_tight_layout(True)

        self.canvas = matplotlib.backends.backend_tkagg.FigureCanvasTkAgg(f, master=self)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)

            #Display Toolbar
        toolbar = NavigationToolbar2TkAgg(self.canvas, framegraph)
        toolbar.update()
        self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
        
        # Frame 0 (Bottom text)
        frame0 = Frame(self)
        frame0.pack(side="bottom", fill="x", expand=1)

            #Display text (allows to give user information)
        self.textboxvar = StringVar()
        self.info = Label(frame0, textvariable=self.textboxvar)
        self.info.pack(side=LEFT, padx=5, pady=5)

        # Button Frame (large buttons, near bottom)
        s = Style() #has its own style
        s.configure('My.TFrame',background='#f7edc3') #fancy colors
        framered = Frame(self, style='My.TFrame')
        framered.pack(side="bottom", fill="x", expand=1)
        #used the tk instead of ttk library for this, allows font and color mods

            #Save Button
        self.saveButton = tk.Button(framered, text="Save Data", bg='green', font=('Arial',20,'bold'),
            command=self.saveData)
        self.saveButton.pack(side="left", padx=5, pady=5)

            #Log button
        self.logButton = tk.Button(framered, text="Start Data Logging", bg="blue", font=('Arial',20,'bold'),
            command=self.logData)
        self.logButton.pack(side="left", padx=5, pady=5)

            #Stop button
        self.stopButton = tk.Button(framered, text="Stop Motor", bg='red', font=('Arial',20,'bold'),
            command=self.stopMotor)
        self.stopButton.pack(side="right", padx=5, pady=5)
         

    #Button behavior functions (hopefully self-explanatory)
         
    def onClickAuto(self): #for the throttle sweep (should rename)
        pass #(I guess I can make it do something if I want)

    def MaxA(self):
        #self.MaxA_Entry.get()
        pass
            
    def MaxV(self):
        pass #not sure why these are even functions

    def onScaleThrottle(self, val):
        throttle = str(int(float(val)))
        self.throttlevar.set(throttle + "%")
        self.throttleval.set(throttle)
        try:
            self.SC.sendThrottleSetting(self.throttleval.get())
        except:
            self.textboxvar.set("Something went wrong, is serial connected?")

    def startSerial(self):
        COM_Port = self.selected_s_Port.get()
        #print type(COM_Port)
        #print COM_Port
        if "COM" in COM_Port:
            self.textboxvar.set("Starting Serial on port " + self.selected_s_Port.get())
            #serialThread = Thread(target=SerialComm, args=(COM_Port)) #probably want to pass the self.vars?
            #serialThread.start()
            #threads.append(serialThread)
            try:
                self.ser = serial.Serial(self.selected_s_Port.get(), 9600) #Baud rate = 9600
                self.SC = SerialComm(self.ser, 50) #Dict deques' maxlength = 50
                
                for key in self.SC.dict.keys(): #Initialize dict deques with values so no length errors -Austin
                    for i in range(self.SC.dict[key].maxlen):
                        self.SC.dict[key].append(None)
                
                self.serialStatus = True
            except Exception,e: #if the com port is wrong dont start serial
                print str(e)
                self.textboxvar.set("Error starting serial on port " + self.selected_s_Port.get() + ": " + str(e))
        else:
Ejemplo n.º 30
0
def display_reporting_procedure(*args):
    no_log_file = not _error_file_name
    path_name = os.path.join(user_directory, 'log', _error_file_name)
    size=500
    fr = Toplevel(height=size, width=size)
    fr.title(string='Diagnil Problem Reporting Procedure')
    Message(fr, aspect=300,
            text=display_messages['reporting_procedure']
            ).pack(padx=10, pady=10)

    def copy_entry_clipboard(ent):
        ent.selection_range(0, END)        # for Unix/Linux
        ent.clipboard_clear()
        ent.clipboard_append(ent.get())    # needed for Windows
    if using_ttk or using_tile:
        addr_ent = Entry(fr, background=text_bg_color, width=60)
    else:
        addr_ent = Entry(fr, background=text_bg_color, width=60, relief=SUNKEN)
    addr_ent.insert(END, email_addr)
    addr_ent.pack(padx=20, pady=5)
    fr_email = Frame(fr)
    Button(fr_email, text='Copy',
           command=EventHandler('Reporting proc',
                                lambda : copy_entry_clipboard(addr_ent))
           ).pack(side=LEFT, padx=5)
    Label(fr_email, text='E-mail Address to Clipboard').pack(side=LEFT, padx=5)
    fr_email.pack(pady=5)
    Frame(fr).pack(pady=5)
    
    if using_ttk or using_tile:
        file_ent = Entry(fr, background=text_bg_color, width=60)
    else:
        file_ent = Entry(fr, background=text_bg_color, width=60, relief=SUNKEN)
    file_ent.insert(END, path_name)
    file_ent.pack(padx=20, pady=5)
    fr_file = Frame(fr)
    copy_file_button = \
        Button(fr_file, text='Copy',
               command=EventHandler('Reporting proc',
                                    lambda : copy_entry_clipboard(file_ent)))
    copy_file_button.pack(side=LEFT, padx=5)
    Label(fr_file, text='File name to Clipboard').pack(side=LEFT, padx=5)
    fr_file.pack(pady=5)
    if no_log_file:
        file_ent['state'] = DISABLED
        copy_file_button['state'] = DISABLED
    Frame(fr).pack(pady=5)
    
    Message(fr, aspect=800,
            text=display_messages['privacy_notice']).pack(padx=10, pady=5)
    if using_ttk or using_tile:
        close_button = Button(fr, text=close_button_text, default=ACTIVE,
                              command=EventHandler('Reporting proc',
                                                   lambda : fr.destroy()))
    else:
        close_button = Button(fr, text=close_button_text, default=ACTIVE,
                              width=6,
                              command=EventHandler('Reporting proc',
                                                   lambda : fr.destroy()))
    close_button.pack(side=RIGHT, padx=30, pady=10)
    wrapped_bind(fr, '<Return>', lambda *ev: fr.destroy())
    rx,ry = root.winfo_rootx(), root.winfo_rooty()
    x = (root.winfo_width() - size) // 2
    y = (root.winfo_height() - size) // 2
    fr.geometry(newGeometry='+%d+%d'%(rx+x, ry+y))
Ejemplo n.º 31
0
class topFrame(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.setUI()

    def setUI(self):
        self.parent.title("ServoGui")
        self.pack(fill=BOTH, expand=1)
        self.comPort = StringVar(self)
        self.laststrm = StringVar(self)

        settingFrame = Frame(self, borderwidth=1, relief=RAISED)
        settingFrame.pack(fill=Y, side=LEFT)

        Label(settingFrame,
              width=50,
              text="Port Settings",
              bg="green",
              fg="black").pack(fill=X)

        ports = self.getComPorts()
        w = apply(OptionMenu, (settingFrame, self.comPort) + tuple(ports))
        w.pack(fill=X)

        BaudFrame = Frame(settingFrame)
        BaudFrame.pack(fill=X)
        Label(BaudFrame, text="Baud:").pack(side=LEFT)
        self.baud_entry = Entry(BaudFrame,
                                width=15,
                                validate="focusout",
                                validatecommand=self.baudValidate)
        self.baud_entry.pack(side=LEFT, expand=True)
        self.baud_entry.insert(0, "115200")

        Button(settingFrame, text="Open Port",
               command=self.openPort).pack(fill=X)
        Button(settingFrame, text="Close Port",
               command=self.closePort).pack(fill=X)

        StreamFrame = Frame(settingFrame)
        StreamFrame.pack()
        self.btnStartStream = Button(StreamFrame,
                                     text="Start Stream",
                                     command=self.startStream,
                                     state=DISABLED)
        self.btnStopStream = Button(StreamFrame,
                                    text="Stop Stream",
                                    command=self.stopStream,
                                    state=DISABLED)
        self.btnGetConfig = Button(StreamFrame,
                                   text="Get Config",
                                   command=self.getConfig,
                                   state=DISABLED)
        self.btnStartStream.pack(side=LEFT)
        self.btnStopStream.pack(side=LEFT)
        self.btnGetConfig.pack(side=LEFT)
        self.queue = Queue.Queue()
        self.writequeue = Queue.Queue()

        Label(settingFrame,
              width=50,
              text="Drive Settings",
              bg="green",
              fg="black").pack(fill=X)
        DriveSettingsFrame = Frame(settingFrame, relief=SUNKEN)
        DriveSettingsFrame.pack(fill=X)

        driveSettingsFrames = []
        self.driveSettingsEntries = []
        for drivesetting in drivesettings:
            driveSettingsFrames.append(Frame(DriveSettingsFrame))
            driveSettingsFrames[-1].pack(fill=X)
            Label(driveSettingsFrames[-1], text=drivesetting).pack(side=LEFT)
            self.driveSettingsEntries.append(Entry(driveSettingsFrames[-1]))
            self.driveSettingsEntries[-1].pack(side=RIGHT)
        Button(DriveSettingsFrame,
               text="Send to drive",
               command=self.sendConfig).pack(fill=X)
        Button(DriveSettingsFrame,
               text="Save config in drive",
               command=self.saveConfig).pack(fill=X)

        Label(settingFrame,
              width=50,
              textvariable=self.laststrm,
              bg="green",
              fg="black").pack(fill=X)

        #MatplotLib stuff

        f = Figure(figsize=(5, 4), dpi=100)
        self.a = f.add_subplot(311)
        self.a.set_title("Requested and actual position")
        self.b = f.add_subplot(312)
        self.b.set_title("Error")
        self.c = f.add_subplot(313)
        self.c.set_title("Current meas ADC value")

        self.canvas = FigureCanvasTkAgg(f, master=self)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)

        toolbar = NavigationToolbar2TkAgg(self.canvas, self)
        toolbar.update()
        self.canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1)

        self.hall = []
        self.encoder_count = []
        self.pos_error = []
        self.requested_position = []
        self.requested_delta = []
        self.adc_value = []
        self.pid_output = []
        self.a.set_autoscaley_on(True)

        self.encoder_line, = self.a.plot([], [])
        self.error_line, = self.b.plot([], [])
        self.reqpos_line, = self.a.plot([], [])
        self.ADC_line, = self.c.plot([], [])
        self.updateCanvas()

    def baudValidate(self):
        sVal = self.baud_entry.get()
        try:
            iVal = int(sVal)
        except ValueError:
            print "Illegal baud value"
            self.baud_entry.delete(0, END)
            self.baud_entry.insert(0, "115200")
            return False
        return True

    def openPort(self):
        try:
            self.ser = serial.Serial(self.comPort.get(),
                                     int(self.baud_entry.get()),
                                     timeout=0)
        except serial.SerialException:
            print "unable to open"
            return
        self.btnStartStream['state'] = NORMAL
        self.btnStopStream['state'] = NORMAL
        self.btnGetConfig['state'] = NORMAL

        self.thread = SerialThread(self.queue, self.writequeue, self.ser)
        self.thread.daemon = True
        self.thread.start()
        self.process_serial()

    def closePort(self):
        self.thread.stop()
        self.thread.join()
        self.ser.closePort()

        self.btnStartStream['state'] = DISABLED
        self.btnStopStream['state'] = DISABLED
        self.btnGetConfig['state'] = DISABLED

    def process_serial(self):
        while self.queue.qsize():
            try:
                line = self.queue.get()
                self.handleLine(line)
            except Queue.Empty:
                pass
        self.after(100, self.process_serial)

    def startStream(self):
        self.writequeue.put(b"STREAM START \r")

    def stopStream(self):
        self.writequeue.put(b"STREAM DIE \r")

    def getConfig(self):
        self.writequeue.put(b"GET\r")

    def saveConfig(self):
        self.writequeue.put(b"SAVE \r")

    def sendConfig(self):
        for setting in drivesettings:
            dataToSend = b"SET " + setting + " " + self.driveSettingsEntries[
                drivesettings.index(setting)].get() + "\r"
            print dataToSend
            self.writequeue.put(dataToSend)
            time.sleep(0.2)

    def getComPorts(self):
        ports = serial.tools.list_ports.comports()
        portNames = []
        for port in ports:
            portNames.append(port[0])
        return portNames

    def handleLine(self, line):
        line = line.replace(" ", "")
        line = line.replace("/n", "")
        line = line.replace("/r", "")
        parts = line.split(":")
        if len(parts) > 1:
            if parts[0] == "STR":
                self.handleStr(parts[1])
                return
            if parts[0] in drivesettings:
                self.driveSettingsEntries[drivesettings.index(
                    parts[0])].delete(0, END)
                self.driveSettingsEntries[drivesettings.index(
                    parts[0])].insert(0, parts[1])

    def handleStr(self, strm):
        #format of the stream line: STR:hall;count;requestedPosition;requestedDelta;error
        parts = strm.split(";")

        self.laststrm.set(strm)
        self.hall.append(int(parts[0]))
        if len(self.hall) > 5000:
            self.hall.pop(0)

        self.encoder_count.append(parts[1])
        if len(self.encoder_count) > 5000:
            self.encoder_count.pop(0)

        self.requested_position.append(parts[2])
        if len(self.requested_position) > 5000:
            self.requested_position.pop(0)

        self.requested_delta.append(parts[3])
        if len(self.requested_delta) > 5000:
            self.requested_delta.pop(0)

        self.pos_error.append(parts[4])
        if len(self.pos_error) > 5000:
            self.pos_error.pop(0)

        self.adc_value.append(parts[5])
        if len(self.adc_value) > 5000:
            self.adc_value.pop(0)

        self.pid_output.append(parts[5])
        if len(self.pid_output) > 5000:
            self.pid_output.pop(0)

    def updateCanvas(self):

        self.encoder_line.set_xdata(range(len(self.encoder_count)))
        self.encoder_line.set_ydata(self.encoder_count)
        self.error_line.set_xdata(range(len(self.pos_error)))
        self.error_line.set_ydata(self.pos_error)
        self.reqpos_line.set_xdata(range(len(self.requested_position)))
        self.reqpos_line.set_ydata(self.requested_position)
        self.ADC_line.set_xdata(range(len(self.adc_value)))
        self.ADC_line.set_ydata(self.adc_value)
        self.a.relim()
        self.a.autoscale_view()
        self.b.relim()
        self.b.autoscale_view()
        self.c.relim()
        self.c.autoscale_view()
        self.canvas.draw()
        self.after(100, self.updateCanvas)
class Test_GPS3G(tk.Frame):
	_title = "GPS + 3G Demo"
	def __init__(self, parent, controller):
		tk.Frame.__init__(self, parent)
		self.controller = controller

		label = tk.Label(self, text=self._title, font=TITLE_FONT)
		label.pack(side="top", fill="x", pady=10)

		frame_apn = tk.Frame(self)
		frame_apn.pack(fill=tk.X)
		lbl_apn = tk.Label(frame_apn, text="apn", width=8)
		lbl_apn.pack(side=tk.LEFT, padx=5, pady=5)
		self.entry_apn = Entry(frame_apn)
		self.entry_apn.insert(tk.END, 'internet')
		self.entry_apn.pack(fill=tk.X, padx=5, expand=True)

		frame_username = tk.Frame(self)
		frame_username.pack(fill=tk.X)
		lbl_username = tk.Label(frame_username, text="username", width=8)
		lbl_username.pack(side=tk.LEFT, padx=5, pady=5)
		self.entry_username = Entry(frame_username)
		self.entry_username.pack(fill=tk.X, padx=5, expand=True)

		frame_password = tk.Frame(self)
		frame_password.pack(fill=tk.X)
		lbl_password = tk.Label(frame_password, text="password", width=8)
		lbl_password.pack(side=tk.LEFT, padx=5, pady=5)
		self.entry_password = Entry(frame_password)
		self.entry_password.pack(fill=tk.X, padx=5, expand=True)

		frame_dial_number = tk.Frame(self)
		frame_dial_number.pack(fill=tk.X)
		lbl_dial_number = tk.Label(frame_dial_number, text="dial_number", width=8)
		lbl_dial_number.pack(side=tk.LEFT, padx=5, pady=5)
		self.entry_dial_number = Entry(frame_dial_number)
		self.entry_dial_number.insert(tk.END, '*99#')
		self.entry_dial_number.pack(fill=tk.X, padx=5, expand=True)

		btn_exit = tk.Button(self, text="Back",
						   command=self.OnClose)
		btn_exit.pack(side=tk.RIGHT, padx=5, pady=5)

		self.btn_test = tk.Button(self, text="Run",
						   command=self.GPS3GTest)
		self.btn_test.pack(side=tk.RIGHT, padx=5, pady=5)

	def OnClose(self):
		self.btn_test.config(state=tk.NORMAL)
		self.controller.show_frame("StartPage")

	def GPS3GTest(self):
		if self.entry_apn.get() == "":
			mbox.showerror("Error", "apn should not be blank")
			return

		App_Argument = ""
		if ENABLE_ARGUMENT == True:
			App_Argument += " -a " + self.entry_apn.get() + \
						" -d " + self.entry_dial_number.get()
			if len(self.entry_username.get()) > 0:
				App_Argument += " -u " + self.entry_username.get()
			if len(self.entry_password.get()) > 0:
				App_Argument += " -p " + self.entry_password.get()
		else:
			App_Argument = LED_GPS3G
		print RUN_SCRIPT + GPS_3G_TEST_APP + App_Argument

		# Force eth0 down, in order to connect 3g correctly
		if ssh_session.CreateSshSession(RUN_SCRIPT + WIFI_DOWN, WIFI_DOWN) != 0:
			return self.OnClose()

		# Wait for eth0 has been down
		time.sleep(2)

		if ssh_session.CreateSshSession(RUN_SCRIPT + GPS_3G_TEST_APP + App_Argument, GPS_3G_TEST_APP) != 0:
			return self.OnClose()

		self.btn_test.config(state=tk.DISABLED)
Ejemplo n.º 33
0
    def initUI(self):

        self.parent.title("Resistor Calculator")

        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.columnconfigure(4, pad=3)
        self.columnconfigure(5, 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)
        self.rowconfigure(9, pad=3)
        self.rowconfigure(10, pad=3)
        self.rowconfigure(11, pad=3)
        self.rowconfigure(12, pad=3)

        entry = Entry(self)
        entry.grid(row=0, columnspan=4, sticky=W + E)
        global resistance
        resistance = ""

        def ringOne(number):
            entry.delete(0, END)
            entry.insert(0, str(number))
            global resistance
            resistance = resistance + str(number)

        def ringTwo(number):
            ent = str(number)
            entry.insert(END, str(number))
            global resistance
            resistance = resistance + str(number)

        def ringThree(number):
            ent = str(number)
            entry.insert(END, str(number))
            global resistance
            resistance = resistance + str(number)

        def ringFour(number):
            global resistance
            entry.delete(0, END)
            for x in range(0, number):
                resistance = resistance + "0"
            ent = "Resistance is: " + resistance
            entry.insert(END, ent)
            resistance = ""

        def cls():
            global resistance
            resistance = ""
            entry.delete(0, END)
            entry.insert(0, "Please Select ring colors")

        entry.insert(0, "Please Select ring colors")
        entry.config(justify=RIGHT)

        black = Button(self, text="Black", command=lambda: ringOne(0))
        black.grid(row=2, column=0)
        brown = Button(self, text="Brown", command=lambda: ringOne(1))
        brown.grid(row=3, column=0)
        red = Button(self, text="Red", command=lambda: ringOne(2))
        red.grid(row=4, column=0)
        orange = Button(self, text="Orange", command=lambda: ringOne(3))
        orange.grid(row=5, column=0)
        yellow = Button(self, text="Yellow", command=lambda: ringOne(4))
        yellow.grid(row=6, column=0)
        green = Button(self, text="Green", command=lambda: ringOne(5))
        green.grid(row=7, column=0)
        blue = Button(self, text="Blue", command=lambda: ringOne(6))
        blue.grid(row=8, column=0)
        violet = Button(self, text="Violet", command=lambda: ringOne(7))
        violet.grid(row=9, column=0)
        grey = Button(self, text="Grey", command=lambda: ringOne(8))
        grey.grid(row=10, column=0)
        white = Button(self, text="White", command=lambda: ringOne(9))
        white.grid(row=11, column=0)

        black2 = Button(self, text="Black", command=lambda: ringTwo(0))
        black2.grid(row=2, column=1)
        brown2 = Button(self, text="Brown", command=lambda: ringTwo(1))
        brown2.grid(row=3, column=1)
        red2 = Button(self, text="Red", command=lambda: ringTwo(2))
        red2.grid(row=4, column=1)
        orange2 = Button(self, text="Orange", command=lambda: ringTwo(3))
        orange2.grid(row=5, column=1)
        yellow2 = Button(self, text="Yellow", command=lambda: ringTwo(4))
        yellow2.grid(row=6, column=1)
        green2 = Button(self, text="Green", command=lambda: ringTwo(5))
        green2.grid(row=7, column=1)
        blue2 = Button(self, text="Blue", command=lambda: ringTwo(6))
        blue2.grid(row=8, column=1)
        violet2 = Button(self, text="Violet", command=lambda: ringTwo(7))
        violet2.grid(row=9, column=1)
        grey2 = Button(self, text="Grey", command=lambda: ringTwo(8))
        grey2.grid(row=10, column=1)
        white2 = Button(self, text="White", command=lambda: ringTwo(9))
        white2.grid(row=11, column=1)

        black3 = Button(self, text="Black", command=lambda: ringThree(0))
        black3.grid(row=2, column=2)
        brown3 = Button(self, text="Brown", command=lambda: ringThree(1))
        brown3.grid(row=3, column=2)
        red3 = Button(self, text="Red", command=lambda: ringThree(2))
        red3.grid(row=4, column=2)
        orange3 = Button(self, text="Orange", command=lambda: ringThree(3))
        orange3.grid(row=5, column=2)
        yellow3 = Button(self, text="Yellow", command=lambda: ringThree(4))
        yellow3.grid(row=6, column=2)
        green3 = Button(self, text="Green", command=lambda: ringThree(5))
        green3.grid(row=7, column=2)
        blue3 = Button(self, text="Blue", command=lambda: ringThree(6))
        blue3.grid(row=8, column=2)
        violet3 = Button(self, text="Violet", command=lambda: ringThree(7))
        violet3.grid(row=9, column=2)
        grey3 = Button(self, text="Grey", command=lambda: ringThree(8))
        grey3.grid(row=10, column=2)
        white3 = Button(self, text="White", command=lambda: ringThree(9))
        white3.grid(row=11, column=2)

        black4 = Button(self, text="Black", command=lambda: ringFour(0))
        black4.grid(row=2, column=3)
        brown4 = Button(self, text="Brown", command=lambda: ringFour(1))
        brown4.grid(row=3, column=3)
        red4 = Button(self, text="Red", command=lambda: ringFour(2))
        red4.grid(row=4, column=3)
        orange4 = Button(self, text="Orange", command=lambda: ringFour(3))
        orange4.grid(row=5, column=3)
        yellow4 = Button(self, text="Yellow", command=lambda: ringFour(4))
        yellow4.grid(row=6, column=3)
        green4 = Button(self, text="Green", command=lambda: ringFour(5))
        green4.grid(row=7, column=3)
        blue4 = Button(self, text="Blue", command=lambda: ringFour(6))
        blue4.grid(row=8, column=3)
        violet4 = Button(self, text="Violet", command=lambda: ringFour(7))
        violet4.grid(row=9, column=3)
        grey4 = Button(self, text="Grey", command=lambda: ringFour(8))
        grey4.grid(row=10, column=3)
        white4 = Button(self, text="White", command=lambda: ringFour(9))
        white4.grid(row=11, column=3)

        i = 0
        labels = "Ring 1", "Ring 2", "Ring 3", "Multiplier"
        for label in labels:
            label1 = Label(self, text=label)
            label1.grid(row=1, column=i)
            i += 1

        clear = Button(self, text="Clear", command=lambda: cls())
        clear.grid(row=12, columnspan=4, sticky=W + E)

        self.pack()
Ejemplo n.º 34
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()
class Test_Wifi(tk.Frame):
	_title = "Wifi Demo"
	def __init__(self, parent, controller):
		tk.Frame.__init__(self, parent)
		self.controller = controller

		label = tk.Label(self, text=self._title, font=TITLE_FONT)
		label.pack(side="top", fill="x", pady=10)

		frame_ssid = tk.Frame(self)
		frame_ssid.pack(fill=tk.X)
		lbl_ssid = tk.Label(frame_ssid, text="ssid", width=6)
		lbl_ssid.pack(side=tk.LEFT, padx=5, pady=5)
		self.entry_ssid = Entry(frame_ssid)
		self.entry_ssid.pack(fill=tk.X, padx=5, expand=True)

		frame_password = tk.Frame(self)
		frame_password.pack(fill=tk.X)
		lbl_password = tk.Label(frame_password, text="password", width=6)
		lbl_password.pack(side=tk.LEFT, padx=5, pady=5)
		self.entry_password = Entry(frame_password)
		self.entry_password.pack(fill=tk.X, padx=5, expand=True)

		frame_url = tk.Frame(self)
		frame_url.pack(fill=tk.X)
		lbl_url = tk.Label(frame_url, text="url", width=6)
		lbl_url.pack(side=tk.LEFT, padx=5, pady=5)
		self.entry_url = Entry(frame_url)
		self.entry_url.insert(tk.END, 'google.com')
		self.entry_url.pack(fill=tk.X, padx=5, expand=True)

		btn_exit = tk.Button(self, text="Back",
						   command=self.OnClose)
		btn_exit.pack(side=tk.RIGHT, padx=5, pady=5)

		self.btn_test = tk.Button(self, text="Run",
						   command=self.WifiTest)
		self.btn_test.pack(side=tk.RIGHT, padx=5, pady=5)

	def OnClose(self):
		self.btn_test.config(state=tk.NORMAL)
		self.controller.show_frame("StartPage")

	def WifiTest(self):
		if self.entry_ssid.get() == "":
			mbox.showerror("Error", "ssid should not be blank")
			return
		if self.entry_password.get() == "":
			mbox.showerror("Error", "password should not be blank")
			return
		if self.entry_url.get() == "":
			mbox.showerror("Error", "url should not be blank")
			return

		App_Argument = ""
		if ENABLE_ARGUMENT == True:
			App_Argument += " -t wifi -s " + self.entry_ssid.get() + \
						" -p " + self.entry_password.get() + \
						" -l " + self.entry_url.get()
		else:
			App_Argument = LED_WIFI
		print RUN_SCRIPT + WIFI_TEST_APP + App_Argument

		if ssh_session.CreateSshSession(RUN_SCRIPT + WIFI_TEST_APP + App_Argument, WIFI_TEST_APP) != 0:
			return self.OnClose()

		self.btn_test.config(state=tk.DISABLED)
Ejemplo n.º 36
0
class Window(Frame):
    def __init__(self, parent, window_type):
        Frame.__init__(self, parent, msg = None)

        self.parent = parent
        if window_type == "main":
            self.initUI_main()
        if window_type == "err":
            self.initUI_err()

    def initUI_main(self):
        self.parent.title("Personal Helper")
        self.pack(fill=BOTH, expand=True)

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


        lbl = Label(self, text="Windows")
        lbl.grid(sticky=W+N, pady=4, padx=5)


        check_box = {"work": IntVar(),
                     "boost": IntVar()}

        check1 = Checkbutton(self, text="work-Mode", variable=check_box["work"])
        check1.grid(row=7, column=0)

        check2 = Checkbutton(self, text="boost games", variable=check_box["boost"])
        check2.grid(row=7, column=1)


        ### old version, may be used again later
        area = Treeview(self)
        area['show'] = 'headings'
        area["columns"] = ("one", "two", "three", "four")
        area.column("one", width=10)
        area.column("two", width=10)
        area.column("three", width=10)
        area.column("four", width=10)
        area.heading("one", text="process name")
        area.heading("two", text="Priority")
        area.heading("three", text="PID")
        area.heading("four", text="Usage")
        ###about this part
        #area.grid(row=1, column=0, columnspan=2, rowspan=4, padx=5, sticky=E + W + S + N)
        #######

        #comboboxes and relevant buttons

        self.block_drop = Combobox(self, postcommand= self.update_blocked)
        self.block_drop['values'] = working_bans
        self.block_drop.current(0)
        self.block_drop.grid(row=1, column=1, pady=1)
        self.entry = Entry(self)
        self.entry.insert(0, "enter to block")
        self.entry.grid(row=1, column=4)

        block_btn_remv = Button(self, text="Remove", command=lambda: remove_from_list(working_bans, self.block_drop.get()))
        block_btn_remv.grid(row=1, column=2)

        block_btn_add = Button(self, text="Add", command=lambda: add_to_list(working_bans, self.entry.get(), self.entry, defults["block"]))
        block_btn_add.grid(row=1, column=3)

        ############
        #boosted combo
        self.boost_drop = Combobox(self, postcommand=self.update_boosted)
        self.boost_drop['values'] = boosted
        self.boost_drop.current(0)
        self.boost_drop.grid(row=2, column=1, pady=1)
        self.entry2 = Entry(self)
        self.entry2.insert(0, "enter to buff priority")
        self.entry2.grid(row=2, column=4, pady=4)

        boost_btn_remv = Button(self, text="Remove", command=lambda: remove_from_list(boosted, self.boost_drop.get()))
        boost_btn_remv.grid(row=2, column=2)

        boost_btn_add = Button(self, text="Add", command=lambda: add_to_list(boosted, self.entry2.get(), self.entry2, defults["boost"]))
        boost_btn_add.grid(row=2, column=3)

        #########################################

        #degraded combo
        self.deg_drop = Combobox(self, postcommand=self.update_degraded)
        self.deg_drop['values'] = degraded
        self.deg_drop.current(0)
        self.deg_drop.grid(row=3, column=1, pady=1)
        self.entry3 = Entry(self)
        self.entry3.insert(0, "enter to lower priority")
        self.entry3.grid(row=3, column=4, pady=4)

        deg_btn_remv = Button(self, text="Remove", command=lambda: remove_from_list(degraded, self.deg_drop.get()))
        deg_btn_remv.grid(row=3, column=2)

        deg_btn_add = Button(self, text="Add", command=lambda: add_to_list(degraded, self.entry3.get(), self.entry3, defults["degrade"]))
        deg_btn_add.grid(row=3, column=3)

        ####
        #music combo

        self.music_drop = Combobox(self, postcommand=self.update_music)
        self.music_drop['values'] = music_list.keys()
        self.music_drop.current(0)
        self.music_drop.grid(row=4, column=1, pady=1)
        self.entry4 = Entry(self)
        self.entry4.insert(0, "enter url")
        self.entry4.grid(row=4, column=5)
        self.entry5 = Entry(self)
        self.entry5.insert(0, "enter song's name")
        self.entry5.grid(row=4, column=4)

        music_btn_remv = Button(self, text="Remove", command=lambda: remove_from_list(music_list, self.music_drop.get()))
        music_btn_remv.grid(row=4, column=2)

        music_btn_add = Button(self, text="Add", command=lambda: add_music(music_list, self.entry5.get(),self.entry4.get() ,self.entry5, defults["music"]))
        music_btn_add.grid(row=4, column=3)


        abtn = Button(self, text="Activate", command=scan_computer_programs)
        abtn.grid(row=1, column=5, sticky=E)

        sbtn = Button(self, text="Stop", command=lambda: stop_running())
        sbtn.grid(row=2, column=5, pady=6, sticky=E)

        cbtn = Button(self, text="Close", command=quit)
        cbtn.grid(row=3, column=5, pady=4, sticky=E)

        hbtn = Button(self, text="Save", command=save_lists)
        hbtn.grid(row=6, column=0, sticky=W)

        tsbtn = Button(self, text="TaskManager", command=lambda: os.system("TaskManager\pyProcMon.py"))
        tsbtn.grid(row=3, column=5, sticky=E)

        obtn = Button(self, text="start", command=lambda: call_running(area, threads["procs"], check_box))
        obtn.grid(row=6, column=5, sticky=E)

    def initUI_err(self):
        self.parent.title("Personal Helper")
        self.pack(fill=BOTH, expand=True)

    def update_boosted(self):
        self.boost_drop['values'] = boosted
        try:
            self.boost_drop.current(0)
        except:
            self.boost_drop.set("empty")

    def update_blocked(self):
        self.block_drop['values'] = working_bans
        try:
            self.block_drop.current(0)
        except:
            self.block_drop.set("empty")

    def update_degraded(self):
        self.deg_drop['values'] = degraded
        try:
            self.block_drop.current(0)
        except:
            self.block_drop.set("empty")

    def update_music(self):
        self.music_drop['values'] = music_list.keys()
        try:
            self.block_drop.current(0)
        except:
            self.block_drop.set("empty")
Ejemplo n.º 37
0
class SelectPaths(MyFrame):
    def __init__(self, topframe=None):

        MyFrame.__init__(self, topframe=topframe)

        style = Style()
        style.theme_use('clam')

        self.patient_foler_path = ""
        self.patients = []
        self.set_title('Brain segmentation GUI')
        self.add_ui_components()

    def add_ui_components(self):

        # Creating the frames.
        self.sub_frame1 = Frame(self)
        self.sub_frame1.grid(column=0, row=0)

        sub_frame2 = Frame(self)
        sub_frame2.grid(column=0, row=1)

        sub_frame3 = Frame(self)
        sub_frame3.grid(column=0, row=2)

        sub_frame21 = Frame(sub_frame2)
        sub_frame21.grid(column=0, row=0)

        sub_frame22 = Frame(sub_frame2)
        sub_frame22.grid(padx=20, column=1, row=0)

        sub_frame221 = Frame(sub_frame22)
        sub_frame221.grid(row=1, column=0)

        # Creating the top-menu buttons.
        self.visualise_button = Button(self.sub_frame1,
                                       text="Visualise",
                                       command=self.start_visualisation)
        self.visualise_button.grid(row=0, column=1)

        self.help_button = Button(self.sub_frame1,
                                  text="Help",
                                  command=self.open_help)
        self.help_button.grid(row=0, column=2)

        # Creating the select modality path.
        self.modality_label = Label(sub_frame21,
                                    text="Path to patient folders",
                                    relief=FLAT)
        self.modality_label.grid(row=1, column=1)
        self.modality_path_entry = Entry(sub_frame21)
        self.modality_path_entry.grid(row=2, column=1)
        #self.modality_path_entry.set(self.patient_folder_path)

        self.modality_path_button = Button(
            sub_frame21,
            text="Choose",
            command=self.choose_directory_and_import)
        self.modality_path_button.grid(row=2, column=2)

        # Creating the patients listbox.
        self.label_patients = Label(sub_frame22, text="Patients")
        self.label_patients.grid(row=0, column=0)

        self.listbox_patients = Listbox(sub_frame221,
                                        selectmode='multiple',
                                        width=50,
                                        height=10)

        self.listbox_patients.pack(side=LEFT, fill=Y)
        #self.listbox_patients.grid(row=1, column=0)
        self.listbox_patients.bind("<Button-1>", self.listbox_changed)

        self.scrollbar = Scrollbar(sub_frame221)
        self.scrollbar.pack(side=RIGHT, fill=Y)

        # attach listbox to scrollbar
        self.listbox_patients.config(yscrollcommand=self.scrollbar.set)
        self.scrollbar.config(command=self.listbox_patients.yview)
        # Creating the status console.
        self.status_text = Text(sub_frame3, height=5)
        self.status_text.grid(column=0, row=0)
        self.status_text.tag_configure('title',
                                       justify='center',
                                       font="Arial 10 bold")
        self.status_text.tag_configure('entry', justify='left', font="Arial 9")
        self.status_text.insert(END, 'Status Console', 'title')
        self.status_text_entry_number = 1
        self.status_text.configure(state='disabled')

# ***** EVENTS - START********************************

    def start_visualisation(self):
        """ Launch visualisation module. 
        Linked to self.visualise_button (Button). """

        patient_path = os.path.join(self.patient_folder_path,
                                    'processed_' + self.patients[0])

        segmentation_path = os.path.join(
            patient_path, SEGM_PREFIX + '_' + self.patients[0] + '.nii.gz')

        supervoxel_path = os.path.join(
            patient_path,
            SUPERVOXEL_PREFIX + '_' + self.patients[0] + '.nii.gz')

        # check if the supervoxels and the segmentation exist
        if not os.path.exists(supervoxel_path):
            supervoxel_path = None
        if not os.path.exists(segmentation_path):
            segmentation_path = None

        mod_paths = []
        for mod in MODALITY_PREFIXES:
            mod_paths.append(\
                    os.path.join(patient_path,
                                 mod+'_'+self.patients[0]+'.nii.gz'))

        vis = vv.VisualVolumes(image_paths=mod_paths,
                               segm_path=segmentation_path,
                               supervoxel_id_path=supervoxel_path,
                               topframe=self.master)
        vis.tkraise()

    def listbox_changed(self, event):
        """ Add a patient upon selection in the listbox. 
        Linked to self.listbox_patients (Listbox). """

        indices = list(self.listbox_patients.curselection())
        selected_idx = self.listbox_patients.nearest(event.y)

        if selected_idx == -1:
            return

        # remove or add a patient index
        if selected_idx not in indices:
            indices.append(selected_idx)
        else:
            indices.remove(selected_idx)

        # set self.patients based on the new patient indices and enable visualisation if only one is selected.
        self.patients = []
        for idx in indices:
            self.patients.append(self.listbox_patients.get(idx).split(' ')[0])
        if len(self.patients) == 1:
            self.visualise_button['state'] = 'enabled'
        else:
            self.visualise_button['state'] = 'disabled'

    def choose_directory_and_import(self):
        """ Allow the user to select an import path. 
	    Linked to self.modality_path_button (Button), 
	    and sets self.modality_path_entry (Entry). """

        initialdir = DATA_PATH
        msg = 'Select directory containing patients'
        path = askdirectory(title=msg, initialdir=initialdir)
        # update the text box.
        self.modality_path_entry.delete(0, END)
        self.modality_path_entry.insert(0, str(path))

        # Adding the modality paths after the folder is selected.
        self.patient_folder_path = self.modality_path_entry.get()
        if os.path.exists(self.patient_folder_path):

            patients_validation = os.listdir(self.patient_folder_path)

            # Checking if the patient has the right modalities and importing the patient.
            for i, patient in enumerate(patients_validation):

                # Checking if the patient was already processed.
                if patient.startswith('processed_') or os.path.exists(
                        os.path.join(self.patient_folder_path,
                                     'processed_' + patient)):
                    print("The files of the patient " + patient +
                          " are already copied")
                    continue

                # If everything is fine, then it continues to makign folders and copying files
                # Copying the files into the new folder.
                valid = self._convert_and_copy_files(patient)
                if not valid:
                    patients_validation[i] = None

            # We make a list of patients with only ids for the listbox.
            valid_patients = [p for p in patients_validation if p is not None]
            self.list_existing_patients(valid_patients)

    def _convert_and_copy_files(self, patient):
        """ Check if all valid files exist for this patient and return
        True if so. """

        # Getting the list of modalities for every patient.
        patient_path = os.path.join(self.patient_folder_path, patient)
        modalities = os.listdir(patient_path)

        # Look for paths
        valid_paths = {}
        prefices = [SEGM_PREFIX, SUPERVOXEL_PREFIX] + MODALITY_PREFIXES
        for prefix in prefices:
            candidates = [modality \
                          for modality in modalities \
                          if modality.startswith(prefix+'.')]
            if len(candidates) != 1:
                err = '%s file not identified. Look for ambiguities in %s.' \
                        % (prefix, patient_path)
                print(err)
                return False
            modality = candidates[0]

            if not any([
                    modality.endswith(ext)
                    for ext in ['.mha', '.nii', '.nii.gz']
            ]):
                err = "Image format not recognized: %s. In %s" \
                            % (modality, patient_path)
                print(err)
                return False

            valid_paths[prefix] = modality

        # Creating a processed patient folder.
        os.mkdir(os.path.join(self.patient_folder_path,
                              'processed_' + patient))
        for prefix, basename in valid_paths.iteritems():
            shutil.copyfile(
                os.path.join(self.patient_folder_path, patient, basename),
                os.path.join(self.patient_folder_path, 'processed_' + patient,
                             prefix + '_' + patient + '.nii.gz'))
        return True

    def open_help(self):

        self.help_window = help_window.HelpWindow()
        self.help_window.tkraise()


# ***** EVENTS - END***************************

    def list_existing_patients(self, patients=None):
        print("Importing existing patients")
        # We make a list of patients with only ids for the listbox.

        if patients is None:
            patients = os.listdir(self.patient_folder_path)
        self.patients = []
        for patient in patients:
            if not patient.startswith('processed_'):
                self.patients.append(patient)
        self.patients.sort()
        self.populate_patient_listbox(self.patients)

        if self.listbox_patients.size() > 0:
            self.listbox_patients.selection_set(0)

        self.status_text.configure(state='normal')
        self.status_text.insert(
            END, '\n' + str(self.status_text_entry_number) +
            '- Patients are imported.', 'entry')
        self.status_text_entry_number += 1
        self.status_text.insert(
            END, '\n' + str(self.status_text_entry_number) +
            '- Please select a patient to proceed', 'entry')
        self.status_text_entry_number += 1
        self.status_text.configure(state='disabled')

    def populate_patient_listbox(self, patients):

        self.listbox_patients.delete(0, END)
        for patient in patients:
            patient_path = os.path.join(self.patient_folder_path,
                                        'processed_' + patient)

            #check if a given patient has a label
            if os.path.exists(
                    os.path.join(
                        patient_path, 'corrected_' + SEGM_PREFIX + '_' +
                        patient + '.nii.gz')):
                patient = patient + ' - segmentation corrected'
            self.listbox_patients.insert(END, patient)
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
Ejemplo n.º 39
0
class GripperDemo(Frame):
    def __init__(self, parent1):
        Frame.__init__(self, parent1)
        self.parent = parent1
        self.initUI()

    def initUI(self):
        self.parent.title("Gripper Demo")
        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)

        #scale1 - Gripper Pos
        ScaleGripperPos = Scale(self,
                                from_=0,
                                to=100,
                                orient=HORIZONTAL,
                                length=300,
                                resolution=1,
                                command=self.onScaleGripperPos)
        ScaleGripperPos.grid(row=1, column=2)

        self.label = Label(self, text="Gripper Pos ")
        self.label.grid(row=1, column=1)

        self.GripperPos = IntVar()
        self.labelScaleGripperPos = Label(self,
                                          text=0,
                                          textvariable=self.GripperPos)
        self.labelScaleGripperPos.grid(row=1, column=3)

        #scale2 - X ROTATION
        scaleRotX = Scale(self,
                          from_=0,
                          to=650,
                          orient=HORIZONTAL,
                          length=300,
                          resolution=1,
                          command=self.onScaleXAxisRot)
        scaleRotX.grid(row=2, column=2)
        scaleRotX.set(450)

        self.label = Label(self, text="X Axis Rotation ")
        self.label.grid(row=2, column=1)

        self.labelRotX = Label(self)
        self.labelRotX.grid(row=2, column=3)

        #Entry1 - Force
        self.entryForce = Entry(self)
        self.entryForce.grid(row=3, column=2)
        self.entryForce.insert(0, "50")  #35=700

        #self.forceString = StringVar()
        #self.forceString.set(1023);
        self.labelForce = Label(self)
        self.labelForce.grid(row=3, column=3)
        #self.entryForce.insert(1023,self.force.get())
        #self.entry1.delete(0,END) #delete entry text
        #entry.bind("<Return>", callback) #calls callback function after hit "enter"

        self.label = Label(self, text="Current (A)")
        self.label.grid(row=6, column=1)
        self.labelCurrent = Label(self)
        self.labelCurrent.grid(row=6, column=3)

        #Entry2 - Speed
        self.entrySpeed = Entry(self)
        self.entrySpeed.grid(row=4, column=2)
        self.entrySpeed.insert(0, "4000")
        self.labelSpeed = Label(self)
        self.labelSpeed.grid(row=4, column=3)

        #Entry2 - Active Distance
        self.entryDistance = Entry(self)
        self.entryDistance.grid(row=5, column=2)

        #Entry3 - Send Command
        self.entrySendCommand = Entry(self)
        self.entrySendCommand.grid(row=8, column=2)

        self.activeDistance = IntVar()
        self.activeDistance.set(15)
        self.labelActiveDistance = Label(self)
        self.labelActiveDistance.grid(row=5, column=3)
        self.entryDistance.insert(0, self.activeDistance.get())

        #Button1 - close
        self.button1 = Button(self, text="close", command=self.gripperClose)
        self.button1.grid(row=7, column=1)
        #Button2 - open
        self.button2 = Button(self, text="open", command=self.gripperOpen)
        self.button2.grid(row=7, column=2)
        #Button3 - home
        self.button3 = Button(self,
                              text="home",
                              command=self.gripperHomeRoutine)
        self.button3.grid(row=7, column=3)
        #Button4 - send command
        self.button4 = Button(self, text="send", command=self.sendCommand)
        self.button4.grid(row=8, column=3)
        #Button3
        self.buttonForce = Button(self,
                                  text="forceSetPoint (mg)",
                                  command=self.gripperSetForce)
        self.buttonForce.grid(row=3, column=1)
        #Button4
        self.buttonSpeed = Button(self,
                                  text="speedSetPoint (mseg/close)",
                                  command=self.gripperSetSpeed)
        #80degree each finger = to move 40 degree to close
        self.buttonSpeed.grid(row=4, column=1)
        #Button5
        self.buttonDistance = Button(self,
                                     text="distanceSetPoint (Cm)",
                                     command=self.gripperSetDistance)
        self.buttonDistance.grid(row=5, column=1)

    def gripperOpen(self):
        message = "open"
        rospy.loginfo(message)
        pub.publish(message)

    def gripperClose(self):
        message = "close_101"  #101 is the auto close command
        rospy.loginfo(message)
        pub.publish(message)

    def gripperHomeRoutine(self):
        message = "home"
        rospy.loginfo(message)
        pub.publish(message)

    def sendCommand(self):
        message = self.entrySendCommand.get()
        rospy.loginfo(message)
        pub.publish(message)

    def gripperSetForce(self):
        aux = map(int(self.entryForce.get()), 0, 1200, 0, 1023)
        message = "setForce_" + str(aux)
        rospy.loginfo(message)
        pub.publish(message)

    def gripperSetSpeed(self):
        #0.174seg 80graus (6.0V sem carga)
        #4s 80 graus na velocidade minima 50ms
        aux = map(int(self.entrySpeed.get()), 4000, 174, 50, 0)
        if aux < 0:
            aux = 0
        message = "setSpeed_" + str(aux)
        rospy.loginfo(message)
        pub.publish(message)

    def gripperSetDistance(self):
        aux = self.entryDistance.get()
        message = "setDistance_" + str(aux)
        rospy.loginfo(message)
        pub.publish(message)

    def onScaleGripperPos(self, x):
        aux = int(float(x))
        self.GripperPos.set(aux)
        message = "close_" + str(aux)
        rospy.loginfo(message)
        pub.publish(message)

    def onScaleXAxisRot(self, x):
        aux = int(float(x))
        message = "rotate_" + str(aux)
        rospy.loginfo(message)
        pub.publish(message)

    def updateLabels(self):
        aux = map(gripperForce.data, 0, 1023, 0, 1200)
        self.labelForce.config(text=str(aux))
        aux = int(self.entrySpeed.get())
        if aux < 174:
            aux = 174
        self.labelSpeed.config(text=str(aux))
        self.labelActiveDistance.config(text=str(gripperDistance.data))
        self.labelRotX.config(text=str(gripperRotationX.data))
        self.labelCurrent.config(text=str((gripperCurrent.data - 511) * 0.024))
class mSim(Frame): #could probably have renamed this class. Oh well...

  
    def __init__(self, parent):

        #base frame init
        Frame.__init__(self, parent)   
        self.parent = parent
        self.initUI()
        self.centerWindow()

        #Used to stop threads from infinitely looping
        global exitapp
        exitapp = False

        #serial port scanning thread (this is provided as-is and should work)
        def serial_ports():
            """ Lists serial port names

                :raises EnvironmentError:
                    On unsupported or unknown platforms
                :returns:
                    A list of the serial ports available on the system
            """
            if sys.platform.startswith('win'):
                ports = ['COM%s' % (i + 1) for i in range(256)]
            elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
                # this excludes your current terminal "/dev/tty"
                ports = glob.glob('/dev/tty[A-Za-z]*')
            elif sys.platform.startswith('darwin'):
                ports = glob.glob('/dev/tty.*')
            else:
                raise EnvironmentError('Unsupported platform')

            result = []
            for port in ports:
                try:
                    s = serial.Serial(port)
                    s.close()
                    result.append(port)
                except (OSError, serial.SerialException):
                    pass
            return result

        
        def scanLoop(): #This thread causes lag when closing the program, could fix, but eh it works
            while True and (not exitapp):
                self.s_Ports = serial_ports()
                #update every 4 seconds
                #(reducing this reduces lag on closing but increases the computation power required)
                #(Could create more elegant solution, but this works well enough)
                time.sleep(4)
                if exitapp == True:
                        break
        ###END FUNCTION###

        #Initiallize ports and start scanning thread
        self.s_Ports = []
        sScanThread = Thread(target=scanLoop, args=())
        sScanThread.start()
        threads.append(sScanThread)
        
        #create variables
        self.startmotor = BooleanVar()
        self.logstate = BooleanVar()
        self.throttlevar.set("0%") #ghetto fixes woo
        self.throttleval.set(0)

        #message sending thread
        def commsServer():
            self.sMsg = None
            #prev_sMsg = None #don't need this no more
            
            def sendSerial(msg, port, baudrate): #just a function to send serial messages
                if (port is not 'None'):
                    ser = serial.Serial(port, baudrate, serial.EIGHTBITS, serial.PARITY_NONE, serial.STOPBITS_ONE)
                    if ser.isOpen():
                        ser.close()
                    ser.open()
                    for b in bytearray("message\n","UTF-8"):
                        ser.write(b)
                    ser.close()
            
            while True and (not exitapp):
                if self.sMsg != None:
                    msg = str(self.sMsg)
                    #send command over serial (pySerial)
                    sendSerial(msg, self.selected_s_Port, self.baudrate)
                    self.sMsg = None
                else:
                    time.sleep(0.1)
                if exitapp == True:
                        break
        ###END FUNCTION###

        #start the serial sending thingy
        commsServerThread = Thread(target=commsServer, args=())
        commsServerThread.start()
        threads.append(commsServerThread) #make sure you do this for any new thread you create!
        #failing to append threads to the threadlist is a criminal offense
        #not really but it'll stop them from being killed when the program closes

    def centerWindow(self):
      
        w = 800 #eh, who needs scaling anyways
        h = 640

        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 initUI(self):

        #Parent Frame
        self.parent.title("Test Stand Control Panel")
        self.style = Style()
        self.style.theme_use("default")

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


        # Frame 1 (top)
        frame1 = Frame(self)
        frame1.pack(fill=X, expand=1)

            #Start motor button
        startButton = Button(frame1, text="Start Motor",
            command=self.startMotor)
        startButton.pack(side=LEFT, padx=5, pady=5)     


            #Throttle slider
        lbl1 = Label(frame1, text="Throttle (0-100):", width=14)
        lbl1.pack(side=LEFT, padx=5, pady=5)
        
        scale = Scale(frame1, from_=0, to=100, 
            command=self.onScaleThrottle)
        scale.pack(side=LEFT, padx=15)
        
        self.throttlevar = StringVar()
        self.throttleval = IntVar()
        self.label = Label(frame1, text="throttle", textvariable=self.throttlevar, width=5)        
        self.label.pack(side=LEFT)

            #Throttlesweep checkbutton
        self.autovar = BooleanVar()
        cb = Checkbutton(frame1, text="Throttle Sweep",
            variable=self.autovar, command=self.onClickAuto)
        cb.pack(side=LEFT, padx=15)

            #Com port selection field
        droplbl = Label(frame1, text="Serial Port:", width=10)
        droplbl.pack(side=LEFT, padx=5, pady=5)
        self.selected_s_Port = StringVar()
        self.s_Ports = []
        drop = OptionMenu(frame1,self.selected_s_Port,"None",*self.s_Ports)
        drop.pack(side=LEFT, padx=5)

            #baudrate selection field (disabled)
##        drop2lbl = Label(frame1, text="Baudrate:", width=9)
##        drop2lbl.pack(side=LEFT, padx=5, pady=5)
##        self.baudrate = StringVar()
##        baudrates = [9600, 19200, 38400, 57600, 115200]
##        drop2 = OptionMenu(frame1,self.baudrate,*baudrates)
##        drop2.pack(side=LEFT, padx=5)

            #Start serial button
        comsButton = Button(frame1, text="Start Serial",
            command=self.startSerial)
        comsButton.pack(side=LEFT, padx=5, pady=5)

            #Stop serial button
        comsStopButton = Button(frame1, text="Stop Serial",
            command=self.stopSerial)
        comsStopButton.pack(side=LEFT, padx=5, pady=5)

        # Frame 2 (second line)
        frame2 = Frame(self)
        frame2.pack(fill=X, expand=1)

            #Amperage entry
        lbl2 = Label(frame2, text="Max Motor Current (A):", width=21)
        lbl2.pack(side=LEFT, padx=5, pady=5)
        
        self.MaxA_Entry = Entry(frame2)
        self.MaxA_Entry.pack(side="left", fill=X, padx=5, expand=False)
        self.MaxA_Entry.insert(0, 10)

            #Voltage entry
        lbl3 = Label(frame2, text="Max Motor Voltage (V):", width=20)
        lbl3.pack(side=LEFT, padx=5, pady=5)
        
        self.MaxV_Entry = Entry(frame2)
        self.MaxV_Entry.pack(side="left", fill=X, padx=5, expand=False)
        self.MaxV_Entry.insert(0, 14)

            #Update button
        updateButton = Button(frame2, text="Update Values",
            command=self.updateValues)
        updateButton.pack(side=LEFT, padx=5, pady=5)
        
        # Graph Frame
        framegraph = Frame(self)
        framegraph.pack(fill=X, expand=1)

            #Init figures
        f = Figure(figsize=(4.5,4.5), dpi=100)
        self.a = f.add_subplot(2, 2, 1)
        self.d = f.add_subplot(2, 2, 4)
        self.c = f.add_subplot(2, 2, 3)
        self.b = f.add_subplot(2, 2, 2)
        
        f.set_tight_layout(True)

        self.canvas = matplotlib.backends.backend_tkagg.FigureCanvasTkAgg(f, master=self)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)

            #Display Toolbar
        toolbar = NavigationToolbar2TkAgg(self.canvas, framegraph)
        toolbar.update()
        self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)

            #Refresh thread function
        def refreshFigure(): #this is threaded and just refreshes the figure (see time.sleep() for refresh rate)
            time.sleep(1)
            while True  and (not exitapp):
                self.a.clear()
                self.b.clear()
                self.c.clear()
                self.d.clear()
                if not serialStatus:
                    self.a.plot([1,2,3,4,5,6,7,8],[0,0,0,0,0,0,0,0])
                    self.b.plot([1,2,3,4,5,6,7,8],[0,0,0,0,0,0,0,0])
                    self.c.plot([1,2,3,4,5,6,7,8],[0,0,0,0,0,0,0,0])
                    self.d.plot([1,2,3,4,5,6,7,8],[0,0,0,0,0,0,0,0])
                else:
                    #debug plotsTimestamp
                    self.a.plot(serialData[-10:]["Timestamp"],serialData[-10:]["Timestamp"])
                    self.b.plot(serialData[-10:]["Timestamp"],serialData[-10:]["raw_temp"])
                    self.c.plot(serialData[-10:]["Timestamp"],serialData[-10:]["conv_temp"])
                    self.d.plot(serialData[-10:]["Timestamp"],serialData[-10:]["Potentiometer"])
                    #final plots
    ##                self.a.plot(serialData[-10:]["Timestamp"],serialData[-10:]["Thrust"])
    ##                self.b.plot(serialData[-10:]["Timestamp"],serialData[-10:]["RPM"])
    ##                self.c.plot(serialData[-10:]["Timestamp"],serialData[-10:]["Current"])
    ##                self.d.plot(serialData[-10:]["Timestamp"],serialData[-10:]["Voltage"])
                    #old demo stuff
    ##                self.a.plot([1,2,3,4,5,6,7,8],[5,6,1,3,self.throttleval.get(),9,3,5])
    ##                self.b.plot([1,2,3,4,5,6,7,8],[3,16,10,30,80,90,30,50])
    ##                self.c.plot([1,2,3,4,5,6,7,8],[8,5,4,(self.throttleval.get())**(0.5),15,15,15,20])
    ##                self.d.plot([1,2,3,4,5,6,7,8],[14,14,13,12,12,11.5,11.2,10.5])

                #set labels for graphs (could make automatic later)
                self.a.set_xlabel('time (s)')
                self.a.set_ylabel('Thrust (N)')
                self.b.set_xlabel('time (s)')
                self.b.set_ylabel('RPM')
                self.c.set_xlabel('time (s)')
                self.c.set_ylabel('Current (A)')
                self.d.set_xlabel('time (s)')
                self.d.set_ylabel('Voltage (V)')

                #try drawing the canvas
                try:
                    self.canvas.draw()
                except:
                    pass #just ignore it, you'll do better next time
                time.sleep(0.1) #refreshrate
        ###END FUNCTION###

            #Start the graphing thread
        plotThread = Thread(target=refreshFigure, args=())
        plotThread.start()
        threads.append(plotThread)
        
        # Frame 0 (Bottom text)
        frame0 = Frame(self)
        frame0.pack(side="bottom", fill="x", expand=1)

            #Display text (allows to give user information)
        self.textboxvar = StringVar()
        self.info = Label(frame0, textvariable=self.textboxvar)
        self.info.pack(side=LEFT, padx=5, pady=5)

        # Button Frame (large buttons, near bottom)
        s = Style() #has its own style
        s.configure('My.TFrame',background='#f7edc3') #fancy colors
        framered = Frame(self, style='My.TFrame')
        framered.pack(side="bottom", fill="x", expand=1)
        #used the tk instead of ttk library for this, allows font and color mods

            #Save Button
        self.saveButton = tk.Button(framered, text="Save Data", bg='green', font=('Arial',20,'bold'),
            command=self.saveData)
        self.saveButton.pack(side="left", padx=5, pady=5)

            #Log button
        self.logButton = tk.Button(framered, text="Start Data Logging", bg="blue", font=('Arial',20,'bold'),
            command=self.logData)
        self.logButton.pack(side="left", padx=5, pady=5)

            #Stop button
        self.stopButton = tk.Button(framered, text="Stop Motor", bg='red', font=('Arial',20,'bold'),
            command=self.stopMotor)
        self.stopButton.pack(side="right", padx=5, pady=5)
         

    #Button behavior functions (hopefully self-explanatory)
         
    def onClickAuto(self): #for the throttle sweep (should rename)
        pass #(I guess I can make it do something if I want)

    def MaxA(self):
        #self.MaxA_Entry.get()
        pass #(I guess I can make it do something if I want)
    def MaxV(self):
        pass #(I guess I can make it do something if I want)

    def onScaleThrottle(self, val):
        throttle = str(int(float(val)))
        self.throttlevar.set(throttle + "%")
        self.throttleval.set(throttle)

    def startSerial(self):
        try:
            serialThread.join()
        except:
            pass
        COM_Port = self.selected_s_Port.get()
        #print type(COM_Port)
        #print COM_Port
        if "COM" in COM_Port:
            self.textboxvar.set("Starting Serial on port " + self.selected_s_Port.get())
            serialThread = Thread(target=SerialComm, args=(COM_Port)) #probably want to pass the self.vars?
            serialThread.start()
            threads.append(serialThread)
            global serialStatus
            serialStatus = True
        else:
            self.textboxvar.set("Please select a port (current port: " + self.selected_s_Port.get() + ")")
            global serialStatus
            serialStatus = False

    def stopSerial(self):
        try:
            serialThread.join()
            global serialStatus
            serialStatus = False
        except:
            pass

    def startMotor(self): #gonna have to make this send a serial message (maybe a popup to confirm too
        if self.autovar.get(): #I'll give you 5 seconds to move your fingers out of the way
            print "Preparing to sweep throttle range in 5 seconds"
            self.textboxvar.set("Sweeping throttle range in 5 seconds")
            self.startmotor.set(True)
        else:
            print "starting motor at " + str(self.throttlevar.get()) + " percent"
            self.textboxvar.set("Starting motor at " + str(self.throttlevar.get()) + "% in 5 seconds")
            self.startmotor.set(True)

    def runMotor(self):
        #runmotor at specified throttle
        self.textboxvar.set("Running the motor is not implemented yet")
        pass

    def stopMotor(self):
        #stop motor
        print "Stopping motor"
        self.textboxvar.set("Stopping motor (not implemented yet)")
        self.startmotor.set(False)
        #self.throttlevar.set("0%") #not sure we want to reset the throttle value
        pass

    def saveData(self):
        #save to csv
        self.textboxvar.set("Saving logged data.")
        #for some reason putting this in a thread causes it to not crash, welp
        try:
          self.loggedData
        except AttributeError:
            self.textboxvar.set("No recorded data.")
        else:
            if messagebox.askokcancel("Save", "This will overwrite any data.csv file in the directory. Save anyways?"):
                def saveCSV():
                    l = self.loggedData
                    with open('data.csv', 'wb') as f:
                       wtr = csv.writer(f, delimiter= ';')
                       wtr.writerows( l )
                    time.sleep(2)
                    self.textboxvar.set("Data saved!")
                saveThread = Thread(target=saveCSV, args=())
                saveThread.start()

    def updateValues(self):
        #update motor values
        print "Updating motor values"
        self.textboxvar.set("Updating motor values (WIP)")
        pass

    def logData(self):
        if self.logstate.get():
            self.logButton.configure(text = 'Start Data Logging')
            self.logButton.configure(bg = 'blue')
            self.logstate.set(False)
        else:
            self.logButton.configure(text = 'Stop Data Logging')
            self.logButton.configure(bg = 'orange')
            self.logstate.set(True)
            #start data logging (probably some kind of thread)
            def logSerialData():
                self.loggedData = []
                global serialData
                l=[serialData[-1].keys()]
                self.textboxvar.set("Logging from arduino is not implemented yet")
                #apparently spamming these messages causes crashes, good to know
                while self.logstate.get() and (not exitapp):
                    print 'Logging Data'
                    time.sleep(1)
                    global serialData
                    data = serialData[-1].values()
                    #recieve and store data (pySerial)
                    l.append(data)
                    self.loggedData = l
                    
            logThread = Thread(target=logSerialData, args=())
            logThread.start()
            threads.append(logThread)
Ejemplo n.º 41
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()
Ejemplo n.º 42
0
 def initUI(self):
     self.parent.title("One Time Pad Generator")
     self.style = Style()
     self.style.theme_use("default")
     self.grid()
     
     #string
     text_to_encrypt = Entry(self)
     text_to_encrypt.grid(row=0, column=0)
     text_to_encrypt.delete(0, Tkinter.END)
     text_to_encrypt.insert(0, "text you want to encrypt or decrypt")
     
     #pad
     encrypt_pad = Entry(self)
     encrypt_pad.grid(row=0, column=1)
     encrypt_pad.delete(0, Tkinter.END)
     encrypt_pad.insert(0, "padOutput")
     
     #start
     start_encrypt = Entry(self)
     start_encrypt.grid(row=0, column=2)
     start_encrypt.delete(0, Tkinter.END)
     start_encrypt.insert(0, 0)
     
     
     
     
     #encrypt button
     encodeButton = Button(self, text="Encrypt",
         command=lambda: self.encrypt(text_to_encrypt.get(), encrypt_pad.get(), start_encrypt.get()))
     encodeButton.grid(row=1, column=0)
     #decrypt button
     encodeButton = Button(self, text="Decrypt",
         command=lambda: self.decrypt(str(text_to_encrypt.get()), encrypt_pad.get(), start_encrypt.get()))
     encodeButton.grid(row=1, column=2)
     
   
     #generate pad
     padgen = Entry(self)
     padgen.grid(row=2, column=0)
     padgen.delete(0, Tkinter.END)
     padgen.insert(0, 0)
     
     #gen key button
     genkey = Button(self, text="Generate Key",
                     command=lambda: Cryptography.outputPad(Cryptography.GenerateKey(int(padgen.get())), encrypt_pad.get()))
     genkey.grid(row=2, column=1)
     
     #encrypted text
    
     self.T = Tkinter.Text(self)
     S = Scrollbar(self.T)
     S.grid(column=2);
     S.config(command=self.T.yview)
     self.T.config(yscrollcommand=S.set)
     self.T.insert(Tkinter.END,self.encrypted[0])
     self.T.grid(row=5, column=0, sticky="nsew", rowspan = 10, columnspan = 3)
     
    
     #input email
     e = Entry(self)
     e.grid(row = 3, column = 0)
     e.delete(0, Tkinter.END)
     e.insert(0, "Send encrypted message via email")
     #send email
     email = Button(self, text="Send Email",command=lambda:self.sendmail(e.get()))
     email.grid(row=3, column=1)
Ejemplo n.º 43
0
class Window(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.initUI()
        self.UIwithGrid()

    def initUI(self):  # creating gui
        self.frame1 = Frame(self)
        self.frame2 = Frame(self)
        self.frame3 = Frame(self)
        self.frame4 = Frame(self)
        self.frame5 = Frame(self)

        # created multiple frames

        self.label1 = Label(self.frame1,
                            text="COURSE PROGRAM ESTIMATOR",
                            font='Helvetica 25 bold',
                            background="SpringGreen3",
                            foreground="black")
        self.label2 = Label(self.frame1,
                            text="     Training Data: ",
                            font="Times 14")
        self.entry = Entry(self.frame1, width=65)
        self.entry.insert(
            0,
            'https://www.sehir.edu.tr/tr/duyurular/2017-2018-Akademik-Yili-Ders-Programi'
        )
        self.color = Label(
            self.frame1,
            text="                   ",
            background="red",
        )
        self.button = Button(self.frame1,
                             text="Fetch and Train",
                             command=self.fetch)
        self.label3 = Label(self.frame2,
                            text="Individual Courses:",
                            font='Helvetica 10 bold')
        self.label4 = Label(self.frame3,
                            text="     Top 3 Estimates:",
                            font='Helvetica 10 bold')
        self.coursesListbox = Listbox(self.frame2, width=30)
        self.label5 = Label(self.frame4,
                            text=" Accuracy Analysis \nBased on Programs: ",
                            font='Helvetica 10 bold')
        self.programsListbox = Listbox(self.frame4, width=30)
        self.estimatesListbox = Text(self.frame5, width=30, height=10)

        self.scrollbar1 = Scrollbar(self.frame2, orient=VERTICAL)
        self.scrollbar2 = Scrollbar(self.frame4, orient=VERTICAL)
        self.scrollbar3 = Scrollbar(self.frame5, orient=VERTICAL)
        self.scrollbar1.config(command=self.coursesListbox.yview)
        self.scrollbar2.config(comman=self.programsListbox.yview)
        self.scrollbar3.config(command=self.estimatesListbox.yview)
        self.coursesListbox.config(yscrollcommand=self.scrollbar1.set)
        self.programsListbox.config(yscrollcommand=self.scrollbar2.set)
        self.estimatesListbox.config(yscrollcommand=self.scrollbar3.set)

    def UIwithGrid(self):
        self.frame1.grid(row=1, column=2, sticky=N + S + E + W)
        self.frame2.grid(row=2, column=1, columnspan=2, sticky=W)
        self.frame3.grid(row=2, column=2, sticky=N + E)
        self.frame4.grid(row=3, column=1, columnspan=2, sticky=W, pady=5)
        self.frame5.grid(row=3, column=2, columnspan=2, sticky=E, pady=5)
        self.label1.grid(row=1, column=2, sticky=E + W)
        self.label2.grid(row=2, column=1, columnspan=2, pady=25, sticky=W)
        self.entry.grid(row=2, column=2, columnspan=2, sticky=E)
        self.color.grid(row=3, column=2, columnspan=2)
        self.button.grid(row=3, column=2, sticky=E, padx=90)
        self.label3.grid(row=1, column=1)
        self.coursesListbox.grid(row=2, column=1)
        self.label4.pack(in_=self.frame3, side='left')
        self.label5.grid(row=1, column=1)
        self.programsListbox.grid(row=2, column=1)
        self.estimatesListbox.grid(row=2, column=3, sticky=E)
        self.scrollbar1.grid(row=2, column=1, sticky=N + S + E)
        self.scrollbar2.grid(row=2, column=1, sticky=N + E + S)
        self.scrollbar3.grid(row=2, column=2, columnspan=2, sticky=N + S + E)
        self.pack()

    def fetch(self):  # fetching phase
        self.color.config(background='yellow')
        self.course_list = []
        self.update()
        url = self.entry.get()
        self.dataobj = Data()  # creating data obj
        self.dataobj.init_data(url)
        self.courses = self.dataobj.courselist.keys()  # getting keys
        self.courses.sort()  # sorting keys
        self.obj_list = []
        for i in self.courses:
            self.obj_list.append(self.dataobj.courselist[i])
        self.classifier_obj = docclass.naivebayes(docclass.getwords)
        for i in self.obj_list:  # TRANING PHASE
            self.classifier_obj.train(i.split_name.lower(), i.first_code)
        r1 = re.compile("(.*?)\s*\(")
        for i in self.courses:  # adding courses to listbox
            course_name = self.dataobj.courselist[i].name
            name = r1.match(course_name)
            if name != None:
                name1 = i + '' + '(' + name.group(1) + ')'
            else:
                name1 = i + ' ' + '(' + course_name + ')'
            self.coursesListbox.insert(END, name1)
        for z in self.courses:  # adding course category to other listbox
            if self.dataobj.courselist[z].first_code not in self.course_list:
                self.course_list.append(self.dataobj.courselist[z].first_code)

            code = self.dataobj.courselist[z].first_code
            if code not in self.programsListbox.get(0, END):
                self.programsListbox.insert(END, code)
        self.color.config(background='green')
        self.update()
        self.coursesListbox.bind('<<ListboxSelect>>', self.estimate)
        self.programsListbox.bind('<<ListboxSelect>>', self.analyze)

    def estimate(self, event):  # estimating phase
        try:
            for wid in self.frame3.winfo_children():
                wid.destroy()
            self.label4 = Label(self.frame3,
                                text="     Top 3 Estimates:",
                                font='Helvetica 10 bold')
            self.label4.pack(in_=self.frame3)
        except:
            print 'ERROR !!!!'
        widget = event.widget
        selection = widget.curselection()
        picked = widget.get(selection[0])
        x = picked.split('(')
        dict_ = {}
        for cat in self.course_list:  # getting estimating scores
            dict_[cat] = self.classifier_obj.prob(x[1], cat) * 10

        scores = dict_
        sorted_scores = sorted(scores.items(),
                               key=operator.itemgetter(1),
                               reverse=True)  # sorting dictionary
        top_3 = sorted_scores[0:3]  # getting top 3 scores
        print top_3
        dict_temp = {x[0].split(' ')[0]: top_3}
        m = 1
        for key, value in dict_temp.items():  # adding items as labels
            for i in value:
                department, score = i
                if department != key:  # checking if it is true estimation or not
                    color = 'red'
                else:
                    color = 'green'
                self.first_element = Label(self.frame3,
                                           text=department + ':' + str(score),
                                           font='Helvetica 15 bold',
                                           background=color,
                                           width=20)
                if m == 1:
                    self.first_element.pack(in_=self.frame3)
                elif m == 2:
                    self.first_element.pack(in_=self.frame3)
                elif m == 3:
                    self.first_element.pack(in_=self.frame3)
                m = m + 1

    def analyze(self, event):
        try:
            self.estimatesListbox.delete('1.0', END)
        except:
            print 'ERROR'
        widget = event.widget
        selection = widget.curselection()
        picked = widget.get(selection[0])
        cat_ = picked
        course_names = {}
        for i in self.obj_list:  # creating a dict. keys name of courses, values code of
            if i.first_code == cat_:  # filtering
                print i.first_code, cat_
                name = i.name.split('(')[0]
                course_names[name] = i.code
            else:
                continue
        info = {}
        for course in course_names.keys():  # finds best match for each course
            score_dict = {}
            for cat in self.course_list:
                score_dict[cat] = self.classifier_obj.prob(course, cat)
            sorted_scores = sorted(score_dict.items(),
                                   key=operator.itemgetter(1),
                                   reverse=True)
            info[course] = sorted_scores[0][0]
        all_info = {
            'Total Number Of Courses: ': str(len(info))
        }  # creating initial analyzing data
        q = 0
        for item in info.values():  # amount of accurate data
            if item != cat_:
                q = q + 1
        all_info['Inaccurate Classification: '] = str(q)
        all_info['Accurately Classified: '] = len(info) - q
        all_info['Accuracy: '] = '%' + str(
            (float(all_info['Accurately Classified: ']) / float(len(info))) *
            100)
        _ = all_info.keys()
        _.sort()
        for infos in _:
            self.estimatesListbox.insert(END,
                                         infos + str(all_info[infos]) + '\n ')

        for course_ in info:
            self.estimatesListbox.insert(
                END,
                '\t' + course_names[course_] + '-->' + info[course_] + '\n')
Ejemplo n.º 44
0
    def ventanaVoluntarios(self,row):

        id = -1
        guardar = TRUE
        # Creamos una ventana nueva
        t = Toplevel(self)
        t.wm_title("Crear Voluntario")

        # Etiqueta y entrada de nombre
        Label(t, text="Nombre").grid(row=0)
        entradaNombre = Entry(t)
        entradaNombre.grid(row=0, column=1,sticky = "ew")

        # Etiqueta y entrada de apellidos
        Label(t, text="Apellidos").grid(row=1)
        entradaApellidos = Entry(t)
        entradaApellidos.grid(row=1, column=1,sticky = "ew")

        # Etiqueta y entrada de DNI
        Label(t, text="DNI").grid(row=2)
        entradaDNI = Entry(t)
        entradaDNI.grid(row=2, column=1,sticky = "ew")

        # Etiqueta y entrada de Dirreccion
        Label(t, text="Direccion").grid(row=3)
        entradaDireccion = Entry(t)
        entradaDireccion.grid(row=3, column=1)

        # Etiqueta y seleccion de Estudios
        Label(t, text="Estudios").grid(row=4)
        box_value = StringVar()
        self.getEstudios()
        self.selectorEstudios = Combobox(t, textvariable=box_value, state='readonly')
        self.selectorEstudios['values'] = self.listadoEstudios[0]
        self.selectorEstudios.configure(width=25)
        self.selectorEstudios.current(0)
        self.selectorEstudios.grid(row=4, column=1)

        botonEditarEstudios = Button(t, text="Editar", command=self.editarEstudio)
        botonNuevosEstudios = Button(t, text="Nuevo", command=self.nuevoEstudio)
        botonEditarEstudios.grid(row=4, column=2)
        botonNuevosEstudios.grid(row=4, column=3)

        # Etiqueta y seleccion de Genero
        Label(t, text="Genero").grid(row=5)
        seleccionGenero = Combobox(t, values=["Masculino (M)", "Femenino (F)"], state='readonly')
        seleccionGenero.grid(row=5, column=1)

        # Etiqueta y seleccion de Parroquial
        Label(t, text="Parroquial").grid(row=6)
        box_value = StringVar()
        self.getParroquial()
        self.selectorParroquial = Combobox(t, textvariable=box_value, state='readonly')
        self.selectorParroquial['values'] = self.listadoParroquial[0]
        self.selectorParroquial.configure(width=25)
        self.selectorParroquial.current(0)
        self.selectorParroquial.grid(row=6, column=1)

        botonEditarParroquial = Button(t, text="Editar", command=self.editarParroquia)
        botonNuevaParroqual = Button(t, text="Nuevo", command=self.nuevaParroquia)
        botonEditarParroquial.grid(row=6, column=2)
        botonNuevaParroqual.grid(row=6, column=3)

        # Etiqueta y seleccion de Correo
        Label(t, text="Correo").grid(row=0, column=4)
        entradaCorreo = Entry(t)
        entradaCorreo.grid(row=0, column=5)

        Label(t, text="Telefono 1").grid(row=1, column=4)
        entradaTelefono1 = Entry(t)
        entradaTelefono1.grid(row=1, column=5)

        Label(t, text="Telefono 2").grid(row=2, column=4)
        entradaTelefono2 = Entry(t)
        entradaTelefono2.grid(row=2, column=5)

        # Etiqueta y entrada de Fecha
        Label(t, text="Fecha").grid(row=3, column=4)
        entradaAno = Entry(t)
        entradaMes = Entry(t)
        entradaDia = Entry(t)
        entradaAno.grid(row=3, column=5)
        entradaMes.grid(row=3, column=6)
        entradaDia.grid(row=3, column=7)

        # Etiqueta y seleccion de Pais
        Label(t, text="Pais").grid(row=4, column=4)
        box_value = StringVar()
        self.getPais()
        self.selectorPais = Combobox(t, textvariable=box_value, state='readonly')
        self.selectorPais['values'] = self.listadoPais[0]
        self.selectorPais.configure(width=25)
        self.selectorPais.current(0)
        self.selectorPais.grid(row=4, column=5)

        botonEditarPais = Button(t, text="Editar", command=self.editarPais)
        botonNuevaPais = Button(t, text="Nuevo", command=self.nuevoPais)
        botonEditarPais.grid(row=4, column=6)
        botonNuevaPais.grid(row=4, column=7)

        #Rellenamos los cambos si estamos editando
        if row > -1:
            voluntario = self.table.model.getRecordAtRow(row)
            entradaNombre.insert(END,voluntario['nombre'])
            entradaApellidos.insert(END,voluntario['apellidos'])
            entradaCorreo.insert(END,voluntario['correo_electronico'])
            entradaTelefono1.insert(END,voluntario['telefono_1'])
            entradaTelefono2.insert(END,voluntario['telefono_2'])
            entradaDireccion.insert(END,voluntario['direccion'])
            entradaDNI.insert(END,voluntario['dni'])
            self.selectorEstudios.set(voluntario['estudio'])
            self.selectorParroquial.set(voluntario['parroquial'])
            guardar = FALSE
            id = voluntario['id']





        button5 = Button(t, text="Guardar", command=lambda: self.nuevoVoluntario(entradaNombre.get(),
                                                                                 entradaApellidos.get(),entradaDNI.get(),entradaDireccion.get(),
                                                                                 entradaCorreo.get(),1,self.listadoEstudios[1][self.selectorEstudios.current()],
                                                                                 self.listadoParroquial[1][self.selectorParroquial.current()],
                                                                                 1,entradaTelefono1.get(),entradaTelefono2.get(),"M","2001-01-01",t,guardar,id))
        button6 = Button(t, text="Cancelar", command=t.destroy)

        button5.grid(row=7, column=4)
        button6.grid(row=7, column=5)
Ejemplo n.º 45
0
    def initUI(self):
        self.master.title("Telegram UnlimitMe")
        self.master.minsize(width=500, height=300)
        self.pack(fill=BOTH, expand=True)

        frame1 = Frame(self)
        frame1.pack(fill=X)

        tknlbl = Label(frame1, text="Token", width=7, font=("Helvetica", 10))
        tknlbl.pack(side=LEFT, padx=5, pady=5)

        tkntxt = Entry(frame1, font=("Helvetica", 10))
        tkntxt.pack(fill=X, padx=5, expand=True)
        tkntxt.insert(0, self.loadtoken())

        frame2 = Frame(self)
        frame2.pack(fill=X)

        cidlbl = Label(frame2, text="Chat ID", width=7, font=("Helvetica", 10))
        cidlbl.pack(side=LEFT, padx=5, pady=5)

        cidtxt = Entry(frame2, font=("Helvetica", 10))
        cidtxt.pack(fill=X, padx=5, expand=True)
        cidtxt.insert(0, self.loadcid())

        frame3 = Frame(self)
        frame3.pack(fill=X)

        msglbl = Label(frame3, text="Message", width=8, font=("Helvetica", 10))
        msglbl.pack(side=LEFT, anchor=N, padx=5, pady=5)

        msgtxt = Entry(frame3, width=30, font=("Helvetica", 10))
        msgtxt.insert(
            0,
            "UnlimitMe script by (Gooogle)[https://github.com/GooogIe/UnlimitMe]"
        )
        msgtxt.pack(fill=BOTH, padx=5, pady=2)

        frame8 = Frame(self)
        frame8.pack(fill=X)

        tmslbl = Label(frame8,
                       text="Spam times",
                       width=10,
                       font=("Helvetica", 10))
        tmslbl.pack(side=LEFT, anchor=N, padx=5, pady=5)

        tmstxt = Entry(frame8, width=30, font=("Helvetica", 10))
        tmstxt.insert(0, "5")
        tmstxt.pack(fill=BOTH, padx=5, pady=2)

        frame7 = Frame(self)
        frame7.pack(fill=X)

        imglbl = Label(frame7,
                       text="Image Source",
                       width=15,
                       font=("Helvetica", 10))
        imglbl.pack(side=LEFT, anchor=N, padx=5, pady=5)

        imgtxt = Entry(self, width=30, font=("Helvetica", 10))
        imgtxt.insert(0, "http://www.photo.it/ok.png")
        imgtxt.pack(fill=BOTH, padx=5, pady=2)

        frame4 = Frame(self)
        frame4.pack(fill=X)

        x = StringVar()
        x.set("Chat IDS found: \n" + str(chatids(tkntxt.get())))
        cidslbl = Label(frame4,
                        textvariable=x,
                        width=40,
                        font=("Helvetica", 10))
        cidslbl.pack(side=LEFT, anchor=N, padx=5, pady=5)

        listbox = Listbox(frame4, width=30, font=("Helvetica", 10))
        listbox.pack(side=RIGHT, padx=5, pady=5)

        frame5 = Frame(self)
        frame5.pack(fill=X)

        spambtn = Button(frame5,
                         relief=FLAT,
                         bg="#1EFE7B",
                         text="Spam",
                         font=("Helvetica", 10),
                         fg="#ffffff",
                         width=15,
                         command=lambda: self.flood(tmstxt.get(), msgtxt.get(
                         ), tkntxt.get(), cidtxt.get()))
        spambtn.pack(side=RIGHT, padx=5, pady=5)

        sendbtn = Button(
            frame5,
            relief=FLAT,
            bg="#2ECC71",
            text="Send",
            font=("Helvetica", 10),
            fg="#ffffff",
            width=15,
            command=lambda: self.sendMessage(msgtxt.get(), tkntxt.get(
            ), cidtxt.get()) & listbox.insert(END, "You: " + msgtxt.get()))
        sendbtn.pack(side=RIGHT, padx=5, pady=5)

        imgbtn = Button(frame5,
                        relief=FLAT,
                        bg="#1ABC9C",
                        text="Send a Photo",
                        font=("Helvetica", 10),
                        fg="#ffffff",
                        width=15,
                        command=lambda: self.sendImage(imgtxt.get(
                        ), tkntxt.get(), cidtxt.get()))
        imgbtn.pack(side=LEFT, padx=5, pady=5)

        savebtn = Button(
            frame5,
            relief=FLAT,
            bg="#E74C3C",
            text="Save CID & Token",
            font=("Helvetica", 10),
            fg="#ffffff",
            width=15,
            command=lambda: self.saveall(tkntxt.get(), cidtxt.get()))
        savebtn.pack(side=LEFT, padx=5, pady=5)

        getcidsbtn = Button(frame5,
                            relief=FLAT,
                            bg="#3498DB",
                            text="Reload Chat IDS",
                            font=("Helvetica", 10),
                            fg="#ffffff",
                            width=15,
                            command=lambda: x.set("Chat IDS found: \n" +
                                                  chatids(tkntxt.get())))
        getcidsbtn.pack(side=LEFT, padx=5, pady=5)

        frame6 = Frame(self)
        frame6.pack(fill=X, expand=True)

        abtlbl = Label(
            frame6,
            font=("Helvetica", 10),
            text="Created by Habb0n - (c) 2016 - Using Python & Tkinter",
            width=50)
        abtlbl.pack(side=BOTTOM, anchor=N, padx=1, pady=1)
Ejemplo n.º 46
0
class Example(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent        
        
      
        self.parent.title("Jo Ion Picker") 
        
        self.pack(fill=BOTH, expand=1)

        self.compounds = deisotope(filename=input_file)
        
        self.error_label = Label(self, text="Error in ppm")     
        self.error_label.place(x=20, y=730)

        self.entry = Entry(self, text='error in ppm')
        self.entry.place(x=20, y=750)
        self.entry.insert(10,'5')
        self.b = Button(self, text="ReCalc Error", width=15, \
                        command=self.callback)
        self.b.place(x=20, y=770)

        self.b_output = Button(self, text="Export", width=10, command=self.write_output)
        self.b_output.place(x=20, y=800)

        #self.b_output = Button(self, text="Allowed", width=10, command=self.only_allowed_ions)
        #self.b_output.place(x=20, y=830)


        self.gaps=IntVar()
        self.check_gaps = Checkbutton(self, text='Remove Gaps', variable=self.gaps,onvalue=1, offvalue=0, command=self.remove_gaps_call)
        #self.check.pack()
        self.check_gaps.place(x=20, y=830)


        self.scrollbar = Scrollbar(self, orient=VERTICAL)
        self.lb = Listbox(self, height=46, yscrollcommand=self.scrollbar.set)
        self.scrollbar.config(command=self.lb.yview)
        self.scrollbar.pack(side=LEFT, fill=Y)

        
        for compound in self.compounds:
            print "found", compound.get_base_peak()
            mzs = compound.get_mz_list()
            num_mzs = len(mzs)
            entry = str(mzs[0]) + "    " + str(num_mzs)
            self.lb.insert(END, entry)
            
            
        self.lb.bind("<<ListboxSelect>>", self.onSelect)    
            
        self.lb.place(x=20, y=20)
        

        self.var = StringVar()
        #self.label = Label(self, text=0, textvariable=self.var)        
        #self.label.place(x=20, y=710)

        self.mz_label = Label(self, text="M/Z        Num Ions")
        self.mz_label.place(x=20, y=0)

        f = Figure(figsize=(8,11), dpi=100)
        self.ax = f.add_subplot(111)
        mass_list = self.compounds[0].get_mz_list()
        print mass_list
        intensity_list = self.compounds[0].get_intensity_list()
        mass_spec_plot = self.ax.bar(mass_list, intensity_list,\
        width=0.05)
        min_mz = mass_list[0]
        max_mz = mass_list[-1]
        self.ax.set_xlim([min_mz-1, max_mz+1])
        self.ax.set_ylim([0, 1.1*max(intensity_list)])
        self.ax.set_xticks(mass_list)
        self.ax.set_xticklabels(mass_list, rotation=45)
        self.ax.set_title("Base Ion:" + str(mass_list[0]))

        self.canvas = FigureCanvasTkAgg(f, master=self)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side=RIGHT)

    def onSelect(self, val):
      
        sender = val.widget
        idx = sender.curselection()
        value = sender.get(idx)   

        self.var.set(value)

        mz_to_search = value.split()[0]

        self.ax.clear()
        for i, compound in enumerate(self.compounds):
            if float(mz_to_search) == compound.get_base_peak():
                index = i
        mass_list = self.compounds[index].get_mz_list()
        print mass_list
        intensity_list = self.compounds[index].get_intensity_list()
        mass_spec_plot = self.ax.bar(mass_list, intensity_list,\
        width=0.05)
        min_mz = mass_list[0]
        max_mz = mass_list[-1]
        self.ax.set_xlim([min_mz-1, max_mz+1])
        self.ax.set_ylim([0, 1.1*max(intensity_list)])
        self.ax.set_xticks(mass_list)
        self.ax.set_xticklabels([str(mass) for mass in mass_list], rotation=45)
        self.ax.set_title("Base Ion:" + str(mass_list[0]))
        
        self.canvas.draw()

    def only_allowed_ions(self):

        ion_list = []

        fp = open('ions.csv', 'r')
        lines = fp.readlines()
        for line in lines:
            ion_list.append(float(line))
        #print ion_list
            
        self.compounds = deisotope(filename=input_file,max_error = float(self.entry.get()))

        new_compound_list = []
        

        for compound in self.compounds:
            for ion in ion_list:
                error_Da = float(self.entry.get())*compound.get_base_peak()/1e6
                if compound.get_base_peak() > ion-error_Da \
                   and compound.get_base_peak() < ion + error_Da:
                    new_compound_list.append(compound)

        for compound in new_compound_list:
            print "compound:",compound.get_base_peak()
        
        self.lb.delete(0, END)
        for compound in new_compound_list:
            mzs = compound.get_mz_list()
            num_mzs = len(mzs)
            entry = str(mzs[0]) + "    " + str(num_mzs)
            self.lb.insert(END, entry)
        
        

    def callback(self):
        self.compounds = deisotope(filename=input_file, max_error = float(self.entry.get()))
        self.lb.delete(0, END)
        for compound in self.compounds:
            mzs = compound.get_mz_list()
            num_mzs = len(mzs)
            entry = str(mzs[0]) + "    " + str(num_mzs)
            self.lb.insert(END, entry)
        print self.entry.get()


    def remove_gaps_call(self):
        self.compounds = deisotope(filename=input_file,max_error = float(self.entry.get()))
        check_for_gaps(self.compounds)
        self.lb.delete(0, END)
        for compound in self.compounds:
            mzs = compound.get_mz_list()
            num_mzs = len(mzs)
            entry = str(mzs[0]) + "    " + str(num_mzs)
            self.lb.insert(END, entry)
        print self.entry.get()


    def do_list_update(self):
        l_multi = self.multi.get()
        l_missing = self.missing.get()
        l_m1gtm2 = self.m1gtm2.get()
        #  possible situations: 000, 001,010,100, 011,101, 110, 111
        if l_multi == 0 and l_missing == 0 and l_m1gtm2 ==0:
            self.lb.delete(0, END)
            for compound in self.compounds:
                mzs = compound.get_mz_list()
                num_mzs = len(mzs)
                entry = str(mzs[0]) + "    " + str(num_mzs)
                self.lb.insert(END, entry)
                
        elif l_multi == 0 and l_missing == 0 and l_m1gtm2 ==1:
            self.lb.delete(0, END)
            for compound in self.compounds:
                mzs = compound.get_mz_list()
                num_mzs = len(mzs)
                intensities = compound.get_intensity_list()
                if intensities[-1] <= intensities[0]:
                    entry = str(mzs[0]) + "    " + str(num_mzs)
                    self.lb.insert(END, entry)
                    
        elif l_multi == 0 and l_missing == 1 and l_m1gtm2 ==0:
            self.lb.delete(0, END)
            for compound in self.compounds:
                mzs = compound.get_mz_list()
                num_mzs = len(mzs)
                if mzs[-1] - mzs[0] <1.75: # margin of error allowed here
                    entry = str(mzs[0]) + "    " + str(num_mzs)
                    self.lb.insert(END, entry)
                    
        elif l_multi == 1 and l_missing == 0 and l_m1gtm2 ==0:
            self.lb.delete(0, END)
            for compound in self.compounds:
                mzs = compound.get_mz_list()
                num_mzs = len(mzs)
                if num_mzs >1:
                    entry = str(mzs[0]) + "    " + str(num_mzs)
                    self.lb.insert(END, entry)
                    
        elif l_multi == 0 and l_missing == 1 and l_m1gtm2 ==1:
            self.lb.delete(0, END)
            for compound in self.compounds:
                mzs = compound.get_mz_list()
                intensities = compound.get_intensity_list()
                num_mzs = len(mzs)
                if mzs[-1] - mzs[0] <1.75 and intensities[-1] <= intensities[0]:
                    entry = str(mzs[0]) + "    " + str(num_mzs)
                    self.lb.insert(END, entry)
                
        elif l_multi == 1 and l_missing == 0 and l_m1gtm2 ==1:
            self.lb.delete(0, END)
            for compound in self.compounds:
                mzs = compound.get_mz_list()
                intensities = compound.get_intensity_list()
                num_mzs = len(mzs)
                if num_mzs >1 and intensities[-1] <= intensities[0]:
                    entry = str(mzs[0]) + "    " + str(num_mzs)
                    self.lb.insert(END, entry)
                
        elif l_multi == 1 and l_missing == 1 and l_m1gtm2 ==0:
            self.lb.delete(0, END)
            for compound in self.compounds:
                mzs = compound.get_mz_list()
                num_mzs = len(mzs)
                if num_mzs >1 and mzs[-1] - mzs[0] <1.75:
                    entry = str(mzs[0]) + "    " + str(num_mzs)
                    self.lb.insert(END, entry)
                
        elif l_multi == 1 and l_missing == 1 and l_m1gtm2 ==1:
            self.lb.delete(0, END)
            for compound in self.compounds:
                mzs = compound.get_mz_list()
                intensities = compound.get_intensity_list()
                num_mzs = len(mzs)
                if num_mzs >1 and mzs[-1] - mzs[0] <1.75 and \
                    intensities[1] <= intensities[0]:
                    entry = str(mzs[0]) + "    " + str(num_mzs)
                    self.lb.insert(END, entry)
        else:
            pass # error!
            

    def write_output(self):
        op = open('edited_output.csv', 'w')

        op.write('mz, intensity, mz, intensity, mz, intensity\n')
        items = self.lb.get(0,END)
        output_list = []
        for item in items:
            mz_val = item.split(' ')[0]
            for compound in self.compounds:
                if float(mz_val) == compound.get_base_peak():
                    mzs = compound.get_mz_list()
                    intensities = compound.get_intensity_list()
                    for i, mz in enumerate(mzs):
                        op.write(str(mz) + ',' + str(intensities[i]) + ',')
                    op.write('\n')
        op.close()