Verify that the pom-file is sorted regardless of formatting
503480
public void verifyPom() {
        String pomFileName = pomFile.getAbsolutePath();
        log.info("Verifying file " + pomFileName);

        XmlOrderedResult xmlOrderedResult = isPomElementsSorted();
        if (!xmlOrderedResult.isOrdered()) {
            switch (verifyFailType) {
                case WARN:
                    log.warn(xmlOrderedResult.getErrorMessage());
                    saveViolationFile(xmlOrderedResult);
                    log.warn(String.format(TEXT_FILE_NOT_SORTED, pomFileName));
                    break;
                case SORT:
                    log.info(xmlOrderedResult.getErrorMessage());
                    saveViolationFile(xmlOrderedResult);
                    log.info(String.format(TEXT_FILE_NOT_SORTED, pomFileName));
                    sortPom();
                    break;
                case STOP:
                    log.error(xmlOrderedResult.getErrorMessage());
                    saveViolationFile(xmlOrderedResult);
                    log.error(String.format(TEXT_FILE_NOT_SORTED, pomFileName));
                    throw new FailureException(String.format(TEXT_FILE_NOT_SORTED, pomFileName));
            }
        }
    }
336528
private boolean hasPrintedPackageIndex(PackageElement pkg) {
        for (PackageElement printedPkg : printedPackageHeaders) {
            if (utils.getPackageName(pkg).startsWith(utils.parsePackageName(printedPkg))) {
                return true;
            }
        }
        return false;
    }
1299466
def sort(ctx):
    """"""
    head = ctx.parent.head
    vcf_handle = ctx.parent.handle
    outfile = ctx.parent.outfile
    silent = ctx.parent.silent

    print_headers(head, outfile=outfile, silent=silent)

    for line in sort_variants(vcf_handle):
        print_variant(variant_line=line, outfile=outfile, silent=silent)
691191
function prepareSortOrder ( pkg ) {
	const index = SORT_ORDER.indexOf('repository');
	const unknownKeys = difference(Object.keys(pkg), SORT_ORDER).sort();
	return flatten(insert(SORT_ORDER, index, unknownKeys));
}
991186
def verify_jar_checksums(self, jar_file, strict=True):
        

        verify_failures = []

        zip_file = ZipFile(jar_file)
        for filename in zip_file.namelist():
            if file_skips_verification(filename):
                continue

            file_section = self.create_section(filename, overwrite=False)

            digests = file_section.keys_with_suffix("-Digest")
            if not digests and strict:
                verify_failures.append(filename)
                continue

            for java_digest in digests:
                read_digest = file_section.get(java_digest + "-Digest")
                calculated_digest = b64_encoded_digest(
                    zip_file.read(filename),
                    _get_digest(java_digest))

                if calculated_digest == read_digest:
                    # found a match
                    break
            else:
                # for all the digests, not one of them matched. Add
                # this filename to the error list
                verify_failures.append(filename)

        return verify_failures
29527
def sort_by_dependencies(exts, retry=None):
    
    sorted_ext, features_from_sorted = [], set()
    pending = [(e, 0) for e in exts]
    retry = len(exts) * 100 if retry is None else retry
    while pending:
        ext, cnt = pending.pop(0)

        if not isinstance(ext, Extractor) and not issubclass(ext, Extractor):
            msg = "Only Extractor instances are allowed. Found {}."
            raise TypeError(msg.format(type(ext)))

        deps = ext.get_dependencies()
        if deps.difference(features_from_sorted):
            if cnt + 1 > retry:
                msg = "Maximun retry ({}) to sort achieved from extractor {}."
                raise RuntimeError(msg.format(retry, type(ext)))
            pending.append((ext, cnt + 1))
        else:
            sorted_ext.append(ext)
            features_from_sorted.update(ext.get_features())
    return tuple(sorted_ext)
1008821
boolean foundGroupFormat(Map<String,?> map, String pkgFormat) {
        if (map.containsKey(pkgFormat)) {
            configuration.message.error("doclet.Same_package_name_used", pkgFormat);
            return true;
        }
        return false;
    }
177163
def stat_sorted_tree_with_dependencies(dir)
      deps = Set.new([build_file_digest_uri(dir)])
      results = stat_sorted_tree(dir).map do |path, stat|
        deps << build_file_digest_uri(path) if stat.directory?
        [path, stat]
      end
      return results, deps
    end
