Create config based on /etc/ddsclient.conf and ~/.ddsclient.conf($DDSCLIENT_CONF)
    :param allow_insecure_config_file: bool: when true we will not check ~/.ddsclient permissions.
    :return: Config with the configuration to use for DDSClient.
510897
def create_config(allow_insecure_config_file=False):
    
    config = Config()
    config.add_properties(GLOBAL_CONFIG_FILENAME)
    user_config_filename = get_user_config_filename()
    if user_config_filename == LOCAL_CONFIG_FILENAME and not allow_insecure_config_file:
        verify_file_private(user_config_filename)
    config.add_properties(user_config_filename)
    return config
170518
def get_bitcoind_config(config_file=None, impl=None):
    

    loaded = False

    bitcoind_server = None
    bitcoind_port = None
    bitcoind_user = None
    bitcoind_passwd = None
    bitcoind_timeout = None
    bitcoind_regtest = None
    bitcoind_p2p_port = None
    bitcoind_spv_path = None

    regtest = None

    if config_file is not None:

        parser = SafeConfigParser()
        parser.read(config_file)

        if parser.has_section('bitcoind'):

            if parser.has_option('bitcoind', 'server'):
                bitcoind_server = parser.get('bitcoind', 'server')

            if parser.has_option('bitcoind', 'port'):
                bitcoind_port = int(parser.get('bitcoind', 'port'))

            if parser.has_option('bitcoind', 'p2p_port'):
                bitcoind_p2p_port = int(parser.get('bitcoind', 'p2p_port'))

            if parser.has_option('bitcoind', 'user'):
                bitcoind_user = parser.get('bitcoind', 'user')

            if parser.has_option('bitcoind', 'passwd'):
                bitcoind_passwd = parser.get('bitcoind', 'passwd')

            if parser.has_option('bitcoind', 'spv_path'):
                bitcoind_spv_path = parser.get('bitcoind', 'spv_path')

            if parser.has_option('bitcoind', 'regtest'):
                regtest = parser.get('bitcoind', 'regtest')
            else:
                regtest = 'no'

            if parser.has_option('bitcoind', 'timeout'):
                bitcoind_timeout = float(parser.get('bitcoind', 'timeout'))

            if regtest.lower() in ["yes", "y", "true", "1", "on"]:
                bitcoind_regtest = True
            else:
                bitcoind_regtest = False
            
            loaded = True

    if not loaded:

        bitcoind_server = 'bitcoin.blockstack.com'
        bitcoind_port = 8332
        bitcoind_user = 'blockstack'
        bitcoind_passwd = 'blockstacksystem'
        bitcoind_regtest = False
        bitcoind_timeout = 300
        bitcoind_p2p_port = 8333
        bitcoind_spv_path = os.path.expanduser("~/.virtualchain-spv-headers.dat")

    default_bitcoin_opts = {
        "bitcoind_user": bitcoind_user,
        "bitcoind_passwd": bitcoind_passwd,
        "bitcoind_server": bitcoind_server,
        "bitcoind_port": bitcoind_port,
        "bitcoind_timeout": bitcoind_timeout,
        "bitcoind_regtest": bitcoind_regtest,
        "bitcoind_p2p_port": bitcoind_p2p_port,
        "bitcoind_spv_path": bitcoind_spv_path
    }

    return default_bitcoin_opts
337238
def make_user_config_dir():
    
    config_path = get_user_config_dir()

    if not user_config_dir_exists():
        try:
            os.mkdir(config_path)
            os.mkdir(os.path.join(config_path, 'hooks.d'))
        except OSError:
            return None

    return config_path
