Derive q home from the environment
2105
def get_q_home(env):
    """"""
    q_home = env.get('QHOME')
    if q_home:
        return q_home
    for v in ['VIRTUAL_ENV', 'HOME']:
        prefix = env.get(v)
        if prefix:
            q_home = os.path.join(prefix, 'q')
            if os.path.isdir(q_home):
                return q_home
    if WINDOWS:
        q_home = os.path.join(env['SystemDrive'], r'\q')
        if os.path.isdir(q_home):
            return q_home
    raise RuntimeError('No suitable QHOME.')
1320328
def _set_environment(self, environ):
        """"""
        if environ:
            q_environ = self._process.processEnvironment()
            for k, v in environ.items():
                q_environ.insert(k, v)
            self._process.setProcessEnvironment(q_environ)
1233894
def inve(env, command, *args, **kwargs):
    """"""
    # we don't strictly need to restore the environment, since pew runs in
    # its own process, but it feels like the right thing to do
    with temp_environ():
        os.environ['VIRTUAL_ENV'] = str(workon_home / env)
        os.environ['PATH'] = compute_path(env)

        unsetenv('PYTHONHOME')
        unsetenv('__PYVENV_LAUNCHER__')

        try:
            return check_call([command] + list(args), shell=windows, **kwargs)
            # need to have shell=True on windows, otherwise the PYTHONPATH
            # won't inherit the PATH
        except OSError as e:
            if e.errno == 2:
                err('Unable to find', command)
                return 2
            else:
                raise
1322074
function environment() {
    var exec = constants_1.ARGV
        .slice(0, 2)
        .map(function (v, i) {
        if (i === 0 && constants_1.EXE_EXP.test(v))
            return;
        var rebased = path_1.relative(constants_2.CWD, v);
        return v.match(/^(\/|([a-zA-Z]:)?\\)/) &&
            rebased.length < v.length ? rebased : v;
    }).join(' ').trim();
    if (constants_1.NODE_PATH !== undefined && constants_1.ARGV[1] === constants_1.NODE_PATH)
        exec = constants_1.NODE_PATH.replace(path_1.dirname(constants_1.EXEC_PATH) + '/', '');
    return {
        CWD: process.cwd(),
        EXEC: exec,
        EXEC_PATH: constants_1.EXEC_PATH || constants_1.ARGV[1],
        NODE_PATH: constants_1.NODE_PATH || constants_1.ARGV[0],
        NODE_ENV: process.env.NODE_ENV,
        HOME_PATH: process.env.HOME,
        PLATFORM: process.platform,
        PKG: findPackage() // NOT bullet proof.
    };
}
168971
def hermetic_environment_as(**kwargs):
  """"""
  old_environment = os.environ.copy() if PY3 else _copy_and_decode_env(os.environ)
  _purge_env()
  try:
    with environment_as(**kwargs):
      yield
  finally:
    _purge_env()
    _restore_env(old_environment)
765258
def show():
    """"""
    env = get_environment()

    for key, val in sorted(env.env.items(), key=lambda item: item[0]):
        click.secho('%s = %s' % (key, val))
2296
def cli(env):
    """"""
    filtered_vars = dict([(k, v)
                          for k, v in env.vars.items()
                          if not k.startswith('_')])
    env.fout(formatting.iter_to_table(filtered_vars))
1016118
def get_environ(environ, defaults, ve_path):
    
    # Copy the parent environment, add in defaults from .vexrc.
    env = environ.copy()
    env.update(defaults)

    # Leaving in existing PYTHONHOME can cause some errors
    if 'PYTHONHOME' in env:
        del env['PYTHONHOME']

    # Now we have to adjust PATH to find scripts for the virtualenv...
    # PATH being unset/empty is OK, but ve_path must be set
    # or there is nothing for us to do here and it's bad.
    if not ve_path:
        raise exceptions.BadConfig('ve_path must be set')
    if platform.system() == 'Windows':
        ve_bin = os.path.join(ve_path, 'Scripts')
    else:
        ve_bin = os.path.join(ve_path, 'bin')

    # If user is currently in a virtualenv, DON'T just prepend
    # to its path (vex foo; echo $PATH -> " /foo/bin:/bar/bin")
    # but don't incur this cost unless we're already in one.
    # activate handles this by running 'deactivate' first, we don't
    # have that so we have to use other ways.
    # This would not be necessary and things would be simpler if vex
    # did not have to interoperate with a ubiquitous existing tool.
    # virtualenv doesn't...
    current_ve = env.get('VIRTUAL_ENV', '')
    system_path = environ.get('PATH', '')
    segments = system_path.split(os.pathsep)
    if current_ve:
        # Since activate doesn't export _OLD_VIRTUAL_PATH, we are going to
        # manually remove the virtualenv's bin.
        # A virtualenv's bin should not normally be on PATH except
        # via activate or similar, so I'm OK with this solution.
        current_ve_bin = os.path.join(current_ve, 'bin')
        try:
            segments.remove(current_ve_bin)
        except ValueError:
            raise exceptions.BadConfig(
                "something set VIRTUAL_ENV prior to this vex execution, "
                "implying that a virtualenv is already activated "
                "and PATH should contain the virtualenv's bin directory. "
                "Unfortunately, it doesn't: it's {0!r}. "
                "You might want to check that PATH is not "
                "getting clobbered somewhere, e.g. in your shell's configs."
                .format(system_path)
            )

    segments.insert(0, ve_bin)
    env['PATH'] = os.pathsep.join(segments)
    env['VIRTUAL_ENV'] = ve_path
    return env
