Example #1
0
def readROIFile(hfile):
    cp =  ConfigParser()
    cp.read(hfile)
    output = []
    for a in cp.options('rois'):
        if a.lower().startswith('roi'):
            iroi = int(a[3:])
            name, dat = cp.get('rois',a).split('|')
            xdat = [int(i) for i in dat.split()]
            dat = [(xdat[0], xdat[1]), (xdat[2], xdat[3]),
                   (xdat[4], xdat[5]), (xdat[6], xdat[7])]
            output.append((iroi, name.strip(), dat))
    roidata = sorted(output)
    calib = {}

    caldat = cp.options('calibration')
    for attr in ('offset', 'slope', 'quad'):
        calib[attr] = [float(x) for x in cp.get('calibration', attr).split()]
    dxp = {}
    ndet = len(calib['offset'])
    for attr in cp.options('dxp'):
        tmpdat = [x for x in cp.get('dxp', attr).split()]
        if len(tmpdat) == 2*ndet:
            tmpdat = ['%s %s' % (i, j) for i, j in zip(tmpdat[::2], tmpdat[1::2])]
        try:
            dxp[attr] = [int(x) for x in tmpdat]
        except ValueError:
            try:
                dxp[attr] = [float(x) for x in tmpdat]
            except ValueError:
                dxp[attr] = tmpdat
    return roidata, calib, dxp
Example #2
0
    def from_file(cls, file_name):
        """ Make a Config from a file. """
        file_name = os.path.expanduser(file_name)

        parser = ConfigParser()
        # IMPORTANT: Turn off downcasing of option names.
        parser.optionxform = str

        parser.read(file_name)
        cfg = Config()
        if parser.has_section('index_values'):
            for repo_id in parser.options('index_values'):
                cfg.version_table[repo_id] = (
                    parser.getint('index_values', repo_id))
        if parser.has_section('request_usks'):
            for repo_dir in parser.options('request_usks'):
                cfg.request_usks[repo_dir] = parser.get('request_usks',
                                                        repo_dir)
        if parser.has_section('insert_usks'):
            for repo_id in parser.options('insert_usks'):
                cfg.insert_usks[repo_id] = parser.get('insert_usks', repo_id)

        # ignored = fms_id|usk_hash|usk_hash|...
        if parser.has_section('fmsread_trust_map'):
            cfg.fmsread_trust_map.clear() # Wipe defaults.
            for ordinal in parser.options('fmsread_trust_map'):
                fields = parser.get('fmsread_trust_map',
                                    ordinal).strip().split('|')
                Config.validate_trust_map_entry(cfg, fields)
                cfg.fmsread_trust_map[fields[0]] = tuple(fields[1:])

        Config.update_defaults(parser, cfg)

        cfg.file_name = file_name
        return cfg
Example #3
0
 def read_properties(self, property_file="Coordinator.properties"):
         """ process properties file """
         ## Reads the configuration properties
         cfg = ConfigParser()
         cfg.read(property_file)
         self.install_dir = cfg.get("config", "install_dir")
         self.euca_rc_dir = cfg.get("config", "euca_rc_dir")
         self.initial_cluster_size = cfg.get("config", "initial_cluster_size")
         self.max_cluster_size = cfg.get("config", "max_cluster_size")
         self.bucket_name = cfg.get("config", "bucket_name")
         self.instance_type = cfg.get("config", "instance_type")
         self.cluster_name = cfg.get("config", "cluster_name")
         self.hostname_template = cfg.get("config", "hostname_template")
         self.reconfigure = cfg.get("config", "reconfigure")
         self.cluster_type = cfg.get("config", "cluster_type")
         self.db_file = cfg.get("config", "db_file")
         self.add_nodes = cfg.get("config", "add_nodes")
         self.rem_nodes = cfg.get("config", "rem_nodes")
         self.cloud_api_type = cfg.get("config", "cloud_api_type")
         self.trans_cost = cfg.get("config", "trans_cost")
         self.gain = cfg.get("config", "gain")
         self.serv_throughput = cfg.get("config", "serv_throughput")
         try:
             self.gamma = cfg.get("config", "gamma")
         except:
             self.gamma = 0
         
         ## Reads the monitoring thresholds
         self.thresholds_add = {}
         self.thresholds_remove = {}
         for option in cfg.options("thresholds_add"):
             self.thresholds_add[option] = cfg.get("thresholds_add", option)
         for option in cfg.options("thresholds_remove"):
             self.thresholds_remove[option] = cfg.get("thresholds_remove", option)
