Get nodes from graph G with indegree 0
335748
def roots(g):
    ""
    return set(n for n, d in iteritems(g.in_degree()) if d == 0)
170146
def get_nodes_by_function(graph: BELGraph, func: Strings) -> Set[BaseEntity]:
    """"""
    return get_nodes(graph, function_inclusion_filter_builder(func))
198474
def getIndices(self):
        """"""
        for indexName in self.neograph.nodes.indexes.keys():
            indexObject = self.neograph.nodes.indexes.get(indexName)
            yield Index(indexName, "vertex", "manual", indexObject)
        for indexName in self.neograph.relationships.indexes.keys():
            indexObject = self.neograph.relationships.indexes.get(indexName)
            yield Index(indexName, "edge", "manual", indexObject)
936074
private Set<SNode> getMatchedNodes(SDocumentGraph graph) {

    Set<SNode> matchedNodes = new HashSet<>();

    for (SNode node: graph.getNodes()) {
       if (node.getFeature(AnnisConstants.ANNIS_NS, AnnisConstants.FEAT_MATCHEDNODE) != null)
         matchedNodes.add(node);
    }

    return matchedNodes;
  }
112604
private static void computeTreeGraph(SharedTreeSubgraph sg, SharedTreeNode node, byte[] tree, ByteBufferWrapper ab, HashMap<Integer, AuxInfo> auxMap,
                                         String names[], String[][] domains) {
        int nodeType = ab.get1U();
        int colId = ab.get2();
        if (colId == 65535) {
            float leafValue = ab.get4f();
            node.setPredValue(leafValue);
            return;
        }
        String colName = names[colId];
        node.setCol(colId, colName);

        int naSplitDir = ab.get1U();
        boolean naVsRest = naSplitDir == NsdNaVsRest;
        boolean leftward = naSplitDir == NsdNaLeft || naSplitDir == NsdLeft;
        node.setLeftward(leftward);
        node.setNaVsRest(naVsRest);

        int lmask = (nodeType & 51);
        int equal = (nodeType & 12);  // Can be one of 0, 8, 12
        assert equal != 4;  // no longer supported

        if (!naVsRest) {
            // Extract value or group to split on
            if (equal == 0) {
                // Standard float-compare test (either < or ==)
                float splitVal = ab.get4f();  // Get the float to compare
                node.setSplitValue(splitVal);
            } else {
                // Bitset test
                GenmodelBitSet bs = new GenmodelBitSet(0);
                if (equal == 8)
                    bs.fill2(tree, ab);
                else
                    bs.fill3(tree, ab);
                node.setBitset(domains[colId], bs);
            }
        }

        AuxInfo auxInfo = auxMap.get(node.getNodeNumber());

        // go RIGHT
        {
            ByteBufferWrapper ab2 = new ByteBufferWrapper(tree);
            ab2.skip(ab.position());

            switch (lmask) {
                case 0:
                    ab2.skip(ab2.get1U());
                    break;
                case 1:
                    ab2.skip(ab2.get2());
                    break;
                case 2:
                    ab2.skip(ab2.get3());
                    break;
                case 3:
                    ab2.skip(ab2.get4());
                    break;
                case 48:
                    ab2.skip(4);
                    break;  // skip the prediction
                default:
                    assert false : "illegal lmask value " + lmask + " in tree " + Arrays.toString(tree);
            }
            int lmask2 = (nodeType & 0xC0) >> 2;  // Replace leftmask with the rightmask

            SharedTreeNode newNode = sg.makeRightChildNode(node);
            newNode.setWeight(auxInfo.weightR);
            newNode.setNodeNumber(auxInfo.nidR);
            newNode.setPredValue(auxInfo.predR);
            newNode.setSquaredError(auxInfo.sqErrR);
            if ((lmask2 & 16) != 0) {
                float leafValue = ab2.get4f();
                newNode.setPredValue(leafValue);
                auxInfo.predR = leafValue;
            }
            else {
                computeTreeGraph(sg, newNode, tree, ab2, auxMap, names, domains);
            }
        }

        // go LEFT
        {
            ByteBufferWrapper ab2 = new ByteBufferWrapper(tree);
            ab2.skip(ab.position());

            if (lmask <= 3)
                ab2.skip(lmask + 1);

            SharedTreeNode newNode = sg.makeLeftChildNode(node);
            newNode.setWeight(auxInfo.weightL);
            newNode.setNodeNumber(auxInfo.nidL);
            newNode.setPredValue(auxInfo.predL);
            newNode.setSquaredError(auxInfo.sqErrL);
            if ((lmask & 16) != 0) {
                float leafValue = ab2.get4f();
                newNode.setPredValue(leafValue);
                auxInfo.predL = leafValue;
            }
            else {
                computeTreeGraph(sg, newNode, tree, ab2, auxMap, names, domains);
            }
        }
        if (node.getNodeNumber() == 0) {
          float p = (float)(((double)auxInfo.predL*(double)auxInfo.weightL + (double)auxInfo.predR*(double)auxInfo.weightR)/((double)auxInfo.weightL + (double)auxInfo.weightR));
          if (Math.abs(p) < 1e-7) p = 0;
          node.setPredValue(p);
          node.setSquaredError(auxInfo.sqErrR + auxInfo.sqErrL);
          node.setWeight(auxInfo.weightL + auxInfo.weightR);
        }
        checkConsistency(auxInfo, node);
    }
