I save the config, and run check_config, potencially returning errors
546417
def saveConfig(self, request):
        """"""
        res = yield self.assertAllowed(request)
        if res:
            defer.returnValue(res)
        request.setHeader('Content-Type', 'application/json')
        if self._in_progress:
            defer.returnValue(json.dumps({'success': False, 'errors': ['reconfig already in progress']}))
        self._in_progress = True
        cfg = json.loads(request.content.read())
        if cfg != self._cfg:
            try:
                err = yield self.saveCfg(cfg)
            except Exception as e:  # noqa
                err = [repr(e)]
            if err is not None:
                self._in_progress = False
                yield self.saveCfg(self._cfg)
                defer.returnValue(json.dumps({'success': False, 'errors': err}))

        yield self.ep.master.reconfig()
        defer.returnValue(json.dumps({'success': True}))
988370
function (is_ignore_errors, opt_config_filename) {

		var self = this;

		var config_paths = [];
		if (opt_config_filename) {
			config_paths.push(opt_config_filename);
		} else {
			// root of dependence source directory
			config_paths.push('./config.json');
			// root of denhub-device directory
			config_paths.push(__dirname + '/../config.json');
		}

		var config_file = null;
		for (var i = 0, l = config_paths.length; i < l; i++) {
			try {
				config_file = require('fs').readFileSync(config_paths[i]);
			} catch (e) {
				continue;
			}
			if (config_file) break;
		}

		if (!config_file && !is_ignore_errors) {
			console.log(colors.bold.red('Error: Could not read the configuration file.'));
			console.log(config_paths.join('\n'));
			console.log(colors.bold('If you never created it, please try the following command:'));
			console.log('$ denhub-device-generator init\n');
			process.exit(255);
		}

		var config = {};
		if (config_file) {
			try {
				config = JSON.parse(config_file.toString());
			} catch (e) {
				if (!is_ignore_errors) throw e;
			}
		}

		config.commands = self._getLocalCommands(is_ignore_errors) || null;

		return config;

	}
