Strategy directly computes dependency graph node based on
    `classes_by_source`, `runtime_classpath`, `product_deps_by_src` parameters and
    stores the result to the build cache.
6520
def calculating_node_creator(self, classes_by_source, runtime_classpath, product_deps_by_src,
                               target_to_vts):
    
    analyzer = JvmDependencyAnalyzer(get_buildroot(), runtime_classpath)
    targets = self.context.targets()
    targets_by_file = analyzer.targets_by_file(targets)
    transitive_deps_by_target = analyzer.compute_transitive_deps_by_target(targets)
    def creator(target):
      transitive_deps = set(transitive_deps_by_target.get(target))
      node = self.create_dep_usage_node(target,
                                        analyzer,
                                        product_deps_by_src,
                                        classes_by_source,
                                        targets_by_file,
                                        transitive_deps)
      vt = target_to_vts[target]
      mode = 'w' if PY3 else 'wb'
      with open(self.nodes_json(vt.results_dir), mode=mode) as fp:
        json.dump(node.to_cacheable_dict(), fp, indent=2, sort_keys=True)
      vt.update()
      return node

    return creator
55834
def compute_dependency_specs(cls, kwargs=None, payload=None):
    """"""
    for spec in super(ImportRemoteSourcesMixin, cls).compute_dependency_specs(kwargs, payload):
      yield spec

    imported_target_specs = cls.imported_target_specs(kwargs=kwargs, payload=payload)
    for spec in imported_target_specs:
      yield spec
731946
def create_dag(self, dependencies):
        
        dag = DirectedGraph()
        for dep in dependencies:
            for vertex in dep.inputs:
                task_uuid = vertex.private_task_config.uuid
                if task_uuid not in self.uuid_dict:
                    raise ValueError('Task {}, which is an input of a task {}, is not part of the defined '
                                     'workflow'.format(vertex.__class__.__name__, dep.name))
                dag.add_edge(self.uuid_dict[task_uuid], dep)
            if not dep.inputs:
                dag.add_vertex(dep)
        return dag
1058936
def _maintain_dep_graph(self, p_todo):
        
        dep_id = p_todo.tag_value('id')
        # maintain dependency graph
        if dep_id:
            self._parentdict[dep_id] = p_todo
            self._depgraph.add_node(hash(p_todo))

            # connect all tasks we have in memory so far that refer to this
            # task
            for dep in \
                    [dep for dep in self._todos if dep.has_tag('p', dep_id)]:

                self._add_edge(p_todo, dep, dep_id)

        for dep_id in p_todo.tag_values('p'):
            try:
                parent = self._parentdict[dep_id]
                self._add_edge(parent, p_todo, dep_id)
            except KeyError:
                pass
1277520
def make_dep_graph(depender):
	
	shutit_global.shutit_global_object.yield_to_draw()
	digraph = ''
	for dependee_id in depender.depends_on:
		digraph = (digraph + '"' + depender.module_id + '"->"' + dependee_id + '";\n')
	return digraph
1161004
private Map<String, Map<String, Set<String>>> getDependencies(Context context,
                                                                  Collection<JavaFileObject> explicitJFOs,
                                                                  boolean cp) {
        Map<String, Map<String, Set<String>>> result = new HashMap<>();

        for (CompletionNode cnode : getDependencyNodes(context, explicitJFOs, true)) {

            String fqDep = cnode.getClassSymbol().outermostClass().flatname.toString();
            String depPkg = Util.pkgNameOfClassName(fqDep);

            Map<String, Set<String>> depsForThisClass = result.get(depPkg);
            if (depsForThisClass == null) {
                result.put(depPkg, depsForThisClass = new HashMap<>());
            }

            Set<String> fqDeps = depsForThisClass.get(fqDep);
            if (fqDeps == null) {
                depsForThisClass.put(fqDep, fqDeps = new HashSet<>());
            }

            for (Node<?,?> depNode : getAllDependencies(cnode)) {
                CompletionNode cDepNode = (CompletionNode) depNode;
                // Symbol is not regarded to depend on itself.
                if (cDepNode == cnode) {
                    continue;
                }
                // Skip anonymous classes
                if (cDepNode.getClassSymbol().fullname == null) {
                    continue;
                }
                if (isSymbolRelevant(cp, cDepNode.getClassSymbol())) {
                    fqDeps.add(cDepNode.getClassSymbol().outermostClass().flatname.toString());
                }
            }

            // The completion dependency graph is not transitively closed for inheritance relations.
            // For sjavac's purposes however, a class depends on it's super super type, so below we
            // make sure that we include super types.
            for (ClassSymbol cs : allSupertypes(cnode.getClassSymbol())) {
                if (isSymbolRelevant(cp, cs)) {
                    fqDeps.add(cs.outermostClass().flatname.toString());
                }
            }

        }
        return result;
    }
