Wrap given tree in pyquery and return.
            If no tree supplied, will generate one from given page_numbers, or
            all page numbers.
976739
def get_pyquery(self, tree=None, page_numbers=None):
        
        if not page_numbers:
            page_numbers = []
        if tree is None:
            if not page_numbers and self.tree is not None:
                tree = self.tree
            else:
                tree = self.get_tree(page_numbers)
        if hasattr(tree, 'getroot'):
            tree = tree.getroot()
        return PyQuery(tree, css_translator=PDFQueryTranslator())
658503
def generate(self, tree):
        '''
        
        '''
        for middleware in DEFAULT_MIDDLEWARES + self.middlewares:
            tree = middleware.process(tree) # changed in place!!
        original = self._generate_node(tree)
        # first n lines n dependencies
        # after that additional code

        if self.a and tree.type == 'module':
            p = original.split('\n')
            r = '\n'.join(p[:len(tree.dependencies)] + (['\n'] if tree.dependencies else []) + self.a + ['\n'] + p[len(tree.dependencies):]) + '\n'
        else:
            r = original
        r = re.sub(CLOSING_CURLY_ENDLINES, r'}\n\2}', r)
        r = re.sub(JS_BRACKET, r'}\1', r)
        return re.sub(TOO_MANY_ENDLINES, r'\n\n', r)
567198
def build_query_fragment(query):
    
    root = etree.Element('query', nsmap={None: 'http://basex.org/rest'})
    text = etree.SubElement(root, 'text')
    text.text = etree.CDATA(query.strip())
    return root
1138886
def etree(self, data, root=None):
        ''''''
        result = self.list() if root is None else root
        if isinstance(data, (self.dict, dict)):
            for key, value in data.items():
                if isinstance(value, (self.dict, dict)):
                    elem = self.element(key)
                    if elem is None:
                        continue
                    result.append(elem)

                    if 'attributes' in value:
                        for k, v in value['attributes'].items():
                            elem.set(k, self._tostring(v))
                    # else:
                    #     raise ValueError('Cobra requires "attributes" key for each element')

                    if 'children' in value:
                        for v in value['children']:
                            self.etree(v, root=elem)
                else:
                    elem = self.element(key)
                    if elem is None:
                        continue
                    elem.text = self._tostring(value)
                    result.append(elem)
        else:
            if root is not None:
                root.text = self._tostring(data)
            else:
                elem = self.element(self._tostring(data))
                if elem is not None:
                    result.append(elem)

        return result
60547
def pq(self) -> PyQuery:
        
        if self._pq is None:
            self._pq = PyQuery(self.lxml)

        return self._pq
610317
def fetch_tree(client, path, expand_keys):
    '''
    
    '''
    _, items = consul_fetch(client, path)
    ret = {}
    has_children = re.compile(r'/$')

    log.debug('Fetched items: %r', items)

    if items is None:
        return ret
    for item in reversed(items):
        key = re.sub(r'^' + re.escape(path) + '/?', '', item['Key'])
        if key != '':
            log.debug('path/key - %s: %s', path, key)
            log.debug('has_children? %r', has_children.search(key))
        if has_children.search(key) is None:
            ret = pillar_format(ret, key.split('/'), item['Value'], expand_keys)
            log.debug('Fetching subkeys for key: %r', item)

    return ret
1284810
def as_tree(self):
        ""
        if self._nodes is None:
            return [self]
        ret = [self]
        for node in self._nodes:
            ret.append(node.as_tree())
        return ret
1001433
def parse_query(self, query):
        """"""
        tree = pypeg2.parse(query, Main, whitespace="")
        return tree.accept(self.converter)
1309420
def select(*queries, **kwargs):
    
    def make_query(*args):
        def simple_query(nodes):
            if len(args) == 0:
                return nodes
            pred = args[0]
            results = []
            if isinstance(pred, list):
                funcs = [make_query(q) for q in pred]
                return __or(funcs, nodes)
            elif isinstance(pred, tuple):
                name, attrs = pred[0], pred[1:]
                name_pred = __make_name_pred(name)
                attrs_pred = __make_attrs_pred(attrs)
                for n in nodes:
                    if name_pred(n.name) and attrs_pred(n.attrs):
                        results.append(n)
            else:
                name_pred = __make_name_pred(pred)
                for n in nodes:
                    if name_pred(n.name):
                        results.append(n)
            return results
        if len(args) > 1:
            return __compose(make_query(*args[1:]), simple_query)
        return simple_query

    def deep_query(query, nodes):
        """ Slide the query down the branches. """
        def inner(children):
            results = []
            for c in children:
                if query([c]):
                    results.append(c)
                results.extend(inner(c.children))
            return results
        return inner(nodes)

    def unique(roots):
        seen = set()
        results = []
        for r in roots:
            if r not in seen:
                seen.add(r)
                results.append(r)
        return results

    def compiled_query(nodes):
        """
        This is the compiled query that can be run against a configuration.
        """
        query = make_query(*queries)

        roots = kwargs.get("roots", True)
        if kwargs.get("deep", False):
            results = deep_query(query, nodes)
            if roots:
                results = unique([r.root for r in results])
        elif roots:
            results = unique([n.root for n in query(nodes)])
        else:
            results = query(nodes)

        one = kwargs.get("one")
        if one is None:
            return SearchResult(children=results)
        return results[one] if results else None
    return compiled_query