538695
def use_file(
    filename: typing.Union[Path, str, None], trust: bool = False
) -> typing.Union[types.ModuleType, None]:
    
    config_file = filename or resolve_path(CONFIG_FILE)

    def preview_unauthorized() -> None:
        if not config_file:
            return None
        print(SEPARATOR, file=sys.stderr)
        with Path(config_file).open("r", encoding="utf-8") as fp:
            for line in fp:
                print(line, end="", file=sys.stderr)
        print(SEPARATOR, file=sys.stderr)

    if config_file and not Path(config_file).exists():
        print_error(f'"{filename}" not found.')
        sys.exit(1)
    if config_file and Path(config_file).exists():
        if not trust:
            with AuthFile.load() as authfile:
                try:
                    authfile.check(Path(config_file))
                except KonchrcChangedError:
                    print_error(f'"{config_file}" has changed since you last used it.')
                    preview_unauthorized()
                    if confirm("Would you like to authorize it?"):
                        authfile.allow(Path(config_file))
                        print()
                    else:
                        sys.exit(1)
                except KonchrcNotAuthorizedError:
                    print_error(f'"{config_file}" is blocked.')
                    preview_unauthorized()
                    if confirm("Would you like to authorize it?"):
                        authfile.allow(Path(config_file))
                        print()
                    else:
                        sys.exit(1)

        logger.info(f"Using {config_file}")
        # Ensure that relative imports are possible
        __ensure_directory_in_path(Path(config_file))
        mod = None
        try:
            mod = imp.load_source("konchrc", str(config_file))
        except UnboundLocalError:  # File not found
            pass
        else:
            return mod
    if not config_file:
        print_warning("No konch config file found.")
    else:
        print_warning(f'"{config_file}" not found.')
    return None
908327
def WriteConfig(self, config_file=None):
    
    config_file = config_file or self.config_file
    config_name = os.path.splitext(os.path.basename(config_file))[0]
    config_lock = (
        '%s/lock/google_%s.lock' % (constants.LOCALSTATEDIR, config_name))
    with file_utils.LockFile(config_lock):
      with open(config_file, 'w') as config_fp:
        if self.config_header:
          self._AddHeader(config_fp)
        self.config.write(config_fp)
456893
def _make_config(config):
        """"""
        # The SBC config encoding is taken from a2dp_codecs.h, in particular,
        # the a2dp_sbc_t type is converted into a 4-byte array:
        #   uint8_t channel_mode:4
        #   uint8_t frequency:4
        #   uint8_t allocation_method:2
        #   uint8_t subbands:2
        #   uint8_t block_length:4
        #   uint8_t min_bitpool
        #   uint8_t max_bitpool
        return dbus.Array([dbus.Byte(config.channel_mode |
                                     (config.frequency << 4)),
                           dbus.Byte(config.allocation_method |
                                     (config.subbands << 2) |
                                     (config.block_length << 4)),
                           dbus.Byte(config.min_bitpool),
                           dbus.Byte(config.max_bitpool)])
883659
def create_file_api(conf):
    
    api_key = conf.config.get('api-key', os.environ.get('SMARTLING_API_KEY'))
    project_id = conf.config.get('project-id', os.environ.get('SMARTLING_PROJECT_ID'))

    if not project_id or not api_key:
        raise SmarterlingError('config.api-key and config.project-id are required configuration items')
    proxy_settings=None
    if conf.config.has_key('proxy-settings'):
        proxy_settings = ProxySettings(
            conf.config.get('proxy-settings').get('username', ''),
            conf.config.get('proxy-settings').get('password', ''),
            conf.config.get('proxy-settings').get('host', ''),
            int(conf.config.get('proxy-settings').get('port', '80')))
    return SmartlingFileApiFactory().getSmartlingTranslationApi(
        not conf.config.get('sandbox', False),
        api_key,
        project_id,
        proxySettings=proxy_settings)
