Esempio n. 1
0
 def save_as(self):
     import tkinter.messagebox as messagebox
     import tkinter.filedialog as filedialog
     import my_constant
     import my_io
     import traceback
     try:
         if self.clan.h:
             path = filedialog.asksaveasfilename(**my_constant.history_opt)
             if path:
                 my_io.append_history(None, path, mode='clear')
                 for item in self.clan.hv:
                     my_io.append_history(item, path, check_exist=False)
                 messagebox.showinfo('保存成功!', '已保存至' + path)
         if self.clan.d:
             path = filedialog.asksaveasfilename(**my_constant.donate_opt)
             if path:
                 my_io.append_donate(None, path, mode='clear')
                 for item in self.clan.dv:
                     my_io.append_donate(item, path, check_exist=False)
                 messagebox.showinfo('保存成功!', '已保存至' + path)
     except Exception as e:
         traceback.print_exc()
         messagebox.showerror('出错了!', '保存失败')
     self.master.master.focus_force()
Esempio n. 2
0
def convertLib():
	fileName=askopenfilename(title = "Input Library",filetypes=[('Eagle V6 Library', '.lbr'), ('all files', '.*')], defaultextension='.lbr') 
	modFileName=asksaveasfilename(title="Module Output Filename", filetypes=[('KiCad Module', '.mod'), ('all files', '.*')], defaultextension='.mod')
	symFileName=asksaveasfilename(title="Symbol Output Filename", filetypes=[('KiCad Symbol', '.lib'), ('all files', '.*')], defaultextension='.lib')
	
	logFile.write("*******************************************\n")
	logFile.write("Converting Lib: "+fileName+"\n")
	logFile.write("Module Output: "+modFileName+"\n")
	logFile.write("Symbol Output: "+symFileName+"\n")
	
	name=fileName.replace("/","\\")
	name=name.split("\\")[-1]
	name=name.split(".")[0]
	
	logFile.write("Lib name: "+name+"\n")
	
	try:
		node = getRootNode(fileName)
		node=node.find("drawing").find("library")	
		lib=Library(node,name)			
		modFile=open(modFileName,"a")
		symFile=open(symFileName,"a")			
		lib.writeLibrary(modFile,symFile)
	except Exception as e:
		showerror("Error",str(e)+"\nSee Log.txt for more info")		
		logFile.write("Conversion Failed\n\n")
		logFile.write(traceback.format_exc())
		logFile.write("*******************************************\n\n\n")
		return
	
	logFile.write("Conversion Successfull\n")
	logFile.write("*******************************************\n\n\n")		
	showinfo("Library Complete","The Modules and Symbols Have Finished Converting \n Check Console for Errors")
Esempio n. 3
0
def save_sol(save_choice):
    global location
    location=StringVar()
    check_block=True
    check_acc_clue=True
    check_dwn_clue=True
    for i in range(0,height):
        for j in range(0,width):
            if(cellblock[i][j]=="-"):
                check_block=False
                break
    for i in range(0,acc):
        if(across[i][1]==""):
            check_acc_clue=False
            break
    for i in range(0,dwn):
        if(down[i][1]==""):
            check_dwn_clue=False
            break
    if(check_block==False):
        messagebox.showinfo("Sorry!", "Solution grid has not been filled completely")
    if(check_acc_clue==False):
        messagebox.showinfo("Sorry!", "Across cluelist has not been filled completely")
    if(check_dwn_clue==False):
        messagebox.showinfo("Sorry!", "Down cluelist has not been filled completely")
    if(check_block==True and check_acc_clue==True and check_dwn_clue==True):
       file_opt=opt = {}
       if (save_choice==0):
           opt['filetypes'] = [('all files', '.*'), ('binary files', '.puz')]
           #options['initialfile'] = 'My_CW_File.puz'
           opt['parent'] = master
           fileloc = filedialog.asksaveasfilename(filetypes=opt['filetypes'])
       else:
           opt['filetypes'] = [('all files', '.*'), ('ipuz files', '.ipuz')]
           #options['initialfile'] = 'My_CW_File.ipuz'
           opt['parent'] = master
           fileloc = filedialog.asksaveasfilename(filetypes=opt['filetypes'])
       File.title=title
       File.author=author
       File.cpyrt=cpyrt
       File.notes=notes
       File.width=width
       File.height=height
       File.solnblock=cellblock
       File.acc=acc
       File.dwn=dwn
       File.across=across
       File.down=down
       File.cellno=cellno
       File.loc=fileloc
       if (save_choice==0):
           filewrite(File)
       else:
           write_ipuz(File)
       master.destroy()
       sys.exit(0)
Esempio n. 4
0
File: gui.py Progetto: hamptus/mftpy
 def exportEntry(self):
     self.selected = self.listbox.curselection()
     if self.selected:
         e = self.listitems[int(self.selected[0])]
         if hasattr(e, "filename"):
             fn = asksaveasfilename(initialfile=e.filename + ".mft")
         else:
             fn = asksaveasfilename()
         with open(fn, "wb") as mftfile:
             mftfile.write(e.dump())
Esempio n. 5
0
def writeFile(key, chunks, overwrite):
    failure = True
    filename = "{}.todo".format(key)
    while failure:
        try:
            with open(filename) as f:
                pass
        except OSError as e:
            try:
                with open(filename, "w") as f:
                    for chunk in chunks:
                        for line in chunk:
                            f.write(line)
                        f.write("\n")
            except OSError as f:
                print("""\
The file {} exists and the file system doesn't want me to touch it. Please
enter a different one.""".format(filename))
                filename = filedialog.asksaveasfilename()
                continue
            else:
                failure = False
        else:
            if overwrite:
                with open(filename, "w") as f:
                    for chunk in chunks:
                        for line in chunk:
                            f.write(line)
                        f.write("\n")
                failure = False
            else:   
                answer = input("""\
Yo, {} exists. Do you want to overwrite it? y/n
> """.format(filename))
                if answer in "yY":
                    print("""\
Okay, your funeral I guess.""")
                    with open(filename, "w") as f:
                        for chunk in chunks:
                            for line in chunk:
                                f.write(line)
                            f.write("\n")
                    failure = False
                elif answer in "nN":
                    print("""\
Okay, enter a new one.""")
                    filename = filedialog.asksaveasfilename()
                    continue
                else:
                    print("""\
Didn't get that, so I'm assuming "no." (Aren't you glad this is my default
behavior for garbled input?)""")
                    filename = filedialog.asksaveasfilename()
                    continue
Esempio n. 6
0
    def on_key_pressed(self, key_pressed_event):
        key = key_pressed_event.keysym

        if "Shift" in key or "Control" in key:
            return

        print(key_pressed_event.keysym)

        self.pressed_keys.append(key)

        if self.pressed_keys == self.easteregg_keys:
            print('A winner is you!')
            filedialog.asksaveasfilename()
Esempio n. 7
0
 def save(self):
     self.paused = True
     try:
         if platform.system() == 'Windows':
             game = filedialog.asksaveasfilename(initialdir = "./saves",title = "choose your file",filetypes = (("all files","*.*"),("p files","*.p")))
         else:
             game = filedialog.asksaveasfilename(initialdir = "./saves",title = "choose your file",filetypes = (("p files","*.p"),("all files","*.*")))
         self.root.title('Warriors & Gatherers - '+shortString(game))
         # Copy logs
         for string in self.playerNames:
             shutil.copyfile(string+'.log',game[:-2]+'_'+string+'.log')
         pickle.dump(self.data, open(game, "wb" ) )
     except:
         return None
Esempio n. 8
0
 def ask_save(filepath, filetypes=None):
     """ Pop-up to get path to save a new file """
     if filetypes is None:
         filename = filedialog.asksaveasfilename()
     else:
         # In case filetypes were not configured properly in the
         # arguments_list
         try:
             filename = filedialog.asksaveasfilename(filetypes=filetypes)
         except TclError as te1:
             filetypes = FileFullPaths.prep_filetypes(filetypes)
             filename = filedialog.asksaveasfilename(filetypes=filetypes)
         except TclError as te2:
             filename = filedialog.asksaveasfilename()
     if filename:
         filepath.set(filename)
