Returns common ancestor for paths represented by absolute path and pattern.
1175
public static String extractCommonAncestor(String pattern, String absPath)
   {
      pattern = normalizePath(pattern);
      absPath = normalizePath(absPath);

      String[] patterEntries = pattern.split("/");
      String[] pathEntries = absPath.split("/");

      StringBuilder ancestor = new StringBuilder();
      int count = Math.min(pathEntries.length, patterEntries.length);

      for (int i = 1; i < count; i++)
      {
         if (acceptName(patterEntries[i], pathEntries[i]))
         {
            ancestor.append("/");
            ancestor.append(pathEntries[i]);
         }
         else
         {
            break;
         }
      }

      return ancestor.length() == 0 ? JCRPath.ROOT_PATH : ancestor.toString();
   }
1178493
def _relative_paths(xs, base_path):
    
    if isinstance(xs, six.string_types):
        if xs.startswith(base_path):
            return xs.replace(base_path + "/", "", 1)
        else:
            return xs
    elif isinstance(xs, (list, tuple)):
        return [_relative_paths(x, base_path) for x in xs]
    elif isinstance(xs, dict):
        out = {}
        for k, v in xs.items():
            out[k] = _relative_paths(v, base_path)
        return out
    else:
        return xs
454750
function findNativeAddonForExists (path) {
    var foundPath = findNativeAddonSyncFreeFromRequire(path);
    if (!foundPath) return false;
    return ancestor.existsSync.call(fs, foundPath);
  }
350904
def common_ancestor(c):
    
    span1 = _to_span(c[0])
    span2 = _to_span(c[1])
    ancestor1 = np.array(span1.sentence.xpath.split("/"))
    ancestor2 = np.array(span2.sentence.xpath.split("/"))
    min_len = min(ancestor1.size, ancestor2.size)
    return list(ancestor1[: np.argmin(ancestor1[:min_len] == ancestor2[:min_len])])
1015563
private Path[] globPathsLevel(Path[] parents, String[] filePattern,
      int level, boolean[] hasGlob) throws IOException {
    if (level == filePattern.length - 1)
      return parents;
    if (parents == null || parents.length == 0) {
      return null;
    }
    GlobFilter fp = new GlobFilter(filePattern[level]);
    if (fp.hasPattern()) {
      parents = FileUtil.stat2Paths(listStatus(parents, fp));
      hasGlob[0] = true;
    } else {
      for (int i = 0; i < parents.length; i++) {
        parents[i] = new Path(parents[i], filePattern[level]);
      }
    }
    return globPathsLevel(parents, filePattern, level + 1, hasGlob);
  }
392060
def get_filebase(path, pattern):
    """"""
    # A pattern can include directories
    tail_len = len(pattern.split(os.path.sep))
    return os.path.join(*str(path).split(os.path.sep)[-tail_len:])
280803
function fromOffsetPath(ancestor, offsets) {
  let current = ancestor;
  for (let i = 0, len = offsets.length; i < len; i++) {
    if (current.childNodes.length <= offsets[i]) {
      current = current.childNodes[current.childNodes.length - 1];
    } else {
      current = current.childNodes[offsets[i]];
    }
  }
  return current;
}
911782
def grandparent_path(self):
        
        return os.path.basename(os.path.join(self.path, '../..'))
