/*
This module looks for the ES_HOST environment variable which is the URL to the
elasticsearch host
422343
async function Client() {
  if (!esClient) {
    esClient = await connect()
    console.log('connected to elasticsearch');
  } else {
    console.log('using existing elasticsearch connection')
  }
  return esClient
}
658590
def _include_environment_variables(self, program, executor_vars):
        """"""
        env_vars = {
            'RESOLWE_HOST_URL': self.settings_actual.get('RESOLWE_HOST_URL', 'localhost'),
        }

        set_env = self.settings_actual.get('FLOW_EXECUTOR', {}).get('SET_ENV', {})
        env_vars.update(executor_vars)
        env_vars.update(set_env)

        export_commands = ['export {}={}'.format(key, shlex.quote(value)) for key, value in env_vars.items()]
        return os.linesep.join(export_commands) + os.linesep + program
1205206
def base_url(self):
        """"""
        if self.location in self.known_locations:
            return self.known_locations[self.location]
        elif '.' in self.location or self.location == 'localhost':
            return 'https://' + self.location
        else:
            return 'https://' + self.location + API_HOST_SUFFIX
636181
function localhost(local, defaultPort) {
  // edge case when hostname:port is not informed via cli
  if (local === undefined || local === 'true') {
    local = [defaultPort];
  } else {
    local = local.toString().split(':');
  }

  return {
    hostname: reIp.test(local[0]) || isNaN(parseInt(local[0], 10)) &&
      local[0] ? local[0] : os.hostname(),
    port: parseInt(local[1] || (!reIp.test(local[0]) && local[0]), 10) ||
      defaultPort
  };
}
1143056
function buildGet (opts) {
  // eslint-disable-next-line no-unused-vars
  const { makeRequest, ConfigurationError, handleError, snakeCaseKeys } = opts
  /**
   * Perform a [get](http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-get.html) request
   *
   * @param {string} id - The document ID
   * @param {string} index - The name of the index
   * @param {string} type - The type of the document (use `_all` to fetch the first document matching the ID across all types)
   * @param {list} stored_fields - A comma-separated list of stored fields to return in the response
   * @param {string} parent - The ID of the parent document
   * @param {string} preference - Specify the node or shard the operation should be performed on (default: random)
   * @param {boolean} realtime - Specify whether to perform the operation in realtime or search mode
   * @param {boolean} refresh - Refresh the shard containing the document before performing the operation
   * @param {string} routing - Specific routing value
   * @param {list} _source - True or false to return the _source field or not, or a list of fields to return
   * @param {list} _source_excludes - A list of fields to exclude from the returned _source field
   * @param {list} _source_includes - A list of fields to extract and return from the _source field
   * @param {number} version - Explicit version number for concurrency control
   * @param {enum} version_type - Specific version type
   */

  const acceptedQuerystring = [
    'stored_fields',
    'parent',
    'preference',
    'realtime',
    'refresh',
    'routing',
    '_source',
    '_source_excludes',
    '_source_includes',
    'version',
    'version_type',
    'pretty',
    'human',
    'error_trace',
    'source',
    'filter_path'
  ]

  const snakeCase = {
    storedFields: 'stored_fields',
    _sourceExcludes: '_source_excludes',
    _sourceIncludes: '_source_includes',
    versionType: 'version_type',
    errorTrace: 'error_trace',
    filterPath: 'filter_path'
  }

  return function get (params, options, callback) {
    options = options || {}
    if (typeof options === 'function') {
      callback = options
      options = {}
    }
    if (typeof params === 'function' || params == null) {
      callback = params
      params = {}
      options = {}
    }

    // check required parameters
    if (params['id'] == null) {
      const err = new ConfigurationError('Missing required parameter: id')
      return handleError(err, callback)
    }
    if (params['index'] == null) {
      const err = new ConfigurationError('Missing required parameter: index')
      return handleError(err, callback)
    }
    if (params.body != null) {
      const err = new ConfigurationError('This API does not require a body')
      return handleError(err, callback)
    }

    // validate headers object
    if (options.headers != null && typeof options.headers !== 'object') {
      const err = new ConfigurationError(`Headers should be an object, instead got: ${typeof options.headers}`)
      return handleError(err, callback)
    }

    var warnings = []
    var { method, body, id, index, type, ...querystring } = params
    querystring = snakeCaseKeys(acceptedQuerystring, snakeCase, querystring, warnings)

    if (method == null) {
      method = 'GET'
    }

    var ignore = options.ignore
    if (typeof ignore === 'number') {
      options.ignore = [ignore]
    }

    var path = ''

    if ((index) != null && (type) != null && (id) != null) {
      path = '/' + encodeURIComponent(index) + '/' + encodeURIComponent(type) + '/' + encodeURIComponent(id)
    } else {
      path = '/' + encodeURIComponent(index) + '/' + '_doc' + '/' + encodeURIComponent(id)
    }

    // build request object
    const request = {
      method,
      path,
      body: null,
      querystring
    }

    options.warnings = warnings.length === 0 ? null : warnings
    return makeRequest(request, options, callback)
  }
}
247755
function strFromEnvironmentVarSetting(functionsVar, envVar) {
  if (!process.env[envVar]) {
    const msg = `${envVar} does not exist on within environment variables`
    warn(msg)
    return ''
  }
  return `${functionsVar}="${process.env[envVar]}"`
}
546650
def index_template_exists(name, hosts=None, profile=None):
    '''
    
    '''
    es = _get_instance(hosts, profile)
    try:
        return es.indices.exists_template(name=name)
    except elasticsearch.TransportError as e:
        raise CommandExecutionError("Cannot retrieve template {0}, server returned code {1} with message {2}".format(name, e.status_code, e.error))