def savefile(master, text):
    try:
        filename = filedialog.asksaveasfilename(filetypes=(("Text files", "*.txt"),
                                                         ("All files", "*.*") ))
        if bAppendtxtwhensaving == 1:
            filename = filename + ".txt"
        
        if not filename == "":
            txtcontent = iolib.writetotextfile(text, filename)
            if txtcontent == 1:
                print("Something went wrong while saving : %s.\n Does this user have to approrite permissions to the file?" % (filename))
                messagebox.showerror("Error", "Something went wrong while saving to: %s.\n Do you have the approrite permissions to the file?" % (filename))
            else:
                conversionsaved=1
                print("Saved conversion to %s." % (filename))
                messagebox.showinfo("Saved", "Saved conversion to %s." % (filename))
                # print(txtcontent) # debugging purposes.
        else:
            # print("passed") # debugging purposes.
            pass
    except Exception as e:
        print("Error while loading file picker.\n %s." % (str(e)))
        messagebox.showerror("Error", "Error while loading file save.\n %s." % (str(e)))
        filename = 1
    return filename
Esempio n. 10
0
 def _save_theme_as(self, event=None):
     """Save current changes to a file."""
     fname = asksaveasfilename()
     if not fname:
         return
     self.__save_changes(fname)
     return fname
Esempio n. 11
0
def write_refl(headers, q, refl, drefl, path):
    '''
    Open a file where the previous was located, and drop a refl with the same
    name as default.
    '''
    # we don't want a full GUI, so keep the root window from appearing
    Tk().withdraw()

    fullpath=asksaveasfilename(initialdir=path,
                initialfile=headers['title']+'.refl',
                defaultextension='.refl',
                filetypes=[('reflectivity','.refl')])

#    fullpath = re.findall('\{(.*?)\}', s)
    if len(fullpath)==0:
        print('Results not saved')
        return

    textlist = ['#pythonfootprintcorrect 1 1 2014-09-11']
    for header in headers:
        textlist.append('#'+header+' '+headers[header])
    textlist.append('#columns Qz R dR')

    for point in tuple(zip(q,refl,drefl)):
        textlist.append('{:.12g} {:.12g} {:.12g}'.format(*point))
#    print('\n'.join(textlist))
    with open(fullpath, 'w') as reflfile:
        reflfile.writelines('\n'.join(textlist))

    print('Saved successfully as:', fullpath)
Esempio n. 12
0
    def process_file(self):
        
        if self.station_id is None or self.station_id == '':
            easygui.msgbox("Please fill in a site id", "Error")
            return
        
       
        #exception handling for the export process
        try:
            out_fname = filedialog.asksaveasfilename()
            if out_fname == '':
                return
#           #get the beginning and end of the selection
            site = self.station_id.get()
            date1 = self.date1.get()
            date2 = self.date2.get()
            tz = self.tzstringvar.get()
            daylight_savings = self.daylightSavings.get()
           
            get_wind_data(out_fname, site, date1, date2, tz, daylight_savings)         
            #convert string to date time, then convert to matplotlib number
            #tz = pytz.timezone(str(self.tzstringvar.get()))
            
            easygui.msgbox("Success grabbing file!", "Success")
        except:
            easygui.msgbox("Could not process file, please check station id and date time entries.", "Error")
Esempio n. 13
0
def start_window():
	import import_from_xlsx

	if not hasattr(import_from_xlsx, 'load_state'):
		setattr(import_from_xlsx, 'load_state', True)
	else:
		reload(import_from_xlsx)
	
	''' tag library '''
	'''
	each tag library corresponds to sqlite table name
	each tag corresponds to sqlite database column name
	'''

	''' config file '''
	config = configparser.ConfigParser()
	config.read(controllers + 'config.ini', encoding='utf-8')

	def convert_to_db():
		source = import_from_xlsx.import_xlsx_path.get_()
		destination = import_from_xlsx.destination_path.get_()

		convert_xlsx_to_db.convert_database(source, destination)
		import_from_xlsx.import_from_xlsx.destroy()

	import_from_xlsx.import_browse_button.settings(\
		command=lambda: import_from_xlsx.import_xlsx_path.set(filedialog.askopenfile().name))
	import_from_xlsx.time_browse_button.settings(\
		command=lambda: import_from_xlsx.time_xlsx_path.set(filedialog.askopenfile().name))
	import_from_xlsx.destination_browse_button.settings(\
		command=lambda: import_from_xlsx.destination_path.set(filedialog.asksaveasfilename() + '.db'))
	import_from_xlsx.cancel_button.settings(command=import_from_xlsx.import_from_xlsx.destroy)
	import_from_xlsx.import_button.settings(command=convert_to_db)
Esempio n. 14
0
 def h2d(self):
     import my_constant
     import tkinter.messagebox as messagebox
     import tkinter.filedialog as filedialog
     import my_io
     import traceback
     play = self.master.master.play
     if not self.clan.h:
         FileMenu.read_h(self)
         if not self.clan.h: return
     path = filedialog.asksaveasfilename(**my_constant.donate_opt)
     if path:
         try:
             my_io.append_donate(None, path, mode='clear')
             my_io.append_history(None, path + '.clh', mode='clear')
             for item in self.clan.hv:
                 self.clan.imah.copyfrom(item)
                 play.InitFlag[0] = True
                 play.flash()
                 play.InitFlag[0] = False
                 my_io.append_donate(self.clan.imad, path, check_exist=False)
                 my_io.append_history(self.clan.imah, path+ '.clh', check_exist=False)
             play.cls()
         except Exception as e:
             print('path=%s\n%s'%(path,e))
             traceback.print_exc()
             messagebox.showerror('出错了!', '保存失败')
         else: messagebox.showinfo('保存成功!', '已保存至' + path)
Esempio n. 15
0
    def export_to_csv(self):
        """
        asksaveasfilename Dialog für den Export der Ansicht als CSV Datei.
        """        
        all_items = self.columntree.get_children()
        all_items = list(all_items)
        all_items.sort()
        data = [("Id", "Datum", "Projekt", "Startzeit", "Endzeit", "Protokoll",
                 "Bezahlt", "Stunden")]
        for item in all_items:
            t_id = self.columntree.set(item, column="id")
            datum = self.columntree.set(item, column="datum")
            projekt = self.columntree.set(item, column="projekt")
            startzeit = self.columntree.set(item, column="startzeit")
            endzeit = self.columntree.set(item, column="endzeit")
            protokoll = self.columntree.set(item, column="protokoll")
            bezahlt = self.columntree.set(item, column="bezahlt")
            stunden = self.columntree.set(item, column="stunden")
            stunden = stunden.replace('.', ',')

            data.append((t_id, datum, projekt, startzeit, endzeit, protokoll,
                        bezahlt, stunden))

        filename = filedialog.asksaveasfilename(
                                        defaultextension=".csv",
                                        initialdir=os.path.expanduser('~'),
                                        title="Export alle Daten als CSV Datei",
                                        initialfile="pystunden_alle_daten",
                                        filetypes=[("CSV Datei", ".csv"),
                                                   ("Alle Dateien", ".*")])        
        if filename:
            with open(filename, "w", newline='') as f:
                writer = csv.writer(f, delimiter=';')
                writer.writerows(data)
Esempio n. 16
0
 def browse_o(self):
     path = filedialog.asksaveasfilename()
     if path:
         self.entry_o.delete(0, 'end')
         self.entry_o.insert(0, path)
         self.entry_changed()
         self.fcd_dir = os.path.dirname(path)#????????
Esempio n. 17
0
 def gravar(self):
     f = open('output.wav','w')
     path = f.name
     f.close()
     recorder.record(path)
     self.path = filedialog.asksaveasfilename(defaultextension='wav')
     os.rename(path, self.path)
Esempio n. 18
0
	def onCreate(self):
		filename = asksaveasfilename()
		if filename:
			alltext = self.gettext()
			open(filename,"w").write(alltext)
			self._commitTask(command = "kubectl create -f ",
							filename = filename)	