1227034
function pageToJqtree(page) {
        var info = {
          label: page.title,
          slug: page.slug,
          id: page._id,
          // For icons
          type: page.type,
          // Also nice for icons and browser-side decisions about what's draggable where
          trash: page.trash,
          published: page.published,
          publish: (page.path === '/trash') || self.apos.permissions.can(req, 'publish-apostrophe-page', page),
          edit: self.apos.permissions.can(req, 'edit-apostrophe-page', page)
        };
        if (page._children && page._children.length) {
          info.children = [];
          // First non-trash, then .trash true,
          // then the conventional trashcan itself
          // to avoid presenting a confusing UI
          _.each(page._children, function(child) {
            if (!child.trash) {
              info.children.push(pageToJqtree(child));
            }
          });
          _.each(page._children, function(child) {
            if (child.trash && (!(child.type === 'trash'))) {
              info.children.push(pageToJqtree(child));
            }
          });
          _.each(page._children, function(child) {
            if (child.trash && (child.type === 'trash')) {
              var forJqtree = pageToJqtree(child);
              if (self.apos.docs.trashInSchema) {
                forJqtree.label = self.apos.i18n.__('Legacy Trash');
              }
              info.children.push(forJqtree);
            }
          });
        }
        return info;
      }
114173
def strip_tree(node,
               # Runtime optimization
               iter_node=iter_node, special=ast.AST,
               list=list, isinstance=isinstance, type=type, len=len):
    
    stripped = set()

    def strip(node, indent):
        unknown = set()
        leaf = True
        for subnode, _ in iter_node(node, unknown=unknown):
            leaf = False
            strip(subnode, indent + '    ')
        if leaf:
            if isinstance(node, special):
                unknown = set(vars(node))
        stripped.update(unknown)
        for name in unknown:
            delattr(node, name)
        if hasattr(node, 'ctx'):
            delattr(node, 'ctx')
            if 'ctx' in node._fields:
                mylist = list(node._fields)
                mylist.remove('ctx')
                node._fields = mylist
    strip(node, '')
    return stripped
20623
def convert(gr, raw_node):
    
    type, value, context, children = raw_node
    if children or type in gr.number2symbol:
        # If there's exactly one child, return that child instead of
        # creating a new node.
        if len(children) == 1:
            return children[0]
        return Node(type, children, context=context)
    else:
        return Leaf(type, value, context=context)
1278514
def get_children_for_page(self, page):
        """"""
        if self.max_levels == 1:
            # If there's only a single level of pages to display, skip the
            # dict creation / lookup and just return the QuerySet result
            return self.pages_for_display
        return super().get_children_for_page(page)
1276158
def _buildElementTree(self,):
        
        t_binder = ctree.Element(self.name)

        for k,v in self.__dict__.items():
            if k not in ('name', 'urls', 'inputs', 'paging') and v :
                t_binder.set(k,v)

        self.etree = t_binder
        return t_binder
906856
def wrap(self, value):
        
        return self._parent.new_query().get_query().get_grammar().wrap(value)
781615
def wrap_node(self, node, options):
        '''
        
        '''
        job_kwargs = {
            'queue': options.get('queue', 'default'),
            'connection': options.get('connection', self.redis_connection),
            'timeout': options.get('timeout', None),
            'result_ttl': options.get('result_ttl', 500),
        }

        return job(**job_kwargs)(node)
186991
def handle_page_crumb(func):
    
    @wraps(func)
    def wrapper(path, model, page, root_name):
        path = PAGE_REGEXP.sub('', path)
        breadcrumbs = func(path, model, root_name)
        if page:
            if page.number > 1:
                breadcrumbs[-1].url = path
                page_crumb = Crumb(_('Page %s') % page.number)
                breadcrumbs.append(page_crumb)
        return breadcrumbs
    return wrapper