290791
@Override
    protected boolean shouldExecutionBeSkipped() {

        boolean toReturn = false;

        if ("pom".equalsIgnoreCase(getProject().getPackaging())) {
            warnAboutIncorrectPluginConfiguration("packaging", "POM-packaged projects should not generate XSDs.");
            toReturn = true;
        }

        if (getSources().isEmpty()) {
            warnAboutIncorrectPluginConfiguration("sources", "At least one Java Source file has to be included.");
            toReturn = true;
        }

        // All done.
        return toReturn;
    }
1035021
def ProcessLine(filename, linenumber, clean_lines, errors):
    
    CheckLintPragma(filename, linenumber, clean_lines.raw_lines[linenumber], errors)
    CheckLineLength(filename, linenumber, clean_lines, errors)
    CheckUpperLowerCase(filename, linenumber, clean_lines, errors)
    CheckStyle(filename, linenumber, clean_lines, errors)
    if IsFindPackage(filename):
        CheckFindPackage(filename, linenumber, clean_lines, errors)
154628
def __priority(self, pr, repo, pkg):
        
        if (pr[0] == repo and pr[1].startswith("*") and
                pr[1].endswith("*")):
            if pr[1][1:-1] in pkg:
                self.black.append(self.__add(repo, pkg))
        elif pr[0] == repo and pr[1].endswith("*"):
            if pkg.startswith(pr[1][:-1]):
                self.black.append(self.__add(repo, pkg))
        elif pr[0] == repo and pr[1].startswith("*"):
            if pkg.endswith(pr[1][1:]):
                self.black.append(self.__add(repo, pkg))
        elif pr[0] == repo and "*" not in pr[1]:
            self.black.append(self.__add(repo, pkg))
783533
def get_pom_from_heuristic(filename)
      begin
        log.debug("Attempting heuristic POM search for #{filename}")
        site = MavenWebsite.new
        filename = cleanup_name(filename)
        version_matcher = VersionMatcher.new
        my_artifact_id, my_version = version_matcher.split_version(filename)
        log.debug("Guessed artifact id: #{my_artifact_id}, version: #{my_version}")

        result = site.search_by_name(my_artifact_id).first
        log.debug("Artifact id search result: #{result}")
        unless result.nil?
          group_id, artifact_id, = site.get_maven_id_from result
          results = site.search_by_group_id_and_artifact_id(group_id, artifact_id)
          log.debug("All versions: #{results}")
          their_versions = results.map { |doc| doc["v"] }
          best_matched_version = (
            if !my_version.nil?
              version_matcher.best_match(my_version, their_versions)
            else
              their_versions.max
            end
          )
          best_matched_result = (results.select { |r| r["v"] == best_matched_version }).first

          group_id, artifact_id, version = site.get_maven_id_from(best_matched_result)
          log.warn("pom.xml for #{filename} found on search.maven.org with heuristic search\
            (#{group_id}:#{artifact_id}:#{version})"
                  )

          return site.download_pom(group_id, artifact_id, version), :found_via_heuristic
        end
      rescue NotFoundOnMavenWebsiteError
        log.warn("Got a 404 error while looking for #{filename} heuristically in search.maven.org")
      end
      nil
    end
1257986
function sortByFileFormat(srcDir, format) {
  const initialFiles = `${srcDir}/*.${format}`
  const files = glob.sync(initialFiles);
  const dest = `${srcDir}/${format}`;
  let count = 0;

  createDirs([dest]);

  // Loop through and move each file
  const promises = files.map(f => {
    return new Promise((resolve, reject) => {
      const filename = sanitize(path.basename(f));
      const reg = /[\w-]+-(16|24|32)\.[\w]+/;
      const match = filename.match(reg);
      let thisDest = dest;

      if (match) {
        const size = match[1];
        thisDest = `${thisDest}/${size}`;
        createDirs([thisDest]);
      }

      fs.rename(f, `${thisDest}/${filename}`, err => {
        if (err) {
          reject(err);
        }
        count++;
        resolve(`${dest}/${filename}`);
      });
    });
  });

  return Promise.all(promises).then(() => {
    swlog.logTaskAction('Moved', `${count}/${files.length} ${format.toUpperCase()} files`);
  });
}
458165
public void execute() throws MojoExecutionException, MojoFailureException {
    if (skip) {
      getLog().info("Skipping format check");
      return;
    }
    if ("pom".equals(packaging)) {
      getLog().info("Skipping format check: project uses 'pom' packaging");
      return;
    }
    if (skipSortingImports) {
      getLog().info("Skipping sorting imports");
    }
    List<File> directoriesToFormat = new ArrayList<File>();
    if (sourceDirectory.exists()) {
      directoriesToFormat.add(sourceDirectory);
    } else {
      handleMissingDirectory("Source", sourceDirectory);
    }
    if (testSourceDirectory.exists()) {
      directoriesToFormat.add(testSourceDirectory);
    } else {
      handleMissingDirectory("Test source", testSourceDirectory);
    }

    for (File additionalSourceDirectory : additionalSourceDirectories) {
      if (additionalSourceDirectory.exists()) {
        directoriesToFormat.add(additionalSourceDirectory);
      } else {
        handleMissingDirectory("Additional source", additionalSourceDirectory);
      }
    }

    Formatter formatter = getFormatter();

    for (File directoryToFormat : directoriesToFormat) {
      formatSourceFilesInDirectory(directoryToFormat, formatter);
    }

    logNumberOfFilesProcessed();
    postExecute(this.filesProcessed, this.nonComplyingFiles);
  }