Esempio n. 19
0
 def __call__(self):
     filename = filedialog.asksaveasfilename(
         initialdir="/", title="ログの保存", filetypes=(("テキスト ファイル", "*.txt"), ("全ての ファイル", "*.*")))
     log = LogController.LogController().get()
     f = open(filename, 'w')
     f.write(log)
     f.close()
 def fileDialog(self, fileOptions=None, mode='r', openMode=True):
     defaultFileOptions = {}
     defaultFileOptions['defaultextension'] = ''
     defaultFileOptions['filetypes'] = []
     defaultFileOptions['initialdir'] = ''
     defaultFileOptions['initialfile'] = ''
     defaultFileOptions['parent'] = self.root
     defaultFileOptions['title'] = ''
     if fileOptions is not None:
         for key in fileOptions:
             defaultFileOptions[key] = fileOptions[key]
     if openMode is True:
         file = askopenfilename(**defaultFileOptions)
         if file is not None and file is not '':
             try :
                 self.compressionCore.openImage(file)
                 self.compressionCore.imageSquaring(self.NValue.get())
             except Exception:
                 messagebox.showerror(
                         _("Error"),
                         "It's impossible open the image.")
                 return 
             self.updateGUI(original=True)
     else:
         file = asksaveasfilename(**defaultFileOptions)
         if file is not None and file is not '':
             try:
                 self.compressionCore.compressedImage.save(fp=file, format="bmp")
             except Exception:
                 messagebox.showwarning(
                     _("Error"),
                     "Fail to save compressed image. Please try again.")
Esempio n. 21
0
 def save_inst(self):
     instance_name = self.get_selected_instance_name()
     if instance_name != '':
         file_name = asksaveasfilename(
             parent=self, filetypes=[('lbk', '.lbk'), ('*', '.*')])
         if file_name != '':
             self.save_instance(instance_name, file_name)
Esempio n. 22
0
File: main.py Progetto: DaZhu/pygubu
 def do_save_as(self):
     options = {
         'defaultextension': '.ui',
         'filetypes': ((_('pygubu ui'), '*.ui'), (_('All'), '*.*'))}
     fname = filedialog.asksaveasfilename(**options)
     if fname:
         self.do_save(fname)
Esempio n. 23
0
	def set_file(textbox):
		out_file = filedialog.asksaveasfilename()
		if len(out_file) != 0:
			textbox.setData(out_file + '.rybdb')
		out_file = out_file.split('/')
		file_name = out_file[-1]
		dest_path = '/'.join(out_file[:-1])
Esempio n. 24
0
def write_css(*args):
    global item_list
    m = find("id", content)
    for match in m:
        item_list.append(clean(match, 'id', '#'))
 
    #find all classes, assign to variable
    m = find("class", content)
    for match in m:
        item_list.append(clean(match, 'class', '.'))
 
    #remove duplicate items in list
    items = set(item_list)
 
    #open file to write CSS to
    f = open(asksaveasfilename(), "w")
 
    #write tag selectorrs to CSS file
    for tag in tags:
        f.write(tag + "{\n\n}\n\n")

    #for each item in list, print item to CSS file
    for i in items:
        f.write(i)
 
    #close the opened file
    f.close()
 def save_session_dialog(self,*event):
     
     path_list = []
     for tab_not_closed_index in range(len(self.model.tabs_html)-1,-1,-1):
         if self.model.tabs_html[tab_not_closed_index].save_path:
             path_list.insert(0,self.model.tabs_html[tab_not_closed_index].save_path)
      # True False or None 
     answer = messagebox.askyesnocancel(
         title=_(u"Question"),
         message=_(u"Voulez vous sauvegarder la session dans un fichier spécifique ?")
     )
     if answer:
        file_path = filedialog.asksaveasfilename(defaultextension=JSON["defaultextension"],
                                              initialdir=self.model.guess_dir(),
                                              filetypes=JSON["filetypes"],
                                              initialfile="webspree_session.json")
        if file_path:
            session_object = {
                "webspree":"webspree_session",
                "version": "1.1.0",
                "path_list": path_list,
                "tab_index": self.model.selected_tab,
                "zoom": self.zoom_level,
                "edit_mod": self.mode.get()
            }
                
            JSON_TEXT = json.dumps(session_object,sort_keys=False, indent=4, separators=(',',':'))
            codecs.open(file_path, 'w', "utf-8").write(JSON_TEXT)
     elif not answer:
         self.model.set_option("previous_files_opened", path_list)
     elif answer is None:
         pass
Esempio n. 26
0
def getfilepath():
    """Calls tk to create a file dialog that asks the user where they want to place the file."""
    # If root.withdraw() is added, window is only accessible by alt-tab.
    root = tk.Tk()
    return filedialog.asksaveasfilename(initialdir='C:/', defaultextension='.csv',
                                             initialfile='Inventory ' + str(datetime.date.today()),
                                             filetypes=(("Comma Separated Values",'*.csv'),("All Files", '*.*')))
def generate_by_date_2():
	
	try:
		cur=dbconn.cursor()
		cur.execute("select distinct mc.ministry_county_name,c.course_name, r.first_name, r.middle_name, r.sur_name, r.personal_id, r.national_id, r.mobile_no, r.email_id,r.scheduled_from,r.scheduled_to,r.attended_from,r.attended_to from register r join ministry_county mc on mc.ministry_county_id = r.ministry_county_id join courses c on c.course_id = r.course_id where scheduled_from between  '%s' and '%s' order by scheduled_from;"%(fromentry.get(),toentry.get()))
		get_sch_report=cur.fetchall()
		
		if get_sch_report ==[]:
			messagebox.showwarning('Warning', "No data found from period '%s' to '%s'" %(fromentry.get(),toentry.get()))
		else: 
			file_format = [("CSV files","*.csv"),("Text files","*.txt"),("All files","*.*")] 
			all_trained_mdac_report = asksaveasfilename( title ="Save As='.csv'", initialdir="C:\\Users\\usrname", initialfile ='Generate by date All Trained MDAC Report', defaultextension=".csv", filetypes= file_format)
			outfile = open(all_trained_mdac_report, "w")
			writer = csv.writer(outfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL)
			writer.writerow( ['ministry_county_name','course_name','first_name','middle_name','sur_name','personal_id','national_id','mobile_no','email_id','scheduled_from','scheduled_to','attended_from','attended_to'])
			
			for i in get_sch_report:
				writer.writerows([i])
			outfile.close()
			gui.destroy()
			
	except psycopg2.InternalError:
		messagebox.showerror('Error', 'You need to input dates')
		messagebox.showerror('Error', 'Fatal Error occured')
		sys.exit(0)
			
	except:
		pass
Esempio n. 28
0
    def btn_save_command(self):
        save_filename = asksaveasfilename(filetypes=(("Excel file", "*.xls"), ))
        if not save_filename:
            return
        filename, file_extension = os.path.splitext(save_filename)
        if file_extension == '':
            save_filename += '.xls'
        wb = xlwt.Workbook()
        ws = wb.add_sheet('Найденные телефоны')

        phone_style = xlwt.XFStyle()
        phone_style.num_format_str = '0000000000'

        ws.col(0).width = 256 * 11

        line = 0
        for k in Parser.phones.keys():
            if k not in Parser.source_excel.keys():
                try:
                    v = Parser.phones[k]
                except EOFError:
                    v = ''
                ws.write(line, 0, int(k), phone_style)
                ws.write(line, 1, v)
                line += 1

        wb.save(save_filename)
        os.startfile(save_filename, 'open')