220436
def save(dir = Dir.pwd, config = {}, type = :local, options = {})
      conffile = config_file(dir, type, options)
      confdir  = File.dirname( conffile )
      unless File.directory?( confdir )
        warning "about to create the configuration directory #{confdir}"
        really_continue?  unless options[:no_interaction]
        run %( mkdir -p #{confdir} )
      end
      store_config(conffile, config, options)
    end
556708
def report_parsing_problems(parsing_out):
    """"""
    _, empty, faulty = parsing_out
    if CONFIG_FILE in empty or CONFIG_FILE in faulty:
        print('Unable to read global config file', CONFIG_FILE,
              file=sys.stderr)
        print('Please run stagpy config --create',
              sep='\n', end='\n\n', file=sys.stderr)
    if CONFIG_LOCAL in faulty:
        print('Unable to read local config file', CONFIG_LOCAL,
              file=sys.stderr)
        print('Please run stagpy config --create_local',
              sep='\n', end='\n\n', file=sys.stderr)
943750
def config_sanity_check(self):
        
        if 'name' not in self.config:
            raise EventifyConfigError(
                """Required configuration parameter missing!
                Please configure "name" as a string in your
                configuration.""")

        if 'publish_topic' not in self.config:
            raise EventifyConfigError(
                """Required configuration parameter missing!
                Please configure "public_topic" as an object
                in your configuration.""")

        if 'topic' not in self.config['publish_topic']:
            raise EventifyConfigError(
                """Required configuration parameter missing!
                Please configure "topic" as a key in your
                "public_topic object.""")
802517
def check_config(self, section, name, has_default=False, value=None, allowEmpty=False):
    
    

    cfg = self.config
    if not cfg.has_key(section) or not cfg.get(section).has_key(name):
      if not has_default:
        self.config_errors.append("%s: %s -> missing" % (section, name))
        return False
      else:
        return True

    v = cfg.get(section).get(name)

    if v == "" and not allowEmpty:
      self.config_errors.append("%s: %s -> empty" % (section, name))
      return False
    return True
314504
def check_config():
    
    configfile = ConfigFile()
    global data
    if data.keys() > 0:
        # FIXME: run a better check of this file
        print("gitberg config file exists")
        print("\twould you like to edit your gitberg config file?")
    else:
        print("No config found")
        print("\twould you like to create a gitberg config file?")
    answer = input("-->  [Y/n]")
    # By default, the answer is yes, as denoted by the capital Y
    if not answer:
        answer = 'Y'

    # If yes, generate a new configuration
    # to be written out as yaml

    if answer in 'Yy':
        print("Running gitberg config generator ...")
        # config.exists_or_make()
        config_gen = ConfigGenerator(current=data)
        config_gen.ask()
        # print(config_gen.answers)
        data = config_gen.answers
        configfile.write()
        print("Config written to {}".format(configfile.file_path))
1194804
def _check_config():
    """"""
    config.CONFIG_DIR.mkdir(parents=True, exist_ok=True)
    verfile = config.CONFIG_DIR / '.version'
    uptodate = verfile.is_file() and verfile.read_text() == __version__
    if not uptodate:
        verfile.write_text(__version__)
    if not (uptodate and config.CONFIG_FILE.is_file()):
        conf.create_config_(update=True)
    for stfile in ('stagpy-paper.mplstyle',
                   'stagpy-slides.mplstyle'):
        stfile_conf = config.CONFIG_DIR / stfile
        if not (uptodate and stfile_conf.is_file()):
            stfile_local = pathlib.Path(__file__).parent / stfile
            shutil.copy(str(stfile_local), str(stfile_conf))
109172
def apply_check_config(self, config):
        
        self.uri = config["uri"]
        self.use_https = config.get("https", False)
        self.method = config.get("method", "GET")
342557
def save(keystorerc=None, keystore=None, files=[], verbose=False):
  ''''''

  config = None
  if keystorerc:
    config = config_reader.read(keystorerc)
    if not config:
      print('No configuration found.', file=sys.stderr)
      sys.exit(-1)
  elif keystore and len(files) > 0:
    config = {
      'keystore': keystore,
      'files': files
    }

  if 'verbose' in config and config['verbose']:
    verbose = True

  keystore_path = None
  if 'keystore' not in config:
    print('.keystorerc needs to specify a keystore file path.', file=sys.stderr)
    sys.exit(-1)

  keystore_path = os.path.expanduser(config['keystore'])
  if os.path.isdir(keystore_path):
    print('keystore cannot be a folder: {}'.format(config['keystore']), file=sys.stderr)
    sys.exit(-1)
  elif not os.path.isfile(keystore_path):
    # If keystore file does not exist already, attempt to create one
    try:
      pathlib.Path(keystore_path).touch()
    except OSError as err:
      print('keystore cannot be accessed: {}\n{}'.format(config['keystore'], err), file=sys.stderr)
      sys.exit(-1)

  # iterate through keys and add them here

  keystore = {}
  try:
    for p in config['files']:

      expanded_path = os.path.expanduser(p)
      path = pathlib.Path(expanded_path)
      if verbose: print('Inspecting {}:'.format(expanded_path))

      if not path.exists():
        print('Error: File or folder does not exist: {}'.format(p), file=sys.stderr)
        sys.exit(-1)
      if path.is_dir():
        for dirpath, dirnames, filenames in os.walk(expanded_path):
          for name in filenames:
            fullpath = os.path.join(dirpath, name)
            if verbose: print('Adding {} ...'.format(fullpath))
            with open(fullpath, 'rb') as keyfile:
              b64_bytes = base64.encodebytes(keyfile.read()).decode('utf-8')
              keystore[fullpath] = b64_bytes
      elif path.is_file():
        fullpath = expanded_path
        if verbose: print('Adding {} ...'.format(fullpath))
        with open(fullpath, 'rb') as keyfile:
          b64_bytes = base64.encodebytes(keyfile.read()).decode('utf-8')
          keystore[fullpath] = b64_bytes

    if verbose: print('Added {} key(s) to keystore.\n'.format(len(keystore)))

    # prompt user for a one-time passphase for encryption

    do_passphrases_match = False
    passphrase = None
    print('This passphrase is used to decrypt your keystore. Please remember it.')
    while not do_passphrases_match:
      passphrase = getpass.getpass('Please enter a passphrase: ')
      passphrase_verify = getpass.getpass('Please verify your passphrase: ')
      do_passphrases_match = passphrase != '' and passphrase == passphrase_verify
      if passphrase == '':
        print('Passphrase cannot be empty.')
      elif not do_passphrases_match:
        print('Passphrases do not match. Please try again.')
    if verbose: print('Passphrase accepted. Encrypting ...')

    # serialise, compress, encrypt

    serial_keystore = json.dumps(keystore)
    compressed_keystore = gzip.compress(serial_keystore.encode('utf-8'))
    try:
      encrypted_keystore = simplecrypt.encrypt(passphrase, compressed_keystore)
    except simplecrypt.EncryptionException as err:
      print('You managed to bump into a very, very rare issue with AES.\nPlease contact the author. {}'.format(err), file=sys.stder)
      sys.exit(-1)

    # save encrypted keystore to file
    keystore_path = os.path.expanduser(keystore_path)
    if verbose: print('Writing to keystore file {}'.format(keystore_path))

    with open(keystore_path, 'wb') as keystore_file:
      keystore_file.write(encrypted_keystore)

    if verbose: print('Keystore successfully created: ')
    # if verbose: print(encrypted_keystore)

  except KeyError as err:
    print('.keystorerc config is missing `files` attribute: {}'.format(err), file=sys.stderr)
    sys.exit(-1)
  except TypeError as err:
    print('Error: {}'.format(err), file=sys.stderr)
    traceback.print_exc()
    sys.exit(-1)
  except OSError as err:
    print('The file system gave an error: {}'.format(err), file=sys.stderr)
    sys.exit(-1)
  except Exception as err:
    print('Serious error. Please report this bug to the author: {}'.format(err), file=sys.stderr)
    sys.exit(-1)
519545
def _install(_):
    
    if not os.path.exists(".git"):
        fatal("not in a git repo.")

    config = __load_config()

    if config.get("checks") is None:
        fatal("global ``checks`` variable missing from configuration.")

    # We try to load all checks to check that they exist NOW.
    for hook in config["checks"]:
        checks = __load_checks(config["checks"][hook])
        # Also verify that they apply to the hooks.
        __verify_checks_for_hook(checks, hook)

    reply = input("This will overwrite your current hooks. "
                  "Proceed [yes/No]? ")
    if reply != "yes":
        raise Exit(0)

    for hook in config["checks"]:
        hook_f = open(os.path.join(".git/hooks/", hook), 'w')
        hook_f.write("""#!/usr/bin/env python
# GENRATED BY GLERBL. DO NOT MODIFY.
from glerbl.__main__ import main


exit(main(["glerbl", "hook", "{0}"]))
""".format(hook))
        os.fchmod(hook_f.fileno(),
                  os.fstat(hook_f.fileno()).st_mode | stat.S_IXUSR)
        hook_f.close()
1317128
def save_config(name, data, base='conf'):
    """"""
    if not os.path.exists(base):
        os.mkdir(base)
    fname = pjoin(base, name+'.json')
    with open(fname, 'w') as f:
        json.dump(data, f, indent=2)
1191791
function checkOpts(config, cb) {
  // jshint eqnull: true

  var prefix = "ragents.createSession(): "

  if (config == null) throw Error(prefix + "config is null")

  if (config.url == null) throw Error(prefix + "config.url is null")
  if (config.key == null) throw Error(prefix + "config.key is null")

  if (null == cb)        throw Error(prefix + "callback is null")
  if (!_.isFunction(cb)) throw Error(prefix + "callback is not a function")
}
1087272
def verify_configs_against_options(self, options):
    
    error_log = []
    for config in self.config.configs():
      for section in config.sections():
        if section == GLOBAL_SCOPE_CONFIG_SECTION:
          scope = GLOBAL_SCOPE
        else:
          scope = section
        try:
          valid_options_under_scope = set(options.for_scope(scope))
        # Only catch ConfigValidationError. Other exceptions will be raised directly.
        except Config.ConfigValidationError:
          error_log.append("Invalid scope [{}] in {}".format(section, config.configpath))
        else:
          # All the options specified under [`section`] in `config` excluding bootstrap defaults.
          all_options_under_scope = (set(config.configparser.options(section)) -
                                     set(config.configparser.defaults()))
          for option in all_options_under_scope:
            if option not in valid_options_under_scope:
              error_log.append("Invalid option '{}' under [{}] in {}".format(option, section, config.configpath))

    if error_log:
      for error in error_log:
        logger.error(error)
      raise Config.ConfigValidationError("Invalid config entries detected. "
                              "See log for details on which entries to update or remove.\n"
                              "(Specify --no-verify-config to disable this check.)")
485524
def check_existence(to_check, name, config_key=None, relative_to=None,
                    allow_undefined=False, allow_not_existing=False,
                    base_key='releaser'):
    """"""
    if allow_undefined and (to_check is None or to_check.lower() == 'none'):
        print("{: <14} -> {}UNDEFINED{}".format(name, WARNING_COLOR,
                                                RESET_COLOR))
        return
    else:
        if config_key is None:
            config_key = "{}.{}".format(base_key, name)
        my_check = Path(to_check).resolve()
        if my_check.exists() and relative_to is not None:
            printed_path = str(my_check.relative_to(relative_to))
            if printed_path != '.':
                printed_path = '.' + os.sep + printed_path
        else:
            printed_path = str(my_check)
        if my_check.exists() or allow_not_existing:
            print("{: <14} -> {}".format(name, printed_path))
            return
        else:
            raise FileNotFoundError("[{}ERROR{}] '{}', as given, doesn't "
                                    "exist. For configuration key '{}', was "
                                    "given: {}".format(ERROR_COLOR, RESET_COLOR,
                                                       name, config_key,
                                                       to_check))
173633
def check_settings!
      required_keys = %w(
        org
        project
      )

      required_keys.each do |key|
        unless Settings.send key
          error = "Config is missing required key '#{key}'. Please add it " \
            "to #{config_path} and try again."
          error += "\n\nFor more info, see https://github.com/jutonz/dctl_rb#required-keys"
          puts Rainbow(error).red
          exit 1
        end
      end
    end
888742
def check_configuration(config):
    '''
    '''
    sections = ('commands', 'parameters', 'pipelines')
    # Check all sections are there and contain dicts
    for section in sections:
        if section not in config:
            error_msg = 'Error: Section {0} is missing.'.format(section)
            raise ConfigurationErrorDietException(error_msg)
        if not isinstance(config[section], dict):
            error_msg = 'Error: Section {0} is malformed.'.format(section)
            raise ConfigurationErrorDietException(error_msg)

    # Check every command has a corresponding parameters entry
    commands_cmds = set(list(config['commands'].keys()))
    parameters_cmds = set(list(config['parameters'].keys()))
    if commands_cmds != parameters_cmds:
        error_msg = ('Every command in commands and parameters section has to '
                     'have a corresponding entry in the other section.')
        raise ConfigurationErrorDietException(error_msg)

    # Check pipelines section contains lists as values and each of them only
    # has entries listed in commands section
    for cmd in config['pipelines']:
        pipeline = config['pipelines'][cmd]
        if not isinstance(pipeline, list):
            error_msg = ('Error: Pipeline {0} is malformed. Values have to '
                         'be a list of command names.').format(cmd)
            raise ConfigurationErrorDietException(error_msg)
        for tool in pipeline:
            if tool not in commands_cmds:
                error_msg = ('Error in pipeline {0}. "{1}" cannot be found '
                             'among commands listed in commands '
                             'section').format(cmd, tool)
                raise ConfigurationErrorDietException(error_msg)