We assume that having wrong versions of these in the tree will likely break your setup. This is a relatively low-effort way to find common issues.
358663
function verifyPackageTree() {
  const depsToCheck = [
    // These are packages most likely to break in practice.
    // See https://github.com/echo008/xmi/issues/1795 for reasons why.
    // I have not included Babel here because plugins typically don't import Babel (so it's not affected).
    'babel-eslint',
    'babel-jest',
    'babel-loader',
    'eslint',
    'jest',
    'webpack',
    'webpack-dev-server',
  ];
  // Inlined from semver-regex, MIT license.
  // Don't want to make this a dependency after ejecting.
  const getSemverRegex = () =>
    /\bv?(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[\da-z-]+(?:\.[\da-z-]+)*)?(?:\+[\da-z-]+(?:\.[\da-z-]+)*)?\b/gi;
  const ownPackageJson = require('../../package.json');
  const expectedVersionsByDep = {};
  // Gather wanted deps
  depsToCheck.forEach(dep => {
    const expectedVersion = ownPackageJson.dependencies[dep];
    if (!expectedVersion) {
      throw new Error('This dependency list is outdated, fix it.');
    }
    if (!getSemverRegex().test(expectedVersion)) {
      throw new Error(
        `The ${dep} package should be pinned, instead got version ${expectedVersion}.`
      );
    }
    expectedVersionsByDep[dep] = expectedVersion;
  });
  // Verify we don't have other versions up the tree
  let currentDir = __dirname;
  // eslint-disable-next-line no-constant-condition
  while (true) {
    const previousDir = currentDir;
    currentDir = path.resolve(currentDir, '..');
    if (currentDir === previousDir) {
      // We've reached the root.
      break;
    }
    const maybeNodeModules = path.resolve(currentDir, 'node_modules');
    if (!fs.existsSync(maybeNodeModules)) {
      continue;
    }
    depsToCheck.forEach(dep => {
      const maybeDep = path.resolve(maybeNodeModules, dep);
      if (!fs.existsSync(maybeDep)) {
        return;
      }
      const maybeDepPackageJson = path.resolve(maybeDep, 'package.json');
      if (!fs.existsSync(maybeDepPackageJson)) {
        return;
      }
      const depPackageJson = JSON.parse(
        fs.readFileSync(maybeDepPackageJson, 'utf8')
      );
      const expectedVersion = expectedVersionsByDep[dep];
      if (depPackageJson.version !== expectedVersion) {
        console.error(
          chalk.red(
            `\nThere might be a problem with the project dependency tree.\n` +
              `It is likely ${chalk.bold(
                'not'
              )} a bug in Create React App, but something you need to fix locally.\n\n`
          ) +
            `The ${chalk.bold(
              ownPackageJson.name
            )} package provided by Create React App requires a dependency:\n\n` +
            chalk.green(
              `  "${chalk.bold(dep)}": "${chalk.bold(expectedVersion)}"\n\n`
            ) +
            `Don't try to install it manually: your package manager does it automatically.\n` +
            `However, a different version of ${chalk.bold(
              dep
            )} was detected higher up in the tree:\n\n` +
            `  ${chalk.bold(chalk.red(maybeDep))} (version: ${chalk.bold(
              chalk.red(depPackageJson.version)
            )}) \n\n` +
            `Manually installing incompatible versions is known to cause hard-to-debug issues.\n\n` +
            chalk.red(
              `If prefer to ignore this check, add ${chalk.bold(
                'SKIP_PREFLIGHT_CHECK=true'
              )} to an ${chalk.bold('.env')} file in your project.\n` +
                `That will permanently disable this message but you might encounter other issues.\n\n`
            ) +
            `To ${chalk.green(
              'fix'
            )} the dependency tree, try following the steps below in the exact order:\n\n` +
            `  ${chalk.cyan('1.')} Delete ${chalk.bold(
              'package-lock.json'
            )} (${chalk.underline('not')} ${chalk.bold(
              'package.json'
            )}!) and/or ${chalk.bold('yarn.lock')} in your project folder.\n` +
            `  ${chalk.cyan('2.')} Delete ${chalk.bold(
              'node_modules'
            )} in your project folder.\n` +
            `  ${chalk.cyan('3.')} Remove "${chalk.bold(
              dep
            )}" from ${chalk.bold('dependencies')} and/or ${chalk.bold(
              'devDependencies'
            )} in the ${chalk.bold(
              'package.json'
            )} file in your project folder.\n` +
            `  ${chalk.cyan('4.')} Run ${chalk.bold(
              'npm install'
            )} or ${chalk.bold(
              'yarn'
            )}, depending on the package manager you use.\n\n` +
            `In most cases, this should be enough to fix the problem.\n` +
            `If this has not helped, there are a few other things you can try:\n\n` +
            `  ${chalk.cyan('5.')} If you used ${chalk.bold(
              'npm'
            )}, install ${chalk.bold(
              'yarn'
            )} (http://yarnpkg.com/) and repeat the above steps with it instead.\n` +
            `     This may help because npm has known issues with package hoisting which may get resolved in future versions.\n\n` +
            `  ${chalk.cyan('6.')} Check if ${chalk.bold(
              maybeDep
            )} is outside your project directory.\n` +
            `     For example, you might have accidentally installed something in your home folder.\n\n` +
            `  ${chalk.cyan('7.')} Try running ${chalk.bold(
              `npm ls ${dep}`
            )} in your project folder.\n` +
            `     This will tell you which ${chalk.underline(
              'other'
            )} package (apart from the expected ${chalk.bold(
              ownPackageJson.name
            )}) installed ${chalk.bold(dep)}.\n\n` +
            `If nothing else helps, add ${chalk.bold(
              'SKIP_PREFLIGHT_CHECK=true'
            )} to an ${chalk.bold('.env')} file in your project.\n` +
            `That would permanently disable this preflight check in case you want to proceed anyway.\n\n` +
            chalk.cyan(
              `P.S. We know this message is long but please read the steps above :-) We hope you find them helpful!\n`
            )
        );
        process.exit(1);
      }
    });
  }
}
96147
def missing_dependencies
      missing = []
      dependency_versions(:recursive => false).each do |pkg, target_versions|
        found = false
        target_versions.each do |_target, versions|
          dependency = dependency_for(pkg)
          found = versions.any? { |version| dependency.match?(pkg, version) }
        end
        missing << pkg unless found
      end
      missing
    end