Esempio n. 29
0
def main():
    # By default Tk shows an empty window, remove it
    tkinter.Tk().withdraw()

    input('Press enter to select the base file')
    baseFilePath = askopenfilename(title='Select the base file to read')
    print('Base file: ' + baseFilePath)

    input('Press enter to select the merge file')
    mergeFilePath = askopenfilename(title='Select the merge file to read')
    print('Merge file: ' + mergeFilePath)
    
    input('Press enter to select the save file')
    saveFilePath = asksaveasfilename()
    print('Save file: ' + saveFilePath)

    baseFile = csv.reader(open(baseFilePath, 'r', encoding='utf-8'))
    mergeFile = deque(csv.reader(open(mergeFilePath, 'r', encoding='utf-8')))
    saveFile = csv.writer(open(saveFilePath, 'w', encoding='utf-8'), delimiter=';', quoting=csv.QUOTE_NONE)

    mergeRow = mergeFile.popleft()
    for baseRow in baseFile:
        if mergeRow[0] == baseRow[0]:
            mergeCol = mergeRow[1]
            try:
                mergeRow = mergeFile.popleft()
            except:
                pass
        else:
            mergeCol = ''

        saveFile.writerow([baseRow[0], mergeCol, baseRow[1]])
Esempio n. 30
0
 def export(self, fullRes = True):
     """Exports the image with bounding boxes drawn on it.
     
     A save-file dialog will be shown to the user to select the target file name.
     
     fullRes - If this set to true and the DetectionFrame instance has been constructed
               with an image given by filename, a full-resolution image will be exported,
               otherwise just the thumbnail will be used.
     """
     
     filename = tkFileDialog.asksaveasfilename(parent = self, title = 'Export image', defaultextension = '.png',
                                               filetypes = [('Portable Network Graphics', '.png'), ('JPEG image', '.jpg .jpeg')])
     if filename:
         if not self._detectionFrame._filepath is None:
             img = Image.open(self._detectionFrame._filepath)
             if not fullRes:
                 img.thumbnail((180,512), Image.ANTIALIAS)
         else:
             img = self._detectionFrame.thumb.copy()
         # Draw bounding boxes of the detected objects
         for i, det in enumerate(self._detectionFrame.detections):
             img = det.scale(float(img.size[0]) / self._detectionFrame.thumb.orig_size[0]).drawToImage(img, gui_utils.getAnnotationColor(i), 2)
         # Save file
         try:
             options = {}
             ext = os.path.splitext(filename)[1].lower()
             if ext == '.jpg':
                 options['quality'] = 96
             elif ext == '.png':
                 options['compress'] = True
             img.save(filename, **options)
         except Exception as e:
             tkMessageBox.showerror(title = 'Export failed', message = 'Could not save image:\n{!r}'.format(e))
Esempio n. 31
0
    raise SystemExit(0)

threshMax = int(d.threshMax)
threshMin = int(d.threshMin)
binSize = int(d.binSize)

# Get .csv files to work with
fileList = filedialog.askopenfilenames(parent=root, title="Select raw data files",
                                        filetypes=(("comma-separated values", "*.csv"), ("all files","*.*")))

if not len(fileList) > 0:
    print("No input files provided - exiting.")
    raise SystemExit(0)

# Select save location for output
outputFile = filedialog.asksaveasfilename(title="Save output file as", defaultextension=".csv",
                                       filetypes=(("comma-separated values", "*.csv"), ("all files","*.*")))

if not outputFile:
    print("No output file - exiting.")
    raise SystemExit(0)

# initalise some variables - why do I do this in python? Habit, I guess.
cleanlines = []  # list for csv entries
summary = {}  # dictionary for bins and their sizes
i = 0  # track # of files so we can look cool
skippedFiles = []  # files we couldn't process

startTime = time.time() # we'll record the time so we can look really smug at the end

for someFile in fileList: # iterate the file list
    print("Processing " + os.path.basename(someFile))
Esempio n. 32
0
 def save_as_button_func():
     save_path = filedialog.asksaveasfilename(filetypes=[('MIDI files',
                                                          '*.mid')])
     save_path += '.mid' if save_path[-4:] != '.mid' else ''
     save_as_label.config(text=save_path)
     info['save_path'] = save_path
Esempio n. 33
0
    def _btnReadClick(self, event):

        if self._validIp():
            self.path = asksaveasfilename(filetypes=[('All', '.*')],
                                          title="Read<----Server")
            Request().Get(self.path, self.txtIp.get())
Esempio n. 34
0
 def save_file(self):
     filename = asksaveasfilename()
     if len(filename) > 0 and filename.endswith(".json"):
         self.save_config(filename)
Esempio n. 35
0
import tkinter as tk
from tkinter import filedialog
import os

application_window = tk.Tk()
my_filetypes = [('all files', '.*'), ('text files', '.*txt')]

answer = filedialog.askdirectory(parent = application_window,
                                 initialdir = os.getcwd(),
                                 title = "Please select a folder")
amswer = filedialog.askopenfilename(parent = application_window,
                                 initialdir = os.getcwd(),
                                 title = "Please select a file",
                                 filetypes = my_filetypes)
answer = filedialog.askopenfilenames(parent = application_window,
                                     initialdir = os.getcwd(),
                                     title = "Please select one or more files",
                                     filetypes = my_filetypes)
answer = filedialog.asksaveasfilename(parent = application_window,
                                      initialdir = os.getcwd(),
                                      title = "Please select a file name for saving:",
                                      filetypes = my_filetypes)
Esempio n. 36
0
)

#the r must be included to avoid unicode errors wherein the SMILES code starts a unicodeescape.
#In the future a line of code must add this r to files which are read in.

mcy = input("Enter a SMILES value for the structure:")
# example smiles to use:   mcy-DASP3-LR = r'O=C([C@@H](CC(N[C@@H](CCC/N=C(N)\N)C(N[C@@H](/C=C/C(C)=C/[C@H](C)[C@@H](OC)CC1=CC=CC=C1)[C@H](C)C(N[C@@H](C(O)=O)CC2)=O)=O)=O)NC([C@H](CC(C)C)NC([C@@H](C)NC(C(N(C)C2=O)=C)=O)=O)=O)O'
m = Chem.MolFromSmiles(mcy)
print('')
print('')
print('Please select an output folder for the data.')
input('Press Enter to select a file')
from tkinter.filedialog import asksaveasfilename
root = tk.Tk()
root.withdraw()
fragments = asksaveasfilename()
print(
    '--------------------------------------------------------------------------------------------------------------------------------------'
)
print('')
print('')
print('')
print(
    'SMARTS manual is available at Daylight Chemical Information Systems https://www.daylight.com/dayhtml/doc/theory/theory.smarts.html'
)
print('')
print('')
print('Examples for peptide analysis:')
print('Methoxy = $([CHX4][O][CH3])')
print('benzylic = $([CH2X4][c])')
print('methyl-methoxy-ethane = $([CH3][CHX4][CHX4][O][CH3])')
 def inpo3():
     namein = filedialog.asksaveasfilename(parent=win)
     e3.insert(END, namein)
     print(e3.get())
Esempio n. 38
0
def load_raw_data_excel(raw_data_path) -> pd.DataFrame:
    """
        ritorna un pandas Dataframe dal file excel specificato dal percorso
        :param raw_data_path:
        :return:
        """
    data = pd.read_excel(raw_data_path,
                         sheet_name=0,
                         header=0,
                         index_col=False,
                         keep_default_na=True)
    return data


# ignore all warnings
if not sys.warnoptions:
    warnings.simplefilter("ignore")

print("Selezionare il file xlsx da convertire:")
Tk().withdraw(
)  # we don't want a full GUI, so keep the root window from appearing
filename = fd.askopenfilename(initialdir="/",
                              title="Seleziona csv",
                              filetypes=(("xlxs files", "*.xlsx"),
                                         ("all files", "*.*")))
print("Conversione del file in corso...")
data = load_raw_data_excel(filename)
print("Selezionare la destinazione su cui salvare il file come csv:")
export_file_path = filedialog.asksaveasfilename(defaultextension='.csv')
data.to_csv(export_file_path, index=None, header=True)
Esempio n. 39
0
def pickle_gui(to_be_pickled, extension=".pickle"):
    """ Uses gui for learning path where object will be pickled.
    
    """
    pickle(to_be_pickled, asksaveasfilename(), extension)
