def calibrate(self): for dev in range(len(self.devices)): d = self.devices[dev] for a in range(d.get_numaxes()): v = d.get_axis(a) self.initial_axes[dev][a] = v Log.debug(f"{d.get_name()} Initial axes: {self.initial_axes[dev]}")
def main(): Log.debug("=== Running Dance Dance Sensei ===") if not os.path.isfile("config.toml"): Log.debug("Config not found, copying default config") shutil.copyfile("default_config.toml", "config.toml") config = toml.load("config.toml") if 'game' not in config: config['game'] = {} config['game']['default_game'] = games[0].code toml.dump(config, open("config.toml", "w")) if os.path.exists('sequence'): print("Sliently moving") print(os.path.expanduser("~\.dds")) ## Find game from config game_id = config['game']['default_game'] game = first(games, lambda x: x.code == game_id) state = GameState(game, config) window = GameWindow(state) pygame.init() ## Get window size width = config['display']['width'] height = config['display']['height'] screen = pygame.display.set_mode((width, height)) clock = pygame.time.Clock() def pygamethread(): try: while state.is_running: for event in pygame.event.get(): state.handle_event(event) window.handle_event(event) ## Drawing screen.fill(pygame.Color('black')) state.update() state.render(screen) ## End drawing pygame.display.update() clock.tick(60) except Exception: traceback.print_exc() pygame.quit() state.is_running = False window.quit() threading.Thread(None, pygamethread).start() window.mainloop()
def soundthread(): last_played = 0 try: while state.is_running: last_played += 1 if state.is_playing and state.use_metronome and last_played > 30: last_played = 0 beep.stop() beep.play(0) soundclock.tick(240) except Exception as e: Log.debug(traceback.format_exc())
def is_tf2_install(log: logger.Log, exe_location: str) -> bool: if not os.path.isfile(exe_location): log.debug(f"No TF2 installation found at {exe_location}") return False is_tf2: bool = False appid_path: str = os.path.join(os.path.dirname(exe_location), 'steam_appid.txt') if os.path.isfile(appid_path): with open(appid_path, 'rb') as appid_file: appid_read: bytes = appid_file.read() if appid_read.startswith(b'440\n'): is_tf2 = True else: log.debug(f"steam_appid.txt contains \"{appid_read}\" ") else: log.debug( f"steam_appid.txt doesn't exist (install folder: {os.listdir(os.path.dirname(exe_location))})" ) if is_tf2: log.debug(f"Found TF2 hl2.exe at {exe_location}") return True else: log.error(f"Found non-TF2 hl2.exe at {exe_location}") return False
def handle_input(self): if self.register_mode is None: self.previous_buttons = self.buttons self.buttons = self.input_manager.poll() else: if self.register_mode == "Movement": next_btn = self.input_manager.poll_full_motion(self.register_mode) else: next_btn = self.input_manager.poll_full(self.register_mode) if next_btn is not None: self.register_mode = None if next_btn[0] is not "INVALID": Log.debug(f"Writing new key binding {next_btn}") f = open(self.mode.mappings, "a") csv.writer(f).writerow(next_btn) f.close() else: Log.debug(f"Key binding invalid: {next_btn[1]}") self.reload_gamepad(self.mode.mappings)
def get_map_gamemode( log: logger.Log, map_filename: str) -> Union[Tuple[str, str, str, bool], list]: if map_filename == '': log.error("Map filename is blank") return map_filename, 'unknown', 'Unknown gamemode', False map_gamemodes: Dict[str, List[str]] = load_maps_db() if map_filename in map_gamemodes: map_data: list = map_gamemodes[map_filename] map_data.append(False) # add some formatting for maps with multiple gamemodes if map_filename in game_state.ambiguous_maps: if map_data[1] in modes_short: map_data[0] = f'{map_data[0]} ({modes_short[map_data[1]]})' else: map_data[0] = f'{map_data[0]} ({map_data[2]})' return map_data elif not map_gamemodes: log.error("maps.json failed to load") log.debug(f"Finding gamemode for custom map: {map_filename}") # determine based on common substrings for gamemode_substring in substrings: if gamemode_substring in map_filename: gamemode: str = substrings[gamemode_substring] gamemode_fancy: str = modes[gamemode] log.debug( f"Determined gamemode to be {(gamemode, gamemode_fancy)}) based on substring ({gamemode_substring}_)" ) return map_filename, gamemode, gamemode_fancy, True # determine based on the map prefix map_prefix: str = map_filename.split('_')[0] if map_prefix in prefixes and '_' in map_filename: gamemode = prefixes[map_prefix] gamemode_fancy = modes[gamemode] log.debug( f"Determined gamemode to be {(gamemode, gamemode_fancy)}) based on prefix ({map_prefix}_)" ) return map_filename, gamemode, gamemode_fancy, True log.debug( "Couldn't determine map gamemode from filename") # probably trading return map_filename, 'unknown', 'Unknown gamemode', True
def pygamethread(): try: while state.is_running: for event in pygame.event.get(): state.handle_event(event) window.handle_event(event) ## Drawing screen.fill(pygame.Color('black')) state.update() state.render(screen) ## End drawing pygame.display.update() clock.tick(60) except Exception as e: Log.debug(traceback.format_exc()) pygame.quit() state.is_running = False window.quit()
def detect_system_language(log: logger.Log): db: Dict[str, Union[bool, list, str]] = utils.access_db() if not db['has_asked_language']: language_codes: dict = { read_localization_files()[lang]['code']: lang for lang in langs[1:] } system_locale: str = locale.windows_locale[ ctypes.windll.kernel32.GetUserDefaultUILanguage()] system_language_code: str = system_locale.split('_')[0] is_brazilian_port: bool = system_locale == 'pt_BR' if system_language_code in language_codes or is_brazilian_port: system_language: str = language_codes[system_language_code] can_localize: bool = True else: if system_language_code != 'en': log.error(f"System locale {system_locale} is not localizable") can_localize = False if can_localize and settings.get('language') != system_language: log.info( f"System language ({system_locale}, {system_language}) != settings language ({settings.get('language')}), asking to change" ) db['has_asked_language'] = True utils.access_db(db) system_language_display: str = 'Português Brasileiro' if is_brazilian_port else system_language # this is intentionally not localized changed_language: str = messagebox.askquestion( f"TF2 Rich Presence {launcher.VERSION}", f"Change language to your system's default ({system_language_display})?" ) log.debug(f"Changed language: {changed_language}") if changed_language == 'yes': settings.change('language', system_language)
data = None try: req = urllib2.Request(url=requrl, data=param) res = urllib2.urlopen(url=req,timeout=to) data = res.read() except HTTPError, e: print "Error code: %d" % e.code logger.debug("Error code: %d" % e.code) except URLError, e: print "Error reason: %s" % e.reason logger.debug("Error reason: %s" % e.reason) finally: return data @staticmethod def get(requrl, param, to=5): param = urllib.urlencode(param) requrl = requrl + '?' + param data = None try: req = urllib2.Request(requrl) res = urllib2.urlopen(url=req,timeout=to) data = res.read() except urllib2.HTTPError, e: logger.debug("Error code: %d" % e.code) except urllib2.URLError, e: logger.debug("Error reason: %s" % e.reason) finally: return data
def __init__(self): pygame.joystick.init() self.mappings: List[Tuple[str, str, str, str]] = [] self.complete_mappings: bool = False self.devices = [ pygame.joystick.Joystick(x) for x in range(pygame.joystick.get_count()) ] self.initial_axes = [] Log.debug(f"{len(self.devices)} Devices detected") for d in self.devices: d.init() Log.debug(f"{d.get_name()}") Log.debug(f"\t{d.get_numbuttons()} Buttons") Log.debug(f"\t{d.get_numaxes()} Axes") Log.debug(f"\t{d.get_numhats()} Hats") Log.debug(f"\t{d.get_numballs()} Balls") axes = [] for a in range(d.get_numaxes()): axes.append(d.get_axis(a)) self.initial_axes.append(axes) self.fully_init = False
class Rutor(TorrentInterface): def __init__(self): self.log = Log(__name__) self.session = aiohttp.ClientSession() self._init_variables() def _init_logging(self): pass def _init_variables(self): self._rutor = dict() self._rutor['protocols'] = ['http', 'https'] self._rutor['host'] = ['rutor.is', 'rutor.info', '6tor.net'] self._rutor['search_string'] = '/search/' self._rutor['search_keyword'] = '/search/0/0/100/0/' self._rutor['search_words'] = '' async def fetch_url(self, url): try: async with self.session.get(url, allow_redirects=False) as resp: if resp.status != 200: self.log.info(f"Got code {resp.status} from {url}") await asyncio.sleep(2.0) return None return await resp.text() except client_exceptions.ClientConnectionError as e: self.log.info(e) await asyncio.sleep(2.0) return None def _generate_links(self, search_str, method='search_string'): links = list() for host in self._rutor['host']: for proto in self._rutor['protocols']: links.append(f"{proto}://{host}{self._rutor[method]}{search_str}") return links @staticmethod def parse(html_text): tree = html.fromstring(html_text) elements = tree.xpath('//table[@width]//tr') results = list() for e in elements: data = e.xpath('./td//text()') link = e.xpath('.//a/@href') if len(data) == 7: element = { "date": data[0], "name": data[2], "size": data[3], "link": link[2] } elif len(data) == 8: element = { "date": data[0], "name": data[2], "size": data[4], "link": link[2] } else: continue results.append(element) return results async def search(self, search_str): futures = [self.fetch_url(link) for link in self._generate_links(search_str)] self.log.debug(f"Generated links: {' '.join(self._generate_links(search_str))}") return await self.run_search(futures) async def run_search(self, futures): done, pending = await asyncio.wait(futures, return_when=asyncio.FIRST_COMPLETED) for future in pending: future.cancel() try: html_page = done.pop().result() except: return None # !!! Make run in executor return self.parse(html_page) async def search_keywords(self, keywords): if type(keywords) is list: keywords = ' '.join(keywords) futures = [self.fetch_url(link) for link in self._generate_links(search_str=keywords, method='search_keyword')] self.log.debug(f"Generated links: " f"{' '.join(self._generate_links(search_str=keywords, method='search_keyword'))}") return await self.run_search(futures)
pygame.quit() state.is_running = False window.quit() def soundthread(): last_played = 0 try: while state.is_running: last_played += 1 if state.is_playing and state.use_metronome and last_played > 30: last_played = 0 beep.stop() beep.play(0) soundclock.tick(240) except Exception as e: Log.debug(traceback.format_exc()) threading.Thread(None, pygamethread).start() threading.Thread(None, soundthread).start() window.mainloop() if __name__ == "__main__": try: main() except Exception as e: Log.debug(traceback.format_exc())
class Runner(RunnerInterface): def __init__(self): super().__init__() self.store = Store() self.torr_searcher = TorrSearch() self.loop = asyncio.get_event_loop() self.queue = asyncio.Queue() self.bot = TgBot(self.queue) self.log = Log(__name__) async def background_updater(self): await asyncio.sleep(5.0) self.log.debug(f"Start update after 5 seconds") while True: await asyncio.sleep(10) movies = await self.store.get_movies() self.log.debug(f"Search for {movies}") for movie in movies: self.log.debug(f"Find '{movie['title']}' for users: {movie['watchers']}") result = await self.torr_searcher.search_word(movie['title']) self.log.debug(f"Result: {result}") if result: message = self.format_films(movie['title'], result) for watcher in movie['watchers']: await self.bot.send_message(watcher, message) await self.store.create_or_update_movie(movie=movie['title'], is_active=False) @staticmethod def format_films(search_str, films): msg = f'По запросу: "{search_str}" найдены следущие раздачи:\n' for i in films[:6]: msg += f"---\n{i['date']} | {i['size']} | {i['name']}\n" return msg async def process_messages(self): while True: item = await self.queue.get() if item is not None: self.log.info(item) if not isinstance(item, dict) or 'type' not in item.keys(): self.log.error(f"Get incorrect object from tgbot: {item}") if item['type'] == 'start': await self.store.create_or_update_user(item['content']['from']) elif item['type'] == 'deactivate': await self.store.create_or_update_user(item['content']['from'], is_active=False) elif item['type'] == 'ignore': watcher = item['content']['from']['id'] movie = item['content']['text'][8:].strip() self.log.debug(f"User {watcher} trying ignore: {movie}") await self.store.ignore_movie(movie=movie, watcher=watcher) answer = f"You are unsubscribed from '{movie}' search." await self.bot.send_message(watcher, answer) elif item['type'] == 'list': watcher = item['content']['from']['id'] movies = await self.store.get_movies(telegram_id=watcher) results = '\n'.join([i['title'] for i in movies]) answer = f"You are waiting for:\n" \ f"{results}" await self.bot.send_message(watcher, answer) elif item['type'] == 'message': movie = item['content']['text'].strip() watcher = item['content']['from']['id'] if movie.startswith('/'): answer = f"Incorrect command. Use /help for additional information." else: if await self.store.get_users(telegram_id=watcher): await self.store.create_or_update_movie(movie=movie, watcher=watcher) answer = f"Title '{movie}' was added" else: answer = f'You need /start chatting with bot before make requests.' await self.bot.send_message(watcher, answer) else: self.log.error(f"Unknown type from item: {item}") def prepare(self): self.loop.create_task(self.process_messages()) self.loop.create_task(self.background_updater()) def run(self): self.prepare() # Bot exec run loop forever self.bot.run() async def search_digital(self, keywords): pass async def search_bd(self): pass async def search_torrent(self, keywords): return await self.torr_searcher.search_word(keywords)