Enforce some structure to the config file
183081
def _validate(self):
        
        # This could be done with a default config

        # Check that specific keys exist
        sections = odict([
                ('catalog',['dirname','basename',
                            'lon_field','lat_field','objid_field',
                            'mag_1_band', 'mag_1_field', 'mag_err_1_field',
                            'mag_2_band', 'mag_2_field', 'mag_err_2_field',
                            ]),
                ('mask',[]),
                ('coords',['nside_catalog','nside_mask','nside_likelihood',
                           'nside_pixel','roi_radius','roi_radius_annulus',
                           'roi_radius_interior','coordsys',
                           ]),
                ('likelihood',[]),
                ('output',[]),
                ('batch',[]),
                ])  

        keys = np.array(list(sections.keys()))
        found = np.in1d(keys,list(self.keys()))

        if not np.all(found):
            msg = 'Missing sections: '+str(keys[~found])
            raise Exception(msg)

        for section,keys in sections.items():
            keys = np.array(keys)
            found = np.in1d(keys,list(self[section].keys()))
            if not np.all(found):
                msg = 'Missing keys in %s: '%(section)+str(keys[~found])
                raise Exception(msg)
563084
private function overwriteConfig()
    {
        foreach (array_keys($this->config()) as $config) {
            $this->config = $config;

            $this->configToEnv();
        }
    }
937300
private void overrideConfigFromFile(Configuration config) throws IOException {
    String configFile = GCS_CONFIG_OVERRIDE_FILE.get(config, config::get);
    if (configFile != null) {
      config.addResource(new FileInputStream(configFile));
    }
  }
556867
public static function ensureDefines()
    {
        if (defined('DIR_CORE')) {
            return;
        }
        
        // Define directory basenames
        define("DIR_PUBLIC_BASENAME", "public/");
        define("DIR_LIBS_BASENAME", "libs/");
        define("DIR_ADDONS_BASENAME", "addons/");
        define("DIR_DATA_BASENAME", "data/");
        define("DIR_CONTENT_BASENAME", "content/");
        define("DIR_CONFIG_BASENAME", "config/");
        define("DIR_TEMPLATES_BASENAME", "templates/");
        define("DIR_LOCALE_BASENAME", "locale/");
        
        // Define directories
        define(Xentriq::CONST_DIR_ASSUMED_ROOT, dirname(DIR_PUBLIC) . '/', false);
        
        define(Xentriq::CONST_DIR_CORE, dirname(__FILE__) . '/', false);
        define(Xentriq::CONST_DIR_LIBS, str_replace(DIR_PUBLIC_BASENAME, DIR_LIBS_BASENAME, DIR_PUBLIC) . '/');
        define(Xentriq::CONST_DIR_ADDONS, str_replace(DIR_PUBLIC_BASENAME, DIR_ADDONS_BASENAME, DIR_PUBLIC) . '/', false);
        define("DIR_DATA", str_replace(DIR_PUBLIC_BASENAME, DIR_DATA_BASENAME, DIR_PUBLIC) . '/', false);
        define("DIR_CONTENT", str_replace(DIR_PUBLIC_BASENAME, DIR_CONTENT_BASENAME, DIR_PUBLIC) . '/', false);
        define("DIR_CONFIG", str_replace(DIR_PUBLIC_BASENAME, DIR_CONFIG_BASENAME, DIR_PUBLIC) . '/', false);
        
        define("DIR_TEMPLATES", DIR_CONTENT . DIR_TEMPLATES_BASENAME);
        
        define("DIR_LOCALE", DIR_CORE . DIR_LOCALE_BASENAME);
        define("DIR_LOCALE_PROJECT", DIR_CONTENT . DIR_LOCALE_BASENAME);
        
        // Define extensions
        define("EXT_PAGE", ".xpage");
        define("EXT_PART", ".xpart");
        define("TEMPLATE_INDEX", 'index.xpage');
        
        define("EXT_CSS", ".css");
        define("EXT_SCSS", ".scss");
        define("EXT_SASS", ".sass");
        define("EXT_JS", ".js");
        define("EXT_PHP", ".php");
        define("EXT_XML", ".xml");
        define("EXT_JSON", ".json");
        define("EXT_AUTH", ".auth");
        
        // Define characters
        define("CHAR_SPACE", ' ');
        define("CHAR_CRLF", "\r\n");
        define("CHAR_SLASH", '/');
        define("CHAR_BACKSLASH", '\\');
        define("CHAR_OB", '[');
        define("CHAR_CB", ']');
        define("CHAR_OCB", '(');
        define("CHAR_CCB", ')');
        define("CHAR_OSB", '{');
        define("CHAR_CSB", '}');
        define("CHAR_SEMICOLON", ';');
        define("CHAR_QUOTE", '\'');
        define("CHAR_DOUBLE_QUOTE", '"');
        define("CHAR_BACKTICK", '`');
        
        define("GZIP_SUPPORTED", (substr_count(ArrayUtils::getArrayValueForKeyOrDefault($_SERVER, 'HTTP_ACCEPT_ENCODING', ''), 'gzip') > 0));
        
        // Define environment, defaults to `default`
        define("XENTRIQ_ENVIRONMENT", Utils::getEnvironmentVariable("XENTRIQ_ENVIRONMENT", "default"));
        
        // Define base DEBUG value to ensure proper output.
        define(Xentriq::CONST_DEBUG, Utils::getEnvironmentVariable(Xentriq::CONST_DEBUG, false), true);
        
        // Try to load configuration values from JSON configuration
        define(Xentriq::CONST_DEBUG, Config::getConfigurationValue('debug'));
        
        define("INDEX_FILE", 'index.php');
        define("USE_INDEX_FILE", Config::getConfigurationValueOrDefault('useIndexPhp', false));
        
        define("DISABLE_GZIP", Config::getConfigurationValueOrDefault('disableGzip', false));
        
        define("DISABLE_DEFAULT_RESPONSE_HEADERS", Config::getConfigurationValueOrDefault('disableDefaultResponseHeaders', false));
        
        define("URL_SITE", Request::getSiteUrl());
    }