205517
def create_config_files(ctx, opts, api_key):
    """"""
    # pylint: disable=unused-argument
    config_reader = opts.get_config_reader()
    creds_reader = opts.get_creds_reader()
    has_config = config_reader.has_default_file()
    has_creds = creds_reader.has_default_file()

    if has_config and has_creds:
        create = False
    else:
        click.echo()
        create = click.confirm(
            "No default config file(s) found, do you want to create them?"
        )

    click.echo()
    if not create:
        click.secho(
            "For reference here are your default config file locations:", fg="yellow"
        )
    else:
        click.secho(
            "Great! Let me just create your default configs for you now ...", fg="green"
        )

    configs = (
        ConfigValues(reader=config_reader, present=has_config, mode=None, data={}),
        ConfigValues(
            reader=creds_reader,
            present=has_creds,
            mode=stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IWGRP,
            data={"api_key": api_key},
        ),
    )

    has_errors = False
    for config in configs:
        click.echo(
            "%(name)s config file: %(filepath)s ... "
            % {
                "name": click.style(config.reader.config_name.capitalize(), bold=True),
                "filepath": click.style(
                    config.reader.get_default_filepath(), fg="magenta"
                ),
            },
            nl=False,
        )

        if not config.present and create:
            try:
                ok = config.reader.create_default_file(
                    data=config.data, mode=config.mode
                )
            except (OSError, IOError) as exc:
                ok = False
                error_message = exc.strerror
                has_errors = True

            if ok:
                click.secho("CREATED", fg="green")
            else:
                click.secho("ERROR", fg="red")
                click.secho(
                    "The following error occurred while trying to "
                    "create the file: %(message)s"
                    % {"message": click.style(error_message, fg="red")}
                )
            continue

        click.secho("EXISTS" if config.present else "NOT CREATED", fg="yellow")

    return create, has_errors
644165
def create_config_file(filename):
    
    import textwrap
    from six.moves.urllib import parse

    if not os.path.exists(filename):
        old_default_config_file = os.path.join(os.path.dirname(filename),
                                               '.tksrc')
        if os.path.exists(old_default_config_file):
            upgrade = click.confirm("\n".join(textwrap.wrap(
                "It looks like you recently updated Taxi. Some "
                "configuration changes are required. You can either let "
                "me upgrade your configuration file or do it "
                "manually.")) + "\n\nProceed with automatic configuration "
                "file upgrade?", default=True
            )

            if upgrade:
                settings = Settings(old_default_config_file)
                settings.convert_to_4()
                with open(filename, 'w') as config_file:
                    settings.config.write(config_file)
                os.remove(old_default_config_file)
                return
            else:
                print("Ok then.")
                sys.exit(0)

        welcome_msg = "Welcome to Taxi!"
        click.secho(welcome_msg, fg='green', bold=True)
        click.secho('=' * len(welcome_msg) + '\n', fg='green', bold=True)

        click.echo(click.wrap_text(
            "It looks like this is the first time you run Taxi. You will need "
            "a configuration file ({}) in order to proceed. Please answer a "
            "few questions to create your configuration file.".format(
                filename
            )
        ) + '\n')

        config = pkg_resources.resource_string('taxi', 'etc/taxirc.sample').decode('utf-8')
        context = {}
        available_backends = plugins_registry.get_available_backends()

        context['backend'] = click.prompt(
            "Backend you want to use (choices are %s)" %
            ', '.join(available_backends),
            type=click.Choice(available_backends)
        )
        context['username'] = click.prompt("Username or token")
        context['password'] = parse.quote(
            click.prompt("Password (leave empty if you're using"
                         " a token)", hide_input=True, default=''),
            safe=''
        )
        # Password can be empty in case of token auth so the ':' separator
        # is not included in the template config, so we add it if the user
        # has set a password
        if context['password']:
            context['password'] = ':' + context['password']

        context['hostname'] = click.prompt(
            "Hostname of the backend (eg. timesheets.example.com)",
            type=Hostname()
        )

        editor = Editor().get_editor()
        context['editor'] = click.prompt(
            "Editor command to edit your timesheets", default=editor
        )

        templated_config = config.format(**context)

        directory = os.path.dirname(filename)
        if not os.path.exists(directory):
            os.makedirs(directory)

        with open(filename, 'w') as f:
            f.write(templated_config)
    else:
        settings = Settings(filename)
        conversions = settings.needed_conversions

        if conversions:
            for conversion in conversions:
                conversion()

            settings.write_config()
