class ConfigReader(object): """ 为傲世堂的游戏项目配置文件定制的配置读取类。 陈超写的arg.gameOption耦合性太强,只能在bible内使用。 但是配置文件的结构设计的很合理。 此类就是根据原来的结构设计重新写的解耦并且适用性更广的类。 Example:: conf = ConfigReader(game, region) ip = conf.get("mobile_www_ip") if conf.has_option("mobile_www_port") port = conf.getint("mobile_www_port") """ def __init__(self, game, section, conf_dir='/app/opbin/work/bible/conf'): self.game = game self.section = section self.conf_file = '{}/{}.conf'.format(conf_dir.rstrip('/'), self.game) self.config = ConfigParser() self.config.read(self.conf_file) self.has_section = self.config.has_section(self.section) def has_option(self, option): return self._has_option(self.section, option) or self._has_option('common', option) def _has_option(self, section, option): return self.config.has_option(section, option) def get(self, option, raw=0, var=None): if self._has_option(self.section, option): return self.config.get(self.section, option, raw, var) elif self._has_option('common', option): return self.config.get('common', option, raw, var) else: raise Exception("Can't find option: {} in {}".format(option, self.conf_file)) def getint(self, option): if self._has_option(self.section, option): return self.config.getint(self.section, option) elif self._has_option('common', option): return self.config.getint('common', option) else: raise Exception("Can't find option: {} in {}".format(option, self.conf_file)) def getfloat(self, option): if self._has_option(self.section, option): return self.config.getfloat(self.section, option) elif self._has_option('common', option): return self.config.getfloat('common', option) else: raise Exception("Can't find option: {} in {}".format(option, self.conf_file)) def getboolean(self, option): if self._has_option(self.section, option): return self.config.getboolean(self.section, option) elif self._has_option('common', option): return self.config.getboolean('common', option) else: raise Exception("Can't find option: {} in {}".format(option, self.conf_file))
def read_metadata(filename): if filename.endswith('bz2'): fname = os.path.splitext(filename)[0] else: fname = filename if os.path.splitext(fname)[1] == '.cbf': try: import pycbf except ImportError: raise NeXusError('Reading CBF files requires the pycbf module') cbf = pycbf.cbf_handle_struct() cbf.read_file(fname, pycbf.MSG_DIGEST) cbf.select_datablock(0) cbf.select_category(0) cbf.select_column(1) meta_text = cbf.get_value().splitlines() date_string = meta_text[2][2:] time_stamp = epoch(date_string) exposure = float(meta_text[5].split()[2]) summed_exposures = 1 return time_stamp, exposure, summed_exposures elif os.path.exists(fname+'.metadata'): parser = ConfigParser() parser.read(fname+'.metadata') return (parser.getfloat('metadata', 'timeStamp'), parser.getfloat('metadata', 'exposureTime'), parser.getint('metadata', 'summedExposures')) else: return time.time(), 1.0, 1
def __init__(self): defaults = getDefaults() config = ConfigParser() config.read(defaults) self.tapertype = config.get('signal', 'tapertype') self.taperwidth = config.getfloat('signal', 'taperwidth') self.lsqr = config.get('mccc', 'lsqr') self.ofilename = config.get('mccc', 'ofilename') self.tapertype = config.get('signal', 'tapertype') self.taperwidth = config.getfloat('signal', 'taperwidth') self.exwt = config.getfloat('mccc', 'extraweight') self.srate = config.getfloat('mccc', 'srate') self.rcfile = config.get('mccc', 'rcfile') self.evlist = config.get('mccc', 'evlist') self.fstack = config.get('iccs', 'fstack') # SAC headers for time window, trace selection, and quality factors self.twhdrs = config.get('sachdrs', 'twhdrs').split() self.hdrsel = config.get('sachdrs', 'hdrsel') # SAC headers for MCCC time picks self.ipick, self.wpick = config.get('sachdrs', 'mchdrs').split() # Choose a xcorr module and function self.shift = config.getint('mccc', 'shift') modu = config.get('mccc', 'xcorr_modu') func = config.get('mccc', 'xcorr_func') cmd = 'from %s import %s; xcorr=%s' % (modu, func, func) exec cmd self.xcorr = xcorr self.xcorr_modu = modu self.xcorr_func = func
def read_config(filename): """Read the config file *filename* and replace the values in global variables. """ cfg = ConfigParser() cfg.read(filename) station = cfg.get("default", "station") satellites = cfg.get("default", "satellites").split(",") forward = cfg.getint("default", "forward") start = cfg.getfloat("default", "start") station_name = cfg.get(station, "name") station_lon = cfg.getfloat(station, "longitude") station_lat = cfg.getfloat(station, "latitude") station_alt = cfg.getfloat(station, "altitude") sat_scores = {} for sat in satellites: sat_scores[sat] = (cfg.getfloat(sat, "night"), cfg.getfloat(sat, "day")) area = utils.parse_area_file(cfg.get(station, "area_file"), cfg.get(station, "area"))[0] return ((station_lon, station_lat, station_alt), sat_scores, station_name, area, forward, start)
def readIni(nb): global K, N, cut, gui, distrWE, distrNS, vehphWEA, vehphNSA, maxSumFlow, tlType, intergreenLength, GSum global phaseMinWE, phaseMaxWE, phaseMinNS, phaseMaxNS, maxGap, detPos filename = 'input' + str(nb).zfill(2) + '.ini' ini = ConfigParser() ini.read(filename) K = ini.getint("general", "K") N = ini.getint("general", "N") cut = ini.getboolean("general", "cut") gui = ini.getboolean("general", "gui") distrWE = ini.get("demand", "distrWE") distrNS = ini.get("demand", "distrNS") vehphWEA = eval(ini.get("demand", "vehphWEA")) vehphNSA = eval(ini.get("demand", "vehphNSA")) maxSumFlow = ini.getint("demand", "maxSumFlow") tlType = ini.get("TL", "tlType") intergreenLength = ini.getint("TL", "intergreenLength") GSum = ini.getfloat("TL", "GSum") [phaseMinWE, phaseMaxWE] = eval(ini.get("TL", "phaseMinMaxWE")) [phaseMinNS, phaseMaxNS] = eval(ini.get("TL", "phaseMinMaxNS")) maxGap = ini.getfloat("TL", "maxGap") detPos = ini.getfloat("TL", "detPos") return filename
def __init__(self): config = ConfigParser() defaults = getDefaults() config.read(defaults) # SAC headers for time window, trace selection, and quality factors self.twhdrs = config.get('sachdrs', 'twhdrs').split() self.hdrsel = config.get('sachdrs', 'hdrsel') self.qfactors = config.get('sachdrs', 'qfactors').split() self.qheaders = config.get('sachdrs', 'qheaders').split() self.qweights = [ float(val) for val in config.get('sachdrs', 'qweights').split() ] # SAC plots self.figsize = [ float(val) for val in config.get('sacplot', 'figsize').split() ] self.rectseis = [ float(val) for val in config.get('sacplot', 'rectseis').split() ] self.colorwave = config.get('sacplot', 'colorwave') self.colorwavedel = config.get('sacplot', 'colorwavedel') self.colortwfill = config.get('sacplot', 'colortwfill') self.colortwsele = config.get('sacplot', 'colortwsele') self.alphatwfill = config.getfloat('sacplot', 'alphatwfill') self.alphatwsele = config.getfloat('sacplot', 'alphatwsele') self.npick = config.getint('sacplot', 'npick') self.pickcolors = config.get('sacplot', 'pickcolors') self.pickstyles = config.get('sacplot', 'pickstyles').split() self.minspan = config.getint('sacplot', 'minspan') self.srate = config.getfloat('sacplot', 'srate') self.tapertype = config.get('signal', 'tapertype') self.taperwidth = config.getfloat('signal', 'taperwidth')
def get_ic_factor(self, det): # storing ic_factor in preferences causing issues # ic_factor stored in detectors.cfg p = os.path.join(paths.spectrometer_dir, 'detectors.cfg') # factors=None ic = 1, 1e-20 if os.path.isfile(p): c = ConfigParser() c.read(p) det = det.lower() for si in c.sections(): if si.lower() == det: v, e = 1, 1e-20 if c.has_option(si, 'ic_factor'): v = c.getfloat(si, 'ic_factor') if c.has_option(si, 'ic_factor_err'): e = c.getfloat(si, 'ic_factor_err') ic = v, e break else: self.debug('no detector file {}. cannot retrieve ic_factor'.format(p)) r = ufloat(*ic) return r
def compileBlock(configFile, binFile): config = ConfigParser() config.read(configFile) block = (configVersion, ) block += (config.getint("radio", "channel"),) block += (speeds.index(config.get("radio", "speed").upper()),) block += (config.getfloat("calib", "pitchTrim"),) block += (config.getfloat("calib", "rollTrim"),) bin = struct.pack(structFormat, *block) #Adding some magic: bin = "0xBC" + bin bin += struct.pack("B", 256-checksum256(bin)) #print("Config block checksum: %02x" % bin[len(bin)-1]) bfile = open(binFile, "w") bfile.write(bin) bfile.close() print "Config block compiled successfully to", binFile
def read_header(folder, n_part, input_): global config config = ConfigParser() config.read(input_) h_data = [] for j in n_part: # n_part h_data.append(int(j)) for j in config.get('header', 'mass_array').split(','): h_data.append(float(j)) h_data.append(config.getfloat('header', 'time')) h_data.append(config.getfloat('header', 'redshift')) h_data.append(config.getint('header', 'flag_sfr')) h_data.append(config.getint('header', 'flag_feedback')) for j in n_part: # n_part_total, assuming equal to n_part h_data.append(int(j)) h_data.append(config.getint('header', 'flag_cooling')) h_data.append(config.getint('header', 'num_files')) h_data.append(config.getfloat('header', 'boxsize')) h_data.append(config.getfloat('header', 'omega0')) h_data.append(config.getfloat('header', 'omega_lambda')) h_data.append(config.getfloat('header', 'hubble_param')) h_data.append(config.getint('header', 'flag_age')) h_data.append(config.getint('header', 'flag_metals')) # blank, present in the header for i in np.arange(88): h_data.append('\0') s = struct.Struct('iiiiii dddddd d d i i iiiiii i i dddd ii cccc\ cccccccccccccccccccccccccccccccccccccccccccccccccc\ cccccccccccccccccccccccccccccccccc') packed_data = s.pack(*h_data) # Need raw h_data as well - D. Rennehan return packed_data, h_data
def __init__(self): defaults = getDefaults() config = ConfigParser() config.read(defaults) self.tapertype = config.get('signal', 'tapertype') self.taperwidth = config.getfloat('signal', 'taperwidth') self.maxiter = config.getint('iccs', 'maxiter') self.convepsi = config.getfloat('iccs', 'convepsi') self.convtype = config.get('iccs', 'convtype') self.stackwgt = config.get('iccs', 'stackwgt') self.srate = config.getfloat('iccs', 'srate') self.fstack = config.get('iccs', 'fstack') # SAC headers for time window, trace selection, and quality factors self.twhdrs = config.get('sachdrs', 'twhdrs').split() self.hdrsel = config.get('sachdrs', 'hdrsel') self.qfactors = config.get('sachdrs', 'qfactors').split() self.qheaders = config.get('sachdrs', 'qheaders').split() self.qweights = [ float(val) for val in config.get('sachdrs', 'qweights').split() ] # SAC headers for ICCS time picks self.ichdrs = config.get('sachdrs', 'ichdrs').split() # Choose a xcorr module and function self.shift = config.getint('iccs', 'shift') modu = config.get('iccs', 'xcorr_modu') func = config.get('iccs', 'xcorr_func') cmd = 'from %s import %s; xcorr=%s' % (modu, func, func) exec cmd self.xcorr = xcorr self.xcorr_modu = modu self.xcorr_func = func
def __init__(self): config = ConfigParser() defaults = getDefaults() config.read(defaults) # SAC headers for time window, trace selection, and quality factors self.twhdrs = config.get("sachdrs", "twhdrs").split() self.hdrsel = config.get("sachdrs", "hdrsel") self.qfactors = config.get("sachdrs", "qfactors").split() self.qheaders = config.get("sachdrs", "qheaders").split() self.qweights = [float(val) for val in config.get("sachdrs", "qweights").split()] # SAC plots self.figsize = [float(val) for val in config.get("sacplot", "figsize").split()] self.rectseis = [float(val) for val in config.get("sacplot", "rectseis").split()] self.colorwave = config.get("sacplot", "colorwave") self.colorwavedel = config.get("sacplot", "colorwavedel") self.colortwfill = config.get("sacplot", "colortwfill") self.colortwsele = config.get("sacplot", "colortwsele") self.alphatwfill = config.getfloat("sacplot", "alphatwfill") self.alphatwsele = config.getfloat("sacplot", "alphatwsele") self.npick = config.getint("sacplot", "npick") self.pickcolors = config.get("sacplot", "pickcolors") self.pickstyles = config.get("sacplot", "pickstyles").split() self.minspan = config.getint("sacplot", "minspan") self.srate = config.getfloat("sacplot", "srate") self.tapertype = config.get("signal", "tapertype") self.taperwidth = config.getfloat("signal", "taperwidth") self.thresholds = [float(val) for val in config.get("sacplot", "thresholds").split()] self.colorthresholds = config.get("sacplot", "colorthresholds").split()
def __init__(self): defaults = getDefaults() config = ConfigParser() config.read(defaults) self.tapertype = config.get("signal", "tapertype") self.taperwidth = config.getfloat("signal", "taperwidth") self.lsqr = config.get("mccc", "lsqr") self.ofilename = config.get("mccc", "ofilename") self.tapertype = config.get("signal", "tapertype") self.taperwidth = config.getfloat("signal", "taperwidth") self.exwt = config.getfloat("mccc", "extraweight") self.srate = config.getfloat("mccc", "srate") self.rcfile = config.get("mccc", "rcfile") self.evlist = config.get("mccc", "evlist") self.fstack = config.get("iccs", "fstack") # SAC headers for time window, trace selection, and quality factors self.twhdrs = config.get("sachdrs", "twhdrs").split() self.hdrsel = config.get("sachdrs", "hdrsel") # SAC headers for MCCC time picks self.ipick, self.wpick = config.get("sachdrs", "mchdrs").split() # Choose a xcorr module and function self.shift = config.getint("mccc", "shift") modu = config.get("mccc", "xcorr_modu") func = config.get("mccc", "xcorr_func") cmd = "from %s import %s; xcorr=%s" % (modu, func, func) exec cmd self.xcorr = xcorr self.xcorr_modu = modu self.xcorr_func = func
def __init__(self): defaults = getDefaults() config = ConfigParser() config.read(defaults) self.tapertype = config.get("signal", "tapertype") self.taperwidth = config.getfloat("signal", "taperwidth") self.maxiter = config.getint("iccs", "maxiter") self.convepsi = config.getfloat("iccs", "convepsi") self.convtype = config.get("iccs", "convtype") self.stackwgt = config.get("iccs", "stackwgt") self.srate = config.getfloat("iccs", "srate") self.fstack = config.get("iccs", "fstack") # SAC headers for time window, trace selection, and quality factors self.twhdrs = config.get("sachdrs", "twhdrs").split() self.hdrsel = config.get("sachdrs", "hdrsel") self.qfactors = config.get("sachdrs", "qfactors").split() self.qheaders = config.get("sachdrs", "qheaders").split() self.qweights = [float(val) for val in config.get("sachdrs", "qweights").split()] # SAC headers for ICCS time picks self.ichdrs = config.get("sachdrs", "ichdrs").split() # Choose a xcorr module and function self.shift = config.getint("iccs", "shift") modu = config.get("iccs", "xcorr_modu") func = config.get("iccs", "xcorr_func") cmd = "from %s import %s; xcorr=%s" % (modu, func, func) exec cmd self.xcorr = xcorr self.xcorr_modu = modu self.xcorr_func = func
def setUp(self): rid = '60754-10' config = ConfigParser() p = '/Users/ross/Sandbox/pychron_validation_data.cfg' config.read(p) signals = map(lambda x: map(float, x.split(',')), [config.get('Signals-{}'.format(rid), k) for k in ['ar40', 'ar39', 'ar38', 'ar37', 'ar36']]) blanks = map(lambda x: map(float, x.split(',')), [config.get('Blanks-{}'.format(rid), k) for k in ['ar40', 'ar39', 'ar38', 'ar37', 'ar36']]) irradinfo = map(lambda x: map(float, x.split(',')), [config.get('irrad-{}'.format(rid), k) for k in ['k4039', 'k3839', 'ca3937', 'ca3837', 'ca3637', 'cl3638']]) j = config.get('irrad-{}'.format(rid), 'j') j = map(lambda x: float(x), j.split(',')) baselines = [(0, 0), (0, 0), (0, 0), (0, 0), (0, 0)] backgrounds = [(0, 0), (0, 0), (0, 0), (0, 0), (0, 0)] ar37df = config.getfloat('irrad-{}'.format(rid), 'ar37df') t = math.log(ar37df) / (constants.lambda_37.nominal_value * 365.25) irradinfo.append(t) # load results r = 'results-{}'.format(rid) self.age = config.getfloat(r, 'age') self.rad4039 = config.getfloat(r, 'rad4039') self.ca37k39 = config.getfloat(r, 'ca37k39') self.age_dict = calculate_arar_age(signals, baselines, blanks, backgrounds, j, irradinfo, )
def test01(): from ConfigParser import ConfigParser CONFIGFILE='config.txt' config=ConfigParser() config.read(CONFIGFILE) print config.get('messages','greeting') radius=input(config.get('messages','question')+' ') print config.get('messages','result_message') print config.getfloat('numbers','pi')*radius**2
def load_glbv(): """load global variables from .xls""" glbv = {} glbv["path"] = "" glbv["config_file"] = "" if platform.system() == "Windows": glbv["path"] = "D:\Experiment\prefetching-simulation" glbv["config_file"] = glbv["path"]+"\project\glbv.conf" elif platform.system() == "Linux": glbv["path"] = "/home/pzy/test" glbv["config_file"] = glbv["path"]+"/glbv.conf" cf = ConfigParser() cf.read(glbv["config_file"]) glbv["tl"] = cf.getint("glbv", "tl") glbv["tn"] = cf.getint("glbv", "tn") glbv["t"] = cf.getint("glbv", "t") glbv["f"] = cf.getint("glbv", "f") glbv["n"] = cf.getint("glbv", "n") glbv["b"] = cf.getint("glbv", "b") glbv["ot"] = cf.getint("glbv", "ot") glbv["maxs"] = cf.getint("glbv", "maxs") glbv["mins"] = cf.getint("glbv", "mins") glbv["recall"] = cf.getfloat("glbv", "recall") glbv["precision"] = cf.getfloat("glbv", "precision") glbv["source"] = cf.get("glbv", "source") glbv["solver"] = cf.get("glbv", "solver") glbv["dis"] = cf.get("glbv", "dis") glbv["wrt"] = cf.get("glbv", "wrt") glbv["draw"] = cf.get("glbv", "draw") glbv["data1"] = cf.get("glbv", "data1") glbv["result1"] = cf.get("glbv", "result1") glbv["sheet_index"] = cf.getint("glbv", "sheet_index") glbv["time_col"] = cf.getint("glbv", "time_col") glbv["size_col"] = cf.getint("glbv", "size_col") glbv["start_row"] = cf.getint("glbv", "start_row") glbv["end_row"] = cf.getint("glbv", "end_row") glbv["t"] = glbv["tn"]*glbv["tl"] glbv["n"] = glbv["t"]/glbv["f"] if platform.system() == "Windows": glbv["data_file"] = glbv["path"]+"\\project\\"+glbv["data1"] glbv["result_file"] = glbv["path"]+"\\project\\"+glbv["result1"] elif platform.system() == "Linux": glbv["data_file"] = glbv["path"]+"/"+glbv["data1"] glbv["result_file"] = glbv["path"]+"/"+glbv["result1"] return glbv
def __init__(self, config_file="body_model.conf", section="BodyModel"): c = ConfigParser() if not path.exists(config_file): print 'Config file %s not found!'%config_file raise IOError c.read(config_file) self.legs = [LegModel() for i in range(NUM_LEGS)] # Leg Offsets self.LEG0_OFFSET_X = c.getfloat(section, "leg0_offset_x") self.LEG0_OFFSET_Y = c.getfloat(section, "leg0_offset_y") self.LEG0_THETA = c.getfloat(section, "leg0_theta") self.LEG1_OFFSET_X = c.getfloat(section, "leg1_offset_x") self.LEG1_OFFSET_Y = c.getfloat(section, "leg1_offset_y") self.CHASSIS_BOTTOM_Z = c.getfloat(section, "chassis_bottom_z")
def parseConfigurationFile(self, configFile): """ Parse the configuration file to get base model parameters """ # Initialize defaults defaultParams = {} # CUDA kernels are defined externally in a .cu file defaultParams["cu_dir"] = os.path.join("pyhawkes", "cuda", "cpp") defaultParams["cu_file"] = "process_id_kernels.cu" defaultParams["thin"] = 1 defaultParams["sigma"] = 0.001 defaultParams["kappa"] = 5 defaultParams["nu"] = 4 defaultParams["mu"] = "None" # Create a config parser object and read in the file cfgParser = ConfigParser(defaultParams) cfgParser.read(configFile) self.params = {} self.params["cu_dir"] = cfgParser.get("proc_id_model", "cu_dir") self.params["cu_file"] = cfgParser.get("proc_id_model", "cu_file") self.params["thin"] = cfgParser.getint("proc_id_model", "thin") self.params["blockSz"] = cfgParser.getint("cuda", "blockSz") # Parse the params for the spatial GMM model self.params["sigma0"] = cfgParser.getfloat("proc_id_model", "sigma") self.params["kap0"] = cfgParser.getfloat("proc_id_model", "kappa") self.params["nu0"] = cfgParser.getfloat("proc_id_model", "nu") # Parse mu0from config file mu0_str = cfgParser.get("proc_id_model", "mu") if mu0_str == "None": # If not specified, take the mean of the data self.params["mu0"] = np.mean(self.base.data.X, 1) else: # Filter out unwanted characters mu0_str = filter(lambda c: c.isdigit() or c=="," or c=="-" or c==".", mu0_str) self.params["mu0"] = np.fromstring(mu0_str, sep=",",dtype=np.float32) self.params["T0"] = self.params["sigma0"]*np.eye(self.base.data.D) # Parse the desired number of mixture components/processes self.params["K"] = cfgParser.getint("proc_id_model", "K")
def __init__(self, config_filename): locale.setlocale(locale.LC_ALL, '') assert os.path.isfile(config_filename), "Config file not found" local_config_parser = ConfigParser() local_config_parser.read(config_filename) product_info_filename = local_config_parser.get("Config", "info_produtos") self._printer_name = local_config_parser.get("Config", "impressora") assert os.path.isfile(product_info_filename), "Product info file not found" # Set barcode filename self._barcode_filename = os.path.join( os.path.dirname(product_info_filename), "barcode" ) cfg_parser = ConfigParser() cfg_parser.read(product_info_filename) self._primary_categories = dict(cfg_parser.items(self.PRIMARY_CATEGORY_SEC)) self._secondary_categories = dict(cfg_parser.items(self.SECONDARY_CATEGORY_SEC)) if cfg_parser.has_section(self.PRICE_SEC): self.price_list = [] for opt in sorted(cfg_parser.options(self.PRICE_SEC)): self.price_list.append(cfg_parser.getfloat(self.PRICE_SEC, opt)) else: self.price_list = [1.7, 2.21] self._label_header = cfg_parser.get("Label", "header").replace("\\n","\n") self._label_template = cfg_parser.get("Label", "label") self._labels_per_file = 30 self._product_unity = "pç" self._category_on_label = cfg_parser.getint("Geral", "cat_etiqueta")
def buttonImportSensors_clicked_cb(self, widget): dialog = gtk.FileChooserDialog("Abrir..", None, gtk.FILE_CHOOSER_ACTION_OPEN, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK)) dialog.set_default_response(gtk.RESPONSE_OK) dialog.set_current_folder(dialog.get_current_folder() + "/sensors/") response = dialog.run() if response == gtk.RESPONSE_OK: filename = dialog.get_filename() FILE = open(filename, "r") c = ConfigParser() c.readfp(FILE) name = c.get("SENSOR", "name") unit = c.get("SENSOR", "unit") description = c.get("SENSOR", "description") self.liststore.append([name, unit, description]) sensor = SensorType(name, unit, description, []) self.sensorTypes.append(sensor) for i in c.sections(): if i != "SENSOR": x = c.getint(i, "x") y = c.getfloat(i, "y") sensor.add_point([x, y]) self.writeSensorsConfig() FILE.close() dialog.destroy()
def __pre_parse(self, opts, args): cp = ConfigParser() self.cp = cp read_files = cp.read(["/etc/xbe/xberc", os.path.expanduser("~/.xbe/xberc"), opts.config]) if not len(read_files): raise CommandFailed("no configuration file found") if opts.timeout is None: opts.timeout = cp.getfloat("network", "timeout") if opts.server is None: opts.server = cp.get("network", "server") if opts.stomp_user is None: opts.stomp_user = cp.get("network", "user") if opts.stomp_pass is None: opts.stomp_pass = cp.get("network", "pass") if opts.user_cert is None: opts.user_cert = os.path.expanduser(cp.get("security", "pubkey")) if opts.user_key is None: opts.user_key = os.path.expanduser(cp.get("security", "privkey")) if opts.ca_cert is None: opts.ca_cert = os.path.expanduser(cp.get("security", "cacert")) from xbe.xml.security import X509Certificate # build the certificate self.user_cert = X509Certificate.load_from_files(opts.user_cert, opts.user_key) self.ca_cert = X509Certificate.load_from_files(opts.ca_cert)
def read(self, f): '''Read the settings from the given file handle.''' cfg = ConfigParser() cfg.readfp(f) netSection = 'Network' if cfg.has_section(netSection): if cfg.has_option(netSection, 'defaultIpAddress'): self.defaultIpAddress = cfg.get(netSection, 'defaultIpAddress') if cfg.has_option(netSection, 'defaultPort'): self.defaultPort = cfg.getint(netSection, 'defaultPort') if cfg.has_option(netSection, 'ephemeralPortsFrom'): self.ephemeralPorts[0] = cfg.getint(netSection, 'ephemeralPortsFrom') if cfg.has_option(netSection, 'ephemeralPortsTo'): self.ephemeralPorts[1] = cfg.getint(netSection, 'ephemeralPortsTo') tftpSection = 'TFTP' if cfg.has_section(tftpSection): if cfg.has_option(tftpSection, 'timeout'): self.tftpTimeout = cfg.getfloat(tftpSection, 'timeout') if cfg.has_option(tftpSection, 'retries'): self.tftpRetries = cfg.getint(tftpSection, 'retries') serverSection = 'Server' if cfg.has_section(serverSection): if cfg.has_option(serverSection, 'defaultDirectory'): self.defaultDirectory = cfg.get(serverSection, 'defaultDirectory') if cfg.has_option(serverSection, 'saveLastUsed'): self.saveLastUsed = cfg.getboolean(serverSection, 'saveLastUsed')
def load_params(self, filename): config = ConfigParser() config.read(filename) self._normalize_config(config) # Input Parameters self._load_config_param(config, 'input', 'semi_major_axis') self._load_config_param(config, 'input', 'star_radius') self._load_config_param(config, 'input', 'planet_radius') self._load_config_param(config, 'input', 'star_temperature') self._load_config_param(config, 'input', 'planet_temperature') self._load_config_param(config, 'input', 'inclination') self._load_config_param(config, 'input', 'darkening_law') self._load_config_param(config, 'input', 'darkening_coefficient_1') self._load_config_param(config, 'input', 'darkening_coefficient_2') self._load_config_param(config, 'input', 'phase_end') self._load_config_param(config, 'input', 'phase_step') self._load_config_param(config, 'input', 'integration_precision') # Import Parameters if config.has_option('import', 'filename') and config.get('import', 'filename'): if '/data/' in config.get('import', 'filename') and config.get('import', 'filename').index('/data/') == 0: self.import_parameters.filename = os.getcwd().replace('\\', '/') + config.get('import', 'filename') else: self.import_parameters.filename = config.get('import', 'filename') self.import_parameters.update_file_label() if config.has_option('import', 'jd2phase') and config.getboolean('import', 'jd2phase') == True : self.import_parameters.hjd_to_phases.setCheckState(Qt.Checked) if config.has_option('import', 'jd2phase_tzero') : self.import_parameters.time_zero.setValue(config.getfloat('import', 'jd2phase_tzero')) if config.has_option('import', 'jd2phase_period') : self.import_parameters.period.setValue(config.getfloat('import', 'jd2phase_period')) if config.has_option('import', 'mag2flux') and config.getboolean('import', 'mag2flux') == True : self.import_parameters.magnitude_to_flux.setCheckState(Qt.Checked) if config.has_option('import', 'mag2flux_mag') : self.import_parameters.magnitude_max.setValue(config.getfloat('import', 'mag2flux_mag')) # Fixes painting bug with range buttons when loading new file # the active ranges stayed active even if they are inactive self.repaint()
def getfloat(self, section, option, default=no_default): try: return ConfigParser.getfloat(self, section, option) except ConfigKeyError: if default is not self.no_default: return default print 'CANNOT FIND CONF KEY', section, option raise
def getfloat(self, section, option, default=NO_DEFAULT): try: return ConfigParser.getfloat(self, section, option) except ConfigKeyError: if default is not self.NO_DEFAULT: return default print "CANNOT FIND CONF KEY", section, option raise
def configfile_parse(args,config_file='swarm.conf'): try: conf_parser=ConfigParser() conf_parser.read(config_file) # output options args.logfile=conf_parser.get("Output","logfile") args.verbose=conf_parser.getboolean("Output","verbose") args.disable_col=conf_parser.getboolean("Output","disable_col") # target options args.target=conf_parser.get("Target","target") args.target_file=conf_parser.get("Target","target_file") if args.target!='': args.target=args.target.split() # swarm options args.swarm=conf_parser.get("Swarm","swarm") args.swarm_file=conf_parser.get("Swarm","swarm_file") args.timeout=conf_parser.getfloat("Swarm","timeout") args.waken_cmd=conf_parser.get("Swarm","waken_cmd") args.m_addr=conf_parser.get("Swarm","m_addr") args.m_port=conf_parser.getint("Swarm","m_port") args.s_port=conf_parser.getint("Swarm","s_port") args.authkey=conf_parser.get("Swarm","authkey") args.sync_data=conf_parser.getboolean("Swarm","sync_data") if args.swarm!='': args.swarm=args.swarm.split() # common options args.process_num=conf_parser.getint("Common","process_num") args.thread_num=conf_parser.getint("Common","thread_num") # domain scan options args.enable_domain_scan=conf_parser.getboolean("Domain Scan","enable_domain_scan") args.domain_compbrute=conf_parser.getboolean("Domain Scan","domain_compbrute") args.domain_dict=conf_parser.get("Domain Scan","domain_dict") args.domain_maxlevel=conf_parser.getint("Domain Scan","domain_maxlevel") args.domain_charset=conf_parser.get("Domain Scan","domain_charset") args.domain_levellen=conf_parser.get("Domain Scan","domain_levellen") args.domain_timeout=conf_parser.getfloat("Domain Scan","domain_timeout") except Exception,e: print 'parse config file error' raise SwarmUseException('parse config file error')
def parse_input(config_file): config = ConfigParser() config.read(config_file) # get params from file, using test values as defaults if missing options lambd = ( config.getfloat("Material Parameters", "lambd") if config.has_option("Material Parameters", "lambd") else 0.5 ) mu = config.getfloat("Material Parameters", "mu") if config.has_option("Material Parameters", "mu") else 1.0 rho = config.getfloat("Material Parameters", "rho") if config.has_option("Material Parameters", "rho") else 3.0 min_x = config.getfloat("Coordinates", "min_x") if config.has_option("Coordinates", "min_x") else 0.0 max_x = config.getfloat("Coordinates", "max_x") if config.has_option("Coordinates", "max_x") else 5.0 min_y = config.getfloat("Coordinates", "min_y") if config.has_option("Coordinates", "min_y") else 0.0 max_y = config.getfloat("Coordinates", "max_y") if config.has_option("Coordinates", "max_y") else 5.0 min_z = config.getfloat("Coordinates", "min_z") if config.has_option("Coordinates", "min_z") else 0.0 max_z = config.getfloat("Coordinates", "max_z") if config.has_option("Coordinates", "max_z") else 5.0 N_x = config.getint("Grid Points", "N_x") if config.has_option("Grid Points", "N_x") else 100 N_y = config.getint("Grid Points", "N_y") if config.has_option("Grid Points", "N_y") else 100 N_z = config.getint("Grid Points", "N_z") if config.has_option("Grid Points", "N_z") else 100 t_0 = config.getfloat("Time Parameters", "t_0") if config.has_option("Time Parameters", "t_0") else 0.0 t_f = config.getfloat("Time Parameters", "t_f") if config.has_option("Time Parameters", "t_f") else 2.5 N_t = config.getint("Time Parameters", "N_t") if config.has_option("Time Parameters", "N_t") else 100 output = config.get("Output File", "data") if config.has_option("Output File", "data") else "output.dat" return lambd, mu, rho, min_x, max_x, min_y, max_y, min_z, max_z, N_x, N_y, N_z, t_0, t_f, N_t, output
def parseConfigurationFile(self, configFile): # Create a config parser object and read in the file defaultParams = {} cfgParser = ConfigParser(defaultParams) cfgParser.read(configFile) self.params = {} self.params["dt_max"] = cfgParser.getfloat("preprocessing", "dt_max")
class ConfigFile(): """ Adapted from a helper method from Python Wiki. This class will hold a config file, and attempt to automatically convert values to ints or booleans. With example.ini as a test file: >>> c = ConfigFile('tests/example.ini') >>> c.get('Section One', 'Key') 'Value' >>> c.get('Section One', 'Luggage_Combination') 12345 >>> c.getsection('Section Two') {'LOCATION': 'Hyrule', 'KEY': 'Value'} """ def __init__(self, path): self.conf = ConfigParser() self.conf.read(path) def getsection(self, section): """ Returns an entire section in a dict. The dict's keys will be uppercase, for convenience. """ keys = {} try: options = self.conf.options(section) except: return {} for opt in options: key = opt.upper() try: keys[key] = self.get(section, opt) except: keys[key] = None return keys def get(self, section, opt): """ Gets a config value. This value will automatically be converted to a boolean, float or int. """ try: key = self.conf.get(section, opt) if key == 'True': return True elif key == 'False': return False elif re.match('^[0-9]+$', key): return self.conf.getint(section, opt) elif re.match('^[0-9]+\.[0-9]+$', key): return self.conf.getfloat(section, opt) else: return key except: return None
class Config(object): """ Parses a .ini configuration file This parser disregards sections, meaning option names are unique >>> fcc = Config("config.ini") >>> fcc["docsFileDir"] "specific_doc_file.txt" """ def __init__(self, configFName): self.confPar = ConfigParser() self.confPar.read(configFName) self.confDict = {} self.options = set() self.readConfig() def readConfig(self): """ Hard coded reading of options to ensure correct data type""" # for section in self.configParser.sections(): # for option in self.configParser.options(section): # self.configDict[option] = self.configParser.get(section, option) self.readConfigHelper("Files", "seedFile") self.readConfigHelper("Files", "blacklistFile") self.readConfigHelper("Files", "trainingDocs") self.readConfigHelper("Model", "useVSM", "boolean") self.readConfigHelper("VSM Filtering", "VSMFilterModel") self.readConfigHelper("VSM Filtering", "minRepositoryDocNum", "int") self.readConfigHelper("VSM Filtering", "filterRelevantThreshold", "float") self.readConfigHelper("VSM Filtering", "filterIrrelevantThreshold", "float") self.readConfigHelper("VSM Filtering", "numFilterTopics", "int") self.readConfigHelper("Classifier", "classifier") self.readConfigHelper("Classifier", "allowAdaptive", "boolean") self.readConfigHelper("Crawling", "pageLimit", "int") self.readConfigHelper("Crawling", "linkLimit", "int") self.readConfigHelper("Crawling", "relevantThreshold", "float") def readConfigHelper(self, sect, opt, dataType="string"): """ Helper function to read in an option, based on dataType """ if dataType.lower() == "string": self.confDict[opt] = self.confPar.get(sect, opt) elif dataType.lower() == "boolean": self.confDict[opt] = self.confPar.getboolean(sect, opt) elif dataType.lower() == "float": self.confDict[opt] = self.confPar.getfloat(sect, opt) elif dataType.lower() == "int": self.confDict[opt] = self.confPar.getint(sect, opt) self.options.add(opt) def __getitem__(self, key): return self.confDict[key] def getOptions(self): return self.options
def loadini(struct, configfile): """Loads .ini configuration file and stores its values in struct""" config_path = os.path.expanduser(configfile) config = ConfigParser() fill_config_with_default_values( config, { 'general': { 'arg_spec': True, 'auto_display_list': True, 'color_scheme': 'default', 'complete_magic_methods': True, 'autocomplete_mode': default_completion, 'dedent_after': 1, 'flush_output': True, 'highlight_show_source': True, 'hist_file': '~/.pythonhist', 'hist_length': 100, 'hist_duplicates': True, 'paste_time': 0.02, 'syntax': True, 'tab_length': 4, 'pastebin_confirm': True, 'pastebin_url': 'https://bpaste.net/json/new', 'pastebin_show_url': 'https://bpaste.net/show/$paste_id', 'pastebin_removal_url': 'https://bpaste.net/remove/$removal_id', 'pastebin_expiry': '1week', 'pastebin_helper': '', 'save_append_py': False, 'editor': os.environ.get('VISUAL', os.environ.get('EDITOR', 'vi')) }, 'keyboard': { 'clear_line': 'C-u', 'clear_screen': 'C-l', 'clear_word': 'C-w', 'cut_to_buffer': 'C-k', 'delete': 'C-d', 'down_one_line': 'C-n', 'exit': '', 'external_editor': 'F7', 'edit_config': 'F3', 'edit_current_block': 'C-x', 'help': 'F1', 'last_output': 'F9', 'pastebin': 'F8', 'save': 'C-s', 'show_source': 'F2', 'suspend': 'C-z', 'toggle_file_watch': 'F5', 'undo': 'C-r', 'reimport': 'F6', 'search': 'C-o', 'up_one_line': 'C-p', 'yank_from_buffer': 'C-y' }, 'cli': { 'suggestion_width': 0.8, 'trim_prompts': False, }, 'curtsies': { 'list_above': False, 'fill_terminal': False, 'right_arrow_completion': True, } }) if not config.read(config_path): # No config file. If the user has it in the old place then complain if os.path.isfile(os.path.expanduser('~/.bpython.ini')): sys.stderr.write("Error: It seems that you have a config file at " "~/.bpython.ini. Please move your config file to " "%s\n" % default_config_path()) sys.exit(1) struct.config_path = config_path struct.dedent_after = config.getint('general', 'dedent_after') struct.tab_length = config.getint('general', 'tab_length') struct.auto_display_list = config.getboolean('general', 'auto_display_list') struct.syntax = config.getboolean('general', 'syntax') struct.arg_spec = config.getboolean('general', 'arg_spec') struct.paste_time = config.getfloat('general', 'paste_time') struct.highlight_show_source = config.getboolean('general', 'highlight_show_source') struct.hist_file = config.get('general', 'hist_file') struct.editor = config.get('general', 'editor') struct.hist_length = config.getint('general', 'hist_length') struct.hist_duplicates = config.getboolean('general', 'hist_duplicates') struct.flush_output = config.getboolean('general', 'flush_output') struct.pastebin_key = config.get('keyboard', 'pastebin') struct.save_key = config.get('keyboard', 'save') struct.search_key = config.get('keyboard', 'search') struct.show_source_key = config.get('keyboard', 'show_source') struct.suspend_key = config.get('keyboard', 'suspend') struct.toggle_file_watch_key = config.get('keyboard', 'toggle_file_watch') struct.undo_key = config.get('keyboard', 'undo') struct.reimport_key = config.get('keyboard', 'reimport') struct.up_one_line_key = config.get('keyboard', 'up_one_line') struct.down_one_line_key = config.get('keyboard', 'down_one_line') struct.cut_to_buffer_key = config.get('keyboard', 'cut_to_buffer') struct.yank_from_buffer_key = config.get('keyboard', 'yank_from_buffer') struct.clear_word_key = config.get('keyboard', 'clear_word') struct.clear_line_key = config.get('keyboard', 'clear_line') struct.clear_screen_key = config.get('keyboard', 'clear_screen') struct.delete_key = config.get('keyboard', 'delete') struct.exit_key = config.get('keyboard', 'exit') struct.last_output_key = config.get('keyboard', 'last_output') struct.edit_config_key = config.get('keyboard', 'edit_config') struct.edit_current_block_key = config.get('keyboard', 'edit_current_block') struct.external_editor_key = config.get('keyboard', 'external_editor') struct.help_key = config.get('keyboard', 'help') struct.pastebin_confirm = config.getboolean('general', 'pastebin_confirm') struct.pastebin_url = config.get('general', 'pastebin_url') struct.pastebin_show_url = config.get('general', 'pastebin_show_url') struct.pastebin_removal_url = config.get('general', 'pastebin_removal_url') struct.pastebin_expiry = config.get('general', 'pastebin_expiry') struct.pastebin_helper = config.get('general', 'pastebin_helper') struct.cli_suggestion_width = config.getfloat('cli', 'suggestion_width') struct.cli_trim_prompts = config.getboolean('cli', 'trim_prompts') struct.complete_magic_methods = config.getboolean( 'general', 'complete_magic_methods') struct.autocomplete_mode = config.get('general', 'autocomplete_mode') struct.save_append_py = config.getboolean('general', 'save_append_py') struct.curtsies_list_above = config.getboolean('curtsies', 'list_above') struct.curtsies_fill_terminal = config.getboolean('curtsies', 'fill_terminal') struct.curtsies_right_arrow_completion = config.getboolean( 'curtsies', 'right_arrow_completion') color_scheme_name = config.get('general', 'color_scheme') default_colors = { 'keyword': 'y', 'name': 'c', 'comment': 'b', 'string': 'm', 'error': 'r', 'number': 'G', 'operator': 'Y', 'punctuation': 'y', 'token': 'C', 'background': 'd', 'output': 'w', 'main': 'c', 'paren': 'R', 'prompt': 'c', 'prompt_more': 'g', 'right_arrow_suggestion': 'K', } if color_scheme_name == 'default': struct.color_scheme = default_colors else: struct.color_scheme = dict() theme_filename = color_scheme_name + '.theme' path = os.path.expanduser( os.path.join(get_config_home(), theme_filename)) try: load_theme(struct, path, struct.color_scheme, default_colors) except EnvironmentError: sys.stderr.write("Could not load theme '%s'.\n" % (color_scheme_name, )) sys.exit(1) # checks for valid key configuration this part still sucks for key in (struct.pastebin_key, struct.save_key): key_dispatch[key]
def __init__(self): config = ConfigParser() config.readfp(open('Config/scorer.cfg')) self.alpha = config.getfloat('Scorer', 'alpha') self.beta = config.getfloat('Scorer', 'beta') self.delta = config.getfloat('Scorer', 'delta') self.exact = config.getfloat('Scorer', 'exact') self.stem = config.getfloat('Scorer', 'stem') self.synonym = config.getfloat('Scorer', 'synonym') self.paraphrase = config.getfloat('Scorer', 'paraphrase') self.related = config.getfloat('Scorer', 'related') self.related_threshold = config.getfloat('Scorer', 'related_threshold') self.context_importance = config.getfloat('Scorer', 'context_importance') self.minimal_aligned_relatedness = config.getfloat('Scorer', 'minimal_aligned_relatedness') self.arguments = config.getfloat('Dependency Weights', 'arguments') self.modifiers = config.getfloat('Dependency Weights', 'modifiers') self.function = config.getfloat('Dependency Weights', 'function') self.argument_types = loads(config.get('Dependency Types', 'arguments')) self.modifier_types = loads(config.get('Dependency Types', 'modifiers')) self.function_types = loads(config.get('Dependency Types', 'function')) self.noisy_types = loads(config.get('Dependency Types', 'noise'))
def create_config(config_path): config = dict() config_raw = ConfigParser() config_raw.read(DEFAULT_CONFIG) config_raw.read(config_path) ### Config config['send_stops'] = config_raw.getboolean('Config', 'STOPS') config['send_gyms'] = config_raw.getboolean('Config', 'GYMS') config['send_portals'] = config_raw.getboolean('Config', 'PORTALS') config['update_gym_stop'] = config_raw.getboolean( 'Config', 'GYM_UPDATE_THROUGH_STOP') config['update_gym_portal'] = config_raw.getboolean( 'Config', 'GYM_UPDATE_THROUGH_PORTAL') config['update_stop_portal'] = config_raw.getboolean( 'Config', 'STOP_UPDATE_THROUGH_PORTAL') config['delete_stops'] = config_raw.getboolean('Config', 'DELETE_CONVERTED_STOP') config['webhook_url_stop'] = config_raw.get('Config', 'STOP_WEBHOOK') config['webhook_url_gym'] = config_raw.get('Config', 'GYM_WEBHOOK') config['webhook_url_portal'] = config_raw.get('Config', 'PORTAL_WEBHOOK') config['lat_small'] = config_raw.getfloat('Config', 'MIN_LAT') config['lat_big'] = config_raw.getfloat('Config', 'MAX_LAT') config['lon_small'] = config_raw.getfloat('Config', 'MIN_LON') config['lon_big'] = config_raw.getfloat('Config', 'MAX_LON') config['dosleep'] = config_raw.getboolean('Config', 'LOOP') config['sleeptime'] = config_raw.getint('Config', 'SECONDS_BETWEEN_LOOPS') ### Embeds config['stop_img'] = config_raw.get('Embeds', 'STOP_IMAGE') config['stop_full_username'] = config_raw.get('Embeds', 'STOP_DETAILS_USERNAME') config['stop_unfull_username'] = config_raw.get( 'Embeds', 'STOP_NO_DETAILS_USERNAME') config['embed_stop_color'] = config_raw.getint('Embeds', 'STOP_COLOR') config['gym_img'] = config_raw.get('Embeds', 'GYM_IMAGE') config['gym_full_username'] = config_raw.get('Embeds', 'GYM_DETAILS_USERNAME') config['gym_unfull_username'] = config_raw.get('Embeds', 'GYM_NO_DETAILS_USERNAME') config['embed_gym_color'] = config_raw.getint('Embeds', 'GYM_COLOR') config['portal_img'] = config_raw.get('Embeds', 'PORTAL_IMAGE') config['portal_username'] = config_raw.get('Embeds', 'PORTAL_USERNAME') config['embed_portal_color'] = config_raw.getint('Embeds', 'PORTAL_COLOR') ### Static Map config['static_provider'] = config_raw.get('Static Map', 'PROVIDER') config['imgur_all'] = config_raw.getboolean( 'Static Map', 'USE_IMGUR_MIRRORS_FOR_EVERYTHING') config['static_fancy'] = config_raw.getboolean('Static Map', 'SUPER_FANCY_STATIC_MAPS') config['client_id_imgur'] = config_raw.get('Static Map', 'IMGUR_CLIENT_ID') config['marker_limit'] = config_raw.getint('Static Map', 'MARKER_LIMIT') config['static_key'] = config_raw.get('Static Map', 'KEY') config['static_zoom'] = config_raw.getint('Static Map', 'ZOOM') config['static_width'] = config_raw.getint('Static Map', 'WIDTH') config['static_height'] = config_raw.getint('Static Map', 'HEIGHT') config['static_marker_size'] = config_raw.getint('Static Map', 'MARKER_SIZE') config['static_marker_color_stop'] = config_raw.get( 'Static Map', 'MARKER_COLOR_STOP') config['static_marker_color_gym'] = config_raw.get('Static Map', 'MARKER_COLOR_GYM') config['static_marker_color_portal'] = config_raw.get( 'Static Map', 'MARKER_COLOR_PORTAL') config['static_selfhosted_url'] = config_raw.get('Static Map', 'TILESERVER_URL') config['geocoding'] = config_raw.getboolean('Static Map', 'USE_GEOCODING') config['language'] = config_raw.get('Static Map', 'LANGUAGE') ### DATABASE config['db_scan_schema'] = config_raw.get('DB', 'SCANNER_DB') config['db_portal_schema'] = config_raw.get('DB', 'PORTAL_DB') config['db_host'] = config_raw.get('DB', 'HOST') config['db_port'] = config_raw.getint('DB', 'PORT') config['db_user'] = config_raw.get('DB', 'USER') config['db_pass'] = config_raw.get('DB', 'PASSWORD') config['db_portal_dbname'] = config_raw.get('DB', 'PORTAL_DB_NAME') config['db_dbname'] = config_raw.get('DB', 'NAME') config['db_stop_table'] = config_raw.get('DB', 'POKESTOP_TABLE') config['db_stop_id'] = config_raw.get('DB', 'POKESTOP_ID') config['db_stop_lat'] = config_raw.get('DB', 'POKESTOP_LAT') config['db_stop_lon'] = config_raw.get('DB', 'POKESTOP_LON') config['db_stop_name'] = config_raw.get('DB', 'POKESTOP_NAME') config['db_stop_img'] = config_raw.get('DB', 'POKESTOP_IMAGE') config['db_gym_table'] = config_raw.get('DB', 'GYM_TABLE') config['db_gymdetails_table'] = config_raw.get('DB', 'GYMDETAILS_TABLE') config['db_gym_id'] = config_raw.get('DB', 'GYM_ID') config['db_gym_lat'] = config_raw.get('DB', 'GYM_LAT') config['db_gym_lon'] = config_raw.get('DB', 'GYM_LON') config['db_gym_name'] = config_raw.get('DB', 'GYM_NAME') config['db_gym_img'] = config_raw.get('DB', 'GYM_IMAGE') config['db_portal_table'] = config_raw.get('DB', 'PORTAL_TABLE') config['db_portal_id'] = config_raw.get('DB', 'PORTAL_ID') config['db_portal_lat'] = config_raw.get('DB', 'PORTAL_LAT') config['db_portal_lon'] = config_raw.get('DB', 'PORTAL_LON') config['db_portal_name'] = config_raw.get('DB', 'PORTAL_NAME') config['db_portal_img'] = config_raw.get('DB', 'PORTAL_IMAGE') return config
def __init__(self, file=None): # If input file is None: Use package internal default config # which contains ftp definition and default output path and stuff. if file is None: import pkg_resources file = pkg_resources.resource_filename(__package__, 'config/default.conf') log.debug("Loading default config file from package source.") import os import sys import re if not os.path.isfile(file): sys.exit("Config fil \"{:s}\" missing".format(file)) # Import ConfigParser, read config if sys.version_info[0] < 3: from ConfigParser import ConfigParser else: from configparser import RawConfigParser as ConfigParser # Read the config file CNF = ConfigParser() CNF.read(file) config = {} self.ftp_if_members = [] self.ftp_ifnot_members = [] try: self.ftp_baseurl = CNF.get("ftp", "baseurl") self.ftp_filename = CNF.get("ftp", "filename") for rec in CNF.get("ftp", "if_members").split(","): self.ftp_if_members.append(rec.strip()) for rec in CNF.get("ftp", "ifnot_members").split(","): self.ftp_ifnot_members.append(rec.strip()) except Exception as e: log.error("Problems reading ftp config") log.error(e) sys.exit(9) # Check if curl logfile is set (logging ftp return codes) try: self.curl_logfile = CNF.get("curl", "logfile") except: self.curl_logfile = None try: self.curl_timeout = CNF.getint("curl", "timeout") except: self.curl_timeout = None try: self.curl_retries = CNF.getint("curl", "retries") except: self.curl_retries = 0 try: self.curl_sleeptime = CNF.getfloat("curl", "sleeptime") except: self.curl_sleeptime = 0 # Date range from datetime import datetime as dt try: self.main_from = dt.strptime(CNF.get("main", "from"), "%Y-%m-%d") self.main_to = dt.strptime(CNF.get("main", "to"), "%Y-%m-%d") except: self.main_from = None self.main_to = None try: self.main_only = CNF.getint("main", "only") except: self.main_only = None if not self.main_only is None: if self.main_only < 1 or self.main_only > 12: sys.exit("Misspecification of [main][only] in config file.") try: self.main_sleeptime = CNF.getfloat("main", "sleeptime") except: self.main_sleeptime = None # Areal subset for wgrib2 --small-grib try: self._lonmin_ = CNF.getfloat("main", "lonmin") self._lonmax_ = CNF.getfloat("main", "lonmax") self._latmin_ = CNF.getfloat("main", "latmin") self._latmax_ = CNF.getfloat("main", "latmax") except: self._lonmin_ = None self._lonmax_ = None self._latmin_ = None self._latmax_ = None self.lonsubset = None self.latsubset = None if self._lonmin_ is not None: if self._lonmin_ >= self._lonmax_ or self._latmin_ >= self._latmax_: log.error( "lonmin/lonmax/latmin/latmax wrong! Please check your config file" ) sys.exit() self.lonsubset = "{:.2f}:{:.2f}".format(self._lonmin_, self._lonmax_) self.latsubset = "{:.2f}:{:.2f}".format(self._latmin_, self._latmax_) # Output file name try: self.outfile = CNF.get("main", "outfile") except Exception as e: log.error(e) sys.exit(9) # Steps to download self.steps = [] try: for rec in CNF.get("main", "steps").split(","): self.steps.append(int(rec)) except: self.steps = None # Reading parameter or variable config secs = CNF.sections() self.data = {} for sec in secs: mtch = re.match("^data\s+(\w+)$", sec) if not mtch: continue try: mem = CNF.getboolean(sec, "members") except Exception as e: log.error(e) sys.exit(9) try: lev = [] for rec in CNF.get(sec, "levels").split(","): lev.append(int(rec)) except: lev = None self.data[mtch.group(1)] = {"members": mem, "levels": lev} # All fine log.info("Config file read, return.")
# notice, this list of conditions and the following disclaimer in # the documentation and/or other materialsprovided with the # distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. from ConfigParser import ConfigParser CONFIG_FILE = 'config.conf' config = ConfigParser() config.read(CONFIG_FILE) print config.get('DEMO', 'STR_VAL') print config.getint('DEMO', 'INT_VAL') print config.getfloat('DEMO', 'FLOAT_VAL')
def ReadCompareConfig(self): if os.path.isfile(self.config_file): pars = ConfigParser() pars.read(self.config_file) print 'Reading config file for comparing runs...', sys.stdout.flush() if pars.has_section('RUNS'): if pars.has_option('RUNS', 'rundirs'): temp_dirs = pars.get('RUNS', 'rundirs') elements = temp_dirs.replace('{', '').replace('}', '') elements = elements.split(',') temp_runs_path = [ Correct_Path(element) for element in elements if os.path.isdir(Correct_Path(element)) and ( len(element) > 2) ] self.run_numbers = np.array([ int(runpath.split('/')[-1]) for runpath in temp_runs_path ], 'uint32') self.runs_path = { self.run_numbers[i]: temp_runs_path[i] for i in xrange(len(temp_runs_path)) } self.runs_subidr = { run: path.split('/' + str(run))[0] for run, path in self.runs_path.iteritems() } if pars.has_option('RUNS', 'settings'): temp_setts = pars.get('RUNS', 'settings') elements = temp_setts.replace('{', '').replace('}', '') elements = elements.split(',') self.runs_settings = [ Correct_Path(element) for element in elements if os.path.isfile(Correct_Path(element)) and ( len(element) > 2) ] if pars.has_option('RUNS', 'outdir'): temp_outdir = pars.get('RUNS', 'outdir') self.outdir = Correct_Path(temp_outdir) if pars.has_option('RUNS', 'do_fit'): self.do_fit = pars.getboolean('RUNS', 'do_fit') if pars.has_option('RUNS', 'testnum'): self.testnum = pars.getint('RUNS', 'testnum') if pars.has_section('SATURATION'): if pars.has_option('SATURATION', 'min_sat_ev'): self.min_sat_ev = pars.getfloat('SATURATION', 'min_sat_ev') if pars.has_option('SATURATION', 'min_not_sat_ev'): self.min_not_sat_ev = pars.getfloat( 'SATURATION', 'min_not_sat_ev') if pars.has_option('SATURATION', 'min_sat_norm'): self.min_sat_norm = pars.getfloat('SATURATION', 'min_sat_norm') if pars.has_option('SATURATION', 'min_not_sat_norm'): self.min_not_sat_norm = pars.getfloat( 'SATURATION', 'min_not_sat_norm') if pars.has_option('SATURATION', 'min_sat_tnorm'): self.min_sat_tnorm = pars.getfloat('SATURATION', 'min_sat_tnorm') if pars.has_option('SATURATION', 'min_not_sat_tnorm'): self.min_not_sat_tnorm = pars.getfloat( 'SATURATION', 'min_not_sat_tnorm') if pars.has_option('SATURATION', 'max_sat_ev'): self.max_sat_ev = pars.getfloat('SATURATION', 'max_sat_ev') if pars.has_option('SATURATION', 'max_not_sat_ev'): self.max_not_sat_ev = pars.getfloat( 'SATURATION', 'max_not_sat_ev') if pars.has_option('SATURATION', 'max_sat_norm'): self.max_sat_norm = pars.getfloat('SATURATION', 'max_sat_norm') if pars.has_option('SATURATION', 'max_not_sat_norm'): self.max_not_sat_norm = pars.getfloat( 'SATURATION', 'max_not_sat_norm') if pars.has_option('SATURATION', 'max_sat_tnorm'): self.max_sat_tnorm = pars.getfloat('SATURATION', 'max_sat_tnorm') if pars.has_option('SATURATION', 'max_not_sat_tnorm'): self.max_not_sat_tnorm = pars.getfloat( 'SATURATION', 'max_not_sat_tnorm') print 'Done'
def load(cls, filename): """Loads an ini file and creates a configuration object""" ini = ConfigParser() ini.read(filename) # copy the fixed values target = cls() target.L1BaseDir = ini.get("InDirectory", "L1BaseDirectory") target.L2BaseDir = ini.get("InDirectory", "L2BaseDirectory") target.use375af = ini.get( "ActiveFire", "use375af" ) # Flag to use M-band 750 m active fire data, AVAFO (y or n) target.use750af = ini.get( "ActiveFire", "use750af" ) # Flag to use I-band 375 m active fire data, VF375 (y or n) try: target.limit375 = ini.getint( "ActiveFire", "limit375") # How many highconf pixels in one row except: pass # don't care if it doesn't have it. target.M07UB = float(ini.get("Thresholds", "M07UB")) #Band 07 (0.86 um)upper bound target.M08LB = float(ini.get("Thresholds", "M08LB")) #Band 08 (1.24 um)lower bound target.M08UB = float(ini.get("Thresholds", "M08UB")) #Band 08 (1.24 um)upper bound target.M10LB = float(ini.get("Thresholds", "M10LB")) #Band 10 (1.61 um)lower bound target.M10UB = float(ini.get("Thresholds", "M10UB")) #Band 10 (1.61 um)upper bound target.M11LB = float(ini.get("Thresholds", "M11LB")) #Band 11 (2.25 um)lower bound target.RthSub = float( ini.get("Thresholds", "RthSub") ) #RthSub is the factor subtracted from the 1.240 band when comparing to the Rth target.Rth = float(ini.get("Thresholds", "Rth")) #Rth target.RthLB = float( ini.get("Thresholds", "RthLB") ) #RthLB is the factor that the Rth check must be greater than or equal to target.MaxSolZen = float( ini.get("Thresholds", "MaxSolZen") ) #Maximum solar zenith angle, used to filter out night pixels from burned area thresholding target.TemporalProximity = int( ini.get("ConfirmBurnParameters", "TemporalProximity")) target.SpatialProximity = int( ini.get("ConfirmBurnParameters", "SpatialProximity")) target.TextOut = ini.get("OutputFlags", "TextFile").lower() target.ShapeOut = ini.get("OutputFlags", "ShapeFile").lower() target.DatabaseOut = ini.get("OutputFlags", "PostGIS").lower() target.ShapePath = ini.get("OutputFlags", "OutShapeDir") target.PostBin = ini.get("OutputFlags", "PostgresqlBin") target.ImageDates = ini.get("ImageDates", "ImageDates").split(',') target.DBname = ini.get("DataBaseInfo", "DataBaseName") target.DBuser = ini.get("DataBaseInfo", "UserName") target.DBschema = ini.get("DataBaseInfo", "Schema") target.pwd = ini.get("DataBaseInfo", "password") if ini.has_option("DataBaseInfo", "Host"): target.DBhost = ini.get("DataBaseInfo", "Host") else: target.DBhost = None if ini.has_section('GeogWindow'): target.north = ini.getfloat('GeogWindow', 'North') target.south = ini.getfloat('GeogWindow', 'South') target.east = ini.getfloat('GeogWindow', 'East') target.west = ini.getfloat('GeogWindow', 'West') if ini.has_section('Burnmask'): target.BMschema = ini.get('Burnmask', 'schema') target.BMtable = ini.get('Burnmask', 'table') target.parse_schema() target.sort_dates() return target
def getfloat(self, *args, **kwargs): return ConfigParser.getfloat(self, *args, **kwargs)
def __init__(self,options): import sys, os from ConfigParser import ConfigParser self.options = options CNF = ConfigParser() CNF.optionxform=str # prevent script to ignore cases CNF.read( options.filename ) # reading config file self.belated = CNF.has_option('general settings','tdate') # - If section [general settings] is missing or # section [parameters] missing: stop if not CNF.has_section("general settings"): sys.exit("ERROR: file does not contain required [general settings] section!") elif not CNF.has_section("parameters"): sys.exit("ERROR: file does not contain required [parameters] section!") # - Else areading [general settings] section, we need # three arguments which is 'city','user','password'. If # at least one is missing: stop. required = ['url','user','password','city'] for req in required: if not CNF.has_option('general settings',req): sys.exit("ERROR: option \"%s\" in section [general settings] not defined." % req) # - Read these 3 strings self.url = CNF.get('general settings','url') self.user = CNF.get('general settings','user') self.password = CNF.get('general settings','password') self.city = CNF.get('general settings','city') if self.belated: self.tdate = CNF.get('general settings','tdate') else: self.tdate = None # - If logfile is defined: take argument. Else # logfile is just options.filename+"log" if not CNF.has_option('general settings','logfile'): self.logfile = "%s.log" % options.filename else: self.logfile = CNF.get('general settings','logfile') self.logfile = self.logfile.replace("%city%", self.city) self.logfile = self.logfile.replace("%user%", self.user) if self.belated: self.logfile = self.logfile.replace("%tdate%", self.tdate) else: self.logfile = self.logfile.replace("%tdate%", "current_tournament") # - Now reading parameters self.data = {} params = CNF.items('parameters') for rec in params: self.data[rec[0]] = CNF.getfloat('parameters',rec[0]) # - Create options string self.args = "city=%s&user=%s&password=%s" % (self.city,self.user,self.password) if self.belated: self.args += "&tdate=%s" % self.tdate for key, val in self.data.iteritems(): self.args += "&%s=%.1f" % (key,val) # - Create list object which can be used in subprocess. self.cmd = ['wget','--no-check-certificate',self.url,'--post-data',self.args,'-O',self.logfile] # - Create command string (for copy and paste users) # For wget with POST request self.cmdstring = "wget --no-check-certificate %s --post-data \"%s\" -O %s" % (self.url, self.args, self.logfile) print self.cmdstring # - GET request if not self.url[-1] == "/": self.geturl = "%s/?%s" % (self.url,self.args) else: self.geturl = "%s?%s" % (self.url,self.args)
def get(self, name, *args): """ Access calibration files. Parameters ---------- name : str One of the following: - 'detarray' - 'hornarray' - 'optics' - 'primbeam' """ if name == 'detarray': hdus = fits.open(self.detarray) version = hdus[0].header['format version'] corner = hdus[2].data shape = corner.shape[:-2] n = shape[0] * shape[1] if version == '1.0': removed = np.zeros(shape, bool) index = np.arange(n, dtype=np.int32).reshape(shape) quadrant = np.zeros(shape, np.int8) efficiency = np.ones(shape) else: removed = hdus[3].data.view(bool) index = hdus[4].data quadrant = hdus[5].data if version > '2.0': efficiency = hdus[6].data else: efficiency = np.ones(shape) return shape, corner, removed, index, quadrant, efficiency elif name == 'hornarray': hdus = fits.open(self.hornarray) version = hdus[0].header['format version'] if version == '1.0': h = hdus[0].header spacing = h['spacing'] center = hdus[1].data shape = center.shape[:-1] layout = Layout(shape, center=center, radius=h['innerrad'], open=None) layout.spacing = spacing elif version == '2.0': h = hdus[0].header spacing = h['spacing'] xreflection = h['xreflection'] yreflection = h['yreflection'] radius = h['radius'] selection = ~hdus[1].data.view(bool) layout = LayoutGrid(removed.shape, spacing, selection=selection, radius=radius, xreflection=xreflection, yreflection=yreflection, open=None) else: h = hdus[1].header spacing = h['spacing'] xreflection = h['xreflection'] yreflection = h['yreflection'] angle = h['angle'] radius = h['radius'] selection = ~hdus[2].data.view(bool) shape = selection.shape layout = HornLayout(shape, spacing, selection=selection, radius=radius, xreflection=xreflection, yreflection=yreflection, angle=angle, startswith1=True, id=None, open=None) layout.id = np.arange(len(layout)) layout.center = np.concatenate( [layout.center, np.full_like(layout.center[..., :1], 0)], -1) layout.open = np.ones(len(layout), bool) return layout elif name == 'optics': dtype = [('name', 'S16'), ('temperature', float), ('transmission', float), ('emissivity', float), ('nstates_pol', int)] if self.optics.endswith('fits'): header = fits.open(self.optics)[0].header return { 'focal length': header['flength'], 'detector efficiency': 1., 'components': np.empty(0, dtype=dtype) } parser = ConfigParser() parser.read(self.optics) keys = 'focal length', out = dict((key, parser.getfloat('general', key)) for key in keys) raw = parser.items('components') components = np.empty(len(raw), dtype=dtype) for i, r in enumerate(raw): component = (r[0], ) + tuple( float(_) for _ in r[1].split(', ')) components[i] = component out['components'] = components return out elif name == 'primbeam': hdu = fits.open(self.primbeam) header = hdu[0].header # Gaussian beam if header['format version'] == '1.0': fwhm0_deg = header['fwhm'] return fwhm0_deg # Fitted beam elif header['format version'] == '2.0': if (self.nu < 170 and self.nu > 130): omega = hdu[1].header['omega'] par = hdu[1].data else: omega = hdu[2].header['omega'] par = hdu[2].data return par, omega # Multi frequency beam else: parth = hdu[1].data parfr = hdu[2].data parbeam = hdu[3].data alpha = hdu[4].data xspl = hdu[5].data return parth, parfr, parbeam, alpha, xspl raise ValueError('Invalid primary beam calibration version') raise ValueError("Invalid calibration item: '{}'".format(name))
def configure(ini): global runs, repeatevery, cutoff, delay, maxtime, logfilemax, outputmax, \ make, makefile, affinitymask try: parser = ConfigParser() parser.read(ini) # override default directory locations for k,v in parser.items('dirs'): dirs[k] = normpath( expandvars( expanduser( v ))) for k,v in parser.items('filters'): filters[k] = v.split() filters['onlydirs'] = frozenset( filters['onlydirs']) for k,v in parser.items('alias'): alias[k] = v.split() make = frozenset( parser.get('build', 'make').split() ) f = dirs['makefile'] if 'makefile' in dirs else defaultMakefile() makefile = normpath( expandvars( expanduser( f ))) if f else None # compiler interpreter runtime location shell vars for k,v in parser.items('tools'): os.environ[k.upper()] = v commandlines.update( parser.items('commandlines') ) for k,v in parser.items('testrange'): testrange[k] = v.split() for k,v in parser.items('testdata'): testdata[k] = v for k,v in parser.items('outputcheck'): outputcheck[k] = frozenset( v.split() ) for k,v in parser.items('ndiff_outputcheck'): ndiff_outputcheck[k] = v # test specific shell vars default = {} for each in filters['onlydirs']: if parser.has_section(each): d = {} for k,v in parser.items(each): d[k.upper()] = v default[k.upper()] = '' testenv[each] = d testenv['default'] = default s = 'measure' if parser.has_section(s): for o in parser.options(s): if o in ('runs'): runs = parser.getint(s,o) elif o in ('repeatevery'): repeatevery = parser.getboolean(s,o) elif o in ('cutoff'): cutoff = parser.getint(s,o) elif o in ('delay'): delay = parser.getfloat(s,o) elif o in ('maxtime'): maxtime = parser.getint(s,o) elif o in ('logfilemax'): logfilemax = parser.getint(s,o) elif o in ('outputmax'): outputmax = parser.getint(s,o) elif o in ('affinitymask'): affinitymask = parser.getint(s,o) except (NoSectionError,NoOptionError), e: if logger: logger.debug(e) print e, 'in', realpath(ini) sys.exit(2)
if not Crawler_Resume: Init_Work = [] Seed_File_Path = Config.get('Initial_Setting', 'Seed_File_Path') fp = open(Seed_File_Path, 'r') while True: line = fp.readline() if len(line) == 0: break if len(line.strip()) > 0: Init_Work.append(line.strip()) fp.close() Crawler_Work_Queue_Lock = threading.Lock() Crawler_Data_Queue_Lock = threading.Lock() Crawler_Check_Iteration = Config.getfloat('Crawler_Control', 'Crawler_Check_Iteration') Crawler_Pause = Config.getboolean('Crawler_Control', 'Crawler_Pause') Crawler_Terminate = Config.getboolean('Crawler_Control', 'Crawler_Terminate') Work_Finish_Threshold = Config.getint('Crawler_Control', 'Work_Finish_Threshold') Foreman_Config = { 'FOREMAN_PAUSE_DURATION': 10, 'FOREMAN_NOWORK_DURATION': 20, 'FOREMAN_FINISH_DURATION': 30 } Foreman_Config['FOREMAN_PAUSE_DURATION'] = Config.getfloat( 'Foreman_Setting', 'FOREMAN_PAUSE_DURATION') Foreman_Config['FOREMAN_NOWORK_DURATION'] = Config.getfloat( 'Foreman_Setting', 'FOREMAN_NOWORK_DURATION') Foreman_Config['FOREMAN_FINISH_DURATION'] = Config.getfloat(
def init(): # Config File global config # Setup Camera Settings global CAM_WIDTH, CAM_HEIGHT, CAM_FPS, CAM_EXPOSURE # Setup Crop Settings global FRAME_WIDTH_START, FRAME_WIDTH_END global FRAME_HEIGHT_START, FRAME_HEIGHT_END # Calibration Values global WIDTH_RATIOS, HEIGHT_RATIOS global PIXEL_WIDTHS, PIXEL_HEIGHTS global ACTUAL_WIDTH, ACTUAL_HEIGHT # Thresh global MIN_AREA, WHITE_THRESH # Pass/Fail Settings global FAIL_WIDTH_LOW, FAIL_WIDTH_HIGH global FAIL_HEIGHT_LOW, FAIL_HEIGHT_HIGH global LANE_FAIL_WIDTHS_LOW, LANE_FAIL_WIDTHS_HIGH global LANE_FAIL_HEIGHTS_LOW, LANE_FAIL_HEIGHTS_HIGH # Lane Settings global LANE_COUNT global LANE_HEIGHT, EDGE_GAP global LANE_WIDTH_START, LANE_WIDTH_END global LANE_HEIGHT_START, LANE_HEIGHT_END global LANE_HISTORY # Draw Settings global FONT global GREEN, RED, ORANGE, YELLOW global PASS_FAIL_Y global TEXT_Y # Bounding Box Settings global LANE_X1, LANE_Y1, LANE_X2, LANE_Y2, SPLIT_X1, SPLIT_X2, SPLIT_X3, SPLIT_X4 # Traffic Lights Settings global TRAFFIC_LANE_1_X1, TRAFFIC_LANE_1_X2 global TRAFFIC_LANE_2_X1, TRAFFIC_LANE_2_X2 global TRAFFIC_LANE_3_X1, TRAFFIC_LANE_3_X2 global TRAFFIC_LANE_4_X1, TRAFFIC_LANE_4_X2 global TRAFFIC_Y1, TRAFFIC_Y2 # AIO Settings global AIO_WAIT # Results Settings global EXPORT_TIMES, FOLDER_LOCATION # Load config file config = ConfigParser() config.read(my_path + '/config.ini') # Get Camera Settings CAM_WIDTH = config.getint('CAMERA', 'CAM_WIDTH') CAM_HEIGHT = config.getint('CAMERA', 'CAM_HEIGHT') CAM_FPS = config.getint('CAMERA', 'CAM_FPS') CAM_EXPOSURE = config.getint('CAMERA', 'CAM_EXPOSURE') FRAME_WIDTH = config.getint('CAMERA', 'FRAME_WIDTH') FRAME_HEIGHT = config.getint('CAMERA', 'FRAME_HEIGHT') # Get Calibration Settings ACTUAL_WIDTH = config.getfloat('CALIBRATION', 'ACTUAL_WIDTH') ACTUAL_HEIGHT = config.getfloat('CALIBRATION', 'ACTUAL_HEIGHT') PIXEL_WIDTHS = getArray(config, 'CALIBRATION', 'PIXEL_WIDTHS') PIXEL_HEIGHTS = getArray(config, 'CALIBRATION', 'PIXEL_HEIGHTS') HEIGHT_RATIOS, WIDTH_RATIOS = [], [] for width in PIXEL_WIDTHS: WIDTH_RATIOS.append(ACTUAL_WIDTH / width) for height in PIXEL_HEIGHTS: HEIGHT_RATIOS.append(ACTUAL_HEIGHT / height) # Get Thresh Setting MIN_AREA = config.getint('THRESHOLD', 'MIN_AREA') WHITE_THRESH = config.getfloat('THRESHOLD', 'WHITE_THRESH') # Get Pass/Fail Settings FAIL_WIDTH_LOW = config.getfloat('THRESHOLD', 'FAIL_WIDTH_LOW') FAIL_WIDTH_HIGH = config.getfloat('THRESHOLD', 'FAIL_WIDTH_HIGH') FAIL_HEIGHT_LOW = config.getfloat('THRESHOLD', 'FAIL_HEIGHT_LOW') FAIL_HEIGHT_HIGH = config.getfloat('THRESHOLD', 'FAIL_HEIGHT_HIGH') # Setup Width Pass/Fail LANE_FAIL_WIDTHS_LOW, LANE_FAIL_WIDTHS_HIGH = [], [] for ratio in WIDTH_RATIOS: LANE_FAIL_WIDTHS_LOW.append(FAIL_WIDTH_LOW / ratio) for ratio in WIDTH_RATIOS: LANE_FAIL_WIDTHS_HIGH.append(FAIL_WIDTH_HIGH / ratio) # Setup Height Pass/Fail LANE_FAIL_HEIGHTS_LOW, LANE_FAIL_HEIGHTS_HIGH = [], [] for ratio in HEIGHT_RATIOS: LANE_FAIL_HEIGHTS_LOW.append(FAIL_HEIGHT_LOW / ratio) for ratio in HEIGHT_RATIOS: LANE_FAIL_HEIGHTS_HIGH.append(FAIL_HEIGHT_HIGH / ratio) # Get Lane Settings LANE_COUNT = config.getint('LANE', 'LANE_COUNT') LANE_HEIGHT = config.getint('LANE', 'LANE_HEIGHT') LANE_HEIGHT_END = config.getint('LANE', 'LANE_HEIGHT_END') EDGE_GAP = config.getint('LANE', 'EDGE_GAP') LANE_WIDTH_START = getArray(config, 'LANE', 'LANE_WIDTH_START') LANE_WIDTH_END = getArray(config, 'LANE', 'LANE_WIDTH_END') LANE_HEIGHT_START = getArray(config, 'LANE', 'LANE_HEIGHT_START') LANE_HISTORY = config.getint('LANE', 'LANE_HISTORY') # Get Draw Settings FONT = config.getint('DRAW', 'FONT') GREEN = getArray(config, 'DRAW', 'GREEN') RED = getArray(config, 'DRAW', 'RED') ORANGE = getArray(config, 'DRAW', 'ORANGE') YELLOW = getArray(config, 'DRAW', 'YELLOW') PASS_FAIL_Y = getArray(config, 'DRAW', 'PASS_FAIL_Y') TEXT_Y = LANE_HEIGHT_END - EDGE_GAP + 60 # Get Bounding Box Settings LANE_X1 = LANE_WIDTH_START[0] LANE_Y1 = LANE_HEIGHT_START + EDGE_GAP LANE_X2 = LANE_WIDTH_END[LANE_COUNT - 1] LANE_Y2 = LANE_HEIGHT_END - EDGE_GAP SPLIT_X1 = LANE_WIDTH_START[1] SPLIT_X2 = LANE_WIDTH_END[1] SPLIT_X3 = LANE_WIDTH_START[2] SPLIT_X4 = LANE_WIDTH_END[2] # Setup Traffic Light Boxes TRAFFIC_LANE_1_X1 = LANE_WIDTH_START[0] TRAFFIC_LANE_1_X2 = LANE_WIDTH_END[0] TRAFFIC_LANE_2_X1 = LANE_WIDTH_START[1] TRAFFIC_LANE_2_X2 = LANE_WIDTH_END[1] TRAFFIC_LANE_3_X1 = LANE_WIDTH_START[2] TRAFFIC_LANE_3_X2 = LANE_WIDTH_END[2] TRAFFIC_LANE_4_X1 = LANE_WIDTH_START[3] TRAFFIC_LANE_4_X2 = LANE_WIDTH_END[3] TRAFFIC_Y1 = LANE_HEIGHT_END - EDGE_GAP TRAFFIC_Y2 = LANE_HEIGHT_END - EDGE_GAP + 30 # Get AIO Settings AIO_WAIT = config.getfloat('AIO', 'AIO_WAIT') # Get Results Settings EXPORT_TIMES = getArray(config, 'RESULTS', 'EXPORT_TIMES') FOLDER_LOCATION = config.get('RESULTS', 'FOLDER_LOCATION') # Get Crop Settings CAM_WIDTH_MIDPOINT = CAM_WIDTH / 2 HALF_FRAME_WIDTH = FRAME_WIDTH / 2 FRAME_WIDTH_START = CAM_WIDTH_MIDPOINT - HALF_FRAME_WIDTH FRAME_WIDTH_END = CAM_WIDTH_MIDPOINT + HALF_FRAME_WIDTH CAM_HEIGHT_MIDPOINT = CAM_HEIGHT / 2 HALF_FRAME_HEIGHT = FRAME_HEIGHT / 2 FRAME_HEIGHT_START = CAM_HEIGHT_MIDPOINT - HALF_FRAME_HEIGHT FRAME_HEIGHT_END = CAM_HEIGHT_MIDPOINT + HALF_FRAME_HEIGHT
from ConfigParser import ConfigParser config_file = 'configtest.txt' config = ConfigParser() config.read(config_file) print config.get('message', 'greeting') radius = input(config.get('message', 'question')) print config.get('message', 'result') + ' ' print config.getfloat('number', 'pi') * radius**2
def loadini(struct, configfile): """Loads .ini configuration file and stores its values in struct""" config_path = os.path.expanduser(configfile) if not os.path.isfile(config_path) and configfile == default_config_path(): # We decided that '~/.bpython/config' still was a crappy # place, use XDG Base Directory Specification instead. Fall # back to old config, though. config_path = os.path.expanduser('~/.bpython/config') config = ConfigParser() fill_config_with_default_values( config, { 'general': { 'arg_spec': True, 'auto_display_list': True, 'color_scheme': 'default', 'complete_magic_methods': True, 'magic_methods': MAGIC_METHODS, 'autocomplete_mode': default_completion, 'dedent_after': 1, 'flush_output': True, 'highlight_show_source': True, 'hist_file': '~/.pythonhist', 'hist_length': 100, 'hist_duplicates': True, 'paste_time': 0.02, 'syntax': True, 'tab_length': 4, 'pastebin_confirm': True, 'pastebin_private': False, 'pastebin_url': 'http://bpaste.net/xmlrpc/', 'pastebin_private': True, 'pastebin_show_url': 'http://bpaste.net/show/$paste_id/', 'pastebin_helper': '', }, 'keyboard': { 'clear_line': 'C-u', 'clear_screen': 'C-l', 'clear_word': 'C-w', 'cut_to_buffer': 'C-k', 'delete': 'C-d', 'down_one_line': 'C-n', 'exit': '', 'last_output': 'F9', 'pastebin': 'F8', 'save': 'C-s', 'show_source': 'F2', 'suspend': 'C-z', 'undo': 'C-r', 'search': 'C-o', 'up_one_line': 'C-p', 'yank_from_buffer': 'C-y' }, 'cli': { 'suggestion_width': 0.8, 'trim_prompts': False, }, 'gtk': { 'font': 'monospace 10', 'color_scheme': 'default' } }) if not config.read(config_path): # No config file. If the user has it in the old place then complain if os.path.isfile(os.path.expanduser('~/.bpython.ini')): sys.stderr.write("Error: It seems that you have a config file at " "~/.bpython.ini. Please move your config file to " "%s\n" % default_config_path()) sys.exit(1) struct.dedent_after = config.getint('general', 'dedent_after') struct.tab_length = config.getint('general', 'tab_length') struct.auto_display_list = config.getboolean('general', 'auto_display_list') struct.syntax = config.getboolean('general', 'syntax') struct.arg_spec = config.getboolean('general', 'arg_spec') struct.paste_time = config.getfloat('general', 'paste_time') struct.highlight_show_source = config.getboolean('general', 'highlight_show_source') struct.hist_file = config.get('general', 'hist_file') struct.hist_length = config.getint('general', 'hist_length') struct.hist_duplicates = config.getboolean('general', 'hist_duplicates') struct.flush_output = config.getboolean('general', 'flush_output') struct.pastebin_key = config.get('keyboard', 'pastebin') struct.save_key = config.get('keyboard', 'save') struct.search_key = config.get('keyboard', 'search') struct.show_source_key = config.get('keyboard', 'show_source') struct.suspend_key = config.get('keyboard', 'suspend') struct.undo_key = config.get('keyboard', 'undo') struct.up_one_line_key = config.get('keyboard', 'up_one_line') struct.down_one_line_key = config.get('keyboard', 'down_one_line') struct.cut_to_buffer_key = config.get('keyboard', 'cut_to_buffer') struct.yank_from_buffer_key = config.get('keyboard', 'yank_from_buffer') struct.clear_word_key = config.get('keyboard', 'clear_word') struct.clear_line_key = config.get('keyboard', 'clear_line') struct.clear_screen_key = config.get('keyboard', 'clear_screen') struct.delete_key = config.get('keyboard', 'delete') struct.exit_key = config.get('keyboard', 'exit') struct.last_output_key = config.get('keyboard', 'last_output') struct.pastebin_confirm = config.getboolean('general', 'pastebin_confirm') struct.pastebin_private = config.getboolean('general', 'pastebin_private') struct.pastebin_url = config.get('general', 'pastebin_url') struct.pastebin_private = config.get('general', 'pastebin_private') struct.pastebin_show_url = config.get('general', 'pastebin_show_url') struct.pastebin_helper = config.get('general', 'pastebin_helper') struct.cli_suggestion_width = config.getfloat('cli', 'suggestion_width') struct.cli_trim_prompts = config.getboolean('cli', 'trim_prompts') struct.complete_magic_methods = config.getboolean( 'general', 'complete_magic_methods') methods = config.get('general', 'magic_methods') struct.magic_methods = [meth.strip() for meth in methods.split(",")] struct.autocomplete_mode = config.get('general', 'autocomplete_mode') struct.gtk_font = config.get('gtk', 'font') color_scheme_name = config.get('general', 'color_scheme') color_gtk_scheme_name = config.get('gtk', 'color_scheme') default_colors = { 'keyword': 'y', 'name': 'c', 'comment': 'b', 'string': 'm', 'error': 'r', 'number': 'G', 'operator': 'Y', 'punctuation': 'y', 'token': 'C', 'background': 'd', 'output': 'w', 'main': 'c', 'paren': 'R', 'prompt': 'c', 'prompt_more': 'g', } default_gtk_colors = { 'keyword': 'b', 'name': 'k', 'comment': 'b', 'string': 'm', 'error': 'r', 'number': 'G', 'operator': 'B', 'punctuation': 'g', 'token': 'C', 'background': 'w', 'output': 'k', 'main': 'c', 'paren': 'R', 'prompt': 'b', 'prompt_more': 'g', } if color_scheme_name == 'default': struct.color_scheme = default_colors else: struct.color_scheme = dict() theme_filename = color_scheme_name + '.theme' path = os.path.expanduser( os.path.join(get_config_home(), theme_filename)) old_path = os.path.expanduser( os.path.join('~/.bpython', theme_filename)) for path in [path, old_path]: try: load_theme(struct, path, struct.color_scheme, default_colors) except EnvironmentError: continue else: break else: sys.stderr.write("Could not load theme '%s'.\n" % (color_scheme_name, )) sys.exit(1) if color_gtk_scheme_name == 'default': struct.color_gtk_scheme = default_gtk_colors else: struct.color_gtk_scheme = dict() # Note: This is a new config option, hence we don't have a # fallback directory. path = os.path.expanduser( os.path.join(get_config_home(), color_gtk_scheme_name + '.theme')) try: load_theme(struct, path, struct.color_gtk_scheme, default_colors) except EnvironmentError: sys.stderr.write("Could not load gtk theme '%s'.\n" % (color_gtk_scheme_name, )) sys.exit(1) # checks for valid key configuration this part still sucks for key in (struct.pastebin_key, struct.save_key): key_dispatch[key]
def plot(self): """Plot chart""" Preferences = ConfigParser() Preferences.read("psyrc") self.diagrama2D.axes2D.clear() self.diagrama2D.config() filename = "%i.pkl" % P if os.path.isfile(filename): with open(filename, "r") as archivo: data = cPickle.load(archivo) self.status.setText("Loading cached data...") QApplication.processEvents() else: self.progressBar.setVisible(True) self.status.setText("Calculating data, be patient...") QApplication.processEvents() data = PsyCoolprop.calculatePlot(self) cPickle.dump(data, open(filename, "w")) self.progressBar.setVisible(False) self.status.setText("Plotting...") QApplication.processEvents() tmax = Preferences.getfloat("Psychr", "isotdbEnd") - 273.15 t = [ti - 273.15 for ti in data["t"]] Hs = data["Hs"] format = {} format["ls"] = Preferences.get("Psychr", "saturationlineStyle") format["lw"] = Preferences.getfloat("Psychr", "saturationlineWidth") format["color"] = Preferences.get("Psychr", "saturationColor") format["marker"] = Preferences.get("Psychr", "saturationmarker") format["markersize"] = 3 self.diagrama2D.plot(t, Hs, **format) format = {} format["ls"] = Preferences.get("Psychr", "isotdblineStyle") format["lw"] = Preferences.getfloat("Psychr", "isotdblineWidth") format["color"] = Preferences.get("Psychr", "isotdbColor") format["marker"] = Preferences.get("Psychr", "isotdbmarker") format["markersize"] = 3 for i, T in enumerate(t): self.diagrama2D.plot([T, T], [0, Hs[i]], **format) H = data["H"] th = data["th"] format = {} format["ls"] = Preferences.get("Psychr", "isowlineStyle") format["lw"] = Preferences.getfloat("Psychr", "isowlineWidth") format["color"] = Preferences.get("Psychr", "isowColor") format["marker"] = Preferences.get("Psychr", "isowmarker") format["markersize"] = 3 for i, H in enumerate(H): self.diagrama2D.plot([th[i], tmax], [H, H], **format) format = {} format["ls"] = Preferences.get("Psychr", "isohrlineStyle") format["lw"] = Preferences.getfloat("Psychr", "isohrlineWidth") format["color"] = Preferences.get("Psychr", "isohrColor") format["marker"] = Preferences.get("Psychr", "isohrmarker") format["markersize"] = 3 for Hr, H0 in data["Hr"].iteritems(): self.diagrama2D.plot(t, H0, **format) self.drawlabel("isohr", Preferences, t, H0, Hr, "%") format = {} format["ls"] = Preferences.get("Psychr", "isotwblineStyle") format["lw"] = Preferences.getfloat("Psychr", "isotwblineWidth") format["color"] = Preferences.get("Psychr", "isotwbColor") format["marker"] = Preferences.get("Psychr", "isotwbmarker") format["markersize"] = 3 for T, (H, Tw) in data["Twb"].iteritems(): self.diagrama2D.plot(Tw, H, **format) value = T - 273.15 txt = u"ºC" self.drawlabel("isotwb", Preferences, Tw, H, value, txt) format = {} format["ls"] = Preferences.get("Psychr", "isochorlineStyle") format["lw"] = Preferences.getfloat("Psychr", "isochorlineWidth") format["color"] = Preferences.get("Psychr", "isochorColor") format["marker"] = Preferences.get("Psychr", "isochormarker") format["markersize"] = 3 for v, (Td, H) in data["v"].iteritems(): self.diagrama2D.plot(Td, H, **format) value = v txt = u"m³/kg" self.drawlabel("isochor", Preferences, Td, H, value, txt) self.diagrama2D.draw() self.status.setText("P = %i Pa" % P)
from ConfigParser import ConfigParser CONFIGFILE = "config.file" config = ConfigParser() config.read(CONFIGFILE) print(config.get("messages", "greeting")) radius = float(input(config.get("messages", "question"))) print(config.get("messages", "result_message")) print(config.getfloat("numbers", "pi") * radius**2)
import numpy as np from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg from pylab import Figure from CoolProp.HumidAirProp import HAProps, HAProps_Aux from PyQt4.QtGui import (QDialog, QGridLayout, QProgressBar, QLabel, QDialogButtonBox, QPushButton, QFileDialog, QApplication) Preferences = ConfigParser() config_path = os.path.join(os.path.dirname(__file__), "psyrc") Preferences.read(config_path) P = Preferences.getfloat("General", "P") def _Pbar(Z): """ ASHRAE Fundamentals Handbook pag 1.1 eq. 3 input: Z: altitude, m return standard atmosphere barometric pressure, Pa """ return 101325. * (1 - 2.25577e-5 * Z)**5.256 class PsychroPlot(FigureCanvasQTAgg): """
def configure(self): defaults = {} defaults["message"] = "UNCLASSIFIED" defaults["fgcolor"] = "#FFFFFF" defaults["bgcolor"] = "#007A33" defaults["face"] = "liberation-sans" defaults["size"] = "small" defaults["weight"] = "bold" defaults["show_top"] = True defaults["show_bottom"] = True defaults["hres"] = 0 defaults["vres"] = 0 defaults["sys_info"] = False defaults["opacity"] = 0.75 defaults["esc"] = True defaults["spanning"] = False # Check if a configuration file was passed in from the command line default_heading = DEFAULTSECT conf_parser = ArgumentParser( formatter_class=RawDescriptionHelpFormatter, add_help=False) conf_parser.add_argument("-c", "--config", help="Specify the configuration file", metavar="FILE") conf_parser.add_argument("--heading", help="Specify the config. section to use.", default=default_heading) options, args = conf_parser.parse_known_args() config_file = None if options.config: config_file = os.path.abspath(options.config) if not os.path.isfile(config_file): print("ERROR: Specified configuration file does not exist.") sys.exit(1) else: config_file = os.path.abspath(CONF_FILE) if not os.path.isfile(config_file): config_file = None # In order to maintain backwards compatibility with the way the # previous configuration file format, a dummy section may need # to be added to the configuration file. If this is the case, # a temporary file is used in order to avoid overwriting the # user's configuration. config = ConfigParser() if config_file is not None: fp = open(config_file, "r") while True: try: if sys.hexversion >= 0x03000000: config.read_file(fp, source=config_file) else: config.readfp(fp, config_file) break except MissingSectionHeaderError: # Recreate the file, adding a default section. fp.close() fp = TemporaryFile() with open(config_file) as original: fp.write("[%s]\n" % default_heading + original.read()) fp.seek(0) fp.close() # If this was a temporary file it will now be deleted. # ConfigParser treats everything as strings and any quotation # marks in a setting are explicitly added to the string. # One way to fix this is to add everything to the defaults and # then strip the quotation marks off of everything. defaults.update(dict(config.items(options.heading))) for key, val in defaults.items(): if config.has_option(options.heading, key): defaults[key] = val.strip("\"'") # TODO: This coercion section is hacky and should be fixed. for key in ["show_top", "show_bottom", "sys_info", "esc", "spanning"]: if config.has_option(options.heading, key): defaults[key] = config.getboolean(options.heading, key) for key in ["hres", "vres"]: if config.has_option(options.heading, key): defaults[key] = config.getint(options.heading, key) for key in ["opacity"]: if config.has_option(options.heading, key): defaults[key] = config.getfloat(options.heading, key) # Use the global config to set defaults for command line options parser = ArgumentParser(parents=[conf_parser]) parser.add_argument("-m", "--message", default=defaults["message"], help="Set the Classification message") parser.add_argument("-f", "--fgcolor", default=defaults["fgcolor"], help="Set the Foreground (text) color") parser.add_argument("-b", "--bgcolor", default=defaults["bgcolor"], help="Set the Background color") parser.add_argument("-x", "--hres", default=defaults["hres"], type=int, help="Set the Horizontal Screen Resolution") parser.add_argument("-y", "--vres", default=defaults["vres"], type=int, help="Set the Vertical Screen Resolution") parser.add_argument("-o", "--opacity", default=defaults["opacity"], type=float, dest="opacity", help="Set the window opacity for composted window managers") parser.add_argument("--face", default=defaults["face"], help="Font face") parser.add_argument("--size", default=defaults["size"], help="Font size") parser.add_argument("--weight", default=defaults["weight"], help="Set the Font weight") parser.add_argument("--disable-esc", default=defaults["esc"], dest="esc", action="store_false", help="Disable the 'ESC to hide' feature and don't show the banner message") parser.add_argument("--hide-top", default=defaults["show_top"], dest="show_top", action="store_false", help="Disable the top banner") parser.add_argument("--hide-bottom", default=defaults["show_bottom"], dest="show_bottom", action="store_false", help="Disable the bottom banner") parser.add_argument("--system-info", default=defaults["sys_info"], dest="sys_info", action="store_true", help="Show user and hostname in the top banner") parser.add_argument("--enable-spanning", default=defaults["spanning"], dest="spanning", action="store_true", help="Enable banner(s) to span across screens as a single banner") options = parser.parse_args() return options
fit = minimize(residuals, params, args=(data, )) report_errors(fit.params) return fit.params if __name__ == '__main__': parser = ArgumentParser('Fit sky brightness model parames to data') parser.add_argument("-c", "--config", help="the configuration file") args = parser.parse_args() cfg = ConfigParser() cfg.read(args.config) latitude = cfg.getfloat('Observatory Position', 'latitude') longitude = cfg.getfloat('Observatory Position', 'longitude') data_fname = cfg.get('Measured data', 'fname') d = pd.read_csv(data_fname) d['ra_rad'] = np.radians(d.telra) d['decl_rad'] = np.radians(d.teldec) lst = gmst(d.mjd) + np.radians(longitude) moon_ra, moon_decl, diam = rdplan(d.mjd, 3, np.radians(longitude), np.radians(latitude)) moon_ha = lst - moon_ra moon_zd = calc_zd(np.radians(latitude), moon_ha, moon_decl) d['moon_zd'] = np.degrees(moon_zd) d['moon_angle'] = np.degrees(