Sort nodes topologically using a depth-first approach. Encountered cycles are broken.
555052
function sortTopologically (originalOrder, edgesById) {
  const sorted = []
  const marked = new Set()

  const visit = (mark) => {
    if (marked.has(mark)) return
    marked.add(mark)
    const edges = edgesById.get(mark)
    if (edges != null) {
      edges.forEach(visit)
    }
    sorted.push(mark)
  }

  originalOrder.forEach(visit)
  return sorted
}
878109
private Coordinate[] getOrderedNodes( Coordinate c, Coordinate coordinate1, Coordinate coordinate2, Coordinate coordinate3 ) {
        double d = distance3d(c, coordinate1, null);
        Coordinate nearest = coordinate1;
        Coordinate c2 = coordinate2;
        Coordinate c3 = coordinate3;

        double d2 = distance3d(c, coordinate2, null);
        if (d2 < d) {
            nearest = coordinate2;
            d = d2;
            c2 = coordinate1;
            c3 = coordinate3;
        }
        double d3 = distance3d(c, coordinate3, null);
        if (d3 < d) {
            nearest = coordinate3;
            c2 = coordinate1;
            c3 = coordinate2;
        }
        return new Coordinate[]{nearest, c2, c3};
    }
1041305
public static Graph sortDFS(Graph g, Graph sortedGraph) {
        int nodes = g.getNodes();
        final GHIntArrayList list = new GHIntArrayList(nodes);
        list.fill(nodes, -1);
        final GHBitSetImpl bitset = new GHBitSetImpl(nodes);
        final AtomicInteger ref = new AtomicInteger(-1);
        EdgeExplorer explorer = g.createEdgeExplorer();
        for (int startNode = 0; startNode >= 0 && startNode < nodes;
             startNode = bitset.nextClear(startNode + 1)) {
            new DepthFirstSearch() {
                @Override
                protected GHBitSet createBitSet() {
                    return bitset;
                }

                @Override
                protected boolean goFurther(int nodeId) {
                    list.set(nodeId, ref.incrementAndGet());
                    return super.goFurther(nodeId);
                }
            }.start(explorer, startNode);
        }
        return createSortedGraph(g, sortedGraph, list);
    }
1144012
public List<V> topologicalSort() {
        Map<V, Integer> degree = inDegree();

        // determine all vertices with zero in-degree
        Stack<V> zeroVertices = new Stack<>(); // stack as good as any here
        for (V v : degree.keySet()) {
            if (degree.get(v) == 0) {
                zeroVertices.push(v);
            }
        }

        // determine the topological order
        List<V> result = new ArrayList<>();
        while (!zeroVertices.isEmpty()) {
            V vertex = zeroVertices.pop(); // choose a vertex with zero in-degree
            result.add(vertex); // vertex 'v' is next in topological order
            // "remove" vertex 'v' by updating its neighbors
            for (V neighbor : neighbors.get(vertex)) {
                degree.put(neighbor, degree.get(neighbor) - 1);
                // remember any vertices that now have zero in-degree
                if (degree.get(neighbor) == 0) {
                    zeroVertices.push(neighbor);
                }
            }
        }

        // check that we have used the entire graph (if not, there was a cycle)
        if (result.size() != neighbors.size()) {
            return null;
        }

        return result;
    }
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();
}
1353001
function recurse(data, depth, nodes) {
    var childs = children.call(hierarchy, data, depth),
        node = d3_layout_hierarchyInline ? data : {data: data};
    node.depth = depth;
    nodes.push(node);
    if (childs && (n = childs.length)) {
      var i = -1,
          n,
          c = node.children = [],
          v = 0,
          j = depth + 1,
          d;
      while (++i < n) {
        d = recurse(childs[i], j, nodes);
        d.parent = node;
        c.push(d);
        v += d.value;
      }
      if (sort) c.sort(sort);
      if (value) node.value = v;
    } else if (value) {
      node.value = +value.call(hierarchy, data, depth) || 0;
    }
    return node;
  }