1329215
def get_undirected(G):
    

    start_time = time.time()

    # set from/to nodes before making graph undirected
    G = G.copy()
    for u, v, k, data in G.edges(keys=True, data=True):
        G.edges[u, v, k]['from'] = u
        G.edges[u, v, k]['to'] = v
        
        # add geometry if it doesn't already exist, to retain parallel
        # edges' distinct geometries
        if 'geometry' not in data:
            point_u = Point((G.nodes[u]['x'], G.nodes[u]['y']))
            point_v = Point((G.nodes[v]['x'], G.nodes[v]['y']))
            data['geometry'] = LineString([point_u, point_v])

    # update edge keys so we don't retain only one edge of sets of parallel edges
    # when we convert from a multidigraph to a multigraph
    G = update_edge_keys(G)

    # now convert multidigraph to a multigraph, retaining all edges in both
    # directions for now, as well as all graph attributes
    H = nx.MultiGraph()
    H.add_nodes_from(G.nodes(data=True))
    H.add_edges_from(G.edges(keys=True, data=True))
    H.graph = G.graph
    H.name = G.name

    # the previous operation added all directed edges from G as undirected
    # edges in H. this means we have duplicate edges for every bi-directional
    # street. so, look through the edges and remove any duplicates
    duplicate_edges = []
    for u, v, key, data in H.edges(keys=True, data=True):

        # if we haven't already flagged this edge as a duplicate
        if not (u, v, key) in duplicate_edges:

            # look at every other edge between u and v, one at a time
            for key_other in H[u][v]:

                # don't compare this edge to itself
                if not key_other == key:

                    # compare the first edge's data to the second's to see if
                    # they are duplicates
                    data_other = H.edges[u, v, key_other]
                    if is_duplicate_edge(data, data_other):

                        # if they match up, flag the duplicate for removal
                        duplicate_edges.append((u, v, key_other))

    H.remove_edges_from(duplicate_edges)
    log('Made undirected graph in {:,.2f} seconds'.format(time.time() - start_time))

    return H
1111544
def nx_gen_node_values(G, key, nodes, default=util_const.NoParam):
    
    node_dict = nx_node_dict(G)
    if default is util_const.NoParam:
        return (node_dict[n][key] for n in nodes)
    else:
        return (node_dict[n].get(key, default) for n in nodes)
218716
private <E> Collection<Block<S, L>> initialize(UniversalGraph<S, E, ?, L> graph,
                                                   Collection<? extends S> initialNodes) {
        Iterable<? extends S> origStates;
        if (initialNodes == null || initialNodes.isEmpty()) {
            origStates = graph.getNodes();
        } else {
            origStates = GraphTraversal.depthFirstOrder(graph, initialNodes);
        }

        Map<L, TransitionLabel<S, L>> transitionMap = new HashMap<>();

        stateStorage = graph.createStaticNodeMapping();

        int numStates = 0;
        for (S origState : origStates) {
            State<S, L> state = new State<>(numStates++, origState);
            stateStorage.put(origState, state);
            stateList.add(state);
        }

        InitialPartitioning<S, L> initPartitioning = new HashMapInitialPartitioning<>(graph);

        for (State<S, L> state : stateList) {
            S origState = state.getOriginalState();

            Block<S, L> block = initPartitioning.getBlock(origState);
            block.addState(state);

            for (E edge : graph.getOutgoingEdges(origState)) {
                S origTarget = graph.getTarget(edge);
                State<S, L> target = stateStorage.get(origTarget);
                L label = graph.getEdgeProperty(edge);
                TransitionLabel<S, L> transition = transitionMap.computeIfAbsent(label, TransitionLabel::new);
                Edge<S, L> edgeObj = new Edge<>(state, target, transition);
                state.addOutgoingEdge(edgeObj);
                target.addIncomingEdge(edgeObj);
            }
        }
        stateList.quickClear();

        return initPartitioning.getInitialBlocks();
    }
