Esempio n. 1
0
def read_config_file(filename):
    """Return Settings instance built from contents of ``filename`` file."""
    parser = ConfigParser()
    parser.read(filename)
    settings = Settings()
    core_section = 'macman'
    default_section = 'default'
    # Handle core configuration.
    if parser.has_section(core_section):
        section = core_section
        for option in ['directory']:
            if parser.has_option(section, option):
                setattr(settings, option, parser.get(section, option))
    # Handle default configuration.
    if parser.has_section(default_section):
        section = settings.default
        settings.default = dict(parser.items(section))
    # Handle configuration of VMs.
    special_sections = (core_section, default_section)
    for section in parser.sections():
        if section in special_sections:
            continue
        vm_id = section
        settings.vms[vm_id] = dict(parser.items(section))
    return settings
Esempio n. 2
0
def readConfig(filename):
  hostname = os.path.basename(filename).split(".")[0]

  cp = ConfigParser()
  cp.readfp(open(filename))

  if cp.has_section("include"):
    includeFile = cp.get("include", "files")
    config = readConfig(includeFile)
  else:
    config = {}
  
  t = {}
  if hostname != 'common':
    t['hostname'] = hostname

  if cp.has_section("inet_http_server"):    
    port = cp.get("inet_http_server", "port")
    if port != None:
      t['port'] = port.split(":")[1]
    t['username'] = cp.get("inet_http_server", "username")
    t['password'] = cp.get("inet_http_server", "password")

  for k,v in t.items():
    if v != None:
      config[k] = v
  
  return config
Esempio n. 3
0
class StoqdriversConfig:

    domain = 'stoqdrivers'

    def __init__(self, filename=None):
        """ filename is the name of the configuration file we're reading """

        self.filename = filename or (self.domain + '.conf')
        self.config = ConfigParser()
        self._load_config()

    def get_homepath(self):
        return os.path.join(os.getenv('HOME'), '.' + self.domain)

    def _open_config(self, path):
        filename = os.path.join(path, self.filename)
        if not os.path.exists(filename):
            return False
        self.config.read(filename)
        return True

    def _load_config(self):
        # Try to load configuration  from:
        # 1) $HOME/.$domain/$filename
        # 2) $PREFIX/etc/$domain/$filename
        # 3) /etc/$filename
        
        # This is a bit hackish:
        # $prefix / lib / $DOMAIN / lib / config.py
        #    -4      -3     -2      -1       0
        filename = os.path.abspath(__file__)
        stripped = filename.split(os.sep)[:-4]
        self.prefix = os.path.join(os.sep, *stripped)
        
        homepath = self.get_homepath()
        etcpath = os.path.join(self.prefix, 'etc', self.domain)
        globetcpath = os.path.join(os.sep, 'etc', self.domain)
        if not (self._open_config(homepath) or self._open_config(etcpath) or
                self._open_config(globetcpath)):
            raise ConfigError(_("Config file not found in: `%s', `%s' and "
                                "`%s'") % (homepath, etcpath, globetcpath))

    def has_section(self, section):
        return self.config.has_section(section)

    def has_option(self, name, section='General'):
        return self.config.has_option(section, name)
    
    def get_option(self, name, section='General'):
        if not self.config.has_section(section):
            raise  ConfigError(_("Invalid section: %s") % section)
        elif not self.config.has_option(section, name):
            raise ConfigError(_("%s does not have option: %s")
                              % (self.filename, name))
        return self.config.get(section, name)

    def set_option(self, name, section='General'):
        if not self.config.has_section(section):
            raise ConfigError(_("Invalid section: %s") % section)
        self.config.set(section, name)
Esempio n. 4
0
 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 parseConfig(config_file):
    global num_cpus, num_l2

    print "\n==============================="
    print "Parsing gem5 config.ini file..."
    print config_file
    print "===============================\n"
    config = ConfigParser()
    if not config.read(config_file):
        print "ERROR: config file '", config_file, "' not found"
        sys.exit(1)

    if config.has_section("system.cpu"):
        num_cpus = 1
    else:
        num_cpus = 0
        while config.has_section("system.cpu" + str(num_cpus)):
            num_cpus += 1

    if config.has_section("system.l2"):
        num_l2 = 1
    else:
        num_l2 = 0
        while config.has_section("system.l2" + str(num_l2)):
            num_l2 += 1

    print "Num CPUs:", num_cpus
    print "Num L2s:", num_l2
    print ""

    return (num_cpus, num_l2)
Esempio n. 6
0
    def load_ini(self, ini_config):
        """
        Read the provided ini contents arguments and merge
        the data in the ini config into the config object.

        ini_config is assumed to be a string of the ini file contents.
        """
        parser = ConfigParser()
        parser.readfp(StringIO(ini_config))
        data = {
            'linters': {},
            'files': {},
            'branches': {},
        }
        if parser.has_section('files'):
            ignore = parser.get('files', 'ignore')
            data['files']['ignore'] = newline_value(ignore)
        if parser.has_section('branches'):
            ignore = parser.get('branches', 'ignore')
            data['branches']['ignore'] = comma_value(ignore)

        linters = []
        if parser.has_section('tools'):
            linters = comma_value(parser.get('tools', 'linters'))
        # Setup empty config sections
        for linter in linters:
            data['linters'][linter] = {}
        for section in parser.sections():
            if not section.startswith('tool_'):
                continue
            # Strip off tool_
            linter = section[5:]
            data['linters'][linter] = dict(parser.items(section))
        self.update(data)
Esempio n. 7
0
 def test_fork(self):
     repo = HM.Repository(
         name='testrepo.hg',
         fs_path='/tmp/',
         url_path = '/test/',
         tool = 'hg',
         status = 'creating')
     repo_path = pkg_resources.resource_filename(
         'forgehg', 'tests/data/testrepo.hg')
     dirname = os.path.join(repo.fs_path, repo.name)
     if os.path.exists(dirname):
         shutil.rmtree(dirname)
     repo.init()
     repo._impl.clone_from(repo_path, copy_hooks=False)
     assert len(repo.log())
     assert not os.path.exists('/tmp/testrepo.hg/.hg/external-changegroup')
     assert not os.path.exists('/tmp/testrepo.hg/.hg/nested/nested-file')
     assert os.path.exists('/tmp/testrepo.hg/.hg/hgrc')
     cp = ConfigParser()
     cp.read('/tmp/testrepo.hg/.hg/hgrc')
     assert not cp.has_section('other')
     assert cp.has_section('hooks')
     assert not cp.has_option('hooks', 'changegroup.external')
     assert not cp.has_option('hooks', 'commit')
     self.assertEquals(cp.get('hooks', 'changegroup.sourceforge'), 'curl -s http://localhost//auth/refresh_repo/p/test/src-hg/')
     assert not os.path.exists('/tmp/testrepo.hg/.hg/undo.branch')
     shutil.rmtree(dirname)
    def parse_image_build_config(self, config_file_name):

        # Logic taken from koji.cli.koji.handle_image_build.
        # Unable to re-use koji's code because "cli" is not
        # a package of koji and this logic is intermingled
        # with CLI specific instructions.

        args = []
        opts = {}

        config = ConfigParser()
        config.readfp(self.get_default_image_build_conf())
        config.read(config_file_name)

        if self.architectures:
            config.set('image-build', 'arches', ','.join(self.architectures))
        elif self.architecture:
            config.set('image-build', 'arches', self.architecture)
        # else just use what was provided by the user in image-build.conf

        config_str = StringIO()
        config.write(config_str)
        self.log.debug('Image Build Config: \n%s', config_str.getvalue())

        image_name = None

        section = 'image-build'
        for option in ('name', 'version', 'arches', 'target', 'install_tree'):
            value = config.get(section, option)
            if not value:
                raise ValueError('{} cannot be empty'.format(option))
            if option == 'arches':
                value = [arch for arch in value.split(',') if arch]
            elif option == 'name':
                image_name = value
            args.append(value)
            config.remove_option(section, option)

        for option, value in config.items(section):
            if option in ('repo', 'format'):
                value = [v for v in value.split(',') if v]
            elif option in ('disk_size'):
                value = int(value)
            opts[option] = value

        section = 'ova-options'
        if config.has_section(section):
            ova = []
            for k, v in config.items(section):
                ova.append('{}={}'.format(k, v))
            opts['ova_option'] = ova

        section = 'factory-parameters'
        if config.has_section(section):
            factory = []
            for option, value in config.items(section):
                factory.append((option, value))
            opts['factory_parameter'] = factory

        return image_name, args, {'opts': opts}
Esempio n. 9
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
Esempio n. 10
0
	def searchConfig(self, nome):
		arquivo = ConfigParser()
		arquivo.read( self.arqRede )
		if arquivo.has_section( nome ):
			return {
					"ip"            : arquivo.get(nome,"ip"),
					"nome"          : nome,
					"prio"          : arquivo.get(nome,"prio"),
					"delimitado"    : arquivo.get(nome,"delimitado"),
					"isolado"       : arquivo.get(nome,"isolado"),
					"banda_down"    : arquivo.get(nome,"banda_down"),
					"banda_liberada": arquivo.get(nome,"banda_liberada"),
			}
		else:
			arquivo.read( self.arqMaquina )
		if arquivo.has_section( nome ):
			return {
					"ip"            : arquivo.get(nome,"ip"),
					"nome"          : nome,
					"prio"          : arquivo.get(nome,"prio"),
					"delimitado"    : arquivo.get(nome,"delimitado"),
					"isolado"       : arquivo.get(nome,"isolado"),
					"banda_down"    : arquivo.get(nome,"banda_down"),
					"banda_liberada": arquivo.get(nome,"banda_liberada"),
					"isolado"		: arquivo.get(nome,"isolado"),
					"delimitado"	: arquivo.get(nome,"delimitado"),
			}
Esempio n. 11
0
class Host(object):
    log=logging.getLogger('Pipeline')

    def __init__(self, config_file=None, hostname=None):
        self.config=ConfigParser()
        if not config_file:
            root_dir=os.path.abspath(os.path.join(os.path.dirname(__file__)))
            config_file=os.path.join(root_dir, 'config', 'hosts.conf')
            
        if not os.path.exists(config_file):
            raise RuntimeError('%s does not exist' % config_file)
        self.config.read(config_file)

        if hostname and not self.config.has_section(hostname):
            raise NoSectionError(hostname)
        elif not hostname: 
            for hn in [gethostname(), gethostname().split('.')[0]]:
                if self.config.has_section(hn):
                    self.hostname=hn
                    break
            try:
                self.hostname
            except AttributeError, e:
                hn=hostname if hostname else 'localhost (%s)' % gethostname()
                raise NoSectionError(hn)
        else:
Esempio n. 12
0
  def loadCfgFromFile(self):
    if not self.cfgFilePath or not path.exists(self.cfgFilePath):
      return

    cfg = ConfigParser()
    cfg.read(self.cfgFilePath)

    ## Iterate over both server and loader config sectoins as topAttr variable
    for cfgSection in cfgFileMap.keys(): 
      if not cfg.has_section(cfgSection):
        continue #FIXME: might want to raise error here... or warn

      ## This is now either self.server or self.loader depending on which key we are on
      topAttr = getattr(self, cfgSection)

      ## Let check the config file for a matchint config entry
      ## if we find it, set it and override any previous value
      for keyName in cfgFileMap[cfgSection].keys():
        if cfg.has_option(cfgSection, keyName):
          setattr(topAttr, keyName, cfg.get(cfgSection, keyName))
        else:
          print "Missing %s in section %s" % (keyName, cfgSection)
      

    ### Allow for static mapping of files to be configured
    if cfg.has_section('static_map'):
      for uriPath, dirPath in cfg.items('static_map'):
        self.staticMap[uriPath] = dirPath
Esempio n. 13
0
File: sim.py Progetto: ssm2017/pyosm
  def load(self):
    logging.main_logger.debug("[sim] 'load' called")

    # return if not a directory
    if not os.path.isdir(self.path):
      logging.main_logger.warning("[sim] sim %s not found" % (self.path))
      return False

    # check if there is a bin folder
    if os.path.isdir(self.path + '/bin'):
      self.has_bin_folder = True

    # check if there is an OpenSim.ini file
    if os.path.isfile(self.path + '/bin/OpenSim.exe'):
      self.has_opensim_exe = True

    # check if there is an OpenSim.ini file
    if os.path.isfile(self.path + '/bin/OpenSim.ini'):
      self.has_opensim_ini = True

    # check if there is an OpenSim.log file
    if os.path.isfile(self.path + '/log/OpenSim.log'):
      self.has_opensim_log = True

    # check if there is an OpenSim.log file
    if os.path.isfile(self.path + '/log/tmux.log'):
      self.has_tmux_log = True

    # check if there is a Regions.ini file
    if os.path.isfile(self.path + '/bin/Regions/Regions.ini'):
      self.has_regions_ini = True

    # check if RAdmin is enabled
    if self.has_opensim_ini:
      from ConfigParser import ConfigParser
      from helpers import sanitize
      opensim_ini = ConfigParser()
      opensim_ini.read(self.path + '/bin/OpenSim.ini')
      if opensim_ini.has_section('RemoteAdmin'):
        if opensim_ini.has_option('RemoteAdmin', 'enabled'):
          if opensim_ini.get('RemoteAdmin', 'enabled').lower() == 'true':
            if opensim_ini.has_option('RemoteAdmin', 'access_password'):
              self.radmin_password = sanitize(opensim_ini.get('RemoteAdmin', 'access_password'))
              self.radmin_ready = True
      if opensim_ini.has_section('Network'):
        if opensim_ini.has_option('Network', 'http_listener_port'):
          self.port = sanitize(opensim_ini.get('Network', 'http_listener_port'))
      if opensim_ini.has_section('Startup'):
        if opensim_ini.has_option('Startup', 'PIDFile'):
          self.pid_file = sanitize(opensim_ini.get('Startup', 'PIDFile')[1:-1])

    self.valid = self.has_bin_folder and self.pid_file != "" and self.has_opensim_exe and self.has_opensim_log and self.has_opensim_ini and self.has_regions_ini and self.has_tmux_log and self.radmin_ready
    return True
Esempio n. 14
0
 def readConfig(self):
     """ read some parameters from tokeidb.conf. The location of statdb.conf is defined in tokeidb.wsgi. """
     config = ConfigParser()
     files = config.read([os.environ['TOKEIDB_CONFIG_FILE']])
     params = {}
     if config.has_section('db'):
         params['dbhost'] = config.get('db', 'dbhost')
         params['appid'] = config.get('db', 'appid')
     if config.has_section('proxy'):
         params['pxhost'] = config.get('proxy', 'host')
         params['pxport'] = config.get('proxy', 'port')
     return params
Esempio n. 15
0
def setup_config():
    cfg = ConfigParser(CFG_DEFAULTS)
    conf_file = J(WORK_DIR, 'checker.conf')
    cfg.read(conf_file)
    if not cfg.has_section('checker'):
        cfg.add_section('checker')
    if not cfg.has_section('mangos'):
        cfg.add_section('mangos')
    fp = open(conf_file, 'wt')
    cfg.write(fp)
    fp.close()
    return cfg
Esempio n. 16
0
class Config(object):

    def __init__(self):
        self._parser = ConfigParser()
        self._parser._defaults = IncludeDict(self._parser)

        # Copy attributes from the parser to avoid one additional
        # function call on each access.
        for attr in ["has_section", "remove_section"]:
            setattr(self, attr, getattr(self._parser, attr))

    def read_configs(self, configs):
        for config in configs:
            match = re.match("(.*)/([^/]+)=(.*)", config)
            if not match:
                raise Exception, "Invalid config string: %s" % config

            (name, option, value) = match.groups()
            if not self._parser.has_section(name):
                self._parser.add_section(name)

            self._parser.set(name, option, value)

    def read_file(self, file, filename="<stream>"):
        logging.info("Reading configurations from: %s", filename)

        self._parser.readfp(file, filename)

    def read_filename(self, filename):
        if not posixpath.exists(filename):
            raise Exception, "No such configuration file: %s" % filename

        file = open(filename, "r")
        return self.read_file(file, filename)

    def get_defaults(self):
        attributes = self._parser.defaults()
        return ConfigDefaults(self, 'DEFAULT', attributes)

    def get_section(self, name):
        if self._parser.has_section(name):
            attributes = dict(self._parser.items(name))
            return ConfigSection(self, name, attributes)

        return None

    def get_section_names(self):
        return self._parser.sections()

    def add_section(self, name):
        self._parser.add_section(name)
        return self.get_section(name)
