Pretty much all below can be combined into a higher order function to traverse revisions The return value from the callback will be passed as context to all children of that node
767381
function traverseRevTree(revs, callback) {
  var toVisit = revs.slice();

  var node;
  while ((node = toVisit.pop())) {
    var pos = node.pos;
    var tree = node.ids;
    var branches = tree[2];
    var newCtx =
      callback(branches.length === 0, pos, tree[0], node.ctx, tree[1]);
    for (var i = 0, len = branches.length; i < len; i++) {
      toVisit.push({pos: pos + 1, ids: branches[i], ctx: newCtx});
    }
  }
}
667490
def traverse(self, node):
        
        old_level = self.current_level
        if isinstance(node, nodes.section):
            if 'level' in node:
                self.current_level = node['level']
        to_visit = []
        to_replace = []
        for c in node.children[:]:
            newnode = self.find_replace(c)
            if newnode is not None:
                to_replace.append((c, newnode))
            else:
                to_visit.append(c)

        for oldnode, newnodes in to_replace:
            node.replace(oldnode, newnodes)

        for child in to_visit:
            self.traverse(child)
        self.current_level = old_level
1013638
def bsp_traverse_post_order(
    node: tcod.bsp.BSP,
    callback: Callable[[tcod.bsp.BSP, Any], None],
    userData: Any = 0,
) -> None:
    
    _bsp_traverse(node.post_order(), callback, userData)
1306140
def each_object(compressed: false, recursive: false, &block)
            return enum_for(__method__, compressed: compressed,
                                        recursive: recursive
                           ) unless block_given?

            @revisions.each do |revision|
                revision.each_object do |object|
                    block.call(object)

                    walk_object(object, &block) if recursive

                    if object.is_a?(ObjectStream) and compressed
                        object.each do |child_obj|
                            block.call(child_obj)

                            walk_object(child_obj) if recursive
                        end
                    end
                end
            end
        end
1179017
def _bsp_traverse(
    node_iter: Iterable[tcod.bsp.BSP],
    callback: Callable[[tcod.bsp.BSP, Any], None],
    userData: Any,
) -> None:
    
    for node in node_iter:
        callback(node, userData)
787546
def traverse(self, id_=None):
        """"""
        if id_ is None:
            id_ = self.group

        nodes = r_client.smembers(_children_key(id_))
        while nodes:
            current_id = nodes.pop()

            details = r_client.get(current_id)
            if details is None:
                # child has expired or been deleted, remove from :children
                r_client.srem(_children_key(id_), current_id)
                continue

            details = self._decode(details)
            if details['type'] == 'group':
                children = r_client.smembers(_children_key(details['id']))
                if children is not None:
                    nodes.update(children)

            yield details