155189
def is_single_tree(data_wrapper):
    '''
    '''
    db = data_wrapper.data_block
    bad_ids = db[db[:, COLS.P] == -1][1:, COLS.ID]
    return CheckResult(len(bad_ids) == 0, bad_ids.tolist())
1012438
private void check(MappingNode tree, MappingNode parent, String prefix) {
        MappingNode child = parent.getLeftMostChild();
        MappingNode sibling = null;
        while (child != null) {
            if (sibling != null) {
                if (child.compareTo(sibling) == 0) {
                    logger.error("mapping conflicts: '" + child.getMapping().getDefinition()
                            + "' conflicts with '" + sibling.getMapping().getDefinition()
                            + "' in '" + prefix + "'; here is the mapping tree, "
                            + "you can find the conflict in it:\n" + PrinteHelper.list(tree));
                    throw new IllegalArgumentException("mapping conflicts: '"
                            + child.getMapping().getDefinition() + "' conflicts with '"
                            + sibling.getMapping().getDefinition() + "' in '" + prefix + "'");
                }
            }
            check(tree, child, prefix + child.getMapping().getDefinition());
            sibling = child;
            child = child.getSibling();
        }

    }
856782
@SuppressWarnings("unchecked")
    private void bindUniqueSubConfigurations() {
        for (ConfigPath item : tree.getUniqueTypePaths()) {
            // bind only with annotation to avoid clashes with direct bindings
            toValue(
                    bind(Key.get(item.getDeclaredTypeWithGenerics(), Config.class)),
                    item.getValue());
        }
    }
