Discover maven home from executable on PATH, using conventions.
327466
public static File getMavenHome() throws Exception {
        final String command;
        switch (OS.current()) {
        case LINUX:
        case MAC:
            command = "mvn";
            break;
        case WINDOWS:
            command = "mvn.bat";
            break;
        default:
            throw new IllegalStateException("invalid o/s");
        }
        String pathVar = System.getenv("PATH");
        String[] pathArray = pathVar.split(File.pathSeparator);
        for (String path : pathArray) {
            File file = new File(path, command);
            if (file.exists() && file.isFile() && file.canExecute()) {
                /** unwrap symbolic links */
                File exec = file.getCanonicalFile();
                /** assume ${maven.home}/bin/exec convention */
                File home = exec.getParentFile().getParentFile();
                return home;
            }
        }
        throw new IllegalStateException("Maven home not found.");
    }
558762
def localpath(*args):
    """"""
    plist = [ROOT] + list(args)
    return os.path.abspath(pjoin(*plist))
335340
function getConfig(fpath, defaults) {
  var path = require('path');
  var dpath = path.dirname(path.resolve(fpath));

  function parentpath(fromdir, pattern) {
    var pp = require('parentpath'),
        cwd = process.cwd();
    try {
      process.chdir(fromdir);
      return pp.sync(pattern);
    } catch (e) {
      return null;
    } finally {
      process.chdir(cwd);
    }
  }

  function fromNpm() {
    var config;
    var dir = parentpath(dpath, 'package.json');
    if (dir) {
      try {
        config = require(dir + '/package.json')[MJS_NPM];
        config.__origin__ = dir + '/package.json';
      } catch (e) {
      }
    }
    return config;
  }

  function fromResourceFile() {
    var candidates = [
      parentpath(path, MJS_RC),
      process.env.HOME, process.env.USERPROFILE, process.env.HOMEPATH, process.env.HOMEDRIVE + process.env.HOMEPATH
    ];

    var config;
    for (var i = 0; i < candidates.length; i++) {
      var candidate = candidates[i] + '/' + MJS_RC;
      if (fs.existsSync(candidate)) {
        try {
          config = JSON.parse(fs.readFileSync(candidate));
          config.__origin__ = candidate;
          break;
        } catch (e) {
          showHelpAndExit('Unable to read config from "' + candidate + '": ' + e.message, 1);
        }
      }
    }
    return config;
  }

  var config = fromNpm() || fromResourceFile() || {};
  // Make sure we apply defaults to missing values
  Object.keys(defaults).filter(function (k) {
    return config[k] == null
  }).forEach(function (k) {
    config[k] = defaults[k];
  });
  return config;
}
1196527
def get_env(path, ignore_git_branch=False):
    """"""
    if 'DEPLOY_ENVIRONMENT' in os.environ:
        return os.environ['DEPLOY_ENVIRONMENT']

    if ignore_git_branch:
        LOGGER.info('Skipping environment lookup from current git branch '
                    '("ignore_git_branch" is set to true in the runway '
                    'config)')
    else:
        # These are not located with the top imports because they throw an
        # error if git isn't installed
        from git import Repo as GitRepo
        from git.exc import InvalidGitRepositoryError

        try:
            b_name = GitRepo(
                path,
                search_parent_directories=True
            ).active_branch.name
            LOGGER.info('Deriving environment name from git branch %s...',
                        b_name)
            return get_env_from_branch(b_name)
        except InvalidGitRepositoryError:
            pass
    LOGGER.info('Deriving environment name from directory %s...', path)
    return get_env_from_directory(os.path.basename(path))
51213
def get_maven_id(jar_path):
        
        props = {}
        try:
            with zipfile.ZipFile(jar_path) as f:
                r = re.compile("META-INF/maven/[^/]+/[^/]+/pom.properties$")
                result = [x for x in f.namelist() if r.match(x)]
                if len(result) != 1:
                    return None
                with f.open(result[0]) as props_f:
                    for line in props_f.readlines():
                        line = line.strip()
                        if not line.startswith(b"#"):
                            try:
                                (key, value) = line.split(b"=")
                                key = key.decode('utf8').strip()
                                value = value.decode('utf8').strip()
                                props[key] = value
                            except ValueError:
                                return None
        except IOError:
            pass
        return props
829777
def get_config_path():
    """"""
    dir_path = (os.getenv('APPDATA') if os.name == "nt"
                else os.path.expanduser('~'))
    return os.path.join(dir_path, '.vtjp')
448747
def which(cmd, safe=False):
    """"""
    from autopaths.file_path import FilePath
    def is_executable(path):
        return os.path.exists(path) and os.access(path, os.X_OK) and not os.path.isdir(path)
    path, name = os.path.split(cmd)
    if path:
        if is_executable(cmd): return FilePath(cmd)
    else:
        for path in os.environ['PATH'].split(os.pathsep):
            candidate = os.path.join(path, cmd)
            if is_executable(candidate): return FilePath(candidate)
    if not safe: raise Exception('which failed to locate a proper command path "%s"' % cmd)
19707
def _find_observable_paths(extra_files=None):
    """"""
    rv = set(
        os.path.dirname(os.path.abspath(x)) if os.path.isfile(x) else os.path.abspath(x)
        for x in sys.path
    )

    for filename in extra_files or ():
        rv.add(os.path.dirname(os.path.abspath(filename)))

    for module in list(sys.modules.values()):
        fn = getattr(module, "__file__", None)
        if fn is None:
            continue
        fn = os.path.abspath(fn)
        rv.add(os.path.dirname(fn))

    return _find_common_roots(rv)
