Return tree positions of all leaves of a subtree.
777484
def subtree_leaf_positions(subtree):
    """"""
    relative_leaf_positions = subtree.treepositions('leaves')
    subtree_root_pos = subtree.treeposition()
    absolute_leaf_positions = []
    for rel_leaf_pos in relative_leaf_positions:
        absolute_leaf_positions.append( subtree_root_pos + rel_leaf_pos)
    return absolute_leaf_positions
561402
function getSegmentedSubPaths(paths) {
    let segments = new Map();

    // Get earliest Path in tree where paths intersect
    paths[0].getDeepestCommonAncestorFrom(
      paths,
      (lastCommon, index, ancestries) => {
        // found the LCA
        if (!lastCommon.isProgram()) {
          let fnParent;
          if (
            lastCommon.isFunction() &&
            t.isBlockStatement(lastCommon.node.body)
          ) {
            segments.set(lastCommon, paths);
            return;
          } else if (
            !(fnParent = getFunctionParent(lastCommon)).isProgram() &&
            t.isBlockStatement(fnParent.node.body)
          ) {
            segments.set(fnParent, paths);
            return;
          }
        }
        // Deopt and construct segments otherwise
        for (const ancestor of ancestries) {
          const fnPath = getChildFuncion(ancestor);
          if (fnPath === void 0) {
            continue;
          }
          const validDescendants = paths.filter(p => {
            return p.isDescendant(fnPath);
          });
          segments.set(fnPath, validDescendants);
        }
      }
    );
    return segments;
  }
866757
private static List<JoinNode> generateInnerJoinOrdersForTree(JoinNode subTree) {
        // Get a list of the leaf nodes(tables) to permute them
        List<JoinNode> tableNodes = subTree.generateLeafNodesJoinOrder();
        List<List<JoinNode>> joinOrders = PermutationGenerator.generatePurmutations(tableNodes);
        List<JoinNode> newTrees = new ArrayList<>();
        for (List<JoinNode> joinOrder: joinOrders) {
            newTrees.add(JoinNode.reconstructJoinTreeFromTableNodes(joinOrder, JoinType.INNER));
        }
        //Collect all the join/where conditions to reassign them later
        AbstractExpression combinedWhereExpr = subTree.getAllFilters();
        List<JoinNode> treePermutations = new ArrayList<>();
        for (JoinNode newTree : newTrees) {
            if (combinedWhereExpr != null) {
                newTree.setWhereExpression(combinedWhereExpr.clone());
            }
            // The new tree root node id must match the original one to be able to reconnect the
            // subtrees
            newTree.setId(subTree.getId());
            treePermutations.add(newTree);
        }
        return treePermutations;
    }
1127527
def get_leaves(self):
        ""
        leaves = self._get_leaves()
        leaves.sort(key=(lambda x: x._path))  # FF sorts "mixed" last
        return leaves
945577
def get_descendants(self):
        
        if self.is_leaf():
            return get_result_class(self.__class__).objects.none()
        return self.__class__.get_tree(self).exclude(pk=self.pk)
1115588
def leaf_nodes(self):
        
        # Now contains all nodes that contain dependencies.
        deps = {item for sublist in self.edges.values() for item in sublist}
        # contains all nodes *without* any dependencies (leaf nodes)
        return self.nodes - deps
1371744
def num_nodes(tree):
    """"""
    if tree.is_leaf:
        return 1
    else:
        return 1 + num_nodes(tree.left_child) + num_nodes(tree.right_child)
520315
def leaf_to_root(self):
        """"""
        node = self
        subp = []
        while node:
            if node.type == TYPE_ALTERNATIVES:
                node.alternatives.append(subp)
                if len(node.alternatives) == len(node.children):
                    #last alternative
                    subp = [tuple(node.alternatives)]
                    node.alternatives = []
                    node = node.parent
                    continue
                else:
                    node = node.parent
                    subp = None
                    break

            if node.type == TYPE_GROUP:
                node.group.append(subp)
                #probably should check the number of leaves
                if len(node.group) == len(node.children):
                    subp = get_characteristic_subpattern(node.group)
                    node.group = []
                    node = node.parent
                    continue
                else:
                    node = node.parent
                    subp = None
                    break

            if node.type == token_labels.NAME and node.name:
                #in case of type=name, use the name instead
                subp.append(node.name)
            else:
                subp.append(node.type)

            node = node.parent
        return subp