Example #4
0
    def getViewsForModule(self, module, model):
        """
        @param module: the name of the model to get the views for
        @param model: the L{commitmessage.model.Model} to initialize views with
        @return: the configured views for a module
        """
        viewLine = ConfigParser.get(self, module, 'views')
        p = re.compile(',\s?')
        viewNames = [name.strip() for name in p.split(viewLine) if len(name.strip()) > 0]

        userMap = self.userMap

        views = []
        for viewName in viewNames:
            fullClassName = ConfigParser.get(self, 'views', viewName)
            view = getNewInstance(fullClassName)
            view.__init__(viewName, model)

            # Setup default values
            if ConfigParser.has_section(self, viewName):
                for name in ConfigParser.options(self, viewName):
                    value = ConfigParser.get(self, viewName, name, 1)
                    view.__dict__[name] = str(Itpl(value))

            # Setup module-specific values
            forViewPrefix = re.compile('^%s.' % viewName)
            for option in ConfigParser.options(self, module):
                if forViewPrefix.search(option):
                    # Take off the 'viewName.'
                    name = option[len(viewName)+1:]
                    value = ConfigParser.get(self, module, option, 1)
                    view.__dict__[name] = str(Itpl(value))

            views.append(view)
        return views
Example #5
0
class PrintersConfig:
    def __init__(self):
        self.Config = ConfigParser()
        self.Config2 = ConfigParser()
        self.Config.read(os.path.join("/etc/printerstats/config", "printers.ini"))
        self.Config2.read(os.path.join("/etc/printerstats/config", "config.ini"))

    def ConfigMap(self, section):
        dict1 = {}
        options = self.Config2.options(section)
        for option in options:
            dict1[option] = self.Config2.get(section, option)
        return dict1


    def CampusMap(self, section):
        dict1 = {}
        options = self.Config.options(section)
        for option in options:
            dict1[section] = self.Config.get(section, option)
        return dict1


    def ConfigMapPrinters(self, section):
        dict1 = {section: {}}
        options = self.Config.options(section)
        for option in options:
            dict1[section][option] = self.Config.get(section, option)
        return dict1
Example #6
0
def main():
    cp = ConfigParser()
    cp.read(sys.argv[1])
    certfile = cp.get('sslexport', 'pemfile')
    external = cp.get('sslexport', 'external')
    internal = '127.0.0.1'
  
    # External (SSL) listeners
    for ext_port in cp.options('sslexport.server'):
        ipport = cp.get('sslexport.server', ext_port)
        ip,port = ipport.split(':')
        server = gevent.server.StreamServer(
            (external, int(ext_port)),
            Forwarder(ip, port, gevent.socket.socket),
            certfile=certfile)
        server.start()
        print 'ssl(%s:%s) => clear(%s:%s)' % (
            external, ext_port, ip, port)
  
    # Internal (non-SSL) listeners
    for int_port in cp.options('sslexport.client'):
        ipport = cp.get('sslexport.client', int_port)
        ip,port = ipport.split(':')
        server = gevent.server.StreamServer(
            (internal, int(int_port)),
            Forwarder(ip, port, lambda:gevent.ssl.SSLSocket(gevent.socket.socket())),
            certfile=certfile)
        server.start()
        print 'clear(%s:%s) => ssl(%s:%s)' % (
            internal, int_port, ip, port)
  
    while True:
        gevent.sleep(10)
        print '--- mark ---'