656589
def fix_bad_headers(self):
        
        # WCSLIB doesn't like "nonstandard" units
        unit = self.header.get('CUNIT1', 'deg')
        if unit.upper() == 'DEGREE':
            # self.header.update('CUNIT1', 'deg')
            self.header['CUNIT1'] = 'deg'
        unit = self.header.get('CUNIT2', 'deg')
        if unit.upper() == 'DEGREE':
            # self.header.update('CUNIT2', 'deg')
            self.header['CUNIT2'] = 'deg'
433669
private static boolean ensureVersion(Version existing, Version expected) {
        return existing != Version.UNDEFINED && existing.greaterThanOrEqualTo(expected);
    }
591827
def fix_tree(tree, a_id_lookup, out):
    
    if check(out) is False and check(tree) is True:
        tree = open(tree).read()
        for line in open(a_id_lookup):
            id, name, header = line.strip().split('\t')
            tree = tree.replace(id+':', name+':')
        out_f = open(out, 'w')
        print(tree.strip(), file=out_f)
    return out
767177
public boolean canTraverseOutsideSubtree()
  {

    if (null != m_parts)
    {
      int n = m_parts.size();

      for (int i = 0; i < n; i++)
      {
        AVTPart part = (AVTPart) m_parts.elementAt(i);

        if (part.canTraverseOutsideSubtree())
          return true;
      }
    }

    return false;
  }
715808
def merge_reference_trees(roots)
      roots.inject(empty_forest) do |forest, root|
        root.keys do |full_key, node|
          if full_key == node.value.to_s
            log_warn(
              "Self-referencing key #{node.full_key(root: false).inspect} in #{node.data[:locale].inspect}"
            )
          end
        end
        forest.merge!(
          root.children,
          on_leaves_merge: lambda do |node, other|
            if node.value != other.value
              log_warn(
                'Conflicting references: '\
            "#{node.full_key(root: false)} ⮕ #{node.value} in #{node.data[:locale]},"\
            " but ⮕ #{other.value} in #{other.data[:locale]}"
              )
            end
          end
        )
      end
    end
1123977
public function rebuildtree() {
		//Rebuild nested set - get cat
		BLog::addToLog('[Items] rebuilding nested sets...');


		$db = \Brilliant\BFactory::getDBO();
		if (empty($db)) {
			return false;
			}
		$r = $db->query('LOCK TABLES `'.$this->tableName.'` WRITE');
		if(!$r){
			BLog::addToLog('[Items] Could not lock table!',LL_ERROR);
			}
		//
		BLog::addToLog('[Items] Invalidating cache...');
		$bcache = \Brilliant\BFactory::getCache();
		if ($bcache) {
			$bcache->invalidate();
			}
		//
		BLog::addToLog('[Items] Get root cats...');
		//
		$catsCount = $this->itemsFilterCount(array());
		BLog::addToLog('[Items] Total categories count:' . $catsCount . '...');
		//
		$rootCatsCount = $this->itemsFilterCount(array('parentisnull'=>true));
		BLog::addToLog('[Items] Root categories count:' . $rootCatsCount. '...');
		//Go th
		$rootCatsOffset = 0;
		while($rootCatsOffset < $rootCatsCount) {
			$paramsRoot = array();
			$paramsRoot['parentisnull']=true;
			$paramsRoot['orderby']='created';
			$paramsRoot['orderdir']='asc';
			$paramsRoot['offset']=$rootCatsOffset;
			$paramsRoot['limit']=1;
			$rootcats = $this->itemsFilter($paramsRoot);
			if(count($rootcats)!=1){
				BLog::addToLog('[Items] Root Category error!',LL_ERROR);
				}
			$rcat = reset($rootcats);
			$groupId = $rcat->getGroupId();
			//
			BLog::addToLog('[Items] Processing group #' . $groupId . ', root = ' . $rcat->id . '...');
			//
			$paramsAll=array();
			$paramsAll['group']=$groupId;
			//$paramsAll['parenttree_lft']
			//$paramsAll['parenttree_rgt']
			$catslist = $this->itemsFilter($paramsAll);


			//Foreach by root categories...
			$rcat->level = 0;
			$lft = 1;
			$rgt = 2;
			$this->rebuildtree_recursive($rcat, $lft, $rgt);
			$rcat->lft = 1;
			$rcat->rgt = $rgt;
			BLog::addToLog('[Items] Updating nested set...');
			foreach ($catslist as $ct) {
				$qr = 'UPDATE `' . $this->tableName . '` set `' . $this->leftKeyName . '`=' . $ct->lft . ', `' . $this->rightKeyName . '`=' . $ct->rgt . ', `' . $this->levelKeyName . '`=' . $ct->level . ' WHERE `' . $this->primaryKeyName . '`=' . $ct->id;
				$q = $db->query($qr);
				if (empty($q)) {
					return false;
					}
				}
			$rootCatsOffset+=1;
			//Invalidate cache after each group...
			$bcache = \Brilliant\BFactory::getCache();
			if ($bcache) {
				$bcache->invalidate();
				}
			}
		return true;
		}