556663
public void addDependencyGraph(DAGraph<DataT, NodeT> dependencyGraph) {
        this.rootNode.addDependency(dependencyGraph.rootNode.key());
        Map<String, NodeT> sourceNodeTable = dependencyGraph.nodeTable;
        Map<String, NodeT> targetNodeTable = this.nodeTable;
        this.merge(sourceNodeTable, targetNodeTable);
        dependencyGraph.parentDAGs.add(this);
        if (this.hasParents()) {
            this.bubbleUpNodeTable(this, new LinkedList<String>());
        }
    }
583408
function processSource(code, dependencyList, depedencyName) {
    // Replace function declarations
    const packageName = dependencyList[depedencyName].packageName;
    code = code.replace(/(\s*)function\s([A-z]*)\s*\(*/g, `$1function ${packageName}_$2(`);

    // TODO replace function calls to dependencies
    const dependencies = dependencyList[depedencyName].dependencies;
    if (dependencies) {
        for (const dependency of Reflect.ownKeys(dependencies)) {
            const oldPrefix = dependencyList[dependency].packageName;
            console.log(oldPrefix);
            var re = new RegExp(`[ ]*${oldPrefix}_([A-z]*)[ ]*\\(`, "g");
            code = code.replace(re, ` ${dependency}_$1(`);
        }
    }
    return code;
}
346468
def _store_graph_parts(self, graph: BELGraph, use_tqdm: bool = False) -> Tuple[List[Node], List[Edge]]:
        
        log.debug('inserting %s into edge store', graph)
        log.debug('building node models')
        node_model_build_start = time.time()

        nodes = list(graph)
        if use_tqdm:
            nodes = tqdm(nodes, total=graph.number_of_nodes(), desc='nodes')

        node_model = {}
        for node in nodes:
            namespace = node.get(NAMESPACE)

            if graph.skip_storing_namespace(namespace):
                continue  # already know this node won't be cached

            node_object = self.get_or_create_node(graph, node)

            if node_object is None:
                log.warning('can not add node %s', node)
                continue

            node_model[node] = node_object

        node_models = list(node_model.values())
        log.debug('built %d node models in %.2f seconds', len(node_models), time.time() - node_model_build_start)

        node_model_commit_start = time.time()
        self.session.add_all(node_models)
        self.session.commit()
        log.debug('stored %d node models in %.2f seconds', len(node_models), time.time() - node_model_commit_start)

        log.debug('building edge models')
        edge_model_build_start = time.time()

        edges = graph.edges(keys=True, data=True)
        if use_tqdm:
            edges = tqdm(edges, total=graph.number_of_edges(), desc='edges')

        edge_models = list(self._get_edge_models(graph, node_model, edges))

        log.debug('built %d edge models in %.2f seconds', len(edge_models), time.time() - edge_model_build_start)

        edge_model_commit_start = time.time()
        self.session.add_all(edge_models)
        self.session.commit()
        log.debug('stored %d edge models in %.2f seconds', len(edge_models), time.time() - edge_model_commit_start)

        return node_models, edge_models
1053839
def load(self):
        

        # reload from scratch to prevent duplication of renamed edges
        self.clear()

        # load primary key info
        keys = self._conn.query("""
                SELECT
                    concat('`', table_schema, '`.`', table_name, '`') as tab, column_name
                FROM information_schema.key_column_usage
                WHERE table_name not LIKE "~%%" AND table_schema in ('{schemas}') AND constraint_name="PRIMARY"
                """.format(schemas="','".join(self._conn.schemas)))
        pks = defaultdict(set)
        for key in keys:
            pks[key[0]].add(key[1])

        # add nodes to the graph
        for n, pk in pks.items():
            self.add_node(n, primary_key=pk)

        # load foreign keys
        keys = self._conn.query("""
        SELECT constraint_name,
            concat('`', table_schema, '`.`', table_name, '`') as referencing_table,
            concat('`', referenced_table_schema, '`.`',  referenced_table_name, '`') as referenced_table,
            column_name, referenced_column_name
        FROM information_schema.key_column_usage
        WHERE referenced_table_name NOT LIKE "~%%" AND (referenced_table_schema in ('{schemas}') OR
            referenced_table_schema is not NULL AND table_schema in ('{schemas}'))
        """.format(schemas="','".join(self._conn.schemas)), as_dict=True)
        fks = defaultdict(lambda: dict(attr_map=OrderedDict()))
        for key in keys:
            d = fks[(key['constraint_name'], key['referencing_table'], key['referenced_table'])]
            d['referencing_table'] = key['referencing_table']
            d['referenced_table'] = key['referenced_table']
            d['attr_map'][key['column_name']] = key['referenced_column_name']

        # add edges to the graph
        for fk in fks.values():
            props = dict(
                primary=all(attr in pks[fk['referencing_table']] for attr in fk['attr_map']),
                attr_map=fk['attr_map'],
                aliased=any(k != v for k, v in fk['attr_map'].items()),
                multi=not all(a in fk['attr_map'] for a in pks[fk['referencing_table']]))
            if not props['aliased']:
                self.add_edge(fk['referenced_table'], fk['referencing_table'], **props)
            else:
                # for aliased dependencies, add an extra node in the format '1', '2', etc
                alias_node = '%d' % next(self._node_alias_count)
                self.add_node(alias_node)
                self.add_edge(fk['referenced_table'], alias_node, **props)
                self.add_edge(alias_node, fk['referencing_table'], **props)

        if not nx.is_directed_acyclic_graph(self):  # pragma: no cover
            raise DataJointError('DataJoint can only work with acyclic dependencies')
1348439
def build(self):
        ''''''
        # right now we do not worry about status of nodes
        # connecting the output to the input of other nodes
        #
        # NOTE: This is implemented in the least efficient way just for
        # testing. It has to be re-implemented.
        #
        # refer to http://stackoverflow.com/questions/33494376/networkx-add-edges-to-graph-from-node-attributes
        #
        # several cases triggers dependency.
        if 'DAG' in env.config['SOS_DEBUG'] or 'ALL' in env.config['SOS_DEBUG']:
            env.log_to_file('DAG', 'build DAG')
        for wf in range(self._forward_workflow_id + 1):
            indexed = [x for x in self.nodes() if x._wf_index == wf]
            indexed.sort(key=lambda x: x._node_index)

            for idx, node in enumerate(indexed):
                # 1. if a node changes context (using option alias), all later steps
                # has to rely on it.
                if node._context['__changed_vars__']:
                    for later_node in indexed[idx + 1:]:
                        if node._context['__changed_vars__'] & (
                                later_node._context['__signature_vars__']
                                | later_node._context['__environ_vars__']):
                            self.add_edge(node, later_node)

                # 2. if the input of a step is undetermined, it has to be executed
                # after all its previous steps.
                if not node._input_targets.valid() and idx > 0:
                    # if there is some input specified, it does not use default
                    # input, so the relationship can be further looked before
                    if node._input_targets.undetermined():
                        # if the input is dynamic, has to rely on previous step...
                        if 'dynamic' in node._context['__environ_vars__']:
                            self.add_edge(indexed[idx - 1], node)
                        else:
                            # otherwise let us look back.
                            for prev_node in indexed[idx - 1::-1]:
                                if node._context[
                                        '__environ_vars__'] & prev_node._context[
                                            '__changed_vars__']:
                                    self.add_edge(prev_node, node)
                    else:
                        self.add_edge(indexed[idx - 1], node)
        #
        # 3. if the input of a step depends on the output of another step
        for target, in_node in self._all_depends_files.items():
            if target not in self._all_output_files:
                continue
            # it is possible that multiple nodes satisfy the same target
            out_node = self._all_output_files[target]
            for i in in_node:
                for j in out_node:
                    if j != i:
                        self.add_edge(j, i)
        self.mark_dirty()
1097839
def _compute_unnecessary_deps(self, target, actual_deps):
    
    # Flatten the product deps of this target.
    product_deps = set()
    for dep_entries in actual_deps.values():
      product_deps.update(dep_entries)

    # Determine which of the DEFAULT deps in the declared set of this target were used.
    used = set()
    unused = set()
    for dep, _ in self._analyzer.resolve_aliases(target, scope=Scopes.DEFAULT):
      if dep in used or dep in unused:
        continue
      # TODO: What's a better way to accomplish this check? Filtering by `has_sources` would
      # incorrectly skip "empty" `*_library` targets, which could then be used as a loophole.
      if isinstance(dep, (Resources, UnpackedJars)):
        continue
      # If any of the target's jars or classfiles were used, consider it used.
      if product_deps.isdisjoint(self._analyzer.files_for_target(dep)):
        unused.add(dep)
      else:
        used.add(dep)

    # If there were no unused deps, break.
    if not unused:
      return {}

    # For any deps that were used, count their derived-from targets used as well.
    # TODO: Refactor to do some of this above once tests are in place.
    for dep in list(used):
      for derived_from in dep.derived_from_chain:
        if derived_from in unused:
          unused.remove(derived_from)
          used.add(derived_from)

    # Prune derived targets that would be in the set twice.
    for dep in list(unused):
      if set(dep.derived_from_chain) & unused:
        unused.remove(dep)

    if not unused:
      return {}

    # For any deps that were not used, determine whether their transitive deps were used, and
    # recommend those as replacements.
    replacements = {}
    for dep in unused:
      replacements[dep] = set()
      for t in dep.closure():
        if t in used or t in unused:
          continue
        if not product_deps.isdisjoint(self._analyzer.files_for_target(t)):
          replacements[dep].add(t.concrete_derived_from)

    return replacements
249906
def _output_digraph(self, target):
    """"""
    color_by_type = {}

    def maybe_add_type(dep, dep_id):
      """Add a class type to a dependency id if --show-types is passed."""
      return dep_id if not self.show_types else '\\n'.join((dep_id, dep.__class__.__name__))

    def make_node(dep, dep_id, internal):
      line_fmt = '  "{id}" [style=filled, fillcolor={color}{internal}];'
      int_shape = ', shape=ellipse' if not internal else ''

      dep_class = dep.__class__.__name__
      if dep_class not in color_by_type:
        color_by_type[dep_class] = len(color_by_type.keys()) + 1

      return line_fmt.format(id=dep_id, internal=int_shape, color=color_by_type[dep_class])

    def make_edge(from_dep_id, to_dep_id, internal):
      style = ' [style=dashed]' if not internal else ''
      return '  "{}" -> "{}"{};'.format(from_dep_id, to_dep_id, style)

    def output_deps(dep, parent, parent_id, outputted):
      dep_id, internal = self._dep_id(dep)

      if dep_id not in outputted:
        yield make_node(dep, maybe_add_type(dep, dep_id), internal)
        outputted.add(dep_id)

        for sub_dep in self._enumerate_visible_deps(dep, self.output_candidate):
          for item in output_deps(sub_dep, dep, dep_id, outputted):
            yield item

      if parent:
        edge_id = (parent_id, dep_id)
        if edge_id not in outputted:
          yield make_edge(maybe_add_type(parent, parent_id), maybe_add_type(dep, dep_id), internal)
          outputted.add(edge_id)

    yield 'digraph "{}" {{'.format(target.id)
    yield '  node [shape=rectangle, colorscheme=set312;];'
    yield '  rankdir=LR;'
    for line in output_deps(target, parent=None, parent_id=None, outputted=set()):
      yield line
    yield '}'
755027
def computeNodeLinks(cls, element, graph):
        
        index = element.nodes.kdims[-1]
        node_map = {}
        if element.nodes.vdims:
            values = zip(*(element.nodes.dimension_values(d)
                           for d in element.nodes.vdims))
        else:
            values = cycle([tuple()])
        for index, vals in zip(element.nodes.dimension_values(index), values):
            node = {'index': index, 'sourceLinks': [], 'targetLinks': [], 'values': vals}
            graph['nodes'].append(node)
            node_map[index] = node

        links = [element.dimension_values(d) for d in element.dimensions()[:3]]
        for i, (src, tgt, value) in enumerate(zip(*links)):
            source, target = node_map[src], node_map[tgt]
            link = dict(index=i, source=source, target=target, value=value)
            graph['links'].append(link)
            source['sourceLinks'].append(link)
            target['targetLinks'].append(link)
89932
private void buildDependencyTree()
        throws DependencyTreeBuilderException
    {
        if ( rootNode == null )
        {
            rootNode =
                dependencyTreeBuilder.buildDependencyTree( project, localRepository, artifactFactory,
                                                           artifactMetadataSource, null, artifactCollector );
        }
    }
914681
private Collection<DependencyInfo> collectChildrenDependencies(DependencyInfo dependency, List<String> groupLines) {
        logger.debug("Collect child dependencies of {}, total group-lines = {}", dependency.getGroupId(), groupLines.size());
        Collection<DependencyInfo> dependencies = new LinkedList<>();
        boolean dependencyLine = false;
        for (String line : groupLines) {
            if (!dependencyLine && line.startsWith(FOUR_SPACES + dependency.getGroupId() + Constants.WHITESPACE)) {
                dependencyLine = true;
                getDependencyFromLine(dependency, line);
            } else if (dependencyLine) {
                if (line.startsWith(SIX_SPACES)) {
                    DependencyInfo childDependency = new DependencyInfo();
                    String lineWithoutSpaces = line.substring(SIX_SPACES.length());
                    childDependency.setGroupId(lineWithoutSpaces.substring(0, lineWithoutSpaces.indexOf(Constants.WHITESPACE)));
                    childDependency.setChildren(collectChildrenDependencies(childDependency, groupLines));
                    // prevent adding dependencies without sha1 or artifact id version and dependency type.
                    if(dependency.getSha1() == null && dependency.getArtifactId() == null) {
                        logger.warn(DEPENDECYERROR, dependency.getGroupId());
                    } else {
                        dependencies.add(childDependency);
                    }
                } else {
                    // move to the next dependency parent with its children
                    break;
                }
            }
        }
        return dependencies;
    }
878854
private void addDependencyToGraph(final DbDependency dependency, final AbstractGraph graph, final int depth, final String parentId) {
        // In that case of Axway artifact we will add a module to the graph
        if (filters.getCorporateFilter().filter(dependency)) {
            final DbModule dbTarget = repoHandler.getModuleOf(dependency.getTarget());

            // if there is no module, add the artifact to the graph
            if(dbTarget == null){
                LOG.error("Got missing reference: " + dependency.getTarget());
                final DbArtifact dbArtifact = DataUtils.createDbArtifact(dependency.getTarget());
                final String targetElementId = graph.getId(dbArtifact);
                graph.addElement(targetElementId, dbArtifact.getVersion(), false);
                graph.addDependency(parentId, targetElementId, dependency.getScope());
                return;
            }

            // Add the element to the graph
            addModuleToGraph(dbTarget, graph, depth + 1);

            //Add the dependency to the graph
            final String moduleElementId = graph.getId(dbTarget);
            graph.addDependency(parentId, moduleElementId, dependency.getScope());
        }
        // In case a third-party we will add an artifact
        else {
            final DbArtifact dbTarget = repoHandler.getArtifact(dependency.getTarget());
            if(dbTarget == null){
                LOG.error("Got missing artifact: " + dependency.getTarget());
                return;
            }

            if(!graph.isTreated(graph.getId(dbTarget))){
                final ModelMapper modelMapper = new ModelMapper(repoHandler);
                final Artifact target = modelMapper.getArtifact(dbTarget);
                final String targetElementId = graph.getId(target);
                graph.addElement(targetElementId, target.getVersion(), false);
                graph.addDependency(parentId, targetElementId, dependency.getScope());
            }
        }
    }