def createDictFromConfig():
    """ Read the configuration from scipion/config/scipionbox.conf.
     A dictionary will be created where each key will be a section starting
     by MICROSCOPE:, all variables that are in the GLOBAL section will be
     inherited by default.
    """
    # Read from users' config file.
    confGlobalDict = OrderedDict()
    confDict = OrderedDict()

    cp = ConfigParser()
    cp.optionxform = str  # keep case (stackoverflow.com/questions/1611799)

    confFile = pw.getConfigPath("scipionbox.conf")

    print "Reading conf file: ", confFile
    cp.read(confFile)

    GLOBAL = "GLOBAL"
    MICROSCOPE = "MICROSCOPE:"

    if not GLOBAL in cp.sections():
        raise Exception("Missing section %s in %s" % (GLOBAL, confFile))
    else:
        for opt in cp.options(GLOBAL):
            confGlobalDict[opt] = cp.get(GLOBAL, opt)

    for section in cp.sections():
        if section != GLOBAL and section.startswith(MICROSCOPE):
            sectionDict = OrderedDict(confGlobalDict)
            for opt in cp.options(section):
                sectionDict[opt] = cp.get(section, opt)
            confDict[section.replace(MICROSCOPE, '')] = sectionDict

    return confDict
Example #8
0
def readROIFile(hfile):
    cp =  ConfigParser()
    cp.read(hfile)
    roiout = []
    try:
        rois = cp.options('rois')
    except:
        print 'rois not found'
        return []

    for a in cp.options('rois'):
        if a.lower().startswith('roi'):
            iroi = int(a[3:])
            name, dat = cp.get('rois',a).split('|')
            xdat = [int(i) for i in dat.split()]
            dat = [(xdat[0], xdat[1]), (xdat[2], xdat[3]),
                   (xdat[4], xdat[5]), (xdat[6], xdat[7])]
            roiout.append((iroi, name.strip(), dat))
    roiout = sorted(roiout)
    calib = {}
    calib['CAL_OFFSET'] = cp.get('calibration', 'OFFSET')
    calib['CAL_SLOPE']  = cp.get('calibration', 'SLOPE')
    calib['CAL_QUAD']   = cp.get('calibration', 'QUAD')
    calib['CAL_TWOTHETA']   = ' 0 0 0 0'
    return roiout, calib
Example #9
0
def readScanConfig(sfile):
    cp =  ConfigParser()
    cp.read(sfile)
    scan = {}
    for a in cp.options('scan'):
        scan[a]  = cp.get('scan',a)
    general = {}
    for a in cp.options('general'):
        general[a]  = cp.get('general',a)
    return scan, general
Example #10
0
def readROIFile(hfile,xrd=False):

    cp =  ConfigParser()
    cp.read(hfile)
    output = []

    if xrd:
        for a in cp.options('xrd1d'):
            if a.lower().startswith('roi'):
                iroi = int(a[3:])
                name,unit,dat = cp.get('xrd1d',a).split('|')
                lims = [float(i) for i in dat.split()]
                dat = [lims[0], lims[1]]
                output.append((iroi, name.strip(), unit.strip(), dat))
        return sorted(output)

    else:
        for a in cp.options('rois'):
            if a.lower().startswith('roi'):
                iroi = int(a[3:])
                name, dat = cp.get('rois',a).split('|')
                lims = [int(i) for i in dat.split()]
                ndet = int(len(lims)/2)
                dat = []
                for i in range(ndet):
                    dat.append((lims[i*2], lims[i*2+1]))
                output.append((iroi, name.strip(), dat))
        roidata = sorted(output)

        calib = {}

        caldat = cp.options('calibration')
        for attr in ('offset', 'slope', 'quad'):
            calib[attr] = [float(x) for x in cp.get('calibration', attr).split()]
        extra = {}
        ndet = len(calib['offset'])
        file_sections = cp.sections()
        for section in ('dxp', 'extra'):
            if section not in file_sections:
                continue
            for attr in cp.options(section):
                tmpdat = [x for x in cp.get(section, attr).split()]
                if len(tmpdat) == 2*ndet:
                    tmpdat = ['%s %s' % (i, j) for i, j in zip(tmpdat[::2], tmpdat[1::2])]
                try:
                    extra[attr] = [int(x) for x in tmpdat]
                except ValueError:
                    try:
                        extra[attr] = [float(x) for x in tmpdat]
                    except ValueError:
                        extra[attr] = tmpdat


        return roidata, calib, extra
    def __init__(self, cfg_file):
        PARSER = ConfigParser()
        PARSER.read(cfg_file)

        for cfg_section in PARSER.sections():
            # First round, create objects
            for cfg_option in PARSER.options(cfg_section):
                setattr(self, cfg_section, self.StandInObject())
            # Second round, add attributes
            for cfg_option in PARSER.options(cfg_section):
                # Set the values for the section options
                setattr(getattr(self, cfg_section), cfg_option, PARSER.get(cfg_section, cfg_option))