1195905
function () {
      var getConflictingDependencies = function (dependencies) {
        var conflicts = [];
        if (!dependencies) {
          return conflicts;
        }
        // for each dependency, extract and check the qualified artifactId
        dependencies.forEach(function (dependency) {
          function filterByDependencyString (dep) {
            return typeof dependency === 'string' ? dependency === dep : _.isEqual(dependency, dep);
          }

          var arrayOfEqualDependencies = dependencies.filter(
            filterByDependencyString);

          // find dependency in conflicts if dependency is n object
          var findedDep;
          if (typeof dependency === 'object') {
            findedDep = conflicts.find(function (dep) {
              return dep.artifactId === dependency.artifactId && dep.webpackageId === dependency.webpackageId && dep.endpointId === dependency.endpointId;
            });
          }
          if (arrayOfEqualDependencies.length > 1 && conflicts.indexOf(dependency) < 0 && !findedDep) {
            conflicts.push(dependency);
          }
        });
        return conflicts;
      };

      var doUniqueDependenciesCheck = function (artifact) {
        var conflictingDependencies = [];
        if (doc.modelVersion.indexOf('8.') === 0) { // we do have at least one endpoints for each artifact (modelVersion 8.x.x)
          // for each artifacts endpoint, check it's dependencies
          artifact.endpoints.forEach(function (endpoint) {
            conflictingDependencies = endpoint.dependencies ? getConflictingDependencies(endpoint.dependencies) : [];

            conflictingDependencies.forEach(function (dependency) {
              errors.push('RuleViolation identified: Artifact \'' + artifact.artifactId + '\' / endpoint \'' +
                endpoint.endpointId + '\' contains multiple references to dependency \'' + dependency +
                '\'');
            });
          });
        } else { // we don't have endpoints in artifact (modelVersion 9.x.x)
          // for each artifact, check it's dependencies
          conflictingDependencies = artifact.dependencies ? getConflictingDependencies(artifact.dependencies) : [];

          conflictingDependencies.forEach(function (dependency) {
            var dependencyStr = typeof dependency === 'object' ? JSON.stringify(dependency) : dependency;
            errors.push('RuleViolation identified: Artifact \'' + artifact.artifactId +
              '\' contains multiple references to dependency \'' + dependencyStr + '\'');
          });
        }
      };
      //
      var allArtifacts = [];
      // collect artifacts
      if (doc.artifacts) {
        var artifactTypes = Object.keys(doc.artifacts);
        artifactTypes.forEach(function (artifactType) {
          allArtifacts = allArtifacts.concat(doc.artifacts[ artifactType ]);
        });
      }
      // call rule for each artifact
      allArtifacts.forEach(function (artifact) {
        if (artifact.endpoints || artifact.dependencies) {
          doUniqueDependenciesCheck(artifact);
        }
      });
    }
1335287
function CompareTreeModel(rootPath, fetchItems, root) {
		this.rootPath = rootPath;
		this.fetchItems = fetchItems;
		this.root = root;
	}
