def process_packet(self, sender, packet): host, port = sender.getpeername() song_info = packet.get_header() packet_id = packet.get_header_field('packet_id') peer_id = self.network.get_pid_by_ip(host, port) if not packet_id: debug('LookupHandler.process_packet(): no packet_id') return if not packet_id in self.__recent_lookups: self.__recent_lookups.append(packet_id) clients = self.network.get_clients() for pid in filter(lambda x: x != peer_id, clients): self.network.send(pid, packet) if song_info: artist = song_info.get('artist') or '' title = song_info.get('title') or '' album = song_info.get('album') or '' search_results = self.db.lookup('title', 'artist', 'album', 'hash', title=('LIKE', title), artist=('LIKE', artist), album=('LIKE', album)) song_list = list() for entry in search_results: title, artist, album, _hash = entry song_list.append(dict(zip(['title', 'artist', 'album', 'hash'], [title, artist, album, _hash]))) self.network.send(peer_id, Packet(Constants.FOUND, {'results': song_list}))
def placerMonstre(etage, typ, pos, salle, prob=0.9, num=-1, boss=False): global index if random() <= prob: try: #Au cas où if boss: fichier = open('Entites/Boss/'+str(etage)+'.txt') else: if num == -1 : num = int(index[typ][etage][randint(0, len(index[typ][etage])-1)]) fichier = open('Entites/Monstres/'+str(typ)+'/'+str(num)+'.txt', mode='r', encoding='Utf-8') attributs = {} ligne = fichier.readline() while ligne != '' : ligne = ligne.split('=') attributs[ligne[0]] = ligne[1] ligne = fichier.readline() fichier.close() if typ == 0 : return CaC(num, attributs, pos, salle) elif typ == 1: return Distance(num, attributs, pos, salle) else: if etage == 0 : return RoiSlime(etage, attributs, pos, salle) debug('Boss remplacé') return Boss(etage, attributs, pos, salle) except Exception as e: debug('Monstre de type ' + str(typ) + ' et de num ' + str(num) + " a l'étage " + str(etage) + ' non généré :' + '\n' + str(type(e)) + ' : ' + str(e)) return 0 else : return 0
def receive_packet(self, _from, peer_id, data): peer_id, data = str(peer_id), str(data) debug('ReceiveController().receive_packet(): Binary from %s has been received' % peer_id) if _from == 0: self.__was_null = True self.__pid2ready[peer_id] = True i = 0 while i < len(self.__inbox) and self.__inbox[i][0] < _from: i += 1 self.__inbox.insert(i, (_from, data)) if len(self.__inbox) > 0: self.__last_packet = self.__inbox[len(self.__inbox) - 1][0] + 1 cons_to = self.__consistent_to() if cons_to > -1: inbox = map(lambda x: x[1], self.__inbox) final_data = "".join(inbox[:cons_to]) self.contentReceived.emit(final_data) pids, nums = self.get_packet_requests() self.nextPacketRequests.emit(self.__current_sid, pids, nums) self.__file.writeData(final_data) self.__file.flush() self.__inbox = self.__inbox[cons_to:]
def run(self): debug('FileLoader.run(): indexing started') os.stat_float_times(int(0)) for dirname in self.__pathes: for root, _, files in os.walk(dirname): valid_files = [f for f in files if os.path.splitext(f)[1] in self.__allowed_extensions] for valid_file in valid_files: full_path = os.path.join(root, valid_file) file_stat = os.stat(full_path) result_list = self.__db.lookup('last_modified', path=('=', full_path)) last_modified = int(result_list[0][0]) if len(result_list) > 0 else None if file_stat.st_mtime != last_modified: last_modified = file_stat.st_mtime sha_obj = sha.new() try: file = open(full_path, 'rb') data = file.read(8192) file.close() except IOError, e: debug("FileLoader.run(): Can't read file '%s'. %s" % (full_path, str(e))) else: id3r = id3reader.Reader(full_path) sha_obj.update(data) hash = sha_obj.hexdigest() title, album, artist = id3r.getValue('title'), id3r.getValue('album'), id3r.getValue('performer') self.__db.store(['title', 'artist', 'album', 'path', 'hash', 'last_modified'], [title, artist, album, full_path, hash, last_modified])
def __init__(self, etage): debug('Etage'+ str(etage) + '...') self.etage = etage #Numéro de l'étage self.grille = creerTableau(10, 10, False) self.generer() self.creerPortes() debug('Etage ' + str(self.etage) +' terminé')
def _parse_call(self, ttext): ''' Parse a call from the token text. ''' debug(ttext) # Compose the call self.compose_call(ttext)
def _infect(self): debug("INFECT"); next_bug = self._next_is_bug() if next_bug and next_bug.team.id != self.team.id: next_bug.team.dec() next_bug.change_team(self) self.team.inc()
def _infect(self): debug("INFECT") next_bug = self._next_is_bug() if next_bug and next_bug.team.id != self.team.id: next_bug.team.dec() next_bug.change_team(self) self.team.inc()
def __init__(self, pathes = []): super(FileLoader, self).__init__() debug('FileLoader: init started') self.__pathes = pathes[:] self.__allowed_extensions = ['.mp3'] self.__db = Database() self.start() debug('FileLoader: init complete')
def stop(self): #Arrête le moteur graphique debug('MoteurGraphique.stop()') for i in self.donjon[perso.Etage].grille[perso.Room[0]][perso.Room[1]].entites: i.actif = False self.projectile = None self.donjon = None self.continuer = False
def __init__(self, path, part_size, stream_id): self.__part_size = part_size dp = DataProcessor() fl = FileLoader() data = fl.load_file(path) self.__size = len(data) self.__chunks = dp.split_data(data, part_size) debug('FileStreamer.init(): len(self.__chunks) == %d' % len(self.__chunks)) self.__stream_id = stream_id
def stop(self): #Arrête le moteur graphique debug('MoteurGraphique.stop()') for i in self.donjon[perso.Etage].grille[perso.Room[0]][ perso.Room[1]].entites: i.actif = False self.projectile = None self.donjon = None self.continuer = False
def _move(self): debug("MOVE"); pos = self._one_ahead(); if Grid.get_pos(pos) == Grid.states.EMPTY: # Set where we were to empty Grid.set_pos(self._pos, Grid.states.EMPTY) # Set new position to filled self._pos = pos Grid.set_pos(pos, self)
def _turnright(self): debug("TURNRIGHT"); if self._direction == _facing.LEFT: self._direction = _facing.UP elif self._direction == _facing.RIGHT: self._direction = _facing.DOWN elif self._direction == _facing.UP: self._direction = _facing.RIGHT else: self._direction = _facing.LEFT
def genererDonjon(etageMax): """Demande le nombre d'étage maximum. Renvoie une liste d'étage""" global nombrePaterne nombrePaterne = len(listdir('Salles'))-2 #On enlève le dossier SallesBoss et "0.txt" debug('Nombre de paterne : ' + str(nombrePaterne)) listeEtage = [] for i in range(etageMax): listeEtage.append(Etage(i)) debug('Génération Terminé') return listeEtage
def _turnright(self): debug("TURNRIGHT") if self._direction == _facing.LEFT: self._direction = _facing.UP elif self._direction == _facing.RIGHT: self._direction = _facing.DOWN elif self._direction == _facing.UP: self._direction = _facing.RIGHT else: self._direction = _facing.LEFT
def _move(self): debug("MOVE") pos = self._one_ahead() if Grid.get_pos(pos) == Grid.states.EMPTY: # Set where we were to empty Grid.set_pos(self._pos, Grid.states.EMPTY) # Set new position to filled self._pos = pos Grid.set_pos(pos, self)
def _account_prop_changed(self, acc, pspec): """Called when an Account property is changed. Save the property to GConf. """ debug("prop changed in " + acc._email) if pspec.name == "password": self.keyring.save_password(acc.props.email, acc.props.password) else: # Can't use get_property because of libindicate bug (LP#499490) self.gconf.set_value( "{0}/accounts/{1}/{2}".format(self.path, acc.props.email, pspec.name), getattr(acc.props, pspec.name) )
def _parse_if(self, instream, tokenizer, ttext, ttype): ''' Parse an if statement from the instream. ''' # We expect a condition to follow condition, ttype = tokenizer.get_next_non_whitespace(instream) if ttype == Constants._types.CONDITION: debug(condition, False) else: exit("Expected a condition after IF") # THEN comes next ttext, ttype = tokenizer.get_next_non_whitespace(instream) debug(ttext) if ttype != Constants._types.KEYWORD or ttext != "THEN": exit("Expected THEN after IF condition") # Parse the conditional block ttext, ttype = tokenizer.get_next_non_whitespace(instream) stmt = StatementParse() ttext, ttype = stmt.parse_block(instream, tokenizer, ttext, ttype) # Check to see if this is an IF ELSE statement if ttype == Constants._types.KEYWORD and ttext == "ELSE": debug("ELSE", False) # Parse the conditional block ttext, ttype = tokenizer.get_next_non_whitespace(instream) elsestmt = StatementParse() ttext, ttype = elsestmt.parse_block(instream, tokenizer, ttext, ttype) # Compose the IF ELSE self.compose_if_else(Constants._conditions_text.index(condition), stmt, elsestmt) else: # Compose the IF self.compose_if(Constants._conditions_text.index(condition), stmt) # Returned token should be END if ttype == Constants._types.KEYWORD and ttext == "END": debug("END", False) else: exit("Expected END to complete the IF statement (But was '" + \ ttext + "')") # END followed by IF ttext, ttype = tokenizer.get_next_non_whitespace(instream) if ttype != Constants._types.KEYWORD or ttext != "IF": exit("Expected IF after END to complete the IF statement " + \ "(But was '" + ttext + "')") else: debug("IF")
def __init__(self): global perso, debugMode perso = __main__.perso pygame.init() pygame.key.set_repeat(30, 60) #Défini le temps entre deux évènements debug('MoteurGraphique.__init__') self.fenetre = pygame.display.set_mode( (784, 320)) #Défini la taille de la fenêtre pygame.display.set_caption("Donjons&Python") self.texture = __main__.texturePack self.projectile = [] #Liste de projectiles self.iPerso = [] #Images du personnage self.mPos = [0, 0] self.marche = 0 self.cpt = 0 self.t1 = pygame.time.get_ticks() self.posEpee = [0, 0] for i in range(4): #Chargement de la texture du personnage iMPerso = [] for j in range(3): iMPerso.append( chargerSprite(self.texture, "Personnage/" + perso.type, str(i) + str(j))) self.iPerso.append(iMPerso) self.donjon = GenerationDonjon.genererDonjon( __main__.nombreEtage) #Chargement du contenu du donjon chargerTextures(self.texture) #Chargement des textures pygame.draw.rect(self.fenetre, [0, 0, 0], [0, 0, 784, 320], 0) #Affiche les contrôles font = pygame.font.SysFont('constantia', 28) text = font.render("Se déplacer", 1, (255, 255, 255)) text1 = font.render("Ctrl: Attaquer au corps à corps", 1, (255, 255, 255)) text2 = font.render("Alt: Faire une attaque spéciale", 1, (255, 255, 255)) self.fenetre.blit(text, (120, 30)) self.fenetre.blit(text1, (30, 130)) self.fenetre.blit(text2, (30, 230)) self.fenetre.blit(image[4], (10, 10)) pygame.display.flip() while pygame.event.wait( ).type != pygame.locals.KEYDOWN: #On attend que le personnage appui sur une touche pour reprendre le programme None afficherCarte(self.donjon[perso.Etage]) self.epee = image[3] self.creerPiece() self.continuer = True self.jauges = []
def store(self, fields, values): if len(fields) != len(values): debug('Database.store(): len(fields) != len(values) so request cannot be made') return for field in fields: if not field in self.__fields: debug('Database.store(): wrong fields in INSERT request') return sql = "INSERT INTO music (" + ', '.join(fields) + ") VALUES (" + ', '.join(['?'] * len(values)) + ')' with self.__mutex: cursor = self.__db_conn.cursor() cursor.execute(sql, tuple(values)) self.__db_conn.commit() cursor.close()
def connect(self, host, port): client_sockets = filter(lambda s: id(s) != id(self.__sock), self.__sock2sockinfo.keys()) sock = filter(lambda s: (host, port) == s.getpeername(), client_sockets) if not sock: sock = socket.socket() sock.setblocking(0) try: sock.connect((host, port)) finally: debug('Network.connect(): Creating client socket.') self.__create_client_socket(sock) return sock else: return sock
def _setup_accounts(self): for acc in self.conf.get_accounts(): debug('Account: {0}, enabled: {1}'.format(acc.props.email, acc.props.enabled)) acc.connect('new-mail', self.notify_mail) acc.connect('auth-error', self.notify_error) acc.connect('notify::enabled', self._account_enabled_cb) acc.connect('user-display', self._account_clicked) if not acc.props.enabled: continue acc.show() def start_check(): acc.start_check() acc.check_mail() return False gobject.timeout_add_seconds(self._initial_check, start_check)
def ASK_for_listpath(self, choice): """ choice can be "rmcomb","rmtests" or passwords """ if choice == 'wgen-rmcomb': message = TEXT_ASK_FOR_RMCOMB_LIST elif choice == 'wgen-rmtests': message = TEXT_ASK_FOR_RMTEST_LIST elif choice == 'wgen-main': message = TEXT_ASK_FOR_PASS_LIST else: debug('WRONG choice (#200): {}'.format(choice)) return False listpath = PATHS.current_dir + '/' + choice if not os.path.exists(listpath) or not os.path.isfile( listpath) or os.stat(listpath)[6] == 0: self.UPDATE_programs_header() self.TUI.insstr(6, 0, message, curses.color_pair(2)) self.TUI.insstr(15, 0, BUTTON__WRITE_RETURN_TO_GO_THE_MENU, curses.color_pair(3)) self.TUI.refresh() self.ALLOW_user_input() listpath = self.TUI.getstr( 12, 1, curses.color_pair(2)).decode('utf-8').strip() if listpath == 'return': self.ALLOW_keyboard_movement() return False while not os.path.exists(listpath) or not os.path.isfile( listpath) or os.stat(listpath)[6] == 0: self.UPDATE_programs_header() self.TUI.insstr(6, 0, TEXT_ASK_FOR_FILE_AGAIN, curses.color_pair(2)) self.TUI.insstr(15, 0, BUTTON__WRITE_RETURN_TO_GO_THE_MENU, curses.color_pair(3)) self.TUI.refresh() listpath = self.TUI.getstr( 12, 1, curses.color_pair(2)).decode('utf-8').strip() if listpath == 'return': listpath = False break self.ALLOW_keyboard_movement() return listpath
def parse(self, instream, tokenizer, ttext, ttype): ''' Parses text from the in stream and returns the next token ''' if ttype == Constants._types.KEYWORD and ttext == "IF": debug("IF", False) self._parse_if(instream, tokenizer, ttext, ttype) elif ttype == Constants._types.KEYWORD and ttext == "WHILE": debug("WHILE", False) self._parse_while(instream, tokenizer, ttext, ttype) elif ttype == Constants._types.IDENTIFIER: self._parse_call(ttext) else: # Not an expected keyword that starts a statement exit("Found " + ttext + ", expected keyword") # Get the next token to return return tokenizer.get_next_non_whitespace(instream)
def __init__(self): global perso, debugMode perso = __main__.perso pygame.init() pygame.key.set_repeat(30, 60) #Défini le temps entre deux évènements debug('MoteurGraphique.__init__') self.fenetre = pygame.display.set_mode((784,320)) #Défini la taille de la fenêtre pygame.display.set_caption("Donjons&Python") self.texture = __main__.texturePack self.projectile = []#Liste de projectiles self.iPerso = []#Images du personnage self.mPos = [0,0] self.marche = 0 self.cpt = 0 self.t1 = pygame.time.get_ticks() self.posEpee = [0,0] for i in range(4): #Chargement de la texture du personnage iMPerso = [] for j in range(3): iMPerso.append(chargerSprite(self.texture, "Personnage/"+perso.type, str(i)+str(j))) self.iPerso.append(iMPerso) self.donjon = GenerationDonjon.genererDonjon(__main__.nombreEtage) #Chargement du contenu du donjon chargerTextures(self.texture) #Chargement des textures pygame.draw.rect(self.fenetre, [0, 0, 0], [0, 0, 784, 320], 0) #Affiche les contrôles font = pygame.font.SysFont('constantia', 28) text = font.render("Se déplacer", 1, (255,255,255)) text1 = font.render("Ctrl: Attaquer au corps à corps", 1, (255,255,255)) text2 = font.render("Alt: Faire une attaque spéciale", 1, (255,255,255)) self.fenetre.blit(text,(120, 30)) self.fenetre.blit(text1,(30, 130)) self.fenetre.blit(text2,(30, 230)) self.fenetre.blit(image[4], (10, 10)) pygame.display.flip() while pygame.event.wait().type != pygame.locals.KEYDOWN: #On attend que le personnage appui sur une touche pour reprendre le programme None afficherCarte(self.donjon[perso.Etage]) self.epee = image[3] self.creerPiece() self.continuer = True self.jauges = []
def lookup(self, *fields, **values): '''fields list of fields that should be passed into callback as result. values dict. key - name of table field, value - tuple of comparasion sign and value of corresponding field. Forms sql requst from parameters and performs it. ''' for field in fields: if not field in self.__fields: # checks if field is exists in table debug('Database.lookup(): wrong field in SELECT request: %s' % field) return not_empty = dict(filter(lambda x: x[1][1] != '', values.items())) # remove empty values parameters = not_empty.keys() signs, values = self.__unzip(not_empty.values()) sql = ("SELECT " + ', '.join(fields) + " FROM music WHERE " + ' AND '.join(["(%s %s ?)" % (f, v) for (f, v) in zip(parameters, signs)])) with self.__mutex: cursor = self.__db_conn.cursor() cursor.execute(sql, tuple(values)) result = list(cursor) cursor.close() return result
def selectionner(self): global savePath, root if True: savePath = 'Saves/Player' + str( int(self.box.curselection()[0]) + 1) + '.txt' self.root.destroy() if self.charger: Sauvegarde.charger(savePath) else: self.warner = Tk() Label(self.warner, text='Êtes vous sûr ? La sauvegarde sera ecrasée !', bg='Red').pack() Button(self.warner, text='Ecraser la sauvegarde', command=self.warner.quit).pack(fill=X) Button(self.warner, text='Annuler', command=self.annuler).pack(fill=X) Fonctions.centrer(self.warner, 73, 222) self.warner.mainloop() self.warner.destroy() root.destroy() debug("Step1") Menu.openMenu()
def placerMonstre(etage, typ, pos, salle, prob=0.9, num=-1, boss=False): global index if random() <= prob: try: #Au cas où if boss: fichier = open('Entites/Boss/' + str(etage) + '.txt') else: if num == -1: num = int(index[typ][etage][randint( 0, len(index[typ][etage]) - 1)]) fichier = open('Entites/Monstres/' + str(typ) + '/' + str(num) + '.txt', mode='r', encoding='Utf-8') attributs = {} ligne = fichier.readline() while ligne != '': ligne = ligne.split('=') attributs[ligne[0]] = ligne[1] ligne = fichier.readline() fichier.close() if typ == 0: return CaC(num, attributs, pos, salle) elif typ == 1: return Distance(num, attributs, pos, salle) else: if etage == 0: return RoiSlime(etage, attributs, pos, salle) debug('Boss remplacé') return Boss(etage, attributs, pos, salle) except Exception as e: debug('Monstre de type ' + str(typ) + ' et de num ' + str(num) + " a l'étage " + str(etage) + ' non généré :' + '\n' + str(type(e)) + ' : ' + str(e)) return 0 else: return 0
def _parse_while(self, instream, tokenizer, ttext, ttype): ''' Parse a while statement from the instream. ''' # We expect a condition to follow condition, ttype = tokenizer.get_next_non_whitespace(instream) if ttype == Constants._types.CONDITION: debug(condition, False) else: exit("Expected a condition after WHILE") # DO comes next ttext, ttype = tokenizer.get_next_non_whitespace(instream) debug(ttext) if ttype != Constants._types.KEYWORD or ttext != "DO": exit("Expected DO after WHILE condition") # Parse the conditional block ttext, ttype = tokenizer.get_next_non_whitespace(instream) stmt = StatementParse() ttext, ttype = stmt.parse_block(instream, tokenizer, ttext, ttype) # Returned token should be END if ttype != Constants._types.KEYWORD or ttext != "END": exit("Expected END to complete the WHILE statement (But was '" + \ ttext + "')") else: debug("END", False) # END is followed by WHILE ttext, ttype = tokenizer.get_next_non_whitespace(instream) if ttype != Constants._types.KEYWORD or ttext != "WHILE": exit("Expected WHILE after END to complete the WHILE statement" + \ " (But was '" + ttext + "')") else: debug("WHILE") # Compose the IF self.compose_while(Constants._conditions_text.index(condition), stmt)
def process_packet(self, sender, packet): host, port = sender.getpeername() peer_id = packet.get_header_field('peer_id') debug('HandshakeHandler.process_packet(): peer_id is %s' % peer_id) if peer_id: self.network.register_pid(peer_id, host, port) if packet.get_header_field('type') == Constants.HANDSHAKE: known_clients = self.network.get_clients_ips(peer_id) self.network.send(peer_id, Packet(Constants.HANDSHAKE_ACCEPT, {'peer_id': str(self.network.get_host_pid()), 'known_peers': known_clients})) debug('HandshakeHandler.packet_received(): Handshake complete.') elif packet.get_header_field('type') == Constants.HANDSHAKE_ACCEPT: to_connect = packet.get_header_field('known_peers') #if to_connect: #for debug('HandshakeHandler.packet_received(): Handshake Accept complete.')
def __create_db(self): debug('Database: init started') self.__db_file = 'media_db' if not os.path.exists(self.__db_file): self.__db_conn = sqlite3.connect(self.__db_file, check_same_thread=False) cursor = self.__db_conn.cursor() cursor.execute('''CREATE TABLE IF NOT EXISTS music (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, artist TEXT, album TEXT, path TEXT, hash TEXT, last_modified INT)''') self.__db_conn.commit() debug('Database.__init__(): table "music" has been created') cursor.close() else: self.__db_conn = sqlite3.connect(self.__db_file, check_same_thread=False) debug('Database: init complete')
def process_packet(self, sender, packet): _type = packet.get_header_field('type') host, port = sender.getpeername() peer_id = self.network.get_pid_by_ip(host, port) if _type == Constants.REQUEST_STREAM: debug('StreamHandler.packet_received() (REQUEST_STREAM): %s' % packet.get_binary()) file_hash = packet.get_header_field('hash') chunk_size = packet.get_header_field('chunk_size') stream_id = packet.get_header_field('packet_id') if (file_hash is not None) and chunk_size > 0: path = self.db.lookup('path', hash=('=', file_hash)) if path: self.__pid2stream[peer_id] = FileStreamer(path[0][0], chunk_size, stream_id) size = self.__pid2stream[peer_id].get_size() self.network.send(peer_id, Packet(Constants.READY_TO_STREAM, {'stream_id': stream_id, 'size': size})) else: debug("Peer.packet_received() (REQUEST_STREAM): No 'hash' or 'chunk_size' field was found in packet or 'chunk_size' is less or equal to 0") elif _type == Constants.REQUEST_PART: debug('StreaHandler.packet_received() (REQUEST_PART): %s' % packet.get_header()) _from = packet.get_header_field('from') stream_id = packet.get_header_field('stream_id') if (_from is not None): chunk = self.__pid2stream[peer_id].get_chunk(_from) if chunk: self.network.send(peer_id, Packet(Constants.CONTENT, {'from': _from, 'stream_id': stream_id}, chunk)) elif _type == Constants.READY_TO_STREAM: stream_id = packet.get_header_field('stream_id') file_size = packet.get_header_field('size') self.streamCreated.emit(stream_id, peer_id, file_size) elif _type == Constants.CONTENT: stream_id = packet.get_header_field('stream_id') c_len = packet.get_header_field('content_len') _from = packet.get_header_field('from') self.packetReceived.emit(_from, peer_id, QByteArray(packet.get_content()))
def run(self): pygame.draw.rect(self.fenetre, [0, 0, 0], [0, 0, 621, 32], 0) self.fenetre.blit(self.iPerso[perso.dir][0], (perso.pos[0]*32+32, perso.pos[1]*32+64)) self.jauges.append(Jauge(self.fenetre, [255, 0, 0], 1, " ", [206, 20], [0,0])) self.majOr(perso.OR) if perso.type == 'Magicien': self.jauges.append(Jauge(self.fenetre, [0, 0, 255], 2, " ", [206, 20], [240,0])) self.jauges[1].majJauge(perso.mana, perso.manaMax) self.jauges[0].majJauge(perso.pv, perso.pvMax) debug('MoteurGraphique.run()') Audio.stageMusic(perso.Etage) self.startMob() #Initialise les monstres self.afficherPiece() while(self.continuer): for event in pygame.event.get(): #On propose au joueur d'agir en appuyant sur une touche if event.type == KEYDOWN: if event.key == K_RIGHT: self.tryBougerPerso(1,0,1) elif event.key == K_LEFT: self.tryBougerPerso(-1,0,3) elif event.key == K_UP: self.tryBougerPerso(0,-1,0) elif event.key == K_DOWN: self.tryBougerPerso(0,1,2) elif event.key == K_F6 and debugMode: perso.mourir() elif event.key == K_F1 and debugMode: for i in self.donjon[perso.Etage].grille[perso.Room[0]][perso.Room[1]].entites: i.perdrePv(100000) elif event.key == K_F2 and debugMode: perso.perdrePv(5) elif event.key == K_F3 and debugMode: perso.gagnerPv(5) elif event.key == K_F7 and debugMode: if len(self.projectile) < 1: self.projectile.append(Projectile(1, [perso.pos[0]+posi(perso.dir, 0), perso.pos[1]+posi(perso.dir, 1)], perso.dir, 100, 10)) self.projectile[len(self.projectile)-1].start() elif event.key == K_LCTRL: pygame.event.set_blocked(pygame.KEYDOWN) self.attaquer() pygame.event.set_allowed(pygame.KEYDOWN) elif event.key == K_LALT: pygame.event.set_blocked(pygame.KEYDOWN) perso.special() self.wait(300) pygame.event.set_allowed(pygame.KEYDOWN) elif event.key == K_F10: self.mort(perso) elif event.type == QUIT: self.continuer = 0 for i in self.projectile: #Supprime les projectiles inactifs if not i.ok: self.projectile.remove(i) self.afficherPiece() #Affiche la pièce sleep(6) pygame.display.quit() #pygame.quit() print('moteur stop')
def exit_main(self): """ Completely exit the program. """ self.incremental_is_working = False curses.nocbreak() self.TUI.keypad(0) curses.echo() curses.endwin() exit() if __name__ == '__main__': try: sys_encoding = sys.getdefaultencoding().lower() launch = True if sys_encoding != 'utf-8': answer = input(ENCODING.format(sys_encoding)) if not 'y' in answer.lower(): launch = False if launch: main = Main() main.SCAN_main() except Exception as e: debug(traceback.format_exc())
def run(self): pygame.draw.rect(self.fenetre, [0, 0, 0], [0, 0, 621, 32], 0) self.fenetre.blit(self.iPerso[perso.dir][0], (perso.pos[0] * 32 + 32, perso.pos[1] * 32 + 64)) self.jauges.append( Jauge(self.fenetre, [255, 0, 0], 1, " ", [206, 20], [0, 0])) self.majOr(perso.OR) if perso.type == 'Magicien': self.jauges.append( Jauge(self.fenetre, [0, 0, 255], 2, " ", [206, 20], [240, 0])) self.jauges[1].majJauge(perso.mana, perso.manaMax) self.jauges[0].majJauge(perso.pv, perso.pvMax) debug('MoteurGraphique.run()') Audio.stageMusic(perso.Etage) self.startMob() #Initialise les monstres self.afficherPiece() while (self.continuer): for event in pygame.event.get( ): #On propose au joueur d'agir en appuyant sur une touche if event.type == KEYDOWN: if event.key == K_RIGHT: self.tryBougerPerso(1, 0, 1) elif event.key == K_LEFT: self.tryBougerPerso(-1, 0, 3) elif event.key == K_UP: self.tryBougerPerso(0, -1, 0) elif event.key == K_DOWN: self.tryBougerPerso(0, 1, 2) elif event.key == K_F6 and debugMode: perso.mourir() elif event.key == K_F1 and debugMode: for i in self.donjon[perso.Etage].grille[ perso.Room[0]][perso.Room[1]].entites: i.perdrePv(100000) elif event.key == K_F2 and debugMode: perso.perdrePv(5) elif event.key == K_F3 and debugMode: perso.gagnerPv(5) elif event.key == K_F7 and debugMode: if len(self.projectile) < 1: self.projectile.append( Projectile(1, [ perso.pos[0] + posi(perso.dir, 0), perso.pos[1] + posi(perso.dir, 1) ], perso.dir, 100, 10)) self.projectile[len(self.projectile) - 1].start() elif event.key == K_LCTRL: pygame.event.set_blocked(pygame.KEYDOWN) self.attaquer() pygame.event.set_allowed(pygame.KEYDOWN) elif event.key == K_LALT: pygame.event.set_blocked(pygame.KEYDOWN) perso.special() self.wait(300) pygame.event.set_allowed(pygame.KEYDOWN) elif event.key == K_F10: self.mort(perso) elif event.type == QUIT: self.continuer = 0 for i in self.projectile: #Supprime les projectiles inactifs if not i.ok: self.projectile.remove(i) self.afficherPiece() #Affiche la pièce sleep(6) pygame.display.quit() #pygame.quit() print('moteur stop')
def parse(self, instream, tokenizer): ''' Parse the text from the instream into a Program object ''' # Expect PROGRAM ttext, ttype = tokenizer.get_next_non_whitespace(instream) if ttype == Constants._types.KEYWORD and ttext == "PROGRAM": debug("PROGRAM", False) else: exit("Expected PROGRAM to begin the program (But was:" + \ ttext + ")") # Expect program name progname, ttype = tokenizer.get_next_non_whitespace(instream) if ttype == Constants._types.IDENTIFIER: debug(progname, False) else: exit("Expected identifier program name after PROGRAM (But was:" + \ progname + ")") self.set_name(progname) # Expect IS ttext, ttype = tokenizer.get_next_non_whitespace(instream) if ttype == Constants._types.KEYWORD and ttext == "IS": debug("IS") else: exit("Expected IS after program name (But was:" + ttext + ")") ttext, ttype = tokenizer.get_next_non_whitespace(instream) # Loop as long as we continue seeing instructions while (ttype == Constants._types.KEYWORD and ttext == "INSTRUCTION"): debug(ttext, False) # Expect instruction name name, ttype = tokenizer.get_next_non_whitespace(instream) if ttype == Constants._types.IDENTIFIER: debug(name, False) else: exit("Expected identifier instruction name after " + \ "INSTRUCTION (But was:" + name + ")") # Expect IS ttext, ttype = tokenizer.get_next_non_whitespace(instream) if ttype == Constants._types.KEYWORD and ttext == "IS": debug(ttext) else: exit("Expected IS after instruction name (But was" + \ ttext + ")") # Parse the statement block making up the instruction ttext, ttype = tokenizer.get_next_non_whitespace(instream) instr = StatementParse() ttext, ttype = instr.parse_block(instream, tokenizer, ttext, ttype) self.add_to_context(name, instr) # Verify we had an END to the instruction if ttype == Constants._types.KEYWORD and ttext == "END": debug("END", False) else: exit("Expected END to complete the instruction (But was:" + \ ttext + ")") # Verify matching instruction name after END ttext, ttype = tokenizer.get_next_non_whitespace(instream) if ttype == Constants._types.IDENTIFIER and ttext == name: debug(ttext) else: exit("Expected matching instruction name ('" + name + \ "') after END (But was:" + ttext + ")") ttext, ttype = tokenizer.get_next_non_whitespace(instream) # Next token should be BEGIN if ttype == Constants._types.KEYWORD and ttext == "BEGIN": debug(ttext) else: exit("Expected BEGIN to initialize the beginning of the " + \ "program (But was:" + ttext + ")") # Parse the statement block making up the body ttext, ttype = tokenizer.get_next_non_whitespace(instream) instr = StatementParse() ttext, ttype = instr.parse_block(instream, tokenizer, ttext, ttype) self.set_body(instr) # Verify we had an END to the body if ttype == Constants._types.KEYWORD and ttext == "END": debug(ttext, False) else: exit("Expected END to complete the body (But was:" + ttext + ")") # Verify matching program name after END ttext, ttype = tokenizer.get_next_non_whitespace(instream) if ttype == Constants._types.IDENTIFIER and ttext == progname: debug(ttext) else: exit("Expected matching instruction name ('" + progname + \ "') after END (But was:" + ttext + ")")
def append_send_queue(self, packet): debug('SocketInfo.append_send_queue(): %s' % str(packet)) self.__out.append(packet)
def check_mail(self): """Check for new mail on the account if it is enabled. If new mail is found a `new-mail` signal is emitted. If an authentication error is encountered, the `auth-error` signal is emitted. """ if not self.props.enabled: debug('Account not enabled') return False debug('Check for new mail on {0}'.format(self._email)) atom = None try: atom = feedparser.parse(urllib2.urlopen(self._req).read()) except urllib2.HTTPError as e: if e.code == 401: self.props.enabled = False self.hide() self.emit('auth-error') debug('Auth error') return False except urllib2.URLError as e: # Probably not connect to the internet. Try again later. debug('urlerror') return True new_mails = [] for email in atom['entries']: utctime = calendar.timegm(time.strptime(email['issued'], '%Y-%m-%dT%H:%M:%SZ')) if not self._last_check or utctime > self._last_check: new_mails.append((email['author_detail']['name'], email['title'], email['summary'])) debug('{0} new mails'.format(len(new_mails))) self._last_check = time.time() count = atom['feed']['fullcount'] self.set_property('count', count) if len(new_mails) > 0: if not self._first_check: self.alert() else: self._first_check = False self.show() self.emit('new-mail', new_mails) elif int(count) > 0: self.show() else: self.hide() self.link = atom['feed']['links'][0]['href'] debug('Checking again in {0} minutes'.format(self._interval)) return True
def _account_enabled_cb(self, acc, prop): debug('account {0} has been {1}'.format(acc._email, acc._enabled and 'enabled' or 'disabled')) if acc.props.enabled: acc.start_check() else: acc.stop_check()
def execute(self): # Jump conditions don't increment PC if self._code[self._pc] >= Constants.codes.JUMP: if self._code[self._pc] == Constants.codes.JUMP: self._pc = self._code[self._pc + 1] debug("JUMP TO " + str(self._pc)) elif self._code[self._pc] == Constants.codes.JUMP_TO_INSTR: # Push PC on to stack (after the jump and jump addr) self._stack.append(self._pc + 2) self._pc = self._code[self._pc + 1] debug("JUMP TO INSTR " + str(self._pc)) elif self._code[self._pc] == Constants.codes.RETURN: # pop off PC from the stack and return to it self._pc = self._stack.pop() debug("RETURN"); else: # We must evaluate the conditional debug("COND " + str(self._code[self._pc]) + " IS " + ("TRUE" if self._check_cond(self._code[self._pc]) else "FALSE")) if self._check_cond(self._code[self._pc]): self._pc = self._code[self._pc + 1] debug(self._code[self._pc]) else: self._pc += 2; debug(self._code[self._pc]) else: if self._code[self._pc] == Constants.codes.MOVE: self._move() elif self._code[self._pc] == Constants.codes.INFECT: self._infect() elif self._code[self._pc] == Constants.codes.TURNLEFT: self._turnleft() elif self._code[self._pc] == Constants.codes.TURNRIGHT: self._turnright() elif self._code[self._pc] == Constants.codes.SKIP: debug("SKIP"); else: # HALT return False self._pc += 1 return True
def execute(self): # Jump conditions don't increment PC if self._code[self._pc] >= Constants.codes.JUMP: if self._code[self._pc] == Constants.codes.JUMP: self._pc = self._code[self._pc + 1] debug("JUMP TO " + str(self._pc)) elif self._code[self._pc] == Constants.codes.JUMP_TO_INSTR: # Push PC on to stack (after the jump and jump addr) self._stack.append(self._pc + 2) self._pc = self._code[self._pc + 1] debug("JUMP TO INSTR " + str(self._pc)) elif self._code[self._pc] == Constants.codes.RETURN: # pop off PC from the stack and return to it self._pc = self._stack.pop() debug("RETURN") else: # We must evaluate the conditional debug("COND " + str(self._code[self._pc]) + " IS " + ("TRUE" if self._check_cond(self._code[self._pc] ) else "FALSE")) if self._check_cond(self._code[self._pc]): self._pc = self._code[self._pc + 1] debug(self._code[self._pc]) else: self._pc += 2 debug(self._code[self._pc]) else: if self._code[self._pc] == Constants.codes.MOVE: self._move() elif self._code[self._pc] == Constants.codes.INFECT: self._infect() elif self._code[self._pc] == Constants.codes.TURNLEFT: self._turnleft() elif self._code[self._pc] == Constants.codes.TURNRIGHT: self._turnright() elif self._code[self._pc] == Constants.codes.SKIP: debug("SKIP") else: # HALT return False self._pc += 1 return True
def INCREMENTAL_mode(self): Loops.Queue = [] self.incremental_is_working = True self.file_name = None self.count_dict = {} self.process_ended = 0 self.max_id = (0, 0) self.password = None self.advancement_queque = [] self.graphical_dots = '' self.average_queue = AverageQueue() # the program will increment the port in case it be already used port = 6434 # the password may be good idea for preventing the TUI having inputs # from other process self.tui_password = randint(100000000, 999999999) number_of_process = self.configuration.get_number_of_process() if os.path.exists(PATHS.stop_loop_file): os.remove(PATHS.stop_loop_file) """ Get the paths that will be used to generate the lists """ passwords_path = self.ASK_for_listpath('wgen-main') if not passwords_path: return self.list_name = os.path.basename(passwords_path) if len(self.list_name) > 9: self.list_name = self.list_name[:7] + '..' self.cracking_text = TEXT_GENERATING_WITH.format(self.list_name) if self.configuration.get_remove_tests(): rmtests_path = self.ASK_for_listpath('wgen-rmtests') if rmtests_path == False: return else: rmtests_path = None remove_tests_tuple = None if self.configuration.get_remove_combinations(): rmcombs_path = self.ASK_for_listpath('wgen-rmcomb') if rmcombs_path == False: return else: rmcombs_path = None remove_combinations_re = None """ Add the binding to cancel the incremental mode by using backspace """ quit_thread = Thread(target=self.THREAD_quit_on_scanning) quit_thread.start() """ Create the lists for the brute force attack """ self.passwords_tuple, self.number_of_words = self.CREATE_words( passwords_path, 'passwords', 'tuple') if rmtests_path != None: remove_tests_tuple, number_of_rmtst = self.CREATE_words( rmtests_path, 'remove_tests', 'tuple') if not remove_tests_tuple: return if rmcombs_path != None: remove_combinations_re, number_of_rmcomb = self.CREATE_words( rmcombs_path, 'remove_combinations', 're') if not remove_combinations_re: return if not self.incremental_is_working: return """ Calculate the total_of_combinations """ self.total_of_combinations = 0 for i in range(self.configuration.get_password_length_start(), self.configuration.get_password_length_end() + 1): self.total_of_combinations += self.number_of_words**i self.combinations_text = TEXT_POSSIBLE_COMBINATIONS.format( format_number_for_tui(self.total_of_combinations)) self.UPDATE_cracking_header() self.TUI.insstr(9, 2, TEXT_INCREMENTAL_IS_BEING_INITIALIZED, curses.color_pair(2)) self.TUI.refresh() try: if os.path.exists(PATHS.output_folder): shutil.rmtree(PATHS.output_folder) os.makedirs(PATHS.output_folder) except Exception as e: debug(traceback.format_exc()) """ Start the listening socket, and increment the port if necessary """ self.serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) while True: try: self.serversocket.bind(('localhost', port)) break except: port += 1 self.serversocket.listen( number_of_process + 1) # max number of connections, +1 doesn't hurts Thread(target=self.SOCKET_listener).start() #debug('7zserver at'+str(port)) """ Initialize the Loops """ for stage, combination_number in enumerate( range(self.configuration.get_password_length_start(), self.configuration.get_password_length_end() + 1)): if not self.incremental_is_working: return elif combination_number == 2: Loops.Loop(combination_number, stage, 0, self.list_name, self.configuration, None, self.passwords_tuple, remove_combinations_re, remove_tests_tuple, self.tui_password, port) self.count_dict['00002:00000'] = 0 else: for substage, word in enumerate(self.passwords_tuple): Loops.Loop(combination_number, stage, substage, self.list_name, self.configuration, word, self.passwords_tuple, remove_combinations_re, remove_tests_tuple, self.tui_password, port) self.count_dict[format_socket_number(stage) + format_socket_number(substage)] = 0 del remove_combinations_re del remove_tests_tuple """ Check if all the loops succesfully pinged the server """ for loop in Loops.Queue: if not loop: self.UPDATE_programs_header() self.TUI.insstr(6, 2, TEXT_PYCORE_PROBLEM, curses.color_pair(2)) self.TUI.insstr(15, 2, BUTTON_PRESS_ANY_KEY_TO_RETURN_TO_THE_MENU, curses.color_pair(3)) self.TUI.refresh() choice = self.TUI.getch() return #debug('\nLoops initialization ended.\n') self.UPDATE_cracking_header() self.TUI.insstr(9, 2, TEXT_THE_STATISTICS_WILL_APPEAR, curses.color_pair(2)) self.TUI.insstr(15, 2, BUTTON_PRESS_BACKSPACE_TO_STOP, curses.color_pair(3)) self.TUI.refresh() self.passwords_tuple = None if self.incremental_is_working: self.start_time = time() for i in range(number_of_process): Thread(target=self.INCREMENTAL_start_next_process).start() while self.incremental_is_working: """ This part of the code used to be placed at the SOCKET_listener method method. in order to improve the speed of the SOCKET_listener, it is now just appending to a queue, and the processing is done here. """ _tui_password = str(self.tui_password) for item in self.advancement_queque: connection, address, buf = item self.advancement_queque.remove(item) if len(buf) > 0 and self.incremental_is_working: data = buf.decode('utf-8').split(':') #debug('7z received data: {}'.format(data)) if data[4] == _tui_password: command = data[0] stage = data[1] substage = data[2] count = data[3] # The commands are organized by "the most called" # if command == '150': """ Increment the count for the stats """ self.count_dict[stage + substage] = int(count) stage = int(stage) substage = int(substage) # The TUI is only updated by the TOP process if (stage == self.max_id[0] and substage >= self.max_id[1] ) or stage > self.max_id[0]: self.UPDATE_incremental_avancement( stage + self.configuration. get_password_length_start(), substage + 1) self.max_id = (stage, substage) elif command == '100': self.INCREMENTAL_start_next_process() elif command == '666': """ The password was found """ self.password = False self.incremental_is_working = False Loops.Queue = [] self.tui_password = None elif command == '200': """ Ping """ pass else: debug( 'Wrong command by: {}, command: {}'.format( address, ':'.join(data))) else: debug('Warning: wrong password by: {}\n data: {}'. format(address[0], ':'.join(data))) #debug('PASSWORD: {}, recived: {}'.format(_tui_password, data[-1:])) self.UPDATE_incremental_result() return
def UPDATE_incremental_avancement(self, string_level, string_stage): """ Update the TUI by displaying the current statistics. """ try: #debug('string_level: {}, string_stage: {}'.format(string_level, string_stage)) done = sum(self.count_dict.values()) self.average_queue.update_from_total(done) total_of_combinations = self.total_of_combinations self.UPDATE_cracking_header() if done <= 0 or total_of_combinations <= 0: self.TUI.insstr(9, 2, TEXT_THE_STATISTICS_WILL_APPEAR, curses.color_pair(2)) else: # Calculate the statistics # left = total_of_combinations - done racio = self.average_queue.get_average() if racio < 0: debug("Negative average") debug(self.average_queue.debug_data()) global_percent = round((done * 100) / total_of_combinations, 1) # Format the statistics # if racio < 99: formatted_racio = str(round(racio, 2)) else: formatted_racio = format_number_for_tui(racio) if string_level > 2: stages = self.number_of_words else: stages = 1 if global_percent > 100: time_string = "?" else: time_string = str(timedelta(seconds=left / racio)) # remove miliseconds if '.' in time_string: time_string = time_string.split('.', 1)[0] # Send the statistics # self.TUI.insstr( 9, 2, TEXT_TOTAL_DONE.format(format_number_for_tui(done), global_percent), curses.color_pair(2)) self.TUI.insstr( 10, 2, TEXT_COMBINING_AND_STAGE.format(string_level, string_stage, stages), curses.color_pair(2)) self.TUI.insstr(11, 2, TEXT_AVERAGE_OF.format(formatted_racio), curses.color_pair(2)) self.TUI.insstr( 12, 2, TEXT_ESTIMATING_X_TO_FINISH.format(time_string) + self.graphical_dots, curses.color_pair(2)) # Update the advancement dots # self.graphical_dots += '.' if self.graphical_dots == '....': self.graphical_dots = '' self.TUI.insstr(15, 2, BUTTON_PRESS_BACKSPACE_TO_STOP, curses.color_pair(3)) self.TUI.refresh() except Exception as e: debug(traceback.format_exc())
def CREATE_words(self, file_path, file_type, object_type='list'): """ This method will read an utf-8 text file and perform a series of tests in order to create a valid/optimized list/tuple/re of words for the incremental mode. The object can be "list", "tuple", "re" """ filter_type = self.configuration.get_clean_lists() file_name = os.path.basename(file_path) self.UPDATE_programs_header() self.TUI.insstr(7, 2, TEXT_THE_LIST_IS_BEING_IMPORTED.format(file_name), curses.color_pair(2)) self.TUI.refresh() if filter_type == 'none': with open(file_path, encoding='utf-8', mode='rt') as f: local_word_list = f.read() local_word_list = [ line.strip() for line in normalize('NFC', local_word_list).splitlines() ] length = len(local_word_list) added_words = length elif filter_type in ['normal', 'advanced']: # This is the normal filter, it removes the duplicated strings with open(file_path, encoding='utf-8', mode='rt') as f: lines = f.read() lines = list( filter( None, set_with_order( line.strip() for line in normalize('NFC', lines).splitlines()))) length = len(lines) if filter_type == 'normal': local_word_list = lines lines = None added_words = length elif filter_type == 'advanced': self.UPDATE_programs_header() self.TUI.insstr( 7, 2, TEXT_THE_LIST_IS_BEING_CHECKED.format(file_name), curses.color_pair(2)) self.TUI.insstr(8, 2, "[> ] 0%", curses.color_pair(2)) self.TUI.insstr(15, 2, BUTTON_PRESS_BACKSPACE_TO_STOP, curses.color_pair(3)) self.TUI.refresh() local_word_list = [] added_words, old_percent = 0, 0 try: for word_count, word in enumerate(lines): if not self.incremental_is_working: return False, False else: for local_word in local_word_list: if not self.incremental_is_working: return False, False elif local_word in word: alredy = True break if not already: local_word_list.append(word) added_words += 1 percent = int(round(word_count * 100 / length)) if percent > old_percent: old_percent = percent av_percent = int(round(percent * 0.2)) avancement = ("=" * av_percent) + ">" + ( " " * (20 - av_percent)) self.UPDATE_programs_header() self.TUI.insstr( 7, 2, TEXT_THE_LIST_IS_BEING_CHECKED.format( file_name), curses.color_pair(2)) self.TUI.insstr( 8, 2, "[" + avancement + "] " + str(percent) + "%", curses.color_pair(2)) self.TUI.insstr(15, 2, BUTTON_PRESS_BACKSPACE_TO_STOP, curses.color_pair(3)) self.TUI.refresh() except Exception as e: debug(traceback.format_exc()) return False, False if self.configuration.get_sort_lists(): self.UPDATE_programs_header() self.TUI.insstr(7, 2, TEXT_THE_LIST_IS_BEING_SORTED.format(file_name), curses.color_pair(2)) self.TUI.insstr(8, 2, "[> ] 0%", curses.color_pair(2)) self.TUI.insstr(15, 2, BUTTON_PRESS_BACKSPACE_TO_STOP, curses.color_pair(3)) self.TUI.refresh() if file_type == 'passwords': local_word_list.sort() else: sorted_password_list = sorted(self.passwords_tuple, key=len, reverse=True) comb_words_dict = {} old_percent = 0 for local_word_count, local_word in enumerate( sorted(local_word_list)): if not self.incremental_is_working: return False, False substrings_count = 0 testing_word = local_word for word in sorted_password_list: if not self.incremental_is_working: return False, False elif word in testing_word: occurence = testing_word.count(word) testing_word = testing_word.replace(word, '') substrings_count += occurence if testing_word == '': break if testing_word != '': substrings_count = 'x' # warn the user that it is not a combinations of words? if substrings_count in comb_words_dict: comb_words_dict[substrings_count].append(local_word) else: comb_words_dict[substrings_count] = [local_word] percent = int(round(local_word_count * 100 / added_words)) if percent > old_percent: old_percent = percent av_percent = int(round(percent * 0.2)) avancement = ("=" * av_percent) + ">" + (" " * (20 - av_percent)) self.UPDATE_programs_header() self.TUI.insstr( 7, 2, TEXT_THE_LIST_IS_BEING_SORTED.format(file_name), curses.color_pair(2)) self.TUI.insstr( 8, 2, "[" + avancement + "] " + str(percent) + "%", curses.color_pair(2)) self.TUI.insstr(15, 2, BUTTON_PRESS_BACKSPACE_TO_STOP, curses.color_pair(3)) self.TUI.refresh() local_word_list = [] for key in sorted(comb_words_dict.keys()): if not self.incremental_is_working: return False, False local_word_list += comb_words_dict[key] if self.configuration.get_write_lists(): try: with open(file_path + '-new', encoding='utf-8', mode='wt') as f: for word in local_word_list: f.write(word + '\n') except Exception as e: debug(traceback.format_exc()) return False, False if object_type == 're': return re.compile('|'.join(map(re.escape, local_word_list))), added_words elif object_type == 'tuple': return tuple(local_word_list), added_words elif object_type == 'list': return local_word_list, added_words else: debug( "Wrong object={} request on CREATE_WORDS".format(object_type)) return False, False