Esempio n. 17
0
def migrate_ipbx(basedir):
	cfg = ConfigParser()
	cfg.read(basedir + '/ipbx.ini')

	if not cfg.has_section('configfiles'):
		cfg.add_section('configfiles')
	cfg.set('configfiles', 'path', '/etc/asterisk/extensions_extra.d')

	if not cfg.has_section('logaccess'):
		cfg.add_section('logaccess')
	cfg.set('logaccess'  , 'file', '/var/log/pf-xivo-web-interface/xivo.log')

	with open(basedir + '/ipbx.ini', 'wb') as fp:
		cfg.write(fp)
Esempio n. 18
0
 def parse(self):
     # extract project
     self.extract()
     # parse
     self._log.debug('Reading project info file...')
     prj_file = os.path.join(self._tmpdir, 'project_info')
     if os.path.exists(prj_file):
         cfg = ConfigParser()
         cfg.read(prj_file)
         if cfg.has_section('project'):
             self.id = cfg.get('project', 'id')
             self.name = cfg.get('project', 'name')
             self.author = cfg.get('project', 'author')
             self.aws_cert = cfg.get('project', 'aws_cert')
             self.aws_key = cfg.get('project', 'aws_key')
             self.aws_id = cfg.get('project', 'aws_id')
             self.aws_s3_bucket = cfg.get('project', 'aws_s3_bucket')
             self.aws_s3_access_id = cfg.get('project', 'aws_s3_access_id')
             self.aws_s3_access_key = cfg.get('project', 'aws_s3_access_key')
             self.version = cfg.get('project', 'version')
             self.distro = cfg.get('project', 'distro')
             self.environment = cfg.get('project', 'environment')
             self.project_type = cfg.get('project', 'project_type')
             self.arch = cfg.get('project', 'arch')
             self.distro_version = cfg.get('project', 'distro_version')
             self.src_iso = cfg.get('project', 'src_iso')
             if cfg.has_option('project', 'base_packages_removed'):
                 base_packages_removed = cfg.get('project', 'base_packages_removed')
                 self.base_packages_removed = base_packages_removed.split(',')
             if cfg.get('project', 'disk_image_type') != '':
                 self.disk_image_type = cfg.get('project', 'disk_image_type')
             if cfg.get('project', 'disk_image_size') != '':
                 self.disk_image_size = cfg.get('project', 'disk_image_size')
             self.output_file = cfg.get('project', 'output_file')
             if cfg.get('project', 'online').lower() == 'true':
                 self.online = True
             else:
                 self.online = False
             if cfg.get('project', 'run_post_config').lower() == 'true':
                 self.run_post_config = True
             else:
                 self.run_post_config = False
         if cfg.has_section('job'):
             self.job_id = cfg.get('job', 'id')
             self.job_status_post_url = cfg.get('job', 'post_url')
         # load packages
         return True
     else:
         self._log.error('Corrupt project.  Unable to load project info file.')
         return False
Esempio n. 19
0
def clean(start_page, end_page):
    """ Batch cleans the pages in text/clean."""

    config = ConfigParser()
    config.read('book.cnf')
    try:
        clean_headers = config.getboolean('process', 'clean_headers')
    except NoOptionError:
        clean_headers = True
    try:
        join_lines = config.getboolean('process', 'join_lines')
    except NoOptionError:
        join_lines = True

    if clean_headers:
	print 'cleaning headers'
        remove_headers()
        if not config.has_section('process'):
            config.add_section('process')
        config.set('process', 'clean_headers', 'false')
        with open('book.cnf', 'wb') as f:
            config.write(f)
        lm =_loaded_aspell_line_manager(start_page, end_page)
        lm.quick_fix()
    elif join_lines:
	print 'joining lines'
        if not config.has_section('process'):
            config.add_section('process')
        config.set('process', 'join_lines', 'false')
        with open('book.cnf', 'wb') as f:
            config.write(f)
        lm =_loaded_file_line_manager(start_page, end_page)
        lm.join_lines()
    else:
        # if interrupted by keyboard, go ahead and write changes
        lang = get_lang()
#           spell_checker.FileConfiguredSpellChecker(lang, './dict.{}.pws'.format(lang)),
#           spell_checker.AspellSpellChecker(lang, './dict.{}.pws'.format(lang)),
        lm = line_manager.LineManager(
#           spell_checker.AspellSpellChecker(lang, './dict.{}.pws'.format(lang)),
            spell_checker.FileConfiguredSpellChecker(lang),
            start_page,
            end_page
            )
        lm.load('text/clean')
        try:
            lm.fix_lines()
        except KeyboardInterrupt:
            pass
    lm.write_pages('text/clean', False)
    def parse_image_build_config(self, config_file_name):

        # Logic taken from koji.cli.koji.handle_image_build.
        # Unable to re-use koji's code because "cli" is not
        # a package of koji and this logic is intermingled
        # with CLI specific instructions.

        args = []
        opts = {}

        config = ConfigParser()
        config.read(config_file_name)

        image_name = None

        section = 'image-build'
        for option in ('name', 'version', 'arches', 'target', 'install_tree'):
            value = config.get(section, option)
            if option == 'arches':
                value = [arch for arch in value.split(',') if arch]
            elif option == 'name':
                image_name = value
            args.append(value)
            config.remove_option(section, option)

        for option, value in config.items(section):
            if option in ('repo', 'format'):
                value = [v for v in value.split(',') if v]
            elif option in ('disk_size'):
                value = int(value)
            opts[option] = value

        section = 'ova-options'
        if config.has_section(section):
            ova = []
            for k, v in config.items(section):
                ova.append('{}={}'.format(k, v))
            opts['ova_option'] = ova

        section = 'factory-parameters'
        if config.has_section(section):
            factory = []
            for option, value in config.items(section):
                factory.append((option, value))
            opts['factory_parameter'] = factory

        # Set some defaults.
        opts.setdefault('disk_size', 10)

        return image_name, args, {'opts': opts}
Esempio n. 21
0
 def __init__(self):
     cfg = ConfigParser()
     try:
         cfg.read(globalcfgfile)
     except:
         pass
     if not cfg.has_section("userconfig"):
         self.loadlasttime = True
         self.openremote = True
         self.fontfamily = None
         self.fontsize = None
         self.__lastdir = home
         self.sengine_own = True
     if not cfg.has_section("searchext"):
         self.searchext = {"html": True, "htm": True, "js": False, "txt": False, "css": False}
     else:
         self.searchext = {}
         for a, b in cfg.items("searchext"):
             if b.lower() == "false":
                 self.searchext[a] = False
             else:
                 self.searchext[a] = True
     try:
         self.loadlasttime = cfg.getboolean("userconfig", "loadlasttime")
     except:
         self.lastlasttime = True
     try:
         self.sengine_own = cfg.getboolean("userconfig", "default_search_engine")
     except:
         self.sengine_own = True
     try:
         self.openremote = cfg.getboolean("userconfig", "openremote")
     except:
         self.openremote = True
     try:
         self.fontfamily = cfg.get("userconfig", "fontfamily").decode("utf-8")
         if self.fontfamily == "default":
             self.fontfamily = None
     except:
         self.fontfamily = None
     try:
         self.fontsize = cfg.getint("userconfig", "fontsize")
     except:
         self.fontsize = None
     try:
         self.__lastdir = cfg.get("userconfig", "lastdir")
     except:
         self.__lastdir = home
Esempio n. 22
0
  def readFrom(self, path, section):
    parser = ConfigParser()
    if not parser.read(path):
      raise CarbonConfigException("Failed to read config file %s" % path)

    if not parser.has_section(section):
      return

    for key, value in parser.items(section):
      key = key.upper()

      # Detect type from defaults dict
      if key in defaults:
        valueType = type(defaults[key])
      else:
        valueType = str

      if valueType is list:
        value = [v.strip() for v in value.split(',')]

      elif valueType is bool:
        value = parser.getboolean(section, key)

      else:
        # Attempt to figure out numeric types automatically
        try:
          value = int(value)
        except:
          try:
            value = float(value)
          except:
            pass

      self[key] = value
Esempio n. 23
0
def install_mercurial_hook():
    """
    Installs the mercurial precommit hook by adding a hook to the hgrc
    file in the .hg directory of the repository.
    """

    repo_dir = get_repo_dir()

    config_file = os.path.join(repo_dir, '.hg', 'hgrc')
    config_parser = ConfigParser()
    config_parser.read(config_file)

    precommit_abs_file = os.path.join(repo_dir, 'scripts',
            'codestyleprecommit.py')

    section = 'hooks'
    key = 'pretxncommit.precommit'
    value = 'python:%s:mercurial_hook' % precommit_abs_file

    if not config_parser.has_section(section):
        config_parser.add_section(section)

    config_parser.set(section, key, value)

    with open(config_file, 'w') as config:
        config_parser.write(config)
Esempio n. 24
0
class UserConfig:

    def __init__(self, filename=default_user_config_file):
        self.parser = ConfigParser()
        self.parser.read(filename)
        self.filename = filename
        if not isfile(self.filename):
            self.parser.add_section('diaspora')
            self.set_activated(False)
            self.__save()
        else:
            self.parser.read(self.filename)

        if not self.parser.has_section('diaspora'):
            self.parser.add_section('diaspora')

    def is_installed(self):
        return self.parser.getboolean('diaspora', 'activated')

    def set_activated(self, value):
        self.parser.set('diaspora', 'activated', str(value))
        self.__save()

    def __save(self):
        with open(self.filename, 'wb') as f:
            self.parser.write(f)
    def initConfig(self):
        kate.debug("initConfig()")
        config_path = kate.pate.pluginDirectories[1] + "/%s/%s.conf" % (__name__, __name__)
        config_file = QFileInfo(config_path)

        if not config_file.exists():
            open(config_path, "w").close()

        config = ConfigParser()
        config.read(config_path)

        # init the DEFAULT options if they don't exist
        # the DEFAULT section is special and doesn't need to be created: if not config.has_section('DEFAULT'): config.add_section('DEFAULT')
        if not config.has_option("DEFAULT", "ignore"):
            config.set("DEFAULT", "ignore", "")
        if not config.has_option("DEFAULT", "filter"):
            config.set("DEFAULT", "filter", "*")
        if not config.has_option("DEFAULT", "finder_size"):
            config.set("DEFAULT", "finder_size", "400x450")
        if not config.has_option("DEFAULT", "config_size"):
            config.set("DEFAULT", "config_size", "300x350")
        if not config.has_option("DEFAULT", "search_type"):
            config.set("DEFAULT", "search_type", "word")

        # create the general section if it doesn't exist
        if not config.has_section("general"):
            config.add_section("general")

        # flush the config file
        config.write(open(config_path, "w"))

        # save the config object and config path as instance vars for use later
        self.config = config
        self.config_path = config_path
Esempio n. 26
0
class Config(object):
    def __new__(type, *args, **kwargs):
        if not '_the_instance' in type.__dict__:
            type._the_instance = object.__new__(type)
        return type._the_instance
    
    def __init__(self, filename = None):
        if filename != None:
            self.filename = filename
            self.config = ConfigParser()
            self.config.read(self.filename)
    
    def get_section(self,name):
        if self.config.has_section(name):
            return _Section(name, self.config.items(name), self)
        else:
            return _Section(name, [], self)
    
    def __getattr__(self, attr):
        if attr == 'irc':
            return self.get_section('IRC')
        elif attr == 'ldap':
            return self.get_section('LDAP')
        elif attr == 'rpc':
            return self.get_section('RPC')
        elif attr == 'bot':
            return self.get_section('Bot')
        elif attr == 'smtp':
            return self.get_section('SMTP')
        elif attr == 'db':
            return self.get_section('Database')
        elif attr == 'identica':
            return self.get_section('Identi.ca')
        else:
            raise AttributeError('No section \'%s\' in Config.' % attr)
Esempio n. 27
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")
Esempio n. 28
0
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 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'])
Esempio n. 30
0
def getVersionedFolderInfo(dirPath):
	"""
	returns a list containing the following information about the asset in dirPath:
	[0] last person to check it out, if locked
	[1] last person to check it in
	[2] time it was last checked in
	[3] latest comment on checkin
	[4] if it is isInstalled
	[5] filepath to install directory
	"""
	if not isVersionedFolder(dirPath):
		raise Exception("Not a versioned folder")
	
	nodeInfo = []
	cp = ConfigParser()
	cp.read(os.path.join(dirPath, ".nodeInfo"))
	if cp.getboolean("Versioning", "locked"):
		nodeInfo.append(cp.get("Versioning", "lastcheckoutuser"))
	else:
		nodeInfo.append("")
	nodeInfo.append(cp.get("Versioning", "lastcheckinuser"))
	nodeInfo.append(cp.get("Versioning", "lastcheckintime"))
	versionNum = int(cp.get("Versioning", "latestversion"))
	latestVersion = "v"+("%03d" % versionNum) 
	if cp.has_section("Comments"):
		nodeInfo.append(cp.get("Comments", latestVersion))
	else:
		nodeInfo.append('')
	if isInstalled(dirPath):
		nodeInfo.append("Yes")
		nodeInfo.append(glob.glob(os.path.join(dirPath, 'stable', '*stable*'))[0])
	else:
		nodeInfo.append("No")
		nodeInfo.append("")
	return nodeInfo
Esempio n. 31
0
def make_plots(simfolder, plot_nrs=[]):
    """ generate plots as specified in the simulation conf

        :param string simfolder: relative path to simfolder
        :param list plot_nrs: a list with plot indices. If empty, plot all
    """
    from sim import utils
    from analysis import plotter

    simfolder = simfolder.strip('/')

    #if osp.exists("%s/plots" % simfolder):
    #   rmtree('%s/plots' % simfolder)
    if not osp.exists("%s/plots" % simfolder):
        os.mkdir('%s/plots' % simfolder)

    # tell about what we'll do if we have at least one plot
    relevant_confs = utils.get_relevant_confs(simfolder)
    for c in relevant_confs:
        if c.has_section("figure1"):
            print
            print '*' * 80
            print "[Nicessa] creating plots ..."
            print '*' * 80
            print
            break
    else:
        print "[Nicessa] No plots specified"

    # Describe all options first.
    # These might be set in plot-settings (in each simulation config)
    # and also per-figure
    general_options = {
        'use-colors': bool,
        'use-tex': bool,
        'line-width': int,
        'font-size': int,
        'infobox-pos': str,
        'use-y-errorbars': bool,
        'errorbar-every': int
    }
    figure_specific_options = {
        'name': str,
        'xcol': int,
        'x-range': str,
        'y-range': str,
        'x-label': str,
        'y-label': str,
        'custom-script': str
    }
    figure_specific_options.update(general_options)

    def get_opt_val(conf, d, section, option, t):
        if conf.has_option(section, option):
            val = c.get(section, option).strip()
            if t is int:
                val = c.getint(section, option)
            if t is bool:
                val = c.getboolean(section, option)
            if t is float:
                val = c.getfloat(section, option)
            # config-options with '-' are nice, but not good parameter names
            d[option.replace('-', '_')] = val

    general_settings = {}
    c = ConfigParser()
    c.read('%s/nicessa.conf' % (simfolder))
    delim = utils.get_delimiter(c)
    for o, t in general_options.iteritems():
        get_opt_val(c, general_settings, 'plot-settings', o, t)
    general_params = []
    if c.has_option('plot-settings', 'params'):
        general_params = c.get('plot-settings', 'params').split(',')

    for c in relevant_confs:
        i = 1
        settings = general_settings.copy()
        # overwrite with plot-settings for this subsimulation
        for o, t in general_options.iteritems():
            get_opt_val(c, settings, 'plot-settings', o, t)
        if c.has_option('plot-settings', 'params'):
            general_params.extend(c.get('plot-settings', 'params').split(','))

        while c.has_section("figure%i" % i):
            if i in plot_nrs or len(plot_nrs) == 0:
                fig_settings = settings.copy()
                for o, t in figure_specific_options.iteritems():
                    get_opt_val(c, fig_settings, 'figure%i' % i, o, t)

                plot_confs = []
                j = 1
                while c.has_option("figure%i" % i, "plot%i" % j):
                    # make plot settings from conf string
                    d = utils.decode_search_from_confstr(
                        c.get('figure%i' % i, 'plot%i' % j),
                        sim=c.get('meta', 'name'))
                    # then add general param settings to each plot, if
                    # not explicitly in there
                    for param in general_params:
                        if ":" in param:
                            param = param.split(':')
                            key = param[0].strip()
                            if not key in d.keys():
                                d[key] = param[1].strip()
                    # making sure all necessary plot attributes are there
                    if ('_name' in d.keys() and '_ycol' in d.keys()
                            and '_type' in d.keys()):
                        plot_confs.append(d)
                    else:
                        print '''
[NICESSA] Warning: Incomplete graph specification in Experiment %s
- for plot %i in figure %i. \n
Specify at least _name and _ycol.''' % (c.get('meta', 'name'), j, i)
                    j += 1
                plotter.plot(filepath='%s/data' % simfolder,
                             delim=delim,
                             outfile_name='%s/plots/%s.pdf' \
                                % (simfolder, fig_settings['name']),\
                             plots=plot_confs,\
                             **fig_settings)
            i += 1