1104597
function numberedVersionData(version) {
  // A version has a numbered part and a modifier part
  // (eg, 1.0.0-patch, 2.0.x-dev).
  const parts = version.split('-')
  const numbered = parts[0]

  // Aliases that get caught here.
  if (numbered === 'dev') {
    return {
      numbers: parts[1],
      modifier: 5,
      modifierCount: 1,
    }
  }

  let modifierLevel = 3
  let modifierLevelCount = 0

  if (parts.length > 1) {
    const modifier = parts[parts.length - 1]
    const firstLetter = modifier.charCodeAt(0)
    let modifierLevelCountString

    // Modifiers: alpha < beta < RC < normal < patch < dev
    if (firstLetter === 97) {
      // a
      modifierLevel = 0
      if (/^alpha/.test(modifier)) {
        modifierLevelCountString = +modifier.slice(5)
      } else {
        modifierLevelCountString = +modifier.slice(1)
      }
    } else if (firstLetter === 98) {
      // b
      modifierLevel = 1
      if (/^beta/.test(modifier)) {
        modifierLevelCountString = +modifier.slice(4)
      } else {
        modifierLevelCountString = +modifier.slice(1)
      }
    } else if (firstLetter === 82) {
      // R
      modifierLevel = 2
      modifierLevelCountString = +modifier.slice(2)
    } else if (firstLetter === 112) {
      // p
      modifierLevel = 4
      if (/^patch/.test(modifier)) {
        modifierLevelCountString = +modifier.slice(5)
      } else {
        modifierLevelCountString = +modifier.slice(1)
      }
    } else if (firstLetter === 100) {
      // d
      modifierLevel = 5
      if (/^dev/.test(modifier)) {
        modifierLevelCountString = +modifier.slice(3)
      } else {
        modifierLevelCountString = +modifier.slice(1)
      }
    }

    // If we got the empty string, it defaults to a modifier count of 1.
    if (!modifierLevelCountString) {
      modifierLevelCount = 1
    } else {
      modifierLevelCount = +modifierLevelCountString
    }
  }

  // Try to convert to a list of numbers.
  function toNum(s) {
    let n = +s
    if (Number.isNaN(n)) {
      n = 0xffffffff
    }
    return n
  }
  const numberList = numbered.split('.').map(toNum)

  return {
    numbers: numberList,
    modifier: modifierLevel,
    modifierCount: modifierLevelCount,
  }
}
565252
def sortedSemver(versions, sort="asc"):
    """"""
    if versions and isinstance(versions, (list, tuple)):
        if PY2:
            return sorted(versions, cmp=semver.compare, reverse=True if sort.upper() == "DESC" else False)
        else:
            from functools import cmp_to_key
            return sorted(versions, key=cmp_to_key(semver.compare), reverse=True if sort.upper() == "DESC" else False)
    else:
        raise TypeError("Invaild Versions, a list or tuple is right.")
131446
def sort_permutations(permutations, user_deps)
      # Cache for versions converted to Gem::Version instances
      versions = {}

      map = lambda do |m, p|
        if p =~ Lyp::PACKAGE_RE
          m[$1] = versions[p] ||= (Lyp.version($2 || '0.0') rescue nil)
        end
        m
      end

      compare = lambda do |x, y|
        x_versions = x.inject({}, &map)
        y_versions = y.inject({}, &map)

        # If the dependency is direct (not transitive), just compare its versions.
        # Otherwise, add the result of comparison to score.
        x_versions.inject(0) do |score, kv|
          package = kv[0]
          cmp = kv[1] <=> y_versions[package]
          if user_deps.include?(package) && cmp != 0
            return cmp
          else
            score += cmp unless cmp.nil?
          end
          score
        end
      end

      permutations.sort(&compare)
    end