374129
private void autoSelectVersionAndError() {
		if (qr.version == -1) {
			QrCode.ErrorLevel levelsToTry[];
			if (autoErrorCorrection) {
				// this is a reasonable compromise between robustness and data storage
				levelsToTry = new QrCode.ErrorLevel[]{QrCode.ErrorLevel.M,QrCode.ErrorLevel.L};
			} else {
				levelsToTry = new QrCode.ErrorLevel[]{qr.error};
			}
			escape:for( QrCode.ErrorLevel error : levelsToTry ) {
				qr.error = error;
				// select the smallest version which can store all the data
				for (int i = 1; i <= 40; i++) {
					int dataBits = bitsAtVersion(i);
					int totalBytes = dataBits / 8 + (dataBits % 8) % 8;
					if (totalBytes <= QrCode.VERSION_INFO[i].totalDataBytes(qr.error)) {
						qr.version = i;
						break escape;
					}
				}
			}
			if (qr.version == -1) {
				throw new IllegalArgumentException("Packet too to be encoded in a qr code");
			}
		} else {
			// the version is set but the error correction level isn't. Pick the one with
			// the most error correction that can which can store all the data
			if (autoErrorCorrection) {
				qr.error = null;
				QrCode.VersionInfo v = QrCode.VERSION_INFO[qr.version];
				int dataBits = bitsAtVersion(qr.version);
				int totalBytes = dataBits / 8 + (dataBits % 8) % 8;
				for (QrCode.ErrorLevel level : QrCode.ErrorLevel.values()) {
					if (totalBytes <= v.totalDataBytes(level)) {
						qr.error = level;
					}
				}
				if (qr.error == null) {
					throw new IllegalArgumentException("You need to use a high version number to store the data. Tried " +
							"all error correction levels at version " + qr.version + ". Total Data " + (packed.size / 8));
				}
			}
		}
		// Sanity check
		int dataBits = bitsAtVersion(qr.version);
		int totalBytes = dataBits / 8 + (dataBits % 8) % 8;
		QrCode.VersionInfo v = QrCode.VERSION_INFO[qr.version];
		if (totalBytes > v.totalDataBytes(qr.error)) {
			throw new IllegalArgumentException("Version and error level can't encode all the data");
		}
	}
550417
@PostConstruct
    public void checkUniqueSchemes() {
        Multimap<String, ConfigFileLoaderPlugin> schemeToPluginMap = HashMultimap.create();

        for (ConfigFileLoaderPlugin plugin: getLoaderPlugins()) {
            schemeToPluginMap.put(plugin.getUriScheme(), plugin);
        }

        StringBuilder violations = new StringBuilder();
        for (String scheme: schemeToPluginMap.keySet()) {
            final Collection<ConfigFileLoaderPlugin> plugins = schemeToPluginMap.get(scheme);
            if (plugins.size() > 1) {
                violations.append("\n\n* ").append("There are  has multiple ")
                        .append(ConfigFileLoaderPlugin.class.getSimpleName())
                        .append(" plugins that support the scheme: '").append(scheme).append('\'')
                        .append(":\n\t").append(plugins);
            }
        }

        if (violations.length() > 0) {
            throw new IllegalStateException(violations.toString());
        }
    }