Example #12
0
def read_stageconfig(filename=None, _larch=None):
    """read Sample Stage configurattion file, saving results

    Parameters
    ----------
    filename:   None or string, name of file holding sample positions (see Note)

    Examples
    --------
      read_stageconfig()

    Notes
    ------
      1. If filename is None (the default) 'SampleStage_autosave.ini'
         from the current working folder is used.
      2. the file timestamp is always tested to find new position names
      3. Generally, you don't need to do this explicitly, as
         move_samplestage will run this when necessary.

    """
    if filename is None: filename = DEF_SampleStageFile
    if not os.path.exists(filename): 
       print 'No stageconfig found!'
       return None
    #endif

    stages = []
    positions = OrderedDict()
    ini = ConfigParser()
    ini.read(filename)

    for item in ini.options('stages'):
        line = ini.get('stages', item)
        words = [i.strip() for i in line.split('||')]
        stages.append(words[0])
    #endfor

    for item in ini.options('positions'):
        line = ini.get('positions', item)
        words = [i.strip() for i in line.split('||')]
        name = words[0].lower()
        vals = [float(i) for i in words[2].split(',')]
        positions[name] = vals
    #endfor
    this = Group(pos=positions, stages=stages,
                 _modtime_=os.stat(filename).st_mtime)
    if _larch is not None:
        if not _larch.symtable.has_group('macros'):
            _larch.symtable.new_group('macros')
        _larch.symtable.macros.stage_conf = this
    print(" Read %d positions from stage configuration." % len(positions) )
        
    return this
Example #13
0
class TesseraConfig(object):
    def __init__(self, path):
        self._path = path
        self._config = ConfigParser()
        if os.path.exists(path):
            self._parse()

    def get_path(self):
        return self._path

    def _parse(self):
        self._config.read(self._path)

    def has_option(self, section, option):
        try:
            self._config.get(section, option)
            return True
        except:
            return False

    def get_option_index(self, section, option):
        try:
            options = self._config.options(section)
        except:
            return -1
        try:
            return options.index(option)
        except:
            return -1

    def get_option_name(self, section, idx):
        try:
            options = self._config.options(section)
        except:
            return "?"
        if idx == None:
            return "no " + section
        return options[idx]

    def get(self, section, option):
        try:
            return self._config.get(section, option)
        except NoSectionError:
            raise ConfigSectionNotFoundError(section, self._path)
        except NoOptionError:
            raise ConfigOptionNotFoundError(option, section, self._path)

    def set(self, section, option, value):
        self._config.set(section, option, value)

    def store(self):
        with open(self._path, "w") as f:
            self._config.write(f)
Example #14
0
def generate_config():
    config_parser = ConfigParser()
    current_directory = os.path.dirname(os.path.abspath(__file__))
    config_parser.read(os.path.normpath(os.path.join(current_directory, '..', 'secrets', 'secrets.ini')))

    config = dict(zip([option.upper() for option in config_parser.options('core')],
                [config_parser.get('core', y) for y in config_parser.options('core')]))

    for section in [s for s in config_parser.sections() if s != 'core']:
        config[section] = ConfigStruct(dict(zip(config_parser.options(section),
                [config_parser.get(section, y) for y in config_parser.options(section)])))

    return config
