Recursive print worker - recurses the AST and prints each node.
174195
def _recurse(node, *args, **kwargs):
    """"""
    node_name = node.__class__.__name__
    try:
        info_for_node = _NODE_INFO_TABLE[node_name]
    except KeyError:
        return

    action = kwargs[info_for_node.handler]
    depth = kwargs["depth"]

    # Invoke action if available
    if action is not None:
        action(node_name, node, depth)

    # Recurse
    recurse_kwargs = kwargs
    kwargs["depth"] = depth + 1

    for single in info_for_node.single:
        _recurse(getattr(node, single),
                 *args,
                 **recurse_kwargs)

    for multi in info_for_node.multi:
        for statement in getattr(node, multi):
            _recurse(statement,
                     *args,
                     **recurse_kwargs)
466858
def print_all(self, out=sys.stdout):
        
        THREAD_FUNC_NAME_LEN = 25
        THREAD_NAME_LEN = 13
        THREAD_ID_LEN = 15
        THREAD_SCHED_CNT_LEN = 10

        out.write(CRLF)
        out.write("name           tid              ttot      scnt")
        out.write(CRLF)
        for stat in self:
            out.write(StatString(stat.name).ltrim(THREAD_NAME_LEN))
            out.write(" " * COLUMN_GAP)
            out.write(StatString(stat.id).rtrim(THREAD_ID_LEN))            
            out.write(" " * COLUMN_GAP)
            out.write(StatString(_fft(stat.ttot)).rtrim(TIME_COLUMN_LEN))
            out.write(" " * COLUMN_GAP)
            out.write(StatString(stat.sched_count).rtrim(THREAD_SCHED_CNT_LEN))
            out.write(CRLF)
511770
def iterate(node)
      return unless node.is_a?(AST::Node)

      before    = :"on_#{node.type}"
      after     = :"after_#{node.type}"
      skip_node = catch :skip_child_nodes do
        execute_callback(before, node)
      end

      if skip_node != node
        node.children.each do |child|
          iterate(child) if child.is_a?(AST::Node)
        end
      end

      execute_callback(after, node)
    end
1108463
def print_subcommands(data, nested_content, markDownHelp=False, settings=None):
    

    definitions = map_nested_definitions(nested_content)
    items = []
    if 'children' in data:
        subCommands = nodes.section(ids=["Sub-commands:"])
        subCommands += nodes.title('Sub-commands:', 'Sub-commands:')

        for child in data['children']:
            sec = nodes.section(ids=[child['name']])
            sec += nodes.title(child['name'], child['name'])

            if 'description' in child and child['description']:
                desc = [child['description']]
            elif child['help']:
                desc = [child['help']]
            else:
                desc = ['Undocumented']

            # Handle nested content
            subContent = []
            if child['name'] in definitions:
                classifier, s, subContent = definitions[child['name']]
                if classifier == '@replace':
                    desc = [s]
                elif classifier == '@after':
                    desc.append(s)
                elif classifier == '@before':
                    desc.insert(0, s)

            for element in renderList(desc, markDownHelp):
                sec += element
            sec += nodes.literal_block(text=child['bare_usage'])
            for x in print_action_groups(child, nested_content + subContent, markDownHelp,
                                         settings=settings):
                sec += x

            for x in print_subcommands(child, nested_content + subContent, markDownHelp,
                                       settings=settings):
                sec += x

            if 'epilog' in child and child['epilog']:
                for element in renderList([child['epilog']], markDownHelp):
                    sec += element

            subCommands += sec
        items.append(subCommands)

    return items