1031858
def environ(on=os, **kw):
    
    
    originals = list()
    
    for key in kw:
        originals.append((key, on.environ.get(key, None)))
        on.environ[key] = kw[key]
    
    yield
    
    for key, value in originals:
        if not value:
            del on.environ[key]
            continue
        
        on.environ[key] = value
587023
def get_environments():
    """"""
    envs = []
    for root, subfolders, files in os.walk('environments'):
        for filename in files:
            if filename.endswith(".json"):
                path = os.path.join(
                    root[len('environments'):], filename[:-len('.json')])
                envs.append(get_environment(path))
    return sorted(envs, key=lambda x: x['name'])
1066261
def _get_environment_details(python_bin: str) -> list:
    """"""
    cmd = "{} -m pipdeptree --json".format(python_bin)
    output = run_command(cmd, is_json=True).stdout
    return [_create_entry(entry) for entry in output]
162157
def cli(env):
    """"""

    settings = config.get_settings_from_client(env.client)
    env.fout(config.config_table(settings))
516943
def _val_from_env(self, env, attr):
        """"""
        val = os.environ[env]
        if attr in ('rules', 'exclude_rules'):
            return self._rules_from_env(val)
        elif attr == 'priority':
            return dict(self._priority_from_env(val))
        elif attr in ('wait_command', 'history_limit', 'wait_slow_command',
                      'num_close_matches'):
            return int(val)
        elif attr in ('require_confirmation', 'no_colors', 'debug',
                      'alter_history', 'instant_mode'):
            return val.lower() == 'true'
        elif attr == 'slow_commands':
            return val.split(':')
        else:
            return val
515013
def _base_environ(self, **request):
        '''
            
        '''
        # This is a minimal valid WSGI environ dictionary, plus:
        # - HTTP_COOKIE: for cookie support,
        # - REMOTE_ADDR: often useful, see #8551.
        # See http://www.python.org/dev/peps/pep-3333/#environ-variables

        environ = {
            'HTTP_COOKIE': self.cookies.output(header='', sep='; '),
            'PATH_INFO': str('/'),
            'REMOTE_ADDR': str('127.0.0.1'),
            'REQUEST_METHOD': str('GET'),
            'SCRIPT_NAME': str(''),
            'SERVER_NAME': str('localhost'),
            'SERVER_PORT': str('8000'),
            'SERVER_PROTOCOL': str('HTTP/1.1'),
            'wsgi.version': (1, 0),
            'wsgi.url_scheme': str('http'),
            'wsgi.input': FakePayload(b''),
            'wsgi.errors': self.errors,
            'wsgi.multiprocess': True,
            'wsgi.multithread': True,
            'wsgi.run_once': False,
        }
        environ.update(self.defaults)
        environ.update(request)
        return environ
1209003
function getEnvironment(opts) {
  if (opts.app) {
    // Merge app env over the process env and return.
    var processEnv = _.cloneDeep(process.env);
    var appEnv = opts.app.env.getEnv();
    return _.merge(processEnv, appEnv);
  } else {
    // Just use process env.
    return process.env;
  }
}
228490
def get_environment_info() -> dict:
    
    data = _environ.systems.get_system_data()
    data['cauldron'] = _environ.package_settings.copy()
    return data
1270061
function setEnv(env) {
  home.initHomeDir();
  const envFile = path.join(home.getHomePath(), FILE_ENV);
  const envData = {
    env,
  };
  debug('set fie env data : %o', envData);
  debug('set fie to : %s', envFile);
  cacheEnv = null;
  fs.outputJsonSync(envFile, envData);
}