699131
def create_config_file(self, vmdk_location, description):
        
        description = description
        format = "vmdk"
        user_bucket = {
            "S3Bucket": self.bucket_name,
            "S3Key": vmdk_location
        }
        parent_obj = {'Description': description, 'Format': format, 'UserBucket': user_bucket}
        obj_list = [parent_obj]

        temp_fd, temp_file = tempfile.mkstemp()
        print 'creating tmp file for {} at {}'.format(vmdk_location, temp_file)

        with os.fdopen(temp_fd, 'w') as f:
            json.dump(obj_list, f)
        return temp_fd, temp_file
154316
def load_config(configfile):
    

    configfile = os.path.abspath(configfile)
    config = configobj.ConfigObj(configfile)

    config_extension = '.conf'

    #########################################################################
    # Load up other config files
    #########################################################################

    if 'configs' in config:
        config_extension = config['configs'].get('extension', config_extension)

        # Load other configs
        if 'path' in config['configs']:
            for cfgfile in os.listdir(config['configs']['path']):
                cfgfile = os.path.join(config['configs']['path'],
                                       cfgfile)
                cfgfile = os.path.abspath(cfgfile)
                if not cfgfile.endswith(config_extension):
                    continue
                newconfig = configobj.ConfigObj(cfgfile)
                config.merge(newconfig)

    #########################################################################

    if 'server' not in config:
        raise Exception('Failed to load config file %s!' % configfile)

    #########################################################################
    # Load up handler specific configs
    #########################################################################

    if 'handlers' not in config:
        config['handlers'] = configobj.ConfigObj()

    if 'handlers_config_path' in config['server']:
        handlers_config_path = config['server']['handlers_config_path']
        if os.path.exists(handlers_config_path):
            for cfgfile in os.listdir(handlers_config_path):
                cfgfile = os.path.join(handlers_config_path, cfgfile)
                cfgfile = os.path.abspath(cfgfile)
                if not cfgfile.endswith(config_extension):
                    continue
                filename = os.path.basename(cfgfile)
                handler = os.path.splitext(filename)[0]

                if handler not in config['handlers']:
                    config['handlers'][handler] = configobj.ConfigObj()

                newconfig = configobj.ConfigObj(cfgfile)
                config['handlers'][handler].merge(newconfig)

    #########################################################################
    # Load up Collector specific configs
    #########################################################################

    if 'collectors' not in config:
        config['collectors'] = configobj.ConfigObj()

    if 'collectors_config_path' in config['server']:
        collectors_config_path = config['server']['collectors_config_path']
        if os.path.exists(collectors_config_path):
            for cfgfile in os.listdir(collectors_config_path):
                cfgfile = os.path.join(collectors_config_path, cfgfile)
                cfgfile = os.path.abspath(cfgfile)
                if not cfgfile.endswith(config_extension):
                    continue
                filename = os.path.basename(cfgfile)
                collector = os.path.splitext(filename)[0]

                if collector not in config['collectors']:
                    config['collectors'][collector] = configobj.ConfigObj()

                try:
                    newconfig = configobj.ConfigObj(cfgfile)
                except Exception as e:
                    raise Exception("Failed to load config file %s due to %s" %
                                    (cfgfile, e))

                config['collectors'][collector].merge(newconfig)

    # Convert enabled to a bool
    for collector in config['collectors']:
        if 'enabled' in config['collectors'][collector]:
            config['collectors'][collector]['enabled'] = str_to_bool(
                config['collectors'][collector]['enabled']
            )

    #########################################################################

    return config
953601
def configure(self):
        
        root = ElementTree.Element("dict")
        print ("It seems like you do not have a preferences file configured. "
               "Please answer the following questions to generate a plist at "
               "%s for use with python-jss." % self.preferences_file)

        self.url = _get_user_input(
            "The complete URL to your JSS, with port (e.g. "
            "'https://mycasperserver.org:8443')\nURL: ", "jss_url", root)

        self.user = _get_user_input("API Username: ", "jss_user", root)

        self.password = _get_user_input("API User's Password: ", "jss_pass",
                                        root, getpass.getpass)

        verify_prompt = ("Do you want to verify that traffic is encrypted by "
                         "a certificate that you trust?: (Y|N) ")
        self.verify = _get_user_input(verify_prompt, "verify", root,
                                      loop_until_valid_response)

        self._handle_repos(root)

        self._write_plist(root)
        print "Preferences created.\n"