1067407
def __recursive_parser(self, onlysymbol, data, production, showerrors = False):
        
        LOG.debug("__recursive_parser: Begin ")
        if not data:
            return []
        from pydsl.grammar.symbol import TerminalSymbol, NullSymbol, NonTerminalSymbol
        if isinstance(onlysymbol, TerminalSymbol):
            LOG.debug("Iteration: terminalsymbol")
            return self._reduce_terminal(onlysymbol,data[0], showerrors)
        elif isinstance(onlysymbol, NullSymbol):
            return [ParseTree(0, 0, onlysymbol, "")]
        elif isinstance(onlysymbol, NonTerminalSymbol):
            validstack = []
            invalidstack = []
            for alternative in self._productionset.getProductionsBySide(onlysymbol): #Alternative
                alternativetree = PositionResultList()
                alternativeinvalidstack = []
                for symbol in alternative.rightside: # Symbol
                    symbol_success = False
                    for totalpos in alternativetree.right_limit_list(): # Right limit
                        if totalpos >= len(data):
                            continue
                        thisresult =  self.__recursive_parser(symbol, data[totalpos:], alternative, showerrors)
                        if not (thisresult and all(thisresult)):
                            alternativeinvalidstack += [x for x in thisresult if not x]
                            continue
                        symbol_success = True
                        for x in thisresult:
                            x.shift(totalpos)
                            success = alternativetree.append(x.left, x.right, x)
                            if not success:
                                #TODO: Add as an error to the tree or to another place
                                LOG.debug("Discarded symbol :" + str(symbol) + " position:" + str(totalpos))
                            else:
                                LOG.debug("Added symbol :" + str(symbol) + " position:" + str(totalpos))
                    if not symbol_success:
                        LOG.debug("Symbol doesn't work" + str(symbol))
                        break #Try next alternative
                else: # Alternative success (no break happened)
                    invalidstack += alternativeinvalidstack
                for x in alternativetree.valid_sequences():
                    validstack.append(x)
            result = []

            LOG.debug("iteration result collection finished:" + str(validstack))
            for alternative in self._productionset.getProductionsBySide(onlysymbol):
                nullcount = alternative.rightside.count(NullSymbol())
                for results in validstack:
                    nnullresults = 0
                    left = results[0]['left']
                    right = results[-1]['right']
                    nnullresults = len([x for x in results if x['content'].symbol == NullSymbol()])
                    if len(results) - nnullresults != len(alternative.rightside) - nullcount:
                        LOG.debug("Discarded: incorrect number of non null symbols")
                        continue
                    if right > len(data):
                        LOG.debug("Discarded: length mismatch")
                        continue
                    for x in range(min(len(alternative.rightside), len(results))):
                        if results[x]['content'] != alternative.rightside[x]:
                            LOG.debug("Discarded: rule doesn't match partial result")
                            continue
                    childlist = [x['content'] for x in results]
                    allvalid = all([x.valid for x in childlist])
                    if allvalid:
                        newresult = ParseTree(0, right - left, onlysymbol,
                                data[left:right], childlist = childlist)
                        newresult.valid = True
                        result.append(newresult)
            if showerrors and not result:
                erroresult = ParseTree(0,len(data), onlysymbol , data, valid = False)
                for invalid in invalidstack:
                    if invalid.content in production.rightside:
                        erroresult.append(invalid)
                return [erroresult]
            return result
        raise Exception("Unknown symbol:" + str(onlysymbol))
810578
void printDotNodesAtLevel(PrintStream os, int levelToPrint, boolean detail, PrintMojo.PrintTreeOptions treeOptions) {
    if (getDepth() == levelToPrint) {
      printDotNode(os, detail, treeOptions);
      return;
    }

    assert (getDepth() < levelToPrint);

    if (leftChild != null) {
      leftChild.printDotNodesAtLevel(os, levelToPrint, detail, treeOptions);
    }
    if (rightChild != null) {
      rightChild.printDotNodesAtLevel(os, levelToPrint, detail, treeOptions);
    }
  }
1333346
def each_recursive(&block) # :yields: node
      self.elements.each {|node|
        block.call(node)
        node.each_recursive(&block)
      }
    end