1370855
function(nodes) {
        var ans = [], config = this.config, root = this.viz.root;
        nodes.sort(function(a, b) { return (a._depth <= b._depth) - (a._depth >= b._depth); });
        for(var i=0; i<nodes.length; i++) {
            if(nodes[i].anySubnode("exist")) {
            	for (var j = i+1, desc = false; !desc && j < nodes.length; j++) {
                    if(!config.multitree || '$orn' in nodes[j].data) {
                		desc = desc || nodes[i].isDescendantOf(nodes[j].id);                    	
                    }
                }
                if(!desc) ans.push(nodes[i]);
            }
        }
        return ans;
    }
294876
private void dfs(Visitor visitor, int v, int[] cc, int id) {
        visitor.visit(v);
        cc[v] = id;
        for (Edge edge : graph[v]) {
            int t = edge.v2;
            if (!digraph && t == v) {
                t = edge.v1;
            }

            if (cc[t] == -1) {
                dfs(visitor, t, cc, id);
            }
        }
    }
1175347
def topological_sort(self):
        
        graph = self.graph

        in_degree = {}
        for u in graph:
            in_degree[u] = 0

        for u in graph:
            for v in graph[u]:
                in_degree[v] += 1

        queue = deque()
        for u in in_degree:
            if in_degree[u] == 0:
                queue.appendleft(u)

        sorted_graph = []
        while queue:
            u = queue.pop()
            sorted_graph.append(u)
            for v in sorted(graph[u]):
                in_degree[v] -= 1
                if in_degree[v] == 0:
                    queue.appendleft(v)

        if len(sorted_graph) == len(graph):
            return sorted_graph
        else:
            raise ValueError('graph is not acyclic')
197024
def top_sort_recursive(graph):
    
    order, enter, state = [], set(graph), {}
    
    def dfs(node):
        state[node] = GRAY
        #print(node)
        for k in graph.get(node, ()):
            sk = state.get(k, None)
            if sk == GRAY:
                raise ValueError("cycle")
            if sk == BLACK:
                continue
            enter.discard(k)
            dfs(k)
        order.append(node)
        state[node] = BLACK
        
    while enter: dfs(enter.pop())
    return order