503034
def _validate_config(config_path):
    '''
    
    '''
    log.debug('Checking configuration file: %s', config_path)

    if not os.path.isfile(config_path):
        message = 'Unable to get configuration file: {}'.format(config_path)
        log.error(message)
        raise SaltInvocationError(message)
    log.debug('Found configuration file: %s', config_path)
23125
function addUserSSLConfig(config) {
  if (config.https === true) {
    try {
      config.https = {
        cert: readFileSync(getSSLPath(config.host, SERVER_CERT_FILENAME)),
        key: readFileSync(getSSLPath(config.host, SERVER_KEY_FILENAME))
      };
    } catch (e) {}
  }

  return config;
}
502102
def get_client_settings_config_file(**kwargs):  # pylint: disable=inconsistent-return-statements
    
    config_files = ['/etc/softlayer.conf', '~/.softlayer']
    if kwargs.get('config_file'):
        config_files.append(kwargs.get('config_file'))
    config_files = [os.path.expanduser(f) for f in config_files]
    config = utils.configparser.RawConfigParser({
        'username': '',
        'api_key': '',
        'endpoint_url': '',
        'timeout': '0',
        'proxy': '',
    })
    config.read(config_files)

    if config.has_section('softlayer'):
        return {
            'endpoint_url': config.get('softlayer', 'endpoint_url'),
            'timeout': config.getfloat('softlayer', 'timeout'),
            'proxy': config.get('softlayer', 'proxy'),
            'username': config.get('softlayer', 'username'),
            'api_key': config.get('softlayer', 'api_key'),
        }
372683
def check_config(filename):
    
    conf = configparser.SafeConfigParser(allow_no_value=False)
    conf.read(filename)
    try:
        server = conf.get('global', 'server')
    except configparser.NoSectionError:
        server = False
    except configparser.NoOptionError:
        server = False
    try:
        username = conf.get('auth', 'username')
    except configparser.NoSectionError:
        username = False
    except configparser.NoOptionError:
        username = False
    try:
        password = conf.get('auth', 'password')
    except configparser.NoSectionError:
        password = False
    except configparser.NoOptionError:
        password = False
    try:
        auto_update_soa = conf.get('global', 'soa_update')
    except configparser.NoSectionError:
        auto_update_soa = False
    except configparser.NoOptionError:
        auto_update_soa = False

    return server, username, password, auto_update_soa
637391
def create_config_files(directory):
    
    # Some constant strings
    vpn_gate_url = "http://www.vpngate.net/api/iphone/"

    if not os.path.exists(directory):
        os.makedirs(directory)

    # get csv into memory
    csv_str = ""
    logging.info("Downloading info from VPN Gate API...")
    r = requests.get(vpn_gate_url)
    for line in r.text.split('\n'):
        csv_str += line.encode('utf-8')
        csv_str += "\n"

    # convert csv string to string IO
    f = StringIO.StringIO(csv_str)

    # generate vpn dict
    vpn_dict = {}
    reader = csv.reader(f)
    reader.next()
    reader.next()
    for row in reader:
        if len(row) == 15:
            alpha2 = row[6]
            vpn_dict[alpha2] = vpn_dict.get(alpha2, [])
            vpn_dict[alpha2].append({
                "vpn_name": row[0],
                "ip": row[1],
                "country_name": row[5],
                "alpha2": alpha2,
                "openvpn_config": b64decode(row[-1])
            })
    f.close()

    server_country = {}

    # write config files
    for country in vpn_dict:
        for data in vpn_dict[country]:
            config_filename = "{}.ovpn".format(data['ip'])
            file_path = os.path.join(directory, config_filename)
            with open(file_path, 'w') as f:
                f.write(data['openvpn_config'])
                f.write("up /etc/openvpn/update-resolv-conf\n")
                f.write("down /etc/openvpn/update-resolv-conf\n")

            server_country[data['ip']] = country

    with open(os.path.join(directory, 'servers.txt'), 'w') as f:
        for ip in server_country:
            f.write('|'.join([ip, server_country[ip]]) + '\n')