1135717
@InterfaceAudience.Private
    public void pullRemoteRevision(final RevisionInternal rev) {

        Log.d(TAG, "%s: pullRemoteRevision with rev: %s", this, rev);

        ++httpConnectionCount;

        // Construct a query. We want the revision history, and the bodies of attachments that have
        // been added since the latest revisions we have locally.
        // See: http://wiki.apache.org/couchdb/HTTP_Document_API#Getting_Attachments_With_a_Document
        StringBuilder path = new StringBuilder(encodeDocumentId(rev.getDocID()));
        path.append("?rev=").append(URIUtils.encode(rev.getRevID()));
        path.append("&revs=true");

        // TODO: CBL Java does not have implementation of _settings yet. Till then, attachments always true
        boolean attachments = true;
        if (attachments)
            path.append("&attachments=true");

        // Include atts_since with a list of possible ancestor revisions of rev. If getting attachments,
        // this allows the server to skip the bodies of attachments that have not changed since the
        // local ancestor. The server can also trim the revision history it returns, to not extend past
        // the local ancestor (not implemented yet in SG but will be soon.)
        AtomicBoolean haveBodies = new AtomicBoolean(false);
        List<String> possibleAncestors = null;
        possibleAncestors = db.getPossibleAncestorRevisionIDs(rev,
                PullerInternal.MAX_NUMBER_OF_ATTS_SINCE, attachments ? haveBodies : null, true);
        if (possibleAncestors != null) {
            path.append(haveBodies.get() ? "&atts_since=" : "&revs_from=");
            path.append(joinQuotedEscaped(possibleAncestors));
        } else {
            int maxRevTreeDepth = getLocalDatabase().getMaxRevTreeDepth();
            if (rev.getGeneration() > maxRevTreeDepth) {
                path.append("&revs_limit=");
                path.append(maxRevTreeDepth);
            }
        }

        //create a final version of this variable for the log statement inside
        //FIXME find a way to avoid this
        final String pathInside = path.toString();
        CustomFuture future = sendAsyncMultipartDownloaderRequest("GET", pathInside,
                null, db, new RemoteRequestCompletion() {

                    @Override
                    public void onCompletion(RemoteRequest remoteRequest, Response httpResponse, Object result, Throwable e) {
                        if (e != null) {
                            Log.w(TAG, "Error pulling remote revision: %s", e, this);
                            if (Utils.isDocumentError(e)) {
                                // Revision is missing or not accessible:
                                revisionFailed(rev, e);
                            } else {
                                // Request failed:
                                setError(e);
                            }
                        } else {

                            Map<String, Object> properties = (Map<String, Object>) result;
                            long size = 0;
                            if (httpResponse != null && httpResponse.body() != null)
                                size = httpResponse.body().contentLength();
                            PulledRevision gotRev = new PulledRevision(properties, size);
                            gotRev.setSequence(rev.getSequence());

                            Log.d(TAG, "%s: pullRemoteRevision add rev: %s to batcher: %s",
                                    PullerInternal.this, gotRev, downloadsToInsert);

                            // NOTE: should not/not necessary to call Body.compact()
                            // new PulledRevision(Map<string, Object>) creates Body instance only
                            // with `object`. Serializing object to json causes two unnecessary
                            // JSON serializations.

                            if (gotRev.getBody() != null)
                                queuedMemorySize.addAndGet(gotRev.getBody().getSize());

                            // Add to batcher ... eventually it will be fed to -insertRevisions:.
                            downloadsToInsert.queueObject(gotRev);

                            // if queue memory size is more than maximum, force flush the queue.
                            if (queuedMemorySize.get() > MAX_QUEUE_MEMORY_SIZE) {
                                Log.d(TAG, "Flushing  queued memory size at: " + queuedMemorySize);
                                downloadsToInsert.flushAllAndWait();
                            }
                        }

                        // Note that we've finished this task:
                        --httpConnectionCount;

                        // Start another task if there are still revisions waiting to be pulled:
                        pullRemoteRevisions();
                    }
                });
        future.setQueue(pendingFutures);
        pendingFutures.add(future);
    }
640972
function traverse(node, callback) {
    callback(node);
    for (var i = 0, cn = node.childNodes, len = cn.length; i < len; i++) {
        var childNode = cn[i];
        if (childNode.tagName) {
            traverse(childNode, callback);
        }
    }
}
466700
function (src, destId, next, parent) {
            var oldId = src.id;
            src.parent = destId;

            async.waterfall([
                async.apply(_getAncestorsFromImmediateParent, destId, parent),
                function saveNodesAncestors(newAncestors, next) {
                    src.ancestors = newAncestors;
                    src._id = new ObjectId();
                    pendingInsertNodes.push(src);
                    async.parallel([
                            function findContentEntries(next) {
                                contentModel.find({"meta.node": oldId}).exec(function (err, data) {
                                    if (err) {
                                        next(err);
                                    }
                                    else {
                                        next(null, data);
                                    }
                                });
                            },
                            function findNodeEntries(next) {
                                nodeModel.find({parent: oldId}).exec(function (err, data) {
                                    if (err) {
                                        next(err);
                                    }
                                    else {
                                        next(null, data);
                                    }
                                });
                            }
                        ],
                        function handleFoundContentAndNodes(err, data) {
                            var contentEntries = data[0], nodeEntries = data[1];
                            _.each(contentEntries, function (item) {
                                item.meta.node = src._id;
                                item._id = new ObjectId();
                                pendingInsertContent.push(item);
                            });
                            if (!nodeEntries.length) {
                                next();
                            }
                            else {
                                async.each(nodeEntries, function (item, next) {
                                    _recursiveCopyNodes(item, src._id, next, src);
                                }, function (err) {
                                    next(err);
                                });
                            }
                        });

                }
            ], function (err) {
                next(err);
            });
        }
