def parse_configs(): env = Env() env.read_env() config.battle_bot_module = env("BATTLE_BOT", 'safest') config.log_to_file = env.bool("LOG_TO_FILE", config.log_to_file) config.save_replay = env.bool("SAVE_REPLAY", config.save_replay) config.use_relative_weights = env.bool("USE_RELATIVE_WEIGHTS", config.use_relative_weights) config.gambit_exe_path = env("GAMBIT_PATH", config.gambit_exe_path) config.search_depth = int(env("MAX_SEARCH_DEPTH", config.search_depth)) config.greeting_message = env("GREETING_MESSAGE", config.greeting_message) config.battle_ending_message = env("BATTLE_OVER_MESSAGE", config.battle_ending_message) config.websocket_uri = env("WEBSOCKET_URI", "sim.smogon.com:8000") config.username = env("PS_USERNAME") config.password = env("PS_PASSWORD", "") config.bot_mode = env("BOT_MODE") config.team_name = env("TEAM_NAME", None) config.pokemon_mode = env("POKEMON_MODE", constants.DEFAULT_MODE) config.run_count = int(env("RUN_COUNT", 1)) if config.bot_mode == constants.CHALLENGE_USER: config.user_to_challenge = env("USER_TO_CHALLENGE") logger.setLevel(env("LOG_LEVEL", "DEBUG"))
def test_emit_logs_on_DEBUG_level(self): url = new_url() try: requests.get(url) except ConnectionError: pass self.assertEqual(self.handler.emit_count, 0) logger.setLevel(logging.DEBUG) try: requests.get(url) except ConnectionError: pass print(self.handler.emit_count) self.assertTrue(self.handler.emit_count > 0)
async def showdown(): env = Env() env.read_env() config.log_to_file = env.bool("LOG_TO_FILE", config.log_to_file) config.save_replay = env.bool("SAVE_REPLAY", config.save_replay) config.decision_method = env("DECISION_METHOD", config.decision_method) config.use_relative_weights = env.bool("USE_RELATIVE_WEIGHTS", config.use_relative_weights) config.gambit_exe_path = env("GAMBIT_PATH", config.gambit_exe_path) config.search_depth = int(env("MAX_SEARCH_DEPTH", config.search_depth)) config.greeting_message = env("GREETING_MESSAGE", config.greeting_message) config.battle_ending_message = env("BATTLE_OVER_MESSAGE", config.battle_ending_message) logger.setLevel(env("LOG_LEVEL", "DEBUG")) websocket_uri = env("WEBSOCKET_URI", "sim.smogon.com:8000") username = env("PS_USERNAME") password = env("PS_PASSWORD", "") bot_mode = env("BOT_MODE") team_name = env("TEAM_NAME", None) pokemon_mode = env("POKEMON_MODE", constants.DEFAULT_MODE) apply_mods(pokemon_mode) original_pokedex = deepcopy(pokedex) original_move_json = deepcopy(all_move_json) ps_websocket_client = await PSWebsocketClient.create( username, password, websocket_uri) await ps_websocket_client.login() battles = [] for i in range(5): battles.append(Battle('empty')) while True: msg = await ps_websocket_client.receive_message() """ loop = asyncio.get_event_loop() t = threading.Thread(target = thr, args=(ps_websocket_client, msg, battles)) t.start() """ await parse_message(ps_websocket_client, msg, battles)
if recover_influx_container(): infl.init_db() run_main() else: logger.info( f"Could not connect to your remote database at {db_settings['host']}:{db_settings['port']}. Please verify connectivity/credentials and try again." ) sys.exit() else: run_main() else: # Program launched in one of the non-main modes. Increase logging level. logger.setLevel(logging.DEBUG) logger.handlers[0].setLevel(logging.DEBUG) if 'help' in MODE.lower() or '-h' in MODE.lower(): logger.info( "See the project Wiki for more detailed usage instructions: https://github.com/David00/rpi-power-monitor/wiki" ) logger.info( dedent("""Usage: Start the program: python3 power-monitor.py Collect raw data and build an interactive plot: python3 power-monitor.py debug "chart title here" Launch interactive phase correction mode: python3 power-monitor.py phase Start the program like normal, but print all python3 power-monitor.py terminal
def tearDown(self): logger.handlers.remove(self.handler) logger.setLevel(logging.WARNING)
from showdown.engine.select_best_move import get_payoff_matrix from showdown.engine.objects import State from showdown.engine.objects import StateMutator from config import logger import logging logger.setLevel(logging.CRITICAL) state = State.from_dict({ 'self': { 'active': { 'id': 'greninja', 'level': 100, 'hp': 285, 'maxhp': 285, 'ability': 'battlebond', 'item': 'choicespecs', 'baseStats': { 'hp': 72, 'attack': 95, 'defense': 67, 'special-attack': 103, 'special-defense': 71, 'speed': 122
logging.info("Parsing process finished!") main_parser.keywords.push_changes('telegram') users = get_all_users() for user in users: user.update_links('telegram') main_parser.keywords.clean_changes('telegram') print('SUCCESS!') @SCHED.scheduled_job('interval', hours=24, next_run_time=datetime.now()) def start_twitter_parsing(): """ Main parsing starting function. :return: None """ logger.info("Parsing process started!") main_parser = Parser(use_proxy=True) main_parser.parse_twitter() logging.info("Parsing process finished!") main_parser.keywords.push_changes('twitter') users = get_all_users() for user in users: user.update_links('twitter') main_parser.keywords.clean_changes('twitter') print('SUCCESS!') if __name__ == '__main__': logger.setLevel(logging.INFO) SCHED.start()
async def showdown(): env = Env() env.read_env() config.log_to_file = env.bool("LOG_TO_FILE", config.log_to_file) config.save_replay = env.bool("SAVE_REPLAY", config.save_replay) logger.setLevel(env("LOG_LEVEL", "DEBUG")) websocket_uri = env("WEBSOCKET_URI", "sim.smogon.com:8000") username = env("PS_USERNAME") password = env("PS_PASSWORD", "") bot_mode = env("BOT_MODE") team_name = env("TEAM_NAME", None) pokemon_mode = env("POKEMON_MODE", constants.DEFAULT_MODE) run_count = int(env("RUN_COUNT", 1)) apply_mods(pokemon_mode) original_pokedex = deepcopy(pokedex) original_move_json = deepcopy(all_move_json) if bot_mode not in constants.BOT_MODES: raise ValueError("{} is not a valid bot mode".format(bot_mode)) ps_websocket_client = await PSWebsocketClient.create( username, password, websocket_uri) await ps_websocket_client.login() team = load_team(team_name) battles_run = 0 wins = 0 losses = 0 while True: if bot_mode == constants.CHALLENGE_USER: user_to_challenge = env("USER_TO_CHALLENGE") await ps_websocket_client.challenge_user(user_to_challenge, pokemon_mode, team) elif bot_mode == constants.ACCEPT_CHALLENGE: await ps_websocket_client.accept_challenge(pokemon_mode, team) elif bot_mode == constants.SEARCH_LADDER: await ps_websocket_client.search_for_match(pokemon_mode, team) else: raise ValueError("Invalid Bot Mode") is_random_battle = "random" in pokemon_mode winner = await pokemon_battle(ps_websocket_client, is_random_battle) if winner == username: wins += 1 else: losses += 1 logger.info("\nW: {}\nL: {}\n".format(wins, losses)) if original_move_json != all_move_json: logger.critical( "Move JSON changed!\nDumping modified version to `modified_moves.json`" ) with open("modified_moves.json", 'w') as f: json.dump(all_move_json, f, indent=4) exit(1) else: logger.debug("Move JSON unmodified!") if original_pokedex != pokedex: logger.critical( "Pokedex JSON changed!\nDumping modified version to `modified_pokedex.json`" ) with open("modified_pokedex.json", 'w') as f: json.dump(pokedex, f, indent=4) exit(1) else: logger.debug("Pokedex JSON unmodified!") battles_run += 1 if battles_run >= run_count: break
def run_archiver(parents=[], logger=logger): # if we're given parents, third-party sw wants to mix with the barebones parser bbones = True if parents else False argparser = get_parser(parents=parents, barebones=bbones) args = argparser.parse_args() loglevel= getattr(logging, args.loglevel.upper()) logger.setLevel(loglevel) # Require either archival or listing operation before proceeding. if not (args.list_folders or args.archivedir): argparser.print_help() sys.exit() # Auth & connect username = args.username or raw_input("Username: "******"Connected") # Get folder listing and folder path separator from server; they will be needed. # Also make a slash ('/') -delimited list of all folders for convenience. # Note: an IMAP folder entry contains the full path, not just the leaf. folders = [fdata[2] for fdata in imapcon.list_folders()] fsep = imapcon.namespace().personal[0][1] folders_slashdelimited = [fname.replace(fsep, u'/') for fname in folders] # If requested (-f/--folders), just output it & exit if args.list_folders: sys.exit("Folders on server: %s" % ", ".join(folders_slashdelimited)) # Apply include/exclude options on the list of folders found on server, after # making sure they exist on server. invalids = [] if args.include: invalids += [fld for fld in args.include if fld not in folders_slashdelimited] if args.exclude: invalids += [fld for fld in args.exclude if fld not in folders_slashdelimited] if invalids: sys.exit("Invalid include/exclude folder names: '%s'" % invalids) folders = args.include or (set(folders_slashdelimited) - set(args.exclude)) # Archive messages! logger.info("Archiving '%s' to %s" % ("', '".join(folders), args.archivedir)) archive = mailbox.Maildir(args.archivedir) for foldername in folders: select_info = imapcon.select_folder(foldername) if select_info['EXISTS'] == 0: logger.info("Folder %s: no messages!" % foldername) continue uids = imapcon.fetch("1:%s" % select_info['EXISTS'], ['UID',]) logger.info("Folder %s: %i messages on server" % (foldername, len(uids))) logger.debug("... fetching uids for 1-%s" %(select_info['EXISTS'],)) uidvalidity = select_info['UIDVALIDITY'] logger.debug("... UID validity: %s" % uidvalidity) parts = [makeFSCompatible(unicode(prt)) for prt in foldername.split(fsep)] fsname = '.'.join(parts) with mailfolder(archive, fsname) as (folder, cached_uid_info): newuids = [id for id in uids if ((uidvalidity, id) not in cached_uid_info)] oldcount, newcount = len(cached_uid_info), len(newuids) logger.info("... %i archived messages, %i new" % (oldcount, newcount)) # use batched logging fetched = [] interval = 1 if len(newuids) > 100: interval = int(math.sqrt(len(newuids))) logger.warn("... using batched logging (entry per %i msgs)" % interval) for i, uid in enumerate(newuids): fetch_info = imapcon.fetch(uid, ["BODY.PEEK[]",]) logger.debug("... info: %s" % fetch_info) msg = fetch_info[uid]["BODY[]"] # If a message cannot be stored, skip it instead of failing try: folder.add(msg) cached_uid_info.append((uidvalidity,uid)) except Exception, e: logger.error("... error storing mail: %s\n%s" %(msg,e), False) fetched.append(str(uid)) if not (i % interval): logger.info("... got message(s): %s" % ", ".join(fetched)) fetched = []
def main(): # Check for command line arguments # d: install_dir: {DOT_INSTALL_DIR} # v: verbose # h: help install_dir = None modules = None try: options, _ = getopt.getopt( sys.argv[1:], "d:vhm:", ["installdir=", "help", "verbose", "modules="]) except getopt.GetoptError as err: print(err) print("Please see the help (--help).") exit(1) # Parse the command line arguments. for option, argument in options: if option in ("-v", "--verbose"): logger.setLevel(logging.DEBUG) for handler in logger.handlers: handler.setLevel(logging.DEBUG) elif option in ("-h", "--help"): print_help() elif option in ("-d", "--installdir"): install_dir = os.path.abspath(argument) elif option in ("-m", "--modules"): if argument.lower() == "all": modules = list(helpers.scan_for_installers(install_dir).keys()) else: modules = argument.split(",") else: assert False, "Unknown option {}.".format(option) if not install_dir: logger.fatal("Installation directory not provided. Not installing.") exit(1) if not modules or len(modules) < 1: logger.fatal("No modules selected.") exit(1) # Get all available modules for installation. available_modules = helpers.scan_for_installers(install_dir) # Remove the dependency modules from the list so they don't get installed twice. dependency_modules = [] for module in modules: for dependency in available_modules[module]["depends"]: dependency_modules.append(dependency) for module in dependency_modules: if module in modules: modules.remove(module) logger.debug("Installation directory: {}".format(install_dir)) for module in modules: try: install_module(module, install_dir, available_modules, install_dependencies=False) except Exception as e: logger.error("Failed to install {}\n {}".format(module, e))
success = request.update_ip(config.hostname, net.get_ip_from_dyndns()) codes = dict(map(lambda a, b: (a, b), request.codes, request.messages)) return success, codes def main(): args = get_args() config = build_config(args) if net.has_ip_changed(config.hostname): print "IP for {0} has changed. Sending update.".format(config.hostname) resp = do_update(config) elif args.force: print "IP for {0} has not changed. Sending update anyway (force-update)".format(config.hostname) resp = do_update(config) else: print "IP for {0} has not changed. Exiting.".format(config.hostname) return 0 if resp[0]: print "Successfully updated IP for {0}".format(config.hostname) return 0 else: print "A problem occurred while updating." for code in resp[1]: print "{0}: {1}".format(message, resp[1][code]) return 1 if __name__ == "__main__": #pragma: no cover logger.setLevel(logging.DEBUG) logger.addHandler(logging.FileHandler("./log.txt", mode='a+')) sys.exit(main())