885837
function somewhere (res) {
  if (typeof res.url === 'string' && res.url !== '') return res.url
  if (res.req) {
    const host = res.req.getHeader('host')
    if (host) return host
  }
  if (res.socket) return res.socket.remoteAddress
  return 'somewhere'
}
517483
def get_environment(self):
        '''
        
        '''
        env = {}
        if self.http:
            env['http_proxy'] = env['HTTP_PROXY'] = self.http
        if self.https:
            env['https_proxy'] = env['HTTPS_PROXY'] = self.https
        if self.ftp:
            env['ftp_proxy'] = env['FTP_PROXY'] = self.ftp
        if self.no_proxy:
            env['no_proxy'] = env['NO_PROXY'] = self.no_proxy
        return env
1035071
def get_host(environ):
    # type: (Dict[str, str]) -> str
    """"""
    if environ.get("HTTP_HOST"):
        rv = environ["HTTP_HOST"]
        if environ["wsgi.url_scheme"] == "http" and rv.endswith(":80"):
            rv = rv[:-3]
        elif environ["wsgi.url_scheme"] == "https" and rv.endswith(":443"):
            rv = rv[:-4]
    elif environ.get("SERVER_NAME"):
        rv = environ["SERVER_NAME"]
        if (environ["wsgi.url_scheme"], environ["SERVER_PORT"]) not in (
            ("https", "443"),
            ("http", "80"),
        ):
            rv += ":" + environ["SERVER_PORT"]
    else:
        # In spite of the WSGI spec, SERVER_NAME might not be present.
        rv = "unknown"

    return rv
1316008
private static String lookupHost(Properties props) {
        String host = null;

        // 1. lookup system property 'td.logger.api.server.host'
        if (props.containsKey(Config.TD_LOGGER_API_SERVER_HOST)) {
            host = props.getProperty(Config.TD_LOGGER_API_SERVER_HOST);
        }

        // if not exists, set default value
        if (host == null) {
            host = Config.TD_LOGGER_API_SERVER_HOST_DEFAULT;
        }

        // write/overwrite it to 'td.api.server.host'
        props.setProperty(Config.TD_API_SERVER_HOST, host);
        return host;
    }
167285
function getExternalModuleNameFromPath(host, fileName) {
        var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); };
        var dir = ts.toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName);
        var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory());
        var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
        return ts.removeFileExtension(relativePath);
    }
1353807
def find_general_mappings(es_major_version):
    

    if es_major_version not in ES_SUPPORTED:
        print("Elasticsearch version not supported %s (supported %s)" % (es_major_version, ES_SUPPORTED))
        sys.exit(1)

    # By default all strings are not analyzed in ES < 6
    if es_major_version == '5':
        # Before version 6, strings were strings
        not_analyze_strings = """
        {
          "dynamic_templates": [
            { "notanalyzed": {
                  "match": "*",
                  "match_mapping_type": "string",
                  "mapping": {
                      "type":        "string",
                      "index":       "not_analyzed"
                  }
               }
            }
          ]
        } """
    else:
        # After version 6, strings are keywords (not analyzed)
        not_analyze_strings = """
        {
          "dynamic_templates": [
            { "notanalyzed": {
                  "match": "*",
                  "match_mapping_type": "string",
                  "mapping": {
                      "type":        "keyword"
                  }
               }
            }
          ]
        } """

    return json.loads(not_analyze_strings)
