def juegaRosco(rosco, tiempo=120): mixer.init(24000) rcg = sr.Recognizer() mic = sr.Microphone() #set threhold level with mic as source: rcg.adjust_for_ambient_noise(source) print("Set minimum energy threshold to {}".format(rcg.energy_threshold)) rcg.pause_threshold = 0.5 print(Fore.RED + Style.BRIGHT + "\nINICIO ROSCO " + Style.RESET_ALL + Fore.CYAN + "[" + str(tiempo) + "seg.]" + Style.RESET_ALL) vueltas = Vueltas() cronometro = MyTimer(tiempo, vueltas.stop) score = vueltas.run(rosco, cronometro, rcg, mic) cronometro.cancel() print("\nResultados: ") print(Fore.CYAN + " BUENAS " + str(score["buenas"])) print(Fore.RED + " MALAS " + str(score["malas"])) print(Fore.YELLOW + " PENDIENTES " + str(len(score["pendientes"]))) print(Fore.RESET + " TIEMPO RESTANTE " + str(cronometro.deadline - cronometro.acumTime)) mixer.quit()
class TestMyTimer(unittest.TestCase): global myTimer @classmethod def setUp(self): self.myTimer = MyTimer() @unittest.skip def test_givenTimeInMinutes__thenTriggerSoundAfterTimeLapse(self): wait_until = 1 self.myTimer.startTimer(wait_until) def test_waitTimePrintMessage(self): self.myTimer.printMessage(60)
def start(self): donnees = None if self.type_session == 'tkt': donnees = {'PC_id':Connexion.PC_id, 'login': self.login , 'ticket_id': self.ticket_id, 'ticket_identifiant': self.ticket_identifiant , 'PC_identifiant': Connexion.PC_identifiant} else: donnees = {'PC_id':Connexion.PC_id, 'user_id': self.user_id , 'mdp': self.mdp, 'login': self.login, 'user_identifiant': self.identifiant_user , 'PC_identifiant': Connexion.PC_identifiant} retour = self.retourServeur(donnees, Connexion.server_url_start) self.id = -1 if 'message' in self.erreur: return -1 if 'connexions' in self.infos: connexions = self.infos['connexions'] for c in connexions: if c['courante'] == 1: self.id = c['id'] self.date_fin = datetime.datetime.strptime(c['date_fin'][0:18], "%Y-%m-%d %H:%M:%S")#attention format date else: if retour <> 0: return -1 if retour <> 0: return self.close() if 'temps_restant' in self.infos: self.temps_restant = Decimal(self.infos['temps_restant']) else: return self.close() if self.id == -1: return -1 if self.temps_restant == 0: return self.close() self.t = MyTimer(int(self.temps_restant)*60/len(self.infos['connexions'])-5, self.testerValidite) self.t.start() self.dernier_pointage = datetime.datetime.now() return 0
def __init__(self, parent = None): QtGui.QWidget.__init__(self, parent) self.setupUi(self) self.title = "Combinatorics - Обчислення комбінацій та перестановок" self.currentTabText = self.tabComb.tabText(self.tabComb.currentIndex()) self.currentTab = self.tabComb.currentWidget() self.setWindowTitle(self.title + " - " + self.currentTabText) self.m = ModelMetadata() #self.v = self self.timer = MyTimer(self) self.thread = MyThread(self) self.status = "stoped" self.handleEvents() self.MetaTableReset() self.metaRows["result"].setText(os.path.abspath(self.m.file.name)) self.tableMetadata.resizeColumnsToContents() self.show()
def setUp(self): self.myTimer = MyTimer()
class Connexion: local_connexions = {} options = json.loads(sys.argv[1]) #{"PC_id": 12, "PC_identifiant": "3215674897", "server_url_start": "http://192.168.1.2/start" #, "server_url_cont": "http://192.168.1.2/cont", "server_url_clo": "http://192.168.1.2/cont", "port": 8080 #, "session_close_cmd": "/sbin/reboot"} if 'server_url_start' in options: server_url_start = options['server_url_start'] else: server_url_start = 'http://192.168.1.2/start' if 'server_url_cont' in options: server_url_cont = options['server_url_cont'] else: server_url_cont = 'http://192.168.1.2/cont' if 'server_url_clo' in options: server_url_clo = options['server_url_clo'] else: server_url_clo = 'http://192.168.1.2/cont' if 'port' in options: port = options['port'] else: port = 8080 if 'session_close_cmd' in options: session_close_cmd = options['session_close_cmd'] else: session_close_cmd = '/sbin/reboot' if 'PC_id' in options: PC_id = int(options['PC_id']) else: print'Pas de PC_id dans les paramètres, il est obligatoire ("PC_id": <int>)' quit() if 'PC_identifiant' in options: PC_identifiant = options['PC_identifiant'] else: print'Pas de PC_identifiant dans les paramètres, il est obligatoire ("PC_identifiant": <int>)' quit() if 'allowed_users' in options: allowed_users = options['allowed_users'] else: allowed_users = {} kill_process_next_check = 0 #Kill processes next check connected_users = {} #connected users def __init__(self, login, mdp, identifiant, user_id): self.login = login self.user_id = user_id self.identifiant_user = identifiant self.mdp = mdp self.code_erreur = 0 self.message = 'OK' self.type_session = 'user' self.erreur = {} self.t_fin = None if self.start() != -1: Connexion.local_connexions[self.type_session+str(self.id)] = self Connexion.connected_users[self.login] = self.type_session+str(self.id) return else: raise Exception('Connexion impossible') def __init__(self, login, ticket_identifiant, ticket_id):#r['user_login'], r['ticket_identifiant'], r['ticket_id'] self.login = login self.ticket_identifiant = ticket_identifiant self.ticket_id = ticket_id self.code_erreur = 0 self.message = 'OK' self.type_session = 'tkt' self.t_fin = None if self.start() != -1: Connexion.local_connexions[self.type_session+str(self.id)] = self Connexion.connected_users[self.login] = self.type_session+str(self.id) return else: raise Exception('Connexion impossible : ('+self.erreur['message']+')') # @staticmethod def poursuit_tkt(login, ticket_identifiant, ticket_id, session_id, tkt): c = Connexion.find(session_id, tkt) if c is not None: if c.login != login or c.ticket_identifiant != ticket_identifiant or c.ticket_id != ticket_id or c.id != session_id: return c.close() else: c.poursuit() return c poursuit_tkt = staticmethod(poursuit_tkt) def check_conn_users(): nb_p_to_kill = 0 p=subprocess.Popen(['/bin/ps', '-e', '-o', 'user,uid,pid,command'], stdout=subprocess.PIPE) #wmctrl -lp pour lister les fenêtres... l = p.stdout.readline() #header line l = ' '.join((p.stdout.readline()).split()) while len(l) > 1: l_d = l.split(' ', 4) process = psutil.Process(int(l_d[2])) uid = int(l_d[1]) if process.username in Connexion.allowed_users or len(Connexion.allowed_users) == 0 or process.username in Connexion.connected_users or uid < 1000: print 'Autorisé ou connecté ou tout le monde autorisé ou < 1000 : '+l else: print 'Non autorisé ni connecté: '+l if Connexion.kill_process_next_check == 1: process.kill() #Last check found one unallowed process : this time kill it else: nb_p_to_kill += 1 #At least one process to kill at next check l = ' '.join((p.stdout.readline()).split()) if nb_p_to_kill > 0: Connexion.kill_process_next_check = 1 else: Connexion.kill_process_next_check = 0 check_conn_users = staticmethod(check_conn_users) # @staticmethod def close_tkt(login, ticket_identifiant, ticket_id, session_id, tkt): c = Connexion.find(session_id, tkt) if c is not None: if c.login != login or c.ticket_identifiant != ticket_identifiant or c.ticket_id != ticket_id or c.id != session_id: return -1 else: c.close() return c close_tkt = staticmethod(close_tkt) # @staticmethod #def poursuit(login, identifiant, connexion_id, connexion_identifiant): #c = Connexion.find(connexion_id) #if c is not None: #if c.login != login or c.identifiant_user != identifiant or c.identifiant != connexion_identifiant or c.id != connexion_id: #c.close() #return c #else: #c.poursuit() #return c #poursuit = staticmethod(poursuit) # @staticmethod #def close(login, identifiant, connexion_id, connexion_identifiant): #c = Connexion.find(connexion_id) #if c is not None: #if c.login != login or c.identifiant_user != identifiant or c.identifiant != connexion_identifiant or c.id != connexion_id: #return -1 #else: #c.close() #return c #close = staticmethod(close) # @staticmethod def find(connexion_id, tkt): if tkt+str(connexion_id) in Connexion.local_connexions: return Connexion.local_connexions[tkt+str(connexion_id)] else: return None find = staticmethod(find) def start(self): donnees = None if self.type_session == 'tkt': donnees = {'PC_id':Connexion.PC_id, 'login': self.login , 'ticket_id': self.ticket_id, 'ticket_identifiant': self.ticket_identifiant , 'PC_identifiant': Connexion.PC_identifiant} else: donnees = {'PC_id':Connexion.PC_id, 'user_id': self.user_id , 'mdp': self.mdp, 'login': self.login, 'user_identifiant': self.identifiant_user , 'PC_identifiant': Connexion.PC_identifiant} retour = self.retourServeur(donnees, Connexion.server_url_start) self.id = -1 if 'message' in self.erreur: return -1 if 'connexions' in self.infos: connexions = self.infos['connexions'] for c in connexions: if c['courante'] == 1: self.id = c['id'] self.date_fin = datetime.datetime.strptime(c['date_fin'][0:18], "%Y-%m-%d %H:%M:%S")#attention format date else: if retour <> 0: return -1 if retour <> 0: return self.close() if 'temps_restant' in self.infos: self.temps_restant = Decimal(self.infos['temps_restant']) else: return self.close() if self.id == -1: return -1 if self.temps_restant == 0: return self.close() self.t = MyTimer(int(self.temps_restant)*60/len(self.infos['connexions'])-5, self.testerValidite) self.t.start() self.dernier_pointage = datetime.datetime.now() return 0 def poursuit(self): donnees = None if self.type_session == 'tkt': donnees = {'PC_id':Connexion.PC_id, 'login': self.login , 'ticket_id': self.ticket_id, 'ticket_identifiant': self.ticket_identifiant , 'PC_identifiant': Connexion.PC_identifiant, 'session_id': self.id} else: donnees = {'PC_id':Connexion.PC_id, 'user_id': self.user_id , 'mdp': self.mdp, 'login': self.login, 'user_identifiant': self.identifiant_user , 'PC_identifiant': Connexion.PC_identifiant, 'session_id': self.id} retour = self.retourServeur(donnees, Connexion.server_url_cont) if retour <> 0: return -1 if 'temps_restant' in self.infos: self.temps_restant = Decimal(self.infos['temps_restant']) else: return self.close() id = -1 if 'connexions' in self.infos: connexions = self.infos['connexions'] for c in connexions: if c['courante'] == 1: id = c['id'] if id == self.id: self.date_fin = datetime.datetime.strptime(c['date_fin'][0:18], "%Y-%m-%d %H:%M:%S")#attention format date else: return self.close() pc = c['pc'] pc_temps_mini = Decimal(pc['temps_mini_facture']) temps_total_restant = Decimal(self.infos['minutes_total_restantes']) # if temps_total_restant < pc_temps_mini: print "Reste : "+str(temps_total_restant) + '(pc_temps_mini='+str(pc_temps_mini)+')' self.t.stop() if self.t_fin != None: self.t_fin.cancel() self.t_fin = None self.t_fin = threading.Timer(int(temps_total_restant*Decimal(60))+44, self.testerValidite) self.t_fin.start() if id == -1 or id != self.id: return -1 self.t._tempo = int(self.temps_restant)*60/len(self.infos['connexions'])-5 self.dernier_pointage = datetime.datetime.now() return 0 def close(self): donnees = None if self.type_session == 'tkt': donnees = {'PC_id':Connexion.PC_id, 'login': self.login , 'ticket_id': self.ticket_id, 'ticket_identifiant': self.ticket_identifiant , 'PC_identifiant': Connexion.PC_identifiant, 'session_id': self.id} else: donnees = {'PC_id':Connexion.PC_id, 'user_id': self.user_id , 'mdp': self.mdp, 'login': self.login, 'user_identifiant': self.identifiant_user , 'PC_identifiant': Connexion.PC_identifiant, 'session_id': self.id} retour = self.retourServeur(donnees, Connexion.server_url_clo) self.t.stop() if self.t_fin != None: self.t_fin.cancel() self.t_fin = None del Connexion.local_connexions[self.type_session+str(self.id)] del Connexion.connected_users[self.login] if retour <> 0: return -1 else: return 0 return -1 def retourServeur(self, donnees, url): req = urllib2.Request(url, urllib.urlencode({'donnees':json.dumps(donnees)})) print 'envoi de ' + str(json.dumps(donnees))+ ' vers ' +str(url) h=None content = None self.erreur = {} try: h = urllib2.urlopen(req) except urllib2.HTTPError, e: print 'Problème : erreur %s' % (str(e.code)) content = json.loads(e.read()) print content self.code_erreur = e.code except urllib2.URLError, e: print 'Echec de la liaison avec le serveur %s(%s)' % (url, e.reason) # self.erreur = json.loads(e.read()) self.erreur = 'Echec de la liaison avec le serveur '+str(url)+'('+str(e.reason)+')' self.code_erreur = -1 return -1
erreur = c.erreur else: self.send_response(400) self.end_headers() return else: self.send_response(400) self.send_response(200) self.end_headers() if 'message' in erreur: print str(erreur) message = json.dumps( erreur) else: message = json.dumps( c.infos) self.wfile.write(message) self.wfile.write('\n') if a == 'tkt_quit': c = None return class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): """Handle requests in a separate thread.""" if __name__ == '__main__': server = ThreadedHTTPServer(('localhost', 8088), Handler) Connexion.t = MyTimer(600, Connexion.check_conn_users) Connexion.t.start() print 'Starting server, use <Ctrl-C> to stop' server.serve_forever()
class Controller(QtGui.QWidget, View): def __init__(self, parent = None): QtGui.QWidget.__init__(self, parent) self.setupUi(self) self.title = "Combinatorics - Обчислення комбінацій та перестановок" self.currentTabText = self.tabComb.tabText(self.tabComb.currentIndex()) self.currentTab = self.tabComb.currentWidget() self.setWindowTitle(self.title + " - " + self.currentTabText) self.m = ModelMetadata() #self.v = self self.timer = MyTimer(self) self.thread = MyThread(self) self.status = "stoped" self.handleEvents() self.MetaTableReset() self.metaRows["result"].setText(os.path.abspath(self.m.file.name)) self.tableMetadata.resizeColumnsToContents() self.show() def run(self): sys.exit(app.exec_()) def closeEvent(self, event): # clean garbage if self.status in ["started", "paused"]: self.handleStop() # stop thread del self.m # close file event.accept() def handleEvents(self): # enable/disable spinBox or plainTextEdit self.connect(self.radioN, QtCore.SIGNAL("toggled(bool)"), self.spinN.setEnabled) self.connect(self.radioNCustom, QtCore.SIGNAL("toggled(bool)"), self.plainNCustom.setEnabled) self.tabComb.currentChanged.connect(self.handleChangeTab) # link in QLabel leads to other Tab within QTabWidget self.label.linkActivated.connect(lambda link: self.tabComb.setCurrentIndex(int(link[4:]))) # prevent setting K larger than N # self.spinN.valueChanged.connect(lambda value: self.spinK.setMaximum(value)) self.spinColumns.valueChanged["int"].connect(lambda val: setattr(self.m, "columns", val)) self.tabComb.currentChanged.connect(self.handleChange) self.plainNCustom.textChanged.connect(self.handleChange) self.spinN.valueChanged.connect(self.handleChange) self.spinK.valueChanged.connect(self.handleChange) self.radioN.clicked.connect(self.handleChange) self.radioNCustom.clicked.connect(self.handleChange) self.btnStart.clicked.connect(self.handleStart) self.btnStop.clicked.connect(self.handleStop) self.btnResultPath.clicked.connect(self.handleChangePath) self.metaRows["btnClear"].clicked.connect(self.handleClearResult) self.tableMetadata.cellDoubleClicked.connect(self.openResult) self.connect(self.timer, QtCore.SIGNAL("upd_prog_bar(int)"), self.metaRows["progressBar"], QtCore.SLOT("setValue(int)")) self.thread.finished.connect(self.handleStop) def handleChange(self): if self.plainNCustom.isEnabled(): self.m.seq = self.plainNCustom.toPlainText().split() if not self.m.seq: return #self.spinK.setMaximum(len(self.m.seq)) # if k can't be larger than N else: self.m.seq = range(1, self.spinN.value() + 1) self.m.K = self.spinK.value() self.MetaAllUpdate() def handleChangeTab(self, index): self.currentTabText = self.tabComb.tabText(index) self.currentTab = self.tabComb.widget(index) self.setWindowTitle(self.title + " - " + self.currentTabText) self.spinK.setDisabled(index==4) # Permutation doesn't require K, only N self.MetaTableReset() def disabledWhenStart(self, flag): # list of elements that gonna be disabled when Calc. starts (and enabled when stops) disableList = [self.tabComb, self.groupInput, self.checkMetadata, self.checkShowResult, self.spinColumns, self.btnResultPath, self.metaRows["btnClear"]] self.btnStop.setEnabled(flag) for w in disableList: w.setDisabled(flag) def handleStart(self): if self.status in ["stoped", "paused"]: if self.status == "stoped": self.writeMetaData() self.status = "started" self.disabledWhenStart(True) self.btnStart.setText("Призупинити") self.btnStart.setIcon(QtGui.QIcon(QtGui.QPixmap(":/icons/pause.png"))) self.timer.start(1000) self.thread.func = self.currentTab.coreGenerator self.thread.start() elif self.status == "started": self.status = "paused" self.btnStart.setText("Продовжити") self.btnStart.setIcon(QtGui.QIcon(QtGui.QPixmap(":/icons/play.png"))) self.handlePause() def handlePause(self): self.timer.stop() if self.checkShowResult.isChecked(): self.openResult() def handleStop(self): self.status = "stoped" self.disabledWhenStart(False) self.btnStart.setText("Старт обчислень") self.btnStart.setIcon(QtGui.QIcon(QtGui.QPixmap(":/icons/play.png"))) if self.timer.isActive(): self.timer.stop() self.MetaTimeUpdate() # adjustment meta data self.flushResult() if self.checkShowResult.isChecked(): self.openResult() self.m.reset() def handleChangePath(self): path = QtGui.QFileDialog.getSaveFileName(parent=self, caption="Виберіть новий файл, для збереження результату", directory=QtCore.QDir.currentPath(), filter="Text files (*.txt)") if path[0]: self.m.filename = path[0] self.m.file.close() self.m.file = open(os.path.normpath(self.m.filename), "w+", encoding="utf8") self.metaRows["result"].setText(os.path.abspath(self.m.file.name)) self.tableMetadata.resizeColumnsToContents() def handleClearResult(self): self.m.file.close() self.m.file = open(self.m.filename, "w+", encoding="utf-8") self.metaRows["labelSize"].setText("0 байт") # periodically write data from result list to file def flushResult(self): i=0 columns = self.m.columns result = "" while i<len(self.m.result): result += "\t".join(self.m.result[i : (i+columns)]) + "\n" i += columns self.m.file.write(result) self.m.file.flush() self.MetaFileSizeUpdate() self.m.result = [] def openResult(self, row=6, col=0): # row and col here recieves from table's cell dblClick signal if row==6 and col==0: os.startfile(os.path.abspath(self.m.file.name)) # os.popen("notepad " + os.path.abspath(self.m.file.name)) # could be that variant as well def writeMetaData(self): if self.checkMetadata.isChecked(): meta = "{0}\n{0}\n\nТип: {1}\nВхідні дані: N={2}{3}\nВсього комбінацій: {4}\n{0}\n".format( "-"*40, self.currentTabText, len(self.m.seq), ", k=%s" % self.spinK.value() if self.tabComb.currentIndex != 4 else "", self.m.All ) self.m.file.write(meta) self.m.file.flush() def MetaTableReset(self): self.metaRows["name"].setText(self.currentTabText) self.metaRows["all"].setText("1") self.metaRows["complete"].setText("0") self.metaRows["progressBar"].setValue(0) self.metaRows["time"].setText("") self.metaRows["left"].setText("") self.tableMetadata.resizeColumnsToContents() def MetaAllUpdate(self): try: self.m.All = self.currentTab.coreNumber(self.m.seq, self.m.K) except ValueError: self.m.All = 0 self.metaRows["all"].setText( str(self.m.All) ) self.tableMetadata.resizeColumnsToContents() def MetaTimeUpdate(self): self.metaRows["time"].setText( self.m.time ) self.metaRows["left"].setText( self.m.left ) self.metaRows["complete"].setText( str(self.m.complete) ) if self.m.complete == self.m.All: self.metaRows["progressBar"].setValue(100) self.tableMetadata.resizeColumnsToContents() def MetaFileSizeUpdate(self): size = os.stat(os.path.abspath(self.m.filename)).st_size # get size of the file in bytes l_size = list(str(size)) for i in range(len(l_size)-3, 0, -3): # insert space in each 3rd position from the end l_size.insert(i, " ") # 12345678 -> 12 345 678 self.metaRows["labelSize"].setText("".join(l_size) + " байт" )