def gettid(terminfos, ignore=False): termnumflag = not ignore config = Config('data/config.txt', '$') k = config.get('termnum') if not termnumflag and \ k and \ re.match(r'\d+$',k) and \ 0<=eval(k)<=len(terminfos)+1: if 1 <= int(k) <= len(terminfos) + 1: t = '第' + str(k) elif k == '0': t = '最新' termnum = int(k) - 1 print('已自动配置下载{}学期课程'.format(t)) else: for termnum in range(len(terminfos)): terminfo = terminfos[termnum] print('第%d次开课:' % (termnum + 1) + terminfo['text'] + ',课程号:' + terminfo['id']) while True: k = input('想下哪个学期的课呢?(最新学期请输入0)') try: if 0 <= int(k) <= len(terminfos) + 1: termnum = int(k) - 1 break else: print('我可不会穿越哦~') except: print('这是啥?') config.termnum = str(termnum + 1) config.save() return terminfos[termnum]['id']
def getloadtype(ignore=False): def check_loadtype(k): if '1' in k or '3' in k or '4' in k or 'all' in k: if 'all' in k: loadtype = [1, 3, 4] else: loadtype = [] for i in k: if i in '134': loadtype.append(int(i)) else: print('不对不对,这个我不认识!') loadtype = [] return loadtype loadtypeflag = not ignore config = Config('data/config.txt', '$') k = config.get('loadtype') if not loadtypeflag and \ check_loadtype(k): loadtype = check_loadtype(k) print('已自动配置下载类型为:' + k + '(1:视频,3:pdf,4:附件,all:全部)') else: while True: k = input('您想下载哪种课件呐?(1:视频,3:pdf,4:附件,all:全部)') loadtype = check_loadtype(k) if loadtype: break config.loadtype = k config.save() return loadtype
def getroot(ignore=False): rootflag = not ignore config = Config('data/config.txt', '$') flag = 0 rootname = platform.system() + 'Root' if config.get(rootname) and os.path.exists(config.get(rootname)): if rootflag: k = input('您上次把课件存到了:{},要不要继续使用这个路径呀?[y/n]'.format( config.get(rootname))) if k[0] in 'Yy': flag = 1 else: print('路径已自动配置:' + config.get(rootname)) flag = 1 if flag: root = config.get(rootname) else: while True: root = input('想存到哪里呢?:') if os.path.exists(root): print('嗯嗯,我记住啦') break else: print('这个路径不存在呀!') config.set(rootname, root) config.save() return root
def __init__(self, size: int, virus: Virus): config = Config() self._size = size self._indexes = np.arange(size) self._ill = np.zeros(size).astype(bool) self._illness_days = np.ones(size) * -1 self._illness_days_start = np.ones(size) * -1 self._health_condition = np.random.random(size) self._need_hospitalization = np.zeros(size).astype(bool) self._hospitalization_start = np.random.poisson( config.get('hospitalization_start'), size) self._hospitalization_percentage = config.get( 'hospitalization_percentage') self._is_new_case = np.zeros(size).astype(bool) self._is_immune = np.zeros(size).astype(bool) self._is_alive = np.ones(size).astype(bool) self._infectious_start = np.random.poisson( config.get('infectious_start'), size) self._mean_stochastic_interactions = config.get( 'population', 'mean_stochastic_interactions') self._mean_periodic_interactions = config.get( 'population', 'mean_periodic_interactions') self._virus = virus self._day_i = 0
def main(argv): #default: M = 'yolov3' gpu = '0' path = None try: opts, args = getopt.getopt(argv[1:], 'hm:p:g:', ['m=', 'path=', 'gpu=']) except getopt.GetoptError: print(argv[0] + ' -m <M> -p <path> -g <gpu>') sys.exit(2) for opt, arg in opts: if opt == '-h': print(argv[0] + ' -m <M> -p <path> -g <gpu>') elif opt in ['-m', '--M']: M = arg elif opt in ['-p', '--path']: path = arg elif opt in ['-g', '--gpu']: gpu = arg if path == None: raise ValueError('you should specify the model path via [python convertor -p /path/to/model/weights]') print('model: [%s], gpu: [%s], weights: [%s]'%(M, gpu, path)) os.environ["CUDA_VISIBLE_DEVICES"] = gpu config = Config(M) config.mgn = True model = MODELS(config = config).model load_weights_by_name(model, path) load_weights_by_name(model, os.path.join(parpath, 'pretrained_weights/%s.h5'%M)) saved_path = os.path.join(parpath, 'saved_weights/%s_reid.h5'%M) print('weights saving to %s'%saved_path) model.save_weights(saved_path)
def get_product_id(self): con = cx_Oracle.connect(Config().get_oracle_connect()) cur = con.cursor() cur.execute( "select product_id from product t where t.merchantid=(select merchantid from user_merchant u where u.userid='{0}')" .format(self.userid)) return cur.fetchone()[0]
def __init__(self): redis_config = Config().get('redis') redis_host = redis_config['host'] redis_port = redis_config['port'] pool = redis.ConnectionPool(host=redis_host, port=redis_port, decode_responses=True) self.r = redis.Redis(connection_pool=pool)
def run_simulation() -> TimeSeriesResult: config = Config() population_size = 450000 virus = Virus.from_string(config.get('virus', 'name')) n_days = config.get('simulation_days') population_centre = PopulationCentreBase( name='Mock city', longitude=17.1, latitude=48.15, populations=[PopulationBase(int(population_size / 10), virus) for i in range(10)], virus=virus ) population_centre.infect(50) for day_i in range(n_days): if day_i % 10 == 0: logging.info(f'day: {day_i}') population_centre.next_day() return TimeSeriesResult( simulation_days=population_centre.simulation_days, infected=population_centre.infected, unaffected=population_centre.unaffected, immune=population_centre.immune, dead=population_centre.dead, new_cases=population_centre.new_cases )
def get_brand_ids(self): con = cx_Oracle.connect(Config().get_oracle_connect()) cur = con.cursor() cur.execute( "select brand_id from m_product_brand t where t.userid='{0}'". format(self.userid)) return cur.fetchall()
def test_PSA_overrides(target_start_size): target, start, size = target_start_size set_targets_json_location() config = Config(target) roms = config.get_all_active_memories(ROM_ALL_MEMORIES) assert("ROM" in roms) assert(roms["ROM"] == [start, size])
class TestBaiDu(unittest.TestCase): url = Config().get('url') excel = DATA_PATH + '/test_data.xlsx' # base_path = os.path.dirname(os.path.abspath(__file__)) + '\..' # driver_path = os.path.abspath(base_path+'\drivers\chromedriver.exe') # print(driver_path) # locator_kw = (By.ID,'kw') # locator_su = (By.ID,'su') # locator_result = (By.XPATH,'//div[contains(@class,"result")]/h3/a') # log = Log() # def sub_setUp(self): # self.dr = webdriver.Chrome(executable_path=DRIVER_PATH+'\chromedriver.exe') # self.dr.get(self.url) # def sub_tearDown(self): # self.dr.quit() # def test_search(self): # datas = ExcelReader(self.excel).data # for d in datas: # with self.subTest(data=d): # self.sub_setUp() # self.dr.find_element(*self.locator_kw).send_keys(d['search']) # self.dr.find_element(*self.locator_su).click() # time.sleep(2) # links = self.dr.find_elements(*self.locator_result) # for link in links: # self.log.info(link.text) # self.sub_tearDown() def setUp(self): self.dr = browser(browser_type='firefox') # self.dr = webdriver.Chrome(executable_path=DRIVER_PATH+'\chromedriver.exe') # self.page.get(self.url) def tearDown(self): self.dr.quit() def test_search_0(self): # self.dr.find_element(*self.locator_kw).send_keys('selenium') # self.dr.find_element(*self.locator_su).click() # time.sleep(2) # links = self.dr.find_elements(*self.locator_result) # for link in links: # self.log.info(link.text) baidu = BaiDuMainPage(self.dr) baidu.open(self.url) logger.info('open url') baidu.search('selenium') baidu.save_screen_shot(REPORT_PATH) logger.info('search selenium')
def get_config(src_path, target, toolchain_name): # Convert src_path to a list if needed src_paths = [src_path] if type(src_path) != ListType else src_path # We need to remove all paths which are repeated to avoid # multiple compilations and linking with the same objects src_paths = [src_paths[0]] + list(set(src_paths[1:])) # Create configuration object config = Config(target, src_paths) # If the 'target' argument is a string, convert it to a target instance if isinstance(target, str): try: target = TARGET_MAP[target] except KeyError: raise KeyError("Target '%s' not found" % target) # Toolchain instance try: toolchain = TOOLCHAIN_CLASSES[toolchain_name](target, options=None, notify=None, macros=None, silent=True, extra_verbose=False) except KeyError as e: raise KeyError("Toolchain %s not supported" % toolchain_name) # Scan src_path for config files resources = toolchain.scan_resources(src_paths[0]) for path in src_paths[1:]: resources.add(toolchain.scan_resources(path)) config.add_config_files(resources.json_files) return config.get_config_data()
def getmobile(self): con = cx_Oracle.connect(Config().get_oracle_connect()) cur = con.cursor() cur.execute( "select mobile from user_info t where t.userid='{0}'".format( self.userid)) return cur.fetchone()[0]
def __init__(self, asymptomatic_ratio: float, hospitalized_ratio: float): self._config = Config() self.illness_days_mean = self._config.get('virus', 'infectious_days_mean') self.illness_days_std = self._config.get('virus', 'infectious_days_std') self.transmission_probability = self._config.get( 'virus', 'transmission_probability') self.asymptomatic_ratio = asymptomatic_ratio self.hospitalized_ratio = hospitalized_ratio self.mild_symptoms_ratio = 1 - hospitalized_ratio - asymptomatic_ratio input_data = InputData() mean_periodic_interactions = self._config.get( 'population', 'mean_periodic_interactions') mean_stochastic_interactions = self._config.get( 'population', 'mean_stochastic_interactions') mean_interactions = mean_periodic_interactions + mean_stochastic_interactions self.R = (1 + input_data.mean_travel_ratio) * \ mean_interactions * self.illness_days_mean * self.transmission_probability logging.info( f'Initialized the {self.__class__.__name__} virus with R0={self.R:.4f}' )
def get_username_from_db(self, levelname): con = cx_Oracle.connect(Config().get_oracle_connect()) cur = con.cursor() cur.execute( "select levelid from user_level t where t.levelname='{0}'".format( levelname)) return cur.fetchone()[0]
def test_bl_too_large(self, mock_intelhex_offset, mock_exists, mock_isabs): """ Create a BL that's too large to fit in ROM and test that exception is generated. :param mock_intelhex_offset: mock intel hex :param mock_exists: mock the file exists call :param mock_isabs: mock the isabs call :return: """ cfg = Config('NRF52_DK') mock_exists.return_value = True mock_isabs.return_value = True # setup the hex file bl = IntelHex() min = 0x0 max = 0x88000 for v in range(max): bl[v] = v mock_intelhex_offset.return_value = bl cfg.target.bootloader_img = True ce = False if cfg.has_regions: try: for r in list(cfg.regions): print(r) except ConfigException as e: print("args %s" % (e.args)) if (e.args[0] == "bootloader segments don't fit within rom"): ce = True self.assertTrue(ce)
def getmerchantid(self): u"""通过数据库获取商户merchant_id""" con = cx_Oracle.connect(Config().get_oracle_connect()) cur = con.cursor() cur.execute( "select merchantid from user_merchant t where t.userid='{0}'". format(self.userid)) return cur.fetchone()[0]
def __init__(self, dataset, detector = 'yolov3', experiment_name = 'default', overwrite = False): self.detector = detector self.dataset = dataset self.overwrite = overwrite self.experiment_name = experiment_name self.checkdir() self.config = Config(detector) self.DA = DA('validation', self.config)
def get_not_receive_order_from_db(self): import cx_Oracle con = cx_Oracle.connect(Config().get_oracle_connect()) cur = con.cursor() cur.execute( "select order_id from m_order t where t.meruserid='{0}' and t.status='4'" .format(self.userid)) return cur.fetchone()[0]
def main(): args = parse_args() if not os.path.isdir(args.save_prefix): os.makedirs(args.save_prefix) config = Config(args.config_filename) roidb = get_dataset(args.dataset, args) sym = get_network(args.network, args, config, 'train') train_net(sym, roidb, args, config)
def get_order_ids_from_db(self): import cx_Oracle con = cx_Oracle.connect(Config().get_oracle_connect()) cur = con.cursor() cur.execute("select order_id from m_order t where t.userid='{0}'".format(self.userid)) order_ids = [] for i in cur.fetchall(): order_ids.append(i[0]) return order_ids
def scan_and_copy_resources(self, prj_paths, trg_path, relative=False): # Copy only the file for the required target and toolchain lib_builds = [] # Create the configuration object if isinstance(prj_paths, basestring): prj_paths = [prj_paths] config = Config(self.target, prj_paths) for src in ['lib', 'src']: resources = self.__scan_and_copy(join(prj_paths[0], src), trg_path) for path in prj_paths[1:]: resources.add(self.__scan_and_copy(join(path, src), trg_path)) lib_builds.extend(resources.lib_builds) # The repository files #for repo_dir in resources.repo_dirs: # repo_files = self.__scan_all(repo_dir) # for path in prj_paths: # self.toolchain.copy_files(repo_files, trg_path, rel_path=join(path, src)) # The libraries builds for bld in lib_builds: build_url = open(bld).read().strip() lib_data = self.build_url_resolver(build_url) lib_path = lib_data['path'].rstrip('\\/') self.__scan_and_copy(lib_path, join(trg_path, lib_data['name'])) # Create .hg dir in mbed build dir so it's ignored when versioning hgdir = join(trg_path, lib_data['name'], '.hg') mkdir(hgdir) fhandle = file(join(hgdir, 'keep.me'), 'a') fhandle.close() if not relative: # Final scan of the actual exported resources resources = self.toolchain.scan_resources(trg_path) resources.relative_to(trg_path, self.DOT_IN_RELATIVE_PATH) else: # use the prj_dir (source, not destination) resources = self.toolchain.scan_resources(prj_paths[0]) for path in prj_paths[1:]: resources.add(toolchain.scan_resources(path)) # Loads the resources into the config system which might expand/modify resources based on config data self.resources = config.load_resources(resources) if hasattr(self, "MBED_CONFIG_HEADER_SUPPORTED" ) and self.MBED_CONFIG_HEADER_SUPPORTED: # Add the configuration file to the target directory self.config_header = self.toolchain.MBED_CONFIG_FILE_NAME config.get_config_data_header(join(trg_path, self.config_header)) self.config_macros = [] self.resources.inc_dirs.append(".") else: # And add the configuration macros to the toolchain self.config_macros = config.get_config_data_macros()
def main(): args = parse_args() if not os.path.isdir(args.prefix): os.makedirs(args.prefix) imdb = get_dataset(args.dataset, args) config = Config(args.config_filename) sym = get_network(args.network, args, config, 'test') test_net(sym, imdb, args, config)
class TestBaidu(unittest.TestCase): url = Config().get('url') def setUp(self): self.client = HTTPClient(url=self.url, method='GET') def test_baidu_http(self): res = self.client.send() # logger.debug(res.text) # self.assertIn('百度一下', res.text) assertHTTPCode(res,[200])
def get_config(src_path, target, toolchain_name): # Convert src_path to a list if needed src_paths = [src_path] if type(src_path) != ListType else src_path # We need to remove all paths which are repeated to avoid # multiple compilations and linking with the same objects src_paths = [src_paths[0]] + list(set(src_paths[1:])) # Create configuration object config = Config(target, src_paths) # If the 'target' argument is a string, convert it to a target instance if isinstance(target, str): try: target = TARGET_MAP[target] except KeyError: raise KeyError("Target '%s' not found" % target) # Toolchain instance try: toolchain = TOOLCHAIN_CLASSES[toolchain_name](target, options=None, notify=None, macros=None, silent=True, extra_verbose=False) except KeyError as e: raise KeyError("Toolchain %s not supported" % toolchain_name) # Scan src_path for config files resources = toolchain.scan_resources(src_paths[0]) for path in src_paths[1:]: resources.add(toolchain.scan_resources(path)) # Update configuration files until added features creates no changes prev_features = set() while True: # Update the configuration with any .json files found while scanning config.add_config_files(resources.json_files) # Add features while we find new ones features = config.get_features() if features == prev_features: break for feature in features: if feature in resources.features: resources += resources.features[feature] prev_features = features config.validate_config() cfg, macros = config.get_config_data() features = config.get_features() return cfg, macros, features
def inner(options): if not options.payload and options.mcu and options.build: mcus = extract_mcus(MbedExtendedArgs(), options) sources = options.source_dir or ['.'] config = Config(mcus[0], sources) app_name = config.name or basename(abspath(sources[0])) payload_name = join( options.build, generate_update_filename(app_name, config.target)) options.payload = open(payload_name, "rb") return func(options)
def prepare_toolchain(src_paths, target, toolchain_name, macros=None, options=None, clean=False, jobs=1, notify=None, silent=False, verbose=False, extra_verbose=False, config=None): """ Prepares resource related objects - toolchain, target, config src_paths: the paths to source directories target: ['LPC1768', 'LPC11U24', 'LPC2368'] toolchain_name: ['ARM', 'uARM', 'GCC_ARM', 'GCC_CR'] clean: Rebuild everything if True notify: Notify function for logs verbose: Write the actual tools command lines if True """ # We need to remove all paths which are repeated to avoid # multiple compilations and linking with the same objects src_paths = [src_paths[0]] + list(set(src_paths[1:])) # If the configuration object was not yet created, create it now config = config or Config(target, src_paths) # If the 'target' argument is a string, convert it to a target instance if isinstance(target, basestring): try: target = TARGET_MAP[target] except KeyError: raise KeyError("Target '%s' not found" % target) # Toolchain instance try: toolchain = TOOLCHAIN_CLASSES[toolchain_name]( target, options, notify, macros, silent, extra_verbose=extra_verbose) except KeyError as e: raise KeyError("Toolchain %s not supported" % toolchain_name) toolchain.config = config toolchain.jobs = jobs toolchain.build_all = clean toolchain.VERBOSE = verbose return toolchain
def inner(options): if not options.payload and options.mcu and options.build: mcus = extract_mcus(MbedExtendedArgs(), options) sources = options.source_dir or ['.'] config = Config(mcus[0], sources) app_name = config.name or basename(abspath(sources[0])) output_ext = getattr(config.target, "OUTPUT_EXT", "bin") payload_name = join( options.build, "{}_application.{}".format(app_name, output_ext)) options.payload = open(payload_name, "rb") return func(options)
def __init__(self, name='root', log_path=LOG_PATH): #文件的命名 c = Config().get('log') self.logname = os.path.join(log_path, '%s.log' % time.strftime('%Y_%m_%d')) self.logger = logging.getLogger(name) self.logger.setLevel(logging.DEBUG) #日志输出格式 pattern = c.get('pattern') if c and c.get( 'pattern') else '[%(asctime)s]-%(name)s-%(levelname)s: %(message)s' self.formatter = logging.Formatter(pattern)
def _getbestid(self): u"""通过数据库获取绑定的best_id""" con = cx_Oracle.connect(Config().get_oracle_connect()) cur = con.cursor() cur.execute( "select bestid from u_bestbinding t where t.userid='{0}'".format( self.userid)) try: return cur.fetchone()[0] except TypeError: print 'merchant did not bind a BEST id!' return None