1276344
function buildConfig( wantedEnv )
{

    const isValid = wantedEnv &&
        wantedEnv.length > 0 && allowedEnvs.indexOf( wantedEnv ) !== -1;
    const validEnv = isValid ? wantedEnv : 'dev';

    return configs[ validEnv ];
}
828398
public function set_config() {

		foreach ( $this->struct['config'] as $key => $setting ) {
			$this->attributes[ 'data-' . $key ] = $setting;
		}

	}
1263691
def override(config, option, escape=false, &blk)
      # override if given on the command line
      if opt = input[option]
        opt = CFMicro.escape_path(opt) if escape
        config[option] = opt
      end
      config[option] = yield unless config[option]
    end
1237853
def conf_files(self):
        
        for attr in dir(self):
            field = getattr(self, attr)
            if isinstance(field, ConfFile):
                yield field
1021186
def enforce_git_config(self):
        '''
        
        '''
        git_config = os.path.join(self.gitdir, 'config')
        conf = salt.utils.configparser.GitConfigParser()
        if not conf.read(git_config):
            log.error('Failed to read from git config file %s', git_config)
        else:
            # We are currently enforcing the following git config items:
            # 1. Fetch URL
            # 2. refspecs used in fetch
            # 3. http.sslVerify
            conf_changed = False
            remote_section = 'remote "origin"'

            # 1. URL
            try:
                url = conf.get(remote_section, 'url')
            except salt.utils.configparser.NoSectionError:
                # First time we've init'ed this repo, we need to add the
                # section for the remote to the git config
                conf.add_section(remote_section)
                conf_changed = True
                url = None
            log.debug(
                'Current fetch URL for %s remote \'%s\': %s (desired: %s)',
                self.role, self.id, url, self.url
            )
            if url != self.url:
                conf.set(remote_section, 'url', self.url)
                log.debug(
                    'Fetch URL for %s remote \'%s\' set to %s',
                    self.role, self.id, self.url
                )
                conf_changed = True

            # 2. refspecs
            try:
                refspecs = sorted(
                    conf.get(remote_section, 'fetch', as_list=True))
            except salt.utils.configparser.NoOptionError:
                # No 'fetch' option present in the remote section. Should never
                # happen, but if it does for some reason, don't let it cause a
                # traceback.
                refspecs = []
            desired_refspecs = sorted(self.refspecs)
            log.debug(
                'Current refspecs for %s remote \'%s\': %s (desired: %s)',
                self.role, self.id, refspecs, desired_refspecs
            )
            if refspecs != desired_refspecs:
                conf.set_multivar(remote_section, 'fetch', self.refspecs)
                log.debug(
                    'Refspecs for %s remote \'%s\' set to %s',
                    self.role, self.id, desired_refspecs
                )
                conf_changed = True

            # 3. http.sslVerify
            try:
                ssl_verify = conf.get('http', 'sslVerify')
            except salt.utils.configparser.NoSectionError:
                conf.add_section('http')
                ssl_verify = None
            except salt.utils.configparser.NoOptionError:
                ssl_verify = None
            desired_ssl_verify = six.text_type(self.ssl_verify).lower()
            log.debug(
                'Current http.sslVerify for %s remote \'%s\': %s (desired: %s)',
                self.role, self.id, ssl_verify, desired_ssl_verify
            )
            if ssl_verify != desired_ssl_verify:
                conf.set('http', 'sslVerify', desired_ssl_verify)
                log.debug(
                    'http.sslVerify for %s remote \'%s\' set to %s',
                    self.role, self.id, desired_ssl_verify
                )
                conf_changed = True

            # Write changes, if necessary
            if conf_changed:
                with salt.utils.files.fopen(git_config, 'w') as fp_:
                    conf.write(fp_)
                    log.debug(
                        'Config updates for %s remote \'%s\' written to %s',
                        self.role, self.id, git_config
                    )
