def show_search(imdbid): config = ConfigParser() if not os.path.exists('data.json'): headers = {"Content-type": "application/json", "X-Api-Key": "{}".format(config['sonarr']['api_key'])} url = "{}/api/series".format(config['sonarr']['baseurl']) rsp = requests.get(url, headers=headers) data = json.loads(rsp.text) with open('data.json', 'w') as json_file: json.dump(data, json_file) else: with open('data.json') as json_file: data = json.load(json_file) for i in data: if i.get('imdbId','') == imdbid: ID = i['id'] headers = {"Content-type": "application/json"} url = "{}/api/command?apikey={}".format(config['sonarr']['baseurl'], config['sonarr']['api_key']) data = json.dumps({"name": "SeriesSearch", "seriesId": ID}) rsp = requests.post(url, headers=headers , data=data) print("Searching For {} ({})\n".format(i['title'],i['year'])) elif title in i['title']: ID = i['id'] headers = {"Content-type": "application/json"} url = "{}/api/command?apikey={}".format(config['sonarr']['baseurl'], config['sonarr']['api_key']) data = json.dumps({"name": "SeriesSearch", "seriesId": ID}) rsp = requests.post(url, headers=headers , data=data) print("Searching For {} ({})\n".format(i['title'],i['year']))
def _getpluginconf(self, modname): '''Parse the plugin specific configuration file and return a IncludingConfigParser instance representing it. Returns None if there was an error reading or parsing the configuration file. ''' for dir in self.pluginconfpath: conffilename = os.path.join(dir, modname + ".conf") if os.access(conffilename, os.R_OK): # Found configuration file break self.verbose_logger.log( logginglevels.INFO_2, _("Configuration file %s not found") % conffilename) else: # for # Configuration files for the plugin not found self.verbose_logger.log( logginglevels.INFO_2, _("Unable to find configuration file for plugin %s") % modname) return None parser = ConfigParser() confpp_obj = ConfigPreProcessor(conffilename) try: parser.readfp(confpp_obj) except ParsingError, e: raise Errors.ConfigError("Couldn't parse %s: %s" % (conffilename, str(e)))
def __init__(self, recipe_name, sort_only=False, config_file=None): self.recipe_name = recipe_name self.config = ConfigParser(config_file) self.recipe = RecipeParser(recipe_name) if self.recipe['library_type'].lower().startswith('movie'): self.library_type = 'movie' elif self.recipe['library_type'].lower().startswith('tv'): self.library_type = 'tv' else: raise Exception("Library type should be 'movie' or 'tv'") # TODO: Support multiple libraries self.source_library_config = self.recipe['source_libraries'] self.plex = plexutils.Plex(self.config['plex']['baseurl'], self.config['plex']['token']) if self.config['trakt']['username']: self.trakt = traktutils.Trakt( self.config['trakt']['username'], client_id=self.config['trakt']['client_id'], client_secret=self.config['trakt']['client_secret']) if self.config['tmdb']['api_key']: self.tmdb = tmdb.TMDb(self.config['tmdb']['api_key'], cache_file=self.config['tmdb']['cache_file']) if self.config['tvdb']['username']: self.tvdb = tvdb.TheTVDB(self.config['tvdb']['username'], self.config['tvdb']['api_key'], self.config['tvdb']['user_key'])
def __init__(self, configfile, req, color=False, detectors=None): self.configfile = configfile print('vulncontroller: %s' % configfile) self.req = req self.color = color self.configparser = ConfigParser(self.configfile) self.tools = [] self.initTools()
def add_show(imdbid, title): # Add Missing to sonarr Work in Progress config = ConfigParser() if imdbid is None: imdbid = title tvdbId = get_tvdbId(imdbid) if tvdbId == "Not Found": print("TVDBId {} Not found".format(title)) return headers = {"Content-type": "application/json"} url = "{}/api/series/lookup?term=tvdb:{}&apikey={}".format(config['sonarr']['baseurl'], tvdbId , config['sonarr']['api_key'] ) rsp = requests.get(url, headers=headers) if rsp.text == "": print("No imdb info Found...\n") return data = json.loads(rsp.text) tvdbId = data[0]["tvdbId"] title = data[0]["title"] year = data[0]["year"] images = json.loads(json.dumps(data[0]["images"])) titleslug = data[0]["titleSlug"] seasons = json.loads(json.dumps(data[0]["seasons"])) headers = {"Content-type": "application/json", "X-Api-Key": "{}".format(config['sonarr']['api_key'])} data = json.dumps({ "title": title , "year": year , "tvdbId": tvdbId , "titleslug": titleslug, "monitored": 'true' , "seasonFolder": 'true', "qualityProfileId": '6', "rootFolderPath": config['sonarr']['rootfolderpath'] , "images": images, "seasons": seasons, "addOptions": { "ignoreEpisodesWithFiles": "true", "ignoreEpisodesWithoutFiles": "false", "searchForMissingEpisodes": config['sonarr']['searchForShow'] } }) url = '{}/api/series'.format(config['sonarr']['baseurl']) rsp = requests.post(url, headers=headers, data=data) if rsp.status_code == 201: print("{} ({}) Added to sonarr\n".format(title,year)) elif rsp.status_code == 400: if config['sonarr']['searchForShow'] == 'true': print("{} ({}) already Exists in sonarr, But Not Downloaded...".format(title, year)) show_search(imdbid) return else: print("{} ({}) already Exists in sonarr, But Not Downloaded, Search not Enabled... \n".format(title, year)) return else: print ("Did not add {} ({}) to Sonarr\n".format(title,year))
def __init__(self, conf_file): parser = ConfigParser(conf_file) conf = parser.conf["server"] self.microservice_thrift = thriftpy.load(conf["thrift_file"], conf["module_name"]) self.service = getattr(self.microservice_thrift, conf["service_name"]) self.client = make_client(self.service, conf["host"], int(conf["port"]))
def __init__(self, recipe_name, sort_only=False, config_file=None, use_playlists=False): self.recipe_name = recipe_name self.use_playlists = use_playlists self.config = ConfigParser(config_file) self.recipe = RecipeParser(recipe_name) if not self.config.validate(): raise Exception("Error(s) in config") if not self.recipe.validate(use_playlists=use_playlists): raise Exception("Error(s) in recipe") if self.recipe['library_type'].lower().startswith('movie'): self.library_type = 'movie' elif self.recipe['library_type'].lower().startswith('tv'): self.library_type = 'tv' else: raise Exception("Library type should be 'movie' or 'tv'") self.source_library_config = self.recipe['source_libraries'] self.plex = plexutils.Plex(self.config['plex']['baseurl'], self.config['plex']['token']) if self.config['trakt']['username']: self.trakt = traktutils.Trakt( self.config['trakt']['username'], client_id=self.config['trakt']['client_id'], client_secret=self.config['trakt']['client_secret'], oauth_token=self.config['trakt'].get('oauth_token', ''), oauth=self.recipe.get('trakt_oauth', False), config=self.config) if self.trakt.oauth_token: self.config['trakt']['oauth_token'] = self.trakt.oauth_token if self.config['tmdb']['api_key']: self.tmdb = tmdb.TMDb(self.config['tmdb']['api_key'], cache_file=self.config['tmdb']['cache_file']) if self.config['tvdb']['username']: self.tvdb = tvdb.TheTVDB(self.config['tvdb']['username'], self.config['tvdb']['api_key'], self.config['tvdb']['user_key']) self.imdb = imdbutils.IMDb(self.tmdb, self.tvdb) self.source_map = IdMap(matching_only=True, cache_file=self.config.get('guid_cache_file')) self.dest_map = IdMap(cache_file=self.config.get('guid_cache_file'))
def get_token(): config = ConfigParser() data = { "apikey": "{}".format(config['tvdb']['api_key']), "userkey": "{}".format(config['tvdb']['user_key']), "username": "******".format(config['tvdb']['username']) } url = "https://api.thetvdb.com/login" rsp = requests.post(url, json=data) data = json.loads(rsp.text) return data['token']
def __init__(self, token): self.config=ConfigParser() self.config.read(CONFIG_FILE_NAME,"utf_8_sig") self.started = True; db = DbHelper() tables_db = db.execute_select("SELECT * FROM {}.{}".format(self.config.get("postgresql","schema"), self.config.get("postgresql","tables_dict"))) self.tables = [] for table in tables_db: self.tables.append(NotificationTable(table[1])) self.TOKEN = token self.URL = "https://api.telegram.org/bot{}/".format(token) LogDBHandler.log(Actions.start, self.config.get("botsettings","messenger_name"),"", "", "success", "")
def __init__(self, configfile, datadir, req, vulncontroller, color=False, detectors=None): self.configfile = configfile self.datadir = datadir self.vulncontroller = vulncontroller self.color = color self.detectors = detectors self.req = req self.tools = [] self.configparser = ConfigParser(self.configfile) self.initTools()
def __init__(self,configfile,blacklist,req,color=False,detectors = None): self.configfile = configfile self.blacklist = parseurls.getList(blacklist) """ print('vulncontroller: %s' % configfile) print('Cfgfile %s' % configfile) print('Blacklist %s' % blacklist) print('type blacklist %s' % type(blacklist)) print('color %s' % color) print('len blacklist %s' % len(self.blacklist)) """ self.req = req self.color = color self.configparser = ConfigParser(self.configfile) self.tools = [] self.initTools()
def __init__(self, recipe_name, config_file=None): self.recipe_name = recipe_name self.config = ConfigParser(config_file) self.recipe = RecipeParser(recipe_name) if self.recipe['library_type'].lower().startswith('movie'): self.library_type = 'movie' elif self.recipe['library_type'].lower().startswith('tv'): self.library_type = 'tv' else: raise Exception("Library type should be 'movie' or 'tv'") self.source_library_config = self.recipe['source_libraries'] self.plex = plexutils.Plex(self.config['plex']['baseurl'], self.config['plex']['token']) if self.config['trakt']['username']: self.trakt = traktutils.Trakt( self.config['trakt']['username'], client_id=self.config['trakt']['client_id'], client_secret=self.config['trakt']['client_secret'], oauth_token=self.config['trakt'].get('oauth_token', ''), oauth=self.recipe.get('trakt_oauth', False), config=self.config) if self.trakt.oauth_token: self.config['trakt']['oauth_token'] = self.trakt.oauth_token if self.config['tmdb']['api_key']: self.tmdb = tmdb.TMDb(self.config['tmdb']['api_key'], cache_file=self.config['tmdb']['cache_file']) if self.config['tvdb']['username']: self.tvdb = tvdb.TheTVDB(self.config['tvdb']['username'], self.config['tvdb']['api_key'], self.config['tvdb']['user_key']) self.imdb = imdbutils.IMDb(self.tmdb, self.tvdb)
# validate input try: config_fp = sys.argv[1] except IndexError: print("You failed to provide a configuration file. Usage: {0} config.json". format(sys.argv[0])) if '.json' not in sys.argv[1]: raise ValueError("The configuration file must be in JSON format.") # parse config config = json.load(open(config_fp, 'r')) # parse config config = ConfigParser().parse_config(config=config, mode='evaluate') # load model if config['model'] == 'linear': model = models.LinearModel(input_shape=(config['history_length'], ), nb_output_units=1, nb_hidden_units=config['nb_hidden_units']) elif config['model'] == 'mlp': model = models.MLPModel(input_shape=(config['history_length'], ), nb_output_units=1, nb_hidden_units=config['nb_hidden_units'], nb_layers=config['nb_layers']) elif config['model'] == 'gru': model = models.GRUModel(input_shape=(config['history_length'], 1), nb_output_units=1, nb_hidden_units=config['nb_hidden_units'],
import game import os abspath = os.path.abspath(__file__) dname = os.path.dirname(abspath) os.chdir(dname) def run(): return game.run() if __name__ == "__main__": parser = ConfigParser(config=config, prog="main.py", description="rewind client for bomberman") parser.parse() if not config.is_replay: win_count, win_avg_diff = 0, 0 lose_count, lose_avg_diff = 0, 0 draw_count = 0 stat = { 'me_alive, ene_alive': { 'win': 0, 'lose': 0, 'draw': 0 }, 'me_alive, ene_dead': {
gui.Application.instance.post_to_main_thread( self.window, lambda: self.update_render( input_frame.get_data_as_image('depth'), input_frame.get_data_as_image('color'), raycast_frame.get_data_as_image('depth'), raycast_frame.get_data_as_image('color'), pcd, frustum)) self.idx += 1 self.is_done = self.is_done | (self.idx >= n_files) time.sleep(0.5) if __name__ == '__main__': parser = ConfigParser() parser.add( '--config', is_config_file=True, help='YAML config file path. Please refer to default_config.yml as a ' 'reference. It overrides the default config file, but will be ' 'overridden by other command line inputs.') parser.add( '--default_dataset', help='Default dataset is used when config file is not provided. ' 'Default dataset may be selected from the following options: ' '[lounge, bedroom, jack_jack]', default='lounge') parser.add('--path_npz', help='path to the npz file that stores voxel block grid.', default='output.npz')
from config import ConfigParser from controller import Controller if __name__ == "__main__": config = ConfigParser() controller = Controller(config) controller.build_train() controller.train() controller.build_test() controller.test()
# validate input try: config_fp = sys.argv[1] except IndexError: print("You failed to provide a configuration file. Usage: {0} config.json". format(sys.argv[0])) if '.json' not in sys.argv[1]: raise ValueError("The configuration file must be in JSON format.") # parse config config = json.load(open(config_fp, 'r')) # parse config config = ConfigParser().parse_config(config=config, mode='train') # load data exclude = [] all_subjects = [540, 544, 552, 567, 584, 596, 559, 563, 570, 575, 588, 591] if config['dataset'] == 'subject_only': exclude = list(set(all_subjects) - set([int(config['subject'])])) elif config['dataset'] == 'exclude_subject': exclude = [int(config['subject'])] print("loading data..") X_train, Y_train, X_val, Y_val, X_train_mean, X_train_stdev = data.load_data( dir=config['data_dir'], exclude=exclude,
def __init__(self, window_size): ''' Nombre: __init__ Descripcion: Constructor del cliente de video Argumentos: window_size: Tamano de la ventana. ''' #Creamos el objeto de configuracion self.config = ConfigParser() #Creamos el objeto de buffer de video self.buffer_video = VideoBuffer(self.config) # Creamos una variable que contenga el GUI principal self.app = gui("Redes2 - P2P", window_size) self.app.setGuiPadding(10, 10) # Preparación del interfaz self.app.addLabel("title", "Cliente Multimedia P2P - Redes2 ") self.app.addLabel("loggeduser", "Sesion no iniciada") self.app.addImage("video", "imgs/webcam.gif") # Registramos la función de captura de video # Esta misma función también sirve para enviar un vídeo self.cap = cv2.VideoCapture(0) #FPS minimo y maximo para el QoS self.fps_send_max = int(self.cap.get(cv2.CAP_PROP_FPS)) self.fps_send_min = self.fps_send_min // 2 self.fps_send = [self.fps_send_max] # Añadir los botones self.app.addButtons(["Conectar", "Espera", "Colgar", "Salir"], self.buttonsCallback) self.app.enableButton("Conectar") self.app.disableButton("Espera") self.app.disableButton("Colgar") # Barra de estado # Debe actualizarse con información útil sobre la llamada (duración, FPS, etc...) self.app.addStatusbar(fields=3, side="LEFT") self.app.setStatusbarWidth(35, field=0) self.app.setStatusbarWidth(50, field=1) self.app.setStatusbarWidth(60, field=2) #Bara de herramientas self.app.addToolbar(["FILE", "CAMERA"], self.toolbarCallback, findIcon=True) self.app.setToolbarIcon("CAMERA", "md-camera-photo") self.app.setStopFunction(self.stop) self.app.setStartFunction(self.on_startup) #Ventana de inicio de sesion self.app.startSubWindow("Login", modal=True) #Modal: Bloquea a la principal. self.app.addLabel("pad", "", 0, 0) #Padding above self.app.setPadding([30, 0]) self.app.setSticky('e') self.app.addLabel("user", "Nick: ", 1, 0) self.app.addLabel("pass", "Password: "******"tcp", "Puerto de control (TCP): ", 3, 0) self.app.addLabel("udp", "Puerto de video (UDP): ", 4, 0) self.app.addLabel("ip", "Direccion IP: ", 5, 0) self.app.addLabel( "ipWarn", "(La IP puede dejarse en blanco para utilizar la IP local)", 6, 2) self.app.setSticky('w') self.app.addEntry("userInput", 1, 2) self.app.addSecretEntry("passInput", 2, 2) self.app.addNumericEntry("tcpInput", 3, 2) self.app.addNumericEntry("udpInput", 4, 2) self.app.addEntry("ipInput", 5, 2) self.app.setPadding([20, 20]) self.app.addButton("Entrar", self.login, 7, 1) self.app.setStopFunction( self.app.stop) #Parar la ventana cierra la app. self.app.setPadding([0, 0]) self.app.stopSubWindow() # Definicion de la ventana de elegir usuario para llamada: self.app.startSubWindow("Iniciar llamada", modal=True) #Modal: Bloquea a la principal. self.app.addLabel("pad2", "", 0, 0) #Padding above self.app.setPadding([30, 0]) self.app.setSticky('e') self.app.addLabel("calleeNick", "Llamar a: ", 1, 0) self.app.addLabel("listInfo", "Usuarios registrados:", 2, 0) self.app.setSticky('w') self.app.addEntry("calleeNickInput", 1, 1) self.app.addListBox("nicksList", ["Cargando..."], 2, 1) #Handler self.app.setListBoxChangeFunction("nicksList", self.list_handler) self.app.setPadding([20, 20]) self.app.addButton("Llamar", self.init_call, 3, 1) self.app.setPadding([0, 0]) self.app.stopSubWindow()
def add_movie(imdbid,title): # Add Missing to Radarr Work in Progress config = ConfigParser() headers = {"Content-type": "application/json"} url = "{}/api/movie/lookup/imdb?imdbId={}&apikey={}".format(config['radarr']['baseurl'], imdbid, config['radarr']['api_key'] ) rsp = requests.get(url, headers=headers) if rsp.status_code != 200: print ("Failed to connect to Radarr.") return if rsp.status_code == 404: print ("Movie Not Found...") return if rsp.text == "": title = title.replace(":","") url = "{}/api/movie/lookup?term={}&apikey={}".format(config['radarr']['baseurl'], title, config['radarr']['api_key'] ) rsp = requests.get(url, headers=headers) if rsp.status_code != 200: print ("Failed to connect to Radarr.") return if rsp.status_code == 404: print ("Movie Not Found...") return if rsp.text == "[]": print ("Movie Not Found...") return data = json.loads(rsp.text) tmdbid = data[0]["tmdbId"] title = data[0]["title"] year = data[0]["year"] images = json.loads(json.dumps(data[0]["images"])) titleslug = data[0]["titleSlug"] if year > datetime.now().year: print("{} ({}) not releasd yet not added to Radarr..".format(title,year)) return else: data = json.loads(rsp.text) tmdbid = data["tmdbId"] title = data["title"] year = data["year"] images = json.loads(json.dumps(data["images"])) titleslug = data["titleSlug"] if year > datetime.now().year: print("{} ({}) not releasd yet not added to Radarr..".format(title,year)) return headers = {"Content-type": "application/json", "X-Api-Key": config['radarr']['api_key']} data = json.dumps({ "title": title , "qualityProfileId": '6' , "year": year , "tmdbId": tmdbid , "titleslug":titleslug, "monitored": 'true' , "minimumAvailability": "released", "rootFolderPath": config['radarr']['rootfolderpath'] , "images": images, "addOptions" : {"searchForMovie" : config['radarr']['searchForMovie']} }) url = '{}/api/movie'.format(config['radarr']['baseurl']) rsp = requests.post(url, headers=headers, data=data) if rsp.status_code == 201: print("{} ({}) Added to Radarr..".format(title,year)) elif rsp.status_code == 400: if config['radarr']['searchForMovie'] == 'true': print("{} ({}) already Exists in Radarr, But Not Downloaded...".format(title, year)) movie_search(imdbid) return else: print("{} ({}) already Exists in Radarr, But Not Downloaded, Search not Enabled...".format(title, year)) return
# -*- conding: utf-8 -*- # @Time : 2018/6/21 15:45 # @Author : Elvis Jia # @Description: parser test from config import ConfigParser import requests if __name__ == "__main__": configParser = ConfigParser('config.txt') rootBlock = configParser.parse() # Test read html file with open('test.htm', 'rb') as reader: content = reader.read().decode('utf-8') result, stop = rootBlock.search(content, 0, len(content)) print 'test html:', result # Test download html url = 'https://mall.kaola.com/search.html?shopId=15662189' content = requests.get(url, verify=False).text result, stop = rootBlock.search(content, 0, len(content)) print 'test html downloaded:', result
def test_config(): c = ConfigParser() c.set("logins.username", "test1") assert c.get("logins.username") == "test1" c.set("concurrency", 10) assert c.get("concurrency") == 10