def __init__(self, name='Analysis1', session_dir='/export/data/mri/Neurometrics', permute=False, **kwargs): SubWorkflow.__init__(self, name=name, output_fields=[ 'frame_scores', 'block_scores', 'halfrun_scores', 'run_scores' ], **kwargs) subjects = [ Subject('a', [ Session('020211el', base_path=session_dir, permute=permute), Session('021611el', base_path=session_dir, permute=permute) ]), Subject('b', [ Session('020511bn', base_path=session_dir, permute=permute), Session('021211bn', base_path=session_dir, permute=permute) ]), Subject('c', [ Session('021911ar', base_path=session_dir, permute=permute), Session('090210ar1', base_path=session_dir, permute=permute) ]), Subject('d', [ Session('080612af', base_path=session_dir, permute=permute), Session('091912af', base_path=session_dir, permute=permute) ]), Subject('e', [ Session('101812rm', base_path=session_dir, permute=permute), Session('011513rm', base_path=session_dir, permute=permute) ]) ] self.subject_workflows = [SubjectWorkflow(u) for u in subjects] self.merge_nodes = dict() self.aggregate_nodes = dict() for name in ('frame', 'block', 'halfrun', 'run'): mn = pe.Node(name=name + '_merge', interface=util.Merge(len(subjects))) self.merge_nodes[name] = mn an = pe.Node(name=name + '_aggregate', interface=AggregateScores()) for i, uw in enumerate(self.subject_workflows): self.connect(uw, 'output.' + name + '_scores', mn, 'in' + str(i + 1)) self.connect(mn, 'out', an, 'scores') self.connect(an, 'scores', self.output_node, name + '_scores')
def _run_interface(self, runtime): run_length = 72 block_length = 6 session = Session(path.basename(self.inputs.session_dir), base_path=path.dirname(self.inputs.session_dir)) X = session.getInputs() y = session.getTargets() active = np.where(y > 0) X = X[active] y = y[active] num_frames = len(y) num_blocks = num_frames / block_length num_runs = num_frames / run_length num_halfruns = num_runs * 2 frames = np.arange(num_frames) blocks = np.arange(num_frames).reshape(-1, block_length) halfruns = np.arange(num_frames).reshape(-1, run_length / 2) runs = np.arange(num_frames).reshape(-1, run_length) frame_split = StratifiedKFold(y[frames], num_frames / 36) block_split = StratifiedKFold(y[blocks][:, 0], num_blocks / 6) halfrun_split = KFold(num_halfruns, num_halfruns) run_split = KFold(num_runs, num_runs) pickle.dump(X, file(path.abspath('inputs.pkl'), 'w')) pickle.dump(y, file(path.abspath('targets.pkl'), 'w')) pickle.dump(frames, file(path.abspath('frames.pkl'), 'w')) pickle.dump(blocks, file(path.abspath('blocks.pkl'), 'w')) pickle.dump(halfruns, file(path.abspath('halfruns.pkl'), 'w')) pickle.dump(runs, file(path.abspath('runs.pkl'), 'w')) pickle.dump(frame_split, file(path.abspath('frame_split.pkl'), 'w')) pickle.dump(block_split, file(path.abspath('block_split.pkl'), 'w')) pickle.dump(halfrun_split, file(path.abspath('halfrun_split.pkl'), 'w')) pickle.dump(run_split, file(path.abspath('run_split.pkl'), 'w')) return runtime
def _run_interface(self, runtime): run_length = 72 block_length = 6 session = Session(path.basename(self.inputs.session_dir), base_path=path.dirname(self.inputs.session_dir)) X = session.getInputs() y = session.getTargets() active = np.where(y > 0) X = X[active] y = y[active] num_frames = len(y) num_blocks = num_frames/block_length num_runs = num_frames/run_length num_halfruns = num_runs*2 frames = np.arange(num_frames) blocks = np.arange(num_frames).reshape(-1,block_length) halfruns = np.arange(num_frames).reshape(-1,run_length/2) runs = np.arange(num_frames).reshape(-1,run_length) frame_split = StratifiedKFold(y[frames], num_frames/36) block_split = StratifiedKFold(y[blocks][:,0], num_blocks/6) halfrun_split = KFold(num_halfruns, num_halfruns) run_split = KFold(num_runs, num_runs) pickle.dump(X,file(path.abspath('inputs.pkl'),'w')) pickle.dump(y,file(path.abspath('targets.pkl'),'w')) pickle.dump(frames,file(path.abspath('frames.pkl'),'w')) pickle.dump(blocks,file(path.abspath('blocks.pkl'),'w')) pickle.dump(halfruns,file(path.abspath('halfruns.pkl'),'w')) pickle.dump(runs,file(path.abspath('runs.pkl'),'w')) pickle.dump(frame_split,file(path.abspath('frame_split.pkl'),'w')) pickle.dump(block_split,file(path.abspath('block_split.pkl'),'w')) pickle.dump(halfrun_split,file(path.abspath('halfrun_split.pkl'),'w')) pickle.dump(run_split,file(path.abspath('run_split.pkl'),'w')) return runtime
def main() -> None: # Use a breakpoint in the code line below to debug your script. #print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint. """ ac = Account("pass") ac.walletsInit() po = Wallet(0.9292, "frank") try: po.pay(69) except NotEnoughFounds as e: print(e) result = db.currencies.insert_one({"name": "frank", "rate": 18, "date": datetime.now()}) result = db.accounts.insert_one({"name": "złoty", "date": datetime.now()}) """ implementacja = Session() session = SessionClient(implementacja) run = True while run: print("Menu\n" "1. Show currencies\n" "2. Log in\n" "3. Create Account\n" "4. Stop\n") choose = int(input("Type numer from menu: ")) if choose == 4: run = False elif choose == 3: session.createAccountInterface() elif choose == 2: run = False account = session.logInInterface() if account == None: raise LogError if type(account) == Oversee: oversee(account, session) else: user(account, session) elif choose == 1: session.BalanceInterface() else: print("Try to choose one more time")
def __init__(self): super().__init__() # Window geometry self.title('VocaPy') self.resizable(0, 0) self.padding = 20 # General settings self.version = '0.3' self.option_add('*font', 'helvetica 11') self.option_add('*Entry.font', 'helvetica 12') self.option_add('*Listbox.font', 'helvetica 12') self.option_add('*Menu.background', 'snow') self.option_add('*Text.background', 'snow') self.option_add('*Menu.relief', 'flat') self.option_add('*Text.relief', 'flat') # Shortcuts self.protocol("WM_DELETE_WINDOW", self.destroyWin) self.bind('<Control-q>', self.destroyWin) self.bind('<Control-a>', self.constructorCall) self.bind('<Control-e>', self.statsCall) self.urlHelp = 'https://github.com/aledruetta/vocapy' self.bind_all('<F1>', lambda e: self.openUrl(self.urlHelp)) # Configurations self.cf_dict = ConfDict() self.cf_dict.load() self.lang = self.cf_dict.setdefault('lang', locale.getlocale()[0]) # Localization self.i18n() # Game self.minWords = 5 self.session = Session(time.time(), attempts=0, guess=0) self.word_list = WordList() self.main_window() self.practice()
def record_subroutine(student_list, transaction_record): """ Subroutine for working with transaction record. """ while True: pretty.print_bar(PROGRAM_WIDTH) print( "What would you like to do? (type either option number or [keyword])" ) pretty.print_options("[View] record", "[Add] transaction", "[Remove] transaction", "[Update] transaction", "[Return]") inp = input().lower() if inp == "1" or inp == "view": try: pretty.print_bar(PROGRAM_WIDTH) print("Select a range of transactions to view.") pretty.print_options("[All]", "[Month]", "[Week]", "[Custom]") inp = input().lower() if inp == "all": start = datetime.date.min end = datetime.date.max elif inp == "month": start = dt_utils.get_start_of_month() end = dt_utils.get_end_of_month() elif inp == "week": start = dt_utils.get_start_of_week() end = dt_utils.get_end_of_week() elif inp == "custom": print("Enter starting date of transactions.") start = dt_utils.build_date() print("Enter ending date of transactions.") end = dt_utils.build_date() else: raise ValueError("Invalid entry: input not understood.") except KeyboardInterrupt: pass except ValueError as e: print(e) else: print() transaction_record.print_table(start, end) input("Press enter to return.") elif inp == "2" or inp == "add": # Add new transaction to transaction record. # Basic flow: ask for all arguments in a try/except block listening # for KeyboardInterrupts. If any are raised, exit add subroutine # and continue looping. Otherwise, verify types of all entered data # and create a new Session with given parameters. Add to transaction # record. Report success. print("Press CTRL+C at any time to cancel.") try: date = dt_utils.build_date() name = input("Enter full name of student\n") student = student_list.get(name) if not student: raise ValueError( "Student {0} not found (check spelling?).".format( name)) start = dt_utils.build_time("start") end = dt_utils.build_time("end") rate = float(input("Hourly rate charged?\n")) method = input("Payment method?\n") pmt_received = input("Payment receieved? (Yes/No)\n").lower() if pmt_received == "yes" or pmt_received == "y" or pmt_received == "1": pmt_received = True elif pmt_received == "no" or pmt_received == "n" or pmt_received == "0": pmt_received = False else: raise ValueError("Payment received must be yes or no.") notes = input("Notes?\n") except ValueError as e: print(e) except KeyboardInterrupt: pass else: pretty.print_bar(PROGRAM_WIDTH) s = Session(date, student, start, end, rate, method, pmt_received, notes) transaction_record.add(s) print( "Transaction on date {0} with {1} from {2} to {3} added successfully." .format(s.date, s.student, pretty.time(s.start), pretty.time(s.end))) save(student_list=None, transaction_record=transaction_record) elif inp == "3" or inp == "remove": # Update session info in transaction record. # Basic flow: Ask for date of session to update in try/except block # listening for KeyboardInterrupts. If any are raised, exit update # subroutine and continue looping. Else, ask for student name # and use TransactionRecord method to remove transaction. Report # success or failure. print("Press CTRL+C at any time to cancel.") try: print("Date of session to remove?") date_of_session = dt_utils.build_date() name = input( "Enter full name of student in session to remove.\n") except KeyboardInterrupt: pass else: pretty.print_bar(PROGRAM_WIDTH) removed = transaction_record.remove(date_of_session, name) if removed: print("Student {0} removed successfully.".format(name)) save(student_list=None, transaction_record=transaction_record) else: print( "Session on {0} with student {1} not found (check spelling?)." .format(date_of_session, name)) elif inp == "4" or inp == "update": # Update session info in transaction record. # Basic flow: Ask for date of session to update in try/except block # listening for KeyboardInterrupts. If any are raised, exit update # subroutine and continue looping. Else, ask for what field to update # and direct flow to specific input type builders. This has to be # done because the Session data type stores hetergeneous objects, which # may or may not be enterable as a pure string (the Session class # does no type checking. Using the helper module, each branch determines # if its entered input is valid and then stores the data correctly # formed as newval, which is finally passed to the Session update # method. A new approach I'm trying is using specific error messages # to pass up what went wrong. print("Press CTRL+C at any time to cancel.") try: print("Date of session to update?") date_of_session = dt_utils.build_date() name = input( "Enter full name of student in session to update.\n") print("Field to update? (type by [keyword])") pretty.print_options("[Date]", "[Student]", "[Start] time", "[End] time", "[Rate]", "Payment [method]", "Payment [received]", "[Notes]") field = input().lower() if field == "date": newval = dt_utils.build_date() elif field == "start": newval = dt_utils.build_time("start") elif field == "end": newval = dt_utils.build_time("end") elif field == "rate": inp = input("New value of field?\n") if valid.is_rate(inp): newval = float(inp) else: raise ValueError( "Invalid entry: rate must be a number.") elif field == "received": inp = input("New value of field?\n") if valid.is_bool(inp): newval = True if inp in ["yes", "y", "1"] else False else: raise ValueError( "Invalid entry: payment received must be either yes or no" ) else: newval = input("New value of field?\n") except ValueError as e: print(e) except KeyboardInterrupt: pass else: pretty.print_bar(PROGRAM_WIDTH, ALERT_SYM) # This works because update method returns True or False for successful update or not. updated = transaction_record.update(date_of_session, name, field, newval) if updated: # A little magic in format to make update to field "first" or "last" show as "first name" or "last name." print( "Field {0} in session on {1} with {2} successfully updated to {3}." .format(field, pretty.date(date_of_session), name, newval)) save(student_list=None, transaction_record=transaction_record) else: print( "Session on {0} with {1} or field {2} not found (check spelling?)." .format(pretty.date(date_of_session), name, field)) elif inp == "5" or inp == "return": # Finishes method and returns to place in main() stack loop. return else: pass
def destroyWin(self, event=None): self.session.append_db() if DEBUG: print("\n{}\n".format(Session.sessions_lst())) self.destroy()
class VocapyApp(tk.Tk): def __init__(self): super().__init__() # Window geometry self.title('VocaPy') self.resizable(0, 0) self.padding = 20 # General settings self.version = '0.3' self.option_add('*font', 'helvetica 11') self.option_add('*Entry.font', 'helvetica 12') self.option_add('*Listbox.font', 'helvetica 12') self.option_add('*Menu.background', 'snow') self.option_add('*Text.background', 'snow') self.option_add('*Menu.relief', 'flat') self.option_add('*Text.relief', 'flat') # Shortcuts self.protocol("WM_DELETE_WINDOW", self.destroyWin) self.bind('<Control-q>', self.destroyWin) self.bind('<Control-a>', self.constructorCall) self.bind('<Control-e>', self.statsCall) self.urlHelp = 'https://github.com/aledruetta/vocapy' self.bind_all('<F1>', lambda e: self.openUrl(self.urlHelp)) # Configurations self.cf_dict = ConfDict() self.cf_dict.load() self.lang = self.cf_dict.setdefault('lang', locale.getlocale()[0]) # Localization self.i18n() # Game self.minWords = 5 self.session = Session(time.time(), attempts=0, guess=0) self.word_list = WordList() self.main_window() self.practice() def main_window(self): # Menu self.menuBar() # Background color = 'crimson' labelFrameApp = tk.LabelFrame(self) labelFrameApp['bg'] = color labelFrameApp.pack(fill='x', expand='yes') # Word label self.labelW = tk.Label(labelFrameApp) self.labelW['font'] = ('Arial Black', 36) self.labelW['bg'] = color self.labelW['fg'] = 'snow' self.labelW['text'] = 'VOCAPY' self.labelW.pack(padx=self.padding, pady=self.padding) # Frame choice buttons frameB = tk.Frame(labelFrameApp) frameB['bg'] = color frameB.pack(padx=self.padding) # Choice buttons create self.radiobuttons = [] for i in range(4): self.radiobuttons.append(tk.Radiobutton(frameB)) self.radiobuttons[i]['indicatoron'] = 0 self.radiobuttons[i]['font'] = 'helvetica 16 bold' self.radiobuttons[i]['height'] = 2 self.radiobuttons[i]['width'] = 40 self.radiobuttons[i]['bg'] = 'Teal' self.radiobuttons[i]['fg'] = 'snow' self.radiobuttons[i].pack(fill='x', expand='yes', pady=3) # Choice buttons commands self.radiobuttons[0]['command'] = lambda: self.check_guess( self.radiobuttons[0]) self.radiobuttons[1]['command'] = lambda: self.check_guess( self.radiobuttons[1]) self.radiobuttons[2]['command'] = lambda: self.check_guess( self.radiobuttons[2]) self.radiobuttons[3]['command'] = lambda: self.check_guess( self.radiobuttons[3]) # Next word button self.buttonF = tk.Button(labelFrameApp) self.buttonF['command'] = self.practice self.buttonF['text'] = '-->' self.buttonF['font'] = ('Arial Black', 20, 'bold') self.buttonF['bg'] = 'snow' self.buttonF['fg'] = 'Teal' self.buttonF.pack( padx=self.padding, pady=self.padding, ipadx=10, ipady=5 ) # Percentbar self.textS = tk.Text(self) self.textS['font'] = 'helvetica 10' self.textS['relief'] = 'flat' self.textS['height'] = 1 self.textS.tag_configure('guess', background='#CBE148') self.textS.tag_configure('wrong', background='#EEB0AB') self.textS.pack(fill='x', expand='yes') self.percentbar() def practice(self, event=None): while len(self.word_list) < self.minWords: self.list_complete() # Practice round self.gr = PracticeRound(self.word_list) if DEBUG: print(self.gr) # Display word self.labelW['text'] = self.gr.word.name self.buttonF['state'] = 'disabled' self.buttonF.unbind('<Return>') self.user_guess = tk.StringVar() # Display choices for i in range(4): self.radiobuttons[i]['variable'] = self.user_guess self.radiobuttons[i]['text'] = self.gr.means[i] self.radiobuttons[i]['value'] = self.gr.means[i] self.radiobuttons[i]['state'] = 'normal' self.focus_set() def check_guess(self, button): # Update attempts self.gr.word.attempts += 1 self.session.attempts += 1 # User choice guess = self.user_guess.get() if guess == self.gr.target: button['selectcolor'] = '#CBE148' # Update guess self.gr.word.guess += 1 self.session.guess += 1 result = True else: button['selectcolor'] = '#EEB0AB' result = False self.gr.word.update_db() self.show_result(result) self.percentbar() for i in range(4): self.radiobuttons[i]['state'] = 'disabled' # New practice round self.buttonF['state'] = 'normal' self.buttonF.bind('<Return>', self.practice) self.buttonF.focus_set() def show_result(self, success): title = _('Resultado') padl = 4 * ' ' padr = 12 * ' ' # Messagebox if success: message = _('\n{}Resultado: Correcto!{}').format(padl, padr) messagebox.showinfo(title, message, parent=self) else: message = _('{0}Resultado: Incorrecto!{1}\n{0}{2}: {3}{1}').format( padl, padr, self.gr.word.name, self.gr.target) messagebox.showerror(title, message, parent=self) def list_complete(self): # Messagebox message = _('''El diccionario posee {} términos. Antes de jugar debería añadir al menos {} términos al diccionario. ''').format(len(self.word_list), self.minWords - len(self.word_list)) messagebox.showinfo(_('Advertencia'), message, parent=self) self.constructorCall() def percentbar(self): attempts = self.session.attempts percent = self.session.percent start = len(str(attempts)) + len(_('palabras')) + 2 info = _('{} palabras [{}{} aciertos]').format(attempts, percent, '%') self.textS['state'] = 'normal' self.textS.delete('1.0', tk.END) self.textS.insert('1.0', info) pBar = PercentBar( self.textS, start=(1, start), lenght=30, char=' ', percent=percent, colors=('#CBE148', '#EEB0AB') ) pBar.create() self.textS['state'] = 'disabled' def constructorCall(self, event=None): self.unbind('<Control-a>') constructor = ConstList(self) constructor.wait_window() self.word_list = constructor.word_list self.bind('<Control-a>', self.constructorCall) def statsCall(self, event=None): self.unbind('<Control-e>') stats = Stats(self) # Check whether stats window was created try: stats.window.wait_window() except AttributeError: pass finally: self.bind('<Control-e>', self.statsCall) def menuBar(self): menuBar = tk.Menu(self) self.config(menu=menuBar) # Archivo fileMenu = tk.Menu(menuBar, tearoff=0) fileMenu.add_command( label=_('Agregar palabras'), accelerator='Ctrl+A', command=self.constructorCall ) fileMenu.add_command( label=_('Eliminar palabra'), accelerator='Ctrl+D', command=self.delWord ) self.bind('<Control-d>', self.delWord) fileMenu.add_command( label=_('Borrar todo'), command=self.clear ) fileMenu.add_separator() langMenu = tk.Menu(fileMenu, tearoff=0) # Language fileMenu.add_cascade(label=_('Lenguaje'), menu=langMenu) langs_lst = [_('español'), _('portugués'), _('inglés')] for l in langs_lst: langMenu.add_radiobutton(label=l, indicatoron=0, command=lambda arg0=l: self.setLang(arg0) ) fileMenu.add_separator() fileMenu.add_command( label=_('Ver estadísticas'), accelerator='Ctrl+E', command=self.statsCall ) fileMenu.add_separator() fileMenu.add_command( label=_('Salir'), accelerator='Ctrl+Q', command=self.destroyWin ) menuBar.add_cascade(label=_('Archivo'), menu=fileMenu) # Ayuda helpMenu = tk.Menu(menuBar, tearoff=0) helpMenu.add_command( label=_('Ayuda'), accelerator='F1', command=lambda: self.openUrl(self.urlHelp) ) helpMenu.add_command(label=_('Sobre'), command=self.about) menuBar.add_cascade(label=_('Ayuda'), menu=helpMenu) def openUrl(self, url, event=None): webbrowser.open(url) def about(self): """About messagebox""" title = _('Sobre') message = """ VocaPy v{} MIT License (MIT) Copyright (c) 2014 Alejandro Druetta\t https://github.com/aledruetta/vocapy """.format(self.version) messagebox.showinfo(title, message, parent=self) def setLang(self, arg0): if arg0 == _('español'): self.lang = 'es_AR' elif arg0 == _('portugués'): self.lang = 'pt_BR' elif arg0 == _('inglés'): self.lang = 'en_US' self.cf_dict.save('lang', self.lang) self.i18n() self.menuBar() self.percentbar() if DEBUG: print('\nmenu: {}\n'.format(self.lang)) def delWord(self, event=None): m = _('Está seguro de que quiere eliminar {} del diccionario?').format( self.gr.word.name) t = _('Eliminar Palabra') if messagebox.askokcancel(t, m, default='cancel', parent=self): self.word_list.remove_db(self.gr.word) if DEBUG: print("\n", self.word_list) self.practice() def clear(self): m = _('Está seguro de que quiere eliminar el diccionario?') t = _('Eliminar Diccionario') if messagebox.askokcancel(t, m, default='cancel', parent=self): self.word_list.clear() self.practice() def destroyWin(self, event=None): self.session.append_db() if DEBUG: print("\n{}\n".format(Session.sessions_lst())) self.destroy() def i18n(self): """ Localization: 1. 'string' to _('string') 2. File's list to potfiles.in 3. To create .pot file: $ xgettext --files-from=potfiles.in --directory=../.. \ --output=messages.pot --language=Python --from-code=utf-8 4. Edit message.pot with poedit 5. Put in locale/lang/LC_MESSAGES/ 6. To update: $ msgmerge --update --no-fuzzy-matching --buckup=off \ ../../locale/lang/LC_MESSAGES/messages.po messages.pot Edit message.po with poedit """ try: lang = gettext.translation('messages', localedir='locale', languages=[self.lang]) except (OSError, AttributeError) as err: lang = gettext.NullTranslations() if DEBUG: print("\nError: {}".format(err)) lang.install()