685253
function(paths) {

      function relativePath(p, dirType) {
          var relativeStart = p.indexOf('./') === 0 || p.indexOf('../') === 0;
          return relativeStart? prefixPath(options.dirs.client,p) : prefixPath(options.dirs[dirType], p);
      }

      function prefixPath(base,p) {
          base = base.replace(/^\//,'');
          if (p === '*') {
            return base;
          }
          p = p.replace(/\/\*$/,'');
          return path.join(base,p);
      }

      function entries(from, dirType) {
        if (from == null) {
          return [];
        }
        var list = (from instanceof Array)? from : [from];

        return list.map(function(value) {
          return relativePath(value, dirType);
        });
      }

      paths.css = entries(paths.css, 'css');
      paths.code = entries(paths.code, 'code');
      paths.tmpl = entries(paths.tmpl || paths.templates, 'templates');

      if (paths.view) {
        paths.view = relativePath(paths.view, 'views');
      }

      return paths;
    }
588523
def root_and_path(self):
        """"""
        rt = []
        curAttr = self
        while isinstance(curAttr.parent, AdHocTree):
            rt.append(curAttr.name)
            curAttr = curAttr.parent
        rt.reverse()
        return (curAttr.parent, rt)
148860
public static String getRelativeNodePath(String basePath, String targetPath) {

		// Both paths are equal
		if (basePath.equals(targetPath)) {

			return ".";

		}

		if (basePath.equals(PATH_SEP) && (targetPath.length() > 1)) {

			// Base path is root path
			return targetPath.substring(1);
		}

		String[] baseAncestors   = FilenameUtils.normalizeNoEndSeparator(basePath).split(PATH_SEP);
		String[] targetAncestors = FilenameUtils.normalizeNoEndSeparator(targetPath).split(PATH_SEP);
		int length               = (baseAncestors.length < targetAncestors.length)
					   ? baseAncestors.length
					   : targetAncestors.length;
		int lastCommonRoot       = -1;
		int i;

		// Iterate over the shorter path
		for (i = 0; i < length; i++) {

			if (baseAncestors[i].equals(targetAncestors[i])) {

				lastCommonRoot = i;

			} else {

				break;

			}

		}

		// Last common root is the common base path
		if (lastCommonRoot != -1) {

			StringBuilder newRelativePath = new StringBuilder();

			// How often must we go back from base path to common root?
			for (i = lastCommonRoot + 1; i < baseAncestors.length; i++) {

				if (baseAncestors[i].length() > 0) {

					newRelativePath.append(".." + PATH_SEP);

				}

			}

			// How often must we go forth from common root to get to tagret path?
			for (i = lastCommonRoot + 1; i < targetAncestors.length; i++) {

				newRelativePath.append(targetAncestors[i]).append(PATH_SEP);

			}

			// newRelativePath.append(targetAncestors[targetAncestors.length - 1]);
			String result = newRelativePath.toString();

			if (result.endsWith(PATH_SEP)) {

				result = result.substring(0, result.length() - 1);

			}

			return result;

		}

		return targetPath;
	}
928962
function getDeepestCommonAncestorFrom(paths, filter) {
  // istanbul ignore next

  var _this = this;

  if (!paths.length) {
    return this;
  }

  if (paths.length === 1) {
    return paths[0];
  }

  // minimum depth of the tree so we know the highest node
  var minDepth = Infinity;

  // last common ancestor
  var lastCommonIndex, lastCommon;

  // get the ancestors of the path, breaking when the parent exceeds ourselves
  var ancestries = paths.map(function (path) {
    var ancestry = [];

    do {
      ancestry.unshift(path);
    } while ((path = path.parentPath) && path !== _this);

    // save min depth to avoid going too far in
    if (ancestry.length < minDepth) {
      minDepth = ancestry.length;
    }

    return ancestry;
  });

  // get the first ancestry so we have a seed to assess all other ancestries with
  var first = ancestries[0];

  // check ancestor equality
  depthLoop: for (var i = 0; i < minDepth; i++) {
    var shouldMatch = first[i];

    var _arr2 = ancestries;
    for (var _i2 = 0; _i2 < _arr2.length; _i2++) {
      var ancestry = _arr2[_i2];
      if (ancestry[i] !== shouldMatch) {
        // we've hit a snag
        break depthLoop;
      }
    }

    // next iteration may break so store these so they can be returned
    lastCommonIndex = i;
    lastCommon = shouldMatch;
  }

  if (lastCommon) {
    if (filter) {
      return filter(lastCommon, lastCommonIndex, ancestries);
    } else {
      return lastCommon;
    }
  } else {
    throw new Error("Couldn't find intersection");
  }
}
1210807
def resolve_relative_paths(paths: List[str]) -> Dict[str, str]:
    
    buck_root = find_buck_root(os.getcwd())
    if buck_root is None:
        LOG.error(
            "Buck root couldn't be found. Returning empty analysis directory mapping."
        )
        return {}
    command = [
        "buck",
        "query",
        "--json",
        "--output-attribute",
        ".*",
        "owner(%s)",
        *paths,
    ]
    try:
        output = json.loads(
            subprocess.check_output(command, timeout=30, stderr=subprocess.DEVNULL)
            .decode()
            .strip()
        )
    except (
        subprocess.TimeoutExpired,
        subprocess.CalledProcessError,
        json.decoder.JSONDecodeError,
    ) as error:
        raise BuckException("Querying buck for relative paths failed: {}".format(error))
    # TODO(T40580762) we should use the owner name to determine which files are a
    # part of the pyre project
    results = {}
    for path in paths:
        # For each path, search for the target that owns it.
        for owner in output.values():
            prefix = os.path.join(buck_root, owner["buck.base_path"]) + os.sep

            if not path.startswith(prefix):
                continue

            suffix = path[len(prefix) :]

            if suffix not in owner["srcs"]:
                continue

            if "buck.base_module" in owner:
                base_path = os.path.join(*owner["buck.base_module"].split("."))
            else:
                base_path = owner["buck.base_path"]

            results[path] = os.path.join(base_path, owner["srcs"][suffix])
            break  # move on to next path
    return results
121276
function getCommonBaseDir(a, b) {
	var common = [];
	a = a.split(path.sep);
	b = b.split(path.sep);
	for (var i = 0; i < a.length; i++) {
		if (b[i] === undefined || b[i] !== a[i]) {
			break;
		}
		common.push(a[i]);
	}
	return common.join(path.sep);
}
755330
def get_paths(patterns, start_dirs=None, max_depth=1):
    """"""
    # Shortcut: if there is only one pattern, make sure we process just that.
    if len(patterns) == 1 and not start_dirs:
        pattern = patterns[0]
        directory = os.path.dirname(pattern)
        if directory:
            patterns = [os.path.basename(pattern)]
            start_dirs = directory
            max_depth = 1

    if not start_dirs or start_dirs == '.':
        start_dirs = os.getcwd()
    for start_dir in start_dirs.split(','):
        for root, dirs, files in os.walk(start_dir):  # pylint: disable=W0612
            if max_depth is not None:
                relpath = os.path.relpath(root, start=start_dir)
                depth = len(relpath.split(os.sep))
                if depth > max_depth:
                    continue
            names = []
            for pattern in patterns:
                names += fnmatch.filter(files, pattern)
            for name in names:
                path = os.path.join(root, name)
                yield path
561402
function getSegmentedSubPaths(paths) {
    let segments = new Map();

    // Get earliest Path in tree where paths intersect
    paths[0].getDeepestCommonAncestorFrom(
      paths,
      (lastCommon, index, ancestries) => {
        // found the LCA
        if (!lastCommon.isProgram()) {
          let fnParent;
          if (
            lastCommon.isFunction() &&
            t.isBlockStatement(lastCommon.node.body)
          ) {
            segments.set(lastCommon, paths);
            return;
          } else if (
            !(fnParent = getFunctionParent(lastCommon)).isProgram() &&
            t.isBlockStatement(fnParent.node.body)
          ) {
            segments.set(fnParent, paths);
            return;
          }
        }
        // Deopt and construct segments otherwise
        for (const ancestor of ancestries) {
          const fnPath = getChildFuncion(ancestor);
          if (fnPath === void 0) {
            continue;
          }
          const validDescendants = paths.filter(p => {
            return p.isDescendant(fnPath);
          });
          segments.set(fnPath, validDescendants);
        }
      }
    );
    return segments;
  }
721156
public Path getPathInHar(Path path) {
    Path harPath = new Path(path.toUri().getPath());
    if (archivePath.compareTo(harPath) == 0)
      return new Path(Path.SEPARATOR);
    Path tmp = new Path(harPath.getName());
    Path parent = harPath.getParent();
    while (!(parent.compareTo(archivePath) == 0)) {
      if (parent.toString().equals(Path.SEPARATOR)) {
        tmp = null;
        break;
      }
      tmp = new Path(parent.getName(), tmp);
      parent = parent.getParent();
    }
    if (tmp != null)
      tmp = new Path(Path.SEPARATOR, tmp);
    return tmp;
  }