Return a libpq connection string using the variables defined in this file.
508466
def dsn():
    
    configs = {'host': host,
               'port': port,
               'dbname': database,
               'user': user,
               'password': password}
    return ' '.join(['{0}={1}'.format(_[0], _[1]) for _ in configs.items() if _[1] is not None and _[1] != ''])
1039223
def _get_connection(self, key, host='', port='', user='', password='', database_url='', tags=None, use_cached=True):
        ""
        if key in self.dbs and use_cached:
            return self.dbs[key]
        try:
            connect_kwargs = self._get_connect_kwargs(
                host=host, port=port, user=user, password=password, database_url=database_url
            )

            connection = pg.connect(**connect_kwargs)
            connection.set_isolation_level(pg.extensions.ISOLATION_LEVEL_AUTOCOMMIT)

        # re-raise the CheckExceptions raised by _get_connect_kwargs()
        except CheckException:
            raise

        except Exception:
            redacted_url = self._get_redacted_dsn(host, port, user, database_url)
            message = u'Cannot establish connection to {}'.format(redacted_url)

            self.service_check(
                self.SERVICE_CHECK_NAME,
                AgentCheck.CRITICAL,
                tags=self._get_service_checks_tags(host, port, database_url, tags),
                message=message,
            )
            raise

        self.dbs[key] = connection
        return connection
260554
def get_connections(self, id, connection_name, **args):
        """"""
        return self.request(
            "{0}/{1}/{2}".format(self.version, id, connection_name), args
        )
43926
def parse_connection_string_psycopg2(connection_string):
    
    conn_prepared = {}
    conn_parsed = urlparse(connection_string)
    if not conn_parsed.hostname:
        _re_dbstr = re.compile(r'\bhost=(?P<host>[0-9a-zA-Z_.!@#$%^&*()~]+)|'
                               r'dbname=(?P<dbname>[0-9a-zA-Z_.!@#$%^&*()~]+)|'
                               r'port=(?P<port>[0-9a-zA-Z_.!@#$%^&*()~]+)|'
                               r'user=(?P<user>[0-9a-zA-Z_.!@#$%^&*()~]+)|'
                               r'password=(?P<password>[0-9a-zA-Z_.!@#$%^&*()~]+)\b', re.IGNORECASE)
        for match in _re_dbstr.finditer(connection_string):
            match_dict = match.groupdict()
            if match_dict['host']:
                conn_prepared['host'] = match_dict['host']
            if match_dict['port']:
                conn_prepared['port'] = match_dict['port']
            if match_dict['dbname']:
                conn_prepared['dbname'] = match_dict['dbname']
            if match_dict['user']:
                conn_prepared['user'] = match_dict['user']
            if match_dict['password']:
                conn_prepared['password'] = match_dict['password']
    else:
        conn_prepared = {
            'host': conn_parsed.hostname,
            'port': conn_parsed.port,
            'dbname': conn_parsed.path,
            'user': conn_parsed.username,
            'password': conn_parsed.password
        }

    return conn_prepared
1183183
function getFilePathFromLine(bundleFile, line, variables) {
	// handle variables
	var varRegex = /@{([^}]+)}/;
	var match;
	while (match = line.match(varRegex)) {
		var varName = match[1];
		if (!variables || typeof (variables[varName]) === 'undefined')
			throw new gutil.PluginError(pluginName, bundleFile.path + ': variable "' + varName + '" is not specified');

		var varValue = variables[varName];
		line = line.substr(0, match.index) + varValue + line.substr(match.index + match[0].length);
	}

	if (line === '')
		return null;
	
	// handle `!` negated file paths
	var negative = line[0] === '!';
	if (negative)
		line = line.substr(1);

	// get file path for line
	var filePath;
	if (line.indexOf('./') === 0)
		filePath = path.resolve(bundleFile.cwd, line);
	else
		filePath = path.resolve(bundleFile.base, line);
	
	// return path
	if (negative)
		return '!' + filePath;
	return filePath;
}
96573
def getpaths(self,libname):
        """"""
        if os.path.isabs(libname):
            yield libname
        else:
            # FIXME / TODO return '.' and os.path.dirname(__file__)
            for path in self.getplatformpaths(libname):
                yield path

            path = ctypes.util.find_library(libname)
            if path: yield path
98558
def createConnection(self):
        """"""
        uri = self.reader.createConnection()
        return Pyro.core.getAttrProxyForURI(uri)
1044242
def getApplicationVariables(dbid=nil)
      variablesHash = {}
      dbid ||= @dbid
      qbc.getSchema(dbid)
      if @variables
         @variables.each_element_with_attribute( "name" ){ |var|
            if var.name == "var" and var.has_text?
              variablesHash[var.attributes["name"]] =  var.text
            end
         }
      end
      variablesHash
    end
268573
def fetch(self):
        
        params = values.of({})

        payload = self._version.fetch(
            'GET',
            self._uri,
            params=params,
        )

        return VariableInstance(
            self._version,
            payload,
            service_sid=self._solution['service_sid'],
            environment_sid=self._solution['environment_sid'],
            sid=self._solution['sid'],
        )