Esempio n. 40
0
def diskRead():
    # Draw parameter entry window
    parameterWindow = Toplevel(mainWindow)
    parameterWindow.title('Copy Disk Parameters')
    parameterWindow.resizable(width=False, height=False)
    parameterWindow.transient(mainWindow)
    parameterWindow.grab_set()

    r_extend_var = IntVar()
    Checkbutton(parameterWindow,
                text="Copy only blocks with BAM entry",
                variable=r_bam_var).grid(row=0, sticky=W, padx=10, pady=4)
    Checkbutton(parameterWindow, text="Copy 40 tracks",
                variable=r_extend_var).grid(row=1, sticky=W, padx=10, pady=4)
    Checkbutton(parameterWindow,
                text="Verify after copying",
                variable=r_verify_var).grid(row=2, sticky=W, padx=10, pady=4)
    Button(parameterWindow,
           text='Select output file',
           command=parameterWindow.quit).grid(row=3,
                                              columnspan=2,
                                              sticky=EW,
                                              padx=4,
                                              pady=4)
    parameterWindow.mainloop()

    bamcopy = r_bam_var.get()
    verify = r_verify_var.get()
    if r_extend_var.get() > 0:
        tracks = 40
        allocated = 768
    else:
        tracks = 35
        allocated = 683
    parameterWindow.destroy()

    # Get output file
    filename = filedialog.asksaveasfilename(title='Select output file',
                                            filetypes=(("D64 files", "*.d64"),
                                                       ('All files', '*.*')))
    if not filename:
        return

    # Establish serial connection
    diskbuddy = Adapter()
    if not diskbuddy.is_open:
        messagebox.showerror('Error', 'DiskBuddy64 Adapter not found !')
        return

    # Check if IEC device ist present
    if not diskbuddy.checkdevice(device.get()):
        diskbuddy.close()
        messagebox.showerror(
            'Error', 'IEC device ' + str(device.get()) + ' not found !')
        return

    # Upload fast loader to disk drive RAM
    if diskbuddy.uploadbin(FASTUPLOAD_LOADADDR, FASTUPLOAD_BIN) > 0 \
    or diskbuddy.fastuploadbin(FASTREAD_LOADADDR, FASTREAD_BIN) > 0:
        diskbuddy.close()
        messagebox.showerror('Error', 'Failed to upload fastread.bin !')
        return

    # Create output file
    try:
        f = open(filename, 'wb')
    except:
        diskbuddy.close()
        messagebox.showerror('Error', 'Failed to create output file !')
        return

    # Fill output file with default values
    for track in range(1, tracks + 1):
        for sector in range(getsectors(track)):
            f.write(b'\x4B' + b'\x01' * 255)

    # Read BAM if necessary
    progress = Progressbox(mainWindow, 'DiskBuddy64 - Reading disk',
                           'Copy disk to D64 file ...')
    if bamcopy > 0:
        dbam = BAM(diskbuddy.readblock(18, 0))
        if not dbam.bam:
            f.close()
            diskbuddy.close()
            progress.destroy()
            messagebox.showerror('Error', 'Failed to read the BAM !')
            return
        allocated = dbam.getallocated()
        if tracks > 35:
            allocated += 85

    # Read disk
    copied = 0
    errors = 0
    starttime = time.time()
    for track in range(1, tracks + 1):
        secnum = getsectors(track)
        sectors = [x for x in range(secnum)]
        seclist = []

        # Cancel sectors without BAM entry
        if bamcopy > 0 and track < 36:
            for x in range(secnum):
                if dbam.blockisfree(track, x): sectors.remove(x)

        # Optimize order of sectors for speed
        sector = trackgap * (track - 1)
        counter = len(sectors)
        while counter:
            sector %= secnum
            while not sector in sectors:
                sector += 1
                if sector >= secnum: sector = 0
            seclist.append(sector)
            sectors.remove(sector)
            sector += interleave
            counter -= 1

        # Send command to disk drive, if there's something to read on track
        progress.setactivity('Copy disk to D64 file ...' + '\nTrack: ' +
                             str(track) + ' of ' + str(tracks))
        seclen = len(seclist)
        if seclen > 0:
            if diskbuddy.startfastread(track, seclist) > 0:
                f.close()
                diskbuddy.close()
                progress.destroy()
                messagebox.showerror('Error', 'Failed to read from disk !')
                return

        # Read track
        diskbuddy.timeout = 3
        for sector in seclist:
            f.seek(getfilepointer(track, sector))
            block = diskbuddy.getblockgcr()
            if not block:
                f.close()
                diskbuddy.close()
                progress.destroy()
                messagebox.showerror('Error', 'Failed to read from disk !')
                return
            if not len(block) == 256:
                errors += 1
            else:
                f.write(block)
            diskbuddy.timeout = 1
            copied += 1
        progress.setvalue(copied * 100 // allocated)

    # Finish all up
    if verify == 0:
        diskbuddy.executememory(MEMCMD_SETTRACK18)
    duration = time.time() - starttime
    f.close()
    diskbuddy.close()
    progress.destroy()
    if verify > 0:
        diskVerify(filename, bamcopy, tracks)
    else:
        messagebox.showinfo(
            'Mission accomplished', 'Copying finished !\nRead Errors: ' +
            str(errors) + '\nDuration: ' + str(round(duration)) + ' sec')
Esempio n. 41
0
 def saveSnapshot(app):
     path = filedialog.asksaveasfilename(initialdir=os.getcwd(), title='Select file: ',filetypes = (('png files','*.png'),('all files','*.*')))
     if (path):
         # defer call to let filedialog close (and not grab those pixels)
         if (not path.endswith('.png')): path += '.png'
         app._deferredMethodCall(afterId='saveSnapshot', afterDelay=0, afterFn=lambda:app.getSnapshot().save(path))
Esempio n. 42
0
 def save_as(self):
     name1 = asksaveasfilename(filetypes=[(("Log files"), "*.*")])
     self.new_img.save(str(name1) + '.png')
Esempio n. 43
0
    def go(self):

        sound_name_list = self.sound_name_list
        key_presses = self.key_presses
        ops = self.ops
        quorum = self.quorum
        play_duration = self.play_duration
        jitter_range = self.jitter_range
        practice = self.practice
        monitor_idx = self.monitor_idx
        beamer_idx = self.beamer_idx
        monitor_fps = self.monitor_fps
        beamer_fps = self.beamer_fps
        back_color = self.back_color

        thresh_results = []
        abort = 0

        # set up the monitors
        beamer = None
        monitor = visual.Window(size=self.monsize,
                                color=self.back_color,
                                screen=monitor_idx,
                                winType="pyglet",
                                useFPO=False,
                                waitBlanking=False)

        print("Monitor fps: " + str(monitor_fps))
        if beamer_idx > -1:
            beamer = visual.Window(size=self.beamsize,
                                   color=back_color,
                                   screen=beamer_idx,
                                   winType="pyglet",
                                   useFPO=False,
                                   waitBlanking=False)
            print("Beamer fps: " + str(beamer_fps))

        visobjs = {}
        beamobjs = {}
        # set up the complex of visual objects

        # text
        visobjs["tonepress_label"] = visual.TextStim(win=monitor,
                                                     text="Sound/Press",
                                                     pos=(-0.9, 0.9),
                                                     height=0.07,
                                                     color=self.text_color,
                                                     alignHoriz="left")
        visobjs["tonepress_l"] = visual.TextStim(win=monitor,
                                                 text="L",
                                                 pos=(-0.8, 0.8),
                                                 height=0.1,
                                                 color=self.text_color)
        visobjs["tonepress_r"] = visual.TextStim(win=monitor,
                                                 text="R",
                                                 pos=(-0.7, 0.8),
                                                 height=0.1,
                                                 color=self.text_color)
        visobjs["tonelabel"] = visual.TextStim(win=monitor,
                                               text="S",
                                               pos=(-0.9, 0.7),
                                               height=0.1,
                                               color=self.text_color)
        visobjs["presslabel"] = visual.TextStim(win=monitor,
                                                text="P",
                                                pos=(-0.9, 0.6),
                                                height=0.1,
                                                color=self.text_color)
        visobjs["acclabel"] = visual.TextStim(win=monitor,
                                              text="Accuracy",
                                              pos=(-0.9, 0.4),
                                              height=0.07,
                                              color=self.text_color,
                                              alignHoriz="left")
        visobjs["acclabel_l"] = visual.TextStim(win=monitor,
                                                text="L",
                                                pos=(-0.9, 0.3),
                                                height=0.1,
                                                color=self.text_color)
        visobjs["acclabel_r"] = visual.TextStim(win=monitor,
                                                text="R",
                                                pos=(-0.9, 0.15),
                                                height=0.1,
                                                color=self.text_color)
        visobjs["filename"] = visual.TextStim(win=monitor,
                                              text="",
                                              pos=(-0.95, -0.1),
                                              height=0.06,
                                              color=self.text_color,
                                              alignHoriz="left")
        visobjs["progress"] = visual.TextStim(win=monitor,
                                              text="",
                                              pos=(-0.95, -0.2),
                                              height=0.06,
                                              color=self.text_color,
                                              alignHoriz="left")
        visobjs["mode"] = visual.TextStim(win=monitor,
                                          text="Normal Mode",
                                          pos=(-0.95, -0.5),
                                          height=0.08,
                                          color=self.text_color,
                                          alignHoriz="left")
        visobjs["status"] = visual.TextStim(win=monitor,
                                            text="Running",
                                            pos=(0.05, -0.5),
                                            height=0.08,
                                            color=self.text_color,
                                            alignHoriz="left")
        visobjs["message"] = visual.TextStim(
            win=monitor,
            text="press p to pause, a to abort",
            pos=(-0.95, -0.8),
            height=0.06,
            color=self.text_color,
            alignHoriz="left")

        if practice:
            visobjs["mode"].text = "Practice"
            visobjs["mode"].color = (1, -1, -1)

        if beamer is not None:
            beamobjs["befehl"] = visual.TextStim(
                win=beamer,
                text=
                "Drücke sofort RECHTS bei einem Ton im rechten Ohr.\n\n\nDrücke sofort LINKS bei einem Ton im linken Ohr.",
                pos=(0, 0),
                height=0.07,
                color=self.text_color)
            beamobjs["bericht"] = VisObj(
                visual.TextStim(win=beamer,
                                text="",
                                pos=(0, 0),
                                height=0.1,
                                color=back_color))
            self.draw_visobjs(beamobjs)
            beamer.flip()

        # tone/press squares
        visobjs["lefttone"] = VisObj(
            visual.Rect(win=monitor,
                        units="norm",
                        width=0.1,
                        height=0.1,
                        pos=(-0.8, 0.7),
                        lineColor=[-1, -1, -1]))
        visobjs["righttone"] = VisObj(
            visual.Rect(win=monitor,
                        units="norm",
                        width=0.1,
                        height=0.1,
                        pos=(-0.7, 0.7),
                        lineColor=[-1, -1, -1]))
        visobjs["leftpress"] = VisObj(
            visual.Rect(win=monitor,
                        units="norm",
                        width=0.1,
                        height=0.1,
                        pos=(-0.8, 0.6),
                        lineColor=[-1, -1, -1]))
        visobjs["rightpress"] = VisObj(
            visual.Rect(win=monitor,
                        units="norm",
                        width=0.1,
                        height=0.1,
                        pos=(-0.7, 0.6),
                        lineColor=[-1, -1, -1]))

        # accuracy squares
        acc_pane_names = [[], []]
        for s_idx, s in enumerate(zip(["left", "right"], [0.3, 0.15])):
            for p_idx in range(quorum):
                acc_pane_names[s_idx].append(s[0] + "acc" + str(p_idx))
                visobjs[acc_pane_names[s_idx][-1]] = VisObj(
                    visual.Rect(win=monitor,
                                units="norm",
                                width=0.1,
                                height=0.1,
                                pos=(-0.8 + (p_idx * 0.1), s[1]),
                                lineColor=(-1, -1, -1),
                                fillColor=back_color))

        # threshold chart
        thresh_height_cent = 0.25
        thresh_width_cent = 0.3
        thresh_height = 1
        thresh_width = 0.7
        thresh_height_min = thresh_height_cent - thresh_height / 2
        visobjs["thresh_back"] = VisObj(
            visual.Rect(win=monitor,
                        units="norm",
                        width=thresh_width,
                        height=thresh_height,
                        pos=(thresh_width_cent, thresh_height_cent),
                        lineColor=[-1, -1, -1],
                        fillColor=(1, 1, 1)))
        visobjs["thresh_left"] = VisObj(
            visual.Rect(win=monitor,
                        units="norm",
                        width=thresh_width / 4,
                        height=0.08,
                        pos=(thresh_width_cent - thresh_width / 4,
                             thresh_height_cent),
                        lineColor=[-1, -1, -1],
                        fillColor=(-1, -1, 1)))
        visobjs["thresh_right"] = VisObj(
            visual.Rect(win=monitor,
                        units="norm",
                        width=thresh_width / 4,
                        height=0.08,
                        pos=(thresh_width_cent + thresh_width / 4,
                             thresh_height_cent),
                        lineColor=[-1, -1, -1],
                        fillColor=(-1, -1, 1)))

        visobjs["thresh_label"] = visual.TextStim(win=monitor,
                                                  text="Hearing Threshold",
                                                  pos=(0.3, 0.9),
                                                  height=0.07,
                                                  color=self.text_color)
        visobjs["thresh_label_l"] = visual.TextStim(
            win=monitor,
            text="L",
            pos=(thresh_width_cent - thresh_width / 4, 0.8),
            height=0.1,
            color=self.text_color)
        visobjs["thresh_label_r"] = visual.TextStim(
            win=monitor,
            text="R",
            pos=(thresh_width_cent + thresh_width / 4, 0.8),
            height=0.1,
            color=self.text_color)
        visobjs["thresh_label_dB"] = visual.TextStim(
            win=monitor,
            text="dB",
            pos=(thresh_width_cent - thresh_width / 2 - 0.13,
                 thresh_height_cent),
            height=0.1,
            color=self.text_color)
        visobjs["thresh_label_max"] = visual.TextStim(
            win=monitor,
            text="0",
            pos=(thresh_width_cent - thresh_width / 2 - 0.13,
                 thresh_height_cent + thresh_height / 2),
            height=0.1,
            color=self.text_color)
        visobjs["thresh_label_min"] = visual.TextStim(
            win=monitor,
            text="-160",
            pos=(thresh_width_cent - thresh_width / 2 - 0.13,
                 thresh_height_cent - thresh_height / 2),
            height=0.1,
            color=self.text_color)

        # for every file name,convert to stereo,
        # and normalise to [-1,1] range, build the SoundWrap objects
        sound_list = []
        for sound_name in sound_name_list:
            snd = audio_load(sound_name)
            sound_list.append(
                SoundWrap(sound_name, snd, incr_dcb,
                          [ops.copy(), ops.copy()]))

        # randomise order of sounds
        reihenfolge = np.array(range(len(sound_name_list)))
        np.random.shuffle(reihenfolge)
        runde = np.concatenate(
            (np.zeros(quorum), np.ones(quorum))).astype(np.int)
        # cycle through sounds randomly
        for abs_idx, sound_idx in enumerate(np.nditer(reihenfolge)):
            swr = sound_list[sound_idx]
            visobjs["filename"].text = sound_name_list[sound_idx]
            visobjs["progress"].text = "File: " + str(abs_idx +
                                                      1) + " of " + str(
                                                          len(sound_name_list))
            # already do a reduction before we begin
            swr.operate(0, dcb_delta=swr.ops[0].pop(0), direction=-1)
            swr.operate(1, dcb_delta=swr.ops[1].pop(0), direction=-1)
            ear_thresh = dec2dcb((np.max(swr.data[:, 0]), np.max(swr.data[:,
                                                                          1])))
            visobjs["thresh_left"].pos = pos_anim(
                visobjs["thresh_left"].visobj.pos,
                (visobjs["thresh_left"].visobj.pos[0], thresh_height_min +
                 thresh_height * (-160 - ear_thresh[0]) / -160),
                int(monitor_fps * 0.5))
            visobjs["thresh_right"].pos = pos_anim(
                visobjs["thresh_right"].visobj.pos,
                (visobjs["thresh_right"].visobj.pos[0], thresh_height_min +
                 thresh_height * (-160 - ear_thresh[1]) / -160),
                int(monitor_fps * 0.5))
            # do until ops are exhausted in both ears
            while swr.ops[0] or swr.ops[1]:
                # make versions with sound only in left or right
                sounds = []
                for s_idx in range(quorum):
                    d = swr.data.copy()
                    d[:, 1 - s_idx] = 0
                    sounds.append(sound.Sound(d))
                # present to each ear twice in random order, record accuracy
                np.random.shuffle(runde)
                accs = [[], []]
                for r_idx, r in enumerate(np.nditer(runde)):
                    # play sound and update tone squares
                    sounds[r].play()
                    if r:
                        visobjs["righttone"].visobj.fillColor = (-1, 1, -1)
                    else:
                        visobjs["lefttone"].visobj.fillColor = (-1, 1, -1)

                    for f_idx in range(int(monitor_fps * play_duration)):
                        response = event.getKeys(key_presses)
                        # update press squares
                        self.draw_visobjs(visobjs)
                        monitor.flip()
                        if response:
                            break

                    sounds[r].stop()
                    # turn off sound and update tone squares
                    # allow a short grace period to respond
                    if not response:
                        for f_idx in range(int(monitor_fps * 0.75)):
                            grace_response = event.getKeys(key_presses)
                            self.draw_visobjs(visobjs)
                            monitor.flip()
                            if grace_response:
                                break
                        response = response + grace_response

                    anim_pattern = col_anim(
                        (-1, 1, -1),
                        (-1, 1, -1), int(monitor_fps * 0.15)) + col_anim(
                            (0, 1, 0), back_color, int(monitor_fps * 0.2))
                    if r:
                        visobjs["righttone"].fillColor = anim_pattern
                    else:
                        visobjs["lefttone"].fillColor = anim_pattern

                    # mark accuracy, update press squares
                    if key_presses[r] in response and key_presses[
                            1 - r] not in response:
                        accs[r].append(1)
                        anim_pattern = col_anim(back_color,(-1,1,-1),int(monitor_fps*0.15)) + \
                          col_anim((-1,1,-1),back_color,int(monitor_fps*0.2))
                        if r:
                            visobjs["rightpress"].fillColor = anim_pattern
                        else:
                            visobjs["leftpress"].fillColor = anim_pattern
                        if practice and beamer_idx > -1:
                            beamobjs["bericht"].visobj.text = "Richtig!"
                            beamobjs["bericht"].color = col_anim(back_color,(-1,1,-1),beamer_fps*0.35) + \
                              col_anim((-1,1,-1),back_color,beamer_fps*0.35)

                    elif key_presses[1 - r] in response:
                        accs[r].append(0)
                        anim_pattern = col_anim(back_color,(1,-1,-1),int(monitor_fps*0.15)) + \
                          col_anim((1,-1,-1),back_color,int(monitor_fps*0.3))
                        if r:
                            visobjs["leftpress"].fillColor = anim_pattern.copy(
                            )
                        else:
                            visobjs[
                                "rightpress"].fillColor = anim_pattern.copy()
                        if practice and beamer_idx > -1:
                            beamobjs["bericht"].visobj.text = "Falsch!"
                            beamobjs["bericht"].color = col_anim(back_color,(1,-1,-1),beamer_fps*0.35) + \
                              col_anim((1,-1,-1),back_color,beamer_fps*0.35)
                    else:
                        accs[r].append(0)
                        if practice and beamer_idx > -1:
                            beamobjs["bericht"].visobj.text = "Verpasst!"
                            beamobjs["bericht"].color = col_anim(back_color,(1,-1,-1),beamer_fps*0.35) + \
                              col_anim((1,-1,-1),back_color,beamer_fps*0.35)

                    # update acc squares
                    if accs[r][-1]:
                        anim_pattern = col_anim(back_color, (-1, 1, -1),
                                                monitor_fps * 0.2)
                    else:
                        anim_pattern = col_anim(back_color, (1, -1, -1),
                                                monitor_fps * 0.2)
                    visobjs[acc_pane_names[r][
                        len(accs[r]) - 1]].fillColor = anim_pattern.copy()

                    # ISI
                    jitter = jitter_range[0] + np.random.rand() * (
                        jitter_range[1] - jitter_range[0])
                    for f_idx in range(int(monitor_fps * jitter)):
                        self.draw_visobjs(visobjs)
                        if beamer_idx > -1:
                            self.draw_visobjs(beamobjs)
                            beamer.flip()
                        monitor.flip()
                    if "p" in event.getKeys(["p"]):
                        visobjs["status"].text = "Paused"
                        visobjs["status"].color = (1, -1, -1)
                        visobjs["message"].text = "press p again to resume"
                        self.draw_visobjs(visobjs)
                        monitor.flip()
                        event.waitKeys(keyList=["p"])
                        visobjs["status"].text = "Running"
                        visobjs["status"].color = self.text_color
                        visobjs[
                            "message"].text = "press p to pause, a to abort"
                        self.draw_visobjs(visobjs)
                        monitor.flip
                    if "a" in event.getKeys(["a"]):
                        abort += 1
                        if abort == 1:
                            visobjs[
                                "message"].text = "press a again to abort, n to cancel"
                            visobjs["message"].color = (1, -1, -1)
                        if abort == 2:
                            monitor.close()
                            if beamer_idx > -1:
                                beamer.close()
                            return ([], 0)
                    if abort == 1 and "n" in event.getKeys(["n"]):
                        abort = 0
                        visobjs[
                            "message"].text = "press p to pause, a to abort"
                        visobjs["message"].color = self.text_color
                    event.clearEvents()

                # assess accuracy and act accordingly
                accs = np.array(accs)
                for r_idx in range(accs.shape[0]):
                    line_flash = col_anim(
                        (-1, -1, -1), (1, 1, 1), monitor_fps * 0.2) + col_anim(
                            (1, 1, 1), (-1, -1, -1), monitor_fps * 0.4)
                    green_flash = col_anim(
                        (-1, 1, -1), (1, 1, 1), monitor_fps * 0.2) + col_anim(
                            (1, 1, 1), back_color, monitor_fps * 0.4)
                    red_flash = col_anim(
                        (1, -1, -1), (1, 1, 1), monitor_fps * 0.2) + col_anim(
                            (1, 1, 1), back_color, monitor_fps * 0.4)
                    if accs[r_idx, ].all() and swr.ops[
                            r_idx]:  # all correct, decrease volume, flash squares
                        swr.operate(r_idx,
                                    dcb_delta=swr.ops[r_idx].pop(0),
                                    direction=-1)
                        for accp in acc_pane_names[r_idx]:
                            visobjs[accp].fillColor = green_flash.copy()
                            visobjs[accp].lineColor = line_flash.copy()
                    elif not accs[r_idx, ].any(
                    ) and swr.ops[r_idx]:  # all false, increase
                        swr.operate(r_idx,
                                    dcb_delta=swr.ops[r_idx].pop(0),
                                    direction=1)
                        for accp in acc_pane_names[r_idx]:
                            visobjs[accp].fillColor = red_flash.copy()
                            visobjs[accp].lineColor = line_flash.copy()
                    else:  # ambiguous result, just clear acc squares
                        for accp in acc_pane_names[r_idx]:
                            visobjs[accp].fillColor = col_anim(
                                visobjs[accp].visobj.fillColor, back_color,
                                monitor_fps * 0.4)
                    # update threshold chart
                    ear_thresh = dec2dcb(
                        (np.max(swr.data[:, 0]), np.max(swr.data[:, 1])))
                    visobjs["thresh_left"].pos = pos_anim(
                        visobjs["thresh_left"].visobj.pos,
                        (visobjs["thresh_left"].visobj.pos[0],
                         thresh_height_min + thresh_height *
                         (-160 - ear_thresh[0]) / -160),
                        int(monitor_fps * 0.5))
                    visobjs["thresh_right"].pos = pos_anim(
                        visobjs["thresh_right"].visobj.pos,
                        (visobjs["thresh_right"].visobj.pos[0],
                         thresh_height_min + thresh_height *
                         (-160 - ear_thresh[1]) / -160),
                        int(monitor_fps * 0.5))
            # store threshold for item
            thresh_results.append(
                [sound_idx, swr.name, ear_thresh[0], ear_thresh[1]])
            for f_idx in range(int(monitor_fps * 0.35)):
                self.draw_visobjs(visobjs)
                monitor.flip()

        # write to file
        if not practice:
            now = datetime.datetime.now()
            Tk().withdraw()
            filename = filedialog.asksaveasfilename(
                filetypes=(("Hearing test files", "*.hrt"), ("All files",
                                                             "*.*")))

            if filename:
                with open(filename, "w") as file:
                    file.write(
                        "Subject {sub}, recorded on {d}.{m}.{y}, {h}:{mi}\n".
                        format(sub="test",
                               d=now.day,
                               m=now.month,
                               y=now.year,
                               h=now.hour,
                               mi=now.minute))
                    file.write("Index\tWavfile\tLeftEar\tRightEar\n")
                    for thrsh in thresh_results:
                        file.write("{idx}\t{name}\t{right}\t{left}\n".format(
                            idx=thrsh[0],
                            name=thrsh[1],
                            right=thrsh[2],
                            left=thrsh[3]))

        monitor.close()
        if not beamer_idx == -1:  # for some reason closing the beamer crashes it
            beamer.close()
        return thresh_results
 def onSave(self):
     filename = asksaveasfilename()
     if filename:
         alltext = self.gettext() # first through last
         open(filename, 'w').write(alltext) # store text in file
Esempio n. 45
0
 def overide_browse_button(self):
     global save_file
     self.save_filename = filedialog.asksaveasfilename(defaultextension='*.png*')
     self.save_file.delete(0, tk.END)
     self.save_file.insert(0, self.save_filename)
     save_file = self.save_file.get()
Esempio n. 46
0
    def save_mask(self, filename=None):

        if filename is None:
            filename = asksaveasfilename()

        imsave(filename + ".png", self.mask)
Esempio n. 47
0
        def convertToExcel():
            global read_file

            export_file_path = filedialog.asksaveasfilename(
                defaultextension=".xlsx")
            read_file.to_excel(export_file_path, index=None, header=True)
Esempio n. 48
0
    "CTID", "Staff Providing The Service", "Service Date"
]]

