Beispiel #1
0
    def __init__(self, pipepanel, pipeline_name, *args, **kwargs) :
        PipelineFrame.__init__(self, pipepanel, pipeline_name, *args, **kwargs)
        self.pairs = None
        
        eframe = self.eframe = LabelFrame(self,text="Options") 
        #,fg=textLightColor,bg=baseColor)
        eframe.grid( row=5, column=1, sticky=W, columnspan=7, padx=10, pady=5 )
        
        label = Label(eframe,text="Pipeline")#,fg=textLightColor,bg=baseColor)
        label.grid(row=3,column=0,sticky=W,padx=10,pady=5)

        PipelineLabels = ['Initial QC', 
			  'Germline',
			  'Somatic Tumor-Normal',
                          'Somatic Tumor-Only']
        Pipelines=["initialqcgenomeseq",
                   "wgslow", 
		   'wgs-somatic',
                   'wgs-somatic-tumoronly']

        self.label2pipeline = { k:v for k,v in zip(PipelineLabels, Pipelines)}
        PipelineLabel = self.PipelineLabel = StringVar()
        Pipeline = self.Pipeline = StringVar()
        PipelineLabel.set(PipelineLabels[0])
        
        #om = OptionMenu(eframe, Pipeline, *Pipelines, command=self.option_controller)
        om = OptionMenu(eframe, PipelineLabel, *PipelineLabels, command=self.option_controller)
        om.config()#bg = widgetBgColor,fg=widgetFgColor)
        om["menu"].config()#bg = widgetBgColor,fg=widgetFgColor)
        #om.pack(side=LEFT,padx=20,pady=5)
        om.grid(row=3,column=1,sticky=W,padx=10,pady=5)
Beispiel #2
0
    def __init__(self, pipepanel, pipeline_name, *args, **kwargs) :
        PipelineFrame.__init__(self, pipepanel, pipeline_name, *args, **kwargs)
        self.info = None
        
        eframe = self.eframe = LabelFrame(self,text="Options") 
        #,fg=textLightColor,bg=baseColor)
        eframe.grid( row=5, column=1, sticky=W, columnspan=7, padx=10, pady=5 )
        
        label = Label(eframe,text="Pipeline:")#,fg=textLightColor,bg=baseColor)
        label.grid(row=3,column=0,sticky=W,padx=10,pady=5)
        Pipelines=["InitialChIPseqQC", "ChIPseq" ]
        Pipeline = self.Pipeline = StringVar()
        Pipeline.set(Pipelines[0])
        
        om = OptionMenu(eframe, Pipeline, *Pipelines, command=self.option_controller)
        om.config()#bg = widgetBgColor,fg=widgetFgColor)
        om["menu"].config()#bg = widgetBgColor,fg=widgetFgColor)
        #om.pack(side=LEFT,padx=20,pady=5)
        om.grid(row=3,column=1,sticky=W,padx=20,pady=5)

        readtypes = ['Single', 'Paired']
        self.readtype = readtype = StringVar()
        readtype.set(readtypes[0])
        readtype_menu = OptionMenu(eframe, readtype, *readtypes)
        readtype_menu.grid(row=3, column=3, sticky=E, pady=5)
        readtype_label = Label(eframe, text="-end   ")
        readtype_label.grid( row=3, column=4, stick=W, pady=5)

        self.add_info(eframe)
        self.option_controller()
        self.peakinfo_fn = 'peakcall.tab'
        self.contrast_fn = 'contrast.tab'
class GuiBasicSettings(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.pack()
        
        #Unit
        self.sizeUnits = {"Byte": 1, "KiB":1024, "MiB":1024**2, "GiB":1024**3}
        
        self._initFile()
        self._initSize()

    def _initFile(self):
        self._fileLbl = Label(self, text="File:       ")
        self._fileTxt = Entry(self)
        self._fileTxt.insert(0, "/tmp/out.txt")
        self._fileBtn = Button(self, text="Create", command=self._callbackFun)
        self._fileLbl.grid(row=0, column=0)
        self._fileTxt.grid(row=0, column=1)
        self._fileBtn.grid(row=0, column=2)
    
    def _initSize(self):
        self._sizeLbl = Label(self, text="FileSize:  ")
        self._sizeTxt = Entry(self)
        self._sizeTxt.insert(0, "1024")
        
        self._sizeVar    = StringVar()
        self._sizeVar.set("Byte")       #FIXME: replace "Byte" with variable
        sizeOptParam = (self, self._sizeVar) + tuple(self.sizeUnits.keys()) 
        self._sizeOptMen = OptionMenu(*sizeOptParam)
        
        self._sizeLbl.grid(row=1, column=0)
        self._sizeTxt.grid(row=1, column=1)
        self._sizeOptMen.grid(row=1, column=2)
    
    def _callbackFun(self):
        print("_callbackBtn")
        self.outerCallback()
    
    def enableButton(self, enabled=True):
        if enabled:
            self._fileBtn.config(state="normal")
        else:
            self._fileBtn.config(state="disabled")
    def getFileName(self):
        return self._fileTxt.get()
        
    def getFileSize(self):
        mult = int(self.sizeUnits[self._sizeVar.get()])
        val  = int(self._sizeTxt.get())
        return val * mult   
    
    def setCallback(self, aCallback):
        self.outerCallback = aCallback
class AccountDialog(gui.tksimpledialog.Dialog):
    def __init__(self, parent, title="", login_name="", password="", path="", dx="dx11"):
        self.login_name = login_name
        self.password = password
        self.path = path
        self.dx = dx
        self.entry_ln = None
        self.variable = None
        self.entry_pw = None
        self.entry_path = None
        self.entry_dx = None
        super().__init__(parent, title)

    def body(self, master):
        Label(master, text="Login Name:").grid(row=0)
        Label(master, text="Password:"******"Eve Path:").grid(row=2)
        Label(master, text="DirectX:").grid(row=3)

        self.entry_ln = Entry(master)
        self.entry_pw = Entry(master, show="*")
        self.entry_path = Entry(master)
        self.variable = StringVar(master)
        self.variable.set(self.dx)
        self.entry_dx = OptionMenu(master, self.variable, "dx9", "dx11")

        self.entry_ln.insert(END, self.login_name)
        self.entry_pw.insert(END, self.password)
        self.entry_path.insert(END, self.path)

        # self.entry_path.bind("<FocusIn>", self.select_eve_path)

        self.entry_ln.grid(row=0, column=1)
        self.entry_pw.grid(row=1, column=1)
        self.entry_path.grid(row=2, column=1)
        self.entry_dx.grid(row=3, column=1)
        return self.entry_ln

        # def select_eve_path(self, event):

    # if event.widget == self.entry_path:
    #            self.path
    #            res = os.path.normpath(askdirectory(initialdir=self.path))
    #           self.path = res
    #            self.entry_path.insert(END, res)

    def apply(self):
        login_name = self.entry_ln.get()
        password = self.entry_pw.get()
        path = self.entry_path.get()
        dx = self.variable.get()
        self.result = [login_name, password, path, dx]
Beispiel #5
0
    def __init__(self, pipepanel, pipeline_name, *args, **kwargs) :
        PipelineFrame.__init__(self, pipepanel, pipeline_name, *args, **kwargs)
        self.pairs = None
        
        eframe = self.eframe = LabelFrame(self,text="Options") 
        #,fg=textLightColor,bg=baseColor)
        eframe.grid( row=5, column=1, sticky=W, columnspan=7, padx=10, pady=5 )
        
        label = Label(eframe,text="Pipeline")#,fg=textLightColor,bg=baseColor)
        label.grid(row=3,column=0,sticky=W,padx=10,pady=5)
        PipelineLabels = ["Initial QC", "Germline", 'Somatic Tumor-Normal', 'Somatic Tumor-Only']
        Pipelines=["initialqc", "exomeseq-germline", "exomeseq-somatic", "exomeseq-somatic-tumoronly"]
        self.label2pipeline = { k:v for k,v in zip(PipelineLabels, Pipelines)}

        Pipeline = self.Pipeline = StringVar()
        PipelineLabel = self.PipelineLabel = StringVar()
        self.Pipeline = StringVar()

        PipelineLabel.set(PipelineLabels[0])
        
        om = OptionMenu(eframe, PipelineLabel, *PipelineLabels, command=self.option_controller)
        #om.config()#bg = widgetBgColor,fg=widgetFgColor)
        #om["menu"].config()#bg = widgetBgColor,fg=widgetFgColor)
        #om.pack(side=LEFT,padx=20,pady=5)
        om.grid(row=3,column=1,sticky=W,padx=10,pady=5)

        targetsL=Label(eframe,
                       text="Target Capture Kit")
                       #,fg=textLightColor,bg=baseColor)
        targetsL.grid(row=5,column=0,sticky=W,padx=10,pady=5)
        targetsE = Entry(eframe,textvariable=self.targetspath, width=50)

        if self.genome=="hg19":
            self.targetspath.set( 
                "/data/CCBR_Pipeliner/db/PipeDB/lib/SS_v5_UTRs_hg19.bed" )
        elif self.genome=="hg38":
            self.targetspath.set( 
                "/data/CCBR_Pipeliner/db/PipeDB/lib/SS_v5_UTRs_hg38.bed" )
        else:
            self.targetspath.set(
                "/data/CCBR_Pipeliner/db/PipeDB/lib/SureSelect_mm10.bed")

        targetsE.grid(row=5,column=1,columnspan=6,sticky=W,padx=10,pady=5)
        self.targetspath.trace('w', lambda a,b,c,x="targetspath":self.makejson(x))
        label = Label (eframe, 
                       text = 
                       "By default, the path to the Agilent V5+UTR targets file is filled in here" ) 
        
        label.grid(row=6, column=0, columnspan=5, sticky=W, padx=10, pady=5)
Beispiel #6
0
 def __init__(self, pipepanel, pipeline_name, *args, **kwargs) :
     PipelineFrame.__init__(self, pipepanel, pipeline_name, *args, **kwargs)
     self.pairs = None
     
     eframe = self.eframe = LabelFrame(self,text="Options") 
     #,fg=textLightColor,bg=baseColor)
     eframe.grid( row=5, column=1, sticky=W, columnspan=7, padx=10, pady=5 )
     
     label = Label(eframe,text="Pipeline")#,fg=textLightColor,bg=baseColor)
     label.grid(row=3,column=0,sticky=W,padx=10,pady=5)
     Pipelines=["initialqcgenomeseq","wgslow"]
     Pipeline = self.Pipeline = StringVar()
     Pipeline.set(Pipelines[0])
     
     om = OptionMenu(eframe, Pipeline, *Pipelines, command=self.option_controller)
     om.config()#bg = widgetBgColor,fg=widgetFgColor)
     om["menu"].config()#bg = widgetBgColor,fg=widgetFgColor)
     #om.pack(side=LEFT,padx=20,pady=5)
     om.grid(row=3,column=1,sticky=W,padx=10,pady=5)
Beispiel #7
0
n = 0


def start_stop():
    global n
    n = n + 1
    if n == 1:
        song_name = songs_listbox.get()
        pygame.mixer.music.load(song_name)
        pygame.mixer.play(0)

    elif (n % 2) == 0:
        pygame.mixer.music.pause()
    elif (n % 2) != 0:
        pygame.mixer.music.unpause()


l1 = Label(window, text="MUSIC PLAYER", font="times 20")
l1.grid(row=1, column=1)

b2 = Button(window, text='o', width=20, command=start_stop)
b2.grid(row=4, column=1)

songs_list = os.listdir()
songs_listbox = StringVar(window)
songs_listbox.set("select songs")
menu = OptionMenu(window, songs_listbox, *songs_list)
menu.grid(row=4, column=4)

window.mainloop()
Beispiel #8
0
class FileEditBar(Frame, object):


    def __init__(self, master, directory='.', filesettings=None, defaultname='*unknown{}', importhook=None,
                 deletehook=None, projecthook=None, filecontenthook=None, selectfilehook=None,
                 fileslisthook=None, updatehook=None, onchangehook=None):

        self.master = master

        Frame.__init__(self, master)

        self.selected_file = StringVar()
        self.selected_file.trace("w", self.select_file)
        self._dirty = False
        self._dirty_file_name = ''
        self._editor_dirty = False

        self.dir = directory
        self.fsettings = filesettings
        self.defaultname = defaultname

        # hooks
        self.import_hook = importhook
        self.delete_hook = deletehook
        self.save_project_hook = projecthook
        self.filecontent_hook = filecontenthook
        self.update_hook = updatehook
        self.select_file_hook = selectfilehook
        self.files_list_hook = fileslisthook
        self.onchange_hook = onchangehook

        row = 0
        self.columnconfigure(1, weight=2)

        files = []
        self.file_buffer = {}
        self.file_reload = True
        if len(files) == 0: files.append("")
        self.list_files = OptionMenu(*(self, self.selected_file) + tuple(files))
        self.list_files.grid(row=row, column=1, sticky="NWE")

        # new file
        self.btn_newfile = Button(self, text='New', command=self.new_file)
        self.btn_newfile.grid(row=row, column=2, sticky="E")

        # import file
        self.btn_importfile = Button(self, text='Import', command=self.import_file)
        self.btn_importfile.grid(row=row, column=3, sticky="E")

        # delete file
        self.btn_delfile = Button(self, text='Delete', command=self.delete_file)
        self.btn_delfile.grid(row=row, column=4, sticky="E")

        # save button
        self.btn_update_file = Button(self, text='Save', command=self.save_file)
        self.btn_update_file.grid(row=row, column=6, sticky="E")

        # save as.. button
        self.btn_saveas_file = Button(self, text='Save as...', command=self.saveas_file)
        self.btn_saveas_file.grid(row=row, column=7, sticky="E")

        # editor
        row += 1
        self.editor = SyntaxHighlightingText(self, change_hook=self.onchange_filecontent)
        self.editor.grid(row=row, column=1, columnspan=7, sticky="NWES")
        self.rowconfigure(row, weight=1)


    @property
    def dirty(self):
        return self._dirty or self.file_buffer != {}


    @dirty.setter
    def dirty(self, d):
        self._dirty = (d or self.file_buffer != {})
        if self.onchange_hook:
            self.onchange_hook(dirty=self._dirty)

    def new_file(self):
        self.list_files['menu'].add_command(label=self.defaultname.format(self.fsettings.get('extension', '.mln')), command=_setit(self.selected_file, self.defaultname.format(self.fsettings.get('extension', '.mln'))))
        self.selected_file.set(self.defaultname.format(self.fsettings.get('extension', '.mln')))
        self.file_buffer[self.defaultname.format(self.fsettings.get('extension', '.mln'))] = ''
        self.editor.delete("1.0", END)
        self.dirty = True


    def import_file(self):
        filename = askopenfilename(initialdir=self.dir, filetypes=self.fsettings.get('ftypes'), defaultextension=self.fsettings.get('extension', '.mln'))
        if filename:
            fpath, fname = ntpath.split(filename)
            self.dir = os.path.abspath(fpath)
            content = mlnpath(filename).content
            if self.import_hook is not None:
                self.import_hook(fname, content)
            self.update_file_choices()
            self.selected_file.set(fname)
            self.dirty = True


    def delete_file(self):
        fname = self.selected_file.get().strip()

        # remove element from project mlns and buffer
        if fname in self.file_buffer:
            del self.file_buffer[fname]

        if self.delete_hook is not None:
            self.delete_hook(fname)

        f = self.update_file_choices()
        # select first element from remaining list
        if f: self.list_files['menu'].invoke(0)
        else:
            self.selected_file.set('')
            self.editor.delete("1.0", END)
        self.dirty = True



    def save_all_files(self):
        current = self.selected_file.get().strip()
        for f in self.file_buffer:
            content = self.file_buffer[f]
            if f == current:
                content = self.editor.get("1.0", END).strip()

            if self.update_hook is not None:
                self.update_hook(f, f.strip('*'), content)

        # reset buffer, dirty flag for editor and update mln selections
        self.file_buffer.clear()
        self._editor_dirty = False
        self.update_file_choices()
        self.dirty = False

        if self.save_project_hook is not None:
            self.save_project_hook()


    def save_file(self):
        oldfname = self.selected_file.get().strip()
        if oldfname == self.defaultname.format(self.fsettings.get('extension', '.mln')):
            self.saveas_file()
        else:
            self.update_file(oldfname, new=oldfname.strip('*'), askoverwrite=False)


    def saveas_file(self):
        oldfname = self.selected_file.get().strip()
        res = tkinter.simpledialog.askstring('Save as', "Enter a filename", initialvalue=oldfname.strip('*'))
        if res is None: return
        elif res:
            if not res.endswith(self.fsettings.get('extension')):
                res = res + self.fsettings.get('extension')
            self.update_file(oldfname, new=res)


    def update_file(self, old, new=None, askoverwrite=True):
        success = 1
        content = self.editor.get("1.0", END).strip()

        if self.update_hook is not None:
            success = self.update_hook(old.strip('*'), new, content, askoverwrite=askoverwrite)

        if success != -1:
            if old in self.file_buffer:
                del self.file_buffer[old]

            # reset dirty flag for editor and update mln selections
            self._editor_dirty = False
            self.update_file_choices()

            fn = new if new is not None and new != '' else old
            if new != '': self.selected_file.set(fn)
            self.dirty = False

            if self.save_project_hook is not None:
                self.save_project_hook()


    def select_file(self, *_):
        filename = self.selected_file.get().strip()
        self.dirty = True

        if filename is not None and filename != '':
            # filename is neither None nor empty
            if self._editor_dirty:
                # save current state to buffer before updating editor
                self.file_buffer[self._dirty_file_name] = self.editor.get("1.0", END).strip()
                self._editor_dirty = True if '*' in filename else False
                if not self.file_reload:
                    self.file_reload = True
                    return
            if '*' in filename:# is edited
                # load previously edited content from buffer instead of mln file in project
                content = self.file_buffer.get(filename, '').strip()
                self.editor.delete("1.0", END)
                content = content.replace("\r", "")
                self.editor.insert(INSERT, content)
                self._editor_dirty = True
                self._dirty_file_name = '*' + filename if '*' not in filename else filename
                return

            if self.files_list_hook is not None and self.filecontent_hook is not None:
                files = self.files_list_hook()
                if filename in files:
                    # load content from mln file in project
                    content = self.filecontent_hook(filename)
                    self.editor.delete("1.0", END)
                    content = content.replace("\r", "")
                    self.editor.insert(INSERT, content)
                    self._editor_dirty = False

        else:
            # should not happen
            self.editor.delete("1.0", END)
            self.list_files['menu'].delete(0, 'end')
        if self.select_file_hook is not None:
            self.select_file_hook()

    def update_file_choices(self):
        self.list_files['menu'].delete(0, 'end')
        files = []
        if self.files_list_hook is not None:
            files = self.files_list_hook()

        new_files = sorted([i for i in files if '*'+i not in self.file_buffer] + list(self.file_buffer.keys()))
        for f in new_files:
            self.list_files['menu'].add_command(label=f, command=_setit(self.selected_file, f))

        return new_files


    def onchange_filecontent(self, *_):
        if not self._editor_dirty:
            self._editor_dirty = True
            self.dirty = True
            self.file_reload = False # do not reload file, only change filename to *filename
            fname = self.selected_file.get().strip()
            fname = '*' + fname if '*' not in fname else fname
            self._dirty_file_name = fname
            self.file_buffer[self._dirty_file_name] = self.editor.get("1.0", END).strip()
            self.update_file_choices()
            self.selected_file.set(self._dirty_file_name)


    def clear(self, keep=False):
        self.file_buffer.clear()

        if not keep:
            self.editor.delete("1.0", END)

        self.dirty = False
Beispiel #9
0
ttk.Separator(root, orient=VERTICAL).grid(row=0,
                                          column=2,
                                          rowspan=6,
                                          sticky="ns")

#input for number of dice
label_Dice = Label(root, text="Roll")
diceNumInput = tk.Entry(root)
diceNumInput.insert(0, "1")

diceNumInput.grid(row=3, column=3, pady=10, padx=5)

#input for the kind of die used
diceKindInput = OptionMenu(root, diceVar, *diceList)

diceKindInput.grid(row=3, column=4, pady=2)

#input for the weapon type
wepInput = OptionMenu(root, wepVar, *weapons)
wepInput.grid(row=2, column=3, columnspan=3)
wepVar.trace(
    "w", callback
)  # Updates the diceKindInput,diceNumInput and dmgInput based on the selected value of wepInput

#input for damage type
dmgInput = OptionMenu(root, dmgVar, *damageTypes)
dmgInput.grid(row=3, column=5)

# SECTION 4: CALCULATION METHODS

Beispiel #10
0
class Window(Frame):
    def __init__(self, master):
        super().__init__()
        self.master = master
        self.master.title("Clapper")
        self.master.geometry('400x450+450+200')
        self.master.config(bg="#1b1b1b")
        # self.master.resizable(0, 0)
        self.AddWidgets()

    def AddWidgets(self):
        global User_input
        fontColor = '#f8bbd0'
        bgColor = '#1b1b1b'
        fontColorDull = '#c29ca5'

        self.TopFrame = Frame(self.master, bg=bgColor, width=400, height=50)
        self.TopFrame.grid(row=1, column=0)

        self.TextLabel = Label(self.master,
                               text="Welcome to Clapper",
                               font="Laksaman",
                               fg=fontColor,
                               bg=bgColor)
        self.TextLabel.grid(row=1, column=0, padx=10, pady=10)

        self.TextLabel = Label(self.master,
                               text="Project Title",
                               font="Laksaman",
                               fg=fontColor,
                               bg=bgColor)
        self.TextLabel.grid(row=2, sticky='W', padx=10, pady=10)

        self.TextLabel = Label(self.master,
                               text="Video File",
                               font="Laksaman",
                               fg=fontColor,
                               bg=bgColor)
        self.TextLabel.grid(row=3, sticky='W', padx=10, pady=10)

        self.TextLabel = Label(self.master,
                               text="Organization:",
                               font="Laksaman",
                               fg=fontColor,
                               bg=bgColor)
        self.TextLabel.grid(row=4, sticky='W', padx=10, pady=10)

        self.User_input = ttk.Entry(self.master, width=15)
        self.User_input.grid(row=2, column=0)
        User_input = self.User_input

        self.button = ttk.Button(self.master,
                                 text="Browse",
                                 cursor="hand2",
                                 width=10,
                                 command=self.OpenFile)
        self.button.grid(row=3, column=0, padx=10, pady=10)

        self.processButton = ttk.Button(self.master,
                                        text="Start",
                                        cursor="hand2",
                                        width=10,
                                        command=self.Process)
        self.processButton.grid(row=4, column=0, padx=10, pady=10)

        # Hidden Initially

        self.OrgLabel = Label(self.master,
                              text="Organizing...",
                              font=("Laksaman", 12),
                              fg=fontColorDull,
                              bg=bgColor)

        self.CutLabel = Label(self.master,
                              text="Compiling...",
                              font=("Laksaman", 12),
                              fg=fontColorDull,
                              bg=bgColor)

        self.RoughLabel = Label(self.master,
                                text="Rough Cut:",
                                font="Laksaman",
                                fg=fontColorDull,
                                bg=bgColor)

        self.CutButton = ttk.Button(self.master,
                                    text="Start",
                                    cursor="hand2",
                                    width=10,
                                    command=self.ScenePicker)

        self.progress = ttk.Progressbar(self.master,
                                        orient=HORIZONTAL,
                                        length=100,
                                        mode='determinate')

    def ScenePicker(self):
        global wantedTakes
        i = 7
        wantedTakes = {}
        for scene in sorted(timeStampsCleaned):
            takeList = list(timeStampsCleaned[scene].keys())
            wantedTakes[scene] = StringVar(self.master)
            wantedTakes[scene].set(takeList[0])
            self.PickerLabel = Label(
                self.master,
                text=("What take would you like for scene %s" % scene))
            self.PickerLabel.grid(row=i, column=0)
            self.Picker = OptionMenu(self.master, wantedTakes[scene],
                                     *takeList)
            self.Picker.grid(row=i + 1, column=0)
            i += 2

        self.finishedButton = ttk.Button(self.master,
                                         text="Finish",
                                         cursor="hand2",
                                         width=10,
                                         command=self.CompileCut)
        self.finishedButton.grid(row=i + 1, column=0)

    def OpenFile(self):
        #global inputDir
        global inputVideos
        inputVideos = []
        # Get the file
        files = askopenfilenames(initialdir=CURRENT,
                                 filetypes=[("Video Files",
                                             "*.mov *.mp4 *.avi")])
        print(files)
        # Split the filepath to get the directory
        for file in files:
            inputDir = os.path.split(file)[0]
            inputVideo = os.path.split(file)[1]
            inputVideos.append((inputDir, inputVideo))

    def Process(self):
        ''' Gets the project name from the input box
            Assigns it to a variable
            Calls the organize function
        '''
        global projectName
        projectName = (User_input.get())
        print("Project Name: %s" % projectName)
        self.Organize()

    def Organize(self):
        ''' Takes the input video and started searching for the QR codes
            When it finds them, it calls the Trim function
            Also creates a nested Dict with {Scenes:{Takes:Frame}}
        '''

        # Timer for keeping track of performance
        START_TIME = datetime.now()

        os.chdir(inputVideos[0][0])
        global timeStampsCleaned
        timeStampsCleaned = {}

        def org_thread(inputVideo):
            global success
            self.processButton.grid_forget()
            self.OrgLabel.grid(row=4, column=0, padx=10, pady=10)
            self.progress.grid(row=4, sticky='E', padx=10, pady=10)
            self.progress.start()

            print("CHECK")

            timeStamps = {}
            video = inputVideo
            cap = cv2.VideoCapture(video)

            fps = cap.get(cv2.CAP_PROP_FPS)

            success, frame = cap.read()

            success = True
            count = 0
            frame1 = 0
            switch = 0
            timeStamp1 = ''

            while success:
                if (count % (int(fps / 2))) == 0:
                    success, frame = cap.read()
                    count += 1
                    data = decode(frame, symbols=[ZBarSymbol.QRCODE])
                    if data == []:
                        continue
                    else:
                        dataClean = (data[0].data).decode('utf8')
                        timeStamps[dataClean] = count
                        if switch == 0:
                            timeStamp1 = dataClean
                            frame1 = count
                            switch += 1
                        if dataClean != timeStamp1:
                            frame2 = count
                            fileName = timeStamp1.split(':')[
                                0] + '.' + timeStamp1.split(':')[1] + '.mp4'
                            self.Trim(str(frame1 / fps), str(frame2 / fps - 1),
                                      video, fileName)
                            sceneNum = int(timeStamp1.split(':')[0])
                            takeNum = int(timeStamp1.split(':')[1])

                            timeStamp1 = dataClean
                            frame1 = count
                            fileNameFinal = timeStamp1.split(':')[
                                0] + '.' + timeStamp1.split(':')[1] + '.mp4'
                            sceneNumFinal = int(timeStamp1.split(':')[0])
                            takeNumFinal = int(timeStamp1.split(':')[1])

                            if not os.path.exists('%s/Scene %d' %
                                                  (projectName, sceneNum)):
                                os.makedirs('%s/Scene %d' %
                                            (projectName, sceneNum))
                            dirName = ('%s/Scene %d' %
                                       (projectName, sceneNum)) + (
                                           '/Take %d' % (takeNum)) + '.mp4'
                            shutil.move(fileName, dirName)
                else:
                    success, frame = cap.read()
                    count += 1
            try:
                self.Trim(str(frame1 / fps), str(count / fps), video,
                          fileNameFinal)
                if not os.path.exists('%s/Scene %d' %
                                      (projectName, sceneNumFinal)):
                    os.makedirs('%s/Scene %d' % (projectName, sceneNumFinal))
                dirNameFinal = ('%s/Scene %d' %
                                (projectName, sceneNumFinal)) + (
                                    '/Take %d' % (takeNumFinal)) + '.mp4'
                shutil.move(fileNameFinal, dirNameFinal)
                success = True
            except UnboundLocalError:
                success = False
                messagebox.showinfo(
                    "Error", "There was no QR Code found in this video.")

            for key in timeStamps:
                sceneNum = int(key.split(':')[0])
                takeNum = int(key.split(':')[1])
                try:
                    timeStampsCleaned[sceneNum][takeNum] = timeStamps[key]
                except:
                    timeStampsCleaned[sceneNum] = {}
                    timeStampsCleaned[sceneNum][takeNum] = timeStamps[key]

            print(timeStampsCleaned)
            cap.release()
            cv2.destroyAllWindows()

            # Timer for keeping track of performance
            END_TIME = datetime.now()
            print('Duration to Organize: {}'.format(END_TIME - START_TIME) +
                  '\n')

        for loc, inputVideo in inputVideos:
            orgthread = threading.Thread(target=org_thread(inputVideo))
            orgthread.start()

        if success:
            self.progress.stop()
            self.progress.grid_forget()
            self.OrgLabel['text'] = "Organized!"
            self.CutButton.grid(row=5, column=0, padx=10, pady=10)
            self.RoughLabel.grid(row=5, sticky='W', padx=10, pady=10)
            messagebox.showinfo(
                "Finished",
                "Finished Organizing. Continue to see a rough cut of your project."
            )

    def CompileCut(self):
        ''' Compiles the different scenes together
            Take the input from the multiple drop down menus
            Adds the names to a txt file and calls ffmpeg using subprocess
        '''
        folders = []

        def cut_thread():
            START_TIME = datetime.now()
            for scene in sorted(timeStampsCleaned):
                wantedFile = (projectName +
                              (r'\Scene %s\Take %s.mp4' %
                               (scene, wantedTakes[scene].get())))
                print(wantedFile)
                folders.append(wantedFile)

            self.CutButton.grid_forget()
            self.CutLabel.grid(row=5, column=0, padx=10, pady=10)
            self.progress.grid(row=5, sticky='E', padx=10, pady=10)
            self.progress.start()
            filenames = open("filenames.txt", "w")

            # Add all the file names to a txt for concatenation
            for folder in folders:
                filenames.write("file '" + folder + "'\n")
            filenames.close()

            ffmpegCall = (r'%s\ffmpeg' % CURRENT)
            command = [
                ffmpegCall, "-f", "concat", "-safe", "0", "-i",
                "filenames.txt", "-c", "copy",
                "%s/roughcut.mp4" % (projectName)
            ]
            call(command, shell=True, stderr=DEVNULL, stdout=DEVNULL)
            print("Finished creating a rough cut.")
            os.remove('filenames.txt')

            self.progress.stop()
            self.progress.grid_forget()
            self.CutLabel['text'] = "Generated!"
            END_TIME = datetime.now()
            print('Duration to Organize: {}'.format(END_TIME - START_TIME) +
                  '\n')
            messagebox.showinfo(
                "Finished",
                "Finished Editing. A rough cut of your project will be in your project folder."
            )

        cutthread = threading.Thread(target=cut_thread)
        cutthread.start()

    def Trim(self, start, end, inputVid, outputVid):
        ''' Edits a given video by the starting and ending points of the video
            Uses subprocess to call ffmpeg application to edit the video
            As long as it is in the same folder as this python script it will work
        '''
        ffmpegCall = (r'"%s\ffmpeg"' % CURRENT)
        trim_command = ffmpegCall + ' -i ' + inputVid + " -ss  " + start + " -to " + end + " -c copy " + outputVid
        call(trim_command, stderr=DEVNULL, stdout=DEVNULL)
        print("Finished cutting: %s" % outputVid)
Beispiel #11
0
class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent
        self.initUI()

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

        self.labelU = Label(self, text="U:")
        self.labelP = Label(self, text="P:")

        self.mailrecipient = 'GoldenSights'
        
        self.entryUsername = Entry(self)
        self.entryUsername.focus_set()
        self.entryUsername.bind('<Return>', lambda event: self.entryPassword.focus_set())

        self.entryPassword = Entry(self)
        self.entryPassword.config(show='•')
        self.entryPassword.bind('<Return>', lambda event: self.login(self.entryUsername.get(), self.entryPassword.get()))

        self.newbutton = Button(self, text="Login", command= lambda: self.login(self.entryUsername.get(), self.entryPassword.get()))
        self.newbutton.bind('<Return>', lambda event: self.login(self.entryUsername.get(), self.entryPassword.get()))
        self.newbutton.config(width=6)
        self.quitbutton = Button(self, text="Quit", command= lambda: self.quit())
        self.quitbutton.config(width=6)
    
        self.labelU.grid(row=0, column=0,padx=0)
        self.entryUsername.grid(row=0, column=1)
        self.labelP.grid(row=1, column=0)
        self.entryPassword.grid(row=1, column=1, pady=4)
        self.newbutton.grid(row=2, column=1)
        self.quitbutton.grid(row=3, column=1, pady=4)

        self.labelErrorPointer = Label(self, text="◀")

        self.indicatorGreen = PhotoImage(file="indicatorGreen.gif")
        self.indicatorRed = PhotoImage(file="indicatorRed.gif")
        self.indicatorBlue = PhotoImage(file="indicatorBlue.gif")
        self.indicatorBlack = PhotoImage(file="indicatorBlack.gif")
        

        
        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()


        w=400
        h=480
        x = (sw - w) / 2
        y = (sh - h) / 2

        self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y-50))
        

    def login(self, username, password):
        print('U: ' + username)
        self.username = username
        if username == '' or not all(char in string.ascii_letters+string.digits+'_-' for char in username):
            print('Please enter a username')
            self.entryUsername.focus_set()
            self.labelErrorPointer.grid(row=0, column=2)
        elif password == '':
            print('Please enter a password')
            self.entryPassword.focus_set()
            self.labelErrorPointer.grid(row=1, column=2)
            
        else:
            self.labelErrorPointer.grid_forget()
            print('Attempting login for ' + username)
            try:
                self.USERAGENT = username + ' practices Tkinter+PRAW mixing with utility by /u/GoldenSights.'
                self.r = praw.Reddit(self.USERAGENT)
                #self.r.login(username, password)
                print('Success')
                self.labelU.grid_forget()
                self.labelP.grid_forget()
                self.entryUsername.grid_forget()
                self.entryPassword.grid_forget()
                self.newbutton.grid_forget()
                self.quitbutton.grid_forget()
                self.usernamelabel = Label(self, text=username + ', Sending to /u/' + self.mailrecipient)
                self.usernamelabel.grid(row=0, column=0, columnspan=8)
                self.quitbutton.grid(row=900, column=0)


                self.labellist = []
                self.entrylist = []
                self.verifylist = []
                self.misclist = []
                
                self.optionDiscuss = "Discussion Flair + Crossposting"
                self.optionRegister = "Register a new Candidate"

                self.prevmode = self.optionDiscuss
                self.curmode = self.optionDiscuss
                self.optionvar = tkinter.StringVar(self)
                self.optionvar.trace("w",self.permaloop)
                self.optionvar.set(self.optionDiscuss)
                self.option = OptionMenu(self, self.optionvar, self.optionDiscuss, self.optionRegister, "three", "four")
                self.newbutton.unbind("<Return>")
                self.entryUsername.unbind("<Return>")
                self.entryPassword.unbind("<Return>")
                self.option.grid(row=1,column=0,columnspan=8,pady=8)
                self.updategui(True)
            except praw.errors.InvalidUserPass:
                pass
                print('Invalid username or password')
                self.entryPassword.delete(0,200)
                self.labelErrorPointer.grid(row=1, column=2)

    def permaloop(self, *args):
        self.curmode = self.optionvar.get()
        print('Was: ' + self.prevmode + ' | Now: ' + self.curmode)
        if self.curmode != self.prevmode:
            self.prevmode = self.curmode
            self.updategui(True)

    def updategui(self, *args):
        if args[0] == True:
            print('Cleaning GUI')
            for item in self.labellist:
                item.grid_forget()
            for item in self.entrylist:
                item.grid_forget()
            for item in self.verifylist:
                item.grid_forget()
            for item in self.misclist:
                item.grid_forget()
            self.labellist = []
            self.entrylist = []
            self.verifylist = []
            self.misclist = []


            if self.curmode == self.optionDiscuss:
                self.newrowindex = 4
                self.labelPermalink = Label(self, text="Thread Permalink:")
                self.entryPermalink = Entry(self)
                self.rowconfigure(2,weight=2)
                self.labelPermalink.grid(row=2,column=0)
                self.entryPermalink.grid(row=2,column=1)
                self.labelcrossposting = Label(self,text="Crosspost to:")
                self.labelcrossposting.grid(row=3,column=0,columnspan=2,sticky="w")

                for m in range(5):
                    self.redditlabel = Label(self,text="/r/")
                    self.redditlabel.grid(row=self.newrowindex,column=0, sticky="e")
                    self.labellist.append(self.redditlabel)

                    self.redditentry = Entry(self)
                    self.redditentry.grid(row=self.newrowindex,column=1)
                    self.entrylist.append(self.redditentry)

                    self.newrowindex +=1

                self.morerowbutton = Button(self,text="+row",command=lambda: self.morerows('/r/', 0, 1, 20))
                self.morerowbutton.grid(row=898,column=0,columnspan=2)

                self.verifybutton = Button(self,text="Verify",command= lambda: self.updategui(False))
                self.verifybutton.grid(row=899,column=0,columnspan=2)

                self.newrowindex += 2

                self.misclist.append(self.labelPermalink)
                self.misclist.append(self.labelcrossposting)
                self.misclist.append(self.entryPermalink)
                self.misclist.append(self.morerowbutton)
                self.misclist.append(self.verifybutton)

            if self.curmode == self.optionRegister:
                self.newrowindex = 6
                self.labelCanUsername = Label(self, text="Candidate's Username:  /u/")
                self.entryCanUsername = Entry(self)
                self.labelCanRealname = Label(self, text="Candidate's Realname:")
                self.entryCanRealname = Entry(self)
                self.labelCanFlair = Label(self, text="Candidate's Flair:")
                self.entryCanFlair = Entry(self)
                self.entryMo = Spinbox(self, width=9, values=('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'))
                self.entryDa = Spinbox(self, width=2, from_=1, to=31)
                self.entryYr = Spinbox(self, width=4, from_=2014, to=2500)
                self.labelHH = Label(self, text="Schedule time UTC:")
                self.entryHH = Spinbox(self, from_=0, to=23, width=2)
                self.entryMM = Spinbox(self, from_=0, to=59, width=2)
                self.entryYr.delete(0,'end')
                self.entryYr.insert(0,2014)

                self.morerowbutton = Button(self,text="+question",command=lambda: self.morerows('Q:', 0, 1, 25))
                self.morerowbutton.grid(row=898,column=0,columnspan=8)

                self.verifybutton = Button(self,text="Verify",command= lambda: self.updategui(False))
                self.verifybutton.grid(row=899,column=0,columnspan=8)

                self.misclist.append(self.labelCanUsername)
                self.misclist.append(self.labelCanRealname)
                self.misclist.append(self.entryCanUsername)
                self.misclist.append(self.entryCanRealname)
                self.misclist.append(self.labelHH)
                self.misclist.append(self.entryHH)
                self.misclist.append(self.entryMM)
                self.misclist.append(self.entryMo)
                self.misclist.append(self.entryDa)
                self.misclist.append(self.entryYr)

                self.labelCanUsername.grid(row=2, column=0, sticky="e")
                self.labelCanRealname.grid(row=3, column=0, sticky="e")
                self.entryCanUsername.grid(row=2, column=1, columnspan=3)
                self.entryCanRealname.grid(row=3, column=1, columnspan=3)
                self.entryMo.grid(row=4, column=1,sticky="e")
                self.entryDa.grid(row=4, column=2)
                self.entryYr.grid(row=4, column=3)
                self.labelHH.grid(row=4, column=0, sticky="se", pady=5)
                self.entryHH.grid(row=5, column=1, sticky="e")
                self.entryMM.grid(row=5, column=2, sticky="w")
        else:
            if self.curmode == self.optionDiscuss:

                verifies = []

                i = self.entryPermalink.get()
                if len(i) == 6:
                    pid = i
                else:
                    if 'www.reddit.com/r/' in i and '/comments/' in i:
                        pid = i.split('/comments/')[1].split('/')[0]
                    if 'http://redd.it/' in i:
                        pid = i.split('redd.it/')[1]

                for flag in self.verifylist:
                    flag.grid_forget()
                    self.verifylist.remove(flag)

                try:
                    print('Fetching Submission ' + pid)
                    self.r.get_info(thing_id="t3_" + pid).title + 'Check'
                    self.redditlabel = Label(self, image=self.indicatorGreen)
                    self.redditlabel.grid(row=2,column=2)
                    self.verifylist.append(self.redditlabel)
                    verifies.append(True)
                    print('\tSuccess')
                except:
                    print('Failed. Make sure to include the http://. Copy and paste straight from your browser for best result')
                    self.redditlabel = Label(self, image=self.indicatorRed)
                    self.redditlabel.grid(row=2,column=2)
                    self.verifylist.append(self.redditlabel)
                    verifies.append(False)

                for entry in self.entrylist:
                    i = entry.get()
                    if i != '':
                        print('Fetching /r/' + i)
                        if all(char in string.ascii_letters+string.digits+'_-' for char in i):
                            try:
                                sub = self.r.get_subreddit(i,fetch=True)
                                self.redditlabel = Label(self, image=self.indicatorGreen)
                                self.redditlabel.grid(row=entry.grid_info()['row'],column=2)
                                self.verifylist.append(self.redditlabel)
                                verifies.append(True)
                                print('\tSuccess')
                            except:
                                self.redditlabel = Label(self, image=self.indicatorRed)
                                self.redditlabel.grid(row=entry.grid_info()['row'],column=2)
                                self.verifylist.append(self.redditlabel)
                                verifies.append(False)
                                print('\tFailed')
                            time.sleep(2)
                        else:
                            self.redditlabel = Label(self, image=self.indicatorRed)
                            self.redditlabel.grid(row=entry.grid_info()['row'],column=2)
                            self.verifylist.append(self.redditlabel)
                            verifies.append(False)
                            print('\tFailed')

                print(verifies)


            if self.curmode == self.optionRegister:

                verifies = []
                u=self.entryCanUsername.get()
                print('Fetching /u/' + u)
                if not all(char in string.ascii_letters+string.digits+'_-' for char in u):
                    self.redditlabel = Label(self, image=self.indicatorRed)
                    self.redditlabel.grid(row=2, column=4)
                    self.verifylist.append(self.redditlabel)
                    verifies.append(False)
                    print('\tBad characterage')
                else:
                    try:
                        u = self.r.get_redditor(u)
                        print(u)
                        self.redditlabel = Label(self, image=self.indicatorGreen)
                        self.redditlabel.grid(row=2,column=4)
                        self.verifylist.append(self.redditlabel)
                        verifies.append(True)
                        print('\tSuccess')
                    except:
                        self.redditlabel = Label(self, image=self.indicatorRed)
                        self.redditlabel.grid(row=2,column=4)
                        self.verifylist.append(self.redditlabel)
                        verifies.append(False)
                        print('\tFailed')

                try:
                    print('Checking Time')
                    t = self.entryMo.get() + ' ' + self.entryDa.get() + ' ' + self.entryYr.get() + ' ' + self.entryHH.get() + ':' + self.entryMM.get()
                    plandate = datetime.datetime.strptime(t, "%B %d %Y %H:%M")
                    plandate = datetime.datetime.utcfromtimestamp(plandate.timestamp())
                    print('\t' + str(plandate.timestamp()))

                    self.redditlabel = Label(self, image=self.indicatorGreen)
                    self.redditlabel.grid(row=5,column=3)
                    self.verifylist.append(self.redditlabel)
                    verifies.append(True)
                except:
                    print('\tFailed')
                    self.redditlabel = Label(self, image=self.indicatorRed)
                    self.redditlabel.grid(row=5,column=3)
                    self.verifylist.append(self.redditlabel)
                    verifies.append(False)

                print(verifies)


    def morerows(self, label, columnm, columnn, limit, *args):
        self.redditlabel = Label(self,text=label)
        self.redditlabel.grid(row=self.newrowindex,column=columnm, sticky="e")
        self.labellist.append(self.redditlabel)

        self.redditentry = Entry(self)
        self.redditentry.grid(row=self.newrowindex,column=columnn, columnspan=8)
        self.entrylist.append(self.redditentry)

        self.newrowindex += 1
        if self.newrowindex >= limit:
            self.morerowbutton.grid_forget()
        print(self.newrowindex)
Beispiel #12
0
    def __init__(self, pipepanel, pipeline_name, *args, **kwargs) :
        PipelineFrame.__init__(self, pipepanel, pipeline_name, *args, **kwargs)
        self.info = None
        
        eframe = self.eframe = LabelFrame(self,text="Options") 
        #,fg=textLightColor,bg=baseColor)
        eframe.grid( row=5, column=1, sticky=W, columnspan=7, padx=10, pady=5 )
        
        label = Label(eframe,text="Pipeline")#,fg=textLightColor,bg=baseColor)
        label.grid(row=3,column=0,sticky=W,padx=10,pady=5)
        PipelineLabels=["CellRanger","Initial/QC","Clustering","Multi-Sample Clustering" ]
        Pipelines=["cellranger","scrnaseqinit","scrnaseqcluster", "scrnaseqmulticluster"]

        self.label2pipeline = { k:v for k,v in zip(PipelineLabels, Pipelines)}
        
        PipelineLabel = self.PipelineLabel = StringVar()
        self.Pipeline = StringVar()

        PipelineLabel.set(PipelineLabels[0])        
        om = OptionMenu(eframe, PipelineLabel, *PipelineLabels, command=self.option_controller)
        om.config()#bg = widgetBgColor,fg=widgetFgColor)
        om["menu"].config()#bg = widgetBgColor,fg=widgetFgColor)
        #om.pack(side=LEFT,padx=20,pady=5)
        om.grid(row=3,column=1,sticky=W,padx=10,pady=5)
        
        self.crOpts = crOpts = LabelFrame( eframe, 
                                              text="CellRanger Settings" )
        self.scrCRID = scrCRID = StringVar()
        scrCRID.set("SPECIFY_PREFIX_HERE")
        self.scrExpected = scrExpected = StringVar()
        scrExpected.set("3000")

        scrcridL = Label(crOpts, text="CellRanger Sample ID: ")
        scrcridE = Entry(crOpts, bd =2, width=25, textvariable=scrCRID)
        scrcridL.grid(row=9,column=1,sticky=W,padx=10,pady=5)
        scrcridE.grid(row=9,column=2,sticky=W,padx=0,pady=5)
        
        screxpectedL = Label(crOpts, text="Expected number of cells: ")
        screxpectedE = Entry(crOpts, bd =2, width=8, textvariable=scrExpected)
        screxpectedL.grid(row=10,column=1,sticky=W,padx=10,pady=5)
        screxpectedE.grid(row=10,column=2,sticky=W,padx=0,pady=5)

        self.clusterOpts = clusterOpts = LabelFrame( eframe, 
                                              text="Clustering and tSNE Options" )

        self.scrPCs = scrPCs = StringVar()
        scrPCs.set("12")
        self.scrRes = scrRes = StringVar()
        scrRes.set("0.6")
        
        #scrPCs.trace('w', lambda a,b,c,x="scrPCs": makejson(x))

        #Filter out genes < [5] read counts in < [2] samples
        scrpcsL = Label(clusterOpts, text="Include principal components 1 through ")
        scrpcsE = Entry(clusterOpts, bd =2, width=3, textvariable=scrPCs)
        scrresL = Label(clusterOpts, text="with clustering resolution: ")
        scrresE = Entry(clusterOpts, bd =2, width=3, textvariable=scrRes)
        
        scrpcsL.grid(row=9,column=1,sticky=W,padx=10,pady=5)
        scrpcsE.grid(row=9,column=2,sticky=W,padx=0,pady=5)
        scrresL.grid(row=9,column=3,sticky=W,padx=5,pady=5)
        scrresE.grid(row=9,column=4,sticky=W,padx=0,pady=5)
        #scrRes.trace('w', lambda a,b,c,x="scrPCs": makejson(x))
        
        clusterOpts.grid( row=8, column=0, columnspan=4, sticky=W, padx=20, pady=10 )
        

        self.multiclusterOpts = multiclusterOpts = LabelFrame( eframe,
                                                text = "Multi-Sample Clustering and tSNE Options")

        scrccsL = Label(multiclusterOpts, text="Include canonical components 1 through ")
        scrccsE = Entry(multiclusterOpts, bd =2, width=3, textvariable=scrPCs)
        scrmcresL = Label(multiclusterOpts, text="with clustering resolution: ")
        scrmcresE = Entry(multiclusterOpts, bd =2, width=3, textvariable=scrRes)

        scrccsL.grid(row=9,column=1,sticky=W,padx=10,pady=5)
        scrccsE.grid(row=9,column=2,sticky=W,padx=0,pady=5)
        scrmcresL.grid(row=9,column=3,sticky=W,padx=5,pady=5)
        scrmcresE.grid(row=9,column=4,sticky=W,padx=0,pady=5)


        self.qcOpts = qcOpts = LabelFrame( eframe, 
                                              text="Initial Settings" )
        countL = Label( qcOpts, text="Counts/Matrix Dir:" )
        countL.grid(row=9, column=1, sticky=W, padx=10, pady=5 )
        countpath=StringVar()  
        self.countpath = countpath
        count_entry = Entry(qcOpts, 
                           bd =2, 
                           width = 50, 
                           #bg = entryBgColor, 
                           #fg = entryFgColor, 
                           textvariable = countpath, state='normal'
                          )
        count_entry.grid( row=9, column=2, columnspan=3 )
        self.count_button = count_button = Button( qcOpts, 
                             text="Open Directory", 
                             command=self.set_count_directory )
        count_button.grid( row=9, column=5 )

        self.mattype = mattype = StringVar()
        mattypeL = Label(qcOpts, text="Count matrix format: ")
        scrMatTypeDropdown = ["cellranger", "cellranger_raw", "zumi", "biorad"]
        mattype.set(scrMatTypeDropdown[0])
        mattype_om = OptionMenu(qcOpts, mattype, *scrMatTypeDropdown)
        mattypeL.grid(row=10,column=1,sticky=W,padx=10,pady=5)
        mattype_om.grid(row=10,column=2,sticky=W,padx=0,pady=5)
        
        self.docycleregress = docycleregress = StringVar()
        docycleregressL = Label(qcOpts, text="Do cell cycle regression? ")
        scrCycleDropdown = ["TRUE", "FALSE"]
        docycleregress.set(scrCycleDropdown[0])
        cycle_om = OptionMenu(qcOpts, docycleregress, *scrCycleDropdown)
        docycleregressL.grid(row=11,column=1,sticky=W,padx=10,pady=5)
        cycle_om.grid(row=11,column=2,sticky=W,padx=0,pady=5)

        usecycleregressL_c = Label(clusterOpts, text="Use cell cycle regressed data? ")
        docycleregress.set(scrCycleDropdown[0])
        cycle_om_c = OptionMenu(clusterOpts, docycleregress, *scrCycleDropdown)
        usecycleregressL_c.grid(row=10,column=1,sticky=W,padx=10,pady=5)
        cycle_om_c.grid(row=10,column=2,sticky=W,padx=0,pady=5)

        usecycleregressL_mc = Label(multiclusterOpts, text="Use cell cycle regressed data? ")
        docycleregress.set(scrCycleDropdown[0])
        cycle_om_mc = OptionMenu(multiclusterOpts, docycleregress, *scrCycleDropdown)
        usecycleregressL_mc.grid(row=10,column=1,sticky=W,padx=10,pady=5)
        cycle_om_mc.grid(row=10,column=2,sticky=W,padx=0,pady=5)


        groups_buttonL = Label(qcOpts, text="SAMPLE INFORMATION: ")
        groups_button = Button(qcOpts, 
                                            text="Set Groups", 
                                            command = self.popup_groups )
        groups_buttonL.grid(row=12,column=1,sticky=W,padx=10,pady=5)
        groups_button.grid(row=12,column=2,sticky=W,padx=0,pady=5)
        #####################
        
        self.option_controller()
Beispiel #13
0
    def __init__(self, pipepanel, pipeline_name, *args, **kwargs):
        PipelineFrame.__init__(self, pipepanel, pipeline_name, *args, **kwargs)
        self.info = None

        eframe = self.eframe = LabelFrame(self, text="Options")
        #,fg=textLightColor,bg=baseColor)
        eframe.grid(row=5, column=1, sticky=W, columnspan=7, padx=10, pady=5)

        label = Label(eframe,
                      text="Pipeline")  #,fg=textLightColor,bg=baseColor)
        label.grid(row=3, column=0, sticky=W, padx=10, pady=5)
        PipelineLabels = [
            "Quality Control Analysis", "Differential Expression Analysis",
            "Fusion Detection", "Variant Calling"
        ]
        Pipelines = [
            "initialqcrnaseq", "rnaseq", "rnaseqfusion", "rnaseqvargerm"
        ]

        self.label2pipeline = {k: v for k, v in zip(PipelineLabels, Pipelines)}

        PipelineLabel = self.PipelineLabel = StringVar()
        self.Pipeline = StringVar()

        PipelineLabel.set(PipelineLabels[0])
        om = OptionMenu(eframe,
                        PipelineLabel,
                        *PipelineLabels,
                        command=self.option_controller)
        om.config()  #bg = widgetBgColor,fg=widgetFgColor)
        om["menu"].config()  #bg = widgetBgColor,fg=widgetFgColor)
        #om.pack(side=LEFT,padx=20,pady=5)
        om.grid(row=3, column=1, sticky=W, padx=10, pady=5)

        rReadlens = [
            'Read Length is 50', 'Read Length is 75', 'Read Length is 100',
            'Read Length is 125', 'Read Length is 150', 'Read Length is 250'
        ]
        self.rReadlen = rReadlen = StringVar()
        rReadlen.set(rReadlens[2])
        self.om2 = OptionMenu(eframe,
                              rReadlen,
                              *rReadlens,
                              command=self.option_controller)
        #self.om2.grid(row=4,column=1,sticky=W,padx=10,pady=5)

        rStrands = [
            '0, Reads are Unstranded', '1, Reads are from Sense Strand',
            '2, Reads are from Anti-Sense Strand'
        ]
        self.rStrand = rStrand = StringVar()
        rStrand.set(rStrands[0])
        self.om3 = OptionMenu(eframe,
                              rStrand,
                              *rStrands,
                              command=self.option_controller)
        #self.om3.grid(row=5,column=1,sticky=W,padx=10,pady=5)

        rDegs = [
            "no, Do not Report Differentially Expressed Genes",
            "yes, Report Differentially Expressed Genes"
        ]
        self.rDeg = rDeg = StringVar()
        rDeg.set(rDegs[0])
        self.om4 = OptionMenu(eframe,
                              rDeg,
                              *rDegs,
                              command=self.option_controller)
        self.om4.grid(row=6, column=1, sticky=W, padx=10, pady=5)

        #####################
        #Sample Threshold
        #####################
        self.sampleLF = sampleLF = LabelFrame(
            eframe, text="Low Abundance Gene Thresholds")

        self.rMincount = rMincount = StringVar()
        rMincount.set("0.5")
        self.rMinsamples = rMinsamples = StringVar()
        rMinsamples.set("2")

        #rMincount.trace('w', lambda a,b,c,x="rmincount": makejson(x))

        #Filter out genes < [5] read counts in < [2] samples
        rminsamplesL = Label(sampleLF, text="Include genes with >=")  # in")
        rmincountE = Entry(sampleLF, bd=2, width=3, textvariable=rMincount)
        rmincountL = Label(sampleLF, text="CPM in  >=")
        rminsamplesE = Entry(sampleLF, bd=2, width=3, textvariable=rMinsamples)
        rminsamplesR = Label(sampleLF, text="samples")

        rminsamplesL.grid(row=9, column=1, sticky=W, padx=10, pady=5)
        rmincountE.grid(row=9, column=2, sticky=W, padx=0, pady=5)
        rmincountL.grid(row=9, column=3, sticky=W, padx=5, pady=5)
        rminsamplesE.grid(row=9, column=4, sticky=W, padx=0, pady=5)
        rminsamplesR.grid(row=9, column=5, sticky=W, padx=10, pady=5)
        #rMinsamples.trace('w', lambda a,b,c,x="rmincount": makejson(x))

        sampleLF.grid(row=8,
                      column=0,
                      columnspan=4,
                      sticky=W,
                      padx=20,
                      pady=10)
        #####################

        self.add_info(eframe)
        self.option_controller()
def student_new_record():
    global screen4
    semester = StringVar()
    entryField = list()
    screen4 = Toplevel(screen)
    screen4.title("New Record")
    adjustWindow(screen4)  # configuring the window
    Label(screen4,
          text="Enter New Record",
          width='40',
          height="2",
          font=("Calibri", 22, 'bold'),
          fg='white',
          bg='#d9660a').grid(row=0, sticky='w', columnspan=4)
    #Label(screen4, text="", bg='#174873', width='60', height='18').place(x=0, y=127)
    #Label(screen4, text="", bg='white',width='100', height='1').place(x=0,y=80)
    Label(screen4, text="", bg='white', width='86',
          height='1').grid(row=1, columnspan=4)
    Label(screen4,
          text="Subject Name",
          font=("Open Sans", 12, 'bold'),
          fg='white',
          bg='#174873').grid(row=2, column=0, pady=(5, 10))
    Label(screen4,
          text="Your Marks",
          font=("Open Sans", 12, 'bold'),
          fg='white',
          bg='#174873').grid(row=2, column=1, pady=(5, 10))
    Label(screen4,
          text="Out of",
          font=("Open Sans", 12, 'bold'),
          fg='white',
          bg='#174873').grid(row=2, column=2, pady=(5, 10))
    Label(screen4,
          text="Credits Points",
          font=("Open Sans", 12, 'bold'),
          fg='white',
          bg='#174873').grid(row=2, column=3, pady=(5, 10))
    rowNo = 3
    for i in range(
            6
    ):  # this loop will generate all input field for taking input from the user
        temp = list()
        for j in range(4):
            e = Entry(screen4, width=14)
            e.grid(row=rowNo, column=j, padx=(3, 0), pady=(0, 25))
            temp.append(e)
        entryField.append(temp)
        rowNo += 2
    Label(screen4,
          text="Select Sem:",
          font=("Open Sans", 12, 'bold'),
          fg='white',
          bg='#174873').grid(row=rowNo, column=0, pady=(15, 0))
    list1 = ['1', '2', '3', '4', '5', '6', '7', '8']
    droplist = OptionMenu(screen4, semester, *list1)
    semester.set('--0--')
    droplist.config(width=5)
    droplist.grid(row=rowNo, column=1, pady=(15, 0))
    Button(screen4,
           text='Submit',
           width=20,
           font=("Open Sans", 13, 'bold'),
           bg='brown',
           fg='white',
           command=lambda: enter_new_record(entryField, semester)).grid(
               row=rowNo, columnspan=2, column=2, pady=(15, 0))
Beispiel #15
0
    def __init__(self, rows, columns, number_of_mines):
        self.rows = rows
        self.columns = columns
        self.buttons = []
        self.number_of_mines = number_of_mines
        self.flag_count = self.number_of_mines
        self.start_time = time.time()
        self.revealed = list(range(0, self.rows * self.columns))
        self.revealed[:] = ['nr'] * len(self.revealed)
        self.flag = list(range(0, self.rows * self.columns))
        self.flag[:] = ['nf'] * len(self.flag)

        self.mine_cells, self.mine_counts = self.load_mines(
            self.number_of_mines)

        self.window = Tk()
        self.window.title("Minesweeper")
        self.window.config(bg="#9ba2a3")
        self.upper_frame = Frame(self.window, bg="#9ba2a3")
        self.lower_frame = Frame(self.window)
        self.upper_frame.pack()
        self.lower_frame.pack()

        self.difficulty = StringVar(self.upper_frame)

        self.difficulty.set(
            self.GAME_DIFFICULTY_OPTIONS[self.GAME_DIFFICULTY_OPTIONS.index(
                self.previous_game_difficulty)])
        self.difficulty.trace("w", self.set_difficulty)
        opt = OptionMenu(self.upper_frame, self.difficulty,
                         *self.GAME_DIFFICULTY_OPTIONS)
        opt.grid(row=0, column=0, padx=50)
        self.flag_label = Label(self.upper_frame,
                                text="Flags: " + str(number_of_mines))
        self.flag_label.grid(row=0, column=1, padx=50)

        self.score_display = Label(self.upper_frame, text="Time")
        self.score_display.after(200, self.timer)
        self.score_display.grid(row=0, column=2, padx=50)

        for self.row in range(0, self.rows):
            for self.column in range(0, self.columns):

                if self.previous_game_difficulty == "Easy":
                    self.button = Button(self.lower_frame,
                                         height=self.BUTTON_HEIGHT,
                                         font='sans 10 bold',
                                         width=self.BUTTON_WIDTH,
                                         borderwidth=self.BUTTON_BORDER_WIDTH,
                                         relief=self.BUTTON_STYLE)
                elif self.previous_game_difficulty == "Medium":
                    self.button = Button(self.lower_frame,
                                         height=self.BUTTON_HEIGHT,
                                         font='sans 8 bold',
                                         width=self.BUTTON_WIDTH,
                                         borderwidth=self.BUTTON_BORDER_WIDTH,
                                         relief=self.BUTTON_STYLE)
                elif self.previous_game_difficulty == "Hard":
                    self.button = Button(self.lower_frame,
                                         height=self.BUTTON_HEIGHT,
                                         font='sans  5 bold',
                                         width=self.BUTTON_WIDTH,
                                         borderwidth=self.BUTTON_BORDER_WIDTH,
                                         relief=self.BUTTON_STYLE)

                self.position = [self.row, self.column]
                self.button.bind("<Button-2>",
                                 lambda event, position=self.position: self.
                                 right_click(event, position))
                self.button.bind("<Button-3>",
                                 lambda event, position=self.position: self.
                                 right_click(event, position))
                self.button.bind("<Button-1>",
                                 lambda event, position=self.position: self.
                                 left_click(event, position))
                self.button.grid(row=self.row,
                                 column=self.column,
                                 sticky="NSEW")

                self.button.grid_columnconfigure(0, weight=1)
                self.button.grid_rowconfigure(0, weight=1)
                self.button.grid_propagate(False)
                self.buttons.append(self.button)

        self.BUTTON_DEFAULT_COLOR = self.button.cget('bg')
        self.window.resizable(False, False)
        self.window.mainloop()
class MainForm(Tk):
    """class to build and add functionality to the main page of TAGUI"""
    def __init__(self, g_sys_instance, g_cal_instance, cons, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        tk.Tk.wm_title(self, 'Main Window')  #window title
        self.grid_rowconfigure(
            0, weight=1)  #Let the window fill out when resizing
        self.grid_columnconfigure(
            0, weight=1)  #Let the window fill out when resizing

        container = tk.Frame(self)  #main frame
        container.grid(row=0, column=0, sticky=tk.E + tk.W + tk.S +
                       tk.N)  # Let the main frame fill out the entire window
        container.grid_rowconfigure(
            1, weight=1
        )  # Notebook sits in row 1 and it should occupy any empty space left
        container.grid_columnconfigure(
            0, weight=1
        )  # Makes sure there is no empty space in the horizontal direction

        self.g_sys_instance = g_sys_instance
        self.g_cal_instance = g_cal_instance
        self.cons = cons

        self.minsize(height=700, width=1024)  # setting window size
        self.protocol("WM_DELETE_WINDOW", self.onClosing)
        self.connect_btn_text = StringVar()
        self.buildMenuBar(container)
        self.buildserialBar(container)
        self.buildCtrlTab(container)
        self.buildStatusBar(container)
        self.ctrlTab.select(self.tabSetup)
        self.dat_buf = []
        self.filename = ''

    def buildMenuBar(self, container):
        # Menu
        menuBar = tk.Menu(container)
        fileMenu = tk.Menu(menuBar, tearoff=0)
        fileMenu.add_command(label='New', command=self.onFileNew)
        fileMenu.add_command(label='Open...', command=self.onFileOpen)
        fileMenu.add_separator()
        fileMenu.add_command(label='Save', command=self.onFileNew)
        fileMenu.add_command(label='Save as', command=self.onFileOpen)
        fileMenu.add_separator()
        fileMenu.add_command(label='Exit', command=self.onFileExit)
        menuBar.add_cascade(label='File', menu=fileMenu)
        tk.Tk.config(self, menu=menuBar)

    # Serial bar is at the top of the window and lets the user choose between experiment/simulation mode, the serial port, the baud rate and connect/disconnect to the ThermoAnalyzer
    def buildserialBar(self, container):

        serial_port = StringVar()
        baud_rate = StringVar()
        self.serialBar = tk.Frame(container, relief=tk.SUNKEN)
        self.serialBar.grid(
            row=0, column=0,
            sticky='w')  # Serial bar is positioned at the top row of the frame
        choose_mode_list = ["TA Experiment", "TA Simulation"]
        self.choose_mode_label = Label(self.serialBar, text="Mode")
        self.choose_mode_label.grid(row=0, column=0)
        self.choose_mode_variable = StringVar()
        self.choose_mode_widget = OptionMenu(self.serialBar,
                                             self.choose_mode_variable,
                                             *choose_mode_list,
                                             command=self.set_mode)
        self.choose_mode_widget.config(width=11)  #, direction='left')
        self.choose_mode_widget.grid(row=0, column=1, sticky='w')
        self.choose_mode_variable.set("TA Experiment")
        self.g_sys_instance.bsimulation = False
        self.serial_port_label = Label(self.serialBar, text="Port")
        self.serial_port_label.grid(row=0, column=2)

        tty_list = [
            "/dev/ttyUSB0", "/dev/ttyUSB1", "/dev/tty.usbserial-FTY3UOSS"
        ]
        self.tty_variable = StringVar()
        self.tty_variable.set(g_tech_instance.tty)
        self.serial_port_widget = OptionMenu(self.serialBar,
                                             self.tty_variable,
                                             *tty_list,
                                             command=self.update_json_file)
        self.serial_port_widget.config(width=21)  #, justify='left')
        self.serial_port_widget.grid(row=0, column=3)
        self.baud_rate_label = Label(self.serialBar, text="Baud")
        self.baud_rate_label.grid(row=0, column=4)
        baud_rate_list = ["9600", "19200", "115200"]
        self.baud_rate_variable = StringVar()
        self.baud_rate_variable.set(g_tech_instance.baud_rate)
        self.baud_rate_list = OptionMenu(self.serialBar,
                                         self.baud_rate_variable,
                                         *baud_rate_list,
                                         command=self.update_json_file)
        self.baud_rate_list.config(width=6)
        self.baud_rate_list.grid(row=0, column=5)
        self.button = Button(self.serialBar,
                             textvariable=self.connect_btn_text,
                             command=self.connect)
        self.connect_btn_text.set("Connect")
        self.button.grid(row=0, column=6)

    #Status bar is at the bottom of the window and text status message on the left and the experiment time on the right

    def buildStatusBar(self, container):

        self.status_label_text = StringVar()
        self.status_time_text = StringVar()
        statusBar = tk.Frame(container, relief=tk.SUNKEN, bd=2)
        statusBar.grid(
            row=2, column=0, sticky=tk.E + tk.W
        )  #Status bar is positioned at the bottom and extends fully horizontally
        self.status_label = Label(statusBar,
                                  textvariable=self.status_label_text)
        self.status_label_text.set('Idle')
        self.status_label.pack(side=tk.LEFT)
        self.status_time = Label(statusBar, textvariable=self.status_time_text)
        self.status_time_text.set('Run time: NA')
        self.status_time.pack(side=tk.RIGHT)

    # CtrlTab hosts the different tabs such as SetUp, Monitor, Terminal, and Config

    def buildCtrlTab(self, container):

        s = ttk.Style()
        s.configure('TNotebook', tabposition='nw')

        self.ctrlTab = ttk.Notebook(container)
        self.ctrlTab.grid(row=1, column=0)  #tk.E+tk.W+tk.S+tk.N)
        self.ctrlTab.bind("<<NotebookTabChanged>>", self.display_tab_selected)
        self.tabSetup = ctrl_setup.CtrlSetup(self.ctrlTab, self.cons,
                                             self.g_sys_instance,
                                             self.g_cal_instance)
        self.ctrlTab.add(self.tabSetup, text='Setup')
        self.tabMon = ctrl_mon.CtrlMon(self.ctrlTab, self.g_sys_instance,
                                       self.cons, self)
        self.ctrlTab.add(self.tabMon, text='Monitor')
        self.tabTerm = ctrl_term.CtrlTerm(self.ctrlTab, self.g_sys_instance,
                                          self.cons)
        self.ctrlTab.add(self.tabTerm, text='Terminal')
        self.calibTab = calib.Calib(self.ctrlTab, self.g_sys_instance,
                                    self.g_cal_instance, self.cons)
        self.ctrlTab.add(self.calibTab, text='Calibration')

    #Function to update the tables in the tab selected by the user
    def display_tab_selected(self, event):
        selected_tab = event.widget.select()
        tab_text = event.widget.tab(selected_tab, "text")

        if tab_text == "Calibration":
            self.calibTab.update_calibration_table()

        elif tab_text == "Setup":
            self.tabSetup.update_setup_table()

    def set_mode(self, event):

        if self.choose_mode_variable.get() == "TA Experiment":
            self.g_sys_instance.bsimulation = False

        elif self.choose_mode_variable.get() == "TA Simulation":
            self.g_sys_instance.bsimulation = True

    #Function to get the updated serial port and baud rate and call the function to update the json file with the latest parameters
    def update_json_file(self, event):
        g_tech_instance.baud_rate = self.baud_rate_variable.get()
        g_tech_instance.tty = self.tty_variable.get()
        g_tech_instance.update()

    def connect(self):

        time_out = 3

        if str(self.connect_btn_text.get()) == "Connect":
            self.cons.Connect(
                self, self.tabMon, self.tty_variable.get(),
                self.baud_rate_variable.get(), str(time_out)
            )  #Send all variables regardless of operation mode
        elif str(self.connect_btn_text.get()) == "Disconnect":
            self.cons.Disconnect(self, self.tabMon)
            self.connect_btn_text.set("Connect")
        time.sleep(4)

    def onFileNew(self):

        self.filename = filedialog.asksaveasfilename(
            initialdir="./",
            title="Select file",
            filetypes=(("xml files", "*.xml"), ("csv files", "*.csv"),
                       ("all files", "*.*")))
        if self.filename != '':
            self.cons.f = open(self.filename, "wb")
            self.cons.f_TAdata = open(self.filename[:-4] + "_TAdata.xml", "wb")
            self.cons.f_Caldata = open(self.filename[:-4] + "_Caldata.xml",
                                       "wb")
            self.cons.f_Commands_to_PC = open(
                self.filename[:-4] + "_Commands_to_PC.xml", "wb")

            root_main = ET.Element("TADataLog")
            tree_main = ET.ElementTree(root_main)
            root_TAdata = ET.Element("TAData")
            tree_TAdata = ET.ElementTree(root_TAdata)
            m2 = ET.Element("CalData")
            m3 = ET.Element("Commands")
            tree_main.write(self.cons.f)
            tree_TAdata.write(self.cons.f_TAdata)

    def onFileOpen(self):

        ftypes = [('xml files', '*.xml'), ("csv files", "*.csv"),
                  ('All files', '*')]
        dlg = filedialog.Open(self, filetypes=ftypes)
        self.filename = dlg.show()
        if self.filename != '':
            self.cons.f = open(self.filename, "a")

    def onFileExit(self):
        # Need to do cleanup here, save files, etc. before quitting.
        # quit()
        self.destroy()

    def onClosing(self):
        self.onFileExit()
Beispiel #17
0
class MainView(Tk):
    class Constants:
        title = "Cambio de Moneda"
        heigth = 100
        width = 550
        input_width = 250
        separator_width = 50
        center = N + S + E + W
        left = W
        right = E
        event = "<Button-1>"
        convert_text = "Convertir"
        separator_text = "▶"
        convertion_base = "USD"
        convertion_final = "To"
        convertion_initial = "From"
        bleeding = 10

    def __init__(self, convert_handler=None):
        super().__init__()
        self.__convert_handler = convert_handler
        self.title(self.Constants.title)
        self.maxsize(width=self.Constants.width, height=self.Constants.heigth)
        self.minsize(width=self.Constants.width, height=self.Constants.heigth)
        self.__configure_grid()
        self.__configure_UI()

    def __configure_grid(self):
        self.grid_rowconfigure(0, weight=True)
        self.grid_rowconfigure(1, weight=True)
        self.grid_rowconfigure(2, weight=True)
        self.grid_columnconfigure(0, minsize=self.Constants.input_width)
        self.grid_columnconfigure(2, minsize=self.Constants.input_width)
        self.grid_columnconfigure(1, minsize=self.Constants.separator_width)

    def __configure_UI(self):

        self.option_final = StringVar(self)
        self.option_final.set(self.Constants.convertion_final)
        self.list_of_convertions = self.convert_data_to_list()
        self.menu = OptionMenu(self, self.option_final,
                               *self.list_of_convertions)
        self.menu.grid(row=2, column=2, sticky=self.Constants.right)
        self.menu.configure(bg="light sea green",
                            fg="black",
                            width=30,
                            font=("Arial black", 8))

        self.option_initial = StringVar(self)
        self.option_initial.set(self.Constants.convertion_initial)
        self.list_of_inital_conversion = self.convert_initial_data_list()
        self.initial_menu = OptionMenu(self, self.option_initial,
                                       *self.list_of_inital_conversion)
        self.initial_menu.grid(row=2, column=0, sticky=self.Constants.left)
        self.initial_menu.configure(bg="light sea green",
                                    fg="black",
                                    width=30,
                                    font=("Arial black", 8))

        currency_name_label = Label(self)
        currency_name_label.configure(textvariable=self.option_initial)
        currency_name_label.grid(row=0, column=0, sticky=self.Constants.left)

        result_name_label = Label(self)
        result_name_label.configure(textvariable=self.option_final)
        result_name_label.grid(row=0, column=2, sticky=self.Constants.left)

        separator_label = Label(self)
        separator_label.configure(text=self.Constants.separator_text)
        separator_label.grid(row=1, column=1, sticky=self.Constants.center)

        self.__result_label = Label(self)
        self.__result_label.configure(text="0")
        self.__result_label.grid(row=1, column=2, sticky=self.Constants.left)

        self.__convert_button = Button(self)
        self.__convert_button.configure(text=self.Constants.convert_text)
        self.__convert_button.configure(bg="lawn green",
                                        fg="black",
                                        font=("Arial black",
                                              self.Constants.bleeding))
        self.__convert_button.grid(row=2,
                                   column=1,
                                   sticky=self.Constants.center,
                                   padx=self.Constants.bleeding,
                                   pady=self.Constants.bleeding)
        self.__convert_button.bind(self.Constants.event,
                                   self.__did_tap_convert)

        vcmd = (self.register(self.__checkNumberOnly), '%d', '%P')
        self.__currency_input = Entry(self,
                                      validate="key",
                                      validatecommand=vcmd)
        self.__currency_input.grid(row=1,
                                   column=0,
                                   sticky=self.Constants.center)

    def __did_tap_convert(self, event):
        if self.__convert_handler is None:
            return
        try:
            ammount_to_convert = float(self.__currency_input.get())
        except ValueError:
            return
        else:
            self.__convert_handler(self.finding_initial_equivalence(),
                                   self.finding_equivalence_of_name(),
                                   ammount_to_convert)

    def update_result(self, text):
        self.__result_label.configure(text=text)

    def __checkNumberOnly(self, action, value_if_allowed):
        if action != '1':
            return True
        try:
            float(value_if_allowed)
        except ValueError:
            return False
        else:
            return True

    def convert_data_to_list(self):
        self.messy_list = CurrencyManager.get_crude_dates(self)
        return self.messy_list

    def finding_equivalence_of_name(self):
        self.sign_convertion = self.option_final.get()
        self.equivalence = CurrencyManager.finding_equivalence(
            self, self.sign_convertion)
        return self.equivalence

    def convert_initial_data_list(self):
        self.initial_options_list = CurrencyManager.get_initial_currency(self)
        return self.initial_options_list

    def finding_initial_equivalence(self):
        self.initial_sign_convertion = self.option_initial.get()
        self.initial_equivalence = CurrencyManager.finding_initial_equivalence(
            self, self.initial_sign_convertion)
        return self.initial_equivalence
Beispiel #18
0
class ParameterSetup:
    def __init__(self, master, par=False):
        """
        GUI for selecting default parameters - will write parameters to file \
        of users choosing.

        :type master: Tk
        :param master: Tkinter window
        :type par: EQcorrscanParameters
        :param par: Default parameters to start-up with.
        """
        from tkinter import Label, Button, Entry, DoubleVar, StringVar, IntVar
        from tkinter import BooleanVar, OptionMenu, Checkbutton
        import tkMessageBox
        from eqcorrscan.utils import parameters
        from obspy import UTCDateTime
        import warnings

        # Set the default par, only if they don't already exist.
        if not par:
            par = parameters.EQcorrscanParameters([''], 2, 10, 4, 100, 2,
                                                  '1900-01-01', '2300-01-01',
                                                  '', 'seishub', 4, False, '',
                                                  'jpg', False, 8, 'MAD', 6)
        # Callback functions for all variables (ugly)

        def update_template_names(*args):
            par.template_names = [name.strip() for name in
                                  template_names.get().split(',')]
            template_names.set(', '.join(par.template_names))

        def update_lowcut(*args):
            par.lowcut = lowcut.get()
            lowcut.set(par.lowcut)

        def update_highcut(*args):
            par.highcut = highcut.get()
            if par.highcut >= 0.5 * par.samp_rate:
                msg = ('Highcut must be less than the Nyquist, setting to ' +
                       str((par.samp_rate / 2.0) - 1))
                tkMessageBox.showwarning(title="Nyquist error",
                                         message=msg)
                par.highcut = (par.samp_rate / 2.0) - 1
            highcut.set(par.highcut)

        def update_filt_order(*args):
            par.filt_order = filt_order.get()
            filt_order.set(par.filt_order)

        def update_samp_rate(*args):
            par.samp_rate = samp_rate.get()
            if par.highcut >= 0.5 * par.samp_rate:
                msg = ('Highcut must be less than the Nyquist, setting to ' +
                       str((par.samp_rate / 2.0) - 1))
                tkMessageBox.showwarning(title="Nyquist error",
                                         message=msg)
                par.highcut = (par.samp_rate / 2.0) - 1
                highcut.set(par.highcut)
            samp_rate.set(par.samp_rate)

        def update_debug(*args):
            par.debug = debug.get()
            debug.set(par.debug)

        def update_startdate(*args):
            par.startdate = UTCDateTime(startdate.get())
            startdate.set(str(par.startdate))

        def update_enddate(*args):
            par.enddate = UTCDateTime(enddate.get())
            enddate.set(str(par.enddate))

        def update_archive(*args):
            par.archive = archive.get()
            archive.set(par.archive)

        def update_arc_type(*args):
            par.arc_type = arc_type.get()
            arc_type.set(par.arc_type)

        def update_cores(*args):
            par.cores = cores.get()
            cores.set(par.cores)

        def update_plotvar(*args):
            par.plotvar = plotvar.get()
            plotvar.set(par.plotvar)

        def update_plot_format(*args):
            par.plot_format = plot_format.get()
            plot_format.set(par.plot_format)

        def update_tempdir(*args):
            par.tempdir = tempdir.get()
            tempdir.set(par.tempdir)

        def update_threshold(*args):
            par.threshold = threshold.get()
            threshold.set(par.threshold)

        def update_threshold_type(*args):
            par.threshold_type = threshold_type.get()
            threshold_type.set(par.threshold_type)

        def update_plotdir(*args):
            par.plotdir = plotdir.get()
            plotdir.set(par.plotdir)

        def update_trigger_interval(*args):
            par.trigger_interval = trigger_interval.get()
            trigger_interval.set(par.trigger_interval)
        # Set some grid parameters
        nrows = 25
        ncolumns = 3
        self.master = master
        master.title("EQcorrscan parameter setup")
        self.label = Label(master, text="Alpha GUI for default setup")
        self.label.grid(column=0, columnspan=ncolumns, row=0)

        # Set up parameter input
        self.t_names_label = Label(master, text="Template names", anchor='e')
        self.t_names_label.grid(column=0, row=1, sticky='e')
        template_names = StringVar()
        template_names.set(', '.join(par.template_names))
        self.t_names_box = Entry(master, bd=2, textvariable=template_names)
        self.t_names_box.grid(column=1, row=1)
        template_names.trace("w", update_template_names)
        self.t_names_lookup = Button(master, text="Lookup",
                                     command=lambda: self.get_template_names(par))
        self.t_names_lookup.grid(column=2, row=1)

        self.lowcut_label = Label(master, text="Lowcut (Hz)", anchor='e')
        self.lowcut_label.grid(column=0, row=2, sticky='e')
        lowcut = DoubleVar()
        lowcut.set(par.lowcut)
        self.lowcut_box = Entry(master, bd=2, textvariable=lowcut)
        self.lowcut_box.grid(column=1, row=2)
        lowcut.trace("w", update_lowcut)

        self.highcut_label = Label(master, text="Highcut (Hz)", anchor='e')
        self.highcut_label.grid(column=0, row=3, sticky='e')
        highcut = DoubleVar()
        highcut.set(par.highcut)
        self.highcut_box = Entry(master, bd=2, textvariable=highcut)
        self.highcut_box.grid(column=1, row=3)
        highcut.trace("w", update_highcut)

        self.filt_order_label = Label(master, text="Filter order")
        self.filt_order_label.grid(column=0, row=4, sticky='e')
        filt_order = DoubleVar()
        filt_order.set(par.filt_order)
        self.filt_order_box = Entry(master, bd=2, textvariable=filt_order)
        self.filt_order_box.grid(column=1, row=4)
        filt_order.trace("w", update_filt_order)

        self.samp_rate_label = Label(master, text="Sample rate (Hz)")
        self.samp_rate_label.grid(column=0, row=5, sticky='e')
        samp_rate = DoubleVar()
        samp_rate.set(par.samp_rate)
        self.samp_rate_box = Entry(master, bd=2, textvariable=samp_rate)
        self.samp_rate_box.grid(column=1, row=5)
        samp_rate.trace("w", update_samp_rate)

        self.debug_label = Label(master, text="Debug")
        self.debug_label.grid(column=0, row=6, sticky='e')
        debug = IntVar()
        debug.set(par.debug)
        self.debug_box = Entry(master, bd=2, textvariable=debug)
        self.debug_box.grid(column=1, row=6)
        debug.trace("w", update_debug)

        self.startdate_label = Label(master, text="Start date (yyyy-mm-dd)")
        self.startdate_label.grid(column=0, row=6, sticky='e')
        startdate = StringVar()
        startdate.set(par.startdate)
        self.startdate_box = Entry(master, bd=2, textvariable=startdate)
        self.startdate_box.grid(column=1, row=6)
        startdate.trace("w", update_startdate)

        self.enddate_label = Label(master, text="End date (yyyy-mm-dd)")
        self.enddate_label.grid(column=0, row=8, sticky='e')
        enddate = StringVar()
        enddate.set(par.enddate)
        self.enddate_box = Entry(master, bd=2, textvariable=enddate)
        self.enddate_box.grid(column=1, row=8)
        enddate.trace("w", update_enddate)

        self.archive_label = Label(master, text="Archive")
        self.archive_label.grid(column=0, row=9, sticky='e')
        archive = StringVar()
        archive.set(par.archive)
        self.archive_box = Entry(master, bd=2, textvariable=archive)
        self.archive_box.grid(column=1, row=9)
        archive.trace("w", update_archive)
        self.archive_lookup = Button(master, text="Lookup",
                                     command=lambda: self.get_archive(par))
        self.archive_lookup.grid(column=2, row=9)


        self.arc_type_label = Label(master, text="Archive type")
        self.arc_type_label.grid(column=0, row=10, sticky='e')
        arc_type = StringVar()
        arc_type.set(par.arc_type)
        self.arc_type_box = OptionMenu(master, arc_type,
                                       "seishub", "fdsn", "day_vols")
        self.arc_type_box.grid(column=1, row=10, sticky='w,e')
        arc_type.trace("w", update_arc_type)

        self.cores_label = Label(master, text="Number of cores")
        self.cores_label.grid(column=0, row=11, sticky='e')
        cores = IntVar()
        cores.set(par.cores)
        self.cores_box = Entry(master, bd=2, textvariable=cores)
        self.cores_box.grid(column=1, row=11)
        cores.trace("w", update_cores)

        self.plotvar_label = Label(master, text="Plotting on/off")
        self.plotvar_label.grid(column=0, row=12, sticky='e')
        plotvar = BooleanVar()
        plotvar.set(par.plotvar)
        self.plotvar_box = Checkbutton(master, text='Plot on', var=plotvar,
                                       onvalue=True, offvalue=False)
        self.plotvar_box.grid(column=1, row=12)
        plotvar.trace("w", update_plotvar)

        self.plotdir_label = Label(master, text="Plot directory")
        self.plotdir_label.grid(column=0, row=13, sticky='e')
        plotdir = StringVar()
        plotdir.set(par.plotdir)
        self.plotdir_box = Entry(master, bd=2, textvariable=plotdir)
        self.plotdir_box.grid(column=1, row=13)
        plotdir.trace("w", update_plotdir)
        self.plotdir_lookup = Button(master, text="Lookup",
                                     command=lambda: self.get_plotdir(par))
        self.plotdir_lookup.grid(column=2, row=13)

        self.plot_format_label = Label(master, text="Plot format")
        self.plot_format_label.grid(column=0, row=14, sticky='e')
        plot_format = StringVar()
        plot_format.set(par.plot_format)
        self.plot_format_box = OptionMenu(master, plot_format,
                                          "jpg", "eps", "pdf", "png")
        self.plot_format_box.grid(column=1, row=14, sticky='w,e')
        plot_format.trace("w", update_plot_format)

        self.tempdir_label = Label(master, text="Temporary directory")
        self.tempdir_label.grid(column=0, row=15, sticky='e')
        tempdir = StringVar()
        tempdir.set(par.tempdir)
        self.tempdir_box = Entry(master, bd=2, textvariable=tempdir)
        self.tempdir_box.grid(column=1, row=15)
        tempdir.trace("w", update_tempdir)
        self.tempdir_lookup = Button(master, text="Lookup",
                                     command=lambda: self.get_tempdir(par))
        self.tempdir_lookup.grid(column=2, row=15)

        self.threshold_label = Label(master, text="Threshold")
        self.threshold_label.grid(column=0, row=16, sticky='e')
        threshold = DoubleVar()
        threshold.set(par.threshold)
        self.threshold_box = Entry(master, bd=2, textvariable=threshold)
        self.threshold_box.grid(column=1, row=16)
        threshold.trace("w", update_threshold)

        self.threshold_type_label = Label(master, text="Threshold type")
        self.threshold_type_label.grid(column=0, row=17, sticky='e')
        threshold_type = StringVar()
        threshold_type.set(par.threshold_type)
        self.threshold_type_box = OptionMenu(master, threshold_type,
                                             "MAD", "absolute", "av_chan_corr")
        self.threshold_type_box.grid(column=1, row=17, sticky='w,e')
        threshold_type.trace("w", update_threshold_type)

        self.trigger_interval_label = Label(master,
                                            text="Minimum trigger " +
                                            "interval (s)")
        self.trigger_interval_label.grid(column=0, row=18, sticky='e')
        trigger_interval = DoubleVar()
        trigger_interval.set(par.trigger_interval)
        self.trigger_interval_box = Entry(master, bd=2,
                                          textvariable=trigger_interval)
        self.trigger_interval_box.grid(column=1, row=18)
        trigger_interval.trace("w", update_trigger_interval)

        # End of user editable section, now we have read/write buttons
        self.read_button = Button(master, text="Read parameters",
                                  command=lambda: self.read_par(master))
        self.read_button.grid(column=0, row=nrows-2, sticky='w,e')

        self.write_button = Button(master, text="Write parameters",
                                   command=lambda: self.write_par(par))
        self.write_button.grid(column=1, row=nrows-2, sticky='w,e')


    def read_par(self, master):
        """
        Function to open a file-browser and to select a parameter file.
        """
        from eqcorrscan.utils import parameters
        from tkFileDialog import askopenfilename
        parameter_filename = askopenfilename()
        try:
            par = parameters.read_parameters(parameter_filename)
            # Start a new instance
            master.destroy()
            run(par=par)
        except IOError:
            print 'No such file'
            return
        except TypeError:
            print 'Invalid parameter file'
            return

    def write_par(self, par):
        import tkMessageBox
        from eqcorrscan.utils import parameters
        from tkFileDialog import asksaveasfilename
        parameter_filename = asksaveasfilename()
        print(parameter_filename)
        # Set overwrite to true because asksavefilename already checks this.
        if len(par.template_names) == 1 and len(par.template_names[0]) == 0:
            msg = ("Warning: You have not selected any templates, " +
                   "you must add them before running matched-filter.")
            tkMessageBox.showwarning(title="No templates",
                                     message=msg)
        par.write(parameter_filename, overwrite=True)

    def get_template_names(self, par):
        from tkFileDialog import askopenfilenames
        par.template_names = askopenfilenames()
        self.master.destroy()
        run(par=par)

    def get_archive(self, par):
        from tkFileDialog import askdirectory
        par.archive = askdirectory()
        par.arc_type = 'day_vols'
        self.master.destroy()
        run(par=par)

    def get_plotdir(self, par):
        from tkFileDialog import askdirectory
        par.plotdir = askdirectory()
        self.master.destroy()
        run(par=par)

    def get_tempdir(self, par):
        from tkFileDialog import askdirectory
        par.tempdir = askdirectory()
        self.master.destroy()
        run(par=par)
Beispiel #19
0
    def __top_frame(self):
        """
        Create top frame content
        """
        self._selected_modulation = StringVar(self._tk_obj)
        self._selected_channel = StringVar(self._tk_obj)
        self._selected_sync_mode = StringVar(self._tk_obj)
        self._cbx_manchester_value = IntVar(self._tk_obj)

        frame = Frame(self._tk_obj, borderwidth=1, relief=SUNKEN, bg='#fff')
        frame.grid(column=0, row=0, padx=15, pady=15, sticky=W + E)
        frame.grid_rowconfigure(0, weight=1)
        frame.grid_columnconfigure(0, weight=1)

        # headline
        lab_section = Label(frame, text="Default RF Settings")
        lab_section.grid(columnspan=6, row=0, padx=5, pady=5, sticky=W + E)
        lab_section.configure(font=self.__FONT_HEADLINE)

        # frequency
        lab_frequency = Label(frame, text='Frequency')
        lab_frequency.grid(column=0, row=1, padx=5, pady=5, sticky=E)
        lab_frequency.configure(font=self.__FONT_STYLE)

        self._ety_frequency = Entry(frame)
        self._ety_frequency.grid(column=1, row=1, padx=5, pady=5, sticky=W)
        self._ety_frequency.configure(font=self.__FONT_STYLE)
        value_frequency = self.rf_object.getFreq()
        self._ety_frequency.insert(0, int(value_frequency[0]))

        # modulation
        lab_modulation = Label(frame, text='Modulation')
        lab_modulation.grid(column=0, row=2, padx=5, pady=5, sticky=E)
        lab_modulation.configure(font=self.__FONT_STYLE)

        opm_modulation = OptionMenu(frame, self._selected_modulation,
                                    *self.__MODULATION_OPTIONS)
        opm_modulation.grid(column=1, row=2, padx=5, pady=5, sticky=W)
        opm_modulation.configure(font=self.__FONT_STYLE)
        value_modulation = self.rf_object.getMdmModulation()
        if value_modulation == 0:
            self._selected_modulation.set(self.__MODULATION_OPTIONS[1])
        elif value_modulation == 16:
            self._selected_modulation.set(self.__MODULATION_OPTIONS[2])
        elif value_modulation == 48:
            self._selected_modulation.set(self.__MODULATION_OPTIONS[3])
        elif value_modulation == 112:
            self._selected_modulation.set(self.__MODULATION_OPTIONS[4])
        else:
            self._selected_modulation.set(self.__MODULATION_OPTIONS[0])

        # channel
        lab_channel = Label(frame, text='Channel')
        lab_channel.grid(column=0, row=3, padx=5, pady=5, sticky=E)
        lab_channel.configure(font=self.__FONT_STYLE)

        sbx_channel = Spinbox(frame, state='readonly')
        sbx_channel.grid(column=1, row=3, padx=5, pady=5, sticky=W)
        sbx_channel.configure(font=self.__FONT_STYLE)
        self._selected_channel.set(self.rf_object.getChannel())
        sbx_channel.configure(from_=0,
                              to=10,
                              increment=1,
                              textvariable=self._selected_channel)

        # baud rate
        lab_baud = Label(frame, text='Baud Rate')
        lab_baud.grid(column=2, row=1, padx=5, pady=5, sticky=E)
        lab_baud.configure(font=self.__FONT_STYLE)

        self._ety_baud = Entry(frame)
        self._ety_baud.grid(column=3, row=1, padx=5, pady=5, sticky=W)
        self._ety_baud.configure(font=self.__FONT_STYLE)
        self._ety_baud.insert(0, int(self.rf_object.getMdmDRate()))

        # deviation
        lab_deviation = Label(frame, text='Deviation')
        lab_deviation.grid(column=2, row=2, padx=5, pady=5, sticky=E)
        lab_deviation.configure(font=self.__FONT_STYLE)

        self._ety_deviation = Entry(frame)
        self._ety_deviation.grid(column=3, row=2, padx=5, pady=5, sticky=W)
        self._ety_deviation.configure(font=self.__FONT_STYLE)
        self._ety_deviation.insert(0, int(self.rf_object.getMdmDeviatn()))
        self._ety_deviation.configure(state='readonly')

        # channel bandwidth
        lab_channel_bandwidth = Label(frame, text='Channel BW')
        lab_channel_bandwidth.grid(column=2, row=3, padx=5, pady=5, sticky=E)
        lab_channel_bandwidth.configure(font=self.__FONT_STYLE)

        self._ety_channel_bandwidth = Entry(frame)
        self._ety_channel_bandwidth.grid(column=3,
                                         row=3,
                                         padx=5,
                                         pady=5,
                                         sticky=W)
        self._ety_channel_bandwidth.configure(font=self.__FONT_STYLE)
        self._ety_channel_bandwidth.insert(0,
                                           int(self.rf_object.getMdmChanBW()))
        self._ety_channel_bandwidth.configure(state='readonly')

        # sync mode
        lab_sync_mode = Label(frame, text='Sync Mode')
        lab_sync_mode.grid(column=4, row=1, padx=5, pady=5, sticky=E)
        lab_sync_mode.configure(font=self.__FONT_STYLE)

        sbx_sync_mode = Spinbox(frame, state='readonly')
        sbx_sync_mode.grid(column=5, row=1, padx=5, pady=5, sticky=W)
        sbx_sync_mode.configure(font=self.__FONT_STYLE)
        self._selected_sync_mode.set(self.rf_object.getMdmSyncMode())
        sbx_sync_mode.configure(from_=0,
                                to=7,
                                increment=1,
                                textvariable=self._selected_sync_mode)

        # sync word
        lab_sync_word = Label(frame, text='Sync Word')
        lab_sync_word.grid(column=4, row=2, padx=5, pady=5, sticky=E)
        lab_sync_word.configure(font=self.__FONT_STYLE)

        self._ety_sync_word = Entry(frame)
        self._ety_sync_word.grid(column=5, row=2, padx=5, pady=5, sticky=W)
        self._ety_sync_word.configure(font=self.__FONT_STYLE)
        self._ety_sync_word.insert(0, self.rf_object.getMdmSyncWord())
        self._ety_sync_word.configure(state='readonly')

        # channel spacing
        lab_channel_spacing = Label(frame, text='Channel Spacing')
        lab_channel_spacing.grid(column=4, row=3, padx=5, pady=5, sticky=E)
        lab_channel_spacing.configure(font=self.__FONT_STYLE)

        self._ety_channel_spacing = Entry(frame)
        self._ety_channel_spacing.grid(column=5,
                                       row=3,
                                       padx=5,
                                       pady=5,
                                       sticky=W)
        self._ety_channel_spacing.configure(font=self.__FONT_STYLE)
        value_channel_spacing = self.rf_object.getMdmChanSpc()
        self._ety_channel_spacing.insert(0, int(value_channel_spacing))
        self._ety_channel_spacing.configure(state='readonly')

        # enable manchester
        lab_manchester = Label(frame, text='Enable Manchester')
        lab_manchester.grid(column=0, row=4, padx=5, pady=5, sticky=E)
        lab_manchester.configure(font=self.__FONT_STYLE)

        cbx_manchester = Checkbutton(frame)
        cbx_manchester.grid(column=1, row=4, padx=5, pady=5, sticky=W)
        if self.rf_object.getEnableMdmManchester() == 1:
            self._cbx_manchester_value.set(1)
        else:
            self._cbx_manchester_value.set(0)
        cbx_manchester.configure(onvalue=1,
                                 offvalue=0,
                                 variable=self._cbx_manchester_value)

        # save settings
        self._btn_save_settings = Button(frame,
                                         text='Save all Settings',
                                         command=self.__action_store_settings)
        self._btn_save_settings.grid(column=5, row=4, padx=5, pady=5)
        self._btn_save_settings.configure(font=self.__FONT_STYLE)
        self._btn_save_settings.bind(
            "<Enter>", lambda event: event.widget.config(fg='indian red'))
        self._btn_save_settings.bind(
            "<Leave>", lambda event: event.widget.config(fg='black'))
Beispiel #20
0
class LoggerClient(object):
    def __init__(self, messages_endpoint):
        self.messages_endpoint = messages_endpoint

        # main window
        self.container = Tk()
        self.container.title('Logger Client')
        self.width = 402
        self.height = 267
        self.container.geometry('%sx%s' % (self.width, self.height))
        self.container.config(bg='grey')
        # required fields frame
        self.fields_frame = Frame(self.container)
        self.fields_frame.grid(row=0, column=0, sticky="W", padx=5, pady=5)
        self.fields_frame.config(highlightthickness=3)
        self.fields_frame.config(highlightbackground='grey')

        self.message_type_label = Label(self.fields_frame,
                                        text='Type',
                                        font="bold")
        self.message_type_label.grid(row=0, column=0)
        self.message_label = Label(self.fields_frame,
                                   text='Log Message',
                                   font="bold")
        self.message_label.grid(row=0, column=1)

        var = StringVar(self.container)
        var.set("INFO")
        self.message_type_optionmenu = OptionMenu(
            self.fields_frame,
            var,
            "INFO",
            "ERROR",
            command=self.set_message_type)
        self.message_type_optionmenu.grid(row=1, column=0)

        self.message_textbox = Entry(self.fields_frame, width=51)
        self.message_textbox.grid(row=1, column=1)

        # optional fields frame
        self.optionals_frame = Frame(self.container)
        self.optionals_frame.grid(row=1, column=0, sticky="W", padx=5, pady=5)
        self.optionals_frame.config(highlightthickness=3)
        self.optionals_frame.config(highlightbackground='grey')
        self.email_label = Label(self.optionals_frame,
                                 text="Email",
                                 font="bold")
        self.email_label.grid(row=2, column=0)
        self.email_textbox = Entry(self.optionals_frame, width=55)
        self.email_textbox_default = 'This field is optional'
        self.email_textbox.insert(0, self.email_textbox_default)
        self.email_textbox.grid(row=2, column=1)

        # login frame
        self.login_frame = Frame(self.container)
        self.login_frame.grid(row=2,
                              column=0,
                              columnspan=20,
                              sticky="W",
                              padx=5,
                              pady=5)
        self.login_frame.config(highlightthickness=3)
        self.login_frame.config(highlightbackground='grey')

        self.username_label = Label(self.login_frame,
                                    text='Username',
                                    font="bold")
        self.username_label.grid(row=0, column=0)
        self.username_textbox = Entry(self.login_frame, width=33)
        self.username_textbox.grid(row=0, column=1)

        self.password_label = Label(self.login_frame,
                                    text='Password',
                                    font="bold")
        self.password_label.grid(row=1, column=0)
        self.password_textbox = Entry(self.login_frame, width=33, show="*")
        self.password_textbox.grid(row=1, column=1)

        self.send_button = Button(self.login_frame,
                                  text='Send',
                                  command=self.send,
                                  width=10,
                                  font="bold",
                                  bg="green")
        self.send_button.grid(row=1, column=2, sticky="W")

        # response frame
        self.response_frame = Frame(self.container)
        self.response_frame.grid(row=3, column=0, sticky="W", padx=5, pady=5)
        self.response_frame.config(highlightthickness=3)
        self.response_frame.config(highlightbackground='grey')
        self.response_label = Label(self.response_frame,
                                    text="Response",
                                    font="bold")
        self.response_label.grid(row=0, column=0)
        self.response_textbox = Text(self.response_frame, width=47, height=2)
        self.response_textbox.grid(row=1, column=0)

        self.message_type = None

    def set_message_type(self, value):
        self.message_type = value

    def clear_response(self):
        self.response_textbox.delete(
            self.response_textbox.index("end-1c linestart"), END)

    def get_auth_payload(self):
        username = self.username_textbox.get()
        password = self.password_textbox.get()
        if not username or not password:
            return None
        return username, password

    def post_message(self, data):
        try:
            auth = data.pop('auth')
            data = json.dumps(data)
            return requests.post(self.messages_endpoint, auth=auth, data=data)
        except MissingSchema:
            # TODO not sure why the default vars are sometimes not loaded. Must fix. Defaulting
            self.messages_endpoint = "http://127.0.0.1:5000/messages/"
            return requests.post(self.messages_endpoint, auth=auth, data=data)

    def send(self):
        self.clear_response()

        message = self.message_textbox.get()
        if not message:
            self.response_textbox.insert(END, "Please enter a Log Message.")
            return

        auth = self.get_auth_payload()
        if not auth:
            self.response_textbox.insert(
                END, "Please enter a username and password.")
            return

        email_text = self.email_textbox.get()
        email = email_text if email_text != self.email_textbox_default else None

        payload = dict()
        payload['message'] = message
        payload['message_type'] = self.message_type
        payload['auth'] = auth
        if email:
            payload['email'] = email

        try:
            res = self.post_message(payload)
        except ConnectionError:
            self.clear_response()
            self.response_textbox.insert(
                END,
                "Could not connect to server. Please contact your system administrator."
            )
        else:
            if res.status_code == 401:
                self.response_textbox.insert(END, "Invalid username/password.")
            elif res.status_code == 400:
                self.response_textbox.insert(END,
                                             json.loads(res.text)['message'])
            elif res.status_code == 200:
                self.response_textbox.insert(END, "Log message saved.")
                self.message_textbox.delete(0, END)
                self.email_textbox.delete(0, END)
                self.email_textbox.insert(END, self.email_textbox_default)
            elif res.status_code == 500:
                self.response_textbox.insert(
                    END,
                    "The server didn't understand how to handle the request. Please contact your system administrator."
                )
            else:
                self.response_textbox.insert(
                    END, "Unknown response code: %s" % res.status_code)

    @classmethod
    def run(cls):
        import os
        import configparser
        env_uri = os.environ.get('SIMPLIFIED_LOGGER_SERVER_URI')
        env_messages_ep = os.environ.get('MESSAGES_ENDPOINT')
        if env_uri and env_messages_ep:
            base_url = os.environ['SIMPLIFIED_LOGGER_SERVER_URI']
            messages_endpoint = os.environ['MESSAGES_ENDPOINT']
        else:
            config = configparser.ConfigParser()
            config.read('config.ini')
            base_url = config['DEFAULT'].get('SERVER_URI')
            messages_endpoint = config['DEFAULT'].get("MESSAGES_ENDPOINT")

        client = cls("%s%s" % (base_url, messages_endpoint))
        client.container.mainloop()
Beispiel #21
0
class myToolbox:
    def __init__(self, master):
        # ~ self.adw = adawat.adawat.Adawat()
        # opend file
        self.filename = ""
        # parser
        self.parser = tm.html_displayer()

        self.master = master
        master.title(u"جدول التوقيت TimeTable ")
        myfont = os.path.join(sys.path[0], "resources", "fonts",
                              "AmiriTypewriter-Regular.ttf")

        self.total = 0
        self.entered_number = 0
        # make menu
        self.makemenu()
        # ~ self.output_label = Label(master, text="Output")
        self.shape_label = Label(master, text="Shape")

        self.label = Label(master, text="Output:")
        self.label_actions = Label(master, text="Action:")
        self.label_config = Label(master, text="Config:")

        #~ vcmd = master.register(self.validate) # we have to wrap the command
        #self.entry = Text(master, height=15, width=70, font=myfont)

        # ~ self.output = Text(master, height=15, width=70, font=myfont)
        self.output = HTMLScrolledText(master,
                                       height=15,
                                       width=70,
                                       font=myfont)

        # ~ sampletext = u"""Greating\tالسلام عليكم ورحمة الله وبركاته
        # ~ Welcome\tمرحبا\tBien venue
        # ~ Welcome\tأهلا ووسهلا"""
        # ~ self.entry.insert("1.0", self.bidi(sampletext))
        #~ self.nshape = Entry(master, validate="key")
        #~ self.nshape.insert(END,2)
        #~ self.entry = Entry(master, validate="key", validatecommand=(vcmd, '%P'))

        self.freerooms_button = Button(
            master,
            text="Free Rooms",
            command=lambda: self.update("freerooms"))
        self.availteachers_button = Button(
            master,
            text="Available Teachers",
            command=lambda: self.update("teachers"))
        self.timetable_button = Button(
            master,
            text="TimeTable",
            command=lambda: self.update("timetables"))
        # ~ self.reshape_button = Button(master, text="Reshape", command=lambda: self.update("reshape"))
        # ~ self.itemize_button = Button(master, text="Itemize", command=lambda: self.update("itemize"))
        self.affectation_button = Button(
            master,
            text="Affectation",
            command=lambda: self.update("affectation"))
        self.charge_button = Button(master,
                                    text="Charges",
                                    command=lambda: self.update("charges"))
        # ~ self.list_button = Button(master, text="Python list", command=lambda: self.update("pythonlist"))
        # ~ self.tabbing_button = Button(master, text="Tabbing", command=lambda: self.update("tabbing"))
        self.submit_button = Button(master,
                                    text="Submit",
                                    bg="green",
                                    fg="white",
                                    command=lambda: self.update("submit"))
        self.reset_button = Button(master,
                                   text="Reset",
                                   command=lambda: self.update("reset"))
        self.copy_button = Button(master,
                                  text="Copy",
                                  command=lambda: self.update("copy"))
        self.recopy_button = Button(master,
                                    text="Recopy",
                                    command=lambda: self.update("recopy"))

        #format options
        OPTIONS_ROOMS = ["all", "tp", "salle"]
        self.rooms_opt = StringVar()
        self.rooms_opt.set(OPTIONS_ROOMS[0])
        self.rooms_options = OptionMenu(master, self.rooms_opt, *OPTIONS_ROOMS)
        #language options
        OPTIONS = ["all", "vac", "tp", "cours", "details"]
        self.teacher_opt = StringVar()
        self.teacher_opt.set(OPTIONS[0])
        self.teacher_options = OptionMenu(master, self.teacher_opt, *OPTIONS)

        # ~ # shape options
        # ~ OPTIONS_SHAPE = [1,2,3,4,5,6,7,8,9]
        # ~ self.shape_opt = IntVar()
        # ~ self.shape_opt.set(OPTIONS_SHAPE[2])
        # ~ self.shape_options = OptionMenu(master, self.shape_opt, *OPTIONS_SHAPE)
        # transliterate
        OPTIONS_TM = ["groups", "teachers", "rooms"]
        self.tm_opt = StringVar()
        self.tm_opt.set(OPTIONS_TM[0])
        self.tm_options = OptionMenu(master, self.tm_opt, *OPTIONS_TM)
        # ~ # itemize options
        # ~ OPTIONS_ITEM = ["itemize","enumerate"]
        # ~ self.itemize_opt = StringVar()
        # ~ self.itemize_opt.set(OPTIONS_ITEM[0])
        # ~ self.itemize_options = OptionMenu(master, self.itemize_opt, *OPTIONS_ITEM)
        # ~ # separator options
        # ~ OPTIONS_SEP= ["tab", "space", ";",",", "\\t"]
        # ~ self.separator_opt = StringVar()
        # ~ self.separator_opt.set(OPTIONS_SEP[0])
        # ~ self.separator_options = OptionMenu(master, self.separator_opt, *OPTIONS_SEP)
        # Actions options
        OPTIONS_ACTION = self.parser.commands
        self.action_opt = StringVar()
        self.action_opt.set(OPTIONS_ACTION[0])
        self.action_options = OptionMenu(master, self.action_opt,
                                         *OPTIONS_ACTION)

        # LAYOUT
        #0
        self.label.grid(row=0, column=0, sticky=W)
        self.label_actions.grid(row=0, column=3, sticky=W)
        self.label_config.grid(row=0, column=4, sticky=W)
        #1
        self.output.grid(row=1,
                         column=0,
                         rowspan=6,
                         columnspan=3,
                         sticky=W + E)

        # ~ self.entry.grid(row=1, column=0, rowspan=6, columnspan=3, sticky=W+E)
        #1
        self.timetable_button.grid(row=1, column=3, sticky=W + E)
        self.tm_options.grid(row=1, column=4, sticky=W + E)

        #2
        self.freerooms_button.grid(row=2, column=3, sticky=W + E)
        self.rooms_options.grid(row=2, column=4, sticky=W + E)

        #3
        self.availteachers_button.grid(row=3, column=3, sticky=W + E)
        self.teacher_options.grid(row=3, column=4, sticky=W + E)

        # ~ #3
        # ~ self.timetable_button.grid(row=3, column=3, sticky=W+E)
        # ~ self.tm_options.grid(row=3, column=4, sticky=W+E)
        #4
        self.affectation_button.grid(row=4, column=3, sticky=W + E)
        self.charge_button.grid(row=4, column=4, sticky=W + E)
        # ~ self.reshape_button.grid(row=5, column=3, sticky=W+E)
        # ~ self.shape_options.grid(row=5, column=4, sticky=W+E)
        # ~ #6
        # ~ self.itemize_button.grid(row=6, column=3, sticky=W+E)
        # ~ self.itemize_options.grid(row=6, column=4, sticky=W+E)
        #7 Output label
        # ~ self.output_label.grid(row=7, column=0, columnspan=1, sticky=W)
        self.submit_button.grid(row=7, column=1, sticky=E)
        self.action_options.grid(row=7, column=2, sticky=W + E)
        # ~ self.tabbing_button.grid(row=7, column=3, sticky=W+E)
        # ~ self.separator_options.grid(row=7, column=4, sticky=W+E)
        # 8

        # ~ self.output.grid(row=8, column=0, rowspan=6, columnspan=3, sticky=W+E)

        # 9
        # ~ self.list_button.grid(row=9, column=4, sticky=W+E)

        #10
        self.copy_button.grid(row=5, column=3, columnspan=2, sticky=W + E)
        self.recopy_button.grid(row=6, column=3, columnspan=2, sticky=W + E)
        self.reset_button.grid(row=7, column=3, columnspan=2, sticky=W + E)
        #5
    def makemenu(self, ):
        menubar = Menu(self.master)
        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label="New", command=donothing)
        filemenu.add_command(label="Open", command=self.browseFiles)
        filemenu.add_command(label="Save", command=donothing)
        filemenu.add_command(label="Save as...", command=donothing)
        filemenu.add_command(label="Close", command=donothing)

        filemenu.add_separator()

        filemenu.add_command(label="Exit", command=self.master.quit)
        menubar.add_cascade(label="File", menu=filemenu)
        editmenu = Menu(menubar, tearoff=0)
        editmenu.add_command(label="Undo", command=donothing)

        editmenu.add_separator()

        editmenu.add_command(label="Cut", command=donothing)
        editmenu.add_command(label="Copy", command=lambda: self.update("copy"))
        editmenu.add_command(label="ReCopy",
                             command=lambda: self.update("recopy"))
        editmenu.add_command(label="Paste", command=donothing)
        editmenu.add_command(label="Delete",
                             command=lambda: self.update("reset"))
        editmenu.add_command(label="Select All", command=donothing)

        menubar.add_cascade(label="Edit", menu=editmenu)

        # Available menu
        latexmenu = Menu(menubar, tearoff=0)
        latexmenu.add_command(label="Free rooms",
                              command=lambda: self.update("freerooms"))
        latexmenu.add_command(label="Available teachers",
                              command=lambda: self.update("teachers"))
        latexmenu.add_command(
            label="Available teachers TP",
            command=lambda: self.update("availableteachers_tp"))
        latexmenu.add_command(
            label="Available teachers vacataires",
            command=lambda: self.update("availableteachers_vac"))
        latexmenu.add_command(
            label="Available teachers Details",
            command=lambda: self.update("availableteachers_details"))
        menubar.add_cascade(label="Available", menu=latexmenu)

        # Time Table
        arabicmenu = Menu(menubar, tearoff=0)
        arabicmenu.add_command(
            label="TimeTable by group",
            command=lambda: self.update("timetables_groups"))
        arabicmenu.add_command(
            label="Language by teachers",
            command=lambda: self.update("timetables_teachers"))
        arabicmenu.add_command(label="Language by rooms",
                               command=lambda: self.update("timetables_rooms"))
        menubar.add_cascade(label="TimeTables", menu=arabicmenu)

        # Charges
        toolsmenu = Menu(menubar, tearoff=0)
        toolsmenu.add_command(label="Charges",
                              command=lambda: self.update("charges"))
        toolsmenu.add_command(label="Affectation",
                              command=lambda: self.update("affectation"))
        menubar.add_cascade(label="Charges", menu=toolsmenu)

        helpmenu = Menu(menubar, tearoff=0)
        helpmenu.add_command(label="Help Index",
                             command=lambda: self.update("help"))
        helpmenu.add_command(label="About...",
                             command=lambda: self.update("about"))
        menubar.add_cascade(label="Help", menu=helpmenu)

        self.master.config(menu=menubar)

    # Function for opening the
    # file explorer window
    def browseFiles(self, ):
        self.filename = filedialog.askopenfilename(
            initialdir="¬",
            title="Select a File",
            filetypes=(("Text files", "*.oct*"), ("all files", "*.*")))

        # Change label contents
        # ~ label_file_explorer.configure(text="File Opened: "+filename)
        #~ @staticmethod
        print("filename :", self.filename)
        self.parser = tm.html_displayer(self.filename)
        # default
        self.update("default")

    def bidi(self, text):
        return text
        #~ reshaped_text  = self.adw.delimite_language_bidi(text, arabic_reshaper.reshape)
        #~ reshaped_text = arabic_reshaper.reshape(text)
        #~ bidi_text = get_display(reshaped_text)
        #~ return bidi_text

    #~ @staticmethod
    def unbidi(self, text):
        return text
        #~ unshaped_text = pyarabic.unshape.unshaping_text(text)
        #~ unshaped_text  = self.adw.delimite_language_bidi(text, pyarabic.unshape.unshaping_text)

        #~ bidi_text = get_display(reshaped_text)
        #~ return unshaped_text

    # ~ def get_separator(self,):
    # ~ sep = self.separator_opt.get()
    # ~ if sep =="tab":
    # ~ return "\t"
    # ~ elif sep =="space":
    # ~ return " "
    # ~ else:
    # ~ return sep
    def help(self):
        tkMessageBox.showinfo("Help", "Not yet implemented")

    def about(self):
        tkMessageBox.showinfo(
            "Help",
            self.bidi(u"TimeTable from OpenOCTT\ndeveloped by Taha Zerrouki"))

    def update(self, method):
        """
        
        """
        if not self.filename:
            tkMessageBox.showinfo("Info", "You should select a timetable file")
            return False
        display_format = self.rooms_opt.get()
        if method == "help":
            self.help()
            return True
        if method == "about":
            self.about()
            return True
        if method == "reset":
            self.output.delete("1.0", END)
            # ~ self.entry.delete("1.0", END)
            return True
        if method == "recopy":
            result = self.output.get("1.0", END)
            # ~ self.entry.delete("1.0", END)
            # ~ self.entry.insert("1.0", result)
            return True
        if method == "copy":
            value = self.output.get("1.0", END)
            self.master.clipboard_clear()
            self.master.clipboard_append(self.unbidi(value))
            return True
        if method == "submit":
            command = self.action_opt.get()
            #~ print(command)
        else:
            command = method
        # ~ value = self.entry.get("1.0",END)
        #value = self.unbidi(value)

        if command == "default":
            command = "timetables_groups"
        if command == "freerooms":
            room_type = self.rooms_opt.get()
            if room_type and room_type != "all":
                command += "_" + room_type
            result = self.parser.action(command)
        elif command == "teachers":
            command = "availableteachers"
            teacher_type = self.teacher_opt.get()
            if teacher_type and teacher_type != "all":
                command += "_" + teacher_type
            result = self.parser.action(command)
        elif command == "timetables":
            slot_type = self.tm_opt.get()
            if slot_type and slot_type != "all":
                command += "_" + slot_type
            result = self.parser.action(command)
        elif command == "affectation":
            result = self.parser.action(command)
        elif command == "charges":
            result = self.parser.action(command)
        elif command in self.parser.commands:
            result = self.parser.action(command)
        else:  # reset
            donothing()
            result = "Nothing to do with %s" % command
        self.output.delete("1.0", END)
        # ~ self.output.insert("1.0", self.bidi(result))
        self.output.set_html(result)
Beispiel #22
0
class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent
        self.initUI()

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

        self.quitbutton = Button(self, text="Quit", command=lambda: self.quit())

        self.quitbutton.grid(row=3, column=1, pady=4)

        self.labelErrorPointer = Label(self, text="◀")

        self.labellist = []
        self.entrylist = []
        self.verifylist = []
        self.misclist = []

        self.optionCreate = "Create"
        self.optionUpcoming = "Upcoming"
        self.optionPast = "Past"

        self.prevmode = self.optionCreate
        self.curmode = self.optionCreate
        self.optionvar = tkinter.StringVar(self)
        self.optionvar.trace("w", self.permaloop)
        self.optionvar.set(self.optionCreate)
        self.option = OptionMenu(self, self.optionvar, self.optionCreate, self.optionUpcoming, self.optionPast)

        self.optionpostmodevar = tkinter.StringVar(self)
        self.optionpostmodevar.trace("w", self.permaloop)
        self.optionpostmodevar.set("url")
        self.optionpostmode = OptionMenu(self, self.optionpostmodevar, "url", "text")

        self.labelText = Label(self, text="Selftext:")
        self.entryText = Text(self)
        self.labelURL = Label(self, text="URL:")
        self.entryURL = Entry(self)
        self.entryURL.configure(width=60)

        self.sql = sqlite3.connect("sql.db")
        print("Loaded SQL Database")
        self.cur = self.sql.cursor()

        self.cur.execute(
            "CREATE TABLE IF NOT EXISTS upcoming(ID TEXT, SUBREDDIT TEXT, TIME INT, TITLE TEXT, URL TEXT, BODY TEXT)"
        )
        self.cur.execute(
            "CREATE TABLE IF NOT EXISTS past(ID TEXT, SUBREDDIT TEXT, TIME INT, TITLE TEXT, URL TEXT, BODY TEXT, POSTLINK TEXT)"
        )
        self.cur.execute("CREATE TABLE IF NOT EXISTS internal(NAME TEXT, ID INT)")
        print("Loaded Completed table")
        self.cur.execute("SELECT * FROM internal")
        f = self.cur.fetchone()
        if not f:
            print("Database is new. Adding ID counter")
            self.cur.execute("INSERT INTO internal VALUES(?, ?)", ["counter", 1])
            self.idcounter = 1
        else:
            self.idcounter = f[1]
            print("Current ID counter: " + str(self.idcounter))

        self.sql.commit()

        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()

        w = 853
        h = 480
        x = (sw - w) / 2
        y = (sh - h) / 2

        self.parent.geometry("%dx%d+%d+%d" % (w, h, x, y - 50))

        self.login()

    def login(self):

        try:
            self.quitbutton.grid_forget()
            self.quitbutton.grid(row=9000, column=0, columnspan=20)

            self.option.grid(row=1, column=0, columnspan=8, pady=8)

            self.updategui(fullclean=True)
        except praw.errors.InvalidUserPass:
            pass
            print("Invalid username or password")
            self.entryPassword.delete(0, 200)
            self.labelErrorPointer.grid(row=1, column=2)

    def permaloop(self, *args):
        self.curmode = self.optionvar.get()
        print("Was: " + self.prevmode + " | Now: " + self.curmode)
        if self.curmode != self.prevmode:
            self.prevmode = self.curmode
            self.updategui(fullclean=True)
        else:
            self.updategui(False)

    def getTime(self, bool):
        timeNow = datetime.datetime.now(datetime.timezone.utc)
        timeUnix = timeNow.timestamp()
        if bool == False:
            return timeNow
        else:
            return timeUnix

    def addentrytobase(self, subreddit, title, url="", body="", mode="", ptime=""):
        curtime = round(self.getTime(True))
        try:
            t = (
                self.entryMo.get()
                + " "
                + self.entryDa.get()
                + " "
                + self.entryYr.get()
                + " "
                + self.entryHH.get()
                + ":"
                + self.entryMM.get()
            )
            plandate = datetime.datetime.strptime(t, "%B %d %Y %H:%M")
            plandate = plandate.timestamp()
        except ValueError:
            print("Invalid Day")
            return False

        if mode == "url":
            url = self.entryURL.get()
            body = ""
            if "http://" not in url and "https://" not in url:
                print("Please enter a proper URL")
                return False
        if mode == "text":
            body = self.entryText.get("1.0", "end")
            url = ""

        if plandate < curtime:
            print("Please enter a time in the future")
            return False

        if not all(char in string.ascii_letters + string.digits + "_-" for char in subreddit):
            print("Subreddit contains invalid characters")
            return False

        if len(subreddit) == 0:
            print("You must enter a subreddit")
            return False

        if len(title) == 0:
            print("You must enter a title")
            return False
        if len(title) > 300:
            print("Title is too long. " + str(len(title)) + "/300 char max")
            return False
        if len(body) > 15000:
            print("Body is too long. " + str(len(body)) + "/15,000 char max")

        print("Timestamp:", plandate)
        self.cur.execute(
            "INSERT INTO upcoming VALUES(?, ?, ?, ?, ?, ?)",
            [self.idcounter, subreddit, int(plandate), title, url, body],
        )
        self.idcounter += 1
        self.cur.execute("UPDATE internal SET ID=? WHERE NAME=?", [self.idcounter, "counter"])
        self.sql.commit()
        print("Post Saved!")
        self.entryText.delete("1.0", "end")
        self.entryURL.delete(0, "end")
        self.entryTitle.delete(0, "end")
        # self.updategui(halfclean=True)

    def dropentryfrombase(self, ID):
        try:
            ID = int(ID)
        except ValueError:
            print("You must enter a number")
            return
        print("Dropping Item " + str(ID) + " from Upcoming")
        self.cur.execute("DELETE FROM upcoming WHERE ID=?", [ID])
        self.sql.commit()
        self.updategui(fullclean=True)

    def printbasetofile(self, db):
        filea = open(db + ".txt", "w")
        if db == "past":
            self.cur.execute("SELECT * FROM past")
        if db == "upcoming":
            self.cur.execute("SELECT * FROM upcoming")
        f = self.cur.fetchall()
        print("Printed " + db + " unimpeded to file")
        for item in f:
            i = list(item)
            d = datetime.datetime.fromtimestamp(i[2])
            i[2] = datetime.datetime.strftime(d, "%b %d %H:%M")
            i.remove("")

            print(str(i)[1:-1], file=filea)
        filea.close()

    def updategui(self, halfclean=False, fullclean=False):

        if self.curmode == self.optionCreate:
            try:
                print(self.optionpostmodevar.get())

                if self.optionpostmodevar.get() == "url":
                    self.entryText.delete("1.0", "end")
                    self.labelText.grid_forget()
                    self.entryText.grid_forget()

                    self.labelURL.grid(row=8, column=0, columnspan=30)
                    self.entryURL.grid(row=9, column=0, columnspan=12, pady=10)

                if self.optionpostmodevar.get() == "text":
                    self.entryURL.delete(0, "end")
                    self.labelURL.grid_forget()
                    self.entryURL.grid_forget()

                    self.labelText.grid(row=8, column=0, columnspan=30)
                    self.entryText.configure(width=40, height=8)
                    self.entryText.grid(row=9, column=0, columnspan=12)
            except AttributeError:
                pass

        if fullclean == True:
            print("Cleaning GUI")
            for item in self.labellist:
                item.grid_forget()
            for item in self.entrylist:
                item.grid_forget()
            for item in self.verifylist:
                item.grid_forget()
            for item in self.misclist:
                item.grid_forget()
            self.labellist = []
            self.entrylist = []
            self.verifylist = []
            self.misclist = []

            if self.curmode == self.optionCreate:
                self.newrowindex = 6
                self.labelSubreddit = Label(self, text="Subreddit:    /r/")
                self.labelTitle = Label(self, text="Post title:  ")
                self.entrySubreddit = Entry(self)
                self.entryTitle = Entry(self)

                self.labelHH = Label(self, text="Schedule time (Local timezone):")
                nowlist = datetime.datetime.strftime(datetime.datetime.now(), "%B %d %Y %H %M").split()

                self.entryMo = Spinbox(
                    self,
                    width=9,
                    values=(
                        "January",
                        "February",
                        "March",
                        "April",
                        "May",
                        "June",
                        "July",
                        "August",
                        "September",
                        "October",
                        "November",
                        "December",
                    ),
                )
                self.entryMo.delete(0, "end")
                self.entryMo.insert(0, nowlist[0])

                self.entryDa = Spinbox(self, width=2, from_=1, to=31)
                self.entryDa.delete(0, "end")
                self.entryDa.insert(0, nowlist[1])

                self.entryYr = Spinbox(self, width=4, from_=2014, to=2500)
                self.entryYr.delete(0, "end")
                self.entryYr.insert(0, nowlist[2])

                self.entryHH = Spinbox(self, from_=0, to=23, width=2)
                self.entryHH.delete(0, "end")
                self.entryHH.insert(0, nowlist[3])

                self.entryMM = Spinbox(self, from_=0, to=59, width=2)
                self.entryMM.delete(0, "end")
                self.entryMM.insert(0, nowlist[4])

                self.buttonAddentry = Button(
                    self,
                    text="Save",
                    command=lambda: self.addentrytobase(
                        self.entrySubreddit.get(), self.entryTitle.get(), mode=self.optionpostmodevar.get()
                    ),
                )

                self.misclist.append(self.labelSubreddit)
                self.misclist.append(self.entrySubreddit)
                self.misclist.append(self.labelHH)
                self.misclist.append(self.entryHH)
                self.misclist.append(self.entryMM)
                self.misclist.append(self.entryMo)
                self.misclist.append(self.entryDa)
                self.misclist.append(self.entryYr)
                self.misclist.append(self.labelTitle)
                self.misclist.append(self.entryTitle)
                self.misclist.append(self.buttonAddentry)
                self.misclist.append(self.optionpostmode)
                self.misclist.append(self.labelText)
                self.misclist.append(self.entryText)
                self.misclist.append(self.labelURL)
                self.misclist.append(self.entryURL)

                self.labelSubreddit.grid(row=2, column=0, sticky="e")
                self.labelTitle.grid(row=3, column=0, sticky="e")
                self.entrySubreddit.grid(row=2, column=1, columnspan=3, sticky="w")
                self.entryTitle.grid(row=3, column=1, columnspan=3, sticky="w")
                self.entryMo.grid(row=4, column=1, sticky="e")
                self.entryDa.grid(row=4, column=2)
                self.entryYr.grid(row=4, column=3)
                self.labelHH.grid(row=4, column=0, sticky="se", pady=5)
                self.entryHH.grid(row=5, column=1, sticky="e")
                self.entryMM.grid(row=5, column=2, sticky="w")
                self.optionpostmode.grid(row=6, column=0, columnspan=20, pady=10)
                self.buttonAddentry.grid(row=200, column=0, columnspan=20)

            if self.curmode == self.optionUpcoming:
                self.cur.execute("SELECT * FROM upcoming")
                dobutton = True

            if self.curmode == self.optionPast:
                self.cur.execute("SELECT * FROM past")
                dobutton = False

            if self.curmode == self.optionPast or self.curmode == self.optionUpcoming:

                self.listboxId = Listbox(self)
                self.listboxId.configure(width=118, height=20, font=("Courier 8"))
                self.misclist.append(self.listboxId)

                self.listboxScroller = Scrollbar(self, orient="horizontal", command=self.listboxId.xview)
                self.listboxScroller.grid(row=4, column=0, columnspan=900)
                self.listboxId.grid(row=3, column=0, columnspan=10)

                self.listboxId.configure(xscrollcommand=self.listboxScroller.set)
                self.misclist.append(self.listboxScroller)

                self.buttonPrinter = Button(self, text="Print to .txt file")
                if self.curmode == self.optionPast:
                    self.buttonPrinter.configure(command=lambda: self.printbasetofile("past"))
                if self.curmode == self.optionUpcoming:
                    self.buttonPrinter.configure(command=lambda: self.printbasetofile("upcoming"))

                self.buttonPrinter.grid(row=6, column=0, columnspan=90)
                self.misclist.append(self.buttonPrinter)

                if dobutton == True:
                    self.entryDelete = Entry(self)
                    self.buttonDelete = Button(
                        self, text="Delete Item: ", command=lambda: self.dropentryfrombase(self.entryDelete.get())
                    )
                    self.buttonDelete.grid(row=5, column=0, sticky="e")
                    self.entryDelete.grid(row=5, column=1, sticky="w")
                    self.misclist.append(self.entryDelete)
                    self.misclist.append(self.buttonDelete)

                fetched = self.cur.fetchall()
                for item in fetched:
                    d = datetime.datetime.fromtimestamp(item[2])
                    info = datetime.datetime.strftime(d, "%b %d %H:%M")

                    if item[4] == "":
                        infx = item[5]
                    if item[5] == "":
                        infx = item[4]
                    if self.curmode == self.optionPast:
                        infy = "." + item[6]
                    else:
                        infy = ""

                    self.listboxId.insert(
                        "end",
                        item[0]
                        + "." * (6 - len(item[0]))
                        + item[1][:10]
                        + "." * (12 - len(item[1][:10]))
                        + info
                        + "." * (15 - len(info[:14]))
                        + item[3][:18]
                        + "." * (20 - len(item[3][:14]))
                        + infx[:45]
                        + "." * (47 - len(infx[:45]))
                        + infy,
                    )

    def morerows(self, label, columnm, columnn, limit, *args):
        self.redditlabel = Label(self, text=label)
        self.redditlabel.grid(row=self.newrowindex, column=columnm, sticky="e")
        self.labellist.append(self.redditlabel)

        self.redditentry = Entry(self)
        self.redditentry.grid(row=self.newrowindex, column=columnn, columnspan=9)
        self.entrylist.append(self.redditentry)

        self.newrowindex += 1
        if self.newrowindex >= limit:
            self.morerowbutton.grid_forget()
        print(self.newrowindex)
Beispiel #23
0
def youtube_dl_launcher_for_ffmpegaudioencoder():
    # Imports----------------------------------------------------------------------------------------------------------
    from tkinter import (filedialog, StringVar, Menu, E, W, N, S, LabelFrame,
                         NORMAL, END, DISABLED, Checkbutton, Label, ttk,
                         scrolledtext, messagebox, OptionMenu, Toplevel, WORD,
                         Entry, Button, HORIZONTAL, SUNKEN, Text)
    import pyperclip, pathlib, threading, yt_dlp
    from re import sub
    from configparser import ConfigParser

    global main

    # --------------------------------------------------------------------------------------------------------- Imports

    # Main Gui & Windows ----------------------------------------------------------------------------------------------
    def main_exit_function():  # Asks if the user is ready to exit
        confirm_exit = messagebox.askyesno(
            title='Prompt',
            message="Are you sure you want to exit the program?\n\n"
            "     Note: This will end all current tasks!",
            parent=main)
        if confirm_exit:  # If user selects Yes - destroy window
            main.destroy()

    # Main UI window --------------------------------------------------------------------------------------------------
    try:  # Checks rather or not the youtube-dl-gui window is already open
        if main is not None or Toplevel.winfo_exists(main):
            main.lift(
            )  # If youtube-dl-gui window exists then bring to top of all other windows

    except:  # If youtube-dl-gui does not exist, create it...
        if not combined_with_ffmpeg_audio_encoder:
            from tkinter import Tk, PhotoImage
            main = Tk()  # Make full tkinter loop if standalone
            main.iconphoto(
                True, PhotoImage(file="Runtime/Images/Youtube-DL-Gui.png"))
        if combined_with_ffmpeg_audio_encoder:
            main = Toplevel()  # Make toplevel loop if NOT standalone
        main.title("Simple-Youtube-DL-Gui v1.21")
        main.configure(background="#434547")
        window_height = 500
        window_width = 610
        screen_width = main.winfo_screenwidth()
        screen_height = main.winfo_screenheight()
        x_coordinate = int((screen_width / 2) - (window_width / 2))
        y_coordinate = int((screen_height / 2) - (window_height / 2))
        main.geometry(
            f"{window_width}x{window_height}+{x_coordinate}+{y_coordinate}")
        main.protocol('WM_DELETE_WINDOW', main_exit_function)

        for n in range(4):  # Loop to specify the needed column/row configures
            main.grid_columnconfigure(n, weight=1)
        for n in range(5):
            main.grid_rowconfigure(n, weight=1)

        # The entire top bar/menu is only present during standalone version -------------------------------------------
        if not combined_with_ffmpeg_audio_encoder:
            my_menu_bar = Menu(main, tearoff=0)
            main.config(menu=my_menu_bar)
            file_menu = Menu(my_menu_bar,
                             tearoff=0,
                             activebackground='dim grey')
            my_menu_bar.add_cascade(label='File', menu=file_menu)
            file_menu.add_command(
                label='Exit', command=main_exit_function)  # Exits the program
            options_menu = Menu(my_menu_bar,
                                tearoff=0,
                                activebackground='dim grey')
            my_menu_bar.add_cascade(label='Options', menu=options_menu)

            def set_ffmpeg_path():
                global ffmpeg
                path = filedialog.askopenfilename(
                    title='Select Location to "ffmpeg.exe"',
                    initialdir='/',
                    filetypes=[('ffmpeg', 'ffmpeg.exe')])
                if path == '':
                    pass
                elif path != '':
                    ffmpeg = str(pathlib.Path(path))
                    config.set('ffmpeg_path', 'path', ffmpeg)
                    with open(config_file, 'w') as configfile:
                        config.write(configfile)

            options_menu.add_command(label='Set path to FFMPEG',
                                     command=set_ffmpeg_path)

            options_menu.add_separator()

            def reset_config():
                msg = messagebox.askyesno(
                    title='Warning',
                    message=
                    'Are you sure you want to reset the config.ini file settings?'
                )
                if not msg:
                    pass
                if msg:
                    try:
                        config.set('ffmpeg_path', 'path', '')
                        with open(config_file, 'w') as configfile:
                            config.write(configfile)
                        messagebox.showinfo(
                            title='Prompt',
                            message='Please restart the program')
                    except:
                        pass
                    main.destroy()

            options_menu.add_command(label='Reset Configuration File',
                                     command=reset_config)

            from Packages.about import openaboutwindow

            def open_browser_for_ffmpeg():
                import webbrowser
                webbrowser.open_new_tab(
                    'https://www.gyan.dev/ffmpeg/builds/ffmpeg-git-essentials.7z'
                )

            help_menu = Menu(my_menu_bar,
                             tearoff=0,
                             activebackground="dim grey")
            my_menu_bar.add_cascade(label="Help", menu=help_menu)
            help_menu.add_command(label="Download FFMPEG",
                                  command=open_browser_for_ffmpeg)
            help_menu.add_separator()
            help_menu.add_command(label="About", command=openaboutwindow)
        # ------------------------------------------- The entire top bar/menu is only present during standalone version

        # Bundled Apps ------------------------------------------------------------------------------------------------
        config_file = 'Runtime/config.ini'  # Defines location of config.ini
        config = ConfigParser()
        config.read(config_file)

        # This creates the config file if on the standalone version ---------------------------------------------------
        if not combined_with_ffmpeg_audio_encoder:
            if not config.has_section(
                    'ffmpeg_path'):  # Create config parameters
                config.add_section('ffmpeg_path')
            if not config.has_option('ffmpeg_path', 'path'):
                config.set('ffmpeg_path', 'path', '')
            try:
                with open(config_file, 'w') as configfile:
                    config.write(configfile)
            except:
                messagebox.showinfo(
                    title='Error',
                    message=
                    'Could Not Write to config.ini file, delete and try again')
        # --------------------------------------------------- This creates the config file if on the standalone version

        # Define location of FFMPEG in a variable ---------------------------------------------------------------------
        ffmpeg = pathlib.Path(config['ffmpeg_path']['path'].replace('"', ''))
        # --------------------------------------------------------------------- Define location of FFMPEG in a variable

        # Code needed to add location of ffmpeg.exe in the event it's missing for standalone version ------------------
        if not combined_with_ffmpeg_audio_encoder:
            if not pathlib.Path(ffmpeg).is_file(
            ):  # Checks config for bundled app paths path ------------------------

                def check_ffmpeg(
                ):  # FFMPEG -------------------------------------------------------------------------
                    global ffmpeg
                    import shutil

                    def write_path_to_ffmpeg(
                    ):  # Writes path to ffmpeg to the config.ini file
                        try:
                            config.set('ffmpeg_path', 'path', ffmpeg)
                            with open(config_file, 'w') as configfile:
                                config.write(configfile)
                        except:
                            pass

                    if shutil.which('ffmpeg') is not None:
                        ffmpeg = str(pathlib.Path(
                            shutil.which('ffmpeg'))).lower()
                        messagebox.showinfo(
                            title='Prompt!',
                            message='ffmpeg.exe found on system PATH, '
                            'automatically setting path to location.\n\n'
                            'Note: This can be changed in the config.ini file'
                            ' or in the Options menu')
                        if pathlib.Path("Apps/ffmpeg/ffmpeg.exe").is_file():
                            rem_ffmpeg = messagebox.askyesno(
                                title='Delete Included ffmpeg?',
                                message=
                                'Would you like to delete the included FFMPEG?'
                            )
                            if rem_ffmpeg:
                                try:
                                    shutil.rmtree(
                                        str(pathlib.Path("Apps/ffmpeg")))
                                except:
                                    pass
                        write_path_to_ffmpeg()
                    elif pathlib.Path("Apps/ffmpeg/ffmpeg.exe").is_file():
                        messagebox.showinfo(
                            title='Info',
                            message='Program will use the included '
                            '"ffmpeg.exe" located in the "Apps" folder')
                        ffmpeg = str(pathlib.Path("Apps/ffmpeg/ffmpeg.exe"))
                        write_path_to_ffmpeg()
                    else:
                        error_prompt = messagebox.askyesno(
                            title='Error!',
                            message='Cannot find ffmpeg, '
                            'please navigate to "ffmpeg.exe"')
                        if not error_prompt:
                            messagebox.showerror(
                                title='Error!',
                                message=
                                'Program requires ffmpeg.exe to work correctly'
                            )
                            main.destroy()
                        if error_prompt:
                            set_ffmpeg_path()
                            if not pathlib.Path(ffmpeg).is_file():
                                messagebox.showerror(
                                    title='Error!',
                                    message=
                                    'Program requires ffmpeg.exe to work correctly'
                                )
                                main.destroy()

                check_ffmpeg(
                )  # FFMPEG ------------------------------------------------------------------------------
        # ------------------------------------------------------------------------------------------------ Bundled Apps
        # ------------------ Code needed to add location of ffmpeg.exe in the event it's missing for standalone version

        # Link Frame --------------------------------------------------------------------------------------------------
        link_frame = LabelFrame(main, text=' Paste Link ')
        link_frame.grid(row=0,
                        columnspan=4,
                        sticky=E + W,
                        padx=20,
                        pady=(10, 10))
        link_frame.configure(fg="white", bg="#434547", bd=3)

        link_frame.rowconfigure(1, weight=1)
        link_frame.columnconfigure(0, weight=1)
        link_frame.columnconfigure(1, weight=1)

        # -------------------------------------------------------------------------------------------------- Link Frame

        # Options Frame -----------------------------------------------------------------------------------------------
        options_frame = LabelFrame(main, text=' Options ')
        options_frame.grid(row=2,
                           columnspan=4,
                           sticky=E + W,
                           padx=20,
                           pady=(10, 10))
        options_frame.configure(fg="white", bg="#434547", bd=3)

        options_frame.rowconfigure(1, weight=1)
        options_frame.columnconfigure(0, weight=1)
        options_frame.columnconfigure(1, weight=1)

        # ----------------------------------------------------------------------------------------------- Options Frame

        # Input Frame -------------------------------------------------------------------------------------------------
        global link_input_label
        input_frame = LabelFrame(main, text=' Input ')
        input_frame.grid(row=1,
                         columnspan=4,
                         sticky=E + W,
                         padx=20,
                         pady=(4, 10))
        input_frame.configure(fg="white", bg="#434547", bd=3)
        input_frame.rowconfigure(1, weight=1)
        input_frame.columnconfigure(0, weight=1)
        input_frame.columnconfigure(1, weight=1)
        link_input_label = Label(
            input_frame,
            text='Please Paste Link Above and Select "Add Link"',
            background="#434547",
            foreground="white",
            height=1,
            font=("Helvetica", 10))
        link_input_label.grid(row=0,
                              column=0,
                              columnspan=4,
                              padx=8,
                              pady=(4, 7),
                              sticky=W + E)

        # ------------------------------------------------------------------------------------------------- Input Frame

        # File Output -------------------------------------------------------------------------------------------------
        def file_save():
            global VideoOutput
            save_entry.config(state=NORMAL)  #
            save_entry.delete(
                0, END
            )  # This function clears entry box in order to add new link to entry box
            save_entry.config(state=DISABLED)  #
            VideoOutput = filedialog.askdirectory(
                parent=main
            )  # Pop up window to choose a save directory location
            if VideoOutput:
                save_for_entry = '"' + VideoOutput + '/"'  # Completes save directory and adds quotes
                save_entry.config(state=NORMAL)  #
                save_entry.insert(
                    0, save_for_entry)  # Adds download_link to entry box
                save_entry.config(state=DISABLED)  #
                start_job_btn.config(state=NORMAL)  # Enables Button

        # ------------------------------------------------------------------------------------------------- File Output

        # Best Video Function -----------------------------------------------------------------------------------------
        def set_video_only():
            if video_only.get(
            ) == 'on':  # If video checkbutton is checked enable video options menu and set audio off
                highest_quality_audio_only.set('')
                video_menu_options_menu.config(state=NORMAL)
                audio_menu_options_menu.config(state=DISABLED)
                audio_menu_options.set('Extract Only')
            if video_only.get(
            ) != 'on':  # If not checked, set video_only to on
                video_only.set(
                    'on'
                )  # This prevents you from being able to de-select the check button

        # ----------------------------------------------------------------------------------------- Audio Only Function
        def highest_quality_audio_only_toggle():
            if highest_quality_audio_only.get(
            ) == 'on':  # If audio checkbutton is checked
                video_only.set(
                    '')  # enables video options menu and set audio to off
                video_menu_options_menu.config(state=DISABLED)
                audio_menu_options_menu.config(state=NORMAL)
            if highest_quality_audio_only.get(
            ) != 'on':  # If not checked, set audio_only to on
                highest_quality_audio_only.set(
                    'on'
                )  # This prevents you from being able to de-select the check button

        # Video Only Checkbutton --------------------------------------------------------------------------------------
        video_only = StringVar()
        video_only_checkbox = Checkbutton(
            options_frame,
            text='Best Video + Audio\nMuxed File',
            variable=video_only,
            onvalue='on',
            offvalue='',
            command=set_video_only,
            takefocus=False)
        video_only_checkbox.grid(row=0,
                                 column=1,
                                 columnspan=1,
                                 rowspan=1,
                                 padx=10,
                                 pady=6,
                                 sticky=N + S + E + W)
        video_only_checkbox.configure(background="#434547",
                                      foreground="white",
                                      activebackground="#434547",
                                      activeforeground="white",
                                      selectcolor="#434547",
                                      font=("Helvetica", 12))
        video_only.set('on')  # Enables Best Video by default

        # -------------------------------------------------------------------------------------- Video Only Checkbutton

        # Highest Quality Audio Only ----------------------------------------------------------------------------------
        highest_quality_audio_only = StringVar()
        highest_quality_audio_only_checkbox = Checkbutton(
            options_frame,
            text='Audio Only',
            variable=highest_quality_audio_only,
            onvalue='on',
            offvalue='',
            command=highest_quality_audio_only_toggle,
            takefocus=False)
        highest_quality_audio_only_checkbox.grid(row=0,
                                                 column=2,
                                                 columnspan=1,
                                                 rowspan=1,
                                                 padx=10,
                                                 pady=3,
                                                 sticky=N + S + E + W)
        highest_quality_audio_only_checkbox.configure(
            background="#434547",
            foreground="white",
            activebackground="#434547",
            activeforeground="white",
            selectcolor="#434547",
            font=("Helvetica", 12))
        highest_quality_audio_only.set('')  # Disables audio only by default

        # ---------------------------------------------------------------------------------- Highest Quality Audio Only

        # Download Rate -----------------------------------------------------------------------------------------------
        def download_rate_menu_hover(e):
            download_rate_menu["bg"] = "grey"
            download_rate_menu["activebackground"] = "grey"

        def download_rate_menu_hover_leave(e):
            download_rate_menu["bg"] = "#23272A"

        download_rate = StringVar(main)
        download_rate_choices = {
            'Unlimited': 131072000000000,
            '10 - KiB      (Slowest)': 1280,
            '50 - KiB': 6400,
            '100 - KiB': 12800,
            '250 - KiB': 32000,
            '500 - KiB': 64000,
            '750 - KiB': 96000,
            '1 - MiB': 131072,
            '5 - MiB': 655360,
            '10 - MiB': 1310720,
            '30 - MiB': 3932160,
            '50 - MiB': 6553600,
            '100 - MiB': 13107200,
            '250 - MiB': 32768000,
            '500 - MiB': 65536000,
            '750 - MiB': 98304000,
            '1000 - MiB  (Fastest)': 13107200000
        }
        download_rate_menu_label = Label(options_frame,
                                         text="Download Rate :",
                                         background="#434547",
                                         foreground="white")
        download_rate_menu_label.grid(row=0,
                                      column=0,
                                      columnspan=1,
                                      padx=10,
                                      pady=(3, 10),
                                      sticky=W + E)
        download_rate_menu = OptionMenu(options_frame, download_rate,
                                        *download_rate_choices.keys())
        download_rate_menu.config(background="#23272A",
                                  foreground="white",
                                  highlightthickness=1,
                                  width=15)
        download_rate_menu.grid(row=1,
                                column=0,
                                columnspan=1,
                                padx=10,
                                pady=(3, 20))
        download_rate.set('Unlimited')
        download_rate_menu["menu"].configure(activebackground="dim grey")
        download_rate_menu.bind("<Enter>", download_rate_menu_hover)
        download_rate_menu.bind("<Leave>", download_rate_menu_hover_leave)

        # ----------------------------------------------------------------------------------------------- Download Rate

        # Video Options -----------------------------------------------------------------------------------------------
        def video_menu_options_menu_hover(e):
            video_menu_options_menu["bg"] = "grey"
            video_menu_options_menu["activebackground"] = "grey"

        def video_menu_options_menu_hover_leave(e):
            video_menu_options_menu["bg"] = "#23272A"

        video_menu_options = StringVar(main)
        video_menu_options_choices = {
            '(bv+ba/b) Best video + audio format '
            'and combine both, or download best combined format':
            'bv+ba/b',
            '(Same as above with video up to 480p)':
            'bv*[height<=480]+ba/b[height<=480] / wv*+ba/w',
            '(Same as above with video up to 720p)':
            'bv*[height<=720]+ba/b[height<=720] / wv*+ba/w',
            '(Same as above with video up to 1080p)':
            'bv*[height<=1080]+ba/b[height<=1080] / wv*+ba/w',
            '(Same as above with video up to 1440p)':
            'bv*[height<=1440]+ba/b[height<=1440] / wv*+ba/w',
            '(Same as above with video up to 2160p)':
            'bv*[height<=2160]+ba/b[height<=2160] / wv*+ba/w',
            '(Default) (bv*+ba/b) Best video and if missing audio, '
            'merge it with best available audio':
            'bv*+ba/b',
            '(bv) Best video only':
            'bv',
            'Download the best h264 video, '
            'or best video if no such codec':
            '(bv * +ba / b)[vcodec ^= avc1] / (bv * +ba / b)'
        }
        video_menu_options_menu = OptionMenu(
            options_frame, video_menu_options,
            *video_menu_options_choices.keys())
        video_menu_options_menu.config(background="#23272A",
                                       foreground="white",
                                       highlightthickness=1,
                                       width=15,
                                       anchor=W)
        video_menu_options_menu.grid(row=1,
                                     column=1,
                                     columnspan=1,
                                     padx=10,
                                     pady=(3, 20))
        video_menu_options.set(
            '(Default) (bv*+ba/b) Best video and if missing audio, '
            'merge it with best available audio')
        video_menu_options_menu["menu"].configure(activebackground="dim grey")
        video_menu_options_menu.bind("<Enter>", video_menu_options_menu_hover)
        video_menu_options_menu.bind("<Leave>",
                                     video_menu_options_menu_hover_leave)

        # ----------------------------------------------------------------------------------------------- Video Options

        # Audio Options -----------------------------------------------------------------------------------------------
        def audio_menu_options_menu_hover(e):
            audio_menu_options_menu["bg"] = "grey"
            audio_menu_options_menu["activebackground"] = "grey"

        def audio_menu_options_menu_hover_leave(e):
            audio_menu_options_menu["bg"] = "#23272A"

        audio_menu_options = StringVar(main)
        audio_menu_options_choices = {
            'Extract Only': '',
            'Encode to mp3': 'mp3',
            'Encode to flac': 'flac',
            'Encode to m4a': 'm4a',
            'Encode to opus': 'opus',
            'Encode to vorbis': 'vorbis',
            'Encode to wav': 'wav'
        }
        audio_menu_options_menu = OptionMenu(
            options_frame, audio_menu_options,
            *audio_menu_options_choices.keys())
        audio_menu_options_menu.config(background="#23272A",
                                       foreground="white",
                                       highlightthickness=1,
                                       width=15,
                                       anchor=W,
                                       state=DISABLED)
        audio_menu_options_menu.grid(row=1,
                                     column=2,
                                     columnspan=1,
                                     padx=10,
                                     pady=(3, 20))
        audio_menu_options.set('Extract Only')
        audio_menu_options_menu["menu"].configure(activebackground="dim grey")
        audio_menu_options_menu.bind("<Enter>", audio_menu_options_menu_hover)
        audio_menu_options_menu.bind("<Leave>",
                                     audio_menu_options_menu_hover_leave)

        # ----------------------------------------------------------------------------------------------- Audio Options

        # Add Link to variable ----------------------------------------------------------------------------------------
        def apply_link():
            global download_link, link_input_label, extracted_title_name
            link_entry.config(state=NORMAL)  #
            link_entry.delete(
                0, END
            )  # This function clears entry box in order to add new link to entry box
            link_entry.config(state=DISABLED)  #
            download_link = text_area.get(1.0, END).rstrip(
                "\n")  # Pasted download link and strips the unneeded newline
            text_area.delete(
                1.0, END
            )  # Deletes entry box where you pasted your link as it stores it into var
            link_entry.config(state=NORMAL)  #
            link_entry.insert(0,
                              download_link)  # Adds download_link to entry box
            link_entry.config(state=DISABLED)  #
            save_btn.config(state=NORMAL)  #
            try:  # The code below checks link input for the title and adds it to a variable for use with the gui
                with yt_dlp.YoutubeDL({'noplaylist': True}) as ydl:
                    dl_link_input = ydl.extract_info(download_link,
                                                     download=False)
                    string_one = sub('[^a-zA-Z0-9 \n]', '',
                                     dl_link_input['title'])
                    string_two = " ".join(string_one.split())
                    extracted_title_name = pathlib.Path(
                        string_two[:128]).with_suffix('')
            except:
                extracted_title_name = download_link
            link_input_label.configure(text=extracted_title_name)

        # ---------------------------------------------------------------------------------------------------- Add Link

        # Start Job ---------------------------------------------------------------------------------------------------
        def start_job(
        ):  # This is the progress window and everything that has to do with actually processing the file
            global download_link

            def close_encode():
                confirm_exit = messagebox.askyesno(
                    title='Prompt',
                    message="Are you sure you want to stop progress?",
                    parent=window)
                if confirm_exit:  # If user selects 'Yes' to the above message prompt, destroy the window in question
                    window.destroy()

            def close_window(
            ):  # This thread is needed in order to close the window while the GUI is processing a file
                thread = threading.Thread(target=close_encode)
                thread.start()

            window = Toplevel(main)  # Programs download window
            window.title(
                extracted_title_name
            )  # Takes extracted_title_name and adds it as the windows title
            window.configure(background='#434547')
            encode_label = Label(window,
                                 text='- ' * 22 + 'Progress ' + '- ' * 22,
                                 font=('Times New Roman', 14),
                                 background='#434547',
                                 foreground='white')
            encode_label.grid(column=0, columnspan=2, row=0)
            window.grid_columnconfigure(0, weight=1)
            window.grid_rowconfigure(0, weight=1)
            window.grid_rowconfigure(1, weight=1)
            window.protocol('WM_DELETE_WINDOW', close_window)
            window.geometry('600x140')
            encode_window_progress = Text(window,
                                          height=2,
                                          relief=SUNKEN,
                                          bd=3)
            encode_window_progress.grid(row=1,
                                        column=0,
                                        columnspan=2,
                                        pady=(10, 6),
                                        padx=10,
                                        sticky=E + W)
            encode_window_progress.insert(END, '')
            app_progress_bar = ttk.Progressbar(window,
                                               orient=HORIZONTAL,
                                               mode='determinate')
            app_progress_bar.grid(row=2,
                                  columnspan=2,
                                  pady=(10, 10),
                                  padx=15,
                                  sticky=E + W)

            def my_hook(
                d
            ):  # This updates the progress bar with the correct percentage
                if d['status'] == 'downloading':
                    p = d['_percent_str']
                    p = p.replace('%', '')
                    app_progress_bar['value'] = float(p)

            class MyLogger:  # ytb-dl logger, allows the program to get all the needed info from the program
                global download_info_string

                def debug(self, msg):
                    # For compatability with youtube-dl, both debug and info are passed into debug
                    # You can distinguish them by the prefix '[debug] '
                    if msg.startswith('[debug] '):
                        pass
                    else:
                        self.info(msg)

                def info(self, msg):
                    encode_window_progress.delete('1.0', END)
                    encode_window_progress.insert(END, msg)

                def warning(self, msg):
                    pass

                def error(self, msg):
                    pass

            if video_only.get(
            ) == 'on':  # If "Best Video..." is selected then use these options for ytb-dl
                ydl_opts = {
                    'ratelimit': download_rate_choices[download_rate.get()],
                    'progress_hooks': [my_hook],
                    'noplaylist': True,
                    'overwrites': True,
                    'merge_output_format': 'mkv',
                    'final_ext': 'mkv',
                    'outtmpl':
                    str(pathlib.Path(VideoOutput)) + '/%(title)s.%(ext)s',
                    'ffmpeg_location': str(pathlib.Path(ffmpeg)),
                    'logger': MyLogger(),
                    "progress_with_newline": True,
                    'format':
                    video_menu_options_choices[video_menu_options.get()],
                    'prefer_ffmpeg': True
                }

            if video_only.get() != 'on' and audio_menu_options.get(
            ) == 'Extract Only':
                # If "Best Video..." is NOT selected and "Audio Menu" is set to Extract Only
                ydl_opts = {
                    'ratelimit': download_rate_choices[download_rate.get()],
                    'progress_hooks': [my_hook],
                    'noplaylist': True,
                    'overwrites': True,
                    'outtmpl':
                    str(pathlib.Path(VideoOutput)) + '/%(title)s.%(ext)s',
                    'ffmpeg_location': str(pathlib.Path(ffmpeg)),
                    'logger': MyLogger(),
                    "progress_with_newline": True,
                    'format': 'bestaudio/best',
                    'extractaudio': True,
                    'prefer_ffmpeg': True
                }

            if video_only.get() != 'on' and audio_menu_options.get(
            ) != 'Extract Only':
                # If "Best Video..." is NOT selected and "Audio Menu" is set to encode to another codec
                ydl_opts = {
                    'ratelimit':
                    download_rate_choices[download_rate.get()],
                    'progress_hooks': [my_hook],
                    'noplaylist':
                    True,
                    'overwrites':
                    True,
                    'outtmpl':
                    str(pathlib.Path(VideoOutput)) + '/%(title)s.%(ext)s',
                    'ffmpeg_location':
                    str(pathlib.Path(ffmpeg)),
                    'logger':
                    MyLogger(),
                    "progress_with_newline":
                    True,
                    'format':
                    'bestaudio/best',
                    'extractaudio':
                    True,
                    'prefer_ffmpeg':
                    True,
                    'postprocessors': [{
                        'key':
                        'FFmpegExtractAudio',
                        'preferredcodec':
                        audio_menu_options_choices[audio_menu_options.get()],
                        'preferredquality':
                        '0'
                    }]
                }

            with yt_dlp.YoutubeDL(
                    ydl_opts
            ) as ydl:  # Block of code needed to process the link/file
                ydl.download([download_link])

            window.destroy(
            )  # Once the job is complete this destroys the download/processing window

        # --------------------------------------------------------------------------------------------------- Start Job

        # Buttons and Entry Box's -------------------------------------------------------------------------------------
        text_area = scrolledtext.ScrolledText(link_frame,
                                              wrap=WORD,
                                              width=69,
                                              height=1,
                                              font=("Times New Roman", 14),
                                              foreground="grey")
        text_area.insert(END, "Right Click or 'Ctrl + V'")
        text_area.grid(row=0,
                       column=0,
                       columnspan=3,
                       pady=(1, 5),
                       padx=10,
                       sticky=W + E)

        # ------------------------------------------------------------------ Right click menu to paste in text_area box
        def paste_clipboard(
        ):  # Allows user to paste what ever is in their clipboard with right click and paste
            text_area.delete(1.0, END)
            text_area.config(foreground="black")
            text_area.insert(END, pyperclip.paste())

        def remove_text(
                e):  # Deletes current text in text box upon 'Left Clicking'
            text_area.config(foreground="black")
            text_area.delete(1.0, END)
            link_input_label.configure(
                text='Please Paste Link Above and Select "Add Link"')
            link_entry.config(state=NORMAL)  #
            link_entry.delete(
                0, END
            )  # This function clears entry box in order to add new link to entry box
            link_entry.config(state=DISABLED)  #

        m = Menu(main, tearoff=0)  # Pop up menu for 'Paste'
        m.add_command(label="Paste", command=paste_clipboard)

        def do_popup(
            event
        ):  # This code allows the program to know where the cursor is upon right clicking
            try:
                m.tk_popup(event.x_root, event.y_root)
            finally:
                m.grab_release()

        text_area.bind("<Button-3>",
                       do_popup)  # Uses right click to make a function
        text_area.bind("<Button-1>",
                       remove_text)  # Uses left click to make a function
        # Right click menu to paste in text_area box ------------------------------------------------------------------

        link_entry = Entry(link_frame,
                           borderwidth=4,
                           background="#CACACA",
                           state=DISABLED,
                           width=70)
        link_entry.grid(row=1,
                        column=1,
                        columnspan=2,
                        padx=10,
                        pady=(0, 0),
                        sticky=W + E)

        def apply_btn_hover(e):
            apply_btn["bg"] = "grey"

        def apply_btn_hover_leave(e):
            apply_btn["bg"] = "#8b0000"

        apply_btn = Button(link_frame,
                           text="Add Link",
                           command=apply_link,
                           foreground="white",
                           background="#8b0000",
                           width=30)
        apply_btn.grid(row=1,
                       column=0,
                       columnspan=1,
                       padx=10,
                       pady=5,
                       sticky=W)
        apply_btn.bind("<Enter>", apply_btn_hover)
        apply_btn.bind("<Leave>", apply_btn_hover_leave)

        def save_btn_hover(e):
            save_btn["bg"] = "grey"

        def save_btn_hover_leave(e):
            save_btn["bg"] = "#8b0000"

        save_btn = Button(main,
                          text="Save Directory",
                          command=file_save,
                          foreground="white",
                          background="#8b0000",
                          state=DISABLED)
        save_btn.grid(row=4,
                      column=0,
                      columnspan=1,
                      padx=10,
                      pady=(15, 0),
                      sticky=W + E)
        save_btn.bind("<Enter>", save_btn_hover)
        save_btn.bind("<Leave>", save_btn_hover_leave)

        save_entry = Entry(main,
                           borderwidth=4,
                           background="#CACACA",
                           state=DISABLED)
        save_entry.grid(row=4,
                        column=1,
                        columnspan=3,
                        padx=10,
                        pady=(15, 0),
                        sticky=W + E)

        def start_job_btn_hover(e):
            start_job_btn["bg"] = "grey"

        def start_job_btn_hover_leave(e):
            start_job_btn["bg"] = "#8b0000"

        start_job_btn = Button(
            main,
            text="Start Job",
            command=lambda: threading.Thread(target=start_job).start(),
            foreground="white",
            background="#8b0000",
            state=DISABLED)
        start_job_btn.grid(row=5,
                           column=3,
                           columnspan=1,
                           padx=10,
                           pady=(15, 15),
                           sticky=N + S + W + E)
        start_job_btn.bind("<Enter>", start_job_btn_hover)
        start_job_btn.bind("<Leave>", start_job_btn_hover_leave)

        # ------------------------------------------------------------------------------------- Buttons and Entry Box's

        # End Loop ----------------------------------------------------------------------------------------------------
        main.mainloop()
Beispiel #24
0
class FilePick(Frame):
    def __init__(self, master, file_mask, default_file, user_onChange = None, font = None, dirs = (".", ), allowNone = False):
        """ file_mask: file mask or list of file masks """
        self.master = master
        self.user_onChange = user_onChange
        Frame.__init__(self, master)
        self.columnconfigure(0, weight=1)
        self.unmodified = True
        self.file_extension = ""
        if "." in file_mask:
            self.file_extension = file_mask[file_mask.rfind('.'):]
        if type(file_mask) != list:
            file_mask = [file_mask]
        self.file_masks = file_mask
        self.allowNone = allowNone
        self.dirs = dirs
        # create list of files
        self.updateList()
        # pick default if applicable
        self.set(default_file)

    def onSelChange(self, name, index=0, mode=0):
        filename = self.picked_name.get()
        if self.user_onChange != None:
            self.user_onChange(filename)

    def updateList(self):
        prev_sel = self.get()
        # get list of files (paths)
        self.files = []
        if self.allowNone:
            self.files.append("")
        for fm in self.file_masks:
            for dir in self.dirs:
                try:
                    for filename in os.listdir(dir):
                        if fnmatch(filename, fm):
                            if dir != ".":
                                path = os.path.join(dir, filename)
                            else:
                                path = filename
                            self.files.append(path)
                except:
                    pass
        self.files.sort()
        if len(self.files) == 0: self.files.append("(no %s files found)" %  self.file_masks)
        # create list object
        self._makelist()
        # reselect
        self.set(prev_sel)

    def getList(self):
        """ returns the current list of files """
        return self.files

    def _makelist(self):
        if havePMW:
            self.list = ComboBox(self,
                    selectioncommand = self.onSelChange,
                    scrolledlist_items = self.files,
            )
            self.list.grid(row=0, column=0, padx=0, sticky="NEWS")
            self.list.component('entryfield').component('entry').configure(state = 'readonly', relief = 'raised')
            self.picked_name = self.list
        else:
            self.picked_name = StringVar()
            self.list = OptionMenu(*(self, self.picked_name) + tuple(self.files))
            self.list.grid(row=0, column=0, sticky="NEW")
            self.picked_name.trace("w", self.onSelChange)

    def set(self, filename):
        default_file = filename
        if default_file in self.files:
            if not havePMW:
                self.picked_name.set(default_file) # default value
            else:
                self.list.selectitem(self.files.index(default_file))
                self.onSelChange(default_file)
                pass

    def get(self):
        if not hasattr(self, 'picked_name'):
            return None
        return self.picked_name.get()
Beispiel #25
0
class Example(Frame):

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

        self.parent = parent
        self.initUI()

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


        self.quitbutton = Button(self, text="Quit", command= lambda: self.quit())

        self.quitbutton.grid(row=3, column=1, pady=4)

        self.labelErrorPointer = Label(self, text="◀")

        self.labellist = []
        self.entrylist = []
        self.verifylist = []
        self.misclist = []
                
        self.optionCreate = "Create"
        self.optionUpcoming = "Upcoming"
        self.optionPast = "Past"

        self.prevmode = self.optionCreate
        self.curmode = self.optionCreate
        self.optionvar = tkinter.StringVar(self)
        self.optionvar.trace("w",self.permaloop)
        self.optionvar.set(self.optionCreate)
        self.option = OptionMenu(self, self.optionvar, self.optionCreate, self.optionUpcoming, self.optionPast)

        self.optionpostmodevar = tkinter.StringVar(self)
        self.optionpostmodevar.trace("w",self.permaloop)
        self.optionpostmodevar.set('url')
        self.optionpostmode = OptionMenu(self, self.optionpostmodevar, 'url', 'text')

        self.labelText = Label(self, text='Selftext:')
        self.entryText = Text(self)
        self.labelURL = Label(self, text='URL:')
        self.entryURL = Entry(self)
        self.entryURL.configure(width=60)  

        self.sql = sqlite3.connect('sql.db')
        print('Loaded SQL Database')
        self.cur = self.sql.cursor()

        self.cur.execute('CREATE TABLE IF NOT EXISTS upcoming(ID TEXT, SUBREDDIT TEXT, TIME INT, TITLE TEXT, URL TEXT, BODY TEXT)')
        self.cur.execute('CREATE TABLE IF NOT EXISTS past(ID TEXT, SUBREDDIT TEXT, TIME INT, TITLE TEXT, URL TEXT, BODY TEXT, POSTLINK TEXT)')
        self.cur.execute('CREATE TABLE IF NOT EXISTS internal(NAME TEXT, ID INT)')
        print('Loaded Completed table')
        self.cur.execute('SELECT * FROM internal')
        f = self.cur.fetchone()
        if not f:
            print('Database is new. Adding ID counter')
            self.cur.execute('INSERT INTO internal VALUES(?, ?)', ['counter', 1])
            self.idcounter = 1
        else:
            self.idcounter = f[1]
            print('Current ID counter: ' + str(self.idcounter))

        self.sql.commit()
        

        
        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()


        w=853
        h=480
        x = (sw - w) / 2
        y = (sh - h) / 2

        self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y-50))

        self.login()
        

    def login(self):

        try:
            self.quitbutton.grid_forget()
            self.quitbutton.grid(row=9000, column=0, columnspan=20)          

            self.option.grid(row=1,column=0,columnspan=80,pady=8)

            self.updategui(fullclean=True)
        except praw.errors.InvalidUserPass:
            pass
            print('Invalid username or password')
            self.entryPassword.delete(0,200)
            self.labelErrorPointer.grid(row=1, column=2)

    def permaloop(self, *args):
        self.curmode = self.optionvar.get()
        print('Was: ' + self.prevmode + ' | Now: ' + self.curmode)
        if self.curmode != self.prevmode:
            self.prevmode = self.curmode
            self.updategui(fullclean=True)
        else:
            self.updategui(False)

    def getTime(self, bool):
        timeNow = datetime.datetime.now(datetime.timezone.utc)
        timeUnix = timeNow.timestamp()
        if bool is False:
            return timeNow
        else:
            return timeUnix

    def addentrytobase(self, subreddit, title, url="", body="", mode="", ptime=""):
        curtime = round(self.getTime(True))
        try:
            t = self.entryMo.get() + ' ' + self.entryDa.get() + ' ' + self.entryYr.get() + ' ' + self.entryHH.get() + ':' + self.entryMM.get()
            plandate = datetime.datetime.strptime(t, "%B %d %Y %H:%M")
            plandate = plandate.timestamp()
        except ValueError:
            print('Invalid Day')
            return False

        if mode == 'url':
            url = self.entryURL.get()
            body = ""
            if 'http://' not in url and 'https://' not in url:
                print('Please enter a proper URL')
                return False
        if mode == 'text':
            body = self.entryText.get("1.0", "end")
            url = ""

        if plandate < curtime:
            print('Please enter a time in the future')
            return False

        if not all(char in string.ascii_letters+string.digits+'_-' for char in subreddit):
            print('Subreddit contains invalid characters')
            return False

        if len(subreddit) == 0:
            print('You must enter a subreddit')
            return False

        if len(title) == 0:
            print('You must enter a title')
            return False
        if len(title) > 300:
            print('Title is too long. ' + str(len(title)) + '/300 char max')
            return False
        if len(body) > 15000:
            print('Body is too long. ' + str(len(body)) + '/15,000 char max')

        print('Timestamp:', plandate)
        self.cur.execute('INSERT INTO upcoming VALUES(?, ?, ?, ?, ?, ?)', [self.idcounter, subreddit, int(plandate), title, url, body])
        self.idcounter += 1
        self.cur.execute('UPDATE internal SET ID=? WHERE NAME=?', [self.idcounter, 'counter'])
        self.sql.commit()
        print('\nPost Saved!')
        print(self.idcounter, subreddit, self.timestamptoday(int(plandate)))
        print(title)
        print(url, body)
        print()
        self.entryText.delete("1.0", "end")
        self.entryURL.delete(0, 'end')
        self.entryTitle.delete(0, 'end')
        #self.updategui(halfclean=True)

    def timestamptoday(self, timestamp):
        d = datetime.datetime.fromtimestamp(timestamp)
        info = datetime.datetime.strftime(d, "%b %d %H:%M")
        return info


    def dropentryfrombase(self, ID):
        if '-' not in ID:
            try:
                ID = int(ID)
                l = [ID]
            except ValueError:
                print('You must enter a number')
                return
        else:
            if ID.count('-') == 1:
                try:
                    ID = ID.replace(' ', '')
                    ID = ID.split('-')
                    ID[0] = int(ID[0])
                    ID[1] = int(ID[1])
                    if ID[1] > ID[0]:
                        l = list(range(ID[0], ID[1]+1))
                    else:
                        return
                except ValueError:
                    return

        for item in l:
            item = str(item)
            print('Dropping Item ' + item + ' from Upcoming')
            self.cur.execute('DELETE FROM upcoming WHERE ID=?', [item])
            self.sql.commit()
        self.updategui(fullclean=True)

    def printbasetofile(self, db):
        filea = open(db + '.txt', 'w')
        if db == 'past':
            self.cur.execute('SELECT * FROM past')
        if db == 'upcoming':
            self.cur.execute('SELECT * FROM upcoming')
        f = self.cur.fetchall()
        print('Printed ' + db + ' unimpeded to file')
        for item in f:
            i = list(item)
            i[2] = self.timestamptoday(i[2])
            i.remove('')

            print(str(i)[1:-1], file=filea)
        filea.close()

        


    def updategui(self, halfclean=False, fullclean=False):

        if self.curmode == self.optionCreate:
            try:
                print(self.optionpostmodevar.get())

                if self.optionpostmodevar.get() == 'url':
                    self.entryText.delete("1.0", 'end')
                    self.labelText.grid_forget()
                    self.entryText.grid_forget()
    
                    self.labelURL.grid(row=8, column=0, columnspan=30)
                    self.entryURL.grid(row=9, column=0, columnspan=12, pady=10)
    
                if self.optionpostmodevar.get() == 'text':
                    self.entryURL.delete(0, 'end')
                    self.labelURL.grid_forget()
                    self.entryURL.grid_forget()
    
                    self.labelText.grid(row=8, column=0, columnspan=30)
                    self.entryText.configure(width=40, height=8)
                    self.entryText.grid(row=9, column=0, columnspan=12)
            except AttributeError:
                pass

        if fullclean is True:
            print('Cleaning GUI')
            for item in self.labellist:
                item.grid_forget()
            for item in self.entrylist:
                item.grid_forget()
            for item in self.verifylist:
                item.grid_forget()
            for item in self.misclist:
                item.grid_forget()
            self.labellist = []
            self.entrylist = []
            self.verifylist = []
            self.misclist = []

            if self.curmode == self.optionCreate:
                self.newrowindex = 6
                self.labelSubreddit = Label(self, text="Subreddit:    /r/")
                self.labelTitle = Label(self, text="Post title:  ")
                self.entrySubreddit = Entry(self)
                self.entryTitle = Entry(self)


                self.labelHH = Label(self, text="Schedule time (Local timezone):")
                nowlist = datetime.datetime.strftime(datetime.datetime.now(), "%B %d %Y %H %M").split()

                self.entryMo = Spinbox(self, width=9, values=('January', 'February', 'March', 'April', 'May', 'June', 'July', \
                    'August', 'September', 'October', 'November', 'December'))
                self.entryMo.delete(0,'end')
                self.entryMo.insert(0, nowlist[0])


                self.entryDa = Spinbox(self, width=2, from_=1, to=31)
                self.entryDa.delete(0,'end')
                self.entryDa.insert(0, nowlist[1])

                self.entryYr = Spinbox(self, width=4, from_=2014, to=2500)
                self.entryYr.delete(0,'end')
                self.entryYr.insert(0, nowlist[2])

                self.entryHH = Spinbox(self, from_=0, to=23, width=2)
                self.entryHH.delete(0,'end')
                self.entryHH.insert(0, nowlist[3])

                self.entryMM = Spinbox(self, from_=0, to=59, width=2)
                self.entryMM.delete(0,'end')
                self.entryMM.insert(0, nowlist[4])

                self.buttonAddentry = Button(self, text='Save', command=lambda: self.addentrytobase(self.entrySubreddit.get(), self.entryTitle.get(),\
                    mode=self.optionpostmodevar.get()))


                self.misclist.append(self.labelSubreddit)
                self.misclist.append(self.entrySubreddit)
                self.misclist.append(self.labelHH)
                self.misclist.append(self.entryHH)
                self.misclist.append(self.entryMM)
                self.misclist.append(self.entryMo)
                self.misclist.append(self.entryDa)
                self.misclist.append(self.entryYr)
                self.misclist.append(self.labelTitle)
                self.misclist.append(self.entryTitle)
                self.misclist.append(self.buttonAddentry)
                self.misclist.append(self.optionpostmode)
                self.misclist.append(self.labelText)
                self.misclist.append(self.entryText)
                self.misclist.append(self.labelURL)
                self.misclist.append(self.entryURL)

                self.labelSubreddit.grid(row=2, column=0, sticky="e")
                self.labelTitle.grid(row=3, column=0, sticky="e")
                self.entrySubreddit.grid(row=2, column=1, columnspan=3, sticky="w")
                self.entryTitle.grid(row=3, column=1, columnspan=3, sticky="w")
                self.entryMo.grid(row=4, column=1,sticky="e")
                self.entryDa.grid(row=4, column=2)
                self.entryYr.grid(row=4, column=3)
                self.labelHH.grid(row=4, column=0, sticky="se", pady=5)
                self.entryHH.grid(row=5, column=1, sticky="e")
                self.entryMM.grid(row=5, column=2, sticky="w")
                self.optionpostmode.grid(row=6, column=0, columnspan=20, pady=10)
                self.buttonAddentry.grid(row=200, column=0, columnspan=20)

            if self.curmode == self.optionUpcoming:
                self.cur.execute('SELECT * FROM upcoming')
                dobutton = True

            if self.curmode == self.optionPast:
                self.cur.execute('SELECT * FROM past')
                dobutton = False

            if self.curmode == self.optionPast or self.curmode == self.optionUpcoming:

                
                self.listboxId = Listbox(self)
                self.listboxId.configure(width=118, height=20, font=("Courier 8"))
                self.misclist.append(self.listboxId)

                self.listboxScroller = Scrollbar(self, orient='horizontal', command=self.listboxId.xview)
                self.listboxScroller.grid(row=4, column=0, columnspan=900)
                self.listboxId.grid(row=3, column=0, columnspan=10)

                self.listboxId.configure(xscrollcommand=self.listboxScroller.set)
                self.misclist.append(self.listboxScroller)

                self.buttonPrinter = Button(self, text="Print to .txt file")
                if self.curmode == self.optionPast:
                    self.buttonPrinter.configure(command=lambda: self.printbasetofile('past'))
                if self.curmode == self.optionUpcoming:
                    self.buttonPrinter.configure(command=lambda: self.printbasetofile('upcoming'))   

                self.buttonPrinter.grid(row = 6, column=0, columnspan=90)
                self.misclist.append(self.buttonPrinter)

                if dobutton is True:
                    self.entryDelete = Entry(self)
                    self.buttonDelete = Button(self, text="Delete Item: ", command=lambda: self.dropentryfrombase(self.entryDelete.get()))
                    self.buttonDelete.grid(row=5, column=0, sticky='e')
                    self.entryDelete.grid(row=5, column=1, sticky='w')
                    self.misclist.append(self.entryDelete)
                    self.misclist.append(self.buttonDelete)


                fetched = self.cur.fetchall()
                for item in fetched:

                    info = self.timestamptoday(item[2])

                    if item[4] == '':
                        infx = item[5]
                    if item[5] == '':
                        infx = item[4]
                    if self.curmode == self.optionPast:
                        infy = '.' + item[6]
                    else:
                        infy = ''

                    self.listboxId.insert('end', \
                        item[0] + '.'*(6 - len(item[0])) \
                        + item[1][:10] + '.'*(12 - len(item[1][:10])) \
                        + info + '.'*(15 - len(info[:14])) \
                        + item[3][:18] + '.'*(20 - len(item[3][:14])) \
                        + infx[:45] + '.'*(47-len(infx[:45])) \
                        + infy)

                    
                



    def morerows(self, label, columnm, columnn, limit, *args):
        self.redditlabel = Label(self,text=label)
        self.redditlabel.grid(row=self.newrowindex,column=columnm, sticky="e")
        self.labellist.append(self.redditlabel)

        self.redditentry = Entry(self)
        self.redditentry.grid(row=self.newrowindex,column=columnn, columnspan=9)
        self.entrylist.append(self.redditentry)

        self.newrowindex += 1
        if self.newrowindex >= limit:
            self.morerowbutton.grid_forget()
        print(self.newrowindex)
Beispiel #26
0
class DropdownList:
    def __init__(self, master, filemask='*.mln', default=None, allowNone=False, onselchange=None, directory='.'):
        self.allowNone = allowNone
        self.directory = directory
        self.list_frame = master
        self.onchange = onselchange
        if type(filemask) != list:
            filemask = [filemask]
        self.file_mask = filemask
        self.updateList()
        if havePMW:
            self.list = ComboBox(master, selectioncommand=onselchange, scrolledlist_items = self.files)
            self.list.component('entryfield').component('entry').configure(state = 'readonly', relief = 'raised')
            self.picked_name = self.list
        else:
            self.picked_name = StringVar()
            self.list = OptionMenu(*(master, self.picked_name) + tuple(self.files))
            if onselchange is not None:
                self.picked_name.trace("w", self.onchange)
        if default is not None:
            self.select(default)
        else:
            self.select(self.files[0])


    def __getattr__(self, name):
        return getattr(self.list, name)


    def get(self):
        return self.picked_name.get()


    def select(self, item):
        if item in self.files:
            if not havePMW:
                self.picked_name.set(item)
            else:
                self.list.selectitem(item)


    def updateList(self):
        self.files = []
        if self.allowNone:
            self.files.append("")
        if os.path.exists(self.directory):
            for filename in os.listdir(self.directory):
                for fm in self.file_mask:
                    if fnmatch(filename, fm):
                        self.files.append(filename)
        self.files.sort()
        if len(self.files) == 0 and not self.allowNone: self.files.append("(no %s files found)" % str(self.file_mask))



    def makelist(self):
        if havePMW:
            self.list = ComboBox(self.list_frame,
                    selectioncommand = self.onSelChange,
                    scrolledlist_items = self.files,
            )
            self.list.grid(row=0, column=0, padx=0, pady=0, sticky="NEWS")
            self.list.component('entryfield').component('entry').configure(state = 'readonly', relief = 'raised')
            self.picked_name = self.list
        else:
            self.list = OptionMenu(*(self.list_frame, self.picked_name) + tuple(self.files))
            self.list.grid(row=0, column=0, sticky="NEW")
            self.picked_name.trace("w", self.onSelChange)
        self.select(self.files[0])

    def setDirectory(self, directory, keep=False):
        self.directory = directory
        self.updateList()
        self.makelist()
        # if keep is true, only the files list will be updated but the content of the
        # text area will not be altered/removed
        if not keep: self.select("")


    def onSelChange(self, name, index=0, mode=0):
        filename = self.picked_name.get()
        if self.onchange != None:
            self.onchange(filename)
Beispiel #27
0
    def __init__(self, pipepanel, pipeline_name, *args, **kwargs):
        PipelineFrame.__init__(self, pipepanel, pipeline_name, *args, **kwargs)
        self.info = None

        eframe = self.eframe = LabelFrame(self, text="Options")
        #,fg=textLightColor,bg=baseColor)
        eframe.grid(row=5, column=1, sticky=W, columnspan=7, padx=10, pady=5)

        label = Label(eframe,
                      text="Pipeline")  #,fg=textLightColor,bg=baseColor)
        label.grid(row=3, column=0, sticky=W, padx=10, pady=5)
        PipelineLabels = [
            "CellRanger", "Initial/QC", "Clustering", "Multi-Sample Clustering"
        ]
        Pipelines = [
            "cellranger", "scrnaseqinit", "scrnaseqcluster",
            "scrnaseqmulticluster"
        ]

        self.label2pipeline = {k: v for k, v in zip(PipelineLabels, Pipelines)}

        PipelineLabel = self.PipelineLabel = StringVar()
        self.Pipeline = StringVar()

        PipelineLabel.set(PipelineLabels[0])
        om = OptionMenu(eframe,
                        PipelineLabel,
                        *PipelineLabels,
                        command=self.option_controller)
        om.config()  #bg = widgetBgColor,fg=widgetFgColor)
        om["menu"].config()  #bg = widgetBgColor,fg=widgetFgColor)
        #om.pack(side=LEFT,padx=20,pady=5)
        om.grid(row=3, column=1, sticky=W, padx=10, pady=5)

        self.crOpts = crOpts = LabelFrame(eframe, text="CellRanger Settings")
        self.scrCRID = scrCRID = StringVar()
        scrCRID.set("SPECIFY_PREFIX_HERE")
        self.scrExpected = scrExpected = StringVar()
        scrExpected.set("3000")

        scrcridL = Label(crOpts, text="CellRanger Sample ID: ")
        scrcridE = Entry(crOpts, bd=2, width=25, textvariable=scrCRID)
        scrcridL.grid(row=9, column=1, sticky=W, padx=10, pady=5)
        scrcridE.grid(row=9, column=2, sticky=W, padx=0, pady=5)

        screxpectedL = Label(crOpts, text="Expected number of cells: ")
        screxpectedE = Entry(crOpts, bd=2, width=8, textvariable=scrExpected)
        screxpectedL.grid(row=10, column=1, sticky=W, padx=10, pady=5)
        screxpectedE.grid(row=10, column=2, sticky=W, padx=0, pady=5)

        self.clusterOpts = clusterOpts = LabelFrame(
            eframe, text="Clustering and tSNE Options")

        self.scrPCs = scrPCs = StringVar()
        scrPCs.set("12")
        self.scrRes = scrRes = StringVar()
        scrRes.set("0.6")

        #scrPCs.trace('w', lambda a,b,c,x="scrPCs": makejson(x))

        #Filter out genes < [5] read counts in < [2] samples
        scrpcsL = Label(clusterOpts,
                        text="Include principal components 1 through ")
        scrpcsE = Entry(clusterOpts, bd=2, width=3, textvariable=scrPCs)
        scrresL = Label(clusterOpts, text="with clustering resolution: ")
        scrresE = Entry(clusterOpts, bd=2, width=3, textvariable=scrRes)

        scrpcsL.grid(row=9, column=1, sticky=W, padx=10, pady=5)
        scrpcsE.grid(row=9, column=2, sticky=W, padx=0, pady=5)
        scrresL.grid(row=9, column=3, sticky=W, padx=5, pady=5)
        scrresE.grid(row=9, column=4, sticky=W, padx=0, pady=5)
        #scrRes.trace('w', lambda a,b,c,x="scrPCs": makejson(x))

        clusterOpts.grid(row=8,
                         column=0,
                         columnspan=4,
                         sticky=W,
                         padx=20,
                         pady=10)

        self.multiclusterOpts = multiclusterOpts = LabelFrame(
            eframe, text="Multi-Sample Clustering and tSNE Options")

        scrccsL = Label(multiclusterOpts,
                        text="Include canonical components 1 through ")
        scrccsE = Entry(multiclusterOpts, bd=2, width=3, textvariable=scrPCs)
        scrmcresL = Label(multiclusterOpts,
                          text="with clustering resolution: ")
        scrmcresE = Entry(multiclusterOpts, bd=2, width=3, textvariable=scrRes)

        scrccsL.grid(row=9, column=1, sticky=W, padx=10, pady=5)
        scrccsE.grid(row=9, column=2, sticky=W, padx=0, pady=5)
        scrmcresL.grid(row=9, column=3, sticky=W, padx=5, pady=5)
        scrmcresE.grid(row=9, column=4, sticky=W, padx=0, pady=5)

        self.qcOpts = qcOpts = LabelFrame(eframe, text="Initial Settings")
        countL = Label(qcOpts, text="Counts/Matrix Dir:")
        countL.grid(row=9, column=1, sticky=W, padx=10, pady=5)
        countpath = StringVar()
        self.countpath = countpath
        count_entry = Entry(
            qcOpts,
            bd=2,
            width=50,
            #bg = entryBgColor,
            #fg = entryFgColor,
            textvariable=countpath,
            state='normal')
        count_entry.grid(row=9, column=2, columnspan=3)
        self.count_button = count_button = Button(
            qcOpts, text="Open Directory", command=self.set_count_directory)
        count_button.grid(row=9, column=5)

        self.mattype = mattype = StringVar()
        mattypeL = Label(qcOpts, text="Count matrix format: ")
        scrMatTypeDropdown = ["cellranger", "cellranger_raw", "zumi", "biorad"]
        mattype.set(scrMatTypeDropdown[0])
        mattype_om = OptionMenu(qcOpts, mattype, *scrMatTypeDropdown)
        mattypeL.grid(row=10, column=1, sticky=W, padx=10, pady=5)
        mattype_om.grid(row=10, column=2, sticky=W, padx=0, pady=5)

        self.docycleregress = docycleregress = StringVar()
        docycleregressL = Label(qcOpts, text="Do cell cycle regression? ")
        scrCycleDropdown = ["TRUE", "FALSE"]
        docycleregress.set(scrCycleDropdown[0])
        cycle_om = OptionMenu(qcOpts, docycleregress, *scrCycleDropdown)
        docycleregressL.grid(row=11, column=1, sticky=W, padx=10, pady=5)
        cycle_om.grid(row=11, column=2, sticky=W, padx=0, pady=5)

        usecycleregressL_c = Label(clusterOpts,
                                   text="Use cell cycle regressed data? ")
        docycleregress.set(scrCycleDropdown[0])
        cycle_om_c = OptionMenu(clusterOpts, docycleregress, *scrCycleDropdown)
        usecycleregressL_c.grid(row=10, column=1, sticky=W, padx=10, pady=5)
        cycle_om_c.grid(row=10, column=2, sticky=W, padx=0, pady=5)

        usecycleregressL_mc = Label(multiclusterOpts,
                                    text="Use cell cycle regressed data? ")
        docycleregress.set(scrCycleDropdown[0])
        cycle_om_mc = OptionMenu(multiclusterOpts, docycleregress,
                                 *scrCycleDropdown)
        usecycleregressL_mc.grid(row=10, column=1, sticky=W, padx=10, pady=5)
        cycle_om_mc.grid(row=10, column=2, sticky=W, padx=0, pady=5)

        groups_buttonL = Label(qcOpts, text="SAMPLE INFORMATION: ")
        groups_button = Button(qcOpts,
                               text="Set Groups",
                               command=self.popup_groups)
        groups_buttonL.grid(row=12, column=1, sticky=W, padx=10, pady=5)
        groups_button.grid(row=12, column=2, sticky=W, padx=0, pady=5)
        #####################

        self.option_controller()
Beispiel #28
0
    def __init__(self, master, queue, scrape_url):
        self.queue = queue

        # ACTION:

        def form_setup():  # function to combin form setup
            form.iconbitmap('Wave_inputs/wave_ico.ico')  # Assign icon
            form.title("Betfair Wave")  # Assign window titly

        form_setup()  # run form setup

        # Define parent tab
        tab_parent = ttk.Notebook(form)

        # ------------------- Bet overview tab
        # init constants
        rw = 1

        # Define tabs existence
        global bet_overview
        bet_overview = ttk.Frame(tab_parent)

        def tab_overview_setup():
            tab_parent.add(bet_overview, text="Overview")

        tab_overview_setup()  # run tab setup

        # & Bet link text

        def bet_overview_static_text():
            Label(bet_overview,
                  text="Betfair Sportsbook URL: ").grid(row=1,
                                                        column=1,
                                                        columnspan=1)
            Label(bet_overview, text="Strategy: ").grid(row=2,
                                                        column=1,
                                                        columnspan=1)
            Label(bet_overview, text="TIme period (s): ").grid(row=3,
                                                               column=1,
                                                               columnspan=1)

        bet_overview_static_text()  # call static text

        # & Bet URL input
        global bet_url_entry
        bet_url_entry = tk.Entry(bet_overview, width=70)
        bet_url_entry.grid(row=rw, column=3, columnspan=7, sticky="W")
        bet_url_entry.insert(END,
                             "https://www.betfair.com/exchange/plus/football")

        # Strategy drop down menu
        OPTIONS = []
        import os
        for file in os.listdir():
            if file.startswith("strategy"):
                file = file.replace(".py", "")
                OPTIONS.append(file)

        global strategyoptions
        strategyoptions = StringVar(bet_overview)
        strategyoptions.set(OPTIONS[1])  # default value

        w = OptionMenu(bet_overview, strategyoptions, *OPTIONS)
        w.grid(row=2, column=3, columnspan=1)

        # Timer drop down menu
        timeoptions = [60, 600, 6000, 60000]

        global timeoption
        timeoption = StringVar(bet_overview)
        timeoption.set(timeoptions[3])  # default value

        w = OptionMenu(bet_overview, timeoption, *timeoptions)
        w.grid(row=3, column=3, columnspan=1)

        #w.pack()

        # & Start button

        start_btn_scrape = tk.Button(bet_overview,
                                     text="Start",
                                     command=scrape_url,
                                     width=15)
        start_btn_scrape.grid(row=rw, column=10, sticky="W")

        # ------------------- Settings
        # init constants
        srw = 1

        # -------- Define tabs existence
        settings = ttk.Frame(tab_parent)

        def tab_settings_setup():
            tab_parent.add(settings, text="Settings")

        tab_settings_setup()  # run tab setup

        # Lift tkinter to front
        var1 = IntVar()

        def on_top_func():
            if var1.get() == 1:
                form.lift()
                form.call('wm', 'attributes', '.', '-topmost', '1')
            else:
                form.call('wm', 'attributes', '.', '-topmost', '0')

        Checkbutton(settings,
                    text="Window always visible",
                    variable=var1,
                    command=on_top_func).grid(row=srw,
                                              sticky="W",
                                              columnspan=3)

        # Add text
        def settings_static_text():
            Label(settings, text="Back Bet Value:").grid(row=2,
                                                         column=1,
                                                         sticky="W")
            Label(settings, text="Lay Bet Value:").grid(row=3,
                                                        column=1,
                                                        sticky="W")

        settings_static_text()  # call static text

        # Lay bet entry
        lay_bet_value = tk.Entry(settings, width=20)
        lay_bet_value.grid(row=2, column=2, sticky="W")
        lay_bet_value.insert(END, "2")

        # Lay bet entry
        lay_bet_value = tk.Entry(settings, width=20)
        lay_bet_value.grid(row=3, column=2, sticky="W")
        lay_bet_value.insert(END, "2")

        # unpack tabs
        tab_parent.pack(expand=1, fill="both")
class PlotterWindow():
    def __init__(self, master):

        # Tkinter parts
        self.master = master
        self.master.title("Live Serial Plotter")
        self.master.resizable(False, False)  # Prevent resizing

        # Serial parts
        self.ser = None
        self.IS_SERIAL_CONNECTED = False
        self.serial_data = [[0 for i in range(MAXINPUTS)]
                            for i in range(NPOINTS)]
        self.serial_plotline = []

        # Figure
        self.f1 = plt.figure(figsize=PLOTRATIO, dpi=PLOTDPI)
        self.a1 = self.f1.add_subplot(111)
        self.a1.grid()
        self.a1.set_title("Serial Values")
        self.a1.set_xticklabels([])
        self.canvas1 = FigureCanvasTkAgg(self.f1, master)
        self.canvas1.get_tk_widget().grid(row=0,
                                          column=0,
                                          columnspan=6,
                                          pady=20)

        # Labels
        self.npointslabel = Label(master, text='# Points')
        self.npointslabel.grid(row=1, column=0, sticky='W')

        self.baudratelabel = Label(master, text="Baud Rate")
        self.baudratelabel.grid(row=2, column=0, sticky='W')

        self.portlabel = Label(master, text='Serial Port')
        self.portlabel.grid(row=3, column=0, sticky='W')

        self.serialconnectedstringvar = StringVar(master, value='Unconnected')
        self.serialconnectedlabel = Label(
            master, textvar=self.serialconnectedstringvar, fg='red', width=15)
        self.serialconnectedlabel.grid(row=1, column=3)

        self.numinputslabel = Label(master, text="# Inputs")
        self.numinputslabel.grid(row=4, column=0, sticky='W')

        self.currentvallabel = Label(master, text="Most recent:")
        self.currentvallabel.grid(row=1, column=5)

        self.currentvalstringvar = StringVar(master, value='None')
        self.currentval = Label(master, textvar=self.currentvalstringvar)
        self.currentval.grid(row=2, column=5)

        self.packageindicator = StringVar(master, value='!')
        self.packageindicatorlabel = Label(master,
                                           textvar=self.packageindicator,
                                           font=('times', 20, 'bold'))
        self.packageindicatorlabel.grid(row=4, column=5)
        self.packageindicator.set(".")

        # OptionMenu lists
        _npoints_list = [10, 25, 50, 75, 100, 250, 500, 750,
                         1000]  # Desired points
        npoints_list = [str(x) for x in _npoints_list
                        ]  # Converting each of these to a string
        available_ports = FindAllSerialPorts()

        if len(available_ports
               ) == 0:  # If there are no available ports, print a warning
            tprint("> Warning: no available ports!")
            available_ports.append('None')

        _baud_rates = [
            110, 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 38400, 57600,
            115200, 128000, 256000
        ]
        baud_rates = [str(x) for x in _baud_rates]
        input_num_options = [str(x) for x in range(1, MAXINPUTS + 1)]

        plotmethods = ['Markers only', 'Line only',
                       'Both']  # Various ways to display the plotted values

        # StringVars
        self.npointsentrystr = StringVar(master, value="250")
        self.baudrateentrystr = StringVar(master, value="115200")
        self.portentrystr = StringVar(master, value=available_ports[-1])
        self.plotmethodentrystr = StringVar(master, value=plotmethods[1])
        self.numinputsentrystr = StringVar(master, value="1")

        # Using OptionMenu instead:
        self.plotmethodoptionmenu = OptionMenu(master, self.plotmethodentrystr,
                                               *plotmethods)
        self.plotmethodoptionmenu.grid(row=4, column=2)

        self.npointsoptionmenu = OptionMenu(master, self.npointsentrystr,
                                            *npoints_list)
        self.npointsoptionmenu.grid(row=1, column=1, sticky='W')

        self.baudrateoptionmenu = OptionMenu(master, self.baudrateentrystr,
                                             *baud_rates)
        self.baudrateoptionmenu.grid(row=2, column=1, sticky='W')

        self.portoptionmenu = OptionMenu(master, self.portentrystr,
                                         *available_ports)
        self.portoptionmenu.width = 20
        self.portoptionmenu.grid(row=3, column=1, sticky='W')

        self.numinputsoptionmenu = OptionMenu(master, self.numinputsentrystr,
                                              *input_num_options)
        self.numinputsoptionmenu.grid(row=4, column=1, sticky='W')

        # Buttons
        self.show_x_axis = IntVar(master, value=0)
        self.showxaxischeckbutton = Checkbutton(master,
                                                text='Show y=0',
                                                variable=self.show_x_axis,
                                                onvalue=1,
                                                offvalue=0)
        self.showxaxischeckbutton.grid(row=1, column=2)

        self.connectbutton = Button(master,
                                    text='Connect',
                                    command=self.ConnectToSerial)
        self.connectbutton.grid(row=2, column=3)

        self.disconnectbutton = Button(master,
                                       text='Disconnect',
                                       command=self.DisconnectFromSerial)
        self.disconnectbutton.grid(row=3, column=3)

        self.refreshserialbutton = Button(master,
                                          text='Refresh Ports',
                                          command=self.RefreshSerial)
        self.refreshserialbutton.grid(row=3, column=2)

        self.exportdatabutton = Button(master,
                                       text='Export',
                                       command=self.ExportData)
        self.exportdatabutton.grid(row=4, column=3)

        self.printrawdata = IntVar(master, value=0)
        self.printrawbutton = Checkbutton(master,
                                          text='Print raw data',
                                          variable=self.printrawdata,
                                          onvalue=1,
                                          offvalue=0)
        self.printrawbutton.grid(row=2, column=2)

        self.requirebrackets = IntVar(master, value=1)
        self.requirebracketsbutton = Checkbutton(master,
                                                 text='Require brackets',
                                                 variable=self.requirebrackets,
                                                 onvalue=1,
                                                 offvalue=0)
        self.requirebracketsbutton.grid(row=3, column=5)
        # =====================================================================

    # =========================================================================
    # Runs the main loop for Tk().
    def mainloop(self):
        self.master.mainloop()
        return

    # =========================================================================

    # =========================================================================
    # Connects GUI to a COM port based on the user selected port.
    def ConnectToSerial(self):
        try:
            port = self.portentrystr.get()
            baudrate = int(self.baudrateentrystr.get())
            tprint("> Trying to connect to %s at %d" % (port, baudrate))
            self.ser = serial.Serial(port, baudrate, timeout=0.1)
            self.ser.flushInput()
        except:
            tprint("> Error")
            self.ToggleSerialConnectedLabel(False)
            return -1

        tprint("> Success.")
        self.IS_SERIAL_CONNECTED = True  # Set GUI state
        self.ToggleSerialConnectedLabel(True)  # Show the state
        self.GetSerialValue()  # Begin the GetSerialValue() loop
        return

    # =========================================================================

    # =========================================================================
    # Disconnects from whatever serial port is currently active.
    def DisconnectFromSerial(self):
        if self.IS_SERIAL_CONNECTED:  # Only do this if already connected.
            self.ser.close()
            self.ToggleSerialConnectedLabel(False)
            self.IS_SERIAL_CONNECTED = False
        return

    # =========================================================================

    # =========================================================================
    # Refreshes the list of available serial ports on the option menu.
    def RefreshSerial(self):
        new_serial_list = FindAllSerialPorts()

        tprint("> Refreshing serial port list")
        if len(new_serial_list) == 0:
            tprint("> No available serial ports.")
            return

        self.portentrystr.set(new_serial_list[-1])  # Set the variable to none
        self.portoptionmenu['menu'].delete(0, 'end')  # Delete the old list

        for port in new_serial_list:  # Refresh:
            self.portoptionmenu['menu'].add_command(label=port,
                                                    command=_setit(
                                                        self.portentrystr,
                                                        port))
        return

    # =========================================================================

    # =========================================================================
    # Exports the data to a file associated with the current date and time.
    def ExportData(self):
        timestamp = datetime.datetime.now().strftime('%y%m%d_%H%M%S')
        outfname = 'SessionLogs/SerialSessionLog_%s.csv' % (timestamp)
        try:
            hit_data_start = False
            f = open(outfname, 'w')
            for sd in self.serial_data:

                # Check if we have data yet, don't start appending until that point
                if not hit_data_start:
                    if not any(sd):
                        continue  # Skip to the next data point if all values are zeros
                    else:
                        hit_data_start = True

                wstr = ''
                for d in sd:
                    wstr += '%f,' % (d)
                wstr = wstr[:-1] + '\n'
                f.write(wstr)
            f.close()
            tprint("> Successfully exported to %s" % (outfname))
        except:
            tprint("> Error: Unable to export data")
        return

    # =========================================================================

    # =========================================================================
    # Changes the "good data received" indicator.
    def SetPackageIndicator(self, state):
        if state == 'good':
            self.packageindicator.set("!")
            self.packageindicatorlabel.config(fg='green',
                                              font=('times', 20, 'bold'))
        else:
            self.packageindicator.set('.')
            self.packageindicatorlabel.config(fg='black',
                                              font=('times', 20, 'bold'))
        return

    # =========================================================================

    # =========================================================================
    # Gets the most recent serial value from connection. IMPORTANT.
    def GetSerialValue(self):
        if not self.IS_SERIAL_CONNECTED:
            tprint("> No connection")
            return

        try:
            # Read data
            rawdata = self.ser.readline().decode('utf8')
            if rawdata != '':
                self.currentvalstringvar.set(str(rawdata[:-1]))
            self.ser.flushInput()  # Clear this out to avoid garbage data
            self.ser.flushOutput()  # Clear this out to avoid garbage data

            # Parse data
            x_nonewline = rawdata[:-1]  # Ignore the trailing newline
            if self.printrawdata.get():  # Print the raw data, if desired
                print(x_nonewline)

            if self.requirebrackets.get():
                if ">" in x_nonewline and "<" in x_nonewline:
                    x = x_nonewline[1:-2]
                    try:
                        npoints = int(self.npointsentrystr.get())
                        x_split = x.split(' ')
                        # Make sure that every data package is the same length, so it's not a sequence
                        senddata = []
                        for i in range(MAXINPUTS):
                            try:
                                senddata.append(float(x_split[i]))
                            except:
                                senddata.append(
                                    self.serial_data[-1]
                                    [i])  # Append the most recent value

                        self.serial_data.append(senddata)
                        self.serial_data = self.serial_data[1:]
                        self.serial_plotline = self.serial_data[-npoints:]

                        # Set the blinker indicator to green!
                        self.SetPackageIndicator('good')

                        self.master.after_idle(
                            self.Plotline)  # Once everything's done, plot it!
                    except ValueError:
                        tprint(
                            "> Invalid serial value: Non-floating point detected: %s"
                            % (x))

                else:
                    self.SetPackageIndicator('bad')
            else:
                x = x_nonewline
                try:
                    npoints = int(self.npointsentrystr.get())
                    x_split = x.split(' ')
                    # Make sure that every data package is the same length, so it's not a sequence
                    senddata = []
                    for i in range(MAXINPUTS):
                        try:
                            senddata.append(float(x_split[i]))
                        except:
                            senddata.append(
                                self.serial_data[-1]
                                [i])  # Append the most recent value

                    self.serial_data.append(senddata)
                    self.serial_data = self.serial_data[1:]
                    self.serial_plotline = self.serial_data[-npoints:]
                    self.master.after_idle(self.Plotline)
                except ValueError:
                    tprint(
                        "> Invalid serial value: Non-floating point detected: %s"
                        % (x))

        except Exception as e:
            tprint("> Error in GetSerialValue()", e)

        self.master.after(
            TIMEDELAY,
            self.GetSerialValue)  # Do it all again: Here's making it the loop
        return

    # =========================================================================

    # =========================================================================
    # Plots the data to the GUI's plot window.
    def Plotline(self):
        numpoints = int(self.npointsentrystr.get())
        numinputs = int(self.numinputsentrystr.get())

        if self.plotmethodentrystr.get() == 'Markers only':
            plotmethod = '.'
        elif self.plotmethodentrystr.get() == 'Line only':
            plotmethod = '-'
        else:
            plotmethod = '.-'
        self.a1.clear()

        for i in range(numinputs):  # Plot each line individually
            plotline = [x[i] for x in self.serial_plotline]
            self.a1.plot(plotline, plotmethod, label=str(i))

        self.a1.grid()
        if self.show_x_axis.get():
            self.a1.set_ylim(0, 1.125 * np.amax(np.array(self.serial_data)))

        # Plot formatting parameters
        ticklabels = np.linspace(numpoints / 10, 0, 5)
        self.a1.set(xticks=np.linspace(0, numpoints, 5),
                    xticklabels=ticklabels)
        self.a1.set_xticklabels([])
        self.a1.set_ylabel("Serial Value")
        self.a1.legend(loc=3)
        self.a1.set_title("Serial Values")

        self.canvas1.draw()  # Actually update the GUI's canvas object
        return

    # =========================================================================

    # =========================================================================
    # Swap out the string label indicating whether serial is connected.
    def ToggleSerialConnectedLabel(self, connection):
        if connection:
            self.serialconnectedstringvar.set('Connected')
            self.serialconnectedlabel.config(fg='green')
        else:
            self.serialconnectedstringvar.set('Unconnected')
            self.serialconnectedlabel.config(fg='red')
        return
Beispiel #30
0
    def popup_window_contrast(self):
        text = "Comparing ChIP-seq Peaks"
        contrast_fn = join(self.workpath.get(), self.contrast_fn)
        peakinfo_fn = join(self.workpath.get(), self.peakinfo_fn)
        NA = 'N/A'

        try:
            groups = list(
                set([
                    l.split('\t')[-1].strip() for l in open(peakinfo_fn)
                    if l.split('\t')[-1].strip()
                ]))
            if len(groups) < 2:
                showwarning(
                    'WARNING!',
                    "More than one groups need to be fefined in Peak Information File!"
                )
                print('groups:', groups)
                return

        except IOError:
            showerror('Error', "Did you set peak information?")
            print('Error:', 'Cannot process peakcall.tab file:')
            return

        top = Toplevel()
        info = LabelFrame(top, text=text)  #"Group Information")

        print(groups)
        contrast_vars = []
        contrast_menus = []
        n = 0
        groups.insert(0, NA)
        for i in range(int((len(groups) - 1) * (len(groups) - 2) / 2)):
            n = n + 1
            v1, v2 = StringVar(), StringVar()
            contrast_vars.append([v1, v2])
            o1, o2 = OptionMenu(info, v1,
                                *groups), OptionMenu(info, v2, *groups)
            contrast_menus.append([o1, o2])

            v1.set(NA)
            v2.set(NA)
            vslabel = Label(info, text="  VS  ")

            o1.grid(row=n, column=0, padx=4, pady=1)
            o2.grid(row=n, column=2, padx=4, pady=1)
            vslabel.grid(row=n, column=1, padx=4, pady=1)

        def savefunc():
            info_text = StringIO()
            for v1, v2 in contrast_vars:
                v1 = v1.get() if v1.get() != NA else ""
                v2 = v2.get() if v2.get() != NA else ""

                if v1 and v2:
                    pass
                elif v1 or v2:
                    showerror('Error',
                              "None or Both columns should be selected!")
                    return
                else:
                    continue

                print(v1, v2, file=info_text, sep="\t")

            fp = open(contrast_fn, 'w')
            fp.write(info_text.getvalue())
            fp.close()

        def loadfunc():
            #self.readpaste( filename, info_text )
            for i, l in enumerate(open(contrast_fn)):
                v1, v2 = l.split('\t')
                v1 = v1.strip()
                v2 = v2.strip()

                if v1:
                    try:
                        assert v1 in groups
                    except:
                        showwarning(
                            'WARNING',
                            'Group name is not in the selection list!')
                        print('v1:', v1)
                        print('group:', groups)
                        continue

                if v2:
                    try:
                        assert v2 in groups
                    except:
                        showwarning(
                            'WARNING',
                            'Group name is not in the selection list!')
                        print('v2:', v2)
                        print('group:', groups)
                        continue

                contrast_vars[i][0].set(v1)
                contrast_vars[i][1].set(v2)

        def clearfunc():
            for v1, v2 in contrast_vars:
                v1.set(NA)
                v2.set(NA)

        info_clear_button = Button(top, text="Clear", command=clearfunc)
        info_save_button = Button(top, text="Save", command=savefunc)
        info_load_button = Button(top, text="Load", command=loadfunc)

        #self.pairs_load_button.pack( side=BOTTOM, padx=5, pady=5 )
        #self.pairs_save_button.pack( side=BOTTOM, padx=5, pady=5 )

        info_clear_button.grid(row=5, column=3, padx=10, pady=5)
        info_load_button.grid(row=5, column=4, padx=10, pady=5)
        info_save_button.grid(row=5, column=5, padx=10, pady=5)

        info.grid(row=7, column=0, columnspan=6, sticky=W, padx=20, pady=10)
        top.focus_force()
Beispiel #31
0
lbl_MaxC.place(x=37.5, y=143)
txt_MinR.place(x=178, y=7)
txt_MaxR.place(x=178, y=35)
txt_MinL.place(x=178, y=63)
txt_MaxL.place(x=178, y=91)
txt_MinC.place(x=178, y=119)
txt_MaxC.place(x=178, y=147)

lbl_Gain.place(x=27, y=3)
lbl_VSWR.place(x=45.5, y=31)
lbl_Z0.place(x=36, y=59)
txt_Gain.place(x=178, y=7)
txt_VSWR.place(x=178, y=35)
txt_Z0.place(x=178, y=63)

opt_Optimizer.grid(row=0, column=0, sticky="E")
opt_Optimizer.place(x=8, y=2)

lbl_Display.place(x=64, y=3)
lbl_MaxFunEval.place(x=51, y=31)
lbl_MaxIter.place(x=59.5, y=59)
lbl_TolFun.place(x=63.2, y=87)
lbl_FminconAlgo.place(x=85, y=115)

opt_fminconDisplay.place(x=176, y=2)
txt_MaxFunEval.place(x=178, y=35)
txt_MaxIter.place(x=178, y=63)
txt_TolFun.place(x=178, y=91)
opt_fminconAlgorithm.place(x=176, y=115)

antennaGeometry.grid_propagate(0)
Beispiel #32
0
def select_season_club_and_home_arena() -> Tuple[int, str, str]:
    """
    show UI for selection of season, club and home arena
    @return: tuple with season, club name and home arena
    """
    selectable_seasons: List[int] = [
        datetime.now().year - 1,
        datetime.now().year,
        datetime.now().year + 1
    ]

    root = Tk()
    root.title("Select season, club and home arena")
    root.geometry("375x120")
    root.columnconfigure(0, weight=1)
    root.columnconfigure(1, weight=1)

    season_variable = StringVar(root)
    club_variable = StringVar(root)
    home_arena_variable = StringVar(root)

    season_label = tkinter.Label(root, text="Season:")
    season_label.grid(row=1, column=0, sticky="w")

    season_option_menu = OptionMenu(root, season_variable, *selectable_seasons)
    season_option_menu.grid(row=1, column=1, sticky="nsew")

    def on_select_season(*args):  # pylint: disable=unused-argument
        """
        callback to be executed on season selection
        @param args:
        """
        clubs = load_clubs(season_variable.get())

        club_label = tkinter.Label(root, text="Club:")
        club_label.grid(row=2, column=0, sticky="w")
        club_option_menu = OptionMenu(root, club_variable, *clubs)
        club_option_menu.grid(row=2, column=1, sticky="nsew")

    season_variable.trace('w', on_select_season)

    def on_select_club(*args):  # pylint: disable=unused-argument
        """
        callback to be executed on club selection
        @param args:
        """
        selected_season = season_variable.get()
        clubs = load_clubs(selected_season)
        club_id = clubs[club_variable.get()]
        arena_names = load_arena_names(club_id, selected_season)

        home_arena_label = tkinter.Label(root, text="Home arena:")
        home_arena_label.grid(row=3, column=0, sticky="w")
        home_arena_option_menu = OptionMenu(root, home_arena_variable,
                                            *arena_names)
        home_arena_option_menu.grid(row=3, column=1, sticky="nsew")

    club_variable.trace('w', on_select_club)

    def on_select_home_arena(*args):  # pylint: disable=unused-argument
        """
        callback to be executed on home arena selection
        @param args:
        """
        root.quit()

    home_arena_variable.trace('w', on_select_home_arena)

    root.mainloop()

    return season_variable.get(), club_variable.get(), home_arena_variable.get(
    )
Beispiel #33
0
class Frontend:
    def __init__(self, master, event):
        self.master = master
        self.event = event
        self.opciones_de_puerto = ['-']
        operatingSystem = platform.system()
        if operatingSystem == 'Windows':
            release = platform.release()
            if release == '7':
                windll.user32.SetProcessDPIAware(1)  # Windows 7 y vista
            elif release == '10' or '8':
                windll.shcore.SetProcessDpiAwareness(1)  # Windows 10 y 8

        self.master.title("GUI: Gimbal 2DOF")
        rootWidth = int(screenWidth * 0.4)
        rootHeight = int(screenHeight * 0.8)
        posWidth = (screenWidth - rootWidth) // 2
        posHeight = (screenHeight - rootHeight) // 2
        self.master.geometry(
            f"{rootWidth}x{rootHeight}+{posWidth}+{posHeight}")
        # TODO: CREACIÓN DE WIDGETS:
        # ------------------------------------------ PLOT1
        self.plot1_label_frame = LabelFrame(self.master,
                                            text='Variables reguladas',
                                            font=font_h1,
                                            fg='#267eb5')
        # ------------------------------------------ PLOT2
        self.plot2_label_frame = LabelFrame(self.master,
                                            text='Acciones de control',
                                            font=font_h1,
                                            fg='#267eb5')
        # ------------------------------------------ BOTÓN
        self.style_button = Style()
        self.style_button.configure('style_button.TButton',
                                    foreground='#267eb5',
                                    font=font_h2,
                                    relief="flat",
                                    background="#ccc")
        # ------------------------------------------ CONFIGURACION
        self.frame_config = Frame(self.master)
        self.conectar_button = Button(
            self.frame_config,
            text='Conectar',
            style='style_button.TButton',
            command=lambda: event_queue.put('CONECTAR'))
        self.puerto_seleccionado = StringVar()
        self.puerto_seleccionado.set('Puertos')
        self.puertos_optionMenu = OptionMenu(self.frame_config,
                                             self.puerto_seleccionado,
                                             *self.opciones_de_puerto)

        # TODO: MAQUETADO DE WIDGETS:
        self.plot1_label_frame.pack(fill='both',
                                    expand=1,
                                    anchor='center',
                                    padx=10,
                                    pady=(10, 5))
        self.plot2_label_frame.pack(fill='both',
                                    expand=1,
                                    anchor='center',
                                    padx=10,
                                    pady=(5, 10))
        self.frame_config.pack(padx=5, pady=(5, 10))
        self.conectar_button.grid(row=0, column=0)
        self.puertos_optionMenu.grid(row=0, column=1)

    def crearPuerto(self, puerto):
        print('puerto CREADO')
        menu = self.puertos_optionMenu['menu']
        menu.add_command(
            label=puerto,
            command=lambda puerto=puerto: self.puerto_seleccionado.set(puerto))

    def eliminarPuerto(self, puerto):
        print('puerto ELIMINADO')
        menu = self.puertos_optionMenu['menu']
        last = menu.index("end")
        items = []
        for index in range(last + 1):
            items.append(menu.entrycget(index, "label"))
        pos = items.index(puerto)
        menu.delete(pos)
Beispiel #34
0
class ObjFormatter:
    """ The main widget """
    def __init__(self, root):
        #
        if MY_OS == 'Windows':
            imgpad = 155
            xpadd = 5
            ypadd = 5
            basefont = 10
            entryfont = 11
            buttonpad = 202
        elif MY_OS == 'Linux':
            imgpad = 170
            xpadd = 5
            ypadd = 5
            basefont = 12
            entryfont = 14
            buttonpad = 210
        else:
            imgpad = 190
            xpadd = 5
            ypadd = 5
            basefont = 14
            entryfont = 16
            buttonpad = 210
        #
        # Main widget background image
        frame0 = Frame(root)
        logoimgpath = resource_path("UPackLogo300.jpg")
        logo = Image.open(logoimgpath)
        self.logoimage = ImageTk.PhotoImage(logo)
        self.logoimglabel = Label(frame0, image=self.logoimage)
        self.logoimglabel.configure(bg='black', bd=0, relief='flat')
        self.logoimglabel.grid(column=0,
                               row=0,
                               pady=7,
                               padx=imgpad,
                               sticky='e')
        frame0.configure(bg=hokiestone, bd=5, relief='sunken')
        frame0.grid(column=0, row=0, pady=0, padx=0, sticky='nsew')
        # Entry for the Folder that contains the items
        frame1 = Frame(root)
        itemfolder = StringVar(frame1)
        labl1 = Label(frame1, text='Folder of\nItems:')
        labl1.configure(fg='black',
                        bg=vtgray,
                        bd=0,
                        font=('Arial', basefont),
                        height=2,
                        width=9,
                        justify='center')
        labl1.grid(column=0, row=0, pady=5, padx=5, sticky='e')
        browse1 = Button(frame1,
                         text='Browse',
                         command=lambda: self.ask_folder(itemfolder))
        browse1.configure(bg=vtsmoke,
                          fg='black',
                          highlightbackground=vtmaroon,
                          font=('Arial', entryfont))
        browse1.grid(column=2, row=0, pady=5, padx=5, sticky='w')
        self.e1 = Entry(frame1, width=50, textvariable=itemfolder)
        self.e1.configure(bg=vtsmoke,
                          relief='sunken',
                          bd=2,
                          font=('Arial', entryfont + 2),
                          justify='left')
        self.e1.grid(column=1, row=0, pady=5, padx=0, sticky='w')
        # Entry for the master CSV metadata file
        csvfile = StringVar(frame1)
        labl2 = Label(frame1, text='CSV File:')
        labl2.configure(fg='black',
                        bg=vtgray,
                        bd=0,
                        font=('Arial', basefont),
                        height=2,
                        width=9,
                        justify='center')
        labl2.grid(column=0, row=1, pady=5, padx=5, sticky='e')
        browse2 = Button(frame1,
                         text='Browse',
                         command=lambda: self.ask_file(csvfile))
        browse2.configure(bg=vtsmoke,
                          fg='black',
                          highlightbackground=vtmaroon,
                          font=('Arial', entryfont),
                          relief='raised')
        browse2.grid(column=2, row=1, pady=5, padx=5, sticky='w')
        self.e2 = Entry(frame1, width=50, textvariable=csvfile)
        self.e2.configure(bg=vtsmoke,
                          relief='sunken',
                          bd=2,
                          font=('Arial', entryfont + 2),
                          justify='left')
        self.e2.grid(column=1, row=1, pady=5, padx=0, sticky='w')
        # Drop-Down of the column headings in the master CSV file
        labl3 = Label(frame1, text='CSV Col.\nw/ ID\'s:')
        labl3.configure(fg='black',
                        bg=vtgray,
                        bd=0,
                        font=('Arial', basefont),
                        height=2,
                        width=9,
                        justify='center')
        labl3.grid(column=0, row=2, pady=5, padx=5, sticky='e')
        self.variable = StringVar(frame1)
        self.options = StringVar(frame1)
        self.options.trace('r', self.get_headers)
        firstone = ["Select CSV", "Then \'Refresh\'"]
        self.hdmenu = OptionMenu(frame1, self.variable, *firstone)
        self.hdmenu.configure(width=20,
                              bg=vtmaroon,
                              font=('Arial', basefont + 2))
        self.hdmenu.grid(column=1, row=2, pady=5, padx=0, sticky='e')
        self.e3 = Entry(frame1, width=24, textvariable=self.variable)
        self.e3.configure(bg=vtsmoke,
                          relief='sunken',
                          bd=2,
                          font=('Arial', entryfont + 2),
                          justify='left')
        self.e3.grid(column=1, row=2, pady=5, padx=0, sticky='w')
        refresh1 = Button(frame1,
                          text='Refresh',
                          command=lambda: self.get_headers(csvfile))
        refresh1.configure(bg=vtsmoke,
                           fg='black',
                           highlightbackground=vtmaroon,
                           font=('Arial', entryfont))
        refresh1.grid(column=2, row=2, pady=5, padx=5, sticky='w')
        frame1.configure(bg=vtmaroon, bd=5, relief='raised')
        frame1.grid(column=0, row=1, pady=0, padx=0, sticky='nsew')
        # Checkbuttons
        frame2 = ToggleFrame(root)
        frame2.configure(bg=hokiestone, bd=5, relief='sunken')
        frame2.grid(column=0, row=2, pady=0, padx=0, sticky='n')
        # Buttons for Quit, Instructions, and Submit
        frame3 = Frame(root)
        cancel1 = Button(frame3, text='Quit', command=root.quit)
        cancel1.configure(bg=vtwhite,
                          fg='black',
                          highlightbackground=vtmaroon,
                          font=('Arial', entryfont))
        cancel1.grid(column=0, row=0, pady=5, padx=xpadd, sticky='e')
        instruct = Button(frame3,
                          text='Instructions',
                          command=lambda: instructions(basefont))
        instruct.configure(bg=vtwhite,
                           fg='black',
                           highlightbackground=vtmaroon,
                           font=('Arial', entryfont))
        instruct.grid(column=1, row=0, pady=5, padx=buttonpad, sticky='e')
        submit1 = Button(frame3,
                         text='Submit',
                         command=lambda: self.run_procs(root, frame2))
        submit1.configure(bg=vtwhite,
                          fg='black',
                          highlightbackground=vtmaroon,
                          font=('Arial', entryfont))
        submit1.grid(column=2, row=0, pady=5, padx=xpadd, sticky='e')
        frame3.configure(bg=vtmaroon, bd=5, relief='raised')
        frame3.grid(column=0, row=3, pady=0, padx=0, sticky='nsew')

    def ask_folder(self, foname):
        foname.set(
            path.abspath(
                askdirectory(initialdir=getcwd(), title='Select the Folder')))
        return foname

    def ask_file(self, fname):
        fname.set(
            path.abspath(
                askopenfilename(initialdir=getcwd(),
                                title='Select the master CSV File')))
        return fname

    def get_headers(self, *args):
        """ Retrieves the options for the drop-down menu of CSV headers """
        csvfi = self.e2.get()
        csvpath = path.join(str(csvfi))
        if path.exists(csvpath) and path.splitext(csvpath)[1] == '.csv':
            with open(csvfi, 'r', encoding='utf-8') as cfile:
                hreader = csv.DictReader(cfile)
                opts = hreader.fieldnames
        else:
            opts = ["Select CSV", "Then \'Refresh\'"]
        self.variable.set(opts[0])
        menu = self.hdmenu['menu']
        menu.delete(0, 'end')
        for headr in opts:
            menu.add_command(
                label=headr,
                command=lambda idcolumn=headr: self.variable.set(idcolumn))

    def make_rdf(self, metacsv):
        """
        Turns 'metadata.csv' into an RDF metadata file, called 'metadata.xml'
        This could be done using a CSV-to-XML conversion, but it's easier to
        just read the values for the fields and write the RDF file manually.
        """
        if not path.exists(metacsv):
            messagebox.showwarning(
                message=
                "Error: The \'metadata.csv\' was not found.\nRDF file not created."
            )
            return False
        with open(metacsv, 'r', encoding='utf-8') as src:
            reader2 = csv.DictReader(src)
            headrow2 = reader2.fieldnames
            for row in reader2:
                sysUUID = str(row['System UUID'])
                localID = str(row['Local ID'])
                deptName = str(row['Department Responsible'])
                persVTID = str(row['Person Responsible'])
                collName = str(row['Collection'])
                description = str(row['Brief Description'])
                objURI = str(row['Object URI'])
                collURI = str(row['Collection URI'])
        src.close()
        # messagebox.showwarning(message="It got this far! Next step is create the Graph.")
        g = Graph()
        # Namespaces
        rdf = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#")
        g.bind('rdf', rdf, False)
        rdfs = Namespace("http://www.w3.org/2000/01/rdf-schema#")
        g.bind('rdfs', rdfs, False)
        dc = Namespace("http://dublincore.org/2012/06/14/dcelements.rdf#")
        g.bind('dc', dc, False)
        dcterms = Namespace("http://purl.org/dc/terms#")
        g.bind('dcterms', dcterms, False)
        dcmitype = Namespace("http://purl.org/dc/dcmitype#")
        g.bind('dcmitype', dcmitype, False)
        foaf = Namespace("http://xmlns.com/foaf/spec/index.rdf#")
        g.bind('foaf', foaf, False)
        owl = Namespace("http://www.w3.org/2002/07/owl#")
        g.bind('owl', owl, False)
        premis = Namespace("http://www.loc.gov/premis/rdf/v3#")
        g.bind('premis', premis, False)
        mets = Namespace("http://www.loc.gov/standards/mets/mets.xsd#")
        g.bind('mets', mets, False)
        # Establishing subjects for triples
        object = URIRef(objURI)
        persID = BNode()
        g.bind('personID', persID, False)
        deptID = BNode()
        g.bind('departmentID', deptID, False)
        collectID = URIRef(collURI)
        g.bind('collectionID', collectID, False)
        metsCustodian = URIRef(
            'http://www.loc.gov/standards/mets/mets.xsd#CUSTODIAN')
        g.bind('custodian', metsCustodian, False)
        # Adding the triples to the Graph
        g.add((object, dcterms.identifier, Literal('%s' % sysUUID)))
        g.add((object, mets.OBJID, Literal('%s' % sysUUID)))
        g.add((object, mets.altRecordID, Literal('%s' % localID)))
        g.add((object, dc.contributor, deptID))
        g.add((deptID, rdf.type, foaf.Group))
        g.add((deptID, mets.ROLE, metsCustodian))
        g.add((deptID, foaf.name, Literal('%s' % deptName)))
        g.add((object, dc.contributor, persID))
        g.add((persID, rdf.type, foaf.Person))
        g.add((persID, mets.ROLE, metsCustodian))
        g.add((persID, foaf.mbox, Literal('%s (at) vt (dot) edu' % persVTID)))
        # g.add((persID, foaf.name, Literal('%s' %persName)))
        g.add((object, dcterms.isPartOf, collectID))
        g.add((collectID, foaf.name, Literal('%s' % collName)))
        g.add((object, dcterms.description, Literal('%s' % description)))
        newrdf = path.join(path.dirname(metacsv), 'metadata.xml')
        serialrdf = g.serialize(format='pretty-xml')
        # serialjson = g.serialize(format='json-ld')
        with open(newrdf, 'wb') as outrdf:
            outrdf.write(serialrdf)
        outrdf.close()
        # jsonfile = path.join(path.dirname(metacsv), 'metadata.json')
        # with open(jsonfile, 'w', encoding='utf-8') as outjson:
        #     outjson.write(serialjson)
        # outjson.close()
        return True

    def meta_from_csv(self, csvIn, locids, fpath):
        nfiles = 0
        rfiles = 0
        overwrite_all = False
        firstone = True
        with open(csvIn, 'r', encoding='utf-8') as incsv:
            reader = csv.DictReader(incsv)
            headers = reader.fieldnames
            verifyHeadrs = [
                'System UUID', 'Local ID', 'Department Responsible',
                'Person Responsible', 'Collection', 'Brief Description',
                'Object URI', 'Collection URI'
            ]
            if not headers == verifyHeadrs:
                messagebox.showwarning(
                    message=
                    "Your input CSV is not formatted correctly.\n\nQuitting action."
                )
                return [0, 0]
            for row in reader:
                skip1 = False
                foldname = row['%s' % locids]
                foldpath = path.join(fpath, foldname)
                if not path.exists(foldpath):
                    skip1 = True
                # The function skips objects that are Bags or already have a
                # 'metadata.csv' file. Thus it skips creating a 'metadata.xml'
                # for these objects also.
                if path.exists(path.join(foldpath, 'data')):
                    skip1 = messagebox.askyesno(
                        message=
                        "It appears that \'%s\' is a bag.\n\nSkip creating \'metadata.csv\' for this one item?"
                        % foldname)
                if path.exists(path.join(foldpath,
                                         'metadata.csv')) and firstone == True:
                    firstone = False
                    overwrite_all = messagebox.askyesno(
                        message=
                        "At least one \'metadata.csv\' already\nexists. Overwrite ALL of them?"
                    )
                if path.exists(path.join(
                        foldpath, 'metadata.csv')) and overwrite_all == False:
                    skip1 = True
                if skip1 == False:
                    metafile = path.join(foldpath, 'metadata.csv')
                    with open(metafile, 'w') as newmeta:
                        metawriter = csv.DictWriter(newmeta,
                                                    fieldnames=headers)
                        metawriter.writeheader()
                        metawriter.writerow(row)
                    nfiles += 1
                    newmeta.close()
                    rdfok = self.make_rdf(metafile)
                    if rdfok == True:
                        rfiles += 1
        return [nfiles, rfiles]

    def create_meta(self, root, folderpath, myfile, idcolname, moreopts1):
        """
        Generates minimal metadata files, 'metadata.csv' and 'metadata.xml'
        based on a master CSV or a METS xml file
        """
        sourcetype = 'csv'  # default
        counts = [0, 0]  # default
        if path.splitext(myfile)[1] == '.csv':
            sourcetype = 'csv'
        else:
            messagebox.showwarning(
                message=
                "The metadata source file must be CSV.\nQuitting action.")
            runnext1 = False
            return runnext1
        if sourcetype == 'csv':
            counts = self.meta_from_csv(myfile, idcolname, folderpath)
        if not moreopts1 == 0:
            if self.prompting == 0:
                runnext1 = True
            else:
                runnext1 = messagebox.askyesno(
                    message=
                    "Created %d \'metadata.csv\' and %d \'metadata.xml\' files.\n\nProceed with the next action?"
                    % (counts[0], counts[1]))
        else:
            runnext1 = False
            messagebox.showwarning(
                message=
                "Created %d \'metadata.csv\' and %d \'metadata.xml\' files." %
                (counts[0], counts[1]))
        return runnext1

    def gen_ID(self):
        """
        Function to generate a System UUID. In future this will request a NOID
        and ARK from the naming authority
        """
        SysUID = 'vtdata_' + str(uuid.uuid4())
        return SysUID

    def register_obj(self, ofolder, moreopts2):
        """
        Function to assign System UUID's to objects and register them in the UDCS
            (a) generate UUID from single naming authority
            (b) log the obj. in a system Processing Log
            (c) create placeholder metadata on the Metadata Server
            (d) update the minimal 'metadata' files with the System UUID
        """
        renamed = 0
        rfiles = 0
        logfile = path.join(ofolder, 'log4preservation.csv')
        if not path.exists(logfile):
            with open(logfile, 'w', encoding='utf-8') as lfile:
                headrow = ['SysUID', 'LocalID', 'RegisDateTime', 'RegisPerson']
                writer = csv.DictWriter(lfile, fieldnames=headrow)
                writer.writeheader()
            lfile.close()
        for fo in listdir(ofolder):
            skip3 = False
            fopath = path.join(ofolder, fo)
            if not path.isdir(fopath):
                skip3 = True
            elif path.isdir(fopath):
                metapath = path.join(fopath, 'metadata.csv')
                oldrdf = path.join(fopath, 'metadata.xml')
                # oldjson = path.join(fopath, 'metadata.json')
                if not path.exists(metapath):
                    skip3 = True
                    messagebox.showwarning(
                        message=
                        "Could not find:\n\'%s\'.\n\nSkipping registration of:\n%s."
                        % (metapath, fo))
                if not skip3:
                    newID = self.gen_ID()
                    with open(metapath, 'r', encoding='utf-8') as oldmeta:
                        r = csv.reader(oldmeta)
                        lines = list(r)
                        lines[1][0] = newID
                        log1 = newID
                        log2 = lines[1][1]
                        log3 = time.strftime("%Y.%m.%d %H:%M:%S")
                        log4 = lines[1][3]
                        logline = [log1, log2, log3, log4]
                    with open(logfile, 'a', encoding='utf-8') as logoutf:
                        cwriter = csv.writer(logoutf)
                        cwriter.writerow(logline)
                    with open(metapath, 'w', encoding='utf-8') as outmeta:
                        w = csv.writer(outmeta)
                        w.writerows(lines)
                    if path.exists(oldrdf):
                        remove(oldrdf)
                    # if path.exists(oldjson):
                    #     remove(oldjson)
                    rdfok = self.make_rdf(metapath)
                    if rdfok == True:
                        rfiles += 1
                    newpath = path.join(path.dirname(fopath), '%s' % newID)
                    rename(fopath, newpath)
                    renamed += 1
        if not moreopts2 == 0:
            if self.prompting == 0:
                runnext2 = True
            else:
                runnext2 = messagebox.askyesno(
                    message=
                    "Registered %d objects.\n\nProceed with the next action?" %
                    renamed)
        else:
            runnext2 = False
            messagebox.showwarning(message="Registered %d objects." % renamed)
        return runnext2

    def md5(self, finame):
        """ Data Services requested Md5 hashes but Md5 is deprecated """
        hash_md5 = hashlib.md5()
        with open(finame, "rb") as md5file:
            for chunk in iter(lambda: md5file.read(4096), b""):
                hash_md5.update(chunk)
        return hash_md5.hexdigest()

    def sha3hash(self, filname):
        """ Generates SHA3-256 hashes """
        chunksize = io.DEFAULT_BUFFER_SIZE
        hash_sha3 = hashlib.sha3_256()
        with open(filname, "rb") as sha3file:
            for chunks in iter(lambda: sha3file.read(chunksize), b""):
                hash_sha3.update(chunks)
        return hash_sha3.hexdigest()

    def convert_size(self, size):
        """ Converts bytes to human readable denominations """
        if (size == 0):
            return '0B'
        # size_name = ("B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB")
        # i = int(math.floor(math.log(size,1024)))
        # p = math.pow(1024,i)
        size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
        i = int(math.floor(math.log(size, 1000)))
        p = math.pow(1000, i)
        s = round(size / p, 2)
        return '%s%s' % (s, size_name[i])

    def run_inventory(self, indir, moreopts3):
        """
        Runs an inventory and generates 'manifest.csv' files for each object
        """
        manifiles = 0
        for obj in listdir(indir):
            objpath = path.join(indir, obj)
            skipit = False
            counter = 0
            if not path.isdir(objpath):
                skipit = True
            elif path.isdir(objpath):
                if path.exists(path.join(objpath, 'data')):
                    isabag = messagebox.askyesno(
                        message=
                        "It appears that \'%s\' is a bag.\nSkip this object?" %
                        obj)
                    if isabag == True:
                        skipit = True
                if path.exists(path.join(objpath, 'manifest.csv')):
                    skipit = True
                    messagebox.showwarning(
                        message=
                        "The file \'manifest.csv\' already exists.\nSkipping inventory of the object: \n\'%s\'"
                        % obj)
            if skipit == False:
                manifiles += 1
                tempmani = open(path.join(indir, 'temp_manifest.csv'),
                                'w',
                                encoding='utf-8')
                tempmani.write(
                    "No., Filename, Filesize, Filetype, C-Time, Modified, Accessed, MD5_Sum, SHA3_256, ChecksumDateTime, RelPath, => , mode, inode, device, enlink, user, group\n"
                )
                workdir = path.dirname(objpath)
                for base, dirs, files in walk(objpath):
                    for name in files:
                        filepathname = path.join(base, name)
                        # Deletes .DS_Store Files
                        if path.basename(filepathname) == '.DS_Store':
                            remove(filepathname)
                        elif not path.basename(filepathname) == '.DS_Store':
                            counter += 1
                            rownum = str(counter)
                            statinfo = stat(filepathname)
                            filesize = statinfo[6]
                            csize = self.convert_size(filesize)
                            filemime = str(
                                mimetypes.guess_type(filepathname)[0])
                            filectime = time.strftime(
                                "%Y.%m.%d %H:%M:%S",
                                time.localtime(statinfo.st_ctime))
                            # note: on a Windows system, ctime is "date created" but on Unix it is
                            # "change time", i.e. the last time the metadata was changed.
                            modifdate = time.strftime(
                                "%Y.%m.%d %H:%M:%S",
                                time.localtime(statinfo.st_mtime))
                            accessdate = time.strftime(
                                "%Y.%m.%d %H:%M:%S",
                                time.localtime(statinfo.st_atime))
                            md5sum = self.md5(filepathname)
                            sha3sum = self.sha3hash(filepathname)
                            runtime = time.strftime("%Y.%m.%d %H:%M:%S")
                            filemode = str(statinfo.st_mode)
                            fileino = str(statinfo.st_ino)
                            filedevice = str(statinfo.st_dev)
                            filenlink = str(statinfo.st_nlink)
                            fileuser = str(statinfo.st_uid)
                            filegroup = str(statinfo.st_gid)
                            # Displays a shortened Path for each file, excluding the directories
                            # that precede the working directory that contains the objects.
                            showpath = path.relpath(filepathname, workdir)
                            tempmani.write("%s," % rownum + "\"%s\"," % name +
                                           "%s," % csize +
                                           "\"%s\"," % filemime +
                                           "%s," % filectime +
                                           "%s," % modifdate +
                                           "%s," % accessdate +
                                           "%s," % md5sum + "%s," % sha3sum +
                                           "%s," % runtime +
                                           "\"%s\"," % showpath)
                            tempmani.write(" ,%s," % filemode +
                                           "%s," % fileino +
                                           "%s," % filedevice +
                                           "%s," % filenlink +
                                           "%s," % fileuser +
                                           "%s\n" % filegroup)
                tempmani.write("Comments, \n")
                tempmani.close()
                tomove = path.join(path.dirname(objpath), 'temp_manifest.csv')
                moveto = path.join(objpath, 'manifest.csv')
                shutil.move(tomove, moveto)
        if not moreopts3 == 0:
            if self.prompting == 0:
                runnext3 = True
            else:
                runnext3 = messagebox.askyesno(
                    message=
                    "Created %d \'manifest.csv\' files.\n\nProceed with the next action?"
                    % manifiles)
        else:
            runnext3 = False
            messagebox.showwarning(
                message="Created %d \'manifest.csv\' files." % manifiles)
        return runnext3

    def run_bagit(self, bagsdir, moreopts4):
        """ Bags all objects in a single directory """
        validbags = 0
        totalbags = 0
        for f in listdir(bagsdir):
            inpath = path.join(bagsdir, f)
            cont = True
            if path.isdir(inpath):
                if path.exists(path.join(inpath, 'data')):
                    cont = messagebox.askyesno(
                        message=
                        "It appears that \'%s\' is already a bag.\nBag it anyway?"
                        % f)
                if cont == True:
                    newbag = bagit.make_bag(inpath,
                                            checksums=['md5', 'sha512'])
                    totalbags += 1
                    if newbag.is_valid():
                        validbags += 1
                    elif not newbag.is_valid():
                        messagebox.showwarning(
                            message="Bag \'%s\' is not a valid bag." % f)
                # elif cont == False:
                #     messagebox.showwarning(message="Skipped bagging of \'%s\'." %f)
        if not moreopts4 == 0:
            if self.prompting == 0:
                runnext4 = True
            else:
                runnext4 = messagebox.askyesno(
                    message=
                    "Created %d total bags,\nof which %d are valid.\n\nProceed with the next action?"
                    % (totalbags, validbags))
        else:
            runnext4 = False
            messagebox.showwarning(
                message="Created %d total bags,\nof which %d are valid." %
                (totalbags, validbags))
        return runnext4

    def run_tar(self, tarfolder, moreopts5):
        """ Tars all objects in a single directory """
        tarfiles = 0
        alreadytar = 0
        notfolder = 0
        outfolder = path.splitext(tarfolder)[0] + '-tarred'
        if not path.exists(outfolder):
            mkdir(outfolder)
        for i in listdir(tarfolder):
            infile = path.join(tarfolder, i)
            if path.isdir(infile):
                outfile = path.join(outfolder, path.splitext(i)[0] + '.tar')
                if path.exists(outfile):
                    messagebox.showwarning(
                        message=
                        "The TAR file: \n\'%s\'\nalready exists!\nTar archive not created."
                        % outfile)
                    alreadytar += 1
                elif not path.exists(outfile):
                    # with tarfile.open(outfile, 'w:gz') as newtar:
                    with tarfile.open(outfile, 'w') as newtar:
                        tarname = path.relpath(infile, tarfolder)
                        newtar.add(infile, arcname='%s' % tarname)
                    tarfiles += 1
            else:
                notfolder += 1
        if not alreadytar == 0:
            messagebox.showwarning(
                message=
                "The folder \'%s\' already contained %d tar files which were skipped."
                % (outfolder, alreadytar))
        # if not notfolder == 0:
        #    messagebox.showwarning(message="The target folder contained %d files, which were ignored." %notfolder)
        if not moreopts5 == 0:
            if self.prompting == 0:
                runnext5 = True
            else:
                runnext5 = messagebox.askyesno(
                    message=
                    "Created %d tar archives.\n\nProceed with the next action?"
                    % tarfiles)
        else:
            runnext5 = False
            messagebox.showwarning(message="Created %d tar archives." %
                                   tarfiles)
        return runnext5

    def trans_manifest(self, indirectory):
        """
        Generates a manifest of filenames and checksums for a directory of
        Bagged and Tarred objects
        """
        askingdir = path.join(path.basename(path.dirname(indirectory)),
                              path.basename(indirectory))
        indir = ""
        tardest = messagebox.askyesno(
            message="Create manifest of \'%s-tarred\'?" % askingdir,
            default='yes')
        if tardest:
            indir = indirectory + "-tarred"
        elif not tardest:
            indir = askdirectory(
                initialdir=path.dirname(indirectory),
                title="In which folder are the objects to be transferred?")
        if not path.exists(indir):
            messagebox.showwarning(
                message=
                "The directory: \n\'%s\'\n does not exist.\n\nCancelling action."
                % indir)
            return
        outdir = path.dirname(indir)
        # messagebox.showwarning(message="The transfer manifest will be saved in: \n\'%s\'" %outdir)
        compfile = open(path.join(
            outdir, "Transfer_%s_%s.csv" %
            (path.basename(indir), time.strftime("%m%d_%H%M%S"))),
                        'w',
                        encoding='utf-8')
        for base, dirs, files in walk(indir):
            for name in files:
                pathname = path.join(base, name)
                if path.basename(pathname) == '.DS_Store':
                    remove(pathname)
                elif not path.basename(pathname) == '.DS_Store':
                    sha3sum = self.sha3hash(pathname)
                    compfile.write("%s, " % name + "%s\n" % sha3sum)
        compfile.close()
        messagebox.showwarning(message="Transfer Manifest Created.")
        return

    def pre_pack(self, packdir):
        """
        Preserves departmental folder structure during Bagging by moving
        object contents into a subdirectory named with the local object ID
        """
        for item in listdir(packdir):
            olditempath = path.join(packdir, item)
            if path.isdir(olditempath):
                newdirpath = path.join(olditempath, path.basename(olditempath))
                temppath = path.join(olditempath, 'temptemptemp')
                shutil.copytree(olditempath, temppath)
                for thing in listdir(olditempath):
                    thingpath = path.join(olditempath, thing)
                    if not thing == 'temptemptemp':
                        if path.isdir(thingpath):
                            shutil.rmtree(thingpath)
                        elif not 'meta' in thing:
                            remove(thingpath)
                rename(temppath, newdirpath)
        return packdir

    def run_procs(self, root, frame2):
        runnext = True
        olditemsdir = self.e1.get()
        meta = frame2.metavar.get()
        regstr = frame2.regisvar.get()
        inv = frame2.invenvar.get()
        bagit = frame2.bagitvar.get()
        tar = frame2.tarvar.get()
        trans = frame2.transvar.get()
        self.prompting = frame2.prompt.get()
        nselect = 0
        for d in [meta, regstr, inv, bagit, tar, trans]:
            if d == 1:
                nselect += 1
        if olditemsdir == "":
            messagebox.showwarning(message="You must first select a folder.")
            return
        if not path.exists(olditemsdir):
            messagebox.showwarning(
                message="Items folder:\n\'%s\'\nnot found." % olditemsdir)
            return
        if nselect == 0:
            messagebox.showwarning(
                message="You have not selected any \'Options\'.")
            return
        # PrePack items
        prepack = messagebox.askyesno(
            title="Pre-Packaging",
            message=
            "Is this the first time running UDOF on THESE items?\n(Clicking \'yes\' will \'pre-package\' them.)",
            default='no')
        if prepack == False:
            itemsdir = olditemsdir
        else:
            itemsdir = self.pre_pack(olditemsdir)
        # Run CSV meta
        if meta == 1:
            nselect -= 1
            metainput = self.e2.get()
            idcolumn = self.e3.get()
            if metainput == "":
                messagebox.showwarning(
                    message="You must choose a CSV master metadata file.")
                return
            if not path.exists(metainput):
                messagebox.showwarning(
                    message="CSV file:\n\'%s\'\nnot found. Stopping action." %
                    metainput)
                return
            if path.splitext(metainput)[1] == '.csv' and idcolumn == "":
                messagebox.showwarning(
                    message="You must choose the column of ID's in the CSV.")
                return
            runnext = self.create_meta(root, itemsdir, metainput, idcolumn,
                                       nselect)
            if runnext == False:
                return
        # Assign UUID's and Register Objects
        if regstr == 1:
            nselect -= 1
            runnext = self.register_obj(itemsdir, nselect)
            if runnext == False:
                return
        # Run Inventory
        if inv == 1:
            nselect -= 1
            runnext = self.run_inventory(itemsdir, nselect)
            if runnext == False:
                return
        # Run BagIt
        if bagit == 1:
            nselect -= 1
            self.run_bagit(itemsdir, nselect)
            if runnext == False:
                return
        # Run Tar
        if tar == 1:
            nselect -= 1
            runnext = self.run_tar(itemsdir, nselect)
            if runnext == False:
                return
        # Make Transfer Manifest
        if trans == 1:
            self.trans_manifest(itemsdir)
        return
Beispiel #35
0
class DebutPartie(Tk):
    def __init__(self):
        """
        Cette fenêtre contient la configuration requise pour débuter le jeu PyMafia
        L'usager doit remplir les données requises avant de pouvoir débuter le jeu
        """
        super().__init__()
        self.title("PyMafia - Débuter une partie")
        self.resizable(0, 0)
        self.framesuperieur = Frame(self)
        self.framesuperieur.grid(row=0, column=0, columnspan=3)
        self.framesuperieur['highlightthickness'] = 0
        self.framesuperieur['highlightbackground'] = 'black'
        self.framechoix = Frame(self)
        self.framechoix.grid(row=1, column=0, columnspan=3)
        self.framechoix['highlightthickness'] = 0
        self.framechoix['highlightbackground'] = 'black'
        self.frameinferieur = Frame(self)
        self.frameinferieur.grid(row=2, column=0, columnspan=3)
        self.frameinferieur['highlightthickness'] = 0
        self.frameinferieur['highlightbackground'] = 'black'
        debuttxt = "Bienvenue à PyMafia, pour débuter une partie, veuillez indiquer le nombre de joueurs: "
        self.label = Label(self.framesuperieur, text=debuttxt, relief=FLAT)
        self.label.grid(row=0, column=0, padx=10, pady=10)
        # Création du DropDown
        choix_nb_joueurs = ["2", "3", "4"]
        nb_joueur = StringVar(self)
        nb_joueur.set(choix_nb_joueurs[0])
        radiobuttons = list()
        self.totalJoueurs = OptionMenu(
            self.framesuperieur,
            nb_joueur,
            *choix_nb_joueurs,
            command=lambda event: self.changement_dropdown(
                radiobuttons, nb_joueur))
        self.totalJoueurs.grid(row=0, column=1, padx=10, pady=10)
        # Fin DropDown
        self.labelChoixHumainOrdinateur = Label(
            self.framechoix,
            text="Veuillez choisir le type de joueur:",
            relief=FLAT,
            justify=LEFT,
            state=DISABLED,
            anchor="w")
        self.labelChoixHumainOrdinateur.grid(row=1, column=0, padx=10, pady=10)
        self.debuterPartie = Button(self.frameinferieur,
                                    text="Let's do this baby!")
        self.joueurVar = self.créer_boutons_radios(radiobuttons,
                                                   int(nb_joueur.get()))
        self.debuterPartie.bind(
            "<ButtonRelease-1>",
            lambda event: self.commencer_partie(nb_joueur, self.joueurVar))
        self.debuterPartie.grid(row=int(nb_joueur.get()) + 2,
                                column=1,
                                padx=10,
                                pady=10)
        intvar = IntVar()
        self.menu = Menu(self)
        self.optionMenu = OptionMenu(self, intvar, 3, 4, 5, 6)
        self.premier_menu = Menu(self.menu, tearoff=0)
        self.premier_menu.add_command(label='Règlements',
                                      command=self.afficher_reglements)
        self.premier_menu.add_separator()
        self.premier_menu.add_command(label='Quitter',
                                      command=self.validation_de_sortie)
        self.menu.add_cascade(label='Fichier', menu=self.premier_menu)
        self.config(menu=self.menu)

    def validation_de_sortie(self):
        """
        fonction qui demande de valider si on veut vraiment quitter la partie en cours.
        :return: None
        """
        message = "Vous avez une partie en cours. Désirez-vous réellement quitter la partie?"
        if messagebox.askokcancel("Annuler",
                                  message,
                                  default="cancel",
                                  icon="warning"):
            self.destroy()
        else:
            pass

    def changement_dropdown(self, radiobuttons, nbjoueurs):
        """
        fonction évenementielle qui détecte un changement dans le dropdown du nombre de joueur
        Elle recrée les boutons radios sur demande
        :radiobuttons (list): lien des boutons radios
        :nbjoueurs (int): valeur sélectionnée dans le dropdown
        :return:
        """
        self.framechoix.destroy()
        self.framechoix = Frame(self)
        self.framechoix.grid(row=1, column=0, columnspan=3)
        self.framechoix['highlightthickness'] = 0
        self.framechoix['highlightbackground'] = 'black'
        self.labelChoixHumainOrdinateur = Label(
            self.framechoix,
            text="Veuillez choisir le type de joueur:",
            relief=FLAT,
            justify=LEFT,
            state=DISABLED,
            anchor="w")
        self.labelChoixHumainOrdinateur.grid(row=1, column=0, padx=10, pady=10)
        self.joueurVar = self.créer_boutons_radios(radiobuttons,
                                                   int(nbjoueurs.get()))

    def créer_boutons_radios(self, radiobuttons, nombre):
        """
        Cette fonction permet de créer/recréer les boutons radios selon le nombre de paramètres requis
        :param radiobuttons: La liste contenant les boutons radios créés
        :param nombre: Le nombre de boutons radios à créer (nombre de joueurs)
        :return: Retourne la variable des boutons radios ainsi que le frame
        """
        type_joueur = [("Humain", 101, "Ordinateur", 102),
                       ("Humain", 201, "Ordinateur", 202),
                       ("Humain", 301, "Ordinateur", 302),
                       ("Humain", 401, "Ordinateur", 402)]
        radio_button_offset_row = 2
        radio_button_offset_col = 1
        joueur_var = list()
        joueur_var_offset = 0
        choix_nb_joueurs = int
        if choix_nb_joueurs == 2:
            radiobuttons.append += 1
        elif joueur_var == 3:
            radiobuttons.append += 2

        for joueurType1, joueurVal1, joueurType2, joueurVal2 in type_joueur:
            if nombre > 0:
                joueur_var.append(StringVar())
                Label(self.framechoix, text=f"Joueur {str(joueurVal1)[0]}", state=DISABLED).\
                    grid(row=radio_button_offset_row, column=radio_button_offset_col - 1)
                Radiobutton(self.framechoix, text=joueurType1, variable=joueur_var[joueur_var_offset], state=DISABLED,
                            value=joueurVal1, padx=0, pady=0, tristatevalue=1). \
                    grid(row=radio_button_offset_row, column=radio_button_offset_col)
                Radiobutton(self.framechoix, text=joueurType2, variable=joueur_var[joueur_var_offset], state=DISABLED,
                            value=joueurVal2, padx=0, pady=0). \
                    grid(row=radio_button_offset_row, column=radio_button_offset_col + 1)
                joueur_var[joueur_var_offset].set(
                    joueurVal1)  # Permet de sélectionner par défaut Humain
                radio_button_offset_row += 1
                joueur_var_offset += 1
            nombre -= 1
        return joueur_var
        # Fin de création des boutons radios

    def commencer_partie(self, nb_joueur: StringVar, joueur_var):
        """
        Cette fonction permet de lancer le GUI du jeu PyMafia

        :param nb_joueur: La variable contenant le menu dropdown du nombre de joueurs
        :param joueur_var: Les valeurs des boutons radios indiquant humain ou ordinateur
        :return: None
        """
        nombre_de_joueurs = int(nb_joueur.get())
        self.lire_bouton_radio(joueur_var)
        self.destroy()
        jouer_partie = FenetrePymafia(nombre_de_joueurs)
        jouer_partie.mainloop()

    @staticmethod
    def lire_bouton_radio(joueur_var):
        # À développer, il faut définir quel joueur dans la liste est un humain, quel ne l'est pas.
        # Ici, joueur_var contient la liste des choix des boutons radios
        # Cette fonction doit extraire le nombre de joueur humains, j'ai défini les joueurs humain par #XX1
        # ordinateurs par #XX2
        # concept mauvais, on ne l'utilisera pas finalement, à développer pour le TP6 !
        # for jv in joueur_var:
        #    print(jv.get())
        pass

    def afficher_reglements(self):
        """
        Cette fonction affiche une fenêtre avec les règlements
        :return:
        """
        reglements = Tk()
        reglements.title("Règlements")
        reglements.resizable(0, 0)
        regles = self.regles_jeu()
        label = Label(reglements, text=regles, relief=RAISED)
        label.grid(row=0, column=0, padx=10, pady=10)
        Button(reglements, text="Fermer",
               command=reglements.destroy).grid(row=1, column=1)
        reglements.mainloop()

    @staticmethod
    def regles_jeu():
        """
        Fait que retourner un string avec les instructions du jeu
        :return: string : règles du jeu
        """
        return """Instructions\n\n,.-'¨'-.,-=-,.-'¨'-.,-= Pymafia =-,.-'¨'-.,-=-,.-'¨'-.,\n\n
Beispiel #36
0
class SettingsDisplay(Dialog):
    """ Settings form User Interface"""
    def body(self, master):
        self.root_window = master.master.master  # This is really gross. I'm sorry.
        self.logger = logging.getLogger(self.root_window.logger.name +
                                        ".SettingsDisplay")
        self.key_listener = KeybindManager(self, sticky=True)
        # Labels
        Label(master, text="Start Minimized?: ").grid(row=0, column=0)
        Label(master, text="Avg. Monitor Default: ").grid(row=1, column=0)
        Label(master, text="Smooth Transition Time (sec): ").grid(row=2,
                                                                  column=0)
        Label(master, text="Brightness Offset: ").grid(row=3, column=0)
        Label(master, text="Add Preset Color: ").grid(row=4, column=0)
        Label(master, text="Audio Input Source: ").grid(row=5, column=0)
        Label(master, text="Add keyboard shortcut").grid(row=6, column=0)

        # Widgets
        # Starting minimized
        self.start_mini = BooleanVar(master,
                                     value=config.getboolean(
                                         "AppSettings", "start_minimized"))
        self.start_mini_check = Checkbutton(master, variable=self.start_mini)

        # Avg monitor color match
        self.avg_monitor = StringVar(
            master, value=config["AverageColor"]["DefaultMonitor"])
        with mss.mss() as sct:
            options = [
                "full",
                "get_primary_monitor",
                *[tuple(m.values()) for m in sct.monitors],
            ]
        # lst = get_display_rects()
        # for i in range(1, len(lst) + 1):
        #    els = [list(x) for x in itertools.combinations(lst, i)]
        #    options.extend(els)
        self.avg_monitor_dropdown = OptionMenu(master, self.avg_monitor,
                                               *options)

        self.duration_scale = Scale(master,
                                    from_=0,
                                    to_=2,
                                    resolution=1 / 15,
                                    orient=HORIZONTAL)
        self.duration_scale.set(float(config["AverageColor"]["Duration"]))

        self.brightness_offset = Scale(master,
                                       from_=0,
                                       to_=65535,
                                       resolution=1,
                                       orient=HORIZONTAL)
        self.brightness_offset.set(
            int(config["AverageColor"]["brightnessoffset"]))

        # Custom preset color
        self.preset_color_name = Entry(master)
        self.preset_color_name.insert(END, "Enter color name...")
        self.preset_color_button = Button(master,
                                          text="Choose and add!",
                                          command=self.get_color)

        # Audio dropdown
        device_names = self.master.audio_interface.get_device_names()
        try:
            init_string = (" " + config["Audio"]["InputIndex"] + " " +
                           device_names[int(config["Audio"]["InputIndex"])])
        except ValueError:
            init_string = " None"
        self.audio_source = StringVar(
            master, init_string
        )  # AudioSource index is grabbed from [1], so add a space at [0]
        as_choices = device_names.items()
        self.as_dropdown = OptionMenu(master, self.audio_source, *as_choices)

        # Add keybindings
        light_names = list(self.root_window.device_map.keys())
        self.keybind_bulb_selection = StringVar(master, value=light_names[0])
        self.keybind_bulb_dropdown = OptionMenu(master,
                                                self.keybind_bulb_selection,
                                                *light_names)
        self.keybind_keys_select = Entry(master)
        self.keybind_keys_select.insert(END, "Add key-combo...")
        self.keybind_keys_select.config(state="readonly")
        self.keybind_keys_select.bind("<FocusIn>", self.on_keybind_keys_click)
        self.keybind_keys_select.bind(
            "<FocusOut>",
            lambda *_: self.keybind_keys_select.config(state="readonly"))
        self.keybind_color_selection = StringVar(master, value="Color")
        self.keybind_color_dropdown = OptionMenu(
            master, self.keybind_color_selection, *self.root_window.frame_map[
                self.keybind_bulb_selection.get()].default_colors,
            *([*config["PresetColors"].keys()]
              if any(config["PresetColors"].keys()) else [None]))
        self.keybind_add_button = Button(
            master,
            text="Add keybind",
            command=lambda *_: self.register_keybinding(
                self.keybind_bulb_selection.get(),
                self.keybind_keys_select.get(),
                self.keybind_color_selection.get(),
            ),
        )
        self.keybind_delete_button = Button(master,
                                            text="Delete keybind",
                                            command=self.delete_keybind)

        # Insert
        self.start_mini_check.grid(row=0, column=1)
        ttk.Separator(master, orient=HORIZONTAL).grid(row=0,
                                                      sticky="esw",
                                                      columnspan=100)
        self.avg_monitor_dropdown.grid(row=1, column=1)
        self.duration_scale.grid(row=2, column=1)
        self.brightness_offset.grid(row=3, column=1)
        ttk.Separator(master, orient=HORIZONTAL).grid(row=3,
                                                      sticky="esw",
                                                      columnspan=100)
        self.preset_color_name.grid(row=4, column=1)
        self.preset_color_button.grid(row=4, column=2)
        ttk.Separator(master, orient=HORIZONTAL).grid(row=4,
                                                      sticky="esw",
                                                      columnspan=100)
        self.as_dropdown.grid(row=5, column=1)
        ttk.Separator(master, orient=HORIZONTAL).grid(row=5,
                                                      sticky="esw",
                                                      columnspan=100)
        self.keybind_bulb_dropdown.grid(row=6, column=1)
        self.keybind_keys_select.grid(row=6, column=2)
        self.keybind_color_dropdown.grid(row=6, column=3)
        self.keybind_add_button.grid(row=6, column=4)
        self.mlb = MultiListbox(master,
                                (("Bulb", 5), ("Keybind", 5), ("Color", 5)))
        for keypress, fnx in dict(config["Keybinds"]).items():
            label, color = fnx.split(":")
            self.mlb.insert(END, (label, keypress, color))
        self.mlb.grid(row=7, columnspan=100, sticky="esw")
        self.keybind_delete_button.grid(row=8, column=0)

    def validate(self) -> int:
        config["AppSettings"]["start_minimized"] = str(self.start_mini.get())
        config["AverageColor"]["DefaultMonitor"] = str(self.avg_monitor.get())
        config["AverageColor"]["Duration"] = str(self.duration_scale.get())
        config["AverageColor"]["BrightnessOffset"] = str(
            self.brightness_offset.get())
        config["Audio"]["InputIndex"] = str(self.audio_source.get()[1])
        # Write to config file
        with open("config.ini", "w", encoding="utf-8") as cfg:
            config.write(cfg)

        self.key_listener.shutdown()

        return 1

    def get_color(self):
        """ Present user with color palette dialog and return color in HSBK """
        color = askcolor()[0]
        if color:
            # RGBtoHBSK sometimes returns >65535, so we have to clamp
            hsbk = [min(c, 65535) for c in RGBtoHSBK(color)]
            config["PresetColors"][self.preset_color_name.get()] = str(hsbk)

    def register_keybinding(self, bulb: str, keys: str, color: str):
        """ Get the keybind from the input box and pass the color off to the root window. """
        try:
            color = self.root_window.frame_map[
                self.keybind_bulb_selection.get()].default_colors[color]
        except KeyError:  # must be using a custom color
            color = str2list(config["PresetColors"][color], int)
        self.root_window.save_keybind(bulb, keys, color)
        config["Keybinds"][str(keys)] = str(bulb + ":" + str(color))
        self.mlb.insert(END, (str(bulb), str(keys), str(color)))
        self.keybind_keys_select.config(state="normal")
        self.keybind_keys_select.delete(0, "end")
        self.keybind_keys_select.insert(END, "Add key-combo...")
        self.keybind_keys_select.config(state="readonly")
        self.preset_color_name.focus_set(
        )  # Set focus to a dummy widget to reset the Entry

    def on_keybind_keys_click(self, event):
        """ Call when cursor is in key-combo entry """
        self.update()
        self.update_idletasks()
        self.key_listener.restart()
        self.keybind_keys_select.config(state="normal")
        self.update()
        self.update_idletasks()
        while self.focus_get() == self.keybind_keys_select:
            self.keybind_keys_select.delete(0, "end")
            self.keybind_keys_select.insert(END,
                                            self.key_listener.key_combo_code)
            self.update()
            self.update_idletasks()

    def delete_keybind(self):
        """ Delete keybind currently selected in the multi-list box. """
        _, keybind, _ = self.mlb.get(ACTIVE)
        self.mlb.delete(ACTIVE)
        self.root_window.delete_keybind(keybind)
        config.remove_option("Keybinds", keybind)
Beispiel #37
0
class Tab(ABC):
    def __init__(self, view, tab_control):
        self.view = view
        self.bandas_estandar_repository = RepositoryProvider.provide_bandas_estandar_repository(
        )
        self.tab_frame = tab_control.agregar_tab(self, self.titulo_tab)
        self.construir_tab()

    @abstractmethod
    def obtener_bandas(self):
        pass

    def construir_tab(self):
        self.construir_frame_titulo()
        self.construir_frame_grafica()
        self.construir_frame_medicion()

    def construir_frame_titulo(self):
        self.frame_titulo_grafica = Frame(self.tab_frame)
        self.frame_titulo_grafica.config(width=400,
                                         borderwidth=2,
                                         relief="groove")
        self.frame_titulo_grafica.grid(row=0,
                                       column=0,
                                       sticky="nsew",
                                       padx=10,
                                       pady=(15, 0))
        self.label_titulo_grafica = Label(self.frame_titulo_grafica)
        self.label_titulo_grafica.config(
            text="Nivel de respuesta impulsional - Curva de decaimiento",
            bg="#0c005a")
        self.label_titulo_grafica.pack(fill="both", expand="True")

    def construir_frame_grafica(self):
        self.frame_grafica = Frame(self.tab_frame)
        self.frame_grafica.grid(row=1, column=0, padx=10, pady=10)
        self.frame_label_grafica = Frame(self.frame_grafica)
        self.frame_label_grafica.config(width=600, height=400)
        self.frame_label_grafica.pack_propagate(False)
        self.frame_label_grafica.grid(row=0, column=0)
        self.label_grafica = Label(self.frame_label_grafica)
        self.label_grafica.config(borderwidth=2, relief="groove", bg="#5893d4")
        self.label_grafica.pack(expand="True", fill="both")
        self.frame_toolbar = Frame(self.frame_grafica)
        self.frame_toolbar.config(width=400, height=40, borderwidth=2)
        self.frame_toolbar.pack_propagate(False)
        self.frame_toolbar.grid(row=1, column=0, sticky="nsew")
        self.construir_plot()

    def construir_plot(self):
        self.figura = Figure(figsize=(6, 4), dpi=100)
        self.figura.patch.set_facecolor("#becbff")
        self.sistema_ejes = self.figura.add_subplot(1, 1, 1)
        self.sistema_ejes.set_facecolor("#dee1ec")
        self.limpiar_ejes()

        self.canvas = FigureCanvasTkAgg(self.figura, master=self.label_grafica)
        self.canvas.get_tk_widget().pack(side=BOTTOM, fill=BOTH, expand=True)

        toolbar = NavigationToolbar2Tk(self.canvas, self.frame_toolbar)
        toolbar.update()

    def limpiar_ejes(self):
        self.sistema_ejes.cla()
        self.sistema_ejes.set_xlabel('Tiempo (s)')
        self.sistema_ejes.set_ylabel('Nivel (dB)')
        self.sistema_ejes.set_xlim(left=0, auto=True)
        self.sistema_ejes.set_ylim(bottom=-120, top=0, auto=True)

    def construir_frame_medicion(self):
        self.frame_medicion = Frame(self.tab_frame)
        self.frame_medicion.grid(row=0, column=1, rowspan=2, sticky="nsew")
        self.construir_frame_bandas()

    def construir_frame_bandas(self):

        self.construir_seleccion_banda()
        self.construir_frame_rts()

    def construir_seleccion_banda(self):

        self.frame_titulo_bandas = Label(self.frame_medicion)
        self.frame_titulo_bandas.config(borderwidth=2, relief="groove")
        self.frame_titulo_bandas.grid(row=0,
                                      column=0,
                                      sticky="nsew",
                                      padx=10,
                                      pady=(15, 0))
        self.label_titulo_bandas_octava = Label(self.frame_titulo_bandas)
        self.label_titulo_bandas_octava.config(text=self.titulo_bandas_text,
                                               bg="#0c005a")
        self.label_titulo_bandas_octava.pack(ipadx=10,
                                             expand="True",
                                             fill="both")
        self.frame_medicion_bandas = Frame(self.frame_medicion)
        self.frame_medicion_bandas.grid(row=1,
                                        column=0,
                                        sticky="nsew",
                                        padx=10,
                                        pady=(20, 0))
        bandas_estandar = self.obtener_bandas()
        self.banda_seleccionada = StringVar()
        self.banda_seleccionada.set(bandas_estandar[0])
        self.combobox_banda = OptionMenu(self.frame_medicion_bandas,
                                         self.banda_seleccionada,
                                         *bandas_estandar)
        self.combobox_banda.config(relief="groove",
                                   borderwidth=0,
                                   bg="#5893d4",
                                   activebackground="#0060ca",
                                   width=20)
        self.combobox_banda['menu'].config(bg="#5893d4",
                                           activebackground="#0060ca")
        self.combobox_banda.grid(row=0, column=0, padx=10)
        self.ponderacion_A_checked = BooleanVar(False)
        self.checkbutton_ponderacion_A = Checkbutton(
            self.frame_medicion_bandas)
        self.checkbutton_ponderacion_A.config(
            text="Ponderación A",
            variable=self.ponderacion_A_checked,
            selectcolor="#5e0606")
        self.checkbutton_ponderacion_A.grid(row=0, column=1, padx=20)
        self.boton_calcular = Button(self.frame_medicion_bandas)
        self.boton_calcular.config(text="Calcular",
                                   command=self.view.on_calcular,
                                   bg="#5e0606",
                                   width=20)
        self.boton_calcular.grid(row=0, column=2, padx=10)

    def construir_frame_rts(self):

        self.frame_rts = Frame(self.frame_medicion)
        self.frame_rts.config(borderwidth=2, relief='ridge')
        self.frame_rts.grid(row=4, column=0, padx=10, pady=(15, 0))

        self.frame_titulo_rts = Label(self.frame_rts)
        self.frame_titulo_rts.config(borderwidth=2, relief="groove")
        self.frame_titulo_rts.grid(row=0,
                                   column=0,
                                   sticky="nsew",
                                   padx=10,
                                   pady=10,
                                   columnspan=2)
        self.label_titulo_rts = Label(self.frame_titulo_rts)
        self.label_titulo_rts.config(text="Tiempos de reverberación",
                                     bg="#0c005a")
        self.label_titulo_rts.pack(ipadx=10, expand="True", fill="both")
        self.frame_titulo_linealidad = Label(self.frame_rts)
        self.frame_titulo_linealidad.config(borderwidth=2, relief="groove")
        self.frame_titulo_linealidad.grid(row=0,
                                          column=2,
                                          sticky="nsew",
                                          padx=10,
                                          pady=10,
                                          columnspan=4)
        self.label_titulo_linealidad = Label(self.frame_titulo_linealidad)
        self.label_titulo_linealidad.config(text="Parámetros de linealidad",
                                            bg="#0c005a")
        self.label_titulo_linealidad.pack(ipadx=10, expand="True", fill="both")

        self.construir_frame_edt()
        self.construir_frame_t20()
        self.construir_frame_t30()
        self.construir_frame_curvatura()

        self.construir_frame_progressbar()

    def construir_frame_edt(self):

        self.frame_edt = Frame(self.frame_rts)
        self.frame_edt.grid(row=1, column=0, pady=(0, 10), columnspan=2)
        self.label_edt = Label(self.frame_edt)
        self.label_edt.config(text="EDT",
                              bg="#5893d4",
                              borderwidth=2,
                              relief="groove",
                              width=4)
        self.label_edt.grid(row=0, column=0, padx=(0, 10), pady=10)
        self.edt_var = StringVar()
        self.label_res_edt = Label(self.frame_edt)
        self.label_res_edt.config(relief="sunken",
                                  bg="#becbff",
                                  borderwidth=2,
                                  width=10,
                                  textvariable=self.edt_var,
                                  fg="black")
        self.label_res_edt.grid(row=0, column=1, padx=(10, 0), pady=10)
        self.frame_linealidad_edt = Frame(self.frame_rts)
        self.frame_linealidad_edt.grid(row=1,
                                       column=2,
                                       pady=(0, 10),
                                       columnspan=4)
        self.label_r_edt = Label(self.frame_linealidad_edt)
        self.label_r_edt.config(text="r",
                                bg="#5893d4",
                                borderwidth=2,
                                relief="groove",
                                width=4)
        self.label_r_edt.grid(row=0, column=0, padx=10, pady=10)
        self.r_edt_var = StringVar()
        self.label_res_r_edt = Label(self.frame_linealidad_edt)
        self.label_res_r_edt.config(relief="sunken",
                                    bg="#becbff",
                                    borderwidth=2,
                                    width=10,
                                    textvariable=self.r_edt_var,
                                    fg="black")
        self.label_res_r_edt.grid(row=0, column=1, padx=10, pady=10)
        self.label_xi_edt = Label(self.frame_linealidad_edt)
        self.label_xi_edt.config(text="ξ",
                                 bg="#5893d4",
                                 borderwidth=2,
                                 relief="groove",
                                 width=4)
        self.label_xi_edt.grid(row=0, column=2, padx=10, pady=10)
        self.xi_edt_var = StringVar()
        self.label_res_xi_edt = Label(self.frame_linealidad_edt)
        self.label_res_xi_edt.config(relief="sunken",
                                     bg="#becbff",
                                     borderwidth=2,
                                     width=10,
                                     fg="black",
                                     textvariable=self.xi_edt_var)
        self.label_res_xi_edt.grid(row=0, column=3, padx=10, pady=10)

    def construir_frame_t20(self):

        self.frame_t20 = Frame(self.frame_rts)
        self.frame_t20.grid(row=2, column=0, pady=(0, 10), columnspan=2)
        self.label_t20 = Label(self.frame_t20)
        self.label_t20.config(text="T20",
                              bg="#5893d4",
                              borderwidth=2,
                              relief="groove",
                              width=4)
        self.label_t20.grid(row=0, column=0, padx=(0, 10), pady=10, sticky='w')
        self.t20_var = StringVar()
        self.label_res_t20 = Label(self.frame_t20)
        self.label_res_t20.config(relief="sunken",
                                  borderwidth=2,
                                  bg="#becbff",
                                  width=10,
                                  textvariable=self.t20_var,
                                  fg='black')
        self.label_res_t20.grid(row=0,
                                column=1,
                                padx=(10, 0),
                                pady=10,
                                sticky='e')
        self.frame_linealidad_t20 = Frame(self.frame_rts)
        self.frame_linealidad_t20.grid(row=2,
                                       column=2,
                                       pady=(0, 10),
                                       columnspan=4)
        self.label_r_t20 = Label(self.frame_linealidad_t20)
        self.label_r_t20.config(text="r",
                                bg="#5893d4",
                                borderwidth=2,
                                relief="groove",
                                width=4)
        self.label_r_t20.grid(row=0, column=2, padx=10, pady=10)
        self.r_t20_var = StringVar()
        self.label_res_r_t20 = Label(self.frame_linealidad_t20)
        self.label_res_r_t20.config(relief="sunken",
                                    bg="#becbff",
                                    borderwidth=2,
                                    width=10,
                                    textvariable=self.r_t20_var,
                                    fg='black')
        self.label_res_r_t20.grid(row=0, column=3, padx=10, pady=10)
        self.label_xi_t20 = Label(self.frame_linealidad_t20)
        self.label_xi_t20.config(text="ξ",
                                 bg="#5893d4",
                                 borderwidth=2,
                                 relief="groove",
                                 width=4)
        self.label_xi_t20.grid(row=0, column=4, padx=10, pady=10)
        self.xi_t20_var = StringVar()
        self.label_res_xi_t20 = Label(self.frame_linealidad_t20)
        self.label_res_xi_t20.config(relief="sunken",
                                     bg="#becbff",
                                     borderwidth=2,
                                     width=10,
                                     fg='black',
                                     textvariable=self.xi_t20_var)

        self.label_res_xi_t20.grid(row=0, column=5, padx=10, pady=10)

    def construir_frame_t30(self):
        self.frame_t30 = Frame(self.frame_rts)
        self.frame_t30.grid(row=3, column=0, pady=(0, 10), columnspan=2)
        self.label_t30 = Label(self.frame_t30)
        self.label_t30.config(text="T30",
                              bg="#5893d4",
                              borderwidth=2,
                              relief="groove",
                              width=4)
        self.label_t30.grid(row=0, column=0, padx=(0, 10), pady=10, sticky='w')
        self.t30_var = StringVar()
        self.label_res_t30 = Label(self.frame_t30)
        self.label_res_t30.config(relief="sunken",
                                  borderwidth=2,
                                  bg="#becbff",
                                  width=10,
                                  textvariable=self.t30_var,
                                  fg='black')
        self.label_res_t30.grid(row=0,
                                column=1,
                                padx=(10, 0),
                                pady=10,
                                sticky='e')
        self.frame_linealidad_t30 = Frame(self.frame_rts)
        self.frame_linealidad_t30.grid(row=3,
                                       column=2,
                                       pady=(0, 10),
                                       columnspan=4)
        self.label_r_t30 = Label(self.frame_linealidad_t30)
        self.label_r_t30.config(text="r",
                                bg="#5893d4",
                                borderwidth=2,
                                relief="groove",
                                width=4)
        self.label_r_t30.grid(row=0, column=2, padx=10, pady=10)
        self.r_t30_var = StringVar()
        self.label_res_r_t30 = Label(self.frame_linealidad_t30)
        self.label_res_r_t30.config(relief="sunken",
                                    bg="#becbff",
                                    borderwidth=2,
                                    width=10,
                                    textvariable=self.r_t30_var,
                                    fg='black')
        self.label_res_r_t30.grid(row=0, column=3, padx=10, pady=10)
        self.label_xi_t30 = Label(self.frame_linealidad_t30)
        self.label_xi_t30.config(text="ξ",
                                 bg="#5893d4",
                                 borderwidth=2,
                                 relief="groove",
                                 width=4)
        self.label_xi_t30.grid(row=0, column=4, padx=10, pady=10)
        self.xi_t30_var = StringVar()
        self.label_res_xi_t30 = Label(self.frame_linealidad_t30)
        self.label_res_xi_t30.config(relief="sunken",
                                     bg="#becbff",
                                     borderwidth=2,
                                     width=10,
                                     fg='black',
                                     textvariable=self.xi_t30_var)
        self.label_res_xi_t30.grid(row=0, column=5, padx=10, pady=10)

    def construir_frame_curvatura(self):
        self.frame_curvatura = Frame(self.frame_rts)
        self.frame_curvatura.grid(row=4,
                                  column=2,
                                  pady=(0, 10),
                                  columnspan=4,
                                  sticky='e')
        self.label_curvatura = Label(self.frame_curvatura)
        self.label_curvatura.config(text="C",
                                    bg="#5893d4",
                                    borderwidth=2,
                                    relief="groove",
                                    width=4)
        self.label_curvatura.grid(row=0,
                                  column=0,
                                  padx=(0, 10),
                                  pady=10,
                                  sticky='w')
        self.curvatura_var = StringVar()
        self.label_res_curvatura = Label(self.frame_curvatura)
        self.label_res_curvatura.config(relief="sunken",
                                        borderwidth=2,
                                        bg="#becbff",
                                        width=10,
                                        textvariable=self.curvatura_var,
                                        fg='black')
        self.label_res_curvatura.grid(row=0, column=1, padx=10, pady=10)

    def get_frecuencia_central_banda_seleccionada(self):
        return float(self.banda_seleccionada.get())

    def get_tipo(self):
        return self.tipo

    def verificar_ponderacion_A(self):
        return self.ponderacion_A_checked.get()

    def desactivar(self):
        self.combobox_banda.config(state=DISABLED)
        self.checkbutton_ponderacion_A.config(state=DISABLED)
        self.boton_calcular.config(state=DISABLED)

    def activar(self):
        self.combobox_banda.config(state=NORMAL)
        self.checkbutton_ponderacion_A.config(state=NORMAL)
        self.boton_calcular.config(state=NORMAL)

    def graficar(self, nivel_respuesta_impulsional, curva_decaimiento):
        dominio_temporal_ri = nivel_respuesta_impulsional.get_dominio_temporal(
        )
        valores_ri = nivel_respuesta_impulsional.get_valores()
        dominio_temporal_cd = curva_decaimiento.get_dominio_temporal()
        valores_cd = curva_decaimiento.get_valores()
        self.limpiar_ejes()
        self.sistema_ejes.plot(dominio_temporal_ri,
                               valores_ri,
                               color='#0000ff',
                               linewidth=0.5,
                               label='Nivel respuesta impulsional')
        self.sistema_ejes.plot(dominio_temporal_cd,
                               valores_cd,
                               color="#ff0000",
                               linewidth=1,
                               label='Curva de decaimiento')
        self.sistema_ejes.legend()
        self.canvas.draw()

    def mostrar_tiempos_de_reverberacion(self, edt, t20, t30):
        self.edt_var.set(str(round(edt, 4)) + "seg")
        self.t20_var.set(str(round(t20, 4)) + "seg")
        self.t30_var.set(str(round(t30, 4)) + "seg")

    def mostrar_parametros_de_linealidad(self, edt, t20, t30, curvatura):
        self.r_edt_var.set(round(edt.get_coef_correlacion(), 4))
        self.xi_edt_var.set(str(round(edt.get_xi(), 4)) + "‰")
        self.r_t20_var.set(round(t20.get_coef_correlacion(), 4))
        self.xi_t20_var.set(str(round(t20.get_xi(), 4)) + "‰")
        self.r_t30_var.set(round(t30.get_coef_correlacion(), 4))
        self.xi_t30_var.set(str(round(t30.get_xi(), 4)) + "‰")
        self.curvatura_var.set(str(round(curvatura, 4)) + "%")

    def construir_frame_progressbar(self):
        self.pb_frame = Frame(self.frame_medicion)
        self.pb_frame.config(padx=20, pady=20)

        self.frame_calculando = Frame(self.pb_frame)
        self.frame_calculando.grid(row=0, column=0, pady=10)
        self.label_calculando = Label(self.frame_calculando)
        self.label_calculando.config(text="Calculando")
        self.label_calculando.pack(expand="True", fill="both")
        self.progressbar = Progressbar(self.pb_frame)
        self.progressbar.config(mode="indeterminate", length=250)
        self.progressbar.grid(row=1, column=0, pady=10)

    def activar_progressbar(self):
        self.pb_frame.grid(row=5, column=0)
        self.progressbar.start(10)

    def desactivar_progressbar(self):
        self.progressbar.stop()
        self.pb_frame.grid_remove()

    def redibujar_canvas(self):
        self.canvas.draw()
        self.canvas.get_tk_widget().pack()

    def ocultar_grafica(self):
        self.canvas.get_tk_widget().pack_forget()
Beispiel #38
0
class RNASeqFrame(PipelineFrame):
    def __init__(self, pipepanel, pipeline_name, *args, **kwargs):
        PipelineFrame.__init__(self, pipepanel, pipeline_name, *args, **kwargs)
        self.info = None

        eframe = self.eframe = LabelFrame(self, text="Options")
        #,fg=textLightColor,bg=baseColor)
        eframe.grid(row=5, column=1, sticky=W, columnspan=7, padx=10, pady=5)

        label = Label(eframe,
                      text="Pipeline")  #,fg=textLightColor,bg=baseColor)
        label.grid(row=3, column=0, sticky=W, padx=10, pady=5)
        PipelineLabels = [
            "Quality Control Analysis", "Differential Expression Analysis",
            "Fusion Detection", "Variant Calling"
        ]
        Pipelines = [
            "initialqcrnaseq", "rnaseq", "rnaseqfusion", "rnaseqvargerm"
        ]

        self.label2pipeline = {k: v for k, v in zip(PipelineLabels, Pipelines)}

        PipelineLabel = self.PipelineLabel = StringVar()
        self.Pipeline = StringVar()

        PipelineLabel.set(PipelineLabels[0])
        om = OptionMenu(eframe,
                        PipelineLabel,
                        *PipelineLabels,
                        command=self.option_controller)
        om.config()  #bg = widgetBgColor,fg=widgetFgColor)
        om["menu"].config()  #bg = widgetBgColor,fg=widgetFgColor)
        #om.pack(side=LEFT,padx=20,pady=5)
        om.grid(row=3, column=1, sticky=W, padx=10, pady=5)

        rReadlens = [
            'Read Length is 50', 'Read Length is 75', 'Read Length is 100',
            'Read Length is 125', 'Read Length is 150', 'Read Length is 250'
        ]
        self.rReadlen = rReadlen = StringVar()
        rReadlen.set(rReadlens[2])
        self.om2 = OptionMenu(eframe,
                              rReadlen,
                              *rReadlens,
                              command=self.option_controller)
        #self.om2.grid(row=4,column=1,sticky=W,padx=10,pady=5)

        rStrands = [
            '0, Reads are Unstranded', '1, Reads are from Sense Strand',
            '2, Reads are from Anti-Sense Strand'
        ]
        self.rStrand = rStrand = StringVar()
        rStrand.set(rStrands[0])
        self.om3 = OptionMenu(eframe,
                              rStrand,
                              *rStrands,
                              command=self.option_controller)
        #self.om3.grid(row=5,column=1,sticky=W,padx=10,pady=5)

        rDegs = [
            "no, Do not Report Differentially Expressed Genes",
            "yes, Report Differentially Expressed Genes"
        ]
        self.rDeg = rDeg = StringVar()
        rDeg.set(rDegs[0])
        self.om4 = OptionMenu(eframe,
                              rDeg,
                              *rDegs,
                              command=self.option_controller)
        self.om4.grid(row=6, column=1, sticky=W, padx=10, pady=5)

        #####################
        #Sample Threshold
        #####################
        self.sampleLF = sampleLF = LabelFrame(
            eframe, text="Low Abundance Gene Thresholds")

        self.rMincount = rMincount = StringVar()
        rMincount.set("0.5")
        self.rMinsamples = rMinsamples = StringVar()
        rMinsamples.set("2")

        #rMincount.trace('w', lambda a,b,c,x="rmincount": makejson(x))

        #Filter out genes < [5] read counts in < [2] samples
        rminsamplesL = Label(sampleLF, text="Include genes with >=")  # in")
        rmincountE = Entry(sampleLF, bd=2, width=3, textvariable=rMincount)
        rmincountL = Label(sampleLF, text="CPM in  >=")
        rminsamplesE = Entry(sampleLF, bd=2, width=3, textvariable=rMinsamples)
        rminsamplesR = Label(sampleLF, text="samples")

        rminsamplesL.grid(row=9, column=1, sticky=W, padx=10, pady=5)
        rmincountE.grid(row=9, column=2, sticky=W, padx=0, pady=5)
        rmincountL.grid(row=9, column=3, sticky=W, padx=5, pady=5)
        rminsamplesE.grid(row=9, column=4, sticky=W, padx=0, pady=5)
        rminsamplesR.grid(row=9, column=5, sticky=W, padx=10, pady=5)
        #rMinsamples.trace('w', lambda a,b,c,x="rmincount": makejson(x))

        sampleLF.grid(row=8,
                      column=0,
                      columnspan=4,
                      sticky=W,
                      padx=20,
                      pady=10)
        #####################

        self.add_info(eframe)
        self.option_controller()

    def option_controller(self, *args, **kwargs):

        PipelineFrame.option_controller(self)

        self.Pipeline.set(self.label2pipeline[self.PipelineLabel.get()])
        print(self.Pipeline.get())

        if self.Pipeline.get() == 'initialqcrnaseq':
            self.om4.grid_forget()
            self.sampleLF.grid_forget()
            self.info.grid_forget()
        elif self.Pipeline.get() == 'rnaseq':
            self.om4.grid(row=6, column=1, sticky=W, padx=10, pady=5)
            self.sampleLF.grid(row=8,
                               column=0,
                               columnspan=4,
                               sticky=W,
                               padx=20,
                               pady=10)
            self.info.grid(row=10,
                           column=0,
                           columnspan=6,
                           sticky=W,
                           padx=20,
                           pady=10)
        else:
            self.om4.grid_forget()
            self.sampleLF.grid_forget()
            self.info.grid_forget()

    def makejson_wrapper(self, *args, **kwargs):
        self.makejson(*args, **kwargs)

    def add_info(self, parent):
        if not self.info:
            self.info = LabelFrame(parent, text="Sample Information")
            self.groups_button = Button(self.info,
                                        text="Set Groups",
                                        command=self.popup_groups)
            self.contrasts_button = Button(self.info,
                                           text="Set Contrasts",
                                           command=self.popup_contrasts)

            #self.pairs_load_button.pack( side=BOTTOM, padx=5, pady=5 )
            #self.pairs_save_button.pack( side=BOTTOM, padx=5, pady=5 )

            self.groups_button.grid(row=5, column=5, padx=10, pady=5)
            self.contrasts_button.grid(row=5, column=6, padx=10, pady=5)

    def popup_groups(self):
        self.popup_window("Groups Information", "groups.tab")

    def popup_contrasts(self):
        self.popup_window("Contrasts Information", "contrasts.tab")

    def popup_window(self, text, filename):
        top = Toplevel()

        info = LabelFrame(top, text=text)  #"Group Information")
        info_text = Text(
            info,
            width=50,
            height=8,
            #bg=projectBgColor,
            #fg=projectFgColor,
            font=("nimbus mono bold", "11"))

        def savefunc():
            self.writepaste(filename, info_text)

        def loadfunc():
            self.readpaste(filename, info_text)

        info_save_button = Button(info, text="Save", command=savefunc)
        info_load_button = Button(info, text="Load", command=loadfunc)

        #self.pairs_load_button.pack( side=BOTTOM, padx=5, pady=5 )
        #self.pairs_save_button.pack( side=BOTTOM, padx=5, pady=5 )

        info_load_button.grid(row=5, column=5, padx=10, pady=5)
        info_save_button.grid(row=5, column=6, padx=10, pady=5)
        info_text.grid(row=1,
                       rowspan=3,
                       column=1,
                       columnspan=7,
                       padx=5,
                       pady=5)

        info.grid(row=7, column=0, columnspan=6, sticky=W, padx=20, pady=10)
        top.focus_force()

    def makejson(self, *args):
        #print(args[0])
        caller = args[0]
        #global PD
        #global UnitsBak
        #global RGbak
        D = dict()
        try:
            F = open(self.workpath.get() + "/samples", "r")
            f = F.read().split("\n")
            F.close()
            for line in f:
                L = line.split()
                a = L.pop(0)
                D[a] = L
                samples = D
        except:
            samples = {"na": "na"}

        D = dict()
        try:
            F = open(self.workpath.get() + "/pairs", "r")
            f = F.read().split()
            F.close()
            for i in range(0, len(f), 2):
                #            a=f[i].split(".")[0]
                #            b=f[i+1].split(".")[0]
                a = f[i]
                b = f[i + 1]

                D[a + "+" + b] = [a, b]

            pairs = D
        except:
            pairs = {"na": "na"}

        D = dict()
        try:
            F = open(self.workpath.get() + "/contrasts.tab", "r")
            #        f=F.read().split('\n')
            #        F.close()
            #        D["rsamps"]=f[0].split()
            #        D["rgroups"]=f[1].split()
            #        D["rcontrasts"]=f[2].split()
            #        D["rlabels"]=f[3].split()
            f = F.readlines()
            F.close()
            ##        sampl=[]
            ##        grp=[]
            cont = []
            ##        lbl=[]
            for x in f:
                if len(x.split()) == 2:
                    cont.append(x.split()[0])
                    cont.append(x.split()[1])
            D["rcontrasts"] = cont
            #        contrasts["rcontrasts"]=cont
            contrasts = D
        except:
            contrasts = {"rcontrasts": "na"}
    ##        contrasts={"rsamps":"na","rgroups":"na","rcontrasts":"na","rlabels":"na"}
    ##------
        D = dict()
        try:
            F = open(self.workpath.get() + "/groups.tab", "r")
            f = F.readlines()
            F.close()
            sampl = []
            grp = []
            #        cont=[]
            lbl = []
            for x in f:
                #           if len(x.split()) == 4 or len(x.split()) == 3:
                if len(x.split()) == 3:
                    sampl.append(x.split()[0])
                    grp.append(x.split()[1])
                    lbl.append(x.split()[2])
            D["rsamps"] = sampl
            D["rgroups"] = grp
            D["rlabels"] = lbl
            #        D["rcontrasts"]="na"
            #        contrasts=D
            groups = D
        except:
            #        contrasts={"rsamps":"na","rgroups":"na","rcontrasts":"na","rlabels":"na"}
            groups = {"rsamps": "na", "rgroups": "na", "rlabels": "na"}

    ##------
        D = dict()
        FT = filetype  #.get()
        #    p = Popen("ls "+workpath.get()+"/*."+FT, shell=True, stdin=PIPE, stdout=PIPE, stderr=DEVNULL, close_fds=True)
        p = Popen("find " + self.workpath.get() +
                  " -maxdepth 1 -type l -printf '%f\n' ",
                  shell=True,
                  stdin=PIPE,
                  stdout=PIPE,
                  stderr=DEVNULL,
                  close_fds=True)
        a = p.stdout.read().decode(encoding='UTF-8').split("\n")

        RG = dict()
        b = a.pop()
        #    tkinter.messagebox.showerror("",a)
        #    if freezeunits.get()=="no":
        for i in a:

            key = re.sub(".realign", "", i.split("/")[-1])
            key = re.sub(".bai", "", key)
            key = re.sub(".bam", "", key)
            key = re.sub(".sam", "", key)
            key = re.sub(".recal", "", key)
            key = re.sub(".dedup", "", key)
            key = re.sub(".sorted", "", key)
            key = re.sub(".fin", "", key)
            key = re.sub("\.R[12]", "", key)
            key = re.sub("_R[12]", "", key)
            key = re.sub(".fastq", "", key)
            key = re.sub(".gz", "", key)
            #        key=re.sub("[\._](R[12]\.)*"+FT+"$","",i.split("/")[-1])
            #        key=re.sub(".R[12]."+FT+"$","",i.split("/")[-1])
            #        key=re.sub("([._]R[12][._])*([fin|sorted|dedup|recal|realign])*\.{0}$".format(FT),"",i.split("/")[-1])
            D[key] = key
            RG[key] = {
                'rgsm': key,
                'rglb': 'na',
                'rgpu': 'na',
                'rgpl': 'ILLUMINA',
                'rgcn': 'na'
            }
        units = D
        UnitsBak = D

        try:
            F = open(self.workpath.get() + "/rg.tab", "r")
            f = F.read().splitlines()
            F.close()
            for theLine in f:
                if not re.match("^ID", theLine):
                    (rgid, rgsm, rglb, rgpl, rgpu, rgcn) = theLine.split("\t")
                    RG[rgid] = {
                        'rgsm': rgsm,
                        'rglb': rglb,
                        'rgpu': rgpu,
                        'rgpl': rgpl,
                        'rgcn': rgcn
                    }
        except:
            pass

        RGbak = RG
        #     else:
        #         units=UnitsBak
        #         RG=RGbak
        #
        PD = dict()

        smparams = []

        for i in range(len(self.parameters)):

            if cp[i].var.get() == "1":
                smparams.append(parameters[i])

        AD = eval(
            open(join(PIPELINER_HOME,
                      self.annotation.get() + ".json"), "r").read())

        SD = AD['references']['rnaseq']['STARDIR']
        #    tkinter.messagebox.showinfo("initLock","SD={0}".format(SD))
        gi = self.global_info
        PD = {
            'project': {
                'pfamily':
                gi.pfamily.get(),
                'units':
                units,
                'samples':
                samples,
                'pairs':
                pairs,
                'id':
                gi.eprojectid.get(),
                'pi':
                gi.epi.get(),
                'pipehome':
                gi.pipehome.get(),
                'organism':
                gi.eorganism.get(),
                'analyst':
                gi.eanalyst.get(),
                'poc':
                gi.epoc.get(),
                'pipeline':
                self.Pipeline.get(),
                'version':
                "1.0",
                'annotation':
                gi.annotation.get(),
                'datapath':
                self.datapath.get(),
                'targetspath':
                self.targetspath.get(),
                'nends':
                self.nends,
                'filetype':
                filetype,
                'binset':
                "standard-bin",
                'username':
                gi.euser.get(),
                'flowcellid':
                gi.eflowcell.get(),
                'platform':
                gi.eplatform.get(),
                'custom':
                customRules,
                'efiletype':
                efiletype,
                'workpath':
                self.workpath.get(),
                'batchsize':
                batchsize,
                "smparams":
                smparams,
                "rgid":
                RG,
                "cluster":
                "cluster_medium.json",
                "description":
                gi.description.get('1.0', END),
                "technique":
                gi.technique.get(),
                "TRIM":
                "yes",
                "groups":
                groups,
                "contrasts":
                contrasts,
                "SJDBOVERHANG":
                self.rReadlen.get().split(" ")[3],
                "STRANDED":
                self.rStrand.get().split(",")[0],
                "DEG":
                self.rDeg.get().split(",")[0].lower(),
                "STARSTRANDCOL":
                "{0}".format(int(self.rStrand.get().split(",")[0]) + 2),
                "MINSAMPLES":
                self.rMinsamples.get(),
                "MINCOUNTGENES":
                self.rMincount.get(),
                "MINCOUNTJUNCTIONS":
                self.rMincount.get(),
                "MINCOUNTGENEJUNCTIONS":
                self.rMincount.get(),
                "STARDIR":
                SD + self.rReadlen.get().split(" ")[3],
                "PICARDSTRAND": [
                    "NONE", "FIRST_READ_TRANSCRIPTION_STRAND",
                    "SECOND_READ_TRANSCRIPTION_STRAND"
                ][int(self.rStrand.get().split(",")[0])]
            }
        }

        J = json.dumps(PD, sort_keys=True, indent=4, ensure_ascii=True)
        gi.jsonconf.delete("1.0", END)
        gi.jsonconf.insert(INSERT, J)
        self.saveproject(gi.jsonconf.get("1.0", END))
Beispiel #39
0
image = PIL.Image.new('RGB', (screen_width, screen_height), 'white')
drawer = ImageDraw.Draw(image)

variable = StringVar(root)
shr = OptionMenu(root, variable, 15, 1, 5, 10, 15, 20, 25, 30, 35, 40, 50, 60, 70, 80, 90, 100)

bytton = tkinter.ttk.Button(root, text='Выбрать цвет', command=color)
btn = tkinter.ttk.Button(root, text='Очистить всё', command=dalate)
btno = tkinter.ttk.Button(root, text='Заливка', command=zal)
lable = tkinter.ttk.Label(root, text='Размер кисти:')
lable_2 = tkinter.ttk.Label(root, text='Цвет кисти (заливки):')
lable_3 = tkinter.ttk.Label(root, text='Название файла:')
btn2 = tkinter.ttk.Button(root, text='Save', command=save)
text = tkinter.ttk.Entry()
canvas.bind("<B1-Motion>", draw)
canvas.bind('<Button-1>', draw)

bytton.grid(column=59, row=1)
lable_3.grid(column=1, row=0, pady=7)
text.grid(column=3, row=0)
btn2.grid(column=9, row=0)
btn.grid(column=19, row=0, padx=100)
btno.grid(column=29, row=0, padx=50)
lable.grid(column=39, row=0, padx=50)
shr.grid(column=39, row=1, padx=50)
lable_2.grid(column=59, row=0, padx=25)
canvas.place(x=0, y=70)
cn.grid(column=69, row=1)

root.mainloop()
Beispiel #40
0
class SelectorWindow(Frame):
    """
        GUI Class extending the tkinter.Frame class
    """
    TIMEOUTS = {
        '1 hour ': 3600,
        '2 hours': 7200,
        '3 hours': 10800,
        'Infinite': -1,
    }

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.__playlist = Playlist()
        self.__controller = PiWallController()
        self.__dropdown_selection = StringVar()
        self.__timeout_selection = StringVar()
        self.__command_thread = Thread(target=self.__controller.run_commands,
                                       args=(self.__playlist, ))
        self.grid()
        self.create_video_file_dropdown()
        self.create_timeout_dropdown()
        self.create_display_box()
        self.create_add_button()
        self.create_delete_button()
        self.create_play_button()
        self.create_reboot_button()
        self.create_status_label()
        self.create_stop_button()

    def create_video_file_dropdown(self):
        """
            Creates the dropdown to display the video files from
        """
        videos = self.__controller.get_video_file_list()

        if videos:
            self.__dropdown_selection.set(videos[0])
        else:
            videos.append(None)

        self.video_dropdown = OptionMenu(None, self.__dropdown_selection,
                                         *videos)
        self.video_dropdown.config(width=10)
        self.video_dropdown.grid(row=0, column=0)

    def create_timeout_dropdown(self):
        """
            Creates the dropdown that displays the timeouts
        """
        timeouts = list(self.TIMEOUTS.keys())
        timeouts.sort()
        self.__timeout_selection.set(timeouts[0])
        self.timeout_dropdown = OptionMenu(None, self.__timeout_selection,
                                           *timeouts)
        self.timeout_dropdown.config(width=5)
        self.timeout_dropdown.grid(row=0, column=1)

    def create_display_box(self):
        """
            Creates display box that displays all current items in the playlist
        """
        self.display_box = Listbox(width=30, height=10)
        self.display_box.grid(row=0, column=2, columnspan=2)

    def create_play_button(self):
        """
            Creates the play button
        """
        self.submit_button = Button(text="Play", width=10)
        self.submit_button['command'] = self.play_wall
        self.submit_button.grid(row=1, column=2, pady=5)

    def create_add_button(self):
        """
            Creates the button to add the current values in the video and timeout dropdown
            into the playlist
        """
        self.add_button = Button(text='Add', fg='green', width=10)
        self.add_button['command'] = self.update_display_box
        self.add_button.grid(row=1, column=0, pady=5)

    def create_delete_button(self):
        """
            Creates delete button to delete items from display blox
        """
        self.delete_button = Button(text='Delete', fg='red', width=10)
        self.delete_button['command'] = self.delete_selected_item
        self.delete_button.grid(row=1, column=1, pady=5)

    def create_reboot_button(self):
        """
            Creates button that reboots the pi's
        """
        self.reboot_button = Button(text='Reboot Tiles', fg='red', width=10)
        self.reboot_button['command'] = self.reboot_pressed
        self.reboot_button.grid(row=1, column=3, pady=5)

    def create_status_label(self):
        """
            Creates label to display current status of the wall
        """
        self.status_label = Label(relief="ridge", width=11)
        self.set_status_label(0)
        self.status_label.grid(row=2, column=3, pady=5)

    def create_stop_button(self):
        """
            Creates stop button to stop PiWall
        """
        self.stop_button = Button(text='Stop Playing')
        self.set_status_label(0)
        self.stop_button['command'] = self.stop_pressed
        self.stop_button.grid(row=2, column=2, pady=5)

    def delete_selected_item(self):
        """
            Deletes the currently selected item from the displaybox
        """
        self.__playlist.remove_playlist_item(self.display_box.curselection())
        self.display_box.delete(self.display_box.curselection())

    def play_wall(self):
        """
            Submits ths form to be played on the pi's
        """
        if self.__playlist.is_empty():
            return
        self.set_status_label(1)
        self.display_box.delete(0, END)
        # If there is a thread running, we need to stop the wall, which will
        # end the thread
        if self.__command_thread.isAlive():
            print("Stopping Wall")
            self.__controller.stop_wall()
            self.__command_thread.join()
        self.__command_thread = Thread(target=self.__controller.run_commands,
                                       args=(self.__playlist, ))
        self.__command_thread.start()

    def update_display_box(self):
        """
            Button listener for the Add Button (create_add_button)
        """
        video_file = self.__dropdown_selection.get()
        timeout = self.__timeout_selection.get()
        self.__playlist.add_playlist_item(video_file, self.TIMEOUTS[timeout])
        self.display_box.insert(END, "{0}   {1}".format(timeout, video_file))

    def stop_pressed(self):
        """
            Button listener for the Stop Button (create_stop_button)
        """
        self.__controller.stop_wall()
        self.set_status_label(0)

    def reboot_pressed(self):
        """
            Button listener for the Reboot Button (create_reboot_button)
        """
        self.set_status_label(0)
        self.__controller.reboot_pis()
        return True

    def set_status_label(self, state):
        """
            Updates the status label to the current status of the PiWall
        """
        if state == 1:
            self.status_label.config(text='Playing', fg='green')
            return True
        elif state == 0:
            self.status_label.config(text='Not Playing', fg='red')
            return True
        else:
            Exception(
                'Status label state {0} not supported. Try 1 or 2'.format(
                    state))

    def get_controller(self):
        """
            Returns the piwallcontrollers
        """
        return self.__controller
Beispiel #41
0
    def popup_window_contrast(self) :
        text = "Comparing ChIP-seq Peaks"
        contrast_fn = join(self.workpath.get(),self.contrast_fn)
        peakinfo_fn  = join(self.workpath.get(),self.peakinfo_fn)
        NA='N/A'
        
        try :
            groups = list(set([l.split('\t')[-1].strip() for l in open(peakinfo_fn) if l.split('\t')[-1].strip()]))
            if len(groups) < 2 :
                showwarning( 'WARNING!', "More than one groups need to be fefined in Peak Information File!" )
                print( 'groups:', groups )
                return
            
        except IOError :
            showerror( 'Error', "Did you set peak information?" )
            print('Error:', 'Cannot process peakcall.tab file:')
            return
        
        top = Toplevel()
        info = LabelFrame(top, text=text )#"Group Information")
        
        print( groups )
        contrast_vars = []
        contrast_menus = []
        n = 0
        groups.insert(0, NA)
        for i in range( int((len(groups)-1)*(len(groups)-2)/2) ):
            n = n + 1
            v1, v2 = StringVar(), StringVar()
            contrast_vars.append( [v1, v2] )
            o1, o2 = OptionMenu(info, v1, *groups), OptionMenu(info, v2, *groups)
            contrast_menus.append( [o1, o2] )

            v1.set(NA)
            v2.set(NA)
            vslabel = Label(info, text="  VS  ")

            o1.grid( row=n, column=0, padx=4, pady=1 )
            o2.grid( row=n, column=2, padx=4, pady=1 )
            vslabel.grid( row=n, column=1, padx=4, pady=1 )

        def savefunc() :
            info_text = StringIO()
            for v1, v2 in contrast_vars :
                v1 = v1.get() if v1.get() != NA else ""
                v2 = v2.get() if v2.get() != NA else ""
                
                if v1 and v2 :
                    pass
                elif v1 or v2 :
                    showerror( 'Error', "None or Both columns should be selected!" )
                    return
                else:
                    continue
                    
                print( v1, v2, file=info_text, sep="\t" )
            
            fp = open( contrast_fn, 'w' )
            fp.write( info_text.getvalue() )
            fp.close()
                              
        
        def loadfunc() :
            #self.readpaste( filename, info_text ) 
            for i, l in enumerate(open( contrast_fn )) :
                v1, v2 = l.split('\t')
                v1 = v1.strip()
                v2 = v2.strip()
                
                if v1 :
                    try : assert v1 in groups
                    except :
                        showwarning('WARNING', 'Group name is not in the selection list!' )
                        print( 'v1:',v1 ) 
                        print( 'group:', groups )
                        continue
                
                if v2 :
                    try: assert v2 in groups
                    except :
                        showwarning('WARNING', 'Group name is not in the selection list!' )
                        print( 'v2:',v2 ) 
                        print( 'group:', groups )
                        continue
                
                contrast_vars[i][0].set(v1)
                contrast_vars[i][1].set(v2)
                
        
        def clearfunc() :
            for v1, v2 in contrast_vars :
                v1.set(NA)
                v2.set(NA)
                
        
        info_clear_button = Button(top, 
                                  text="Clear", 
                                  command = clearfunc )
        info_save_button = Button(top, 
                                  text="Save", 
                                  command = savefunc )
        info_load_button = Button(top,
                                  text="Load",
                                  command = loadfunc )

        #self.pairs_load_button.pack( side=BOTTOM, padx=5, pady=5 )
        #self.pairs_save_button.pack( side=BOTTOM, padx=5, pady=5 )

        info_clear_button.grid( row=5, column=3, padx=10, pady=5 )
        info_load_button.grid( row=5, column=4, padx=10, pady=5 )
        info_save_button.grid( row=5, column=5, padx=10, pady=5 )


        info.grid(row=7,column=0, columnspan=6, sticky=W, padx=20, pady=10 )
        top.focus_force()
Beispiel #42
0
Datei: main.py Projekt: kr1/roqba
class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.send_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.bind((host, port))
        self.grid()
        self.columnconfigure(0, minsize=100)
        self.columnconfigure(1, minsize=200)
        self.columnconfigure(2, minsize=200)
        self.columnconfigure(3, minsize=150)
        self.columnconfigure(4, minsize=150)
        self.columnconfigure(5, minsize=150)
        self.columnconfigure(6, minsize=150)
        self.create_widgets()
        self.settables = self.assemble_settables()
        self.gui_logger = logging.getLogger('gui')
        self.request_update()

    def create_widgets(self):
        self.create_monitor()
        self.create_check_buttons()
        self.create_ranges()
        self.create_scales()
        self.create_radio_buttons()
        self.create_voices()
        self.quitButton = Button(self, text='Quit', command=self.quit)
        self.quitButton.grid(columnspan=7, sticky=E + W)

    def assemble_settables(self):
        settables = self.winfo_children()
        for w in settables:
            settables += w.winfo_children()
        return [w for w in settables if w.__class__.__name__ in ['Scale', 'Checkbutton']]

    def create_radio_buttons(self):
        # Scale related
        entries = ['DIATONIC', 'HARMONIC', 'MELODIC', 'PENTATONIC', 'PENTA_MINOR',
                   'GREEK_CHROMATIC', 'GREEK_ENHARMONIC']
        self.scale = StringVar()
        self.scale.set('DIATONIC')
        self.rb_frame = Frame(self)
        for e in entries:
            rb = Radiobutton(self.rb_frame, value=e, text=e, anchor=W,
                             command=self.send_scale, variable=self.scale)
            rb.grid(row=len(self.rb_frame.winfo_children()), sticky=W)
        self.rb_frame.grid(column=1, row=len(self.grid_slaves(column=1)), rowspan=3)

    def create_monitor(self):
        self.monitor_frame = LabelFrame(self, text="Monitor and Transport")
        this_cycle = Scale(self.monitor_frame, label='cycle_pos', orient=HORIZONTAL,
                           from_=1, to=16, resolution=1)
        this_cycle.disable, this_cycle.enable = (None, None)
        this_cycle.ref = 'cycle_pos'
        this_cycle.grid(column=0, row=0, sticky=E + W)
        self.updateButton = Button(self.monitor_frame,
                                   text='Reload all Settings',
                                   command=self.request_update)
        self.updateButton.grid(row=1, sticky=E + W)
        self.ForceCaesuraButton = Button(self.monitor_frame,
                                         text='Force Caesura',
                                         command=self.force_caesura)
        self.ForceCaesuraButton.grid(row=2, sticky=E + W)
        self.saveBehaviourButton = Button(self.monitor_frame,
                                          text='Save current behaviour',
                                          command=self.request_saving_behaviour)
        self.saveBehaviourButton.grid(row=3, sticky=E + W)
        self.saveBehaviourNameEntry = Entry(self.monitor_frame)
        self.saveBehaviourNameEntry.grid(row=4, sticky=E + W)
        self.saveBehaviourNameEntry.bind('<KeyRelease>', self.request_saving_behaviour)
        self.selected_behaviour = StringVar()
        self.selected_behaviour.trace('w', self.new_behaviour_chosen)
        self.savedBehavioursMenu = OptionMenu(self.monitor_frame,
                                              self.selected_behaviour, None,)
        self.savedBehavioursMenu.grid(row=5, sticky=E + W)
        self.monitor_frame.grid(column=0, row=10, sticky=E + W)

    def request_update(self):
        self.send({'sys': 'update'})

    def request_saving_behaviour(self, event=None):
        """callback for save behaviour button and textentry"""
        if event and event.widget == self.saveBehaviourNameEntry:
            if event.keysym == 'Return':
                name = self.saveBehaviourNameEntry.get()
                self.saveBehaviourNameEntry.delete(0, len(name))
            else:
                return
        else:  # button was pressed
            name = self.saveBehaviourNameEntry.get()
        if name:
            self.send({'sys': ['save_behaviour', name]})

    def force_caesura(self):
        self.send({'force_caesura': True})

    def create_voices(self):
        voice_ids = ['1', '2', '3', '4']
        SCALES = OrderedDict([
                  ('pan_pos', {'min': -1, 'max': 1, 'start': 0.5, 'res': 0.001}),
                  ('volume', {'min': 0, 'max': 1, 'start': 0.666, 'res': 0.001}),
                  ('slide_duration_msecs', {'min': 0, 'max': 2000, 'start': 60, 'res': 1}),
                  ('slide_duration_prop', {'min': 0, 'max': 2, 'start': 0.666, 'res': 0.001}),
                  ('binaural_diff', {'min': 0, 'max': 66, 'start': 0.2, 'res': 0.01})
                ])

        for vid in voice_ids:
            counter = 0
            for sca in SCALES:
                name = 'voice_' + vid + '_' + sca
                setattr(self, 'min_' + name, SCALES[sca]['min'])
                setattr(self, 'max_' + name, SCALES[sca]['max'])
                this_sca = Scale(self, label=sca, orient=HORIZONTAL,
                                 from_=getattr(self, 'min_' + name),
                                 to=getattr(self, 'max_' + name),
                                 resolution=SCALES[sca]['res'])
                this_sca.enable = ('enable' in list(SCALES[sca].keys()) and
                                   SCALES[sca]['enable'] or None)
                this_sca.disable = ('disable' in list(SCALES[sca].keys()) and
                                    SCALES[sca]['disable'] or None)
                this_sca.grid(column=int(2 + int(vid)), row=counter, sticky=E + W)
                this_sca.bind("<ButtonRelease>", self.scale_handler)
                this_sca.ref = name
                counter += 1
        CHECK_BUTTONS = OrderedDict(
                 [('mute', False),
                  ('automate_binaural_diffs', True),
                  ('automate_note_duration_prop', True),
                  ('use_proportional_slide_duration', {'val': True, 'label': 'proportional slide'}),
                  ('automate_pan', True),
                  ('automate_wavetables', True)])
        for vid in voice_ids:
            counter = 0
            cb_frame = LabelFrame(self, text="Voice {0} - Automation".format(vid))
            setattr(self, 'voice_' + vid + '_cb_frame', cb_frame)
            for cb in CHECK_BUTTONS:
                options = CHECK_BUTTONS[cb]
                name = 'voice_' + vid + '_' + cb
                if isinstance(options, dict) and 'label' in list(options.keys()):
                    label = options['label']
                else:
                    label = cb[9:] if cb[:9] == 'automate_' else cb
                setattr(self, name, IntVar(
                    value=type(options) == dict and options['val'] or options))
                self.this_cb = Checkbutton(cb_frame, text=label, variable=getattr(self, name))
                self.this_cb.bind('<Button-1>', self.check_boxes_handler)
                self.this_cb.disable = None
                self.this_cb.grid(sticky=W, column=0, row=counter)
                self.this_cb.ref = name
                counter += 1
            # add trigger wavetable-button
            trigWavetableButton = Button(cb_frame, text='Next Wavetable')
            trigWavetableButton.bind('<Button-1>', self.trigger_waveform_handler)
            trigWavetableButton.ref = 'voice_' + vid + "_trigger_wavetable"
            trigWavetableButton.grid(row=counter)
            cb_frame.grid(column=int(vid) + 2, row=5, sticky=E + W + N, rowspan=8)
        for vid in voice_ids:
            generation_types = ["random", "random_harmonic", "harmonic"]
            partial_pools = ["even", "odd", "all"]
            prefix = 'voice_' + vid + '_'
            types_name = prefix + 'wavetable_generation_type'
            pools_name = prefix + 'partial_pool'
            setattr(self, types_name, StringVar())
            getattr(self, types_name).set("random")
            setattr(self, pools_name, StringVar())
            getattr(self, pools_name).set("all")
            target_frame = getattr(self, 'voice_' + vid + '_cb_frame')
            gen_typ_frame = LabelFrame(target_frame, text="type")
            gen_typ_frame.grid(row=len(target_frame.winfo_children()), sticky=W)
            for gen_t in generation_types:
                gen_t_entry = Radiobutton(gen_typ_frame, value=gen_t, text=gen_t, anchor=W,
                                          variable=getattr(self, types_name))
                gen_t_entry.bind('<ButtonRelease-1>', self.wt_handler)
                gen_t_entry.ref = types_name
                gen_t_entry.grid(row=len(gen_typ_frame.winfo_children()), sticky=W)
            pp_frame = LabelFrame(target_frame, text="harmonics")
            for pp in partial_pools:
                pp_entry = Radiobutton(pp_frame, value=pp, text=pp, anchor=W,
                                       variable=getattr(self, pools_name))
                pp_entry.bind('<ButtonRelease-1>', self.wt_handler)
                pp_entry.ref = pools_name
                pp_entry.grid(row=len(pp_frame.winfo_children()), sticky=E + W)
            this_num_partials = Scale(pp_frame, label='number of harmonics', orient=HORIZONTAL,
                                      from_=1, to=24, resolution=1)
            this_num_partials.ref = prefix + 'num_partials'
            this_num_partials.grid(column=0, row=len(pp_frame.winfo_children()), sticky=E + W)
            this_num_partials.bind("<ButtonRelease>", self.scale_handler)
            pp_frame.grid(row=len(target_frame.winfo_children()), sticky=E + W)

    def wt_handler(self, event):
        print(event.widget.tk)
        ref = event.widget.ref
        self.send({ref: getattr(self, ref).get()})

    def create_check_buttons(self):
        self.cb_frame = LabelFrame(self, text="Global Settings")
        for cb in CHECK_BUTTONS:
            label = cb
            target_parent = self.cb_frame
            if isinstance(CHECK_BUTTONS[cb], dict) and 'sub_frame' in list(CHECK_BUTTONS[cb].keys()):
                target_parent = getattr(self, CHECK_BUTTONS[cb]['sub_frame'])
            setattr(self, cb, IntVar(value=type(CHECK_BUTTONS[cb]) == dict and
                                     CHECK_BUTTONS[cb]['val'] or
                                     CHECK_BUTTONS[cb]))
            self.this_cb = Checkbutton(target_parent, text=label, variable=getattr(self, cb))
            self.this_cb.bind('<Button-1>', self.check_boxes_handler)
            self.this_cb.disable = (type(CHECK_BUTTONS[cb]) == dict and
                                    'disable' in list(CHECK_BUTTONS[cb].keys()))
            self.this_cb.grid(sticky=W, column=0, row=len(target_parent.winfo_children()))
            self.this_cb.ref = cb
        for but in GLOBAL_BUTTONS:
            label = but
            ele = GLOBAL_BUTTONS[but]
            this_but = Button(self.cb_frame, text=but)
            this_but.bind('<ButtonRelease-1>', getattr(self, ele['handler']))
            this_but.ref = but
            this_but.grid(sticky=W, column=0, row=len(self.cb_frame.winfo_children()))
        self.cb_frame.grid(column=0, row=0, rowspan=10, sticky=N)

    def new_behaviour_chosen(self, a, b, c):
        self.send({'sys': ['change_behaviour', self.selected_behaviour.get()]})

    def set_value(self, name, val):
        '''sets a widget to the specified value

        various different widget types need custom setting functionality'''

        direct = ['scale', 'wavetable_generation_type', 'partial_pool']
        if [x for x in direct if match("(voice_\d_|)" + x, name)]:
            self.gui_logger.info("setting: '{0}' to '{1}' in GUI".format(name, val))
            getattr(self, name).set(val)
            return
        if name == 'saved_behaviours' and len(val):
            self.savedBehavioursMenu.destroy()
            self.savedBehavioursMenu = OptionMenu(self.monitor_frame,
                                                  self.selected_behaviour, *sorted(val))
            self.savedBehavioursMenu.grid(row=5, sticky=E + W)
            return
        for w in self.settables:
            typ = w.__class__.__name__
            if w.ref == name:
                # print "setting '{0}' of type: '{1}' to: {2}".format(name, typ, val)
                if typ == 'Scale':
                    w.set(val)
                elif typ == "Checkbutton":
                    w.select() if val else w.deselect()

    def check_boxes_handler(self, event):
        '''handles checkbox events.

        shows and hides gui elements according to their enable/disable fields'''
        # print event.__dict__
        # print event.widget.__dict__
        ref = event.widget.ref
        val = not getattr(self, ref).get()  # because is read before the var is changed
        self.send({ref: val})
        # print ref, val
        # handle gui elements
        # enable/disable functionality temporarily(?) commented on:
        # Wed Aug 17 09:39:54 CEST 2011
#        if event.widget.disable:
#            for w in self.children.values():
#
#                # this try clause is for debugging, remove when stable
#                try:
#                    w.ref
#                    #print w.ref
#                except:
#                    pass
#                if (w.__class__.__name__ == 'Scale' and
#                    (w.disable or w.enable)):
#                    if w.disable == ref:
#                        if val:
#                            w.grid()
#                        else:
#                            w.grid_remove()
#                    elif w.enable == ref:
#                        if val:
#                            w.grid_remove()
#                        else:
#                            w.grid()
#                    #print w.disable, w.enable

    def create_scales(self):
        counter = 0
        for sca in SCALES:
            label = SCALES[sca]['label'] if 'label' in list(SCALES[sca].keys()) else sca
            setattr(self, 'min_' + sca, SCALES[sca]['min'])
            setattr(self, 'max_' + sca, SCALES[sca]['max'])
            self.this_scale = Scale(self, label=label, orient=HORIZONTAL,
                                    from_=getattr(self, 'min_' + sca),
                                    to=getattr(self, 'max_' + sca),
                                    resolution=SCALES[sca]['res'])
            self.this_scale.set(SCALES[sca]['start'])
            self.this_scale.enable = ('enable' in list(SCALES[sca].keys()) and
                                      SCALES[sca]['enable'] or None)
            self.this_scale.disable = ('disable' in list(SCALES[sca].keys()) and
                                       SCALES[sca]['disable'] or None)
            if 'pos' in list(SCALES[sca].keys()):
                pos = SCALES[sca]['pos']
                col = pos['c']
                row = pos['r']
            else:
                row = counter
                col = 1
                counter += 1
            self.this_scale.grid(column=col, row=row, sticky=E + W)
            self.this_scale.ref = sca
            self.this_scale.bind("<ButtonRelease>", self.scale_handler)

    def scale_handler(self, event):
        self.send({event.widget.ref: event.widget.get()})
        self.gui_logger.info("handling scale: {0}, with new value: {1}".format(
                  event.widget.ref, event.widget.get()))

    def trigger_waveform_handler(self, event):
        self.send({event.widget.ref: True})
        # print event.widget.ref, "- triggering wavetable"

    def send_scale(self):
        do = {'scale': self.scale.get()}
        self.send(do)

    def send(self, msg):
        self.gui_logger.info("sending: {0}".format(msg))
        self.send_sock.sendto(json.dumps(msg), (remote_host, send_port))

    def create_ranges(self):
        counter = 0
        for ran in RANGES:
            setattr(self, 'min_' + ran, RANGES[ran]['min'])
            setattr(self, 'max_' + ran, RANGES[ran]['max'])
            self.this_min_scale = Scale(self, label='min ' + ran, orient=HORIZONTAL,
                                        from_=getattr(self, 'min_' + ran),
                                        to=getattr(self, 'max_' + ran),
                                        resolution=RANGES[ran]['res'])
            self.this_max_scale = Scale(self, label='max ' + ran, orient=HORIZONTAL,
                                        from_=getattr(self, 'min_' + ran),
                                        to=getattr(self, 'max_' + ran),
                                        resolution=RANGES[ran]['res'])
            self.this_min_scale.set(RANGES[ran]['min_start'])
            self.this_max_scale.set(RANGES[ran]['max_start'])
            self.this_min_scale.enable = ('enable' in list(RANGES[ran].keys()) and
                                          RANGES[ran]['enable'] or None)
            self.this_min_scale.disable = ('disable' in list(RANGES[ran].keys()) and
                                           RANGES[ran]['disable'] or None)
            self.this_max_scale.enable = ('enable' in list(RANGES[ran].keys()) and
                                          RANGES[ran]['enable'] or None)
            self.this_max_scale.disable = ('disable' in list(RANGES[ran].keys()) and
                                           RANGES[ran]['disable'] or None)
            self.this_min_scale.grid(column=2, row=counter, sticky=E + W)
            self.this_max_scale.grid(column=2, row=counter + 1, sticky=E + W)
            self.this_min_scale.ref = 'min_' + ran
            self.this_max_scale.ref = 'max_' + ran
            self.this_min_scale.bind("<ButtonRelease>", self.scale_handler)
            self.this_max_scale.bind("<ButtonRelease>", self.scale_handler)
            counter += 2

    def socket_read_handler(self, file, mask):
        data_object = json.loads(file.recv(1024))
        do = list(data_object.items())[0]
        self.set_value(do[0], do[1])
Beispiel #43
0
    def __init__(self, master, gconf, directory=None):
        self.master = master

        self.initialized = False

        self.master.bind('<Return>', self.infer)
        self.master.bind('<Escape>', lambda a: self.master.quit())
        self.master.protocol('WM_DELETE_WINDOW', self.quit)

        self.dir = os.path.abspath(ifnone(directory, ifnone(gconf['prev_query_path'], os.getcwd())))

        self.frame = Frame(master)
        self.frame.pack(fill=BOTH, expand=1)
        self.frame.columnconfigure(1, weight=1)

        row = 0
        # pracmln project options
        Label(self.frame, text='PRACMLN Project: ').grid(row=row, column=0,
                                                         sticky='ES')
        project_container = Frame(self.frame)
        project_container.grid(row=row, column=1, sticky="NEWS")

        # new proj file
        self.btn_newproj = Button(project_container, text='New Project...', command=self.new_project)
        self.btn_newproj.grid(row=0, column=1, sticky="WS")

        # open proj file
        self.btn_openproj = Button(project_container, text='Open Project...', command=self.ask_load_project)
        self.btn_openproj.grid(row=0, column=2, sticky="WS")

        # save proj file
        self.btn_updateproj = Button(project_container, text='Save Project...', command=self.noask_save_project)
        self.btn_updateproj.grid(row=0, column=3, sticky="WS")

        # save proj file as...
        self.btn_saveproj = Button(project_container, text='Save Project as...', command=self.ask_save_project)
        self.btn_saveproj.grid(row=0, column=4, sticky="WS")

        # grammar selection
        row += 1
        Label(self.frame, text='Grammar: ').grid(row=row, column=0, sticky='E')
        grammars = ['StandardGrammar', 'PRACGrammar']
        self.selected_grammar = StringVar()
        self.selected_grammar.trace('w', self.settings_setdirty)
        l = OptionMenu(*(self.frame, self.selected_grammar) + tuple(grammars))
        l.grid(row=row, column=1, sticky='NWE')

        # logic selection
        row += 1
        Label(self.frame, text='Logic: ').grid(row=row, column=0, sticky='E')
        logics = ['FirstOrderLogic', 'FuzzyLogic']
        self.selected_logic = StringVar()
        self.selected_logic.trace('w', self.settings_setdirty)
        l = OptionMenu(*(self.frame, self.selected_logic) + tuple(logics))
        l.grid(row=row, column=1, sticky='NWE')

        # mln section
        row += 1
        Label(self.frame, text="MLN: ").grid(row=row, column=0, sticky='NE')
        self.mln_container = FileEditBar(self.frame, directory=self.dir,
                                         filesettings={'extension': '.mln', 'ftypes': [('MLN files', '.mln')]},
                                         defaultname='*unknown{}',
                                         importhook=self.import_mln,
                                         deletehook=self.delete_mln,
                                         projecthook=self.save_proj,
                                         filecontenthook=self.mlnfilecontent,
                                         fileslisthook=self.mlnfiles,
                                         updatehook=self.update_mln,
                                         onchangehook=self.project_setdirty)
        self.mln_container.editor.bind("<FocusIn>", self._got_focus)
        self.mln_container.grid(row=row, column=1, sticky="NEWS")
        self.mln_container.columnconfigure(1, weight=2)
        self.frame.rowconfigure(row, weight=1)

        row += 1
        self.use_emln = IntVar()
        self.use_emln.set(0)
        self.cb_use_emln = Checkbutton(self.frame, text="use model extension",
                                       variable=self.use_emln,
                                       command=self.onchange_use_emln)
        self.cb_use_emln.grid(row=row, column=1, sticky="W")

        # mln extension section
        row += 1
        self.emlncontainerrow = row
        self.emln_label = Label(self.frame, text="EMLN: ")
        self.emln_label.grid(row=self.emlncontainerrow, column=0, sticky='NE')
        self.emln_container = FileEditBar(self.frame,
                                          directory=self.dir,
                                          filesettings={'extension': '.emln', 'ftypes': [('MLN extension files','.emln')]},
                                          defaultname='*unknown{}',
                                          importhook=self.import_emln,
                                          deletehook=self.delete_emln,
                                          projecthook=self.save_proj,
                                          filecontenthook=self.emlnfilecontent,
                                          fileslisthook=self.emlnfiles,
                                          updatehook=self.update_emln,
                                          onchangehook=self.project_setdirty)
        self.emln_container.grid(row=self.emlncontainerrow, column=1, sticky="NEWS")
        self.emln_container.editor.bind("<FocusIn>", self._got_focus)
        self.emln_container.columnconfigure(1, weight=2)
        self.onchange_use_emln(dirty=False)
        self.frame.rowconfigure(row, weight=1)

        # db section
        row += 1
        Label(self.frame, text="Evidence: ").grid(row=row, column=0, sticky='NE')
        self.db_container = FileEditBar(self.frame, directory=self.dir,
                                        filesettings={'extension': '.db', 'ftypes': [('Database files', '.db')]},
                                        defaultname='*unknown{}',
                                        importhook=self.import_db,
                                        deletehook=self.delete_db,
                                        projecthook=self.save_proj,
                                        filecontenthook=self.dbfilecontent,
                                        fileslisthook=self.dbfiles,
                                        updatehook=self.update_db,
                                        onchangehook=self.project_setdirty)
        self.db_container.grid(row=row, column=1, sticky="NEWS")
        self.db_container.editor.bind("<FocusIn>", self._got_focus)
        self.db_container.columnconfigure(1, weight=2)
        self.frame.rowconfigure(row, weight=1)

        # inference method selection
        row += 1
        self.list_methods_row = row
        Label(self.frame, text="Method: ").grid(row=row, column=0, sticky=E)
        self.selected_method = StringVar()
        self.selected_method.trace('w', self.select_method)
        methodnames = sorted(InferenceMethods.names())
        self.list_methods = OptionMenu(*(self.frame, self.selected_method) + tuple(methodnames))
        self.list_methods.grid(row=self.list_methods_row, column=1, sticky="NWE")

        # options
        row += 1
        option_container = Frame(self.frame)
        option_container.grid(row=row, column=1, sticky="NEWS")

        # Multiprocessing
        self.multicore = IntVar()
        self.cb_multicore = Checkbutton(option_container, text="Use all CPUs",
                                        variable=self.multicore,
                                        command=self.settings_setdirty)
        self.cb_multicore.grid(row=0, column=2, sticky=W)

        # profiling
        self.profile = IntVar()
        self.cb_profile = Checkbutton(option_container, text='Use Profiler',
                                      variable=self.profile,
                                      command=self.settings_setdirty)
        self.cb_profile.grid(row=0, column=3, sticky=W)

        # verbose
        self.verbose = IntVar()
        self.cb_verbose = Checkbutton(option_container, text='verbose',
                                      variable=self.verbose,
                                      command=self.settings_setdirty)
        self.cb_verbose.grid(row=0, column=4, sticky=W)

        # options
        self.ignore_unknown_preds = IntVar()
        self.cb_ignore_unknown_preds = Checkbutton(option_container,
                                                   text='ignore unkown predicates',
                                                   variable=self.ignore_unknown_preds,
                                                   command=self.settings_setdirty)
        self.cb_ignore_unknown_preds.grid(row=0, column=5, sticky="W")

        # queries
        row += 1
        Label(self.frame, text="Queries: ").grid(row=row, column=0, sticky=E)
        self.query = StringVar()
        self.query.trace('w', self.settings_setdirty)
        Entry(self.frame, textvariable=self.query).grid(row=row, column=1, sticky="NEW")

        # additional parameters
        row += 1
        Label(self.frame, text="Add. params: ").grid(row=row, column=0, sticky="NE")
        self.params = StringVar()
        self.params.trace('w', self.settings_setdirty)
        self.entry_params = Entry(self.frame, textvariable=self.params)
        self.entry_params.grid(row=row, column=1, sticky="NEW")

        # closed-world predicates
        row += 1
        Label(self.frame, text="CW preds: ").grid(row=row, column=0, sticky="E")

        cw_container = Frame(self.frame)
        cw_container.grid(row=row, column=1, sticky='NEWS')
        cw_container.columnconfigure(0, weight=1)

        self.cwPreds = StringVar()
        self.cwPreds.trace('w', self.settings_setdirty)
        self.entry_cw = Entry(cw_container, textvariable=self.cwPreds)
        self.entry_cw.grid(row=0, column=0, sticky="NEWS")

        self.closed_world = IntVar()
        self.cb_closed_world = Checkbutton(cw_container, text="CW Assumption",
                                           variable=self.closed_world,
                                           command=self.onchange_cw)
        self.cb_closed_world.grid(row=0, column=1, sticky='W')

        # output filename
        row += 1
        output_cont = Frame(self.frame)
        output_cont.grid(row=row, column=1, sticky='NEWS')
        output_cont.columnconfigure(0, weight=1)

        # - filename
        Label(self.frame, text="Output: ").grid(row=row, column=0, sticky="NE")
        self.output_filename = StringVar()
        self.entry_output_filename = Entry(output_cont, textvariable=self.output_filename)
        self.entry_output_filename.grid(row=0, column=0, sticky="NEW")

        # - save option
        self.save = IntVar()
        self.cb_save = Checkbutton(output_cont, text="save", variable=self.save)
        self.cb_save.grid(row=0, column=1, sticky=W)

        # start button
        row += 1
        start_button = Button(self.frame, text=">> Start Inference <<", command=self.infer)
        start_button.grid(row=row, column=1, sticky="NEW")

        self.settings_dirty = IntVar()
        self.project_dirty = IntVar()

        self.gconf = gconf
        self.project = None
        self.project_dir = os.path.abspath(ifnone(directory, ifnone(gconf['prev_query_path'], os.getcwd())))
        if gconf['prev_query_project': self.project_dir] is not None:
            self.load_project(os.path.join(self.project_dir, gconf['prev_query_project':self.project_dir]))
        else:
            self.new_project()

        self.config = self.project.queryconf
        self.project.addlistener(self.project_setdirty)

        self.mln_container.dirty = False
        self.emln_container.dirty = False
        self.db_container.dirty = False
        self.project_setdirty(dirty=False)

        self.master.geometry(gconf['window_loc_query'])

        self.initialized = True
class Zzzscoring():
    def __init__(self, master):

        self.master = master

        master.title("Zzzscoring: Automatic sleep scoring package")

        #### !!~~~~~~~~~~~~~~~~~ DEFINE INPUT DATAFRAME ~~~~~~~~~~~~~~~~~!!####

        self.frame_import = LabelFrame(self.master,
                                       text="Import files section",
                                       padx=150,
                                       pady=100,
                                       font='Calibri 18 bold')
        self.frame_import.grid(row=0,
                               column=0,
                               padx=200,
                               pady=50,
                               columnspan=8)

        #### ==================== Help pop-up button ======================####

        self.popup_button = Button(self.master,
                                   text="Help",
                                   command=self.help_pop_up_func,
                                   font='Calibri 13 bold',
                                   fg='white',
                                   bg='black')
        self.popup_button.grid(row=1, column=8)

        #### ==================== Import data EDFs ========================####
        # Label: Import EDF
        self.label_import = Label(self.frame_import,
                                  text="Import EDF files here:",
                                  font='Calibri 12 bold')
        self.label_import.grid(row=0, column=0, padx=15, pady=10)

        # Button: Import EDF (Browse)
        self.button_import_browse = Button(self.frame_import,
                                           text="Browse data",
                                           padx=100,
                                           pady=20,
                                           font='Calibri 10 bold',
                                           command=self.load_data_file_dialog,
                                           fg='blue',
                                           relief=RIDGE)
        self.button_import_browse.grid(row=1, column=0, padx=15, pady=10)

        #### ================== Import hypnogram files ====================####
        # Show a message about hypnograms
        self.label_hypnos = Label(self.frame_import,
                                  text="Import hypnogram file (.txt) here:",
                                  font='Calibri 12 bold')
        self.label_hypnos.grid(row=0, column=1, padx=15, pady=10)

        # Define browse button to import hypnos
        self.button_hypnos_browse = Button(self.frame_import,
                                           text="Browse labels",
                                           padx=100,
                                           pady=20,
                                           font='Calibri 10 bold',
                                           command=self.load_hypno_file_dialog,
                                           fg='blue',
                                           relief=RIDGE)
        self.button_hypnos_browse.grid(row=1, column=1, padx=15, pady=10)

        #### ===================== Define train size ======================####
        # Define train size section
        self.label_train_size = Label(
            self.frame_import,
            text="Train size portion (between 0 - 1):",
            font='Calibri 12 bold')
        self.label_train_size.grid(row=0, column=3, padx=15, pady=10)

        # Bar to ask for user's entry
        self.train_size = DoubleVar()
        self.train_size.set(0.7)
        self.entry_train_size = OptionMenu(self.frame_import, self.train_size,
                                           0.6, 0.7, 0.8, 0.9)
        self.entry_train_size.grid(row=1, column=3, padx=15, pady=10)
        self.entry_train_size.config(font='Calibri 10 bold', fg='black')

        #### =================== Push apply to load data ==================####
        #Label to read data and extract features
        self.label_apply = Label(
            self.frame_import,
            text="Press to Load, pre-process, and extract features!",
            font='Calibri 12 bold')
        self.label_apply.grid(row=0, column=4)
        # Apply button
        self.button_apply = Button(self.frame_import,
                                   text="Apply",
                                   padx=100,
                                   pady=20,
                                   font='Calibri 10 bold',
                                   relief=RIDGE,
                                   fg='blue',
                                   command=self.Apply_button)
        self.button_apply.grid(row=1, column=4, padx=15, pady=10)

        #### !!~~~~~~~~~~~~~~ DEFINE ML SECTION FRAME ~~~~~~~~~~~~~~~~~~~!!####

        self.frame_ML = LabelFrame(self.master,
                                   text="Machine Learning Section",
                                   padx=150,
                                   pady=100,
                                   font='Calibri 18 bold')
        self.frame_ML.grid(row=1, column=0, padx=200, pady=50, columnspan=8)

        #### ================ Pick ML Algorithm of interest ===============####
        # Label
        self.label_ML_algorithm = Label(
            self.frame_ML,
            text="Choose the machine learning algorithm:",
            font='Calibri 12 bold')
        self.label_ML_algorithm.grid(row=0, column=0, padx=15, pady=10)

        # Dropdown menu
        self.selected_ML = StringVar()
        self.selected_ML.set("Random forest")
        self.drop = OptionMenu(self.frame_ML, self.selected_ML, "SVM",
                               "Random forest", "XGBoost",
                               "Logistic regression", "Naive bayes",
                               "Randomized trees", "GradientBoosting",
                               "ADABoost")
        self.drop.grid(row=1, column=0)
        self.drop.config(font='Calibri 10 bold', fg='blue')

        # label_selec
        self.label_select = Label(self.frame_ML,
                                  text="Press after choosing ML algorithm:",
                                  font='Calibri 12 bold')
        self.label_select.grid(row=0, column=1)

        # select button
        self.button_select = Button(self.frame_ML,
                                    text="Select!",
                                    padx=100,
                                    pady=20,
                                    font='Calibri 12 bold',
                                    relief=RIDGE,
                                    fg='blue',
                                    command=self.Select_ML_button)
        self.button_select.grid(row=1, column=1, padx=15, pady=10)

        # Chekbox for time-dependency

        self.td_var = IntVar()
        self.checkbox_td = Checkbutton(self.frame_ML,
                                       text="Multi-to-one classifcation",
                                       font='Calibri 12 bold',
                                       variable=self.td_var)

        self.checkbox_td.grid(row=2, column=0)

        # Chekbox for feature selection

        self.feat_select_var = IntVar()
        self.checkbox_feat_select = Checkbutton(self.frame_ML,
                                                text="Feature Selection",
                                                font='Calibri 12 bold',
                                                variable=self.feat_select_var)

        self.checkbox_feat_select.grid(row=3, column=0)

    #%% ################### DEFINE FUNCTIONS OF BUTTONS #######################
    #%% Function: Import EDF (Browse)
    def load_data_file_dialog(self):

        global data_files_list

        self.filenames = filedialog.askopenfilenames(
            initialdir="C:/",
            title='select data files',
            filetype=(("edf", "*.edf"), ("All Files", "*.*")))

        # Make a list of imported file names (full path)
        data_files_list = self.frame_import.tk.splitlist(self.filenames)
        self.n_data_files = len(data_files_list)

        # check if the user chose somthing
        if not data_files_list:

            self.label_data = Label(self.frame_import,
                                    text="No file has been selected!",
                                    fg='red',
                                    font='Helvetica 9 bold').grid(row=2,
                                                                  column=0)

        else:
            self.label_data = Label(self.frame_import,
                                    text=str(self.n_data_files) +
                                    " EDF files has been loaded!",
                                    fg='green',
                                    font='Helvetica 9 bold').grid(row=2,
                                                                  column=0)

    #%% Function: Import Hypnogram (Browse)
    def load_hypno_file_dialog(self):

        global hypno_files_list

        self.filenames = filedialog.askopenfilenames(
            initialdir="C:/",
            title='select label files',
            filetype=(("txt", "*.txt"), ("csv", "*.csv"), ("All Files",
                                                           "*.*")))
        hypno_files_list = self.frame_import.tk.splitlist(self.filenames)
        self.n_label_files = len(hypno_files_list)

        # check if the user chose somthing
        if not hypno_files_list:

            self.label_labels = Label(self.frame_import,
                                      text="No hypnogram has been selected!",
                                      fg='red',
                                      font='Helvetica 9 bold').grid(row=2,
                                                                    column=1)

        else:

            self.label_labels = Label(self.frame_import,
                                      text=str(self.n_label_files) +
                                      " hypnogram files has been loaded!",
                                      fg='green',
                                      font='Helvetica 9 bold').grid(row=2,
                                                                    column=1)

    #%% Read EDF and hypnograms and apply feature extraction
    def Read_Preproc_FeatExtract(self):
        global subjects_dic, hyp_dic, dic_pciked_chans
        subjects_dic = {}
        hyp_dic = {}
        dic_pciked_chans = {}

        #### ======================= Create log window ====================####
        self.log_win = Toplevel()
        self.log_win.title("Log file of current processes")

        # Label
        self.label = Label(self.log_win,
                           text="Process log file:",
                           font='Helvetica 12 bold')

        self.label.pack()

        self.close_log_win = Button(self.log_win,
                                    text="Dismiss",
                                    command=self.log_win.destroy)
        self.close_log_win.pack()

        #### ======================= Read data files ======================####

        for idx, c_subj in enumerate(data_files_list):
            self.log1_ = Label(self.log_win,
                               text="Analyzing data: " + str(c_subj[-11:-4]) +
                               "\tPlease wait ...").pack()
            print(f'Analyzing data: {c_subj[-11:-4]}')
            ## Read in data
            file = data_files_list[idx]
            tic = time.time()
            data = mne.io.read_raw_edf(file)
            # Data raw EEG --> Deactive
            # data.plot(duration = 30, highpass = .3 , lowpass = 25 )
            raw_data = data.get_data()
            print('Time to read EDF: {}'.format(time.time() - tic))
            self.log2_ = Label(self.log_win,
                               text="Time to read EDF data (s): " +
                               str(np.round(time.time() - tic))).pack()

            #####=================Retrieving information from data====================#####

            # =============================================================================
            #             DataInfo          = data.info
            #             AvailableChannels = DataInfo['ch_names']
            #             self.fs                = int(DataInfo['sfreq'])
            # =============================================================================

            #####================= Find index of required channels ===================#####

            # =============================================================================
            #             for indx, c in enumerate(AvailableChannels):
            #                 if c in RequiredChannels:
            #                     Idx.append(indx)
            #                 elif c in Mastoids:
            #                     Idx_Mastoids.append(indx)
            # =============================================================================

            #####===== Sampling rate is 200hz; thus 1 epoch(30s) is 6000 samples =====#####
            self.fs = 256
            T = 30  #secs
            len_epoch = self.fs * T
            start_epoch = 0
            n_channels = 1

            #####============ Cut tail; use modulo to find full epochs ===============#####

            raw_data = raw_data[:, 0:raw_data.shape[1] -
                                raw_data.shape[1] % len_epoch]

            #####========== Reshape data [n_channel, len_epoch, n_epochs] ============#####
            data_epoched = np.reshape(
                raw_data,
                (n_channels, len_epoch, int(raw_data.shape[1] / len_epoch)),
                order='F')

            #####===================== Reading hypnogram data ========================#####

            hyp = loadtxt(hypno_files_list[idx])

            ### Create sepereate data subfiles based on hypnogram (N1, N2, N3, NREM, REM)
            tic = time.time()

            #####================= Concatenation of selected channels ================#####

            # Calculate referenced channels:

            #data_epoched_selected = data_epoched[Idx] - data_epoched[Idx_Mastoids]

            #####================= Find order of the selected channels ===============#####
            # =============================================================================
            #             #Init
            #             picked_channels = []
            #             picked_refs     = []
            #             List_Channels   = []
            #
            #             # Find main channels
            #             for jj,kk in enumerate(Idx):
            #                 picked_channels = np.append(picked_channels, AvailableChannels[kk])
            #             # Find references
            #             for jj,kk in enumerate(Idx_Mastoids):
            #                 picked_refs     = np.append(picked_refs, AvailableChannels[kk])
            #             print(f'subject LK {c_subj} --> detected channels: {str(picked_channels)} -  {str(picked_refs)}')
            #             self.log3_ = Label(self.log_win, text = "Dectected channels:"+str(picked_channels) +"-" +str(picked_refs)).pack()
            #
            #             # Create lis of channels
            #             for kk in np.arange(0, len(Idx)):
            #                 List_Channels = np.append(List_Channels, picked_channels[kk] + '-' + picked_refs[kk])
            # =============================================================================

            #%% Analysis section
            #####================= remove chanbnels without scroing ==================#####

            # assign the proper data and labels
            #x_tmp_init = data_epoched_selected
            x_tmp_init = data_epoched

            y_tmp_init = hyp

            #Define ssccoorriinngg object:
            self.Object = ssccoorriinngg(filename='',
                                         channel='',
                                         fs=self.fs,
                                         T=30)
            # Ensure equalituy of length for arrays:
            self.Object.Ensure_data_label_length(x_tmp_init, y_tmp_init)

            # Remove non-scored epochs
            x_tmp, y_tmp = self.Object.remove_channels_without_scoring(
                hypno_labels=y_tmp_init, input_feats=x_tmp_init)

            # Remove disconnections
            x_tmp, y_tmp = self.Object.remove_disconnection(hypno_labels=y_tmp,
                                                            input_feats=x_tmp)

            #####============= Create a one hot encoding form of labels ==============#####

            # Create binary labels array
            self.yy = self.Object.One_hot_encoding(y_tmp)

            # Ensure all the input labels have a class
            self.Object.Unlabaled_rows_detector(self.yy)

            #%% Function: Feature_Extraction
            # Initialize feature array:
            self.Feat_all_channels = np.empty((np.shape(x_tmp)[-1], 0))

            #####================== Extract the relevant features ====================#####

            for k in np.arange(np.shape(data_epoched)[0]):

                feat_temp = self.Object.FeatureExtraction_per_subject(
                    Input_data=x_tmp[k, :, :])
                self.Feat_all_channels = np.column_stack(
                    (self.Feat_all_channels, feat_temp))

            toc = time.time()
            print(
                f'Features of subject { c_subj[-11:-4]} were successfully extracted in: {toc-tic} secs'
            )
            self.log4_ = Label(self.log_win,
                               text="Features of subject" +
                               str(c_subj[-11:-4]) +
                               " were successfully extracted in (secs):" +
                               str(np.round(toc - tic))).pack()

            # Double check the equality of size of arrays
            self.Object.Ensure_feature_label_length(self.Feat_all_channels,
                                                    self.yy)

            # Defining dictionary to save features PER SUBJECT
            subjects_dic["subject{}".format(c_subj)] = self.Feat_all_channels

            # Defining dictionary to save hypnogram PER SUBJECT
            hyp_dic["hyp{}".format(c_subj)] = self.yy

            # =============================================================================
            #             # Show picked channels per subject
            #             dic_pciked_chans["subj{}".format(c_subj[-11:-4])] = List_Channels
            #
            # =============================================================================

            #####=============== Removing variables for next iteration ===============#####
            del x_tmp, y_tmp

            toc = time.time()

            print(
                f'Feature extraction of subject { c_subj[-11:-4]} has been finished.'
            )
            self.log5_ = Label(self.log_win,
                               text="Feature extraction of subject " +
                               str(c_subj[-11:-4]) +
                               " has been finished.").pack()

        #print(f'Total feature extraction of subjects took {tic_tot - time.time()} secs.')

    #%% Function: Import Hypnogram (Browse)
    def Apply_button(self):

        print(f'Train size --> {str(self.train_size.get() * 100)}%')
        #### ======================= Get the train size ===================####
        self.train_size = self.train_size.get()

        # Has the user loaded hypnos?!
        if not hypno_files_list:
            self.label_apply1 = Label(self.frame_import,
                                      text="You haven't added any hypnogram!",
                                      fg='red',
                                      font='Helvetica 9 bold').grid(row=2,
                                                                    column=4)
        # Has the user loaded EDF files?!
        elif not data_files_list:
            self.label_apply2 = Label(self.frame_import,
                                      text="You haven't added any EDF files!",
                                      fg='red',
                                      font='Helvetica 9 bold').grid(row=2,
                                                                    column=4)

        # Check if train size is a valid value
        elif not self.train_size:
            self.label_apply1 = Label(self.frame_import,
                                      text="No train size is entered!",
                                      fg='red',
                                      font='Helvetica 9 bold').grid(row=2,
                                                                    column=4)

        elif float(self.train_size) > 0.99 or float(self.train_size) < 0.01:
            self.label_apply1 = Label(
                self.frame_import,
                text="Invalid train size! (acceptable range:0-1)",
                fg='red',
                font='Helvetica 9 bold').grid(row=2, column=4)

        # Do the imported data an hypnos have the same amount of inputs?
        elif len(data_files_list) != len(hypno_files_list):
            self.label_apply3 = Label(
                self.frame_import,
                text=
                "Size of the loaded hypons and EDF files do not match! Please recheck ...",
                fg='red',
                font='Helvetica 9 bold').grid(row=2, column=4)
        # Else --> Go next
        if len(data_files_list) == len(hypno_files_list) and float(
                self.train_size) < .99 and float(self.train_size) > 0.01:
            self.label_apply4 = Label(
                self.frame_import,
                text="Train size: " + str(self.train_size) +
                "\nData and hypnogram have received in a good order!\n Go to next section to proceed ...",
                fg='green',
                font='Helvetica 9 bold').grid(row=2, column=4)

            self.Read_Preproc_FeatExtract()

    #%% Function: Import Hypnogram (Browse)
    def Select_ML_button(self):
        # Check the current ML flag
        self.selected_ML = self.selected_ML.get()
        # Define label
        self.label_select1 = Label(
            self.frame_ML,
            text=str(self.selected_ML) +
            " has been selected.\n Please adjust the folloiwng hypermarameters.",
            fg='green',
            font='Helvetica 9 bold').grid(row=2, column=1)

        # Report current td val
        print(
            f'Time dependence (0: deactive, 1: active) = {self.td_var.get()}')

        #### ============== Train the model and predict test ==============####
        self.label_train = Label(self.frame_ML,
                                 text="Start Taining!",
                                 font='Calibri 12 bold')
        self.label_train.grid(row=0, column=3)
        # Activate train Button
        self.button_train = Button(self.frame_ML,
                                   text="Train model!",
                                   padx=100,
                                   pady=20,
                                   font='Calibri 12 bold',
                                   relief=RIDGE,
                                   fg='blue',
                                   command=self.Training_function)
        self.button_train.grid(row=1, column=3)

        #### ==============  multi-to-one classification flag ============ ####

        if int(self.td_var.get()) == 1:

            # Label
            self.label_checkbox = Label(self.frame_ML,
                                        text="Time-dependence (#epochs):",
                                        font='Calibri 12 bold')
            self.label_checkbox.grid(row=2, column=2)

            # Dropdown menu for td

            self.entry_td = IntVar()
            self.entry_td.set(5)
            self.drop_td = OptionMenu(self.frame_ML, self.entry_td, 1, 2, 3, 4,
                                      5, 6)
            self.drop_td.grid(row=3, column=2)
            self.drop_td.config(font='Calibri 10 bold', fg='blue')
        # SVM Hyperparameters

        if self.selected_ML == "SVM":
            self.kernel_ = StringVar()
            #init
            self.kernel_.set('rbf')
            # Differnt Kernel functions of SVM:
            Kernel_rbf = Radiobutton(self.frame_ML,
                                     text='rbf',
                                     variable=self.kernel_,
                                     value='rbf',
                                     font='Helvetica 12 bold')
            Kernel_sig = Radiobutton(self.frame_ML,
                                     text='sigmoid',
                                     variable=self.kernel_,
                                     value='sigmoid',
                                     font='Helvetica 12 bold')
            Kernel_pol = Radiobutton(self.frame_ML,
                                     text='poly',
                                     variable=self.kernel_,
                                     value='poly',
                                     font='Helvetica 12 bold')
            # Get the chosen Kernel
            #self.kernel = self.kernel.get()

            # Shoving the radio buttons to the frame
            Kernel_rbf.grid(row=0, column=2)
            Kernel_sig.grid(row=1, column=2)
            Kernel_pol.grid(row=2, column=2)

        # Random forest hyperparameters
        elif self.selected_ML == "Random forest":
            self.n_estimator_RF = IntVar()
            self.n_estimator_RF.set(10)
            # Create n_estimators label
            self.label_n_estimators = Label(self.frame_ML,
                                            text="Number of trees:",
                                            font='Calibri 12 bold')
            self.label_n_estimators.grid(row=0, column=2, padx=15, pady=10)
            # Create entry for user
            self.entry_n_estimator_RF = Entry(self.frame_ML,
                                              text=" Enter the value here ",
                                              borderwidth=8,
                                              width=10)
            self.entry_n_estimator_RF.grid(row=1, column=2, padx=15, pady=10)
            # Assign the value to send to classifier
            #self.n_estimator_RF = self.entry_n_estimator_RF.get()

        # XGBoost
        elif self.selected_ML == "XGBoost":
            self.n_estimator_xgb = IntVar()
            # Create n_estimators label
            self.label_n_estimators = Label(self.frame_ML,
                                            text="Number of trees:",
                                            font='Calibri 12 bold')
            self.label_n_estimators.grid(row=0, column=2, padx=15, pady=10)
            # Create entry for user
            self.entry_n_estimator_xgb = Entry(self.frame_ML,
                                               text=" Enter the value here ",
                                               borderwidth=8,
                                               width=10)
            self.entry_n_estimator_xgb.grid(row=1, column=2, padx=15, pady=10)
            # Assign the value to send to classifier
            #self.n_estimator_xgb = self.entry_n_estimator_xgb.get()

        # ADABoost
        elif self.selected_ML == "ADABoost":
            self.n_estimator_ada = IntVar()
            # Create n_estimators label
            self.label_n_estimators = Label(self.frame_ML,
                                            text="Number of trees:",
                                            font='Calibri 12 bold')
            self.label_n_estimators.grid(row=0, column=2, padx=15, pady=10)
            # Create entry for user
            self.entry_n_estimator_ada = Entry(self.frame_ML,
                                               text=" Enter the value here ",
                                               borderwidth=8,
                                               width=10)
            self.entry_n_estimator_ada.grid(row=1, column=2, padx=15, pady=10)
            # Assign the value to send to classifier
            #self.n_estimator_ada = self.entry_n_estimator_ada.get()

        # GradientBoosting
        elif self.selected_ML == "GradientBoosting":
            self.n_estimator_gb = IntVar()
            # Create n_estimators label
            self.label_n_estimators = Label(self.frame_ML,
                                            text="Number of trees:",
                                            font='Calibri 12 bold')
            self.label_n_estimators.grid(row=0, column=2, padx=15, pady=10)
            # Create entry for user
            self.entry_n_estimator_gb = Entry(self.frame_ML,
                                              text=" Enter the value here ",
                                              borderwidth=8,
                                              width=10)
            self.entry_n_estimator_gb.grid(row=1, column=2, padx=15, pady=10)
            # Assign the value to send to classifier
            #self.n_estimator_gb = self.entry_n_estimator_gb.get()

        # Randomized trees

        elif self.selected_ML == "Randomized trees":
            self.n_estimator_rt = IntVar()
            # Create n_estimators label
            self.label_n_estimators = Label(self.frame_ML,
                                            text="Number of trees:",
                                            font='Calibri 12 bold')
            self.label_n_estimators.grid(row=0, column=2, padx=15, pady=10)
            # Create entry for user
            self.entry_n_estimator_rt = Entry(self.frame_ML,
                                              text=" Enter the value here ",
                                              borderwidth=8,
                                              width=10)
            self.entry_n_estimator_rt.grid(row=1, column=2, padx=15, pady=10)
            # Assign the value to send to classifier
            #self.n_estimator_rt = self.entry_n_estimator_rt.get()

        # Naive Bayes
        elif self.selected_ML == "Naive Bayes":
            pass

        # Logistic regression
        elif self.selected_ML == "Logistic regression":
            pass

        print(f'Time dependence : {self.entry_td.get()} epochs')

    #%% Function: Help pop-up
    def help_pop_up_func(self):

        line1 = "Welcome to Zzzscoring!\n"
        line2 = "Pick the EDF files of interest and their corresponding hypnograms!\n"
        line3 = "** Notes:\n- hypnograms should be in .txt or .csv format.\n"
        line4 = "- The first and second column of hypnos are labels and artefact annotations, respecively.\n"
        line5 = "- Default labels should be as below:\n"
        line6 = "- Wake:0, N1: 1, N2: 2, SWS: 3, REM: 4.\n"
        line7 = "- Once pushing a button e,.g. 'Apply' or 'Train' the process is time-taking. One can follow the status of process in the console (e.g. command prompt).\n"
        line8 = "- After choosing a ML algorithm you should press 'Select' and then specify hyperparameters. After this, one is allowed to press 'Train' button.\n"
        line9 = "- Activating feature selection extend the process time. Don't forget to follow the status from console. "
        lines = line1 + line2 + line3 + line4 + line5 + line6 + line7 + line8 + line9

        messagebox.showinfo(title="Help", message=lines)

    #%% Training function
    def Training_function(self):
        # Training perentage

        self.n_train = round(float(self.train_size) * len(data_files_list))

        # ========================== Show reuslt ============================ #
        # Label
        self.label_results = Label(self.frame_ML,
                                   text="Train and prediction finished!",
                                   font='Calibri 12 bold')
        self.label_results.grid(row=0, column=4)
        # Activate results Button
        self.button_show_results = Button(self.frame_ML,
                                          text="Show results",
                                          padx=80,
                                          pady=15,
                                          font='Calibri 12 bold',
                                          relief=RIDGE,
                                          fg='blue',
                                          command=self.show_results_function)
        self.button_show_results.grid(row=1, column=4)

        # ========================== Plot conf mat ========================== #
        # Activate plot confusion Button
        self.button_plot_conf = Button(self.frame_ML,
                                       text="Plot confusion mat",
                                       padx=80,
                                       pady=15,
                                       font='Calibri 12 bold',
                                       relief=RIDGE,
                                       fg='blue',
                                       command=self.plot_conf_mat)
        self.button_plot_conf.grid(row=1, column=5)

        # ========================== Activate plot hypnogram ================ #
        self.button_plot_hyp = Button(self.frame_ML,
                                      text="Plot hypnograms",
                                      padx=80,
                                      pady=15,
                                      font='Calibri 12 bold',
                                      relief=RIDGE,
                                      fg='blue',
                                      command=self.plot_hyp_function)
        self.button_plot_hyp.grid(row=2, column=4)

        #######=== Randomly shuffle subjects to choose train and test splits ===######

        # =============================================================================
        #         subj_c = np.random.RandomState(seed=42).permutation(subj_c)
        #
        # =============================================================================
        #######=============== Initialize train and test arrays ================#######
        global X_train, X_test, y_train
        X_train = np.empty((0, np.shape(self.Feat_all_channels)[1]))
        X_test = np.empty((0, np.shape(self.Feat_all_channels)[1]))
        y_train = np.empty((0, np.shape(self.yy)[1]))
        self.y_test = np.empty((0, np.shape(self.yy)[1]))

        ########======= Picking the train subjetcs and concatenate them =======########

        for c_subj in data_files_list[0:self.n_train]:

            self.tmp_name = c_subj

            # train hypnogram
            self.str_train_hyp = 'hyp' + str(self.tmp_name)

            # train featureset
            self.str_train_feat = 'subject' + str(self.tmp_name)

            # create template arrays for featurs and label
            self.tmp_x = subjects_dic[self.str_train_feat]
            self.tmp_y = hyp_dic[self.str_train_hyp]

            # Concatenate features and labels
            X_train = np.row_stack((X_train, self.tmp_x))
            y_train = np.row_stack((y_train, self.tmp_y))

            #del self.tmp_x, self.tmp_y, self.tmp_name, self.str_train_hyp, self.str_train_feat

        ########======== Picking the test subjetcs and concatenate them =======########

        self.test_subjects_list = []

        for c_subj in data_files_list[self.n_train:]:

            self.tmp_name = c_subj
            # test hypnogram
            str_test_hyp = 'hyp' + str(self.tmp_name)

            # test featureset
            str_test_feat = 'subject' + str(self.tmp_name)

            # create template arrays for featurs and  label
            self.tmp_x = subjects_dic[str_test_feat]
            self.tmp_y = hyp_dic[str_test_hyp]

            # Concatenate features and labels
            X_test = np.row_stack((X_test, self.tmp_x))
            self.y_test = np.row_stack((self.y_test, self.tmp_y))

            # keep the subject id
            self.test_subjects_list.append(str_test_feat)

            # remove for next iteration
            #del self.tmp_x, self.tmp_y,self.tmp_name, self.str_test_feat, self.str_test_hyp
        ################# FOR NOW WE IGNOR MOVEMENT AROUSAL ###################
        y_train = y_train[:, :5]
        self.y_test = self.y_test[:, :5]

        # ========================= Time-dependency ========================= #
        #global X_train_td, X_test_td
        if int(self.td_var.get()) == 1:
            print(f'Adding time-dependency ... n_td : {self.entry_td.get()} ')
            X_train_td = self.Object.add_time_dependence_backward(
                X_train,
                n_time_dependence=int(self.entry_td.get()),
                padding_type='sequential')

            X_test_td = self.Object.add_time_dependence_backward(
                X_test,
                n_time_dependence=int(self.entry_td.get()),
                padding_type='sequential')

            X_train = X_train_td
            X_test = X_test_td
        # ======================== Feature selection ======================== #

        self.y_train_td = self.Object.binary_to_single_column_label(y_train)

        # Check activation of flag
        if int(self.feat_select_var.get()) == 1:

            tmp1, tmp2, self.selected_feats_ind = self.Object.FeatSelect_Boruta(
                X_train, self.y_train_td[:, 0], max_iter=50)
            X_train = X_train[:, self.selected_feats_ind]
            X_test = X_test[:, self.selected_feats_ind]

        ######## ================= Apply chosen ML ================= ##########
        global y_pred
        # SVM
        if self.selected_ML == "SVM":

            y_pred = self.Object.KernelSVM_Modelling(X_train,
                                                     y_train,
                                                     X_test,
                                                     self.y_test,
                                                     kernel=self.kernel_.get())
            y_pred = np.expand_dims(y_pred, axis=1)
            # One hot encoding

        # Random forest
        elif self.selected_ML == "Random forest":

            y_pred = self.Object.RandomForest_Modelling(
                X_train,
                y_train,
                X_test,
                self.y_test,
                n_estimators=int(self.entry_n_estimator_RF.get()))
            self.Object.multi_label_confusion_matrix(self.y_test,
                                                     y_pred,
                                                     print_results='on')

        # XGB
        elif self.selected_ML == "XGBoost":
            y_pred = self.Object.XGB_Modelling(
                X_train,
                y_train,
                X_test,
                self.y_test,
                n_estimators=int(self.entry_n_estimator_xgb.get()),
                max_depth=3,
                learning_rate=.1)

        # ADABoost
        elif self.selected_ML == "ADABoost":
            y_pred = self.Object.ADAboost_Modelling(
                X_train,
                y_train,
                X_test,
                self.y_test,
                n_estimators=int(self.entry_n_estimator_ada.get()))

        # GRadient Boosting
        elif self.selected_ML == "GradientBoosting":
            y_pred = self.Object.gradient_boosting_classifier(
                X_train,
                y_train,
                X_test,
                self.y_test,
                n_estimators=int(self.entry_n_estimator_gb.get()),
                learning_rate=1.0,
                max_depth=1)
        # Randomized trees
        elif self.selected_ML == "Randomized trees":
            y_pred = self.Object.Extra_randomized_trees(
                X_train,
                y_train,
                X_test,
                self.y_test,
                n_estimators=int(self.entry_n_estimator_rt.get()),
                max_depth=None,
                min_samples_split=2,
                max_features="sqrt")

    #%% Def show_results function
    def show_results_function(self):

        from sklearn.metrics import multilabel_confusion_matrix, cohen_kappa_score

        #### =================== Create results window ================####
        self.results_win = Toplevel()
        self.results_win.title("Results of classification")

        # Label
        self.label_results_win = Label(self.results_win,
                                       text="Results were found as below:\n",
                                       font='Calibri 16 bold')

        self.label_results_win.pack()

        self.close_res_win = Button(self.results_win,
                                    text="Dismiss",
                                    command=self.results_win.destroy)
        self.close_res_win.pack()

        # If the size of y_test & y_pred differ --> change them accordingly

        try:
            if np.shape(self.y_test)[1] != np.shape(y_pred)[1]:
                self.y_test = self.Object.binary_to_single_column_label(
                    self.y_test)

        except IndexError:
            self.y_test = self.Object.binary_to_single_column_label(
                self.y_test)

        self.mcm = multilabel_confusion_matrix(self.y_test, y_pred)
        self.tn = self.mcm[:, 0, 0]
        self.tp = self.mcm[:, 1, 1]
        self.fn = self.mcm[:, 1, 0]
        self.fp = self.mcm[:, 0, 1]
        self.Recall = self.tp / (self.tp + self.fn)
        self.prec = self.tp / (self.tp + self.fp)
        self.f1_sc = 2 * self.Recall * self.prec / (self.Recall + self.prec)
        self.Acc = (self.tp + self.tn) / (self.tp + self.fp + self.fn +
                                          self.tn)
        #kappa = cohen_kappa_score(y_true, y_pred)
        self.label_res1 = Label(
            self.results_win,
            text="Accuracy for Wake,N1,N2,N3,REM were respectively:" +
            str(self.Acc),
            font='Calibri 12 bold').pack()
        self.label_res2 = Label(
            self.results_win,
            text="Precision for Wake,N1,N2,N3,REM were respectively:" +
            str(self.prec),
            font='Calibri 12 bold').pack()
        self.label_res3 = Label(
            self.results_win,
            text="Recall for Wake,N1,N2,N3,REM were respectively:" +
            str(self.Recall),
            font='Calibri 12 bold').pack()
        self.label_res4 = Label(
            self.results_win,
            text="F1-score for Wake,N1,N2,N3,REM were respectively:" +
            str(self.f1_sc),
            font='Calibri 12 bold').pack()

    #%% Plot confusion matrix
    def plot_conf_mat(self):

        self.Object.plot_confusion_matrix(
            self.y_test,
            y_pred,
            target_names=['Wake', 'N1', 'N2', 'SWS', 'REM'],
            title='Confusion matrix of ssccoorriinngg algorithm',
            cmap=None,
            normalize=True)

    #%% Plot hypnograms
    def plot_hyp_function(self):

        # =============================================================================
        #         # If the size of y_test & y_pred differ --> change them accordingly
        #
        #         try:
        #             if np.shape(self.y_test)[1] != np.shape(y_pred)[1]:
        #                 self.y_test = self.Object.binary_to_single_column_label(self.y_test)
        #
        #
        #         except IndexError:
        #             self.y_test = self.Object.binary_to_single_column_label(self.y_test)
        #
        #         self.hyp_true = self.Object.binary_to_single_column_label(self.y_test)
        #
        #         if np.shape(y_pred)[1] == 1:
        #             self.hyp_pred = self.Object.binary_to_single_column_label(y_pred)
        #         else:
        # =============================================================================
        self.hyp_true = self.y_test
        self.hyp_pred = y_pred
        self.Object.plot_comparative_hyp(self.hyp_true,
                                         self.hyp_pred,
                                         mark_REM='active',
                                         Title='True Hypnogram')
Beispiel #45
0
class FilePickEdit(Frame):
    
    def __init__(self, master, file_mask, default_file, edit_height = None, user_onChange = None, 
                 rename_on_edit=0, font = None, coloring=True, allowNone=False, highlighter=None, directory='.'):
        """
            file_mask: file mask (e.g. "*.foo") or list of file masks (e.g. ["*.foo", "*.abl"])
        """
        self.master = master
        self.directory = directory
        self.user_onChange = user_onChange
        Frame.__init__(self, master)
        row = 0
        self.unmodified = True
        self.allowNone = allowNone
        self.file_extension = ""
        if type(file_mask) != list:
            file_mask = [file_mask]
        if "." in file_mask[0]:
            self.file_extension = file_mask[0][file_mask[0].rfind('.'):]
        # read filenames
        self.file_mask = file_mask
        self.updateList()
        # filename frame
        self.list_frame = Frame(self)
        self.list_frame.grid(row=row, column=0, sticky="WE")
        self.list_frame.columnconfigure(0, weight=1)
        # create list
        self.picked_name = StringVar()
        self.makelist()
        # refresh button
        self.refresh_button = Button(self.list_frame, text='<- refresh', command=self.refresh, height=1)
        self.refresh_button.grid(row=0, column=1, sticky='E')        
        # save button
        self.save_button = Button(self.list_frame, text="save", command=self.save, height=1)
        self.save_button.grid(row=0, column=2, sticky="E")
        # editor
        row += 1
        if coloring:
            self.editor = SyntaxHighlightingText(self, self.onEdit, highlighter=highlighter)
        else:
            self.editor = ScrolledText2(self, self.onEdit)
        if font is not None:
            self.editor.configure(font=font)
        if edit_height is not None:
            self.editor.configure(height=edit_height)
        self.editor.grid(row=row, column=0, sticky="NEWS")
        self.rowconfigure(row, weight=1)
        self.columnconfigure(0, weight=1)
        # option to change filename on edit
        row += 1
        self.options_frame = Frame(self)
        self.options_frame.grid(row=row, column=0, sticky=W)
        self.rename_on_edit = IntVar()
        self.cb = Checkbutton(self.options_frame, text="rename on edit", variable=self.rename_on_edit)
        self.cb.pack(side=LEFT)
        self.cb.configure(command=self.onChangeRename)
        self.rename_on_edit.set(rename_on_edit)
        # filename frame
        row += 1
        self.filename_frame = Frame(self)
        self.filename_frame.grid(row=row, column=0, sticky="WE")
        self.filename_frame.columnconfigure(0, weight=1)
        # save as filename
        self.save_name = StringVar()
        self.save_edit = Entry(self.filename_frame, textvariable = self.save_name)
        self.save_edit.grid(row=0, column=0, sticky="WE")
        self.save_name.trace("w", self.onSaveChange)
        # pick default if applicableButton
        self.select(default_file)
        self.row = row
        
    def setDirectory(self, directory, keep=False):
        self.directory = directory
        self.updateList()
        self.makelist()
#         menu = self.list["menu"] scrolledlist
#         menu = self.list.listbox#["scrolledlist"]
#         menu.delete(0, 'end')
        # add the new ones
#         for filename in self.files:
#             menu.add_command(label=filename, command=_setit(self.picked_name, filename, None))
        # if keep is true, only the files list will be updated but the content of the
        # text area will not be altered/removed
        if not keep: self.select("")
    
    def refresh(self):
        sel = self.get()
        self.updateList()
        self.select(sel, notify=False)
    
    def reloadFile(self):
        self.editor.delete("1.0", END)
        filename = self.picked_name.get()
        if os.path.exists(os.path.join(self.directory, filename)):
            new_text = open(os.path.join(self.directory, filename)).read()
            if new_text.strip() == "":
                new_text = "// %s is empty\n" % filename
            new_text = new_text.replace("\r", "")
        else:
            new_text = ""
        self.editor.insert(INSERT, new_text)
        
    def setText(self, txt):
        """
        Replaces the text in the edit field as by typing
        into it.
        """
        self.select("")
        if txt.strip() == "":
            txt = "// empty database\n"
        self.editor.insert(INSERT, txt)
        self.onEdit()
        

    def onSelChange(self):
        self.reloadFile()
        filename = self.picked_name.get()
        self.save_name.set(filename)
        self.save_edit.configure(state=DISABLED)
        self.unmodified = True
        if self.user_onChange is not None:
            self.user_onChange(filename)

    def onSaveChange(self, name, index, mode):
        pass

    def autoRename(self):
        # modify "save as" name
        filename = self.picked_name.get()
        if filename == "": filename = "new" + self.file_extension # if no file selected, create new filename
        ext = ""
        extpos = filename.rfind(".")
        if extpos != -1: ext = filename[extpos:]
        base = filename[:extpos]
        hpos = base.rfind("-")
        num = 0
        if hpos != -1:
            try:
                num = int(base[hpos+1:])
                base = base[:hpos]
            except:
                pass
        while True:
            num += 1
            filename = "%s-%d%s" % (base, num, ext)
            if not os.path.exists(filename):
                break
        self.save_name.set(filename)
        # user callback
        if self.user_onChange is not None:
            self.user_onChange(filename)

    def onEdit(self):
        if self.unmodified:
            self.unmodified = False
            # do auto rename if it's enabled or there is no file selected (editing new file)
            if self.rename_on_edit.get() == 1 or self.picked_name.get() == "":
                self.autoRename()
            # enable editing of save as name
            self.save_edit.configure(state=NORMAL)

    def onChangeRename(self):
        # called when clicking on "rename on edit" checkbox
        if self.rename_on_edit.get() == 1:
            if (not self.unmodified) and self.save_name.get() == self.picked_name.get():
                self.autoRename()
        else:
            self.save_name.set(self.picked_name.get())

    def updateList(self):
        self.files = []
        if self.allowNone:
            self.files.append("")
        if os.path.exists(self.directory):
            for filename in os.listdir(self.directory):
                for fm in self.file_mask:
                    if fnmatch(filename, fm):
                        self.files.append(filename)
        self.files.sort()
        if len(self.files) == 0 and not self.allowNone: self.files.append("(no %s files found)" % str(self.file_mask))
        

    def select(self, filename, notify=True):
        """ selects the item given by filename """
        if filename in self.files:
            if not havePMW:
                self.picked_name.set(filename)
            else:
                self.list.selectitem(self.files.index(filename))
                if notify: self.onSelChange(filename)
        else:
            self.editor.delete("1.0", END)
                

    def makelist(self):
        if havePMW:
            self.list = ComboBox(self.list_frame,
                    selectioncommand = self.onSelChange,
                    scrolledlist_items = self.files,
            )
            self.list.grid(row=0, column=0, padx=0, pady=0, sticky="NEWS")
            self.list.component('entryfield').component('entry').configure(state = 'readonly', relief = 'raised')
            self.picked_name = self.list
        else:
            self.list = OptionMenu(*(self.list_frame, self.picked_name) + tuple(self.files))
            self.list.grid(row=0, column=0, sticky="NEW")
            self.picked_name.trace("w", self.onSelChange)

    def save(self):
        self.get()

    def set(self, selected_item):
        self.select(selected_item)

    def get(self):
        """ gets the name of the currently selected file, saving it first if necessary """
        filename = self.save_name.get()
        if self.unmodified == False:
            self.unmodified = True
            # save the file
            f = open(os.path.join(self.directory, filename), "w")
            f.write(self.editor.get("1.0", END).encode('utf-8'))
            f.close()
            # add it to the list of files
#             if not filename in self.files:
#                 self.files.append(filename)
#                 self.files.sort()
#                 self.list.destroy()
#                 self.makelist()
            # set it as the new pick
            #if havePMW:
            #    self.picked_name.selectitem(self.files.index(filename), 1)
            #else:
            #    self.picked_name.set(filename)
#             self.select(filename)
            self.refresh()
            self.select(filename, notify=False)
            self.save_edit.configure(state=DISABLED)
        return filename

    def get_text(self):
        return self.editor.get("1.0", END)

    def get_filename(self):
        return self.save_name.get()

    def set_enabled(self, state):
        self.editor.configure(state=state)
        if havePMW:
            self.list.component('entryfield_entry').configure(state=state)
#             self.list.component('arrowbutton').configure(state=state)
            self.list.component('arrowbutton').bind('<1>', (lambda a: 'break') if state==DISABLED else self.list._postList)
        else:
            self.list.configure(state=state)
        self.save_button.configure(state=state)
        self.cb.configure(state=state)
        self.save_edit.configure(state=state)
Beispiel #46
0
class MLNQueryGUI(object):
    def __init__(self, master, gconf, directory=None):
        self.master = master

        self.initialized = False

        self.master.bind('<Return>', self.infer)
        self.master.bind('<Escape>', lambda a: self.master.quit())
        self.master.protocol('WM_DELETE_WINDOW', self.quit)

        self.dir = os.path.abspath(ifnone(directory, ifnone(gconf['prev_query_path'], os.getcwd())))

        self.frame = Frame(master)
        self.frame.pack(fill=BOTH, expand=1)
        self.frame.columnconfigure(1, weight=1)

        row = 0
        # pracmln project options
        Label(self.frame, text='PRACMLN Project: ').grid(row=row, column=0,
                                                         sticky='ES')
        project_container = Frame(self.frame)
        project_container.grid(row=row, column=1, sticky="NEWS")

        # new proj file
        self.btn_newproj = Button(project_container, text='New Project...', command=self.new_project)
        self.btn_newproj.grid(row=0, column=1, sticky="WS")

        # open proj file
        self.btn_openproj = Button(project_container, text='Open Project...', command=self.ask_load_project)
        self.btn_openproj.grid(row=0, column=2, sticky="WS")

        # save proj file
        self.btn_updateproj = Button(project_container, text='Save Project...', command=self.noask_save_project)
        self.btn_updateproj.grid(row=0, column=3, sticky="WS")

        # save proj file as...
        self.btn_saveproj = Button(project_container, text='Save Project as...', command=self.ask_save_project)
        self.btn_saveproj.grid(row=0, column=4, sticky="WS")

        # grammar selection
        row += 1
        Label(self.frame, text='Grammar: ').grid(row=row, column=0, sticky='E')
        grammars = ['StandardGrammar', 'PRACGrammar']
        self.selected_grammar = StringVar()
        self.selected_grammar.trace('w', self.settings_setdirty)
        l = OptionMenu(*(self.frame, self.selected_grammar) + tuple(grammars))
        l.grid(row=row, column=1, sticky='NWE')

        # logic selection
        row += 1
        Label(self.frame, text='Logic: ').grid(row=row, column=0, sticky='E')
        logics = ['FirstOrderLogic', 'FuzzyLogic']
        self.selected_logic = StringVar()
        self.selected_logic.trace('w', self.settings_setdirty)
        l = OptionMenu(*(self.frame, self.selected_logic) + tuple(logics))
        l.grid(row=row, column=1, sticky='NWE')

        # mln section
        row += 1
        Label(self.frame, text="MLN: ").grid(row=row, column=0, sticky='NE')
        self.mln_container = FileEditBar(self.frame, directory=self.dir,
                                         filesettings={'extension': '.mln', 'ftypes': [('MLN files', '.mln')]},
                                         defaultname='*unknown{}',
                                         importhook=self.import_mln,
                                         deletehook=self.delete_mln,
                                         projecthook=self.save_proj,
                                         filecontenthook=self.mlnfilecontent,
                                         fileslisthook=self.mlnfiles,
                                         updatehook=self.update_mln,
                                         onchangehook=self.project_setdirty)
        self.mln_container.editor.bind("<FocusIn>", self._got_focus)
        self.mln_container.grid(row=row, column=1, sticky="NEWS")
        self.mln_container.columnconfigure(1, weight=2)
        self.frame.rowconfigure(row, weight=1)

        row += 1
        self.use_emln = IntVar()
        self.use_emln.set(0)
        self.cb_use_emln = Checkbutton(self.frame, text="use model extension",
                                       variable=self.use_emln,
                                       command=self.onchange_use_emln)
        self.cb_use_emln.grid(row=row, column=1, sticky="W")

        # mln extension section
        row += 1
        self.emlncontainerrow = row
        self.emln_label = Label(self.frame, text="EMLN: ")
        self.emln_label.grid(row=self.emlncontainerrow, column=0, sticky='NE')
        self.emln_container = FileEditBar(self.frame,
                                          directory=self.dir,
                                          filesettings={'extension': '.emln', 'ftypes': [('MLN extension files','.emln')]},
                                          defaultname='*unknown{}',
                                          importhook=self.import_emln,
                                          deletehook=self.delete_emln,
                                          projecthook=self.save_proj,
                                          filecontenthook=self.emlnfilecontent,
                                          fileslisthook=self.emlnfiles,
                                          updatehook=self.update_emln,
                                          onchangehook=self.project_setdirty)
        self.emln_container.grid(row=self.emlncontainerrow, column=1, sticky="NEWS")
        self.emln_container.editor.bind("<FocusIn>", self._got_focus)
        self.emln_container.columnconfigure(1, weight=2)
        self.onchange_use_emln(dirty=False)
        self.frame.rowconfigure(row, weight=1)

        # db section
        row += 1
        Label(self.frame, text="Evidence: ").grid(row=row, column=0, sticky='NE')
        self.db_container = FileEditBar(self.frame, directory=self.dir,
                                        filesettings={'extension': '.db', 'ftypes': [('Database files', '.db')]},
                                        defaultname='*unknown{}',
                                        importhook=self.import_db,
                                        deletehook=self.delete_db,
                                        projecthook=self.save_proj,
                                        filecontenthook=self.dbfilecontent,
                                        fileslisthook=self.dbfiles,
                                        updatehook=self.update_db,
                                        onchangehook=self.project_setdirty)
        self.db_container.grid(row=row, column=1, sticky="NEWS")
        self.db_container.editor.bind("<FocusIn>", self._got_focus)
        self.db_container.columnconfigure(1, weight=2)
        self.frame.rowconfigure(row, weight=1)

        # inference method selection
        row += 1
        self.list_methods_row = row
        Label(self.frame, text="Method: ").grid(row=row, column=0, sticky=E)
        self.selected_method = StringVar()
        self.selected_method.trace('w', self.select_method)
        methodnames = sorted(InferenceMethods.names())
        self.list_methods = OptionMenu(*(self.frame, self.selected_method) + tuple(methodnames))
        self.list_methods.grid(row=self.list_methods_row, column=1, sticky="NWE")

        # options
        row += 1
        option_container = Frame(self.frame)
        option_container.grid(row=row, column=1, sticky="NEWS")

        # Multiprocessing
        self.multicore = IntVar()
        self.cb_multicore = Checkbutton(option_container, text="Use all CPUs",
                                        variable=self.multicore,
                                        command=self.settings_setdirty)
        self.cb_multicore.grid(row=0, column=2, sticky=W)

        # profiling
        self.profile = IntVar()
        self.cb_profile = Checkbutton(option_container, text='Use Profiler',
                                      variable=self.profile,
                                      command=self.settings_setdirty)
        self.cb_profile.grid(row=0, column=3, sticky=W)

        # verbose
        self.verbose = IntVar()
        self.cb_verbose = Checkbutton(option_container, text='verbose',
                                      variable=self.verbose,
                                      command=self.settings_setdirty)
        self.cb_verbose.grid(row=0, column=4, sticky=W)

        # options
        self.ignore_unknown_preds = IntVar()
        self.cb_ignore_unknown_preds = Checkbutton(option_container,
                                                   text='ignore unkown predicates',
                                                   variable=self.ignore_unknown_preds,
                                                   command=self.settings_setdirty)
        self.cb_ignore_unknown_preds.grid(row=0, column=5, sticky="W")

        # queries
        row += 1
        Label(self.frame, text="Queries: ").grid(row=row, column=0, sticky=E)
        self.query = StringVar()
        self.query.trace('w', self.settings_setdirty)
        Entry(self.frame, textvariable=self.query).grid(row=row, column=1, sticky="NEW")

        # additional parameters
        row += 1
        Label(self.frame, text="Add. params: ").grid(row=row, column=0, sticky="NE")
        self.params = StringVar()
        self.params.trace('w', self.settings_setdirty)
        self.entry_params = Entry(self.frame, textvariable=self.params)
        self.entry_params.grid(row=row, column=1, sticky="NEW")

        # closed-world predicates
        row += 1
        Label(self.frame, text="CW preds: ").grid(row=row, column=0, sticky="E")

        cw_container = Frame(self.frame)
        cw_container.grid(row=row, column=1, sticky='NEWS')
        cw_container.columnconfigure(0, weight=1)

        self.cwPreds = StringVar()
        self.cwPreds.trace('w', self.settings_setdirty)
        self.entry_cw = Entry(cw_container, textvariable=self.cwPreds)
        self.entry_cw.grid(row=0, column=0, sticky="NEWS")

        self.closed_world = IntVar()
        self.cb_closed_world = Checkbutton(cw_container, text="CW Assumption",
                                           variable=self.closed_world,
                                           command=self.onchange_cw)
        self.cb_closed_world.grid(row=0, column=1, sticky='W')

        # output filename
        row += 1
        output_cont = Frame(self.frame)
        output_cont.grid(row=row, column=1, sticky='NEWS')
        output_cont.columnconfigure(0, weight=1)

        # - filename
        Label(self.frame, text="Output: ").grid(row=row, column=0, sticky="NE")
        self.output_filename = StringVar()
        self.entry_output_filename = Entry(output_cont, textvariable=self.output_filename)
        self.entry_output_filename.grid(row=0, column=0, sticky="NEW")

        # - save option
        self.save = IntVar()
        self.cb_save = Checkbutton(output_cont, text="save", variable=self.save)
        self.cb_save.grid(row=0, column=1, sticky=W)

        # start button
        row += 1
        start_button = Button(self.frame, text=">> Start Inference <<", command=self.infer)
        start_button.grid(row=row, column=1, sticky="NEW")

        self.settings_dirty = IntVar()
        self.project_dirty = IntVar()

        self.gconf = gconf
        self.project = None
        self.project_dir = os.path.abspath(ifnone(directory, ifnone(gconf['prev_query_path'], os.getcwd())))
        if gconf['prev_query_project': self.project_dir] is not None:
            self.load_project(os.path.join(self.project_dir, gconf['prev_query_project':self.project_dir]))
        else:
            self.new_project()

        self.config = self.project.queryconf
        self.project.addlistener(self.project_setdirty)

        self.mln_container.dirty = False
        self.emln_container.dirty = False
        self.db_container.dirty = False
        self.project_setdirty(dirty=False)

        self.master.geometry(gconf['window_loc_query'])

        self.initialized = True

    def _got_focus(self, *_):
        if self.master.focus_get() == self.mln_container.editor:
            if not self.project.mlns and not self.mln_container.file_buffer:
                self.mln_container.new_file()
        elif self.master.focus_get() == self.db_container.editor:
            if not self.project.dbs and not self.db_container.file_buffer:
                self.db_container.new_file()
        elif self.master.focus_get() == self.emln_container.editor:
            if not self.project.emlns and not self.emln_container.file_buffer:
                self.emln_container.new_file()

    def quit(self):
        if self.settings_dirty.get() or self.project_dirty.get():
            savechanges = messagebox.askyesnocancel("Save changes", "You have unsaved project changes. Do you want to save them before quitting?")
            if savechanges is None:
                return
            elif savechanges:
                self.noask_save_project()
            self.master.destroy()
        else:
            # write gui settings and destroy
            self.write_gconfig()
            self.master.destroy()


    ####################### PROJECT FUNCTIONS #################################

    def new_project(self):
        self.project = MLNProject()
        self.project.addlistener(self.project_setdirty)
        self.project.name = DEFAULTNAME.format('.pracmln')
        self.reset_gui()
        self.set_config(self.project.queryconf)
        self.mln_container.update_file_choices()
        self.emln_container.update_file_choices()
        self.db_container.update_file_choices()
        self.project_setdirty(dirty=True)


    def project_setdirty(self, dirty=False, *args):
        self.project_dirty.set(dirty or self.mln_container.dirty or self.db_container.dirty or
            self.emln_container.dirty)
        self.changewindowtitle()


    def settings_setdirty(self, *args):
        self.settings_dirty.set(1)
        self.changewindowtitle()


    def changewindowtitle(self):
        title = (WINDOWTITLEEDITED if (self.settings_dirty.get() or self.project_dirty.get()) else WINDOWTITLE).format(self.project_dir, self.project.name)
        self.master.title(title)


    def ask_load_project(self):
        filename = askopenfilename(initialdir=self.dir, filetypes=[('PRACMLN project files', '.pracmln')], defaultextension=".pracmln")
        if filename and os.path.exists(filename):
            self.load_project(filename)
        else:
            logger.info('No file selected.')
            return


    def load_project(self, filename):
        if filename and os.path.exists(filename):
            projdir, _ = ntpath.split(filename)
            self.dir = os.path.abspath(projdir)
            self.project_dir = os.path.abspath(projdir)
            self.project = MLNProject.open(filename)
            self.project.addlistener(self.project_setdirty)
            self.reset_gui()
            self.set_config(self.project.queryconf.config)
            self.mln_container.update_file_choices()
            self.db_container.update_file_choices()
            if len(self.project.mlns) > 0:
                self.mln_container.selected_file.set(self.project.queryconf['mln'] or list(self.project.mlns.keys())[0])
            self.mln_container.dirty = False
            if len(self.project.emlns) > 0:
                self.emln_container.selected_file.set(self.project.queryconf['emln'] or list(self.project.emlns.keys())[0])
            self.emln_container.dirty = False
            if len(self.project.dbs) > 0:
                self.db_container.selected_file.set(self.project.queryconf['db'] or list(self.project.dbs.keys())[0])
            self.db_container.dirty = False
            self.write_gconfig(savegeometry=False)
            self.settings_dirty.set(0)
            self.project_setdirty(dirty=False)
            self.changewindowtitle()
        else:
            logger.error('File {} does not exist. Creating new project...'.format(filename))
            self.new_project()


    def noask_save_project(self):
        if self.project.name and not self.project.name == DEFAULTNAME.format('.pracmln'):
            self.save_project(os.path.join(self.project_dir, self.project.name))
        else:
            self.ask_save_project()


    def ask_save_project(self):
        fullfilename = asksaveasfilename(initialdir=self.project_dir,
                                         confirmoverwrite=True,
                                         filetypes=[('PRACMLN project files','.pracmln')],
                                         defaultextension=".pracmln")
        self.save_project(fullfilename)


    def save_project(self, fullfilename):
        if fullfilename:
            fpath, fname = ntpath.split(fullfilename)
            fname = fname.split('.')[0]
            self.project.name = fname
            self.dir = os.path.abspath(fpath)
            self.project_dir = os.path.abspath(fpath)

            self.mln_container.save_all_files()
            self.emln_container.save_all_files()
            self.db_container.save_all_files()

            self.update_config()
            self.project.save(dirpath=self.project_dir)
            self.write_gconfig()

            self.load_project(fullfilename)
            self.settings_dirty.set(0)


    def save_proj(self):
        self.project.save(dirpath=self.project_dir)
        self.write_gconfig()
        self.project_setdirty(dirty=False)


    ####################### MLN FUNCTIONS #####################################

    def import_mln(self, name, content):
        self.project.add_mln(name, content)


    def delete_mln(self, fname):
        if fname in self.project.mlns:
            self.project.rm_mln(fname)
        fnamestr = fname.strip('*')
        if fnamestr in self.project.mlns:
            self.project.rm_mln(fnamestr)


    def update_mln(self, old=None, new=None, content=None, askoverwrite=True):
        if old is None:
            old = self.mln_container.selected_file.get()
        if new is None:
            new = self.mln_container.selected_file.get().strip('*')
        if content is None:
            content = self.mln_container.editor.get("1.0", END).strip()

        if old == new and askoverwrite:
            savechanges = messagebox.askyesno("Save changes", "A file '{}' already exists. Overwrite?".format(new))
            if savechanges:
                self.project.mlns[old] = content
            else:
                logger.error('no name specified!')
                return -1
        elif old == new and not askoverwrite:
            self.project.mlns[old] = content
        else:
            if new in self.project.mlns:
                if askoverwrite:
                    savechanges = messagebox.askyesno("Save changes", "A file '{}' already exists. Overwrite?".format(new))
                    if savechanges:
                        self.project.mlns[new] = content
                    else:
                        logger.error('no name specified!')
                        return -1
            else:
                self.project.mlns[new] = content
        return 1


    def mlnfiles(self):
        return list(self.project.mlns.keys())


    def mlnfilecontent(self, filename):
        return self.project.mlns.get(filename, '').strip()

    # /MLN FUNCTIONS #####################################


    ####################### EMLN FUNCTIONS #####################################

    def import_emln(self, name, content):
        self.project.add_emln(name, content)


    def delete_emln(self, fname):
        if fname in self.project.emlns:
            self.project.rm_emln(fname)
        fnamestr = fname.strip('*')
        if fnamestr in self.project.emlns:
            self.project.rm_emln(fnamestr)


    def update_emln(self, old=None, new=None, content=None, askoverwrite=True):
        if old is None:
            old = self.emln_container.selected_file.get()
        if new is None:
            new = self.emln_container.selected_file.get().strip('*')
        if content is None:
            content = self.emln_container.editor.get("1.0", END).strip()

        if old == new and askoverwrite:
            savechanges = messagebox.askyesno("Save changes", "A file '{}' already exists. Overwrite?".format(new))
            if savechanges:
                self.project.emlns[old] = content
            else:
                logger.error('no name specified!')
                return -1
        elif old == new and not askoverwrite:
            self.project.emlns[old] = content
        else:
            if new in self.project.emlns:
                if askoverwrite:
                    savechanges = messagebox.askyesno("Save changes", "A file '{}' already exists. Overwrite?".format(new))
                    if savechanges:
                        self.project.emlns[new] = content
                    else:
                        logger.error('no name specified!')
                        return -1
            else:
                self.project.emlns[new] = content
        return 1


    def emlnfiles(self):
        return list(self.project.emlns.keys())


    def emlnfilecontent(self, filename):
        return self.project.emlns.get(filename, '').strip()

    # /EMLN FUNCTIONS #####################################

    # DB FUNCTIONS #####################################
    def import_db(self, name, content):
        self.project.add_db(name, content)


    def delete_db(self, fname):
        if fname in self.project.dbs:
            self.project.rm_db(fname)
        fnamestr = fname.strip('*')
        if fnamestr in self.project.dbs:
            self.project.rm_db(fnamestr)


    def update_db(self, old=None, new=None, content=None, askoverwrite=True):
        if old is None:
            old = self.db_container.selected_file.get()
        if new is None:
            new = self.db_container.selected_file.get().strip('*')
        if content is None:
            content = self.db_container.editor.get("1.0", END).strip()

        if old == new and askoverwrite:
            savechanges = messagebox.askyesno("Save changes", "A file '{}' already exists. Overwrite?".format(new))
            if savechanges:
                self.project.dbs[old] = content
            else:
                logger.error('no name specified!')
                return -1
        elif old == new and not askoverwrite:
            self.project.dbs[old] = content
        else:
            if new in self.project.dbs:
                if askoverwrite:
                    savechanges = messagebox.askyesno("Save changes", "A file '{}' already exists. Overwrite?".format(new))
                    if savechanges:
                        self.project.dbs[new] = content
                    else:
                        logger.error('no name specified!')
                        return -1
            else:
                self.project.dbs[new] = content
        return 1


    def dbfiles(self):
        return list(self.project.dbs.keys())


    def dbfilecontent(self, filename):
        return self.project.dbs.get(filename, '').strip()

    # /DB FUNCTIONS #####################################

    # GENERAL FUNCTIONS #################################

    def select_method(self, *args):
        self.set_outputfilename()
        self.settings_setdirty()


    def onchange_use_emln(self, dirty=True, *args):
        if not self.use_emln.get():
            self.emln_label.grid_forget()
            self.emln_container.grid_forget()
        else:
            self.emln_label.grid(row=self.emlncontainerrow, column=0, sticky="NE")
            self.emln_container.grid(row=self.emlncontainerrow, column=1, sticky="NWES")
        if dirty:
            self.settings_setdirty()


    def onchange_cw(self, *args):
        if self.closed_world.get():
            self.entry_cw.configure(state=DISABLED)
        else:
            self.entry_cw.configure(state=NORMAL)
        self.settings_setdirty()


    def reset_gui(self):
        self.set_config({})
        self.db_container.clear()
        self.emln_container.clear()
        self.mln_container.clear()


    def set_config(self, newconf):
        self.config = newconf
        self.selected_grammar.set(ifnone(newconf.get('grammar'), 'PRACGrammar'))
        self.selected_logic.set(ifnone(newconf.get('logic'), 'FirstOrderLogic'))
        self.mln_container.selected_file.set(ifnone(newconf.get('mln'), ''))
        if self.use_emln.get():
            self.emln_container.selected_file.set(ifnone(newconf.get('mln'), ''))
        self.db_container.selected_file.set(ifnone(newconf.get('db'), ""))
        self.selected_method.set(ifnone(newconf.get("method"), InferenceMethods.name('MCSAT'), transform=InferenceMethods.name))
        self.multicore.set(ifnone(newconf.get('multicore'), 0))
        self.profile.set(ifnone(newconf.get('profile'), 0))
        self.params.set(ifnone(newconf.get('params'), ''))
        self.use_emln.set(ifnone(newconf.get('use_emln'), 0))
        self.verbose.set(ifnone(newconf.get('verbose'), 1))
        self.ignore_unknown_preds.set(ifnone(newconf.get('ignore_unknown_preds'), 0))
        self.output_filename.set(ifnone(newconf.get('output_filename'), ''))
        self.cwPreds.set(ifnone(newconf.get('cw_preds'), ''))
        self.closed_world.set(ifnone(newconf.get('cw'), 0))
        self.save.set(ifnone(newconf.get('save'), 0))
        self.query.set(ifnone(newconf.get('queries'), ''))
        self.onchange_cw()


    def set_outputfilename(self):
        if not hasattr(self, "output_filename") or not hasattr(self, "db_filename") or not hasattr(self, "mln_filename"):
            return
        mln = self.mln_container.selected_file.get()
        db = self.db_container.selected_file.get()
        if "" in (mln, db):
            return
        if self.selected_method.get():
            method = InferenceMethods.clazz(self.selected_method.get())
            methodid = InferenceMethods.id(method)
            filename = config.query_output_filename(mln, methodid, db)
            self.output_filename.set(filename)


    def update_config(self):

        self.config = PRACMLNConfig()
        self.config["use_emln"] = self.use_emln.get()
        self.config['mln'] = self.mln_container.selected_file.get().strip().lstrip('*')
        self.config['emln'] = self.emln_container.selected_file.get().strip().lstrip('*')
        self.config["db"] = self.db_container.selected_file.get().strip().lstrip('*')
        self.config["method"] = InferenceMethods.id(self.selected_method.get().strip())
        self.config["params"] = self.params.get().strip()
        self.config["queries"] = self.query.get()
        self.config["output_filename"] = self.output_filename.get().strip()
        self.config["cw"] = self.closed_world.get()
        self.config["cw_preds"] = self.cwPreds.get()
        self.config['profile'] = self.profile.get()
        self.config['logic'] = self.selected_logic.get()
        self.config['grammar'] = self.selected_grammar.get()
        self.config['multicore'] = self.multicore.get()
        self.config['save'] = self.save.get()
        self.config['ignore_unknown_preds'] = self.ignore_unknown_preds.get()
        self.config['verbose'] = self.verbose.get()
        self.config['window_loc'] = self.master.winfo_geometry()
        self.config['dir'] = self.dir
        self.project.queryconf = PRACMLNConfig()
        self.project.queryconf.update(self.config.config.copy())


    def write_gconfig(self, savegeometry=True):
        self.gconf['prev_query_path'] = self.dir
        self.gconf['prev_query_project': self.dir] = self.project.name

        # save geometry
        if savegeometry:
            self.gconf['window_loc_query'] = self.master.geometry()
        self.gconf.dump()


    def infer(self, savegeometry=True, options={}, *args):
        mln_content = self.mln_container.editor.get("1.0", END).strip()
        db_content = self.db_container.editor.get("1.0", END).strip()

        # create conf from current gui settings
        self.update_config()

        # write gui settings
        self.write_gconfig(savegeometry=savegeometry)

        # hide gui
        self.master.withdraw()

        try:
            print((headline('PRACMLN QUERY TOOL')))
            print()

            if options.get('mlnarg') is not None:
                mlnobj = MLN(mlnfile=os.path.abspath(options.get('mlnarg')),
                             logic=self.config.get('logic', 'FirstOrderLogic'),
                             grammar=self.config.get('grammar', 'PRACGrammar'))
            else:
                mlnobj = parse_mln(mln_content, searchpaths=[self.dir],
                                   projectpath=os.path.join(self.dir, self.project.name),
                                   logic=self.config.get('logic', 'FirstOrderLogic'),
                                   grammar=self.config.get('grammar', 'PRACGrammar'))

            if options.get('emlnarg') is not None:
                emln_content = mlnpath(options.get('emlnarg')).content
            else:
                emln_content = self.emln_container.editor.get("1.0", END).strip()

            if options.get('dbarg') is not None:
                dbobj = Database.load(mlnobj, dbfiles=[options.get('dbarg')], ignore_unknown_preds=self.config.get('ignore_unknown_preds', True))
            else:
                out(self.config.get('ignore_unknown_preds', True))
                dbobj = parse_db(mlnobj, db_content, ignore_unknown_preds=self.config.get('ignore_unknown_preds', True))

            if options.get('queryarg') is not None:
                self.config["queries"] = options.get('queryarg')

            infer = MLNQuery(config=self.config, mln=mlnobj, db=dbobj, emln=emln_content)
            result = infer.run()


            # write to file if run from commandline, otherwise save result to project results
            if options.get('outputfile') is not None:
                output = io.StringIO()
                result.write(output)
                with open(os.path.abspath(options.get('outputfile')), 'w') as f:
                    f.write(output.getvalue())
                logger.info('saved result to {}'.format(os.path.abspath(options.get('outputfile'))))
            elif self.save.get():
                output = io.StringIO()
                result.write(output)
                fname = self.output_filename.get()
                self.project.add_result(fname, output.getvalue())
                self.project.save(dirpath=self.dir)
                logger.info('saved result to file results/{} in project {}'.format(fname, self.project.name))
            else:
                logger.debug('No output file given - results have not been saved.')
        except:
            traceback.print_exc()

        # restore main window
        sys.stdout.flush()
        self.master.deiconify()
Beispiel #47
0
@author: Rodrigo
"""

from tkinter import StringVar, Tk, Label, Button, Entry, filedialog, OptionMenu

root = Tk()

# Function for the Button
def myClick():
    myLabel1 = Label(root, text= clicked.get())
    myLabel1.grid(row=2, column=0)

options = [str(x) for x in range(10)]

clicked = StringVar()
clicked.set(options[5])

# Button Widget
myButton = Button(root, text="Show selection", padx=50, pady=15, command=myClick, fg="white", bg="blue")

# Drop Down Boxes
drop = OptionMenu(root, clicked, *options)


# Palce it on a grid
myButton.grid(row=0, column=0)
drop.grid(row=1, column=0)


# Loop
root.mainloop()
Beispiel #48
0
class TwySearch(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)
        self.grid()
        self.create_widgets()

    def create_widgets(self) :

        #Search keyword
        self.keyword_desc = Label(self,text="Enter Keyword")
        self.keyword_desc.grid(row=0, column=0, columnspan=3)
        self.keyword = Entry(self)
        self.keyword.grid(row=1, column=0, columnspan=3)

        #Divider
        self.div1 = Label(self,text="____________________________________________________________________")
        self.div1.grid(row=3, column=0, columnspan=3)

        #ADVANCED OPTIONS
        self.advanced_opts_div = Label(self,text="ADVANCED OPTIONS")
        self.advanced_opts_div.grid(row=4, column=0, columnspan=3)
        #Divider
        self.div2 = Label(self,text="____________________________________________________________________")
        self.div2.grid(row=5, column=0, columnspan=3)

        #MAX_Results
        self.max_results_desc = Label(self,text="Maximum Results")
        self.max_results_desc.grid(row=7, column=0, columnspan=1)
        self.max_results = Entry(self)
        self.max_results.grid(row=8, column=0, columnspan=1)

        #Geocode
        #(latitude,longitude,radius[mi/km])
        self.geocode_desc = Label(self,text="Enter Geocode")
        self.geocode_desc.grid(row=7, column=1, columnspan=1)
        self.geocode = Entry(self)
        self.geocode.grid(row=8, column=1, columnspan=1)

        #Lang
        #use 639-1 language codes
        #picked top languages http://www.statista.com/statistics/267129/most-used-languages-on-twitter/
        self.lang_desc = Label(self,text="Select Language")
        self.lang_desc.grid(row=7, column=2, columnspan=1)
        self.lang_options = {'None':'None','Arabic':'ar', 'Dutch':'nl', 'English':'en', 'Japanese':'ja', 'Korean':'ko',
                        'Portuguese':'pt', 'Spanish':'es', 'Malay':'ms', 'Thai':'th'}
        self.lang_v = StringVar()
        self.lang_v.set(self.lang_options['None'])
        self.lang_om = OptionMenu(self, self.lang_v, *self.lang_options)
        self.lang_om.grid(row=8, column=2, columnspan=1)

        #Result_type
        self.result_type_desc = Label(self,text="Select Result Type")
        self.result_type_desc.grid(row=9, column=0, columnspan=1)
        result_type_options = ['Mixed','Recent','Popular']
        self.result_type_v = StringVar()
        self.result_type_v.set(result_type_options[0])
        self.result_type_om = OptionMenu(self, self.result_type_v, *result_type_options)
        self.result_type_om.grid(row=10, column=0, columnspan=1)

        #Max Date
        #(YYYY-MM-DD)
        self.max_date_desc = Label(self,text="Enter Max Date")
        self.max_date_desc.grid(row=9, column=2, columnspan=1)
        self.max_date = Entry(self)
        self.max_date.grid(row=10, column=2, columnspan=1)

        #Divider
        self.div3 = Label(self,text="____________________________________________________________________")
        self.div3.grid(row=11, column=0, columnspan=3)

        #File Name
        self.file_name = Button(self, text="Save as...", command=self.save_as)
        self.file_name.grid(row=12, column=0, columnspan=1)

        #Execute search
        self.search_button = Button(self, text="Search", command=self.start_search)
        self.search_button.grid(row=12, column=2, columnspan=1)

    def save_as(self):
        self.file_opt = options = {}
        options['filetypes'] = [('JSON', '.json'), ('Tab Separated', '.tsv')]
        options['initialfile'] = 'myfile.tsv'
        options['parent'] = root
        file = filedialog.asksaveasfilename(**self.file_opt)
        self.file_name = file
        self.file_type = os.path.splitext(file)[1]

    #new user popup window
    def popup(self):
        self.w=NewUser(self.master)
        self.master.wait_window(self.w.top)

    def start_search(self):
        #new user check
        user = TwitterUser()
        if user.new_user():
            webbrowser.open(user.auth_url())
            new_user = self.popup()
            user.save_user(self.w.value)
        user.read_user_json()

        search = TwitterRequest()

        #set values for search from GUI
        search.keyword = self.keyword.get()
        search.max_results = self.max_results.get()
        search.geocode = self.geocode.get()
        search.lang = self.lang_options[self.lang_v.get()]
        search.result_type = self.result_type_v.get()
        search.max_date = self.max_date.get()
        search.session = user.auth()
        messagebox.showinfo("Estimated Time to Complete", str(search.estimate_time()) + ' Seconds')

        data = search.make_request()
        save = TwitterOutput()
        #set values from GUI
        try:
            save.file_name = self.file_name
            save.out_type = self.file_type
        except:
            save.file_name = 'Output.tsv'
            save.out_type = '.tsv'
        save.result_set = data
        if save.out_type == '.json':
            save.json_output()
        elif save.out_type == '.tsv':
            save.tsv_output()
        messagebox.showinfo("Completed", "Search Completed")
class View:
    def __init__(self, controller, model, root):
        root.wm_title("Finish player in tournament")
        self.controller = controller
        self.model = model
        self.list_of_environments = self.model.get_list_of_environments()
        self.buttons = []
        self.top_frame = Frame(root)
        self.top_frame.pack()
        self.right_frame = Frame(root, bd=20)
        self.right_frame.pack(side=constants.RIGHT)

        self.bottom_frame = Frame(root)
        self.bottom_frame.pack()
        self.bottom_frame_text = Frame(root)
        self.bottom_frame_text.pack(side=constants.BOTTOM)

        self.message = Text(self.bottom_frame_text, height=1, width=50)
        self.message.pack()
        self.__show_text_in_message_box("Enter Tournament ID")

        self.var_select_env = StringVar(self.top_frame)
        self.var_select_env.set(self.list_of_environments[0])
        self.option = OptionMenu(self.top_frame, self.var_select_env,
                                 *self.list_of_environments)
        self.option.grid(row=1, column=1)
        self.var_select_env.trace('w', self.__change_environment)

        self.refresh = Button(self.top_frame,
                              text='Refresh',
                              command=self.__refresh_players)
        self.refresh.grid(row=1, column=2)
        self.__disable_button(self.refresh)

        self.top_frame.grid_columnconfigure(3, minsize=80)

        self.entry = Entry(self.top_frame, width=12)
        self.entry.grid(row=1, column=4)

        self.enter_tour_id = Button(self.top_frame,
                                    text='Change Tour ID',
                                    command=self.__change_tour_id)
        self.enter_tour_id.grid(row=1, column=5)

        self.evict_all_players = Button(self.top_frame,
                                        text='Evict All',
                                        command=self.__evict_all)
        self.evict_all_players.grid(row=1, column=6)
        self.__disable_button(self.evict_all_players)

        self.var = IntVar()
        self.var.set(1)
        Radiobutton(self.right_frame, text="Players Name", variable=self.var, value=1, command=self.refresh_view).\
            pack(anchor=W)
        Radiobutton(self.right_frame, text="Players Nickname", variable=self.var, value=2, command=self.refresh_view).\
            pack(anchor=W)
        Radiobutton(self.right_frame, text="Players ID", variable=self.var, value=3, command=self.refresh_view).\
            pack(anchor=W)
        Radiobutton(self.right_frame, text="Players chips", variable=self.var, value=4, command=self.refresh_view).\
            pack(anchor=W)

    def __show_text_in_message_box(self, text):
        self.message.config(state=constants.NORMAL)
        self.message.delete(1.0, constants.END)
        self.message.insert(constants.END, text)
        self.message.config(state=constants.DISABLED)

    def __draw_buttons(self, list_of_players_id):
        column_x = 0
        row_y = 0
        count = 0
        choice = self.var.get()
        text = ''
        for player_id in list_of_players_id:
            if choice == 1:
                text = self.model.get_player_name(player_id)
            elif choice == 2:
                text = self.model.get_player_nick_name(player_id)
            elif choice == 3:
                text = player_id
            elif choice == 4:
                text = int(self.model.get_player_chips(player_id))

            evict_button = Button(
                self.bottom_frame,
                text=text,
                width=10,
                fg="purple",
                command=lambda num=count: self.__evict_player(
                    list_of_players_id[num], self.buttons[num]))
            self.buttons.append(evict_button)
            evict_button.grid(row=row_y, column=column_x)

            if column_x == 9:
                column_x = 0
                row_y += 1
            else:
                column_x += 1

            count += 1

    def __destroy_buttons(self):
        for button in self.buttons:
            button.destroy()

        self.buttons = []

    def refresh_view(self):
        self.entry.delete(0, constants.END)
        self.__destroy_buttons()
        list_of_players_id = self.model.get_list_of_players_id()
        tour_id = self.model.get_tour_id()
        if tour_id == 0:
            self.__disable_button(self.refresh)
            self.__disable_button(self.evict_all_players)
            self.__show_text_in_message_box("Enter Tournament ID")
        else:
            self.__enable_button(self.refresh)
            self.entry.insert(0, tour_id)
            if list_of_players_id:
                self.__draw_buttons(list_of_players_id)
                self.__enable_button(self.evict_all_players)
                self.__show_text_in_message_box(
                    "Click on player button to evict player.")
            else:
                self.__disable_button(self.evict_all_players)
                self.__show_text_in_message_box("There is no active players!")

    def __disable_button(self, button):
        button.config(state='disable')

    def __enable_button(self, button):
        button.config(state='normal')

    def __refresh_players(self):
        self.controller.refresh_model_view()

    def __change_tour_id(self):
        try:
            tour_id = int(self.entry.get())
        except ValueError:
            self.__show_text_in_message_box(
                "Invalid input!!! Please enter valid ID!")
            return -1
        if tour_id > 0:
            self.controller.change_tour_id(tour_id)
        else:
            self.__show_text_in_message_box(
                "Incorrect tournament ID!!! Please enter valid ID!")

    def __change_environment(self, *args):
        self.controller.change_environment(self.var_select_env.get())

    def __evict_player(self, player_id, button):
        self.controller.evict_player(player_id)
        self.__disable_button(button)
        self.__show_text_in_message_box(
            'The player will be evicted after current hand.')

    def __evict_all(self):
        self.controller.evict_all()
        self.__disable_button(self.evict_all_players)
        for button in self.buttons:
            self.__disable_button(button)
        self.__show_text_in_message_box(
            'All players will be evicted after current hand.')
class ApplicationUI(tkinter.Frame):

	def __init__(self, master = None):
		master.minsize(width=550, height=450)
		master.maxsize(width=550, height=450)
		tkinter.Frame.__init__(self, master)
		self.grid()
		self.pack()
		self.createWidgets()
		

	def createWidgets(self):
		self.title = Label(self, text="Image!", font=("Helvetica", 16))
		self.title.grid(row=0, column=1, columnspan=2)

		self.open_file = Button(self)
		self.open_file['text'] = "OPEN"
		self.open_file["command"] = self.openfile
		self.open_file.grid(row=1, column=0)

		self.save_button = Button(self, text='SAVE',
									command=self.save_file)
		self.save_button.grid(row=1, column=1)

		self.canvas = Canvas(self, width=400, height=300)
		self.canvas.grid(row=2, column=0, rowspan=5, columnspan=4)

		self.convert_grayscale_button= Button(self)
		self.convert_grayscale_button['text'] = "Convert to\n grayscale"
		self.convert_grayscale_button["command"] = self.convert_grayscale
		self.convert_grayscale_button.grid(row=7, column=0)

		self.variable = StringVar(self)
		self.variable.set("gray") 
		self.choose_color_menu = OptionMenu(self, self.variable,"gray", "blue", "green", "red")
		self.choose_color_menu['text'] = "Choose Color"
		self.choose_color_menu.grid(row=7, column=1)
					
		self.color_button = Button(self, text="COLOR", command=self.color_image)
		self.color_button.grid(row=7, column=2)

		self.quit_button = Button(self, text="QUIT", command=self.quit)
		self.quit_button.grid(row=7, column=3)
	
	def openfile(self):
		self.filename = askopenfilename()
		self.pilImage = Image.open(self.filename)
		width, height = self.pilImage.size
		rate = 400/width
		new_width = 400
		new_height = int(height*rate)
		print (new_width, new_height)
		self.pilImage=self.pilImage.resize((new_width, new_height), Image.ANTIALIAS)
		self.image = ImageTk.PhotoImage(self.pilImage)
		self.canvas.create_image(250, 200, image=self.image, anchor='center')

	def save_file(self):
		self.filename=asksaveasfilename()
		with open(self.filename, 'wb') as f:
			self.backwards.export(f.name, format="png")

	def quit(self):
		if hasattr(self, 'player'):
			os.remove(TEMP_FILE)
		root.destroy()

	def choose_color(self):
		self.color = self.variable.get()


	def color_image(self):
		if hasattr(self, 'grayImage'):
			self.choose_color()
			if self.color == 'blue':
				color = '#0000FF'
			elif self.color == 'red':
				color = '#FF0000'
			elif self.color == 'green':
				color = '#00FF00'
			self.coloredImg = ImageOps.colorize(self.grayImage, (0,0,0,0), color)
			self.image = ImageTk.PhotoImage(self.coloredImg)
			self.canvas.create_image(250, 200, image=self.image, anchor='center')
		else:
			tkMessageBox.showinfo('Warning', "Convert the file to grayscale first")

	def convert_grayscale(self):
		self.grayImage = self.pilImage.convert('L')
		self.image = ImageTk.PhotoImage(self.grayImage)
		self.canvas.create_image(250, 200, image=self.image, anchor='center')
Beispiel #51
0
def func_main(dfolder, taskfilter):
    #Initialize Tkinter
    global main
    global datafolder
    datafolder = dfolder

    print("Öffne Einstellungen")
    main = Tk()
    main.title("Einstellungen")

    #Add window elements
    Label(main, font='Helvetica 11 bold', pady=4, padx=4,
          text="Einstellungen").grid(row=0, column=0, columnspan=3)
    Frame(main, bg="grey", height=1, bd=0).grid(column=0,
                                                row=1,
                                                columnspan=3,
                                                sticky='ew')
    Frame(main, bg="grey", height=1, bd=0).grid(column=0,
                                                row=4,
                                                columnspan=3,
                                                sticky='ew')
    Frame(main, bg="grey", height=1, bd=0).grid(column=0,
                                                row=6,
                                                columnspan=3,
                                                sticky='ew')

    #Add popup to select taskfilter
    Label(main, text="Aufgaben:").grid(row=2, column=0, pady=4, padx=4)
    value = StringVar(main)
    value.set(taskfilter)
    taskfilter = OptionMenu(main,
                            value,
                            "current",
                            "past",
                            "all",
                            command=func_update_tfilter)
    taskfilter.config(font='Helvetica 11')
    taskfilter.grid(row=2, column=1)

    #Add buttons
    Button(master=main,
           text="?",
           command=functools.partial(popup.func_main, 4)).grid(row=2, column=2)
    Button(master=main, text="Speichern", command=func_save).grid(row=3,
                                                                  column=1,
                                                                  columnspan=3,
                                                                  pady=5,
                                                                  sticky='e',
                                                                  padx=5)
    Button(master=main,
           text="Nutzerdaten aktualisieren...",
           command=func_rewrite).grid(row=5,
                                      column=0,
                                      columnspan=3,
                                      pady=5,
                                      padx=5)
    Button(master=main, text="Backup erstellen",
           command=func_backup).grid(row=7,
                                     column=0,
                                     columnspan=3,
                                     pady=5,
                                     padx=5)
Beispiel #52
0
    def init_project_frame( self ) :
        projframe = Frame(self)
        
        ######################
        #The Project Entry Form
        #
        #Current design inherited from others
        #is very bad. It should have been made as
        #json or dictionary as is in this point
        #then the subsequent coding will be much
        #eaiser.
        #BK
        ######################
        BS=StringVar()

        self.eprojectid = eprojectid= StringVar()
        self.eorganism = eorganism=StringVar()
        self.eanalyst = eanalyst=StringVar()
        self.epoc = epoc=StringVar()
        self.epi = epi=StringVar()
        self.euser = euser=StringVar()
        self.eflowcell = eflowcell=StringVar()
        self.eplatform = eplatform=StringVar()
        eplatform.set("Illumina")
        self.technique = technique=StringVar()
        self.pipehome = pipehome=StringVar()
        pipehome.set(PIPELINER_HOME)

        editframe = Frame( self )
        editframe.grid( column=0, row=3, columnspan=3 )
        
        projpanel1 = LabelFrame(editframe,text="Project Information") 
        #,fg=textLightColor,bg=baseColor)
        projpanel1.pack( side = TOP, fill=X, padx=10, pady=5, expand=YES )
        
        pipeline_panel = LabelFrame(editframe, text="Global Settings")
        pipeline_panel.pack( side=TOP, fill=X, padx=10, pady=5, expand=YES )
        
        l=Label( pipeline_panel, text="Genome:" )
        l.grid(row=1,column=3,sticky=W,padx=0,pady=5)
        l = Label( pipeline_panel, text="Pipeline Family:" )
        l.grid(row=1,column=1,sticky=W,padx=0,pady=5)
        
        annotations=['hg19','mm10','mm9','hg38','GRCh38']
        self.annotation = annotation = StringVar()
        annotation.set(annotations[0])
        #annotation.trace('w', lambda *_ :settargets(annotation) )
        
        om = OptionMenu(pipeline_panel, annotation, *annotations, command=self.set_pipeline)
        #, command=lambda _:makejson("refsets"))
        om.config() #bg = widgetBgColor,fg=widgetFgColor)
        om["menu"].config() #bg = widgetBgColor,fg=widgetFgColor)
        om.grid(row=1,column=4,sticky=W,padx=10,pady=10)
        
        pfamilys = ['exomeseq', 'rnaseq', 'genomeseq', 'mirseq', 'ChIPseq', 'scrnaseq']
        self.pfamily = pfamily = StringVar()
        pfamily.set('Select a pipeline')
        om = OptionMenu(pipeline_panel, pfamily, *pfamilys, command=self.set_pipeline)
        #, command=lambda _:makejson(pfamily.get()))
        om.config() #bg = widgetBgColor,fg=widgetFgColor)
        om["menu"].config() #bg = widgetBgColor,fg=widgetFgColor)
        om.grid(row=1,column=2,sticky=W,padx=10,pady=5)
        #add_button = Button( pipeline_panel, 
        #                    text="Set a pipeline", 
        #                    command=self.add_pipeline
        #                   )
        #add_button.grid(row=1, column=5, sticky=W, padx=10, pady=5)
        
        self.notebook = notebook = Notebook( editframe )
        self.pipelineframe = None #the pipeline frame in the notebook frame!
        
        projpanel2 = Frame(notebook) #,fg=textLightColor,bg=baseColor)
        projpanel2.pack( side = LEFT, fill=BOTH, padx=10, pady=5, expand=YES )
        notebook.add( projpanel2, text="Project Description" )
        notebook.pack( side=LEFT, fill=BOTH, padx=10, pady=5, expand=YES )

        Dscrollbar = Scrollbar(projpanel2)
        Dscrollbar.grid(row=2,column=4,rowspan=40)
        
        self.description =description= Text(projpanel2,
                           width=75,
                           height=28,
                           #bg=commentBgColor,
                           #fg=commentFgColor,
                           font=("nimbus mono bold","10"),
                           yscrollcommand = Dscrollbar.set)  
        
        description.delete("1.0", END)
        description.insert(INSERT, "Enter CCBR Project Description and Notes here.")
        #description.bind('<FocusOut>',lambda _:makejson("none"))
        description.grid(row=2,column=3,sticky="e",padx=10,pady=5)
        Dscrollbar['command']=description.yview
        
        L=Label(projpanel1, text="Project Id", anchor="ne" )
        #,bg=baseColor,fg=textLightColor)
        E = Entry(projpanel1, 
                  bd =2, 
                  width=20, 
                  #bg=entryBgColor, 
                  #fg=entryFgColor, 
                  textvariable=eprojectid 
                 )
        #L.pack(pady=5,padx=5)
        #E.pack(pady=1,padx=5)
        L.grid(row=0, column=0, sticky=W, padx=10, pady=5)
        E.grid(row=0, column=2, sticky=W, padx=10, pady=5)
        eprojectid.set("project")
        #eprojectid.trace('w', makejson)
        L2=Label(projpanel1,
                 text = "(Examples: CCBR-nnn,Labname or short project name)",
                 anchor="ne"
                )#,bg="firebrick",fg="white")
        L2.grid(row=0, column=3, padx=10, pady=5, sticky="w")

        L=Label( projpanel1,
                text="Email address",
                anchor="ne")#,bg=baseColor,fg=textLightColor)
        
        E = Entry( projpanel1, 
                  bd =2, 
                  width=20, 
                  #bg=entryBgColor, 
                  #fg=entryFgColor,
                  textvariable=euser)
        
        L3 = Label(projpanel1,
                   text ="(Mandatory field: must use @nih.gov email address)",
                   anchor="ne")
        L3.grid(row=1,column=3,padx=10,pady=5,sticky="w")
        L.grid(row=1,column=0,sticky=W,padx=10,pady=5)
        E.grid(row=1,column=2,sticky=W,padx=10,pady=5)

        #euser.trace('w', makejson)

        L=Label(projpanel1,text="Flow Cell ID",anchor="ne")
        E = Entry(projpanel1, bd =2, width=20, textvariable=eflowcell )#, bg=entryBgColor)
        L4=Label( projpanel1,
                 text="(Examples: FlowCellID, Labname, date or short project name)",
                 anchor="ne" 
                )#,bg="firebrick",fg="white")
        L4.grid(row=2,column=3,padx=10,pady=5,sticky="w")
        L.grid(row=2,column=0,sticky=W,padx=10,pady=5)
        E.grid(row=2,column=2,sticky=W,padx=10,pady=5)
        eflowcell.set("stats")
        #eflowcell.trace('w', makejson)

        Projscrollbar = Scrollbar(projframe)
        Projscrollbar.grid(row=2,column=4,rowspan=30 )
        self.jsonconf = jsonconf = Text( projframe,
                        width=80,
                        height=30,
                        #bg=projectBgColor,
                        #fg=projectFgColor,
                        font=("nimbus mono bold","11"),
                        yscrollcommand = Projscrollbar.set)
        
        Projscrollbar['command']=jsonconf.yview
        jsonconf.grid(row=3,column=0,sticky="e",padx=10,pady=5)
Beispiel #53
0
    def __init__(self, pipepanel, pipeline_name, *args, **kwargs) :
        PipelineFrame.__init__(self, pipepanel, pipeline_name, *args, **kwargs)
        self.info = None
        
        eframe = self.eframe = LabelFrame(self,text="Options") 
        #,fg=textLightColor,bg=baseColor)
        eframe.grid( row=5, column=1, sticky=W, columnspan=7, padx=10, pady=5 )
        
        label = Label(eframe,text="Pipeline")#,fg=textLightColor,bg=baseColor)
        label.grid(row=3,column=0,sticky=W,padx=10,pady=5)
        PipelineLabels=["CellRanger","Initial/QC","Clustering" ]
        Pipelines=["cellranger","scrnaseqinit","scrnaseqcluster"]

        self.label2pipeline = { k:v for k,v in zip(PipelineLabels, Pipelines)}
        
        PipelineLabel = self.PipelineLabel = StringVar()
        self.Pipeline = StringVar()

        PipelineLabel.set(PipelineLabels[0])        
        om = OptionMenu(eframe, PipelineLabel, *PipelineLabels, command=self.option_controller)
        om.config()#bg = widgetBgColor,fg=widgetFgColor)
        om["menu"].config()#bg = widgetBgColor,fg=widgetFgColor)
        #om.pack(side=LEFT,padx=20,pady=5)
        om.grid(row=3,column=1,sticky=W,padx=10,pady=5)
        
        self.crOpts = crOpts = LabelFrame( eframe, 
                                              text="CellRanger Settings" )
        self.scrCRID = scrCRID = StringVar()
        scrCRID.set("SPECIFY_PREFIX_HERE")
        self.scrExpected = scrExpected = StringVar()
        scrExpected.set("3000")

        scrcridL = Label(crOpts, text="CellRanger Sample ID: ")
        scrcridE = Entry(crOpts, bd =2, width=25, textvariable=scrCRID)
        scrcridL.grid(row=9,column=1,sticky=W,padx=10,pady=5)
        scrcridE.grid(row=9,column=2,sticky=W,padx=0,pady=5)
        
        screxpectedL = Label(crOpts, text="Expected number of cells: ")
        screxpectedE = Entry(crOpts, bd =2, width=8, textvariable=scrExpected)
        screxpectedL.grid(row=10,column=1,sticky=W,padx=10,pady=5)
        screxpectedE.grid(row=10,column=2,sticky=W,padx=0,pady=5)

        self.clusterOpts = clusterOpts = LabelFrame( eframe, 
                                              text="Clustering and tSNE Options" )

        self.scrPCs = scrPCs = StringVar()
        scrPCs.set("12")
        self.scrRes = scrRes = StringVar()
        scrRes.set("0.6")
        
        #scrPCs.trace('w', lambda a,b,c,x="scrPCs": makejson(x))

        #Filter out genes < [5] read counts in < [2] samples
        scrpcsL = Label(clusterOpts, text="Include principal components 1 through ")
        scrpcsE = Entry(clusterOpts, bd =2, width=3, textvariable=scrPCs)
        scrresL = Label(clusterOpts, text="with clustering resolution: ")
        scrresE = Entry(clusterOpts, bd =2, width=3, textvariable=scrRes)
        
        scrpcsL.grid(row=9,column=1,sticky=W,padx=10,pady=5)
        scrpcsE.grid(row=9,column=2,sticky=W,padx=0,pady=5)
        scrresL.grid(row=9,column=3,sticky=W,padx=5,pady=5)
        scrresE.grid(row=9,column=4,sticky=W,padx=0,pady=5)
        #scrRes.trace('w', lambda a,b,c,x="scrPCs": makejson(x))
        
        clusterOpts.grid( row=8, column=0, columnspan=4, sticky=W, padx=20, pady=10 )
        
        self.qcOpts = qcOpts = LabelFrame( eframe, 
                                              text="Initial Settings" )
        countL = Label( qcOpts, text="Counts/Matrix Dir:" )
        countL.grid(row=9, column=1, sticky=W, padx=10, pady=5 )
        countpath=StringVar()  
        self.countpath = countpath
        count_entry = Entry(qcOpts, 
                           bd =2, 
                           width = 50, 
                           #bg = entryBgColor, 
                           #fg = entryFgColor, 
                           textvariable = countpath, state='normal'
                          )
        count_entry.grid( row=9, column=2, columnspan=3 )
        self.count_button = count_button = Button( qcOpts, 
                             text="Open Directory", 
                             command=self.set_count_directory )
        count_button.grid( row=9, column=5 )
        #####################
        
        self.option_controller()