1267543
function vhostof (req, regexp) {
  var host = req.headers.host
  var hostname = hostnameof(req)

  if (!hostname) {
    return
  }

  var match = regexp.exec(hostname)

  if (!match) {
    return
  }

  var obj = Object.create(null)

  obj.host = host
  obj.hostname = hostname
  obj.length = match.length - 1

  for (var i = 1; i < match.length; i++) {
    obj[i - 1] = match[i]
  }

  return obj
}
611565
function getEnvsListForTemplate(){
		var envsList = [];
		var keys = Object.keys(allEnvs).sort();
		for(var j = 0; j < keys.length; j++) {
			var key = keys[j];
			if(key !== 'builtin'){
				envsList.push(key);
			}
		}
		var templateList = {
			type: "link", //$NON-NLS-0$
			values: envsList,
			title: 'ESLint Environments',
			style: 'no_emphasis' //$NON-NLS-1$
		};
		return JSON.stringify(templateList).replace("}", "\\}");
	}
1033587
def _eb_env_tags(envs, session_factory, retry):
    """"""

    client = local_session(session_factory).client('elasticbeanstalk')

    def process_tags(eb_env):
        try:
            eb_env['Tags'] = retry(
                client.list_tags_for_resource,
                ResourceArn=eb_env['EnvironmentArn'])['ResourceTags']
        except client.exceptions.ResourceNotFoundException:
            return
        return eb_env

    # Handle API rate-limiting, which is a problem for accounts with many
    # EB Environments
    return list(map(process_tags, envs))
83029
function (module) {
        "use strict";
    
        var getResource = function (hostType, resource) {
    
            var host;
            var modulePath, filePath;
    
            if (resource.substr(0, 1) === '/') {
                resource = resource.substr(1);
            }
    
            if (hostType === 'module') {
    
                if (module.library) {
                    host = beyond.hosts.libraries[module.library.name].js;
                    library = module.library.name;
                }
                else {
                    host = beyond.hosts.application.js;
                    library = undefined;
                }
    
                modulePath = module.path;
                filePath = resource;
    
            }
            else if (hostType === 'application') {
    
                host = beyond.hosts.application.js;
                return host + resource;
    
            }
            else {
    
                var library = hostType;
                host = beyond.hosts.libraries[library];
    
                if (!host) {
                    console.warn('invalid css host on module "' + module.ID + '", resource "' + resource + '"' +
                        ', library "' + library + '" is not defined');
                    return;
                }
    
                if (resource.substr(0, 7) === 'static/') {
                    modulePath = 'main';
                    filePath = resource.substr(7);
                }
                else {
                    var overwrite = resource.split('/static/');
                    modulePath = overwrite[0];
                    filePath = overwrite[1];
                }
    
            }
    
            var overwrites = beyond.overwrites;
            var overwrited;
            if (library) {
                overwrited = overwrites[library];
            }
    
            if (!overwrited || !overwrited[modulePath] ||
                overwrited[modulePath].indexOf(filePath) === -1) {
    
                return host + modulePath + '/static/' + filePath;
            }
    
            return beyond.hosts.application.js +
                'custom/' + library + '/' +
                modulePath + '/static/' + filePath;
    
        };
    
        var setHosts = function (styles) {
    
            // find variables
            var variable;
    
            var replace = {};
    
            var regexp = /#host\.(.*?)#(.*?)[\)\s]/g;
            variable = regexp.exec(styles);
    
            var resource;
            while (variable) {
    
                // hostType can be 'application', 'module', libraryName
                var hostType = variable[1];
                resource = variable[2];
                resource = getResource(hostType, resource);
    
                var original = variable[0];
                if (original.substr(original.length - 1) === ')')
                    original = original.substr(0, original.length - 1);
    
                replace[original] = resource;
                variable = regexp.exec(styles);
    
            }
    
            // replace #host.* variables with their values
            for (var original in replace) {
    
                resource = replace[original];
    
                while (styles.indexOf(original) !== -1)
                    styles = styles.replace(original, resource);
    
            }
    
            return styles;
    
        };
    
        this.process = function (styles) {
    
            // find and replace #host...
            styles = setHosts(styles);
            return styles;
    
        };
    
    }