287543
protected function configure()
    {
        $this->analyser->setDirectory(WORKING_DIRECTORY);
        $this->setName('validate');
        $description = 'Validates the .gitattributes file of a given '
            . 'project/micro-package repository';
        $this->setDescription($description);

        $directoryDescription = 'The directory of a project/micro-package repository';

        $this->addArgument(
            'directory',
            InputArgument::OPTIONAL,
            $directoryDescription,
            $this->analyser->getDirectory()
        );

        $createDescription = 'Create a .gitattributes file if not present';
        $enforceStrictOrderDescription = 'Enforce a strict order comparison of '
            . 'export-ignores in the .gitattributes file';
        $enforceExportIgnoreAligmentDescription = 'Enforce a strict alignment of '
            . 'export-ignores in the .gitattributes file';
        $overwriteDescription = 'Overwrite existing .gitattributes file '
            . 'with missing export-ignores';
        $validateArchiveDescription = 'Validate Git archive against current HEAD';

        $exampleGlobPattern = '{.*,*.md}';
        $globPatternDescription = 'Use this glob pattern e.g. <comment>'
            . $exampleGlobPattern . '</comment> to match artifacts which should be '
            . 'export-ignored';
        $globPatternFileDescription = 'Use this file with glob patterns '
            . 'to match artifacts which should be export-ignored';

        $keepLicenseDescription = 'Do not export-ignore license file';

        $alignExportIgnoresDescription = 'Align export-ignores on create or overwrite';

        $this->addOption('create', 'c', InputOption::VALUE_NONE, $createDescription);
        $this->addOption(
            'enforce-strict-order',
            null,
            InputOption::VALUE_NONE,
            $enforceStrictOrderDescription
        );
        $this->addOption(
            'enforce-alignment',
            null,
            InputOption::VALUE_NONE,
            $enforceExportIgnoreAligmentDescription
        );

        $this->addOption('overwrite', 'o', InputOption::VALUE_NONE, $overwriteDescription);
        $this->addOption(
            'validate-git-archive',
            null,
            InputOption::VALUE_NONE,
            $validateArchiveDescription
        );
        $this->addOption(
            'glob-pattern',
            null,
            InputOption::VALUE_REQUIRED,
            $globPatternDescription
        );
        $this->addOption(
            'glob-pattern-file',
            null,
            InputOption::VALUE_OPTIONAL,
            $globPatternFileDescription,
            $this->defaultLpvFile
        );
        $this->addOption(
            'keep-license',
            null,
            InputOption::VALUE_NONE,
            $keepLicenseDescription
        );
        $this->addOption(
            'align-export-ignores',
            'a',
            InputOption::VALUE_NONE,
            $alignExportIgnoresDescription
        );
    }