Example #15
0
    def init_from_options(self):

        # If a config file is provided, read it into the ABACManager
        if self._options.config:
            cp = ConfigParser()
            cp.optionxform=str
            cp.read(self._options.config)

            for name in cp.options('Principals'):
                cert_file = cp.get('Principals', name)
                self.register_id(name, cert_file)

            for name in cp.options('Keys'):
                key_file = cp.get('Keys', name)
                self.register_key(name, key_file)

            if 'Assertions' in cp.sections():
                for assertion in cp.options('Assertions'):
                    self.register_assertion(assertion)

            if 'AssertionFiles' in cp.sections():
                for assertion_file in cp.options("AssertionFiles"):
                    self.register_assertion_file(assertion_file)

        # Use all the other command-line options to override/augment 
        # the values in the ABCManager

        # Add new principal ID's / keys
        if self._options.id:
            for id_filename in options.id:
                parts = id_filename.split(':')
                id_name = parts[0].strip()
                id_cert_file = None
                if len(parts) > 1:
                    id_cert_file = parts[1].strip()
                    self.register_id(id_name, id_cert_file)
                    
                id_key_file = None
                if len(parts) > 2:
                    id_key_file = parts[2].strip()
                    self.register_key(name, id_key_file)

        # Register assertion files provided by command line
        if self._options.assertion_file:
            for assertion_file in self._options.assertion_file:
                self.register_assertion_file(assertion_file)

        # Grab pure ABAC assertions from commandline
        if self._options.assertion:
            for assertion in self._options.assertion:
                self.register_assertion(assertion)
Example #16
0
    def writeConfigFiles2Database(self):
        print '-------------------------------------------------------------------------- start write config2SQL'
        
        cParser = ConfigParser()
        cParser.read(self.CUON_FS + '/user.cfg')
        try:
            sP = cParser.get('password',self.POSTGRES_USER)
            print sP
            sID = self.xmlrpc_createSessionID(self.POSTGRES_USER, sP)
                
        
            dicUser = {'Name': self.POSTGRES_USER, 'SessionID':sID, 'userType':'cuon' }
            print '2-------------------------------------------------------------------------- start write config2SQL ',  dicUser
            
            
                        
                        
           #clients
            sSql = "select id from clients where status != 'delete'"
            result = self.xmlrpc_executeNormalQuery(sSql, dicUser )
            print '3-------------------------------------------------------------------------- start write config2SQL ',  sSql,  result

            if result and result not in self.liSQL_ERRORS:
                for row  in result:
                    client_id = row["id"]
                    cpSection = "CLIENT_" + `client_id`
                    cParser = ConfigParser()
                    cParser.read(self.CUON_FS + '/clients.ini')
                    print '4-------------------------------------------------------------------------- start write config2SQL'

                    if cParser. has_section(cpSection):
                        print cParser.options(cpSection)
                        for sOptions in self.liClientsOptions:
                            print '5-------------------------------------------------------------------------- start write config2SQL ',  cpSection,  sOptions

                            sValue = self.getConfigOption(cpSection, sOptions,  cParser)
                            if sValue:
                                print '6-------------------------------------------------------------------------- start write config2SQL ', cpSection, sOptions, sValue
                                sSql = "select * from fct_write_config_value(" + `client_id` + ", '" + 'clients.ini' + "', '" + cpSection + "', '" + sOptions + "', '" + sValue + "' ) "
                                print sSql
                                self.xmlrpc_executeNormalQuery(sSql, dicUser)
                                
            sSql =  "select * from fct_get_config_option(1,'clients.ini', 'client_1', 'order_main_headline_articles_id') "
            print sSql
            result = self.xmlrpc_executeNormalQuery(sSql, dicUser)
            print result 
                           
                          
                         
        except Exception,  params:
            print Exception,  params
Example #17
0
def parse_ini(path, names):
    """
    Parse the deployment file.

    This function parses the deployment file, searching for sections
    that specify rulesets; these sections should have the name
    ``wsgirewrite:``, followed by the name of the ruleset. Eg::

        [wsgirewrite:blocked]
        cond1 = %{REMOTE_HOST} !^.*example.com$
        rule1 = ^.*$ - F

    The ruleset aboved is called "blocked", and will be applied if
    it is in the parameter ``names``. Condition and rules are sorted
    by their names, which should start with ``cond`` and ``rule``,
    respectively.

    """
    from ConfigParser import ConfigParser

    # Read the deployment file.
    config = ConfigParser()
    config.read(path)
    names = names.split()

    # Get relevant sections.
    sections = [section for section in config.sections() if
            section.startswith('wsgirewrite:') and
            section.split(':')[1] in names]

    rulesets = []
    for section in sections:
        conditions = []
        directives = []

        # Parse config.
        conds = [option for option in config.options(section)
                if option.startswith('cond')]
        conds.sort()
        rules = [option for option in config.options(section)
                if option.startswith('rule')]
        rules.sort()
        for cond in conds:
            line = config.get(section, cond)
            conditions.append(parse_line(line))
        for rule in rules:
            line = config.get(section, rule)
            directives.append(parse_line(line))

        rulesets.append((conditions, directives))
    return rulesets