162217
def all_leaves(self, graph=None):
        
        if graph is None:
            graph = self.graph
        return [key for key in graph if not graph[key]]
12169
def get_shared_nodes(G1: nx.DiGraph, G2: nx.DiGraph) -> List[str]:
    """"""
    return list(set(G1.nodes()).intersection(set(G2.nodes())))
401685
@SuppressWarnings("unchecked")
    private Set<Integer> getPredecessors(Graph g, Integer vertex) {
        // The DirectedGraph cast seems to change the return type of the set
        // from Set<Integer> to just Set
        if (g instanceof DirectedGraph) {
            DirectedGraph<?> dg = (DirectedGraph)g;
            return dg.predecessors(vertex);
        }
        else {
            return g.getNeighbors(vertex);
        }
    }
829169
def getVertex(self, _id):
        """"""
        try:
            node = self.neograph.nodes.get(_id)
        except client.NotFoundError:
            return None
        return Vertex(node)
32678
def get_graph(self, name):
        
        if name in self._graph_objs:
            return self._graph_objs[name]
        graphtypes = {
            'Graph': Graph,
            'DiGraph': DiGraph,
            'MultiGraph': MultiGraph,
            'MultiDiGraph': MultiDiGraph
        }
        type_s = self.query.graph_type(name)
        if type_s not in graphtypes:
            raise GraphNameError(
                "I don't know of a graph named {}".format(name)
            )
        g = graphtypes[type_s](self, name)
        self._graph_objs[name] = g
        return g
605932
def get_gene_leaves(graph) -> Iterable[BaseEntity]:
    
    for node in get_nodes_by_function(graph, GENE):
        if graph.in_degree(node) != 0:
            continue

        if graph.out_degree(node) != 1:
            continue

        _, _, d = list(graph.out_edges(node, data=True))[0]

        if d[RELATION] == TRANSCRIBED_TO:
            yield node
330206
def __extract_pattern_nodes(graph):
    
    tp_nodes = graph.subjects(RDF.type, AGORA.TriplePattern)
    for tpn in tp_nodes:
        subject = list(graph.objects(tpn, AGORA.subject)).pop()
        predicate = list(graph.objects(tpn, AGORA.predicate)).pop()
        obj = list(graph.objects(tpn, AGORA.object)).pop()
        subject_str = list(graph.objects(subject, RDFS.label)).pop().toPython()
        predicate_str = graph.qname(predicate)
        if (obj, RDF.type, AGORA.Variable) in graph:
            object_str = list(graph.objects(obj, RDFS.label)).pop().toPython()
        else:
            object_str = list(graph.objects(obj, AGORA.value)).pop().toPython()
        __plan_patterns[tpn] = '{} {} {}'.format(subject_str, predicate_str, object_str)
435820
function tightTree(t, g) {
  function dfs(v) {
    _.forEach(g.nodeEdges(v), function(e) {
      var edgeV = e.v,
        w = (v === edgeV) ? e.w : edgeV;
      if (!t.hasNode(w) && !slack(g, e)) {
        t.setNode(w, {});
        t.setEdge(v, w, {});
        dfs(w);
      }
    });
  }

  _.forEach(t.nodes(), dfs);
  return t.nodeCount();
}
1236558
def __get_cycle(graph, ordering, parent_lookup):
    """"""
    root_node = ordering[0]
    for i in range(2, len(ordering)):
        current_node = ordering[i]
        if graph.adjacent(current_node, root_node):
            path = []
            while current_node != root_node:
                path.append(current_node)
                current_node = parent_lookup[current_node]
            path.append(root_node)
            path.reverse()
            return path