# tracking those who graduated a RentWell Class
graduate = spsc[spsc["Provider Specific Code"].str.contains("Graduation")][[
    "CTID", "Staff Providing The Service", "Service Date"
]]

# tracking those who were referred to a RentWell Class
referred = spsc[spsc["Provider Specific Code"].str.contains("Referral")][[
    "CTID", "Staff Providing The Service", "Service Date"
]]

# create a summary
summary = spsc.pivot_table(index=["Provider Specific Code"],
                           values=["CTID"],
                           aggfunc=len)

writer = pd.ExcelWriter(asksaveasfilename(
    title="RentWell Monthly Data",
    initialdir="//tproserver/Reports/Monthly Report",
    initialfile="RentWell Monthly Data.xlsx",
    defaultextension=".xlsx"),
                        engine="xlsxwriter")
summary.to_excel(writer, sheet_name="Summary")
graduate.to_excel(writer, sheet_name="RentWell Graduates", index=False)
attendee.to_excel(writer, sheet_name="RentWell Attendees", index=False)
referred.to_excel(writer, sheet_name="RentWell Referrals", index=False)
spsc_is_blank.to_excel(writer, sheet_name="Errors", index=False)
writer.save()
Esempio n. 49
0
__author__ = 'iamhssingh'

import sqlite3
from tkinter import Tk
from tkinter import filedialog
from tkinter import messagebox