1185551
function(node, level, leaf) {
        var size = this.getSize(node, true), baseHeight = 0, that = this;
        if(leaf(level, node)) return size;
        if(level === 0) return 0;
        node.eachSubnode(function(elem) {
            baseHeight += that.getTreeBaseSize(elem, level -1, leaf);
        });
        return (size > baseHeight? size : baseHeight) + this.config.subtreeOffset;
    }
849568
def parents(self, node):
        """"""
        return [
            parent for parent in
            getattr( node, 'parents', [] )
            if getattr(parent, 'tree', self.TREE) == self.TREE
        ]
627257
def positions(self, reverse=False):
        """"""
        def Posgen(reverse):
            if reverse:
                lastrootsib = self.last_sibling_position(self.root)
                current = self.last_decendant(lastrootsib)
                while current is not None:
                    yield current
                    current = self.prev_position(current)
            else:
                current = self.root
                while current is not None:
                    yield current
                    current = self.next_position(current)
        return Posgen(reverse)
798485
def get_tree(cls, parent=None):
        
        cls = get_result_class(cls)

        if parent is None:
            # return the entire tree
            return cls.objects.all()
        if parent.is_leaf():
            return cls.objects.filter(pk=parent.pk)
        return cls.objects.filter(
            path__startswith=parent.path,
            depth__gte=parent.depth
        ).order_by(
            'path'
        )
1022355
def _format_subtree(self, subtree):
        """"""
        subtree['children'] = list(subtree['children'].values())
        for child in subtree['children']:
            self._format_subtree(child)
        return subtree
294205
def get_tree_depth( self ):
        '''  '''
        if (self.children):
            depth = 1
            childDepths = []
            for child in self.children:
                childDepths.append( child.get_tree_depth() )
            return depth + max(childDepths)
        else:
            return 0
1056542
def get_tree(cls, parent=None):
        
        if parent:
            depth = parent.get_depth() + 1
            results = [parent]
        else:
            depth = 1
            results = []
        cls._get_tree_recursively(results, parent, depth)
        return results
840689
def gather_positions(tree):
    """"""
    pos = {'data-x': 'r0',
           'data-y': 'r0',
           'data-z': 'r0',
           'data-rotate-x': 'r0',
           'data-rotate-y': 'r0',
           'data-rotate-z': 'r0',
           'data-scale': 'r0',
           'is_path': False
           }

    steps = 0
    default_movement = True

    for step in tree.findall('step'):
        steps += 1

        for key in POSITION_ATTRIBS:
            value = step.get(key)

            if value is not None:
                # We have a new value
                default_movement = False  # No longer use the default movement
                pos[key] = value
            elif pos[key] and not pos[key].startswith('r'):
                # The old value was absolute and no new value, so stop
                pos[key] = 'r0'
            # We had no new value, and the old value was a relative
            # movement, so we just keep moving.

        if steps == 1 and pos['data-scale'] == 'r0':
            # No scale given for first slide, it needs to start at 1
            pos['data-scale'] = '1'

        if default_movement and steps != 1:
            # No positioning has been given, use default:
            pos['data-x'] = 'r%s' % DEFAULT_MOVEMENT

        if 'data-rotate' in step.attrib:
            # data-rotate is an alias for data-rotate-z
            pos['data-rotate-z'] = step.get('data-rotate')
            del step.attrib['data-rotate']

        if 'hovercraft-path' in step.attrib:
            # Path given x and y will be calculated from the path
            default_movement = False  # No longer use the default movement
            pos['is_path'] = True
            # Add the path spec
            pos['path'] = step.attrib['hovercraft-path']
            yield pos.copy()
            # And get rid of it for the next step
            del pos['path']
        else:
            if 'data-x' in step.attrib or 'data-y' in step.attrib:
                # No longer using a path
                pos['is_path'] = False
            yield pos.copy()
227887
def get_subtree(self, tree, xpath_str):
        """"""
        return tree.xpath(xpath_str, namespaces=self.namespaces)