Esempio n. 32
0
    parser.add_option(
        "-w",
        "--writepls",
        help="A file to write the playlist into. Can be the same as -p.")
    parser.add_option("-q",
                      "--enqueue",
                      help="Enqueue the tracks named on the command line.",
                      action="store_true",
                      default=False)
    options, posargs = parser.parse_args()

    conf = ConfigParser()
    conf.read(os.path.join(os.environ["HOME"], ".failplay",
                           "failblaster.conf"))

    if conf.has_section("environment"):
        for key in conf.options("environment"):
            os.environ[key.upper()] = conf.get("environment", key)

    def getconf(value, default=None):
        if getattr(options, value) is not None:
            return getattr(options, value)
        if conf.has_option("options", value):
            return conf.get("options", value)
        return default

    p = Playlist()

    playlistfile = getconf("playlist")
    if playlistfile:
        print "Loading playlist from", playlistfile
Esempio n. 33
0
class Config(object):
    """
        Reading of config file attributes. Any instance holds state
        information about Azure account, region, storage and container
        references
    """
    PLATFORM = sys.platform[:3]

    def __init__(self,
                 account_name=None,
                 region_name=None,
                 storage_account_name=None,
                 storage_container_name=None,
                 filename=None,
                 platform=PLATFORM):
        from ..logger import log

        self.storage_container_name = storage_container_name
        self.storage_account_name = storage_account_name

        self.config_file = self.__lookup_config_file(platform, account_name,
                                                     filename)

        self.config = ConfigParser()
        try:
            log.debug('Using configuration from %s', self.config_file)
            self.config.read(self.config_file)
        except Exception as e:
            raise AzureConfigParseError(
                'Could not parse config file: "%s"\n%s' %
                (self.config_file, e.message))

        if not self.config.defaults():
            raise AzureAccountDefaultSectionNotFound(
                'Empty or undefined default section in configuration file %s' %
                self.config_file)

        self.account_name = self.__import_default_account()
        self.selected_region_name = region_name
        self.region_name = None

    def get_storage_account_name(self):
        storage_account_name = self.storage_account_name
        if not storage_account_name:
            storage_account_name = self.__get_region_option(
                'default_storage_account')
        return storage_account_name

    def get_storage_container_name(self):
        storage_container_name = self.storage_container_name
        if not storage_container_name:
            storage_container_name = self.__get_region_option(
                'default_storage_container')
        return storage_container_name

    def get_subscription_id(self):
        return self.__get_account_option('subscription_id')

    def get_publishsettings_file_name(self):
        return self.__get_account_option('publishsettings')

    def get_management_url(self):
        return self.__get_account_option('management_url')

    def get_management_pem_filename(self):
        return self.__get_account_option('management_pem_file')

    def get_region_name(self):
        if not self.region_name:
            try:
                self.region_name = self.__import_default_region(
                    self.selected_region_name).replace('region:', '')
            except AzureConfigSectionNotFound:
                self.region_name = self.selected_region_name
        return self.region_name

    def get_account_name(self):
        return self.account_name.replace('account:', '')

    @classmethod
    def get_config_file(self, account_name=None, filename=None, platform=None):
        paths = ConfigFilePath(account_name, platform)
        if filename:
            return filename
        elif account_name:
            return paths.default_new_account_config()
        else:
            return paths.default_config()

    @classmethod
    def get_config_file_list(self):
        paths = ConfigFilePath()
        return [paths.default_config()] + paths.account_config()

    @classmethod
    def set_default_config_file(self, account_name, platform=None):
        paths = ConfigFilePath(account_name, platform)
        account_config_file = paths.default_new_account_config()
        if not os.path.exists(account_config_file):
            raise AzureConfigAccountFileNotFound(
                'Account config file %s not found' % account_config_file)

        default_config_file = paths.default_config()
        if not default_config_file:
            default_config_file = paths.default_new_config()

        default_exists = os.path.exists(default_config_file)
        default_islink = os.path.islink(default_config_file)

        if default_exists and not default_islink:
            message = dedent('''
                Can not link %s as default account.

                A default account configuration file from a former
                azurectl version was found. Consider one of the following
                options to handle the config file: %s

                1. Delete the configuration file if no longer needed
                2. Move the configuration file with context information to
                   ~/.config/azurectl/config.<context>
            ''').strip()
            raise AzureConfigDefaultLinkError(
                message % (account_config_file, default_config_file))

        if default_exists:
            os.remove(default_config_file)

        os.symlink(account_config_file, default_config_file)

    def __check_for_section(self, section):
        if section and not self.config.has_section(section):
            raise AzureConfigSectionNotFound(
                'Section %s not found in configuration file %s' %
                (section, self.config_file))

    def __get_account_option(self, option):
        try:
            result = self.config.get(self.account_name, option)
        except Exception:
            raise AzureConfigVariableNotFound(
                '%s not defined for account %s in configuration file %s' %
                (option, self.account_name, self.config_file))
        return result

    def __get_region_option(self, option):
        try:
            if not self.region_name:
                self.get_region_name()
            result = self.config.get('region:' + self.region_name, option)
        except Exception as e:
            message = '%s not found: %s' % (option, format(e))
            raise AzureConfigVariableNotFound(message)
        return result

    def __lookup_config_file(self, platform, account_name, filename):
        paths = ConfigFilePath(account_name, platform)
        if filename:
            # lookup a custom config file
            if not os.path.isfile(filename):
                raise AzureAccountLoadFailed('Could not find config file: %s' %
                                             filename)
        elif account_name:
            # lookup an account config file
            filename = paths.default_new_account_config()
            if not os.path.isfile(filename):
                raise AzureAccountLoadFailed(
                    'Could not find account config file: %s %s: %s' %
                    (paths.account_config_file, 'in home directory',
                     paths.home_path))
        else:
            # lookup default config file
            filename = paths.default_config()
            if not filename:
                raise AzureAccountLoadFailed(
                    'could not find default configuration file %s %s: %s' %
                    (' or '.join(paths.config_files), 'in home directory',
                     paths.home_path))
        return filename

    def __import_default_region(self, region_name):
        defaults = self.config.defaults()
        if region_name:
            region_name = 'region:' + region_name
        else:
            try:
                region_name = defaults['default_region']
            except Exception:
                raise AzureConfigRegionNotFound(
                    'No region referenced in configuration file %s' %
                    self.config_file)
        self.__check_for_section(region_name)
        return region_name

    def __import_default_account(self):
        defaults = self.config.defaults()
        try:
            account_name = defaults['default_account']
        except Exception:
            raise AzureConfigAccountNotFound(
                'No account referenced in configuration file %s' %
                self.config_file)
        self.__check_for_section(account_name)
        return account_name
Esempio n. 34
0
    VMINFO_JSON = False
    OIDC_CLIENT_ID = None
    OIDC_CLIENT_SECRET = None
    OIDC_SCOPES = []
    VM_NUM_USE_CTXT_DIST = 30
    DELAY_BETWEEN_VM_RETRIES = 5


config = ConfigParser()
config.read([
    Config.IM_PATH + '/../im.cfg', Config.IM_PATH + '/../etc/im.cfg',
    '/etc/im/im.cfg'
])

section_name = "im"
if config.has_section(section_name):
    parse_options(config, section_name, Config)

# Get some vars from environment variables to make easy docker container configuration
if 'IM_DATA_DB' in os.environ:
    Config.DATA_DB = os.environ['IM_DATA_DB']

if 'IM_SINGLE_SITE_ONE_HOST' in os.environ:
    Config.SINGLE_SITE = True
    Config.SINGLE_SITE_TYPE = 'OpenNebula'
    Config.SINGLE_SITE_AUTH_HOST = 'http://%s:2633' % os.environ[
        'IM_SINGLE_SITE_ONE_HOST']
    Config.SINGLE_SITE_IMAGE_URL_PREFIX = 'one://%s/' % os.environ[
        'IM_SINGLE_SITE_ONE_HOST']

Esempio n. 35
0
    def ReadInputFile(self, in_file=''):
        if in_file != '':
            if os.path.isfile(in_file):
                pars = ConfigParser()
                pars.read(in_file)
                print 'Loading job description from file:', in_file

                if pars.has_section('RUN'):
                    if pars.has_option('RUN', 'StripTelescopeAnalysis_path'):
                        self.StripTelescopeAnalysis_path = pars.get(
                            'RUN', 'StripTelescopeAnalysis_path')
                    if pars.has_option('RUN', 'run'):
                        self.run = pars.getint('RUN', 'run')
                    else:
                        ExitMessage('Must specify run under [RUN]. Exiting...')
                    if pars.has_option('RUN', 'events'):
                        self.total_events = pars.getint('RUN', 'events')
                    else:
                        ExitMessage(
                            'Must specify events under [RUN]. Exiting...')
                    if pars.has_option('RUN', 'dia_input'):
                        self.dia_input = pars.getint('RUN', 'dia_input')
                    if pars.has_option('RUN', 'dia_saturation'):
                        self.dia_saturation = pars.getint(
                            'RUN', 'dia_saturation')
                    if pars.has_option('RUN', 'max_transparent_cluster_size'):
                        self.max_transparent_cluster_size = pars.getint(
                            'RUN', 'max_transparent_cluster_size')
                    if pars.has_option('RUN', 'datadir'):
                        self.data_dir = pars.get('RUN', 'datadir')
                    else:
                        ExitMessage(
                            'Must specify datadir under [RUN]. Exiting...')
                    if pars.has_option('RUN', 'outputdir'):
                        self.out_dir = pars.get('RUN', 'outputdir')
                    else:
                        ExitMessage(
                            'Must specify outputdir under [RUN]. Exiting...')
                    if pars.has_option('RUN', 'settingsdir'):
                        self.settings_dir = pars.get('RUN', 'settingsdir')
                    else:
                        ExitMessage(
                            'Must specify settingsdir under [RUN]. Exiting...')
                    if pars.has_option('RUN', 'runlistsdir'):
                        self.run_lists_dir = pars.get('RUN', 'runlistsdir')
                    else:
                        ExitMessage(
                            'Must specify runlistsdir under [RUN]. Exiting...')
                    if pars.has_option('RUN', 'scratch_path'):
                        self.scratch_path = pars.get('RUN', 'scratch_path')
                    if pars.has_option('RUN', 'subdir'):
                        self.subdir = pars.get('RUN', 'subdir')
                    if pars.has_option('RUN', 'do_even'):
                        self.do_even = pars.getboolean('RUN', 'do_even')
                    if pars.has_option('RUN', 'do_odd'):
                        self.do_odd = pars.getboolean('RUN', 'do_odd')
                    if pars.has_option('RUN', 'do_chs'):
                        self.do_chs = pars.getboolean('RUN', 'do_chs')
                    if pars.has_option('RUN', 'batch'):
                        self.batch = pars.getboolean('RUN', 'batch')
                    if pars.has_option('RUN', 'symlinks'):
                        self.symlinks = pars.getboolean('RUN', 'symlinks')

                if pars.has_section('ANALYSIS'):
                    if pars.has_option('ANALYSIS', 'first_event'):
                        self.first_event = pars.getint('ANALYSIS',
                                                       'first_event')
                    if pars.has_option('ANALYSIS', 'num_events'):
                        self.num_events = pars.getint('ANALYSIS', 'num_events')
                    if pars.has_option('ANALYSIS', 'do_pedestal'):
                        self.do_pedestal = pars.getboolean(
                            'ANALYSIS', 'do_pedestal')
                    if pars.has_option('ANALYSIS', 'do_cluster'):
                        self.do_cluster = pars.getboolean(
                            'ANALYSIS', 'do_cluster')
                    if pars.has_option('ANALYSIS', 'do_selection'):
                        self.do_selection = pars.getboolean(
                            'ANALYSIS', 'do_selection')
                    if pars.has_option('ANALYSIS', 'do_alignment'):
                        self.do_alignment = pars.getboolean(
                            'ANALYSIS', 'do_alignment')
                    if pars.has_option('ANALYSIS', 'do_transparent'):
                        self.do_transparent = pars.getboolean(
                            'ANALYSIS', 'do_transparent')
                    if pars.has_option('ANALYSIS', 'do_3d'):
                        self.do_3d = pars.getboolean('ANALYSIS', 'do_3d')

                self.num_events = self.total_events if self.num_events == 0 else self.num_events
                return
        ExitMessage(
            'Input file "{i}" does not exist. Must input a valid file. Exiting'
            .format(i=in_file))
Esempio n. 36
0
            exit(-1)

        # Create directory
        suffix = "_" + str(int(time.time()))
        cov_dir = tempfile.mkdtemp(suffix, "m2_coverage_")

        # Create configuration file
        coveragerc = os.path.join(cov_dir, ".coveragerc")
        coverage = os.path.join(cov_dir, ".coverage")

        from ConfigParser import ConfigParser
        from os.path import expanduser

        config = ConfigParser()
        config.read(['/etc/coveragerc', expanduser('~/.coveragerc')])
        if not config.has_section('run'):
            config.add_section('run')
        config.set('run', 'data_file', coverage)
        config.write(open(coveragerc, 'w'))

        # Add arguments to tests command line
        testset.add_additionnal_args(["-m", "coverage", "run", "--rcfile",
                                      coveragerc, "-a"])


        # Inform the user
        d = {"blue": cosmetics.colors['blue'],
             "end": cosmetics.colors['end'],
             "cov_dir": cov_dir}
        print "[%(blue)sCoverage%(end)s] Report will be written in %(cov_dir)s" % d
