This returns you subtree of ordered objects relative
        to the start parent_id (currently only implemented in postgresql)

        :param resource_id:
        :param limit_depth:
        :param db_session:
        :return:
507877
def from_parent_deeper(
        cls, parent_id=None, limit_depth=1000000, db_session=None, *args, **kwargs
    ):
        

        if parent_id:
            limiting_clause = "res.parent_id = :parent_id"
        else:
            limiting_clause = "res.parent_id is null"
        tablename = cls.model.__table__.name
        raw_q = """
            WITH RECURSIVE subtree AS (
                    SELECT res.*, 1 AS depth, LPAD(res.ordering::CHARACTER VARYING, 7, '0') AS sorting,
                    res.resource_id::CHARACTER VARYING AS path
                    FROM {tablename} AS res WHERE {limiting_clause}
                  UNION ALL
                    SELECT res_u.*, depth+1 AS depth,
                    (st.sorting::CHARACTER VARYING || '/' || LPAD(res_u.ordering::CHARACTER VARYING, 7, '0') ) AS sorting,
                    (st.path::CHARACTER VARYING || '/' || res_u.resource_id::CHARACTER VARYING ) AS path
                    FROM {tablename} res_u, subtree st
                    WHERE res_u.parent_id = st.resource_id
            )
            SELECT * FROM subtree WHERE depth<=:depth ORDER BY sorting;
        """.format(
            tablename=tablename, limiting_clause=limiting_clause
        )  # noqa
        db_session = get_db_session(db_session)
        text_obj = sa.text(raw_q)
        query = db_session.query(cls.model, "depth", "sorting", "path")
        query = query.from_statement(text_obj)
        query = query.params(parent_id=parent_id, depth=limit_depth)
        return query
297048
def _resource(self, resource_id):
        
        resource = self.__model__.query.get(resource_id)
        if not resource:
            raise NotFoundException()
        return resource
819148
def traverse_depth_first_post_order(self, callback):
        
        # a. Reimplement without python lists?..
        # b. Interface will require it to have not internal nodes only?..
        #    (but actually this implementation gives a ~2x gain of performance)
        last_interval = None
        n = len(self.suftab)
        stack = [[0, 0, None, []]]  # <l, i, j, children>
        for i in xrange(1, n):
            lb = i - 1
            while self.lcptab[i] < stack[-1][0]:
                stack[-1][2] = i - 1
                last_interval = stack.pop()
                callback(last_interval)
                lb = last_interval[1]
                if self.lcptab[i] <= stack[-1][0]:
                    stack[-1][3].append(last_interval)
                    last_interval = None
            if self.lcptab[i] > stack[-1][0]:
                if last_interval:
                    stack.append([self.lcptab[i], lb, None, [last_interval]])
                    last_interval = None
                else:
                    stack.append([self.lcptab[i], lb, None, []])
        stack[-1][2] = n - 1
        callback(stack[-1])
1118180
def children_resources(parent_id)
      http_get(url('/resources/%s/children', parent_id))['results'].map { |r| Resource.new(r) }
    end
716931
def _retrieve(self, namespace, stream, start_id, end_time, order, limit,
                configuration):
    
    start_id_event = Event(start_id)
    end_id_event = Event(uuid_from_kronos_time(end_time,
                                               _type=UUIDType.HIGHEST))
    stream_events = self.db[namespace][stream]

    # Find the interval our events belong to.
    lo = bisect.bisect_left(stream_events, start_id_event)
    if lo + 1 > len(stream_events):
      return
    if stream_events[lo] == start_id_event:
      lo += 1
    hi = bisect.bisect_right(stream_events, end_id_event)

    if order == ResultOrder.DESCENDING:
      index_it = xrange(hi - 1, lo - 1, -1)
    else:
      index_it = xrange(lo, hi)

    for i in index_it:
      if limit <= 0:
        break
      limit -= 1
      yield marshal.dumps(stream_events[i])
648563
def family_ids(force_reload=false)
      return @family_ids unless @family_ids.nil? or force_reload
      
      transaction do
        reload_boundaries
        query = "SELECT id FROM #{self.class.quote_db_property(base_class.table_name)} " + 
                "WHERE #{nested_set_column(:left)} >= #{left} AND #{nested_set_column(:right)} <= #{right} " +
                "ORDER BY #{nested_set_column(:left)}"
        @family_ids = base_class.connection.select_values(query).map(&:to_i)
      end
    end
1349095
def get_resource_children(raml_resource):
    
    path = raml_resource.path
    return [res for res in raml_resource.root.resources
            if res.parent and res.parent.path == path]
212803
def get_child_ids(self, parent_alias):
        
        self._cache_init()
        return self._cache_get_entry(self.CACHE_NAME_PARENTS, parent_alias, [])
339434
def _get_resource_id(resource, name, region=None, key=None,
                     keyid=None, profile=None):
    '''
    
    '''

    _id = _cache_id(name, sub_resource=resource,
                    region=region, key=key,
                    keyid=keyid, profile=profile)
    if _id:
        return _id

    r = _get_resource(resource, name=name, region=region, key=key,
                      keyid=keyid, profile=profile)

    if r:
        return r.id
740667
def from_resource_deeper(
        self, resource_id=None, limit_depth=1000000, db_session=None, *args, **kwargs
    ):
        
        return self.service.from_resource_deeper(
            resource_id=resource_id,
            limit_depth=limit_depth,
            db_session=db_session,
            *args,
            **kwargs
        )
1004372
def get_parent_id(self, resource, document):
        
        parent_type = self._get_parent_type(resource)
        if parent_type and document:
            return document.get(parent_type.get('field'))

        return None
224805
def query(self, parents=None):
        
        # TODO: benchmark single-query strategy
        q = Select([])
        q = self.project(q, parent=True)
        q = self.filter(q, parents=parents)

        if self.parent is None:
            subq = Select([self.var])
            subq = self.filter(subq, parents=parents)
            subq = subq.offset(self.node.offset)
            subq = subq.limit(self.node.limit)
            subq = subq.distinct()
            # TODO: sorting.
            subq = subq.order_by(desc(self.var))
            q = q.where(subq)

        # if hasattr(self.context, 'identifier'):
        #     q._where = graph(self.context.identifier, q._where)
        log.debug("Compiled query: %r", q.compile())
        return q
974486
def parent(self):
        
        try:
            return Resource(self['parent_type'], uuid=self['parent_uuid'], check=True)
        except KeyError:
            raise ResourceMissing('%s has no parent resource' % self)
429802
def info(self, account_id, resource_id, parent_id):
        
        resource = self.record(account_id, resource_id)
        if resource is None and not parent_id:
            return {'ResourceId': resource_id,
                    'LockStatus': self.STATE_UNLOCKED}
        elif resource is None:
            parent = self.record(account_id, parent_id)
            if parent is None:
                return {'ResourceId': resource_id,
                        'ParentId': parent_id,
                        'LockStatus': self.STATE_UNLOCKED}
            parent['ResourceId'] = resource_id
            parent['ParentId'] = parent_id
            parent['LockType'] = 'parent'
            return parent
        if resource['ResourceId'].startswith('vpc-'):
            return resource
        if resource['ResourceId'].startswith('sg-'):
            return resource
1156306
def query_by_postid(postid, limit=5):
        '''
        
        '''
        recs = TabPostHist.select().where(
            TabPostHist.post_id == postid
        ).order_by(
            TabPostHist.time_update.desc()
        ).limit(limit)
        return recs
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
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)