def __init__(self, libinfoFile, tablename=defaultTable, conf=None, species=defaultSpecies, verbose=False, log=sys.stderr): "create load_libinfo instance, connect to MySQL and check for existance of libinfo file" # set attributes self.verbose = verbose self.log = log self.file = libinfoFile self.tablename = tablename self.conf = None self.species = species self.__db = None # db connection self.__cursor = None # check libinfoFile if not os.path.exists(self.file): self.__inform("ERROR: library info file %s does not exist\n" % self.file) raise Errors.ObjectInitError('load_libinfo', "library info file '%s' does not exist\n" % self.file) # init configuration if conf is not None and isinstance(conf, configuration.Configuration): self.conf = conf elif conf is not None and os.path.exists(conf): self.conf = configuration.Configuration(filename=conf) else: self.conf = configuration.Configuration() # check species if not self.species in self.conf.getSpeciesList(): self.__inform("ERROR: species %s is not in configuration file %s\n" % (self.species, self.conf.configFile())) raise Errors.ObjectInitError('load_libinfo', "species '%s' is not in configuration file %s\n" % (self.species, self.conf.configFile())) # connect to MySQL self.__connect()
def configuration(self, new_configuration): """Set configuration. Parameters ---------- new_configuration : :class:`configuration:Configuration` or string or 2-tuple The attribute is set in one of the three following ways: (i) an object of :class:`configuration:Configuration`; (ii) a string with the name of the file to be read with the configuration information; and (iii) a 2-tuple with the name and the path to the file to be read. Examples -------- The following examples explain the ways to set the attribute: >>> solver.configuration = Configuration(...) >>> solver.configuration = 'myfile' >>> solver.configuration = ('myfile', './folder/') """ if isinstance(new_configuration, tuple): file_name, file_path = new_configuration self._configuration = cfg.Configuration(import_filename=file_name, import_filepath=file_path) elif isinstance(new_configuration, str): self._configuration = cfg.Configuration( import_filename=new_configuration) else: self._configuration = cp.deepcopy(new_configuration)
def __init__(self, conf=None, log=sys.stderr): "instanciate MakeMySQL class and read configuration" # configuration if conf is not None and isinstance(conf, configuration.Configuration): self.conf = conf elif conf is not None and os.path.exists(conf): self.conf = configuration.Configuration(filename=conf) else: self.conf = configuration.Configuration() # log self.log = log # store MySQL information self.MySQL_info = {} for species in self.conf.getSpeciesList(): self.MySQL_info[species] = { "user": os.getlogin(), "DB": self.conf[species]["Assembly"], "PASSWORD": '', "host": self.conf[species]["MySQLHost"], "knownGene": self.conf[species]["knownGene"], "mRNA": self.conf[species]["mRNA"], "MetaTable": self.conf[species]["MetaTable"], "Chromosomes": self.conf[species]["Chromosomes"].split(","), } self.db = None self.cursor = None self.currentspecies = None
def test_settings_save_load(self): self.config = configuration.Configuration(self.path) self.config.load() element = configuration.createConfigurable(BasicConfig, self.config) v = "New" element.p2 = v self.config.save() self.config = configuration.Configuration(self.path) self.config.load() element = configuration.createConfigurable(BasicConfig, self.config) self.assertEqual(element.p2, v)
def __init__(self, conf=None, replace=True, log=sys.stderr, gunzip=True): if conf is not None and isinstance(conf, configuration.Configuration): self.conf = conf elif conf is not None and os.path.exists(conf): self.conf = configuration.Configuration(filename=conf) else: self.conf = configuration.Configuration() self.replace = bool(replace) self.species = None self.log = log self.gunzip = gunzip self.tablenames = { } #format: self.tablenames[species][tablename] = dir_with_sql_and_data_files
def main(): # GLOBAL stuff # detections=detect_by_gmm(frame) config = configuration.Configuration() test_img = cv2.imread('C:/Users/Public/Pictures/Sample Pictures/test.jpg') # test NORMALIZE INPUT SHAPE print("normalize_shape") normalize_shape(test_img,config.input_shapes[3]) # test RELATIVE_to_absolute print('relative_to_absolute') relative_detections = [[70,170,40,105],[90,160,50,70]] bb = [50, 300 , 20 , 340] h_padding = 25 w_padding = 40 print(relative_to_absolute(relative_detections,bb,h_padding,w_padding)) # test SELECT model print('select_model') print(select_model(bb,config)) # test ABSOLUTE_to_relative print('absolute_to_relative') abs_cordinate = [70,350,40,415] print(absolute_to_relative(abs_cordinate,bb))
def __init__(self, configfile=None): ''' Initialization method of Choronzon. Reads the configuration, instantiates objects of the vital classes, builds and analyzes the first generation of chromosomes by reading the initial population provided to the fuzzer. ''' # configuration is a singleton self.configuration = configuration.Configuration(configfile) self.campaign = campaign.Campaign(self.configuration['CampaignName']) seedpath = self.campaign.copy_directory( self.configuration['InitialPopulation'], name='seedfiles') self.tracer = tracer.Tracer() self.strategy = strategy.FuzzingStrategy() self.population = world.Population(self.tracer.cache) self.evaluator = evaluator.Evaluator(self.tracer.cache) try: self.sharedpath = self.campaign.create_shared_directory( self.configuration['ChromosomeShared']) except: self.sharedpath = None # Initialize factory for building chromosome # and the proxy for computing the fitness. chromosomes = chromosome.Factory.build(seedpath) for chromo in chromosomes: self.population.add_chromosome(chromo) self.analyze()
def __init__(self, fake=False): self.fake = fake if self.fake: self.table_name = "Fake" + self.table_name self.ddb = ddb.DDB(self.table_name, [('channel_key', 'S')]) self.table = self.ddb.get_table() self.configuration = configuration.Configuration()
def __init__(self, seed=1): # configuration self.seed = seed if isinstance(seed,(range,list)) else [seed] self.cnf = cf.Configuration() self.random = np.random self.time = tm.strftime('%Y-%m-%d_%H-%M-%S') self.cnf_name = '_'.join([self.cnf.learning_method, self.cnf.loss_function, 'lr='+str(self.cnf.learning_rate)])
def test_listDependencyGraph(self): config = configuration.Configuration() config.addClassifiers = "" sourceKey = "repository:central" topGavs = ['org.apache.ant:ant:1.8.0'] dependencies = { 'org.apache.ant:ant:pom:1.8.0': set(['']), #'org.apache.ant:ant:jar:1.8.0': set(['']), 'org.apache.ant:ant-launcher:pom:1.8.0': set(['']), 'org.apache.ant:ant-launcher:jar:1.8.0': set(['']), 'org.apache.ant:ant-parent:pom:1.8.0': set(['']), 'org.apache:apache:pom:3': set(['']), 'org.apache:apache:pom:4': set(['']), 'xerces:xercesImpl:pom:2.9.0': set(['']), 'xerces:xercesImpl:jar:2.9.0': set(['']), 'xml-apis:xml-apis:pom:1.3.04': set(['']), 'xml-apis:xml-apis:jar:1.3.04': set(['']), 'xml-resolver:xml-resolver:pom:1.2': set(['']), 'xml-resolver:xml-resolver:jar:1.2': set(['']) } expectedArtifacts = self._getExpectedArtifacts(self.indyUrl, dependencies) builder = artifact_list_builder.ArtifactListBuilder(config) actualArtifacts = builder._listDependencyGraph(self.indyUrl, None, sourceKey, topGavs) self.assertEqualArtifactList(expectedArtifacts, actualArtifacts)
def __init__(self, notation, cam): """ Parses the passed notation and saves values into members. @sfunc: Represents the function that returns the next given state. @ruleset: A created ruleset that matches always @offsets: Represents the Moore neighborhood corresponding to the given CAM """ self.sfunc = None self.offsets = c.Configuration.moore(cam.master) self.ruleset = r.Ruleset(r.Ruleset.Method.ALWAYS_PASS) if re.match(CAMParser.MCELL_FORMAT, notation): x, y = notation.split('/') if all(map(self._numasc, [x, y])): self.sfunc = self._mcell(x, y) else: raise ValueError("Non-ascending values in MCELL format") elif re.match(CAMParser.RLE_FORMAT, notation): B, S = map(lambda x: x[1:], notation.split('/')) if all(map(self._numasc, [B, S])): self.sfunc = self._mcell(S, B) else: raise ValueError("Non-ascending values in RLE format") else: raise ValueError("No supported format passed to parser.") # Add configuration to given CAM config = c.Configuration(self.sfunc, plane=cam.master, offsets=self.offsets) self.ruleset.configurations.append(config)
def reset(self): self.unsubscribe_all() # make conf self.conf = configuration.Configuration(self.aircraft) self.settings = [] for sc in self.conf.settings: for s in sc['settings']: if not ((s['has_key']('settingsapp') and s['settingsapp'] == "ignore")): self.settings.append(s) # if setting doesn't have guipage, set guipage to "unsorted" for s in self.settings: if not s['has_key']('guipage'): s['guipage'] = 'unsorted' self.settings.sort(key=lambda x: x['guipage']) # group settings by guipage and add to notebook self.notebook = wx.Notebook(self) self.guipages = {} from itertools import groupby for guipage_name, g in groupby(self.settings, lambda s: s['guipage']): self.guipages[guipage_name] = GuiPage(self.notebook, self.lc, list(g), self.lc_event) self.notebook.AddPage(self.guipages[guipage_name], guipage_name)
def test_handleGetConfigCommand(self): self.backend.storage = MockStorage(test=self) self.backend.BL4PAddress = 'BL4PAddress' MS = MockStorage(test=self) MS.configuration['bl4p.apiKey'] = 'foo' MS.configuration['bl4p.apiSecret'] = 'bar' self.backend.configuration = configuration.Configuration(MS) cmd = Mock() cmd.commandID = 42 self.backend.handleGetConfigCommand(cmd) self.assertEqual(self.outgoingMessages, [messages.PluginCommandResult( commandID=42, result=\ { 'values': { 'bl4p.url' : '', 'bl4p.apiKey' : 'foo', 'bl4p.apiSecret' : 'bar', 'bl4p.signingPrivateKey': '', } } )])
def convert_osm_to_roadgraph(filename, network_type, options): configuration = config.Configuration(network_type) r_index = filename.rfind(".") out_file = filename[:r_index] print("selected network type: {}".format(configuration.network_type)) print("accepted highway tags: {}".format(configuration.accepted_highways)) print("opening file: {}".format(filename)) nodes, ways = osm.read_osm.read_file(filename, configuration) osm.sanitize_input.sanitize_input(ways, nodes) graph = graphfactory.build_graph_from_osm(nodes, ways) if not options.lcc: graph = algorithms.computeLCCGraph(graph) output.write_to_file(graph, out_file, configuration.get_file_extension()) if options.contract: contracted_graph = contract.contract(graph) output.write_to_file(contracted_graph, out_file, "{}c".format(configuration.get_file_extension()))
def convert_osm_to_roadgraph(filename, network_type, options): configuration = config.Configuration(network_type) r_index = filename.rfind(".") out_file = filename[:r_index] print(f"selected network type: {configuration.network_type}") print(f"accepted highway tags: {configuration.accepted_highways}") print(f"opening file: {filename}") nodes, ways = osm.read_osm.read_file(filename, configuration) osm.sanitize_input.sanitize_input(ways, nodes) graph = graphfactory.build_graph_from_osm(nodes, ways) if not options.lcc: graph = algorithms.computeLCCGraph(graph) output.write_to_file(graph, out_file, configuration.get_file_extension()) if options.networkx_output: nx_graph = convert_graph.convert_to_networkx(graph) output.write_nx_to_file(nx_graph, f"{out_file}.json") if options.contract: contracted_graph = contract_graph.ContractGraph(graph).contract() output.write_to_file(contracted_graph, out_file, f"{configuration.get_file_extension()}c") if options.networkx_output: nx_graph = convert_graph.convert_to_networkx(contracted_graph) output.write_nx_to_file(nx_graph, f"{out_file}_contracted.json")
def load_config(self, config_file, raise_exception=False): try: config_from_yaml = yaml.load(open(config_file, 'r')) config = configuration.Configuration(config_from_yaml) for module_name in config.plugins: action_module = '%s.actions' % module_name importlib.import_module(action_module) self.validate_config(config) self.config_filename = config_file self.config_mtime = os.stat(config_file).st_mtime # move clients from old config if they have the same connection if self.config is not None: for gerrit_name in config.gerrits: client = config.gerrits[gerrit_name]['client'] old_client = self.config.gerrits[gerrit_name]['client'] if old_client == client: logging.debug('Reusing client for %s' % gerrit_name) config.gerrits[gerrit_name]['client'] = old_client self.config.gerrits[gerrit_name]['client'] = None self.config.close_clients() self.config = config except Exception as e: logging.error('Could not load configuration file, ' 'encountered errors : ' + e.message) if raise_exception: raise e
def __init__(self, master=None, name='root'): tk.Frame.__init__(self, master, name=name) self.grid(sticky=tk.N + tk.S + tk.E + tk.W) self.path = os.path.dirname(os.path.abspath(__file__)) self.config = configuration.Configuration('cosmexo', 'config') self.createWidgets() self.db = None
def __init__(self, db: asyncpg.pool.Pool): intents: discord.Intents = discord.Intents.none() intents.guilds = True intents.guild_messages = True intents.members = True super().__init__( command_prefix='!reg ', activity=discord.Game('type "!reg help" for help'), description= 'Hello, I\'m Reg. I help with managing this server. Contact Alpatron if I go haywire. My commands are:', intents=intents) self.db = db import configuration #This is to prevent circular dependency errors. Come to think about it, cogs are circularly dependent! All cogs must know about the bot, and the bot needs to know about cogs! self.add_cog(configuration.Configuration(self)) import configurationCommands self.add_cog( configurationCommands.ConfigurationCommands( self, self.get_cog('Configuration'))) import adminCommands self.add_cog( adminCommands.AdminCommands(self, self.get_cog('Configuration'))) import userCommands self.add_cog( userCommands.UserCommands(self, self.get_cog('Configuration'))) self.http_session = aiohttp.ClientSession() print("Reg Bot ready!")
def test_listDependencies_recursive(self): config = configuration.Configuration() config.addClassifiers = "__all__" repoUrls = ['http://repo.maven.apache.org/maven2/'] gavs = ['com.sun.faces:jsf-api:2.0.11', 'org.apache.ant:ant:1.8.0'] dependencies = { 'junit:junit:pom:3.8.2': set(['']), 'junit:junit:jar:3.8.2': set(['', 'sources', 'javadoc']), 'xerces:xercesImpl:pom:2.9.0': set(['']), 'xerces:xercesImpl:jar:2.9.0': set(['']), 'xml-apis:xml-apis:pom:1.3.04': set(['']), 'xml-apis:xml-apis:jar:1.3.04': set(['', 'source', 'sources']), 'javax.el:javax.el-api:pom:2.2.1': set(['']), 'javax.el:javax.el-api:jar:2.2.1': set(['', 'sources', 'javadoc']), 'xml-resolver:xml-resolver:pom:1.2': set(['']), 'xml-resolver:xml-resolver:jar:1.2': set(['', 'sources']), 'javax.servlet:servlet-api:pom:2.5': set(['']), 'javax.servlet:servlet-api:jar:2.5': set(['', 'sources']), 'javax.servlet.jsp:jsp-api:pom:2.1': set(['']), 'javax.servlet.jsp:jsp-api:jar:2.1': set(['', 'sources']), 'org.apache.ant:ant-launcher:pom:1.8.0': set(['']), 'org.apache.ant:ant-launcher:jar:1.8.0': set(['']), 'javax.servlet.jsp.jstl:jstl-api:pom:1.2': set(['']), 'javax.servlet.jsp.jstl:jstl-api:jar:1.2': set(['', 'sources', 'javadoc']), 'javax.servlet:javax.servlet-api:pom:3.0.1': set(['']), 'javax.servlet:javax.servlet-api:jar:3.0.1': set(['', 'sources', 'javadoc']), 'javax.servlet.jsp:javax.servlet.jsp-api:pom:2.2.1': set(['']), 'javax.servlet.jsp:javax.servlet.jsp-api:jar:2.2.1': set(['', 'sources', 'javadoc']) } expectedArtifacts = self._getExpectedArtifacts(repoUrls[0], dependencies) builder = artifact_list_builder.ArtifactListBuilder(config) actualArtifacts = builder._listDependencies(repoUrls, gavs, True, None, False) self.assertEqualArtifactList(expectedArtifacts, actualArtifacts)
def elaborate_data(elaborate, config, invariants): print("==== Starting data elaboration ====") # extract the input file name input_file = do_manual_substitution(elaborate.input_file.currValue(), config) print("\t*** The skeleton for input files is: %s ***" % input_file) dir_skel = os.path.dirname(input_file) file_skel = os.path.basename(input_file) # create an iterator through all the directories spawned by this benchmark dc = configuration.Configuration() for param_name in extract_parameters(dir_skel): dc += config.parameters[param_name] fc = configuration.Configuration() for param_name in extract_parameters(file_skel): fc += config.parameters[param_name] # now iterate through all the directories for it in iterator.ConfigIterator(dc, invariants): # for each directory we list the files and look for files which have been generated by the benchmark curr_dir = dir_skel.format(**it.parameters) print("\t*** Looking up directory: %s ***" % curr_dir) for file in os.listdir(curr_dir): if not file.startswith('~'): # skip raw files continue print("\t\t-> Opening file:", file) p = re.compile('-{0,1}[a-zA-Z0-9]+') file_name_vals = [ config_parse.convert(x.group()) for x in p.finditer(os.path.splitext(file)[0]) ] # check number of arguments in file name if len(file_name_vals) != len(fc): print( '\t\t\t# Wrong number of elements in file name: found %d expected %d #, skipping file!' % (len(file_name_vals), len(fc))) continue # if the number of args is correct we now set the configuration values i = 0 for param_name in fc.parameter_keys(): fc.parameters[param_name].setValue(file_name_vals[i]) i += 1
def scheduled_job(): c = configuration.Configuration() p = async_html_parser.HtmlParser(c) m = mail_sender.MailSender(c) m.send_zip(p.process_async())
def __init__(self, fake=False): self.fake = fake if fake: self.table_name = self.fake_table_name self.ddb = ddb.DDB(self.table_name, [('id', 'S')]) self.table = self.ddb.get_table() self.users = {} self.userhash = userhash.UserHash(fake=fake) self.configuration = configuration.Configuration(fake=fake) self.modified = {}
def main(): #make a list of algorithms functions = [] for algorithm in att.ALGORITHMS: functions.append(getattr(conf.Configuration(), algorithm)) #execute each configuration with Pool(processes=att.THREADS) as p: p.starmap(call_function, zip(functions))
def setUp(self) -> None: self.configurationService = configuration.Configuration() # reads and parses initial configuration file with open( self.configurationService. shared_memory_manager_dict["config_file"], "r") as f: raw = f.read() self.configurationService.shared_memory_manager_dict[ "config_data"], _flag, _error = configuration.parse(raw, yaml=True)
def draw_gap(file_name): cfg = configuration.Configuration(file_name=file_name) gap, a, b = max_backwards(cfg.path.points) path = cfg.path.points movie = Movie() movie.background([(cfg, "black")]) movie.background([(circle.Circle(path[a], cfg.cheerio_radius / 2), "green")]) movie.background([(circle.Circle(path[b], cfg.cheerio_radius / 2), "green")]) movie.just_draw() exit(0)
def remote_sensing(): count = 0 count_good = 0 for file_name in misc.all_file_names(): cfg = configuration.Configuration(file_name=file_name) count1, count_good1 = remote_sensing1(cfg) count += count1 count_good += count_good1 print(count, count_good, count_good/count) exit(0)
def __init__(self, fake=False): self.fake = fake if fake: self.table_name = self.fake_table_name self.ddb = ddb.DDB(self.table_name, [('slack_uid', 'S')]) self.table = self.ddb.get_table() self.users = {} self.configuration = configuration.Configuration(fake=fake) self.modified = {} self.uc = user_created.UserCreated()
def main(): """ Usage: python main.py [ -c config_file -s config_section ] """ parser = argparse.ArgumentParser() parser.add_argument('-c', '--config_file', default="default.ini") parser.add_argument('-s', '--config_section', default="DEFAULT") args = parser.parse_args() config_file = args.config_file #"default.ini" config_section = args.config_section #"DEFAULT" # "DISJOINT" "TEST" CONFIG = configuration.Configuration(config_file, config_section) n_seed = int(CONFIG.get("random_seed")) if n_seed != -1: random.seed(n_seed) # for reproducibility else: n_seed = None n_run = int(CONFIG.get("n_run")) knn = int(CONFIG.get("knn")) model_type = CONFIG.get("model_type") prediction_type = CONFIG.get("prediction_type") features = set(CONFIG.get("features").split("|")) recalculate_similarity = CONFIG.get_boolean("recalculate_similarity") disjoint_cv = CONFIG.get_boolean("disjoint_cv") try: split_both = CONFIG.get_boolean("pairwise_disjoint") except: split_both = False output_file = CONFIG.get("output_file") n_fold = int(CONFIG.get("n_fold")) n_proportion = int(CONFIG.get("n_proportion")) n_subset = int(CONFIG.get("n_subset")) # for faster results - subsampling drug_disease_file = CONFIG.get("drug_disease_file") drug_side_effect_file = CONFIG.get("drug_side_effect_file") drug_structure_file = CONFIG.get("drug_structure_file") drug_target_file = CONFIG.get("drug_target_file") # Get data data = get_data(drug_disease_file, drug_side_effect_file, drug_structure_file, drug_target_file) # Check prediction accuracy of ML classifier on the data set using the parameters above check_ml(data, n_run, knn, n_fold, n_proportion, n_subset, model_type, prediction_type, features, recalculate_similarity, disjoint_cv, split_both, output_file, model_fun=None, n_seed=n_seed) return
def new(self): self.testReceptionPage.destroy() self.configurationPage.destroy() self.calibrationPage.destroy() self.autrePage.destroy() self.testReceptionPage = tR.TestReception(fenetre_principale=self) self.testReceptionPage.pack() self.configurationPage = conf.Configuration(fenetre_principale=self) self.calibrationPage = calib.Calibration(fenetre_principale=self) self.autrePage = autr.Autres(fenetre_principale=self)
def __init__(self, dbus_conn, object_path='/org/sugarlabs/listens/recognizer'): dbus.service.Object.__init__(self, dbus_conn, object_path) self._config = configuration.Configuration() self._language_model = self._config.language_models['en'][0] self._acoustic_model = self._config.acoustic_models['en'] self._phonetic_dictionary = self._config.phonetic_dictionaries['en'] self._language_model_param = self._config.language_models['en'][1] self._pipeline = None self._muted = False