Esempio n. 37
0
class Config(object):
    ''' This class represents the barman configuration.

    Default configuration files are /etc/barman.conf,
    /etc/barman/barman.conf
    and ~/.barman.conf for a per-user configuration
    '''
    CONFIG_FILES = [
        '~/.barman.conf', '/etc/barman.conf', '/etc/barman/barman.conf'
    ]

    def __init__(self, filename=None):
        self._config = ConfigParser()
        if filename:
            if hasattr(filename, 'read'):
                self._config.readfp(filename)
            else:
                self._config.read(os.path.expanduser(filename))
        else:
            for path in self.CONFIG_FILES:
                full_path = os.path.expanduser(path)
                if os.path.exists(
                        full_path) and full_path in self._config.read(
                            full_path):
                    filename = full_path
                    break
        self.config_file = filename
        self._servers = None
        self._parse_global_config()
        self._load_configuration_files_directory()

    def get(self, section, option, defaults={}):
        '''Method to get the value from a given section from
        Barman configuration
        '''
        if not self._config.has_section(section):
            return None
        try:
            value = self._config.get(section, option, raw=False, vars=defaults)
            if value == 'None':
                value = None
            if value != None:
                value = self._QUOTERE.sub(lambda m: m.group(2), value)
            return value
        except NoOptionError:
            return None

    _QUOTERE = re.compile(r"""^(["'])(.*)\1$""")

    def _parse_global_config(self):
        '''This method parses the configuration file'''
        self.barman_home = self.get('barman', 'barman_home')
        self.user = self.get('barman', 'barman_user') or 'barman'
        self._enforce_user()
        log_file = self.get('barman', 'log_file')
        handler = logging.StreamHandler()
        warn = None
        if log_file:
            log_file = os.path.abspath(log_file)
            logdir = os.path.dirname(log_file)
            try:
                if not os.path.isdir(logdir):
                    os.makedirs(logdir)
                handler = logging.handlers.WatchedFileHandler(log_file)
            except:
                # fallback to standard error
                warn = "Failed opening the requested log file. Using standard error instead."
        fmt = self.get(
            'barman',
            'log_format') or "%(asctime)s %(name)s %(levelname)s: %(message)s"
        formatter = logging.Formatter(fmt)
        handler.setFormatter(formatter)
        logging.root.addHandler(handler)
        if warn:
            _logger.warn(
                warn
            )  # this will be always displayed because the default level is WARNING
        level = self.get('barman', 'log_level') or 'INFO'
        if level.isdigit():
            level_int = int(level)
        else:
            level_int = logging.getLevelName(level)
        if type(level_int) == int:
            logging.root.setLevel(level_int)
        else:
            _logger.warn('unknown log_level in config file: %s', level)
        self._global_config = set(self._config.items('barman'))

    def _is_global_config_changed(self):
        return self._global_config != set(self._config.items('barman'))

    def _enforce_user(self):
        '''Set the correct user'''
        try:
            pw = pwd.getpwnam(self.user)
        except:
            msg = "ERROR: the configured user %r does not exists" % self.user
            raise SystemExit(msg)
        if pw.pw_uid == os.getuid():
            return
        try:
            os.setgroups(
                [e.gr_gid for e in grp.getgrall() if pw.pw_name in e.gr_mem] +
                [pw.pw_gid])
            os.setgid(pw.pw_gid)
            os.setuid(pw.pw_uid)
            os.setegid(pw.pw_gid)
            os.seteuid(pw.pw_uid)
        except:
            msg = "ERROR: please run barman as %r user" % self.user
            raise SystemExit(msg)
        os.environ['HOME'] = pw.pw_dir

    def _load_configuration_files_directory(self):
        '''Read the "configuration_files_directory" option and loads all the
        configuration files with the .conf suffix that lie in that folder
        '''

        configuration_files_directory = self.get(
            'barman', 'configuration_files_directory')

        if not configuration_files_directory:
            return

        if not os.path.isdir(
                os.path.expanduser(configuration_files_directory)):
            _logger.warn(
                'Ignoring the "configuration_files_directory" option as "%s" is not a directory',
                configuration_files_directory)
            return

        for cfile in sorted(
                iglob(
                    os.path.join(
                        os.path.expanduser(configuration_files_directory),
                        '*.conf'))):
            filename = os.path.basename(cfile)
            if os.path.isfile(cfile):
                # Load a file
                _logger.info('Including configuration file: %s', filename)
                self._config.read(cfile)
                if self._is_global_config_changed():
                    msg = "the configuration file %s contains a not empty [barman] section" % filename
                    _logger.fatal(msg)
                    raise SystemExit("FATAL: %s" % msg)
            else:
                # Add an info that a file has been discarded
                _logger.warn('Discarding configuration file: %s (not a file)',
                             filename)

    def _populate_servers(self):
        '''Populate server list from configuration file'''
        if self._servers != None:
            return
        self._servers = {}
        for section in self._config.sections():
            if section == 'barman':
                continue  # skip global settings
            if section in FORBIDDEN_SERVER_NAMES:
                msg = "the reserved word '%s' is not allowed as server name. Please rename it." % section
                _logger.fatal(msg)
                raise SystemExit("FATAL: %s" % msg)
            self._servers[section] = Server(self, section)

    def server_names(self):
        '''This method returns a list of server names'''
        self._populate_servers()
        return self._servers.keys()

    def servers(self):
        '''This method returns a list of server parameters'''
        self._populate_servers()
        return self._servers.values()

    def get_server(self, name):
        '''Get the server scpecifying its name'''
        self._populate_servers()
        return self._servers.get(name, None)
Esempio n. 38
0
import os
import socket
import smtplib
import json
from ConfigParser import ConfigParser

# set default timeout to 2 seconds
socket.setdefaulttimeout(2)

hello_world_config = '/usr/local/etc/helloworld/helloworld.conf'

result = {}
if os.path.exists(hello_world_config):
    cnf = ConfigParser()
    cnf.read(hello_world_config)
    if cnf.has_section('general'):
        try:
            smtpObj = smtplib.SMTP(cnf.get('general', 'SMTPHost'))
            msg_header = "From: " + cnf.get('general', 'FromEmail') + "\n" + \
                         "To: " + cnf.get('general', 'ToEmail') + "\n" + \
                         "Subject: " + cnf.get('general', 'Subject') + "\n" + \
                         "Test message!"

            smtpObj.sendmail(cnf.get('general', 'FromEmail'),
                             [cnf.get('general', 'ToEmail')], msg_header)
            smtpObj.quit()
            result['message'] = 'test ok!'
        except smtplib.SMTPException as error:
            # unable to send mail
            result['message'] = '%s' % error
        except socket.error as error:
Esempio n. 39
0
    def _load(self):
        self.gconf = {}
        self.template_conf = []
        self.gconf_typecast = {}
        self.non_configurable_configs = []
        self.session_conf_items = []
        self.default_values = {}

        conf = ConfigParser()
        # Default Template config file
        with open(self.default_conf_file) as f:
            conf.readfp(f)

        # Custom Config file
        if self.custom_conf_file is not None:
            with open(self.custom_conf_file) as f:
                conf.readfp(f)

        # Get version from default conf file
        self.version = conf.get("__meta__", "version")

        # Populate default values
        for sect in conf.sections():
            if sect in ["__meta__", "vars"]:
                continue

            # Collect list of available options with help details
            self.gconfdata[sect] = {}
            for k, v in conf.items(sect):
                self.gconfdata[sect][k] = v.strip()

            # Collect the Type cast information
            if conf.has_option(sect, "type"):
                self.gconf_typecast[sect] = conf.get(sect, "type")

            # Prepare list of configurable conf
            if conf.has_option(sect, "configurable"):
                if conf.get(sect, "configurable").lower() == "false":
                    self.non_configurable_configs.append(sect)

            # if it is a template conf value which needs to be substituted
            if conf.has_option(sect, "template"):
                if conf.get(sect, "template").lower().strip() == "true":
                    self.template_conf.append(sect)

            # Set default values
            if conf.has_option(sect, "value"):
                self.gconf[sect] = conf.get(sect, "value").strip()

        # Load the custom conf elements and overwrite
        if conf.has_section("vars"):
            for k, v in conf.items("vars"):
                self.session_conf_items.append(k)
                self.default_values[k] = self.gconf.get(k, "")
                self.gconf[k] = v.strip()

        # Overwrite the Slave configurations which are sent as
        # arguments to gsyncd slave
        if self.override_from_args:
            for k, v in self.args.items():
                k = k.replace("_", "-")
                if k.startswith("slave-") and k in self.gconf:
                    self.gconf[k] = v

        self._tmpl_substitute()
        self._do_typecast()
Esempio n. 40
0
    def config_load(self):

        config_file = self.install_dir + '/' + self.game_name + '/config.ini'
        config_parser = ConfigParser()
        config_parser.read(config_file)

        if not config_parser.has_section('Settings'):
            config_parser.add_section('Settings')

        if not config_parser.has_option('Settings', 'wine'):
            self.wine = 'global'
            config_parser.set('Settings', 'wine', str(self.wine))
        else:
            self.wine = config_parser.get('Settings', 'wine')

        if not config_parser.has_option('Settings', 'wine_path'):
            self.wine_path = global_wine_path
            config_parser.set('Settings', 'wine_path', str(self.wine_path))
        else:
            self.wine_path = config_parser.get('Settings', 'wine_path')

        if not config_parser.has_option('Settings', 'wine_version'):
            self.wine_version = global_wine_version
            config_parser.set('Settings', 'wine_version', str(self.wine_version))
        else:
            self.wine_version = config_parser.get('Settings', 'wine_version')

        if not config_parser.has_option('Settings', 'monitor'):
            self.monitor = global_monitor
            config_parser.set('Settings', 'monitor', str(self.monitor))
        else:
            self.monitor = config_parser.getint('Settings', 'monitor')

        if not config_parser.has_option('Settings', 'launcher'):
            self.launcher = True
            config_parser.set('Settings', 'launcher', str(self.launcher))
        else:
            self.launcher = config_parser.getboolean('Settings', 'launcher')

        if not config_parser.has_option('Settings', 'show_banner'):
            self.show_banner = True
            config_parser.set('Settings', 'show_banner', str(self.show_banner))
        else:
            self.show_banner = config_parser.getboolean('Settings', 'show_banner')

        if not config_parser.has_option('Settings', 'win_ver'):
            self.win_ver = 0
            config_parser.set('Settings', 'win_ver', str(self.win_ver))
        else:
            self.win_ver = config_parser.getint('Settings', 'win_ver')

        if not config_parser.has_option('Settings', 'virtual_desktop'):
            self.virtual_desktop = False
            config_parser.set('Settings', 'virtual_desktop', str(self.virtual_desktop))
        else:
            self.virtual_desktop = config_parser.getboolean('Settings', 'virtual_desktop')

        if not config_parser.has_option('Settings', 'virtual_desktop_width'):
            self.virtual_desktop_width = ''
            config_parser.set('Settings', 'virtual_desktop_width', str(self.virtual_desktop_width))
        else:
            self.virtual_desktop_width = config_parser.get('Settings', 'virtual_desktop_width')

        if not config_parser.has_option('Settings', 'virtual_desktop_height'):
            self.virtual_desktop_height = ''
            config_parser.set('Settings', 'virtual_desktop_height', str(self.virtual_desktop_height))
        else:
            self.virtual_desktop_height = config_parser.get('Settings', 'virtual_desktop_height')

        if not config_parser.has_option('Settings', 'mouse_capture'):
            self.mouse_capture = False
            config_parser.set('Settings', 'mouse_capture', str(self.mouse_capture))
        else:
            self.mouse_capture = config_parser.getboolean('Settings', 'mouse_capture')

        if not config_parser.has_option('Settings', 'own_prefix'):
            self.own_prefix = False
            config_parser.set('Settings', 'own_prefix', str(self.own_prefix))
        else:
            self.own_prefix = config_parser.getboolean('Settings', 'own_prefix')

        if not config_parser.has_option('Settings', 'winearch'):
            self.winearch = 'win32'
            config_parser.set('Settings', 'winearch', str(self.winearch))
        else:
            self.winearch = config_parser.get('Settings', 'winearch')

        if not config_parser.has_option('Settings', 'command_before'):
            self.command_before = ''
            config_parser.set('Settings', 'command_before', str(self.command_before))
        else:
            self.command_before = config_parser.get('Settings', 'command_before')

        if not config_parser.has_option('Settings', 'command_after'):
            self.command_after = ''
            config_parser.set('Settings', 'command_after', str(self.command_after))
        else:
            self.command_after = config_parser.get('Settings', 'command_after')

        new_config_file = open(config_file, 'w')
        config_parser.write(new_config_file)
        new_config_file.close()
Esempio n. 41
0
                                 ["bin=", "file=", "help"])
    op = ""
    filename = ""
    bindir = ""
    for (o, a) in opts:
        if o in ("-h", "--help"):
            usage()
            sys.exit(2)
        if o in ("-f", "--file"):
            filename = a
        elif o in ("-b", "--bin"):
            bindir = a

    if not os.path.exists(filename):
        print "%s : config file doesn't exist\n" % filename
        sys.exit(-1)

    if not os.path.exists(bindir):
        print "%s : bindir doesn't exist\n" % bindir
        sys.exit(-1)

    config = ConfigParser()
    config.readfp(open(filename, 'r'))
    if not config.has_section('metaserver'):
        raise config.NoSectionError, "No metaserver section"

    node = config.get('metaserver', 'node')
    port = config.getint('metaserver', 'baseport')
    cmd = "%s/tools/kfsshell -s %s -p %d" % (bindir, node, port)
    os.system(cmd)
Esempio n. 42
0
        txtOutPaths.append(application.getTxtOutPath())

    if generateTSV:
        from PyPop.Meta import Meta

        print "Generating TSV (.dat) files..."
        Meta(popmetabinpath=pypopbinpath,
             datapath=datapath,
             metaXSLTDirectory=None,
             dump_meta=0,
             R_output=1,
             PHYLIP_output=0,
             ihwg_output=1,
             batchsize=len(xmlOutPaths),
             files=xmlOutPaths)

    if interactiveFlag:

        print "PyPop run complete!"
        print "XML output(s) can be found in: ", xmlOutPaths
        print "Plain text output(s) can be found in: ", txtOutPaths

        # update .pypoprc file

        if pypoprc.has_section('Files') != 1:
            pypoprc.add_section('Files')

        pypoprc.set('Files', 'config', os.path.abspath(configFilename))
        pypoprc.set('Files', 'pop', os.path.abspath(fileNames[0]))
        pypoprc.write(open(pypoprcFilename, 'w'))
Esempio n. 43
0
File: Song.py Progetto: twcb/FoF
class SongInfo(object):
    def __init__(self, infoFileName):
        self.songName = os.path.basename(os.path.dirname(infoFileName))
        self.fileName = infoFileName
        self.info = ConfigParser()
        self._difficulties = None

        try:
            self.info.read(infoFileName)
        except:
            pass

        # Read highscores and verify their hashes.
        # There ain't no security like security throught obscurity :)
        self.highScores = {}

        scores = self._get("scores", str, "")
        if scores:
            scores = Cerealizer.loads(binascii.unhexlify(scores))
            for difficulty in scores.keys():
                try:
                    difficulty = difficulties[difficulty]
                except KeyError:
                    continue
                for score, stars, name, hash in scores[difficulty.id]:
                    if self.getScoreHash(difficulty, score, stars,
                                         name) == hash:
                        self.addHighscore(difficulty, score, stars, name)
                    else:
                        Log.warn(
                            "Weak hack attempt detected. Better luck next time."
                        )

    def _set(self, attr, value):
        if not self.info.has_section("song"):
            self.info.add_section("song")
        if type(value) == unicode:
            value = value.encode(Config.encoding)
        else:
            value = str(value)
        self.info.set("song", attr, value)

    def getObfuscatedScores(self):
        s = {}
        for difficulty in self.highScores.keys():
            s[difficulty.id] = [
                (score, stars, name,
                 self.getScoreHash(difficulty, score, stars, name))
                for score, stars, name in self.highScores[difficulty]
            ]
        return binascii.hexlify(Cerealizer.dumps(s))

    def save(self):
        self._set("scores", self.getObfuscatedScores())

        f = open(self.fileName, "w")
        self.info.write(f)
        f.close()

    def _get(self, attr, type=None, default=""):
        try:
            v = self.info.get("song", attr)
        except:
            v = default
        if v is not None and type:
            v = type(v)
        return v

    def getDifficulties(self):
        # Tutorials only have the medium difficulty
        if self.tutorial:
            return [difficulties[MEDIUM_DIFFICULTY]]

        if self._difficulties is not None:
            return self._difficulties

        # See which difficulties are available
        try:
            noteFileName = os.path.join(os.path.dirname(self.fileName),
                                        "notes.mid")
            info = MidiInfoReader()
            midiIn = midi.MidiInFile(info, noteFileName)
            try:
                midiIn.read()
            except MidiInfoReader.Done:
                pass
            info.difficulties.sort(lambda a, b: cmp(b.id, a.id))
            self._difficulties = info.difficulties
        except:
            self._difficulties = difficulties.values()
        return self._difficulties

    def getName(self):
        return self._get("name")

    def setName(self, value):
        self._set("name", value)

    def getArtist(self):
        return self._get("artist")

    def getCassetteColor(self):
        c = self._get("cassettecolor")
        if c:
            return Theme.hexToColor(c)

    def setCassetteColor(self, color):
        self._set("cassettecolor", Theme.colorToHex(color))

    def setArtist(self, value):
        self._set("artist", value)

    def getScoreHash(self, difficulty, score, stars, name):
        return sha.sha("%d%d%d%s" %
                       (difficulty.id, score, stars, name)).hexdigest()

    def getDelay(self):
        return self._get("delay", int, 0)

    def setDelay(self, value):
        return self._set("delay", value)

    def getHighscores(self, difficulty):
        try:
            return self.highScores[difficulty]
        except KeyError:
            return []

    def uploadHighscores(self, url, songHash):
        try:
            d = {
                "songName": self.songName,
                "songHash": songHash,
                "scores": self.getObfuscatedScores(),
                "version": Version.version()
            }
            data = urllib.urlopen(url + "?" + urllib.urlencode(d)).read()
            Log.debug("Score upload result: %s" % data)
            if ";" in data:
                fields = data.split(";")
            else:
                fields = [data, "0"]
            return (fields[0] == "True", int(fields[1]))
        except Exception, e:
            Log.error(e)
            return (False, 0)