81723
def avl_join_dir_recursive(t1, t2, node, direction):
    
    other_side = 1 - direction
    if _DEBUG_JOIN_DIR:
        print('--JOIN DIR (dir=%r) --' % (direction,))
        ascii_tree(t1, 't1')
        ascii_tree(t2, 't2')

    if direction == 0:
        large, small = t2, t1
    elif direction == 1:
        large, small = t1, t2
    else:
        assert False

    # Follow the spine of the larger tree
    spine = large[direction]
    rest = large[other_side]
    # k_, v_ = large.key, large.value

    hsmall = height(small)
    hspine = height(spine)
    hrest = height(rest)

    if _DEBUG_JOIN_DIR:
        ascii_tree(spine, 'spine')
        ascii_tree(rest, 'rest')
        ascii_tree(small, 'small')

    if hspine <= hsmall + 1:
        t_ = avl_new_top(small, spine, node, direction)
        if _DEBUG_JOIN_DIR:
            print('JOIN DIR (BASE)')
            ascii_tree(t_, 't_')
        if height(t_) <= hrest + 1:
            if _DEBUG_JOIN_DIR:
                print('JOIN DIR (Case 1)')
            return avl_new_top(t_, rest, large, direction)
        else:
            # Double rotation, but with a new node
            if _DEBUG_JOIN_DIR:
                print('JOIN DIR (Case 2)')
            t_rotate = avl_rotate_single(t_, direction)
            if _DEBUG_JOIN_DIR:
                ascii_tree(t_rotate, 't_rotate')
                EulerTourTree(root=t_rotate)._assert_nodes('t_rotate')
            t_merge = avl_new_top(rest, t_rotate, large, other_side)
            if _DEBUG_JOIN_DIR:
                ascii_tree(t_merge, 't_merge')
                EulerTourTree(root=t_merge)._assert_nodes('t_merge')
            new_root = avl_rotate_single(t_merge, other_side)
            if _DEBUG_JOIN_DIR:
                ascii_tree(new_root, 'new_root')
                EulerTourTree(root=new_root)._assert_nodes('new_root')
            return new_root
    else:
        # Traverse down the spine in the appropriate direction
        if _DEBUG_JOIN_DIR:
            print('JOIN DIR (RECURSE)')
        if direction == 0:
            t_ = avl_join_dir_recursive(small, spine, node, direction)
        elif direction == 1:
            t_ = avl_join_dir_recursive(spine, t2, node, direction)
        else:
            raise AssertionError('invalid direction')
        t__ = avl_new_top(t_, rest, large, direction)
        if height(t_) <= hrest + 1:
            if _DEBUG_JOIN_DIR:
                print('JOIN DIR (Case 3)')
            return t__
        else:
            if _DEBUG_JOIN_DIR:
                print('JOIN DIR (Case 4)')
            return avl_rotate_single(t__, other_side)
    assert False, 'should never get here'
843781
def run(self):
        """"""
        paths = [x for x in practices.__dict__.values()
                 if hasattr(x, 'code')]

        for node in ast.walk(self.tree):
            try:
                lineno, col_offset = node.lineno, node.col_offset
            except AttributeError:
                # Not all nodes have coordinates, e.g.: ast.Module
                continue

            for checker in paths:
                if checker(node):
                    message = self.build_message(checker)
                    yield lineno, col_offset, message, type(self)
1125645
def print_tree(self) -> str:
        

        if self.ast:
            return self.ast.print_tree(ast_obj=self.ast)
        else:
            return ""
371726
def print_cliques(cliques, next_cliques, node_id_map):
    """"""
    n_cliques = len(cliques)
    format_str = '{:<' + str(n_cliques * 2) + '}  {} {}'
    branches = ['|'] * len(cliques)
    for i, clique in enumerate(cliques):
        block_id, nodes = clique
        print(format_str.format(
            ' '.join(branches[:i] + ['*'] + branches[i + 1:]),
            block_id[:8], format_siblings(nodes, node_id_map)))
        if block_id not in next_cliques:
            branches[i] = ' '