Example #18
0
def registerStats(config_file):
    print "==============================="
    print "Parsing stats config.ini file..."
    print config_file
    print "==============================="

    config = ConfigParser()
    if not config.read(config_file):
        print "ERROR: config file '", config_file, "' not found!"
        sys.exit(1)

    print "\nRegistering Stats..."

    stats = Stats()

    per_cpu_stat_groups = config.options('PER_CPU_STATS')
    for group in per_cpu_stat_groups:
        i = 0
        per_cpu_stats_list = config.get('PER_CPU_STATS', group).split('\n')
        for item in per_cpu_stats_list:
            if item:
                stats.register(item, group, i, True)
                i += 1

    per_l2_stat_groups = config.options('PER_L2_STATS')
    for group in per_l2_stat_groups:
        i = 0
        per_l2_stats_list = config.get('PER_L2_STATS', group).split('\n')
        for item in per_l2_stats_list:
            if item:
                for l2 in range(num_l2):
                    if num_l2 > 1:
                        name = re.sub("#", str(l2), item)
                    else:
                        name = re.sub("#", "", item)
                    stats.register(name, group, i, False)
                i += 1

    other_stat_groups = config.options('OTHER_STATS')
    for group in other_stat_groups:
        i = 0
        other_stats_list = config.get('OTHER_STATS', group).split('\n')
        for item in other_stats_list:
            if item:
                stats.register(item, group, i, False)
                i += 1

    stats.createStatsRegex()

    return stats
Example #19
0
    def values(self):
        # get schemas defaults
        schema = self._schema_
        values = self._default_values_()
        
        # let's parse configuration file
        cp = ConfigParser()
        cp.read(self._configuration_file_)

        # Sections verifications
        unused_sections = [section for section in cp.sections() \
                           if section not in schema.keys()]
        if unused_sections != []:
            raise ConfigurationSectionNotUsed, \
                  "Section(s) not used in configuration file : %s" % \
                  ' '.join(unused_sections)
        
        not_found_sections = [section for section in schema.keys() \
                              if section not in cp.sections()]
        if not_found_sections != []:
            raise ConfigurationSectionNotFound, \
                  "Section(s) not found in configuration file : %s" % \
                  ' '.join(not_found_sections)

        # Options verifications and merging
        for section in schema:
            not_used_options = [option for option in cp.options(section) \
                                if option not in schema[section] and not '_any_' in schema[section]]
            if not_used_options != []:
                raise ConfigurationOptionNotUsed, \
                    'Option(s) not used in section \'%s\' : %s' % \
                    (section, ' '.join(not_used_options))

            for option in cp.options(section):
                if option in schema[section]:
                    t = schema[section][option]['type']
                elif 'any' in schema[section]:
                    t = schema[section]['_any_']['type']

                try:
                    v = t( cp.get(section,option) )
                except ValueError:
                    raise ConfigurationOptionTypeMismatch, \
                          'Option \'%s\' must be \'%s\'' % (option, t.__name__)
                if section == 'default':
                    values[option] = v
                else:
                    values['%s.%s' % (section, option)] = v
        return values
Example #20
0
def getDataSources(fName = None):
    ''' return data sources directories for this machine.
    directories are defined in datasources.ini or provided filepath'''
    import socket
    from ConfigParser import ConfigParser

    pcName = socket.gethostname()

    p = ConfigParser()
    p.optionxform = str


    if fName is None:
        fName = 'datasources.ini'

    p.read(fName)

    if pcName not in p.sections():
        raise NameError('Host name section %s not found in file %s' %(pcName,fName))

    dataSources = {}
    for option in p.options(pcName):
        dataSources[option] = p.get(pcName,option)

    return dataSources