1150290
def _get_from_java_home(self):
        
        # Get the environment variable
        java_home = os.getenv("JAVA_HOME")
        if java_home and os.path.exists(java_home):
            # Get the real installation path
            java_home = os.path.realpath(java_home)

            # Cygwin has a bug in realpath
            if not os.path.exists(java_home):
                java_home = os.getenv("JAVA_HOME")

            # Look for the library file
            return self.find_libjvm(java_home)
103192
def collect_local(self, path):
        
        for f in os.listdir(path):
            lpath = os.path.join(path, f)
            if not os.path.isfile(lpath):
                continue
            Artifact(self, lpath)
1332164
def get_home_dir():
    """"""
    _home_dir = os.environ.get('MXNET_HOME', os.path.join('~', '.mxnet'))
    # expand ~ to actual path
    _home_dir = os.path.expanduser(_home_dir)
    return _home_dir
335197
def _clean_path(path):
        """"""
        path = path.replace('"', '')
        path = path.replace("'", '')
        # Replace ~ with /home/user
        path = os.path.expanduser(path)
        # Replace environment variables
        path = os.path.expandvars(path)
        # If the path is relative, assume it is relative to the config file directory
        if not os.path.isabs(path):
            path = os.path.join(config.global_config.path, path)
        # Clean path, e.g. replace /./ with /
        path = os.path.abspath(path)
        # Eliminate symbolic links
        path = os.path.realpath(path)
        return path
176941
def _getConfigPath(self):
        
        confHome = environ.get('VIBE_CONFIG_HOME')
        return confHome if confHome is not None else path.join(path.expanduser("~"), '.vibe')
1279798
function (str) {
        if (!str) {
            return str;
        }
        if (str.substr(0,1) === '~') {
            str = process.env.HOME + str.substr(1);
        }
        return path.resolve(str);
    }
75060
def find_lib_path():
    
    lib_from_env = os.environ.get('MXNET_LIBRARY_PATH')
    if lib_from_env:
        if os.path.isfile(lib_from_env):
            if not os.path.isabs(lib_from_env):
                logging.warning("MXNET_LIBRARY_PATH should be an absolute path, instead of: %s",
                                lib_from_env)
            else:
                if os.name == 'nt':
                    os.environ['PATH'] = os.environ['PATH'] + ';' + os.path.dirname(lib_from_env)
                return [lib_from_env]
        else:
            logging.warning("MXNET_LIBRARY_PATH '%s' doesn't exist", lib_from_env)

    curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))
    api_path = os.path.join(curr_path, '../../lib/')
    cmake_build_path = os.path.join(curr_path, '../../build/')
    dll_path = [curr_path, api_path, cmake_build_path]
    if os.name == 'nt':
        dll_path.append(os.path.join(curr_path, '../../build'))
        vs_configuration = 'Release'
        if platform.architecture()[0] == '64bit':
            dll_path.append(os.path.join(curr_path, '../../build', vs_configuration))
            dll_path.append(os.path.join(curr_path, '../../windows/x64', vs_configuration))
        else:
            dll_path.append(os.path.join(curr_path, '../../build', vs_configuration))
            dll_path.append(os.path.join(curr_path, '../../windows', vs_configuration))
    elif os.name == "posix" and os.environ.get('LD_LIBRARY_PATH', None):
        dll_path[0:0] = [p.strip() for p in os.environ['LD_LIBRARY_PATH'].split(":")]
    if os.name == 'nt':
        os.environ['PATH'] = os.path.dirname(__file__) + ';' + os.environ['PATH']
        dll_path = [os.path.join(p, 'libmxnet.dll') for p in dll_path]
    elif platform.system() == 'Darwin':
        dll_path = [os.path.join(p, 'libmxnet.dylib') for p in dll_path] + \
                   [os.path.join(p, 'libmxnet.so') for p in dll_path]
    else:
        dll_path.append('../../../')
        dll_path = [os.path.join(p, 'libmxnet.so') for p in dll_path]
    lib_path = [p for p in dll_path if os.path.exists(p) and os.path.isfile(p)]
    if len(lib_path) == 0:
        raise RuntimeError('Cannot find the MXNet library.\n' +
                           'List of candidates:\n' + str('\n'.join(dll_path)))
    if os.name == 'nt':
        os.environ['PATH'] = os.environ['PATH'] + ';' + os.path.dirname(lib_path[0])
    return lib_path
319506
def law_home_path(*paths):
    
    home = os.getenv("LAW_HOME", "$HOME/.law")
    home = os.path.expandvars(os.path.expanduser(home))
    return os.path.normpath(os.path.join(home, *paths))
169725
def exec_path(self, baseVersion=None):
    """"""
    if not os.path.isdir(self.data_dir):
        raise sc_process.SC2LaunchError("Install Starcraft II at %s or set the SC2PATH environment variable"%(self.data_dir))
    if baseVersion==None: # then select most recent version's baseVersion
        mostRecent = versions.handle.mostRecent
        if mostRecent:  return mostRecent["base-version"]
        raise sc_process.SC2LaunchError(
            "When requesting a versioned executable path without specifying base-version, expected "
            "to find StarCraft II versions installed at %s."%(self.versionsDir))
    elif isinstance(baseVersion, versions.Version):
        baseVersion = baseVersion.baseVersion
    elif str(baseVersion).count(".") > 0:
        baseVersion = versions.Version(baseVersion).baseVersion
    #else: # otherwise expect that the baseVersion specified is correct
    baseVersExec = os.path.join(self.versionsDir, "Base%s"%baseVersion, self._exec_name)
    if os.path.isfile(baseVersExec):
        return baseVersExec # if baseVersion in Versions subdir is valid, it is the correct executable
    raise sc_process.SC2LaunchError("Specified baseVersion %s does not exist at %s.%s    available: %s"%(\
        baseVersion, baseVersExec, os.linesep, " ".join(
            str(val) for val in sorted(self.versionMap().keys())) ))