root = Tk()

c = filedialog.asksaveasfilename(defaultextension='.db', filetypes=[('database files', '.db')], initialfile='bmngmnt',
                                 title="Choose your databasefile", initialdir=".", parent=root)

success = False
create = False
cursor = None
try:
    db = sqlite3.connect(c)
    cursor = db.cursor()
    success = True
except sqlite3.Error as err:
    messagebox.showwarning(title="Database Connection Error", message="Something went wrong: {}".format(err))

if success:
    try:
        cursor.execute("""CREATE TABLE `user_master` (
	`userID`	INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
	`userName`	TEXT NOT NULL,
	`userFName`	TEXT NOT NULL,
	`userLName`	TEXT NOT NULL,
	`userPassword`	TEXT NOT NULL
);""")
Esempio n. 50
0
 def pick_export_path(self):
     self.export_path = filedialog.asksaveasfilename()
     self.label_export_path['text'] = self.export_path
     self.master.lift()
     self.master.focus_force()
Esempio n. 51
0
    NbFiles += MyKML.ScanFolder(Folder=Foldername)

print("Imported " + str(NbFiles) + " files from folders.")

if (NbFiles == 0):
    # Canceled by user
    print("No GPS info found in folder. Aborting.")
    sys.exit()

# FilteredQty = MyKML.FilterPlacemarks(MinDistance)
MyKML.MinDistanceBetweenPlacemarks = MinDistance