Esempio n. 44
0
File: Song.py Progetto: twcb/FoF
class LibraryInfo(object):
    def __init__(self, libraryName, infoFileName):
        self.libraryName = libraryName
        self.fileName = infoFileName
        self.info = ConfigParser()
        self.songCount = 0

        try:
            self.info.read(infoFileName)
        except:
            pass

        # Set a default name
        if not self.name:
            self.name = os.path.basename(os.path.dirname(self.fileName))

        # Count the available songs
        libraryRoot = os.path.dirname(self.fileName)
        for name in os.listdir(libraryRoot):
            if not os.path.isdir(os.path.join(libraryRoot,
                                              name)) or name.startswith("."):
                continue
            if os.path.isfile(os.path.join(libraryRoot, name, "song.ini")):
                self.songCount += 1

    def _set(self, attr, value):
        if not self.info.has_section("library"):
            self.info.add_section("library")
        if type(value) == unicode:
            value = value.encode(Config.encoding)
        else:
            value = str(value)
        self.info.set("library", attr, value)

    def save(self):
        f = open(self.fileName, "w")
        self.info.write(f)
        f.close()

    def _get(self, attr, type=None, default=""):
        try:
            v = self.info.get("library", attr)
        except:
            v = default
        if v is not None and type:
            v = type(v)
        return v

    def getName(self):
        return self._get("name")

    def setName(self, value):
        self._set("name", value)

    def getColor(self):
        c = self._get("color")
        if c:
            return Theme.hexToColor(c)

    def setColor(self, color):
        self._set("color", Theme.colorToHex(color))

    name = property(getName, setName)
    color = property(getColor, setColor)