977874
function printNodes(node, indent) {
  indent = indent || 0;

  print(node.typename + ': ', indent);

  if (node instanceof NodeList) {
    print('\n');
    node.children.forEach((n) => {
      printNodes(n, indent + 2);
    });
  } else if (node instanceof CallExtension) {
    print(`${node.extName}.${node.prop}\n`);

    if (node.args) {
      printNodes(node.args, indent + 2);
    }

    if (node.contentArgs) {
      node.contentArgs.forEach((n) => {
        printNodes(n, indent + 2);
      });
    }
  } else {
    let nodes = [];
    let props = null;

    node.iterFields((val, fieldName) => {
      if (val instanceof Node) {
        nodes.push([fieldName, val]);
      } else {
        props = props || {};
        props[fieldName] = val;
      }
    });

    if (props) {
      print(JSON.stringify(props, null, 2) + '\n', null, true);
    } else {
      print('\n');
    }

    nodes.forEach(([fieldName, n]) => {
      print(`[${fieldName}] =>`, indent + 2);
      printNodes(n, indent + 4);
    });
  }
}
187406
def recursive_iter(enumerables):
    '''
    
    '''
    if not is_collection(enumerables) or isinstance(enumerables, (basestring, dict)):
        yield enumerables
    else:
        for elem in enumerables:
            for sub_elem in recursive_iter(elem):
                yield sub_elem
814404
def pretty_print(node):
        
        for pre, _, node in RenderTree(node):
            print('{}{}'.format(pre, node.name))
519042
def traversal(root):
    ''''''
    stack = [root]
    while len(stack) > 0:
        node = stack.pop()
        if hasattr(node,'children'):
            if node.children == set():
                try:
                    stack[-1].children.remove(node)
                except:
                    pass
                yield (node,stack)
            else:
                childnode = node.children.pop()
                stack += [node,childnode]
        else: 
            children = [x for x in ast.iter_child_nodes(node)]
            node.children = set(children)
            stack.append(node)
801530
private static void print(Node node, PrintWriter out) {
        if (node == null) {
            return;
        }

        boolean hasChildren = false;
        int type = node.getNodeType();
        NodeList children = null;
        switch (type) {
            case Node.DOCUMENT_NODE:
                children = node.getChildNodes();
                if (children != null) {
                    int numChildren = children.getLength();
                    for (int i = 0; i < numChildren; i++) {
                        print(children.item(i), out);
                    }
                }
                break;
            case Node.ELEMENT_NODE:
                out.print('<');
                out.print(node.getNodeName());
                if (node.hasAttributes()) {
                    NamedNodeMap attrs = node.getAttributes();
                    int len = (attrs != null) ? attrs.getLength() : 0;
                    for (int a = 0; a < len; a++) {
                        Attr attr = (Attr) attrs.item(a);
                        out.print(' ');
                        out.print(attr.getNodeName());
                        out.print("=\"");
                        out.print(attr.getValue());
                        out.print('\"');
                    }
                }
                children = node.getChildNodes();
                if (children != null) {
                    int numChildren = children.getLength();
                    hasChildren = (numChildren > 0);
                    if (hasChildren) {
                        out.print('>');
                    }
                    for (int i = 0; i < numChildren; i++) {
                        print(children.item(i), out);
                    }
                } else {
                    hasChildren = false;
                }
                if (!hasChildren) {
                    out.print("/>");
                }
                break;
            case Node.ENTITY_REFERENCE_NODE:
                out.print('&');
                out.print(node.getNodeName());
                out.print(';');
                break;
            case Node.CDATA_SECTION_NODE:
                out.print("<![CDATA[");
                out.print(node.getNodeValue());
                out.print("]]>");
                break;
            case Node.TEXT_NODE:
                out.print(node.getNodeValue());
                break;
            default:
                if (logger.isDebugEnabled()) {
                    logger.debug("Unknown type: " + type);
                }
        }
        if (type == Node.ELEMENT_NODE && hasChildren) {
            out.print("</");
            out.print(node.getNodeName());
            out.print('>');
            hasChildren = false;
        }
    }
1075666
def _print_details(extra=None):
    """"""
    def print_node_handler(name, node, depth):
        """Standard printer for a node."""
        line = "{0}{1} {2} ({3}:{4})".format(depth,
                                             (" " * depth),
                                             name,
                                             node.line,
                                             node.col)
        if extra is not None:
            line += " [{0}]".format(extra(node))

        sys.stdout.write(line + "\n")

    return print_node_handler