# Export KML file
if (KMLFileName == ""):
    KMLFileName = filedialog.asksaveasfilename(title="Select KML output file",
                                               filetypes={("KML files",
                                                           "*.kml")})
file, ext = os.path.splitext(KMLFileName)

if (KMLFileName == ""):
    # Canceled by user
    print("No KML file provided. Aborting.")
    sys.exit()

# enforce kml extension
if (ext.lower() != ".kml"):
    KMLFileName = file + ".kml"

_, MyKML.MapName = os.path.split(KMLFileName)
MyKML.MinDistanceBetweenPlacemark = MinDistance
FileSaved = MyKML.SaveKMLFile(KMLFileName)
Esempio n. 52
0
 def guardar_como(self):
     guardar_info = asksaveasfilename(title='Guardar Archivo')
     write_file = open(guardar_info, 'w+')
     write_file.write(self.entrada.get('1.0', END))
     write_file.close()
     self.archivo = guardar_info
Esempio n. 53
0
def save_image():
    path = filedialog.asksaveasfilename()
    print(path)
    cv2.imwrite(path + "-edged.jpg", can)
Esempio n. 54
0
def export():
    exportfile = fd.asksaveasfilename()
    config.library.to_csv(exportfile, index=False)
Esempio n. 55
0
 def save_map_as(self):
     self.file = filedialog.asksaveasfilename(initialdir="~",
                                              title="Save map")
     if self.file != None and len(self.file) > 0:
         self.lscr.lmap.write_to_file(self.file)
Esempio n. 56
0
def save_departs_csv():
    filename = filedialog.asksaveasfilename(initialdir=" ", title="Введите название среза",
                                            filetypes=(
                                                ("csv files", "*.csv"), ("csv files", "*.csv")))
    df_to_save.to_csv(filename + '.csv', index=False)
Esempio n. 57
0
 def salvar_imagem(self):
     filename = filedialog.asksaveasfilename()
     self.fig.savefig(filename)
Esempio n. 58
0
 def file_save(self):
     default_dir = os.path.expandvars(r'%USERPROFILE%\Desktop')
     out_file = filedialog.asksaveasfilename(title='选择文件', initialdir=(default_dir), initialfile='new.gjf',  defaultextension='.gjf', filetypes=(('Gaussian files', '.gjf'), ('Text files', '.txt')))
     if out_file!='':
         self.parent.fio.output_gaussian_file(out_file)
 def save_game(self):
     file_name = filedialog.asksaveasfilename(defaultextension=".txt", initialdir="/", title="Select file",
                                              filetypes=(("Text file", "*.txt"), ("All Files", "*.*")))
     if file_name is not None:
         self.world.save_game(file_name)
Esempio n. 60
0
def save_to_file():
    global dic_grids
    fout = filedialog.asksaveasfilename()
    with open(fout, 'wb') as f:
        pickle.dump(dic_grids, f, 3)