Example #21
0
 def read_config(self, config_path):
     config_parser = ConfigParser()
     config_parser.read(config_path)
     for section in config_parser.sections():
         for option in config_parser.options(section):
             value = config_parser.get(section, option)
             setattr(self, option, value)
def _load_configuration(environment, path):
        """Loads a given configuration file specified by path and environment header (ini file).
        returns a key value representing the configuration. Values enclosed in {} are automatically
        decrypted using the $FURTHER_PASSWORD variable. Values that equal [RND] will be replaced with
        a random string."""

        # Read configuration file
        parser = ConfigParser()
        parser.read(path)

        config = {}
        for option in parser.options(environment):
                value = parser.get(environment, option)

                # Handle encrypted configuration
                if (re.match(r'^\{.*\}$', value)):
                        encrypted_value = re.match(r'^\{(.*)\}$', value).group(1)
                        value = (local('decrypt.sh input="' + encrypted_value + '" password=$FURTHER_PASSWORD algorithm="PBEWithSHA1AndDESede" verbose="false"', capture=True))

                # Handle random values
                if (re.match(r'\[RND\]', value)):
                        value = _random_string()

                config[option] = value;

        return config
Example #23
0
    def restore_rois(self, roifile):
        """restore ROI setting from ROI.dat file"""
        cp =  ConfigParser()
        cp.read(roifile)
        rois = []
        self.mcas[0].clear_rois()
        prefix = self.mcas[0]._prefix
        if prefix.endswith('.'):
            prefix = prefix[:-1]
        iroi = 0
        for a in cp.options('rois'):
            if a.lower().startswith('roi'):
                name, dat = cp.get('rois', a).split('|')
                lims = [int(i) for i in dat.split()]
                lo, hi = lims[0], lims[1]
                roi = ROI(prefix=prefix, roi=iroi)
                roi.left = lo
                roi.right = hi
                roi.name = name.strip()
                rois.append(roi)
                iroi += 1

        epics.poll(0.050, 1.0)
        self.mcas[0].set_rois(rois)
        cal0 = self.mcas[0].get_calib()
        for mca in self.mcas[1:]:
            mca.set_rois(rois, calib=cal0)
Example #24
0
 def _set_config_all(self, path_to_file):
     out = sys.stdout
     if not os.access(path_to_file, os.R_OK):
         self.log.warning( "cannot access file %s" % path_to_file )
         return
     elif not self.env.config:
         self.log.warning( "cannot access config file trac.ini" )
         return
     
     cfg = ConfigParser()
     cfg.read(path_to_file)
     
     if os.access(self.env.path, os.W_OK):
         path_to_trac_ini = os.path.join(self.env.path, 'conf', 'trac.ini')
         shutil.copy(path_to_trac_ini, path_to_trac_ini + '.bak')
         out.write( "created a backup of trac.ini to %s.bak" % path_to_trac_ini )
         out.write('\n')
     else:
         out.write( "could not create backup of trac.ini - continue anyway? [y|n] "  )
         input = sys.stdin.readline()
         if not input or not input.strip() == 'y':
             return
     
     for sect in cfg.sections():
         for opt in cfg.options(sect):
             self.config.set(sect, opt, cfg.get(sect, opt))
             out.write( "added config [%s] %s = %s" % (sect, opt, cfg.get(sect, opt)) )
             out.write('\n')
     self.config.save()
    def write_ini_config_file(self, command, data, client):
        """\
        Write the new command configuration in the plugin configuration file
        """
        try:

            # read the config file
            config = ConfigParser()
            config.read(command.plugin.config.fileName)

            # if there is no commands section
            if not config.has_section('commands'):
                raise NoSectionError('could not find <commands> section in '
                                     'plugin <%s> config file' % data['plugin_name'])

            # remove the old entry
            found = False
            for temp in config.options('commands'):
                search = temp.split('-')[0]
                if search == command.command:
                    config.remove_option('commands', temp)
                    found = True

            # set the new command option value
            config.set('commands', data['command_name'], data['command_level'])
            self.debug('%s command <%s> in plugin <%s> config file' % ('updated' if found else 'created new entry for',
                                                                       command.command, data['plugin_name']))

            # write the updated configuration file
            with open(command.plugin.config.fileName, 'wb') as configfile:
                config.write(configfile)

        except (IOError, NoSectionError), e:
            self.warning('could not change plugin <%s> config file: %s' % (data['plugin_name'], e))
            client.message('^7could not change plugin ^1%s ^7config file' % data['plugin_name'])