589159
def get_var(var):
    '''
    
    '''
    makeconf = _get_makeconf()
    # Open makeconf
    with salt.utils.files.fopen(makeconf) as fn_:
        conf_file = salt.utils.data.decode(fn_.readlines())
    for line in conf_file:
        if line.startswith(var):
            ret = line.split('=', 1)[1]
            if '"' in ret:
                ret = ret.split('"')[1]
            elif '#' in ret:
                ret = ret.split('#')[0]
            ret = ret.strip()
            return ret
    return None
961821
def create_pgpass_file(connection_string_or_info):
    """"""
    info = pgutil.get_connection_info(connection_string_or_info)
    if "password" not in info:
        return pgutil.create_connection_string(info)
    linekey = "{host}:{port}:{dbname}:{user}:".format(
        host=info.get("host", "localhost"),
        port=info.get("port", 5432),
        user=info.get("user", ""),
        dbname=info.get("dbname", "*"))
    pwline = "{linekey}{password}".format(linekey=linekey, password=info.pop("password"))
    pgpass_path = os.path.join(os.environ.get("HOME"), ".pgpass")
    if os.path.exists(pgpass_path):
        with open(pgpass_path, "r") as fp:
            pgpass_lines = fp.read().splitlines()
    else:
        pgpass_lines = []
    if pwline in pgpass_lines:
        LOG.debug("Not adding authentication data to: %s since it's already there", pgpass_path)
    else:
        # filter out any existing lines with our linekey and add the new line
        pgpass_lines = [line for line in pgpass_lines if not line.startswith(linekey)] + [pwline]
        content = "\n".join(pgpass_lines) + "\n"
        with open(pgpass_path, "w") as fp:
            os.fchmod(fp.fileno(), 0o600)
            fp.write(content)
        LOG.debug("Wrote %r to %r", pwline, pgpass_path)
    return pgutil.create_connection_string(info)
1104607
def variables(package):
    
    _raise_if_not_exists(package)
    result = _query(package, '--print-variables')
    names = (x.strip() for x in result.split('\n') if x != '')
    return dict(((x, _query(package, '--variable={0}'.format(x)).strip()) for x in names))
763545
public static String getSqlFile(String fileName) {
		String file = "/jk/sql/".concat(fileName);
		logger.debug("Loading sql file: ", file);
		return readFile(file);
	}
826990
def get_connection_params(self):
        
        return {
            'uri': self.settings_dict['NAME'],
            'tls': self.settings_dict.get('TLS', False),
            'bind_dn': self.settings_dict['USER'],
            'bind_pw': self.settings_dict['PASSWORD'],
            'retry_max': self.settings_dict.get('RETRY_MAX', 1),
            'retry_delay': self.settings_dict.get('RETRY_DELAY', 60.0),
            'options': {
                k if isinstance(k, int) else k.lower(): v
                for k, v in self.settings_dict.get('CONNECTION_OPTIONS', {}).items()
            },
        }
864475
def get_connection(self, command_name, *keys, **options):
        """"""
        self._checkpid()
        try:
            connection = self._available_connections[self._pattern_idx].pop()
        except IndexError:
            connection = self.make_connection()
        self._in_use_connections[self._pattern_idx].add(connection)
        self._next_pattern()
        return connection
1355827
def __getVariables(self):
        """'"""
        try:
            startupinfo = None
            if os.name == 'nt':
                startupinfo = subprocess.STARTUPINFO()
                startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            output = subprocess.check_output(['p4', 'set'], startupinfo=startupinfo)
            if six.PY3:
                output = str(output, 'utf8')
        except subprocess.CalledProcessError as err:
            LOGGER.error(err)
            return

        p4vars = {}
        for line in output.splitlines():
            if not line:
                continue
            try:
                k, v = line.split('=', 1)
            except ValueError:
                continue
            p4vars[k.strip()] = v.strip().split(' (')[0]
            if p4vars[k.strip()].startswith('(config'):
                del p4vars[k.strip()]

        self._port = self._port or os.getenv('P4PORT', p4vars.get('P4PORT'))
        self._user = self._user or os.getenv('P4USER', p4vars.get('P4USER'))
        self._client = self._client or os.getenv('P4CLIENT', p4vars.get('P4CLIENT'))
287780
def get_mysql_vars(mysql: str,
                   host: str,
                   port: int,
                   user: str) -> Dict[str, str]:
    
    cmdargs = [
        mysql,
        "-h", host,
        "-P", str(port),
        "-e", "SHOW VARIABLES; SHOW STATUS",
        "-u", user,
        "-p"  # prompt for password
    ]
    log.info("Connecting to MySQL with user: {}", user)
    log.debug(cmdargs)
    process = subprocess.Popen(cmdargs, stdout=subprocess.PIPE)
    out, err = process.communicate()
    lines = out.decode("utf8").splitlines()
    mysqlvars = {}
    for line in lines:
        var, val = line.split("\t")
        mysqlvars[var] = val
    return mysqlvars