429893
function depthFirst(node, parent) {
  var results = [];
  if (node && (typeof node === 'object')) {

    // valid node so push it to the list and set new parent
    //  don't overwrite parent if one was not given
    if ('type' in node) {
      if (parent !== undefined) {
        node.parent = parent;
      }
      parent = node;
      results.push(node);
    }

    // recurse object members using nested function call
    for (var key in node) {
      if (WHITE_LIST.test(key)) {
        var value = node[key];
        if (value && (typeof value === 'object')) {
          results.push.apply(results, depthFirst(value, parent));
        }
      }
    }
  }
  return results;
}
1355420
function closeness(graph, oriented) {
  var Q = [];
  // list of predecessors on shortest paths from source
  // distance from source
  var dist = Object.create(null);

  var currentNode;
  var centrality = Object.create(null);

  graph.forEachNode(setCentralityToZero);
  graph.forEachNode(calculateCentrality);

  return centrality;

  function setCentralityToZero(node) {
    centrality[node.id] = 0;
  }

  function calculateCentrality(node) {
    currentNode = node.id;
    singleSourceShortestPath(currentNode);
    accumulate();
  }

  function accumulate() {
    // Add all distances for node to array, excluding -1s
    var distances = Object.keys(dist).map(function(key) {return dist[key]}).filter(function(val){return val !== -1});
    // Set number of reachable nodes
    var reachableNodesTotal = distances.length;
    // Compute sum of all distances for node
    var totalDistance = distances.reduce(function(a,b) { return a + b });
    if (totalDistance > 0) {
      centrality[currentNode] = ((reachableNodesTotal - 1) / totalDistance); 
    } else {
      centrality[currentNode] = 0;
    }
  }

  function singleSourceShortestPath(source) {
    graph.forEachNode(initNode);
    dist[source] = 0;
    Q.push(source);

    while (Q.length) {
      var v = Q.shift();
      graph.forEachLinkedNode(v, processNode, oriented);
    }

    function initNode(node) {
      var nodeId = node.id;
      dist[nodeId] = -1;
    }

    function processNode(otherNode) {
      var w = otherNode.id
      if (dist[w] === -1) {
        // Node w is found for the first time
        dist[w] = dist[v] + 1;
        Q.push(w);
      }
    }
  }
}
462908
function topologicalSort(graph) {
    const allNodes = {}, outgoingEdgeCount = {}, inverseEdges = {};
    Object.keys(graph).forEach((fromNode) => {
        allNodes[fromNode] = true;
        outgoingEdgeCount[fromNode] = graph[fromNode].length;
        graph[fromNode].forEach((toNode) => {
            allNodes[toNode] = true;
            outgoingEdgeCount[toNode] = outgoingEdgeCount[toNode] || 0;
            inverseEdges[toNode] = inverseEdges[toNode] || [];
            inverseEdges[toNode].push(fromNode);
        });
    });
    // https://en.wikipedia.org/wiki/Topological_sorting
    const S = [], L = [];
    Object.keys(allNodes).forEach((node) => {
        if (outgoingEdgeCount[node] === 0) {
            delete outgoingEdgeCount[node];
            S.push(node);
        }
    });
    while (S.length > 0) {
        // Ensure the exact same order all the time with the same inputs
        S.sort();
        const n = S.shift();
        L.push(n);
        const myInverseEdges = inverseEdges[n] || [];
        myInverseEdges.forEach((m) => {
            outgoingEdgeCount[m]--;
            if (outgoingEdgeCount[m] === 0) {
                delete outgoingEdgeCount[m];
                S.push(m);
            }
        });
    }
    if (Object.keys(outgoingEdgeCount).length > 0) {
        throw new Error('Cannot do topological sort on cyclic graph, remaining nodes: ' + Object.keys(outgoingEdgeCount));
    }
    return L;
}
450684
def depth_first_spanning_tree(start_node)
      raise ArgumentError unless vertices.include?(start_node)
      tree = DirectedAdjacencyGraph.new
      visited = Set.new
      build_dfst(tree, start_node, visited)
      tree
    end
577510
def toposorted(nodes, edges):
    
    incoming = defaultdict(set)
    outgoing = defaultdict(set)
    for edge in edges:
        incoming[edge.to_id].add(edge.from_id)
        outgoing[edge.from_id].add(edge.to_id)

    working_set = list(nodes.values())
    results = []
    while working_set:
        remaining = []
        for node in working_set:
            if incoming[node.id]:
                # node still has incoming edges
                remaining.append(node)
                continue

            results.append(node)
            for child in outgoing[node.id]:
                incoming[child].remove(node.id)

        if len(working_set) == len(remaining):
            raise Exception("Cycle detected")
        working_set = remaining

    return results
54916
private void sort()
    {
        DefaultDirectedWeightedGraph<RuleProvider, DefaultEdge> graph = new DefaultDirectedWeightedGraph<>(
                    DefaultEdge.class);

        for (RuleProvider provider : providers)
        {
            graph.addVertex(provider);
        }

        addProviderRelationships(graph);

        checkForCycles(graph);

        List<RuleProvider> result = new ArrayList<>(this.providers.size());
        TopologicalOrderIterator<RuleProvider, DefaultEdge> iterator = new TopologicalOrderIterator<>(graph);
        while (iterator.hasNext())
        {
            RuleProvider provider = iterator.next();
            result.add(provider);
        }

        this.providers = Collections.unmodifiableList(result);

        int index = 0;
        for (RuleProvider provider : this.providers)
        {
            if (provider instanceof AbstractRuleProvider)
                ((AbstractRuleProvider) provider).setExecutionIndex(index++);
        }
    }
519226
def sorted_source_files(self):
        """"""

        assert self.final, 'Call build() before using the graph.'
        out = []
        for node in nx.topological_sort(self.graph):
            if isinstance(node, NodeSet):
                out.append(node.nodes)
            else:
                # add a one-element list for uniformity
                out.append([node])
        return list(reversed(out))