Example #26
0
    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 read():
        """
            Loads default variables from the 'resources/settings.ini' file.

            Arguments:
            - None.

            Return:
            - None.
        """
        try:
            p = BuiltIn().get_variable_value('${resources_path}')
            if p is not None:
                _settingsFullFileName = join(p, _settingsFileName)
            else:
                _settingsFullFileName = join(getcwd(), 'resources',
                                             _settingsFileName)

            conf = ConfigParser()
            conf.read(_settingsFullFileName)

            for setting in conf.options('default'):
                BuiltIn().set_global_variable('${%s}' % setting,
                                              conf.get('default', setting))
        except:
            pass
Example #28
0
def process_l10n_ini(inifile):
    """Read a Mozilla l10n.ini file and process it to find the localisation files
    needed by a project"""

    l10n = ConfigParser()
    l10n.readfp(open(path_neutral(inifile)))
    l10n_ini_path = os.path.dirname(inifile)

    for dir in l10n.get('compare', 'dirs').split():
        frompath = os.path.join(l10n_ini_path, l10n.get('general', 'depth'), dir, 'locales', 'en-US')
        if verbose:
            print '%s -> %s' % (frompath, os.path.join(l10ncheckout, 'en-US', dir))
        try:
            shutil.copytree(frompath, os.path.join(l10ncheckout, 'en-US', dir))
        except OSError:
            print 'ERROR: %s does not exist' % frompath

    try:
        for include in l10n.options('includes'):
            include_ini = os.path.join(
                l10n_ini_path, l10n.get('general', 'depth'), l10n.get('includes', include)
            )
            if os.path.isfile(include_ini):
                process_l10n_ini(include_ini)
    except TypeError:
        pass
    except NoSectionError:
        pass
Example #29
0
def get_params(args, params_file):
    """Extracts 'alignments' and 'annotations' parameters from either args or params_file"""
    def override(section, names):
        for name in names:
            value = getattr(args, name)
            if not params.has_key(section):
                params[section] = {}
            if not params[section].has_key(name) or value is not None:
                params[section][name] = value

    params = {}
    if params_file is not None and os.path.exists(params_file):
        cfg = ConfigParser()
        cfg.read(params_file)
        for section in cfg.sections():
            params[section] = {}
            for option in cfg.options(section):
                value = cfg.get(section, option)
                if value.lower() in ('true', 'false'):
                    if value.lower() == 'true':
                        value = True
                    else:
                        value = False
                elif ' ' in value:
                    value = value.split()
                elif value.isspace():
                    value = None
                params[section][option] = value

    override('alignments', ('genome_index', 'transcripts_fasta', 'sort_mem'))
    override('annotations', ('genome_fasta', 'gtf', 'suppl_annot'))

    return params
Example #30
0
def _scan_plugins():
    """Scan the plugins directory for .ini files and parse them
    to gather plugin meta-data.

    """
    pd = os.path.dirname(__file__)
    ini = glob(os.path.join(pd, '*.ini'))

    for f in ini:
        cp = ConfigParser()
        cp.read(f)
        name = cp.sections()[0]

        meta_data = {}
        for opt in cp.options(name):
            meta_data[opt] = cp.get(name, opt)
        plugin_meta_data[name] = meta_data

        provides = [s.strip() for s in cp.get(name, 'provides').split(',')]
        valid_provides = [p for p in provides if p in plugin_store]

        for p in provides:
            if not p in plugin_store:
                print "Plugin `%s` wants to provide non-existent `%s`." \
                      " Ignoring." % (name, p)

        plugin_provides[name] = valid_provides
        plugin_module_name[name] = os.path.basename(f)[:-4]