853975
function _doc_to_tree_node(doc, parent_id){

    var retnode = {};

    // ID.
    var raw_id = doc['id'];
    var safe_id = raw_id; // need to process?
    retnode['attr'] = { "id" : safe_id }; 

    // Label (with fallback).
    var label = doc['label'];
    if( ! label || label == '' ){
	label = raw_id;
    }else{
	label = label + ' (' + raw_id + ')';
    }

    // Set anchor title and href.
    var detlink = linker.url(raw_id, 'term');
    retnode['data'] = {"title" : label,
		       "attr": {"href": detlink}};

    // Turn to graph, get kids.
    var graph = new bbop.model.graph();
    graph.load_json(jQuery.parseJSON(doc['topology_graph']));
    var kids = graph.get_child_nodes(doc['id']);

    // Add state and kid_query.
    if( ! kids || kids.length == 0 ){
	// No kids...
    }else{
	// No kids, make sure the node is closed.
    	retnode['state'] = 'closed';

	// Collect kid info for the query to get them later.
	var qbuff = [];
	bbop.core.each(kids,
		       function(kid){
			   qbuff.push('id:"' + kid.id() + '"');
		       });
	retnode['attr']['kid_query'] = qbuff.join(' OR ');
    }

    // If the parent_id is defined, use that to pull the relationship
    // out of the graph and get a more appropriate icon.
    if( parent_id ){

	// Try and dig out the rel to display.
	var edges = graph.get_edges(raw_id, parent_id);
	if( edges && edges.length ){
	    var weight = {
		'is_a': 3,
		'part_of': 2
	    };
	    var unknown_rel_weight = 1;
	    edges.sort(
		function(a, b){
		    var aw = weight[a.predicate_id()];
		    if( ! aw ){ aw = unknown_rel_weight; }
		    var bw = weight[b.predicate_id()];
		    if( ! bw ){ bw = unknown_rel_weight; }
		    return bw - aw;
		});

	    // Add it in a brittle way.
	    var prime_rel = edges[0].predicate_id();
	    retnode['data']['icon'] = 
	    	server_meta.image_base() + '/' + prime_rel + '.gif';
	}
    }

    return retnode;
}
746818
def bsp_traverse_in_order(
    node: tcod.bsp.BSP,
    callback: Callable[[tcod.bsp.BSP, Any], None],
    userData: Any = 0,
) -> None:
    
    _bsp_traverse(node.in_order(), callback, userData)
1350555
def traverse_depth_first_pre_order(self, callback):
        
        n = len(self.suftab)
        root = [0, 0, n - 1, ""]  # <l, i, j, char>

        def _traverse_top_down(interval):  # TODO: Rewrite with stack? As in bottom-up
            callback(interval)
            i, j = interval[1], interval[2]
            if i != j:
                children = self._get_child_intervals(i, j)
                children.sort(key=lambda child: child[3])
                for child in children:
                    _traverse_top_down(child)

        _traverse_top_down(root)
863034
def _get_children(node, contexts=False, restrict=None, parent=None):
        """"""
        yield (parent, node) if contexts else node
        if restrict and isinstance(node, restrict):
            return
        for code in node.__children__():
            for child in code.nodes:
                sub = Wikicode._get_children(child, contexts, restrict, code)
                for result in sub:
                    yield result
129275
def __descendants(self):
        
        return itertools.chain(self.contents,
                               *[c.descendants for c in self.children])
1104554
function rootToLeaf(revs) {
  var paths = [];
  var toVisit = revs.slice();
  var node;
  while ((node = toVisit.pop())) {
    var pos = node.pos;
    var tree = node.ids;
    var id = tree[0];
    var opts = tree[1];
    var branches = tree[2];
    var isLeaf = branches.length === 0;

    var history = node.history ? node.history.slice() : [];
    history.push({id: id, opts: opts});
    if (isLeaf) {
      paths.push({pos: (pos + 1 - history.length), ids: history});
    }
    for (var i = 0, len = branches.length; i < len; i++) {
      toVisit.push({pos: pos + 1, ids: branches[i], history: history});
    }
  }
  return paths.reverse();
}
143726
function readFullTree() {
                        // Return null if the contextTree is not correctly closed
                        if (root !== currentContext) {
                            return null;
                        }

                        function recusiveRead(node) {
                            if (node.children.length === 0) {
                                delete node.children;
                            } else {
                                for (var i=0, max=node.children.length ; i<max ; i++) {
                                    recusiveRead(node.children[i]);
                                }
                            }
                            delete node.parent;
                        }
                        recusiveRead(root);

                        return root;
                    }
484874
def current_revision(self):
        
        if self.current_index is None:
            return None

        if len(self.revisions) > self.current_index:
            return self.revisions[self.current_index]

        return None