def main(): printWait("Your current balance is Rs." + str(appData['total'])) while True: cc, main, cclen = getCommand() if (main == "deposit"): user.deposit(int(cc[1]), appData) elif (main == "withdraw"): user.withdraw(int(cc[1]), appData) elif (cclen == 2): funcName(main, askAmount(), user, appData, cc) elif (cclen == 3): try: amount = int(cc[2]) funcName(main, amount, user, appData, cc) except: funcName(main, askAmount(), user, appData, cc) elif (main == "summary"): printWait("Fetching summary...") progressBar() printTable(createTable(appData)) elif (main == "exit" or main == "quit"): if (confirm("Are you sure? ") == True): printWait("\nThank you for using this budgeting software. See you next time, " + name[0].upper() + name[ 1:] + ". Bye!") lastUser = name time.sleep(1) appData.close() quit() else: printWait("Sorry, I don't understand this command. Please try again.")
def writeDocument(cncpt, features, X, y, s_arr, twnd): path = cncpt+'//'+twnd+'//' createFolder(path) p = 0 q = len(s_arr) + X.shape[0] w = open(path + 'PreSelectedFTS_'+twnd+'_'+cncpt+'.csv', 'w') try: for i in range(0, len(s_arr)): w.write(str(features[s_arr[i]]) + ',') p += 1 progressBar('----Output file',p,q) w.write('Tag\n') for i in range(0, X.shape[0]): for j in range(0, len(s_arr)): w.write(str(X[i][s_arr[j]]) + ',') w.write(str(y[i])) if i < X.shape[0]-1: w.write('\n') p += 1 progressBar('----Output file',p,q) except KeyboardInterrupt: print('The program has been interrupted by the user.') except Exception as e: print('Unexpected error: ' + str(e)) w.close()
def DeleteFolder(n_dir, n_sub=[1, 17], n_act=[1, 11], n_trl=[1, 3], n_cam=[1, 2]): print('Deleating temporal files') p = 0 q = (n_sub[1] + 1 - n_sub[0]) * (n_act[1] + 1 - n_act[0]) * ( n_trl[1] + 1 - n_trl[0]) * (n_cam[1] + 1 - n_cam[0]) progressBar('--Progress', p, q) #Subjects for i in range(n_sub[0], n_sub[1] + 1): sub = 'Subject' + str(i) #Activities for j in range(n_act[0], n_act[1] + 1): act = 'Activity' + str(j) #Trials for k in range(n_trl[0], n_trl[1] + 1): trl = 'Trial' + str(k) gral = sub + '//' + act + '//' + trl + '//' #Cameras for l in range(n_cam[0], n_cam[1] + 1): path = n_dir + gral + sub + act + trl + 'Camera' + str( l) + '_OF_temp' try: shutil.rmtree(path) except: print('An error ocurred while deleting: ' + path) p += 1 progressBar('--Progress', p, q)
def withdraw(self, amount, appData): if (amount > appData['total']): print("Sorry, you do not have enough money!") else: appData['total'] -= amount print("Withdrawing...") progressBar(endText="Withdrawal Succesful!") printWait("Your total balance now is Rs." + str(appData['total']))
def UnzipFolders(directory, path, task): createFolder(path) try: p = 0 progressBar(task, p, len(os.listdir(directory))) for filen in os.listdir(directory): zipf = zf.ZipFile(directory + '//' + filen) zipf.extractall(path) zipf.close() p += 1 progressBar(task, p, len(os.listdir(directory))) except: print('--------The following direcory was not found: ' + directory)
def remove(self, type_, amount, appData): if (amount > appData[type_]): print("Sorry, that's not possible!") elif (amount == appData[type_]): types.remove(type_) appData['types'] = "/".join(types) else: appData['total'] += amount appData[type_] -= amount print("Tranferring Rs." + str(amount) + " back to your Total Balance...") progressBar(endText="Transfer Complete!") printWait("Your total balance now is Rs." + str(appData['total']))
def main(): if len(sys.argv) != 3: print('ERROR Debe especificar 1 ruta, 2 fichero md5') sys.exit(1) if not os.path.exists(sys.argv[1]): print('ERROR El fichero o directorio no existe: ' + sys.argv[1]) sys.exit(1) if not os.path.exists(sys.argv[2]): print('ERROR El fichero de md5 no existe: ' + sys.argv[2]) sys.exit(2) # listado de ficheros que existen lineas = fichero.leeLineas(sys.argv[2]) existen = [] for l in lineas: existen.append(l[0:32]) ficheros = [] if os.path.isdir(sys.argv[1]): ficheros = fichero.ficherosEnDir(sys.argv[1]) else: ficheros = [sys.argv[1]] print("Se van a calcular los MD5 de " + str(len(ficheros)) + " ficheros") iteracion = 0 total = len(ficheros) borrados = 0 errores = [] for f in ficheros: iteracion += 1 if fichero.md5sum(f) in existen: borrados += 1 try: os.remove(f) except: print("Error borrando: " + f) errores.append(f) progressBar(iteracion,total, str(borrados) + " " + str(f)) else: progressBar(iteracion,total) print("\nSe han borrado " + str(borrados) + " de " + str(total) + " ficheros") print("Errores: " + "\n".join(errores)) return 0
def main(): if len(sys.argv) != 3: print('ERROR Debe especificar 1 ruta, 2 fichero md5') sys.exit(1) if not os.path.exists(sys.argv[1]): print('ERROR El fichero o directorio no existe: ' + sys.argv[1]) sys.exit(1) if not os.path.exists(sys.argv[2]): print('ERROR El fichero de md5 no existe: ' + sys.argv[2]) sys.exit(2) # listado de ficheros que existen lineas = fichero.leeLineas(sys.argv[2]) existen = [] for l in lineas: existen.append(l[0:32]) ficheros = [] if os.path.isdir(sys.argv[1]): ficheros = fichero.ficherosEnDir(sys.argv[1]) else: ficheros = [sys.argv[1]] print("Se van a calcular los MD5 de " + str(len(ficheros)) + " ficheros") iteracion = 0 total = len(ficheros) borrados = 0 errores = [] for f in ficheros: iteracion += 1 if fichero.md5sum(f) in existen: borrados += 1 try: os.remove(f) except: print("Error borrando: " + f) errores.append(f) progressBar(iteracion, total, str(borrados) + " " + str(f)) else: progressBar(iteracion, total) print("\nSe han borrado " + str(borrados) + " de " + str(total) + " ficheros") print("Errores: " + "\n".join(errores)) return 0
def main(): if len(sys.argv) != 2 and len(sys.argv) != 3: print('ERROR Debe especificar 1 ruta, [2 fichero almacenamiento]') sys.exit(1) if not os.path.exists(sys.argv[1]): print('ERROR El fichero o directorio no existe: ' + sys.argv[1]) sys.exit(1) # El fichero resultado por defecto será el nombre del fichero/carpeta ficheroResultado = sys.argv[1] + ".md5"; # Comprobamos que no termine en / para que no genere un fichero ".md5" # dentro de él if sys.argv[1][len(sys.argv[1])-1] == '/': ficheroResultado = sys.argv[1][0:len(sys.argv[1])-1] + ".md5"; if len(sys.argv) == 3: ficheroResultado = sys.argv[2] if os.path.exists(ficheroResultado): os.remove(ficheroResultado) open(ficheroResultado, 'w').close() ficheros = [] if os.path.isdir(sys.argv[1]): ficheros = fichero.ficherosEnDir(sys.argv[1]) else: ficheros = [sys.argv[1]] print("Se van a calcular los MD5 de " + str(len(ficheros)) + " ficheros") texto = "" iteracion = 0 total = len(ficheros) for f in ficheros: try: iteracion += 1 texto += fichero.md5sum(f) + " " + f + '\n' progressBar.progressBar(iteracion,total,f) except Exception as e: print("ERROR fichero: " +f, e) fichero.escribirFicheroAlFinal(ficheroResultado, texto) print("El resultado se ha almacenado en: " + ficheroResultado) return 0
def setupCurses(self): self.titlewin = self.stdscr.subwin(1, 80, 0, 0) self.mainwin = self.stdscr.subwin(23, 80, 1, 0) self.progwin = self.stdscr.subwin(10, 60, 6, 10) self.statwin = self.stdscr.subwin(1, 80, 24, 0) self.progBar = progressBar(0, 100, 56) curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE) curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_CYAN) curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_WHITE) curses.init_pair(4, curses.COLOR_RED, curses.COLOR_WHITE) curses.init_pair(5, curses.COLOR_WHITE, curses.COLOR_BLACK) self.titlewin.bkgd(' ', curses.color_pair(1)) self.statwin.bkgd(' ', curses.color_pair(1)) self.mainwin.bkgd(' ', curses.color_pair(2)) self.titlewin.addstr(0, 0, "Installing " + self.packageName) self.statwin.addstr(0, 0, "Please wait...") self.resetProgWin() self.stdscr.refresh()
def start_bar(total): global current_count bar = progressBar.progressBar(total) while current_count < total: sys.stdout.write("\r[+] %s %d/%d" % (bar.get_bar(current_count), current_count+1, total)) sys.stdout.flush() time.sleep(0.2) sys.stdout.write("\r[+] %s %d/%d" % (bar.get_bar(total), total, total)) sys.stdout.flush()
def treeClss(X,y): q = 99 if X.shape[1] < 100: q = X.shape[1] progressBar('----Extra trees',0,q) forest = ExtraTreesClassifier(n_estimators=250, random_state=0) forest.fit(X, y) importances = forest.feature_importances_ indices = np.argsort(importances)[::-1] selection = [] for f in range(X.shape[1]): if f < 100: selection.append(indices[f]) progressBar('----Extra trees',f,q) else: break return selection
def display_bar(): global number_of_accounts, count bar = progressBar.progressBar(number_of_accounts) while show_bar: if count >= number_of_accounts: break sys.stdout.write("\r[+] %s" % bar.get_bar(count)) sys.stdout.flush() time.sleep(0.20) print "\r[+] %s" % bar.get_bar(number_of_accounts)
def freq(path,arr_1,arr_2,arr_3,features): i_flg = False arr = [] f_arr = join([], arr_1) f_arr = join(f_arr, arr_2) f_arr = join(f_arr, arr_3) w = open(path, 'w') p = 0 q = len(f_arr) try: progressBar('----Frequencies',p,q) w.write('Attribute No,Attribute,Frequency') for f in f_arr: i = 0 i = quantity(arr_1, f, i) i = quantity(arr_2, f, i) i = quantity(arr_3, f, i) w.write('\n' + str(f+1) + ',' + features[f] + ',' + str(i)) arr.append([f,i]) p += 1 progressBar('----Frequencies',p,q) except KeyboardInterrupt: print('The program has been aborted by the user') i_flg = True except Exception as e: print('Unexpected error: ' + str(e)) w.close() if not i_flg: temp = [] for i in range(0,len(f_arr)): for j in range(i,len(f_arr)): if arr[i][1] < arr[j][1]: temp = arr[i] arr[i] = arr[j] arr[j] = temp s_arr = [] for i in range(0,len(f_arr)): if arr[i][1] > 1: s_arr.append(arr[i][0]) s_arr.append(0) return s_arr return i_flg
def rfRFE(X,y): q = 100 if X.shape[1] < 100: q = int(X.shape[1]*0.3) progressBar('----RFE with RF',0,int(q*1.3)) estimator = RndFC(n_estimators = 10) selector = RFE(estimator, q, step=1) progressBar('----RFE with RF',int(q*0.2),int(q*1.3)) selector = selector.fit(X, y) progressBar('----RFE with RF',q,int(q*1.3)) selection = selector.get_support(1) progressBar('----RFE with RF',int(q*1.3),int(q*1.3)) return selection
def l2SM(X,y): q = 100 progressBar('----Linear SVC ',0,q) lsvc = LinearSVC(C=1.00, penalty="l2", dual=False).fit(X, y) model = SelectFromModel(lsvc, prefit=True) X_new = model.transform(X) if X_new.shape[1] < 100: q = X_new.shape[1] p = 0 selection = [] for f in range(X_new.shape[1]): for i in range(X.shape[1]): flg = True for j in range(X.shape[0]): if X[j][i] != X_new[j][f]: flg = False break if flg and (len(selection)<=100): selection.append(i) p += 1 progressBar('----Linear SVC ',p,q) return selection
def fileJoiner(path, n_sub=[1, 17], n_act=[1, 11], n_trl=[1, 3]): f_row = 1 f_name = 'CameraResizedOF.csv' f_flg = True p = 0 n_files = (n_sub[1] + 1 - n_sub[0]) * (n_act[1] + 1 - n_act[0]) * ( n_trl[1] + 1 - n_trl[0]) w = open(path + f_name, 'w') try: for i in range(n_sub[0], n_sub[1] + 1): sub = 'Subject' + str(i) for j in range(n_act[0], n_act[1] + 1): act = 'Activity' + str(j) for k in range(n_trl[0], n_trl[1] + 1): trl = 'Trial' + str(k) f_path = path + sub + '\\' + act + '\\' progressBar('--Joining files', p, n_files - 1) r = open(f_path + sub + act + trl + 'CameraResizedOF.csv', 'r') txt = r.read() r.close() file = txt.split('\n') start = f_row if f_flg: w.write(file[0]) if f_row == 2: w.write('\n' + file[1]) f_flg = False for row in file[start:]: q = row.split(',') if (q[0] != '') and (q[-1] != ''): w.write('\n' + row) p += 1 except KeyboardInterrupt: print("\n--The program has been interrupted.") except Exception as e: print('\n--Unexpected error: ' + str(e)) w.close()
def Func_ProgBar(Progress): if len(sys.argv) > 1: f = open('Progress.txt', 'r') num = f.read() prog = progressBar(maxValue=int(sys.argv[1])) prog.updateAmount(int(num)) prog.draw() print("") f.close() else: print('usage: progress.py MAXSIZE')
def checkOrCreateData(name, password): # Create shelve object while keeping nomenclature # to the specific user for easier access appData = shelve.open(('fad' + name)) printWait("\nInitializing your account...") printWait("Retrieving any previous data, if any...") # Checking username against existing shelve data if (name in appData): progressBar(endText="Data found. Checking password...") # If username exists, then check password # against user-defined existing shelve data while (password != appData['password']): password = str(input("Wrong password. Try again!\nPassword: "******"Password is correct! Logging in...") progressBar(endText="Success!") # Save the specific shelve object to a variable for # permanent data accessibility for the user session user = appData[name] else: progressBar(endText="No previous record found.") if (confirm("\nWould you like to create a new account?") == True): # Creating new user object using data provided # by user at script initialization user = Budget(name, password) # Saving customized class object to shelve object appData[user.user_name] = user printWait("Creating account...") progressBar(endText="Account created.") else: printWait("I will not create an account. Exiting program...") # Deleting data that this script may have unintentionally # created while checking for username against shelve data try: os.unlink(os.path.abspath(os.curdir) + "fad" + name + ".dir") pritn("Deleted .dir") os.unlink(os.path.abspath(os.curdir) + "fad" + name + ".bak") print("Deleted .bak") os.unlink(os.path.abspath(os.curdir) + "fad" + name + ".dat") print("Deleted .dat") except FileNotFoundError: print("Couldn't delete file.") quit() return user, appData
def checkInput(): global maxNumber, progress # Holding error status status = 1 # Check if max number of percentage is passed as argument or not if (len(argv) == 2): maxNumber = argv[1] # Checking if max number is valid input if (maxNumber.isdigit()): maxNumber = int(maxNumber) # Updating progress object with the new max value progress = progressBar(maxValue=maxNumber) else: status = 0 else: status = 0 return status
def train(self, x_train, y_train, x_valid, y_valid, epochs, eta=0.001, alpha=0.9): def forwardpass(x_train): """ Description:\n Forwardpass function (recursive function)\n Input:\n x_train: the intput x_train for current layer layer: current layer (number) out_vec: the output vector with corresponding output """ if self.bias: patterns = np.concatenate( (x_train, np.ones((1, np.shape(x_train)[1]))), axis=0) else: patterns = x_train hin = self.weights[0] @ patterns hout = self.transferFunction(hin) if self.bias: hout = np.concatenate((hout, np.ones( (1, np.shape(x_train)[1]))), axis=0) oin = self.weights[1] @ hout out = self.transferFunction(oin) out_vec = [hout, out] return out_vec def backprop(out_vec, y_train): """ Description:\n Backprop function\n Input:\n out_vec: the output vector for each layer\n y_train: target label\n Output:\n delta_h: the delta for the hidden layer\n delta_o: the delta for the output layer\n """ #print(np.shape(out_vec[1])) delta_o = (out_vec[1] - y_train) * ((1 + out_vec[1]) * (1 - out_vec[1])) * 0.5 delta_h = (np.transpose(self.weights[1]) @ delta_o) * ( (1 + out_vec[0]) * (1 - out_vec[0])) * 0.5 delta_h = delta_h[0:self.layers[0], :] return delta_h, delta_o # Inital delta weights. dw = np.zeros(np.shape(self.weights[0])) dv = np.zeros(np.shape(self.weights[1])) progBar = progressBar(epochs) loss_vec_train = [] loss_vec_valid = [] epoch_vec = [] # training for all the epochs. for epoch in range(epochs): progBar.Progress(epoch) # Forwarding out_vec = forwardpass(x_train=x_train) # Back propogating delta_hidden, delta_output = backprop(out_vec, y_train) # Weights update if self.bias: pat = np.concatenate( (x_train, np.ones((1, np.shape(x_train)[1])))) else: pat = x_train dw = (dw * alpha) - (delta_hidden @ np.transpose(pat)) * (1 - alpha) dv = (dv * alpha ) - (delta_output @ np.transpose(out_vec[0])) * (1 - alpha) self.weights[0] = self.weights[0] + dw * eta self.weights[1] = self.weights[1] + dv * eta # Loss function loss_vec_train.append(self.loss_val(x_train, target=y_train)) loss_vec_valid.append(self.loss_val(x_valid, target=y_valid)) epoch_vec.append(epoch) return epoch_vec, loss_vec_train, loss_vec_valid
def setup_prog_bar(self, minValue = 0, maxValue = 10, totalWidth=12): if self.pb_enabled: self.pb_max_val = maxValue self.pb_min_val = minValue self.pb = progressBar.progressBar(minValue, maxValue , totalWidth)
def __init__(self): #Create the window---------------------------------------------------------- self.__win=Tk() self.__win.title("Timer") self.__win.iconbitmap("favicon.bmp") #Frame contain simple words------------------------------------------------- self.__instruFrame=Frame(self.__win) self.__instruLabel=Label(self.__instruFrame,text="Please select minutes and enter seconds") self.__instruLabelExplain=Label(self.__instruFrame,text="This timer only allow count \ down within 10:59 minutes.\n Please enter a integer between 0 to 59 as the seconds") self.__instruLabel.pack(side="top") self.__instruLabelExplain.pack(side="top") self.__instruFrame.pack() #Frame contian the dropdown bars--------------------------------------------- self.__chooseFrame=Frame(self.__win) #For min self.__minList=[0,1,2,3,4,5,6,7,8,9,10] self.__minVar=IntVar(self.__chooseFrame) self.__minVar.set(0) self.__minOption=OptionMenu(self.__chooseFrame,self.__minVar,\ *self.__minList,command=self.checkStartTimer) self.__minLabel=Label(self.__chooseFrame,text="Min") #For sec self.__secVar=IntVar(self.__chooseFrame) self.__secVar.set(0) self.__secEntry=Entry(self.__chooseFrame,width=7) self.__secEntry.bind('<Return>',self.setSec) self.__secLabel=Label(self.__chooseFrame,text="Sec") #pack self.__minOption.pack(side="left") self.__minLabel.pack(side="left") self.__secEntry.pack(side="left") self.__secLabel.pack(side="left") self.__chooseFrame.pack() #Frame contain the command buttons------------------------------------------- self.__commandFrame=Frame(self.__win) self.__stage=False #The buttons should be disabled initially self.__startButton=Button(self.__commandFrame,text="Start",command=self.start) self.__startButton.config(state="disabled") self.__pauseButton=Button(self.__commandFrame,text="Pause",command=self.pause) self.__pauseButton.config(state="disabled") self.__resetButton=Button(self.__commandFrame,text="Reset",command=self.reset) self.__resetButton.config(state="disabled") self.__startButton.pack(side="left") self.__pauseButton.pack(side="left") self.__resetButton.pack(side="left") self.__commandFrame.pack() #Display frame------------------------------------------------------------- self.__displayFrame=Frame(self.__win) #text frame self.__textFrame=Frame(self.__displayFrame) self.__stageVar=StringVar(self.__textFrame) self.__stageVar.set(" ") self.__stageLabel=Label(self.__textFrame,textvariable=self.__stageVar) self.__currentSec=IntVar(self.__textFrame) self.__currentSec.set(0) self.__currentMin=IntVar(self.__textFrame) self.__currentMin.set(0) self.__currentMinLable=Label(self.__textFrame,textvariable=self.__currentMin) self.__minLeft=Label(self.__textFrame,text="Min") self.__currentSecLable=Label(self.__textFrame,textvariable=self.__currentSec) self.__secLeft=Label(self.__textFrame,text="Sec") self.__currentMinLable.pack(side="left") self.__minLeft.pack(side="left") self.__currentSecLable.pack(side="left") self.__secLeft.pack(side="left") self.__stageLabel.pack(side="left") self.__textFrame.pack() #Loading frame self.__loadingFrame=Frame(self.__displayFrame) self.__progressBar=progressBar.progressBar(self) self.__loadingFrame.pack() self.__displayFrame.pack() mainloop()
def __createCollection__(self, collection, path, newline=False): for element in collection: tmpPath = os.path.join(path, self.__classes[element['class']]) shutil.copy(element['src'], tmpPath) progressBar(self.__totalData, self.__dataCount, newline)
def transfer(filename, HOST='localhost', PORT=8578): clientsock = socket(AF_INET, SOCK_STREAM) # CHECK FOR HOST AVAILABILITY. clientsock.settimeout(120) tmp = clientsock.connect_ex((HOST, PORT)) if tmp != 0: sys.exit('Connection Timeout - 200sec') # SEND HOST FILESIZE. size = os.path.getsize(filename) size = str(size) clientsock.send(size) # WAIT FOR ACKNOWLEDGEMENT BEFORE PROCEED clientsock.recv(1024) # SEND FILE NAME TO SOCKET SERVER. # STRIP \ FROM FILEPATH STRING AND ASSIGN FILENAME # OR ELSE SERVER WONT SAVE IN THE SAME DIRECTORY # IT WILL SAVE IN THE SAME DIRECTORY AS THE FILEPATH. tmp = filename.split('\\') tmpFilename = tmp[len(tmp) - 1] clientsock.send(tmpFilename) clientsock.recv(1024) # WAIT FOR ACK # FILE CHECKSUM MD5 - FASTER THEN SHA-1 import filecheckmd5 hash = filecheckmd5.compute(filename) clientsock.send(hash) print tmpFilename, '- md5 : ', hash clientsock.recv(1024) # ACK import time size = int(size) import progressBar temp = progressBar.progressBar(0, size) # FOR UPDATING PROGRESS BAR currentSize = 0 t = time.time() # CHECK TIME FOR ACK FROM HOST t2 = 0.0 chunkSize = 2048 try: while size > 0: chunk = f.read(chunkSize) t2 = time.time() clientsock.send(chunk) size = size - chunkSize currentSize = currentSize + chunkSize temp.updateAmount(currentSize) clientsock.recv(1024) # WAIT FOR ACKNOWLEDGEMENT HOST speed = time.time() - t2 print temp.progBar, currentSize, ' out of ', temp.max, " Chunk Travel - 2KB/%.5f sec" % ( speed), "\r", except: sys.exit("Error - connection lost") t = time.time() - t print '\nTransfer Complete - took %s sec' % (t) print 'Close socket' clientsock.close()
from PIL import Image import matplotlib.pyplot as plt import matplotlib.image as mpimg import os model_name = "model3" itr = 1 epoch_count = 500 batch_size = 1 label_count = 47 learning_rate = 0.001 image_size = 28 * 28 image_shape = [-1, 28, 28, 1] label_shape = [-1, label_count] progress = progressBar(tot_items=30) #session sess = tf.Session() #tensorboard writer = tf.summary.FileWriter("./Logs/NN_log", sess.graph) merged = tf.summary.merge_all() Input_image = tf.placeholder(tf.float64) Input_image_reshaped = tf.reshape(Input_image, image_shape) label_matrix = tf.placeholder(tf.float64) label_matrix_reshaped = tf.reshape(label_matrix, label_shape) #model :
tree.addFile("a1.h5") frame = frame(content.getObject(), values_json["frame"][0], values_json["frame"][1]) frame1 = frame.getObject() button1 = button(frame1, frame1.quit, values_json["button"][0], values_json["button"][1]) label = label(content.getObject(), values_json["label"][0], values_json["label"][1]) # entry = entry(content.getObject(), values_json["entry"][0], values_json["entry"][1]) # entry.render() textBig = text(content.getObject(), values_json["textBig"][0], values_json["textBig"][1]) buttonPrintEntry = button(frame1, entry.getTextVal, values_json["buttonEntry"][0], values_json["buttonEntry"][1]) buttonPrintText = button(frame1, textBig.getTextVal, values_json["buttonText"][0], values_json["buttonText"][1]) progBar = progressBar(content.getObject(), values_json["progressBar"][0], values_json["progressBar"][1]) buttonProgBar = button(frame1, progBar.step, values_json["progButton"][0], values_json["progButton"][1]) menubar = menuBar(frame1, position=values_json["menubar"][0]) menuFile = menuFile(menubar.getObject()) menubar.addMenuFile("File", menuFile.getObject()) trigger = button(frame1, createCanvas, values_json["buttonTrigger"][0], values_json["buttonTrigger"][1]) root.mainloop()
def camOF_joiner(gral, rs_path, n_sub=[1, 17], n_act=[1, 11], n_trl=[1, 3], n_cam=[1, 2]): cmr = [] interrupt = False for cam in n_cam: cmr.append('Camera' + str(cam) + '_OF_UZ//') for i in range(n_sub[0], n_sub[1] + 1): if interrupt: break sub = 'Subject' + str(i) print(sub) for j in range(n_act[0], n_act[1] + 1): if interrupt: break act = 'Activity' + str(j) print('S' + str(i) + '--' + act) for k in range(n_trl[0], n_trl[1] + 1): if interrupt: break trl = 'Trial' + str(k) print('S' + str(i) + '-A' + str(j) + '--' + trl) path = gral + sub + '//' + act + '//' + trl + '//' + sub + act + trl + cmr[ 0] #path = gral+trl+'//'+sub+act+trl+cmr[0] path2 = gral + sub + '//' + act + '//' + trl + '//' + sub + act + trl + cmr[ 1] if os.path.exists(path) and os.path.exists(path2): files = os.listdir(path) files2 = os.listdir(path2) if len(files) == len(files2): p = 0 n_path = rs_path + sub + '//' + act + '//' createFolder(n_path) n_file = sub + act + trl + 'CameraResizedOF_notag.csv' print('----------Writing...') w = open(n_path + n_file, 'w') try: w.write('Timestamp') for z in range(n_cam[0], n_cam[1] + 1): for q in range(0, 20): for r in range(0, 20): w.write(',C' + str(z) + '(' + str(q) + ';' + str(r) + ')') w.write(',Subject,Activity,Trial') print('------------Joining ' + str(len(files)) + ' files') while p < len(files): if p % 2 == 0: npath = path + files[p] npath2 = path2 + files[p] tst = tstGT(files[p]) arr1 = resCSV(npath) sar1 = resCSV(npath2) p += 1 npath = path + files[p] npath2 = path2 + files[p] arr2 = resCSV(npath) sar2 = resCSV(npath2) arrf = sqrd(arr1, arr2) sarf = sqrd(sar1, sar2) w.write('\n' + tst) for q in range(0, 20): for r in range(0, 20): w.write(',' + str(arrf[i][j])) for q in range(0, 20): for r in range(0, 20): w.write(',' + str(sarf[i][j])) w.write(',' + str(i) + ',' + str(j) + ',' + str(k)) progressBar('-------------Progress', p, len(files), width=2) p += 1 except KeyboardInterrupt: print("\nThe program has been interrupted.") interrupt = True except Exception as e: print('-----------Unexpected error: ' + str(e)) w.close() if not interrupt: print('\n------------' + n_file + ' has been successfully created.') else: print('------------Images from paths ' + path + ' and ' + path2 + ' do not fit')
def tag_track(gral='', tag_path, file_tags, n_sub=[1, 17], n_act=[1, 11], n_trl=[1, 3]): interrupt = False d_base = relData(readDBase(file_tags)) #to store the index in wich a certain trial begins db_i = 0 for i in range(n_sub[0], n_sub[1] + 1): if interrupt: break sub = 'Subject' + str(i) print(sub) while int(d_base[db_i][1]) < i: db_i += 1 if db_i == len(d_base): print(sub + ' was not found') interrupt = True break for j in range(n_act[0], n_act[1] + 1): if interrupt: break act = 'Activity' + str(j) print('S' + str(i) + '--' + act) flg_out = False while int(d_base[db_i][2]) < j: db_i += 1 if (int(d_base[db_i][1]) > i): flg_out = True elif db_i == len(d_base): interrupt = True if flg_out: print(sub + ' ' + act + ' was not found') break for k in range(n_trl[0], n_trl[1] + 1): trl = 'Trial' + str(k) print('S' + str(i) + '-A' + str(j) + '--' + trl) flg_out = False while int(d_base[db_i][3]) < k: db_i += 1 if (int(d_base[db_i][1]) > i) or (int(d_base[db_i][2]) > i): flg_out = True elif db_i == len(d_base): break if flg_out: print(sub + ' ' + act + ' ' + trl + ' was not found') break if interrupt: break path = gral + sub + '//' + act + '//' + sub + act + trl + 'CameraResizedOF_notag.csv' n_path = tag_path + sub + '//' + act + '//' createFolder(n_path) n_file = sub + act + trl + 'CameraResizedOF.csv' if os.path.exists(path): trl_data = readDBase(path) w = open(n_path + n_file, 'w') try: w.write(trl_data[0] + ',Tag') #An array in which to store timestamps that have no pair in a trial unpaired = [] for p in range(1, len(trl_data)): progressBar('-------Progress', p, len(trl_data) - 1) ln = trl_data[p].split(',') db_tmp = db_i tst_flg = True while index_val(d_base, db_tmp, i, j, k): #current timestamp is compared with the tag's timestamp if ln[0] == d_base[db_tmp][0]: w.write('\n' + trl_data[p] + ',' + d_base[db_tmp][4]) tst_flg = False break db_tmp += 1 if tst_flg: unpaired.append(tst) except KeyboardInterrupt: print("\nThe program has been interrupted.") interrupt = True except Exception as e: print('\n-----------Unexpected error: ' + str(e)) w.close() if not interrupt: state = ' successfully' if len(unpaired) > 0: state = '' print('--------Warning, unpaired time stamps: ') print(unpaired) print('-------File' + state + ' created.')
def setup_prog_bar(self, minValue=0, maxValue=10, totalWidth=12): if self.pb_enabled: self.pb_max_val = maxValue self.pb_min_val = minValue self.pb = progressBar.progressBar(minValue, maxValue, totalWidth)
from progressBar import progressBar from time import sleep import sys import os progress = progressBar(tot_items=30, name="Epoch progress") t = [30, 25, 60, 70, 10] for j in range(5): for i in range(t[j]): progress.signal_job_done() sleep(0.25) print("EPOCH FINISHED !!!") if j + 1 < 5: progress.reset(t[j + 1])
def deposit(self, amount, appData): if amount > 0: appData['total'] += amount print("Depositing...") progressBar(endText="Deposit Succesful!") printWait("Your total balance now is Rs." + str(appData['total']))