1162232
def set_config(self, **config):
        """"""
        reinit = False
        if 'stdopt' in config:
            stdopt = config.pop('stdopt')
            reinit = (stdopt != self.stdopt)
            self.stdopt = stdopt
        if 'attachopt' in config:
            attachopt = config.pop('attachopt')
            reinit = reinit or (attachopt != self.attachopt)
            self.attachopt = attachopt
        if 'attachvalue' in config:
            attachvalue = config.pop('attachvalue')
            reinit = reinit or (attachvalue != self.attachvalue)
            self.attachvalue = attachvalue
        if 'auto2dashes' in config:
            self.auto2dashes = config.pop('auto2dashes')
        if 'name' in config:
            name = config.pop('name')
            reinit = reinit or (name != self.name)
            self.name = name
        if 'help' in config:
            self.help = config.pop('help')
            self._set_or_remove_extra_handler(
                self.help, ('--help', '-h'), self.help_handler)
        if 'version' in config:
            self.version = config.pop('version')
            self._set_or_remove_extra_handler(
                self.version is not None,
                ('--version', '-v'),
                self.version_handler)
        if 'case_sensitive' in config:
            case_sensitive = config.pop('case_sensitive')
            reinit = reinit or (case_sensitive != self.case_sensitive)
            self.case_sensitive = case_sensitive
        if 'optionsfirst' in config:
            self.options_first = config.pop('optionsfirst')
        if 'appearedonly' in config:
            self.appeared_only = config.pop('appearedonly')
        if 'namedoptions' in config:
            namedoptions = config.pop('namedoptions')
            reinit = reinit or (namedoptions != self.namedoptions)
            self.namedoptions = namedoptions
        if 'extra' in config:
            self.extra.update(self._formal_extra(config.pop('extra')))

        if config:  # should be empty
            raise ValueError(
                '`%s` %s not accepted key argument%s' % (
                    '`, `'.join(config),
                    'is' if len(config) == 1 else 'are',
                    '' if len(config) == 1 else 's'
                ))

        if self.doc is not None and reinit:
            logger.warning(
                'You changed the config that requires re-initialized'
                ' `Docpie` object. Create a new one instead'
            )
            self._init()
654536
def write_config_file(path, config):
    """"""
    contents = json.dumps(config, indent=4, separators=(',', ': ')) + '\n'
    try:
        with open(path, 'w') as f:
            f.write(contents)
        return True
    except IOError as ex:
        if ex != errno.ENOENT:
            raise
    return False
583468
public function doChecks()
    {
        foreach ($this->checks as $check) {
            $method = 'check' . ucfirst($check);
            $this->$method();
        }

        // If the config folder is OK, but the config files are missing, attempt to fix it.
        foreach ($this->configChecks as $check) {
            $this->lowlevelConfigFix($check);
        }
    }
155919
def set_config(config, overwrite=False):
    '''
    
    '''

    if config is None:
        config = get_conf_path_from_env()

    # must be after the fallback other a bad fallback will incorrectly clear
    if overwrite is True:
        _runtime_conf.empty()

    if isinstance(config, six.string_types):
        config = conf_from_file(config)
        _runtime_conf.update(config)
        if config.__file__:
            _runtime_conf.__file__ = config.__file__
    elif isinstance(config, dict):
        _runtime_conf.update(conf_from_dict(config))
    else:
        raise TypeError('%s is neither a dictionary or a string.' % config)
1251298
function initConfig(conf) {
  const result = Object.assign({}, conf);
  if (conf.filename) {
    result.filepath = path.dirname(conf.filename);
  }
  return result;
}
479157
private static String[] adjustConf(String[] argv, Configuration conf) {
    String[] serviceId = new String[] { "" };
    String[] filteredArgv = DFSUtil.getServiceName(argv, serviceId);
    
    if (!serviceId[0].equals("")) {
      NameNode.checkServiceName(conf, serviceId[0]);
      DFSUtil.setGenericConf(conf, serviceId[0],
          NameNode.NAMESERVICE_SPECIFIC_KEYS);
      NameNode.setupDefaultURI(conf);
    }
    
    // make it avatar aware (manual option)
    if (optionExist(argv, "-one")) {
      updateConfKeys(conf, "1", serviceId[0]);
    } else {
      updateConfKeys(conf, "0", serviceId[0]);
    }
    return filteredArgv;
  }
800157
def config_files(override)
      files = []
      if override.stringify_keys.key?('config')
        files = override.stringify_keys.delete('config')
        override.delete('config')
      else
        files << source(override) + File::SEPARATOR + DEFAULT_FILENAME
      end
      files = [files] unless files.is_a? Array
      files
    end