1014949
def prune_tree_for_supertree(self,
                                 ott,
                                 to_prune_fsi_set,
                                 root_ott_id,
                                 taxonomy_treefile=None,
                                 id_to_other_prune_reason=None):
        
        if id_to_other_prune_reason is None:
            id_to_other_prune_reason = {}
        self.prune_to_ingroup()
        self.prune_unmapped_leaves()
        other_pruned = set()
        if id_to_other_prune_reason:
            id2p = set(id_to_other_prune_reason.keys()).intersection(set(self.by_ott_id.keys()))
            for ott_id in id2p:
                reason = id_to_other_prune_reason[ott_id]
                self.prune_ott_problem_leaves_by_id(ott_id, reason)
        # Check the stored OTT Ids against the current version of OTT
        mapped, unrecog, forward2unrecog, pruned, above_root, old2new = ott.map_ott_ids(self.by_ott_id.keys(),
                                                                                        to_prune_fsi_set, root_ott_id)
        for ott_id in unrecog:
            self.prune_ott_problem_leaves_by_id(ott_id, 'unrecognized_ott_id')
        for ott_id in forward2unrecog:
            self.prune_ott_problem_leaves_by_id(ott_id, 'forwarded_to_unrecognized_ott_id')
        for ott_id in pruned:
            self.prune_ott_problem_leaves_by_id(ott_id, 'flagged')
        for ott_id in above_root:
            self.prune_ott_problem_leaves_by_id(ott_id, 'above_root')
        for old_id, new_id in old2new.items():
            old_node_list = self.by_ott_id[old_id]
            del self.by_ott_id[old_id]
            if new_id in self.by_ott_id:
                v = self.by_ott_id[new_id]
                v.extend(old_node_list)
                v.sort() # I think only the last step requires sorting (NEED to check that,
                         # If so, we could move this sort to that point to avoid multiple sortings.
            else:
                self.by_ott_id[new_id] = old_node_list
            for sortable_el in old_node_list:
                otu = sortable_el[3]
                assert otu['^ot:ottId'] == old_id
                otu['^ot:ottId'] = new_id
                assert '^ot:ottTaxonName' in otu
                otu['^ot:ottTaxonName'] = ott.get_name(new_id)
        lost_tips = set(unrecog)
        lost_tips.update(forward2unrecog)
        lost_tips.update(pruned)
        lost_tips.update(other_pruned)
        # Get the induced tree...
        assert self.root_node_id
        try:
            ott_tree = ott.induced_tree(mapped, create_monotypic_nodes=True)
        except SpikeTreeError:
            error('SpikeTreeError from mapped ott_id list = {}'.format(', '.join([str(i) for i in mapped])))
            raise EmptyTreeError()
        if taxonomy_treefile is not None:
            with codecs.open(taxonomy_treefile, 'w', encoding='utf-8') as tto:
                ott_tree.write_newick(tto)
        # ... so that we can look for leaves mapped to ancestors of other leaves
        taxon_contains_other_ott_ids = []
        to_retain = []
        for ott_id in self.by_ott_id:
            if ott_id in lost_tips:
                continue
            n = old2new.get(ott_id)
            if n is None:
                n = ott_id
            nd = ott_tree.find_node(n)
            assert nd is not None
            if nd.children:
                # nd must be an internal node.
                #   given that the descendants of this node are mapped in a more specific
                #   way, we will prune this ott_id from the tree
                taxon_contains_other_ott_ids.append(ott_id)
            else:
                to_retain.append(ott_id)

        for ott_id in taxon_contains_other_ott_ids:
            self.prune_ott_problem_leaves_by_id(ott_id, 'mapped_to_taxon_containing_other_mapped_tips')
        # finally, we walk through any ott_id's mapped to multiple nodes
        for ott_id in to_retain:
            nm = self.by_ott_id[ott_id]
            if len(nm) > 1:
                el = nm.pop(0)
                reason = 'replaced_by_exemplar_node' if (el[0] == -1) else 'replaced_by_arbitrary_node'
                self.prune_ott_problem_leaves_by_id(ott_id, reason)
        return self
789772
def _reuse_pre_installed_setuptools(env, installer):
    
    if not env.setuptools_version:
        return  # no prior setuptools ==> no reuse
    reuse_old = config.reuse_old_setuptools
    reuse_best = config.reuse_best_setuptools
    reuse_future = config.reuse_future_setuptools
    reuse_comment = None
    if reuse_old or reuse_best or reuse_future:
        pv_old = parse_version(env.setuptools_version)
        pv_new = parse_version(installer.setuptools_version())
        if pv_old < pv_new:
            if reuse_old:
                reuse_comment = "%s+ recommended" % (
                    installer.setuptools_version(),)
        elif pv_old > pv_new:
            if reuse_future:
                reuse_comment = "%s+ required" % (
                    installer.setuptools_version(),)
        elif reuse_best:
            reuse_comment = ""
    if reuse_comment is None:
        return  # reuse not allowed by configuration
    if reuse_comment:
        reuse_comment = " (%s)" % (reuse_comment,)
    print("Reusing pre-installed setuptools %s distribution%s." % (
        env.setuptools_version, reuse_comment))
    return True