Esempio n. 45
0
                if run_once:
                    try:
                        results[idx].update(tmp_results[idx])
                    except IndexError:
                        pass
                        # sleep(3)
            run_once = True
            tmp_results = results
        df = pd.DataFrame(results)

        df['parsing'] = df['Product Description'].apply(
            lambda x: ce.cleansing_prodDesc(x))
        df['shop_input_fts'] = df['Shop Name']
        df['addres_input_fts'] = df['Shop Address']

        if config.has_section('Discount2'):
            df[[
                'Date_bfr', 'Number_bfr', 'Name_bfr', 'Alamat_bfr',
                'Price_bfr', 'Total_bfr', 'Diskon_bfr', 'Diskon2_bfr',
                'Unit_bfr'
            ]] = df[[
                'Invoice date', 'Invoice Number', 'Shop Name', 'Shop Address',
                'Price', 'Total Value', 'Discount', 'Discount2', 'Unit'
            ]]
        else:
            df[[
                'Date_bfr', 'Number_bfr', 'Name_bfr', 'Alamat_bfr',
                'Price_bfr', 'Total_bfr', 'Diskon_bfr', 'Unit_bfr'
            ]] = df[[
                'Invoice date', 'Invoice Number', 'Shop Name', 'Shop Address',
                'Price', 'Total Value', 'Discount', 'Unit'
Esempio n. 46
0
parser = argparse.ArgumentParser(description='Light sensor toolset.')
parser.add_argument('--sensor', help='url of the video')
parser.add_argument('--sunrise', help='Set the sunrise time in format hh:mm')
parser.add_argument('--sunset', help='Set the sunset time in format hh:mm')
args = parser.parse_args()

filename = expanduser('~/assistant-helper/smarthome.ini')
section = 'light_' + args.sensor

config = ConfigParser()
config.read(filename)

# setter
if args.sunrise or args.sunset:
    if not config.has_section(section):
        config.add_section(section)
    config.set(section, 'sunrise', args.sunrise)
    config.set(section, 'sunset', args.sunset)

    with open(filename, 'w') as outfile:
        config.write(outfile)
else:
    sunrise = config.get(section, 'sunrise')
    sunset = config.get(section, 'sunset')
    
    now = datetime.now()
    m_today = (now - now.replace(hour=0, minute=0, second=0, microsecond=0)).total_seconds() / 60.0

    print json.dumps({
        "light_needed": m_today < int(sunrise[:-3]) * 60 + int(sunrise[-2:]) or m_today > int(sunset[:-3]) * 3600 + int(sunset[-2:]),
Esempio n. 47
0
def create_instance(c_instance, user_path = ''):
    """ The generic script can be customised by using parameters.
        In this case, the user has written a text file with all necessary info.
        Here we read this file and fill the necessary data structures before
        instantiating the generic script.
    """
    device_map_mode = Live.MidiMap.MapMode.absolute
    volume_map_mode = Live.MidiMap.MapMode.absolute
    sends_map_mode = Live.MidiMap.MapMode.absolute
    if not user_path == '':
        file_object = open(user_path)
        if file_object:
            file_data = None
            config_parser = ConfigParser()
            config_parser.readfp(file_object, user_path)
            device_controls = [(-1, -1),
             (-1, -1),
             (-1, -1),
             (-1, -1),
             (-1, -1),
             (-1, -1),
             (-1, -1),
             (-1, -1)]
            transport_controls = {'STOP': -1,
             'PLAY': -1,
             'REC': -1,
             'LOOP': -1,
             'RWD': -1,
             'FFWD': -1}
            volume_controls = [(-1, -1),
             (-1, -1),
             (-1, -1),
             (-1, -1),
             (-1, -1),
             (-1, -1),
             (-1, -1),
             (-1, -1)]
            trackarm_controls = [-1,
             -1,
             -1,
             -1,
             -1,
             -1,
             -1,
             -1]
            bank_controls = {'TOGGLELOCK': -1,
             'NEXTBANK': -1,
             'PREVBANK': -1,
             'BANK1': -1,
             'BANK2': -1,
             'BANK3': -1,
             'BANK4': -1,
             'BANK5': -1,
             'BANK6': -1,
             'BANK7': -1,
             'BANK8': -1}
            controller_descriptions = {'INPUTPORT': '',
             'OUTPUTPORT': '',
             'CHANNEL': -1}
            mixer_options = {'NUMSENDS': 2,
             'SEND1': [-1,
                       -1,
                       -1,
                       -1,
                       -1,
                       -1,
                       -1,
                       -1],
             'SEND2': [-1,
                       -1,
                       -1,
                       -1,
                       -1,
                       -1,
                       -1,
                       -1],
             'MASTERVOLUME': -1,
             'MASTERVOLUMECHANNEL': -1}
            for index in range(8):
                if config_parser.has_section('DeviceControls'):
                    encoder_tuple = [-1, -1]
                    option_name = 'Encoder' + str(index + 1)
                    if config_parser.has_option('DeviceControls', option_name):
                        option_value = config_parser.getint('DeviceControls', option_name)
                        if option_value in range(128):
                            encoder_tuple[0] = option_value
                    option_name = 'EncoderChannel' + str(index + 1)
                    if config_parser.has_option('DeviceControls', option_name):
                        option_value = config_parser.getint('DeviceControls', option_name)
                        if option_value in range(128):
                            encoder_tuple[1] = option_value
                    device_controls[index] = tuple(encoder_tuple)
                    option_name = 'Bank' + str(index + 1) + 'Button'
                    if config_parser.has_option('DeviceControls', option_name):
                        option_value = config_parser.getint('DeviceControls', option_name)
                        if option_value in range(128):
                            option_key = 'BANK' + str(index + 1)
                            bank_controls[option_key] = option_value
                if config_parser.has_section('MixerControls'):
                    volume_tuple = [-1, -1]
                    option_name = 'VolumeSlider' + str(index + 1)
                    if config_parser.has_option('MixerControls', option_name):
                        option_value = config_parser.getint('MixerControls', option_name)
                        if option_value in range(128):
                            volume_tuple[0] = option_value
                    option_name = 'Slider' + str(index + 1) + 'Channel'
                    if config_parser.has_option('MixerControls', option_name):
                        option_value = config_parser.getint('MixerControls', option_name)
                        if option_value in range(16):
                            volume_tuple[1] = option_value
                    volume_controls[index] = tuple(volume_tuple)
                    option_name = 'TrackArmButton' + str(index + 1)
                    if config_parser.has_option('MixerControls', option_name):
                        option_value = config_parser.getint('MixerControls', option_name)
                        if option_value in range(128):
                            trackarm_controls[index] = option_value
                    option_name = 'Send1Knob' + str(index + 1)
                    if config_parser.has_option('MixerControls', option_name):
                        option_value = config_parser.getint('MixerControls', option_name)
                        if option_value in range(128):
                            mixer_options['SEND1'][index] = option_value
                    option_name = 'Send2Knob' + str(index + 1)
                    if config_parser.has_option('MixerControls', option_name):
                        option_value = config_parser.getint('MixerControls', option_name)
                        if option_value in range(128):
                            mixer_options['SEND2'][index] = option_value
                if config_parser.has_section('Globals'):
                    if config_parser.has_option('Globals', 'GlobalChannel'):
                        option_value = config_parser.getint('Globals', 'GlobalChannel')
                        if option_value in range(16):
                            controller_descriptions['CHANNEL'] = option_value
                    if config_parser.has_option('Globals', 'InputName'):
                        controller_descriptions['INPUTPORT'] = config_parser.get('Globals', 'InputName')
                    if config_parser.has_option('Globals', 'OutputName'):
                        controller_descriptions['OUTPUTPORT'] = config_parser.get('Globals', 'OutputName')
                    pad_translation = []
                    for pad in range(16):
                        pad_info = []
                        note = -1
                        channel = -1
                        option_name = 'Pad' + str(pad + 1) + 'Note'
                        if config_parser.has_option('Globals', option_name):
                            note = config_parser.getint('Globals', option_name)
                            if note in range(128):
                                option_name = 'Pad' + str(pad + 1) + 'Channel'
                                if config_parser.has_option('Globals', option_name):
                                    channel = config_parser.getint('Globals', option_name)
                                if channel is -1 and controller_descriptions['CHANNEL'] is not -1:
                                    channel = controller_descriptions['CHANNEL']
                                if channel in range(16):
                                    pad_info.append(pad % 4)
                                    pad_info.append(int(pad / 4))
                                    pad_info.append(note)
                                    pad_info.append(channel)
                                    pad_translation.append(tuple(pad_info))

                    if len(pad_translation) > 0:
                        controller_descriptions['PAD_TRANSLATION'] = tuple(pad_translation)
                if config_parser.has_section('DeviceControls'):
                    if config_parser.has_option('DeviceControls', 'NextBankButton'):
                        option_value = config_parser.getint('DeviceControls', 'NextBankButton')
                        if option_value in range(128):
                            bank_controls['NEXTBANK'] = option_value
                    if config_parser.has_option('DeviceControls', 'PrevBankButton'):
                        option_value = config_parser.getint('DeviceControls', 'PrevBankButton')
                        if option_value in range(128):
                            bank_controls['PREVBANK'] = option_value
                    if config_parser.has_option('DeviceControls', 'LockButton'):
                        option_value = config_parser.getint('DeviceControls', 'LockButton')
                        if option_value in range(128):
                            bank_controls['TOGGLELOCK'] = option_value
                    if config_parser.has_option('DeviceControls', 'EncoderMapMode'):
                        device_map_mode = interpret_map_mode(config_parser.get('DeviceControls', 'EncoderMapMode'))
                if config_parser.has_section('MixerControls'):
                    if config_parser.has_option('MixerControls', 'MasterVolumeSlider'):
                        option_value = config_parser.getint('MixerControls', 'MasterVolumeSlider')
                        if option_value in range(128):
                            mixer_options['MASTERVOLUME'] = option_value
                    if config_parser.has_option('MixerControls', 'MasterSliderChannel'):
                        option_value = config_parser.getint('MixerControls', 'MasterSliderChannel')
                        if option_value in range(16):
                            mixer_options['MASTERVOLUMECHANNEL'] = option_value
                    if config_parser.has_option('MixerControls', 'VolumeMapMode'):
                        volume_map_mode = interpret_map_mode(config_parser.get('MixerControls', 'VolumeMapMode'))
                    if config_parser.has_option('MixerControls', 'SendsMapMode'):
                        sends_map_mode = interpret_map_mode(config_parser.get('MixerControls', 'SendsMapMode'))
                        mixer_options['SENDMAPMODE'] = sends_map_mode
                if config_parser.has_section('TransportControls'):
                    if config_parser.has_option('TransportControls', 'StopButton'):
                        option_value = config_parser.getint('TransportControls', 'StopButton')
                        if option_value in range(128):
                            transport_controls['STOP'] = option_value
                    if config_parser.has_option('TransportControls', 'PlayButton'):
                        option_value = config_parser.getint('TransportControls', 'PlayButton')
                        if option_value in range(128):
                            transport_controls['PLAY'] = option_value
                    if config_parser.has_option('TransportControls', 'RecButton'):
                        option_value = config_parser.getint('TransportControls', 'RecButton')
                        if option_value in range(128):
                            transport_controls['REC'] = option_value
                    if config_parser.has_option('TransportControls', 'LoopButton'):
                        option_value = config_parser.getint('TransportControls', 'LoopButton')
                        if option_value in range(128):
                            transport_controls['LOOP'] = option_value
                    if config_parser.has_option('TransportControls', 'RwdButton'):
                        option_value = config_parser.getint('TransportControls', 'RwdButton')
                        if option_value in range(128):
                            transport_controls['RWD'] = option_value
                    if config_parser.has_option('TransportControls', 'FfwdButton'):
                        option_value = config_parser.getint('TransportControls', 'FfwdButton')
                        if option_value in range(128):
                            transport_controls['FFWD'] = option_value

    return GenericScript(c_instance, device_map_mode, volume_map_mode, tuple(device_controls), transport_controls, tuple(volume_controls), tuple(trackarm_controls), bank_controls, controller_descriptions, mixer_options)
Esempio n. 48
0
# Add the project-global data
package_info['package_data'].setdefault(PACKAGENAME, [])
package_info['package_data'][PACKAGENAME].append('data/*')
package_info['package_data'][PACKAGENAME].append('pathprof/data/*')
package_info['package_data'][PACKAGENAME].append('itudata/*.*')
package_info['package_data'][PACKAGENAME].append('itudata/p.452-16/*')
package_info['package_data'][PACKAGENAME].append(
    'itudata/p.452-16/R-REC-P.452-16-201507/*')
package_info['package_data'][PACKAGENAME].append('itudata/p.676-10/*')
package_info['package_data'][PACKAGENAME].append('itudata/ra.769-2/*')

# Define entry points for command-line scripts
entry_points = {'console_scripts': []}

if conf.has_section('entry_points'):
    entry_point_list = conf.items('entry_points')
    for entry_point in entry_point_list:
        entry_points['console_scripts'].append('{0} = {1}'.format(
            entry_point[0], entry_point[1]))

# Include all .c files, recursively, including those generated by
# Cython, since we can not do this in MANIFEST.in with a "dynamic"
# directory name.
c_files = []
for root, dirs, files in os.walk(PACKAGENAME):
    for filename in files:
        if filename.endswith('.c'):
            c_files.append(
                os.path.join(os.path.relpath(root, PACKAGENAME), filename))
package_info['package_data'][PACKAGENAME].extend(c_files)
Esempio n. 49
0
class Config(object):
    def __init__(self, inifile='data/config.ini'):
        self.inifile = inifile
        self.cfg = ConfigParser()

        with FileLock(self.inifile):
            if os.path.exists(inifile):
                self.cfg.read(inifile)

            # initialize configurations
            default_configs = {
                'server': {
                    'ip': '*',
                    'port': '8888',
                    'lastcheckupdate': 0,
                    'updateinfo': ''
                },
                'auth': {
                    'username': '******',
                    'password': '',  # empty password never validated
                    'passwordcheck': 'on',
                    'accesskey': '',  # empty access key never validated
                    'accesskeyenable': 'off',
                },
                'runtime': {
                    'mode': '',
                    'loginlock': 'off',
                    'loginfails': 0,
                    'loginlockexpire': 0,
                },
                'file': {
                    'lastdir': '/root',
                    'lastfile': '',
                },
            }
            needupdate = False
            for sec, secdata in default_configs.iteritems():
                if not self.cfg.has_section(sec):
                    self.cfg.add_section(sec)
                    needupdate = True
                for opt, val in secdata.iteritems():
                    if not self.cfg.has_option(sec, opt):
                        self.cfg.set(sec, opt, val)
                        needupdate = True

            # update ini file
            if needupdate: self.update(False)

    def update(self, lock=True):
        if lock:
            flock = FileLock(self.inifile)
            flock.acquire()

        try:
            inifp = open(self.inifile, 'w')
            self.cfg.write(inifp)
            inifp.close()
            if lock: flock.release()
            return True
        except:
            if lock: flock.release()
            return False

    def has_option(self, section, option):
        return self.cfg.has_option(section, option)

    def get(self, section, option):
        return self.cfg.get(section, option)

    def getboolean(self, section, option):
        return self.cfg.getboolean(section, option)

    def getint(self, section, option):
        return self.cfg.getint(section, option)

    def has_section(self, section):
        return self.cfg.has_section(section)

    def add_section(self, section):
        return self.cfg.add_section(section)

    def remove_option(self, section):
        return self.cfg.remove_option(section)

    def set(self, section, option, value):
        try:
            self.cfg.set(section, option, value)
        except:
            return False
        return self.update()
Esempio n. 50
0
class Configuration(object):
    """Thin layer over `ConfigParser` from the Python standard library.

    In addition to providing some convenience methods, the class remembers
    the last modification time of the configuration file, and reparses it
    when the file has changed.
    """
    def __init__(self, filename, params={}):
        self.filename = filename
        self.parser = ConfigParser()
        self._old_sections = {}
        self.parents = []
        self._lastmtime = 0
        self._sections = {}
        self.parse_if_needed(force=True)

    def __contains__(self, name):
        """Return whether the configuration contains a section of the given
        name.
        """
        return name in self.sections()

    def __getitem__(self, name):
        """Return the configuration section with the specified name."""
        if name not in self._sections:
            self._sections[name] = Section(self, name)
        return self._sections[name]

    def __repr__(self):
        return '<%s %r>' % (self.__class__.__name__, self.filename)

    @property
    def exists(self):
        """Return boolean indicating configuration file existence.

        :since: 1.0.11
        """
        return os.path.isfile(self.filename)

    def get(self, section, key, default=''):
        """Return the value of the specified option.

        Valid default input is a string. Returns a string.
        """
        return self[section].get(key, default)

    def getbool(self, section, key, default=''):
        """Return the specified option as boolean value.

        If the value of the option is one of "yes", "true", "enabled", "on",
        or "1", this method wll return `True`, otherwise `False`.

        Valid default input is a string or a bool. Returns a bool.

        (since Trac 0.9.3, "enabled" added in 0.11)
        """
        return self[section].getbool(key, default)

    def getint(self, section, key, default=''):
        """Return the value of the specified option as integer.

        If the specified option can not be converted to an integer, a
        `ConfigurationError` exception is raised.

        Valid default input is a string or an int. Returns an int.

        (since Trac 0.10)
        """
        return self[section].getint(key, default)

    def getfloat(self, section, key, default=''):
        """Return the value of the specified option as float.

        If the specified option can not be converted to a float, a
        `ConfigurationError` exception is raised.

        Valid default input is a string, float or int. Returns a float.

        (since Trac 0.12)
        """
        return self[section].getfloat(key, default)

    def getlist(self, section, key, default='', sep=',', keep_empty=False):
        """Return a list of values that have been specified as a single
        comma-separated option.

        A different separator can be specified using the `sep` parameter. If
        the `keep_empty` parameter is set to `True`, empty elements are
        included in the list.

        Valid default input is a string or a list. Returns a string.

        (since Trac 0.10)
        """
        return self[section].getlist(key, default, sep, keep_empty)

    def getpath(self, section, key, default=''):
        """Return a configuration value as an absolute path.

        Relative paths are resolved relative to the location of this
        configuration file.

        Valid default input is a string. Returns a normalized path.

        (enabled since Trac 0.11.5)
        """
        return self[section].getpath(key, default)

    def set(self, section, key, value):
        """Change a configuration value.

        These changes are not persistent unless saved with `save()`.
        """
        self[section].set(key, value)

    def defaults(self, compmgr=None):
        """Returns a dictionary of the default configuration values
        (''since 0.10'').

        If `compmgr` is specified, return only options declared in components
        that are enabled in the given `ComponentManager`.
        """
        defaults = {}
        for (section, key), option in Option.get_registry(compmgr).items():
            defaults.setdefault(section, {})[key] = option.default
        return defaults

    def options(self, section, compmgr=None):
        """Return a list of `(name, value)` tuples for every option in the
        specified section.

        This includes options that have default values that haven't been
        overridden. If `compmgr` is specified, only return default option
        values for components that are enabled in the given `ComponentManager`.
        """
        return self[section].options(compmgr)

    def remove(self, section, key):
        """Remove the specified option."""
        self[section].remove(key)

    def sections(self, compmgr=None, defaults=True):
        """Return a list of section names.

        If `compmgr` is specified, only the section names corresponding to
        options declared in components that are enabled in the given
        `ComponentManager` are returned.
        """
        sections = set([to_unicode(s) for s in self.parser.sections()])
        for parent in self.parents:
            sections.update(parent.sections(compmgr, defaults=False))
        if defaults:
            sections.update(self.defaults(compmgr))
        return sorted(sections)

    def has_option(self, section, option, defaults=True):
        """Returns True if option exists in section in either the project
        trac.ini or one of the parents, or is available through the Option
        registry.

        (since Trac 0.11)
        """
        section_str = _to_utf8(section)
        if self.parser.has_section(section_str):
            if _to_utf8(option) in self.parser.options(section_str):
                return True
        for parent in self.parents:
            if parent.has_option(section, option, defaults=False):
                return True
        return defaults and (section, option) in Option.registry

    def save(self):
        """Write the configuration options to the primary file."""
        if not self.filename:
            return

        # Only save options that differ from the defaults
        sections = []
        for section in self.sections():
            section_str = _to_utf8(section)
            options = []
            for option in self[section]:
                default_str = None
                for parent in self.parents:
                    if parent.has_option(section, option, defaults=False):
                        default_str = _to_utf8(parent.get(section, option))
                        break
                option_str = _to_utf8(option)
                current_str = False
                if self.parser.has_option(section_str, option_str):
                    current_str = self.parser.get(section_str, option_str)
                if current_str is not False and current_str != default_str:
                    options.append((option_str, current_str))
            if options:
                sections.append((section_str, sorted(options)))

        # At this point, all the strings in `sections` are UTF-8 encoded `str`
        try:
            wait_for_file_mtime_change(self.filename)
            with AtomicFile(self.filename, 'w') as fileobj:
                fileobj.write('# -*- coding: utf-8 -*-\n\n')
                for section_str, options in sections:
                    fileobj.write('[%s]\n' % section_str)
                    section = to_unicode(section_str)
                    for key_str, val_str in options:
                        if to_unicode(key_str) in self[section].overridden:
                            fileobj.write('# %s = <inherited>\n' % key_str)
                        else:
                            val_str = val_str.replace(CRLF, '\n') \
                                             .replace('\n', '\n ')
                            fileobj.write('%s = %s\n' % (key_str, val_str))
                    fileobj.write('\n')
            self._old_sections = deepcopy(self.parser._sections)
        except Exception:
            # Revert all changes to avoid inconsistencies
            self.parser._sections = deepcopy(self._old_sections)
            raise

    def parse_if_needed(self, force=False):
        if not self.filename or not self.exists:
            return False

        changed = False
        modtime = os.path.getmtime(self.filename)
        if force or modtime != self._lastmtime:
            self.parser._sections = {}
            if not self.parser.read(self.filename):
                raise TracError(_("Error reading '%(file)s', make sure it is "
                                  "readable.", file=self.filename))
            self._lastmtime = modtime
            self._old_sections = deepcopy(self.parser._sections)
            changed = True

        if changed:
            self.parents = []
            if self.parser.has_option('inherit', 'file'):
                for filename in self.parser.get('inherit', 'file').split(','):
                    filename = to_unicode(filename.strip())
                    if not os.path.isabs(filename):
                        filename = os.path.join(os.path.dirname(self.filename),
                                                filename)
                    self.parents.append(Configuration(filename))
        else:
            for parent in self.parents:
                changed |= parent.parse_if_needed(force=force)

        if changed:
            self._sections = {}
        return changed

    def touch(self):
        if self.filename and self.exists \
                and os.access(self.filename, os.W_OK):
            wait_for_file_mtime_change(self.filename)

    def set_defaults(self, compmgr=None):
        """Retrieve all default values and store them explicitly in the
        configuration, so that they can be saved to file.

        Values already set in the configuration are not overridden.
        """
        for (section, name), option in Option.get_registry(compmgr).items():
            if not self.parser.has_option(_to_utf8(section), _to_utf8(name)):
                value = option.default
                if any(parent[section].contains(name, defaults=False)
                       for parent in self.parents):
                    value = None
                if value is not None:
                    value = option.dumps(value)
                self.set(section, name, value)
Esempio n. 51
0
def options_parser():
    usage = "%prog [options]"
    defaults = {'verbose'         : False,
                'dest_dir'        : '~/Downloads/Anime',
                'titles_file'       : '~/.kage/titles.cfg',
                'use_transmission': True,
                'use_smtp'        : True,
                'smtp_host'       : 'localhost',
                'smtp_port'       : 25,
                'emails'          : [],
               }
               
    parser = OptionParser(usage=usage, version=__VERSION__)
    parser.add_option("-c", "--config", metavar="FILE",
                      help="Config with base settings and anime list.",
                      default=os.path.expanduser('~/.kage/kage.cfg'))
    parser.add_option("-v", "--verbose", action="store_true",
                      help="Print debug information.")
    parser.add_option("-l", "--log", metavar="FILE",
                      help="Write messages to file.")
    parser.add_option("-t", "--titles-file", metavar="FILE",
                      help="File with saved anime titles info.")
    parser.add_option("-b", "--download-dir", metavar="DIR",
                      help="Download anime to this dir.")
                      
    main_g = OptionGroup(parser, "Main options")                      
    main_g.add_option("-a", "--add", action="store_true",
                      help="Add new anime to config.")
    main_g.add_option("-d", "--delete", action="store_true",
                      help="Remove anime from config by from kage ID")
    main_g.add_option("-u", "--update", action="store_true",
                      help="Search for first unseen episode and try to get them.")
    main_g.add_option("--list", action="store_true",
                      help="List enabled titles from config.")
                      
    main_g.add_option("-i", "--id", type="int", dest="kage_id",
                      help="ID from url of KageProject anime page.")
    main_g.add_option("-n", "--title-name", dest="title_name",
                      help="Anime title name.")
    main_g.add_option("-s", "--last-episode", type="int", dest="start_episode",
                      help="Download episodes after this.")
    main_g.add_option("--sub-rg-id", type="int", dest="sub_rg_id",
                      help="Subtitles release group id.")                      
    main_g.add_option("--subdelay", type="int",
                      help="Wait prefered group for n secs.")
                      
    main_g.add_option("-U", "--get-all", action="store_true",
                      help="Search for new episodes and try to get them all.")
                      
    torrent_g = OptionGroup(parser, "Torrent client options")
    torrent_g.add_option("--no-transmission", action="store_false",
                      dest="use_transmission", help="Don't add torrent to Transmission.")
    torrent_g.add_option("--transmission-host",
                      help="'Host:port' of remote transmission instance.")
    torrent_g.add_option("--transmission-cred",
                      help="'user:password' for remote transmission instance.") 

    smtp_g = OptionGroup(parser, "Notification sending")
    smtp_g.add_option("--no-smtp", action="store_false", dest="use_smtp",
                      help="Don't send email notifications.", default=True)
    smtp_g.add_option("--smtp-host", help="SMTP host")
    smtp_g.add_option("--smtp-port", type="int", help="SMTP host port")
    smtp_g.add_option("--smtp-user", type="string", help="SMTP user")
    smtp_g.add_option("--smtp-password", type="string", help="SMTP password")
    smtp_g.add_option("--email-from", type="string", help="Send emeil from this addr.")          
    smtp_g.add_option("-r", "--recipient", type="string", action="append", dest="emails",
                      help="Send notification to this email. Can be listed several times.")
                      
    parser.add_option_group(main_g)
    parser.add_option_group(torrent_g)
    parser.add_option_group(smtp_g)                  
    (options, args) = parser.parse_args()

    options.config = os.path.expanduser(options.config)
    if not os.path.isfile(options.config):
        parser.error("Config file '%s' does't exists." % options.config)

    cfgparser = ConfigParser()
    cfgparser.read(options.config)
    if cfgparser.has_section('global'):
        for key, value in cfgparser.items('global'):
            if getattr(options, key, 'XXXXXX') is None:
                if key in ['verbose', 'use_transmission', 'use_smtp']:
                    value = cfgparser.getboolean('global', key)
                elif key in ['smtp_port']:
                    value = cfgparser.getint('global', key)
                elif key in ['emails']:
                    value = value.strip().split(' ')
                setattr(options, key, value)
                
    for key, value in defaults.iteritems():
        if getattr(options, key, 'XXXXXX') is None:
            setattr(options, key, value)
    
    if (options.add or options.delete) and options.kage_id is None:
        parser.error("To add or delete anime title you must specify kage ID with '--id'")
    if options.add and options.delete:
        parser.error("Delete and Add opts don't work together!")
    
    if options.update and options.get_all:
        parser.error("Update and GetAll opts don't work together!")    
            
    if options.use_transmission and options.transmission_host is not None and \
       options.transmission_cred is None:
        parser.error("Please specify login:password if you using remote transmission instance.")
        
    if options.use_smtp:
        if options.smtp_user is not None and options.smtp_pass is None:
            parser.error("Specify password for smtp user '%s'." % options.smtp_user)
        if len(options.emails) == 0:
            parser.error("SMTP notification is enabled but no recipients was listed!")

    options.dest_dir = os.path.expanduser(options.dest_dir)
    if not os.path.isdir(options.dest_dir):
        parser.error("Output dir '%s' does't exists." % options.dest_dir)

    options.titles_file = os.path.expanduser(options.titles_file)
    if not os.path.isfile(options.titles_file):
        if options.add is None:
            parser.error("File with anime info '%s' does't exists." % options.titles_file)
        else:
            open(options.titles_file, 'w').close()
      
    return options
Esempio n. 52
0
    raise RuntimeError("Usage: compilemap <config file> [<target>]")

if not exists(sys.argv[1]):
    raise RuntimeError("Config file not found...")

conf = ConfigParser()
conf.read(sys.argv[1])

if len(sys.argv) > 2:
    target = sys.argv[2]
else:
    target = "default"

targetsec = ":%s" % target

if not conf.has_section(targetsec):
    raise KeyError(
        "Can't build target %s: Section %s not found in the config file." %
        (target, targetsec))
else:
    print "Building Target", target

mapname = conf.get("general", "mapname")
materialsdir = conf.get("general", "materialsdir")
mapsrcdir = conf.get("general", "mapsrcdir")
gamedir = conf.get("general", "gamedir")

vbsp = conf.get("programs", "vbsp")
vvis = conf.get("programs", "vvis")
vrad = conf.get("programs", "vrad")
bspzip = conf.get("programs", "bspzip")
Esempio n. 53
0
    def _get_paths_for_root(self, rootname):
        if self.rootpaths.has_key(rootname):
            return self.rootpaths[rootname]

        paths_for_root = {}

        # Parse the authz file, replacing ConfigParser's optionxform()
        # method with something that won't futz with the case of the
        # option names.
        cp = ConfigParser()
        cp.optionxform = lambda x: x
        try:
            cp.read(self._get_authz_file(rootname))
        except:
            raise ViewVCException("Unable to parse configured authzfile file")

        # Ignore context; assume the authz file only has the repository URL's
        # basename, just like mod_dav_svn requires it.
        # Perhaps it's better to just use the repository directory's basename.
        root_parts = rootname.split('/')
        repo_name = root_parts[-1]

        # Figure out if there are any aliases for the current username
        aliases = []
        if cp.has_section('aliases'):
            for alias in cp.options('aliases'):
                entry = cp.get('aliases', alias)
                if entry == self.username:
                    aliases.append(alias)

        # Figure out which groups USERNAME has a part of.
        groups = []
        if cp.has_section('groups'):
            all_groups = []

            def _process_group(groupname):
                """Inline function to handle groups within groups.

        For a group to be within another group in SVN, the group
        definitions must be in the correct order in the config file.
        ie. If group A is a member of group B then group A must be
        defined before group B in the [groups] section.

        Unfortunately, the ConfigParser class provides no way of
        finding the order in which groups were defined so, for reasons
        of practicality, this function lets you get away with them
        being defined in the wrong order.  Recursion is guarded
        against though."""

                # If we already know the user is part of this already-
                # processed group, return that fact.
                if groupname in groups:
                    return 1
                # Otherwise, ensure we don't process a group twice.
                if groupname in all_groups:
                    return 0
                # Store the group name in a global list so it won't be processed again
                all_groups.append(groupname)
                group_member = 0
                groupname = groupname.strip()
                entries = cp.get('groups', groupname).split(',')
                for entry in entries:
                    entry = entry.strip()
                    if entry == self.username:
                        group_member = 1
                        break
                    elif entry[0:1] == "@" and _process_group(entry[1:]):
                        group_member = 1
                        break
                    elif entry[0:1] == "&" and entry[1:] in aliases:
                        group_member = 1
                        break
                if group_member:
                    groups.append(groupname)
                return group_member

            # Process the groups
            for group in cp.options('groups'):
                _process_group(group)

        def _userspec_matches_user(userspec):
            # If there is an inversion character, recurse and return the
            # opposite result.
            if userspec[0:1] == '~':
                return not _userspec_matches_user(userspec[1:])

            # See if the userspec applies to our current user.
            return userspec == '*' \
                   or userspec == self.username \
                   or (self.username is not None and userspec == "$authenticated") \
                   or (self.username is None and userspec == "$anonymous") \
                   or (userspec[0:1] == "@" and userspec[1:] in groups) \
                   or (userspec[0:1] == "&" and userspec[1:] in aliases)

        def _process_access_section(section):
            """Inline function for determining user access in a single
      config secction.  Return a two-tuple (ALLOW, DENY) containing
      the access determination for USERNAME in a given authz file
      SECTION (if any)."""

            # Figure if this path is explicitly allowed or denied to USERNAME.
            allow = deny = 0
            for user in cp.options(section):
                user = user.strip()
                if _userspec_matches_user(user):
                    # See if the 'r' permission is among the ones granted to
                    # USER.  If so, we can stop looking.  (Entry order is not
                    # relevant -- we'll use the most permissive entry, meaning
                    # one 'allow' is all we need.)
                    allow = cp.get(section, user).find('r') != -1
                    deny = not allow
                    if allow:
                        break
            return allow, deny

        # Read the other (non-"groups") sections, and figure out in which
        # repositories USERNAME or his groups have read rights.  We'll
        # first check groups that have no specific repository designation,
        # then superimpose those that have a repository designation which
        # matches the one we're asking about.
        root_sections = []
        for section in cp.sections():

            # Skip the "groups" section -- we handled that already.
            if section == 'groups':
                continue

            if section == 'aliases':
                continue

            # Process root-agnostic access sections; skip (but remember)
            # root-specific ones that match our root; ignore altogether
            # root-specific ones that don't match our root.  While we're at
            # it, go ahead and figure out the repository path we're talking
            # about.
            if section.find(':') == -1:
                path = section
            else:
                name, path = section.split(':', 1)
                if name == repo_name:
                    root_sections.append(section)
                continue

            # Check for a specific access determination.
            allow, deny = _process_access_section(section)

            # If we got an explicit access determination for this path and this
            # USERNAME, record it.
            if allow or deny:
                if path != '/':
                    path = '/' + '/'.join(filter(None, path.split('/')))
                paths_for_root[path] = allow

        # Okay.  Superimpose those root-specific values now.
        for section in root_sections:

            # Get the path again.
            name, path = section.split(':', 1)

            # Check for a specific access determination.
            allow, deny = _process_access_section(section)

            # If we got an explicit access determination for this path and this
            # USERNAME, record it.
            if allow or deny:
                if path != '/':
                    path = '/' + '/'.join(filter(None, path.split('/')))
                paths_for_root[path] = allow

        # If the root isn't readable, there's no point in caring about all
        # the specific paths the user can't see.  Just point the rootname
        # to a None paths dictionary.
        root_is_readable = 0
        for path in paths_for_root.keys():
            if paths_for_root[path]:
                root_is_readable = 1
                break
        if not root_is_readable:
            paths_for_root = None

        self.rootpaths[rootname] = paths_for_root
        return paths_for_root
Esempio n. 54
0
    def ReadSettingsFile(self, in_file=''):
        if in_file != '':
            if os.path.isfile(in_file):
                pars = ConfigParser()
                pars.read(in_file)
                print 'Loading settings from file:', in_file

                if pars.has_section('BASIC'):
                    if pars.has_option('BASIC', 'run'):
                        self.run = pars.getint('BASIC', 'run')
                    else:
                        ExitMessage('Must specify run under [BASIC]. Exiting...')
                    if pars.has_option('BASIC', 'events'):
                        self.total_events = pars.getint('BASIC', 'events')
                    if pars.has_option('BASIC', 'ana_events'):
                        self.ana_events = pars.getint('BASIC', 'ana_events')
                    if pars.has_option('BASIC', 'first_event'):
                        self.first_event = pars.getint('BASIC', 'first_event')
                    if pars.has_option('BASIC', 'repeater_card'):
                        self.repeater_card = pars.getint('BASIC', 'repeater_card')
                    if pars.has_option('BASIC', 'voltage'):
                        self.voltage = pars.getfloat('BASIC', 'voltage')
                    if pars.has_option('BASIC', 'current_begin'):
                        self.current_begin = pars.getfloat('BASIC', 'current_begin')
                    if pars.has_option('BASIC', 'current_end'):
                        self.current_end = pars.getfloat('BASIC', 'current_end')
                    if pars.has_option('BASIC', 'dut_input'):
                        self.dut_input = pars.getint('BASIC', 'dut_input')
                    if pars.has_option('BASIC', 'dut_saturation'):
                        self.dut_saturation = pars.getint('BASIC', 'dut_saturation')
                    if pars.has_option('BASIC', 'data_dir'):
                        self.data_dir = pars.get('BASIC', 'data_dir')
                        if not os.path.isdir(self.data_dir):
                            ExitMessage('The specified data directory does not exist. Exiting...')
                    if pars.has_option('BASIC', 'sub_dir'):
                        self.sub_dir = pars.get('BASIC', 'sub_dir')
                    if pars.has_option('BASIC', 'output_dir'):
                        self.output_dir = pars.get('BASIC', 'output_dir')
                    if pars.has_option('BASIC', 'analysis_path'):
                        self.analysis_path = pars.get('BASIC', 'analysis_path')
                        if not os.path.isdir(self.analysis_path):
                            ExitMessage('Must give a valid analysis_path under [BASIC]. Exiting...')
                    if pars.has_option('BASIC', 'num_parallel') and self.do_parallel:
                        self.num_parallel = pars.getint('BASIC', 'num_parallel') if pars.getint('BASIC', 'num_parallel') <= mp.cpu_count() else self.num_parallel

                if pars.has_section('DUTS'):
                    if pars.has_option('DUTS', 'num'):
                        self.dut_num = pars.getint('DUTS', 'num')
                    if pars.has_option('DUTS', 'not_connected'):
                        self.not_connected = ChannelStringToArray(pars.get('DUTS', 'not_connected'))
                    if pars.has_option('DUTS', 'screened'):
                        self.screened = ChannelStringToArray(pars.get('DUTS', 'screened'))
                    if pars.has_option('DUTS', 'noisy'):
                        self.noisy = ChannelStringToArray(pars.get('DUTS', 'noisy'))

                for dut in xrange(self.dut_num):
                    if pars.has_section('DUT{d}'.format(d=dut)):
                        if pars.has_option('DUT{d}'.format(d=dut), 'name'):
                            self.dut_name[dut] = pars.get('DUT{d}'.format(d=dut), 'name')
                        if pars.has_option('DUT{d}'.format(d=dut), 'x0'):
                            self.dut_pos[dut] = pars.getfloat('DUT{d}'.format(d=dut), 'x0')
                        if pars.has_option('DUT{d}'.format(d=dut), 'pitch'):
                            self.dut_pitch[dut] = pars.getfloat('DUT{d}'.format(d=dut), 'pitch')
                        if pars.has_option('DUT{d}'.format(d=dut), 'first'):
                            self.dut_first_ch[dut] = pars.getint('DUT{d}'.format(d=dut), 'first')
                        if pars.has_option('DUT{d}'.format(d=dut), 'skip'):
                            self.dut_skip_ch[dut] = ChannelStringToArray(pars.get('DUT{d}'.format(d=dut), 'skip'))
                        if pars.has_option('DUT{d}'.format(d=dut), 'last'):
                            self.dut_last_ch[dut] = pars.getint('DUT{d}'.format(d=dut), 'last')

                if pars.has_section('ANALYSIS'):
                    if pars.has_option('ANALYSIS', 'do_pedestal'):
                        self.do_pedestal = pars.getboolean('ANALYSIS', 'do_pedestal')
                    if pars.has_option('ANALYSIS', 'do_cluster'):
                        self.do_cluster = pars.getboolean('ANALYSIS', 'do_cluster')
                    if pars.has_option('ANALYSIS', 'do_cluster_analysis'):
                        self.do_cluster_ana = pars.getboolean('ANALYSIS', 'do_cluster_analysis')
                    if pars.has_option('ANALYSIS', 'do_alignment'):
                        self.do_alignment = pars.getboolean('ANALYSIS', 'do_alignment')
                    if pars.has_option('ANALYSIS', 'do_alignment_analysis'):
                        self.do_alignment_ana = pars.getboolean('ANALYSIS', 'do_alignment_analysis')
                    if pars.has_option('ANALYSIS', 'do_transparent'):
                        self.do_transparent = pars.getboolean('ANALYSIS', 'do_transparent')
                    if pars.has_option('ANALYSIS', 'do_3d'):
                        self.do_3d = pars.getboolean('ANALYSIS', 'do_3d')

                if pars.has_section('PEDESTAL'):
                    if pars.has_option('PEDESTAL', 'tel_ped_hit_factor'):
                        self.tel_hit_factor = pars.getfloat('PEDESTAL', 'tel_ped_hit_factor')
                    if pars.has_option('PEDESTAL', 'dut_ped_hit_factor'):
                        self.dut_hit_factor = pars.getfloat('PEDESTAL', 'dut_ped_hit_factor')
                    if pars.has_option('PEDESTAL', 'do_cmc'):
                        self.do_cmc = pars.getboolean('PEDESTAL', 'do_cmc')
                    if pars.has_option('PEDESTAL', 'cm_cut'):
                        self.cm_cut = pars.getfloat('PEDESTAL', 'cm_cut')
                    if pars.has_option('PEDESTAL', 'sliding_length'):
                        self.sliding_length = pars.getint('PEDESTAL', 'sliding_length')

                if pars.has_section('CLUSTER'):
                    if pars.has_option('CLUSTER', 'clust_seed_facts'):
                        self.clust_seed = eval(pars.get('CLUSTER', 'clust_seed_facts'))
                    if pars.has_option('CLUSTER', 'clust_hit_facts'):
                        self.clust_hit = eval(pars.get('CLUSTER', 'clust_hit_facts'))

                if pars.has_section('SELECTION_SCINT'):
                    if pars.has_option('SELECTION_SCINT', 'xlow'):
                        self.scint_fid_cut['xlow'] = pars.getfloat('SELECTION_SCINT', 'xlow')
                    if pars.has_option('SELECTION_SCINT', 'xhigh'):
                        self.scint_fid_cut['xhigh'] = pars.getfloat('SELECTION_SCINT', 'xhigh')
                    if pars.has_option('SELECTION_SCINT', 'ylow'):
                        self.scint_fid_cut['ylow'] = pars.getfloat('SELECTION_SCINT', 'ylow')
                    if pars.has_option('SELECTION_SCINT', 'yhigh'):
                        self.scint_fid_cut['yhigh'] = pars.getfloat('SELECTION_SCINT', 'yhigh')

                for dut in xrange(self.dut_num):
                    if pars.has_section('SELECTION{d}'.format(d=dut)):
                        if pars.has_option('SELECTION{d}'.format(d=dut), 'xlow') and pars.has_option('SELECTION{d}'.format(d=dut), 'xhigh') and pars.has_option('SELECTION{d}'.format(d=dut), 'ylow') and pars.has_option('SELECTION{d}'.format(d=dut), 'yhigh'):
                            self.fid_region[dut] = {'xlow': pars.getfloat('SELECTION{d}'.format(d=dut), 'xlow'), 'xhigh': pars.getfloat('SELECTION{d}'.format(d=dut), 'xhigh'), 'ylow': pars.getfloat('SELECTION{d}'.format(d=dut), 'ylow'), 'yhigh': pars.getfloat('SELECTION{d}'.format(d=dut), 'yhigh')}
                        elif pars.has_option('SELECTION{d}'.format(d=dut), 'xlow') or pars.has_option('SELECTION{d}'.format(d=dut), 'xhigh') or pars.has_option('SELECTION{d}'.format(d=dut), 'ylow') or pars.has_option('SELECTION{d}'.format(d=dut), 'yhigh'):
                            print 'setting default fiducial region for nos specifying all the parameters xlow, xhigh, ylow, yhigh'
                            self.fid_region[dut] = {'xlow': 0, 'xhigh': 255, 'ylow': 0, 'yhigh': 255}
                        else:
                            self.fid_region[dut] = {'xlow': 0, 'xhigh': 255, 'ylow': 0, 'yhigh': 255}
                    else:
                        ExitMessage('You should have a SELECTION section for each dut i.e. SELECTION0 and SELECTION1 if num or DUTS is 2')
                if pars.has_section('ALIGNMENT'):
                    if pars.has_option('ALIGNMENT', 'align_dut'):
                        self.align_dut = min(0, pars.getint('ALIGNMENT', 'align_dut'))
                    if pars.has_option('ALIGNMENT', 'z_coordinates'):
                        self.z_coordinates = eval(pars.get('ALIGNMENT', 'z_coordinates'))
                    if pars.has_option('ALIGNMENT', 'alignment_method'):
                        if pars.get('ALIGNMENT', 'alignment_method') in ['events', 'percentage']:
                            self.align_method = pars.get('ALIGNMENT', 'alignment_method')
                    if pars.has_option('ALIGNMENT', 'alignment_factor'):
                        self.align_factor = pars.getint('ALIGNMENT', 'alignment_factor')
                    if pars.has_option('ALIGNMENT', 'do_align_dut'):
                        self.do_align_dut = pars.getboolean('ALIGNMENT', 'do_align_dut')
                    if pars.has_option('ALIGNMENT', 'no_align_dut_chs'):
                        self.no_align_dut_chs = ChannelStringToArray(pars.get('ALIGNMENT', 'no_align_dut_chs'))
                    if pars.has_option('ALIGNMENT', 'alignment_chi2_cut'):
                        self.align_chi2_cut = pars.getfloat('ALIGNMENT', 'alignment_chi2_cut')

                if pars.has_section('TRANSPARENT'):
                    if pars.has_option('TRANSPARENT', 'max_transp_cluster_size'):
                        self.max_transp_clust_size = pars.getint('TRANSPARENT', 'max_transp_cluster_size')
                    if pars.has_option('TRANSPARENT', 'save_transp_cluster_size'):
                        self.save_transp_clust_size = pars.getint('TRANSPARENT', 'save_transp_cluster_size')
                    if pars.has_option('TRANSPARENT', 'analyse_align'):
                        self.do_analyse_alignment = pars.getboolean('TRANSPARENT', 'analyse_align')
        self.SetFileAndTreeName()
        CreateDirectoryIfNecessary(self.output_dir + '/' + self.sub_dir + '/' + str(self.run))
        self.SaveSettingsAsPickle()
Esempio n. 55
0
class mrConfigParser(object):
    '''
    Class to parse config file
    '''
    __config = ConfigParser()
    __cfgFile = "config.ini"

    def __init__(self, cfgFile="config.ini"):
        '''
        Constructor
        @param cfgFile: Filepath of config file
        '''
        self.__config = ConfigParser()

        # check if file exsists
        if isfile(cfgFile):
            self.__config.read(cfgFile)
            self.__cfgFile = cfgFile

    def getSections(self):
        '''
        Returns list of section names
        '''
        return self.__config.sections()

    def getOptions(self, section):
        '''
        Returns list of options in a section
        '''
        if self.__config.has_section(section):
            return self.__config.options(section)
        return None

    def getConfigValue(self, section, option):
        '''
        Returns a config value of a option inside a section
        '''
        if self.__config.has_option(section, option):
            return self.__config.get(section, option)
        return None

    def getConfigValueBool(self, section, option):
        '''
        Returns a boolean config value of a option inside a section
        '''
        if self.__config.has_option(section, option):
            return self.__config.getboolean(section, option)
        return None

    def getConfigValueInt(self, section, option):
        '''
        Returns a integer config value of a option inside a section
        '''
        if self.__config.has_option(section, option):
            return self.__config.getint(section, option)
        return None

    def getConfigValueFloat(self, section, option):
        '''
        Returns a float config value of a option inside a section
        '''
        if self.__config.has_option(section, option):
            return self.__config.getfloat(section, option)
        return None

    def setConfigValue(self, section, option, value):
        '''
        Sets a config Value
        '''
        self.__config.set(section, option, value)

    def saveConfig(self, cfgFile=None):
        '''
        Saves config to file.
        @param cfgFile: Filepath of config file.
        If filepath is None or omitted, config is saved
        to filepath used at initiation  
        '''
        if cfgFile == None:
            cfgFile = self.__cfgFile

        fp = open(cfgFile, 'w')
        self.__config.write(fp)
        fp.close()
Esempio n. 56
0
class Config(object):
    _default_section = 'app'
    _default_config_file_path = os.path.abspath(
        os.path.join(os.path.dirname(__file__), 'default.ini'))

    def __init__(self, auto_save=True, path=None):
        if not path:
            if 'GRAB_SCREEN_CONFIG_FILE' in os.environ:
                path = os.environ['GRAB_SCREEN_CONFIG_FILE']
            else:
                path = os.path.join(os.path.expanduser('~'), '.config',
                                    'grab-screen', 'config.ini')

        self.auto_save = auto_save
        self.path = path
        self._parser = None

        self.load()

    def __iter__(self):
        for section in self._parser.sections():
            for option in self._parser.options(section):
                key = '{}_{}'.format(section, option).upper()
                yield key

    def __getattribute__(self, key):
        if key.isupper():
            return self.get(key)

        return object.__getattribute__(self, key)

    def __setattr__(self, key, value):
        if key.isupper():
            return self.set(key, value)

        return object.__setattr__(self, key, value)

    def __delattr__(self, key):
        if key.isupper():
            return self.delete(key)

        return object.__delattr__(self, key)

    def get(self, key):
        """Gets an option."""
        section, option = self._split_key(key)

        if not self._parser.has_option(section, option):
            return None

        return self._parser.get(section, option)

    def set(self, key, value):
        """Sets an option."""
        if value is None:
            self.delete(key)
            return

        section, option = self._split_key(key)

        self._parser.set(section, option, str(value))

        if self.auto_save:
            self.save()

    def delete(self, key):
        """Deletes an option."""
        section, option = self._split_key(key)
        removed = self._parser.remove_option(section, option)

        if removed and self.auto_save:
            self.save()

    def load(self):
        """Reads settings from the file."""
        if not os.path.exists(self.path):
            self.reset()
            return

        self._parser = ConfigParser()
        self._parser.read(self.path)

        self._load_logger()

    def save(self):
        """Writes settings to the file."""
        self._create_config_directory()

        for section in self._parser.sections():
            if not self._parser.options(section):
                self._parser.remove_section(section)

        with open(self.path, 'w') as config_file:
            self._parser.write(config_file)

    def reset(self):
        """Restores the default settings."""
        self._create_config_directory()

        copyfile(self._default_config_file_path, self.path)

        self.load()

    def _create_config_directory(self):
        directory = os.path.dirname(self.path)
        if not os.path.exists(directory):
            os.makedirs(directory)

    def _load_logger(self):
        """
        Setup the logger configs.

        User can set `LOGGER_LEVEL` setting to change the logger level.
        """
        level = self.LOGGER_LEVEL
        if level:
            level = level.upper()
        if level not in LOGGER_LEVELS:
            logger.warning("Invalid logger level '%s'", level)
            level = DEFAULT_LEVEL

        logging.config.dictConfig({
            'version': 1,
            'formatters': {
                'simple': {
                    'format': '%(asctime)s [%(levelname)s] %(message)s'
                },
            },
            'handlers': {
                'console': {
                    'level': 'DEBUG',
                    'class': 'logging.StreamHandler',
                    'formatter': 'simple',
                },
            },
            'loggers': {
                'grab_screen': {
                    'level': level,
                    'handlers': ['console'],
                },
            }
        })

    def _split_key(self, key):
        """Gets a section and an option names by the key."""
        key = key.lower()

        try:
            section, option = key.split('_', 1)
        except (ValueError, IndexError):
            section = self._default_section
            option = key

        if not self._parser.has_section(section):
            self._parser.add_section(section)

        return section, option
Esempio n. 57
0
    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.BaseDir = ini.get("InDirectory", "BaseDirectory")

        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
Esempio n. 58
0
    def config_load(self):

        self.start_gn_exists = os.path.exists(self.install_dir + '/' +
                                              self.game_name + '/start_gn.sh')
        self.start_gog_exists = os.path.exists(self.install_dir + '/' +
                                               self.game_name +
                                               '/start_gog.sh')

        config_file = self.install_dir + '/' + self.game_name + '/config.ini'
        config_parser = ConfigParser()
        config_parser.read(config_file)

        if not config_parser.has_section('Settings'):
            config_parser.add_section('Settings')

        if not config_parser.has_option('Settings', 'launcher_type'):
            if self.start_gog_exists:
                self.launcher_type = 'gog'
            else:
                self.launcher_type = 'gn'
            config_parser.set('Settings', 'launcher_type',
                              str(self.launcher_type))
        else:
            self.launcher_type = config_parser.get('Settings', 'launcher_type')

        if not config_parser.has_option('Settings', 'monitor'):
            self.monitor = global_monitor
            config_parser.set('Settings', 'monitor', str(self.monitor))
        else:
            self.monitor = config_parser.getint('Settings', 'monitor')

        if not config_parser.has_option('Settings', 'launcher'):
            self.launcher = True
            config_parser.set('Settings', 'launcher', str(self.launcher))
        else:
            self.launcher = config_parser.getboolean('Settings', 'launcher')

        if not config_parser.has_option('Settings', 'show_banner'):
            self.show_banner = True
            config_parser.set('Settings', 'show_banner', str(self.show_banner))
        else:
            self.show_banner = config_parser.getboolean(
                'Settings', 'show_banner')

        if not config_parser.has_option('Settings', 'command_before'):
            self.command_before = ''
            config_parser.set('Settings', 'command_before',
                              str(self.command_before))
        else:
            self.command_before = config_parser.get('Settings',
                                                    'command_before')

        if not config_parser.has_option('Settings', 'command_after'):
            self.command_after = ''
            config_parser.set('Settings', 'command_after',
                              str(self.command_after))
        else:
            self.command_after = config_parser.get('Settings', 'command_after')

        new_config_file = open(config_file, 'w')
        config_parser.write(new_config_file)
        new_config_file.close()
Esempio n. 59
0
class Mixer(Gtk.Window):
    """ Volti Mixer Application"""
    def __init__(self):
        GObject.GObject.__init__(self)

        self.cp = ConfigParser()
        self.cp.read(CONFIG_FILE)

        self.lock_mask = {}
        self.control_mask = {}
        self.card_hbox = {}
        self.alsa_channels = {}

        self.set_title("Volti Mixer")
        self.set_resizable(True)
        self.set_border_width(5)
        self.set_position(Gtk.WindowPosition.CENTER)
        self.add_events(Gdk.EventMask.BUTTON_PRESS_MASK)
        self.connect('delete_event', self.quit)

        icon_theme = Gtk.IconTheme.get_default()
        if icon_theme.has_icon("multimedia-volume-control"):
            self.set_icon_name("multimedia-volume-control")
        else:
            file = os.path.join(RES_DIR, "icons",
                                "multimedia-volume-control.svg")
            self.set_icon_from_file(file)

        self.acards = alsa.cards()
        self.set_layout()
        self.init_controls()
        self.show()

        card_index = int(self.cp.get("global", "card_index"))
        self.notebook.set_current_page(card_index)

    def set_layout(self):
        """ Gui layout """
        self.notebook = Gtk.Notebook()
        self.notebook.set_tab_pos(Gtk.PositionType.TOP)
        self.notebook.show()

        vbox = Gtk.VBox()
        vbox.add(self.notebook)
        self.add(vbox)

        bbox = Gtk.HButtonBox()
        bbox.set_layout(Gtk.ButtonBoxStyle.EDGE)
        button1 = Gtk.Button(label=_('_Select Controls...'))
        button1.connect("clicked", self.on_select_controls)
        bbox.add(button1)
        button2 = Gtk.Button(stock=Gtk.STOCK_QUIT)
        button2.connect("clicked", self.quit)
        bbox.add(button2)

        align = Gtk.Alignment.new(xscale=1, yscale=1)
        align.set_padding(5, 0, 0, 0)

        align.add(bbox)
        vbox.pack_start(align, False, False)
        vbox.show_all()

    def init_controls(self):
        try:
            show_values = bool(int(self.cp.get("global", "mixer_show_values")))
        except:
            show_values = False

        for card_index, card_name in enumerate(self.acards):
            vbox = Gtk.VBox()
            frame = Gtk.Frame()
            hbox = Gtk.HBox(True, 10)

            align = Gtk.Alignment.new(xscale=1, yscale=1)
            align.set_padding(10, 10, 10, 10)

            align.add(hbox)
            vbox.add(align)
            frame.add(vbox)

            self.card_hbox[card_index] = hbox
            self.notebook.insert_page(frame, Gtk.Label(label=card_name),
                                      card_index)

            try:
                self.lock_mask[card_index] = int(
                    self.cp.get("card-%d" % card_index, "mask_lock"))
            except:
                self.lock_mask[card_index] = 0

            try:
                self.control_mask[card_index] = int(
                    self.cp.get("card-%d" % card_index, "mask_control"))
            except:
                self.control_mask[card_index] = 0
                amixers = []
                try:
                    amixers = alsa.mixers(card_index)
                except alsa.ALSAAudioError:
                    pass
                for count, mixer in enumerate(amixers):
                    self.control_mask[card_index] |= (1 << count)

            n = 0
            self.get_channels(card_index)
            for channel, id in self.alsa_channels[card_index]:
                option_mask = option_value = _LOCK
                mixer = alsa.Mixer(channel, id, card_index)

                if not len(mixer.volumecap()):
                    continue

                if len(mixer.getvolume()) > 1:
                    option_mask |= _STEREO
                    option_mask |= _LOCK

                if self.lock_mask[card_index] & (1 << n):
                    option_value |= _LOCK

                try:
                    if mixer.getrec():
                        option_mask |= _REC
                    if mixer.getrec()[0]:
                        option_value |= _REC
                    if mixer.getmute():
                        option_mask |= _MUTE
                    if mixer.getmute()[0]:
                        option_value |= _MUTE
                except:
                    pass

                for el in hbox, align, vbox, frame:
                    el.show()

                volume = MixerControl(n, option_mask, option_value,
                                      show_values, card_index, channel)
                volume.set_level(self.get_volume(n, card_index))
                volume.connect("volume_changed", self.adjust_volume)
                volume.connect("volume_setting_toggled", self.setting_toggled)
                hbox.pack_start(volume, True, True)
                n += 1

            self.show_hide_controls(card_index)

    def get_channels(self, card_index):
        try:
            self.alsa_channels[card_index] = []
            for channel in alsa.mixers(card_index):
                id = 0
                while (channel, id) in self.alsa_channels[card_index]:
                    id += 1
                mixer = alsa.Mixer(channel, id, card_index)
                if len(mixer.volumecap()):
                    self.alsa_channels[card_index].append((channel, id))
        except:
            pass

    def setting_toggled(self, vol, channel, button, val, card_index):
        """ Handle checkbox toggles """
        ch, id = self.alsa_channels[card_index][channel]
        mixer = alsa.Mixer(ch, id, card_index)

        if button == _MUTE:
            mixer.setmute(val)

        if button == _LOCK:
            if val:
                self.lock_mask[card_index] |= (1 << channel)
            else:
                self.lock_mask[card_index] &= ~(1 << channel)

        if button == _REC:
            mixer.setrec(val)

    def adjust_volume(self, vol, channel, volume1, volume2, card_index):
        """ Track changes to the volume controls """
        self.set_volume((volume1, volume2), channel, card_index)

    def set_volume(self, volume, channel, card_index):
        """ Set the playback volume """
        ch, id = self.alsa_channels[card_index][channel]
        mixer = alsa.Mixer(ch, id, card_index)
        try:
            mixer.setvolume(volume[0], 0)
            mixer.setvolume(volume[1], 1)
        except:
            pass

    def get_volume(self, channel, card_index):
        """ Get the current sound card setting for specified channel """
        ch, id = self.alsa_channels[card_index][channel]
        mixer = alsa.Mixer(ch, id, card_index)
        vol = mixer.getvolume()
        if len(vol) == 1:
            return (vol[0], vol[0])
        return (vol[0], vol[1])

    def on_select_controls(self, widget=None):
        card_index = self.notebook.get_current_page()
        dialog = SelectControls(self, self.cp, card_index)

    def show_hide_controls(self, card_index):
        controls = self.card_hbox[card_index].get_children()
        for control in controls:
            if self.control_mask[card_index] & (1 << control.channel):
                control.show()
            else:
                control.hide()

    def write_config(self):
        for card_index, card_name in enumerate(self.acards):
            section = "card-%d" % card_index
            if not self.cp.has_section(section):
                self.cp.add_section(section)
            self.cp.set(section, "mask_lock", self.lock_mask[card_index])
        self.cp.write(open(CONFIG_FILE, "w"))

    def quit(self, element=None, event=None):
        """ Exit main loop """
        self.write_config()
        Gtk.main_quit()
Esempio n. 60
0
class SFLvaultConfig(object):
    """This object deals with everything configuration.

    It handles the aliases adding/removal and talks with other systems
    through Exceptions.

    It handles the keyring support and passwords management

    """
    def __init__(self, config_file):
        self.config_file = os.path.expanduser(config_file)
        self.config_check()
        self.config_read()
        
        
    def config_check(self):
        """Checks for ownership and modes for all paths and files, à-la SSH"""
        fullfile = self.config_file
        fullpath = os.path.dirname(self.config_file)
    
        if not os.path.exists(fullpath):
            os.makedirs(fullpath, mode=0700)

        if not os.stat(fullpath)[0] & 0700:
            ### TODO: RAISE EXCEPTION INSTEAD
            print "Modes for %s must be 0700 (-rwx------)" % fullpath
            sys.exit()

        if not os.path.exists(fullfile):
            fp = open(fullfile, 'w')
            fp.write("[SFLvault]\n")
            fp.close()
            os.chmod(fullfile, 0600)
        
        if not os.stat(fullfile)[0] & 0600:
            # TODO: raise exception instead.
            print "Modes for %s must be 0600 (-rw-------)" % fullfile
            sys.exit()

    def config_read(self):
        """Return the ConfigParser object, fully loaded"""    
        self.cfg = ConfigParser()
        fp = open(self.config_file, 'r')
        self.cfg.readfp(fp)
        fp.close()

        if not self.cfg.has_section('SFLvault'):
            self.cfg.add_section('SFLvault')

        if not self.cfg.has_section('Aliases'):
            self.cfg.add_section('Aliases')

        if not self.cfg.has_option('SFLvault', 'username'):
            self.cfg.set('SFLvault', 'username', '')
    
        if not self.cfg.has_option('SFLvault', 'url'):
            self.cfg.set('SFLvault', 'url', '')

    def config_write(self):
        """Write the ConfigParser element to disk."""
        fp = open(self.config_file, 'w')
        self.cfg.write(fp)
        fp.close()

    # Fake being the actual ConfigParser object
    def get(self, *args, **kwargs):
        return self.cfg.get(*args, **kwargs)
    def set(self, *args, **kwargs):
        return self.cfg.set(*args, **kwargs)
    def has_option(self, *args, **kwargs):
        return self.cfg.has_option(*args, **kwargs)

    def alias_add(self, alias, ptr):
        """Add an alias and save config."""
        tid = re.match(r'(.)#(\d+)', ptr)
        if not tid:
            raise ValueError("VaultID must be in the format: (.)#(\d+)")

        # Set the alias value
        self.cfg.set('Aliases', alias, ptr)
        # Save config.
        self.config_write()
        return True

    def alias_del(self, alias):
        """Remove an alias from the config.

        :rtype: True if removed, False otherwise.
        """
        if self.cfg.has_option('Aliases', alias):
            self.cfg.remove_option('Aliases', alias)
            self.config_write()
            return True
        else:
            return False

    def alias_list(self):
        """Return a list of aliases

        :rtype: list of (alias, value) pairs.
        """
        return self.cfg.items('Aliases')

    def alias_get(self, alias):
        """Return the pointer for a given alias"""
        if not self.cfg.has_option('Aliases', alias):
            return None
        else:
            return self.cfg.get('Aliases', alias)


    def _check_keyring(self):
        try:
            import keyring
        except ImportError, e:
            raise KeyringError("No keyring support, please install python-keyring")